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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
6f019723c914bd24063d6b4911339c206a6dc829 | C++ | kamalsirsa/vtp | /TerrainSDK/vtlib/core/Contours.h | UTF-8 | 2,192 | 2.625 | 3 | [
"MIT"
] | permissive | //
// Contours.h
//
// Copyright (c) 2004-2009 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#ifndef CONTOURSH
#define CONTOURSH
#if SUPPORT_QUIKGRID
#include "Terrain.h"
class SurfaceGrid;
/** \defgroup utility Utility classes
*/
/*@{*/
/**
* This class provides the ability to easily construct contour lines
* on a terrain. It does so by calling the QuikGrid library to generate
* contour vectors, then converts those vectors into 3D line geometry
* draped on the terrain.
*
* \par Here is an example of how to use it:
\code
vtContourConverter cc;
cc.Setup(pTerrain, RGBf(1,1,0), 10);
cc.GenerateContours(100);
cc.Finish();
\endcode
*
* \par Or, you can generate specific contour lines:
\code
vtContourConverter cc;
cc.Setup(pTerrain, RGBf(1,1,0), 10);
cc.GenerateContour(75);
cc.GenerateContour(125);
cc.GenerateContour(250);
cc.Finish();
\endcode
*
* \par If you keep a pointer to the geometry, you can toggle or delete it later:
\code
vtContourConverter cc;
vtGeode *geode = cc.Setup(pTerrain, RGBf(1,1,0), 10);
[...]
geom->SetEnabled(bool); // set visibility
[...]
pTerrain->GetScaledFeatures()->RemoveChild(geom);
geom->Release(); // delete
\endcode
*/
class vtContourConverter
{
public:
vtContourConverter();
~vtContourConverter();
// There are two ways to use the converter:
/// Setup to generate geometry directly on a terrain
vtGeode *Setup(vtTerrain *pTerr, const RGBf &color, float fHeight);
/// Setup to generate line features
bool Setup(vtTerrain *pTerr, vtFeatureSetLineString *fset);
void GenerateContour(float fAlt);
void GenerateContours(float fAInterval);
void Finish();
void Coord(float x, float y, bool bStart);
protected:
bool SetupTerrain(vtTerrain *pTerr);
void Flush();
SurfaceGrid *m_pGrid;
vtTerrain *m_pTerrain;
vtHeightFieldGrid3d *m_pHF;
DRECT m_ext;
DPoint2 m_spacing;
float m_fAltitude;
float m_fHeight;
DLine2 m_line;
// These are used if building geometry directly
vtGeode *m_pGeode;
vtGeomFactory *m_pMF;
// This is used if building line features
vtFeatureSetLineString *m_pLS;
};
/*@}*/ // utility
#endif // SUPPORT_QUIKGRID
#endif // CONTOURSH
| true |
458bbf46f6c53f59e33db55036972e12a2a59157 | C++ | StetsonMathCS/SPAMM | /room.cpp | UTF-8 | 3,461 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <sstream>
#include "room.h"
#include "common.h"
#include "database.h"
using namespace std;
Room::Room(string t, string d){
title = t;
desc = d;
roomId = -1;
requirement == "No Req";
startingRoom = false;
}
Room::Room(string t, string d, string r){
title = t;
desc = d;
roomId = -1;
requirement = r;
}
void Room::save(){
string temp;
if(roomId == -1){
string north = getAdjacent("north")->getTitle();
string south = getAdjacent("south")->getTitle();
string east = getAdjacent("east")->getTitle();
string west = getAdjacent("west")->getTitle();
roomId = db->lastid;
stringstream converter;
bool b = isStartingRoom();
converter << boolalpha << b;
temp = "room \n title:"+getTitle()+"\n"+"desc:"+getDesc()+"\n"+converter.str()+"\n"+"north"+north+"\n"+"south"+south+"\n"+"east"+east+"\n"+"west"+west+"\n";
db->write(to_string(roomId),temp);
db->increment_lastid();
db->addRoom(this);
}
}
string Room::getRequirement() const {
return requirement;
}
string Room::getTitle() const {
return title;
}
string Room::getDesc() const {
return desc;
}
void Room::setAdjacent(string s, Room *r) {
exits[s] = r;
}
Room *Room::getAdjacent(string s) {
if(exits.find(s) != exits.end()) {
return exits[s];
} else {
return NULL;
}
}
map<string, Room*> Room::getExits() const {
return exits;
}
void Room::addItemToFloor(Item* item) {
floor.insert(item);
}
void Room::dropItemFromFloor(Item* item) {
floor.erase(item);
}
set<Item*> Room::getFloor() const {
return floor;
}
set<Item*> Room::getItems() const {
return floor;
}
Item* Room::findItemOnFloor(std::string name) const {
set<Item*>::const_iterator p;
for(p = floor.begin(); p != floor.end(); p++) {
if ((*p)->getName() == name) {
return *p;
}
}
cout << "ERROR: Item not found." << endl;
return NULL;
}
void Room::listItemsOnFloor() const {
set<Item*>::const_iterator p;
cout << "You scan the room and try to find anything useful." << endl;
/*
if (roomSet.size() == 0) {
cout << "There are no useful items in this room." << endl;
} else {
cout << "You can make out the faint out lines of the following items: " << endl;
for (p = floor.begin(); p != floor.end(); p++){
cout << (*p)->getName() << endl;
}
}
*/
}
void Room::setReq(string req)
{
string title = this->getTitle();
string description = this->getDesc();
Room(title, description, req);
}
void Room::setDesc(string description)
{
string req = this->getRequirement();
string title = this->getTitle();
if(roomhaveReq())
{
Room(title, description, req);
}
else
{
Room(title, description);
}
}
void Room::setreqMove(string oldroom, string req, string newroom)
{
if(this->roomhaveReq())
{
}
}
void Room::setChance(string oldRoom, double chance, string newroom)
{
}
bool Room::roomhaveReq()
{
if(this->getRequirement() == "No Req")
{
return false;
}
else
{
return true;
}
}
void Room::setStartingRoom(bool b) {
startingRoom = b;
}
bool Room::isStartingRoom() const {
return startingRoom;
}
| true |
efe9c0dfbb196556d6a3c789c861de4d038ad5f0 | C++ | andrinux/miniCppSTL | /ExtString.h | UTF-8 | 181 | 2.515625 | 3 | [] | no_license | //Implementation of String
#ifndef _EXT_STRING_H
#define _EXT_STRING_H
#include <cstring>
class ExtString{
public:
typedef char value_type;
typedef char * iterator;
};
#endif | true |
26e216b4c9bd5a3086f0a9b44f0f5f9be8fe962f | C++ | FranekStark/monocular-visual-odometry | /mvo/src/operations/FeatureOperations.h | UTF-8 | 2,985 | 2.515625 | 3 | [
"MIT"
] | permissive | //
// Created by franek on 24.09.19.
//
#ifndef MVO_SRC_SLIDING_WINDOW_FEATUREOPERATIONS_H_
#define MVO_SRC_SLIDING_WINDOW_FEATUREOPERATIONS_H_
#include <opencv2/core.hpp>
#include <image_geometry/pinhole_camera_model.h>
#include <math.h>
class FeatureOperations {
public:
/**
* Calculates the procentualdiparity between twoVectors of Featres. The Features are matched by Index.
* @param first first features
* @param second second features
* @return the Disparity between 0 and 1
*/
static double calcDisparity(const std::vector<cv::Vec3d> &first, const std::vector<cv::Vec3d> &second);
/**
* Project camera-pixel-coordinate Feature into camera-projected Feature
* @param features source vector
* @param featuresE empty target vector
* @param cameraModel parameters of the camera
*/
static void euclidNormFeatures(const std::vector<cv::Point2f> &features, std::vector<cv::Vec3d> &featuresE,
const image_geometry::PinholeCameraModel &cameraModel);
/**
* Unproject camera-projected Features into pixel-coordinates
* @param featuresE source vector
* @param features emtpy target vector
* @param cameraModel parameters of the camera
*/
static void euclidUnNormFeatures(const std::vector<cv::Vec3d> &featuresE, std::vector<cv::Point2f> &features,
const image_geometry::PinholeCameraModel &cameraModel);
/**
* Norms every feature INPLACE
* @param featuresE the vector of features
*/
static void normFeatures(std::vector<cv::Vec3d> & featuresE);
/**
* Unrotates features from source- into target-vector
* @param features source vector
* @param unrotatedFeatures empty target vector
* @param R the rotation between the features
*/
static void unrotateFeatures(const std::vector<cv::Vec3d> &features, std::vector<cv::Vec3d> &unrotatedFeatures,
const cv::Matx33d &R);
/**
* Reconstructs the Depth of two detections of the same Feature on two different places (triangulation)
* @param depth the target vector (first empty)
* @param m2L second detections of the points
* @param m1L first detections of the point
* @param r the rotation between first and second
* @param b the baseline between first and second
*/
static void reconstructDepth(std::vector<double> &depth,
const std::vector<cv::Vec3d> &vec1,
const std::vector<cv::Vec3d> &vec0,
const cv::Matx33d &R1,
const cv::Matx33d &R0,
const cv::Vec3d &b);
static void calcProjectionsAngleDiff(std::vector<double> &depth,
const std::vector<cv::Vec3d> &vec1,
const std::vector<cv::Vec3d> &vec0,
const cv::Matx33d &R1,
const cv::Matx33d &R0,
const cv::Vec3d &b);
};
#endif //MVO_SRC_SLIDING_WINDOW_FEATUREOPERATIONS_H_
| true |
448e3be1465a951012770c25267f617196285183 | C++ | sshedbalkar/DigiPen_Backup | /Team_Alien/GAM 550/AlienEngine/source/depthshaderclass.cpp | UTF-8 | 10,431 | 2.5625 | 3 | [] | no_license | ////////////////////////////////////////////////////////////////////////////////
// Filename: depthshaderclass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "Precompiled.h"
#include "depthshaderclass.h"
#include "lightclass.h"
namespace Framework {
DepthShaderClass::DepthShaderClass()
{
m_vertexShader = 0;
m_geometryShader = 0;
m_layout = 0;
m_matrixBuffer = 0;
m_CMVMBuffer = 0;
}
DepthShaderClass::DepthShaderClass(const DepthShaderClass& other)
{
}
DepthShaderClass::~DepthShaderClass()
{
}
bool DepthShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
bool result;
// Initialize the vertex and pixel shaders.
result = InitializeShader(device, hwnd, "Shaders//depth.vs", "Shaders//depth.gs");
if(!result)
{
return false;
}
return true;
}
void DepthShaderClass::Shutdown()
{
// Shutdown the vertex and pixel shaders as well as the related objects.
ShutdownShader();
return;
}
bool DepthShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix,
D3DXMATRIX projectionMatrix, const std::vector<LightClass>& lights, int LightIndex)
{
bool result;
// Set the shader parameters that it will use for rendering.
result = SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, lights, LightIndex);
if(!result)
{
return false;
}
// Now render the prepared buffers with the shader.
RenderShader(deviceContext, indexCount);
return true;
}
bool DepthShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, char* vsFilename, char* gsFilename)
{
HRESULT result;
ID3D10Blob* errorMessage;
ID3D10Blob* vertexShaderBuffer;
ID3D10Blob* geometryShaderBuffer;
D3D11_INPUT_ELEMENT_DESC polygonLayout[1];
unsigned int numElements;
D3D11_BUFFER_DESC matrixBufferDesc;
D3D11_BUFFER_DESC CMVMBufferDesc;
// Initialize the pointers this function will use to null.
errorMessage = 0;
vertexShaderBuffer = 0;
geometryShaderBuffer = 0;
// Compile the vertex shader code.
result = D3DX11CompileFromFile(vsFilename, NULL, NULL, "DepthVertexShader", "vs_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL,
&vertexShaderBuffer, &errorMessage, NULL);
if(FAILED(result))
{
// If the shader failed to compile it should have writen something to the error message.
if(errorMessage)
{
OutputShaderErrorMessage(errorMessage, hwnd, vsFilename);
}
// If there was nothing in the error message then it simply could not find the shader file itself.
else
{
MessageBox(hwnd, vsFilename, "Missing Shader File", MB_OK);
}
return false;
}
// Compile the geometry shader code.
result = D3DX11CompileFromFile(gsFilename, NULL, NULL, "DepthGeometryShader", "gs_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL,
&geometryShaderBuffer, &errorMessage, NULL);
if(FAILED(result))
{
// If the shader failed to compile it should have writen something to the error message.
if(errorMessage)
{
OutputShaderErrorMessage(errorMessage, hwnd, gsFilename);
}
// If there was nothing in the error message then it simply could not find the file itself.
else
{
MessageBox(hwnd, gsFilename, "Missing Shader File", MB_OK);
}
return false;
}
// Create the vertex shader from the buffer.
result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader);
if(FAILED(result))
{
return false;
}
// Create the geometry shader from the buffer.
result = device->CreateGeometryShader(geometryShaderBuffer->GetBufferPointer(), geometryShaderBuffer->GetBufferSize(), NULL, &m_geometryShader);
if(FAILED(result))
{
return false;
}
// Create the vertex input layout description.
// This setup needs to match the VertexType stucture in the ModelClass and in the shader.
polygonLayout[0].SemanticName = "POSITION";
polygonLayout[0].SemanticIndex = 0;
polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[0].InputSlot = 0;
polygonLayout[0].AlignedByteOffset = 0;
polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[0].InstanceDataStepRate = 0;
// Get a count of the elements in the layout.
numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);
// Create the vertex input layout.
result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout);
if(FAILED(result))
{
return false;
}
// Release the vertex shader buffer and pixel shader buffer since they are no longer needed.
vertexShaderBuffer->Release();
vertexShaderBuffer = 0;
geometryShaderBuffer->Release();
geometryShaderBuffer = 0;
// Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType);
matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
matrixBufferDesc.MiscFlags = 0;
matrixBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer);
if(FAILED(result))
{
return false;
}
// Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
CMVMBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
CMVMBufferDesc.ByteWidth = sizeof(CMVMBufferType);
CMVMBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
CMVMBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
CMVMBufferDesc.MiscFlags = 0;
CMVMBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
result = device->CreateBuffer(&CMVMBufferDesc, NULL, &m_CMVMBuffer);
if(FAILED(result))
{
return false;
}
return true;
}
void DepthShaderClass::ShutdownShader()
{
// Release the matrix constant buffer.
if(m_matrixBuffer)
{
m_matrixBuffer->Release();
m_matrixBuffer = 0;
}
// Release the cube map view matrix constant buffer.
if(m_CMVMBuffer)
{
m_CMVMBuffer->Release();
m_CMVMBuffer = 0;
}
// Release the layout.
if(m_layout)
{
m_layout->Release();
m_layout = 0;
}
// Release the geometry shader.
if(m_geometryShader)
{
m_geometryShader->Release();
m_geometryShader = 0;
}
// Release the vertex shader.
if(m_vertexShader)
{
m_vertexShader->Release();
m_vertexShader = 0;
}
return;
}
void DepthShaderClass::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, char* shaderFilename)
{
char* compileErrors;
unsigned long bufferSize, i;
ofstream fout;
// Get a pointer to the error message text buffer.
compileErrors = (char*)(errorMessage->GetBufferPointer());
// Get the length of the message.
bufferSize = errorMessage->GetBufferSize();
// Open a file to write the error message to.
fout.open("shader-error.txt");
// Write out the error message.
for(i=0; i<bufferSize; i++)
{
fout << compileErrors[i];
}
// Close the file.
fout.close();
// Release the error message.
errorMessage->Release();
errorMessage = 0;
// Pop a message up on the screen to notify the user to check the text file for compile errors.
MessageBox(hwnd, "Error compiling shader. Check shader-error.txt for message.", shaderFilename, MB_OK);
return;
}
bool DepthShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix, const std::vector<LightClass>& lights, int LightIndex)
{
HRESULT result;
D3D11_MAPPED_SUBRESOURCE mappedResource;
unsigned int bufferNumber;
MatrixBufferType* dataPtr;
CMVMBufferType* dataPtr2;
// Lock the constant buffer so it can be written to.
result = deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if(FAILED(result))
{
return false;
}
// Get a pointer to the data in the constant buffer.
dataPtr = (MatrixBufferType*)mappedResource.pData;
// Copy the matrices into the constant buffer.
dataPtr->World = worldMatrix;
// Unlock the constant buffer.
deviceContext->Unmap(m_matrixBuffer, 0);
// Set the position of the constant buffer in the vertex shader.
bufferNumber = 0;
// Now set the constant buffer in the vertex shader with the updated values.
deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer);
// Lock the constant buffer so it can be written to.
result = deviceContext->Map(m_CMVMBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if(FAILED(result))
{
return false;
}
// Get a pointer to the data in the constant buffer.
dataPtr2 = (CMVMBufferType*)mappedResource.pData;
D3DXMATRIX CubeMapViewMatrix[6];
lights[LightIndex].GetCubeMapViewMatrix(CubeMapViewMatrix);
// Copy the matrices into the constant buffer.
for (int index = 0; index < 6; ++index)
{
dataPtr2->viewM[index] = CubeMapViewMatrix[index];
}
// Unlock the constant buffer.
deviceContext->Unmap(m_CMVMBuffer, 0);
// Set the position of the constant buffer in the vertex shader.
bufferNumber = 0;
// Now set the constant buffer in the vertex shader with the updated values.
deviceContext->GSSetConstantBuffers(bufferNumber, 1, &m_CMVMBuffer);
return true;
}
void DepthShaderClass::RenderShader(ID3D11DeviceContext* deviceContext, int indexCount)
{
// Set the vertex input layout.
deviceContext->IASetInputLayout(m_layout);
// Set the vertex and pixel shaders that will be used to render this triangle.
deviceContext->VSSetShader(m_vertexShader, NULL, 0);
deviceContext->GSSetShader(m_geometryShader, NULL, 0);
deviceContext->PSSetShader(NULL, NULL, 0);
deviceContext->DSSetShader(NULL, NULL, 0);
deviceContext->HSSetShader(NULL, NULL, 0);
deviceContext->CSSetShader(NULL, NULL, 0);
// Render the triangle.
deviceContext->DrawIndexed(indexCount, 0, 0);
return;
}
} | true |
333ed65e66afbdf7ade941d620a875943782ce5b | C++ | wangyu9/MDGCNN | /ShapeAnalysis/noise.h | UTF-8 | 1,766 | 2.75 | 3 | [] | no_license | #pragma once
#ifndef NOISE_H
#define NOISE_H
#include "utils.h"
template <typename num_t>
void snow_noise(double intensity, std::vector<num_t>& f) {
for (int i = 0; i < f.size(); i++) {
f[i] += 2.0*intensity*(random_real() - 0.5);
}
}
template <typename num_t>
void salt_noise(double t, std::vector<num_t>& f) {
for (int i = 0; i < f.size(); i++) {
if (random_real() > 1-t) {
f[i] = std::max(1.0, f[i]);
}
}
}
template <typename num_t>
void perturb_bnd(double t, const Eigen::MatrixXi& F, std::vector<num_t>& f) {
bool cond;
for (int i = 0; i < F.rows(); i++) {
cond = (f[F(i,0)] > 0.5) || (f[F(i, 1)] > 0.5) || (f[F(i, 2)] > 0.5);
if (cond) {
if (random_real() > 1 - t) {
f[F(i, 0)] = std::max(1.0, f[F(i, 0)]);
}
if (random_real() > 1 - t) {
f[F(i, 1)] = std::max(1.0, f[F(i, 1)]);
}
if (random_real() > 1 - t) {
f[F(i, 2)] = std::max(1.0, f[F(i, 2)]);
}
}
}
}
template <typename num_t>
void local_average(const Eigen::MatrixXi& F, std::vector<num_t>& f) {
std::vector<num_t> f_tmp(f.size());
std::fill(f_tmp.begin(), f_tmp.end(), 0.0);
std::vector<int> nb_neigh(f.size());
std::fill(nb_neigh.begin(), nb_neigh.end(), 0);
double x;
for (int i = 0; i < F.rows(); i++) {
x = (f[F(i, 0)] + f[F(i, 1)] + f[F(i, 2)])/3.0;
f_tmp[F(i, 0)] += x;
f_tmp[F(i, 1)] += x;
f_tmp[F(i, 2)] += x;
nb_neigh[F(i, 0)]++;
nb_neigh[F(i, 1)]++;
nb_neigh[F(i, 2)]++;
}
for (int i = 0; i < f.size(); i++) {
f[i] = f_tmp[i]/nb_neigh[i];
}
}
template <typename num_t>
void local_average(const Eigen::MatrixXi& F, std::vector<num_t>& f, int nb_iter) {
for (int i = 0; i < nb_iter; i++) {
local_average(F, f);
}
}
#endif // !NOISE_H
| true |
add20d4930641856507bd0e1c64baefcc2b26c4f | C++ | Bloodclot24/crap | /tp2/lib/ComandoCambiarTextura.cpp | UTF-8 | 1,302 | 2.640625 | 3 | [] | no_license | #include "ComandoCambiarTextura.h"
#include "MundoTP2.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
ComandoCambiarTextura::ComandoCambiarTextura(const char * filename){
cargarTextura(filename);
}
void ComandoCambiarTextura::ejecutar(){
MundoTP2::get_instance()->obtenerCuerpo()->setTextura(texture);
}
GLuint ComandoCambiarTextura::getTextura(){
return texture;
}
void ComandoCambiarTextura::cargarTextura( const char * filename ){
int width, height;
unsigned char * data;
FILE * file;
file = fopen( filename, "rb" );
width = 1024;
height = 512;
data = (unsigned char *)malloc( width * height * 3 );
fread( data, width * height * 3, 1, file );
fclose( file );
glGenTextures( 1, &texture );
glBindTexture( GL_TEXTURE_2D, texture );
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height, GL_BGR, GL_UNSIGNED_BYTE, data );
free( data );
}
| true |
6b97eec992203e2e6d6caa7b94f02a7059d0aece | C++ | SharpSnake/CPP_Primer_5th_Edition | /CppPrimer5th/TestHelper.h | GB18030 | 3,935 | 3.328125 | 3 | [
"MIT"
] | permissive | // =============================================================================
//
// Some helper functions or structs.
// - WuYu, 2018.06.
// =============================================================================
#ifndef TESTHELPER_H // Ԥʵͷļ
#define TESTHELPER_H // ijcppдhļֱܱӻӰ
// ĿǷֹظı
#define MCPP11 // עC++11
#include "ConsoleUtility.h"
#include "Functions.hpp"
#include "Geom.hpp"
// ͷļòҪusingͷļcppʱ
// ܻ벻ֳͻcppԼʹЩusing
using namespace std;
// C++11ö٣
enum class ProgramLan : unsigned MCPP11
{
Lan_CPP = 0x001,
Lan_CSharp = 0x002,
Lan_Java = 0x004,
Lan_Matlab = 0x008,
Lan_Python = Lan_Matlab << 1,
Lan_All = Lan_CPP | Lan_CSharp | Lan_Java | Lan_Matlab | Lan_Python
};
// ࣺζʽax^2 + bx + c
class QuadraticPoly
{
public:
double m_Coef[ 3 ];
public:
// ζʽֵ
double Polyval( const double &x ) const
{
return m_Coef[ 0 ] * x * x + m_Coef[ 1 ] * x + m_Coef[ 2 ];
}
friend ostream & operator <<( ostream &ostm, const QuadraticPoly &obj )
{
return ostm << obj.m_Coef[ 0 ] << " * x^2 + " << obj.m_Coef[ 1 ]
<< " * x + " << obj.m_Coef[ 2 ];
}
};
// ֵʾر
class Placemark MCPP11
{
public:
using ushort = unsigned short;
public:
// defaultΪconstexprʱÿԱڳʼֵ
constexpr Placemark() = default;
Placemark( double x, double y, ushort h )
: m_Coord( x, y ), m_Height( h ) {}
// һconstexpr죬ҺΪաҡÿԱҪʼһ
constexpr Placemark( double x, double y, ushort h, const char *title )
: m_Coord( x, y ), m_Height( h ), m_Title( title ) {}
// ܡԶ
public:
friend ostream& operator <<( ostream &o, const Placemark &p )
{
o << "꣺" << p.m_Coord << endl
<< "Σ" << p.m_Height << endl
<< "ƣ" << p.m_Title;
return o;
}
private:
// ԱͱͣԶֵͣ
// ڳʼֵǡʽʹԼġconstexpr캯
Coordinate m_Coord{ 121, 36 }; // ڳʼֵֻáбʼ
ushort m_Height = Factorial( 5 );
const char *m_Title = "찲";
};
// ֵ
template< typename T >
struct Op_Abs
{
T operator()( const T &val ) const
{
return val > 0 ? val : -val;
}
void operator()( T &val ) const
{
if( val < 0 )
val = -val;
}
};
// 볣
template< typename T >
struct Op_Times_N
{
Op_Times_N( T n ) : m_N( n ) {}
T operator()( const T &val ) const { return val * m_N; }
void operator()( T &val ) const { val *= m_N; }
private:
T m_N;
};
// ģ±עȥõģ壬ƫػʵ
template< typename T >
struct RemoveRef {
typedef T type;
};
template< typename T >
struct RemoveRef< T& > { // ֵػ
typedef T type;
};
template< typename T >
struct RemoveRef< T&& > { // ֵػ
typedef T type;
};
/////////////////////////////////////////////////////////////////////////////////
inline void StartOneTest( const char *msg = nullptr MCPP11 )
{
CONSOLE_COLOR_AUTO_RESET;
SetConsoleTextColor( CmdColor_Red );
cout << endl << "*********************************"
"*********************************" << endl;
SetConsoleTextColor( CmdColor_Green );
if ( msg )
cout << msg << endl;
}
// Եijʼ
inline void HelperInit( void )
{
FunctionsInit();
ConsoleInit();
}
#endif // !TESTHELPER_H
| true |
346d1968cd69cb1c3b68eeb6ea706f8db8e52065 | C++ | tahiat/UVA-Solutions | /10664_luggage.cpp | UTF-8 | 997 | 2.625 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<stdio.h>
#define size 25
using namespace std;
int T;
char input[4*size];
int A[size];
void readcase()
{
gets(input);
}
int N;
void formatting()
{
N = 0;
A[0] = 0;
for (int i = 0; input[i]; i++)
{
if (input[i] >= '0'&&input[i] <= '9')
{
A[N] = A[N] * 10 + input[i] - '0';
}
else if (input[i] == ' ')
{
N++;
A[N] = 0;
}
}
N++;
}
int Ans;
int solve(int i, int sum1, int sum2)
{
if (i == N)
{
if (sum1 == sum2){
return 1;
}
else
return 0;
}
if(solve(i + 1, sum1 + A[i], sum2))
return 1;
if(solve(i + 1, sum1, sum2 + A[i]))
return 1;
return 0;
}
void solvecase()
{
Ans= solve(0, 0, 0);
if (Ans == 1)
printf("YES\n");
else
printf("NO\n");
}
int main()
{
int t;
char c[2];
freopen("input.txt", "r", stdin);
cin >> t;
gets(c);
for (T = 1; T <= t; T++)
{
readcase();
formatting();
solvecase();
}
} | true |
1577efc192db2272d3a912763d478cc6ae14c5ce | C++ | jdlouhy/Piezas | /Piezas.cpp | UTF-8 | 4,487 | 3.78125 | 4 | [
"MIT"
] | permissive | #include "Piezas.h"
#include <vector>
/** CLASS Piezas
* Class for representing a Piezas vertical board, which is roughly based
* on the game "Connect Four" where pieces are placed in a column and
* fall to the bottom of the column, or on top of other pieces already in
* that column. For an illustration of the board, see:
* https://en.wikipedia.org/wiki/Connect_Four
*
* Board coordinates [row,col] should match with:
* [2,0][2,1][2,2][2,3]
* [1,0][1,1][1,2][1,3]
* [0,0][0,1][0,2][0,3]
* So that a piece dropped in column 2 should take [0,2] and the next one
* dropped in column 2 should take [1,2].
**/
/**
* Constructor sets an empty board (default 3 rows, 4 columns) and
* specifies it is X's turn first
**/
Piezas::Piezas()
{
for (int i = 0; i < BOARD_ROWS; i++){
std::vector<Piece> vec;
for (int x = 0; x < BOARD_COLS; x++){
Piece t;
t = Blank;
vec.push_back(t);
}
board.push_back(vec);
}
//it is xs turn first
turn = X;
}
/**
* Resets each board location to the Blank Piece value, with a board of the
* same size as previously specified
**/
void Piezas::reset()
{
for (int i = 0; i < BOARD_ROWS; i++){
for (int x = 0; x < BOARD_COLS; x++){
board[i][x] = Blank;
}
}
}
/**
* Places a piece of the current turn on the board, returns what
* piece is placed, and toggles which Piece's turn it is. dropPiece does
* NOT allow to place a piece in a location where a column is full.
* In that case, placePiece returns Piece Blank value
* Out of bounds coordinates return the Piece Invalid value
* Trying to drop a piece where it cannot be placed loses the player's turn
**/
Piece Piezas::dropPiece(int column)
{
//first check out of bounds place
if (column >= BOARD_COLS || column < 0){
if (turn == X){
turn = O;
}
else {
turn = X;
}
return Invalid;
}
//then check if the column is full case
if (board[0][column] != Blank){
if (turn == X){
turn = O;
}
else {
turn = X;
}
return Blank;
}
int count = 0;
//find lowest blank place in this column
while ( count+1 < BOARD_ROWS && board[count+1][column] == Blank ){
count = count + 1;
}
//set that spot to turn piece, store turn piece before flip, flip, then return the stored previous turn piece
board[count][column] = turn;
Piece cp = turn;
if (turn == X){
turn = O;
}
else {
turn = X;
}
return cp;
}
/**
* Returns what piece is at the provided coordinates, or Blank if there
* are no pieces there, or Invalid if the coordinates are out of bounds
**/
Piece Piezas::pieceAt(int row, int column)
{
if (row < 0 || row >= BOARD_ROWS || column >= BOARD_COLS || column < 0 ){
return Invalid;
}
return board[row][column];
}
/**
* Returns which Piece has won, if there is a winner, Invalid if the game
* is not over, or Blank if the board is filled and no one has won ("tie").
* For a game to be over, all locations on the board must be filled with X's
* and O's (i.e. no remaining Blank spaces). The winner is which player has
* the most adjacent pieces in a single line. Lines can go either vertically
* or horizontally. If both X's and O's have the same max number of pieces in a
* line, it is a tie.
* We will signify this tie case with a blank piece.
**/
Piece Piezas::gameState()
{
//max counts
int xmax = 0;
int omax = 0;
for (int i = 0; i < BOARD_ROWS; i++){
int xcount = 0;
int ocount = 0;
//scan horizontally to find maxes
for (int x = 0; x < BOARD_COLS; x++){
if (board[i][x] == X){
ocount = 0;
xcount += 1;
if (xcount > xmax) {
xmax = xcount;
}
}
else if (board [i][x] == O){
xcount = 0;
ocount += 1;
if (ocount > omax){
omax = ocount;
}
}
//found a blank piece then game is not over
else if (board[i][x] == Blank){
return Invalid;
}
}
}
//vertical scan below
for (int i = 0; i < BOARD_COLS; i++){
int xcount = 0;
int ocount = 0;
for (int x = 0; x < BOARD_ROWS; x++){
if (board[x][i] == X){
ocount = 0;
xcount += 1;
if (xcount > xmax) {
xmax = xcount;
}
}
else if (board [x][i] == O){
xcount = 0;
ocount += 1;
if (ocount > omax){
omax = ocount;
}
}
}
}
if (omax > xmax) {
Piece ret = O;
return ret;
}
else if (xmax > omax) {
Piece ret = X;
return ret;
}
//tie case
else {
Piece ret = Blank;
return ret;
}
}
| true |
b16a8adfd28a60f483ace70bb4ebd808af2103f9 | C++ | raghavdotcom/chamber-crawler | /game/subjects/characters/enemies/enemy.h | UTF-8 | 1,479 | 3.234375 | 3 | [] | no_license | #ifndef __ENEMY__
#define __ENEMY__
#include "../character.h"
#include "../../items/treasures/treasure.h"
#include "../../items/treasures/normalHoard.h"
#include "../../items/treasures/smallHoard.h"
#include <memory>
using namespace std;
class Enemy : public Character
{
private:
/* data */
public:
Enemy(int hp, int atk, int def, int x, int y, char c);
virtual ~Enemy() = default;
//void move() override;
virtual int attack(shared_ptr<Character>);
virtual int attackBy(int) override;
virtual int giveGold() {
if (getHP() <= 0) {
if (rand()%2 + 1 == 1) return 1;
else return 2;
} else return 0;
}
};
Enemy::Enemy(int hp, int atk, int def, int x, int y, char c) : Character{hp, atk, def, x, y, c} {}
int Enemy::attack(shared_ptr<Character> c) {
return c->attackBy(atk);
}
int Enemy::attackBy(int oppAtk) {
int ceiling = (100*oppAtk) % (100+def) == 0 ? 0 : 1;
int damage = ( ( (100/(100+def))*oppAtk ) + ceiling ); // ceiling of this exp
HP -= damage;
return damage;
}
#endif
//Damage(Def ender) = ceiling((100/(100+Def (Def ender)))∗Atk(Attacker)), where Attacker specifies the attacking character (enemy or PC) and defender specifies the character being attacked. Thus, in a single round a character can be both an attacker and a defender.
// If the player character has the Barrier Suit, then their damage calculation is changed such that Damage(PC) = ceiling(Damage(Defender)). | true |
c57c78197ceec98fca9cf117d6f7438d99dbeafd | C++ | vrsys/lamure | /apps/rendering/MatrixInterpolation.cpp | UTF-8 | 946 | 2.546875 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright (c) 2014-2018 Bauhaus-Universitaet Weimar
// This Software is distributed under the Modified BSD License, see license.txt.
//
// Virtual Reality and Visualization Research Group
// Faculty of Media, Bauhaus-Universitaet Weimar
// http://www.uni-weimar.de/medien/vr
#include "MatrixInterpolation.hpp"
glm::mat4 interpolate(const glm::mat4& ma, const glm::mat4& mb, float t){
glm::quat firstQuat = glm::quat_cast(ma);
glm::quat secondQuat = glm::quat_cast(mb);
glm::quat finalQuat = glm::slerp(firstQuat, secondQuat, t);
glm::mat4 r = glm::mat4_cast(finalQuat);
glm::vec4 transformComp1 = glm::vec4(ma[3][0],ma[3][1],ma[3][2],ma[3][3]);
glm::vec4 transformComp2 = glm::vec4(mb[3][0],mb[3][1],mb[3][2],mb[3][3]);
glm::vec4 finalTrans = (1.0f-t)*transformComp1 + t*transformComp2;
r[3][0] = finalTrans.x;
r[3][1] = finalTrans.y;
r[3][2] = finalTrans.z;
r[3][3] = finalTrans.w;
return r;
}
| true |
702ec2a8a9b2faa89a113a5bc075a07f4505ac8a | C++ | myu404/HuntTheWumpus | /HuntTheWumpusLib/UserNotification.cpp | UTF-8 | 3,734 | 3.140625 | 3 | [] | no_license | /*
* Author: Michael Yu
* C++ Programming, Spring 2021
* Hunt The Wumpus: Assignment 05
* 6/20/2021
*/
#include "UserNotification.h"
#include <iostream>
#include <stdexcept>
namespace HuntTheWumpus
{
std::ostream& operator<<(std::ostream& out, const UserNotification::Notification& value)
{
static std::unordered_map<UserNotification::Notification, std::string> s_valueMap =
{
{UserNotification::Notification::ObserveWumpus, "ObserveWumpus"},
{UserNotification::Notification::ObservePit, "ObservePit"},
{UserNotification::Notification::ObserveBat, "ObserveBat"},
{UserNotification::Notification::ObserveMiss, "ObserveMiss"},
{UserNotification::Notification::ObserveOutOfArrows, "ObserveOutOfArrows"},
{UserNotification::Notification::BatTriggered, "BatTriggered"},
{UserNotification::Notification::PitTriggered, "PitTriggered"},
{UserNotification::Notification::WumpusTriggered, "WumpusTriggered"},
{UserNotification::Notification::WumpusAwoken, "WumpusAwoken"},
{UserNotification::Notification::WumpusShot, "WumpusShot"},
{UserNotification::Notification::HunterEaten, "HunterEaten"},
{UserNotification::Notification::HunterShot, "HunterShot"},
{UserNotification::Notification::CaveEntered, "CaveEntered"},
{UserNotification::Notification::NeighboringCaves, "NeighboringCaves"},
{UserNotification::Notification::ReportIllegalMove, "ReportIllegalMove"}
};
out << s_valueMap[value];
return out;
}
void UserNotification::AddCallback(const Notification category, std::function<void()>&& callback)
{
m_callbacks.insert_or_assign(category, std::move(callback));
}
void UserNotification::AddCallback(const Notification category, std::function<void(int)>&& callback)
{
m_callbacks.insert_or_assign(category, std::move(callback));
}
void UserNotification::AddCallback(const Notification category, std::function<void(const std::vector<int>&)>&& callback)
{
m_callbacks.insert_or_assign(category, std::move(callback));
}
void UserNotification::Notify(const Notification category) const
{
const auto callback = m_callbacks.find(category);
if (callback == m_callbacks.end()) throw std::out_of_range("Notification is missing");
const auto* callbackFunc = std::get_if<std::function<void()>>(&callback->second);
// Throw exception for missing callback function.
if (!callbackFunc) throw std::bad_function_call();
(*callbackFunc)();
}
template<typename Callback, typename CallbackArg> void DoCallback(const std::unordered_map<UserNotification::Notification, UserNotification::CallbackData>& callbacks, const UserNotification::Notification callbackId, const CallbackArg& arg)
{
const auto callback = callbacks.find(callbackId);
if (callback == callbacks.end()) throw std::out_of_range("Notification is missing");
const auto* callbackFunc = std::get_if<Callback>(&callback->second);
// Throw exception for missing callback function.
if (!callbackFunc) throw std::bad_function_call();
(*callbackFunc)(arg);
}
void UserNotification::Notify(const Notification category, const int arg) const
{
DoCallback<std::function<void(int)>, int>(m_callbacks, category, arg);
}
void UserNotification::Notify(const Notification category, const std::vector<int>& arg) const
{
DoCallback<std::function<void(const std::vector<int> &)>, std::vector<int>>(m_callbacks, category, arg);
}
}
| true |
3ceb62b3fc27d65372faf312d6af430384068e03 | C++ | petuzk/Warcaby | /inc/game/board/BoardConst.hpp | UTF-8 | 420 | 2.65625 | 3 | [
"MIT"
] | permissive | #pragma once
/* Przechowuje podstawowe stałe dotyczące plansy.
* Ma to na celu ułatwienie zmiany zasad gry, ackolwiek
* w implementacji często są pewne założenia co do tych wartości.
*/
class BoardConst {
public:
static constexpr int SIZE = 8;
static constexpr int START_ROWS = 3;
static_assert(START_ROWS * 2 <= SIZE, "logic error");
static constexpr int CHECKERS_PER_PLAYER = SIZE * START_ROWS / 2;
}; | true |
fd6875e139753b5e98934e807e619f4f1b2e9e77 | C++ | patmosxx-v2/reed-solomon | /rs.cc | UTF-8 | 4,573 | 2.59375 | 3 | [
"MIT"
] | permissive | #include "rs.hh"
#include <stdexcept>
#include <string.h>
#include <iostream>
extern "C" {
#include <fec.h>
}
using namespace std;
RSCodec::RSCodec(const std::vector<unsigned int>& roots, unsigned int fcr, unsigned int prim, unsigned int nroots, unsigned int pad, unsigned int bits)
: d_N((1<< (bits)) - pad -1),
d_K((1<< (bits)) - pad - 1 - nroots),
d_nroots(nroots),
d_bits(bits)
{
if(d_bits > 8)
throw std::runtime_error("This encoder supports 8 bits at most");
for(const auto& r : roots)
d_gfpoly |= (1<<r);
d_rs = init_rs_char(d_bits, d_gfpoly, fcr, prim, nroots, pad);
if(!d_rs)
throw std::runtime_error("Unable to initialize RS codec");
}
void RSCodec::encode(std::string& msg)
{
if(msg.size() > d_K)
throw std::runtime_error("Can't encode message longer than "+std::to_string(d_K)+" bytes");
msg.append(d_K - msg.size(), 0);
// void encode_rs_char(void *rs,unsigned char *data,
// unsigned char *parity);
uint8_t parity[d_nroots];
encode_rs_char(d_rs, (uint8_t*)msg.c_str(), parity);
msg.append((char*)&parity[0], (char*)&parity[d_nroots]);
}
int RSCodec::decode(const std::string& in, std::string& out, vector<unsigned int>* corrs)
{
// int decode_rs_char(void *rs,unsigned char *data,int *eras_pos,
// int no_eras);
unsigned char data[in.length()];
memcpy(data, in.c_str(), in.length());
vector<int> eras_pos;
int eras_no=0;
if(corrs) {
for(const auto& c : *corrs) {
eras_pos.push_back(c);
eras_no++;
}
}
eras_pos.resize(d_nroots);
int ret = decode_rs_char(d_rs, data, &eras_pos[0], eras_no);
/*
The decoder corrects the symbols "in place", returning the number of symbols in error. If the codeword is uncorrectable, -1 is returned and the data block is unchanged. If
eras_pos is non-null, it is used to return a list of corrected symbol positions, in no particular order. This means that the array passed through this parameter must have at
least nroots elements to prevent a possible buffer overflow.
*/
if(ret < 0)
throw std::runtime_error("Could not correct message");
if(corrs)
corrs->clear();
if(ret && corrs) {
for(int n=0; n < ret; ++n)
corrs->push_back(eras_pos[n]);
}
out.assign((char*) data, (char*)data + d_N);
return ret;
}
RSCodec::~RSCodec()
{
if(d_rs)
free_rs_char(d_rs);
}
////
RSCodecInt::RSCodecInt(const std::vector<unsigned int>& roots, unsigned int fcr, unsigned int prim, unsigned int nroots, unsigned int pad, unsigned int bits)
: d_N((1<< (bits)) - pad -1),
d_K((1<< (bits)) - pad - 1 - nroots),
d_nroots(nroots),
d_bits(bits)
{
if(d_bits > 32)
throw std::runtime_error("This encoder supports 32 bits at most");
for(const auto& r : roots)
d_gfpoly |= (1<<r);
d_rs = init_rs_int(d_bits, d_gfpoly, fcr, prim, nroots, pad);
if(!d_rs)
throw std::runtime_error("Unable to initialize RS codec");
}
void RSCodecInt::encode(vector<unsigned int>& msg)
{
if(msg.size() > d_K)
throw std::runtime_error("Can't encode message longer than "+std::to_string(d_K)+" bytes");
msg.resize(d_K);
vector<unsigned int> parity(d_nroots);
encode_rs_int(d_rs, (int*)&msg[0], (int*)&parity[0]);
for(const auto& i : parity)
msg.push_back(i);
}
int RSCodecInt::decode(const std::vector<unsigned int>& in, std::vector<unsigned int>& out, vector<unsigned int>* corrs)
{
// int decode_rs_char(void *rs,unsigned char *data,int *eras_pos,
// int no_eras);
vector<unsigned int> data = in;
vector<unsigned int> eras_pos;
int eras_no=0;
if(corrs) {
for(const auto& c : *corrs) {
eras_pos.push_back(c);
eras_no++;
}
}
eras_pos.resize(d_nroots);
int ret = decode_rs_int(d_rs, (int*)&data[0], (int*)&eras_pos[0], eras_no);
/*
The decoder corrects the symbols "in place", returning the number of symbols in error. If the codeword is uncorrectable, -1 is returned and the data block is unchanged. If
eras_pos is non-null, it is used to return a list of corrected symbol positions, in no particular order. This means that the array passed through this parameter must have at
least nroots elements to prevent a possible buffer overflow.
*/
if(ret < 0)
throw std::runtime_error("Could not correct message");
if(corrs)
corrs->clear();
if(ret && corrs) {
for(int n=0; n < ret; ++n)
corrs->push_back(eras_pos[n]);
}
out = data;
out.resize(d_N);
return ret;
}
RSCodecInt::~RSCodecInt()
{
if(d_rs)
free_rs_int(d_rs);
}
| true |
1567c28f588ca3cb0c15c3f008f64d8262ae10c0 | C++ | syedbilal07/cplusplus | /C++ Basics/Chapter 5 - Modifier Types/ModifierTypes/main.cpp | UTF-8 | 335 | 3.203125 | 3 | [] | no_license | #include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
short unsigned int x; // value always positive
short signed int y; // value can be positive or negative
x = 50000;
y = 50000;
cout << x << endl; // 50000
cout << y << endl; // -15536
return 0;
}
| true |
3e539976cd497623efd986d21c264d02f8678fd6 | C++ | TimPhoeniX/MyUJ | /AiSD2/1/main.cpp | UTF-8 | 472 | 3.15625 | 3 | [] | no_license | #include "ctl_set.hpp"
template class Set<int>;
int main()
{
AbstractSet<int>* A = new Set<int>();
AbstractSet<int>* B = new Set<int>();
A->Insert(1);
A->Insert(2);
A->Insert(3);
B->Insert(3);
B->Insert(4);
B->Insert(5);
A->Print();
B->Print();
auto C = A->Sum(B);
C->Print();
auto D = A->Difference(B);
D->Print();
auto E = A->Intersection(B);
E->Print();
A->Delete(1);
A->Print();
std::cout << B->IsMember(1) << ' ' << B->IsMember(5) << std::endl;
} | true |
71890644995ca73438f5eb87f6a9873d087dca86 | C++ | FinancialEngineerLab/XPricer | /VanillaOption.h | UTF-8 | 932 | 2.65625 | 3 | [] | no_license | #ifndef VANILLAOPTION_H
#define VANILLAOPTION_H
#include "VanillaPayoff.h"
#include "PricingEngine.h"
#include "Option.h"
#include <memory>
using std::shared_ptr;
class VanillaOption : public Option
{
public:
class Arguments;
class Engine;
VanillaOption(){}
VanillaOption(const shared_ptr<VanillaPayoff>& thePayoff_, double Exercise_);
double getPayoff(double Spot) const;
void setPayoff(const shared_ptr<VanillaPayoff>& thePayoff_);
double getExercise() const;
void setExercise(double Exercise_);
void setArguments(PricingEngine::Arguments* args);
private:
shared_ptr<VanillaPayoff> thepayoff;
double Exercise;
};
class VanillaOption::Arguments : public Option::Arguments
{
public:
Arguments(){}
shared_ptr<VanillaPayoff> thePayoff_;
double Exercise_;
};
class VanillaOption::Engine : public GenericEngine<VanillaOption::Arguments>
{
public:
Engine()
{}
};
#endif | true |
2561c49c43d8acb2a3afb544b5ff7118fe1406b2 | C++ | kermado/Suborbital | /source/suborbital/component/ComponentRegistry.cpp | UTF-8 | 2,484 | 2.84375 | 3 | [
"MIT"
] | permissive | #include <suborbital/component/ComponentRegistry.hpp>
#include <suborbital/component/AttributeFactory.hpp>
#include <suborbital/component/PythonBehaviourFactory.hpp>
#include <suborbital/component/PythonAttributeFactory.hpp>
namespace suborbital
{
ComponentRegistry::ComponentRegistry()
: m_factory_registry()
{
// Nothing to do.
}
ComponentRegistry::~ComponentRegistry()
{
// Nothing to do.
}
void ComponentRegistry::register_component(const std::string& name, std::unique_ptr<ComponentFactory> factory)
{
m_factory_registry.insert(FactoryRegistry::value_type(name, std::move(factory)));
}
std::unique_ptr<Attribute> ComponentRegistry::create_attribute(const std::string& name) const
{
// We will first attempt to instantiate an attribute registered under the supplied name.
auto iter = m_factory_registry.find(name);
if (iter != m_factory_registry.end())
{
std::unique_ptr<Component> component = iter->second->create();
return std::unique_ptr<Attribute>(dynamic_cast<Attribute*>(component.release()));
}
// If no attribute was registered under the supplied name then we attempt to instantiate a scripted attribute.
// Note that the factory's create function will return a nullptr in the event that it is unable to instantiate
// the attribute.
AttributeFactory<PythonAttribute> factory(name);
return std::unique_ptr<Attribute>(dynamic_cast<Attribute*>(factory.create().release()));
}
std::unique_ptr<Behaviour> ComponentRegistry::create_behaviour(const std::string& name) const
{
// We will first attempt to instantiate a behaviour registered under the supplied name.
auto iter = m_factory_registry.find(name);
if (iter != m_factory_registry.end())
{
std::unique_ptr<Component> component = iter->second->create();
return std::unique_ptr<Behaviour>(dynamic_cast<Behaviour*>(component.release()));
}
// If no behaviour was registered under the supplied name then we attempt to instantiate a scripted behaviour.
// Note that the factory's create function will return a nullptr in the event that it is unable to instantiate
// the behaviour.
BehaviourFactory<PythonBehaviour> factory(name);
return std::unique_ptr<Behaviour>(dynamic_cast<Behaviour*>(factory.create().release()));
}
} | true |
5d89ce1035b9affe9a83fbc6c21ff2fcac543e0c | C++ | Demix361/Algorithm-Analysis | /lab_5/code/processing.cpp | UTF-8 | 1,363 | 3.09375 | 3 | [] | no_license | #include "processing.h"
Processing::Processing(int count, QTime *timer, PostProcessing *p, QMutex *mutex2, QMutex *mutex3)
{
this->_count = count;
this->_timer = timer;
this->_proc = p;
this->_mutex2 = mutex2;
this->_mutex3 = mutex3;
}
void Processing::addToQueue(MyObject obj)
{
_queue.push(obj);
}
void Processing::process()
{
while (processed != _count)
{
if (_queue.size() != 0)
{
// cout << "Processing" << _timer->elapsed() << endl;
MyObject obj = _queue.front();
QThread thread;
obj.setTime(_timer->elapsed());
unsigned long nod = this->nod_pow(obj.get_a(), 11);
obj.set_a(nod);
obj.setTime(_timer->elapsed());
_mutex2->lock();
_queue.pop();
_mutex2->unlock();
_mutex3->lock();
_proc->addToQueue(obj);
_mutex3->unlock();
processed++;
}
}
}
unsigned long Processing::nod_pow(unsigned long a, unsigned long b)
{
unsigned long int nod = 0;
for (unsigned long int i = a; i > 0; i--)
{
if (a % i == 0 && b % i == 0)
{
nod = i;
break;
}
}
unsigned long result = 1;
for (int i = 0; i < 10000000; i++)
result *= nod;
return result;
}
| true |
5b300421f7c8e83c76c14f0812fa217bb7a166cf | C++ | comp413-2017/RDFS | /utility/config-reader/ConfigReader.cc | UTF-8 | 1,621 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <unordered_map>
#include "ConfigReader.h"
#include <pugixml.hpp>
#include <easylogging++.h>
namespace config_reader {
using namespace pugi;
const char *ConfigReader::HDFS_DEFAULTS_CONFIG = "hdfs-default.xml";
ConfigReader::ConfigReader() {
InitHDFSDefaults();
}
int ConfigReader::getInt(std::string key) {
return conf_ints[key];
}
std::string ConfigReader::getString(std::string key) {
return conf_strings[key];
}
bool ConfigReader::getBool(std::string key) {
return conf_bools[key];
}
/**
* Init the hdfs defaults xml file
*/
void ConfigReader::InitHDFSDefaults() {
xml_document doc;
xml_parse_result result = doc.load_file(HDFS_DEFAULTS_CONFIG);
if (!result) {
LOG(ERROR) << "XML [" << HDFS_DEFAULTS_CONFIG << "] parsed with errors, attr value: [" <<
doc.child("node").attribute("attr").value() << "]\n";
LOG(ERROR) << "Error description: " << result.description() << "\n";
}
xml_node properties = doc.child("configuration");
for (xml_node child : properties.children()) {
// the name and value nodes in the xml
xml_node name = child.first_child();
xml_node value = name.next_sibling();
const char *name_str = name.first_child().text().get();
int value_int = value.first_child().text().as_int();
conf_ints[name_str] = value_int;
std::string value_str = value.first_child().text().as_string();
conf_strings[name_str] = value_str;
bool value_bool = value.first_child().text().as_bool();
conf_bools[name_str] = value_bool;
}
LOG(INFO) << "Configured namenode (but not really!)";
}
} //namespace
| true |
db04bf4ca76d673ba793e9bb7d3966c86a6db816 | C++ | BinhNMT/Code_Metric | /CodeMetric_Lib/CommentMetric.h | UTF-8 | 1,599 | 2.578125 | 3 | [] | no_license | /*
* CommentMetric.h
*
* Created on: Apr 11, 2020
* Author: BinhNMT
* Email: binhmainguyen193@gmail.com
*/
#ifndef COMMENTMETRIC_H
#define COMMENTMETRIC_H
#include <string>
using namespace std;
namespace C_M
{
class CommentMetric
{
private:
// @brief : a flag that used to notice in a block comments
// @detail : - True in case of in a block comments
// : - False in case of not in a block comments
bool blockCmt;
// @brief : Verify the doubt code is a comment with twin slash type or not
// @param : pos - position of slash was detected
// codeString - a line of input source code
// @return : true - commented code
// fasle - not a commented code
bool checkTwinSlashCmt(int, string);
// @brief : Verify the doubt code is a comment with block comment type or not
// @param : pos - position of slash was detected
// codeString - a line of input source code
// @return : true - commented code
// fasle - not a commented code
bool checkBlockCmt(int, string);
public:
// @brief : set the default value for blockCmt flag is zero
void setFlagToDefault(void);
// @brief : Verify the doubt code is a comment or not
// @param : pos - position of slash was detected
// codeString - a line of input source code
// @return : 0 - not a commented code
// 1 - commented code
// 2 - block commented code
bool checkCmtCode(string);
};
}
#endif // COMMENTMETRIC_H
| true |
9f40a2d5598c34804ae6a8805e5590ddd3ba1960 | C++ | willjie/LeetCode | /Binary Tree Level Order Traversal II.cpp | GB18030 | 1,575 | 3.859375 | 4 | [] | no_license | /*
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
*/
/*ǰǸ֮ǰַʽ鷴þ*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
queue<TreeNode *> qlist;
vector<vector<int>> v1;
if(root == NULL)
{
return v1;
}
qlist.push(root);
while(!qlist.empty())
{
int size = qlist.size();
vector<int> level;
for(int i = 0; i< size;i++)
{
TreeNode *temp = qlist.front();
qlist.pop();
level.push_back(temp->val);
if(temp->left != NULL)
{
qlist.push(temp->left);
}
if(temp->right != NULL)
{
qlist.push(temp->right);
}
}
v1.push_back(level);
}
std::reverse(v1.begin(),v1.end());
return v1;
}
}; | true |
edba44a0ba7f8df46387c1f39a3ed1fd7cf62e02 | C++ | alexandraback/datacollection | /solutions_5640146288377856_1/C++/Mastojun/main.cpp | UTF-8 | 509 | 2.5625 | 3 | [] | no_license | #include <cstdio>
#include <cmath>
#include <cstring>
#include <vector>
#include <string>
#include <unordered_map>
#include <queue>
#include <algorithm>
using namespace std;
int T;
int R, C, W;
int solve() {
if(C % W == 0) return C / W + W - 1 + C / W * (R - 1);
return C / W + W + C / W * (R - 1);
}
int main() {
scanf("%d", &T);
for(int Case = 1; Case <= T; Case++) {
scanf("%d %d %d", &R, &C, &W);
printf("Case #%d: %d\n", Case, solve());
}
return 0;
}
| true |
44de6ab05c8a85a3b9bf9597a75ef8e2f2d5288d | C++ | A-Day-in-the-Woods/A-Day-in-the-Woods | /ARGO/ARGO/MenuScreen.h | UTF-8 | 1,607 | 2.609375 | 3 | [] | no_license | #ifndef MENU
#define MENU
#include <SDL.h>
#include <SDL_image.h>
#include <iostream>
#include <Game.h>
#include <Player.h>
#include <InputSystem.h>
#include "CharacterFactory.h"
#include"AudioManager.h"
class Game;
class MenuScreen
{
public:
MenuScreen(Game& game, SDL_Renderer* t_renderer, SDL_Event &event, GameState& t_currentState, InputSystem& t_inputSystem, std::vector<Player*> t_entity, AudioManager & t_audioManager );
~MenuScreen();
void update();
void render();
void processEvent();
void setGameState();
Factory* m_factory;
std::vector<Character*> m_characters;
private:
int m_numberPlayers;
Game& m_game;
SDL_Renderer* m_renderer; // game renderer
SDL_Event& m_event;
GameState& m_currentState;
InputSystem m_inputSystem;
std::vector<Player*> m_entity;
const int MENU_NUM = 4;
int m_currentButton = 0;
//Background
SDL_Texture* m_backgroundTexture;
//Background
SDL_Texture* m_titleTexture;
SDL_Rect m_titleRect;
//Selector for Buttons
std::vector <SDL_Texture*> m_buttonSelectorTexture; // button texture
std::vector <SDL_Texture*> m_buttonSelectorTextureTwo; // button texture
std::vector<SDL_Rect> m_buttonSelectorRect;
std::vector<SDL_Rect> m_buttonSelectorRectTwo;
bool flip{true};
//Buttons
std::vector <SDL_Texture*> m_menuButtonTexture;
std::vector<SDL_Rect> m_menuButtonPosition;
std::vector<SDL_Rect> m_menuButtonPositionSelected;
SDL_AudioSpec wavSpec;
Uint32 wavLength;
Uint8* wavBuffer;
SDL_AudioDeviceID deviceId;
bool audioPlaying = false;
//bee
SDL_Texture* m_beeTexture;
AudioManager & m_audioManager;
};
#endif // MENU | true |
4f5262af977d32d3fa5fb31280ea6b537f54e0bc | C++ | avovana/tasks | /olympiad_tasks/1313.cpp | UTF-8 | 2,096 | 3.1875 | 3 | [] | no_license | // Task - http://acm.timus.ru/problem.aspx?space=1&num=1313&locale=en
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <limits>
using Raw = std::vector<unsigned int>;
struct Node
{
size_t index{0};
Raw raw;
};
using Matrix = std::vector<Node>;
auto getMatrix()
{
size_t matrixDim;
std::cin >> matrixDim;
std::cin.ignore();
Matrix matrix;
matrix.reserve(matrixDim);
unsigned int pixel;
Raw currentRaw;
currentRaw.reserve(matrixDim);
auto raws = matrixDim;
while(raws--)
{
for(auto elements = matrixDim; elements; --elements)
{
std::cin >> pixel;
currentRaw.push_back(pixel);
}
matrix.push_back({0, currentRaw});
currentRaw.clear();
}
return matrix;
}
auto getSequence(Matrix& matrix)
{
Raw sequence;
sequence.reserve(matrix.size() * matrix.size());
for(size_t i = 0; i < matrix.size(); ++i)
{
for(size_t j = i; j != std::numeric_limits<std::size_t>::max(); --j)
{
auto curr = matrix[j].index;
if(curr < matrix[j].raw.size())
{
sequence.push_back(matrix[j].raw[curr]);
matrix[j].index++;
}
}
}
auto lastRaw = matrix[matrix.size() - 1];
for(size_t i = lastRaw.index; i < lastRaw.raw.size(); ++i)
{
for(size_t j = matrix.size() - 1; j != std::numeric_limits<std::size_t>::max(); --j)
{
auto curr = matrix[j].index;
if(curr < matrix[j].raw.size())
{
sequence.push_back(matrix[j].raw[curr]);
matrix[j].index++;
}
}
}
return sequence;
}
int main()
{
try
{
auto matrix = getMatrix();
auto sequence = getSequence(matrix);
for(const auto& el : sequence)
std::cout << el << " ";
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
}
} | true |
ea407132742fa6e2903ae48eb372439459a22f91 | C++ | Coutinho020/Apontamentos-ISEC | /2ºAno/1ºSemestre/POO/TP/TP_POO/TP_POO/imperio.cpp | ISO-8859-1 | 8,693 | 2.703125 | 3 | [] | no_license | #include "imperio.h"
Imperio::Imperio()
{
territorios.push_back(new TerrInic());
}
Imperio::Imperio(const Imperio& imp) {
*this = imp;
}
Imperio& Imperio::operator=(const Imperio& imp) {
cofre = imp.cofre;
armazem = imp.armazem;
forca_militar = imp.forca_militar;
pontos_vitoria = imp.pontos_vitoria;
sorte = imp.sorte;
num_tecnologia = imp.num_tecnologia;
drones_militares = imp.drones_militares;
misseis_teleguiados = imp.misseis_teleguiados;
defesas_territoriais = imp.defesas_territoriais;
bolsa_valores = imp.bolsa_valores;
banco_central = imp.banco_central;
// limpamos a memoria
for (auto i : territorios) {
delete i;
}
territorios.clear();
// escreve
for (size_t i = 0; i < imp.territorios.size(); i++) {
territorios.push_back(imp.territorios[i]->clone());
}
return *this;
}
Imperio::~Imperio()
{
// limpa os ponteiros do vector territorios
for (auto i : territorios) {
delete i;
}
territorios.clear();
}
int Imperio::getFSorte() {
srand((unsigned int)time(NULL));
int f_sorte = (rand() % 5 + 1) + forca_militar;
sorte = f_sorte;
return f_sorte;
}
void Imperio::setContaTecnologia() {
if (drones_militares)
num_tecnologia++;
if (misseis_teleguiados)
num_tecnologia++;
if (defesas_territoriais)
num_tecnologia;
if (bolsa_valores)
num_tecnologia++;
if (banco_central)
num_tecnologia++;
}
bool Imperio::insereTerritorio(Territorio* t) {
if (t == nullptr)
return false;
territorios.push_back(t);
return true;
}
string Imperio::getAsString()const {
ostringstream os;
int max_ouro_prod, max_forca_militar;
if (banco_central)
max_ouro_prod = 5;
else
max_ouro_prod = 3;
if (drones_militares)
max_forca_militar = 5;
else
max_forca_militar = 3;
os <<" Ouro no cofre: " << cofre << " Produtos no armazem: " << armazem << " Valor Max. de Recursos: " << max_ouro_prod << endl
<< " Forca militar: " << forca_militar << " Valor Max. de Forca Militar: "<< max_forca_militar << endl
<< " Pontos de vitoria: " << pontos_vitoria << " Fator sorte: " << sorte << endl;
return os.str();
}
string Imperio::getInfoTecnologias()const {
ostringstream os;
os <<endl<< "Tecnologias Existentes" << endl;
os << "=========================" << endl << endl;
os << "Drones Militares (3 de ouro) -> Aumenta nivel maximo da Forca Militar para 5 -> ";
(drones_militares) ? os << "Adquirida\n" : os << "Nao Adquirida" << endl;
os << "Misseis Teleguiados (4 de ouro) -> Permite o utilizador conquistar ilhas -> ";
(misseis_teleguiados) ? os << " Adquirida\n" : os << " Nao Adquirida" << endl;
os << "Defesas Territoriais (4 de ouro) -> Acrescenta 1 unidade de resistencia ao ultimo Territorio conquistado -> ";
(defesas_territoriais) ? os << " Adquirida\n" : os << " Nao Adquirida" << endl;
os << "Bolsa de Valores (2 de ouro) -> Torna possiveis as trocas entre produtos e ouro 'maisouro' e 'maisprod' -> ";
(bolsa_valores) ? os << " Adquirida\n" : os << " Nao Adquirida" << endl;
os << "Banco Central (3 de ouro) -> Aumenta a capacidade mxima do armazem e do cofre -> ";
(banco_central) ? os << " Adquirida\n" : os << " Nao Adquirida" << endl;
return os.str();
}
string Imperio::getTerritorios()const {
ostringstream os;
os << endl;
os << "\t============================" << endl
<< "\t|| Territorios do Imperio ||" << endl
<< "\t============================" << endl << endl;
for (auto imp : territorios)
os << imp->getAsString();
return os.str();
}
string Imperio::getTecnologias()const {
ostringstream os;
int conta = 0;
os << " Tecnologias: ";
if (drones_militares) {
os << "Drones Militares" << " / ";
conta++;
}
if (misseis_teleguiados) {
os << "Misseis Teleguiados" << " / ";
conta++;
}
if (defesas_territoriais) {
os << "Defesas Territorias" << " / ";
conta++;
}
if (bolsa_valores) {
os << "Bolsa de Valores" << " / ";
conta++;
}
if (banco_central) {
os << "Banco Central";
conta++;
}
if (conta == 0)
os << "Nao tem nenhuma Tecnologia";
return os.str();
}
bool Imperio::conqIlha() {
if (misseis_teleguiados && territorios.size() >= 5)
return true;
return false;
}
void Imperio::setPontosVitoria(Territorio* t) {
if (t->getTipo() == "Ilha") {
pontos_vitoria += 2;
}
else {
pontos_vitoria += 1;
}
}
bool Imperio::setRecolher(int ano, int turno) {
int aux_ouro = 0, aux_prod = 0, aux_c = 0, aux_a = 0, soma_a = 0, soma_c = 0;
for (Territorio *t : territorios) {
if (banco_central) {
aux_ouro = 0, aux_prod = 0;
t->recolher(ano, turno, &aux_ouro, &aux_prod);
soma_a = armazem + aux_prod;
soma_c = cofre + aux_ouro;
if (soma_c >= 5 && soma_a >= 5) {
cofre = 5;
armazem = 5;
}
else if (soma_c >= 5 && soma_a < 5) {
cofre = 5;
armazem = soma_a;
}
else if (soma_c < 5 && soma_a >= 5) {
cofre = soma_c;
armazem = 5;
}
else if (soma_c < 5 && soma_a < 5) {
cofre = soma_c;
armazem = soma_a;
}
}
if (!banco_central) {
aux_ouro = 0, aux_prod = 0;
t->recolher(ano, turno, &aux_ouro, &aux_prod);
soma_a = armazem + aux_prod;
soma_c = cofre + aux_ouro;
if (soma_c >= 3 && soma_a >= 3) {
cofre = 3;
armazem = 3;
}
else if (soma_c >= 3 && soma_a < 3) {
cofre = 3;
armazem = soma_a;
}
else if (soma_c < 3 && soma_a >= 3) {
cofre = soma_c;
armazem = 3;
}
else if(soma_c < 3 && soma_a < 3){
cofre = soma_c;
armazem = soma_a;
}
}
}
return true;
}
bool Imperio::setMaisOuro() {
if (bolsa_valores && !banco_central) {
if (armazem >= 2 && cofre < 3) {
cofre += 1;
armazem -= 2;
return true;
}
else if (armazem < 2 || cofre >= 3)
return false;
}
else if (bolsa_valores && banco_central) {
if (armazem >= 2 && cofre < 5) {
cofre += 1;
armazem -= 2;
return true;
}
else if (armazem < 2 || cofre >= 5)
return false;
}
return false;
}
bool Imperio::setMaisProd() {
if (bolsa_valores && !banco_central) {
if (cofre >= 2 && armazem < 3) {
armazem += 1;
cofre -= 2;
return true;
}
else if (cofre < 2 || armazem >= 3)
return false;
}
else if (bolsa_valores && banco_central) {
if (cofre >= 2 && armazem < 5) {
armazem += 1;
cofre -= 2;
return true;
}
else if (cofre < 2 || armazem >= 5)
return false;
}
return false;
}
bool Imperio::setMaisMilitar() {
if (drones_militares && forca_militar < 5) {
armazem -= 1;
cofre -= 1;
forca_militar += 1;
return true;
}
else if (!drones_militares && forca_militar < 3) {
armazem -= 1;
cofre -= 1;
forca_militar += 1;
return true;
}
return false;
}
bool Imperio::setDronesMilitares() {
if (cofre >= 3 && !drones_militares) {
drones_militares = true;
cofre -= 3;
return true;
}
return false;
}
bool Imperio::setMisseisTeleguiados() {
if (cofre >= 4 && !misseis_teleguiados) {
misseis_teleguiados = true;
cofre -= 4;
return true;
}
return false;
}
bool Imperio::setDefesasTerritoriais() {
if (cofre >= 4 && !defesas_territoriais) {
defesas_territoriais = true;
cofre -= 4;
return true;
}
return false;
}
bool Imperio::setBolsaValores() {
if (cofre >= 2 && !bolsa_valores) {
bolsa_valores = true;
cofre -= 2;
return true;
}
return false;
}
bool Imperio::setBancoCentral() {
if (cofre >= 3 && !banco_central) {
banco_central = true;
cofre -= 3;
return true;
}
return false;
}
bool Imperio::recAbandonado(int ano) {
if (ano == 1) { // ser produtos
if (banco_central && armazem < 5 || !banco_central && armazem < 3) {
armazem++;
return true;
}
return false;
}
if (ano == 2) { // SERA OURO
if (banco_central && cofre < 5 || !banco_central && cofre < 3) {
cofre++;
return true;
}
return false;
}
return false;
}
int Imperio::evenInvasao(int ano) {
srand((unsigned int)time(NULL));
int fator_sorte, resultado;
fator_sorte = (rand() % 6 + 1);
if (ano == 1)
fator_sorte += 2;
else if (ano == 2)
fator_sorte += 3;
resultado = fator_sorte;
// se tiver a tecnologia Defesas Territoriais
if (defesas_territoriais)
territorios.back()->setResistencia(territorios.back()->getResistencia() + 1);
if (resultado < territorios.back()->getResistencia()) {
return 0; // retorna 0 se a invasao falhar
}
else {
// foi feita a invasao
territorios.pop_back();
//se es o vector ficar vazio porque o Territorio Inicial foi conquistado
if (territorios.empty())
return 2;
return 1;
}
}
bool Imperio::aliDiplomatica() {
// fora militar entre 0 e 3 mas no max 5
if (drones_militares && forca_militar < 5 || !drones_militares && forca_militar < 3) {
forca_militar++;
return true;
}
return false;
} | true |
8b12c46499166a3a9780d09c8476e9421dcaa33b | C++ | krishna-mathuria/competitive | /dsasheet432.cpp | UTF-8 | 1,847 | 3.109375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
bool sumZero(int temp[], int* starti,int* endj, int n)
{
map<int, int> presum;
int sum = 0; // Initialize sum of elements
int max_length = 0;
for (int i = 0; i < n; i++)
{
sum += temp[i];
if (temp[i] == 0 && max_length == 0)
{
*starti = i;
*endj = i;
max_length = 1;
}
if (sum == 0)
{
if (max_length < i + 1)
{
*starti = 0;
*endj = i;
}
max_length = i + 1;
}
if (presum.find(sum) != presum.end())
{
int old = max_length;
max_length = max(max_length, i - presum[sum]);
if (old < max_length)
{
*endj = i;
*starti = presum[sum] + 1;
}
}
else
presum[sum] = i;
}
return (max_length != 0);
}
void sumZeroMatrix(int a[][MAX], int row, int col)
{
int temp[row];
int fup = 0, fdown = 0, fleft = 0, fright = 0;
int sum;
int up, down;
int maxl = INT_MIN;
for (int left = 0; left < col; left++)
{
memset(temp, 0, sizeof(temp));
for (int right = left; right < col; right++)
{
for (int i = 0; i < row; i++)
temp[i] += a[i][right];
bool sum = sumZero(temp, &up, &down, row);
int ele = (down - up + 1) * (right - left + 1);
if (sum && ele > maxl)
{
fup = up;
fdown = down;
fleft = left;
fright = right;
maxl = ele;
}
}
}
if (fup == 0 && fdown == 0 && fleft == 0 &&
fright == 0 && a[0][0] != 0) {
cout << "No zero-sum sub-matrix exists";
return;
}
// Print final values
for (int j = fup; j <= fdown; j++)
{
for (int i = fleft; i <= fright; i++)
cout << a[j][i] << " ";
cout << endl;
}
}
// Driver program to test above functions
int main()
{
int a[][MAX] = { { 9, 7, 16, 5 }, { 1, -6, -7, 3 },
{ 1, 8, 7, 9 }, { 7, -2, 0, 10 } };
int row = 4, col = 4;
sumZeroMatrix(a, row, col);
return 0;
}
| true |
66ab3135666480007478a919b58452d57f72e497 | C++ | Carson13331145/TALK_ROBOT | /Robot/robot_v2.0/algorithm.h | UTF-8 | 2,928 | 3.0625 | 3 | [] | no_license | #ifndef ALGORITHM_H
#define ALGORITHM_H
#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
using namespace std;
char* string_to_char(string src) {
char *ch = new char[src.length()+1];
for (int i = 0; i < src.length(); i++) {
ch[i] = src[i];
}
ch[src.length()] = '\0';
return ch;
}
bool find_words(const string src, string str[], int num) {
string source = src;
transform(source.begin(), source.end(), source.begin(), ::tolower);
char *chs = string_to_char(source);
char *tmp = string_to_char(str[0]);
char *p = strstr(chs , tmp);
if (p == NULL) return false;
for (int i = 1; i < num; i++) {
tmp = string_to_char(str[i]);
p = strstr(p+1 , tmp);
if (p == NULL) return false;
}
return true;
}
void get_time(const string str, int& y, int& m, int& d) {
int pos = 0;
int pos_m = 0;
int pos_d = 0;
int pos_y = 0;
char month[1024];
char day[1024];
char year[1024];
while (str[pos] != '/') {
year[pos_y++] = str[pos++];
}
while (str[pos+1] != '/') {
month[pos_m++] = str[++pos];
}
pos++;
while (str[pos+1] != '\n') {
day[pos_d++] = str[++pos];
}
for (int i = pos_y-1; i >= 0; i--) {
if (i == 0) {
y += (year[i]-'0')*1000;
} else if (i == 1) {
y += (year[i]-'0')*100;
} else if (i == 2) {
y += (year[i]-'0')*10;
} else if (i == 3) {
y += year[i]-'0';
}
}
for (int i = pos_m-1; i >= 0; i--) {
if (pos_m == 2) {
if (i == 1) {
m += month[i]-'0';
} else {
m += (month[i]-'0')*10;
}
} else {
m += month[i]-'0';
}
}
for (int i = pos_d-1; i >= 0; i--) {
if (pos_d == 2) {
if (i == 1) {
d += day[i]-'0';
} else {
d += (day[i]-'0')*10;
}
} else {
d += day[i]-'0';
}
}
}
int ldistance(const string src, const string tar)
{
string source = src;
string target = tar;
transform(source.begin(), source.end(), source.begin(), ::tolower);
transform(target.begin(), target.end(), target.begin(), ::tolower);
int n=source.length();
int m=target.length();
if (m==0) return n;
if (n==0) return m;
typedef vector< vector<int> > Tmatrix;
Tmatrix matrix(n+1);
for(int i=0; i<=n; i++) matrix[i].resize(m+1);
for(int i=1;i<=n;i++) matrix[i][0] = i;
for(int i=1;i<=m;i++) matrix[0][i] = i;
for(int i=1;i<=n;i++)
{
const char si=source[i-1];
for(int j=1;j<=m;j++)
{
const char dj=target[j-1];
int cost;
if(si == dj) {
cost = 0;
}
else {
cost = 1;
}
const int above = matrix[i-1][j]+1;
const int left = matrix[i][j-1]+1;
const int diag = matrix[i-1][j-1]+cost;
matrix[i][j] = min(above,min(left,diag));
}
}
return matrix[n][m];
}
#endif
| true |
f5ea144b1e8675dfa94de3a863fc6bb35945eb73 | C++ | jiwon4178/practice | /2020-09-02-1.cpp | UTF-8 | 1,538 | 3.25 | 3 | [] | no_license | #include <string>
#include <vector>
#include <algorithm>
#include <queue>
//https://programmers.co.kr/learn/courses/30/lessons/49189
int solution(int n, std::vector<std::vector<int>> edge) {
int answer = 0;
std::vector<int> dv(n,0); // 거리에 따른 개수 기록용
// 반대 간선도 넣기
int s = edge.size();
for(int i=0;i<s;i++){
std::vector<int> temp;
temp.push_back(edge[i][1]);
temp.push_back(edge[i][0]);
edge.push_back(temp);
}
sort(edge.begin(), edge.end()); // 출발 정점 기준 정렬
std::vector<bool> check(n+1); // 방문 체크용
// bfs를 통해 가장 먼 거리의 노드들 추가
std::queue<std::pair<int,int>> q; // index, 거리
q.push(std::pair<int,int>(1,1));
check[1] = true; // visit
// BFS
while(!q.empty()){
std::pair<int,int> now_p = q.front();
int now = now_p.first; // 현재 경로
int now_d = now_p.second; // 현재 거리
q.pop();
// 갈 수 있고 가지 않은 곳들 추가
for(int i=0;i<edge.size();i++){
if(edge[i][0] == now && !check[edge[i][1]]){
q.push(std::pair<int,int>(edge[i][1], now_d+1));
check[edge[i][1]] = true; // visit
dv[now_d]++; // 거리마다 기록
}
}
}
// 가장 멀리 떨어져 있는 노드 수
reverse(dv.begin(), dv.end());
for(int i=0;i<dv.size();i++)
if(dv[i]!=0)
return dv[i];
} | true |
0fa83348be723b732b797d08ad268ebdd44bb350 | C++ | SnigdhaD/MorphIO | /src/mitochondria.cpp | UTF-8 | 962 | 2.71875 | 3 | [] | no_license | #include <morphio/mito_section.h>
#include <morphio/mitochondria.h>
namespace morphio {
const MitoSection Mitochondria::section(const uint32_t& id) const
{
return MitoSection(id, _properties);
}
const std::vector<MitoSection> Mitochondria::sections() const
{
std::vector<MitoSection> sections_;
for (unsigned int i = 0;
i < _properties->get<morphio::Property::MitoSection>().size(); ++i) {
sections_.push_back(section(i));
}
return sections_;
}
const std::vector<MitoSection> Mitochondria::rootSections() const
{
std::vector<MitoSection> result;
try {
const std::vector<uint32_t>& children = _properties->children<morphio::Property::MitoSection>().at(-1);
result.reserve(children.size());
for (auto id : children) {
result.push_back(section(id));
}
return result;
} catch (const std::out_of_range&) {
return result;
}
}
} // namespace morphio
| true |
c3ace4616f32025d6c3d9efc5e6b4426788d2cfd | C++ | chenna1199/Data-Structures-Algorithms-Handbook | /Trees/Left-View-of-Binary-Tree.cpp | UTF-8 | 2,073 | 3.703125 | 4 | [
"MIT"
] | permissive | // Given a Binary Tree, print Left view of it. Left view of a Binary Tree is set of nodes visible when tree is visited from Left side. The task is to complete the function leftView(), which accepts root of the tree as argument.
// Left view of following tree is 1 2 4 8.
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
// \
// 8
// Example 1:
// Input:
// 1
// / \
// 3 2
// Output: 1 3
// Example 2:
// Input:
// Output: 10 20 40
// Your Task:
// You just have to complete the function leftView() that prints the left view. The newline is automatically appended by the driver code.
// Expected Time Complexity: O(N).
// Expected Auxiliary Space: O(Height of the Tree).
// Constraints:
// 0 <= Number of nodes <= 100
// 1 <= Data of a node <= 1000
// ITERATIVE
vector<int> ans;
void solve(Node* root){
if(!root) return;
queue<Node*> q;
q.push(root);
while(!q.empty()){
int n = q.size();
for(int i=1; i<=n; i++){
Node* temp = q.front();
q.pop();
if(i==1)
ans.push_back(temp->data);
if(temp->left!=NULL) q.push(temp->left);
if(temp->right!=NULL) q.push(temp->right);
}
}
}
//Function to return a list containing elements of left view of the binary tree.
vector<int> leftView(Node *root)
{
if(root == NULL) return ans;
solve(root);
return ans;
}
// RECURSIVE
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
void leftView(TreeNode* root, vector<int> &ans, int n){
if(!root) return;
if(ans.size() == n)
ans.push_back(root->val);
leftView(root->left, ans, n+1);
leftView(root->right, ans, n+1);
}
vector<int> Solution::solve(TreeNode* root) {
vector<int> ans;
leftView(root, ans, 0);
return ans;
}
| true |
e4dfd2c1e40c426df08478cb2ae217fda5848faa | C++ | MoeMod/Thanatos-Launcher | /Interface/IGameUIFuncs.h | UTF-8 | 2,429 | 2.609375 | 3 | [] | no_license | #ifndef IGAMEUIFUNCS_H
#define IGAMEUIFUNCS_H
#include <interface.h>
#include "vgui/VGUI2.h"
#include "vgui/KeyCode.h"
#include "modes.h"
/**
* Provides a number of GameUI functions.
*/
class IGameUIFuncs : public IBaseInterface
{
public:
/**
* Gets whether a key is down or not.
* @param keyname Key whose state should be queried.
* @param isdown If the key exists, whether the key is down or not.
* @return Whether the given key exists or not.
*/
virtual bool IsKeyDown( const char* keyname, bool& isdown ) = 0;
/**
* @param keynum Key ID.
* @return The name of the given key code.
*/
virtual const char* Key_NameForKey( int keynum ) = 0;
/**
* @param keynum Key code.
* @return String that is executed when the key is pressed, or an empty string if it isn't bound.
*/
virtual const char* Key_BindingForKey( int keynum ) = 0;
/**
* @param bind Binding to look up the key for.
* @return Key code of the key that is bound to the binding.
*/
virtual vgui2::KeyCode GetVGUI2KeyCodeForBind( const char* bind ) = 0;
/**
* Gets the array of video modes. The array is guaranteed to remain in memory up until shutdown.
* @param liststart Pointer to pointer to an array of modes.
* @param count Number of modes stored in the array.
*/
virtual void GetVideoModes( vmode_t** liststart, int* count ) = 0;
/**
* Gets the current video mode.
* @param wide Width of the screen.
* @param tall Height of the screen.
* @param bpp Bits Per Pixel.
*/
virtual void GetCurrentVideoMode( int* wide, int* tall, int* bpp ) = 0;
/**
* Gets the current renderer's information.
* @param name Name of the renderer.
* @param namelen Size of pszName in bytes.
* @param windowed Whether the game is currently in windowed mode.
* @param hdmodels Whether the game checks the _hd directory.
* @param addons_folder Whether the game checks the _addon directory.
* @param vid_level Video level. Affects window scaling and anti aliasing.
*/
virtual void GetCurrentRenderer(char* name, int namelen, int* windowed) = 0;
/**
* @return Whether the client is currently connected to a VAC secure server.
*/
virtual bool IsConnectedToVACSecureServer() = 0;
/**
* @return Key code of a given key name. Returns -1 if the key doesn't exist.
*/
virtual int Key_KeyStringToKeyNum( const char* pchKey ) = 0;
};
#define ENGINE_GAMEUIFUNCS_INTERFACE_VERSION "VENGINE_GAMEUIFUNCS_VERSION001"
#endif // IGAMEUIFUNCS_H
| true |
59f86f98113c2f58e33e9ffd260bfb7f5069a850 | C++ | LU-JIANGZHOU/Cpp-Snippets | /Cpp-Snippets-02-constexpr/main.cpp | UTF-8 | 720 | 3.1875 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
#define LEN 10
int len_foo()
{
int i = 2;
return i;
}
constexpr int len_foo_constexpr()
{
return 5;
}
constexpr int len_foo_constexpr(const int n)
{
if (n < -1)
return -1;
else if (n > 1)
return 1;
else
return 0;
}
int main()
{
char arr01[10]; // ok
char arr02[LEN]; // ok
int len = 10;
char arr03[len]; // run time allocate
const int len_2 = len + 1;
constexpr int len_2_constexpr = 1 + 2 + 3;
char arr04[len_2]; //ok for GCC 9.x
arr04[0] = 'h';
arr04[1] = 'e';
char arr05[len_2_constexpr]; //compile time allocated
char arr06[len_foo() + 5]; //
char arr07[len_foo_constexpr() + 1]; //
return EXIT_SUCCESS;
}; | true |
be3cdba7d73e90e68f6cbc03c9f3562c3cb58804 | C++ | vinayrn12/gfg_interview_questions | /Dynamic programming/Longest common Subsequence/Edit distance/main.cpp | WINDOWS-1258 | 855 | 3.28125 | 3 | [] | no_license | /*
Given two strings str1 and str2 and below operations that can performed on str1.
Find minimum number of edits (operations) required to convert str1 into str2.
Insert
Remove
Replace
*/
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s1, s2;
getline(cin, s1);
getline(cin, s2);
int n = s1.length();
int m = s2.length();
vector<vector<int>> tab(n+1, vector<int>(m+1));
for(int i=0; i<=n; i++)
tab[i][0] = i;
for(int j=0; j<=m; j++)
tab[0][j] = j;
for(int i=1; i<=n; i++){
for(int j=1; j<=m; j++){
if(s1[i-1] == s2[j-1])
tab[i][j] = tab[i-1][j-1];
else
tab[i][j] = 1 + min(tab[i-1][j], min(tab[i][j-1], tab[i-1][j-1]));
}
}
cout<<tab[n][m];
return 0;
}
| true |
9ea5b3c68e77fe303555d9c566e59e9a1b911126 | C++ | javileyes/curso-cpp | /Dia22/lst22-04.cxx | ISO-8859-1 | 588 | 2.953125 | 3 | [] | no_license | // Listado 22.4 Muestra el uso de control de versiones
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int tirarDado(void);
main (int argc, char * argv[])
{
int i;
int iIter;
int Dado[ 6 ];
if(argc < 2)
{
printf("Uso: %s n\n", argv[0]);
return 1;
}
iIter = atoi(argv[1]);
memset(Dado, 0, sizeof(Dado));
printf("$Header$\n");
for(i = 0; i < iIter; i++)
{
Dado[ tirarDado() - 1 ]++;
}
printf("%d tiradas\n", iIter);
printf("\tNmero\tTiradas\n");
for(i = 0; i < 6; i++)
{
printf("\t%d :\t%d\n", i + 1, Dado[i]);
}
}
| true |
bb7e3d6183052490666b36ae5d4b0b30b0bcf404 | C++ | ded1ad/Progream_Files-Bookqt- | /3.6.2.cpp | WINDOWS-1251 | 647 | 2.984375 | 3 | [
"Unlicense"
] | permissive | // ++. x y. -
//, (x; y) .
// . 3.613.85.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
float x, y;
cout << "x=";
cin >> x;
cout << "y=";
cin >> y;
if (y <= 0 && y >= -4 * x - 12 && y >= -4 && y >= 4 * x - 12)
cout << "In the region" << endl;
else
cout << "Not in the region" << endl;
return 0;
}
| true |
a7318c9b7378fd75f7616a5775224dc440c04c6e | C++ | AeonFlor/Algorithm | /BOJ/BOJ_10798.cpp | UTF-8 | 706 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(void)
{
vector<string> arr(5);
string line;
for(int i=0; i<5; ++i)
{
getline(cin,line);
arr[i]=line;
}
for(int i=0; i<15; ++i)
{
for(int j=0; j<5; ++j)
{
if(arr[j].length()>i)
cout<<arr[j][i];
}
}
}
// printf 와 scanf 로도 풀 수 있었다.
// scanf 로만 풀 경우 char arr[5][16] 으로 선언하고 scanf("%s", arr[i]); 로 for 문 돌리면 됐다.
// 그리고 printf 의 경우 scanf 를 쓸 때 마지막에 자동으로 null 이 들어가므로 if(arr[j][i]) 있는지 판단하면 된다.
// 이렇게 되면 vector 를 쓰지않고 string 배열로만 풀 수 있었다.
| true |
7f33f5185e1eaab854802183b49660955f59270c | C++ | vshreyas/serialize | /binary_streamwriter.hpp | UTF-8 | 2,854 | 3.296875 | 3 | [] | no_license | /**
* @file binary_streamwriter.hpp
* @author Shreyas Vinayakumar
* @date Tue Dec 4 17:39:19 2012
*
* @brief Classes/methods to serialize binary data in a compact format
* Expected to be used for native data i.e. currently non-portable. Will be extended to portable also in next revision
*/
#ifndef BINARY_STREAMWRITER_HPP
#define BINARY_STREAMWRITER_HPP
#include "streamwriter.hpp"
#include "stl_serialize.hpp"
#include <cstddef>
#include <type_traits>
class BinaryStreamWriter: public StreamWriter
{
public:
/**
* Constructed from an output stream which could be any sequential access
*/
BinaryStreamWriter(std::ostream&m_stream): StreamWriter(m_stream) {
}
~BinaryStreamWriter();
template <typename T>
typename std::enable_if<std::is_fundamental<T>::value>::type
save(const T & T_data)
{
write_data(T_data);
}
void save(const std::string & string_data)
{
write_data(string_data);
}
template <typename T>
typename std::enable_if<std::is_class<T>::value>::type
save(const T & T_data)
{
//serialize(*this, T_data);
}
template <typename T>
typename std::enable_if<std::is_polymorphic<T>::value>::type
save(T* T_data)
{
write_type(T_data);
//write_type(T_data);
//serialize(*this, T_data);
}
template <typename T>
typename std::enable_if<std::is_array<T>::value>::type
save(const T & T_data)
{
// number of elements
size_t length = std::extent<T>::value;
*this<<length;
for (size_t i = 0; i < length; ++i)
*this<<T_data[i];
}
private:
template <class T>
void write_data(const T & T_data)
{
stream->write(reinterpret_cast<const char*>(&T_data), sizeof(T_data));
}
/**
* Write a given char*, assuming it to be a C-style string.
* Format: <length><one space><cstring data>
*
* @param cstring_data given char* whose data is to be written
*/
void write_data(const char* cstring_data)
{
size_t slen = 0;
while (cstring_data[slen] != '\0')
slen++;
stream->write(reinterpret_cast<const char*>(&slen), sizeof(slen));
stream->write(cstring_data, slen);
}
void write_data(const std::string& string_data)
{
size_t slen = string_data.size();
stream->write(reinterpret_cast<const char*>(&slen), sizeof(slen));
stream->write(string_data.c_str(), string_data.size());
}
/**
* Serialize pointers to polymorphic objects
* Must write the type key also as there is no other way to know what object it represents at runtime
* @param T* pointer to polymorphic base class
*/
template <class T>
typename std::enable_if<std::is_polymorphic<T>::value>::type
write_type(T* & T_data)
{
std::string type_key(InfoList<BinaryStreamWriter>::get_matching_type(T_data)->key());
*this<<type_key;
}
};
BinaryStreamWriter::~BinaryStreamWriter()
{
}
#endif
| true |
55cdf66563743ceff8c2c67b9ae7578969be6ef4 | C++ | broccolism/study_with_alcohol | /3_DP/broccolism_1890_jump.cpp | UTF-8 | 944 | 3.046875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int BOARD[101][101] = {};
long long CASE[101][101] = {};
int N;
/*dp() return type을 int로 해서 제출하니까 자꾸 틀림ㅋㅋ
으악*/
long long dp()
{
CASE[0][0] = (long long)1;
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N; ++j)
{
for (int x = 1; x < 10; ++x)
{
//check vertical line first
if (i - x > -1 && BOARD[i - x][j] == x)
CASE[i][j] += CASE[i - x][j];
//check horizontal line
if (j - x > -1 && BOARD[i][j - x] == x)
CASE[i][j] += CASE[i][j - x];
}
}
}
return CASE[N - 1][N - 1];
}
int main()
{
//get input!
cin >> N;
for (int i = 0; i < N; ++i)
for (int j = 0; j < N; ++j)
cin >> BOARD[i][j];
printf("%ld\n", dp());
} | true |
ccd96f476732d6222b1363e3dfb7a5487d307f08 | C++ | yogesh019/DataStructures | /HashTable/stringContainsAtMostNDifferentCharacters.cpp | UTF-8 | 589 | 3.578125 | 4 | [] | no_license | #include<iostream>
#include<string>
#include<unordered_set>
using namespace std;
bool CheckCount(const string&s,int N){
unordered_set<char>check;
int i=0;
while(s[i]){
check.insert(s[i]);
i++;
}
return check.size()<=N;
}
int main(){
string s;
int N;
cout<<"Enter string: ";
getline(cin,s);
cout<<"Enter N: ";
cin>>N;
if(CheckCount(s,N)){
cout<<"string contains at most "<<N<<"different characters"<<endl;
}
else{
cout<<"string contains more no. of characters than required";
}
return 0;
}
| true |
408eadf095b60129d1a3b48164f7a54e46c12f3e | C++ | shadab16/ProjectEuler | /src/78.cpp | UTF-8 | 668 | 2.75 | 3 | [] | no_license | #include <iostream>
const long limit = 100000;
const long mod = 1e6;
const long sign[2] = {-1, 1};
// Partition cache
long partition[limit] = {1};
int main() {
long n = 0;
while (++n < limit) {
for (long k = 1; k <= n; ++k) {
const long long p1 = (k * (3 * k - 1)) / 2;
if (n - p1 < 0) {
// n-p1 < 0, so p[n-p1] = 0
// n-p1-k is also < 0, so p[n-(p1+k)] = 0
break;
}
long terms = partition[n - p1];
if (n - p1 - k >= 0) {
terms += partition[n - p1 - k];
}
partition[n] += sign[k % 2] * terms;
}
partition[n] %= mod;
if (partition[n] == 0) {
std::cout << n << std::endl;
break;
}
}
return 0;
}
| true |
9a561a862c1e24506eb9d4c5abec33818f12fb04 | C++ | shipoyewu/code | /CF#313B.cpp | UTF-8 | 584 | 2.765625 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
int a[3][2];
int main(){
for(int i = 0;i < 3;i++){
scanf("%d%d",&a[i][0],&a[i][1]);
}
int flag = 0;
for(int i = 0;i < 2;i++){
int x = a[1][i] + a[2][i];
int y = max(a[1][1-i],a[2][1-i]);
if(x <= a[0][0] && y <= a[0][1] || x <= a[0][1] && y <=a[0][0]){
flag = 1;
}
x = a[2][1-i] + a[1][i];
y = max(a[2][i],a[1][1-i]);
if(x <= a[0][0] && y <= a[0][1] || x <= a[0][1] && y <=a[0][0]){
flag = 1;
}
}
if(flag){
cout <<"YES" <<endl;
}
else{
cout << "NO" << endl;
}
}
| true |
e104ebb0f0d59bedab6bf3df35565d23e3d63016 | C++ | laninivan/3dModelMaker | /src/Object/LightSource.cpp | UTF-8 | 590 | 2.671875 | 3 | [] | no_license | #include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#ifndef LIGHT_S
#define LIGHT_S
class LightSourse {
public:
LightSourse()
{
this->position = glm::vec3(20.0f, 40.0f, 60.0f);
this->color = glm::vec3(1.0f, 1.0f, 1.0f);
}
LightSourse(glm::vec3 position, glm::vec3 color)
{
this->position = position;
this->color = color;
}
glm::vec3 getColor()
{
return this->color;
}
glm::vec3 getPos()
{
return this->position;
}
private:
glm::vec3 color;
glm::vec3 position;
};
#endif | true |
3483827dc54d77019e3174f1492c293e5a04f9a0 | C++ | ulissesg/Heap_Sort_Tree | /main.cpp | UTF-8 | 1,053 | 3.71875 | 4 | [] | no_license | //Ulisses Genguini - 2019
#include<stdio.h>
#include <stdlib.h>
void imprimeVetor (int *v){
for (int i = 0; i< 10; i++){
printf("-%d\n", v[i]);
}
}
void troca(int *v1, int *v2){
int aux = *v1;
*v1 = *v2;
*v2 = aux;
}
void Heapify(int *Arv, int i, int n){
int left = 2*(i+1)-1;
int right = 2*(i+1);
int maior;
if ((left <= n) && (Arv[left] > Arv[i])){
maior = left;
}else{
maior = i;
}
if ((right <= n) && (Arv[right] > Arv[maior])){
maior = right;
}
if (maior != i){
troca(&(Arv[i]), &(Arv[maior]));
Heapify(Arv, maior, n);
}
}
void criarHeap(int *Arv, int n){
for(int i = (n / 2); i >= 0; i--){
Heapify(Arv, i, n);
}
}
void Heapsort(int *Arv, int n){
criarHeap(Arv, n);
for (int i = n-1; i > 0; i--){
troca(&(Arv[0]), &(Arv[i]));
Heapify(Arv, 0, i-1);
}
}
int main(){
int vetor[10];
for(int i = 0; i<10; i++){
vetor[i] = i;
}
Heapsort(vetor, 10);
imprimeVetor(vetor);
}
| true |
0e48caf0f89961fba0c069a1df0585b1ee099766 | C++ | HarielGiacomuzzi/Trabalho-Final-Redes | /Exemplos/Trabalho1/IPProtocol.cpp | UTF-8 | 2,432 | 3.140625 | 3 | [] | no_license | #include "IPProtocol.h"
#include <stdio.h>
void IPProtocol::setPackage(unsigned char *pckg){
this->package = pckg;
}
IPProtocol::IPProtocol(){}
IPProtocol::~IPProtocol(){}
// identifies the type of service and send's back the enum that represent it
int IPProtocol::identifyPackageSize(){
if(this->identifyProtocol() == IP){
int pkgSize;
pkgSize=(package[16]<<8)|(package[17]);
return pkgSize;
}
return 0;
}
// identifies the type of service inside the package
int IPProtocol::identifyTypeOfService(){
if(this->identifyProtocol() == IP){
int typeOfService;
typeOfService=package[23];
return typeOfService;
}
return 0;
}
// identifiesd the type of the protocol and returns it as a Enum.
int IPProtocol::identifyProtocol(){
int type;
type=(package[12]<<8)|(package[13]);
if(type == IP){
return IP;
}
if(type == ARP){
return ARP;
}
}
int IPProtocol::getDestinationPort(){
int port = 0;
if(this->identifyTypeOfService() == UDP || this->identifyTypeOfService() == TCP){
port=(package[36]<<8)|(package[37]);
return port;
}
printf("###########################\nNão foi possivel identificar a porta do pacote por não ser um pacote UDP/TCP\n###########################");
return 0;
}
int IPProtocol::getSourcePort(){
int port = 0;
if(this->identifyTypeOfService() == UDP || this->identifyTypeOfService() == TCP){
port=(package[34]<<8)|(package[35]);
return port;
}
printf("###########################\nNão foi possivel identificar a porta do pacote por não ser um pacote UDP/TCP\n###########################");
return 0;
}
int* IPProtocol::getDestinationIPFromHTTP(){
int *ip = new int[4];
if(this->identifyHTTP()){
ip[0] = package[26];
ip[1] = package[27];
ip[2] = package[28];
ip[3] = package[29];
return ip;
}
return NULL;
}
int* IPProtocol::getSourceIPFromHTTP(){
int *ip = new int[4];
if(this->identifyHTTP()){
ip[0] = package[30];
ip[1] = package[31];
ip[2] = package[32];
ip[3] = package[33];
return ip;
}
return NULL;
}
bool IPProtocol::identifyHTTP(){
if(this->identifyTypeOfService() == TCP && (this->getSourcePort() == 80 || this->getDestinationPort() == 80 ) ){
return true;
}
return false;
}
| true |
da57522b448cea0a102708ae4b8e43c0901e52a9 | C++ | Dimeurg/DisplayProjectsTask | /src/Parser.cpp | UTF-8 | 1,248 | 2.5625 | 3 | [] | no_license | #include "Parser.h"
#include <QJsonArray>
#include <QJsonObject>
#include <QStringLiteral>
void Parser::projectsInfoParse(const QJsonArray& projectsInfo, std::vector<std::shared_ptr<ProjectInfo>>& projectsOutput)
{
std::vector<std::shared_ptr<ProjectInfo>> projects;
for(auto infoJson : projectsInfo)
{
QString prName = infoJson["name"].toString();
bool isActive = infoJson["is_active"].toInt();
bool isWatcher = infoJson["is_owner_watcher"].toInt();
QUrl iconUrl = infoJson["logo_url"].toString();
int spentTimeWeek = infoJson["spent_time_week"].toInt();
int spentTimeMonth = infoJson["spent_time_month"].toInt();
int spentTimeTotal = infoJson["spent_time_all"].toInt();
int id = infoJson["id"].toInt();
QString users;
int index = 0;
const QJsonArray& usersJson = infoJson["users"].toArray();
for(auto user : usersJson)
{
users += QStringLiteral("user%1: ").arg(index++) + user["name"].toString();
}
projects.emplace_back(new ProjectInfo(prName, isActive, isWatcher, users, iconUrl, Time(spentTimeWeek), Time(spentTimeMonth), Time(spentTimeTotal), id));
}
projectsOutput.swap(projects);
}
| true |
643e20623292d10547e633936ec0323d4a958c6e | C++ | Murami/rtype | /Server/include/Game/AMonster.hh | UTF-8 | 656 | 2.90625 | 3 | [] | no_license |
#ifndef _MONSTER_HH_
# define _MONSTER_HH_
# include <string>
# include <cstdint>
# include "APlugin.hh"
class AMonster : public PluginManager::APlugin
{
public:
virtual ~AMonster() {}
std::uint32_t getLevel() const;
bool isAlive() const;
void takeDamage(std::uint32_t damage);
virtual std::uint32_t basicAttack() const = 0;
virtual std::uint32_t specialAttack() const = 0;
/* getters et setters */
void x(std::int32_t);
std::int32_t x() const;
void y(std::int32_t);
std::int32_t y() const;
protected:
std::uint32_t _life;
std::uint32_t _level;
std::int32_t _x;
std::int32_t _y;
};
#endif /* _MONSTER_HH_ */
| true |
549785f8a1790b76edf30abb71421ecba827a8f7 | C++ | motepc/Euler | /48.Self_index.cpp | UTF-8 | 780 | 3.109375 | 3 | [] | no_license | /*
The series, 11 + 22 + 33 + ... + 1010 = 10405071317.
Find the last ten digits of the series, 11 + 22 + 33 + ... + 10001000.
*/
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;
int main()
{
int i, j, k, carry, num[10], acc[10] = {0};
for(i=1; i<1001; i++)
{
num[0] = 1;
for(j=1; j<10; j++)
num[j] = 0;
for(j=0; j<i; j++)
{
carry = 0;
for(k=0; k<10; k++)
{
carry += num[k]*i;
num[k] = carry%10;
carry = carry/10;
}
}
carry = 0;
for(j=0; j<10; j++)
{
carry += num[j] + acc[j];
acc[j] = carry%10;
carry = carry/10;
}
}
printf("\n\n ");
for(j=0; j<10; j++)
printf("%d", acc[9-j]);
printf("\n");
return 0;
}
| true |
81e70919e137bd241532c34fa808dbc35dcfdecc | C++ | fredlim/GameEngine | /Tools/FBXLoader/Display/DisplayLight.cpp | UTF-8 | 1,858 | 2.6875 | 3 | [] | no_license | #include "DisplayLight.h"
#ifdef DUMP_FBX_INFO
namespace Tools
{
namespace DisplayLight
{
void DisplayDefaultAnimationValues( FbxLight *i_light );
}
}
void Tools::DisplayLight::DisplayLight( FbxNode* i_node )
{
DisplayCommon::DisplayString( "\n\n--------------------\nLight\n--------------------" );
FbxLight *light = (FbxLight*) i_node->GetNodeAttribute();
DisplayCommon::DisplayString( "Light Name: ", (char *) i_node->GetName() );
DisplayCommon::DisplayMetaDataConnections(light);
const char *lightTypes[] = { "Point", "Directional", "Spot" };
DisplayCommon::DisplayString( " Type: ", lightTypes[light->LightType.Get()] );
DisplayCommon::DisplayBool( " Cast Light: ", light->CastLight.Get() );
if( !(light->FileName.Get().IsEmpty()) )
{
DisplayCommon::DisplayString( " Gobo" );
DisplayCommon::DisplayString( " File Name: \"", light->FileName.Get().Buffer(), "\"" );
DisplayCommon::DisplayBool( " Ground Projection: ", light->DrawGroundProjection.Get() );
DisplayCommon::DisplayBool( " Volumetric Projection: ", light->DrawVolumetricLight.Get() );
DisplayCommon::DisplayBool( " Front Volumetric Projection: ", light->DrawFrontFacingVolumetricLight.Get() );
}
DisplayDefaultAnimationValues( light );
}
void Tools::DisplayLight::DisplayDefaultAnimationValues( FbxLight *i_light )
{
DisplayCommon::DisplayString( " Default Animation Values" );
FbxDouble3 c = i_light->Color.Get();
FbxColor lColor( c[0], c[1], c[2] );
DisplayCommon::DisplayColor( " Default Color: ", lColor );
DisplayCommon::DisplayDouble( " Default Intensity: ", i_light->Intensity.Get() );
DisplayCommon::DisplayDouble( " Default Outer Angle: ", i_light->OuterAngle.Get() );
DisplayCommon::DisplayDouble( " Default Fog: ", i_light->Fog.Get() );
}
#endif // #ifdef DUMP_FBX_INFO | true |
a76c6b035e02cf6471aa0e2e998f4de38de721c2 | C++ | ponlawat-w/cpp-tsp | /classes/frontierZdd/frontierMap.cpp | UTF-8 | 2,088 | 3.015625 | 3 | [] | no_license | #include "frontierMap.hpp"
namespace TSP::FrontierZDD {
FrontierMap::FrontierMap(Graph* graph, bool induced) {
this->graph = induced ? graph->clone()->makeCompleteGraph() : graph->clone();
set<Edge*> edgeSet = this->graph->getEdgeSet();
this->edges = this->edgeSetToArray(edgeSet);
this->edgeSize = edgeSet.size();
this->terminalFalse = new BinaryNode(0, true);
this->terminalTrue = new BinaryNode(1, true);
}
FrontierMap::~FrontierMap() {
for (int e = 0; e < this->edgeSize; e++) {
delete[] this->frontiers[e];
}
delete[] this->frontiers;
delete[] this->frontierSizes;
delete[] this->edges;
delete this->graph;
}
bool FrontierMap::vertexIsFinished(int vertex, int edgeIndex) {
for (int e = edgeIndex; e < this->edgeSize; e++) {
if (this->edges[e]->connects(vertex)) {
return false;
}
}
return true;
}
Edge** FrontierMap::edgeSetToArray(set<Edge*> edgeSet) {
Edge** edges = new Edge*[edgeSet.size()];
int index = 0;
for (Edge* edge: edgeSet) {
edges[index] = edge;
index++;
}
return edges;
}
int* FrontierMap::intSetToArray(set<int> intSet) {
int* array = new int[intSet.size()];
int index = 0;
for (int n: intSet) {
array[index] = n;
index++;
}
return array;
}
void FrontierMap::printFrontiers() {
for (int e = 0; e < this->edgeSize + 1; e++) {
string ev1 = e > 0 ? this->graph->vertexName(this->edges[e - 1]->getVertex(0)) : "";
string ev2 = e > 0 ? this->graph->vertexName(this->edges[e - 1]->getVertex(1)) : "";
cout << "Frontier[" << e << ": " << ev1 << "<->" << ev2 << "]: ";
for (int vf = 0; vf < this->frontierSizes[e]; vf++) {
cout << this->graph->vertexName(this->frontiers[e][vf]) << " ";
}
cout << "\n";
}
}
} | true |
4f87be2034f6ec60c6972354adcdbf2ef7e6e066 | C++ | vishnujayvel/SPOJ-1 | /GNY07B.cpp | UTF-8 | 580 | 2.828125 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | /*
USER: zobayer
TASK: GNY07B
ALGO: ad-hoc
*/
#include <iostream>
#include <string>
using namespace std;
int main()
{
int t, x;
double val;
string unit;
ios::sync_with_stdio(false);
cout.setf(ios::fixed,ios::floatfield);
cout.precision(4);
cin >> t;
for(x=1; x<=t; x++)
{
cin >> val >> unit;
if(unit=="kg") cout << x << ' ' << val * 2.2046 << " lb\n";
else if(unit=="lb") cout << x << ' ' << val * 0.4536 << " kg\n";
else if(unit=="l") cout << x << ' ' << val * 0.2642 << " g\n";
else if(unit=="g") cout << x << ' ' << val * 3.7854 << " l\n";
}
return 0;
}
| true |
37cb34c72138633e6bdc215386f030409428205d | C++ | wilmercastrillon/Ejercicios-Uva-Judge-Online | /Competitive Programming 3/Data Structures and Libraries/Data Structures with Our-Own Libraries/12532 Interval Product___2.cpp | UTF-8 | 571 | 2.640625 | 3 | [] | no_license | #include <stdio.h>
#include <algorithm>
#include <vector>
using namespace std;
typedef pair<int, int> ii;
int main(){
int casos, a, x;
scanf("%d", &casos);
while(casos--){
scanf("%d", &a);
vector<ii> v;
for(int i = 0; i < a; i++)
scanf("%d", &x), v.push_back(ii(x, i));
sort(v.begin(), v.end());
int res = 0;
for(int i = v.size() - 1; i > -1; i--)
for(int j = 0; j < i; j++)
if(v[j].second < v[i].second) res++;
printf("%d\n", res);
}
return 0;
}
| true |
9ecdf896c2fd6fa1a657a6de08937b34a62f289e | C++ | NathanYu1124/PLR_Vision | /NYPR/Model/NYCharacter.hpp | UTF-8 | 1,197 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | //
// NYCharacter.hpp
// NYPlateRecognition
//
// Created by NathanYu on 29/01/2018.
// Copyright © 2018 NathanYu. All rights reserved.
//
#ifndef NYCharacter_hpp
#define NYCharacter_hpp
#include <stdio.h>
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
class NYCharacter {
public:
// 初始化
NYCharacter();
// 字符Mat setter getter
void setCharacterMat(Mat param);
Mat getCharacterMat();
// 字符 setter getter
void setCharacterStr(string param);
string getCharacterStr();
// 字符位置 setter getter
void setCharacterPos(cv::Rect param);
cv::Rect getCharacterPos();
// 中文bool值 setter getter
void setIsChinese(bool param);
bool getIsChinese();
// 字符相似度 setter getter
void setLikelyScore(double param);
double getLikelyScore();
private:
// 字符Mat
Mat characterMat;
// 字符
string characterStr;
// 字符位置
cv::Rect characterPos;
// 是否为中文字符
bool isChinese;
// 字符相似度
double likelyScore;
};
#endif /* NYCharacter_hpp */
| true |
8f782ed0e26fb78690383012403a97f77ffecdec | C++ | rohmer/HydroGarden | /InstallLib/Version.h | UTF-8 | 2,135 | 3.171875 | 3 | [] | no_license | #pragma once
#include <sstream>
#include <string>
#include <json.hpp>
struct sVersion
{
private:
unsigned int major, minor, buildNum;
public:
sVersion()
: major(0)
, minor(0)
, buildNum(0)
{
}
sVersion(int major, int minor, int buildNum)
: major(major)
, minor(minor)
, buildNum(buildNum)
{
}
bool operator>(const sVersion& other)
{
if (major > other.major)
return true;
if (major == other.major && minor > other.minor)
return true;
if (major == other.major&&minor == other.minor&&buildNum > other.buildNum)
return true;
return false;
}
bool operator<(const sVersion& other)
{
if (major < other.major)
return true;
if (major == other.major && minor < other.minor)
return true;
if (major == other.major&&minor == other.minor&&buildNum < other.buildNum)
return true;
return false;
}
bool operator==(const sVersion& other)
{
if (major == other.major&&minor == other.minor&&buildNum == other.buildNum)
return true;
return false;
}
std::string ToString()
{
std::stringstream ss;
ss << major << "." << minor << "." << buildNum;
return ss.str();
}
static sVersion FromString(std::string s)
{
unsigned int major = 0, minor = 0, buildNum = 0;
int i = 0, pos = 0;
std::string token;
try
{
int fields[3];
std::istringstream ss(s);
std::string token;
while (std::getline(ss, token, '.'))
{
fields[i] = std::atoi(token.c_str());
i++;
}
if (i > 0)
major = fields[0];
if (i > 1)
minor = fields[1];
if (i > 2)
buildNum = fields[2];
}
catch (std::exception &e)
{
return (sVersion());
}
return sVersion(major, minor, buildNum);
}
nlohmann::json ToJson()
{
nlohmann::json vj;
vj["major"] = major;
vj["minor"] = minor;
vj["buildNum"] = buildNum;
return vj;
}
static sVersion FromJson(nlohmann::json vj)
{
unsigned int major = 0, minor = 0, buildNum = 0;
if (vj.contains("major"))
major = vj["major"];
if (vj.contains("minor"))
minor = vj["minor"];
if (vj.contains("buildNum"))
buildNum = vj["buildNum"];
return sVersion(major, minor, buildNum);
}
}; | true |
8d62c1be6d6475f8200a634ae3c46dd3cd6d519d | C++ | freezer-glp/leetcode-submit | /src/Construct Binary Tree from Preorder and Inorder Traversal.cpp | UTF-8 | 1,774 | 3.53125 | 4 | [] | no_license | /*Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Hide Tags Tree Array Depth-first Search
Show Similar Problems
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* build(vector<int>& preorder, vector<int>& inorder,int pl,int pr,int il,int ir){
if(pl > pr || il > ir){
return NULL;
}
TreeNode* root = new TreeNode(preorder[pl]);
if(pl == pr && il == ir){//only hava one node
return root;
}else{//build left and right subtree
int rootval = preorder[pl];
//find the root in preorder
int indexrootp = -1;
for(int i = pl; i <= pr; i++){
if(preorder[i] == rootval){
indexrootp = i;
break;
}
}
//find the root in inorder
int indexrooti = -1;
for(int i = il; i <= ir; i++){
if(inorder[i] == rootval){
indexrooti = i;
break;
}
}
//count the num of node of left subtree and right subtree
int leftnum = indexrooti - il;
int rightnum = ir - indexrooti;
//build left subtree
root -> left = build(preorder, inorder,indexrootp + 1,indexrootp + leftnum,indexrooti - leftnum,indexrooti - 1);
//build right subtree
root -> right = build(preorder, inorder, indexrootp + leftnum + 1,pr,indexrooti + 1,ir);
return root;
}
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.size() == 0 || inorder.size() == 0)
return NULL;
return build(preorder, inorder,0, preorder.size() - 1,0, inorder.size() - 1);
}
}; | true |
7728d89babf7a60a0c205adf63dad20075ba8d73 | C++ | mananmangal/codechef-solution | /practice/beginner/SUMTRIAN.cpp | UTF-8 | 510 | 2.65625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int t;
cin>>t;
for(int i=0;i<t;i++){
int n;
cin>>n;
int arr[n][n];
for(int j=0;j<n;j++){
for(int k=0;k<=j;k++){
cin>>arr[j][k];
}
}
for(int j=n-1;j>0;j--){
for(int k=0;k<=j;k++){
if(arr[j][k]>arr[j][k+1])
arr[j-1][k]+=arr[j][k];
else
arr[j-1][k]+=arr[j][k+1];
}
}
cout<<arr[0][0]<<endl;
}
return 0;
}
| true |
d4b1b997186e823c550625daf5dbe760db16e1b4 | C++ | MargaretKocherga/MovieTickets | /SourceFiles/editwindow.h | UTF-8 | 1,245 | 2.640625 | 3 | [
"MIT"
] | permissive | #ifndef EDITWINDOW_H
#define EDITWINDOW_H
#include <QDialog>
#include "seance.h"
namespace Ui {
class EditWindow;
}
class EditWindow : public QDialog
{
Q_OBJECT
//Очередь сеансов на определенный день
Queue<Seance> arrayOfSeances;
//Выбранная дата
QString selectedDate;
//Флаг редактирования/добавления объекта
QString buttonName;
//Индекс редактируемого объекта
int index;
public:
//Конструктор класса EditWindow
explicit EditWindow(QString _buttonName, QString _selectedDate,
Queue<Seance> _arrayOfSeances = {},
int _index = 0, QWidget *parent = nullptr);
//Деструктор класса EditWindow
~EditWindow();
private slots:
//Обработчик нажатия на кнопку addButton, добавляет
//новый сеанс или изменяет старый в зависимости от флага
void on_addButton_clicked();
private:
//Указатель на графическую составляющую класса
Ui::EditWindow *ui;
};
#endif // EDITWINDOW_H
| true |
703b9f6d083af38b8ee1f4cefb6b9fc4296f00fa | C++ | higgsch/CS6300 | /Optimizations/MaximizeBlocks/MaximizeBlocks.cpp | UTF-8 | 1,717 | 2.515625 | 3 | [] | no_license | #include <algorithm>
#include "MaximizeBlocks.hpp"
#include "AST/BasicBlock.hpp"
#include "AST/ThreeAddressInstruction.hpp"
#include "VisitedBlocks.hpp"
#include "NumParents.hpp"
void cs6300::maximizeBlocks(cs6300::FlowGraph& original)
{
// traverse the blocks
auto vb = VisitedBlocks::instance();
vb->reset();
buildParentCounts(original.first);
vb->reset();
combineBlocks(original.first, original);
}
void cs6300::buildParentCounts(std::shared_ptr<BasicBlock> block)
{
auto vb = VisitedBlocks::instance();
auto np = NumParents::instance();
if (vb->isVisited(block)) return;
if (block->branchTo != nullptr)
{
np->addParent(block->branchTo);
buildParentCounts(block->branchTo);
}
if (block->jumpTo != nullptr)
{
np->addParent(block->jumpTo);
buildParentCounts(block->jumpTo);
}
}
void cs6300::combineBlocks(std::shared_ptr<BasicBlock> block, FlowGraph& graph)
{
auto vb = VisitedBlocks::instance();
auto np = NumParents::instance();
if (vb->isVisited(block)) return;
if (block->branchTo) combineBlocks(block->branchTo, graph);
if (block->jumpTo) combineBlocks(block->jumpTo, graph);
// determine if they can be merged on the way back up...
if (block->jumpTo != nullptr && block->branchTo == nullptr &&
np->getNumParents(block->jumpTo) == 1)
{
//Redirect the end of the graph
if (block->jumpTo == graph.second)
{
graph.second = block;
}
// merge jumpTo to this block
for (auto inst : block->jumpTo->instructions)
{
block->instructions.push_back(inst);
}
block->branchTo = block->jumpTo->branchTo;
block->branchOn = block->jumpTo->branchOn;
block->jumpTo = block->jumpTo->jumpTo;
}
}
| true |
f5cffa833f37390b4df13cb380fc7d6ac9514dfc | C++ | rslinford/DWC_CS217_Data-Structures-and-Algorithms | /Structures/sortedlist.cpp | UTF-8 | 1,963 | 2.84375 | 3 | [] | no_license | /*! \file sortedlist.cpp
* \brief Definitions for class container::SortedList
*
* \section svn Source Control
*
* $URL: http://tablet-001/svn/DWC/CS217/trunk/Structures/sortedlist.cpp $
* $Date: 2009-06-10 21:54:03 -0400 (Wed, 10 Jun 2009) $
* $Author: slinford $
* $Revision: 385 $
*
* \section original File Creation
* <pre>
* Original file name: sortedlist.cpp
* File creator: slinford
* Created on: March 30, 2009, 11:45 PM
* </pre>
* \section course Course Information
* <pre>
* CS-217 Data Structures and Algorithms I
* Daniel Webster College - Nashua
* 03/18/2009 - 05/05/2009
* Independent Study
*
* Instructor: Robert Schaefer
*
* Description:
*
* Students will be responsible for the specification, design,
* implementation and practical demonstration of correctness of the
* abstract data type sets, functions, sequences, stacks, queues, and
* strings. Special emphasis will be given to searching and sorting
* algorithms. Other algorithms covered may include compression,
* encryption, hashing, and sorting, and sampling.
*
* Student:
*
* R. Scott Linford
* </pre>
*/
#include "sortedlist.h"
namespace container {
const Object::Info* const SortedList::TYPE_INFO = Object::typeInfoFactory("SortedList");
SortedList::SortedList() { }
SortedList::SortedList(const SortedList& orig) { }
SortedList::~SortedList() { }
/********************* SortedList Methods (public) *********************/
bool SortedList::insertSorted(Entity* entity) {
if (insertSorted_impl(entity)) {
incCount();
return true;
}
return false;
}
/********************* Object Methods (public) *********************/
ostream & SortedList::renderState(ostream& os) const {
return this->List::renderState(os);
}
const Object::Info* SortedList::typeInfo() const {
return TYPE_INFO;
}
} // namespace container
| true |
628ccc82a679905860d7521b0e1aec85a1fa7b72 | C++ | zhangjiangen/SnowTerrainDeformation | /Engine/API/Code/Graphics/Material/FramebufferMaterial.h | UTF-8 | 1,491 | 2.515625 | 3 | [] | no_license | #pragma once
#include "../../Toolbox/Toolbox.h"
#include "Material.h"
#include "../Shader/ShaderParameter/ShaderParameterTexture.h"
#include "../Shader/ShaderParameter/ShaderParameterBool.h"
namespace ae
{
/// \ingroup graphics
/// <summary>Framebuffer shading settings for rendering.</summary>
/// <seealso cref="Material"/>
/// <seealso cref="FramebufferSprite"/>
class AERO_CORE_EXPORT FramebufferMaterial : public Material
{
public:
/// <summary>Set the shader to the default framebuffer shader and create the its properties.</summary>
FramebufferMaterial();
/// <summary>Retrieve the parameter for the framebuffer texture.</summary>
/// <returns>The parameter for the framebuffer texture.</returns>
ShaderParameterTexture& GetTexture();
/// <summary>Retrieve the parameter for the framebuffer texture.</summary>
/// <returns>The parameter for the framebuffer texture.</returns>
const ShaderParameterTexture& GetTexture() const;
/// <summary>Retrieve the parameter for the IsDepth parameter.</summary>
/// <returns>The parameter for the IsDepth parameter.</returns>
ShaderParameterBool& GetIsDepth();
/// <summary>Retrieve the parameter for the IsDepth parameter.</summary>
/// <returns>The parameter for the IsDepth parameter.</returns>
const ShaderParameterBool& GetIsDepth() const;
private:
/// <summary>Parameter for the framebuffer texture.</summary>
ShaderParameterTexture* m_Texture;
ShaderParameterBool* m_IsDepth;
};
} // ae
| true |
b5661f11b33faddeb0c0df3a5aa4ffc87ffa9ad9 | C++ | hallgeirl/hiage-original | /src/mario/mariosystems.cpp | UTF-8 | 6,200 | 2.59375 | 3 | [] | no_license | #include "mariosystems.hpp"
#include "mariocomponents.hpp"
#include "events.hpp"
using namespace std;
using namespace hiage;
CharacterStateMachineSystem::CharacterStateMachineSystem() : System()
{
}
void CharacterStateMachineSystem::registerSystem(flecs::world& world)
{
world.system<CollidableComponent, StateComponent>()
.each([](flecs::entity, CollidableComponent& collidable, StateComponent& state)
{
for (auto& tc : collidable.tileCollisions)
{
if (tc.collisionResult.hitNormal.getY() > 0.5) {
auto& metadata = state.metadata;
metadata["onGround"] = 1;
metadata["ticks-since-landed"] = 0;
}
}
});
world.system<VelocityComponent, StateComponent>()
.each([](flecs::entity, VelocityComponent& velocity, StateComponent& state)
{
auto& vel = velocity.vel;
auto& metadata = state.metadata;
if (vel.getX() < -1e-6)
metadata["x-flip"] = 1;
else if (vel.getX() > 1e-6)
metadata["x-flip"] = 0;
if (!metadata.contains("ticks-since-landed"))
metadata["ticks-since-landed"] = 0;
std::get<int>(metadata["ticks-since-landed"])++;
if (get<int>(metadata["ticks-since-landed"]) > 5)
{
metadata["onGround"] = 0;
if (vel.getY() > 0)
{
if (abs(vel.getX()) > 150)
state.stateName = "longjump";
else
state.stateName = "jump";
}
else
state.stateName = "fall";
}
else
{
if (abs(vel.getX()) > 150)
{
state.stateName = "run";
}
else if (abs(vel.getX()) > 10)
{
state.stateName = "walk";
}
else
{
state.stateName = "stand";
}
}
});
}
CharacterControllerSystem::CharacterControllerSystem(Game& game) : System(), _game(game)
{
}
void CharacterControllerSystem::registerSystem(flecs::world& world)
{
world.system<VelocityComponent, ControllerStateComponent, StateComponent, SpeedLimitComponent>()
.each([&](flecs::entity e, VelocityComponent& velocity, ControllerStateComponent& controllerStateComponent, StateComponent& state, SpeedLimitComponent& speedlimit)
{
double magnitude = 800. * e.delta_time();
auto& vel = velocity.vel;
auto& controllerState = controllerStateComponent.controllerState;
speedlimit.speedLimit.setX(110);
// apply slowdown
if (abs(vel.getX()) > 400 * e.delta_time() && state.metadata.contains("onGround"))
{
if (vel.getX() > 0)
vel.add(Vector2<double>(-400. * e.delta_time(), 0));
if (vel.getX() < 0)
vel.add(Vector2<double>(400. * e.delta_time(), 0));
}
else
{
vel.setX(0);
}
if (controllerState.contains("run"))
speedlimit.speedLimit.setX(220);
if (controllerState.contains("goRight") && abs(vel.getX()) < speedlimit.speedLimit.getX())
vel.add(Vector2<double>(1, 0) * magnitude);
else if (controllerState.contains("goLeft") && abs(vel.getX()) < speedlimit.speedLimit.getX())
vel.add(Vector2<double>(-1, 0) * magnitude);
else if (controllerState.contains("crouch"))
vel.add(Vector2<double>(0, -1) * magnitude);
else if (controllerState.contains("lookUp"))
vel.add(Vector2<double>(0, 1) * magnitude);
if (controllerState.contains("jump") && state.metadata.contains("onGround") && get<int>(state.metadata.at("onGround")) != 0)
{
_game.getAudioManager().playWav("NormalJump");
state.metadata["onGround"] = 0;
vel.setY(300);
}
});
}
MarioCollisionResponseSystem::MarioCollisionResponseSystem() : System()
{
}
void MarioCollisionResponseSystem::registerSystem(flecs::world& world)
{
world.system<CollidableComponent, PositionComponent, VelocityComponent, StateComponent*>()
.each([](flecs::entity e, CollidableComponent& collidable, PositionComponent& position, VelocityComponent& velocity, StateComponent* state)
{
auto& col = collidable;
auto& pos = position.pos;
auto& vel = velocity.vel;
for (auto& oc : col.objectCollisions)
{
// Handle moving object colliding with blocking object
auto e2 = flecs::entity(e.world(), oc.entityId2);
auto blocking = e2.get<BlockingComponent>();
if (blocking != nullptr)
{
auto& collisionResult = oc.collisionResult;
// collisionTimeFactor is the fraction of the velocity that should be applied to move the object to the position of the collision
auto collisionTimeFactor = e.delta_time() * collisionResult.collisionTime;
// Calculate the per-axis velocity
Vec2d deltaPos(vel.getX() * collisionTimeFactor * collisionResult.axis.getX(), vel.getY() * collisionTimeFactor * collisionResult.axis.getY());
pos.add(deltaPos - vel * 1.0e-6);
// Adjust the velocity according to the hit normal
vel.set(vel - (collisionResult.hitNormal * (1.0 + 0) * vel.dot(oc.collisionResult.hitNormal)));
// normal vector of 30 degrees or higher => count as solid ground
if (oc.collisionResult.hitNormal.getY() > 0.5 && state != nullptr) {
auto& metadata = state->metadata;
metadata["onGround"] = 1;
metadata["ticks-since-landed"] = 0;
}
}
}
});
}
AISystem::AISystem() : System()
{
}
void AISystem::registerSystem(flecs::world& world)
{
world.system<CollidableComponent, GroundMonsterControllerComponent, ControllerStateComponent, VelocityComponent>()
.each([](flecs::entity e, CollidableComponent& col, GroundMonsterControllerComponent& gmc, ControllerStateComponent& controllerState, VelocityComponent& velocity)
{
auto& vel = velocity.vel;
for (auto& tc : col.tileCollisions)
{
if (tc.collisionResult.hitNormal.getX() > 0.7)
gmc.direction = "right";
else if (tc.collisionResult.hitNormal.getX() < -0.7)
gmc.direction = "left";
}
for (auto& oc : col.objectCollisions)
{
if (oc.collisionResult.hitNormal.getX() > 0.7)
{
gmc.direction = "right";
vel.setX(vel.getX() * -1);
}
else if (oc.collisionResult.hitNormal.getX() < -0.7)
{
gmc.direction = "left";
vel.setX(vel.getX() * -1);
}
}
unordered_set<string> actions;
if (gmc.direction == "left")
actions.insert("goLeft");
else if (gmc.direction == "right")
actions.insert("goRight");
controllerState.controllerState = actions;
});
}
| true |
d60aa6f53f962cb68e4162c5d4b82e153e0951f5 | C++ | jameshfisher/align | /align.cpp | UTF-8 | 6,645 | 3.40625 | 3 | [
"MIT"
] | permissive | /* Given some standard input, fold it to the specified line length in the
* same manner as the `fold` tool, but ensure that appropriate lines are
* justified to the specified line length by inserting spaces at heuristically
* appropriate places.
*/
#include <math.h>
#include <iostream>
#include <vector>
#include <boost/algorithm/string/trim.hpp>
using namespace std;
/**************************
* HELPER FUNCTIONS FIRST *
**************************/
void tokenize(
const string& str,
vector<string>& tokens,
const string& delimiters = " "
) {
/* Taken from the web. Sorry.
* Basically the same as strtok(), but with strings, not character arrays.
*/
// Skip delimiters at beginning.
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos) {
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
}
string replace(
string input,
string find,
string repl,
unsigned char max,
bool from_end = false
) {
/* Replace `max` occurrences of `find` with `repl` in `input`. */
string out = input;
if(from_end) {
reverse(out.begin(), out.end());
reverse(find.begin(), find.end());
reverse(repl.begin(), repl.end());
}
size_t pos = 0;
size_t find_len = find.length();
size_t repl_len = repl.length();
unsigned char replaced = 0;
if( find_len != 0 ) {
for(;
(replaced < max) &&
((pos = out.find( find, pos )) != std::string::npos)
;) {
out.replace( pos, find_len, repl );
replaced++;
pos += repl_len;
}
}
if(from_end) {
reverse(out.begin(), out.end());
}
return out;
}
/*********************************
* ALIGNMENT FUNCTIONS FOR SLUGS *
*********************************/
// The four kinds of alignment you can do with this tool.
enum Alignment {
align_left = 1,
align_right,
align_center,
align_justify
};
// Search-and-replace-ments for justification, in order of preference.
string justify_replacements[4][2] = {
". ", ". ",
"; ", "; ",
", ", ", ",
" ", " "
};
string justify_slug(string slug, unsigned char width, bool rtl) {
//Given a literal slug of text, justify to the width.
int padding = width - slug.length();
int i = 0;
int r;
while(padding > 0) {
int r = i % 4;
slug = replace(slug, justify_replacements[r][0], justify_replacements[r][1], padding, rtl);
padding = width - slug.length();
i++;
}
return slug;
}
string center_slug(string slug, unsigned char width) {
int padding = width - slug.length();
int left = floor(padding / 2);
int right = padding - left;
string centered_slug = "";
for(int i = 0; i < left; i++) {
centered_slug += " ";
}
centered_slug += slug;
for(int i = 0; i < right; i++) {
centered_slug += " ";
}
return centered_slug;
}
string right_slug(string slug, unsigned char width) {
int padding = width - slug.length();
string righted_slug = "";
for(int i = 0; i < padding; i++) {
righted_slug += " ";
}
return righted_slug + slug;
}
string align_para(string para, unsigned char width=72, Alignment alignment=align_justify) {
// Given a paragraph, align it.
string trimmed = boost::algorithm::trim_copy(para);
// If this line shouldn't be justified ...
if( trimmed.length() == 0 ||
trimmed[0] == '|' ||
trimmed[0] == '*' ||
trimmed[0] == '-' ||
trimmed[0] == '#'
)
{
return para;
}
// Else, start justifying.
vector<string> words;
tokenize(trimmed, words, " ");
vector<string> slugs(0); // Holds our justified paragraph
string current_slug = ""; // The current slug of text that will eventually be appended to `justified'
for(int i = 0; i < words.size(); i++) {
if( current_slug.length() + 1 + words[i].length() <= width ) {
current_slug += words[i]+" ";
}
else {
current_slug = current_slug.substr(0,current_slug.length()-1);
if(alignment == align_justify) {
current_slug = justify_slug(current_slug, width, slugs.size() % 2);
}
else if(alignment == align_left) {
// Nothing. We assume the input is aligned left.
}
else if(alignment == align_right) {
current_slug = right_slug(current_slug, width);
}
else if(alignment == align_center) {
current_slug = center_slug(current_slug, width);
}
slugs.push_back(current_slug); // + "\n";
current_slug = words[i] + " ";
}
}
// Add the final, shorter slug
current_slug = current_slug.substr(0,current_slug.length()-1);
if(alignment == align_justify || alignment == align_left) {
// With justification, we don't do the last line.
slugs.push_back(current_slug);
}
else if(alignment == align_right) {
slugs.push_back(right_slug(current_slug, width));
}
else if(alignment == align_center) {
slugs.push_back(center_slug(current_slug, width));
}
string justified_para = "";
for(int i = 0; i < slugs.size(); i++) {
justified_para += slugs[i];
if (i < slugs.size()-1) {
justified_para += "\n";
}
}
return justified_para;
}
int main(int argc, char* argv[]) {
enum Alignment alignment = align_justify;
int width = 72;
for(int i = 1; i < argc; i++) {
string arg = argv[i];
if(arg == "left") {
alignment = align_left;
}
else if(arg == "right") {
alignment = align_right;
}
else if(arg == "center") {
alignment = align_center;
}
else if(arg == "justify") {
alignment = align_justify;
}
else {
// Attempt to parse as line width
const char *arg_char = arg.c_str();
width = atoi(arg_char);
if(!width) {
// Not a valid argument.
// Note that atoi() returning 0 on failure is OK;
// a width of 0 doesn't make sense anyway.
cout << "Please supply a valid argument.";
return 1;
}
}
}
string line;
bool first_line = true;
while(cin) {
if(!first_line) {
cout << endl;
}
first_line = false;
getline(cin, line);
cout << align_para(line, width, alignment);
}
return 0;
}
| true |
7406da4890cd87eaa61557b170d6a45ee4a8e6f8 | C++ | pompon0/traders_puzzle | /utils/number_theory.h | UTF-8 | 671 | 3.296875 | 3 | [] | no_license | #ifndef UTILS_NUMBER_THEORY_H_
#define UTILS_NUMBER_THEORY_H_
namespace util {
template<typename T> constexpr T pow(T a, T b) {
T res = 1;
while(b) {
if(b&1) res *= a;
a *= a;
b >>= 1;
}
return res;
}
// inv(a)*a % (1<<bits(T)) = 1
// T is an unsigned integer type.
template<typename T> constexpr T inv(T a) {
static_assert(T(-1)>T(0));
if(!a%2) return 0; // TODO: throw error
// By Fermat's little theorem:
// a^totient(n) = 1 (%n)
// a^{-1} = a^{totient(n)-1}
//
// For n = 1<<bits(T) we have totient(n) = n/2
T tot = T(1)<<(sizeof(T)*8-1);
return pow<T>(a,tot-T(1));
}
} // namespace utils
#endif // UTILS_NUMBER_THEORY_H_
| true |
2cb5ba2217d480cbb4cd510eae7c5993a7c8f2bf | C++ | jschulz97/3220 | /FinalProject/Encrypt.h | UTF-8 | 347 | 2.859375 | 3 | [] | no_license | /**
*
*/
std::string encrypt(std::string m) {
int count = 0, keycount = 0;
std::string key = "banking";
for(auto i : m) {
if(keycount == 7)
keycount = 0;
m[count] = i+key[keycount];
while(m[count] < 33) {
m[count]+=93;
}
while(m[count] > 126) {
m[count]-=93;
}
count++;
keycount++;
}
return m;
} | true |
c32d5e11b7e68dc21e0eb8dd0e6bce68ecd737cd | C++ | FRENSIE/FRENSIE | /packages/monte_carlo/collision/core/test/tstAceLaw4NuclearScatteringEnergyDistribution.cpp | UTF-8 | 5,910 | 2.609375 | 3 | [
"BSD-3-Clause"
] | permissive | //---------------------------------------------------------------------------//
//!
//! \file tstAceLaw4NuclearScatteringDistribution.cpp
//! \author Alex Bennett
//! \brief Law 4 neutron scattering distribution unit tests
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <iostream>
// FRENSIE Includes
#include "MonteCarlo_AceLaw4NuclearScatteringEnergyDistribution.hpp"
#include "Utility_RandomNumberGenerator.hpp"
#include "Utility_HistogramDistribution.hpp"
#include "Utility_TabularDistribution.hpp"
#include "Utility_UnitTestHarnessWithMain.hpp"
//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
FRENSIE_UNIT_TEST( AceLaw4NuclearScatteringEnergyDistribution,
sampleEnergy_lower_bound_histogram )
{
MonteCarlo::AceLaw4NuclearScatteringEnergyDistribution::EnergyDistribution
energy_distribution(2);
energy_distribution[0].first = 1.0;
energy_distribution[1].first = 2.0;
std::vector<double> outgoing_energy_grid(5);
std::vector<double> pdf(4);
outgoing_energy_grid[0] = 1.0;
outgoing_energy_grid[1] = 2.0;
outgoing_energy_grid[2] = 3.0;
outgoing_energy_grid[3] = 4.0;
outgoing_energy_grid[4] = 5.0;
pdf[0] = 0.2;
pdf[1] = 0.2;
pdf[2] = 0.2;
pdf[3] = 0.2;
energy_distribution[0].second.reset( new Utility::HistogramDistribution(
outgoing_energy_grid,
pdf ) );
outgoing_energy_grid[0] = 2.0;
outgoing_energy_grid[1] = 3.0;
outgoing_energy_grid[2] = 4.0;
outgoing_energy_grid[3] = 5.0;
outgoing_energy_grid[4] = 6.0;
pdf[0] = 0.1;
pdf[1] = 0.1;
pdf[2] = 0.1;
pdf[3] = 0.1;
energy_distribution[1].second.reset( new Utility::HistogramDistribution(
outgoing_energy_grid,
pdf ) );
// Create the fake stream
std::vector<double> fake_stream( 1 );
fake_stream[0] = 0.5;
Utility::RandomNumberGenerator::setFakeStream( fake_stream );
MonteCarlo::AceLaw4NuclearScatteringEnergyDistribution
distribution( energy_distribution );
FRENSIE_CHECK_FLOATING_EQUALITY(distribution.sampleEnergy(0.5), 3.0, 1e-15);
}
//---------------------------------------------------------------------------//
FRENSIE_UNIT_TEST( AceLaw4NuclearScatteringEnergyDistribution,
sampleEnergy_upper_bound_histogram )
{
MonteCarlo::AceLaw4NuclearScatteringEnergyDistribution::EnergyDistribution
energy_distribution(2);
energy_distribution[0].first = 1.0;
energy_distribution[1].first = 2.0;
std::vector<double> outgoing_energy_grid(5);
std::vector<double> pdf(4);
outgoing_energy_grid[0] = 1.0;
outgoing_energy_grid[1] = 2.0;
outgoing_energy_grid[2] = 3.0;
outgoing_energy_grid[3] = 4.0;
outgoing_energy_grid[4] = 5.0;
pdf[0] = 0.2;
pdf[1] = 0.2;
pdf[2] = 0.2;
pdf[3] = 0.2;
energy_distribution[0].second.reset( new Utility::HistogramDistribution(
outgoing_energy_grid,
pdf ) );
outgoing_energy_grid[0] = 2.0;
outgoing_energy_grid[1] = 3.0;
outgoing_energy_grid[2] = 4.0;
outgoing_energy_grid[3] = 5.0;
outgoing_energy_grid[4] = 6.0;
pdf[0] = 0.1;
pdf[1] = 0.1;
pdf[2] = 0.1;
pdf[3] = 0.1;
energy_distribution[1].second.reset( new Utility::HistogramDistribution(
outgoing_energy_grid,
pdf ) );
// Create the fake stream
std::vector<double> fake_stream( 1 );
fake_stream[0] = 0.5;
Utility::RandomNumberGenerator::setFakeStream( fake_stream );
MonteCarlo::AceLaw4NuclearScatteringEnergyDistribution
distribution( energy_distribution );
FRENSIE_CHECK_FLOATING_EQUALITY(distribution.sampleEnergy(2.5), 4.0, 1e-15);
}
//---------------------------------------------------------------------------//
FRENSIE_UNIT_TEST( AceLaw4NuclearScatteringEnergyDistribution,
sampleEnergy_histogram )
{
MonteCarlo::AceLaw4NuclearScatteringEnergyDistribution::EnergyDistribution
energy_distribution(2);
energy_distribution[0].first = 1.0;
energy_distribution[1].first = 2.0;
std::vector<double> outgoing_energy_grid(5);
std::vector<double> pdf(4);
outgoing_energy_grid[0] = 1.0;
outgoing_energy_grid[1] = 2.0;
outgoing_energy_grid[2] = 3.0;
outgoing_energy_grid[3] = 4.0;
outgoing_energy_grid[4] = 5.0;
pdf[0] = 0.2;
pdf[1] = 0.2;
pdf[2] = 0.2;
pdf[3] = 0.2;
energy_distribution[0].second.reset( new Utility::HistogramDistribution(
outgoing_energy_grid,
pdf ) );
outgoing_energy_grid[0] = 2.0;
outgoing_energy_grid[1] = 3.0;
outgoing_energy_grid[2] = 4.0;
outgoing_energy_grid[3] = 5.0;
outgoing_energy_grid[4] = 6.0;
pdf[0] = 0.1;
pdf[1] = 0.1;
pdf[2] = 0.1;
pdf[3] = 0.1;
energy_distribution[1].second.reset( new Utility::HistogramDistribution(
outgoing_energy_grid,
pdf ) );
// Create the fake stream
std::vector<double> fake_stream( 2 );
fake_stream[0] = 0.25;
fake_stream[1] = 0.5;
Utility::RandomNumberGenerator::setFakeStream( fake_stream );
MonteCarlo::AceLaw4NuclearScatteringEnergyDistribution
distribution( energy_distribution );
FRENSIE_CHECK_FLOATING_EQUALITY(distribution.sampleEnergy(1.5), 3.5, 1e-15);
}
//---------------------------------------------------------------------------//
// Custom Setup
//---------------------------------------------------------------------------//
FRENSIE_CUSTOM_UNIT_TEST_SETUP_BEGIN();
FRENSIE_CUSTOM_UNIT_TEST_INIT()
{
// Initialize the random number generator
Utility::RandomNumberGenerator::createStreams();
}
FRENSIE_CUSTOM_UNIT_TEST_SETUP_END();
//---------------------------------------------------------------------------//
// tstAceLaw4NuclearScatteringDistribution.cpp
//---------------------------------------------------------------------------//
| true |
e82203e63b4f004ba6a5b5e2b631572133d1e2ed | C++ | beautifularea/misc | /std_bind_weak_fn.cc | UTF-8 | 3,285 | 3.203125 | 3 | [] | no_license | #ifndef BOOST_WEAK_FN_HPP
#define BOOST_WEAK_FN_HPP
#include <memory>
#include <iostream>
namespace std {
template <typename T = void>
struct ignore_if_invalid { T operator()() const {} };
template <typename V = void>
struct throw_if_invalid {
V operator()() const {
throw std::bad_weak_ptr();
}
};
template <typename V>
struct return_default_if_invalid {
return_default_if_invalid(): def_value_() {}
return_default_if_invalid(V def_value): def_value_(def_value) {}
V operator()() const {
return def_value_;
}
private:
V def_value_;
};
template <typename T>
using default_invalid_policy = ignore_if_invalid<T>;
//typedef ignore_if_invalid default_invalid_policy;
} // namespace std
namespace std {
namespace detail {
template<typename T, typename R, typename Policy, typename... Args>
class weak_fn_storage {
public:
typedef R result_type;
weak_fn_storage(
R (T::*mem_fn)(Args...),
const std::weak_ptr<T>& ptr,
Policy policy)
: mem_fn_(mem_fn)
, ptr_(ptr)
, policy_(policy)
{}
R operator()(Args... args)
{
if (std::shared_ptr<T> ptr = ptr_.lock()) {
return ((*ptr).*mem_fn_)(args...);
} else {
return policy_();
}
}
private:
R (T::*mem_fn_)(Args...);
std::weak_ptr<T> ptr_;
Policy policy_;
};
} // namespace detail
/** Returns a callback that can be used eg. in std::bind. When called, it
* tries to lock weak_ptr to get a shared_ptr. If successful, it calls
* given member function with given arguments. If not successful, it calls given
* policy functor. Built-in policies are:
*
* "ignore_if_invalid" - does nothing
* "throw_if_invalid" - throws "bad_weak_ptr"
* "return_default_if_invalid" - returns given value
*
* Example:
*
* struct Foo {
* void bar(int i) {
* std::cout << i << std::endl;
* }
* int have_return() {
* return 1;
* }
* };
*
* struct do_something {
* void operator()() {
* std::cout << "outdated reference" << std::endl;
* }
* };
*
* int main()
* {
* std::shared_ptr<Foo> sp(new Foo());
* std::weak_ptr<Foo> wp(sp);
*
* std::bind(std::weak_fn(&Foo::bar, wp), _1)(1);
* sp.reset();
* std::bind(std::weak_fn(&Foo::bar, wp), 1)();
* std::bind(std::weak_fn(&Foo::bar, wp, do_something()), 1)();
*
* FIX: 2
* FIX BIND RETURN VALUE FUNCTION COMPILE ERROR!!!
* std::cout << "return value = " << std::bind(std::weak_fn(&Foo::have_return, wp))() << std::endl;
* }
*/
template <typename T, typename R, typename Policy, typename... Args>
detail::weak_fn_storage<T, R, Policy, Args...> weak_fn(
R (T::*mem_fn)(Args...),
const std::weak_ptr<T>& ptr,
Policy policy)
{
return detail::weak_fn_storage<T, R, Policy, Args...>
(mem_fn, ptr, policy);
}
template <typename T, typename R, typename... Args>
detail::weak_fn_storage<T, R, default_invalid_policy<R>, Args...> weak_fn(
R (T::*mem_fn)(Args...),
const std::weak_ptr<T>& ptr)
{
return detail::weak_fn_storage<T, R, default_invalid_policy<R>, Args...>
(mem_fn, ptr, default_invalid_policy<R>());
}
} // namespace std
#endif
| true |
051eb98f5ace9592c010e0ef00c8aed234243b8b | C++ | tanmayGIT/Teaching | /La_Rochelle/IUT/iOS/Learn_iOS/VariousSequenceMatchingTechniques/VariousSequenceMatchingTechniques/numeric.h | UTF-8 | 1,806 | 3.359375 | 3 | [
"MIT",
"BSL-1.0"
] | permissive | /*!
\author Abdourahman Aden Hassan
\date 20/12/2013
*/
#ifndef NUMERIC_H
#define NUMERIC_H
#include "element.h"
namespace model{
class Numeric : public Element
{
/*!
* \class Numeric
* \brief Cette classe définit un élément de type numérique pour une séquence.
* Inherits Element
* \package model
*/
protected:
/*!< La valeur du nombre*/
float fNvalue;
public:
/*!
* \brief Constructeur
* Constructeur par défaut de la classe Numeric
*/
Numeric();
/*!
* \brief Constructeur
* Constructeur à un argument de la classe Numeric
* \param value la valeur de l'objet
*/
Numeric(float value);
/*!
* \brief Constructeur de recopie
* Constructeur de recopie de la classe Numeric
* \param copy : l'objet caractère à copier
*/
Numeric(Numeric const & copy);
/*!
* \brief Accesseur getValue
* Accesseur de la classe Numeric
* \return ret : la valeur de l'attribut value
*/
float getValue();
/*!
* \brief modifieur setValue
* Modifieur de la classe Numeric
* \param value : l'attribut value
*/
void setValue(float value);
/*!
\brief méthode abstraite "distance"
Cette méthode définit la distance entre deux éléments d'une séquence
\param eOD1 le premier élément de comparaison
\param eOD2 le second élément de comparaison
\return ret la valeur de la distance de comparaison
*/
float distance(Element *eOD1, Element *eOD2);
/*!
* \brief toString
* Méthode d'affichage de l'élément
* \return
*/
string toString();
/*!
* \brief copy
* Méthode de copie d'un élément alloué sur la pile
* \return
*/
Element * copy();
};
}
#endif // NUMERIC_H
| true |
f70c792c03d9e93998c1a97d64d547cad627c29f | C++ | Pyk017/C | /Code_regular/LetterCountOfaString.cpp | UTF-8 | 353 | 2.96875 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
int main()
{
int i=0,b[100]={0};char a[100];
printf("Enter a String :- \n");
gets(a);
while(a[i]!=NULL)
{
if((a[i]>='A' && a[i]<='Z') || (a[i]>='a' && a[i]<='z'))
{
b[a[i]-'A']++;
}
i++;
}
for(int i=0;i<52;i++)
{
if(b[i]!=0)
printf(" %c is occcured %d times.",i+'A',b[i]);
}
return 0;
}
| true |
bec3aebc60284c8181171bf6ba69362313d61fec | C++ | JavierSLX/Deitel-cpp | /Cap_03/Exer3_15/Fecha.cpp | UTF-8 | 602 | 3.421875 | 3 | [] | no_license | #include "Fecha.h"
void Fecha::establecerDia(int dia)
{
if (dia < 1)
diaFecha = 1;
else
diaFecha = dia;
}
void Fecha::establecerMes(int mes)
{
if (mes >= 1 && mes <= 12)
mesFecha = mes;
else
mesFecha = 1;
}
void Fecha::establecerAno(int ano)
{
anoFecha = ano;
}
int Fecha::obtenerDia(void)
{
return diaFecha;
}
int Fecha::obtenerMes(void)
{
return mesFecha;
}
int Fecha::obtenerAno(void)
{
return anoFecha;
}
void Fecha::mostrarFecha(void)
{
cout << "La fecha es: " << diaFecha << "/" << mesFecha << "/" << anoFecha << endl;
}
| true |
8703b0bf5e34be114f9b3421ce341dd89030d6e4 | C++ | andylang8445/BOSSMONSTER_Final_BACKUP | /20180311/괄호의 값/괄호의 값/main.cpp | UTF-8 | 676 | 2.859375 | 3 | [] | no_license | #include<stdio.h>
//#include<conio.h>
//#pragma warning(disable: 4996)
int multiple = 1;
int sum = 0;
int n, m;
char queue[50];
int main()
{
scanf("%s", queue);
for (int i = 0; queue[i] != NULL; i++)
{
if (queue[i] == '(')
{
n++;
multiple *= 2;
if (queue[i + 1] != NULL && queue[i + 1] == ')')
sum += multiple;
}
else if (queue[i] == '[')
{
m++;
multiple *= 3;
if (queue[i + 1] != NULL && queue[i + 1] == ']')
sum += multiple;
}
else if (queue[i] == ')')
{
n--;
multiple /= 2;
}
else if (queue[i] == ']')
{
m--;
multiple /= 3;
}
}
if (n != 0 || m != 0)
printf("0");
else
printf("%d", sum);
//_getch();
} | true |
c03a9825a39b112424215bb296be9a1f52797d69 | C++ | erwa/robotics-lab-2020 | /servo-test-2/servo-test-2.ino | UTF-8 | 1,287 | 2.53125 | 3 | [] | no_license | #include <Romi32U4.h>
#include <Servo.h> //Servo library
Romi32U4ButtonA buttonA;
Servo testservo; //initialize a servo object for the connected servo
uint32_t next;
int angle = 0;
void setup()
{
buttonA.waitForButton();
delay(1000);
// gripper: 500: fully open, 2400: fully closed
// need to use more than the documented 1200 to get tilt to go down
// tilt: 900: fully down, 1900: fully up
// lift: 700: fully up, 1900: fully down
testservo.attach(3, 900, 1900);
next = millis() + 500;
// gripper: 180: closed; 0: open
// tilt: 180: fully up, 0: fully down
// lift: 0: fully up, 110 (@ 1900): basically fully down
testservo.write(0);
buttonA.waitForButton();
delay(1000);
}
void loop()
{
static bool rising = true;
while (!buttonA.isPressed()) {
if(millis() > next)
{
if(rising)
{
testservo.write(110);
rising = false;
}
else
{
testservo.write(0);
rising = true;
}
// repeat again after a couple seconds.
next += 3000;
}
}
buttonA.waitForRelease();
while (!buttonA.isPressed()) {
delay(500);
}
buttonA.waitForRelease();
}
| true |
74375de865ce00bb9812f68ffc17f91c3b164719 | C++ | taruchu/ServicePool | /ServicePool/NETOLookUp.cpp | UTF-8 | 2,100 | 2.75 | 3 | [] | no_license | #include "NETOLookUp.h"
void* NETOLookUp::FirstResourceProviderMatching(string property)
{
if(VerifyProperty(property) == false)
return nullptr;
else
{
map<__int64, void*>::iterator itr;
__int64 index;
for (itr = _propertyTable[property].begin(); itr != _propertyTable[property].end();)
{
index = itr->first;
if (VerifyReferenceID(index))
{
return _resourceProviders[index];
}
else
++itr;
}
return nullptr;
}
}
__int64 NETOLookUp::RegisterProvider(void * reference)
{
__int64 index = GetNewIndex();
_resourceProviders[index] = reference;
return index;
}
bool NETOLookUp::UnRegisterProvider(__int64 refID)
{
if (VerifyReferenceID(refID) == false)
return false;
else
{
CleanPropertyTable(refID);
_resourceProviders.erase(refID);
}
return true;
}
bool NETOLookUp::AddProperty(__int64 refID, string property)
{
if (VerifyReferenceID(refID))
{
_propertyTable[property][refID] = nullptr;
return true;
}
else
return false;
}
bool NETOLookUp::RemoveProperty(__int64 refID, string property)
{
if (VerifyReferenceID(refID) && VerifyProperty(property))
{
_propertyTable[property].erase(refID);
if (_propertyTable[property].size() == 0)
_propertyTable.erase(property);
return true;
}
return false;
}
__int64 NETOLookUp::GetNewIndex()
{
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}
bool NETOLookUp::VerifyReferenceID(__int64 refID)
{
map<__int64, void*>::iterator itr;
itr = _resourceProviders.find(refID);
return (itr != _resourceProviders.end());
}
bool NETOLookUp::VerifyProperty(string property)
{
map<string, map<__int64, void*>>::iterator itr;
itr = _propertyTable.find(property);
return (itr != _propertyTable.end());
}
void NETOLookUp::CleanPropertyTable(__int64 refID)
{
map<string, map<__int64, void*>>::iterator itr;
for (itr = _propertyTable.begin(); itr != _propertyTable.end();)
{
itr->second.erase(refID);
if (itr->second.size() == 0)
_propertyTable.erase(itr++);
else
++itr;
}
return;
}
| true |
f14cb38c7ad3ed2a1db5c4d5cfba8959d7f30137 | C++ | Witek902/Raytracer | /Core/Math/Vector4.h | UTF-8 | 13,191 | 2.5625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Math.h"
#include "Float2.h"
#include "Float3.h"
#include "VectorBool4.h"
namespace rt {
namespace math {
/**
* 4-element SIMD vector
*/
struct RT_ALIGN(16) Vector4
{
union
{
float f[4];
int32 i[4];
uint32 u[4];
#ifdef RT_USE_SSE
__m128 v;
__m128i vi;
#endif // RT_USE_SSE
struct
{
float x;
float y;
float z;
float w;
};
};
RT_FORCE_INLINE Vector4();
RT_FORCE_INLINE Vector4(const Vector4& other);
RT_FORCE_INLINE static const Vector4 Zero();
RT_FORCE_INLINE explicit Vector4(const float scalar); // splat
RT_FORCE_INLINE explicit Vector4(const int32 scalar); // splat
RT_FORCE_INLINE explicit Vector4(const uint32 scalar); // splat
RT_FORCE_INLINE Vector4(const float x, const float y, const float z = 0.0f, const float w = 0.0f);
RT_FORCE_INLINE Vector4(const int32 x, const int32 y, const int32 z = 0, const int32 w = 0);
RT_FORCE_INLINE Vector4(const uint32 x, const uint32 y, const uint32 z = 0u, const uint32 w = 0u);
RT_FORCE_INLINE explicit Vector4(const float* src);
RT_FORCE_INLINE explicit Vector4(const Float2& src);
RT_FORCE_INLINE explicit Vector4(const Float3& src);
RT_FORCE_INLINE Vector4& operator = (const Vector4& other);
RT_FORCE_INLINE static const Vector4 FromInteger(int32 x);
RT_FORCE_INLINE static const Vector4 FromIntegers(int32 x, int32 y, int32 z, int32 w);
RT_FORCE_INLINE explicit operator float() const { return x; }
RT_FORCE_INLINE float operator[] (uint32 index) const { return f[index]; }
RT_FORCE_INLINE float& operator[] (uint32 index) { return f[index]; }
#ifdef RT_USE_SSE
RT_FORCE_INLINE Vector4(const __m128& src);
RT_FORCE_INLINE operator __m128() const { return v; }
RT_FORCE_INLINE operator __m128i() const { return _mm_castps_si128(v); }
#endif // RT_USE_SSE
// simple arithmetics
RT_FORCE_INLINE const Vector4 operator- () const;
RT_FORCE_INLINE const Vector4 operator+ (const Vector4& b) const;
RT_FORCE_INLINE const Vector4 operator- (const Vector4& b) const;
RT_FORCE_INLINE const Vector4 operator* (const Vector4& b) const;
RT_FORCE_INLINE const Vector4 operator/ (const Vector4& b) const;
RT_FORCE_INLINE const Vector4 operator* (float b) const;
RT_FORCE_INLINE const Vector4 operator/ (float b) const;
RT_FORCE_INLINE Vector4& operator+= (const Vector4& b);
RT_FORCE_INLINE Vector4& operator-= (const Vector4& b);
RT_FORCE_INLINE Vector4& operator*= (const Vector4& b);
RT_FORCE_INLINE Vector4& operator/= (const Vector4& b);
RT_FORCE_INLINE Vector4& operator*= (float b);
RT_FORCE_INLINE Vector4& operator/= (float b);
// modulo 1
RT_FORCE_INLINE static const Vector4 Mod1(const Vector4& x);
RT_FORCE_INLINE const VectorBool4 operator == (const Vector4& b) const;
RT_FORCE_INLINE const VectorBool4 operator < (const Vector4& b) const;
RT_FORCE_INLINE const VectorBool4 operator <= (const Vector4& b) const;
RT_FORCE_INLINE const VectorBool4 operator > (const Vector4& b) const;
RT_FORCE_INLINE const VectorBool4 operator >= (const Vector4& b) const;
RT_FORCE_INLINE const VectorBool4 operator != (const Vector4& b) const;
// bitwise logic operations
RT_FORCE_INLINE const Vector4 operator& (const Vector4& b) const;
RT_FORCE_INLINE const Vector4 operator| (const Vector4& b) const;
RT_FORCE_INLINE const Vector4 operator^ (const Vector4& b) const;
RT_FORCE_INLINE Vector4& operator&= (const Vector4& b);
RT_FORCE_INLINE Vector4& operator|= (const Vector4& b);
RT_FORCE_INLINE Vector4& operator^= (const Vector4& b);
RT_FORCE_INLINE const Vector4 SplatX() const;
RT_FORCE_INLINE const Vector4 SplatY() const;
RT_FORCE_INLINE const Vector4 SplatZ() const;
RT_FORCE_INLINE const Vector4 SplatW() const;
// Change sign of selected elements (immediate)
template<uint32 flipX, uint32 flipY, uint32 flipZ, uint32 flipW>
RT_FORCE_INLINE const Vector4 ChangeSign() const;
// Change sign of selected elements (variable)
RT_FORCE_INLINE const Vector4 ChangeSign(const VectorBool4& flip) const;
// Prepare mask vector
template<uint32 maskX, uint32 maskY, uint32 maskZ, uint32 maskW>
RT_FORCE_INLINE static const Vector4 MakeMask();
// Rearrange vector elements (immediate)
template<uint32 ix = 0, uint32 iy = 1, uint32 iz = 2, uint32 iw = 3>
RT_FORCE_INLINE const Vector4 Swizzle() const;
// Rearrange vector elements (variable)
RT_FORCE_INLINE const Vector4 Swizzle(uint32 ix, uint32 iy, uint32 iz, uint32 iw) const;
// Convert to 3 uint8 values (with clamping)
// xyz [0.0f...1.0f] -> zyx [0...255]
RT_FORCE_INLINE uint32 ToBGR() const;
RT_FORCE_INLINE Float2 ToFloat2() const;
RT_FORCE_INLINE Float3 ToFloat3() const;
RT_FORCE_INLINE static const Vector4 Floor(const Vector4& v);
RT_FORCE_INLINE static const Vector4 Sqrt(const Vector4& v);
RT_FORCE_INLINE static const Vector4 Reciprocal(const Vector4& v);
RT_FORCE_INLINE static const Vector4 FastReciprocal(const Vector4& v);
RT_FORCE_INLINE static const Vector4 Lerp(const Vector4& v1, const Vector4& v2, const Vector4& weight);
RT_FORCE_INLINE static const Vector4 Lerp(const Vector4& v1, const Vector4& v2, float weight);
RT_FORCE_INLINE static const Vector4 Min(const Vector4& a, const Vector4& b);
RT_FORCE_INLINE static const Vector4 Max(const Vector4& a, const Vector4& b);
RT_FORCE_INLINE static const Vector4 Abs(const Vector4& v);
RT_FORCE_INLINE static const Vector4 Saturate(const Vector4& v);
RT_FORCE_INLINE static const Vector4 Clamp(const Vector4& x, const Vector4& min, const Vector4& max);
// Build mask of sign bits
RT_FORCE_INLINE int GetSignMask() const;
// For each vector component, copy value from "a" if "sel" is "false", or from "b" otherwise
RT_FORCE_INLINE static const Vector4 Select(const Vector4& a, const Vector4& b, const VectorBool4& sel);
template<uint32 selX, uint32 selY, uint32 selZ, uint32 selW>
RT_FORCE_INLINE static const Vector4 Select(const Vector4& a, const Vector4& b);
// Calculate 2D dot product (scalar result)
RT_FORCE_INLINE static float Dot2(const Vector4& v1, const Vector4& v2);
// Calculate 2D dot product (vector result)
RT_FORCE_INLINE static const Vector4 Dot2V(const Vector4& v1, const Vector4& v2);
// Calculate 3D dot product (scalar result)
RT_FORCE_INLINE static float Dot3(const Vector4& v1, const Vector4& v2);
// Calculate 3D dot product (vector result)
RT_FORCE_INLINE static const Vector4 Dot3V(const Vector4& v1, const Vector4& v2);
// Calculate 4D dot product (scalar result)
RT_FORCE_INLINE static float Dot4(const Vector4& v1, const Vector4& v2);
// Calculate 4D dot product (vector result)
RT_FORCE_INLINE static const Vector4 Dot4V(const Vector4& v1, const Vector4& v2);
// Calculate 3D cross product
RT_FORCE_INLINE static const Vector4 Cross3(const Vector4& v1, const Vector4& v2);
// Square length of a 2D vector (scalar result)
RT_FORCE_INLINE float SqrLength2() const;
// Length of a 2D vector (scalar result)
RT_FORCE_INLINE float Length2() const;
// Length of a 2D vector (vector result)
RT_FORCE_INLINE const Vector4 Length2V() const;
// Length of a 3D vector (scalar result)
RT_FORCE_INLINE float Length3() const;
// Square length of a 3D vector (scalar result)
RT_FORCE_INLINE float SqrLength3() const;
// Length of a 3D vector (vector result)
RT_FORCE_INLINE const Vector4 Length3V() const;
// Length of a 4D vector (scalar result)
RT_FORCE_INLINE float Length4() const;
// Length of a 4D vector (vector result)
RT_FORCE_INLINE const Vector4 Length4V() const;
// Square length of a 4D vector (scalar result)
RT_FORCE_INLINE float SqrLength4() const;
// Normalize as 3D vector
RT_FORCE_INLINE Vector4& Normalize3();
RT_FORCE_INLINE Vector4& FastNormalize3();
// Normalize as 4D vector
RT_FORCE_INLINE Vector4& Normalize4();
// Return normalized 3D vector
RT_FORCE_INLINE const Vector4 Normalized3() const;
RT_FORCE_INLINE const Vector4 FastNormalized3() const;
// Return normalized 3D vector and its inverse
RT_FORCE_INLINE const Vector4 InvNormalized(Vector4& outInvNormalized) const;
// Return normalized 4D vector
RT_FORCE_INLINE const Vector4 Normalized4() const;
// Reflect a 3D vector
RT_FORCE_INLINE static const Vector4 Reflect3(const Vector4& i, const Vector4& n);
// Refract a 3D vector
static const Vector4 Refract3(const Vector4& i, const Vector4& n, float eta);
// Check if two vectors are (almost) equal
RT_FORCE_INLINE static bool AlmostEqual(const Vector4& v1, const Vector4& v2, float epsilon = RT_EPSILON);
// Check if the vector is equal to zero
RT_FORCE_INLINE const VectorBool4 IsZero() const;
// Check if any component is NaN
RT_FORCE_INLINE const VectorBool4 IsNaN() const;
// Check if any component is an infinity
RT_FORCE_INLINE const VectorBool4 IsInfinite() const;
// Check if is not NaN or infinity
RT_FORCE_INLINE bool IsValid() const;
// Fused multiply and add (a * b + c)
RT_FORCE_INLINE static const Vector4 MulAndAdd(const Vector4& a, const Vector4& b, const Vector4& c);
RT_FORCE_INLINE static const Vector4 MulAndAdd(const Vector4& a, const float b, const Vector4& c);
// Fused multiply and subtract (a * b - c)
RT_FORCE_INLINE static const Vector4 MulAndSub(const Vector4& a, const Vector4& b, const Vector4& c);
RT_FORCE_INLINE static const Vector4 MulAndSub(const Vector4& a, const float b, const Vector4& c);
// Fused multiply (negated) and add (-a * b + c)
RT_FORCE_INLINE static const Vector4 NegMulAndAdd(const Vector4& a, const Vector4& b, const Vector4& c);
RT_FORCE_INLINE static const Vector4 NegMulAndAdd(const Vector4& a, const float b, const Vector4& c);
// Fused multiply (negated) and subtract (-a * b - c)
RT_FORCE_INLINE static const Vector4 NegMulAndSub(const Vector4& a, const Vector4& b, const Vector4& c);
RT_FORCE_INLINE static const Vector4 NegMulAndSub(const Vector4& a, const float b, const Vector4& c);
// Calculate horizontal maximum. Result is splatted across all elements
RT_FORCE_INLINE const Vector4 HorizontalMax() const;
// transpose 3x3 matrix
RT_FORCE_INLINE static void Transpose3(Vector4& a, Vector4& b, Vector4& c);
// make vector "v" orthogonal to "reference" vector
RT_FORCE_INLINE static const Vector4 Orthogonalize(const Vector4& v, const Vector4& reference);
// Compute fmodf(x, 1.0f)
RT_FORCE_INLINE static const Vector4 Fmod1(const Vector4& v);
};
// like Vector4::operator * (float)
RT_FORCE_INLINE const Vector4 operator*(float a, const Vector4& b);
// [-1...1] -> [0...1]
RT_FORCE_INLINE const Vector4 BipolarToUnipolar(const Vector4& x);
// [-1...1] -> [0...1]
RT_FORCE_INLINE const Vector4 UnipolarToBipolar(const Vector4& x);
////
// some commonly used constants
RT_GLOBAL_CONST Vector4 VECTOR_EPSILON = { RT_EPSILON, RT_EPSILON, RT_EPSILON, RT_EPSILON };
RT_GLOBAL_CONST Vector4 VECTOR_HALVES = { 0.5f, 0.5f, 0.5f, 0.5f };
RT_GLOBAL_CONST Vector4 VECTOR_MIN = { std::numeric_limits<float>::min(), std::numeric_limits<float>::min(), std::numeric_limits<float>::min(), std::numeric_limits<float>::min() };
RT_GLOBAL_CONST Vector4 VECTOR_MAX = { std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max() };
RT_GLOBAL_CONST Vector4 VECTOR_INF = { std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity() };
RT_GLOBAL_CONST Vector4 VECTOR_ONE = { 1.0f, 1.0f, 1.0f, 1.0f };
RT_GLOBAL_CONST Vector4 VECTOR_ONE3 = { 1.0f, 1.0f, 1.0f, 0.0f };
RT_GLOBAL_CONST Vector4 VECTOR_ONE2 = { 1.0f, 1.0f, 0.0f, 0.0f };
RT_GLOBAL_CONST Vector4 VECTOR_MINUS_ONE = { -1.0f, -1.0f, -1.0f, -1.0f };
RT_GLOBAL_CONST Vector4 VECTOR_EXPONENT_MASK = { 0x7F800000u, 0x7F800000u, 0x7F800000u, 0x7F800000u };
RT_GLOBAL_CONST Vector4 VECTOR_MANTISSA_MASK = { 0x007FFFFFu, 0x007FFFFFu, 0x007FFFFFu, 0x007FFFFFu };
RT_GLOBAL_CONST Vector4 VECTOR_MASK_ABS = { 0x7FFFFFFFu, 0x7FFFFFFFu, 0x7FFFFFFFu, 0x7FFFFFFFu };
RT_GLOBAL_CONST Vector4 VECTOR_MASK_SIGN_W = { 0u, 0u, 0u, 0x80000000u };
RT_GLOBAL_CONST Vector4 VECTOR_INV_255 = { 1.0f / 255.0f, 1.0f / 255.0f, 1.0f / 255.0f, 1.0f / 255.0f };
RT_GLOBAL_CONST Vector4 VECTOR_255 = { 255.0f, 255.0f, 255.0f, 255.0f };
RT_GLOBAL_CONST Vector4 VECTOR_X = { 1.0f, 0.0f, 0.0f, 0.0f };
RT_GLOBAL_CONST Vector4 VECTOR_Y = { 0.0f, 1.0f, 0.0f, 0.0f };
RT_GLOBAL_CONST Vector4 VECTOR_Z = { 0.0f, 0.0f, 1.0f, 0.0f };
RT_GLOBAL_CONST Vector4 VECTOR_W = { 0.0f, 0.0f, 0.0f, 1.0f };
} // namespace math
} // namespace rt
#include "Vector4Impl.h"
#ifdef RT_USE_SSE
#include "Vector4ImplSSE.h"
#else
#include "Vector4ImplNaive.h"
#endif // RT_USE_SSE
| true |
e60c9bd5ab17dc872d07a08c67d0eb4aed05ca4e | C++ | GauravS99/Arduino-Smartphone-Car | /Arduino_Car_Control.ino | UTF-8 | 3,734 | 3.359375 | 3 | [] | no_license | /*Arduino Car Controller
*
* The following program will allow the user to run a car equipped with an arduino, motor shield, and onesheeld to
drive the car using their android smartphone.
It makes use of the Adafruit Motor Shield Library.
The motor.run() command sets the motor to move either FORWARD,BACKWARD, or RELEASE.
The motor.setSpeed(int) command sets the speed of the motor, and the int is a value between 0 and 255
The OneSheeld app is used to control the car. Scan and select your OneSheeld to begin.
The accelerometer x value is used to decide how fast the car moves forward or backwards, while the y value decides the turning.
*/
#define CUSTOM_SETTINGS
#define INCLUDE_ACCELEROMETER_SENSOR_SHIELD
#include <OneSheeld.h>
#include <AFMotor.h>
//initialize the motors
AF_DCMotor motor4(4);
AF_DCMotor motor3(3);
const int FWD_THRESHOLD = 5; //Threshold for max speed forward. If X is more than this, then it should be full speed forward.
const int TURN_THRESHOLD = 7; //Threshold for full turn. If Y is more than this, then it should be a full, sharp, turn.
const int MAX = 255; //Max Speed
int mSpeed = MAX; //mSpeed is motor speed, and it is a number that will always be between 0 - 255, indicating the speed of the motor.
int slow = 0; //The slow variable serves as an offset of the mSpeed variable. A larger slow variable means the speed of the motor will be slower.
void setup() {
OneSheeld.begin();
motor3.run(RELEASE);
motor4.run(RELEASE);
}
void loop() {
float x = AccelerometerSensor.getX();
float y = AccelerometerSensor.getY();
if (x >= 1) //If x >= 1 that means that the car should move FORWARD
{
motor3.run(FORWARD);
motor4.run(FORWARD); //Set both motors to move foward
if ( y > -1 && y < 1) //No turn. If y is in the middle, that means that the phone is not tilted enough to make a turn.
forward(x);
if (y >= 1) //right turn. Phone is tilted right.
turnRight(y);
if (y <= -1) //left turn. Phone is tilted left.
turnLeft(y);
}
else if (x <= -1) //BACKWARD
{
motor3.run(BACKWARD);
motor4.run(BACKWARD); //Set both motors to move backward
if (y > -1 && y < 1) //no turn
backward(x);
if (y >= 1) //right turn
turnRight(y);
if (y <= -1) //left turn
turnLeft(y);
}
else //HALT
{
motor3.run(RELEASE); //Stops both motors
motor4.run(RELEASE);
}
}
void turnLeft(int yVal) {
if (yVal <= -TURN_THRESHOLD) //if y <= -7, make the car turn sharply left
slow = MAX;
else //else, turn it based on how far the phone is tilted left. Allows gentle turns.
slow = map(-yVal, 1, TURN_THRESHOLD, 0, MAX);
motor3.setSpeed(mSpeed);
motor4.setSpeed(mSpeed - slow);
}
void turnRight(int yVal) {
if (yVal >= TURN_THRESHOLD) //if y >= 7, make the car turn sharply right
slow = MAX;
else //else, turn it based on how far the phone is tilted right.
slow = map(yVal, 1, TURN_THRESHOLD, 0, MAX);
motor3.setSpeed(mSpeed - slow);
motor4.setSpeed(mSpeed);
}
void forward(int xVal) {
if (xVal >= FWD_THRESHOLD) //if x >= 5, full speed
mSpeed = MAX;
else //else, change the speed depending on how far the phone is tilted forward
mSpeed = map(xVal, 1, FWD_THRESHOLD, 0, MAX);
motor3.setSpeed(mSpeed);
motor4.setSpeed(mSpeed);
}
void backward(int xVal) {
if (xVal <= -FWD_THRESHOLD) //if x <= -5, full speed backward
mSpeed = MAX;
else //else, change the speed depending on how far the phone is tilted backward
mSpeed = map(-xVal, 1, FWD_THRESHOLD, 0, MAX);
motor3.setSpeed(mSpeed);
motor4.setSpeed(mSpeed);
}
| true |
ec4df1d19e5518ff0933b0bd28bfdf9fb0404118 | C++ | sploitfun/sploitfun | /XploitDev1/bof.cpp | UTF-8 | 2,120 | 2.640625 | 3 | [] | no_license | /*
Buffer Overflow Demo Program
cl /GS- bof.cpp - Disable Stack cookie(/GS)
link /defaultlib:ws2_32.lib bof.obj
*/
#include <winsock2.h>
#include <stdio.h>
#define BUFLEN 1024
void bof(char *recvbuf) {
char sendBuf[512];
strcpy(sendBuf,recvbuf);
}
int main() {
WSADATA wsaData;
int result;
sockaddr_in sock;
SOCKET psk = INVALID_SOCKET;
SOCKET csk = INVALID_SOCKET;
char recvbuf[BUFLEN];
int recvResult, sendResult;
int recvbuflen = BUFLEN;
result = WSAStartup(MAKEWORD(2,2), &wsaData);
if (result != NO_ERROR) {
printf("Error at WSAStartup\n");
return 1;
}
psk = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(psk == INVALID_SOCKET) {
printf("Error at socket creation\n");
WSACleanup();
return 1;
}
sock.sin_family = AF_INET;
sock.sin_addr.s_addr = inet_addr("0.0.0.0");
sock.sin_port = htons(8888);
result = bind(psk,(SOCKADDR*) &sock,sizeof(sock));
if(result == SOCKET_ERROR) {
printf("Bind failed\n");
closesocket(psk);
WSACleanup();
}
result = listen(psk,SOMAXCONN);
if(result == SOCKET_ERROR) {
printf("Listen failed\n");
closesocket(psk);
WSACleanup();
}
csk = accept(psk,NULL,NULL);
if(psk == INVALID_SOCKET) {
printf("Error at accept\n");
WSACleanup();
closesocket(psk);
return 1;
} else {
printf("Client Connected\n");
}
do {
memset(recvbuf,0,BUFLEN);
recvResult = recv(csk, recvbuf, BUFLEN, 0);
if (recvResult > 0) {
printf("%s\n", recvbuf);
bof(recvbuf);
sendResult = send(csk, recvbuf, recvResult, 0);
if (sendResult == SOCKET_ERROR) {
printf("Send failed: %d\n", WSAGetLastError());
closesocket(csk);
WSACleanup();
return 1;
}
printf("%s\n", recvbuf);
} else if (recvResult == 0) {
printf("Connection closing...\n");
} else {
printf("Recieve failed: %d\n", WSAGetLastError());
closesocket(csk);
WSACleanup();
return 1;
}
} while (recvResult > 0);
return 0;
}
| true |
984790f39eabdee0d90625f9e208bb50a9616a5e | C++ | Silly-Face-LLC/Dynamite-Engine | /Dynamite Engine/Dynamite Engine/Source.cpp | UTF-8 | 1,164 | 2.96875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
int main()
{
string senario;
string choice1;
string choice1a;
string choice2;
string choice2a;
string userchoice;
cout << "Dynamite Engine \n";
cout << "v0.1.0a \n";
cout << "Create your own choices game! \n";
cout << "What do you want the senario to be? \n";
getline(cin, senario);
cout << "What do you want choice number 1 to be? \n";
getline(cin, choice1);
cout << "What do you want the output of choice number 1 to be? \n";
getline(cin, choice1a);
cout << "What do you want choice number 2 to be? \n";
getline(cin, choice2);
cout << "What do you want the output of choice number 2 to be? \n";
getline(cin, choice2a);
cout << "Your game is all ready now! \n";
Sleep(3000);
for (int n = 0; n < 1000; n++)
{
printf("\n\n\n\n\n\n\n\n\n\n");
}
cout << senario << endl;
cout << "What do you want to do? \n";
cout << choice1 << " or " << choice2 << endl;
getline(cin, userchoice);
if (userchoice == choice1)
{
cout << choice1a << endl;
}
if (userchoice == choice2)
{
cout << choice2a << endl;
}
} | true |
86ce4c95321e2a1df810158015f2b2082c2bd515 | C++ | Wallace-Chen/LeetCode | /0066PlusOne.cpp | UTF-8 | 652 | 3.140625 | 3 | [] | no_license | class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int len = digits.size(), carryover = 1, pos=len-1;
while(pos>=0 && carryover){
int tmp = carryover + digits[pos];
carryover = tmp/10;
digits[pos] = tmp%10;
pos--;
}
if(carryover!=0) digits.insert(digits.begin(), carryover);
return digits;
}
};
/* alternative concise conde
vector<int> plusOne(vector<int>& digits) {
for (int i=digits.size(); i--; digits[i] = 0)
if (digits[i]++ < 9)
return digits;
digits[0]++;
digits.push_back(0);
return digits;
}
*/ | true |
e3e5eecc2fd08a520e0a8b50d7d93af19bfdb08b | C++ | banjowabble/BT07 | /A3.cpp | UTF-8 | 440 | 3.3125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int countEven(int*, int);
int main ()
{
int a[10] = {1,2,3,4,5,6,7,8,9,10};
countEven(a, 10);
}
int countEven(int* a, int n)
{
int count = 0, revCount = 0;
for (int i=0; i<5; i++)
{
if (a[i] % 2 == 0) count++;
}
for (int i=n-1; i>n-6 ;i--)
{
if (a[i] % 2 == 0) revCount++;
}
cout << count << ' ' << revCount;
}
| true |
9edc0c880cea7fb86990ab4587e8c268bc692e77 | C++ | JatinSharma2821/C-plus-plus | /Functions/Armstrong.cpp | UTF-8 | 669 | 3.40625 | 3 | [] | no_license | #include<iostream>
#include<math.h>
using namespace std;
// Armstrong no. - A no. whose sum of cube of all digits is equal to no. itself.
int main()
{
int num;
cout<<"This Program is to check wether the given is armstrong or not."<<endl;
cout<<"Enter number to check"<<endl;
cin>>num;
int rem ;
int sum = 0;
int originalnum = num;
while (num>0)
{ rem = num%10;
cout<<rem<<" || ";
cout<<pow(rem,3)<<" ";
cout<<sum<<" ";
sum = sum + pow(rem,3);
cout<<sum<<" ---- ";
num = num/10;
}
if(sum==originalnum) {cout<<"Its a armstrong no.";}
else {cout<<"Not armstrong no.";}
cout<<pow(3,3)<<" "<<pow(5,3)<<" "<<pow(1,3);
return 0;
} | true |
9da3d5b195bf2adc8598d802f6e96469f6cee8bf | C++ | lpcteste/wc3data | /DataGen/datafile/id.cpp | UTF-8 | 343 | 2.671875 | 3 | [] | no_license | #include "id.h"
#include "utils/common.h"
std::string idToString(uint32 id) {
if ((id & 0xFFFF0000) == 0x000D0000) {
return fmtstring("0x%08X", id);
} else {
std::string res;
res.push_back(char(id >> 24));
res.push_back(char(id >> 16));
res.push_back(char(id >> 8));
res.push_back(char(id));
return res;
}
}
| true |
0bb1749df51fe2218f07697b23cb53d44e7d527e | C++ | hoangtrung1999/Data-Structures-and-Algorithms | /Codeforces/StringTask.cpp | UTF-8 | 542 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main()
{
string S;
string S2;
cin>>S;
for (unsigned int i = 0 ; i < S.size() ; i++)
if ((int) S[i] > 64 && (int)S[i] < 91)
S[i] = char ((int)S[i] + 32);
for (unsigned int i = 0 ; i < S.size() ;)
if (S[i] == 'a' || S[i] == 'o' || S[i] == 'e' || S[i] == 'u'
|| S[i] == 'i' || S[i] == 'y')
{
S.erase(i,1);
i = 0;
}
else
i++;
for (unsigned int i = 0 ; i < S.size() ; i++)
{
S2.push_back('.');
S2.push_back(S[i]);
}
cout<<S2;
return 0;
} | true |
16e48d2ff73355a3df15d69b7f5c16c437c8550e | C++ | kwsephiroth/CPPCraftDemo | /UnitTests/unittests.cpp | UTF-8 | 3,952 | 2.6875 | 3 | [] | no_license | #include "stdafx.h"
#include "CppUnitTest.h"
#include <string>
#include <vector>
#include <algorithm>
#include <chrono>
#include <iostream>
#include <ratio>
#include "../CPPCraftDemo/QBRecordCollectionOperators.h"
#include "../CPPCraftDemo/QBRecordDatabase.h"
#include "../CPPCraftDemo/QBBaseImplementation.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTests
{
TEST_CLASS(UnitTests)
{
public:
TEST_METHOD(PerformanceComparisons)
{
using namespace std::chrono;
//Using Base Implementation
{
// populate a bunch of data
auto data = QBBasePopulateDummyData("testdata", 1000);
// Find a record that contains and measure the perf
auto startTime = steady_clock::now();
auto filteredSet = QBBaseFindMatchingRecords(data, "column1", "testdata500");
auto filteredSet2 = QBBaseFindMatchingRecords(data, "column2", "24");
auto finishTime = steady_clock::now();
auto message = ("Base Implementation execution time: " + std::to_string((double((finishTime - startTime).count()) * steady_clock::period::num / steady_clock::period::den)) + " seconds\n");
Logger::WriteMessage(message.c_str());
// make sure that the function is correct
Assert::AreEqual(filteredSet.size(), (size_t)1);
}
//Using QBRecordCollectionOperators
{
// populate a bunch of data
auto data = QBRecordCollectionOperators::PopulateDummyData("testdata", 1000);
// Find a record that contains and measure the perf
auto startTime = steady_clock::now();
auto filteredSet = QBRecordCollectionOperators::QBFindMatchingRecords(data, ColumnID::Column1, "testdata500");
auto filteredSet2 = QBRecordCollectionOperators::QBFindMatchingRecords(data, ColumnID::Column2, "24");
auto finishTime = steady_clock::now();
auto message = ("QBRecordCollectionOperators execution time: " + std::to_string((double((finishTime - startTime).count()) * steady_clock::period::num / steady_clock::period::den)) + " seconds\n");
Logger::WriteMessage(message.c_str());
// make sure that the function is correct
Assert::AreEqual(filteredSet.size(), (size_t)1);
}
//Using QBRRecordDatabase
{
// populate a bunch of data
QBRecordDatabase rdb;
rdb.PopulateDummyData("testdata", 1000);
// Find a record that contains and measure the perf
auto startTime = steady_clock::now();
auto filteredSet = rdb.QBFindMatchingRecords(ColumnID::Column1, "testdata500");
auto filteredSet2 = rdb.QBFindMatchingRecords(ColumnID::Column2, "24");
auto finishTime = steady_clock::now();
auto message = ("QBRecordDatabase execution time: " + std::to_string((double((finishTime - startTime).count()) * steady_clock::period::num / steady_clock::period::den)) + " seconds\n");
Logger::WriteMessage(message.c_str());
// make sure that the function is correct
Assert::AreEqual(filteredSet.size(), (size_t)1);
}
}
TEST_METHOD(DeleteRecordsByID)
{
{
auto data = QBRecordCollectionOperators::PopulateDummyData("testdata", 1000);
auto filteredSet = QBRecordCollectionOperators::QBFindMatchingRecords(data, ColumnID::Column1, "testdata500");
Assert::AreEqual(filteredSet.size(), (size_t)1);
QBRecordCollectionOperators::DeleteRecordByID(data, 500);
filteredSet = QBRecordCollectionOperators::QBFindMatchingRecords(data, ColumnID::Column1, "testdata500");
Assert::AreEqual(filteredSet.size(), (size_t)0);
}
}
TEST_METHOD(AlphabeticalMatchingStringForNumericColumn)
{
auto data = QBRecordCollectionOperators::PopulateDummyData("testdata", 1000);
auto filteredSet = QBRecordCollectionOperators::QBFindMatchingRecords(data, ColumnID::Column0, "testdata500");//String to integer conversion attempted
//Exception thrown and caught upon failure
//No record added.
Assert::AreEqual(filteredSet.size(), (size_t)0);
}
};
} | true |
91d6c348b086c59fad7685af07884eb35bbaed8b | C++ | songjunyu/LeetCode | /字符串转换整数 (atoi).cpp | UTF-8 | 1,531 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <utility>
#include <queue>
#include <stack>
using namespace std;
class Solution {
public:
int myAtoi(string str)
{
str.erase(0, str.find_first_not_of(" "));
int i = 0;
bool flag = true;
if (str[i] == '+' || str[i] == '-')
{
if (str[i] == '-')
flag = false;
++i;
}
int res = 0;
while (i < str.size() && str[i] >= '0'&&str[i] <= '9')
{
int tmp = str[i] - '0';
if (flag)
{
if (res > INT_MAX / 10 || (res == INT_MAX / 10 && tmp >= 7))
return INT_MAX;
res = res * 10 + tmp;
}
else
{
if (res < INT_MIN / 10 || (res == INT_MIN / 10 && tmp >= 8))
return INT_MIN;
res = res * 10 - tmp;
}
++i;
}
return res;
}
//
int myAtoi2(string str)
{
int positive = 1;
int i = 0;
int res = 0;
//去除空格
while (str[i] == ' ')
{
++i;
}
//判断第一个字符
if (str[i] == '-'|| str[i] == '+')
{
if (str[i] == '-')
positive = -1;
++i;
}
//判断数字
for (; i < str.size(); ++i)
{
int num = str[i] - '0';
if (num > 9 || num < 0)
return res;
if (positive == 1 && res > (INT_MAX - positive * num) / 10)
return INT_MAX;
if (positive == -1 && res < (INT_MIN - positive * num) / 10)
return INT_MIN;
res = res * 10 + positive * num;
}
return res;
}
};
int main()
{
string s = "2147483648";
Solution a;
cout << a.myAtoi(s) << endl;
system("pause");
return 0;
}
| true |
5dc0227ddeeaa22593c96a6b56cb3d97734d32e5 | C++ | seventeeen/algorithm | /baekjoon_online_judge/boj_03034_앵그리창영.cpp | UTF-8 | 395 | 2.75 | 3 | [] | no_license | /*
* About
*
* Author: seventeeen@GitHub <powdragon1@gmail.com>
* Date : 2017-02-21
* URL : https://www.acmicpc.net/problem/3034
*
*/
#include <iostream>
using namespace std;
int main(void){
int N, W, H, length, a;
cin >> N >> W >> H;
length = W*W + H*H;
for (int i = 0; i < N; i++) {
cin >> a;
if (a*a <= length)
cout << "DA" << endl;
else
cout << "NE" << endl;
}
return 0;
}
| true |
c1c861a49c38fb33ad05c67f48773fa79ffc2d66 | C++ | mgrang/caffeinic-codelets | /linkedlist/linkedlist.cpp | UTF-8 | 3,177 | 3.71875 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include "linkedlist.h"
using namespace std;
void test(const vector<int> &nums) {
auto *L = new LinkedList(nums);
cout << "List: ";
L->print();
cout << "Reverse list: ";
L->reverse();
L->print();
cout << "Reverse first 1: ";
L->reverse(1);
L->print();
cout << "Reverse first 2: ";
L->reverse(2);
L->print();
cout << "Reverse first 3: ";
L->reverse(3);
L->print();
cout << "Reverse first 4: ";
L->reverse(4);
L->print();
cout << "Reverse first 5: ";
L->reverse(5);
L->print();
cout << "Middle node: " << L->getMid() << "\n";
cout << "Remove 3: ";
L->remove(3);
L->print();
cout << "Add 10: ";
L->add(10);
L->print();
cout << "Remove 5: ";
L->remove(5);
L->print();
cout << "Remove 10: ";
L->remove(10);
L->print();
cout << "Remove head: ";
L->remove(L->getHead());
L->print();
cout << "Add 10, 20, 30, 40, 50: ";
L->add(10);
L->add(20);
L->add(30);
L->add(40);
L->add(50);
L->print();
cout << "3rd from end: " << L->getNthFromEnd(3) << "\n";
cout << "1st from end: " << L->getNthFromEnd(1) << "\n";
cout << "7th from end: " << L->getNthFromEnd(7) << "\n";
cout << "Is palindrome: " << L->isPalindrome() << "\n";
cout << "Add 40, 30, 20, 10, 1, 2: ";
L->add(40);
L->add(30);
L->add(20);
L->add(10);
L->add(1);
L->add(2);
L->print();
cout << "Is palindrome: " << L->isPalindrome() << "\n";
cout << "Pair-wise swap: ";
L->pairWiseSwap(L->getHead());
L->print();
cout << "Num of nodes: " << L->getNumNodes() << "\n";
cout << "Move 1 to front: ";
L->moveNToFront(1);
L->print();
cout << "Move 2 to front: ";
L->moveNToFront(2);
L->print();
L->~LinkedList();
cout << "--------------------------------------------------------\n";
}
void test2(const vector<int> &nums1, const vector<int> &nums2) {
auto *L1 = new LinkedList(nums1);
auto *L2 = new LinkedList(nums2);
cout << "List1: ";
L1->print();
cout << "List2: ";
L2->print();
cout << "Intersection: ";
L1->getSortedIntersection(L2->getHead());
L1->~LinkedList();
L2->~LinkedList();
cout << "--------------------------------------------------------\n";
}
void test3(vector<int> nums) {
auto *L = new LinkedList(nums);
cout << "List: ";
L->print();
cout << "Sorted list: ";
L->sort();
L->print();
L->~LinkedList();
cout << "--------------------------------------------------------\n";
}
void test4(vector<int> nums1, vector<int> nums2) {
auto *L1 = new LinkedList(nums1);
auto *L2 = new LinkedList(nums2);
cout << "List1: ";
L1->print();
cout << "List2: ";
L2->print();
cout << "Addition: ";
auto *L3 = L1->getSum(L2);
L3->print();
L1->~LinkedList();
L2->~LinkedList();
cout << "--------------------------------------------------------\n";
}
int main() {
test({1, 2, 3, 4, 5});
test2({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {2, 4, 8, 9});
test3({2, 1, 2, 1, 1, 2, 0, 1, 0});
test4({1}, {9, 9, 9, 9});
test4({9, 9, 9, 9}, {1});
test4({9, 9, 9, 1}, {9});
test4({9, 8, 7, 6}, {1, 2, 3, 4});
test4({1, 2, 3}, {3, 2, 1});
test4({9}, {0, 0, 0, 0});
}
| true |
9ab45bdbad3c9b2fc8476c11e87fb0f2329de10d | C++ | zhengziqiang/learngit | /acm/acm/acm_pre/leecode/约瑟夫环.cpp | UTF-8 | 2,176 | 3.921875 | 4 | [] | no_license | /*==============================================================================
> File Name: 约瑟夫环.cpp
> Author: zzq
> Mail: zhengziqiang1@gmail.com
> Created Time: 2016年09月27日 星期二 21时11分33秒
==========================================================================*/
// 6.cpp -- using gcc compiler
#include <iostream>
using namespace std;
typedef struct List
{
int num;
struct List *next;
}*pList;
class Josephus
{
public:
Josephus() {}
Josephus(int number, int mes):
n(number),
m(mes){}
void set();
void creat();
void del();
private:
pList head;
int n, m, tmp_n;
};
void Josephus::set()
{
cout << "please input the number of the people: ";
cin >> n;
tmp_n = n;
cout << "please input the m: ";
cin >> m;
}
void Josephus::creat()
{
pList p1, p2;
pList p = new List;//直接申请空间就行
n += 1;//n+1连成环状
p -> num = 1;
p2 = head = p;
for(int i = 2; i < n; i++)
{
p = new List;
p -> num = i;
p1 = p2;
p2 = p;
p1 -> next = p2;
}
p2 -> next = head;
// output each number of the circle list's members.
// and it should be: 1, 2, ..., n
p = head;
cout << "Now, the \"num\" member of the list is: " << endl;
while(n--)
{
if(n == 0)
cout << p-> num << ".";
else
{
cout << p->num << ", ";
p = p -> next;
}
}
}
void Josephus::del()
{
pList p1 = NULL;
pList p2 = head;
n = tmp_n + 1;
while(n--)
{
int s = m - 1;
while(s--)
{
p1 = p2;//用p1来记录p2的值
p2 = p2 -> next;
}
if(n == 0)
{
p2 = p2 -> next;
p1 -> next = NULL;
cout << "The result is: " << p2 -> num << endl;
}
else
{
p2 = p2 -> next;//删除当前p2的值
p1 -> next = p2;
}
}
}
int main()
{
Josephus t;
t.set();
t.creat();
cout << endl;
t.del();
return 0;
}
| true |
f1695dbcb061909b441ebbfe00c2cb07c8e040eb | C++ | ingyeoking13/algorithm | /swex/programmingAdvanced/1251.cc | UTF-8 | 1,424 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
struct point
{
int x, y;
point() {};
};
struct Edge
{
long long len;
int u, v;
Edge() {};
Edge(int u, int v, long long len ) :u(u), v(v), len(len) {};
bool operator<(Edge b) { return len < b.len; }
};
int p[(int)1e3];
Edge edges[(int)1e6];
bool mycmp(const Edge& aa, const Edge& bb)
{
return aa.len < bb.len;
}
int ufind(int now)
{
if ( now == p[now] ) return now;
return p[now] = ufind(p[now]);
}
int main()
{
int tt=0;
int T;
cin >> T;
point a[(int)1e3];
int edgeNum;
while (++tt<= T)
{
edgeNum=0;
int n;
cin >> n;
for (int i=0; i<n; i++) cin >> a[i].x;
for (int i=0; i<n; i++) cin >> a[i].y;
for (int i=0; i<n; i++) p[i] = i;
double ee;
cin >> ee;
for (int i=0; i<n; i++)
{
for (int j=i+1; j<n; j++)
{
long long len =
((long long)(a[i].x-a[j].x))*(a[i].x-a[j].x) + ((long long)(a[i].y-a[j].y))*(a[i].y-a[j].y);
edges[edgeNum++] = Edge(i, j, len);
}
}
sort(edges, edges+edgeNum, mycmp);
double ans = 0;
for (int i=0; i<edgeNum; i++)
{
Edge cur = edges[i];
int u = cur.u, v = cur.v;
u = ufind(u), v = ufind(v);
if ( u == v ) continue;
p[u] =v;
ans += (cur.len*ee);
}
long long lll = ans*10;
lll+=5;
lll/=10;
cout << "#" << tt << " " << lll <<"\n";
}
}
| true |
71e93e63bbdfca34184e7f70f579fa4d7a29a8f6 | C++ | tinhphantrong0612/networkprogramming | /client/Client_UI/weapon.h | UTF-8 | 454 | 2.5625 | 3 | [] | no_license | #pragma once
#include "constant.h"
#define NO_WEAPON_NAME "Egg fights rock"
#define BALISTA_NAME "Balista Sword"
#define CATAPULT_NAME "Big Catapult"
#define CANNON_NAME "Super Dupper Gaint Cannon"
class Weapon {
public:
int type;
char name[NAME_LENGTH + 1];
int attack;
int wood;
int stone;
int iron;
Weapon();
Weapon(int type, int attack, char* name, int wood, int stone, int iron);
};
Weapon get_weapon(int type);
| true |
3ec0a37b067a5a6d69be1451370f30450cfb2f3c | C++ | imoren2x/biblab | /Cpp/Ejercicios/90_Ejercicios/fsm.hpp | UTF-8 | 1,230 | 3.328125 | 3 | [] | no_license | //FSM.h
#ifndef FSM_H
#define FSM_H
#include <iostream>
#include <string>
#include <vector>
#include <memory>
class FSM;
//An individual state (must belong to a FSM)
//This is an abstract class and must be sub-classed
class FSMState {
public:
FSMState(){};
FSMState(FSM *fsm){};
virtual ~FSMState(){};
virtual void Update(const float& dt) = 0;
virtual void DoENTER(){};
virtual void DoEXIT(){};
//Attributes//
std::string stateName; //used to switch between states
FSM *fsm;
};
//A vector of shared pointers housing all the states in the machine
typedef std::vector< std::tr1::shared_ptr<FSMState> > StateBank;
//---------------------------------------//
//A Simple Finite State Machine
class FSM {
public:
FSM();
~FSM();
void Update(const float& dt);
void TransitionTo(std::string stateName);
void DelayTransitionTo(std::string stateName);
void AddState(FSMState *newState, bool makeCurrent);
std::string GetState();
public:
FSMState *currentState;
std::string delayState;
//Bank to house list of states
StateBank stateBank;
std::vector< std::tr1::shared_ptr<FSMState> >::iterator iter;
};
#endif | true |
b6a528611cdfbbc7811772e5a45a7f40834a818c | C++ | AMPWorks/ArduinoLibs | /ShiftBar/ShiftBar.h | UTF-8 | 738 | 2.5625 | 3 | [] | no_license | /*
* Code to drive ShiftBar, ShiftBrite, etc
*/
#ifndef SHIFTBAR_H
#define SHIFTBAR_H
#include <Arduino.h>
/* SPI Pins */
#define SHIFTBAR_CLOCK_PIN 13 // CI
#define SHIFTBAR_ENABLE_PIN 10 // EI
#define SHIFTBAR_LATCH_PIN 9 // LI
#define SHIFTBAR_DATA_PIN 11 // DI
#define SHIFTBAR_MAX 1023
#define SHIFTBAR_RED 0
#define SHIFTBAR_GREEN 1
#define SHIFTBAR_BLUE 2
class ShiftBar
{
public:
ShiftBar(uint8_t modules, uint16_t *values);
void set(uint8_t module, uint16_t red, uint16_t green, uint16_t blue);
void set(uint16_t red, uint16_t green, uint16_t blue);
void update(void);
uint8_t num_modules;
private:
uint16_t *_values;
void spiSend(int commandmode, int red, int blue, int green);
};
#endif
| true |
94a3c97f3ca4d03ee384451d48e52db975551c3e | C++ | ansich/C-C-Medio | /Actividad_7_1/main.cpp | ISO-8859-1 | 1,014 | 3.765625 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
//1.Implementar una funcin genrica para contar el nmero de veces que un elemento aparece en un vector de elementos.
template <typename T>
int contar (T *Vector){
int max;
T elem;
int cont = 0;
cout << "introduzca elemento" << endl;
cin >> elem;
cout << "introduzca numero elementos" << endl;
cin >> max;
for (int i=0; i < max-1; i++){
if ( Vector[i] == elem ){
cont++;
}return cont;
}
}
template<typename T>
void ordenar(T *v, int n){
for(int i = 0; i < n-1 ;i++){
for (int j=i+1; j < n;j++){
if(v[i] > v[j]){
T aux;
aux = v[i];
v[i] = v[j];
v[j] = aux;
}
}
} for(int i=0; i< n;i++){
cout << v[i] << endl;
}
}
int main(){
int v1[5] = {3, 8, 4, 7, 2};
string v3[4] = { "irene", "ana", "david", "zzz"};
ordenar(v3,4);
}
| true |
8fe6a8a2d37ee829e31deca8cf18fb241add197d | C++ | justincervantes/InfoSniffer | /Source Code/session.cpp | UTF-8 | 9,434 | 2.890625 | 3 | [] | no_license | /*------------------------------------------------------------------------------------------------------------------
-- SOURCE FILE: session.cpp - This file contains all the Winsock 2 API calls.
--
-- PROGRAM: InfoSniffer
--
-- FUNCTIONS:
-- QString hostNameToIP(QString input);
-- QString ipToHostName(QString input);
-- QString serviceNameProtocolToPortNumber(QString input);
-- QString PortNumberToServiceNameProtocol(QString input);
--
-- DATE: January 16, 2020
--
-- REVISIONS: (Date and Description)
-- N/A
--
-- DESIGNER: Justin Cervantes
--
-- PROGRAMMER: Justin Cervantes
--
-- NOTES:
-- All API calls have error handling, however the return for all methods, which is a QString (Qt version of
-- std::string), will give a bit more details to the UI via the calling method, so it will return the
-- error for the user. The calling method from the application layer (application.cpp) is on_pushButton_clicked().
-- All code in this file has been adapted from Aman Abdulla's samples on Winsock 2.
--
----------------------------------------------------------------------------------------------------------------------*/
#include "session.h"
#define _WINSOCK_DEPRECATED_NO_WARNINGS
/*------------------------------------------------------------------------------------------------------------------
-- FUNCTION: hostNameToIP
--
-- DATE: January 16, 2020
--
-- REVISIONS: (Date and Description)
-- N/A
--
-- DESIGNER: Aman Abdulla
--
-- PROGRAMMER: Justin Cervantes
--
-- INTERFACE: QString hostNameToIP(QString input)
-- QString input: the query to be processed.
--
-- RETURNS: Returns the IP address(es) of the provided host name as a QString.
-- Returns an error message provided by h_errno if gethostbyname fails.
-- NOTES:
-- This function is used to determine the IP address(es) of a hostname.
----------------------------------------------------------------------------------------------------------------------*/
QString hostNameToIP(QString input) {
QString retval = "Resolving the hostname's IP: \n";
const char *str;
QByteArray ba;
ba = input.toLatin1();
str = ba.data();
struct hostent *hp;
struct in_addr my_addr, *addr_p;
char **p;
WORD wVersionRequested = MAKEWORD(2,2);
WSADATA wsaData;
// Open a Winsock v2.2 session
WSAStartup(wVersionRequested, &wsaData);
addr_p = (struct in_addr*)malloc(sizeof(struct in_addr));
addr_p = &my_addr;
// Queries the hostname, error is stored in h_errno if failed
if((hp=gethostbyname(str)) == NULL) {
switch(h_errno) {
case HOST_NOT_FOUND:
return "No such host";
case TRY_AGAIN:
return "Try again later";
case NO_RECOVERY:
return "DNS Error";
case NO_ADDRESS:
return "No IP Address for the given host";
default:
QString unknownError = "Unknown error: ";
unknownError.append(h_errno);
return unknownError;
}
}
// Checks the address list of the hostname lookup and provides all known IP addresses
for(p = hp->h_addr_list; *p != 0; p++) {
struct in_addr in;
memcpy(&in.s_addr, *p, sizeof (in.s_addr));
retval.append(inet_ntoa(in));
retval.append("\n");
}
return retval;
}
/*------------------------------------------------------------------------------------------------------------------
-- FUNCTION: ipToHostName
--
-- DATE: January 16, 2020
--
-- REVISIONS: (Date and Description)
-- N/A
--
-- DESIGNER: Aman Abdulla
--
-- PROGRAMMER: Justin Cervantes
--
-- INTERFACE: QString ipToHostName(QString input)
-- QString input: the IP address to be processed.
--
-- RETURNS: Returns the host name of the provided IP address as a QString.
-- Returns an error message if the input is not in correct IP format (x.x.x.x) or if the query fails to retrieve
-- a valid host name.
-- NOTES:
-- This function is used to determine the host name of an IP address.
----------------------------------------------------------------------------------------------------------------------*/
QString ipToHostName(QString input) {
QString retval = "Resolving the IP address' hostname: \n";
const char *str;
QByteArray ba;
ba = input.toLatin1();
str = ba.data();
int a;
struct hostent *hp;
struct in_addr my_addr, *addr_p;
char **p;
char ip_address[256]; // String for IP address
WORD wVersionRequested = MAKEWORD(2,2);
WSADATA wsaData;
// Open a Winsock v2.2 session
WSAStartup(wVersionRequested, &wsaData);
addr_p = (struct in_addr*)malloc(sizeof(struct in_addr));
addr_p = &my_addr;
if(isdigit(*str)) {
if((a = inet_addr(str)) == 0) {
return "IP Address must be of the form x.x.x.x\n";
}
strcpy(ip_address, str);
addr_p->s_addr=inet_addr(ip_address);
hp = gethostbyaddr((char *) addr_p, PF_INET, sizeof(my_addr));
if(hp == NULL) {
return "Host information not found\n";
}
} else {
return "IP's must begin with a digit";
}
// Checks the address list of the IP lookup and provides all known host names
for(p = hp->h_addr_list; *p != 0; p++) {
struct in_addr in;
memcpy(&in.s_addr, *p, sizeof (in.s_addr));
retval.append(hp->h_name);
retval.append("\n");
}
WSACleanup();
return retval;
}
/*------------------------------------------------------------------------------------------------------------------
-- FUNCTION: serviceNameProtocolToPortNumber
--
-- DATE: January 16, 2020
--
-- REVISIONS: (Date and Description)
-- N/A
--
-- DESIGNER: Aman Abdulla
--
-- PROGRAMMER: Justin Cervantes
--
-- INTERFACE: QString serviceNameProtocolToPortNumber(QString input)
-- QString input: the query to be processed. The input must have the delimeter ','. Leading and trailing
-- whitespace is trimmed for the second parameter. Valid input form: "<service name>, <protocol>"
--
-- RETURNS: Returns a message which explains the port number of the provided service name and protocol.
-- Returns a usage reminder if a valid input is not received.
-- Returns an error update if getservbyname was unable to retrieve the port number.
--
-- NOTES:
-- This function is used to determine the port number of a service.
----------------------------------------------------------------------------------------------------------------------*/
QString serviceNameProtocolToPortNumber(QString input) {
QString retval = "";
QStringList elements = input.split(',');
// Ensure only 2 parameters are entered
if(elements.length() != 2) {
return "Invalid input received, Usage: service, protocol";
}
struct servent *sv;
WORD wVersionRequested = MAKEWORD(2,2);
WSADATA wsaData;
const char *service;
const char *protocol;
//Converts a QString to a char*
QByteArray ba;
ba = elements[0].toLatin1();
service = ba.data();
ba = elements[1].trimmed().toLatin1();
protocol = ba.data();
// Open a Winsock v2.2 session
WSAStartup(wVersionRequested, &wsaData);
sv = getservbyname(service, protocol);
if(sv == NULL) {
return "Error in getservbyname\n";
}
retval.append("The port number for service ");
retval.append(service);
retval.append(" is: ");
retval.append(QString::number(ntohs(sv->s_port)));
WSACleanup();
return retval;
}
/*------------------------------------------------------------------------------------------------------------------
-- FUNCTION: PortNumberToServiceNameProtocol
--
-- DATE: January 16, 2020
--
-- REVISIONS: (Date and Description)
-- N/A
--
-- DESIGNER: Aman Abdulla
--
-- PROGRAMMER: Justin Cervantes
--
-- INTERFACE: QString PortNumberToServiceNameProtocol(QString input)
-- QString input: the query to be processed. The input must have the delimeter ','. Leading and trailing
-- whitespace is trimmed for the second parameter. Valid input form: "<service name>, <protocol>"
--
-- RETURNS: Returns a message which explains the service name of the provided port number and protocol.
-- Returns a usage reminder if a valid input is not received.
-- Returns an error update if getservbyport was unable to resolve the service name.
--
-- NOTES:
-- This function is used to determine the name of a service.
----------------------------------------------------------------------------------------------------------------------*/
QString PortNumberToServiceNameProtocol(QString input) {
QString retval = "";
QStringList elements = input.split(',');
// Ensure only 2 parameters are entered
if(elements.length() != 2) {
return "Usage: service, protocol";
}
struct servent *sv;
int s_port;
WORD wVersionRequested = MAKEWORD(2,2);
WSADATA wsaData;
const char *port;
const char *protocol;
//Converts a QString to a char*
QByteArray ba;
ba = elements[0].toLatin1();
port = ba.data();
ba = elements[1].trimmed().toLatin1();
protocol = ba.data();
// Open a Winsock v2.2 session
WSAStartup(wVersionRequested, &wsaData);
s_port = atoi(port);
sv = getservbyport(htons(s_port), protocol);
if(sv == NULL) {
return "Error in getservbyport\n";
}
retval.append("The service for port ");
retval.append(QString::number(s_port));
retval.append(" is: ");
retval.append(sv->s_name);
WSACleanup();
return retval;
}
| true |
6d4eaa19840a08cc271853e1e1e2c2951597d0bb | C++ | beikehanbao23/dlgv32 | /dlgv32/gctpc/imolwinv.cxx | UTF-8 | 4,446 | 2.671875 | 3 | [] | no_license | /*******************************************************************************
NAME INTERRUPTED MOLLWEIDE
PURPOSE: Transforms input Easting and Northing to longitude and
latitude for the Interrupted Mollweide projection. The
Easting and Northing must be in meters. The longitude
and latitude values will be returned in radians.
PROGRAMMER DATE REASON
---------- ---- ------
D. Steinwand, EROS June, 1991 Initial Development
S. Nelson, EDC June, 1993 Changed precision for values to
determine regions and if coordinates
are in the break, and for the values
in the conversion algorithm.
ALGORITHM REFERENCES
1. Snyder, John P. and Voxland, Philip M., "An Album of Map Projections",
U.S. Geological Survey Professional Paper 1453 , United State Government
Printing Office, Washington D.C., 1989.
2. Snyder, John P., "Map Projections--A Working Manual", U.S. Geological
Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
State Government Printing Office, Washington D.C., 1987.
*******************************************************************************/
#include "gctpc/cproj.h"
#include "gctpc/report.h"
/* Variables common to all subroutines in this code file
-----------------------------------------------------*/
static double R; /* Radius of the earth (sphere) */
static double lon_center[6]; /* Central meridians, one for each region */
static double feast[6]; /* False easting, one for each region */
/* Initialize the Interrupted Mollweide projection
--------------------------------------------*/
long
imolwinvint(double r)
/* (I) Radius of the earth (sphere) */
{
/* Place parameters in static storage for common use
-------------------------------------------------*/
R = r;
/* Initialize central meridians for each of the 6 regions
------------------------------------------------------*/
lon_center[0] = 1.0471975512; /* 60.0 degrees */
lon_center[1] = -2.96705972839; /* -170.0 degrees */
lon_center[2] = -0.523598776; /* -30.0 degrees */
lon_center[3] = 1.57079632679; /* 90.0 degrees */
lon_center[4] = -2.44346095279; /* -140.0 degrees */
lon_center[5] = -0.34906585; /* -20.0 degrees */
/* Initialize false eastings for each of the 6 regions
---------------------------------------------------*/
feast[0] = R * -2.19988776387;
feast[1] = R * -0.15713484;
feast[2] = R * 2.04275292359;
feast[3] = R * -1.72848324304;
feast[4] = R * 0.31426968;
feast[5] = R * 2.19988776387;
/* Report parameters to the user
-----------------------------*/
ptitle("INTERRUPTED MOLLWEIDE EQUAL-AREA");
radius(r);
return(OK);
}
long
imolwinv(double x, double y, double *lon, double *lat)
/* (I) X projection coordinate */
/* (I) Y projection coordinate */
/* (O) Longitude */
/* (O) Latitude */
{
double adjust_lon(double x); /* Function to adjust longitude to -180 - 180 */
double theta;
double temp;
long region;
/* Inverse equations
-----------------*/
if (y >= 0.0)
{
if (x <= R * -1.41421356248) region = 0;
else if (x <= R * 0.942809042) region = 1;
else region = 2;
}
else
{
if (x <= R * -0.942809042) region = 3;
else if (x <= R * 1.41421356248) region = 4;
else region = 5;
}
x = x - feast[region];
theta = asin(y / (1.4142135623731 * R));
*lon = adjust_lon(lon_center[region] + (x / (0.900316316158*R * cos(theta))));
*lat = asin((2.0 * theta + sin(2.0 * theta)) / PI);
/* Are we in a interrupted area? If so, return status code of IN_BREAK.
---------------------------------------------------------------------*/
if (region == 0 && (*lon < 0.34906585 || *lon > 1.91986217719))return(IN_BREAK);
if (region == 1 && ((*lon < 1.91986217719 && *lon > 0.34906585) ||
(*lon > -1.74532925199 && *lon < 0.34906585))) return(IN_BREAK);
if (region == 2 && (*lon < -1.745329252 || *lon > 0.34906585)) return(IN_BREAK);
if (region == 3 && (*lon < 0.34906585 || *lon > 2.44346095279))return(IN_BREAK);
if (region == 4 && ((*lon < 2.44346095279 && *lon > 0.34906585) ||
(*lon > -1.2217304764 && *lon < 0.34906585))) return(IN_BREAK);
if (region == 5 && (*lon < -1.2217304764 || *lon> 0.34906585))return(IN_BREAK);
return(OK);
}
| true |
6f1b0dd3bbf50f3e3ba50f58f718d24207a77b3e | C++ | avidLearnerInProgress/Cpp17-STL-Cookbook | /Chapter01/fold_expressions.cpp | UTF-8 | 2,836 | 3.5625 | 4 | [
"MIT"
] | permissive | #include <stdio.h>
#include <string>
#include <vector>
#include <type_traits>
#include <algorithm>
#include <set>
#include <cassert>
// C++11 style recursive sum function
template <typename T>
auto sum_rec(T t)
{
return t;
}
template <typename T, typename ... Ts>
auto sum_rec(T t, Ts ... ts)
{
return t + sum_rec(ts...);
}
// C++17 style fold expression
template <typename ... Ts>
auto sum(Ts ... ts)
{
return (0 + ... + ts);
}
// C++17 style fold expression with constexpr if addition to make it more generic
template <typename ... Ts>
auto sum_generic(Ts ... ts)
{
if constexpr ((std::is_same<Ts, const char*>::value && ...)) {
// Works with const char* parameters
return (std::string{} + ... + std::string{ts});
} else if constexpr ((std::is_same<Ts, std::string>::value && ...)) {
// Works with std::string parameters
return (std::string{} + ... + ts);
} else {
// Works with integral/floating point types
return (0 + ... + ts);
}
}
template <typename ... Ts>
auto logical_or(Ts ... ts)
{
return (... || ts);
}
template <typename ... Ts>
auto bitwise_or(Ts ... ts)
{
return (0 | ... | ts);
}
template <typename T, typename ... Ts>
bool within(T min, T max, Ts ...ts)
{
return ((min <= ts && ts <= max) && ...);
}
template <typename C, typename ... Ts>
auto matches(const C &a, Ts ... ts)
{
return (std::count(std::begin(a), std::end(a), ts) + ...);
}
template <typename C, typename ... Ts>
bool insert_all(C &s, Ts ... ts)
{
return (s.insert(ts).second && ...);
}
int main() {
assert( sum_rec(1, 2, 3, 4, 5) == 15);
assert( sum(1, 2, 3, 4, 5) == 15);
assert( sum(1, 2, 3, 4, 5, 6.5) == 21.5);
std::string hello {"Hello"};
std::string world {" world"};
assert( sum_generic(hello, world) == "Hello world");
assert( sum_generic(std::string("a"), std::string("b"), std::string("c")) == "abc");
assert( sum_generic("a", "b", "c") == "abc");
assert( logical_or() == false);
assert( logical_or(false, true) == true);
assert( bitwise_or(1, 2, 4) == 7);
assert( bitwise_or() == 0);
assert(within(0, 9, 1, 2, 3, 4, 5) == true);
assert(within(0, 9, 1, 2, 3, 4, 20) == false);
std::string aaa {"aaa"};
std::string bcd {"bcd"};
std::string def {"def"};
std::string zzz {"zzz"};
assert( within(aaa, zzz, bcd, def));
assert(!within(aaa, def, bcd, zzz));
std::set<int> s;
assert( insert_all(s, 1, 2, 3) == true);
assert( insert_all(s, 4, 5, 6, 6) == false);
assert( 1 == matches(std::vector<int>{1, 2, 3, 4}, 2, 5) );
assert( 1 == matches(std::initializer_list<int>{1, 2, 3, 4}, 10, 2) );
assert( 1 == matches("abcdefg", 'x', 'y', 'z', 'd') );
assert( 3 == matches("abcdefg", 'a', 'c', 'e', 'z') );
}
| true |
e011b8e4cd01edba3cd4453f26e7e94b184a3841 | C++ | AnkangH/LeetCode | /BFS/269. 火星词典.cpp | UTF-8 | 2,994 | 3.6875 | 4 | [] | no_license | /*
现有一种使用字母的全新语言,这门语言的字母顺序与英语顺序不同。
假设,您并不知道其中字母之间的先后顺序。但是,会收到词典中获得一个 不为空的 单词列表。因为是从词典中获得的,
所以该单词列表内的单词已经 按这门新语言的字母顺序进行了排序。
您需要根据这个输入的列表,还原出此语言中已知的字母顺序。
示例 1:
输入:
[
"wrt",
"wrf",
"er",
"ett",
"rftt"
]
输出: "wertf"
示例 3:
输入:
[
"z",
"x",
"z"
]
输出: ""
解释: 此顺序是非法的,因此返回 ""。
注意:
你可以默认输入的全部都是小写字母
假如,a 的字母排列顺序优先于 b,那么在给定的词典当中 a 定先出现在 b 前面
若给定的顺序是不合法的,则返回空字符串即可
若存在多种可能的合法字母顺序,请返回其中任意一种顺序即可
*/
class Solution {
public:
string alienOrder(vector<string>& words)
{
vector<vector<bool>> ad(26,vector<bool>(26,false));//邻接表 若a在b前 有ad[a][b]=true
vector<int> inDec(26,INT_MAX);//每个出现字母的入度
vector<bool> known(26,false);//出现过的字母
int n=words.size();//单词数目
for(int i=0;i<n-1;i++)//12 23...n-2,n-1
{
int sizea=words[i].size();
int sizeb=words[i+1].size();
int size=min(sizea,sizeb);
for(int j=0;j<sizea;j++)
known[words[i][j]-'a']=true;//保存当前单词中出现的字母
for(int j=0;j<size;j++)
if(words[i][j]!=words[i+1][j])//相邻单词第一个不同字母
{
ad[words[i][j]-'a'][words[i+1][j]-'a']=true;//构建邻接关系
break;//退出
}
}
for(auto p:words[n-1])
known[p-'a']=true;//最后一个单词出现的字母 记录
int cnt=0;//出现过的字母数目
for(int i=0;i<26;i++)
if(known[i])
{
inDec[i]=0;//出现过的字母 入度初始化为0
cnt++;//出现过的字母
}
for(int i=0;i<26;i++)
for(int j=0;j<26;j++)
{
if(j==i)
continue;//跳过a->a
if(ad[i][j])
inDec[j]++;//a->b 则b的入度+1
}
queue<int> q;//拓扑排序辅助队列
string res;
for(int i=0;i<26;i++)
if(inDec[i]==0)
q.push(i);//入度为0的先入队列
while(!q.empty())
{
int cur=q.front();//当前字母
q.pop();
res+=cur+'a';//放入拓扑排序中
for(int i=0;i<26;i++)
if(ad[cur][i])//当前字母的邻接表每个字母
{
inDec[i]--;//其入度-1
if(inDec[i]==0)
q.push(i);//若入度为0 则入队列
}
}
if(res.size()==cnt)
return res;//出现所有字母有拓扑排序
else
return "";//无拓扑排序
}
};
| true |
0bb371d8f08fef728b95b5c91bd6d1d2e3822fc3 | C++ | Skuuully/UniGraphicsI | /Rasteriser/Camera.h | UTF-8 | 663 | 2.828125 | 3 | [] | no_license | #pragma once
#include"Vertex.h"
#include"Matrix.h"
#include <math.h>
class Camera
{
public:
Camera();
~Camera();
Camera(float xRotation, float yRotation, float zRotation, const Vertex &position);
//Accessors
float GetxRotation();
void SetxRotation(const float xRotation);
float GetyRotation();
void SetyRotation(const float yRotation);
float GetzRotation();
void SetzRotation(const float zRotation);
Vertex GetPosition();
void SetPosition(const Vertex newPos);
void CreateMatrix();
Matrix GetViewMatrix();
private:
float _xRotation;
float _yRotation;
float _zRotation;
Vertex _position;
Matrix _view;
};
| true |
03bc32c5a9a6d5a593197e6ebacbc49e02536615 | C++ | juanfparra12/COP3530_Project2 | /Project2.cpp | UTF-8 | 6,292 | 3.96875 | 4 | [] | no_license | #include <vector>
#include <string>
#include <iostream>
using namespace std;
void calculatingLongestPrefixSuffix(string hint, int lengthOfHint, int *LPS);
//Uses KMP patterm searching algorithm
vector<int> KMP(string hint, string initial)
{
//Converts the length of the strings into int variables
int lengthOfHint = hint.length();
int legnthOfInitial = initial.length();
//Array for storing of LPS values of hint string
int LPS[lengthOfHint];
//Vector for storing the index of a char match between the initial and hint string
vector<int> indexOfMatch;
//Calulates the LPS values and stroes them
calculatingLongestPrefixSuffix(hint, lengthOfHint, LPS);
//Start of initial index
int x = 0;
//Start of hint index
int y = 0;
while (x < legnthOfInitial)
{
//Matching chars causes both indices to increment
if (hint[y] == initial[x])
{
y++;
x++;
}
//Storing hint index when result is matched with initial string
if (y == lengthOfHint)
{
//Stores index of hint string
indexOfMatch.push_back(x-y);
y = LPS[y - 1];
}
//When new char is found
else if (x < legnthOfInitial && hint[y] != initial[x])
{
//When first char is not the same as the hint index
//Goes to matching index of previous j-1 indices
if (y != 0)
{
y = LPS[y - 1];
}
//Else increment initial index
else
{
x++;
}
}
}
//Retrun result of the matched indices
return indexOfMatch;
}
//Calculates the Longest Prefix Suffix (LPS) of the hint string
void calculatingLongestPrefixSuffix(string hint, int lengthOfHint, int *LPS)
{
//int value of the previousLength of the LPS
int prevLength = 0;
//Initial value of LPS must always start at 0, the beginning
LPS[0] = 0;
//Begin on index 1
int x = 1;
while (x < lengthOfHint)
{
//If chars match, increments index number and store in LPS array
if (hint[x] == hint[prevLength])
{
prevLength++;
LPS[x] = prevLength;
x++;
}
else
{
//When no matching is found , decrement LPS index value by 1
if (prevLength != 0)
{
prevLength = LPS[prevLength - 1];
}
//if no LPS index value initialze to 0.
else
{
LPS[x] = 0;
x++;
}
}
}
}
//Longest Common Subsequence between fowards and backward index subtractions
void longestCommonCombination(vector<int> indexSubtraction)
{
int dimension = indexSubtraction.size();
int y;
//Create a square matrix to compare common chars for each backward and forward subtraction of indices
int matrix[dimension][dimension];
//When common subsequence is only one char long
for (int x = 0; x < dimension; x++)
{
matrix[x][x] = 1;
}
//Loops for the length of the indexSubtraction
for (int z = 2; z <= dimension; z++)
{
//Upper values of foward index subtraction
for (int x = 0; x < dimension - z + 1; x++)
{
//Y value
y = x + z-1;
//When common subsequence is only two chars long
if (indexSubtraction[x] == indexSubtraction[y] && z == 2)
{
matrix[x][y] = 2;
}
//LCS must have the the same chars at the first and last chars of the string
else if (indexSubtraction[x] == indexSubtraction[y])
{
matrix[x][y] = matrix[x + 1][y - 1] + 2;
}
//When chars are not the same find max of both strings
else
{
matrix[x][y] = max(matrix[x][y - 1], matrix[x + 1][y]);
}
}
}
//Value of combination
int lengthOfCombination = matrix[0][dimension - 1];
int combination[lengthOfCombination];
//first and last chars of the combination
int first = 0;
int last = lengthOfCombination - 1;
//Initial values of each edge of spectrum
int x = 0;
y = dimension - 1;
while (last - first >= 1)
{
//When chars of backwards and fowards index subtractions are the same
//Stores indices of matching chars
if (indexSubtraction.at(x) == indexSubtraction.at(y))
{
combination[first] = indexSubtraction.at(x);
combination[last] = combination[first];
first++;
last--;
x++;
y--;
}
//When last chars do not match on neither backwards nor fowards index subtractions strings
else
{
if (matrix[x + 1][y] > matrix[x][y - 1])
{
x++;
}
else
{
y--;
}
}
}
//handling odd number LCS
if (last == first)
{
combination[last] = indexSubtraction.at(x);
}
//Printing combination result
for (int x = 0; x < lengthOfCombination; x++)
{
cout << combination[x];
if (x != lengthOfCombination - 1)
{
cout << " ";
}
}
}
int main()
{
string initial;
string hint;
getline(cin, initial);
getline(cin, hint);
//indexofMatch values stored for both hint and initial strings into vector
vector<int> indexOfMatch = KMP(hint, initial);
//Store subtraction of indecies
vector<int> indexSubtraction;
//When no matching hint string in initial string or hint string with one occurance
//Cannot subtract indices of solo index, thus empty string
if (indexOfMatch.size() == 1 || indexOfMatch.size() == 0 )
{
cout << endl;
return 0;
}
//Subtracting index x and index x+1
for (int x = 0; x < indexOfMatch.size() - 1; x++)
{
int result = indexOfMatch[x + 1]-indexOfMatch[x];
indexSubtraction.push_back(result);
}
//Final result
longestCommonCombination(indexSubtraction);
cout << endl;
}
| true |
23e7103eec535174d55fbb61c095def7c61a3cb7 | C++ | Gauraviiitian/Codechef_Solutions_Codes | /LRQUER.cpp | UTF-8 | 1,074 | 2.734375 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
const int N = 1e5; // limit for array size
int n; // array size
ll t[2*N];
multiset<int> s[4*N];
void build() { // build the tree
for (int i=n-1; i>0; --i) t[i] = max(t[i<<1], t[i<<1|1]);
}
void modify(int p, int value) { // set value at position p using 0 based index
for (t[p+=n]=value; p>1; p>>=1) t[p>>1] = min(t[p], t[p^1]);
}
int query(int l, int r) { // sum on interval [l, r) using 0 based index
int res = 100000000;
for (l+=n, r+=n; l<r; l>>=1, r>>=1){
if (l&1) res = min(t[l++], res);
if (r&1) res = min(t[--r], res);
}
return res;
}
int main(){
int t;
cin>>t;
while(t--){
int q;
cin>>n>>q;
for(int i=0; i<n; ++i) cin>>t[n+i];
build();
while(q--){
int t, l, r;
cin>>t>>l>>r;
if(t==1) cout<<query(l, r+1)<<endl;
else modify(l, r);
}
}
return 0;
}
| true |
91a4ee1647690ef7654b841503244da04ff5cabe | C++ | seanzaretzky23/AdvancedProgServer | /server/OnGoingGamesStatsManager.h | UTF-8 | 3,757 | 3 | 3 | [] | no_license | /****************************************************************
* Student name: sean zaretzky(209164086), yaniv zimmer (318849908)
* Course Exercise Group: 03, 05
*****************************************************************/
#ifndef ADVANCEDPROGSERVER_ONGOINGGAMESSTATSMANAGER_H
#define ADVANCEDPROGSERVER_ONGOINGGAMESSTATSMANAGER_H
#include "GameStats.h"
#include "GameHandler.h"
#include <vector>
#include <algorithm>
#include <iostream>
#include <unistd.h>
struct OnGoingGamesInfo{
GameStats *gameStats;
pthread_t threadIdOfGame;
};
/*
* responsible for on going (games that are in process, players play between them) games.
* implemented as singleton class
*/
class OnGoingGamesStatsManager {
public:
/**************************************************************
* function name: getInstanceOfOnGoingGameStatsManager
* @return OnGoingGamesStatsManager *
* Function operation: returns pointer to the instance of the class
**************************************************************/
static OnGoingGamesStatsManager *getInstanceOfOnGoingGameStatsManager();
/**************************************************************
* function name: startGame
* Input:GameStats *newGameStats
* @return void
* Function operation: creates new game and thread and put it
* in the game in the thread.
**************************************************************/
void startGame(GameStats *newGameStats);
//returns true if removal succeded and false if there is no game with the given name in the OnGoingGamesStatsManager (removal failed)
//also closes the sockets of the players in the removed game
/**************************************************************
* function name: removeGame
* Input:const GameStats * const gameStats
* @return bool
* Function operation: removes the game which's pointer received
* returns true if removal succeded and
* false if there is no game with the given name in the
* OnGoingGamesStatsManager (removal failed)
* also closes the sockets of the players in the removed game
**************************************************************/
bool removeGame(const GameStats * const gameStats);
/**************************************************************
* function name: stopAndTerminateAllGames
* Input:none
* @return void
* Function operation: terminate all games
**************************************************************/
void stopAndTerminateAllGames();
//bool gameExists(std::string gameName) const;
//const std::vector<GameStats> getGames() const;
//void stopAllOnGoingGames();
/**************************************************************
* function name: OnGoingGamesStatsManager class destructor
**************************************************************/
~OnGoingGamesStatsManager();
private:
/**************************************************************
* function name: OnGoingGamesStatsManager private constructor
* Input:none
* @return instance of the OnGoingGamesStatsManager class
**************************************************************/
OnGoingGamesStatsManager();
std::vector<OnGoingGamesInfo *> onGoingGames;
/**************************************************************
* function name: startNewGame
* Input:const void *InfoForNewGame
* @return void *
* Function operation: static method that is used in the threads
* starting new game
**************************************************************/
static void *startNewGame(void *InfoForNewGame);
//instance of the singleton class
static OnGoingGamesStatsManager *instance;
};
#endif
| true |