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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1109bc1224dfa27c54160766022ccdfb4b66e85c | C++ | johnBuffer/ZombieV | /src/System/SoundPlayer.cpp | UTF-8 | 1,101 | 2.859375 | 3 | [] | no_license | #include "System/SoundPlayer.hpp"
std::vector<SoundHandler> SoundPlayer::_buffers;
void SoundHandler::update()
{
livingSounds.remove_if( [](sf::Sound& s){return s.getStatus() == sf::Sound::Stopped;} );
}
size_t SoundPlayer::registerSound(const std::string& filename, size_t maxSounds)
{
_buffers.push_back(SoundHandler());
SoundHandler& handler = _buffers.back();
handler.soundBuffer.loadFromFile(filename);
handler.maxLivingSounds = maxSounds;
return _buffers.size()-1;
}
void SoundPlayer::playInstanceOf(size_t soundID)
{
SoundHandler& handler = _buffers[soundID];
std::list<sf::Sound>& soundList(handler.livingSounds);
soundList.push_back(sf::Sound());
sf::Sound& newSound = soundList.back();
newSound.setBuffer(_buffers[soundID].soundBuffer);
newSound.play();
if (soundList.size() > handler.maxLivingSounds)
{
soundList.front().stop();
soundList.pop_front();
}
handler.update();
}
sf::Sound SoundPlayer::getInstanceOf(size_t soundID)
{
sf::Sound sound(_buffers[soundID].soundBuffer);
return sound;
}
| true |
a62e1ed5f202f571f449db31cd2b6902dd777b7a | C++ | AdrianNostromo/CodeSamples | /CPP_Joc_Windows_Android/SH_Client_Win_Cpp_Cmake/App/src/base/view/debug/entryUser/DebugEntryUser.cpp | UTF-8 | 2,434 | 2.609375 | 3 | [] | no_license | #include "DebugEntryUser.h"
#include "../entry/IDebugEntry.h"
#include <base/util/StringUtil.h>
using namespace base;
DebugEntryUser::DebugEntryUser(IDebugEntry* debugEntry)
: debugEntry(debugEntry)
{
//void
}
bool DebugEntryUser::getIsConnected() {
return debugEntry != nullptr ? true : false;
}
void DebugEntryUser::remove() {
if (debugEntry != nullptr) {
debugEntry->remove();
}
}
void DebugEntryUser::setLinesCount(int linesCount) {
debugEntry->setLinesCount(linesCount);
}
void DebugEntryUser::setPlaceholderedText(std::string placeholderedText) {
this->placeholderedText = placeholderedText;
invalidateData();
}
void DebugEntryUser::appendTrackedDataValue(std::shared_ptr<base::IWrappedValue> trackedWrappedValue) {
wrappedValuesList.appendDirect(trackedWrappedValue);
invalidateData();
}
void DebugEntryUser::invalidateData() {
if (debugEntry != nullptr) {
debugEntry->invalidateData();
}
}
void DebugEntryUser::setToggleSwitchIsOn(bool isOn) {
if (debugEntry != nullptr) {
debugEntry->setToggleSwitchIsOn(isOn);
}
}
void DebugEntryUser::setCb_onToggleSwitchStateChanged(
std::function<void(
IDebugEntryUser* debugEntryUser, bool newState)> cb_onToggleSwitchStateChanged)
{
this->cb_onToggleSwitchStateChanged = cb_onToggleSwitchStateChanged;
}
void DebugEntryUser::setCb_onBtnCursorDown(
std::function<void(
IDebugEntryUser* debugEntryUser)> cb_onBtnCursorDown)
{
this->cb_onBtnCursorDown = cb_onBtnCursorDown;
}
std::string DebugEntryUser::getText() {
std::string s = "";
s = placeholderedText;
for (int i = 0; i < wrappedValuesList.count(); i++) {
std::shared_ptr<base::IWrappedValue>& wrappedValue = wrappedValuesList.getReference(i);
int occurencesCount = 0;
std::string replacePattern = "#" + std::to_string(i) + "#";
if (wrappedValue->checkType(base::IWrappedValue::Type::T_int)) {
occurencesCount = StringUtil::replace(s, replacePattern, std::to_string(wrappedValue->getDirectAs_int()));
} else if (wrappedValue->checkType(base::IWrappedValue::Type::T_float)) {
occurencesCount = StringUtil::replace(s, replacePattern, StringUtil::floatToFixedPrecisionString(wrappedValue->getDirectAs_float(), 2));
} else {
throw LogicException(LOC);
}
if (occurencesCount != 1) {
// Replace not made or made more than once.
throw LogicException(LOC);
}
}
return s;
}
DebugEntryUser::~DebugEntryUser() {
if (debugEntry != nullptr) {
remove();
}
}
| true |
c29c791a6b8ffec945df6334d713b45cb36e0bc1 | C++ | jmh045000/utd_cs6378 | /hw3/Socket.h | UTF-8 | 1,459 | 3.421875 | 3 | [] | no_license | #ifndef __SOCKET_H__
#define __SOCKET_H__
#include <stdint.h>
#include <iostream>
#include <sstream>
#include <string>
class ClosedException : public std::exception {};
//simple wrapper around BSD tcp sockets
// basic idea is to write the code to deal with opening/closing sockets once
class Socket
{
protected:
//Vars:
bool connected;
int sockFD;
//Functions:
void createFD(void);
void connectFD(struct sockaddr * psaddr, uint32_t retries=50); //default to retry 50 times
int output(std::string data);
std::string input();
public:
Socket() {}
Socket(const Socket ©);
Socket(std::string host, uint16_t port);
Socket(int sockFD) : connected(true), sockFD(sockFD) {}
Socket(struct sockaddr * psaddr, uint32_t retries=50); //default to retry 50 times
~Socket();
bool isConnected() { return connected; }
void write(std::string data) { output(data); }
std::string read() { return input(); }
void closeSock();
//print if socket is connected
friend std::ostream & operator<< (std::ostream &ostr, Socket s)
{
if(s.connected)
ostr << "Connected with FD: " << s.sockFD;
else
ostr << "Not Connected";
return ostr;
}
};
//simple listen socket
class ListenSocket : public Socket
{
public:
~ListenSocket();
ListenSocket(uint16_t port);
Socket acceptConnection();
};
#endif /* __SOCKET_H__ */
| true |
e99193f42822956ae344b6d9a8ce5dcb060e51ff | C++ | ayush-105192219/c-test-code | /current/main.cpp | UTF-8 | 920 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <bits/stdc++.h>
using namespace std;
void fun1(int n)
{ switch(n){
case 1: std::cout<<"one";
break;
case 2: cout<<"two";
break;
case 3: cout<<"three";
break;
case 4: cout<<"four";
break;
case 5: cout<<"five";
break;
case 6: cout<<"six";
break;
case 7: cout<<"seven";
break;
case 8: cout<<"eight";
break;
case 9: cout<<"nine";
break;
}
}
int main()
{
int n;
cin >> n;
if (n>=1 && n<=9)
{
fun1(n);
}
else if (n>9)
{ int a = n%2;
if(n%2 == 0)
printf("even");
else
printf("odd");
}
return 0;
}
| true |
d21b4b20d67a8a9a9b0b02c413ca8a52cd57a0df | C++ | codeshef/datastructure-and-algorithm | /Algorithm/GreedyAlgorithm/Egyptian.cpp | UTF-8 | 564 | 3.5 | 4 | [] | no_license | // Egyptian form using greedy algorithm
#include<iostream>
using namespace std;
void printEgyptian(int nr,int dr)
{
if(dr==0 || nr==0)
{ return;
}
if(dr%nr ==0)
{
cout<<"1/"<<dr/nr;
return;
}
if(nr%dr==0)
{ cout<<nr/dr;
return;
}
if(nr > dr)
{ cout<<nr/dr<<"+";
printEgyptian(nr%dr,dr);
return;
}
// ceiling of dr/nr
int n =dr/nr+1;
cout<<"1/" <<n<<"+";
printEgyptian(nr*n-dr,dr*n);
}
int main(){
int nr=6,dr=14;
cout<<"Egyptian Fraction Representation of"<<nr<<"/"<<dr<<"is\n";
printEgyptian(nr,dr);
return 0;
}
| true |
045451457fbcd45dcdbbea30929b91c944f05dae | C++ | fernandezeric/acmudec | /DanielOrtega/Semestre1-2017/Hechos/11507.cpp | UTF-8 | 1,582 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main() {
int n;
while(1){
cin >> n;
if (n ==0)
break;
string pos1,a;
pos1= "+x";
for( int i = 0; i <n-1; i++ ){
cin >> a;
if(!pos1.compare("+x")){
if(!a.compare("+y"))
pos1="+y";
else if(!a.compare("-y"))
pos1="-y";
else if(!a.compare("+z"))
pos1= "+z";
else if(!a.compare("-z"))
pos1 = "-z";
}
else if(!pos1.compare("-x")){
if(!a.compare("+y"))
pos1="-y";
else if(!a.compare("-y"))
pos1="+y";
else if(!a.compare("+z"))
pos1= "-z";
else if(!a.compare("-z"))
pos1 = "+z";
}
else if(!pos1.compare("+y")){
if(!a.compare("+y"))
pos1="-x";
else if(!a.compare("-y"))
pos1="+x";
else if(!a.compare("+z"))
pos1= "+y";
else if(!a.compare("-z"))
pos1= "+y";
}
else if(!pos1.compare("-y")){
if(!a.compare("+y"))
pos1="+x";
else if(!a.compare("-y"))
pos1="-x";
else if(!a.compare("+z"))
pos1= "-y";
else if(!a.compare("-z"))
pos1= "-y";
}
else if(!pos1.compare("+z")){
if(!a.compare("+y"))
pos1="+z";
else if(!a.compare("-y"))
pos1="+z";
else if(!a.compare("+z"))
pos1= "-x";
else if(!a.compare("-z"))
pos1= "+x";
}
else if(!pos1.compare("-z")){
if(!a.compare("+y"))
pos1="-z";
else if(!a.compare("-y"))
pos1="-z";
else if(!a.compare("+z"))
pos1= "+x";
else if(!a.compare("-z"))
pos1= "-x";
}
}
cout << pos1 << "\n";
}
}
| true |
b9d7f1ae7309becb4d1129b255fcfbc5c3547a36 | C++ | eindacor/fractal_generator | /screencap.cpp | UTF-8 | 17,331 | 2.578125 | 3 | [] | no_license | #include "screencap.h"
string paddedValue(unsigned int value, unsigned short total_digits)
{
string padded_number;
for (int i = 0; i < total_digits; i++)
{
padded_number += std::to_string(value % 10);
value /= 10;
}
std::reverse(padded_number.begin(), padded_number.end());
return padded_number;
}
bool saveImage(const fractal_generator &fg, const shared_ptr<ogl_context> &context, image_extension ie, int multisample_count, shared_ptr<ogl_camera_flying> &camera)
{
cout << "rendering image..." << endl;
vec4 background_color = context->getBackgroundColor();
string resolution_input;
cout << "resolution: ";
std::getline(std::cin, resolution_input);
cout << endl;
int image_height = glm::clamp((resolution_input == "" || resolution_input == "\n") ? context->getWindowHeight() : std::stoi(resolution_input), 100, 5000);
int image_width = int(float(image_height) * float(context->getAspectRatio()));
float render_scale = float(image_height) / float(context->getWindowHeight());
int render_max_point_size = int(float(fg.getMaxPointSize()) * render_scale) * 2;
context->setUniform1i("max_point_size", render_max_point_size);
GLsizei width(image_width);
GLsizei height(image_height);
glEnable(GL_MULTISAMPLE);
// initialize multisample texture
GLuint multisample_tex;
glGenTextures(1, &multisample_tex);
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, multisample_tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, multisample_count, GL_RGBA8, width, height, GL_TRUE);
// initialize multisample fbo
GLuint multisample_fbo;
glGenFramebuffers(1, &multisample_fbo);
glBindFramebuffer(GL_FRAMEBUFFER, multisample_fbo);
// attach multisample texture
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, multisample_tex, 0);
GLuint depth_rb;
glGenRenderbuffers(1, &depth_rb);
glBindRenderbuffer(GL_RENDERBUFFER, depth_rb);
glRenderbufferStorageMultisample(GL_RENDERBUFFER, multisample_count, GL_DEPTH_COMPONENT24, width, height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth_rb);
char error_messages[256];
GLint value = glExtCheckFramebufferStatus(error_messages);
if (value < 0)
{
cout << "multisample: " << error_messages << endl;
return false;
}
glClearDepth(1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, width, height);
// render
fg.drawFractal(camera);
// initialize downsample texture
GLuint downsample_tex;
glGenTextures(1, &downsample_tex);
glBindTexture(GL_TEXTURE_2D, downsample_tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//NULL means reserve texture memory, but texels are undefined
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL);
// initialize downsample fbo
GLuint downsample_fbo;
glGenFramebuffers(1, &downsample_fbo);
glBindFramebuffer(GL_FRAMEBUFFER, downsample_fbo);
// attach downsample texture
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, downsample_tex, 0);
value = glExtCheckFramebufferStatus(error_messages);
if (value < 0)
{
cout << "downsample: " << error_messages << endl;
return false;
}
// select multisample framebuffer for reading
glBindFramebuffer(GL_READ_FRAMEBUFFER, multisample_fbo);
// select downsample framebuffer for drawing
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, downsample_fbo);
// blit from read framebuffer to draw framebuffer
glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
GLubyte *pixels = new GLubyte[width * height * 4];
if (pixels == NULL)
return false;
// select downsample framebuffer for reading
glBindFramebuffer(GL_READ_FRAMEBUFFER, downsample_fbo);
// read pixels
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
// delete resources
glDeleteFramebuffers(1, &multisample_fbo);
glDeleteFramebuffers(1, &downsample_fbo);
glDeleteRenderbuffers(1, &depth_rb);
glDeleteTextures(1, &multisample_tex);
glDeleteTextures(1, &downsample_tex);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
glBindTexture(GL_TEXTURE_2D, 0);
string filename;
string file_extension;
switch (ie)
{
case JPG: file_extension = ".jpg"; break;
case TIFF: file_extension = ".tiff"; break;
case BMP: file_extension = ".bmp"; break;
case PNG: file_extension = ".png"; break;
default: return false;
}
FILE *file_check;
string seed = fg.getSeed();
if (seed.length() > 32)
{
seed = seed.substr(0, 32);
}
int image_count = 0;
while (image_count < 256)
{
filename = seed + "_g" + paddedValue(fg.getGeneration(), 3) + "_" + paddedValue(image_count, 3) + file_extension;
file_check = fopen(filename.c_str(), "rb");
if (file_check == NULL) break;
else fclose(file_check);
++image_count;
if (image_count == 256)
{
cout << "Screenshot limit of 256 reached." << endl;
return false;
}
}
// save to image class
Bitmap output_bitmap(width, height);
vector<int> signature_indices = {
0, 1, 2, 3, 4, 6,
width, width + 2, width + 4, width + 6,
(width * 2) ,(width * 2) + 2, (width * 2) + 4, (width * 2) + 6,
(width * 3) + 2, (width * 3) + 4,
(width * 4), (width * 4) + 2, (width * 4) + 3, (width * 4) + 4, (width * 4) + 5, (width * 4) + 6,
(width * 5), (width * 5) + 2, (width * 5) + 4, (width * 5) + 6,
(width * 6), (width * 6) + 2, (width * 6) + 3, (width * 6) + 4, (width * 6) + 5, (width * 6) + 6
};
//convert to BGR format
for (int i = 0; i < width * height; i++)
{
int texture_index = i * 4;
ColorTranslator ct();
Color pixel_color;
if (std::find(signature_indices.begin(), signature_indices.end(), i) != signature_indices.end())
pixel_color = pixel_color.FromArgb(Byte(pixels[texture_index + 3]), Byte(255 - pixels[texture_index]), Byte(255 - pixels[texture_index + 1]), Byte(255 - pixels[texture_index + 2]));
else pixel_color = pixel_color.FromArgb(Byte(pixels[texture_index + 3]), Byte(pixels[texture_index]), Byte(pixels[texture_index + 1]), Byte(pixels[texture_index + 2]));
output_bitmap.SetPixel(i % width, height - (i / width) - 1, pixel_color);
}
delete[] pixels;
context->setBackgroundColor(background_color);
context->setUniform1i("max_point_size", fg.getMaxPointSize());
glViewport(0, 0, context->getWindowWidth(), context->getWindowHeight());
switch (ie)
{
case JPG: output_bitmap.Save(gcnew String(&filename[0]), ImageFormat::Jpeg); break;
case TIFF: output_bitmap.Save(gcnew String(&filename[0]), ImageFormat::Tiff); break;
case BMP: output_bitmap.Save(gcnew String(&filename[0]), ImageFormat::Bmp); break;
case PNG: output_bitmap.Save(gcnew String(&filename[0]), ImageFormat::Png); break;
default: return false;
}
cout << "file saved: " << filename << endl;
return true;
}
bool batchRender(fractal_generator &fg, const shared_ptr<ogl_context> &context, image_extension ie, int multisample_count, int x_count, int y_count, int quadrant_size, bool mix_background, shared_ptr<ogl_camera_flying> &camera)
{
cout << "rendering image..." << endl;
int initial_background_index = fg.getBackgroundColorIndex();
GLsizei width(quadrant_size);
GLsizei height(quadrant_size);
glEnable(GL_MULTISAMPLE);
vector<int> signature_indices = {
0, 1, 2, 3, 4, 6,
width, width + 2, width + 4, width + 6,
(width * 2) ,(width * 2) + 2, (width * 2) + 4, (width * 2) + 6,
(width * 3) + 2, (width * 3) + 4,
(width * 4), (width * 4) + 2, (width * 4) + 3, (width * 4) + 4, (width * 4) + 5, (width * 4) + 6,
(width * 5), (width * 5) + 2, (width * 5) + 4, (width * 5) + 6,
(width * 6), (width * 6) + 2, (width * 6) + 3, (width * 6) + 4, (width * 6) + 5, (width * 6) + 6
};
float render_scale = max(x_count, y_count);
int render_max_point_size = int(float(fg.getMaxPointSize()) * render_scale) * 2;
context->setUniform1i("max_point_size", render_max_point_size);
context->setUniform1i("render_quadrant", 1);
for (int quadrant_index = 0; quadrant_index < x_count * y_count; quadrant_index++)
{
if (mix_background)
fg.cycleBackgroundColorIndex();
// initialize multisample texture
GLuint multisample_tex;
glGenTextures(1, &multisample_tex);
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, multisample_tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, multisample_count, GL_RGBA8, width, height, GL_TRUE);
// initialize multisample fbo
GLuint multisample_fbo;
glGenFramebuffers(1, &multisample_fbo);
glBindFramebuffer(GL_FRAMEBUFFER, multisample_fbo);
// attach multisample texture
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, multisample_tex, 0);
GLuint depth_rb;
glGenRenderbuffers(1, &depth_rb);
glBindRenderbuffer(GL_RENDERBUFFER, depth_rb);
glRenderbufferStorageMultisample(GL_RENDERBUFFER, multisample_count, GL_DEPTH_COMPONENT24, width, height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth_rb);
char error_messages[256];
GLint value = glExtCheckFramebufferStatus(error_messages);
if (value < 0)
{
cout << "multisample: " << error_messages << endl;
return false;
}
// scaled_chunk_size is essentially the size of one quadrant scaled to the current viewspace
// the rendered viewspace is a square that's 2.0 long and 2.0 high (-1.0 to 1.0 in each axis)
// if that viewspace is to be broken up into 16 tiles, the scaled_chunk_size is the width and height of one of those tiles
// 16 tiles would mean the 2-unit viewspace becomes a 4x4 grid
// if scale == 4, then scaled_chunk_size is 0.5
// 4 tiles across x 0.5 = the original 2.0 of the viewspace
float scaled_chunk_size = 2.0f / render_scale;
float x_translation_start = (float(x_count) * scaled_chunk_size) / 2.0f;
float y_translation_start = (float(y_count) * scaled_chunk_size) / 2.0f;
float x_translation = ((float(quadrant_index % x_count) * scaled_chunk_size) - (x_translation_start - (scaled_chunk_size / 2.0f))) * -1.0f;
float y_translation = ((float(quadrant_index / x_count) * scaled_chunk_size) - (y_translation_start - (scaled_chunk_size / 2.0f))) * -1.0f;
mat4 quadrant_translation = glm::translate(mat4(1.0f), vec3(x_translation, y_translation, 0.0f));
mat4 quadrant_scale = glm::scale(mat4(1.0f), vec3(render_scale, render_scale, 1.0f));
mat4 quadrant_matrix = quadrant_scale * quadrant_translation;
context->setUniformMatrix4fv("quadrant_matrix", 1, GL_FALSE, quadrant_matrix);
glClearDepth(1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, quadrant_size, quadrant_size);
// render
fg.drawFractal(camera);
// initialize downsample texture
GLuint downsample_tex;
glGenTextures(1, &downsample_tex);
glBindTexture(GL_TEXTURE_2D, downsample_tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//NULL means reserve texture memory, but texels are undefined
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL);
// initialize downsample fbo
GLuint downsample_fbo;
glGenFramebuffers(1, &downsample_fbo);
glBindFramebuffer(GL_FRAMEBUFFER, downsample_fbo);
// attach downsample texture
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, downsample_tex, 0);
value = glExtCheckFramebufferStatus(error_messages);
if (value < 0)
{
cout << "downsample: " << error_messages << endl;
return false;
}
// select multisample framebuffer for reading
glBindFramebuffer(GL_READ_FRAMEBUFFER, multisample_fbo);
// select downsample framebuffer for drawing
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, downsample_fbo);
// blit from read framebuffer to draw framebuffer
glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
GLubyte *pixels = new GLubyte[width * height * 4];
if (pixels == NULL)
return false;
// select downsample framebuffer for reading
glBindFramebuffer(GL_READ_FRAMEBUFFER, downsample_fbo);
// read pixels
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
// delete resources
glDeleteFramebuffers(1, &multisample_fbo);
glDeleteFramebuffers(1, &downsample_fbo);
glDeleteRenderbuffers(1, &depth_rb);
glDeleteTextures(1, &multisample_tex);
glDeleteTextures(1, &downsample_tex);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
glBindTexture(GL_TEXTURE_2D, 0);
string filename;
string file_extension;
switch (ie)
{
case JPG: file_extension = ".jpg"; break;
case TIFF: file_extension = ".tiff"; break;
case BMP: file_extension = ".bmp"; break;
case PNG: file_extension = ".png"; break;
default: return false;
}
FILE *file_check;
int image_count = 0;
string seed = fg.getSeed();
if (seed.length() > 32)
{
seed = seed.substr(0, 32);
}
while (image_count < 256)
{
string dimension_string = std::to_string(y_count * quadrant_size) + "x" + std::to_string(x_count * quadrant_size);
filename = seed + "_g" + paddedValue(fg.getGeneration(), 3) + "_" + dimension_string + "_" + paddedValue(image_count, 3) + "_q" + paddedValue(quadrant_index, 2) + file_extension;
file_check = fopen(filename.c_str(), "rb");
if (file_check == NULL) break;
else fclose(file_check);
++image_count;
if (image_count == 256)
{
cout << "Screenshot limit of 256 reached." << endl;
return false;
}
}
// save to image class
Bitmap output_bitmap(width, height);
//convert to BGR format
for (int i = 0; i < width * height; i++)
{
int texture_index = i * 4;
ColorTranslator ct();
Color pixel_color;
if (quadrant_index == 0 && std::find(signature_indices.begin(), signature_indices.end(), i) != signature_indices.end())
pixel_color = pixel_color.FromArgb(Byte(pixels[texture_index + 3]), Byte(255 - pixels[texture_index]), Byte(255 - pixels[texture_index + 1]), Byte(255 - pixels[texture_index + 2]));
else pixel_color = pixel_color.FromArgb(Byte(pixels[texture_index + 3]), Byte(pixels[texture_index]), Byte(pixels[texture_index + 1]), Byte(pixels[texture_index + 2]));
output_bitmap.SetPixel(i % width, height - (i / width) - 1, pixel_color);
}
delete[] pixels;
switch (ie)
{
case JPG: output_bitmap.Save(gcnew String(&filename[0]), ImageFormat::Jpeg); break;
case TIFF: output_bitmap.Save(gcnew String(&filename[0]), ImageFormat::Tiff); break;
case BMP: output_bitmap.Save(gcnew String(&filename[0]), ImageFormat::Bmp); break;
case PNG: output_bitmap.Save(gcnew String(&filename[0]), ImageFormat::Png); break;
default: return false;
}
cout << "file saved: " << filename << endl;
}
if (mix_background)
fg.setBackgroundColorIndex(initial_background_index);
glViewport(0, 0, context->getWindowWidth(), context->getWindowHeight());
context->setUniform1i("max_point_size", fg.getMaxPointSize());
context->setUniform1i("render_quadrant", 0);
return true;
}
GLint glExtCheckFramebufferStatus(char *error_message)
{
GLenum status;
status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
switch (status)
{
case GL_FRAMEBUFFER_COMPLETE:
break;
case GL_FRAMEBUFFER_UNSUPPORTED:
//Choose different formats
strcpy(error_message, "Framebuffer object format is unsupported by the video hardware. (GL_FRAMEBUFFER_UNSUPPORTED)(FBO - 820)");
return -1;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
strcpy(error_message, "Incomplete attachment. (GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT)(FBO - 820)");
return -1;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
strcpy(error_message, "Incomplete missing attachment. (GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT)(FBO - 820)");
return -1;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
strcpy(error_message, "Incomplete draw buffer. (GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER)(FBO - 820)");
return -1;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
strcpy(error_message, "Incomplete read buffer. (GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER)(FBO - 820)");
return -1;
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
strcpy(error_message, "Incomplete multisample buffer. (GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE)(FBO - 820)");
return -1;
default:
//Programming error; will fail on all hardware
strcpy(error_message, "Some video driver error or programming error occured. Framebuffer object status is invalid. (FBO - 823)");
return -2;
}
return 1;
} | true |
7d7ccc2507088f1bc59be1a6f7f85f1bf2c652d4 | C++ | chhavibansal/CodeAsylum_cpp | /Batch_2_june/LIS.cpp | UTF-8 | 574 | 3.15625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int LongestincreasingSubsequence(int *arr, int n ){
int dp[n] ={0};
for(int i = 0 ; i < n ; i++)
dp[i] = 1;
int maxAns = 1 ;
for(int i = 1 ; i < n ; i++){
for(int j = 0 ; j < i ; j++){
if(arr[i] > arr[j]){
dp[i] = max(dp[i] , dp[j] + 1);
maxAns = max(maxAns , dp[i]);
}
}
}
return maxAns;
}
int main(){
int arr[]={10 , 22, 9, 33, 21, 50 , 41 , 60 };
int n = 8;
cout << LongestincreasingSubsequence(arr, n );
} | true |
7df67d97682185534131c6155ca353130a15d6ab | C++ | utmi-2014/utmi-soft2 | /140512/labmember4.h | UTF-8 | 296 | 2.890625 | 3 | [
"MIT"
] | permissive | class LabMember {
protected:
char name[32];
public:
LabMember() {}
LabMember(char* _name) {
strcpy(name, _name);
}
~LabMember() {
}
char* SetName(char* _name) {
sprintf(name, "Mr. %s", _name);
}
char* GetName() {
return name;
}
virtual void PrintInfo() {};
}; | true |
a7823bc7995870533ecfa7c48d8dc5e5d1604ba8 | C++ | poiqwe12/Pamsi_sortowanie | /Nagłówek.h | UTF-8 | 648 | 3.09375 | 3 | [] | no_license | #pragma once
#ifndef _nazwa_pliku_
#define _nazwa_pliku_
#include <iostream>
template<typename Typ,int Wymiar>
class Dane
{
Typ tab[Wymiar];
public:
const Typ& operator [] (unsigned int index)const
{
if (index < Wymiar) return tab[index];
exit(EXIT_FAILURE);
}
void Inicjuj_losowo();
};
template <typename Typ, int Wymiar>
std::ostream& operator << (std::ostream &Strm, const Dane<Typ, Wymiar> &D)
{
for (int i =0;i<Wymiar;++i)
{
Strm << D[i] << " ";
}
return Strm;
}
template<typename Typ, int Wymiar>
void Dane<Typ, Wymiar>::Inicjuj_losowo()
{
for (Typ &i : tab)
{
i = rand() ;
}
}
#endif
| true |
0ee0fd3c3939f095a2677a69c97e12b7f38d764e | C++ | shanmo/google-hash-code-2021 | /practice/solution/utils.h | UTF-8 | 2,203 | 3.328125 | 3 | [
"MIT"
] | permissive | #ifndef UTILS_H
#define UTILS_H
#include <exception>
#include <string>
#include <iostream>
#include <vector>
#include <fstream>
#include <unordered_map>
#include "pizza_delivery.h"
PizzaDelivery parse_input(const std::string& filename)
{
std::ifstream ifs(filename);
if (!ifs.is_open())
{
throw std::ios_base::failure("Cannot open input file");
}
int numPizza, numTeamTwo, numTeamThree, numTeamFour;
ifs >> numPizza >> numTeamTwo >> numTeamThree >> numTeamFour;
// for debugging, print info
// std::cout << "numPizza " << numPizza << " numTeamTwo " << numTeamTwo << " numTeamThree " << numTeamThree << " numTeamFour " << numTeamFour << std::endl;
std::vector<int> teamNums = {numTeamTwo, numTeamThree, numTeamFour};
pizza_vec pizzas;
for (int i = 0; i < numPizza; ++i)
{
// read one pizza
pizza piz;
piz.index = i;
int numIngredients;
std::string temp;
ifs >> temp;
numIngredients = std::stoi(temp);
piz.numIngredients = numIngredients;
// for debugging
// std::cout << "numIngredients: " << numIngredients << std::endl;
for (int j = 0; j < numIngredients; ++j)
{
std::string ingredient;
ifs >> ingredient;
piz.ingredients.push_back(ingredient);
}
// sort the ingredients, maybe useless
// std::sort(piz.ingredients.begin(), piz.ingredients.end());
pizzas.push_back(piz);
}
// for debugging, print input pizza info
// std::cout << pizzas;
return PizzaDelivery(pizzas, teamNums);
}
void save_results(std::unordered_multimap<int, std::vector<int>>& results, const std::string& filename)
{
std::ofstream ofs(filename);
if (!ofs.is_open())
{
throw std::ios_base::failure("Cannot open the output file");
}
// write the number of teams
ofs << results.size() << std::endl;
std::unordered_map<int, std::vector<int>>::iterator it = results.begin();
while (it != results.end())
{
ofs << it->first << " ";
for (const auto& piz_id : it->second)
ofs << piz_id << " ";
ofs << "\n";
it++;
}
ofs.close();
}
#endif // UTILS_H
| true |
6a95b181e5096fd75a7aef4ed85f47462e6732bc | C++ | OscarSandell/Wordchain | /kattis.h | UTF-8 | 5,027 | 3.390625 | 3 | [] | no_license | #pragma once
#include <vector>
#include <string>
#include <sstream>
#include <functional> // std::hash
using std::vector;
using std::string;
typedef unsigned char byte;
/**
* Fil med hjälpfunktioner för att hantera tecknen å, ä, ö och é korrekt i C++, vilket krävs för en
* accepterad lösning i Kattis.
*
* I C++ använder man oftast typen 'char' för att representera text. En 'char' är en byte stor, och
* kan därför inte representera alla tecken som är definierade i Unicode-standarden. På grund av det
* brukar man använda en teckenkodning som heter UTF-8, där alla tecken i ASCII (kör 'man ascii' i
* terminalen för att se alla tecken i ASCII) representeras med en byte, men resten kräver flera
* bytes. Tecknen å, ä, ö och é ligger tyvärr utanför ASCII och kommer därför vara representerade
* som flera tecken. I detta fall representeras dem som sekvenserna 0xC3 0xA5, 0xC3 0xA4, 0xC3 0xB6
* och 0xC3 0xA9 respektive. Detta måste vi ta hänsyn till för att kunna manipulera strängarna
* korrekt.
*
* Här löser vi problemet genom att omvandla tecknen å, ä, ö och é till tecknen '{', '|', '}' och
* '~' respektive. Det är inte den snyggaste lösningen, men i det här fallet är det smidigt eftersom
* de tecknen ligger precis efter 'z' i ASCII. Med hjälp av den här transformationen kan vi alltså
* fortfarande iterera över alla tecken smidigt med en loop:
*
* for (char i{'a'}; i <= '~'; i++)
*
* Den här filen implementerar två sätt att hantera strängar av den här typen. Ett manuellt sätt,
* där du själv måste komma ihåg att anropa 'from_utf8' och 'to_utf8' på lämpliga ställen, och en
* typ 'kattis_string' som ser till att göra det åt dig så länge du använder 'cin' och 'cout' för
* in/utmatning. Det finns också en vector, 'alphabet', som innehåller alla tecken i alfabetet, så
* att du enkelt kan iterera över alla tecken.
*/
/**
* Alla tecken i alfabetet, efter transformation till ASCII.
*/
const vector<char> alphabet = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '{', '|', '}', '~'
};
/**
* Manuell metod:
*/
// Konvertera från UTF-8 till vår representation.
string from_utf8(const string &utf8) {
std::ostringstream out;
for (size_t i = 0; i < utf8.size(); i++) {
if (byte(utf8[i]) == 0xC3) {
switch (byte(utf8[i + 1])) {
case 0xA5: // å
out << '{';
break;
case 0xA4: // ä
out << '|';
break;
case 0xB6: // ö
out << '}';
break;
case 0xA9: // é
out << '~';
break;
}
i++;
} else {
// Kontrollera om det råkade vara iso-latin-1 i indatan (vanligt på Windows)
switch (byte(utf8[i])) {
case 0xE5: // å
out << '{';
break;
case 0xE4: // ä
out << '|';
break;
case 0xF6: // ö
out << '}';
break;
case 0xE9: // é
out << '~';
break;
default:
out << utf8[i];
break;
}
}
}
return out.str();
}
// Konvertera från vår representation tillbaka till utf-8.
string to_utf8(const string &our) {
std::ostringstream out;
for (auto i : our) {
switch (i) {
case '{':
out << "å";
break;
case '|':
out << "ä";
break;
case '}':
out << "ö";
break;
case '~':
out << "é";
break;
default:
out << i;
break;
}
}
return out.str();
}
/**
* Semi-automatisk metod. Så länge all in- och utmatning sker med strömmar så sköts omvandlingen
* automatiskt.
*/
class kattis_string : public std::string {
public:
kattis_string() : string() {}
kattis_string(const string &src) : string(from_utf8(src)) {}
kattis_string(const kattis_string &src) = default;
};
// Tillåt användning i unordered_set och unordered_map.
namespace std {
template <>
struct hash<kattis_string> {
hash<string> original;
std::size_t operator () (const kattis_string &k) const {
return original(k);
}
};
}
std::ostream &operator <<(std::ostream &to, const kattis_string &from) {
return to << to_utf8(from);
}
std::istream &operator >>(std::istream &from, kattis_string &to) {
string tmp;
if (from >> tmp)
to = kattis_string(tmp);
return from;
}
namespace std {
istream &getline(istream &from, kattis_string &to) {
string tmp;
getline(from, tmp);
to = tmp; // Notera: Konverterar strängen korrekt.
return from;
}
}
| true |
85b21a69d9ce83466eb7a6cfdce39da9eb9b5e4b | C++ | faxinwang/cppNotes | /containters/data structure/myList/DLList.hpp | GB18030 | 2,274 | 3.546875 | 4 | [] | no_license |
#ifndef DLList_h
#define DLList_h
#include"../myColl/Coll.hpp"
#include"../myExp/myExp.hpp"
/*˫ʵ*/
template<class T>
class DLList:public Coll<T>{
private:
struct Node{
T data;
Node *prev,*next;
Node():prev(0),next(0){}
Node(const T& x,Node* pre=0,Node* nxt=0):data(x),prev(pre),next(nxt){}
};
Node *head,*tail;
int counter;
private:
Node* moveTo(int pos)const;
public:
DLList();
~DLList(){clear();delete head;delete tail;}
void clear();
int size()const{return counter;}
void remove(int pos);
int find(const T& x)const;
const T& at(int pos)const;
void push_back(const T& elem);
void push_front(const T& elem);
void insert(int pos,const T& x);
bool empty()const;
int capacity()const{return -1;}
};
template<class T>
typename DLList<T>::Node* DLList<T>::moveTo(int n)const{
Node* p = head;
if(n<=0||n>counter) throw OutOfBound();
while(n--)
p=p->next;
return p;
}
template<class T>
DLList<T>::DLList():counter(0){
head=new Node;
tail=new Node;
head->next=tail;
tail->prev=head;
}
template<class T>
bool DLList<T>::empty()const{
return !counter;
}
template<class T>
void DLList<T>::clear(){
Node *p=head->next;
Node *q;
head->next=tail;
tail->prev=head;
while(p!=tail){
q=p->next;
delete p;
p=q;
}
counter=0;
}
template<class T>
void DLList<T>::insert(int n,const T& elem){
Node *pos,*tmp;
pos=moveTo(n);
tmp=new Node(elem,pos->prev,pos);//elemŵnǰһλ
pos->prev->next=tmp;
pos->prev=tmp;
++counter;
}
template<class T>
void DLList<T>::remove(int n){
Node *pos;
pos=moveTo(n);
pos->prev->next=pos->next;
pos->next->prev=pos->prev;
delete pos;
--counter;
}
template<class T>
int DLList<T>::find(const T& x)const{
Node *p=head->next;
int i=0;
while(p!=tail && p->data != x){
p=p->next;
++i;
}
return p==tail?-1:i;
}
template<class T>
const T& DLList<T>::at(int n)const{
Node*p=moveTo(n);
return p->data;
}
template<class T>
void DLList<T>::push_back(const T& elem){
Node *tmp=new Node(elem,tail->prev,tail);
tail->prev->next=tmp;
tail->prev=tmp;
++counter;
}
template<class T>
void DLList<T>::push_front(const T& elem){
Node *tmp=new Node(elem,head,head->next);
head->next->prev=tmp;
head->next=tmp;
++counter;
}
#endif
| true |
dbff2619517ec9d226dfd19ddd1eadb9ace2a13e | C++ | kssenii/ClickHouse | /dbms/src/Storages/StorageInput.cpp | UTF-8 | 1,966 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | #include <Storages/StorageInput.h>
#include <Storages/IStorage.h>
#include <Interpreters/Context.h>
#include <DataStreams/IBlockInputStream.h>
#include <memory>
namespace DB
{
namespace ErrorCodes
{
extern const int INVALID_USAGE_OF_INPUT;
}
StorageInput::StorageInput(const String & table_name_, const ColumnsDescription & columns_)
: IStorage({"", table_name_})
{
setColumns(columns_);
}
class StorageInputBlockInputStream : public IBlockInputStream
{
public:
StorageInputBlockInputStream(Context & context_, const Block sample_block_)
: context(context_),
sample_block(sample_block_)
{
}
Block readImpl() override { return context.getInputBlocksReaderCallback()(context); }
void readPrefix() override {}
void readSuffix() override {}
String getName() const override { return "Input"; }
Block getHeader() const override { return sample_block; }
private:
Context & context;
const Block sample_block;
};
void StorageInput::setInputStream(BlockInputStreamPtr input_stream_)
{
input_stream = input_stream_;
}
BlockInputStreams StorageInput::read(const Names & /*column_names*/,
const SelectQueryInfo & /*query_info*/,
const Context & context,
QueryProcessingStage::Enum /*processed_stage*/,
size_t /*max_block_size*/,
unsigned /*num_streams*/)
{
Context & query_context = const_cast<Context &>(context).getQueryContext();
/// It is TCP request if we have callbacks for input().
if (query_context.getInputBlocksReaderCallback())
{
/// Send structure to the client.
query_context.initializeInput(shared_from_this());
input_stream = std::make_shared<StorageInputBlockInputStream>(query_context, getSampleBlock());
}
if (!input_stream)
throw Exception("Input stream is not initialized, input() must be used only in INSERT SELECT query", ErrorCodes::INVALID_USAGE_OF_INPUT);
return {input_stream};
}
}
| true |
0484a609a3a983cad227a7fb5a7ba984a76d79da | C++ | BrianGoga/School | /Networking/CPE400.cpp | UTF-8 | 4,811 | 3.234375 | 3 | [] | no_license | ////////////////////////////
// CPE 400 //
// Brian Goga //
// Battery Life of //
// Sensor nodes //
////////////////////////////
//Header Files
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <queue>
#include <string>
#include <time.h>
#include <vector>
using namespace std;
//Structs
struct Node
{
int batteryLife;
bool isOn;
queue<int> data;
int waitTime;
int sleepCounter;
};
//Functions
int senseData();
float simulation(float sleeplength);
int findBest(float *array);
//main
int main()
{
//variables
float results[9];
float ratios[9] = {0, 0.3, 0.5, 0.8, 1, 1.5, 2, 2.5, 3};
int best = 0;
//Rand it up
srand(time(NULL));
for(int i = 0; i < 9; i++)
{
//run through all the ratios and save results in an array
cout<<endl<<"Testing a ratio of " << ratios[i]<<" sleep/wake cycle"<<endl;
results[i] = simulation(ratios[i]);
}
//used to find the best ratio in results
cout<<endl;
cout<<"Finding best sleep/wake ratio..."<<endl;
best = findBest(results);
cout<<"The best sleep/wake ratio was: " << ratios[best] << " with a efficency of " << results[best] <<endl;
cout<<"This means the nodes only slept " << ratios[best] * 10 <<" percent of the time."<<endl<<endl;
//going home
return 0;
}
//Implementations
int senseData()
{
return rand() % 1000;
}
float simulation(float sleeplength)
{
//variables
vector<Node> sensorArray;
Node tempNode;
int cycleCounter = 0;
int throughput = 0;
int offset = 0;
float ratio;
//initialize Vector
tempNode.batteryLife = 100;
tempNode.isOn = false;
tempNode.sleepCounter = 0;
ratio = sleeplength;
for(int i = 0; i<9; i++)
{
//create offset so all sensors are not on at the same time
offset = rand() %5;
tempNode.waitTime = offset;
sensorArray.push_back(tempNode);
}
//Simulate sensors communicating
while(sensorArray[0].batteryLife > 0)
{
//go through each node and turn on after wait time
if(cycleCounter < 5)
{
for(int i = 0; i< 9; i++)
{
if(cycleCounter == sensorArray[i].waitTime)
{
sensorArray[i].isOn = true;
}
}
}
//decrement battery life
for(int i = 0; i<9; i++)
{
if(sensorArray[i].isOn)
{
sensorArray[i].batteryLife = sensorArray[i].batteryLife - 3;
//try to send data
//Check if recieving node is awake
if(i == 0 && !sensorArray[i].data.empty())
{
//Node 0 is home so it will cout what it recieves
cout<<"I have recieved data: " << sensorArray[i].data.front() <<endl;
sensorArray[i].data.pop();
//increament throughput counter
throughput++;
}
else if(sensorArray[(i-1)/2].isOn && !sensorArray[i].data.empty())
{
//all other nodes can send data
//cout<<"I am node: " << i <<" and I am pushing: "<< sensorArray[i].data.front() <<" to node: "<< (i-1)/2 << endl;
sensorArray[(i-1)/2].data.push(sensorArray[i].data.front());
sensorArray[i].data.pop();
}
//furthermore, Nodes 4->8 are sensor nodes and create data
if(i > 3)
{
sensorArray[i].data.push(senseData());
}
}
//even being off drains battery
else
{
sensorArray[i].batteryLife = sensorArray[i].batteryLife - 1;
sensorArray[i].sleepCounter++;
}
}
//Sensors are only on for 10 cycles at a time
//Sensors need to be turned off if on for more than 10 cycles
//Sensors need to be turned on if off for more than 10 * ratio cycles
for(int i = 0; i<9; i++)
{
if((sensorArray[i].isOn) && ((cycleCounter - sensorArray[i].waitTime) % 10 == 0) && cycleCounter > 4)
{
sensorArray[i].isOn = false;
}
else if ((!sensorArray[i].isOn) && (sensorArray[i].sleepCounter == (10 * ratio) ))
{
sensorArray[i].isOn = true;
sensorArray[i].sleepCounter = 0;
}
}
//count cycles alive
cycleCounter++;
}
cout<<"The Home node lasted: "<<cycleCounter<<" cycles out of "<< tempNode.batteryLife<<endl;
cout<<"The throughput of this ratio was: "<<throughput<<" units of data."<<endl;
cout<<"This sleep/wake ratio efficency is: "<<float(throughput)/float(cycleCounter)<<" percent."<<endl;
return float(throughput)/float(cycleCounter);
}
int findBest(float *array)
{
int best = array[0];
//loop through passed array looking for best ratio and return it
for(int i = 0; i < 9; i++)
{
if(array[i] > array[best])
{
best = i;
}
}
return best;
}
| true |
3ee9c2de10a6f932d270a6886b9c12c2c8ceb710 | C++ | gbrlas/AVSP | /CodeJamCrawler/dataset/13_3721_85.cpp | UTF-8 | 1,256 | 2.828125 | 3 | [] | no_license | #include <stdio.h>
// google code jam 2013, qualification round, problem B
// israel leiva - april 13th
int main(void){
int T, tc = 0, N, M, i, j, k, min;
int lawn[100][100];
short pattern;
scanf("%d\n", &T);
while(T){
tc++;
scanf("%d %d\n", &N, &M);
printf("Case #%d: ", tc);
min = 100;
// read input and save the min
for(i = 0; i < N; i++){
for(j = 0; j < M; j++){
scanf("%d", &lawn[i][j]);
if(lawn[i][j] < min)
min = lawn[i][j];
}
}
// the min is the last cutting so it's the only one who
// should keep the pattern
for(i = 0; i < N; i++){
for(j = 0; j < M; j++){
pattern = 1;
if(lawn[i][j] == min){
pattern = 0;
// check for pattern
// rows
for(k = 0; k < M; k++)
if(lawn[i][k] != min)
break;
if(k == M)
pattern = 1;
// columns
if(!pattern){
for(k = 0; k < N; k++)
if(lawn[k][j] != min)
break;
if(k == N)
pattern = 1;
}
// if the number does not belong to any pattern then it's not a valid cutting
if(!pattern)
break;
}
}
if(!pattern)
break;
}
if(!pattern)
printf("NO\n");
else
printf("YES\n");
T--;
}
}
| true |
45fd3a70f636a5b60dae88e51c1cd5de700eea42 | C++ | IrwinYauri/clases-c- | /punteroValor.cpp | UTF-8 | 220 | 2.953125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int a=5,b=2;
int *p=&a; //p aputna a 'a'
p=&b;//p apunta a 'b'
*p=3;//asignamos valor a casilla de memoria donde apunta p
cout<<b<<endl;
}
| true |
78a0fadbffc96615f3aae76479c0813cede14c64 | C++ | cok1/SeboApp | /SeboApp/DAO/ManagerActeur.h | UTF-8 | 2,652 | 2.9375 | 3 | [] | no_license | #pragma once
#include <vector>
#include "Entity\Acteur.h"
#include "Tools\Connexion.h"
#include <qsqlquery.h>
#include <qvariant.h>
#include <memory>
class ManagerActeur
{
public:
/// <summary>
/// Destructeur par défaut
/// </summary>
~ManagerActeur();
/// <summary>
/// Cette fonction permet de récupérer un vecteur contenant l'intégralité des acteurs présent dans la base de données
/// </summary>
/// <returns>un vecteur contenant les acteurs de la base de données</returns>
static vector<shared_ptr<Acteur>> getListeActeur();
/// <summary>
/// Cette fonction permet d'ajouter un nouvel acteur dans la base de données
/// </summary>
/// <param name="acteurAAjouter">acteur que l'on souhaite ajouter à la base de données</param>
/// <returns>true si l'ajout a été réalisé, false sinon.</returns>
static bool addActeur(Acteur acteurAAjouter);
/// <summary>
/// Cette méthode permet d'ajouter un acteur dans la base de données
/// </summary>
/// <param name="nomActeur">nom de l'acteur à ajouter</param>
/// <param name="idRole">identifiant du rôle de l'acteur</param>
/// <returns>true si l'ajout a été réalisé, false sinon.</returns>
static bool addActeur(QString nomActeur, int idRole);
/// <summary>
/// Cette fonction permet de modifier un acteur dans la base de données
/// </summary>
/// <param name="acteurAModifier">acteur que l'on souhaite modifier</param>
/// <returns>true si l'ajout a été réalisé, false sinon.</returns>
static bool modifActeur(Acteur acteurAModifier);
/// <summary>
/// Cette fonction permet de supprimer un acteur de la base de données
/// </summary>
/// <param name="acteurASupprimer">acteur que l'on souhaite supprimer</param>
/// <returns>true si l'ajout a été réalisé, false sinon.</returns>
static bool supActeur(Acteur acteurASupprimer);
/// <summary>
/// Cette fonction permet de supprimer un acteur de la base de données
/// </summary>
/// <param name="idActeurASupprimer">identifiant de l'acteur que l'on souhaite supprimer</param>
/// <returns>true si l'ajout a été réalisé, false sinon.</returns>
static bool supActeur(int idActeurASupprimer);
/// <summary>
/// cette fonction permet de récupérer le dernier message d'erreur
/// </summary>
/// <returns>le dernier message d'erreur de la classe</returns>
static QString getLastError()
{
return m_strLastError;
}
private:
/// <summary>
/// Constructeur par défaut privé pour empêcher l'instanciation de la classe
/// </summary>
ManagerActeur();
/// <summary>
/// Stocke le dernier message d'erreur
/// </summary>
static QString m_strLastError;
};
| true |
266bf6e552cdb6a095cd5cbb8f58184e6aa54d3d | C++ | nontokozo/Tut2 | /Tut2/Fraction.h | UTF-8 | 1,354 | 3.203125 | 3 | [] | no_license |
#ifndef FRACTION_H
#define FRACTION_H
//***********************DEFINITION OF CLASS FRACTION*************************//
class Fraction
{
public:
Fraction(); // default constructor function header
Fraction(int, int); // non default constructor function header
void reduce(); // reduce fraction function header
void setFraction(int, int); // set the fraction function header
void getFraction(int&, int&); // get the fraction function header
void print(); // print fraction function header
void add(Fraction, Fraction);
void subtract(Fraction, Fraction);
void multiply(Fraction, Fraction);
void divide(Fraction, Fraction);
~Fraction();
// relational operators
bool operator>>(const Fraction &) const;
bool operator<<(const Fraction &) const;
friend const Fraction operator + (const Fraction& lhs, const Fraction& rhs); // + operator overloaded function header
friend const Fraction operator - (const Fraction& lhs, const Fraction& rhs); // - operator overloaded function header
friend const Fraction operator * (const Fraction& lhs, const Fraction& rhs); // * operator overloaded function header
friend const Fraction operator / (const Fraction& lhs, const Fraction& rhs); // / operator overloaded function header
private:
// private data members
int numerator;
int denominator;
};// end of class Fraction
#endif | true |
efba6b067dee92c8dead6c947d2bc0f3ab71ffc4 | C++ | Garanyan/msu_cpp_spring_2017 | /Bezsudnova/Army/Army.h | UTF-8 | 1,578 | 3.171875 | 3 | [] | no_license | #pragma once
struct Army
{
std::vector<std::unique_ptr<Unit>> infantry_;
std::vector<std::unique_ptr<Unit>> archer_;
std::vector<std::unique_ptr<Unit>> horseman_;
void save(std::ostream& out) const
{
out << "Infantry - " << infantry_.size() << '\n';
out << "Archer - " << archer_.size() << '\n';
out << "Horseman - "<< horseman_.size() << '\n';
}
};
struct ArmyBuilder
{
ArmyBuilder()
: army_(new Army())
{
}
std::unique_ptr<Army> army_;
virtual void buildArmy() {}
};
struct ArmyBuilderRomans: public ArmyBuilder
{
void buildArmy()
{
srand(time(0));
int number = rand() % 20;
for ( int i = 0; i < number; i++ )
{
army_->infantry_.push_back(createUnit(Type::Infantry));
}
number = rand() % 20;
for ( int i = 0; i < number; i++ )
{
army_->archer_.push_back(createUnit(Type::Archer));
}
number = rand() % 20;
for ( int i = 0; i < number; i++ )
{
army_->horseman_.push_back(createUnit(Type::Horseman));
}
}
};
struct ArmyBuilderVarvar: public ArmyBuilder
{
void buildArmy()
{
srand(time(0));
int number = rand() % 20;
for (int i = 0; i < number; i++ )
{
army_->infantry_.push_back(createUnit(Type::Infantry));
}
number = rand() % 20;
for (int i = 0; i < number; i++ )
{
army_->archer_.push_back(createUnit(Type::Archer));
}
}
};
| true |
183a814b6a911c2e79c2d8e800fad62a3e0e9c5d | C++ | ImbaCow/OOD | /lab05/command/command/CResizeImageCommand.cpp | UTF-8 | 564 | 2.875 | 3 | [] | no_license | #include "pch.h"
#include "CResizeImageCommand.h"
CResizeImageCommand::CResizeImageCommand(int& widthContainer, int& heightContainer, int newWidth, int newHeight)
: m_widthHeightContainer(widthContainer, heightContainer)
, m_nextWidthHeight(newWidth, newHeight)
{
}
void CResizeImageCommand::DoExecute()
{
SwapPairs();
}
void CResizeImageCommand::DoUnexecute()
{
SwapPairs();
}
void CResizeImageCommand::SwapPairs()
{
std::swap(m_widthHeightContainer.first, m_nextWidthHeight.first);
std::swap(m_widthHeightContainer.second, m_nextWidthHeight.second);
}
| true |
e0416762d79a69b88ae42570d0032bab504bbae7 | C++ | wangtss/leetcodePractice | /source/92ReverseLinkedListII.cpp | UTF-8 | 504 | 2.890625 | 3 | [] | no_license | ListNode* reverseBetween(ListNode* head, int m, int n) {
if (head == NULL || head->next == NULL || m == n) return head;
ListNode *dummy = new ListNode(0), *pre, *post;
dummy->next = head;
pre = dummy;
int count = 1;
while (count != m) {
pre = pre->next;
count++;
}
post = pre;
while (count++ != n) post = post->next;
post = post->next;
while (m != n) {
ListNode *temp = pre->next;
pre->next = temp->next;
temp->next = post->next;
post->next = temp;
m++;
}
return dummy->next;
} | true |
a109b4d0f949670d7edaefef97c7350053230a34 | C++ | 3l-d1abl0/DS-Algo | /cpp/practise/selection_algorithm.cpp | UTF-8 | 1,180 | 3.140625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define MAX 7
int A[MAX] = {12, 3, 5, 7, 4, 19, 26};
int N = sizeof(A)/sizeof(A[0]);
int partitions(int low,int high)
{
int p=low,r=high,x=A[r],i=p-1;
for(int j=p;j<=r-1;j++)
{
if (A[j]<=x)
{
i=i+1;
swap(A[i],A[j]);
}
}
swap(A[i+1],A[r]);
return i+1;
}
int selection_algorithm(int left,int right,int kth)
{
for(;;)
{
int pivotIndex=partitions(left,right); //Select the Pivot Between Left and Right
int len=pivotIndex-left+1;
if(kth==len)
return A[pivotIndex];
else if(kth<len)
right=pivotIndex-1;
else
{
kth=kth-len;
left=pivotIndex+1;
}
}
}
int main(){
cout<<"N : "<<N<<endl;
for(int i=0; i<N;i++){
cout<<A[i]<<" ";
}
cout<<endl<<endl;
int K=N/2;
selection_algorithm(1,N,K);
cout<<"N : :"<<N<<endl;
for(int i=0; i<N;i++){
cout<<A[i]<<" ";
}
cout<<endl<<endl;
cout<<A[N/2]<<endl;
return 0;
}
| true |
194982bee8085a37d8570c42f8f3531d2379afd5 | C++ | Ravenm/DataStruct3013 | /infixPostfix/infixPostfix/infixScanner.cpp | UTF-8 | 3,379 | 3.46875 | 3 | [] | no_license | #include "infixScanner.h"
infixScanner::infixScanner()
{
}
infixScanner::~infixScanner()
{
}
//<summary>Scan a string for numbers and operators
//to create a postfix string</summary>
//<param name=none></param>
//<returns></returns>
void infixScanner::Scan()
{
std::stack<std::string> operators;
std::stack<int> prestStack;
int prest;
int topPrest;
char buff;
std::string temp;
for (int i = 0; i < inString.length(); i++)
{
buff = inString[i];
switch (buff)
{
case '-':
case '+':
prest = 2;
while(!operators.empty() && prestStack.top() >= prest)
{
outString += operators.top();
operators.pop();
prestStack.pop();
outString += " ";
}
prestStack.push(prest);
operators.push(std::string(1, buff));
i++;
break;
case '*':
case '/':
case '%':
prest = 3;
while (!operators.empty() && prestStack.top() >= prest)
{
outString += operators.top();
operators.pop();
prestStack.pop();
outString += " ";
}
prestStack.push(prest);
operators.push(std::string(1, buff));
i++;
break;
case '(':
//lowest prest just push to stack
operators.push(std::string(1, buff));
prest = 1;
prestStack.push(prest);
break;
case ')':
//scan until you find the (
if(operators.top() == "(")
{
prestStack.pop();
operators.pop();
}
else
{
while(operators.top() != "(")
{
outString += operators.top();
operators.pop();
prestStack.pop();
outString += " ";
}
operators.pop();
prestStack.pop();
}
break;
case ' ':
break;
default: //is it a number
while(buff == '1' || buff == '2' || buff == '3' || buff == '4' || buff == '5' || buff == '6' ||
buff == '7' || buff == '8' || buff == '9' || buff == '0')
{
outString += std::string(1,buff);
buff = inString[++i];
}
i--;
outString += " ";
break;
}
}
while(!operators.empty())
{
outString += operators.top();
outString += " ";
operators.pop();
prestStack.pop();
}
}
//<summary>set the input string</summary>
//<param name=></param>
//<returns></returns>
void infixScanner::SetString(std::string in)
{
inString = in;
outString = "";
}
//<summary>return the output string</summary>
//<param name=></param>
//<returns>outstring</returns>
std::string infixScanner::GetString()
{
outString = "";
infixScanner::Scan();
return outString;
}
//<summary>solve the problem</summary>
//<param name=none></param>
//<returns></returns>
int infixScanner::mathIt()
{
outString = "";
Scan();
std::stack<char> nums;
int operand = 0;
char element;
for (int i = 0; i < outString.length(); i++)
{
element = outString[i];
switch (element)
{
case '-':
operand = nums.top();
nums.pop();
nums.top() -= operand;
break;
case '+':
operand = nums.top();
nums.pop();
nums.top() += operand;
break;
case '*':
operand = nums.top();
nums.pop();
nums.top() *= operand;
break;
case '/':
operand = nums.top();
nums.pop();
nums.top() /= operand;
break;
case '%':
operand = nums.top();
nums.pop();
nums.top() %= operand;
break;
case ' ':
break;
default: //is it a number
nums.push(element - '0');
element = outString[++i];
while(element != ' ')
{
nums.push(element - '0');
element = outString[++i];
}
break;
}
}
return nums.top();
}
| true |
96f2a861b45d99a3809a12e90779948d4472f4a7 | C++ | VictorDubois/KrabiRobotique | /scarabi/Scarabi.cpp | UTF-8 | 2,133 | 2.640625 | 3 | [] | no_license | #include "Scarabi.h"
Scarabi* Scarabi::_singleton = 0;
Scarabi* Scarabi::singleton()
{
if (_singleton==0)
_singleton = new Scarabi();
return _singleton;
}
Scarabi::Scarabi() : color(colorBlue), timerMatchStarted(0), isRunning(false)
{
Serial.println("Skarabi created !");
Serial.println("First it was Scarabi, but now it's Skarabi...");
Move::singleton();
pinMode(PIN_TIRETTE, INPUT);
matchTimeInfo = TIME_INFO;
}
Scarabi::~Scarabi()
{
//dtor
}
void Scarabi::update()
{
// Call in the loop function
currentTimer = micros();
if (isRunning)
{
if (currentTimer - timerMatchStarted >= TIME_MATCH - 1000000)
{
isRunning = false;
Move::singleton()->stop();
Serial.print("END OF THE MATCH !!!");
}
else
{
Move::singleton()->update(micros() - previousTimer);
if (currentTimer - timerMatchStarted >= matchTimeInfo - 1000)
{
Serial.print((TIME_MATCH - currentTimer + timerMatchStarted)/1000000);
Serial.print(" seconds left until the end of the match !\n");
matchTimeInfo += TIME_INFO;
}
}
}
previousTimer = micros();
}
void Scarabi::waitTirette(bool avoid)
{
Serial.println("Waiting for the tirette to be removed...");
// Waits for the tirette to be removed
bool tiretteWasPresent = false;
if (!avoid)
while(true)
{
if (digitalRead(PIN_TIRETTE)==LOW && tiretteWasPresent)
break;
if (digitalRead(PIN_TIRETTE)==HIGH)
tiretteWasPresent = true;
}
Serial.println("Tirette removed !");
// Beginning of the match timer
timerMatchStarted = micros();
isRunning = true;
// Departure area
if(digitalRead(PIN_COLOR)==HIGH)
color = colorBlue;
else
color = colorRed;
// Debug
//Move::singleton()->startAction(MOVE_FORWARD);
}
Scarabi::sideColor Scarabi::getColor()
{
return color;
}
void Scarabi::finalStop()
{
isRunning = false;
}
| true |
4804d14e4240f5fc947bde1660db79ecf34f0108 | C++ | JKurtAnderson/CPP-Projects | /Sorting/algorithms/SelectionSort.h | UTF-8 | 928 | 3.109375 | 3 | [] | no_license | //
// Created by Jason on 12/8/2019.
//
#ifndef SORTING_SELECTIONSORT_H
#define SORTING_SELECTIONSORT_H
#include <cstddef>
#include <iostream>
#include "Arrays.h"
template <class T>
static void selectionSort(T* array, size_t length){
#if defined(DEBUGGING) && (DEBUGGING == 1)
printArray(array, length, "unsorted");
#endif
for(size_t selectionIndex = 0; selectionIndex < length - 1; selectionIndex++) {
size_t iterationIndex = selectionIndex;
size_t minimumIndex;
for(minimumIndex = iterationIndex; iterationIndex < length; iterationIndex++) {
if(array[iterationIndex] < array[minimumIndex]) {
minimumIndex = iterationIndex;
}
}
swap(array, selectionIndex, minimumIndex);
}
#if defined(DEBUGGING) && (DEBUGGING == 1)
printArray(array, length, "sorted");
#endif
}
#endif //SORTING_SELECTIONSORT_H
| true |
50d9ec99cffc887015ab60e626b8933541954d12 | C++ | luisg122/cpp_programming_projects | /C++/Gaussian1.cc | UTF-8 | 5,881 | 3.59375 | 4 | [] | no_license | #include<iostream>
#include<cmath>
#include<cstdlib>
using namespace std;
class Gaussian{
private:
int a,b;
public :
Gaussian(int nx,int ny):a(nx),b(ny){} //in-class initializer constructor
Gaussian():Gaussian(0,0){}
//default consturctor with delegating constructor
Gaussian(const Gaussian &other); //copy constructor
/*Gaussian(int n){ //convert int to Gaussian int constuctor
a = n;
b = 0;
}*/
Gaussian(int n):a(n){} //using a delegating constructor
//to convert int -> Gaussian int
int norm(){ //norm function (a^2 + b^2)
a *= a;
b *= b;
return a + b;
}
//int get_a(){return a;}
//int get_b(){return b;}
//-----------------------------------------------------------------------------------
Gaussian add(const Gaussian &other) const;
Gaussian operator+(const Gaussian &other);
Gaussian sub(const Gaussian &other) const;
Gaussian operator-(const Gaussian &other);
Gaussian multi(const Gaussian &other) const;
Gaussian operator*(const Gaussian &other);
bool div(const Gaussian &other);
bool operator|(const Gaussian &other);
//------------------------------------------------------------------------------------
bool operator==(const Gaussian &other){
if (a == other.a && b == other.b) return true;
else return false;
}
//WHY do you have to 'friend keyword' for ostream
friend ostream &operator<<(ostream &os, const Gaussian &x){ //notation is really important
//OVERLOADING THE INSERTION OPERATOR //this function does away with x.get_a(), and x.get_b(), it looks ugly
//insertion operator == overflow operator?
if(x.a != 0 && x.b == -1) os << x.a << " - i";
if(x.a != 0 && x.b < -1) os << x.a << " - " << x.b*(-1) << "i";
if(x.a != 0 && x.b == 1) os << x.a << " + i";
if(x.a != 0 && x.b == 0) os << x.a;
if(x.a == 0 && x.b == 0) os << false;
if(x.a == 0 && x.b == -1) os << "-i";
if(x.a == 0 && x.b == 1) os << "i" ;
if(x.a == 0 && x.b < -1) os << "-" << x.b*(-1) << "i";
if(x.a == 0 && x.b > 1) os << x.b << "i";
else if(x.a != 0 && x.b > 1) os << x.a << " + " << x.b << "i";
return os;
}
Gaussian &operator=(const Gaussian &other){
a = other.a;
b = other.b;
return *this;
}
};
//------------------------------------------------------------------------------------------------
Gaussian::Gaussian(const Gaussian &other){
a = other.a;
b = other.b;
}
Gaussian Gaussian::add(const Gaussian &other)const{
return Gaussian(a + other.a, b + other.b); //this is why you need a delegating constructor!!!
}
Gaussian Gaussian::operator+(const Gaussian &other){
return add(other);
}
Gaussian Gaussian::sub(const Gaussian &other)const{
return Gaussian(a - other.a, b - other.b); // this is why you need a delegating constructor!!!
}
Gaussian Gaussian::operator-(const Gaussian &other){
return sub(other);
}
Gaussian Gaussian::multi(const Gaussian &other)const{
Gaussian n1;
n1.a = ((a) * (other.a)) - ((b) * (other.b)); //i^2 == -1, therefore -(b*other.b) takes care of that
n1.b = ((a) * (other.b)) + ((b) * (other.a));
return Gaussian(n1.a, n1.b); // this is why you need a delegating constructor!!!
}
Gaussian Gaussian::operator*(const Gaussian &other){
return multi(other);
}
bool Gaussian::div(const Gaussian &other){
int x,y;
bool isPrime = true;
Gaussian n1(a,b),n2(other.a,other.b), conj_n1(a, (-1)*b);
Gaussian n3 = n2*conj_n1;
Gaussian n4 = n1*conj_n1;
int den = n4.a + n4.b;
int c = double(n3.a)/den;
int d = double(n3.b)/den;
int z = pow(c,2) + pow(d,2); //implicit normalization
x = n1.norm();
y = n2.norm();
if(x != 0){
if((y % x) == 0){
if(y == x*z)return true;
else return false;
}
}
else return false;
}
bool Gaussian::operator|(const Gaussian &other){
return div(other);
}
//-------------------------------------------------------------------------------------------------
int main(){
cout << "Luis Gualpa - Project 1" << endl;
cout << "===================================================\n";
cout << "CHECK Expected OUTPUT\n";
const Gaussian x1, x2(3), x3(0,1), x4(0,-1), x5(1,2), x6(3,-2), x7(-3,1), x8(2,-1), x9(0,-2), x10(0,3);
cout<<x1<<", "<<x2<<", "<<x3<<", "<<x4<<", "<<x5<<", "<<x6<<", "<<x7<<", "<<x8<<", "
<<x9<<", " << x10<<endl << endl;
//---------------------------------------------------------------------
cout << "===================================================\n\n";
cout << "Program for Computing Complex Numbers\n" ;
int a,b,c,d;
cout << "Enter Real integer: ";
cin >> a;
cout << "Enter Imag. integer: ";
cin >> b;
Gaussian X1(a,b);
cout << "Enter Real integer: ";
cin >> c;
cout << "Enter Imag. integer: ";
cin >> d;
Gaussian X2(c,d);
cout << endl;
//X2 = X1;
cout << "Your First Complex Number Is: " << "(" << X1 << ")\n";
cout << "Your Second Complex Number Is: " << "(" << X2 << ")\n";
//--------------------------------------------------------------------------------------------------------
Gaussian X3 = X1 * X2;
cout << "\nMultiplication of complex numbers: " << "(" << X1 << ") * (" << X2 << ") = " << X3 << endl;
X3 = X1 + X2;
cout << "\nAddition of complex numbers: " << "(" << X1 << ") + (" << X2 << ") = " << X3 << endl;
X3 = X1 - X2;
cout << "\nSubtraction of complex numbers: " << "(" << X1 << ") - (" << X2 << ") = " << X3 << endl;
Gaussian x(1,2);
cout << "\n\nThe norm for ((1)^2 + (2)^2) = " << x.norm() << endl;
Gaussian m(2,4),n(4,8); //false
bool bb = (m|n);
cout << bb; //0, therefore False
return 0;
}
| true |
8e97694a13fdf0f0e0c48eaba51b31647bb6748d | C++ | Jamxscape/LearnCPlusPlus | /3/3/21.cpp | UTF-8 | 367 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | //
// 21.cpp
// 3
//
// Created by 马元 on 2016/12/24.
// Copyright © 2016年 MaYuan. All rights reserved.
//
#include<iostream>
#include <cmath>
using namespace std;
int main21()
{
int n=0,h;
cin>>h;
for(int i=2;i<=sqrt(h);i++)
if(h%i==0) n=1;
if(n==0)cout<<h<<"是素数"<<endl;
else cout<<h<<"不是素数"<<endl;
return 0;
}
| true |
2addafec78876e82e68a1886769f0d577f96174e | C++ | fenixlin/leetcode | /c++/pb008.cpp | UTF-8 | 1,618 | 3.078125 | 3 | [] | no_license | // Brute force, O(n)
#include <string>
#include <gtest/gtest.h>
using namespace std;
class Solution {
public:
int myAtoi(string str) {
int sign = 1;
int ans = 0;
string::iterator i = str.begin();
while (*i==' ' && i!=str.end()) i++;
if (*i=='-') { sign = -1; i++; }
else if (*i=='+') i++;
for (; i!=str.end(); i++) {
if (*i<'0' || *i>'9') return (-sign)*ans;
if (ans<-214748364) return (sign>>1) ^ 0x7fffffff;
if (ans==-214748364 && (sign>0 && *i>'7' || sign<0 && *i>'8')) return (sign>>1) ^ 0x7fffffff;
ans = ans*10 - (*i-'0');
}
return (-sign)*ans;
}
};
TEST(case1, test1) {
Solution sol;
EXPECT_EQ(123, sol.myAtoi("123"));
EXPECT_EQ(-123, sol.myAtoi("-123"));
EXPECT_EQ(2147483647, sol.myAtoi("2234236469"));
EXPECT_EQ(10, sol.myAtoi("0000000000000000000000010"));
EXPECT_EQ(123, sol.myAtoi("+000123"));
EXPECT_EQ(-1, sol.myAtoi("-1abc"));
EXPECT_EQ(-1, sol.myAtoi("-1.0000"));
EXPECT_EQ(-2147483648, sol.myAtoi("-2147483648"));
EXPECT_EQ(-2147483648, sol.myAtoi("-2147483649"));
EXPECT_EQ(2147483646, sol.myAtoi("2147483646"));
EXPECT_EQ(2147483647, sol.myAtoi("2147483648"));
EXPECT_EQ(0, sol.myAtoi("-0"));
EXPECT_EQ(0, sol.myAtoi(" "));
EXPECT_EQ(1, sol.myAtoi(" 01 0"));
EXPECT_EQ(10, sol.myAtoi(" 010"));
EXPECT_EQ(-12, sol.myAtoi(" -0012a10"));
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| true |
26d7ec8ef4cbe698d86731f0083419f4b5593b35 | C++ | tyhenry/dt_openframeworks_2018 | /week12/06_mesh_texture/src/ofApp.cpp | UTF-8 | 4,806 | 2.53125 | 3 | [] | no_license | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
earthImg.load("earth_texture.jpg");
sphere.set(200,3);
sphere.mapTexCoordsFromTexture(earthImg.getTexture());
gui.setup();
gui.add( bLight.set("lighting", true));
gui.add( bFaces.set("draw faces", true));
gui.add( bTexture.set("draw texture", true));
gui.add( bWires.set("draw wireframe", true));
gui.add( bVerts.set("draw vertices", true));
gui.add( bNormals.set("draw normals", true));
// setup sun
sun.setDirectional();
sun.setPosition(glm::vec3(-100,20,500));
sun.lookAt(glm::vec3(0)); // point ofNode -z at earth
sun.rotateDeg(180, glm::vec3(0,1,0)); // ofLight shines +z!
sun.setDiffuseColor(ofColor::wheat);
}
//--------------------------------------------------------------
void ofApp::update(){
sphere.rotateDeg(.05, glm::vec3(0,1,0)); // rotate earth
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackgroundGradient(ofColor::wheat, ofColor::darkOrchid);
ofSetColor(255);
cam.begin();
ofEnableDepthTest();
if (bLight){
ofEnableLighting();
sun.enable();
}
// draw the sphere surface
if (bFaces){
if (bTexture) earthImg.bind(); // bind image texture
else ofSetColor(170); // or color flat gray
sphere.drawFaces(); // aka sphere.draw();
if (bTexture) earthImg.unbind(); // unbind after binding!
}
ofSetColor(ofColor::thistle);
if (bWires) sphere.drawWireframe();
/* below we use custom code to draw
the mesh vertices and normals of the sphere
first we need to transform the space so the mesh draws
along with the sphere's internal ofNode rotation:
*/
ofPushMatrix();
ofMultMatrix( sphere.getGlobalTransformMatrix() );
ofMesh& mesh = sphere.getMesh(); // reference to mesh
if (bVerts) {
// draw vertices (as spheres)
ofSetColor(ofColor::plum);
for (int i=0; i<mesh.getVertices().size(); i++){
ofDrawSphere(mesh.getVertices()[i], 1);
}
// or sphere.getMesh().drawVertices(); // draw points
}
if (bNormals) {
// draw face normals from centers of mesh faces
ofSetColor(ofColor::indigo);
for (auto& face: mesh.getUniqueFaces()){
/* faces are triangles -
find center of a triangle:
2/3 from a point to the middle of opposite edge
0
/|\
/ c \
/_____\
2 m 1
*/
auto vert0 = face.getVertex(0);
auto vert1 = face.getVertex(1);
auto vert2 = face.getVertex(2);
auto midpt = (vert1 + vert2)*0.5;
auto centroid = vert0 + (2./3.)*(midpt-vert0);
ofDrawLine(centroid, centroid-face.getFaceNormal()*10);
}
// or sphere.getMesh().drawNormals(10); // draw *vertex* normals
}
ofPopMatrix();
if (bLight){
sun.disable();
ofDisableLighting();
ofSetColor(sun.getDiffuseColor());
sun.draw(); // draw the sun as an ofNode
}
ofDisableDepthTest();
cam.end();
gui.draw();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| true |
ba68f899974352d619062c735db04b9352a20d01 | C++ | teddyort/NumberDisplay | /NumberDisplay.cpp | UTF-8 | 686 | 3.21875 | 3 | [] | no_license | #include "Arduino.h"
#include "NumberDisplay.h"
NumberDisplay::NumberDisplay(const int pins[]){
//Setup all the pins as outputs
_pins = pins;
int i;
for(i=0;i<8;i++){
pinMode(pins[i], OUTPUT);
}
}
void NumberDisplay::output(int num) {
//Map Numbers to Bytes (using hexadecimal to keep it short)
//Note that 0x7E is in binary: 01111110
const byte numBytes[] = {0x7E, 0x30, 0x6D, 0x79, 0x33, 0x5B, 0x5F, 0x70, 0x7F, 0x7B, 0x80};
byte code = numBytes[num];
byte mask;
int index = 0;
for(mask = 1; mask > 0; mask <<=1){
if(code & mask){
digitalWrite(_pins[index],HIGH);
}else{
digitalWrite(_pins[index],LOW);
}
index++;
}
} | true |
5fd8db46e395893d876b6ed7e1b1c1b2931e8f79 | C++ | DFRobot/DFRobot_L218 | /example/DFRobot_L218_Tracker/DFRobot_L218_Tracker.ino | UTF-8 | 3,223 | 2.78125 | 3 | [] | no_license | /*
* File : DFRobot_L218_Tracker.ino
* Power : L218 powered by 3.7V lithium battery
* Brief : This example use L218 as a tracker
* Press the button when the net light blinks L218 start
* After initialization is completed it will print longitude (Positive numbers for East and Negative numbers for West)
* and latitude (Positive numbers for North and Negative numbers for South)
* Thus we finished the positioning function verification
* Note : This example needs SIM card
* The tracker function only available in outdoor
*/
#include <DFRobot_L218.h>
DFRobot_L218 l218;
#define BUTTON_PIN 3
#define CHARGE_PIN 6
#define DONE_PIN 7
#define POWER_PIN 9
void turn_on()
{
static int t1=0,t2=0;
t1=t2;
t2=millis();
if(t1-t2){
if( digitalRead(BUTTON_PIN) == LOW ){
tone(4,2000);
digitalWrite(POWER_PIN,HIGH);
}else{
noTone(4);
digitalWrite(POWER_PIN,LOW );
}
}else{
noTone(4);
}
}
void charge()
{
if(digitalRead(DONE_PIN)){
if( digitalRead(CHARGE_PIN) == LOW ){
tone(4,4000,500);
}
}
}
void setup(){
SerialUSB.begin(115200);
while(!SerialUSB);
l218.init(); //Initialization
//L218 boot interrupt. Press the button for 1-2 seconds, L218 turns on when NET LED light up, Press and hold the button until the NET LED light off L218 turns off.
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN) , turn_on , CHANGE);
//Battery charge interrupt. When battery get charge from USB, Buzzer sounds for 0.5 seconds
attachInterrupt(digitalPinToInterrupt(CHARGE_PIN) , charge , CHANGE);
}
void loop(){
if(l218.checkTurnON()){ //Check if L218 start
delay(10000);
SerialUSB.println("Turn ON !");
delay(500);
SerialUSB.println("Turn ON !");
if(l218.checkSIMcard()){ //Check SIM card
SerialUSB.println("Card ready");
delay(500);
}else{
SerialUSB.println("NO Card");
return;
}
if(l218.initPos()){ //Init positioning functions
SerialUSB.println("Init position");
delay(500);
}else{
SerialUSB.println("Not init position");
return;
}
while(1){
delay(2000);
if(l218.getPos()){ //Get location information
SerialUSB.println("Get position");
double Longitude,Latitude;
Longitude = l218.getLongitude(); //Get longitude
Latitude = l218.getLatitude(); //Get latitude
SerialUSB.print("Longitude = ");
SerialUSB.print(Longitude,6);
SerialUSB.print("Latitude = ");
SerialUSB.print(Latitude ,6);
}else{
SerialUSB.println("Not position");
}
}
}else{
SerialUSB.println("Please Turn ON L218");
delay(3000);
}
}
| true |
ca1266577b1ec7f4b0ef8e9c035428855572af24 | C++ | ankurdcruz/Smart-Search-Dictionary | /Class12th_C++_Project.cpp | UTF-8 | 19,518 | 2.671875 | 3 | [] | no_license | #include<fstream.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
class data
{
char word[15],mean[50],syn[15],ant[15];
public:
void input()
{
gotoxy(4,13);
cout<<"Enter Word:";
cin>>word;
gotoxy(4,14);
cout<<"Enter meaning:";
cin>>mean;
gotoxy(4,15);
cout<<"Enter synonym:";
cin>>syn;
gotoxy(4,16);
cout<<"Enter antonym:";
cin>>ant;
}
void outword() { cprintf(word); }
void outmean() { cprintf(mean); }
void outsyn() { cprintf(syn); }
void outant() { cprintf(ant); }
char* retch() { return word; }
};
void border()
{
int i;
textcolor(14);
gotoxy(1,1);cprintf("###############################################################################");cout<<endl;
cprintf("###############################################################################");cout<<endl;
gotoxy(1,23);
cprintf("###############################################################################");cout<<endl;
cprintf("###############################################################################");cout<<endl;
for(i=1;i<23;i++)
{
gotoxy(1,i);cprintf("##");
gotoxy(78,i);cprintf("##");
}
gotoxy(1,3);
textcolor(WHITE);
}
void pageend()
{
int i;
long j;
gotoxy(1,1);
textcolor(BLUE);
for(i=1;i<24;i++)
{
for(j=0;j<120000;j++); for(j=0;j<120000;j++); for(j=0;j<120000;j++); for(j=0;j<120000;j++);
gotoxy(1,i);
cprintf(" ");cout<<endl;
cprintf("_______________________________________________________________________________");cout<<endl;
cprintf("_______________________________________________________________________________");cout<<endl;
cprintf(" ");cout<<endl;
}
textcolor(WHITE);
}
void question()
{
int v=2,u=62;
gotoxy(u,v);cout<<" .-''''-.. "<<endl;
gotoxy(u,v+1);cout<<" .' .'''. '. "<<endl;
gotoxy(u,v+2);cout<<"/ \\ \\ `."<<endl;
gotoxy(u,v+3);cout<<"\ ' | |"<<endl;
gotoxy(u,v+4);cout<<" `--' / / "<<endl;
gotoxy(u,v+5);cout<<" .' ,-'' "<<endl;
gotoxy(u,v+6);cout<<" | / "<<endl;
gotoxy(u,v+7);cout<<" | ' "<<endl;
gotoxy(u,v+8);cout<<" '-' "<<endl;
gotoxy(u,v+9);cout<<" .--. "<<endl;
gotoxy(u,v+10);cout<<" / \\ "<<endl;
gotoxy(u,v+11);cout<<" \\ / "<<endl;
gotoxy(u,v+12);cout<<" `--' "<<endl;
}
int noofwords()
{
fstream file("dict.dat",ios::in|ios::binary);
data s;
int pend,psize,prec;
file.seekg(0,ios::end);
pend=file.tellg();
psize=sizeof(s);
prec=pend/psize;
file.close();
return prec;
}
int pass()
{
char pass[25]="Hello",user[25]="";
char ch;
clrscr();
border();
int p=0,q;
gotoxy(25,13);cout<<"Enter Password ";
int col=40;
while(ch!=13)
{
ch=getch();
gotoxy(col,13);cout<<"*";
user[p]=ch;
p++;
col++;
}
user[p-1]='\0'; //checks for last entry so p-1
if(strcmp(pass,user)==0)
{
gotoxy(25,15);cout<<"Permission Granted ";
gotoxy(25,15);cout<<" ";
q=1;
}
else
{
gotoxy(25,15);cout<<"Access Denied ";getch();
gotoxy(25,15);cout<<" ";
q=0;
}
return q;
}
void book()
{
gotoxy(42,11);cout<<" _.--._ _.--._ "<<endl;
gotoxy(42,12);cout<<",-=.-` \\` `-._ "<<endl;
gotoxy(42,13);cout<<"\\\\\\ \\ \\ "<<endl;
gotoxy(42,14);cout<<" \\\\\\ \\ \\ "<<endl;
gotoxy(42,15);cout<<" \\\\\\ \\ \\ "<<endl;
gotoxy(42,16);cout<<" \\\\\\ \\ \\ "<<endl;
gotoxy(42,17);cout<<" \\\\\\ \\ \\ "<<endl;
gotoxy(42,18);cout<<" \\\\\\ _:--:\\:_:--:_ \\ "<<endl;
gotoxy(42,19);cout<<" \\\\\\\_.-` : `-._\\ "<<endl;
gotoxy(42,20);cout<<" \\`_..--``--.;.--``--.._=> "<<endl;
gotoxy(42,21);cout<<" ` "<<endl;
}
void smartpattern()
{
border();
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
cout<<" ____ _ ____ _ "<<endl;
cout<<" / ___| _ __ ___ __ _ _ __| |_ / ___| ___ __ _ _ __ ___| |__ "<<endl;
cout<<" \\___ \\| '_ ` _ \\ / _` | '__| __| \\___ \\ / _ \\/ _` | '__/ __| '_ \\ "<<endl;
cout<<" ___) | | | | | | (_| | | | |_ ___) | __/ (_| | | | (__| | | | "<<endl;
cout<<" |____/|_| |_| |_|\\__,_|_| \\__| |____/ \\___|\\__,_|_| \\___|_| |_| "<<endl;
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
gotoxy(45,21);textcolor(RED);cprintf("use /|\\ and \\|/ to navigate");textcolor(WHITE);
}
void create()
{
int c;
c=pass();
if(c==1)
{
clrscr();
border();
textcolor(WHITE);
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
cout<<" ____ _ _ ____ _ "<<endl;
cout<<" / ___|_ __ ___ __ _| |_(_)_ __ __ _ | _ \\ ___ ___ ___ _ __ __| |___ "<<endl;
cout<<" | | | '__/ _ \\/ _` | __| | '_ \\ / _` | | |_) / _ \\/ __/ _ \\| '__/ _` / __| "<<endl;
cout<<" | |___| | | __/ (_| | |_| | | | | (_| | | _ < __/ (_| (_) | | | (_| \\__ \\ " <<endl;
cout<<" \\____|_| \\___|\\__,_|\\__|_|_| |_|\\__, | |_| \\_\\___|\\___\\___/|_| \\__,_|___ "<<endl;
cout<<" |___/ "<<endl;
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl<<endl;
fstream f("dict.dat",ios::out|ios::binary);
int i;
char m;
data d;
while(1)
{
d.input();
f.write((char*)&d,sizeof(d));
gotoxy(4,17);cout<<"Do you want to continue adding words (Y/N)? :";
cin>>m;
gotoxy(4,13);cout<<" ";
gotoxy(4,14);cout<<" ";
gotoxy(4,15);cout<<" ";
gotoxy(4,16);cout<<" ";
gotoxy(4,17);cout<<" ";
if(toupper(m)=='N')
break;
}
f.close();
}
}
void move(char c,int a)
{
long i;
int x,y,j=0;
gotoxy(35,19);cout<<" __...--~~~~~-._ _.-~~~~~--...__ "<<endl;
gotoxy(35,20);cout<<" // `|' \\\\ "<<endl;
gotoxy(35,21);cout<<" // | \\\\ "<<endl;
gotoxy(35,22);cout<<" //__...--~~~~~~-._ | _.-~~~~~~--...__\\\\ "<<endl;
gotoxy(35,23);cout<<" //__.....----~~~~._\\ | /_.~~~~----.....__\\\\ "<<endl;
gotoxy(35,24);cout<<"====================\\\\|//===================="<<
endl;
for(x=22;x>4;x=x-1)
{
gotoxy(1,1);
y=(x*x)/10;
gotoxy((y+a),x);
cout<<c;
for(i=0;i<500000;i++);
if(x!=5)
{
gotoxy(y+a,x);
cout<<" ";
}
}
j++;
}
void add()
{
clrscr();
border();
textcolor(WHITE);
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
cout<<" _ _ _ _ ____ _ "<<endl;
cout<<" / \\ __| | __| (_)_ __ __ _ | _ \\ ___ ___ ___ _ __ __| |___ "<<endl;
cout<<" / _ \\ / _` |/ _` | | '_ \\ / _` | | |_) / _ \\/ __/ _ \\| '__/ _` / __| "<<endl;
cout<<" / ___ \\ (_| | (_| | | | | | (_| | | _ < __/ (_| (_) | | | (_| \\__ \\ "<<endl;
cout<<" /_/ \\_\\__,_|\\__,_|_|_| |_|\\__, | |_| \\_\\___|\\___\\___/|_| \\__,_|___/ "<<endl;
cout<<" |___/ "<<endl;
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl<<endl;
fstream f("dict.dat",ios::app|ios::binary);
int i;
char m;
data d;
while(1)
{
d.input();
f.write((char*)&d,sizeof(d));
gotoxy(4,17); cout<<"Do you want to continue adding words (Y/N)? :";
cin>>m;
gotoxy(4,13);cout<<" ";
gotoxy(4,14);cout<<" ";
gotoxy(4,15);cout<<" ";
gotoxy(4,16);cout<<" ";
gotoxy(4,17);cout<<" ";
if(toupper(m)=='N')
break;
}
textcolor(WHITE);
f.close();
}
void smart()
{
clrscr();
fstream f;
int i=0,a=32,j,k,pos=-1,b=10,z=0,g,l,m=0,n; //b is the ctr
data s;
char tword[15],ch,tch,temp[15];
tword[0]='\0';
smartpattern();
gotoxy(5,b);cout<<"Enter word to be searched: ";
while(1) //repeat the process inside the loop
{
z=0;
b=10;
g=0;
gotoxy(a,b);
ch=getch();
if(ch==0)
{
ch=getch(); //special keys
if(ch=='P'|| ch=='H') //1 down //2 up
{
n=1;
clrscr();
if(ch=='P')
m++; //down
else
m--; //up
smartpattern();
gotoxy(5,b);cout<<"Enter word to be searched: "<<tword;
f.open("dict.dat",ios::in|ios::binary);
l=0;
while(f)
{
f.read((char*)&s,sizeof(s));
if(f.eof())
break;
j=-1; //found or not found
for(i=0;i<=pos;i++)
{
if(s.retch()[i]!=tword[i])
j=1; //no
}
if(j==-1) //yes show the word with mean
{
l++;
if(g==0)
{
gotoxy(15,b+4);
cout<<"WORD";
gotoxy(60,b+4);
cout<<"MEANING";
g=1;
}
if(m==l)
{
textcolor(YELLOW);
gotoxy(10,b+6);
cprintf(">>");
gotoxy(15,b+6);
s.outword();
gotoxy(35,b+6);
cout<<"------";
gotoxy(60,b+6);
s.outmean();
b=b+1; //row increase
z++;
}
else
{
gotoxy(10,b+6);
textbackground(BLACK);
cprintf(" ");
textcolor(WHITE);
gotoxy(15,b+6);
s.outword();
gotoxy(35,b+6);
cout<<"------";
gotoxy(60,b+6);
s.outmean();
b=b+1; //row increase
z++;
}
}
}
f.close();
}
} //for special char up and down
else if(ch==13)
{
if(n==2)
break;
else
{
f.open("dict.dat",ios::in|ios::binary);
l=0;
while(f)
{
f.read((char*)&s,sizeof(s));
if(f.eof())
break;
j=-1; //found or not found
for(i=0;i<=pos;i++)
{
if(s.retch()[i]!=tword[i])
j=1; //no
}
if(j==-1)
{
l++;
if(l==m)
{
pageend();
clrscr();
border();
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
cout<<"__ __ _ ____ _ _ _ "<<endl;
cout<<"\\ \\ / /__ _ __ __| | | _ \\ ___ ___ ___ _ __(_)_ __ | |_(_) ___ _ __ "<<endl;
cout<<" \\ \\ /\\ / / _ \\| '__/ _` | | | | |/ _ \\/ __|/ __| '__| | '_ \\| __| |/ _ \\| '_ "<<endl;
cout<<" \\ V V / (_) | | | (_| | | |_| | __/\\__ \\ (__| | | | |_) | |_| | (_) | | ||"<<endl;
cout<<" \\_/\\_/ \\___/|_| \\__,_| |____/ \\___||___/\\___|_| |_| .__/ \\__|_|\\___/|_| ||"<<endl;
cout<<" |_| "<<endl;
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
gotoxy(15,13);cout<<"WORD: ";s.outword();
gotoxy(15,15);cout<<"MEANING: ";s.outmean();
gotoxy(15,17);cout<<"SYNONYMS: ";s.outsyn();
gotoxy(15,19);cout<<"ANTONYMS: ";s.outant();
book();
break;
}
}
}
f.close();
getch();
break;
}
}
else
{
n=2;
textcolor(WHITE);
m=0;
a++;
ch=tolower(ch); //lower case
pos++;
tword[pos]=ch;
tword[pos+1]='\0'; //terminate the new temp word
clrscr();
smartpattern();
gotoxy(5,b);cout<<"Enter word to be searched: "<<tword;
f.open("dict.dat",ios::in|ios::binary);
while(f)
{
f.read((char*)&s,sizeof(s));
if(f.eof())
break;
j=-1; //found or not found
for(i=0;i<=pos;i++)
{
if(s.retch()[i]!=tword[i])
j=1; //no
}
if(j==-1) //yes show the word with mean
{
if(g==0)
{
gotoxy(15,b+4);
cout<<"WORD";
gotoxy(60,b+4);
cout<<"MEANING";
g=1;
}
gotoxy(15,b+6);
s.outword();
gotoxy(35,b+6);
cout<<"------";
gotoxy(60,b+6);
s.outmean();
b=b+1; //row increase
z++;
}
}
f.close();
if(z==0)
{
gotoxy(17,b+3);cout<<"Word not found. ";
}
}
}
}
void random()
{
clrscr();
border();
unsigned int seedval;
time_t t;
seedval=(unsigned)time(&t);
srand(seedval);
fstream f;
data s;
int i,j,k;
k=noofwords();
i=(rand()%k);
f.open("dict.dat",ios::in|ios::binary);
for(j=0;j<=i;j++)
f.read((char*)&s,sizeof(s));
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
cout<<" ____ _ __ __ _ "<<endl;
cout<<" | _ \\ __ _ _ __ __| | ___ _ __ ___ \\ \\ / /__ _ __ __| | "<<endl;
cout<<" | |_) / _` | '_ \\ / _` |/ _ \\| '_ ` _ \\ \\ \\ /\\ / / _ \\| '__/ _` | "<<endl;
cout<<" | _ < (_| | | | | (_| | (_) | | | | | | \\ V V / (_) | | | (_| | "<<endl;
cout<<" |_| \\_\\__,_|_| |_|\\__,_|\\___/|_| |_| |_| \\_/\\_/ \\___/|_| \\__,_| "<<endl;
cout<<" "<<endl;
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
gotoxy(15,13);cout<<"RANDOM WORD: ";
s.outword();
gotoxy(15,15);cout<<"MEANING: ";
s.outmean();
gotoxy(15,17);cout<<"SYNONYMS: ";s.outsyn();
gotoxy(15,19);cout<<"ANTONYMS: ";s.outant();
book();
f.close();
getch();
}
void all()
{
fstream f;
int i,j=0;
char ch;
data s;
f.open("dict.dat",ios::in|ios::binary);
while(j>=0)
{
f.seekg(0);
for(i=0;i<=j;i++)
f.read((char*)&s,sizeof(s));
if(f.eof())
break;
clrscr();
border();
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
cout<<" _ _ _ ____ _ "<<endl;
cout<<" / \\ | | | | _ \\ ___ ___ ___ _ __ __| |___ "<<endl;
cout<<" / _ \\ | | | | |_) / _ \\/ __/ _ \\| '__/ _` / __| "<<endl;
cout<<" / ___ \\| | | | _ < __/ (_| (_) | | | (_| \\__ \\ "<<endl;
cout<<" /_/ \\_\\_|_| |_| \\_\\___|\\___\\___/|_| \\__,_|___/ "<<endl;
cout<<" "<<endl;
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
gotoxy(15,13);cout<<"WORD NO "<<j+1<<": ";
s.outword();
gotoxy(15,15);cout<<"MEANING: ";
s.outmean();
gotoxy(15,17);cout<<"SYNONYMS: ";s.outsyn();
gotoxy(15,19);cout<<"ANTONYMS: ";s.outant();
book();
gotoxy(50,22);textcolor(RED);cprintf("use --> and <-- to navigate");textcolor(WHITE);
ch=getch();
if(ch==0)
{
ch=getch(); //special keys
if(ch=='M')
j++;
else if(ch=='K')
j--;
else
break;
//1 down //2 up
}
else
break;
}
f.close();
}
void pattern()
{
clrscr();
cout<<" _____ _ _ _ "<<endl;
cout<<"| ____|_ __ __ _| (_)___| |__ "<<endl;
cout<<"| _| | '_ \\ / _` | | / __| '_ \\ "<<endl;
cout<<"| |___| | | | (_| | | \\__ \\ | | |"<<endl;
cout<<"|_____|_| |_|\\__, |_|_|___/_| |_|"<<endl;
cout<<" |___/ "<<endl;
cout<<" ____ _ _ _ "<<endl;
cout<<"| _ \\(_) ___| |_(_) ___ _ __ __ _ _ __ _ _"<<endl;
cout<<"| | | | |/ __| __| |/ _ \\| '_ \\ / _` | '__| | | |"<<endl;
cout<<"| |_| | | (__| |_| | (_) | | | | (_| | | | |_| |"<<endl;
cout<<"|____/|_|\\___|\\__|_|\\___/|_| |_|\\__,_|_| \\__, |"<<endl;
cout<<" |___/"<<endl;
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
cout<<endl;
cout<<" .-~~~~~~~~~-._ _.-~~~~~~~~~-. "<<endl;
cout<<" __.' ~. .~ `.__ "<<endl;
cout<<" .'// \./ \\`. "<<endl;
cout<<" .'// | \\`. "<<endl;
cout<<" .'// .-~~~~~~~~~~~~-._ | _,-~~~~~~~~~~~~-. \\`. "<<endl;
cout<<" .'//.-! !-. | .-! !-. \\`."<<endl;
cout<<" .'//______.============-.. \\ | / ..-============._______\\`."<<endl;
cout<<".'______________________________\\|/______________________________`."<<endl;
question();
getch();
}
void main()
{
int a=6;
textcolor(WHITE);
clrscr();
pattern();
pageend();
clrscr();
int ch=0;
while(ch<=5)
{
textcolor(WHITE);
clrscr();
border();
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
cout<<" ____ _ _ _ "<<endl;
cout<<" | _ \\(_) ___| |_(_) ___ _ __ __ _ _ __ _ _ "<<endl;
cout<<" | | | | |/ __| __| |/ _ \\| '_ \\ / _` | '__| | | | "<<endl;
cout<<" | |_| | | (__| |_| | (_) | | | | (_| | | | |_| | "<<endl;
cout<<" |____/|_|\\___|\\__|_|\\___/|_| |_|\\__,_|_| \\__, | "<<endl;
cout<<" |___/ "<<endl;
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
gotoxy(6,12);cout<<"1.Create new record";
gotoxy(6,13);cout<<"2.Add records";
gotoxy(6,14);cout<<"3.Smart search";
gotoxy(6,15);cout<<"4.Random Word";
gotoxy(6,16);cout<<"5.View all records";
gotoxy(6,17);cout<<"6.Exit";
gotoxy(6,18);cout<<"________________________________________________";
gotoxy(6,20);cout<<"________________________________________________";
gotoxy(6,19);cout<<"Enter Choice: ";
cin>>ch;
pageend();
switch(ch)
{
case 1: create(); pageend(); break;
case 2: add(); pageend(); break;
case 3: smart(); pageend();break;
case 4: random();pageend();break;
case 5: all();pageend();
}
clrscr();
}
clrscr();
move('T',0);
move('H',2);
move('A',4);
move('N',6);
move('K',8);
move('Y',12);
move('O',14);
move('U',16);
gotoxy(5,10);
cout<<"MADE BY-ANKUR DCRUZ";
getch();
}
| true |
4410d9ec153168efda72e8ad5404032ac55665c6 | C++ | 15831944/Fdo_SuperMap | /源代码/CAD PlugIn/UGC的封装/SMCTest/SMCTest.cpp | GB18030 | 8,127 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive |
#include "SMCTest.h"
int main()
{
/* SMCWorkspace workspace;
SMCDataSource* pDataSource = new SMCDataSource ;
SMCDatasetVector* pDataset = new SMCDatasetVector;
//! Թռ
_tstring strWorkspaceName(_T("C:\\TestDS\\World.sxw"));
// std::string strWorkspaceName("D:\\World.sxw");
bool bOpen = workspace.Open(strWorkspaceName);
if(bOpen)
{
std::cout << "ռɹ" << std::endl;
}
else
{
std::cout << "ռʧܣ" << std::endl;
return 0;
}
//! ԹռԴĸ
std::cout << "Դ: " << workspace.m_DataSources.GetCount() << std::endl;
//! ԴϺԴ
SMCDataSource *pDs = new SMCDataSource();
if(workspace.m_DataSources.Lookup (_T("world"), pDs))
{
std::wcout << "Դȫ·: " << pDs->GetName().c_str() << std::endl; //õԴȫ·
std::wcout << "Դ: " << pDs->GetEngineName().c_str() << std::endl;
std::cout << "ԴǷѾ: " << pDs->IsOpen() << std::endl;
std::cout << "Ϣ: " << pDs->SaveInfo() <<std::endl;
std::cout << "ԴǷ: " << pDs->IsConnected() <<std::endl;
std::cout << "ݿ: " << pDs->Connect() <<std::endl;
pDs->SetModifiedFlag(true);
std::cout << "ԴǷѾ: " << pDs->IsModified() <<std::endl;
std::cout << "Դݼĸ: " << pDs->GetDatasetCount() << std::endl;
SMCDatasetVector *pDst = new SMCDatasetVector();
if(pDs->GetDataset(_T("Ocean"), (SMCDataset*&)pDst))
{
std::cout << "ȡΪOceanݼɹ!" << std::endl;
std::wcout << "ΪOceanݼΪ: " << pDst->GetName() << std::endl;
pDst->Open();
//²ݼвѯļ¼
SMCQueryDef def;
SMCRecordset *pRecordset = new SMCRecordset();
if(pDst->Query(def, pRecordset))
{
std::cout << "¼ȡɹ! " << std::endl;
//²Լ¼ĽӿpRecordset
std::cout << "¼Ƿݣ " << pRecordset->HasDBInfo() << std::endl;
std::cout << "¼Ƿм: " << pRecordset->HasGeometry() <<std::endl;
pRecordset->GetDataset(pDst);
std::cout << "¼ӦݼΪ: " << pDst->m_pDataset <<std::endl;
std::cout << "ˢ¼¼: " << pRecordset->Refresh() <<std::endl;
std::cout << "¼ǷΪ: " << pRecordset->IsEmpty() <<std::endl;
int nRecCount = pRecordset->GetRecordCount();
std::cout << "¼ĸΪ: " << nRecCount << std::endl;
while (!pRecordset->IsEOF())
{
std::cout << "¼" << std::endl;
//²Եõֵֶ
SMCVariant var;
pRecordset->GetFieldValue(1, var);
std::cout << var.m_nType <<std::endl;
// std::cout << double(var.m_value) << std::endl;
// double varvalue = (double)var.m_value;
pRecordset->MoveNext();
}
int nFieldCount = pRecordset->GetFieldCount();
std::cout << "ֶεĸΪ: " << nFieldCount << std::endl;
//²ԵõֶϢ
//SMCFieldInfos infos;
//pRecordset->GetFieldInfos(infos);
// std::wcout << infos.at(3).m_strName << std::endl;
}
else
{
std::cout << "¼ȡʧ! " << std::endl;
}
delete pRecordset;
}
else
{
std::cout << "ȡΪ0ݼʧ!" << std::endl;
}
std::cout << "ɾT1ݼ: " << pDs->DeleteDataset(_T("T1")) <<std::endl;
delete pDst;
}
delete pDs;
//! ԹռԴǷΪ
std::cout << "ԴǷΪ: " << workspace.m_DataSources.IsEmpty() << std::endl ;
//! ͨԴ
std::cout << "ΪworldԴΪ: " << workspace.m_DataSources.FindAlias(_T("world")) << std::endl;
//! ԴϵToXML
// std::cout << workspace.m_DataSources.ToXML("D:\\World.sxw") << std::endl;
//! ԴGetAliasAt
std::wcout << "Ϊ0ԴΪ: " << workspace.m_DataSources.GetAliasAt(0) << std::endl;
//! ԴΪ״̬
workspace.m_DataSources.SetModifiedFlag();
//! жԴǷѾ
std::cout << "ԴǷ: " << workspace.m_DataSources.IsModified() << std::endl;
//! ԴϵRename
// std::cout << workspace.m_DataSources.Rename(_T("123"),_T("abc")) << std::endl;
//! 湤ռ
bOpen = workspace.Save();
if(bOpen)
{
std::cout << "ռ䱣ɹ" << std::endl;
}
else
{
std::cout << "Դȡʧܣ" << std::endl;
return 0;
}
std::cout << "ԴӦǣ " << ASCII_STRING(pDataSource->GetName()) << std::endl;
SMCRecordset* pRecordset = new SMCRecordset;
SMCQueryDef queryDef;
//! õռ
int nType = workspace.GetType();
switch( nType )
{
pDataSource->GetDataset(n, (SMCDataset*&)pDataset);
if(!pDataset->Open())
{
std::cout << "ݼʧܣ " << std::endl;
}
if(!pDataset->Query(queryDef, pRecordset))
{
std::cout << "ѯȡ¼ʧܣ" << std::endl;
}
if(pDataset != NULL)
{
std::cout << ASCII_STRING(pDataset->GetName()) << "¼ " << pDataset->GetRecordsetCount() << std::endl;
}
}
//! õռ
std::wstring strPwd = workspace.GetPassword();
std::wcout << _T("ռǣ ") << strPwd << std::endl;
//! رչռ
workspace.Close();*/
SMCDataSource sdbDs;
/* sdbDs.CreateDataSource(SMCDsConnection::SMEngineType::SDBPlus);
SMCDsConnection conn;
conn.m_strServer = _T("C:\\TestDS\\World.sdb");
conn.m_strAlias = _T("World");
sdbDs.SetConnection(conn);
// std::cout << "Դ--C:\\World.sdb " << sdbDs.Create() << std::endl;
std::cout << "Դ--C:\\TestDS\\World.sdb " << sdbDs.Open() << std::endl;
std::cout << "ǷɹԴ--C:\\TestDS\\World.sdb " << sdbDs.IsOpen() << std::endl;
std::cout << "ɾݼ--T1: " << sdbDs.DeleteDataset(_T("T1")) <<std::endl;
std::wcout << "Դȫ·: " << sdbDs.GetName().c_str() << std::endl; //õԴȫ·
std::wcout << "Դ: " << sdbDs.GetEngineName().c_str() << std::endl;
std::cout << "ԴǷѾ: " << sdbDs.IsOpen() << std::endl;
std::cout << "Ϣ: " << sdbDs.SaveInfo() <<std::endl;
std::cout << "ԴǷ: " << sdbDs.IsConnected() <<std::endl;
std::cout << "ݿ: " << sdbDs.Connect() <<std::endl;
sdbDs.SetModifiedFlag(true);
std::cout << "ԴǷѾ: " << sdbDs.IsModified() <<std::endl;
std::cout << "Դݼĸ: " << sdbDs.GetDatasetCount() << std::endl;*/
// _tstring file(_T("SDB;file=C:\\TestDS\\testds.sdb;user=majun;pwd=majun;"));
// _tstring file(_T("Ora;server=ugces;database=majun2;user=majun2;pwd=majun2;"));
sdbDs.OpenDataSource(sdbDs, _T("type=SDB;file=C:\\TestDS\\world.sdb;"));
std::cout << "ǷɹԴ-- " << sdbDs.IsOpen() << std::endl;
std::cout << "ɾݼ--T1: " << sdbDs.DeleteDataset(_T("T1")) << std::endl;
std::wcout << "Դȫ·: " << sdbDs.GetName().c_str() << std::endl; //õԴȫ·
std::wcout << "Դ: " << sdbDs.GetEngineName().c_str() << std::endl;
std::cout << "ԴǷѾ: " << sdbDs.IsOpen() << std::endl;
std::cout << "Ϣ: " << sdbDs.SaveInfo() << std::endl;
std::cout << "ԴǷ: " << sdbDs.IsConnected() << std::endl;
std::cout << "ݿ: " << sdbDs.Connect() << std::endl;
sdbDs.SetModifiedFlag(true);
std::cout << "ԴǷѾ: " << sdbDs.IsModified() << std::endl;
std::cout << "Դݼĸ: " << sdbDs.GetDatasetCount() << std::endl;
// sdbDs.OpenOraDS();
}
| true |
a50e4bba5ac056b6367c620e6139645c0683e6e8 | C++ | luoguanghao/PAT | /patAdv/patA80.cpp | UTF-8 | 1,923 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct manType{
int id;
int rank;
int GE,GI;
double tG;
vector<int> choice;
};
bool cmp(manType a, manType b){
if(a.tG!=b.tG) return a.tG>b.tG;
return a.GE>b.GE;
}
int main(){
int n,m,k;
vector<int> quota, passList[105];
vector<manType> manList;
cin>>n>>m>>k;
int tmp;
for(int i=0;i<m;i++){
cin>>tmp;
quota.push_back(tmp);
}
for(int i=0;i<n;i++){
manType tmpMan;
tmpMan.id=i;
scanf("%d %d",&tmpMan.GE,&tmpMan.GI);
tmpMan.tG=(tmpMan.GE+tmpMan.GI)/2;
int tmpChoice;
for(int j=0;j<k;j++){
scanf("%d",&tmpChoice);
tmpMan.choice.push_back(tmpChoice);
}
manList.push_back(tmpMan);
}
/*////
for(int i=0;i<manList.size();i++){
printf("\n");
for(int j=0;j<manList[i].choice.size();j++){
printf("%d ",manList[i].choice[j]);
}
}
*////
sort(manList.begin(),manList.end(),cmp);
int r=1;
for(int i=0;i<manList.size();i++){
if(i>0&&(manList[i].GE!=manList[i-1].GE||manList[i].tG!=manList[i-1].tG))
r=i+1;
manList[i].rank=r;
}
/*
for(int i=0;i<manList.size();i++)
printf("id=%d %d %d rank=%d\n",manList[i].id,manList[i].GE,manList[i].GI,manList[i].rank);
*/
for(int i=0;i<manList.size();i++){
//printf("\n");
int c;
for(c=0;c<manList[i].choice.size();c++){
int choice=manList[i].choice[c]; //printf("%d ",choice);
if(passList[choice].size()<quota[choice]||manList[passList[choice][passList[choice].size()-1]].rank==manList[i].rank){
passList[choice].push_back(manList[i].id);
break;
}/*else if(manList[passList[choice][passList[choice].size()-1]].rank==manList[i].rank){
passList[choice].push_back(manList[i].id);
break;
}*/
}
}
for(int i=0;i<m;i++){
sort(passList[i].begin(),passList[i].end());
for(int j=0;j<passList[i].size();j++){
if(j!=0)printf(" ");
printf("%d",passList[i][j]);
}
if(i!=m-1) printf("\n");
}
return 0;
} | true |
60d152004d1c94d35a4acdd112a101824047bc85 | C++ | nstbayless/gyoa | /include/gyoa/World.h | UTF-8 | 3,087 | 2.859375 | 3 | [] | no_license | /*
* World.h
*
* Created on: Aug 9, 2015
* Author: n
*/
#ifndef BACKEND_MODEL_WORLD_H_
#define BACKEND_MODEL_WORLD_H_
#include <map>
#include <string>
#include "Room.h"
struct git_repository;
namespace gyoa {
namespace model {
//! Model root. contains list of rooms.
struct world_t {
//! name of the gyoa world.
std::string title="";
//! the next id_type::gid to be assigned on creation of a new room.
unsigned int next_rm_gid=0;
//!rm_id_t of starting room.
id_type first_room=rm_id_t::null();
//! list of rooms, mapped from id_type to room_t.
std::map<id_type,room_t> rooms;
//! not part of model, used to efficiently save data
bool edited=false;
};
/**
* Contains a path, the world model for
* the given path, git repo data, and
* other data pertaining to
* active instances of a model in use
*/
struct ActiveModel {
ActiveModel(){}
//! directory where model is saved/loaded
std::string path;
//! model instance including all unsaved changes
model::world_t world;
git_repository* repo=nullptr;
private:
//non-copyable:
ActiveModel & operator=(const ActiveModel&) = delete;
ActiveModel (const ActiveModel&) = delete;
};
extern "C" {
//! creates a new model (with default parameters). Must be freed with freeModel()
ActiveModel* makeModel(std::string directory);
//! frees an instance of ActiveModel
void freeModel(ActiveModel*);
//! checks if a model exists at directory/world.txt
bool directoryContainsModel(std::string dir);
//! checks if any files are in the directory
bool directoryInUse(std::string dir);
//! loads the model from the given directory (creating a new model if no model is saved there)
//! should be freed with freeModel
ActiveModel* loadModel(const char* dir);
//! preloads all rooms (rather than loading them on-the-fly)
//! returns number of rooms loaded
int loadAllRooms(ActiveModel*);
//! returns true if a room exists with the given ID
bool roomExists(ActiveModel*,rm_id_t);
//! retrieves the room with the given id, loading if necessary
//! should not be modified (will be const in future versions)
room_t& getRoom(ActiveModel*,rm_id_t);
//! retrieves title of room (loading it if necessary)
const char* getRoomTitle(ActiveModel*,rm_id_t);
//retrieves body text of room (loading it if necessary)
const char* getRoomBody(ActiveModel*,rm_id_t);
//retrieves number of options in the given room (loading it if necessary)
const int getOptionCount(ActiveModel*,rm_id_t);
//!retrieves descriptive text of the o-th option in the given room
const char* getOptionDescription(ActiveModel*,rm_id_t,int o);
//!retrieves destination for the o-th option in the given room
rm_id_t getOptionDestination(ActiveModel*,rm_id_t,int o);
//! retrieves nth option id by id from given room, where n is from 0 to 8.
//! returns opt_id_t::null() if no option found.
//! should not be modified (will be const in future versions)
opt_id_t getOptionID(ActiveModel*,rm_id_t, int n);
//! returns path to the given room
std::string rm_id_to_filename(rm_id_t id, std::string root_dir);
}
}
}
#endif /* BACKEND_MODEL_WORLD_H_ */
| true |
0193059e1f8a332182c26e0c3f08009f88452fb9 | C++ | lbel/icsc2018 | /linked_list/main.cxx | UTF-8 | 2,396 | 3.46875 | 3 | [
"Apache-2.0"
] | permissive | #include <ctime>
#include <functional>
#include <iostream>
#include <vector>
#include "linked_list.h"
using std::cout;
using std::endl;
void time(std::function<void()> function, const char* label)
{
const std::clock_t start = std::clock();
function();
const std::clock_t end = std::clock();
cout << "Time (ms) spent on " << label << ": " << (end - start) * 1000. / CLOCKS_PER_SEC << endl;
}
template <class C>
void print_all(const C& collection)
{
for (const auto& x : collection)
{
cout << x << endl;
}
}
int main(int argc, char** argv)
{
const std::uint_least32_t N_ITEMS =
argc >= 2 ? atoi(argv[1]) : 10;
linked_list<int> l;
std::vector<int> v;
time([&l, &N_ITEMS] {
for (std::remove_cv<decltype(N_ITEMS)>::type i = 0; i < N_ITEMS; ++i)
{
l.push_front(i);
}
}, "linked list push_front");
print_all(l);
time([&l, &N_ITEMS] {
for (std::remove_cv<decltype(N_ITEMS)>::type i = 0; i < N_ITEMS; ++i)
{
l.push_back(i);
}
}, "linked list push_back");
// Determining the size many times - should be fast!
time([&l, &N_ITEMS] {
for (std::remove_cv<decltype(N_ITEMS)>::type i = 0; i < N_ITEMS; ++i)
{
l.size();
}
}, "linked list size");
time([&l, &N_ITEMS] {
for (std::remove_cv<decltype(N_ITEMS)>::type i = 0; i < N_ITEMS; ++i)
{
l.pop_front();
}
}, "linked list pop_front");
time([&l, &N_ITEMS] {
for (std::remove_cv<decltype(N_ITEMS)>::type i = 0; i < N_ITEMS; ++i)
{
l.pop_back();
}
}, "linked list pop_back");
time([&v, &N_ITEMS] {
for (std::remove_cv<decltype(N_ITEMS)>::type i = 0; i < N_ITEMS; ++i)
{
v.push_back(i);
}
}, "vector push_back");
time([&v, &N_ITEMS] {
for (std::remove_cv<decltype(N_ITEMS)>::type i = 0; i < N_ITEMS; ++i)
{
v.size();
}
}, "vector size");
time([&v, &N_ITEMS] {
for (std::remove_cv<decltype(N_ITEMS)>::type i = 0; i < N_ITEMS; ++i)
{
v.pop_back();
}
}, "vector pop_back");
}
| true |
97d2fdc6e3633f1b979d7b34b96c7ea8eb1abeaa | C++ | Hengle/isogrid-houdini-sop | /isogrid/isogrid/src/WB_CubeGridExporter.cpp | UTF-8 | 4,803 | 2.703125 | 3 | [] | no_license | #include "WB_CubeGridExporter.h"
#include <fstream>
#include <sstream>
void WB_CubeGridExporter::exportMesh(const std::string &path, double cx, double cy, double cz, int I, int J, int K,
double dx, double dy, double dz, const std::vector<bool> &values, int li, int ui,
int lj, int uj, int lk, int uk)
{
struct Vertex
{
float x, y, z;
};
struct Face
{
int a, b, c, d;
};
std::vector<Vertex> vertices;
std::vector<Face> faces;
getMesh(
[&vertices](float x, float y, float z) {
vertices.push_back({ x, y, z });
},
[&faces](int a, int b, int c, int d) {
faces.push_back({ a, b, c, d });
},
cx, cy, cz, I, J, K, dx, dy, dz, values, li, ui, lj, uj, lk, uk);
std::ofstream file(path);
std::stringstream objstr;
objstr << "# generated by WB_CubeGridExporter\n";
for (auto &vertex : vertices)
{
objstr << "v " << vertex.x << " " << vertex.y << " " << vertex.z << '\n';
}
for (auto &face : faces)
{
objstr << "f " << face.a << ' ' << face.b << ' ' << face.c << '\n';
objstr << "f " << face.c << ' ' << face.d << ' ' << face.a << '\n';
}
file << objstr.str();
}
void WB_CubeGridExporter::getMesh(std::function<void(float, float, float)> addVertexCallback,
std::function<void(int, int, int, int)> addFaceCallback, double cx, double cy,
double cz, int I, int J, int K, double dx, double dy, double dz,
const std::vector<bool> &values, int li, int ui, int lj, int uj, int lk, int uk)
{
auto vertexCount = 0;
auto index = [](int i, int j, int k, int JK, int K, int li, int ui, int lj, int uj, int lk, int uk) {
if (i > li - 1 && j > lj - 1 && k > lk - 1 && i < ui && j < uj && k < uk)
{
return k + j * K + i * JK;
}
else
{
return -1;
}
};
std::vector<std::vector<std::vector<int>>> vertexIndices;
std::vector<double> c = { cx - I * 0.5f * dx, cy - J * 0.5f * dy, cz - K * 0.5f * dz };
auto getVindex = [&vertexIndices, c, addVertexCallback, &vertexCount](int i, int j, int k, double dx, double dy,
double dz) {
if (vertexIndices[i][j][k] == -1)
{
vertexIndices[i][j][k] = (vertexCount++) + 1;
addVertexCallback((float)(c[0] + i * dx), (float)(c[1] + j * dy), (float)(c[2] + k * dz));
}
return vertexIndices[i][j][k];
};
vertexIndices.resize(I + 1);
for (int i = 0; i <= I; i++)
{
vertexIndices[i].resize(J + 1);
for (int j = 0; j <= J; j++)
{
vertexIndices[i][j].resize(K + 1);
for (int k = 0; k <= K; k++)
{
vertexIndices[i][j][k] = -1;
}
}
}
int val0 = 0, valm = 0, sum = 0;
int idx = 0;
int JK = J * K;
for (int i = li; i <= ui; i++)
{
for (int j = lj; j < uj; j++)
{
for (int k = lk; k < uk; k++)
{
idx = index(i, j, k, J, JK, li, ui, lj, uj, lk, uk);
val0 = idx == -1 ? 0 : values[idx] ? 1 : 0;
idx = index(i - 1, j, k, J, JK, li, ui, lj, uj, lk, uk);
valm = idx == -1 ? 0 : values[idx] ? 1 : 0;
sum = val0 + valm;
if (sum == 1)
{
addFaceCallback(getVindex(i, j, k, dx, dy, dz), getVindex(i, j + 1, k, dx, dy, dz),
getVindex(i, j + 1, k + 1, dx, dy, dz), getVindex(i, j, k + 1, dx, dy, dz));
}
}
}
}
for (int i = li; i < ui; i++)
{
for (int j = lj; j <= uj; j++)
{
for (int k = lk; k < uk; k++)
{
idx = index(i, j, k, J, JK, li, ui, lj, uj, lk, uk);
val0 = idx == -1 ? 0 : values[idx] ? 1 : 0;
idx = index(i, j - 1, k, J, JK, li, ui, lj, uj, lk, uk);
valm = idx == -1 ? 0 : values[idx] ? 1 : 0;
sum = val0 + valm;
if (sum == 1)
{
addFaceCallback(getVindex(i, j, k, dx, dy, dz), getVindex(i + 1, j, k, dx, dy, dz),
getVindex(i + 1, j, k + 1, dx, dy, dz), getVindex(i, j, k + 1, dx, dy, dz));
}
}
}
}
for (int i = li; i < ui; i++)
{
for (int j = lj; j < uj; j++)
{
for (int k = lk; k <= uk; k++)
{
idx = index(i, j, k, J, JK, li, ui, lj, uj, lk, uk);
val0 = idx == -1 ? 0 : values[idx] ? 1 : 0;
idx = index(i, j, k - 1, J, JK, li, ui, lj, uj, lk, uk);
valm = idx == -1 ? 0 : values[idx] ? 1 : 0;
sum = val0 + valm;
if (sum == 1)
{
addFaceCallback(getVindex(i, j, k, dx, dy, dz), getVindex(i + 1, j, k, dx, dy, dz),
getVindex(i + 1, j + 1, k, dx, dy, dz), getVindex(i, j + 1, k, dx, dy, dz));
}
}
}
}
}
| true |
022f6af8ed6284c80f478a984e342437904fadd0 | C++ | wangzhen11aaa/CPlusPlus_Primer | /chapter8/exercise5.cpp | UTF-8 | 569 | 3.390625 | 3 | [] | no_license | //
// Created by wangzhen on 20/02/2017.
//
#include <iostream>
template <typename T>
T largest(const T arr[]);
const int knum = 5;
int main(void)
{
int iarr[knum] = {3, 10, 2, 20, 100};
double darr[knum] = {-100.0, 2.0, 4.0, 256.0, 1024.0};
std::cout << "iarr max is " << largest(iarr) << std::endl;
std::cout << "darr max is " << largest(darr) << std::endl;
}
template <typename T>
T largest(const T arr[])
{
T max = arr[0];
for(int i = 1; i < knum; ++i)
{
if (max < arr[i])
max = arr[i];
}
return max;
} | true |
9b580f6719d6ce8f66e49d49fae0fd3289c8f02d | C++ | oliriley/PhantomController | /SensAble/GHOST/v4.0/include/gstBasicTransformMatrix.h | UTF-8 | 13,348 | 2.9375 | 3 | [] | no_license | //
// File:gstBasicTransformMatrix.h
//
// Copyright (C) 2000 SensAble Technologies, Inc.
// All rights reserved.
//
//
//
// Provides basic functionality of a 4x4 transform matrix.
//
#ifndef GST_BASIC_TRANFORM_MATRIX
#define GST_BASIC_TRANFORM_MATRIX
#include <gstGenericMatrix.h>
#include <gstBasic.h>
#include <gstPoint.h>
#include <gstVector.h>
class GHOST_DLL_IMPORT_EXPORT gstBasicTransformMatrix
{
public:
//
// Default constructor.
//
gstBasicTransformMatrix()
{
makeIdentity();
}
//
// Constructor from array of 16 values
// stored by row.
//
gstBasicTransformMatrix(const double * const mat);
//
// Construct from 16 values. Values construct the following matrix:
// a1 a2 a3 a4
// a5 a6 a7 a8
// a9 a10 a11 a12
// a13 a14 a15 a16
//
gstBasicTransformMatrix(double a1, double a2, double a3, double a4,
double a5, double a6, double a7, double a8,
double a9, double a10, double a11, double a12,
double a13, double a14, double a15, double a16)
{
double a[4][4] = {
{a1,a2,a3,a4},{a5,a6,a7,a8},{a9,a10,a11,a12},{a13,a14,a15,a16}};
set (a);
}
//
// Constructor from 4x4 array of values
//
gstBasicTransformMatrix(
const double a[4][4])
{
set(a);
}
//
// Compare matrices (returns true if all elements
// of one matrix are within epsilon of the other).
//
bool compare(const gstBasicTransformMatrix& rhs,
double epsilon=GST_EPSILON) const;
//
// Comparison operator (==).
//
bool operator ==(
const gstBasicTransformMatrix& rhs) const
{
return compare(rhs);
}
//
// Comparison operator (!=)
//
bool operator !=(
const gstBasicTransformMatrix& rhs) const
{
return !compare(rhs);
}
//
// Get value at location (i,j).
//
double get(
const int i,
const int j) const
{
return m_elements[i][j];
}
//
// Set value at location (i,j).
//
void set(
const int i,
const int j,
const double value)
{
m_elements[i][j] = value;
}
//
// operator() get element (i,j)
//
double & operator()(const int i, const int j)
{
return m_elements[i][j];
}
const double & operator()(const int i, const int j) const
{
return m_elements[i][j];
}
//
// operator[][] returns element (i,j)
//
double * operator [](const int i)
{
return &m_elements[i][0];
}
const double * operator[](int i) const
{
return &m_elements[i][0];
}
//
// Matrix Multiplication
//
gstBasicTransformMatrix multiply(
const gstBasicTransformMatrix & rhs) const;
//
// Matrix Multiplication (operator *).
//
gstBasicTransformMatrix operator *(
const gstBasicTransformMatrix &rhs) const;
//
// Matrix Multiplication (operator *=).
//
gstBasicTransformMatrix & operator *=(
const gstBasicTransformMatrix &rhs);
//
// post multiply point with matrix and returns
// resultant point. Assumes fourth coordinate is
// 1 (picks up translation).
//
gstPoint postMultiply(
const gstPoint &p) const;
//
// pre multiply point with matrix and returns
// resultant point. Assumes fourth coordinate is
// 1 (picks up translation).
//
gstPoint preMultiply(
const gstPoint &p) const;
//
// post multiply vector with matrix and returns
// resultant vector. Assumes fourth coordinate is
// 0 (does not pick up translation).
//
gstVector postMultiply(
const gstVector &v) const;
//
// pre multiply vector with matrix and returns
// resultant vector. Assumes fourth coordinate is
// 0 (does not pick up translation).
//
gstVector preMultiply(
const gstVector &v) const;
//
// Sets to identity matrix.
//
void makeIdentity()
{
gstGenericMatrix::makeIdentity4x4(*this);
}
//
// Tests if matrix is an identity matrix.
//
bool isIdentity();
//
// get transpose of matrix
//
gstBasicTransformMatrix getTranspose() const;
//
// Set value of matrix to its transpose
//
void transpose();
//
// Get inverse of matrix. 'success' is set to TRUE if the matrix
// was inverted (i.e. has an inverse), and FALSE if the matrix
// inverse failed (e.g. the matrix was singular). The return
// value is indeterminate if success is FALSE.
// Calling getInverse without the 'success' variable will
// also yield indeterminate results if no inverse for the matrix
// exists.
//
gstBasicTransformMatrix getInverse();
gstBasicTransformMatrix getInverse(bool &success);
//
// Sets value of matrix to inverse.
// Returns TRUE if the matrix was successfully inverted, FALSE if there
// is no inverse to the matrix (e.g. the matrix is singular).
// The matrix is not modified (i.e. is unchanged as a result of
// calling the function) if the function returns FALSE.
//
bool invert();
//
// Set 4x4 array.
//
void set(const double a[4][4])
{
copy4x4(m_elements, a);
}
//
// Set 4x4 array.
//
void set(const gstBasicTransformMatrix &m)
{
set(m.m_elements);
}
//
// Get 4x4 array.
//
void get(double a[4][4]) const
{
copy4x4(a, m_elements);
}
//
// Copies values from copyFromMat to copyToMat.
//
inline static void copy4x4(
double dst[4][4],
const double src[4][4])
{
memcpy(dst, src, sizeof(double) * 16);
}
//
// Returns a matrix with the given translation.
// Translations are set along the last row of the matrix.
// The generated translation matrix is:
// 1 0 0 0
// 0 1 0 0
// 0 0 1 0
// x y z 1
//
static gstBasicTransformMatrix createTranslation(const double x,
const double y,
const double z);
static gstBasicTransformMatrix createTranslation(const gstPoint &p);
//
// Returns a matrix with the given scale.
// The generated scale matrix is:
// x 0 0 0
// 0 y 0 0
// 0 0 z 0
// 0 0 0 1
//
static gstBasicTransformMatrix createScale(const double x,
const double y,
const double z);
static gstBasicTransformMatrix createScale(const gstPoint &p);
//
// Returns a matrix with the given rotation.
// The matrix is created with a rotation of <radians>
// radians around the specified <v> vector.
// <v> is required to have non-zero magnitude. Other than that,
// the magnitude of <v> does not affect the rotation (i.e.
// a normalized version of <v> is used to determine the
// rotation).
//
static gstBasicTransformMatrix createRotation(const gstVector &v,
const double radians);
//
// Returns a matrix with the given rotation.
// The matrix is created with a rotation of <radians>
// radians around a vector with components {x,y,z}.
// The vector {x,y,z} is required to have non-zero magnitude.
// Other than that, the magnitude of the vector does not affect the
// rotation (i.e. a normalized version of {x,y,z} is used to
// determine the rotation).
//
static gstBasicTransformMatrix createRotation(const double x,
const double y,
const double z,
const double radians);
//
// Returns a gstBasicTransformMatrix with a
// rotation of <radians> radians around the X axis.
//
static gstBasicTransformMatrix createRotationAroundX(const double radians)
{
return createRotation(gstVector(1,0,0),radians);
}
//
// Returns a gstBasicTransformMatrix with a
// rotation of <angle> radians around the Y axis.
//
static gstBasicTransformMatrix createRotationAroundY(const double radians)
{
return createRotation(gstVector(0,1,0),radians);
}
//
// Returns a gstBasicTransformMatrix with a
// rotation of <angle> radians around the Z axis.
//
static gstBasicTransformMatrix createRotationAroundZ(const double radians)
{
return createRotation(gstVector(0,0,1),radians);
}
private:
double m_elements[4][4];
};
inline ostream& operator<<(ostream& os,
const gstBasicTransformMatrix &mat)
{
return gstGenericMatrix::output<
gstBasicTransformMatrix,
4, 4, ostream>(os, mat);
}
inline gstPoint operator *(
const gstPoint &pt,
const gstBasicTransformMatrix &mat)
{
return mat.preMultiply(pt);
}
inline gstPoint operator *(
const gstBasicTransformMatrix &mat,
const gstPoint &pt)
{
return mat.postMultiply(pt);
}
inline gstVector operator *(
const gstVector &vec,
const gstBasicTransformMatrix &mat)
{
return mat.preMultiply(vec);
}
inline gstVector operator *(
const gstBasicTransformMatrix &mat,
const gstVector &vec)
{
return mat.postMultiply(vec);
}
//
// Constructor from array of 16 values
// stored by row.
//
inline gstBasicTransformMatrix::gstBasicTransformMatrix(
const double * const mat)
{
for (int i=0;i < 4 ;++i )
{
for (int j=0;j < 4 ;++j )
{
set(i,j,mat[4*i+j]);
}
}
}
//
// Compare matrices (returns true if all elements
// of one matrix are within epsilon of the other).
//
inline bool gstBasicTransformMatrix::compare(
const gstBasicTransformMatrix& rhs,
double epsilon) const
{
return gstGenericMatrix::compare<
gstBasicTransformMatrix,
gstBasicTransformMatrix,
4,4, double>(*this, rhs, epsilon);
}
//
// Matrix Multiplication
//
inline gstBasicTransformMatrix
gstBasicTransformMatrix::multiply(
const gstBasicTransformMatrix & rhs) const
{
gstBasicTransformMatrix res;
gstGenericMatrix::mulMatrixMatrix4x4(res, *this, rhs);
return res;
}
//
// Matrix Multiplication (operator *).
//
inline gstBasicTransformMatrix
gstBasicTransformMatrix::operator *(
const gstBasicTransformMatrix &rhs) const
{
gstBasicTransformMatrix res;
gstGenericMatrix::mulMatrixMatrix4x4(res, *this, rhs);
return res;
}
//
// Matrix Multiplication (operator *=).
//
inline gstBasicTransformMatrix &
gstBasicTransformMatrix::operator *=(
const gstBasicTransformMatrix &rhs)
{
gstBasicTransformMatrix res;
gstGenericMatrix::mulMatrixMatrix4x4(res, *this, rhs);
set(res);
return *this;
}
inline gstPoint gstBasicTransformMatrix::postMultiply(
const gstPoint &p) const
{
gstPoint res;
gstGenericMatrix::mulMatrix4x4Point3(res, *this, p);
return res;
}
//
// pre multiply point with matrix and returns
// resultant point. Assumes fourth coordinate is
// 1 (picks up translation).
//
inline gstPoint gstBasicTransformMatrix::preMultiply(
const gstPoint &p) const
{
gstPoint res;
gstGenericMatrix::mulPoint3Matrix4x4(res, p, *this);
return res;
}
//
// post multiply vector with matrix and returns
// resultant vector. Assumes fourth coordinate is
// 0 (does not pick up translation).
//
inline gstVector gstBasicTransformMatrix::postMultiply(
const gstVector &v) const
{
gstVector res;
gstGenericMatrix::mulMatrix4x4Vector3(res, *this, v);
return res;
}
//
// pre multiply vector with matrix and returns
// resultant vector. Assumes fourth coordinate is
// 0 (does not pick up translation).
//
inline gstVector gstBasicTransformMatrix::preMultiply(
const gstVector &v) const
{
gstVector res;
gstGenericMatrix::mulVector3Matrix4x4(res, v, *this);
return res;
}
//
// get transpose of matrix
//
inline gstBasicTransformMatrix
gstBasicTransformMatrix::getTranspose() const
{
gstBasicTransformMatrix m;
gstGenericMatrix::transpose4x4(m, *this);
return m;
}
//
// Set value of matrix to its transpose
//
inline void gstBasicTransformMatrix::transpose()
{
gstBasicTransformMatrix m;
gstGenericMatrix::transpose4x4(m, *this);
set(m);
}
//
// Sets value of matrix to its inverse.
// Returns TRUE if the matrix was successfully inverted, FALSE if there
// is no inverse to the matrix (e.g. the matrix is singular).
// The matrix is not modified (i.e. is unchanged as a result of
// calling the function) if the function returns FALSE.
//
inline bool gstBasicTransformMatrix::invert()
{
bool success;
gstBasicTransformMatrix m = getInverse(success);
if (success)
set(m);
return success;
}
//
// Get inverse of matrix. The result is indeterminate if
// no inverse exists for the matrix (e.g. the matrix is singular).
//
inline gstBasicTransformMatrix gstBasicTransformMatrix::getInverse()
{
bool success;
return getInverse(success);
}
//
// Tests if matrix is an identity matrix.
//
inline bool gstBasicTransformMatrix::isIdentity()
{
gstBasicTransformMatrix i;
i.makeIdentity();
return compare(i,.0001);
}
#endif // GST_BASIC_TRANFORM_MATRIX
| true |
c171cf0f8947b229b2a643ec0a30e6e7c938e192 | C++ | IgnisRain/Game-Programming-CS3113 | /Platformer+Sound/Entity.cpp | UTF-8 | 3,091 | 2.875 | 3 | [] | no_license | #include "Entity.h"
Entity::Entity(float x, float y, float rotation, GLuint textureID, float width, float height)
: x(x), y(y), rotation(rotation), textureID(textureID), width(width), height(height) {
velocityX = 0.0f;
velocityY = 0.0f;
accelerationX = 0.0f;
accelerationY = 0.0f;
frictionX = 2.0f;
frictionY = 2.0f;
}
Entity::Entity() {}
void Entity::Draw() {
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, textureID);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(x, y, 0.0);
glRotatef(rotation, 0.0, 0.0, 1.0);
GLfloat quad[] = { -width * 0.5f, height * 0.5f, -width * 0.5f, -height * 0.5f, width * 0.5f, -height * 0.5f, width * 0.5f, height * 0.5f };
glVertexPointer(2, GL_FLOAT, 0, quad);
glEnableClientState(GL_VERTEX_ARRAY);
GLfloat quadUVs[] = { 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0 };
glTexCoordPointer(2, GL_FLOAT, 0, quadUVs);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDrawArrays(GL_QUADS, 0, 4);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisable(GL_TEXTURE_2D);
}
void Entity::ssDraw(float scale){
glLoadIdentity();
glTranslatef(x, y, 0.0);
glRotatef(rotation, 0.0, 0.0, 1.0);
sprite.draw(scale);
}
void Entity::setX(float newX){ x = newX; }
void Entity::setY(float newY){ y = newY; }
void Entity::setWidth(float w) { width = w; }
void Entity::setHeight(float h) { height = h; }
void Entity::setAccelerationX(float newA) { accelerationX = newA; }
void Entity::setAccelerationY(float newA) { accelerationY = newA; }
void Entity::setVelocityX(float newV) { velocityX = newV; }
void Entity::setVelocityY(float newV) { velocityY = newV; }
void Entity::setFrictionX(float newF) { frictionX = newF; }
void Entity::setFrictionY(float newf) { frictionY = newf; }
void Entity::setSprite(SpriteSheet temp){ sprite = temp; }
float Entity::getVelocityX() { return velocityX; }
float Entity::getVelocityY() { return velocityY; }
float Entity::getAccelerationX() { return accelerationX; }
float Entity::getAccelerationY() { return accelerationY; }
float Entity::getFrictionX() { return frictionX; }
float Entity::getFrictionY() { return frictionY; }
float Entity::getX(){ return x; }
float Entity::getY() { return y; }
float Entity::getHeight() { return height; }
float Entity::getWidth() { return width; }
bool Entity::collidesWith(Entity* other)
{
float thisTop = this->getY() + (this->getHeight() * 0.3);
float thisBottom = this->getY() - (this->getHeight()* 0.3);
float thisLeft = this->getX() - (this->getWidth()* 0.3);
float thisRight = this->getX() + (this->getWidth()* 0.3);
float otherTop = other->getY() + (other->getHeight() * 0.3);
float otherBottom = other->getY() - (other->getHeight()* 0.3);
float otherLeft = other->getX() - (other->getWidth() * 0.3);
float otherRight = other->getX() + (other->getWidth()* 0.3);
if (thisBottom > otherTop || thisTop < otherBottom || thisLeft > otherRight || thisRight < otherLeft)
return false;
else
return true;
}
| true |
f86834fe8e250dadaac813d7c49ca00b335d4c04 | C++ | WadieAC/C-CODES | /18_POO_02/7. Estaticos/Estatico.h | UTF-8 | 321 | 3.078125 | 3 | [] | no_license | #include<iostream>
using namespace std;
class Estatico{
private:
static int contador; //Declaracion de un atributo static
public:
Estatico(){
contador++;
}
int getContador(){
return contador;
}
static int sumar(int n1,int n2){
int suma = n1+n2;
return suma;
}
};
| true |
1c01fa32c26b63662396449b8907b033845e3c49 | C++ | zzo30802/design_pattern_Cpp | /src/SOLID/04_Interface_Segregation_Principle.cpp | UTF-8 | 3,215 | 3.015625 | 3 | [] | no_license | // 介面隔離原則 Interface Segregation Principle (ISP)
// https://medium.com/@f40507777/%E4%BB%8B%E9%9D%A2%E9%9A%94%E9%9B%A2%E5%8E%9F%E5%89%87-interface-segregation-principle-isp-6854c5b3b42c
/*
理念核心:
1. 不應該強迫用戶去依賴他們未使用的辦法
2. 最小化類別與類別之間的介面
遇到的問題:
1. 避免介面太多
2. 並非全部的方法都會使用到
3. 繼承後空實作
沒遵守DIP可能造成情況:
1. 繼承或抽象類別 : 多餘的界面在子類別可能會有空實作,會使使用方造成不可預期錯誤。
2. 假使A介面有BCD方法,使用者E使用B,其他人使用C or D,如果為了使用者改變了方法B的介面,其他使用者就必須重新Compile
解決辦法:
1. 客製使用者的interface,只提供用的到的,在利用組合實現。
2. 分割組合:將類別分割後,需要reuse實作地方在利用組合方式實現,這裡可以使用多重繼承或Delegate等等
*/
#include <cstdio>
#include <fstream>
#include <iostream>
#include <string>
#include <tuple>
#include <vector>
// #include <python3.5m/Python.h>
// int main() {
// // Python initialize
// Py_Initialize();
// if (!Py_IsInitialized()) {
// std::cout << "Python initialization failed" << std::endl;
// return -1;
// }
// // choose 1
// if (!PyRun_SimpleString("execfile('pythontest.py')"))
// std::cout << "fail" << std::endl;
// // choose 2
// char fileStr[] = "pythontest.py";
// FILE *fp;
// if (!(fp = fopen(fileStr, "r")))
// std::cout << "open python file failed" << std::endl;
// if (!PyRun_SimpleFile(fp, fileStr))
// std::cout << "execute python file failed!" << std::endl;
// fclose(fp);
// // 釋放資源
// Py_Finalize();
// return 0;
// }
struct Document;
/*
struct IMachine {
virtual void print(Document& doc) = 0;
virtual void scan(Document& doc) = 0;
virtual void fax(Document& doc) = 0;
};
struct MFP : IMachine {
void print(Document& doc) override {
}
void scan(Document& doc) override {
}
void fax(Document& doc) override {
}
};
// 1. Recompile
// 2. Client does not need this
// 3. Forcing implementors to implement too much
*/
// virtual interface
struct IPrinter {
virtual void print(Document& doc) = 0;
};
struct IScanner {
virtual void scan(Document& doc) = 0;
};
// implement interface
struct Printer : IPrinter {
void print(Document& doc) override;
};
struct Scanner : IScanner {
void scan(Document& doc) override;
};
// 如果客戶指要求print && scan,而沒有fax,我們就可以新增一個interface
// 並且只繼承了print && scan
// IMachine 繼承了兩個功能的interface
struct IMachine : IPrinter, IScanner {
};
struct Machine : IMachine {
IPrinter& printer;
IScanner& scanner;
// constructor
Machine(IPrinter& printer, IScanner& scanner)
: printer{printer},
scanner{scanner} {
}
void print(Document& doc) override {
printer.print(doc);
}
void scan(Document& doc) override {
scanner.scan(doc);
}
};
// IPrinter --> Printer
// everything --> Machine
int main() {
Document doc;
Printer print;
Scanner scan;
Machine a(print, scan);
a.print(doc);
} | true |
b1b458c7bfd1ff16d700ff1e88fd60750a251826 | C++ | ca2/app2018 | /appseed/aura/aura/aura/aura_console_window.h | UTF-8 | 2,538 | 2.546875 | 3 | [] | no_license | #pragma once
void RedirectIOToConsole();
class std_out_buffer:
virtual public ::file::file
{
public:
std_out_buffer() {}
virtual ~std_out_buffer() {}
void write(const void * lpBuf,memory_size_t nCount);
};
//class console_ostream:
// virtual public ::file::plain_text_stream
//{
//public:
//
// console_ostream(): ::file::plain_text_stream(canew(std_out_buffer())){}
// virtual ~console_ostream(){}
//
//};
namespace console
{
const int WHITE = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
const int RED = FOREGROUND_RED | FOREGROUND_INTENSITY;
const int BLUE = FOREGROUND_BLUE | FOREGROUND_INTENSITY;
const int DARKBLUE = FOREGROUND_BLUE;
const int CYAN = FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
const int MAGENTA = FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
const int YELLOW = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY;
const int BLACK = 0;
class CLASS_DECL_AURA window:
virtual public ::object
{
public:
::file::plain_text_stream cout;
virtual void redirect_io();
virtual void SetWindowSize(int iHeight,int iWidth) = 0;
virtual void SetCursorVisibility(bool show) = 0;
virtual void SetCursorPosition(int y,int x) = 0;
virtual void SetTextColor(int color) = 0;
virtual void SetScreenColor(int color,int iLineStart = 0,int iLineCount = -1) = 0;
virtual void write(const char * psz) = 0;
};
class window_composite:
virtual public window
{
public:
window * m_p;
window_composite()
{
m_p = NULL;
}
window_composite(window * p):
object(p->get_app()),
m_p(p)
{
cout.m_spfile = m_p->cout.m_spfile;
}
virtual void redirect_io() { m_p->redirect_io(); }
virtual void SetWindowSize(int iHeight,int iWidth) { m_p->SetWindowSize(iHeight,iWidth); }
virtual void SetCursorVisibility(bool show) { m_p->SetCursorVisibility(show); }
virtual void SetCursorPosition(int y,int x) { m_p->SetCursorPosition(y,x); }
virtual void SetTextColor(int color) { m_p->SetTextColor(color); }
virtual void SetScreenColor(int color,int iLineStart = 0,int iLineCount = -1) { m_p->SetScreenColor(color,iLineStart,iLineCount); }
virtual void write(const char * psz) { m_p->write(psz); }
//virtual void write(const void * lpBuf,memory_size_t nCount);
};
} // namespace console
| true |
c58550d6f216df5f86c079c10792ac0c2a2031e7 | C++ | techtronics/Cleaver2 | /src/gui/Application/Data/DataManager.cpp | UTF-8 | 6,718 | 2.8125 | 3 | [
"MIT"
] | permissive | #include "DataManager.h"
#include <QMessageBox>
#include <Cleaver/InverseField.h>
#include <Cleaver/AbstractScalarField.h>
DataManager::DataManager()
{
}
void DataManager::addMesh(cleaver::TetMesh *mesh)
{
m_meshes.push_back(mesh);
emit dataChanged();
emit dataAdded();
emit meshAdded();
emit meshListChanged();
}
void DataManager::removeMesh(cleaver::TetMesh *mesh)
{
std::vector<cleaver::TetMesh*>::iterator iter = m_meshes.begin();
while(iter != m_meshes.end())
{
if(*iter == mesh)
iter = m_meshes.erase(iter);
}
emit dataChanged();
emit dataRemoved();
emit meshRemoved();
emit meshListChanged();
}
void DataManager::addField(cleaver::AbstractScalarField *field)
{
m_fields.push_back(field);
emit dataChanged();
emit dataAdded();
emit fieldAdded();
emit fieldListChanged();
}
void DataManager::removeField(cleaver::AbstractScalarField *field, bool ask_delete_volume)
{
std::vector<cleaver::AbstractScalarField*>::iterator iter;
bool deleteVolume = false;
bool addInverse = false;
if (m_fields.size() == 2 && ask_delete_volume) {
QMessageBox msgBox;
msgBox.setText("You are Removing too many fields");
msgBox.setInformativeText("Do you want remove the volume, or mesh one field?");
QPushButton *deleteVol = msgBox.addButton(tr("Remove Volume"), QMessageBox::DestructiveRole);
QPushButton *addInv = msgBox.addButton(tr("Mesh One"), QMessageBox::ActionRole);
QPushButton *cancel = msgBox.addButton(tr("Cancel"), QMessageBox::NoRole);
msgBox.exec();
if (msgBox.clickedButton() == reinterpret_cast<QAbstractButton*>(deleteVol)) {
deleteVolume = true;
} else if (msgBox.clickedButton() == reinterpret_cast<QAbstractButton*>(addInv)) {
addInverse = true;
} else if (msgBox.clickedButton() == reinterpret_cast<QAbstractButton*>(cancel)) {
return;
}
}
for(iter = m_fields.begin(); iter != m_fields.end(); iter++)
{
// remove field if there's a match
if(*iter == field){
iter = m_fields.erase(iter);
// make sure we're not at the end
if(iter == m_fields.end())
break;
}
}
// remove it from any volume's that have it
std::vector<cleaver::Volume*>::iterator vol_iter;
cleaver::Volume *temp_volume = NULL;
for(vol_iter = m_volumes.begin(); vol_iter != m_volumes.end(); vol_iter++)
{
cleaver::Volume *volume = *vol_iter;
// first check materials
for(int m=0; m < volume->numberOfMaterials(); m++)
{
if(volume->getMaterial(m) == field) {
volume->removeMaterial(field);
temp_volume = volume;
}
}
// then check sizing field
if(volume->getSizingField() == field)
volume->setSizingField(NULL);
}
// finally free the memory
//if (field)
// delete field;
if (deleteVolume && temp_volume)
removeVolume(temp_volume);
if (addInverse && temp_volume) {
cleaver::AbstractScalarField* fld = new cleaver::InverseScalarField(m_fields[0]);
fld->setName(m_fields[0]->name() + "-inverse");
temp_volume->addMaterial(fld);
addField(fld);
}
emit dataChanged();
emit dataRemoved();
emit fieldRemoved();
emit fieldListChanged();
emit volumeListChanged();
}
void DataManager::addVolume(cleaver::Volume *volume)
{
m_volumes.push_back(volume);
emit dataChanged();
emit dataAdded();
emit volumeAdded();
emit volumeListChanged();
}
void DataManager::removeVolume(cleaver::Volume *volume)
{
std::vector<cleaver::Volume*>::iterator iter;
for(iter = m_volumes.begin(); iter != m_volumes.end(); iter++)
{
cleaver::Volume* vol = *iter;
while (vol->numberOfMaterials() > 0) {
this->removeField(vol->getMaterial(0),false);
}
this->removeField(vol->getSizingField(),false);
// remove the volume if there's a match
if(*iter == volume){
iter = m_volumes.erase(iter);
// make sure we're not at the end
if(iter == m_volumes.end())
break;
}
}
// free memory
delete volume;
emit dataChanged();
emit dataRemoved();
emit volumeRemoved();
emit volumeListChanged();
}
std::vector<ulong> DataManager::getSelection()
{
return m_selection;
}
//============================================
// This method will set the given data object
// to be the exclusive selection.
//============================================
void DataManager::setSelection(ulong ptr)
{
m_selection.clear();
m_selection.push_back(ptr);
emit selectionChanged();
}
//============================================
// This method will add the given data object
// to the selection list. Keeping any prior
// items on the list as well.
//============================================
void DataManager::addSelection(ulong ptr)
{
// make sure we don't add it twice
std::vector<ulong>::iterator iter = m_selection.begin();
while(iter != m_selection.end())
{
if(*iter == ptr)
return;
iter++;
}
m_selection.push_back(ptr);
emit selectionChanged();
}
//===============================================
// This method will altnerate the given data
// object from selected or not selected, and
// remove any other current selections.
//===============================================
void DataManager::toggleSetSelection(ulong ptr)
{
std::vector<ulong>::iterator iter = m_selection.begin();
while(iter != m_selection.end())
{
if(*iter == ptr)
{
m_selection.clear();
emit selectionChanged();
return;
}
iter++;
}
m_selection.clear();
m_selection.push_back(ptr);
std::cout << "Selection Toggled" << std::endl;
emit selectionChanged();
}
//===============================================
// This method will alternate the given data object
// from selected or not selected. It will not alter
// any other selection in place.
//===============================================
void DataManager::toggleAddSelection(ulong ptr)
{
std::vector<ulong>::iterator iter = m_selection.begin();
while(iter != m_selection.end())
{
// remove it if we find it
if(*iter == ptr)
{
m_selection.erase(iter);
emit selectionChanged();
return;
}
iter++;
}
// otherwise add it
m_selection.push_back(ptr);
std::cout << "Selection Toggled" << std::endl;
emit selectionChanged();
}
void DataManager::clearSelection()
{
m_selection.clear();
emit selectionChanged();
}
| true |
9f3197ba3c1ffd61bd978c9a2fc4a9dc19fbe341 | C++ | FOSSBOSS/Learning-OpenCV-3_examples | /examples/chapter2/example2_9.cpp | UTF-8 | 1,367 | 2.96875 | 3 | [] | no_license | //Examples 2-8, 2-9,, are extended version of example 2.7
//Getting, and setting pixels
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char ** argv){
Mat img_rgb, img_gray, img_cny, img_pyr0, img_pyr1;
img_rgb=imread(argv[1]); //get an image
int x=16, y=32;
Vec3b intensity = img_rgb.at< Vec3b >(x,y); //set, but not used. page35
uchar blue=intensity[0];
uchar green=intensity[1];
uchar red =intensity[2];
namedWindow("Source", WINDOW_AUTOSIZE);
namedWindow("Gray", WINDOW_AUTOSIZE);
namedWindow("Canny", WINDOW_AUTOSIZE);
cvtColor(img_rgb, img_gray, COLOR_BGR2GRAY);
pyrDown(img_gray, img_pyr0); //produces an image half the x,y pixels of the first image.
pyrDown(img_pyr0, img_pyr1); //Half again
Canny(img_pyr1,img_cny,10,100,3,true);
cout << "At point (x,y) = (" << x << "," << y << ") blue, green, red = (" << (unsigned int)blue <<", " << (unsigned int)green <<", " << (unsigned int)red <<")\n ";
cout << "The Gray pixel there is: " << (unsigned int)img_gray.at<uchar>(x,y) << "\n";
x/=4;
y/=4;
cout << "Pyramid pixel there is: " << (unsigned int)img_pyr1.at<uchar>(x,y) << "\n";
img_cny.at<uchar>(x,y) = 128; //set pixel at this location to 128
imshow("Source",img_rgb);
imshow("Gray",img_pyr1);
imshow("Canny",img_cny);
waitKey(0);
return 0; //not in book example, pg 34
}
| true |
afa0329e587012b88a3dca95c6fe646bf8a66c34 | C++ | Patrick-Gemmell/ICS3U-Assignement4-CPP | /package.cpp | UTF-8 | 2,008 | 3.59375 | 4 | [] | no_license | // Copyright (c) 2019 Patrick Gemmell All rights reserved.
//
// Created by: Patrick Gemmell
// Created on: September 2019
// This Program sees if a package can be processed
#include <iostream>
#include <cstdlib>
#include <string>
int main() {
// This function sees if a package can be processed
// variables and constants
const float WEIGHT = 27;
const float SIZE = 10000;
std::string weightAsString;
std::string lengthAsString;
std::string widthAsString;
std::string heightAsString;
int weightAsInt = 0;
int lengthAsInt = 0;
int widthAsInt = 0;
int heightAsInt = 0;
int volume = 0;
while (true) {
// inputs
std::cout << "Input the weight: ";
std::cin >> weightAsString;
try {
weightAsInt = std::stoi(weightAsString);
// process and output
if (weightAsInt > WEIGHT) {
std::cout << "Your package cannot be processed as the maximum \
weight is 27 kg, and yours is " << weightAsInt << std::endl;
continue;
} else {
std::cout << "input length: ";
std::cin >> lengthAsString;
lengthAsInt = std::stoi(lengthAsString);
std::cout << "input width: ";
std::cin >> widthAsString;
widthAsInt = std::stoi(widthAsString);
std::cout << "input height";
std::cin >> heightAsString;
heightAsInt = std::stoi(heightAsString);
volume = heightAsInt * widthAsInt * lengthAsInt;
}
if (volume > SIZE) {
std::cout << "Your package cannot be processed as the maximum \
volume is 10, 000cm^3, but yours is " << volume << std::endl;
} else {
std::cout << "Your package can be processed" << std::endl;
break;
}
} catch (std::invalid_argument) {
std::cout << "invalid integer" << std::endl;
}
}
}
| true |
14f17f2f96a8f6cda19e277af0792e26a86a82b5 | C++ | Charleo85/uvaicpc | /code/2006/routing.cpp | UTF-8 | 4,840 | 3.265625 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
// several constraints, defined by the problem statements
const int MaxN = 100;
const int Max = 1000;
// dis[x][y] is the shortest path from x to y, tr[] is the segment tree, used
// for getting the smallest answer and book-keeping when answer is updated,
// ans[x][y] means there are at least this many nodes in paths 1->x and 1->y
int dis[MaxN][MaxN], tr[MaxN * MaxN * 3], ans[MaxN][MaxN];
// other necessary global variables for this program
int Cases, n, m, i, j, k, x, y;
// from the root node n and its corresponding interval, set all values to Max
// in the segment tree
void Make(int n, int x, int y) {
tr[n] = Max;
if (x == y) return;
Make(n + n, x, (x + y) / 2);
Make(n + n + 1, (x + y) / 2 + 1, y);
}
// from the root node n, update node ch's value to data and book-keeping
void Change(int n, int x, int y, int ch, int data) {
if (x == y) {
tr[n] = data;
} else if ((x+y) / 2 >= ch) {
Change(n + n, x, (x + y) / 2, ch, data);
if (tr[n+n] < tr[n+n+1]) tr[n] = tr[n + n];
else tr[n] = tr[n + n + 1];
} else {
Change(n + n + 1, (x + y) / 2 + 1, y, ch, data);
if (tr[n+n] < tr[n+n+1]) tr[n] = tr[n + n];
else tr[n] = tr[n + n + 1];
}
}
// get the position of the min value in the segment tree
int Get_Min(int n, int x, int y) {
if (x == y) return x;
if (tr[n+n] < tr[n+n+1]) return Get_Min(n + n, x, (x + y) / 2);
else return Get_Min(n + n + 1, (x + y) / 2 + 1, y);
}
int main() {
Cases = 0;
while (scanf("%d %d", &n, &m) && n) {
// initialize the shortest path lengths, arrays index is 0..(n-1)
for (i = 0; i < n; i++) for (j = 0; j < n; j++) dis[i][j] = Max;
// construct the adjacency matrix
for (i = 0; i < m; i++) {
scanf("%d %d", &x, &y); dis[x - 1][y - 1] = 1;
}
// any shortest path length from and to the same node is 0
for (i = 0; i < n; i++) dis[i][i] = 0;
// use floyd-warshall algorithm to compute the shortest path length
// for any pair of nodes
for (k = 0; k < n; k++)
for (i = 0; i < n; i++) for (j = 0; j < n; j++)
if (dis[i][j] > dis[i][k] + dis[k][j])
dis[i][j] = dis[i][k] + dis[k][j];
// initialize the segment tree and change the value of first index
Make(1, 0, n * n - 1);
Change(1, 0, n * n - 1, 0, 1);
// ans[0][0] = 1other values of ans[][] on the diagonal should be Max
for (i = 0; i < n; i++) for (j = 0; j < n; j++) ans[i][j] = Max;
ans[0][0] = 1;
while (tr[1] < Max) {
// get the interval corresponding to the min value in the tree
x = Get_Min(1, 0, n * n - 1);
y = x % n; x /= n;
// case 3: x and y are all repeated points, then exit the loop
if (x == 1 && y == 1) break;
if (x != y && ans[y][x] <= Max &&
ans[x][y] + dis[x][y] - 1 < ans[y][x])
{
ans[y][x] = ans[x][y] + dis[x][y] - 1;
Change(1, 0, n * n - 1, y * n + x, ans[y][x]);
}
// iterate over all points in the interval [x, y], not equal
for (i = 0; i < n; i++) if (i != x && i != y) {
// case 1: the next point of x is not repeated
if (dis[x][i] == 1 && ans[i][y] <= Max &&
ans[x][y] + 1 < ans[i][y])
{
ans[i][y] = ans[x][y] + 1;
Change(1, 0, n * n - 1, i * n + y, ans[i][y]);
}
// case 2: the previous point of y is not repeated
if (dis[i][y] == 1 && ans[x][i] <= Max &&
ans[x][y] + 1 < ans[x][i])
{
ans[x][i] = ans[x][y] + 1;
Change(1, 0, n * n - 1, x * n + i, ans[x][i]);
}
}
// case 4: x is repeated and is also the previous point of y
if (dis[x][y] == 1 && ans[y][y] <= Max && ans[x][y] < ans[y][y]) {
ans[y][y] = ans[x][y];
Change(1, 0, n * n - 1, y * n + y, ans[x][y]);
}
// case 5: y is repeated and is also the next point of x
if (dis[x][y] == 1 && ans[x][x] <= Max && ans[x][y] < ans[x][x]) {
ans[x][x] = ans[x][y];
Change(1, 0, n * n - 1, x * n + x, ans[x][y]);
}
// mark the values of ans already used in the recursion
ans[x][y] = Max + 1;
Change(1, 0, n * n - 1, x * n + y, ans[x][y]);
}
printf("Network %d\n", ++Cases);
if (ans[1][1] == Max) printf("Impossible\n\n");
else printf("Minimum number of nodes = %d\n\n", ans[1][1]);
}
return 0;
}
| true |
7dfbef2fa2d88080685dbbd2493bf028dc032a50 | C++ | Masters-Akt/CS_codes | /leetcode_sol/1315-Sum_Of_Nodes_With_Even-Valued_Grandparent.cpp | UTF-8 | 1,835 | 3.625 | 4 | [] | no_license | //Method 1
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
void solve(TreeNode* root, int& ans){
if(root==NULL) return;
if(root->val%2==0){
if(root->left){
if(root->left->left) ans+=root->left->left->val;
if(root->left->right) ans+=root->left->right->val;
}
if(root->right){
if(root->right->left) ans+=root->right->left->val;
if(root->right->right) ans+=root->right->right->val;
}
}
solve(root->left, ans);
solve(root->right, ans);
}
public:
int sumEvenGrandparent(TreeNode* root) {
if(root==NULL) return 0;
int ans = 0;
solve(root, ans);
return ans;
}
};
//Method 2
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int sumEvenGrandparent(TreeNode* root, int parent=-1, int grandparent=-1) {
if(!root) return 0;
int ans = 0;
ans+=sumEvenGrandparent(root->left, root->val, parent);
ans+=sumEvenGrandparent(root->right, root->val, parent);
if(grandparent!=-1 && !(grandparent&1)) ans+=root->val;
return ans;
}
}; | true |
b4c1bb1dd2bd37e7193dc797b16205c040475b56 | C++ | cyro809/tep-trabalhos | /transportationsystem.cpp | UTF-8 | 3,292 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <math.h>
#include <algorithm>
#include <stdio.h>
#include <string>
#include <utility>
#include <fstream>
#include <sstream>
#include <map>
#include <queue>
#include <functional>
using namespace std;
vector<pair<pair<int,int>, double> > mapping;
vector<pair<int,int> > coord;
int *id;
int* ranking;
int counter;
int Find(int x){
int root = x;
while(root != id[root]){
root = id[root];
}
while(x != root){
int newx = id[x];
id[x] = root;
x = newx;
}
return x;
}
void Union(int &x, int &y){
int i = Find(x);
int j = Find(y);
if(i == j){
return;
}
if(ranking[i] < ranking[j]){
id[i] = j;
ranking[j] += ranking[i];
}
else {
id[j] = i;
ranking[i] += ranking[j];
if(ranking[i] == ranking[j]) ranking[j]++;
}
counter--;
}
void kruskal(){
}
struct sort_pred {
bool operator()(const std::pair<pair<int,int>,double> &left, const std::pair<pair<int,int>, double> &right) {
return left.second < right.second;
}
};
int main()
{
int test_cases;
int n, m;
int x, y;
double ans;
double roads, railroads;
int states;
cin>>test_cases;
for(int t=0;t<test_cases;t++){
ans = 0.0;
states = 1;
cin>>m>>n;
id = new int[m];
ranking = new int[m];
counter = m;
for(int i=0;i<m;i++){
cin>>x>>y;
coord.push_back(pair<int,int>(x,y));
id[i] = i;
ranking[i] = 0;
}
for(int i=0;i<m;i++){
for(int j=i+1;j<m;j++){
// cout<<"c[i].first = "<<coord[i].first<<" c[j].first = "<<coord[j].first<<endl;
// cout<<"c[i].second = "<<coord[i].second<<" c[j].second = "<<coord[j].second<<endl;
int dx = abs(coord[i].first-coord[j].first);
int dy = abs(coord[i].second-coord[j].second);
// cout<<"dx = "<<dx<<" dy = "<<dy<<endl;
double distance = sqrt(dx*dx + dy*dy);
//distance = round(distance);
// cout<<"distance = "<<distance<<endl;
mapping.push_back(pair<pair<int,int>, double>(pair<int,int>(i,j), distance));
}
}
std::sort(mapping.begin(), mapping.end(), sort_pred());
roads = 0.0;
railroads = 0.0;
for(int i=0;i<mapping.size();i++){
int u = mapping[i].first.first;
int v = mapping[i].first.second;
// cout<<"u = "<<u<<" v = "<<v<<endl;
// cout<<"counter = "<<counter<<endl;
if(Find(u) != Find(v)){
Union(u,v);
ans = mapping[i].second;
if(ans > n){
railroads += ans;
states++;
}
else{
roads += ans;
}
//cout<<"map[i] = "<<ans<<endl;
}
}
railroads = round(railroads);
roads = round(roads);
cout<<"Case #"<<t+1<<": "<<states<<" "<<roads<<" "<<railroads<<endl;
delete[] id;
delete[] ranking;
mapping.clear();
coord.clear();
}
return 0;
}
| true |
07ae3bf6ccf099a6e41af2cea7162cb86e4be4f9 | C++ | Pieloaf/dijkstras-algorithm-cpp | /source/dijkstra.cpp | UTF-8 | 3,420 | 3.1875 | 3 | [] | no_license | #include "../header/dijkstra.hpp"
Node* closestNode(map<Node*, int>* dist, vector<Node*>* unvisited) {
//initialising closest node to the first in list of unvisted nodes
pair<Node*, int> min = *dist->find(unvisited->at(0));
//comapring current closest node with each unvisited nodes and updating as needed
for (vector<Node*>::iterator itr = unvisited->begin();
itr != unvisited->end(); itr++)
{
if (min.second > dist->find(*itr)->second) {
min = *dist->find(*itr);
}
}
return min.first;
}
//Dijkstra's shortest path algorithm
pair<stack<Node*>*,int> dijkstra(map<char, Node*>* graph, char start, char end, int limit) {
vector<Node*> unvisited;
map<Node*, int> nodeDist;
map<Node*, Node*> prevNode;
stack<Node*>* path = new stack<Node*>;
pair<stack<Node*>*, int> result (path, 0);
Node* current;
//getting Node objects for the start and end (specified in the input)
Node* source = graph->at(start);
Node* target = graph->at(end);
//occupy the vector of unvisted nodes with all nodes in graph
for (map<char, Node*>::iterator itr = graph->begin();
itr != graph->end(); itr++) {
//set inital distance to infinity i.e. very large number
//used max short because using max int would overflow on addition
nodeDist.insert(pair<Node*, int>(itr->second, numeric_limits<short>::max()));
unvisited.push_back(itr->second);
}
//setting distance from source to source = 0
nodeDist.at(source) = 0;
//do until all nodes have been visited
while (unvisited.size() != 0) {
//setting the current node as closest, unvisted, node to the source
current = closestNode(&nodeDist, &unvisited);
//remove current node from unvisted
unvisited.erase(find(unvisited.begin(), unvisited.end(), current));
//for all nodes adjacent to current that have not yet been visited
for (map<Node*, int>::iterator itr = current->adj.begin(); itr != current->adj.end(); itr++)
{
if (find(unvisited.begin(), unvisited.end(), itr->first) != unvisited.end()) {
//if alternative route through the current node is shorter
//update the previous node
int altRoute = nodeDist.at(current) + itr->second;
if (altRoute < nodeDist.at(itr->first)) {
nodeDist.at(itr->first) = altRoute;
if (prevNode.find(itr->first) == prevNode.end()) {
prevNode.insert(pair<Node*, Node*>(itr->first, current));
}
else prevNode.at(itr->first) = current;
}
}
}
} //TODO: keep track of multiple shortest paths
for (pair<Node*, int> p : nodeDist) {
if (p.second == numeric_limits<short>::max()) {
logError(E2);
return result;
}
}
//if no path under the limit could be found produce error
//else add each node to a stack
if (nodeDist.find(target)->second > limit){
logError(E3);
}
else {
current = target;
result.second = nodeDist.at(target);
while (current != source) {
path->push(current);
current = prevNode.at(current);
}
path->push(current);
result.first = path;
}
return result;
} | true |
943dff7ac848750e55c09669b27c7f6ca5549a2e | C++ | BryanWheeler/ucd-csci2312-pa5 | /Agent.cpp | UTF-8 | 1,557 | 2.921875 | 3 | [] | no_license |
#include "Agent.h"
#include "Resource.h"
const double Gaming::Agent::AGENT_FATIGUE_RATE = 0.3;
void Gaming::Agent::age() {
if(this->__energy <= 0.000001){
this->__energy = 0.0;
this->finish();
}
else {
this->__energy -= AGENT_FATIGUE_RATE;
}
}
//No Default constructor so higher Class constructor used
Gaming::Agent::Agent(const Gaming::Game &g, const Gaming::Position &p, double energy)
:Piece(g, p)
{
this->__energy = energy;
}
Gaming::Piece &Gaming::Agent::operator*(Gaming::Piece &other) {
if(other.getType() == SIMPLE || other.getType() == STRATEGIC){
return this->interact(dynamic_cast<Agent *>(&other));
}
else if(other.getType() == ADVANTAGE || other.getType() == FOOD){
return this->interact(dynamic_cast<Resource *>(&other));
}
return *this;
}
Gaming::Piece &Gaming::Agent::interact(Gaming::Agent *agent) {
if(this->__energy < agent->__energy){
agent->__energy -= this->__energy;
this->__energy = 0;
this->finish();
return * agent;
}
else if(agent->__energy < this->__energy){
this->__energy -= agent->__energy;
agent->__energy = 0;
agent->finish();
return * this;
}
else{
this->__energy = 0;
this->finish();
agent->__energy = 0;
agent->finish();
return * this;
}
}
Gaming::Piece &Gaming::Agent::interact(Gaming::Resource *resource) {
this->__energy += resource->consume();
return * this;
}
Gaming::Agent::~Agent() {
}
| true |
60a747c7ff35296f6e63da32eca873cabb1298a2 | C++ | WarfareCode/mixr | /include/mixr/instruments/dials/AnalogDial.hpp | UTF-8 | 2,608 | 2.671875 | 3 | [] | no_license |
#ifndef __mixr_instruments_AnalogDial_HPP__
#define __mixr_instruments_AnalogDial_HPP__
#include "mixr/instruments/Instrument.hpp"
namespace mixr {
namespace base { class Boolean; class Integer; class Number; }
namespace instruments {
//------------------------------------------------------------------------------
// Class: AnalogDial
//
// Description: Used as a parent class for other dials, it will draw a background
// that can be visible or not, depending on a flag. It can also rotate according
// to a scale, or it can be fixed. This is a generic intelligent background
// that will also pass along instrument values down to its components.
//
// Inputs:
// UPDATE_INSTRUMENTS -> (from instrument), sets our rotation angle
// UPDATE_VALUE -> setRadius (inches)
//------------------------------------------------------------------------------
class AnalogDial : public Instrument
{
DECLARE_SUBCLASS(AnalogDial, Instrument)
public:
AnalogDial();
virtual bool setOriginAngle(const double);
virtual bool setSweepAngle(const double);
virtual bool setRadius(const double);
virtual bool setMobile(const bool);
virtual bool setSlices(const int);
// here are the get functions
double getStartAngle() const { return originAngle; }
double getSweepAngle() const { return sweepAngle; }
bool getMobile() const { return isMobile; }
double getRadius() const { return radius; }
int getSlices() const { return slices; }
void drawFunc() override;
bool event(const int event, base::Object* const obj = nullptr) override;
protected:
// event function
virtual bool onUpdateRadius(const base::Number* const);
private:
double originAngle {}; // angle we start drawing ticks from (degrees, default is 0)
double positionAngle {}; // our position (if we are being rotated)
double sweepAngle {360}; // how far around the circle we sweep
double radius {}; // radius of our background
bool isMobile {}; // are we moving around on the dial, or just sending the value down (to our components)
int slices {1000}; // number of slices to use while drawing
private:
// slot table helper methods
bool setSlotOriginAngle(const base::Number* const);
bool setSlotMobile(const base::Boolean* const);
bool setSlotSweepAngle(const base::Number* const);
bool setSlotRadius(const base::Number* const);
bool setSlotSlices(const base::Integer* const);
};
}
}
#endif
| true |
96c194b0f13544c1c9177f9b13f5849d960e19c5 | C++ | BebeShen/NCKU_Course-Competitive-Programming-2021 | /HW4/longest naps/newl.cpp | UTF-8 | 1,457 | 2.640625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main(){
std::ios_base::sync_with_stdio(false);
std::cin.tie(NULL);
int s;
int test_case = 1;
while(cin>>s){
vector<bool>schedule_empty(481,true);
schedule_empty[480] = false;
for(int i=0;i<s;++i){
int h1,h2,m1,m2;
char skip;
string s;
cin>>h1>>skip>>m1>>h2>>skip>>m2;
getline(cin,s);
for(int j=(h1-10)*60 + m1;j<(h2-10)*60 + m2;++j){
schedule_empty[j] = false;
}
}
int tcount, max_period = -1, max_start;
if(schedule_empty[0])tcount = 1;
else tcount = 0;
for(int i=1;i<481;++i){
if(schedule_empty[i-1]&&schedule_empty[i])tcount++;
if((!schedule_empty[i-1]) && schedule_empty[i])tcount=1;
if(schedule_empty[i-1]&& (!schedule_empty[i])){
if(max_period < tcount){
max_period = tcount;
max_start = i - max_period;
}
}
}
cout<<"Day #"<<test_case++<<": the longest nap starts at "<<10 + max_start/60<<":"<<setw(2) << setfill('0')<<max_start%60<<" and will last for ";
if(max_period>=60)
cout<<to_string(max_period/60)<<" hours and " << to_string(max_period%60) << " minutes.\n";
else
cout<<to_string(max_period%60) << " minutes.\n";
}
return 0;
} | true |
f397ed8d923a1eb1f1ef3d85ba77832ab3891c86 | C++ | lorderikstark0/codechef | /beginner/flow010.cpp | UTF-8 | 569 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
#define pb push_back
#define ll long long
#define forit(it,a) for(_typeof(a.begin()) it =a.begin();it!=a.end();it++)
#define mp make_apir
using namespace std;
string ship(char c){
string s;
if(c=='B'|| c=='b'){
s= "BattleShip";
}
else if(c=='C'|| c=='c'){
s= "Cruiser";
}
else if(c=='D'||c=='d'){
s= "Destroyer";
}
else if(c=='F'||c=='f'){
s= "Frigate";
}
return s;
}
int main(){
int t;
cin >> t;
while(t--){
char c;
cin >> c;
cout << ship(c)<<"\n";
}
return 0;
} | true |
b2300414f422a164e3a29143756b5ac20f3e0589 | C++ | spockwangs/wsd | /test/url_test.cc | UTF-8 | 10,740 | 2.671875 | 3 | [] | no_license | #include "url.h"
#include "gtest/gtest.h"
#define NMEM(array) (sizeof(array) / sizeof(array[0]))
struct UrlCase {
const char *input;
bool is_valid;
const char *scheme;
const char *username;
const char *password;
const char *host;
int port;
const char *path;
const char *query;
const char *ref;
const char *canon_url;
};
TEST(Url, parse)
{
UrlCase cases[] = {
// URL IsValid scheme username password host port path query
// ref Canon URL
// ------------------------------------- ------- ------- -------- -------- ---- ---- ---- -----
// ----- -----------------------------------
{"http://user:pass@foo:21/bar;par?b#c", true, "http", "user", "pass", "foo", 21, "/bar;par", "b", "c",
"http://user:pass@foo:21/bar;par?b#c"},
{"Http://user:pass@foo:21/bar;par?b#", true, "http", "user", "pass", "foo", 21, "/bar;par", "b", "",
"http://user:pass@foo:21/bar;par?b#"},
{"HTTP://user:pass@foo:21/bar;par?b", true, "http", "user", "pass", "foo", 21, "/bar;par", "b", NULL,
"http://user:pass@foo:21/bar;par?b"},
{"http://user:pass@foo:21/bar;par?", true, "http", "user", "pass", "foo", 21, "/bar;par", "", NULL,
"http://user:pass@foo:21/bar;par?"},
{"http://user:pass@foo:21/bar;par?#c", true, "http", "user", "pass", "foo", 21, "/bar;par", "", "c",
"http://user:pass@foo:21/bar;par?#c"},
{"http://user:pass@foo:21/bar;par#c", true, "http", "user", "pass", "foo", 21, "/bar;par", NULL, "c",
"http://user:pass@foo:21/bar;par#c"},
{"http://user:pass@foo:21/bar;par", true, "http", "user", "pass", "foo", 21, "/bar;par", NULL, NULL,
"http://user:pass@foo:21/bar;par"},
{"http://user:pass@foo:21/bar;par", true, "http", "user", "pass", "foo", 21, "/bar;par", NULL, NULL,
"http://user:pass@foo:21/bar;par"},
{"http://user:pass@foo:21/", true, "http", "user", "pass", "foo", 21, "/", NULL, NULL,
"http://user:pass@foo:21/"},
{"http://user:pass@foo:21", true, "http", "user", "pass", "foo", 21, "/", NULL, NULL,
"http://user:pass@foo:21/"},
{"http://user:pass@foo:21/?b", true, "http", "user", "pass", "foo", 21, "/", "b", NULL,
"http://user:pass@foo:21/?b"},
{"http://user:pass@foo:21/?", true, "http", "user", "pass", "foo", 21, "/", "", NULL,
"http://user:pass@foo:21/?"},
{"http://user:pass@foo:21/?#", true, "http", "user", "pass", "foo", 21, "/", "", "",
"http://user:pass@foo:21/?#"},
{"http://user:pass@foo:21/#", true, "http", "user", "pass", "foo", 21, "/", NULL, "",
"http://user:pass@foo:21/#"},
{"http://user:@foo:21/", true, "http", "user", "", "foo", 21, "/", NULL, NULL, "http://user:@foo:21/"},
{"http://user@foo:21/", true, "http", "user", NULL, "foo", 21, "/", NULL, NULL, "http://user@foo:21/"},
{"http://user::p@foo:21/", true, "http", "user", ":p", "foo", 21, "/", NULL, NULL,
"http://user::p@foo:21/"},
{"http://user::p@@foo:21/", true, "http", "user", ":p@", "foo", 21, "/", NULL, NULL,
"http://user::p@@foo:21/"},
{"http://user::p@@:foo:21/", true, "http", "user", ":p@", ":foo", 21, "/", NULL, NULL,
"http://user::p@@:foo:21/"},
{"http://user::p@@:foo:21//", true, "http", "user", ":p@", ":foo", 21, "/", NULL, NULL,
"http://user::p@@:foo:21/"},
{"http:user::p@@:foo:21//??##", true, "http", "user", ":p@", ":foo", 21, "/", "?", "#",
"http://user::p@@:foo:21/??##"},
{"http:user::p@@:foo:21/?/??##", true, "http", "user", ":p@", ":foo", 21, "/", "/??", "#",
"http://user::p@@:foo:21/?/??##"},
{"http://@foo:21/", true, "http", "", NULL, "foo", 21, "/", NULL, NULL, "http://@foo:21/"},
{"http://:@foo:21/", true, "http", "", "", "foo", 21, "/", NULL, NULL, "http://:@foo:21/"},
{"http://foo:21/", true, "http", NULL, NULL, "foo", 21, "/", NULL, NULL, "http://foo:21/"},
{"http://foo:/", true, "http", NULL, NULL, "foo", -1, "/", NULL, NULL, "http://foo/"},
{"http://foo/", true, "http", NULL, NULL, "foo", -1, "/", NULL, NULL, "http://foo/"},
{"http:///", false, "http", NULL, NULL, NULL, -1, NULL, NULL, NULL, "http:"},
{":///foo/", false, "", NULL, NULL, "foo", -1, "/", NULL, NULL, "://foo/"},
{"///foo/", false, NULL, NULL, NULL, "foo", -1, "/", NULL, NULL, "foo/"},
{"foo/", false, NULL, NULL, NULL, "foo", -1, "/", NULL, NULL, "foo/"},
// Creative URLs missing key elements
{"", false, NULL, NULL, NULL, NULL, -1, NULL, NULL, NULL, ""},
{" \t", false, NULL, NULL, NULL, NULL, -1, NULL, NULL, NULL, ""},
{":foo.com/", false, "", NULL, NULL, "foo.com", -1, "/", NULL, NULL, "://foo.com/"},
{":", false, "", NULL, NULL, NULL, -1, NULL, NULL, NULL, ":"},
{":a", false, "", NULL, NULL, "a", -1, "/", NULL, NULL, "://a/"},
{":/", false, "", NULL, NULL, NULL, -1, NULL, NULL, NULL, ":"},
{":#", false, "", NULL, NULL, NULL, -1, "/", NULL, "", ":/#"},
{"#", false, NULL, NULL, NULL, NULL, -1, "/", NULL, "", "/#"},
{"#/", false, NULL, NULL, NULL, NULL, -1, "/", NULL, "/", "/#/"},
{"#\\", false, NULL, NULL, NULL, NULL, -1, "/", NULL, "\\", "/#\\"},
{"#;?", false, NULL, NULL, NULL, NULL, -1, "/", NULL, ";?", "/#;?"},
{"?", false, NULL, NULL, NULL, NULL, -1, "/", "", NULL, "/?"},
{"/", false, NULL, NULL, NULL, NULL, -1, NULL, NULL, NULL, ""},
{":23", false, "", NULL, NULL, "23", -1, "/", NULL, NULL, "://23/"},
{"/:23", true, "/", NULL, NULL, "23", -1, "/", NULL, NULL, "/://23/"},
{"//", false, NULL, NULL, NULL, NULL, -1, NULL, NULL, NULL, ""},
{"::", false, "", NULL, NULL, NULL, -1, "/", NULL, NULL, ":///"},
{"::23", false, "", NULL, NULL, NULL, 23, "/", NULL, NULL, "://:23/"},
{"foo://", false, "foo", NULL, NULL, NULL, -1, NULL, NULL, NULL, "foo:"},
// Username/passwords
{"http://a:b@c:29/d", true, "http", "a", "b", "c", 29, "/d", NULL, NULL, "http://a:b@c:29/d"},
{"http::@c:29", true, "http", "", "", "c", 29, "/", NULL, NULL, "http://:@c:29/"},
{"http://&a:foo(b]c@d:2/", true, "http", "&a", "foo(b]c", "d", 2, "/", NULL, NULL,
"http://&a:foo(b]c@d:2/"},
{"http://::@c@d:2", true, "http", "", ":@c", "d", 2, "/", NULL, NULL, "http://::@c@d:2/"},
{"http://foo.com:b@d/", true, "http", "foo.com", "b", "d", -1, "/", NULL, NULL, "http://foo.com:b@d/"},
// Use the first question mark for the query and the ref.
{"http://foo/path;a??e#f#g", true, "http", NULL, NULL, "foo", -1, "/path;a", "?e", "f#g",
"http://foo/path;a??e#f#g"},
{"http://foo/abcd?efgh?ijkl", true, "http", NULL, NULL, "foo", -1, "/abcd", "efgh?ijkl", NULL,
"http://foo/abcd?efgh?ijkl"},
{"http://foo/abcd#foo?bar", true, "http", NULL, NULL, "foo", -1, "/abcd", NULL, "foo?bar",
"http://foo/abcd#foo?bar"},
// IPv6, check also interesting uses of colons.
{"[61:24:74]:98", true, "[61", NULL, NULL, "24:74]", 98, "/", NULL, NULL, "[61://24:74]:98/"},
{"http://[61:27]:98", true, "http", NULL, NULL, "[61:27]", 98, "/", NULL, NULL, "http://[61:27]:98/"},
{"http:[61:27]/:foo", true, "http", NULL, NULL, "[61:27]", -1, "/:foo", NULL, NULL, "http://[61:27]/:foo"},
{"http://[1::2]:3:4", true, "http", NULL, NULL, "[1::2]:3", 4, "/", NULL, NULL, "http://[1::2]:3:4/"},
{"http://2001::1", true, "http", NULL, NULL, "2001:", 1, "/", NULL, NULL, "http://2001::1/"},
{"http://[2001::1", true, "http", NULL, NULL, "[2001::1", -1, "/", NULL, NULL, "http://[2001::1/"},
{"http://2001::1]", true, "http", NULL, NULL, "2001::1]", -1, "/", NULL, NULL, "http://2001::1]/"},
{"http://[[::]]", true, "http", NULL, NULL, "[[::]]", -1, "/", NULL, NULL, "http://[[::]]/"},
// Path canonicalization.
{"http://foo.com///./a/b/..//c/d/../../e", true, "http", NULL, NULL, "foo.com", -1, "/a/e", NULL, NULL,
"http://foo.com/a/e"},
{"http://foo.com///./../a/../../c/d/../e", true, "http", NULL, NULL, "foo.com", -1, "/c/e", NULL, NULL,
"http://foo.com/c/e"},
{"http://foo.com///./../a/../../c/d/.../e", true, "http", NULL, NULL, "foo.com", -1, "/c/d/.../e", NULL,
NULL, "http://foo.com/c/d/.../e"},
};
for (size_t i = 0; i < NMEM(cases); i++) {
wsd::Url url(cases[i].input);
EXPECT_EQ(cases[i].is_valid, url.isValid()) << "url=" << cases[i].input;
if (cases[i].scheme)
EXPECT_EQ(cases[i].scheme, url.getScheme());
else
EXPECT_FALSE(url.hasScheme()) << "url=" << cases[i].input;
if (cases[i].username)
EXPECT_EQ(cases[i].username, url.getUsername()) << "url=" << cases[i].input;
else
EXPECT_FALSE(url.hasUsername()) << "url=" << cases[i].input;
if (cases[i].password)
EXPECT_EQ(cases[i].password, url.getPassword()) << "url=" << cases[i].input;
else
EXPECT_FALSE(url.hasPassword()) << "url=" << cases[i].input;
if (cases[i].host)
EXPECT_EQ(cases[i].host, url.getHost()) << "url=" << cases[i].input;
else
EXPECT_FALSE(url.hasHost()) << "url=" << cases[i].input;
if (cases[i].port)
EXPECT_EQ(cases[i].port, url.getIntPort()) << "url=" << cases[i].input;
else
EXPECT_FALSE(url.hasPort()) << "url=" << cases[i].input;
if (cases[i].path)
EXPECT_EQ(cases[i].path, url.getPath()) << "url=" << cases[i].input;
else
EXPECT_FALSE(url.hasPath()) << "url=" << cases[i].input;
if (cases[i].query)
EXPECT_EQ(cases[i].query, url.getQuery()) << "url=" << cases[i].input;
else
EXPECT_FALSE(url.hasQuery()) << "url=" << cases[i].input;
if (cases[i].ref)
EXPECT_EQ(cases[i].ref, url.getRef()) << "url=" << cases[i].input;
else
EXPECT_FALSE(url.hasRef()) << "url=" << cases[i].input;
EXPECT_EQ(cases[i].canon_url, url.getCanonUrl());
}
}
| true |
aa5a0ca27828c1894d488028515d0c1089dfa43b | C++ | AlexKreu/MCMC | /Rand.h | UTF-8 | 1,575 | 2.78125 | 3 | [] | no_license | #ifndef RAND_H
#define RAND_H
#include <Eigen/Dense>
#include <boost/random/uniform_real.hpp>
#include <boost/random/variate_generator.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/normal_distribution.hpp>
static const Eigen::VectorXd zero_vec = Eigen::VectorXd::Zero(1);
static const Eigen::MatrixXd one_mat = Eigen::MatrixXd::Ones(1, 1);
class Rand
{
typedef boost::mt19937 RGEN; // random number generator
typedef boost::normal_distribution<double> NDIST; // Normal distribution
typedef boost::variate_generator<RGEN&, NDIST> NGEN; // Normal distribution generator
typedef boost::uniform_real<double> UNIF; // Uniform distribution
typedef boost::variate_generator<RGEN&, UNIF> UGEN; //Uniform distribution generator
private:
RGEN m_randgen;
NDIST m_sndist;
NGEN m_sngen;
UNIF m_unif;
UGEN m_ugen;
public:
Rand(int seed = 123) : m_randgen(RGEN(seed)), m_sndist(NDIST(0, 1)), m_sngen(m_randgen, m_sndist), m_unif(UNIF(0, 1)), m_ugen(m_randgen, m_unif)
{};
void set_seed(int seed)
{
m_randgen = RGEN(seed);
}
double unif()
{
return m_ugen();
}
Eigen::VectorXd n(const Eigen::MatrixXd& mu = zero_vec, const Eigen::MatrixXd& sigma = one_mat)
{
return mu + sigma * m_sngen();
}
Eigen::VectorXd mn(const Eigen::VectorXd& meanvec, const Eigen::MatrixXd& covmat)
{
Eigen::VectorXd normals(covmat.cols());
Eigen::LLT<Eigen::MatrixXd> llt(covmat);
for (int i = 0; i < covmat.cols(); ++i)
{
normals(i) = m_sngen();
}
return meanvec + llt.matrixL() * normals;
}
};
#endif
| true |
f4835ff7a03bdc4d3a7f712a28a0b1a609917c24 | C++ | vaidasuope/Cplus_08_10_2020 | /pamoka_su _funkcija.cpp | UTF-8 | 2,132 | 2.59375 | 3 | [] | no_license | #include <iostream>
using namespace std;
void kiekis (string txt, int &kiek);
void ivedimas(string txt, int kiek, int Z[]); //funkcijos prototipas - funkcija kiekimas ir ivedimui pazymiu su masyvu. Skirtingose funkcijose galim naudoti tuos pacius vardus
void isvedimas (string txt, int kiek, int Z[]);
int main()
{
int kiekP, kiekA, kiekM, suma(0), paz, maxPaz, kelintas;
kiekis ("Petras", kiekP);//cia kreipiames i funkcija
int P[kiekP];
ivedimas ("Petro", kiekP, P);
kiekis ("Antanas", kiekA);
int A[kiekA];
ivedimas ("Antano", kiekA, A);
kiekis ("Martynas", kiekM);
int M[kiekM];
ivedimas ("Martyno", kiekM, M);
isvedimas("Petro pazymiai",kiekP,P);
isvedimas("Antano pazymiai",kiekA,A);
isvedimas("Martyno pazymiai",kiekM,M);
//float vid;
/* for(int i=1; i<=kiek; i++)
{
cout<<"iveskite "<<i<<"-aji pazymi ";
cin>>paz;
if(paz>10 or paz<1) {
cout<<"blogas pazymys\n";
i--;
}
else { suma = suma + paz;
if(i == 1 ){maxPaz = paz; kelintas=i;}
else if (maxPaz<=paz){maxPaz = paz; kelintas=i;}
}
}
vid = (float)suma / kiek;
cout <<" petriuko vidurkis "<<vid;
cout<<"\n max ivertinimas "<<kelintas <<" pazimys "<<maxPaz; */
return 0;
}
//------kiekio ivedimas-----
void kiekis (string txt, int &kiek)
//kadangi kieki tures grazinti i programa, tai rasomk pries kintamaji &, parodo, kad grazina i pograma
{
cout<<"Kiek "<<txt<<" turi pazymiu? ";//apsirasem f-ja kuri leidzia ivesti pazymiu kieki
cin>>kiek;
}
//----ivedimas masyvo---//
void ivedimas(string txt, int kiek, int Z[])
{
for(int i=0; i<kiek; i++)
{
cout<<"iveskite "<<txt<<i+1<<"-aji pazymi ";
cin>>Z[i];
if(Z[i]>10 or Z[i]<1) {
cout<<"blogas pazymys\n";
i--;
}
}
}
//--------------------------
//isvedimas
void isvedimas (string txt, int kiek, int Z[])
{
cout<<txt<<endl;
for(int i=0; i<kiek; i++)
{
cout<<Z[i]<<" ";
}
}
//-------------------
| true |
2e5350827d3c2f03600439a464c8acff219e99ab | C++ | ShelbyKS/AlgorithmsTP | /Module2/Algr_DZ2_4/main.cpp | UTF-8 | 5,868 | 3.40625 | 3 | [] | no_license | #include <iostream>
#include <cassert>
template <class T>
struct Node {
T key;
int height;
int count;
Node* left;
Node* right;
Node() {}
Node(T key) : key(key), height(1), count(1), left(nullptr), right(nullptr) {}
~Node() {}
Node(const Node& other): key(other.key), height(other.height), count(other.count),
left(other.left), right(other.right) {}
Node(Node&& other): key(other.key), height(other.height), count(other.count),
left(other.left), right(other.right) {
other.key = 0;
other.height = 0;
other.count = 0;
other.left = nullptr;
other.right = nullptr;
}
Node operator=(const Node& other) {
if (this != &other) {
key = other.key;
height = other.height;
count = other.count;
left = other.left;
right = other.right;
}
return *this;
}
Node operator=(Node&& other) {
if (this != &other) {
key = other.key;
height = other.height;
count = other.count;
left = other.left;
right = other.right;
other.key = 0;
other.height = 0;
other.count = 0;
other.left = nullptr;
other.right = nullptr;
}
return *this;
}
};
template <class T>
class AVLTree {
private:
Node<T>* root;
int height(Node<T>* node) { return node ? node->height : 0; }
int count(Node<T>* node) { return node ? node->count : 0; }
int bFactor(Node<T>* node) { return height(node->right) - height(node->left); }
void fixHeight(Node<T>* node);
Node<T>* rotateLeft(Node<T>* node);
Node<T>* rotateRight(Node<T>* node);
Node<T>* balance(Node<T>* node);
Node<T>* insert(Node<T>* node, T key);
Node<T>* remove(Node<T>* node, T key);
Node<T>* findMax(Node<T>* node);
Node<T>* removeMax(Node<T>* node);
void clear(Node<T>* node) {
if (!node) {
return;
}
clear(node->left);
clear(node->right);
delete node;
}
public:
AVLTree() {root = nullptr; }
~AVLTree() { clear(root); }
Node<T>* Add(T key);
Node<T>* Delete(T key);
T KStatistic(int k);
};
template <class T>
void AVLTree<T>::fixHeight(Node<T> *node) {
int heightLeft = height(node->left);
int heightRight = height(node->right);
node->height = (heightLeft > heightRight ? heightLeft : heightRight) + 1;
node->count = node->left ? node->left->count + 1 : 0;
node->count += node->right ? node->right->count + 1 : 0;
}
template <class T>
Node<T>* AVLTree<T>::rotateLeft(Node<T> *node) {
Node<T>* root = node->right;
node->right = root->left;
root->left = node;
fixHeight(node);
fixHeight(root);
return root;
}
template <class T>
Node<T>* AVLTree<T>::rotateRight(Node<T> *node) {
Node<T>* root = node->left;
node->left = root->right;
root->right = node;
fixHeight(node);
fixHeight(root);
return root;
}
template <class T>
Node<T>* AVLTree<T>::balance(Node<T> *node) {
fixHeight(node);
int nodeBFactor = bFactor(node);
if (nodeBFactor == 2) {
if (bFactor(node->right) < 0) {
node->right = rotateRight(node->right);
}
return rotateLeft(node);
}
if (nodeBFactor == -2) {
if (bFactor(node->left) > 0) {
node->left = rotateLeft(node->left);
}
return rotateRight(node);
}
return node;
}
template <class T>
Node<T>* AVLTree<T>::insert(Node<T>* node, T key) {
if (!node) {
return new Node<T>(key);
}
if (key < node->key) {
node->left = insert(node->left, key);
} else {
node->right = insert(node->right, key);
}
return balance(node);
}
template <class T>
Node<T>* AVLTree<T>::Add(T key) {
root = insert(root, key);
}
template <class T>
Node<T>* AVLTree<T>::findMax(Node<T>* node) {
return node->right ? findMax(node->right) : node;
}
template <class T>
Node<T>* AVLTree<T>::removeMax(Node<T> *node) {
if (!node->right) {
return node->left;
}
node->right = removeMax(node->right);
return balance(node);
}
template <class T>
Node<T>* AVLTree<T>::remove(Node<T> *node, T key) {
if (!node) {
return nullptr;
}
if (key < node->key) {
node->left = remove(node->left, key);
} else if (key > node->key) {
node->right = remove(node->right, key);
} else {
Node<T>* left = node->left;
Node<T>* right = node->right;
delete node;
if (!left) {
return right;
}
Node<T>* max = findMax(left);
max->left = removeMax(left);
max->right = right;
return balance(max);
}
return balance(node);
}
template <class T>
Node<T>* AVLTree<T>::Delete(T key) {
root = remove(root, key);
}
template <class T>
T AVLTree<T>::KStatistic(int k) {
assert(root);
Node<T>* node = root;
int kNode = k - 1;
while (kNode != k) {
if (k < kNode) {
node = node->left;
if (!node) {
return node->key;
}
kNode = count(node->left);
} else {
node = node->right;
if (!node) {
return node->key;
}
kNode = count(node->left) - 1;
//k = k -
}
}
return node->key;
}
int main() {
AVLTree<int> avlTree;
int count = 0;
std::cin >> count;
int key = 0;
int k = 0;
for (int i = 0; i < count; i++) {
std::cin >> key >> k;
if (key > 0) {
avlTree.Add(key);
} else {
avlTree.Delete(-key);
}
std::cout << avlTree.KStatistic(k) << ' ';
}
return 0;
} | true |
d3b0612c923649ecbe264087172620bf87125e4d | C++ | v0idkr4ft/algo.vga | /HINTS/BOXGEN.CPP | WINDOWS-1252 | 1,228 | 3.15625 | 3 | [] | no_license | //
// Title : Text box generator
// File : BOXGEN.CPP
// Author : Caglios
// Date : 25-04-97
//
// This procedure generates a box, given the co-ordinates in the procedure
// call. This proc. is stand-alone, it can be cut directly from this file
// and placed into your own program.
//
// Nothing special with the code, but it does need both setpos (or someting
// similar) as well as BoxGen to run.
//
// Stay gravy. \:)<=
//
#include <stdio.h>
void setpos(char x, char y)
{
asm mov dl,x
asm mov dh,y
asm mov ah,02
asm xor bh,bh
asm int 10h
}
void BoxGen(int topx, int topy, int botx, int boty)
{
int width, length;
setpos(topx,topy); printf("");
for (width=topx+1;width<botx;width++)
{
setpos(width,topy);
printf("");
}
setpos(botx,topy); printf("");
for (length=topy+1;length<boty;length++)
{
setpos(topx,length);
printf("");
setpos(botx,length);
printf("");
}
setpos(topx,boty); printf("");
for (width=topx+1;width<botx;width++)
{
setpos(width,boty);
printf("");
}
setpos(botx,boty); printf("");
}
main()
{
BoxGen(5,5,25,20);
return(0);
}
| true |
bdb441b4da0c31cb33c0bb3ef49a2c7a9ca104f4 | C++ | pleomaxmouse/orange | /shared/Vector3F.cpp | UTF-8 | 3,566 | 3.46875 | 3 | [] | no_license | #include <Vector3F.h>
#include <math.h>
Vector3F::Vector3F()
{
x = y = z = 0.f;
}
Vector3F::Vector3F(const float& vx, const float& vy, const float& vz)
{
x = vx;
y = vy;
z = vz;
}
Vector3F::Vector3F(const float* p)
{
x = p[0];
y = p[1];
z = p[2];
}
Vector3F::Vector3F(float* p)
{
x = p[0];
y = p[1];
z = p[2];
}
Vector3F::Vector3F(const Vector3F& from, const Vector3F& to)
{
x = to.x - from.x;
y = to.y - from.y;
z = to.z - from.z;
}
void Vector3F::set(float vx, float vy, float vz)
{
x = vx;
y = vy;
z = vz;
}
void Vector3F::operator+=( const Vector3F& other )
{
x += other.x;
y += other.y;
z += other.z;
}
void Vector3F::operator-=( const Vector3F& other )
{
x -= other.x;
y -= other.y;
z -= other.z;
}
void Vector3F::operator/=( const float& scale )
{
x /= scale;
y /= scale;
z /= scale;
}
void Vector3F::operator*=( const float& scale )
{
x *= scale;
y *= scale;
z *= scale;
}
Vector3F Vector3F::operator*(const float& scale ) const
{
return Vector3F(x*scale,y*scale,z*scale);
}
Vector3F Vector3F::operator/(const float& scale ) const
{
return Vector3F(x/scale,y/scale,z/scale);
}
Vector3F Vector3F::operator*( const Vector3F& other ) const
{
return Vector3F(x*other.x,y* other.y, z* other.z);
}
Vector3F Vector3F::operator+( Vector3F other )
{
return Vector3F(x+other.x, y+other.y, z+other.z);
}
Vector3F Vector3F::operator-( Vector3F other )
{
return Vector3F(x-other.x, y-other.y, z-other.z);
}
Vector3F Vector3F::operator+( Vector3F other ) const
{
return Vector3F(x+other.x, y+other.y, z+other.z);
}
Vector3F Vector3F::operator+(Vector3F& other ) const
{
return Vector3F(x+other.x, y+other.y, z+other.z);
}
Vector3F Vector3F::operator-(Vector3F other ) const
{
return Vector3F(x-other.x, y-other.y, z-other.z);
}
Vector3F Vector3F::operator-(Vector3F& other ) const
{
return Vector3F(x-other.x, y-other.y, z-other.z);
}
float Vector3F::length() const
{
return (float)sqrt(x*x + y*y + z*z);
}
float Vector3F::dot(const Vector3F& other) const
{
return ( x*other.x + y*other.y + z*other.z);
}
Vector3F Vector3F::cross(const Vector3F& other) const
{
return Vector3F(y * other.z - z * other.y, z * other.x - x * other.z, x * other.y - y * other.x);
}
void Vector3F::normalize()
{
float len = length();
if(len > 10e-8)
{
x /= len;
y /= len;
z /= len;
}
else
{
x = y = z = 0.577350f;
}
}
Vector3F Vector3F::normal() const
{
double mag = sqrt( x * x + y * y + z * z ) + 10e-8;
return Vector3F(x /(float)mag, y /(float)mag, z /(float)mag);
}
void Vector3F::reverse()
{
x = -x;
y = -y;
z = -z;
}
Vector3F Vector3F::reversed() const
{
return Vector3F(-x, -y, -z);
}
void Vector3F::rotateAroundAxis(const Vector3F& axis, float theta)
{
if(theta==0) return;
Vector3F ori(x,y,z);
float l = ori.length();
ori.normalize();
Vector3F up = axis.cross(ori);
up.normalize();
Vector3F side = ori - axis*(axis.dot(ori));
up *=side.length();
ori += side*(cos(theta) - 1);
ori += up*sin(theta);
ori.normalize();
x = ori.x*l;
y = ori.y*l;
z = ori.z*l;
}
Vector3F Vector3F::perpendicular() const
{
Vector3F ref(0,1,0);
Vector3F n = normal();
if(n.y < -0.9f || n.y > 0.9f) ref = Vector3F(1,0,0);
Vector3F per = cross(ref);
per.normalize();
return per;
}
| true |
a8563ccac963c675a0dbd8761cd4b617c64d7f1b | C++ | lawinse/AlgorithmExercises | /leetcode/solutions/222.count-complete-tree-nodes/count-complete-tree-nodes.cpp | UTF-8 | 573 | 3.140625 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
typedef TreeNode Node;
public:
int countNodes(TreeNode* root) {
if (!root) return 0;
Node* l = root->left;
Node *r = root->right;
int l1 = 0, l2 = 0;
while(l) l= l->left, ++l1;
while(r) r = r->right, ++l2;
return l1 == l2 ? (2<<l1) - 1 : 1 + countNodes(root->left) + countNodes(root->right);
}
}; | true |
480326ada32b0878dd354fb30d7549821dd28e2f | C++ | Grubbly/CPP-To-PostScript-Library-Refactored | /include/Polygon.h | UTF-8 | 1,251 | 2.703125 | 3 | [] | no_license | /*-------------------------------------------------------
| CS 372: Software Construction |
| Project 2: C++ To PostScript Library |
| Date: 3/20/18 |
| File: polygon.h |
| Written By: Collin Lasley & Tristan Van Cise |
| Description: Header Of Polygon Class |
------------------------------------------------------*/
#include <string>
#include <cmath>
#include "shape.h"
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#ifndef POLYGON_H
#define POLYGON_H
namespace PostLib {
class Polygon : public PostLib::Shape
{
public:
Polygon();
Polygon(PostLib::PostScriptPoint centerPoint, unsigned int numSides, double sideLength);
virtual std::string PostScriptRepresentation() override;
std::string postScript(void) override;
int getNumSides() const;
double getSideLength() const;
private:
int _numSides;
double _sideLength;
PrimitiveRectangle calculatePrimitiveRectangle(int numSides, double sideLength, PostLib::PostScriptPoint centerPoint) const;
};
}
#endif // !POLYGON_H
| true |
3e6eb94f68f29d7a1ec34784357b05a956ec68fe | C++ | rtvt123/bluster_cache | /server/log.cpp | UTF-8 | 1,389 | 2.6875 | 3 | [] | no_license | #include "log.h"
std::ostringstream & Log::get(log_types level) {
LVL_REPORTING = (log_types)LOG_TYPE;
msg_lvl = level;
auto now = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(now);
os << "- " << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d %X");
os << " " << get_enum_str(level) << " ";
return os;
}
Log::~Log() {
if(LVL_REPORTING <= msg_lvl) {
if(CIO_ENABLED) {
std::cout << os.str() << std::endl;
}
if(FIO_FLAG) {
if(msg_lvl >= LWARN) {
auto now = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(now);
std::stringstream file_name;
file_name << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d_%H:%m") << ".log";
std::ofstream fd;
fd.open(file_name.str(), std::ofstream::in | std::ofstream::app);
if(fd.is_open()) {
fd << os.str();
fd.close();
} else {
std::clog << "Can't create log file" << std::endl;
}
}
}
}
}
std::string Log::get_enum_str(log_types n) {
std::string type;
switch(n) {
case LINFO:
type = "INFO";
break;
case LDEBUG:
type = "DEBUG";
break;
case LWARN:
type = "WARNING";
break;
case LERR:
type = "ERROR";
break;
}
return type;
} | true |
61eadf87fe9b8bdb36ea212ce31c9f0fbe2797d1 | C++ | lehmamic/gameprogcpp | /Chapter12/SkeletalMeshComponent.h | UTF-8 | 1,125 | 2.75 | 3 | [] | no_license | //
// SkeletalMeshComponent.hpp
// Game-mac
//
// Created by Michael Lehmann on 27.01.21.
// Copyright © 2021 Sanjay Madhav. All rights reserved.
//
#ifndef SkeletalMeshComponent_hpp
#define SkeletalMeshComponent_hpp
#include "MeshComponent.h"
#include "MatrixPalette.h"
class SkeletalMeshComponent : public MeshComponent
{
public:
SkeletalMeshComponent(class Actor* owner);
// Draw this mesh component
void Draw(class Shader* shader) override;
void Update(float deltaTime) override;
// Setters
void SetSkeleton(const class Skeleton* sk) { mSkeleton = sk; }
// Play an animation. Returns the length of the animation
float PlayAnimation(const class Animation* anim, float playRate = 1.0f);
protected:
void ComputeMatrixPalette();
// Matrix palette
MatrixPalette mPalette;
const class Skeleton* mSkeleton;
// Animation currently playing
const class Animation* mAnimation;
// Play rate of animation (1.0 is normal speed)
float mAnimPlayRate;
// Current time in the animation
float mAnimTime;
};
#endif /* SkeletalMeshComponent_hpp */
| true |
46f4691828b3f78043e8ecc96561fd319369117c | C++ | xymostech/abxy | /abxy/Formatter.cpp | UTF-8 | 470 | 2.953125 | 3 | [] | no_license | #include <abxy/Formatter.hpp>
Formatter &Formatter::operator<<(std::shared_ptr<IFormat> insert) {
formatters.push_back(insert);
return *this;
}
Formatter &Formatter::operator<<(const Formatter &formatter) {
for (auto f : formatter.formatters) {
*this << f;
}
return *this;
}
void Formatter::Clear() {
formatters.clear();
}
std::string Formatter::Format() const {
std::string store;
for (auto f : formatters) {
store += f->Format();
}
return store;
}
| true |
52512bb2bcbdc8f05fd87dbb7b7f2033c0ba20bf | C++ | ankurrai1/cpp-programs | /sum_without_+opreator.cpp | UTF-8 | 146 | 2.59375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int a,b,sum;
a=10;
b=20;
sum=-(-a-b);
cout<<"sum is: "<<sum<<endl;
return 0;
}
| true |
0ce004eba4e5a410d311e0bd57ca768e85690751 | C++ | Jayant-saksham/Coding-blocks-FAANG-course | /Array and Strings/5sunnyBuildings.cpp | UTF-8 | 525 | 2.921875 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
int main(){
int n;
cout<<"Enter n : ";
cin>>n;
int A[n];
for(int i=0;i<n;i++){
cin>>A[i];
}
int maxHeight = 0;
int count = 0;
vector<int>v;
for(int i=0;i<n;i++){
if(A[i]>=maxHeight){
count++;
maxHeight=max(maxHeight, A[i]);
v.push_back(A[i]);
}
}
cout<<"count : "<<count<<endl;
for(int i=0;i<v.size();i++){
cout<<v.at(i)<<" ";
}
return 0;
} | true |
00389ab921c920687b21dae6b8c53a0bd6209303 | C++ | SrMrBurchick/Might-of-the-King | /TheGame/army.hpp | UTF-8 | 1,679 | 3.015625 | 3 | [] | no_license | #ifndef ARMY_HPP
#define ARMY_HPP
#define ARMY_COUNT 6
#include<Windows.h>
#include"Soldier.hpp"
class Army
{
public:
Army(int _count, int _mcount)
: a_count(_count), a_max_count(_mcount)
{
for (int i = 0; i < ARMY_COUNT; i++)
a_army[i] = 0;
}
~Army() = default;
//--------------Getters---------------------------------------------------------------------------------------------------------------------------------------------------------
const int* getInfo() const { return a_army; }
const int getcurrCount() const { return a_count; }
//--------------Setters---------------------------------------------------------------------------------------------------------------------------------------------------------
bool updateArmy(const Soldier);
bool setArmy(const int*);
bool replenishArmy(const Soldier);
void changeMaxCount(int _count) { a_max_count = _count; }
private:
int a_count, a_max_count;
int a_army[ARMY_COUNT];
};
inline bool Army::updateArmy(const Soldier _soilder)
{
a_army[(int)_soilder];
switch (_soilder)
{
case Soldier::soldier:
a_army[(int)Soldier::recruit]--;
break;
case Soldier::knight:
a_army[(int)Soldier::soldier]--;
break;
case Soldier::archer:
a_army[(int)Soldier::soldier]--;
break;
case Soldier::arbalester:
a_army[(int)Soldier::archer]--;
break;
case Soldier::surgeon:
a_army[(int)Soldier::soldier]--;
break;
}
return true;
}
inline bool Army::replenishArmy(const Soldier _soilder)
{
if (a_count <= a_max_count)
{
a_army[(int)_soilder] ++;
a_count ++;
}
else
return false;
return true;
}
#endif // !ARMY_HPP
| true |
466b3299c2fcdefb3bbbb312cb43615ae23fed7c | C++ | 0niel/clipboard-writer | /clipboard_writer/source/cwriter/writer.cpp | WINDOWS-1252 | 4,729 | 2.578125 | 3 | [] | no_license | #include "writer.h"
#include <vector>
#include "../../converters.h"
using namespace std;
void cWriter::PressKeyB(char mK)
{
HKL kbl = GetKeyboardLayout(0);
INPUT ip;
ip.type = INPUT_KEYBOARD;
ip.ki.time = 0;
ip.ki.dwFlags = KEYEVENTF_UNICODE;
if ((int)mK < 65 && (int)mK>90) //for lowercase
{
ip.ki.wScan = 0;
ip.ki.wVk = VkKeyScanEx(mK, kbl);
}
else //for uppercase
{
if ((int)mK > 0) {
ip.ki.wScan = mK;
ip.ki.wVk = 0;
}
}
ip.ki.dwExtraInfo = 0;
SendInput(1, &ip, sizeof(INPUT));
ip.ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP;
SendInput(1, &ip, sizeof(INPUT));
}
void cWriter::PressEnter()
{
INPUT ip;
ip.type = INPUT_KEYBOARD;
ip.ki.time = 0;
ip.ki.dwFlags = KEYEVENTF_UNICODE;
ip.ki.wScan = VK_RETURN; //VK_RETURN is the code of Return key
ip.ki.wVk = 0;
ip.ki.dwExtraInfo = 0;
SendInput(1, &ip, sizeof(INPUT));
ip.ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP;
SendInput(1, &ip, sizeof(INPUT));
}
void cWriter::PressTab()
{
INPUT ip;
ip.type = INPUT_KEYBOARD;
ip.ki.time = 0;
ip.ki.dwFlags = KEYEVENTF_UNICODE;
ip.ki.wScan = VK_TAB; //VK_RETURN is the code of Return key
ip.ki.wVk = 0;
ip.ki.dwExtraInfo = 0;
SendInput(1, &ip, sizeof(INPUT));
ip.ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP;
SendInput(1, &ip, sizeof(INPUT));
}
std::wstring cWriter::GetClipboardText()
{
if (!OpenClipboard(nullptr))
{
CloseClipboard();
return L"";
}
HANDLE hData = GetClipboardData(CF_UNICODETEXT);
if (hData == nullptr)
{
CloseClipboard();
return L"";
}
wchar_t* pszText = static_cast<wchar_t*>(GlobalLock(hData));
if (pszText == nullptr)
{
CloseClipboard();
return L"";
}
wstring text(pszText);
GlobalUnlock(hData);
CloseClipboard();
return text;
}
void cWriter::CheckStartState() {
while (true) {
if ((GetAsyncKeyState(g_Cvars.keyStartWrite) & 0x8000)) {
this->m_isWriting = true;
}
if ((GetAsyncKeyState(g_Cvars.keyStopWrite) & 0x8000)) {
this->m_isWriting = false;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
std::string StringReplacer(const std::string& inputStr, const std::string& src, const std::string& dst)
{
std::string result(inputStr);
size_t pos = result.find(src);
while (pos != std::string::npos) {
result.replace(pos, src.size(), dst);
pos = result.find(src, pos);
}
return result;
}
std::string Normalize(const std::string& inputStr) {
string str1 = StringReplacer(inputStr, " ", "\t");
string str2 = StringReplacer(str1, "", "<");
string str3 = StringReplacer(str2, "", ">>");
string str4 = StringReplacer(str3, "\r\n", "\n");
string str5 = StringReplacer(str4, "\r\r", "\n");
return str5;
}
void cWriter::Start()
{
std::locale system("");
std::locale::global(system);
SetConsoleOutputCP(65001);
setlocale(LC_ALL, "en_US.UTF-8");
srand(time(0));
std::thread keyChecker(&cWriter::CheckStartState, this);
while (true) {
if (m_isWriting) {
int writtenChars = 0;
int maxWritternChars = 0;
wstring clipboardText = GetClipboardText();
string s = UtfConv<std::string>(clipboardText);
s = Normalize(s);
for (int i = 0; i < s.length(); i++)
{
//mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, NULL, NULL, 0, 0);
switch (s[i]) {
case '\n':
PressEnter();
if (g_Cvars.useSmartDelay)
std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 180 + 350));
break;
case '\t':
PressTab();
if (g_Cvars.useSmartDelay)
std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100 + 350));
break;
default:
if (g_Cvars.useSmartDelay) {
if (maxWritternChars == 0) {
maxWritternChars = rand() % 10 + 7;
}
else {
if (writtenChars < maxWritternChars) {
writtenChars++;
std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100 + 50));
}
else {
maxWritternChars = 0;
writtenChars = 0;
std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 200 + 650));
}
}
}
PressKeyB(s[i]);
break;
}
if (!g_Cvars.useSmartDelay) {
if (g_Cvars.userRandomDelay) {
std::this_thread::sleep_for(std::chrono::milliseconds(rand() % g_Cvars.delayRandom + g_Cvars.delay + 1));
}
else {
std::this_thread::sleep_for(std::chrono::milliseconds(g_Cvars.delay));
}
}
if (!m_isWriting)
break;
}
m_isWriting = false;
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
} | true |
529039603ae4cae5211da6eea5b2829fcb8a6fe1 | C++ | olderor/speed-test | /temp/main.cpp | UTF-8 | 6,993 | 3 | 3 | [] | no_license | #include <fstream>
#include <iostream>
#include <vector>
#include <ctime>
#include <iomanip>
using namespace std;
typedef unsigned long long ull;
int foo_vector(vector<int> v) {
return 0;
}
int foo_int(ull v) {
return 0;
}
int foo_address_vector(vector<int> &v) {
return 0;
}
int foo_address_int(ull &v) {
return 0;
}
int foo_const_int(const ull v) {
return 0;
}
int foo_const_address_int(const ull &v) {
return 0;
}
int foo_const_vector(const vector<int> v) {
return 0;
}
int foo_const_address_vector(const vector<int> &v) {
return 0;
}
int get_time_of_func(void(*f)(ull), ull parameter) {
clock_t begin = clock();
f(parameter);
clock_t end = clock();
return end - begin;
}
void test_vector(ull test_size) {
vector<int> v(test_size);
for (int i = 0; i < test_size; ++i) {
v[i] = i;
}
foo_vector(v);
}
void test_int(ull test_size) {
for (ull i = 0; i < test_size; ++i) {
foo_int(i);
}
}
void test_address_vector(ull test_size) {
vector<int> v(test_size);
for (int i = 0; i < test_size; ++i) {
v[i] = i;
}
foo_address_vector(v);
}
void test_address_int(ull test_size) {
for (ull i = 0; i < test_size; ++i) {
foo_address_int(i);
}
}
void test_const_int(ull test_size) {
for (ull i = 0; i < test_size; ++i) {
foo_const_int(i);
}
}
void test_const_address_int(ull test_size) {
for (ull i = 0; i < test_size; ++i) {
foo_const_address_int(i);
}
}
void test_const_vector(ull test_size) {
vector<int> v(test_size);
for (int i = 0; i < test_size; ++i) {
v[i] = i;
}
foo_const_vector(v);
}
void test_const_address_vector(ull test_size) {
vector<int> v(test_size);
for (int i = 0; i < test_size; ++i) {
v[i] = i;
}
foo_const_address_vector(v);
}
void make_test1(std::ostream &_Istr, ull size, int test_index) {
double vector_time = get_time_of_func(test_vector, size);
double int_time = get_time_of_func(test_int, size);
double vector_address_time = get_time_of_func(test_address_vector, size);
double int_address_time = get_time_of_func(test_address_int, size);
_Istr << "test #" << test_index << " with size " << size << ":" << endl;
_Istr << "vector test was elapsed within " << (int)vector_time << " milliseconds." << endl;
_Istr << "int test was elapsed within " << (int)int_time << " milliseconds." << endl;
_Istr << "vector address test was elapsed within " << (int)vector_address_time << " milliseconds." << endl;
_Istr << "int address test was elapsed within " << (int)int_address_time << " milliseconds." << endl;
_Istr << "int " << 100 - (int)(int_time / vector_time * 100.0) << "% faster than vector" << endl;
_Istr << "vector address " << 100 - (int)(vector_address_time / vector_time * 100.0) << "% faster than vector" << endl;
_Istr << "int address " << 100 - (int)(int_address_time / int_time * 100.0) << "% faster than int" << endl;
_Istr << endl;
}
void make_test2(std::ostream &_Istr, ull size, int test_index) {
double int_time = get_time_of_func(test_int, size);
double int_address_time = get_time_of_func(test_address_int, size);
double int_const_time = get_time_of_func(test_const_int, size);
double int_const_address_time = get_time_of_func(test_const_address_int, size);
_Istr << "test #" << test_index << " with size " << size << ":" << endl;
_Istr << "int test was elapsed within " << (int)int_time << " milliseconds." << endl;
_Istr << "int address test was elapsed within " << (int)int_address_time << " milliseconds." << endl;
_Istr << "int const test was elapsed within " << (int)int_const_time << " milliseconds." << endl;
_Istr << "int const address test was elapsed within " << (int)int_const_address_time << " milliseconds." << endl;
_Istr << "int address " << 100 - (int)(int_address_time / int_time * 100.0) << "% faster than int" << endl;
_Istr << "int const address " << 100 - (int)(int_const_address_time / int_const_time * 100.0) << "% faster than const int" << endl;
_Istr << "int const " << 100 - (int)(int_const_time / int_time * 100.0) << "% faster than int" << endl;
_Istr << "int const address " << 100 - (int)(int_const_address_time / int_address_time * 100.0) << "% faster than int address" << endl;
_Istr << endl;
}
void make_test3(std::ostream &_Istr, ull size, int test_index) {
double vector_time = get_time_of_func(test_vector, size);
double vector_const_time = get_time_of_func(test_const_vector, size);
double vector_address_time = get_time_of_func(test_address_vector, size);
double vector_const_address_time = get_time_of_func(test_const_address_vector, size);
_Istr << "test #" << test_index << " with size " << size << ":" << endl;
_Istr << "vector test was elapsed within " << (int)vector_time << " milliseconds." << endl;
_Istr << "vector address test was elapsed within " << (int)vector_address_time << " milliseconds." << endl;
_Istr << "vector const test was elapsed within " << (int)vector_const_time << " milliseconds." << endl;
_Istr << "vector const address test was elapsed within " << (int)vector_const_address_time << " milliseconds." << endl;
_Istr << "vector address " << 100 - (int)(vector_address_time / vector_time * 100.0) << "% faster than vector" << endl;
_Istr << "vector const " << 100 - (int)(vector_const_time / vector_time * 100.0) << "% faster than vector" << endl;
_Istr << "vector const address " << 100 - (int)(vector_const_address_time / vector_address_time * 100.0) << "% faster than vector address" << endl;
_Istr << "vector const address " << 100 - (int)(vector_const_address_time / vector_const_time * 100.0) << "% faster than vector const" << endl;
_Istr << endl;
}
int main() {
ofstream fout("log.txt", ios::app);
cout << "Starting testing 10^8 tests..." << endl;
/*
ull size = 10000;
for (int test = 4; test <= 8; ++test) {
cout << "Testing for size " << size << " (test " << test << ")..." << endl;
make_test1(fout, size, test);
cout << "Complete." << endl;
size *= 10;
}
for (int test = 9; test <= 10; ++test) {
cout << "Testing for size " << size << " (test " << test << ")..." << endl;
make_test2(fout, size, test);
cout << "Complete." << endl;
size *= 10;
}*/
int test = 6;
ull size = 1000000;
for (int i = 0; i < 100; ++i) {
cout << "Test #" << i << " for size " << size << " (test " << test << ")..." << endl;
make_test3(fout, size, test);
}
++test;
size *= 10;
for (int i = 0; i < 10; ++i) {
cout << "Test #" << i << " for size " << size << " (test " << test << ")..." << endl;
make_test3(fout, size, test);
}
fout.close();
cout << "Done." << endl;
cin.get();
return 0;
}
| true |
5b33bc2e6f8071c7ef8b29b60492355121558d4f | C++ | 0josephb/RPG-Player-Class | /ogre.cpp | UTF-8 | 1,515 | 2.59375 | 3 | [] | no_license | // Joseph Brown
// Program 3
// Ogre implementation
#include <string>
#include <iostream>
#include "gamespace.h"
#include "voc.h"
#include "dice.h"
#include "wpn.h"
#include "ogre.h"
using namespace std;
using namespace GameSpace;
const string Ogre::RACE = "OGRE";
const int Ogre::ABILITY_ADJ[6] = {8, 15, 6, 7, 21, 10};
const int Ogre::HIT_DIE[NUM_DICE_DATA] = {4, 8, 8};
const int Ogre::SAVE_THROW[3] = {6, 0, 1};
const int Ogre::BASE_ATT_BONUS[2] = {1,8};
const string Ogre::INIT_WPN = "SPEAR";
const int Ogre::NUM_INIT_SKILLS;
const string Ogre::INIT_SKILLS[NUM_INIT_SKILLS] = {"INTIMIDATE", "LISTEN", "SPOT"};
Ogre::Ogre(string name):Monster(name, ABILITY_ADJ, HIT_DIE) {
for (int i = 0; i < NUM_INIT_SKILLS; i++) {
PlayerClass::AddSkill(INIT_SKILLS[i]);
}
}
Ogre::Ogre* Ogre::Clone() const {
return new Ogre(*this);
}
vector<string> Ogre::InitialWeaponList() const {
vector<string> weaponList;
weaponList.push_back(INIT_WPN);
return weaponList;
}
string Ogre::RaceStr() const {
return RACE;
}
int Ogre::RollAttack() const {
int rollAttk = 0;
rollAttk = Monster::RollAttack(BASE_ATT_BONUS);
return rollAttk;
}
int Ogre::RollSavingThrow(SavingThrowType kindofThrow) const {
int saveThrow = 0;
saveThrow = Monster::RollSavingThrow(kindofThrow, SAVE_THROW);
return saveThrow;
}
void Ogre::Write(ostream& out) const {
out << RACE << "#";
Monster::Write(out);
return;
}
| true |
3add77b11767149afa040530d0f772bd43afc2b8 | C++ | vikeshkhanna/codechef | /practice/medium/Flipping Coins/binary.cpp | UTF-8 | 1,456 | 2.890625 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<string>
#include<stack>
#include<queue>
#include<fstream>
#include<cmath>
#define FILE "input.txt"
#define MAX 100000
#define FOR(i,n) for(int i=0;i<n;i++)
typedef unsigned int uint;
typedef unsigned short sint;
typedef unsigned long lint;
using namespace std;
/*
* @author: Vikesh Khanna
*/
struct Node
{
Node *left, *right;
uint low, high;
uint count;
Node(){
count=0;
left = right = NULL;
}
};
Node* construct(uint low, uint high)
{
Node* root = new Node();
if(high==low){
root->low = low;
root->high = high;
}
else{
root->low = low;
root->high = high;
uint mid = (high+low)/2;
root->left = construct(low,mid);
root->right = construct(mid+1,high);
}
return root;
}
void inorder(Node* root)
{
if(root!=NULL){
inorder(root->left);
cout<<"("<<root->low<<","<<root->high<<")"<<endl;
inorder(root->right);
}
}
int arr_size(const int* a)
{
uint i=0;
while( a[i++]!=-1);
return i;
}
int main()
{
int a[] = {10,2,6,8,3,9,4,8,17,25,14,56,19,27,78,43,-1};
Node* root = construct(0,3);
inorder(root);
system("Pause");
return 0;
}
| true |
c1a35e8e3f613692981646434dd179f0729dc856 | C++ | davemar-bbc/libadm | /include/adm/detail/named_option_helper.hpp | UTF-8 | 523 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <memory>
#include <functional>
#include <type_traits>
namespace adm {
namespace detail {
template <typename Element>
inline void setNamedOptionHelper(Element&& /*element*/) {}
template <typename Element, typename T, typename... Parameters>
void setNamedOptionHelper(Element&& element, T v, Parameters... args) {
element->set(std::move(v));
setNamedOptionHelper(std::forward<Element>(element), std::move(args)...);
}
} // namespace detail
} // namespace adm
| true |
17ac40634e90a153ecc0d2c9339ca174d66d18cd | C++ | isliulin/MobileCArm | /Common/Include/CArmVT.h | UTF-8 | 7,141 | 2.578125 | 3 | [] | no_license | #pragma once
#include "IViewingTool.h"
#include "CArmCommon.h"
#define _CArmImgVT 0 //!< 图像处理工具类型
#define _CArmBright_Origin 1.0 //!< 原始图像明亮度
#define _CArmBright_MinValue 0.0 //!< 明亮度最小值(最暗)
#define _CArmBright_MaxValue 4.0 //!< 明亮度最大值(最亮)
#define _CArmContrast_Origin 1.0 //!< 原始图像对比度
#define _CArmContrast_MinValue 0.0 //!< 图像对比度最小值(对比最弱)
#define _CArmContrast_MaxValue 3.0 //!< 图像对比度最大值(对比最强)
#define _CArmSharpen_Origin 1.0 //!< 原始图像锐化度
#define _CArmSharpen_MinValue 0.0 //!< 图像锐化度最小值(最模糊)
#define _CArmMaxValue_Contrast 3.0 //!< 图像锐化度最大值(最增强)
/**
* @brief 移动C型臂工作站通用功能函数
*/
class CArmVT : public IViewingTool
{
public:
CArmVT(int type);
~CArmVT();
/**
* @brief 调用该函数,调节显示参数
*
* @param value 调节量
*/
virtual void adjustValue(float value, std::string name) {}
/**
* @brief 调用该函数,设置显示参数
*
* @param value 显示参数
*/
virtual void setValue(float value, std::string name) {};
/**
* @brief 调用该函数,显示工具对窗口进行处理
*
* @param view 显示窗口对象
*/
virtual void disposeViewer(BaseView* view) {};
};
/**
* @brief 移动C型臂工作站锐化工具
*/
class CArmSharpenVT : public CArmVT
{
public:
CArmSharpenVT(const CArmSharpenVTObject& param) : CArmVT{ CArmVTEnum::VT_Sharpen }, m_param( param ) { }
~CArmSharpenVT() { }
/**
* @brief 调用该函数,显示工具对窗口进行处理
*
* @param view 显示窗口对象
*/
void disposeViewer(BaseView* view);
protected:
CArmSharpenVTObject m_param; //!< 锐化参数
};
/**
* @brief 移动C型臂工作站降噪工具
*/
class CArmDenoiseVT : public CArmVT
{
public:
CArmDenoiseVT(const CArmDenoiseVTObject& param) : CArmVT{ CArmVTEnum::VT_Denoise }, m_param( param ) { }
~CArmDenoiseVT() { }
/**
* @brief 调用该函数,显示工具对窗口进行处理
*
* @param view 显示窗口对象
*/
void disposeViewer(BaseView* view);
protected:
CArmDenoiseVTObject m_param; //!< 降噪参数
};
/**
* @brief 移动C型臂工作站金属校正工具
*/
class CArmMetalCalibVT : public CArmVT
{
public:
CArmMetalCalibVT(const CArmMetalCalibVTObject& param) : CArmVT{ CArmVTEnum::VT_MetalCalib }, m_param( param ) { }
~CArmMetalCalibVT() { }
/**
* @brief 调用该函数,显示工具对窗口进行处理
*
* @param view 显示窗口对象
*/
void disposeViewer(BaseView* view);
protected:
CArmMetalCalibVTObject m_param; //!< 金属校正参数
};
/**
* @brief 移动C型臂工作站明亮度调节工具
*/
class CArmBrightVT : public CArmVT
{
public:
CArmBrightVT(float value) : CArmVT{ CArmVTEnum::VT_Bright }, m_param { value } { }
~CArmBrightVT() { }
/**
* @brief 调用该函数,显示工具对窗口进行处理
*
* @param view 显示窗口对象
*/
void disposeViewer(BaseView* view);
protected:
float m_param; //!< 明亮度参数
};
/**
* @brief 移动C型臂工作站对比度调节工具
*/
class CArmContrastVT : public CArmVT
{
public:
CArmContrastVT(float value) : CArmVT{ CArmVTEnum::VT_Contrast }, m_param{ value } { }
~CArmContrastVT() { }
/**
* @brief 调用该函数,显示工具对窗口进行处理
*
* @param view 显示窗口对象
*/
void disposeViewer(BaseView* view);
protected:
float m_param; //!< 对比度参数
};
/**
* @brief 图像水平翻转工具
*/
class CArmFlipHVT : public CArmVT
{
public:
CArmFlipHVT(bool en) : CArmVT{ CArmVTEnum::VT_FlipH }, m_param{ en } { }
~CArmFlipHVT() { }
/**
* @brief 调用该函数,显示工具对窗口进行处理
*
* @param view 显示窗口对象
*/
void disposeViewer(BaseView* view);
protected:
bool m_param; //!< 水平翻转参数
};
/**
* @brief 图像竖直翻转工具
*/
class CArmFlipVVT : public CArmVT
{
public:
CArmFlipVVT(bool en) : CArmVT{ CArmVTEnum::VT_FlipV }, m_param{ en } { }
~CArmFlipVVT() { }
/**
* @brief 调用该函数,显示工具对窗口进行处理
*
* @param view 显示窗口对象
*/
void disposeViewer(BaseView* view);
protected:
bool m_param; //!< 竖直翻转参数
};
/**
* @brief 图像负片工具
*/
class CArmNegativeVT : public CArmVT
{
public:
CArmNegativeVT(bool en) : CArmVT{ CArmVTEnum::VT_Negative }, m_param{ en } { }
~CArmNegativeVT() { }
/**
* @brief 调用该函数,显示工具对窗口进行处理
*
* @param view 显示窗口对象
*/
void disposeViewer(BaseView* view);
protected:
bool m_param; //!< 负片参数
};
/**
* @brief 图像旋转工具
*/
class CArmRotateVT : public CArmVT
{
public:
CArmRotateVT(int en) : CArmVT{ CArmVTEnum::VT_Rotate }, m_param{ en } { }
~CArmRotateVT() { }
/**
* @brief 调用该函数,显示工具对窗口进行处理
*
* @param view 显示窗口对象
*/
void disposeViewer(BaseView* view);
protected:
int m_param; //!< 旋转参数
};
/**
* @brief 移动C型臂工作站通用功能函数
*/
class CArmImgVT
{
public:
CArmImgVT(BaseView* view) : m_pViewer{ view } { }
~CArmImgVT() { }
/**
* @brief 调用该函数,设置锐化参数
* @param value 锐化参数
*/
void setSharpenParam(CArmSharpenVTObject value);
/**
* @brief 调用该函数,设置降噪参数
* @param value 降噪参数
*/
void setDenoiseParam(CArmDenoiseVTObject value);
/**
* @brief 调用该函数,设置金属校正参数
* @param value 金属校正参数
*/
void setMetalCalibParam(CArmMetalCalibVTObject value);
/**
* @brief 调用该函数,设置明亮度参数
* @param value 明亮度参数
*/
void updateBright(int value);
/**
* @brief 调用该函数,设置对比度参数
* @param value 对比度参数
*/
void updateContrast(int value);
/**
* @brief 调用该函数,开启/关闭水平翻转
* @param en 开启/关闭
*/
void enableFlipH(bool en);
/**
* @brief 调用该函数,开启/关闭竖直翻转
* @param en 开启/关闭
*/
void enableFlipV(bool en);
/**
* @brief 调用该函数,开启/关闭负片
* @param en 开启/关闭
*/
void setNegative(bool en);
/**
* @brief 调用该函数,设置旋转参数
* @param value 旋转参数
*/
void setRotateParam(int value);
CArmImgParam getImageParam();
protected:
/**
* @brief 调用该函数,进行图像处理
*/
void processImage();
private:
CArmImgParam m_param; //!< 图像处理参数
BaseView* m_pViewer; //!< 处理窗口
}; | true |
0b669db94a39515f830fa2c5ca6897521a1fbfd3 | C++ | ppzzyy11/codes | /AVLTree.cpp | UTF-8 | 6,194 | 3.71875 | 4 | [] | no_license | /*
* AVL Tree | Self Balanced Tree
*
* So many tiny tests passed
*
*/
#include <iostream>
#include <vector>
#include <unordered_map>
#include <climits>
#include <algorithm>
using namespace std;
template<typename T>
ostream& operator<<(ostream& os,const vector<T>& ts)
{
for(auto t:ts)
{
cout<<t<<' ';
}
//cout<<'\n';
return os;
}
template<typename T>
class AVLNode{
private:
int height;
T key;
AVLNode<T>* left;
AVLNode<T>* right;
public:
AVLNode(T k,AVLNode<T>* l=NULL,AVLNode<T>* r=NULL,int h=1):key(k),left(l),right(r),height(h){;}
~AVLNode(){}
int GetHeight(){return height;}
void SetHeight(const int h){height=h;}
AVLNode<T>* GetLeft(){return left;}
AVLNode<T>* GetRight(){return right;}
void SetLeft(AVLNode<T>* l){left=l;}
void SetRight(AVLNode<T>* r){right=r;}
T GetKey(){return key;}
void SetKey(T k){key=k;}
};
template<typename T>
class AVLTree
{
private:
AVLNode<T>* LeftRotate(AVLNode<T>* z)
{
if(z==NULL) return NULL;
AVLNode<T>* y=z->GetRight();
if(y==NULL) return NULL;
AVLNode<T>* t2=y->GetLeft();
y->SetLeft(z);
z->SetRight(t2);
UpdateHeight(z);
UpdateHeight(y);
return y;
}
AVLNode<T>* RightRotate(AVLNode<T>* z)
{
if(z==NULL) return NULL;
AVLNode<T>* y=z->GetLeft();
if(y==NULL) return NULL;
AVLNode<T>* t3=y->GetRight();
z->SetLeft(t3);
y->SetRight(z);
UpdateHeight(z);
UpdateHeight(y);
return y;
}
bool UpdateHeight(AVLNode<T>* nod)
{
if(nod==NULL) return false;
int lh=GetHeight(nod->GetLeft());
int rh=GetHeight(nod->GetRight());
nod->SetHeight(max(lh,rh)+1);
return true;
}
int GetHeight(AVLNode<T>* nod)
{
if(nod==NULL) return 0;
return nod->GetHeight();
}
int GetBalance(AVLNode<T>* nod)
{
if(nod==NULL) return 0;
return GetHeight(nod->GetLeft())-GetHeight(nod->GetRight());
}
AVLNode<T>*Insert(AVLNode<T>* nod,T t)
{
if(nod==NULL) return new AVLNode<T>(t,NULL,NULL,1);
if(nod->GetKey()>t)// go to left child
{
nod->SetLeft(Insert(nod->GetLeft(),t));
}else if(nod->GetKey()<t)//t is bigger than nod->t
{
nod->SetRight(Insert(nod->GetRight(),t));
}else
{
return nod;
}
UpdateHeight(nod);
int balance=GetBalance(nod);//balance factor
if(balance>1&&t<nod->GetLeft()->GetKey())//left left
{
return RightRotate(nod);
}
if(balance<-1&&t>nod->GetRight()->GetKey())//right right
{
return LeftRotate(nod);
}
if(balance>1&&t>nod->GetLeft()->GetKey())//left right
{
nod->SetLeft(LeftRotate(nod->GetLeft()));
return RightRotate(nod);
}
if(balance<-1&&t<nod->GetRight()->GetKey())//left right
{
nod->SetRight(RightRotate(nod->GetRight()));
return LeftRotate(nod);
}
return nod;
}
AVLNode<T>* Delete(AVLNode<T>* nod,T t)
{
if(nod==NULL) return NULL;
if(nod->GetKey()>t)//go to left
{
nod->SetLeft(Delete(nod->GetLeft(),t));
}else if(nod->GetKey()<t)//go to right
{
nod->SetRight(Delete(nod->GetRight(),t));
}else {
if(nod->GetLeft()==NULL&&nod->GetRight()==NULL)//no child
{
delete nod;
return NULL;
}else if(nod->GetLeft()!=NULL&&nod->GetRight()!=NULL)//two children
{
AVLNode<T>* predecessor=nod->GetLeft();
while(predecessor->GetRight()!=NULL)
{
predecessor=predecessor->GetRight();
}
nod->SetKey(predecessor->GetKey());
nod->SetLeft(Delete(nod->GetLeft(),predecessor->GetKey()));
}else// only one child
{
AVLNode<T>* child;
if(nod->GetLeft()!=NULL)
child=nod->GetLeft();
else
child=nod->GetRight();
delete nod;
return child;
}
}
UpdateHeight(nod);
int balance=GetBalance(nod);
if(balance>1&&GetBalance(nod->GetLeft())>=0)//left left
{
return RightRotate(nod);
}
if(balance>1&&GetBalance(nod->GetLeft())<0)//left right
{
nod->SetLeft(LeftRotate(nod->GetLeft()));
return RightRotate(nod);
}
if(balance<-1&&GetBalance(nod->GetRight())<=0)//right right
{
return LeftRotate(nod);
}
if(balance<-1&&GetBalance(nod->GetRight())>0)//right left
{
nod->SetRight(RightRotate(nod->GetRight()));
return LeftRotate(nod);
}
return nod;
}
bool Search(AVLNode<T>* nod,T t)
{
if(nod==NULL) return false;
if(nod->GetKey()==t)
{
return true;
}else if(t<nod->GetKey())//go to nod->left
{
return Search(nod->GetLeft(),t);
}else//go to right
{
return Search(nod->GetRight(),t);
}
}
void PreOrder(AVLNode<T>* nod)
{
if(nod==NULL) return ;
cout<<nod->GetKey()<<' ';
PreOrder(nod->GetLeft());
PreOrder(nod->GetRight());
}
void InOrder(AVLNode<T>* nod)
{
if(nod==NULL) return ;
InOrder(nod->GetLeft());
cout<<nod->GetKey()<< ' ';
InOrder(nod->GetRight());
}
void PostOrder(AVLNode<T>* nod)
{
if(nod==NULL) return ;
PostOrder(nod->GetLeft());
PostOrder(nod->GetRight());
cout<<nod->GetKey()<<' ';
}
void Clear(AVLNode<T>* nod)
{
if(nod==NULL) return ;
Clear(nod->GetLeft());
Clear(nod->GetRight());
delete nod;
}
public:
AVLTree(const vector<T> ts)
{
root=NULL;
for(auto t:ts)
{
Insert(t);
}
}
~AVLTree()
{
Clear(root);
root=NULL;
}
void Insert(T t)
{
root=Insert(root,t);
}
void Delete(T t)
{
root=Delete(root,t);
}
bool Search(T t)
{
return Search(root,t);
}
void PreOrder()
{
PreOrder(root);
cout<<'\n';
}
void InOrder()
{
InOrder(root);
cout<<'\n';
}
void PostOrder()
{
PostOrder(root);
cout<<'\n';
}
int height()
{
return root==NULL?0:root->GetHeight();
}
void clear()
{
Clear(root);
root=NULL;
}
protected:
AVLNode<T>* root;
};
int main()
{
int len=10000;
vector<int> nums;
srand(time(NULL));
for(int i=0;i<len;i++)
{
nums.push_back(rand()%999);
}
AVLTree<int> AVLt(nums);
while(nums.size()!=0)
{
int idx=rand()%nums.size();
cout<<nums<<'\n';
cout<<"delte "<<nums[idx]<<"\n";
AVLt.Delete(nums[idx]);
swap(nums[idx],nums[nums.size()-1]);
nums.pop_back();
}
AVLt.PreOrder();
AVLt.InOrder();
cout<<AVLt.height()<<endl;
return 0;
}
| true |
9a184f2271730f2ca8c87e4364da4f6bb61f8923 | C++ | tannuchoudhary/Data-structure-and-Algorithms | /LINKED_LIST/linkedlist.cpp | UTF-8 | 9,389 | 3.5 | 4 | [] | no_license |
//--------------- DON'T TOUCH, IT WORKS-------------------------------------
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
class Node
{
public:
int data;
struct Node * next;
};
class linkedList
{
public:
struct Node * head;
struct Node * tail;
int nodeCount;
//Function prototype
void menu();
int loadFromFile(char *);
void createRandomList(int);
void insertAtHead(int);
void insertAtTail(int);
void printListDetails();
void printListData();
Node * find_(int, Node **);
int deleteAtHead();
int deleteAtTail();
int deleteTarget(int);
void reverse_();
linkedList()
{
head = NULL;
tail = NULL;
nodeCount = 0;
}
};
//Function definition
void linkedList :: menu()
{
printf("1. Load from file\n");
printf("2. Create random list\n");
printf("3. Insert at tail\n");
printf("4. Insert at head\n");
printf("5. Print list (details)\n");
printf("6. Print list (data only)\n");
printf("7. Find\n");
printf("8. Delete at head\n");
printf("9. Delete at tail\n");
printf("10. Delete target\n");
printf("11. Reverse\n");
printf("12. Quit\n");
}
void linkedList :: createRandomList(int num)
{
int i, k;
srand(time(NULL));
for (i=0; i<num; i++)
{
k = rand() % 1000;
insertAtTail(k);
}
}
void linkedList :: insertAtTail(int data)
{
Node *newNodePtr = (Node*)malloc(sizeof(Node));
if(newNodePtr == NULL)
{
printf("Memory cannot be allocated\n");
return;
}
newNodePtr->data = data;
newNodePtr->next = NULL;
if(nodeCount == 0)
{
head = newNodePtr;
tail = newNodePtr;
}
else
{
tail->next = newNodePtr;
tail = newNodePtr;
}
nodeCount++;
}
void linkedList :: insertAtHead(int data)
{
Node * newNodePtr = (Node *)malloc(sizeof(Node));
if(newNodePtr == NULL)
{
printf("Memory cannot be allocated for node");
return;
}
newNodePtr->data = data;
newNodePtr->next = NULL;
if(nodeCount == 0)
{
head = newNodePtr;
tail = newNodePtr;
}
else
{
newNodePtr->next = head;
head = newNodePtr;
}
nodeCount++;
}
void linkedList :: printListData()
{
if(nodeCount == 0)
{
printf("Linked list is empty\n");
return;
}
else
{
Node * current = head;
while(current != NULL)
{
printf("%d \n", current->data);
current = current->next;
}
}
}
void linkedList :: printListDetails()
{
if(nodeCount == 0)
{
printf("Linked list is empty\n");
return;
}
else
{
Node *current = head;
printf("\nHEAD : %p ", head);
printf("\n\n");
int count_ = 0;
printf("Sl.no | Node address | Node data | Next address \n");
while(current != NULL)
{
printf("%d | %p | %d | %p \n", count_, current, current->data, current->next);
current = current->next;
count_++;
}
printf("\nTAIL : %p", tail);
printf("\n\n");
}
}
int linkedList :: loadFromFile(char *fileName)
{
FILE *fp = fopen(fileName, "r");
if(fp == NULL)
{
return 0;
}
int data;
fscanf(fp, "%d", &data);
while(!feof(fp))
{
insertAtTail(data);
fscanf(fp, "%d", &data);
}
fclose(fp);
return 1;
}
Node * linkedList :: find_(int target, Node ** prev)
{
*prev = NULL;
Node * current = head;
while(current != NULL)
{
if(current->data == target)
{
break;
}
*prev = current;
current = current->next;
}
return current;
}
int linkedList :: deleteAtHead()
{
if(nodeCount == 0)
{
return -9999;
}
Node *first = head; //keeping the address of head in first variable to free the memory later.
int data = first->data;
if (nodeCount == 1)
{
head == NULL;
tail == NULL;
}
else
{
head = first->next;
}
free(first);
nodeCount--;
return data;
}
int linkedList :: deleteAtTail()
{
if(nodeCount == 0)
{
return -9999;
}
Node *last = tail; //keeping the address of head in first variable to free the memory later.
int data = last->data;
if (nodeCount == 1)
{
head == NULL;
tail == NULL;
}
else
{
Node *current = head;
Node * prev = NULL;
while(current != NULL)
{
prev = current;
current = current ->next;
}
tail = prev;
prev->next = NULL;
}
free(last);
nodeCount--;
return data;
}
int linkedList :: deleteTarget(int target)
{
Node *current = NULL;
Node * prev = NULL;
current = find_(target, &prev);
int data = current->data;
if(current == NULL)
return -9999;
if(target == head->data)
deleteAtHead();
if(target == tail->data)
deleteAtTail();
else
{
prev->next = current->next;
free(current);
nodeCount--;
return data;
}
}
void linkedList :: reverse_()
{
if (nodeCount <= 1)
return;
Node *p, *q, *r;
q = NULL;
p = head;
r = p->next;
while(1)
{
p->next = q;
if(p == tail)
break;
q = p;
p = r;
r = r->next;
}
tail = head;
head = p;
}
int main()
{
linkedList list;
list.menu();
int data, choice, success;
Node * current = NULL;
Node * prev = NULL;
while(1)
{
printf("Enter your choice : ");
scanf("%d", &choice);
switch(choice)
{
case 1:
success = list.loadFromFile("num.txt");
if (success == 1)
{
printf("File has been loaded successfully.\n");
}
else
printf("Unable to load file\n");
break;
case 2:
printf("Enter number of integers to be generated : ");
scanf("%d",&data);
list.createRandomList(data);
break;
case 3:
printf("Enter the number you want to insert : ");
scanf("%d",&data);
list.insertAtTail(data);
break;
case 4:
printf("Enter the number you want to insert : ");
scanf("%d",&data);
list.insertAtHead(data);
break;
case 5:
list.printListDetails();
break;
case 6:
list.printListData();
break;
case 7:
printf("Enter target to find :");
scanf("%d",&data);
current = list.find_(data, &prev);
if(current == NULL)
{
printf("Target not found\n");
}
else
{
printf("Target node exists, address of the target node :%p, previous : %p\n", current , prev);
}
break;
case 8:
data = list.deleteAtHead();
if(data == -9999)
{
printf("Linked list is empty\n");
}
else
{
printf("First node is deleted, data : %d\n", data);
}
break;
case 9:
data = list.deleteAtTail();
if(data == -9999)
{
printf("Linked list is empty\n");
}
else
{
printf("Last node is deleted, data : %d\n", data);
}
break;
case 10:
printf("Enter the target you want to delete : ");
scanf("%d", &data);
success = list.deleteTarget(data);
if (success == -9999)
printf("Linked list is empty.\n");
else
printf("Target is deleted, data : %d\n", success);
break;
case 11:
list.reverse_();
break;
case 12:
exit(0);
break;
default :
printf("Invalid choice\n");
//exit(0);
}
}
}
| true |
41830c3dc0cc10e852ae910121aa17193583f023 | C++ | iamjatin08/DATA-STRUCTURES | /hashmaps/mapUSE.cpp | UTF-8 | 655 | 3.234375 | 3 | [] | no_license | #include<iostream>
#include<unordered_map>
#include<string>
using namespace std;
int main(int argc, char const *argv[])
{
unordered_map<string,int> ourmap;
//insert
pair<string,int> p("abc",1);
ourmap.insert(p);
ourmap["def"] = 2;
// find or access
cout<<ourmap["abc"]<<endl;
cout<<ourmap.at("abc")<<endl;
cout<<ourmap.size()<<endl;
cout<<ourmap["gfi"]<<endl;
//size function
cout<<ourmap.size()<<endl;
// check presence
if(ourmap.count("ghi")>0){
cout<<ourmap["ghi"]<<endl;
}
else{
cout<<ourmap["abc"]<<endl;
}
//erase
ourmap.erase("abc");
cout<<ourmap.size()<<endl;
return 0;
} | true |
fe842d81e152215ef75eb173700a0e73d9527812 | C++ | ArchiGn98/LTC-CPP-Student | /constrexpr-if.h | UTF-8 | 356 | 3.546875 | 4 | [] | no_license | #pragma once
#include <type_traits>
#include <vector>
template<typename T>
class Addable
{
T val;
public:
Addable(T v) : val(v) {}
template<typename U>
T Add(U x) const
{
if constexpr (std::is_same_v<T, std::vector<U>>)
{
auto copy(val);
for (auto& n : copy)
{
n += x;
}
return copy;
}
else
{
return val + x;
}
}
}; | true |
ff0782428792c0fb9f27eb5baaa131d63ae144cd | C++ | wpineda21/PED0319-WRMH-00019618 | /Ejemplos/EX-02.cpp | UTF-8 | 3,691 | 3.90625 | 4 | [] | no_license | /*
Ejemplo de pila utilizando punteros y typedef
Programa para almacenar datos para la creacion de un correo electronico
*/
#include <iostream>
using namespace std;
// Declaracion de estructura que contendra la informacion requerida
struct email{
string mail, fullname, country, postalCode, phone;
int age;
};
// Redefinicion del tipo email a tipo T (template)
typedef email T;
// Declaracion de estructura correspondiente a los nodos de la pila
struct node{
T info;
node* next;
};
// Prototipos
node* push(node* st, T aux);
T top(node* st);
node* pop(node* st);
int size(node* st);
bool empty(node* st);
int main(void){
// Declaracion e inizalizacion del puntero que apuntara al inicio de la pila
node* st = NULL;
// Declaracion de variable auxiliar para almacenar los datos
T aux;
int option = 0;
do{
cout << "Nombre:\t"; getline(cin, aux.fullname);
cout << "Edad:\t"; cin >> aux.age; cin.ignore();
cout << "Pais:\t"; getline(cin, aux.country);
cout << "Codigo postal:\t"; getline(cin, aux.postalCode);
cout << "Telefono:\t"; getline(cin, aux.phone);
cout << "Correo electronico:\t"; getline(cin, aux.mail);
// Anadir el elemento a la pila
st = push(st, aux);
cout << "Crear nuevo correo (1 - si, 0 - no)\t"; cin >> option; cin.ignore();
cout << endl;
} while(option != 0);
(empty(st)) ? cout << "La pila esta vacia" : cout << "La pila no esta vacia";
cout << endl << endl;
cout << "Se han creado " << size(st) << " nuevos correos" << endl << endl;
aux = top(st);
cout << "Datos del ultimo correo anadido" << endl;
cout << "Nombre:\t" << aux.fullname << endl;
cout << "Edad:\t" << aux.age << endl;
cout << "Pais:\t" << aux.country << endl;
cout << "Codigo postal:\t" << aux.postalCode << endl;
cout << "Telefono:\t" << aux.phone << endl;
cout << "Correo electronico:\t" << aux.mail << endl << endl;
cout << "Eliminando ultimo correo electronico" << endl;
st = pop(st);
return 0;
}
// Funcion de insercion de elemento en la pila
node* push(node* st, T aux){
// Creacion de nodo a insertar en la pila
node* insert = new node;
// Asignacion de la informacion
insert->info = aux;
// Conexion con lo demas de la pila
insert->next = st;
st = insert;
// Retorno de la cola modificada
return st;
}
// Funcion para consultar al elemento de la cima de la pila
T top(node* st){
// Declaracion de nodo auxiliar a devolver
node* aux = st;
// Si auxiliar esta vacia, entonces retornar un elemento vacio, sino retornar el elemento en el nodo
if(!aux){
T auxReturn = {"", "", "", "", "", 0};
return auxReturn;
}
else
return aux->info;
/*
Aclaraciones
* Si la pila esta vacia, la funcion retornara una variable de tipo T por defecto vacia
* Al enviarse el puntero de la cola por valor, no se pierde la conexion de todos los nodos en el main
*/
}
// Funcion para eliminar el elemento de la cima de la pila
node* pop(node* st){
return st->next;
}
// Funcion recursiva que determina la cantidad de nodos en la pila
int size(node* st){
// Caso base: que la pila este vacia
if(!st)
return 0;
// Si la pila contiene elementos, se regresa 1 + la cantidad de elementos del resto de la pila (llamada rec)
else
return 1 + size(st->next);
}
// Funcion que determina si la pila esta vacia
bool empty(node* st){
return (!st);
} | true |
0470683ab7a4b6497ea70444eb550a0be7378347 | C++ | ArcSung/ON_THE_ROAD | /arduino/attiny_IRTest2/attiny_IRTest2.ino | UTF-8 | 1,804 | 2.703125 | 3 | [] | no_license | #include <SoftwareSerial.h>
#include <MeetAndroid.h>
int LEDpin = 4;
int Threshold = 200;
const byte IRPIN = 1;
float p[3];
int i = 0;
int Temp = 200;
SoftwareSerial mySerial(0,1); // 設定對應bt的 rx 與 tx 接腳
MeetAndroid meetAndroid(mySerial);
//MeetAndroid meetAndroid(0, 1, 9600);
void setup()
{
// use the baud rate your bluetooth module is configured to
// not all baud rates are working well, i.e. ATMEGA168 works best with 57600
mySerial.begin(9600);
meetAndroid.registerFunction(ArdSetting,'S');
meetAndroid.registerFunction(StopCount, 'o');
meetAndroid.registerFunction(ArdCheck,'c');
}
void loop()
{
meetAndroid.receive(); // you need to keep this in your loop() to receive events
int dist = Count_distnce();
if(compare_filter(dist, Threshold) && (dist > 20))
meetAndroid.send(dist);
else
meetAndroid.send(0);
}
void ArdSetting(byte flag, byte numOfValues)
{
Threshold = meetAndroid.getInt();
}
void StopCount(byte flag, byte numOfValues)
{
int received = meetAndroid.getInt();
}
void ArdCheck(byte flag, byte numOfValues)
{
int ACK = 0;
meetAndroid.send(ACK);
}
int Count_distnce()
{
float volts = analogRead(IRPIN)*0.0048828125; // value from sensor * (5/1024) - if running 3.3.volts then change 5 to 3.3
int distance = (int)(65*pow(volts, -1.10)); // worked out from graph 65 = theretical distance / (1/Volts)S - luckylarry.co.
return distance;
}
int average_filter(int average)
{
p[i] = average;
i++;
if(i >= 3)
i = 0;
average = (p[0] + p[1] + p[2] )/3;
return (int)average;
}
boolean compare_filter(int arg, int thd)
{
boolean Flag = false;
if (Temp < Threshold && arg <Threshold && arg > 20)
Flag = true;
else
Flag = false;
Temp = arg;
return Flag;
}
| true |
3decc9a839f959be77436cf0f47d5572c6289231 | C++ | devthedevil/Competetive_programming | /coding_ninja/backtracking/rat_in_maz1.cpp | UTF-8 | 1,123 | 2.859375 | 3 | [] | no_license | #include<iostream>
using namespace std;
#include<bits/stdc++.h>
using namespace std;
int board[20][20];
void maz(int maze[][20],int n,int row,int col)
{
if(row==n-1 && col==n-1)
{
board[row][col]=1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
cout<<board[i][j]<<" ";
}
cout<<endl;
board[row][col]=0;
return;
}
else if(row<0 || col<0 || row>=n || col>=n || board[row][col]==1 || maze[row][col]==0)
return;
else
{
board[row][col]=1;
maz(maze, n, row-1, col);
maz(maze, n, row+1, col);
maz(maze, n, row, col-1);
maz(maze, n, row, col+1);
board[row][col]=0;
}
}
void ratInAMaze(int maze[][20], int n)
{
memset(board,0,20*20*sizeof(int));
maz(maze,n,0,0);
}
#include<iostream>
using namespace std;
#include "Solution.h"
int main(){
int n;
cin >> n ;
int maze[20][20];
for(int i = 0; i < n ;i++){
for(int j = 0; j < n; j++){
cin >> maze[i][j];
}
}
ratInAMaze(maze, n);
}
| true |
8683aa856d206bae0e554b288f094d330beb3c37 | C++ | ThereWillBeOneDaypyf/Summer_SolveSet | /codeforces/cf_911_e.cpp | UTF-8 | 1,284 | 2.53125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
const int N = 1e6;
int a[N];
int vis[N];
int main()
{
int n, k;
while (cin >> n >> k)
{
int Max = 0;
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= k; i++)
{
cin >> a[i];
Max = max(a[i], Max);
}
int cur = 1;
stack<int> st;
for (int i = 1; i <= k; i++)
{
vis[a[i]] = 1;
if (a[i] == cur)
{
cur ++;
while (!st.empty() && st.top() == cur)
{
st.pop();
cur ++;
}
}
else
st.push(a[i]);
}
if (vis[cur] && st.top() != cur)
cout << -1 << endl;
else
{
int curcnt = k;
vector<int> v;
for (int i = 1; i <= Max; i++)
{
if (!vis[i])
{
v.clear();
while (!vis[i])
v.push_back(i++);
reverse(v.begin(), v.end());
for (auto x : v)
a[++curcnt] = x;
i--;
}
}
for (int i = n; i > Max; i--)
a[++curcnt] = i;
for (int i = k + 1; i <= n; i++)
{
vis[a[i]] = 1;
if (a[i] == cur)
{
cur ++;
while (!st.empty() && st.top() == cur)
st.pop(), cur ++;
}
else
st.push(a[i]);
}
if (!st.empty())
cout << -1 << endl;
else
{
for (int i = 1; i <= n; i++)
{
if (i != 1)
cout << " ";
cout << a[i];
}
}
cout << endl;
}
}
} | true |
6b0ebb10496b96b29af552df9e434352b1d2e2e8 | C++ | felipedmz/cExperiments | /bubble_sort_recursivo.cpp | UTF-8 | 725 | 3.453125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
int bubble_rec(int busca, int vetor[],int tamanho){
if (busca==vetor[tamanho])
return 1;
else if(tamanho==0)
return 0;
return bubble_rec(busca,vetor,tamanho-1);
}
int main(){
int v[5],b;
printf("Complete o vetor[5] com valores inteiros\n");
for(int i=0;i<5;i++){
printf("\ndigite o valor [%d]: ",i+1);
scanf("%d",&v[i]);
}
printf("\nVetor completo !\n\n");
printf("Digite o valor a ser buscado: ");
scanf("%d",&b);
if (bubble_rec(b,v,5)){
printf("\nVALOR ENCONTRADO");
}
else{
printf("\nVALOR NAO ENCONTRADO");
}
printf("\n\n\n");
system("pause");
return 0;
}
| true |
f2db3c06a2332491711a972499dab6d550c1c314 | C++ | nugusha/ProjectEuler-HackerRank | /Project Euler #18 Maximum path sum I.cpp | UTF-8 | 717 | 2.515625 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int a[20][20];
int d[20][20];
int n;
int solve(){
int ret=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)d[i][j]=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=i;j++)
d[i][j]=max(d[i-1][j],d[i-1][j-1])+a[i][j];
for(int i=1;i<=n;i++)
ret=max(ret,d[n][i]);
return ret;
}
int main() {
int t;
cin>>t;
while(t--){
cin>>n;
for(int i=1;i<=n;i++)
for(int j=1;j<=i;j++)
{cin>>a[i][j];d[i][j]=0;}
cout<<solve()<<endl;
}
return 0;
}
| true |
800bd603b3b4ae355d4434331c63a6f76c34497c | C++ | mstniy/cerius | /bootloader/common/port_io.cpp | UTF-8 | 985 | 3.015625 | 3 | [
"MIT"
] | permissive | #include "port_io.h"
BYTE PortIO::InB(WORD port)
{
// A handy C wrapper function that reads a byte from the specified port
// "=a" (result) means: put AL register in variable RESULT when finished
// "d" (port) means: load EDX with port
BYTE result;
__asm__("in %%dx, %%al" : "=a" (result) : "d" (port));
return result;
}
void PortIO::OutB(WORD port , BYTE data)
{
// "a" (data) means: load EAX with data
// "d" (port) means: load EDX with port
__asm__("out %%al, %%dx" : :"a" (data), "d" (port));
}
WORD PortIO::InW(WORD port)
{
WORD result;
__asm__("in %%dx, %%ax" : "=a" (result) : "d" (port));
return result;
}
void PortIO::OutW(WORD port , WORD data)
{
__asm__("out %%ax, %%dx" : :"a" (data), "d" (port));
}
DWORD PortIO::InD(WORD port)
{
DWORD result;
__asm__("in %%dx, %%eax" : "=a" (result) : "d" (port));
return result;
}
void PortIO::OutD(WORD port , DWORD data)
{
__asm__("out %%eax, %%dx" : :"a" (data), "d" (port));
}
| true |
07a7da194646f5c640408c2290336e4ebbf2f384 | C++ | carloshd86/IA_BehaviorTree | /steering/obstacleAvoidanceSteering.cpp | UTF-8 | 2,955 | 2.515625 | 3 | [] | no_license | #include <stdafx.h>
#include "obstacleAvoidanceSteering.h"
ObstacleAvoidanceSteering::ObstacleAvoidanceSteering(GameEntity& entity) :
mEntity (entity),
mAcceleration (0.f, 0.f),
mIsNearVector (0.f, 0.f),
mDistanceToObstacle (0.f, 0.f),
mCollisionCheck (0.f, 0.f),
mCollidingObstacle (nullptr) {}
// **************************************************
USVec2D ObstacleAvoidanceSteering::GetSteering() {
USVec2D entityPosition = mEntity.GetLoc();
USVec2D entityDirection = mEntity.GetLinearVelocity();
entityDirection.NormSafe();
mCollisionCheck = entityDirection * mEntity.GetParams().look_ahead;
mAcceleration.mX = 0;
mAcceleration.mY = 0;
mDistanceToObstacle.mX = 0;
mDistanceToObstacle.mY = 0;
mIsNearVector.mX = 0;
mIsNearVector.mY = 0;
mCollidingObstacle = nullptr;
const Obstacles& existingObstacles = mEntity.GetObstacles();
size_t obstaclesSize = existingObstacles.obstacles.size();
for (size_t i = 0; i < obstaclesSize; ++i) {
USVec2D obstaclePosition(existingObstacles.obstacles[i].mX, existingObstacles.obstacles[i].mY);
mDistanceToObstacle = obstaclePosition - entityPosition;
float proj = mDistanceToObstacle.Dot(entityDirection);
if (proj > 0 && (proj*proj <= mCollisionCheck.LengthSquared())) {
// Obstaculo en la direccion de movimiento y en rango de comprobacion
mIsNearVector = entityPosition + (entityDirection * proj);
USVec2D diff = mIsNearVector - obstaclePosition;
float obstacleRadius = existingObstacles.obstacles[i].mZ + mEntity.GetParams().char_radius;
if (diff.LengthSquared() <= obstacleRadius * obstacleRadius) {
// Existe colision.
mCollidingObstacle = &existingObstacles.obstacles[i];
mAcceleration = diff;
mAcceleration.NormSafe();
mAcceleration *= mEntity.GetParams().max_acceleration;
break;
}
}
}
return mAcceleration;
}
// **************************************************
void ObstacleAvoidanceSteering::SetTargetPosition(USVec2D targetPosition) {
}
// **************************************************
void ObstacleAvoidanceSteering::DrawDebug() {
MOAIGfxDevice& gfxDevice = MOAIGfxDevice::Get();
USVec2D entityPosition = mEntity.GetLoc();
USVec2D linearVelocity = mEntity.GetLinearVelocity();
gfxDevice.SetPenColor(1.0f, 1.0f, 0.0f, 0.5f);
MOAIDraw::DrawLine(entityPosition, entityPosition + mIsNearVector);
gfxDevice.SetPenColor(0.0f, 1.0f, 1.0f, 0.5f);
MOAIDraw::DrawLine(entityPosition, entityPosition + mAcceleration);
gfxDevice.SetPenColor(1.0f, 0.0f, 0.0f, 0.5f);
MOAIDraw::DrawLine(entityPosition, entityPosition + mDistanceToObstacle);
gfxDevice.SetPenColor(0.0f, 0.0f, 1.0f, 0.5f);
MOAIDraw::DrawLine(entityPosition, entityPosition + mCollisionCheck);
if (mCollidingObstacle) {
gfxDevice.SetPenColor(1.f, 0.f, 0.f, 0.5f);
MOAIDraw::DrawEllipseFill(mCollidingObstacle->mX, mCollidingObstacle->mY, mCollidingObstacle->mZ, mCollidingObstacle->mZ, 50);
}
} | true |
2fba88f9670e8e68debc9e1c9ae333d48031cd8e | C++ | entao1128/read-lammpstrj | /main.cpp | UTF-8 | 743 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <vector>
using namespace std;
#include "lammpstrj.h"
#define PI 3.141592654
#define PI2 6.2831853071
int read_lammpstrj(const char*, const int, const int) ;
int main( const int argc, const char* argv[] ) {
if ( argc < 2 ) {
cout << "Usage: postproc-lammpstrj [input.lammpstrj] [first frame index] [last frame index]" << endl;
exit(1);
}
int fr1 = stoi(argv[2]);
int fr2 = stoi(argv[3]);
int frs = read_lammpstrj(argv[1], fr1, fr2);
if ( frs != ( fr2 - fr1 ) ) {
cout << "Mismatch in frames read and input!" << endl;
exit(1);
}
cout << xt[frs-1][nsites-1][0] << " " << xt[frs-1][nsites-1][1] << endl;
return 0;
}
| true |
e46900d808f475e406b4e8dd6a5ef24610378ca6 | C++ | EganChin/PAT-Advanced-Level | /Others/1101 Quick Sort(25).cpp | UTF-8 | 2,988 | 3.765625 | 4 | [] | no_license | /*
1101 Quick Sort (25 分)
There is a classical process named partition in the famous quick sort algorithm. In this process we typically choose one element as the pivot. Then the elements less than the pivot are moved to its left and those larger than the pivot to its right. Given N distinct positive integers after a run of partition, could you tell how many elements could be the selected pivot for this partition?
For example, given N=5 and the numbers 1, 3, 2, 4, and 5. We have:
1 could be the pivot since there is no element to its left and all the elements to its right are larger than it;
3 must not be the pivot since although all the elements to its left are smaller, the number 2 to its right is less than it as well;
2 must not be the pivot since although all the elements to its right are larger, the number 3 to its left is larger than it as well;
and for the similar reason, 4 and 5 could also be the pivot.
Hence in total there are 3 pivot candidates.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤10
5
). Then the next line contains N distinct positive integers no larger than 10
9
. The numbers in a line are separated by spaces.
Output Specification:
For each test case, output in the first line the number of pivot candidates. Then in the next line print these candidates in increasing order. There must be exactly 1 space between two adjacent numbers, and no extra space at the end of each line.
Sample Input:
5
1 3 2 4 5
Sample Output:
3
1 4 5
*/
//2019.3.18 15:09 reading
//15:14 read
#include<iostream>
#include<algorithm>
using namespace std;
const int INF = (1<<31)-1;
int main(){
int n;
scanf("%d", &n);
int A[n+10], leftMax[n+10], rightMin[n+10],count=0;
//最后一个元素的左边的最大元素是0
leftMax[0] = 0;
for(int i=0;i<n;i++){
scanf("%d", &A[i]);
//存储A[i]左边最小的元素
if(i==1)
leftMax[i] = A[i-1];
else if(i>1)
leftMax[i] = max(A[i-1], leftMax[i-1]);
}
//最后一个元素的右边的最小元素是无限大
rightMin[n-1] = INF;
//从右到左遍历,存储右边最小的元素
for(int i=n-1;i>=0;i--){
if(i==n-2)
rightMin[i] = A[n-1];
else if(i<n-2)
rightMin[i] = min(A[i+1], rightMin[i+1]);
//printf("A[%d]=%d, leftMax=%d, rightMin=%d ", i, A[i], leftMax[i], rightMin[i]);
//同时计算满足条件的主元的个数
if(A[i]<=rightMin[i] && A[i]>=leftMax[i]){
//printf("pivot=%d", A[i]);
count++;
}
//printf("\n");
}
printf("%d\n",count);
for(int i=0,cnt=0; i<n;i++){
if(A[i]<=rightMin[i] && A[i]>=leftMax[i]){
if(cnt++==0)
printf("%d", A[i]);
else
printf(" %d", A[i]);
}
}
printf("\n");
return 0;
}
//15:41 AC
| true |
c8b672a177e2aa994034dd7cf7d7a1a6693db013 | C++ | caszhang/BackendDevelopmentEnvironment | /base/dsalgo/gcc_4_1_plus/lock_free_queue.cc | UTF-8 | 3,197 | 3 | 3 | [] | no_license | // Author: zhangguoqiang01 <80176975@qq.com>
// Fixed size, lock-free, support multithreaded, circular queue
// especially suitable for one producer and mutiple consumer
// if one producer, Single_Push and Single_Pop is better
// otherwise, use Multi_Func
#include <stdio.h>
#include <sched.h>
#include "lock_free_queue.h"
template <class T>
LockFreeQueue<T>::LockFreeQueue()
{
m_read_idx = 0;
m_write_idx = 0;
m_max_read_idx = 0;
m_size = 0;
m_data = NULL;
}
template <class T>
LockFreeQueue<T>::~LockFreeQueue()
{}
template <class T>
bool LockFreeQueue<T>::Init(uint32_t size)
{
if (size <= 0) {
return false;
}
m_size = size + 1;
m_data = new T[m_size];
if (NULL == m_data) {
return false;
}
return true;
}
template <class T>
uint32_t LockFreeQueue<T>::GetIdx(uint32_t idx)
{
return (idx % m_size);
}
template <class T>
bool LockFreeQueue<T>::Multi_Push(const T& node)
{
uint32_t cur_read_idx;
uint32_t cur_write_idx;
uint32_t new_write_idx;
do {
cur_read_idx = m_read_idx;
cur_write_idx = m_write_idx;
new_write_idx = GetIdx(cur_write_idx + 1);
if (new_write_idx == GetIdx(cur_read_idx)) {
// full
return false;
}
} while (!CAS(&m_write_idx, cur_write_idx, new_write_idx));
m_data[cur_write_idx] = node;
while (!CAS(&m_max_read_idx, cur_write_idx, new_write_idx)) {
sched_yield();
}
return true;
}
template <class T>
bool LockFreeQueue<T>::Single_Push(const T& node)
{
uint32_t cur_read_idx;
uint32_t cur_write_idx;
uint32_t new_write_idx;
cur_read_idx = m_read_idx;
cur_write_idx = m_write_idx;
new_write_idx = GetIdx(cur_write_idx + 1);
if (new_write_idx == GetIdx(cur_read_idx)) {
// full
return false;
}
m_data[cur_write_idx] = node;
// atomic m_write_idx = new_write_idx
__sync_val_compare_and_swap(&m_write_idx, m_write_idx, new_write_idx);
return true;
}
template <class T>
bool LockFreeQueue<T>::Multi_Pop(T& node)
{
uint32_t cur_read_idx;
uint32_t cur_max_read_idx;
uint32_t new_read_idx;
do {
cur_read_idx = m_read_idx;
cur_max_read_idx = m_max_read_idx;
new_read_idx = GetIdx(cur_read_idx + 1);
if (cur_read_idx == cur_max_read_idx) {
// empty or not commit
return false;
}
node = m_data[cur_read_idx];
} while (!CAS(&m_read_idx, cur_read_idx, new_read_idx));
return true;
}
template <class T>
bool LockFreeQueue<T>::Single_Pop(T& node)
{
uint32_t cur_read_idx;
uint32_t cur_max_read_idx;
uint32_t new_read_idx;
do {
cur_read_idx = m_read_idx;
cur_max_read_idx = m_write_idx;
new_read_idx = GetIdx(cur_read_idx + 1);
if (cur_read_idx == cur_max_read_idx) {
// empty or not commit
return false;
}
node = m_data[cur_read_idx];
} while (!CAS(&m_read_idx, cur_read_idx, new_read_idx));
return true;
}
template <class T>
void LockFreeQueue<T>::Release()
{
if (NULL != m_data) {
delete[] m_data;
m_data = NULL;
}
return;
}
| true |
f9f4b9a0840a1ff25615dffbd825e7dabdae0a81 | C++ | stdstring/leetcode | /Algorithms/Tasks.1001.1500/1054.DistantBarcodes/solution.cpp | UTF-8 | 1,723 | 3.3125 | 3 | [
"MIT"
] | permissive | #include <queue>
#include <utility>
#include <vector>
#include "gtest/gtest.h"
namespace
{
class Solution
{
public:
[[nodiscard]] std::vector<int> rearrangeBarcodes(std::vector<int> const &barcodes) const
{
std::unordered_map<int, size_t> valuesCount;
for (int barcode : barcodes)
++valuesCount[barcode];
auto cmp = [](std::pair<int, size_t> const &l, std::pair<int, size_t> const &r){ return (l.second < r.second) || ((l.second == r.second) && (l.first < r.first)); };
std::priority_queue<std::pair<int, size_t>, std::vector<std::pair<int, size_t>>, decltype(cmp)> queue(cmp);
for (auto entry : valuesCount)
queue.push(entry);
std::vector<int> result;
while (queue.size() > 1)
{
std::pair<int, size_t> firstEntry(queue.top());
queue.pop();
std::pair<int, size_t> secondEntry(queue.top());
queue.pop();
result.push_back(firstEntry.first);
result.push_back(secondEntry.first);
if (firstEntry.second > 1)
queue.emplace(firstEntry.first, firstEntry.second - 1);
if (secondEntry.second > 1)
queue.emplace(secondEntry.first, secondEntry.second - 1);
}
if (!queue.empty())
result.push_back(queue.top().first);
return result;
}
};
}
namespace DistantBarcodesTask
{
TEST(DistantBarcodesTaskTests, Examples)
{
constexpr Solution solution;
ASSERT_EQ(std::vector<int>({2, 1, 2, 1, 2, 1}), solution.rearrangeBarcodes({1, 1, 1, 2, 2, 2}));
ASSERT_EQ(std::vector<int>({1, 3, 1, 2, 1, 3, 2, 1}), solution.rearrangeBarcodes({1, 1, 1, 1, 2, 2, 3, 3}));
}
} | true |
5f28e9017d2c318ce63085ed6adf0a1c098d74e3 | C++ | sumonmd/Algorithm | /Pascal_Pattern.cpp | UTF-8 | 613 | 3.109375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int pascal[53][53];
void pascal_pattern()
{
pascal[0][0]=1;
pascal[1][0]=1;
pascal[1][1]=1;
int j;
for(int i = 2;i<53;i++){
pascal[i][0]=1;
for(j=1;j<53;j++){
pascal[i][j]=pascal[i-1][j]+pascal[i-1][j-1];
}
pascal[i][j]=1;
}
}
int main()
{
int n;
cin>>n;
pascal_pattern();
for(int i=0;i<n;i++){
for(int j=0;j<n-i;j++){
cout<<" ";
}
for(int k=0;k<=i;k++){
cout<<pascal[i][k]<<" ";
}
cout<<endl;
}
return 0;
}
| true |
2875c588958463446cb95eec6d247b90730490e6 | C++ | Nordaj/LilEngie | /LilEngie/Core/src/Graphics/ShaderReader.cpp | UTF-8 | 717 | 3.34375 | 3 | [
"MIT"
] | permissive | #include <string>
#include <fstream>
#include "ShaderReader.h"
void ShaderReader::ReadShader(std::string *vertex, std::string *surface, std::string path)
{
//Create ifstream
std::ifstream file = std::ifstream(path);
//Use to keep track
int currentType = 0; //0=undef, 1=vert, 2=surf
//Go through stream
std::string line;
if (file.is_open())
{
while (std::getline(file, line))
{
//Check shader type
if (line == "#vert")
{
currentType = 1;
continue;
}
else if (line == "#surf")
{
currentType = 2;
continue;
}
//Append current line
if (currentType == 1)
vertex->append(line + "\n");
else if (currentType == 2)
surface->append(line + "\n");
}
}
}
| true |
628950660722f17e8b4e1f494eba776e9b28c937 | C++ | Lurgypai/Runny | /Walkie/SquareShape.h | UTF-8 | 414 | 2.796875 | 3 | [] | no_license | #pragma once
#include "MSF.h"
class SquareShape : public msf::Shape {
public:
SquareShape(float left_, float top_, float width, float height);
~SquareShape();
void setTop(float top);
void setLeft(float left);
void setWidth(float width);
void setHeight(float height);
sf::FloatRect getBoundingBox() const override;
std::unique_ptr<msf::Shape> clone() override;
private:
float width;
float height;
};
| true |
0a78c11c722bc91a345819ef5a372fa916c0a0af | C++ | greenfox-zerda-sparta/nmate91 | /week_04/11-11/src/JukeBox.cpp | UTF-8 | 1,992 | 3.140625 | 3 | [] | no_license | #include "JukeBox.h"
JukeBox::JukeBox() : songs() {
songs.songs = NULL;
}
void JukeBox::add_song(Song& song) {
if (&song != NULL) {
songs.push_song(song);
}
}
void JukeBox::rate_song(Song& song, double value) {
if (song.get_genre() == "Rock" && value <= 5 && value >= 2) {
song.set_rating(value);
}
else if (song.get_genre() == "Pop" && value <= 5 && value >= 1) {
song.set_rating(value);
}
else if (song.get_genre() == "Reggie" && value <= 4 && value >= 1) {
song.set_rating(value);
}
return;
}
double JukeBox::get_artist_rating(string _artist) {
double artist_rate = 0;
int count_artist = 0;
for (int i = 0; i < songs.song_count; i++) {
if (songs.songs[i]->get_artist() == _artist) {
artist_rate = artist_rate + songs.songs[i]->get_avg_song();
count_artist++;
}
}
return (artist_rate / count_artist);
}
double JukeBox::get_genre_rating(string _genre) {
double genre_rate = 0;
double count_genre = 0;
for (int i = 0; i < songs.song_count; i++) {
if (songs.songs[i]->get_genre() == _genre) {
genre_rate = genre_rate + songs.songs[i]->get_avg_song();
count_genre++;
}
}
return (genre_rate / count_genre);
}
string JukeBox::get_top_title() {
string top_title;
double top_title_rate = 0;
if (songs.songs != NULL) {
for (int i = 0; i < songs.song_count; i++) {
if (songs.songs[i]->get_avg_song() > top_title_rate) {
top_title_rate = songs.songs[i]->get_avg_song();
top_title = songs.songs[i]->get_title();
}
}
}
return top_title;
}
string JukeBox::get_top_genre() {
if (songs.songs != NULL) {
string top_genre = songs.songs[0]->get_genre();
for (int i = 1; i < songs.song_count; i++) {
if (get_genre_rating(songs.songs[i]->get_genre()) > get_genre_rating(top_genre)) {
top_genre = songs.songs[i]->get_genre();
}
return top_genre;
}
}
return "There are no songs stored in JukeBox.";
}
| true |
87559a47495bec90d4a7a353553e07418c261c33 | C++ | peteward44/raytracer | /source/SDL/Exception.h | UTF-8 | 936 | 2.84375 | 3 | [
"MIT"
] | permissive |
#ifndef EXCEPTION_H
#define EXCEPTION_H
#include <string>
#include <exception>
namespace SDL
{
class Exception : public std::exception
{
private:
std::string message;
public:
Exception()
{}
virtual ~Exception() throw()
{}
Exception(const std::string& message)
: message(message)
{
}
inline std::string GetMessage() const
{ return message; }
};
class NotImplementedException : public Exception
{
};
class EventException : public Exception
{
};
class SurfaceException : public Exception
{
public:
SurfaceException(const std::string& message) : Exception(message)
{}
SurfaceException()
{}
};
class SurfaceLockedException : public Exception
{
};
class SurfaceLostException : public Exception
{
};
class CDRomException : public Exception
{
public:
CDRomException(const std::string& message) : Exception(message)
{}
CDRomException()
{}
};
}
#endif
| true |
9006f27f3af4388d9dba0401bd97c4abd27565de | C++ | FedeGB/7559-TP1 | /src/Utils.cpp | UTF-8 | 1,163 | 3.21875 | 3 | [] | no_license | //
// Created by fedenote on 9/25/16.
//
#include "Utils.h"
#include <sys/types.h>
#include <unistd.h>
int getRandomInt(int min, int max){
srand(getpid());
return rand()%(max-min + 1) + min;
}
void trim(std::string &str) {
const std::string whitespace = " \t";
const auto strBegin = str.find_first_not_of(whitespace);
if (strBegin == std::string::npos)
return; // vacio
const auto strEnd = str.find_last_not_of(whitespace);
const auto strRange = strEnd - strBegin + 1;
str = str.substr(strBegin, strRange);
}
bool stringIsInt(std::string str) {
if(str.empty() || ((!isdigit(str[0])) && (str[0] != '-')))
return false;
char * pointer ;
strtol(str.c_str(), &pointer, 10) ;
return (*pointer == 0) ;
}
bool stringIsValidPrice(std::string str) {
std::istringstream iss(str);
float f;
iss >> std::noskipws >> f; // Espacio al principio es considerado como invalido
if(str[0] == '-') return false; // No puede ser negativo
return iss.eof() && !iss.fail(); // Chequeamos que sea un float valido
}
void simularAccion(int minT, int maxT) {
sleep(getRandomInt(minT, maxT));
} | true |
99ac8c26e88afb0884e468ab8f8d698c1eee1a23 | C++ | AMatrix/AMatrix | /test/test_matrix_assign.cpp | UTF-8 | 4,338 | 2.96875 | 3 | [
"MIT"
] | permissive | #include "amatrix.h"
#include "checks.h"
template <std::size_t TSize1, std::size_t TSize2>
int TestZeroMatrixAssign() {
AMatrix::Matrix<double, TSize1, TSize2> a_matrix;
a_matrix = AMatrix::ZeroMatrix<double>(TSize1, TSize2);
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++)
AMATRIX_CHECK_EQUAL(a_matrix(i, j), 0.00);
return 0; // not failed
}
template <std::size_t TSize>
int TestIdentityMatrixAssign() {
AMatrix::Matrix<double, TSize, TSize> a_matrix;
a_matrix = AMatrix::IdentityMatrix<double>(TSize);
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++){
if (i == j) {
AMATRIX_CHECK_EQUAL(a_matrix(i, j), 1.00);
} else {
AMATRIX_CHECK_EQUAL(a_matrix(i, j), 0.00);
}
}
return 0; // not failed
}
template <std::size_t TSize1, std::size_t TSize2>
int TestMatrixAssign() {
AMatrix::Matrix<double, TSize1, TSize2> a_matrix;
AMatrix::Matrix<double, TSize1, TSize2> b_matrix;
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++)
a_matrix(i, j) = 2.33 * i - 4.52 * j;
b_matrix = a_matrix;
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++)
AMATRIX_CHECK_EQUAL(b_matrix(i, j), 2.33 * i - 4.52 * j);
return 0; // not failed
}
template <std::size_t TSize1, std::size_t TSize2>
int TestMatrixExpressionAssign() {
AMatrix::Matrix<double, TSize1, TSize2> a_matrix;
AMatrix::Matrix<double, TSize1, TSize2> b_matrix;
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++)
a_matrix(i, j) = 2.33 * i - 4.52 * j;
b_matrix = a_matrix * 2.00;
for (std::size_t i = 0; i < a_matrix.size1(); i++)
for (std::size_t j = 0; j < a_matrix.size2(); j++)
AMATRIX_CHECK_EQUAL(b_matrix(i, j), 2.00* (2.33 * i - 4.52 * j));
return 0; // not failed
}
int main() {
int number_of_failed_tests = 0;
number_of_failed_tests += TestZeroMatrixAssign<1, 1>();
number_of_failed_tests += TestZeroMatrixAssign<1, 2>();
number_of_failed_tests += TestZeroMatrixAssign<2, 1>();
number_of_failed_tests += TestZeroMatrixAssign<2, 2>();
number_of_failed_tests += TestZeroMatrixAssign<3, 1>();
number_of_failed_tests += TestZeroMatrixAssign<3, 2>();
number_of_failed_tests += TestZeroMatrixAssign<3, 3>();
number_of_failed_tests += TestZeroMatrixAssign<1, 3>();
number_of_failed_tests += TestZeroMatrixAssign<2, 3>();
number_of_failed_tests += TestZeroMatrixAssign<3, 3>();
number_of_failed_tests += TestIdentityMatrixAssign<1>();
number_of_failed_tests += TestIdentityMatrixAssign<2>();
number_of_failed_tests += TestIdentityMatrixAssign<3>();
number_of_failed_tests += TestMatrixAssign<1, 1>();
number_of_failed_tests += TestMatrixAssign<1, 2>();
number_of_failed_tests += TestMatrixAssign<2, 1>();
number_of_failed_tests += TestMatrixAssign<2, 2>();
number_of_failed_tests += TestMatrixAssign<3, 1>();
number_of_failed_tests += TestMatrixAssign<3, 2>();
number_of_failed_tests += TestMatrixAssign<3, 3>();
number_of_failed_tests += TestMatrixAssign<1, 3>();
number_of_failed_tests += TestMatrixAssign<2, 3>();
number_of_failed_tests += TestMatrixAssign<3, 3>();
number_of_failed_tests += TestMatrixExpressionAssign<1, 1>();
number_of_failed_tests += TestMatrixExpressionAssign<1, 2>();
number_of_failed_tests += TestMatrixExpressionAssign<2, 1>();
number_of_failed_tests += TestMatrixExpressionAssign<2, 2>();
number_of_failed_tests += TestMatrixExpressionAssign<3, 1>();
number_of_failed_tests += TestMatrixExpressionAssign<3, 2>();
number_of_failed_tests += TestMatrixExpressionAssign<3, 3>();
number_of_failed_tests += TestMatrixExpressionAssign<1, 3>();
number_of_failed_tests += TestMatrixExpressionAssign<2, 3>();
number_of_failed_tests += TestMatrixExpressionAssign<3, 3>();
std::cout << number_of_failed_tests << "tests failed" << std::endl;
return number_of_failed_tests;
}
| true |
5589e9162063c29144b1ed60c8a7004d61259696 | C++ | TankMermaid/GraphAligner | /CommonUtils.cpp | UTF-8 | 3,198 | 2.703125 | 3 | [] | no_license | #include "CommonUtils.h"
#include "stream.hpp"
namespace CommonUtils
{
void mergeGraphs(vg::Graph& graph, const vg::Graph& part)
{
for (size_t i = 0; i < part.node_size(); i++)
{
auto node = graph.add_node();
node->set_id(part.node(i).id());
node->set_sequence(part.node(i).sequence());
node->set_name(part.node(i).name());
}
for (size_t i = 0; i < part.edge_size(); i++)
{
auto edge = graph.add_edge();
edge->set_from(part.edge(i).from());
edge->set_to(part.edge(i).to());
edge->set_from_start(part.edge(i).from_start());
edge->set_to_end(part.edge(i).to_end());
edge->set_overlap(part.edge(i).overlap());
}
}
vg::Graph LoadVGGraph(std::string filename)
{
vg::Graph result;
std::ifstream graphfile { filename, std::ios::in | std::ios::binary };
std::function<void(vg::Graph&)> lambda = [&result](vg::Graph& g) {
mergeGraphs(result, g);
};
stream::for_each(graphfile, lambda);
return result;
}
std::vector<vg::Alignment> LoadVGAlignments(std::string filename)
{
std::vector<vg::Alignment> result;
std::ifstream graphfile { filename, std::ios::in | std::ios::binary };
std::function<void(vg::Alignment&)> lambda = [&result](vg::Alignment& g) {
result.push_back(g);
};
stream::for_each(graphfile, lambda);
return result;
}
vg::Alignment LoadVGAlignment(std::string filename)
{
vg::Alignment result;
std::ifstream graphfile { filename, std::ios::in | std::ios::binary };
std::function<void(vg::Alignment&)> lambda = [&result](vg::Alignment& g) {
result = g;
};
stream::for_each(graphfile, lambda);
return result;
}
std::string ReverseComplement(std::string str)
{
std::string result;
result.reserve(str.size());
for (int i = str.size()-1; i >= 0; i--)
{
switch (str[i])
{
case 'A':
case 'a':
result += 'T';
break;
case 'C':
case 'c':
result += 'G';
break;
case 'T':
case 't':
result += 'A';
break;
case 'G':
case 'g':
result += 'C';
break;
case 'N':
case 'n':
result += 'N';
break;
case 'U':
case 'u':
result += 'A';
break;
case 'R':
case 'r':
result += 'Y';
break;
case 'Y':
case 'y':
result += 'R';
break;
case 'K':
case 'k':
result += 'M';
break;
case 'M':
case 'm':
result += 'K';
break;
case 'S':
case 's':
result += 'S';
break;
case 'W':
case 'w':
result += 'W';
break;
case 'B':
case 'b':
result += 'V';
break;
case 'V':
case 'v':
result += 'B';
break;
case 'D':
case 'd':
result += 'H';
break;
case 'H':
case 'h':
result += 'D';
default:
assert(false);
}
}
return result;
}
}
BufferedWriter::BufferedWriter(std::ostream& stream) : stream(stream) {};
BufferedWriter& BufferedWriter::operator<<(FlushClass f)
{
flush();
return *this;
}
void BufferedWriter::flush()
{
stringstream << std::endl;
stream << stringstream.str();
stringstream.str("");
}
| true |
d0694534e107722e58e1ebb4eb73b29fd2e7a0b3 | C++ | theawless/sr-lib | /base/inc/codebook.h | UTF-8 | 1,058 | 2.859375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <vector>
#include "feature.h"
struct Codebook
{
public:
std::vector<Feature> centroids;
/// Return whether empty.
bool empty() const;
/// Find the buckets where the features lie in codebook.
std::vector<int> observations(const std::vector<Feature> &features) const;
/// Operators for loading and saving.
friend std::istream &operator>>(std::istream &input, Codebook &codebook);
friend std::ostream &operator<<(std::ostream &output, const Codebook &codebook);
};
/// An Algorithm for Vector Quantizer Design - Y. Linde, A. Buzo and R. Gray.
class LBG
{
public:
/// Constructor.
LBG(int x_codebook);
/// Call Kmeans coroutine and split the centroids and till codebook size is reached.
Codebook generate(const std::vector<Feature> &universe) const;
private:
static constexpr double epsilon = 0.025;
const int x_codebook;
/// Find the initial centroid of the universe.
static Feature mean(const std::vector<Feature> &universe);
/// Split the given centroids.
static void split(std::vector<Feature> ¢roids);
};
| true |