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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
a73b597c5862106b4c9cfe987107b86cbdea6abc | C++ | diantaowang/cocoding | /937_k_closest.cc | UTF-8 | 940 | 2.703125 | 3 | [] | no_license | #include <vector>
#include <algorithm>
#include <string>
#include <map>
#include <set>
#include <iostream>
#include <tuple>
#include <queue>
#include <stack>
#include <queue>
using namespace::std;
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
priority_queue<pair<int, int>> que;
for (int i = 0; i < K; ++i)
que.emplace(points[i][0] * points[i][0] + points[i][1] * points[i][1], i);
for (int i = K; i < points.size(); ++i) {
int val = points[i][0] * points[i][0] + points[i][1] * points[i][1];
if (val < que.top().first) {
que.pop();
que.emplace(val, i);
}
}
vector<vector<int>> result;
while (!que.empty()) {
result.push_back(points[que.top().second]);
que.pop();
}
return result;
}
};
int main()
{
return 0;
}
| true |
e337f6bf2c57c41ac78eef3adce9e4c087f9f1d5 | C++ | StartAt24/Cpp_stuff | /design_patterns/command_pattern.cpp | UTF-8 | 823 | 3.140625 | 3 | [] | no_license | #include <iostream>
using namespace std;
class Receiver{
public:
void act(){
cout << "receiver act" << endl;
}
};
class Command{
public:
Command(){
}
virtual ~Command(){
}
virtual void excute() = 0;
private:
Receiver* recv_;
};
class Invoker{
public:
Invoker(Command* cmd){
cmd_ = cmd;
}
virtual ~Invoker(){}
void call(){
cmd_->excute();
}
private:
Command* cmd_;
};
class ConcreteCommand :public Command{
public:
ConcreteCommand(Receiver* recv):receiver_(recv){
}
void excute() override{
receiver_->act();
}
private:
Receiver* receiver_;
};
int main(){
Receiver* recv = new Receiver();
Command * cmd = new ConcreteCommand(recv);
Invoker* inv = new Invoker(cmd);
inv->call();
return 0;
} | true |
85575f589757f82642114d153bcbc8a74998088c | C++ | D34Dspy/warz-client | /External/NaturalMotion/common/XMD/src/XMD/ItPolygon.cpp | UTF-8 | 24,731 | 2.53125 | 3 | [] | no_license | //----------------------------------------------------------------------------------------------------------------------
/// \file ItPolygon.cpp
/// \note (C) Copyright 2003-2005 Robert Bateman. All rights reserved.
//----------------------------------------------------------------------------------------------------------------------
#include "XMD/Model.h"
#include "XMD/PolygonMesh.h"
#include "XMD/ItPolygon.h"
#include "XMD/FileIO.h"
#include "XM2/Plane.h"
namespace XMD
{
//----------------------------------------------------------------------------------------------------------------------
XItPolygon::XItPolygon(XPolygonMesh* poly_mesh)
: m_Mesh(poly_mesh)
{
Reset();
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::IsValid() const
{
return m_Mesh != 0;
}
//----------------------------------------------------------------------------------------------------------------------
void XItPolygon::Next()
{
if(!IsValid())
return;
if(m_CurrentFaceIndex<m_Mesh->m_PolyCounts.size())
{
// increment current vertex index by number of vertices
// in the previous face.
m_CurrentVertexIndex += m_NumVertices;
// increment current face index
++m_CurrentFaceIndex;
// now set the num of vertices in this face
if(m_CurrentFaceIndex<m_Mesh->m_PolyCounts.size())
m_NumVertices = m_Mesh->m_PolyCounts[m_CurrentFaceIndex];
else
m_NumVertices = 0;
}
}
//----------------------------------------------------------------------------------------------------------------------
void XItPolygon::Previous()
{
if(!IsValid())
return;
if(m_CurrentFaceIndex>0)
{
// decrement current face index
--m_CurrentFaceIndex;
// get num of vertices in this face
m_NumVertices = m_Mesh->m_PolyCounts[m_CurrentFaceIndex];
// decrement current vertex index by number of vertices
// in the previous face.
m_CurrentVertexIndex -= m_NumVertices;
}
}
//----------------------------------------------------------------------------------------------------------------------
void XItPolygon::Reset()
{
if(!IsValid())
return;
m_CurrentVertexIndex=0;
m_CurrentFaceIndex=0;
m_NumVertices = m_Mesh->m_PolyCounts.size() ? m_Mesh->m_PolyCounts[m_CurrentFaceIndex] : 0;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::IsDone() const
{
if(IsValid())
{
return m_CurrentFaceIndex == m_Mesh->m_PolyCounts.size();
}
return true;
}
//----------------------------------------------------------------------------------------------------------------------
XU32 XItPolygon::GetFaceIndex() const
{
return m_CurrentFaceIndex;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::SetToFace(const XU32 face_index)
{
if(IsValid())
{
// make sure face index is valid.
if(face_index<m_Mesh->m_PolyCounts.size())
{
// if the requested face is further on that the current
// face, the quickest way is to iterate there from the
// current position
if(face_index>GetFaceIndex())
{
XU32 temp = face_index-GetFaceIndex();
for (XU32 i=0;i!=temp;++i)
Next();
}
else
{
// in this case the requested index is before the current
// face.
XU32 temp = GetFaceIndex() - face_index;
// if it will take less work to move backwards from the current
// position to the requested face, then do that...
if(temp<face_index)
{
for (XU32 i=0;i!=temp;++i)
Previous();
}
else
{
// else reset to the beginning and iterate forwards...
Reset();
for(XU32 i=0;i!=face_index;++i)
Next();
}
}
return true;
}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------
XReal XItPolygon::GetArea() const
{
XReal area = 0.0f;
if(IsValid())
{
// for all triangles in the face
for (XU32 i=2;i<GetNumPoints();++i)
{
XU32 index0 = 0;
XU32 index1 = i-1;
XU32 index2 = i;
XVector3 v0,v1,v2;
GetVertex(v0,index0);
GetVertex(v1,index1);
GetVertex(v2,index2);
// get 2 edges
XVector3 e1,e2,n;
e1.sub(v1,v0);
e2.sub(v1,v2);
n.cross(e1,e2);
// sum area from the 2 tris
area += n.length()*0.5f;
}
}
return area;
}
//----------------------------------------------------------------------------------------------------------------------
XU32 XItPolygon::GetNumPoints() const
{
return m_NumVertices;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::IsPlanar(const XReal tolerance) const
{
// triangles are always planar
if(GetNumPoints()==3 || !IsValid())
return true;
XVector3 p0,p1,p2;
GetVertex(p0,0);
GetVertex(p1,1);
GetVertex(p2,2);
// construct a test plane using the first 3 verts.
XPlane test_plane;
// now do a distance test between the remaining points and that plane
for(XU32 i=3;i<GetNumPoints();++i)
{
XVector3 p;
if(!GetVertex(p,i))
return false;
if(test_plane.distance(p)>tolerance)
return false;
}
return true;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetVertex(XVector3& point,const XU32 face_vertex_index) const
{
if(IsValid() && face_vertex_index<GetNumPoints())
{
XU32 index = GetVertexIndex(face_vertex_index);
if (index<m_Mesh->GetNumPoints())
{
point = m_Mesh->Points()[index];
return true;
}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetNormal(XVector3& normal,const XU32 face_vertex_index) const
{
const XVertexSet* vset = IsValid() ? m_Mesh->GetVertexSet(XVertexSet::kNormal) : 0;
return GetVertexData(face_vertex_index,*vset,normal);
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetTangent(XVector3& tangent,const XU32 face_vertex_index) const
{
const XVertexSet* vset = IsValid() ? m_Mesh->GetVertexSet(XVertexSet::kTangent) : 0;
return GetVertexData(face_vertex_index,*vset,tangent);
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetBiNormal(XVector3& binormal,const XU32 face_vertex_index) const
{
const XVertexSet* vset = IsValid() ? m_Mesh->GetVertexSet(XVertexSet::kBiNormal) : 0;
return GetVertexData(face_vertex_index,*vset,binormal);
}
//----------------------------------------------------------------------------------------------------------------------
/* bool XItPolygon::GetColour(XColour3& colour,const XU32 face_vertex_index) const
{
return GetColour(colour,face_vertex_index,0);
}*/
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetColour(XColour& colour,const XU32 face_vertex_index) const
{
return GetColour(colour,face_vertex_index,0);
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetUvCoord(XReal& uv,const XU32 face_vertex_index) const
{
return GetUvCoord(uv,face_vertex_index,0);
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetUvCoord(XVector2& uv,const XU32 face_vertex_index) const
{
return GetUvCoord(uv,face_vertex_index,0);
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetUvCoord(XVector3& uv,const XU32 face_vertex_index) const
{
return GetUvCoord(uv,face_vertex_index,0);
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetUvCoord(XVector4& uv,const XU32 face_vertex_index) const
{
return GetUvCoord(uv,face_vertex_index,0);
}
//----------------------------------------------------------------------------------------------------------------------
/* bool XItPolygon::GetColour(XColour3& colour,const XU32 face_vertex_index,const XU32 colour_set_index) const
{
const XVertexSet* vset = IsValid() ? m_Mesh->GetColourSet(colour_set_index) : 0;
return (vset!=0) ? GetVertexData(face_vertex_index,*vset,colour) : false;
}*/
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetColour(XColour& colour,const XU32 face_vertex_index,const XU32 colour_set_index) const
{
const XVertexSet* vset = IsValid() ? m_Mesh->GetColourSet(colour_set_index) : 0;
return (vset!=0) ? GetVertexData(face_vertex_index,*vset,colour) : false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetUvCoord(XReal& uv,const XU32 face_vertex_index,const XU32 uv_set_index) const
{
const XVertexSet* vset = IsValid() ? m_Mesh->GetUvSet(uv_set_index) : 0;
return (vset!=0) ? GetVertexData(face_vertex_index,*vset,uv) : false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetUvCoord(XVector2& uv,const XU32 face_vertex_index,const XU32 uv_set_index) const
{
const XVertexSet* vset = IsValid() ? m_Mesh->GetUvSet(uv_set_index) : 0;
return (vset!=0) ? GetVertexData(face_vertex_index,*vset,uv) : false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetUvCoord(XVector3& uv,const XU32 face_vertex_index,const XU32 uv_set_index) const
{
const XVertexSet* vset = IsValid() ? m_Mesh->GetUvSet(uv_set_index) : 0;
return (vset!=0) ? GetVertexData(face_vertex_index,*vset,uv) : false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetUvCoord(XVector4& uv,const XU32 face_vertex_index,const XU32 uv_set_index) const
{
const XVertexSet* vset = IsValid() ? m_Mesh->GetUvSet(uv_set_index) : 0;
return (vset!=0) ? GetVertexData(face_vertex_index,*vset,uv) : false;
}
//----------------------------------------------------------------------------------------------------------------------
/*
bool XItPolygon::GetColour(XColour3& colour,const XU32 face_vertex_index,const XString& colour_set_name) const
{
const XVertexSet* vset = IsValid() ? m_Mesh->GetColourSet(colour_set_name) : 0;
return (vset!=0) ? GetVertexData(face_vertex_index,*vset,colour) : false;
}*/
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetColour(XColour& colour,const XU32 face_vertex_index,const XString& colour_set_name) const
{
const XVertexSet* vset = IsValid() ? m_Mesh->GetColourSet(colour_set_name) : 0;
return (vset!=0) ? GetVertexData(face_vertex_index,*vset,colour) : false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetUvCoord(XReal& uv,const XU32 face_vertex_index,const XString& uv_set_name) const
{
const XVertexSet* vset = IsValid() ? m_Mesh->GetUvSet(uv_set_name) : 0;
return (vset!=0) ? GetVertexData(face_vertex_index,*vset,uv) : false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetUvCoord(XVector2& uv,const XU32 face_vertex_index,const XString& uv_set_name) const
{
const XVertexSet* vset = IsValid() ? m_Mesh->GetUvSet(uv_set_name) : 0;
return (vset!=0) ? GetVertexData(face_vertex_index,*vset,uv) : false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetUvCoord(XVector3& uv,const XU32 face_vertex_index,const XString& uv_set_name) const
{
const XVertexSet* vset = IsValid() ? m_Mesh->GetUvSet(uv_set_name) : 0;
return (vset!=0) ? GetVertexData(face_vertex_index,*vset,uv) : false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetUvCoord(XVector4& uv,const XU32 face_vertex_index,const XString& uv_set_name) const
{
const XVertexSet* vset = (m_Mesh!=0) ? m_Mesh->GetUvSet(uv_set_name) : 0;
return (vset!=0) ? GetVertexData(face_vertex_index,*vset,uv) : false;
}
//----------------------------------------------------------------------------------------------------------------------
XS32 XItPolygon::GetVertexIndex(const XU32 face_vertex_index) const
{
XIndexSet* vset = IsValid() ? m_Mesh->m_PointSet : 0;
return vset ? GetIndex(face_vertex_index,vset) : face_vertex_index + m_CurrentVertexIndex;
}
//----------------------------------------------------------------------------------------------------------------------
XS32 XItPolygon::GetNormalIndex(const XU32 face_vertex_index) const
{
XVertexSet* vset = IsValid() ? m_Mesh->GetVertexSet(XVertexSet::kNormal) : 0;
return vset ? GetIndex(face_vertex_index,vset) : 0;
}
//----------------------------------------------------------------------------------------------------------------------
XS32 XItPolygon::GetBiNormalIndex(const XU32 face_vertex_index) const
{
XVertexSet* vset = IsValid() ? m_Mesh->GetVertexSet(XVertexSet::kBiNormal) : 0;
return vset ? GetIndex(face_vertex_index,vset) : 0;
}
//----------------------------------------------------------------------------------------------------------------------
XS32 XItPolygon::GetTangentIndex(const XU32 face_vertex_index) const
{
XVertexSet* vset = IsValid() ? m_Mesh->GetVertexSet(XVertexSet::kTangent) : 0;
return vset ? GetIndex(face_vertex_index,vset) : 0;
}
//----------------------------------------------------------------------------------------------------------------------
XS32 XItPolygon::GetColourIndex(const XU32 face_vertex_index) const
{
XVertexSet* vset = IsValid() ? m_Mesh->GetColourSet(0) : 0;
return vset ? GetIndex(face_vertex_index,vset) : 0;
}
//----------------------------------------------------------------------------------------------------------------------
XS32 XItPolygon::GetColourIndex(const XU32 face_vertex_index,const XU32 colour_set_index) const
{
XVertexSet* vset = IsValid() ? m_Mesh->GetColourSet(colour_set_index) : 0;
return vset ? GetIndex(face_vertex_index,vset) : 0;
}
//----------------------------------------------------------------------------------------------------------------------
XS32 XItPolygon::GetColourIndex(const XU32 face_vertex_index,const XString& colour_set_name) const
{
XVertexSet* vset = IsValid() ? m_Mesh->GetColourSet(colour_set_name) : 0;
return vset ? GetIndex(face_vertex_index,vset) : 0;
}
//----------------------------------------------------------------------------------------------------------------------
XS32 XItPolygon::GetUvCoordIndex(const XU32 face_vertex_index) const
{
XVertexSet* vset = IsValid() ? m_Mesh->GetUvSet(0) : 0;
return vset ? GetIndex(face_vertex_index,vset) : 0;
}
//----------------------------------------------------------------------------------------------------------------------
XS32 XItPolygon::GetUvCoordIndex(const XU32 face_vertex_index,const XU32 uv_set_index) const
{
XVertexSet* vset = IsValid() ? m_Mesh->GetUvSet(uv_set_index) : 0;
return vset ? GetIndex(face_vertex_index,vset) : 0;
}
//----------------------------------------------------------------------------------------------------------------------
XS32 XItPolygon::GetUvCoordIndex(const XU32 face_vertex_index,const XString& uv_set_name) const
{
XVertexSet* vset = IsValid() ? m_Mesh->GetUvSet(uv_set_name) : 0;
return vset ? GetIndex(face_vertex_index,vset) : 0;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetVertexData(const XU32 face_vertex_index,const XU32 vertex_set_index,XReal& data) const
{
if(IsValid())
{
const XVertexSet* vertex_set = m_Mesh->GetVertexSet(vertex_set_index);
if (vertex_set)
{
return GetVertexData(face_vertex_index,*vertex_set,data);
}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetVertexData(const XU32 face_vertex_index,const XU32 vertex_set_index,XVector2& data) const
{
if(IsValid())
{
const XVertexSet* vertex_set = m_Mesh->GetVertexSet(vertex_set_index);
if (vertex_set)
{
return GetVertexData(face_vertex_index,*vertex_set,data);
}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetVertexData(const XU32 face_vertex_index,const XU32 vertex_set_index,XVector3& data) const
{
if(IsValid())
{
const XVertexSet* vertex_set = m_Mesh->GetVertexSet(vertex_set_index);
if (vertex_set)
{
return GetVertexData(face_vertex_index,*vertex_set,data);
}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetVertexData(const XU32 face_vertex_index,const XU32 vertex_set_index,XVector4& data) const
{
if(IsValid())
{
const XVertexSet* vertex_set = m_Mesh->GetVertexSet(vertex_set_index);
if (vertex_set)
{
return GetVertexData(face_vertex_index,*vertex_set,data);
}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetVertexData(const XU32 face_vertex_index,const XU32 vertex_set_index,XColour& data) const
{
if(IsValid())
{
const XVertexSet* vertex_set = m_Mesh->GetVertexSet(vertex_set_index);
if (vertex_set)
{
return GetVertexData(face_vertex_index,*vertex_set,data);
}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetVertexData(const XU32 face_vertex_index,const XString& vertex_set_name,XReal& data) const
{
if(IsValid())
{
const XVertexSet* vertex_set = m_Mesh->GetVertexSet(vertex_set_name);
if (vertex_set)
{
return GetVertexData(face_vertex_index,*vertex_set,data);
}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetVertexData(const XU32 face_vertex_index,const XString& vertex_set_name,XVector2& data) const
{
if(IsValid())
{
const XVertexSet* vertex_set = m_Mesh->GetVertexSet(vertex_set_name);
if (vertex_set)
{
return GetVertexData(face_vertex_index,*vertex_set,data);
}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetVertexData(const XU32 face_vertex_index,const XString& vertex_set_name,XVector3& data) const
{
if(IsValid())
{
const XVertexSet* vertex_set = m_Mesh->GetVertexSet(vertex_set_name);
if (vertex_set)
{
return GetVertexData(face_vertex_index,*vertex_set,data);
}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetVertexData(const XU32 face_vertex_index,const XString& vertex_set_name,XVector4& data) const
{
if(IsValid())
{
const XVertexSet* vertex_set = m_Mesh->GetVertexSet(vertex_set_name);
if (vertex_set)
{
return GetVertexData(face_vertex_index,*vertex_set,data);
}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetVertexData(const XU32 face_vertex_index,const XString& vertex_set_name,XColour& data) const
{
if(IsValid())
{
const XVertexSet* vertex_set = m_Mesh->GetVertexSet(vertex_set_name);
if (vertex_set)
{
return GetVertexData(face_vertex_index,*vertex_set,data);
}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetVertexData(const XU32 face_vertex_index,const XVertexSet& vertex_set,XReal& data) const
{
if (IsValid() && face_vertex_index<GetNumPoints())
{
const XIndexSet* indices = vertex_set.GetIndexSet();
if (indices)
{
return vertex_set.GetElement( data, (*indices)[ face_vertex_index + m_CurrentVertexIndex ] );
}
else
{
return vertex_set.GetElement( data, face_vertex_index+m_CurrentVertexIndex );
}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetVertexData(const XU32 face_vertex_index,const XVertexSet& vertex_set,XVector2& data) const
{
if (IsValid() && face_vertex_index<GetNumPoints())
{
const XIndexSet* indices = vertex_set.GetIndexSet();
if (indices)
{
return vertex_set.GetElement( data, (*indices)[ face_vertex_index + m_CurrentVertexIndex ] );
}
else
{
return vertex_set.GetElement( data, face_vertex_index+m_CurrentVertexIndex );
}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetVertexData(const XU32 face_vertex_index,const XVertexSet& vertex_set,XVector3& data) const
{
if (IsValid() && face_vertex_index<GetNumPoints())
{
const XIndexSet* indices = vertex_set.GetIndexSet();
if (indices)
{
return vertex_set.GetElement( data, (*indices)[ face_vertex_index + m_CurrentVertexIndex ] );
}
else
{
return vertex_set.GetElement( data, face_vertex_index+m_CurrentVertexIndex );
}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetVertexData(const XU32 face_vertex_index,const XVertexSet& vertex_set,XVector4& data) const
{
if (IsValid() && face_vertex_index<GetNumPoints())
{
const XIndexSet* indices = vertex_set.GetIndexSet();
if (indices)
{
return vertex_set.GetElement( data, (*indices)[ face_vertex_index + m_CurrentVertexIndex ] );
}
else
{
return vertex_set.GetElement( data, face_vertex_index+m_CurrentVertexIndex );
}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------
bool XItPolygon::GetVertexData(const XU32 face_vertex_index,const XVertexSet& vertex_set,XColour& data) const
{
if (IsValid() && face_vertex_index<GetNumPoints())
{
const XIndexSet* indices = vertex_set.GetIndexSet();
if (indices)
{
return vertex_set.GetElement( data, (*indices)[ face_vertex_index + m_CurrentVertexIndex ] );
}
else
{
return vertex_set.GetElement( data, face_vertex_index+m_CurrentVertexIndex );
}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------
XS32 XItPolygon::GetIndex(const XU32 face_vertex_index,const XIndexSet* index_set) const
{
if (index_set && IsValid())
{
return (*index_set)[ face_vertex_index + m_CurrentVertexIndex ];
}
return 0;
}
//----------------------------------------------------------------------------------------------------------------------
XS32 XItPolygon::GetIndex(const XU32 face_vertex_index,const XVertexSet* vertex_set) const
{
if (vertex_set && IsValid())
{
const XIndexSet* iset = vertex_set->GetIndexSet();
return (iset!=0) ? GetIndex(face_vertex_index,iset) : face_vertex_index + m_CurrentVertexIndex;
}
return 0;
}
}
| true |
adc8026ea8f2281442c01090201762261675ad79 | C++ | BrittanyBlairDesign/Programming-2- | /Project3/BunnyTask.cpp | UTF-8 | 4,670 | 3.15625 | 3 | [] | no_license | /*
BunnyTask defines all Methods and functions involved in progressing the bunny farm forward.
BrittanyBlair
*/
#include <iostream>
#include <string>
#include <stdlib.h>
#include "Bunnies.h"
#include "BunnyTask.h"
//Population counting maximum bunnies, adult males adult females, and mutations.
int g_count = 0, g_maxBun = 1000, g_males = 0, g_females = 0, g_MutantRabbits = 0;
//Map size and characters
int height = 80, with = 80;
//Set up the game with the first Bunnies
void BunnyFunctions::Setup(vector<Bunny>& newBunnyList)
{
int start = 5;
// creat the 5 starter bunnnies using default constructor.
for (int i = 0; i < start; ++i) {
//create new bunny
Bunny newBunny;
++g_count;
//determine if the random new bunny is an adult male or female.
int newage = newBunny.getAge();
if (newage > 2)
{
if (newBunny.getGender() && !newBunny.getMutant())
{
++g_females;
}
else if (!newBunny.getGender() && !newBunny.getMutant())
{
++g_males;
}
}
//if bunny is radioactive mutant add them to the mutant count.
if (newBunny.getMutant())
{
++g_MutantRabbits;
}
//Add them to the vector.
newBunnyList.push_back(newBunny);
}
}
//Spawn new born bunnies
void BunnyFunctions::SpawnBunnies(vector<Bunny>& newBunnyList)
{
unsigned int size = newBunnyList.size();
if (g_males >= 1 && g_count < g_maxBun)
{
// if there is at least one male rabbit , reproduce with adult female rabbits.
for (unsigned int i = 0; i < size; ++i)
{
if (newBunnyList[i].getGender() && !newBunnyList[i].getMutant())
{
if (newBunnyList[i].getAge() >= 2)
{
//Mothers color and non mutant status is given to the new bunny.
bool M = newBunnyList[i].getMutant();
string C = newBunnyList[i].getcolor();
Bunny newBunny(C, M);
//if bunny is radioactive mutant add them to the mutant count.
if (newBunny.getMutant())
{
++g_MutantRabbits;
}
//add new bunny to population count.
++g_count;
}
}
}
}
}
//For moving bunnies, Aging bunnies, and announcing thier passing.
void BunnyFunctions::BunnyAi(vector<Bunny>& newBunnyList)
{
unsigned int size = newBunnyList.size();
for (unsigned int i = 0; i < size;)
{
//increase every bunnies age.
int newAge;
newAge = newBunnyList[i].ageUP();
//if a regular bunny is 10 and older, or if a mutant bunny is 50 or older they die.
if (newAge >= 10 && !newBunnyList[i].getMutant() || newAge > 50 && newBunnyList[i].getMutant())
{
//announce the loss of the bunny.
if (newBunnyList[i].getMutant())
{
cout << "Radioactive Mutant Vampire Bunny " << newBunnyList[i].getname() << " Has died of old age.\n";
}
else
{
cout << "Bunny " << newBunnyList[i].getname() << " Has died of old age.\n";
}
//remove the bunny from the counters
if (newBunnyList[i].getGender() && !newBunnyList[i].getMutant())
{
--g_females;
}
else if (!newBunnyList[i].getGender() && !newBunnyList[i].getMutant())
{
--g_males;
}
else
{
--g_MutantRabbits;
}
--g_count;
//Erase Bunny
newBunnyList.erase(newBunnyList.begin() + i);
size = newBunnyList.size();
}
else
{
++i;
}
//TODO::
// this section is all about moving the bunny for the map.
//int xPos, yPos, rN;
//xPos = newBunnyList[i].getX();
//yPos = newBunnyList[i].getY();
//
//// replace bunny char with '.' here
//rN = rand() % 4 + 1;
//
//if (rN == 1) {
// if (xPos + 1 <= 80) { xPos++; }
//}
//else if (rN == 2) {
// if (xPos - 1 >= 0) { xPos--; }
//}
//else if (rN == 3) {
// if (yPos + 1 <= 80) { yPos++; }
//}
//else if (rN == 4) {
// if (yPos - 1 >= 0) { yPos--; }
//}
//
//Here Check to make sure that if the bunny moves it wont be ontop
//of another bunny or off the map. if it is either of those things
//The bunny will stay still.
}
}
void BunnyFunctions::MutateBunnies(vector<Bunny>& newBunnyList)
{
unsigned int size = newBunnyList.size();
for (unsigned int i = 0; i < size; )
{
if (newBunnyList[i].getMutant())
{
int randBunny = rand() % size;
if (!newBunnyList[randBunny].getMutant())
{
newBunnyList[randBunny].Mutation();
std::cout << newBunnyList[i].getname() << " Has turned " << newBunnyList[randBunny].getname() << "Into a Mutant!\n";
if (newBunnyList[randBunny].getGender())
{
--g_females;
}
else
{
--g_males;
}
++i;
}
}
else
++i;
}
}
| true |
2c794c610a871f8cc3a289103ecd0e1567eee271 | C++ | FALCH2000/Project_1 | /Interface/constructor.cpp | UTF-8 | 3,125 | 2.890625 | 3 | [] | no_license | #include "constructor.h"
Constructor::Constructor(string path, string object) {
this->path_= path;
this->object_=object;
}
vector<Song *> *Constructor::getSongsList() {
return &this->SongsList;
}
void Constructor::ParseCSV(int start, int end) {
if(this->object_=="Songs"){
Parse_Songs(start,end);
} else if(this->object_=="Artists"){
Parse_Artists();
}
}
void Constructor::Parse_Songs(int start, int end) {
//--------------- Get All Songs Available ---------------
if(this->filesInFolder.empty()){
ParseSongs_OnFolder();
}
string line, separator=",", token;
vector<string> filesList, stringFileList;
fstream file;
file.open(this->path_);
size_t pos = 0;
getline(file, line);
for(int i=start; i<=end; i++){
token = line.substr(0, line.find(separator));
if(!isPart(token, i)){
//While inside
while(!isPart(token, i)) {
getline(file, line);
token = line.substr(0, line.find(separator));
}
}
/// -------------------------Song *newSong= new Song; -------------- I'm Here
int j=0;
Song* mySong= new Song;
while ((pos = line.find(separator)) != std::string::npos) {
token = line.substr(0, line.find(separator));
if(j==0){
mySong->setId(token);
}else if(j==1){
mySong->setArtist(token);
}else{
cout << token<<endl;
mySong->setLength(token);
}
line.erase(0, pos + separator.length());
j++;
}
mySong->setName(line);
SongsList.push_back(mySong);
getline(file, line);
}
}
bool Constructor::isPart(string token, int position){
string pos= this->filesInFolder[position];
stringstream temp_1(token);
stringstream temp_2(pos);
int x, y;
temp_1>>x;
temp_2>>y;
if(x==y){
return true;
}else{
return false;
}
}
void Constructor::ParseSongs_OnFolder(){
string line, temp="/",token;
vector<string> filesList;
fstream file;
file.open("/home/fatima/Documents/fma_small/checksums");
size_t pos = 0;
/** Se parsea el csv haciendo split hasta que se obtiene solo el id de las canciones que hay disponibles*/
while(getline(file, line)){
while ((pos = line.find(temp)) != string::npos) {
token = line.substr(0, pos);
line.erase(0, pos + temp.length());
}
//cout << line << endl;
filesList.push_back(line);
}
pos=0; temp=".";
//borra el .mp3 de las canciones
for(string word:filesList){
while ((pos = word.find(temp)) != string::npos) {
token = word.substr(0, pos);
filesInFolder.push_back(token);
word.erase(0, pos + temp.length());
}
}
file.close();
}
void Constructor::Parse_Artists() {
//_________________ Make Something _________________
}
vector<Song> Constructor::getArtistsList() const {
return ArtistsList;
}
| true |
77d65efa6d973e066b6e7e1181275ea01946eb18 | C++ | lxlyh/Adept-Engine | /GraphicsEngine/Source/TDPhysics/TDSAT.cpp | UTF-8 | 4,155 | 2.609375 | 3 | [
"MIT"
] | permissive | #include "TDSAT.h"
#include "Shapes/TDAABB.h"
#include "Shapes/TDBox.h"
#include "Shapes/TDMeshShape.h"
namespace TD
{
TDSAT::SatInterval TDSAT::GetInterval(TDBox* box, const glm::vec3 axis)
{
const int VertCount = 8;
glm::vec3 vertex[VertCount];
const glm::vec3 Centre = box->GetPos();
const glm::vec3 HalfExtends = box->HalfExtends;
glm::mat3x3 Rotation = glm::mat3(box->GetTransfrom()->GetQuatRot());
glm::vec3 u0 = glm::vec3(Rotation[0][0], Rotation[1][0], Rotation[2][0]);
glm::vec3 u1 = glm::vec3(Rotation[0][1], Rotation[1][1], Rotation[2][1]);//todo: wrong way round?
glm::vec3 u2 = glm::vec3(Rotation[0][2], Rotation[1][2], Rotation[2][2]);
vertex[0] = Centre + Rotation[0] * HalfExtends[0] + Rotation[1] * HalfExtends[1] + Rotation[2] * HalfExtends[2];
vertex[1] = Centre - Rotation[0] * HalfExtends[0] + Rotation[1] * HalfExtends[1] + Rotation[2] * HalfExtends[2];
vertex[2] = Centre + Rotation[0] * HalfExtends[0] - Rotation[1] * HalfExtends[1] + Rotation[2] * HalfExtends[2];
vertex[3] = Centre + Rotation[0] * HalfExtends[0] + Rotation[1] * HalfExtends[1] - Rotation[2] * HalfExtends[2];
vertex[4] = Centre - Rotation[0] * HalfExtends[0] - Rotation[1] * HalfExtends[1] - Rotation[2] * HalfExtends[2];
vertex[5] = Centre + Rotation[0] * HalfExtends[0] - Rotation[1] * HalfExtends[1] - Rotation[2] * HalfExtends[2];
vertex[6] = Centre - Rotation[0] * HalfExtends[0] + Rotation[1] * HalfExtends[1] - Rotation[2] * HalfExtends[2];
vertex[7] = Centre - Rotation[0] * HalfExtends[0] - Rotation[1] * HalfExtends[1] + Rotation[2] * HalfExtends[2];
SatInterval result;
result.min = result.max = glm::dot(axis, vertex[0]);
for (int i = 1; i < VertCount; ++i)
{
float projection = glm::dot(axis, vertex[i]);
result.min = (projection < result.min) ? projection : result.min;
result.max = (projection > result.max) ? projection : result.max;
}
return result;
}
bool TDSAT::OverlapOnAxis(TDBox * BoxA, TDBox * BoxB, glm::vec3 axis, float& value)
{
SatInterval a = GetInterval(BoxA, axis);
SatInterval b = GetInterval(BoxB, axis);
value = a.min - b.min;
return ((b.min <= a.max) && (a.min <= b.max));
}
TDSAT::SatInterval TDSAT::GetInterval(const TDAABB* aabb, const glm::vec3 axis)
{
glm::vec3 min = aabb->GetMin();
glm::vec3 Max = aabb->GetMax();
const int VertCount = 8;
glm::vec3 Verts[VertCount] = {
glm::vec3(min.x, Max.y, Max.z),
glm::vec3(min.x, Max.y, min.z),
glm::vec3(min.x, min.y, Max.z),
glm::vec3(min.x, min.y, min.z),
glm::vec3(Max.x, Max.y, Max.z),
glm::vec3(Max.x, Max.y, min.z),
glm::vec3(Max.x, min.y, Max.z),
glm::vec3(Max.x, min.y, min.z)
};
SatInterval result;
result.min = result.max = glm::dot(axis, Verts[0]);
for (int i = 1; i < VertCount; ++i)
{
float projection = glm::dot(axis, Verts[i]);
result.min = (projection < result.min) ? projection : result.min;
result.max = (projection > result.max) ? projection : result.max;
}
return result;
}
bool TDSAT::OverlapOnAxis(TDAABB * AABB, TDBox * Box, const glm::vec3 axis)
{
SatInterval a = GetInterval(AABB, axis);
SatInterval b = GetInterval(Box, axis);
return ((b.min <= a.max) && (a.min <= b.max));
}
TDSAT::SatInterval TDSAT::GetInterval(const TDTriangle* triangle, const glm::vec3 axis)
{
SatInterval result;
result.min = glm::dot(axis, triangle->Points[0]);
result.max = result.min;
const int TrangleSides = 3;
for (int i = 1; i < TrangleSides; ++i)
{
float value = glm::dot(axis, triangle->Points[i]);
result.min = fminf(result.min, value);
result.max = glm::max(result.max, value);
}
return result;
}
bool TDSAT::OverlapOnAxis(const TDAABB* aabb, const TDTriangle* triangle, const glm::vec3 axis)
{
const SatInterval a = GetInterval(aabb, axis);
const SatInterval b = GetInterval(triangle, axis);
return (b.min <= a.max) && (a.min <= b.max);
}
bool TDSAT::OverlapOnAxis(TDBox* obb, const TDTriangle* triangle, const glm::vec3 axis)
{
const SatInterval a = GetInterval(obb, axis);
const SatInterval b = GetInterval(triangle, axis);
return (b.min <= a.max) && (a.min <= b.max);
}
}; | true |
01bb0b289ac748a42ed4514fe8030e2db1fdd8c3 | C++ | DingFeng0103/CS561 | /Assignment1/Node.h | UTF-8 | 850 | 2.828125 | 3 | [] | no_license | #ifndef __NODE__
#define __NODE__
#include<vector>
#include<string>
#include<iostream>
#include"Path.h"
#define UNEXPLORED 0
#define EXPLORED 1
using namespace std;
class Node
{
private:
Node* ptrParentNode;
int PathOrder;
string Name;
int State;
int TotalCost;
int TrafficEstimate;
vector<Path> vecPaths;
Node* nextChain;
public:
Node();
~Node();
int setState(int state);
int setTrafficeEstimate(int traffic_estimate);
int setName(string name);
int setCost(int cost);
int setParent(Node* nodeParent);
int addPath(string start, string end,int order, int cost);
int setPathOrder(int order);
int setNextChain(Node* ptrNextChain);
int getPathOrder();
int getEstimate();
int getCost();
int getState();
int getNumPaths();
Path* getPaths(int index);
Node* getNextChain();
Node* getParent();
string getName();
};
#endif
| true |
09e613aaada47b91f6aaa393bf3f4315c807d58e | C++ | DorShaar/catch-the-flag | /CatchTheFlag/Point.h | UTF-8 | 390 | 3.03125 | 3 | [] | no_license | #pragma once
using namespace std;
class Point
{
int coordinateX;
int coordinateY;
public:
Point() : coordinateX(0), coordinateY(0) { };
Point(int newXCoord, int newYCoord) : coordinateX(newXCoord), coordinateY(newYCoord) { };
// Setters and Getters.
int getXcoordinate();
void setXCoordinate(int newXCoordinate);
int getYcoordinate();
void setYCoordinate(int newYCoordinate);
}; | true |
6267ca40b5b4967d46798e771457209ff82b64d5 | C++ | lewissbaker/generator | /tests/nested_test.cpp | UTF-8 | 8,727 | 3.09375 | 3 | [
"BSL-1.0"
] | permissive | ///////////////////////////////////////////////////////////////////////////////
// Copyright Lewis Baker, Corentin Jabot
//
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0.
// (See accompanying file LICENSE or http://www.boost.org/LICENSE_1_0.txt)
///////////////////////////////////////////////////////////////////////////////
#include <generator>
#include <string>
#include <string_view>
#include <vector>
#include <memory>
#include <exception>
#include "check.hpp"
void test_yielding_elements_of_empty_generator() {
bool started1 = false;
bool started2 = false;
bool finished = false;
auto makeGen = [&]() -> std::generator<int> {
started1 = true;
co_yield std::ranges::elements_of([&]() -> std::generator<int> {
started2 = true;
co_return;
}());
finished = true;
};
auto gen = makeGen();
CHECK(!started1);
CHECK(!started2);
CHECK(!finished);
auto it = gen.begin();
CHECK(started1);
CHECK(started2);
CHECK(finished);
CHECK(it == gen.end());
}
void test_yielding_elements_of_nested_one_level() {
int checkpoint = 0;
auto makeGen = [&]() -> std::generator<int> {
checkpoint = 1;
co_yield 1;
checkpoint = 2;
co_yield std::ranges::elements_of([&]() -> std::generator<int> {
checkpoint = 3;
co_yield 2;
checkpoint = 4;
}());
checkpoint = 5;
co_yield 3;
checkpoint = 6;
};
auto gen = makeGen();
CHECK(checkpoint == 0);
auto it = gen.begin();
CHECK(checkpoint == 1);
CHECK(it != gen.end());
CHECK(*it == 1);
++it;
CHECK(checkpoint == 3);
CHECK(it != gen.end());
CHECK(*it == 2);
++it;
CHECK(checkpoint == 5);
CHECK(it != gen.end());
CHECK(*it == 3);
++it;
CHECK(checkpoint == 6);
CHECK(it == gen.end());
}
void test_yielding_elements_of_recursive() {
auto makeGen = [](auto& makeGen, int depth) -> std::generator<int> {
co_yield depth;
if (depth > 0) {
co_yield std::ranges::elements_of(makeGen(makeGen, depth - 1));
co_yield -depth;
}
};
auto gen = makeGen(makeGen, 3);
auto it = gen.begin();
CHECK(it != gen.end());
CHECK(*it == 3);
++it;
CHECK(it != gen.end());
CHECK(*it == 2);
++it;
CHECK(it != gen.end());
CHECK(*it == 1);
++it;
CHECK(it != gen.end());
CHECK(*it == 0);
++it;
CHECK(it != gen.end());
CHECK(*it == -1);
++it;
CHECK(it != gen.end());
CHECK(*it == -2);
++it;
CHECK(it != gen.end());
CHECK(*it == -3);
++it;
CHECK(it == gen.end());
}
void test_yielding_elements_of_generator_with_different_value_type() {
auto strings = [](int x) -> std::generator<std::string_view, std::string> {
co_yield std::to_string(x);
// This should still perform O(1) nested suspend/resume operations even
// though the value_type is different.
// Note that there's not really a way to test this property, though.
co_yield std::ranges::elements_of([]() -> std::generator<std::string_view, std::string_view> {
co_yield "foo";
co_yield "bar";
}());
co_yield std::to_string(x + 1);
}(42);
auto it = strings.begin();
CHECK(it != strings.end());
CHECK(*it == "42");
++it;
CHECK(it != strings.end());
CHECK(*it == "foo");
++it;
CHECK(it != strings.end());
CHECK(*it == "bar");
++it;
CHECK(it != strings.end());
CHECK(*it == "43");
++it;
CHECK(it == strings.end());
}
void test_yielding_elements_of_generator_with_different_reference_type() {
auto get_strings1 = []() -> std::generator<std::string> {
co_yield "foo";
};
auto get_strings2 = [&]() -> std::generator<std::string_view> {
co_yield std::ranges::elements_of(get_strings1());
co_yield "bar";
};
auto g = get_strings2();
auto it = g.begin();
CHECK(it != g.end());
CHECK(*it == "foo");
++it;
CHECK(it != g.end());
CHECK(*it == "bar");
++it;
CHECK(it == g.end());
}
struct counting_allocator_base {
static std::atomic<std::size_t> allocatedCount;
};
std::atomic<std::size_t> counting_allocator_base::allocatedCount{0};
template<typename T>
struct counting_allocator : counting_allocator_base {
using value_type = T;
T* allocate(size_t n) {
size_t size = n * sizeof(T);
T* p = std::allocator<T>{}.allocate(n);
counting_allocator_base::allocatedCount += size;
return p;
}
void deallocate(T* p, size_t n) {
size_t size = n * sizeof(T);
counting_allocator_base::allocatedCount -= size;
std::allocator<T>{}.deallocate(p, n);
}
};
void test_yielding_elements_of_generator_with_different_allocator_type() {
// TODO: Ideally we'd be able to detect that yielding elements of a nested generator
// with a different allocator type wasn't wrapping the nested generator in another
// coroutine, but we can only really check this by inspecting assembly.
// So for now we just check that it is functional and ignore the runtime
// aspects of this.
auto g = []() -> std::generator<int, int, std::allocator<std::byte>> {
co_yield std::ranges::elements_of([]() -> std::generator<int, int, counting_allocator<std::byte>> {
co_yield 42;
}());
co_yield 101;
}();
auto it = g.begin();
CHECK(it != g.end());
CHECK(*it == 42);
++it;
CHECK(it != g.end());
CHECK(*it == 101);
++it;
CHECK(it == g.end());
}
void test_yielding_elements_of_vector() {
auto g = []() -> std::generator<int> {
std::vector<int> v = {2, 4, 6, 8};
co_yield std::ranges::elements_of(v);
}();
auto it = g.begin();
CHECK(it != g.end());
CHECK(*it == 2);
++it;
CHECK(it != g.end());
CHECK(*it == 4);
++it;
CHECK(it != g.end());
CHECK(*it == 6);
++it;
CHECK(it != g.end());
CHECK(*it == 8);
++it;
CHECK(it == g.end());
}
template<typename F>
struct scope_guard {
F f;
scope_guard(F f) : f(std::move(f)) {}
scope_guard(scope_guard&&) = delete;
scope_guard(const scope_guard&) = delete;
~scope_guard() {
f();
}
};
void test_nested_generator_scopes_exit_innermost_scope_first() {
std::vector<int> events;
auto makeGen = [&]() -> std::generator<int> {
events.push_back(1);
scope_guard f{[&] { events.push_back(2); }};
auto nested = [&]() -> std::generator<int> {
events.push_back(3);
scope_guard g{[&] { events.push_back(4); }};
co_yield 42;
}();
scope_guard h{[&] { events.push_back(5); }};
co_yield std::ranges::elements_of(std::move(nested));
};
{
auto gen = makeGen();
auto it = gen.begin();
CHECK(*it == 42);
CHECK((events == std::vector{1, 3}));
}
CHECK((events == std::vector{1, 3, 4, 5, 2}));
}
void test_exception_propagating_from_nested_generator() {
struct my_error : std::exception {};
auto g = []() -> std::generator<int> {
try {
co_yield std::ranges::elements_of([]() -> std::generator<int> {
co_yield 42;
throw my_error{};
}());
CHECK(false);
} catch (const my_error&) {
}
co_yield 99;
}();
auto it = g.begin();
CHECK(it != g.end());
CHECK(*it == 42);
++it;
CHECK(it != g.end());
CHECK(*it == 99);
++it;
CHECK(it == g.end());
}
void test_elementsof_with_allocator_args() {
std::vector<int> v;
auto with_alloc = [&] (std::allocator_arg_t, std::allocator<std::byte> a) -> std::generator<int> {
co_yield 42;
//co_yield std::ranges::elements_of(v);
co_yield std::ranges::elements_of(v, a);
};
for(auto && i : with_alloc(std::allocator_arg, {})){
}
}
int main() {
RUN(test_yielding_elements_of_empty_generator);
RUN(test_yielding_elements_of_nested_one_level);
RUN(test_yielding_elements_of_recursive);
RUN(test_yielding_elements_of_generator_with_different_value_type);
RUN(test_yielding_elements_of_generator_with_different_reference_type);
RUN(test_yielding_elements_of_generator_with_different_allocator_type);
RUN(test_elementsof_with_allocator_args);
RUN(test_yielding_elements_of_vector);
RUN(test_nested_generator_scopes_exit_innermost_scope_first);
RUN(test_exception_propagating_from_nested_generator);
return 0;
}
| true |
6088e4c803382c35d0183056ff91191b0fd79910 | C++ | Madzik890/Wykop-Virus | /Source/UsbParameter.cpp | UTF-8 | 1,138 | 2.734375 | 3 | [] | no_license | #include "UsbParameter.hpp"
#include <Windows.h>
void UsbParameter::mainFunc()
{
getDeviceList();
}
std::string UsbParameter::getInformation()
{
std::string text;
text += "\n [Parametry USB] \n";
text += "Liczba podlaczonych urzadzen: " + std::to_string(u_connectedDevices) + "\n";
text += "[/Parametry USB] \n";
return text;
}
bool UsbParameter::getDeviceList()
{
UINT nDevices = 0;
GetRawInputDeviceList(NULL, &nDevices, sizeof(RAWINPUTDEVICELIST));
// Got Any?
if (nDevices < 1)
return false;// Exit
// Allocate Memory For Device List
PRAWINPUTDEVICELIST pRawInputDeviceList;
pRawInputDeviceList = new RAWINPUTDEVICELIST[sizeof(RAWINPUTDEVICELIST) * nDevices];
// Got Memory?
if (pRawInputDeviceList == NULL)
return false;// Error
// Fill Device List Buffer
int nResult;
nResult = GetRawInputDeviceList(pRawInputDeviceList, &nDevices, sizeof(RAWINPUTDEVICELIST));
// Got Device List?
if (nResult < 0)
{
// Clean Up
delete[] pRawInputDeviceList;
return false;// Error
}
// Loop Through Device List
u_connectedDevices = nDevices;
// Clean Up - Free Memory
delete[] pRawInputDeviceList;
}
| true |
dafd1a22a1295b5ca623e9b100c9b44bdc216afc | C++ | shoumitro-cse/data-structure-solving | /BinaryTree/Misc/MaxBend.cpp | UTF-8 | 3,059 | 3.6875 | 4 | [] | no_license | // Path length having maximum number of bends
// g++ MaxBend.cpp && ./a.out
#include <bits/stdc++.h>
using namespace std;
// structure node
struct Node {
int key;
struct Node* left;
struct Node* right;
};
// Utility function to create a new node
struct Node* newNode(int key)
{
struct Node* node = new Node();
node->left = NULL;
node->right = NULL;
node->key = key;
return node;
}
void findMaxBendsUtil(struct Node* node,
char dir, int bends,
int* maxBends, int soFar,
int* len)
{
// Base Case
if (node == NULL)
return;
// Leaf node
if (node->left == NULL && node->right == NULL) {
if (bends > *maxBends) {
*maxBends = bends;
*len = soFar;
}
}
// Recurring for both left and right child
else {
if (dir == 'l') {
findMaxBendsUtil(node->left, dir,
bends, maxBends,
soFar + 1, len);
findMaxBendsUtil(node->right, 'r',
bends + 1, maxBends,
soFar + 1, len);
}
else {
findMaxBendsUtil(node->right, dir,
bends, maxBends,
soFar + 1, len);
findMaxBendsUtil(node->left, 'l',
bends + 1, maxBends,
soFar + 1, len);
}
}
}
// Helper function to call findMaxBendsUtil()
int findMaxBends(struct Node* node) {
if (node == NULL)
return 0;
int len = 0, bends = 0, maxBends = -1;
// Call for left subtree of the root
if (node->left)
findMaxBendsUtil(node->left, 'l', bends, &maxBends, 1, &len);
// Call for right subtree of the root
if (node->right)
findMaxBendsUtil(node->right, 'r', bends, &maxBends, 1, &len);
// Include the root node as well in the path length
len++;
return len;
}
// Driver code
int main()
{
/*
10
/ \
8 2
/ \ /
3 5 2
\
1
/
9
*/
struct Node* root = newNode(10);
root->left = newNode(8);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(5);
root->right->left = newNode(2);
root->right->left->right = newNode(1);
root->right->left->right->left = newNode(9);
cout << findMaxBends(root) - 1;
return 0;
}
/*
Path length having maximum number of bends
Given a binary tree, find the path length having maximum number of bends.
Note : Here, bend indicates switching from left to right or vice versa while traversing in the tree.
For example, consider below paths (L means moving leftwards, R means moving rightwards):
LLRRRR – 1 Bend
RLLLRR – 2 Bends
LRLRLR – 5 Bends
Prerequisite : Finding Max path length in a Binary Tree
Examples:
Input :
4
/ \
2 6
/ \ / \
1 3 5 7
/
9
/ \
12 10
\
11
/ \
45 13
\
14
Output : 6
In the above example, the path 4-> 6-> 7-> 9-> 10-> 11-> 45
is having the maximum number of bends, i.e., 3.
The length of this path is 6.
*/ | true |
3dee611511549b85896c1a20ebc4946f00f9dd6f | C++ | sraihan73/Lucene- | /core/src/java/org/apache/lucene/search/Multiset.cpp | UTF-8 | 1,005 | 2.734375 | 3 | [] | no_license | using namespace std;
#include "Multiset.h"
namespace org::apache::lucene::search
{
Multiset<T>::IteratorAnonymousInnerClass::IteratorAnonymousInnerClass(
shared_ptr<Multiset<std::shared_ptr<T>>> outerInstance,
unordered_map<T, int>::const_iterator mapIterator)
{
this->outerInstance = outerInstance;
this->mapIterator = mapIterator;
}
bool Multiset<T>::IteratorAnonymousInnerClass::hasNext()
{
// C++ TODO: Java iterators are only converted within the context of 'while'
// and 'for' loops:
return remaining > 0 || mapIterator.hasNext();
}
shared_ptr<T> Multiset<T>::IteratorAnonymousInnerClass::next()
{
if (remaining == 0) {
// C++ TODO: Java iterators are only converted within the context of 'while'
// and 'for' loops:
unordered_map::Entry<std::shared_ptr<T>, int> next = mapIterator.next();
current = next.getKey();
remaining = next.getValue();
}
assert(remaining > 0);
remaining -= 1;
return current;
}
} // namespace org::apache::lucene::search | true |
3837b530d7f9d4d60d97c1a6336762c74611bc23 | C++ | bsparnochia/clase-array-cpp | /src/main.cpp | ISO-8859-1 | 605 | 3.546875 | 4 | [] | no_license | /*
* main.cpp
*
* Created on: 12 may. 2020
* Author: brian
*/
#include "Array.h"
#include <iostream>
int main(){
/* defino un arreglo con tamao 2 */
Array a(2);
/* arreglo inicializado por vector temporal */
Array b = { 6,3,7};
/* copia de b en c */
Array c (b);
/* asigno un vector "b" a "a" */
a=b;
/* asigno un vector temporal */
a = { 1, 2, 33, 44, 5 };
c.mostrarArray();
a.mostrarArray();
/* contenido de c en la posicin 2 */
std::cout<<c[2]<<std::endl;
/* comparaciones */
std::cout<< (c == b) <<std::endl;
std::cout<< (a == b) <<std::endl;
return 0;
}
| true |
12673cbd5926c04ed021ace1bbe5bceeead4e39e | C++ | joe-zxh/OJ | /剑指offer/面试题42 连续子数组的最大和.cpp | UTF-8 | 360 | 2.984375 | 3 | [] | no_license | class Solution {
public:
int FindGreatestSumOfSubArray(vector<int> array) {
int sz = array.size();
if(sz==0){
return 0;
}
int pre=array[0];
int retsum=pre;
for(int i = 1;i<sz;i++){
pre = pre+array[i]>array[i]?pre+array[i]:array[i];
retsum = pre>retsum?pre:retsum;
}
return retsum;
}
}; | true |
f9ca3cd99c0bfaee2ffc9e96956701f9e1a4b275 | C++ | ernikus/Edabit-Challenges-Cpp | /5. VERY HARD/Longest Alternating Substring/main.cpp | UTF-8 | 4,215 | 3.234375 | 3 | [] | no_license | //Title: Longest Alternating Substring
//Difficulty: Very Hard
//Source: https://edabit.com/challenge/R95FfS8PGtsCLxnKH
//Soln Author: ernikus
#include "Solution.h"
#include <iostream>
#include <string>
#include <vector>
extern std::string longestSubstring(std::string digits);
extern bool isEven(const int num);
bool execute(const std::string input, const std::string output, const std::string answer, std::vector<std::string>& failed)
{
std::string comp{};
std::cout << "Input:\t" << input << std::endl;
comp += "Input";
comp += input;
std::cout << "Output:\t" << output << std::endl;
comp += ";\tOutput: ";
comp += output;
std::cout << "Answer:\t" << answer << std::endl;
comp += ";\tAnswer: ";
comp += answer;
if (output == answer)
{
std::cout << "Correct Answer!" << std::endl << std::endl;
return true;
}
else
{
std::cout << "Bad Answer!" << std::endl << std::endl;
failed.push_back(comp);
return false;
}
}
int main()
{
int correct{ 0 }, testNum{ 0 };
std::vector<std::string> failed{};
correct += execute("844929328912985315632725682153", longestSubstring("844929328912985315632725682153"), "56327256", failed);
testNum++;
correct += execute("769697538272129475593767931733", longestSubstring("769697538272129475593767931733"), "27212947", failed);
testNum++;
correct += execute("937948289456111258444958189244", longestSubstring("937948289456111258444958189244"), "894561", failed);
testNum++;
correct += execute("736237766362158694825822899262", longestSubstring("736237766362158694825822899262"), "636", failed);
testNum++;
correct += execute("369715978955362655737322836233", longestSubstring("369715978955362655737322836233"), "369", failed);
testNum++;
correct += execute("345724969853525333273796592356", longestSubstring("345724969853525333273796592356"), "496985", failed);
testNum++;
correct += execute("548915548581127334254139969136", longestSubstring("548915548581127334254139969136"), "8581", failed);
testNum++;
correct += execute("417922164857852157775176959188", longestSubstring("417922164857852157775176959188"), "78521", failed);
testNum++;
correct += execute("251346385699223913113161144327", longestSubstring("251346385699223913113161144327"), "638569", failed);
testNum++;
correct += execute("483563951878576456268539849244", longestSubstring("483563951878576456268539849244"), "18785", failed);
testNum++;
correct += execute("853667717122615664748443484823", longestSubstring("853667717122615664748443484823"), "474", failed);
testNum++;
correct += execute("398785511683322662883368457392", longestSubstring("398785511683322662883368457392"), "98785", failed);
testNum++;
correct += execute("368293545763611759335443678239", longestSubstring("368293545763611759335443678239"), "76361", failed);
testNum++;
correct += execute("775195358448494712934755311372", longestSubstring("775195358448494712934755311372"), "4947", failed);
testNum++;
correct += execute("646113733929969155976523363762", longestSubstring("646113733929969155976523363762"), "76523", failed);
testNum++;
correct += execute("575337321726324966478369152265", longestSubstring("575337321726324966478369152265"), "478369", failed);
testNum++;
correct += execute("754388489999793138912431545258", longestSubstring("754388489999793138912431545258"), "545258", failed);
testNum++;
correct += execute("198644286258141856918653955964", longestSubstring("198644286258141856918653955964"), "2581418569", failed);
testNum++;
correct += execute("643349187319779695864213682274", longestSubstring("643349187319779695864213682274"), "349", failed);
testNum++;
correct += execute("919331281193713636178478295857", longestSubstring("919331281193713636178478295857"), "36361", failed);
testNum++;
std::cout << "Correctness: " << std::endl;
std::cout << correct << "/" << testNum << "!";
std::cout << "\t(" << int(float(correct) / float(testNum) * 100) << "%/" << 100 << "%)" << std::endl;
if (!failed.empty())
{
std::cout << "Failed: " << testNum - correct << std::endl;
for (int i = 0; i < failed.size(); ++i)
{
std::cout << failed[i] << std::endl;
}
}
}
| true |
6c9bfc8877f6e5fb62d844e99e8501f8dd38829f | C++ | cdzech/DBBenchmark | /src/Layout/Relationship.cpp | UTF-8 | 2,165 | 2.9375 | 3 | [] | no_license | /*
* Relationship.cpp
*
* Created on: Oct 28, 2014
* Author: root
*/
#include "Relationship.h"
namespace HDDTest
{
Relationship::Relationship(std::string name, uint64_t size, unsigned int pagesPerExtent, unsigned int pageSizeInKB)
{
this->name = name;
this->extents.reserve(size);
this->unallocatedExtents = size;
this->pagesPerExtent = pagesPerExtent;
this->pageSizeInKB = pageSizeInKB;
}
Relationship::~Relationship()
{
// TODO Auto-generated destructor stub
}
void Relationship::addExtent(uint64_t start)
{
struct Extent extent;
extent.startKb = start;
extent.number = extents.size();
this->extents.push_back(extent);
this->unallocatedExtents--;
}
void Relationship::setNextExtent(uint64_t nextExtent)
{
this->nextExtent = nextExtent;
}
uint64_t Relationship::getNextExtent()
{
if (isNextExtent())
{
uint64_t extentStart = this->extents.at(this->nextExtent).startKb;
this->nextExtent++;
return extentStart;
}
else
{
return 0;
}
}
uint64_t Relationship::getNextPage()
{
uint64_t nextPage;
if(this->pageNumber == 0)
{
this->currentExtent = this->getNextExtent();
nextPage = this->currentExtent;
}
nextPage = currentExtent + this->pageNumber * this->pageSizeInKB;
pageNumber++;
if(pageNumber == this->pagesPerExtent)
{
pageNumber = 0;
}
return nextPage;
}
uint64_t Relationship::getPrevExtent()
{
if (isNextExtent())
{
this->nextExtent--;
uint64_t extentStart = this->extents.at(this->nextExtent).startKb;
return extentStart;
}
else
{
return 0;
}
}
bool Relationship::isNextExtent()
{
return this->nextExtent < this->extents.size();
}
bool Relationship::isUnAllocatedExtent()
{
return this->unallocatedExtents != 0;
}
int Relationship::getProbability(uint64_t totalUnallocatedExtents)
{
int prob = this->unallocatedExtents * 100 / totalUnallocatedExtents ;
return prob;
}
uint64_t Relationship::getRandomExtent()
{
return this->extents[rand() % this->extents.size()].startKb;
}
uint64_t Relationship::getRandomPage()
{
return this->extents[rand() % this->extents.size()].startKb + (rand() % this->pagesPerExtent) * this->pageSizeInKB;
}
} /* namespace HDDTest */
| true |
4b559136c97234d9f6782d9388ef6b7a7225b7d8 | C++ | zl1704/zlcompiler | /src/tree/Ident.hpp | UTF-8 | 485 | 2.78125 | 3 | [] | no_license | /*
* Ident.hpp
*
* Created on: 2017年12月8日
* Author: ZL
*/
#ifndef TREE_IDENT_HPP_
#define TREE_IDENT_HPP_
#include "Expression.hpp"
/**
* 标识符
*/
class Ident:public Expression {
public:
string name;
Symbol* sym;
Ident();
Ident(int pos,string name):Expression(pos),name(name.data()){
sym = NULL;
};
virtual void accept(Visitor* v) {
v->visitIdent(this);
}
virtual int getTag() {
return IDENT;
}
virtual ~Ident();
};
#endif /* TREE_IDENT_HPP_ */
| true |
cc968590525b681f8ce04eb2c32fa33513b1cd50 | C++ | chriscoo/CA-Frogger | /CAFrogger/Projectile.h | UTF-8 | 1,109 | 2.625 | 3 | [] | no_license | /**
@file Projectile
@author Chris Arsenault Chris.arsenault06@gmail.com
@version 1.0
@section LICENSE
This software is based on the material accompanying the book "SFML Game Development" see License.txt
Additions and modifications are my sole work for prog 1266
@section DESCRIPTION
<your description of the purpose of this file here>
*/
#pragma once
#include "Entity.h"
#include "TextureHolder.h"
#include "TextNode.h"
#include "CommandQueue.h"
namespace GEX {
class Projectile : public Entity
{
public:
enum class Type
{
AlliedBullet,
EnemyBullet,
Missle
};
public:
Projectile(Type type);
unsigned int getCategory() const override;
float getMaxSpeed() const;
bool isGuided() const;
void guideTowards(sf::Vector2f position);
sf::FloatRect getBoundingRect() const override;
private:
virtual void updateCurrent(sf::Time dt, CommandQueue& commands) override;
virtual void drawCurrent(sf::RenderTarget& target, sf::RenderStates states) const override;
private:
Type _type;
sf::Sprite _sprite;
sf::Vector2f _targetDirection; // unit vecor pointing at the closest enemy plane
};
}
| true |
3952b5eb954cfb8db303586f9a6399ed8484287d | C++ | ksvcng/code | /documents/codechef/november challange/3.cpp | UTF-8 | 1,035 | 2.53125 | 3 | [] | no_license | #include<iostream>
#include <vector>
#include <algorithm>
#include<string>
#include<math.h>
using namespace std;
int main()
{ int t,n,p;
cin>>t;
while(t--){
int r,j=1,i=0;
cin>>n>>p;
if(n==1 || n==2){cout<<"impossible"<<endl;}
else if(p==1 || p==2){cout<<"impossible"<<endl;}
else{
char arr[n];
int l=n/p;
if(p%2==0){
while(i<p/2-1){arr[i]='a';arr[p-i-1]='a';i++;}
arr[i]='b';i++;arr[i]='b';
}
else {
while(i<p/2){arr[i]='a';arr[p-i-1]='a';i++;}
arr[i]='b';
}
if(l>1){
for(i=0;i<p;i++){
arr[(j)*p+i]=arr[i];
if(i==p-1)
{if(j==l-1)break;
else j++;i=-1;
}
}
}
for(i=0;i<n;i++){cout<<arr[i];}
cout<<endl;
}
}
return 0;}
| true |
7370f27829f59fdd5a7c08905c8333a95276d098 | C++ | JediChou/jedichou-study-algo | /standard-cpp/cpp-WrxBegVC2008/Ex4_02.cpp | UTF-8 | 443 | 3.28125 | 3 | [] | no_license | // From Wrox Begining Visual C++ 2008, page 157
// Ex4_02.cpp
// Initialize array
#include <iostream>
#include <iomanip>
using std::cout;
using std::endl;
using std::setw;
int main(void)
{
int value[5] = {1, 2, 3};
int junk [5];
cout << endl;
for( int i = 0; i < 5; i++)
cout << setw(12) << value[i];
cout << endl;
for( int i = 0; i < 5; i++)
cout << setw(12) << junk[i];
cout << endl;
return 0;
}
| true |
6a47a6809921dfe4868f8b40203e1822240f4fdc | C++ | adhaase/decision-crawler | /hero.cpp | UTF-8 | 1,261 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <windows.h> // WinApi header
#include "hero.h"
Hero::Hero() {
vitality = 25;
attack = 5;
agility = 5;
luck = 5;
}
void Hero::setvitality(int vitality, Hero &h) {
h.vitality = vitality;
}
void Hero::setAttack(int attack, Hero &h) {
h.attack = attack;
}
void Hero::setAgility(int agility, Hero &h) {
h.agility = agility;
}
void Hero::setLuck(int luck, Hero &h) {
h.luck = luck;
}
void Hero::printvitality(Hero &h) {
std::cout << h.vitality;
}
void Hero::printAttack(Hero &h) {
std::cout << h.attack;
}
void Hero::printAgility(Hero &h) {
std::cout << h.agility;
}
void Hero::printLuck(Hero &h) {
std::cout << h.luck;
}
void Hero::printHeroStats(Hero &h) {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, 10); // light green
std::cout << "VITALITY: " << h.vitality << std::endl;
SetConsoleTextAttribute(hConsole, 12); // light red
std::cout << "ATTACK: " << h.attack << std::endl;
SetConsoleTextAttribute(hConsole, 11);
std::cout << "AGILITY: " << h.agility << std::endl;
SetConsoleTextAttribute(hConsole, 14); // yellow
std::cout << "LUCK: " << h.luck << std::endl;
SetConsoleTextAttribute(hConsole, 15); // white
} | true |
b6c98c0be62e2ad510ceaea9031612e4769c9ebc | C++ | sharma18b/DSA_Codes | /Assignment1/ques4.cpp | UTF-8 | 599 | 2.53125 | 3 | [] | no_license | #include <stdio.h>
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
void timetable(int x)
{
int num_of_classes,num_students,num_teachers,total_hrs,hrs_per_class,break_betw_class;
cout << " please enter the number of classes ";
cin >> num_of_classes;
cout << " please enter the num_students ";
cin >> num_students;
cout << " please enter the num_teachers ";
cin >> num_teachers;
cout << " please enter the total_hrs ";
cin >> total_hrs;
cout << " please enter the hrs_per_class ";
cin >> hrs_per_class;
}
int main()
{
timetable();
return 0;
}
| true |
3da964e95913aa3f41aef900923af823cfb78db2 | C++ | hadashiA/sometuke | /sometuke/process/process.cc | UTF-8 | 1,597 | 2.671875 | 3 | [] | no_license | #include "sometuke/process/process.h"
#include "sometuke/process/repeat.h"
#include "sometuke/process/sequence.h"
#include "sometuke/process/process_timer.h"
#include <functional>
namespace sometuke {
shared_ptr<Process> Process::Repeat(int num) {
shared_ptr<Process> repeat(new class Repeat(shared_from_this(), num));
return repeat;
}
shared_ptr<Process> Process::Delay(const s2_time duration) {
shared_ptr<Process> timer(new class ProcessTimer(shared_from_this(),
0, ProcessTimer::REPEAT_FOREVER, duration));
return timer;
}
shared_ptr<Process> Process::Interval(const s2_time interval) {
shared_ptr<Process> timer(new class ProcessTimer(shared_from_this(), interval));
return timer;
}
shared_ptr<Process> Process::Timer(const s2_time interval,
const unsigned int repeat, const s2_time delay) {
shared_ptr<Process> timer(new class ProcessTimer(shared_from_this(),
interval, repeat, delay));
return timer;
}
template<class T>
shared_ptr<Sequence> Process::Chain() {
shared_ptr<Process> next(new T);
shared_ptr<Sequence> sequence(new Sequence(shared_from_this(), next));
return sequence;
}
template<class T, class Arg1, class... Args>
shared_ptr<Sequence> Process::Chain(Arg1&& arg1, Args&& ... args) {
shared_ptr<Process> next(new T(std::forward<Arg1>(arg1), std::forward<Args>(args)...));
shared_ptr<Sequence> sequence(new Sequence(shared_from_this(), next));
return sequence;
}
}
| true |
9b8e0f14b4b9e6a6857f767e0258027e2416102a | C++ | mseidel42/apfelxx | /inc/apfel/operatorerbl.h | UTF-8 | 693 | 2.5625 | 3 | [
"MIT"
] | permissive | //
// APFEL++ 2017
//
// Authors: Valerio Bertone: valerio.bertone@cern.ch
//
#pragma once
#include "apfel/operator.h"
namespace apfel
{
/**
* @brief The class, derived from the Operator class, defines a
* special kind of Object necessary for the evolution of GPDs in the
* ERBL region.
*/
class OperatorERBL: public Operator
{
public:
OperatorERBL() = delete;
/**
* @brief The Operator constructor.
* @param gr: the Grid object
* @param expr: the expression to be transformed
* @param eps: relative accuracy of the numerical integrations (default: 10<SUP>-5</SUP>)
*/
OperatorERBL(Grid const& gr, Expression const& expr, double const& eps = 1e-5);
};
}
| true |
e6a5fc79d938ed33069f8376e8df4872730b3061 | C++ | ptahmose/ArchImgProc | /ArchImgProc/Bitmap/datastore.h | UTF-8 | 3,223 | 3.34375 | 3 | [] | no_license | #pragma once
#include <algorithm>
namespace ArchImgProc
{
/// <summary> Return value for CDataStore::AddOrSetValue. </summary>
enum class DataStoreStatusCode
{
/// <summary> The item was new and it was successfully added. </summary>
OK_Added,
/// <summary> The item was already present, and it was successfully updated. </summary>
OK_Updated,
/// <summary> The item was already present, but the stored length is less than what it was tried to update. </summary>
LengthMismatch,
/// <summary> The item could not be added because it did not fit into the datastore. </summary>
CapacityExceeded
};
/// <summary> A very simplistic (but fast...) data store. It allows to store a couple of (untyped) items,
/// the total size if limited by the template parameter (max. 255 bytes). The overhead per item is 3 bytes.
/// </summary>
///
/// <remarks> This class is only meant to store just a few items. Also note that this class is not thread-safe. </remarks>
///
/// <typeparam name="tInitialSize"> The total size of the data store (255 bytes max!). </typeparam>
template <uint8_t tInitialSize>
class CDataStore
{
private:
uint8_t builtinStore[tInitialSize];
uint8_t sizeUsed;
public:
CDataStore() :sizeUsed(0)
{
memset(this->builtinStore, 0, tInitialSize);
}
bool GetValue(uint16_t key, void* ptrData, uint8_t sizeData, uint8_t* ptrSizeRequired) const
{
int offset = this->GetOffsetForKey(key);
if (offset >= 0)
{
// the next byte gives us the size
uint8_t actualSize = this->builtinStore[offset + 2];
if (ptrSizeRequired != nullptr)
{
*ptrSizeRequired = actualSize;
}
if (ptrData != nullptr)
{
memcpy(ptrData, this->builtinStore + offset + 3, (std::min)(sizeData, actualSize));
}
return true;
}
return false;
}
ITinyDataStore::AddValueRetCode AddOrSetValue(uint16_t key, void* ptrData, uint8_t sizeData)
{
int offset = this->GetOffsetForKey(key);
if (offset < 0)
{
// key is new!
// TODO: check if it fits in
if (sizeof(builtinStore) - this->sizeUsed < ((int)sizeData) + 3)
{
return ITinyDataStore::AddValueRetCode::Failure_CapacityExceeded;
}
*((uint16_t*)((&this->builtinStore[0]) + this->sizeUsed)) = key;
this->builtinStore[this->sizeUsed + 2] = sizeData;
memcpy(&(this->builtinStore[this->sizeUsed + 3]), ptrData, sizeData);
this->sizeUsed += sizeData + 3;
return ITinyDataStore::AddValueRetCode::Success_Added;// DataStoreStatusCode::OK_Added;
}
uint8_t sizeCurrent = this->builtinStore[offset + 2];
if (sizeCurrent < sizeCurrent)
{
return ITinyDataStore::AddValueRetCode::Failure_ItemsLengthTooLarge;// DataStoreStatusCode::LengthMismatch;
}
memcpy(&(this->builtinStore[offset + 3]), ptrData, (std::min)(sizeData, sizeCurrent));
return ITinyDataStore::AddValueRetCode::Success_Updated;// DataStoreStatusCode::OK_Updated;
}
private:
int GetOffsetForKey(uint16_t key) const
{
for (int i = 0; i < this->sizeUsed;)
{
if (*((uint16_t*)(this->builtinStore + i)) == key)
{
return i;
}
// advance to next chunk
i += 3 + this->builtinStore[i + 2];
}
return -1;
}
};
} | true |
4fe9029236ec530427625493e2cf0c5055c54281 | C++ | Jisti007/Mobile-Project-ideal-broccoli | /gles3jni/app/src/main/cpp/game/scenes/MovementAnimation.cpp | UTF-8 | 1,166 | 2.796875 | 3 | [] | no_license | #include "MovementAnimation.h"
#include "../GameMap.h"
MovementAnimation::MovementAnimation(
Actor* actor, Scene* scene, glm::vec2 destination,
bool follows, float speed, bool blocking
) : Animation(blocking) {
this->actor = actor;
this->scene = scene;
this->destination = destination;
this->follows = follows;
this->speed = speed;
}
bool MovementAnimation::onAnimate(float deltaTime) {
auto deltaPosition = destination - actor->getPosition();
auto distanceSquared = glm::dot(deltaPosition, deltaPosition);
const auto movementSpeed = GameMap::gridSize * speed;
auto movementDistance = movementSpeed * deltaTime;
bool destinationReached = false;
if (distanceSquared <= movementDistance * movementDistance) {
actor->setPosition(destination);
destinationReached = true;
} else {
auto direction = glm::normalize(deltaPosition);
auto nextPosition = actor->getPosition() + movementDistance * direction;
actor->setDepth(-nextPosition.y);
actor->setPosition(nextPosition);
//actor->offsetPosition(direction * movementDistance);
}
if (follows) {
scene->getCamera()->setTarget(actor->getPosition() / 128.0f);
}
return destinationReached;
}
| true |
8caef793860a92beeed7a76f82b32fa830cb4b9e | C++ | zlite/OpenMVrover | /pulsein_test/pulsein_test.ino | UTF-8 | 607 | 2.609375 | 3 | [] | no_license |
const int BAUD_RATE = 9600;
int RC;
int RC1_pin = 3;
int RC2_pin = 4;
int RC3_pin = 5;
unsigned long RC1_value;
unsigned long RC2_value;
unsigned long RC3_value;
void setup() {
Serial.begin(BAUD_RATE);
pinMode(RC1_pin, INPUT);
pinMode(RC2_pin, INPUT);
pinMode(RC3_pin, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
RC1_value = pulseIn(RC1_pin, HIGH);
RC2_value = pulseIn(RC2_pin, HIGH);
RC3_value = pulseIn(RC3_pin, HIGH);
Serial.print(RC1_value);
Serial.print(" ");
Serial.print(RC2_value);
Serial.print(" ");
Serial.println(RC3_value);
}
| true |
7224ba882f590d138347f72d2dc2c603df903748 | C++ | MORETechnologies/MoreArduinoController | /DriveController.h | UTF-8 | 607 | 2.84375 | 3 | [] | no_license | #ifndef DriveController_h
#define DriveController_h
#include "MotorController.h"
#include <Arduino.h>
class DriveController
{
public:
DriveController(int leftSpeedPin, int leftDirectionPin1, int leftDirectionPin2, int rightSpeedPin, int rightDirectionPin1, int rightDirectionPin2);
void setup();
void goForward(int speed);
void goBackward(int speed);
void turnLeft(int speed);
void turnRight(int speed);
MotorController getLeftMotorController();
MotorController getRightMotorController();
private:
MotorController leftMotor;
MotorController rightMotor;
};
#endif
| true |
d397e439db98a1470bc9dc6765c0224933cc7029 | C++ | NLGRF/Advance-Compro | /mid term/week 3.1/ex2.cpp | UTF-8 | 302 | 3.234375 | 3 | [] | no_license | #include <stdio.h>
int main()
{
int d,even = 0 ,odd = 0;
long num;
printf("Enter a number : ");
scanf("%ld",&num);
while(num>0){
d = num%10;
if(d%2==0){
even++;
}
else
odd++;
num = num/10;
}
printf("count event = %d \n",even);
printf("count odd = %d \n",odd);
return 0;
}
| true |
a0887172f4b858a5e1274bbb2669febb0b1fe03d | C++ | LUTLJS/CodeForces | /DataStructure/Extended Euclidean Algorithm.cpp | UTF-8 | 447 | 2.828125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b, int& x, int& y) {
x = 1, y = 0;
int x1 = 0, y1 = 1, a1 = a, b1 = b;
while (b1) {
int q = a1 / b1;
tie(x, x1) = make_tuple(x1, x - q * x1);
tie(y, y1) = make_tuple(y1, y - q * y1);
tie(a1, b1) = make_tuple(b1, a1 - q * b1);
}
return a1;
}
int main()
{
int x,y;
cout<<gcd(9,54,x,y);
cout<<x<<" "<<y;
return 0;
}
| true |
7ba2889ab1a93e1fb9bec953776a0e4d4fdf39df | C++ | 1432849339/SimpleJson | /SimpleJson/stage/thread.h | UTF-8 | 1,357 | 2.703125 | 3 | [] | no_license | /* =====================================================================================
* Author: Zhang Wen(zhangwen@szkingdom.com)
* Created: 2014-6-20 14:57
* Description:
* =====================================================================================
*/
#ifndef ISON_BASE_THREAD_H_
#define ISON_BASE_THREAD_H_
#include <thread>
#include <atomic>
#include <memory>
#include "isonbase.h"
namespace ison {
namespace base {
class ISONBASE_API Thread {
public:
enum State {
kStopped = 0,
kRunning,
kStoping,
};
Thread() : state_(kStopped) {}
virtual ~Thread() { if (self_ && self_->joinable()) self_->join(); }
virtual void Run() = 0;
virtual void Start() {
if (!self_) {
self_.reset(new std::thread(std::bind(&Thread::Run, this)));
state_ = kRunning;
}
}
virtual void Stop() {
state_ = kStoping;
}
virtual void Join() {
if (self_) {
self_->join();
Stopped();
}
}
void Stopped() {
state_ = kStopped;
}
bool IsRunning() {
return state_ == kRunning;
}
bool IsStopping() {
return state_ == kStoping;
}
bool IsStopped() {
return state_ == kStopped;
}
private:
std::shared_ptr<std::thread> self_;
std::atomic<int> state_;
};
} //namespace base
} //namespace ison
#endif // ISON_BASE_THREAD_H_ | true |
de45f36d142f09dea27afe2a359010984a34bd49 | C++ | agancsos/cpp | /preparer/src/AMGString/amgstring.h | UTF-8 | 571 | 2.6875 | 3 | [
"MIT"
] | permissive | #ifndef __AMGSTRING_H_INCLUDED__
#define __AMGSTRING_H_INCLUDED__
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/**
This class helps manipulate custom string objects
*/
class AMGString{
private:
string str;
public:
AMGString();
AMGString(string st);
~AMGString();
string padRight(int len, string pad);
string padLeft(int len, string pad);
vector<string>split(string delim);
vector<string>splitByLine();
string replaceAll(string search,string replace);
string strip();
bool contains(string search);
};
#endif
| true |
a05ea97639f22eb227ee10c2f51be02221266cee | C++ | JaysonSunshine/Portfolio | /Software_Engineering/C++/parentheses(without_subsets).cpp | UTF-8 | 1,085 | 3.734375 | 4 | [] | no_license | #include <algorithm>
#include <iostream>
#include <string>
using namespace std;
void parentheses(int left_remain, int right_remain, int left_have, int right_have, string word){
if(left_remain == 0 && right_remain == 0){
if(left_have == right_have)
cout << word << endl;
}
else if(left_remain == 0){
if(left_have > right_have){
parentheses(left_remain, right_remain - 1, left_have, right_have + 1, word + ")");
}
else if(left_have == right_have)
cout << word << endl;
}
else if(right_remain == 0){
if(left_have == right_have)
cout << word << endl;
}
else{
if(right_remain > left_have - right_have){
parentheses(left_remain - 1, right_remain, left_have + 1, right_have, word + "(");
}
if(left_have > right_have){
parentheses(left_remain, right_remain - 1, left_have, right_have + 1, word + ")");
if(left_have == right_have)
cout << word << endl;
}
}
}
int main(int argc, char* argv[]){
if(argc > 2){
int left = atoi(argv[1]);
int right = atoi(argv[2]);
string word = "";
parentheses(left, right, 0, 0, word);
}
return 0;
} | true |
64baf97ae297118a0837b8961bdea414cb9995da | C++ | mashood951/Random-Programs | /ASCII code finer.cpp | UTF-8 | 253 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
cout << "Enter a name : " << endl;
getline(cin, name);
for (int i = 0; i < name.size(); i++)
{
cout << (int)name[i] << endl;
}
system("pause");
return 0;
}
| true |
f141cc06e49a0363cc6f771561a11b0afe878983 | C++ | Trung-Rei/Project-MMT-Socket-HTTP | /C++/TCPServer.cpp | UTF-8 | 2,187 | 2.953125 | 3 | [] | no_license | #include "TCPServer.h"
#include <iostream>
#include <WS2tcpip.h>
#include <string>
#pragma comment (lib, "ws2_32.lib")
using namespace std;
// khởi tạo để lắng nghe tại PORT
TCPServer::TCPServer(short port)
{
_port = port;
}
// Bắt đầu server
void TCPServer::start()
{
// Initialze winsock
WSADATA wsData;
WORD ver = MAKEWORD(2, 2);
int wsOk = WSAStartup(ver, &wsData);
// Create a socket
SOCKET listening = socket(AF_INET, SOCK_STREAM, 0);
// Bind the ip address and port to a socket
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(_port);
hint.sin_addr.S_un.S_addr = INADDR_ANY; // Could also use inet_pton ....
bind(listening, (sockaddr*)&hint, sizeof(hint));
// Tell Winsock the socket is for listening
listen(listening, SOMAXCONN);
cout << "Listening at port " << _port << endl;
// Wait for a connection
while (true)
{
sockaddr_in client;
int clientSize = sizeof(client);
SOCKET clientSocket = accept(listening, (sockaddr*)&client, &clientSize);
char host[NI_MAXHOST]; // Client's remote name
char service[NI_MAXSERV]; // Service (i.e. port) the client is connect on
ZeroMemory(host, NI_MAXHOST); // same as memset(host, 0, NI_MAXHOST);
ZeroMemory(service, NI_MAXSERV);
if (getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0)
{
cout << host << " connected on port " << service << endl;
}
else
{
inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST);
cout << host << " connected on port " <<
ntohs(client.sin_port) << endl;
}
vector<char> data(4096);
char* buf = data.data();
ZeroMemory(buf, 4096);
// Wait for client to send data
int bytesReceived = recv(clientSocket, buf, 4096, 0);
data.resize(bytesReceived);
// Xử lý dữ liệu
vector<char> response = handle_request(data);
// Send message back to client
send(clientSocket, response.data(), response.size(), 0);
// Close the socket
closesocket(clientSocket);
}
}
// Xử lý request từ client (cài đặt chi tiết ở các class kế thừa)
std::vector<char> TCPServer::handle_request(std::vector<char> data)
{
return data;
}
| true |
637e5e89db7e9dd1bd3b47f0e6dd221b6ab9de56 | C++ | Hecrecerelle/hello-world | /cpoint.cpp | WINDOWS-1252 | 223 | 2.859375 | 3 | [] | no_license | #include "cpoint.h"
cpoint::cpoint(int x1,int y1)
{
x=x1;
y=y1;
}
cpoint::cpoint(cpoint &obj)//캯
{
x=obj.x;
y=obj.y;
}
int cpoint::getx(void)
{
return x;
}
int cpoint::gety(void)
{
return y;
}
| true |
a13b8012a8128e5973e7ecb9ef15f926958ca2b1 | C++ | buptrh/leetcode | /Round1/592.Fraction Addition and Subtraction.cpp | UTF-8 | 4,285 | 3.546875 | 4 | [] | no_license | // Given a string representing an expression of fraction addition and subtraction, you need to return the calculation result in string format. The final result should be irreducible fraction. If your final result is an integer, say 2, you need to change it to the format of fraction that has denominator 1. So in this case, 2 should be converted to 2/1.
// Example 1:
// Input:"-1/2+1/2"
// Output: "0/1"
// Example 2:
// Input:"-1/2+1/2+1/3"
// Output: "1/3"
// Example 3:
// Input:"1/3-1/2"
// Output: "-1/6"
// Example 4:
// Input:"5/3+1/3"
// Output: "2/1"
// Note:
// The input string only contains '0' to '9', '/', '+' and '-'. So does the output.
// Each fraction (input and output) has format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.
// The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1,10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.
// The number of given fractions will be in the range [1,10].
// The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.
//not finished in contest
class Solution {
public:
std::vector<std::string> split(const std::string& s, const std::string& delim)
{
std::vector<std::string> elems;
size_t pos = 0;
size_t len = s.length();
size_t delim_len = delim.length();
if (delim_len == 0) return elems;
while (pos < len)
{
int find_pos = s.find(delim, pos);
if (find_pos < 0)
{
elems.push_back(s.substr(pos, len - pos));
break;
}
elems.push_back(s.substr(pos, find_pos - pos));
pos = find_pos + delim_len;
}
// elems.push_back(s.substr(pos, len-pos));
return elems;
}
string& replace_all(string& str,const string& old_value,const string& new_value)
{
int pos = 0;
while(true) {
pos=str.find(old_value, pos);
if( pos >= 0 ) {
str.replace(pos,old_value.length(),new_value);
} else {
break;
}
pos += old_value.length() + 1;
}
return str;
}
int maximumCommonDevisor(int a, int b) {
int ret = 0;
while(a != 0) {
if(b <= 0) {
b = -b;
}
if(a <= 0) {
a = -a;
}
b = b % a;
ret = a;
swap(a, b);
}
return ret;
}
string fractionAddition(string expression) {
expression = replace_all(expression, "-", "+-");
// cout<<expression<<endl;
int a = 0, b = 1;
vector<string> words = split(expression, "+");
bool minus = false;
// cout<<"~~" << words.size() << " " << words[0] << " " << words[1] << " " << words[2] <<endl;
for(int i = 0; i < words.size(); i++ ) {
if(words[i][0] == '-') {
minus = true;
} else {
minus = false;
}
vector<string> letters = split(words[i], "/");
if(letters.size() < 2 ) {
continue;
}
int num1 = std::atoi(letters[0].c_str() );
int num2 = std::atoi(letters[1].c_str() );
// cout<<"!!!"<<a<<" " << b <<" "<<num1 << " " << num2<<endl;
a = a * num2 + num1 * b;
b = b * num2;
}
// cout<<"final" << a<<" " << b <<endl;
int devisor = maximumCommonDevisor(a, b);
if(devisor != 0) {
a = a / devisor;
b = b / devisor;
} else {
a = 0; b = 1;
}
string ret = "";
minus = false;
if(a != 0 && a / abs(a) != b / abs(b) ) {
minus = true;
}
if(minus) {
ret = "-";
}
ret = ret + to_string(abs(a)) + "/" + to_string(abs(b));
// std::sprintf(ret, "%s%d/%d", ret, abs(a), abs(b));
return ret;
}
}; | true |
208ff22ab01d6bf4462682569b01b084d7b870de | C++ | taichunmin/uva | /AC/10302.cpp | UTF-8 | 177 | 2.59375 | 3 | [] | no_license | #include<iostream>
#include<cmath>
using namespace std;
int main()
{
long long a;
while(cin>>a)
{
long long b=(a*(a+1))/2;
cout<<b*b<<endl;
}
}
| true |
5a60e0e9d1dd57fc1708d9fbf9d464539e26e236 | C++ | DarkShadowM/InterviewBit-Topicwise-Solutions | /Arrays/Rearrange the array.cpp | UTF-8 | 1,295 | 3.453125 | 3 | [] | no_license | void rearrangeUtil(vector<int> &arr, int n, int i)
{
// 'val' is the value to be stored at 'arr[i]'
int val = -(i+1); // The next value is determined
// using current index
i = arr[i] - 1; // The next index is determined
// using current value
// While all elements in cycle are not processed
while (arr[i] > 0)
{
// Store value at index as it is going to be
// used as next index
int new_i = arr[i] - 1;
// Update arr[]
arr[i] = val;
// Update value and index for next iteration
val = -(i + 1);
i = new_i;
}
}
vector<int> Solution::solve(vector<int> &arr)
{
int n = arr.size();
int i;
for (i=0; i<n; i++)
arr[i]++;
// Process all cycles
for (i=0; i<n; i++)
{
// Process cycle starting at arr[i] if this cycle is
// not already processed
if (arr[i] > 0)
rearrangeUtil(arr, n, i);
}
// Change sign and values of arr[] to get the original
// values back, i.e., values in range from 0 to n-1
for (i=0; i<n; i++)
arr[i] = (-arr[i]) - 1;
return arr;
}
| true |
d9281379c21a5eb55444dcad9820eb4ffaeda16a | C++ | suzannealdrich/cs143-pp1-lexical-analysis | /declaration.cc | UTF-8 | 738 | 3.21875 | 3 | [] | no_license | /* File: declaration.cc
* --------------------
* Implementation of Declaration class.
*
* pp1: You need to fill in the class implementation and define
* additional member data/functions as needed. See declaration.h
* for comments.
*/
#include "declaration.h"
#include "utility.h"
Declaration::Declaration(char *ident, int lineFound)
{
name = CopyString(ident);
firstLine = lineFound;
numOccurrences = 1;
}
Declaration::~Declaration()
{
free(name);
}
void Declaration::IncrementOccurrences()
{
numOccurrences = numOccurrences + 1;
}
void Declaration::Print()
{
printf("(%s seen %d time(s), first on line %d)\n", name, numOccurrences, firstLine);
}
char * Declaration::GetName()
{
return name;
}
| true |
7f3bc092ae0a3c4619ebffcb14b498506f4842a5 | C++ | Kwon770/icon_c_lesson | /mentor/1108_mission_solution.cpp | UTF-8 | 931 | 3.546875 | 4 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int mission1() {
int arr[5] = {1, 2, 3, 4, 5};
int* ptr;
ptr = arr;
for (int i = 0; i < 5; i++) {
ptr[i] = ptr[i] + 2;
printf("%d\n", ptr[i]);
}
return 0;
}
int mission2() {
int size, temp, sum = 0;
int* ptr;
scanf("%d", &size);
ptr = (int*)malloc(size * sizeof(int));
for (int i = 0; i < size; i++) {
scanf("%d", temp);
ptr[i] = temp;
sum += temp;
}
printf("%d", sum);
free(ptr);
return 0;
}
int mission3() {
int arr[5] = {1, 2, 3, 4, 5};
int* p;
p = arr;
// 2 = 5 / 2 (배열 크기에서 / 2 한 만큼만 교체하면 배열이 뒤집어짐)
for (int i = 0; i < 2; i++) {
int temp = p[i];
p[i] = p[4 - i];
p[4 - i] = temp;
}
for (int i = 0; i < 5; i++) {
printf("%d", p[i]);
}
} | true |
492456ca81f2f00cb079971aaf300b9db38ce350 | C++ | pawellazicki/C_Homework | /sem 1/7.12/main.cpp | UTF-8 | 379 | 2.90625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
float row(float a,float b,float c,float x)
{
return a*x*x+b*x+c;
}
int main()
{
float a,b,c,x;
printf("podaj a=");
scanf("%f", &a);
printf("podaj b=");
scanf("%f", &b);
printf("podaj c=");
scanf("%f", &c);
printf("podaj x=");
scanf("%f", &x);
printf("wynik=%f", row(a,b,c,x));
return 0;
}
| true |
254f0d6e8144bf40b0425d20482fa732e8970b78 | C++ | barbaric1/cppcourse-brunel | /neuron.cpp | UTF-8 | 4,497 | 2.765625 | 3 | [] | no_license | #include "neuron.hpp"
#include <vector>
#include <cmath>
#include <iostream>
#include <random>
#include <cassert>
using namespace std;
/*! \brief All the constants used to make Neuron work.
*
* The first two constants are the ones to change if we wish to obtein a different graph.
**/
const double VARIABLE_RATIO = 2;
const double INHIBITORY_STRENGHT = 5;
const double STANDARD_MEMBRANE_POT = 20;
const double REFRACTORY_TIME = 20;
const double SIGNAL_BUFFER = 15;
const double MEMBRANE_TIME_CONSTANT_TAU = 200;
const double MEMBRANE_RESISTENCE = 20;
const double CONSTANT_J = 0.1;
const int NUMBER_NEURONS = 12500;
const int NUMBER_NEURONS_CONNECTED = 0.8 * NUMBER_NEURONS;
const int NUMBER_NEURONS_CONNECTED_EXCITATORY = 0.1 * NUMBER_NEURONS_CONNECTED;
const int NUMBER_NEURONS_CONNECTED_INHIBITORY = 0.25 * NUMBER_NEURONS_CONNECTED_EXCITATORY;
const double Vthr = STANDARD_MEMBRANE_POT/(CONSTANT_J * NUMBER_NEURONS_CONNECTED_EXCITATORY * MEMBRANE_TIME_CONSTANT_TAU);
const double Vext = Vthr * VARIABLE_RATIO;
Neuron::Neuron()
: membranePotential(0), current(0), neuronIsRefractory(false), neuronWaiting(0), buffer(16,0), bufferCounter(0), inhibitoryNeuron(true), target(0) {}
/** membrnePotential: the membrane potential of the Neuron.
* current: the external current input (this parameter is obsolete once we have a neural network).
* neuronIsRefractory: a bool that tells us if the Neuron is in a spiking state or not (if false, the neuron isn't spiking).
* neuronWaiting: a counter that keeps the Neuron actionless for some time after a spike occured.
* buffer: a vector that simulates our irng buffer.
* bufferCounter: a counter that helps us to move in our ring buffer every step of the simulation.
* inhibitoryNeuron: a bool that tells us if our Neuron in the Network is inhibitory or not.
* target: a vector that collects all the Neurons that are connected to our Neuron.
**/
void Neuron::update()
{
static random_device rd;
static mt19937 gen(rd());
poisson_distribution<int> poisson(Vext * NUMBER_NEURONS_CONNECTED_EXCITATORY);
/** We want first to know if our Neuron is in a refractory state or not.
**/
if (neuronWaiting < 0)
{
setNeuronIsRefractory(false);
}
else
{
if(getMembranePot() > STANDARD_MEMBRANE_POT)
{
setNeuronIsRefractory(true);
setMembranePot(0);
/** This attribute grants us that our neuron will wait for exactly 20 steps of simulation after a spike without being able
* to spike again.
**/
neuronWaiting = -REFRACTORY_TIME - 1;
}
else
{
setMembranePot((exp((-1)*(1/MEMBRANE_TIME_CONSTANT_TAU))* getMembranePot()) + (getCurrent() * MEMBRANE_RESISTENCE * (1 - exp((-1)*(1/MEMBRANE_TIME_CONSTANT_TAU)))) + (buffer[bufferCounter] + poisson(gen)) * CONSTANT_J);
}
}
bufferCounter += 1;
neuronWaiting += 1;
/** Condition necessary to navigate through our ring buffer and avoid Segmentations Faults.
**/
if (bufferCounter > 14)
{
bufferCounter = 0;
}
/** Every time that one step ends, we have to empty our buffer ring vector.
**/
buffer[bufferCounter] = 0;
}
void Neuron::receive(int buf)
{
/** To be sure to avoid Segmentation Faults, we put this condition in our method
**/
if (bufferCounter == 0)
{
buffer[SIGNAL_BUFFER - 1] +=1;
}
/** Once we are sure to avoid Segmentations Faults, we write on our buffer ring when a spike occured.
**/
else
{
buffer[buf -1] += 1;
}
}
void Neuron::receiveNeg(int buf)
{
if (bufferCounter == 0)
{
buffer[SIGNAL_BUFFER - 1] -= INHIBITORY_STRENGHT;
}
else
{
buffer[buf - 1] -= INHIBITORY_STRENGHT;
}
}
void Neuron::addTarget(Neuron* neuron)
{
/** This assert grants us that our simulation will not run if the pointer to a Neuron that we add is equal to nullptr.
**/
assert(neuron != nullptr);
target.push_back(neuron);
}
void Neuron::setMembranePot(double m)
{
membranePotential = m;
}
double Neuron::getMembranePot()
{
return membranePotential;
}
void Neuron::setCurrent(double c)
{
current = c;
}
double Neuron::getCurrent()
{
return current;
}
void Neuron::setNeuronIsRefractory(bool a)
{
neuronIsRefractory = a;
}
bool Neuron::getNeuronIsRefractory()
{
return neuronIsRefractory;
}
vector<Neuron*> Neuron::getTarget()
{
return target;
}
void Neuron::setInhibitoryState(bool i)
{
inhibitoryNeuron = i;
}
bool Neuron::getInhibitoryState()
{
return inhibitoryNeuron;
}
int Neuron::getBufferTime()
{
return bufferCounter;
}
| true |
c94e52bc44d60f0bbaa1d17e86fc9b792ba9e501 | C++ | travelbeeee/ProblemSolving | /Programmers/N-Queen.cpp | UTF-8 | 1,240 | 3.203125 | 3 | [] | no_license | #include <string>
#include <vector>
using namespace std;
int answer;
bool visited[12][12];
bool isCanPutQueen(int row, int col, int n) {
// visited[row][col] 에 Queen을 놓을 수 있는지!
// 위아래 체크
for (int i = 0; i < n; i++)
if (visited[i][col] && i != row) return false;
// 위 좌, 우측 대각선 체크
for (int i = 0; i < row; i++){
if (col - (row - i) >= 0 && visited[i][col - (row - i)]) return false;
if (col + (row - i) < n && visited[i][col + (row - i)]) return false;
}
// 아래 좌, 우측 대각선 체크
for (int i = row + 1; i < n; i++) {
if (col - (i - row) >= 0 && visited[i][col - (i - row)]) return false;
if (col + (i - row) < n && visited[i][col + (row - i)]) return false;
}
return true;
}
void backtracking(int row, int n) {
if (row == n) {
answer++;
return;
}
for (int j = 0; j < n; j++) {
if (isCanPutQueen(row, j, n)) { // visited[row][j] 에 Queen을 놓을 수 있다면!
visited[row][j] = true;
backtracking(row + 1, n);
visited[row][j] = false;
}
}
}
int solution(int n) {
backtracking(0, n);
return answer;
}
| true |
57b325c8960838c3caffe54faa96fa7e3a47f0f4 | C++ | Xilinx/Vitis_Libraries | /data_analytics/L1/include/hw/xf_data_analytics/text/editDistance.hpp | UTF-8 | 7,525 | 2.546875 | 3 | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | /*
* Copyright (C) 2019-2022, Xilinx, Inc.
* Copyright (C) 2022-2023, Advanced Micro Devices, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file editDistance.hpp
* @brief Implementation for Levenshtein distance to quantify how dissimilar two strings.
*
* This editDistance output one stream to indicate each edit distance of each input string against one query string
* based on diagonal approach.
*/
#ifndef XF_TEXT_EDIT_DISTANCE_H
#define XF_TEXT_EDIT_DISTANCE_H
#include "ap_int.h"
#include "hls_stream.h"
#ifndef __SYNTHESIS__
#include <iostream>
#endif
namespace xf {
namespace data_analytics {
namespace text {
namespace internal {
/**
* @brief compute one step against diagonal line
*
* @param pattern_string shifted input string
* @param input_string input query string
* @param northwest cache bits at northwest direction
* @param north cache bits at north direction
* @param west cache bits at west direction
*
*/
template <int N, int BITS>
void compute_ed(char pattern_string[N], // must be shifted
char input_string[N],
ap_uint<BITS> northwest[N],
ap_uint<BITS> north[N],
ap_uint<BITS> west[N]) {
#pragma HLS inline
for (int i = N - 1; i >= 0; i--) { // Remove the dependence
#pragma HLS unroll
const char ichar = input_string[i];
const char pchar = pattern_string[i];
const ap_uint<BITS> nw_value =
(pchar != ichar && (northwest[i] <= (ap_uint<BITS>)-2)) ? (ap_uint<BITS>)(northwest[i] + 1) : northwest[i];
const ap_uint<BITS> n_value = (north[i] > (ap_uint<BITS>)-2) ? north[i] : (ap_uint<BITS>)(north[i] + 1);
const ap_uint<BITS> w_value = (west[i] > (ap_uint<BITS>)-2) ? west[i] : (ap_uint<BITS>)(west[i] + 1);
if (nw_value <= n_value && nw_value <= w_value) { // north west
northwest[i] = north[i];
west[i] = nw_value;
north[i] = nw_value;
} else if (n_value <= w_value) { // north
northwest[i] = north[i];
west[i] = n_value;
north[i] = n_value;
} else { // west
northwest[i] = north[i];
west[i] = w_value;
north[i] = w_value;
}
}
}
/**
* @brief left shift one string toward the LSB char, with feeding the MSB char with given char
*
* @param in_char input char to fill the MSB location
* @param str input string
*
*/
template <int N>
void char_shift(char in_char, char str[N]) {
#pragma HLS inline
for (int i = 1; i < N; i++) {
#pragma HLS unroll
str[i - 1] = str[i];
}
str[N - 1] = in_char;
}
/**
* @brief circular left shifter, each call will move one char for two input string independently
*
* @param northwest input string 1
* @param west input string 2
*
*/
template <int N, int BITS>
void left_shift(ap_uint<BITS> northwest[N], ap_uint<BITS> west[N]) {
#pragma HLS inline
ap_uint<8> nw0 = northwest[0];
ap_uint<8> w0 = west[0];
for (int i = 1; i < N; i++) {
#pragma HLS unroll
northwest[i - 1] = northwest[i];
west[i - 1] = west[i];
}
northwest[N - 1] = nw0;
west[N - 1] = w0;
}
} // namespace internal
/**
* @brief Levenshtein distance implementation
*
* @tparam N maximum length of query string.
* @tparam M maximum length of input stream string, N must be less than M.
* @tparam BITS data width of internal edit distance in bits.
*
* @param len1_strm length of the query string in bytes.
* @param query_strm the query string folded into mutiple 8B elements.
* @param len2_strm length of each input string in bytes.
* @param input_strm input strings to compute edit distance against the given query string, which is folded into
* multiple 8B elements.
* @param max_ed_strm the maximum threshold of edit distance.
* @param i_e_strm end flag of input_strm and max_ed_strm.
* @param o_e_strm end flag of output matched stream.
* @param o_match_strm only the calculated ED less than threshold in max_ed_strm will be TRUE.
*
*/
template <int N, int M, int BITS>
void editDistance(hls::stream<ap_uint<BITS> >& len1_strm,
hls::stream<ap_uint<64> >& query_strm,
hls::stream<ap_uint<BITS> >& len2_strm,
hls::stream<ap_uint<64> >& input_strm,
hls::stream<ap_uint<BITS> >& max_ed_strm,
hls::stream<bool>& i_e_strm,
hls::stream<bool>& o_e_strm,
hls::stream<bool>& o_match_strm) {
ap_uint<BITS> north[N];
#pragma HLS ARRAY_PARTITION variable = north complete dim = 1
ap_uint<BITS> west[N];
#pragma HLS ARRAY_PARTITION variable = west complete dim = 1
ap_uint<BITS> northwest[N];
#pragma HLS ARRAY_PARTITION variable = northwest complete dim = 1
char str1[N], str3[N];
#pragma HLS ARRAY_PARTITION variable = str1 complete dim = 1
#pragma HLS ARRAY_PARTITION variable = str3 complete dim = 1
char str2[M];
#pragma HLS ARRAY_PARTITION variable = str2 complete dim = 1
const int fold_num = (8 * M + 63) / 64;
// read the query string
const ap_uint<BITS> len1 = len1_strm.read();
for (int i = 0; i < fold_num; i++) {
ap_uint<64> str1_part = query_strm.read();
for (int j = 0; j < 8; j++) {
#pragma HLS unroll
if (i * 8 + j < N) str1[i * 8 + j] = str1_part(j * 8 + 7, j * 8);
}
}
bool last = i_e_strm.read();
while (!last) {
// initialize the cache lines
northwest[N - 1] = 0;
north[N - 1] = 1;
west[N - 1] = 1;
for (int i = 0; i < N - 1; i++) {
#pragma HLS unroll
northwest[i] = (ap_uint<BITS>)-1;
north[i] = (i == 0) ? (ap_uint<BITS>)1 : (ap_uint<BITS>)-1;
west[i] = (i == N - 2) ? (ap_uint<BITS>)1 : (ap_uint<BITS>)-1;
}
for (int i = 0; i < N; i++) {
#pragma HLS unroll
str3[i] = 255;
}
// read one input string to compute the distance against the query string
const ap_uint<BITS> len2 = len2_strm.read();
ap_uint<BITS> med = max_ed_strm.read();
for (int i = 0; i < fold_num; i++) {
ap_uint<64> str2_part = input_strm.read();
for (int j = 0; j < 8; j++) {
#pragma HLS unroll
if (i * 8 + j < M) str2[i * 8 + j] = str2_part(j * 8 + 7, j * 8);
}
}
ED_CORE_LOOP:
for (unsigned short i = 0; i < len1 + len2 - 1; i++) {
#pragma HLS pipeline
internal::char_shift<N>(str2[M - 1 - i], str3);
internal::compute_ed<N, BITS>(str3, str1, northwest, north, west);
internal::left_shift<N, BITS>(northwest, west);
}
ap_uint<BITS> ed = north[N - len1]; // edit distance is at the last element
o_match_strm.write(ed <= med);
o_e_strm.write(false);
last = i_e_strm.read();
}
o_e_strm.write(true);
}
} // namespace text
} // namespace data_analytics
} // namespace xf
#endif // XF_TEXT_EDIT_DISTANCE_H
| true |
e2e97123ebe1e5d3481770782c28b10f1dfc9456 | C++ | evanmiller067/cs260 | /assignments/housing/familymgr.cpp | UTF-8 | 651 | 3.0625 | 3 | [] | no_license | #include "familymgr.h"
#include <iostream>
using namespace std;
familymgr::familymgr(): table(7877)
{}
void familymgr::addFamily(const family& f)
{
table.insert(f.getID(), f);
}
void familymgr::printAllFamilies()
{
table.dumpTable();
}
void familymgr::printSmallCircle(const char* id)
{
cout << "Printing family and imediate friends " << id << endl;
cout << "== Family ==" << endl;
family* f = table.lookup(id);
cout << *f << endl;
cout << "== Friends (1 level) ==" << endl;
char** friendsList = f->getFriends();
for(int i = 0; i < f->getNumberOfFriends(); i++)
{
family* fr = table.lookup(friendsList[i]);
cout << *fr << endl;
}
}
| true |
840c07a1bd0786d26fdd2e4b31940538fdad2c8d | C++ | ZarkianMouse/Initial-programming | /Programming (1st, 2nd semesters)/CodeBlocks Assignments/Project 3/checkOpen.hpp | UTF-8 | 561 | 3.078125 | 3 | [] | no_license | #ifndef CHECKOPEN_HPP_INCLUDED
#define CHECKOPEN_HPP_INCLUDED
// checkOpen is used to determine if input file
// could be successfully opened in program
// precondition: is passed input file by reference
// postcondition: returns false if input file failure
// returns true otherwise
bool checkOpen(std::ifstream& inputFile)
{
if(!inputFile)
{
std::cerr << "File Open Failure\n";
return false;
}
else
{
std::cout << "Successful Open!\n";
return true;
}
}
#endif // CHECKOPEN_HPP_INCLUDED
| true |
09f525506d7c68452f609258b46dfa30c104d5a1 | C++ | nimbuscontrols/EIPScanner | /src/sockets/BaseSocket.h | UTF-8 | 1,548 | 2.65625 | 3 | [
"MIT"
] | permissive | //
// Created by Aleksey Timin on 11/18/19.
//
#ifndef EIPSCANNER_SOCKETS_BASESOCKET_H
#define EIPSCANNER_SOCKETS_BASESOCKET_H
#include <vector>
#include <cstdint>
#include <string>
#include <chrono>
#include <functional>
#include <memory>
#include <system_error>
#include "EndPoint.h"
namespace eipScanner {
namespace sockets {
class BaseSocket {
public:
using BeginReceiveHandler = std::function<void(BaseSocket&)>;
using SPtr = std::shared_ptr<BaseSocket>;
using UPtr = std::unique_ptr<BaseSocket>;
explicit BaseSocket(EndPoint endPoint);
BaseSocket(std::string host, int port);
virtual ~BaseSocket();
virtual void Send(const std::vector<uint8_t>& data) const = 0;
virtual std::vector<uint8_t> Receive(size_t size) const = 0;
void setBeginReceiveHandler(BeginReceiveHandler handler);
const std::chrono::milliseconds &getRecvTimeout() const;
void setRecvTimeout(const std::chrono::milliseconds &recvTimeout);
int getSocketFd() const;
static int getLastError();
static const std::error_category& getErrorCategory() noexcept;
const EndPoint &getRemoteEndPoint() const;
static void select(std::vector<BaseSocket::SPtr> sockets, std::chrono::milliseconds timeout);
protected:
void BeginReceive();
void Shutdown();
void Close();
int _sockedFd;
EndPoint _remoteEndPoint;
std::chrono::milliseconds _recvTimeout;
BeginReceiveHandler _beginReceiveHandler;
static timeval makePortableInterval(const std::chrono::milliseconds &recvTimeout);
};
}
}
#endif // EIPSCANNER_SOCKETS_BASESOCKET_H
| true |
f5548301e0e81b74980c77b0c6e55ffa2c67018f | C++ | EcutDavid/oj-practices | /leetcode/1051.cpp | UTF-8 | 305 | 2.65625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int heightChecker(vector<int>& heights) {
vector<int> cp = heights;
sort(cp.begin(), cp.end());
int ret = 0;
for (int i = 0; i < cp.size(); i++) {
if (cp[i] != heights[i]) ret++;
}
return ret;
}
};
| true |
7ea79538a38117f016ebb5e936b31b0467fc22f5 | C++ | TheRedLady/Data-Structures-Pract | /Final Projects/81368/Huffman_Coding/HuffmanDecoder.cpp | UTF-8 | 2,173 | 2.75 | 3 | [] | no_license | #include "BTree.h"
#include "HuffmanDecoder.h"
void HuffmanDecoder::decode(ifstream &tableCode, ifstream &codeFile, ofstream &decodeFile){
map<char, int>table;
vector<string> readedCharacters;
string str = "";
char characterToRead;
bool chekFor = true;
while (tableCode.get(characterToRead)){
if (characterToRead == '#' && chekFor){
readedCharacters.push_back(str);
str.clear();
chekFor = false;
}
else{
str = str + characterToRead;
chekFor = true;
}
}
tableCode.close();
for (int i = 0; i < readedCharacters.size() - 1; i += 2){
char key = readedCharacters[i][0];
int value = stoi(readedCharacters[i + 1], 0, 10);
table[key] = value;
}
BTree tree(table);
char charToRead;
char symbol;
codeFile.seekg(-1, codeFile.end);
char bitsToRead;
codeFile.get(bitsToRead);
int fileLengthInBytes = codeFile.tellg();
codeFile.clear();
codeFile.seekg(0, ios::beg);
for(int i =0;i<fileLengthInBytes-2;i++)
{
codeFile.get(charToRead);
for (int i = 7; i >= 0; --i)
{
char bit = (((charToRead >> i) & 1) + 48);
if (tree.consumeSymbol(bit, symbol))
{
decodeFile << symbol;
}
}
}
codeFile.get(charToRead);
for(int i =7;bitsToRead!=0;i--,bitsToRead--)
{
char bit = (((charToRead >> i) & 1) + 48);
if (tree.consumeSymbol(bit, symbol))
{
decodeFile << symbol;
}
}
decodeFile.close();
codeFile.close();
}
HuffmanDecoder::HuffmanDecoder(){};
void HuffmanDecoder:: decode(){
string codeTablePath;
string codeFilePath;
string decodeFilePath;
cout << "Please enter a file of the table:\n";
cin >> codeTablePath;
cout << "Please enter a file of the code:\n";
cin >> codeFilePath;
cout << "Please enter a file for the decode:\n";
cin >> decodeFilePath;
ifstream codeTable(codeTablePath.c_str(), std::ifstream::in | std::ifstream::binary);
ifstream codeFile(codeFilePath.c_str(), std::ifstream::in | std::ifstream::binary);
ofstream decodeFile(decodeFilePath.c_str(), std::ofstream::out | std::ofstream::binary);
decode(codeTable, codeFile, decodeFile);
}
| true |
c664836c8028ed710bb3d2d44ce964e03b269b48 | C++ | shadercoder/RenderMaster | /GameEngine/Source/Renderer/Cameras/Camera.h | UTF-8 | 4,764 | 2.71875 | 3 | [] | no_license | #pragma once
#include "../../Math/Vector.h"
#include "../../Math/Matrix.h"
#include "../../Math/Geometry/Frustum.h"
#include "../../Graphics/Other/Viewport.h"
class Entity;
class Camera
{
protected:
/**
View and Projection matrices
**/
Mat4x4 m_view;
Mat4x4 m_prevView;
Mat4x4 m_projection;
Mat4x4 m_prevProj;
Mat4x4 m_viewProj;
Mat4x4 m_orthoProj;
bool m_bVPRecalc;
bool m_bOrthoRecalc;
/**
General Data
**/
Vec m_pos; //position
Vec m_dir; //direction of the camera
Vec m_initialDir;
Vec m_lookAt; //point camera is looking at
Vec m_up; //direction of up vector
float m_yaw;
float m_pitch;
float m_roll;
/**
Projection Data
**/
Frustum m_frustum;
//Viewport to render to
Viewport m_viewport;
/**
Other Data
**/
bool m_bActive;
bool m_bDebug;
/** ===============================
Methods
=============================== **/
void UpdateTransforms();
//Target camera is following
shared_ptr<Entity> m_pTarget;
bool m_bHasTarget;
public:
//Constructor and destructor
Camera(const Frustum & frustum, const Vec & position, const Vec & dir,
const Vec & up, const Viewport & viewport);
/*==
Mutators
==*/
void SetActive(bool isActive);
void SetPosition(const Vec & pos);
void SetLookAt(const Vec & lookAt);
void SetDir(const Vec & dir);
void SetRoll(float roll);
void SetPitch(float pitch);
void SetYaw(float yaw);
void SetTarget(shared_ptr<Entity> pTarget);
/*==
Accessors
==*/
bool IsActive() const;
//AVIRTUAL HRESULT SetViewTransform(Scene *pScene);
const Frustum &GetFrustum();
const Mat4x4 & GetProjection() const;
const Mat4x4 & GetView() const;
const Mat4x4 & GetViewProjection();
const Mat4x4 & GetPrevView() const;
const Mat4x4 & GetPrevProjection() const;
const Mat4x4 & GetOrthoProjection();
Vec GetPosition() const;
Vec GetLookAt() const;
Vec GetDir() const;
float GetRoll() const;
float GetPitch() const;
float GetYaw() const;
float GetNearZ() const;
float GetFarZ() const;
float GetViewportWidth() const;
float GetViewportHeight() const;
shared_ptr<Entity> GetTarget() const;
bool HasTarget() const;
/*==
Methods
==*/
virtual void VUpdate(unsigned int elapsedMs);
__forceinline void BindViewport();
};
__forceinline void Camera::SetActive(bool isActive)
{
m_bActive = isActive;
}
__forceinline void Camera::SetPosition(const Vec & pos)
{
m_pos = pos;
}
__forceinline void Camera::SetLookAt(const Vec & lookAt)
{
m_lookAt = lookAt;
}
__forceinline void Camera::SetDir(const Vec & dir)
{
m_dir = dir;
}
__forceinline void Camera::SetRoll(float roll)
{
m_roll = roll;
}
__forceinline void Camera::SetPitch(float pitch)
{
m_pitch = pitch;
}
__forceinline void Camera::SetYaw(float yaw)
{
m_yaw = yaw;
}
__forceinline void Camera::SetTarget(shared_ptr<Entity> pTarget)
{
if (pTarget)
{
m_bHasTarget = true;
}
else
{
m_bHasTarget = false;
}
m_pTarget = pTarget;
}
__forceinline bool Camera::IsActive() const
{
return m_bActive;
}
__forceinline const Frustum & Camera::GetFrustum()
{
return m_frustum;
}
__forceinline const Mat4x4 & Camera::GetProjection() const
{
return m_projection;
}
__forceinline const Mat4x4 & Camera::GetView() const
{
return m_view;
}
__forceinline const Mat4x4 & Camera::GetViewProjection()
{
//if (!m_bVPRecalc)
//{
m_viewProj = m_view * m_projection;
// m_bVPRecalc = true;
//}
return m_viewProj;
}
__forceinline const Mat4x4 & Camera::GetPrevView() const
{
return m_prevView;
}
__forceinline const Mat4x4 & Camera::GetPrevProjection() const
{
return m_prevProj;
}
__forceinline const Mat4x4 & Camera::GetOrthoProjection()
{
//if (!m_bOrthoRecalc)
//{
m_orthoProj = Mat4x4::CreateOrthoProjectionLH(SCREEN_WIDTH, SCREEN_HEIGHT, m_frustum.GetNearZ(), m_frustum.GetFarZ());
// m_bOrthoRecalc = true;
//}
return m_orthoProj;
}
__forceinline Vec Camera::GetPosition() const
{
return m_pos;
}
__forceinline Vec Camera::GetLookAt() const
{
return m_lookAt;
}
__forceinline Vec Camera::GetDir() const
{
return m_dir;
}
__forceinline float Camera::GetRoll() const
{
return m_roll;
}
__forceinline float Camera::GetPitch() const
{
return m_pitch;
}
__forceinline float Camera::GetYaw() const
{
return m_yaw;
}
__forceinline float Camera::GetNearZ() const
{
return m_frustum.GetNearZ();
}
__forceinline float Camera::GetFarZ() const
{
return m_frustum.GetFarZ();
}
__forceinline float Camera::GetViewportWidth() const
{
return m_viewport.Width;
}
__forceinline float Camera::GetViewportHeight() const
{
return m_viewport.Height;
}
__forceinline shared_ptr<Entity> Camera::GetTarget() const
{
return m_pTarget;
}
__forceinline bool Camera::HasTarget() const
{
return m_bHasTarget;
}
__forceinline void Camera::BindViewport()
{
m_viewport.Bind();
} | true |
4e32b0d0c9670cef28a48cae824e2bd5b89303d6 | C++ | jjzhang166/Eagle3D | /jni/Material.cpp | UTF-8 | 1,616 | 2.609375 | 3 | [] | no_license | #include "Material.h"
#include <Shader.h>
#include <RenderOfCamera.h>
Material::Material(){
}
void Material::AddTexture(string name,Texture texture){
textureMap[name]=texture;
}
Texture Material::GetTexture(string name){
return textureMap[name];
}
void Material::AddVector3(string name,Vector3 target){
vector3Map[name]=target;
}
Vector3 Material::GetVector3(string name){
return vector3Map[name];
}
void Material::AddFloat(string name,float target){
floatMap[name]=target;
}
float Material::GetFloat(string name){
return floatMap[name];
}
void Material::AddShader(Shader* shader){
shaderList.push_back(shader);
}
void Material::Render(Transform *trans,RenderOfCamera* renderOfCam){
for(int i=0;i<shaderList.size();i++){
shaderList[i]->Bind();
shaderList[i]->UpdateUniforms(trans,*this,renderOfCam);
}
for(textureMapIte=textureMap.begin();textureMapIte!=textureMap.end();++textureMapIte){
textureMapIte->second.Render();
}
}
void Material::Finalize(){
for(textureMapIte=textureMap.begin();textureMapIte!=textureMap.end();++textureMapIte){
textureMapIte->second.Finalize();
}
}
void Material::Pause(){
for(textureMapIte=textureMap.begin();textureMapIte!=textureMap.end();++textureMapIte){
textureMapIte->second.Pause();
}
}
void Material::Resume(){
for(textureMapIte=textureMap.begin();textureMapIte!=textureMap.end();++textureMapIte){
textureMapIte->second.Resume();
}
}
void Material::ApplicationQuit(){
for(textureMapIte=textureMap.begin();textureMapIte!=textureMap.end();++textureMapIte){
textureMapIte->second.ApplicationQuit();
}
}
| true |
956f77aedd58b242543d1b8222cf9ffbe3a19c37 | C++ | KangZehui/speed_test | /src/Addons/GeoStar/include/geomathd/nearest_finder_base.h | UTF-8 | 2,933 | 2.640625 | 3 | [] | no_license | // nearest_finder_base.h: interface for the nearest_finder_base class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_NEAREST_FINDER_BASE_H__142B17FB_7C56_4CA3_9EF4_185F0C3DAC71__INCLUDED_)
#define AFX_NEAREST_FINDER_BASE_H__142B17FB_7C56_4CA3_9EF4_185F0C3DAC71__INCLUDED_
#include "point.h"
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
struct SLIST;
class CHeap;
GEO_NAMESPACE_BEGIN
typedef double (*point_dis2_fun)(const point& pt,const void* p);
class nearest_finder_base
{
//node结构描述了一个结点
//一个结点对应一个矩形env,假如pt在env内,那么它的最近对象一定在这个node中
//node对应的矩形不保存在成员变量中,由程序在运算的时候给出
struct node
{
//两个子结点如果它们为空,那么所有可能最近对象都保存在data中,否则data必然为0
//假如this对应的矩形为env,那么child对应的矩形是env.split函数得到的两个矩形
node* child[2];
//所有可能的最近对象
SLIST* data;
//假如this对应的矩形为env,那么dis2为所有对象中和env最大距离的最小值
//如果一个对象和this对应矩形的最近距离大于dis2,那么可知这个对象不会是env中任何一个点的最近对象
float dis2;
void update_dis2();
//描述:找到包含pt的节点,返回其data
SLIST* find(const envelope& env,point pt);
};
friend struct node;
static node g_node;
envelope m_env;
node* m_root;
CHeap* m_node_heap;
CHeap* m_list_heap;
int m_deep;
//m_min_dis2是计算点或者线段和矩形最小距离的回调函数
double (*m_min_dis2)(envelope&,const void*);
//m_max_dis2是计算点或者线段和矩形最大距离的回调函数
double (*m_max_dis2)(envelope&,const void*);
//描述:取出pn->data中的数据放入A中,并且回收pn->data所占有的资源
void get_data(node* pn,std::vector<const void*>& A);
//描述:将一个数据p挂到节点pn上
void add(node* pn,envelope& env,const void* p,int deep);
//描述:将多个数据A挂到节点pn上
void n_add(node* pn,envelope& env,std::vector<const void*>& A);
public:
nearest_finder_base(
envelope env,
double (*min_dis2)(envelope&,const void*),
double (*max_dis2)(envelope&,const void*),
int deep);
~nearest_finder_base();
void add(const void* p);
const void* nearest(point pt,point_dis2_fun fun)const;
};
GEO_NAMESPACE_END
#endif // !defined(AFX_NEAREST_FINDER_BASE_H__142B17FB_7C56_4CA3_9EF4_185F0C3DAC71__INCLUDED_)
| true |
391b681a1e525c7f2750a75cdb8690eef9784229 | C++ | vicentesi/so2 | /trabalhoFinal-Vicente-Fernando-Taciane/ip_datagram_receiver.h | UTF-8 | 2,610 | 2.703125 | 3 | [] | no_license | /*
* ip_datagram_receiver.h
*
* Created on: Nov 24, 2013
* Author: vicente
*/
#ifndef IP_DATAGRAM_RECEIVER_H_
#define IP_DATAGRAM_RECEIVER_H_
// TEMPO MAXIMO DE ESPERA
#define WAIT_TIME 1000 // chronometro eh em microssegundos = 1 millis
#include "chronometer.h"
#include "ip_datagram.h"
using namespace EPOS;
class IP_Datagram_Receiver {
public:
// Enumeracao para status dos frames
enum StatusFrameReceiver
{
INCOMPLETO, COMPLETO, TEMPO_ESGOTADO
};
IP_Datagram_Receiver()
{
_somaTotal = 0;
_chronometer.start();
_tempoInicio = _chronometer.read();
_chegouUltimoFrame = false;
_datagramaCompleto = false;
}
~IP_Datagram_Receiver()
{
_chronometer.stop();
}
StatusFrameReceiver addFrame(IP_Datagram * frame)
{
_tempoFinal = _chronometer.read();
if (_tempoFinal - _tempoInicio > WAIT_TIME)
return TEMPO_ESGOTADO;
else
_tempoInicio = WAIT_TIME;
_somaTotal = _somaTotal - frame->_datagram._header->_total_length + 20; // tira 20 do cabecalho
Simple_List<IP_Datagram>::Element* element =
new Simple_List<IP_Datagram>::Element(frame);
_frames.insert(element);
// LAST FRAGMENT
if (frame->_datagram._header->_flags == false)
chegouUltimoFrame(frame);
if (_chegouUltimoFrame) {
if (_somaTotal == 0) {
_datagramaCompleto = true;
return COMPLETO;
}
}
return INCOMPLETO;
}
char* getDatagramaDataCompleto()
{
if (!_datagramaCompleto)
return 0;
return montarDatagramaCompleto();
}
private:
// METODO QUE VERIFICA SE CHEGOU O ULTIMO FRAGMENTO
void chegouUltimoFrame(IP_Datagram * frame)
{
_tamanhoTotal = (frame->_datagram._header->_frag_offset * 8) // numero se sequencia (offset)
+ frame->_datagram._header->_total_length - 20;
_somaTotal += _tamanhoTotal;
_chegouUltimoFrame = true;
}
char* montarDatagramaCompleto()
{
char* datagramaTotalData = new char[_tamanhoTotal];
for (Simple_List<IP_Datagram>::Iterator i = _frames.begin();
i != _frames.end(); i++)
{
Simple_List<IP_Datagram>::Element* datagrama =
_frames.remove_head();
// REVER ESSE TRECHO DE CODIGO, VER COMO MEMSET E MEMCOPY!!!
/*System.arraycopy(datagrama._datagram._data, 0, datagramaTotalData,
datagrama._datagram._header._frag_offset * 8,
datagrama._datagram._header._total_length - 20);*/
}
return datagramaTotalData;
}
private:
OStream _cout;
int _somaTotal;
int _tamanhoTotal;
long _tempoInicio;
long _tempoFinal;
bool _chegouUltimoFrame;
bool _datagramaCompleto;
Chronometer _chronometer;
Simple_List<IP_Datagram> _frames;
};
#endif /* IP_DATAGRAM_RECEIVER_H_ */
| true |
99e465bb50f1b0be8c0632b808dd076db347268f | C++ | uchiiii/fmm-bem-relaxed | /include/executor/P2P.hpp | UTF-8 | 2,885 | 2.84375 | 3 | [] | no_license | #pragma once
/** @file P2P.hpp
* @brief Dispatch methods for the P2P stage
*
*/
#include "Direct.hpp"
struct P2P
{
//////////////////////////////////////
/////// Static Dispatchers ///////////
//////////////////////////////////////
struct ONE_SIDED {};
struct TWO_SIDED {};
/** One sided P2P
*/
template <typename Kernel, typename Context>
inline static void eval(const Kernel& K,
Context& bc,
const typename Context::box_type& source,
const typename Context::box_type& target,
const ONE_SIDED&)
{
#ifdef DEBUG
printf("P2P: %d to %d\n", source.index(), target.index());
#endif
Direct::matvec(K,
bc.source_begin(source), bc.source_end(source),
bc.charge_begin(source),
bc.target_begin(target), bc.target_end(target),
bc.result_begin(target));
}
/** Two sided P2P
*/
template <typename Kernel, typename Context>
inline static void eval(const Kernel& K,
Context& bc,
const typename Context::box_type& source,
const typename Context::box_type& target,
const TWO_SIDED&)
{
#ifdef DEBUG
printf("P2P: %d to %d\n", source.index(), target.index());
printf("P2P: %d to %d\n", target.index(), source.index());
#endif
Direct::matvec(K,
bc.source_begin(source), bc.source_end(source),
bc.charge_begin(source), bc.result_begin(source),
bc.target_begin(target), bc.target_end(target),
bc.charge_begin(target), bc.result_begin(target));
}
/** Two sided, self P2P
*/
template <typename Kernel, typename Context>
inline static void eval(const Kernel& K,
Context& bc,
const typename Context::box_type& source)
{
#ifdef DEBUG
printf("P2P: %d to %d\n", source.index(), source.index());
#endif
Direct::matvec(K,
bc.source_begin(source), bc.source_end(source),
bc.charge_begin(source), bc.result_begin(source),
bc.target_begin(source), bc.target_end(source),
bc.charge_begin(source), bc.result_begin(source));
}
};
struct P2P_Batch {
/** Construct a P2P context on the bodies within a single box */
template <typename Context>
P2P_Batch(Context& bc,
const typename Context::box_type& b) {
// Do nothing
}
/** Construct a P2P context on the sources and targets within two boxes */
template <typename Context>
P2P_Batch(Context& bc,
const typename Context::box_type& source,
const typename Context::box_type& target) {
// Do nothing
}
inline void compute() {
// Do nothing
}
};
| true |
d84f0ac040bd4c617f51e84edceaadad00498108 | C++ | yunn0504/ycyang | /Algorithm/Algorithm/1260.cpp | UTF-8 | 1,285 | 2.890625 | 3 | [] | no_license | //1260 DFS,BFS
#include<iostream>
#include<fstream>
#include<string>
#include<queue>
#include<stack>
using namespace std;
void DFS(int, int);
void BFS(int, int);
int check(int);
void init(int);
int graph[1001][1001];
int visit[1001];
int find[1001];
stack<int> stack1;
queue<int> queue1;
int main()
{
int n, m, v;
int i, j;
int x, y;
ifstream f;
f.open("input2.txt");
cin >> n >> m >> v;
for (i = 1; i <= m; i++)
{
cin >> x >> y;
graph[x][y] = graph[y][x] = 1;
}
/*for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
cout << graph[i][j];
}
cout << endl;
}*/
DFS(v, n);
init(n);
cout << endl;
BFS(v, n);
}
void DFS(int v, int n)
{
int i;
cout << v << " ";
visit[v] = 1;
for (i = 1; i <= n; i++) {
if (graph[v][i] == 1 && visit[i] == 0)
DFS(i, n);
}
if (check(n)) return;
}
void BFS(int v, int n)
{
int i;
visit[v] = 1;
queue1.push(v);
while (!queue1.empty()) {
v = queue1.front();
queue1.pop();
for (i = 1; i <= n; i++) {
if (graph[v][i] == 1 && visit[i] == 0) {
queue1.push(i);
visit[i] = 1;
}
}
visit[v] = 2;
cout << v << " ";
}
}
int check(int n)
{
int i;
for (i = 1; i <= n; i++) {
if (visit[i] == 0)
return 0;
}
return 1;
}
void init(int n)
{
int i;
for (i = 1; i <= n; i++) {
visit[i] = 0;
}
} | true |
4e9e264884365a958f7c8e0fbcf48627329bee59 | C++ | Vipiao/HeroesOfTheCitadel | /Heroes_of_the_Citadel/Heroes_of_the_Citadel/Sphere.cpp | UTF-8 | 1,172 | 3.140625 | 3 | [] | no_license |
#include "Sphere.h"
uint64_t Sphere::m_totalNumSpheres{ 0 };
Sphere::Sphere () {
m_id = m_totalNumSpheres++;
calculateMomentOfInertia ();
}
void Sphere::calculateMomentOfInertia () {
m_momentOfInertia = 2.0 / 5.0 * m_mass * m_radius * m_radius * m_momentOfInertiaMultiplier;
}
void Sphere::setRadius (double radius) {
m_radius = radius;
calculateMomentOfInertia ();
}
void Sphere::setRadiusDensity (double radius, double density) {
m_radius = radius;
m_mass = 4.0/3.0 * glm::pi<double>() * m_radius * m_radius * m_radius * density;
calculateMomentOfInertia ();
}
double Sphere::getRadius () {
return m_radius;
}
void Sphere::setMass (double mass) {
m_mass = mass;
calculateMomentOfInertia ();
}
double Sphere::getMass () {
return m_mass;
}
void Sphere::setMomentOfInertiaMultiplier (double mm) {
m_momentOfInertiaMultiplier = mm;
calculateMomentOfInertia ();
}
double Sphere::getMomentOfInertiaMultiplier () {
return m_momentOfInertiaMultiplier;
}
glm::dvec3 Sphere::getAngVel () {
if (m_rotationVel == 0.0) {
return glm::dvec3{ 0 };
}
return glm::normalize(m_rotationAxis) * m_rotationVel;
}
| true |
de1fb3f027466b29bd1fcfafd77022c17c4d3033 | C++ | mversace/LeetCode | /LeetCode/Problems/001-050/25. Reverse Nodes in k-Group.h | GB18030 | 2,045 | 3.984375 | 4 | [] | no_license | #pragma once
/*
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
*/
class Solution25 {
private:
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
public:
static ListNode* reverseKGroup(ListNode* head, int k) {
if (k <= 1) return head;
ListNode* pResult = nullptr;
ListNode* pNode = nullptr;
ListNode* pItemHead = head;
ListNode* pItemTail = nullptr;
// תkNode
while (pItemHead)
{
pItemTail = pItemHead;
bool bEnough = true;
for (int i = 0; i < k - 1; ++i)
{
if (pItemTail->next)
{
pItemTail = pItemTail->next;
}
else
{
bEnough = false;
break;
}
}
// תpItemHeadΪͷpItemTailΪβ
if (bEnough)
{
ListNode* pPre = pItemHead;
ListNode* pNext = pItemHead->next;
pItemHead->next = pItemTail->next;
while (pPre != pItemTail)
{
/*
abc pPre = a pNext = b
to ab c pPre = b pNext = c
*/
ListNode* pData = pNext;
pNext = pNext->next;
pData->next = pPre;
pPre = pData;
}
ListNode* pTemp = pItemTail;
pItemTail = pItemHead;
pItemHead = pTemp;
}
// node
if (!pResult)
{
pResult = pItemHead;
}
else
{
pNode->next = pItemHead;
}
// pNodeֵƶpItemHead
pNode = pItemTail;
pItemHead = pItemTail->next;
}
return pResult;
}
static void test()
{
ListNode a(1);
ListNode b(2);
ListNode c(3);
a.next = &b;
b.next = &c;
reverseKGroup(&a, 2);
}
}; | true |
92b43a4f8a784b75198191bd0ef7d9c7d7fd3f6e | C++ | DrFeelgreat/Aquatorium | /rob_lab1_1/Screen.h | UTF-8 | 575 | 2.609375 | 3 | [] | no_license | #pragma once
#include <SFML/Graphics.hpp>
class Screen :public sf::Drawable, sf::Transformable
{
public:
Screen();
~Screen();
bool load(const std::string & textureFile, sf::FloatRect textureCoord, sf::Vector2u size, sf::Vector2f position);
void setMaxFrame(int frameNumber);
void nextFrame();
void visibility(bool visible);
private:
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
bool vis = true;
int animation_step = 0;
int animation_step_max = 0;
sf::FloatRect m_frameSize;
sf::VertexArray m_vertices;
sf::Texture m_texture;
}; | true |
73be3ba17e2116c0c8285e04ebb7e8b1a9ce3872 | C++ | BankC/BC2448630 | /HomeWork/Assignment 1/Savitch_8thEdition_Chap1_Prob8/main.cpp | UTF-8 | 1,011 | 3.515625 | 4 | [] | no_license | /*
* File: Chapter1 Problem 8
* Author: Bank Conway
* Created on June 26, 2014, 11:08 AM
* Purpose
*/
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
//Declare variable
unsigned short penny, nickel, dime, quarter,pamt, nkamt, damt, qramt, total;
//User interaction
cout << "Press Enter after entering the number of coins\n";
cout <<"Enter numbers of pennies\n";
cin >> penny;
cout <<"Enter numbers of nickel\n";
cin >> nickel;
cout <<"Enter numbers of dimes\n";
cin >> dime;
cout <<"Enter numbers of quarters\n";
cin >> quarter;
//Process
pamt = penny * 1; //penny calculations
nkamt = nickel * 5; //nickels calculation
damt = dime * 10; //dimes calculation
qramt = quarter * 25; //quarters calculation
total = pamt + nkamt + damt + qramt;
//output
cout <<"The total is " << total << " cents"<< endl;
//Exit
return 0;
}
| true |
2e2be33f5bd710fe0c491312f0c819a0b1cb9629 | C++ | DanNixon/CSC8503_AdvancedGameTechnologies | /Build/ncltech/Utility.cpp | UTF-8 | 3,724 | 3.421875 | 3 | [] | no_license | #include "Utility.h"
#define NOMINMAX
#include <Windows.h>
#include <algorithm>
#include <shlobj.h>
#include <sstream>
/**
* @brief Splits a string by a delimiter.
* @param str String to split
* @param delim Delimiter
* @return Vector of substrings
*/
std::vector<std::string> Utility::Split(const std::string &str, char delim)
{
std::vector<std::string> retVal;
std::stringstream ss(str);
std::string item;
while (std::getline(ss, item, delim))
{
if (!item.empty())
retVal.push_back(item);
}
return retVal;
}
/**
* @brief Joins a vector of strings on a delimiter.
* @param strings Vector of strings to join
* @param delimiter Delimiter to join on
* @return Joined string
*/
std::string Utility::Join(const std::vector<std::string> &strings, char delim)
{
std::stringstream str;
for (auto it = strings.begin(); it != strings.end(); ++it)
{
if (it != strings.begin())
str << delim;
str << *it;
}
return str.str();
}
/**
* @brief Converts a string into a string that can be a filename/path by removing whitespace and punctuation.
* @param str String to sanitize
* @return Sanitized string
*
* e.g. SanitizeFilename("Snooker Loopy!") = "SnookerLoopy"
*/
std::string Utility::SanitizeFilename(std::string str)
{
str.erase(std::remove_if(str.begin(), str.end(), [](const char &c) { return ispunct(c) || isspace(c); }), str.end());
return str;
}
/**
* @brief Coverts a string value to a boolean.
* @param str String value
* @param defaultVal If string could not be parsed this value is returned
* @return Parsed value, defaultValue if value could not be determined
*/
bool Utility::StringToBool(std::string str, bool defaultVal)
{
bool retVal = defaultVal;
// Make string lowercase
std::transform(str.begin(), str.end(), str.begin(), tolower);
// List of words that correspond to true or false
static const std::vector<std::string> trueStrs = {"1", "true", "yes", "on", "enable"};
static const std::vector<std::string> falseStrs = {"0", "false", "no", "off", "disable"};
// Test for a true value
if (std::find(trueStrs.begin(), trueStrs.end(), str) != trueStrs.end())
retVal = true;
// Test for a false value
else if (std::find(falseStrs.begin(), falseStrs.end(), str) != falseStrs.end())
retVal = false;
return retVal;
}
/**
* @brief Parses an IP address from a string.
* @param data Storage for IP address
* @param str String containing IP address
*
* Format is the standard IPv4 standard, i.e. 127.0.0.1
*/
void Utility::ParseIPAddress(uint8_t *data, const std::string &str)
{
std::vector<std::string> tokens = Split(str, '.');
for (size_t i = 0; i < 4; i++)
data[i] = std::stoi(tokens[i]);
}
/**
* @brief Creates a new diretcory tree.
* @param path Path to create
* @return True if path was created
*/
bool Utility::MakeDirectories(const std::string &path)
{
return CreateDirectory(path.c_str(), NULL) == TRUE;
}
/**
* @brief Gets a diretory in th ehome directory in which to stopre configurations and persistent data (e.g. high scores).
* @param appName Name of the game/application
* @return Directory path (empty on failure)
*/
std::string Utility::GetHomeConfigDirectory(const std::string &appName)
{
std::string directory;
WCHAR path[MAX_PATH];
char charPath[MAX_PATH];
char c = ' ';
if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, path)) &&
SUCCEEDED(WideCharToMultiByte(CP_ACP, 0, path, -1, charPath, 260, &c, NULL)))
{
std::string sanitizedName = SanitizeFilename(appName);
directory = std::string(charPath) + "\\." + sanitizedName + "\\";
}
// Ensure the directory exists
MakeDirectories(directory);
return directory;
}
| true |
c27d256c15c92813d794afc5cddf1dad458d6a57 | C++ | gutioliveira/Algorithms | /URI/1907.cpp | UTF-8 | 1,742 | 2.765625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define MAX 1025
int campo[MAX][MAX];
int A,B;
void bfs( int a, int b ){
queue < pair<int,int> >q;
q.push(make_pair(a,b));
pair <int,int> atual;
while(!q.empty()){
atual = q.front();
q.pop();
if ( atual.first - 1 > 0 && campo[atual.first-1][atual.second] != 1 ){
campo[atual.first-1][atual.second] = 1;
q.push(make_pair(atual.first-1, atual.second));
}
if ( atual.first + 1 <= A && campo[atual.first+1][atual.second] != 1 ){
campo[atual.first+1][atual.second] = 1;
q.push(make_pair(atual.first+1, atual.second));
}
if ( atual.second - 1 > 0 && campo[atual.first][atual.second-1] != 1 ){
campo[atual.first][atual.second-1] = 1;
q.push(make_pair(atual.first, atual.second-1));
}
if ( atual.second + 1 <= B && campo[atual.first][atual.second+1] != 1 ){
campo[atual.first][atual.second+1] = 1;
q.push(make_pair(atual.first, atual.second+1));
}
}
}
int main(){
int a,b;
scanf("%d %d", &A, &B);
char aux;
int conta = 0;
memset(campo, 0, sizeof(campo[0][0]) * MAX * MAX);
// for ( int i = 1 ; i <= A ; i++ ){
// printf("\n");
// for ( int j = 1 ; j <= B ; j++ ){
// printf("%d", campo[i][j]);
// }
// }
for ( int i = 1 ; i <= A ; i++ ){
for ( int j = 1 ; j <= B ; j++ ){
cin >> aux;
if ( aux == 'o' ){
campo[i][j] = 1;
}
}
}
for ( int i = 1 ; i <= A ; i++ ){
for ( int j = 1 ; j <= B ; j++ ){
if ( campo[i][j] == 0 ){
campo[i][j] = 1;
bfs(i,j);
conta++;
}
}
}
// for ( int i = 1 ; i <= A ; i++ ){
// printf("\n");
// for ( int j = 1 ; j <= B ; j++ ){
// printf("%d", campo[i][j]);
// }
// }
printf("%d\n", conta);
return 0;
} | true |
86cb27e21582c22eaeb2afafdf07f9a326a8a465 | C++ | Alecfut07/Programacion-ATS | /POO (Programacion Orientada a Objetos)/Clase Tiempo (Alec).cpp | ISO-8859-1 | 1,181 | 4.40625 | 4 | [] | no_license | /*Construya una clase Tiempo que contenga los siguientes atributos enteros:
horas, minutos y segundos. Haga que la clase contenga 2 constructores, el
primero debe tener 3 parmetros Tiempo(int, int, int) y el segundo slo tendr
un campo que sern los segundos y desensamble el nmero entero largo en horas,
minutos y segundos.*/
#include <iostream>
#include <stdlib.h>
using namespace std;
class Tiempo
{
private:
int horas, minutos, segundos;
public:
Tiempo(int, int, int);
Tiempo(long);
void mostrarTiempo();
};
Tiempo::Tiempo(int _horas, int _minutos, int _segundos)
{
horas = _horas;
minutos = _minutos;
segundos = _segundos;
}
Tiempo::Tiempo(long tiempo)
{
horas = tiempo / 3600; //Extraer horas.
tiempo %= 3600;
minutos = tiempo / 60; //Extraer minutos.
segundos = tiempo % 60; //Extraer segundos.
}
void Tiempo::mostrarTiempo()
{
if (minutos >= 60)
{
minutos -= 60;
horas++;
}
if (segundos >= 60)
{
segundos -= 60;
minutos++;
}
cout << "El tiempo es: " << horas << ":" << minutos << ":" << segundos << endl;
}
int main()
{
Tiempo t1(5, 35, 20);
Tiempo t2(20120);
t1.mostrarTiempo();
t2.mostrarTiempo();
return 0;
}
| true |
75aeec5b0e460109284481882557c032a60d002e | C++ | Wibben/WCIPEG | /ccc97s3.cpp | UTF-8 | 763 | 3.265625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int t,undefeated,oneloss,eliminated;
cin >> t;
for(int i=0; i<t; i++) {
cin >> undefeated;
cout << "Round 0: " << undefeated << " undefeated, 0 one-loss, 0 eliminated" << endl;
oneloss = eliminated = 0;
int round = 1;
while(undefeated+oneloss>1) {
if(undefeated==1 && oneloss==1) {
oneloss++;
undefeated--;
} else {
eliminated += oneloss/2;
oneloss += undefeated/2-oneloss/2;
undefeated -= undefeated/2;
}
cout << "Round " << round++ << ": " << undefeated << " undefeated, " << oneloss << " one-loss, " << eliminated << " eliminated" << endl;
}
cout << "There are " << round-1 << " rounds." << endl;
}
return 0;
}
| true |
f28b83fe7bee1f06a064f2bb0c13e6f2cd8bd846 | C++ | myk502/ACM | /hdu_oj/hdu1175 correct.cpp | GB18030 | 1,826 | 2.625 | 3 | [] | no_license | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <queue>
#include <climits>
using namespace std;
const int MAX = 1003;
const int dirx[5] = {0,0,1,0,-1};
const int diry[5] = {0,1,0,-1,0};
bool visit[MAX][MAX];
int map[MAX][MAX];
int wan[MAX][MAX];
int n,m,bx,by;
bool mark;
bool yes(int x,int y,int dir){
int dx = bx - x;
int dy = by - y;
if(dx!=0)dx = dx/abs(dx);
if(dy!=0)dy = dy/abs(dy);
if(dx==dirx[dir] && dy==diry[dir])return true;
else return false;
}
void dfs(int x,int y,int cnt,int dir){
int i,tx,ty;
if(mark)return;
if(x<1 || y<1 || x>n || y>m || cnt>2)return;
//ע漸֦˳˳˾ͻΪһԪط0
if(x==bx && y==by){
mark = true;
return;
}
if(cnt==2 && !yes(x,y,dir))return;//֦ǿ˴˼֦ʱֻ18ms
if(map[x][y]!=0)return;
if(wan[x][y]!=-1 && wan[x][y]<=cnt)return;
wan[x][y] = cnt;
for(i=1;i<=4;++i){
tx = x + dirx[i];
ty = y + diry[i];
if(dir!=i){
dfs(tx,ty,cnt+1,i);
}else{
dfs(tx,ty,cnt,i);
}
}
}
int main(){
freopen("E:\\in.txt","r",stdin);
freopen("E:\\out.txt","w",stdout);
int i,j,t,ax,ay;
while(scanf("%d %d",&n,&m)!=EOF){
if(n==0 && m==0)break;
for(i=1;i<=n;++i){
for(j=1;j<=m;++j){
scanf("%d",&map[i][j]);
}
}
scanf("%d",&t);
while(t--){
memset(wan,-1,sizeof(wan));
scanf("%d %d %d %d",&ax,&ay,&bx,&by);
mark = false;
if(map[ax][ay]!=map[bx][by] || map[ax][ay]==0||((ax==bx)&&(ay==by))){
printf("NO\n");
continue;
}
wan[ax][ay] = 0;
for(i=1;i<=4;++i){
dfs(ax+dirx[i],ay+diry[i],0,i);
}
if(mark){
printf("YES\n");
}else{
printf("NO\n");
}
}
}
return 0;
}
| true |
177ed38e395fb6a2ea13e7f09d3a9534d16f672b | C++ | rohit-0308/CPP-Placement-Practice-Problems | /5. 2D Arrays/Spiral_order_print.cpp | UTF-8 | 993 | 2.828125 | 3 | [] | no_license | #include "bits/stdc++.h"
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
int a[n][m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> a[i][j];
}
}
int row_start = 0, column_start = 0, row_end = n - 1, column_end = m - 1;
while (row_start <= row_end && column_start <= column_end)
{
// for first-row
for (int c = column_start; c <= column_end; c++)
cout << a[row_start][c] << " ";
row_start++;
// for last-column
for (int r = row_start; r <= row_end; r++)
cout << a[r][column_end] << " ";
column_end--;
// for last-row
for (int c = column_end; c >= column_start; c--)
cout << a[row_end][c]<<" ";
row_end--;
// for first-column
for (int r = row_end; r >= row_start; r--)
cout << a[r][column_start]<<" ";
column_start++;
}
return 0;
} | true |
27c11dc64dfc1d2d452e46125e0c30903208bf6f | C++ | nikifaets/bytesmack | /src/main.cpp | UTF-8 | 2,860 | 2.5625 | 3 | [] | no_license | #include <fstream>
#include <iostream>
#include <string>
#include "HTree.h"
#include <queue>
#include <cassert>
#include <unordered_map>
#include "Encoder.h"
#include "Bitset.h"
#include "Utils.h"
#include "FileReader.h"
#include "Archiver.h"
#include "FilePathManager.h"
#include "CLIParser.h"
/*
Командният интерфейс не е напълно завършен. Има проблем с метода за обновяване на файл. Може да се направи тест като се закоментират ред 19-21 включително и
се разкоментират другите.
Предоставена функционалност: Всичко описано в заданието освен възможността за използване на wildcards като * и ?, и проверката дали
в архива има проблем.
*/
/*
Тествайте командния интерфейс като пуснете програмата и дадете help като CLI аргумент.
*/
int main(int argc, char* argv[]){
/*CLIParser parser;
parser.parse(argc, argv);
std::vector<byte> inp;*/
// Разкоментирайте за тест, който не е през командния интерфейс.
Archiver archiver;
std::string arch_name = "archive";
std::string fname1 = "/home/nikifaets/Documents/vaccination";
std::string fname2 = "/home/nikifaets/Documents/fmi_io";
std::vector<std::string> files = {fname1, fname2};
std::string out_dir = "decompressed";
FilePathManager path_manager;
std::vector<std::string> out;
std::vector<std::string> files_to_decompress = {fname1, fname2}; // Това са файловете или директориите, които ще се компресират
path_manager.filepaths_to_readable_files(files_to_decompress, out);
archiver.compress(arch_name, files); // Компресия във файл "archive"
archiver.decompress(arch_name, out_dir, out, true); // Декомпресия в директория "decompressed"
std::cout << "---------------------------------------------Decompressed\n";
archiver.modify_archived_file(arch_name, "/home/nikifaets/Documents/fmi_io/io_kontr.ods", "testrec_modified"); // Промяна на даден файл от архива. Попълнете файл от архива в левите кавички и случаен файл в десните.
// За десните, моля, използвайте абсолютен път в машината.
std::cout << "....................................." << "Added new file\n";
archiver.decompress(arch_name, "decompressed_changed", out, false);
return 0;
} | true |
a3de8082c310f0572ce0d0c4439d07291309ad2c | C++ | blockspacer/Unity2018ShaderCompiler | /Tools/BugReporterV2/qt_face/tests/src/AttachmentItemViewTest.cpp | UTF-8 | 6,350 | 2.78125 | 3 | [] | no_license | #include "AttachmentItemView.h"
#include "attachment/Attachment.h"
#include "attachment/AttachmentProperties.h"
#include "AttachmentDummy.h"
#include "AttachmentSpy.h"
#include "AttachmentPropertyStub.h"
#include "shims/logical/IsEmpty.h"
#include "shims/attribute/GetSize.h"
#include "shims/attribute/GetRawPtr.h"
#include <UnitTest++.h>
#include <stdexcept>
#include <exception>
#include <memory>
#include <vector>
#include <sstream>
SUITE(AttachmentItemView)
{
using namespace ureport;
using namespace ureport::ui;
using namespace ureport::test;
TEST(Constructor_GivenNullAttachment_ThrowsInvalidArgument)
{
CHECK_THROW(AttachmentItemView(nullptr), std::invalid_argument);
}
TEST(GetSize_GivenAttachment_GetsAttachmentsSizeProperty)
{
auto attachment = std::make_shared<AttachmentSpy>();
AttachmentItemView view(attachment);
view.GetSize();
CHECK_EQUAL(attachment::kSize, attachment->m_LastPropertyAsked);
}
TEST(MakeItems_GivenEmptySetOfAttachments_ReturnsEmptySet)
{
std::vector<std::shared_ptr<Attachment> > attachments;
auto items = AttachmentItemView::MakeItems(attachments);
CHECK(IsEmpty(items));
}
TEST(MakeItems_GivenNonEmptySetOfAttachments_ReturnsTheSameAmountOfItems)
{
std::vector<std::shared_ptr<Attachment> > attachments;
attachments.push_back(std::make_shared<AttachmentDummy>());
attachments.push_back(std::make_shared<AttachmentDummy>());
auto items = AttachmentItemView::MakeItems(attachments);
CHECK_EQUAL(GetSize(attachments), GetSize(items));
}
TEST(GetAttachment_ForViewConstructedFromNotNullAttachment_ReturnsReferenceToAttachment)
{
auto attachment = std::make_shared<AttachmentDummy>();
AttachmentItemView view(attachment);
CHECK_EQUAL(GetRawPtr(attachment), GetRawPtr(view.GetAttachment()));
}
class AnAttachmentView
{
public:
AnAttachmentView()
: m_Attachment(std::make_shared<AttachmentPropertyStub>())
, m_View(m_Attachment)
{
}
void SetAttachmentSize(size_t size)
{
std::stringstream property;
property << size;
SetAttachmentSize(property.str());
}
void SetAttachmentSize(const std::string& size)
{
m_Attachment->m_Property = size;
}
public:
std::shared_ptr<AttachmentPropertyStub> m_Attachment;
AttachmentItemView m_View;
};
TEST_FIXTURE(AnAttachmentView, GetSize_GivenAttachmentWithEmptySize_ReturnsEmptyString)
{
m_Attachment->m_Property = "";
CHECK_EQUAL("", m_View.GetSize());
}
TEST_FIXTURE(AnAttachmentView, GetSize_GivenAttachmentOf0BytesSize_Returns0bytes)
{
m_Attachment->m_Property = "0";
CHECK_EQUAL("0 bytes", m_View.GetSize());
}
TEST_FIXTURE(AnAttachmentView, GetSize_GivenAttachmentOf100BytesSize_Returns100bytes)
{
m_Attachment->m_Property = "100";
CHECK_EQUAL("100 bytes", m_View.GetSize());
}
TEST_FIXTURE(AnAttachmentView, GetSize_GivenAttachmentOf1024BytesSize_Returns1Kb)
{
m_Attachment->m_Property = "1024";
CHECK_EQUAL("1 Kb", m_View.GetSize());
}
TEST_FIXTURE(AnAttachmentView, GetSize_GivenAttachmentOf2049BytesSize_Returns2Kb)
{
m_Attachment->m_Property = "2049";
CHECK_EQUAL("2 Kb", m_View.GetSize());
}
TEST_FIXTURE(AnAttachmentView, GetSize_GivenAttachmentOf1024x1024BytesSize_Returns1Mb)
{
SetAttachmentSize(1024 * 1024);
CHECK_EQUAL("1 Mb", m_View.GetSize());
}
TEST_FIXTURE(AnAttachmentView, GetSize_GivenAttachmentOf1024x1024x2point555BytesSize_Returns2point6Mb)
{
SetAttachmentSize(size_t(1024 * 1024 * 2.555));
CHECK_EQUAL("2.6 Mb", m_View.GetSize());
}
TEST_FIXTURE(AnAttachmentView, GetSize_GivenAttachmentOf1024x1024x1024BytesSize_Returns1Gb)
{
SetAttachmentSize(1024 * 1024 * 1024);
CHECK_EQUAL("1 Gb", m_View.GetSize());
}
TEST_FIXTURE(AnAttachmentView, GetSize_GivenAttachmentOf1024x1024x1024x2point24BytesSize_Returns2point2Gb)
{
SetAttachmentSize(size_t(1024 * 1024 * 1024 * 2.24));
CHECK_EQUAL("2.2 Gb", m_View.GetSize());
}
TEST_FIXTURE(AnAttachmentView, GetSize_RealityCheck1)
{
SetAttachmentSize(size_t(10.5 * 1024));
CHECK_EQUAL("10 Kb", m_View.GetSize());
}
TEST_FIXTURE(AnAttachmentView, GetSize_RealityCheck2)
{
SetAttachmentSize(size_t(255.55555 * 1024 * 1024));
CHECK_EQUAL("255.6 Mb", m_View.GetSize());
}
TEST_FIXTURE(AnAttachmentView, GetSize_RealityCheck3)
{
SetAttachmentSize(size_t(10.5 * 1024 * 1024));
CHECK_EQUAL("10.5 Mb", m_View.GetSize());
}
TEST_FIXTURE(AnAttachmentView, GetSizeInBytes_GivenAttachmentWithEmptySize_ReturnsZero)
{
SetAttachmentSize("");
CHECK_EQUAL(0, m_View.GetSizeInBytes());
}
TEST_FIXTURE(AnAttachmentView, GetSizeInBytes_GivenAttachmentOf1ByteSize_ReturnsOne)
{
SetAttachmentSize(1);
CHECK_EQUAL(1, m_View.GetSizeInBytes());
}
TEST_FIXTURE(AnAttachmentView, GetSizeInBytes_GivenAttachmentOf1024BytesSize_Returns1024)
{
SetAttachmentSize(1024);
CHECK_EQUAL(1024, m_View.GetSizeInBytes());
}
TEST_FIXTURE(AnAttachmentView, GetSizeInBytes_GivenAttachmentOf1024x1024x1024x2point24BytesSize_Returns1024x1024x1024x2point24)
{
auto size = size_t(1024 * 1024 * 1024 * 2.24);
SetAttachmentSize(size);
CHECK_EQUAL(size, m_View.GetSizeInBytes());
}
TEST(GetSizeAndSizeInBytes_CalledMultipleGivenAttachementWithNonEmptySize_GetsSizePropertyOnce)
{
auto attachment = std::make_shared<AttachmentSpy>();
attachment->m_PropertyValue = "0";
AttachmentItemView view(attachment);
view.GetSize();
view.GetSizeInBytes();
view.GetSize();
view.GetSizeInBytes();
CHECK_EQUAL(1, attachment->m_CallsNumber);
}
TEST_FIXTURE(AnAttachmentView, GetName_GivenAttachmentWithNonEmptyName_ReturnsAttachmentName)
{
m_Attachment->m_Property = "name";
CHECK_EQUAL("name", m_View.GetName());
}
}
| true |
84051be18befa53caee4a889aa759621ec97b975 | C++ | Divyarajsinh/lb-Arduino-Code | /LBCards/GVSDuino/GVSDwATP/GVSwATP.ino | UTF-8 | 1,147 | 3.078125 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | /*
GVSwATP
Tests the LEDs on the ATP daughter card when it is mounted above a GVSDuino card.
Bounce a light across the LEDs.
*/
// The LEDs follow
int progLED = 7;
int errLED = 8;
int hbLED = 9;
// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output.
pinMode(progLED, OUTPUT);
pinMode(errLED, OUTPUT);
pinMode(hbLED, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
digitalWrite(progLED, LOW); // turn the progLED off by making the voltage LOW
delay(500); // wait for a second
digitalWrite(progLED, HIGH); // turn the progLED on (HIGH is the voltage level)
digitalWrite(errLED, LOW); // turn the progLED off by making the voltage LOW
delay(500); // wait for a second
digitalWrite(errLED, HIGH); // turn the progLED on (HIGH is the voltage level)
digitalWrite(hbLED, LOW); // turn the progLED off by making the voltage LOW
delay(500); // wait for a second
digitalWrite(hbLED, HIGH); // turn the progLED on (HIGH is the voltage level)
}
| true |
1d58638d093324dba85d90c80b4ddc2c401537a6 | C++ | jay-jay-chang/DX11 | /framework/ModelExample/src/utility.h | UTF-8 | 354 | 2.59375 | 3 | [] | no_license | #pragma once
#include <windows.h>
#include <string>
#include <vector>
using namespace std;
static string utf16ToUTF8(const wstring &s)
{
const int size = ::WideCharToMultiByte(CP_UTF8, 0, s.c_str(), -1, NULL, 0, 0, NULL);
vector<char> buf(size);
::WideCharToMultiByte(CP_UTF8, 0, s.c_str(), -1, &buf[0], size, 0, NULL);
return string(&buf[0]);
}
| true |
27a5143a9735e004dc77d1cc0d05a946b26beb1b | C++ | titiloxx/Anti-debugging | /DebugHook/dllmain.cpp | UTF-8 | 997 | 2.640625 | 3 | [] | no_license | // dllmain.cpp : Defines the entry point for the DLL application.
#include "windows.h"
#include <iostream>
#include <fstream>
#include <map>
DWORD funcion = 0x77666000;
bool Hook(void* toHook, void* ourFunct, int len)
{
if (len < 5)
{
return false;
}
DWORD curProtection;
VirtualProtect(toHook, len, PAGE_EXECUTE_READWRITE, &curProtection);
memset(toHook, 0x90, len);//El nopeador
DWORD relativeAddress = ((DWORD)ourFunct - (DWORD)toHook) - 5;
*(BYTE*)toHook = 0xE9;
*(DWORD*)((DWORD)toHook + 1) = relativeAddress;
DWORD temp;
VirtualProtect(toHook, len, curProtection, &temp);
return true;
}
void __declspec(naked)ourFunct() {
__asm {
jmp[funcion+0x4]
}
}
DWORD WINAPI MainThread(LPVOID param)
{
Hook((void*)funcion, ourFunct, 7);
return 0x0;
}
BOOL WINAPI DllMain(HINSTANCE hModule, DWORD dwReason, LPVOID lpReserved)
{
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
CreateThread(0, 0, MainThread, hModule, 0, 0);
break;
default:
break;
}
return TRUE;
}
| true |
9e65650d14b32f1ce6a0a169ea9323f7988a6cae | C++ | Jasonarea/Baekjoon_ | /Divide_Conquer/Divide_Conquer/1517_버블소트.cpp | UTF-8 | 754 | 2.8125 | 3 | [] | no_license | #include <cstdio>
int a[500000];
int b[500000];
long long solve(int start, int end) {
if(start == end) return 0;
int mid = (start + end)/2;
long long ans = solve(start, mid) + solve(mid+1, end);
int i = start; int j = mid + 1;
int k = 0;
while (i <= mid || j <= end) {
if (i <= mid && (j > end || a[i] <= a[j])) {
b[k++] = a[i++];
} else {
ans += (long long)(mid-i+1);
b[k++] = a[j++];
}
}
for(int i = start;i<=end;i++)
a[i] = b[i-start];
return ans;
}
int main(void)
{
int n;
scanf("%d", &n);
for(int i = 0;i<n;i++)
scanf("%d", &a[i]);
long long ans = solve(0, n-1);
printf("%lld", ans);
return 0;
}
| true |
5becb918b9419ef522204045df91f11511ac12d2 | C++ | JanKuiken/rp3synth | /src/filter.cpp | UTF-8 | 1,299 | 2.875 | 3 | [] | no_license | #include "filter.h"
#include <cmath>
#include "utils.h"
Filter::Filter(int in_rate)
{
rate = in_rate;
}
void Filter::Start(double in_frequency, std::string in_type, double in_sensitifity)
{
// IIR filter constants for a low pass filter
sensitifity = bounds_limit(in_sensitifity, 0.0, 1.0);
filtertype = StringToFilterType(in_type);
double fx = exp(-2.0 * M_PI * in_frequency / rate);
switch (filtertype) {
case lowpass:
a_0 = 1.0 - fx;
a_1 = 0.0;
b_1 = fx;
break;
case highpass:
a_0 = (1.0 + fx) / 2.0;
a_1 = - (1.0 + fx) / 2.0;
b_1 = fx;
break;
default:
a_0 = 1.0;
a_1 = 0.0;
b_1 = 0.0;
break;
}
prev_x = 0.0;
prev_y = 0.0;
}
FilterType Filter::StringToFilterType(std::string in_type) {
FilterType ft = lowpass; // default, if no valid string is provided
if (in_type == "lowpass") ft = lowpass;
if (in_type == "highpass") ft = highpass;
return ft;
}
double Filter::Next(double current_x)
{
double current_y = a_0 * current_x
+ a_1 * prev_x
+ b_1 * prev_y ;
prev_x = current_x;
prev_y = current_y;
return sensitifity * current_y + (1.0 - sensitifity) * current_x;
}
| true |
2ea7a25668b738103e5ba3343f745c22fa8b9fed | C++ | letuananh035/Paint32 | /Source/Paint32/CLine.cpp | UTF-8 | 1,898 | 2.578125 | 3 | [] | no_license |
#include "CLine.h"
#include "Exception.h"
namespace Paint32{
namespace Model{
void CLine::SetDraw(COLORREF color, COLORREF colorbg,
POINT lefttop, POINT rightbottom,
int iPenStyle, int iPenWidth, bool bSetRop){
this->ColorBG = colorbg;
this->Color = color;
this->LeftTop = lefttop;
this->RightBottom = rightbottom;
this->PenStyle = iPenStyle;
this->PenWidth = iPenWidth;
this->SetRop = bSetRop;
}
void CLine::Draw(HDC hDc, COLORREF color, COLORREF colorbg,
POINT lefttop, POINT rightbottom,
int iPenStyle, int iPenWidth, bool bSetRop)
{
//Lưu lại các thuộc tính để vẽ lại
this->ColorBG = colorbg;
this->Color = color;
this->LeftTop = lefttop;
this->RightBottom = rightbottom;
this->PenStyle = iPenStyle;
this->PenWidth = iPenWidth;
//HDC hdc = GetDC(hwnd);
if (bSetRop == true)
SetROP2(hDc, R2_MERGEPENNOT);
//HPEN hPen = CreatePen(iPenStyle, iPenWidth, color);
//SelectObject(hDc, hPen);
//if (!MoveToEx(hDc, lefttop.x, lefttop.y, NULL)){
// throw Exception(L"Lỗi MoveToEx");
// return;
//}
//if(!LineTo(hDc, rightbottom.x, rightbottom.y)){
// throw Exception(L"Lỗi LineTo");
// return;
//}
//DeleteObject(hPen);
::Color color_;
color_.SetFromCOLORREF(color);
Graphics* graphics = new Graphics(hDc);
Pen* pen = new Pen(color_, iPenWidth);
pen->SetDashStyle((DashStyle)iPenStyle);
graphics->DrawLine(pen, lefttop.x, lefttop.y, rightbottom.x, rightbottom.y);
delete pen;
delete graphics;
//ReleaseDC(hwnd, hdc);
}
void CLine::ReDraw(HDC hDc)
{
this->Draw(hDc, this->Color,this->ColorBG, this->LeftTop, this->RightBottom,
this->PenStyle, this->PenWidth, false);
}
CShape* CLine::CreateNewShape()
{
CShape* shape = new CLine;
return shape;
}
POINT CLine::GetLefttop(){
return this->LeftTop;
};
}
}
| true |
7e55f7d93a3d911cb94ec7a606dff2199454bcc9 | C++ | exgile/pangya-server-1 | /src/common/timer.cpp | UTF-8 | 1,586 | 3.1875 | 3 | [] | no_license | #include "timer.h"
#include <map>
#include <memory>
std::map<int, std::unique_ptr<Worker>> timers;
void timer_init() {
// Create timer
for (int i = 0; i < MAX_TIMER; ++i) {
timers[i] = std::make_unique<Worker>();
timers[i]->enabled = false;
}
}
int aquire_timerid() {
for (int i = 0; i < MAX_TIMER; ++i) {
if (timers[i]->enabled == false) {
return i;
}
}
return -1; // No Slot available for timer.
}
// -1 = Fail to add timer
int addtimer(int ms, std::function<void(void)> handler, bool periodic) {
int timerid = aquire_timerid();
if (timerid == -1) {
throw "Timer : No Slot available for timer.";
}
timers[timerid]->enabled = true;
timers[timerid]->end = std::chrono::system_clock::now() + std::chrono::milliseconds(ms);
timers[timerid]->ms = std::chrono::milliseconds(ms);
timers[timerid]->periodic = periodic;
timers[timerid]->handler = handler;
return timerid;
}
bool deltimer(int timerid) {
if (timers[timerid]->enabled == true) {
timers[timerid]->enabled = false;
timers[timerid]->handler = nullptr;
return true;
}
return false;
}
void do_timer() {
for (auto const &timer : timers) {
if (timer.second->enabled == true && timer.second->end <= std::chrono::system_clock::now()) {
if (timer.second->handler)
timer.second->handler(); // Execute the function
if (!timer.second->periodic) {
timer.second->enabled = false;
timer.second->handler = nullptr;
}
timer.second->end = std::chrono::system_clock::now() + std::chrono::milliseconds(timer.second->ms);
}
}
}
void timer_final() {
timers.clear();
} | true |
e1789dd5fefb69ccce8007fba7abcd4eb9b524ab | C++ | rleonard21/Sphere-Simulator | /Simulator.h | UTF-8 | 2,564 | 2.9375 | 3 | [] | no_license | //
// Created by robert on 6/25/20.
//
#ifndef SPHERE_SIM_SIMULATOR_H
#define SPHERE_SIM_SIMULATOR_H
#include "Sphere.h"
#include "Vector.h"
#include <vector>
const double gravity = -9.81;
const double airDensity = 1.225;
// EFFECTS: struct for passing parameters to simulator constructor
struct SimulationParameters {
Sphere projectile;
double deltaT;
double tMax;
Vector initialVelocity;
Vector initialPosition;
Vector initialWind;
Vector initialAngularVelocity;
};
// EFFECTS: struct for saving data from simulation
struct SimulationData {
double time = 0;
Vector position;
Vector velocity;
Vector netForce;
};
class Simulator {
private:
std::vector<SimulationData> results;
SimulationParameters parameters;
SimulationData stepData;
Vector weight;
// EFFECTS: computes force due to gravitational acceleration
Vector computeWeight() const;
// EFFECTS: computes force due to the magnus effect (spin)
Vector computeMagnus() const;
// EFFECTS: helper to compute the air resistance magnitude
double computeAirResistanceMagnitude() const;
// EFFECTS: computes force due to air resistance
Vector computeAirResistance() const;
// EFFECTS: computes the net force on the projectile
void updateNetForce();
// EFFECTS: computes the new velocity for the given time step
void updateVelocity();
// EFFECTS: computes the new position for the given time step
void updatePosition();
// EFFECTS: saves the results of the simulation step
void saveStepResults();
public:
// EFFECTS: constructor
explicit Simulator(SimulationParameters _param) : parameters(_param) {
this->weight = Vector(0, this->parameters.projectile.mass * gravity, 0);
this->stepData.position = this->parameters.initialPosition;
this->stepData.velocity = this->parameters.initialVelocity;
auto maxDatapoints = static_cast<unsigned long>(this->parameters.tMax / this->parameters.deltaT);
this->results.reserve(maxDatapoints);
}
// EFFECTS: runs the simulation
void solve();
// EFFECTS: prints the summary to stdout
void printResultSummary() const;
// EFFECTS: prints the saved data to stdout
void printResultData() const;
// EFFECTS: saves data to CSV
void printCSV(const char *filename) const;
// EFFECTS: returns a reference to the simulation data
std::vector<SimulationData> &getResults() { return this->results; }
};
#endif //SPHERE_SIM_SIMULATOR_H
| true |
6f68dae46e49e166179e0a4578ac31455612fff5 | C++ | ParCoreLab/Split_SpTRSV | /src/matrix.cpp | UTF-8 | 2,526 | 2.71875 | 3 | [] | no_license | // matrix.cpp
#include <matrix.h>
#include <common.h>
csr_matrix::csr_matrix(ind_type * const csrRowPtr,
ind_type * const csrColIdx,
val_type * const csrVal,
const sz_type m,
const sz_type n,
const sz_type nnz,
const std::string &name)
: csrRowPtr(csrRowPtr), csrColIdx(csrColIdx), csrVal(csrVal), m(m), n(n), nnz(nnz), name(name) {}
csc_matrix::csc_matrix(ind_type * const cscRowIdx,
ind_type * const cscColPtr,
val_type * const cscVal,
const sz_type m,
const sz_type n,
const sz_type nnz,
const std::string &name)
: cscRowIdx(cscRowIdx), cscColPtr(cscColPtr), cscVal(cscVal), m(m), n(n), nnz(nnz), name(name) {}
uf_matrix_reader::uf_matrix_reader()
: collection(uf_collection_init1(UF_COLLECTION_VERBOSE)) {
std::cout << "Database contains " << uf_collection_num_matrices(collection) << " matrices.\n";
}
csr_matrix::csr_matrix()
{
}
csc_matrix::csc_matrix()
{
}
csr_matrix::~csr_matrix()
{
//free(csrRowPtr);
//free()
}
csr_matrix uf_matrix_reader::get_matrix_csr_libufget(int id) {
printf("ID: %d\n", id);
uf_matrix_t *mat = uf_collection_get_by_id(collection, id);
uf_matrix_get(mat);
uf_field_t field;
sz_type m, n, nnz;
ind_type *csrRowPtr, *csrColIdx;
val_type *csrVal;
int retCode = uf_matrix_coord_int32(&field, &m, &n, &nnz, &csrRowPtr, &csrColIdx, (void **) &csrVal, mat);
if(retCode != 0)
{
printf("Error reading the matrix archive file!\n");
printf("Function return code: %d\n", retCode);
exit(1);
}
uf_matrix_coord_to_csr_int32(field, m, n, nnz, &csrRowPtr, &csrColIdx, (void **) &csrVal);
printf("matrix name = %s\n", mat->name);
printf("Rows: %10d\t Cols: %10d\t nnz: %12d\n", (int) m, (int) n, (int) nnz);
//csrRowPtr = (ind_type *)malloc((m+1) * sizeof(ind_type));
//csrColIdx = (ind_type *)malloc(nnz * sizeof(ind_type));
//csrVal = (val_type *)malloc(nnz * sizeof(val_type));
uf_matrix_free(mat);
return csr_matrix{
csrRowPtr,
csrColIdx,
csrVal,
m,
n,
nnz,
mat->name
};
}
uf_matrix_reader::~uf_matrix_reader() {
uf_collection_finalize(collection);
}
std::string uf_matrix_reader::get_matrix_name(int id) {
uf_matrix_t *mat = uf_collection_get_by_id(collection, id);
std::string name(mat->name);
uf_matrix_free(mat);
return name;
} | true |
f8f2e9fc27ce055ff3fbe263e68d58bc7157383a | C++ | juliawong22/LAIG | /LAIG-1/src/Parser.cpp | WINDOWS-1252 | 27,242 | 2.84375 | 3 | [] | no_license | #include <sstream>
#include <string>
#include <iomanip>
#include <algorithm>
#include <cctype>
#include <iostream>
#include <vector>
#include "Parser.h"
#include "PerspectiveCamera.h"
#include "OrthoCamera.h"
#include "Appearance.h"
#include "Node.h"
#include "Animation.h"
using namespace std;
/*Recebe:
* string text - com varios numeros,
* int n - o numero de numeros a tirar da string,
* vector elements - onde sao guardados os numeros */
void extractElementsFromString(vector<float> &elements, string text, int n)
{
stringstream text_ss;
text_ss << text;
elements.clear();
for (int i = 0; i < n; i++)
{
float j;
if(text_ss.rdbuf()->in_avail()==0) //verifica antes de ler a stringstream se o numero de caracteres a ler 0, pois se for, significa que faltam elementos pois vai ser lido o ultimo numero outra vez
throw "Error parsing, parameter with invalid number/type of attribute(s)!";
text_ss >> j;
elements.push_back(j);
}
if(text_ss.rdbuf()->in_avail()!=0)
throw "Error parsing, parameter with invalid number/type of attribute(s)!";
}
void Parser::parseGlobals()
{
globalsElement = yafElement->FirstChildElement( "globals" );
if(!globalsElement)
throw "Error parsing globals";
string drawmode, shading, cullface, cullorder;
vector<float> background;
extractElementsFromString(background, globalsElement->Attribute("background"), 4);
drawmode = globalsElement->Attribute("drawmode");
shading = globalsElement->Attribute("shading");
cullface = globalsElement->Attribute("cullface");
cullorder = globalsElement->Attribute("cullorder");
if(background.empty() || drawmode.empty() || shading.empty() || cullface.empty() || cullorder.empty())
throw "Error parsing globals attributes";
//print globals attributes
cout << "Globals" << endl;
cout << "\tBackground: ";
for (unsigned int i = 0; i < background.size(); i++)
{
cout << background[i] << " ";
}
cout << "\n\tDrawmode: " << drawmode << endl;
cout << "\tShading: " << shading << endl;
cout << "\tCullface: " << cullface << endl;
cout << "\tCullorder: " << cullorder << endl;
scene.backgroundR = background[0];
scene.backgroundG = background[1];
scene.backgroundB = background[2];
scene.backgroundA = background[3];
if(drawmode == "fill")
this->scene.drawMode = GL_FILL;
else if(drawmode == "line")
this->scene.drawMode = GL_LINE;
else if(drawmode == "point")
this->scene.drawMode = GL_POINT;
else
throw "Invalid drawmode";
if(shading == "flat")
this->scene.shadeModel = GL_FLAT;
else if(shading == "gouraud")
this->scene.shadeModel = GL_SMOOTH;
else
throw "Invalid shading";
if(cullface == "none")
this->scene.cullface = false;
else {
this->scene.cullface = true;
if(cullface=="back")
this->scene.cullfaceMode = GL_BACK;
else if(cullface=="front")
this->scene.cullfaceMode = GL_FRONT;
else if(cullface=="both")
this->scene.cullfaceMode = GL_FRONT_AND_BACK;
else
throw "Invalid cullface";
}
if(cullorder == "CCW")
this->scene.cullorder = GL_CCW;
else if(cullorder == "CW")
this->scene.cullorder = GL_CW;
else
throw "Invalid cullorder";
}
void Parser::parseCameras()
{
camerasElement = yafElement->FirstChildElement( "cameras" );
if(!camerasElement)
throw "Error parsing cameras";
string initialCameraID = camerasElement->Attribute("initial");
if(initialCameraID.empty())
throw "Error parsing initial camera";
TiXmlElement* initialCamera = findChildByAttribute(camerasElement, "id", initialCameraID.c_str());
if(!initialCamera)
throw "Initial camera not declared";
cout << "Cameras" << endl;
cout << "\t Initial: " << initialCameraID << endl;
TiXmlElement* camera = camerasElement->FirstChildElement();
while(camera)
{
float near, far, left, right, top, bottom, angle;
int cameraVectorIndex = 0;
string id = camera->Attribute("id"),type = camera->Value(), target;
vector<float> pos_vector;// = {0,0,0};
vector<float> target_vector;
if (id.empty() || type.empty())
throw "Error parsing Cameras: empty string";
if (camera->QueryFloatAttribute("near", &near) != 0)
throw "Error parsing Cameras: no 'near' attribute";
if (camera->QueryFloatAttribute("far", &far) != 0)
throw "Error parsing Cameras: no 'far' attribute";
cout << endl << "\tID: " << id << endl;
cout << "\tType: " << type << endl;
cout << "\tNear: " << near << endl;
cout << "\tFar: " << far << endl;
if (type == "perspective")
{
if (camera->QueryFloatAttribute("angle", &angle) != 0)
throw "Error parsing Cameras: no 'angle' attribute";
extractElementsFromString(pos_vector, camera->Attribute("pos"), 3);
extractElementsFromString(target_vector, camera->Attribute("target"), 3);
//print camera attributes
cout << "\tAngle: " << angle << endl;
cout << "\tPos: ";
for (unsigned int i = 0; i < pos_vector.size(); i++)
cout << pos_vector[i] << " ";
cout << endl;
cout << "\tTarget: ";
for (unsigned int i = 0; i < target_vector.size(); i++)
cout << target_vector[i] << " ";
cout << endl;
PerspectiveCamera *c = new PerspectiveCamera(id, near, far, angle);
c->setX(pos_vector[0]);
c->setY(pos_vector[1]);
c->setZ(pos_vector[2]);
c->setTargetX(target_vector[0]);
c->setTargetY(target_vector[1]);
c->setTargetZ(target_vector[2]);
cameraVectorIndex = this->scene.addCamera(c);
}
else if (type == "ortho")
{
if (camera->QueryFloatAttribute("left", &left) != 0)
throw "Error parsing Cameras: no 'left' attribute";
if (camera->QueryFloatAttribute("right", &right) != 0)
"Error parsing Cameras: no 'right' attribute";
if (camera->QueryFloatAttribute("top", &top) != 0)
throw "Error parsing Cameras: no 'top' attribute";
if (camera->QueryFloatAttribute("bottom", &bottom) != 0)
"Error parsing Cameras: no 'bottom' attribute";
//print camera attributes
cout << "\tLeft: " << left << endl;
cout << "\tRight: " << right << endl;
cout << "\tTop: " << top << endl;
cout << "\tBottom: " << bottom << endl;
OrthoCamera *c = new OrthoCamera(id, near, far, left, right, top, bottom);
cameraVectorIndex = this->scene.addCamera(c);
}
if(camera == initialCamera)
this->scene.activateCamera(cameraVectorIndex);
camera = camera->NextSiblingElement();
}
}
void Parser::parseLighting()
{
lightingElement = yafElement->FirstChildElement( "lighting" );
if(!lightingElement)
throw "Error parsing lighting";
bool doublesided, local, enabled;
vector<float> ambient;
doublesided = to_bool(lightingElement->Attribute("doublesided"));
local = to_bool(lightingElement->Attribute("local"));
enabled = to_bool(lightingElement->Attribute("enabled"));
extractElementsFromString(ambient, lightingElement->Attribute("ambient"), 4);
if(ambient.empty())
throw "Error parsing lighting attributes";
this->scene.lightingDoubleSided = doublesided;
this->scene.lightingLocal = local;
this->scene.lightingEnabled = enabled;
for(unsigned int i=0;i<ambient.size();i++) //set all background_ambient array fields with corresponding vector
Light::background_ambient[i]=ambient[i];
cout << "Lighting" << endl;
cout << "\tDoublesided: " << boolalpha << doublesided << endl;
cout << "\tLocal: " << boolalpha << local << endl;
cout << "\tEnabled: " << boolalpha << enabled << endl;
cout << "\tAmbient: ";
for (unsigned int i = 0; i < ambient.size(); i++)
cout << ambient[i] << " ";
TiXmlElement *lighting = lightingElement->FirstChildElement();
string id, type;
vector<float> location, diffuse, specular, direction;
float angle, exponent;
unsigned int j=0;
if(!lighting)
throw "Error parsing lighting";
else
while(lighting)
{
type = lighting->Value();
id = lighting->Attribute("id");
enabled = to_bool(lighting->Attribute("enabled"));
extractElementsFromString(location, lighting->Attribute("location"), 3);
extractElementsFromString(ambient, lighting->Attribute("ambient"), 4);
extractElementsFromString(diffuse, lighting->Attribute("diffuse"), 4);
extractElementsFromString(specular, lighting->Attribute("specular"), 4);
if (type.empty() || id.empty())
throw "Error parsing Lighting: empty string";
location.push_back(1);
cout << "\n\n\t- ID: " << id << endl;
cout << "\tType: " << type << endl;
cout << "\tEnabled: " << boolalpha << enabled << endl;
cout << "\tLocation: ";
for (unsigned int i = 0; i < location.size(); i++)
cout << location[i] << " ";
cout << "\n\tAmbient: ";
for (unsigned int i = 0; i < ambient.size(); i++)
cout << ambient[i] << " ";
cout << "\n\tDiffuse: ";
for (unsigned int i = 0; i < diffuse.size(); i++)
cout << diffuse[i] << " ";
cout << "\n\tSpecular: ";
for (unsigned int i = 0; i < specular.size(); i++)
cout << specular[i] << " ";
Light *l = new Light(id, GL_LIGHT0+j, &location[0]);
if (type == "spot")
{
if (lighting->QueryFloatAttribute("angle", &angle) != 0)
throw "Error parsing Lighting: no 'angle' attribute!";
if (lighting->QueryFloatAttribute("exponent", &exponent) != 0)
throw "Error parsing Lighting: no 'exponent' attribute!";
extractElementsFromString(direction, lighting->Attribute("direction"), 3);
cout << "\tangle:" << angle << endl;
cout << "\texponent:" << exponent << endl;
for (unsigned int i = 0; i < direction.size(); i++)
cout << "\tdirection:" << direction[i] << endl;
//got to create again to set direction and exponent
l = new Light(id, GL_LIGHT0+j, &location[0], &direction[0], exponent);
l->setAngle(angle);
}
l->setAmbient(&ambient[0]);
l->setDiffuse(&diffuse[0]);
l->setSpecular(&specular[0]);
if(enabled)
l->enable();
else
l->disable();
this->scene.addLight(l);
j++;
lighting = lighting->NextSiblingElement();
}
}
void Parser::parseTextures()
{
string id, file_name;
texturesElement = yafElement->FirstChildElement( "textures" );
if(!texturesElement)
throw "Error parsing textures";
cout << "\nTextures" << endl;
TiXmlElement *textures = texturesElement->FirstChildElement("texture");
while (textures)
{
id = textures->Attribute("id");
file_name = textures->Attribute("file");
if (id.empty() || file_name.empty())
throw "Error parsing textures: empty string!";
cout << "\tID: " << id << endl;
cout << "\tFile: " << file_name << endl << endl;
this->scene.addTexture(new Texture(id, this->path+file_name)); //usa o caminho do yaf para as texturas
textures = textures->NextSiblingElement();
}
}
void Parser::parseAppearances()
{
appearancesElement = yafElement->FirstChildElement( "appearances" );
string id;
vector<float> ambient, diffuse, specular;
if(!appearancesElement)
throw "Error parsing appearances";
cout << "Appearances" << endl;
TiXmlElement *appearances = appearancesElement->FirstChildElement("appearance");
if (!appearances)
throw "Error parsing appearances";
while (appearances)
{
vector<float> emissive;
float shininess, texlength_s, texlength_t;
string textureref;
id = appearances->Attribute("id");
if (id.empty())
throw "Error parsing appearances: empty string";
extractElementsFromString(emissive, appearances->Attribute("emissive"), 4);
extractElementsFromString(ambient, appearances->Attribute("ambient"), 4);
extractElementsFromString(diffuse, appearances->Attribute("diffuse"), 4);
extractElementsFromString(specular, appearances->Attribute("specular"), 4);
if (appearances->QueryFloatAttribute("shininess", &shininess) != 0)
throw "Error parsing appearances: no 'shininess' attribute";
cout << "\n\t- ID: " << id << endl;
cout << "\temissive: ";
for (unsigned int i = 0; i < emissive.size(); i++)
cout << emissive[i] << " ";
cout << "\n\tambient: ";
for (unsigned int i = 0; i < ambient.size(); i++)
cout << ambient[i] << " ";
cout << "\n\tdiffuse: ";
for (unsigned int i = 0; i < diffuse.size(); i++)
cout << diffuse[i] << " ";
cout << "\n\tspecular: ";
for (unsigned int i = 0; i < specular.size(); i++)
cout << specular[i] << " ";
cout << "\n\tshininess: " << shininess;
Appearance *a = new Appearance(id, &ambient[0], &diffuse[0], &specular[0], &emissive[0], shininess);
//se textureref existir, tem de haver texlength_s e texlength_t
if (appearances->Attribute("textureref") != NULL)
{
textureref = appearances->Attribute("textureref");
if (textureref.empty())
throw "Error parsing appearanes: no 'textureref' attribute";
if (appearances->QueryFloatAttribute("texlength_s", &texlength_s) != 0)
throw "Error parsing appearances: no 'textlength_s' attribute";
if (appearances->QueryFloatAttribute("texlength_t", &texlength_t) != 0)
throw "Error parsing apearances: no 'length_t' attribute";
cout << "\n\ttextureref: " << textureref;
cout << "\n\ttexlength_s: " << texlength_s;
cout << "\n\ttexlength_t: " << texlength_t;
a->setTexture(scene.getTextureByID(textureref)); //get previously set texture by nodeID
if(!texlength_s || !texlength_t)
throw("Texture wrap not set or invalid");
a->setTextureWrap(texlength_s, texlength_t);
}
scene.addAppearance(a);
appearances = appearances->NextSiblingElement();
}
}
void Parser::parseAnimations()
{
animationsElement = yafElement->FirstChildElement("animations");
if (!animationsElement)
throw "Animations element doesn't exist!";
else
{
TiXmlElement *animation = animationsElement->FirstChildElement();
while (animation)
{
string id, type;
float span, xx, yy, zz;
id = animation->Attribute("id");
if (id.empty())
throw "Error parsing animation: no id attribute";
if (animation->QueryFloatAttribute("span", &span) != 0)
throw "Error parsing animation: no span attribute";
type = animation->Attribute("type");
if (type.empty())
throw "Error parsing animation: no type attribute";
if (type == "linear")
{
LinearAnimation *readAnimation = new LinearAnimation(id, span);
TiXmlElement *controlpoint = animation->FirstChildElement();
if (!controlpoint)
throw "Error parsing animation: at least one control point is needed!"; //two i guess
while (controlpoint)
{
if (controlpoint->QueryFloatAttribute("xx", &xx) != 0 || controlpoint->QueryFloatAttribute("yy", &yy) || controlpoint->QueryFloatAttribute("zz", &zz))
throw "Error parsing animation: no controlpoint attributes";
std::array<float, 3> readControlPoint;
readControlPoint[0] = xx;
readControlPoint[1] = yy;
readControlPoint[2] = zz;
readAnimation->addControlPoint(readControlPoint);
controlpoint = controlpoint->NextSiblingElement();
}
if (readAnimation->getNumControlPoints() < 2)
throw "Error parsing animation: you must define at least 2 control points";
this->scene.addAnimation(readAnimation);
animation = animation->NextSiblingElement();
}
else
throw "Only linear animations supported";
}
}
}
void Parser::parseGraph()
{
graphElement = yafElement->FirstChildElement( "graph" );
if(!graphElement)
throw "Error parsing graph";
string rootid, id;
bool displayList;
rootid = graphElement->Attribute("rootid");
if(rootid.empty())
throw "Error parsing graph attributes";
cout << "\nGraph" << endl;
cout << "\tRoot ID: " << rootid << endl;
this->scene.rootNode = rootid;
TiXmlElement *node = graphElement->FirstChildElement("node");
if (!node)
throw "Error parsing nodes!";
else
while (node)
{
id = node->Attribute("id");
if (id.empty())
throw "Error parsing node: no 'id' attribute";
cout << "\n\tID: " << id << endl;
TiXmlElement *transforms = node->FirstChildElement("transforms");
TiXmlElement *transformsElement = transforms->FirstChildElement();
Node *readNode = new Node(id);
const char * readDisplayList = node->Attribute("displaylist");
if (readDisplayList != NULL)
{
displayList = to_bool(readDisplayList);
readNode->displayList = displayList;
cout << "\tDisplaylist: " << boolalpha << displayList << endl;
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
cout << "\t-Transforms:" << endl;
if (!transforms)
throw "Error parsing transforms";
else
while (transformsElement)
{
vector<float> transforms_components, scale;
float angle;
string axis, value = transformsElement->Value();
if (value.empty())
throw "error parsing node: no tag value";
else if (value == "translate")
{
extractElementsFromString(transforms_components, transformsElement->Attribute("to"), 3);
cout << "\tTranslate: ";
for (unsigned int i = 0; i < transforms_components.size(); i++)
cout << transforms_components[i] << " ";
cout << endl;
glTranslatef(transforms_components[0],transforms_components[1],transforms_components[2]);
}
else if (value == "rotate")
{
axis = transformsElement->Attribute("axis");
if (axis.empty())
throw "Error parsing node: no 'axis' attribute";
if (transformsElement->QueryFloatAttribute("angle", &angle) != 0)
throw "Error parsing node: no 'angle' attribute";
cout << "\tRotate axis " << axis << " by " << angle <<" degrees" << endl;
if(axis=="x")
glRotatef(angle, 1, 0, 0);
else if(axis=="y")
glRotatef(angle, 0, 1, 0);
else if(axis=="z")
glRotatef(angle, 0, 0, 1);
else
throw "Invalid axis";
}
else if (value == "scale")
{
extractElementsFromString(transforms_components, transformsElement->Attribute("factor"), 3);
cout << "\tScale factor: ";
for (unsigned int i = 0; i < transforms_components.size(); i++)
{
cout << transforms_components[i] << " ";
}
cout << endl;
glScalef(transforms_components[0], transforms_components[1], transforms_components[2]);
}
transformsElement = transformsElement->NextSiblingElement();
}
glGetFloatv(GL_MODELVIEW_MATRIX, readNode->T);
string appearancerefid, value;
TiXmlElement *children = transforms->NextSiblingElement("children"), *appearanceref = transforms->NextSiblingElement("appearanceref"), *animationref = transforms->NextSiblingElement("animationref"); //pode ser children ou appearanceref ou animationref
if (!children)
throw "Error parsing node: no children block";
if (appearanceref)
{
appearancerefid = appearanceref->Attribute("id");
if (appearancerefid.empty())
throw "Error parsing appearanceref id";
cout << "\t-Appearanceref ID: " << appearancerefid << endl;
readNode->appearance=this->scene.getAppearanceByID(appearancerefid);
}
if (animationref)
{
string animationrefid = animationref->Attribute("id");
if (animationrefid.empty())
throw "Error parsing animationref id";
cout << "\t-Animationref ID: " << animationrefid << endl;
readNode->animation = this->scene.getAnimationByID(animationrefid);
}
TiXmlElement *childrenElement = children->FirstChildElement();
cout << "\t-Children:" << endl;
while (childrenElement)
{
value = childrenElement->Value();
//cout << "\tVALUE: " << value << endl;
if (value.empty())
throw "Error parsing node: no children 'value' set";
if (value == "rectangle")
{
vector<float> xy1, xy2;
extractElementsFromString(xy1, childrenElement->Attribute("xy1"), 2);
extractElementsFromString(xy2, childrenElement->Attribute("xy2"), 2);
cout << "\tRectangle: ";
for (unsigned int i = 0; i < xy1.size(); i++)
cout << xy1[i] << " ";
for (unsigned int i = 0; i < xy2.size(); i++)
cout << xy2[i] << " ";
cout << endl;
readNode->primitivas.push_back(new Rectangle(xy1[0],xy2[0],xy1[1],xy2[1]));
}
else if (value == "triangle")
{
vector<float> xyz1, xyz2, xyz3;
extractElementsFromString(xyz1, childrenElement->Attribute("xyz1"), 3);
extractElementsFromString(xyz2, childrenElement->Attribute("xyz2"), 3);
extractElementsFromString(xyz3, childrenElement->Attribute("xyz3"), 3);
readNode->primitivas.push_back(new Triangle(xyz1[0],xyz2[0],xyz3[0],xyz1[1],xyz2[1],xyz3[1],xyz1[2],xyz2[2],xyz3[2]));
}
else if (value == "cylinder")
{
float base, top, height;
int slices, stacks;
if (childrenElement->QueryFloatAttribute("base", &base) != 0)
throw "Error parsing cylinder: no 'base' attribute";
if (childrenElement->QueryFloatAttribute("top", &top) != 0)
throw "Error parsing cylinder: no 'top' attribute";
if (childrenElement->QueryFloatAttribute("height", &height) != 0)
throw "Error parsing cylinder: no 'height' attribute";
if (childrenElement->QueryIntAttribute("slices", &slices) != 0)
throw "Error parsing cylinder: no 'slices' attribute";
if (childrenElement->QueryIntAttribute("stacks", &stacks) != 0)
throw "Error parsing cylinder: no 'stacks' attribute";
readNode->primitivas.push_back(new Cylinder(base, top, height, slices, stacks));
}
else if (value == "sphere")
{
float radius;
int slices, stacks;
if (childrenElement->QueryFloatAttribute("radius", &radius) != 0)
throw "Error parsing sphere: no 'radius' attribute";
if (childrenElement->QueryIntAttribute("slices", &slices) != 0)
throw "Error parsing sphere: no 'slices' attribute";
if (childrenElement->QueryIntAttribute("stacks", &stacks) != 0)
throw "Error parsing sphere: no 'stacks' attribute";
readNode->primitivas.push_back(new Sphere(radius, slices, stacks));
}
else if (value == "torus")
{
float inner, outer;
int slices, loops;
if (childrenElement->QueryFloatAttribute("inner", &inner) != 0)
throw "Error parsing torus: no 'inner' attribute";
if (childrenElement->QueryFloatAttribute("outer", &outer) != 0)
throw "Error parsing torus: no 'outer' attribute";
if (childrenElement->QueryIntAttribute("slices", &slices) != 0)
throw "Error parsing torus: no 'slices' attribute";
if (childrenElement->QueryIntAttribute("loops", &loops) != 0)
throw "Error parsing torus: no 'loops' attribute";
readNode->primitivas.push_back(new Torus(inner, outer, slices, loops));
}
else if (value == "noderef")
{
string childid = childrenElement->Attribute("id");
if (childid.empty())
throw "Error parsing node: no noderef 'id' attribute";
cout << "\tnoderef id:" << childid << endl;
readNode->children.push_back(childid);
}
else if (value == "plane")
{
int parts;
if (childrenElement->QueryIntAttribute("parts", &parts) != 0)
throw "Error parsing node: no plane 'parts' attribute";
readNode->primitivas.push_back(new Plane(parts));
}
else if (value == "patch")
{
int order, partsU, partsV;
string compute = childrenElement->Attribute("compute");
if (childrenElement->QueryIntAttribute("order", &order) != 0 || childrenElement->QueryIntAttribute("partsU", &partsU) != 0 || childrenElement->QueryIntAttribute("partsV", &partsV) || compute.empty())
throw "Error parsing patch attributes";
TiXmlElement *controlpoint = childrenElement->FirstChildElement();
float xx, yy, zz;
Patch *patch = new Patch(order, partsU, partsV, compute);
while (controlpoint)
{
if (controlpoint->QueryFloatAttribute("xx", &xx) != 0 || controlpoint->QueryFloatAttribute("yy", &yy) || controlpoint->QueryFloatAttribute("zz", &zz))
throw "Error parsing animation: no controlpoint attributes";
patch->addControlPoint(xx, yy, zz);
controlpoint = controlpoint->NextSiblingElement();
}
readNode->primitivas.push_back(patch);
}
else if (value == "vehicle")
{
readNode->primitivas.push_back(new Vehicle);
}
else if (value == "waterline")
{
string heightmap = childrenElement->Attribute("heightmap"), texturemap = childrenElement->Attribute("texturemap"), fragmentshader = childrenElement->Attribute("fragmentshader"), vertexshader = childrenElement->Attribute("vertexshader");
if (heightmap.empty() || texturemap.empty() || fragmentshader.empty() || vertexshader.empty())
throw "Error parsing waterline attributes";
readNode->primitivas.push_back(new Waterline(heightmap, texturemap, fragmentshader, vertexshader));
}
else if (value == "mountain")
{
string heightmap = childrenElement->Attribute("heightmap"), texturemap = childrenElement->Attribute("texturemap"), fragmentshader = childrenElement->Attribute("fragmentshader"), vertexshader = childrenElement->Attribute("vertexshader");
if (heightmap.empty() || texturemap.empty() || fragmentshader.empty() || vertexshader.empty())
throw "Error parsing waterline attributes";
readNode->primitivas.push_back(new Mountain(heightmap, texturemap, fragmentshader, vertexshader));
}
else if (value == "board")
{
int size;
if (childrenElement->QueryIntAttribute("size", &size) != 0)
throw "Error parsing Board: no 'size' attribute";
Board *board = new Board(size);
readNode->primitivas.push_back(board);
scene.board = board;
}
childrenElement = childrenElement->NextSiblingElement();
}
this->scene.addNode(id, readNode);
node = node->NextSiblingElement();
}
}
Parser::Parser(char *filename)
{
string path = filename;
unsigned found = path.find_last_of("/\\");
if(found!=string::npos)
this->path = path.substr(0,found+1); //guarda o caminho para o ficheiro yaf (para usar no caminho das texturas)
//INIT Scene
this->scene = * new Scene();
// Read XML from file
doc=new TiXmlDocument( filename );
bool loadOkay = doc->LoadFile();
if ( !loadOkay )
{
string message = "Could not load file '";
message+=filename;
message+="'!. Error='";
message+=doc->ErrorDesc();
message+="'. Exiting.\n";
throw message;
}
yafElement = doc->FirstChildElement( "yaf" );
if (yafElement == NULL)
throw "Main yaf block element not found! Exiting!\n";
parseGlobals();
parseCameras();
parseLighting();
parseTextures();
parseAppearances();
parseAnimations();
parseGraph();
interface.setScene(&this->scene);
}
Parser::~Parser()
{
delete(doc);
}
TiXmlElement *Parser::findChildByAttribute(TiXmlElement *parent,const char * attr, const char *val)
// Searches within descendants of a parent for a node that has an attribute _attr_ (e.g. an id) with the value _val_
// A more elaborate version of this would rely on XPath expressions
{
TiXmlElement *child=parent->FirstChildElement();
int found=0;
while (child && !found)
if (child->Attribute(attr) && strcmp(child->Attribute(attr),val)==0)
found=1;
else
child=child->NextSiblingElement();
return child;
}
bool to_bool(std::string str) {
if (str.empty())
throw "Error parsing: empty string";
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
std::istringstream is(str);
bool b;
is >> std::boolalpha >> b;
return b;
} | true |
858b0eef090c7f4be29661f780bbaab610ae1d61 | C++ | meethkr/CppPrimer | /C3/323.cc | UTF-8 | 403 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <vector>
using std::vector;
int main()
{
vector<int> ivec;
int temp;
for (int i = 0; i < 10; i++)
{
std::cin >> temp;
ivec.push_back(temp);
}
for (auto it = ivec.begin(); it != ivec.end(); it++)
{
*it = *it * 2;
}
for (auto i: ivec)
std::cout << i << " ";
std::cout << std::endl;
return 0;
} | true |
e508ffba97d8a886ba4ae47462631710b02706ca | C++ | WhiZTiM/coliru | /Archive2/69/9082582e73376e/main.cpp | UTF-8 | 1,397 | 2.59375 | 3 | [] | no_license | #include <vector>
#include <unordered_map>
#include <boost/variant.hpp>
namespace libdocplus {
typedef bool Boolean;
typedef int Integer;
typedef double Real;
typedef std::vector<unsigned char> ByteBuffer;
typedef ByteBuffer String;
typedef ByteBuffer Name;
typedef ByteBuffer Stream;
class Null {};
class DictionaryWrapper;
class ArrayWrapper {
public:
typedef boost::variant<Boolean, Integer, Real, String, Name, Stream, Null, boost::recursive_wrapper<ArrayWrapper>, boost::recursive_wrapper<DictionaryWrapper>> ScalarType;
std::vector<ScalarType> Array;
};
class DictionaryWrapper {
public:
typedef boost::variant<Boolean, Integer, Real, String, Name, Stream, Null, boost::recursive_wrapper<DictionaryWrapper>, boost::recursive_wrapper<ArrayWrapper>> ScalarType;
std::unordered_map<ScalarType, ScalarType> Dictionary;
};
typedef ArrayWrapper Array;
typedef DictionaryWrapper Dictionary;
typedef boost::variant<Boolean, Integer, Real, String, Name, Stream, Null, Array, Dictionary> Object;
class PDFStreamParser {
};
}
#include <iostream>
int main() {
using namespace libdocplus;
Object b = true;
Object i = 1;
Object r = 2.0;
Object m = DictionaryWrapper();
auto d = boost::get<DictionaryWrapper>(m);
d.Dictionary[1] = 2;
} | true |
1c5303cf64d2186f0175930162010d5b098bd692 | C++ | acherian18/SIT107 | /BLINKSOS.ino | UTF-8 | 2,822 | 2.578125 | 3 | [] | no_license | void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
}
void morse()
{
//morse code for 's'- three short blinks
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(500); // wait for a half second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(500); // wait for a half second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(500); // wait for a half second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
//morse code for 'O'- that is three long blinks
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(2000); // wait for two second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(500); // wait for half second
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(2000); // wait for two seconds
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(500); // wait for a half second
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(2000); // wait for two seconds
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(500); //wait for a half second
//morse code for 'S'- three short blinks
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(500); // wait for a half second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(500); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(500); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(1000);
}
void loop()
{
morse();
}
| true |
a87985805d4cc17b48715f3ba2c09f42a65d51ec | C++ | hellsdeur/exercises-concrete-math | /src/3_3.cpp | UTF-8 | 939 | 3.609375 | 4 | [] | no_license | #include <iostream>
#include <vector>
std::vector<int> concatenar(std::vector<int> vec1, std::vector<int> vec2) {
std::vector<int> concatenacao;
concatenacao.insert(concatenacao.end(), vec1.begin(), vec1.end());
concatenacao.insert(concatenacao.end(), vec2.begin(), vec2.end());
return concatenacao;
}
int main() {
std::vector<int> input_A;
std::vector<int> input_B;
std::vector<int> ba;
int n, x;
std::cout << "Insira o tamanho da sequencia A: ";
std::cin >> n;
std::cout << "Insira os " << n << " elementos da sequencia A: ";
while (n > 0) {
std::cin >> x;
input_A.push_back(x);
--n;
}
std::cout << "Insira o tamanho da sequencia B: ";
std::cin >> n;
std::cout << "Insira os " << n << " elementos da sequencia B: ";
while (n > 0) {
std::cin >> x;
input_B.push_back(x);
--n;
}
ba = concatenar(input_B, input_A);
std::cout << ba.size() << " elementos BA: ";
for (auto i: ba) std::cout << i << " ";
}
| true |
062951c49268bfd7f45241e9798e2314904459e3 | C++ | 15cm/LeetCode | /313.super-ugly-number.hpp | UTF-8 | 519 | 2.890625 | 3 | [] | no_license | class Solution {
public:
int nthSuperUglyNumber(int n, vector<int>& primes) {
int m = primes.size();
vector<int> ptr(m), f(n);
f[0] = 1;
for(int i = 1; i < n; i++) {
f[i] = INT_MAX;
for(int j = 0; j < m; j++) {
f[i] = min(f[i], f[ptr[j]] * primes[j]);
}
for(int j = 0; j < m; j++) {
if(f[i] == f[ptr[j]] * primes[j])
ptr[j]++;
}
}
return f[n-1];
}
};
| true |
a98061c4dbb4de41e91dbc33688323646cd5818c | C++ | jerryhanhuan/test-code-backup | /UI/Bkwin/bkwindemo/branches/FileSearch.h | GB18030 | 2,603 | 2.625 | 3 | [] | no_license | /********************************************************************
created: 2008/10/17
filename: FileSearch.h
file base: FileSearch
file ext: h
author: huchao
purpose: Windows ļķװ
*********************************************************************/
#pragma once
#include <Windows.h>
#include <atlstr.h>
#include <vector>
#include <cassert>
// ļȫ·Ľṹ
typedef struct tagSearchFileInfo
{
CString strFullPath; // ļȫ·
}SearchFileInfo, *pSearchFileInfo;
typedef std::vector<pSearchFileInfo> vecFileInfo; // ļȫ· Vector
class CFileSearch
{
public:
CFileSearch(void);
~CFileSearch(void);
public:
// ܣʼļ
// ֵFALSE--ʧܣɹ
BOOL InitSearch();
// ܣʼļ
// ֵFALSE--ʧܣɹ
BOOL UnInitSearch();
// ܣǷҪļ
// ˵
// bIsSearchChildTRUE--ҪFALSE--Ҫ
// ֵFALSE--ʧܣɹ
BOOL SetSearchChildDirectory(IN BOOL bIsSearchChild);
// ܣһضļյб
// ˵
// strFileFullPathļľ·
// ֵFALSE--ʧܣɹ
BOOL AddFileToSearchList(IN const CString& strFileFullPath);
// ܣҪļ
// ˵
// strFullPathļеľ·
// ֵFALSE--ʧܣɹ
BOOL AddSearchDiretory(IN const CString& strFullPath);
// ܣļ
// ֵFALSE--ʧܣɹ
BOOL DoSearch();
// ܣȡļб
// ˵
// vecFilesļбVectorڴ˴ãעֹ౻
// ֵFALSE--ʧܣɹ
BOOL GetSearchResultList(OUT vecFileInfo& vecFiles);
protected:
typedef enum enumSearchStatus
{ // ļ״̬
enumStatus_Stoped = 0, // δʼ
enumStatus_Inited, // ʼ
enumStatus_Search, //
}SearchStatus;
BOOL FreeItemMemory();
private:
BOOL _FindFiles();
BOOL _AddFindFilesToList(const CString& strDirectory);
SearchStatus m_CurSearchStatus; // ǰ״̬
vecFileInfo m_vecFileInfo; // ļб
BOOL m_bIsSearchChildDiretory; // Ƿļ
std::vector<CString> m_vecSearchDir; // Ҫļб
};
| true |
36c89d686b14620066a15a4c9147ab1bca1bb885 | C++ | MirekJ/SC | /scOOP/mc/pairenergycalculator.h | UTF-8 | 8,105 | 2.921875 | 3 | [] | no_license | /** @file pairenergycalculator.h*/
#ifndef PAIRENERGYCALCULATOR_H
#define PAIRENERGYCALCULATOR_H
/*
* Calculates energy of a pair of Particle
* One particle stored as a internal state
*/
#include "../structures/topo.h"
#include "../structures/Conf.h"
class PairEnergyCalculator
{
private:
Particle* part1;
Particle* part2;
ConList* conlist;
/*
* Parameters pased to functions of interaction calculation
*/
double dist; // closest distance
Vector distvec; // vector of closes distance
Vector r_cm; // Vector between centres of mass from part2 to part1
double distcm; // distance between center of masses
double dotrcm; // square size of r_cm
double contt; // closest point on spherocylinder to sphere
GeoBase* pbc; // box size
double (PairEnergyCalculator::*intFCE[MAXT][MAXT])();
public:
PairEnergyCalculator(GeoBase* pbc) : pbc(pbc) {
initIntFCE();
}
double operator() (Particle* part1, Particle* part2, ConList* conlist=NULL);
/**
* @brief init_intfce Initializes the array with the pointers to the energy function
*/
void initIntFCE();
private:
/**
* @brief Determines angle energy between spherocylinders
*/
double angleEnergy();
/**
* @brief Determines bond energy
*/
double bondEnergy();
/**
* @brief harmonic function for calculation of harmonic potential
* @param aktualvalue
* @param eqvalue
* @param springconst
* @return
*/
double harmonicPotential(double aktualvalue, double eqvalue, double springconst) {
return springconst*(aktualvalue-eqvalue)*(aktualvalue-eqvalue)*0.5;
}
/**
* @brief calculates scaling for parallel and antiparallel interactions
* @param epsilonparallel
* @param dir1
* @param dir2
* @return
*/
double scparallel(double epsilonparallel, Vector dir1, Vector dir2);
/**
* @brief enoexist Indicates not yet programmed interaction
* @return
*/
double eNoExist();
/**
* @brief e_psc_psc Determines total energy of two spherocylinders type PSC PSC
* @return energy
*/
double ePscPsc();
/**
* @brief eattractive_psc_psc Determines attractive energy of two spherocylinders type PSC PSC
* @param patchnum1
* @param patchnum2
* @return
*/
double eattractivePscPsc(int patchnum1,int patchnum2);
/**
* @brief e_cpsc_cpsc Determines total energy of two spherocylinders of type 3 -cylindrical psc -CPSC
* @return
*/
double eCpscCpsc();
/**
* @brief eattractive_cpsc_cpsc Determines attractive energy of two spherocylinders of type 3 -cylindrical psc -CPSC
* @param patchnum1
* @param patchnum2
* @return
*/
double eattractiveCpscCpsc(int patchnum1, int patchnum2);
/**
* @brief e_psc_cpsc Determines total energy of spherocylinders type PSC and CPSC
* @return
*/
double ePscCpsc();
/**
* @brief eattractive_psc_cpsc Determines attractive energy of spherocylinders type PSC and CPSC
* @param patchnum1
* @param patchnum2
* @return
*/
double eattractivePscCpsc(int patchnum1,int patchnum2);
/**
* @brief e_spa_sca Determines total energy of spherocylinder type 1 and sphere type 11
* @return
*/
double eSpaSca();
/**
* @brief e_psc_spa Determines total energy of spherocylinder type 2 and sphere type 11
* @return
*/
double ePscSpa();
/**
* @brief eattractive_psc_spa Determines attractive energy of spherocylinder type 2 and sphere type 11
* @param patchnum1
* @return
*/
double eattractivePscSpa(int patchnum1);
/**
* @brief e_cpsc_spa Determines total energy of spherocylinder type 3 and sphere type 11
* @return
*/
double eCpscSpa();
/**
* @brief eattractive_cpsc_spa Determines attractive energy of spherocylinder type 3 and sphere type 11
* @param patchnum1
* @return
*/
double eattractiveCpscSpa(int patchnum1);
/**
* @brief e_2sca_or_2spa Determines total energy of two spherocylinders type 11
* @return
*/
double e2ScaOr2Spa();
/**
* @brief e_spn_or_scn Determines total energy with purely repulsive types
* @return
*/
double eSpnOrScn();
/**
* @brief closestdist closest distance calculation
*/
void closestDist();
/**
* @brief fanglscale a = r_ij * n_i
* @param a
* @param which
* @return
*/
double fanglScale(double a, int which);
/**
* @brief erepulsive Determines repulsive energy of two spherocylinders
* @return
*/
double eRepulsive();
/**
* @brief mindist_segments Find closest distance between line segments and return its vector
gets orientations and lengths of line segments and the vector connecting
their center os masses (from vec1 to vec2)
* @param dir1
* @param halfl1
* @param dir2
* @param halfl2
* @param r_cm
* @return
*/
Vector minDistSegments(double halfl1, double halfl2, Vector r_cm);
/**
* @brief psc_intersect Calculate intersections of sc2 with a patch of sc1 and return them in
* @param halfl1
* @param halfl2
* @param r_cm
* @param intersections
* @param which
* @param patchnum
* @return
*/
int pscIntersect(Particle* part1, Particle* part2, double halfl1, double halfl2, Vector r_cm,
double intersections[5], int which, int patchnum);
/**
* @brief test_intrpatch Find if vector vec has angular intersection with patch of sc1
* @param part1
* @param vec
* @param cospatch
* @param ti
* @param intersections
* @param patchnum
* @return
*/
int testIntrPatch(Particle * part1, Vector vec, double cospatch,
double ti, double intersections[5],int patchnum);
/**
* @brief find_intersect_plane Find intersections of SC and plane defined by vector w_vec.and returns number of them
* @param part1
* @param part2
* @param halfl2
* @param r_cm
* @param w_vec
* @param rcut
* @param cospatch
* @param intersections
* @return
*/
int findIntersectPlane(Particle * part1, Particle * part2, double halfl2,
Vector r_cm, Vector w_vec, double cospatch, double intersections[5]);
/**
* @brief cpsc_intersect Calculate intersections of sc2 with a patch of sc1
and return them in this works for cylindrical psc -CPSC
* @param part1
* @param part2
* @param halfl1
* @param halfl2
* @param r_cm
* @param intersections
* @param which
* @param patchnum
* @return
*/
int cpscIntersect(Particle * part1, Particle * part2, double halfl1, double halfl2, Vector r_cm,
double intersections[5], int which, int patchnum);
/**
* @brief find_intersect_planec Find intersections of plane defined by vector w_vec.
and returns number of them - for cylindrical psc -CPSC
* @param part1
* @param part2
* @param halfl
* @param r_cm
* @param w_vec
* @param cospatch
* @param intersections
* @return
*/
int findIntersectPlanec(Particle * part1, Particle * part2, double halfl,
Vector r_cm, Vector w_vec, double cospatch, double intersections[5]);
double angleEnergyAngle2( Particle &p1, Particle &p2);
};
#endif // PAIRENERGYCALCULATOR_H
| true |
36a7fefb4303c2b689d8ac3c838f6637f8411e63 | C++ | jocanas/projects | /rgb.cpp | UTF-8 | 2,053 | 2.78125 | 3 | [] | no_license | const int pins[6] = {3,5,6,9,10,11};
int color[3] = {255,255,255};
void setup(){
for(int i = 0; i < 6; i++){
pinMode(pins[i], OUTPUT);
}
randomSeed(analogRead(0));
Serial.begin(9600);
}
void loop(){
// int color[3] = { 255, 255, 255 };
int incomingByte = 0;
if(Serial.available() > 9){
incomingByte = Serial.read() - 48;
if(incomingByte == 3){
for(int i = 0; i<3;i++){
color[i] = 100 * (Serial.read()-48);
color[i] = color[i] + 10 * (Serial.read() - 48);
color[i] = color[i] + (Serial.read() - 48);
}
}
else if(incomingByte == 1){
color[0] = random(256);
color[1] = random(256);
color[2] = random(256);
}
Serial.print("color chosen : ");
Serial.print(color[0]);
Serial.print(" ");
Serial.print(color[1]);
Serial.print(" ");
Serial.println(color[2]);
Serial.flush();
}
blinkColor(color);
// for(int i = 0; i < 100; i++){
// color[0] = random(256);
// color[1] = random(256);
// color[2] = random(256);
// //fadeColor(color);
// blinkColor(color);
// delay(50);
//}
// for(int i=0; i<1000;i++){
// for(int j=0; j < 3; j++){
// color[0] = 0;
// color[1] = 0;
// color[2] = 0;
// color[j] = 255;
// blinkColor(color);
// delay(50);
// }
//}
}
void fadeColor(int color[3]){
int bright = color[0];
for(int i = 0; i < 3; i++){
if(bright > 255)
bright=255;
else if(bright < 0)
bright=0;
color[i] = bright;
bright = color[i+1];
}
for(int j=0; j < 3; j++){
for(int b = 0; b <= color[j]; b++){
analogWrite(pins[j], b);
analogWrite(pins[j+3], b);
delay(25);
}
}
}
void blinkColor(int color[3]){
int bright = color[0];
for(int i = 0; i < 3; i++){
if(bright > 255)
bright=255;
else if(bright < 0)
bright=0;
color[i] = bright;
bright = color[i+1];
}
for(int j=0; j < 3; j++){
analogWrite(pins[j], color[j]);
analogWrite(pins[j+3], color[j]);
// delay(25);
}
}
| true |
3e07394f57a0a52bd9e794ab284d47797690754f | C++ | CMcFeaters/light_monitor | /client_test_photo_resist/array_wifi.h | UTF-8 | 1,093 | 2.65625 | 3 | [] | no_license | /*
test.h - library for testing libraries
*/
#ifndef array_wifi_h
#define array_wifi_h
#define BED_TIME 2100
#define WAKE_TIME 600
#include <WiFiClient.h>
#include "Arduino.h"
class my_wifi
{
public: //publically accessible stuff
my_wifi(char* ssid,char* pw, char* host,int port, IPAddress ip, IPAddress gateway); //initiate, assigns all wifi data to private variables
void setup_wifi(); //configures the wifi and
void connect_to_server(); //connect to the wifi server
void static_IP(IPAddress my_IP,IPAddress my_gateway); //setup the static IP
void send_data(uint16_t* data,int size,int sleep_time, bool night_mode); //sends the pointed to data to the location
bool send_packet(WiFiClient client, String data, bool night_mode);//sends an individual packet
String pack_data(uint16_t* data, int size,int sleep_time);//returns a string that details the packet and contains the data
private:
char* _my_ssid;
char* _my_pw;
char* _host;
int _port;
IPAddress _my_IP;
IPAddress _my_gateway;
//default subnet
};
#endif
| true |
af62baa698c9984fa4540ff6d0f146246fea80ba | C++ | Iximiel/Tesina-Calcolo2 | /CrankSolverDD.cpp | UTF-8 | 3,796 | 2.609375 | 3 | [] | no_license | #include "CrankSolver.hpp"
#include <iostream>
#include <fstream>
#ifdef DEBUG
#include <cmath>//per gli abs
void wait(){
cout<< "Premi enter per continuare."<<endl;
cin.get();
}
#endif //DEBUG
using namespace std;
CranckSolver::CranckSolver(const tridiag &mat, int Ns, int Nt,/* std::string opt,*/ double CCi, double CCe)
:CS_mat(mat){
/* options = opt;
if(options == "DD")
CCfstep= CCestep = 1;
else
CCfstep= CCestep = 0;*/
//CS_mat = mat;
CS_ns = Ns;
CS_nt = Nt;
CS_cci = CCi;
CS_cce =CCe;
CS_data = new Var [CS_ns * CS_nt];
CS_step = 0;
CS_mat.create_h();
}
CranckSolver::~CranckSolver(){
//delete h;
delete CS_data;
}
void CranckSolver::SetInitialState(Var* initialVector){
for(int i=0;i<CS_ns;i++)
CS_data[i] = initialVector[i];
CS_step =1;
#ifdef DEBUG
cout << "Acquisite condizioni iniziali"<< endl;
#endif //DEBUG
}
bool CranckSolver::doStep(){
if(CS_step ==0){
cout << "Non ho acquisito le condizioni iniziali"<<endl;
return false;
}else if(CS_step >= CS_nt){
cout << "Ho fatto tutti i passi previsti"<<endl;
return false;
}else{
processCC();
Stepper();
CS_step++;
return true;
}
}
Var CranckSolver::getPoint(int t, int x){
return CS_data[t*CS_ns+x];
}
void CranckSolver::Stepper(){
int t = CS_step*CS_ns; //dummy per comodita`
int tm1 = (CS_step-1)*CS_ns; //dummy per comodita`
Var *p = new Var [CS_ns];
//0 e` l'indice delle condizioni al contorno, se uso Dirichlet 0 serve a non aggiungere eccezioni all'algoritmo
//la spiegazione e` in create_h() di Tridiag.cpp
//preparo del vettore delle p[]
//if(options ==" DD")
p[0] = 0;
/*else{
p[0] = CS_mat.pi(0,0,CS_mat.bi(0,0,
CS_data[tm1],CS_data[tm1+1]););
}*/
for(int i=1;i<CS_ns-1;i++){
//calcolo il valore di b[i]
Var bi = CS_mat.bi(i,CS_data[tm1+i-1],
CS_data[tm1+i],CS_data[tm1+i+1]);
//if(options ==" DD"){
//aggiungo le CC, non penso che questi if rallentino eccessivamente il calcolo
if(i==1)
bi-=CS_mat.GetA(i)*CS_cci;// so che h[0] = 0, p[0] = 0
else if(i==CS_ns-2)
bi-=CS_mat.GetC(i)*CS_cce;
//}
p[i] = CS_mat.pi(i,p[i-1],bi);
#ifdef DEBUG
if(abs(CS_ns/2.-i)<=5){
cout << i <<": b[i] = "<< bi <<" p[i]= "<<p[i];//<<endl;
cout << "\t" << (CS_mat.d[i]-CS_mat.a[i]*h[i-1])<< " " << h[i-1]<<endl;
}
#endif //DEBUG
}
//ora procedo finalmente con l'assegnare i risultati
CS_data[t+CS_ns-2] = p[CS_ns-2];
for(int i=CS_ns-3;i>0;i--){
CS_data[t+i] = p[i] - CS_mat.H(i) * CS_data[t+i+1];
//da pi = xi + hi x(i+1)
#ifdef DEBUG
if(abs(CS_ns/2.-i)<=5)
cout << i <<": p[i]= "<<p[i] <<",x[i](t-1)="<<CS_data[tm1+i]
<<"=>x[i](t)="<<CS_data[t+i]<<endl;
#endif //DEBUG
}
#ifdef DEBUG
wait();
#endif //DEBUG
}
bool CranckSolver::prepareTGraph2D(string filename, double timestep, double spacestep, int timespan, int spacespan){
if(CS_step <= 1){
cout << "Non ho svolto alcun calcolo, non preparo il file \""
<< filename <<"\"" << endl;
return false;
}else{
ofstream outfile(filename.c_str());
if(!outfile.is_open()){
cout << "Non sono riuscito ad aprire il file \""
<< filename <<"\"" << endl;
return false;
}else{
for(int i= 0;i<CS_nt/1;i+=timespan){
int t = CS_ns * i;
for(int j = 0;j< CS_ns ;j+=spacespan){
outfile << i*timestep << "\t" << j*spacestep << "\t"
<< CS_data[t+j]<<endl;
}
}
cout << "Ho salvato i dati sul file \""
<< filename <<"\"" << endl;
return true;
}
}
}
void CranckSolver::processCC(){
int t = CS_step*CS_ns; //dummy per comodita`
// int tm1 = (CS_step-1)*CS_ns; //dummy per comodita`
// if(options == "DD"){
CS_data[t+0] = CS_cci;
CS_data[t+CS_ns-1] = CS_cce;
//}
}
| true |
a1f2873897a0625b4bc66fb3586ce9e5c97624a2 | C++ | pauzabalgoitia/tarea-algoritmos- | /numeros iguales.cpp | UTF-8 | 325 | 2.640625 | 3 | [] | no_license | #include<conio.h>
#include<stdio.h>
#include<iostream>
float a,b;
main(){
printf("indique el primer numero");
scanf("%f", &a);
printf("indique el segundo numero");
scanf("%f", &b);
if (a==b)
{
printf("los numeros son iguales");
}
else
{
printf("los numeros son diferentes");
}
getche();
}
| true |
273f903d94109978cf3beb38735b0defb519d7b7 | C++ | jkjan/Baekjoon | /1495.cpp | UTF-8 | 897 | 2.546875 | 3 | [] | no_license | #include <iostream>
#define MAX_VOL 1001
#define MAX_SONG 101
using namespace std;
int main() {
int N, S, M;
int dp[MAX_SONG][MAX_VOL];
int V[MAX_SONG];
cin >> N >> S >> M;
fill(&dp[0][0], &dp[MAX_SONG-1][MAX_VOL], -1);
for (int i = 1; i <= N; i++) {
cin >> V[i];
}
dp[0][S] = S;
V[0] = S;
for (int i = 1; i <= N; i++) {
for (int j = 0; j <= M; j++) {
if (dp[i-1][j] == -1)
continue;
int added = dp[i-1][j] + V[i];
int subtracted = dp[i-1][j] - V[i];
if (added <= M) {
dp[i][added] = added;
}
if (subtracted >= 0) {
dp[i][subtracted] = subtracted;
}
}
}
int maxVol = -1;
for (int i = 0; i <= M; i++) {
maxVol = max(maxVol, dp[N][i]);
}
cout << maxVol;
return 0;
} | true |
7d9c241af4aa999f1ba711904b1b8267fbf42185 | C++ | GaaH/VegetableCrushSaga | /src/views/StartView.cpp | UTF-8 | 1,187 | 2.734375 | 3 | [] | no_license | #include <SFML/Window/Event.hpp>
#include "views/StartView.hpp"
#include "controllers/GameController.hpp"
#include "Globals.hpp"
StartView::StartView(Controller *controller, sf::RenderWindow &window):
View(controller),
window(window)
{
auto font = globals.getFontManager().getResource("wombo_font");
start_text.setFont(*font);
start_text.setColor(sf::Color::Green);
start_text.setCharacterSize(180);
start_text.setString("Vegetable Crush Saga");
start_text.setPosition(40, window.getSize().y / 3);
}
StartView::~StartView()
{
}
void StartView::clear()
{
window.clear(sf::Color::White);
}
void StartView::draw()
{
window.draw(start_text);
}
void StartView::display()
{
window.display();
}
void StartView::sendEvents()
{
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
globals.shutdown();
running = false;
break;
default:
break;
}
}
}
void StartView::loop()
{
start_clock.restart();
while (running)
{
sendEvents();
if (start_clock.getElapsedTime().asMilliseconds() > 1500)
{
globals.setCurrentView("Game");
running = false;
}
clear();
draw();
display();
}
}
| true |
ef6fcebe8487c3c38cceb8c243d17b6135b3f5a3 | C++ | dcoded2/tftp-client | /src/tftp/packet/data.cpp | UTF-8 | 812 | 2.609375 | 3 | [] | no_license | #include <tftp/packet/data.h>
namespace tftp {
namespace packet {
data::data () : packet (Opcode::OP_DTA) {}
data::data (char* buf) : packet (Opcode::OP_DTA) {
unpack (buf);
}
// data::data (char* buf, uint16_t size) : packet (Opcode::OP_DTA) {
// unpack (buf, size);
// }
uint16_t data::pack (char* buf) const {
char* it = buf;
serializer <uint16_t> (it, this->opcode);
serializer <uint16_t> (it, index);
serializer <std::string> (it, text);
return (it - buf);
}
bool data::unpack (char* it) {
deserializer <uint16_t> (it, (uint16_t*)&this->opcode);
if (opcode != Opcode::OP_DTA)
return false;
deserializer <uint16_t> (it, &index);
deserializer <std::string> (it, &text);
last_ = (text.size () < 512);
return true;
}
bool data::last () const {
return last_;
}
}} | true |
7e2fdf3ead1c26919e308d2a162a3fe938f8463d | C++ | hys2rang/WHrkTLQKF | /samsungProblems/2DarrayCalc.cpp | UTF-8 | 2,027 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <list>
#include <vector>
#include <algorithm>
#pragma warning(disable:4996)
using namespace std;
const int MAX = 110;
struct Num {
int cnt, n;
};
vector<int> calc(int arr[], int size);
bool compare(Num a, Num b);
int main()
{
int cnt;
int cy = 3, cx = 3;
int r, c, k;
int arr[MAX][MAX] = { 0, };
cin >> r >> c >> k;
for (int i = 0; i < cy; i++) {
for (int j = 0; j < cx; j++) {
cin >> arr[i][j];
}
}
for(cnt=0;cnt<101;cnt++) {
int tmp[MAX][MAX] = { 0, };
if (arr[r-1][c-1] == k) {
break;
}
if(cy>100){
cy = 100;
}
if(cx>100){
cx=100;
}
if (cy >= cx) {
//R연산
int mx = 0;
for (int i = 0; i < cy; i++) {
vector<int> res = calc(arr[i],cx);
int j = 0;
for (int k = 0; k < res.size() && k < 100; k++) {
tmp[i][j++] = res[k];
}
mx = max(mx, j);
}
cx = mx;
}
else {
//C연산
int my = 0;
for (int i = 0; i < cx; i++) {
int ty[MAX] = { 0, };
for (int j = 0; j < cy; j++) {
ty[j] = arr[j][i];
}
vector<int> res = calc(ty, cy);
int j = 0;
for (int k = 0; k < res.size() && k < 100; k++) {
tmp[j++][i] = res[k];
}
my = max(my, j);
}
cy = my;
}
for (int i = 0; i < cy; i++) {
for (int j = 0; j < cx; j++) {
arr[i][j] = tmp[i][j];
}
}
}
if (cnt == 101) {
cnt = -1;
}
cout << cnt;
}
vector<int> calc(int arr[], int size)
{
int cnt[MAX] = { 0, };
int mnum = 0;
vector<Num> numbers;
vector<int> res;
for (int i = 0; i < size; i++) {
cnt[arr[i]]++;
mnum = max(mnum, arr[i]);
}
for (int i = 1; i <= mnum; i++) {
if (cnt[i]) {
numbers.push_back({ cnt[i],i });
}
}
sort(numbers.begin(), numbers.end(),compare);
for (int i = 0, j = 0; i < numbers.size(); i++,j+=2) {
res.push_back(numbers[i].n);
res.push_back(numbers[i].cnt);
}
return res;
}
bool compare(Num a, Num b)
{
if (a.cnt != b.cnt) {
return a.cnt < b.cnt;
}
else if (a.cnt == b.cnt) {
return a.n < b.n;
}
}
| true |
c66115f6013c29ed8bec2657e6e78372ad31b19e | C++ | avocado-bytes/light-controller | /light.ino | UTF-8 | 2,529 | 3.046875 | 3 | [] | no_license |
const int minimum = 400;
const int lightSensor = A0;
const int sensitivity = A1;
const int relayOutput = 7;
const byte bufferMax = 127;
byte buffer = 0;
void setup() {
pinMode(lightSensor, INPUT);
pinMode(sensitivity, INPUT);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(relayOutput, OUTPUT);
Serial.begin(9600);
}
void loop() {
delay(1000);
int lightLevel = analogRead(lightSensor);
int sensitivitySettings = analogRead(sensitivity);
int limit = calculateLimit(lightLevel, sensitivitySettings, minimum);
bool limitReached = lightLevel > limit;
bool ON = buffer == bufferMax;
updateBuffer(limitReached);
printDebugMessage(lightLevel, limitReached, sensitivitySettings, limit, ON);
if (ON) {
digitalWrite(relayOutput, LOW);
} else {
digitalWrite(relayOutput, HIGH);
}
}
/**
* The buffer serves to smooth out oscillating light levels.
* The light level might oscilate around the intended light level limit
* and this might cause the light controller to flicker uncontrollably.
* If the limit for light being lit has been reached a 1 is written to the
* right most bit of the buffer. Each cycle the buffer is right shifted which
* causes the byte value of the buffer to change. The light will only turn on if the
* byte has all of its bits set. Oscillating values will never allow
* the buffer to reach its max value and will not cause the light to turn on.
**/
void updateBuffer(bool limitReached) {
if (limitReached) {
buffer = buffer | B10000000;
}
buffer = buffer >> 1;
}
void printDebugMessage(int lightLevel, int limitReached,
int sensitivitySettings, int limit, bool on) {
Serial.print("Light level:");
Serial.println(lightLevel);
Serial.print("Limit reached:");
Serial.println(limitReached);
Serial.print("Light ON:");
Serial.println(on);
Serial.print("Sensitivity: ");
Serial.println(sensitivitySettings);
Serial.print("New limit: ");
Serial.println(limit);
Serial.print("Buffer: ");
Serial.println(buffer);
Serial.println("-----------------------");
}
/**
* The Arduino's ADC module has the value range of 0 - 1024. However to achieve more
* sensitivity in the region of values that is typical for light conditions that occur
* it has been limited to minimal value that is set as constant at the top of the program.
**/
int calculateLimit(int lightLevel, int sensitivitySettings, int minimum) {
float ratio = ((float)sensitivitySettings)/((float)1024);
return ((1024 - minimum) * ratio) + minimum;
}
| true |
872019365b40d5fcaaa0bd7a2511b0e1143c33ae | C++ | sherlockwxl/cs343 | /a4/q1voter.cc | UTF-8 | 1,191 | 2.75 | 3 | [] | no_license | #include "q1voter.h"
#include "q1printer.h"
#include <iostream>
extern MPRNG mprng;
extern bool printmode;
// class constructor for voter
Voter::Voter( unsigned int id, unsigned int nvotes, TallyVotes & voteTallier, Printer & printer ):
id(id), nvotes(nvotes), voteTallier(voteTallier), printer(printer){};
// main function
void Voter::main(){
// yield 0 - 19 first
yield(mprng(19));
//print start message
for(unsigned int i = 0 ; i < nvotes; i++){
if(printmode)
printer.print(id, States::Start);
//second yield
yield(mprng(4));
//random a vote
TallyVotes::Ballot vote = cast();
TallyVotes::Tour voteres;
try{// vote will throw failed when fail to form a group
// vote
voteres = voteTallier.vote(id, vote);
yield(mprng(4));
if(printmode)
printer.print(id, States::Finished, voteres);
} catch (TallyVotes::Failed &){
if(printmode)
printer.print(id, Voter::States::Failed);
break;
}
}
voteTallier.done();
if(printmode)
printer.print(id, States::Terminated);
}
| true |
78d0f704a1f49442455dc0840cc2d4f925586c1b | C++ | RunaticMoon/BOJ | /백준/2675 문자열 반복.cpp | UTF-8 | 397 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main() {
int T, loop_number;
string str, newstr;
cin >> T;
for (int test_case = 0; test_case < T; ++test_case) {
cin >> loop_number >> str;
newstr = "";
for (auto it = str.begin(); it != str.end(); ++it) {
for (int i = 0; i < loop_number; ++i) {
newstr += *it;
}
}
cout << newstr << '\n';
}
return 0;
} | true |
ee14fd11c7a7ebe8d679d85a78ae7cfe92aa3ba8 | C++ | TanavShah/SPOJ | /cpp_codes/bandw.cpp | UTF-8 | 725 | 2.640625 | 3 | [] | no_license | // Saheb Aaje Su Karvana?
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
while(1)
{
string s1,s2;
cin >> s1 >> s2;
if((s1 == "*") && (s2 == "*"))
{
break;
}
vector<int> pos;
for(int i = 0 ; i < s1.length() ; i++)
{
if(s1.at(i) != s2.at(i))
{
pos.push_back(i);
}
}
int cnt = 1;
if(pos.size() == 0)
{
printf("%d \n" , 0);
continue;
}
if(pos.size() == s1.length())
{
printf("%d \n" , 1);
continue;
}
for(int i = 0 ; i < pos.size() - 1 ; i++)
{
if(pos[i + 1] != pos[i] + 1)
{
cnt++;
}
}
// if(pos[pos.size() - 1] == s1.length())
// {
// cnt++;
// }
printf("%d \n" , cnt);
}
return 0;
}
| true |
74351117bf504c1cf7ef35ae18b2f35686bf9cbb | C++ | mostafaelsayyad/ProblemSolving | /C++/UVA/UVA_summing digits.cpp | UTF-8 | 573 | 2.6875 | 3 | [] | no_license | #include<iostream>
#include<sstream>
using namespace std;
int conv(string st)
{
long long result;
stringstream(st) >> result;
return result;
}
string converttostring(long long num)
{
string s;
//SS ss;
stringstream ss;
ss<<num;
ss>>s;
return s;
}
int main()
{
string str;
while(cin>>str)
{
if(str=="0")
break;
bool ok=false;
long long sum=99;
int loop=0;
while(sum>10)
{
if(loop!=0)
str=converttostring(sum);
sum=0;
for(int i=0;i<str.size();i++)
{
sum+=(str[i]-48);
}
loop++;
}
cout<<sum<<endl;
}
return 0;
}
| true |
b2ba9b5721a3ed9f4b015fb9ce9dae646727a9dc | C++ | mfazekas/cpp_primitives_benchmark | /Tests/MallocTests.cpp | UTF-8 | 1,974 | 2.640625 | 3 | [] | no_license |
#include "PerfTestRegistry.h"
#include "PerfTestBase.h"
#include <stdlib.h>
#include <sstream>
template <int size>
class MallocFreeCallPerfTest : public PerfTestBase {
public:
virtual int perform (int& rounds_,int fourtytwo_,int random_) {
int result = 0;
for (int i = 0; i < rounds_; ++i) {
void* x = malloc(fourtytwo_-42+size);
result += reinterpret_cast<ptrdiff_t>(x);
free(x);
}
return result;
}
std::string name() const {
std::ostringstream os;
os << "mallocfree-" << size;
return os.str();
}
};
template <int size,int batchsize>
class LotMallocFreeCallPerfTest : public PerfTestBase {
public:
virtual int perform (int& rounds_,int fourtytwo_,int random_) {
int result = 0;
rounds_ -= rounds_ % batchsize;
for (int i = 0; i < rounds_/batchsize; ++i) {
void* ptrs[batchsize];
for (int j =0; j < batchsize; ++j) {
ptrs[j] = malloc(fourtytwo_-42+size);
}
result += reinterpret_cast<ptrdiff_t>(ptrs[0]);
for (int j =0; j < batchsize; ++j) {
free(ptrs[j]);
}
}
return result;
}
std::string name() const {
std::ostringstream os;
os << "mallocfree-" << size << "batch-" << batchsize;
return os.str();
}
};
PERFTEST_AUTOREGISTER(MallocPerfTest1,new MallocFreeCallPerfTest<10>());
PERFTEST_AUTOREGISTER(MallocPerfTest2,new MallocFreeCallPerfTest<100>());
PERFTEST_AUTOREGISTER(MallocPerfTest3,new MallocFreeCallPerfTest<1024>());
PERFTEST_AUTOREGISTER(MallocPerfTest4,new MallocFreeCallPerfTest<8192>());
PERFTEST_AUTOREGISTER(MallocFreePerfTest1,(new LotMallocFreeCallPerfTest<10,1024>()));
PERFTEST_AUTOREGISTER(MallocFreePerfTest2,(new LotMallocFreeCallPerfTest<100,1024>()));
PERFTEST_AUTOREGISTER(MallocFreePerfTest3,(new LotMallocFreeCallPerfTest<1024,1024>()));
| true |
ec7ab64d4540ca8aa1a96561f0db6e3e9448ff02 | C++ | NilsKarlbrinkMalmquist/EDAF50 | /Labs/lab1/buggy_programs/sum.cc | UTF-8 | 294 | 3.125 | 3 | [] | no_license | #include <iostream>
#define N (4)
int x = 1000;
int a[]{ 1, 2, 3, 4 };
int y = 2000;
int main()
{
int sum{0};
std::cout << "welcome to the buggy sum program. the sum should be 10\n";
for (int i = 0; i <= N; i++)
sum += a[i];
std::cout << "sum = " << sum << "\n";
return 0;
}
| true |