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 |
---|---|---|---|---|---|---|---|---|---|---|---|
0345257a9b5b4285b0c7c00965c42dac13b52a66
|
C++
|
Huangxy0106/CXCEngine
|
/Include/Engine/Core/CObject.h
|
UTF-8
| 796 | 2.546875 | 3 |
[] |
no_license
|
#ifndef CXC_COBJECT_H
#define CXC_COBJECT_H
#include "Core/EngineCore.h"
#include <memory>
namespace cxc
{
class World;
class LogicFramework;
/* CObject is the base class for all the engine core class */
class CXC_ENGINECORE_API CObject
{
public:
friend class LogicFramework;
CObject();
virtual ~CObject();
public:
virtual void Initialize() {};
public:
virtual void Tick(float DeltaSeconds);
public:
std::shared_ptr<LogicFramework> GetLogicFramework();
std::shared_ptr<World> GetWorld();
uint32_t GetObjectGUID() const { return GUID; }
private:
// Global unique ID of the CObject, 0 represents the invalid ID
uint32_t GUID;
// Weak pointer back to the logic framework
std::weak_ptr<LogicFramework> OwnerLogicFramework;
};
}
#endif // CXC_COBJECT_H
| true |
fdeb8a3468975325369d1fc72ced791167071994
|
C++
|
zpfbuaa/Algorithm-Data-Structures
|
/数据结构/3.书上数据结构代码/第3章/程序3-6(顺序栈退栈操作的实现).cpp
|
GB18030
| 484 | 3.578125 | 4 |
[] |
no_license
|
//3-6˳ջջʵ֣
int Pop(SeqStack &S,SElemType &x)//ջջΪ0
//ջջָһջԪͨͲxأջɹ1
{
if(S.top==-1)return 0;
x=S.elem[S.top--];
return 1;
};
/* (1)жǷΪգջʱջǿյģܽջ0
(2)ջգȽջָջȡȻtopָһ
*/
| true |
b3e43a2a373d67a39cf56a2485ea948139302fd5
|
C++
|
DanielM08/C-lculo-Num-rico
|
/calculoNumerico_atvd5/1_3simpson.cpp
|
UTF-8
| 1,674 | 3.765625 | 4 |
[] |
no_license
|
#include <iostream>
#include <cmath>
#include <stdlib.h>
#include <math.h>
double funcao(double );
double (*func) (double) = funcao; //Ponteiro para a função
double um_tres_simpson(double , double , int , double (*func)(double)); //Método 1/3 simpson
int main()
{
//Pre-definindo o numero de iteracoes e os intervalos,
//sem interacao com o usuario.
int n = 6; // numero de sub intervalos (tem que ser par)
double a = -5;
double b = 5;
double result = um_tres_simpson(a, b, n, func);
std::cout << std::endl;
std::cout << ">>Resultado aproximado da integral: ";
std::cout << result << std::endl;
std::cout << std::endl << std::endl;
std::cout << "Para mais detalhes sobre a funcao integrada e o metodo 1/3 de Simpson, consultar o codigo." << std::endl;
return 0;
}
double funcao(double x)
{
return x * std::sin(x);
//return std::pow(x,2);
}
double um_tres_simpson(double a, double b, int n, double (*func)(double))
{
double h = (b-a)/n;
double vet_x[n+1];
double vet_y[n+1];
double width = (std::abs(a) + std::abs(b))/n;
vet_x[0] = a;
vet_y[0] = func(vet_x[0]);
for(int i = 1; i < n+1; ++i)
{
vet_x[i] = vet_x[i-1] + width;
vet_y[i] = func(vet_x[i]);
}
//Ex da 1_3 Simpson composta para 7 pontos (Ou seja, aplicada 3 vezes):
//h/3*[ f(x0) + 4*f(x1) + 2*f(x2) + 4*f(x3) + 2*f(x4) + 4*f(x5) + f(x6) ];
double result = vet_y[0] + vet_y[n]; //f(x0) + f(xn)
for(int i = 1; i < n; ++i)
{
if(i%2 != 0) //Valor em posição ímpar, multiplica por 4
{
result = result + 4 * vet_y[i];
}
else //Valor em posição par, multiplica por 2
{
result = result + 2* vet_y[i];
}
}
result = (h/3) * result;
return result;
}
| true |
85f02fe27a94b08828c00027f5d416737c2a09b5
|
C++
|
dengjun/GrB
|
/deeplogger.cpp
|
UTF-8
| 2,010 | 2.859375 | 3 |
[] |
no_license
|
#include"deeplogger.h"
#include<list>
DeepLogger::DeepLogger(const char* fName) : BaseLogger(fName)
{
}
DeepLogger::~DeepLogger()
{
}
void DeepLogger::writeToLogNodes(std::map<Cell, node_ptr, CellComparator>& open, std::map<Cell, node_ptr, CellComparator>& close)
{
if (!gotoRoot())
{
return;
}
if (!gotoFirstChildElement("lowlevel"))
{
addNewElement("lowlevel");
if (!gotoFirstChildElement("lowlevel"))
{
return;
}
}
addNewElement("step");
gotoLastChildElement("step");
addAttribute("number", iteration);
addNewElement("open");
gotoFirstChildElement("open");
writeNodes(open);
gotoParent();
addNewElement("close");
gotoFirstChildElement("close");
writeNodes(close);
iteration++;
}
bool sortByF(const NodeInLogData& first, const NodeInLogData& second)
{
return first.F < second.F;
}
void DeepLogger::writeNodes(std::map<Cell, node_ptr, CellComparator>& nodes)
{
std::list<NodeInLogData> nodesInLog;
for(auto nodeIter : nodes)
{
node_ptr node = nodeIter.second;
NodeInLogData data;
data.x = node->getCell().j;
data.y = node->getCell().i;
data.F = node->getF();
data.g = node->getG();
if (node->isParentListEmpty())
{
data.hasParent = false;
}
else
{
auto bestParent = node->getBestParent();
if (bestParent == nullptr)
{
data.hasParent = false;
}
else
{
data.parent_x = bestParent->getCell().j;
data.parent_y = bestParent->getCell().i;
data.hasParent = true;
}
}
nodesInLog.push_back(data);
}
nodesInLog.sort(sortByF);
for(auto node : nodesInLog)
{
addNewElement("node");
gotoLastChildElement("node");
addAttribute("x", node.x);
addAttribute("y", node.y);
addAttribute("F", node.F);
addAttribute("g", node.g);
if(node.hasParent)
{
addAttribute("parent_x", node.parent_x);
addAttribute("parent_y", node.parent_y);
}
gotoParent();
}
nodesInLog.clear();
}
| true |
f9a4523b38d3d2ce61d35ae43b470423df56fe65
|
C++
|
LBluu/1708SEM_ISIM
|
/大二下/C语言/部分作业/第七周作业/5.249_12.cpp
|
GB18030
| 822 | 2.84375 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void Print(int n);
int main(){
srand(time(NULL));
int n;
int i;
int memory[6];
for(i=0;i<6;i++){
memory[i] = 0;
}
int total = 0;
printf("û:");
while(true){
n = rand()%26+1;
Print(n);
total+=1;
if((n==20&&memory[0]==1)||(n==19&&memory[2]==1)||(n==5&&memory[5]==1 )|| (n==5&&memory[1]==1 )|| (n==14&&memory[3]==1)|| (n==16&&memory[4]==1)){
break;
}
if(n==1){
memory[0] = 1;
}else if(n==8){
memory[1] = 1;
}else if(n==9){
memory[2] = 1;
}else if(n==15){
memory[3] = 1;
}else if(n==21){
memory[4] = 1;
}else if(n==23){
memory[5] = 1;
}else{
for(i=0;i<6;i++){
memory[i] = 0;
}
}
}
printf("\nû%dĸ",total);
}
void Print(int n){
printf("%c",'a'+n-1);
}
| true |
7895114280b226be3e7e6ca25050dfa150ff8caa
|
C++
|
py2many/py2many
|
/tests/expected/lambda.cpp
|
UTF-8
| 230 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
#include <iostream> // NOLINT(build/include_order)
inline void show() {
auto myfunc = [](auto x, auto y) { return x + y; };
std::cout << myfunc(1, 2);
std::cout << std::endl;
}
int main(int argc, char** argv) { show(); }
| true |
d1110f51a61c80b5e8f3a121c03ff24b96deaec6
|
C++
|
amedhi/dmrg
|
/scheduler/inputparams.h
|
UTF-8
| 3,156 | 2.578125 | 3 |
[] |
no_license
|
/*---------------------------------------------------------------------------
* InputParameter: Classes for processing input parameters.
* Copyright (C) 2015-2015 by Amal Medhi <amedhi@iisertvm.ac.in>.
* All rights reserved.
* Date: 2015-08-17 13:33:19
* Last Modified by: amedhi
* Last Modified time: 2015-09-29 16:05:55
*----------------------------------------------------------------------------*/
// File: inputparams.h
#ifndef INPUT_PARAMETERS_H
#define INPUT_PARAMETERS_H
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <stdexcept>
namespace input {
enum class value_type {boo, num, str, nan};
class Parameters; // forward declaration
class JobInput
{
public:
JobInput() {n_tasks=n_params=0; valid=false;}
JobInput(const std::string& inputfile);
bool read_params(const std::string& inputfile);
bool not_valid(void) const {return !valid;};
unsigned int task_size(void) {return n_tasks;}
void get_task_param(const unsigned& task_id);
void init_task_param(Parameters& p);
void set_task_param(Parameters& p, const unsigned& task_id);
private:
struct parameter {std::string name; value_type type; unsigned size;};
unsigned int n_params;
unsigned int n_tasks;
bool valid;
std::string infile;
std::vector<parameter> param_list;
std::map<std::string, std::vector<bool> > boo_params;
std::map<std::string, std::vector<double> > num_params;
std::map<std::string, std::vector<std::string> > str_params;
unsigned int parse(const std::string& inputfile);
// bad_input exception
class bad_input: public std::runtime_error
{
public:
bad_input(const std::string& msg, const int& ln=-1);
std::string message(void) const;
private:
int lnum;
};
};
class Parameters
{
public:
Parameters() {};
int set_value(const std::string& pname, const int& defval) const;
int set_value(const std::string& pname, const int& defval, int& info) const;
int set_value(const std::string& pname, const int& defval, int& info, bool& is_const) const;
double set_value(const std::string& pname, const double& defval) const;
double set_value(const std::string& pname, const double& defval, int& info) const;
double set_value(const std::string& pname, const double& defval, int& info, bool& is_const) const;
std::string set_value(const std::string& pname, const std::string& defval) const;
bool is_constant(const std::string& pname) const;
unsigned task_id(void) const { return this_task; }
unsigned task_size(void) const { return n_tasks; }
void show(const unsigned&) const;
friend void JobInput::init_task_param(Parameters& p);
friend void JobInput::set_task_param(Parameters& p, const unsigned& task_id);
private:
struct pval {bool is_const; value_type type; bool bool_val; double num_val; std::string str_val;};
std::map<std::string, pval> params;
unsigned n_params;
unsigned this_task;
unsigned n_tasks;
mutable std::map<std::string, pval>::const_iterator it;
void warn_not_found(const std::string& pname) const;
void warn_type_mismatch(const std::string& pname, const std::string& type) const;
};
} // end namespace input
#endif
| true |
889ff9b4e796457eacc316b5d61ddd522323e851
|
C++
|
tchen0123/Solutions-to-CLRS
|
/Chapter06-Heapsort/heap.cpp
|
UTF-8
| 1,499 | 3.625 | 4 |
[] |
no_license
|
#include "heap.h"
void maxHeapify(std::vector<int> &array, std::size_t size, std::size_t index)
{
std::size_t left = LEFT(index), right = RIGHT(index);
std::size_t largest;
if (left < size && array[left] > array[index]) {
largest = left;
}
else {
largest = index;
}
if (right < size && array[right] > array[largest]) {
largest = right;
}
if (largest != index) {
std::swap(array[largest], array[index]);
maxHeapify(array, size, largest);
}
}
void buildMaxheap(std::vector<int> &array)
{
for (int i = array.size(); i >= 0; --i) {
maxHeapify(array, array.size(), i);
}
}
void minHeapify(std::vector<int> &array, std::size_t size, std::size_t index)
{
std::size_t left = LEFT(index), right = RIGHT(index);
std::size_t least;
if (left < size && array[left] < array[index]) {
least = left;
}
else {
least = index;
}
if (right < size && array[right] < array[least]) {
least = right;
}
if (least != index) {
std::swap(array[least], array[index]);
minHeapify(array, size, least);
}
}
void buildMinheap(std::vector<int> &array)
{
for (int i = array.size() / 2; i >= 0; --i) {
minHeapify(array, array.size(), i);
}
}
| true |
89909767fb748be5ac38bf0cf1bfb7cc20140c52
|
C++
|
Hunger-Prevails/fluid_simulation
|
/include/particle_sampler.h
|
UTF-8
| 4,690 | 2.875 | 3 |
[] |
no_license
|
#pragma once
#include <storage.h>
using namespace std;
namespace learnSPH{
/*
* samples border particles on a triangular face
* Args:
* vertex_a - corner A of the triangular face
* vertex_b - corner B of the triangular face
* vertex_c - corner C of the triangular face
* samplingDistance - distance between the centers of each two adjacent particles
* borderParticles - container for fetched particles
* hexagonal - whether to employ hexagonal patterns when sampling the particles (default: false)
*/
void sample_triangle(const Vector3R &vertex_a, const Vector3R &vertex_b, const Vector3R &vertex_c, Real samplingDistance, vector<Vector3R> &borderParticles);
/*
* samples border particles on the faces of a cube
* Args:
* lowerCorner - lower corner of the cube
* upperCorner - upper corner of the cube
* restDensity - rest density for the border (assumed as constant among all particles)
* samplingDistance - distance between the centers of each two adjacent particles
* eta - eta for the border (assumed as constant among all particles)
* hexagonal - whether to employ hexagonal patterns when sampling the particles (default: false)
*/
BorderSystem* sample_border_box(const Vector3R &lowerCorner, const Vector3R &upperCorner, Real restDensity, Real samplingDistance, Real eta);
void sample_ring(vector<Vector3R> &borderParticles, const Vector3R ¢er, Real radius, const Vector3R &unit_x, const Vector3R &unit_y, Real samplingDistance);
/*
* samples border particles on the surface of a cone
* Args:
* lowerRadius - radius of the lower cross section of the truncated cone
* lowerCenter - center of the lower cross section of the truncated cone
* upperRadius - radius of the upper cross section of the truncated cone
* upperCenter - center of the upper cross section of the truncated cone
* restDensity - rest density for the border (assumed as constant among all particles)
* samplingDistance - distance between the centers of each two adjacent particles
* eta - eta for the border (assumed as constant among all particles)
*/
BorderSystem* sample_border_cone(Real lowerRadius, const Vector3R &lowerCenter, Real upperRadius, const Vector3R &upperCenter, Real restDensity, Real samplingDistance, Real eta);
/*
* samples border particles on the surface of a sphere
* Args:
* radius - radius of the sphere
* center - center of the sphere
* restDensity - rest density for the border (assumed as constant among all particles)
* samplingDistance - distance between the centers of each two adjacent particles
* eta - eta for the border (assumed as constant among all particles)
*/
BorderSystem* sample_border_sphere(Real radius, const Vector3R ¢er, Real restDensity, Real samplingDistance, Real eta);
Real sample_cube(vector<Vector3R> &positions, const Vector3R &lowerCorner, const Vector3R &upperCorner, Real samplingDistance);
/*
* samples fluid particles inside a cube in axis-aligned fashion.
* Args:
* lowerA - lower corner of the cube A
* upperA - upper corner of the cube A
* restDensity - rest density for the fluid (assumed as constant among all particles)
* samplingDistance - distance between the centers of each two adjacent particles
*/
FluidSystem* single_dam(const Vector3R &lowerA, const Vector3R &upperA, Real restDensity, Real samplingDistance, Real eta);
/*
* samples fluid particles inside two cubes in axis-aligned fashion.
* Args:
* lowerA - lower corner of the cube A
* upperA - upper corner of the cube A
* lowerB - lower corner of the cube B
* upperB - upper corner of the cube B
* restDensity - rest density for the fluid (assumed as constant among all particles)
* samplingDistance - distance between the centers of each two adjacent particles
*/
FluidSystem* double_dam(const Vector3R &lowerA, const Vector3R &upperA, const Vector3R &lowerB, const Vector3R &upperB, Real restDensity, Real samplingDistance, Real eta);
void sample_shell(vector<Vector3R> &positions, const Vector3R ¢er, Real radius, Real samplingDistance);
/*
* samples fluid particles inside a sphere with initial velocity
* Args:
* center - center of the sphere
* speed - initial velocity
* radius - radius of the sphere
* restDensity - rest density for the fluid (assumed as constant among all particles)
* samplingDistance - distance between the centers of each two adjacent particles
*/
FluidSystem* water_drop(const Vector3R ¢er, const Vector3R &speed, Real radius, Real restDensity, Real samplingDistance, Real eta);
};
| true |
7f543ff83385c75bcc5e03cd5441f1efe47061e5
|
C++
|
opentechschool-zurich/cpp-co-learning
|
/programming-principles-and-practice/12-display-model/ale/presentation/02-square/main.cpp
|
UTF-8
| 213 | 3.0625 | 3 |
[] |
no_license
|
#include <iostream>
#include "Square.h"
using namespace std;
int main()
{
Square square{};
square.setWidth(10);
square.setHeight(5);
cout << "Area: " << square.getArea() << endl;
return 0;
}
| true |
f6ef8dbdeea256febdd1dcd6bf34cd7d785f7840
|
C++
|
yeodongbin/CppLecture
|
/09.1.2.TemplateParam.cpp
|
UHC
| 818 | 3.875 | 4 |
[] |
no_license
|
#include <iostream>
using namespace std;
template <typename T, int nSize = 10> //ø Ű 2 Ƶ ȴ.
class CMyArray
{
private:
T* m_pData;
public:
CMyArray() { m_pData = new T[nSize]; }
~CMyArray() { delete[] m_pData; }
//迭
T& operator[](int nIndex)
{
if (nIndex < 0 || nIndex >= nSize)
{
cout << "ERROR: 迭 踦 Դϴ." << endl;
exit(1);
}
return m_pData[nIndex];
}
//ȭ 迭
T& operator[](int nIndex) const { return operator[](nIndex); }
//迭 ȯ
int GetSize() { return nSize; }
};
int main()
{
CMyArray<int, 3> arr; //Ű
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
for (int i = 0; i < 3; ++i)
cout << arr[i] << endl;
return 9;
}
| true |
92ee98b85cbe4ed876a41c1efa3d57aeca17ecf5
|
C++
|
AlexZhanghao/Algorithm--notes
|
/程序代码/LeetCode/double pointer/removeElement.cpp
|
UTF-8
| 871 | 3.390625 | 3 |
[] |
no_license
|
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int nsize = nums.size();
if (nsize == 0) {
return 0;
}
int fast = 0, slow = 0;
while (fast < nsize) {
if (nums[fast] == val) {
Exchange(nums[fast], nums[slow]);
++fast;
++slow;
}
else {
++fast;
}
}
if (nums[0] == val) {
for (int i = 0; i < slow; ++i) {
nums.erase(nums.begin());
}
}
return fast - slow;
}
void Exchange(int &a, int &b) {
int c = a;
a = b;
b = c;
}
};
class Solution2 {
public:
int removeElement(vector<int>& nums, int val) {
int slow=0;
for(int fast=0;fast<nums.size();++fast){
if(nums[fast]!=val){
nums[slow]=nums[fast];
++slow;
}
}
return slow;
}
};
| true |
f7dc3470dd721cb5864c499ac08cc7b911f91dde
|
C++
|
TheUnicum/MathForGameDevelopers
|
/MathForGameDevelopers/src/mfgd/matrix.cpp
|
UTF-8
| 9,608 | 3.046875 | 3 |
[
"Apache-2.0"
] |
permissive
|
#include "matrix.h"
#include <string> // for std::memset
Matrix4x4::Matrix4x4(const Vector & v0, const Vector & v1, const Vector & v2, const Vector & v3)
{
v[0] = { v0.x, v0.y, v0.z, 0.0f };
v[1] = { v1.x, v1.y, v1.z, 0.0f };
v[2] = { v2.x, v2.y, v2.z, 0.0f };
v[3] = { v3.x, v3.y, v3.z, 1.0f };
}
Matrix4x4::Matrix4x4(const Vector4d & v0, const Vector4d & v1, const Vector4d & v2, const Vector4d & v3)
{
v[0] = { v0.x, v0.y, v0.z, v0.w };
v[1] = { v1.x, v1.y, v1.z, v1.w };
v[2] = { v2.x, v2.y, v2.z, v2.w };
v[3] = { v3.x, v3.y, v3.z, v3.w };
}
void Matrix4x4::Identity()
{
std::memset(this, 0, sizeof(Matrix4x4));
m[0][0] = m[1][1] = m[2][2] = m[3][3] = 1.0f;
}
Matrix4x4 Matrix4x4::Transposed() const
{
Matrix4x4 r;
r.m[0][0] = m[0][0]; r.m[1][0] = m[0][1]; r.m[2][0] = m[0][2]; r.m[3][0] = m[0][3];
r.m[0][1] = m[1][0]; r.m[1][1] = m[1][1]; r.m[2][1] = m[1][2]; r.m[3][1] = m[1][3];
r.m[0][2] = m[2][0]; r.m[1][2] = m[2][1]; r.m[2][2] = m[2][2]; r.m[3][2] = m[2][3];
r.m[0][3] = m[3][0]; r.m[1][3] = m[3][1]; r.m[2][3] = m[3][2]; r.m[3][3] = m[3][3];
return r;
}
Matrix4x4 Matrix4x4::operator*(const Matrix4x4 & t) const
{
Matrix4x4 r;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
r.m[i][j] = m[i][0] * t.m[0][j] + m[i][1] * t.m[1][j] + m[i][2] * t.m[2][j] + m[i][3] * t.m[3][j];
//r.m[i][j] = m[0][j] * t.m[i][0] + m[1][j] * t.m[i][1] + m[2][j] * t.m[i][2] + m[3][j] * t.m[i][3];
}
return r;
}
bool Matrix4x4::operator==(const glm::mat4 & t) const
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
//if (m[i][j] != t[j][i])
// return false;
if (std::fabs(m[i][j] - t[j][i]) > 0.00001f)
return false;
}
}
return true;
}
Vector Matrix4x4::GetTranslation() const
{
return Vector(m[0][3], m[1][3], m[2][3]);
}
void Matrix4x4::SetTranslation(const Vector & vecPos)
{
// Non mi torna
//m[3][0] = vecPos.x;
//m[3][1] = vecPos.y;
//m[3][2] = vecPos.z;
m[0][3] = vecPos.x;
m[1][3] = vecPos.y;
m[2][3] = vecPos.z;
}
void Matrix4x4::SetRotation(float flAngle, const Vector & vecAxis)
{
Vector _vecAxis = vecAxis.Normalized();
// Rotaion Ax Z
float x = _vecAxis.x;
float y = _vecAxis.y;
float z = _vecAxis.z;
float c = std::cos(flAngle*(float)M_PI / 180);
float s = std::sin(flAngle*(float)M_PI / 180);
float t = 1 - c;
/*
https://learnopengl.com/Getting-started/Transformations
https://en.wikipedia.org/wiki/Rotation_matrix
https://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToMatrix/
*/
//1 + (1-cos(angle))*(x*x-1) -z*sin(angle)+(1-cos(angle))*x*y y*sin(angle)+(1-cos(angle))*x*z
m[0][0] = +c + x*x*t; //
m[0][1] = x*y*t - z*s; //
m[0][2] = x*z*t + y*s; //
//z*sin(angle)+(1-cos(angle))*x*y 1 + (1-cos(angle))*(y*y-1) -x*sin(angle)+(1-cos(angle))*y*z
m[1][0] = y*x*t + z*s; //
m[1][1] = c + y*y *t; //
m[1][2] = y*z*t - x*s; //
//-y*sin(angle)+(1-cos(angle))*x*z x*sin(angle)+(1-cos(angle))*y*z 1 + (1-cos(angle))*(z*z-1)
m[2][0] = z*x*t - y * s; //
m[2][1] = z*y*t + x*s; //
m[2][2] = c + z*z *t; //
}
void Matrix4x4::SetScale(const Vector & vecScale)
{
m[0][0] = vecScale.x;
m[1][1] = vecScale.y;
m[2][2] = vecScale.z;
}
Vector Matrix4x4::operator*(const Vector & v) const
{
/*
[a b c d][X]
[d e f y][Y] = [aX+bY+cZ+dW, dX+eY+fZ+yW, gX+hY+iZ+zW]
[g h i z][Z]
[1]
*/
Vector vecResult;
vecResult.x = m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3];
vecResult.y = m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3];
vecResult.z = m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3];
return vecResult;
}
Vector4d Matrix4x4::operator*(const Vector4d & v) const
{
/*
[a b c d][X]
[d e f y][Y] = [aX+bY+cZ+dW, dX+eY+fZ+yW, gX+hY+iZ+zW, jX+kY+lZ+mW]
[g h i z][Z]
[j k l m][W]
*/
Vector4d vecResult;
vecResult.x = m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3] * v.w;
vecResult.y = m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3] * v.w;
vecResult.z = m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3] * v.w;
vecResult.w = m[3][0] * v.x + m[3][1] * v.y + m[3][2] * v.z + m[3][3] * v.w;
return vecResult;
}
// Change of basis
// FRU
/* R U F
+- -+
| Rx Uy Fz 0 |
R U F = | Rx Uy Fz 0 |
| Rx Uy Fz 0 |
| 0 0 0 1 |
+- -+
*/
glm::mat4 Matrix4x4::ToGlm() const
{
glm::mat4 r(1.0f);
// Vector 0
r[0] = glm::vec4(v[0].x, v[0].y, v[0].z, v[0].w );
r[1] = glm::vec4(v[1].x, v[1].y, v[1].z, v[1].w );
r[2] = glm::vec4(v[2].x, v[2].y, v[2].z, v[2].w );
r[3] = glm::vec4(v[3].x, v[3].y, v[3].z, v[3].w );
r = glm::transpose(r);
return r;
}
Matrix4x4 Matrix4x4::InvertedTR() const
{
// This method can only be used if the matrix is a translation/rotation matrix.
// The below asserts will trigger if this is not the case.
//TAssert(fabs(GetForwardVector().LengthSqr() - 1) < 0.00001f); // Each basis vector should be length 1.
//TAssert(fabs(GetUpVector().LengthSqr() - 1) < 0.00001f);
//TAssert(fabs(GetRightVector().LengthSqr() - 1) < 0.00001f);
//TAssert(fabs(GetForwardVector().Dot(GetUpVector())) < 0.0001f); // All vectors should be orthogonal.
//TAssert(fabs(GetForwardVector().Dot(GetRightVector())) < 0.0001f);
//TAssert(fabs(GetRightVector().Dot(GetUpVector())) < 0.0001f);
Matrix4x4 M;
// M^-1 = R^-1 * T^-1
/*
+- -+ +- -+ +- -+
| | | | | |
LookAt = | R^T 0 | | I -t | = | R^T -(R^T)*t|
| | | | | |
| 0 1 | | 0 1 | | 0 1 |
+- -+ +- -+ +- -+
*/
// Create the transpose upper 3x3 matrix
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
M.m[i][j] = m[j][i];
// The new matrix translatrion = -Rt
M.SetTranslation(-(M*GetTranslation()));
return M;
}
// Static funcitons
Matrix4x4 GetView(Point & position, Vector & target, Vector & worldUp)
{
/*
+- -+ +- -+
| Rx Ry Rz 0 | | 1 0 0 -Px |
LookAt = | Ux Uy Uz 0 | | 0 1 0 -Py |
| Dx Dy Dz 0 | | 0 0 1 -Pz |
| 0 0 0 1 | | 0 0 0 1 |
+- -+ +- -+
*/
// Matrix "r-Rotation"
// -------------------
Vector zaxis_D = position - target;
zaxis_D = zaxis_D.Normalized();
Vector xaxis_R = worldUp.Cross(zaxis_D);
xaxis_R = xaxis_R.Normalized();
Vector yaxis_U = zaxis_D.Cross(xaxis_R);
yaxis_U.Normalized();
Matrix4x4 r(xaxis_R, yaxis_U, zaxis_D);
// Matrix "t-Translation"
// -------------------
Matrix4x4 t;
t.m[0][3] = -position.x;
t.m[1][3] = -position.y;
t.m[2][3] = -position.z;
return r * t;
}
// utility overload for iostream Vertex Data
std::ostream & operator<<(std::ostream & stream, const Matrix4x4 & matrix)
{
stream << "-----------Matrix4x4-----[row][col]--------------\n";
//stream << "M4x4 mm: (" << matrix.m[0][0] << ", " << matrix.m[0][1] << ", " << matrix.m[0][2] << ", " << matrix.m[0][3] << ")\n";
//stream << "M4x4 mm: (" << matrix.m[1][0] << ", " << matrix.m[1][1] << ", " << matrix.m[1][2] << ", " << matrix.m[1][3] << ")\n";
//stream << "M4x4 mm: (" << matrix.m[2][0] << ", " << matrix.m[2][1] << ", " << matrix.m[2][2] << ", " << matrix.m[2][3] << ")\n";
//stream << "M4x4 mm: (" << matrix.m[3][0] << ", " << matrix.m[3][1] << ", " << matrix.m[3][2] << ", " << matrix.m[3][3] << ")\n";
stream << "my_:M4d4 v0: (" << matrix.v[0].x << ", " << matrix.v[0].y << ", " << matrix.v[0].z << ", " << matrix.v[0].w << ")\n";
stream << "my_:M4d4 v0: (" << matrix.v[1].x << ", " << matrix.v[1].y << ", " << matrix.v[1].z << ", " << matrix.v[1].w << ")\n";
stream << "my_:M4d4 v0: (" << matrix.v[2].x << ", " << matrix.v[2].y << ", " << matrix.v[2].z << ", " << matrix.v[2].w << ")\n";
stream << "my_:M4d4 v0: (" << matrix.v[3].x << ", " << matrix.v[3].y << ", " << matrix.v[3].z << ", " << matrix.v[3].w << ")";
return stream;
}
std::ostream & operator<<(std::ostream & stream, const glm::mat4 & matrix)
{
stream << "-----------glm::mat4-----[col][row]--------------\n";
//stream << "M4x4 mm: (" << matrix[0][0] << ", " << matrix[0][1] << ", " << matrix[0][2] << ", " << matrix[0][3] << ")\n";
//stream << "M4x4 mm: (" << matrix[1][0] << ", " << matrix[1][1] << ", " << matrix[1][2] << ", " << matrix[1][3] << ")\n";
//stream << "M4x4 mm: (" << matrix[2][0] << ", " << matrix[2][1] << ", " << matrix[2][2] << ", " << matrix[2][3] << ")\n";
//stream << "M4x4 mm: (" << matrix[3][0] << ", " << matrix[3][1] << ", " << matrix[3][2] << ", " << matrix[3][3] << ")\n";
stream << "glm:M4x4 v0: (" << matrix[0][0] << ", " << matrix[1][0] << ", " << matrix[2][0] << ", " << matrix[3][0] << ")\n";
stream << "glm:M4x4 v0: (" << matrix[0][1] << ", " << matrix[1][1] << ", " << matrix[2][1] << ", " << matrix[3][1] << ")\n";
stream << "glm:M4x4 v0: (" << matrix[0][2] << ", " << matrix[1][2] << ", " << matrix[2][2] << ", " << matrix[3][2] << ")\n";
stream << "glm:M4x4 v0: (" << matrix[0][3] << ", " << matrix[1][3] << ", " << matrix[2][3] << ", " << matrix[3][3] << ")";
return stream;
}
std::ostream & operator<<(std::ostream & stream, const glm::vec4 & vec4)
{
stream << "-----------glm::Vec4----------------------------\n";
stream << "glm::Vec4: (" << vec4.x << ", " << vec4.y << ", " << vec4.z << ", " << vec4.w << ")";
return stream;
}
std::ostream & operator<<(std::ostream & stream, const Vector4d vec4)
{
stream << "-----------Vector4d---------------------------\n";
stream << "Vector4d : (" << vec4.x << ", " << vec4.y << ", " << vec4.z << ", " << vec4.w << ")";
return stream;
}
| true |
b7ec3e9ae6c0cae84efdb6211d40df7f8044fd3c
|
C++
|
Durand-Chuante/Programmierung-C-PlusPlus
|
/Aufgaben/vererbung2/main.cpp
|
UTF-8
| 393 | 3.25 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
class Animal
{
public:
double poid;
int patte;
};
class chat : public Animal
{
public:
string nom;
void affiche();
};
void chat::affiche()
{
poid = 21.3;
cout << " nombre de patte: " << patte << "weight: " << poid << " nom: " << nom << endl;
}
int main()
{
chat c;
c.affiche();
return 0;
}
| true |
3293275e5eb58abfb25194bbeeeb230c28ca92d0
|
C++
|
vieirajlt/FEUP-IART-P2
|
/Project/Project/Genetics.cpp
|
ISO-8859-1
| 4,180 | 3.125 | 3 |
[] |
no_license
|
#include "Genetics.h"
#include <random>
#include <iostream>
#include <map>
#include <set>
#include <iterator>
#include <chrono>
Genetics::Genetics()
{
}
Genetics::Genetics(Data* data, Node initial) : Genetics(data, initial, 30)
{
}
Genetics::Genetics(Data* data, Node initial, int mutationProbability) : Genetics(data, initial, 50, 1000, mutationProbability, 15, 10000)
{
}
Genetics::Genetics(Data* data, Node initial, int populationSize, int maxNoGenerations, int mutationProbability, int parentEliteNo, long maxTimeMilliseconds)
{
this->data = data;
this->initial = initial;
this->best = initial;
this->populationSize = populationSize;
this->maxNoGenerations = maxNoGenerations;
this->mutationProbability = mutationProbability;
this->parentEliteNo = parentEliteNo;
this->maxTimeMilliseconds = maxTimeMilliseconds;
}
void Genetics::printBest()
{
this->best.print();
}
//change to choose from the best
Node Genetics::randomSelection(std::set<Node>* population)
{
int n = this->random(0, population->size() -1);
int index = 0;
auto it = population->begin();
std::advance(it, n);
return (*it);
}
void Genetics::mutate(Node* elem)
{
int n = this->random(1,100); //random number between 1 and 100
if (n > this->mutationProbability)
return;
int nrOfMutations = this->random(1, elem->getAnswersSize());
int index, randomPeriod, randomRoom;
for (int i = 0; i < nrOfMutations; i++) {
index = this->random(0, elem->getAnswersSize() -1);
randomPeriod = this->random(0, this->data->getPeriodsCnt() -1);
randomRoom = this->random(0, this->data->getRoomsCnt() -1);
elem->setAnswer(index, randomPeriod, randomRoom);
}
}
Node Genetics::reproduce(Node* elem1, Node* elem2)
{
int c = this->random(0, elem1->getAnswersSize() - 1);
std::vector<std::pair<int, int>> elemAnswers = elem1->getAnswers();
std::vector<std::pair<int, int>> answers1(elemAnswers.begin(), elemAnswers.begin()+ c);
elemAnswers = elem2->getAnswers();
std::vector<std::pair<int, int>> answers2(elemAnswers.begin() + c, elemAnswers.begin() + elem2->getAnswersSize());
answers1.insert(answers1.end(), answers2.begin(), answers2.end());
Node child = Node();
child.setAnswers(answers1);
return child;
}
//permite elitismo, manter os parentEliteNo progenitores na populaao
void Genetics::insertPopulationBestElements(std::set<Node>* prevPopulation, std::set<Node>* newPopulation)
{
int ad = this->parentEliteNo;
if (prevPopulation->size() < this->parentEliteNo)
ad = prevPopulation->size();
auto bg = prevPopulation->begin();
std::advance(bg, ad);
newPopulation->insert(prevPopulation->begin(), bg );
}
int Genetics::random(int min, int max)
{
std::mt19937::result_type seed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
std::mt19937 rng(seed);
std::uniform_int_distribution<int> gen(min, max);
int r = gen(rng);
return r;
}
//o best vai ser o que tiver menor penalty
Node Genetics::solve(std::set<Node> population)
{
int bestPenalty = -1, bestNoFaults, penalty, noFaults;
Node elem1, elem2, child;
const auto begin = clock();
for (int generationsCount = 0; generationsCount < this->maxNoGenerations; generationsCount++) {
std::set<Node> newPopulation;
insertPopulationBestElements(&population, &newPopulation);
//todo refactor -> mudar para outra funo
for (int currentPopulationSize = 0; currentPopulationSize < this->populationSize; currentPopulationSize++) {
elem1 = this->randomSelection(&population);
elem2 = this->randomSelection(&population);
child = reproduce(&elem1, &elem2);
mutate(&child);
this->data->evaluateSolution(&child);
penalty = child.getPenalty();
noFaults = child.getNoFaults();
if (bestPenalty == -1 || (penalty <= bestPenalty && noFaults <= bestNoFaults) || noFaults < bestNoFaults) {
this->best = child;
bestPenalty = penalty;
bestNoFaults = noFaults;
}
if ((noFaults == 0 && penalty == 0)
|| (maxTimeMilliseconds > 0L && ((clock() - begin) / CLOCKS_PER_SEC *1000 >= maxTimeMilliseconds))) {
return this->best;
}
newPopulation.insert(child);
}
population = newPopulation;
}
return this->best;
}
| true |
2e924f9a3117ac001a2882098a177a76424030b4
|
C++
|
njustbyq/Algorithms
|
/LeetCode/128.最长连续序列.cpp
|
UTF-8
| 1,270 | 3.421875 | 3 |
[] |
no_license
|
/*
* @lc app=leetcode.cn id=128 lang=cpp
*
* [128] 最长连续序列
*/
// @lc code=start
/*
* Solution 1: HashTable: (key, len)
* Case 1: no neighbor
* h[key] = 1
*
* Case 2: has a single neighbor, extend
* l = h[key +- 1]
* h[key +- 1] = h[key] = l + 1
*
* Case 3: has 2 neighbors, a bridge
* l = h[key - 1]
* r = h[key + 1]
* t = l + r + 1
* h[key - l] = h[key + r] = t
*/
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_map<int , int> h;
for (int num: nums) {
if(h.count(num)) continue;
auto it_l = h.find(num - 1);
auto it_r = h.find(num + 1);
int l = it_l != h.end() ? it_l->second : 0;
int r = it_r != h.end() ? it_r->second : 0;
if (l > 0 && r > 0)
h[num] = h[num - l] = h[num + r] = l + r + 1;
else if (l > 0)
h[num] = h[num - l] = l + 1;
else if (r > 0)
h[num] = h[num + r] = r + 1;
else
h[num] = 1;
}
int ans = 0;
for(const auto& kv : h)
ans = max(ans, kv.second);
return ans;
}
};
// @lc code=end
| true |
8e7077637177413213fea55db289adfdb209cdf1
|
C++
|
ca2/app
|
/acme/filesystem/filesystem/listing.cpp
|
UTF-8
| 1,463 | 2.65625 | 3 |
[] |
no_license
|
#include "framework.h"
namespace file
{
listing::listing()
{
m_nGrowBy = 128;
}
listing::listing(const listing & listing) :
patha(listing)
{
m_nGrowBy = 128;
}
listing::~listing()
{
}
relative_name_listing::relative_name_listing()
{
}
relative_name_listing::relative_name_listing(const relative_name_listing & listing) :
::file::listing(listing)
{
}
relative_name_listing::~relative_name_listing()
{
}
} // namespace file
CLASS_DECL_ACME bool matches_wildcard_criteria(const string_array & straCriteria, const string & strValue)
{
if (straCriteria.is_empty())
{
return true;
}
for (auto & strCriteria : straCriteria)
{
if (matches_wildcard_criteria(strCriteria, strValue))
{
return true;
}
}
return false;
}
CLASS_DECL_ACME bool matches_wildcard_criteria_ci(const string_array & straCriteria, const string & strValue)
{
if (straCriteria.is_empty())
{
return true;
}
for (auto & strCriteria : straCriteria)
{
if (matches_wildcard_criteria_ci(strCriteria, strValue))
{
return true;
}
}
return false;
}
CLASS_DECL_ACME string normalize_wildcard_criteria(const string & strPattern)
{
if (strPattern.is_empty() || strPattern == "*.*")
{
return "*";
}
else
{
return strPattern;
}
}
| true |
774a8f2a93f1481660b1e7dad5eaa104b2e6d93b
|
C++
|
chrisoldwood/XML
|
/Writer.hpp
|
UTF-8
| 1,938 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
////////////////////////////////////////////////////////////////////////////////
//! \file Writer.hpp
//! \brief The Writer class declaration.
//! \author Chris Oldwood
// Check for previous inclusion
#ifndef XML_WRITER_HPP
#define XML_WRITER_HPP
#if _MSC_VER > 1000
#pragma once
#endif
#include "Document.hpp"
#include "ElementNode.hpp"
namespace XML
{
////////////////////////////////////////////////////////////////////////////////
//! The writer to create a text stream from an XML document.
class Writer /*: private NotCopyable*/
{
public:
//! The writing flags.
enum Flag
{
DEFAULT = 0x0000, //!< Default flags.
NO_FORMATTING = 0x0001, //!< Don't pretty print the XML.
};
//! The default indentation style.
static const tchar* DEFAULT_INDENT_STYLE;
//! The default line terminator.
static const tchar* DEFAULT_TERMINATOR;
//
// Class methods.
//
//! Write a document to a string buffer.
static tstring writeDocument(DocumentPtr document, uint flags = DEFAULT, const tchar* indentStyle = DEFAULT_INDENT_STYLE);
private:
//
// Members.
//
uint m_flags; //!< The flags to control writing.
tstring m_indentStyle; //!< The string to use for indenting.
tstring m_buffer; //!< The output buffer.
uint m_depth; //!< The indentation depth.
//
// Internal methods.
//
//! Default constructor.
Writer();
//! Constructor.
Writer(uint flags, const tchar* indent);
//! Destructor.
~Writer();
//! Write a document to a string buffer.
tstring formatDocument(DocumentPtr document);
//! Write a container of nodes to the buffer.
void writeContainer(const NodeContainer& container);
//! Write the attributes to the buffer.
void writeAttributes(const Attributes& attributes);
//! Write an element to the buffer.
void writeElement(ElementNodePtr element);
// NotCopyable.
Writer(const Writer&);
Writer& operator=(const Writer);
};
//namespace XML
}
#endif // XML_WRITER_HPP
| true |
313ceaa474f9c891cf712714237eedfc454a6797
|
C++
|
jariasf/Online-Judges-Solutions
|
/LeetCode/30-Day Challenge/April/Week 1.5 Best Time to Buy and Sell Stock II.cpp
|
UTF-8
| 518 | 3.25 | 3 |
[] |
no_license
|
/*******************************************
***Problema: Best Time to Buy and Sell Stock II
***ID: Week1.5
***Juez: LeetCode
***Tipo: Greedy
***Autor: Jhosimar George Arias Figueroa
*******************************************/
class Solution {
public:
int maxProfit(vector<int>& prices) {
int sz = prices.size();
int ans = 0;
for( int i = 1 ; i < sz ; ++i ){
if( prices[i] > prices[i - 1]){
ans += prices[i] - prices[i - 1];
}
}
return ans;
}
};
| true |
6749d6cbdd67e3fef83390eadf3e1539c60221e5
|
C++
|
RichezA/progHELHA
|
/2eme/Programmation/Codes/C++/10-15/c++1stpart.cpp
|
UTF-8
| 1,556 | 3.6875 | 4 |
[] |
no_license
|
//Ceci est un commentaire
/* un commentaire
sur plusieurs lignes
*/
#ifdef commentaire
sur plusieurs lignes
#endif
#include <iostream>
//using namespace std;
void f(int m)
{
// passage par valeur int& pour référence si on passe par ref => i = 1 si par valeur => i = 0
cout << ++m << endl;
}
int main()
{
//cout << "Hello" << endl;
const int n = 40; // on doit déclarer tout de suite la valeur
bool isFound = false;
// n = 12; // erreur de compilation
for (int i = 0; i < n && !isFound; i++)
{
// différence i++ et ++i
// i++ on utilise d'abord i puis on incrémente
// ++i on incrémente d'abord i puis on l'utilise
int j = 25;
i += j;
cout << "i vaut: " << i << endl;
if (i > 20)
{
isFound = true; // on peut aussi utiliser 1 ou n'importe quel autre valeur à la place de true
}
}
enum Color
{
red,
green,
blue
};
Color r = red;
switch (r)
{
case red:
cout << red << "red\n";
break;
case green:
cout << green << "green\n";
break;
case blue:
cout << blue << "blue\n";
break;
}
int i = 0, j = 10;
int &value = i;
f(i); // renvoie 1 mais i vaut toujours 0
cout << "i vaut : " << i << " valeur : " << value << endl;
i = 10;
cout << "i vaut : " << i << " valeur : " << value << endl;
value = j;
j += 5;
cout << "i vaut : " << i << " valeur : " << value << endl;
return 0;
}
| true |
615f47fa98e087e71c54be29bd3fa1cbc14af221
|
C++
|
akowalew/tiva-freertos
|
/src/buttons.cpp
|
UTF-8
| 3,418 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
///////////////////////////////////////////////////////////////////////////////
// Buttons management
///////////////////////////////////////////////////////////////////////////////
//
// Global variables
//
//! Queue to store buttons presses events
static QueueHandle_t buttons_queue = nullptr;
//
// Private functions
//
//! Implementation of button handling routine
static void buttons_task([[maybe_unused]] void* params)
{
// We need some structure to represent buttons and their debouncing state
struct Button { u8 pin; u8 timer; u8 counter; } buttons[2];
buttons[0].pin = BTN_LEFT_PIN;
buttons[1].pin = BTN_RIGHT_PIN;
// Parameters of debouncing - suited for this board's buttons
constexpr u8 DEBOUNCE_INTERVAL_MS = 4;
constexpr u8 DEBOUNCE_REPEATS = 16;
// In loop either wait for any pin to be touched or perform debouncing
while(true)
{
// Wait for any pin to be touched
gpio_wait(BTNS_PINS);
// Some pins have been touched. Begin debouncing
auto nextwaketime = xTaskGetTickCount();
auto debounce_pins = 0x00;
while(true)
{
// Check, if some pins was touched recently
const auto next_debounce_pins = gpio_get();
if(next_debounce_pins) {
// Initialize them for debouncing
for(auto& button : buttons) {
if(next_debounce_pins & button.pin) {
button.timer = DEBOUNCE_REPEATS;
button.counter = 0;
}
}
debounce_pins |= next_debounce_pins;
}
// Latch state of pins
const auto pins_states = GPIOF->DATA[debounce_pins];
// Handle debouncing
auto finished_pins = 0x00;
auto pressed_pins = 0x00;
for(auto& [pin, timer, counter] : buttons) {
if(!(debounce_pins & pin)) {
// Pin is not under debouncing, go to next one
continue;
}
// Perform voting for "not_pressed"
const auto is_not_pressed = (pins_states & pin);
if(is_not_pressed) { ++counter; }
// If debouncing has finished, detect state of the pin
if(--timer == 0) {
if(counter < DEBOUNCE_REPEATS/4) {
// More than 75% of votes was for "is pressed"
pressed_pins |= pin;
}
finished_pins |= pin;
}
}
// If there were detected pressed pins, send them to the queue
if(pressed_pins) {
CHECK(xQueueSend(buttons_queue, &pressed_pins, 0));
}
// Do we have some buttons, that have just end debouncing?
if(finished_pins) {
// Re-enable interrupts for them
gpio_enable(finished_pins);
// Exclude them from debouncing
debounce_pins &= ~finished_pins;
if(!debounce_pins)
{
// No more pins to debounce, we have to wait for interrupt!
break;
}
}
// Wait for next interval
vTaskDelayUntil(&nextwaketime, pdMS_TO_TICKS(DEBOUNCE_INTERVAL_MS));
}
}
}
//
// Public functions
//
void buttons_init()
{
// Create queue for button press events
const auto queue_size = 8;
CHECK(buttons_queue = xQueueCreate(queue_size, sizeof(u8)));
// Create task for buttons handling
const auto stacksize = configMINIMAL_STACK_SIZE;
const auto params = nullptr;
const auto priority = (tskIDLE_PRIORITY + 1);
CHECK(xTaskCreate(buttons_task, "buttons", stacksize, params, priority, nullptr));
}
u8 buttons_read()
{
u8 pressed_pins;
// Read in blocking way press events from the queue
CHECK(xQueueReceive(buttons_queue, &pressed_pins, portMAX_DELAY));
CHECK(pressed_pins != 0x00);
// Return what buttons was pressed
return pressed_pins;
}
| true |
eb8b000090f35f963e8a6e453c9f7fff10d53d6d
|
C++
|
Sidetalker/CGTermProject
|
/CGTermProject/BubbleProjectile.cpp
|
UTF-8
| 3,180 | 2.859375 | 3 |
[] |
no_license
|
#include "BubbleProjectile.h"
#include <cmath>
#include "Target.h"
#include "Plane.h"
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
const static uint SLICES_AND_STACKS = 10;
BubbleProjectile::BubbleProjectile( Vector center, float radius, float speed ) :
BaseProjectile( center, speed )
, m_radius( radius )
{
m_type = ProjectileTypes::BUBBLE;
}
BubbleProjectile::~BubbleProjectile()
{
}
// simply draws the object in the scene
void BubbleProjectile::draw()
{
glColor3f( 1.0, 0.0, 0.0 );
glPushMatrix();
glTranslatef( getCenterX(), getCenterY(), getCenterZ() );
glutSolidSphere( m_radius, SLICES_AND_STACKS, SLICES_AND_STACKS );
glPopMatrix();
}
// check for collision with a provided array of targets
void BubbleProjectile::checkCollisions( BaseTarget* targets[], uint numTargets )
{
for ( uint i = 0; i < numTargets; ++i )
{
// prevent double hit for one projectile
if ( m_bHitObject == true )
{
break;
}
// prevent double hit target
if ( targets[ i ]->getStatus() == TargetStatus::ACTIVE )
{
switch ( targets[ i ]->getType() )
{
case TargetTypes::BULLSEYE:
{
// cast as Target
Target* t = ( Target* ) targets[ i ];
// Vector from near plane to current center
Vector nearPlaneToCurCenter( ( m_center ) - ( t->getNearPlane().getPoint() ) );
// Vector from near plane to previous center
Vector nearPlaneToPrevCenter( ( m_prevPosition ) - ( t->getNearPlane().getPoint() ) );
// if opposite signs (crossed the near plane)
if ( ( nearPlaneToPrevCenter.dotProduct( t->getNearPlane().getNormal() ) < 0 != nearPlaneToCurCenter.dotProduct( t->getNearPlane().getNormal() ) < 0 ) )
{
// point on near plane of intersection
Vector intersectionNear = t->getNearPlane().lineIntersect( Line( m_prevPosition, m_velocity ) );
// if point of intersection is within bounds of circle target face
if ( ( intersectionNear - t->getNearPlane().getPoint() ).squareMagnitude() <= pow( ( t->getRadius() + m_radius ), 2 ) )
{
t->setStatus( TargetStatus::HIT );
m_bHitObject = true;
break;
}
}
// Vector from far plane to current center
Vector farPlaneToCurCenter( ( m_center ) - ( t->getFarPlane().getPoint() ) );
// Vector from far plane to previous center
Vector farPlaneToPrevCenter( ( m_prevPosition ) - ( t->getFarPlane().getPoint() ) );
// if opposite signs (crossed the far plane)
if ( ( farPlaneToPrevCenter.dotProduct( t->getFarPlane().getNormal() ) < 0 != farPlaneToCurCenter.dotProduct( t->getFarPlane().getNormal() ) < 0 ) )
{
// point on far plane of intersection
Vector intersectionFar = t->getFarPlane().lineIntersect( Line( m_prevPosition, m_velocity ) );
// if point of intersection is within bounds of circle target face
if ( ( intersectionFar - t->getFarPlane().getPoint() ).squareMagnitude() <= pow( ( t->getRadius() + m_radius ), 2 ) )
{
t->setStatus( TargetStatus::HIT );
m_bHitObject = true;
}
}
break;
}
default:
{
// invalid target type
break;
}
}
}
}
}
| true |
9042baa0e4b7545d4a7c50574e396dcdbf6979fc
|
C++
|
Leobuaa/LeetCode
|
/C++/Bulls and Cows/main.cpp
|
UTF-8
| 611 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
class Solution {
public:
string getHint(string secret, string guess) {
int len = int(secret.length());
int a = 0, b = 0;
vector<int> count1(10, 0), count2(10, 0);
for (int i = 0; i < len; i++)
{
if (secret[i] == guess[i])
a++;
else
{
count1[secret[i] - '0']++;
count2[guess[i] - '0']++;
}
}
for (int i = 0; i < 10; i++)
b += min(count1[i], count2[i]);
return to_string(a) + "A" + to_string(b) + "B";
}
};
| true |
e5167c6bd4b000e76038d2381bd303f3c2b90995
|
C++
|
BinyuHuang-nju/leetcode-implement
|
/all115/all115/main.cpp
|
UTF-8
| 1,396 | 2.96875 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <cstring>
class Solution_false { //exceeds time limitation
public:
int numDistinct(string s, string t) {
int num = 0;
son_pattern(num, s, t, 0, 0);
return num;
}
void son_pattern(int& num, string s, string t, int scur, int tcur) {
if (tcur == t.length())
num++;
else {
int i = scur;
while (i < s.length() && s[i] != t[tcur])
i++;
if (i == s.length())
return;
else {
son_pattern(num, s, t, i + 1, tcur + 1);
son_pattern(num, s, t, i + 1, tcur);
}
}
}
};
class Solution {
public:
int numDistinct(string s, string t) {
if (s.length() < t.length())
return 0;
vector<vector<unsigned int>> dp(s.length() + 1, vector<unsigned int>(t.length() + 1, 0));
int i, j;
for (i = 0; i <= s.length(); i++)
dp[i][0] = 1;
for (i = 1; i <= s.length(); i++) {
for (j = 1; j <= t.length(); j++) {
if (s[i - 1] == t[j - 1])
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
else
dp[i][j] = dp[i - 1][j];
}
}
return (int)dp[s.length()][t.length()];
}
};
| true |
60fd9318b54dff0280091dcd0683220a7845eb2a
|
C++
|
zhaoyuRobotics/BeautiOfProgram
|
/1.CpuLine/Cpuline1.cpp
|
UTF-8
| 932 | 2.953125 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <unistd.h>
// 我的电脑主频是1.6Ghz, 1.6*10的9次方个始终周期每秒,现在cpu每个时钟周期可以执行两条以上汇编代码,我们取平均两条,于是有(1600000000*2)/5=540000000(循环/秒),除以5是因为for循环执行了五条汇编代码。我们不能简单的循环540000000次,然后sleep1秒,cpu波形很可能就是先达到峰值(>50%),然后跌到一个很低的占用率(锯齿状)。我们缩小两个数量级(10ms左右,正好是时间片段大小),这样我们看到的cpu曲线效果大概就是百分之50附近。因为还有其他程序在运行,所以还需要微调。
// 查看方式:cat /proc/cpuinfo | grep name | cut -f2 -d: | uniq -c
//
int main()
{
for(;;)
{
for(int i=0;i<5400000;i++)
{
;
}
usleep(1000*10);
}
}
| true |
c0a0c3e4d2ce4d389275e9cc0f8dd94130553a52
|
C++
|
noobneo/NoobEngine
|
/engine/maths/mat4.cpp
|
UTF-8
| 11,552 | 2.9375 | 3 |
[] |
no_license
|
#include "Mat4.h"
#include "vec3.h"
#include "vec4.h"
#include <string>
#include "math-common.h"
#ifdef TEST_MODE
#include "../enginelogger/enginelogger.h"
#endif
namespace enginecore {
namespace maths {
Mat4::Mat4()
{
memset(elements, 0, 4 * 4 * sizeof(float));
}
Mat4::Mat4(float diagonal)
{
memset(elements, 0, 4 * 4 * sizeof(float));
elements[0 + 0 * 4] = diagonal;
elements[1 + 1 * 4] = diagonal;
elements[2 + 2 * 4] = diagonal;
elements[3 + 3 * 4] = diagonal;
}
Mat4::Mat4(float* elements)
{
memcpy(this->elements, elements, 4 * 4 * sizeof(float));
}
Mat4::Mat4(const Vec4& row0, const Vec4& row1, const Vec4& row2, const Vec4& row3)
{
rows[0] = row0;
rows[1] = row1;
rows[2] = row2;
rows[3] = row3;
}
Mat4 Mat4::Identity()
{
return Mat4(1.0f);
}
Mat4& Mat4::Multiply(const Mat4& other)
{
float data[16];
for (int row = 0; row < 4; row++)
{
for (int col = 0; col < 4; col++)
{
float sum = 0.0f;
for (int e = 0; e < 4; e++)
{
sum += elements[e + row * 4] * other.elements[col + e * 4];
}
data[col + row * 4] = sum;
}
}
memcpy(elements, data, 4 * 4 * sizeof(float));
return *this;
}
Vec3 Mat4::Multiply(const Vec3& other) const
{
return other.Multiply(*this);
}
Vec4 Mat4::Multiply(const Vec4& other) const
{
return other.Multiply(*this);
}
Mat4 operator*(Mat4 left, const Mat4& right)
{
return left.Multiply(right);
}
Mat4& Mat4::operator*=(const Mat4& other)
{
return Multiply(other);
}
Vec3 operator*(const Mat4& left, const Vec3& right)
{
return left.Multiply(right);
}
Vec4 operator*(const Mat4& left, const Vec4& right)
{
return left.Multiply(right);
}
Mat4& Mat4::Invert()
{
float temp[16];
temp[0] = elements[5] * elements[10] * elements[15] -
elements[5] * elements[11] * elements[14] -
elements[9] * elements[6] * elements[15] +
elements[9] * elements[7] * elements[14] +
elements[13] * elements[6] * elements[11] -
elements[13] * elements[7] * elements[10];
temp[4] = -elements[4] * elements[10] * elements[15] +
elements[4] * elements[11] * elements[14] +
elements[8] * elements[6] * elements[15] -
elements[8] * elements[7] * elements[14] -
elements[12] * elements[6] * elements[11] +
elements[12] * elements[7] * elements[10];
temp[8] = elements[4] * elements[9] * elements[15] -
elements[4] * elements[11] * elements[13] -
elements[8] * elements[5] * elements[15] +
elements[8] * elements[7] * elements[13] +
elements[12] * elements[5] * elements[11] -
elements[12] * elements[7] * elements[9];
temp[12] = -elements[4] * elements[9] * elements[14] +
elements[4] * elements[10] * elements[13] +
elements[8] * elements[5] * elements[14] -
elements[8] * elements[6] * elements[13] -
elements[12] * elements[5] * elements[10] +
elements[12] * elements[6] * elements[9];
temp[1] = -elements[1] * elements[10] * elements[15] +
elements[1] * elements[11] * elements[14] +
elements[9] * elements[2] * elements[15] -
elements[9] * elements[3] * elements[14] -
elements[13] * elements[2] * elements[11] +
elements[13] * elements[3] * elements[10];
temp[5] = elements[0] * elements[10] * elements[15] -
elements[0] * elements[11] * elements[14] -
elements[8] * elements[2] * elements[15] +
elements[8] * elements[3] * elements[14] +
elements[12] * elements[2] * elements[11] -
elements[12] * elements[3] * elements[10];
temp[9] = -elements[0] * elements[9] * elements[15] +
elements[0] * elements[11] * elements[13] +
elements[8] * elements[1] * elements[15] -
elements[8] * elements[3] * elements[13] -
elements[12] * elements[1] * elements[11] +
elements[12] * elements[3] * elements[9];
temp[13] = elements[0] * elements[9] * elements[14] -
elements[0] * elements[10] * elements[13] -
elements[8] * elements[1] * elements[14] +
elements[8] * elements[2] * elements[13] +
elements[12] * elements[1] * elements[10] -
elements[12] * elements[2] * elements[9];
temp[2] = elements[1] * elements[6] * elements[15] -
elements[1] * elements[7] * elements[14] -
elements[5] * elements[2] * elements[15] +
elements[5] * elements[3] * elements[14] +
elements[13] * elements[2] * elements[7] -
elements[13] * elements[3] * elements[6];
temp[6] = -elements[0] * elements[6] * elements[15] +
elements[0] * elements[7] * elements[14] +
elements[4] * elements[2] * elements[15] -
elements[4] * elements[3] * elements[14] -
elements[12] * elements[2] * elements[7] +
elements[12] * elements[3] * elements[6];
temp[10] = elements[0] * elements[5] * elements[15] -
elements[0] * elements[7] * elements[13] -
elements[4] * elements[1] * elements[15] +
elements[4] * elements[3] * elements[13] +
elements[12] * elements[1] * elements[7] -
elements[12] * elements[3] * elements[5];
temp[14] = -elements[0] * elements[5] * elements[14] +
elements[0] * elements[6] * elements[13] +
elements[4] * elements[1] * elements[14] -
elements[4] * elements[2] * elements[13] -
elements[12] * elements[1] * elements[6] +
elements[12] * elements[2] * elements[5];
temp[3] = -elements[1] * elements[6] * elements[11] +
elements[1] * elements[7] * elements[10] +
elements[5] * elements[2] * elements[11] -
elements[5] * elements[3] * elements[10] -
elements[9] * elements[2] * elements[7] +
elements[9] * elements[3] * elements[6];
temp[7] = elements[0] * elements[6] * elements[11] -
elements[0] * elements[7] * elements[10] -
elements[4] * elements[2] * elements[11] +
elements[4] * elements[3] * elements[10] +
elements[8] * elements[2] * elements[7] -
elements[8] * elements[3] * elements[6];
temp[11] = -elements[0] * elements[5] * elements[11] +
elements[0] * elements[7] * elements[9] +
elements[4] * elements[1] * elements[11] -
elements[4] * elements[3] * elements[9] -
elements[8] * elements[1] * elements[7] +
elements[8] * elements[3] * elements[5];
temp[15] = elements[0] * elements[5] * elements[10] -
elements[0] * elements[6] * elements[9] -
elements[4] * elements[1] * elements[10] +
elements[4] * elements[2] * elements[9] +
elements[8] * elements[1] * elements[6] -
elements[8] * elements[2] * elements[5];
float determinant = elements[0] * temp[0] + elements[1] * temp[4] + elements[2] * temp[8] + elements[3] * temp[12];
determinant = 1.0f / determinant;
for (int i = 0; i < 4 * 4; i++)
elements[i] = temp[i] * determinant;
return *this;
}
Vec4 Mat4::GetColumn(int index)
{
return Vec4(elements[index + 0 * 4], elements[index + 1 * 4], elements[index + 2 * 4], elements[index + 3 * 4]);
}
void Mat4::SetColumn(int index, const Vec4& column)
{
elements[index + 0 * 4] = column.get_x();
elements[index + 1 * 4] = column.get_y();
elements[index + 2 * 4] = column.get_z();
elements[index + 3 * 4] = column.get_w();
}
Mat4 Mat4::Orthographic(float left, float right, float bottom, float top, float near, float far)
{
Mat4 result(1.0f);
result.elements[0 + 0 * 4] = 2.0f / (right - left);
result.elements[1 + 1 * 4] = 2.0f / (top - bottom);
result.elements[2 + 2 * 4] = 2.0f / (near - far);
result.elements[3 + 0 * 4] = (left + right) / (left - right);
result.elements[3 + 1 * 4] = (bottom + top) / (bottom - top);
result.elements[3 + 2 * 4] = -(far + near) / (far - near);
return result;
}
Mat4 Mat4::Perspective(float fov, float aspectRatio, float near, float far)
{
Mat4 result(1.0f);
float q = 1.0f / tan(ConvertToRadians(0.5f * fov));
float a = q / aspectRatio;
float b = (near + far) / (near - far);
float c = (2.0f * near * far) / (near - far);
result.elements[0 + 0 * 4] = a;
result.elements[1 + 1 * 4] = q;
result.elements[2 + 2 * 4] = b;
result.elements[2 + 3 * 4] = -1.0f;
result.elements[3 + 2 * 4] = c;
/*Mat4 result(1.0f);
float q = 1.0f / tanf(ConvertToRadians(0.5f * fov));
float a = q * aspectRatio;
float b = (near + far) / (near - far);
float c = (2.0f * near * far) / (near - far);
result.elements[0 + 0 * 4] = q;
result.elements[1 + 1 * 4] = a;
result.elements[2 + 2 * 4] = b;
result.elements[2 + 3 * 4] = c;
result.elements[3 + 2 * 4] = -1.0f;*/
return result;
}
Mat4 Mat4::LookAt(const Vec3& camera, const Vec3& object, const Vec3& up)
{
Mat4 result = Identity();
Vec3 f = (object - camera).Normalize();
Vec3 s = f.Cross(up.Normalize());
Vec3 u = s.Cross(f);
result.elements[0 + 0 * 4] = s.get_x();
result.elements[0 + 1 * 4] = s.get_y();
result.elements[0 + 2 * 4] = s.get_z();
result.elements[1 + 0 * 4] = u.get_x();
result.elements[1 + 1 * 4] = u.get_y();
result.elements[1 + 2 * 4] = u.get_z();
result.elements[2 + 0 * 4] = -f.get_x();
result.elements[2 + 1 * 4] = -f.get_y();
result.elements[2 + 2 * 4] = -f.get_z();
return result * Translate(Vec3(-camera.get_x(), -camera.get_y(), -camera.get_z()));
}
Mat4 Mat4::Translate(const Vec3& translate)
{
Mat4 result(1.0f);
result.elements[3 + 0 * 4] = translate.get_x();
result.elements[3 + 1 * 4] = translate.get_y();
result.elements[3 + 2 * 4] = translate.get_z();
return result;
}
Mat4 Mat4::Rotate(float angle, const Vec3& axis)
{
Mat4 result(1.0f);
float r = ConvertToRadians(angle);
float c = cos(r);
float s = sin(r);
float omc = 1.0f - c;
float x = axis.get_x();
float y = axis.get_y();
float z = axis.get_z();
result.elements[0 + 0 * 4] = x * x * omc + c;
result.elements[0 + 1 * 4] = y * x * omc + z * s;
result.elements[0 + 2 * 4] = x * z * omc - y * s;
result.elements[1 + 0 * 4] = x * y * omc - z * s;
result.elements[1 + 1 * 4] = y * y * omc + c;
result.elements[1 + 2 * 4] = y * z * omc + x * s;
result.elements[2 + 0 * 4] = x * z * omc + y * s;
result.elements[2 + 1 * 4] = y * z * omc - x * s;
result.elements[2 + 2 * 4] = z * z * omc + c;
return result;
}
Mat4 Mat4::Scale(const Vec3& scale)
{
Mat4 result(1.0f);
result.elements[0 + 0 * 4] = scale.get_x();
result.elements[1 + 1 * 4] = scale.get_y();
result.elements[2 + 2 * 4] = scale.get_z();
return result;
}
Mat4 Mat4::Invert(const Mat4& matrix)
{
Mat4 result = matrix;
return result.Invert();
}
Mat4 Mat4::Transpose(const Mat4& matrix)
{
return Mat4(
Vec4(matrix.rows[0].get_x(), matrix.rows[1].get_x(), matrix.rows[2].get_x(), matrix.rows[3].get_x()),
Vec4(matrix.rows[0].get_y(), matrix.rows[1].get_y(), matrix.rows[2].get_y(), matrix.rows[3].get_y()),
Vec4(matrix.rows[0].get_z(), matrix.rows[1].get_z(), matrix.rows[2].get_z(), matrix.rows[3].get_z()),
Vec4(matrix.rows[0].get_w(), matrix.rows[1].get_w(), matrix.rows[2].get_w(), matrix.rows[3].get_w())
);
}
Mat4 Mat4 ::Modeling(const Vec2& translate, const Vec2& scaling, float rotate) {
Vec3 t(translate);
Vec3 s(scaling);
Vec3 r(0.0f,1.0f,0.0f);
t.set_z(-3.0f);
// return Mat4(Translate(t)*Rotate(rotate, r)*Scale(s));
return Mat4(Scale(s));
}
void Mat4::Print() {
#ifdef TEST_MODE
for (int i = 0; i < 4; i++) {
ENGINE_LOG("%.2f %.2f %.2f %.2f", elements[i*4], elements[i * 4 + 1], elements[i * 4 + 2], elements[i * 4 + 3]);
}
#endif
}
}
}
| true |
4098d59553ae6e4cc2deda9105b1a006a9be9340
|
C++
|
RemmyChen/RemoteProcedureCall
|
/testarray1.cpp
|
UTF-8
| 287 | 2.578125 | 3 |
[] |
no_license
|
#include "testarray1.idl" // include the idl file
#include <cstdio>
int sqrt(int x[24], int y[24]) {
printf("server sqrt invoked with: \n");
int res = 0;
for (int i=0; i<24; i++) {
printf("%d\n", x[i]);
res += x[i];
}
printf("returning %d\n", res);
return res;
}
| true |
2e926cd928caf193f2389ca89906bbbab8242efe
|
C++
|
atbaird/ProceduralSystemsForNonCombatRPG
|
/Thesis/RPGWithNoCombat/Code/Game/Quest/QuestEvents/QuestTrigger.hpp
|
UTF-8
| 874 | 2.671875 | 3 |
[] |
no_license
|
#pragma once
#ifndef QUESTTRIGGER_HPP
#define QUESTTRIGGER_HPP
#include "Engine/EventSystem/NamedProperties.hpp"
#include "Engine/Core/StringUtils.hpp"
#include "Engine/Core/EngineXMLParser.hpp"
class Quest;
class QuestTrigger
{
private:
protected:
std::string m_TriggerName = "";
Quest* m_owningQuest = nullptr;
public:
//Constructors
QuestTrigger();
QuestTrigger(const XMLNode& node, Quest* owningQuest = nullptr);
QuestTrigger(const QuestTrigger& other, Quest* owningQuest = nullptr);
virtual ~QuestTrigger();
//Setters
void SetOwningQuest(Quest* quest);
//Getters
const Quest* GetOwningQuest() const;
Quest* GetEditableOwningQuest();
//Operations
virtual bool PerformQuestTrigger();
virtual QuestTrigger* Clone(Quest* owningQuest = nullptr) const = 0;
virtual void WriteQuestTriggerToString(std::string& str, int indentationAmt) const = 0;
};
#endif
| true |
8df9a7b528d7d6b6a53d23a182c50d03080f5bb8
|
C++
|
hoilus/LeetCode
|
/001-1-Two Sum.cpp
|
UTF-8
| 334 | 2.75 | 3 |
[] |
no_license
|
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> tmap;
for (int i = 0; i < nums.size(); i++) {
auto p = tmap.find(target-nums[i]);
if (p!=tmap.end())
return {p->second,i};
tmap[nums[i]] = i;
}
}
};
| true |
bd099547aece1fff5a125c21dd272bbe8d055340
|
C++
|
ilyamoskalev/Algorithms
|
/7_1/main.cpp
|
UTF-8
| 2,912 | 3.25 | 3 |
[] |
no_license
|
//7_1. Атлеты.
//В город N приехал цирк с командой атлетов. Они хотят удивить горожан города N — выстроить из своих тел
//башню максимальной высоты. Башня — это цепочка атлетов, первый стоит на земле, второй стоит у него на
//плечах, третий стоит на плечах у второго и т.д.Каждый атлет характеризуется силой si
//(kg) и массой mi(kg). Сила — это максимальная масса, которую атлет способен держать у себя на плечах.
//К сожалению ни один из атлетов не умеет программировать, так как всю жизнь они занимались физической подготовкой, и у них не было времени на изучение языков программирования. Помогите им, напишите
//программу, которая определит максимальную высоту башни, которую они могут составить.
//Известно, что если атлет тяжелее, то он и сильнее: если mi>mj, то si> sj.
//Атлеты равной массы могут иметь различную силу.
//Формат входных данных: Вход содержит только пары целых чисел — массу и силу атлетов. Число атлетов 1 ≤ n ≤ 100000. Масса и
//сила являются положительными целыми числами меньше, чем 2000000.
//Формат выходных данных: Выход должен содержать натуральное число — максимальную высоту башни.
#include <stdio.h>
#include <algorithm>
struct Athlete{
long int mass;
long int strong;
};
int maxHeight( Athlete* A, int &n ){
int CurrentHeight = 1;
long int CurrentMass = A[n - 1].mass;
for( int i = n - 2; i >= 0; i--){
if( A[i].strong >= CurrentMass ){
CurrentMass += A[i].mass;
++CurrentHeight;
}
}
return CurrentHeight;
}
int main(){
size_t size = 100000;
Athlete* A = new Athlete[size];
int n = 0;
long int a = 0;
long int b = 0;
while(n <= 100000 && scanf("%ld %ld", &a, &b) == 2) {
A[n].mass = a;
A[n].strong = b;
++n;
}
if (n == 1){
printf("1");
return 0;
}
std::sort( A , A + n, [](Athlete& a, Athlete& b){
if(a.mass == b.mass)
return a.strong > b.strong;
return a.mass > b.mass;});
printf("%d", maxHeight( A, n ));
delete[] A;
return 0;
}
| true |
39cfca69ee59cff3b71adb94316577bde8c838b7
|
C++
|
team3990/TechBot2014
|
/GamepadXbox.cpp
|
UTF-8
| 1,519 | 2.546875 | 3 |
[] |
no_license
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) TechForKid 2014. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
#include "GamepadXbox.h"
/* --------------------------------------------------------------------------- */
// Constructors
/**
* Construct an instance of a GamepadXbox.
* The joystick index is the usb port on the drivers station.
*
* @param port The port on the driver station that the joystick is plugged into.
*/
GamepadXbox::GamepadXbox(UINT32 port)
: Joystick(port)
{
}
GamepadXbox::~GamepadXbox()
{
}
/* --------------------------------------------------------------------------- */
// Methods
/**
* Get the X value of the joystick in ENU - BODY format.
*/
float GamepadXbox::GetLeftX()
{
return -Joystick::GetRawAxis(2); // Pour retourner la valeur Y de la classe de base, mais de sens inverse
}
float GamepadXbox::GetLeftY()
{
return Joystick::GetRawAxis(1);
}
float GamepadXbox::GetRightX()
{
return -Joystick::GetRawAxis(5);
}
float GamepadXbox::GetRightY()
{
return Joystick::GetRawAxis(4);
}
float GamepadXbox::Trigger()
{
// Left Trigger goes from 0 to 1;
// Right Trigger goes from -1 to 0;
return Joystick::GetRawAxis(3);
}
| true |
b093f450db1a3e739c7a6c35854baced55c88471
|
C++
|
guiOsorio/C-CPP-DataStructs
|
/Queue/main.cpp
|
UTF-8
| 2,889 | 4.125 | 4 |
[] |
no_license
|
// Implementation of queue using an array
#include<iostream>
using namespace std;
#define N 10
class Queue
{
private:
int A[N];
int front, rear;
public:
Queue()
{
front = -1;
rear = -1;
}
bool isEmpty() {
// checks if queue has at least one element
return (front == -1 && rear == -1);
}
int Front() {
// returns the 1st element in the queue (from front to back)
if(front == -1) return -1;
return A[front];
}
bool isFull() {
// checks if there is space available for one more element in the queue (since the queue is an array of fixed size)
return ((rear + 1) % N == front);
}
int enqueue(int x) {
// adds an element to the back of the queue
// case 1: queue has no elements
if(isEmpty()) {
front = rear = 0;
}
// case 2: queue has no space left for the enqueue operation
else if(isFull()) {
cout << "Can't enqueue because queue is full" << endl;
return -1;
}
// case 3: queue has elements and space to add one more in the back of the queue
else {
rear = (rear + 1) % N;
}
A[rear] = x;
return 0;
}
int dequeue() {
// removes an element from the front of the queue
// case 1: queue has no elements
if(isEmpty()) {
cout << "Can't dequeue because queue is empty" << endl;
return -1;
}
// case 2: there is only one element in the queue, so it will be empty after the dequeue operation
else if(front == rear) {
front = rear = -1;
}
// case 3: element can be removed from the front of the queue normally
else {
front = (front + 1) % N;
}
return 0;
}
void print() {
// prints all elements in the queue
int count = (rear + N - front) % N + 1;
cout << "Elements\n";
for(int i = 0; i < count; i++) {
int index = (front + i) % N;
cout << A[index] << " ";
}
cout << "\n\n";
}
};
int main() {
// test queue implementation
Queue Q;
if(Q.isEmpty()) {
cout << "True\n" << endl;
}
else {
cout << "False\n" << endl;
}
Q.enqueue(1);
if(Q.isEmpty()) {
cout << "True\n" << endl;
}
else {
cout << "False\n" << endl;
}
if(Q.isFull()) {
cout << "True\n" << endl;
}
else {
cout << "False\n" << endl;
}
Q.enqueue(2);
Q.enqueue(3);
Q.enqueue(4);
Q.enqueue(5);
Q.print();
Q.dequeue();
Q.print();
Q.enqueue(6);
Q.enqueue(7);
cout << Q.Front() << endl;
cout << "\n";
Q.enqueue(8);
Q.enqueue(9);
Q.enqueue(10);
Q.enqueue(11);
Q.print();
if(Q.isFull()) {
cout << "True" << endl;
}
else {
cout << "False" << endl;
}
}
| true |
a1ca2d45c54de0d9f28b56cb0a0f6575d43009d7
|
C++
|
99002537/Linux_assignment
|
/Activity_5/Q2.cpp
|
UTF-8
| 3,806 | 2.6875 | 3 |
[] |
no_license
|
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#define NUM_ELEM 15 /* Number of elements in shared memory buffer */
#define SEM_MUTEX 0
#define SEM_EMPTY 1
#define SEM_FULL 2
FILE* fp;
int rc, semID, shmID, status, i, x;
char elem;
union semun
{
int val;
struct semid_ds *buf;
ushort *array;
} seminfo;
struct sembuf WaitMutex={SEM_MUTEX, -1, 0};
struct sembuf SignalMutex={SEM_MUTEX, 1, 0};
struct sembuf WaitEmpty={SEM_EMPTY, -1, 0};
struct sembuf SignalEmpty={SEM_EMPTY, 1, 0};
struct sembuf WaitFull={SEM_FULL, -1, 0};
struct sembuf SignalFull={SEM_FULL, 1, 0};
struct shmid_ds shminfo;
char *shmPtr;
void initialize();
void producer();
void consumer();
main()
{
/* Open file */
fp= fopen("mytest.dat", "r");
/* Initialize shared memory and semaphores */
initialize();
/* Start a child process and proceed accordingly*/
if (fork()==0)
{
/* Child becomes the consumer */
consumer();
/* Child quits after consuming 26 characters */
exit(0);
}
else
{
/* Parent becomes the producer */
producer();
/* Wait for child to finish */
//wait(&status);
/* Remove shared memory */
shmctl(shmID, IPC_RMID, &shminfo);
/* Remove semaphores */
semctl(semID, SEM_MUTEX, IPC_RMID, seminfo);
/* Close file */
fclose(fp);
/* Parent is done cleaning up, so now quits */
exit(0);
}
}
void initialize()
{
/* Init semaphores */
/* Three semaphores (Empty, Full, Mutex) are created in one set */
semID=semget(IPC_PRIVATE, 3, 0666 | IPC_CREAT);
/* Init Mutex to one, allowing access to critical section */
seminfo.val=1;
semctl(semID, SEM_MUTEX, SETVAL, seminfo);
/* Init Empty to number of elements in shared memory (circular buffer) */
seminfo.val=NUM_ELEM;
semctl(semID, SEM_EMPTY, SETVAL, seminfo);
/* Init Full to zero, no elements are produced yet */
seminfo.val=0;
semctl(semID, SEM_FULL, SETVAL, seminfo);
/* Init Shared memory */
shmID=shmget(IPC_PRIVATE, NUM_ELEM, 0666 | IPC_CREAT);
}
void producer()
{
/* attach shared memory to process */
shmPtr=(char*)shmat(shmID, 0, SHM_W);
while((x = fgetc(fp)) != EOF)
{
/* Wait(Empty) - pause if no empty spots in circular buffer (i.e. all filled) */
semop(semID, &WaitEmpty, 1);
elem = x;
printf("Produced elem '%c'\n", elem);
/* Wait(Mutex) - don't touch shared memory while consumer is using it */
semop(semID, &WaitMutex, 1);
/* Put element into shared memory buffer (circular buffer) */
*(shmPtr + (i%NUM_ELEM))=elem;
/* Signal(Mutex) - allow consumer to access shared memory now */
semop(semID, &SignalMutex, 1);
/* Signal(Full) - record one more filled spot in circular buffer */
semop(semID, &SignalFull, 1);
}
}
void consumer()
{
/* attach shared memory to process */
shmPtr=(char*)shmat(shmID, 0, SHM_R);
while((elem != '*'))
{
/* Wait(Full) - pause if no filled spots in circular buffer (i.e. all empty) */
semop(semID, &WaitFull, 1);
/* Wait(Mutex) - don't touch shared memory while producer is using it */
semop(semID, &WaitMutex, 1);
/* Get element from the shared memory buffer (circular buffer) */
elem=*(shmPtr + (i%NUM_ELEM));
/* Signal(Mutex) - allow producer to access shared memory now */
semop(semID, &SignalMutex, 1);
/* Display character */
printf("Consumed elem '%c'\n", elem);
/* Signal(Empty) - record one more empty spot in circular buffer */
semop(semID, &SignalEmpty, 1);
}
}
| true |
a6ef5994909bfb0896419da70b7f99d3e42ed7af
|
C++
|
vrcordoba/NewsClustering
|
/src/NewsDiscriminator.cpp
|
UTF-8
| 1,464 | 2.859375 | 3 |
[] |
no_license
|
#include "NewsDiscriminator.h"
NewsDiscriminator::NewsDiscriminator() : firstReceived(TypeOfNews::notDetermined),
secondReceived(TypeOfNews::notDetermined)
{
}
NewsDiscriminator::~NewsDiscriminator()
{
}
NewsDiscriminator::DiscriminatorResult NewsDiscriminator::discriminateType(
const std::shared_ptr<News>& firstNews, const std::shared_ptr<News>& secondNews)
{
firstNews->accept(this);
secondNews->accept(this);
DiscriminatorResult result = bothFromNewspaper;
if (TypeOfNews::newspaperNews == firstReceived and TypeOfNews::twitterNews == secondReceived)
result = firstFromNewspaperSecondFromTwitter;
else if (TypeOfNews::twitterNews == firstReceived and TypeOfNews::newspaperNews == secondReceived)
result = firstFromTwitterSecondFromNewspaper;
else if (TypeOfNews::twitterNews == firstReceived and TypeOfNews::twitterNews == secondReceived)
result = bothFromTwitter;
firstReceived = TypeOfNews::notDetermined;
secondReceived = TypeOfNews::notDetermined;
return result;
}
void NewsDiscriminator::visit(const NewspaperNews* news)
{
if (TypeOfNews::notDetermined == firstReceived)
firstReceived = TypeOfNews::newspaperNews;
else
secondReceived = TypeOfNews::newspaperNews;
}
void NewsDiscriminator::visit(const TwitterNews* news)
{
if (TypeOfNews::notDetermined == firstReceived)
firstReceived = TypeOfNews::twitterNews;
else
secondReceived = TypeOfNews::twitterNews;
}
| true |
f6e7f498a76249414714ae3b23ec56226a2b0799
|
C++
|
nathanshaw/SNES_Circuit_Bending
|
/Firmware/automated_switcher/automated_switcher.ino
|
UTF-8
| 2,690 | 2.84375 | 3 |
[] |
no_license
|
/*
* Dirty POC program for operating the automated video switcher
* Sketch for controlling the AV switcher using an Arduino Nano and 8 relay switches
*/
// Arduino Pins (NANO)
uint8_t relayPins[] = {2, 3, 4, 5, 6, 7, 8, 11};
uint8_t rgbLedPins[] = {9, 10, 12};
int buttonPin = A0;
int potPin = A1;
// sensors
uint16_t potValue = 0;
bool buttonState = false;
bool lastButtonState = false;
uint64_t lastButtonPress = 0;
// switching output
uint64_t lastSwitch = 0;
float turnMult = 10.0;
uint16_t turnLength;
bool relayStates[] = {true, false, false, false,
false, false, false, false};
bool randomDst = true;
// debugging
uint8_t DEBUG = 0;
// Setup Loop
void setup() {
// set relay pins as outputs
for (int i = 0; i < 8; i++) {
pinMode(relayPins[i], OUTPUT);
}
// set led pins as outputs
for (int i = 0; i < 3; i++) {
pinMode(rgbLedPins[i], OUTPUT);
}
// set button pin as input
pinMode(buttonPin, INPUT);
//set pot pin as input
pinMode(potPin, INPUT);
if (DEBUG) {
Serial.begin(57600);
};
}
void loop() {
// put your main code here, to run repeatedly:
readSensors();
switchOutput();
if (DEBUG > 1) {printStats(DEBUG);};
}
void printStats(uint8_t debug) {
delay(debug);
Serial.print("Relay States : ");
for (int i = 0; i< 8; i++) {
Serial.print(relayStates[i]);
}
Serial.print(" pot : ");
Serial.print(potValue);
Serial.print(" button state : ");
Serial.print(buttonState);
Serial.print(" random dst : ");
Serial.println(randomDst);
}
void switchOutput() {
if (millis() > lastSwitch + turnLength) {
lastSwitch = millis();
if (randomDst) {
if(DEBUG){Serial.print(" random ");};
int choosen = random(0, 8);
for (int i = 0; i < 8; i++) {
digitalWrite(relayPins[i], LOW);
relayStates[i] = false;
}
digitalWrite(relayPins[choosen], HIGH);
relayStates[choosen] = true;
}
else {
if(DEBUG){Serial.print(" ordered ");};
for (int i = 0; i < 8; i++) {
if (relayStates[i] == true) {
if(DEBUG){Serial.print(" entered if ");};
digitalWrite(relayPins[i], LOW);
relayStates[i] = false;
digitalWrite(relayPins[(i + 1) % 7], HIGH);
relayStates[(i + 1) % 7] = true;
break;
}
}
}
}
}
void readSensors() {
potValue = analogRead(potPin);
lastButtonState = buttonState;
buttonState = digitalRead(buttonPin);
if(buttonState == lastButtonState) {
randomDst = buttonState;
}
turnLength = potValue * turnMult;
if (lastButtonState == false) {
if (buttonState == true) {
lastButtonPress = millis();
}
}
}
| true |
84dc1510090b522063118cb34d0f1f20dfeee1f5
|
C++
|
jhryu1208/MiniGame-BaseballGame
|
/BaseballGame/BaseballGame/BBG1.cpp
|
UHC
| 1,631 | 3.5 | 4 |
[] |
no_license
|
#include <iostream>
#include <time.h>
using namespace std;
enum SRP
{
SRP_S = 1,
SRP_R,
SRP_P,
SRP_END
};
int main()
{
//̺
srand((unsigned int)time(0));
int iPlayer, iAI;
while (true)
{
cout << "1. " << endl;
cout << "2. " << endl;
cout << "3. " << endl;
cout << "4. " << endl;
cout << " ϼ :" << endl;
cin >> iPlayer;
if (iPlayer<SRP_S || iPlayer>SRP_END)
{
cout << "߸ ԷϿϴ." << endl;
//Ͻ
system("pause");
//continue : ݺ ̵ִ
continue;
}
else if (iPlayer == SRP_END)
break;
// Ѵ.
iAI = rand() % 3 + SRP_S;
switch (iAI)
{
case SRP_S:
cout << "AI : " << endl;
break;
case SRP_R:
cout << "AI : " << endl;
break;
case SRP_P:
cout << "AI : " << endl;
break;
}
int iWin = iPlayer - iAI;
/*
if (iWin == 1 || iWin == -2)
cout << "Player ¸" << endl;
else if (iWin == 0)
cout << "ϴ" << endl;
else
cout << "AI ¸" << endl;
*/
switch (iWin)
{
case 1:
case -2:
cout << "player ¸" << endl;
break;
case 0:
cout << "ϴ" << endl;
break;
default:
cout << "AI ¸" << endl;
break;
}
// system("pause");
// ̰ "Ϸ ƹ Ű ʽÿ.." ִ Լ̴.
// Լ ؼ α ߰, ϰ ִ.
system("pause");
}
return 0;
}
| true |
06e7ddbd567e241b50b94d0bc044142fc1d8e565
|
C++
|
Miracle-cl/Algorithms
|
/BinarySearch/RussianDollEnvelopes.cpp
|
UTF-8
| 2,300 | 3.09375 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <algorithm>
using std::vector;
class Solution {
public:
int maxEnvelopes_0(vector<vector<int>>& envelopes) {
if (envelopes.empty()) return 0;
std::sort(envelopes.begin(), envelopes.end());
int maxl = 1, n = envelopes.size();
int dp[n];
dp[0] = 1;
for (int i = 1; i < n; ++i) {
dp[i] = 1;
for (int j = 0; j < i; ++j) {
if (envelopes[j][0] < envelopes[i][0] && envelopes[j][1] < envelopes[i][1])
dp[i] = std::max(dp[i], dp[j] + 1);
}
maxl = std::max(maxl, dp[i]);
}
return maxl;
}
int maxEnvelopes_1(vector<vector<int>>& envelopes) {
if (envelopes.empty()) return 0;
std::sort(envelopes.begin(), envelopes.end(), [](auto& v1, auto& v2) {
return (v1[0] < v2[0]) || (v1[0] == v2[0] && v1[1] > v2[1]);
});
int maxl = 1, n = envelopes.size();
int dp[n];
dp[0] = 1;
for (int i = 1; i < n; ++i) {
dp[i] = 1;
for (int j = 0; j < i; ++j) {
if (envelopes[j][1] < envelopes[i][1])
dp[i] = std::max(dp[i], dp[j] + 1);
}
maxl = std::max(maxl, dp[i]);
}
return maxl;
}
int maxEnvelopes_2(vector<vector<int>>& envelopes) {
if (envelopes.empty()) return 0;
std::sort(envelopes.begin(), envelopes.end(), [](auto& v1, auto& v2) {
return (v1[0] < v2[0]) || (v1[0] == v2[0] && v1[1] > v2[1]);
});
vector<int> increase_seq {envelopes[0][1]};
for (int i = 1; i < envelopes.size(); ++i) {
if (envelopes[i][1] > increase_seq.back()) {
increase_seq.emplace_back(envelopes[i][1]);
}
else {
int insert_id = std::lower_bound(increase_seq.begin(), increase_seq.end(), envelopes[i][1]) - increase_seq.begin();
increase_seq[insert_id] = envelopes[i][1];
}
}
return increase_seq.size();
}
};
int main()
{
vector<vector<int>> envelopes {{5,4},{6,9},{6,7},{2,3}};
Solution sol;
int res = sol.maxEnvelopes_2(envelopes);
std::cout << res << '\n';
return 0;
}
| true |
41b8de44708b6a2d4e8cc39a156ca931578a2ecb
|
C++
|
MISSCHERYLWANG/leetcode
|
/tree/btLevelTraversalII.cc
|
UTF-8
| 1,375 | 3.625 | 4 |
[] |
no_license
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
// 先求depth,然后dfs从depth-1开始
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> res;
levelOrderDFS(root, res, 0);
reverse(res.begin(), res.end());
return res;
}
void levelOrderDFS(TreeNode *root, vector<vector<int>>& res, int level) {
if (!root)
{
return;
}
if (level >= res.size())
{
res.push_back({});
}
res[level].push_back(root->val);
levelOrderDFS(root->left, res, level+1);
levelOrderDFS(root->right, res, level+1);
}
};
int main()
{
Solution sol = Solution();
TreeNode *root = new TreeNode(3);
TreeNode *node1 = new TreeNode(9);
TreeNode *node2 = new TreeNode(20);
TreeNode *node3 = new TreeNode(15);
TreeNode *node4 = new TreeNode(7);
root->left = node1; root->right = node2;
node2->left = node3; node2->right = node4;
vector<vector<int>> ans = sol.levelOrderBottom(root);
for (auto v: ans)
{
for (int num: v)
{
cout << num << " ";
}
cout << endl;
}
}
| true |
6807eb3171b97ccc5e445a86c9f5b965445dc5f1
|
C++
|
rlaqlc/Tic-Tac-Toe
|
/Tic Tac Toe/Board.cpp
|
UTF-8
| 11,869 | 3.046875 | 3 |
[] |
no_license
|
#include "Board.h"
#include <iostream>
Board::Board()
{
renderer = NULL;
}
void Board::setRenderer(SDL_Renderer * renderer)
{
this->renderer = renderer;
texture.setRenderer(renderer);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
tile[i][j].setRenderer(renderer);
}
}
writings[ROUND].setRenderer(renderer);
writings[PLAYER_SCORE].setRenderer(renderer);
writings[CPU_SCORE].setRenderer(renderer);
writings[TIE_COUNT].setRenderer(renderer);
writings[CROSS].setRenderer(renderer);
}
void Board::draw()
{
// draw the main board artwork
texture.loadFromFile(BOARD_FILE_PATH);
texture.render(0, 0);
// draw each tiles
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
tile[i][j].draw();
}
}
// draw writings on the board
writings[ROUND].draw();
writings[PLAYER_SCORE].draw();
writings[CPU_SCORE].draw();
writings[TIE_COUNT].draw();
writings[CROSS].draw();
}
void Board::setRound(int round)
{
if (round > 0 && round <= 3)
{
switch (round)
{
case 1:
writings[0].setSprite(1);
break;
case 2:
writings[0].setSprite(2);
break;
case 3:
writings[0].setSprite(3);
break;
}
}
}
void Board::setPlayerScore(int score)
{
if (score >= 0 && score <= 3)
{
switch (score)
{
case 0:
writings[PLAYER_SCORE].setSprite(7);
break;
case 1:
writings[PLAYER_SCORE].setSprite(4);
break;
case 2:
writings[PLAYER_SCORE].setSprite(5);
break;
case 3:
writings[PLAYER_SCORE].setSprite(6);
break;
}
}
}
void Board::setNumTies(int numTies)
{
if (numTies >= 0 && numTies <= 3)
{
switch (numTies)
{
case 0:
writings[TIE_COUNT].setSprite(7);
break;
case 1:
writings[TIE_COUNT].setSprite(4);
break;
case 2:
writings[TIE_COUNT].setSprite(5);
break;
case 3:
writings[TIE_COUNT].setSprite(6);
break;
}
}
}
void Board::setCpuScore(int score)
{
if (score >= 0 && score <= 3)
{
switch (score)
{
case 0:
writings[CPU_SCORE].setSprite(7);
break;
case 1:
writings[CPU_SCORE].setSprite(4);
break;
case 2:
writings[CPU_SCORE].setSprite(5);
break;
case 3:
writings[CPU_SCORE].setSprite(6);
break;
}
}
}
void Board::setTile(int x, int y)
{
if (x < 213 && y < 150 && x > 155 && y > 90 && tile[0][0].empty())
{
/*
[*][ ][ ]
[ ][ ][ ]
[ ][ ][ ]
*/
tile[0][0].setLetter('O');
tile[0][0].setSprite(1);
}
else if (x < 287 && y < 150 && x > 215 && y > 90 && tile[0][1].empty())
{
/*
[ ][*][ ]
[ ][ ][ ]
[ ][ ][ ]
*/
tile[0][1].setLetter('O');
tile[0][1].setSprite(1);
}
else if (x < 344 && y < 150 && x > 292 && y > 90 && tile[0][2].empty())
{
/*
[ ][ ][*]
[ ][ ][ ]
[ ][ ][ ]
*/
tile[0][2].setLetter('O');
tile[0][2].setSprite(1);
}
else if (x < 210 && y < 214 && x > 156 && y > 154 && tile[1][0].empty())
{
/*
[ ][ ][ ]
[*][ ][ ]
[ ][ ][ ]
*/
tile[1][0].setLetter('O');
tile[1][0].setSprite(1);
}
else if (x < 282 && y < 214 && x > 216 && y > 154 && tile[1][1].empty())
{
/*
[ ][ ][ ]
[ ][*][ ]
[ ][ ][ ]
*/
tile[1][1].setLetter('O');
tile[1][1].setSprite(1);
}
else if (x < 348 && y < 211 && x > 288 && y > 154 && tile[1][2].empty())
{
/*
[ ][ ][ ]
[ ][ ][*]
[ ][ ][ ]
*/
tile[1][2].setLetter('O');
tile[1][2].setSprite(1);
}
else if (x < 212 && y < 269 && x > 150 && y > 223 && tile[2][0].empty())
{
/*
[ ][ ][ ]
[ ][ ][ ]
[*][ ][ ]
*/
tile[2][0].setLetter('O');
tile[2][0].setSprite(1);
}
else if (x < 280 && y < 269 && x > 218 && y > 223 && tile[2][1].empty())
{
/*
[ ][ ][ ]
[ ][ ][ ]
[ ][*][ ]
*/
tile[2][1].setLetter('O');
tile[2][1].setSprite(1);
}
else if (x < 344 && y < 265 && x > 288 && y > 219 && tile[2][2].empty())
{
/*
[ ][ ][ ]
[ ][ ][ ]
[ ][ ][*]
*/
tile[2][2].setLetter('O');
tile[2][2].setSprite(1);
}
}
void Board::setTile(Player player)
{
bool done = false;
while (!done)
{
int x = player.getCpuColValue();
int y = player.getCpuRowValue();
if (tile[y][x].empty())
{
tile[y][x].setLetter('X');
tile[y][x].setSprite(2);
done = true;
}
}
}
void Board::loadSpriteSheet()
{
tile[0][0].setPosition(170, 108);
tile[0][1].setPosition(237, 108);
tile[0][2].setPosition(304, 108);
tile[1][0].setPosition(170, 176);
tile[1][1].setPosition(237, 174);
tile[1][2].setPosition(304, 173);
tile[2][0].setPosition(170, 238);
tile[2][1].setPosition(237, 235);
tile[2][2].setPosition(304, 233);
writings[0].setPosition(455, 187);
writings[1].setPosition(150, 340);
writings[2].setPosition(452, 340);
writings[3].setPosition(295, 340);
}
// checks if the mouse cursor is in a tile boundary
bool Board::isOnBoard(int x, int y)
{
bool onBoard = false;
if (x < 213 && y < 150 && x > 155 && y > 90 && tile[0][0].empty())
{
onBoard = true;
}
else if (x < 287 && y < 150 && x > 215 && y > 90 && tile[0][1].empty())
{
onBoard = true;
}
else if (x < 344 && y < 150 && x > 292 && y > 90 && tile[0][2].empty())
{
onBoard = true;
}
else if (x < 210 && y < 214 && x > 156 && y > 154 && tile[1][0].empty())
{
onBoard = true;
}
else if (x < 282 && y < 214 && x > 216 && y > 154 && tile[1][1].empty())
{
onBoard = true;
}
else if (x < 348 && y < 211 && x > 288 && y > 154 && tile[1][2].empty())
{
onBoard = true;
}
else if (x < 212 && y < 269 && x > 150 && y > 223 && tile[2][0].empty())
{
onBoard = true;
}
else if (x < 280 && y < 269 && x > 218 && y > 223 && tile[2][1].empty())
{
onBoard = true;
}
else if (x < 344 && y < 265 && x > 288 && y > 219 && tile[2][2].empty())
{
onBoard = true;
}
return onBoard;
}
void Board::setCrossingLine(int n)
{
switch (n)
{
case 0:
writings[CROSS].setSprite(0);
break;
case 1:
/*
[O][O][O]
[ ][ ][ ]
[ ][ ][ ]
*/
writings[CROSS].setPosition(175, 120);
writings[CROSS].setSprite(8);
break;
case 2:
/*
[ ][ ][ ]
[0][0][0]
[ ][ ][ ]
*/
writings[CROSS].setPosition(175, 185);
writings[CROSS].setSprite(8);
break;
case 3:
/*
[ ][ ][ ]
[ ][ ][ ]
[0][0][0]
*/
writings[CROSS].setPosition(175, 245);
writings[CROSS].setSprite(8);
break;
case 4:
/*
[O][ ][ ]
[0][ ][ ]
[0][ ][ ]
*/
writings[CROSS].setPosition(181, 111);
writings[CROSS].setSprite(9);
break;
case 5:
/*
[ ][0][ ]
[ ][0][ ]
[ ][0][ ]
*/
writings[CROSS].setPosition(248, 108);
writings[CROSS].setSprite(9);
break;
case 6:
/*
[ ][ ][0]
[ ][ ][0]
[ ][ ][0]
*/
writings[CROSS].setPosition(316, 107);
writings[CROSS].setSprite(9);
break;
case 7:
break;
case 8:
break;
}
}
void Board::setSprite(int x, int y)
{
loadSpriteSheet();
/*
[*][ ][ ]
[ ][ ][ ]
[ ][ ][ ]
*/
if (x < 213 && y < 150 && x > 155 && y > 90 && tile[0][0].empty())
{
tile[0][0].setSprite(1);
}
else
{
// to prevent from already occupied tile changes
if (tile[0][0].empty())
{
tile[0][0].setSprite(3);
}
}
/*
[ ][*][ ]
[ ][ ][ ]
[ ][ ][ ]
*/
if (x < 287 && y < 150 && x > 215 && y > 90 && tile[0][1].empty())
{
tile[0][1].setSprite(1);
}
else
{
if (tile[0][1].empty())
{
tile[0][1].setSprite(3);
}
}
/*
[ ][ ][*]
[ ][ ][ ]
[ ][ ][ ]
*/
if (x < 344 && y < 150 && x > 292 && y > 90 && tile[0][2].empty())
{
tile[0][2].setSprite(1);
}
else
{
if (tile[0][2].empty())
{
tile[0][2].setSprite(3);
}
}
/*
[ ][ ][ ]
[*][ ][ ]
[ ][ ][ ]
*/
if (x < 210 && y < 214 && x > 156 && y > 154 && tile[1][0].empty())
{
tile[1][0].setSprite(1);
}
else
{
if (tile[1][0].empty())
{
tile[1][0].setSprite(3);
}
}
/*
[ ][ ][ ]
[ ][*][ ]
[ ][ ][ ]
*/
if (x < 282 && y < 214 && x > 216 && y > 154 && tile[1][1].empty())
{
tile[1][1].setSprite(1);
}
else
{
if (tile[1][1].empty())
{
tile[1][1].setSprite(3);
}
}
/*
[ ][ ][ ]
[ ][ ][*]
[ ][ ][ ]
*/
if (x < 348 && y < 211 && x > 288 && y > 154 && tile[1][2].empty())
{
tile[1][2].setSprite(1);
}
else
{
if (tile[1][2].empty())
{
tile[1][2].setSprite(3);
}
}
/*
[ ][ ][ ]
[ ][ ][ ]
[*][ ][ ]
*/
if (x < 212 && y < 269 && x > 150 && y > 223 && tile[2][0].empty())
{
tile[2][0].setSprite(1);
}
else
{
if (tile[2][0].empty())
{
tile[2][0].setSprite(3);
}
}
/*
[ ][ ][ ]
[ ][ ][ ]
[ ][*][ ]
*/
if (x < 280 && y < 269 && x > 218 && y > 223 && tile[2][1].empty())
{
tile[2][1].setSprite(1);
}
else
{
if (tile[2][1].empty())
{
tile[2][1].setSprite(3);
}
}
/*
[ ][ ][ ]
[ ][ ][ ]
[ ][ ][*]
*/
if (x < 344 && y < 265 && x > 288 && y > 219 && tile[2][2].empty())
{
tile[2][2].setSprite(1);
}
else
{
if (tile[2][2].empty())
{
tile[2][2].setSprite(3);
}
}
}
bool Board::isFull()
{
bool full = true;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (tile[i][j].empty())
{
full = false;
}
}
}
return full;
}
void Board::clear()
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
tile[i][j].setLetter('n');
}
}
}
int Board::checkWinner()
{
// check col
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j += 3)
{
if (tile[i][j].getLetter() == 'O' &&
tile[i][j + 1].getLetter() == 'O' &&
tile[i][j + 2].getLetter() == 'O')
{
return 1;
}
else if (tile[i][j].getLetter() == 'X' &&
tile[i][j + 1].getLetter() == 'X' &&
tile[i][j + 2].getLetter() == 'X')
{
return 2;
}
}
}
// check row
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j += 3)
{
if (tile[j][i].getLetter() == 'O' &&
tile[j + 1][i].getLetter() == 'O' &&
tile[j + 2][i].getLetter() == 'O')
{
return 1;
}
else if (tile[j][i].getLetter() == 'X' &&
tile[j + 1][i].getLetter() == 'X' &&
tile[j + 2][i].getLetter() == 'X')
{
return 2;
}
}
}
// check 1st diagonal
if (tile[2][0].getLetter() == 'O' &&
tile[1][1].getLetter() == 'O' &&
tile[0][2].getLetter() == 'O')
{
return 1;
}
else if (tile[2][0].getLetter() == 'X' &&
tile[1][1].getLetter() == 'X' &&
tile[0][2].getLetter() == 'X')
{
return 2;
}
// check 2nd diagonal
if (tile[0][0].getLetter() == 'O' &&
tile[1][1].getLetter() == 'O' &&
tile[2][2].getLetter() == 'O')
{
return 1;
}
else if (tile[0][0].getLetter() == 'X' &&
tile[1][1].getLetter() == 'X' &&
tile[2][2].getLetter() == 'X')
{
return 2;
}
// 0 indicates no winner found
return 0;
}
int Board::getCrossingPos()
{
// check col
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j += 3)
{
if (tile[i][j].getLetter() == 'O' &&
tile[i][j + 1].getLetter() == 'O' &&
tile[i][j + 2].getLetter() == 'O')
{
return i + 1;
}
else if (tile[i][j].getLetter() == 'X' &&
tile[i][j + 1].getLetter() == 'X' &&
tile[i][j + 2].getLetter() == 'X')
{
return i + 1;
}
}
}
// check row
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j += 3)
{
if (tile[j][i].getLetter() == 'O' &&
tile[j + 1][i].getLetter() == 'O' &&
tile[j + 2][i].getLetter() == 'O')
{
return i + 4;
}
else if (tile[j][i].getLetter() == 'X' &&
tile[j + 1][i].getLetter() == 'X' &&
tile[j + 2][i].getLetter() == 'X')
{
return i + 4;
}
}
}
// check 1st diagonal
if (tile[2][0].getLetter() == 'O' &&
tile[1][1].getLetter() == 'O' &&
tile[0][2].getLetter() == 'O')
{
return 0;
}
else if (tile[2][0].getLetter() == 'X' &&
tile[1][1].getLetter() == 'X' &&
tile[0][2].getLetter() == 'X')
{
return 0;
}
// check 2nd diagonal
if (tile[0][0].getLetter() == 'O' &&
tile[1][1].getLetter() == 'O' &&
tile[2][2].getLetter() == 'O')
{
return 0;
}
else if (tile[0][0].getLetter() == 'X' &&
tile[1][1].getLetter() == 'X' &&
tile[2][2].getLetter() == 'X')
{
return 0;
}
// 0 indicates no winner found
return 0;
}
Board::~Board()
{
}
| true |
dffb83f333bc95531070175c00401a1a1b459b79
|
C++
|
seanballais/foxy-journey-port
|
/code/biomManager.cpp
|
UTF-8
| 2,793 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
#include "biomManager.h"
biomManager::biomManager(physicsObject * pPlayer)
{
int idx = rand() % 3 + 1;
switch (idx)
{
case HILLS:
biomsToDraw.push_back(new biom("hills_start", "hills"));
biomsToDraw.push_back(new biom("hills", "hills"));
biomsToDraw.push_back(new biom("hills_end", "hills"));
break;
case MOUNTAINS:
biomsToDraw.push_back(new biom("mountains_start", "mountains"));
biomsToDraw.push_back(new biom("mountains", "mountains"));
biomsToDraw.push_back(new biom("mountains_end", "mountains"));
break;
case BAMBOO:
biomsToDraw.push_back(new biom("bamboo_start", "bamboo"));
biomsToDraw.push_back(new biom("bamboo", "bamboo"));
biomsToDraw.push_back(new biom("bamboo_end", "bamboo"));
break;
}
player = pPlayer;
}
biomManager::~biomManager()
{
for (auto & b : biomsToDraw)
{
delete b;
}
}
void biomManager::update(Camera & pCamera, float deltaTime, int marginY)
{
if (!biomsToDraw.empty())
{
biomsToDraw.front()->setPosition(getPosition());
accumulatedOffset += player->vx * deltaTime * 0.25f;
float moveValue = accumulatedOffset;
if (moveValue >= WINDOW_WIDTH)
{
accumulatedOffset = 0.0f;
delete biomsToDraw.front();
biomsToDraw.pop_front();
if (!biomsToDraw.empty())
{
biomsToDraw.front()->setPosition(getPosition());
}
}
else
{
biomsToDraw.front()->move(moveValue * -1, 0);
}
if(biomsToDraw.size() > 1)
for (size_t i = 1; i < biomsToDraw.size(); i++)
{
biomsToDraw[i]->setPosition(biomsToDraw[i - 1]->getPosition() + sf::Vector2f(WINDOW_WIDTH, 0));
}
if (biomsToDraw.size() == 1)
{
int index = rand() % 3 + 1;
addBiom(index);
}
}
}
void biomManager::draw(sf::RenderTarget & target, sf::RenderStates states) const
{
for (auto & b : biomsToDraw)
{
target.draw(*b, states);
}
}
void biomManager::addBiom(int biomId)
{
if(!biomsToDraw.empty())
//biomsToDraw.push_back(new biom(biomsToDraw.front()->biomId + "_end",biomsToDraw.front()->biomId));
switch (biomId)
{
case HILLS:
biomsToDraw.push_back(new biom("hills_start","hills"));
biomsToDraw.push_back(new biom("hills","hills"));
biomsToDraw.push_back(new biom("hills_end", "hills"));
break;
case MOUNTAINS:
biomsToDraw.push_back(new biom("mountains_start","mountains"));
biomsToDraw.push_back(new biom("mountains","mountains"));
biomsToDraw.push_back(new biom("mountains_end", "mountains"));
break;
case BAMBOO:
biomsToDraw.push_back(new biom("bamboo_start", "bamboo"));
biomsToDraw.push_back(new biom("bamboo", "bamboo"));
biomsToDraw.push_back(new biom("bamboo_end", "bamboo"));
break;
}
}
| true |
1ef264ab9386332ee96e6871ac202aede4d40f1f
|
C++
|
micmacIGN/micmac
|
/MMVII/src/UtiMaths/uti_fonc_analytique.cpp
|
UTF-8
| 5,922 | 2.796875 | 3 |
[
"LicenseRef-scancode-cecill-b-en"
] |
permissive
|
#include "MMVII_Ptxd.h"
namespace MMVII
{
/*
template TYPE Sqrt(const TYPE & aSin);
template <typename Type> Type Sqrt(const Type & aX)
{
MMVII_INTERNAL_ASSERT_tiny((aX>=0),"Bad value for arcsinus");
return std::sqrt(aX);
}
*/
template <typename Type> Type DerSqrt(const Type & aX)
{
MMVII_INTERNAL_ASSERT_tiny((aX>0),"Bad value for arcsinus");
return 1/(2*std::sqrt(aX));
}
template <typename Type> Type DerASin(const Type & aSin)
{
Type UMS2 = 1-Square(aSin);
MMVII_ASSERT_STRICT_POS_VALUE(UMS2);
return 1 / std::sqrt(UMS2);
}
template <typename Type> Type ASin(const Type & aSin)
{
MMVII_INTERNAL_ASSERT_tiny((aSin>=-1) && (aSin<=1),"Bad value for arcsinus");
return std::asin(aSin);
}
constexpr int Fact3 = 2 * 3;
constexpr int Fact5 = 2 * 3 * 4 * 5; // Dont use Fact3, we dont control order of creation
constexpr int Fact7 = 2 * 3 * 4 * 5 * 6 * 7 ;
constexpr int Fact9 = 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9;
constexpr int Fact11 = 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9;
template <typename Type> Type DerSinC(const Type & aTeta,const Type & aEps)
{
/* sin(X)/X' = (x cos(x) -sinx) / X^ 2 */
if (std::abs(aTeta) > aEps)
return (aTeta*std::cos(aTeta)-std::sin(aTeta))/Square(aTeta);
Type aTeta2 = Square(aTeta);
Type aT3 = aTeta * aTeta2;
Type aT5 = aT3 * aTeta2;
Type aT7 = aT5 * aTeta2;
Type aT9 = aT7 * aTeta2;
return - aTeta * (static_cast<Type>(2.0)/static_cast<Type>(Fact3))
+ aT3 * (static_cast<Type>(4.0)/static_cast<Type>(Fact5))
- aT5 * (static_cast<Type>(6.0)/static_cast<Type>(Fact7))
+ aT7 * (static_cast<Type>(8.0)/static_cast<Type>(Fact9))
- aT9 * (static_cast<Type>(10.0)/static_cast<Type>(Fact11));
}
template <typename Type> Type DerSinC(const Type & aTeta)
{
return DerSinC(aTeta,tElemNumTrait<Type>::Accuracy());
}
template <typename Type> Type sinC(const Type & aTeta,const Type & aEps)
{
// x - x3/3! + x5/5! - x7/7! +
if (std::abs(aTeta) > aEps)
return std::sin(aTeta)/aTeta;
Type aT2 = Square(aTeta);
Type aT4 = Square(aT2);
Type aT6 = aT4 * aT2;
Type aT8 = Square(aT4);
return static_cast<Type>(1.0) - aT2/static_cast<Type>(Fact3) + aT4/static_cast<Type>(Fact5) - aT6/static_cast<Type>(Fact7) + aT8/static_cast<Type>(Fact9);
}
template <typename Type> Type sinC(const Type & aTeta)
{
return sinC(aTeta,tElemNumTrait<Type>::Accuracy());
}
template <typename Type> Type AtanXsY_sX(const Type & X,const Type & Y,const Type & aEps)
{
if (std::abs(X) > aEps * std::abs(Y))
return std::atan2(X,Y) / X;
Type XsY2 = Square(X/Y);
Type XsY4 = XsY2 * XsY2;
Type XsY6 = XsY4 * XsY2;
Type XsY8 = XsY4 * XsY4;
return (1
- static_cast<Type>(XsY2)/static_cast<Type>(3.0)
+ static_cast<Type>(XsY4)/static_cast<Type>(5.0)
- static_cast<Type>(XsY6)/static_cast<Type>(7.0)
+ static_cast<Type>(XsY8)/static_cast<Type>(9.0) ) / static_cast<Type>(Y);
}
template <typename Type> Type AtanXsY_sX(const Type & X,const Type & Y)
{
return AtanXsY_sX(X,Y,tElemNumTrait<Type>::Accuracy() );
}
template <typename Type> Type DerXAtanXsY_sX(const Type & X,const Type & Y,const Type & aEps)
{
// atan(x/y) /x => -1/x2 atan(x/y) + 1/xy 1/(1+x/y^2)
if (std::abs(X) > aEps * std::abs(Y))
return -std::atan2(X,Y)/Square(X) + Y/(X*(Square(X)+Square(Y)));
Type XsY2 = Square(X/Y);
Type XsY4 = XsY2 * XsY2;
Type XsY6 = XsY4 * XsY2;
Type XsY8 = XsY4 * XsY4;
return (X/Cube(Y)) * ( - static_cast<Type>(2.0/3.0)
+ static_cast<Type>(4.0/5.0) * XsY2
- static_cast<Type>(6.0/7.0) * XsY4
+ static_cast<Type>(8.0/9.0) * XsY6
- static_cast<Type>(10.0/11.0) * XsY8);
}
template <typename Type> Type DerXAtanXsY_sX(const Type & X,const Type & Y)
{
return DerXAtanXsY_sX(X,Y,tElemNumTrait<Type>::Accuracy());
}
template <typename Type> Type DerYAtanXsY_sX(const Type & X,const Type & Y)
{
return -1/(Square(X)+Square(Y));
}
template <typename Type> Type ATan2(const Type & aX,const Type & aY)
{
MMVII_INTERNAL_ASSERT_tiny((aX!=0)||(aY!=0),"Bad value for arcsinus");
return std::atan2(aX,aY);
}
template <typename Type> Type DerX_ATan2(const Type & aX,const Type & aY)
{
MMVII_INTERNAL_ASSERT_tiny((aX!=0)||(aY!=0),"Bad value for arcsinus");
return aY / (Square(aX)+Square(aY));
}
template <typename Type> Type DerY_ATan2(const Type & aX,const Type & aY)
{
MMVII_INTERNAL_ASSERT_tiny((aX!=0)||(aY!=0),"Bad value for arcsinus");
return (- aX) / (Square(aX)+Square(aY));
}
template <typename Type> Type sinH(const Type & aX) {return std::exp(aX)-std::exp(-aX);}
template <typename Type> Type cosH(const Type & aX) {return std::exp(aX)+std::exp(-aX);}
#define INSTATIATE_FUNC_ANALYTIQUE(TYPE)\
template TYPE DerSqrt(const TYPE & aSin);\
template TYPE DerASin(const TYPE & aSin);\
template TYPE ASin(const TYPE & aSin);\
template TYPE sinC(const TYPE & aTeta,const TYPE & aEps);\
template TYPE sinC(const TYPE & aTeta);\
template TYPE DerSinC(const TYPE & aTeta,const TYPE & aEps);\
template TYPE DerSinC(const TYPE & aTeta);\
template TYPE ATan2(const TYPE & X,const TYPE & Y);\
template TYPE DerX_ATan2(const TYPE & X,const TYPE & Y);\
template TYPE DerY_ATan2(const TYPE & X,const TYPE & Y);\
template TYPE AtanXsY_sX(const TYPE & X,const TYPE & Y,const TYPE & aEps);\
template TYPE AtanXsY_sX(const TYPE & X,const TYPE & Y);\
template TYPE DerXAtanXsY_sX(const TYPE & X,const TYPE & Y,const TYPE & aEps);\
template TYPE DerXAtanXsY_sX(const TYPE & X,const TYPE & Y);\
template TYPE DerYAtanXsY_sX(const TYPE & X,const TYPE & Y);\
template TYPE sinH(const TYPE & );\
template TYPE cosH(const TYPE & );
INSTATIATE_FUNC_ANALYTIQUE(tREAL4)
INSTATIATE_FUNC_ANALYTIQUE(tREAL8)
INSTATIATE_FUNC_ANALYTIQUE(tREAL16)
};
| true |
a3426f51e4dd71273ba54c062c287cba98169428
|
C++
|
memmaprofeten/dungeoncrawler4
|
/src/room.hpp
|
UTF-8
| 5,929 | 3 | 3 |
[] |
no_license
|
#ifndef ROOM_HH
#define ROOM_HH
#include "tile.hpp"
#include <vector>
#include <SFML/Graphics.hpp>
#include <iostream>
#include <string>
#include "monster.hpp"
class Projectile;
class Character;
class Weapon;
class Npc;
class Room {
public:
/**
* Constructor creating the room by loading it from the given file.
*/
Room(std::string const file, Character* character);
/**
* Constructor creating a random generated room based on the given
* parameters.
*/
Room(int width, int height, float p, int randomGenIterations, std::vector<bool> entrances, Character* character);
/**
* The Room destructor
*/
~Room();
/**
* Returns the width of the room (in blocks)
*/
int getWidth() const;
/**
* Returns the height of the room (in blocks)
*/
int getHeight() const;
/**
* Checks whether the room contains the coordinates at (x, y) (= not out of bounds).
*/
bool hasCoordinate(int x, int y);
/**
* Checks whether the room contains the given position (= not out of bounds).
*/
bool hasPosition(sf::Vector2f pos);
/**
* Returns a 2D vector describing in which direction(s) the given position
* is out of bounds. If the given position is still within bounds, the
* returned vector is the zero vector.
*/
sf::Vector2i getOffsetDirection(sf::Vector2f pos);
/**
* Returns a reference to the tile at coordinates (x, y).
* If (x, y) are invalid coordinates, an error is thrown.
*/
Tile& getTile(int x, int y);
/**
* Returns a reference to the tile at position pos.
* If pos is out of bounds, an error is thrown.
*/
Tile& getTile(sf::Vector2f pos);
/**
* Returns a vector of neighbour coordinates to teh coordinate at (x, y).
* If 'includingSelf' is true, the original coordinate is included.
* If 'includingDiagonals' is true, the diagonal neighbours are included.
* If 'includingOutsiders' is true, such neighbours that are out of bounds are included.
*/
std::vector<sf::Vector2i> getNeighbours(int x, int y, bool includingSelf, bool includingDiagonals, bool includingOutsiders);
/**
* Performs an attack from the given position, in the given direction, with
* the given weapon. If friendly, the attack targets only monsters. If not,
* it targets only monsters.
*/
void performAttack(bool friendly, sf::Vector2f source, sf::Vector2f direction, const Weapon& weapon);
/**
* Draws the room.
*/
void draw(sf::RenderWindow& window);
/**
* Updates the projectiles in the room and draws them.
*/
void drawProjectiles(sf::RenderWindow& window, float elapsed);
/**
* Calls the monster AI for each monster in this room and draws them.
*/
void drawmonsters(float elapsed, sf::RenderWindow& window);
/**
* Calls any necessary frame calls for the NPCs in this room and draws them.
*/
void drawnpcs(sf::RenderWindow& window);
/**
* Returns a reference to the vector containing pointers to all the NPCs in
* this room.
*/
std::vector<Npc*>& getNpcs();
/**
* Draws the items on the ground.
*/
void drawitems(sf::RenderWindow& window);
/**
* Adds an item to the ground.
*/
void additem(Item* newitem);
/**
* Identifies if there is any item on the ground within reach from the
* the player. If one such item is found, it is picked up. Therefore, a
* maximum of 1 item can be picked up each frame.
*/
void checkDrops();
/**
* Prints the room to std::cout.
*/
void print();
/**
* Returns a 2D vector of booleans representing the room, where a 'true'
* value represents a non-penetrable cell and a 'false' value represents
* a penetrable cell.
*/
std::vector<std::vector<bool>> getPenetrabilityMap();
/**
* Returns refernce to a sprite for the sprite resuse ecosystem.
*/
sf::Sprite* getSprite();
/**
* Deactivates a sprite for other instances to use.
*/
void deactivateSprite(sf::Sprite* sprite);
/**
* Adds a projectile with the input parameters as constructor parameters
* to this room and returns the projectile index of this projectile in the
* Room's projectile buffer.
* NB! Always use this method to add a projectile - never use the Projectile
* class' explicit constructor! (This method will try to reactivate a
* deactivated projectile class in its projectile buffer and assign these
* parameters to it.)
*/
Projectile& createProjectile(bool shotbyplayer, int damagein, int radiusin, float speedin, int txtrIndex);
/**
* Returns a reference to the monster vector of the room, i.e., pointers to
* all the monsters that are currently in the room (active or inactive).
*/
std::vector<Monster*>& getmonsters();
/**
* Returns a reference to the tile vector of the room, i.e. pointers to all
* the items that are currently on the ground in the room.
*/
std::vector<Item*>& getitems();
/**
* Returns a pointer to the room's character.
*/
Character* getcharacter();
/**
* Adds the given monster to the room.
*/
void addmonster(Monster* monsteri);
/**
* Adds the given NPC to the room.
*/
void addNpc(Npc* npc);
private:
int width; // The room's width, in terms of cells (tiles)
int height; // The rooms' height, in terms of cells (tiles)
Character* character; // A pointer to the character
std::vector<std::vector<Tile>> room; // A 2D-array of tile-objects mapping the game room.
std::vector<sf::Sprite> sprites; // All sprites belonging to different objects in this room
std::vector<bool> spritesInUse; // A vector of flags telling if the sprite at that index is to be drawn
std::vector<Projectile> projectiles; // The rooms' projectiles
std::vector<int> freeProjectiles; // A vector of projectile indices that are free for replacement
std::vector<Monster*> monsters; // Vector containing pointers to monsters in the room
std::vector<Npc*> npcs; // Vector of NPC:s
std::vector<Item*> itemstorage; // Vector containing items in the room
};
#endif
| true |
c3b428be9058310bc423dab2a57d9ab1665cdbca
|
C++
|
Aashutosh97/Launchpad17-Fasttrack
|
/21_graphs/graph.cc
|
UTF-8
| 1,449 | 3.203125 | 3 |
[] |
no_license
|
// Deepak Aggarwal, Coding Blocks
// deepak@codingblocks.com
#include <iostream>
#include <vector>
using namespace std;
class Graph {
typedef vector<vector<int> > vvi;
vvi vtxList;
int nVertices;
void dfs(int src, vector<bool>& visited) {
// if (visited[src] == true) return;
cout << src << " ";
visited[src] = true;
vector<int>& ngbrList = vtxList[src];
for (int i = 0; i < ngbrList.size(); ++i) {
int curNgbr = ngbrList[i];
if (visited[curNgbr] == false) {
dfs(ngbrList[i], visited);
}
}
}
public:
Graph(int n) {
nVertices = n;
vtxList.resize(n);
}
void addEdge(int src, int dest, int biDirectional = true) {
vtxList[src].push_back(dest);
if (biDirectional) {
vtxList[dest].push_back(src);
}
}
void print() {
for (int i = 0; i < nVertices; ++i) {
cout << i << "\t: ";
for (int j = 0; j < vtxList[i].size(); ++j) {
cout << vtxList[i][j] << " ";
}
cout << endl;
}
}
void dfs(int src) {
vector<bool> visited(nVertices, false); // look vector ctor C++.com
dfs(src, visited);
}
};
int main() {
Graph g(5);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(0, 3);
g.addEdge(1, 3);
g.addEdge(2, 4);
g.addEdge(3, 4);
g.print();
g.dfs(0);
}
| true |
2c053cee074b5fb425538aff5f585d4065fa6309
|
C++
|
RMoraffah/hippo-postgresql
|
/src/include/izenelib/include/util/compression/ordered/Compressor.h
|
UTF-8
| 5,943 | 3.203125 | 3 |
[
"Apache-2.0",
"PostgreSQL"
] |
permissive
|
/**
* @file Compressor.h
* @brief The header file of Compressor.
* @author Peisheng Wang
* @date 2008-10-22
*
* This file defines class Compressor.
*
* Change from jiazeng's work:
* ============================
* 1. When compressing a file, it stores bitPattern instead of alphabet tree in compressing.
* 2. We use greedy algorithm to find the index for makeing left sub tree and right sub tree.
* And its complexity is O(n).
* 3. After experiment, compressing is much faster, while decompressing is almost the same.
* 4. Add interface to set bitPatttern:
* void setBitPattern(const string& compressedFile)
* void setBitPattern(const BitPattern& bp)
* 5. Add showCode() method to display the corresponding compressed bit strings for very keyword of inputFile
* void showCode(const string& inputFile, const string& outputFile);
*
* 6. Make it more scable and extendible.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <iostream>
#include <map>
#include <vector>
#include <bitset>
#include <stack>
#include <queue>
#include <algorithm>
#include <numeric>
#include "CompressorException.h"
#include "BitPattern.h"
#include "PatternGenerator.h"
using namespace std;
/**
* \brief Order preserving compressor header file.
*
* This file defines an order preserving compressor.
*/
namespace izenelib {
namespace compression {
struct CompressedString {
unsigned int bitlength;
string bits;
};
/** \brief Order preserving compressor.
*
* This compressor can be used to compress a text file to compressed form by order preserving compression algorithm.
* And it can also decompress a compressed file generated by itself.
*
*/
class Compressor {
/* compressor to perform linear compression */
public:
/**
* \brief default constructor
*/
Compressor();
/**
* \brief default deconstructor
*/
~Compressor();
/**
* \brief constructor from a plaintext file
*
* @param fileName the file is used to initialize bitPattern.
*
*/
Compressor(const string& fileName) :
pg_(fileName) {
bitPattern_ = pg_.getBitPattern();
}
/**
* \brief constructor from a plaintext file
*
* @param fileName the file is used to initialize bitPattern.
* @param NOFILE it true, it dones't encode '\n'.
*/
Compressor(const string& fileName, bool NOFILE=false) :
pg_(fileName, NOFILE) {
bitPattern_ = pg_.getBitPattern();
}
Compressor(const BitPattern& bp) :
bitPattern_(bp) {
}
/**
* \brief set the BitPattern thourgh given file
*
* @param fileName must be a compressed file or file that contains Bitpatten in the head.
*/
void setBitPattern(const string& compressedFile) {
FILE *fp;
fp = fopen(compressedFile.c_str(), "r");
bitPattern_.fromFile(fp);
}
/**
* \brief set the bitpattern directly,
*
*/
void setBitPattern(const BitPattern& bp) {
bitPattern_ = bp;
}
/**
* \brief get the bitpattern.
*
*/
BitPattern& getBitPattern() {
return bitPattern_;
}
/**
* \brief compress a given string input and save it in output.
*
* @param output also contains actual bits length.
*/
void compressString(const string& input, CompressedString& output);
/**
* \brief compress a given string input and save it in output.
*
*/
void decompressString(const CompressedString& input, string& output);
/**
* \brief compress a given file and save it in the output file.
*
* @param UseDefaultPattern if false, use the bitPattern generated from input file, otherwise use bitPattern already exists.
*
*/
void compressFile(const string& inputFile, const string& outputFile,
bool UseDefaultPattern=0);
/**
* \brief decompress from a file
*
* @param SaveBitPattern if true save BitPattern in file header, otherwise not
* note that, if not save bitpattern, then the corressponding bitPattern must be provied when decompressing.
*
*/
void decompressFile(const string& compressfile, const string& textfile);
/**
* \brief show the bitpattern in text of each line of input file.
*
*/
void showCode(const string& inputFile, const string& outputFile);
/**
* \brief display the info of bitPattern.
*/
void displayPattern() {
bitPattern_.display();
}
/**
* \brief show the bitpattern in text of input string.
*/
void showEncode(const string& input, string& output);
/**
* \brief show the original text of compressed string in bit text.
*/
void showDecode(const string& input, string& output);
/*unsigned int stringToInt1(const string& input) {
char ch;
int h = 0;
int cnt = 0;
ub4 mask = 0x80000000;
size_t sz = input.size();
for (unsigned int k = 0; k < sz; k++) {
ch = input[k];
Pattern bincode = bitPattern_.getPattern(ch);
for (size_t i=0; i<bincode.nbits; i++) {
cnt++;
if (bincode.bits & (mask>>i)) {
h = h*2 + 1;
//output.push_back('1');
} else {
h = h*2;
}
//output.push_back('0');
if( cnt >= 32 )
return h;
}
}
if( cnt <32 )
h <<= (32-cnt);
return h;
}*/
unsigned int stringToInt(const string& input) {
char ch;
int h = 0;
int cnt = 0;
int acc = 1;
ub4 mask = 0x80000000;
size_t sz = input.size();
for (unsigned int k = 0; k < sz; k++) {
ch = input[k];
Pattern bincode = bitPattern_.getPattern(ch);
for (size_t i=0; i<bincode.nbits; i++) {
cnt++;
if (bincode.bits & (mask>>i)) {
h |= acc;
//output.push_back('1');
} else {
//h = h*2;
}
acc <<= 1;
//output.push_back('0');
if(cnt >= 32)
return h;
}
}
return h;
}
private:
//Tree *tree_; // internal storage for tree
BitPattern bitPattern_; // internal storage for compression scheme
//TreeAlgorithm ta_;
PatternGenerator pg_;//used to generate pattern.
};
}
} // namespace
| true |
bca65c9c096d1a27cf66570af5947152e164a9a4
|
C++
|
bluemix/Online-Judge
|
/POJ/2986 A Triangle and a Circle.cpp
|
UTF-8
| 3,604 | 3.0625 | 3 |
[] |
no_license
|
/* 14126892 840502 2986 Accepted 168K 1407MS C++ 2933B 2015-04-24 22:58:43 */
#include<bits\stdc++.h>
#define EPS 1e-9
#define PI acos(-1.0)
using namespace std;
struct Point{
double x, y;
Point(){}
Point(double x, double y) :x(x), y(y){}
Point operator +(const Point &a) const{
return Point(x + a.x, y + a.y);
}
Point operator -(const Point &a) const{
return Point(x - a.x, y - a.y);
}
Point operator *(const double &m) const{
return Point(x * m, y * m);
}
Point operator /(const double &m) const{
return Point(x / m, y / m);
}
double cross(const Point &a, const Point &b){
return (a.x - x)*(b.y - y) - (a.y - y)*(b.x - x);
}
double length() const{
return sqrt(x*x + y*y);
}
double distance(const Point &a) const{
return sqrt((x - a.x)*(x - a.x) + (y - a.y)*(y - a.y));
}
};
Point P[50], circle;
double circleR;
double isZero(double x){
return fabs(x) < EPS ? 0 : x;
}
double segment_cross_circle(Point p, Point q, double r, Point pp[]){
double a = p.distance(q) * p.distance(q);
Point tmp = q - p;
double b = (tmp.x*p.x + tmp.y*p.y) * 2;
double c = p.length() * p.length() - r*r;
double D = b*b - 4 * a*c;
D = isZero(D);
if (D < 0) return 0;
D = sqrt(D);
double x1 = (-b + D) / 2 / a;
double x2 = (-b - D) / 2 / a;
if (x1 > x2) swap(x1, x2);
int ptr = 0;
if (isZero(x1) > 0 && isZero(x1 - 1) < 0)
pp[ptr++] = Point(p.x + (q.x - p.x) * x1, p.y + (q.y - p.y) * x1);
if (isZero(x2 - x1) != 0 && isZero(x2) > 0 && isZero(x2 - 1) < 0)
pp[ptr++] = Point(p.x + (q.x - p.x) * x2, p.y + (q.y - p.y) * x2);
return ptr;
}
double getArea(Point p[], int ptr, double r){
double res = 0;
for (int i = 1; i < ptr; i++){
Point a = p[i - 1], b = p[i];
if (isZero(a.distance(circle) - r) > 0 || isZero(b.distance(circle) - r) > 0){
double angle = atan2(b.y, b.x) - atan2(a.y, a.x);
while (isZero(angle - PI) > 0) angle -= PI * 2;
while (isZero(angle + PI) < 0) angle += PI * 2;
res += angle * r * r;
}
else
res += circle.cross(a, b);
}
return res;
}
double triangle_cross_circle(Point a, Point b, double radius){
Point q[2], pp[5];
int ptr = 0, cnt;
pp[ptr++] = a;
cnt = segment_cross_circle(a, b, radius, q);
for (int i = 0; i < cnt; i++) pp[ptr++] = q[i];
pp[ptr++] = b;
return getArea(pp, ptr, radius);
}
int main(){
while (scanf("%lf%lf%lf%lf%lf%lf%lf%lf%lf", &P[0].x, &P[0].y, &P[1].x, &P[1].y, &P[2].x, &P[2].y, &circle.x, &circle.y, &circleR) == 9){
double ans = 0;
for (int i = 0; i < 3; i++)
P[i] = P[i] - circle;
circle = circle - circle;
for (int i = 0; i < 3; i++)
ans += triangle_cross_circle(P[i], P[(i + 1) % 3], circleR);
printf("%.2lf\n", fabs(ans)*0.5);
}
return 0;
}
/*
A Triangle and a Circle
Time Limit: 5000MS Memory Limit: 131072K
Total Submissions: 2981 Accepted: 673 Special Judge
Description
Given one triangle and one circle in the plane. Your task is to calculate the common area of these two figures.
Input
The input will contain several test cases. Each line of input describes a test case. Each test case consists of nine floating point numbers, x1, y1, x2, y2, x3, y3, x4, y4 and r, where (x1, y1), (x2, y2) and (x3, y3) are the three vertices of the triangle and (x4, y4) is the center of the circle and r is the radius. We guarantee the triangle and the circle are not degenerate.
Output
For each test case you should output one real number, which is the common area of the triangle and the circle, on a separate line. The result should be rounded to two decimal places.
Sample Input
0 20 10 0 -10 0 0 0 10
Sample Output
144.35
Source
POJ Monthly--2006.08.27, Rainer
*/
| true |
cd3015aebba90d2f5708b3e7edcc85f1f9043696
|
C++
|
anveshh/cpp-book
|
/src/Leetcode/830_positions-of-large-groups.cpp
|
UTF-8
| 770 | 3.25 | 3 |
[] |
no_license
|
// https://leetcode.com/problems/positions-of-large-groups/
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
vector<vector<int>> largeGroupPositions(string s)
{
vector<vector<int>> res;
int count = 1, len = s.length();
for (int i = 1; i < len; i++)
{
if (s[i] == s[i - 1])
count += 1;
else
{
if (count >= 3)
res.push_back({i - count, i - 1});
count = 1;
}
}
if (count >= 3)
res.push_back({len - count, len - 1});
return res;
}
};
int main()
{
Solution a;
vector<vector<int>> show = a.largeGroupPositions("aaa");
return 0;
}
| true |
16af9f6e74eeb66427d018eb851ef1bd87628e74
|
C++
|
Ubaid-Manzoor/Interview_Practice
|
/Data Structures Problems/Stack/Medium/check_if_parenthesis_are_balanced_or_not/main.cpp
|
UTF-8
| 1,147 | 3.859375 | 4 |
[] |
no_license
|
#include <iostream>
#include <stack>
using namespace std;
bool check_is_balanced(string arr){
stack<char> stack;
for(int i = 0 ; i < arr.size() ; i++){
if(arr[i] == '{' || arr[i] == '(' || arr[i] == '['){
stack.push(arr[i]);
continue;
}
if(stack.empty())
return false;
char c = arr[i];
const char p = stack.top();
switch (c) {
case '}':
if(p == '{')
stack.pop();
else
return false;
break;
case ')':
if(p == '(')
stack.pop();
else
return false;
break;
case ']':
if(p == '[')
stack.pop();
else
return false;
break;
default:
break;
}
}
return stack.empty();
}
int main()
{
int tc;cin>>tc;
for(int i = 0 ; i < tc; i++){
string arr;cin>>arr;
if(check_is_balanced(arr))
cout<<"balanced"<<endl;
else
cout<<"not balanced"<<endl;
}
}
| true |
2e75bcb8dd24dab48670b36c395b39f45044f956
|
C++
|
Jay-Ppark/Algorithm
|
/1406_에디터_리스트_stl.cpp
|
UTF-8
| 615 | 2.96875 | 3 |
[] |
no_license
|
#include<iostream>
#include<string>
#include<list>
using namespace std;
int main(void){
string s;
cin>>s;
list<char> l;
for(int i=0;i<s.size();i++){
l.push_back(s[i]);
}
auto cursor=l.end();
int order;
cin>>order;
for(int t=0;t<order;t++){
char c;
cin>>c;
if(c=='P'){
char tmp;
cin>>tmp;
l.insert(cursor,tmp);
}
else if(c=='L'){
if(cursor!=l.begin()){
cursor--;
}
}
else if(c=='D'){
if(cursor!=l.end()){
cursor++;
}
}
else if(c=='B'){
if(cursor!=l.begin()){
cursor--;
cursor=l.erase(cursor);
}
}
}
for(auto i:l){
cout<<i;
}
return 0;
}
| true |
f3fd0805d4443173714b79d3675eeec64ae939df
|
C++
|
kdoggdev/cncn_m2
|
/srcs/server_src/game/src/item_manager.h
|
UHC
| 13,049 | 2.53125 | 3 |
[
"Unlicense"
] |
permissive
|
#ifndef __INC_ITEM_MANAGER__
#define __INC_ITEM_MANAGER__
#ifdef M2_USE_POOL
#include "pool.h"
#endif
// special_item_group.txt ϴ Ӽ
// type attr ִ.
// Ӽ ̿ ִ special_item_group.txt Special type ǵ 쿡 UNIQUE ITEM̴.
class CSpecialAttrGroup
{
public:
CSpecialAttrGroup(DWORD vnum)
: m_dwVnum(vnum)
{}
struct CSpecialAttrInfo
{
CSpecialAttrInfo (DWORD _apply_type, DWORD _apply_value)
: apply_type(_apply_type), apply_value(_apply_value)
{}
DWORD apply_type;
DWORD apply_value;
};
DWORD m_dwVnum;
std::string m_stEffectFileName;
std::vector<CSpecialAttrInfo> m_vecAttrs;
};
class CSpecialItemGroup
{
public:
enum EGiveType
{
NONE,
GOLD,
EXP,
MOB,
SLOW,
DRAIN_HP,
POISON,
MOB_GROUP,
};
// QUEST Ÿ Ʈ ũƮ vnum.sig_use ִ ̴.
// , 쿡 ؼ ITEM ü TYPE QUEST Ѵ.
// SPECIAL Ÿ idx, item_vnum, attr_vnum ԷѴ. attr_vnum CSpecialAttrGroup Vnum̴.
// 쿡 ִ .
enum ESIGType { NORMAL, PCT, QUEST, SPECIAL };
struct CSpecialItemInfo
{
DWORD vnum;
int count;
int rare;
CSpecialItemInfo(DWORD _vnum, int _count, int _rare)
: vnum(_vnum), count(_count), rare(_rare)
{}
};
CSpecialItemGroup(DWORD vnum, BYTE type=0)
: m_dwVnum(vnum), m_bType(type)
{}
void AddItem(DWORD vnum, int count, int prob, int rare)
{
if (!prob)
return;
if (!m_vecProbs.empty())
prob += m_vecProbs.back();
m_vecProbs.push_back(prob);
m_vecItems.push_back(CSpecialItemInfo(vnum, count, rare));
}
bool IsEmpty() const
{
return m_vecProbs.empty();
}
// Type Multi, m_bType == PCT ,
// Ȯ ذ ʰ, Ͽ Ѵ.
// ִ.
// by rtsummit
int GetMultiIndex(std::vector <int> &idx_vec) const
{
idx_vec.clear();
if (m_bType == PCT)
{
int count = 0;
if (number(1,100) <= m_vecProbs[0])
{
idx_vec.push_back(0);
count++;
}
for (uint i = 1; i < m_vecProbs.size(); i++)
{
if (number(1,100) <= m_vecProbs[i] - m_vecProbs[i-1])
{
idx_vec.push_back(i);
count++;
}
}
return count;
}
else
{
idx_vec.push_back(GetOneIndex());
return 1;
}
}
int GetOneIndex() const
{
int n = number(1, m_vecProbs.back());
itertype(m_vecProbs) it = lower_bound(m_vecProbs.begin(), m_vecProbs.end(), n);
return std::distance(m_vecProbs.begin(), it);
}
int GetVnum(int idx) const
{
return m_vecItems[idx].vnum;
}
int GetCount(int idx) const
{
return m_vecItems[idx].count;
}
int GetRarePct(int idx) const
{
return m_vecItems[idx].rare;
}
bool Contains(DWORD dwVnum) const
{
for (DWORD i = 0; i < m_vecItems.size(); i++)
{
if (m_vecItems[i].vnum == dwVnum)
return true;
}
return false;
}
// Group Type Special 쿡
// dwVnum ĪǴ AttrVnum returnش.
DWORD GetAttrVnum(DWORD dwVnum) const
{
if (CSpecialItemGroup::SPECIAL != m_bType)
return 0;
for (itertype(m_vecItems) it = m_vecItems.begin(); it != m_vecItems.end(); it++)
{
if (it->vnum == dwVnum)
{
return it->count;
}
}
return 0;
}
// Group Size returnش.
int GetGroupSize() const
{
return m_vecProbs.size();
}
DWORD m_dwVnum;
BYTE m_bType;
std::vector<int> m_vecProbs;
std::vector<CSpecialItemInfo> m_vecItems; // vnum, count
};
class CMobItemGroup
{
public:
struct SMobItemGroupInfo
{
DWORD dwItemVnum;
int iCount;
int iRarePct;
SMobItemGroupInfo(DWORD dwItemVnum, int iCount, int iRarePct)
: dwItemVnum(dwItemVnum),
iCount(iCount),
iRarePct(iRarePct)
{
}
};
CMobItemGroup(DWORD dwMobVnum, int iKillDrop, const std::string& r_stName)
:
m_dwMobVnum(dwMobVnum),
m_iKillDrop(iKillDrop),
m_stName(r_stName)
{
}
int GetKillPerDrop() const
{
return m_iKillDrop;
}
void AddItem(DWORD dwItemVnum, int iCount, int iPartPct, int iRarePct)
{
if (!m_vecProbs.empty())
iPartPct += m_vecProbs.back();
m_vecProbs.push_back(iPartPct);
m_vecItems.push_back(SMobItemGroupInfo(dwItemVnum, iCount, iRarePct));
}
// MOB_DROP_ITEM_BUG_FIX
bool IsEmpty() const
{
return m_vecProbs.empty();
}
int GetOneIndex() const
{
int n = number(1, m_vecProbs.back());
itertype(m_vecProbs) it = lower_bound(m_vecProbs.begin(), m_vecProbs.end(), n);
return std::distance(m_vecProbs.begin(), it);
}
// END_OF_MOB_DROP_ITEM_BUG_FIX
const SMobItemGroupInfo& GetOne() const
{
return m_vecItems[GetOneIndex()];
}
private:
DWORD m_dwMobVnum;
int m_iKillDrop;
std::string m_stName;
std::vector<int> m_vecProbs;
std::vector<SMobItemGroupInfo> m_vecItems;
};
class CDropItemGroup
{
struct SDropItemGroupInfo
{
DWORD dwVnum;
DWORD dwPct;
int iCount;
SDropItemGroupInfo(DWORD dwVnum, DWORD dwPct, int iCount)
: dwVnum(dwVnum), dwPct(dwPct), iCount(iCount)
{}
};
public:
CDropItemGroup(DWORD dwVnum, DWORD dwMobVnum, const std::string& r_stName)
:
m_dwVnum(dwVnum),
m_dwMobVnum(dwMobVnum),
m_stName(r_stName)
{
}
const std::vector<SDropItemGroupInfo> & GetVector()
{
return m_vec_items;
}
void AddItem(DWORD dwItemVnum, DWORD dwPct, int iCount)
{
m_vec_items.push_back(SDropItemGroupInfo(dwItemVnum, dwPct, iCount));
}
private:
DWORD m_dwVnum;
DWORD m_dwMobVnum;
std::string m_stName;
std::vector<SDropItemGroupInfo> m_vec_items;
};
class CLevelItemGroup
{
struct SLevelItemGroupInfo
{
DWORD dwVNum;
DWORD dwPct;
int iCount;
SLevelItemGroupInfo(DWORD dwVnum, DWORD dwPct, int iCount)
: dwVNum(dwVnum), dwPct(dwPct), iCount(iCount)
{ }
};
private :
DWORD m_dwLevelLimit;
std::string m_stName;
std::vector<SLevelItemGroupInfo> m_vec_items;
public :
CLevelItemGroup(DWORD dwLevelLimit)
: m_dwLevelLimit(dwLevelLimit)
{}
DWORD GetLevelLimit() { return m_dwLevelLimit; }
void AddItem(DWORD dwItemVnum, DWORD dwPct, int iCount)
{
m_vec_items.push_back(SLevelItemGroupInfo(dwItemVnum, dwPct, iCount));
}
const std::vector<SLevelItemGroupInfo> & GetVector()
{
return m_vec_items;
}
};
class CBuyerThiefGlovesItemGroup
{
struct SThiefGroupInfo
{
DWORD dwVnum;
DWORD dwPct;
int iCount;
SThiefGroupInfo(DWORD dwVnum, DWORD dwPct, int iCount)
: dwVnum(dwVnum), dwPct(dwPct), iCount(iCount)
{}
};
public:
CBuyerThiefGlovesItemGroup(DWORD dwVnum, DWORD dwMobVnum, const std::string& r_stName)
:
m_dwVnum(dwVnum),
m_dwMobVnum(dwMobVnum),
m_stName(r_stName)
{
}
const std::vector<SThiefGroupInfo> & GetVector()
{
return m_vec_items;
}
void AddItem(DWORD dwItemVnum, DWORD dwPct, int iCount)
{
m_vec_items.push_back(SThiefGroupInfo(dwItemVnum, dwPct, iCount));
}
private:
DWORD m_dwVnum;
DWORD m_dwMobVnum;
std::string m_stName;
std::vector<SThiefGroupInfo> m_vec_items;
};
class ITEM;
class ITEM_MANAGER : public singleton<ITEM_MANAGER>
{
public:
ITEM_MANAGER();
virtual ~ITEM_MANAGER();
bool Initialize(TItemTable * table, int size);
void Destroy();
void Update(); // θ.
void GracefulShutdown();
DWORD GetNewID();
bool SetMaxItemID(TItemIDRangeTable range); // ִ ̵
bool SetMaxSpareItemID(TItemIDRangeTable range);
// DelayedSave: ƾ ؾ ϸ
// ʹ Ƿ " Ѵ" ǥø صΰ
// (: 1 frame) Ŀ Ų.
void DelayedSave(LPITEM item);
void FlushDelayedSave(LPITEM item); // Delayed Ʈ ִٸ Ѵ. ó .
void SaveSingleItem(LPITEM item);
LPITEM CreateItem(DWORD vnum, DWORD count = 1, DWORD dwID = 0, bool bTryMagic = false, int iRarePct = -1, bool bSkipSave = false);
#ifndef DEBUG_ALLOC
void DestroyItem(LPITEM item);
#else
void DestroyItem(LPITEM item, const char* file, size_t line);
#endif
void RemoveItem(LPITEM item, const char * c_pszReason=NULL); // ڷ
LPITEM Find(DWORD id);
LPITEM FindByVID(DWORD vid);
TItemTable * GetTable(DWORD vnum);
bool GetVnum(const char * c_pszName, DWORD & r_dwVnum);
bool GetVnumByOriginalName(const char * c_pszName, DWORD & r_dwVnum);
bool GetDropPct(LPCHARACTER pkChr, LPCHARACTER pkKiller, OUT int& iDeltaPercent, OUT int& iRandRange);
bool CreateDropItem(LPCHARACTER pkChr, LPCHARACTER pkKiller, std::vector<LPITEM> & vec_item);
bool ReadCommonDropItemFile(const char * c_pszFileName);
bool ReadEtcDropItemFile(const char * c_pszFileName);
bool ReadDropItemGroup(const char * c_pszFileName);
bool ReadMonsterDropItemGroup(const char * c_pszFileName);
bool ReadSpecialDropItemFile(const char * c_pszFileName);
// convert name -> vnum special_item_group.txt
bool ConvSpecialDropItemFile();
// convert name -> vnum special_item_group.txt
DWORD GetRefineFromVnum(DWORD dwVnum);
static void CopyAllAttrTo(LPITEM pkOldItem, LPITEM pkNewItem); // pkNewItem Ӽ ϴ Լ.
const CSpecialItemGroup* GetSpecialItemGroup(DWORD dwVnum);
const CSpecialAttrGroup* GetSpecialAttrGroup(DWORD dwVnum);
const std::vector<TItemTable> & GetTable() { return m_vec_prototype; }
// CHECK_UNIQUE_GROUP
int GetSpecialGroupFromItem(DWORD dwVnum) const { itertype(m_ItemToSpecialGroup) it = m_ItemToSpecialGroup.find(dwVnum); return (it == m_ItemToSpecialGroup.end()) ? 0 : it->second; }
// END_OF_CHECK_UNIQUE_GROUP
protected:
int RealNumber(DWORD vnum);
void CreateQuestDropItem(LPCHARACTER pkChr, LPCHARACTER pkKiller, std::vector<LPITEM> & vec_item, int iDeltaPercent, int iRandRange);
protected:
typedef std::map<DWORD, LPITEM> ITEM_VID_MAP;
std::vector<TItemTable> m_vec_prototype;
std::vector<TItemTable*> m_vec_item_vnum_range_info;
std::map<DWORD, DWORD> m_map_ItemRefineFrom;
int m_iTopOfTable;
ITEM_VID_MAP m_VIDMap; ///< m_dwVIDCount Ѵ.
DWORD m_dwVIDCount; ///< ̳༮ VID ƴ϶ ׳ μ ũ ȣ.
DWORD m_dwCurrentID;
TItemIDRangeTable m_ItemIDRange;
TItemIDRangeTable m_ItemIDSpareRange;
std::unordered_set<LPITEM> m_set_pkItemForDelayedSave;
std::map<DWORD, LPITEM> m_map_pkItemByID;
std::map<DWORD, DWORD> m_map_dwEtcItemDropProb;
std::map<DWORD, CDropItemGroup*> m_map_pkDropItemGroup;
std::map<DWORD, CSpecialItemGroup*> m_map_pkSpecialItemGroup;
std::map<DWORD, CSpecialItemGroup*> m_map_pkQuestItemGroup;
std::map<DWORD, CSpecialAttrGroup*> m_map_pkSpecialAttrGroup;
std::map<DWORD, CMobItemGroup*> m_map_pkMobItemGroup;
std::map<DWORD, CLevelItemGroup*> m_map_pkLevelItemGroup;
std::map<DWORD, CBuyerThiefGlovesItemGroup*> m_map_pkGloveItemGroup;
// CHECK_UNIQUE_GROUP
std::map<DWORD, int> m_ItemToSpecialGroup;
// END_OF_CHECK_UNIQUE_GROUP
private:
// Ͽ ij ۰ , ȯ ij ٰ Ͽ,
// ۿ ȯ ÷ ο ۵ ,
// ο 뿪 ҴϿ.
// ο ۵ ۰ ȿ ϴµ,
// , Ŭ, vnum Ǿ־
// ο vnum ˴ ھƾϴ Ÿ Ȳ ´Ҵ.
// vnum ̸, ư vnum ٲ㼭 ϰ,
// vnum ٲֵ Ѵ.
// ̸ vnum ο vnum ִ .
typedef std::map <DWORD, DWORD> TMapDW2DW;
TMapDW2DW m_map_new_to_ori;
public:
DWORD GetMaskVnum(DWORD dwVnum);
std::map<DWORD, TItemTable> m_map_vid;
std::map<DWORD, TItemTable>& GetVIDMap() { return m_map_vid; }
std::vector<TItemTable>& GetVecProto() { return m_vec_prototype; }
const static int MAX_NORM_ATTR_NUM = 5;
const static int MAX_RARE_ATTR_NUM = 2;
bool ReadItemVnumMaskTable(const char * c_pszFileName);
private:
#ifdef M2_USE_POOL
ObjectPool<CItem> pool_;
#endif
};
#ifndef DEBUG_ALLOC
#define M2_DESTROY_ITEM(ptr) ITEM_MANAGER::instance().DestroyItem(ptr)
#else
#define M2_DESTROY_ITEM(ptr) ITEM_MANAGER::instance().DestroyItem(ptr, __FILE__, __LINE__)
#endif
#endif
| true |
c34133040d2a5a581ff45f6b116ebcddd31aa2c2
|
C++
|
cpe102/practica-exam-rehearsal-theeramet0793
|
/rehearsal_1.cpp
|
UTF-8
| 299 | 2.90625 | 3 |
[] |
no_license
|
#include<iostream>
#include<string>
using namespace std;
int main(){
string name;
float grade;
cout<<"What is your name?: ";
cin>>name;
cout<<"What is your GPA?: ";
cin>>grade;
if(grade>=3.5){
cout<<name<<" InW Jrim Jrim!!!";
}
else
{
cout<<"Try harder, "<<name<<"!!!";
}
return 0;
}
| true |
957330b1c05bf8057848579bc81a3b479c277d14
|
C++
|
Kannupriyasingh/CPP-files
|
/twoDishes.cpp
|
UTF-8
| 302 | 2.859375 | 3 |
[] |
no_license
|
/**
* Problem Code: TWODISH
*/
#include <iostream>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
int n, a, b, c;
cin >> n >> a >> b >> c;
if ((n > b) || n > (a + c))
cout << "NO\n";
else
cout << "YES\n";
}
return 0;
}
| true |
09bd1e0b6e5095767603fbfc77d4da4997e58b74
|
C++
|
liangdahanay/al
|
/lowestCommonAncestor.cpp
|
UTF-8
| 4,389 | 3.359375 | 3 |
[] |
no_license
|
/*
* lowestCommonAncestor.cpp
*
* Created on: Feb 8, 2015
* Author: liang
*/
#include "lowestCommonAncestor.h"
#include <iostream>
#include <time.h>
#include "tree.h"
int count(Node* root, Node* p, Node* q){
if(root==nullptr) return 0;
int match = count(root->left, p, q) + count(root->right, p, q);
if(root==p ||root==q){
match++;
}
return match;
}
Node* LCAUpDownHelper(Node* root, Node* p, Node* q){
if(p==nullptr||q==nullptr||root==nullptr) return nullptr;
if(root==q||root==p) return root;
int matchLeft = count(root->left, p, q);
if(matchLeft==1){
return root;
}else if(matchLeft==2){
return LCAUpDown(root->left, p, q);
}else{
return LCAUpDown(root->right, p, q);
}
}
Node* LCAUpDown(Node* root, Node* p, Node* q){
if(count(root, p, q)!=2) return nullptr;
return LCAUpDownHelper( root, p, q);
}
Node* LCADownUpHelper(Node* root, Node* p, Node* q){
if(p==nullptr||q==nullptr||root==nullptr) return nullptr;
if(root==q||root==p) return root;
Node* left = LCADownUpHelper(root->left, p, q);
Node* right = LCADownUpHelper(root->right, p, q);
if(left!=nullptr && right!=nullptr) return root;
return left==nullptr?right:left;
}
Node* LCADownUp(Node* root, Node* p, Node* q){
if(count(root, p, q)!=2) return nullptr;
return LCADownUpHelper( root, p, q);
}
Node* LCABSTHelper(Node* root, Node* p, Node* q){
if(p==nullptr||q==nullptr||root==nullptr) return nullptr;
if(root==q||root==p) return root;
if(root->val<min(p->val, q->val)){
return LCABSTHelper(root->right, p, q);
}else if(root->val>max(p->val, q->val)){
return LCABSTHelper(root->left, p, q);
}else{
return root;
}
}
Node* LCABST(Node* root, Node* p, Node* q){
if(count(root, p, q)!=2) return nullptr;
return LCABSTHelper( root, p, q);
}
void lowestCommonAncestorTest(){
clock_t start;
Node* ancestor;
vector<int> num;
for(int i=0;i<10000;i++){
num.push_back(i);
}
start = clock();
Node* root = constructBalanceTree(num);
Node* node1 = getByValue(root, 101);
Node* node2 = getByValue(root, 1000);
std::cout << "Init balanced tree finished " << std::endl;
Node* rootu = constructUnbalanceTree(num);
Node* node1u = getByValue(rootu, 101);
Node* node2u = getByValue(rootu, 1000);
std::cout << "Init Unbalanced tree finished " << std::endl;
std::cout << "Init Time: " << clock()-start << std::endl;
std::cout << "Balanced" << std::endl << std::endl;
std::cout << "Up to Down" << std::endl;
start = clock();
ancestor = LCAUpDown(root, node1, node2);
std::cout << "Time: " << clock()-start << std::endl;
if(ancestor==nullptr){
std::cout << "no ancestor" << std::endl;
}else{
std::cout << "Ancestor: "<< ancestor->val << std::endl;
}
std::cout << std::endl;
std::cout << "Down to Up" << std::endl;
start = clock();
ancestor = LCADownUpHelper(root, node1, node2);
std::cout << "Time: " << clock()-start << std::endl;
if(ancestor==nullptr){
std::cout << "no ancestor" << std::endl;
}else{
std::cout << "Ancestor: " << ancestor->val << std::endl;
}
std::cout << std::endl;
std::cout << "BST" << std::endl;
start = clock();
ancestor = LCABST(root, node1, node2);
std::cout << "Time: " << clock()-start << std::endl;
if(ancestor==nullptr){
std::cout << "no ancestor" << std::endl;
}else{
std::cout << "Ancestor: " << ancestor->val << std::endl;
}
std::cout << std::endl;
std::cout << "Unbalanced" << std::endl << std::endl;
std::cout << "Up to Down" << std::endl;
start = clock();
ancestor = LCAUpDown(rootu, node1u, node2u);
std::cout << "Time: " << clock()-start << std::endl;
if(ancestor==nullptr){
std::cout << "no ancestor" << std::endl;
}else{
std::cout << "Ancestor: "<< ancestor->val << std::endl;
}
std::cout << std::endl;
std::cout << "Down to Up" << std::endl;
start = clock();
ancestor = LCADownUpHelper(rootu, node1u, node2u);
std::cout << "Time: " << clock()-start << std::endl;
if(ancestor==nullptr){
std::cout << "no ancestor" << std::endl;
}else{
std::cout << "Ancestor: " << ancestor->val << std::endl;
}
std::cout << std::endl;
std::cout << "BST" << std::endl;
start = clock();
ancestor = LCABST(rootu, node1u, node2u);
std::cout << "Time: " << clock()-start << std::endl;
if(ancestor==nullptr){
std::cout << "no ancestor" << std::endl;
}else{
std::cout << "Ancestor: " << ancestor->val << std::endl;
}
std::cout << std::endl;
}
| true |
f69469db43d1550acb49566419b35e4cd843ae05
|
C++
|
cocoa-xu/evision
|
/c_src/ArgInfo.hpp
|
UTF-8
| 445 | 2.6875 | 3 |
[
"Apache-2.0"
] |
permissive
|
#ifndef ARGINFO_HPP
#define ARGINFO_HPP
class ArgInfo
{
public:
const char* name;
bool outputarg;
bool has_default;
// more fields may be added if necessary
ArgInfo(const char* name_, bool outputarg_, bool has_default_ = false) :
name(name_), outputarg(outputarg_), has_default(has_default_) {}
private:
ArgInfo(const ArgInfo&) = delete;
ArgInfo& operator=(const ArgInfo&) = delete;
};
#endif // ARGINFO_HPP
| true |
e211cbef3ca3ef84fdc40396d039bcb3242b5677
|
C++
|
HuangDave/MP3
|
/L5_Application/MP3/UI/View.hpp
|
UTF-8
| 1,015 | 3.015625 | 3 |
[] |
no_license
|
/*
* View.hpp
*
* Created on: Apr 6, 2018
* Author: huang
*/
#ifndef VIEW_HPP_
#define VIEW_HPP_
#include "../gfx.h"
/**
* The View class the base class for displaying views on the LCD Display.
*
* The frame of the view determines the origin of the view as well as the width and height it occupies on the display.
* The view is drawn when the reDraw() functions are called.
*/
class View {
public:
View(Frame frame);
virtual ~View();
void setFrame(Frame frame);
void setOrigin(Point2D origin);
void setSize(Size2D size);
void setBackgroundColor(Color c);
/// Set the view as dirty and completely redraw the view.
virtual void draw();
/// Redraw the view and only update parts of the view that needs updating.
virtual void reDraw();
/// Redraw the view with a different background color.
virtual void reDrawWithBackground(Color *color);
protected:
Frame mFrame;
Color mBackgroundColor;
bool mIsDirty;
};
#endif /* VIEW_HPP_ */
| true |
d11b4a7b0750612c4937a481e806f06cf2ee51a0
|
C++
|
alwaystiys/OpenGL
|
/ogl3.3/src/LightTest.cpp
|
GB18030
| 17,075 | 2.53125 | 3 |
[] |
no_license
|
#include "LightTest.h"
#include "Common/lib_transform.h"
#include <iostream>
using namespace LightTest;
TextureShader::TextureShader(const char *vertexShaderSource, const char *fragmentShaderSource, const char *vsFilePath, const char *fsFilePath) {
this->vertexShaderSource = vertexShaderSource;
this->fragmentShaderSource = fragmentShaderSource;
this->vsFilePath = vsFilePath;
this->fsFilePath = fsFilePath;
}
bool TextureShader::Init() {
if(!ShaderBasic::Init()) {
return false;
}
if(!AddShader(GL_VERTEX_SHADER, vsFilePath, NULL)) {
return false;
}
if(!AddShader(GL_FRAGMENT_SHADER, fsFilePath, NULL)) {
return false;
}
if(!LinkProgram()) {
return false;
}
return true;
}
//**************************************************
FPS2Test::FPS2Test() :
camera(vec3(0.0f, 0.0f, 3.0f)) {
lightingShader = NULL;
lambShader = NULL;
}
FPS2Test::~FPS2Test() {
delete lightingShader;
delete lambShader;
glDeleteVertexArrays(1, &cubeVAO);
glDeleteVertexArrays(1, &lightVAO);
glDeleteBuffers(1, &VBO);
}
bool FPS2Test::Init() {
lightingShader = new TextureShader(NULL, NULL, "../Shader/light_cube_01.vs", "../Shader/light_cube_01.fs");
if(!lightingShader->Init()) {
return false;
}
lambShader = new TextureShader(NULL, NULL, "../Shader/light_lamb_01.vs", "../Shader/light_lamb_01.fs");
if(!lambShader->Init()) {
return false;
}
float vertices[] = {
-0.5f, -0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, -0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, -0.5f,
};
// init cubeVAO
glGenVertexArrays(1, &cubeVAO);
glGenBuffers(1, &VBO);
glBindVertexArray(cubeVAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glBindVertexArray(0);
// inti lightVAO
glGenVertexArrays(1, &lightVAO);
glBindVertexArray(lightVAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
lightingShader->Enable();
lightingShader->setUniform3f("objectColor", 1.0f, 0.5f, 0.31f);
lightingShader->setUniform3f("lightColor", 1.0f, 1.0f, 1.0f);
return true;
}
void FPS2Test::RenderSceneCB() {
lightingShader->Enable();
Transform model;
lightingShader->setUniformMatrix4fv("model", model.getTransformResult());
Transform view(camera.GetViewMatrix());
lightingShader->setUniformMatrix4fv("view", view.getTransformResult());
Transform projection(libmath::genPerspective(libmath::toRadians(camera.zoom), (float) 800 / 600, 1.0f, 100.0f));
lightingShader->setUniformMatrix4fv("projection", projection.getTransformResult());
glBindVertexArray(cubeVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
lambShader->Enable();
lambShader->setUniformMatrix4fv("view", view.getTransformResult());
lambShader->setUniformMatrix4fv("projection", projection.getTransformResult());
model.translate(1.2f, 1.0f, 2.0f).scale(0.2f, 0.2f, 0.2f);
lambShader->setUniformMatrix4fv("model", model.getTransformResult());
glBindVertexArray(lightVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
}
void FPS2Test::ProcessInput(KEY_PRESS isKeyPress, float delta) {
if(isKeyPress(GLFW_KEY_W)) {
camera.processKeyboard(FORWARD, delta);
}
if(isKeyPress(GLFW_KEY_S)) {
camera.processKeyboard(BACKWARD, delta);
}
if(isKeyPress(GLFW_KEY_A)) {
camera.processKeyboard(LEFT, delta);
}
if(isKeyPress(GLFW_KEY_D)) {
camera.processKeyboard(RIGHT, delta);
}
}
void FPS2Test::PorcessMouseInput(float delta, double xpos, double ypos) {
camera.processMouseMovement(delta, xpos, ypos);
}
void FPS2Test::PorcessScrollInput(float delta, double xoffset, double yoffset) {
camera.processMouseScroll(delta, xoffset, yoffset);
}
//**************************************************
BasicLightTest::BasicLightTest() :
camera(vec3(0.0f, 0.0f, 5.0f)), lightPos(1.2f, 1.0f, 2.0f) {
lightingShader = NULL;
lambShader = NULL;
}
BasicLightTest::~BasicLightTest() {
delete lightingShader;
delete lambShader;
glDeleteVertexArrays(1, &cubeVAO);
glDeleteVertexArrays(1, &lightVAO);
glDeleteBuffers(1, &VBO);
}
bool BasicLightTest::Init() {
lightingShader = new TextureShader(NULL, NULL, "../Shader/light_gouraud_cube_02.vs", "../Shader/light_gouraud_cube_02.fs");
//lightingShader = new TextureShader(NULL, NULL, "../Shader/light_cube_02.vs", "../Shader/light_cube_02.fs");
if(!lightingShader->Init()) {
return false;
}
lambShader = new TextureShader(NULL, NULL, "../Shader/light_lamb_01.vs", "../Shader/light_lamb_01.fs");
if(!lambShader->Init()) {
return false;
}
float vertices[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f
};
// init cubeVAO
glGenVertexArrays(1, &cubeVAO);
glGenBuffers(1, &VBO);
glBindVertexArray(cubeVAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(sizeof(float) * 3));
glEnableVertexAttribArray(1);
glBindVertexArray(0);
// inti lightVAO
glGenVertexArrays(1, &lightVAO);
glBindVertexArray(lightVAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
lightingShader->Enable();
lightingShader->setUniform3f("objectColor", 1.0f, 0.5f, 0.31f);
lightingShader->setUniform3f("lightColor", 1.0f, 1.0f, 1.0f);
return true;
}
void BasicLightTest::RenderSceneCB() {
//lightPos.x = 1.0f + sin(glfwGetTime()) * 2.0f;
//lightPos.y = sin(glfwGetTime() / 2.0f) * 1.0f;
lightingShader->Enable();
Transform model;
lightingShader->setUniformMatrix4fv("model", model.getTransformResult());
Transform view(camera.GetViewMatrix());
lightingShader->setUniformMatrix4fv("view", view.getTransformResult());
Transform projection(libmath::genPerspective(libmath::toRadians(camera.zoom), (float) 800 / 600, 1.0f, 100.0f));
lightingShader->setUniformMatrix4fv("projection", projection.getTransformResult());
lightingShader->setUniform3f("viewPos", camera.position.x, camera.position.y, camera.position.z);
lightingShader->setUniformVec3f("lightPos", lightPos);
glBindVertexArray(cubeVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
lambShader->Enable();
lambShader->setUniformMatrix4fv("view", view.getTransformResult());
lambShader->setUniformMatrix4fv("projection", projection.getTransformResult());
model.translate(lightPos.x, lightPos.y, lightPos.z).scale(0.2f, 0.2f, 0.2f);
lambShader->setUniformMatrix4fv("model", model.getTransformResult());
glBindVertexArray(lightVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
}
void BasicLightTest::ProcessInput(KEY_PRESS isKeyPress, float delta) {
if(isKeyPress(GLFW_KEY_W)) {
camera.processKeyboard(FORWARD, delta);
}
if(isKeyPress(GLFW_KEY_S)) {
camera.processKeyboard(BACKWARD, delta);
}
if(isKeyPress(GLFW_KEY_A)) {
camera.processKeyboard(LEFT, delta);
}
if(isKeyPress(GLFW_KEY_D)) {
camera.processKeyboard(RIGHT, delta);
}
}
void BasicLightTest::PorcessMouseInput(float delta, double xpos, double ypos) {
camera.processMouseMovement(delta, xpos, ypos);
}
void BasicLightTest::PorcessScrollInput(float delta, double xoffset, double yoffset) {
camera.processMouseScroll(delta, xoffset, yoffset);
}
//**************************************************
MaterialTest::MaterialTest() :
camera(vec3(0.0f, 0.0f, 5.0f)), lightPos(1.2f, 1.0f, 2.0f) {
lightingShader = NULL;
lambShader = NULL;
}
MaterialTest::~MaterialTest() {
delete lightingShader;
delete lambShader;
glDeleteVertexArrays(1, &cubeVAO);
glDeleteVertexArrays(1, &lightVAO);
glDeleteBuffers(1, &VBO);
}
bool MaterialTest::Init() {
lightingShader = new TextureShader(NULL, NULL, "../Shader/light_material_cube.vs", "../Shader/light_material_cube.fs");
if(!lightingShader->Init()) {
return false;
}
lambShader = new TextureShader(NULL, NULL, "../Shader/light_lamb_01.vs", "../Shader/light_lamb_01.fs");
if(!lambShader->Init()) {
return false;
}
float vertices[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f
};
// init cubeVAO
glGenVertexArrays(1, &cubeVAO);
glGenBuffers(1, &VBO);
glBindVertexArray(cubeVAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(sizeof(float) * 3));
glEnableVertexAttribArray(1);
glBindVertexArray(0);
// inti lightVAO
glGenVertexArrays(1, &lightVAO);
glBindVertexArray(lightVAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
lightingShader->Enable();
lightingShader->setUniform3f("objectColor", 1.0f, 0.5f, 0.31f);
lightingShader->setUniform3f("lightColor", 1.0f, 1.0f, 1.0f);
lightingShader->setUniform3f("material.ambient", 1.0f, 0.5f, 0.31f);
lightingShader->setUniform3f("material.diffuse", 1.0f, 0.5f, 0.31f);
lightingShader->setUniform3f("material.specular", 0.5f, 0.5f, 0.5f);
lightingShader->setUniform1f("material.shininess", 32.0f);
lightingShader->setUniform3f("light.ambient", 0.2f, 0.2f, 0.2f);
lightingShader->setUniform3f("light.diffuse", 0.5f, 0.5f, 0.5f); // յһЩԴ䳡
lightingShader->setUniform3f("light.specular", 1.0f, 1.0f, 1.0f);
return true;
}
void MaterialTest::RenderSceneCB() {
//lightPos.x = 1.0f + sin(glfwGetTime()) * 2.0f;
//lightPos.y = sin(glfwGetTime() / 2.0f) * 1.0f;
lightingShader->Enable();
Transform model;
lightingShader->setUniformMatrix4fv("model", model.getTransformResult());
Transform view(camera.GetViewMatrix());
lightingShader->setUniformMatrix4fv("view", view.getTransformResult());
Transform projection(libmath::genPerspective(libmath::toRadians(camera.zoom), (float) 800 / 600, 1.0f, 100.0f));
lightingShader->setUniformMatrix4fv("projection", projection.getTransformResult());
lightingShader->setUniform3f("viewPos", camera.position.x, camera.position.y, camera.position.z);
lightingShader->setUniformVec3f("lightPos", lightPos);
vec3 lightColor;
lightColor.x = sin(glfwGetTime() * 2.0f);
lightColor.y = sin(glfwGetTime() * 0.7f);
lightColor.z = sin(glfwGetTime() * 1.3f);
vec3 diffuseColor = lightColor * vec3(0.5f); // Ӱ
vec3 ambientColor = diffuseColor * vec3(0.2f); // ܵ͵Ӱ
lightingShader->setUniformVec3f("light.ambient", ambientColor);
lightingShader->setUniformVec3f("light.diffuse", diffuseColor); // յһЩԴ䳡
glBindVertexArray(cubeVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
lambShader->Enable();
lambShader->setUniformMatrix4fv("view", view.getTransformResult());
lambShader->setUniformMatrix4fv("projection", projection.getTransformResult());
model.translate(lightPos.x, lightPos.y, lightPos.z).scale(0.2f, 0.2f, 0.2f);
lambShader->setUniformMatrix4fv("model", model.getTransformResult());
glBindVertexArray(lightVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
}
void MaterialTest::ProcessInput(KEY_PRESS isKeyPress, float delta) {
if(isKeyPress(GLFW_KEY_W)) {
camera.processKeyboard(FORWARD, delta);
}
if(isKeyPress(GLFW_KEY_S)) {
camera.processKeyboard(BACKWARD, delta);
}
if(isKeyPress(GLFW_KEY_A)) {
camera.processKeyboard(LEFT, delta);
}
if(isKeyPress(GLFW_KEY_D)) {
camera.processKeyboard(RIGHT, delta);
}
}
void MaterialTest::PorcessMouseInput(float delta, double xpos, double ypos) {
camera.processMouseMovement(delta, xpos, ypos);
}
void MaterialTest::PorcessScrollInput(float delta, double xoffset, double yoffset) {
camera.processMouseScroll(delta, xoffset, yoffset);
}
| true |
6afbd5be0796884aecbebd2f225a5746feb11ff0
|
C++
|
zpoint/Reading-Exercises-Notes
|
/C++ Primer/11_Associative_Containers/11_10.cpp
|
UTF-8
| 908 | 3.421875 | 3 |
[] |
no_license
|
#include <map>
#include <vector>
#include <list>
#include <iostream>
int main()
{
std::vector<int> ivec{1, 2};
std::cout << (ivec.end() < ivec.begin()) << std::endl;
std::list<int> lst{1, 2};
// std::cout << (lst.end() < lst.begin()) << std::endl;
std::map<std::vector<int>::iterator, int> vec_iter_map;
std::map<std::list<int>::iterator, int> lst_iter_map;
vec_iter_map[ivec.begin()] = 5;
lst_iter_map[lst.begin()] = 6; // error, iterator of list has not < experssion, need to define a predicate manually
/*
std::cout << "vec: " << vec_iter_map[ivec.begin()];
std::cout << "lst: " << lst_iter_map[lst.begin()];
ivec.push_back(2);
ivec.push_back(3);
lst.push_back(2);
lst.push_back(3);
std::cout << "After push back: \n";
std::cout << "vec: " << lst_iter_map[lst.begin()] << std::endl;
std::cout << "lst: " << vec_iter_map[ivec.begin()] << std::endl;
*/
return 0;
}
| true |
21998a32f4c81e96bfd6dc833743d2fb0788fca7
|
C++
|
mxmz/json-cpp-lib
|
/jsonlib/src/mxmz/json/v4/json_writer.hxx
|
UTF-8
| 7,281 | 2.546875 | 3 |
[] |
no_license
|
#ifndef json_writer_hxx_374827627653726346239234029302039029309489884842
#define json_writer_hxx_374827627653726346239234029302039029309489884842
#include <string>
namespace mxmz {
namespace json {
namespace v4 {
struct json_element_writer_default_features {
typedef ::std::string string_t;
typedef char char_t;
static const char array_beg = '[';
static const char array_end = ']';
static const char map_beg = '{';
static const char map_end = '}';
static const char element_sep = ',';
static const char key_sep = ':';
static const char space = ' ';
static const char* E_bs() {
return "\\\\";
}
static const char* E_lf() {
return "\\n";
}
static const char* E_tab() {
return "\\t";
}
static const char* E_cr() {
return "\\r";
}
static const char* E_ff() {
return "\\f";
}
static const char quotes = '"';
static const char* E_quotes() {
return "\\\"";
}
};
template< class OStreamT, class WriterFeatures = json_element_writer_default_features >
struct json_token_writer_tmpl {
typedef WriterFeatures feat_t;
typedef typename feat_t::string_t string_t;
private:
OStreamT* out;
public:
json_token_writer_tmpl() : out(0) {
}
void bind( OStreamT* o ) {
out = o;
}
void write_map_begin() {
*out << feat_t::map_beg;
}
void write_map_end() {
*out << feat_t::map_end ;
}
void write_array_begin() {
*out << feat_t::array_beg;
}
void write_array_end() {
*out << feat_t::array_end;
}
void write_element_separator() {
*out << feat_t::element_sep;
}
void write_key_separator() {
*out << feat_t::key_sep;
}
void write_integer(long long int v) {
*out << v;
}
void write_double(long double v) {
*out << v;
}
void write_bool( bool v ) {
*out << (v ? "true": "false") ;
}
void write_null() {
*out << "null" ;
}
void write_qstring( const string_t& s ) {
*out<< feat_t::quotes;
for ( typename string_t::const_iterator i = s.begin(); i != s.end(); ++i ) {
switch (*i) {
case '\\':
*out << feat_t::E_bs();
break;
case '\n':
*out << feat_t::E_lf();
break;
case '\t':
*out << feat_t::E_tab();
break;
case '\r':
*out << feat_t::E_cr();
break;
case '\f':
*out << feat_t::E_ff();
break;
/*
case '\"': *out << feat_t::E_dq(); break;
case '\'': *out << feat_t::E_sq(); break;
*/
case feat_t::quotes:
*out << feat_t::E_quotes();
break;
default: {
if ( (unsigned char)*i < 32 ) {
char ucode[7];
sprintf(ucode, "\\u%.04d",*i);
*out << ucode;
continue;
} else
*out << *i;
}
}
}
*out<< feat_t::quotes;
}
void write_key_pair( const string_t& k, const string_t& v, bool quoted ) {
write_qstring(k);
*out << feat_t::key_sep;
if ( quoted ) {
write_qstring(v);
} else {
*out << v;
}
}
};
template< class OStreamT, class JsonValueHandleT,
class WriterT = json_token_writer_tmpl<OStreamT> >
struct json_writer_tmpl :public JsonValueHandleT::json_value_const_visitor {
typedef JsonValueHandleT json_value_handle;
typedef WriterT writer_t;
typedef typename json_value_handle::json_string json_string;
typedef typename json_value_handle::json_number json_number;
typedef typename json_value_handle::json_integer json_integer;
typedef typename json_value_handle::json_bool json_bool;
typedef typename json_value_handle::json_object json_object;
typedef typename json_value_handle::json_array json_array;
typedef typename json_value_handle::string_t string_t;
typedef typename json_value_handle::number_t number_t;
typedef typename json_value_handle::integer_t integer_t;
typedef typename writer_t::feat_t feat_t;
WriterT writer;
void visit( const json_object& jm ) {
const typename json_object::value_type& m = jm.get();
writer.write_map_begin();
typename json_object::value_type::const_iterator i = m.begin();
if ( i != m.end() ) {
writer.write_qstring(i->first);
writer.write_key_separator();
deref_ptr(i->second).accept(*this);
++i;
while ( i != m.end() ) {
writer.write_element_separator();
writer.write_qstring(i->first);
writer.write_key_separator();
deref_ptr(i->second).accept(*this);
++i;
}
}
writer.write_map_end();
}
void visit( const json_array& ja ) {
const typename json_array::value_type& a = ja.get();
writer.write_array_begin();
typename json_array::value_type::const_iterator i= a.begin();
if ( i != a.end() ) {
( deref_ptr( *i ) ).accept(*this);
++i;
while ( i != a.end()) {
writer.write_element_separator();
( deref_ptr( *i ) ).accept(*this);
++i;
}
}
writer.write_array_end();
}
void write( const json_value_handle& o, OStreamT&out ) {
writer.bind(&out);
o.accept(*this);
}
void visit() {
writer.write_null();
}
void visit( const json_string& v ) {
writer.write_qstring( v.get() );
}
void visit( const json_number& v ) {
writer.write_double( v.get() );
}
void visit( const json_integer& v ) {
writer.write_integer( v.get() );
}
void visit( const json_bool& v ) {
writer.write_bool(v.get());
}
};
}
}
}
namespace mxmz {
namespace json {
namespace v4 {
namespace util {
class string_writer {
::std::string buffer;
public:
::std::string& str() {
return buffer;
}
void reset() {
buffer.resize(0);
}
string_writer& operator<<( char c ) {
buffer += c;
return *this;
}
string_writer& operator<<( const char* p ) {
buffer += p;
return *this;
}
string_writer& operator<<( const ::std::string& s ) {
buffer += s;
return *this;
}
string_writer& operator<<( double v ) {
char buf[30];
sprintf( buf, "%g", v );
buffer += buf;
return *this;
}
string_writer& operator<<( long double v ) {
char buf[30];
sprintf( buf, "%llg", v );
buffer += buf;
return *this;
}
string_writer& operator<<( long long int v ) {
char buf[30];
sprintf( buf, "%lld", v );
buffer += buf;
return *this;
}
};
}
}
}
}
#endif
| true |
dd24f6851130e050f449b84bd1d687f7c7de600b
|
C++
|
aeremin/Codeforces
|
/alexey/Solvers/6xx/604/Solver604A.cpp
|
UTF-8
| 1,156 | 2.953125 | 3 |
[] |
no_license
|
#include <Solvers/pch.h>
#include "iter/range.h"
#include "algo/io/readvector.h"
using namespace std;
// Solution for Codeforces problem http://codeforces.com/contest/604/problem/A
class Solver604A
{
public:
void run();
};
void Solver604A::run()
{
auto times = readVector<int>(5);
auto tries = readVector<int>(5);
auto successfulHacks = read<int>();
auto unsuccessfulHacks = read<int>();
int res = 100 * successfulHacks - 50 * unsuccessfulHacks;
for (int i : range(5))
{
auto problemCostBy250 = (i + 1) * 2;
res += max(75 * problemCostBy250, (250 - times[i]) * problemCostBy250 - 50 * tries[i]);
}
print(res);
}
class Solver604ATest : public ProblemTest {};
TEST_F(Solver604ATest, Example1)
{
string input = R"(20 40 60 80 100
0 1 2 3 4
1 0
)";
string output = R"(4900
)";
setInput(input);
Solver604A().run();
EXPECT_EQ_FUZZY(getOutput(), output);
}
TEST_F(Solver604ATest, Example2)
{
string input = R"(119 119 119 119 119
0 0 0 0 0
10 0
)";
string output = R"(4930
)";
setInput(input);
Solver604A().run();
EXPECT_EQ_FUZZY(getOutput(), output);
}
| true |
eb9538ed4affd67b78258db003e1f3d2a1626234
|
C++
|
ThatCoolCoder/sfml-tictactoe
|
/src/miniengine/utils.cpp
|
UTF-8
| 273 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
#include "utils.hpp"
namespace miniengine::utils
{
void centerAlignText(sf::Text& text)
{
sf::FloatRect textRect = text.getLocalBounds();
text.setOrigin(textRect.left + textRect.width/2.0f,
textRect.top + textRect.height/2.0f);
}
}
| true |
987de29af763df99c9869171dc802473c86c373a
|
C++
|
Karan-MUJ/SPOJ_300
|
/The_Cats_and_the_Mouse_282.cpp
|
UTF-8
| 3,187 | 3.25 | 3 |
[] |
no_license
|
/*#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int mdist[100][100];
int cdist[100][100];
int n, m;
struct cord
{
int x;
int y;
};
void cbfs(cord cat)
{
bool visited[n][m];
int i, j;
for (i = 0; i < n; ++i)
{
for (j = 0; j < n; ++j)
{
visited[i][j] = false;
}
}
cat.x -= 1;
cat.y -= 1;
queue< cord > q;
q.push(cat);
cdist[cat.x][cat.y] = 0;
while (!q.empty())
{
cord p = q.front();
q.pop();
if (!visited[p.x][p.y])
{
visited[p.x][p.y] = true;
if (p.x + 1 < n && cdist[p.x + 1][p.y] > cdist[p.x][p.y] + 1)
{
q.push((cord) { p.x + 1, p.y });
cdist[p.x + 1][p.y] = cdist[p.x][p.y] + 1;
}
if (p.x - 1 >= 0 && cdist[p.x - 1][p.y] > cdist[p.x][p.y] + 1)
{
q.push((cord) { p.x - 1, p.y });
cdist[p.x - 1][p.y] = cdist[p.x][p.y] + 1;
}
if (p.y + 1 < m && cdist[p.x][p.y + 1] > cdist[p.x][p.y] + 1)
{
q.push((cord) { p.x, p.y + 1 });
cdist[p.x][p.y + 1] = cdist[p.x][p.y] + 1;
}
if (p.y - 1 >= 0 && cdist[p.x][p.y - 1] > cdist[p.x][p.y] + 1)
{
q.push((cord) { p.x, p.y - 1 });
cdist[p.x][p.y - 1] = cdist[p.x][p.y] + 1;
}
}
}
}
void mbfs(cord mouse)
{
bool visited[n][m];
int i, j;
for (i = 0; i < n; ++i)
{
for (j = 0; j < n; ++j)
{
visited[i][j] = false;
}
}
queue< cord > q;
mouse.x -= 1;
mouse.y -= 1;
q.push(mouse);
mdist[mouse.x][mouse.y] = 0;
while (!q.empty())
{
cord p = q.front();
q.pop();
if (!visited[p.x][p.y])
{
visited[p.x][p.y] = true;
if (p.x + 1 < n && mdist[p.x + 1][p.y] > mdist[p.x][p.y] + 1)
{
q.push((cord) { p.x + 1, p.y });
mdist[p.x + 1][p.y] = mdist[p.x][p.y] + 1;
}
if (p.x - 1 >= 0 && mdist[p.x - 1][p.y] > mdist[p.x][p.y] + 1)
{
q.push((cord) { p.x - 1, p.y });
mdist[p.x - 1][p.y] = mdist[p.x][p.y] + 1;
}
if (p.y + 1 < m && mdist[p.x][p.y + 1] > mdist[p.x][p.y] + 1)
{
q.push((cord) { p.x, p.y + 1 });
mdist[p.x][p.y + 1] = mdist[p.x][p.y] + 1;
}
if (p.y - 1 >= 0 && mdist[p.x][p.y - 1] > mdist[p.x][p.y] + 1)
{
q.push((cord) { p.x, p.y - 1 });
mdist[p.x][p.y - 1] = mdist[p.x][p.y] + 1;
}
}
}
}
int main()
{
cin >> n >> m;
int t;
cin >> t;
int i, j;
cord cat1, cat2, mouse;
bool found;
while (t > 0)
{
found = false;
for (i = 0; i < n; ++i)
{
for (j = 0; j < m; ++j)
{
mdist[i][j] = cdist[i][j] = 1000000;
}
}
cin >> mouse.x >> mouse.y >> cat1.x >> cat1.y >> cat2.x >> cat2.y;
cbfs(cat1);
cbfs(cat2);
mbfs(mouse);
if (!found)
{
for (i = 0; i < n; ++i)
{
if (mdist[i][0] < cdist[i][0] || mdist[i][m - 1] < cdist[i][m - 1])
{
cout << "YES" << endl;
found = true;
break;
}
}
}
if (!found)
{
for (j = 0; j < m; ++j)
{
if (mdist[0][j] < cdist[0][j] || mdist[n - 1][j] < cdist[n - 1][j])
{
cout << "YES" << endl;
found = true;
break;
}
}
}
if (!found)
{
cout << "NO" << endl;
}
--t;
}
return 0;
}*/
| true |
33af8d1af7ddad6c2e46614af43a604e04140aef
|
C++
|
mostarr/CSE-111
|
/Lab5/shape.cpp
|
UTF-8
| 6,543 | 2.640625 | 3 |
[] |
no_license
|
// $Id: shape.cpp,v 1.2 2019-02-28 15:24:20-08 - - $
#include <typeinfo>
#include <unordered_map>
#include <GL/freeglut.h>
#include <cmath>
using namespace std;
#include "shape.h"
#include "util.h"
static unordered_map<void *, string> fontname{
{GLUT_BITMAP_8_BY_13, "Fixed-8x13"},
{GLUT_BITMAP_9_BY_15, "Fixed-9x15"},
{GLUT_BITMAP_HELVETICA_10, "Helvetica-10"},
{GLUT_BITMAP_HELVETICA_12, "Helvetica-12"},
{GLUT_BITMAP_HELVETICA_18, "Helvetica-18"},
{GLUT_BITMAP_TIMES_ROMAN_10, "Times-Roman-10"},
{GLUT_BITMAP_TIMES_ROMAN_24, "Times-Roman-24"},
};
ostream &operator<<(ostream &out, const vertex &where)
{
out << "(" << where.xpos << "," << where.ypos << ")";
return out;
}
shape::shape()
{
DEBUGF('c', this);
}
text::text(void *glut_bitmap_font_, const string &textdata_) : glut_bitmap_font(glut_bitmap_font_), textdata(textdata_)
{
DEBUGF('c', this);
}
ellipse::ellipse(GLfloat width, GLfloat height) : dimension({width, height})
{
DEBUGF('c', this);
}
circle::circle(GLfloat diameter) : ellipse(diameter, diameter)
{
DEBUGF('c', this);
}
polygon::polygon(const vertex_list &vertices_) : vertices(vertices_)
{
DEBUGF('c', this);
}
rectangle::rectangle(GLfloat width, GLfloat height)
: polygon(calcVerticies(width, height))
{
DEBUGF('c', this << "(" << width << "," << height << ")");
}
diamond::diamond(GLfloat width, GLfloat height)
: polygon(calcVerticies(width, height))
{
DEBUGF('c', this << "(" << width << "," << height << ")");
}
square::square(GLfloat width) : rectangle(width, width)
{
DEBUGF('c', this);
}
triangle::triangle(const vertex_list &vertices_) : polygon(vertices_)
{
DEBUGF('c', this);
}
equilateral::equilateral(const GLfloat width) : triangle(calcVerticies(width))
{
DEBUGF('c', this);
}
vertex_list rectangle::calcVerticies(GLfloat width, GLfloat height)
{
return {vertex{-width / 2, height / 2},
vertex{-width / 2, -height / 2},
vertex{width / 2, -height / 2},
vertex{width / 2, height / 2}};
}
vertex_list equilateral::calcVerticies(GLfloat width)
{
float height = (width * (sqrt(3) / 2));
return {vertex{0, height / 2},
vertex{-width / 2, -height / 2},
vertex{width / 2, -height / 2}};
}
vertex_list diamond::calcVerticies(const GLfloat width, const GLfloat height)
{
return {vertex{0, height / 2},
vertex{-width / 2, 0},
vertex{0, -height / 2},
vertex{width / 2, 0}};
}
void text::draw(const vertex ¢er, const rgbcolor &color) const
{
DEBUGF('d', this << "(" << center << "," << color << ")");
glColor3ubv(color.ubvec);
auto text_ = reinterpret_cast<const GLubyte *>(textdata.c_str());
glRasterPos2f(center.xpos, center.ypos);
glutBitmapString(glut_bitmap_font, text_);
}
void text::outline(const vertex ¢er, const rgbcolor &color, const size_t thicknes) const
{
size_t width = glutBitmapLength(glut_bitmap_font, reinterpret_cast<const GLubyte *>(textdata.c_str()));
size_t height = glutBitmapHeight(glut_bitmap_font);
glLineWidth(thicknes);
glBegin(GL_LINES);
glColor3ubv(color.ubvec);
// left vertical line
glVertex2f(center.xpos - thicknes, center.ypos - (thicknes * 1.5));
glVertex2f(center.xpos - thicknes, center.ypos + height);
// bottom horizontal line
glVertex2f(center.xpos - (thicknes * 1.5), center.ypos - thicknes);
glVertex2f(center.xpos + width + (thicknes * 1.5), center.ypos - thicknes);
// right vertical line
glVertex2f(center.xpos + width + thicknes, center.ypos - (thicknes * 1.5));
glVertex2f(center.xpos + width + thicknes, center.ypos + height);
// top horizontal line
glVertex2f(center.xpos - (thicknes * 1.5), center.ypos + height);
glVertex2f(center.xpos + width + (thicknes * 1.5), center.ypos + height);
glEnd();
}
void ellipse::draw(const vertex ¢er, const rgbcolor &color) const
{
DEBUGF('d', this << "(" << center << "," << color << ")");
glLineWidth(4);
glBegin(GL_LINE_LOOP);
glColor3ubv(color.ubvec);
const size_t points = 30;
const GLfloat theta = 2.0 * M_PI / points;
for (size_t point = 0; point < points; ++point)
{
GLfloat angle = point * theta;
GLfloat xpos = ((dimension.xpos / 2) * cos(angle)) + center.xpos;
GLfloat ypos = ((dimension.ypos / 2) * sin(angle)) + center.ypos;
glVertex2f(xpos, ypos);
}
glEnd();
}
void ellipse::outline(const vertex ¢er, const rgbcolor &color, const size_t thicknes) const
{
glLineWidth(thicknes);
glBegin(GL_LINE_LOOP);
glColor3ubv(color.ubvec);
const size_t points = 30;
const GLfloat theta = 2.0 * M_PI / points;
for (size_t point = 0; point < points; ++point)
{
GLfloat angle = point * theta;
GLfloat xpos = (((1.25 * dimension.xpos) / 2) * cos(angle)) + center.xpos;
GLfloat ypos = (((1.25 * dimension.ypos) / 2) * sin(angle)) + center.ypos;
glVertex2f(xpos, ypos);
}
glEnd();
}
void polygon::draw(const vertex ¢er, const rgbcolor &color) const
{
DEBUGF('d', this << "(" << center << "," << color << ")");
// draw shape
glBegin(GL_POLYGON);
glLineWidth(4);
glColor3ubv(color.ubvec);
for (auto vertex : vertices)
{
glVertex2f(vertex.xpos + center.xpos,
vertex.ypos + center.ypos);
}
glEnd();
}
void polygon::outline(const vertex ¢er, const rgbcolor &color, const size_t thicknes) const
{
// draw outline
glLineWidth(thicknes);
glBegin(GL_LINES);
glColor3ubv(color.ubvec);
vertex lastVertex = vertices.at(0);
for (auto vertex : vertices)
{
glVertex2f(((1.0 * lastVertex.xpos) + center.xpos),
((1.0 * lastVertex.ypos) + center.ypos));
glVertex2f(((1.0 * vertex.xpos) + center.xpos),
((1.0 * vertex.ypos) + center.ypos));
lastVertex = vertex;
}
glVertex2f(((1.0 * lastVertex.xpos) + center.xpos),
((1.0 * lastVertex.ypos) + center.ypos));
glVertex2f(((1.0 * vertices.at(0).xpos) + center.xpos),
((1.0 * vertices.at(0).ypos) + center.ypos));
glEnd();
}
void shape::show(ostream &out) const
{
out << this << "->" << demangle(*this) << ": ";
}
void text::show(ostream &out) const
{
shape::show(out);
out << glut_bitmap_font << "(" << fontname[glut_bitmap_font]
<< ") \"" << textdata << "\"";
}
void ellipse::show(ostream &out) const
{
shape::show(out);
out << "{" << dimension << "}";
}
void polygon::show(ostream &out) const
{
shape::show(out);
out << "{" << vertices << "}";
}
ostream &operator<<(ostream &out, const shape &obj)
{
obj.show(out);
return out;
}
| true |
18adc4f2a22ddff4feaf1a9989aad0fc5c7cff4b
|
C++
|
saich/cpp-practice
|
/Library/src/encoding/Base64.cpp
|
UTF-8
| 2,409 | 2.953125 | 3 |
[] |
no_license
|
#include "Base64.h"
#include <stdint.h> // TODO: Use <cstdint>
#include <stdexcept>
std::string Base64::ENCODING_MAP =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string Base64::encode(std::string in) {
std::string out;
out.resize((((in.size() - 1) / 3) + 1) * 4);
for (size_t i = 0, j = 0; i < in.size();) {
char ch1 = i < in.size() ? in[i++] : 0;
char ch2 = i < in.size() ? in[i++] : 0;
char ch3 = i < in.size() ? in[i++] : 0;
// combine ch1, ch2, ch3 into a single block
uint32_t triplet = (ch1 << 0x10) + (ch2 << 0x08) + ch3;
// Extract in multiples of 6 bits..
out[j++] = ENCODING_MAP[(triplet >> 3 * 6) & 63];
out[j++] = ENCODING_MAP[(triplet >> 2 * 6) & 63];
out[j++] = ENCODING_MAP[(triplet >> 1 * 6) & 63];
out[j++] = ENCODING_MAP[(triplet >> 0 * 6) & 63];
}
// Determine if last few characters of output needs to be set to "="
if (in.size() % 3 != 0) {
out[out.size() - 1] = '=';
if (in.size() % 3 == 1) {
out[out.size() - 2] = '=';
}
}
return out;
}
std::string Base64::decode(std::string in) {
std::string out;
if (in.size() % 4 != 0) {
throw std::runtime_error("Invalid input");
}
if (in[in.size() - 2] == '=' && in[in.size() - 1] != '=') {
throw std::runtime_error("Invalid input");
}
size_t out_size = (in.size() / 4) * 3;
// The last 1/2 characters can be "=", lets ignore them for a while
size_t in_size = in.size();
if (in[in_size - 1] == '=') {
in_size--;
out_size--;
if (in[in_size - 1] == '=') {
in_size--;
out_size--;
}
}
out.resize(out_size);
for (size_t i = 0, j = 0; i < in.size();) {
// TODO: find() can be costly... Use a reverse lookup table.
// Get 1st 4 characters..
size_t idx1 = ENCODING_MAP.find(in[i++]);
size_t idx2 = ENCODING_MAP.find(in[i++]);
size_t idx3 = (i == in.size() - 2) && in[i] == '=' ? 0 : ENCODING_MAP.find(in[i]);
i++;
size_t idx4 = (i == in.size() - 1) && in[i] == '=' ? 0 : ENCODING_MAP.find(in[i]);
i++;
if (idx1 == in.npos || idx2 == in.npos || idx3 == in.npos || idx4 == in.npos) {
throw std::runtime_error("Invalid input");
}
uint32_t triplet = (idx1 << 3 * 6) + (idx2 << 2 * 6) + (idx3 << 1 * 6) + (idx4 << 0 * 6);
if (j < out_size)
out[j++] = (triplet >> 2 * 8) & 0xFF;
if (j < out_size)
out[j++] = (triplet >> 1 * 8) & 0xFF;
if (j < out_size)
out[j++] = (triplet >> 0 * 8) & 0xFF;
}
return out;
}
| true |
9c396db95e5c085ec9417d9f54541deae89d3e55
|
C++
|
lukevand/kattis-submissions
|
/doubleplusgood.cpp
|
UTF-8
| 819 | 2.53125 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define debug(XXX) cerr << #XXX << ": " << XXX << '\n'
int digits[20];
int main()
{
unordered_set<ll> s;
int plus=0;
for ( ; scanf("%d+", &digits[plus]) != EOF; plus++);
int limit = 1<<plus;
for (int i=0; i < limit; i++) {
ll ssum = 0;
ll current = digits[0];
for (int j=1; j<plus; j++) {
if (i & (1 << j)) {
// add what we have to ssum, then set our current to the next thing
ssum += current;
current = digits[j];
} else {
current = stoll(to_string(current) + to_string(digits[j]));
}
}
ssum += current;
s.insert(ssum);
}
printf("%d\n", (int) s.size());
return 0;
}
| true |
37612fd2ca94120306c3ff829c38d42414fd625e
|
C++
|
yianshu/LFGame
|
/src/LFServerLib/QueueService.cpp
|
GB18030
| 8,490 | 2.640625 | 3 |
[] |
no_license
|
#include "QueueService.h"
#include "DataStorage.h"
//////////////////////////////////////////////////////////////////////////
//캯
CQueueServiceThread::CQueueServiceThread(void)
{
m_hCompletionPort=NULL;
memset(m_cbBuffer,0,sizeof(m_cbBuffer));
}
//
CQueueServiceThread::~CQueueServiceThread(void)
{
}
//ú
bool CQueueServiceThread::InitThread(HANDLE hCompletionPort)
{
//Ч
ASSERT(IsRuning()==false);
ASSERT(m_hCompletionPort==NULL);
//ñ
m_hCompletionPort=hCompletionPort;
memset(m_cbBuffer,0,sizeof(m_cbBuffer));
return true;
}
//ȡ
bool CQueueServiceThread::UnInitThread()
{
//Ч
ASSERT(IsRuning()==false);
//ñ
m_hCompletionPort=NULL;
memset(m_cbBuffer,0,sizeof(m_cbBuffer));
return true;
}
//к
bool CQueueServiceThread::RepetitionRun()
{
//Ч
ASSERT(m_hCompletionPort!=NULL);
//
DWORD dwThancferred=0;
OVERLAPPED * pOverLapped=NULL;
CQueueService * pQueueService=NULL;
//ȴɶ˿
if (GetQueuedCompletionStatus(m_hCompletionPort,&dwThancferred,(PULONG_PTR)&pQueueService,&pOverLapped,INFINITE))
{
//ж˳
if (pQueueService==NULL) return false;
//ȡ
tagDataHead DataHead;
bool bSuccess=pQueueService->GetData(DataHead,m_cbBuffer,sizeof(m_cbBuffer));
ASSERT(bSuccess==true);
//
if (bSuccess==true) pQueueService->OnQueueServiceThread(DataHead,m_cbBuffer,DataHead.wDataSize);
return true;
}
return false;
}
//////////////////////////////////////////////////////////////////////////
//캯
CQueueService::CQueueService(void)
{
m_bService=false;
m_hCompletionPort=NULL;
m_pQueueServiceSink=NULL;
m_lUnComplete=0;
}
//
CQueueService::~CQueueService(void)
{
//ֹͣ
EndService();
return;
}
//ýӿ
void CQueueService::SetQueueServiceSink(CQueueServiceSink *pQueueServiceSink)
{
ASSERT(pQueueServiceSink!=NULL);
m_pQueueServiceSink = pQueueServiceSink;
}
//Ϣ
bool CQueueService::GetBurthenInfo(tagBurthenInfo & BurthenInfo)
{
CThreadLockHandle LockHandle(&m_ThreadLock);
return m_DataStorage.GetBurthenInfo(BurthenInfo);
}
//
bool CQueueService::AddToQueue(WORD wIdentifier, void * const pBuffer, WORD wDataSize)
{
CThreadLockHandle LockHandle(&m_ThreadLock);
m_DataStorage.AddData(wIdentifier,pBuffer,wDataSize);
PostQueuedCompletionStatus(m_hCompletionPort,wDataSize,(ULONG_PTR)this,NULL);
m_lUnComplete++;
return true;
}
LONG CQueueService::GetUnCompleteCount()
{
CThreadLockHandle LockHandle(&m_ThreadLock);
return m_lUnComplete;
}
//ʼ
bool CQueueService::BeginService()
{
//Ч
ASSERT(m_bService==false);
ASSERT(m_hCompletionPort==NULL);
ASSERT(m_pQueueServiceSink!=NULL);
//ɶ˿
m_hCompletionPort=CreateIoCompletionPort(INVALID_HANDLE_VALUE,NULL,NULL,1);
if (m_hCompletionPort==NULL) throw TEXT("жɶ˿ڴʧ");
//߳
if (m_QueueServiceThread.InitThread(m_hCompletionPort)==false) throw TEXT("ж̳߳ʼʧ");
if (m_QueueServiceThread.StartThead()==false) throw TEXT("ж߳ʧ");
//ò
m_bService=true;
return true;
}
//ֹͣ
bool CQueueService::EndService()
{
//ñ
m_bService=false;
//ֹͣ߳
if (m_hCompletionPort!=NULL) PostQueuedCompletionStatus(m_hCompletionPort,0,NULL,NULL);
m_QueueServiceThread.StopThread();
m_QueueServiceThread.UnInitThread();
//رɶ˿
if (m_hCompletionPort!=NULL)
{
CloseHandle(m_hCompletionPort);
m_hCompletionPort=NULL;
}
//
m_DataStorage.RemoveData(false);
return true;
}
//ȡ
bool CQueueService::GetData(tagDataHead & DataHead, void * pBuffer, WORD wBufferSize)
{
CThreadLockHandle LockHandle(&m_ThreadLock);
m_lUnComplete--;
return m_DataStorage.GetData(DataHead,pBuffer,wBufferSize);
}
//Ϣ
void CQueueService::OnQueueServiceThread(const tagDataHead & DataHead, void * pBuffer, WORD wDataSize)
{
ASSERT(m_pQueueServiceSink!=NULL);
try
{
m_pQueueServiceSink->OnQueueServiceSink(DataHead.wIdentifier,pBuffer,DataHead.wDataSize);
}
catch (...) {}
return;
}
//////////////////////////////////////////////////////////////////////////
//캯
CQueueServiceEvent::CQueueServiceEvent()
:m_pQueueService(NULL)
{
}
//
CQueueServiceEvent::~CQueueServiceEvent()
{
}
//ýӿ
void CQueueServiceEvent::SetQueueService(CQueueServiceBase *pQueueService)
{
ASSERT(pQueueService!=NULL);
m_pQueueService = pQueueService;
}
//ʱ¼
bool CQueueServiceEvent::PostTimerEvent(WORD wTimerID, WPARAM wBindParam)
{
//Ч
ASSERT(m_pQueueService!=NULL);
if (m_pQueueService==NULL) return false;
//
CThreadLockHandle BufferLockHandle(&m_BufferLock);
//ͶϢ
NTY_TimerEvent * pTimerEvent=(NTY_TimerEvent *)m_cbBuffer;
pTimerEvent->wTimerID=wTimerID;
pTimerEvent->wBindParam=wBindParam;
m_pQueueService->AddToQueue(EVENT_TIMER,m_cbBuffer,sizeof(NTY_TimerEvent));
return true;
}
//ݿ¼
bool CQueueServiceEvent::PostDataBaseEvent(WORD wRequestID, DWORD dwSocketID, const void * pDataBuffer, WORD wDataSize)
{
//Ч
ASSERT(m_pQueueService!=NULL);
ASSERT((wDataSize+sizeof(NTY_DataBaseEvent))<=MAX_QUEUE_PACKET);
if (m_pQueueService==NULL) return false;
if ((wDataSize+sizeof(NTY_DataBaseEvent))>MAX_QUEUE_PACKET) return false;
//
CThreadLockHandle BufferLockHandle(&m_BufferLock);
//ͶϢ
NTY_DataBaseEvent * pDataBaseEvent=(NTY_DataBaseEvent *)m_cbBuffer;
pDataBaseEvent->dwSocketID=dwSocketID;
pDataBaseEvent->wRequestID=wRequestID;
pDataBaseEvent->wDataSize=wDataSize;
pDataBaseEvent->pDataBuffer=NULL;
if (wDataSize>0)
{
ASSERT(pDataBuffer!=NULL);
CopyMemory(m_cbBuffer+sizeof(NTY_DataBaseEvent),pDataBuffer,wDataSize);
}
m_pQueueService->AddToQueue(EVENT_DATABASE,m_cbBuffer,sizeof(NTY_DataBaseEvent)+wDataSize);
return true;
}
//Ӧ¼
bool CQueueServiceEvent::PostSocketAcceptEvent(DWORD dwSocketID, DWORD dwClientIP)
{
//Ч
ASSERT(m_pQueueService!=NULL);
if (m_pQueueService==NULL) return false;
//
CThreadLockHandle BufferLockHandle(&m_BufferLock);
//ͶϢ
NTY_SocketAcceptEvent * pSocketAcceptEvent=(NTY_SocketAcceptEvent *)m_cbBuffer;
pSocketAcceptEvent->dwSocketID=dwSocketID;
pSocketAcceptEvent->dwClientIP=dwClientIP;
m_pQueueService->AddToQueue(EVENT_SOCKET_ACCEPT,m_cbBuffer,sizeof(NTY_SocketAcceptEvent));
return true;
}
//ȡ¼
bool CQueueServiceEvent::PostSocketReadEvent(DWORD dwSocketID, DWORD dwCommand, const void * pDataBuffer, WORD wDataSize)
{
//Ч
ASSERT(m_pQueueService!=NULL);
ASSERT((wDataSize+sizeof(NTY_SocketReadEvent))<=MAX_QUEUE_PACKET);
if (m_pQueueService==NULL) return false;
if ((wDataSize+sizeof(NTY_SocketReadEvent))>MAX_QUEUE_PACKET) return false;
//
CThreadLockHandle BufferLockHandle(&m_BufferLock);
//ͶϢ
NTY_SocketReadEvent * pSocketReadEvent=(NTY_SocketReadEvent *)m_cbBuffer;
pSocketReadEvent->dwSocketID=dwSocketID;
pSocketReadEvent->dwCommand=dwCommand;
pSocketReadEvent->wDataSize=wDataSize;
pSocketReadEvent->pDataBuffer=NULL;
if (wDataSize>0)
{
ASSERT(pDataBuffer!=NULL);
CopyMemory(m_cbBuffer+sizeof(NTY_SocketReadEvent),pDataBuffer,wDataSize);
}
m_pQueueService->AddToQueue(EVENT_SOCKET_READ,m_cbBuffer,sizeof(NTY_SocketReadEvent)+wDataSize);
return false;
}
//ر¼
bool CQueueServiceEvent::PostSocketCloseEvent(DWORD dwSocketID, DWORD dwClientIP, DWORD dwConnectSecond)
{
//Ч
ASSERT(m_pQueueService!=NULL);
if (m_pQueueService==NULL) return false;
//
CThreadLockHandle BufferLockHandle(&m_BufferLock);
//ͶϢ
NTY_SocketCloseEvent * pSocketCloseEvent=(NTY_SocketCloseEvent *)m_cbBuffer;
pSocketCloseEvent->dwSocketID=dwSocketID;
pSocketCloseEvent->dwClientIP=dwClientIP;
pSocketCloseEvent->dwConnectSecond=dwConnectSecond;
m_pQueueService->AddToQueue(EVENT_SOCKET_CLOSE,m_cbBuffer,sizeof(NTY_SocketCloseEvent));
return true;
}
LONG CQueueServiceEvent::GetUnCompleteCount()
{
//Ч
ASSERT(m_pQueueService!=NULL);
if (m_pQueueService==NULL) return false;
//
CThreadLockHandle BufferLockHandle(&m_BufferLock);
return m_pQueueService->GetUnCompleteCount();
}
//////////////////////////////////////////////////////////////////////////
| true |
76dd3c96dffc2de4d11a160e23f6843dfe486a08
|
C++
|
vule12345/ETF-OS1
|
/inc/PCB.h
|
UTF-8
| 1,367 | 2.59375 | 3 |
[] |
no_license
|
// File: PCB.h
#ifndef _PCB_H_
#define _PCB_H_
#include "thread.h"
#include "list.h"
#include "PCBlist.h"
#include "utility.h"
#include "kernel.h"
#define SP_DISP 20
#define SS_DISP 22
#define STACK_DISP 12
#define STACK_SIZE_DISP 4
#define OWNER_THREAD_SIZE_DISP 16
const StackSize MAX_STACK_SIZE = 65536; // 64KB
class PCB {
static ID MAX_ID;
public:
const ID id; // 0, 2
const Time timeSlice; // 2, 2
const StackSize stackSize; // 4, 4
TName name; // 8, 4
void* stack; // 12, 4
Thread* const ownerThread; // 16, 4
unsigned sp, ss; // 20, 2; 22, 2
TimeListNode timeListPosition;
PCBListNode waitingListPosition;
// Da li je probudjena nit pre sa wakeUp (pre nego sto je trebala)
volatile bool wokenUp;
// Da li je zavrsena run metoda
volatile bool completed;
PCBList waitingForMeToComplete;
PCBListNode threadsListPosition;
PCB(TName _name,
StackSize _stackSize,
Time _timeSlice,
Thread* _ownerThread
);
~PCB();
inline bool sleeping() const {
return timeListPosition != NULL;
}
inline bool waiting() const {
return waitingListPosition != NULL;
}
bool waitToComplete(); // Thread safe
bool wakeUp(); // Thread safe
void start(); // Thread safe
};
#endif // _PCB_H_
| true |
fa02dfb30ec04462764b5213b92409fd736c7e1d
|
C++
|
humbertodias/challenges
|
/uri/2 - Ad-Hoc/1845/main.cpp
|
UTF-8
| 692 | 2.671875 | 3 |
[] |
no_license
|
#include <string>
#include <iostream>
#include <map>
#include <cstdio>
using namespace std;
int main(){
char X, aux;
while (scanf("%c", &X) != EOF) {
if(X=='s' || X=='v' || X=='p' || X=='x' || X=='b' || X=='j' || X=='z' || X=='f') {
if(aux != 'f' && aux != 'F') {
printf("f");
aux = 'f';
}
}
else if(X=='S' || X=='V' || X=='P' || X=='X' || X=='B' || X=='J' || X=='Z' || X=='F') {
if(aux != 'f' && aux != 'F') {
printf("F");
aux = 'F';
}
}
else {
printf("%c", X);
aux = X;
}
}
return 0;
}
| true |
ea1bd620ed16dbf8ae228d0077716513a97f7ba7
|
C++
|
erik-jenkins/Breakout
|
/include/texture.hpp
|
UTF-8
| 425 | 2.6875 | 3 |
[] |
no_license
|
#pragma once
#include <GL/glew.h>
class Texture2D
{
public:
GLuint id;
GLuint width, height;
GLuint internalFormat;
GLuint imageFormat;
GLuint wrapS;
GLuint wrapT;
GLuint filterMin;
GLuint filterMax;
Texture2D();
// generate texture from image data
void generate(GLuint width, GLuint height, unsigned char* data);
// binds the texture as the current active GL_TEXTURE_2D texture object
void bind() const;
};
| true |
e6909f9439987d9ad89bd644275e578fbbed93cd
|
C++
|
yaluen/Robotics2015
|
/AssignmentIII/part_b/main.cpp
|
UTF-8
| 7,334 | 2.890625 | 3 |
[] |
no_license
|
// This program is a simple template of an C++ program loading and showing image with OpenCV.
// You can ignore this file and write your own program.
// The program takes a image file name as an argument.
#include <stdio.h>
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
float calculateMoment(Mat Image, float a, float b);
float calculateCentralMoment(Mat Image, float j, float b, float x, float y);
int main(int argc, char **argv) {
// Check number of arguments.
// If no argument input, exit the program.
if ( argc != 2 )
exit(1);
Mat SrcImage, WorkImage;
// Load a gray scale picture.
SrcImage = imread(argv[1], 0);
if (!SrcImage.data)
exit(1);
// Create windows for debug.
//namedWindow("SrcImage", WINDOW_AUTOSIZE);
//namedWindow("WorkImage", WINDOW_AUTOSIZE);
if (SrcImage.channels()>1)
cvtColor(SrcImage, SrcImage, CV_BGR2GRAY);
//else gray = original;
blur(SrcImage, SrcImage, Size(3, 3));
// Show the source image.
imshow("SrcImage", SrcImage);
//waitKey(0);
// Duplicate the source iamge.
WorkImage = SrcImage.clone();
Mat canny_output;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
// For images 1-3
int x_border = 0;
int y_border = 0;
int x_border_max = 700;
int y_border_max = 700;
int thresh = 100;
// For image 4
int max_thresh = 255;
RNG rng(12345);
/// Detect edges using canny
Canny(WorkImage, canny_output, thresh, thresh * 2, 3);
/// Find contours
findContours(canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
/// Get the moments
vector<Moments> mu(contours.size());
for (int i = 0; i < contours.size(); i++)
{
mu[i] = moments(contours[i], false);
}
/// Get the mass centers (aka centroid):
vector<Point2f> mc(contours.size());
for (int i = 0; i < contours.size(); i++)
{
mc[i] = Point2f(mu[i].m10 / mu[i].m00, mu[i].m01 / mu[i].m00);
}
/// Draw contours
Mat drawing = Mat::zeros(canny_output.size(), CV_8UC3);
for (int i = 0; i< contours.size(); i++)
{
if (mc[i].x > x_border && mc[i].y > y_border && mc[i].x < x_border_max && mc[i].y < y_border_max)
{
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());
circle(drawing, mc[i], 4, color, -1, 8, 0);
}
}
/// Show in a window
namedWindow("Contours", CV_WINDOW_AUTOSIZE);
imshow("Contours", drawing);
// Debug use
/// Calculate the area with the moments 00 and compare with the result of the OpenCV function
printf("\t Info: Area and Contour Length \n");
for (int i = 0; i< contours.size(); i++)
{
if (mc[i].x > x_border && mc[i].y > y_border && mc[i].x < x_border_max && mc[i].y < y_border_max)
{
printf(" * Contour[%d] - Area (M_00) = %.2f - Area OpenCV: %.2f - Length: %.2f \n", i, mu[i].m00, contourArea(contours[i]), arcLength(contours[i], true));
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());
circle(drawing, mc[i], 4, color, -1, 8, 0);
}
}
// Calculate the principal angle using the central moments
// Central moments can be retrieved from moments (mu) by: mu[i].mu20, mu[i].mu11, etc
// So we should be able to get the principal angle like so:
for (int i = 0; i < contours.size(); i++)
{
float theta;
// Further filter of noise: No area too small, and no border of the entire picture.
/*if (mu[i].m00 > 20 && mu[i].m00 < 100000 && (mc[i].x > x_border && mc[i].y > y_border && mc[i].x < x_border_max && mc[i].y < y_border_max))
{*/
if (mc[i].x > x_border && mc[i].y > y_border && mc[i].x < x_border_max && mc[i].y < y_border_max)
{
theta = 0.5 * atan2(2 * mu[i].m11, mu[i].m20 - mu[i].m02);
//cout << "theta = " << (theta * 180.0 / 3.14) << endl << endl;
//cout << "Number: " << i << " " << mc[i].x << " " << mc[i].y << " " << (theta * 180.0 / 3.14) << endl << endl;
cout << mc[i].x << " " << mc[i].y << " " << (theta * 180.0 / 3.14) << endl;
}
}
//Extract the contour of
/* If you're familiar with OpenCV, findContours() will be a better way.*/
// GaussianBlur(WorkImage, WorkImage, Size( 5, 5), 0, 0);
// threshold(WorkImage, WorkImage, 160, 255, THRESH_BINARY);
// // Not sure what is the output... because put ONE threshold on 3 channel picture????????????
// // Or maybe it's not a RGB picture?
//
//
//
//
// // // Opening
// // erode(WorkImage, WorkImage, Mat());
// // dilate(WorkImage, WorkImage, Mat());
//
// // // Duplicate the working iamge.
// ComImage = WorkImage.clone();
//
// // Show the working image after preprocessing.
//
//
//
//
//
//// for testing, draw a small picture:
//// Mat testImage(4,2,CV_8UC3, Scalar::all(0));
//
//// testImage.at<Vec3b>(0,0)[0] = 255;
//// testImage.at<Vec3b>(0,0)[1] = 255;
//// testImage.at<Vec3b>(0,0)[2] = 255;
//
//// testImage.at<Vec3b>(1,1)[0] = 255;
//// testImage.at<Vec3b>(1,1)[1] = 255;
//// testImage.at<Vec3b>(1,1)[2] = 255;
//
//// testImage.at<Vec3b>(2,1)[0] = 255;
//// testImage.at<Vec3b>(2,1)[1] = 255;
//// testImage.at<Vec3b>(2,1)[2] = 255;
//
//// testImage.at<Vec3b>(3,1)[0] = 255;
//// testImage.at<Vec3b>(3,1)[1] = 255;
//// testImage.at<Vec3b>(3,1)[2] = 255;
//
//// WorkImage = testImage.clone();
//// cout << WorkImage << endl;
//
//
//
// float xc, yc, m11, m20, m02, theta;
// xc = calculateMoment(WorkImage, 1, 0) / calculateMoment(WorkImage, 0, 0);
// yc = calculateMoment(WorkImage, 0, 1) / calculateMoment(WorkImage, 0, 0);
//
//
// cout << "xc, yc = " << xc << " " << yc << endl;
// cout << "h, w = " << WorkImage.rows << " " << WorkImage.cols << endl;
// cout << "xc, yc = " << xc / (float)WorkImage.rows << " " << yc / (float)WorkImage.cols << endl;
//
//
// m11 = calculateCentralMoment(WorkImage, 1, 1, xc, yc);
// m20 = calculateCentralMoment(WorkImage, 2, 0, xc, yc);
// m02 = calculateCentralMoment(WorkImage, 0, 2, xc, yc);
// theta = 0.5 * atan2(2*m11, m20 - m02);
// cout << "theta = " << theta * 180.0 / 3.14 << endl << endl;
//
// for (int i = -2; i <= 2; i++)
// {
// for (int j = -2; j <= 2; j++)
// {
// // For each chanel.... What's going on?????????????
// for (int k = 0; k < 3; k++)
// {
// WorkImage.at<Vec3b>((int)xc + i, (int)yc + j)[k] = 0;
// }
// }
// }
//
// imshow("WorkImage", WorkImage);
waitKey(0);
return 0;
}
//
//float calculateMoment(Mat Image, float a, float b)
//{
// float sum = 0;
// int height = Image.rows;
// int width = Image.cols;
// float i, j;
//
// for (i = 0; i < height; i+= 1)
// {
// for (j = 0; j < width; j+= 1)
// {
// if ((Image.at<Vec3b>(i, j)).val[0] == 255)
// {
// sum += pow(i, a) * pow(j, b);
// }
// }
// }
//// cout << "i, j = " << i << " " << j << endl;
// cout << "calculateMoment, " << a << " "<< b << ",ans:" << sum << endl;
// return sum;
//}
//
//float calculateCentralMoment(Mat Image, float a, float b, float x, float y)
//{
// float sum = 0;
// int height = Image.rows;
// int width = Image.cols;
//
// for (float i = 0; i < height; i++)
// {
// for (float j = 0; j < width; j++)
// {
// if ((Image.at<Vec3b>(i, j)).val[0] == 255)
// {
// sum += pow(i - x, a) * pow(j - y, b);
// }
// }
// }
// cout << "calculateCentralMoment, " << a << " "<< b << ",ans:" << sum << endl;
// return sum;
//}
//
//
//
//
| true |
3b67c5c1aa700cdf9cbc1ecb59fecd6b593d2389
|
C++
|
internetofthingsgolem/ITGJava
|
/trie.h
|
UTF-8
| 317 | 2.671875 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
class trie
{
public:
struct node
{
node* Zero ;
node* One ;
bool is_prefix;
node()
{
Zero = NULL;
One = NULL;
is_prefix = false;
}
};
node* root;
trie();
void insert_ip(string netAddress, int subnetlength);
int find_ip(string ip_find);
};
| true |
5070040345333c67a5dff1db83bb6dd42ef95f95
|
C++
|
rahulnairiit/VisualStudiocodes
|
/algocoding/algocoding/permuteRecursive.cpp
|
WINDOWS-1252
| 1,609 | 3.875 | 4 |
[] |
no_license
|
/*
Implement a function that prints all possible combinations of the characters in a string.
These combinations range in length from one to the length of the string. Two combinations
that differ only in ordering of their characters are the same combination. In other words,
12 and 31 are different combinations from the input string 123, but 21 is the same as 12.
*/
#include <iostream>
using namespace std;
void dopermute(char * input,int numofchar, int *used, int level,char* out);
void permutestring(char * input)
{
int *used = (int*) malloc((strlen(input) + 1)*sizeof(int));
memset(used,0,strlen(input) + 1);
for(int i =1; i <= strlen(input);i++)
{
char * out = (char*) malloc ((i+1)*sizeof(char));
memset(out,0,(i+1)*sizeof(char));
memset(used,0,(strlen(input) + 1)*sizeof(int));
dopermute(input,i,used,0,out);
free(out);
}
}
void dopermute(char * input,int numofchar, int *used, int level,char * out)
{
int len = strlen(input);
if( (level == numofchar) || (level == len) )
{
out[level] = '\0';
cout<<out<<endl;
return;
}
for(int i = 0; i < len; i++)
{
char x = input[i];
if(used[i] == 1)
continue;
else
{
out[level] = x;
used[i] = 1;
dopermute(input,numofchar,used,level+1,out);
if( (level == numofchar - 2))
{
//so that if abc is already printed then dont free a
// so we will get abd and adb too not bad or bac which is already printed
}
else
{
used[i] = 0;
out[level] = '\0';
}
}
}
}
int main()
{
char input[] = "abcd";
permutestring(input);
getchar();
}
| true |
692e8bb0c04ee92862e5c255dc984d8dcc252ce9
|
C++
|
agaucher/Arduino
|
/Micrologiciel_cpy.ino
|
UTF-8
| 3,165 | 2.859375 | 3 |
[] |
no_license
|
#include <SPI.h>
#include <Ethernet2.h>
const int PIN = 6;
const unsigned int MAX_DATA_LENGTH = 300;
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
const int PORT = 9800;
EthernetServer server(PORT);
void setup() {
Serial.begin(9600);
Serial.println("Initialization");
pinMode(PIN, OUTPUT);
while (Ethernet.begin(mac) == 0)
{
Serial.println ("Cannot get an IP address using DHCP protocol. Error !");
delay (10000);
}
Serial.println("Server web is started");
Serial.print("Listening on following interface: ");
Serial.print(Ethernet.localIP());
Serial.print(" (");
Serial.print(PORT);
Serial.println(")");
}
void loop() {
EthernetClient client = server.available();
if (client) {
Serial.println("-----------------------------");
Serial.println("Receiving new http request...\n");
char data[MAX_DATA_LENGTH];
int index = 0;
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
if (index < MAX_DATA_LENGTH-1)
{
data[index] = c;
index ++;
}
if (c == '\n' && currentLineIsBlank) {
data[index] = '\0';
Serial.println(data);
if (strstr(data, "GET /openDoor HTTP"))
{
handleOpenDoorRequest(&client, data);
}
else
{
// URL is wrong !
sendResponse(&client, 404, (char*)"");
}
break;
}
if (c == '\n') {
currentLineIsBlank = true;
}
else if (c != '\r') {
currentLineIsBlank = false;
}
}
}
client.stop();
Serial.println("client disconnected");
Serial.println("-----------------------------");
}
delay (50);
}
void handleOpenDoorRequest(EthernetClient* client, char* data)
{
if (isUserAuthorized(data))
{
openDoor();
sendResponse(client, 200, (char*)"Done!");
}
else
{
sendResponse(client, 403, (char*)"");
}
}
bool isUserAuthorized(char* data)
{
bool success = false;
success |= strstr(data, "Authorization: Basic YWdhdWNoZXI6OWghTDIqUXA=") != NULL;
success |= strstr(data, "Authorization: Basic ZWxlc3RyYkQ6NE0zeQosciE=") != NULL;
return success;
}
void openDoor()
{
Serial.println("opening door");
digitalWrite(PIN, HIGH);
delay(1250);
digitalWrite(PIN, LOW);
}
void sendResponse(EthernetClient* client, int code, char* body)
{
char response[MAX_DATA_LENGTH];
Serial.println("Reply to client: ");
switch(code)
{
case 200:
strcpy(response, "HTTP/1.1 200 OK\n");
break;
case 404:
strcpy(response, "HTTP/1.1 404 Not Found\n");
break;
case 403:
strcpy(response, "HTTP/1.1 403 Forbidden\n");
break;
default:
strcpy(response, "HTTP/1.1 500 Internal Server Error\n");
}
strcat(response, "Content-Type: text/html\n");
strcat(response, "Connection: close\n");
strcat(response, "\n");
strcat(response, body);
strcat(response, "\n");
Serial.println(response);
client->print (response);
}
| true |
1e64c2fa799722d135ce25fd97f5cb26e20a7d11
|
C++
|
mohit3112/FullMetalEngine
|
/FMEGraphics/inc/RenderComponent.h
|
UTF-8
| 750 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
#ifndef IRENDERCOMPONENT_H_
#define IRENDERCOMPONENT_H_
#include "IComponent.h"
#include "IModel.h"
namespace FME
{
namespace Graphics
{
enum GameType
{
RENDER2D,
RENDER3D
};
/** \class RenderComponent
* \brief a component dedicated to rendering objects
*/
class RenderComponent : public IComponent
{
public:
RenderComponent(std::shared_ptr<IModel> model);
virtual void Update();
virtual void Draw();
std::string GetShaderName() const;
virtual void SetGameType(GameType type) { m_gameType = type; };
virtual GameType GetGameType() const { return m_gameType; };
private:
std::shared_ptr<IModel> m_model;
GameType m_gameType;
};
}
}
#endif
| true |
e2c005ef74ef4d34fe33daa86ee8aff1e23679b2
|
C++
|
ffamilyfriendly/teamsDLL
|
/test/helpers.cpp
|
UTF-8
| 933 | 2.84375 | 3 |
[] |
no_license
|
#include "helpers.h"
#include <sstream>
#include <fstream>
size_t utils::split(const std::string &txt, std::vector<std::string> &strs, char ch)
{
size_t pos = txt.find( ch );
size_t initialPos = 0;
strs.clear();
// Decompose statement
while( pos != std::string::npos ) {
strs.push_back( txt.substr( initialPos, pos - initialPos ) );
initialPos = pos + 1;
pos = txt.find( ch, initialPos );
}
// Add the last one
strs.push_back( txt.substr( initialPos, std::min( pos, txt.size() ) - initialPos + 1 ) );
return strs.size();
}
json utils::config() {
std::ifstream t("config.json");
if(!t.good()) {
std::cout << "NOT GOOD >:(" << std::endl;
return json::parse("{\"error\":\"file does not exist\"}");
}
std::stringstream buffer;
buffer << t.rdbuf();
std::string epicly = buffer.str();
t.close();
return json::parse(epicly);
}
| true |
8772a51af9757871e30b776f854466983fd4ce8d
|
C++
|
kounelisagis/Text-Compression---Huffman-Coding
|
/source codes/help_library.cpp
|
UTF-8
| 2,440 | 3.140625 | 3 |
[
"MIT"
] |
permissive
|
#include "help_library.h"
bool CustomCompare:: operator() (const TreeNode* first_node, const TreeNode* second_node)
{
return first_node->frequency > second_node->frequency;
}
/*int get_index_of(vector<TreeNode*> myvector, char a) {
vector<TreeNode*>::iterator ptr;
for (ptr = myvector.begin(); ptr < myvector.end(); ptr++)
if((*ptr)->letter == a)
return distance(myvector.begin(), ptr);
return -1;
}*/
pr_queue create_queue(const string &text) {
unordered_map<char, TreeNode*> umap;
//vector<TreeNode*> vec;
for(unsigned int i=0;i<text.size();i++) {
/*int index = get_index_of(vec, text[i]);
if(index == -1) { // first time
TreeNode *temp_node = new TreeNode();
temp_node->frequency = 1;
temp_node->letter = text[i];
vec.push_back(temp_node);
}
else //not first time
vec[index]->frequency++;*/
char current_char = text[i];
if(umap.count(current_char)>0)
umap[current_char]->frequency++;
else {
TreeNode *temp_node = new TreeNode();
temp_node->frequency = 1;
temp_node->letter = current_char;
umap[current_char] = temp_node;
}
}
pr_queue pq;
//for(unsigned int i=0;i<vec.size();i++)
// pq.push(vec[i]);
for (auto x : umap)
pq.push(x.second);
//encode_help_string += x.second + '\n' + x.first + '\n';
return pq;
}
string read_file(const string& file_name) {
string text;
ifstream input_stream(file_name, ios::in | ios::binary);
if(!input_stream)
return "";
do {
int c= input_stream.get();
if (c==EOF) break;
text += (char)c;
} while (!input_stream.fail());
return text;
}
void save_text_to_file(const string& text, const string& file_name) {
ofstream OutFile;
OutFile.open(file_name, ios::out | ios::binary);
OutFile << text;
OutFile.close();
}
string int_to_byte(unsigned int num) {
string final_string = "00000000";
for(int i=7;i>=0;i--) {
final_string[i] = (num%2) + '0';
num = num >> 1;
}
return final_string;
}
void delete_tree_nodes(TreeNode *root) {
//delete
if(root->left!=nullptr)
delete_tree_nodes(root->left);
//right
if(root->right!=nullptr)
delete_tree_nodes(root->right);
//root visit
root = nullptr;
delete root;
}
| true |
525d6eb78ed29d35cae8dbcc3762ad9303d68826
|
C++
|
MtMindSculptz95/Minh-Tran
|
/h31/h31.cpp
|
UTF-8
| 647 | 2.53125 | 3 |
[] |
no_license
|
/**
@file h31.cpp
@author your name here
@version what day and meeting time
*/
#include <string>
#include <stdexcept>
using namespace std;
#include "h31.h"
string STUDENT = "mtran362"; // Add your Canvas/occ-email ID
// Add your implementation here
bool find(const string& s, const string& t)
{
size_t x = t.size();
if (s.size() < x)
{
return false;
}
else if (s.substr(0, x) == t)
{
return true;
}
return find(s.substr(1) , t);
}
////////////////// Student Testing //////////////////////////
#include <iostream>
int run()
{
cout << "Student testing" << endl;
return 0;
}
| true |
dfe1e62510097cac0416f4cd14f09fd79223f45e
|
C++
|
ajnirp/binarysearch
|
/linked-list-deletion.cpp
|
UTF-8
| 511 | 3.484375 | 3 |
[] |
no_license
|
// https://binarysearch.com/problems/Linked-List-Deletion
// Explanation: https://stackoverflow.com/questions/12914917/using-pointers-to-remove-item-from-singly-linked-list
/**
* class LLNode {
* public:
* int val;
* LLNode *next;
* };
*/
LLNode* solve(LLNode* node, int target) {
LLNode** pp = &node;
while (*pp != nullptr) {
if ((*pp)->val == target) {
*pp = (*pp)->next;
} else {
pp = &(*pp)->next;
}
}
return node;
}
| true |
e2c6d58152a42ee4011d33a8b9734e954e0d5faf
|
C++
|
zhidateh/fusionparser
|
/mathfunction.cpp
|
UTF-8
| 1,601 | 3.234375 | 3 |
[] |
no_license
|
#include "mathfunction.h"
MathFunction::MathFunction()
{
}
void MathFunction::rotationMatrix(double &x, double &y, double angle)
{
double _x = x*cos(angle) - y*sin(angle);
double _y = x*sin(angle) + y*cos(angle);
x = _x;
y = _y;
}
QVector<double> MathFunction::calculateHeading(QVector<double> &x, QVector<double> &y)
{
QVector<double> _hdg;
for(int i=0;i < x.length()-1; ++i){
double _heading = atan2(y.at(i+1) - y.at(i), x.at(i+1) - x.at(i));
_hdg.push_back(normalizeAngle(_heading));
}
//last heading is previous heading
_hdg.push_back(_hdg.last());
return _hdg;
}
Coordinate MathFunction::linearinterpolation(QVector<double> &xData, QVector<double> &yData, int nPoints)
{
Coordinate _coordinate;
// Interpolate
for (int i =0; i < xData.length()-1;++i )
{
double xL = xData.at(i);
double xR = xData.at(i+1);
double yL = yData.at(i);
double yR = yData.at(i+1);
double dx = (xR-xL)/nPoints;
double dy = (yR-yL)/nPoints;
for(int i =0;i <= nPoints; ++i){
_coordinate.UTMX.push_back(xL + i*dx);
_coordinate.UTMY.push_back(yL + i*dy);
}
}
return _coordinate;
}
double MathFunction::normalizeAngle(double angle)
{
if (angle > M_PI){
angle -= 2*M_PI;
}
else if(angle < -M_PI){
angle += 2*M_PI;
}
return angle;
}
double MathFunction::reverseAngle(double angle)
{
if (angle > 0){
angle -= M_PI;
}
else if(angle < 0){
angle += M_PI;
}
return angle;
}
| true |
7cf9fe20238bf7ca6e4546c9e9a6d103fa2128ea
|
C++
|
jmppmj/3dgameengine_jillplatts
|
/core/MousePicker.cpp
|
UTF-8
| 2,118 | 3.046875 | 3 |
[
"MIT"
] |
permissive
|
#include "MousePicker.hpp"
#include <iostream>
#define GLM_ENABLE_EXPERIMENTAL
#include "glm/gtx/string_cast.hpp"
MousePicker::MousePicker(Camera *cam) {
camera = cam;
projMatriX = camera->getProjectionMatrix();
viewMatriX = camera->getViewMatrix();
}
glm::vec3 MousePicker::getCurrentRay() {
return currentRay;
}
//needs to be called every frame
void MousePicker::update() {
viewMatriX = camera->getViewMatrix();
projMatriX = camera->getProjectionMatrix();
currentRay = calculateMouseRay();
}
//get x coord from mousecallback
void MousePicker::saveCoordX(double x) {
this->x = x;
}
//get y coord from mousecallback
void MousePicker::saveCoordY(double y) {
this->y = y;
}
//get width from mousecallback
void MousePicker::updateBufferW(int width) {
this->width = width;
}
//get height from mousecallback
void MousePicker::updateBufferH(int height) {
this->height = height;
}
glm::vec3 MousePicker::calculateMouseRay() {
//screen coordinates
double x1 = x;
double y1 = y;
glm::vec2 normalCoords = getNormalizedDevCoor(x1, y1);
//clip space
clipCoords = glm::vec4(normalCoords.x, normalCoords.y, -1.0f, 1.0f);
//eye space
glm::vec4 eyeSpaceCoords = toEye(clipCoords);
//world space
glm::vec3 worldSpaceRay = toWorldCoor(eyeSpaceCoords);
worldSpaceRay.z = -worldSpaceRay.z;
return worldSpaceRay;
}
//clip space to eye space/4d eye coordinates
glm::vec4 MousePicker::toEye(glm::vec4 clips) {
glm::mat4 invProj = glm::inverse(projMatriX);
glm::vec4 eyeCoor = invProj * clips;
glm::vec4 eyeCoorFinal = glm::vec4(eyeCoor.x, eyeCoor.y, -camera->getNearPlane(), 1.0f);
return eyeCoorFinal;
}
//eye space to world space
glm::vec3 MousePicker::toWorldCoor(glm::vec4 eyeSpaceCoords) {
glm::mat4 invView = glm::inverse(viewMatriX);
glm::vec4 rWorld = invView * eyeSpaceCoords;
glm::vec3 finalWorld = glm::vec3(rWorld.x, rWorld.y, rWorld.z);
return finalWorld;
}
glm::vec2 MousePicker::getNormalizedDevCoor(double x1, double y1) {
double x2 = (2.0f * x1) / ((float)width) - 1.0f;
double y2 = (2.0f * y1) / ((float)height) - 1.0f;
glm::vec2 newVec = glm::vec2(x2, -y2);
return newVec;
}
| true |
9c964f2f748c6c68b0dcd4df324131b92cc174c2
|
C++
|
yaito3014/UECRayTracing
|
/yk/color.hpp
|
UTF-8
| 3,156 | 2.984375 | 3 |
[] |
no_license
|
#pragma once
#ifndef YK_RAYTRACING_COLOR_H
#define YK_RAYTRACING_COLOR_H
#include <algorithm>
#include <cstdint>
#include "concepts.hpp"
namespace yk {
template <concepts::arithmetic T>
struct alignas(T) color3 {
using value_type = T;
T r, g, b;
template <concepts::arithmetic U>
constexpr color3<U> to() const {
return {
.r = static_cast<U>(r),
.g = static_cast<U>(g),
.b = static_cast<U>(b),
};
}
constexpr color3 &clamp(T min, T max) {
r = std::clamp(r, min, max);
g = std::clamp(g, min, max);
b = std::clamp(b, min, max);
return *this;
}
constexpr color3 clamped(T min, T max) const {
return {
.r = std::clamp(r, min, max),
.g = std::clamp(g, min, max),
.b = std::clamp(b, min, max),
};
}
constexpr bool operator==(const color3 &) const = default;
constexpr color3 operator-() const { return {-r, -g, -b}; }
constexpr color3 &operator+=(const color3 &rhs) {
r += rhs.r;
g += rhs.g;
b += rhs.b;
return *this;
}
constexpr color3 &operator-=(const color3 &rhs) {
r -= rhs.r;
g -= rhs.g;
b -= rhs.b;
return *this;
}
constexpr color3 &operator*=(const color3 &rhs) {
r *= rhs.r;
g *= rhs.g;
b *= rhs.b;
return *this;
}
template <concepts::arithmetic U>
constexpr color3 &operator*=(U rhs) {
r *= rhs;
g *= rhs;
b *= rhs;
return *this;
}
template <concepts::arithmetic U>
constexpr color3 &operator/=(U rhs) {
r /= rhs;
g /= rhs;
b /= rhs;
return *this;
}
};
template <concepts::arithmetic T, concepts::arithmetic U>
constexpr auto operator+(const color3<T> &lhs, const color3<U> &rhs) {
return color3{lhs.r + rhs.r, lhs.g + rhs.g, lhs.b + rhs.b};
}
template <concepts::arithmetic T, concepts::arithmetic U>
constexpr auto operator-(const color3<T> &lhs, const color3<U> &rhs) {
return color3{lhs.r - rhs.r, lhs.g - rhs.g, lhs.b - rhs.b};
}
template <concepts::arithmetic T, concepts::arithmetic U>
constexpr auto operator*(const color3<T> &lhs, const color3<U> &rhs) {
return color3{lhs.r * rhs.r, lhs.g * rhs.g, lhs.b * rhs.b};
}
template <concepts::arithmetic T, concepts::arithmetic U>
constexpr auto operator*(const color3<T> &color, U scalar) {
return color3{color.r * scalar, color.g * scalar, color.b * scalar};
}
template <concepts::arithmetic T, concepts::arithmetic U>
constexpr auto operator*(T scalar, color3<U> color) {
return color3{color.r * scalar, color.g * scalar, color.b * scalar};
}
template <concepts::arithmetic T, concepts::arithmetic U>
constexpr auto operator/(color3<T> color, U scalar) {
return color3{color.r / scalar, color.g / scalar, color.b / scalar};
}
template <concepts::arithmetic T, concepts::arithmetic U>
constexpr auto operator/(T scalar, color3<U> color) {
return color3{color.r / scalar, color.g / scalar, color.b / scalar};
}
using color3b = color3<uint8_t>;
using color3d = color3<double>;
} // namespace yk
#endif // !YK_RAYTRACING_COLOR_H
| true |
74fc50e1348bfb0e3ee5a77f90467f2b0e57928a
|
C++
|
ORNL-QCI/exatn
|
/src/numerics/tensor_leg.hpp
|
UTF-8
| 2,977 | 3.078125 | 3 |
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/** ExaTN::Numerics: Tensor leg (connection)
REVISION: 2020/10/09
Copyright (C) 2018-2019 Dmitry I. Lyakh (Liakh)
Copyright (C) 2018-2019 Oak Ridge National Laboratory (UT-Battelle) **/
/** Rationale:
(a) A tensor leg associates a tensor mode with a mode in another tensor
by carrying the id of another tensor, its specific mode (position),
and direction of the association.
**/
#ifndef EXATN_NUMERICS_TENSOR_LEG_HPP_
#define EXATN_NUMERICS_TENSOR_LEG_HPP_
#include "tensor_basic.hpp"
#include <iostream>
#include <fstream>
#include <vector>
#include "errors.hpp"
namespace exatn{
namespace numerics{
inline LegDirection reverseLegDirection(LegDirection dir){
if(dir == LegDirection::INWARD) return LegDirection::OUTWARD;
if(dir == LegDirection::OUTWARD) return LegDirection::INWARD;
return LegDirection::UNDIRECT;
}
class TensorLeg{
public:
/** Create a tensor leg by specifying the id of the connected tensor [0:*] and its corresponding dimension [0:*]. **/
TensorLeg(unsigned int tensor_id,
unsigned int dimensn_id,
LegDirection direction = LegDirection::UNDIRECT);
/** Create the tensor leg {0,0,UNDIRECT}. **/
TensorLeg();
TensorLeg(const TensorLeg &) = default;
TensorLeg & operator=(const TensorLeg &) = default;
TensorLeg(TensorLeg &&) noexcept = default;
TensorLeg & operator=(TensorLeg &&) noexcept = default;
virtual ~TensorLeg() = default;
/** Print. **/
void printIt() const;
void printItFile(std::ofstream & output_file) const;
/** Return the connected tensor id: [0..*]. **/
unsigned int getTensorId() const;
/** Return the connected tensor dimension id: [0..*]. **/
unsigned int getDimensionId() const;
/** Return the direction of the tensor leg. **/
LegDirection getDirection() const;
/** Reset the tensor leg to another connection. **/
void resetConnection(unsigned int tensor_id,
unsigned int dimensn_id,
LegDirection direction = LegDirection::UNDIRECT);
/** Reset only the tensor id in the tensor leg. **/
void resetTensorId(unsigned int tensor_id);
/** Reset only the tensor dimension id in the tensor leg. **/
void resetDimensionId(unsigned int dimensn_id);
/** Reset the direction of the tensor leg. **/
void resetDirection(LegDirection direction);
/** Reverse the direction of the tensor leg. **/
void reverseDirection();
private:
unsigned int tensor_id_; //id of the connected tensor [0..*]
unsigned int dimensn_id_; //dimension id in the connected tensor [0..*]
LegDirection direction_; //direction of the leg: {UNDIRECT, INWARD, OUTWARD}, defaults to UNDIRECT
};
/** Returns true if two vectors of tensor legs are congruent, that is,
they have the same size and direction of each tensor leg. **/
bool tensorLegsAreCongruent(const std::vector<TensorLeg> * legs0,
const std::vector<TensorLeg> * legs1);
} //namespace numerics
} //namespace exatn
#endif //EXATN_NUMERICS_TENSOR_LEG_HPP_
| true |
f501c042372703817f3727c4d74a85f4d8a5e797
|
C++
|
Iten-No-404/Snakes-and-Ladders-with-a-hint-of-Monopoly
|
/DeleteGameObjectAction.h
|
UTF-8
| 659 | 2.78125 | 3 |
[] |
no_license
|
#pragma once
#include "Action.h"
class DeleteGameObjectAction : public Action
{
// Always add action parameters as private data members
// [Action Parameters]
CellPosition PostionToDelete; // The postion of the cell whose game object will be deleted
// Note: This parameter should be read in ReadActionParameters()
public:
DeleteGameObjectAction(ApplicationManager* pApp); // A Constructor
virtual void ReadActionParameters(); // Reads DeleteGameObjectAction action parameter (PostitionToDelete)
virtual void Execute(); // Deletes any gameobject if there's one in the chosen cell
virtual ~DeleteGameObjectAction(); // Virtual Destructor
};
| true |
870b678e34bf2b6818181cba27ce90d1474d3980
|
C++
|
senli123/tensorrt-pythonv1
|
/model/classification/classification_utils.cpp
|
UTF-8
| 788 | 2.578125 | 3 |
[] |
no_license
|
#include "classification_utils.h"
bool ClassificationUtils::TopNums(std::vector<std::vector<std::pair<float, int>>> &class_index, int topnum, std::vector<image_info>& outputinfo)
{
for (int batch = 0; batch < class_index.size(); batch++)
{
std::vector<std::pair<float, int>> one_batch_class_index = class_index[batch];
std::partial_sort(one_batch_class_index.begin(), one_batch_class_index.begin() + topnum, one_batch_class_index.end(),
std::greater<std::pair<float, int>>());
image_info info;
for (int i = 0; i < topnum; i++)
{
info.indexs.push_back(one_batch_class_index[i].second);
info.scores.push_back(one_batch_class_index[i].first);
}
outputinfo.push_back(info);
}
}
| true |
0bdc3ae4181f0adc12ead9e4f5b1db5b17c0c85b
|
C++
|
quantity123/CoinFlipGame
|
/CoinFlipGame/mainwindow.cpp
|
UTF-8
| 2,797 | 2.515625 | 3 |
[] |
no_license
|
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, mWidth(320)
, mHeight(588)
, mWidget(this)
, mVBoxLayout(this)
, mMenuBar(this)
, mLevelConfig(this)
, mBackBtnMovePoint(mWidth-77, mHeight-57)
, mStartScene(this)
, mChooseLevelScene(this)
, mPlayScene(this)
{
this->setFixedSize(mWidth, mHeight);
// QDesktopWidget *desktop = QApplication::desktop();
// move((desktop->width()-this->width())*0.5, (desktop->height()-this->height())*0.5); //ubuntu需要设置主窗口在桌面中间位置
this->setWindowIcon(QIcon(":/res/Coin0001.png"));
this->setCentralWidget(&mWidget);
mWidget.setLayout(&mVBoxLayout);
mVBoxLayout.addWidget(&mMenuBar);
mVBoxLayout.addWidget(&mStartScene);
mVBoxLayout.addWidget(&mChooseLevelScene);
mVBoxLayout.addWidget(&mPlayScene);
mVBoxLayout.setMargin(0);
//设置菜单和退出
this->setMenuBar(&mMenuBar);
QMenu *startMenu = mMenuBar.addMenu("菜单");
QAction *exitAction = startMenu->addAction("退出");
auto onActionExit = [&]()
{
this->close();
};
connect(exitAction, &QAction::triggered, onActionExit);
//设置准备开始游戏场景的宽和高
mStartScene.setFixedWindowSize(mWidth, mHeight);
mChooseLevelScene.setFixedWindowSize(mWidth, mHeight);
//获取游戏一共有多少个关卡并创建关卡
uint levelCount = mLevelConfig.levelCount();
mChooseLevelScene.createLevel(levelCount);
mChooseLevelScene.setBackBtnMovePoint(mBackBtnMovePoint);
mPlayScene.setFixedWindowSize(mWidth, mHeight);
//获取行和列数量并创建硬币阵列
uint rowCount = mLevelConfig.rowCount();
uint colCount = mLevelConfig.colCount();
mPlayScene.buildCoinBtnRowArray(rowCount, colCount);
mPlayScene.setBackBtnMovePoint(mBackBtnMovePoint);
//显示准备开始游戏场景
setScene(MainWindow::SceneType::stStartScene);
}
MainWindow::~MainWindow()
{
}
void MainWindow::setScene(SceneType aSceneType)
{
switch (aSceneType)
{
case stStartScene:
mStartScene.show();
this->setWindowTitle("准备开始游戏");
break;
case stChooseLevelScene:
mChooseLevelScene.show();
this->setWindowTitle("选择游戏关卡");
break;
case stPalyScene:
mPlayScene.show();
this->setWindowTitle("游戏中");
break;
default:
this->setWindowTitle("错误的场景类型!");
break;
}
}
void MainWindow::setPlayLevel(const uchar &aLevel)
{
QLevelConfig::QLevelConfigArray levelConfigArray = mLevelConfig.levelConfigArray(aLevel);
QString sLevel = QString("%1").arg(aLevel);
mPlayScene.setPlayLevel(sLevel, levelConfigArray);
}
| true |
64930addebe32722fb955850ce9d4f9403852db6
|
C++
|
sankar96/Competitive_Programming
|
/A2OJ/Ladder/Eighteen.cpp
|
UTF-8
| 600 | 2.890625 | 3 |
[] |
no_license
|
/****
*
* Description : http://codeforces.com/problemset/problem/155/A
* Created by : Sankaranarayanan G
* Date : 2018-03-13 15:01:28
*
****/
#include <iostream>
using namespace std;
int main () {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
int maxV = arr[0];
int minV = arr[0];
int count = 0;
for (int i = 1; i < n; i++) {
if (arr[i] > maxV) {
maxV = arr[i];
count++;
} else if (arr[i] < minV) {
minV = arr[i];
count++;
}
}
cout << count;
return 0;
}
| true |
dcfa86e7d9af9edfdb35134befe4b534780c2447
|
C++
|
pqros/leetcode-exercices
|
/03LongestSubstring.cpp
|
UTF-8
| 655 | 3.203125 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int lengthOfLongestSubstring(string s) {
if (s.empty()) return 0;
int maxlen = 0;
int start = 0;
unordered_map <char, int> m;
for (int i = 0; i < s.size(); ++i) {
char c = s[i];
if (m.find(c) == m.end() || m[c] < start) {
m[c] = i;
continue;
}
maxlen = max(maxlen, i - start);
start = m[c] + 1;
m[c] = i;
}
maxlen = max(maxlen, (int)s.size() - start);
return maxlen;
}
int main(){
string s = "abcabcbb";
cout << lengthOfLongestSubstring(s) << endl;
}
| true |
66ceb93ab74d28a27931ecee72b232bb9ff56484
|
C++
|
sakshi-chauhan/CodechefCppCodes
|
/EASY/DIVIDING.cpp
|
UTF-8
| 281 | 2.609375 | 3 |
[] |
no_license
|
#include<iostream>
int main(){
long long n,c,sum=0;
std::cin>>n;
for(int i=0;i<n;i++){
std::cin>>c;
sum+=c;
}
if(sum==n*(n+1)/2)
std::cout<<"YES\n";
else
std::cout<<"NO\n";
return 0;
}
| true |
abdd77de9611ef33b7ff25877ffc22a583874909
|
C++
|
everescent/drqst
|
/Production/DragonAttack/DragonAttack/Input_Handler.cpp
|
WINDOWS-1252
| 1,502 | 2.890625 | 3 |
[] |
no_license
|
/* Start Header ************************************************************************/
/*!
\file Input_Handler.cpp
\project Dragon Attack
\author William Yoong
\par email: william.yoong\@digipen.edu
\brief
Cpp file for Input_Handler
All content 2018 DigiPen (SINGAPORE) Corporation, all rights reserved.
*/
/* End Header **************************************************************************/
#include "Input_Handler.h"
#include "Camera.h"
#include <iostream>
namespace Input {
int input[NUM_OF_KEYS] {};
const int* Get_User_Input(void)
{
using namespace Input;
memset(input, 0, sizeof(int) * NUM_OF_KEYS);
if (AEInputCheckCurr(go_right))
{
input[0] = go_right;
}
if (AEInputCheckCurr(go_left))
{
input[1] = go_left;
}
if (AEInputCheckCurr(go_up))
{
input[2] = go_up;
}
if (AEInputCheckCurr(go_down))
{
input[3] = go_down;
}
if (AEInputCheckCurr(jump_up))
{
input[4] = jump_up;
}
if (AEInputCheckTriggered(fire))
{
input[5] = fire;
}
if (AEInputCheckTriggered(special))
{
input[6] = special;
}
return input;
}
bool Quit_Triggered()
{
if (AEInputCheckTriggered(quit_game) || 0 == AESysDoesWindowExist())
{
return true;
}
return false;
}
}
| true |
1c6e2d1cbaf606b081b7e47ab61b3a117f06eca1
|
C++
|
Andydiaz12/Estructura-de-Datos-con-Muratalla
|
/Ejercicios de parciales/3 parcial/CH05_2_180416_24500468.cpp
|
ISO-8859-1
| 2,023 | 3.390625 | 3 |
[] |
no_license
|
/* Jos Andrs Daz Escobar
18 de Abril del 2016
Ahora haremos una pila un poco ms prctica. Vas a realizar un administrador de tareas para un
sistema operativo para esto necesitars almacenar dos datos: clave del proceso (entero), nombre del proceso (cadena)
y aplicacin que lo ejecuta (cadena). Lo que tendrs que hacer es presentar el siguiente men:
1. Agregar proceso.
2. Eliminar proceso.
3. Listado de procesos activos.
4. Limpiar lista de procesos.
5. Salir.
NOTAS:
Considera que mximo tienes 10 procesos disponibles.
La clave del proceso ser un entero positivo.
Recuerda que es una pila, por lo que eliminar proceso eliminars el ULTIMO introducido.
En listado de procesos imprimirs el listado de ejecucin (como si fuera la salida de la pila).
En limpiar procesos vaciars la pila y me dirs "Han sido eliminados todos los procesos".
No olvides implementar tu funcin isEmpty, es decir si te mando a limpiar o imprimir la lista y est vaca debers decrmelo.*/
#include <cstdlib>
#include <stdio.h>
#include "PILA_INICIALES.h"
int menu(){
int x;
do{
printf("1. Agregar proceso.\n2. Eliminar proceso.\n3. Listado de procesos activos.\n4. Limpiar lista de procesos.\n5. Salir.\n");
printf("\n\tIngrese la opcion deseada:\t");
scanf("%d", &x);
if(x < 1 || x > 5)
printf("Opcion del menu invalida\n");
}while(x < 1 || x > 5);
return x;
}
float valor(){
float x;
printf("Ingrese el dato:\t");
scanf("%f", &x);
return x;
}
int main(){
float arr[10], VALOR;
int MENU, LLENO, VACIO, TOPE=0;
do{
MENU=menu();
switch(MENU){
case 1:
LLENO=lleno(TOPE);
if(LLENO == 0){
VALOR=valor();
TOPE=push(VALOR, &arr, TOPE);
}
break;
case 2:
VACIO=vacio(TOPE);
if(VACIO == 0)
TOPE=pop(&arr, TOPE);
break;
case 3:
recorrido(&arr, TOPE);
break;
case 4:
TOPE=inicializar_tope(TOPE);
break;
}
}while(MENU != 5);
system("PAUSE");
return 0;
}
| true |
cdb7a60874fdaa7afabe1b940f2b6a6987e9a222
|
C++
|
Mikhaelyes/4-semester
|
/2sem/vector2D.h
|
UTF-8
| 1,291 | 2.8125 | 3 |
[] |
no_license
|
class Vector2D
{
double x, y;
public:
Vector2D();
Vector2D(double x);
Vector2D(double x, double y);
double get_x();
double get_y();
void set_x(double x);
void set_y(double y);
Vector2D *plus(Vector2D *A);
Vector2D *minus(Vector2D *A);
double mod();
friend double mod(Vector2D &A);
friend Vector2D operator+ (Vector2D &A, Vector2D &B);
friend Vector2D operator- (Vector2D &A, Vector2D &B);
friend double operator* (Vector2D &A, Vector2D &B);
friend Vector2D operator* (Vector2D &A, double n);
friend Vector2D operator* (double n, Vector2D &A);
friend Vector2D operator++ (Vector2D &A, int x);
friend Vector2D operator-- (Vector2D &A, int x);
friend Vector2D operator++ (Vector2D &A);
friend Vector2D operator-- (Vector2D &A);
friend Vector2D operator+ (Vector2D &A);
friend Vector2D operator- (Vector2D &A);
friend bool operator== (Vector2D &A, Vector2D &B);
friend bool operator!= (Vector2D &A, Vector2D &B);
friend bool operator> (Vector2D &A, Vector2D &B);
friend bool operator< (Vector2D &A, Vector2D &B);
friend bool operator>= (Vector2D &A, Vector2D &B);
friend bool operator<= (Vector2D &A, Vector2D &B);
friend std::ostream &operator << (std::ostream &out, Vector2D &B);
friend Vector2D &operator >> (std::istream &out, Vector2D &B);
};
| true |
a1479dbc0fd7b14651a351ad15662ae2817e218b
|
C++
|
xiaoruiwei1998/XRW
|
/swarm.cpp
|
UTF-8
| 7,081 | 2.578125 | 3 |
[] |
no_license
|
#include<iostream>
#include<time.h>
#include<stdlib.h>
#include<cmath>
#include<fstream>
#include<iomanip>
#include "benchmark.h"
#include "Algorithm.h"
using namespace std;
/*******主函数*******/
int main()
{
/*
ofstream output;
output.open("dataABC.txt");
*/
srand((unsigned)time(NULL));
initilize();//初始化
MemorizeBestSource();//保存最好的蜜源
//主要的循环
int gen=0;
while(gen<maxCycle)
{
sendEmployedBees();
CalculateProbabilities();
sendOnlookerBees();
MemorizeBestSource();
sendScoutBees();
MemorizeBestSource();
//output<<setprecision(30)<<BestSource.fitness<<endl;
gen++;
}
//output.close();
cout<<"运行结束!!"<<endl;
return 0;
}
/*****函数的实现****/
double random(double start, double end)//随机产生区间内的随机数
{
return start+(end-start)*rand()/(RAND_MAX + 1.0);
}
void initilize()//初始化参数
{
int i,j;
for (i=0;i<FoodNumber;i++)
{
for (j=0;j<D;j++)
{
NectarSource[i].dim[j]=random(LOWBOUND[j],UPBOUND[j]);
EmployedBee[i].dim[j]=NectarSource[i].dim[j];
OnLooker[i].dim[j]=NectarSource[i].dim[j];
BestSource.dim[j]=NectarSource[0].dim[j];
}
/****蜜源的初始化*****/
NectarSource[i].fitness=calculationfitness(NectarSource[i]);
NectarSource[i].F=calculationF(NectarSource[i].fitness);
NectarSource[i].CR=0;
NectarSource[i].trail=0;
/****采蜜蜂的初始化*****/
EmployedBee[i].fitness=NectarSource[i].fitness;
EmployedBee[i].F=NectarSource[i].F;
EmployedBee[i].CR=NectarSource[i].CR;
EmployedBee[i].trail=NectarSource[i].trail;
/****观察蜂的初始化****/
OnLooker[i].fitness=NectarSource[i].fitness;
OnLooker[i].F=NectarSource[i].F;
OnLooker[i].CR=NectarSource[i].CR;
OnLooker[i].trail=NectarSource[i].trail;
}
/*****最优蜜源的初始化*****/
BestSource.fitness=NectarSource[0].fitness;
BestSource.F=NectarSource[0].F;
BestSource.CR=NectarSource[0].CR;
BestSource.trail=NectarSource[0].trail;
}
double calculationfitness(individual bee)//计算真实的函数值
{
double fitness=0;
/******测试函数1******/
return fitness;
}
double calculationF(double fitness)//计算适应值
{
double FResult=0;
if (fitness>=0)
{
FResult=1/(fitness+1);
}
else
{
FResult=1+abs(fitness);
}
return FResult;
}
void sendEmployedBees()//修改采蜜蜂的函数
{
int i,j,k;
int param2change;//需要改变的维数
double Rij;//[-1,1]之间的随机数
for (i=0;i<FoodNumber;i++)
{
param2change=(int)random(0,D);//随机选取任意一维需要改变的维数
/******选取不等于i的k********/
while (1)
{
k=(int)random(0,FoodNumber);
if (k!=i)
break;
}
for (j=0;j<D;j++)
{
EmployedBee[i].dim[j]=NectarSource[i].dim[j];//一组解向量置为相等
}
/*******采蜜蜂去更新信息*******/
Rij=random(-1,1);
EmployedBee[i].dim[param2change]=NectarSource[i].dim[param2change]+Rij*(NectarSource[i].dim[param2change]-NectarSource[k].dim[param2change]);
/*******判断是否越界********/
if (EmployedBee[i].dim[param2change]>UPBOUND[param2change])
{
EmployedBee[i].dim[param2change]=UPBOUND[param2change];
}
if (EmployedBee[i].dim[param2change]<LOWBOUND[param2change])
{
EmployedBee[i].dim[param2change]=LOWBOUND[param2change];
}
EmployedBee[i].fitness=calculationfitness(EmployedBee[i]);
EmployedBee[i].F=calculationF(EmployedBee[i].fitness);
/******贪婪选择策略*******/
if (EmployedBee[i].fitness<NectarSource[i].fitness)
{
for (j=0;j<D;j++)
{
NectarSource[i].dim[j]=EmployedBee[i].dim[j];
}
NectarSource[i].trail=0;
NectarSource[i].fitness=EmployedBee[i].fitness;
NectarSource[i].F=EmployedBee[i].F;
}else
{
NectarSource[i].trail++;
}
}
}
void CalculateProbabilities()//计算轮盘赌的选择概率(选择策略可以不同,比如p = fit[i]/fit[1]+...+fit[n])
{
int i;
double maxfit;
maxfit=NectarSource[0].F;
for (i=1;i<FoodNumber;i++)
{
if (NectarSource[i].F>maxfit)
maxfit=NectarSource[i].F;
}
for (i=0;i<FoodNumber;i++)
{
NectarSource[i].CR=(0.9*(NectarSource[i].F/maxfit))+0.1;//???
}
}
void sendOnlookerBees()//采蜜蜂与观察蜂交流信息,观察蜂更改信息
{
int i,j,t,k;
double R_choosed;//被选中的概率
int param2change;//需要被改变的维数
double Rij;//[-1,1]之间的随机数
i=0;
t=0;
while(t<FoodNumber)
{
R_choosed=random(0,1);
if(R_choosed<NectarSource[i].CR)//根据被选择的概率选择
{
t++;
param2change=(int)random(0,D);
/******选取不等于i的k********/
while (1)
{
k=(int)random(0,FoodNumber);
if (k!=i)
{
break;
}
}
for(j=0;j<D;j++)
{
OnLooker[i].dim[j]=NectarSource[i].dim[j];
}
/****更新******///在已有解空间code[i]~code[k]附近求解
Rij=random(-1,1);
OnLooker[i].dim[param2change]=NectarSource[i].dim[param2change]+Rij*(NectarSource[i].dim[param2change]-NectarSource[k].dim[param2change]);
/*******判断是否越界*******/
if (OnLooker[i].dim[param2change]<LOWBOUND[param2change])
{
OnLooker[i].dim[param2change]=LOWBOUND[param2change];
}
if (OnLooker[i].dim[param2change]>UPBOUND[param2change])
{
OnLooker[i].dim[param2change]=UPBOUND[param2change];
}
OnLooker[i].fitness=calculationfitness(OnLooker[i]);
OnLooker[i].F=calculationF(OnLooker[i].fitness);
/****贪婪选择策略******/
if (OnLooker[i].fitness<NectarSource[i].fitness)
{
for (j=0;j<D;j++)
{
NectarSource[i].dim[j]=OnLooker[i].dim[j];
}
NectarSource[i].trail=0;
NectarSource[i].fitness=OnLooker[i].fitness;
NectarSource[i].F=OnLooker[i].F;
}else
{
NectarSource[i].trail++;
}
}
i++;
if (i==FoodNumber)
{
i=0;
}
}
}
/*******只有一只侦查蜂**********/
void sendScoutBees()//判断是否有侦查蜂的出现,有则重新生成蜜源(侦查蜂只有在试验次数>limit时出现)
{
int maxtrialindex,i,j;
double R;//[0,1]之间的随机数
//maxtrialindex=0;
for (i=0;i<FoodNumber;i++)
{
if(NectarSource[maxtrialindex].trail>=limit)//从循环外搬到循环内,防止该组数据中有一个以上试验次数超过limit的蜜源
{
/*******重新初始化*********/
for (j=0;j<D;j++)
{
R=random(0,1);
NectarSource[maxtrialindex].dim[j]=LOWBOUND[j]+R*(UPBOUND[j]-LOWBOUND[j]);
}
NectarSource[maxtrialindex].trail=0;
NectarSource[maxtrialindex].fitness=calculationfitness(NectarSource[maxtrialindex]);
NectarSource[maxtrialindex].F=calculationF(NectarSource[maxtrialindex].fitness);
}
}
}
void MemorizeBestSource()//保存最优的蜜源
{
int i,j;
for (i=1;i<FoodNumber;i++)
{
if (NectarSource[i].fitness<BestSource.fitness)
{
for (j=0;j<D;j++)
{
BestSource.dim[j]=NectarSource[i].dim[j];
}
BestSource.fitness=NectarSource[i].fitness;
}
}
}
| true |
1389f27cf2a322bae8b4d753a8025fc61d149f3a
|
C++
|
thanhvietgl/lthdt-18clc6-18127252
|
/18127252_w07_03/Ball/function.cpp
|
UTF-8
| 190 | 2.5625 | 3 |
[] |
no_license
|
#include "Header.h"
Ball* Ball::instance = nullptr;
Ball* Ball::getInstance()
{
if (!instance)
instance = new Ball;
return instance;
}
void Game::play()
{
cout << "Ready!" << endl;
}
| true |
045b2a1515a2bd83ce36d3104f06952a1553c71a
|
C++
|
alok0366/Programs
|
/cpp/copytemplate.cpp
|
UTF-8
| 899 | 3.234375 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
template<class T>
class vector
{
T v[3];
public:
vector(){
for(int i=0;i<3;i++)
v[i]=0;
}
vector(T* a)
{
for(int i=0;i<3;i++)
v[i]=a[i];
}
T operator*(vector &y)
{
T sum=0;
for(int i=0;i<3;i++)
sum=sum+v[i]*y.v[i];
return sum;
}
void display()
{
for(int i=0;i<3;i++)
cout<<v[i]<<"\t";
cout<<"\n";
}
};
int main(){
int x[3]={1,2,3};
int y[3]={4,5,6};
vector<int>v1;
vector<int>v2;
v1=x;
v2=y;
cout<<"v1"<<" ";
v1.display();
cout<<"v2"<<" ";
v2.display();
cout<<"v1*v2="<<v1*v2;
return 0;
}
| true |
4215568f17353d1813db7c7b95c86d317d0b25e1
|
C++
|
WireCell/wire-cell-gen
|
/inc/WireCellGen/Fourdee.h
|
UTF-8
| 2,064 | 2.578125 | 3 |
[] |
no_license
|
#ifndef WIRECELL_FOURDEE_H
#define WIRECELL_FOURDEE_H
#include "WireCellIface/IApplication.h"
#include "WireCellIface/IConfigurable.h"
#include "WireCellIface/IDepoSource.h"
#include "WireCellIface/IDepoFilter.h"
#include "WireCellIface/IDrifter.h"
#include "WireCellIface/IDuctor.h"
#include "WireCellIface/IFrameSource.h"
#include "WireCellIface/IFrameFilter.h"
#include "WireCellIface/IFrameSink.h"
#include "WireCellUtil/Configuration.h"
namespace WireCell {
namespace Gen {
/**
Fourdee is a Wire Cell Toolkit application class which
handles a chain of "the 4 D's": deposition, drifting,
"ducting" (induction response) and digitization. There is
an optional "5th D": "dissonance" which provides a source
of noise to be summed.
Each step provided by a model implemented as an instance of the
associated component class. A final sink is also provided if
the digitization output is provided.
*/
class Fourdee : public WireCell::IApplication, public WireCell::IConfigurable {
public:
Fourdee();
virtual ~Fourdee();
virtual void execute();
virtual void execute_old();
virtual void execute_new();
virtual void configure(const WireCell::Configuration& config);
virtual WireCell::Configuration default_configuration() const;
private:
WireCell::IDepoSource::pointer m_depos; // required
WireCell::IDepoFilter::pointer m_depofilter; // optional
WireCell::IDrifter::pointer m_drifter; // optional, but likely
WireCell::IDuctor::pointer m_ductor; // effectively required
WireCell::IFrameSource::pointer m_dissonance; // optional
WireCell::IFrameFilter::pointer m_digitizer; // optional
WireCell::IFrameFilter::pointer m_filter; // optional
WireCell::IFrameSink::pointer m_output; // optional
};
}
}
#endif
| true |
f0b355ec597bcae99230f5e942bae697b6ab551b
|
C++
|
tkalani/CodeChef
|
/April Challenge 2019/KLPM.cpp
|
UTF-8
| 1,064 | 3.546875 | 4 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
bool isPalindrome(string str)
{
int l = 0;
int h = str.length() - 1;
while (h > l)
{
if (str[l++] != str[h--])
{
return false;
}
}
return true;
}
int SECONDSUBSTR(string S, int start, string first_substr)
{
string tempS = S.substr(start, S.length());
int length = tempS.length(), count = 0;
for (int i = 0; i < length; i++)
{
for (int len = 1; len <= length - i; len++)
{
string second_substr = tempS.substr(i, len);
if(isPalindrome(first_substr+second_substr))
count++;
}
}
return count;
}
int main()
{
string S;
cin >> S;
int length = S.length();
int count=0;
for(int i=0; i<=length-2; i++)
{
for(int len_i=1; len_i<=length-i-1; len_i++)
{
string first_substr = S.substr(i, len_i);
count += SECONDSUBSTR(S, i+len_i, first_substr);
}
}
cout << count << endl;
}
| true |
4365ff68f3af4476ef83fceabced03ef834a44da
|
C++
|
eduardoschk/QT-2DCad
|
/src/command/CommandCreateArc.cpp
|
UTF-8
| 2,145 | 2.875 | 3 |
[] |
no_license
|
#include "CommandCreateArc.h"
#include "Data.h"
#include "File.h"
#include "ArcShape.h"
#include "Coordinate.h"
#include "UserInterface.h"
void CommandCreateArc::exec(Data& data,UserInterface& ui)
{
if (data.hasFile()) {
id= data.getCurrentFile().generateIdShape();
ui.markArcOptionAsSelected();
ui.setTipMessage("Select the center point of the circle, after, select the initial point to draw and this point will be your radius default, with the mouse down move to draw your arc");
}
else
ui.markOffAllOptions();
}
///////////////////////////////////////////////////////////////////////////////
void CommandCreateArc::posMousePress(Coordinate& coordinate,Data& data,UserInterface& ui)
{
auto dataViewController= data.getCurrentFile().getDataViewController();
if (center.isNull())
center= dataViewController.repairCoordinateViewToWorld(coordinate);
else
initial= dataViewController.repairCoordinateViewToWorld(coordinate);
ui.activateMouseTracking();
}
void CommandCreateArc::posMouseMove(Coordinate& coordinate,Data& data,UserInterface& ui)
{
auto dataViewController= data.getCurrentFile().getDataViewController();
if (!initial.isNull()) {
final= dataViewController.repairCoordinateViewToWorld(coordinate);
draw(ui,dataViewController,ArcShape(id,center,initial,final));
}
}
void CommandCreateArc::posMouseRelease(Coordinate& coordinate,Data& data,UserInterface& ui)
{
auto dataViewController= data.getCurrentFile().getDataViewController();
if (!final.isNull()) {
final= dataViewController.repairCoordinateViewToWorld(coordinate);
Shape& arc= saveShapeOnFile(data);
draw(ui,dataViewController,arc);
}
}
///////////////////////////////////////////////////////////////////////////////
void CommandCreateArc::prepareToNewDraw(Data& data)
{
center= initial= final= Coordinate();
id= data.getCurrentFile().generateIdShape();
}
Shape& CommandCreateArc::saveShapeOnFile(Data& data)
{
ArcShape* arc= new ArcShape(id,center,initial,final);
data.getCurrentFile().addShapeOnFile(arc);
prepareToNewDraw(data);
return *arc;
}
| true |
457a25f1f68b480d1a3433046a8ce3928cfcf350
|
C++
|
rafa7loza/computer_networks_lab
|
/proyecto_final/includes/ICMPv4.h
|
UTF-8
| 487 | 2.5625 | 3 |
[] |
no_license
|
#ifndef ICMPV4_H
#define ICMPV4_H
#include <iostream>
#include <string>
// ICMPv4 Protocol
#define ICMPV4_TYPE "icmpv4_type"
#define ICMPV4_CODE "icmpv4_code"
#define ICMPV4_CHECKSUM "icmpv4_checksum"
#define ICMPV4_OTHER "icmpv4_other"
using namespace std;
class ICMPv4{
public:
ICMPv4();
ICMPv4(string data);
void showData();
private:
string type;
int errorCode;
string checksum;
string otherFields;
void initField(string field, string representation);
};
#endif
| true |
4e2379ceccb00a149cea278dab140a2d4b12ce14
|
C++
|
IliyaKarkamov/Warrior
|
/Warrior/Warrior.Engine/src/Graphics/OpenGL/Program.cpp
|
UTF-8
| 3,494 | 2.65625 | 3 |
[] |
no_license
|
#include "Engine/Graphics/OpenGL/Program.h"
#include "Engine/Graphics/OpenGL/Shader.h"
#include "Utils/ErrorHandler.h"
#include "Engine/Core.h"
#include <GL/glew.h>
namespace WarriorEngine::Graphics::OpenGL
{
Program::Program() noexcept { GL_CALL(id_ = glCreateProgram()); }
Program::Program(const Shader& vertex, const Shader& fragment) noexcept
{
GL_CALL(id_ = glCreateProgram());
attach(vertex);
attach(fragment);
link();
}
Program::~Program() noexcept { destroy(); }
Program::Program(Program&& other) noexcept
{
id_ = other.id_;
other.id_ = 0u;
}
Program& Program::operator=(Program&& other) noexcept
{
if (id_ != other.id_)
{
destroy();
id_ = other.id_;
other.id_ = 0u;
}
return *this;
}
void Program::destroy() const noexcept
{
if (id_ == 0u)
return;
GL_CALL(glDeleteProgram(id_));
}
void Program::attach(const Shader& shader) const noexcept
{
GL_CALL(glAttachShader(id_, static_cast<unsigned int>(shader)));
}
void Program::link() const noexcept
{
GLint linkStatus;
glLinkProgram(id_);
glGetProgramiv(id_, GL_LINK_STATUS, &linkStatus);
if (linkStatus == GL_FALSE)
WE_ENGINE_ERROR("[OpenGL error]: Program linking failed: %s", getInfoLog().c_str());
}
void Program::bind() const noexcept { GL_CALL(glUseProgram(id_)); }
void Program::unbind() const noexcept { GL_CALL(glUseProgram(0u)); }
int Program::getAttributeLocation(const std::string& name) const noexcept
{
GL_CALL(const auto location = glGetAttribLocation(id_, name.c_str()));
return location;
}
int Program::getUniformLocation(const std::string& name) const noexcept
{
if (const auto it = uniformLocationCache_.find(name); it != uniformLocationCache_.end())
return it->second;
GL_CALL(const auto location = glGetUniformLocation(id_, name.c_str()));
uniformLocationCache_[name] = location;
return location;
}
void Program::setUniform(const std::string& name, const int value) const noexcept
{
GL_CALL(glUniform1i(getUniformLocation(name), value));
}
void Program::setUniform(const std::string& name, const float value) const noexcept
{
GL_CALL(glUniform1f(getUniformLocation(name), value));
}
void Program::setUniform(const std::string& name, const glm::vec2& value) const noexcept
{
GL_CALL(glUniform2f(getUniformLocation(name), value.x, value.y));
}
void Program::setUniform(const std::string& name, const glm::vec3& value) const noexcept
{
GL_CALL(glUniform3f(getUniformLocation(name), value.x, value.y, value.z));
}
void Program::setUniform(const std::string& name, const glm::vec4& value) const noexcept
{
GL_CALL(glUniform4f(getUniformLocation(name), value.x, value.y, value.z, value.w));
}
void Program::setUniform(const std::string& name, const glm::mat3& value) const noexcept
{
GL_CALL(glUniformMatrix3fv(getUniformLocation(name), 1, GL_FALSE, &value[0][0]));
}
void Program::setUniform(const std::string& name, const glm::mat4& value) const noexcept
{
GL_CALL(glUniformMatrix4fv(getUniformLocation(name), 1, GL_FALSE, &value[0][0]));
}
std::string Program::getInfoLog() const noexcept
{
GLint logLength;
GL_CALL(glGetProgramiv(id_, GL_INFO_LOG_LENGTH, &logLength));
if (logLength > 0)
{
std::string infoLog(logLength, 0);
GL_CALL(glGetProgramInfoLog(id_, logLength, &logLength, &infoLog[0]));
return infoLog;
}
return "";
}
} // namespace WarriorEngine::Graphics::OpenGL
| true |
2e93ebdc86ce9898f56dddfbd33f7b7bcc91ac4f
|
C++
|
fpga-tom/pcb_sat
|
/Circuit.cpp
|
UTF-8
| 521 | 2.578125 | 3 |
[] |
no_license
|
//
// Created by tomas on 12/26/18.
//
#include "Circuit.h"
namespace solg {
namespace circuit {
bool operator==(const edge_t &a, const edge_t &b) {
return a == b;
}
bool operator==(const node_t &a, const node_t &b) {
return a == b;
}
bool operator<(const node_t &a, const node_t &b) {
return a < b;
}
edge_t operator+(const node_t &a, const node_t &b) {
return edge_t(new edge_s(a, b));
}
}
}
| true |
f4582086ac1cab203bac7bf0a3d457aed633a07d
|
C++
|
teju85/teditor
|
/src/core/lrucache.hpp
|
UTF-8
| 2,097 | 3.53125 | 4 |
[
"WTFPL"
] |
permissive
|
#pragma once
#include <unordered_map>
namespace teditor {
/**
* @brief LRU Cache implementation
* @tparam K key type
* @tparam V value type
*/
template <typename K, typename V>
class LRUCache {
public:
/**
* @brief ctor
* @param c capacity of the cache
*/
LRUCache(size_t c) : objs(), cap(c), head(nullptr), tail(nullptr) {}
bool exists(const K& k) const { return objs.find(k) != objs.end(); }
size_t capacity() const { return cap; }
size_t size() const { return objs.size(); }
/**
* @brief Gets value at the given key and if the key does not exist it returns
* a default value object
*/
V& get(const K& k) {
auto itr = objs.find(k);
if (itr == objs.end()) {
put(k, V());
itr = objs.find(k);
}
auto& node = itr->second;
make_recent(&node);
return node.value;
}
/** puts a new element into the cache */
void put(const K& k, const V& v) {
if (objs.size() >= cap) remove_tail();
auto itr = objs.find(k);
if (itr == objs.end()) {
Node n;
n.key = k;
n.prev = n.next = nullptr;
objs[k] = n;
itr = objs.find(k);
}
auto& node = itr->second;
node.value = v;
make_recent(&node);
}
private:
struct Node {
K key;
V value;
Node *prev, *next;
Node() {}
}; // struct Node
std::unordered_map<K, Node> objs;
size_t cap;
// together represent a non-allocating doubly linked list
Node *head, *tail;
void make_recent(Node* val) {
if (head == val) return;
if (tail == val) {
tail = tail->prev;
tail->next = nullptr;
} else {
if (val->prev != nullptr) val->prev->next = val->next;
if (val->next != nullptr) val->next->prev = val->prev;
}
val->prev = nullptr;
val->next = head;
if (head != nullptr) head->prev = val;
head = val;
if (tail == nullptr) tail = head;
}
void remove_tail() {
if (tail == nullptr) return;
const K& key = tail->key;
objs.erase(key);
tail = tail->prev;
tail->next = nullptr;
}
}; // class LRUCache
} // namespace teditor
| true |
047df7f9eb4012a1c16491f81b3b5085312f976c
|
C++
|
nicosuarez/pacmantaller
|
/client/src/Camara.cpp
|
UTF-8
| 3,953 | 3.171875 | 3 |
[] |
no_license
|
#include "Camara.h"
#include <iostream>
using namespace std;
Camara::Camara():posOjo(0,0,0),posCentro(0,0,0),dirArriba(0,1,0){
}
Camara::Camara(Coordenada posOjo,Coordenada posCentro ,Coordenada dirArriba): posOjo(posOjo),posCentro(posCentro),dirArriba(dirArriba) {
cSpeed = 0.5;//mientras mas alto mas velocidad de la camara: "mas rapido llego de una posicion a otra".
rSpeed = 45;
}
Camara::~Camara(){
}
void Camara::setSpeed(float speed) {
cSpeed = speed;
}
void Camara::setOjo(Coordenada pos) {
posOjo.x= pos.x;
posOjo.y= pos.y;
posOjo.z= pos.z;
}
void Camara::setCentro(Coordenada pos) {
posCentro.x= pos.x;
posCentro.y= pos.y;
posCentro.z= pos.z;
}
void Camara::setArriba(Coordenada pos) {
dirArriba.x= pos.x;
dirArriba.y= pos.y;
dirArriba.z= pos.z;
}
Coordenada Camara::getOjo() {
return posOjo;
}
Coordenada Camara::getCentro() {
return posCentro;
}
Coordenada Camara::getArriba() {
return dirArriba;
}
//realiza calculo para mover la camara
int Camara::move(float dir) { //dir =1 ADELANTE dir=-1 ATRAS
Coordenada vDir;
vDir = posCentro - posOjo;// x o y se haran cero
//if (vDir.x<0) vDir.x = - vDir.x;
//if (vDir.z<0) vDir.z = - vDir.z;
posOjo.x= posOjo.x + vDir.x * (dir * cSpeed);
posOjo.z= posOjo.z + vDir.z * (dir * cSpeed);
posCentro.x=posCentro.x + vDir.x * (dir * cSpeed);
posCentro.z=posCentro.z + vDir.z * (dir * cSpeed);
return 0;
}
int Camara::moverAdelante() {
Coordenada vDir = posCentro - posOjo;// x o y se haran cero
posOjo.x= posOjo.x + vDir.x * cSpeed;
posOjo.z= posOjo.z + vDir.z * cSpeed;
posCentro.x=posCentro.x + vDir.x * cSpeed;
posCentro.z=posCentro.z + vDir.z * cSpeed;
return 0;
}
/*void Camara::rotate(float droot) {//dir =1 DERECHA dir=-1 IZQUIERDA
//posCentro.z=(float)(posOjo.z+ sin(rSpeed*droot )*vDir.x + cos(rSpeed*droot )*vDir.z);
//posCentro.x=(float)(posOjo.x+ cos(rSpeed*droot )*vDir.x - sin(rSpeed*droot )*vDir.z);
//Coordenada vDir = posCentro-posOjo;
Coordenada vDir;
vDir.x= posCentro.x - posOjo.x;
vDir.z= posCentro.z - posOjo.z;
if (vDir.x<0) vDir.x = - vDir.x;
if (vDir.z<0) vDir.z = - vDir.z;
cout<<"vDir "<<vDir.x<<" "<<vDir.z<<endl;
cout<<"ojo rotate x antes= "<<posOjo.x<<endl;
cout<<"ojo rotate z antes= "<<posOjo.z<<endl;
cout<<"Centro rotate x antes= "<<posCentro.x<<endl;
cout<<"Centro rotate z antes= "<<posCentro.z<<endl;
posCentro.x=posOjo.x + vDir.z * droot;
posCentro.z=posOjo.z - vDir.x * droot;
cout<<"Centro rotate x= "<<posCentro.x<<endl;
cout<<"Centro rotate z= "<<posCentro.z<<endl<<endl;
}
*/
void Camara::moverIzq() {
Coordenada vDir=posCentro-posOjo;
if (vDir.z==0) {
posCentro.x=posOjo.x - vDir.z;
posCentro.z=posOjo.z - vDir.x;
}
else {
posCentro.x=posOjo.x + vDir.z;
posCentro.z=posOjo.z + vDir.x;
}
}
void Camara::moverDer() {
Coordenada vDir=posCentro-posOjo;
if (vDir.z==0) {
posCentro.x=posOjo.x + vDir.z;
posCentro.z=posOjo.z + vDir.x;
}
else {
posCentro.x=posOjo.x - vDir.z;
posCentro.z=posOjo.z - vDir.x;
}
}
void Camara::rotateUp(float droot) {
posCentro.y=posCentro.y + rSpeed*1*droot;
}
void Camara::strafeUp(float droot) {
posOjo.y=posOjo.y + cSpeed*0.5*droot;
posCentro.y=posOjo.y;
}
void Camara::update() {
glLoadIdentity();//antes que nada se inicializa la matriz a la identidad
//gluLookAt define dónde esta el observador, hacia donde esta mirando y cual es el eje que nos indica la dirección hacia arriba.
//gluPerspective(45,(GLfloat)width/(GLfloat)height, 0.01, 100);
//gluLookAt(camera[0],camera[1],camera[2],target[0],target[1],target[2],0,1,0);
gluLookAt(posOjo.x,posOjo.y,posOjo.z,posCentro.x,posCentro.y,posCentro.z,dirArriba.x,dirArriba.y,dirArriba.z);
}
void Camara::vistaAerea(int alto, int ancho) {
posOjo.x=ancho;
posOjo.y=(alto+ancho)*2;
posOjo.z=-alto;
posCentro.x=ancho;
posCentro.y= (alto+ancho)*2 - 5;
posCentro.z=-alto;
dirArriba.x=1;
dirArriba.y=0;
dirArriba.z=0;
}
| true |