blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
6fd8452dc085236caaea381f04b86e4a27727e9a
889ca74cbc316998ab398d59793bc2582d3bd739
/Engine/ModuleScene.cpp
db0e4071c198e06ba7c1e27130162d31c293fc2f
[ "MIT" ]
permissive
Beautiful-Engines/Engine
ee28cc318973694c3a5db78315ff7bbc5c5dcd22
fab1b2415d63218078cc6f2b2a33676e9ef45543
refs/heads/master
2020-07-22T22:20:04.503652
2019-12-29T20:16:11
2019-12-29T20:16:11
207,347,488
0
0
MIT
2019-12-29T18:01:32
2019-09-09T15:54:35
C++
UTF-8
C++
false
false
15,031
cpp
ModuleScene.cpp
#include "Application.h" #include "ModuleWindow.h" #include "ModuleRenderer3D.h" #include "ModuleGUI.h" #include "ModuleInput.h" #include "ModuleImport.h" #include "ModuleFileSystem.h" #include "ModuleResource.h" #include "GameObject.h" #include "Primitive.h" #include "ComponentTransform.h" #include "ComponentTexture.h" #include "ComponentMesh.h" #include "ComponentCamera.h" #include "ModuleTimeManager.h" #include "WindowHierarchy.h" #include "ModuleScene.h" #include "ResourceMesh.h" #include "ResourceAnimation.h" #include "glew\glew.h" #include <fstream> #include <iomanip> ModuleScene::ModuleScene(bool start_enabled) : Module(start_enabled) { name = "Scene"; } ModuleScene::~ModuleScene() { } bool ModuleScene::Init() { LOG("Creating Scene"); return true; } bool ModuleScene::Start() { CreateGrid(); GameObject *root = CreateGameObject("root"); CreateCamera(); CreateQuadtree(); App->resource->LoadAllAssets(); return true; } update_status ModuleScene::PreUpdate(float dt) { return UPDATE_CONTINUE; } update_status ModuleScene::Update(float dt) { if (App->timemanager->saved) { App->scene->SaveScene(true); App->timemanager->saved = false; } if (App->timemanager->load) { App->scene->LoadScene(true); App->timemanager->load = false; } if (App->renderer3D->grid) DrawGrid(); game_objects[0]->Update(dt); if(debug_quadtree) quadtree.Draw(); FrustrumCulling(); if (App->input->GetKey(SDL_SCANCODE_LCTRL) == KEY_REPEAT && App->input->GetKey(SDL_SCANCODE_S) == KEY_DOWN) SaveScene(); if (App->input->GetKey(SDL_SCANCODE_LCTRL) == KEY_REPEAT && App->input->GetKey(SDL_SCANCODE_L) == KEY_DOWN) LoadScene(); if (App->input->GetKey(SDL_SCANCODE_1) == KEY_DOWN && App->timemanager->play) { GetGameObjectByName("Assets/skeleton@idle.fbx")->GetAnimation()->blend_id = GetGameObjectByName("Assets/skeleton@idle.fbx")->GetAnimation()->attack_animation->GetId(); GetGameObjectByName("Assets/skeleton@idle.fbx")->GetAnimation()->blend = true; GetGameObjectByName("Assets/skeleton@idle.fbx")->GetAnimation()->blend_loop = false; } else if (App->input->GetKey(SDL_SCANCODE_2) == KEY_REPEAT && App->timemanager->play && !GetGameObjectByName("Assets/skeleton@idle.fbx")->GetAnimation()->running) { GetGameObjectByName("Assets/skeleton@idle.fbx")->GetAnimation()->blend_id = GetGameObjectByName("Assets/skeleton@idle.fbx")->GetAnimation()->run_animation->GetId(); GetGameObjectByName("Assets/skeleton@idle.fbx")->GetAnimation()->blend = true; GetGameObjectByName("Assets/skeleton@idle.fbx")->GetAnimation()->blend_loop = true; GetGameObjectByName("Assets/skeleton@idle.fbx")->GetAnimation()->running = true; } else if (App->input->GetKey(SDL_SCANCODE_2) == KEY_UP && App->timemanager->play) { GetGameObjectByName("Assets/skeleton@idle.fbx")->GetAnimation()->resource_animation = GetGameObjectByName("Assets/skeleton@idle.fbx")->GetAnimation()->idle_animation; GetGameObjectByName("Assets/skeleton@idle.fbx")->GetAnimation()->blend = false; GetGameObjectByName("Assets/skeleton@idle.fbx")->GetAnimation()->running = false; } return UPDATE_CONTINUE; } update_status ModuleScene::PostUpdate(float dt) { return UPDATE_CONTINUE; } bool ModuleScene::CleanUp() { LOG("Cleaning Scene"); return true; } // Save void ModuleScene::SaveScene(bool _tmp) { std::string file; if (_tmp) file = ASSETS_FOLDER "scene.tmp"; else { LOG("Saving scene into %s", ASSETS_FOLDER"Scene.mgr"); file = ASSETS_FOLDER + std::string("scene") + OUR_SCENE_EXTENSION; } nlohmann::json json = { {"GameObjects", nlohmann::json::array()}, }; game_objects[0]->Save(json.find("GameObjects")); std::ofstream ofstream(file); ofstream << std::setw(4) << json << std::endl; } bool ModuleScene::LoadScene(bool _tmp) { std::string file; if (_tmp) file = ASSETS_FOLDER "scene.tmp"; else { LOG("Loading scene from %s", ASSETS_FOLDER"Scene.mgr"); file = ASSETS_FOLDER + std::string("scene") + OUR_SCENE_EXTENSION; } if (App->file_system->Exists(file.c_str())) { game_objects.clear(); std::ifstream ifstream(file); nlohmann::json json = nlohmann::json::parse(ifstream); nlohmann::json json_game_objects = json.find("GameObjects").value(); for (nlohmann::json::iterator iterator = json_game_objects.begin(); iterator != json_game_objects.end(); ++iterator) { nlohmann::json object = iterator.value(); uint parent_id = object["ParentUID"]; if (parent_id != 0) { GameObject* game_object = new GameObject(); game_object->SetName(object["Name"]); game_object->SetId(object["UID"]); game_object->is_static = object["IsStatic"]; if (object["Enable"]) game_object->Enable(); else game_object->Disable(); for (uint i = 0; i < game_objects.size(); ++i) { if (game_objects[i]->GetId() == parent_id) game_object->SetParent(game_objects[i]); } for (nlohmann::json::iterator components_it = object["Components"].begin(); components_it != object["Components"].end(); ++components_it) { nlohmann::json json_component = components_it.value(); Component* component; if (json_component["type"] == ComponentType::TRANSFORM) component = game_object->GetTransform(); else if (json_component["type"] == ComponentType::MESH) component = new ComponentMesh(game_object); else if (json_component["type"] == ComponentType::TEXTURE) component = new ComponentTexture(game_object); else if (json_component["type"] == ComponentType::ANIMATION) component = new ComponentAnimation(game_object); else if (json_component["type"] == ComponentType::BONE) component = new ComponentBone(game_object); else if (json_component["type"] == ComponentType::CAMERA) component = new ComponentCamera(game_object); component->Load(json_component); } game_object->GetTransform()->GetTransformMatrix(); AddGameObject(game_object, false); } else { GameObject* root = CreateGameObject("root"); root->SetId(object["UID"]); } } } else { LOG("File %s doesn't exist", ASSETS_FOLDER"Scene.mgr"); } return true; } GameObject* ModuleScene::CreateGameObject(std::string _name) { GameObject *game_object = new GameObject(); for (uint i = 0; i < game_objects.size(); ++i) { if (game_objects[i]->GetParent() == nullptr) game_object->SetParent(game_objects[0]); } game_object->SetName(_name); AddGameObject(game_object); return game_object; } void ModuleScene::ActiveBBDebug(bool active) { for (uint i = 0; i < game_objects.size(); ++i) { if(game_objects[i]->GetMesh()) game_objects[i]->GetMesh()->debug_bb = active; } } void ModuleScene::AddGameObject(GameObject* _game_object, bool _change_name) { if(_change_name) game_objects.push_back(ChangeNameByQuantities(_game_object)); else game_objects.push_back(_game_object); CreateQuadtree(); } void ModuleScene::DeleteGameObject(GameObject* _game_object) { // Delete children, recursive for (uint i = 0; i < game_objects.size(); ++i) { if (game_objects[i]->GetParent() == _game_object) { DeleteGameObject(game_objects[i]); i = 0; } } // Delete parent pointer, erase from children for (uint i = 0; i < game_objects.size(); ++i) { if (game_objects[i] == _game_object->GetParent()) { game_objects[i]->DeleteChild(_game_object); } } // Erase from game_objects for (auto iterator_go = game_objects.begin(); iterator_go < game_objects.end(); iterator_go++) { if (*iterator_go != nullptr && (*iterator_go) == _game_object) { RELEASE(*iterator_go); iterator_go = game_objects.erase(iterator_go); break; } } } GameObject* ModuleScene::GetSelected() { for (uint i = 0; i < game_objects.size(); ++i) { if (game_objects[i]->IsFocused()) { return game_objects[i]; } } return nullptr; } GameObject* ModuleScene::GetMainCamera() { for (uint i = 0; i < game_objects.size(); ++i) { if (game_objects[i]->GetCamera()) { return game_objects[i]; } } return nullptr; } void ModuleScene::ChangeSelected(GameObject* selected) { for (uint i = 0; i < game_objects.size(); ++i) { if (game_objects[i] != selected) { game_objects[i]->SetFocus(false); } } } void ModuleScene::SetSelected(GameObject* go) { for (uint i = 0; i < game_objects.size(); ++i) { if (game_objects[i] == go) { game_objects[i]->SetFocus(true); } } } const std::vector<GameObject*> ModuleScene::GetGameObjects() const { return game_objects; } GameObject* ModuleScene::GetGameObject(uint id) { for (uint i = 0; i < game_objects.size(); ++i) { if (game_objects[i]->GetId() == id) { return game_objects[i]; } } return nullptr; } GameObject* ModuleScene::GetGameObjectByName(std::string _name) { for (uint i = 0; i < game_objects.size(); ++i) { uint pos = game_objects[i]->GetName().find_last_of("_"); std::string name = game_objects[i]->GetName().substr(0, pos).c_str(); if (name == _name) { return game_objects[i]; } } return nullptr; } void ModuleScene::FrustrumCulling() { std::vector<GameObject*> objects_hit; for (uint i = 0; i < App->scene->GetGameObjects().size(); ++i) { if (AnyCamera()) { if (App->scene->GetGameObjects()[i]->GetCamera() != nullptr) { if (App->scene->GetGameObjects()[i]->GetCamera()->frustum_culling == true) { quadtree.Intersect(objects_hit, App->scene->GetGameObjects()[i]->GetCamera()->frustum); for (uint j = 0; j < App->scene->GetGameObjects().size(); ++j) { if (!App->scene->GetGameObjects()[j]->is_static) { if (App->scene->GetGameObjects()[j]->GetMesh()) { if (App->scene->GetGameObjects()[i]->GetCamera()->frustum.Intersects(App->scene->GetGameObjects()[j]->abb)) { objects_hit.push_back(App->scene->GetGameObjects()[j]); } } } } for (int i = 0; i < objects_hit.size(); ++i) { objects_hit[i]->GetMesh()->draw = true; } /*for (uint j = 0; j < objects_hit.size(); ++j) { if (objects_hit[j]->GetMesh()) { if (App->scene->GetGameObjects()[i]->GetCamera()->frustum.Intersects(objects_hit[j]->abb)) { if (App->renderer3D->camera->frustum.Intersects(objects_hit[j]->abb)) { objects_hit[j]->GetMesh()->draw = true; } } else { objects_hit[j]->GetMesh()->draw = false; } } }*/ } else { quadtree.Intersect(objects_hit, App->renderer3D->camera->frustum); for (uint j = 0; j < App->scene->GetGameObjects().size(); ++j) { if (!App->scene->GetGameObjects()[j]->is_static) { if (App->scene->GetGameObjects()[j]->GetMesh()) { if (App->renderer3D->camera->frustum.Intersects(App->scene->GetGameObjects()[j]->abb)) { objects_hit.push_back(App->scene->GetGameObjects()[j]); } } } } for (int i = 0; i < objects_hit.size(); ++i) { if (objects_hit[i]->GetMesh() != nullptr) objects_hit[i]->GetMesh()->draw = true; } } } } else { CreateCamera(); LOG("You always need to have at least one camera in the scene!") } } } bool ModuleScene::AnyCamera() { for (uint i = 0; i < App->scene->GetGameObjects().size(); ++i) { if (App->scene->GetGameObjects()[i]->GetCamera() != nullptr) { return true; } } return false; } void ModuleScene::CreateCamera() { GameObject *camera = CreateGameObject("camara"); ComponentCamera* cam = new ComponentCamera(camera); cam->frustum_culling = true; cam->main_camera = true; } GameObject* ModuleScene::ChangeNameByQuantities(GameObject* _game_object) { uint cont = 1; std::string name = _game_object->GetName(); for (uint i = 0; i < game_objects.size(); ++i) { if (game_objects[i]->GetName() == name + "_" + std::to_string(cont)) { cont++; i = 0; } } if (name != "root") _game_object->SetName(name.append("_" + std::to_string(cont))); return _game_object; } void ModuleScene::MouseClicking(const LineSegment& line) { std::map<float, GameObject*> selected; quadtree.Intersect(selected, line); for (uint i = 0; i < game_objects.size(); i++) { if (line.Intersects(game_objects[i]->abb)) { float hit_near, hit_far; if (line.Intersects(game_objects[i]->obb, hit_near, hit_far)) selected[hit_near] = game_objects[i]; } } GameObject* clicked = nullptr; for (std::map<float, GameObject*>::iterator it = selected.begin(); it != selected.end() && clicked == nullptr; it++) { const ResourceMesh* mesh = it->second->GetMesh()->GetResourceMesh(); if (mesh) { LineSegment local = line; local.Transform(it->second->GetTransform()->transform_matrix.Inverted()); for (uint v = 0; v < mesh->n_indexes; v += 3) { float3 v1(mesh->vertices[mesh->indexes[v]]); float3 v2(mesh->vertices[mesh->indexes[v + 1]]); float3 v3(mesh->vertices[mesh->indexes[v + 2]]); Triangle triangle(v1, v2, v3); if (local.Intersects(triangle, nullptr, nullptr)) { clicked = it->second; break; } } } } for (uint i = 0; i < game_objects.size(); i++) { if (game_objects[i] == clicked) { App->scene->SetSelected(game_objects[i]); App->scene->ChangeSelected(game_objects[i]); LOG("%s", game_objects[i]->GetName().c_str()); } } } void ModuleScene::DrawGrid() { glColor3f(1.f, 1.f, 1.f); glEnableClientState(GL_VERTEX_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, id_grid); glVertexPointer(3, GL_INT, 0, NULL); glDrawArrays(GL_LINES, 0, grid_vertices); glDisableClientState(GL_VERTEX_ARRAY); } void ModuleScene::CreateGrid() { grid_vertices = (grid_size + 1) * 12; uint *grides = new uint[grid_vertices]; for (int i = 0; i <= grid_size * 12; i += 12) { grides[i] = i / 6 - grid_size; grides[i + 1] = 0; grides[i + 2] = -grid_size; grides[i + 3] = i / 6 - grid_size; grides[i + 4] = 0; grides[i + 5] = grid_size; grides[i + 6] = grid_size; grides[i + 7] = 0; grides[i + 8] = i / 6 - grid_size; grides[i + 9] = -grid_size; grides[i + 10] = 0; grides[i + 11] = i / 6 - grid_size; } glGenBuffers(1, &id_grid); glBindBuffer(GL_ARRAY_BUFFER, id_grid); glBufferData(GL_ARRAY_BUFFER, sizeof(int) * grid_vertices, grides, GL_STATIC_DRAW); delete[] grides; } std::vector<GameObject*> ModuleScene::GetStaticGameObjects() { std::vector<GameObject*> static_game_objects; for (uint i = 0; i < game_objects.size(); ++i) { if (game_objects[i]->is_static) static_game_objects.push_back(game_objects[i]); } return static_game_objects; } void ModuleScene::CreateQuadtree() { const math::float3 center(0.0f, 0.0f, 0.0f); const math::float3 size(100, 40, 100); math::AABB boundary; boundary.SetFromCenterAndSize(center, size); quadtree.Create(boundary); RecalculateQuadtree(); } void ModuleScene::RecalculateQuadtree() { for (uint i = 0; i < GetStaticGameObjects().size(); ++i) App->scene->quadtree.Insert(GetStaticGameObjects()[i]); }
8421012d8461064c4d0abcb06cbbaa040c7a4784
f0f576e84c3e36f56167544869f5e5ac9ab75adc
/TIMLE/SourceFiles/States/state.cpp
363592b324fc681872a8ff8aaddd5387b3c5d776
[ "Apache-2.0" ]
permissive
Vasar007/TIMLE
89386279dfe0236b0a08663830db24016dc661e0
9beaf5f122f8fbbd23d7dcb89a297378fdd68559
refs/heads/master
2021-06-24T19:59:51.215100
2020-03-21T23:43:58
2020-03-21T23:43:58
102,362,098
1
1
Apache-2.0
2020-03-17T21:52:32
2017-09-04T13:03:13
C++
UTF-8
C++
false
false
1,373
cpp
state.cpp
#include "state_stack.hpp" #include "States/state.hpp" State::CurrentSettings::CurrentSettings(const sf::Vector2u windowSize, const WindowStyle windowStyle, const float musicVolume, const Fonts::ID fontType, const ActualLanguage language, const DebugMode debugMode) : mWindowSize(windowSize) , mWindowStyle(windowStyle) , mMusicVolume(musicVolume) , mFontType(fontType) , mLanguage(language) , mDebugMode(debugMode) , mPressedButton() , mHasAnyChanges(false) { } State::Context::Context(sf::RenderWindow& window, TextureHolder& textures, FontHolder& fonts, SoundBufferHolder& sounds, PlayerInfo& playerInfo, CurrentSettings& currentSettings) : mWindow(&window) , mTextures(&textures) , mFonts(&fonts) , mSounds(&sounds) , mPlayerInfo(&playerInfo) , mCurrentSettings(&currentSettings) { } State::State(StateStack& stack, const Context context) : _stack(&stack) , _context(context) { } void State::requestStackPush(const States::ID stateID) const { _stack->pushState(stateID); } void State::requestStackPop() const { _stack->popState(); } void State::requestStateClear() const { _stack->clearStates(); } State::Context State::getContext() const noexcept { return _context; }
557e1643916a70ec69725cd9d0809e8e67198ec7
b564a92684f51be4cccb5d9a90fc4c129b8b5de2
/KiteOpenGLDriver/WindowsMouseMessageHandler.cpp
6fafbca641c8334af869a1a40555db5f573d9e55
[ "BSD-3-Clause" ]
permissive
awyhhwxz/KiteOpenGLDriver
0c84f89b8a7fa34990582d0c2acfeeaccc6a02be
cce0a67b93431d3958a485d0cc9420ecb6295d42
refs/heads/master
2020-03-22T03:46:10.035046
2019-02-25T14:34:20
2019-02-25T14:34:20
139,451,343
2
0
null
null
null
null
UTF-8
C++
false
false
1,589
cpp
WindowsMouseMessageHandler.cpp
#include "stdafx.h" #include "WindowsMouseMessageHandler.h" WindowsMouseMessageHandler::WindowsMouseMessageHandler() { } WindowsMouseMessageHandler::~WindowsMouseMessageHandler() { } void WindowsMouseMessageHandler::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_MOUSEMOVE: { kite_driver::KiteDriverInputManager::Instance()->InvokeMouseMove(GetMousePosition(lParam)); } break; case WM_LBUTTONDOWN: case WM_RBUTTONDOWN: case WM_MBUTTONDOWN: kite_driver::KiteDriverInputManager::Instance()->InvokeButtonDown(GetMouseButtonType(message), GetMousePosition(lParam)); break; case WM_LBUTTONUP: case WM_RBUTTONUP: case WM_MBUTTONUP: kite_driver::KiteDriverInputManager::Instance()->InvokeButtonUp(GetMouseButtonType(message), GetMousePosition(lParam)); break; case WM_MOUSEWHEEL: kite_driver::KiteDriverInputManager::Instance()->OnMouseWheelRoll((INT)wParam); break; default: break; } } kite_driver::MouseButtonType WindowsMouseMessageHandler::GetMouseButtonType(UINT message) { switch (message) { case WM_LBUTTONDOWN: case WM_LBUTTONUP: return kite_driver::MouseButtonType::MBT_LEFT; case WM_RBUTTONDOWN: case WM_RBUTTONUP: return kite_driver::MouseButtonType::MBT_RIGHT; case WM_MBUTTONDOWN: case WM_MBUTTONUP: return kite_driver::MouseButtonType::MBT_MIDDLE; default: break; } return kite_driver::MouseButtonType(); } kite_math::Vector2f WindowsMouseMessageHandler::GetMousePosition(LPARAM lParam) { auto x = LOWORD(lParam); auto y = HIWORD(lParam); return kite_math::Vector2f(x, y); }
8dc3c3a79b7630a9b0c8c772190a579f4508eb85
debc0908d22666cedb051d309d58865735b8fb04
/AR_Landkaart_Leroy/AR_Landkaart/main.cpp
1bacfd5847f83bea609e14bd0a9a03782d4cd68b
[]
no_license
E-pep/2018_beeldinterpretatie_Leroy_Paul
c5c746b6dc832b666101ad3b595a91714b8b389a
4a8fe1070d367ade025b3c7173fac513c9d75610
refs/heads/master
2021-07-12T05:03:30.880425
2020-06-09T21:25:20
2020-06-09T21:25:20
153,741,227
0
0
null
null
null
null
UTF-8
C++
false
false
14,483
cpp
main.cpp
#include <iostream> #include <opencv2/opencv.hpp> #include <chrono> using namespace std; using namespace cv; /// Global variables // default values for the sliders int thresholdSlider = 12; double thresholdSliderDouble = (double)thresholdSlider/100; int ImageWidth = 400; int ImageHeight = 400; ///functions //get a vector filled with every country name vector<string> getCountrylist(string pathName); //get a vector filled with every country contour vector<vector<Point>> getCountryContours(string pathName); // returns the contour of the country with it's center closest to frame center vector<Point> ContoursFrame_WholeMap(Mat image); // vector with all the vacation pictures. Index = which country vector<vector<Mat>> get_vacation_pictures(vector<string> countrynames, string pathNameToVacation); // static void on_trackbar( int, void* ) { thresholdSliderDouble = (double)thresholdSlider/100; } int main(int argc,const char** argv) { ///The commandlineparser for variables CommandLineParser parser(argc,argv, "{help h | | show this message}" "{pathContours pc | | Path to the directory containing the contours(required)}" "{pathVacation pv | | Path to the directory containing the vacation pictures(required)}" ); // Help printing if(parser.has("help") || argc <= 1) { cerr << "Please use absolute paths when supplying your images." << endl; parser.printMessage(); return 0; } // Parser fail if (!parser.check()) { parser.printErrors(); return -1; } ///-------------------------------------------------------- Variables ----------------------------------------------------------------------------------------------- string pathName(parser.get<string>("pathContours")); string pathNameToVacation(parser.get<string>("pathVacation")); string defaultPictureName = "default.jpg"; //check if arguments are filled in if(pathName.empty() ) { cerr << "give the contour pathname please" << endl; return -1; } if(pathName.empty() ) { cerr << "give the vacation pathname please" << endl; return -1; } Mat defaultPicture; // vector filled with names of everey country with a contour vector<string> CountryList = getCountrylist(pathName); // Same order as countryList vector vector<vector<Mat>> picturesVector; //check all names in the vector cout << "countrylist contains:" << endl; for(int countList = 0; countList < CountryList.size(); countList++) { cout << CountryList.at(countList) << endl; } // vector filled with the contourpoints of the countries => used as template vector<vector<Point>> CountryContours = getCountryContours(pathName); // get the vacation pictures and sture them in a vector of vectors. Index = country picturesVector = get_vacation_pictures(CountryList, pathNameToVacation); char stop; Mat frame; vector<Point> hull1; vector<Point> hull2; vector<Point> hull3; double testshape = 100; int index; double temp_testshape = 100; Mat FrameSmall; /// ------------------------------------------------------------------------ reading in Images------------------------------------------------- defaultPicture = imread(defaultPictureName, IMREAD_COLOR); // Check for invalid input if( defaultPicture.empty() ) { cout << "Could not open or find image1" << std::endl ; return -1; } // make the image smaller resize(defaultPicture, defaultPicture, Size(ImageWidth, ImageHeight)); //read out webcam //cap 1 is the external camera VideoCapture cap(1); if(!cap.isOpened()) { cout << "Cam could notbe opened" << endl; return -1; } /// ------------------------------------------------------------------------ -------------------------------------------------------------------- //create a window with a trackbar for the threshold namedWindow("thresholds", WINDOW_AUTOSIZE); createTrackbar( "threshold", "thresholds", &thresholdSlider, 50, on_trackbar ); imshow( "thresholds",defaultPicture); while (true) { // put the captured frame in Mat object cap >> frame; // Find the contour of the country in the center hull1 = ContoursFrame_WholeMap(frame); if(!hull1.empty()) { testshape = 100; // We iterate over every country contour and compare it with the contour of the country in the center for(int matchShapeCounter = 0; matchShapeCounter < CountryContours.size(); matchShapeCounter++) { // calculate similarity between 2 contours, how lower the result, how more simularity there is // rotation and scale invariant // based on hue moments // source: https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_contours/py_contours_more_functions/py_contours_more_functions.html temp_testshape = matchShapes(hull1, CountryContours.at(matchShapeCounter),1,1); cout << "match value: " <<temp_testshape << endl; // save the most similar country shape, and below certain threshold to ensure we have a country if(temp_testshape <= testshape && temp_testshape < thresholdSliderDouble) { testshape = temp_testshape; index = matchShapeCounter; } } //cout << "testshape:" << index << endl; cout << "detected country" << CountryList.at(index) << endl; cout << "test shape" << testshape << endl; cout << "thresholdSliderDouble" << thresholdSliderDouble << endl; } resize(frame, FrameSmall, Size(ImageWidth, ImageHeight)); imshow( "thresholds",FrameSmall); // iterate over the images of the found country and show them for(int ImageCounter = 0; ImageCounter <picturesVector.at(index).size(); ImageCounter++) { string temp_string = "foto"+ImageCounter; if(testshape < thresholdSliderDouble) { imshow(temp_string, picturesVector.at(index).at(ImageCounter)); } // if no country found, show default image else { imshow(temp_string, defaultPicture); } // imshow(temp_string, picturesVector.at(index).at(ImageCounter)); } //When q is pressed, the program stops stop = (char) waitKey(30); if (stop == 'q') { break; } } return 0; } vector<string> getCountrylist(string pathName) { vector<string> returnNames; vector<String> fileNames; String fullPathName = pathName + "/*.jpg"; // read every filename in directory glob(fullPathName, fileNames, false); // we delete the.jpg and only save the name itself string tempString; for (size_t i=0; i<fileNames.size(); i++) { tempString = fileNames.at(i); tempString.erase(0,pathName.length()+1); tempString.pop_back(); tempString.pop_back(); tempString.pop_back(); tempString.pop_back(); cout << "found file for the list: " << tempString << endl; returnNames.push_back(tempString); } return returnNames; } vector<vector<Point>> getCountryContours(string pathName) { // This is a method based on Colour like Labo 2. This is because the first version used colour to detect a country. // The disadvantage was we could only show 1 contour of a country // vector filled with the contours of the countries vector<vector<Point>> contoursList; //variables Mat CountryImage; Mat CountryImage_hsv; Mat Total_Contour; //temporary contour vector for pushing in other vector vector<Point> contour; Point2f center; float radius; //stick .jpg after string String fullPathName = pathName + "/*.jpg"; //vector that keeps the full path filenames vector<String> fileNames; //find all pathnames in directory glob(fullPathName, fileNames, false); // loop all pictures found in file size_t picture_count = fileNames.size(); //number of png files in images folder for (size_t i=0; i<picture_count; i++) { cout << "found file: " << fileNames.at(i) << endl; // read in Images and put in Mat variable CountryImage = imread(fileNames.at(i), IMREAD_COLOR); // Convert to HSV space, easier for different tints of green cvtColor(CountryImage, CountryImage_hsv, CV_BGR2HSV); // We put a threshold on the image and only keep the green parts Mat Image_thresholded(CountryImage.rows, CountryImage.cols, CV_8UC3); inRange(CountryImage_hsv, Scalar(0, 100, 0), Scalar(180, 255, 255), Image_thresholded); // We find all the contours in the picture vector< vector<Point>> Allcontours; findContours(Image_thresholded.clone(), Allcontours, RETR_EXTERNAL, CHAIN_APPROX_NONE); // We only keep the biggest contour for(size_t j=0; j<Allcontours.size(); j++) { // only the biggest country to compare if(contourArea(Allcontours.at(j)) > 50000) { contoursList.push_back(Allcontours.at(j)); } } } // drawcontours needs a vector of vectorpoints vector< vector<Point>> test; test.push_back(contoursList.at(1)); Total_Contour = Mat::zeros(CountryImage.rows, CountryImage.cols, CV_8UC3); drawContours(Total_Contour, test, -1, 255, -1); // find the center of our contour Moments moment = moments((cv::Mat)test.at(0)); double area = moment.m00; int x,y; x = moment.m10/area; y = moment.m01/area; circle( Total_Contour, Point(x,y), 7, Scalar( 0, 0, 255 ), FILLED, LINE_8 ); resize(Total_Contour, Total_Contour, Size(ImageWidth, ImageHeight)); imshow("Total_Contour", Total_Contour); return contoursList; } vector<vector<Mat>> get_vacation_pictures(vector<string> countrynames, string pathNameToVacation) { //list we are going to return vector<vector<Mat>> picturesList; vector<Mat> tempVector; Mat tempImage; vector<String> fileNames; String temp; size_t picture_count; //loop over every country we have a contour of for(int countrycounter=0; countrycounter<countrynames.size(); countrycounter++) { temp = pathNameToVacation + "/" + countrynames.at(countrycounter) + "/*.jpg"; cout << "filename for path to pictures" << temp << endl; //get every picturepath in the file glob(temp, fileNames, false); //read in every picture in the file picture_count = fileNames.size(); //number of png files in images folder for (size_t i=0; i<picture_count; i++) { tempImage = imread(fileNames.at(i), IMREAD_COLOR); // make them smaller resize(tempImage, tempImage, Size(ImageWidth, ImageHeight)); tempVector.push_back(tempImage); } picturesList.push_back(tempVector); tempVector.clear(); } return picturesList; } vector<Point> ContoursFrame_WholeMap(Mat image) { //variables vector< vector<Point>> contours; vector< vector<Point>> bigContours; vector<Point2f>center( contours.size() ); vector<float>radius( contours.size() ); double areaContour; Moments moment; double area; int x,y; int xClosest =0; int yClosest =0; int returnIndexbigContours = 0; Mat ImageGray; cvtColor(image, ImageGray, CV_BGR2GRAY); /// CLAHE // thresholding // Less noise than OTSU //contrast amplification is limited, so as to reduce this problem of noise amplification. //source: https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE Mat result_clahe; Ptr<CLAHE> clahe_pointer = createCLAHE(); clahe_pointer->setTilesGridSize(Size(15,15)); clahe_pointer->setClipLimit(1); clahe_pointer->apply(ImageGray.clone(), result_clahe); Mat claheThreshold = Mat::zeros(ImageGray.rows, ImageGray.cols, CV_8UC1); threshold(result_clahe, claheThreshold, 0, 255, THRESH_BINARY | THRESH_OTSU); Mat ClaheSmall; resize(claheThreshold, ClaheSmall, Size(ImageWidth, ImageHeight)); imshow("CLAHE ", ClaheSmall); ///contours // search for contours in the thresholded frame findContours(claheThreshold.clone(), contours, RETR_EXTERNAL, CHAIN_APPROX_NONE); // We only want bigger contours. Smalls ones are difficult to compare for(int i=0; i<contours.size(); i++) { areaContour = contourArea(contours.at(i)); if(areaContour > 40000) { bigContours.push_back(contours.at(i)); } } //We draw the contours on a seperate image Mat ContoursTotal; ContoursTotal = Mat::zeros(image.rows, image.cols, CV_8UC3); drawContours(ContoursTotal, bigContours, -1, 255, -1); //We calculate the center of the contours and look which one is closest to the center of the frame for(int j = 0; j < bigContours.size(); j++) { // Image moments help you to calculate some features like center of mass of the object, area of the object etc. // source: https://docs.opencv.org/3.4.2/dd/d49/tutorial_py_contour_features.html. moment = moments((cv::Mat)bigContours.at(j)); area = moment.m00; x = moment.m10/area; y = moment.m01/area; if( (abs(x-image.cols/2) < abs(xClosest - image.cols/2)) && (abs(y-image.cols/2) < abs(x-yClosest - image.cols/2))) { xClosest = x; yClosest = y; returnIndexbigContours = j; } } //draw the center on the total image circle( ContoursTotal, Point(xClosest,yClosest), 7, Scalar( 0, 0, 255 ), FILLED, LINE_8 ); Mat ContourSmall; resize(ContoursTotal, ContourSmall, Size(ImageWidth, ImageHeight)); imshow("ContoursTotal", ContourSmall); // return the center contour or an empty contour if nothing is found if(!bigContours.empty()) { return bigContours.at(returnIndexbigContours); } else { return vector<Point>(); } }
9923152e460d6d1120316199bb75bbaef6e87dd1
f3a468e648a5a8321d72324c167d2db3404287c1
/NoiseTemplated/Noise.h
fd788e375af5908a65a48825b6bd9035c6d1b95f
[]
no_license
NCCA/RandomTests
cf4a73a8712498a0e3b7cf6ae8351989cf85f568
75a7d9f916d253318b7832062e4980797d00bc8c
refs/heads/master
2021-01-10T14:59:59.128372
2016-03-09T20:40:40
2016-03-09T20:40:40
53,491,581
0
0
null
null
null
null
UTF-8
C++
false
false
8,796
h
Noise.h
//---------------------------------------------------------------------------------------------------------------------- /// @brief /// simple Perlin noise class cobbled together from Computer Graphics OpenGL by F,S Hill /// and Texturing and Modeling Ebert et-al /// also thanks to Ian Stephenson for help and debuging tips /// more work needs to be done to add interpolated noise functions and improve the /// aliasing of the textures but it is ok for basic use //---------------------------------------------------------------------------------------------------------------------- #include <memory> #include <algorithm> #include <random> #include <vector> #include <iostream> #ifndef NOISE_H_ #define NOISE_H_ typedef struct Point { float x=0.0f; float y=0.0f; float z=0.0f; Point()=default; Point(float _x, float _y, float _z) { x=_x; y=_y; z=_z; } }Point_t; template <typename Type> class Noise { static_assert(std::is_unsigned<Type>::value,"Can Only use Unsigned types"); static_assert(std::numeric_limits<Type>::max() <= std::numeric_limits<unsigned int>::max() ,"Can Only use sizes up to unsigned int!"); public : //---------------------------------------------------------------------------------------------------------------------- /// @brief a ctor dynamically allocates two tables //---------------------------------------------------------------------------------------------------------------------- Noise(); //---------------------------------------------------------------------------------------------------------------------- /// @brief dtor will remove tables allocated by dtor //---------------------------------------------------------------------------------------------------------------------- ~Noise(); //---------------------------------------------------------------------------------------------------------------------- /// @brief a noise function to return a float based on input point and scale /// @param [in] _scale the scale to process the noise with /// @param [in] _p the point to sample noise from /// @brief returns a noise value //---------------------------------------------------------------------------------------------------------------------- float noise( float _scale,const Point &_p); //---------------------------------------------------------------------------------------------------------------------- /// @brief turbulance function creates higher frequency versions of noise as harmonics /// @param [in] _scale the scale to process the noise with /// @param [in] _p the point to sample noise from /// @brief returns a noise value //---------------------------------------------------------------------------------------------------------------------- float turbulance(float _scale, const Point &_p ); float complex(int _steps, float _persistence, float _scale, const Point &_p ); //---------------------------------------------------------------------------------------------------------------------- /// @brief reset the noise tables will also re-set the seed so must be called after setSeed is /// called //---------------------------------------------------------------------------------------------------------------------- void resetTables(); //---------------------------------------------------------------------------------------------------------------------- /// @brief set the seed of the random number generator //---------------------------------------------------------------------------------------------------------------------- inline void setSeed(int _s){m_seed=_s; resetTables();} private : // have to use heap allocation as stack will be too small so // can't use std::array //---------------------------------------------------------------------------------------------------------------------- /// @brief noise table used for the noise generation //---------------------------------------------------------------------------------------------------------------------- std::vector<float> m_noiseTable; //---------------------------------------------------------------------------------------------------------------------- /// @brief index into the noise table //---------------------------------------------------------------------------------------------------------------------- std::vector<Type> m_indexTable; // the size of the unit is 4294967296 the largest we can hold! unsigned long long m_size; //---------------------------------------------------------------------------------------------------------------------- /// @brief random number generator seed (default to 1) //---------------------------------------------------------------------------------------------------------------------- unsigned int m_seed=1.0; //---------------------------------------------------------------------------------------------------------------------- /// @brief function to generate latticeNoise (from Ian Stephenson) /// @param [in] _i index into table /// @param [in] _j index into table /// @param [in] _k index into table //---------------------------------------------------------------------------------------------------------------------- float latticeNoise(int _i, int _j, int _k); }; template <typename Type> Noise<Type>::Noise() { // grab the size of the data and add 1. m_size=static_cast<unsigned long long>(std::numeric_limits<Type>::max()); // allocate memory m_noiseTable.resize(m_size); m_indexTable.resize(m_size); unsigned long long i=0; std::generate(std::begin(m_indexTable), std::end(m_indexTable), [&i]{ return i++; }); resetTables(); } //---------------------------------------------------------------------------------------------------------------------- template <typename Type> void Noise<Type>::resetTables() { // create an instance of the Mersenne Twister random number generator std::mt19937 gen(m_seed); // and create a RandFloat function std::uniform_real_distribution<float> randPosFloat(0.0f, 1.0f); // shuffle the index table randomly std::shuffle(std::begin(m_indexTable), std::end(m_indexTable), gen); for(auto &t : m_noiseTable) { t=randPosFloat(gen); } } template <typename Type> //---------------------------------------------------------------------------------------------------------------------- Noise<Type>::~Noise() { } //---------------------------------------------------------------------------------------------------------------------- template <typename Type> float Noise<Type>::latticeNoise(int _i, int _j, int _k) { #define PERM(x) m_indexTable[(x)&m_size] #define INDEX(ix,iy,iz) PERM( (ix) + PERM((iy)+PERM(iz))) // m_noiseTable[m_index[((_i) + m_index[((_j)+m_index[(_k)&255])&255])&255]]; return m_noiseTable[INDEX(_i,_j,_k)]; } template <typename T> T lerp(T _a, T _b, float _t) { T p; p=_a+(_b-_a)*_t; return p; } template <typename Type> float Noise<Type>::noise(float _scale, const Point &_p) { float d[2][2][2]; Point pp; pp.x=_p.x * _scale ; pp.y=_p.y * _scale ; pp.z=_p.z * _scale ; long ix = (long) pp.x; long iy = (long) pp.y; long iz = (long) pp.z; float tx,ty,tz,x0,x1,x2,x3,y0,y1; tx=pp.x-ix; ty=pp.y-iy; tz=pp.z-iz; for(int k=0; k<=1; ++k) { for(int j=0; j<=1; ++j) { for(int i=0; i<=1; ++i) { d[k][j][i]=latticeNoise(ix+i,iy+j,iz+k); } } } x0=lerp(d[0][0][0],d[0][0][1],tx); x1=lerp(d[0][1][0],d[0][1][1],tx); x2=lerp(d[1][0][0],d[1][0][1],tx); x3=lerp(d[1][1][0],d[1][1][1],tx); y0=lerp(x0,x1,ty); y1=lerp(x2,x3,ty); return lerp(y0,y1,tz); } //---------------------------------------------------------------------------------------------------------------------- template <typename Type> float Noise<Type>::turbulance(float _scale, const Point &_p ) { float val= (noise(_scale,_p)/2.0) + (noise(2.0*_scale,_p)/4.0) + (noise(4.0*_scale,_p)/8.0) + (noise(8.0*_scale,_p)/16.0); return val; } //---------------------------------------------------------------------------------------------------------------------- // values for this are based on http://freespace.virgin.net/hugo.elias/models/m_perlin.htm //---------------------------------------------------------------------------------------------------------------------- template <typename Type> float Noise<Type>::complex( int _steps,float _persistence,float _scale, const Point &_p ) { float val=0.0; for(int i=1; i<=_steps; ++i) { val+=(noise(i*_scale,_p)/std::pow(_persistence,i)); } return val; } //---------------------------------------------------------------------------------------------------------------------- #endif
e42cbce5cd2a8cbea94e813ff1c7b91bf773d158
cbda5f974082fff2f4d607444312f81b58ad213a
/main_preprocessed.cpp
7bebe8779bdb6530bcaabafb144dd3c132159b5b
[]
no_license
arigatory/HowCppCompiles
fa518bd5a4113994876c78870a7d2bc61375990b
64524424a5ea127ecaa38ec0ee1bf3c1b40b7137
refs/heads/master
2023-01-13T11:52:42.466829
2020-11-25T18:54:06
2020-11-25T18:54:06
316,028,179
0
0
null
null
null
null
UTF-8
C++
false
false
184
cpp
main_preprocessed.cpp
# 1 ".\\main.cpp" # 1 "<built-in>" # 1 "<command-line>" # 1 ".\\main.cpp" # 1 ".\\square.hpp" 1 int square(int x); # 2 ".\\main.cpp" 2 int main() { square(5); return 0; }
8bece9edf30a9b464010bf21246c884873f77eed
218c021e1fe148c168e81527f19afcb2ba811361
/Implementations/11 - Math (4)/11.3 - Matrix/Matrix Inverse (6).cpp
68bb14bc84f77a7322fa3f2b56b600f22e806f9f
[ "MIT" ]
permissive
nuha14m/USACO
2232d3f13ae3b57f1691a21e36c8826a5b655cbf
5830a6d05f8c52bfddc36f916619fa3d863abcba
refs/heads/master
2020-06-09T22:52:14.287724
2019-06-23T20:03:16
2019-06-23T20:03:16
193,522,765
1
0
MIT
2019-06-24T14:35:53
2019-06-24T14:35:52
null
UTF-8
C++
false
false
1,630
cpp
Matrix Inverse (6).cpp
/* * Description: calculates determinant via gaussian elimination * Source: various * Verification: SPOJ MIFF */ namespace matInv { template<class T> void elim(Mat<T>& m, int col, int a, int b) { // eliminate row a from row b auto x = m.d[b][col]; FOR(i,col,m.c) m.d[b][i] -= x*m.d[a][i]; } template<class T> T gauss(Mat<T>& m) { // determinant of 1000x1000 Matrix in ~1s T prod = 1; int nex = 0; F0R(i,m.r) { int row = -1; FOR(j,nex,m.r) if (m.d[j][i] != 0) { row = j; break; } // for ld use EPS if (row == -1) { prod = 0; continue; } if (row != nex) prod *= -1, swap(m.d[row],m.d[nex]); prod *= m.d[nex][i]; auto x = 1/m.d[nex][i]; FOR(k,i,m.c) m.d[nex][k] *= x; F0R(k,m.r) if (k != nex) elim(m,i,nex,k); nex ++; } return prod; } mi numSpan(Mat<mi> m) { // Kirchhoff's theorem Mat<mi> res(m.r-1,m.r-1); F0R(i,m.r) FOR(j,i+1,m.r) { if (i) { res.d[i-1][i-1] += m.d[i][j]; res.d[i-1][j-1] -= m.d[i][j]; res.d[j-1][i-1] -= m.d[i][j]; } res.d[j-1][j-1] += m.d[i][j]; } return gauss(res); } template<class T> Mat<T> inv(Mat<T> m) { Mat<T> x(m.r,2*m.r); F0R(i,m.r) F0R(j,m.r) x.d[i][j] = m.d[i][j]; F0R(i,m.r) x.d[i][i+m.r] = 1; if (gauss(x) == 0) return Mat<T>(0,0); Mat<T> r(m.r,m.r); F0R(i,m.r) F0R(j,m.r) r.d[i][j] = x.d[i][j+m.r]; return r; } } using namespace matInv;
1cf9bf9bf0985a99443018151c0da8d85acea59f
13d984667a378bcc6a6dfc8b29f2660d31ca851d
/universitymanagementsecond final.cpp
c4885f70817e4766c72a164233e23839c341fb2a
[]
no_license
ahosanul/cpp_project
8eac72bd1338750c9844bfe9e6631617d7da24cd
2e093532788c449666ab2ca834e22213e4227ad4
refs/heads/master
2022-04-25T23:37:08.217701
2020-04-26T15:00:29
2020-04-26T15:00:29
259,051,886
0
0
null
null
null
null
UTF-8
C++
false
false
18,024
cpp
universitymanagementsecond final.cpp
#include<iostream> #include<fstream> #include<cstring> #include<conio.h> #include<stdlib.h> #include<cstring> #include<iomanip> #include <stdlib.h> // testing using namespace std; fstream file; void great(double data); void control(); int sub=0; int a=0,b=0; double temp_total_cradit; double temp_multi_credit; char tempsubcode[100]; double tempcredit=0; int no_of_sub=0; double greade_point; void inputresultdata(); void show_data(); struct result{ long int ID; char subcode[100]; double mark; float credit; float earncredit; }; result one_one; struct studentinfo { long int ID; double mark; int semester_no; double gpa_of_thet_semester; }; studentinfo data; void findsubject(int a,int b,int subno) { switch(b) { case 1: { switch(subno) { case 1: { cout<<"Fundamental of Information and Communication Technology "<<endl; char tempsubcode[100]={'I','C','E','1','1','0','1'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3; break; } case 2: { cout<<"Fundamental of Information and Communication Technology Sessional"<<endl; char tempsubcode[100]={'I','C','E','1','1','0','2'}; strcpy(one_one.subcode,tempsubcode); tempcredit=1.5; break; } case 3: { cout<<"Electronics"<<endl; char tempsubcode[100]={'I','C','E','1','1','0','3'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3; break; } case 4: { cout<<"Electronics Sessional"<<endl; char tempsubcode[100]={'I','C','E','1','1','0','4'}; strcpy(one_one.subcode,tempsubcode); tempcredit=1.5; break; } case 5: { cout<<" Differential and Integral Calculus "<<endl; char tempsubcode[100]={'M','A','T','H','1','1','4','1'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3; break; } case 6: { cout<<"Physics "<<endl; char tempsubcode[100]={'P','H','Y','1','1','0','3'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3; break; } case 7: { cout<<"Physics Sessional"<<endl; char tempsubcode[100]={'P','H','Y','1','1','0','4'}; strcpy(one_one.subcode,tempsubcode); tempcredit=1.5; break; } case 8: { cout<<"Technical and Communicative English"<<endl; char tempsubcode[100]={'H','U','M','1','1','0','1'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3; break; } case 9: { cout<<"Technical and Communicative English Sessional"<<endl; char tempsubcode[100]={'H','U','M','1','1','0','2'}; strcpy(one_one.subcode,tempsubcode); tempcredit=1.5; break; } } break; } case 2: { switch(subno) { case 1: { cout<<"Structured Programming Language "<<endl; char tempsubcode[100]={'I','C','E','1','2','2','1'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3; break; } case 2: { cout<<"Structured Programming Language Sessional"<<endl; char tempsubcode[100]={'I','C','E','1','2','1','2'}; strcpy(one_one.subcode,tempsubcode); tempcredit=1.5; break; } case 3: { cout<<"Digital Electronics"<<endl; char tempsubcode[100]={'I','C','E','1','2','2','1'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3; break; } case 4: { cout<<"Digital Electronics Sessional"<<endl; char tempsubcode[100]={'I','C','E','1','2','2','2'}; strcpy(one_one.subcode,tempsubcode); tempcredit=1.5; break; } case 5: { cout<<"Algebra and Vector Analysis "<<endl; char tempsubcode[100]={'M','A','T','H','1','2','4','3'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3; break; } case 6: { cout<<" Statistics for Engineers "<<endl; char tempsubcode[100]={'S','T','A','T','1','2','1','1'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3; break; } case 7: { cout<<" Chemistry "<<endl; char tempsubcode[100]={'C','H','E','M','1','2','0','1'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3; break; } } break; } case 3: { switch(subno) { case 1: { cout<<"Object oriented Programming Language "<<endl; char tempsubcode[100]={'I','C','E','2','1','1','1'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3; break; } case 2: { cout<<"Object oriented Programming Language Sessional"<<endl; char tempsubcode[100]={'I','C','E','1','2','1','2'}; strcpy(one_one.subcode,tempsubcode); tempcredit=1.5; break; } case 3: { cout<<"Electrical Circuits and Electromagnetic Waves"<<endl; char tempsubcode[100]={'I','C','E','2','1','2','1'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3; break; } case 4: { cout<<"Electrical Circuits and Electromagnetic Waves Sessional"<<endl; char tempsubcode[100]={'I','C','E','2','1','2','2'}; strcpy(one_one.subcode,tempsubcode); tempcredit=1.5; break; } case 5: { cout<<" Signals and Systems "<<endl; char tempsubcode[100]={'I','C','E','2','1','3','1'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3; break; } case 6: { cout<<"Signals and Systems Sessional "<<endl; char tempsubcode[100]={'I','C','E','2','1','3','2'}; strcpy(one_one.subcode,tempsubcode); tempcredit=1.5; break; } case 7: { cout<<"Matrices and Differential Equations "<<endl; char tempsubcode[100]={'M','A','T','H','2','1','1','1'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3; break; } case 8: { cout<<"Industrial Management and Accountancy"<<endl; char tempsubcode[100]={'H','U','M','2','1','0','1'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3; break; } } break; } case 4: { switch(subno) { case 1: { cout<<"Data Communication"<<endl; char tempsubcode[100]={'I','C','E','2','2','1','1'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3.0; break; } case 2: { cout<<"Data Communication Sessional"<<endl; char tempsubcode[100]={'I','C','E','2','2','1','2'}; strcpy(one_one.subcode,tempsubcode); tempcredit=1.5; break; } case 3: { cout<<"Wireless Communication"<<endl; char tempsubcode[100]={'I','C','E','2','2','2','1'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3.0; break; } case 4: { cout<<"Wireless Communication Sessional"<<endl; char tempsubcode[100]={'I','C','E','2','2','2','2'}; strcpy(one_one.subcode,tempsubcode); tempcredit=1.5; break; } case 5: { cout<<"Data Structures and Algorithms"<<endl; char tempsubcode[100]={'I','C','E','2','2','3','1'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3.0; break; } case 6: { cout<<"Data Structures and Algorithms Sessional"<<endl; char tempsubcode[100]={'I','C','E','2','2','3','2'}; strcpy(one_one.subcode,tempsubcode); tempcredit=1.5; break; } case 7: { cout<<"Discrete Math and Numerical methods"<<endl; char tempsubcode[100]={'M','A','T','H','2','2','2','1'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3.0; break; } case 8: { cout<<"Society, Ethics and Technology"<<endl; char tempsubcode[100]={'H','U','M','2','2','5','5'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3.0; break; } case 9: { cout<<"Economics"<<endl; char tempsubcode[100]={'H','U','M','2','2','0','1'}; strcpy(one_one.subcode,tempsubcode); tempcredit=3.0; break; } } break; } case 5: { } case 6: { } case 7: { } case 8: { } } } void inputstudentifno() { temp_multi_credit=0; temp_total_cradit=0; tempcredit=NULL; no_of_sub=NULL; greade_point=NULL; cout<<"enter ID"; cin>>data.ID; inputresultdata(); data.semester_no=b; data.gpa_of_thet_semester=(temp_multi_credit/temp_total_cradit); cout<<endl<<" result is="<<data.gpa_of_thet_semester<<endl; } void inputresultdata() { cout<<"enter semester "; cin>>b; if(b==1) { no_of_sub=9; } else if(b==2) { no_of_sub=7; } else if(b==3) { no_of_sub=8; } else if(b==4) { no_of_sub=9; } else if(b==5) { no_of_sub=8; } else if(b==6) { no_of_sub=10; } else if(b==7) { no_of_sub=8; } else if(b==8) { no_of_sub=8; } //cout<<"subject code is "; for(int i=1;i<=no_of_sub;i++) { one_one.ID=data.ID; findsubject(a,b,i); one_one.credit=tempcredit; here: cout<<"Enter Mark"<<endl; cin>>data.mark; if(data.mark>100 ) { cout<<"are you mad !!! "<<endl; goto here; } if(data.mark<0 ) { cout<<" invalid !! "<<endl; goto here; } one_one.mark=data.mark; great(data.mark); one_one.earncredit=greade_point; temp_total_cradit=temp_total_cradit+tempcredit; temp_multi_credit=temp_multi_credit+(greade_point*tempcredit); file.open("f:\\bash_is_here.txt",ios::app) ; file.write((char*)&one_one,sizeof(one_one)); file.close(); } } void great(double data) { if(data>=80) { cout<<"A+"<<endl; greade_point=4; } if(data>=75&&data<80) { cout<<"A"<<endl; greade_point=3.75; } if(data>=70&&data<75) { cout<<"A-"<<endl; greade_point=3.50; } if(data >=65&&data <70) { cout<<"B+"<<endl; greade_point=3.25; } if(data >=60&&data <65) { cout<<"B"<<endl; greade_point=3; } if(data>=55&&data <60) { cout<<"B-"<<endl; greade_point=2.75; } if(data >=50&&data <55) { cout<<"C+"<<endl; greade_point=2.50; } if(data >=45&&data <50) { cout<<"C"<<endl; greade_point=2.25; } if(data >=40&&data <45) { cout<<"D"<<endl; greade_point=2.00; } if(data <40) { cout<<"Fail"<<endl; greade_point=0; } } void show_data() { file.open("f:\\bash_is_here.txt",ios::in) ; if(!file) { cout<<endl<<"no data here "<<endl; control(); } long int check_id; system("cls"); cout<<endl<<setw(45)<<"** students mark sheet **"<<endl; file.read((char*)&one_one,sizeof(one_one)); cout<<"enter id to see result :"; cin>>check_id; cout<<endl<<setw(16)<<"student id"<<setw(22)<<"subject code "<<setw(8)<<"Mark"<< setw(15)<<"Great point"<<endl; cout<<setw(47)<<"________________________________________________________________________________________"<<endl; while (file.eof()==0) { cout<<setw(16)<<one_one.ID<<setw(19)<<one_one.subcode<<setw(10)<<one_one.mark<< setw(13)<<one_one.earncredit<<endl<<endl; file.read((char*)&one_one,sizeof(one_one)); } file.close(); cout<<"press any key to go to main menu .... "; getch(); system("cls"); } void control() { main: //system("cls"); cout<<endl<<setw(70)<<" 1 . Result processing\n"; cout<<setw(65)<<" 2 . view result \n"; /* cout<<setw(71)<<" 3 . to search Record\n"; cout<<setw(69)<<" 4 . to edit Record\n"; cout<<setw(64)<<" 5 . to delete\n"; cout<<setw(70)<<" 6 . any key to exit\n"<<endl;*/ cout<<"Enter your key :"; int a; cin>>a; if(a>=1&&a<=5) { switch(a) { case 1: { inputstudentifno(); cout<<" "<<endl; goto main; } case 2: { show_data(); cout<<" "<<endl; goto main; } /* case 3: { search(); cout<<"done :/"<<endl; goto main; } // case 4: { edit(); cout<<"updated :)"<<endl; goto main; } case 5: { deleting(); cout<<" :)"<<endl; goto main; }*/ case 6: exit(0); } } else cout<<"enter the right key"; } int main() { cout<<endl<<setw(83)<<"BANGLADESH ARMY UMIVERSITY OF ENGINEERING & TECHNOLOGY"<<endl; control(); }
0810326cead2be3d8dd675e8435269391894d574
66d87304552c5cd561006c05f147a3e0953791f6
/校园导航/test.cpp
cd2e2e990f7fa0a9505346625fd86b8e8a62250a
[]
no_license
puyuerong/Campus_Navigation
e498612c48b32584caa35e0b1398aa65f72fc947
2ceab45f1d17243229ec3e5415b2eecc8edd2848
refs/heads/master
2022-04-05T06:21:38.599028
2020-01-03T02:21:04
2020-01-03T02:21:04
231,494,754
0
0
null
null
null
null
GB18030
C++
false
false
28,129
cpp
test.cpp
#include"stdio.h" #include"stdlib.h" #include"windows.h" #include <graphics.h> #include <conio.h> #define MAXVEX 20 //最大顶点数 #define INFINITY 9999 typedef struct { int x; int y; char name[100]; char describe[200]; }Location; typedef struct { char name[30]; char password[30]; }LandMessage; typedef struct { int arc[MAXVEX][MAXVEX]; Location loc[MAXVEX]; int vexnum; int arcnum; int landnum; int chargernum; LandMessage land[MAXVEX]; LandMessage charger[MAXVEX]; }AdjMatrix; int Transform(char a[20]) { int i = 0, sum = 0; while(i < strlen(a)) { sum = sum * 10 + (int)a[i++] - 48; } return sum; } int book[MAXVEX], route[MAXVEX]; //route[0]存放路径长度 int shortest[MAXVEX], short_num, short_num2, turn_minimum[MAXVEX], turn_num; DFS(AdjMatrix *adj, int current, int end, int begin, int t, int option) { int i, j; if (current == end) { if (route[0] < short_num) { short_num = route[0]; short_num2 = t; for (i = 2; i < t; i++) { shortest[i] = route[i]; } } if (t < turn_num) { turn_num = t; for (i = 2; i < t; i++) { turn_minimum[i] = route[i]; } } shortest[1] = begin; shortest[t] = end; turn_minimum[1] = begin; turn_minimum[t] = end; if(option == 1) { printf("%d: ", route[0]); printf("%s", adj->loc[begin].name); for (i = 2; i < t; i++) { printf("-->"); printf("%s", adj->loc[route[i]].name); } printf("-->%s\n\n", adj->loc[end].name); } return; } for(i = 1; i <= adj->vexnum; i++) { book[current] = 1; if(current == begin) { t = 1; } if (i == begin) { continue; } route[t] = current; while(((adj->arc[i][current] == 0) || (book[i] == 1)) && (i <= adj->vexnum)) { i++; } if ((i > adj->vexnum) || (adj->arc[i][current] == 0) || (book[i] == 1)){ return; } route[0] += adj->arc[i][current]; DFS(adj, i, end, begin, t + 1, option); book[i] = 0; route[0] -= adj->arc[i][current]; } } AdjMatrix *ReadFromFile(AdjMatrix *adj) { FILE *fp; int i = 0, count = 0, t; char a[10], b[10]; fp = fopen("课设.txt", "r"); fscanf(fp, "%s", b); fgetc(fp); while(!feof(fp)) { fscanf(fp, "%s", adj->loc[++i].name); fgetc(fp); fscanf(fp, "%s", a); adj->loc[i].x = Transform(a); fgetc(fp); fscanf(fp, "%s", a); adj->loc[i].y = Transform(a); fgetc(fp); fscanf(fp, "%s", adj->loc[i].describe); fgetc(fp); } adj->vexnum = Transform(b); fclose(fp); return adj; } AdjMatrix *ReadLandMessage(AdjMatrix *adj) { FILE *fp1, *fp2; int i; fp1 = fopen("管理员.txt", "r"); fscanf(fp1, "%d", &adj->chargernum); fgetc(fp1); for (i = 1; i <= adj->chargernum; i++) { fscanf(fp1, "%s", adj->charger[i].name); fgetc(fp1); fscanf(fp1, "%s", adj->charger[i].password); fgetc(fp1); } fclose(fp1); fp2 = fopen("普通用户.txt", "r"); fscanf(fp2, "%d", &adj->landnum); fgetc(fp2); for (i = 1; i <= adj->landnum; i++) { fscanf(fp2, "%s", adj->land[i].name); fgetc(fp2); fscanf(fp2, "%s", adj->land[i].password); fgetc(fp2); } fclose(fp2); return adj; } AdjMatrix *ReadFromMatrixFile(AdjMatrix *adj) { FILE *fp; int i, j; fp = fopen("矩阵.txt", "r"); for(i = 1; i <= adj->vexnum; i++) { for(j = 1; j <= adj->vexnum; j++) { fscanf(fp, "%d", &adj->arc[i][j]); fgetc(fp); } } return adj; } PrintMap(AdjMatrix *adj) { //地图输出 int i; for (i = 1; i <= adj->vexnum; i++) { printf("%s %d %d %s\n", adj->loc[i].name, adj->loc[i].x, adj->loc[i].y, adj->loc[i].describe); } } PrintPicture(AdjMatrix *adj) { int i, j; /* for(i = 1; i <= adj->vexnum; i++) { for(j = 1; j <= adj->vexnum; j++) { printf("%-4d ", adj->arc[i][j]); } printf("\n"); }*/ printf("\t 图书馆--------------600---------------创业园区------100----浴室\n"); printf("\t / | / \n"); printf("\t 200 | /400 \n"); printf("\t / | / \n"); printf("\t 心型湖-------|------600-------------------通院 \n"); printf("\t | \\ | / \n"); printf("\t | \\____|_____600______________ /200 \n"); printf("\t 400 | \\ / \n"); printf("\t | 1000 电院 \n"); printf("\t | | |200 \n"); printf("\t 大活---------|-------500-----------自动化院 \n"); printf("\t / \\ | / \n"); printf("\t / \\ | /300 \n"); printf("\t / \\ | / \n"); printf("\t / \\ | ___300_________B楼__ \n"); printf("\t 700 800 | / / \\100 \n"); printf("\t / \\ 水池 / A楼 \n"); printf("\t / \\ | __400_____/ / \\ \n"); printf("\t / \\ | / / \\200 \n"); printf("\t / \\ | / ____500_________/ \\ \n"); printf("\t / \\|/ / \\ \n"); printf("\t行政楼------300--------北门-------------300----------西邮宾馆 \n"); } Description(AdjMatrix *adj) { //位置信息描述 int i, option; for (i = 1; i <= adj->vexnum; i++) { if (i % 2 != 0) { printf("\n\n"); } printf("%-2d、%-20s", i, adj->loc[i].name); } printf("\n\n请从上述位置中选择查看详细信息\t option : "); while(1) { scanf("%d", &option); if ((1 <= option) && (option <= 15)) { printf("\n\n%s", adj->loc[option].describe); break; } else { printf("输入有误,请按正确格式输入(eg:1)\n"); } } } StudentEnterance(AdjMatrix *adj) { int option, i, begin, end, mark = 0; char a[10]; route[0] = 0; while(1) { printf("\n\t\t-------------------- 请选择服务项目 --------------------\n\n"); printf("\t 1、校园一览图\n"); printf("\t 2、地点信息查询\n"); printf("\t 3、校园导航\n\n"); while(1) { printf("option : "); scanf("%d", &option); gets(a); if ((option == 1) || (option == 2) || (option == 3)) { Sleep(500); system("cls"); break; } else { printf("输入有误, 请按正确格式输入(eg:1)\n"); } } switch(option) { case 1 : PrintPicture(adj); break; case 2 : Description(adj); break; case 3 : for (i = 1; i <= adj->vexnum; i++) { //输出所有地点 if (i % 2 != 0) { printf("\n\n"); } printf("%-2d、%-20s", i, adj->loc[i].name); } printf("\n\n请从上述地点中选择:\n\n"); while(1) { //选择起始地点 printf("\t\t起始地点:\t"); scanf("%d", &begin); printf("\n\t\t 终点:\t"); scanf("%d", &end); printf("\n\n\n"); if ((begin >= 1) && (begin <= adj->vexnum) && (end >= 1) && (end <= adj->vexnum)) { route[0] = 0; short_num = INFINITY; turn_num = INFINITY; for (i = 0; i <= adj->vexnum; i++) { shortest[i] = 0; turn_minimum[i] = 0; } for (i = 0; i <= adj->vexnum; i++) { book[i] = 0; } DFS(adj, begin, end, begin, 1, 0); break; } else { printf("输入有误, 请按正确格式输入(eg:1)\n"); } } while(1) { system("cls"); printf("当前所选起点:%s\n所选终点:%s\n", adj->loc[begin].name, adj->loc[end].name); printf("\n\n\n\t\t**************************请选择服务项目*************************\n\n"); printf("\t\t 1、输出全部可行路线\n"); printf("\t\t 2、输出最短路线\n"); printf("\t\t 3、输出中转次数最少路线\n\n"); printf("\t\t*****************************************************************\n\n"); while(1) { //选择服务项目 printf("\noption:"); scanf("%d", &option); if ((option == 1) || (option == 2) || (option == 3)) { break; } else { printf("输入有误, 请按正确格式输入(eg:1)\n"); } } switch(option) { case 1 : DFS(adj, begin, end, begin, 1, 1); break; case 2 : printf("\n从%s到%s的最短路线如下:总长%d\n\n", adj->loc[begin].name, adj->loc[end].name, short_num); printf("%s-->", adj->loc[begin].name); for (i = 2; i < short_num2; i++) { printf("%s-->", adj->loc[shortest[i]].name); } printf("%s", adj->loc[end].name); break; case 3 : printf("\n从%s到%s中转次数最少的路线如下:总中转次数%d\n\n", adj->loc[begin].name, adj->loc[end].name, turn_num); printf("%s-->", adj->loc[begin].name); for (i = 2; i < turn_num; i++) { printf("%s-->", adj->loc[turn_minimum[i]].name); } printf("%s", adj->loc[end].name); break; } printf("\n\n1、返回主界面\n"); printf("2、继续查看路径\n"); printf("3、退出\n\noption : "); while(1) { scanf("%d", &option); switch(option) { case 1 : mark = 1; break; case 2 : break; case 3 : exit(0); break; default : printf("输入有误,请按正确格式输入(eg:1)\n"); } if ((option == 1) || (option == 2) || (option == 3)) { system("cls"); break; } } if (mark == 1) { break; } } } if (mark == 1) { mark = 0; continue; } printf("\n\n1、返回上一层\n"); printf("2、退出\n\noption : "); while(1) { scanf("%d", &option); switch(option) { case 1 : break; case 2 : exit(0); break; default : printf("输入有误,请按正确格式输入(eg:1)\n"); } if (option == 1) { system("cls"); break; } } } } AddPasswordMessage(AdjMatrix *adj) { FILE *fp; char name[20], password[20], a[20]; int i, option; printf("请选择端口:\n\t1、管理端\t2、普通用户端\n"); while(1) { printf("option : "); scanf("%d", &option); gets(a); if ((option == 1) || (option == 2)) { printf("\n请输入要添加的用户名:\t"); gets(name); printf(" 密码:\t"); gets(password); } else { printf("输入有误,请按正确格式输入(eg:1)\n"); continue; } if (option == 1) { fp = fopen("管理员.txt", "wt"); fprintf(fp, "%d\n", (adj->chargernum) + 1); for (i = 1; i <= adj->chargernum; i++) { fprintf(fp, "%s %s\n", adj->charger[i].name, adj->charger[i].password); } fprintf(fp, "%s %s", name, password); fclose(fp); } else { fp = fopen("普通用户.txt", "wt"); fprintf(fp, "%d\n", (adj->landnum) + 1); for (i = 1; i <= adj->chargernum; i++) { fprintf(fp, "%s %s\n", adj->land[i].name, adj->land[i].password); } fprintf(fp, "%s %s", name, password); fclose(fp); } printf("\n\t\t添加成功!\n\n"); adj = ReadLandMessage(adj); return; } } DeletePasswordMessage(AdjMatrix *adj) { FILE *fp; char name[20], password[20], a[20]; int i, option, mark; printf("请选择端口:\n\t1、管理端\t2、普通用户端\n"); while(1) { printf("option : "); scanf("%d", &option); gets(a); if ((option == 1) || (option == 2)) { printf("\n请输入要删除的用户名:\t"); gets(name); } else { printf("输入有误,请按正确格式输入(eg:1)\n"); continue; } if (option == 1) { fp = fopen("管理员.txt", "wt"); for (i = 1; i <= adj->chargernum; i++) { if(strcmp(name, adj->charger[i].name) == 0) { mark = 1; fprintf(fp, "%d", (adj->chargernum) - 1); for (i = 1; i <= adj->chargernum; i++) { if(strcmp(name, adj->charger[i].name) == 0) { continue; } fprintf(fp, "\n%s %s", adj->charger[i].name, adj->charger[i].password); } } } if (mark == 0) { printf("\n该用户不存在!\n"); } else { printf("\n删除成功!\n"); } fclose(fp); } else { fp = fopen("普通用户.txt", "wt"); for (i = 1; i <= adj->landnum; i++) { if(strcmp(name, adj->land[i].name) == 0) { mark = 1; fprintf(fp, "%d", (adj->landnum) - 1); for (i = 1; i <= adj->landnum; i++) { if(strcmp(name, adj->land[i].name) == 0) { continue; } fprintf(fp, "\n%s %s", adj->land[i].name, adj->land[i].password); } } } if (mark == 0) { printf("\n该用户不存在!\n"); } else { printf("\n删除成功!\n"); } fclose(fp); } adj = ReadLandMessage(adj); return; } } CorrectPasswordMessage(AdjMatrix *adj) { FILE *fp; char name[20], password[20], a[20]; int i, option, mark = 0; printf("请选择端口:\n\t1、管理端\t2、普通用户端\n"); while(1) { printf("option : "); scanf("%d", &option); gets(a); if ((option == 1) || (option == 2)) { printf("\n请输入要修改的用户名:\t"); gets(name); } else { printf("输入有误,请按正确格式输入(eg:1)\n"); continue; } if (option == 1) { fp = fopen("管理员.txt", "wt"); for (i = 1; i <= adj->chargernum; i++) { if(strcmp(name, adj->charger[i].name) == 0) { mark = 1; printf("\n输入修改后的用户名:\t"); gets(adj->charger[i].name); printf("\n输入修改后的密码:\t"); gets(adj->charger[i].password); fprintf(fp, "%d", adj->chargernum); for (i = 1; i <= adj->chargernum; i++) { fprintf(fp, "\n%s %s", adj->charger[i].name, adj->charger[i].password); } } } if (mark == 0) { printf("\n该用户不存在!\n"); } else { printf("\n修改成功!\n"); } fclose(fp); } else { fp = fopen("普通用户.txt", "wt"); for (i = 1; i <= adj->landnum; i++) { if(strcmp(name, adj->land[i].name) == 0) { mark = 1; printf("\n输入修改后的用户名:\t"); gets(adj->land[i].name); printf("\n输入修改后的密码:\t"); gets(adj->land[i].password); fprintf(fp, "%d", adj->landnum); for (i = 1; i <= adj->landnum; i++) { fprintf(fp, "\n%s %s", adj->land[i].name, adj->land[i].password); } } } if (mark == 0) { printf("\n该用户不存在!\n"); } else { printf("\n修改成功!\n"); } fclose(fp); } adj = ReadLandMessage(adj); return; } } SearchPasswordMessage(AdjMatrix *adj) { FILE *fp; char name[20], password[20], a[20]; int i, option; printf("请选择端口:\n\t1、管理端\t2、普通用户端\n"); while(1) { printf("option : "); scanf("%d", &option); gets(a); if ((option == 1) || (option == 2)) { printf("\n请输入要查找的用户名:\t"); gets(name); } else { printf("输入有误,请按正确格式输入(eg:1)\n"); continue; } if (option == 1) { // fp = fopen("管理员.txt", "wt"); for (i = 1; i <= adj->chargernum; i++) { if(strcmp(name, adj->charger[i].name) == 0) { printf("\n你所要查找的用户信息如下所示:\n\n"); printf("\t用户名:%s", adj->charger[i].name); printf("\t密码:%s", adj->charger[i].password); } } // fclose(fp); } else { for (i = 1; i <= adj->landnum; i++) { if(strcmp(name, adj->land[i].name) == 0) { printf("你所要查找的用户信息如下所示:\n"); printf("\t用户名:%s", adj->land[i].name); printf("\t密码:%s", adj->land[i].password); } } } return; } } AddLocationMessage(AdjMatrix *adj) { FILE *fp, *fp1; char name[20], produce[20], a[20]; int i, option, j, begin, end, choice; printf("增添位置or路线:\n\t1、位置\t2、路线\n"); while(1) { printf("option : "); scanf("%d", &option); gets(a); if ((option == 1) || (option == 2)) { break; } else { printf("输入有误,请按正确格式输入(eg:1)\n"); continue; } } gets(a); if (option == 1) { //增添位置 fp = fopen("课设.txt", "w"); printf("输入要增添的位置名称:"); gets(adj->loc[adj->vexnum + 1].name); printf("\n 位置介绍:"); adj->loc[adj->vexnum + 1].x = 0; adj->loc[adj->vexnum + 1].y = 0; gets(adj->loc[adj->vexnum + 1].describe); fprintf(fp, "%d", adj->vexnum + 1); for (i = 1; i <= (adj->vexnum) + 1; i++) { fprintf(fp, "\n%s %d %d %s", adj->loc[i].name, adj->loc[i].x, adj->loc[i].y, adj->loc[i].describe); } fclose(fp); printf("与这条路相通的路, 可直达输入路径长度, 不可直达输入0\n"); for (i = 1; i <= adj->vexnum; i++) { printf("%-12s", adj->loc[i].name); scanf("%d", &adj->arc[i][(adj->vexnum) + 1]); adj->arc[(adj->vexnum) + 1][i] = adj->arc[i][(adj->vexnum) + 1]; } adj->arc[(adj->vexnum) + 1][(adj->vexnum) + 1] = 0; fp1 = fopen("矩阵.txt", "w"); for (i = 1; i <= adj->vexnum + 1; i++) { fprintf(fp1, "%d", adj->arc[i][1]); for (j = 2; j <= (adj->vexnum) + 1; j++) { fprintf(fp1, " %d", adj->arc[i][j]); } if (i != ((adj->vexnum) + 1)) { fprintf(fp1, "\n"); } } fclose(fp1); } else { printf("\n要增添的路线信息:\n\n"); printf(" 起点:"); scanf("%d", &begin); printf(" 终点:"); scanf("%d", &end); printf(" 路径长度:"); scanf("%d", &choice); adj->arc[begin][end] = adj->arc[end][begin] = choice; fp1 = fopen("矩阵.txt", "w"); for (i = 1; i <= adj->vexnum; i++) { fprintf(fp1, "%d", adj->arc[i][1]); for (j = 2; j <= adj->vexnum; j++) { fprintf(fp1, " %d", adj->arc[i][j]); } if (i != adj->vexnum) { fprintf(fp1, "\n"); } } fclose(fp1); } adj = ReadFromFile(adj); adj = ReadFromMatrixFile(adj); } DeleteLocationMessage(AdjMatrix *adj) { FILE *fp, *fp1; char name[20], produce[20], a[20]; int i, option, j, begin, end, choice; printf("删除位置or路线:\n\t1、位置\t2、路线\n"); while(1) { printf("option : "); scanf("%d", &option); gets(a); if ((option == 1) || (option == 2)) { break; } else { printf("输入有误,请按正确格式输入(eg:1)\n"); continue; } } gets(a); if (option == 1) { fp = fopen("课设.txt", "w"); printf("输入要删除的位置名称:"); scanf("%d", &choice); fprintf(fp, "%d", adj->vexnum - 1); for (i = 1; i <= adj->vexnum; i++) { if (choice == i) { continue; } fprintf(fp, "\n%s %d %d %s", adj->loc[i].name, adj->loc[i].x, adj->loc[i].y, adj->loc[i].describe); } fclose(fp); fp1 = fopen("矩阵.txt", "w"); for (i = 1; i <= adj->vexnum; i++) { if (i == choice) { continue; } fprintf(fp1, "%d", adj->arc[i][1]); for (j = 2; j <= adj->vexnum; j++) { if (j == choice) { continue; } fprintf(fp1, " %d", adj->arc[i][j]); } if (i != ((adj->vexnum) + 1)) { fprintf(fp1, "\n"); } } fclose(fp1); } else { printf("\n\n请选择要删除的路线:\n\n"); printf(" 起点:"); scanf("%d", &begin); printf(" 终点:"); scanf("%d", &end); fp1 = fopen("矩阵.txt", "w"); adj->arc[end][begin] = adj->arc[begin][end] = 0; for (i = 1; i <= adj->vexnum; i++) { fprintf(fp1, "%d", adj->arc[i][1]); for (j = 2; j <= adj->vexnum; j++) { fprintf(fp1, " %d", adj->arc[i][j]); } if (i != adj->vexnum) { fprintf(fp1, "\n"); } } fclose(fp1); } adj = ReadFromFile(adj); adj = ReadFromMatrixFile(adj); } LocationOperate(AdjMatrix *adj) { int i, option; while(1) { printf("********************************************************************\n\n"); for (i = 1; i <= adj->vexnum; i++) { if ((i - 1) % 3 == 0) { printf("\n"); } printf("%-2d、%-12s\t", i, adj->loc[i].name); } printf("\n\n********************************************************************\n\n"); printf("\n\t\t-------------------- 现存地点如上所示, 请选择操作项目 --------------------\n\n"); printf("\t 1、增加位置信息\n"); printf("\t 2、删除位置信息\n"); printf("\t 3、返回上一层\n\n"); while(1) { printf("option : "); scanf("%d", &option); if ((option == 1) || (option == 2) || (option == 3)) { Sleep(500); system("cls"); } switch(option) { case 1 : AddLocationMessage(adj); break; case 2 : DeleteLocationMessage(adj); break; case 3 : return; default : printf("输入有误,请按正确格式输入(eg:1)\n"); } if ((option == 1) || (option == 2) || (option == 3)) { break; } } printf("\n\n1、返回上一层\n"); printf("2、退出\n\noption : "); while(1) { scanf("%d", &option); switch(option) { case 1 : break; case 2 : exit(0); break; default : printf("输入有误,请按正确格式输入(eg:1)\n"); } if (option == 1) { system("cls"); break; } } } } PasswordOperate(AdjMatrix *adj) { int i, option; while(1) { printf("********************************************************************\n普通用户\n"); for (i = 1; i <= adj->landnum; i++) { if (i - 1 % 3 == 0) { printf("\n"); } printf("%-20s: %-20s\t", adj->land[i].name, adj->land[i].password); } printf("\n\n\t********************************************************************\n管理端\n"); for (i = 1; i <= adj->chargernum; i++) { if (i - 1 % 3 == 0) { printf("\n"); } printf("%-10s: %-10s\t", adj->charger[i].name, adj->charger[i].password); } printf("\n\n\t********************************************************************"); printf("\n\t\t-------------------- 现存用户信息如上所示, 请选择操作项目 --------------------\n\n"); printf("\t 1、增加密码\n"); printf("\t 2、删除密码\n"); printf("\t 3、修改密码\n"); printf("\t 4、查找密码\n"); printf("\t 5、返回上一层\n\n"); while(1) { printf("option : "); scanf("%d", &option); if ((option == 1) || (option == 2) || (option == 3) || (option == 4) || (option == 5)) { Sleep(500); system("cls"); } switch(option) { case 1 : AddPasswordMessage(adj); break; case 2 : DeletePasswordMessage(adj); break; case 3 : CorrectPasswordMessage(adj); break; case 4 : SearchPasswordMessage(adj); break; case 5 : return; default : printf("输入有误,请按正确格式输入(eg:1)\n"); } if ((option == 1) || (option == 2) || (option == 3) || (option == 4) || (option == 5)) { break; } } printf("\n\n1、返回上一层\n"); printf("2、退出\n\noption : "); while(1) { scanf("%d", &option); switch(option) { case 1 : break; case 2 : exit(0); break; default : printf("输入有误,请按正确格式输入(eg:1)\n"); } if (option == 1) { system("cls"); break; } } } } ChargerEnterance(AdjMatrix *adj) { int option; while(1) { printf("\n\t\t-------------------- 请选择服务项目 --------------------\n\n"); printf("\t 1、位置信息修改\n"); printf("\t 2、密码修改\n\n"); while(1) { printf("option : "); scanf("%d", &option); if ((option == 1) || (option == 2)) { Sleep(500); system("cls"); } switch(option) { case 1 : LocationOperate(adj); break; case 2 : PasswordOperate(adj); break; default : printf("输入有误,请按正确格式输入(eg:1)\n"); } if ((option == 1) || (option == 2)) { break; } } } } JudgeForLand(AdjMatrix *adj, int option) { char id[20], password[20], mark = 0; int i, count = 0; while(1) { printf("\t\t---------------------------------------------\n"); printf("\t\t请输入用户名:\t\t"); gets(id); printf("\n\t\t请输入密码:\t\t"); for (i = 0; ; i++) { password[i] = getch(); if (((int)password[i] == 10) || ((int)password[i] == 32) || ((int)password[i] == 13)) { password[i] = '\0'; break; } if ((int)password[i] == 8) { i = i - 2; printf("\b \b"); } else { printf("*"); } } printf("\n\t\t---------------------------------------------\n"); if (option == 2) { for (i = 1; i <= adj->chargernum; i++) { if (strcmp(adj->charger[i].name, id) == 0) { if (strcmp(adj->charger[i].password, password) == 0) { printf("\t\t输入正确"); Sleep(200); system("cls"); ChargerEnterance(adj); mark = 1; break; } else { break; } } } } else { for (i = 1; i <= adj->landnum; i++) { if (strcmp(adj->land[i].name, id) == 0) { if (strcmp(adj->land[i].password, password) == 0) { printf("\n\n\n\t\t输 入 正 确 ......"); Sleep(500); system("cls"); StudentEnterance(adj); mark = 1; break; } else { break; } } } } if (mark == 1) { break; } else { count++; printf("\n\n用户名或密码错误, 三次错误, 账号锁定, 当前剩余次数:%d\n\n", 3 - count); } if (count == 3) { printf("输入错误达三次, 请稍后再试。。。。。。\n"); exit(0); } } } main() { AdjMatrix *adj; FILE *fp; int option, t, i, mark = 0; char a[10]; adj = (AdjMatrix*)malloc(sizeof(AdjMatrix)); adj = ReadFromFile(adj); adj = ReadFromMatrixFile(adj); adj = ReadLandMessage(adj); for (i = 0; i <= adj->vexnum; i++) { book[i] = 0; } // adj->vexnum = 14; printf("\n\n\n\n\n\n\n\t\t-------------------- 欢迎进入校园导航系统 --------------------\n\n"); Sleep(1000); printf("\t\t .\n\n"); Sleep(1000); printf("\t\t .\n\n"); Sleep(1000); printf("\t\t .\n\n"); while (1) { Sleep(1000); system("cls"); printf("\n\t\t-------------------- 请选择登录端 --------------------\n\n"); printf("\t 1、普通用户登录\n"); printf("\t 2、管理员登录\n"); while(1) { printf("option : "); scanf("%d", &option); if ((option == 1) || (option == 2)) { Sleep(500); system("cls"); break; } else { printf("输入有误,请按正确格式输入(eg:1)\n"); } } gets(a); JudgeForLand(adj, option); } }
1c36d4b31b73b4d7e8175ed308d3e5498397330d
e0316d6fb4fd539e2890de8a67cb8203d0079560
/assign1/pi_gen.cpp
0f32877b082fc0b06c510471b877d975ef330603
[]
no_license
mikeaalv/Monte_Carlo_course_assign
d07ceedf6e47da98e6e8b2cccb4b2632cf1da27b
13ba676d2d004c07cfcc6c08a0a072905d94b070
refs/heads/master
2021-01-03T14:04:09.289815
2020-04-19T16:14:23
2020-04-19T16:14:23
240,096,821
0
0
null
null
null
null
UTF-8
C++
false
false
1,404
cpp
pi_gen.cpp
// this program approximate pi through random drawing points in square // pi is calculated by 4*Q, Q is the ratio of sample in the quarter circile within the square // Compile: // module load icc/2018.1.163-GCC-6.4.0-2.28 // icc -O2 pi_gen.cpp -o pi_gen // Run // ./pi_gen N_sample randseed // N_sample is the number of drawn points // randseed is the start random seed // there will be 10 (N_INDEP_CHAIN) independent run each with length N_sample and with random seed randseed..randseed+9 // Return: the program will output 10 rows, and each row is an estimated pi #include <iostream> #include <string> #include <fstream> #include <stdio.h> #include <stdlib.h> #include <cmath> using namespace std; #define N_INDEP_CHAIN 10 int main(int argc, char* argv[]) { long Nsample=stol(argv[1]); long randseed=stol(argv[2]); double pi_est[10]; // sample for each sampling chain for(long i=0;i<N_INDEP_CHAIN;i++){ //different random seed for each sampling chain long randseednew=randseed+i; srand48(randseednew); double rand_axis[2]; long Ncircle=0; // sample within one sampling chain for(long j=0;j<Nsample;j++){ rand_axis[0]=drand48(); rand_axis[1]=drand48(); // within circle if(pow(rand_axis[0],2)+pow(rand_axis[1],2) < 1){ Ncircle++; } } pi_est[i]=4.0*(double)Ncircle/(double)Nsample; printf("%.7f\n",pi_est[i]); } }
dc3776d1099ce9744896d5626233248aee352f96
3bcc13b266921198e8efd6e31bd9214b2442f91f
/Documentos/clase7/example13_strcmp.cpp
4afb577861d425722bdeb3def1a0603ec5990ef0
[]
no_license
lidersamir/CursoFCII_UdeA_2021_1
5604f283188a52280894e62993c3503308a2bc63
23f24e799a1175589f38a735bd1aa1ab79999336
refs/heads/main
2023-07-18T13:35:13.680024
2021-08-28T18:19:24
2021-08-28T18:19:24
343,796,042
1
0
null
2021-03-02T14:08:44
2021-03-02T14:08:43
null
UTF-8
C++
false
false
733
cpp
example13_strcmp.cpp
// Uso de strcpy y strncpy. #include <iostream> #include <cstring> #include <iomanip> using namespace std; int main() { char *s1 = "Felices Fiestas"; char *s2 = "Felices Fiestas"; char *s3 = "Felices Dias de fiesta"; cout << "s1 = " << s1 << "\ns2 = " << s2 << "\ns3 = " << s3 << "\n\nstrcmp(s1, s2) = " << setw( 2 ) << strcmp( s1, s2 ) << "\nstrcmp(s1, s3) = " << setw( 2 ) << strcmp( s1, s3 ) << "\nstrcmp(s3, s1) = " << setw( 2 )<< strcmp( s3, s1 ); cout << "\n\nstrncmp(s1, s3, 8) = " << setw( 2 )<< strncmp( s1, s3, 8 ) << "\nstrncmp(s1, s3, 9) = " << setw( 2 ) << strncmp( s1, s3, 9 ) << "\nstrncmp(s3, s1, 9) = " << setw( 2 ) << strncmp( s3, s1, 9 ) << endl; return 0; }
1f846e7254a859fb777394853cc8fe463c9e6718
a75da3ed862028ce488fb8c12633a870a3ff36a3
/include/pc/composite_rtp_transport.h
35f9382571bf12ebee8cb6ab5ea91c81164b997f
[ "Apache-2.0" ]
permissive
ispysoftware/spitfire
e6eb5b31b742a2a86ac95f90b1d01b6683d17f9d
fe2b395207bdea04223854163dbd2b6404ad75f5
refs/heads/master
2021-04-24T12:47:55.240914
2020-03-03T20:51:37
2020-03-03T20:51:37
250,120,278
1
0
Apache-2.0
2020-03-26T00:09:46
2020-03-26T00:09:45
null
UTF-8
C++
false
false
4,800
h
composite_rtp_transport.h
/* * Copyright 2019 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef PC_COMPOSITE_RTP_TRANSPORT_H_ #define PC_COMPOSITE_RTP_TRANSPORT_H_ #include <memory> #include <set> #include <string> #include <vector> #include "call/rtp_demuxer.h" #include "call/rtp_packet_sink_interface.h" #include "pc/rtp_transport_internal.h" #include "pc/session_description.h" #include "rtc_base/async_packet_socket.h" #include "rtc_base/copy_on_write_buffer.h" namespace webrtc { // Composite RTP transport capable of receiving from multiple sub-transports. // // CompositeRtpTransport is receive-only until the caller explicitly chooses // which transport will be used to send and calls |SetSendTransport|. This // choice must be made as part of the SDP negotiation process, based on receipt // of a provisional answer. |CompositeRtpTransport| does not become writable or // ready to send until |SetSendTransport| is called. // // When a full answer is received, the user should replace the composite // transport with the single, chosen RTP transport, then delete the composite // and all non-chosen transports. class CompositeRtpTransport : public RtpTransportInternal { public: // Constructs a composite out of the given |transports|. |transports| must // not be empty. All |transports| must outlive the composite. explicit CompositeRtpTransport(std::vector<RtpTransportInternal*> transports); // Sets which transport will be used for sending packets. Once called, // |IsReadyToSend|, |IsWritable|, and the associated signals will reflect the // state of |send_tranpsort|. void SetSendTransport(RtpTransportInternal* send_transport); // Removes |transport| from the composite. No-op if |transport| is null or // not found in the composite. Removing a transport disconnects all signals // and RTP demux sinks from that transport. The send transport may not be // removed. void RemoveTransport(RtpTransportInternal* transport); // All transports within a composite must have the same name. const std::string& transport_name() const override; int SetRtpOption(rtc::Socket::Option opt, int value) override; int SetRtcpOption(rtc::Socket::Option opt, int value) override; // All transports within a composite must either enable or disable RTCP mux. bool rtcp_mux_enabled() const override; // Enables or disables RTCP mux for all component transports. void SetRtcpMuxEnabled(bool enabled) override; // The composite is ready to send if |send_transport_| is set and ready to // send. bool IsReadyToSend() const override; // The composite is writable if |send_transport_| is set and writable. bool IsWritable(bool rtcp) const override; // Sends an RTP packet. May only be called after |send_transport_| is set. bool SendRtpPacket(rtc::CopyOnWriteBuffer* packet, const rtc::PacketOptions& options, int flags) override; // Sends an RTCP packet. May only be called after |send_transport_| is set. bool SendRtcpPacket(rtc::CopyOnWriteBuffer* packet, const rtc::PacketOptions& options, int flags) override; // Updates the mapping of RTP header extensions for all component transports. void UpdateRtpHeaderExtensionMap( const cricket::RtpHeaderExtensions& header_extensions) override; // SRTP is only active for a composite if it is active for all component // transports. bool IsSrtpActive() const override; // Registers an RTP demux sink with all component transports. bool RegisterRtpDemuxerSink(const RtpDemuxerCriteria& criteria, RtpPacketSinkInterface* sink) override; bool UnregisterRtpDemuxerSink(RtpPacketSinkInterface* sink) override; private: // Receive-side signals. void OnNetworkRouteChanged(absl::optional<rtc::NetworkRoute> route); void OnRtcpPacketReceived(rtc::CopyOnWriteBuffer* packet, int64_t packet_time_us); // Send-side signals. void OnWritableState(bool writable); void OnReadyToSend(bool ready_to_send); void OnSentPacket(const rtc::SentPacket& packet); std::vector<RtpTransportInternal*> transports_; RtpTransportInternal* send_transport_ = nullptr; // Record of registered RTP demuxer sinks. Used to unregister sinks when a // transport is removed. std::set<RtpPacketSinkInterface*> rtp_demuxer_sinks_; }; } // namespace webrtc #endif // PC_COMPOSITE_RTP_TRANSPORT_H_
f0f6c717d0dad86c1dcfd337359c9ae9aeb7ad63
7ca22b3a8e95c03b54c37b33cc49e27240f22274
/include/Table.h
684cee426177f846a07f103818d41c961f3efc75
[]
no_license
almda/Spl-Restaurant
e640f630ed650426fc0717f50b5ed94a8d6d6101
84e2406305c56803807ff21b4c4e465e99b5d5f1
refs/heads/master
2022-12-12T16:21:45.160068
2020-09-14T21:39:51
2020-09-14T21:39:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,263
h
Table.h
#ifndef TABLE_H_ #define TABLE_H_ #include <vector> #include "Customer.h" #include "Dish.h" //This class represents a table in the restaurant //Each table has a finite number of available seats - represented by capacity //indicator if the table is open - bool open //list of orders done by the table - orderList //list of customers in the table - customersList //this class has resource so rule of 5 is needed typedef std::pair<int, Dish> OrderPair; class Table{ public: //Rule Of Five virtual ~Table();//destructor Table(const Table &aTable); //copy constructor Table&operator=(const Table &aTable);//Assignment Operator Table(Table&& other); //The Move Constructor Table &operator=(Table && other);//The Move Assignment Table(int t_capacity); int getCapacity() const; void addCustomer(Customer* customer); void removeCustomer(int id); Customer* getCustomer(int id); std::vector<Customer*>& getCustomers(); std::vector<OrderPair>& getOrders(); void order(const std::vector<Dish> &menu); void openTable(); void closeTable(); int getBill(); bool isOpen(); private: int capacity; bool open; std::vector<Customer*> customersList; std::vector<OrderPair> orderList; }; #endif
a6fd88c31d734302af22cbed084bb2dfa18ea678
4ba4b9de9fc1afe23da48f9dddd7aa071a629b66
/Source.cpp
2166c8b3a5b106b208512aa0ad18cfa36d762b66
[]
no_license
13beehiqbal/HQPlayer
f3951482574f6409f9436601869b8dc7bb52053f
5b485ba05a25c93ec7d96a3e5e352d06ccee30f4
refs/heads/master
2020-04-23T15:19:40.341846
2019-03-05T10:13:40
2019-03-05T10:13:40
171,261,547
0
1
null
null
null
null
UTF-8
C++
false
false
1,406
cpp
Source.cpp
#include<iostream> using namespace std; #include<string> #include"HQPlayer.h" void Menu() { HQPlayer player; char ch; do { char i; cout << "Press a to add song" << endl << "Press d to delete" << endl << "Press s for search" << endl << "Press v for display" << endl << "Press e for backward display" << endl << "Press n for Next Song" << endl << "Press p for previous song"<<endl <<"Press r for repeat all"<<endl <<"Press t for no repeat"<<endl <<"Press u for shuffle"<<endl <<"Press l for play"<<endl; cin >> i; switch (i) { case'a': player.add_song(); break; case'd': player.delete_song(); break; case'v': player.display(); break; case's': player.search(); break; case'e': player.backwards_display(); break; case'n': player.next(); break; case'p': player.previous(); break; case'r': player.repeat_all(); break; case't': player.no_repeat(); break; case'u': player.shuffle(); break; case'l': player.play_from_start(); default: cout << "Bad input" << endl; break; } cout << "want to process more y/n" << endl; cin >> ch; } while (ch != 'n'); } int main() { try{ Menu(); cin.get(); return 0; } catch (int n){ if (n == -1){ cout << "Extension not valid" << endl; } } }
4dbb68d4799b74875d58c294da214e16100315e4
a342390195124fa2ad4773d444383a337b7b757b
/src/turtlebotDetector.cpp
6e819fe6290d11f3aabfc5b2e194f27ec6374f48
[ "MIT" ]
permissive
akhopkar01/turtlebot_inspection_bot
fba49e66306c6b937df18b8056b58da0fd96504b
fd6ad72eef8bd26acd124cce695ce7ad9737d337
refs/heads/master
2023-02-01T04:43:25.108027
2020-12-17T07:21:04
2020-12-17T07:21:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,381
cpp
turtlebotDetector.cpp
/** * * Copyright (c) 2020 Kartik Venkat Kushagra Agrawal Aditya Khopkar * * @section LICENSE * * MIT License * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * @file turtlebotDetector.cpp * * @authors * Kartik Venkat kartik.venkat86@gmail.com \n * Kushagra Agrawal kushagraagrawal425@gmail.com \n * Aditya Khopkar aadi0110@gmail.com \n * * @version 1.0 * * @section DESCRIPTION: * This is the implementation for the Turtlebot Detector node. */ #include <detector.hpp> #include "cv_bridge/cv_bridge.h" #include <opencv2/opencv.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <config.hpp> #define COLOR_ cv::Scalar(0, 0, 255) /** * @brief: Detector class constructor definition * */ AnomalyDetector::AnomalyDetector(ros::NodeHandle& nh) : it_(nh) { P_ = intP * extP; anomalyDetected_ = false; subImg_ = it_.subscribe("/camera/rgb/image_raw", 1, &AnomalyDetector::imgCallback, this); } AnomalyDetector::~AnomalyDetector() { cv::destroyAllWindows(); } /** * @brief: Detection definition * */ void AnomalyDetector::detectAnomaly(bool TEST) { getImgPoints(); // If anomaly is detected if (anomalyDetected_) { cv::Point3f robotCoords = localizePoints(); ROS_WARN_STREAM("Anomaly Detected at: " << robotCoords); } else { ROS_INFO_STREAM("Exploring.."); } if (TEST == false) { cv::imshow("Turtlebot Viewer", cvImg_); cv::waitKey(3); } } /** * @brief: Callback function definition * */ void AnomalyDetector::imgCallback(const sensor_msgs::Image::ConstPtr& msg) { cv_bridge::CvImagePtr cvPtr; try { // Convert ROS image to OpenCV image cvPtr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); cvImg_ = cvPtr->image; // Check if image is empty if (cvImg_.empty()) { ROS_ERROR_STREAM("No callback received, Waiting.."); } else { detectAnomaly(); } } catch(cv_bridge::Exception& exc) { ROS_ERROR_STREAM("CV Bridge Exception " << exc.what()); return; } } /** * @brief: Get image points from the image * */ void AnomalyDetector::getImgPoints() { imgCoords_ = cv::Point2i(0, 0); anomalyDetected_ = false; cv::Mat hsvImg; // Convert image to HSV cv::cvtColor(cvImg_, hsvImg, cv::COLOR_BGR2HSV); // Set threshold to detect green // Create a thresholded mask cv::Scalar greenLo(35, 40, 40); cv::Scalar greenHi(86, 255, 255); cv::inRange(hsvImg, greenLo, greenHi, maskImg_); // Morphological operations opening cv::erode(maskImg_, maskImg_, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(3, 3))); cv::dilate(maskImg_, maskImg_, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(3, 3))); // Morphological operations closing cv::dilate(maskImg_, maskImg_, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(3, 3))); cv::erode(maskImg_, maskImg_, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(3, 3))); // Find centroid of the image cv::Moments moments_ = cv::moments(maskImg_); double Area{moments_.m00}; // Find contours to detect bounding box cv::Rect bounding_rect; std::vector<std::vector<cv::Point2i>> contours; cv::findContours(maskImg_, contours, cv::RETR_CCOMP, cv::CHAIN_APPROX_SIMPLE); // If considerable area if (Area >= 1000.f) { // Bounding Box bounding_rect = cv::boundingRect(contours[0]); int posX = moments_.m10 / Area; int posY = moments_.m01 / Area; imgCoords_.x = posX; imgCoords_.y = posY; cv::putText(cvImg_, "Anomaly", cv::Point2i(posX - 20, posY + 20), cv::FONT_HERSHEY_SIMPLEX, 0.8, COLOR_); cv::rectangle(cvImg_, bounding_rect, COLOR_); anomalyDetected_ = true; } return; } /** * @brief: get robot frame coordinates definition * */ cv::Point3f AnomalyDetector::localizePoints() const { // Perform geometric transformation cv::Matx31f robotPoints; cv::Matx33f H{P_(0, 0), P_(0, 1), P_(0, 3), P_(1, 0), P_(1, 1), P_(1, 3), P_(2, 0), P_(2, 1), P_(2, 3)}; cv::Matx31f pixel{static_cast<float>(imgCoords_.x), static_cast<float>(imgCoords_.y), 1}; robotPoints = H.inv() * pixel; float w = robotPoints(2); float u{robotPoints(0)}, v{robotPoints(1)}; return {u/w, v/w, 0}; }
c5ba120e41b0873276123dd3fe6d5601eaf0a17f
cac4474b23cdcced68559676e5e262035e0b30ea
/TowerDefeneseGame/Mobs.hpp
5644c6a40ed9e3296f6e12ba62642c149899f3d1
[]
no_license
Arozzal/TowerDefenseGame
d95b2f38cd9960969e13dc5eaec480c0dc87654b
9c0172682ccf6f9776ddfb545bb3ea6d718e7072
refs/heads/master
2023-06-03T15:55:37.779125
2021-06-25T15:37:43
2021-06-25T15:37:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,144
hpp
Mobs.hpp
#pragma once #include "Mob.hpp" class MobGreenTank : public Mob { public: MobGreenTank(int xpos, int ypos); void update(Game& game) override; void draw(Game& game) override; }; class MobSmallCar : public Mob { public: MobSmallCar(int xpos, int ypos); void update(Game& game) override; void draw(Game& game) override; }; class MobVeryTinyCar : public Mob { public: MobVeryTinyCar(int xpos, int ypos); void update(Game& game) override; void draw(Game& game) override; }; class MobTankGray : public Mob { public: MobTankGray(int xpos, int ypos); void update(Game& game) override; void draw(Game& game) override; }; class MobSphere : public Mob { bool hascreated = false; public: MobSphere(int xpos, int ypos); void update(Game& game) override; void draw(Game& game) override; }; class MobPlane : public Mob { public: MobPlane(int xpos, int ypos); void update(Game& game) override; void draw(Game& game) override; }; class MobFlyingBomb : public Mob { sf::Vector2f followunitpos; bool hasdamaged = false; public: MobFlyingBomb(int xpos, int ypos); void update(Game& game) override; void draw(Game& game) override; };
5410feb7fb722fc9cb247399b6785f0b5ed1b5a9
f23264b4529de3464f7b41acd17405ad29b0cf5c
/Anul 1/Semestrul 1/Algoritmi si Structuri de Date - Miroiu Maria/Laborator/ASD15/R2_Forma_Poloneza.cpp
2b065ce2dd9b0935816a55ad1c5c297ebcef39dd
[]
no_license
PMS25/Facultate
43c30c723a17f66f7543270bb1e31aeb4c58bfdf
6c3dee9772e365b0b0eceed5e3e0c31622c1c888
refs/heads/master
2021-09-08T07:44:47.538072
2021-05-22T11:44:21
2021-05-22T11:44:21
221,477,050
0
0
null
null
null
null
UTF-8
C++
false
false
1,204
cpp
R2_Forma_Poloneza.cpp
#include <iostream> #include <cstring> using namespace std; #define NMAX 30 char s[NMAX]; char stiva[NMAX]; int varf; char fp[NMAX]; int n=-1; int Prioritate(char c){ switch(c){ case '*': case '/': return 2; case '+': case '-': return 1; case '(': case ')': return 0; default: return -1; } } void Convertire(){ for(int i=0; i<strlen(s); i++) switch (s[i]){ case '(': stiva[++varf]='('; break; case ')': while(stiva[varf]!='(') fp[++n] = stiva[varf--]; varf--; break; case '+': case '-': case '*': case '/': while(Prioritate(stiva[varf]) >= Prioritate(s[i])) fp[++n] = stiva[varf--]; stiva[++varf] = s[i]; break; default: fp[++n] = s[i]; } } void Citire(){ cout<<"Dati ecuatia: "; cin.get(s,NMAX); cin.get(); int l = strlen(s); for(int i=l; i>0; i--) s[i] = s[i-1]; s[0] = '('; s[l+1] = ')'; cout<<s<<endl; } int main(){ Citire(); Convertire(); cout<<"Forma poloneza: "<<fp<<endl; }
1fa4dd1abe9a8b129042e62929a1b1014a33bfde
6b731c15869e1d37f43f2573d5d4a774c88f43a8
/MuseEngine/Muse/src/Core/ECS/Component/CameraComponent.h
68ff43a107984e561ba60ecda22821d2c8924257
[]
no_license
Daniel95/MuseEngine
546151aaf510077c6e0088a582eb847892037e5a
8119dff8f783ae2c63b726a82762aa68fd91d5fe
refs/heads/master
2020-10-02T04:05:37.898613
2020-09-04T17:35:46
2020-09-04T17:35:46
227,696,196
0
2
null
null
null
null
UTF-8
C++
false
false
1,920
h
CameraComponent.h
#pragma once #include "glm/glm.hpp" #include <glm/gtc/matrix_transform.hpp> namespace Muse { class TransformComponent; class CameraComponent { public: CameraComponent(); ~CameraComponent() = default; void SetProjection(float a_AspectRatio, float a_ZoomLevel); void SetProjectionMatrix(float a_Left, float a_Right, float a_Bottom, float a_Top, float a_Near = -1.0, float a_Far = 1.0); const glm::mat4& GetProjectionViewMatrix(TransformComponent& a_TransformComponent); void SetZoomLevel(float a_ZoomLevel) { SetProjection(m_AspectRatio, a_ZoomLevel); } float GetZoomLevel() { return m_ZoomLevel; } void SetAspectRatio(float a_AspectRatio) { SetProjection(a_AspectRatio, m_ZoomLevel); } float GetAspectRatio() { return m_AspectRatio; } void SetFixedAspectRatio(bool a_FixedAspectRatio) { m_FixedAspectRatio = a_FixedAspectRatio; } bool GetFixedAspectRatio() { return m_FixedAspectRatio; } void SetViewportSize(uint32_t a_Width, uint32_t a_Height); void SetOrthographicSize(float a_Size); float GetOrthographicSize() const { return m_OrthographicSize; } static CameraComponent* GetMain() { return s_MainCamera; }; static void SetMain(CameraComponent* a_CameraComponent) { s_MainCamera = a_CameraComponent; }; private: void RecalculateProjection(); glm::mat4 m_ViewMatrix = glm::identity<glm::mat4>(); glm::mat4 m_ProjectionMatrix = glm::identity<glm::mat4>(); glm::mat4 m_ViewProjectionMatrix = glm::identity<glm::mat4>(); float m_ZoomLevel = 1.0f; float m_AspectRatio = 1.6f; float m_OrthographicSize = 10.0f; float m_OrthographicNear = -1.0f, m_OrthographicFar = 1.0f; bool m_IsDirty = true; bool m_FixedAspectRatio = false; static CameraComponent* s_MainCamera; }; }
abf8408991e5c978658ed511769648121275d0f4
3e6f75da8292ded75bf0b474e910d67d7850ac91
/UEB12/ListenDialog.h
44bc10d48dfb86467c044aefd40801fb7eb9ec27
[]
no_license
Prog2-2015-HTWSAAR/UEB12
5fc2030eed69927f6a01b819420b1017f8b9886c
29bc9b83f9f7a22bda272ab8ee5622bd0374e1ae
refs/heads/master
2021-03-12T19:46:52.604006
2015-07-20T22:02:30
2015-07-20T22:02:30
39,314,904
0
0
null
null
null
null
ISO-8859-3
C++
false
false
6,021
h
ListenDialog.h
/** * compile: g++ -c -Wall -pedantic *.cpp * compile: g++ -o ueb08 *.o * @file ListenDialog.h * @author Andreas Schreiner & Simon Bastian * Changelog: https://onedrive.live.com/redir?page=view&resid=A24EC16A1F3E72AA!4270&authkey=!AFE0aRW5WKEHg3Q * * @date 14.06.2015 */ #include "LinList.h" #include <iostream> #include <sstream> #ifndef LINLIST_LISTENDIALOG_H_ #define LINLIST_LISTENDIALOG_H_ enum LanguageDialogOption{ CLOSEPROGRAM, GERMAN, ENGLISH, HODOR, START_MAINDIALOG, runAgain}; enum MainDialogOption{ EXIT, AUTOMATICTEST, MANUELLDIALOG}; enum ManuellDialogOption{ BACK, PUSH_BACK, PUSH_FRONT, POP_BACK, POP_FRONT, INSERT_ELEMENT, ERASE_ELEMENT, CLEAR, STREAM, SAVE_BACKUP, LOAD_BACKUP, FILE_DIALOG, ABORT }; enum AutomaticTestOption{ AUTO_INIT ,AUTO_PUSH_BACK, AUTO_PUSH_FRONT, AUTO_POP_BACK, AUTO_POP_FRONT, AUTO_INSERT, AUTO_INSERT_HIGH_VALUE, AUTO_INSERT_LOW_VALUE, AUTO_ERASE, AUTO_ERASE_ZERO, AUTO_ERASE_NON_EXISTENT_ELEMENT, AUTO_INPUT_STREAM, AUTO_COPY_TEST, AUTO_TEST_EQUAL_ONE, AUTO_TEST_NON_EQUAL_ONE, AUTO_APPEND, AUTO_TEST_EQUAL_TWO, AUTO_TEST_NON_EQUAL_TWO, AUTO_COMBINE, ELEMENT_AT_POSITION, AUTO_CLEAR, POP_EMPTY }; //enum FileDialogOption{ CLOSE_FILE_DIALOG, SAVE, LOAD }; class ListenDialog { public: //Konstanten //Seperators static const char* SPACER; static const string PARSE_COPY; //Errorphrasses // LanguageDialog static const string STD_LANG_NOT_FOUND; static const string DE_DE_LANG_NOT_FOUND; static const string EN_US_LANG_NOT_FOUND; static const string HODOR_WESTEROS_LANG_NOT_FOUND; static const string PARSE_LANGUAGEDIALOG; static const string LANGUAGE_GERMAN; static const string LANGUAGE_ENGLISH; static const string LANGUAGE_HODOR; static const string LANGUAGE_STD; static const string STD_INP_PHRASE; // Maindialog static const string PARSE_SEPERATOR_LINLIST_BLOCK; static const string PARSE_MAINDIALOG; //ManuellDialog static const string PARSE_MANUELLDIALOG; static const string PARSE_SEPERATOR_DELETE_LISTE; static const string PARSE_SEPERATOR_MANUELL_BLOCK; static const string PARSE_SEPERATOR_INSERT; static const string PARSE_SEPERATOR_ERASE; static const string PARSE_SEPERATOR_CLEAR; static const string PARSE_SEPERATOR_PUSH ; static const string PARSE_SEPERATOR_POP; static const string PARSE_SEPERATOR_BACKUP; static const string PARSE_PHRASE_NAME; static const string PARSE_PHRASE_POSITION; static const string PARSE_PHRASE_ELEMENT_DELETE_BACK_CONFIRMATION; static const string PARSE_PHRASE_ELEMENT_DELETE_CONFIRMATION; static const string PARSE_PHRASE_CLEAR_CONFIRMATION; static const string PARSE_PHRASE_LOAD_CONFIRMATION; static const string PARSE_PHRASE_SAVE_CONFIRMATION; static const string PARSE_PHRASE_READ_STREAM; static const string CONFIRM_DELETE; // Automatic Test static const string PARSE_AUTOMATICTEST; static const string PARSE_A_INIT_PUSH; static const string PARSE_A_PUSH_BACK; static const string PARSE_A_PUSH_FRONT; static const string PARSE_A_POP_BACK; static const string PARSE_A_POP_FRONT; static const string PARSE_A_INSERT; static const string PARSE_A_ERASE; static const string PARSE_A_READ; static const string PARSE_A_CLEAR; static const string PARSE_A_POP_EMPTY; static const string PARSE_A_INIT; static const string PARSE_A_BACK; static const string PARSE_A_FRONT; static const string PARSE_A_IMHERE; static const string PARSE_A_HIGH; static const string PARSE_A_LOW; static const string PARSE_A_INPUT_STREAM; static const string PARSE_A_INPUT_STREAM_VALUE; // Allgemein static const string PARSE_INPUT_ERROR; static const string PARSE_STD_ERROR; static const string PARSE_EQUAL; static const string PARSE_NON_EQUAL; static const string PARSE_APPEND_LIST; static const string PARSE_COMBINE_LIST; static const string PARSE_ELEMENT_AT_POSITION; static const string CHECK_EQUAL; static const string CHECK_NON_EQUAL; //const Int static const int STD_ANSWER_VALUE; static const int ZERO_VALUE; static const int INPUT_ONE; static const int INPUT_VALUE; static const int HIGH_VALUE; static const int TEST_QUANTITY; static const int MAX_RUNS_FILE_READ; static const int A_REGULAR_OUTPUT_STOPER; static const int ARRAY_OPERATOR_TEST_VALUE; //FKT /** * @brief mainDialog() * @details HauptDialog Auswahl Auto Manuell Exit */ void mainDialog(string &fileName); /** * @brief automaticTest() * @details Automatischer Test */ void automaticTest(string &fileName); /** * @brief manuellDialog() * @details Manuelle Steuerung Des Programmes */ void manuellDialog(string &fileName); /* * @brief fileDialog(LinList* linListe, string fileName) * @details SAVE AND LOAD * @param *linListe Listenreferenz * @param fileName Dateiname */ // void fileDialog(LinList* linListe, string fileName); /** * @brief clearInput() * @details Im Falle einer falschen eingabe leer dies den Eingabepuffer. */ void clearInput(); /** * @brief initLanguage() * @details Language Dialog */ void initLanguage(); /** * @brief fileExists prüft existenz * @param fileName Xml Datei die genutzt werden soll */ bool fileExists(string fileName); /** * @brief readIntegerInput read in int */ int readIntegerInput(); /** * @brief readIntegerInput read in double */ double readDoubleInput(); /** * @brief readIntegerInput read in string */ string readStringInput(); /** * @brief parsePhrases Xml Parser * @param fileName Xml Datei die genutzt werden soll * @param begin String in Xml Datei der als start und endpunkt gennommen werden soll */ string parsePhrases(string fileName, string begin); /** * @brief trim string trimmer * @param str String Referenz */ void trim(std::string& str); /** * @brief Konstruktor */ ListenDialog(); /** * @brief Dekonstruktor */ virtual ~ListenDialog(); }; #endif /* LINLIST_LISTENDIALOG_H_ */
7581abb99af9a9f1c5c8dbc0900ca4e324c850a0
40ca2419b494a1dbe4c0b2d3bea5db26f86ff040
/C++ chapter_ten/10_27/10_27.cpp
911996aae91b26fb48351d8c275176aca8dc4803
[]
no_license
whix/my_code_for_cpp_primer_5th
73c16a082ef400a4980fefb1b790616982035878
d3c1141caaea79ee4b48208b7a2aaf5570ef3968
refs/heads/master
2021-01-22T05:15:33.903737
2015-07-13T03:16:55
2015-07-13T03:16:55
38,985,529
0
0
null
null
null
null
GB18030
C++
false
false
605
cpp
10_27.cpp
//使用unique_copy函数,第三个参数要使用back_inserter迭代器,记住算法不改变容器大小~ 20141202 wan #include <iostream> #include <list> #include <algorithm> #include <vector> #include <string> using namespace std; int main(){ vector<string> words; string tmp; cout << "Enter some strings(Ctrl+Z to end) :" << endl; while(cin >> tmp){ words.push_back(tmp); } list<string> words_copy; unique_copy(words.begin(), words.end(), back_inserter(words_copy)); for_each(words_copy.begin(), words_copy.end(), [](const string &s){ cout << s << " ";}); system("pause"); }
5405361a869c066a52a7a3932976ec954a7436f0
43cef8331c78b0f1179940885b0e48aaad375a9e
/SDLWrappers/ScaledSurface.cpp
2d7078b6267e3eb81e3a6642d0c360290ace49a2
[]
no_license
hackerlank/JERonimo
70c1eccd98e99ec025fd0b9a02ff6f8ff53e364b
fb2c28c93e4b8b48a924d8abfb6a1b0f25987fbe
refs/heads/master
2020-06-13T06:52:11.529189
2014-11-16T01:05:40
2014-11-16T01:05:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,240
cpp
ScaledSurface.cpp
#include "ScaledSurface.h" namespace jer { ScaledSurface& ScaledSurface::operator= (const ScaledSurface &other) { this->operator=(other); resize(other.getDim()); } const SUCCESS ScaledSurface::load() { const SUCCESS ret = Surface::load(); return ret | resize(); } const SUCCESS ScaledSurface::resize(const Dimensions<int> &d) { size = d; if(isLoaded()) { if(getDim() != size) { Surface old(*this); Surface::operator=(SDL_CreateRGBSurface(0, size.x(), size.y(), (*this)->format->BitsPerPixel, (*this)->format->Rmask, (*this)->format->Gmask, (*this)->format->Bmask, (*this)->format->Amask)); if(getSurf() == nullptr) return FAILED; if(SDL_BlitScaled(old, NULL, *this, NULL) < SUCCEEDED) { Surface::FileLoadable::unload(); return FAILED; } else return SUCCEEDED; } } return SUCCEEDED; } }
3c26b48fd06789aefaf111f91096dc7dd1d06ed1
ee50ace26abde4ed4374bb30e6529f7503c56e34
/OpenMP/SummarySin.cpp
bf30452f59b85c592de545975481f893fdb8b777
[ "MIT" ]
permissive
ebaty/ParallelProgramming
64b0aba4f0aecb1b5e27bcd71dbc95c720f7efd6
6212f8c6601bb6dd6e365dfa0866d6fa11e44745
refs/heads/master
2021-01-10T12:23:10.346335
2015-12-16T05:37:23
2015-12-16T05:37:23
48,089,419
0
0
null
null
null
null
UTF-8
C++
false
false
558
cpp
SummarySin.cpp
#include <cstdio> #include <iostream> #include <cmath> #include <omp.h> #define kSize 1000000000 using namespace std; void printThreads() { int count; #pragma omp parallel { count = omp_get_num_threads(); } cout << "use thread: " << count << endl; } int main(void) { printThreads(); static double array[kSize]; for(int i = 0; i < kSize; ++i) array[i] = sin( (i+1) / kSize ); double sum = 0; #pragma omp parallel { #pragma omp for reduction(+:sum) for(int i = 0; i < kSize; ++i) sum += array[i]; } cout << sum << endl; return 0; }
588cca32165a42879358d1dcac37fe5eb23cb2f2
99dd9323eafaea5344b74f1c46beb8dc6ed883ce
/neurons/BasicNeuron.cpp
f119f43410049fa8170cecf9b12a924d6154fd17
[]
no_license
Izeren/spikeflow
59aed8d28a9f7271a4fbc1792efb0c8e1ed087c0
0a56c92119de9ce247a46f66d53dfb36150421e3
refs/heads/master
2021-08-07T09:35:46.472318
2021-06-23T18:25:16
2021-06-23T18:25:16
178,170,574
2
0
null
null
null
null
UTF-8
C++
false
false
2,214
cpp
BasicNeuron.cpp
#include <BasicSynapse.h> #include "BasicNeuron.h" float BasicNeuron::ProcessInputSpike( SPIKING_NN::Time time, SPIKING_NN::Potential _potential ) { potential = _potential; } void BasicNeuron::Reset() { potential = 0; consistent = true; grad = 0; inputSpikeCounter = 0; outputSpikeCounter = 0; grad = 0; } void BasicNeuron::ResetGrad() { grad = 0; } void BasicNeuron::RandomInit( float alpha, size_t layerSize, size_t nextLayerSize, float z, std::uniform_real_distribution<float> &dist, std::default_random_engine &generator ) { } BasicNeuron::BasicNeuron() { outputSynapses = std::unordered_set<ISynapse *>(); inputSynapses = std::unordered_set<ISynapse *>(); potential = 0; tRef = 0; consistent = true; grad = 0; inputSpikeCounter = 0; outputSpikeCounter = 0; } void BasicNeuron::RelaxOutput( SPIKING_NN::Time time, bool withSpike ) { } void BasicNeuron::Backward( float sumOutput, float delta, size_t totalNeurons, size_t activeNeurons, float meanReversedSquaredThresholds ) { if ( outputSynapses.empty()) { grad = delta; } for ( ISynapse *outputSynapse: outputSynapses ) { auto outputSynapsePtr = outputSynapse; if ( !( outputSynapsePtr->IsUpdatable())) { continue; } auto next = outputSynapsePtr->GetPostSynapticNeuron(); grad += next->GetGrad() * outputSynapsePtr->GetStrength(); outputSynapsePtr->Backward( potential ); } } void BasicNeuron::SetGrad( float _grad ) { grad = _grad; } float BasicNeuron::GetGrad() const { return grad; } void BasicNeuron::GradStep( float learningRate, size_t neurons, size_t inputSynapses, size_t inputActiveSynapses ) { // Does nothing cause we don't have neuron based dynamic parameters } float BasicNeuron::GetOutput() const { return potential; } float BasicNeuron::NormalizePotential( SPIKING_NN::Time time ) { // Does nothing because this logic is not applicable } SPIKING_NN::Time BasicNeuron::GetFirstSpikeTS() { // Returns -1 as spike logic is not applicable return -1; } float BasicNeuron::GetMaxMP() { return 0; }
2a3b3bf9652ada42a7e2bc70c1235ac742688a4b
cb6c5cf210f7da4c42fe547adeb26800ec2dc33d
/src/swf/oglMesh.cpp
9c5847d5c0201b31e5f4c09c09a82805a1af42cc
[]
no_license
magnusl/FlashPlayer
c4fd4ae00089f68eb549ab9bc5bc7a76cc169a99
57c873edea93e8fbf989d46c6fd29203293db5f6
refs/heads/master
2020-03-07T10:16:41.267126
2018-03-30T12:57:06
2018-03-30T12:57:06
127,427,652
0
1
null
null
null
null
UTF-8
C++
false
false
4,144
cpp
oglMesh.cpp
#include "oglMesh.h" #include "CGLTexture.h" #include "gfxGradient.h" #include "gfxMesh.h" #include <memory> #include <GL\glew.h> using namespace std; namespace swf { namespace ogl { static bool generateTexture(const gfx::Gradient_t & a_Gradient, uint8_t a_Texture[], size_t a_TextureSize); std::shared_ptr<ogl::Shape> CreateOGLShape(const std::vector<gfx::Mesh> & meshes) { shared_ptr<ogl::Shape> shape = make_shared<ogl::Shape>(); if (!meshes.size()) { return shape; } shape->meshes.resize(meshes.size()); for(size_t i = 0; i < meshes.size(); ++i) { if (!(shape->meshes[i] = CreateOGLMesh(meshes[i]))) { return std::shared_ptr<ogl::Shape>(); } } return shape; } /** * Creates a OpenGL mesh from a gfx::Mesh. */ std::shared_ptr<ogl::Mesh> CreateOGLMesh(const gfx::Mesh & gfxMesh) { shared_ptr<ogl::Mesh> glMesh = make_shared<ogl::Mesh>(); if (gfxMesh.VertexData.empty() || gfxMesh.Indicies.empty()) { return shared_ptr<ogl::Mesh>(); } glMesh->m_Verticies = std::make_shared<ogl::CGLVertexBuffer>(&gfxMesh.VertexData[0], gfxMesh.VertexData.size() * sizeof(gfx::Point_t<float>), GL_STATIC_DRAW); glMesh->m_Indicies = std::make_shared<CGLIndexBuffer>(&gfxMesh.Indicies[0], gfxMesh.Indicies.size() * sizeof(gfx::Triangle_t)); if (!gfxMesh.TextureCoords.empty()) { glMesh->m_TexCoords = std::make_shared<CGLVertexBuffer>(&gfxMesh.TextureCoords[0], gfxMesh.TextureCoords.size() * sizeof(gfx::Point_t<float>), GL_STATIC_DRAW); } glMesh->m_Material = gfxMesh.Material; glMesh->m_NumIndicies = gfxMesh.Indicies.size() * 3; glMesh->m_Filled = true; glMesh->m_ShapeBounds = gfxMesh.Bounds; switch(gfxMesh.Material.MaterialType) { case gfx::Material::MATERIAL_LINEAR_GRADIENT: case gfx::Material::MATERIAL_RADIAL_GRADIENT: { uint8_t texture[1024]; generateTexture(glMesh->m_Material.Gradient, texture, 1024); glMesh->m_Texture = std::make_shared<CGLTexture1D>(CGLTexture::eRGBA_TEXTURE, texture, 256); break; } } return glMesh; } static void interpolatePoints(const gfx::GradientPoint_t & a_Start, const gfx::GradientPoint_t & a_End, uint8_t a_Texture[]) { size_t num = a_End.Ratio - a_Start.Ratio; if (!num) { return; } float dt[4]; dt[0] = (a_End.Color[0] - a_Start.Color[0]) / num; dt[1] = (a_End.Color[1] - a_Start.Color[1]) / num; dt[2] = (a_End.Color[2] - a_Start.Color[2]) / num; dt[3] = (a_End.Color[3] - a_Start.Color[3]) / num; size_t c = 0; size_t index = a_Start.Ratio * 4; for(size_t i = a_Start.Ratio; i < a_End.Ratio; ++i) { a_Texture[index++] = (uint8_t) ((a_Start.Color[0] + dt[0] * c) * 255); a_Texture[index++] = (uint8_t) ((a_Start.Color[1] + dt[1] * c) * 255); a_Texture[index++] = (uint8_t) ((a_Start.Color[2] + dt[2] * c) * 255); a_Texture[index++] = (uint8_t) ((a_Start.Color[3] + dt[3] * c) * 255); ++c; } } static bool generateTexture(const gfx::Gradient_t & a_Gradient, uint8_t a_Texture[], size_t a_TextureSize) { if ((a_TextureSize < 1024) || (a_Gradient.Count == 0)) { return false; } /** a dummy start point that will be used if the first ratio isn't zero */ gfx::GradientPoint_t start = {{0.0f, 0.0f,0.0f, 1.0f}, 0}; gfx::GradientPoint_t stop = {{0.0f, 0.0f,0.0f, 0.0f}, 255}; if (a_Gradient.Points[0].Ratio != 0) { gfx::GradientPoint_t p = a_Gradient.Points[0]; p.Ratio = 0; interpolatePoints(p, a_Gradient.Points[0], a_Texture); } for(uint8_t i = 0; i < (a_Gradient.Count - 1); ++i) { interpolatePoints(a_Gradient.Points[i], a_Gradient.Points[i + 1], a_Texture); } interpolatePoints(a_Gradient.Points[a_Gradient.Count - 1], stop, a_Texture); return true; } } }
b4574b8e881292f3358783b0b18128e75a0581c2
8015792b79fe76987e36594c1915001df315d6d6
/HM-27/6-BubbleSort.cpp
d1c82cf6b0470a47f17a7ac3eb94f8499564d15a
[]
no_license
WhiteRabbit-21/C-Exercise
7ecd3e0bcdf6134fcb021ed02f9a3aacbe28690e
21cdb8aae9887812902b6b94dec260acc6aed9f2
refs/heads/master
2020-09-13T10:20:58.991478
2020-05-02T04:34:51
2020-05-02T04:34:51
222,740,391
1
0
null
null
null
null
UTF-8
C++
false
false
1,520
cpp
6-BubbleSort.cpp
#include <iostream> #include <ctime> using namespace std; void RandArray(int N, int Array[]) { for (int i = 0; i < N; i++) { Array[i] = rand() % 21; } } void PrintArray(int N, int Array[]) { for (int i = 0; i < N; i++) { cout << Array[i] << "\t"; } cout << endl; } int Ret(int Num) { int tmp, tmp1; tmp1 = Num; while (Num > 0) { tmp = Num % 10; if (tmp == 7) { return tmp1; } else { Num = Num / 10; } } return 0; } //6. Дано лінійний масив цілих чисел. Відсортувати масив двома способами наступним чином: спочатку йдуть невпорядковані числа, що містять цифру 7, потім всі інші числа. void BubbleSort(int cnt, int *Array ) { int temp; bool p = true; while (p) { p = false; for (int i = 1; i < cnt; i++) if (Ret(Array[i]) != 0) { temp = Array[i - 1]; Array[i - 1] = Array[i]; Array[i] = temp; p = true; } cnt--; } } int main() { srand(time(0)); //6. Дано лінійний масив цілих чисел. Відсортувати масив двома способами наступним чином: спочатку йдуть невпорядковані числа, що містять цифру 7, потім всі інші числа. int N; cout << "Enter N"; cin >> N; int *Array = new int[N]; RandArray(N, Array); PrintArray(N, Array); BubbleSort(N, Array); PrintArray(N, Array); }
ed9b9096c3df35553c3b647651d7054e596596ae
10e0e4a6021587a032317ef62d94cae56b44d6d6
/sources/CRecordingSettingsList.h
4d7e9ee35e17ad4fd821f3ac10e072a22abf5f98
[]
no_license
jamiepg1/veris6
8cb52122d26438f192644506a1a6fb289ba7cecd
e1639d3b79388b6dfa6fb055f419ed41ee615a21
refs/heads/master
2018-03-26T16:45:01.203355
2014-08-06T00:30:09
2014-08-06T00:30:09
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,536
h
CRecordingSettingsList.h
// =================================================================== // CRecordingSettingsList.h ©2006-2011 EDI // =================================================================== #pragma once #include "CFileList.h" #include "CRecordingSettingsFileItem.h" class CRecordingSettingsList : public CFileList<CRecordingSettingsFileItem> { public: CRecordingSettingsList(); CRecordingSettingsList(long inItems); CRecordingSettingsList(CRecordingSettingsList *inList); virtual ~CRecordingSettingsList(); virtual long GetVersion (); virtual void Load (LStream& inStream); virtual void LoadVariables (LStream& inStream); virtual void Save (LStream& inStream); virtual void SaveChangedFiles (); CRecordingSettingsFileItem *GetFileItem(CTestNum inTestNum); CRecordingSettingsFileItem *GetFileItem(CSetupData *inSetupData); void CheckForUniqueTestNums(); protected: virtual CRecordingSettingsFileItem *MakeFileItem(CFileRef inFileRef); virtual LStr255 GetFileTypeStr (); virtual LStr255 GetCacheName (); virtual void ConvertFile (CFileRef inFileRef); virtual OSErr ReadFileData (CRecordingSettingsFileItem *ioFileItem); virtual void * MakeFileList (); private: void UndoChangedFiles (); void LoadOldVersion (LStream& inStream); long mVersion; }; inline LStr255 CRecordingSettingsList::GetFileTypeStr() { return kRecordingSettingsFolder; } inline LStr255 CRecordingSettingsList::GetCacheName() { return kRecordingSettingsCache; }
0351bfd1d8fc69650c0fd1ec88ce95bd161d747d
5ca8458b07d6c632abfdc26001cee52c56f2104b
/nullunit/src/t_stream_reporter.h
8a9a86465b02d78a687c07a59bd04af9d461733a
[ "BSD-2-Clause" ]
permissive
dcbGH/nullunit
2fead5cc18c4f4e20561d1b80920691d40ef1c0c
dd3075877359fc53d1b56dbba9f3e7c7d003dad1
refs/heads/master
2021-01-11T04:06:06.337537
2012-09-08T04:44:51
2012-09-08T04:44:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,654
h
t_stream_reporter.h
// Copyright (c) 2011-2012, Jonathan Clark // All rights reserved. // // This software is licensed under the two-clause Simplified BSD License. // The text of this license is available from: // http://www.opensource.org/licenses/bsd-license.php #ifndef _T_STREAM_REPORTER_H_INCLUDED_ #define _T_STREAM_REPORTER_H_INCLUDED_ #include "nullunit/internal/t_reporter.h" #include <string> #include <unordered_map> #include <unordered_set> #include <iostream> namespace NullUnit { class StreamReporter : public Reporter { std::ostream& stream; std::unordered_map<std::string, unsigned int> suiteSuccesses; std::unordered_map<std::string, unsigned int> suiteFailures; unsigned int packageSuccesses; unsigned int packageFailures; private: void AddSuccess(const std::string& suite_name); void AddFailure(const std::string& suite_name); public: StreamReporter(std::ostream& s); void ListBegin(); void ListEnd(); void ListEntrySuite(const std::string& suite_name, const std::string& filename, int linenumber); void ListEntryCase(const std::string& suite_name, const std::string& case_name, const std::string& filename, int linenumber); void ReportBegin(); void ReportEnd(); void SuiteBegin(const std::string& suite_name); void SuiteEnd(const std::string& suite_name); void CaseBegin(const std::string& suite_name, const std::string& case_name); void CaseEnd(const std::string& suite_name, const std::string& case_name); void CasePass(const std::string& suite_name, const std::string& case_name); void CaseFail(const std::string& suite_name, const std::string& case_name, const std::string& reason, const std::string& filename, int lineNumber); void CaseStdExceptionFail(const std::string& suite_name, const std::string& case_name, const std::string& what, const std::string& filename, int lineNumber); void CaseUnhandledExceptionFail(const std::string& suite_name, const std::string& case_name, const std::string& filename, int lineNumber); void CaseAssertionFail(const std::string& suite_name, const std::string& case_name, const std::string& reason, const std::string& filename, int lineNumber); void CaseExpectationFail(const std::string& suite_name, const std::string& case_name, const std::string& reason, const std::string& filename, int lineNumber); void FixtureSetupFail(const std::string& suite_name, const std::string& case_name, const std::string& filename, int lineNumber); void FixtureTeardownFail(const std::string& suite_name, const std::string& case_name, const std::string& filename, int lineNumber); }; } #endif // _T_STREAM_REPORTER_H_INCLUDED_
9ee7dc83348ccb915f2bbdc9042e69fb95847d19
d3f27b69c3fd34bdf426a9fb9463b98a0b3d8dbb
/main.cpp
61ca34674b4a19a29af8c9c934a6586d1b49aa57
[]
no_license
qingliansuiying/work6
7f55a67683931e2f42c3a6d22438fd51a18ac7ac
c48ff4e4639528fb6cfa9c42322a963f3edfdaea
refs/heads/master
2021-01-23T04:48:34.145535
2017-06-09T13:19:44
2017-06-09T13:19:44
92,943,246
0
0
null
null
null
null
GB18030
C++
false
false
1,339
cpp
main.cpp
#include<iostream> #include<ctime> #include <fstream> #include<string> #include<stdlib.h> #include<string.h> #include "head.h" using namespace std; int main() { string lan[10]; //存储语言 char s[30]; //s存储表达式 int i=0,sum=0,language,type,answer=0; float check=0; //用于储存式子答案 Interaction inter; File file; Calculate caculate; RandomNumber randomnumber; RandomOperation randomoperation; Judge judge; cout<<"Welcom!"<<"Please choose the language you need:"<<endl; //进行语言选择 cout<<"1.中文"<<" "<<"2.英文"<<endl; cin>>language; file.Language(language,lan); cout<<lan[0]; cin>>sum; while(judge.Judgeend(i,sum)) { randomnumber.random(); randomoperation.random(); RandomExpression randomexpression(randomnumber,randomoperation); randomexpression.random(s); check=caculate.calculateresult(s); if(judge.Judgeresult(check)) //输出式子 { i++; for(i=0;i<strlen(s);i++) { cout<<s[i]; } cout<<'='; cin>>answer; if(judge.Judgeanswer(answer,check)) //判断答案正误 { cout<<lan[1]<<endl; inter.Statistics(1); } else { cout<<lan[2]<<check<<endl; inter.Statistics(0); } } } cout<<lan[3]<<inter.getright()<<endl; //输出统计结果 cout<<lan[4]<<inter.getwrong()<<endl; return 0; }
e9af8f7e1c5c88b24d562f0f8743cd9f30c461e9
7e62f0928681aaaecae7daf360bdd9166299b000
/external/DirectXShaderCompiler/tools/clang/test/PCH/Inputs/working-directory-1.h
73eba50627d0a7127e8515394979331cae6367ed
[ "NCSA", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yuri410/rpg
949b001bd0aec47e2a046421da0ff2a1db62ce34
266282ed8cfc7cd82e8c853f6f01706903c24628
refs/heads/master
2020-08-03T09:39:42.253100
2020-06-16T15:38:03
2020-06-16T15:38:03
211,698,323
0
0
null
null
null
null
UTF-8
C++
false
false
63
h
working-directory-1.h
template<typename T> struct A { A() { int a; } };
9430bf802477cbd78a7e3abde0e6d40a4cb0d541
67fc20f8917fa808a762eebab6355ec33475adba
/Problemsetting/24R1/8/validator.cpp
1794a1452ef5987fd5b18e06a78910f76abe18cd
[]
no_license
DreadArceus/Codeforces
ac557f4b28ad813471e71b6ba9acbfcd2d028044
e34d0ff9535987c2dc8e1f92fbc466223e6c8b4f
refs/heads/master
2023-06-04T16:55:55.576281
2021-06-15T02:01:10
2021-06-15T02:01:10
277,622,351
0
1
null
2020-09-30T19:14:59
2020-07-06T18:46:09
C++
UTF-8
C++
false
false
1,151
cpp
validator.cpp
#include <vector> #include <queue> #include "testlib.h" using namespace std; vector<vector<int>> graph; vector<bool> visited; void bfs(int source) { visited[source] = true; queue<int> q; q.push(source); while (!q.empty()) { int x = q.front(); q.pop(); for (auto y : graph[x]) { if (!visited[y]) { visited[y] = true; q.push(y); } } } } int main(int argc, char *argv[]) { registerValidation(argc, argv); int n = inf.readInt(1, 100000, "n"); visited.resize(n); graph.resize(n); inf.readSpace(); int m = inf.readInt(1, 1000000, "m"); inf.readEoln(); for (int i = 0; i < m; i++) { int u = inf.readInt(1, n, "u"); inf.readSpace(); int v = inf.readInt(1, n, "v"); inf.readSpace(); graph[u - 1].push_back(v - 1); graph[v - 1].push_back(u - 1); int w = inf.readInt(1, 1000, "w"); inf.readEoln(); } bfs(0); for (auto x : visited) { ensuref(x == true, "Disconnected graph"); } inf.readEof(); }
3fac836a48a84556b4f390c23d9c5d78bbadc617
472154315d971c899a64b06fe310353af4334e9e
/ScaleFactors/LeptonEfficiency/CMSTriggerSFs/CMSTriggerSFTest.cc
a69110c5340ebbebb0ae0c6a1c70952631d5b487
[]
no_license
brunel-physics/tZq_Dilepton_NanoAOD
8a646ed04c80467faefa053ee9341459d6bf51de
4d28475017e98dc4931b9afe1e728a53357dcaf1
refs/heads/master
2022-08-31T02:59:31.133592
2022-08-04T16:14:33
2022-08-04T16:14:33
252,706,676
0
0
null
2021-03-29T11:03:27
2020-04-03T10:58:25
C++
UTF-8
C++
false
false
4,588
cc
CMSTriggerSFTest.cc
#include <iostream> #include <fstream> auto CMSTriggerSFTest2(const string& year, const string& UpOrDown){ vector<float> PtTest{1000, 99.2, 25.2, 54.1, 74.3}; vector<float> AbsEtaTest{1.7, 2.3, 0.25, 0.99, 0.324}; float lumiRunBCDEF_triggerSF = 19648.534; float lumiRunGH_triggerSF = 16144.444; TFile* inputfile_RunsBCDEF; TFile* inputfile_RunsGH; TH2* histo_RunsBCDEF; TH2* histo_RunsGH; if(year == "2016"){ //HLT Mu24 file (runs BCDEF) inputfile_RunsBCDEF = new TFile("/home/eepgkkc/ScaleFactors/LeptonEfficiency/CMSTriggerSFs/2016/HLT_Mu24_EfficienciesAndSF_RunBtoF.root", "READ"); histo_RunsBCDEF = (TH2*)inputfile_RunsBCDEF->GetObjectChecked("IsoMu24_OR_IsoTkMu24_PtEtaBins/pt_abseta_ratio", "TH2"); //HLT Mu24 ID file (runs GH) inputfile_RunsGH = new TFile("/home/eepgkkc/ScaleFactors/LeptonEfficiency/CMSTriggerSFs/2016/HLT_Mu24_EfficienciesAndSF_RunGtoH.root", "READ"); histo_RunsGH = (TH2*)inputfile_RunsGH->GetObjectChecked("IsoMu24_OR_IsoTkMu24_PtEtaBins/pt_abseta_ratio", "TH2"); } else if(year == "2017"){ inputfile_RunsBCDEF = new TFile("/home/eepgkkc/ScaleFactors/LeptonEfficiency/CMSTriggerSFs/2017/HLT_Mu24_EfficienciesAndSF_RunBtoF.root", "READ"); histo_RunsBCDEF = (TH2*)inputfile_RunsBCDEF->GetObjectChecked("IsoMu27_PtEtaBins/pt_abseta_ratio", "TH2"); } else{cout << "need to add code for 2018" << endl;} vector<float> CMSTriggerSFOutput{}; for(int i = 0; i < PtTest.size(); i++){ int PtBin_RunsBCDEF = histo_RunsBCDEF->GetXaxis()->FindBin(PtTest.at(i)); int AbsEtaBin_RunsBCDEF = histo_RunsBCDEF->GetYaxis()->FindBin(AbsEtaTest.at(i)); float CMSTriggerSF_RunsBCDEF = histo_RunsBCDEF->GetBinContent(PtBin_RunsBCDEF, AbsEtaBin_RunsBCDEF); float Error_RunsBCDEF = histo_RunsBCDEF->GetBinError(PtBin_RunsBCDEF, AbsEtaBin_RunsBCDEF); float Error_RunsBCDEFGH, CMSTriggerSF_RunsBCDEFGH, Error_RunsGH, CMSTriggerSF_RunsGH; int PtBin_RunsGH, AbsEtaBin_RunsGH; if(year == "2016"){ PtBin_RunsBCDEF = histo_RunsBCDEF->GetXaxis()->FindBin(PtTest.at(i)); AbsEtaBin_RunsBCDEF = histo_RunsBCDEF->GetYaxis()->FindBin(AbsEtaTest.at(i)); PtBin_RunsGH = histo_RunsGH->GetXaxis()->FindBin(PtTest.at(i)); AbsEtaBin_RunsGH = histo_RunsGH->GetYaxis()->FindBin(AbsEtaTest.at(i)); CMSTriggerSF_RunsBCDEF = histo_RunsBCDEF->GetBinContent(PtBin_RunsBCDEF, AbsEtaBin_RunsBCDEF); Error_RunsBCDEF = histo_RunsBCDEF->GetBinError(PtBin_RunsBCDEF, AbsEtaBin_RunsBCDEF); CMSTriggerSF_RunsGH = histo_RunsGH->GetBinContent(PtBin_RunsGH, AbsEtaBin_RunsGH); Error_RunsGH = histo_RunsGH->GetBinError(PtBin_RunsGH, AbsEtaBin_RunsGH); CMSTriggerSF_RunsBCDEFGH = ( (CMSTriggerSF_RunsBCDEF * lumiRunBCDEF_triggerSF) + (CMSTriggerSF_RunsGH * lumiRunGH_triggerSF) ) / (lumiRunBCDEF_triggerSF * lumiRunGH_triggerSF + 1.0e-06); Error_RunsBCDEFGH = ( (Error_RunsBCDEF * lumiRunBCDEF_triggerSF) + (Error_RunsGH * lumiRunGH_triggerSF) ) / (lumiRunBCDEF_triggerSF * lumiRunGH_triggerSF + 1.0e-06); if(UpOrDown == "Up"){ CMSTriggerSF_RunsBCDEFGH += Error_RunsBCDEFGH; CMSTriggerSFOutput.push_back(CMSTriggerSF_RunsBCDEFGH); } else if(UpOrDown == "Down"){ CMSTriggerSF_RunsBCDEFGH -= Error_RunsBCDEFGH; CMSTriggerSFOutput.push_back(CMSTriggerSF_RunsBCDEFGH); } else{CMSTriggerSFOutput.push_back(CMSTriggerSF_RunsBCDEFGH);} } else if(year == "2017"){ if(UpOrDown == "Up"){ CMSTriggerSF_RunsBCDEF += Error_RunsBCDEF; CMSTriggerSFOutput.push_back(CMSTriggerSF_RunsBCDEF); } else if(UpOrDown == "Down"){ CMSTriggerSF_RunsBCDEF -= Error_RunsBCDEF; CMSTriggerSFOutput.push_back(CMSTriggerSF_RunsBCDEF); } else{CMSTriggerSFOutput.push_back(CMSTriggerSF_RunsBCDEF);} } else{cout << "only 2016 and 2017 have so far been included" << endl;} } return CMSTriggerSFOutput; } auto CMSTriggerSFTest(){ //return CMSTriggerSFTest2("2017", " "); //return CMSTriggerSFTest2("2017", "Up"); //return CMSTriggerSFTest2("2017", "Down"); //return CMSTriggerSFTest2("2016", " "); //return CMSTriggerSFTest2("2016", "Up"); return CMSTriggerSFTest2("2016", "Down"); }
f9d597c9aaa0e62622c4f7d797a452e501d66e35
d487407aea027d6da16443043610a2ef55e7e3e4
/sort_vector.cpp
0d364b52b4859cc256922b72ebc0f11df8f54f9f
[]
no_license
satiamit/DS-and-Algo
e575ab42f798a82a6e49bb155ab292d97b0ab5b3
4ad8281b2181084c5b7b5c5f89ac2e5a9e025b61
refs/heads/master
2020-04-19T03:29:44.418970
2019-01-28T09:42:52
2019-01-28T09:42:52
167,936,003
0
0
null
null
null
null
UTF-8
C++
false
false
1,864
cpp
sort_vector.cpp
//Initial Template for C++ #include <bits/stdc++.h> using namespace std; vector<pair<string, int> > sortMarks(vector<pair<string, int> > v, int N); //Position this line where user code will be pasted. // Driver code int main() { int testcase; cin >> testcase; while(testcase--){ int N; cin >> N; // Declaring vector vector<pair<string, int> > v; // Taking input to vector for(int i = 0;i<N;i++){ string s; cin >> s; int k; cin >> k; v.push_back(make_pair(s, k)); } // Calling function v = sortMarks(v, N); // Printing student name with their marks for(vector<pair<string, int> >::iterator it = v.begin(); it!=v.end();it++){ cout << it->first << " " << it->second << endl; } } return 0; } /*Please note that it's Function problem i.e. you need to write your solution in the form of Function(s) only. Driver Code to call/invoke your function is mentioned above.*/ //User function Template for C++ /*Function to sort students with respect to their marks * v : vector input with student name and their marks * N : size of vector * Your need to implement comparator to sort on the basis of marks. */ bool compe(const pair<string, int> &it1, const pair<string, int> &it2) { bool retVal = true; if(it1.second > it2.second) retVal = true; else if(it1.second < it2.second) retVal = false; if(it1.second == it2.second) retVal = true; // else // retVal = (bool)strncmp((it1.first).c_str(), (it2.first).c_str(), // min(strlen((it1.first).c_str()), strlen((it2.first).c_str()))); return retVal; } vector<pair<string, int> > sortMarks(vector<pair<string, int> > v, int N){ sort(v.begin(), v.end(), compe); return v; //Complete the code and return the sorted vector }
075c0a3988d7c905f21f924bbe570a5784eab95a
bf53c0103fe3261662f24b4ae026b180279121ea
/se/flag.h
996b2b53021c91556831e4f87b6b90ac562fdb49
[]
no_license
tigerinsky/se
372538869510e2e35b376f0b85fc554e2402f97c
2425bcf3cb6de784f9f2cce4add06acc41fbf8e5
refs/heads/master
2020-05-17T02:03:47.140775
2015-06-09T03:34:30
2015-06-09T03:34:30
34,048,891
0
0
null
null
null
null
UTF-8
C++
false
false
322
h
flag.h
#ifndef __FLAG_H_ #define __FLAG_H_ #include "google/gflags.h" namespace tis { DECLARE_int32(port); DECLARE_int32(thread_num); DECLARE_string(catalog_info_conf); DECLARE_string(segment_dict); DECLARE_string(catalog_conf); DECLARE_string(index_conf); DECLARE_string(tag_conf); DECLARE_string(version_file); } #endif
fb14bf199c0dcad40a12ed1ad5b05ac05f80bbd2
684df684759bfbef64b0fbcde9eb2b898a2e2061
/swagger-gen/cpp/model/LinearPositionListResult.cpp
fcafea79283c62cc02089da21142789615ac8101
[]
no_license
bybit-exchange/api-connectors
ae13caecb98c82460c0a24b910f2e9c1eb80b9bc
cc021a371bde30c2fd282be9fdc8eef0ed0e362e
refs/heads/master
2021-12-31T10:23:24.429638
2021-11-24T16:37:18
2021-11-24T16:37:18
213,896,494
192
185
null
2023-03-03T12:50:12
2019-10-09T11:10:19
C#
UTF-8
C++
false
false
20,424
cpp
LinearPositionListResult.cpp
/** * Bybit API * ## REST API for the Bybit Exchange. Base URI: [https://api.bybit.com] * * OpenAPI spec version: 0.2.10 * Contact: support@bybit.com * * NOTE: This class is auto generated by the swagger code generator 2.4.8. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ #include "LinearPositionListResult.h" namespace io { namespace swagger { namespace client { namespace model { LinearPositionListResult::LinearPositionListResult() { m_Bust_price = 0.0; m_Bust_priceIsSet = false; m_Cum_realised_pnl = 0.0; m_Cum_realised_pnlIsSet = false; m_Entry_price = 0.0; m_Entry_priceIsSet = false; m_Free_qty = 0.0; m_Free_qtyIsSet = false; m_Leverage = 0.0; m_LeverageIsSet = false; m_Liq_price = 0.0; m_Liq_priceIsSet = false; m_Occ_closing_fee = 0.0; m_Occ_closing_feeIsSet = false; m_Position_margin = 0.0; m_Position_marginIsSet = false; m_Position_value = 0.0; m_Position_valueIsSet = false; m_Realised_pnl = 0.0; m_Realised_pnlIsSet = false; m_Side = utility::conversions::to_string_t(""); m_SideIsSet = false; m_Size = 0.0; m_SizeIsSet = false; m_Symbol = utility::conversions::to_string_t(""); m_SymbolIsSet = false; m_User_id = 0L; m_User_idIsSet = false; m_Tp_sl_mode = utility::conversions::to_string_t(""); m_Tp_sl_modeIsSet = false; } LinearPositionListResult::~LinearPositionListResult() { } void LinearPositionListResult::validate() { // TODO: implement validation } web::json::value LinearPositionListResult::toJson() const { web::json::value val = web::json::value::object(); if(m_Bust_priceIsSet) { val[utility::conversions::to_string_t("bust_price")] = ModelBase::toJson(m_Bust_price); } if(m_Cum_realised_pnlIsSet) { val[utility::conversions::to_string_t("cum_realised_pnl")] = ModelBase::toJson(m_Cum_realised_pnl); } if(m_Entry_priceIsSet) { val[utility::conversions::to_string_t("entry_price")] = ModelBase::toJson(m_Entry_price); } if(m_Free_qtyIsSet) { val[utility::conversions::to_string_t("free_qty")] = ModelBase::toJson(m_Free_qty); } if(m_LeverageIsSet) { val[utility::conversions::to_string_t("leverage")] = ModelBase::toJson(m_Leverage); } if(m_Liq_priceIsSet) { val[utility::conversions::to_string_t("liq_price")] = ModelBase::toJson(m_Liq_price); } if(m_Occ_closing_feeIsSet) { val[utility::conversions::to_string_t("occ_closing_fee")] = ModelBase::toJson(m_Occ_closing_fee); } if(m_Position_marginIsSet) { val[utility::conversions::to_string_t("position_margin")] = ModelBase::toJson(m_Position_margin); } if(m_Position_valueIsSet) { val[utility::conversions::to_string_t("position_value")] = ModelBase::toJson(m_Position_value); } if(m_Realised_pnlIsSet) { val[utility::conversions::to_string_t("realised_pnl")] = ModelBase::toJson(m_Realised_pnl); } if(m_SideIsSet) { val[utility::conversions::to_string_t("side")] = ModelBase::toJson(m_Side); } if(m_SizeIsSet) { val[utility::conversions::to_string_t("size")] = ModelBase::toJson(m_Size); } if(m_SymbolIsSet) { val[utility::conversions::to_string_t("symbol")] = ModelBase::toJson(m_Symbol); } if(m_User_idIsSet) { val[utility::conversions::to_string_t("user_id")] = ModelBase::toJson(m_User_id); } if(m_Tp_sl_modeIsSet) { val[utility::conversions::to_string_t("tp_sl_mode")] = ModelBase::toJson(m_Tp_sl_mode); } return val; } void LinearPositionListResult::fromJson(web::json::value& val) { if(val.has_field(utility::conversions::to_string_t("bust_price"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("bust_price")]; if(!fieldValue.is_null()) { setBustPrice(ModelBase::doubleFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("cum_realised_pnl"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("cum_realised_pnl")]; if(!fieldValue.is_null()) { setCumRealisedPnl(ModelBase::doubleFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("entry_price"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("entry_price")]; if(!fieldValue.is_null()) { setEntryPrice(ModelBase::doubleFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("free_qty"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("free_qty")]; if(!fieldValue.is_null()) { setFreeQty(ModelBase::doubleFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("leverage"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("leverage")]; if(!fieldValue.is_null()) { setLeverage(ModelBase::doubleFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("liq_price"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("liq_price")]; if(!fieldValue.is_null()) { setLiqPrice(ModelBase::doubleFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("occ_closing_fee"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("occ_closing_fee")]; if(!fieldValue.is_null()) { setOccClosingFee(ModelBase::doubleFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("position_margin"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("position_margin")]; if(!fieldValue.is_null()) { setPositionMargin(ModelBase::doubleFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("position_value"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("position_value")]; if(!fieldValue.is_null()) { setPositionValue(ModelBase::doubleFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("realised_pnl"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("realised_pnl")]; if(!fieldValue.is_null()) { setRealisedPnl(ModelBase::doubleFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("side"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("side")]; if(!fieldValue.is_null()) { setSide(ModelBase::stringFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("size"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("size")]; if(!fieldValue.is_null()) { setSize(ModelBase::doubleFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("symbol"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("symbol")]; if(!fieldValue.is_null()) { setSymbol(ModelBase::stringFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("user_id"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("user_id")]; if(!fieldValue.is_null()) { setUserId(ModelBase::int64_tFromJson(fieldValue)); } } if(val.has_field(utility::conversions::to_string_t("tp_sl_mode"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("tp_sl_mode")]; if(!fieldValue.is_null()) { setTpSlMode(ModelBase::stringFromJson(fieldValue)); } } } void LinearPositionListResult::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const { utility::string_t namePrefix = prefix; if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { namePrefix += utility::conversions::to_string_t("."); } if(m_Bust_priceIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("bust_price"), m_Bust_price)); } if(m_Cum_realised_pnlIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("cum_realised_pnl"), m_Cum_realised_pnl)); } if(m_Entry_priceIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("entry_price"), m_Entry_price)); } if(m_Free_qtyIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("free_qty"), m_Free_qty)); } if(m_LeverageIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("leverage"), m_Leverage)); } if(m_Liq_priceIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("liq_price"), m_Liq_price)); } if(m_Occ_closing_feeIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("occ_closing_fee"), m_Occ_closing_fee)); } if(m_Position_marginIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("position_margin"), m_Position_margin)); } if(m_Position_valueIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("position_value"), m_Position_value)); } if(m_Realised_pnlIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("realised_pnl"), m_Realised_pnl)); } if(m_SideIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("side"), m_Side)); } if(m_SizeIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("size"), m_Size)); } if(m_SymbolIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("symbol"), m_Symbol)); } if(m_User_idIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("user_id"), m_User_id)); } if(m_Tp_sl_modeIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("tp_sl_mode"), m_Tp_sl_mode)); } } void LinearPositionListResult::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) { utility::string_t namePrefix = prefix; if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { namePrefix += utility::conversions::to_string_t("."); } if(multipart->hasContent(utility::conversions::to_string_t("bust_price"))) { setBustPrice(ModelBase::doubleFromHttpContent(multipart->getContent(utility::conversions::to_string_t("bust_price")))); } if(multipart->hasContent(utility::conversions::to_string_t("cum_realised_pnl"))) { setCumRealisedPnl(ModelBase::doubleFromHttpContent(multipart->getContent(utility::conversions::to_string_t("cum_realised_pnl")))); } if(multipart->hasContent(utility::conversions::to_string_t("entry_price"))) { setEntryPrice(ModelBase::doubleFromHttpContent(multipart->getContent(utility::conversions::to_string_t("entry_price")))); } if(multipart->hasContent(utility::conversions::to_string_t("free_qty"))) { setFreeQty(ModelBase::doubleFromHttpContent(multipart->getContent(utility::conversions::to_string_t("free_qty")))); } if(multipart->hasContent(utility::conversions::to_string_t("leverage"))) { setLeverage(ModelBase::doubleFromHttpContent(multipart->getContent(utility::conversions::to_string_t("leverage")))); } if(multipart->hasContent(utility::conversions::to_string_t("liq_price"))) { setLiqPrice(ModelBase::doubleFromHttpContent(multipart->getContent(utility::conversions::to_string_t("liq_price")))); } if(multipart->hasContent(utility::conversions::to_string_t("occ_closing_fee"))) { setOccClosingFee(ModelBase::doubleFromHttpContent(multipart->getContent(utility::conversions::to_string_t("occ_closing_fee")))); } if(multipart->hasContent(utility::conversions::to_string_t("position_margin"))) { setPositionMargin(ModelBase::doubleFromHttpContent(multipart->getContent(utility::conversions::to_string_t("position_margin")))); } if(multipart->hasContent(utility::conversions::to_string_t("position_value"))) { setPositionValue(ModelBase::doubleFromHttpContent(multipart->getContent(utility::conversions::to_string_t("position_value")))); } if(multipart->hasContent(utility::conversions::to_string_t("realised_pnl"))) { setRealisedPnl(ModelBase::doubleFromHttpContent(multipart->getContent(utility::conversions::to_string_t("realised_pnl")))); } if(multipart->hasContent(utility::conversions::to_string_t("side"))) { setSide(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("side")))); } if(multipart->hasContent(utility::conversions::to_string_t("size"))) { setSize(ModelBase::doubleFromHttpContent(multipart->getContent(utility::conversions::to_string_t("size")))); } if(multipart->hasContent(utility::conversions::to_string_t("symbol"))) { setSymbol(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("symbol")))); } if(multipart->hasContent(utility::conversions::to_string_t("user_id"))) { setUserId(ModelBase::int64_tFromHttpContent(multipart->getContent(utility::conversions::to_string_t("user_id")))); } if(multipart->hasContent(utility::conversions::to_string_t("tp_sl_mode"))) { setTpSlMode(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("tp_sl_mode")))); } } double LinearPositionListResult::getBustPrice() const { return m_Bust_price; } void LinearPositionListResult::setBustPrice(double value) { m_Bust_price = value; m_Bust_priceIsSet = true; } bool LinearPositionListResult::bustPriceIsSet() const { return m_Bust_priceIsSet; } void LinearPositionListResult::unsetBust_price() { m_Bust_priceIsSet = false; } double LinearPositionListResult::getCumRealisedPnl() const { return m_Cum_realised_pnl; } void LinearPositionListResult::setCumRealisedPnl(double value) { m_Cum_realised_pnl = value; m_Cum_realised_pnlIsSet = true; } bool LinearPositionListResult::cumRealisedPnlIsSet() const { return m_Cum_realised_pnlIsSet; } void LinearPositionListResult::unsetCum_realised_pnl() { m_Cum_realised_pnlIsSet = false; } double LinearPositionListResult::getEntryPrice() const { return m_Entry_price; } void LinearPositionListResult::setEntryPrice(double value) { m_Entry_price = value; m_Entry_priceIsSet = true; } bool LinearPositionListResult::entryPriceIsSet() const { return m_Entry_priceIsSet; } void LinearPositionListResult::unsetEntry_price() { m_Entry_priceIsSet = false; } double LinearPositionListResult::getFreeQty() const { return m_Free_qty; } void LinearPositionListResult::setFreeQty(double value) { m_Free_qty = value; m_Free_qtyIsSet = true; } bool LinearPositionListResult::freeQtyIsSet() const { return m_Free_qtyIsSet; } void LinearPositionListResult::unsetFree_qty() { m_Free_qtyIsSet = false; } double LinearPositionListResult::getLeverage() const { return m_Leverage; } void LinearPositionListResult::setLeverage(double value) { m_Leverage = value; m_LeverageIsSet = true; } bool LinearPositionListResult::leverageIsSet() const { return m_LeverageIsSet; } void LinearPositionListResult::unsetLeverage() { m_LeverageIsSet = false; } double LinearPositionListResult::getLiqPrice() const { return m_Liq_price; } void LinearPositionListResult::setLiqPrice(double value) { m_Liq_price = value; m_Liq_priceIsSet = true; } bool LinearPositionListResult::liqPriceIsSet() const { return m_Liq_priceIsSet; } void LinearPositionListResult::unsetLiq_price() { m_Liq_priceIsSet = false; } double LinearPositionListResult::getOccClosingFee() const { return m_Occ_closing_fee; } void LinearPositionListResult::setOccClosingFee(double value) { m_Occ_closing_fee = value; m_Occ_closing_feeIsSet = true; } bool LinearPositionListResult::occClosingFeeIsSet() const { return m_Occ_closing_feeIsSet; } void LinearPositionListResult::unsetOcc_closing_fee() { m_Occ_closing_feeIsSet = false; } double LinearPositionListResult::getPositionMargin() const { return m_Position_margin; } void LinearPositionListResult::setPositionMargin(double value) { m_Position_margin = value; m_Position_marginIsSet = true; } bool LinearPositionListResult::positionMarginIsSet() const { return m_Position_marginIsSet; } void LinearPositionListResult::unsetPosition_margin() { m_Position_marginIsSet = false; } double LinearPositionListResult::getPositionValue() const { return m_Position_value; } void LinearPositionListResult::setPositionValue(double value) { m_Position_value = value; m_Position_valueIsSet = true; } bool LinearPositionListResult::positionValueIsSet() const { return m_Position_valueIsSet; } void LinearPositionListResult::unsetPosition_value() { m_Position_valueIsSet = false; } double LinearPositionListResult::getRealisedPnl() const { return m_Realised_pnl; } void LinearPositionListResult::setRealisedPnl(double value) { m_Realised_pnl = value; m_Realised_pnlIsSet = true; } bool LinearPositionListResult::realisedPnlIsSet() const { return m_Realised_pnlIsSet; } void LinearPositionListResult::unsetRealised_pnl() { m_Realised_pnlIsSet = false; } utility::string_t LinearPositionListResult::getSide() const { return m_Side; } void LinearPositionListResult::setSide(utility::string_t value) { m_Side = value; m_SideIsSet = true; } bool LinearPositionListResult::sideIsSet() const { return m_SideIsSet; } void LinearPositionListResult::unsetSide() { m_SideIsSet = false; } double LinearPositionListResult::getSize() const { return m_Size; } void LinearPositionListResult::setSize(double value) { m_Size = value; m_SizeIsSet = true; } bool LinearPositionListResult::sizeIsSet() const { return m_SizeIsSet; } void LinearPositionListResult::unsetSize() { m_SizeIsSet = false; } utility::string_t LinearPositionListResult::getSymbol() const { return m_Symbol; } void LinearPositionListResult::setSymbol(utility::string_t value) { m_Symbol = value; m_SymbolIsSet = true; } bool LinearPositionListResult::symbolIsSet() const { return m_SymbolIsSet; } void LinearPositionListResult::unsetSymbol() { m_SymbolIsSet = false; } int64_t LinearPositionListResult::getUserId() const { return m_User_id; } void LinearPositionListResult::setUserId(int64_t value) { m_User_id = value; m_User_idIsSet = true; } bool LinearPositionListResult::userIdIsSet() const { return m_User_idIsSet; } void LinearPositionListResult::unsetUser_id() { m_User_idIsSet = false; } utility::string_t LinearPositionListResult::getTpSlMode() const { return m_Tp_sl_mode; } void LinearPositionListResult::setTpSlMode(utility::string_t value) { m_Tp_sl_mode = value; m_Tp_sl_modeIsSet = true; } bool LinearPositionListResult::tpSlModeIsSet() const { return m_Tp_sl_modeIsSet; } void LinearPositionListResult::unsetTp_sl_mode() { m_Tp_sl_modeIsSet = false; } } } } }
82bb295636cdd21b8586f585285a9833cdbfe521
e3b7ccc6fb645b765047ea732fe603f1c3c0ef05
/Game.cpp
d7ae9e1e7f992dc7ea6c1d330eb34b1c2dce4542
[]
no_license
cpp-teaching/tic-tac-toe
d93f24942478595f38c5ec41e586d3598bd24d8b
2cddca7ef6e96bc9f095c21518b60bc033cf917f
refs/heads/master
2021-01-22T04:57:34.327010
2017-05-26T21:24:35
2017-05-26T21:24:35
81,604,755
0
0
null
null
null
null
UTF-8
C++
false
false
172
cpp
Game.cpp
#include "GameStatus.h" #include "Tile.h" #include <vector> #include "Grid.h" int main() { std::vector <Tile> board(9, Tile::Empty); return 0; }
635d9fc57b1029d3e66f7256ea624213d4694d5f
36a3665f38aa6636c57ea2b793e4a1787fb03df0
/modules/multiplier.cpp
964b742af382fe9e23ea4c1d7bf81a900b0e144c
[]
no_license
bozskybedrich/EvoHSC
405ce73f7f2dd1b6d3ec3b7368f4b4023463c8d0
6607cb7ce352df7478715ed332c34a45b544767f
refs/heads/master
2021-01-11T03:22:28.062347
2016-11-11T16:51:31
2016-11-11T16:51:31
71,040,082
0
0
null
null
null
null
UTF-8
C++
false
false
510
cpp
multiplier.cpp
#include "multiplier.h" #ifdef _DEBUG #define new MYDEBUG_NEW #endif CMultiplier::CMultiplier(UINT nFractBits) : CModule() { m_nInputCount = 2; m_nOutputCount = 1; m_nFractBits = nFractBits; } int CMultiplier::Execute(REGISTER_TYPE * pInputs, REGISTER_TYPE * pOutputs, UINT * pExecDelay) { pOutputs[0] = pInputs[0] * pInputs[1]; if (m_nFractBits > 0) pOutputs[0] >>= m_nFractBits; SetZero(pOutputs[0] == 0); SetSign(pOutputs[0] < 0); if (pExecDelay) *pExecDelay = 20; return ERR_SUCCESS; }
0e41f21d8c2d052c4a9172113a909d24ca0cbc33
d1cf34b4d5280e33ebcf1cd788b470372fdd5a26
/codeforces/ac/2/220/C.cpp
af687a04b1cc4614253634205cd3f63dbf956028
[]
no_license
watashi/AlgoSolution
985916ac511892b7e87f38c9b364069f6b51a0ea
bbbebda189c7e74edb104615f9c493d279e4d186
refs/heads/master
2023-08-17T17:25:10.748003
2023-08-06T04:34:19
2023-08-06T04:34:19
2,525,282
97
32
null
2020-10-09T18:52:29
2011-10-06T10:40:07
C++
UTF-8
C++
false
false
1,240
cpp
C.cpp
#include <set> #include <cstdio> #include <algorithm> using namespace std; const int MAXN = 100100; int a[MAXN], b[MAXN]; multiset<int> st; int main() { int n, x; vector<pair<int, int> > v, w; scanf("%d", &n); for (int i = 0; i < n; ++i) { scanf("%d", &x); a[x - 1] = i; } for (int i = 0; i < n; ++i) { scanf("%d", &x); b[x - 1] = i; } for (int i = 0; i < n; ++i) { v.push_back({0, b[i] - a[i]}); w.push_back({b[i] + 1, b[i] - a[i]}); v.push_back({b[i] + 1, n + b[i] - a[i]}); } st.insert(-n - n); st.insert(n + n); sort(v.rbegin(), v.rend()); sort(w.rbegin(), w.rend()); for (int i = 0; i < n; ++i) { while (!v.empty() && v.back().first == i) { st.insert(v.back().second); v.pop_back(); } while (!w.empty() && w.back().first == i) { st.erase(st.find(w.back().second)); w.pop_back(); } auto it = st.lower_bound(i); int r = *it; --it; int l = *it; // printf("%d %d\n", l, r); // printf("%d\n", min(dis(n, l, i), dis(n, r, i))); printf("%d\n", min(i - l, r - i)); } return 0; }
0be393d8a80526a35cabe0dfd1d11432716e6a6a
eedd904304046caceb3e982dec1d829c529da653
/tut7/Map.h
9fb694bc31f5a5b43f7c78e4febb09380f45ebeb
[]
no_license
PaulFSherwood/cplusplus
b550a9a573e9bca5b828b10849663e40fd614ff0
999c4d18d2dd4d0dd855e1547d2d2ad5eddc6938
refs/heads/master
2023-06-07T09:00:20.421362
2023-05-21T03:36:50
2023-05-21T03:36:50
12,607,904
4
0
null
null
null
null
UTF-8
C++
false
false
320
h
Map.h
#ifndef SOLDIER_H_ #define SOLDIER_H_ class Map { public: Map(int startHealth, int startSrength); void attack(); void heal(int amountHealth); void beAttacked(); int GetHealth(); char GetMap(); private: int health; int strength; char myArray[2][2]; }; #endif /* SOLDIER_H_ */
153805360e6e6dcaa6936a3e2c9270277cf6adb7
32ea98f33cb9550ee81f7a498e8b8238a04800c0
/BitTest.cpp
575dc85be603b2c5e90b19053dfb0f78f9d2dafa
[]
no_license
pkroy0185/C-plus-plus-programs2
2e6a841f27571934a793fa5b2b49c7ba7c728766
70a4f1dc0b65bd1a28ced94a139f18b66c5813cc
refs/heads/main
2023-04-01T10:20:59.402411
2021-03-22T17:24:21
2021-03-22T17:24:21
350,429,085
0
0
null
null
null
null
UTF-8
C++
false
false
590
cpp
BitTest.cpp
#include<iostream> #include<bitset> using namespace std; int main() { bitset<32> bitvec; cout<<"Bitvec : "<<bitvec<<endl; bitvec.flip(0); bitvec.flip(3); bitvec.flip(7); bitvec.flip(31); cout<<"Bitvec : "<<bitvec<<endl; cout<<"At bit 7 : "<<bitvec[7]<<endl<<"At bit 31 : "<<bitvec[31]<<endl; if(bitvec.test(7)) cout<<"Bit at position 7 is ON."<<endl; else cout<<"Bit at position 7 is OFF."<<endl; if(bitvec.test(5)) cout<<"Bit at position 5 is ON."<<endl; else cout<<"Bit at position 5 is OFF."<<endl; return 0; }
781ed4d2b46e222cc08790fc5f173400d8f6f2b8
5b4d939559a20ce3ca5290ec5d08548623459dad
/CCZU_ODM_ProductionDataQueryTool_V1.0.0/PACKView.h
5bf2326f1feadb28cebcb1a53cc7f3ad211f741b
[]
no_license
lean-net/mes
1e0fd327af923f9a77ee94df6d092f0e6702c2ed
c0593b20042ace109608986b50ba71fa452aad8d
refs/heads/master
2021-06-18T19:36:45.636554
2017-06-23T07:50:45
2017-06-23T07:50:45
null
0
0
null
null
null
null
GB18030
C++
false
false
5,041
h
PACKView.h
// PACKView.h : interface of the CPACKView class // ///////////////////////////////////////////////////////////////////////////// //{{AFX_INCLUDES() #include "msflexgrid1.h" //}}AFX_INCLUDES #include "Config.h" #include "StateList.h" #include "Label.h" #include "BtnST.h" #include "skapi.h" #include "excel.h" #include "comdef.h" #if !defined(AFX_PACKVIEW_H__6C8D4E97_3F26_4924_9D1B_A9B8695F8446__INCLUDED_) #define AFX_PACKVIEW_H__6C8D4E97_3F26_4924_9D1B_A9B8695F8446__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CPACKView : public CFormView { protected: // create from serialization only CPACKView(); DECLARE_DYNCREATE(CPACKView) public: //{{AFX_DATA(CPACKView) enum { IDD = IDD_PACK_FORM }; CButton m_ctrCarton; CComboBox m_ctrOrderType; CComboBox m_ctrCustomer; CComboBox m_ctrComboxType; CButton m_ctrUnusedIMEI; CLabel m_ctrReleaseUser; CLabel m_ctrCreateUser; CButton m_ctrRework; CButton m_ctrIMEIQuery; CLabel m_ctrCurrentPlan; CComboBox m_ctrComboxProduct; CComboBox m_ctrComboxOrder; CLabel m_ctrCurrentProduct; CLabel m_ctrCurrentOrder; CLabel m_ctrCurrentColor; int m_iComboxProduct; int m_iComboxOrder; CString m_csCurrentProduct; CString m_csCurrentOrder; CString m_csCurrentColor; CString m_csCurrentWorkStation; CButton m_ctrBtnPrint; CStateList m_state_list; CMSFlexGrid m_flex; CString m_csCurrentPlan; CString m_csCreateUser; CString m_csReleaseUser; int m_iComboxType; int m_iCustomer; int m_iOrderType; //}}AFX_DATA // Attributes public: CPACKDoc* GetDocument(); public://KEY unsigned short UserID; CString m_csReadCount; CString m_csWriteCount; int m_iReadCount; int m_iWriteCount; CFont m_staticfont; public: void SetMyFont(); void SetUIDisableAll(); void InsertListInfo(CString state,int imageIndex); CString GetCurTimes(); bool ConnectMDBDatabase(); CString VariantToCString(VARIANT var); void SetRowCol(int rows,int cols); void SetNumText(int rows); bool GetProductList(); bool GetProductOrderList(); bool GetProductOrderInfo(); bool GetProductionData(); bool GetColorBoxWeighData(); bool GetCartonBoxWeighData(); bool GetShippingData(); void ProductionDataRealTimeDisplay(); public: CConfig m_Config; CImageList m_imageList; CString m_csConfigPath; //分时段数据显示 CStringArray csaPut; CStringArray csaWrite; CStringArray csaCheckS1; CStringArray csaColorBox; CStringArray csaCheckS2; CStringArray csaColorWeigh; CStringArray csaCarton; CStringArray csaCartonWeigh; CStringArray csaPallet; //数据库中获取卡通箱信息 CString m_csCustomerNo; CString m_csDWNo; CString m_csCartonNameStatic; int m_iCartonNameLength; int m_iCartonMaxCount; //数据库中获取栈板信息 CString m_csPalletNameStatic; int m_iPalletNameLength; int m_iPalletMaxCount; //数据库中计划产量 int m_iPlannedOutput; //excel CString m_excel_path; _Application m_ExlApp; _Workbook m_ExlBook; _Worksheet m_ExlSheet; Workbooks m_ExlBooks; Worksheets m_ExlSheets; Range m_ExlRge; public: CStringArray m_csaIMEI1; CStringArray m_csaIMEI2; CStringArray m_csaIMEI3; CStringArray m_csaNetCode; CStringArray m_csaSN; CStringArray m_csaBoxID; CStringArray m_csaPalletID; CStringArray m_csaShippingDate; CStringArray m_csaCartonNametemp; CStringArray m_csaPalletNametemp; CStringArray m_csaShippingDatetemp; CStringArray m_csaColorBoxWeigh; CStringArray m_csaCartonBoxWeigh; CStringArray m_csaMACAddr; CStringArray m_csaBTAddr; int m_cur_row; int m_cur_col; // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CPACKView) public: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual void OnInitialUpdate(); // called first time after construct //}}AFX_VIRTUAL // Implementation public: virtual ~CPACKView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: //{{AFX_MSG(CPACKView) afx_msg void OnTimer(UINT nIDEvent); afx_msg void OnCloseupComboProduct(); afx_msg void OnCloseupComboOrder(); afx_msg void OnBtnPrint(); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnBtnImeiquery(); afx_msg void OnBtnUnusedimei(); afx_msg void OnBtnOrderquery(); afx_msg void OnCloseupComboType(); afx_msg void OnBtnDetail(); afx_msg void OnBtnCarton(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // debug version in PACKView.cpp inline CPACKDoc* CPACKView::GetDocument() { return (CPACKDoc*)m_pDocument; } #endif ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_PACKVIEW_H__6C8D4E97_3F26_4924_9D1B_A9B8695F8446__INCLUDED_)
b4e112da827412478a8bff0162491f6313641560
ba1944305bd4641be09c90f4464475901845077a
/CAKE wALK/binaryserchtree.cpp
621f958f0231fe1b401cedfa869eb55f4543a653
[]
no_license
Ravi-Khatri/code
e5c9bb0d88a5ea74ac2b0dfae83b90944b69ce0b
be40c85ec888059457b2189829f329268cd036b5
refs/heads/main
2023-04-03T18:38:54.289012
2021-04-18T08:05:20
2021-04-18T08:05:20
256,105,251
0
1
null
null
null
null
UTF-8
C++
false
false
1,529
cpp
binaryserchtree.cpp
#include<iostream> using namespace std; struct node { int val; node* left; node* right; }; node* createNewNode(int x) { node* nn = new node; nn->val = x; nn->left = nullptr; nn->right = nullptr; return nn; } void bstInsert(node* &root, int x) { if(root == nullptr) { root = createNewNode(x); return; } if(x < root->val) { if(root->left == nullptr) { root->left = createNewNode(x); return; } else { bstInsert(root->left, x); } } if( x > root->val ) { if(root->right == nullptr) { root->right = createNewNode(x); return; } else { bstInsert(root->right, x); } } } void inorder(node *root) { if(!root) return ; else { inorder(root->left); cout<<" -> "<<root->val; inorder(root->right); } } void preorder(node *root) { if(!root) return ; else { cout<<" -> "<<root->val; inorder(root->left); inorder(root->right); } } void postorder(node *root) { if(!root) return ; else { inorder(root->left); inorder(root->right); cout<<" -> "<<root->val; } } int main() { node* root = nullptr; int x; while(cin >> x) { if(x==0)break; bstInsert(root, x); } inorder(root); cout<<endl; postorder(root); cout<<endl; preorder(root); return 0; }
96cbc1286e4f947418c909330be3f53fc6a11130
44ab57520bb1a9b48045cb1ee9baee8816b44a5b
/Assist/Code/Toolset/Framework/WinMainEntryPoint3/WinMainEntryPoint3.cpp
ee0151547a84c86ddaee6745611066bbde7df6dc
[ "BSD-3-Clause" ]
permissive
WuyangPeng/Engine
d5d81fd4ec18795679ce99552ab9809f3b205409
738fde5660449e87ccd4f4878f7bf2a443ae9f1f
refs/heads/master
2023-08-17T17:01:41.765963
2023-08-16T07:27:05
2023-08-16T07:27:05
246,266,843
10
0
null
null
null
null
GB18030
C++
false
false
1,210
cpp
WinMainEntryPoint3.cpp
/// Copyright (c) 2010-2023 /// Threading Core Render Engine /// /// 作者:彭武阳,彭晔恩,彭晔泽 /// 联系作者:94458936@qq.com /// /// 标准:std:c++20 /// 版本:0.9.1.2 (2023/07/28 10:52) #include "WinMainEntryPoint3.h" #include "CoreTools/Helper/ClassInvariant/FrameworkClassInvariantMacro.h" #include "Framework/MainFunctionHelper/WindowMainFunctionHelperDetail.h" #include "Framework/WindowsAPIFrame/WindowsAPIFrameBuildDetail.h" Framework::WinMainEntryPoint3::WinMainEntryPoint3(WindowsHInstance instance, const char* commandLine, const WindowApplicationInformation& information, const EnvironmentDirectory& environmentDirectory) : ParentType{ instance, commandLine, information, environmentDirectory } { FRAMEWORK_SELF_CLASS_IS_VALID_1; } CLASS_INVARIANT_PARENT_IS_VALID_DEFINE(Framework, WinMainEntryPoint3) std::shared_ptr<Framework::WinMainEntryPoint3> Framework::WinMainEntryPoint3::Create(WindowsHInstance instance, const char* commandLine, const WindowApplicationInformation& information, const EnvironmentDirectory& environmentDirectory) { return std::make_shared<Framework::WinMainEntryPoint3>(instance, commandLine, information, environmentDirectory); }
d59164c4c8676ac55c259e4a2cf6b40d62308eab
66658a28df66ac6e59592cd166c9cf2d07a13cd8
/src/ksieveui/sievescriptdebugger/autotests/sievescriptdebuggerdialogtest.cpp
8e240b68d79a14d4ae82548bb7c13976f64064f3
[ "CC0-1.0", "BSD-3-Clause" ]
permissive
KDE/libksieve
ef305594a5252686ad2c77416ef661d6a6a07f70
4adf80b227a6a77896a3ee51e09ac34658310d90
refs/heads/master
2023-09-01T16:24:11.116547
2023-08-30T16:38:09
2023-08-30T17:19:35
47,667,167
7
1
null
null
null
null
UTF-8
C++
false
false
2,449
cpp
sievescriptdebuggerdialogtest.cpp
/* SPDX-FileCopyrightText: 2015-2023 Laurent Montel <montel@kde.org> SPDX-License-Identifier: LGPL-2.0-or-later */ #include "sievescriptdebuggerdialogtest.h" #include "../sievescriptdebuggerdialog.h" #include "../sievescriptdebuggerfrontendwidget.h" #include "../sievescriptdebuggerwidget.h" #include <KUrlRequester> #include <QDialogButtonBox> #include <QPushButton> #include <QStandardPaths> #include <QTest> SieveScriptDebuggerDialogTest::SieveScriptDebuggerDialogTest(QObject *parent) : QObject(parent) { QStandardPaths::setTestModeEnabled(true); } SieveScriptDebuggerDialogTest::~SieveScriptDebuggerDialogTest() = default; void SieveScriptDebuggerDialogTest::shouldHaveDefaultValue() { KSieveUi::SieveScriptDebuggerDialog dlg; auto buttonBox = dlg.findChild<QDialogButtonBox *>(QStringLiteral("buttonbox")); QVERIFY(buttonBox); auto widget = dlg.findChild<KSieveUi::SieveScriptDebuggerWidget *>(QStringLiteral("sievescriptdebuggerwidget")); QVERIFY(widget); QVERIFY(dlg.script().isEmpty()); auto mOkButton = dlg.findChild<QPushButton *>(QStringLiteral("okbutton")); QVERIFY(mOkButton); QVERIFY(!mOkButton->isEnabled()); auto mDebugScriptButton = dlg.findChild<QPushButton *>(QStringLiteral("debug_button")); QVERIFY(mDebugScriptButton); QVERIFY(!mDebugScriptButton->isEnabled()); } void SieveScriptDebuggerDialogTest::shouldChangeDebugButtonEnabledState() { KSieveUi::SieveScriptDebuggerDialog dlg; auto widget = dlg.findChild<KSieveUi::SieveScriptDebuggerWidget *>(QStringLiteral("sievescriptdebuggerwidget")); auto mSieveScriptFrontEnd = widget->findChild<KSieveUi::SieveScriptDebuggerFrontEndWidget *>(QStringLiteral("sievescriptfrontend")); QVERIFY(mSieveScriptFrontEnd); auto emailPath = mSieveScriptFrontEnd->findChild<KUrlRequester *>(QStringLiteral("emailpath")); QVERIFY(emailPath); auto mDebugScriptButton = dlg.findChild<QPushButton *>(QStringLiteral("debug_button")); QVERIFY(mDebugScriptButton); QVERIFY(!mDebugScriptButton->isEnabled()); emailPath->setUrl(QUrl::fromLocalFile(QStringLiteral("/"))); QVERIFY(!mDebugScriptButton->isEnabled()); mSieveScriptFrontEnd->setScript(QStringLiteral("foo")); QVERIFY(mDebugScriptButton->isEnabled()); emailPath->setUrl(QUrl::fromLocalFile(QStringLiteral(" "))); QVERIFY(!mDebugScriptButton->isEnabled()); } QTEST_MAIN(SieveScriptDebuggerDialogTest)
11adbc53a523f974f66637fb18d3c982fcec066f
dc48f11c1a7c97e13534bdb34af38e1d7f1a2f9d
/Monumentum/Utility/Dispatcher.cpp
166d5a23781339d1f098029e9dc6657640da3927
[ "Apache-2.0" ]
permissive
m1kor/Monumentum
1b7dff54a19f458941e76f46ee0d11f3c5f6d1c9
95f1181decbf2c2c269f2a306a2f18c91679e1c0
refs/heads/master
2021-06-16T08:22:54.384658
2017-05-28T13:55:55
2017-05-28T13:55:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
986
cpp
Dispatcher.cpp
#include <Monumentum/Utility/Dispatcher.hpp> #include <iostream> namespace Monumentum { Dispatcher::Dispatcher() { } Dispatcher::~Dispatcher() { } void Dispatcher::Remove(const uint16_t id) { if (commandRegistry.count(id) > 0) commandRegistry.erase(id); else std::cerr << "Dispatcher::Remove() -> Trying to remove unregistered command" << std::endl ; } void Dispatcher::Execute(ByteBuffer &commandBuffer, const int bufferLength) { if (bufferLength > 0) { commandBuffer.Reset(); do { commandId = commandBuffer.ReadUInt16(); if (commandRegistry.count(commandId) > 0) commandRegistry[commandId]->Execute(commandBuffer); else { std::cerr << "Dispatcher::Execute() -> Received command with ID = " << commandId << " is unregistered, aborting execution" << std::endl; break; } } while (commandBuffer.Index < bufferLength); } } }
fe9d236910b72f4788d1a8424d89355cb23f8d1e
b6e6d3abb438c717611d5e93aa22d64fda186571
/Classes/SlotScene.h
68340ebd31b35094351e2181a3f005102d12f8b6
[]
no_license
manlan/GAFSlotMachine
321b396fb003ab60edb7fc9c7fe4e676899b2194
318e919a6f24a86a37a1e94a3dbb1c844f82faa4
refs/heads/master
2021-01-14T13:17:24.656033
2015-02-17T13:27:32
2015-02-17T13:27:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
570
h
SlotScene.h
#ifndef __HELLOWORLD_SCENE_H__ #define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" class SlotMachine; class SlotScene : public cocos2d::Layer { public: static cocos2d::Scene* createScene(); virtual bool init(); virtual void update(float dt); virtual bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event); virtual void onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event); void switchMachineCallback(Ref* pSender); CREATE_FUNC(SlotScene); private: SlotMachine* m_machine; }; #endif // __HELLOWORLD_SCENE_H__
e6b84eda1ff2448dcd7e81bb6e06f970d8adf2f6
82b359fc3e7cb45abc9712e35675e3f0a8609713
/t2/2.2.cpp
325d6b2bb79d67928bdbc4d2e921c6fa58770575
[]
no_license
chenkk7/programming-of-c--
122c8b8c20b95b89e7b323f95cb552dc65346b05
e5d8a81821fe184df5712c4c27635be92042f305
refs/heads/master
2020-05-31T22:57:23.595157
2019-12-18T15:46:37
2019-12-18T15:46:37
190,529,344
1
0
null
2019-06-06T06:45:15
2019-06-06T06:45:14
null
GB18030
C++
false
false
582
cpp
2.2.cpp
/*2.已知一个string的对象str的内容为“We are here!”,使用多种方法输出“h”。*/ #include <iostream> #include <string> #include <algorithm> #include <iterator> using namespace std; int main() { string str="We are here!"; int i=str.find('h',0); cout<<"1 "<<str[i]<<endl;//str第i个元素 string str2 = str.substr(i,1);//截取 cout<<"2 "<<str2<<endl; char str3 = str[i]; cout<<"3 "<<str3<<endl; char str4[1]; copy(str.begin()+i, str.begin()+i+1, str4);//拷贝出来 cout<<"4 "<<str4[0]<<endl; return 0; }
a7c50eb5a55656dd5f48ddf97fda52d2cb4cc328
b2888cdd7a914c9060e555ef8d0e2cc0552d8e3a
/src/transactions/ManageOfferOpFrameBase.h
ae422d77022cd41fc3c7af6da6eb203dd115238a
[]
no_license
OlehKSS/DigitalBits
44010731138b37d98c2b4c8ced042825c9023b50
0da87773a23762c8bcb8083eac555be9ac6a7a3e
refs/heads/master
2023-07-11T02:25:57.992010
2021-08-13T10:47:54
2021-08-13T10:47:54
395,321,733
0
0
null
2021-08-16T08:49:23
2021-08-12T13:05:48
C++
UTF-8
C++
false
false
2,855
h
ManageOfferOpFrameBase.h
#pragma once // Copyright 2019 DigitalBits Development Foundation and contributors. Licensed // under the Apache License, Version 2.0. See the COPYING file at the root // of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 #include "transactions/OperationFrame.h" namespace digitalbits { class AbstractLedgerTxn; class ManageOfferOpFrameBase : public OperationFrame { Asset const mSheep; Asset const mWheat; int64_t const mOfferID; Price const mPrice; bool const mSetPassiveOnCreate; bool checkOfferValid(AbstractLedgerTxn& lsOuter); bool computeOfferExchangeParameters(AbstractLedgerTxn& ltxOuter, bool creatingNewOffer, int64_t& maxSheepSend, int64_t& maxWheatReceive); LedgerEntry buildOffer(int64_t amount, uint32_t flags, LedgerEntry::_ext_t const& extension) const; virtual int64_t generateNewOfferID(LedgerTxnHeader& header); public: ManageOfferOpFrameBase(Operation const& op, OperationResult& res, TransactionFrame& parentTx, Asset const& sheep, Asset const& wheat, int64_t offerID, Price const& price, bool setPassiveOnCreate); bool doCheckValid(uint32_t ledgerVersion) override; bool doApply(AbstractLedgerTxn& lsOuter) override; void insertLedgerKeysToPrefetch(UnorderedSet<LedgerKey>& keys) const override; virtual bool isAmountValid() const = 0; virtual bool isDeleteOffer() const = 0; virtual int64_t getOfferBuyingLiabilities() = 0; virtual int64_t getOfferSellingLiabilities() = 0; virtual void applyOperationSpecificLimits(int64_t& maxSheepSend, int64_t sheepSent, int64_t& maxWheatReceive, int64_t wheatReceived) = 0; virtual void getExchangeParametersBeforeV10(int64_t& maxSheepSend, int64_t& maxWheatReceive) = 0; virtual bool isResultSuccess() = 0; virtual ManageOfferSuccessResult& getSuccessResult() = 0; virtual void setResultSuccess() = 0; virtual void setResultMalformed() = 0; virtual void setResultSellNoTrust() = 0; virtual void setResultBuyNoTrust() = 0; virtual void setResultSellNotAuthorized() = 0; virtual void setResultBuyNotAuthorized() = 0; virtual void setResultLineFull() = 0; virtual void setResultUnderfunded() = 0; virtual void setResultCrossSelf() = 0; virtual void setResultSellNoIssuer() = 0; virtual void setResultBuyNoIssuer() = 0; virtual void setResultNotFound() = 0; virtual void setResultLowReserve() = 0; }; }
9313b33216307ba80fb5fbec844076b74912d224
dffd7156da8b71f4a743ec77d05c8ba031988508
/ac/arc105/arc105_d/17351337.cpp
d6f955a03f709be832213ab8c583f731848ad5d1
[]
no_license
e1810/kyopro
a3a9a2ee63bc178dfa110788745a208dead37da6
15cf27d9ecc70cf6d82212ca0c788e327371b2dd
refs/heads/master
2021-11-10T16:53:23.246374
2021-02-06T16:29:09
2021-10-31T06:20:50
252,388,049
0
0
null
null
null
null
UTF-8
C++
false
false
393
cpp
17351337.cpp
#include<bits/stdc++.h> using ll = int_fast64_t; #define REP(i,b,e) for(ll i=b; i<e; i++) int main(){ int q; scanf("%d", &q); while(q--){ int n; scanf("%d", &n); std::map<ll,int> mp; REP(i, 0, n){ int a; scanf("%d", &a); mp[a]++; } bool ok = true; for(auto [k, v]: mp){ if(v%2) ok = false; } if((n&1)^ok) puts("Second"); else puts("First"); } return 0; }
5122e296fe42755b39a9b86524538e2409977904
939389fc86985aed5a0da234b792434d20fe00d6
/Framework/ECS/ECS.h
ea58e356c05f0ead01ab394ede2d01a4062645e2
[]
no_license
zachrammell/Damascus
aff551501b6365d00df2603079f7c555658363a8
2c7491b0b716c344db2bd05c977c261e13e0127e
refs/heads/master
2023-06-27T09:17:22.463461
2021-07-11T18:50:46
2021-07-11T18:50:46
389,797,844
0
0
null
2021-07-26T23:48:37
2021-07-26T23:48:36
null
UTF-8
C++
false
false
684
h
ECS.h
#pragma once class TransformComponentSystem; class RenderComponentSystem; class PhysicsComponentSystem; #define COMPONENTS(x)\ TransformComponent##x, RenderComponent##x, PhysicsComponent##x\ #define COMPONENT_SYSTEMS COMPONENTS(System) class ECS { public: static entt::registry& Get() { ASSERT(registry != nullptr, "ECS not initialized"); return *registry; } static void CreateSystems(); template <class System> static System& GetSystem() { return std::get<System>(systems); } static void UpdateSystems(float dt); static void DestroySystems(); private: static std::tuple< COMPONENT_SYSTEMS > systems; inline static entt::registry* registry = nullptr; };
5f29c3aada1ee2d5bd5b1b749de1a2e234633482
ea6038e56c4743e728286f9264ba143bfb440055
/bottomtimegrid.cpp
89762c838f304fb5d76466194b800db4ed6ad496
[]
no_license
pppkitppp/StockKLine
ab0508e0e8853dabe6336fbd6ea3682e0d0e7429
f10febf8eeced04e3863b5222a197a8726608290
refs/heads/master
2020-06-04T08:35:13.733141
2019-10-23T16:13:37
2019-10-23T16:13:37
191,945,712
1
0
null
2019-06-14T13:13:49
2019-06-14T13:13:48
null
UTF-8
C++
false
false
1,233
cpp
bottomtimegrid.cpp
#include <QWidget> #include <QPainter> #include <QMouseEvent> #include <QKeyEvent> #include "bottomtimegrid.h" BottomTimeGrid::BottomTimeGrid(MarketDataSplitter* parent, DataFile* dataFile) : DataWidget(parent, dataFile, false) { this->setFixedHeight(tipsHeight); } void BottomTimeGrid::paintEvent(QPaintEvent* event) { if (!bCross) { return; } else if (mousePoint.x() < getMarginLeft() || mousePoint.x() > getGridWidth() + getMarginLeft()) { return; } QPainter painter(this); QPen pen; QBrush brush(QColor(64,0,128)); painter.setBrush(brush); pen.setColor(QColor("#FFFFFF")); pen.setWidth(1); painter.setPen(pen); QRect rect(mousePoint.x(), 0, tipsWidth, tipsHeight); painter.drawRect(rect); int currentDayAtMouse = ( mousePoint.x() - getMarginLeft() ) * totalDay / getGridWidth() + beginDay; if( currentDayAtMouse >= endDay) { currentDayAtMouse = endDay; } else if (currentDayAtMouse <= beginDay) { currentDayAtMouse = beginDay; } QRect rectText(mousePoint.x() + 5, 5, tipsWidth, tipsHeight); painter.drawText(rectText, mDataFile->kline[currentDayAtMouse].time); }
a62df93a9c9489446d902b2f38fee9af60b869b6
6bac07ceda232029b6a9ea0144ad261311348699
/shared/extensions/FontPrint.h
e9d3156e8806d1e5dbf8a4e74cef5e4dc0525b8e
[ "Zlib" ]
permissive
DK22Pac/plugin-sdk
ced6dc734846f33113e3596045b58febb7eb083c
b0ebc6e4f44c2d5f768b36c6a7a2a688e7e2b9d3
refs/heads/master
2023-08-17T06:36:25.363361
2023-08-10T05:19:16
2023-08-10T05:19:20
17,803,683
445
221
Zlib
2023-08-13T04:34:28
2014-03-16T16:40:08
C++
UTF-8
C++
false
false
3,941
h
FontPrint.h
/* Plugin-SDK (Grand Theft Auto) SHARED header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #pragma once #ifndef GTA2 #include <string> #include <vector> #include "CRGBA.h" #include "CVector.h" #include "Screen.h" #ifdef GTA3 #define FONT_DEFAULT 0 #else #define FONT_DEFAULT 1 #endif namespace plugin { class gamefont { public: enum Alignment { AlignCenter, AlignLeft, AlignRight }; enum ScreenSide { LeftTop, LeftBottom, RightTop, RightBottom }; static void PrintUnscaled(const std::string &line, float x, float y, unsigned char style = FONT_DEFAULT, float w = 1.0f, float h = 1.0f, CRGBA const &color = CRGBA(255, 255, 255, 255), Alignment alignment = AlignLeft, unsigned char dropPosition = 1, CRGBA const &dropColor = CRGBA(0, 0, 0, 255), bool shadow = false, float lineSize = 9999.0f, bool proportional = true, bool justify = false); static void Print(const std::string &line, float x, float y, unsigned char style = FONT_DEFAULT, float w = 1.0f, float h = 1.0f, CRGBA const &color = CRGBA(255, 255, 255, 255), Alignment alignment = AlignLeft, unsigned char dropPosition = 1, CRGBA const &dropColor = CRGBA(0, 0, 0, 255), bool shadow = false, float lineSize = 9999.0f, bool proportional = true, bool justify = false, ScreenSide screenSide = LeftTop); static void Print(ScreenSide screenSide, Alignment alignment, const std::string &line, float x, float y, unsigned char style = FONT_DEFAULT, float w = 1.0f, float h = 1.0f, CRGBA const &color = CRGBA(255, 255, 255, 255), unsigned char dropPosition = 1, CRGBA const &dropColor = CRGBA(0, 0, 0, 255), bool shadow = false, float lineSize = 9999.0f, bool proportional = true, bool justify = false); static void Print(std::vector<std::string> const &lines, float x, float y, float spacing = 1.0f, unsigned char style = FONT_DEFAULT, float w = 1.0f, float h = 1.0f, CRGBA const &color = CRGBA(255, 255, 255, 255), Alignment alignment = AlignLeft, unsigned char dropPosition = 1, CRGBA const &dropColor = CRGBA(0, 0, 0, 255), bool shadow = false, float lineSize = 9999.0f, bool proportional = true, bool justify = false, ScreenSide screenSide = LeftTop); static void Print(ScreenSide screenSide, Alignment alignment, std::vector<std::string> const &lines, float x, float y, float spacing = 1.0f, unsigned char style = FONT_DEFAULT, float w = 1.0f, float h = 1.0f, CRGBA const &color = CRGBA(255, 255, 255, 255), unsigned char dropPosition = 1, CRGBA const &dropColor = CRGBA(0, 0, 0, 255), bool shadow = false, float lineSize = 9999.0f, bool proportional = true, bool justify = false); static bool PrintAt3d(CVector const &posn, const std::string &line, float offset_x = 0.0f, float offset_y = 0.0f, unsigned char style = FONT_DEFAULT, float w = 1.0f, float h = 1.0f, CRGBA const &color = CRGBA(255, 255, 255, 255), bool scaleOnDistance = true, Alignment alignment = AlignLeft, unsigned char dropPosition = 1, CRGBA const &dropColor = CRGBA(0, 0, 0, 255), bool shadow = false, float lineSize = 9999.0f, bool proportional = true, bool justify = false); static bool PrintAt3d(CVector const &posn, std::vector<std::string> const &lines, float spacing = 1.0f, float offset_x = 0.0f, float offset_y = 0.0f, unsigned char style = FONT_DEFAULT, float w = 1.0f, float h = 1.0f, CRGBA const &color = CRGBA(255, 255, 255, 255), bool scaleOnDistance = true, Alignment alignment = AlignLeft, unsigned char dropPosition = 1, CRGBA const &dropColor = CRGBA(0, 0, 0, 255), bool shadow = false, float lineSize = 9999.0f, bool proportional = true, bool justify = false); }; } #endif
1f6dac0cf4dc53494ff5d7620fa0e478cbc9e16b
a363b5e64374f299ede8dcb4aaacc4999de5568f
/test/matrixMultiplication/matrixMultiplication_e3-K256-B8.cpp
cb89d8902a3443d303eb34f3babe48278f8a4023
[]
no_license
educhielle/e3extensions
d6f86ef03b035619cdf8cc051d170a73dfec57c9
0a5d1a0b0c9eb2b89e824fcfc909a6a4263e6469
refs/heads/master
2021-03-22T05:12:42.606459
2017-08-27T12:45:47
2017-08-27T12:45:47
89,483,857
0
0
null
null
null
null
UTF-8
C++
false
false
5,957
cpp
matrixMultiplication_e3-K256-B8.cpp
#include <iostream> #include "../../src/e3extensions/secureint.h" using namespace std; string libgDir = "./libg.so"; string gFunctionName = "libg"; int main() { Cryptosystem cs("105887758112610492763957030143817554940461266207577495880141219828795573971961",8,"8560006943331903586878980207313807142650655176162490108390747982212675778300885119192923417987545090589552938656123492733771371575943132123959057118790534",{"6995490489767564401590943893969144012026396031739620285356906849316791087378638618678868751981399780688592236055654698948854033548388465978379587735034689","766734570715646667170613587142320625995424649503039024602955163037925802757086548582778980166119192404473402659117992523143982872424972504168451771744311","10507612914042540030754614073557707260325712131902121856759588652197015245615815496950737947188772183779962554648495086093857794931767749066341212390304497","5647274536818589148995929178369312459150394720184417076339808313910749037616947195874513586957604440181592812687853203673470481825798587536271103747737269","3172445291869429271799505277263211038343451282326012470386771350059807612695045937519671345599606152035743736142646678966744502539167974867272991150351999","10049681986922660950130770884339419811211036799911573128875124913992927150573551468302044704586765577921787869137656727976551947885072327853820688169852393","453439695495770005903545372832514470747499613620233456083125280318646874435747682264989292890966751237386736601532998665256913165075072019134266252163199","5629939006592551728058786520315177942980714026019805556288691514534369892412394454445084145781295614280321612079531897127437194244568435338178854155005905","9252009396932445780620321358755492691858734392693660834696028327256608049081984279545259477277067709950737767075158877940082603003407187586702890803983627"},"5834761312989683755407741473015814372992246045561181175059828223752184186513867392401180266418911858429817818484144568679913945289647634391846282174169078","8101353866820382196327009282928576259568543078762261505794541708566140857317232456548309973853285882297908714037405430832417281004191380145073716229923022", libgDir, gFunctionName); SecureInt a[3][3], b[3][3], c[3][3]; a[0][0] = SecureInt("3733823668430950370860093053069683752665825431461616384740985002448629735799323886382707679094281115943859768783647818025946789216395234855369623193813196",cs); a[0][1] = SecureInt("4306196179978443695514459561001073628930001667145239485415475519404076601691730969034299811181239582550150962214223798252491748733697007297668758337058618",cs); a[0][2] = SecureInt("4785747863939172670629025856688614660310022844091049282671190208883738943835550745309260953254595352683185980814227460423762181532285237981530023027032565",cs); a[1][0] = SecureInt("8975142146050810165217561525228136683254178162862843852519497472773830190195503141145499281652808186969572934859513014986743700694688263495147807097159598",cs); a[1][1] = SecureInt("6486502605444915474142954751440098831329624912153735324939161572227122110401679446703108028428152904765941236339202069417741411680830832607654729334170990",cs); a[1][2] = SecureInt("4679676901924624238880258161299277784946867638271291022197170933975686194946595516980853632809832626175937361102168983089111360729897997651433146867042421",cs); a[2][0] = SecureInt("3762518128378468200258363766765274544080318260017769843255458406591025829218143307579786954549690262311983809672928947633674013986975721276922890543631276",cs); a[2][1] = SecureInt("7731529394878588945655981716016632959732923293986150185108540807823847296519992999616072674751913798043812762127820024740155355224688331986873242200790533",cs); a[2][2] = SecureInt("8474801581967898734788630572138762508897890931824724566143100644946167020080427162256782778290547894459948756059955377825143082327140643825624868883631953",cs); b[0][0] = SecureInt("1063112530860118040888239502265162193381267783127775424119524142715684445039936893669159720746047684872658814961603570024280105713745759969439390269727151",cs); b[0][1] = SecureInt("7367450640511377964305500857816572630518697201953296901437857397067582594727941746775443980267452204218233444779664920947187261511472139446467713551918853",cs); b[0][2] = SecureInt("2791894924586106034193268725953803079258373066278499104378129813674648993115709873982144923037434279480340642897651507387454779310766539871941026063217149",cs); b[1][0] = SecureInt("3674522940956460139372117481483169882565901806006516328613008124841845341132312076864632763011545978193029265294994996582479568182364167678828689638699931",cs); b[1][1] = SecureInt("8208259728625271945347856481583562663905973379147853796114090405798504386531373409428418178290903394382868036499110112596192098093450033136425025428621039",cs); b[1][2] = SecureInt("10249886159501576436553208931087448131946481181480598268316969041202062098931572290844788704742328617831984343252828695104081901722976949310905083430070232",cs); b[2][0] = SecureInt("924434646081613058458591839794414648027566613325627323415830343786306618121378444264638054307669779973108979779183707450134767566607207157085036945952768",cs); b[2][1] = SecureInt("8748958840855096258436485827088592095984650611787190061896573868864255411101404976113418429976771641958773641213051291866385756055998748493742315478171341",cs); b[2][2] = SecureInt("9671021436245577893045801291536193759316572420790765440212311633649343014721071110330586333894391375427870128593822011404726118071429369500675725069205633",cs); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { c[i][j] = SecureInt("8373440721428978607605121005123833259863142383141291289194397965207842362925390657942347160482860712657724374891223664559533334158962000265810535439477311",cs); for (int k = 0; k < 3; k++) c[i][j] += a[i][k] * b[k][j]; } } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) cout << c[i][j].str() << " "; cout << "\n"; } return 0; }
1a9c13f139030484beec354f18e7685e1b5d37f2
877c1199a8f283a7efd7059a33a397d8ef375ef5
/Laboratorios/Laboratorio 3/Ejercicio 7.cpp
0b822d1eedbe4a1a4cd21d350decb2bf61463c89
[]
no_license
HeyChobe/Portafolio_00204119
05f4c025a5ff7c798462f4032475560f0b9bc857
77c30235d330c6726abff25565855cca20fc6fc1
refs/heads/master
2020-07-09T02:28:09.416501
2019-11-18T01:34:18
2019-11-18T01:34:18
203,848,772
3
1
null
null
null
null
UTF-8
C++
false
false
2,129
cpp
Ejercicio 7.cpp
#include <iostream> using namespace std; struct TNodo{ int dato; struct TNodo *sig; }; typedef struct TNodo Nodo; Nodo *pInicio; void Insertar(int p) { Nodo *nuevo = new Nodo; nuevo->dato = p; nuevo->sig = NULL; if (pInicio == NULL) { pInicio = nuevo; } else { Nodo *p = pInicio; Nodo *q = NULL; while (p != NULL) { q = p; p = p->sig; } q->sig = nuevo; } } void Mostrar(int x){ cout<<"["<<x<<"]"; } void mostrarLista() { Nodo *s = pInicio; if(s==NULL){ cout<<"No hay elementos en la lista"<<endl; return; } while (s != NULL) { Mostrar(s->dato); s = s->sig; } cout<<endl<<endl; } //Por razones que desconozco, me elimina los elementos comunes, pero siempre me deja 1 sin eliminar void FelimV(Nodo *l, int x){ Nodo *q=NULL; l=pInicio; if(l == NULL){ cout<<"No hay elementos!"<<endl; return; } while(l != NULL){ if(x == l->dato){ if(q == NULL){ pInicio = l->sig; } else q->sig = l->sig; delete(l); } q=l; l=l->sig; } } int main(){ pInicio=NULL; Nodo Fila; bool FIN=false; int opcion=0, x=0; do{ cout<<"Que desea hacer?"; cout<<"\n\t1) Insertar Elementos\n\t2) Ver Elementos\n\t3) Eliminar un numero en especifico\n\t4) Salir"; cout<<"\nSu opcion: "; cin>>opcion; cout<<endl; switch (opcion) { case 1: cout<<"Valor por ingresar: "; cin>>x; cout<<endl; Insertar(x); break; case 2: mostrarLista(); break; case 3: cout<<"Valor por eliminar: "; cin>>x; cout<<endl; FelimV(&Fila,x); break; default: cout<<"Opcion erronea!"<<endl; break; } }while(FIN==false); }
1ca395f7dc325c85504089787d1df8c7e94cae31
370b42bbc0060e6d3741fd9f03b8f53804970063
/coreAI/evaluate.cpp
80fc17b100e966f66a8edbf48e9dbf153e6dedaa
[]
no_license
Michael-Z/pokerautomation
2669038941015ad4d340ff692a9c6e6d98d1aead
ab3bb389653b06dd52fedc11af8d160a2c05560e
refs/heads/master
2020-04-09T01:56:55.458046
2014-08-17T20:51:30
2014-08-17T20:51:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,560
cpp
evaluate.cpp
/* $Revision: 51 $ $Date: 2008-10-03 00:41:53 -0700 (Fri, 03 Oct 2008) $ $Author: vananth $ */ #include <iostream> #include <string.h> #include "evaluate.h" #include "lookupTables.h" namespace evaluate { /** This returns the rank of a hand. Higher ranked hands are better than lower ranked ones. \param handMask : 64 bit number representing the hand \param nCards : Number of cards in the hand \return rank : Returns a 32 bit rank */ uint32 evaluateHand(uint64 handMask, uint32 nCards) { /* Hand : 52 bit number with bits set for the appropriate card cccc...dddd...hhhh...ssss (lowest bit is 2 followed by 3,4...K,A) This is the packed format for a hand. The unpacked format is used for the return value. In the unpacked format, each card's rank is represented by 4 bits. Therefore we need 20 bits for a 5-card hand + 4 bits for the hand type. This is an ordered set. Mapping : 2=0, 3=1, .....K=11, A=12 Hand looks like : HAND_TYPE-TOP_CARD-SECOND_CARD-THIRD_CARD-FOURTH_CARD-FIFTH_CARD where each element is a 4 bit number */ uint32 retval = VALUE_ERROR; uint32 pairCardMask; uint32 tripsCardMask; uint32 quadsCardMask; uint32 remainingCards; /* Split the 52 bit hand into 4 hands based on the suit */ uint32 cardSpades = (uint32)((handMask >> SPADES_OFFSET) & 0x00001fffUL); uint32 cardHearts = (uint32)((handMask >> HEARTS_OFFSET) & 0x00001fffUL); uint32 cardDice = (uint32)((handMask >> DICE_OFFSET) & 0x00001fffUL); uint32 cardClubs = (uint32)((handMask >> CLUBS_OFFSET) & 0x00001fffUL); uint32 ranks = cardSpades | cardHearts | cardDice | cardClubs; uint32 nRanks = nBitsTable[ranks]; //number of different ranks uint32 nDuplicates = ((uint32)(nCards - nRanks)); //number of duplicate cards #ifdef DEBUGASSERT if ((nBitsTable[cardSpades]+nBitsTable[cardHearts]+nBitsTable[cardDice]+nBitsTable[cardClubs]) != nCards) { std::cout<<"ERROR in evaluateHand : nCards does not match bits set in handMask\n"; } #endif //Step 1 if (nRanks >=5) //atleast 5 different cards. If this is true, the hand can be a flush, //straight or straight flush { if (nBitsTable[cardSpades] >= 5) //5 or more spades { /*FIXME : Why the TOP_CARD_SHIFT ?? Straight table returns the unpacked format top card of the straight. */ if (straightTable[cardSpades] != 0) { #ifdef NO_TOPCARD_SHIFT_STFLUSH return VALUE_STRAIGHTFLUSH + (uint32)(straightTable[cardSpades]); #else return VALUE_STRAIGHTFLUSH + (uint32)(straightTable[cardSpades] << TOP_CARD_SHIFT); #endif } else retval = VALUE_FLUSH + topFiveCardsTable[cardSpades]; } else if (nBitsTable[cardHearts] >= 5) { if (straightTable[cardHearts] != 0) { #ifdef NO_TOPCARD_SHIFT_STFLUSH return VALUE_STRAIGHTFLUSH + (uint32)(straightTable[cardHearts]); #else return VALUE_STRAIGHTFLUSH + (uint32)(straightTable[cardHearts] << TOP_CARD_SHIFT); #endif } else retval = VALUE_FLUSH + topFiveCardsTable[cardHearts]; } else if (nBitsTable[cardDice] >= 5) { if (straightTable[cardDice] != 0) { #ifdef NO_TOPCARD_SHIFT_STFLUSH return VALUE_STRAIGHTFLUSH + (uint32)(straightTable[cardDice]); #else return VALUE_STRAIGHTFLUSH + (uint32)(straightTable[cardDice] << TOP_CARD_SHIFT); #endif } else retval = VALUE_FLUSH + topFiveCardsTable[cardDice]; } else if (nBitsTable[cardClubs] >= 5) { if (straightTable[cardClubs] != 0) { #ifdef NO_TOPCARD_SHIFT_STFLUSH return VALUE_STRAIGHTFLUSH + (uint32)(straightTable[cardClubs]); #else return VALUE_STRAIGHTFLUSH + (uint32)(straightTable[cardClubs] << TOP_CARD_SHIFT); #endif } else retval = VALUE_FLUSH + topFiveCardsTable[cardClubs]; } else { uint32 topCard = straightTable[ranks]; if (topCard != 0) retval = VALUE_STRAIGHT + (topCard << TOP_CARD_SHIFT); } //If we found a flush or straight, but there are not enough duplicates for a full house //or quads, return because this is the best hand if (retval != VALUE_ERROR && nDuplicates < 3) return retval; } // if nRanks >=5 /*Step 2 : Either we have no flushes or straights OR There are flushes or straights, but we may have a better hand (full house or quads) */ switch (nDuplicates) { case 0: //No duplicates, so just a high card return VALUE_HIGHCARD + topFiveCardsTable[ranks]; case 1: //One pair pairCardMask = ranks ^ (cardSpades ^ cardHearts ^ cardClubs ^ cardDice); //inner xor sets the paired card //to 0. last xor inverts it remainingCards = ranks ^ pairCardMask; // Discard the paired card. /*Set the top card value to the value of the paired card (because higher pair is the deciding factor) Get the top five cards. ShiftR by 4 to avoid colliding with the pairCard (which is at bits 19-16) and retain the 4 kickers Zero out the fourth kicker because we need only 3 kickers (the other two cards are the pair) */ retval = (uint32) (VALUE_PAIR + (topCardTable[pairCardMask] << TOP_CARD_SHIFT) + ((topFiveCardsTable[remainingCards] >> 4) & 0xFFFFFFF0)); return retval; case 2: // Either two pair or trips pairCardMask = ranks ^ (cardSpades ^ cardHearts ^ cardClubs ^ cardDice); //inner xor sets the paired card //to 0. last xor inverts it if (pairCardMask != 0) //Two pair { //pairCardMask has two bits set remainingCards = ranks ^ pairCardMask; retval = (uint32) (VALUE_TWOPAIR + (topFiveCardsTable[pairCardMask] & (0x000FF000)) + (topCardTable[remainingCards] << THIRD_CARD_SHIFT)); return retval; } else //pairCardMask == 0 because of three xors on the same bit, which means it is a trips { tripsCardMask = ((cardClubs & cardDice) | (cardHearts & cardSpades)) & ((cardClubs & cardHearts) | (cardDice & cardSpades)); remainingCards = ranks ^ tripsCardMask; retval = (uint32) (VALUE_TRIPS + (topCardTable[tripsCardMask] << TOP_CARD_SHIFT)); //FIXME: Instead of two lookups, why not just one into the five card table //Maybe better to use topCardTable because it has been cached in the previous step #ifdef TRIPS_SINGLE_LOOKUP retval += (topFiveCardsTable[remainingCards]>>4) & 0xFFFFFF00; #else uint32 secondCard = topCardTable[remainingCards]; retval += (secondCard << SECOND_CARD_SHIFT); remainingCards ^= (0x1 << (int)secondCard); retval += (uint32) (topCardTable[remainingCards] << THIRD_CARD_SHIFT); #endif return retval; } default: //Quads, FullHouse, Two Pair, Straight or Flush //All of them are lumped under default, because three or more duplicates can be any one of them. //Check for quads first quadsCardMask = cardSpades & cardHearts & cardDice & cardClubs ; if (quadsCardMask != 0) { uint32 topCard = topCardTable[quadsCardMask]; uint32 secondCard = ranks ^ (0x1 << (int)topCard); retval = (uint32) (VALUE_QUADS + (topCard << TOP_CARD_SHIFT) + ((topCardTable[secondCard]) << SECOND_CARD_SHIFT)); return retval; } pairCardMask = ranks ^ (cardSpades ^ cardHearts ^ cardClubs ^ cardDice); if (nBitsTable[pairCardMask] != nDuplicates) { /* This means there were an odd number of xors somewhere, which implies a full house (since duplicates >=3) */ uint32 topCard; tripsCardMask = ((cardClubs & cardDice) | (cardHearts & cardSpades)) & ((cardClubs & cardHearts) | (cardDice & cardSpades)); topCard = topCardTable[tripsCardMask]; remainingCards = (pairCardMask | tripsCardMask) ^ (0x1 << (int)topCard); retval = (VALUE_FULLHOUSE + (topCard << TOP_CARD_SHIFT) + (topCardTable[remainingCards] << SECOND_CARD_SHIFT)); return retval; } if (retval != VALUE_ERROR) //retval is non error if it got set while checking for a flush or straight { //If no quads or fullhouse, then the flush or straight discovered before is the best hand //so return with that value return retval; } else { //Three pairs. Therefore choose the best two pair uint32 topCard, secondCard, thirdCard; topCard = topCardTable[pairCardMask]; secondCard = topCardTable[pairCardMask ^ (0x1 << (int)topCard)]; thirdCard = topCardTable[ranks ^ (0x1 << (int)topCard) ^ (0x1 << (int)secondCard)]; retval = (VALUE_TWOPAIR + (topCard << TOP_CARD_SHIFT)+ (secondCard << SECOND_CARD_SHIFT) + (thirdCard << THIRD_CARD_SHIFT)); return retval; } } } uint32 cardStringToInt(char* card) { uint32 cardOffset; switch (card[0]) { case 'A': case 'a': cardOffset = 12; break; case 'K': case 'k': cardOffset = 11; break; case 'Q': case 'q': cardOffset = 10; break; case 'J': case 'j': cardOffset = 9; break; case 'T': case 't': cardOffset = 8; break; case '9': cardOffset = 7; break; case '8': cardOffset = 6; break; case '7': cardOffset = 5; break; case '6': cardOffset = 4; break; case '5': cardOffset = 3; break; case '4': cardOffset = 2; break; case '3': cardOffset = 1; break; case '2': cardOffset = 0; break; } switch (card[1]) { case 'S': case 's': cardOffset += SPADES_OFFSET; break; case 'H': case 'h': cardOffset += HEARTS_OFFSET; break; case 'D': case 'd': cardOffset += DICE_OFFSET; break; case 'C': case 'c': cardOffset += CLUBS_OFFSET; break; } return cardOffset; } void handStringToInt(char* handString, int* cardArr) { char* card; int cardCount(0); card = strtok(handString," "); while (card != NULL) { cardArr[cardCount++] = cardStringToInt(card); card = strtok(NULL," "); } } void handStringToInt(std::string handString, int* cardArr) { char* hand = new char[handString.length()+1]; strcpy(hand,handString.c_str()); handStringToInt(hand,cardArr); delete [] hand; } } //namespace
9258c7c6cae06a1bc2dbe6380520daee51d7259c
b4c9a788a419677212e7263e22d395312672ffb8
/dynamic-layers/b2qt/recipes-qt/automotive/qtapplicationmanager-noop.inc
e4618c84aa3ae27db635aeaded254edc2c000d06
[ "MIT" ]
permissive
dimtass/meta-pelux
eb2116d34fbe394461a801ea82392e9ea74d0c30
450cd0978f2d353c0fd25b74460fa77e1b850a4c
refs/heads/master
2020-08-29T03:39:47.828767
2019-10-24T10:29:35
2019-10-25T17:07:39
217,913,248
0
0
MIT
2019-10-27T20:34:58
2019-10-27T20:34:58
null
UTF-8
C++
false
false
510
inc
qtapplicationmanager-noop.inc
# # Copyright (C) 2017 Pelagicore AB # SPDX-License-Identifier: MIT # # This file is intentionally left blank: it is sourced by the _append recipe for # qtapplicationmanager when the softwarecontainer plugin is disabled. This file # is needed because the "require" directive would fail otherwise; and on the # other hand, we want to use the "require" directory (instead of just # "include") because we want an error to be generated if, for any reason, the # qtapplicationmanager-sc.inc file is not found.
a94db70681fbf1d7eef44d63ac409c15c1fffcdb
5784bbc79aad6f74ca4729634532fd366f932f7f
/STL_Container/AccessList.h
d3f64c519887f7aacfd1069baaa4eb1a2e91d58f
[]
no_license
kuliantnt/Professional_Cpp_linux
792cdea744ce40a4cd285db788a5152b4ffe29ab
43592f23182f26bf66a5047cd815391886f8286a
refs/heads/master
2020-12-02T17:46:26.395827
2017-08-09T00:51:03
2017-08-09T00:51:03
96,424,050
0
0
null
null
null
null
UTF-8
C++
false
false
513
h
AccessList.h
// // Created by lianlian on 17-7-30. // #pragma once #include <initializer_list> #include <string> #include <set> #include <string> #include <list> class AccessList { public: AccessList() = default; AccessList(const std::initializer_list<std::string> & initlist); void addUser(const std::string& user); void removeUser(const std::string& user); bool isAllowed(const std::string &user) const; std::list<std::string> getAllUsers() const; private: std::set<std::string> mAllowed; };
57398293abcf001b4e3e75f0081894991b19cd86
3aabc2a6de308456967161419fc4e2d3c612bace
/src/reactor/linux/file_impl.cpp
ee2ea004bdbf5bddbc2d73f1d87eaf0cd736cac8
[ "Apache-2.0", "BSL-1.0" ]
permissive
victor-smirnov/dumbo
4f7322f04777198442ff09ecc927bdf02fc7eaf6
57fe7f765c69490a9bda6619bcab8fcca0e1d2d9
refs/heads/master
2021-01-11T01:09:10.322459
2017-04-02T15:40:12
2017-04-02T15:40:12
71,056,780
4
0
null
null
null
null
UTF-8
C++
false
false
6,988
cpp
file_impl.cpp
// Copyright 2017 Victor Smirnov // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <dumbo/v1/reactor/linux/file_impl.hpp> #include <dumbo/v1/reactor/linux/io_poller.hpp> #include <dumbo/v1/reactor/reactor.hpp> #include <dumbo/v1/reactor/message/fiber_io_message.hpp> #include <dumbo/v1/tools/ptr_cast.hpp> #include <dumbo/v1/tools/bzero_struct.hpp> #include <dumbo/v1/tools/perror.hpp> #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <stdio.h> #include <unistd.h> #include <sys/syscall.h> #include <sys/epoll.h> #include <sys/eventfd.h> #include <fcntl.h> #include <string.h> #include <stdint.h> #include <exception> namespace dumbo { namespace v1 { namespace reactor { class FileSingleIOMessage: public FileIOMessage { iocb block_; int64_t size_{}; uint64_t status_{}; FiberContext* fiber_context_; public: FileSingleIOMessage(int cpu, int fd, int eventfd, char* buffer, int64_t offset, int64_t size, int command): FileIOMessage(cpu), block_(tools::make_zeroed<iocb>()), fiber_context_(fibers::context::active()) { block_.aio_fildes = fd; block_.aio_lio_opcode = command; block_.aio_reqprio = 0; block_.aio_buf = (__u64) buffer; block_.aio_nbytes = size; block_.aio_offset = offset; block_.aio_flags = IOCB_FLAG_RESFD; block_.aio_resfd = eventfd; block_.aio_data = (__u64) this; } virtual ~FileSingleIOMessage() {} virtual void report(io_event* status) { size_ = status->res; status_ = status->res2; } FiberContext* fiber_context() {return fiber_context_;} const FiberContext* fiber_context() const {return fiber_context_;} virtual void process() noexcept { return_ = true; } virtual void finish() { engine().scheduler()->resume(fiber_context_); } virtual std::string describe() { return "FileSingleIOMessage"; } void wait_for() { engine().scheduler()->suspend(fiber_context_); } int64_t size() const {return size_;} uint64_t status() const {return status_;} iocb* block() {return &block_;} }; File::File(std::string path, FileFlags flags, FileMode mode): path_(path) { fd_ = ::open(path_.c_str(), (int)flags | O_DIRECT, (mode_t)mode); if (fd_ < 0) { tools::rise_perror(tools::SBuf() << "Can't open file " << path); } } File::~File() noexcept { } void File::close() { if (::close(fd_) < 0) { tools::rise_perror(tools::SBuf() << "Can't close file " << path_); } } int64_t File::seek(int64_t pos, FileSeek whence) { off_t res = ::lseek(fd_, pos, (int)whence); if (res >= 0) { return res; } else { tools::rise_perror(tools::SBuf() << "Error seeking in file " << path_); } } int64_t File::process_single_io(char* buffer, int64_t offset, int64_t size, int command, const char* opname) { Reactor& r = engine(); FileSingleIOMessage message(r.cpu(), fd_, r.io_poller().event_fd(), buffer, offset, size, command); iocb* pblock = message.block(); while (true) { int res = io_submit(r.io_poller().aio_context(), 1, &pblock); if (res > 0) { message.wait_for(); if (message.size() < 0) { tools::rise_perror(-message.size(), tools::SBuf() << "AIO " << opname << " operation failed for file " << path_); } return message.size(); } else if (res < 0) { tools::rise_perror(tools::SBuf() << "Can't submit AIO " << opname << " operation for file " << path_); } } } int64_t File::read(char* buffer, int64_t offset, int64_t size) { return process_single_io(buffer, offset, size, IOCB_CMD_PREAD, "read"); } int64_t File::write(const char* buffer, int64_t offset, int64_t size) { return process_single_io(const_cast<char*>(buffer), offset, size, IOCB_CMD_PWRITE, "write"); } class FileMultiIOMessage: public FileIOMessage { IOBatchBase& batch_; size_t remaining_{}; FiberContext* fiber_context_; public: FileMultiIOMessage(int cpu, int fd, int event_fd, IOBatchBase& batch): FileIOMessage(cpu), batch_(batch), remaining_(batch.nblocks()), fiber_context_(fibers::context::active()) { batch.configure(fd, event_fd, this); return_ = true; } virtual ~FileMultiIOMessage() {} virtual void report(io_event* status) { ExtendedIOCB* eiocb = tools::ptr_cast<ExtendedIOCB>((char*)status->obj); eiocb->processed = status->res; eiocb->status = status->res2; } FiberContext* fiber_context() {return fiber_context_;} const FiberContext* fiber_context() const {return fiber_context_;} virtual void process() noexcept {} virtual void finish() { if (--remaining_ == 0) { engine().scheduler()->resume(fiber_context_); } } virtual std::string describe() { return "FileMultiIOMessage"; } void wait_for() { engine().scheduler()->suspend(fiber_context_); } void add_submited(size_t num) { remaining_ = num; batch_.set_submited(batch_.submited() + num); } }; size_t File::process_batch(IOBatchBase& batch, bool rise_ex_on_error) { Reactor& r = engine(); FileMultiIOMessage message(r.cpu(), fd_, r.io_poller().event_fd(), batch); size_t total = batch.nblocks(); size_t done = 0; while (done < total) { iocb** pblock = batch.blocks(done); int to_submit = total - done; int res = io_submit(r.io_poller().aio_context(), to_submit, pblock); if (res > 0) { message.add_submited(res); message.wait_for(); done += res; } else if (res < 0) { tools::rise_perror(tools::SBuf() << "Can't submit AIO batch operations for file " << path_); } else { return 0; } } return done; } void File::fsync() { // NOOP at the moment } void File::fdsync() { // NOOP at the moment } }}}
12204944b3f2fc3db95866635e0b8cd32a1b8227
a88f0ca4bc31b40ab414476f0a0df733418ff038
/Include/3ds_Max/2018/CATAPI/ITail.h
02ad786a11dd02042696e05f5b3859591860cc86
[]
no_license
Goshido/GXEngine-Windows-OS-x64
8c9011442a5ef47a3c2864bdc7e6471e622763d5
10a1428d0284552856528d519283295388eea35b
refs/heads/master
2020-06-28T16:59:26.904805
2019-11-24T06:07:03
2019-11-24T06:09:40
74,490,143
11
1
null
null
null
null
UTF-8
C++
false
false
886
h
ITail.h
////////////////////////////////////////////////////////////////////////////// // // Copyright 2009 Autodesk, Inc. All rights reserved. // Copyright 2003 Character Animation Technologies. // // Use of this software is subject to the terms of the Autodesk license // agreement provided at the time of installation or download, or which // otherwise accompanies this software in either electronic or hard copy form. // ////////////////////////////////////////////////////////////////////////////// #pragma once #include "../ifnpub.h" namespace CatAPI { static const Interface_ID TAIL_INTERFACE_FP(0x17392178, 0x3c020f81); #define GetCATITailFPInterface(anim) (anim ? ((CatAPI::ITail*)anim->GetInterface(CatAPI::TAIL_INTERFACE_FP)) : nullptr) class IHub; class ITail : public FPMixinInterface { public: virtual IHub* GetIHub() = 0; }; }
388bb40653692499776c01f6c093e1a9d6da4854
20933700bd5cd75d6e9db44b3aad3d6088f18beb
/32.longest-valid-parentheses.cpp
4ea04680780f62893182cac45043e7b0965383d5
[]
no_license
llk2why/leetcode
6d994c5d0aa453a91c4145863278b10272105e82
c96bc85e2763e7374cd2b6cefef92a1f4bbd548a
refs/heads/master
2020-09-08T19:31:07.264375
2020-05-22T15:22:26
2020-05-22T15:22:26
221,225,076
0
0
null
null
null
null
UTF-8
C++
false
false
1,039
cpp
32.longest-valid-parentheses.cpp
/* * @lc app=leetcode id=32 lang=cpp * * [32] Longest Valid Parentheses */ class Solution { public: int longestValidParentheses(string s) { int l,r,n,ans; l=r=n=ans=0; for(int i=0;i<s.size();i++){ if(s[i]=='(')l++; else if(s[i]==')'){ if(l>0)l--; else s[i]='_'; } } for(int i=s.size()-1;i>=0;i--){ if(s[i]==')')r++; else if(s[i]=='('){ if(r>0)r--; else s[i]='_'; } } for(int i=0;i<s.size();i++){ if(s[i]=='('){ l++; } else if(s[i]==')'){ if(l>0){ l--; n++; ans = n>ans?n:ans; } else{ n=0; l=0; } } else{ n=0;l=0; } } ans*=2; return ans; } };
e2a0d179806a913094734a977d6ed31e2bd6ae2e
ff69ce58b8d690952ceabefba0e45c62ffd8dab3
/Source/LudumDare49/Public/Pickups/PickupKey.h
d66d082b892f31db2fba5384c671fad91090b9b5
[ "MIT" ]
permissive
TrickyFatCat/LudumDare49
bcc742d8ed59198da0b7b97b61d6f423ac60675a
afb0063f557e0973a0c38a1b84a14c3321891978
refs/heads/main
2023-08-19T12:38:35.420363
2021-10-14T23:12:32
2021-10-14T23:12:32
412,625,719
1
1
null
null
null
null
UTF-8
C++
false
false
498
h
PickupKey.h
// Made by Title Goose Team during LudumDare 49. All rights reserved. #pragma once #include "CoreMinimal.h" #include "Actors/PickupBase.h" #include "Components/KeyRingComponent.h" #include "PickupKey.generated.h" /** * */ UCLASS() class LUDUMDARE49_API APickupKey : public APickupBase { GENERATED_BODY() protected: UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="Pickup") EKey KeyColor = EKey::Blue; virtual bool ActivatePickup_Implementation(AActor* TargetActor) override; };
555ee625d6db20c3a728265fd366454ee5bdc8dc
80833b1770e19def702038b78ee7239ca74cad0a
/windovl.cpp
05c983ae111622debc02d55f94b5024a7e5d1238
[ "Unlicense" ]
permissive
SegHaxx/citplus
ddbcbec5d9384908e6a13fa98b508be345023f43
90aedfc7047fe92bdd0d09f1eb1671d7ddcde8a3
refs/heads/master
2022-05-10T14:08:49.261467
2014-07-30T20:53:08
2014-07-30T20:53:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,852
cpp
windovl.cpp
// -------------------------------------------------------------------------- // Citadel: WindOvl.CPP // // Machine dependent windowing routines. #include "ctdl.h" #pragma hdrstop #include "cwindows.h" #include "scrlback.h" #include "extmsg.h" #include "statline.h" // -------------------------------------------------------------------------- // Contents // // cls() clears the screen // help() toggles help menu // setscreen() Set SCREEN to correct address for VIDEO // save_screen() allocates a buffer and saves the screen // setborder() wow. extern ConsoleLockC ConsoleLock; // -------------------------------------------------------------------------- // setborder(): wow. void setborder(int battr) { #ifndef WINCIT union REGS REG; if (battr != 0xff) { REG.h.ah = 11; REG.x.bx = ScreenSaver.IsOn() ? 0 : battr; int86(0x10, &REG, &REG); // border clr } #endif } // -------------------------------------------------------------------------- // cls(): Clears the screen. void TERMWINDOWMEMBER cls(int whatToDo) { #ifdef WINCIT scroll(conRows, conRows + 1, (uchar) cfg.attr); position(0, 0); #else if (whatToDo == SCROLL_SAVE && cfg.scrollSize) { SaveToScrollBackBuffer(logiRow); } if (cfg.bios && !ScreenSaver.IsOn() && !StatusLine.IsFullScreen() && !allWindows) { scroll_bios(conRows, 0, cfg.attr); } else { cls_fast(ScreenSaver.IsOn() ? 0 : cfg.attr); } setborder(cfg.battr); position(0, 0); if (allWindows && !oPhys) { RedrawAll(); } #endif } // -------------------------------------------------------------------------- // help(): This toggles our help menu. void StatusLineC::ToggleHelp(WC_TW) { if (!Visible) { #ifdef WINCIT Toggle(TW); #else Toggle(); #endif } else { int row = tw()logiRow, col = tw()logiCol; // small window? if (!HelpTimeout) { if (LockMessages(MSG_HELP)) { // Make big window... time(&HelpTimeout); scrollpos = conRows - Height(); if (row > scrollpos) { tw()scroll(row, row - scrollpos, cfg.attr); row = scrollpos; } } } else { // Make small window... HelpTimeout = 0; if (State == SL_TWOLINES) { tw()clearline(conRows - 5, cfg.attr); } tw()clearline(conRows - 4, cfg.attr); tw()clearline(conRows - 3, cfg.attr); tw()clearline(conRows - 2, cfg.attr); tw()clearline(conRows - 1, cfg.attr); scrollpos = conRows - Height(); UnlockMessages(MSG_HELP); } tw()position(row, col); updateStatus = TRUE; #ifdef WINCIT Update(TW); #else Update(); #endif } } // -------------------------------------------------------------------------- // sftf10(void): Blank stat lines. void StatusLineC::Toggle(WC_TW) { int row = tw()logiRow, col = tw()logiCol; if (Visible) { Visible = FALSE; for (int i = scrollpos + 1; i <= conRows; i++) { tw()clearline(i, cfg.attr); } scrollpos = conRows; } else { Visible = TRUE; scrollpos = conRows - Height(); if (row > scrollpos) { tw()scroll(row, row - scrollpos, cfg.attr); row = scrollpos; } } tw()position(row, col); updateStatus = TRUE; #ifdef WINCIT Update(TW); #else Update(); #endif } // -------------------------------------------------------------------------- // altF10(): Extra stat line. void StatusLineC::ToggleSecond(WC_TW) { // No second line when in full-screen mode if (State == SL_FULLSCREEN) { return; } // If nothing is visible... make it so. if (!Visible) { #ifdef WINCIT Toggle(TW); #else Toggle(); #endif } else { int row = tw()logiRow, col = tw()logiCol; if (State == SL_ONELINE) { // Make it two... State = SL_TWOLINES; scrollpos = conRows - Height(); if (row > scrollpos) { tw()scroll(row, row - scrollpos, cfg.attr); row = scrollpos; } } else { // Make it one... State = SL_ONELINE; scrollpos = conRows - Height(); tw()clearline(scrollpos, cfg.attr); } tw()position(row, col); updateStatus = TRUE; #ifdef WINCIT Update(TW); #else Update(); #endif } } // -------------------------------------------------------------------------- // save_screen(): Allocates a buffer and saves the screen. Bool TERMWINDOWMEMBER save_screen(void) { #ifndef WINCIT if (saveBuffer == NULL) { compactMemory(); saveBuffer = new char[(conRows + 1) * conCols * 2]; if (saveBuffer == NULL) { mPrintfCR(getmsg(135)); return (FALSE); } else { memcpy(saveBuffer, logiScreen, ((scrollpos + 1) * conCols * 2)); if (scrollpos != conRows) { memset(saveBuffer + ((scrollpos + 1) * conCols * 2), 0, (conRows - scrollpos) * conCols * 2); } s_conRows = conRows; return (TRUE); } } else { return (FALSE); } #else return (FALSE); #endif } // -------------------------------------------------------------------------- // restore_screen(): Restores screen and frees buffer. void TERMWINDOWMEMBER restore_screen(void) { #ifndef WINCIT if (ScreenSaver.IsOn() || allWindows) { return; } // just to be sure, here if (logiScreen == saveBuffer) { logiScreen = physScreen; dgLogiScreen = logiScreen; } if (saveBuffer != NULL) { if (s_conRows <= conRows) { const int row = logiRow, col = logiCol; cls(SCROLL_NOSAVE); position(row, col); memcpy(physScreen, saveBuffer, (s_conRows+1) * conCols * 2); } else { if (cfg.scrollSize) { char *SaveIt = logiScreen; logiScreen = saveBuffer; SaveToScrollBackBuffer(s_conRows - conRows); logiScreen = SaveIt; } memcpy(physScreen, saveBuffer + (s_conRows - conRows) * conCols * 2, (conRows+1) * conCols * 2); } delete [] saveBuffer; saveBuffer = NULL; } #endif } // -------------------------------------------------------------------------- // setscreen(): Set video mode flag 0 mono 1 cga. void setscreen(void) { #ifndef WINCIT int mode; union REGS REG; static uchar heightmode = 0; static uchar scanlines = 0; char mono = 0; char far *CrtHite = (char far *) 0x00400085L; if (!cfg.restore_mode) { heightmode = 0; scanlines = 0; } if (gmode() == 7) { mono = TRUE; } if (!heightmode) { if (*CrtHite == 8) { heightmode = 0x012; } else if (*CrtHite == 14) { heightmode = 0x011; } else if (*CrtHite == 16) { heightmode = 0x014; } } if (scanlines) { REG.h.ah = 0x12; // Video function: REG.h.bl = 0x30; // Set scan lines REG.h.al = scanlines; // Num scan lines int86(0x10, &REG, &REG); } if (heightmode && conMode != -1) // make sure heightmode is set { // conMode 1000 --> EGA 43 line, or VGA 50 line REG.h.ah = 0x00; REG.h.al = (uchar) ((conMode >= 1000) ? 3 : conMode); int86(0x10, &REG, &REG); // Set to character set 18, (EGA 43 line, or VGA 50 line) if (conMode == 1000) { REG.h.ah = 0x11; REG.h.al = 18; REG.h.bl = 0x00; int86(0x10, &REG, &REG); } else { REG.h.ah = 0x11; REG.h.al = heightmode; REG.h.bl = 0x00; int86(0x10, &REG, &REG); } } if (!scanlines) { getScreenSize(&conCols, &conRows); if (!mono) { if (conRows == 24) { if (*CrtHite == 14) scanlines = 1; // Old char set if (*CrtHite == 16) scanlines = 2; // Vga char set } if (conRows == 42) scanlines = 1; if (conRows == 49) scanlines = 2; } else { if (conRows == 24) scanlines = 1; if (conRows == 27) scanlines = 2; // herc only if (conRows == 42) scanlines = 1; } } mode = gmode(); conMode = (mode == 3 && conMode >= 1000) ? conMode : mode; if (mode == 7) { physScreen = (char far *) 0xB0000000L; // mono logiScreen = saveBuffer ? saveBuffer : physScreen; } else { physScreen = (char far *) 0xB8000000L; // cga logiScreen = saveBuffer ? saveBuffer : physScreen; setborder(cfg.battr); } dgLogiScreen = logiScreen; getScreenSize(&conCols, &conRows); scrollpos = conRows - StatusLine.Height(); if (cfg.bios) { charattr = bioschar; stringattr = biosstring; } else { charattr = directchar; stringattr = directstring; } OC.ansiattr = cfg.attr; #endif } void TERMWINDOWMEMBER getScreenSize(uint *Cols, uint *Rows) { #ifndef WINCIT *Cols = (uint) *(uchar far *) (0x0000044A); *Rows = (uint) *(uchar far *) (0x00000484); // sanity checks, some cards don't set these locations. // (Heather's CGA for example. =] ) if (*Cols < 40) *Cols = 80; if (*Rows < 15) *Rows = 24; // now an overide for stupid CGA's (like Krissy's) who // insist on writing to this location.. if (conMode == 1001) { *Cols = 80; *Rows = 24; } #else // This might be correct... *Cols = cfg.ConsoleCols; *Rows = cfg.ConsoleRows - 1; #endif } // -------------------------------------------------------------------------- // ClearToEndOfLine(): Delete to end of line. void TERMWINDOWMEMBER ClearToEndOfLine(void) { const int row = logiRow, col = logiCol; for (int i = col; i < conCols; i++) { #ifdef WINCIT WinPutChar(' ', OC.ansiattr, FALSE); #else (*charattr)(' ', OC.ansiattr, FALSE); #endif } position(row, col); } Bool ScreenSaverC::TurnOn(void) { #ifndef WINCIT if (!On && save_screen()) { const int row = logiRow, col = logiCol; int wow = cfg.attr; int wow2 = cfg.battr; cfg.attr = 0; cfg.battr = 0; cls(SCROLL_NOSAVE); cfg.attr = wow; cfg.battr = wow2; position(row, col); On = TRUE; logiScreen = saveBuffer; dgLogiScreen = logiScreen; if (!cfg.really_really_fucking_stupid) { cursoff(); } if (cfg.LockOnBlank && *cfg.f6pass) { ConsoleLock.Lock(); } } return (On); #else return (FALSE); #endif } void ScreenSaverC::TurnOff(void) { #ifndef WINCIT if (On) { On = FALSE; logiScreen = physScreen; dgLogiScreen = logiScreen; restore_screen(); curson(); StatusLine.Update(WC_TWp); } #endif } void TERMWINDOWMEMBER outPhys(Bool phys) { #ifndef WINCIT static char *save; if (phys) { save = logiScreen; logiScreen = physScreen; dgLogiScreen = logiScreen; oPhys = TRUE; } else { if (save) { logiScreen = save; dgLogiScreen = logiScreen; oPhys = FALSE; } } #endif } Bool StatusLineC::ToggleFullScreen(WC_TW) { #ifndef WINCIT if (!ScreenSaver.IsOn()) { if (State == SL_FULLSCREEN) { State = SL_ONELINE; logiScreen = physScreen; dgLogiScreen = logiScreen; restore_screen(); curson(); UnlockMessages(MSG_F4SCREEN); return (TRUE); } else { if (!Visible) { Toggle(); } if (State == SL_TWOLINES) { ToggleSecond(); } State = SL_FULLSCREEN; updateStatus = TRUE; if (save_screen()) { logiScreen = saveBuffer; dgLogiScreen = logiScreen; const int oldrow = logiRow, oldcol = logiCol; if (!cfg.really_really_fucking_stupid) { cursoff(); } outPhys(TRUE); cls(SCROLL_NOSAVE); outPhys(FALSE); position(oldrow, oldcol); LockMessages(MSG_F4SCREEN); return (TRUE); } else { State = SL_ONELINE; } } } #endif return (FALSE); }
1f8d541b57e0c8a2bae482b897d42d88293e81c5
8a2668da32c439f648bd0571b5da407f798b0d60
/VNTU Training 18/F.cpp
892271d7e4f6b5e4e6a5179299f2fecf67468e58
[]
no_license
Mykhailo-Granik/ACM-Solutions
fea96cbcc485e503f3d268e4d184fc3a3c5cae33
0107543ef2e275454c9217e85104c4b427910993
refs/heads/master
2021-01-10T15:48:33.744653
2017-10-28T21:42:10
2017-10-28T21:42:10
46,673,344
0
0
null
null
null
null
UTF-8
C++
false
false
1,011
cpp
F.cpp
#include <list> #include <map> #include <set> #include <deque> #include <stack> #include <queue> #include <algorithm> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <memory.h> #include <ctime> #include <bitset> #include <unordered_map> using namespace std; #define ABS(a) ((a>0)?a:-(a)) #define MIN(a,b) ((a<b)?(a):(b)) #define MAX(a,b) ((a<b)?(b):(a)) #define FOR(i,a,n) for (int i=(a);i<(n);++i) #define MEMS(a,b) memset((a),(b),sizeof(a)) #define FI(i,n) for (int i=0; i<(n); ++i) #define pnt pair <int, int> #define mp make_pair #define LL long long using namespace std; int a[6][6]; int main() { // your code goes here int m; cin>>m; FOR(i,0,m) { int v1,v2; cin>>v1>>v2; a[v1 - 1][v2 - 1] = a[v2 - 1][v1 - 1] = 1; } bool f = false; FOR(i,0,5) FOR(j,i+1,5) FOR(k,j+1,5) if ((a[i][j] == a[i][k]) && (a[i][j] == a[k][j])) f = true; if (f) cout<<"WIN"<<endl; else cout<<"FAIL"<<endl; return 0; }
065b79c6637498880f5f0edf5499f816dce52928
c5a17ffbd62eee183790cc33847ebc719346a8ba
/queueUsing2stacks.cpp
29cbcb41f04bc47d4b7ba3839e66ba2b1b62ad79
[]
no_license
manyu22/CPPPrograms
dff92b3b01cbd8612112e23c183bf763bcc73d69
bf65fda36db44358747d1970d01d8d89c3952e2f
refs/heads/master
2019-01-19T17:50:39.544406
2014-06-27T11:28:00
2014-06-27T11:28:00
21,249,341
1
0
null
null
null
null
UTF-8
C++
false
false
660
cpp
queueUsing2stacks.cpp
#include<iostream> #include<stack> using namespace std; stack<int> inbox; stack<int> outbox; void enqueue( int value ) { inbox.push( value ); } int dequeue() { int temp; if( !outbox.empty() ){ temp = outbox.top(); outbox.pop(); return temp; } else{ while( !inbox.empty() ){ outbox.push( inbox.top()); inbox.pop(); } if( !outbox.empty() ){ temp = outbox.top(); outbox.pop(); return temp; } else return NULL; } } int main() { enqueue( 10 ); enqueue( 20 ); enqueue( -1); cout<<dequeue()<<endl; cout<<dequeue()<<endl; cout<<dequeue()<<endl; cout<<dequeue()<<endl; }
4e17dbe0371ef7ae214ec7bf393dd9e28f343ff3
04fee3ff94cde55400ee67352d16234bb5e62712
/csp-s2019.luogu/source/XJ-00035/code/code.cpp
fdff385c633d1687ca2b638dbb1463ae650fc3b5
[]
no_license
zsq001/oi-code
0bc09c839c9a27c7329c38e490c14bff0177b96e
56f4bfed78fb96ac5d4da50ccc2775489166e47a
refs/heads/master
2023-08-31T06:14:49.709105
2021-09-14T02:28:28
2021-09-14T02:28:28
218,049,685
1
0
null
null
null
null
UTF-8
C++
false
false
602
cpp
code.cpp
#include<cstdio> #include<algorithm> using namespace std; typedef int int_; #define int long long int n,k; int ans[100]; void work(int o){ if(o==1){ if(k==1) ans[o]=0; else ans[o]=1; return ; } if(o==64){ ans[o]=0; work(o-1); } else{ if(k>(1ll<<(o-1))) ans[o]=1,k=((1ll<<(o-1))-(k-(1ll<<(o-1)))+1ll),work(o-1); else ans[o]=0,work(o-1); } return ; } int_ main() { freopen("code.in","r",stdin); freopen("code.out","w",stdout); scanf("%lld %lld",&n,&k); k+=1; work(n); for(int i=n;i>=1;i--){ printf("%lld",ans[i]); } return 0; }
0b100f05c90d0054e118793ca70df66cb405f738
363687005f5b1d145336bf29d47f3c5c7b867b5b
/atcoder/arc065/d/d.cpp
a50f4b2cf911bcd4def3d4b195ef4f03113fc93d
[]
no_license
gky360/contests
0668de0e973c0bbbcb0ccde921330810265a986c
b0bb7e33143a549334a1c5d84d5bd8774c6b06a0
refs/heads/master
2022-07-24T07:12:05.650017
2022-01-17T14:01:33
2022-07-10T14:01:33
113,739,612
1
0
null
null
null
null
UTF-8
C++
false
false
1,473
cpp
d.cpp
// AtCoder Regular Contest 065 // D - 連結 / Connectivity #include <bits/stdc++.h> using namespace std; typedef long long int ll; typedef pair<int, int> PII; class UnionFind { public: vector<int> data; void init(int size) { data = vector<int>(size, -1); } bool unite(int x, int y) { x = root(x); y = root(y); if (x == y) { return false; } if (data[y] < data[x]) { swap(x, y); } data[x] += data[y]; data[y] = x; return true; } bool same(int x, int y) { return root(x) == root(y); } int root(int x) { return data[x] < 0 ? x : data[x] = root(data[x]); } int size(int x) { return -data[root(x)]; } }; int N, KL[2]; UnionFind uf[2]; map<PII, int> mp; int main() { PII p; int a, b; scanf("%d%d%d", &N, &KL[0], &KL[1]); for (int j = 0; j < 2; j++) { uf[j].init(N); for (int i = 0; i < KL[j]; i++) { scanf("%d%d", &a, &b); uf[j].unite(a - 1, b - 1); } } for (int i = 0; i < N; i++) { p = PII(uf[0].root(i), uf[1].root(i)); mp[p] = mp[p] + 1; } for (int i = 0; i < N; i++) { p = PII(uf[0].root(i), uf[1].root(i)); printf("%d%c", mp[p], i == N - 1 ? '\n' : ' '); } return 0; }
e3b88d83d62fc6f072b076ff7d8533d72d338de0
d06299d476168d2e85d15c200986c4909d7cbaf2
/排序算法/编程练习的地方.cpp
1261eb7663b1854e539a7268738a0877f9d09e1c
[]
no_license
zeroker/Algorithm
e5e8251d66fa87ecc4b73fa39fe02f59f98ff8bb
a2daf280e19b87da9ea2f7690cdb862140d604a1
refs/heads/master
2020-05-01T16:43:57.012659
2019-03-25T12:39:16
2019-03-25T12:39:16
177,580,363
0
0
null
null
null
null
GB18030
C++
false
false
7,273
cpp
编程练习的地方.cpp
//#if 1 //#include<bits/stdc++.h> //using namespace std; // //int line,value; //queue<int> q; //int i; //void bfs(int a[],int i,int k,int sum) //下标从1开始 //{ // if(sum == k) // { // cout<<"=="<<endl; // return ; // } // q.push(a[i]); // q.push(-a[i]); // sum += q.pop(); //} // //void dfs(int a[],int n,int k,int sum) //{ // if(sum == k) // { // // } // // //} // //int main() //{ // int a[1000]; // int n,k; // for(int i=0; i<n; i++) // { // cin>>a[i]; // } // // //} // //#endif // //#if 1 //#include<bits/stdc++.h> //using namespace std; //int main() //{ // int j=1; // int sum = 0; // for(int i=2008; i>=1005; i--) // { // if(j%2 == 1) // sum+=(-1*j*i); // else // sum+=(i*j); // j++; // } // cout<<sum<<endl; //} //#endif #if 0 #include<bits/stdc++.h> #define exp 1e-7 using namespace std; unsigned int n,k; double a[10001],sum; int fun(double s) { int cnt=0; for(int i=0; i<n; i++) { cnt+=(int)(a[i]/s); } if(cnt>=k) return 1; //大于等于 else return 0; } int main() { double mid ,l , r; // cin>>n>>k; scanf("%d,%d",n,k); sum=0; for(int i=0; i<n; i++) { cin>>a[i]; sum+=a[i]; } sum/=k; l=0;r=sum; while(fabs(l-r)>exp) { mid=(l+r)/2; if(fun(mid)) l=mid; else r=mid; } printf("%0.2f\n",l); } #endif //蓝桥练习 //3.19 //十六进制转八进制的 //1、 #if 0 #include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; while(n--) { string s; cin>>s; string str; for(int i=0; i<s.size(); i++) { if(s[i] == '0') str += "0000"; else if(s[i] == '1') str += "0001"; else if(s[i] == '2') str += "0010"; else if(s[i] == '3') str += "0011"; else if(s[i] == '4') str += "0100"; else if(s[i] == '5') str += "0101"; else if(s[i] == '6') str += "0110"; else if(s[i] == '7') str += "0111"; else if(s[i] == '8') str += "1000"; else if(s[i] == '9') str += "1001"; else if(s[i] == 'A') str += "1010"; else if(s[i] == 'B') str += "1011"; else if(s[i] == 'C') str += "1100"; else if(s[i] == 'D') str += "1101"; else if(s[i] == 'E') str += "1110"; else if(s[i] == 'F') str += "1111"; } if(str.size() % 3 == 1) str = "00" + str; else if(str.size() % 3 == 2) str = "0" + str; // for(int i=0; i<str.size(); i++) // { // if(i%4 == 0) // cout<<" "; // cout<<str[i]; // } int flag = 0; for(int i=0; i<str.size(); i+=3) { int t = 0; t = (str[i]-'0')*4 + (str[i+1]-'0')*2 + (str[i+2]-'0')*1; // cout<<t<<"----"<<endl; if(t == 0 && flag == 0) continue; else flag = 1; if(flag) cout<<t; } cout<<endl; } } #endif //2基础练习 闰年判断 #if 0 #include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; if(n%400==0 || (n%4==0 && n%100!=0)) cout<<"yes"<<endl; else cout<<"no"<<endl; } #endif //3. //2018 //1 #if 0 //125 #include<bits/stdc++.h> using namespace std; int a[] = {0,31,29,31,30}; int main() { int count=0; for(int i=1; i<=4; i++) count+=a[i]; count+=4; cout<<count<<endl; } #endif //2 //明码 #if 0 #include<bits/stdc++.h> using namespace std; void fun(int x) //转二进制 { string s = ""; if(x > 0) { while(x != 0) { int temp = x%2; s = char(temp+'0') + s; // x /= 2; } if(s.size() < 8) { int sub = 8-s.size(); for(int i=0; i<sub; i++) s = '0' + s; } } else if(x < 0) { int j; x = -x; while(x != 0) { int temp = x%2; s = char(temp + '0') + s; // x /= 2; } if(s.size() < 8) { int sub = 8-s.size(); for(int i=0; i<sub; i++) s = '0' + s; } for(int i=s.size()-1; i>=0; i--) { if(s[i] == '1') { j = i; break; } } for(int i=0; i<j; i++) { if(s[i] == '0') s[i] = '1'; else s[i] = '0'; } } else if(x == 0) { s = "00000000"; } // for(int i=0; i<s.size(); i++) if(s[i] == '1') cout<<"1"; else if(s[i] == '0') cout<<" "; } int main() { int k = 0; int a[30][1000]; for(int i=1; i<=10; i++) for(int j=1; j<=32; j++) cin>>a[i][j]; for(int i=1; i<=10; i++) { for(int j=1; j<=32; j++) { fun(a[i][j]); if(j%2 == 0) cout<<endl; } cout<<endl; } } #endif //3 #if 0 //26 错误 //31 #include<bits/stdc++.h> using namespace std; int a[11][11]; int main() { int count = 0; int sum = 1; for(int i=0; i<10; i++) for(int j=0; j<10; j++) cin>>a[i][j]; for(int i=0; i<10; i++) { for(int j=0; j<10; j++) { if(sum == 0) sum = 1; sum *= a[i][j]; while(sum%10 == 0 && sum != 0) { sum /= 10; count++; // cout<<"==="<<endl; } // cout<<"++1"<<endl; } } cout<<count<<endl; } #endif // 4 10次 //5 #if 0 #include<bits/stdc++.h> using namespace std; int MAX = 100000+2; int main() { int n; cin>>n; int a[MAX],b[MAX],c[MAX]; for(int i=0; i<n; i++) cin>>a[i]; for(int i=0; i<n; i++) cin>>b[i]; for(int i=0; i<n; i++) cin>>c[i]; sort(a,a+n); sort(b,b+n); sort(c,c+n); int na,nb,nc; if(a[n-1] <= n) na = n; else { for(int i=0; i<n; i++) { if(a[i] > n) { na = i; break; } } } if(b[n-1] <= n) nb = n; else { for(int i=0; i<n; i++) { if(b[i] > n) { nb = i; break; } } } if(c[n-1] <= n) nc = n; for(int i=0; i<n; i++) { if(c[i] > n) { nc = i; break; } } int t[MAX]; int t2[MAX]; for(int i=0; i<nb; i++) { int x = b[i]; int *k = lower_bound(a,a+na,x); t[i] = k-a; //比他小的数的 个数 // cout<<t[i]<<" "; } int sum = 0; for(int i=0; i<nc; i++) { int x = c[i]; int *k = lower_bound(b,b+nb,x); for(int j=0; j<k-b; j++) { t2[i] += t[j]; } // cout<<t2[i]<<" "; sum += t2[i]; } // // for(int i=0; i<nc; i++) // cout<<t2[i]<<" "; cout<<sum<<endl; } #endif // //6 #if 0 #include<bits/stdc++.h> using namespace std; int x[4] = {-1,0,1,0}; //左上 右下 int y[4] = {0,1,0,-1}; int main() { int sum = 0; int step = 1; int func_id = 0; //方向 int count = 1; //转 2 次 ,加 1 个step (记录局部 内 转的 次数) int nx,ny; scanf("%d %d",&nx,&ny); int i=0,j=0; int flag = 0; while(1) { if(i==nx && j==ny) break; if(count == 3) { count = 1; step++; } if(func_id == 4) func_id = 0; for(int k=0; k<step; k++) { if(i==nx && j==ny) { flag = 1; break; } i += x[func_id]; j += y[func_id]; sum++; } if(flag) break; func_id++; count++; //换方向的次数 } cout<<sum<<endl; } #endif #if 1 #include<bits/stdc++.h> using namespace std; int main() { int s[4]; for(int i=1; i<9; i++) { s[0] = i; s[3] = i; for(int j=0; j<9; j++) { s[1] = j; s[2] = j; for(int i=0; i<4; i++) cout<<s[i]; cout<<endl; } } } #endif
a8a2d1b92b4cb36b41605baa49d382d9acf9e289
c82e1101197b19671b1a318c76da934262134dde
/oneTBB-tbb_2020/examples/quicksort_tbb/quicksort/quicksort.cpp
c79229db8bebbb25f5aa6acd87725621a5c20a10
[ "Apache-2.0" ]
permissive
COEN-145-Project/quicksort
405555399f3469bb901382f1c5e31889780403f3
c32b81c0b7814adb23604c54766663e0da43d401
refs/heads/master
2022-09-26T14:08:15.591526
2020-06-04T21:17:15
2020-06-04T21:17:15
266,841,337
0
1
null
2020-05-29T00:12:09
2020-05-25T17:34:52
C
UTF-8
C++
false
false
2,257
cpp
quicksort.cpp
#include "quicksort.h" #include <unistd.h> #include <algorithm> #include <cassert> #include <cstdio> #include <cstring> #include <math.h> #include <cstdlib> #include <cctype> #include "tbb/parallel_reduce.h" #include "tbb/parallel_invoke.h" #include "tbb/tick_count.h" using namespace std; static void import(char const * const filename, int * const np, int** const ap) { int i, j, n, ret; FILE *fp; int *a; fp = fopen(filename, "r"); ret = fscanf(fp, "%d", &n); a = (int *)malloc(n*sizeof(*a)); for( i = 0; i < n; i++) { ret = fscanf(fp, "%d", &a[i]); } fclose(fp); *np = n; *ap = a; } int partition(int *a, int lo, int hi) { int i, j; i = lo; for(j = lo; j < hi; ++j) { if(a[j] < a[hi]) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; ++i; } } int tmp2 = a[i]; a[i] = a[hi]; a[hi] = tmp2; return i; } void quickSort(int *a, int lo, int hi) { //printf("%d %d %d\n", a[0], lo, hi); int pivot; if (lo < hi) { pivot = partition(a, lo, hi); tbb::parallel_invoke( [&]{quickSort(a, lo, pivot-1);}, [&]{quickSort(a, pivot+1, hi);} ); // quickSort(a, lo, pivot-1); // quickSort(a, pivot+1, hi); } } static void print1() { printf("test1\n"); sleep(1); printf("test3\n"); } static void print2() { printf("test2\n"); sleep(1); printf("test4\n"); } int quickSortMain(char * fileName, int thread_count) { int n, i, j, low, high; int *a; // if(argc < 3) // { // return EXIT_FAILURE; // } printf("running with %d threads\n", thread_count); import(fileName, &n, &a); low = 0; high = n; /*for(i = 0; i < n; i++) { printf("%d\n", a[i]); }*/ // tbb::parallel_invoke( // [&]{print1();}, // [&]{print2();} // ); // test line tbb::global_control c(tbb::global_control::max_allowed_parallelism, thread_count); tbb::tick_count start_time = tbb::tick_count::now(); quickSort(a, low, high); tbb::tick_count end_time = tbb::tick_count::now(); // cout << "That took: " << (end_time-start_time).seconds() << "seconds\n"}; printf("That took %f seconds\n", (end_time-start_time).seconds()); // for(i = 0; i < n; i++) // { // printf("%d\n", a[i]); // } return EXIT_SUCCESS; }
f419005b9a07591925f8e37884d38bdb613d8b75
6fd13ec932ef0e0b6829d2585838e5eb84a5cb9a
/core/object/object.h
133e382043726f624e13aea4fe676f8bd46b7288
[]
no_license
SeregaGomen/QFEM
85202e1cd27459e96e8bc46a47aba792e197c97e
7656c828fdb49f5fc14883d202fa6ca5d969d9e0
refs/heads/main
2023-05-25T14:02:18.003816
2023-05-14T13:17:11
2023-05-14T13:17:11
455,945,669
1
0
null
null
null
null
UTF-8
C++
false
false
15,962
h
object.h
#ifndef OBJECT_H #define OBJECT_H #include <string> #include "params.h" #include "mesh/mesh.h" #include "fem/fem.h" #include "analyse/analyse.h" using namespace std; class TFEM; // Класс, описывающий конечно-элементный объект class TFEMObject { private: int numThread; // Количество потоков, используемых при вычислениях string fileName; // Имя файла с данными string objName; // Имя объекта bool isProcessStarted; // Признак того, что процесс запущен bool isProcessCalculated; // ... успешно завершен list<string> notes; // Вспомогательная информация по решению задачи TFEMParams params; // Параметры решения задачи TResults results; // Результаты расчета TFEM *fem; // Реализация МКЭ TMesh mesh; // КЭ сетка template<typename SOLVER> TFEM *createProblem(void); // Создание задачи с заданным решателем public: TFEMObject(void) { fem = nullptr; isProcessStarted = isProcessCalculated = false; numThread = thread::hardware_concurrency() - 1; } ~TFEMObject(void) { clear(); } void clear(void); void setProcessCalculated(bool p) { isProcessCalculated = p; } bool setMeshFile(string); TFEMParams& getParams(void) { return params; } TMesh& getMesh(void) { return mesh; } bool isCalculated(void) { return isProcessCalculated; } bool isStarted(void) { return isProcessStarted; } void stop(void) { if (fem) fem->breakProcess(); } void setTaskParam(FEMType); bool start(void); list<string>& getNotes(void) { return notes; } TResults& getResult(void) { return results; } TResult& getResult(unsigned i) { return results[i]; } FEType getFEType(void) { return mesh.getTypeFE(); } bool saveResult(string); bool loadResult(string); void printResult(string); void setFileName(string n) { cout << endl << n << endl; fileName = n; objName = n.substr(n.find_last_of("/\\") + 1,n.find_last_of(".") - n.find_last_of("/\\") - 1); } string getFileName(void) { return fileName; } string getObjectName(void) { return objName; } void setT0(unsigned p) { params.t0 = p; } void setT1(unsigned p) { params.t1 = p; } void setTh(unsigned p) { params.th = p; } void setEps(double p) { params.eps = p; } void setWidth(int p) { params.width = p; } void setPrecision(int p) { params.precision = p; } void setLoadStep(double p) { params.loadStep = p; } // Толщина void addThickness(double v, string p) { params.plist.addThickness(v, p); } void addThickness(double v) { params.plist.addThickness(v, ""); } void addThickness(string e, string p) { params.plist.addThickness(e, p); } void addThickness(string e) { params.plist.addThickness(e, ""); } void addThickness(double v, function<double (double, double, double, double)> p) { params.plist.addThickness(v, p); } void addThickness(function<double (double, double, double, double)> e, function<double (double, double, double, double)> p) { params.plist.addThickness(e, p); } void addThickness(function<double (double, double, double, double)> e) { params.plist.addThickness(e, nullptr); } // Температура void addTemperature(double v, string p) { params.plist.addTemperature(v, p); } void addTemperature(double v) { params.plist.addTemperature(v, ""); } void addTemperature(string e, string p) { params.plist.addTemperature(e, p); } void addTemperature(string e) { params.plist.addTemperature(e, ""); } void addTemperature(double v, function<double (double, double, double, double)> p) { params.plist.addTemperature(v, p); } void addTemperature(function<double (double, double, double, double)> e, function<double (double, double, double, double)> p) { params.plist.addTemperature(e, p); } void addTemperature(function<double (double, double, double, double)> e) { params.plist.addTemperature(e, nullptr); } // Альфа void addAlpha(double v, string p) { params.plist.addAlpha(v, p); } void addAlpha(double v) { params.plist.addAlpha(v, ""); } void addAlpha(string e, string p) { params.plist.addAlpha(e, p); } void addAlpha(string e) { params.plist.addAlpha(e, ""); } void addAlpha(double v, function<double (double, double, double, double)> p) { params.plist.addAlpha(v, p); } void addAlpha(function<double (double, double, double, double)> e, function<double (double, double, double, double)> p) { params.plist.addAlpha(e, p); } void addAlpha(function<double (double, double, double, double)> e) { params.plist.addAlpha(e, nullptr); } // Плотность void addDensity(double v, string p) { params.plist.addDensity(v, p); } void addDensity(double v) { params.plist.addDensity(v, ""); } void addDensity(string e, string p) { params.plist.addDensity(e, p); } void addDensity(string e) { params.plist.addDensity(e, ""); } void addDensity(double v, function<double (double, double, double, double)> p) { params.plist.addDensity(v, p); } void addDensity(function<double (double, double, double, double)> e, function<double (double, double, double, double)> p) { params.plist.addDensity(e, p); } void addDensity(function<double (double, double, double, double)> e) { params.plist.addDensity(e, nullptr); } // Параметр демпфирования void addDamping(double v, string p) { params.plist.addDamping(v, p); } void addDamping(double v) { params.plist.addDamping(v, ""); } void addDamping(string e, string p) { params.plist.addDamping(e, p); } void addDamping(string e) { params.plist.addDamping(e, ""); } void addDamping(double v, function<double (double, double, double, double)> p) { params.plist.addDamping(v, p); } void addDamping(function<double (double, double, double, double)> e, function<double (double, double, double, double)> p) { params.plist.addDamping(e, p); } void addDamping(function<double (double, double, double, double)> e) { params.plist.addDamping(e, nullptr); } // Модуль Юнга void addYoungModulus(double v, string p) { params.plist.addYoungModulus(v, p); } void addYoungModulus(double v) { params.plist.addYoungModulus(v, ""); } void addYoungModulus(string e, string p) { params.plist.addYoungModulus(e, p); } void addYoungModulus(string e) { params.plist.addYoungModulus(e, ""); } void addYoungModulus(double v, function<double (double, double, double, double)> p) { params.plist.addYoungModulus(v, p); } void addYoungModulus(function<double (double, double, double, double)> e, function<double (double, double, double, double)> p) { params.plist.addYoungModulus(e, p); } void addYoungModulus(function<double (double, double, double, double)> e) { params.plist.addYoungModulus(e, nullptr); } // Коэффициент Пуассона void addPoissonRatio(double v, string p) { params.plist.addPoissonRatio(v, p); } void addPoissonRatio(double v) { params.plist.addPoissonRatio(v, ""); } void addPoissonRatio(string e, string p) { params.plist.addPoissonRatio(e, p); } void addPoissonRatio(string e) { params.plist.addPoissonRatio(e, ""); } void addPoissonRatio(function<double (double, double, double, double)> e, function<double (double, double, double, double)> p) { params.plist.addPoissonRatio(e, p); } void addPoissonRatio(double v, function<double (double, double, double, double)> p) { params.plist.addPoissonRatio(v, p); } void addPoissonRatio(function<double (double, double, double, double)> e) { params.plist.addPoissonRatio(e, nullptr); } // Граничные условия void addBoundaryCondition(Direction dir, double v, string p) { params.plist.addBoundaryCondition(v, p, dir); } void addBoundaryCondition(Direction dir, string e, string p) { params.plist.addBoundaryCondition(e, p, dir); } void addBoundaryCondition(Direction dir, double v, function<double (double, double, double, double)> p) { params.plist.addBoundaryCondition(v, p, dir); } void addBoundaryCondition(Direction dir, function<double (double, double, double, double)> e, function<double (double, double, double, double)> p) { params.plist.addBoundaryCondition(e, p, dir); } // Начальные условия void addInitialCondition(InitialCondition ic, double v) { params.plist.addInitialCondition(v, ic); } void addInitialCondition(InitialCondition ic, string e) { params.plist.addInitialCondition(e, ic); } void addInitialCondition(InitialCondition ic, function<double (double, double, double, double)> e) { params.plist.addInitialCondition(e, ic); } // Сосредоточенная нагрузка void addConcentratedLoad(Direction dir, double v, string p) { params.plist.addConcentratedLoad(v, p, dir); } void addConcentratedLoad(Direction dir, double v) { params.plist.addConcentratedLoad(v, "", dir); } void addConcentratedLoad(Direction dir, string e, string p) { params.plist.addConcentratedLoad(e, p, dir); } void addConcentratedLoad(Direction dir, string e) { params.plist.addConcentratedLoad(e, "", dir); } void addConcentratedLoad(Direction dir, function<double (double, double, double, double)> e, function<double (double, double, double, double)> p) { params.plist.addConcentratedLoad(e, p, dir); } void addConcentratedLoad(Direction dir, double v, function<double (double, double, double, double)> p) { params.plist.addConcentratedLoad(v, p, dir); } void addConcentratedLoad(Direction dir, function<double (double, double, double, double)> e) { params.plist.addConcentratedLoad(e, nullptr, dir); } // Объемная нагрузка void addVolumeLoad(Direction dir, double v, string p) { params.plist.addVolumeLoad(v, p, dir); } void addVolumeLoad(Direction dir, double v) { params.plist.addVolumeLoad(v, "", dir); } void addVolumeLoad(Direction dir, string e, string p) { params.plist.addVolumeLoad(e, p, dir); } void addVolumeLoad(Direction dir, string e) { params.plist.addVolumeLoad(e, "", dir); } void addVolumeLoad(Direction dir, function<double (double, double, double, double)> e, function<double (double, double, double, double)> p) { params.plist.addVolumeLoad(e, p, dir); } void addVolumeLoad(Direction dir, double v, function<double (double, double, double, double)> p) { params.plist.addVolumeLoad(v, p, dir); } void addVolumeLoad(Direction dir, function<double (double, double, double, double)> e) { params.plist.addVolumeLoad(e, nullptr, dir); } // Поверхностная нагрузка void addSurfaceLoad(Direction dir, double v, string p) { params.plist.addSurfaceLoad(v, p, dir); } void addSurfaceLoad(Direction dir, double v) { params.plist.addSurfaceLoad(v, "", dir); } void addSurfaceLoad(Direction dir, string e, string p) { params.plist.addSurfaceLoad(e, p, dir); } void addSurfaceLoad(Direction dir, string e) { params.plist.addSurfaceLoad(e, "", dir); } void addSurfaceLoad(Direction dir, double v, function<double (double, double, double, double)> p) { params.plist.addSurfaceLoad(v, p, dir); } void addSurfaceLoad(Direction dir, function<double (double, double, double, double)> e, function<double (double, double, double, double)> p) { params.plist.addSurfaceLoad(e, p, dir); } void addSurfaceLoad(Direction dir, function<double (double, double, double, double)> e) { params.plist.addSurfaceLoad(e, nullptr, dir); } // Давление void addPressureLoad(double v, string p) { params.plist.addPressureLoad(v, p); } void addPressureLoad(double v) { params.plist.addPressureLoad(v, ""); } void addPressureLoad(string e, string p) { params.plist.addPressureLoad(e, p); } void addPressureLoad(string e) { params.plist.addPressureLoad(e, ""); } void addPressureLoad(double v, function<double (double, double, double, double)> p) { params.plist.addPressureLoad(v, p); } void addPressureLoad(function<double (double, double, double, double)> e, function<double (double, double, double, double)> p) { params.plist.addPressureLoad(e, p); } void addPressureLoad(function<double (double, double, double, double)> e) { params.plist.addPressureLoad(e, nullptr); } void addVariable(string name, double val) { params.variables[name] = val; } // Диаграмма деформирования void addStressStrainCurve(matrix<double> &ssc, function<double (double, double, double, double)> p) { params.plist.addStressStrainCurve(ssc, p); } void addStressStrainCurve(matrix<double> &ssc, string p) { params.plist.addStressStrainCurve(ssc, p); } void addStressStrainCurve(matrix<double> &ssc) { params.plist.addStressStrainCurve(ssc, ""); } void setFunName(vector<string>& fn) { params.names = fn; } void setPlasticityMethod(PlasticityMethod p) { params.pMethod = p; } void setNumThread(int n) { numThread = n; } void setLanguage(int); string stdTxtResName(void) { return getFileName().substr(0, getFileName().find_last_of(".")) + ".txt"; } string stdResName(void) { return getFileName().substr(0, getFileName().find_last_of(".")) + ".res"; } }; #endif // OBJECT_H
e86f8e3445dd4c06bcf2948522edaa2e313c947c
7106724c5de461d5156bc13d48b31cff6b22113a
/modules/StageInterface/src/StageManager.h
7bfabbde392bc57184470caa743e415204efc6ea
[]
no_license
YCP-Swarm-Robotics-Capstone-2020-2021/SRCSim
c76d9a4e5a6ded200d83da1b887c0f20371d4042
9710b22b9e42f63e48ed20eabdedd7569ce6afd6
refs/heads/master
2023-04-20T23:54:50.820904
2021-04-30T12:40:01
2021-04-30T12:40:01
269,135,291
0
0
null
2021-04-30T12:40:02
2020-06-03T16:11:12
C++
UTF-8
C++
false
false
1,906
h
StageManager.h
#ifndef STAGEMANAGER_H #define STAGEMANAGER_H #ifndef PI #define PI 3.141592653589 #endif #include <QObject> #include <QString> #include <QThread> #include <map> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sstream> #include <iostream> #include <cmath> #include <thread> #include <QTimer> #include "global.h" #define ROBOT_IDENTIFIER "Dolphin" static const int BLACK_LINE_LOCATION = 16; using namespace Stg; class StageRun : public QObject { Q_OBJECT public: StageRun(int num_bots); ~StageRun(); void Tick(World *); void connectStage(World *world); void setNumBots(int bots){num_bots = bots;} static int Callback(World *world, void *userarg) { StageRun *stageRun = reinterpret_cast<StageRun*>(userarg); stageRun->Tick(world); // never remove this call-back return 0; } signals: void updatePose(int idx, double x, double y); protected: private: Robot *robots; int num_bots; QObject *parent; public slots: friend class StageManager; }; class StageManager : public QThread { Q_OBJECT public: StageManager(QObject * parent = nullptr); ~StageManager(); void run() override; void setWorldFile(QString file){world_file = file;} void setNumBots(int bots){num_bots = bots;} StageRun *stageRun; protected: bool runStarted; public slots: void getNumBots(int bots){ num_bots = bots; } void getWorldFile(QString world_file){ this->world_file = world_file; } void getMotion(int idx, double xSpeed, double turnSpeed){ if(runStarted){ stageRun->robots[idx].forward_speed = xSpeed; stageRun->robots[idx].turn_speed = turnSpeed; } } void startManager(){ this->start(); } private: Stg::WorldGui *world; QString world_file; int num_bots; }; #endif // STAGEMANAGER_H
0a97616942bb5f1785adc03e7e025f49db411e1c
93b7d137f0ae9b0c29b41d3139315478d084278d
/STUDY/introc++/9/9/Vector2.cpp
084ef52b7d4b88055f7168d56f966c4399e1af3c
[]
no_license
tsuyopon/cpp
c32643c837ac0665395cc2ed0a4ac8b8e90dc750
96ee23a65f0fcaa5b68c376064f8ba9771d1b103
refs/heads/master
2023-05-01T10:05:20.716354
2023-04-13T19:04:52
2023-04-13T19:04:52
7,288,806
1
0
null
null
null
null
UTF-8
C++
false
false
305
cpp
Vector2.cpp
#include <iostream> #include <vector> using namespace std; void Show(const int* array, int size){ for(int i = 0; i < size; ++i){ cout << array[i] << ' '; } cout << endl; } int main(){ vector<int> v(5); for(int i = 0, size = v.size(); i < size; ++i){ v[i] = i * i; } Show(&v[0], v.size()); }
1c35bece79b4e1b68e44f5d6d72cc1e88ba7be60
4f8f3243554bba62e8e2996aa2d97967e08da1b7
/CodeChefDsaLearning/Complexity/Factorial.cpp
1fef8c5ace52d6d92886daa3017dd0b5e652e710
[]
no_license
singhsiddharth10/CodeChefDsaLearning
83e5974c3d7a316ce1c0c09d9219ce836ffdb5d5
2144313379bb595d5f39b2c3dec1175f11634a73
refs/heads/master
2023-04-14T13:39:04.672270
2021-04-15T11:12:02
2021-04-15T11:12:02
358,229,936
0
0
null
null
null
null
UTF-8
C++
false
false
2,351
cpp
Factorial.cpp
//The most important part of a GSM network is so called Base Transceiver Station (BTS). //These transceivers form the areas called cells (this term gave the name to the cellular phone) //and every phone connects to the BTS with the strongest signal (in a little simplified view). //Of course, BTSes need some attention and technicians need to check their function periodically. //The technicians faced a very interesting problem recently. Given a set of BTSes to visit, //they needed to find the shortest path to visit all of the given points and return back to the central company building. //Programmers have spent several months studying this problem but with no results. They were unable to find the solution fast enough. //After a long time, one of the programmers found this problem in a conference article. //Unfortunately, he found that the problem is so called "Traveling Salesman Problem" and it is very hard to solve. If we have N BTSes to be visited, //we can visit them in any order, giving us N! possibilities to examine. The function expressing that number is called factorial and can be computed as a product //1.2.3.4....N. The number is very high even for a relatively small N. //The programmers understood they had no chance to solve the problem. //But because they have already received the research grant from the government, they needed to continue with their studies and produce at least some results. //So they started to study behavior of the factorial function. //For example, they defined the function Z. For any positive integer N, Z(N) is the number of zeros at the end of the decimal form of number N!. //They noticed that this function never decreases. If we have two numbers N1<N2, then Z(N1) <= Z(N2). //It is because we can never "lose" any trailing zero by multiplying by any positive number. //We can only get new and new zeros. The function Z is very interesting, so we need a computer program that can determine its value efficiently. #include <bits/stdc++.h> using namespace std; long long int findTrailingZeros(long long int n) { long long int count = 0; for (int i = 5; n / i >= 1; i *= 5) count += n / i; return count; } int main() { long long int t; cin>>t; while(t--){ long long int n; cin>>n; cout <<findTrailingZeros(n)<<"\n"; } return 0; }
2a563e45719b2370bd43ef34df1187e9869f7388
8cc87a7be8bc158c09003bf558f0fa7bd3c7f3f7
/LZL.1/Data_structure/I.cpp
27ff61d91ff4e721cb9caf3029ff7ea22924b6a3
[]
no_license
Super-long/Summer-of-2019
1da0399e728a1e070c5da1a4eb2ed5e9e5d2f704
e92682543cdb25a37aebdabeb1354bffb92ed3df
refs/heads/master
2020-07-30T13:06:10.625018
2019-09-23T02:03:56
2019-09-23T02:03:56
210,244,869
2
0
null
null
null
null
UTF-8
C++
false
false
1,326
cpp
I.cpp
#include<iostream> #include<algorithm> #include<cstdio> #define lson (q<<1) #define rson (q<<1|1) #define mid ((l+r)>>1) using namespace std; int m,n,q; int book[200000+10]; int tmpa,tmpb; char tmpc[10]; int segt[200010<<2]; void build(int q,int l,int r) { if(l==r){ segt[q]=book[l]; return; } int m=mid; build(lson,l,m); build(rson,m+1,r); segt[q]=max(segt[lson],segt[rson]); } void update(int q,int l,int r,int number,int k) { if(l==r) { segt[q]=k; return; } int m=mid; if(number<=m) update(lson,l,m,number,k); if(number>m) update(rson,m+1,r,number,k); segt[q]=max(segt[lson],segt[rson]); } int query(int q,int l,int r,int a,int b) { if(l>=a && r<=b) { return segt[q]; } int m=mid; int MAX=0; if(a<=m) MAX=max(query(lson,l,m,a,b),MAX); if(b>m) MAX=max(query(rson,m+1,r,a,b),MAX); return MAX; } int main() { while(~scanf("%d %d",&m,&n)) { for(int i=1;i<=m;i++) { scanf("%d",&book[i]); } build(1,1,m); while(n--) { scanf("%s %d %d",tmpc,&tmpa,&tmpb); if(tmpc[0]=='Q') printf("%d\n",query(1,1,m,tmpa,tmpb)); else update(1,1,m,tmpa,tmpb); } } return 0; }
7da809ea0551a4fb636404b8056efd38f6380977
3e1a626e043bd7471ebdc21939204f337079e57d
/src/cryptopp/pkcspad.cpp
a45751ff993f64cfa63269fcfb8b2b9d7c53a52d
[ "MIT", "GPL-3.0-only", "LicenseRef-scancode-unknown-license-reference", "BSL-1.0", "LicenseRef-scancode-public-domain" ]
permissive
qtumproject/qtum
834cd8d1df04c779ed8fec2d26627e97644f5275
88fd52d40026f4705b63889cdd4b4c86375ddaf8
refs/heads/master
2023-09-05T00:27:23.149231
2023-09-01T22:35:32
2023-09-01T22:35:32
83,774,906
1,468
631
MIT
2023-09-01T22:35:35
2017-03-03T08:17:11
C++
UTF-8
C++
false
false
6,768
cpp
pkcspad.cpp
// pkcspad.cpp - written and placed in the public domain by Wei Dai #include "pch.h" #ifndef CRYPTOPP_PKCSPAD_CPP // SunCC workaround: compiler could cause this file to be included twice #define CRYPTOPP_PKCSPAD_CPP #include "pkcspad.h" #include "emsa2.h" #include "misc.h" #include "trap.h" NAMESPACE_BEGIN(CryptoPP) // More in dll.cpp. Typedef/cast change due to Clang, http://github.com/weidai11/cryptopp/issues/300 template<> const byte PKCS_DigestDecoration<Weak1::MD2>::decoration[] = {0x30,0x20,0x30,0x0c,0x06,0x08,0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x02,0x05,0x00,0x04,0x10}; template<> const unsigned int PKCS_DigestDecoration<Weak1::MD2>::length = (unsigned int)sizeof(PKCS_DigestDecoration<Weak1::MD2>::decoration); template<> const byte PKCS_DigestDecoration<Weak1::MD5>::decoration[] = {0x30,0x20,0x30,0x0c,0x06,0x08,0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x05,0x05,0x00,0x04,0x10}; template<> const unsigned int PKCS_DigestDecoration<Weak1::MD5>::length = (unsigned int)sizeof(PKCS_DigestDecoration<Weak1::MD5>::decoration); template<> const byte PKCS_DigestDecoration<RIPEMD160>::decoration[] = {0x30,0x21,0x30,0x09,0x06,0x05,0x2b,0x24,0x03,0x02,0x01,0x05,0x00,0x04,0x14}; template<> const unsigned int PKCS_DigestDecoration<RIPEMD160>::length = (unsigned int)sizeof(PKCS_DigestDecoration<RIPEMD160>::decoration); template<> const byte PKCS_DigestDecoration<Tiger>::decoration[] = {0x30,0x29,0x30,0x0D,0x06,0x09,0x2B,0x06,0x01,0x04,0x01,0xDA,0x47,0x0C,0x02,0x05,0x00,0x04,0x18}; template<> const unsigned int PKCS_DigestDecoration<Tiger>::length = (unsigned int)sizeof(PKCS_DigestDecoration<Tiger>::decoration); // Inclusion based on DLL due to Clang, http://github.com/weidai11/cryptopp/issues/300 #ifndef CRYPTOPP_IS_DLL template<> const byte PKCS_DigestDecoration<SHA1>::decoration[] = {0x30,0x21,0x30,0x09,0x06,0x05,0x2B,0x0E,0x03,0x02,0x1A,0x05,0x00,0x04,0x14}; template<> const unsigned int PKCS_DigestDecoration<SHA1>::length = (unsigned int)sizeof(PKCS_DigestDecoration<SHA1>::decoration); template<> const byte PKCS_DigestDecoration<SHA224>::decoration[] = {0x30,0x2d,0x30,0x0d,0x06,0x09,0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x04,0x05,0x00,0x04,0x1c}; template<> const unsigned int PKCS_DigestDecoration<SHA224>::length = (unsigned int)sizeof(PKCS_DigestDecoration<SHA224>::decoration); template<> const byte PKCS_DigestDecoration<SHA256>::decoration[] = {0x30,0x31,0x30,0x0d,0x06,0x09,0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x01,0x05,0x00,0x04,0x20}; template<> const unsigned int PKCS_DigestDecoration<SHA256>::length = (unsigned int)sizeof(PKCS_DigestDecoration<SHA256>::decoration); template<> const byte PKCS_DigestDecoration<SHA384>::decoration[] = {0x30,0x41,0x30,0x0d,0x06,0x09,0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x02,0x05,0x00,0x04,0x30}; template<> const unsigned int PKCS_DigestDecoration<SHA384>::length = (unsigned int)sizeof(PKCS_DigestDecoration<SHA384>::decoration); template<> const byte PKCS_DigestDecoration<SHA512>::decoration[] = {0x30,0x51,0x30,0x0d,0x06,0x09,0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x03,0x05,0x00,0x04,0x40}; template<> const unsigned int PKCS_DigestDecoration<SHA512>::length = (unsigned int)sizeof(PKCS_DigestDecoration<SHA512>::decoration); template<> const byte EMSA2HashId<SHA1>::id = 0x33; template<> const byte EMSA2HashId<SHA224>::id = 0x38; template<> const byte EMSA2HashId<SHA256>::id = 0x34; template<> const byte EMSA2HashId<SHA384>::id = 0x36; template<> const byte EMSA2HashId<SHA512>::id = 0x35; #endif size_t PKCS_EncryptionPaddingScheme::MaxUnpaddedLength(size_t paddedLength) const { return SaturatingSubtract(paddedLength/8, 10U); } void PKCS_EncryptionPaddingScheme::Pad(RandomNumberGenerator& rng, const byte *input, size_t inputLen, byte *pkcsBlock, size_t pkcsBlockLen, const NameValuePairs& parameters) const { CRYPTOPP_UNUSED(parameters); CRYPTOPP_ASSERT (inputLen <= MaxUnpaddedLength(pkcsBlockLen)); // this should be checked by caller // convert from bit length to byte length if (pkcsBlockLen % 8 != 0) { pkcsBlock[0] = 0; pkcsBlock++; } pkcsBlockLen /= 8; pkcsBlock[0] = 2; // block type 2 // pad with non-zero random bytes for (unsigned i = 1; i < pkcsBlockLen-inputLen-1; i++) pkcsBlock[i] = (byte)rng.GenerateWord32(1, 0xff); pkcsBlock[pkcsBlockLen-inputLen-1] = 0; // separator memcpy(pkcsBlock+pkcsBlockLen-inputLen, input, inputLen); } DecodingResult PKCS_EncryptionPaddingScheme::Unpad(const byte *pkcsBlock, size_t pkcsBlockLen, byte *output, const NameValuePairs& parameters) const { CRYPTOPP_UNUSED(parameters); bool invalid = false; size_t maxOutputLen = MaxUnpaddedLength(pkcsBlockLen); // convert from bit length to byte length if (pkcsBlockLen % 8 != 0) { invalid = (pkcsBlock[0] != 0) || invalid; pkcsBlock++; } pkcsBlockLen /= 8; // Require block type 2. invalid = (pkcsBlock[0] != 2) || invalid; // skip past the padding until we find the separator size_t i=1; while (i<pkcsBlockLen && pkcsBlock[i++]) { // null body } CRYPTOPP_ASSERT(i==pkcsBlockLen || pkcsBlock[i-1]==0); size_t outputLen = pkcsBlockLen - i; invalid = (outputLen > maxOutputLen) || invalid; if (invalid) return DecodingResult(); memcpy (output, pkcsBlock+i, outputLen); return DecodingResult(outputLen); } // ******************************************************** #ifndef CRYPTOPP_IMPORTS void PKCS1v15_SignatureMessageEncodingMethod::ComputeMessageRepresentative(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength, HashTransformation &hash, HashIdentifier hashIdentifier, bool messageEmpty, byte *representative, size_t representativeBitLength) const { CRYPTOPP_UNUSED(rng), CRYPTOPP_UNUSED(recoverableMessage), CRYPTOPP_UNUSED(recoverableMessageLength); CRYPTOPP_UNUSED(messageEmpty), CRYPTOPP_UNUSED(hashIdentifier); CRYPTOPP_ASSERT(representativeBitLength >= MinRepresentativeBitLength(hashIdentifier.second, hash.DigestSize())); size_t pkcsBlockLen = representativeBitLength; // convert from bit length to byte length if (pkcsBlockLen % 8 != 0) { representative[0] = 0; representative++; } pkcsBlockLen /= 8; representative[0] = 1; // block type 1 unsigned int digestSize = hash.DigestSize(); byte *pPadding = representative + 1; byte *pDigest = representative + pkcsBlockLen - digestSize; byte *pHashId = pDigest - hashIdentifier.second; byte *pSeparator = pHashId - 1; // pad with 0xff memset(pPadding, 0xff, pSeparator-pPadding); *pSeparator = 0; memcpy(pHashId, hashIdentifier.first, hashIdentifier.second); hash.Final(pDigest); } #endif NAMESPACE_END #endif
d7b7fea87e168e7c23d9eec52fb5dcfa85bb664f
c6f69ac70fbfe5380d691e35a818a6e8eaf6e914
/src/translation_warp.cpp
88435f4d33e89a130aa383ff12fcafedbd05b1b1
[]
no_license
jvlmdr/non-rigid-tracking
00e9d116410628da2d4f5153439167f5a34c55a1
ee0377e3a324b4e82ee0fc2eee0fbcfe7ec062a1
refs/heads/master
2020-04-15T16:27:25.755272
2013-03-13T05:45:28
2013-03-13T05:45:28
6,432,545
5
3
null
null
null
null
UTF-8
C++
false
false
1,552
cpp
translation_warp.cpp
#include "translation_warp.hpp" TranslationWarp::TranslationWarp(double x, double y, const TranslationWarper& warper) : params_(NUM_PARAMS, 0.), warper_(&warper) { params_[0] = x; params_[1] = y; } TranslationWarp::TranslationWarp() : params_(NUM_PARAMS, 0.), warper_(NULL) {} TranslationWarp::~TranslationWarp() {} int TranslationWarp::numParams() const { return warper_->numParams(); } cv::Point2d TranslationWarp::evaluate(const cv::Point2d& position, double* jacobian) const { return warper_->evaluate(position, params(), jacobian); } cv::Mat TranslationWarp::matrix() const { return warper_->matrix(params()); } bool TranslationWarp::isValid(const cv::Size& image_size, int radius) const { return warper_->isValid(params(), image_size, radius); } void TranslationWarp::draw(cv::Mat& image, int radius, const cv::Scalar& color, int thickness) const { double x = params_[0]; double y = params_[1]; cv::Point center(std::floor(x + 0.5), std::floor(y + 0.5)); cv::Point offset(radius, radius); cv::Point pt1 = center - offset; cv::Point pt2 = center + offset; cv::rectangle(image, pt1, pt2, color, thickness); } double* TranslationWarp::params() { return &params_.front(); } const double* TranslationWarp::params() const { return &params_.front(); } const Warper* TranslationWarp::warper() const { return warper_; }
aaaf3a47990b0a9458036270b1a173d4699c537d
7d2f42661aabcb1b0d5e842063a89a78a228a048
/src/Time/IsoDateTimeFormat.hxx
470ed99785f4890e1dc06b7965ab36e39a8f9b80
[ "ISC" ]
permissive
def-/sxc
71bd92dc437d43681b653c376b948fda46602240
1dfd275d33931e02b81e65fde3b67bf6578cde63
refs/heads/master
2020-04-25T07:00:39.160603
2009-07-14T07:14:47
2009-07-14T07:14:47
29,000,659
0
0
null
null
null
null
UTF-8
C++
false
false
2,590
hxx
IsoDateTimeFormat.hxx
// LICENSE/*{{{*/ /* sxc - Simple Xmpp Client Copyright (C) 2008 Dennis Felsing, Andreas Waidler Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /*}}}*/ #ifndef ISODATETIMEFORMAT_HXX #define ISODATETIMEFORMAT_HXX // INCLUDES/*{{{*/ #include <string> #include "DateTimeFormat.hxx" /*}}}*/ namespace Time { /** * @brief Formatter according to the ISO 8601 standard. */ class IsoDateTimeFormat : public DateTimeFormat { public: // static const unsigned short FORMAT_DATE = 0x1;/*{{{*/ /// Bitmask value to enable formatting of the date. static const unsigned short FORMAT_DATE = 0x1; /*}}}*/ // static const unsigned short FORMAT_SECONDS = 0x2;/*{{{*/ /// Bitmask value to enable formatting of the seconds. static const unsigned short FORMAT_SECONDS = 0x2; /*}}}*/ // IsoDateTimeFormat(const DateTime*, unsigned short);/*{{{*/ /** * @brief Constructs this object. * * Directly formats the passed date which then can be obtained by calling * string(). * * @param dateTime The date and time to represent. * @param formatOptions Bitmask which parts of the DateTime to format. */ IsoDateTimeFormat(const DateTime *dateTime, unsigned short formatOptions=(FORMAT_DATE | FORMAT_SECONDS)); /*}}}*/ // ~IsoDateTimeFormat();/*{{{*/ /** * @brief Nonvirtual destructor. Do not inherit. */ ~IsoDateTimeFormat(); /*}}}*/ private: // std::string format(const std::string &format, unsigned int length=50);/*{{{*/ /// Make format() private so that the date can not be re-formatted. std::string format(const std::string &format, unsigned int length=50); /*}}}*/ }; } #endif // ISODATETIMEFORMAT_HXX // Use no tabs at all; two spaces indentation; max. eighty chars per line. // vim: et ts=2 sw=2 sts=2 tw=80 fdm=marker
34afed3fc040e17175e35a20786390af1a10bf75
9ecbc437bd1db137d8f6e83b7b4173eb328f60a9
/gcc-build/i686-pc-linux-gnu/libjava/gnu/gcj/runtime/NameFinder.h
735b640ccccc91f0ece5224ceedd6c3d8cdc3524
[]
no_license
giraffe/jrate
7eabe07e79e7633caae6522e9b78c975e7515fe9
764bbf973d1de4e38f93ba9b9c7be566f1541e16
refs/heads/master
2021-01-10T18:25:37.819466
2013-07-20T12:28:23
2013-07-20T12:28:23
11,545,290
1
0
null
null
null
null
UTF-8
C++
false
false
2,287
h
NameFinder.h
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*- #ifndef __gnu_gcj_runtime_NameFinder__ #define __gnu_gcj_runtime_NameFinder__ #pragma interface #include <java/lang/Object.h> #include <gcj/array.h> extern "Java" { namespace gnu { namespace gcj { namespace runtime { class NameFinder; } class RawData; } } }; class ::gnu::gcj::runtime::NameFinder : public ::java::lang::Object { public: NameFinder (); private: static ::java::lang::String *getExecutable (); ::java::lang::StackTraceElement *dladdrLookup (::java::lang::Throwable *, ::gnu::gcj::RawData *, jint); ::java::lang::String *getAddrAsString (::gnu::gcj::RawData *, jint); ::java::lang::String *getExternalLabel (::java::lang::String *); ::java::lang::StackTraceElement *lookupInterp (::java::lang::Throwable *, ::gnu::gcj::RawData *, jint); ::java::lang::StackTraceElement *lookup0 (::java::lang::Throwable *, ::gnu::gcj::RawData *, jint); public: virtual JArray< ::java::lang::StackTraceElement *> *lookup (::java::lang::Throwable *, ::gnu::gcj::RawData *, jint); private: static JArray< ::java::lang::StackTraceElement *> *sanitizeStack (JArray< ::java::lang::StackTraceElement *> *, ::java::lang::Throwable *); ::java::lang::StackTraceElement *createStackTraceElement (::java::lang::Throwable *, ::java::lang::String *, ::java::lang::String *); ::java::lang::String *demangleName (::java::lang::String *); public: static ::java::lang::String *demangleInterpreterMethod (::java::lang::String *, ::java::lang::String *); virtual void close (); public: // actually protected virtual void finalize (); private: static jboolean demangle; static jboolean sanitize; static jboolean remove_unknown; static jboolean remove_interpreter; static jboolean use_addr2line; ::java::lang::String * __attribute__((aligned(__alignof__( ::java::lang::Object )))) executable; ::java::lang::Process *cppfilt; ::java::io::BufferedWriter *cppfiltOut; ::java::io::BufferedReader *cppfiltIn; ::java::lang::Process *addr2line; ::java::io::BufferedWriter *addr2lineOut; ::java::io::BufferedReader *addr2lineIn; jboolean usingAddr2name; public: static ::java::lang::Class class$; }; #endif /* __gnu_gcj_runtime_NameFinder__ */
91ca000210bbdf63a6cf5a18fc72b0160333d2dd
1a8d3e52a0fb2f51b5c2cf54a2a74bcebe85b6cf
/twincat2mqtt.cpp
ca9b6c806ae583f30dec6a0088ac4d686e337cc6
[]
no_license
ilmanzo/Twincat2MQTT
8730d490db3e1aaea2345bc18d5e9793cb640403
f567e141d1e744adab03b61e167f444bfbe46dda
refs/heads/master
2021-01-09T20:56:37.571122
2016-08-02T10:19:02
2016-08-02T10:19:02
64,745,353
1
0
null
null
null
null
UTF-8
C++
false
false
1,601
cpp
twincat2mqtt.cpp
#include <iostream> #include "AdsLib.h" #include "MqClient.h" #include "TwincatVar.h" using namespace std; //returns a port if everything goes well //returns 0 (zero) if error long plc_connect(const AmsNetId& remote_id, const char* ipV4) { // add local route to your EtherCAT Master if (AdsAddRoute(remote_id, ipV4)) { std::cout << "Adding ADS route failed, did you specified valid addresses?\n"; return 0; } // open a new ADS port const long port = AdsPortOpenEx(); if (!port) { std::cout << "Open ADS port failed\n"; return 0; } return port; } bool plc_disconnect(long port) { const long closeStatus = AdsPortCloseEx(port); if (closeStatus) { std::cout << "Close ADS port failed with: " << std::dec << closeStatus << '\n'; return false; } return true; } int main() { const AmsNetId remoteNetId { 192, 168, 0, 231, 1, 1 }; const char remoteIpV4[] = "192.168.0.232"; const char* mqBrokerAddress="127.0.0.1"; const AmsAddr remote { remoteNetId, AMSPORT_R0_PLC_TC3 }; const long port=plc_connect(remoteNetId,remoteIpV4); TwincatVar<bool> miavar("MAIN.Bool1",remote,port); miavar.getValue(); //publish to mqtt broker (example) MqClient mq("test from c++",mqBrokerAddress); std::string message; //main loop : until the user press ENTER do { message=miavar.getValue()?"TRUE":"FALSE"; mq.strpublish("plcvars/Bool1",message); } while (cin.get()!='\n'); mq.disconnect(); plc_disconnect(port); }
2555c42630489eacb7529d0f0cf28b2044682b18
11ef1a773d539bd8f66b3dfdff950dbdc505c363
/game-source-code/Drawer.cpp
041c2e8ce34ca32dac06c378232b99f67d6fcf59
[]
no_license
SelloClinton/centiheritance
5fbbb97a769671ddf2ef33915132ef9e2f31a5b0
1cbee0148e4fd46561231896006d3238b16a4fe5
refs/heads/master
2020-03-30T05:57:36.108054
2018-10-01T20:03:38
2018-10-01T20:03:38
150,830,105
0
0
null
null
null
null
UTF-8
C++
false
false
5,097
cpp
Drawer.cpp
#include "Drawer.h" Drawer::Drawer(shared_ptr<sf::RenderWindow> window): // data_(make_unique<DataBank>()), window_(window) //, // object_sprites_(data_->getSprites()) { if(window_ == nullptr) throw WindowNotCreated(); } void Drawer::drawGameObjects(list<shared_ptr<Entity>>& entities){ // auto numberOfEntities = entities.size(); // auto drawables_loader = make_unique<DrawablesLoader>(entities,numberOfEntities); // auto drawables = drawables_loader->loadDrawables(); // // auto entities_iterator = begin(entities); // auto drawables_iterator = begin(drawables); for(auto& entity:entities){ if(entity->getEntityID() == EntityID::PLAYER){ auto player_drawable = make_shared<LaserDrawable>(EntityID::LASER); shared_ptr<Drawable> drawable = player_drawable; drawable->createDrawable(); // auto drawable = make_shared<Drawable>(entity->getEntityID()); auto[x,y] = entity->position()->getXYPosition(); drawable->setPosition(x,y); window_->draw(*(drawable->getDrawable())); } if (entity->getEntityID() == EntityID::STRONG_MUSHROOM){ auto player_drawable = make_shared<MushroomDrawable>(entity->getEntityID()); shared_ptr<Drawable> drawable = player_drawable; drawable->createDrawable(); // auto drawable = make_shared<Drawable>(entity->getEntityID()); auto[x,y] = entity->position()->getXYPosition(); drawable->setPosition(x,y); window_->draw(*(drawable->getDrawable())); } } // for(auto& entity:entities){ // auto drawable_loader = make_shared<DrawablesLoader>(); // auto drawable = drawable_loader->loadDrawable(entity->getEntityID()); // auto[drawable_x_position,drawable_y_position] = entity->position()->getXYPosition(); // drawable->createDrawable(); // drawable->setPosition(drawable_x_position,drawable_y_position); // window_->draw(*(drawable->getDrawable())); // } // while((entities_iterator != end(entities)&&(drawables_iterator != end(drawables)))){ // (*drawables_iterator)->createDrawable(); // auto[x,y] = (*entities_iterator)->position()->getXYPosition(); // (*drawables_iterator)->setPosition(x,y); //// window_->draw(*((*drawables_iterator)->getDrawable())); // window_->draw(*(*drawables_iterator)->getDrawable()); // // } // for(auto& drawable:drawables){ // drawable->createDrawable(); // window_->draw(*(drawable->getDrawable())); // } } //void Drawer::drawPlayer(shared_ptr<Player> player){ // // auto[x_position,y_position] = player->attribute()->position()->getPosition(); // // auto player_sprite = make_shared<DrawableLoader>(Object::PLAYER); // player_sprite->setPosition(x_position,y_position); // window_->draw(*(player_sprite->getDrawable())); //} //void Drawer::drawCentipede(shared_ptr<Centipede> centipede){ // // auto segments = centipede->getCentipede(); // // for(const auto& segment:segments){ // drawSegment(segment); // } // //} //void Drawer::drawBullets(shared_ptr<Player>player){ // // auto bullets = player->getBullets(); // // for(const auto& bullet:bullets){ // drawBullet(bullet); // } // //} //void Drawer::drawField(shared_ptr<Field> field){ // // auto mushrooms = field->getMushrooms(); // // for(const auto& mushroom:mushrooms){ // drawMushroom(mushroom); // } //} //void Drawer::drawPauseMessage(){ // // sf::Text text; // auto font = data_->getFont(); // text.setFillColor(sf::Color::Green); // text.setFont(font); // text.setCharacterSize(25); // text.setString("GAME PAUSED .... PRESS P TO RESUME"); // text.setPosition(100,250); // window_->draw(text); // // //} //void Drawer::drawGameOverMessage(const string& wonOrLost){ // sf::Text text; // auto font = data_->getFont(); // text.setFont(font); // text.setFillColor(sf::Color::Green); // text.setCharacterSize(25); // if (auto str = "won"; wonOrLost == str) // text.setString("YOU WON!...PRESS ESCAPE TO GO TO MAIN MENU"); // else{ // text.setFillColor(sf::Color::Red); // text.setString("YOU LOST!...PRESS ESCAPE TO GO TO MAIN MENU"); // } // text.setPosition(50,250); // window_->draw(text); // //} //void Drawer::drawSegment(shared_ptr<Segment> segment){ // // auto[x_position,y_position] = segment->attribute()->position()->getPosition(); // auto segment_sprite = make_shared<DrawableLoader>(Object::SEGMENT);//object_sprites_.at(1); // segment_sprite->setPosition(x_position,y_position); // window_->draw(*(segment_sprite->getDrawable())); // //} //void Drawer::drawBullet(shared_ptr<Bullet>bullet){ // auto[x_position,y_position] = bullet->attribute()->position()->getPosition(); // auto bullet_sprite = make_shared<DrawableLoader>(Object::BULLET); // bullet_sprite->setPosition(x_position,y_position); // window_->draw(*(bullet_sprite->getDrawable())); // //} //void Drawer::drawMushroom(shared_ptr<Mushroom> mushroom){ // auto[x_position,y_position] = mushroom->position()->getPosition(); // auto mushroom_sprite = make_shared<DrawableLoader>(Object::MUSHROOM); // mushroom_sprite->setPosition(x_position,y_position); //setPosition(x_position,y_position); // window_->draw(*(mushroom_sprite->getDrawable())); //}
9cf00d89889c14ffa661482b7b0247efd7678a12
1ed244147c7efef5a3d13d28e511a235d7216e1f
/Classes/Ship.cpp
adbc4cc4ff6365f752078b915e5b8d3531f79bb7
[]
no_license
harp07/HumberPhysicsGame
14de9fd0adc34f62736f5016ce981c4bbf8a82e6
e7c3b44248bfba4faac0ff9347dba26d424d6c67
refs/heads/master
2020-04-27T01:47:04.685232
2013-04-18T13:31:04
2013-04-18T13:31:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,437
cpp
Ship.cpp
#include "Ship.h" #define weaponScale 0.01f using namespace cocos2d; Ship::Ship(shipType sType, userType uType,float waterHeight, CCLayer* layer, b2World* m_world){ if(sType == SHIP){ if(uType == PLAYER){ obj = new GameObject("Ship",Globals::globalsInstance()->screenSize().width/4,waterHeight+10,1.0f); obj->spriteInit(layer,GameObject::MIDDLEGROUND); obj->physicsInit(m_world,GameObject::SHAPE_PLIST,GameObject::BODY_DYNAMIC,"Ships.plist"); playerBody = obj->objBody; playerSprite = obj->objSprite; setPlayerType(sType); initWeapon(layer,uType,sType); } else if (uType == ENEMY){ obj = new GameObject("ShipFlipped",Globals::globalsInstance()->screenSize().width/1.5,waterHeight+10,1.0f); obj->spriteInit(layer,GameObject::MIDDLEGROUND); obj->physicsInit(m_world,GameObject::SHAPE_PLIST,GameObject::BODY_DYNAMIC,"Ships.plist"); enemyBody = obj->objBody; enemySprite = obj->objSprite; setEnemyType(sType); initWeapon(layer,uType,sType); } factorX = 4.0; factorY = 6.0; } else if (sType == SUBMARINE){ if(uType == PLAYER){ obj = new GameObject("Submarine",Globals::globalsInstance()->screenSize().width/4,waterHeight-30,1.0f); obj->spriteInit(layer,GameObject::MIDDLEGROUND); obj->physicsInit(m_world,GameObject::SHAPE_PLIST,GameObject::BODY_DYNAMIC,"Ships.plist"); playerBody = obj->objBody; playerSprite = obj->objSprite; setPlayerType(sType); initWeapon(layer,uType,sType); } else if (uType == ENEMY){ obj = new GameObject("SubmarineFlipped",Globals::globalsInstance()->screenSize().width/1.5,waterHeight-30,1.0f); obj->spriteInit(layer,GameObject::MIDDLEGROUND); obj->physicsInit(m_world,GameObject::SHAPE_PLIST,GameObject::BODY_DYNAMIC,"Ships.plist"); enemyBody = obj->objBody; enemySprite = obj->objSprite; setEnemyType(sType); initWeapon(layer,uType,sType); } factorX = 1.8; factorY = 4.0; } } void Ship::initWeapon(CCLayer* layer, userType uType, shipType sType){ if(uType == PLAYER){ if(sType == SUBMARINE){ playerWeapon = new GameObject("ball",playerSprite->getPosition().x+playerSprite->getContentSize().width/2,playerSprite->getPosition().y,weaponScale); playerWeapon->spriteInit(layer,GameObject::MIDDLEGROUND); playerWeapon->physicsInit(Globals::globalsInstance()->getWorld(),GameObject::SHAPE_BOX,GameObject::BODY_DYNAMIC); playerWeapon->objBody->SetActive(false); } else if (sType == SHIP){ playerWeapon = new GameObject("ball",playerSprite->getPosition().x,playerSprite->getPosition().y,weaponScale); playerWeapon->spriteInit(layer,GameObject::MIDDLEGROUND); playerWeapon->physicsInit(Globals::globalsInstance()->getWorld(),GameObject::SHAPE_BOX,GameObject::BODY_DYNAMIC); playerWeapon->objBody->SetActive(false); } } else if (uType == ENEMY){ if(sType == SUBMARINE){ enemyWeapon = new GameObject("ball",enemySprite->getPosition().x-enemySprite->getContentSize().width/2,enemySprite->getPosition().y,weaponScale); enemyWeapon->spriteInit(layer,GameObject::MIDDLEGROUND); enemyWeapon->physicsInit(Globals::globalsInstance()->getWorld(),GameObject::SHAPE_BOX,GameObject::BODY_DYNAMIC); enemyWeapon->objBody->SetActive(false); } else if(sType == SHIP){ enemyWeapon = new GameObject("ball",enemySprite->getPosition().x,enemySprite->getPosition().y,weaponScale); enemyWeapon->spriteInit(layer,GameObject::MIDDLEGROUND); enemyWeapon->physicsInit(Globals::globalsInstance()->getWorld(),GameObject::SHAPE_BOX,GameObject::BODY_DYNAMIC); enemyWeapon->objBody->SetActive(false); } } //obj->objBody->CreateFixture(&obj->objShapeDef); //obj->objBody->CreateFixture(&weapon->objShapeDef); //weapon->objBody->SetGravityScale(0.1f); } float Ship::getFactorX(){ return factorX; } float Ship::getFactorY(){ return factorY; } CCSprite* Ship::getWeaponSprite(userType uType){ if(uType == PLAYER){ return playerWeapon->objSprite; } else if (uType == ENEMY){ return enemyWeapon->objSprite; } } b2Body* Ship::getWeaponBody(userType uType){ if(uType == PLAYER){ return playerWeapon->objBody; } else if (uType == ENEMY){ return enemyWeapon->objBody; } } void Ship::startContact(b2Vec2 location){ //Globals::globalsInstance()->Output(location.x*32); //Globals::globalsInstance()->Output(location.y*32); //explosion(ccp(location.x*32,location.y*32)); if(!Globals::globalsInstance()->getUnitTurn()){ Globals::globalsInstance()->setEnemyHealth(Globals::globalsInstance()->getEnemyHealth()-1); Globals::globalsInstance()->Output(Globals::globalsInstance()->getEnemyHealth()); } else if (Globals::globalsInstance()->getUnitTurn()){ Globals::globalsInstance()->setPlayerHealth(Globals::globalsInstance()->getPlayerHealth()-1); Globals::globalsInstance()->Output(Globals::globalsInstance()->getPlayerHealth()); } //enemyHealth -= 1; //Globals::globalsInstance()->Output(enemyHealth); //Globals::globalsInstance()->Output(1); } void Ship::endContact(){ //Globals::globalsInstance()->Output(2); } void Ship::explosion(CCPoint location){ m_emitter = CCParticleExplosion::create(); m_emitter->retain(); m_emitter->setPosition(location); m_emitter->setSpeed(1.0f); m_emitter->setLife(0.5f); m_emitter->setGravity(ccp(0.0f,-200.0f/PTM_RATIO)); m_emitter->setTotalParticles(5); ccColor4F startColor = {0.0f, 0.0f, 0.0f, 1.0f}; m_emitter->setStartColor(startColor); //ccColor4F startColorVar = {1.0f, 0.1f, 0.1f, 1.0f}; //m_emitter->setStartColorVar(startColorVar); //ccColor4F endColor = {0.1f, 0.1f, 0.1f, 0.2f}; //m_emitter->setEndColor(endColor); //ccColor4F endColorVar = {0.1f, 0.1f, 0.1f, 0.2f}; //m_emitter->setEndColorVar(endColorVar); m_emitter->setTexture( CCTextureCache::sharedTextureCache()->addImage("ball.png")); Globals::globalsInstance()->getLayer()->addChild(m_emitter, GameObject::MIDDLEGROUND); m_emitter->setAutoRemoveOnFinish(true); } void Ship::setPlayerType(shipType sType){ playerS = sType; if(sType == SUBMARINE){ Globals::globalsInstance()->setPlayerHealth(100.0f); } else if (sType == SHIP){ Globals::globalsInstance()->setPlayerHealth(75.0f); } } void Ship::setEnemyType(shipType sType){ enemyS = sType; if(sType == SUBMARINE){ Globals::globalsInstance()->setEnemyHealth(100.0f); } else if (sType == SHIP){ Globals::globalsInstance()->setEnemyHealth(75.0f); } } Ship::shipType Ship::getPlayerType(){ return playerS; } Ship::shipType Ship::getEnemyType(){ return enemyS; }
18f23bebb71f1f0d095565ee37687953d4a7e5a3
bcae155999374a2a0bbf2bb80342f104e8061389
/c++_files/Spring_20_Files/test/Source.cpp
b70dec3049a465a616a85d1214dc0e07c855b372
[]
no_license
JStevens209/consolidated_projects
bd8b97e377076406c61b19d67950efa740197221
6d0e4868f4d585da7258f7e6fd0329a8eab11b50
refs/heads/main
2023-07-11T12:50:59.348385
2021-08-23T15:47:34
2021-08-23T15:47:34
315,665,984
0
0
null
null
null
null
UTF-8
C++
false
false
447
cpp
Source.cpp
/*#include <iostream> using namespace std; class Student { public: string firstName; string lastName; string level; }; int main(int argc, char** argv) { int* ip; Student* sp; Student s; s.firstName = "John"; s.lastName = "Doe"; sp = &s; int intArray[5] = { 2,5,7,9,12 }; ip = intArray; //Arrays are ALWAYS passed by reference cout << ip << " " << *ip << " " << &intArray << endl; return 0; }*/
1d05066c02e6702d6f7df3d814182d1ec47c4efa
09810ef133e6016d9f2d6936e9f6a819aed338fe
/test/test_crybox.cpp
c2c788f6a497827bf44c3e95764a7a00f46b6597
[ "MIT" ]
permissive
dufkan/pb173_project
f3bbb1e2958bfe50d7f844afb3e11e329891116b
9e6277eb25eb79ec1ef6c1c93aa0d44d89422211
refs/heads/master
2020-04-10T10:56:03.634906
2018-05-27T20:13:32
2018-05-27T20:13:32
124,269,935
1
0
null
null
null
null
UTF-8
C++
false
false
12,841
cpp
test_crybox.cpp
#include "../shared/crybox.hpp" #include <numeric> TEST_CASE("IdBox"){ IdBox box; SECTION("empty") { std::vector<uint8_t> data = {}; REQUIRE(box.encrypt(data) == data); REQUIRE(box.decrypt(data) == data); REQUIRE(box.decrypt(box.encrypt(data)) == data); } SECTION("some") { std::vector<uint8_t> data = {'T', 'e', 's', 't', ' ', 0x00, 0x01, 0x02, 0x03, 0x04}; REQUIRE(box.encrypt(data) == data); REQUIRE(box.decrypt(data) == data); REQUIRE(box.decrypt(box.encrypt(data)) == data); } SECTION("a lot") { std::vector<uint8_t> data; data.resize(1024 * 1024); std::iota(data.begin(), data.end(), 0); REQUIRE(box.encrypt(data) == data); REQUIRE(box.decrypt(data) == data); REQUIRE(box.decrypt(box.encrypt(data)) == data); } } TEST_CASE("AESBox"){ std::array<uint8_t, 32> K; std::for_each(K.begin(), K.end(), [](uint8_t x){ return x * x + 1; }); AESBox box{K}; SECTION("empty") { std::vector<uint8_t> data = {}; REQUIRE(box.encrypt(data) == cry::encrypt_aes(data, {}, K)); REQUIRE(box.decrypt(box.encrypt(data)) == cry::decrypt_aes(cry::encrypt_aes(data, {}, K), {}, K)); REQUIRE(box.decrypt(box.encrypt(data)) == data); } SECTION("some") { std::vector<uint8_t> data = {'T', 'e', 's', 't', ' ', 0x00, 0x01, 0x02, 0x03, 0x04}; REQUIRE(box.encrypt(data) == cry::encrypt_aes(data, {}, K)); REQUIRE(box.decrypt(box.encrypt(data)) == cry::decrypt_aes(cry::encrypt_aes(data, {}, K), {}, K)); REQUIRE(box.decrypt(box.encrypt(data)) == data); } SECTION("a lot") { std::vector<uint8_t> data; data.resize(1024 * 1024); std::iota(data.begin(), data.end(), 0); REQUIRE(box.encrypt(data) == cry::encrypt_aes(data, {}, K)); REQUIRE(box.decrypt(box.encrypt(data)) == cry::decrypt_aes(cry::encrypt_aes(data, {}, K), {}, K)); REQUIRE(box.decrypt(box.encrypt(data)) == data); } } TEST_CASE("MACBox"){ std::array<uint8_t, 32> K{}; std::iota(K.begin(), K.end(), 0); MACBox box{K}; std::array<uint8_t, 32> SK = cry::hash_sha(K); SECTION("empty") { std::vector<uint8_t> data = {}; std::vector<uint8_t> macd = data; std::array<uint8_t, 32> mac = cry::mac_data(data, SK); macd.insert(macd.end(), mac.begin(), mac.end()); REQUIRE(box.encrypt(data) == macd); REQUIRE(box.decrypt(macd) == data); REQUIRE(box.decrypt(box.encrypt(data)) == data); macd[0] += 1; REQUIRE_THROWS(box.decrypt(macd)); } SECTION("some") { std::vector<uint8_t> data = {'T', 'e', 's', 't', ' ', 0x00, 0x01, 0x02, 0x03, 0x04}; std::vector<uint8_t> macd = data; std::array<uint8_t, 32> mac = cry::mac_data(data, SK); macd.insert(macd.end(), mac.begin(), mac.end()); REQUIRE(box.encrypt(data) == macd); REQUIRE(box.decrypt(macd) == data); REQUIRE(box.decrypt(box.encrypt(data)) == data); macd[0] += 1; REQUIRE_THROWS(box.decrypt(macd)); } SECTION("a lot") { std::vector<uint8_t> data; data.resize(1024 * 1024); std::iota(data.begin(), data.end(), 0); std::vector<uint8_t> macd = data; std::array<uint8_t, 32> mac = cry::mac_data(data, SK); macd.insert(macd.end(), mac.begin(), mac.end()); REQUIRE(box.encrypt(data) == macd); REQUIRE(box.decrypt(macd) == data); REQUIRE(box.decrypt(box.encrypt(data)) == data); macd[0] += 1; REQUIRE_THROWS(box.decrypt(macd)); } } TEST_CASE("SeqBox single") { std::array<uint8_t, 32> K; std::for_each(K.begin(), K.end(), [](uint8_t x){ return x * x + 1; }); SeqBox box = SeqBox(std::unique_ptr<CryBox>{new AESBox{K}}); AESBox abox{K}; SECTION("empty") { std::vector<uint8_t> data = {}; std::vector<uint8_t> enc = box.encrypt(data); REQUIRE(enc == abox.encrypt(data)); REQUIRE(box.decrypt(enc) == abox.decrypt(enc)); } SECTION("some") { std::vector<uint8_t> data = {'T', 'e', 's', 't', ' ', 0x00, 0x01, 0x02, 0x03, 0x04}; std::vector<uint8_t> enc = box.encrypt(data); REQUIRE(enc == abox.encrypt(data)); REQUIRE(box.decrypt(enc) == abox.decrypt(enc)); } SECTION("a lot") { std::vector<uint8_t> data; data.resize(1024 * 1024); std::iota(data.begin(), data.end(), 0); std::vector<uint8_t> enc = box.encrypt(data); REQUIRE(enc == abox.encrypt(data)); REQUIRE(box.decrypt(enc) == abox.decrypt(enc)); } } TEST_CASE("SeqBox multiple") { std::array<uint8_t, 32> K; std::for_each(K.begin(), K.end(), [](uint8_t x){ return x * x + 1; }); SeqBox box{new IdBox, new MACBox{K}, new AESBox{K}}; AESBox abox{K}; MACBox mbox{K}; SECTION("empty") { std::vector<uint8_t> data = {}; std::vector<uint8_t> enc = box.encrypt(data); REQUIRE(enc == abox.encrypt(mbox.encrypt(data))); REQUIRE(box.decrypt(enc) == mbox.decrypt(abox.decrypt(enc))); } SECTION("some") { std::vector<uint8_t> data = {'T', 'e', 's', 't', ' ', 0x00, 0x01, 0x02, 0x03, 0x04}; std::vector<uint8_t> enc = box.encrypt(data); REQUIRE(enc == abox.encrypt(mbox.encrypt(data))); REQUIRE(box.decrypt(enc) == mbox.decrypt(abox.decrypt(enc))); } SECTION("a lot") { std::vector<uint8_t> data; data.resize(1024 * 1024); std::iota(data.begin(), data.end(), 0); std::vector<uint8_t> enc = box.encrypt(data); REQUIRE(enc == abox.encrypt(mbox.encrypt(data))); REQUIRE(box.decrypt(enc) == mbox.decrypt(abox.decrypt(enc))); } } TEST_CASE("DRBox1", "smaller functions") { std::array<uint8_t, 32> root; cry::ECKey akey; cry::ECKey bkey; akey.gen_pub_key(); bkey.gen_pub_key(); DRBox a{root, bkey.get_bin_q()}; DRBox b{root, bkey}; SECTION("Constructor") { CHECK(a.pubkey == bkey.get_bin_q()); CHECK(b.RK == root); CHECK(b.DHs == bkey); CHECK(a.RK != b.RK); } SECTION("KDF and DHratchet") { auto [newkey, deckey] = a.kdf_CK(root); CHECK(newkey != deckey); CHECK(newkey != root); b.DHRatchet(a.DHs.get_bin_q()); CHECK(b.PN == 0); CHECK(b.CKr == a.CKs); CHECK(a.DHs.get_bin_q() == b.pubkey); CHECK(!(b.DHs == bkey)); CHECK(a.RK != b.RK); b.DHRatchet(a.DHs.get_bin_q()); CHECK(b.CKr != a.CKs); CHECK(a.DHs.get_bin_q() == b.pubkey); } SECTION("DHRatchet more times") { b.DHRatchet(a.DHs.get_bin_q()); CHECK(b.PN == 0); CHECK(b.CKr == a.CKs); CHECK(a.DHs.get_bin_q() == b.pubkey); CHECK(!(b.DHs == bkey)); CHECK(a.RK != b.RK); a.DHRatchet(b.DHs.get_bin_q()); CHECK(a.CKr == b.CKs); b.DHRatchet(a.DHs.get_bin_q()); CHECK(b.CKr == a.CKs); a.DHRatchet(b.DHs.get_bin_q()); CHECK(a.CKr == b.CKs); b.DHRatchet(a.DHs.get_bin_q()); CHECK(b.CKr == a.CKs); } SECTION("create and parse header") { std::vector<uint8_t> msg = a.create_header(root,0,0); auto [key, PN, N] = a.parse_header(msg); CHECK(key == root); CHECK(PN == 0); CHECK(N == 0); uint16_t pn2 = 37; uint16_t n2 = 17; msg = a.create_header(root,pn2,n2); auto [key1, PN1, N1] = a.parse_header(msg); CHECK(key1 == root); CHECK(PN1 == pn2); CHECK(N1 == n2); } SECTION("Compute skipped") { CHECK(a.SKIPPED.size() == 0); CHECK(a.Nr == 0); a.compute_skipped(5); CHECK(a.SKIPPED.size() == 4); CHECK(a.Nr == 4); } } TEST_CASE("DRBox2","encrypt and decrypt"){ std::array<uint8_t, 32> root; cry::ECKey akey; akey.gen_pub_key(); cry::ECKey bkey; bkey.gen_pub_key(); DRBox a{root, bkey.get_bin_q()}; DRBox b{root, bkey}; SECTION("empty") { std::vector<uint8_t> data = {}; REQUIRE(b.decrypt(a.encrypt(data)) == data); REQUIRE(a.decrypt(b.encrypt(data)) == data); REQUIRE(a.decrypt(b.encrypt(data)) == data); REQUIRE(b.decrypt(a.encrypt(data)) == data); REQUIRE(a.RK != b.RK); REQUIRE_THROWS(a.decrypt(a.encrypt(a.encrypt(data)))); } SECTION("some") { std::vector<uint8_t> data = {'T', 'e', 's', 't', ' ', 0x00, 0x01, 0x02, 0x03, 0x04}; REQUIRE(b.decrypt(a.encrypt(data)) == data); REQUIRE(a.decrypt(b.encrypt(data)) == data); REQUIRE(a.decrypt(b.encrypt(data)) == data); REQUIRE(b.decrypt(a.encrypt(data)) == data); REQUIRE(a.RK != b.RK); REQUIRE_THROWS(a.decrypt(a.encrypt(a.encrypt(data)))); } SECTION("recv start") { std::vector<uint8_t> data = {'T', 'e', 's', 't', ' ', 0x00, 0x01, 0x02, 0x03, 0x04}; REQUIRE(a.decrypt(b.encrypt(data)) == data); REQUIRE(a.decrypt(b.encrypt(data)) == data); REQUIRE(b.decrypt(a.encrypt(data)) == data); REQUIRE(b.decrypt(a.encrypt(data)) == data); REQUIRE(a.decrypt(b.encrypt(data)) == data); } SECTION("a lot") { std::vector<uint8_t> data; data.resize(1024 * 1024); std::iota(data.begin(), data.end(), 0); REQUIRE(b.decrypt(a.encrypt(data)) == data); REQUIRE(a.decrypt(b.encrypt(data)) == data); REQUIRE(a.decrypt(b.encrypt(data)) == data); REQUIRE(b.decrypt(a.encrypt(data)) == data); REQUIRE(a.RK != b.RK); REQUIRE_THROWS(a.decrypt(a.encrypt(a.encrypt(data)))); } SECTION("Some skipped") { std::vector<uint8_t> data = {'T', 'e', 's', 't', ' ', 0x00, 0x01, 0x02, 0x03, 0x04}; REQUIRE(b.decrypt(a.encrypt(data)) == data); CHECK(a.CKs == b.CKr); std::vector skipped1 = a.encrypt(data); std::array<uint8_t,32> key = cry::kdf(a.CKs, std::array<uint8_t, 32>{}); std::array<uint8_t,32> pubkey = a.DHs.get_bin_q(); CHECK(pubkey == b.pubkey); CHECK(a.CKs != b.CKr); REQUIRE(a.decrypt(b.encrypt(data)) == data); REQUIRE(a.decrypt(b.encrypt(data)) == data); CHECK(a.CKr == b.CKs); REQUIRE(b.decrypt(a.encrypt(data)) == data); CHECK(b.CKr == a.CKs); REQUIRE(b.decrypt(a.encrypt(data)) == data); CHECK(a.PN == 2); CHECK(b.PN == 2); REQUIRE(b.SKIPPED.size() == 1); REQUIRE(b.decrypt(a.encrypt(data)) == data); REQUIRE((b.SKIPPED.find(std::make_pair(pubkey,2)) != b.SKIPPED.end())); REQUIRE(b.SKIPPED.find(std::make_pair(pubkey,2))->second == key); REQUIRE(b.decrypt(skipped1) == data); REQUIRE((b.SKIPPED.find(std::make_pair(pubkey,2)) == b.SKIPPED.end())); REQUIRE(a.decrypt(b.encrypt(data)) == data); std::vector<uint8_t> skippa = a.encrypt(data); CHECK(a.CKs != b.CKr); std::vector<uint8_t> skippb = b.encrypt(data); REQUIRE(a.decrypt(b.encrypt(data)) == data); CHECK(a.CKr == b.CKs); REQUIRE(a.decrypt(b.encrypt(data)) == data); CHECK(a.CKr == b.CKs); REQUIRE(b.decrypt(a.encrypt(data)) == data); REQUIRE(b.decrypt(skippa) == data); REQUIRE(a.decrypt(skippb) == data); } } TEST_CASE("DRBox serialize/deserialize") { std::array<uint8_t, 32> root; cry::ECKey akey; akey.gen_pub_key(); cry::ECKey bkey; bkey.gen_pub_key(); DRBox a{root, bkey.get_bin_q()}; DRBox b{root, bkey}; REQUIRE(a.serialize() == a.serialize()); REQUIRE(b.serialize() == b.serialize()); REQUIRE(a.serialize() != b.serialize()); DRBox restored_a{a.serialize()}; REQUIRE(restored_a.RK == a.RK); REQUIRE(restored_a.CKs == a.CKs); REQUIRE(restored_a.CKr == a.CKr); REQUIRE(restored_a.DHs == a.DHs); REQUIRE(restored_a.Ns == a.Ns); REQUIRE(restored_a.Nr == a.Nr); REQUIRE(restored_a.PN == a.PN); REQUIRE(restored_a.pubkey_to_send == a.pubkey_to_send); REQUIRE(restored_a.pubkey == a.pubkey); REQUIRE(restored_a.SKIPPED == a.SKIPPED); } TEST_CASE("DRBox MAC") { std::array<uint8_t, 32> root; cry::ECKey akey; akey.gen_pub_key(); cry::ECKey bkey; bkey.gen_pub_key(); DRBox a{root, bkey.get_bin_q()}; DRBox b{root, bkey}; std::vector<uint8_t> data = {'T', 'e', 's', 't', ' ', 0x00, 0x01, 0x02, 0x03, 0x04}; auto aencrypted = a.encrypt(data); aencrypted[0] ^= 1 << 4; REQUIRE_THROWS(b.decrypt(aencrypted)); auto bencrypted = b.encrypt(data); bencrypted[0] ^= 1 << 4; REQUIRE_THROWS(a.decrypt(bencrypted)); }
1f0b9380d6f5aaedd587f2a92d2e4cf32434cb60
2bae07914bcd383fefe415194ffb63e2b007aff2
/engine/modules/graveyard/webserver/include/tiki/webserver/httprequest.hpp
2367d7437ff439293b13db999521c91bda268826
[]
no_license
TikiTek/mechanica
ec4972b541bfb7dc685b0b7918785c5ca99622d2
d151a818a279f1969b977ff7a935148b18ab9546
refs/heads/master
2021-10-09T07:27:23.308704
2021-10-08T07:42:04
2021-10-08T07:42:04
71,704,579
1
0
null
null
null
null
UTF-8
C++
false
false
280
hpp
httprequest.hpp
#pragma once #ifndef TIKI_HTTPREQUEST_HPP_INCLUDED__ #define TIKI_HTTPREQUEST_HPP_INCLUDED__ #include "tiki/base/types.hpp" #include "tiki/net/url.hpp" namespace tiki { struct HttpRequest { Url url; const char* pBody; }; } #endif // TIKI_HTTPREQUEST_HPP_INCLUDED__
9b8a8091b322e5c2bd1c1ef50abc1d92b177d880
20b49a6ef1fa417d67abef2d29a598c9e41c478e
/CodeForces/Lockout/Round 7/designTutorialLearnFromLife.cpp
ea2dab0daa608cf3a9816207843606352c9b736f
[]
no_license
switchpiggy/Competitive_Programming
956dac4a71fdf65de2959dd142a2032e2f0710e1
beaaae4ece70889b0af1494d68c630a6e053558a
refs/heads/master
2023-04-15T19:13:12.348433
2021-04-04T06:12:29
2021-04-04T06:12:29
290,905,106
1
3
null
2020-10-05T20:16:53
2020-08-27T23:38:48
C++
UTF-8
C++
false
false
381
cpp
designTutorialLearnFromLife.cpp
#include <bits/stdc++.h> using namespace std; typedef long long int ll; ll n, k, f[2007]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> k; for(ll i = 0; i < n; ++i) cin >> f[i]; sort(f, f + n, greater<ll>()); ll ans = 0; for(ll i = 0; i < n; i += k) { ans += (f[i] - 1) * 2; } cout << ans << '\n'; return 0; }
a7f2f392400c45b171b31148d3016f3406db3d69
bc2c0261cc3a3dd9c9e5c9d3fdf778864cec7864
/Event.cpp
dba68adc8100eb6878916c44288634fbfcb2e119
[]
no_license
denper-0/M7012E
0a974fcdd4431a629babf9927592bcedcf6c2641
19fe79b6357ef843bb9b6cab17d19f7197a70006
refs/heads/master
2021-01-13T02:17:59.966619
2014-01-19T14:32:46
2014-01-19T14:32:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,702
cpp
Event.cpp
#include "Event.h" Event::Event(MyLeapAction a, PlayerState* current_PS, RoomState* current_RS, PlayerState* newPS, RoomState* newRS, std::string eText) { action = a; cur_PS = current_PS; new_PS = newPS; cur_RS = current_RS; new_RS = newRS; eventText = eText; moveToNextRoom = false; barelyEscapable = false; Room* barelyEscapableRoom = NULL; } Event::~Event(void) { } void Event::setText(std::string eventStr){ eventText = eventStr; } std::string Event::getText(){ return eventText; } void Event::setPlayerState(PlayerState* currentPS, PlayerState* newPS){ cur_PS = currentPS; new_PS = newPS; } void Event::setRoomState(RoomState* currentRS,RoomState* newRS){ cur_RS = currentRS; new_RS = newRS; } PlayerState* Event::getNewPlayerstate() { return new_PS; } RoomState* Event::getNewRoomstate() { return new_RS; } PlayerState* Event::getCurrentPlayerstate() { return cur_PS; } RoomState* Event::getCurrentRoomstate() { return cur_RS; } MyLeapAction Event::getAction() { return action; } bool Event::getMoveToNextRoom() { return moveToNextRoom; } void Event::setMoveToNextRoom(bool isOnThisEvent) { moveToNextRoom = isOnThisEvent; } bool Event::isBarelyEscapable() { return barelyEscapable; } void Event::setBarelyEscapable(Room *barelyEscapableRoom) { this->barelyEscapableRoom = barelyEscapableRoom; if(barelyEscapableRoom != NULL) { barelyEscapable = true; } else{ barelyEscapable = false; } } Room* Event::getBarelyEscapableRoom() { return barelyEscapableRoom; } void Event::setActionOnEvent(OnEventAction action) { this->eventActions.push_back(action); } std::vector<OnEventAction> Event::getActionOnEvent() { return this->eventActions; }
2136c82535ec464e095f6bd240c353fc7a5e525f
402bdfabc4a4462c4a5264ad510ae6365ec05d4a
/src/plugins/openmptplugin/openmpt/common/mptAlloc.cpp
41d81ec5d53830dd716bf506fd01414fea6a37cb
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
sasq64/musicplayer
aa6a7513801808ad8dac999f65bbe37d0d471010
2f122363b99a8a659885d5f8908c1ea3534c3946
refs/heads/master
2023-03-20T03:26:02.935156
2023-03-06T07:21:41
2023-03-06T07:21:41
113,909,161
12
3
NOASSERTION
2020-08-19T14:45:09
2017-12-11T21:13:44
C
UTF-8
C++
false
false
2,870
cpp
mptAlloc.cpp
/* * mptAlloc.cpp * ------------ * Purpose: Dynamic memory allocation. * Notes : (currently none) * Authors: OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #include "mptAlloc.h" #include "mptBaseTypes.h" #include <memory> #include <new> #include <cstddef> #include <cstdlib> #if MPT_COMPILER_MSVC #include <malloc.h> #endif OPENMPT_NAMESPACE_BEGIN namespace mpt { #if MPT_CXX_AT_LEAST(17) #else void* align(std::size_t alignment, std::size_t size, void* &ptr, std::size_t &space) noexcept { std::size_t offset = static_cast<std::size_t>(reinterpret_cast<std::uintptr_t>(ptr) & (alignment - 1)); if(offset != 0) { offset = alignment - offset; } if((space < offset) || ((space - offset) < size)) { return nullptr; } ptr = static_cast<mpt::byte*>(ptr) + offset; space -= offset; return ptr; } #endif aligned_raw_memory aligned_alloc_impl(std::size_t size, std::size_t count, std::size_t alignment) { #if MPT_CXX_AT_LEAST(17) && (!MPT_COMPILER_MSVC && !MPT_GCC_BEFORE(8,1,0) && !MPT_CLANG_BEFORE(5,0,0)) && !(MPT_COMPILER_CLANG && defined(__GLIBCXX__)) && !(MPT_COMPILER_CLANG && MPT_OS_MACOSX_OR_IOS) && !MPT_OS_EMSCRIPTEN && !(defined(__clang__) && defined(_MSC_VER)) std::size_t space = count * size; void* mem = std::aligned_alloc(alignment, space); if(!mem) { MPT_EXCEPTION_THROW_OUT_OF_MEMORY(); } return aligned_raw_memory{mem, mem}; #elif MPT_COMPILER_MSVC || (defined(__clang__) && defined(_MSC_VER)) std::size_t space = count * size; void* mem = _aligned_malloc(space, alignment); if(!mem) { MPT_EXCEPTION_THROW_OUT_OF_MEMORY(); } return aligned_raw_memory{mem, mem}; #else if(alignment > alignof(std::max_align_t)) { std::size_t space = count * size + (alignment - 1); void* mem = std::malloc(space); if(!mem) { MPT_EXCEPTION_THROW_OUT_OF_MEMORY(); } void* aligned_mem = mem; void* aligned = mpt::align(alignment, size * count, aligned_mem, space); if(!aligned) { MPT_EXCEPTION_THROW_OUT_OF_MEMORY(); } return aligned_raw_memory{aligned, mem}; } else { std::size_t space = count * size; void* mem = std::malloc(space); if(!mem) { MPT_EXCEPTION_THROW_OUT_OF_MEMORY(); } return aligned_raw_memory{mem, mem}; } #endif } void aligned_free(aligned_raw_memory raw) { #if MPT_CXX_AT_LEAST(17) && (!MPT_COMPILER_MSVC && !MPT_GCC_BEFORE(8,1,0) && !MPT_CLANG_BEFORE(5,0,0)) && !(MPT_COMPILER_CLANG && defined(__GLIBCXX__)) && !(MPT_COMPILER_CLANG && MPT_OS_MACOSX_OR_IOS) && !MPT_OS_EMSCRIPTEN && !(defined(__clang__) && defined(_MSC_VER)) std::free(raw.mem); #elif MPT_COMPILER_MSVC || (defined(__clang__) && defined(_MSC_VER)) _aligned_free(raw.mem); #else std::free(raw.mem); #endif } } // namespace mpt OPENMPT_NAMESPACE_END
9fa7d218cb1e050c1061f5312d634ed2daa52669
1e07bd2360ecb738f1a36b8fd033760485575797
/Square Matrix II/Square Matrix II/main.cpp
c18d28ff57f88851224772c6714a15b3c902cc3e
[ "MIT" ]
permissive
brunorabelo/URI-Online-Judge
437af37a24b4a50118c9c39f2febd620739dda94
87051c4fa7339c0ed6d9613739b70cedea2fe090
refs/heads/master
2021-01-21T16:54:04.701823
2017-05-20T22:39:57
2017-05-20T22:39:57
91,916,692
0
0
null
null
null
null
UTF-8
C++
false
false
623
cpp
main.cpp
// // main.cpp // Square Matrix II // // Created by MacBook on 01/05/17. // Copyright © 2017 Bruno Botelho. All rights reserved. // #include <stdio.h> #include <stdlib.h> int main(int argc, const char * argv[]) { // insert code here... int size; scanf("%d",&size); while(size!=0){ for(int i=0;i<size;i++){ for(int j=0;j<size;j++){ printf("%3d",abs(i-j)+1); if(j!=size-1) printf(" "); } printf("\n"); } printf("\n"); scanf("%d",&size); } return 0; }
3f65f0e4dc98d86e0a2c413d21dec62b02ff1348
c83393c627739a9423ed06664b0ba27a98b7d351
/test/http/http_response.h
e348d863ab4c99b12e0afbe8d12f1f4939009c42
[ "BSD-3-Clause" ]
permissive
caozhiyi/CppNet
7a00053200234dffbb23e3eb90bd9bc0520942fd
a96449fe22b80a2c892ee0f7157831d63cc5d05a
refs/heads/master
2023-08-20T05:29:03.732554
2023-06-21T08:29:50
2023-06-21T08:29:50
136,014,386
953
249
BSD-3-Clause
2023-09-09T12:12:45
2018-06-04T11:20:12
C++
UTF-8
C++
false
false
1,442
h
http_response.h
#ifndef TEST_HTTP_HTTP_RESPONSE_HEADER #define TEST_HTTP_HTTP_RESPONSE_HEADER #include <map> enum HttpStatusCode { kUnknown, k200Ok = 200, k301MovedPermanently = 301, k400BadRequest = 400, k404NotFound = 404, }; class HttpResponse { public: explicit HttpResponse(bool close) : _status_code(kUnknown), _close_connection(close) { } void SetStatusCode(HttpStatusCode code) { _status_code = code; } void SetStatusMessage(const std::string& message) { _status_message = message; } void SetCloseConnection(bool on) { _close_connection = on; } bool GetCloseConnection() const { return _close_connection; } void SetContentType(const std::string& contentType) { AddHeader("Content-Type", contentType); } // FIXME: replace string with StringPiece void AddHeader(const std::string& key, const std::string& value) { _headers_map[key] = value; } void SetBody(const std::string& body) { _body = body; } std::string GetSendBuffer() const; private: std::map<std::string, std::string> _headers_map; HttpStatusCode _status_code; // FIXME: add http version std::string _status_message; bool _close_connection; std::string _body; }; #endif
d71b87384c207a6ee309714fe043c5592106de7a
5402279b0e58e0aed68a8c40174f3a12dccf6187
/src/seri.cpp
b5e95eee81422359cca8f34de4c06288f47cd811
[]
no_license
YangTaoCraig/C955-RTU_Version-1009
59b97d081b2e12c329c078a6aa1a38c669ffb20d
594158642e7d4047e69b787b4b19d2a2c2d1a73e
refs/heads/master
2021-01-20T20:42:22.780302
2016-07-04T01:41:02
2016-07-04T01:41:02
62,523,955
0
0
null
null
null
null
UTF-8
C++
false
false
12,678
cpp
seri.cpp
/*---------------------------------------------------------------------------- Copyright (c) 2010 ST Electronics Ltd. PROPRIETARY RIGHTS of ST Electronics Ltd are involved in the subject matter of this material. All manufacturing, reproduction, use, and sales rights pertaining to this subject matter are governed by the license agreement. The recipient of this software implicitly accepts the terms of the license. ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- FILE NAME VERSION seri.cpp D1.0.4 COMPONENT SER - Serial Link Management DESCRIPTION This file consists of initialization routine for the Serial Link Management AUTHOR Bryan KW Chong HISTORY NAME DATE REMARKS Bryan Chong 07-Sep-2009 Initial revision ----------------------------------------------------------------------------*/ #include <stdio.h> #include <string.h> #include <fcntl.h> #include <sys/neutrino.h> #include <termios.h> #include <fixerrno.h> #include <sys/dcmd_chr.h> #include <devctl.h> #include "cfg_def.h" #include "type_def.h" #include "err_def.h" #include "ser_def.h" #include "ser_ext.h" #include "swc_def.h" #include "sys_def.h" #include "sys_ext.h" #include "sys_ass.h" #include "hwp_def.h" #include "hwp_ext.h" /*---------------------------------------------------------------------------- Public variables declaration ----------------------------------------------------------------------------*/ SER_CB_T *pSER_CB; CHAR *SER_acSerialPortName[24] = { /* (CHAR *)ser1, (CHAR *)ser2, (CHAR *)ser3, (CHAR *)ser4, */ (CHAR *)ser5, (CHAR *)ser6, (CHAR *)ser7, (CHAR *)ser8, (CHAR *)ser9, (CHAR *)ser10, (CHAR *)ser11, (CHAR *)ser12, (CHAR *)ser13, (CHAR *)ser14, (CHAR *)ser15, (CHAR *)ser16, (CHAR *)ser17, (CHAR *)ser18, (CHAR *)ser19, (CHAR *)ser20, (CHAR *)ser21, (CHAR *)ser22, (CHAR *)ser23, (CHAR *)ser24 }; /*---------------------------------------------------------------------------- Public Prototypes declaration ----------------------------------------------------------------------------*/ E_ERR_T SER_Initialization(); E_ERR_T SER_SendMsg(INT32 *pfd, CHAR *pmsg); //E_ERR_T SER_ClosePort(INT32 *pfd); //E_ERR_T SER_ReInitializePort(const E_SER_COM comport); /*---------------------------------------------------------------------------- Private variables declaration ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- Private Prototypes declaration ----------------------------------------------------------------------------*/ static E_ERR_T ser_OpenPort(E_SER_COM com_port, const CHAR *p_pathname, INT32 *pfd, UINT32 accessmode); static SER_CB_T ser_ControlBlk[E_SER_COM_EndOfList]; /*---------------------------------------------------------------------------- Private lookup table declaration ----------------------------------------------------------------------------*/ static SER_PD_T ser_PortDescriptor[] = { /* port, path name, baudrate, parity, databit, stopbit, */ // onboard serial com port {E_SER_COM_Port_Reserved, "reserved\0", B0, E_SER_PARITY_Disable, E_SER_DATABIT_Reserved, E_SER_STOPBIT_Reserved}, {E_SER_COM_Port_1, "/dev/ser1", B38400, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_1, O_RDWR}, {E_SER_COM_Port_2, "/dev/ser2", B57600, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_2, O_RDWR}, {E_SER_COM_Port_3, "/dev/ser3", B38400, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_1, O_RDWR}, {E_SER_COM_Port_4, "/dev/ser4", B57600, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_2, O_RDWR}, // Moxa card 1 PCI based serial com port {E_SER_COM_Port_5, "/dev/ser5", B19200, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_1, (O_RDWR | O_NONBLOCK)}, {E_SER_COM_Port_6, "/dev/ser6", B19200, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_1, (O_RDWR | O_NONBLOCK)}, {E_SER_COM_Port_7, "/dev/ser7", B19200, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_2, (O_RDWR | O_NONBLOCK)}, {E_SER_COM_Port_8, "/dev/ser8", B19200, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_2, (O_RDWR | O_NONBLOCK)}, {E_SER_COM_Port_9, "/dev/ser9", B19200, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_2, (O_RDWR | O_NONBLOCK)}, {E_SER_COM_Port_10, "/dev/ser10", B19200, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_1, (O_RDWR | O_NONBLOCK)}, {E_SER_COM_Port_11, "/dev/ser11", B19200, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_1, (O_RDWR | O_NONBLOCK)}, {E_SER_COM_Port_12, "/dev/ser12", B19200, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_1, (O_RDWR | O_NONBLOCK)}, // Moxa card 2 PCI based serial com port {E_SER_COM_Port_13, "/dev/ser13", B19200, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_1, (O_RDWR | O_NONBLOCK)}, {E_SER_COM_Port_14, "/dev/ser14", B19200, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_1, (O_RDWR | O_NONBLOCK)}, {E_SER_COM_Port_15, "/dev/ser15", B19200, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_2, (O_RDWR | O_NONBLOCK)}, {E_SER_COM_Port_16, "/dev/ser16", B19200, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_2, (O_RDWR | O_NONBLOCK)}, {E_SER_COM_Port_17, "/dev/ser17", B19200, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_2, (O_RDWR | O_NONBLOCK)}, {E_SER_COM_Port_18, "/dev/ser18", B19200, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_2, (O_RDWR | O_NONBLOCK)}, {E_SER_COM_Port_19, "/dev/ser19", B19200, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_2, (O_RDWR | O_NONBLOCK)}, {E_SER_COM_Port_20, "/dev/ser20", B19200, E_SER_PARITY_Disable, E_SER_DATABIT_8, E_SER_STOPBIT_2, (O_RDWR | O_NONBLOCK)}, {E_SER_COM_EndOfList, "End Of List", B0, E_SER_PARITY_Disable, E_SER_DATABIT_EndOfList, E_SER_STOPBIT_EndOfList} }; /*----------------------------------------------------------------------------- PRIVATE ROUTINE SER_Initialization DESCRIPTION This routine will initialize serial link management. Use ser_PortDescriptor look-up table to add or remove serial port. CALLED BY Application main CALLS [TBD] PARAMETER None RETURN E_ERR_Success the routine executed successfully AUTHOR Bryan KW Chong HISTORY NAME DATE REMARKS Bryan Chong 07-Sep-2009 Created initial revision -----------------------------------------------------------------------------*/ E_ERR_T SER_Initialization() { E_ERR_T rstatus = E_ERR_Success; UINT8 port_cnt = E_SER_COM_Port_1; SER_PD_T *ppd; // port descriptor array SER_CB_T *pcb; // port control block ppd = ser_PortDescriptor; pcb = ser_ControlBlk; // initialize global pointer to serial management control block pSER_CB = ser_ControlBlk; if(pHWP_CB->uctotalSerialCOMPort > E_SER_COM_EndOfList) return E_ERR_SER_SerialCOMPortOutOfRange; for(port_cnt = (UINT8)E_SER_COM_Port_1; port_cnt <= pHWP_CB->uctotalSerialCOMPort; port_cnt++) { ppd = &ser_PortDescriptor[port_cnt]; pcb = &ser_ControlBlk[port_cnt]; rstatus = ser_OpenPort(ppd->port, ppd->path_name, &pcb->fd, ppd->accessmode); if(rstatus != E_ERR_Success) { #ifdef CFG_PRN_ERR printf("[SER] SER_Initialization, open port %d fail\n", port_cnt); #endif // CFG_PRN_ERR } rstatus = SER_SetAttribute(ppd->port, ppd->baudrate, ppd->parity, ppd->databit, ppd->stopbit); SYS_ASSERT_RETURN(rstatus != E_ERR_Success, rstatus); delay(10); // flush input and output data tcflush(pcb->fd, TCIOFLUSH ); pcb->pport_desc = ppd; #if ((defined CFG_DEBUG_MSG) && (defined CFG_DEBUG_SER)) printf("[SER] SER_Initialization, port %d, port fd = %d\n", port_cnt, pcb->fd); #endif // ((defined CFG_DEBUG_MSG) && (defined CFG_DEBUG_SER)) } memset(pcb->history, 0, sizeof(pcb->history)); pcb->nextEmptyHistoryId = 0; #if ((defined CFG_DEBUG_MSG) && (defined CFG_DEBUG_SER_HOSTCMD)) printf("[SER] SER_Initialization, history size %d bytes, start id %d\n", sizeof(pcb->history), pcb->nextEmptyHistoryId); #endif // ((defined CFG_DEBUG_MSG) && (defined CFG_DEBUG_SER)) return E_ERR_Success; } // SER_Initialization /*----------------------------------------------------------------------------- PRIVATE ROUTINE SER_ReInitializePort DESCRIPTION This routine will re-initialize the designated serial port. CALLED BY Application main CALLS [TBD] PARAMETER None RETURN E_ERR_Success the routine executed successfully AUTHOR Bryan KW Chong HISTORY NAME DATE REMARKS Bryan Chong 22-Oct-2010 Created initial revision -----------------------------------------------------------------------------*/ //E_ERR_T SER_ReInitializePort(const E_SER_COM comport) //{ // E_ERR_T rstatus = E_ERR_Success; // INT32 fd; // SER_PD_T *ppd; // port descriptor array // SER_CB_T *pcb; // port control block // // if((comport > E_SER_COM_EndOfList) || (comport < E_SER_COM_Port_1)) // return E_ERR_SER_SerialCOMPortOutOfRange; // // fd = pSER_CB[comport].fd; // // if(fd != TYP_NULL) // rstatus = SER_ClosePort(&fd); // // ppd = &ser_PortDescriptor[comport]; // pcb = &ser_ControlBlk[comport]; // // rstatus = ser_OpenPort(ppd->port, ppd->path_name, &pcb->fd, // ppd->accessmode); // if(rstatus != E_ERR_Success) // { // #ifdef CFG_PRN_ERR // printf("[SER] SER_Initialization, open port %d fail\n", comport); // #endif // CFG_PRN_ERR // return rstatus; // } // // rstatus = SER_SetAttribute(ppd->port, ppd->baudrate, ppd->parity, // ppd->databit, ppd->stopbit); // SYS_ASSERT_RETURN(rstatus != E_ERR_Success, rstatus); // // delay(10); // // flush input and output data // tcflush(pcb->fd, TCIOFLUSH ); // // pcb->pport_desc = ppd; // // #if ((defined CFG_DEBUG_MSG) && (defined CFG_DEBUG_SER)) // printf("[SER] SER_ReInitializePort, port %d, fd %d\n", // comport, pcb->fd); // #endif // ((defined CFG_DEBUG_MSG) && (defined CFG_DEBUG_SER)) // // return E_ERR_Success; //} // SER_ReInitializePort /*----------------------------------------------------------------------------- PUBLIC ROUTINE SER_ClosePort DESCRIPTION This routine will close the serial port CALLED BY Application main CALLS [TBD] PARAMETER None RETURN E_ERR_Success the routine executed successfully AUTHOR Bryan KW Chong HISTORY NAME DATE REMARKS Bryan Chong 07-Sep-2009 Created initial revision -----------------------------------------------------------------------------*/ //E_ERR_T SER_ClosePort(INT32 *pfd) //{ // if(pfd == TYP_NULL) // return E_ERR_InvalidNullPointer; // // close(*pfd); // return E_ERR_Success; //} // SER_ClosePort /*----------------------------------------------------------------------------- PRIVATE ROUTINE ser_OpenPort DESCRIPTION This routine will open a serial port CALLED BY Application main CALLS [TBD] PARAMETER None RETURN E_ERR_Success the routine executed successfully AUTHOR Bryan KW Chong HISTORY NAME DATE REMARKS Bryan Chong 07-Sep-2009 Created initial revision -----------------------------------------------------------------------------*/ static E_ERR_T ser_OpenPort(E_SER_COM com_port, const CHAR *p_pathname, INT32 *pfd, UINT32 accessmode) { INT32 fd; //if((fd = open(p_pathname, (O_RDWR))) < 0) if((fd = open(p_pathname, accessmode)) < 0) { #ifdef CFG_DEBUG_MSG printf("[SER] ser_OpenPort, open port %d fail\n", (UINT8)com_port); #endif // CFG_DEBUG_MSG return E_ERR_SER_OpenPortFail; } #if ((defined CFG_DEBUG_MSG) && (CFG_DEBUG_SER)) printf("[SER] ser_OpenPort, fd = %d\r\n", fd); #endif // ((defined CFG_DEBUG_MSG) && (CFG_DEBUG_SER)) *pfd = fd; return E_ERR_Success; } // ser_OpenPort
d9917e80a8bcb7d1ee27fbe07c9be1aaba8e7e88
72ceae2bcd7716fc0e5eb9bfac5a2e80b9594a83
/src/shader/character.cc
870c7ad87af558f48b90de244d5d82aa9a48538f
[ "MIT" ]
permissive
gyf1214/gl-danmaku
6e296c313b74a554d476e218a25ce1c215fd5f08
a4cdff1052a87c0ea3d7cf3a2c02d395a8bc019e
refs/heads/master
2021-01-23T02:18:50.034243
2017-07-06T16:59:24
2017-07-06T16:59:24
85,981,461
2
0
null
2017-07-06T16:07:37
2017-03-23T18:00:01
C++
UTF-8
C++
false
false
2,520
cc
character.cc
#include "component/shader.hpp" static GLuint program = 0; static const char *vsh = R"( #version 330 core precision highp float; in vec3 position; in vec3 normal; in vec2 uv; in ivec4 boneIndex; in vec4 boneWeight; uniform mat4 mMat; uniform mat4 vMat; uniform mat4 pMat; uniform vec4 lightPosition; uniform samplerBuffer morphData; uniform int morphCount; uniform float morphs[128]; uniform Bones { mat4 bones[512]; }; out vec3 normalOut; out vec2 uvOut; out vec4 vPos; out vec4 lPos; void main(void) { vec3 pos = position; for (int i = 0; i < morphCount; ++i) { vec3 offset = texelFetch(morphData, gl_VertexID * morphCount + i).xyz; pos += morphs[i] * offset; } mat4 bMat = boneWeight.x * bones[boneIndex.x] + boneWeight.y * bones[boneIndex.y]; vPos = vMat * mMat * bMat * vec4(pos, 1.0); gl_Position = pMat * vPos; normalOut = normalize((vMat * mMat * bMat * vec4(normal, 0.0)).xyz); uvOut = vec2(uv.x, 1.0 - uv.y); lPos = vMat * lightPosition; if (lPos.w == 0.0) { lPos = vec4(normalize(-lPos.xyz), 0.0); } else { lPos = vec4(lPos.xyz - vPos.xyz, 1.0); } } )"; static const char *fsh = R"( #version 330 core precision highp float; in vec3 normalOut; in vec2 uvOut; in vec4 vPos; in vec4 lPos; uniform vec3 lightColor; uniform vec3 ambient; uniform vec4 lightMaterial; uniform vec4 diffuse; uniform vec4 specular; uniform sampler2D texture0; out vec4 fragColor; void main(void) { vec3 color = texture(texture0, uvOut).rgb; vec3 c = ambient * color; vec3 N = normalize(normalOut); vec3 L = normalize(lPos.xyz); vec3 H = normalize(L - normalize(vPos.xyz)); float scalar = 1.0; if (lPos.w != 0.0) { float dis = length(lPos.xyz); scalar /= dot(lightMaterial.xyz, vec3(1.0, dis, dis * dis)); } float side = gl_FrontFacing ? -1.0 : 1.0; vec3 diff = scalar * diffuse.xyz * max(dot(L, N) * side, 0.0); c += lightColor * color * diff; vec3 spec = scalar * specular.xyz * pow(max(dot(N, H), 0.0), specular.w); c += lightColor * spec; fragColor = vec4(c, 1.0); } )"; GLuint Shader::character() { if (!program) program = programShader(vsh, fsh); return program; }
41eb5ac1deba201d6ce26c7d736c76f17d163c77
12b7d29ab6791836f8ca31561255ee27ac6a7cf0
/tut9.cpp
9d2022a45b1ec8c5231008afe3cde939d64248d8
[]
no_license
Prathamesh2642/learningcpp
bdedde09c6095e6d66575c923071bafdd4dce87e
1aeb85350dcfebda639f9468efd3071672a93950
refs/heads/main
2023-08-11T03:56:35.811337
2021-09-30T17:53:48
2021-09-30T17:53:48
411,654,974
0
0
null
null
null
null
UTF-8
C++
false
false
980
cpp
tut9.cpp
#include <iostream> using namespace std; int main(){ //cout<<"How are you"; int age; cout<<"please enter your age:"<<endl; cin>>age; //********if -else********** //if(age>18){ // cout<<"Party hard bro!"; //} // else{ // cout<<"You are not allowed,get out"; // } //*********if-else ladder******** //if(age>18 && age<59){ // cout<<"Party hard bro"<<endl; // // else if (age==18){ // cout<<"ask for parents permission"<<endl; // } // else if(age>59){ // cout<<"too old bruh"<<endl; // } // else{ // cout<<"get out"<<endl; // } //**********switch case statement********** switch (age) { case 18: cout<<"18"<<endl; break; case 22: cout<<"22"<<endl; break; case 9: cout<<"9"<<endl; break; default: cout<<"get out"; break; } return 0; }
9a08a3d2aa42f498b27d14cf4eeac294d58b3ebe
6b78e5377558d715386382064bdb77cc71cb8025
/Queue.h
d1f998c3ce1c7dc45909d42a01319a4c542b9d03
[]
no_license
nkahile/Tree-Based-Evaluator
1034f5780a2d677be62257e2a698968d76d8ef5f
4077d5088e8b399735887031d9fe56f5f8c5e894
refs/heads/main
2023-05-04T13:23:43.016533
2021-05-24T19:04:57
2021-05-24T19:04:57
365,877,865
1
0
null
null
null
null
UTF-8
C++
false
false
1,705
h
Queue.h
#ifndef _CS507_QUEUE_H_ #define _CS507_QUEUE_H_ #include <exception> #include "Array.h" /*Constant time or O(1) run time*/ template <typename T> class Queue { public: /// Type definition of the type. typedef T type; /** * @class empty_exception * * Exception thrown to indicate the Queue is empty. */ class empty_exception : public std::exception { public: // Default constructor. empty_exception(void) : std::exception() { } //Initializing constructor. //@param[in] msg Error message. empty_exception(const char* msg) : std::exception(msg) { } }; /// Default constructor. Queue(void); /// Copy constructor. Queue(const Queue& q); //Queue Destructor~ ~Queue(void); // Assigment operator for the queue const Queue& operator = (const Queue& rhs); //Adds the element to the end of the list; void enqueue(T element); //removes the element at the front of the list.If there are not elements in the queue, //an empty_exception will be thrown, T dequeue(void); //This method returns true if queue is empty || false if queue is full bool is_empty(void) const; //returns the number of elements in the queue size_t size(void) const; //clear contents of the Queue void clear(void); //show the contents of the Queue void show(void); private: Array<T> queue_data_; size_t queue_size_; size_t front_; size_t rear_; }; #include"Queue.cpp" #endif
2858fbb03b8b98ba6f31890ae4173c83f1d29d52
9f05d15a3f6d98711416d42e1ac3b385d9caa03a
/sem4/da/kp/conc/tokenizer.h
17874e05c5c0c94234dab31b0f17f1265efa0798
[]
no_license
dtbinh/MAI
abbad3bef790ea231a1dc36233851a080ea53225
a5c0b7ce0be0f5b5a1d5f193e228c685977a2f93
refs/heads/master
2020-06-16T06:45:58.595779
2016-08-21T15:37:10
2016-08-21T15:37:10
75,237,279
1
0
null
2016-11-30T23:45:58
2016-11-30T23:45:58
null
UTF-8
C++
false
false
409
h
tokenizer.h
#ifndef TOKENIZER_H #define TOKENIZER_H #include <string> #include <cstdio> #include "types.h" class TTokenizer { public: TTokenizer(FILE* file); void ReadNext(std::string& str); TUINT GetOffset() const; TUINT GetNum() const; TUINT GetRow() const; TUSHORT GetCol() const; private: TUINT mOffset; TUINT mNum; TUINT mRow; TUSHORT mCol; TUSHORT mCurCol; TUINT mCurRow; FILE* mFile; }; #endif
9d3370bf63eb8206927523320a5eccff0c88c6c2
b4a550fe493e0dead649113f3e3f629697574432
/src/win32/win32api_win32.cc
2bab8cbac6af00c14807951828697ec63befc649
[]
no_license
russellklenk/pil
0f1bd002fe98444194263d0041bcda7b992bdfc9
047a122bd2982f25275fdbd33749a8d7749df64f
refs/heads/master
2020-04-01T03:22:18.320257
2019-07-03T20:20:49
2019-07-03T20:20:49
152,819,240
0
0
null
null
null
null
UTF-8
C++
false
false
1,992
cc
win32api_win32.cc
/** * @summary win32api_win32.cc: Implement the Windows API runtime loader for the * Windows platform. */ #include "win32/win32api_win32.h" static HRESULT WINAPI SetProcessDpiAwareness_Stub ( PROCESS_DPI_AWARENESS level ) { UNREFERENCED_PARAMETER(level); if (SetProcessDPIAware()) { return S_OK; } else { return E_ACCESSDENIED; } } static HRESULT WINAPI GetDpiForMonitor_Stub ( HMONITOR monitor, MONITOR_DPI_TYPE type, UINT *dpi_x, UINT *dpi_y ) { if (type == MDT_EFFECTIVE_DPI) { HDC screen_dc = GetDC(NULL); DWORD h_dpi = GetDeviceCaps(screen_dc, LOGPIXELSX); DWORD v_dpi = GetDeviceCaps(screen_dc, LOGPIXELSY); ReleaseDC(NULL, screen_dc); *dpi_x = h_dpi; *dpi_y = v_dpi; UNREFERENCED_PARAMETER(monitor); return S_OK; } else { *dpi_x = USER_DEFAULT_SCREEN_DPI; *dpi_y = USER_DEFAULT_SCREEN_DPI; return E_INVALIDARG; } } PIL_API(int) Win32ApiPopulateDispatch ( struct WIN32API_DISPATCH *dispatch, uint32_t loader_flags ) { RUNTIME_MODULE shcore_dll; int result; assert(dispatch != NULL); RuntimeModuleInit(&shcore_dll); UNREFERENCED_PARAMETER(loader_flags); result = RuntimeModuleLoad(&shcore_dll, "Shcore.dll"); RuntimeFunctionResolve(dispatch, &shcore_dll, SetProcessDpiAwareness); RuntimeFunctionResolve(dispatch, &shcore_dll, GetDpiForMonitor); dispatch->ModuleHandle_Shcore = shcore_dll; return result; } PIL_API(int) Win32ApiQuerySupport ( struct WIN32API_DISPATCH *dispatch ) { UNREFERENCED_PARAMETER(dispatch); return 1; } PIL_API(void) Win32ApiInvalidateDispatch ( struct WIN32API_DISPATCH *dispatch ) { dispatch->SetProcessDpiAwareness = SetProcessDpiAwareness_Stub; dispatch->GetDpiForMonitor = GetDpiForMonitor_Stub; RuntimeModuleUnload(&dispatch->ModuleHandle_Shcore); }
f7953ff36ddcff3337b1b2cd83fcc8293c3eecff
26df6604faf41197c9ced34c3df13839be6e74d4
/ext/src/javax/swing/JLabel.hpp
336d997c55109a26971fcfd469d03db0c47b2ef0
[ "Apache-2.0" ]
permissive
pebble2015/cpoi
58b4b1e38a7769b13ccfb2973270d15d490de07f
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
refs/heads/master
2021-07-09T09:02:41.986901
2017-10-08T12:12:56
2017-10-08T12:12:56
105,988,119
0
0
null
null
null
null
UTF-8
C++
false
false
4,133
hpp
JLabel.hpp
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #pragma once #include <fwd-POI.hpp> #include <java/awt/fwd-POI.hpp> #include <java/io/fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <javax/accessibility/fwd-POI.hpp> #include <javax/swing/fwd-POI.hpp> #include <javax/swing/plaf/fwd-POI.hpp> #include <javax/swing/JComponent.hpp> #include <javax/swing/SwingConstants.hpp> #include <javax/accessibility/Accessible.hpp> struct default_init_tag; class javax::swing::JLabel : public JComponent , public virtual SwingConstants , public virtual ::javax::accessibility::Accessible { public: typedef JComponent super; private: static ::java::lang::String* LABELED_BY_PROPERTY_; Icon* defaultIcon { }; Icon* disabledIcon { }; bool disabledIconSet { }; int32_t horizontalAlignment { }; int32_t horizontalTextPosition { }; int32_t iconTextGap { }; public: /* protected */ ::java::awt::Component* labelFor { }; private: int32_t mnemonic { }; int32_t mnemonicIndex { }; ::java::lang::String* text { }; static ::java::lang::String* uiClassID_; int32_t verticalAlignment { }; int32_t verticalTextPosition { }; protected: void ctor(); void ctor(::java::lang::String* text); void ctor(Icon* image); void ctor(::java::lang::String* text, int32_t horizontalAlignment); void ctor(Icon* image, int32_t horizontalAlignment); void ctor(::java::lang::String* text, Icon* icon, int32_t horizontalAlignment); public: /* protected */ virtual int32_t checkHorizontalKey(int32_t key, ::java::lang::String* message); virtual int32_t checkVerticalKey(int32_t key, ::java::lang::String* message); public: ::javax::accessibility::AccessibleContext* getAccessibleContext() override; virtual Icon* getDisabledIcon(); virtual int32_t getDisplayedMnemonic(); virtual int32_t getDisplayedMnemonicIndex(); virtual int32_t getHorizontalAlignment(); virtual int32_t getHorizontalTextPosition(); virtual Icon* getIcon(); virtual int32_t getIconTextGap(); virtual ::java::awt::Component* getLabelFor(); virtual ::java::lang::String* getText(); virtual ::javax::swing::plaf::LabelUI* getUI(); ::java::lang::String* getUIClassID() override; virtual int32_t getVerticalAlignment(); virtual int32_t getVerticalTextPosition(); bool imageUpdate(::java::awt::Image* img, int32_t infoflags, int32_t x, int32_t y, int32_t w, int32_t h) override; public: /* protected */ ::java::lang::String* paramString() override; public: virtual void setDisabledIcon(Icon* disabledIcon); virtual void setDisplayedMnemonic(int32_t key); virtual void setDisplayedMnemonic(char16_t aChar); virtual void setDisplayedMnemonicIndex(int32_t index); virtual void setHorizontalAlignment(int32_t alignment); virtual void setHorizontalTextPosition(int32_t textPosition); virtual void setIcon(Icon* icon); virtual void setIconTextGap(int32_t iconTextGap); virtual void setLabelFor(::java::awt::Component* c); virtual void setText(::java::lang::String* text); virtual void setUI(::javax::swing::plaf::LabelUI* ui); virtual void setVerticalAlignment(int32_t alignment); virtual void setVerticalTextPosition(int32_t textPosition); void updateUI() override; /*void writeObject(::java::io::ObjectOutputStream* s); (private) */ // Generated JLabel(); JLabel(::java::lang::String* text); JLabel(Icon* image); JLabel(::java::lang::String* text, int32_t horizontalAlignment); JLabel(Icon* image, int32_t horizontalAlignment); JLabel(::java::lang::String* text, Icon* icon, int32_t horizontalAlignment); protected: JLabel(const ::default_init_tag&); public: static ::java::lang::Class *class_(); public: /* protected */ virtual void setUI(::javax::swing::plaf::ComponentUI* newUI); public: /* package */ static ::java::lang::String*& LABELED_BY_PROPERTY(); private: static ::java::lang::String*& uiClassID(); virtual ::java::lang::Class* getClass0(); };
070eba079014487c1b5c5b41c8fd88a0ac0d6182
fa0135628d8499145e9f45c9e936b30803c74ae8
/introspective_ORB_SLAM/include/torch_helpers.h
759c7a6404ed019e020ee6294032f71636a5a056
[]
no_license
YznMur/IV_SLAM
b67b1d9f9d1f77fb983be5748cbcf360250101bc
2cb772ae9ea30e6c99ea0c3ae0e72968d905a978
refs/heads/main
2023-08-20T23:36:12.102432
2021-03-02T17:01:04
2021-03-02T17:01:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,601
h
torch_helpers.h
// Copyright 2019 srabiee@cs.utexas.edu // College of Information and Computer Sciences, // University of Texas at Austin // // // This software is free: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License Version 3, // as published by the Free Software Foundation. // // This software is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // Version 3 in the file COPYING that came with this distribution. // If not, see <http://www.gnu.org/licenses/>. // ======================================================================== #ifndef iSLAM_TORCH_HELPERS #define iSLAM_TORCH_HELPERS #include <torch/torch.h> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #if (CV_VERSION_MAJOR >= 4) #include<opencv2/imgcodecs/legacy/constants_c.h> #endif #include <string> namespace ORB_SLAM2 { std::string GetImageType( const cv::Mat& img, bool more_info = true ); void ShowImage( cv::Mat img, std::string title ); at::Tensor TransposeTensor( at::Tensor & tensor, c10::IntArrayRef dims = { 0, 3, 1, 2 } ); at::Tensor CVImgToTensor( cv::Mat & img, bool unsqueeze = false, int unsqueeze_dim = 0 ); cv::Mat ToCvImage( at::Tensor & tensor ); } // namespace ORB_SLAM2 #endif // iSLAM_TORCH_HELPERS
f2de5a5640405d070541edf936a77e7699dc9a2a
eb588f91afa14ddb027d28cbc883e8e472a076f6
/Bohyoh/VerId/VerId.h
59dc4a8bd181997411c3bcbe545ed7de352bd94b
[]
no_license
kawauso-github/cpp
1ed8193a3d0727e9bdb23d7e86bff4243770a4c4
4076873463846a0a8e8329f2640b11f3cbe676f7
refs/heads/master
2023-05-28T20:36:27.424677
2021-06-07T08:01:22
2021-06-07T08:01:22
374,580,959
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
387
h
VerId.h
// 検証用・識別番号クラスVerId(ヘッダ部) #ifndef ___Class_VerId #define ___Class_VerId //===== 識別番号クラス =====// class VerId { int id_no; // 識別番号 public: static int counter; // 何番までの識別番号を与えたのか VerId(); // コンストラクタ int id() const; // 識別番号を調べる }; #endif
2737caec642a7c6c411ff2c941908df9e63abba3
328d5d577f15c5927d64c8715dce01766f625d6f
/code/ext/lwpr/src/IPCSEM.h
ccad4e747c83745f0d3d526e13d530d1f4e68922
[ "Apache-2.0" ]
permissive
vintagewang/tuxone
61aa1822cbedc1397753faf74b71ad2ade064316
a7299bcb80647bae0e2fed597f8baffc54b53619
refs/heads/master
2022-05-31T09:45:35.852238
2022-05-27T09:33:59
2022-05-27T09:33:59
4,544,177
20
21
null
2020-01-10T06:49:16
2012-06-04T06:48:38
C++
GB18030
C++
false
false
2,124
h
IPCSEM.h
/** * Copyright 2012 Wangxr, vintage.wang@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef LWPR_IPCSEM_H__ #define LWPR_IPCSEM_H__ #include "LWPRType.h" #include "Exception.h" namespace LWPR { /** * 本文件中提到的信号量都是为读写控制所用 * 分两种类型:正常锁与读写锁 */ class IPCSEM { public: /** * 创建一个信号量,单值信号量 * iswrlock标志是否是读写锁,如果是读写锁,则设置信号量的值为SHRT_MAX * 读锁时减1,写锁时减-SHRT_MAX */ static IPCID_T Create(const IPCKEY_T key, bool iswrlock = false, IPC_CREATE_TYPE_E type = LWPR::CREATE_NEW_ONE, int perm = IPC_DEFAULT_PERM); /** * 根据IPC Key返回相应的IPC ID */ static IPCID_T GetID(const IPCKEY_T key); /** * 销毁一个信号量对象 */ static void Destroy(const IPCID_T id); /** * 加锁信号量 */ static void Lock(const IPCID_T id, bool blocked = true, bool iswrlock = false); /** * 解锁信号量 */ static void Unlock(const IPCID_T id, bool iswrlock = false); /** * 判断信号量是否处于加锁状态 */ static bool IsLocked(const IPCID_T id); }; DEFINE_EXCEPTION(LWPR_IPC_SEM_GET_ERR); DEFINE_EXCEPTION(LWPR_IPC_SEM_RESET_ERR); DEFINE_EXCEPTION(LWPR_IPC_SEM_LOCK_ERR); DEFINE_EXCEPTION(LWPR_IPC_SEM_UNLOCK_ERR); DEFINE_EXCEPTION(LWPR_IPC_SEM_CTL_ERR); DEFINE_EXCEPTION(LWPR_IPC_SEM_LOCKED_BEFORE); DEFINE_EXCEPTION(LWPR_IPC_SEM_NOT_EXIST); }; #endif // end of LWPR_IPCSEM_H__
6e3ca46f47034ca5060d2b19155725c8ae0b5924
4f4d3ec9bca4e2acb085a0c77e5cd3ed1b43b98d
/DP/9251.cpp
b648a2ec51be8d99b72166125d782d3af7e69364
[]
no_license
Jeonghwan-Yoo/BOJ
5293c181e17ea3bcd7f15e3a9e1df08d3a885447
5f2018106a188ce36b15b9ae09cf68da4566ec99
refs/heads/master
2021-03-05T02:36:45.338480
2021-01-20T12:43:40
2021-01-20T12:43:40
246,088,916
0
0
null
null
null
null
UTF-8
C++
false
false
644
cpp
9251.cpp
#include <iostream> #include <string> #include <algorithm> using namespace std; int dp[2][1'001]; int main() { freopen("in.txt", "r", stdin); ios::sync_with_stdio(false); cin.tie(nullptr); string s1, s2; cin >> s1 >> s2; int n = (int)s1.size(); int m = (int)s2.size(); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (s1[i - 1] == s2[j - 1]) dp[i & 1][j] = dp[(i - 1) & 1][j - 1] + 1; else dp[i & 1][j] = max(dp[(i - 1) & 1][j], dp[i & 1][j - 1]); } } cout << dp[n & 1][m]; return 0; }
e0eda6fd5a360f412bbef983dbd3c0664fb06932
eb21836432b85b049e65fcd59cf4ee4445fe1546
/simulator/mainform.h
50ace5c791faf5cb975daa7b77865c34170d9fc5
[]
no_license
Liufengxuan/Simulator
d8238ad68f64e38649acaa024150b56351e45e5a
4c681c145df4d1f21e38d6eb32db8ebcd930a690
refs/heads/main
2023-08-03T10:18:29.679748
2021-09-14T02:32:42
2021-09-14T02:32:42
394,601,479
0
0
null
null
null
null
UTF-8
C++
false
false
5,298
h
mainform.h
#ifndef MAINFROM_H #define MAINFROM_H #include <QWidget> #include <xmlparsing.h> #include"ncparsing.h" #include "simworker.h" #include "ui_mainfrom.h" #include<qmessagebox.h> #include <QThread> #include <QPainter> #include <QPointF> #include <QMouseEvent> #include <QtGlobal> #include"math.h" //#include "simparameter.h"; #include "qfont.h" #include"qmessagebox.h" using namespace NcCode; using namespace Parameters; using namespace Simulator; namespace Ui { class MainForm; } class MainForm : public QWidget { Q_OBJECT public: explicit MainForm(QWidget *parent = nullptr); ~MainForm(); protected: void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); void wheelEvent(QWheelEvent *event); void paintEvent(QPaintEvent *event); void showEvent(QShowEvent *event); void DrawDatumPoint(QPainter &painter); void DrawDrills(QPainter &painter); void DrawClamp(QPainter &painter); void DrawWord(QPainter &painter); void DrawPart(QPainter &painter); void DrawSideView(QPainter &painter,m_Drill *drill); private: Ui::MainForm *ui; QThread *workThread; Simulator::SimWorker *simWork; QMap<QString,float> REAL_TIME_POS; QStringList REAL_M_T_CODE; public: int parm_argc; char **parm_argv; protected: float zoom=0.5; float oldZoom=1.0; QPointF mousePos; QPointF LeftTopPos;//绘图的实时原点 QPixmap tempPix;//缓冲图片 bool moveButtonPress=false;//拖动按钮按下 ///是否允许绘图 bool ALLOW_PAINT=false; ///最大缩放比 float ZOOM_MAX=4.0; ///最小缩放比 float ZOOM_MIN=0.2; ///缩放步进值 float STEP_VALUE=0.1; ///Π float PI=3.14159265; bool ANTI_ALIASING=false;//抗锯齿 Qt::GlobalColor BACK_COLOR=Qt::black;//背景色 ///Y轴镜像 bool MIRROR_Y_AXIS=false; ///窗口初始大小 QSize INIT_FORM_SIZE=QSize(1366,900); ///默认画笔 QPen DEFAULT_PEN=QPen(Qt::white,1,Qt::PenStyle::SolidLine); QBrush DEFAULT_BRUSH=QBrush(Qt::white,Qt::NoBrush); ///坐标系线段长度 float COOR_LEN=120; ///夹钳滑轨长度 float SLIDE_RAIL=3000; ///夹钳滑轨宽度 float SLIDE_RAIL_WIDTH=30; ///壕沟长度 float TRENCH_LEN=1200; ///夹钳滑轨画笔 QPen SLIDE_RAIL_PEN=QPen(QColor(105,105,105),1,Qt::PenStyle::SolidLine); QBrush SLIDE_RAIL_BRUSH=QBrush(QColor(70,70,70),Qt::SolidPattern); ///坐标系的画笔 QPen COOR_PEN=QPen(QColor(0,255,0),2,Qt::PenStyle::SolidLine); ///钻头打出时的笔和画刷 QPen DRILL_DOWN_PEN=QPen(QColor(255,0,0),1.5,Qt::PenStyle::SolidLine); QBrush DRILL_DOWN_BRUSH=QBrush(QColor(255,0,0),Qt::NoBrush); ///垂直钻收回时的颜色 QPen VER_DRILL_PEN=QPen(QColor(0,245,255),1,Qt::PenStyle::SolidLine); ///水平钻收回时的颜色 QPen HOR_DRILL_PEN=QPen(QColor(0,255,127),1,Qt::PenStyle::SolidLine); ///压料收回时的颜色 QPen PRESS_PEN=QPen(QColor(255,215,0),1,Qt::PenStyle::SolidLine); QBrush PRESS_DOWN_BRUSH=QBrush(QColor(255,215,0),Qt::Dense6Pattern); ///板子的颜色 QPen PANEL_PEN=QPen(QColor(220,220,220),1,Qt::PenStyle::SolidLine); QBrush PANEL_BRUSH=QBrush(QColor(160,82,45),Qt::SolidPattern); ///正面和反面孔的颜色 // QPen MACHINE_FRONT_PEN=QPen(Qt::white,1,Qt::PenStyle::SolidLine); // QPen MACHINE_BACK_PEN=QPen(Qt::blue,1,Qt::PenStyle::SolidLine); QBrush MACHINE_FRONT_Brush=QBrush(QColor(186, 186, 186),Qt::SolidPattern); QBrush MACHINE_BACK_Brush=QBrush(Qt::blue,Qt::SolidPattern); ///夹钳的画笔 QPen CLAMP_OPEN_PEN=QPen(QColor(220,220,220),1,Qt::PenStyle::SolidLine); QBrush CLAMP_CLOSE_BRUSH=QBrush(QColor(105,105,105),Qt::SolidPattern); const QString VER_DRILL="VerDrill";//垂直钻 const QString HOR_LEFT_DIRECTION="HorLeftDirection";// 水平向左 const QString HOR_RIGHT_DIRECTION="HorRightDirection";// 水平向右 const QString HOR_UP_DIRECTION="HorUpDirection";// 水平向上 const QString HOR_DOWN_DIRECTION="HorDownDirection";//水平向下 const QString SPINDLE="Spindle";//主轴 const QString SAW="Saw";//锯片 const QString VERTICAL_ROLLER="VerticalRoller";//垂直压轮 const QString VERTICAL_CLAMP="VerticalClamp";//垂直压料 const QString HORIZONTAL_CLAMP="HorizontalClamp";//水平压料 const QString HORIZONTAL_ROLLER="HorizontalRoller";//水平压轮 const QString MAIN_PRESS="MainPress";//主轴压料 const QString UNDERLAY="Underlay";//下托料 ///水平钻长度 const float HOR_DRILL_LEN=60; const QString PACKAGE_TOP1="Top1";//Y1 const QString PACKAGE_TOP2="Top2";//Y3 const QString PACKAGE_BOTTOM1="Bottom1";//Y2 const QString PACKAGE_BOTTOM_MAIN="BottomMain"; const QString PACKAGE_TOPMAIN="TopMain"; const QFont WORD_FONT=QFont("Consoles",14,QFont::Normal,false); private slots: void Sim_Handle(QMap<QString,float> pos,const NCCommand* nc,QStringList mAndTCode); void btn_start_clicked(); void btn_stop_clicked(); void btn_reset_clicked(); void EditSimSpeed(int); signals: void doWork(int); }; #endif // MAINFROM_H
0593244b7dd4d583d164f62fd5ad8ac7cc76d1a0
9943350b9dd994b3ceb5c78a66667316e3cecd8d
/db2/quiz2/gen.cc
3e65a34c8f1f663c9502045f72c6ec0a9f3d743a
[]
no_license
mimizunohimono/myBackup
a4dc4150f54feeab0ca44ab74c3ca8a73d05d16c
f52e0e06edf137efefe2af5c17d425ec8dada37d
refs/heads/master
2021-01-20T12:38:17.020394
2014-12-27T20:08:48
2014-12-27T20:08:48
30,452,940
0
0
null
null
null
null
UTF-8
C++
false
false
823
cc
gen.cc
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <pthread.h> #include <iostream> #include "debug.h" using namespace std; typedef struct _TUPLE { int key; int val; } TUPLE; int main(int argc, char *argv[]) { if (argc != 2) { cout << "Usage: program numberOfTuples" << endl; exit(1); } int fd; TUPLE t; int max = atoi(argv[1]); fd = open("R", O_WRONLY|O_CREAT|O_TRUNC|O_APPEND, 0644); if (fd == -1) ERR; for (int i = 0; i < max; i++) { t.key = i; t.val = i; write(fd, &t, sizeof(TUPLE)); } close(fd); fd = open("S", O_WRONLY|O_CREAT|O_TRUNC|O_APPEND, 0644); if (fd == -1) ERR; for (int i = 0; i < max; i++) { t.key = i; if (i < 1000) t.val = i; else t.val = max; write(fd, &t, sizeof(TUPLE)); } close(fd); }