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
b889d22b3474ba2421b9d3c1ca11fe61deb09319
3e644fa536a60c449ed44c674ec437c10d4e74bf
/WorldBuildingModule/OpenSimScene/OpenSimSceneExporter.cpp
9dfaf05c5b4f4510842a99b562890078a86799df
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jarmovh/naali
3a29a2baff715637a0986ed56d3f6e433772f9e2
bcbd92499cdbb6e891774a4694a150bf06499e22
refs/heads/master
2021-01-09T05:40:50.550403
2011-08-12T05:42:22
2011-08-12T05:42:22
1,462,841
0
0
null
null
null
null
UTF-8
C++
false
false
34,466
cpp
OpenSimSceneExporter.cpp
// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "OpenSimSceneExporter.h" #include "OpenSimSceneService.h" #include "WorldBuildingModule.h" #include "SceneParser.h" #include "UiServiceInterface.h" #include "UiProxyWidget.h" #include "TextureServiceInterface.h" #include "TextureResource.h" #include "OgreImage.h" #include <QHash> #include <QSet> #include <QDateTime> #include <QFile> #include <QFileInfo> #include <QImage> #include <QFileDialog> #include <QMessageBox> #include <QGraphicsScene> #include <QCryptographicHash> #include <QUrl> #include <QMessageBox> namespace WorldBuilding { SceneExporter::SceneExporter(QObject *parent, Foundation::Framework *framework, SceneParser *scene_parser) : QObject(parent), framework_(framework), scene_parser_(scene_parser), backup_widget_(new QWidget()), backup_proxy_(0), backup_button_enabled_(false) { ui_.setupUi(backup_widget_); connect(ui_.button_do_backup, SIGNAL(clicked()), SLOT(StartBackup())); connect(ui_.button_browse_location, SIGNAL(clicked()), SLOT(BrowseStoreLocation())); connect(backup_widget_, SIGNAL(destroyed(QObject*)), SLOT(InternalDestroyed(QObject*))); backup_meshes_ = true; backup_textures_ = true; backup_animations_ = true; backup_particles_ = true; backup_sounds_ = true; } SceneExporter::~SceneExporter() { if (backup_proxy_) { UiServiceInterface *ui = framework_->GetService<UiServiceInterface>(); if (ui) { backup_proxy_->hide(); ui->RemoveWidgetFromScene(backup_proxy_); } } if (backup_widget_) backup_widget_->deleteLater(); } void SceneExporter::InternalDestroyed(QObject *object) { backup_widget_ = 0; } void SceneExporter::PostInitialize() { UiServiceInterface *ui = framework_->GetService<UiServiceInterface>(); if (ui) { backup_proxy_ = ui->AddWidgetToScene(backup_widget_); backup_widget_->hide(); } else WorldBuildingModule::LogWarning("OpenSimSceneService: Failed to add OpenSim Scene Tool to scene and menu"); } void SceneExporter::ShowBackupTool() { OpenSimSceneService* scene_service = qobject_cast<OpenSimSceneService*>(parent()); if (scene_service) scene_service->BackupToolButtonEnableRequest(); if (!backup_proxy_) return; if (backup_proxy_->scene()->isActive() && !backup_proxy_->isVisible()) backup_proxy_->show(); } void SceneExporter::BrowseStoreLocation() { QString location = QFileDialog::getExistingDirectory(backup_widget_, "Browse Store Location"); if (location.isEmpty()) return; ui_.lineedit_store_location->setText(location); } void SceneExporter::StartBackup() { if (!backup_button_enabled_) { QMessageBox* message = new QMessageBox("Accecc denied", "You don't have permission to excecute this command.", QMessageBox::Critical, QMessageBox::Ok, 0, 0, 0); message->show(); return; } backup_meshes_ = ui_.meshCheckBox->isChecked(); backup_textures_ = ui_.texturesCheckBox->isChecked(); backup_animations_ = ui_.animationsCheckBox->isChecked(); backup_particles_ = ui_.particleScriptsCheckBox->isChecked(); backup_sounds_ = ui_.soundsCheckBox->isChecked(); QString input_location = ui_.lineedit_store_location->text(); if (input_location.isEmpty()) { QMessageBox::information(backup_widget_, "Invalid directory", "Given store directory is a empty string."); return; } QDir store_dir(input_location); if (!store_dir.exists()) { QMessageBox::information(backup_widget_, "Invalid directory", "Given store directory does not exist"); return; } QUrl store_url(ui_.lineedit_base_url->text(), QUrl::TolerantMode); if (!store_url.isValid()) { QMessageBox::information(backup_widget_, "Invalid URL", "Given asset base URL is invalid."); return; } QString base_url = store_url.toString().toLower(); if (base_url.endsWith("/")) base_url = base_url.left(base_url.length()-1); ui_.log->clear(); StoreSceneAndAssets(store_dir, base_url); } void SceneExporter::LogHeadline(const QString &bold, const QString &msg) { ui_.log->appendHtml(QString("<b>%1</b> %2").arg(bold, msg)); } void SceneExporter::Log(const QString &message) { ui_.log->appendHtml(message); } void SceneExporter::LogLineEnd() { ui_.log->appendPlainText(" "); } void SceneExporter::StoreSceneAndAssets(QDir store_location, const QString &asset_base_url) { WorldBuildingModule::LogDebug(QString("SceneExport: Storing scene with assets to %1 with asset base url %2").arg(store_location.absolutePath(),asset_base_url).toStdString().c_str()); QString filename = store_location.absolutePath() + "/scene.xml"; QString subfolder, asset_type; LogHeadline("Asset base URL :", asset_base_url); LogHeadline("Store directory :", store_location.absolutePath()); // Cleanup target directory CleanLocalDir(store_location); // Needed data QSet<QString> *mesh_ref_set = new QSet<QString>(); QSet<QString> *animation_ref_set = new QSet<QString>(); QSet<QString> *particle_ref_set = new QSet<QString>(); QSet<QString> *sound_ref_set = new QSet<QString>(); QHash<QString, uint> *material_ref_set = new QHash<QString, uint>(); QHash<QString, QString> old_to_new_references; // Pass storage containers for scene parser scene_parser_->mesh_ref_set = mesh_ref_set; scene_parser_->animation_ref_set = animation_ref_set; scene_parser_->material_ref_set = material_ref_set; scene_parser_->particle_ref_set = particle_ref_set; scene_parser_->sound_ref_set = sound_ref_set; // Parse scene, this will populate our sets Log("-- Iterating all entities for export"); LogLineEnd(); QByteArray scene_data = scene_parser_->ExportSceneXml(); // Meshes if (backup_meshes_) { asset_type = "Mesh"; subfolder = "meshes"; old_to_new_references.unite(ProcessAssetsRefs(store_location, asset_base_url, subfolder, asset_type, mesh_ref_set)); } else Log("-- Skipping mesh export"); // Animations if (backup_animations_) { asset_type = "Skeleton"; subfolder = "animations"; old_to_new_references.unite(ProcessAssetsRefs(store_location, asset_base_url, subfolder, asset_type, animation_ref_set)); } else Log("-- Skipping animation export"); // Sound if (backup_sounds_) { asset_type = "SoundVorbis"; subfolder = "audio"; old_to_new_references.unite(ProcessAssetsRefs(store_location, asset_base_url, subfolder, asset_type, sound_ref_set)); } else Log("-- Skipping sound export"); // Material/texture processing if (backup_textures_) { QDir store_location_textures(store_location); store_location_textures.mkdir("textures"); asset_type = "MaterialScript"; subfolder = "scripts"; store_location.mkdir(subfolder); if (store_location.cd(subfolder) && store_location_textures.cd("textures")) { WorldBuildingModule::LogDebug("SceneExport: Processing textures and materials"); LogHeadline("Processing", "textures and materials"); CleanLocalDir(store_location_textures); CleanLocalDir(store_location); Log("-- Parsing material scripts to resolve texture references"); int found_tex = 0; int found_mat = 0; int failed_tex = 0; int failed_mat = 0; int not_found_tex = 0; int not_found_mat = 0; int replaced_material_texture_refs = 0; Foundation::TextureServiceInterface *texture_service = framework_->GetService<Foundation::TextureServiceInterface>(); if (texture_service) { foreach (QString mat_ref, material_ref_set->keys()) { uint mat_type = material_ref_set->value(mat_ref); // Texture if (mat_type == 0) { QString replace_url = TryStoreTexture(mat_ref, store_location_textures, asset_base_url); if (!replace_url.isEmpty() && replace_url != "DYNAMIC_TEXTURE_CREATION_FAILED") { old_to_new_references[mat_ref] = replace_url; found_tex++; } else if (replace_url == "DYNAMIC_TEXTURE_CREATION_FAILED") failed_tex++; else if (replace_url.isEmpty()) not_found_tex++; } // Material script else if (mat_type == 45) { QString cache_path = GetCacheFilename(mat_ref, asset_type); if (QFile::exists(cache_path)) { QString file_only = cache_path.split("/").last().toLower(); if (file_only.isEmpty()) continue; if (file_only.endsWith(".materialscript")) file_only.replace(".materialscript", ".material"); store_location.remove(file_only); QString new_filename = store_location.absoluteFilePath(file_only); if (QFile::copy(cache_path, new_filename)) { old_to_new_references[mat_ref] = asset_base_url + "/scripts/" + file_only; found_mat++; // Replace all texture refs inside material scipts int replaced = ReplaceMaterialTextureRefs(store_location_textures, asset_base_url, new_filename); replaced_material_texture_refs += replaced; } else { WorldBuildingModule::LogError(">> Failed to copy " + file_only.toStdString()); failed_mat++; } } else not_found_mat++; } else WorldBuildingModule::LogWarning(">> Skipping due unknown type for material/texture: " + QString::number(mat_type).toStdString()); } // Report findings WorldBuildingModule::LogDebug("SceneExport: Textures"); LogLineEnd(); LogHeadline("Textures"); if (not_found_tex > 0 || failed_tex > 0) { WorldBuildingModule::LogDebug(">> Found : " + QString::number(found_tex).toStdString()); WorldBuildingModule::LogDebug(">> Not Found : " + QString::number(not_found_tex).toStdString()); WorldBuildingModule::LogDebug(">> Failed : " + QString::number(failed_tex).toStdString()); LogHeadline(">> Found :", QString::number(found_tex)); LogHeadline(">> Not Found :", QString::number(not_found_tex)); LogHeadline(">> Failed :", QString::number(failed_tex)); } else if (not_found_tex == 0 && failed_tex == 0 && found_tex == 0) { WorldBuildingModule::LogDebug(">> There were no textures in this scene"); } else if (not_found_tex == 0 && failed_tex == 0 && found_tex > 0) { WorldBuildingModule::LogDebug(">> All Found : " + QString::number(found_tex).toStdString()); LogHeadline(">> All found :", QString::number(found_tex)); } WorldBuildingModule::LogDebug("SceneExport: Materials"); LogLineEnd(); LogHeadline("Materials"); if (not_found_mat > 0 || failed_mat > 0) { WorldBuildingModule::LogDebug(">> Found : " + QString::number(found_mat).toStdString()); WorldBuildingModule::LogDebug(">> Not Found : " + QString::number(not_found_mat).toStdString()); WorldBuildingModule::LogDebug(">> Failed : " + QString::number(failed_mat).toStdString()); LogHeadline(">> Found :", QString::number(found_mat)); LogHeadline(">> Not Found :", QString::number(not_found_mat)); LogHeadline(">> Failed :", QString::number(failed_mat)); } else if (not_found_mat == 0 && failed_mat == 0 && found_mat == 0) { WorldBuildingModule::LogDebug(">> There were no matrial scripts in this scene"); } else if (not_found_mat == 0 && failed_mat == 0 && found_mat > 0) { WorldBuildingModule::LogDebug(">> All Found : " + QString::number(found_mat).toStdString()); LogHeadline(">> All Found :", QString::number(found_mat)); } LogHeadline(">> Replaced texture references:" , QString::number(replaced_material_texture_refs)); } else WorldBuildingModule::LogError(">> Texture service not accessible, aborting processing"); store_location.cdUp(); } else WorldBuildingModule::LogError(">> Failed to create textures and scripts folders, aborting processing"); LogLineEnd(); } else Log("-- Skipping texture and material script export"); // Particle processing if (backup_particles_) { asset_type = "ParticleScript"; subfolder = "scripts"; old_to_new_references.unite(ProcessAssetsRefs(store_location, asset_base_url, subfolder, asset_type, particle_ref_set)); } else Log("-- Skipping particle script export"); // Replace old references references QString new_ref; WorldBuildingModule::LogDebug("SceneExport: Replacing old asset refs with base URL " + asset_base_url.toStdString()); LogLineEnd(); Log("Replacing all old references using given base URL"); foreach(QString old_ref, old_to_new_references.keys()) { new_ref = old_to_new_references[old_ref]; scene_data.replace(old_ref, new_ref.toStdString().c_str()); } // Store scene data to file QFile scene_file(filename); if (scene_file.open(QIODevice::ReadWrite|QIODevice::Text)) { WorldBuildingModule::LogDebug("SceneExport: Writing scene.xml file with new URL refs"); Log("Saving scene.xml"); scene_file.resize(0); // empty content scene_file.write(scene_data); scene_file.close(); } else { WorldBuildingModule::LogError("SceneExport: Failed to open output file, coult not write XML."); LogHeadline("Failed to write scene.xml - I/O error!"); } // Cleanup scene_parser_->mesh_ref_set = 0; scene_parser_->animation_ref_set = 0; scene_parser_->material_ref_set = 0; scene_parser_->particle_ref_set = 0; scene_parser_->sound_ref_set = 0; mesh_ref_set->clear(); material_ref_set->clear(); animation_ref_set->clear(); particle_ref_set->clear(); sound_ref_set->clear(); SAFE_DELETE(mesh_ref_set); SAFE_DELETE(material_ref_set); SAFE_DELETE(animation_ref_set); SAFE_DELETE(particle_ref_set); SAFE_DELETE(sound_ref_set); WorldBuildingModule::LogDebug("SceneExport: Scene backup with assets done"); LogHeadline("Done"); } QHash<QString, QString> SceneExporter::ProcessAssetsRefs(QDir store_location, const QString &asset_base_url, const QString &subfolder, const QString &asset_type, QSet<QString> *ref_set) { QHash<QString, QString> ref_to_file; store_location.mkdir(subfolder); if (store_location.cd(subfolder)) { WorldBuildingModule::LogDebug("SceneExport: Processing " + subfolder.toStdString()); LogHeadline("Processing ", subfolder + " / " + asset_type); if (asset_type != "ParticleScript") CleanLocalDir(store_location); // Copy from cache to target dir int copied = 0; int not_found = 0; int failed = 0; int replaced = -1; foreach(QString ref, *ref_set) { QString cache_path = GetCacheFilename(ref, asset_type); if (QFile::exists(cache_path)) { QString file_only = cache_path.split("/").last().toLower(); if (file_only.isEmpty()) { failed++; continue; } if (file_only.endsWith(".particlescript")) file_only.replace(".particleScript", ".particle"); if (file_only.endsWith(".soundvorbis")) file_only.replace(".soundvorbis", ".ogg"); store_location.remove(file_only); QString new_filename = store_location.absoluteFilePath(file_only); if (QFile::copy(cache_path, new_filename)) { ref_to_file[ref] = asset_base_url + "/" + subfolder + "/" + file_only; copied++; if (asset_type == "ParticleScript") { if (replaced == -1) replaced = 0; int replaced_count = ReplaceParticleMaterialRefs(store_location, asset_base_url, new_filename); replaced += replaced_count; } } else { WorldBuildingModule::LogError(">> Failed to copy " + file_only.toStdString()); failed++; } } else not_found++; } // Report findings if (not_found > 0 || failed > 0) { WorldBuildingModule::LogDebug(">> Found : " + QString::number(copied).toStdString()); WorldBuildingModule::LogDebug(">> Not Found : " + QString::number(not_found).toStdString()); WorldBuildingModule::LogDebug(">> Failed : " + QString::number(failed).toStdString()); LogHeadline(">> Found :", QString::number(copied)); LogHeadline(">> Not Found :", QString::number(not_found)); LogHeadline(">> Failed :", QString::number(failed)); } else if (not_found == 0 && failed == 0 && copied > 0) { WorldBuildingModule::LogDebug(">> All Found : " + QString::number(copied).toStdString()); LogHeadline(">> All Found :", QString::number(copied)); } else if (not_found == 0 && failed == 0 && copied == 0) { WorldBuildingModule::LogDebug(">> There was no " + subfolder.toStdString() + " in this scene"); Log(QString(">> There was no %1 in the scene").arg(subfolder)); } if (replaced >= 0) { LogHeadline(">> Replaced material references:", QString::number(replaced)); } // Remove the dir if its empty if (copied == 0) { store_location.cdUp(); store_location.rmdir(subfolder); } else store_location.cdUp(); } else WorldBuildingModule::LogError(">> Failed to create " + subfolder.toStdString() + " folder, aborting processing"); LogLineEnd(); return ref_to_file; } int SceneExporter::ReplaceMaterialTextureRefs(const QDir &store_location_textures, const QString &asset_base_url, const QString &material_file_path) { QString KEYWORD = "texture "; QHash<QString, QString> old_to_new_ref; QFile material_file(material_file_path); if (material_file.open(QIODevice::ReadWrite|QIODevice::Text)) { QByteArray content = material_file.readAll(); content.replace('\t', " "); content = content.trimmed(); QString replace_url = ""; QString texture_ref = ""; int i_start = content.indexOf(KEYWORD); while (i_start != -1) { i_start += QString(KEYWORD).length(); int i_end_space = content.indexOf(" ", i_start); int i_end_endl = content.indexOf('\n', i_start); // If either was not found if (i_end_space == -1 && i_end_endl == -1) { i_start = content.indexOf(KEYWORD, i_start); continue; } // Make the ' ' or '\n' the end index, which one is lower int i_end = i_end_endl; if (i_end_space > 0) if (i_end_space < i_end) i_end = i_end_space; if (i_end != -1) { int ref_len = i_end - i_start; QByteArray texture_ref_b = content.mid(i_start, ref_len); texture_ref = QString(texture_ref_b); // Try to get the texture from texture cache and store it to our texture location with qt or ogre // depending on the pixel format and components replace_url = TryStoreTexture(texture_ref, store_location_textures, asset_base_url); if (!replace_url.isEmpty() && replace_url != "DYNAMIC_TEXTURE_CREATION_FAILED") old_to_new_ref[texture_ref] = replace_url; } // Look for the next texture i_start = content.indexOf(KEYWORD, i_start); } // If the texture could be replicated to our export location, replace the old refs with our new url ref if (old_to_new_ref.count() > 0) { foreach(QString old_ref, old_to_new_ref.keys()) { QByteArray new_ref(old_to_new_ref[old_ref].toStdString().c_str()); content.replace(QByteArray(old_ref.toStdString().c_str()), new_ref); } material_file.resize(0); material_file.write(content); } material_file.close(); } else WorldBuildingModule::LogDebug("SceneExport: Could not open copied material script"); return old_to_new_ref.count(); } int SceneExporter::ReplaceParticleMaterialRefs(const QDir store_location_particles, const QString &asset_base_url, const QString &particle_file_path) { bool overwrite = false; int replaced = 0; QString old_ref; QString new_ref; QDir texture_location(store_location_particles); texture_location.cdUp(); texture_location.cd("textures"); QFile particle_file(particle_file_path); if (particle_file.open(QIODevice::ReadWrite|QIODevice::Text)) { QByteArray content = particle_file.readAll(); content.replace('\t', " "); content = content.trimmed(); QString replace_url = ""; QString texture_ref = ""; int i_start = content.indexOf("material "); if (i_start != -1) { i_start += QString("material ").length(); int i_end_space = content.indexOf(" ", i_start); int i_end_endl = content.indexOf('\n', i_start); // If either was not found if (i_end_space == -1 && i_end_endl == -1) return 0; // Make the ' ' or '\n' the end index, which one is lower int i_end = i_end_endl; if (i_end_space > 0) if (i_end_space < i_end) i_end = i_end_space; if (i_end != -1) { int ref_len = i_end - i_start; QByteArray material_ref_b = content.mid(i_start, ref_len); old_ref = QString(material_ref_b); QString cache_file = GetCacheFilename(old_ref, "MaterialScript"); QString file_only = cache_file.split("/").last().toLower(); file_only.replace(".materialscript", ".material"); // 1. Check from our store location if this material script was already // moved and its textures replaced inside. This is the ideal case if (store_location_particles.exists(file_only)) { new_ref = asset_base_url + "/scripts/" + file_only; overwrite = true; } // 2. Check the cache if this material is in there. If found // we have to replace the textures and move it to our scripts location else { if (QFile::exists(cache_file)) { QString new_material_path = store_location_particles.absoluteFilePath(file_only); if (QFile::copy(cache_file, new_material_path)) { new_ref = asset_base_url + "/scripts/" + file_only; overwrite = true; ReplaceMaterialTextureRefs(texture_location, asset_base_url, new_material_path); } } // 3. Check if this "material" is really a texture. There is a mechanish in naali and the legacy // viewer to accept textures here too. It will generate a fullbringht material with that texture dynamically. else { QString replace_url = TryStoreTexture(old_ref, texture_location, asset_base_url); if (!replace_url.isEmpty() && replace_url != "DYNAMIC_TEXTURE_CREATION_FAILED") { new_ref = replace_url; overwrite = true; } } } } } if (overwrite) { content.replace(QByteArray(old_ref.toStdString().c_str()), QByteArray(new_ref.toStdString().c_str())); particle_file.resize(0); particle_file.write(content); replaced++; } particle_file.close(); } return replaced; } QString SceneExporter::TryStoreTexture(const QString &original_ref, const QDir &store_location, const QString &base_url) { QString new_ref = "DYNAMIC_TEXTURE_CREATION_FAILED"; // a bit of a hack, yeah Foundation::TextureServiceInterface *texture_service = framework_->GetService<Foundation::TextureServiceInterface>(); if (!texture_service) return new_ref; TextureDecoder::TextureResource *texture = texture_service->GetFromCache(original_ref.toStdString()); if (texture) { // This will get the original name of a web texture <name>.png // and for UUIDs/other single word id's it will fallback to <UUID>.png QString file_only = QString(texture->GetId().c_str()).split("/").last(); file_only = file_only.split(".").first(); if (file_only.isEmpty()) file_only = QString(texture->GetId().c_str()).split(".").first(); file_only.append(".png"); // New filename in our export location and the url to replace in the material script QString tex_filename = store_location.absoluteFilePath(file_only); QString replace_url = base_url + "/textures/" + file_only; // Read texture resource data int ogre_format = texture->GetFormat(); int comps = texture->GetComponents(); // -1 means jpeg2000, lets use ogre to get the correct pixelformat // as qt does not provide ABGR directly if (ogre_format == -1) { Ogre::Image image; Ogre::PixelFormat ogre_image_format; if (comps == 1) ogre_image_format = Ogre::PF_L8; else if (comps == 2) ogre_image_format = Ogre::PF_BYTE_LA; else if (comps == 3) ogre_image_format = Ogre::PF_B8G8R8; else if (comps == 4) ogre_image_format = Ogre::PF_A8B8G8R8; else { WorldBuildingModule::LogDebug(">> Failed to store material texture with ogre, unhandled comps: " + QString::number(comps).toStdString()); return new_ref; } image.loadDynamicImage(texture->GetData(), texture->GetWidth(), texture->GetHeight(), ogre_image_format); image.save(tex_filename.toStdString()); new_ref = replace_url; } else { // Try to resolce qt format with ogre format QImage::Format qt_format; switch (ogre_format) { case 6: qt_format = QImage::Format_RGB16; break; case 26: qt_format = QImage::Format_RGB32; break; case 12: qt_format = QImage::Format_ARGB32; break; default: qt_format = QImage::Format_Invalid; break; } // If qt format can be used, lets make a qimage out of the data if (qt_format != QImage::Format_Invalid) { QImage image(texture->GetData(), texture->GetWidth(), texture->GetHeight(), qt_format); if (!image.isNull()) { if (image.save(tex_filename, "PNG")) new_ref = replace_url; else WorldBuildingModule::LogDebug(">> Qt failed to store texture as png, skipping texture"); } else WorldBuildingModule::LogDebug(">> Failed to create image from raw texture data, skipping texture"); } else WorldBuildingModule::LogDebug(">> Could not resolve texture format: " + QString::number(ogre_format).toStdString() + ", skipping texture"); } } else return ""; // empty means was not in cache aka "not found" return new_ref; } void SceneExporter::CleanLocalDir(QDir dir) { int deleted = 0; QFileInfoList info_list = dir.entryInfoList(QDir::Files); foreach(QFileInfo file_info, info_list) { if (dir.remove(file_info.fileName())) deleted++; } Log(QString("Cleaned directory: %1 removed %2 files").arg(dir.absolutePath(), QString::number(deleted))); } QString SceneExporter::GetCacheFilename(const QString &asset_id, const QString &type) { std::string temp = asset_id.toStdString(); QCryptographicHash md5_engine(QCryptographicHash::Md5); md5_engine.addData(temp.c_str(), temp.size()); QString md5_hash(md5_engine.result().toHex()); md5_engine.reset(); QString cache_path = framework_->GetPlatform()->GetApplicationDataDirectory().c_str(); cache_path.append("/assetcache/"); cache_path.append(md5_hash); cache_path.append("."); cache_path.append(type); return cache_path; } }
9dfe9d441dd59dc63cfc31172e4e3248919900df
96ba02fd095db9b9ceed80df5d3fef7267473e3d
/src/tracking_node.cpp
3065cad55b35a9fec83927fa0ce0c200efdc87fc
[]
no_license
synioe/xiaoqiang_track
81daf448e01a989b7da6496618445ed74c8bfb1a
164dd5606bf615210b28536fc0fa582c5daa83e0
refs/heads/master
2020-03-22T12:30:40.825159
2018-07-03T01:11:58
2018-07-03T01:11:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,650
cpp
tracking_node.cpp
/****************************************************************************** * * The MIT License (MIT) * * Copyright (c) 2018 Bluewhale Robot * * 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. * * Author: Randoms *******************************************************************************/ #include <opencv2/opencv.hpp> #include <opencv2/tracking.hpp> #include <opencv2/core/ocl.hpp> #include <ros/ros.h> #include <sensor_msgs/Image.h> #include <std_msgs/String.h> #include "baidu_track.h" using namespace cv; using namespace std; using namespace XiaoqiangTrack; sensor_msgs::Image last_frame; Ptr<Tracker> tracker; Rect2d body_rect; ros::Publisher image_pub; BaiduTrack client; sensor_msgs::Image get_one_frame() { return last_frame; } void update_frame(const sensor_msgs::ImageConstPtr &new_frame) { last_frame = *new_frame; return; cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(new_frame, "bgr8"); cv::Mat cv_image = cv_ptr->image; if (tracker == NULL) return; tracker->update(cv_image, body_rect); image_pub.publish(cv_ptr->toImageMsg()); } int main(int argc, char **argv) { ros::init(argc, argv, "xiaoqiang_track_node"); ros::NodeHandle nh; ros::Publisher talk_pub = nh.advertise<std_msgs::String>("~text", 10); // image_pub = nh.advertise<sensor_msgs::Image>("~processed_image", 10); // ros::Subscriber image_sub = nh.subscribe<sensor_msgs::ImageConstPtr>("~image", 10, &update_frame); // // 告诉用户站在前面 // std_msgs::String words; // words.data = "请站在我前面"; // talk_pub.publish(words); // // 提醒用户调整好距离 // sensor_msgs::Image frame = get_one_frame(); // body_rect.x = -1; // body_rect.y = -1; // while (1) // { // if (frame.data.size() != 0) // { // std::vector<int> rect = client.getBodyRect(frame); // if (rect.size() == 0) // { // words.data = "我没有看到人,请站到我前面"; // talk_pub.publish(words); // sleep(4); // } // else if (body_rect.x + body_rect.width / 2 > 370 || body_rect.x - body_rect.width / 2 < 270) // { // body_rect.x = rect[0]; // body_rect.y = rect[1]; // body_rect.width = rect[2]; // body_rect.height = rect[3]; // words.data = "请站到镜头中间来"; // talk_pub.publish(words); // sleep(4); // } // } // sleep(4); // frame = get_one_frame(); // } }
965e0f4f80ccc77a37979303233929296776df9e
b7461f820e656a5414c16db21e566148d165709c
/CalibrateCamera.h
c76b1ff39cd219810f73b0f5f8850dcbd1ab6d63
[]
no_license
DSC2035/VHeightProjective
7507d19fba145ddce60c8d473520531fac1c0a63
dafeadd387fe191a1153c2eabeba8110ec44a13c
refs/heads/master
2021-01-23T03:53:06.503352
2017-08-10T02:51:06
2017-08-10T02:51:06
86,129,876
1
0
null
null
null
null
UTF-8
C++
false
false
215
h
CalibrateCamera.h
#pragma once #include "FunctorClassI.h" class CalibrateCamera : public FunctorClassI { public: CalibrateCamera(); ~CalibrateCamera(); virtual const char* GetDescription(); virtual void Run(); };
9766914ffc0855177868e0b9e69b50b3335d9f2b
04b1803adb6653ecb7cb827c4f4aa616afacf629
/ash/wm/workspace/backdrop_delegate.h
bbf3ddf8a10c5f1471922ae83ec33ebc2fd200af
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
788
h
backdrop_delegate.h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_WM_WORKSPACE_WORKSPACE_LAYOUT_MANAGER_BACKDROP_DELEGATE_H_ #define ASH_WM_WORKSPACE_WORKSPACE_LAYOUT_MANAGER_BACKDROP_DELEGATE_H_ #include "ash/ash_export.h" namespace aura { class Window; } namespace ash { // A delegate which can be set to create and control a backdrop which gets // placed below the top level window. class ASH_EXPORT BackdropDelegate { public: virtual ~BackdropDelegate() {} // Returns true if |window| should have a backdrop. virtual bool HasBackdrop(aura::Window* window) = 0; }; } // namespace ash #endif // ASH_WM_WORKSPACE_WORKSPACE_LAYOUT_MANAGER_BACKDROP_DELEGATE_H_
eeddbf1237416a26bf530678eeec758bf9d2f54d
56158f389e97c9d2b0592b99fc76964bc3bcb5a1
/libraries/TGRSIAnalysis/TEmma/LinkDef.h
af8d50f263029d62789d8524c1316d07b3b8907e
[]
no_license
GRIFFINCollaboration/GRSIData
48cb16563bdd8626f29ddb55522db1452d175bb0
b6206a400453a92b19e338421e32818931f42153
refs/heads/main
2023-06-09T16:12:02.310812
2023-05-31T19:58:03
2023-05-31T19:58:03
145,007,439
2
11
null
2023-05-31T19:58:04
2018-08-16T15:35:09
C++
UTF-8
C++
false
false
289
h
LinkDef.h
//TEmma.h TEmmaHit.h #ifdef __CINT__ #pragma link off all globals; #pragma link off all classes; #pragma link off all functions; #pragma link C++ nestedclasses; #pragma link C++ class TEmmaHit+; #pragma link C++ class std::vector<TEmmaHit>+; #pragma link C++ class TEmma+; #endif
94f0b67df9392b6a1b07afc7336931582a5e9dc6
4749b64b52965942f785b4e592392d3ab4fa3cda
/content/shell/browser/shell_notification_manager.h
7520d15e67829d01938134ba6c7800efd4cb9786
[ "BSD-3-Clause" ]
permissive
crosswalk-project/chromium-crosswalk-efl
763f6062679727802adeef009f2fe72905ad5622
ff1451d8c66df23cdce579e4c6f0065c6cae2729
refs/heads/efl/crosswalk-10/39.0.2171.19
2023-03-23T12:34:43.905665
2014-12-23T13:44:34
2014-12-23T13:44:34
27,142,234
2
8
null
2014-12-23T06:02:24
2014-11-25T19:27:37
C++
UTF-8
C++
false
false
1,666
h
shell_notification_manager.h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_SHELL_BROWSER_SHELL_NOTIFICATION_MANAGER_H_ #define CONTENT_SHELL_BROWSER_SHELL_NOTIFICATION_MANAGER_H_ #include <map> #include "base/callback.h" #include "third_party/WebKit/public/platform/WebNotificationPermission.h" #include "url/gurl.h" namespace content { // Responsible for tracking active notifications and allowed origins for the // Web Notification API when running layout tests. The methods in this class // should only be used on the IO thread. class ShellNotificationManager { public: ShellNotificationManager(); ~ShellNotificationManager(); // Checks whether |origin| has permission to display notifications in tests. blink::WebNotificationPermission CheckPermission( const GURL& origin); // Requests permission for |origin| to display notifications in layout tests. void RequestPermission( const GURL& origin, const base::Callback<void(blink::WebNotificationPermission)>& callback); // Sets the permission to display notifications for |origin| to |permission|. void SetPermission(const GURL& origin, blink::WebNotificationPermission permission); // Clears the currently granted permissions. void ClearPermissions(); private: typedef std::map<GURL, blink::WebNotificationPermission> NotificationPermissionMap; NotificationPermissionMap permission_map_; DISALLOW_COPY_AND_ASSIGN(ShellNotificationManager); }; } // content #endif // CONTENT_SHELL_BROWSER_SHELL_NOTIFICATION_MANAGER_H_
26fc9fba5626e0a534767712d241ff6afcd6a9a6
aab3a814eb3086dcba0e4474cda4434453c78246
/src/MainForms/DateCountTabWidget.h
ef869bb08dd26be1306dd81e3c766601918ac0da
[]
no_license
isliulin/Msigma_DAR
239744e60905a81381c50244dbda1bcce199f725
93b441b2c2c0b2b454f30617319a125022bc5f65
refs/heads/main
2023-08-25T18:20:36.534371
2021-10-13T02:01:53
2021-10-13T02:01:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,151
h
DateCountTabWidget.h
#ifndef DATECOUNTTABWIDGET_H #define DATECOUNTTABWIDGET_H #include <QWidget> #include <QTableWidget> namespace Ui { class DateCountTabWidget; } class ModelBase; class DateCountTabWidget : public QWidget { Q_OBJECT public: explicit DateCountTabWidget(QWidget *parent = nullptr); ~DateCountTabWidget(); void addModelObject(ModelBase *object); std::vector<ModelBase *> modelBases; QAction *getActionState(); int getCount(); std::vector<ModelBase *> getModelBase() { return modelBases; } QTableWidget *getTableWidget(); void addColumnTab(QTableWidget *table); int tableCount = 0; std::vector<QString> strs; std::vector<std::vector<double> > tableValues; void setTableWidgetValue(std::vector<std::vector<double> > values); private slots: void on_tableWidget_customContextMenuRequested(const QPoint &pos); void on_pushButton_3_clicked(bool checked); void on_pushButton_4_clicked(bool checked); void on_pushButton_5_clicked(bool checked); void on_pushButton_6_clicked(bool checked); private: Ui::DateCountTabWidget *ui; }; #endif // DATECOUNTTABWIDGET_H
1a21d5769b845267812b4c97a0388b92bcd491a2
0bc0903fc444257398798e286d96b3ff3fca2901
/src/common/requests/AbstractResponse.h
182171730631f687572ae8a4265039d33788760a
[ "Apache-2.0" ]
permissive
smartdu/kafkaclient-cpp
675bdc7f9ab6a0e7d98511364f85e4932762782b
03d108808a50a13d7a26e63461a1ac27c5bc141c
refs/heads/master
2020-05-18T00:14:17.062934
2019-05-15T03:43:33
2019-05-15T03:43:33
184,055,595
5
1
Apache-2.0
2019-05-13T08:11:57
2019-04-29T11:07:51
C++
UTF-8
C++
false
false
825
h
AbstractResponse.h
#ifndef __KFK_ABSTRACTRESPONSE_H__ #define __KFK_ABSTRACTRESPONSE_H__ #pragma once #include "AbstractRequestResponse.h" #include <map> class Struct; class ResponseHeader; class ApiKeys; class Errors; class AbstractResponse : public AbstractRequestResponse { public: static const int DEFAULT_THROTTLE_TIME = 0; virtual ~AbstractResponse() { } ByteBuffer* serialize(short version, ResponseHeader *responseHeader); virtual std::map<Errors*, int> errorCounts() = 0; static AbstractResponse* parseResponse(ApiKeys *apiKey, Struct *s, short version); protected: std::map<Errors*, int> errorCounts(Errors *error); void updateErrorCounts(std::map<Errors*, int> errorCounts, Errors *error); virtual Struct* toStruct(short version) = 0; }; #endif // !__KFK_ABSTRACTRESPONSE_H__
6b8acc70d37fa9b3653813e8d009aa645aa3a7a1
1388d23b912e9d7e9fe9d4240b339a781822fd6e
/uva572OilDeposits.cpp
db5090479f898dd89f8b72991238aceaf029b5a4
[]
no_license
xiekch/AOAPC2
b15834daec459cf4e033f91cf89d87650952b527
6b371d254c80dae1150ab38d0916559fe6b3980b
refs/heads/master
2020-03-27T08:40:14.974890
2018-08-27T09:28:48
2018-08-27T09:28:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
636
cpp
uva572OilDeposits.cpp
#include<iostream> #include<cstring> using namespace std; const int maxn=1000+5; char graph[maxn][maxn]; int r,c,idx[maxn][maxn],cnt;//index has been used! void dfs(int i,int j,int id) { if(i<0||j<0||i>=r||j>=c)return; if(idx[i][j]||graph[i][j]=='*')return; idx[i][j]=id; for(int m=-1; m<2; m++) for(int n=-1; n<2; n++) if(m!=0||n!=0)dfs(i+m,j+n,id); } int main() { while(cin>>r>>c&&r&&c) { memset(idx,0,sizeof(idx)); for(int i=0; i<r; i++) cin>>graph[i]; cnt=0; for(int i=0; i<r; i++) for(int j=0; j<c; j++) { if(graph[i][j]=='@'&&!idx[i][j]) dfs(i,j,++cnt); } cout<<cnt<<endl; } return 0; }
5ea1d5cea91442b3ff74373a3190bb208e6a87c9
2340859cdfd21ecf9bf5dd3d4dc3304b89ebf115
/dogpack-mapped/lib/3d/cart/DogStateCart3.h
9756f97b91d7629fae00d04b2c8120a9f92ac6f2
[]
no_license
smoe1/ThesisCode
56c97c440f7f8182f5be7dba76848741dcf9a9d6
bd535bc99d0add16787524bd2ac5c4a53f2d86ee
refs/heads/master
2021-01-24T07:18:55.455846
2017-06-07T02:15:40
2017-06-07T02:15:40
93,338,238
0
1
null
null
null
null
UTF-8
C++
false
false
3,059
h
DogStateCart3.h
#ifndef DogStateCart3_h #define DogStateCart3_h #include "DogState.h" class dTensorBC4; class dTensorBC5; class DogSolverCart3; struct DogStateCart3: public DogStateTB { private: dTensorBC5* q; dTensorBC5* aux; private: void init(int mx, int my, int mz); DogStateCart3& operator=(const DogStateCart3& in); // disabled DogSolverCart3& fetch_solver(){return (DogSolverCart3&) DogState::get_solver();} protected: virtual const char* get_classname(){return (const char*) "DogStateCart3";} DogStateCart3(const DogStateCart3&in, CopyMode::Enum copyMode=CopyMode::DEEP); public: // Default constructor: DogStateCart3(): q(NULL), aux(NULL) {}; // Destructor: ~DogStateCart3(); virtual DogState* clone(CopyMode::Enum copyMode)const { return new DogStateCart3(*this, copyMode); } virtual void init(); virtual void copyfrom(const DogStateCart3& in); virtual bool check_valid_state() const; // Reverting to top level debug_check_condition(). // It looks like this was used once to check the posititivy of the // function, which I beleive is now being checked elsewhere. // (-DS, 3/27/2013). // virtual bool debug_check_condition() const; virtual void init_coarser_state(const DogStateCart3& in, int mx, int my, int mz); // write restart frame and movie frames virtual void write_output(int noutput) const; virtual void write_frame(int nframe, const char* outputdir) const; // read (restart) frame virtual void read_frame(int nframe); // accessors (fetch means write-access, get means read-access) // const dTensorBC5& get_q() const{return *q;} const dTensorBC5& get_aux() const{return *aux;} dTensorBC5& fetch_q() {return *q;} dTensorBC5& fetch_aux() {return *aux;} const DogStateCart3& get_solver()const {return (DogStateCart3&) DogState::get_solver();} // -- user "callbacks" -- // // // class methods with the virtual keyword have subclasses that can override // these methods. In other words, EVERY subclass of this class will have // these functions, and can override them. // This function projects initial conditions onto aux and q. virtual void InitState(); virtual void AfterInitState(); virtual void BeforeStage(double dt); virtual void SetBndValues(); virtual void ConstructL(); virtual void ApplyLimiter(); virtual void AfterStage(double dt); virtual void AfterReject(double dt); virtual void AfterFullTimeStep(double dt); virtual void ReportAfterStep() const; }; // low-level methods to write and read state arrays void WriteStateArray(const char* framedir, const char* varname, const dTensorBC4& q, double t, int nframe); double ReadStateArray(const char* dir, const char* varname, dTensorBC4& q, int nstart); #endif
434b24ec8e45d0feff807b51c8b11df7a8386b39
af1f72ae61b844a03140f3546ffc56ba47fb60df
/src/swagger/converters/cpu.hpp
4b798a7f3a76e77f5e32b16911e81669358bd2dd
[ "Apache-2.0" ]
permissive
Spirent/openperf
23dac28e2e2e1279de5dc44f98f5b6fbced41a71
d89da082e00bec781d0c251f72736602a4af9b18
refs/heads/master
2023-08-31T23:33:38.177916
2023-08-22T03:23:25
2023-08-22T07:13:15
143,898,378
23
16
Apache-2.0
2023-08-22T07:13:16
2018-08-07T16:13:07
C++
UTF-8
C++
false
false
852
hpp
cpu.hpp
#ifndef _OP_CPU_JSON_CONVERTERS_HPP_ #define _OP_CPU_JSON_CONVERTERS_HPP_ #include "json.hpp" namespace swagger::v1::model { class CpuGenerator; class CpuGeneratorConfig; class BulkCreateCpuGeneratorsRequest; class BulkDeleteCpuGeneratorsRequest; class BulkStartCpuGeneratorsRequest; class BulkStopCpuGeneratorsRequest; class CpuGeneratorResult; void from_json(const nlohmann::json&, CpuGenerator&); void from_json(const nlohmann::json&, CpuGeneratorConfig&); void from_json(const nlohmann::json&, BulkCreateCpuGeneratorsRequest&); void from_json(const nlohmann::json&, BulkDeleteCpuGeneratorsRequest&); void from_json(const nlohmann::json&, BulkStartCpuGeneratorsRequest&); void from_json(const nlohmann::json&, BulkStopCpuGeneratorsRequest&); void from_json(const nlohmann::json&, CpuGeneratorResult&); } // namespace swagger::v1::model #endif
10038eeb0a9b3bec95da628bebd08c20239c61de
421a832c2d7747f4b0612f22debd4e523e4a8e24
/RED_DWARF/PROB#31.CPP
4a295552e6556ac3e01712120c145ffd6b5c5761
[ "MIT" ]
permissive
AllenCompSci/FLOPPYGLORY
85e712a7af64ab4e72a93fdbb6d0759f6565ae49
ef08a690f237f0b8e711dc234607828375ae0a72
refs/heads/master
2021-01-20T01:19:51.330189
2018-03-18T03:11:34
2018-03-18T03:11:34
89,257,274
2
0
null
null
null
null
UTF-8
C++
false
false
1,081
cpp
PROB#31.CPP
//Kris BIckham //Prob31 //Tuesday //Period 6 //Mr. Baker //Libary Section #include <conio.h> #include <iostream.h> #include <iomanip.h> #include <apstring.h> #include <apmatrix.h> //Const Section const char A='A'; const char B='B'; const char C='C'; //e Section int Discs; char Ans; int I; //Protoypes void hanoi (int, char, char, char, int&); //Main void main () { do { clrscr (); gotoxy(30,1); I=0; cout<<"Towers of Hanoi"; gotoxy(30,2); cout<<"***************"; cout<<endl; getch(); cout<<"Enter number of Disc(s): - Discs"<<endl; gotoxy(26,3); cin>>Discs; hanoi (Discs, A,C,B,I); cout<<endl; cout<<I<<" Moves"; getch (); cout<<endl; cout<<"Do you wish to run again? "; cin>>Ans; }while(Ans=='Y'||Ans=='y'); getch (); }; void hanoi (int D, char Origin, char End , char Empty,int& I) { if (D<=1) { I++; cout<<I<<".) Move a disc from "<<Origin<<" to "<<End<<endl; } else {hanoi(D-1, Origin, Empty, End, I); hanoi(1 , Origin, End, Empty, I ); hanoi(D-1, Empty, End ,Origin, I); } };
dad7d64f9dd7ff3bd9b12663f9451df629758469
0bfc37cec10ebec82e4ad319e5de1b346ca7beda
/Project1/Ball.cpp
5dda8c008a6f4f7f7ccd9127f7d5371b73be8778
[]
no_license
anhtoan1103/OOP2
a25a272f01eef9fb9dfa56a283d61b8a0244aca2
a96fad83ad52edc1cca907f266efc752f0a1cb99
refs/heads/master
2020-09-28T12:52:57.652112
2019-12-14T17:05:44
2019-12-14T17:05:44
226,779,895
6
0
null
2019-12-10T09:02:42
2019-12-09T03:50:03
C++
UTF-8
C++
false
false
8,058
cpp
Ball.cpp
#include "Ball.h" #include <time.h> #include "Constants.h" Ball::Ball(float initX, float initY) { srand(time(NULL)); int count = 0; int i = 0, j = 0; readFile(i, j, "2.txt"); for (int a = 0; a < i; a++) { for (int b = 0; b < j; b++) { if ((int)arr[b + a * j] == 126) { RectangleShape brick; Brick.push_back(brick); Brick[count].setPosition(Vector2f((1366 / j) * b, 60 + 22 * a)); Brick[count].setSize(Vector2f(1366 / j - 2, 20)); Brick[count].setFillColor(Color::Red); count++; } else if ((int)arr[b + a * j] == 45) { RectangleShape brick; Brick.push_back(brick); Brick[count].setPosition(Vector2f((1366 / j) * b, 60 + 22 * a)); Brick[count].setSize(Vector2f(1366 / j - 2, 20)); Brick[count].setFillColor(Color::Green); count++; } } } position.x = initX; position.y = initY; ballShape.setRadius(10); ballShape.setPosition(position); ballShape.setFillColor(Color::Red); Texture* gift1Texture = new Texture; Texture* gift2Texture = new Texture; Texture* gift3Texture = new Texture; Texture* gift4Texture = new Texture; gift1Texture->loadFromFile("electric.png"); gift2Texture->loadFromFile("rock.png"); gift3Texture->loadFromFile("fighting.png"); gift4Texture->loadFromFile("fire.png"); Gift1.setTexture(gift1Texture); Gift2.setTexture(gift2Texture); Gift3.setTexture(gift3Texture); Gift4.setTexture(gift4Texture); Gift1.setRadius(25); Gift2.setRadius(25); Gift3.setRadius(25); Gift4.setRadius(25); Gift4.setPosition(Vector2f(650, 450)); selectedItem = 4; winBrick.setSize(Vector2f(65, 20)); winBrick.setFillColor(Color::Yellow); winBrick.setPosition(Vector2f((1300 + 65) / 2, 40)); } FloatRect Ball::getPosition() { return ballShape.getGlobalBounds(); } CircleShape Ball::getShape() { return ballShape; } float Ball::getvx() { return vx; } float Ball::getvy() { return vy; } void Ball::hitSides() { vy = -vy; } void Ball::hitPaddle2(Paddle temp) { setSpeed(); vy = -vy; } void Ball::hitRight() { if (vx > 0) { vx = -vx; } } void Ball::hitLeft() { if (vx < 0) { vx = -vx; } } void Ball::hitRightBrick() { vx = -vx; } void Ball::hitLeftBrick() { score++; vx = -vx; } void Ball::hitTopBrick() { vy = -vy; } void Ball::hitBotBrick() { score++; vy = -vy; } void Ball::updatePosition() { position.x = position.x + vx; position.y = position.y + vy; ballShape.setPosition(position); } FloatRect Ball::getRectanglePositionBall() { return ballShape.getGlobalBounds(); } int Ball::move(int WIDTH, int HEIGHT, Paddle paddle2, RenderWindow& window, vector<DestructiveBrick> &VectorDestructiveBrick) { for (int i = 0; i < Brick.size(); i++) { //Bong cham cuc gach if (getPosition().intersects(Brick[i].getGlobalBounds())) { if (ballShape.getGlobalBounds().top <= Brick[i].getGlobalBounds().top) { hitLeftBrick(); if (Brick[i].getFillColor() == Color::Red) { Brick[i].setFillColor(Color::Green); } else if (Brick[i].getFillColor() == Color::Green) { Brick.erase(Brick.begin() + i); } } else { hitBotBrick(); if (Brick[i].getFillColor() == Color::Red) { Brick[i].setFillColor(Color::Green); } else if (Brick[i].getFillColor() == Color::Green) { Brick.erase(Brick.begin() + i); } } } } //Bong cham vat pham 1 if (getPosition().intersects(Gift1.getGlobalBounds()) && selectedItem == 1) { // Item co chuc nang nhan x2 diem dang co score *= 2; setItem(); } //Bong cham vat pham 2 if (getPosition().intersects(Gift2.getGlobalBounds()) && selectedItem == 2) { // Item co chuc nang tao ra 1 vat pham khong the bi pha huy setImmortalBrick(); setItem(); } //Bong cham vat pham 3 if (getPosition().intersects(Gift3.getGlobalBounds()) && selectedItem == 3) { score *= 0.5; setItem(); } //Bong cham vat pham 4 if (getPosition().intersects(Gift4.getGlobalBounds()) && selectedItem == 4) { RectangleShape brick; brick.setFillColor(Color::Red); brick.setSize(Vector2f(20, 60)); brick.setPosition(Vector2f(rand() % 1280, 0)); VectorDestructiveBrick.push_back(DestructiveBrick(brick)); setItem(); } //Bong cham paddle if (getPosition().intersects(paddle2.getPosition())) { hitPaddle2(paddle2); } //Dung vao cuc gach trang for (int i = 0; i < ImmortalBrick.size(); i++) { if (getPosition().intersects(ImmortalBrick[i].getGlobalBounds())) { if (ballShape.getGlobalBounds().top <= ImmortalBrick[i].getGlobalBounds().top) { hitLeftBrick(); score--; } else { hitBotBrick(); score--; } } } //Bong cham bien ngang tren if (getPosition().top < 0) { hitSides(); } //Bong cham bien phai if (getPosition().left +ballShape.getRadius()*2 > WIDTH) { hitRight(); } //Bong cham bien trai if (getPosition().left < 0) { hitLeft(); } //Bong cham bien ngang duoi thi thua if (getPosition().height + getPosition().top > HEIGHT) { return 1; } for (int i = 0; i < VectorDestructiveBrick.size(); i++) { //Paddle cham vao cuc gach huy diet thi thua if (VectorDestructiveBrick[i].getShape().getGlobalBounds().intersects(paddle2.getPosition())) { return 1; } } //Het gach thi thang if (Brick.size() == 0) { return 2; } //Dung vao cuc gach vang thi thang if (getRectanglePositionBall().intersects(winBrick.getGlobalBounds())) { return 2; } } void Ball::setSpeed() { if (vx <= 0) { vx = vx - 0.02; } else if (vx >= 0) { vx = vx + 0.02; } if (vy <= 0) { vy = vy - 0.02; } else if (vy >= 0) { vy = vy + 0.02; } } int Ball::getScorePalyer2() { return score; } void Ball::readFile(int& i, int& j, string file_name) { ifstream file; file.open(file_name); char a[250]; string s; while (!file.eof()) { file.getline(a, 250); s = a; if (j < s.length()) { j = s.length(); } i++; } file.close(); file.open(file_name); int c = 0, d = 0; while (!file.eof()) { file.getline(a, 250); for (c = 0; c < j; c++) { arr[c + d * j] = a[c]; } d++; } file.close(); } void Ball::draw(RenderWindow& window) { window.draw(ballShape); window.draw(winBrick); if (selectedItem == 1) { window.draw(Gift1); } else if (selectedItem == 2) { window.draw(Gift2); } else if (selectedItem == 3) { window.draw(Gift3); } else if (selectedItem == 4) { window.draw(Gift4); } for (int i = 0; i < Brick.size(); i++) { window.draw(Brick[i]); } for (int i = 0; i < ImmortalBrick.size(); i++) { window.draw(ImmortalBrick[i]); } } bool Ball::isIntersectBrick(RectangleShape brick) { for (int i = 0; i < Brick.size(); i++) { if (brick.getGlobalBounds().intersects(Brick[i].getGlobalBounds())) { return 1; } } return 0; } bool Ball::isIntersectBrick(CircleShape gift) { for (int i = 0; i < Brick.size(); i++) { if (gift.getGlobalBounds().intersects(Brick[i].getGlobalBounds())) { return 1; } } return 0; } void Ball::setItem() { selectedItem = rand() % 4 + 1; Vector2f positionGift = Vector2f(40 * (rand() % 10 + 1), 20 * (rand() % 10 + 1)); if (selectedItem == 1) { Gift1.setPosition(positionGift); if (isIntersectBrick(Gift1)) { setItem(); } } else if (selectedItem == 2) { Gift2.setPosition(positionGift); if (isIntersectBrick(Gift2)) { setItem(); } } else if (selectedItem == 3) { Gift3.setPosition(positionGift); if (isIntersectBrick(Gift3)) { setItem(); } } else if (selectedItem == 4) { Gift4.setPosition(positionGift); if (isIntersectBrick(Gift4)) { setItem(); } } } void Ball::setImmortalBrick() { RectangleShape brick; Vector2f positionImmortalBrick = Vector2f(40 * (rand() % 10 + 1), 20 * (rand() % 10 + 1)); brick.setPosition(positionImmortalBrick); if (isIntersectBrick(brick) == 1) { setImmortalBrick(); } brick.setSize(Vector2f(65, 20)); brick.setFillColor(Color::White); ImmortalBrick.push_back(brick); } void Ball::setWinBrick() { winBrick.setSize(Vector2f(65, 20)); winBrick.setFillColor(Color::Yellow); winBrick.setPosition(Vector2f((1300 + 65) / 2, 40)); }
075d16d3c11efd6c10b0a14e9fcc7b795db151ac
3789b34cda26c9e2fe91101525a5afb78c13a8d8
/Final/Tree.cpp
7f58d854bb32031a51eb2e6fd504272d5555adc2
[]
no_license
ariasmartinez/trabajosed
636e02806c4e6e1a90bab4331f7f9c8899a83c2c
acb9c6bb948e1eb1410bdcd140587719e32526bd
refs/heads/master
2020-04-05T20:42:57.125266
2019-01-07T20:48:02
2019-01-07T20:48:02
157,192,624
0
0
null
null
null
null
UTF-8
C++
false
false
3,103
cpp
Tree.cpp
/** * @file src/Tree.cpp * @author Gustavo Rivas Gervilla */ #include "Tree.h" #include "Node.h" #include "Diccionario.h" using namespace std; void Tree::print(ostream &os, const Node* node, int level) const{ string separator = string(level, '\t'); os << separator << node->get_label() << "|" << node->get_score() << endl; Node::const_iterator it; for (it = node->cbegin(); it != node->cend(); it++) print(os, *it, level + 1); } ostream& operator<<(ostream &os, const Tree &tree){ tree.print(os, &tree.root, 0); return os; } Tree::Tree(){ // no habría que ponerlo no? } // Este no lo veo Tree::Tree(const Diccionario &d){ Diccionario::iterator it_dicc; Node root('r'); // la r xq? // root children ?? //funcion it_dicc ?? for (it_dicc = d.begin(); it_dicc != d.end(); ++it_dicc){ root.aniadirPalabra((*it_dicc)); } } Node Tree::get_root(){ return root; } // Le metemos siempre primero un NULL para saber cuando llega al final? Tree::tree_iterator::tree_iterator(){ node_stack.clear(); node_stack.push(NULL); } bool Tree::tree_iterator::operator==(const tree_iterator &it){ return (this->node_stack.top() == it.node_stack.top()); } bool Tree::tree_iterator::operator!=(const tree_iterator &it){ return(this->node_stack.top() != it.node_stack.top()); } // no se si los iteradores habrá que ponerlos constantes, no los voy a poner si da problemas es aquí tree_iterator& Tree::tree_iterator::operator=(const tree_iterator &i){ // Pensaba hacerlo con el constructor del nodo pero es que no se que coño hay que hacer la verdad Node * nodo = i.top(); } Node* Tree::tree_iterator::operator*(){ } tree_iterator& Tree::tree_iterator::operator++(){ } tree_iterator& Tree::tree_iterator::operator--(){ } tree_iterator Tree::begin(){ } tree_iterator Tree::end(){ } /* recorre un camino bueno dado un nodo hasta una hoja y los mete en la pila-vector */ /* PROBLEMAS DEL MÉTODO -> SOLUCIONES (lucia no me mates) al hacer top se borra -> utilizar un vector necesitamos utilizar childer -> lo hacemos friend hacer metodo esBueno de Nodo */ void Tree::tree_iterator::meterHijosBuenos(){ if (!node_stack.top().is_leaf()){ // qhacer que no se borre el nodo de la pila! Node_Set::iterator it_set; it_set = node_stack.top().children().begin(); for (it_set = node_stack.top().children().begin(); it_set != node_stack.top().children().end() && encontrado == false; it_set++){ if ((*it_set).esBueno()){ encontrado = true; node_stack.push(*it_set); meterHijosBuenos(); } } } } tree_iterator& Tree::tree_operator::operator++(){ while((*this) != end()){ if (!node_stack.top().isleaf()){ meterHijosBuenos(); return (*this); } else node_stack.erase(node_stack.size()-1); } return NULL; } tree_iterator Tree::tree_operator::begin(){ node_stack.push(root); meterHijosBuenos(); return node_stack[node_stack.size()-1]; }
68675a0fe5d92f52c2187127b5b334f6583e6dac
722a673f676a946cb8662793fe29f2c86d11b03e
/PAETT-tool/src/libcollect_energy.cpp
2bdb279cbd374c0c9593423baaf14ad86628dd9b
[]
no_license
JerryYouxin/PAETT-toolbox
09a083de1d398355279cd701a9fda93a3b4f55db
83dd7d1a505b72ef09a666adda7bea4310e6d682
refs/heads/master
2023-08-10T16:02:07.550669
2021-09-27T15:17:41
2021-09-27T15:17:41
260,846,944
0
0
null
null
null
null
UTF-8
C++
false
false
8,767
cpp
libcollect_energy.cpp
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <stdint.h> #include <signal.h> #include <papi.h> #include <cassert> #include <string.h> #include "CallingContextTree.h" #include "common.h" #include <sys/time.h> #include <sys/syscall.h> #define MAX_THREAD 50 #define GET_THREADID 0 #include <omp.h> #define THREAD_HANDLER omp_get_thread_num #define GET_ACTIVE_THREAD_NUM std::max(omp_get_max_threads(),1) #define METRIC_FN "metric.out" //#define STOP_WHEN_WARN //#define ENABLE_INFO_LOG #ifdef ENABLE_INFO_LOG #define INFO(msg, ...) printf("INFO: "); printf(msg, ##__VA_ARGS__); fflush(stdout) #else #define INFO(msg, ...) #endif static CallingContextLog root[MAX_THREAD]; static CallingContextLog* cur[MAX_THREAD] = {0}; static bool danger[MAX_THREAD] = {false}; static int* _eventList; // PAPI global vars static uint8_t initialized = 0; static int EventSet = PAPI_NULL; static int eventNum = 0; uint64_t elapsed_us; uint64_t elapsed_us_multi[MAX_THREAD] = {0}; uint64_t begin_us_multi[MAX_THREAD]; #define CYCLE_THRESHOLD 1 #define THRESHOLD 100000 #ifdef DEBUG_PAPI #define CHECK_PAPI(stmt, PASS) printf("%s:%d: Executing %s\n",__FILE__, __LINE__,#stmt); fflush(stdout); if((retval=stmt)!=PASS) handle_error(retval) #else #define CHECK_PAPI(stmt, PASS) if((retval=stmt)!=PASS) handle_error(retval) #endif #define CHECK_PAPI_ISOK(stmt) CHECK_PAPI(stmt, PAPI_OK) #define handle_error(e) do { fprintf(stderr, "Error at %s:%d: %s\n",__FILE__, __LINE__, PAPI_strerror(e)); exit(1); } while(0) #define MAXEVENT 64 static int total[MAXEVENT][MAX_THREAD] = {0}; static long long counterVal[MAXEVENT] = {0}; static uint64_t g_cycles[MAX_THREAD] = {0}; // fake interfaces same as libpaett_inst // C-style interfaces for lib call extern "C" void PAETT_print(); extern "C" void PAETT_inst_init(); extern "C" void PAETT_inst_enter(uint64_t key); // key = MAKE_KEY(mid, l_key) extern "C" void PAETT_inst_exit(uint64_t key); extern "C" void PAETT_inst_thread_init(uint64_t key); // key = MAKE_KEY(mid, l_key) extern "C" void PAETT_inst_thread_fini(uint64_t key); extern "C" void PAETT_inst_finalize(); static double init_energy; #include "energy_utils.h" void PAETT_print() { printf("\n=========== COLLECTING METRICS ENERGY =============\n"); fflush(stdout); } void PAETT_inst_init() { // the args are not used. just fakes if(initialized) { fprintf(stderr, "Error Duplicated initialization!!!\n"); exit(EXIT_FAILURE); } // LOG = fopen(LIBPAETT_INST_LOGFN,"w"); initialized = 1; // typically, backtrace size is often very small, so preallocate it. int retval, i; for(i=0;i<MAX_THREAD;++i) { cur[i]=&root[i]; } ++(cur[0]->data.ncall); energy_init(); init_energy = get_pkg_energy(); cur[0]->data.last_energy = init_energy; g_cycles[0] = PAPI_get_real_usec(); elapsed_us = g_cycles[0]; } // actually should be inserted after PAETT_inst_enter void PAETT_inst_thread_init(uint64_t key) { int retval, i; int tid = GET_THREADID; assert(tid<=MAX_THREAD && "Thread number exceeds preallocated size!!!"); assert(cur[tid] && !danger[tid] && initialized); if(cur[tid]->key!=key) { PAETT_inst_enter(key); printf("After Enter: thread_init for 0x%lx @ 0x%lx\n",key,cur[tid]->key); fflush(stdout); } danger[tid] = true; // we should have already called PAETT_inst_enter assert(cur[tid] && cur[tid]->key==key); // Stop counting first to disable overflow cur[tid]->data.active_thread = std::max(cur[tid]->data.active_thread, (uint64_t)GET_ACTIVE_THREAD_NUM); cur[tid]->data.last_energy = get_pkg_energy(); begin_us_multi[tid] = PAPI_get_real_usec(); g_cycles[tid] = PAPI_get_real_usec(); } // Different from init, the fini instrumentation will do the work similiarly as PAETT_inst_exit, so only fini should be inserted. void PAETT_inst_thread_fini(uint64_t key) { int retval, i; uint64_t e_cycles = PAPI_get_real_usec(); uint64_t e_us = PAPI_get_real_usec(); double energy = get_pkg_energy(); int tid = GET_THREADID; double e = energy - cur[tid]->data.last_energy; CallingContextLog* p = cur[tid]; while(p!=NULL) { p->data.pkg_energy+= e; RLOG("Update %lx PKG energy to %.6lf (+%.6lf) J\n", p->key, p->data.pkg_energy, e); p = p->parent; } RLOG("Thread_fini: PAETT_inst_thread_fini: cur[tid]->data.pkg_energy=%.2lf\n",cur[tid]->data.pkg_energy); elapsed_us_multi[tid] += e_us - begin_us_multi[tid]; // make sure that init called before fini and the parallel region should not change the cursol if(cur[tid]->key==key) { cur[tid]->data.cycle += e_cycles - g_cycles[tid]; assert(cur[tid]!=&root[tid]); assert(cur[tid]->parent); cur[tid] = cur[tid]->parent; } else { printf("Error: [libpaett_inst] paett_inst_thread_fini not handled as key (cur=%lu, key=%lu) is not same !!!\n",cur[tid]->key, key); exit(-1); } cur[tid]->data.last_energy = get_pkg_energy(); danger[tid] = false; g_cycles[tid] = PAPI_get_real_usec(); } void PAETT_inst_enter(uint64_t key) { if(danger[0] || !initialized) return; uint64_t e_cycles = PAPI_get_real_usec(); double energy = get_pkg_energy(); int tid = GET_THREADID; assert(tid==0); danger[tid] = true; //halt_energy_collection(); double e = energy - cur[tid]->data.last_energy; CallingContextLog* p = cur[tid]; while(p!=NULL) { p->data.pkg_energy+= e; RLOG("Enter: Update %lx PKG energy to %.6lf (+%.6lf) J\n", p->key, p->data.pkg_energy, e); p = p->parent; } assert(cur[tid]); cur[tid]->data.cycle += e_cycles - g_cycles[tid]; cur[tid] = cur[tid]->getOrInsertChild(key); ++(cur[tid]->data.ncall); cur[tid]->data.last_energy = get_pkg_energy(); assert(cur[tid]); danger[tid] = false; g_cycles[tid] = PAPI_get_real_usec(); } void PAETT_inst_exit(uint64_t key) { if(danger[0] || !initialized) return; uint64_t e_cycles = PAPI_get_real_usec(); double energy = get_pkg_energy(); int tid = GET_THREADID; danger[tid] = true; double e = energy - cur[tid]->data.last_energy; CallingContextLog* p = cur[tid]; while(p!=NULL) { p->data.pkg_energy+= e; RLOG("Exit: Update %lx PKG energy to %.6lf (+%.6lf) J\n", p->key, p->data.pkg_energy, e); p = p->parent; } assert(cur[tid]); if(cur[tid]->key==key) { cur[tid]->data.cycle += e_cycles - g_cycles[tid]; assert(cur[tid]!=&root[tid]); assert(cur[tid]->parent); cur[tid] = cur[tid]->parent; } else { #ifdef ENABLE_INFO_LOG printf("Warning: [libpaett_inst] paett_inst_exit not handled as key (cur=0x%lx, key=0x%lx) is not same !!!\n",cur[tid]->key, key); cur[tid]->printStack(); fflush(stdout); #endif if (auto warn = cur[tid]->findStack(key)) { printf("Error: Something May wrong as this key appears as current context's parent:\n"); warn->printStack(); exit(-1); } else { #ifdef STOP_WHEN_WARN assert("Warning detected. Stop."); #endif } } cur[tid]->data.last_energy = get_pkg_energy(); danger[tid] = false; g_cycles[tid] = PAPI_get_real_usec(); } void PAETT_inst_finalize() { // disable first int retval; double fini_energy = get_pkg_energy(); energy_finalize(); printf("INFO : total Energy: %lf J\n", fini_energy-init_energy); uint64_t end_us = PAPI_get_real_usec(); elapsed_us = end_us - elapsed_us; printf("INFO : Elasped Time: %lf s\n", elapsed_us*1e-6); int i,j,k; assert(initialized); // fclose(LOG); int tid; elapsed_us_multi[0] = elapsed_us; FILE* fp = fopen(METRIC_FN, "w"); //fprintf(fp, "%ld", elapsed_us); for(tid=0;tid<MAX_THREAD;++tid) { // if the root is not initialized, next; if(root[tid].data.ncall==0) continue; printf("\n======== THREAD ID = %d, elasped time = %ld ==========\n",tid, elapsed_us_multi[tid]); // fprintf(fp," %ld",elapsed_us_multi[tid]); // ROOT data.nall should not be modified during execution assert(root[tid].data.ncall==1); if(cur[tid]!=&root[tid]) { printf("Warning: [libpaett_inst] cur[%d] is not at root when paett_inst_finalize is called : ",tid); CallingContextLog* p = cur[0]->parent; printf("cur=[%lu] ",cur[0]->key); while(p!=NULL) { printf("<= [%lu] ",p->key); p=p->parent; } printf("\n"); } printMergedEnergy(fp, &root[tid]); } fclose(fp); printf("=== finish ===\n"); fflush(stdout); initialized = false; }
d2061e44cf4358734a00585d22c316e376029c0d
12668533836d2845f1c8c37dd13dbbbb816f3c71
/src/IO/writeOut.h
aeda28404cc6c2aef634a25c48e67fcc6ee99be9
[]
no_license
nyameaama/CheckData
71d7a350c66b4438d014ccaaf01a1a6d1a58d44d
73008c4caa298430857366dc8d24bab832e05c87
refs/heads/master
2022-10-02T21:41:59.345629
2020-06-08T10:58:36
2020-06-08T10:58:36
259,270,894
0
0
null
null
null
null
UTF-8
C++
false
false
691
h
writeOut.h
#ifndef WRITE_OUT #define WRITE_OUT #include<fstream> #include"../Pref/getOS.h" //#include<unistd.h> #define OS OperatingS #define IN 0 #define OUT 1 class writeOut { const char *path = "home/user/documents"; std::fstream file; public: //Constructor writeOut(); //Destructor //~writeOut(); //Function to create folder for program resources void createProgramDir(); //Function to open file uint8_t file_open(std::string flePath,uint8_t stat); //Function to read from file std::string file_Read(); //Function to write to file uint8_t fileWrite(std::string x); }; #endif
3f2778013e4412729338e1cc8928a969257126b7
c6fa5287afb14f1f326f02806f2e2e295c0cd80a
/Source/ComponentAnimationEvent.h
faa9b25eba4920e3ff4d7b8da24fdb15815ed8fb
[ "MIT" ]
permissive
project-3-bcn-2019/Project-Atlas
d5a2537157262e55ab6c002437e32f590e237ebc
16ae881cec41d17a168d10f2f9cd2cf9207b2855
refs/heads/master
2020-04-20T02:17:31.724146
2019-03-20T19:53:42
2019-03-20T19:53:42
168,567,870
0
0
MIT
2019-03-18T17:35:34
2019-01-31T17:38:50
C++
UTF-8
C++
false
false
1,757
h
ComponentAnimationEvent.h
#ifndef _ANIMATION_EVENT_ #define _ANIMATION_EVENT_ #include "Component.h" #include "Parson/parson.h" #include "Globals.h" #include "Random.h" #include <vector> #include <string> #include <map> #include <list> typedef std::map<int, void*> KeyframeVals; typedef std::map<double, KeyframeVals> KeyMap; typedef std::map<uint, std::map<double, std::map<int, void*>>> CompAnimMap; // Explanation // std::multimap<uint,...> uint is the UUID of the component // ...<...,std::map<...>> is the keyframes for the component // ...<...,std::map<double,...>> uint is the frame (time) of keyframe // ...<...,...<...,std::map<...,...>> is the keyframe info // ...<...,...<...,std::map<int,...>> int is the component event triggered // // ...<...,...<...,std::map<...,void*>> void* is the values required for the event to play struct AnimSet { std::string name = "error"; uint linked_animation = 0; CompAnimMap AnimEvts; int own_ticks = 0; int ticksXsecond = 0; bool loop = false; float speed = 1.0f; bool selected; }; class ComponentAnimationEvent : public Component { public: ComponentAnimationEvent(GameObject* gameobject) : Component(gameobject, ANIMATION_EVENT) {} // empty constructor ComponentAnimationEvent(JSON_Object* deff, GameObject* parent); ~ComponentAnimationEvent(); bool Update(float dt); bool DrawInspector(int id = 0) override; // Get the resource when there is void Play() { paused = false; } void Pause() { paused = true; } void Save(JSON_Object* config); bool Finished() const { return false; } bool isPaused() const { return paused; } void CheckLinkAnim(); private: float animTime = 0.0f; bool paused = false; int last_frame = -1; public: std::list<AnimSet> AnimEvts; AnimSet* curr = nullptr; }; #endif
9b68f62ca156da1eea9df9a77deb88e71405dadc
12c5cd2336ebf1f79722f5c92ff8f7f59297c82e
/C++程式考試作業/實習11/統計各組距人數/B2.cpp
dad3630387c29f2abf0ba3c2a00d83ec90f6a79a
[]
no_license
jennysu1101/C-CTF
63afe4c098845502c36e72c7f9cd42d4d6dd0f1b
dcc4bd54c7affc29410d3c3bb2ded5185559010b
refs/heads/master
2023-08-31T03:34:03.248334
2018-03-09T08:56:55
2018-03-09T08:56:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
396
cpp
B2.cpp
#include <iostream> #include <iomanip> using namespace std; int distribution(int score[],int arraySize){ int n[11]={0}; int i=0; for (;i<arraySize;i++){ n[score[i]/10]++; } for (int j=0;j<11;j++){ cout << n[j] << " "; } } int main(){ const int arraySize=100; int score[arraySize]; for(int i=0;i<arraySize;i++){ cin>>score[i]; } distribution(score, arraySize); }
a3eabbbcbd5127ad7f61eca5ab36a635da36de52
b6910389f6f6065ce12055874572304d9a1a105e
/src/api/apiserver.cpp
a449503fe992f651bf7553ba6ddcafc0097694c2
[ "MIT" ]
permissive
suxinde2009/nitroshare-desktop
85416c811657576880720821bd33a16ccce54713
6b441aef15ded64e0ef38e5978093d699c49fc9e
refs/heads/master
2021-01-16T22:50:37.151415
2016-09-10T18:46:05
2016-09-10T18:46:05
68,022,474
0
1
null
2016-09-12T15:35:54
2016-09-12T15:35:53
null
UTF-8
C++
false
false
2,903
cpp
apiserver.cpp
/** * The MIT License (MIT) * * Copyright (c) 2015 Nathan Osman * * 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. **/ #include <QHostAddress> #include <QJsonDocument> #include <QJsonObject> #include <QUuid> #include "apiserver.h" #include "apiserver_p.h" ApiServerPrivate::ApiServerPrivate(ApiServer *apiServer) : QObject(apiServer), q(apiServer), token(QUuid::createUuid().toString()), handler(token), server(&handler) { connect(&handler, &ApiHandler::itemsQueued, q, &ApiServer::itemsQueued, Qt::QueuedConnection); connect(Settings::instance(), &Settings::settingsChanged, this, &ApiServerPrivate::onSettingsChanged); } ApiServerPrivate::~ApiServerPrivate() { stop(); } void ApiServerPrivate::onSettingsChanged(const QList<Settings::Key> &keys) { Settings *settings = Settings::instance(); if (keys.empty() || keys.contains(Settings::Key::LocalAPI)) { stop(); if (settings->get(Settings::Key::LocalAPI).toBool()) { start(); } } } void ApiServerPrivate::stop() { localFile.remove(); server.close(); } void ApiServerPrivate::start() { if (!server.listen(QHostAddress::LocalHost)) { emit q->error(tr("Unable to find an available port for the local API")); return; } if (!localFile.open()) { emit q->error(tr("Unable to open %1\n\nDescription: \"%2\"") .arg(localFile.fileName()) .arg(localFile.errorString())); return; } QJsonObject object(QJsonObject::fromVariantMap({ { "port", server.serverPort() }, { "token", token } })); localFile.write(QJsonDocument(object).toJson()); localFile.close(); } ApiServer::ApiServer(QObject *parent) : QObject(parent), d(new ApiServerPrivate(this)) { } void ApiServer::start() { d->onSettingsChanged(); }
8018dde97cf9adbf1712066d473afbafc88cb370
90cf4becd1fdea951d51ce2a615f03881b81e63c
/trunk/tzhang.cpp
15d979b069b7411d47f7b38b7ff4765c1433f649
[]
no_license
cbshiles/KALX-fmsroot
9731d5557e8707671b1e80f70792f1a0fe1d251f
5db5338566a4fef9247b55d1d14f95bb5704e87a
refs/heads/master
2021-05-15T08:07:51.686275
2014-01-03T15:15:05
2014-01-03T15:15:05
109,078,881
0
0
null
null
null
null
UTF-8
C++
false
false
455
cpp
tzhang.cpp
// tzhange.cpp - test Zhang root finding algorithm #include <iostream> #include "zhang.h" using namespace std; using namespace root; template<class T> void test_zhang(void) { T x0 = 1., x1 = 2.; auto F = [](T x) { return x*x - 2; }; for (size_t i = 0; i < 10; ++i) { size_t n = 1; _1d::zhang_(x0, x1, F, 0, n); // cout << "x0 = " << x0 << " x1 = " << x1 << endl; } } void fms_test_zhang(void) { test_zhang<double>(); }
455935f8e0ad5f32f8a3d483e6b69bb660c5d2b5
e7d7377b40fc431ef2cf8dfa259a611f6acc2c67
/SampleDump/Cpp/SDK/BP_ChoiceMenuEntry_parameters.h
a51784a51936d99ed632eefdef67dfaa5b85f275
[]
no_license
liner0211/uSDK_Generator
ac90211e005c5f744e4f718cd5c8118aab3f8a18
9ef122944349d2bad7c0abe5b183534f5b189bd7
refs/heads/main
2023-09-02T16:37:22.932365
2021-10-31T17:38:03
2021-10-31T17:38:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,941
h
BP_ChoiceMenuEntry_parameters.h
#pragma once // Name: Mordhau, Version: Patch23 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function BP_ChoiceMenuEntry.BP_ChoiceMenuEntry_C.Update struct UBP_ChoiceMenuEntry_C_Update_Params { }; // Function BP_ChoiceMenuEntry.BP_ChoiceMenuEntry_C.Get_SlotNumber_Text_1 struct UBP_ChoiceMenuEntry_C_Get_SlotNumber_Text_1_Params { struct FText ReturnValue; // 0x0000(0x0018) (Parm, OutParm, ReturnParm) }; // Function BP_ChoiceMenuEntry.BP_ChoiceMenuEntry_C.GetVisibility_1 struct UBP_ChoiceMenuEntry_C_GetVisibility_1_Params { UMG_ESlateVisibility ReturnValue; // 0x0000(0x0001) (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash) }; // Function BP_ChoiceMenuEntry.BP_ChoiceMenuEntry_C.GetText_1 struct UBP_ChoiceMenuEntry_C_GetText_1_Params { struct FText ReturnValue; // 0x0000(0x0018) (Parm, OutParm, ReturnParm) }; // Function BP_ChoiceMenuEntry.BP_ChoiceMenuEntry_C.Construct struct UBP_ChoiceMenuEntry_C_Construct_Params { }; // Function BP_ChoiceMenuEntry.BP_ChoiceMenuEntry_C.ExecuteUbergraph_BP_ChoiceMenuEntry struct UBP_ChoiceMenuEntry_C_ExecuteUbergraph_BP_ChoiceMenuEntry_Params { int EntryPoint; // 0x0000(0x0004) (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
a1634f33a326ab80647f69fc47c88e3b0731c442
98e5fd588b356aff074e907c27aede0b609aae85
/programming/HackerRank/allPairsSP.cpp
4472637b98c07683f867ed8c782726ad606e664e
[]
no_license
ayushshukla92/algorithms
060521612773e93bf4804abd5644fc35d4d32eb7
a3d5baa3c71de5fa9a8049d436c802c75ad32cd2
refs/heads/master
2016-08-12T02:01:53.233754
2015-11-04T11:09:00
2015-11-04T11:09:00
45,024,626
0
0
null
null
null
null
UTF-8
C++
false
false
2,239
cpp
allPairsSP.cpp
#include <iostream> #include <queue> #include <algorithm> #include <climits> #include <string> #include <cstdlib> #include <sstream> #include <cmath> #include <cctype> #include <iomanip> #include <cstdio> #include <list> #include <stack> #include <vector> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <cstring> using namespace std; typedef pair <int, int> PII; typedef pair <int, double> PID; typedef pair <double, double> PDD; typedef vector <int> VI; typedef vector <bool> VB; typedef vector < pair<int,int> > VP; typedef vector <double> VD; typedef long long ll; typedef long double ld; typedef unsigned long long ull; // Input macros #define SD(n) scanf("%d",&n) #define SF(n) scanf("%f",&n) #define SLF(n) scanf("%lf",&n) #define SS(n) scanf("%s",&n) #define REP(i,n) for(int i=0;i<(n);i++) #define FOR(i,a,b) for(int i=(a);i<=(b);i++) #define foreach(v, c) for( typeof( (c).begin()) v = (c).begin(); v != (c).end(); ++v) #define ALL(a) a.begin(), a.end() #define IN(a,b) ( (b).find(a) != (b).end()) #define MP make_pair #define PB push_back #define PPB pop_back #define PF push_front #define PPF pop_front #define EL endl #define CO cout #define F first #define S second #define MAX 1000000007 template <typename T> void print(vector<T> &v) { for(T t : v){ cout<<t<<' '; } CO<<EL; } //-----------------------------------------utilities end--------------------------- int main() { int tc; tc=1; while(tc--){ int n,m,q; SD(n); SD(m); vector<std::vector<int> > g(n,std::vector<int>(n,MAX) ); for (int i = 0; i < n; ++i) { g[i][i]=0; } while(m--){ int l,r,w; SD(l);SD(r);SD(w); l--; r--; g[l][r] = w; // g[r][l] = w; // g[r].PB({l,w}); } for (int k = 0; k < n; ++k) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { // if(i==j) // continue; if(g[i][j] > g[i][k] + g[k][j]) g[i][j] = g[i][k] + g[k][j]; } } } SD(q); while(q--){ int l,r; SD(l); SD(r); l--;r--; if(g[l][r] != MAX){ printf("%d\n",g[l][r] ); } else printf("-1\n"); } } return 0; }
107db77f912bb740b3c82dad9b56037ea5213e90
5386865e2ea964397b8127aba4b2592d939cd9f2
/codeforces/RCC 2014/warmup/d.cpp
290a33ae6b73a4f6d944e80bc64de0eda819d9ba
[]
no_license
HekpoMaH/Olimpiads
e380538b3de39ada60b3572451ae53e6edbde1be
d358333e606e60ea83e0f4b47b61f649bd27890b
refs/heads/master
2021-07-07T14:51:03.193642
2017-10-04T16:38:11
2017-10-04T16:38:11
105,790,126
2
0
null
null
null
null
UTF-8
C++
false
false
1,782
cpp
d.cpp
#include<bits/stdc++.h> using namespace std; const int maxm=105000,maxn=102; long long n,m,b; const long long inf=1e15; struct state { long long cost; set<int> ufr; long long bc;//bought computers }; struct fr { long long x,k,m; long long probl[22]; }; fr frs[maxn]; state dp[maxm]; void read() { cin>>n>>m>>b; for(int i=1;i<=n;i++) { cin>>frs[i].x>>frs[i].k>>frs[i].m; for(int j=0;j<frs[i].m;j++)cin>>frs[i].probl[j]; } } //we solve it like a BFS //NOT void solve() { state x; queue<long long> toc; dp[0].cost=0; dp[0].bc=0; dp[0].ufr.clear(); long long mask=0; long long amask=0; for(long long i=0;i<m;i++)amask+=(1<<i); //cout<<"amask="<<amask<<endl;; for(int i=1;i<=amask;i++)dp[i].cost=inf; for(int i=0;i<=amask;i++) { //cout<<i<<" "<<dp[i].cost<<"\n"; if(dp[i].cost!=inf) { //x.cost for(int j=1;j<=n;j++) { if(x.ufr.find(j)!=x.ufr.end())continue; x=dp[i]; mask=i; x.cost+=max(0LL,frs[j].k-x.bc)*b; x.bc=max(x.bc,frs[j].k); x.cost+=frs[j].x; x.ufr.insert(j); for(int j1=0;j1<frs[j].m;j1++) { mask|= 1<<(frs[j].probl[j1]-1); //cout<<"solving probl "<<frs[j].probl[j1]<<" adding "<< (1<<(frs[j].probl[j1]-1))<<" "; } //cout<<"mask="<<mask<<"\n"; if(dp[mask].cost>x.cost)dp[mask]=x; } } } if(dp[amask].cost==inf)cout<<"-1\n"; else cout<<dp[amask].cost<<"\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); read(); solve(); }
4cd63aa9b05b0fca61508d3a0d05de7663be3e2a
8a063e76b2796eee31b51a6d4eb16a9640219ed6
/linux/GUI/MainWindow.cpp
19ec1104c1a2d675dd18c16ea2bca8bafe6e1e4b
[]
no_license
ubi-agni/TactileGlove
7368aaa800779aeaac57c1aa128f074f73bed82d
b9239af688fa3e536b856a93674037a13f0bf1b3
refs/heads/master
2022-10-06T02:21:11.748008
2022-09-20T20:42:55
2022-09-20T22:40:25
27,046,875
5
2
null
2022-09-01T18:18:10
2014-11-23T20:43:47
C++
UTF-8
C++
false
false
16,600
cpp
MainWindow.cpp
#include "MainWindow.h" #include "ui_MainWindow.h" #include "GloveWidget.h" #include "MappingDialog.h" #include "FileExistsDialog.h" #include "ColorMap.h" #include "QSerialInput.h" #include "RandomInput.h" #if HAVE_ROS #include "ROSInput.h" #endif #include <tactile_filters/PieceWiseLinearCalib.h> #include <QCloseEvent> #include <QComboBox> #include <QFileDialog> #include <QMessageBox> #include <QTextStream> #include <iostream> #include <math.h> #include <qtimer.h> #include <boost/bind.hpp> using namespace std; using tactile::PieceWiseLinearCalib; using tactile::TactileValue; using tactile::TactileValueArray; MainWindow::MainWindow(size_t noTaxels, QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) , gloveWidget(nullptr) , input(nullptr) , data(noTaxels) , display(noTaxels) , mapDlg(nullptr) , iJointIdx(-1) , absColorMap(nullptr) , relColorMap(nullptr) , frameCount(-1) , timerID(0) { ui->setupUi(this); ui->toolBar->addWidget(ui->updateTimeSpinBox); ui->toolBar->addWidget(ui->lambdaSpinBox); ui->toolBar->addWidget(ui->modeComboBox); ui->toolBar->addWidget(ui->inputLineEdit); ui->toolBar->addWidget(ui->btnConnect); ui->toolBar->addWidget(ui->btnDisconnect); ui->btnDisconnect->setEnabled(false); ui->fps->hide(); connect(ui->actConfMap, SIGNAL(triggered()), this, SLOT(configureMapping())); connect(ui->actSaveMapping, SIGNAL(triggered()), this, SLOT(saveMapping())); connect(ui->updateTimeSpinBox, SIGNAL(valueChanged(int)), this, SLOT(setTimer(int))); connect(ui->lambdaSpinBox, SIGNAL(valueChanged(double)), this, SLOT(setLambda(double))); ui->lambdaSpinBox->setValue(0.5); data.setRangeLambda(0.9995); data.setReleaseDecay(0.1); initModeComboBox(ui->modeComboBox); // init upper ranges for (auto &value : data) value.init(FLT_MAX, 4095); // init color maps QStringList colorNames; absColorMap = new ColorMap; colorNames << "black" << "lime" << "yellow" << "red"; absColorMap->append(colorNames); relColorMap = new ColorMap; colorNames.clear(); colorNames << "red" << "black" << "lime"; relColorMap->append(colorNames); } void MainWindow::initModeComboBox(QComboBox *cb) { QStringList items; for (unsigned int m = 0, e = TactileValue::lastMode; m <= e; ++m) items << TactileValue::getModeName((TactileValue::Mode)m).c_str(); cb->addItems(items); cb->setCurrentIndex(TactileValue::getMode("default")); } void MainWindow::setCalibration(const std::string &sCalibFile) { QMutexLocker lock(&dataMutex); calib.reset(new PieceWiseLinearCalib(PieceWiseLinearCalib::load(sCalibFile))); for (unsigned int id : nodeToData) { data[id].setCalibration(calib); } // init upper ranges float fMax = calib->output_range().max(); for (auto &value : data) value.init(FLT_MAX, fMax); } MainWindow::~MainWindow() { if (input) { input->disconnect(); delete input; } delete ui; delete absColorMap; delete relColorMap; } void MainWindow::initJointBar(TaxelMapping &mapping) { // do we have a joint value? TaxelMapping::iterator it = mapping.find("bar"); if (it != mapping.end()) { iJointIdx = it->second; mapping.erase(it); } else iJointIdx = -1; if (iJointIdx < 0 || static_cast<size_t>(iJointIdx) >= data.size()) { iJointIdx = -1; ui->jointBar->hide(); } else ui->jointBar->show(); } void MainWindow::initGloveWidget(const QString &layout, bool bMirror, const TaxelMapping &mapping) { // do before creating the GloveWidget to allow for removing of the bar mapping initJointBar(const_cast<TaxelMapping &>(mapping)); QMutexLocker lock(&dataMutex); if (gloveWidget) { on_btnDisconnect_clicked(); ui->verticalLayout->removeWidget(gloveWidget); delete gloveWidget; gloveWidget = nullptr; } gloveWidget = new GloveWidget(layout, bMirror, this); ui->verticalLayout->insertWidget(0, gloveWidget); resetColors(); gloveWidget->setFocus(); connect(ui->actSaveSVG, SIGNAL(triggered()), gloveWidget, SLOT(saveSVG())); connect(gloveWidget, SIGNAL(doubleClickedNode(uint)), this, SLOT(editMapping(uint))); connect(gloveWidget, SIGNAL(unAssignedTaxels(bool)), ui->actConfMap, SLOT(setEnabled(bool))); gloveWidget->setShowChannels(ui->actShowChannels->isChecked()); gloveWidget->setShowNames(ui->actShowIDs->isChecked()); gloveWidget->setShowAllNames(ui->actShowAllIDs->isChecked()); connect(ui->actShowChannels, SIGNAL(toggled(bool)), gloveWidget, SLOT(setShowChannels(bool))); connect(ui->actShowIDs, SIGNAL(toggled(bool)), gloveWidget, SLOT(setShowNames(bool))); connect(ui->actShowAllIDs, SIGNAL(toggled(bool)), gloveWidget, SLOT(setShowAllNames(bool))); // initialize TaxelMapping for (const auto &item : mapping) { QString sName = QString::fromStdString(item.first); int nodeIdx = gloveWidget->findPathNodeIndex(sName); if (nodeIdx < 0) cerr << "couldn't find a node named " << item.first << endl; gloveWidget->setChannel(nodeIdx, item.second); nodeToData[nodeIdx] = item.second; } bDirtyMapping = false; } void MainWindow::setTimer(int interval) { if (!timerID) return; killTimer(timerID); timerID = startTimer(interval); } void MainWindow::setLambda(double value) { data.setMeanLambda(value); } void MainWindow::chooseMapping(TactileValue::Mode mode, const std::shared_ptr<tactile::Calibration> &calib, ColorMap *&colorMap, float &fMin, float &fMax) { switch (mode) { case TactileValue::rawCurrent: case TactileValue::rawMean: if (calib) { tactile::Range r = calib->output_range(); fMin = r.min(); fMax = r.max(); } else { fMin = 0; fMax = 4095; } colorMap = absColorMap; break; case TactileValue::absCurrent: case TactileValue::absMean: case TactileValue::dynCurrent: case TactileValue::dynMean: fMin = 0; fMax = 1; colorMap = absColorMap; break; case TactileValue::dynCurrentRelease: case TactileValue::dynMeanRelease: fMin = -1; fMax = 1; colorMap = relColorMap; break; } } void MainWindow::timerEvent(QTimerEvent *event) { if (event->timerId() != timerID) return; if (frameCount < 0) return; // no data received yet QMutexLocker lock(&dataMutex); int fps = -1; TactileValue::Mode mode = (TactileValue::Mode)ui->modeComboBox->currentIndex(); data.getValues(mode, display); if (lastUpdate.elapsed() > 1000) { // update framerate every 1s fps = roundf(1000. * frameCount / lastUpdate.restart()); frameCount = 0; } if (!gloveWidget) return; lock.unlock(); ColorMap *colorMap; float fMin, fMax; chooseMapping(mode, calib, colorMap, fMin, fMax); for (NodeToDataMap::const_iterator it = nodeToData.begin(), end = nodeToData.end(); it != end; ++it) { if (highlighted.contains(it.key())) continue; QColor color = colorMap->map(display[it.value()], fMin, fMax); gloveWidget->updateColor(it.key(), color); } gloveWidget->updateSVG(); // update MappingDialog if present if (mapDlg) { std::vector<float> display(data.size()); mode = TactileValue::absCurrent; chooseMapping(mode, calib, colorMap, fMin, fMax); lock.relock(); data.getValues(mode, display); lock.unlock(); mapDlg->update(display, colorMap, fMin, fMax); } if (iJointIdx >= 0) updateJointBar(data[iJointIdx].value(TactileValue::rawCurrent)); if (fps >= 0) ui->fps->setText(QString("%1 fps").arg(fps)); } void MainWindow::resetColors(const QColor &color) { for (NodeToDataMap::const_iterator it = nodeToData.begin(), end = nodeToData.end(); it != end; ++it) gloveWidget->updateColor(it.key(), color); gloveWidget->updateSVG(); } void MainWindow::updateJointBar(unsigned short value) { const int min = 4095; const int max = 2000; const int targetRange = 100; ui->jointBar->setValue(((value - min) * targetRange) / (max - min)); } void MainWindow::closeEvent(QCloseEvent *event) { if (bDirtyMapping) { QMessageBox::StandardButton result = QMessageBox::warning( this, "Unsaved taxel mapping", "You have unsaved changes to the taxel mapping. Close anyway?", QMessageBox::Save | QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel); if (result == QMessageBox::Save) saveMapping(); if (result == QMessageBox::Cancel) { event->ignore(); return; } } if (gloveWidget && !gloveWidget->canClose()) event->ignore(); } /*** functions for taxel mapping configuration ***/ void MainWindow::editMapping(unsigned int nodeIdx) { static const QColor highlightColor("blue"); highlighted.insert(nodeIdx); QString oldStyle = gloveWidget->highlight(nodeIdx, highlightColor); bool bOwnDialog = false; if (!mapDlg) { mapDlg = new MappingDialog(this); connect(mapDlg, SIGNAL(destroyed()), this, SLOT(resetMapDlg())); bOwnDialog = true; } const QString &oldName = gloveWidget->getNodeName(nodeIdx); const NodeToDataMap::const_iterator node = nodeToData.find(nodeIdx); const int channel = node == nodeToData.end() ? -1 : node.value(); mapDlg->init(oldName, channel, data.size(), getUnassignedChannels()); int res = mapDlg->exec(); gloveWidget->restore(nodeIdx, oldStyle); highlighted.remove(nodeIdx); if (res == QDialog::Accepted) { QString newName = mapDlg->name().trimmed(); if (oldName != mapDlg->name() && !newName.isEmpty()) { if (gloveWidget->findPathNodeIndex(newName)) QMessageBox::warning(this, "Name clash", "Taxel name already in use.", QMessageBox::Ok); else { // change node id in gloveWidget's DOM gloveWidget->setNodeName(nodeIdx, newName); gloveWidget->updateSVG(); } } if (mapDlg->channel() != channel) { bDirtyMapping = true; if (mapDlg->channel() < 0) nodeToData.remove(nodeIdx); else nodeToData[nodeIdx] = mapDlg->channel(); gloveWidget->setChannel(nodeIdx, mapDlg->channel()); } } if (bOwnDialog) mapDlg->deleteLater(); } void MainWindow::resetMapDlg() { mapDlg = nullptr; } void MainWindow::setCancelConfigure(bool bCancel) { bCancelConfigure = bCancel; } void MainWindow::configureMapping() { mapDlg = new MappingDialog(this); connect(mapDlg, SIGNAL(destroyed()), this, SLOT(resetMapDlg())); QPoint pos; bCancelConfigure = false; QPushButton *btn = mapDlg->addButton(tr("&Abort"), QDialogButtonBox::DestructiveRole); connect(btn, SIGNAL(clicked()), this, SLOT(setCancelConfigure())); connect(btn, SIGNAL(clicked()), mapDlg, SLOT(reject())); // display channel numbers, but not the names bool bShowChannels = ui->actShowChannels->isChecked(); bool bShowNames = ui->actShowIDs->isChecked(); bool bShowAllNames = ui->actShowAllIDs->isChecked(); ui->actShowAllIDs->setChecked(false); ui->actShowChannels->setChecked(true); ui->actShowIDs->setChecked(false); for (unsigned int nodeIdx = 0, end = gloveWidget->numNodes(); !bCancelConfigure && nodeIdx != end; ++nodeIdx) { const QString &oldName = gloveWidget->getNodeName(nodeIdx); // ignore nodes named path* if (oldName.startsWith("path")) continue; // and nodes already assigned if (nodeToData.find(nodeIdx) != nodeToData.end()) continue; editMapping(nodeIdx); pos = mapDlg->pos(); mapDlg->show(); mapDlg->move(pos); } mapDlg->deleteLater(); // restore channel/name display ui->actShowChannels->setChecked(bShowChannels); ui->actShowIDs->setChecked(bShowNames); ui->actShowAllIDs->setChecked(bShowAllNames); } QList<unsigned int> MainWindow::getUnassignedChannels() const { QList<unsigned int> unassigned; for (size_t i = 0, end = data.size(); i < end; ++i) unassigned.append(i); for (NodeToDataMap::const_iterator it = nodeToData.begin(), end = nodeToData.end(); it != end; ++it) unassigned.removeOne(it.value()); return unassigned; } void MainWindow::saveMapping() { using FilterMap = std::map<QString, std::pair<QString, bool (GloveWidget::*)(const QString &, const QString &)> >; static FilterMap filterMap; static QString sFilters; static FilterMap::const_iterator defaultFilter; if (filterMap.empty()) { filterMap[tr("mapping configs (*.cfg)")] = make_pair(".cfg", &GloveWidget::saveMappingCfg); defaultFilter = filterMap.begin(); filterMap[tr("xacro configs (*.yaml)")] = make_pair(".yaml", &GloveWidget::saveMappingYAML); for (const auto &item : filterMap) { if (!sFilters.isEmpty()) sFilters.append(";;"); sFilters.append(item.first); } } // choose default filter from current file name QString selectedFilter = defaultFilter->first; for (const auto &item : filterMap) { if (sMappingFile.endsWith(item.second.first)) selectedFilter = item.first; } // exec file dialog QFileDialog dlg(this, "save taxel mapping", sMappingFile, sFilters); dlg.setFileMode(QFileDialog::AnyFile); dlg.selectNameFilter(selectedFilter); dlg.selectFile(sMappingFile); dlg.setLabelText(QFileDialog::Accept, tr("Save")); QString sFileName; QString mapping_name; FilterMap::const_iterator chosenFilter = filterMap.end(); while (true) { if (dlg.exec() == QDialog::Rejected) return; selectedFilter = dlg.selectedNameFilter(); sFileName = dlg.selectedFiles().first(); // which filter was choosen? chosenFilter = filterMap.find(selectedFilter); // file suffix superseeds chosen filter for (FilterMap::const_iterator it = filterMap.begin(), end = filterMap.end(); it != end; ++it) { if (sFileName.endsWith(it->second.first)) chosenFilter = it; } if (chosenFilter == filterMap.end()) chosenFilter = defaultFilter; // append default extension from selected filter QFileInfo fi(sFileName); if (fi.suffix().isEmpty()) sFileName.append(chosenFilter->second.first); if (fi.exists()) { FileExistsDialog msg(sFileName, chosenFilter->second.second == &GloveWidget::saveMappingCfg, this); int result = msg.exec(); if (result == QDialog::Rejected) continue; if (result == QDialogButtonBox::YesRole) QFile(sFileName).remove(); mapping_name = msg.mappingName(); } break; } // save name of mapping file for next saving attempt sMappingFile = sFileName; if ((gloveWidget->*chosenFilter->second.second)(sFileName, mapping_name)) bDirtyMapping = false; else QMessageBox::warning(this, "Save taxel mapping", QString("Failed to open file for writing:\n%1").arg(sFileName)); } /*** functions for connection handling ***/ template <typename value_type> void MainWindow::updateData(const std::vector<value_type> &frame) { QMutexLocker lock(&dataMutex); assert(frame.size() == data.size()); data.updateValues(frame.begin(), frame.end()); ++frameCount; } void MainWindow::configSerial(const QString &sDevice) { ui->inputLineEdit->setText(sDevice); ui->inputLineEdit->setToolTip("serial device name"); QSerialInput *serial = new QSerialInput(data.size()); serial->setUpdateFunction(boost::bind(&MainWindow::updateData<tactile::InputInterface::data_type>, this, _1)); connect(serial, SIGNAL(statusMessage(QString, int)), ui->statusBar, SLOT(showMessage(QString, int))); connect(serial, SIGNAL(disconnected(QString)), this, SLOT(onSerialError(QString))); input = serial; } void MainWindow::onSerialError(const QString &reason) { if (!reason.isEmpty()) { QTimer::singleShot(50, this, SLOT(on_btnDisconnect_clicked())); statusBar()->showMessage(reason, 5000); } } void MainWindow::configROS(const QString &sTopic) { #if HAVE_ROS ui->inputLineEdit->setText(sTopic); ui->inputLineEdit->setToolTip("ROS topic"); ROSInput *rosInput = new ROSInput(data.size()); rosInput->setUpdateFunction(boost::bind(&MainWindow::updateData<float>, this, _1)); connect(rosInput, SIGNAL(statusMessage(QString, int)), ui->statusBar, SLOT(showMessage(QString, int))); input = rosInput; on_btnConnect_clicked(); // auto-connect to ROS topic #endif } void MainWindow::configRandom() { ui->verticalLayout->addWidget(ui->inputLineEdit); ui->inputLineEdit->hide(); RandomInput *random = new RandomInput(data.size()); random->setUpdateFunction(boost::bind(&MainWindow::updateData<tactile::InputInterface::data_type>, this, _1)); input = random; } void MainWindow::on_btnConnect_clicked() { if (input->connect(ui->inputLineEdit->text())) { ui->statusBar->showMessage("Successfully connected.", 2000); frameCount = -1; lastUpdate.start(); timerID = startTimer(ui->updateTimeSpinBox->value()); ui->btnConnect->setEnabled(false); ui->btnDisconnect->setEnabled(true); ui->fps->show(); ui->toolBar->addWidget(ui->fps); } } void MainWindow::on_btnDisconnect_clicked() { ui->btnDisconnect->setEnabled(false); input->disconnect(); if (ui->statusBar->currentMessage().isEmpty()) ui->statusBar->showMessage("Disconnected.", 2000); resetColors(); ui->btnConnect->setEnabled(true); killTimer(timerID); timerID = 0; }
2643bb3d322af0821d68f3c038b068f681b3b1ce
d397b0d420dffcf45713596f5e3db269b0652dee
/src/Axe/ArchiveInvocation.hpp
00c46552b502d04a2a05c0c5aa43504803137eec
[]
no_license
irov/Axe
62cf29def34ee529b79e6dbcf9b2f9bf3709ac4f
d3de329512a4251470cbc11264ed3868d9261d22
refs/heads/master
2021-01-22T20:35:54.710866
2010-09-15T14:36:43
2010-09-15T14:36:43
85,337,070
0
0
null
null
null
null
UTF-8
C++
false
false
387
hpp
ArchiveInvocation.hpp
# pragma once # include <AxeUtil/ArchiveWrite.hpp> # include <Axe/ConnectionCache.hpp> namespace Axe { class ArchiveInvocation : public AxeUtil::ArchiveWrite { public: ArchiveInvocation( const ConnectionCachePtr & _connectionCache ); public: const ConnectionCachePtr & getConnectionCache() const; protected: ConnectionCachePtr m_connectionCache; }; }
4f582c2bd95e66017821d799913bcdc5faa554b0
49f15e237696d1c166c727fad9c8923d33497494
/cp-3/data structure /with built library/1d array/12356.cpp
4e9fd36f2261996ecaed75d0c07a4fddda7de169
[]
no_license
gauravkr123/Codes
280284a3c7cdab2454a8da267c0622b40707e32b
c0295cfbad7794a25c1d4cf85ef8d4d13da8f2c6
refs/heads/master
2020-03-22T17:29:24.819064
2017-12-14T17:59:33
2017-12-14T17:59:33
140,398,111
2
0
null
2018-07-10T08:01:38
2018-07-10T08:01:38
null
UTF-8
C++
false
false
1,127
cpp
12356.cpp
#include<bits/stdc++.h> using namespace std; int main() { int a,b; while(scanf("%d %d",&a,&b),(a||b)) { int death[a+1]={}; while(b--) { int x,y; cin>>x>>y; for(int i=x;i<=y;i++) { death[i]=1; } while(x--) { if(x>=1) { if(death[x]==0) { cout<<x<<" "; break; } } else { cout<<"* "; break; } } while(y++) { if(y<=a) { if(death[y]==0) { cout<<y<<" "; break; } } else { cout<<"* "; break; } } cout<<"\n"; } cout<<"-\n"; } }
4c84f9f98f278678bf224a35a48de16465e4838f
224bb4c15505e0b494eec0b911ee3fc67e6935db
/ServerBrowser/HistoryGames.h
030b8ddb8e6b6f9f254bf6442468cc187e23f1b0
[]
no_license
MoeMod/Thanatos-Launcher
7b19dcb432172ee35f050b4f4f46e37a1e46c612
1f38c7cc1ebc911805ecf83222b5254d4b25a132
refs/heads/master
2021-12-27T15:27:02.097029
2021-09-09T17:05:04
2021-09-09T17:05:04
128,214,239
9
2
null
null
null
null
UTF-8
C++
false
false
1,338
h
HistoryGames.h
#ifndef HISTORYGAMES_H #define HISTORYGAMES_H #ifdef _WIN32 #pragma once #endif #include "BaseGamesPage.h" #include "IGameList.h" #include <ServerBrowser/IServerRefreshResponse.h> #include "server.h" class CHistoryGames : public CBaseGamesPage { DECLARE_CLASS_SIMPLE(CHistoryGames, CBaseGamesPage); public: CHistoryGames(vgui2::Panel *parent); ~CHistoryGames(void); public: void LoadHistorysList(KeyValues *historysData); void SaveHistorysList(KeyValues *historysData); public: virtual void OnPageShow(void); virtual void OnPageHide(void); virtual void OnBeginConnect(void); virtual void OnViewGameInfo(void); public: virtual bool SupportsItem(InterfaceItem_e item); virtual void StartRefresh(void); virtual void GetNewServerList(void); virtual void StopRefresh(void); virtual bool IsRefreshing(void); virtual void AddNewServer(serveritem_t &server); virtual void ListReceived(bool moreAvailable, int lastUnique); virtual void ServerFailedToRespond(serveritem_t &server); virtual void RefreshComplete(void); public: void SetRefreshOnReload(void) { m_bRefreshOnListReload = true; } private: void OnRefreshServer(int serverID); private: MESSAGE_FUNC_INT(OnOpenContextMenu, "OpenContextMenu", itemID); MESSAGE_FUNC(OnRemoveFromHistory, "RemoveFromHistory"); private: bool m_bRefreshOnListReload; }; #endif
d370a170b563e479f3e29dc995cffe5a8ae4281f
9e646ddaa1f210a56b75d841697025e758e7339f
/LeetCode/LeetCode/KeyboardRow.cpp
2e1bb160a51f369858ef4ad4c2006eda69ecd253
[]
no_license
madpotato1713/algorithm
03faec881bc7aea99ae23395a081fc570a648e20
6789523646813780c6fcf77ab0a74887c0e41913
refs/heads/master
2020-09-17T04:27:12.723476
2020-08-26T16:25:37
2020-08-26T16:25:37
223,982,464
0
0
null
null
null
null
UTF-8
C++
false
false
1,821
cpp
KeyboardRow.cpp
/* CASE1 */ class Solution { public: vector<string> findWords(vector<string>& words) { vector<string> res; unordered_map<char, int> um; um['q'] = um['w'] = um['e'] = um['r'] = um['t'] = um['y'] = um['u'] = um['i'] = um['o'] = um['p'] = 1; um['Q'] = um['W'] = um['E'] = um['R'] = um['T'] = um['Y'] = um['U'] = um['I'] = um['O'] = um['P'] = 1; um['a'] = um['s'] = um['d'] = um['f'] = um['g'] = um['h'] = um['j'] = um['k'] = um['l'] = 2; um['A'] = um['S'] = um['D'] = um['F'] = um['G'] = um['H'] = um['J'] = um['K'] = um['L'] = 2; um['z'] = um['x'] = um['c'] = um['v'] = um['b'] = um['n'] = um['m'] = 3; um['Z'] = um['X'] = um['C'] = um['V'] = um['B'] = um['N'] = um['M'] = 3; for (int i = 0; i < words.size(); i++) { int val = um[words[i][0]]; for (int j = 1; j < words[i].size(); j++) { if (val != um[words[i][j]]) { val = 0; break; } } if (val) { res.push_back(words[i]); } } return res; } }; /* CASE2 */ class Solution { public: vector<string> findWords(vector<string>& words) { vector<string> res; unordered_map<char, int> um; um['q'] = um['w'] = um['e'] = um['r'] = um['t'] = um['y'] = um['u'] = um['i'] = um['o'] = um['p'] = 1; um['a'] = um['s'] = um['d'] = um['f'] = um['g'] = um['h'] = um['j'] = um['k'] = um['l'] = 2; um['z'] = um['x'] = um['c'] = um['v'] = um['b'] = um['n'] = um['m'] = 3; for (int i = 0; i < words.size(); i++) { char ch1 = words[i][0]; if (!(ch1 >= 'a' && ch1 <= 'z')) { ch1 = ch1 - 'A' + 'a'; } int val = um[ch1]; for (int j = 1; j < words[i].size(); j++) { char ch2 = words[i][j]; if (!(ch2 >= 'a' && ch2 <= 'z')) { ch2 = ch2 - 'A' + 'a'; } if (val != um[ch2]) { val = 0; break; } } if (val) { res.push_back(words[i]); } } return res; } };
256e7fa7776d182147936516e954356df64f164b
07eeea7ed7ca6772cce5de55e0eabb91cb47cd1b
/cgnspp/cgnsconverged.cpp
d7f6a56f8b63d29f82423698e8776c1485740183
[ "MIT" ]
permissive
octwanna/CGNSxx
2cefb8ce8163b22a71f73f942afb0820bffcc842
bbb6985ba1817c055e16a3b8ed1bb5fe3024730b
refs/heads/master
2021-05-09T22:07:35.755297
2017-10-03T00:05:16
2017-10-03T00:05:16
118,742,907
1
0
null
2018-01-24T09:28:53
2018-01-24T09:28:53
null
UTF-8
C++
false
false
1,954
cpp
cgnsconverged.cpp
/*************************************************************************** cgnsconverged.cpp - description ------------------- begin : Mon Mar 26 2001 Copyright (c) 1998-2004 Manuel Kessler, University of Stuttgart Copyright (c) 2001-2002 Udo Tremel, EADS Germany See the file COPYING in the toplevel directory for details. ***************************************************************************/ #include "cgnsconverged.h" #include "cgnsconvergence.h" #include "cgnsequationset.h" #include "cgnsreferencestate.h" #include "cgnsbroker.h" #include "cgnszone.h" #include <iostream> #include <assert.h> using CGNS::Converged; GENERATE_D(Converged); COMMON_NODE_IMPLEMENTATION(Converged); INIT_IMPLEMENTATION3(Converged, mHistory, mEqSet, mIntegral); CGNS::Private::Zone const * CGNS::Private::Converged::getZone() const { return P() ? static_cast<Zone const *>(this) : 0; } void CGNS::Private::Converged::Read(Converged * me, refcnt_ptr<ConvergenceHistory> & cDest) { assert(&cDest==&me->mHistory); // decide if this is a zone or base for stupid default name confusion char const * historyName=me->mParent ? "ZoneConvergenceHistory" : "GlobalConvergenceHistory"; readChild(me->mNode, historyName, cDest, me); } OPTIONAL_CHILD_IMPLEMENTATION(ConvergenceHistory, ConvergenceHistory, Converged, D()->mHistory) CGNS::ConvergenceHistory Converged::writeConvergenceHistory(int iNumIterations) { NEEDS(mHistory); char const * historyName=D()->P() ? "ZoneConvergenceHistory" : "GlobalConvergenceHistory"; CGNS::Private::ConvergenceHistory * history=Private::assureChild(D()->mHistory, historyName, D()); history->Modify(iNumIterations); return history; } OPTIONAL_CHILD_IMPLEMENTATION_WRITE(FlowEquationSet, FlowEquationSet, Converged, D()->mEqSet) N_CHILDS_IMPLEMENTATION_WRITE(IntegralData, IntegralData, Converged, D()->mIntegral)
917e94b17eaad8c1e98c34d62e7810902777da76
40138941b188d387e613c53f9aacf8cf54b55fd5
/code/creature.h
5039943409a8d16c6587b07e7702f26b9725f545
[]
no_license
RogerGee/AdventureGame
06c580f7f827dd84678486b1bf3f41886780ec8b
95e546912ff02d8ea3abbe69504def765ab61d2c
refs/heads/master
2021-01-21T13:18:23.396111
2014-10-16T21:18:19
2014-10-16T21:18:19
13,591,056
0
1
null
null
null
null
UTF-8
C++
false
false
900
h
creature.h
/* creature.h * Project: AdventureGame * Owner: Ethan Rutherford * Brief: Interface for creatures of various types. */ #ifndef ADVENTUREGAME_CREATURE_H #define ADVENTUREGAME_CREATURE_H #include <string> // get 'string' type #include "game_element.h" #include "tag.h" // get 'tag' type namespace adventure_game{ class Creature: public game_element{ public: bool isHostile() const {return hostile;} int getHealth() const {return health;} void takeDamage(int damage); int attack(); void invalidate() {isValidState = false;} bool isValid() const {return isValidState;} Creature(); protected: int power; bool hostile; //determines if creature attacks you. becomes true if you attack a non-hostile int health; String desc; private: bool isValidState; virtual void _loadFromMarkup(const tag&); virtual void _writeDescription() const; }; } #endif
5f826cbdc16e494f8b72d2a213050a3edc5c1712
75526e4ffbff7598208247dcfaa3b5ad07b703bd
/NeuralNetwork/Perceptron/Perceptron.h
63875fc911ccf989e6b3656bd15a7d8f2a0456c7
[ "BSD-2-Clause" ]
permissive
alekstheod/tnnlib
2106e4592a1f9939911949744ca365ea0ca22f2e
d69c26cf6df5b01e23fa35844433bce8d33f0455
refs/heads/master
2023-08-05T10:36:09.253840
2023-07-08T13:10:44
2023-07-08T13:10:44
21,096,548
6
1
BSD-2-Clause
2023-07-08T13:16:17
2014-06-22T15:03:31
C++
UTF-8
C++
false
false
4,841
h
Perceptron.h
#pragma once #include "NeuralNetwork/Serialization/PerceptronMemento.h" #include "NeuralNetwork/Utils/Utils.h" #include <MPL/Tuple.h> #include <MPL/Algorithm.h> #include <MPL/TypeTraits.h> #include <algorithm> #include <cassert> #include <tuple> #include <type_traits> namespace nn { namespace detail { template< typename Var, typename... Layers > struct Perceptron; template< typename Var, typename... Layers > static constexpr auto perceptron(std::tuple< Layers... >) -> Perceptron< Var, Layers... >; template< template< class > class Wrapper, typename... Layers > constexpr auto wrap_layers(std::tuple< Layers... >) -> std::tuple< Wrapper< Layers >... >; template< typename... Layers > constexpr auto layers_memento(std::tuple< Layers... >) -> std::tuple< typename Layers::Memento... >; /*! \class Perceptron * \briefs Contains an input neurons layer one output and one or more * hidden layers. */ template< typename VarType, typename... L > struct Perceptron { using Var = VarType; private: using TmplLayers = std::tuple< typename L::template use< Var >... >; public: using InputLayerType = utils::front_t< TmplLayers >; static constexpr auto size() { return sizeof...(L); } static constexpr auto inputs() { return InputLayerType::size(); } using Layers = typename mpl::rebindInputs< InputLayerType::inputs(), TmplLayers >::type; using OutputLayerType = typename std::tuple_element< size() - 1, Layers >::type; static constexpr auto outputs() { return OutputLayerType::size(); } template< template< class > typename Layer > using wrap = decltype(perceptron< Var >(wrap_layers< Layer >(std::declval< Layers >()))); using LayersMemento = decltype(layers_memento(std::declval< Layers >())); using Memento = PerceptronMemento< LayersMemento >; template< typename T > using use = decltype(perceptron< T >(std::declval< Layers >())); using Input = typename InputLayerType::Input; private: Layers m_layers; static_assert(std::tuple_size< Layers >::value > 1, "Invalid number of layers, at least two layers need " "to be set"); public: Layers& layers() { return m_layers; } void setMemento(const Memento& memento) { utils::for_< size() >([this, &memento](auto i) { auto& layer = utils::get< i.value >(m_layers); layer.setMemento(utils::get< i.value >(memento.layers)); }); } Memento getMemento() const { LayersMemento memento; utils::for_< size() >([this, &memento](auto i) { auto& layer = utils::get< i.value >(m_layers); utils::get< i.value >(memento) = layer.getMemento(); }); return {memento}; } /*! * @brief this method will calculate the outputs of perceptron. * @param begin is the iterator which is pointing to the first input * @param end the iterator which is pointing to the last input * @param out the output iterator where the results of the * calculation will be stored. */ template< typename Iterator, typename OutputIterator > void calculate(Iterator begin, Iterator end, OutputIterator out) { unsigned int inputId = 0; while(begin != end) { std::get< 0 >(m_layers).setInput(inputId, *begin); begin++; inputId++; } utils::for_< size() - 1U >([this](auto i) { auto& layer = utils::get< i.value >(m_layers); auto& nextLayer = utils::get< i.value + 1 >(m_layers); layer.calculateOutputs(nextLayer); }); auto& lastLayer = utils::get< size() - 1U >(m_layers); lastLayer.calculateOutputs(); for(const auto& neuron : lastLayer) { *out = neuron.getOutput(); ++out; } } }; } // namespace detail template< typename Var, typename... NeuralLayers > using Perceptron = detail::Perceptron< Var, NeuralLayers... >; } // namespace nn
701f5cd55df858f8ca995be53fbeba11d6c41516
e032843d31309ca21bfba351d45c354ee5a36e8b
/main.cpp
6b18cb6797547271fec65432b175d15e15b1142c
[]
no_license
yukiyoru98/Matrix
9fcbf3ab97e8af686fc9313b63a852ced3728020
94b88cdd6abb198d0c0864126bec2aeb60dafcc3
refs/heads/master
2022-04-25T11:34:18.790205
2020-04-26T02:51:49
2020-04-26T02:51:49
258,924,360
0
0
null
null
null
null
UTF-8
C++
false
false
1,962
cpp
main.cpp
#include<iostream> #include"Matrix.h" #include"Complex.h" using namespace std; int main() { cout << "<<Default Construster>>\ntest1\n"; Matrix test1; test1.displayData(); cout << endl; cout << "\n<<Constructor>> (只設定大小, 資料預設為0)"<<endl; cout<<"test2\n"; Matrix test2(3, 4); test2.displayData(); cout << endl; cout << "\n<<Constructor>>\ntest3a\n"; Complex m2[6] = { Complex(3,-1),Complex(3.7,0),Complex(8.9,-1),Complex(2,0),Complex(-1.3,1),Complex(2.3,0) }; Matrix test3a(3, 2, m2, 6); test3a.displayData(); cout << endl; cout << "test3b\n"; //for multiply Complex m1[6] = { Complex(2.4,1),Complex(2.8,0),Complex(-29.1,1),Complex(4,0),Complex(-2,-1),Complex(72.3,0) }; Matrix test3b(2, 3, m1, 6); test3b.displayData(); cout << endl; cout << "\n<<Copy constructor>>\ntest4\n"; Matrix test4(test3a); test4.displayData(); cout << endl; cout << "\n<<Set data>>\ntest4\n"; test4.setData(0, 1, Complex(7.4,-1)); test4.displayData(); cout << endl; cout << "\ntest4(row,col)="<<"("<< test4.getRow()<<","<< test4.getCol()<<")"<<endl; cout << endl; cout << "\ntest4(0,1)=";//Get data test4.getData(0, 1).print(); cout << endl ; cout << "\n\n<<Add>>" << endl; cout << "test3a + test4:"<< endl; test3a.displayData(); cout << " +\n"; test4.displayData(); cout << " =" << endl; test3a.add(test4).displayData(); cout << endl; cout << "\n<<Mmultiply>>" << endl; cout << "test3a * test3b" << endl; test3a.displayData(); cout << " *\n"; test3b.displayData(); cout << " =" << endl; test3a.multiply(test3b).displayData(); cout << endl; cout << "\n<<Transpose>>\n"; test4.displayData(); cout << "transpose\n"; test4.transpose().displayData(); cout << endl; system("pause"); return 0; }
e8d42dc4b00e0ee9b305947cfd1f5594f2217e58
09ac39bfd5b8fd30a2764d6c975deb7b41029cea
/src/core/renderer/Voxelizer.h
ef289a6ee65c8da856a1ec44b1e99a18534baf87
[ "MIT" ]
permissive
Kelan0/SVOEngine
5a5c07efeeb97de86761cff2e819b8cd6aedda7c
b3546715a07c13d240e6ba6fb42e90f175a9d937
refs/heads/master
2021-02-07T06:45:53.386926
2020-05-24T14:04:27
2020-05-24T14:04:27
243,963,877
0
0
null
null
null
null
UTF-8
C++
false
false
2,552
h
Voxelizer.h
#pragma once #include "core/pch.h" class ShaderProgram; class Voxelizer { enum VoxelStorage { POSITION = 0, CHILD_INDEX = 0, ALBEDO = 1, NORMAL = 2, EMISSIVE = 3 }; enum VoxelizationStage { FRAGMENT_COUNT = 0, FRAGMENT_STORAGE = 1, OCTREE_FLAG = 2, OCTREE_ALLOCATE = 3, OCTREE_INITIALIZE = 4, LIGHT_INJECTION = 5, VISUALIZATION_COPY = 6, VISUALIZATION = 6, }; public: Voxelizer(uint32_t size, double scale); ~Voxelizer(); void startRender(); void finishRender(); void renderPass(double dt, double partialTicks); void renderDebug(); void applyUniforms(ShaderProgram* shaderProgram); void updateAxisProjections(); void allocateVoxelFragmentList(uint64_t allocatedVoxels); void allocateOctreeStorageList(uint64_t allocatedVoxels); void setSize(uint32_t size); void setScale(double scale); void setPosition(dvec3 position); uint32_t getSize() const; double getScale() const; dvec3 getPosition() const; static ShaderProgram* voxelGenerationShader(); static ShaderProgram* voxelOctreeFlagShader(); static ShaderProgram* voxelOctreeAllocShader(); static ShaderProgram* voxelOctreeInitShader(); static ShaderProgram* voxelDirectLightInjectionShader(); static ShaderProgram* voxelVisualizationShader(); static ShaderProgram* voxelVisualizationCopyShader(); static ShaderProgram* voxelClearShader(); private: void initTextureBufferStorage(uint64_t size, uint32_t format, uint32_t* textureHandlePtr, uint32_t* textureBufferHandlePtr); uint32_t m_size; double m_scale; dvec3 m_position; bool m_countVoxelPass; uint32_t m_voxelFragmentCount; uint32_t m_allocatedOctreeCount; dmat4 m_axisProjections[3]; uint32_t m_voxelFragmentCounterBuffer; uint32_t m_voxelFragmentListTexture[4]; uint32_t m_voxelFragmentListTextureBuffer[4]; uint32_t m_octreeStorageCounterBuffer; uint32_t m_octreeStorageTexture[4]; uint32_t m_octreeStorageTextureBuffer[4]; uint32_t m_voxelVisualizationTexture; uint32_t m_tempVAO; VoxelizationStage m_voxelizationStage; static ShaderProgram* s_voxelGenerationShader; static ShaderProgram* s_voxelOctreeFlagShader; static ShaderProgram* s_voxelOctreeAllocShader; static ShaderProgram* s_voxelOctreeInitShader; static ShaderProgram* s_voxelDirectLightInjectionShader; static ShaderProgram* s_voxelVisualizationShader; static ShaderProgram* s_voxelVisualizationCopyShader; static ShaderProgram* s_voxelClearShader; };
17e43b8ec18df34b3d3663f4003e4b098c264cf8
9b98a87adf62be44af9c0d93ee8359999a1f5d9b
/GameEngineProject/Intermediate/Build/Win64/UE4Editor/Inc/GameEngineProject/GameEngineProjectGameMode.generated.h
b2dda0f290c5b954c95824cef615962592a4550c
[]
no_license
PFratt/UnrealProject
395a482698773b6dbfe4b2589cace5f5bc246952
652a0251d135832e65a5e285b72f17c7d9c284fc
refs/heads/master
2020-07-27T02:20:26.222550
2019-10-21T14:01:39
2019-10-21T14:01:39
208,834,258
0
0
null
null
null
null
UTF-8
C++
false
false
4,943
h
GameEngineProjectGameMode.generated.h
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef GAMEENGINEPROJECT_GameEngineProjectGameMode_generated_h #error "GameEngineProjectGameMode.generated.h already included, missing '#pragma once' in GameEngineProjectGameMode.h" #endif #define GAMEENGINEPROJECT_GameEngineProjectGameMode_generated_h #define GameEngineProject_Source_GameEngineProject_GameEngineProjectGameMode_h_12_RPC_WRAPPERS #define GameEngineProject_Source_GameEngineProject_GameEngineProjectGameMode_h_12_RPC_WRAPPERS_NO_PURE_DECLS #define GameEngineProject_Source_GameEngineProject_GameEngineProjectGameMode_h_12_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesAGameEngineProjectGameMode(); \ friend struct Z_Construct_UClass_AGameEngineProjectGameMode_Statics; \ public: \ DECLARE_CLASS(AGameEngineProjectGameMode, AGameModeBase, COMPILED_IN_FLAGS(0 | CLASS_Transient), CASTCLASS_None, TEXT("/Script/GameEngineProject"), GAMEENGINEPROJECT_API) \ DECLARE_SERIALIZER(AGameEngineProjectGameMode) #define GameEngineProject_Source_GameEngineProject_GameEngineProjectGameMode_h_12_INCLASS \ private: \ static void StaticRegisterNativesAGameEngineProjectGameMode(); \ friend struct Z_Construct_UClass_AGameEngineProjectGameMode_Statics; \ public: \ DECLARE_CLASS(AGameEngineProjectGameMode, AGameModeBase, COMPILED_IN_FLAGS(0 | CLASS_Transient), CASTCLASS_None, TEXT("/Script/GameEngineProject"), GAMEENGINEPROJECT_API) \ DECLARE_SERIALIZER(AGameEngineProjectGameMode) #define GameEngineProject_Source_GameEngineProject_GameEngineProjectGameMode_h_12_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ GAMEENGINEPROJECT_API AGameEngineProjectGameMode(const FObjectInitializer& ObjectInitializer); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(AGameEngineProjectGameMode) \ DECLARE_VTABLE_PTR_HELPER_CTOR(GAMEENGINEPROJECT_API, AGameEngineProjectGameMode); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AGameEngineProjectGameMode); \ private: \ /** Private move- and copy-constructors, should never be used */ \ GAMEENGINEPROJECT_API AGameEngineProjectGameMode(AGameEngineProjectGameMode&&); \ GAMEENGINEPROJECT_API AGameEngineProjectGameMode(const AGameEngineProjectGameMode&); \ public: #define GameEngineProject_Source_GameEngineProject_GameEngineProjectGameMode_h_12_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ GAMEENGINEPROJECT_API AGameEngineProjectGameMode(AGameEngineProjectGameMode&&); \ GAMEENGINEPROJECT_API AGameEngineProjectGameMode(const AGameEngineProjectGameMode&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(GAMEENGINEPROJECT_API, AGameEngineProjectGameMode); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AGameEngineProjectGameMode); \ DEFINE_DEFAULT_CONSTRUCTOR_CALL(AGameEngineProjectGameMode) #define GameEngineProject_Source_GameEngineProject_GameEngineProjectGameMode_h_12_PRIVATE_PROPERTY_OFFSET #define GameEngineProject_Source_GameEngineProject_GameEngineProjectGameMode_h_9_PROLOG #define GameEngineProject_Source_GameEngineProject_GameEngineProjectGameMode_h_12_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ GameEngineProject_Source_GameEngineProject_GameEngineProjectGameMode_h_12_PRIVATE_PROPERTY_OFFSET \ GameEngineProject_Source_GameEngineProject_GameEngineProjectGameMode_h_12_RPC_WRAPPERS \ GameEngineProject_Source_GameEngineProject_GameEngineProjectGameMode_h_12_INCLASS \ GameEngineProject_Source_GameEngineProject_GameEngineProjectGameMode_h_12_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define GameEngineProject_Source_GameEngineProject_GameEngineProjectGameMode_h_12_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ GameEngineProject_Source_GameEngineProject_GameEngineProjectGameMode_h_12_PRIVATE_PROPERTY_OFFSET \ GameEngineProject_Source_GameEngineProject_GameEngineProjectGameMode_h_12_RPC_WRAPPERS_NO_PURE_DECLS \ GameEngineProject_Source_GameEngineProject_GameEngineProjectGameMode_h_12_INCLASS_NO_PURE_DECLS \ GameEngineProject_Source_GameEngineProject_GameEngineProjectGameMode_h_12_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS template<> GAMEENGINEPROJECT_API UClass* StaticClass<class AGameEngineProjectGameMode>(); #undef CURRENT_FILE_ID #define CURRENT_FILE_ID GameEngineProject_Source_GameEngineProject_GameEngineProjectGameMode_h PRAGMA_ENABLE_DEPRECATION_WARNINGS
dfd51d08bb23915fc8f95c95fe14f56253fec0e7
0568e3d075240aba67b22a2befa8c5a7e6a4484c
/core/frechet.h
fd9d93e91e832401c29c87d50d43baa17fec97b9
[ "Apache-2.0" ]
permissive
Cecca/FRESH
9c723276ae527e880e2d415c17e08c84bb6f6089
d7740ed59b1566bf77f6a54ed3423e6a3d62e230
refs/heads/master
2020-03-27T18:10:57.264735
2018-09-02T09:07:13
2018-09-02T09:07:13
146,903,653
6
0
null
null
null
null
UTF-8
C++
false
false
20,073
h
frechet.h
/* * Copyright 2018 Matteo Ceccarello * * 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. */ #pragma once #ifndef CURVEDIST_FRECHER_H #define CURVEDIST_FRECHER_H #include "prelude.h" #include "types.h" #include "omp.h" #include "babr/frechet_distance.hpp" #define INCREASE_COUNTER(counter) \ if (tl_cfdp_current_simplification < 0) { \ _Pragma("omp atomic") \ tl_cfdp_ ## counter++; \ } else {\ _Pragma("omp atomic") \ tl_cfdp_simplification_ ## counter[tl_cfdp_current_simplification]++; \ } enum CFDPExitReason { GREEDY, NEGATIVE_FILTER, FULL }; extern CFDPExitReason tl_cfdp_exit_reason; #pragma omp threadprivate(tl_cfdp_exit_reason) extern int tl_cfdp_current_simplification; #pragma omp threadprivate(tl_cfdp_current_simplification) // Thread local counters for frechet distance predicate, for profiling purposes extern size_t tl_cfdp_positives_greedy, tl_cfdp_negatives_filter, tl_cfdp_invocations, tl_cfdp_negatives_start_end, tl_cfdp_positives_equal_time, tl_cfdp_negatives_full, tl_cfdp_positives_full; #pragma omp threadprivate(tl_cfdp_positives_greedy,tl_cfdp_negatives_filter,tl_cfdp_invocations,tl_cfdp_negatives_start_end,tl_cfdp_positives_equal_time,tl_cfdp_negatives_full,tl_cfdp_positives_full) #define MAX_COUNTABLE_SIMPLIFICATIONS 16 extern std::array<size_t, MAX_COUNTABLE_SIMPLIFICATIONS> tl_cfdp_simplification_positives_equal_time, tl_cfdp_simplification_positives_greedy, tl_cfdp_simplification_positives_full, tl_cfdp_simplification_negatives_filter, tl_cfdp_simplification_negatives_full; #pragma omp threadprivate(tl_cfdp_simplification_positives_equal_time,tl_cfdp_simplification_positives_greedy,tl_cfdp_simplification_positives_full,tl_cfdp_simplification_negatives_filter,tl_cfdp_simplification_negatives_full) /// Return true if the first or last pair of points are farther than range template<typename Point> bool start_end_heuristic(const Curve<Point> &a, const Curve<Point> &b, double range) { return ((euclidean(a[0], b[0]) > range) || (euclidean(a[a.size() - 1], b[b.size() - 1]) > range)); } double discrete_frechet_distance_r(const std::vector<Point2D> &a, const std::vector<Point2D> &b); template <typename Point> double discrete_frechet_distance(const std::vector<Point> &a, const std::vector<Point> &b, std::vector<double> &previous_row, std::vector<double> &current_row) { // TODO: see if it's convenient to always use the shortest or // longest curve to populate the row previous_row.clear(); current_row.clear(); previous_row.resize(a.size()); current_row.resize(a.size()); // Initialize the first row of the table current_row[0] = euclidean_squared(a[0], b[0]); for (size_t i = 1; i < a.size(); i++) { current_row[i] = std::max(current_row[i - 1], euclidean_squared(a[i], b[0])); } for (size_t j = 1; j < b.size(); j++) { // Swap current and previous row current_row.swap(previous_row); // Initialize first element of current row current_row[0] = std::max(previous_row[0], euclidean_squared(a[0], b[j])); for (size_t i = 1; i < a.size(); i++) { double min = std::min(current_row[i - 1], std::min(previous_row[i - 1], previous_row[i])); current_row[i] = std::max(min, euclidean_squared(a[i], b[j])); } } return std::sqrt(current_row[a.size() - 1]); } template <typename Point> double discrete_frechet_distance(const Curve<Point> &a, const Curve<Point> &b, double bound, std::vector<double> &previous_row, std::vector<double> &current_row) { // TODO: see if it's convenient to always use the shortest or // longest curve to populate the row // we are using squared Euclidean distances. The additive term is to // take into account rounding errors bound = (bound * bound) + 0.00001; previous_row.clear(); current_row.clear(); previous_row.resize(a.size()); current_row.resize(a.size()); current_row[0] = euclidean_squared(a[0], b[0]); // Check for early termination if (current_row[0] > bound || euclidean_squared(a[a.size() - 1], b[b.size() - 1]) > bound) { return -1.0; } // Initialize the first row of the table for (size_t i = 1; i < a.size(); i++) { current_row[i] = std::max(current_row[i - 1], euclidean_squared(a[i], b[0])); } for (size_t j = 1; j < b.size(); j++) { // Swap current and previous row current_row.swap(previous_row); // Initialize first element of current row current_row[0] = std::max(previous_row[0], euclidean_squared(a[0], b[j])); for (size_t i = 1; i < a.size(); i++) { double min = std::min(current_row[i - 1], std::min(previous_row[i - 1], previous_row[i])); current_row[i] = std::max(min, euclidean_squared(a[i], b[j])); } } return std::sqrt(current_row[a.size() - 1]); } inline void idx_to_pair(const size_t k, const size_t wrap, size_t &i, size_t &j) { i = k / wrap; j = k % wrap; } inline void pair_to_idx(const size_t i, const size_t j, const size_t wrap, size_t &k) { k = i * wrap + j; } template <typename Point> bool discrete_frechet_distance_predicate(const Curve<Point> &a, const Curve<Point> &b, double bound, std::vector<size_t> &stack, std::vector<bool> &visited) { /* bound = (bound * bound); */ stack.clear(); stack.reserve(std::min(a.size(), b.size())); visited.clear(); size_t matrix_size = a.size() * b.size(); visited.resize(matrix_size); std::fill(visited.begin(), visited.end(), false); const size_t wrap = b.size(); size_t i = a.size() - 1; size_t j = b.size() - 1; if (euclidean(a[i], b[j]) > bound || euclidean(a[0], b[0]) > bound) { return false; } size_t k; pair_to_idx(i, j, wrap, k); // printf("[%lu] (%lu, %lu) {a: %lu, b: %lu, flags: %lu}\n", k, i, j, // a.size(), // b.size(), tl_visited.size()); visited[k] = true; stack.push_back(k); while (!stack.empty()) { k = stack.back(); stack.pop_back(); idx_to_pair(k, wrap, i, j); // printf("[%lu] (%lu, %lu) {a: %lu, b: %lu, flags: %lu}\n", k, i, j, // a.size(), // b.size(), tl_visited.size()); if (i == 0 && j == 0) { return true; // We got there! } if (i > 0 && j > 0) { pair_to_idx(i - 1, j - 1, wrap, k); if (!visited[k] && euclidean(a[i - 1], b[j - 1]) <= bound) { stack.push_back(k); visited[k] = true; } } if (i > 0) { pair_to_idx(i - 1, j, wrap, k); if (!visited[k] && euclidean(a[i - 1], b[j]) <= bound) { stack.push_back(k); visited[k] = true; } } if (j > 0) { pair_to_idx(i, j - 1, wrap, k); if (!visited[k] && euclidean(a[i], b[j - 1]) <= bound) { stack.push_back(k); visited[k] = true; } } } // we found no path, fail return false; } extern std::vector<size_t> g_tl_stack; extern std::vector<bool> g_tl_visited; #pragma omp threadprivate(g_tl_stack, g_tl_visited) template <typename Point> bool discrete_frechet_distance_predicate(const Curve<Point> &a, const Curve<Point> &b, double bound) { return discrete_frechet_distance_predicate(a, b, bound, g_tl_stack, g_tl_visited); } /// Report counters to the global experiment void report_counters(); template<typename Point> void simplify(const double mu, const Curve<Point> &input, Curve<Point> &output) { double mu_mu = mu * mu; size_t n = input.size(); output.clear(); Point last = input.at(0); output.push_back(input[0]); for (size_t i = 1; i < n - 1; i++) { if (euclidean_squared<Point>(last, input[i]) > mu_mu) { output.push_back(input[i]); last = input[i]; } } output.push_back(input[n - 1]); } /// Implementation of the continuous Frechet distance predicate template<typename Point> bool continuous_frechet_distance_predicate_impl(const Curve<Point> &a, const Curve<Point> &b, double bound) { if (babr::get_frechet_distance_upper_bound(a, b) <= bound) { tl_cfdp_exit_reason = CFDPExitReason::GREEDY; return true; } else if (babr::negfilter(a, b, bound)) { tl_cfdp_exit_reason = CFDPExitReason::NEGATIVE_FILTER; return false; } else if (babr::is_frechet_distance_at_most(a, b, bound)) { tl_cfdp_exit_reason = CFDPExitReason::FULL; return true; } else { tl_cfdp_exit_reason = CFDPExitReason::FULL; return false; } } template<typename Point> bool continuous_frechet_distance_predicate(const Curve<Point> &a, const Curve<Point> &b, double bound); template<> inline bool continuous_frechet_distance_predicate(const Curve<Point1D> &a, const Curve<Point1D> &b, double bound){ return continuous_frechet_distance_predicate_impl<Point1D>(a, b, bound); } template<> inline bool continuous_frechet_distance_predicate(const Curve<Point2D> &a, const Curve<Point2D> &b, double bound){ return continuous_frechet_distance_predicate_impl<Point2D>(a, b, bound); } extern std::vector<double> tl_cumulative_dist_a; extern std::vector<double> tl_cumulative_dist_b; #pragma omp threadprivate(tl_cumulative_dist_a, tl_cumulative_dist_b) template<typename Point> double equal_time_distance(const Curve<Point> &a, const Curve<Point> &b); template<> inline double equal_time_distance(const Curve<Point2D> &a, const Curve<Point2D> &b) { tl_cumulative_dist_a.clear(); tl_cumulative_dist_b.clear(); tl_cumulative_dist_a.resize(a.size()); tl_cumulative_dist_b.resize(b.size()); tl_cumulative_dist_a[0] = 0; double sum = 0.0; for (size_t i = 1; i < a.size(); i++) { sum += sum + euclidean(a[i - 1], a[i]); tl_cumulative_dist_a[i] = sum; } tl_cumulative_dist_b[0] = 0; sum = 0.0; for (size_t i = 1; i < b.size(); i++) { sum += sum + euclidean(b[i - 1], b[i]); tl_cumulative_dist_b[i] = sum; } double total_length_a = tl_cumulative_dist_a[a.size() - 1]; double total_length_b = tl_cumulative_dist_b[b.size() - 1]; double max_dist = euclidean(a[0], b[0]); size_t idx_a = 1; size_t idx_b = 1; Point2D pt_a, pt_b; while ((idx_a < a.size()) && (idx_b < b.size())) { // The position in the interval [0, 1] corresponding to the // current index for a and b double pos_a = tl_cumulative_dist_a[idx_a] / total_length_a; double pos_b = tl_cumulative_dist_b[idx_b] / total_length_b; if (pos_a < pos_b) { // the index of a is behind b in terms of equal-time pt_a = a[idx_a]; // we initialize pt_b to a point mid-segment, where the segment is the one double time_offset = pos_a - (tl_cumulative_dist_b[idx_b - 1] / total_length_b); double diff_x = b[idx_b].x - b[idx_b - 1].x; double diff_y = b[idx_b].y - b[idx_b - 1].y; pt_b.x = b[idx_b].x + time_offset * diff_x; pt_b.y = b[idx_b].y + time_offset * diff_y; idx_a++; } else { pt_b = b[idx_b]; double time_offset = pos_b - (tl_cumulative_dist_a[idx_a - 1] / total_length_a); double diff_x = a[idx_a].x - a[idx_a - 1].x; double diff_y = a[idx_a].y - a[idx_a - 1].y; pt_a.x = a[idx_a].x + time_offset * diff_x; pt_a.y = a[idx_a].y + time_offset * diff_y; idx_b++; } double d = euclidean(pt_a, pt_b); if (d > max_dist) { max_dist = d; } } double d = euclidean(a[a.size() - 1], b[b.size() - 1]); if (d > max_dist) { max_dist = d; } return max_dist; } template<> inline double equal_time_distance(const Curve<Point1D> &a, const Curve<Point1D> &b) { tl_cumulative_dist_a.clear(); tl_cumulative_dist_b.clear(); tl_cumulative_dist_a.resize(a.size()); tl_cumulative_dist_b.resize(b.size()); tl_cumulative_dist_a[0] = 0; double sum = 0.0; for (size_t i = 1; i < a.size(); i++) { sum += sum + euclidean(a[i - 1], a[i]); tl_cumulative_dist_a[i] = sum; } tl_cumulative_dist_b[0] = 0; sum = 0.0; for (size_t i = 1; i < b.size(); i++) { sum += sum + euclidean(b[i - 1], b[i]); tl_cumulative_dist_b[i] = sum; } double total_length_a = tl_cumulative_dist_a[a.size() - 1]; double total_length_b = tl_cumulative_dist_b[b.size() - 1]; double max_dist = euclidean(a[0], b[0]); size_t idx_a = 1; size_t idx_b = 1; Point1D pt_a, pt_b; while ((idx_a < a.size()) && (idx_b < b.size())) { // The position in the interval [0, 1] corresponding to the // current index for a and b double pos_a = tl_cumulative_dist_a[idx_a] / total_length_a; double pos_b = tl_cumulative_dist_b[idx_b] / total_length_b; if (pos_a < pos_b) { // the index of a is behind b in terms of equal-time pt_a = a[idx_a]; // we initialize pt_b to a point mid-segment, where the segment is the one double time_offset = pos_a - (tl_cumulative_dist_b[idx_b - 1] / total_length_b); double diff_x = b[idx_b].x - b[idx_b - 1].x; pt_b.x = b[idx_b].x + time_offset * diff_x; idx_a++; } else { pt_b = b[idx_b]; double time_offset = pos_b - (tl_cumulative_dist_a[idx_a - 1] / total_length_a); double diff_x = a[idx_a].x - a[idx_a - 1].x; pt_a.x = a[idx_a].x + time_offset * diff_x; idx_b++; } double d = euclidean(pt_a, pt_b); if (d > max_dist) { max_dist = d; } } double d = euclidean(a[a.size() - 1], b[b.size() - 1]); if (d > max_dist) { max_dist = d; } return max_dist; } enum FuzzyResult { YES, YES_ET, NO, MAYBE }; extern Curve<Point2D> tl_a_simplification_2d; extern Curve<Point2D> tl_b_simplification_2d; extern Curve<Point1D> tl_a_simplification_1d; extern Curve<Point1D> tl_b_simplification_1d; #pragma omp threadprivate(tl_a_simplification_2d, tl_b_simplification_2d, tl_a_simplification_1d, tl_b_simplification_1d) template<typename Point> FuzzyResult fuzzy_decide(const Curve<Point> &a, const Curve<Point> &b, const double epsilon, const double delta, Curve<Point> & simplification_a, Curve<Point> & simplification_b) { double mu = epsilon / 4 * delta; double delta_prime = delta + 2 * mu; simplify<Point>(mu, a, simplification_a); simplify<Point>(mu, b, simplification_b); if (!continuous_frechet_distance_predicate(simplification_a, simplification_b, delta_prime)) { return FuzzyResult::NO; } double delta_positive = delta / (1 + epsilon); mu = epsilon / 4 * delta_positive; delta_prime = delta_positive + 2 * mu; simplify<Point>(mu, a, simplification_a); simplify<Point>(mu, b, simplification_b); if (equal_time_distance(simplification_a, simplification_b) <= delta_prime) { return FuzzyResult::YES_ET; } else if (continuous_frechet_distance_predicate(simplification_a, simplification_b, delta_prime)) { return FuzzyResult::YES; } else { return FuzzyResult::MAYBE; } } template<typename Point> FuzzyResult fuzzy_decide(const Curve<Point> &a, const Curve<Point> &b, const double epsilon, const double delta); template<> inline FuzzyResult fuzzy_decide(const Curve<Point1D> &a, const Curve<Point1D> &b, const double epsilon, const double delta) { return fuzzy_decide(a, b, epsilon, delta, tl_a_simplification_1d, tl_b_simplification_1d); } template<> inline FuzzyResult fuzzy_decide(const Curve<Point2D> &a, const Curve<Point2D> &b, const double epsilon, const double delta) { return fuzzy_decide(a, b, epsilon, delta, tl_a_simplification_2d, tl_b_simplification_2d); } template <typename Point> bool continuous_frechet_distance_predicate(const Curve<Point> &a, const Curve<Point> &b, double range, const std::vector<double> &simplification_epsilons) { const size_t n_simplifications = simplification_epsilons.size(); #pragma omp atomic tl_cfdp_invocations++; if (start_end_heuristic(a, b, range)) { #pragma omp atomic tl_cfdp_negatives_start_end++; return false; // This is a negative match } // Check the simplifications for (size_t i = 0; i < n_simplifications; i++) { tl_cfdp_current_simplification = i; double epsilon = simplification_epsilons[i]; switch (fuzzy_decide(a, b, epsilon, range)) { case FuzzyResult::YES_ET: INCREASE_COUNTER(positives_equal_time); /* tl_cfdp_simplification_positives_equal_time.at(i)++; */ return true; case FuzzyResult::YES: /* tl_cfdp_simplification_positives.at(i)++; */ switch(tl_cfdp_exit_reason) { case CFDPExitReason::GREEDY: INCREASE_COUNTER(positives_greedy); break; case CFDPExitReason::FULL: INCREASE_COUNTER(positives_full); break; default: throw std::logic_error("should not be here"); } return true; case FuzzyResult::NO: /* tl_cfdp_simplification_negatives.at(i)++; */ switch(tl_cfdp_exit_reason) { case CFDPExitReason::NEGATIVE_FILTER: INCREASE_COUNTER(negatives_filter); break; case CFDPExitReason::FULL: INCREASE_COUNTER(negatives_full); break; default: throw std::logic_error("should not be here"); } return false; case FuzzyResult::MAYBE: // Go on and check next simplification break; } } tl_cfdp_current_simplification = -1; // Check equal time distance if (equal_time_distance(a, b) <= range) { INCREASE_COUNTER(positives_equal_time); /* tl_cfdp_equal_time_positives++; */ return true; } // Check the true distance if (continuous_frechet_distance_predicate(a, b, range)) { /* tl_cfdp_full_distance_positives++; */ switch(tl_cfdp_exit_reason) { case CFDPExitReason::GREEDY: INCREASE_COUNTER(positives_greedy); break; case CFDPExitReason::FULL: INCREASE_COUNTER(positives_full); break; default: throw std::logic_error("should not be here"); } return true; } else { /* tl_cfdp_full_distance_negatives++; */ switch(tl_cfdp_exit_reason) { case CFDPExitReason::NEGATIVE_FILTER: INCREASE_COUNTER(negatives_filter); break; case CFDPExitReason::FULL: INCREASE_COUNTER(negatives_full); break; default: throw std::logic_error("should not be here"); } return false; } } #endif // CURVEDIST_FRECHER_H
ef30169643090cc16515d9b486e8529d39e94af3
62669fbaa3d9b52bd34a8ab8bf781f2d18b3778b
/dlib/test/threads.cpp
1aeb1a3f96b29f4f91116e8fa4020b0433d2e21f
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
davisking/dlib
05c04e5c73c8b92526c77431e9bb622974ffe3f2
f6c58c2d21a49d84967e48ffa33e7d1c783ae671
refs/heads/master
2023-09-06T08:22:13.063202
2023-08-26T23:55:59
2023-08-26T23:55:59
16,331,291
13,118
3,600
BSL-1.0
2023-09-10T12:50:42
2014-01-29T00:45:33
C++
UTF-8
C++
false
false
4,580
cpp
threads.cpp
// Copyright (C) 2006 Davis E. King (davis@dlib.net) // License: Boost Software License See LICENSE.txt for the full license. #include <sstream> #include <string> #include <cstdlib> #include <ctime> #include <dlib/misc_api.h> #include <dlib/threads.h> #include "tester.h" namespace { using namespace test; using namespace dlib; using namespace std; logger dlog("test.threads"); void test_async() { #if __cplusplus >= 201103 print_spinner(); auto v1 = dlib::async([]() { dlib::sleep(500); return 1; }).share(); auto v2 = dlib::async([v1]() { dlib::sleep(400); return v1.get()+1; }).share(); auto v3 = dlib::async([v2](int a) { dlib::sleep(300); return v2.get()+a; },2).share(); auto v4 = dlib::async([v3]() { dlib::sleep(200); return v3.get()+1; }); DLIB_TEST(v4.get() == 5); print_spinner(); auto except = dlib::async([](){ dlib::sleep(300); throw error("oops"); }); bool got_exception = false; try { except.get(); } catch (error&e) { got_exception = true; DLIB_TEST(e.what() == string("oops")); } DLIB_TEST(got_exception); #endif } class threads_tester : public tester { public: threads_tester ( ) : tester ("test_threads", "Runs tests on the threads component."), sm(cm) {} thread_specific_data<int> tsd; rmutex cm; rsignaler sm; int count; bool failure; void perform_test ( ) { failure = false; print_spinner(); count = 10; if (!create_new_thread<threads_tester,&threads_tester::thread1>(*this)) failure = true; if (!create_new_thread<threads_tester,&threads_tester::thread2>(*this)) failure = true; if (!create_new_thread<threads_tester,&threads_tester::thread3>(*this)) failure = true; if (!create_new_thread<threads_tester,&threads_tester::thread4>(*this)) failure = true; if (!create_new_thread<threads_tester,&threads_tester::thread5>(*this)) failure = true; if (!create_new_thread<threads_tester,&threads_tester::thread6>(*this)) failure = true; if (!create_new_thread<threads_tester,&threads_tester::thread7>(*this)) failure = true; if (!create_new_thread<threads_tester,&threads_tester::thread8>(*this)) failure = true; if (!create_new_thread<threads_tester,&threads_tester::thread9>(*this)) failure = true; if (!create_new_thread<threads_tester,&threads_tester::thread10>(*this)) failure = true; thread(66); // this should happen in the main program thread if (is_dlib_thread()) failure = true; auto_mutex M(cm); while (count > 0 && !failure) sm.wait(); DLIB_TEST(!failure); test_async(); } void thread_end_handler ( ) { auto_mutex M(cm); --count; if (count == 0) sm.signal(); } void thread1() { thread(1); } void thread2() { thread(2); if (is_dlib_thread() == false) failure = true; } void thread3() { thread(3); } void thread4() { thread(4); } void thread5() { thread(5); } void thread6() { thread(6); } void thread7() { thread(7); } void thread8() { thread(8); } void thread9() { thread(9); } void thread10() { thread(10); } void thread ( int num ) { dlog << LTRACE << "starting thread num " << num; if (is_dlib_thread()) register_thread_end_handler(*this,&threads_tester::thread_end_handler); tsd.data() = num; for (int i = 0; i < 0x3FFFF; ++i) { if ((i&0xFFF) == 0) { print_spinner(); dlib::sleep(10); } // if this isn't equal to num then there is a problem with the thread specific data stuff if (tsd.data() != num) { auto_mutex M(cm); failure = true; sm.signal(); } } dlog << LTRACE << "ending of thread num " << num; } } a; }
42f4ce6dbf83fd0c9ff0aa13ab3c9f155e5d9ec4
c056dfe8476cc7db4ee7af6ba908cba19f251e89
/RTRA1/src/scene/Scene00.cpp
07d59689bfececde15f20027e8f37bca397f4e81
[]
no_license
tomashaddad/RTRA1
9bbe11fbfb6b5b4134172a11fda9094bfa4f06b6
b57f91032a52e64469882c77e648249dc953dd89
refs/heads/master
2023-07-26T05:33:43.676088
2021-09-05T12:23:42
2021-09-05T12:23:42
397,475,859
0
0
null
null
null
null
UTF-8
C++
false
false
6,249
cpp
Scene00.cpp
#include "Scene00.h" #include <glad/glad.h> #include "RTRApp.h" #include "api/Shader.h" #include <iostream> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/string_cast.hpp> #include <glm/gtc/quaternion.hpp> #include <glm/gtx/quaternion.hpp> Scene00::Scene00() : m_VBO(0) , m_cubeVAO(0) , m_lightCubeVAO(0) , m_cubeShader("./src/shaders/scene00/cube.vert", "./src/shaders/scene00/cube_blinnphong.frag") , m_lightShader("./src/shaders/scene00/lighting.vert", "./src/shaders/scene00/lighting.frag") {} Scene00::~Scene00() { std::cout << "Scene00 destructor called!" << std::endl; } void Scene00::init() { // these vertices are from the book; their winding order is wrong float vertices[] = { -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f }; glGenVertexArrays(1, &m_cubeVAO); glGenBuffers(1, &m_VBO); // give us a buffer glBindBuffer(GL_ARRAY_BUFFER, m_VBO); // this is the buffer we will be using glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // please load the vertex data into buffer's memory // GL_STREAM_DRAW: Set once, used a few times // GL_STATIC_DRAW: Set once, used many times // GL_DYNAMIC_DRAW: Set a lot, used a lot // Any subsequent vertex attribute calls from this point on will be stored in this bound VAO // It stores: // Calls to glEnableVertexAttribArray or glDisableVertexAttribArray // Vertex attribute configurations via glVertexAttribPointer // VBO's associated with vertex attributes by calls to glVertexAttribPointer glBindVertexArray(m_cubeVAO); // now we need to specify what part of our input data goes to which vertex attribute in the vertex shader // i.e. we need to tell OpenGL how it should interpret the vertex data before rendering // each verte attribute takes its data from memory managed by a VBO,a nd which VBO it takes its data from is // determined by the VBO currently bound to GL_ARRAY_BUFFER when calling glVertexAttribPointer. // So the vertex attribute pointer calls below will associate vertex attributes 0 and 1 with the given layout. // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0); // vertex attributes are disabled by default and need to be manually enabled glEnableVertexAttribArray(0); // normal attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); // second, configure the light's VAO (VBO stays the same; the vertices are the same for the light object which is also a 3D cube) glGenVertexArrays(1, &m_lightCubeVAO); glBindVertexArray(m_lightCubeVAO); glBindBuffer(GL_ARRAY_BUFFER, m_VBO); // note that we update the lamp's position attribute's stride to reflect the updated buffer data glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); } void Scene00::render() { glm::mat4 model = glm::mat4(1.0f); glm::mat4 view = RTRApp::instance().getCamera()->getViewMatrix(); glm::mat4 projection = RTRApp::instance().getCamera()->getProjectionMatrix(); m_cubeShader.bind(); m_cubeShader.setMat4("model", model); m_cubeShader.setMat4("view", view); m_cubeShader.setMat4("projection", projection); m_cubeShader.setVec3f("viewPos", RTRApp::instance().getCamera()->getPosition()); m_cubeShader.setVec3f("material.ambient", glm::vec3(1.0f, 0.5f, 0.31f)); m_cubeShader.setVec3f("material.diffuse", glm::vec3(1.0f, 0.5f, 0.31f)); m_cubeShader.setVec3f("material.specular", glm::vec3(0.5f, 0.5f, 0.5f)); m_cubeShader.setFloat("material.shininess", 32.0f); glm::vec3 lightPos(0.5f, 1.0f, 1.5f); m_cubeShader.setVec3f("light.position", lightPos); m_cubeShader.setVec3f("light.ambient", glm::vec3(0.2f, 0.2f, 0.2f)); m_cubeShader.setVec3f("light.diffuse", glm::vec3(0.5f, 0.5f, 0.5f)); m_cubeShader.setVec3f("light.specular", glm::vec3(1.0f, 1.0f, 1.0f)); glBindVertexArray(m_cubeVAO); glDrawArrays(GL_TRIANGLES, 0, 36); m_lightShader.bind(); model = glm::translate(model, lightPos); model = glm::scale(model, glm::vec3(0.2f)); m_lightShader.setMat4("model", model); m_lightShader.setMat4("view", view); m_lightShader.setMat4("projection", projection); glBindVertexArray(m_lightCubeVAO); glDrawArrays(GL_TRIANGLES, 0, 36); }
cfcc279bf3551d12fa7f606090471f067b3f0ded
27edfcd70a4bb9c051b8bcbeed7cefc966cc60a8
/EMComponent/CommonEdge.cpp
c86fc1943f813db0632982897571ee5431d4227a
[]
no_license
xiangwei0909/EMFA
e3fca62bb7e1761613d2e237267a4bad555294b6
c31dcef457c9f6ae2c4fe162c77c24569b3c1853
refs/heads/master
2022-10-19T21:56:46.167618
2020-06-10T07:52:18
2020-06-10T07:52:18
271,191,251
0
0
null
null
null
null
GB18030
C++
false
false
24,868
cpp
CommonEdge.cpp
#include "CommonEdge.h" #include "ErrorHandle.h" #include "tools.h" #include "Mathdef.h" using namespace component; CommonEdge::CommonEdge() { } CommonEdge::~CommonEdge() { } void CommonEdge::getCommonEdge(int index, int & _vp, int & _vm, int & _fp, int & _fm, value_t & _len) const { auto& edge = m_ceList[index]; _vp = edge.vxp; _vm = edge.vxm; _fp = edge.tpid; _fm = edge.tmid; _len = edge.length; } void CommonEdge::getCommonEdge(int index, int & _vp, int & _vm, int & _fp, int & _fm, value_t & _len,int &_bedge) const { auto& edge = m_ceList[index]; _vp = edge.vxp; _vm = edge.vxm; _fp = edge.tpid; _fm = edge.tmid; _len = edge.length; _bedge = edge.bedge; } void CommonEdge::getCommonEdge(int index, int & _vp, int & _vm, int & _fp, int & _fm, value_t & _len, int &_sedid, int &_bedge) const { auto& edge = m_ceList[index]; _vp = edge.vxp; _vm = edge.vxm; _fp = edge.tpid; _fm = edge.tmid; _len = edge.length; _sedid = edge.sedid; _bedge = edge.bedge; } void CommonEdge::getCommonEdge(int index, int & _vp, int & _vm, int & _fp, int & _fm, value_t & _len, value_t &_ep,value_t &_em,int &_bedge) const { auto& edge = m_ceList[index]; _vp = edge.vxp; _vm = edge.vxm; _fp = edge.tpid; _fm = edge.tmid; _len = edge.length; _ep = edge.ep; _em = edge.em; _bedge = edge.bedge; } void CommonEdge::getCommonEdge(int index, int & _vp, int & _vm, int & _fp, int & _fm, value_t & _len, Qstring &_fla_p,Qstring &_fla_m) const { auto& edge = m_ceList[index]; _vp = edge.vxp; _vm = edge.vxm; _fp = edge.tpid; _fm = edge.tmid; _len = edge.length; _fla_p = edge.fla_p; _fla_m = edge.fla_m; } void CommonEdge::buildCommonEdge(std::shared_ptr<Mesh> mesh_ptr_) { auto triNum = mesh_ptr_->getTriangleNum(); int nAID, nBID, nCID; for (int i = 0; i < triNum; ++i) { auto& tri = mesh_ptr_->getTriangleRef(i); tri.getVertex(nAID, nBID, nCID); updateCommonEdge(nAID, nBID, nCID, i); } totalEdges = static_cast<int>(m_ceListTemp.size()); for (int i = 0; i < totalEdges; ++i) { if (!isCommonEdgeTemp(i)) { m_beList.push_back(std::move(m_ceListTemp[i])); continue; } m_ceList.push_back(std::move(m_ceListTemp[i])); } m_ceListTemp.clear(); m_ceListTemp.shrink_to_fit(); m_ceList.shrink_to_fit(); VectorR3 vertex1, vertex2; for (auto &ce : m_ceList) { vertex1 = mesh_ptr_->getVertex(ce.v1); vertex2 = mesh_ptr_->getVertex(ce.v2); ce.length = (vertex1 - vertex2).Norm(); } } void CommonEdge::buildContinuousEdges(std::shared_ptr<Mesh> mesh_ptr_) { buildCommonEdge(mesh_ptr_); boundaryEdges = m_beList.size(); VectorR3 minBox, maxBox; mesh_ptr_->getBoundary(minBox, maxBox); std::vector<SCE> maxEdges_x, maxEdges_y; std::vector<SCE> minEdges_x, minEdges_y; for (int i = 0; i < boundaryEdges; ++i) { VectorR3 v1 = mesh_ptr_->getVertex(m_beList[i].v1); VectorR3 v2 = mesh_ptr_->getVertex(m_beList[i].v2); if (abs(v1.x - v2.x) < 1e-4) { if (abs(v1.x - minBox.x) < 1e-4) minEdges_x.push_back(std::move(m_beList[i])); else if(abs(v1.x - maxBox.x) < 1e-4) maxEdges_x.push_back(std::move(m_beList[i])); } else if (abs(v1.y - v2.y) < 1e-4) { if (abs(v1.y - minBox.y) < 1e-4) minEdges_y.push_back(std::move(m_beList[i])); else if (abs(v1.y - maxBox.y) < 1e-4) maxEdges_y.push_back(std::move(m_beList[i])); } } if ((minEdges_x.size() == maxEdges_x.size())&&(minEdges_y.size() == maxEdges_y.size())) Qcout << "The boundary number is match..." << std::endl; else Qcout << "The boundary number isn't match...." << std::endl; int bnum1 = maxEdges_x.size(); int bnum2 = maxEdges_y.size(); auto triNum = mesh_ptr_->getTriangleNum(); for (int i = 0; i < bnum1; ++i) { VectorR3 vmax1 = mesh_ptr_->getVertex(maxEdges_x[i].v1); VectorR3 vmax2 = mesh_ptr_->getVertex(maxEdges_x[i].v2); for (int j = 0; j < bnum1; ++j) { VectorR3 vmin1 = mesh_ptr_->getVertex(minEdges_x[j].v1); VectorR3 vmin2 = mesh_ptr_->getVertex(minEdges_x[j].v2); if (abs(vmax1.y + vmax2.y - vmin1.y - vmin2.y) < 1e-4) { maxEdges_x[i].vxm = minEdges_x[j].vxp; maxEdges_x[i].tmid = minEdges_x[j].tpid; maxEdges_x[i].bedge = 1; maxEdges_x[i].length = (vmax1 - vmax2).Norm(); m_ceList.push_back(std::move(maxEdges_x[i])); } } } for (int i = 0; i < bnum2; ++i) { VectorR3 vmax1 = mesh_ptr_->getVertex(maxEdges_y[i].v1); VectorR3 vmax2 = mesh_ptr_->getVertex(maxEdges_y[i].v2); for (int j = 0; j < bnum2; ++j) { VectorR3 vmin1 = mesh_ptr_->getVertex(minEdges_y[j].v1); VectorR3 vmin2 = mesh_ptr_->getVertex(minEdges_y[j].v2); if (abs(vmax1.x + vmax2.x - vmin1.x - vmin2.x) < 1e-4) { maxEdges_y[i].vxm = minEdges_y[j].vxp; maxEdges_y[i].tmid = minEdges_y[j].tpid; maxEdges_y[i].bedge = 2; maxEdges_y[i].length = (vmax1 - vmax2).Norm(); m_ceList.push_back(std::move(maxEdges_y[i])); } } } minEdges_x.clear(); minEdges_y.clear(); maxEdges_x.clear(); maxEdges_y.clear(); m_ceList.shrink_to_fit(); std::stringstream tmpcelist; for (auto &ce : m_ceList) { tmpcelist << ce.v1 + 1 << '\t' << ce.v2 + 1 << '\t' << ce.vxp + 1 << '\t' << ce.vxm + 1 << '\t' << ce.tpid + 1 << '\t' << ce.tmid + 1 <<'\t'<<ce.bedge <<'\n'; } Qofstream tmpfile("temp_celist.dat", std::ios::out); tmpfile << tmpcelist.rdbuf(); tmpfile.flush(); Qcout << "It is already output the commonEdge!" << std::endl; } void CommonEdge::buildSEDCommonEdge_com(std::shared_ptr<Mesh> mesh_ptr_) { auto triNum = mesh_ptr_->getTriangleNum(); int nAID, nBID, nCID; for (int i = 0; i < triNum; ++i) { auto& tri = mesh_ptr_->getTriangleRef(i); tri.getVertex(nAID, nBID, nCID); updateCommonEdge(nAID, nBID, nCID, i); } totalEdges = static_cast<int>(m_ceListTemp.size()); for (int i = 0; i < totalEdges; ++i) { if (!isCommonEdgeTemp(i)) { m_beList.push_back(std::move(m_ceListTemp[i])); continue; } m_ceList_SED0.push_back(std::move(m_ceListTemp[i])); m_ceList_SED1.push_back(std::move(m_ceListTemp[i])); m_ceList_SED2.push_back(std::move(m_ceListTemp[i])); m_ceList_SED3.push_back(std::move(m_ceListTemp[i])); m_ceList_SED4.push_back(std::move(m_ceListTemp[i])); m_ceList_SED5.push_back(std::move(m_ceListTemp[i])); m_ceList_SED6.push_back(std::move(m_ceListTemp[i])); m_ceList_SED7.push_back(std::move(m_ceListTemp[i])); m_ceList_SED8.push_back(std::move(m_ceListTemp[i])); } common_ce = m_ceList_SED0.size(); m_ceListTemp.clear(); m_ceListTemp.shrink_to_fit(); //m_ceList.shrink_to_fit(); VectorR3 vertex1, vertex2; for (auto &ce : m_ceList) { vertex1 = mesh_ptr_->getVertex(ce.v1); vertex2 = mesh_ptr_->getVertex(ce.v2); ce.length = (vertex1 - vertex2).Norm(); } } void CommonEdge::buildSEDCommonEdge_boundary(std::shared_ptr<Mesh> mesh_ptr_,value_t _Dx,value_t _Dy) { //buildSEDCommonEdge_com(mesh_ptr_); boundaryEdges = m_beList.size(); VectorR3 minBox, maxBox; mesh_ptr_->getBoundary(minBox, maxBox); value_t dis_x, dis_y, dis_z; mesh_ptr_->getSize(dis_x, dis_y, dis_z); //maxBox.x = minBox.x + _Dx; //maxBox.y = minBox.y + _Dy; std::vector<SCE> maxEdges_x, maxEdges_y; std::vector<SCE> minEdges_x, minEdges_y; for (int i = 0; i < boundaryEdges; ++i) { VectorR3 v1 = mesh_ptr_->getVertex(m_beList[i].v1); VectorR3 v2 = mesh_ptr_->getVertex(m_beList[i].v2); if ((abs(v1.x - v2.x) < 1e-4) && (abs(_Dx - dis_x)<1e-4)) { if ((abs(v1.x - minBox.x) < 1e-4)&&(abs(_Dx-dis_x)<1e-4)) minEdges_x.push_back(std::move(m_beList[i])); else if ((abs(v1.x - maxBox.x) < 1e-4)&& (abs(_Dx - dis_x)<1e-4)) maxEdges_x.push_back(std::move(m_beList[i])); } else if ((abs(v1.y - v2.y) < 1e-4) && (abs(_Dy - dis_y)<1e-4)) { if ((abs(v1.y - minBox.y) < 1e-4)&& (abs(_Dy - dis_y)<1e-4)) minEdges_y.push_back(std::move(m_beList[i])); else if ((abs(v1.y - maxBox.y) < 1e-4)&& (abs(_Dy - dis_y)<1e-4)) maxEdges_y.push_back(std::move(m_beList[i])); } } if ((minEdges_x.size() == maxEdges_x.size()) && (minEdges_y.size() == maxEdges_y.size())) Qcout << "The boundary number is match..." << std::endl; else Qcout << "The boundary number isn't match...." << std::endl; int bnum1 = maxEdges_x.size(); int bnum2 = maxEdges_y.size(); b_ce1 = bnum1; b_ce2 = bnum2; auto triNum = mesh_ptr_->getTriangleNum(); for (int i = 0; i < bnum1; ++i) { VectorR3 vmax1 = mesh_ptr_->getVertex(maxEdges_x[i].v1); VectorR3 vmax2 = mesh_ptr_->getVertex(maxEdges_x[i].v2); for (int j = 0; j < bnum1; ++j) { VectorR3 vmin1 = mesh_ptr_->getVertex(minEdges_x[j].v1); VectorR3 vmin2 = mesh_ptr_->getVertex(minEdges_x[j].v2); if ((abs(vmax1.y + vmax2.y - vmin1.y - vmin2.y) < 1e-3) &&(abs(vmax1.z + vmax2.z - vmin1.z - vmin2.z)<1e-3)) { maxEdges_x[i].vxm = minEdges_x[j].vxp; maxEdges_x[i].tmid = minEdges_x[j].tpid; maxEdges_x[i].bedge = 1; maxEdges_x[i].length = (vmax1 - vmax2).Norm(); m_ceList_SED0.push_back(std::move(maxEdges_x[i])); m_ceList_SED1.push_back(std::move(maxEdges_x[i])); m_ceList_SED2.push_back(std::move(maxEdges_x[i])); m_ceList_SED3.push_back(std::move(maxEdges_x[i])); m_ceList_SED4.push_back(std::move(maxEdges_x[i])); m_ceList_SED5.push_back(std::move(maxEdges_x[i])); } } } for (int i = 0; i < bnum2; ++i) { VectorR3 vmax1 = mesh_ptr_->getVertex(maxEdges_y[i].v1); VectorR3 vmax2 = mesh_ptr_->getVertex(maxEdges_y[i].v2); for (int j = 0; j < bnum2; ++j) { VectorR3 vmin1 = mesh_ptr_->getVertex(minEdges_y[j].v1); VectorR3 vmin2 = mesh_ptr_->getVertex(minEdges_y[j].v2); if ((abs(vmax1.x + vmax2.x - vmin1.x - vmin2.x) < 1e-3) && (abs(vmax1.z + vmax2.z - vmin1.z - vmin2.z)<1e-3)) { maxEdges_y[i].vxm = minEdges_y[j].vxp; maxEdges_y[i].tmid = minEdges_y[j].tpid; maxEdges_y[i].bedge = 2; maxEdges_y[i].length = (vmax1 - vmax2).Norm(); m_ceList_SED0.push_back(std::move(maxEdges_y[i])); m_ceList_SED1.push_back(std::move(maxEdges_y[i])); m_ceList_SED3.push_back(std::move(maxEdges_y[i])); m_ceList_SED4.push_back(std::move(maxEdges_y[i])); m_ceList_SED6.push_back(std::move(maxEdges_y[i])); m_ceList_SED7.push_back(std::move(maxEdges_y[i])); } } } minEdges_x.clear(); minEdges_y.clear(); maxEdges_x.clear(); maxEdges_y.clear(); //m_ceList.shrink_to_fit(); } void CommonEdge::buildSEDCommonEdge_boundary(std::shared_ptr<Mesh> mesh_ptr_, value_t _Dx, value_t _Dy,value_t _lamda) { //buildSEDCommonEdge_com(mesh_ptr_); boundaryEdges = m_beList.size(); VectorR3 minBox, maxBox; mesh_ptr_->getBoundary(minBox, maxBox); value_t dis_x, dis_y, dis_z; mesh_ptr_->getSize(dis_x, dis_y, dis_z); //maxBox.x = minBox.x + _Dx; //maxBox.y = minBox.y + _Dy; std::vector<SCE> maxEdges_x, maxEdges_y; std::vector<SCE> minEdges_x, minEdges_y; for (int i = 0; i < boundaryEdges; ++i) { VectorR3 v1 = mesh_ptr_->getVertex(m_beList[i].v1); VectorR3 v2 = mesh_ptr_->getVertex(m_beList[i].v2); if ((abs(v1.x - v2.x) < 1e-4*_lamda) && (abs(_Dx - dis_x)<1e-4*_lamda)) { if ((abs(v1.x - minBox.x) < 1e-4*_lamda) && (abs(_Dx - dis_x)<1e-4*_lamda)) minEdges_x.push_back(std::move(m_beList[i])); else if ((abs(v1.x - maxBox.x) < 1e-4*_lamda) && (abs(_Dx - dis_x)<1e-4*_lamda)) maxEdges_x.push_back(std::move(m_beList[i])); } else if ((abs(v1.y - v2.y) < 1e-4*_lamda) && (abs(_Dy - dis_y)<1e-4*_lamda)) { if ((abs(v1.y - minBox.y) < 1e-4*_lamda) && (abs(_Dy - dis_y)<1e-4*_lamda)) minEdges_y.push_back(std::move(m_beList[i])); else if ((abs(v1.y - maxBox.y) < 1e-4*_lamda) && (abs(_Dy - dis_y)<1e-4*_lamda)) maxEdges_y.push_back(std::move(m_beList[i])); } } if ((minEdges_x.size() == maxEdges_x.size()) && (minEdges_y.size() == maxEdges_y.size())) Qcout << "The boundary number is match..." << std::endl; else Qcout << "The boundary number isn't match...." << std::endl; int bnum1 = maxEdges_x.size(); int bnum2 = maxEdges_y.size(); b_ce1 = bnum1; b_ce2 = bnum2; auto triNum = mesh_ptr_->getTriangleNum(); for (int i = 0; i < bnum1; ++i) { VectorR3 vmax1 = mesh_ptr_->getVertex(maxEdges_x[i].v1); VectorR3 vmax2 = mesh_ptr_->getVertex(maxEdges_x[i].v2); for (int j = 0; j < bnum1; ++j) { VectorR3 vmin1 = mesh_ptr_->getVertex(minEdges_x[j].v1); VectorR3 vmin2 = mesh_ptr_->getVertex(minEdges_x[j].v2); if ((abs(vmax1.y + vmax2.y - vmin1.y - vmin2.y) < 1e-4*_lamda) && (abs(vmax1.z + vmax2.z - vmin1.z - vmin2.z)<1e-4*_lamda)) { maxEdges_x[i].vxm = minEdges_x[j].vxp; maxEdges_x[i].tmid = minEdges_x[j].tpid; maxEdges_x[i].bedge = 1; maxEdges_x[i].length = (vmax1 - vmax2).Norm(); m_ceList_SED0.push_back(std::move(maxEdges_x[i])); m_ceList_SED1.push_back(std::move(maxEdges_x[i])); m_ceList_SED2.push_back(std::move(maxEdges_x[i])); m_ceList_SED3.push_back(std::move(maxEdges_x[i])); m_ceList_SED4.push_back(std::move(maxEdges_x[i])); m_ceList_SED5.push_back(std::move(maxEdges_x[i])); } } } for (int i = 0; i < bnum2; ++i) { VectorR3 vmax1 = mesh_ptr_->getVertex(maxEdges_y[i].v1); VectorR3 vmax2 = mesh_ptr_->getVertex(maxEdges_y[i].v2); for (int j = 0; j < bnum2; ++j) { VectorR3 vmin1 = mesh_ptr_->getVertex(minEdges_y[j].v1); VectorR3 vmin2 = mesh_ptr_->getVertex(minEdges_y[j].v2); if ((abs(vmax1.x + vmax2.x - vmin1.x - vmin2.x) < 1e-4*_lamda) && (abs(vmax1.z + vmax2.z - vmin1.z - vmin2.z)<1e-4*_lamda)) { maxEdges_y[i].vxm = minEdges_y[j].vxp; maxEdges_y[i].tmid = minEdges_y[j].tpid; maxEdges_y[i].bedge = 2; maxEdges_y[i].length = (vmax1 - vmax2).Norm(); m_ceList_SED0.push_back(std::move(maxEdges_y[i])); m_ceList_SED1.push_back(std::move(maxEdges_y[i])); m_ceList_SED3.push_back(std::move(maxEdges_y[i])); m_ceList_SED4.push_back(std::move(maxEdges_y[i])); m_ceList_SED6.push_back(std::move(maxEdges_y[i])); m_ceList_SED7.push_back(std::move(maxEdges_y[i])); } } } minEdges_x.clear(); minEdges_y.clear(); maxEdges_x.clear(); maxEdges_y.clear(); //m_ceList.shrink_to_fit(); } /*void CommonEdge::buildSPINCommonEdge_boundary(std::shared_ptr<Mesh> mesh_ptr_,value_t _angle) { //buildSEDCommonEdge_com(mesh_ptr_); boundaryEdges = m_beList.size(); //VectorR3 minBox, maxBox; //mesh_ptr_->getBoundary(minBox, maxBox); //value_t dis_x, dis_y, dis_z; //mesh_ptr_->getSize(dis_x, dis_y, dis_z); //maxBox.x = minBox.x + _Dx; //maxBox.y = minBox.y + _Dy; std::vector<SCE> maxEdges; std::vector<SCE> minEdges; value_t theta = _angle * DegreesToRadians; for (int i = 0; i < boundaryEdges; ++i) { VectorR3 v1 = mesh_ptr_->getVertex(m_beList[i].v1); VectorR3 v2 = mesh_ptr_->getVertex(m_beList[i].v2); if (abs((v1.y*v2.x) - (v2.y*v1.x)) < 1e-4) { if (abs(v1.y -(v1.x*tan(theta))) < 1e-4) maxEdges.push_back(std::move(m_beList[i])); else if ((abs(v1.x - maxBox.x) < 1e-4) && (abs(_Dx - dis_x)<1e-4)) maxEdges_x.push_back(std::move(m_beList[i])); } else if (abs(v1.y - v2.y) < 1e-4) { if ((abs(v1.y - minBox.y) < 1e-4) && (abs(_Dy - dis_y)<1e-4)) minEdges_y.push_back(std::move(m_beList[i])); else if ((abs(v1.y - maxBox.y) < 1e-4) && (abs(_Dy - dis_y)<1e-4)) maxEdges_y.push_back(std::move(m_beList[i])); } } if ((minEdges_x.size() == maxEdges_x.size()) && (minEdges_y.size() == maxEdges_y.size())) Qcout << "The boundary number is match..." << std::endl; else Qcout << "The boundary number isn't match...." << std::endl; int bnum1 = maxEdges_x.size(); int bnum2 = maxEdges_y.size(); auto triNum = mesh_ptr_->getTriangleNum(); for (int i = 0; i < bnum1; ++i) { VectorR3 vmax1 = mesh_ptr_->getVertex(maxEdges_x[i].v1); VectorR3 vmax2 = mesh_ptr_->getVertex(maxEdges_x[i].v2); for (int j = 0; j < bnum1; ++j) { VectorR3 vmin1 = mesh_ptr_->getVertex(minEdges_x[j].v1); VectorR3 vmin2 = mesh_ptr_->getVertex(minEdges_x[j].v2); if ((abs(vmax1.y + vmax2.y - vmin1.y - vmin2.y) < 1e-4) && (abs(vmax1.z + vmax2.z - vmin1.z - vmin2.z)<1e-4)) { maxEdges_x[i].vxm = minEdges_x[j].vxp; maxEdges_x[i].tmid = minEdges_x[j].tpid; maxEdges_x[i].bedge = 1; maxEdges_x[i].length = (vmax1 - vmax2).Norm(); m_ceList_SED0.push_back(std::move(maxEdges_x[i])); m_ceList_SED1.push_back(std::move(maxEdges_x[i])); m_ceList_SED2.push_back(std::move(maxEdges_x[i])); m_ceList_SED3.push_back(std::move(maxEdges_x[i])); m_ceList_SED4.push_back(std::move(maxEdges_x[i])); m_ceList_SED5.push_back(std::move(maxEdges_x[i])); } } } for (int i = 0; i < bnum2; ++i) { VectorR3 vmax1 = mesh_ptr_->getVertex(maxEdges_y[i].v1); VectorR3 vmax2 = mesh_ptr_->getVertex(maxEdges_y[i].v2); for (int j = 0; j < bnum2; ++j) { VectorR3 vmin1 = mesh_ptr_->getVertex(minEdges_y[j].v1); VectorR3 vmin2 = mesh_ptr_->getVertex(minEdges_y[j].v2); if ((abs(vmax1.x + vmax2.x - vmin1.x - vmin2.x) < 1e-4) && (abs(vmax1.z + vmax2.z - vmin1.z - vmin2.z)<1e-4)) { maxEdges_y[i].vxm = minEdges_y[j].vxp; maxEdges_y[i].tmid = minEdges_y[j].tpid; maxEdges_y[i].bedge = 2; maxEdges_y[i].length = (vmax1 - vmax2).Norm(); m_ceList_SED0.push_back(std::move(maxEdges_y[i])); m_ceList_SED1.push_back(std::move(maxEdges_y[i])); m_ceList_SED3.push_back(std::move(maxEdges_y[i])); m_ceList_SED4.push_back(std::move(maxEdges_y[i])); m_ceList_SED6.push_back(std::move(maxEdges_y[i])); m_ceList_SED7.push_back(std::move(maxEdges_y[i])); } } } minEdges_x.clear(); minEdges_y.clear(); maxEdges_x.clear(); maxEdges_y.clear(); //m_ceList.shrink_to_fit(); }*/ void CommonEdge::buildIBCCommonEdge(std::shared_ptr<Mesh> mesh_ptr_) { auto triNum = mesh_ptr_->getTriangleNum(); int nAID, nBID, nCID; //value_t eps; Qstring fla; for (int i = 0; i < triNum; ++i) { auto& tri = mesh_ptr_->getTriangleRef(i); tri.getVertex(nAID, nBID, nCID); tri.getFla(fla); updateIBCCommonEdge(nAID, nBID, nCID, i, fla); //d_ptList.push_back(SCE(nAID, nBID, nCID, i, fla)); //将冲击基函数的三角形保存 } totalEdges = static_cast<int>(m_ceListTemp.size()); for (int i = 0; i < totalEdges; ++i) { /*if (!isCommonEdgeTemp(i)) { m_beList.push_back(std::move(m_ceListTemp[i])); continue; }*/ m_ceList.push_back(std::move(m_ceListTemp[i])); } m_ceListTemp.clear(); m_ceListTemp.shrink_to_fit(); m_ceList.shrink_to_fit(); VectorR3 vertex1, vertex2; for (auto &ce : m_ceList) { vertex1 = mesh_ptr_->getVertex(ce.v1); vertex2 = mesh_ptr_->getVertex(ce.v2); ce.length = (vertex1 - vertex2).Norm(); } } void CommonEdge::combineSEDCommonEdge(std::shared_ptr<Mesh> mesh_ptr_) { int unk_SED; m_ce_size[0] = 0; unk_SED = m_ceList_SED0.size(); for (int i = 0; i < unk_SED; i++) { m_ceList_SED0[i].sedid = 0; m_ceList.push_back(std::move(m_ceList_SED0[i])); } m_ce_size[1] = m_ceList.size(); unk_SED = m_ceList_SED1.size(); for (int i = 0; i < unk_SED; i++) { m_ceList_SED1[i].sedid = 1; m_ceList.push_back(std::move(m_ceList_SED1[i])); } m_ce_size[2] = m_ceList.size(); unk_SED = m_ceList_SED2.size(); for (int i = 0; i < unk_SED; i++) { m_ceList_SED2[i].sedid = 2; m_ceList.push_back(std::move(m_ceList_SED2[i])); } m_ce_size[3] = m_ceList.size(); unk_SED = m_ceList_SED3.size(); for (int i = 0; i < unk_SED; i++) { m_ceList_SED3[i].sedid = 3; m_ceList.push_back(std::move(m_ceList_SED3[i])); } m_ce_size[4] = m_ceList.size(); unk_SED = m_ceList_SED4.size(); for (int i = 0; i < unk_SED; i++) { m_ceList_SED4[i].sedid = 4; m_ceList.push_back(std::move(m_ceList_SED4[i])); } m_ce_size[5] = m_ceList.size(); unk_SED = m_ceList_SED5.size(); for (int i = 0; i < unk_SED; i++) { m_ceList_SED5[i].sedid = 5; m_ceList.push_back(std::move(m_ceList_SED5[i])); } m_ce_size[6] = m_ceList.size(); unk_SED = m_ceList_SED6.size(); for (int i = 0; i < unk_SED; i++) { m_ceList_SED6[i].sedid = 6; m_ceList.push_back(std::move(m_ceList_SED6[i])); } m_ce_size[7] = m_ceList.size(); unk_SED = m_ceList_SED7.size(); for (int i = 0; i < unk_SED; i++) { m_ceList_SED7[i].sedid = 7; m_ceList.push_back(std::move(m_ceList_SED7[i])); } m_ce_size[8] = m_ceList.size(); unk_SED = m_ceList_SED8.size(); for (int i = 0; i < unk_SED; i++) { m_ceList_SED8[i].sedid = 8; m_ceList.push_back(std::move(m_ceList_SED8[i])); } m_ce_size[9] = m_ceList.size(); VectorR3 vertex1, vertex2; for (auto &ce : m_ceList) { vertex1 = mesh_ptr_->getVertex(ce.v1); vertex2 = mesh_ptr_->getVertex(ce.v2); ce.length = (vertex1 - vertex2).Norm(); } std::stringstream tmpcelist; for (auto &ce : m_ceList) { tmpcelist << ce.v1 + 1 << '\t' << ce.v2 + 1 << '\t' << ce.vxp + 1 << '\t' << ce.vxm + 1 << '\t' << ce.tpid + 1 << '\t' << ce.tmid + 1 << '\t' << ce.bedge << '\t' << ce.sedid << '\t' << ce.length << '\n'; } Qofstream tmpfile("temp_celist.dat", std::ios::out); tmpfile << tmpcelist.rdbuf(); tmpfile.flush(); Qcout << "It is already output the commonEdge!" << std::endl; } bool CommonEdge::writeLengthData(const std::string & filename, value_t lamda) const { Qofstream output(filename, std::ios::out); if (output.fail()) throw FileError("fail opening file: " + filename); auto edgesNum = m_ceList.size(); output << std::fixed << std::setprecision(4); output << "length data: " << output.widen('\n'); for (size_t i = 0; i < edgesNum; ++i) { output << std::setw(10) << i + 1 << std::setw(15) << m_ceList[i].length/lamda << output.widen('\n'); } return true; } void CommonEdge::reportInfo(Qostream & strm) const { size_t mem = m_ceList.size() * m_ceList.size() * 2 * sizeof(value_t) / (1024 * 1024); size_t cemem = sizeof(SCE) * m_ceList.size() / (1024 * 1024); auto oldState = strm.flags(); strm << HEADING "CommonEdge Information\n" TRAILING; strm << LEVEL1 "Total edges: " << totalEdges << strm.widen('\n') << LEVEL1 "Total RWGs: " << m_ceList.size() << strm.widen('\n') << LEVEL1 "Memory prediction: " << mem << " MB" << FORMAT_MEMORY(mem) << '\n' << LEVEL1 "Memory detail:" << '\n' << LEVEL2 "RWG:" << cemem << " MB" << FORMAT_MEMORY(cemem) << '\n'; strm.flush(); strm.flags(oldState); } void CommonEdge::updateCommonEdge(int nA, int nB, int nC, int faceID) { bool newEdge1 = true, newEdge2 = true, newEdge3 = true; int v1ID, v2ID; int edgeNum = static_cast<int>(m_ceListTemp.size()); for (int i = 0; i < edgeNum; ++i) { if (isCommonEdgeTemp(i)) continue; getEdgeTempAt(i, v1ID, v2ID); if (nA == v2ID&&nB == v1ID) { newEdge1 = false; setEdgeTempAt(i, nC, faceID); } else if (nB == v2ID&&nC == v1ID) { newEdge2 = false; setEdgeTempAt(i, nA, faceID); } else if (nC == v2ID&&nA == v1ID) { newEdge3 = false; setEdgeTempAt(i, nB, faceID); } } if (newEdge1) { m_ceListTemp.push_back(SCE(nA, nB, nC, faceID)); } if (newEdge2) { m_ceListTemp.push_back(SCE(nB, nC, nA, faceID)); } if (newEdge3) { m_ceListTemp.push_back(SCE(nC, nA, nB, faceID)); } } void CommonEdge::updateIBCCommonEdge(int nA, int nB, int nC, int faceID, Qstring fla) { bool newEdge1 = true, newEdge2 = true, newEdge3 = true; int v1ID, v2ID; //value_t eps_temp; Qstring fla_temp; int edgeNum = static_cast<int>(m_ceListTemp.size()); for (int i = 0; i < edgeNum; ++i) { if (isCommonEdgeTemp(i)) continue; getEdgeTempAt(i, v1ID, v2ID); if (nA == v2ID && nB == v1ID) { newEdge1 = false; setEdgeTempAt(i, nC, faceID, fla); } else if (nB == v2ID && nC == v1ID) { newEdge2 = false; setEdgeTempAt(i, nA, faceID,fla); } else if (nC == v2ID && nA == v1ID) { newEdge3 = false; setEdgeTempAt(i, nB, faceID, fla); } } if (newEdge1) { m_ceListTemp.push_back(SCE(nA, nB, nC, faceID, fla_temp)); } if (newEdge2) { m_ceListTemp.push_back(SCE(nB, nC, nA, faceID, fla_temp)); } if (newEdge3) { m_ceListTemp.push_back(SCE(nC, nA, nB, faceID, fla_temp)); } } void CommonEdge::setEdgeTempAt(int index, int _vm, int _fp) { m_ceListTemp[index].vxm = _vm; m_ceListTemp[index].tmid = _fp; } void CommonEdge::setEdgeTempAt(int index, int _vm, int _fp, Qstring _fla) { m_ceListTemp[index].vxm = _vm; m_ceListTemp[index].tmid = _fp; m_ceListTemp[index].fla_m = _fla; m_ceListTemp[index].bedge = 1; } void CommonEdge::getEdgeTempAt(int index, int & _v1, int & _v2) const { _v1 = m_ceListTemp[index].v1; _v2 = m_ceListTemp[index].v2; } void CommonEdge::getEdgeTempAt(int index, int & _v1, int & _v2,Qstring& _fla) const { //_v1 = m_ceListTemp[index].v1; //_v2 = m_ceListTemp[index].v2; //_fla = m_ceListTemp[index].fla; }
904c3ea49cee7b0e30404a8c40c5f76b792dd38f
bb60bd764b23d780c5796a76f91439e182849ad5
/include/patterns.h
06023bc7475a0e57869049736c607300d0092d05
[]
no_license
SPbun/cobi
b83ce25603dfec3c09a000e191ce130246db3dd7
e9bc4a5675ead1874ad9ffa953de8edb3a763479
refs/heads/master
2020-04-11T10:39:56.986607
2014-06-10T04:27:21
2014-06-10T04:27:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,265
h
patterns.h
/***************************************************************************** ** Cobi http://www.scalasca.org/ ** ***************************************************************************** ** Copyright (c) 2009-2010 ** ** Forschungszentrum Juelich, Juelich Supercomputing Centre ** ** ** ** See the file COPYRIGHT in the base directory for details ** *****************************************************************************/ /** * @file patterns.h * @author Jan Mussler * @brief All pattern related class defintions */ #ifndef _PATTERNS_H #define _PATTERNS_H #include <map> #include <vector> #include "ruletree.h" namespace gi { namespace filter { /** * Match String Strategy Interface */ class IMatchString { friend class MatchStrategyFactory; protected: IMatchString(); virtual ~IMatchString() {}; public: /** * @return true if test matches pattern */ virtual bool match(std::string pattern, std::string test) const = 0; /** * @return true if provided pattern is valid ( relevant for regular expression patterns ) */ virtual bool validPattern(std::string pattern) { return true; }; }; /** * Base class for pattern filters using functionname, modulname, ... */ class IPattern : public IRule { protected: /** * strategy used in matching to strings * either char by char, simple pattern or regular expression */ const IMatchString * const matchStrategy; protected: virtual ~IPattern() {}; /** * @param strategy matching strategy */ IPattern(IMatchString* strategy); }; /** * base class for all filters using a list of patterns to match with function * stores patterns and provides implementation for matching * input function against stored patterns */ class IPatterns : public IPattern { protected: std::vector<std::string> patterns; /** * template method to be overriden * returns the requested name of the function e.g. class or function name * * @param f input function * @return requested name */ virtual std::string getName(gi::mutatee::IFunction* f) = 0; /** * @param strategy matching strategy */ IPatterns(IMatchString* strategy); public: virtual ~IPatterns() {}; /** * Add pattern to list of patterns * @param aPattern pattern to add */ void addPattern(std::string aPattern); /** * Try to match name with any of the stored patterns * using template function getName() * * @param f function to inspect * @return wether function matched any of the patterns */ virtual bool match(gi::mutatee::IFunction* f); }; /** * Functionnames rule * contains a list of patterns and returns true if function matches any pattern */ class Names : public IPatterns { protected: virtual std::string getName(gi::mutatee::IFunction* f); public: virtual ~Names() {}; /** * @param strategy strategy used for matching function names and pattern */ Names(IMatchString* strategy); }; /** * Functionnames rule * contains a list of patterns and returns true if function matches any pattern */ class FunctionNames : public IPatterns { protected: virtual std::string getName(gi::mutatee::IFunction* f); public: virtual ~FunctionNames() {}; /** * @param strategy strategy used for matching function names and pattern */ FunctionNames(IMatchString* strategy); }; /** * Functionnames rule * contains a list of patterns and returns true if function matches any pattern */ class ClassNames : public IPatterns { protected: virtual std::string getName(gi::mutatee::IFunction* f); public: virtual ~ClassNames() {}; /** * @param strategy strategy used for matching function names and pattern */ ClassNames(IMatchString* strategy); }; /** * Functionnames rule * contains a list of patterns and returns true if function matches any pattern */ class Namespaces : public IPatterns { protected: virtual std::string getName(gi::mutatee::IFunction* f); public: virtual ~Namespaces() {}; /** * @param strategy strategy used for matching function names and pattern */ Namespaces(IMatchString* strategy); }; /** * Modulenames rule * contains a list of patterns and returns true if function's modulename matches any pattern */ class ModuleNames : public IPatterns { protected: virtual std::string getName(gi::mutatee::IFunction* f); public: virtual ~ModuleNames() {}; /** * @param strategy strategy used for matching function names and pattern */ ModuleNames(IMatchString* strategy); }; /** * Pattern matching against function name */ class FunctionName : public IPattern { private: std::string name; public: virtual ~FunctionName() {}; FunctionName(IMatchString* strategy, std::string aName); virtual bool match(gi::mutatee::IFunction* f); }; /** * Pattern matching against modul name */ class ModuleName : public IPattern { private: std::string name; public: virtual ~ModuleName() {}; ModuleName(IMatchString* strategy, std::string aName); virtual bool match(gi::mutatee::IFunction* f); }; /** * Strategy for matching strings characater for character "==" */ class MatchEquals : public IMatchString { protected: virtual ~MatchEquals() {}; public: /** * @return true if both strings are equal */ virtual bool match(std::string pattern, std::string test) const; }; /** * Strategy for matching using * at the end */ class MatchSimplePattern : public IMatchString { protected: virtual ~MatchSimplePattern() {}; public: /** * @return true if test matches the pattern */ virtual bool match(std::string pattern, std::string test) const; }; /** * Strategy for matching using regular expressions */ class MatchRegex : public IMatchString { protected: virtual ~MatchRegex() {}; public: /** * @return true if test matches the regular expression pattern */ virtual bool match(std::string pattern, std::string test) const; virtual bool validPattern(std::string pattern) const; }; class MatchPrefix : public IMatchString { protected: virtual ~MatchPrefix() {}; public: virtual bool match(std::string pattern, std::string test) const; }; class MatchSuffix : public IMatchString { protected: virtual ~MatchSuffix() {}; public: virtual bool match(std::string pattern, std::string test) const; }; class MatchFind : public IMatchString { protected: virtual ~MatchFind() {}; public: virtual bool match(std::string pattern, std::string test) const; }; /** * Factory for all Match Strategies used in patterns */ class MatchStrategyFactory { public: enum strategies { EQUALS, SIMPLE, REGEX, PREFIX, SUFFIX, FIND }; private: /** * static map, will be initialised by first use */ static std::map<strategies, IMatchString*> strategymap; public: /** * @return pointer to specified strategy */ static IMatchString * const getStrategy(strategies s); }; } } #endif /* _PATTERNS_H */
75d796415ef0eb6324e893ff46356fc54cb9568e
115c6d0b28478f068cc666d1be0f7aa0b645fc41
/e05_04/src/e05_04.cpp
d2c300e019fdbf253c7df1390793a632fe602581
[]
no_license
ddtBeppu/meikaicpp_beppu
586e758911472323a8f0b4fa6f5eba5d568ff1b9
c0aa321ca8a7886789181e4265901c0d47c17183
refs/heads/master
2021-04-28T20:09:23.297808
2018-05-02T02:35:41
2018-05-02T02:35:41
121,744,700
0
0
null
null
null
null
UTF-8
C++
false
false
1,436
cpp
e05_04.cpp
//============================================================================ // Name : e05_04.cpp // Author : Naoto Beppu // Version : // Copyright : Your copyright notice // Description : 演習5-4 // 連続する要素が同じ値とならないように、演習5-3のプログラムを改変したプログラムを作成せよ。 // 例えば、{1,3,5,5,3,2}とならないようにすること。 //============================================================================ #include <iostream> using namespace std; int main() { const int sizeArray = 6; // 配列の要素数を定義 int iArray[sizeArray] = {}; // 要素数がsizeArrayの配列 int iRand = 0; // 乱数を格納する変数 // 乱数の種を生成 srand(time(NULL)); // 配列の要素数だけ繰り返し for (int i = 0; i < sizeArray; i++) { do { // 以下を実行 // 1 ~ 10の乱数を生成 iRand = rand() % 10 + 1; //cout << iRand << endl; } while (i != 0 && iRand == iArray[i-1]); // 最初を除き、生成した乱数が一回前に配列に代入した値と等しい場合、繰り返し // 生成した値を要素として代入 iArray[i] = iRand; } // 配列の要素数だけ繰り返し for (int i = 0; i < sizeArray; i++) { // 配列の要素を出力 cout << "iArray[" << i << "]" << " = " << iArray[i] << endl; } // 整数値を返す return 0; }
5d7132baf944850753c0cc46bace6dc7f4b0acca
2d0bada349646b801a69c542407279cc7bc25013
/examples/waa/plugins/include/pl/features/xf_fast.hpp
e0d1683651bad72c53ae48bfd7e5768e6c543fc1
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSD-3-Clause-Open-MPI", "LicenseRef-scancode-free-unknown", "Libtool-exception", "GCC-exception-3.1", "LicenseRef-scancode-mit-old-style", "OFL-1.1", "JSON", "LGPL-2.1-only", "LGPL-2.0-or-later", "ICU", "LicenseRef-scancode-other-permissive", "GPL-2.0-or-later", "GPL-3.0-only", "LicenseRef-scancode-issl-2018", "MIT", "LGPL-2.1-or-later", "LicenseRef-scancode-unicode", "LGPL-3.0-only", "LicenseRef-scancode-warranty-disclaimer", "GPL-3.0-or-later", "Zlib", "BSD-Source-Code", "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "ISC", "NCSA", "LicenseRef-scancode-proprietary-license", "GPL-2.0-only", "CC-BY-4.0", "FSFULLR", "Minpack", "Unlicense", "BSL-1.0", "NAIST-2003", "Apache-2.0", "LicenseRef-scancode-protobuf", "LicenseRef-scancode-public-domain", "Libpng", "Spencer-94", "BSD-2-Clause", "Intel", "GPL-1.0-or-later", "MPL-2.0" ]
permissive
Xilinx/Vitis-AI
31e664f7adff0958bb7d149883ab9c231efb3541
f74ddc6ed086ba949b791626638717e21505dba2
refs/heads/master
2023-08-31T02:44:51.029166
2023-07-27T06:50:28
2023-07-27T06:50:28
215,649,623
1,283
683
Apache-2.0
2023-08-17T09:24:55
2019-10-16T21:41:54
Python
UTF-8
C++
false
false
38,216
hpp
xf_fast.hpp
/* * Copyright 2019 Xilinx, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _XF_FAST_HPP_ #define _XF_FAST_HPP_ #include "hls_stream.h" #include "common/xf_common.hpp" #include "common/xf_utility.hpp" #define __MIN(a, b) ((a < b) ? a : b) #define __MAX(a, b) ((a > b) ? a : b) #define PSize 16 #define NUM 25 namespace xf { namespace cv { // coreScore computes the score for corner pixels // For a given pixel identified as corner in process_function, the theshold is // increaded by a small value in each iteration till the pixel becomes // a non-corner. That value of threshold becomes the score for that corner pixel. static void xFCoreScore(short int* flag_d, int _threshold, uchar_t* core) { // clang-format off #pragma HLS INLINE // clang-format on short int flag_d_min2[NUM - 1]; short int flag_d_max2[NUM - 1]; short int flag_d_min4[NUM - 3]; short int flag_d_max4[NUM - 3]; short int flag_d_min8[NUM - 7]; short int flag_d_max8[NUM - 7]; for (ap_uint<5> i = 0; i < NUM - 1; i++) { flag_d_min2[i] = __MIN(flag_d[i], flag_d[i + 1]); flag_d_max2[i] = __MAX(flag_d[i], flag_d[i + 1]); } for (ap_uint<5> i = 0; i < NUM - 3; i++) { flag_d_min4[i] = __MIN(flag_d_min2[i], flag_d_min2[i + 2]); flag_d_max4[i] = __MAX(flag_d_max2[i], flag_d_max2[i + 2]); } for (ap_uint<5> i = 0; i < NUM - 7; i++) { flag_d_min8[i] = __MIN(flag_d_min4[i], flag_d_min4[i + 4]); flag_d_max8[i] = __MAX(flag_d_max4[i], flag_d_max4[i + 4]); } uchar_t a0 = _threshold; for (ap_uint<5> i = 0; i < PSize; i += 2) { short int a = 255; if (PSize == 16) { a = flag_d_min8[i + 1]; } // else { // for(ap_uint<5> j=1;j<PSize/2+1;j++) // { // a=__MIN(a,flag_d[i+j]); // } // } a0 = __MAX(a0, __MIN(a, flag_d[i])); // a0 >= _threshold a0 = __MAX(a0, __MIN(a, flag_d[i + PSize / 2 + 1])); } short int b0 = -_threshold; for (ap_uint<5> i = 0; i < PSize; i += 2) { short int b = -255; if (PSize == 16) { b = flag_d_max8[i + 1]; } // } else { // for(ap_uint<5> j=1;j<PSize/2+1;j++) // { // b=__MAX(b,flag_d[i+j]); // } // } b0 = __MIN(b0, __MAX(b, flag_d[i])); // b0 <= -_threshold b0 = __MIN(b0, __MAX(b, flag_d[i + PSize / 2 + 1])); } *core = __MAX(a0, -b0) - 1; } // Core window score computation complete template <int NPC, int WORDWIDTH, int DEPTH, int WIN_SZ, int WIN_SZ_SQ> void xFfastProc(XF_PTNAME(DEPTH) OutputValues[XF_NPIXPERCYCLE(NPC)], XF_PTNAME(DEPTH) src_buf[WIN_SZ][XF_NPIXPERCYCLE(NPC) + (WIN_SZ - 1)], ap_uint<8> win_size, uchar_t _threshold, XF_PTNAME(DEPTH) & pack_corners) { // clang-format off #pragma HLS INLINE // clang-format on uchar_t kx = 0, ix = 0; // XF_SNAME(WORDWIDTH) tbuf_temp; XF_PTNAME(DEPTH) tbuf_temp = 0; //////////////////////////////////////////////// // Main code goes here // Bresenham's circle score computation short int flag_d[(1 << XF_BITSHIFT(NPC))][NUM] = {0}, flag_val[(1 << XF_BITSHIFT(NPC))][NUM] = {0}; // clang-format off #pragma HLS ARRAY_PARTITION variable=flag_val dim=1 #pragma HLS ARRAY_PARTITION variable=flag_d dim=1 // clang-format on for (ap_uint<4> i = 0; i < 1; i++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT MAX=1 #pragma HLS LOOP_FLATTEN off #pragma HLS PIPELINE II=1 // clang-format on // Compute the intensity difference between the candidate pixel and pixels on the Bresenham's circle flag_d[i][0] = src_buf[3][3 + i] - src_buf[0][3 + i]; // tbuf4[3+i] - tbuf1[3+i]; flag_d[i][1] = src_buf[3][3 + i] - src_buf[0][4 + i]; // tbuf4[3+i] - tbuf1[4+i]; flag_d[i][2] = src_buf[3][3 + i] - src_buf[1][5 + i]; // tbuf4[3+i] - tbuf2[5+i]; flag_d[i][3] = src_buf[3][3 + i] - src_buf[2][6 + i]; // tbuf4[3+i] - tbuf3[6+i]; flag_d[i][4] = src_buf[3][3 + i] - src_buf[3][6 + i]; // tbuf4[3+i] - tbuf4[6+i]; flag_d[i][5] = src_buf[3][3 + i] - src_buf[4][6 + i]; // tbuf4[3+i] - tbuf5[6+i]; flag_d[i][6] = src_buf[3][3 + i] - src_buf[5][5 + i]; // tbuf4[3+i] - tbuf6[5+i]; flag_d[i][7] = src_buf[3][3 + i] - src_buf[6][4 + i]; // tbuf4[3+i] - tbuf7[4+i]; flag_d[i][8] = src_buf[3][3 + i] - src_buf[6][3 + i]; // tbuf4[3+i] - tbuf7[3+i]; flag_d[i][9] = src_buf[3][3 + i] - src_buf[6][2 + i]; // tbuf4[3+i] - tbuf7[2+i]; flag_d[i][10] = src_buf[3][3 + i] - src_buf[5][1 + i]; // tbuf4[3+i] - tbuf6[1+i]; flag_d[i][11] = src_buf[3][3 + i] - src_buf[4][0 + i]; // tbuf4[3+i] - tbuf5[0+i]; flag_d[i][12] = src_buf[3][3 + i] - src_buf[3][0 + i]; // tbuf4[3+i] - tbuf4[0+i]; flag_d[i][13] = src_buf[3][3 + i] - src_buf[2][0 + i]; // tbuf4[3+i] - tbuf3[0+i]; flag_d[i][14] = src_buf[3][3 + i] - src_buf[1][1 + i]; // tbuf4[3+i] - tbuf2[1+i]; flag_d[i][15] = src_buf[3][3 + i] - src_buf[0][2 + i]; // tbuf4[3+i] - tbuf1[2+i]; // Repeating the first 9 values flag_d[i][16] = flag_d[i][0]; flag_d[i][17] = flag_d[i][1]; flag_d[i][18] = flag_d[i][2]; flag_d[i][19] = flag_d[i][3]; flag_d[i][20] = flag_d[i][4]; flag_d[i][21] = flag_d[i][5]; flag_d[i][22] = flag_d[i][6]; flag_d[i][23] = flag_d[i][7]; flag_d[i][24] = flag_d[i][8]; // Classification of pixels on the Bresenham's circle into brighter, darker or similar w.r.t. // the candidate pixel for (ap_uint<4> j = 0; j < 8; j++) { // clang-format off #pragma HLS unroll // clang-format on if (flag_d[i][j] > _threshold) flag_val[i][j] = 1; else if (flag_d[i][j] < -_threshold) flag_val[i][j] = 2; else flag_val[i][j] = 0; if (flag_d[i][j + 8] > _threshold) flag_val[i][j + 8] = 1; else if (flag_d[i][j + 8] < -_threshold) flag_val[i][j + 8] = 2; else flag_val[i][j + 8] = 0; // Repeating the first 9 values flag_val[i][j + PSize] = flag_val[i][j]; } flag_val[i][PSize / 2 + PSize] = flag_val[i][PSize / 2]; flag_d[i][PSize / 2 + PSize] = flag_d[i][PSize / 2]; // Bresenham's circle score computation complete // Decision making for corners uchar_t core = 0; uchar_t iscorner = 0; uchar_t count = 1; for (ap_uint<5> c = 1; c < PSize + PSize / 2 + 1; c++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT MAX=25 #pragma HLS UNROLL // clang-format on if ((flag_val[i][c - 1] == flag_val[i][c]) && flag_val[i][c] > 0) { count++; if (count > PSize / 2) { iscorner = 1; // Candidate pixel is a corner } } else { count = 1; } } // Corner position computation complete // NMS Score Computation if (iscorner) { xFCoreScore(flag_d[i], _threshold, &core); pack_corners.range(ix + 7, ix) = 255; } else pack_corners.range(ix + 7, ix) = 0; ix += 8; // Pack the 8-bit score values into 64-bit words tbuf_temp.range(kx + 7, kx) = core; // Set bits in a range of positions. kx += 8; } // return tbuf_temp; OutputValues[0] = tbuf_temp; // array[(WIN_SZ_SQ)>>1]; return; } template <int SRC_T, int ROWS, int COLS, int DEPTH, int NPC, int WORDWIDTH, int TC, int WIN_SZ, int WIN_SZ_SQ> void ProcessFast(xf::cv::Mat<SRC_T, ROWS, COLS, NPC>& _src_mat, xf::cv::Mat<SRC_T, ROWS, COLS, NPC>& _out_mat, XF_SNAME(WORDWIDTH) buf[WIN_SZ][(COLS >> XF_BITSHIFT(NPC))], XF_PTNAME(DEPTH) src_buf[WIN_SZ][XF_NPIXPERCYCLE(NPC) + (WIN_SZ - 1)], XF_PTNAME(DEPTH) OutputValues[XF_NPIXPERCYCLE(NPC)], XF_SNAME(WORDWIDTH) & P0, uint16_t img_width, uint16_t img_height, uint16_t& shift_x, ap_uint<13> row_ind[WIN_SZ], ap_uint<13> row, ap_uint<8> win_size, uchar_t _threshold, XF_PTNAME(DEPTH) & pack_corners, int& read_index, int& write_index) { // clang-format off #pragma HLS INLINE // clang-format on XF_SNAME(WORDWIDTH) buf_cop[WIN_SZ]; // clang-format off #pragma HLS ARRAY_PARTITION variable=buf_cop complete dim=1 // clang-format on uint16_t npc = XF_NPIXPERCYCLE(NPC); uint16_t col_loop_var = 0; if (npc == 1) { col_loop_var = (WIN_SZ >> 1); } else { col_loop_var = 1; } for (int extract_px = 0; extract_px < WIN_SZ; extract_px++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ #pragma HLS unroll // clang-format on for (int ext_copy = 0; ext_copy < npc + WIN_SZ - 1; ext_copy++) { // clang-format off #pragma HLS unroll // clang-format on src_buf[extract_px][ext_copy] = 0; } } Col_Loop: for (ap_uint<13> col = 0; col < ((img_width) >> XF_BITSHIFT(NPC)) + col_loop_var; col++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=TC max=TC #pragma HLS pipeline #pragma HLS LOOP_FLATTEN OFF // clang-format on if (row < img_height && col < (img_width >> XF_BITSHIFT(NPC))) buf[row_ind[win_size - 1]][col] = _src_mat.read(read_index++); // Read data if (NPC == XF_NPPC8) { for (int copy_buf_var = 0; copy_buf_var < WIN_SZ; copy_buf_var++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ #pragma HLS UNROLL // clang-format on if ((row > (img_height - 1)) && (copy_buf_var > (win_size - 1 - (row - (img_height - 1))))) { buf_cop[copy_buf_var] = buf[(row_ind[win_size - 1 - (row - (img_height - 1))])][col]; } else { if (col < (img_width >> XF_BITSHIFT(NPC))) buf_cop[copy_buf_var] = buf[(row_ind[copy_buf_var])][col]; } } XF_PTNAME(DEPTH) src_buf_temp_copy[WIN_SZ][XF_NPIXPERCYCLE(NPC)]; XF_PTNAME(DEPTH) src_buf_temp_copy_extract[XF_NPIXPERCYCLE(NPC)]; for (int extract_px = 0; extract_px < WIN_SZ; extract_px++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ #pragma HLS unroll // clang-format on XF_SNAME(WORDWIDTH) toextract = buf_cop[extract_px]; xfExtractPixels<NPC, WORDWIDTH, DEPTH>(src_buf_temp_copy_extract, toextract, 0); for (int ext_copy = 0; ext_copy < npc; ext_copy++) { // clang-format off #pragma HLS unroll // clang-format on src_buf_temp_copy[extract_px][ext_copy] = src_buf_temp_copy_extract[ext_copy]; } } for (int extract_px = 0; extract_px < WIN_SZ; extract_px++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on for (int col_warp = 0; col_warp < (WIN_SZ >> 1); col_warp++) { // clang-format off #pragma HLS UNROLL #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on if (col == img_width >> XF_BITSHIFT(NPC)) { src_buf[extract_px][col_warp + npc + (WIN_SZ >> 1)] = src_buf[extract_px][npc + (WIN_SZ >> 1) - 1]; } else { src_buf[extract_px][col_warp + npc + (WIN_SZ >> 1)] = src_buf_temp_copy[extract_px][col_warp]; } } } if (col == 0) { for (int extract_px = 0; extract_px < WIN_SZ; extract_px++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on for (int col_warp = 0; col_warp < npc + (WIN_SZ >> 1); col_warp++) { // clang-format off #pragma HLS UNROLL #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on src_buf[extract_px][col_warp] = src_buf_temp_copy[extract_px][0]; } } } XF_PTNAME(DEPTH) src_buf_temp_med_apply[WIN_SZ][XF_NPIXPERCYCLE(NPC) + (WIN_SZ - 1)]; for (int applyfast = 0; applyfast < npc; applyfast++) { // clang-format off #pragma HLS UNROLL // clang-format on for (int copyi = 0; copyi < WIN_SZ; copyi++) { for (int copyj = 0; copyj < WIN_SZ; copyj++) { src_buf_temp_med_apply[copyi][copyj] = src_buf[copyi][copyj + applyfast]; } } XF_PTNAME(DEPTH) OutputValues_percycle[1]; OutputValues_percycle[0] = 0; if (row < (img_height) && row >= 6 && (!(col <= 1 && applyfast < 3)) && (!(col == (((img_width) >> XF_BITSHIFT(NPC))) && applyfast > 4))) // && (!(col==1 && applyfast<=6))) { xFfastProc<NPC, WORDWIDTH, DEPTH, WIN_SZ, WIN_SZ_SQ>(OutputValues_percycle, src_buf_temp_med_apply, WIN_SZ, _threshold, pack_corners); } if (row >= img_height) { OutputValues_percycle[0] = 0; } OutputValues[applyfast] = OutputValues_percycle[0]; } if (col >= 1) { shift_x = 0; P0 = 0; xfPackPixels<NPC, WORDWIDTH, DEPTH>(OutputValues, P0, 0, npc, shift_x); _out_mat.write(write_index++, P0); } for (int extract_px = 0; extract_px < WIN_SZ; extract_px++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on for (int col_warp = 0; col_warp < (WIN_SZ >> 1); col_warp++) { // clang-format off #pragma HLS UNROLL #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on src_buf[extract_px][col_warp] = src_buf[extract_px][col_warp + npc]; } } for (int extract_px = 0; extract_px < WIN_SZ; extract_px++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on for (int col_warp = 0; col_warp < npc; col_warp++) { // clang-format off #pragma HLS UNROLL #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on src_buf[extract_px][col_warp + (WIN_SZ >> 1)] = src_buf_temp_copy[extract_px][col_warp]; } } } else { for (int copy_buf_var = 0; copy_buf_var < WIN_SZ; copy_buf_var++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ #pragma HLS UNROLL // clang-format on if ((row > (img_height - 1)) && (copy_buf_var > (win_size - 1 - (row - (img_height - 1))))) { buf_cop[copy_buf_var] = buf[(row_ind[win_size - 1 - (row - (img_height - 1))])][col]; } else { buf_cop[copy_buf_var] = buf[(row_ind[copy_buf_var])][col]; } } for (int extract_px = 0; extract_px < WIN_SZ; extract_px++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ #pragma HLS UNROLL // clang-format on if (col < img_width) { src_buf[extract_px][win_size - 1] = buf_cop[extract_px]; } else { src_buf[extract_px][win_size - 1] = src_buf[extract_px][win_size - 2]; } } if ((col < (img_width) && row < (img_height)) && col >= 6 && row >= 6) { xFfastProc<NPC, WORDWIDTH, DEPTH, WIN_SZ, WIN_SZ_SQ>(OutputValues, src_buf, win_size, _threshold, pack_corners); } if (row >= img_height || col >= img_width) { OutputValues[0] = 0; } if (col >= (WIN_SZ >> 1)) { _out_mat.write(write_index++, OutputValues[0]); } for (int wrap_buf = 0; wrap_buf < WIN_SZ; wrap_buf++) { // clang-format off #pragma HLS UNROLL #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on for (int col_warp = 0; col_warp < WIN_SZ - 1; col_warp++) { // clang-format off #pragma HLS UNROLL #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on if (col == 0) { src_buf[wrap_buf][col_warp] = src_buf[wrap_buf][win_size - 1]; } else { src_buf[wrap_buf][col_warp] = src_buf[wrap_buf][col_warp + 1]; } } } } } // Col_Loop } template <int SRC_T, int ROWS, int COLS, int DEPTH, int NPC, int WORDWIDTH, int TC, int WIN_SZ, int WIN_SZ_SQ> void xFfast7x7(xf::cv::Mat<SRC_T, ROWS, COLS, NPC>& _src_mat, xf::cv::Mat<SRC_T, ROWS, COLS, NPC>& _out_mat, ap_uint<8> win_size, uint16_t img_height, uint16_t img_width, uchar_t _threshold) { ap_uint<13> row_ind[WIN_SZ]; // clang-format off #pragma HLS ARRAY_PARTITION variable=row_ind complete dim=1 // clang-format on XF_PTNAME(DEPTH) pack_corners; uint16_t shift_x = 0; ap_uint<13> row, col; XF_PTNAME(DEPTH) OutputValues[XF_NPIXPERCYCLE(NPC)]; // clang-format off #pragma HLS ARRAY_PARTITION variable=OutputValues complete dim=1 // clang-format on XF_PTNAME(DEPTH) src_buf[WIN_SZ][XF_NPIXPERCYCLE(NPC) + (WIN_SZ - 1)]; // clang-format off #pragma HLS ARRAY_PARTITION variable=src_buf complete dim=1 #pragma HLS ARRAY_PARTITION variable=src_buf complete dim=2 // clang-format on // src_buf1 et al merged XF_SNAME(WORDWIDTH) P0; XF_SNAME(WORDWIDTH) buf[WIN_SZ][(COLS >> XF_BITSHIFT(NPC))]; // clang-format off #pragma HLS ARRAY_PARTITION variable=buf complete dim=1 #pragma HLS RESOURCE variable=buf core=RAM_S2P_BRAM // clang-format on // initializing row index for (int init_row_ind = 0; init_row_ind < win_size; init_row_ind++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on row_ind[init_row_ind] = init_row_ind; } int read_index = 0; int write_index = 0; read_lines: for (int init_buf = row_ind[win_size >> 1]; init_buf < row_ind[win_size - 1]; init_buf++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on for (col = 0; col<img_width>> XF_BITSHIFT(NPC); col++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=TC max=TC #pragma HLS pipeline #pragma HLS LOOP_FLATTEN OFF // clang-format on buf[init_buf][col] = _src_mat.read(read_index++); } } // takes care of top borders for (col = 0; col<img_width>> XF_BITSHIFT(NPC); col++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=TC max=TC // clang-format on for (int init_buf = 0; init_buf<WIN_SZ>> 1; init_buf++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ #pragma HLS UNROLL // clang-format on buf[init_buf][col] = 0; // buf[row_ind[win_size>>1]][col]; } } Row_Loop: for (row = (win_size >> 1); row < img_height + (win_size >> 1); row++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS // clang-format on P0 = 0; ProcessFast<SRC_T, ROWS, COLS, DEPTH, NPC, WORDWIDTH, TC, WIN_SZ, WIN_SZ_SQ>( _src_mat, _out_mat, buf, src_buf, OutputValues, P0, img_width, img_height, shift_x, row_ind, row, win_size, _threshold, pack_corners, read_index, write_index); // update indices ap_uint<13> zero_ind = row_ind[0]; for (int init_row_ind = 0; init_row_ind < WIN_SZ - 1; init_row_ind++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ #pragma HLS UNROLL // clang-format on row_ind[init_row_ind] = row_ind[init_row_ind + 1]; } row_ind[win_size - 1] = zero_ind; } // Row_Loop } template <int NPC, int DEPTH, int WIN_SZ, int WIN_SZ_SQ> void xFnmsProc(XF_PTNAME(DEPTH) OutputValues[XF_NPIXPERCYCLE(NPC)], XF_PTNAME(DEPTH) src_buf[WIN_SZ][XF_NPIXPERCYCLE(NPC) + (WIN_SZ - 1)], ap_uint<8> win_size) { // clang-format off #pragma HLS INLINE // clang-format on XF_PTNAME(DEPTH) pix; // Comparing scores of the candidate pixel with neighbors in a 3x3 window if (src_buf[1][1] != 0) { // if score of candidate pixel != 0 if ((src_buf[1][1] > src_buf[1][0]) && (src_buf[1][1] > src_buf[1][2]) && (src_buf[1][1] > src_buf[0][0]) && (src_buf[1][1] > src_buf[0][1]) && (src_buf[1][1] > src_buf[0][2]) && (src_buf[1][1] > src_buf[2][0]) && (src_buf[1][1] > src_buf[2][1]) && (src_buf[1][1] > src_buf[2][2])) { pix = 255; } else { pix = 0; } } else { pix = 0; } OutputValues[0] = pix; // array[(WIN_SZ_SQ)>>1]; return; } template <int SRC_T, int ROWS, int COLS, int DEPTH, int NPC, int WORDWIDTH, int TC, int WIN_SZ, int WIN_SZ_SQ> void Processfastnms(xf::cv::Mat<SRC_T, ROWS, COLS, NPC>& _src_mat, xf::cv::Mat<SRC_T, ROWS, COLS, NPC>& _out_mat, XF_SNAME(WORDWIDTH) buf[WIN_SZ][(COLS >> XF_BITSHIFT(NPC))], XF_PTNAME(DEPTH) src_buf[WIN_SZ][XF_NPIXPERCYCLE(NPC) + (WIN_SZ - 1)], XF_PTNAME(DEPTH) OutputValues[XF_NPIXPERCYCLE(NPC)], XF_SNAME(WORDWIDTH) & P0, uint16_t img_width, uint16_t img_height, uint16_t& shift_x, ap_uint<13> row_ind[WIN_SZ], ap_uint<13> row, ap_uint<8> win_size, int& read_index, int& write_index) { // clang-format off #pragma HLS INLINE // clang-format on XF_SNAME(WORDWIDTH) buf_cop[WIN_SZ]; // clang-format off #pragma HLS ARRAY_PARTITION variable=buf_cop complete dim=1 // clang-format on uint16_t npc = XF_NPIXPERCYCLE(NPC); uint16_t col_loop_var = 0; if (npc == 1) { col_loop_var = (WIN_SZ >> 1); } else { col_loop_var = 1; } for (int extract_px = 0; extract_px < WIN_SZ; extract_px++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ #pragma HLS unroll // clang-format on for (int ext_copy = 0; ext_copy < npc + WIN_SZ - 1; ext_copy++) { // clang-format off #pragma HLS unroll // clang-format on src_buf[extract_px][ext_copy] = 0; } } Col_Loop: for (ap_uint<13> col = 0; col < ((img_width) >> XF_BITSHIFT(NPC)) + col_loop_var; col++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=TC max=TC #pragma HLS pipeline #pragma HLS LOOP_FLATTEN OFF // clang-format on if (row < img_height && col < (img_width >> XF_BITSHIFT(NPC))) buf[row_ind[win_size - 1]][col] = _src_mat.read(read_index++); // Read data if (NPC == XF_NPPC8) { for (int copy_buf_var = 0; copy_buf_var < WIN_SZ; copy_buf_var++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ #pragma HLS UNROLL // clang-format on if ((row > (img_height - 1)) && (copy_buf_var > (win_size - 1 - (row - (img_height - 1))))) { buf_cop[copy_buf_var] = buf[(row_ind[win_size - 1 - (row - (img_height - 1))])][col]; } else { if (col < (img_width >> XF_BITSHIFT(NPC))) buf_cop[copy_buf_var] = buf[(row_ind[copy_buf_var])][col]; // else // buf_cop[copy_buf_var] = buf_cop[copy_buf_var]; } } XF_PTNAME(DEPTH) src_buf_temp_copy[WIN_SZ][XF_NPIXPERCYCLE(NPC)]; XF_PTNAME(DEPTH) src_buf_temp_copy_extract[XF_NPIXPERCYCLE(NPC)]; for (int extract_px = 0; extract_px < WIN_SZ; extract_px++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ #pragma HLS unroll // clang-format on XF_SNAME(WORDWIDTH) toextract = buf_cop[extract_px]; xfExtractPixels<NPC, WORDWIDTH, DEPTH>(src_buf_temp_copy_extract, toextract, 0); for (int ext_copy = 0; ext_copy < npc; ext_copy++) { // clang-format off #pragma HLS unroll // clang-format on src_buf_temp_copy[extract_px][ext_copy] = src_buf_temp_copy_extract[ext_copy]; } } for (int extract_px = 0; extract_px < WIN_SZ; extract_px++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on for (int col_warp = 0; col_warp < (WIN_SZ >> 1); col_warp++) { // clang-format off #pragma HLS UNROLL #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on if (col == img_width >> XF_BITSHIFT(NPC)) { src_buf[extract_px][col_warp + npc + (WIN_SZ >> 1)] = src_buf[extract_px][npc + (WIN_SZ >> 1) - 1]; } else { src_buf[extract_px][col_warp + npc + (WIN_SZ >> 1)] = src_buf_temp_copy[extract_px][col_warp]; } } } if (col == 0) { for (int extract_px = 0; extract_px < WIN_SZ; extract_px++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on for (int col_warp = 0; col_warp < npc + (WIN_SZ >> 1); col_warp++) { // clang-format off #pragma HLS UNROLL #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on src_buf[extract_px][col_warp] = src_buf_temp_copy[extract_px][0]; } } } XF_PTNAME(DEPTH) src_buf_temp_med_apply[WIN_SZ][XF_NPIXPERCYCLE(NPC) + (WIN_SZ - 1)]; for (int applyfast = 0; applyfast < npc; applyfast++) { // clang-format off #pragma HLS UNROLL // clang-format on for (int copyi = 0; copyi < WIN_SZ; copyi++) { for (int copyj = 0; copyj < WIN_SZ; copyj++) { src_buf_temp_med_apply[copyi][copyj] = src_buf[copyi][copyj + applyfast]; } } XF_PTNAME(DEPTH) OutputValues_percycle[XF_NPIXPERCYCLE(NPC)]; xFnmsProc<NPC, DEPTH, WIN_SZ, WIN_SZ_SQ>(OutputValues_percycle, src_buf_temp_med_apply, WIN_SZ); OutputValues[applyfast] = OutputValues_percycle[0]; } if (col >= 1) { shift_x = 0; P0 = 0; xfPackPixels<NPC, WORDWIDTH, DEPTH>(OutputValues, P0, 0, npc, shift_x); _out_mat.write(write_index++, P0); } for (int extract_px = 0; extract_px < WIN_SZ; extract_px++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on for (int col_warp = 0; col_warp < (WIN_SZ >> 1); col_warp++) { // clang-format off #pragma HLS UNROLL #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on src_buf[extract_px][col_warp] = src_buf[extract_px][col_warp + npc]; } } for (int extract_px = 0; extract_px < WIN_SZ; extract_px++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on for (int col_warp = 0; col_warp < npc; col_warp++) { // clang-format off #pragma HLS UNROLL #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on src_buf[extract_px][col_warp + (WIN_SZ >> 1)] = src_buf_temp_copy[extract_px][col_warp]; } } } else { for (int copy_buf_var = 0; copy_buf_var < WIN_SZ; copy_buf_var++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ #pragma HLS UNROLL // clang-format on if ((row > (img_height - 1)) && (copy_buf_var > (win_size - 1 - (row - (img_height - 1))))) { buf_cop[copy_buf_var] = buf[(row_ind[win_size - 1 - (row - (img_height - 1))])][col]; } else { buf_cop[copy_buf_var] = buf[(row_ind[copy_buf_var])][col]; } } for (int extract_px = 0; extract_px < WIN_SZ; extract_px++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ #pragma HLS UNROLL // clang-format on if (col < img_width) { src_buf[extract_px][win_size - 1] = buf_cop[extract_px]; } else { src_buf[extract_px][win_size - 1] = src_buf[extract_px][win_size - 2]; } } xFnmsProc<NPC, DEPTH, WIN_SZ, WIN_SZ_SQ>(OutputValues, src_buf, win_size); if (col >= (WIN_SZ >> 1)) { _out_mat.write(write_index++, OutputValues[0]); } for (int wrap_buf = 0; wrap_buf < WIN_SZ; wrap_buf++) { // clang-format off #pragma HLS UNROLL #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on for (int col_warp = 0; col_warp < WIN_SZ - 1; col_warp++) { // clang-format off #pragma HLS UNROLL #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on if (col == 0) { src_buf[wrap_buf][col_warp] = src_buf[wrap_buf][win_size - 1]; } else { src_buf[wrap_buf][col_warp] = src_buf[wrap_buf][col_warp + 1]; } } } } } // Col_Loop } template <int SRC_T, int ROWS, int COLS, int DEPTH, int NPC, int WORDWIDTH, int TC, int WIN_SZ, int WIN_SZ_SQ> void xFfastnms(xf::cv::Mat<SRC_T, ROWS, COLS, NPC>& _src_mat, xf::cv::Mat<SRC_T, ROWS, COLS, NPC>& _out_mat, ap_uint<8> win_size, uint16_t img_height, uint16_t img_width) { ap_uint<13> row_ind[WIN_SZ]; // clang-format off #pragma HLS ARRAY_PARTITION variable=row_ind complete dim=1 // clang-format on uint16_t shift_x = 0; ap_uint<13> row, col; XF_PTNAME(DEPTH) OutputValues[XF_NPIXPERCYCLE(NPC)]; // clang-format off #pragma HLS ARRAY_PARTITION variable=OutputValues complete dim=1 // clang-format on XF_PTNAME(DEPTH) src_buf[WIN_SZ][XF_NPIXPERCYCLE(NPC) + (WIN_SZ - 1)]; // clang-format off #pragma HLS ARRAY_PARTITION variable=src_buf complete dim=1 #pragma HLS ARRAY_PARTITION variable=src_buf complete dim=2 // clang-format on // src_buf1 et al merged XF_SNAME(WORDWIDTH) P0; XF_SNAME(WORDWIDTH) buf[WIN_SZ][(COLS >> XF_BITSHIFT(NPC))]; // clang-format off #pragma HLS ARRAY_PARTITION variable=buf complete dim=1 #pragma HLS RESOURCE variable=buf core=RAM_S2P_BRAM // clang-format on // initializing row index for (int init_row_ind = 0; init_row_ind < win_size; init_row_ind++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on row_ind[init_row_ind] = init_row_ind; } int readind_val = 0, writeind_val = 0; read_lines: for (int init_buf = row_ind[win_size >> 1]; init_buf < row_ind[win_size - 1]; init_buf++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ // clang-format on for (col = 0; col<img_width>> XF_BITSHIFT(NPC); col++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=TC max=TC #pragma HLS pipeline #pragma HLS LOOP_FLATTEN OFF // clang-format on buf[init_buf][col] = _src_mat.read(readind_val++); } } // takes care of top borders for (col = 0; col<img_width>> XF_BITSHIFT(NPC); col++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=TC max=TC // clang-format on for (int init_buf = 0; init_buf<WIN_SZ>> 1; init_buf++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ #pragma HLS UNROLL // clang-format on buf[init_buf][col] = buf[row_ind[win_size >> 1]][col]; } } Row_Loop: for (row = (win_size >> 1); row < img_height + (win_size >> 1); row++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS // clang-format on P0 = 0; Processfastnms<SRC_T, ROWS, COLS, DEPTH, NPC, WORDWIDTH, TC, WIN_SZ, WIN_SZ_SQ>( _src_mat, _out_mat, buf, src_buf, OutputValues, P0, img_width, img_height, shift_x, row_ind, row, win_size, readind_val, writeind_val); // update indices ap_uint<13> zero_ind = row_ind[0]; for (int init_row_ind = 0; init_row_ind < WIN_SZ - 1; init_row_ind++) { // clang-format off #pragma HLS LOOP_TRIPCOUNT min=WIN_SZ max=WIN_SZ #pragma HLS UNROLL // clang-format on row_ind[init_row_ind] = row_ind[init_row_ind + 1]; } row_ind[win_size - 1] = zero_ind; } // Row_Loop } template <int SRC_T, int ROWS, int COLS, int DEPTH, int NPC, int WORDWIDTH_SRC, int WORDWIDTH_DST, int NMSVAL> void xFFastCornerDetection(xf::cv::Mat<SRC_T, ROWS, COLS, NPC>& _src_mat, xf::cv::Mat<SRC_T, ROWS, COLS, NPC>& _dst_mat, unsigned short _image_height, unsigned short _image_width, uchar_t _threshold) { #ifndef __SYNTHESIS__ assert(((DEPTH == XF_8UP)) && "Invalid Depth. The function xFFast " "is valid only for the Depths AU_8U"); assert(((NMSVAL == 0) || (NMSVAL == 1)) && "Invalid Value. The NMS value should be either 0 or 1"); assert(((_image_height <= ROWS) && (_image_width <= COLS)) && "ROWS and COLS should be greater than input image"); #endif xf::cv::Mat<SRC_T, ROWS, COLS, NPC> _dst(_image_height, _image_width); // clang-format off #pragma HLS DATAFLOW // clang-format on #pragma HLS stream variable = _dst.data depth = 2 if (NMSVAL == 1) { xFfast7x7<SRC_T, ROWS, COLS, DEPTH, NPC, WORDWIDTH_SRC, (COLS >> XF_BITSHIFT(NPC)) + (7 >> 1), 7, 7 * 7>( _src_mat, _dst, 7, _image_height, _image_width, _threshold); xFfastnms<SRC_T, ROWS, COLS, DEPTH, NPC, WORDWIDTH_SRC, (COLS >> XF_BITSHIFT(NPC)) + (3 >> 1), 3, 3 * 3>( _dst, _dst_mat, 3, _image_height, _image_width); } else if (NMSVAL == 0) { xFfast7x7<SRC_T, ROWS, COLS, DEPTH, NPC, WORDWIDTH_SRC, (COLS >> XF_BITSHIFT(NPC)) + (7 >> 1), 7, 7 * 7>( _src_mat, _dst_mat, 7, _image_height, _image_width, _threshold); } } template <int NMS, int SRC_T, int ROWS, int COLS, int NPC = 1> void fast(xf::cv::Mat<SRC_T, ROWS, COLS, NPC>& _src_mat, xf::cv::Mat<SRC_T, ROWS, COLS, NPC>& _dst_mat, unsigned char _threshold) { // clang-format off #pragma HLS inline off // clang-format on // clang-format off // clang-format on xFFastCornerDetection<SRC_T, ROWS, COLS, XF_DEPTH(SRC_T, NPC), NPC, XF_WORDWIDTH(SRC_T, NPC), XF_32UW, NMS>( _src_mat, _dst_mat, _src_mat.rows, _src_mat.cols, _threshold); } } // namespace cv } // namespace xf #endif //_XF_FAST_HPP_
75af3a46d0ffef8e607eacec8824846b0c4afddd
d97b36614ecd3ea7f1e32b5a131db1c4cec2d452
/ADSA-PS/PracticeCPP/GCDEuclid.cpp
4ff98a7d781578e806617a46171274b1570c10d2
[]
no_license
SumanM-IIIT/IIIT-H_Sem1_Suman
896e1b5f5fd6f7dcd8801f1d413ae89bcb154416
1cc57d131ebcff4154dcdf9292d94bd5f6a847e4
refs/heads/master
2023-01-21T08:50:16.959690
2020-11-27T15:35:35
2020-11-27T15:35:35
294,190,200
0
0
null
null
null
null
UTF-8
C++
false
false
470
cpp
GCDEuclid.cpp
#include <bits/stdc++.h> using namespace std; template <class T> class demo { T x, y; public: demo(T a, T b) { x = a; y = b; } void print() { cout << x << " " << y << endl; } }; int main(int argc, char const *argv[]) { /*int a, b, swap; cin >> a >> b; if(b > a) { swap = a; a = b; b = swap; } int tmp; while(b != 0) { tmp = a % b; a = b; b = tmp; } cout << "The GCD: " << a << endl; */ demo<char> dm('a', 'b'); dm.print(); return 0; }
7a50c318e78e839b6a1d0be9e1decd5c4b6fc613
15b141a7648a05b7ad6c724c43fb703c7ba25857
/cache/Solution.cpp
a4d0104e740cb23aa66fe0cd7358ae3afecfce96
[]
no_license
puffikru/Brown_belt
d1a1ec0797535eae04852461a395ba3e33cb431d
e309ce08e21f48454195849b573bb119d051ac56
refs/heads/master
2021-06-20T12:19:16.014648
2021-05-08T21:44:04
2021-05-08T21:44:04
215,209,647
3
2
null
null
null
null
UTF-8
C++
false
false
1,824
cpp
Solution.cpp
#include "Common.h" #include <unordered_map> #include <list> #include <mutex> using namespace std; class LruCache : public ICache { public: LruCache( shared_ptr<IBooksUnpacker> books_unpacker, const Settings &settings) : books_unpacker_(move(books_unpacker)), settings_(settings) {} BookPtr GetBook(const string &book_name) override { lock_guard<mutex> lock(mx); if (auto it = cache_.find(book_name); it != cache_.end()) { rate_.splice(rate_.begin(), rate_, it->second); return rate_.front(); } auto book = books_unpacker_->UnpackBook(book_name); if (book->GetContent().size() > settings_.max_memory) { rate_.clear(); cache_.clear(); total_size = 0; return move(book); } total_size += book->GetContent().size(); if (total_size > settings_.max_memory) { while (total_size > settings_.max_memory) { total_size -= rate_.back()->GetContent().size(); cache_.erase(rate_.back()->GetName()); rate_.pop_back(); } } rate_.emplace_front(move(book)); cache_[rate_.front()->GetName()] = rate_.begin(); return *cache_[book_name]; } ~LruCache() override { } private: shared_ptr<IBooksUnpacker> books_unpacker_; const Settings settings_; list<BookPtr> rate_; unordered_map<string, list<BookPtr>::iterator> cache_; size_t total_size = 0; mutable mutex mx; }; unique_ptr<ICache> MakeCache( shared_ptr<IBooksUnpacker> books_unpacker, const ICache::Settings &settings ) { return make_unique<LruCache>(books_unpacker, settings); }
7c79a06dc11baf05599326c75f8966bf0eec0dfe
1d9237e0ecc227a3c9ce3cb6d4b913d3ad87e368
/Arkanoid_v2.0/ball/ball.cpp
3fcea50fd18559b3c3c20606a19bc03d9ecff604
[]
no_license
jarromi/Arkanoid_v2.0
d5d5438526a11775ef70426372f3917866f79d83
e2094a0e9f1100a1098741c67ef75cc21461e035
refs/heads/master
2022-07-06T08:15:56.561790
2020-05-18T18:31:05
2020-05-18T18:31:05
263,603,099
0
0
null
null
null
null
UTF-8
C++
false
false
12,159
cpp
ball.cpp
#include "ball.h" // ------------------------------------------------------------- // Initialization of static variables // Vertices (in header file since only a few of them) const float ball::vertices[] = { 0.0f, 1.0f, _PHI_ICOSAHEDRON, 0.1f, 0.2f, 0.0f, 1.0f,-_PHI_ICOSAHEDRON, 0.8f, 0.4f, 0.0f,-1.0f, _PHI_ICOSAHEDRON, 0.3f, 0.2f, 0.0f,-1.0f,-_PHI_ICOSAHEDRON, 0.6f, 0.4f, // 1.0f, _PHI_ICOSAHEDRON, 0.0f, 0.0f, 0.4f, 1.0f,-_PHI_ICOSAHEDRON, 0.0f, 0.4f, 0.4f, -1.0f, _PHI_ICOSAHEDRON, 0.0f, 0.9f, 0.2f, -1.0f,-_PHI_ICOSAHEDRON, 0.0f, 0.5f, 0.2f, // _PHI_ICOSAHEDRON, 0.0f, 1.0f, 0.2f, 0.4f, _PHI_ICOSAHEDRON, 0.0f,-1.0f, 0.5f, 0.6f, -_PHI_ICOSAHEDRON, 0.0f, 1.0f, 0.6f, 0.0f, -_PHI_ICOSAHEDRON, 0.0f,-1.0f, 0.7f, 0.2f }; // Indices for the EBO (in header file since only a few of them) const unsigned int ball::indices[] = { 0, 2, 8, 0, 4, 6, 0, 6, 10, 0, 8, 4, 0, 10, 2, 1, 3, 9, 1, 4, 6, 1, 6, 11, 1, 9, 4, 1, 11, 3, 2, 5, 7, 2, 7, 10, 2, 8, 5, 3, 5, 7, 3, 7, 11, 3, 9, 5, 4, 8, 9, 5, 8, 9, 6, 10, 11, 7, 10, 11 }; // Color - shade of grey const glm::vec3 ball::color = glm::vec3(0.3f,0.3f,0.3f); const glm::vec3 ball::scaleVec = glm::vec3(0.2628655, 0.2628655, 0.2628655); const glm::vec3 ball::rotationAxis = glm::vec3(1.0f, 1.0f, 0.1f); //Texture, VAO, EBO, and VBO indices unsigned int ball::TextureID=0; unsigned int ball::VAO = 0; unsigned int ball::EBO = 0; unsigned int ball::VBO = 0; unsigned int ball::count = 0; const float ball::rad = 0.5f; // --------------------------------------------------------------------------------- // Constructors, destructors and assignment operator // Default constructor ball::ball() { // keep count of number of balls ++count; // set the position and state position = glm::vec3(0.0f, -8.25f, 0.0f); // Initial position at the bottom of the screen futurePosition = position; // Set the position in the next frame to be the same as initial velocity = glm::vec3(0.0f, 1.0f, 0.0f); // Velocity - by default straight up speed = 0.0f; // Speed - initially 0 modelMatrix = glm::mat4(1.0); // modelMatrix will map the object for drawing modelMatrix = glm::translate(modelMatrix, position); modelMatrix = glm::scale(modelMatrix, scaleVec); // load textures if neede if (count == 1) { glGenTextures(1, &TextureID); glBindTexture(GL_TEXTURE_2D, TextureID); // bind texture // next set properties of textures glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); unsigned char* data; int width, height, nrChannels; data = stbi_load("./ball/white.png", &width, &height, &nrChannels, 0); // load texture - plain white if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); } else { logger::log("Failed to load the ball texture.\n"); throw "BAD_BALL"; } stbi_image_free(data); // release the memory of the image // set VAO, EBO, VBO if needed glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); glGenBuffers(1, &EBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); glBindVertexArray(0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); } } // Position constructor - set position, velocity and speed ball::ball(const glm::vec2 &_pos, const glm::vec2 &_vel, const float &_spd) { // keep count of number of balls ++count; // set the position and state position = glm::vec3(_pos, 0.0f); if (position.x > _X_BNDR - rad) { position.x = _X_BNDR - rad; } else if (position.x < -_X_BNDR + rad) { position.x = -_X_BNDR + rad; } if (position.y > _Y_BNDR - rad) { position.y = _Y_BNDR - rad; } else if (position.y < -_Y_BNDR + rad) { position.y = -_Y_BNDR + rad; } futurePosition = position; velocity = glm::normalize(glm::vec3(_vel, 0.0f)); if (abs(velocity.y) < abs(velocity.x) * 0.3f) { float sign = velocity.y / abs(velocity.y); velocity.y = abs(velocity.x) * 0.3f * sign; velocity = glm::normalize(velocity); } speed = _spd; modelMatrix = glm::mat4(1.0); modelMatrix = glm::translate(modelMatrix, position); modelMatrix = glm::scale(modelMatrix, scaleVec); // load textures if neede if (count == 1) { glGenTextures(1, &TextureID); glBindTexture(GL_TEXTURE_2D, TextureID); // bind texture // next set properties of textures glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); unsigned char* data; int width, height, nrChannels; data = stbi_load("./ball/white.png", &width, &height, &nrChannels, 0); // load texture if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { logger::log("Failed to load the ball texture.\n"); throw "BAD_BALL"; } stbi_image_free(data); // release the memory of the image // set VAO, EBO, VBO if needed glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); glGenBuffers(1, &EBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); glBindVertexArray(0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); } } //Copy constructor ball::ball(const ball &_lhs) { // keep count of number of balls ++count; // set the position and state position = _lhs.position; futurePosition = _lhs.futurePosition; velocity = _lhs.velocity; speed = _lhs.speed; modelMatrix = _lhs.modelMatrix; // No need to load textures VAO, VBO, EBO } // Assignment operator ball& ball::operator = (const ball& _lhs) { // set the position and state position = _lhs.position; futurePosition = _lhs.futurePosition; velocity = _lhs.velocity; speed = _lhs.speed; modelMatrix = glm::mat4(1.0); modelMatrix = glm::translate(modelMatrix, position); modelMatrix = glm::scale(modelMatrix, scaleVec); // No need to load textures VAO, VBO, EBO return *this; } //default destructor ball::~ball() { --count; if (count == 0) { glDeleteTextures(1, &TextureID); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); glDeleteVertexArrays(1, &VAO); } } // ----------------------------------------------------------------------- // Setters and getters // Set position void ball::set_position(const glm::vec2& _pos) { position = glm::vec3(_pos, 0.0f); if (position.x > _X_BNDR - rad) { position.x = _X_BNDR - rad; } else if (position.x < -_X_BNDR + rad) { position.x = -_X_BNDR + rad; } if (position.y > _Y_BNDR - rad) { position.y = _Y_BNDR - rad; } else if (position.y < -_Y_BNDR + rad) { position.y = -_Y_BNDR + rad; } futurePosition = position; float angle = glfwGetTime()*1000.f; modelMatrix = glm::mat4(1.0); modelMatrix = glm::translate(modelMatrix, position); modelMatrix = glm::scale(modelMatrix, scaleVec); modelMatrix = glm::rotate(modelMatrix, glm::radians(angle),rotationAxis); } // Set velocity void ball::set_velocity(const glm::vec2 &_vel) { velocity = glm::normalize(glm::vec3(_vel, 0.0f)); if (abs(velocity.y) < abs(velocity.x) * 0.3f) { float sign = velocity.y / abs(velocity.y); velocity.y = abs(velocity.x) * 0.3f * sign; velocity = glm::normalize(velocity); } } // Set speed void ball::set_speed(const float& _spd) { speed = _spd; } // Get position glm::vec2 ball::get_position() const { return glm::vec2(position.x, position.y); } // Get futurePosition glm::vec2 ball::get_future_position() const { return glm::vec2(futurePosition.x, futurePosition.y); } // Get velocity glm::vec2 ball::get_velocity() const { return glm::vec2(velocity.x,velocity.y); } // Get speed float ball::get_speed() const { return speed; } // Get count unsigned int ball::get_count() { return count; } // ----------------------------------------------------------------------- // Other methods and functions // Prepare to draw void ball::prepare_to_draw(const Shader& _SO) { _SO.setInt("ourTexture", 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, TextureID); glBindVertexArray(VAO); } // Draw an object void ball::draw(const Shader& _SO) { unsigned int modelID = glGetUniformLocation(_SO.ID, "model"); glUniformMatrix4fv(modelID, 1, GL_FALSE, glm::value_ptr(modelMatrix)); unsigned int colorID = glGetUniformLocation(_SO.ID, "ourColor"); glUniform3f(colorID, color.x, color.y, color.z); glDrawElements(GL_TRIANGLES, 60, GL_UNSIGNED_INT, 0); } // Propagate with a time discretization deltaTime void ball::propagate(const float &deltaTime){ position += speed*velocity * deltaTime; float angle = glfwGetTime() * 1000.f; futurePosition = position + speed * velocity * deltaTime; if (position.x > _X_BNDR-rad) { position.x = _X_BNDR-rad; velocity.x *= -1.0f; } else if (position.x < -_X_BNDR+rad) { position.x = -_X_BNDR+rad; velocity.x *= -1.0f; } if (position.y > _Y_BNDR-rad) { position.y = _Y_BNDR-rad; velocity.y *= -1.0f; } modelMatrix = glm::mat4(1.0); modelMatrix = glm::translate(modelMatrix, position); modelMatrix = glm::scale(modelMatrix, scaleVec); modelMatrix = glm::rotate(modelMatrix, glm::radians(angle), rotationAxis); } // Condition for loosing bool ball::out_of_bounds() { if (position.y < -10.0f) return true; else return false; } // Function for network communication // We need to exchange information about about: // velocity, position, futurePosition, speed // _lptr - points to the memory position where to write data // _rptr - points to the memory position beyond which we cannot write // returns pointer to the first free address after writing float* ball::comm_props(float* _lptr, float* _rptr) { if (_lptr + 7 <= _rptr) { //velocity *_lptr = velocity.x; _lptr += 1; *_lptr = velocity.y; _lptr += 1; //position *_lptr = position.x; _lptr += 1; *_lptr = position.y; _lptr += 1; //futurePosition *_lptr = futurePosition.x; _lptr += 1; *_lptr = futurePosition.y; _lptr += 1; //speed *_lptr = speed; _lptr += 1; return _lptr; } else { logger::log("Not enough space in the given pointer.\n"); throw "BAD_BALL_COMM"; } } // Function for network communication // We need to exchange information about about: // velocity, position, futurePosition, speed // _lptr - points to the memory position where to write data // _rptr - points to the memory position beyond which we cannot write // returns pointer to the first free address after writing float* ball::read_props(float* _lptr, float* _rptr) { if (_lptr + 7 <= _rptr) { //velocity velocity.x = *_lptr; _lptr += 1; velocity.y = *_lptr;; _lptr += 1; //position position.x = *_lptr;; _lptr += 1; position.y = *_lptr;; _lptr += 1; //futurePosition futurePosition.x = *_lptr;; _lptr += 1; futurePosition.y = *_lptr;; _lptr += 1; //speed speed = *_lptr;; _lptr += 1; return _lptr; } else { logger::log("Not enough space in the given pointer.\n"); throw "BAD_BALL_COMM"; } }
d0a7307d287687e479ea9b832d3fc62e939cc4f7
d14b5d78b72711e4614808051c0364b7bd5d6d98
/third_party/llvm-16.0/llvm/lib/DebugInfo/LogicalView/Core/LVElement.cpp
a320752befc4634639227d85d53b6884c504c69d
[ "Apache-2.0" ]
permissive
google/swiftshader
76659addb1c12eb1477050fded1e7d067f2ed25b
5be49d4aef266ae6dcc95085e1e3011dad0e7eb7
refs/heads/master
2023-07-21T23:19:29.415159
2023-07-21T19:58:29
2023-07-21T20:50:19
62,297,898
1,981
306
Apache-2.0
2023-07-05T21:29:34
2016-06-30T09:25:24
C++
UTF-8
C++
false
false
17,558
cpp
LVElement.cpp
//===-- LVElement.cpp -----------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This implements the LVElement class. // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/LogicalView/Core/LVElement.h" #include "llvm/DebugInfo/LogicalView/Core/LVReader.h" #include "llvm/DebugInfo/LogicalView/Core/LVScope.h" #include "llvm/DebugInfo/LogicalView/Core/LVSymbol.h" #include "llvm/DebugInfo/LogicalView/Core/LVType.h" using namespace llvm; using namespace llvm::logicalview; #define DEBUG_TYPE "Element" LVElementDispatch LVElement::Dispatch = { {LVElementKind::Discarded, &LVElement::getIsDiscarded}, {LVElementKind::Global, &LVElement::getIsGlobalReference}, {LVElementKind::Optimized, &LVElement::getIsOptimized}}; LVType *LVElement::getTypeAsType() const { return ElementType && ElementType->getIsType() ? static_cast<LVType *>(ElementType) : nullptr; } LVScope *LVElement::getTypeAsScope() const { return ElementType && ElementType->getIsScope() ? static_cast<LVScope *>(ElementType) : nullptr; } // Set the element type. void LVElement::setGenericType(LVElement *Element) { if (!Element->isTemplateParam()) { setType(Element); return; } // For template parameters, the instance type can be a type or a scope. if (options().getAttributeArgument()) { if (Element->getIsKindType()) setType(Element->getTypeAsType()); else if (Element->getIsKindScope()) setType(Element->getTypeAsScope()); } else setType(Element); } // Discriminator as string. std::string LVElement::discriminatorAsString() const { uint32_t Discriminator = getDiscriminator(); std::string String; raw_string_ostream Stream(String); if (Discriminator && options().getAttributeDiscriminator()) Stream << "," << Discriminator; return String; } // Get the type as a string. StringRef LVElement::typeAsString() const { return getHasType() ? getTypeName() : typeVoid(); } // Get name for element type. StringRef LVElement::getTypeName() const { return ElementType ? ElementType->getName() : StringRef(); } static size_t getStringIndex(StringRef Name) { // Convert the name to Unified format ('\' have been converted into '/'). std::string Pathname(transformPath(Name)); // Depending on the --attribute=filename and --attribute=pathname command // line options, use the basename or the full pathname as the name. if (!options().getAttributePathname()) { // Get the basename by ignoring any prefix up to the last slash ('/'). StringRef Basename = Pathname; size_t Pos = Basename.rfind('/'); if (Pos != std::string::npos) Basename = Basename.substr(Pos + 1); return getStringPool().getIndex(Basename); } return getStringPool().getIndex(Pathname); } void LVElement::setName(StringRef ElementName) { // In the case of Root or Compile Unit, get index for the flatted out name. NameIndex = getTransformName() ? getStringIndex(ElementName) : getStringPool().getIndex(ElementName); } void LVElement::setFilename(StringRef Filename) { // Get index for the flattened out filename. FilenameIndex = getStringIndex(Filename); } // Return the string representation of a DIE offset. std::string LVElement::typeOffsetAsString() const { if (options().getAttributeOffset()) { LVElement *Element = getType(); return hexSquareString(Element ? Element->getOffset() : 0); } return {}; } StringRef LVElement::accessibilityString(uint32_t Access) const { uint32_t Value = getAccessibilityCode(); switch (Value ? Value : Access) { case dwarf::DW_ACCESS_public: return "public"; case dwarf::DW_ACCESS_protected: return "protected"; case dwarf::DW_ACCESS_private: return "private"; default: return StringRef(); } } StringRef LVElement::externalString() const { return getIsExternal() ? "extern" : StringRef(); } StringRef LVElement::inlineCodeString(uint32_t Code) const { uint32_t Value = getInlineCode(); switch (Value ? Value : Code) { case dwarf::DW_INL_not_inlined: return "not_inlined"; case dwarf::DW_INL_inlined: return "inlined"; case dwarf::DW_INL_declared_not_inlined: return "declared_not_inlined"; case dwarf::DW_INL_declared_inlined: return "declared_inlined"; default: return StringRef(); } } StringRef LVElement::virtualityString(uint32_t Virtuality) const { uint32_t Value = getVirtualityCode(); switch (Value ? Value : Virtuality) { case dwarf::DW_VIRTUALITY_none: return StringRef(); case dwarf::DW_VIRTUALITY_virtual: return "virtual"; case dwarf::DW_VIRTUALITY_pure_virtual: return "pure virtual"; default: return StringRef(); } } void LVElement::resolve() { if (getIsResolved()) return; setIsResolved(); resolveReferences(); resolveParents(); resolveExtra(); resolveName(); } // Set File/Line using the specification element. void LVElement::setFileLine(LVElement *Specification) { // In the case of inlined functions, the correct scope must be associated // with the file and line information of the outline version. if (!isLined()) { setLineNumber(Specification->getLineNumber()); setIsLineFromReference(); } if (!isFiled()) { setFilenameIndex(Specification->getFilenameIndex()); setIsFileFromReference(); } } void LVElement::resolveName() { // Set the qualified name if requested. if (options().getAttributeQualified()) resolveQualifiedName(); setIsResolvedName(); } // Resolve any parents. void LVElement::resolveParents() { if (isRoot() || isCompileUnit()) return; LVScope *Parent = getParentScope(); if (Parent && !Parent->getIsCompileUnit()) Parent->resolve(); } // Generate a name for unnamed elements. void LVElement::generateName(std::string &Prefix) const { LVScope *Scope = getParentScope(); if (!Scope) return; // Use its parent name and any line information. Prefix.append(std::string(Scope->getName())); Prefix.append("::"); Prefix.append(isLined() ? lineNumberAsString(/*ShowZero=*/true) : "?"); // Remove any whitespaces. Prefix.erase(std::remove_if(Prefix.begin(), Prefix.end(), ::isspace), Prefix.end()); } // Generate a name for unnamed elements. void LVElement::generateName() { setIsAnonymous(); std::string Name; generateName(Name); setName(Name); setIsGeneratedName(); } void LVElement::updateLevel(LVScope *Parent, bool Moved) { setLevel(Parent->getLevel() + 1); if (Moved) setHasMoved(); } // Generate the full name for the element, to include special qualifiers. void LVElement::resolveFullname(LVElement *BaseType, StringRef Name) { // For the following sample code, // void *p; // some compilers do not generate an attribute for the associated type: // DW_TAG_variable // DW_AT_name 'p' // DW_AT_type $1 // ... // $1: DW_TAG_pointer_type // ... // For those cases, generate the implicit 'void' type. StringRef BaseTypename = BaseType ? BaseType->getName() : emptyString(); bool GetBaseTypename = false; bool UseBaseTypename = true; bool UseNameText = true; switch (getTag()) { case dwarf::DW_TAG_pointer_type: // "*"; if (!BaseType) BaseTypename = typeVoid(); break; case dwarf::DW_TAG_const_type: // "const" case dwarf::DW_TAG_ptr_to_member_type: // "*" case dwarf::DW_TAG_rvalue_reference_type: // "&&" case dwarf::DW_TAG_reference_type: // "&" case dwarf::DW_TAG_restrict_type: // "restrict" case dwarf::DW_TAG_volatile_type: // "volatile" case dwarf::DW_TAG_unaligned: // "unaligned" break; case dwarf::DW_TAG_base_type: case dwarf::DW_TAG_compile_unit: case dwarf::DW_TAG_class_type: case dwarf::DW_TAG_enumerator: case dwarf::DW_TAG_namespace: case dwarf::DW_TAG_skeleton_unit: case dwarf::DW_TAG_structure_type: case dwarf::DW_TAG_union_type: case dwarf::DW_TAG_unspecified_type: case dwarf::DW_TAG_GNU_template_parameter_pack: GetBaseTypename = true; break; case dwarf::DW_TAG_array_type: case dwarf::DW_TAG_call_site: case dwarf::DW_TAG_entry_point: case dwarf::DW_TAG_enumeration_type: case dwarf::DW_TAG_GNU_call_site: case dwarf::DW_TAG_imported_module: case dwarf::DW_TAG_imported_declaration: case dwarf::DW_TAG_inlined_subroutine: case dwarf::DW_TAG_label: case dwarf::DW_TAG_subprogram: case dwarf::DW_TAG_subrange_type: case dwarf::DW_TAG_subroutine_type: case dwarf::DW_TAG_typedef: GetBaseTypename = true; UseBaseTypename = false; break; case dwarf::DW_TAG_template_type_parameter: case dwarf::DW_TAG_template_value_parameter: UseBaseTypename = false; break; case dwarf::DW_TAG_GNU_template_template_param: break; case dwarf::DW_TAG_catch_block: case dwarf::DW_TAG_lexical_block: case dwarf::DW_TAG_try_block: UseNameText = false; break; default: llvm_unreachable("Invalid type."); return; break; } // Overwrite if no given value. 'Name' is empty when resolving for scopes // and symbols. In the case of types, it represents the type base name. if (Name.empty() && GetBaseTypename) Name = getName(); // Concatenate the elements to get the full type name. // Type will be: base_parent + pre + base + parent + post. std::string Fullname; if (UseNameText && Name.size()) Fullname.append(std::string(Name)); if (UseBaseTypename && BaseTypename.size()) { if (UseNameText && Name.size()) Fullname.append(" "); Fullname.append(std::string(BaseTypename)); } // For a better and consistent layout, check if the generated name // contains double space sequences. assert((Fullname.find(" ", 0) == std::string::npos) && "Extra double spaces in name."); LLVM_DEBUG({ dbgs() << "Fullname = '" << Fullname << "'\n"; }); setName(Fullname); } void LVElement::setFile(LVElement *Reference) { if (!options().getAttributeAnySource()) return; // At this point, any existing reference to another element, have been // resolved and the file ID extracted from the DI entry. if (Reference) setFileLine(Reference); // The file information is used to show the source file for any element // and display any new source file in relation to its parent element. // a) Elements that are not inlined. // - We record the DW_AT_decl_line and DW_AT_decl_file. // b) Elements that are inlined. // - We record the DW_AT_decl_line and DW_AT_decl_file. // - We record the DW_AT_call_line and DW_AT_call_file. // For both cases, we use the DW_AT_decl_file value to detect any changes // in the source filename containing the element. Changes on this value // indicates that the element being printed is not contained in the // previous printed filename. // The source files are indexed starting at 0, but DW_AT_decl_file defines // that 0 means no file; a value of 1 means the 0th entry. size_t Index = 0; // An element with no source file information will use the reference // attribute (DW_AT_specification, DW_AT_abstract_origin, DW_AT_extension) // to update its information. if (getIsFileFromReference() && Reference) { Index = Reference->getFilenameIndex(); if (Reference->getInvalidFilename()) setInvalidFilename(); setFilenameIndex(Index); return; } // The source files are indexed starting at 0, but DW_AT_decl_file // defines that 0 means no file; a value of 1 means the 0th entry. Index = getFilenameIndex(); if (Index) { StringRef Filename = getReader().getFilename(this, Index); Filename.size() ? setFilename(Filename) : setInvalidFilename(); } } LVScope *LVElement::traverseParents(LVScopeGetFunction GetFunction) const { LVScope *Parent = getParentScope(); while (Parent && !(Parent->*GetFunction)()) Parent = Parent->getParentScope(); return Parent; } LVScope *LVElement::getFunctionParent() const { return traverseParents(&LVScope::getIsFunction); } LVScope *LVElement::getCompileUnitParent() const { return traverseParents(&LVScope::getIsCompileUnit); } // Resolve the qualified name to include the parent hierarchy names. void LVElement::resolveQualifiedName() { if (!getIsReferencedType() || isBase() || getQualifiedResolved() || !getIncludeInPrint()) return; std::string Name; // Get the qualified name, excluding the Compile Unit. LVScope *Parent = getParentScope(); if (Parent && !Parent->getIsRoot()) { while (Parent && !Parent->getIsCompileUnit()) { Name.insert(0, "::"); if (Parent->isNamed()) Name.insert(0, std::string(Parent->getName())); else { std::string Temp; Parent->generateName(Temp); Name.insert(0, Temp); } Parent = Parent->getParentScope(); } } if (Name.size()) { setQualifiedName(Name); setQualifiedResolved(); } LLVM_DEBUG({ dbgs() << "Offset: " << hexSquareString(getOffset()) << ", Kind: " << formattedKind(kind()) << ", Name: " << formattedName(getName()) << ", QualifiedName: " << formattedName(Name) << "\n"; }); } bool LVElement::referenceMatch(const LVElement *Element) const { return (getHasReference() && Element->getHasReference()) || (!getHasReference() && !Element->getHasReference()); } bool LVElement::equals(const LVElement *Element) const { // The minimum factors that must be the same for an equality are: // line number, level, name, qualified name and filename. LLVM_DEBUG({ dbgs() << "\n[Element::equals]\n"; if (options().getAttributeOffset()) { dbgs() << "Reference: " << hexSquareString(getOffset()) << "\n"; dbgs() << "Target : " << hexSquareString(Element->getOffset()) << "\n"; } dbgs() << "Reference: " << "Kind = " << formattedKind(kind()) << ", " << "Name = " << formattedName(getName()) << ", " << "Qualified = " << formattedName(getQualifiedName()) << "\n" << "Target : " << "Kind = " << formattedKind(Element->kind()) << ", " << "Name = " << formattedName(Element->getName()) << ", " << "Qualified = " << formattedName(Element->getQualifiedName()) << "\n" << "Reference: " << "NameIndex = " << getNameIndex() << ", " << "QualifiedNameIndex = " << getQualifiedNameIndex() << ", " << "FilenameIndex = " << getFilenameIndex() << "\n" << "Target : " << "NameIndex = " << Element->getNameIndex() << ", " << "QualifiedNameIndex = " << Element->getQualifiedNameIndex() << ", " << "FilenameIndex = " << Element->getFilenameIndex() << "\n"; }); if ((getLineNumber() != Element->getLineNumber()) || (getLevel() != Element->getLevel())) return false; if ((getQualifiedNameIndex() != Element->getQualifiedNameIndex()) || (getNameIndex() != Element->getNameIndex()) || (getFilenameIndex() != Element->getFilenameIndex())) return false; if (!getType() && !Element->getType()) return true; if (getType() && Element->getType()) return getType()->equals(Element->getType()); return false; } // Print the FileName Index. void LVElement::printFileIndex(raw_ostream &OS, bool Full) const { if (options().getPrintFormatting() && options().getAttributeAnySource() && getFilenameIndex()) { // Check if there is a change in the File ID sequence. size_t Index = getFilenameIndex(); if (options().changeFilenameIndex(Index)) { // Just to keep a nice layout. OS << "\n"; printAttributes(OS, /*Full=*/false); OS << " {Source} "; if (getInvalidFilename()) OS << format("[0x%08x]\n", Index); else OS << formattedName(getPathname()) << "\n"; } } } void LVElement::printReference(raw_ostream &OS, bool Full, LVElement *Parent) const { if (options().getPrintFormatting() && options().getAttributeReference()) printAttributes(OS, Full, "{Reference} ", Parent, referenceAsString(getLineNumber(), /*Spaces=*/false), /*UseQuotes=*/false, /*PrintRef=*/true); } void LVElement::printLinkageName(raw_ostream &OS, bool Full, LVElement *Parent) const { if (options().getPrintFormatting() && options().getAttributeLinkage()) { printAttributes(OS, Full, "{Linkage} ", Parent, getLinkageName(), /*UseQuotes=*/true, /*PrintRef=*/false); } } void LVElement::printLinkageName(raw_ostream &OS, bool Full, LVElement *Parent, LVScope *Scope) const { if (options().getPrintFormatting() && options().getAttributeLinkage()) { LVSectionIndex SectionIndex = getReader().getSectionIndex(Scope); std::string Text = (Twine(" 0x") + Twine::utohexstr(SectionIndex) + Twine(" '") + Twine(getLinkageName()) + Twine("'")) .str(); printAttributes(OS, Full, "{Linkage} ", Parent, Text, /*UseQuotes=*/false, /*PrintRef=*/false); } }
3866a16f11b506576b00b0933307d4d432724c80
a077eb51ff18df52d741d6c9ba9a5003673415df
/cpp/functions/helpers/get_printInstanceName.cc
067641e942681458c1eb2415065a4e06935d75fc
[ "MIT" ]
permissive
michieluithetbroek/A-MDVRP
d4a5f2f4e742c70c9cebd7dccde9837b1f718a2f
f378333e21b874e1cfad1333df5d47dec8c7b13e
refs/heads/master
2022-04-30T19:55:40.080660
2022-03-29T15:19:58
2022-03-29T15:19:58
241,376,430
43
13
null
null
null
null
UTF-8
C++
false
false
1,038
cc
get_printInstanceName.cc
#include "./../../main.ih" string getPrintInstanceName(int n, int m, int rep) { string instName; if (P_TYPE == PROBLEMTYPE::MDATSP) instName += "A-MDTSP"; else if (P_TYPE == PROBLEMTYPE::MDAMTSP) instName += "A-MDmTSP"; else if (P_TYPE == PROBLEMTYPE::MDACVRP) instName += "A-MDCVRP"; else if (P_TYPE == PROBLEMTYPE::ACLRP) instName += "A-CLRP"; else throw string("Unknown instance type (getPrintInstanceName.cc)"); instName += "_" + to_string(n) + "_" + to_string(m) + "_" + to_string(rep); return instName; } string getPrintInstanceName() { string instName; if (P_TYPE == PROBLEMTYPE::MDATSP) instName += "A-MDTSP"; else if (P_TYPE == PROBLEMTYPE::MDAMTSP) instName += "A-MDmTSP"; else if (P_TYPE == PROBLEMTYPE::MDACVRP) instName += "A-MDCVRP"; else if (P_TYPE == PROBLEMTYPE::ACLRP) instName += "A-CLRP"; else throw string("Unknown instance type (getPrintInstanceName.cc)"); return instName; }
27e4151f0adfacb61d919e05af39a809cebab85d
0c9c8af5dd109d5458d5d9e95df33c5806a057a7
/src/test.cpp
4a4e4b1dac2824c477edf44ec1a0f09fbd33321e
[ "MIT" ]
permissive
tairaO/CarND-Kidnapped-Vehicle-Project
ebd363afebcaf1e02dc51643b8b2cbcca3ff4772
77ddb953d34348ead50c97d135eb7fb8b0f5da71
refs/heads/master
2020-03-27T08:54:12.110462
2018-08-27T13:12:35
2018-08-27T13:12:35
146,296,790
0
0
null
null
null
null
UTF-8
C++
false
false
1,464
cpp
test.cpp
#include <uWS/uWS.h> #include <iostream> #include "json.hpp" #include <math.h> #include "particle_filter.h" using namespace std; int main(){ //Set up parameters here double delta_t = 0.1; // Time elapsed between measurements [sec] double sensor_range = 50; // Sensor range [m] double sigma_pos [3] = {0.3, 0.3, 0.01}; // GPS measurement uncertainty [x [m], y [m], theta [rad]] double sigma_landmark [2] = {0.3, 0.3}; // Landmark measurement uncertainty [x [m], y [m]] // Sense noisy position data from the simulator double sense_x = 0.0; double sense_y = 0.0; double sense_theta = 0.0; // Create particle filter ParticleFilter pf; // Read map data Map map; if (!read_map_data("../data/map_data.txt", map)) { cout << "Error: Could not open map file" << endl; return -1; } pf.init(sense_x, sense_y, sense_theta, sigma_pos); double previous_velocity = 0; // double previous_yawrate = M_PI / 8; double previous_yawrate = 0.0001; pf.prediction(delta_t, sigma_pos, previous_velocity, previous_yawrate); // Update the weights and resample vector<LandmarkObs> noisy_observations; LandmarkObs obs; obs.x = 17; obs.y = -4.5; noisy_observations.push_back(obs); obs.x = -7.1; obs.y = -34; noisy_observations.push_back(obs); obs.x = 29; obs.y = -39; noisy_observations.push_back(obs); pf.updateWeights(sensor_range, sigma_landmark, noisy_observations, map); pf.resample(); return 0; }
4e9af4b9e40dfe968b0d88dd8d678442dd944f0c
4503b4ec29e9a30d26c433bac376f2bddaefd9e5
/XtreamToolkit/v16.4.0/Source/CommandBars/XTPFrameWnd.cpp
13363508ac635965ad9c7604cda76c7bf5a56f34
[]
no_license
SwunZH/ecocommlibs
0a872e0bbecbb843a0584fb787cf0c5e8a2a270b
4cff09ff1e479f5f519f207262a61ee85f543b3a
refs/heads/master
2021-01-25T12:02:39.067444
2018-02-23T07:04:43
2018-02-23T07:04:43
123,447,012
1
0
null
2018-03-01T14:37:53
2018-03-01T14:37:53
null
UTF-8
C++
false
false
2,257
cpp
XTPFrameWnd.cpp
// XTPFrameWnd.cpp : implementation for the CXTPFrameWnd and CXTPMDIFrameWnd classes. // // This file is a part of the XTREME COMMANDBARS MFC class library. // (c)1998-2013 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Resource.h" #include <Common/XTPSystemHelpers.h> #include <Common/XTPHookManager.h> #include <Common/XTPDrawHelpers.h> #include "XTPCommandBarsDefines.h" #include "XTPCommandBar.h" #include "XTPToolBar.h" #include "XTPCommandBars.h" #include "XTPShortcutManager.h" #include "XTPControl.h" #include "XTPControlEdit.h" #include "XTPFrameWnd.h" // CXTPFrameWnd IMPLEMENT_DYNCREATE(CXTPFrameWnd, CFrameWnd) CXTPFrameWnd::CXTPFrameWnd() { } // CXTPMDIFrameWnd IMPLEMENT_DYNCREATE(CXTPMDIFrameWnd, CMDIFrameWnd) CXTPMDIFrameWnd::CXTPMDIFrameWnd() { } extern const UINT XTP_WM_UPDATE_MDI_CHILD_THEME = RegisterWindowMessage(_T("XTP_WM_UPDATE_MDI_CHILD_THEME")); void CXTPMDIFrameWnd::UpdateMDIChildrenTheme() { if (NULL != GetSafeHwnd()) { CWnd* pWnd = GetActiveFrame(); while (NULL != pWnd) { pWnd->SendMessage(XTP_WM_UPDATE_MDI_CHILD_THEME); pWnd = pWnd->GetNextWindow(); } } } BOOL CXTPMDIFrameWnd::OnCmdMsg( UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo) { if (nID >= XTP_ID_WORKSPACE_MOVEPREVIOUS && nID <= XTP_ID_WORKSPACE_NEWVERTICAL) { CWnd* pWnd = CWnd::FromHandlePermanent(m_hWndMDIClient); if (pWnd && pWnd->OnCmdMsg(nID, nCode, pExtra, pHandlerInfo)) return TRUE; } // then pump through normal frame return CMDIFrameWnd::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo); }
13cd32382a005024bf149040cb5942256e221dc0
4bf11a797dc9daa52b56b1f370c13171c34d856d
/solution/0008____String_to_Integer_(atoi).cpp
fa1630926e6fece5ef808549fe827adc42791cc7
[ "MIT" ]
permissive
jhinkoo331/leetcode
680635f6ef5cbe701e4c345fe3e3f90d0d88d3b3
2ef6886575e0004097815fe38ed2cfafe0b7aa6c
refs/heads/master
2023-06-24T11:50:21.403165
2023-06-19T16:51:32
2023-06-19T16:51:32
231,519,913
1
0
null
2020-07-19T13:50:43
2020-01-03T05:43:05
C++
UTF-8
C++
false
false
1,186
cpp
0008____String_to_Integer_(atoi).cpp
#include <string> using std::string; class Solution { public: int myAtoi(string str) { return _1(str); } private: static const int k = 0x7fffffff / 10; /** * @perf: [4ms, 19] * @time: O(n), where n is the length of the string * @space: constant * @param str * @return int */ int _1(string str){ int i = 0; //* skip prevailing whitespaces while(i < str.size() && str[i] == ' ') i++; //* check optional sign flag int is_neg = false; if(i < str.size() && str[i] == '-') is_neg = true; if(i < str.size() && (str[i] == '-' || str[i] == '+')) i++; unsigned value = 0; //* while str[i] is valid while(i < str.size() && isdigit(str[i])){ //* value * 10 would renders int overflow if(value > k) return is_neg ? 0x80000000 : 0x7fffffff; //* update value value *= 10; value += str[i] - '0'; //* check overflow if(is_neg && value >= 0x80000000) return 0x80000000; else if(!is_neg && value >= 0x7fffffff) return 0x7fffffff; i++; } //* get the final answer int ans = is_neg ? -value : value; return ans; } }; int main(){ Solution sln; sln.myAtoi("-91283472332"); sln.myAtoi("42"); return 0; }
516a82c277e8a94598612db6e9a43e812b1de9cd
e28f2a1e39f48015f5ec62b71c3ec5a93ad5573e
/oj/hdoj/hdoj_2602.cpp
f0837a5fef813595e2a8787ad6ab479cc59bb877
[]
no_license
james47/acm
22678d314bcdc3058f235443281a5b4abab2660d
09ad1bfc10cdd0af2d56169a0bdb8e0f22cba1cb
refs/heads/master
2020-12-24T16:07:28.284304
2016-03-13T15:16:48
2016-03-13T15:16:48
38,529,014
0
0
null
null
null
null
UTF-8
C++
false
false
624
cpp
hdoj_2602.cpp
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; int N, V, T; int dp[1100], v[1100], w[1100]; int main() { scanf("%d", &T); while(T--) { scanf("%d%d", &N, &V); for (int i = 0; i < N; i++) scanf("%d", v+i); for (int i = 0; i < N; i++) scanf("%d", w+i); memset(dp, -1, sizeof(dp)); dp[0] = 0; for (int i = 0; i < N; i++) for (int j = V; j >= w[i]; j--){ int tmp = j - w[i]; if (dp[tmp] == -1) continue; dp[j] = max(dp[j], dp[tmp] + v[i]); } int ans = 0; for (int i = 0; i <= V; i++) if (dp[i] > ans) ans = dp[i]; printf("%d\n", ans); } return 0; }
ee979b3bf8c0ec2d156ee8c06510b89503f09212
47cd0d53bec9ecf1d8a57eee587c6782493aa7e1
/main.cpp
578ef6fe51f0b5b458bdad3fa669b35061b42e43
[]
no_license
asilardo/-CPP-Polymorphism-Demo-4-in-1-2-Variable-Arithmetic-Calculator
fad6105c85c6476af8f3d79e86fb9dc755e2b903
ddb7a7fb416e6800d7442d23b7264511e687dc5e
refs/heads/master
2022-11-28T10:10:49.344605
2020-07-28T02:23:12
2020-07-28T02:23:12
283,069,160
2
0
null
null
null
null
UTF-8
C++
false
false
1,895
cpp
main.cpp
#include <iostream> using namespace std; class calculator { protected: int num1, num2; public: calculator(int n1 = 0, int n2 = 0) { num1 = n1; num2 = n2; } virtual int calc() //used for dynamic linkage { cout << "Parent class: " << endl; return 0; } }; class addition : public calculator { public: addition(int n1 = 0, int n2 = 0) : calculator(n1 , n2) {} int calc() { cout << "Sum = "; return (num1 + num2); } }; class subtraction : public calculator { public: subtraction(int n1 = 0, int n2 = 0) : calculator(n1, n2) {} int calc() { cout << endl << "Difference = "; return (num1 - num2); } }; class multiplication : public calculator { public: multiplication(int n1 = 0, int n2 = 0) : calculator(n1, n2) {} int calc() { cout << endl << "Product = "; return (num1 * num2); } }; class division : public calculator { public: division(int n1 = 0, int n2 = 0) : calculator(n1, n2) {} int calc() { cout << endl << "Quotient = "; return (num1 / num2); } }; int main() { calculator* c; int input1, input2; char again = 'Y'; cout << "4-IN-1 2-VARIABLE ARITHMETIC CALCULATOR" << endl << "(Demo of Polymorphism)" << endl << endl; while (again == 'y' || again == 'Y') { cout << "Enter first input: "; cin >> input1; cout << "Enter second input: "; cin >> input2; cout << endl; addition add(input1, input2); subtraction sub(input1, input2); multiplication mult(input1, input2); division div(input1, input2); c = &add; cout << c->calc(); c = &sub; cout << c->calc(); c = &mult; cout << c->calc(); c = &div; cout << c->calc() << endl; cout << endl << endl << "Go again? (y/n): "; cin >> again; cout << "______________________________________________________________________________________________________________" << endl; cout << endl << endl; } return 0; }
dbea0de3334eece142e277629c36ff26fb71a848
2ab7bf87d98fd7e367b1f3c3190573b45b9fb497
/XQ_Muggle/evaluate.cpp
e76b5802b3d6527400674db96066054f40a92c78
[]
no_license
NewCityLetter/TJCS-XQ_Muggle
6764e426581863ead3fa4ff77da7e7b7bebd963b
4562ed124be23c9d5a1998fabd92ea2236ad316b
refs/heads/main
2023-05-15T00:52:33.673373
2021-06-07T05:52:25
2021-06-07T05:52:25
349,408,741
5
0
null
null
null
null
GB18030
C++
false
false
21,341
cpp
evaluate.cpp
#include "base.h" #include "board.h" const int TOTAL_MIDGAME_VALUE = 66; const int TOTAL_ADVANCED_VALUE = 4; const int TOTAL_ATTACK_VALUE = 8; const int ADVISOR_BISHOP_ATTACKLESS_VALUE = 80; const int TOTAL_ADVISOR_LEAKAGE = 80; int32 AdvancedVal; //先行权因素的分值 int32 redValueTable[7][256]; //计算出的子力价值表 int32 blackValueTable[7][256]; //计算出的子力价值表 int32 HollowThreatVal[16]; int32 RedBottomThreatVal[16], BlackBottomThreatVal[16]; int32 BlackAdvisorLeakageVal, RedAdvisorLeakageVal;//缺士怕双车的罚分 extern boardStruct board; inline bool RED_HALF(int sq) { return (sq & 0x80) != 0; } inline bool BLACK_HALF(int sq) { return (sq & 0x80) == 0; } // 1. 开中局、有进攻机会的帅(将)和兵(卒) static const int32 KingPawnMidgameAttackingVal[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 11, 13, 11, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 39, 49, 69, 84, 89, 84, 69, 49, 39, 0, 0, 0, 0, 0, 0, 0, 39, 49, 64, 74, 74, 74, 64, 49, 39, 0, 0, 0, 0, 0, 0, 0, 39, 46, 54, 59, 61, 59, 54, 46, 39, 0, 0, 0, 0, 0, 0, 0, 29, 37, 41, 54, 59, 54, 41, 37, 29, 0, 0, 0, 0, 0, 0, 0, 7, 0, 13, 0, 16, 0, 13, 0, 7, 0, 0, 0, 0, 0, 0, 0, 7, 0, 7, 0, 15, 0, 7, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 15, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 2. 开中局、没有进攻机会的帅(将)和兵(卒) static const int32 KingPawnMidgameAttacklessVal[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 11, 13, 11, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 19, 24, 34, 42, 44, 42, 34, 24, 19, 0, 0, 0, 0, 0, 0, 0, 19, 24, 32, 37, 37, 37, 32, 24, 19, 0, 0, 0, 0, 0, 0, 0, 19, 23, 27, 29, 30, 29, 27, 23, 19, 0, 0, 0, 0, 0, 0, 0, 14, 18, 20, 27, 29, 27, 20, 18, 14, 0, 0, 0, 0, 0, 0, 0, 7, 0, 13, 0, 16, 0, 13, 0, 7, 0, 0, 0, 0, 0, 0, 0, 7, 0, 7, 0, 15, 0, 7, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 15, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 3. 残局、有进攻机会的帅(将)和兵(卒) static const int32 KingPawnEndgameAttackingVal[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 15, 15, 15, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 50, 55, 60, 85,100, 85, 60, 55, 50, 0, 0, 0, 0, 0, 0, 0, 65, 70, 70, 75, 75, 75, 70, 70, 65, 0, 0, 0, 0, 0, 0, 0, 75, 80, 80, 80, 80, 80, 80, 80, 75, 0, 0, 0, 0, 0, 0, 0, 70, 70, 65, 70, 70, 70, 65, 70, 70, 0, 0, 0, 0, 0, 0, 0, 45, 0, 40, 45, 45, 45, 40, 0, 45, 0, 0, 0, 0, 0, 0, 0, 40, 0, 35, 40, 40, 40, 35, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 15, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 13, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 11, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 4. 残局、没有进攻机会的帅(将)和兵(卒) static const int32 KingPawnEndgameAttacklessVal[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 15, 15, 15, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 15, 20, 45, 60, 45, 20, 15, 10, 0, 0, 0, 0, 0, 0, 0, 25, 30, 30, 35, 35, 35, 30, 30, 25, 0, 0, 0, 0, 0, 0, 0, 35, 40, 40, 45, 45, 45, 40, 40, 35, 0, 0, 0, 0, 0, 0, 0, 25, 30, 30, 35, 35, 35, 30, 30, 25, 0, 0, 0, 0, 0, 0, 0, 25, 0, 25, 25, 25, 25, 25, 0, 25, 0, 0, 0, 0, 0, 0, 0, 20, 0, 20, 20, 20, 20, 20, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 13, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 12, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 11, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 5. 没受威胁的仕(士)和相(象) static const int32 AdvisorBishopThreatlessVal[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 0, 0, 20, 23, 20, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 20, 0, 20, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 5. 受到威胁的仕(士)和相(象) static const int32 AdvisorBishopThreatenedVal[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40, 0, 0, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, 0, 0, 40, 43, 40, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 43, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40, 40, 0, 40, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 6. 开中局的马 static const int32 KnightMidgameVal[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 90, 90, 90, 96, 90, 96, 90, 90, 90, 0, 0, 0, 0, 0, 0, 0, 90, 96,103, 97, 94, 97,103, 96, 90, 0, 0, 0, 0, 0, 0, 0, 92, 98, 99,103, 99,103, 99, 98, 92, 0, 0, 0, 0, 0, 0, 0, 93,108,100,107,100,107,100,108, 93, 0, 0, 0, 0, 0, 0, 0, 90,100, 99,103,104,103, 99,100, 90, 0, 0, 0, 0, 0, 0, 0, 90, 98,101,102,103,102,101, 98, 90, 0, 0, 0, 0, 0, 0, 0, 92, 94, 98, 95, 98, 95, 98, 94, 92, 0, 0, 0, 0, 0, 0, 0, 93, 92, 94, 95, 92, 95, 94, 92, 93, 0, 0, 0, 0, 0, 0, 0, 85, 90, 92, 93, 78, 93, 92, 90, 85, 0, 0, 0, 0, 0, 0, 0, 88, 85, 90, 88, 90, 88, 90, 85, 88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 7. 残局的马 static const int32 KnightEndgameVal[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 92, 94, 96, 96, 96, 96, 96, 94, 92, 0, 0, 0, 0, 0, 0, 0, 94, 96, 98, 98, 98, 98, 98, 96, 94, 0, 0, 0, 0, 0, 0, 0, 96, 98,100,100,100,100,100, 98, 96, 0, 0, 0, 0, 0, 0, 0, 96, 98,100,100,100,100,100, 98, 96, 0, 0, 0, 0, 0, 0, 0, 96, 98,100,100,100,100,100, 98, 96, 0, 0, 0, 0, 0, 0, 0, 94, 96, 98, 98, 98, 98, 98, 96, 94, 0, 0, 0, 0, 0, 0, 0, 94, 96, 98, 98, 98, 98, 98, 96, 94, 0, 0, 0, 0, 0, 0, 0, 92, 94, 96, 96, 96, 96, 96, 94, 92, 0, 0, 0, 0, 0, 0, 0, 90, 92, 94, 92, 92, 92, 94, 92, 90, 0, 0, 0, 0, 0, 0, 0, 88, 90, 92, 90, 90, 90, 92, 90, 88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 8. 开中局的车 static const int32 RookMidgameVal[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,206,208,207,213,214,213,207,208,206, 0, 0, 0, 0, 0, 0, 0,206,212,209,216,233,216,209,212,206, 0, 0, 0, 0, 0, 0, 0,206,208,207,214,216,214,207,208,206, 0, 0, 0, 0, 0, 0, 0,206,213,213,216,216,216,213,213,206, 0, 0, 0, 0, 0, 0, 0,208,211,211,214,215,214,211,211,208, 0, 0, 0, 0, 0, 0, 0,208,212,212,214,215,214,212,212,208, 0, 0, 0, 0, 0, 0, 0,204,209,204,212,214,212,204,209,204, 0, 0, 0, 0, 0, 0, 0,198,208,204,212,212,212,204,208,198, 0, 0, 0, 0, 0, 0, 0,200,208,206,212,200,212,206,208,200, 0, 0, 0, 0, 0, 0, 0,194,206,204,212,200,212,204,206,194, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 9. 残局的车 static const int32 RookEndgameVal[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,182,182,182,184,186,184,182,182,182, 0, 0, 0, 0, 0, 0, 0,184,184,184,186,190,186,184,184,184, 0, 0, 0, 0, 0, 0, 0,182,182,182,184,186,184,182,182,182, 0, 0, 0, 0, 0, 0, 0,180,180,180,182,184,182,180,180,180, 0, 0, 0, 0, 0, 0, 0,180,180,180,182,184,182,180,180,180, 0, 0, 0, 0, 0, 0, 0,180,180,180,182,184,182,180,180,180, 0, 0, 0, 0, 0, 0, 0,180,180,180,182,184,182,180,180,180, 0, 0, 0, 0, 0, 0, 0,180,180,180,182,184,182,180,180,180, 0, 0, 0, 0, 0, 0, 0,180,180,180,182,184,182,180,180,180, 0, 0, 0, 0, 0, 0, 0,180,180,180,182,184,182,180,180,180, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 10. 开中局的炮 static const int32 CannonMidgameVal[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,100,100, 96, 91, 90, 91, 96,100,100, 0, 0, 0, 0, 0, 0, 0, 98, 98, 96, 92, 89, 92, 96, 98, 98, 0, 0, 0, 0, 0, 0, 0, 97, 97, 96, 91, 92, 91, 96, 97, 97, 0, 0, 0, 0, 0, 0, 0, 96, 99, 99, 98,100, 98, 99, 99, 96, 0, 0, 0, 0, 0, 0, 0, 96, 96, 96, 96,100, 96, 96, 96, 96, 0, 0, 0, 0, 0, 0, 0, 95, 96, 99, 96,100, 96, 99, 96, 95, 0, 0, 0, 0, 0, 0, 0, 96, 96, 96, 96, 96, 96, 96, 96, 96, 0, 0, 0, 0, 0, 0, 0, 97, 96,100, 99,101, 99,100, 96, 97, 0, 0, 0, 0, 0, 0, 0, 96, 97, 98, 98, 98, 98, 98, 97, 96, 0, 0, 0, 0, 0, 0, 0, 96, 96, 97, 99, 99, 99, 97, 96, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 11. 残局的炮 static const int32 CannonEndgameVal[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,100,100,100,100,100,100,100,100,100, 0, 0, 0, 0, 0, 0, 0,100,100,100,100,100,100,100,100,100, 0, 0, 0, 0, 0, 0, 0,100,100,100,100,100,100,100,100,100, 0, 0, 0, 0, 0, 0, 0,100,100,100,102,104,102,100,100,100, 0, 0, 0, 0, 0, 0, 0,100,100,100,102,104,102,100,100,100, 0, 0, 0, 0, 0, 0, 0,100,100,100,102,104,102,100,100,100, 0, 0, 0, 0, 0, 0, 0,100,100,100,102,104,102,100,100,100, 0, 0, 0, 0, 0, 0, 0,100,100,100,102,104,102,100,100,100, 0, 0, 0, 0, 0, 0, 0,100,100,100,104,106,104,100,100,100, 0, 0, 0, 0, 0, 0, 0,100,100,100,104,106,104,100,100,100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 空头炮威胁分值,行号 0-16 const int32 HOLLOW_THREAT[16] = { 0, 0, 0, 0, 0, 0, 60, 65, 70, 75, 80, 80, 80, 0, 0, 0 }; //沉底炮的威胁分值 列号 0-16 const int32 BOTTOM_THREAT[16] = { 0, 0, 0, 40, 30, 0, 0, 0, 0, 0, 30, 40, 0, 0, 0, 0 }; int32 PawnPiecesAttackingVal[256], PawnPiecesAttacklessVal[256]; void PreEvaluate() { int midgameValue = 0;//判断局势 int blackSimpleValue = 0, redSimpleValue = 0;//双方轻子数量 //计算当前子力情况 //方法是计算各种棋子的数量,按照车=6、马炮=3、其它=1相加,顺便计算轻子数量 for (int i = 16; i < 48; i++) { int chessPiece = GETTYPE(i); switch (chessPiece) { case 0: case 1: case 2: case 6: midgameValue += (board.currentPosition[i] == 0 ? 0 : 1);//其余棋子加1 break; case 3://马 case 5://炮 if (i < 32 && board.currentPosition[i] != 0) redSimpleValue++; else if (board.currentPosition[i] != 0) blackSimpleValue++; midgameValue += (board.currentPosition[i] == 0 ? 0 : 3);//马和炮加3 break; case 4://车 midgameValue += (board.currentPosition[i] == 0 ? 0 : 6);//车加6 if (i < 32 && board.currentPosition[i] != 0) redSimpleValue += 2; else if (board.currentPosition[i] != 0) blackSimpleValue += 2; break; default: break; } } // 使用二次函数,子力很少时才认为接近残局 midgameValue = (2 * TOTAL_MIDGAME_VALUE - midgameValue) * midgameValue / TOTAL_MIDGAME_VALUE; AdvancedVal = (TOTAL_ADVANCED_VALUE * midgameValue + TOTAL_ADVANCED_VALUE / 2) / TOTAL_MIDGAME_VALUE; //printf("midgame=%d advance=%d\n", midgameValue, AdvancedVal); //std::cout << "midgamevalue:" << midgameValue << " advanced:" << AdvancedVal << " "; //计算子力价值表 for (int sq = 0; sq < 256; sq++) { if (IN_BOARD(sq)) { redValueTable[0][sq] = blackValueTable[0][SQUARE_FLIP(sq)] = (int32) ((KingPawnMidgameAttackingVal[sq] * midgameValue + KingPawnEndgameAttackingVal[sq] * (TOTAL_MIDGAME_VALUE - midgameValue)) / TOTAL_MIDGAME_VALUE); redValueTable[3][sq] = blackValueTable[3][SQUARE_FLIP(sq)] = (int32) ((KnightMidgameVal[sq] * midgameValue + KnightEndgameVal[sq] * (TOTAL_MIDGAME_VALUE - midgameValue)) / TOTAL_MIDGAME_VALUE); redValueTable[4][sq] = blackValueTable[4][SQUARE_FLIP(sq)] = (int32) ((RookMidgameVal[sq] * midgameValue + RookEndgameVal[sq] * (TOTAL_MIDGAME_VALUE - midgameValue)) / TOTAL_MIDGAME_VALUE); redValueTable[5][sq] = blackValueTable[5][SQUARE_FLIP(sq)] = (int32) ((CannonMidgameVal[sq] * midgameValue + CannonEndgameVal[sq] * (TOTAL_MIDGAME_VALUE - midgameValue)) / TOTAL_MIDGAME_VALUE); PawnPiecesAttackingVal[sq] = redValueTable[0][sq]; PawnPiecesAttacklessVal[sq] = (int32) ((KingPawnMidgameAttacklessVal[sq] * midgameValue + KingPawnEndgameAttacklessVal[sq] * (TOTAL_MIDGAME_VALUE - midgameValue)) / TOTAL_MIDGAME_VALUE); } } // 判断各方是否处于进攻状态,方法是计算各种过河棋子的数量,按照车马2炮兵1相加 int redAttacks = 0, blackAttacks = 0; for (int i = SELF_SIDE(0) + KNIGHT_FROM; i <= SELF_SIDE(0) + PAWN_TO; i++) { if (board.currentPosition[i] != 0 && BLACK_HALF(board.currentPosition[i])) { if (i <= SELF_SIDE(0) + ROOK_TO) redAttacks += 2; else redAttacks++; } } for (int i = SELF_SIDE(1) + KNIGHT_FROM; i <= SELF_SIDE(1) + PAWN_TO; i++) { if (board.currentPosition[i] != 0 && RED_HALF(board.currentPosition[i])) { if (i <= SELF_SIDE(1) + ROOK_TO) blackAttacks += 2; else blackAttacks++; } } // 如果本方轻子数比对方多,每多一个轻子(车算2个轻子)威胁值加2。威胁值最多不超过8 if (redSimpleValue > blackSimpleValue) redAttacks += (redSimpleValue - blackSimpleValue) * 2; else blackAttacks += (blackSimpleValue - redSimpleValue) * 2; redAttacks = redAttacks < TOTAL_ATTACK_VALUE ? redAttacks : TOTAL_ATTACK_VALUE; blackAttacks = blackAttacks < TOTAL_ATTACK_VALUE ? blackAttacks : TOTAL_ATTACK_VALUE; //std::cout << "redattack:" << redAttacks << " blackattack:" << blackAttacks << " "; //对空头炮、沉底炮的威胁分值做调整 for (int i = 0; i < 16; i++) { HollowThreatVal[i] = HOLLOW_THREAT[i] * (midgameValue + TOTAL_MIDGAME_VALUE) / (TOTAL_MIDGAME_VALUE * 2); RedBottomThreatVal[i] = BOTTOM_THREAT[i] * blackAttacks / TOTAL_ATTACK_VALUE; BlackBottomThreatVal[i] = BOTTOM_THREAT[i] * redAttacks / TOTAL_ATTACK_VALUE; } //计算缺士怕双车的罚分 BlackAdvisorLeakageVal = TOTAL_ADVISOR_LEAKAGE * redAttacks / TOTAL_ATTACK_VALUE; RedAdvisorLeakageVal = TOTAL_ADVISOR_LEAKAGE * blackAttacks / TOTAL_ATTACK_VALUE; //计算子力价值表 for (int sq = 0; sq < 256; sq++) { if (IN_BOARD(sq)) { redValueTable[1][sq] = redValueTable[2][sq] = (int32)((AdvisorBishopThreatenedVal[sq] * blackAttacks + (AdvisorBishopThreatlessVal[sq]) * (TOTAL_ATTACK_VALUE - blackAttacks)) / TOTAL_ATTACK_VALUE); blackValueTable[1][sq] = blackValueTable[2][sq] = (int32)((AdvisorBishopThreatenedVal[SQUARE_FLIP(sq)] * redAttacks + (AdvisorBishopThreatlessVal[SQUARE_FLIP(sq)]) * (TOTAL_ATTACK_VALUE - redAttacks)) / TOTAL_ATTACK_VALUE); redValueTable[6][sq] = (int32)((PawnPiecesAttackingVal[sq] * redAttacks + PawnPiecesAttacklessVal[sq] * (TOTAL_ATTACK_VALUE - redAttacks)) / TOTAL_ATTACK_VALUE); blackValueTable[6][sq] = (int32)((PawnPiecesAttackingVal[SQUARE_FLIP(sq)] * blackAttacks + PawnPiecesAttacklessVal[SQUARE_FLIP(sq)] * (TOTAL_ATTACK_VALUE - blackAttacks)) / TOTAL_ATTACK_VALUE); } } // 调整不受威胁方少掉的仕(士)相(象)分值 board.redVal = ADVISOR_BISHOP_ATTACKLESS_VALUE * (TOTAL_ATTACK_VALUE - blackAttacks) / TOTAL_ATTACK_VALUE; board.blackVal = ADVISOR_BISHOP_ATTACKLESS_VALUE * (TOTAL_ATTACK_VALUE - redAttacks) / TOTAL_ATTACK_VALUE; //std::cout<<"FUCK\n"; for(int i=16;i<32;i++) { int pos=board.currentPosition[i]; if(pos) board.redVal+=redValueTable[pieceTypes[i]][pos]; } for(int i=32;i<48;i++) { int pos=board.currentPosition[i]; if(pos) board.blackVal+=blackValueTable[pieceTypes[i]][pos]; } //std::cout << "redval:" << board.redVal << " blackval:" << board.blackVal << '\n'; }
73ae91a3f8ca98e2be800383e533b302e1234960
70a148273adf94c8a3305523585d6472b56247f7
/problems_1_lottery/lottery.cpp
9608d079fb474f2609fb2fbde215d5d8b64007f3
[]
no_license
xunter/yacup2020_algorithm
b1cbda758e2ffb8a6cdff22faa4a65429062a8f7
56d1791d50a7e7fcf36fd3cb04986eae5d468322
refs/heads/master
2022-12-24T22:56:44.736845
2020-10-02T19:25:56
2020-10-02T19:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,920
cpp
lottery.cpp
#include <stdio.h> #include <iostream> #include <vector> using namespace std; vector<string> split(const string& str, const string& delim); int main() { int luckyNums[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; string sLuckyNums, sTiraz, sTicketNums; vector<int*> ticketNumsArr; getline(cin, sLuckyNums); vector<string> sLuckyNumsTokens = split(sLuckyNums, " "); for (int i = 0; i < 10; i++) { luckyNums[i] = atoi(sLuckyNumsTokens[i].c_str()); } getline(cin, sTiraz); int tirazNum = atoi(sTiraz.c_str()); int n = 0; while (n++ < tirazNum) { getline(cin, sTicketNums); vector<string> tokenNumsArr = split(sTicketNums, " "); int *ticketNums = new int[6]; for (int i = 0; i < 6; i++) { ticketNums[i] = atoi(tokenNumsArr[i].c_str()); } ticketNumsArr.push_back(ticketNums); } vector<bool> ticketLuckyStatusArr; for (int i = 0; i < ticketNumsArr.size(); i++) { ticketLuckyStatusArr.push_back(false); int *ticketNums = ticketNumsArr[i]; int luckyCounter = 0; for (int j = 0; j < 6; j++) { bool luckyFound = false; for (int k = 0; k < 10; k++) { if (ticketNums[j] == luckyNums[k]) { luckyCounter++; } if (luckyCounter == 3) { luckyFound = true; ticketLuckyStatusArr[i] = true; break; } } if (luckyFound) { break; } } cout << (ticketLuckyStatusArr[i] ? "Lucky" : "Unlucky") << endl; delete ticketNums; } return 0; } vector<string> split(const string& str, const string& delim) { vector<string> tokens; size_t prev = 0, pos = 0; do { pos = str.find(delim, prev); if (pos == string::npos) pos = str.length(); string token = str.substr(prev, pos-prev); if (!token.empty()) tokens.push_back(token); prev = pos + delim.length(); } while (pos < str.length() && prev < str.length()); return tokens; } //https://stackoverflow.com/a/37454181/1487713
990ff57809ceea1cd365ca87ee0af8259dc315fd
cc324e4a74aeb8ed984fafbac87167a299625d23
/Algorithms/BinaryTreeIterativeTraversal.h
dbb7e020d0d76a928e8139dc5264057d0ed80fed
[]
no_license
narekhovsepian/DataStructure
fe5085029cdc428de5a741a350d7460608ca7087
40052e8176f576015f877b55e43f8f93a7e1ed7e
refs/heads/master
2020-03-07T23:14:22.461686
2018-12-02T20:39:26
2018-12-02T20:39:26
127,774,300
0
0
null
null
null
null
UTF-8
C++
false
false
1,852
h
BinaryTreeIterativeTraversal.h
#pragma once #include<iostream> namespace BinaryTreeIterativeTraversal { template<typename T> struct Node { T _info; Node<T> *_father, *_left, *_right; Node(const T& info = T()) : _info(info), _father(0), _left(0), _right(0) { } }; template<typename T> void PreorderIterative_NLR(Node<T> *tree) { if (tree == 0) return; Node<T> *vertex = tree, *father; while (1) { std::cout << vertex->_info << " "; if (vertex->_left) { vertex = vertex->_left; continue; } if (vertex->_right) { vertex = vertex->_right; continue; } for (father = vertex->_father; father != 0; vertex = father, father = vertex->_father) if (father->_left == vertex && father->_right != 0) break; if (father == 0) return; vertex = father->_right; } } template<typename T> void InorderIterative_LNR(Node<T> *tree) { if (tree == 0) return; Node<T> *vertex = tree, *father; while (1) { if (vertex->_left) { vertex = vertex->_left; continue; } std::cout << vertex->_info << " "; if (vertex->_right) { vertex = vertex->_right; continue; } for (father = vertex->_father; father != 0; vertex = father, father = vertex->_father) if (father->_left == vertex) { std::cout << father->_info << " "; if (father->_right) break; } if (father == 0) return; vertex = father->_right; } } /* template<typename Elem> void PostorderIterative_LRN(ExtendenNode<Elem> *tree) { if (tree == 0) return; ExtendenNode<Elem> *vertex = tree, *father; while (1) { if (vertex->_left) { vertex = vertex->_left; contiune; } if (vertex->_right) { vertex = vertex->_right; contiune; } std::cout << vertex->_info << " "; for (father = vertex->_father; father != 0; vertex = father, father = vertex->_father) if (father->_left == vertex) { } } } */ }
a2dcd8ba42b345e3ca313911b65104542aee8bf4
8271edfc6939415f8d49058a4d0f5a00c92aead6
/source/string.cpp
96baa91741b601d53c9b036256926c59be352707
[]
no_license
kdchambers/kpl
c4d813f1a0496b8b9dc8203979044a2f605b6b1c
4e54f35745468d9797c8e98b0edd5d7a7e93d071
refs/heads/master
2020-04-24T10:18:25.841478
2019-12-19T03:31:37
2019-12-19T03:31:37
171,889,899
0
0
null
null
null
null
UTF-8
C++
false
false
2,499
cpp
string.cpp
#include <kpl/string.h> namespace kpl { QString viewToString(kpl::StringView string) { kpl::Char tmp = *string.end(); kpl::Char* end = const_cast<kpl::Char*>(string.end()); *end = '\0'; QString result(string.begin()); result.append(tmp); *end = tmp; return result; } kpl::String trimEnd(const kpl::String& string, kpl::Char remove_char) { kpl::String result = string; kpl::String::const_reverse_iterator sentinal = string.rbegin(); u32 truncate = 0; for(kpl::String::const_reverse_iterator reverse_itr = result.rend(); reverse_itr != sentinal; reverse_itr++ ) { if(*reverse_itr != remove_char) { break; } truncate++; } result.truncate(string.size() - truncate); return result; } kpl::String& trimEndMut(kpl::String& string, kpl::Char remove_char) { kpl::String::reverse_iterator sentinal = string.rbegin(); u32 truncate = 0; for(kpl::String::reverse_iterator reverse_itr = string.rend(); reverse_itr != sentinal; reverse_itr++ ) { if(*reverse_itr != remove_char) { break; } truncate++; } string.truncate(string.size() - truncate); return string; } kpl::StringView stringToView(const kpl::String& string) { u32 size = string.size(); return kpl::StringView { string.data(), size }; } kpl::StringView forwardUntilView(kpl::StringView string, const kpl::Char sentinal) { return kpl::head(string, kpl::countElementsFromBegin(string, sentinal)); } kpl::String forwardUntil(kpl::StringView string, const kpl::Char sentinal) { return viewToString(kpl::head(string, kpl::countElementsFromBegin(string, sentinal))); } kpl::StringView backwardUntilView(kpl::StringView string, const kpl::Char sentinal) { return kpl::tail(string, kpl::countElementsFromEnd(string, sentinal)); } kpl::String backwardUntil(kpl::StringView string, const kpl::Char sentinal) { return viewToString(kpl::tail(string, kpl::countElementsFromEnd(string, sentinal))); } kpl::String forwardUntilLast(const kpl::String& string, const kpl::Char find) { u32 truncate_from_end = kpl::countElementsFromEnd(stringToView(string), find); return string.right(string.size() - truncate_from_end); } kpl::String backwardUntilFirst(const kpl::String& string, const kpl::Char find) { u32 truncate_from_begin = kpl::countElementsFromBegin(stringToView(string), find); return string.left(string.size() - truncate_from_begin); } }
7bae7c4b8d0910ecec300c22f1f6a24febb5c9d1
86bf90b77cd97c9959dfd27774e5d9437be81be7
/Release/include/cpprest/details/http_response_proxy.h
30bbab288e51483a6a4faba6119e89c651028a20
[ "MIT" ]
permissive
SergeyZhuravlev/cpprestsdk_Net
e9c599959b5ca2d5aba8e6eb2b560752cea04701
11331ee568e2bfe486c3ebb57818b7c040716ab0
refs/heads/master
2022-05-22T05:28:52.034314
2022-04-27T20:04:25
2022-04-27T20:04:25
177,675,342
0
0
null
null
null
null
UTF-8
C++
false
false
837
h
http_response_proxy.h
#pragma once #include "..\..\include\cpprest\CppRestProxyExport.h" #include "http_response_base.h" #include "..\..\include\cpprest\http_headers.h" #include "..\..\include\cpprest\istreambuf_type_erasure.h" namespace web::http::details { class http_response_proxy : public http_response_base, public std::enable_shared_from_this<http_response_proxy> { public: virtual void set_status_code(http::status_code code) = 0; virtual void set_reason_phrase(const http::reason_phrase &reason) = 0; virtual void _set_response_body(const std::shared_ptr<Concurrency::streams::istreambuf_type_erasure> &streambuf, utility::size64_t contentLength, const utf16string &contentType) = 0; virtual void _set_content_ready(uint64_t contentSize) = 0; virtual http::http_headers& headers() = 0; CPPRESTPROXY_API ~http_response_proxy(); }; }
faf821b0517e5c9421a359af4b478979eefefaac
35e2595f82bb3295012ab9bdaa98597a715ade56
/CCFwithAxin/Hearthstone/Minion.cpp
e1fa5948755fd0e579c95a4b82c93cc43736f421
[]
no_license
kangyijie5473/AC_list
328084923796751f5a1836e85a6ea69d9e1e990a
3f8092c3cc857111cb64e9e9662b657228ea8dc2
refs/heads/master
2021-07-15T04:47:09.584992
2019-01-13T14:47:38
2019-01-13T14:47:38
97,422,938
0
0
null
null
null
null
UTF-8
C++
false
false
429
cpp
Minion.cpp
/* * > File Name: Minion.cpp * > Author: Jack Kang * > Mail: kangyijie@xiyoulinux.org * > Created Time: 2017年10月29日 星期日 10时01分24秒 */ #include <iostream> #include "Minion.h" using namespace std; void Minion::attack(Hero &enemy, int id) { if(!id){ enemy.hp -= this->attackNum; return; } int attack; attack = enemy.underAttack(id, this->attackNum); this->hp -= attack; }
a3488f5ee6980890c1bc7502729f0471ecc879dd
ef43f7a4ec8317ccfdff09121ca03727f8bcbd05
/src/default_traits.h
22519380f840baef8b94afae9ef8d4343d704e60
[ "BSD-3-Clause" ]
permissive
chafey/charls
30baa98f5107c22a731a55e188e6c18b7131fa6c
3058b6856abe1120665d49ebd616d1c4f417146c
refs/heads/master
2021-01-18T21:49:52.755519
2020-04-24T16:20:07
2020-04-24T16:20:07
250,872,014
1
3
NOASSERTION
2020-03-28T19:01:54
2020-03-28T19:01:53
null
UTF-8
C++
false
false
4,357
h
default_traits.h
// Copyright (c) Team CharLS. // SPDX-License-Identifier: BSD-3-Clause #pragma once #include "constants.h" #include "util.h" #include <algorithm> #include <cassert> #include <cmath> #include <cstdlib> // Default traits that support all JPEG LS parameters: custom limit, near, maxval (not power of 2) // This traits class is used to initialize a coder/decoder. // The coder/decoder also delegates some functions to the traits class. // This is to allow the traits class to replace the default implementation here with optimized specific implementations. // This is done for lossless coding/decoding: see losslesstraits.h namespace charls { template<typename sample, typename pixel> struct DefaultTraits final { using SAMPLE = sample; using PIXEL = pixel; int32_t MAXVAL; const int32_t RANGE; const int32_t NEAR; const int32_t qbpp; const int32_t bpp; const int32_t LIMIT; const int32_t RESET; DefaultTraits(const int32_t max, const int32_t near, const int32_t reset = DefaultResetValue) noexcept : MAXVAL{max}, RANGE{(max + 2 * near) / (2 * near + 1) + 1}, NEAR{near}, qbpp{log_2(RANGE)}, bpp{log_2(max)}, LIMIT{2 * (bpp + std::max(8, bpp))}, RESET{reset} { } DefaultTraits(const DefaultTraits& other) noexcept : MAXVAL{other.MAXVAL}, RANGE{other.RANGE}, NEAR{other.NEAR}, qbpp{other.qbpp}, bpp{other.bpp}, LIMIT{other.LIMIT}, RESET{other.RESET} { } DefaultTraits() = delete; DefaultTraits(DefaultTraits&&) noexcept = default; ~DefaultTraits() = default; DefaultTraits& operator=(const DefaultTraits&) = delete; DefaultTraits& operator=(DefaultTraits&&) = delete; FORCE_INLINE int32_t ComputeErrVal(const int32_t e) const noexcept { return ModuloRange(Quantize(e)); } FORCE_INLINE SAMPLE ComputeReconstructedSample(const int32_t Px, const int32_t ErrVal) const noexcept { return FixReconstructedValue(Px + DeQuantize(ErrVal)); } FORCE_INLINE bool IsNear(const int32_t lhs, const int32_t rhs) const noexcept { return std::abs(lhs - rhs) <= NEAR; } bool IsNear(const Triplet<SAMPLE> lhs, const Triplet<SAMPLE> rhs) const noexcept { return std::abs(lhs.v1 - rhs.v1) <= NEAR && std::abs(lhs.v2 - rhs.v2) <= NEAR && std::abs(lhs.v3 - rhs.v3) <= NEAR; } bool IsNear(const Quad<SAMPLE> lhs, const Quad<SAMPLE> rhs) const noexcept { return std::abs(lhs.v1 - rhs.v1) <= NEAR && std::abs(lhs.v2 - rhs.v2) <= NEAR && std::abs(lhs.v3 - rhs.v3) <= NEAR && std::abs(lhs.v4 - rhs.v4) <= NEAR; } FORCE_INLINE int32_t CorrectPrediction(const int32_t Pxc) const noexcept { if ((Pxc & MAXVAL) == Pxc) return Pxc; return (~(Pxc >> (int32_t_bit_count - 1))) & MAXVAL; } /// <summary> /// Returns the value of errorValue modulo RANGE. ITU.T.87, A.4.5 (code segment A.9) /// This ensures the error is reduced to the range (-⌊RANGE/2⌋ .. ⌈RANGE/2⌉-1) /// </summary> FORCE_INLINE int32_t ModuloRange(int32_t errorValue) const noexcept { ASSERT(std::abs(errorValue) <= RANGE); if (errorValue < 0) { errorValue += RANGE; } if (errorValue >= (RANGE + 1) / 2) { errorValue -= RANGE; } ASSERT(-RANGE / 2 <= errorValue && errorValue <= ((RANGE + 1) / 2) - 1); return errorValue; } private: int32_t Quantize(const int32_t errorValue) const noexcept { if (errorValue > 0) return (errorValue + NEAR) / (2 * NEAR + 1); return -(NEAR - errorValue) / (2 * NEAR + 1); } FORCE_INLINE int32_t DeQuantize(const int32_t ErrorValue) const noexcept { return ErrorValue * (2 * NEAR + 1); } FORCE_INLINE SAMPLE FixReconstructedValue(int32_t value) const noexcept { if (value < -NEAR) { value = value + RANGE * (2 * NEAR + 1); } else if (value > MAXVAL + NEAR) { value = value - RANGE * (2 * NEAR + 1); } return static_cast<SAMPLE>(CorrectPrediction(value)); } }; } // namespace charls
f8e629ef3760accf7e58902d67343fdf7d8b8af7
68ab5a57117168cb77c8755a34eb094a573e89f9
/leetcode/cpp/find_all_anagrams_in_a_string.cpp
4d468f6a5fdc6ee0e45a22031cbf8d890439172b
[]
no_license
hitlye/code-pool
732197e76d27b57c2d328adf34cc843c03101673
2ab57dd33db76abeac1632fd68c136a7ae3978af
refs/heads/master
2020-03-24T16:16:01.422465
2019-09-04T06:58:54
2019-09-04T06:58:54
142,818,753
0
0
null
2019-02-18T07:58:18
2018-07-30T03:13:45
C++
UTF-8
C++
false
false
1,272
cpp
find_all_anagrams_in_a_string.cpp
// Copyright 2018 Leo - All Rights Reserved // Author: Leo // Best solution time: O(n) n is the length // Best solution space: O(1) // Solution dependencies #include<map> #include<string> #include<vector> using std::map; using std::string; using std::vector; // Core: Sliding Window // Time: O(n) n is the length of s // Space: O(1) class Solution { public: vector<int> findAnagrams(string s, string p) { // count letter occurance of pattern map<char, int> letter_counter; for (const auto &c : p) ++letter_counter[c]; // sliding window parameters int begin = 0, end = 0; int len = letter_counter.size(); vector<int> anagram_start; while (end < s.size()) { auto found_end = letter_counter.find(s[end]); if (found_end != letter_counter.end()) { if (--found_end->second == 0) --len; } ++end; // we have a window now while (len == 0) { // a valid anagram if (end - begin == p.size()) anagram_start.emplace_back(begin); // slide window auto found_begin = letter_counter.find(s[begin]); if (found_begin != letter_counter.end()) { if (++found_begin->second > 0) ++len; } ++begin; } } return anagram_start; } };
0add1d388d445d3487bee0c23b72fa2dbbd4b829
1016c5f6570b2a0f20ccc73748f6baf347a0510c
/BoxTreeNode.h
12e61827385ab78abaf9a504805e700f842012c4
[]
no_license
awthomps/CSE168HW3
f9ad05ae9810b3fca002b1740adc7ac2ea6ca59c
211a2e5cb051b85f4c1ac6971c168b96507a3a80
refs/heads/master
2021-01-17T15:01:28.042764
2014-05-14T18:53:53
2014-05-14T18:53:53
19,590,978
1
0
null
null
null
null
UTF-8
C++
false
false
604
h
BoxTreeNode.h
#pragma once #ifndef CSE168_BOXTREENODE_H #define CSE168_BOXTREENODE_H #define MAXTRIANGLESPERBOX 10 #define SHARENUMBER 1 #include "Vector3.h" #include "Intersection.h" #include "Ray.h" #include "Triangle.h" class BoxTreeNode { public: BoxTreeNode(); ~BoxTreeNode(); bool Intersect(const Ray &ray, Intersection &hit); void Contruct(int count, Triangle **tri); bool TestRay(const Ray &ray, float &t); bool ContainsPoint(Vector3 point); private: Vector3 BoxMin, BoxMax; BoxTreeNode *Child1, *Child2; Triangle *Tri[MAXTRIANGLESPERBOX]; int numTriangles; bool isLeaf = false; }; #endif
660c4aef4c78e0d1a2c3473339010c120621fb93
7188896510d360dc713c6d9af35fba91095bd717
/Lab_5.cpp
ba9f82804ba1e9cf728e99f6136b7b77891ebdba
[]
no_license
MarmuraVlad/OOP_Laboratories
ee4a3f9359191cf909c218d33b226fddb77c2991
01b4ce07be6dd767045eea785162386818f6c86a
refs/heads/master
2022-07-31T11:03:49.830639
2020-05-24T21:45:31
2020-05-24T21:45:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,662
cpp
Lab_5.cpp
#include <iostream> #include <String> using namespace std; void clear() { cout << "____________________________________________________________" << endl; } class Ship { public: void setShipName(string Name) { sName = Name; } void setShipPass(int passengers) { sPass = passengers; } void setShipFuel(int fuel) { sFuel = fuel; } void setShipValue(int value) { sValue = value; } void setShipMilesValue(int cost) { sMileValue = cost; } void setShipFuelPerMile(int fuel) { sFuelPerMile = fuel; } string getShipName() { return sName; } int getShipPass() { return sPass; } int getShipFuel() { return sFuel; } int getShipValue() { return sValue; } int getShipMilesValue() { return sMileValue; } int getShipFuelPerMile() { return sFuelPerMile; } bool Move(int miles) { sValue -= sMileValue * miles; sMiles += miles; sFuel -= sFuelPerMile * miles; if (sFuel > 0) { return true; } else if (sFuel <= 0) { cout << "Fuel tank empty, ship had stucked in ocean..." << endl; return false; } } void PortOut(int passengers) { sPass -= passengers; } void PortIn(int passengers) { sPass += passengers; } void State() { clear(); cout << "Ship Name - " << this->sName << endl; cout << "Ship Passengers - " << this->sPass << endl; cout << "Ship Fuel - " << this->sFuel << endl; cout << "Ship Value - " << this->sValue << endl; cout << "Ship Miles - " << this->sMiles << endl; clear(); } Ship(string name, int passengers, int fuel, int value, int valuepermile, int fuelpermile) { sName = name; sPass = passengers; sFuel = fuel; sValue = value; sMileValue = valuepermile; sMiles = 0; sFuelPerMile = fuelpermile; } friend bool operator+= (Ship ship1, Ship ship2) { ship1.sFuel += ship2.getShipFuel(); cout << "Ship 1 fuel = " << ship1.sFuel << endl; cout << "Ship 2 fuel = " << ship2.getShipFuel() << endl; return true; } friend bool operator-= (Ship ship1, Ship ship2) { ship1.sFuel -= ship2.getShipFuel(); cout << "Ship 1 fuel = " << ship1.sFuel << endl; cout << "Ship 2 fuel = " << ship2.getShipFuel() << endl; return false; } Ship& operator= (const Ship& ship2) { if (this == &ship2) { return *this; } sFuel = ship2.sFuel; sPass = ship2.sPass; return *this; } private: string sName; int sPass, sFuel, sValue, sMileValue, sMiles, sFuelPerMile; }; bool operator == (Ship ship1, Ship ship2) { if (ship1.getShipFuel() == ship2.getShipFuel() && ship1.getShipName() == ship2.getShipName() && ship1.getShipMilesValue() == ship2.getShipMilesValue()) { return true; } else return false; } bool operator != (Ship ship1, Ship ship2) { if (ship1.getShipFuel() == ship2.getShipFuel() && ship1.getShipName() == ship2.getShipName() && ship1.getShipMilesValue() == ship2.getShipMilesValue()) { return false; } else return true; } bool operator > (Ship ship1, Ship ship2) { if (ship1.getShipFuel() > ship2.getShipFuel() && ship1.getShipPass() > ship2.getShipPass()) { return true; } else return false; } bool operator < (Ship ship1, Ship ship2) { if (ship1.getShipFuel() < ship2.getShipFuel() && ship1.getShipName() < ship2.getShipName() && ship1.getShipMilesValue() < ship2.getShipMilesValue()) { return true; } else return false; } int main() { string sName, sName1; int sPassengers, sFuel, sValue, sMileValue, sFuelPerMile; int sPassengers1, sFuel1, sValue1, sMileValue1, sFuelPerMile1; cout << "Enter a first ship's name - "; cin >> sName; cout << endl << "Enter a ship's passengers on board - "; cin >> sPassengers; cout << endl << "Enter a ship's fuel on board - "; cin >> sFuel; cout << endl << "Enter a ship's value - "; cin >> sValue; cout << endl << "Enter a ship's usage value per 1 mile - "; cin >> sMileValue; cout << endl << "Enter a ship's fuel usage per 1 mile - "; cin >> sFuelPerMile; Ship myShip1(sName, sPassengers, sFuel, sValue, sMileValue, sFuelPerMile); cout << endl << endl; cout << endl << "First ship state - " << endl; myShip1.State(); cout << "Enter a second ship's name - "; cin >> sName1; cout << endl << "Enter a ship's passengers on board - "; cin >> sPassengers1; cout << endl << "Enter a ship's fuel on board - "; cin >> sFuel1; cout << endl << "Enter a ship's value - "; cin >> sValue1; cout << endl << "Enter a ship's usage value per 1 mile - "; cin >> sMileValue1; cout << endl << "Enter a ship's fuel usage per 1 mile - "; cin >> sFuelPerMile1; Ship myShip2(sName1, sPassengers1, sFuel1, sValue1, sMileValue1, sFuelPerMile1); cout << endl << "Second ship state - " << endl; myShip2.State(); if (myShip1==myShip2) { cout << "Ships are same" << endl; } if (myShip1>myShip2) { cout << "First ship is more loaded than second" << endl; } myShip1 += myShip2; myShip1 = myShip2; myShip1.State(); myShip2.State(); }
6c2b29e9a3815471292faeef5978630e81d37825
437504aa449f1f0b0ce75de1a6c7d271b3e956df
/src/lib/uno/uno.h
4103e2edc776ae05d9982621ba50e569376cfaed
[]
no_license
AtifMahmud/UNO
26d4edd5697c06e2692b04b2d39cf78d42d25af0
8d29c225313f39243ee38e3ea7bfedd9138014e8
refs/heads/master
2020-04-07T06:30:54.522975
2019-11-30T02:44:38
2019-11-30T02:44:38
158,138,717
1
1
null
2019-11-30T02:44:39
2018-11-18T23:55:07
C++
UTF-8
C++
false
false
259
h
uno.h
#ifndef UNO_H #define UNO_H /** * File: uno.h * Purpose: Declarations of the functions to implement the UNO gameplay * Author: Atif Mahmud * */ #include "../cardClass/cardClass.h" #include <vector> std::vector <CardClass> initUnoVector(); #endif
ad89bce8ed909a34fdf5c0e53178291bc3ceab90
c00cd6aed5ba0be602f44262bbaa22672688e8ad
/src/libtimer/Timer.h
07cce8212d0711efcffbe890c442dd77c87ff9b1
[ "MIT" ]
permissive
selavy/word-brain-solver
8c72902589574058c86ef2041b694bd840d5fafb
2c011053f560a9e5b388f2ae809e17d872ce914e
refs/heads/master
2016-09-05T10:50:17.878788
2015-04-26T21:34:36
2015-04-26T21:34:36
30,813,243
0
0
null
null
null
null
UTF-8
C++
false
false
367
h
Timer.h
// // Created by peter on 3/29/15. // #ifndef WORD_BRAIN_SOLVER_TIMER_H #define WORD_BRAIN_SOLVER_TIMER_H #include <cstdint> #include <chrono> class Timer { public: Timer(); ~Timer() {} void start(); int64_t elapsedNs() const; private: std::chrono::time_point<std::chrono::high_resolution_clock> start_; }; #endif //WORD_BRAIN_SOLVER_TIMER_H
ff5af8a71270fda25445a08385c56502180a2f94
f2188de782bbbb123a1fa72bef2c4c7e3c7dbf3e
/src/train/pretrain.cpp
eeadba4cbffdbcee51152b7420c33c77012abe6b
[ "WTFPL" ]
permissive
shaswata56/GOTURN
68d71855f18473071aa53daaeac8f5e69e6cad9b
e96067f42ef1233a4846e393dbffe58f6600b6eb
refs/heads/master
2020-03-25T19:53:57.696829
2018-08-09T05:45:06
2018-08-09T05:45:06
144,105,900
2
0
MIT
2018-08-09T05:42:22
2018-08-09T05:42:21
null
UTF-8
C++
false
false
3,526
cpp
pretrain.cpp
#include <string> #include <iostream> #include <caffe/caffe.hpp> #include "example_generator.h" #include "helper/helper.h" #include "loader/loader_imagenet_det.h" #include "loader/rgbd_loader.h" #include "network/regressor_train.h" #include "train/tracker_trainer.h" #include "tracker/tracker_manager.h" using std::string; namespace { // 450,000 batches * (50 images / batch) / (10 images / example) = n examples. const int kNumIters = 450000 * 5; // Train on a random image. void preTrainImage(const LoaderImagenetDet& image_loader, const std::vector<std::vector<Annotation> >& images, TrackerTrainer* tracker_trainer) { // Choose a random image. const int image_num = rand() % images.size(); // Load the image. cv::Mat image; image_loader.getImage(image_num, &image); // Get a random bounding box for this image. BoundingBox bbox; bbox.rand(image); // Train on this example tracker_trainer->train(image, image, bbox, bbox); } } // namespace int main (int argc, char *argv[]) { if (argc < 13) { std::cerr << "Usage: " << argv[0] << " videos_folder_imagenet annotations_folder_imagenet" << " train_deploy.prototxt network.caffemodel" << " mean.binaryproto solver_file" << " lambda_shift lambda_scale min_scale max_scale" << " gpu_id random_seed" << std::endl; return 1; } FLAGS_alsologtostderr = 1; ::google::InitGoogleLogging(argv[0]); int arg_index = 1; const string& images_folder_imagenet = argv[arg_index++]; const string& annotations_folder_imagenet = argv[arg_index++]; const string& caffe_model = argv[arg_index++]; const string& deploy_proto = argv[arg_index++]; const string& test_proto = argv[arg_index++]; const string& mean_file = argv[arg_index++]; const string& solver_file = argv[arg_index++]; const double lambda_shift = atof(argv[arg_index++]); const double lambda_scale = atof(argv[arg_index++]); const double min_scale = atof(argv[arg_index++]); const double max_scale = atof(argv[arg_index++]); const int gpu_id = atoi(argv[arg_index++]); const int random_seed = atoi(argv[arg_index++]); caffe::Caffe::set_random_seed(random_seed); printf("Using random seed: %d\n", random_seed); #ifdef CPU_ONLY printf("Setting up Caffe in CPU mode\n"); caffe::Caffe::set_mode(caffe::Caffe::CPU); #else printf("Setting up Caffe in GPU mode with ID: %d\n", gpu_id); caffe::Caffe::set_mode(caffe::Caffe::GPU); caffe::Caffe::SetDevice(gpu_id); #endif // Load the ImageNet data. LoaderImagenetDet image_loader(images_folder_imagenet, annotations_folder_imagenet); const std::vector<std::vector<Annotation> >& train_images = image_loader.get_images(); // Create an example generator. ExampleGenerator example_generator(lambda_shift, lambda_scale, min_scale, max_scale); printf("Setting up training objects\n"); RegressorTrain regressor_train(deploy_proto, caffe_model, mean_file, gpu_id, solver_file); regressor_train.set_test_net(test_proto); TrackerTrainer tracker_trainer(&example_generator, &regressor_train); //TrackerManagerTrainer track_manager(train_videos, &regressor, &tracker_trainer); //track_manager.set_use_gt_target(true); for (int i = 0; i < kNumIters; ++i) { preTrainImage(image_loader, train_images, &tracker_trainer); } return 0; }
55222bf961a6662c5d5ed6b6f789cca5a4537704
9d364070c646239b2efad7abbab58f4ad602ef7b
/platform/external/chromium_org/chrome/test/chromedriver/logging.h
b6471fbc5126352ebae841a19140dcb40fade764
[ "BSD-3-Clause" ]
permissive
denix123/a32_ul
4ffe304b13c1266b6c7409d790979eb8e3b0379c
b2fd25640704f37d5248da9cc147ed267d4771c2
refs/heads/master
2021-01-17T20:21:17.196296
2016-08-16T04:30:53
2016-08-16T04:30:53
65,786,970
0
2
null
2020-03-06T22:00:52
2016-08-16T04:15:54
null
UTF-8
C++
false
false
1,848
h
logging.h
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_TEST_CHROMEDRIVER_LOGGING_H_ #define CHROME_TEST_CHROMEDRIVER_LOGGING_H_ #include <string> #include "base/basictypes.h" #include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/values.h" #include "chrome/test/chromedriver/chrome/log.h" struct Capabilities; class CommandListener; class DevToolsEventListener; class ListValue; struct Session; class Status; class WebDriverLog : public Log { public: static const char kBrowserType[]; static const char kDriverType[]; static const char kPerformanceType[]; static bool NameToLevel(const std::string& name, Level* out_level); WebDriverLog(const std::string& type, Level min_level); virtual ~WebDriverLog(); scoped_ptr<base::ListValue> GetAndClearEntries(); std::string GetFirstErrorMessage() const; virtual void AddEntryTimestamped(const base::Time& timestamp, Level level, const std::string& source, const std::string& message) OVERRIDE; const std::string& type() const; void set_min_level(Level min_level); Level min_level() const; private: const std::string type_; Level min_level_; scoped_ptr<base::ListValue> entries_; DISALLOW_COPY_AND_ASSIGN(WebDriverLog); }; bool InitLogging(); Status CreateLogs(const Capabilities& capabilities, const Session* session, ScopedVector<WebDriverLog>* out_logs, ScopedVector<DevToolsEventListener>* out_devtools_listeners, ScopedVector<CommandListener>* out_command_listeners); #endif
b5b196999a2e50af5e84772c0da04bce86b4bd67
7e87822f3dd391188eb6510866dec0245a7eaa23
/main.cpp
3b2efc650d9c10ea801fa9a8ec47cd8d6398ea52
[]
no_license
harrahx3/SFML_game
d0c61fb2288e9be422444250a64d5bc1b345c51a
b96546671332e65e035b040c2f008d9d535cf041
refs/heads/main
2023-03-09T18:37:17.378550
2021-02-26T15:59:00
2021-02-26T15:59:00
342,621,202
0
0
null
null
null
null
ISO-8859-1
C++
false
false
11,389
cpp
main.cpp
#include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <iostream> #include <cmath> #include <string> #include <sstream> #include <vector> #include <time.h> #include <ctime> #include <fstream> #include "Perso.h" #include "Perso.cpp" #include "fonctions.cpp" #include "fonctions.h" using namespace sf; using namespace std; int main() { /// Load a music to play sf::Music music; if (!music.openFromFile("musicMario.ogg")) cout<<"erreur music"<<endl; music.setLoop(true); bool creation = false; bool creationMur = false; bool creationMechant = false; string create; cin>>create; if (create=="1") creation=true; Vector2f coordonnees; srand(time(0)); /// int exemple = rand () %2 ; int const largeurEcran (800); int const hauteurEcran (600); Vector2f const dimensionsEcran (600,400); unsigned score(0); Text texte; Font fonte; Color couleurFond (34,177,76); ///unsigned maxi =1000; ///dimension de la zone de jeu (100*maxi+100) pour aleatoire Vector2f spawnPoint (100,100); ///point où apparait Mario enum types {point, mur, mechant}; types type = point; if (!fonte.loadFromFile("Fipps-Regular.otf")) ///charger la fonte std::cout<<"erreur chargement fonte \n"; else texte.setFont(fonte); texte.setString("0"); texte.setPosition(0,0); texte.setColor(Color::Black); Mario mario (spawnPoint); ///creer mario RenderWindow app(VideoMode(largeurEcran,hauteurEcran),"Mario Game"); ///creer la fenetre app.setFramerateLimit(60); vector <Point> points = creerObjets <Point> ("savePoints.txt",2); vector <Mur> murs = creerObjets <Mur> ("saveMurs.txt",4); ///creer les objets vector <Mechant> mechants = creerObjets <Mechant> ("saveMechants.txt",4); vector <Point> pointsCrees; vector <Mur> mursCrees; vector <Mechant> mechantsCrees; music.play(); /// Play the music /**if (Keyboard::isKeyPressed(Keyboard::A)) ///Creation aleatoire { int nb; int nbs; std::vector <Mechant> mechants; ///creer les méchants for (int i=0; i<2; i++) { nb =(rand()%maxi)+100; nbs =(rand()%maxi)+100; Mechant mechant (Vector2f(nb,(rand()%maxi)+100),Vector2f(nb,(rand()%maxi)+100),3); mechants.push_back(mechant); nb =(rand()%maxi)+100; nbs =(rand()%maxi)+100; Mechant mechant2 (Vector2f((rand()%maxi)+100,nb),Vector2f((rand()%maxi)+100,nb)); mechants.push_back(mechant2); } std::vector <Mur> murs; ///creer les murs for (int i=0; i<5; i++) { Mur mur (Vector2f((rand()%500)+200,50),Vector2f((rand()%maxi)+100,(rand()%maxi)+100)); murs.push_back(mur); Mur mur2 (Vector2f(50,(rand()%500)+200),Vector2f((rand()%maxi)+100,(rand()%maxi)+100)); murs.push_back(mur2); } std::vector <Point> points; ///creer les points for (int i=0; i<20; i++) { Point point (Vector2f((rand()%maxi)+100,(rand()%maxi)+100)); points.push_back(point); } }**/ while (app.isOpen()) { Event event; while (app.pollEvent(event)) { if (event.type==Event::Closed || (event.type==Event::KeyPressed && event.key.code==Keyboard::Space)) { if (creation) { enregistrer <Point> (pointsCrees,"savePoints.txt",2); ///enregistrer tous les objets crées enregistrer <Mechant> (mechantsCrees,"saveMechants.txt",4); enregistrer <Mur> (mursCrees,"saveMurs.txt",4); } app.close(); ///fermer la fenetre si on clique sur la croix ou si on appuie sur la bare espace } if (creation) { if (event.type==Event::KeyPressed && event.key.code==Keyboard::P) { pointsCrees.push_back(Point(mario.getM_sprite().getPosition())); ///points.push_back(placerObjet(mario.getM_sprite().getPosition(),"savePoints.txt")); } if (event.type==Event::KeyPressed && event.key.code==Keyboard::W) { ///coordonnees = placerObjet(mario.getM_sprite().getPosition(),"saveMurs.txt"); coordonnees = mario.getM_sprite().getPosition(); creationMur = true; } if (event.type==Event::KeyReleased && event.key.code==Keyboard::W) { ///murs.push_back(Mur(coordonnees, placerObjet(mario.getM_sprite().getPosition(),"saveMurs.txt"))); mursCrees.push_back(Mur(coordonnees, mario.getM_sprite().getPosition())); creationMur = false; } if (event.type==Event::KeyPressed && event.key.code==Keyboard::M) { ///coordonnees = placerObjet(mario.getM_sprite().getPosition(),"saveMechants.txt"); coordonnees = mario.getM_sprite().getPosition(); creationMechant = true; } if (event.type==Event::KeyReleased && event.key.code==Keyboard::M) { ///mechants.push_back(Mechant(coordonnees, placerObjet(mario.getM_sprite().getPosition(),"saveMechants.txt"))); mechantsCrees.push_back(Mechant(coordonnees, mario.getM_sprite().getPosition())); creationMechant = false; } if (event.type==Event::KeyPressed && event.key.code==Keyboard::A) { if(Keyboard::isKeyPressed(Keyboard::P)) if (pointsCrees.size()>0) pointsCrees.pop_back(); /** if(Keyboard::isKeyPressed(Keyboard::M)) if(Keyboard::isKeyPressed(Keyboard::W))**/ } if (event.type==Event::KeyPressed && event.key.code==Keyboard::Numpad4) { switch (type) { case point : type = mechant; break; case mur : type = point; break; case mechant : type = mur; break; } } if (event.type==Event::KeyPressed && event.key.code==Keyboard::Numpad6) { switch (type) { case point : type = mur; break; case mur : type = mechant; break; case mechant : type = point; break; } } } } if (creation) { if (creationMur) { Mur murCreer (coordonnees, mario.getM_sprite().getPosition()); app.draw(murCreer.getM_mur()); } if (creationMechant) { Mur mechantCreer (coordonnees, Vector2f (mario.getM_sprite().getPosition().x-5, mario.getM_sprite().getPosition().y-5),Color::Red); app.draw(mechantCreer.getM_mur()); } for (std::vector<Point>::iterator it=pointsCrees.begin(); it!=pointsCrees.end(); ++it) ///iterateur pour agir sur tous { app.draw(it->getM_point()); ///on dessine tous les points } for (std::vector<Mur>::iterator it=mursCrees.begin(); it!=mursCrees.end(); ++it) ///iterateur pour agir sur tous { app.draw(it->getM_mur()); ///on dessine tous les points } for (std::vector<Mechant>::iterator it=mechantsCrees.begin(); it!=mechantsCrees.end(); ++it) ///iterateur pour agir sur tous { it->deplacer(); app.draw(it->getM_sprite()); ///on dessine tous les points } } for (std::vector<Mur>::iterator it=murs.begin(); it!=murs.end(); ++it) ///iterateur pour agir sur tous { app.draw(it->getM_mur()); ///on dessine tous les murs if (!creation) mario.collision(*it); ///et on gere les collisisions } for (std::vector<Point>::iterator it=points.begin(); it!=points.end(); ++it) ///iterateur pour agir sur tous { app.draw(it->getM_point()); ///on dessine tous les points if (!creation) if (mario.Perso::collision(*it)) score++; ///et on gere les collisisions } for (std::vector<Mechant>::iterator it=mechants.begin(); it!=mechants.end(); ++it) ///iterateur pour agir sur tous { it->deplacer(); app.draw(it->getM_sprite()); ///on deplace et dessine chaque méchants if (!creation) { mario.collision(*it); ///on test la collision avec un méchant for (std::vector<Mur>::iterator ite=murs.begin(); ite!=murs.end(); ++ite) ///iterateur pour agir sur tous { it->collision(*ite); /// collisions Mechant/Mur } } } mario.deplacer(); app.draw(mario.getM_sprite()); ///on deplace et dessine mario app.setView(app.getDefaultView()); texte.setPosition(20,20); app.draw (texte); /// app.draw(drawScore(mario.getM_sprite().getPosition(), dimensionsEcran, texte, score)); ///on affiche le score View vue = setVue(Vector2f(mario.getM_sprite().getPosition().x+mario.getM_dimensions().x/2, mario.getM_sprite().getPosition().y+mario.getM_dimensions().y/2), dimensionsEcran); ///on centre la vue sur mario View miniMapView = setVue(Vector2f(500,500), Vector2f(1000,1000)); ///on centre la vue sur mario miniMapView.setViewport(sf::FloatRect(0.75f, 0, 0.25f, 0.25f)); vue.setViewport(sf::FloatRect(0, 0, 1, 1)); app.setView(miniMapView); app.draw(mario.getM_sprite()); app.setView(vue); app.draw(mario.getM_sprite()); app.display(); ///on raffraichie l'image app.clear(couleurFond); /**app.setView(setVue(Vector2f(mario.getM_sprite().getPosition().x+mario.getM_dimensions().x/2, mario.getM_sprite().getPosition().y+mario.getM_dimensions().y/2), dimensionsEcran)); ///on centre la vue sur mario app.display(); ///on raffraichie l'image app.clear(couleurFond);**/ } return 0; }
da1c5210a0ebfb359683352a089efed74d418baf
d0fb46aecc3b69983e7f6244331a81dff42d9595
/ddoscoo/src/model/DescribeDefenseRecordsResult.cc
9bff687cb292ab5416654c85011caf0d12cfb824
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
2,818
cc
DescribeDefenseRecordsResult.cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * 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 <alibabacloud/ddoscoo/model/DescribeDefenseRecordsResult.h> #include <json/json.h> using namespace AlibabaCloud::Ddoscoo; using namespace AlibabaCloud::Ddoscoo::Model; DescribeDefenseRecordsResult::DescribeDefenseRecordsResult() : ServiceResult() {} DescribeDefenseRecordsResult::DescribeDefenseRecordsResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeDefenseRecordsResult::~DescribeDefenseRecordsResult() {} void DescribeDefenseRecordsResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allDefenseRecordsNode = value["DefenseRecords"]["DefenseRecord"]; for (auto valueDefenseRecordsDefenseRecord : allDefenseRecordsNode) { DefenseRecord defenseRecordsObject; if(!valueDefenseRecordsDefenseRecord["EndTime"].isNull()) defenseRecordsObject.endTime = std::stol(valueDefenseRecordsDefenseRecord["EndTime"].asString()); if(!valueDefenseRecordsDefenseRecord["Status"].isNull()) defenseRecordsObject.status = std::stoi(valueDefenseRecordsDefenseRecord["Status"].asString()); if(!valueDefenseRecordsDefenseRecord["StartTime"].isNull()) defenseRecordsObject.startTime = std::stol(valueDefenseRecordsDefenseRecord["StartTime"].asString()); if(!valueDefenseRecordsDefenseRecord["EventCount"].isNull()) defenseRecordsObject.eventCount = std::stoi(valueDefenseRecordsDefenseRecord["EventCount"].asString()); if(!valueDefenseRecordsDefenseRecord["InstanceId"].isNull()) defenseRecordsObject.instanceId = valueDefenseRecordsDefenseRecord["InstanceId"].asString(); if(!valueDefenseRecordsDefenseRecord["AttackPeak"].isNull()) defenseRecordsObject.attackPeak = std::stol(valueDefenseRecordsDefenseRecord["AttackPeak"].asString()); defenseRecords_.push_back(defenseRecordsObject); } if(!value["TotalCount"].isNull()) totalCount_ = std::stol(value["TotalCount"].asString()); } std::vector<DescribeDefenseRecordsResult::DefenseRecord> DescribeDefenseRecordsResult::getDefenseRecords()const { return defenseRecords_; } long DescribeDefenseRecordsResult::getTotalCount()const { return totalCount_; }
9b46d8cf1c9b222c950b6f1c9fbb09ea45b468d2
f106e9a8197d2f8e2e151bb345cbc7db7cbab3e3
/exp2prob6.cpp
9381b41744c162038b504851c4a8bd21f27f6d8c
[]
no_license
franchescago/experiment2
e6af507ab2090a76216a4bc3c3a4c189aaba7c5f
58f8804177f55dcaeab163d8e72186ed125bf5f1
refs/heads/master
2020-05-19T12:53:44.267131
2019-05-05T12:00:08
2019-05-05T12:00:08
184,856,903
0
0
null
null
null
null
UTF-8
C++
false
false
414
cpp
exp2prob6.cpp
#include<iostream> #include<math.h> #include<conio.h> using namespace std; int main() { int n, sum, i; do { cout<<"Enter a number: " ; cin>>n; if (n<=0) { cout<<"Thank you!"<<endl; } i = 1; sum = 0; while(i<=n) { sum+=i; i++; } cout<<"The sum of all whole numbers from 1 to "<<n<<" is "<<sum<<endl; } while(n>0); getch(); return 0; }
b0a300ac7ede47a21ac6ad66a1871208901f220a
1e0db3bab23930fce239844e3e4813ae51735861
/Attacks_on_reduced-round_KetjeMinor/Teston6rKetjeMinor_rightkey.cpp
2ed85bbbc88ef1ea60618e1fbfe75460948e154b
[]
no_license
siweisun/MILP_conditional_cube_attack
7ac4d543bbf6792ced2bc51c4d0d8a3d56936cb2
2000fbc847e07b2d0404952a437db36311553b90
refs/heads/master
2021-01-25T14:27:00.726233
2017-07-15T12:23:27
2017-07-15T12:23:27
123,699,708
0
2
null
2018-03-03T14:33:53
2018-03-03T14:33:53
null
UTF-8
C++
false
false
13,332
cpp
Teston6rKetjeMinor_rightkey.cpp
/* Teston6rKetjeMinor_rightkey.cpp; Test whether the cube sum with the right key guess is zero or not. The program is run in Visual Studio 2010 with x64 platform Release. One experiment averagely takes 76 minutes with this procedure. */ #include <stdio.h> #include <conio.h> #include <string.h> #include <time.h> #include <stdlib.h> typedef unsigned char UINT8; typedef unsigned long int UINT32; typedef signed long long int INT64; typedef unsigned long long int UINT64; #define random(x) (rand())%x; #define nrRounds 6 UINT32 KeccakRoundConstants[nrRounds];//these are constant, #define nrLanes 25 unsigned int KeccakRhoOffsets[nrLanes];//these are constant, #define nrMessage 0x8000 void KeccakPermutationOnWords(UINT32 *state); void theta(UINT32 *A); void rho(UINT32 *A); void pi(UINT32 *A); void chi(UINT32 *A); void iota(UINT32 *A, unsigned int indexRound); void KeccakPermutationOnWords(UINT32 *state) { unsigned int i; for(i=0; i<nrRounds; i++) { theta(state); rho(state); pi(state); chi(state); iota(state, i); } } // used in theta #define index(x, y) (((x)%5)+5*((y)%5)) //used in theta #define ROL32(a, offset) ((offset != 0) ? ((((UINT32)a) << offset) ^ (((UINT32)a) >> (32-offset))) : a) void theta(UINT32 *A) { unsigned int x, y; UINT32 C[5], D[5];//C are the Xors of the five bits in every column. D are the Xors of the ten bits in right-behind column and right column for(x=0; x<5; x++) { C[x] = 0; for(y=0; y<5; y++) C[x] ^= A[index(x, y)]; } for(x=0; x<5; x++) D[x] = ROL32(C[(x+1)%5], 1) ^ C[(x+4)%5]; for(x=0; x<5; x++) for(y=0; y<5; y++) A[index(x, y)] ^= D[x]; } void rho(UINT32 *A) { unsigned int x, y; for(x=0; x<5; x++) for(y=0; y<5; y++) A[index(x, y)] = ROL32(A[index(x, y)], KeccakRhoOffsets[index(x, y)]); } void pi(UINT32 *A) { unsigned int x, y; UINT32 tempA[25]; for(x=0; x<5; x++) for(y=0; y<5; y++) tempA[index(x, y)] = A[index(x, y)]; for(x=0; x<5; x++) for(y=0; y<5; y++) A[index(0*x+1*y, 2*x+3*y)] = tempA[index(x, y)];//learn from this! } void chi(UINT32 *A) { unsigned int x, y; UINT32 C[5]; for(y=0; y<5; y++) { for(x=0; x<5; x++) C[x] = A[index(x, y)] ^ ((~A[index(x+1, y)]) & A[index(x+2, y)]); for(x=0; x<5; x++) A[index(x, y)] = C[x]; } } void iota(UINT32 *A, unsigned int indexRound) { A[index(0, 0)] ^= KeccakRoundConstants[indexRound]; } int LFSR86540(UINT8 *LFSR) { int result = ((*LFSR) & 0x01) != 0; if (((*LFSR) & 0x80) != 0) // Primitive polynomial over GF(2): x^8+x^6+x^5+x^4+1 (*LFSR) = ((*LFSR) << 1) ^ 0x71; else (*LFSR) <<= 1; return result; } void KeccakInitializeRoundConstants() { UINT8 LFSRstate = 0x01; unsigned int i, j, bitPosition; for(i=0; i<nrRounds; i++) { KeccakRoundConstants[i] = 0; for(j=0; j<7; j++) { bitPosition = (1<<j)-1; //2^j-1 if (LFSR86540(&LFSRstate)) KeccakRoundConstants[i] ^= (UINT32)1<<bitPosition; } } } void KeccakInitializeRhoOffsets() { unsigned int x, y, t, newX, newY; KeccakRhoOffsets[index(0, 0)] = 0; x = 1; y = 0; for(t=0; t<24; t++) { KeccakRhoOffsets[index(x, y)] = ((t+1)*(t+2)/2) % 32; newX = (0*x+1*y) % 5; newY = (2*x+3*y) % 5; x = newX; y = newY; } } void KeccakInitialize() { KeccakInitializeRoundConstants(); KeccakInitializeRhoOffsets(); } int main() { clock_t start,finish; start = clock(); UINT32 InitialState[25]={0}; UINT32 TempState[25]={0}; UINT32 FinalState[4]={0}; UINT32 Key[5]={0}; int tempkey[12]={0}; int guessedkey[40][12]={0}; int GIndex[40]; UINT64 i,j,k,temp,temp1; unsigned int rightkey[12]={0}; unsigned int index0[2][6]; index0[0][0]=5;index0[1][0]=19; index0[0][1]=15;index0[1][1]=19; index0[0][2]=11;index0[1][2]=15; index0[0][3]=16;index0[1][3]=15; index0[0][4]=8;index0[1][4]=0; index0[0][5]=13;index0[1][5]=0; unsigned int index[2][31]; index[0][0]=2;index[1][0]=2; index[0][1]=2;index[1][1]=4; index[0][2]=2;index[1][2]=7; index[0][3]=2;index[1][3]=11; index[0][4]=2;index[1][4]=12; index[0][5]=2;index[1][5]=20; index[0][6]=2;index[1][6]=23; index[0][7]=2;index[1][7]=29; index[0][8]=2;index[1][8]=30; index[0][9]=3;index[1][9]=3; index[0][10]=3;index[1][10]=6; index[0][11]=3;index[1][11]=12; index[0][12]=3;index[1][12]=13; index[0][13]=3;index[1][13]=17; index[0][14]=3;index[1][14]=21; index[0][15]=3;index[1][15]=22; index[0][16]=3;index[1][16]=26; index[0][17]=3;index[1][17]=31; index[0][18]=4;index[1][18]=0; index[0][19]=4;index[1][19]=5; index[0][20]=4;index[1][20]=8; index[0][21]=4;index[1][21]=15; index[0][22]=4;index[1][22]=18; index[0][23]=4;index[1][23]=22; index[0][24]=4;index[1][24]=24; index[0][25]=10;index[1][25]=1; index[0][26]=10;index[1][26]=5; index[0][27]=10;index[1][27]=10; index[0][28]=10;index[1][28]=15; index[0][29]=10;index[1][29]=31; index[0][30]=11;index[1][30]=4; FILE *f; f=fopen("result.txt","w+b"); srand(time(NULL)); for(i=8;i<32;i++){ temp=random(2); if(temp){ Key[0]^=((UINT32)0x1<<i); fprintf(f,"1"); } else{ fprintf(f,"0"); } } Key[0]^=((UINT32)0x1<<1); Key[0]^=((UINT32)0x1<<4); for(i=1;i<4;i++){ for(j=0;j<32;j++){ temp=random(2); if(temp) { Key[i]^=((UINT32)0x1<<j); fprintf(f,"1"); } else{ fprintf(f,"0"); } } } for(i=0;i<8;i++){ temp=random(2); if(temp){ Key[4]^=((UINT32)0x1<<i); fprintf(f,"1"); } else{ fprintf(f,"0"); } } fprintf(f,"\n"); Key[4]^=((UINT32)0x1<<8); for(i=0;i<40;i++) { GIndex[i]=-1; } for(i=0;i<25;i++){ InitialState[i]=0; } for(i=0;i<5;i++){ InitialState[6*i]=Key[i]; } /*for(i=0;i<25;i++) { if(i%6!=0){ for(j=0;j<64;j++) { temp=random(2); if(temp) { InitialState[i]^=((UINT32)0x1<<j); } } } }*/ InitialState[21]|=((UINT32)0x1<<30); InitialState[21]|=((UINT32)0x1<<31); rightkey[0]=((Key[1]>>24)&1); rightkey[1]=((Key[1]>>31)&1) ^ ((Key[3]>>30)&1); rightkey[2]=((Key[1]>>19)&1) ^ ((Key[3]>>18)&1); rightkey[3]=((Key[0]>>(8+8))&1) ^ ((Key[3]>>17)&1); rightkey[4]=((Key[0]>>(5+8))&1) ^ ((Key[2]>>12)&1); rightkey[5]=((Key[1]>>20)&1); rightkey[6]=((Key[1]>>10)&1) ^ ((Key[3]>>9)&1); rightkey[7]=((Key[0]>>(19+8))&1) ^ ((Key[3]>>28)&1); rightkey[8]=((Key[0]>>(7+8))&1) ^ ((Key[3]>>16)&1); rightkey[9]=((Key[0]>>(12+8))&1) ^ ((Key[3]>>21)&1); rightkey[10]=((Key[0]>>(18+8))&1) ^ ((Key[2]>>25)&1); rightkey[11]=((Key[1]>>25)&1) ^ ((Key[3]>>24)&1); fprintf(f,"right key:"); printf("right key:"); for(i=0;i<12;i++) { if(rightkey[i]) { fprintf(f,"1"); printf("1"); } else { fprintf(f,"0"); printf("0"); } } fprintf(f,"\n"); printf("\n"); KeccakInitialize(); for(j=0;j<4;j++){ FinalState[j]=0; } for(j=0;j<12;j++){ tempkey[j]=rightkey[j]; } fprintf(f,"temp key:"); printf("temp key:"); for(j=0;j<12;j++) { if(tempkey[j]) { fprintf(f,"1"); printf("1"); } else { fprintf(f,"1"); printf("0"); } } fprintf(f,"\n"); printf("\n"); //give the value for dynamic value temp=(InitialState[1]>>24)&1; temp1=(tempkey[0]&1) ^ ((InitialState[4]>>25)&1) ^ ((InitialState[9]>>25)&1) ^ ((InitialState[10]>>25)&1) ^ ((InitialState[11]>>24)&1) ^ ((InitialState[14]>>25)&1) ^ ((InitialState[16]>>24)&1) ^ ((InitialState[19]>>25)&1) ^ ((InitialState[21]>>24)&1) ^ ((InitialState[24]>>25)&1) ^ 1; if(temp!=temp1) { InitialState[1]^=(UINT32)0x1<<24; } temp=(InitialState[1]>>31)&1; temp1=(tempkey[1]&1) ^ ((InitialState[3]>>30)&1) ^ ((InitialState[8]>>30)&1) ^ ((InitialState[11]>>31)&1) ^ ((InitialState[13]>>30)&1) ^ ((InitialState[16]>>31)&1) ^ ((InitialState[22]>>31)&1) ^ ((InitialState[23]>>30)&1) ^ 1; if(temp!=temp1) { InitialState[1]^=(UINT32)0x1<<31; } temp=(InitialState[1]>>19)&1; temp1=(tempkey[2]&1) ^ ((InitialState[3]>>18)&1) ^ ((InitialState[7]>>19)&1) ^ ((InitialState[8]>>18)&1) ^ ((InitialState[11]>>19)&1) ^ ((InitialState[13]>>18)&1) ^ ((InitialState[16]>>19)&1) ^ ((InitialState[21]>>19)&1) ^ ((InitialState[23]>>18)&1) ^ 1; if(temp!=temp1) { InitialState[1]^=(UINT32)0x1<<19; } temp=(InitialState[5]>>16)&1; temp1=(tempkey[3]&1) ^ ((InitialState[10]>>16)&1) ^ ((InitialState[13]>>17)&1) ^ ((InitialState[15]>>16)&1) ^ ((InitialState[19]>>17)&1) ^ ((InitialState[20]>>16)&1) ^ ((InitialState[23]>>17)&1); if(temp!=temp1) { InitialState[5]^=(UINT32)0x1<<16; } temp=(InitialState[5]>>13)&1; temp1=(tempkey[4]&1) ^ ((InitialState[10]>>13)&1) ^ ((InitialState[11]>>13)&1) ^ ((InitialState[15]>>13)&1) ^ ((InitialState[17]>>12)&1) ^ ((InitialState[20]>>13)&1) ^ ((InitialState[22]>>12)&1); if(temp!=temp1) { InitialState[5]^=(UINT32)0x1<<13; } temp=(InitialState[1]>>20)&1; temp1=(tempkey[5]&1) ^ ((InitialState[4]>>21)&1) ^ ((InitialState[5]>>21)&1) ^ ((InitialState[9]>>21)&1) ^ ((InitialState[11]>>20)&1) ^ ((InitialState[14]>>21)&1) ^ ((InitialState[16]>>20)&1) ^ ((InitialState[19]>>21)&1) ^ ((InitialState[21]>>20)&1) ^ ((InitialState[24]>>21)&1) ^ 1; if(temp!=temp1) { InitialState[1]^=(UINT32)0x1<<20; } temp=(InitialState[1]>>10)&1; temp1=(tempkey[6]&1) ^ ((InitialState[3]>>9)&1) ^ ((InitialState[8]>>9)&1) ^ ((InitialState[11]>>10)&1) ^ ((InitialState[13]>>9)&1) ^ ((InitialState[16]>>10)&1) ^ ((InitialState[17]>>10)&1) ^ ((InitialState[21]>>10)&1) ^ ((InitialState[23]>>9)&1); if(temp!=temp1) { InitialState[1]^=(UINT32)0x1<<10; } temp=(InitialState[5]>>27)&1; temp1=(tempkey[7]&1) ^ ((InitialState[3]>>28)&1) ^ ((InitialState[4]>>28)&1) ^ ((InitialState[8]>>28)&1) ^ ((InitialState[10]>>27)&1) ^ ((InitialState[13]>>28)&1) ^ ((InitialState[15]>>27)&1) ^ ((InitialState[20]>>27)&1) ^ ((InitialState[23]>>28)&1) ^ 1; if(temp!=temp1) { InitialState[5]^=(UINT32)0x1<<27; } temp=(InitialState[5]>>15)&1; temp1=(tempkey[8]&1) ^ ((InitialState[3]>>16)&1) ^ ((InitialState[8]>>16)&1) ^ ((InitialState[13]>>16)&1) ^ ((InitialState[14]>>16)&1) ^ ((InitialState[20]>>15)&1) ^ ((InitialState[23]>>16)&1); if(temp!=temp1) { InitialState[5]^=(UINT32)0x1<<15; } temp=(InitialState[5]>>20)&1; temp1=(tempkey[9]&1) ^ ((InitialState[10]>>20)&1) ^ ((InitialState[13]>>21)&1) ^ ((InitialState[14]>>21)&1) ^ ((InitialState[15]>>20)&1) ^ ((InitialState[20]>>20)&1) ^ ((InitialState[23]>>21)&1) ^ 1; if(temp!=temp1) { InitialState[5]^=(UINT32)0x1<<20; } temp=(InitialState[5]>>26)&1; temp1=(tempkey[10]&1) ^ ((InitialState[2]>>25)&1) ^ ((InitialState[7]>>25)&1) ^ ((InitialState[10]>>26)&1) ^ ((InitialState[15]>>26)&1) ^ ((InitialState[17]>>25)&1) ^ ((InitialState[20]>>26)&1) ^ ((InitialState[21]>>26)&1) ^ ((InitialState[22]>>25)&1); if(temp!=temp1) { InitialState[5]^=(UINT32)0x1<<26; } temp=(InitialState[1]>>25)&1; temp1=(tempkey[11]&1) ^ ((InitialState[2]>>25)&1) ^ ((InitialState[3]>>24)&1) ^ ((InitialState[8]>>24)&1) ^ ((InitialState[11]>>25)&1) ^ ((InitialState[13]>>24)&1) ^ ((InitialState[16]>>25)&1) ^ ((InitialState[21]>>25)&1) ^ ((InitialState[23]>>24)&1) ^ 1; if(temp!=temp1) { InitialState[1]^=(UINT32)0x1<<25; } //displaystate(InitialState); for(j=0;j<(UINT64(1)<<32);j++)//initialize tempstate { for(k=0;k<25;k++)//fresh the tempstate for the key and initial value { TempState[k]=InitialState[k]; } //give the value for cube variables temp1=j&1; for(k=0;k<6;k++){ TempState[index0[0][k]]^=UINT32(temp1)<<index0[1][k]; } for(k=1;k<32;k++) { temp1=(j>>k)&1; if(temp1){ TempState[index[0][k-1]]|=UINT32(1)<<index[1][k-1]; TempState[index[0][k-1]+5]|=UINT32(1)<<index[1][k-1]; } else{ TempState[index[0][k-1]]&=(~(UINT32(1)<<index[1][k-1])); TempState[index[0][k-1]+5]&=(~(UINT32(1)<<index[1][k-1])); } } KeccakPermutationOnWords((UINT32 *)TempState); for(k=0;k<4;k++){ FinalState[k]^=TempState[6*k]; } } fprintf(f,"\n"); printf("\n"); fprintf(f,"cube sum: %llx,\t%llx\n",FinalState[0],FinalState[1],FinalState[2],FinalState[3]); printf("cube sum: %llx,\t%llx\n",FinalState[0],FinalState[1],FinalState[2],FinalState[3]); if(FinalState[0]==0 && FinalState[1]==0 && FinalState[2]==0 && FinalState[3]==0) { fprintf(f,"zero cube sum, temp key is right key"); printf("zero cube sum, temp key is right key"); } else{ fprintf(f,"nonzero cube sum, temp key is wrong key"); printf("nonzero cube sum, temp key is wrong key"); } fclose(f); finish = clock(); printf("time=%f\n",(double)(finish-start)/CLK_TCK); printf("Done!\n"); getch(); return 0; }
7a0a618dccfc52140bfb782f69d59bd34ff57b9d
8ae6b1b46d56ed9a221ac498a3a67a655159b83a
/flexc++/pattern/interval.cc
d430a1114dd4853cd76e3fb72e3a71da82196115
[]
no_license
ajunlonglive/flexcpp
decc3baa645ddfe6f455291c110d3250ba9c18bf
2de6b90d79d930152f767bf0117a8d2b26a11e12
refs/heads/master
2023-03-16T11:32:46.610788
2018-06-25T12:45:38
2018-06-25T12:45:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,389
cc
interval.cc
#include "pattern.ih" Pattern Pattern::interval(States &states, Pattern &regex, Interval const &interval) { Pattern ret; size_t lower = interval.lower(); size_t upper = interval.upper(); if (lower == 0) { switch (upper) { case 0: wmsg << "ignoring regex{0, 0}" << endl; return regex; case 1: ret = questionMark(states, regex); break; case numeric_limits<size_t>::max(): ret = star(states, regex); break; default: // {0, x}, with 1 < x < size_t::max { Interval oneUp(1, upper); Pattern tmp = Pattern::interval(states, regex, oneUp); ret = questionMark(states, tmp); } break; } } else if (lower == 1 && upper == max<size_t>()) ret = plus(states, regex); else if (lower <= upper) { ret = copy(states, regex, lower, upper); if (lower == upper && regex.fixedLength()) ret.d_length = lower * regex.d_length; } else { Pair pair = states.next2(); states[pair.first] = State(EMPTY, pair.second, 0); ret = Pattern(pair); } return ret; }
cf3a23a059e5b665b50c0ff9b0031ed011ee1928
9bc2462106be4df51f31e44e28ea6a78b42a3deb
/2019_05_19/a/src.cpp
5371569bca12fadb291d53355bc692469d98c495
[]
no_license
ysuzuki19/atcoder
4c8128c8a7c7ed10fc5684b1157ab5513ba9c32e
0fbe0e41953144f24197b4dcd623ff04ef5bc4e4
refs/heads/master
2021-08-14T19:35:45.660024
2021-07-31T13:40:39
2021-07-31T13:40:39
178,597,227
0
0
null
null
null
null
UTF-8
C++
false
false
185
cpp
src.cpp
#include <bits/stdc++.h> using namespace std; int main(){ int i, j; int N, K; cin >> N >> K; string S; cin >> S; S[K-1] = S[K-1] + 0x20; cout << S << endl; return 0; }
ab51500e83d64019f33e9f409b176b3ac1743de4
3e1551295154d40d22c5e94b421ed3b1c3f32fcc
/课程设计/8随机文件读写/8随机文件读写/file.h
8eb903177b90462272aea2483d601738bfbb6453
[]
no_license
letusget/Cplusplus_work
2cdd81a029839c1fa530ea86e20818576b884333
24590a90dd4afe8081744084b40511710f674490
refs/heads/master
2023-06-01T01:58:25.726968
2021-07-02T15:37:42
2021-07-02T15:37:42
373,537,522
1
0
null
null
null
null
GB18030
C++
false
false
395
h
file.h
#pragma once #include <iostream> #include <string> #include <vector> #include <map> #include <fstream> using namespace std; class ReadFile { public: //获取文章数据 map<int, vector<string>>mFile; //存放文件名 map<int, string>mFileName; //构造函数 ReadFile(); //读取文件 void read(); //重载操作符,实现从数据文件随机读写 void operator[](int i); };
7639fe60ec1c90f0e67bbd46e651e4271459c8e6
42d643419562048f585ea7d78caac0e8726d93cd
/llm_dct.cc
f06ae726489474c6fc93ad11b4da3847970e5913
[]
no_license
mypopydev/dct
00e4fdb877f18151139f2548b7b7f2bb311662db
df802d0436e32456ceb90e4a6257764ac9ccd222
refs/heads/master
2023-05-06T19:23:24.761827
2021-06-05T07:39:55
2021-06-05T07:39:55
373,781,709
0
2
null
null
null
null
UTF-8
C++
false
false
3,865
cc
llm_dct.cc
// https://unix4lyfe.org/dct-1d/ #include <cmath> // Implementation of LLM DCT. void llm_dct(const double in[8], double out[8]) { // Constants: const double s1 = sin(1. * M_PI / 16.); const double c1 = cos(1. * M_PI / 16.); const double s3 = sin(3. * M_PI / 16.); const double c3 = cos(3. * M_PI / 16.); const double r2s6 = sqrt(2.) * sin(6. * M_PI / 16.); const double r2c6 = sqrt(2.) * cos(6. * M_PI / 16.); // After stage 1: const double s1_0 = in[0] + in[7]; const double s1_1 = in[1] + in[6]; const double s1_2 = in[2] + in[5]; const double s1_3 = in[3] + in[4]; const double s1_4 = -in[4] + in[3]; const double s1_5 = -in[5] + in[2]; const double s1_6 = -in[6] + in[1]; const double s1_7 = -in[7] + in[0]; // After stage 2: const double s2_0 = s1_0 + s1_3; const double s2_1 = s1_1 + s1_2; const double s2_2 = -s1_2 + s1_1; const double s2_3 = -s1_3 + s1_0; const double z1 = c3 * (s1_7 + s1_4); const double s2_4 = ( s3-c3) * s1_7 + z1; const double s2_7 = (-s3-c3) * s1_4 + z1; const double z2 = c1 * (s1_6 + s1_5); const double s2_5 = ( s1-c1) * s1_6 + z2; const double s2_6 = (-s1-c1) * s1_5 + z2; // After stage 3: const double s3_0 = s2_0 + s2_1; const double s3_1 = -s2_1 + s2_0; const double z3 = r2c6 * (s2_3 + s2_2); const double s3_2 = ( r2s6-r2c6) * s2_3 + z3; const double s3_3 = (-r2s6-r2c6) * s2_2 + z3; const double s3_4 = s2_4 + s2_6; const double s3_5 = -s2_5 + s2_7; const double s3_6 = -s2_6 + s2_4; const double s3_7 = s2_7 + s2_5; // After stage 4: const double s4_4 = -s3_4 + s3_7; const double s4_5 = s3_5 * sqrt(2.); const double s4_6 = s3_6 * sqrt(2.); const double s4_7 = s3_7 + s3_4; // Shuffle and scaling: out[0] = s3_0 / sqrt(8.); out[4] = s3_1 / sqrt(8.); out[2] = s3_2 / sqrt(8.); out[6] = s3_3 / sqrt(8.); out[7] = s4_4 / sqrt(8.); out[3] = s4_5 / sqrt(8.); // Alternative: s3_5 / 2 out[5] = s4_6 / sqrt(8.); out[1] = s4_7 / sqrt(8.); } #if 0 // Naive implementation of LLM DCT. // Easier to read, but uses more multiplications for rotation. void llm_dct(const double in[8], double out[8]) { // After stage 1: const double s1_0 = in[0] + in[7]; const double s1_1 = in[1] + in[6]; const double s1_2 = in[2] + in[5]; const double s1_3 = in[3] + in[4]; const double s1_4 = -in[4] + in[3]; const double s1_5 = -in[5] + in[2]; const double s1_6 = -in[6] + in[1]; const double s1_7 = -in[7] + in[0]; // After stage 2: const double s2_0 = s1_0 + s1_3; const double s2_1 = s1_1 + s1_2; const double s2_2 = -s1_2 + s1_1; const double s2_3 = -s1_3 + s1_0; const double s2_4 = s1_4 * cos(3. * M_PI / 16.) + s1_7 * sin(3. * M_PI / 16.); const double s2_7 = -s1_4 * sin(3. * M_PI / 16.) + s1_7 * cos(3. * M_PI / 16.); const double s2_5 = s1_5 * cos(1. * M_PI / 16.) + s1_6 * sin(1. * M_PI / 16.); const double s2_6 = -s1_5 * sin(1. * M_PI / 16.) + s1_6 * cos(1. * M_PI / 16.); // After stage 3: const double s3_0 = s2_0 + s2_1; const double s3_1 = -s2_1 + s2_0; const double s3_2 = sqrt(2.) * ( s2_2 * cos(6. * M_PI / 16.) + s2_3 * sin(6. * M_PI / 16.)); const double s3_3 = sqrt(2.) * (-s2_2 * sin(6. * M_PI / 16.) + s2_3 * cos(6. * M_PI / 16.)); const double s3_4 = s2_4 + s2_6; const double s3_5 = -s2_5 + s2_7; const double s3_6 = -s2_6 + s2_4; const double s3_7 = s2_7 + s2_5; // After stage 4: const double s4_4 = -s3_4 + s3_7; const double s4_5 = s3_5 * sqrt(2.); const double s4_6 = s3_6 * sqrt(2.); const double s4_7 = s3_7 + s3_4; // Shuffle and scaling: out[0] = s3_0 / sqrt(8.); out[4] = s3_1 / sqrt(8.); out[2] = s3_2 / sqrt(8.); out[6] = s3_3 / sqrt(8.); out[7] = s4_4 / sqrt(8.); out[3] = s4_5 / sqrt(8.); out[5] = s4_6 / sqrt(8.); out[1] = s4_7 / sqrt(8.); } #endif // vim:set ts=2 sw=2 et:
062aa8b7b5ef2a64c0114acfab7ea7e9d51e7136
4fd97ff64e457d41820348aebaea704ca4abc48b
/src/plugins/legacy/meshMapping/meshMappingPlugin.cpp
700afd4a1b8dbabb2e950d1640bde3bc08e1c20d
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Florent2305/medInria-public
c075b2064b2fe96081197ce300777be5be18a339
595a2ce62c8864c4ecb8acbf0d50e32aa734ed8f
refs/heads/master
2023-08-08T00:41:51.671245
2023-04-12T07:46:33
2023-04-12T07:46:33
98,999,842
1
1
BSD-4-Clause
2021-05-31T08:38:28
2017-08-01T12:39:01
C++
UTF-8
C++
false
false
1,977
cpp
meshMappingPlugin.cpp
/*========================================================================= medInria Copyright (c) INRIA 2013 - 2019. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include <meshMapping.h> #include <meshMappingPlugin.h> #include <meshMappingToolBox.h> meshMappingPlugin::meshMappingPlugin(QObject *parent) : medPluginLegacy(parent) { } bool meshMappingPlugin::initialize() { if(!meshMapping::registered()) { qWarning() << "Unable to register meshMapping type"; } if ( !meshMappingToolBox::registered() ) { qWarning() << "Unable to register meshMapping toolbox"; } return true; } QString meshMappingPlugin::name() const { return "Mesh Mapping"; } QString meshMappingPlugin::description() const { QString description; description += "<h1>Mesh Mapping Tutorial</h1>"; description += "Sample data values at specified point locations on a mesh. "; description += "It keeps the intersection of the mesh and the data, and set these values to the mesh."; description += "<ul>"; description += "<li>Drop a mesh and a data in the view.</li>"; description += "<li>Select the data (from which to obtain values) in the parameters of the toolbox.</li>"; description += "<li>Select the mesh (whose geometry will be used to determine positions to map) in the parameters of the toolbox.</li>"; description += "<li>When you are ready, click on 'Run'.</li>"; description += "</ul>"; description += "This plugin uses the VTK library: https://vtk.org"; return description; } QString meshMappingPlugin::version() const { return MESHMAPPINGPLUGIN_VERSION; } QStringList meshMappingPlugin::types() const { return QStringList() << "meshMapping"; }
5d0a36138e28fdc280426a2525226c5bd4a7eb02
05ba6be9793ba2d9a6507dbaa8ae17561a864f30
/kwm/space.cpp
6d178f4ce143eaa258b9c5912deaa1657cdd35bf
[ "MIT" ]
permissive
acarlson1029/kwm
c3a07aa8e12039dec0469cd8362408674c677781
3554ebf4fb9203536f34c823408a907885b261a6
refs/heads/master
2020-04-08T14:31:23.921002
2016-03-01T09:09:14
2016-03-01T09:09:14
52,635,532
0
0
null
2016-02-26T22:01:07
2016-02-26T22:01:07
null
UTF-8
C++
false
false
6,944
cpp
space.cpp
#include "space.h" #include "display.h" #include "window.h" #include "tree.h" #include "border.h" extern kwm_screen KWMScreen; extern kwm_focus KWMFocus; extern kwm_toggles KWMToggles; extern kwm_mode KWMMode; extern kwm_thread KWMThread; extern kwm_border FocusedBorder; extern kwm_border MarkedBorder; void GetTagForMonocleSpace(space_info *Space, std::string &Tag) { tree_node *Node = Space->RootNode; bool FoundFocusedWindow = false; int FocusedIndex = 0; int NumberOfWindows = 0; if(Node && KWMFocus.Window) { FocusedIndex = 1; NumberOfWindows = 1; if(Node->WindowID == KWMFocus.Window->WID) FoundFocusedWindow = true; while(Node->RightChild) { if(Node->WindowID == KWMFocus.Window->WID) FoundFocusedWindow = true; if(!FoundFocusedWindow) ++FocusedIndex; ++NumberOfWindows; Node = Node->RightChild; } if(Node->WindowID == KWMFocus.Window->WID) FoundFocusedWindow = true; } if(FoundFocusedWindow) Tag = "[" + std::to_string(FocusedIndex) + "/" + std::to_string(NumberOfWindows) + "]"; else Tag = "[" + std::to_string(NumberOfWindows) + "]"; } void GetTagForCurrentSpace(std::string &Tag) { if(IsSpaceInitializedForScreen(KWMScreen.Current)) { space_info *Space = GetActiveSpaceOfScreen(KWMScreen.Current); if(Space->Mode == SpaceModeBSP) Tag = "[bsp]"; else if(Space->Mode == SpaceModeFloating) Tag = "[float]"; else if(Space->Mode == SpaceModeMonocle) GetTagForMonocleSpace(Space, Tag); } else { if(KWMMode.Space == SpaceModeBSP) Tag = "[bsp]"; else if(KWMMode.Space == SpaceModeFloating) Tag = "[float]"; else if(KWMMode.Space == SpaceModeMonocle) Tag = "[monocle]"; } } bool IsActiveSpaceFloating() { return IsSpaceFloating(KWMScreen.Current->ActiveSpace); } bool IsSpaceFloating(int SpaceID) { bool Result = false; if(IsSpaceInitializedForScreen(KWMScreen.Current)) { std::map<int, space_info>::iterator It = KWMScreen.Current->Space.find(SpaceID); if(It != KWMScreen.Current->Space.end()) Result = KWMScreen.Current->Space[SpaceID].Mode == SpaceModeFloating; } return Result; } space_info *GetActiveSpaceOfScreen(screen_info *Screen) { space_info *Space = NULL; std::map<int, space_info>::iterator It = Screen->Space.find(Screen->ActiveSpace); if(It == Screen->Space.end()) { space_info Clear = {{0}}; Screen->Space[Screen->ActiveSpace] = Clear; Space = &Screen->Space[Screen->ActiveSpace]; } else { Space = &Screen->Space[Screen->ActiveSpace]; } return Space; } bool IsSpaceInitializedForScreen(screen_info *Screen) { if(!Screen) return false; std::map<int, space_info>::iterator It = Screen->Space.find(Screen->ActiveSpace); if(It == Screen->Space.end()) return false; else return It->second.Initialized; } bool DoesSpaceExistInMapOfScreen(screen_info *Screen) { if(!Screen) return false; std::map<int, space_info>::iterator It = Screen->Space.find(Screen->ActiveSpace); if(It == Screen->Space.end()) return false; else return It->second.RootNode != NULL && It->second.Initialized; } bool IsSpaceTransitionInProgress() { if(KWMScreen.Transitioning) return true; Assert(KWMScreen.Current, "IsSpaceTransitionInProgress()") if(!KWMScreen.Current->Identifier) KWMScreen.Current->Identifier = GetDisplayIdentifier(KWMScreen.Current); bool Result = CGSManagedDisplayIsAnimating(CGSDefaultConnection, KWMScreen.Current->Identifier); if(Result) { DEBUG("IsSpaceTransitionInProgress() Space transition detected") KWMScreen.Transitioning = true; ClearFocusedWindow(); ClearMarkedWindow(); } return Result; } bool IsActiveSpaceManaged() { space_info *Space = GetActiveSpaceOfScreen(KWMScreen.Current); return Space->Managed; } void ShouldActiveSpaceBeManaged() { space_info *Space = GetActiveSpaceOfScreen(KWMScreen.Current); Space->Managed = CGSSpaceGetType(CGSDefaultConnection, KWMScreen.Current->ActiveSpace) == CGSSpaceTypeUser; } void FloatFocusedSpace() { if(KWMToggles.EnableTilingMode && !IsSpaceTransitionInProgress() && IsActiveSpaceManaged()) { space_info *Space = GetActiveSpaceOfScreen(KWMScreen.Current); if(Space->Mode == SpaceModeFloating) return; DestroyNodeTree(Space->RootNode, Space->Mode); Space->RootNode = NULL; Space->Mode = SpaceModeFloating; Space->Initialized = true; ClearFocusedWindow(); } } void TileFocusedSpace(space_tiling_option Mode) { if(KWMToggles.EnableTilingMode && !IsSpaceTransitionInProgress() && IsActiveSpaceManaged() && FilterWindowList(KWMScreen.Current)) { space_info *Space = GetActiveSpaceOfScreen(KWMScreen.Current); if(Space->Mode == Mode) return; DestroyNodeTree(Space->RootNode, Space->Mode); Space->RootNode = NULL; Space->Mode = Mode; std::vector<window_info*> WindowsOnDisplay = GetAllWindowsOnDisplay(KWMScreen.Current->ID); CreateWindowNodeTree(KWMScreen.Current, &WindowsOnDisplay); } } void ToggleFocusedSpaceFloating() { if(!IsSpaceFloating(KWMScreen.Current->ActiveSpace)) FloatFocusedSpace(); else TileFocusedSpace(SpaceModeBSP); } void UpdateActiveSpace() { pthread_mutex_lock(&KWMThread.Lock); Assert(KWMScreen.Current, "UpdateActiveSpace()") KWMScreen.Transitioning = false; KWMScreen.PrevSpace = KWMScreen.Current->ActiveSpace; KWMScreen.Current->ActiveSpace = GetActiveSpaceOfDisplay(KWMScreen.Current); ShouldActiveSpaceBeManaged(); if(KWMScreen.PrevSpace != KWMScreen.Current->ActiveSpace) { DEBUG("UpdateActiveSpace() Space transition ended " << KWMScreen.PrevSpace << " -> " << KWMScreen.Current->ActiveSpace) KWMScreen.ForceRefreshFocus = true; UpdateActiveWindowList(KWMScreen.Current); space_info *Space = GetActiveSpaceOfScreen(KWMScreen.Current); if(Space->FocusedNode) { SetWindowFocusByNode(Space->FocusedNode); MoveCursorToCenterOfFocusedWindow(); } else if(Space->Mode != SpaceModeFloating) { if(IsAnyWindowBelowCursor() && KWMMode.Focus != FocusModeDisabled) FocusWindowBelowCursor(); else if(FocusWindowOfOSX()) MoveCursorToCenterOfFocusedWindow(); } KWMScreen.ForceRefreshFocus = false; } pthread_mutex_unlock(&KWMThread.Lock); }
7d116da9caafc090827d4a4d6b1b9b9e67c8ad0f
bbeac306f87b85d31b163d9e0673d5fb24f47f39
/punteros-ej2.cpp
88986d18a8a00378f99d792d68d6cf8d59650d05
[]
no_license
programacion-desde-cero/Ejemplos
d24ba4e28f2e17d150488437fe7e70cfdcffc821
c7b13e8eb4afe8305739e5e21cd2e7fe49ba153b
refs/heads/master
2021-06-25T08:13:15.227092
2021-03-22T11:51:09
2021-03-22T11:51:09
202,524,811
13
23
null
2020-08-30T23:02:40
2019-08-15T10:53:27
C++
UTF-8
C++
false
false
1,016
cpp
punteros-ej2.cpp
/* ---------------- /* Este ejemplo corresponde al video sobre punteros: https://www.youtube.com/watch?v=s8T7cPnYrz0 /* Ejecución del código paso a paso: http://pythontutor.com/cpp.html#code=%23include%20%3Ciostream%3E%0A%23include%20%3Cstring%3E%0Ausing%20namespace%20std%3B%0A%0Aint%20main%28%29%20%7B%0A%20%20string%20saludo%20%3D%20%22hola%22%3B%0A%20%20string*%20p%20%3D%20%26saludo%3B%0A%20%20cout%20%3C%3C%20p%20%3C%3C%20endl%3B%0A%20%20cout%20%3C%3C%20*p%20%3C%3C%20endl%3B%0A%20%20*p%20%3D%20%22amo%20programar%22%3B%0A%20%20cout%20%3C%3C%20*p%20%3C%3C%20endl%3B%0A%20%20cout%20%3C%3C%20saludo%20%3C%3C%20endl%3B%0A%20%20%0A%20%20return%200%3B%0A%7D&curInstr=0&mode=display&origin=opt-frontend.js&py=cpp&rawInputLstJSON=%5B%5D ------------------- */ #include <iostream> #include <string> using namespace std; int main() { string saludo = "hola"; string* p = &saludo; cout << p << endl; cout << *p << endl; *p = "amo programar"; cout << *p << endl; cout << saludo << endl; return 0; }
6d1a065ac53476db423292341e52deb3028a02bd
9cf4270a3adac89e49b18e534648e9e7bf500f55
/SHM#2/ProgramFiles/Player.cpp
e92845cd1b0d14d017950c9f5b6c9b7892d336db
[]
no_license
BarTes8/MaciejSalamonski
e1bd303cf4bc1c25ea5f3d2d1c57c0681173ef41
c14cc54dfe2912bb56d2d2ca9280f9822f51f63e
refs/heads/master
2023-03-09T09:49:46.025498
2021-02-10T17:26:14
2021-02-10T17:26:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,341
cpp
Player.cpp
#include "Player.hpp" Player::Player(std::shared_ptr<Ship> ship, uint16_t money, uint16_t availableSpace) : ship_(ship), money_(money), availableSpace_(availableSpace) {} std::shared_ptr<Ship> Player::getShip() const { return ship_; } uint16_t Player::getMoney() const { return money_; } uint16_t Player::getAvailableSpace() const { return availableSpace_; } uint16_t Player::getSpeed() const { return ship_->getSpeed(); } std::shared_ptr<Cargo> Player::getCargo(uint16_t index) const { return ship_->getCargo(index); } void Player::updateAvailableSpace() { uint16_t space = ship_->getCapacity(); for (const auto& cargo : ship_->getCargos()) { if (space > cargo->getAmount()) { space -= cargo->getAmount(); } else { availableSpace_ = 0; return; } } availableSpace_ = space; } void Player::setMoney(uint16_t money) { money_ = money; } void Player::payCrew(uint16_t money) { if (money_ > money) { money_ -= money; return; } money_ = 0; } void Player::loadCargoOnShip(std::shared_ptr<Cargo> cargo) { ship_->load(cargo); updateAvailableSpace(); } void Player::unloadCargoFromShip(std::shared_ptr<Cargo> cargo, uint16_t amount) { ship_->unload(cargo, amount); updateAvailableSpace(); }
9783756dbaa6da1fe2a1b3ce93d066d8a0c8c0cf
e034278570555d2be24d7852a856ffc14466fc77
/Testing/UnitTests/enigmaTest.cpp
b9bea404935c6948cbd8cc62dfcc770b46818e6c
[]
no_license
Toyohara01/ChatRoom
0592b7647b3f1e61bb428f68ec28af55200a4f60
22197046f6db624fef6b175346d567de9f0c2f3a
refs/heads/master
2022-10-28T23:11:55.704289
2020-01-19T22:17:46
2020-01-19T22:17:46
271,136,133
0
0
null
null
null
null
UTF-8
C++
false
false
2,492
cpp
enigmaTest.cpp
/****************************************************************************** * enigmaTest.cpp * * Test driver for the Crypto module, runs a user specified number of test * * cases in which a random string is generated, encryped and decrypted. * * * * Author: Lukas DeLong * * Spring 2019 * * SE420/SE310 * *******************************************************************************/ #include "../../Crypto.hpp" #include <iostream> #include <random> #include <cstdlib> #include <string> #include <ctime> using namespace std; void gen_random(char *s, const int len); int main() { //instantiate enigma objects Enigma encryptObj; Enigma decryptObj; //declare variables string encText, decText; char testText[2048]; int pass=0, fail=0, testNum=0, i=0; double avgTime=0; cout << "Enter number of tests: "; cin >> testNum; for(i=0;i<testNum;i++) { gen_random(testText, 2047); cout << "Test text is: " << testText << endl << endl; clock_t start = clock(); //encrypt string and display ciphertext encText = encryptObj.callEncrypt(testText); cout << "Encrypted text is: " + encText << endl << endl; //decrypt string and display plaintext decText = decryptObj.callDecrypt(encText); cout << "Decrypted text is: " + decText << endl << endl; clock_t end = clock(); avgTime = (avgTime + double(end - start))/CLOCKS_PER_SEC; //if the input string is not equal to the decrypted string if(testText != decText) { fail++; } //otherwise the strings are equal to eachother else { pass++; } } avgTime = avgTime/testNum; cout << pass << " successes" << endl; cout << fail << " failures" << endl; cout << "Average time(s) to execute: " << avgTime << endl; } void gen_random(char *s, const int len) { static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ "; for (int i = 0; i < len; ++i) { s[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; } s[len] = 0; }
204c057accde49c0c5ccce0f940a8bae47088c30
38bdfe2722abac8d3a3bb0dafed42791d6fbbef4
/StudentActivity.cpp
815eb42ddd48967a4ea62734f2aab0aada3e9941
[]
no_license
abe-mused/student-activities
4df52e56a0ea85f351061a82767a5ac3a4cafdae
6c8b40fcfd70045cfcf02c871b1a816faf250575
refs/heads/master
2022-12-29T04:44:06.288794
2020-10-19T22:32:16
2020-10-19T22:32:16
305,528,489
0
0
null
null
null
null
UTF-8
C++
false
false
1,337
cpp
StudentActivity.cpp
#include "StudentActivity.h" #include <iostream> #include <iomanip> #include <string> using namespace std; StudentActivity::StudentActivity(string sportName, double sportFee, string clubOneName, string clubOneMettingDay, string clubTwoName, string clubTwoMettingDay, int studentId, string studentName): sport(sportName, sportFee), clubOne(clubOneName, clubOneMettingDay), clubTwo(clubTwoName, clubTwoMettingDay){ this->studentId = studentId; this->studentName = studentName; this->totalAmountDue = 0; } double StudentActivity::calcTotalDue(){ this->totalAmountDue += this->sport.getFee(); if(clubOne.getName() != "NONE") this->totalAmountDue += 55.5; if(clubTwo.getName() != "NONE") this->totalAmountDue += 35.5; return this->totalAmountDue; } void StudentActivity::displayActivities(){ cout<<setprecision(2)<<fixed; system("cls"); cout<<endl<<this->studentId<<" "<<this->studentName<<endl<<endl; if(sport.getName()!=""){ cout<<sport.getName()<<" $"<<sport.getFee()<<endl; } else { cout<<"you have not registered for any sports."<<endl; } if(clubOne.getName() != "NONE") cout<<clubOne.getName()<<" meets on "<<clubOne.getMeetingDay()<<endl; if(clubTwo.getName() != "NONE") cout<<clubTwo.getName()<<" meets on "<<clubTwo.getMeetingDay()<<endl; cout<<endl<<"total due is $"<<calcTotalDue()<<endl; }
4e5fbe8675866c0c93c637c60d838539f0649330
1bf1bec2a1439de2f53a955a527461235b654601
/Zumo32U4LEDs.h
6cb668d363d56d2f4b1acaf48eb081c6ea94154b
[ "MIT" ]
permissive
jeppefrandsen/zumo-32u4-arduino-library
a9d6ea718839642016b0a9525a6a7c3fafa8adf9
9756156895cca55344c0dcbfbcefa99b59c03573
refs/heads/master
2021-01-02T10:50:02.709401
2020-02-15T10:52:24
2020-02-15T10:52:24
240,090,651
0
0
NOASSERTION
2020-02-12T18:57:11
2020-02-12T18:57:10
null
UTF-8
C++
false
false
1,293
h
Zumo32U4LEDs.h
// Copyright Pololu Corporation. For more information, see http://www.pololu.com/ /*! \file Zumo32U4LEDs.h */ #pragma once #include <FastGPIO.h> /*! \brief Turns the red user LED (RX) on or off. The red user LED is on pin 17, which is also known as PB0, SS, and RXLED. The Arduino core code uses this LED to indicate when it receives data over USB, so it might be hard to control this LED when USB is connected. */ class Zumo32U4LEDRed { public: Zumo32U4LEDRed() = default; void on() { FastGPIO::Pin<17>::setOutput(false); } void off() { FastGPIO::Pin<17>::setOutput(true); } }; /*! \brief Turns the yellow user LED on pin 13 on or off. */ class Zumo32U4LEDYellow { public: Zumo32U4LEDYellow() = default; void on() { FastGPIO::Pin<13>::setOutput(true); } void off() { FastGPIO::Pin<13>::setOutput(false); } }; /*! \brief Turns the green user LED (TX) on or off. The green user LED is pin PD5, which is also known as TXLED. The Arduino core code uses this LED to indicate when it receives data over USB, so it might be hard to control this LED when USB is connected. */ class Zumo32U4LEDGreen { public: Zumo32U4LEDGreen() = default; void on() { FastGPIO::Pin<IO_D5>::setOutput(false); } void off() { FastGPIO::Pin<IO_D5>::setOutput(true); } };
f58d3b152d190dc74cd0ccf1a861ff320f87497e
320413f31bb959ae5902cb37dcb87dd977fd38ab
/spoj/ANARC05B.cpp
52f9f0a77d3cd7cbe2ad513064c8fda51c61d70c
[]
no_license
aquelemiguel/road-to-swerc
d74b0010f36ac5b078764d428211d97a2541683d
0f869865b1ea642db5a6a7d97aa5da25577c7606
refs/heads/master
2020-03-18T00:51:13.865042
2018-07-31T03:52:37
2018-07-31T03:52:37
134,115,863
3
2
null
null
null
null
UTF-8
C++
false
false
1,126
cpp
ANARC05B.cpp
#include <bits/stdc++.h> using namespace std; #define MAX 10000 int main() { ios::sync_with_stdio(0); // Input and output become more efficient. cin.tie(); int na, nb; int a[MAX], b[MAX]; while (true) { scanf("%d", &na); if (na == 0) break; int res = 0, sa = 0, sb = 0; for (int i = 0; i < na; i++) scanf("%d", &a[i]); scanf("%d", &nb); for (int i = 0; i < nb; i++) scanf("%d", &b[i]); int i, j; for (i = 0, j = 0; i < na && j < nb;) { if (a[i] < b[j]) { sa += a[i++]; } else if (a[i] > b[j]) { sb += b[j++]; } else { res += max(sa, sb) + a[i]; // a[i] is simply the intersection point. sa = 0, sb = 0; i++, j++; } } for (i; i < na; i++) // Iterate the possible remaining elements of the array. sa += a[i]; for (j; j < nb; j++) sb += b[j]; res += max(sa, sb); printf("%d\n", res); } }
b53f14374c181a14e728186ab1815f8a349d569f
63367295aef13e2d4d812dc71227631462a10605
/ConsoleApplication1/ConsoleApplication1/general_register.cpp
e67e20b582d055f4eba22b57118a895b710072f6
[]
no_license
daggerplusplus/OS-Group-Project
d2d7d41b7f58d58b36827dc7e1ad93e27cf40442
1e1311e9069a8314166a2712d13999710f75e456
refs/heads/master
2023-07-13T13:54:14.710744
2020-10-07T19:02:02
2020-10-07T19:02:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
362
cpp
general_register.cpp
#include "general_register.h" OSSim::general_register::general_register(){ content = 0; } OSSim::general_register::~general_register(){} int OSSim::general_register::get_content(){ return content; } void OSSim::general_register::set_content(int contents){ content = contents; } void OSSim::general_register::clear() { content = 0; }
92a06b548fcef09c3bb610bd8652f12a26c6bcb1
e875f4349e4bb8b75b88e0c80626bddf724abb34
/SmartVestArduino/sketch_smartvest_new.ino
3e19319ff33cacb25da3cc5d01e3ca17d9e85dbb
[]
no_license
nayoon-kim/SmartSafetyVest
c0b7601b138e3eb8134326ee257827ee5db1dd94
447cfbc50ac685e82ae79f824bf4c5e195cd5680
refs/heads/master
2023-08-27T19:31:58.680252
2021-10-31T15:08:06
2021-10-31T15:08:06
315,169,050
2
0
null
null
null
null
UTF-8
C++
false
false
8,557
ino
sketch_smartvest_new.ino
#include <SoftwareSerial.h> #define BT_RXD 9//수신 #define BT_TXD 8//전송 SoftwareSerial bluetooth(8, 9); //lcd #include <Wire.h> // i2C 통신을 위한 라이브러리 #include<LiquidCrystal_I2C.h> LiquidCrystal_I2C lcd(0x27,16,2); // 접근주소: 0x3F or 0x27 //온습도 #include <DHT.h> #define DHTPIN 2 //digtal ~2 pin #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); //gas #define MQ_PIN (A0) #define MQ_PIN_2 (A1) #define RL_VALUE (5) //define the load resistance on the board, in kilo ohms #define RO_CLEAN_AIR_FACTOR (9.83) #define GAS_LPG (0) #define GAS_CO (1) #define GAS_CH4 (2) #define CALIBARAION_SAMPLE_TIMES (50) //define how many samples you are going to take in the calibration phase #define CALIBRATION_SAMPLE_INTERVAL (100) //define the time interal(in milisecond) between each samples in the //cablibration phase #define READ_SAMPLE_INTERVAL (50) //define how many samples you are going to take in normal operation #define READ_SAMPLE_TIMES (5) //define the time interal(in milisecond) between each samples in float Ro=10; float Ro_2=10; const float LPGCurve[3] = {2.3,0.51,-0.40}; //2.3,0.51,-0.47 const float COCurve[3] = {2.3,0.72,-0.34};; const float CH4Curve[3] = {2.1,1.00,-0.20}; //1.8,1.15,-0.10 unsigned long previousMillis = 0; //이전시간 const long delayTime = 1000; //1초(1000) 대기시간 int moveNum=0; //GPS #include <TinyGPS++.h> TinyGPSPlus gps; //SoftwareSerial nss(3,4); long lat1=(35.523961)*10000.0L; //9 long lng1=(129.372504)*10000.0L; //4 float lat2=lat1/10000.0; float lng2=lng1/10000.0; int move_Num=0; char cmd='@'; char gas_cmd='@'; const PROGMEM int speakerpin = 12; const PROGMEM int red = 10; const PROGMEM int green = 11; const PROGMEM int blue = 13; const String id="7583033343935180B1E1"; String tt=""; boolean num=false; String name1=""; char gps_w='@'; char buffer1[2]={}; void setup(void) { //gas pinMode(MQ_PIN ,INPUT); pinMode(MQ_PIN_2 ,INPUT); Serial.begin(9600); //bluetooth bluetooth.begin(9600); //온습도 dht.begin(); Serial.println("power on!"); pinMode(red, OUTPUT); pinMode(green, OUTPUT); pinMode(blue, OUTPUT); //lcd lcd.init(); // LCD 초기화 // Print a message to the LCD. lcd.backlight(); // 백라이트 켜기 Ro=4.93; //already calculate Ro_2=5.14; ////GPS // nss.begin(9600); // nss.available(); } void loop(void) { Serial.println(analogRead(MQ_PIN)); Serial.println(analogRead(MQ_PIN_2)); previousMillis=millis(); char text; String arr=""; arr+=id+","; if(bluetooth.available()){ // BT –> Data –> Serial cmd=bluetooth.read(); if(cmd=='!'){ // Serial.readBytes(buffer1,2); Serial.println(cmd); } } if(num==false){ text=(char)cmd; if(text!='*'&&text!='@'&&text!='!'){ name1+=text; while(bluetooth.available()){ if(text!='*'&&text!='@'&&text!='!'){ text=(char)bluetooth.read(); name1+=text; delay(5); } } name1.trim(); Serial.println(name1); lcd.clear(); lcd.setCursor(0,0); lcd.print(name1); delay(10); num=true; } } if(gas_cmd=='*'){ tone(speakerpin,2000,1144); digitalWrite(blue, HIGH); digitalWrite(red, LOW); digitalWrite(green, LOW); }else if(cmd=='!'){ // tone(speakerpin,2000,1144); digitalWrite(red, HIGH); digitalWrite(green, LOW); digitalWrite(blue, LOW); cmd='@'; }else{ digitalWrite(red, LOW); digitalWrite(green, LOW); digitalWrite(blue, LOW); } //GPS //nss.listen(); // gps.encode(nss.read()); if (gps.location.isUpdated()){ lat2=gps.location.lat(); lng2=gps.location.lng(); } // if(move_Num%20<10){ // lat2-=0.00005; // lng2-=0.00015; // move_Num++; // }else if((move_Num%20)>=10&& (move_Num%20)<20){ // lat2+=0.00005; // lng2+=0.00015; // move_Num++; // } int leng=13; int moo=move_Num%leng; if(moo==1){ //안쪽 왼쪽위 2 lat2=35.524670; //35.524670, 129.372015 lng2=129.372015; }else if(moo==2){ //안쪽 왼쪽아래 3 lat2=35.523980; //35.523980, 129.371728 lng2=129.371728; }else if(moo<1){ //바깥 위 1 //35.524479, 129.372650 lat2=35.524479; lng2=129.372650; }else if(moo==3){ //바깥 4 35.523767, 129.372259 lat2=35.522780; lng2=129.371647; }else if(moo==4){ //바깥 5 35.523941, 129.372385 lat2=35.522058; lng2=129.370834; //35.521961, 129.371434 }else if(moo==7){ //바깥 6 lat2=35.521612; lng2=129.373076; }else if(moo==5){ //바깥 6-1 lat2=35.521961; lng2=129.371434; }else if(moo==6){ //바깥 6-2 lat2=35.521883; lng2=129.372164; }else if(moo==8){ //바깥 7 lat2=35.522433; lng2=129.373130; }else if(moo==9){ //바깥 7-1 lat2=35.522701; lng2=129.372547; } else if(moo==10){ //바깥 8 lat2=35.523496; lng2=129.372236; } else if(moo==11){ //바깥 9 lat2=35.524039; lng2=129.372389; }else{ lat2=35.524272; lng2=129.372649; } Serial.print(move_Num); move_Num++; String latt=""; String lngg=""; latt=String(lat2,5); lngg=String(lng2,5); arr+=latt+","+lngg+","; int ch4=MQGetGasPercentage(MQRead(MQ_PIN)/Ro,GAS_CH4); if(ch4<0||ch4>10000) ch4=10000; int lpg=MQGetGasPercentage(MQRead(MQ_PIN)/Ro,GAS_LPG); if(lpg<0||lpg>10000) lpg=10000; int co=MQGetGasPercentage(MQRead(MQ_PIN_2)/Ro_2,GAS_CO) ; if(co<0||co>10000) co=10000; Serial.print("CH4:"); Serial.print(ch4); Serial.print( "ppm" ); Serial.print(" "); Serial.print("LPG:"); Serial.print(lpg); Serial.print( "ppm" ); Serial.print(" "); Serial.print("CO:"); Serial.print(co); Serial.print( "ppm" ); Serial.print(" "); Serial.println(); arr=arr+String(ch4)+","+String(lpg)+","+String(co)+","; float h = dht.readHumidity(); //습도 float t = dht.readTemperature(); //온도 if (isnan(h) || isnan(t)) { Serial.println("Failed to read from DHT sensor!"); arr=arr+"24,38,"; }else{ arr+=String(t)+","+String(h)+","; } //좋음 0 주의 1 나쁨 2 if(ch4>1000){ arr+="2,"; }else if((ch4>500&&ch4<=1000)){ arr+="1,"; }else{ arr+="0,"; } if(lpg>70){ arr+="2,"; }else if((lpg>40 && lpg<=70)){ arr+="1,"; }else{ arr+="0,"; } if(co>1000 || co<0){ arr+="2,"; }else if((co>500 && co<=1000)){ arr+="1,"; }else{ arr+="0,"; } if(t>40 || t<0){ arr+="2,"; }else if((t>35 && h<=40)||(h>0&&h<10)){ arr+="1,"; }else{ arr+="0,"; } if(h>80 || h<10){ arr+="2,"; }else if((h>70 && h<=80)||(h>=10&&h<20)){ arr+="1,"; }else{ arr+="0,"; } if(ch4>1000|| lpg>70|| co>1000){ gas_cmd='*'; arr+="1"; }else{ gas_cmd='@'; arr+="0"; } Serial.println(arr); bluetooth.print(arr); bluetooth.println(); delay(100); unsigned long currentMillis = millis(); Serial.println(currentMillis-previousMillis); } float MQResistanceCalculation(int raw_adc) { return ( ((float)RL_VALUE*(1023-raw_adc)/raw_adc)); } float MQRead(int mq_pin) { int i; float rs=0; for (i=0;i<READ_SAMPLE_TIMES;i++) { rs += MQResistanceCalculation(analogRead(mq_pin)); delay(READ_SAMPLE_INTERVAL); } rs = rs/READ_SAMPLE_TIMES; return rs; } int MQGetGasPercentage(float rs_ro_ratio, int gas_id) { if ( gas_id == GAS_LPG ) { return MQGetPercentage(rs_ro_ratio,LPGCurve); } else if ( gas_id == GAS_CO ) { return MQGetPercentage(rs_ro_ratio,COCurve); } else { return MQGetPercentage(rs_ro_ratio,CH4Curve); } return 0; } int MQGetPercentage(float rs_ro_ratio, float *pcurve) { return (pow(10,( ((log(rs_ro_ratio)-pcurve[1])/pcurve[2]) + pcurve[0]))); }
766d7a9bdfd44d02fefecc924f5de559786730f9
d1f382dd8090791eca8813bc61d4829c43349a0e
/level1/12932.cpp
3cb3cdfe9df66606699ed70a43aff227a25070b4
[]
no_license
kangyeop/algorithm
0f12ac33acbfc6a7c20db300d51a1a22c0b0429b
d39587ad2b0832d86efcec70a1f2a4f5ec557cc9
refs/heads/master
2023-04-24T09:54:21.300288
2021-05-07T06:11:44
2021-05-07T06:11:44
308,500,889
2
0
null
null
null
null
UTF-8
C++
false
false
263
cpp
12932.cpp
#include <string> #include <vector> using namespace std; vector<int> solution(long long n) { string s = to_string(n); vector<int> answer; for (int i = s.size() - 1; i >= 0; i--) { answer.push_back(s[i] - '0'); } return answer; }
d3333bbf9619f47a178efb4240700809b78f0924
ac34cad5e20b8f46c0b0aa67df829f55ed90dcb6
/src/ballistica/scene_v1/node/sound_node.h
2ce642e73daf4e0adad6bd0f3664612d6be72339
[ "MIT" ]
permissive
sudo-logic/ballistica
fd3bf54a043717f874b71f4b2ccd551d61c65008
9aa73cd20941655e96b0e626017a7395ccb40062
refs/heads/master
2023-07-26T19:52:06.113981
2023-07-12T21:32:56
2023-07-12T21:37:46
262,056,617
0
0
null
null
null
null
UTF-8
C++
false
false
1,344
h
sound_node.h
// Released under the MIT License. See LICENSE for details. #ifndef BALLISTICA_SCENE_V1_NODE_SOUND_NODE_H_ #define BALLISTICA_SCENE_V1_NODE_SOUND_NODE_H_ #include <vector> #include "ballistica/scene_v1/node/node.h" namespace ballistica::scene_v1 { class SoundNode : public Node { public: static auto InitType() -> NodeType*; explicit SoundNode(Scene* scene); ~SoundNode() override; void Step() override; auto position() const -> const std::vector<float>& { return position_; } void SetPosition(const std::vector<float>& vals); auto volume() const -> float { return volume_; } void SetVolume(float val); auto positional() const -> bool { return positional_; } void SetPositional(bool val); auto music() const -> bool { return music_; } void SetMusic(bool val); auto loop() const -> bool { return loop_; } void SetLoop(bool val); auto sound() const -> SceneSound* { return sound_.Get(); } void SetSound(SceneSound* s); private: Object::Ref<SceneSound> sound_; millisecs_t last_position_update_time_{}; std::vector<float> position_{0.0f, 0.0f, 0.0f}; float volume_{1.0f}; bool positional_{true}; bool position_dirty_{true}; bool music_{}; bool loop_{true}; uint32_t play_id_{}; bool playing_{}; }; } // namespace ballistica::scene_v1 #endif // BALLISTICA_SCENE_V1_NODE_SOUND_NODE_H_
cb6ce523b8cb70e9c724e40b1602413cbfd39c58
060c7e5fb11d25c7c32f20e5961b2f13d83774a5
/Chapter5/Chapter5Task1.cpp
1f512d54fdcdc6fb85c847e9dae57610af636d57
[]
no_license
StevenTCShearer/Jumping-Into-CPP
501c415a7c1802c52164e262d1ef8593ccecc3fb
23cb5da7971725e5fdac69d3864ad9b93f54059b
refs/heads/master
2020-04-01T12:04:57.347677
2018-10-19T01:20:18
2018-10-19T01:20:18
153,190,438
0
0
null
null
null
null
UTF-8
C++
false
false
1,697
cpp
Chapter5Task1.cpp
#include <iostream> using namespace std; int main() { int answer; cout << "Menu" << endl; cout << "1) Calculator" << endl; cout << "2) 99 Bottles of Beer" << endl; cin >> answer; switch (answer) { case 1: calculator(); break; case 2: 99Bottles(); break; default: cout << "Please Enter a valid input" << endl; } return 0; } int calculator() { string operation; int num1, num2; cout << "Please Enter the Opertation you would like to do (+, -, /, *)" << endl; cin >> operation; cout << "Enter first number" << endl; cin >> num1; cout << "Enter second number" << endl; cin >> num2; if(operation == "+") { cout << num1 << " + " << num2 << " = " << num1+num2 << endl; } else if(operation == "/") { cout << num1 << " / " << num2 << " = " << num1/num2 << endl; } else if(operation == "-") { cout << num1 << " -" << num2 << " = " << num1-num2 << endl; } else if(operation == "*") { cout << num1 << " * " << num2 << " * " << num1/num2 << endl; } else { cout << "Please Enter Correct Input" << endl; } } string 99Bottles() { for(int i = 99; i == 0; i--) { if (i > 0) { cout << i << " bottles of beer on the wall," << i << " bottles of beer. Take one down, pass it around," << i - 1 << " bottles of beer on the wall..." << endl; } else { cout << "No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more, 99 bottles of beer on the wall..." << endl; } } }
52a0dde0ac741507707df66c614408dc19f88ea1
29eb66c7d378e212c78278b3e622a77436db1f58
/SourceCode/Framework/android/AndroidHandler.cpp
02ba727945fc76ae379359923f85c600fb037cf5
[]
no_license
yf885188/BeyondEngine
b71dc0db844e5e9769e30a341e1ca55fc784d9de
9950c12e6c34450c234905731454b40a6f55609c
refs/heads/master
2021-06-16T16:02:09.778944
2017-03-06T07:01:33
2017-03-06T07:01:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,667
cpp
AndroidHandler.cpp
#include "stdafx.h" #include <arpa/inet.h> #include "AndroidHandler.h" #include "Event/TouchDelegate.h" #include "Event/GestureState.h" #include "Framework/Application.h" #include "Render/RenderTarget.h" #include "Render/RenderManager.h" #include "external/Configuration.h" #include "Framework/android/JniHelper.h" #include "StarRaidersCenter.h" #include "Resource/ResourceManager.h" #include "BeyondEngineUI/StarRaidersGUISystem.h" #include "Audio/include/AudioEngine.h" #include "EnginePublic/EngineCenter.h" #include "Utility/BeatsUtility/FilePathTool.h" #include "EnginePublic/PlayerPrefs.h" #include "GUI/IMEManager.h" #include "Framework/android/AndroidKeyBoardDelegate.h" #include "Task/ExtractAndroidAssets.h" #include "PlatformHelper.h" #include "BeyondEngineUI/UISystemManager.h" CAndroidHandler* CAndroidHandler::m_pInstance = NULL; #define ASENSOR_TYPE_GRAVITY 9 extern "C" { jint JNI_OnLoad(JavaVM *vm, void *reserved) { JniHelper::setJavaVM(vm); return JNI_VERSION_1_4; } JNIEXPORT void JNICALL Java_com_beyondtech_starraiders_BeyondEngineHelper_nativeSetContext(JNIEnv* env, jobject thiz, jobject context) { JniHelper::setClassLoaderFrom(context); BEATS_PRINT(_T("Java_com_beyondtech_starraiders_BeyondEngineHelper_nativeSetContext\n")); JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, BEYONDENGINE_HELPER_CLASS_NAME, "GetExternalSDPath", "()Ljava/lang/String;")) { jstring strRet = (jstring)methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID); TString strExteranlPath = JniHelper::jstring2string(strRet); CAndroidHandler::GetInstance()->SetAndroidPath(eAPT_ExternalDirectory, strExteranlPath); methodInfo.env->DeleteLocalRef(strRet); } methodInfo.CleanUp(); if (JniHelper::getStaticMethodInfo(methodInfo, BEYONDENGINE_HELPER_CLASS_NAME, "GetFilesDirectoryPath", "()Ljava/lang/String;")) { jstring strRet = (jstring)methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID); TString strExteranlPath = JniHelper::jstring2string(strRet); CAndroidHandler::GetInstance()->SetAndroidPath(eAPT_FilesDirectory, strExteranlPath); methodInfo.env->DeleteLocalRef(strRet); } methodInfo.CleanUp(); if (JniHelper::getStaticMethodInfo(methodInfo, BEYONDENGINE_HELPER_CLASS_NAME, "GetPackageName", "()Ljava/lang/String;")) { jstring strRet = (jstring)methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID); TString strPackageName = JniHelper::jstring2string(strRet); CAndroidHandler::GetInstance()->SetPackageName(strPackageName); methodInfo.env->DeleteLocalRef(strRet); } CPlatformHelper::GetInstance()->InitGameExtrat(); if (!CPlatformHelper::GetInstance()->IsAssetFileExtracted()) { TString strDirectoryAbsolutePath = CAndroidHandler::GetInstance()->GetAndroidPath(eAPT_FilesDirectory); strDirectoryAbsolutePath.append("/assets/resource/font"); BEATS_PRINT("Start extract basic file to %s\n", strDirectoryAbsolutePath.c_str()); CFilePathTool::GetInstance()->MakeDirectory(strDirectoryAbsolutePath.c_str()); SDirectory fontDirectory(nullptr, "resource/font"); CAndroidHandler::GetInstance()->FillDirectory(fontDirectory); uint32_t uExtractSize = 0; CExtractAndroidAssets::ExtractAssetsFromDirectory(&fontDirectory, uExtractSize); BEATS_PRINT("Extract basic file to %s\n", strDirectoryAbsolutePath.c_str()); } } JNIEXPORT void JNICALL Java_com_beyondtech_starraiders_StarRaidersActivity_InitAndroidHandler(JNIEnv * env, jobject thiz) { //HACK:fix the mult thread bug CAndroidHandler::GetInstance(); } JNIEXPORT void JNICALL Java_com_beyondtech_starraiders_StarRaidersActivity_StarRaidersLogin(JNIEnv * env, jobject thiz, jstring account, jstring password) { std::string strAccount = JniHelper::jstring2string(account); std::string strPassword = JniHelper::jstring2string(password); CStarRaidersCenter::GetInstance()->SetAccountString(strAccount); CStarRaidersCenter::GetInstance()->SetPasswordString(strPassword); CApplication::GetInstance()->Resume(); CPlatformHelper::GetInstance()->SetLoginState(eLoginEnd); } JNIEXPORT void JNICALL Java_com_beyondtech_starraiders_StarRaidersActivity_ChangeChar(JNIEnv* env, jobject thiz, jstring str) { std::string strChar = JniHelper::jstring2string(str); CAndroidHandler::GetInstance()->SetTextBoxStr(strChar); } JNIEXPORT void JNICALL Java_com_beyondtech_starraiders_StarRaidersActivity_OnBackwardChar(JNIEnv* env, jobject thiz) { CIMEManager::GetInstance()->OnKeyBackward(); } JNIEXPORT jstring JNICALL Java_com_beyondtech_starraiders_StarRaidersActivity_GetCurrText(JNIEnv* env, jobject thiz) { std::string strText = CIMEManager::GetInstance()->GetCurrText(); jstring jstrText = env->NewStringUTF(strText.c_str()); return jstrText; } JNIEXPORT jfloat JNICALL Java_com_beyondtech_starraiders_StarRaidersActivity_GetEditBoxPosYPercent(JNIEnv* env, jobject thiz) { float fRet = CIMEManager::GetInstance()->GetEditBoxPosYPercent(); return (jfloat)fRet; } JNIEXPORT jstring JNICALL Java_com_beyondtech_starraiders_StarRaidersActivity_StringFilter(JNIEnv* env, jobject thiz, jstring str) { std::string strChar = JniHelper::jstring2string(str); std::string strText = CIMEManager::GetInstance()->OnStringFilter(strChar); jstring jstrText = env->NewStringUTF(strText.c_str()); return jstrText; } JNIEXPORT jstring JNICALL Java_com_beyondtech_starraiders_StarRaidersActivity_GetLogListString(JNIEnv* env, jobject thiz) { TString strLogList; #ifdef DEVELOP_VERSION strLogList = CLogManager::GetInstance()->GetLastLogList(500); #endif jstring jstrText = env->NewStringUTF(strLogList.c_str()); return jstrText; } }; CAndroidHandler::CAndroidHandler() : m_bHasFocus(false) , m_glContext (ndk_helper::GLContext::GetInstance()) , m_pApp(nullptr) , m_pSensorManager(nullptr) , m_pAccelerometerSensor(nullptr) , m_pGravitySensor(nullptr) , m_pSensorEventQueue(nullptr) { m_pKeyBoardDelegate = new CAndroidKeyBoardDelegate(); CIMEManager::GetInstance()->SetKeyBoardDelegate(m_pKeyBoardDelegate); } CAndroidHandler::~CAndroidHandler() { BEATS_SAFE_DELETE(m_pKeyBoardDelegate); } bool CAndroidHandler::Initialize(android_app* pApp) { BEATS_ASSERT(pApp != NULL, _T("App can't be null when initialize Android handler!")); m_pApp = pApp; m_pinchDetector.SetConfiguration( m_pApp->config ); } bool CAndroidHandler::IsFocus() const { return m_bHasFocus; } void CAndroidHandler::InitSensors() { m_pSensorManager = ASensorManager_getInstance(); BEATS_ASSERT(m_pSensorManager != NULL, _T("SensorManager can't be null!")); m_pGravitySensor = ASensorManager_getDefaultSensor( m_pSensorManager, ASENSOR_TYPE_GRAVITY ); m_pAccelerometerSensor = ASensorManager_getDefaultSensor( m_pSensorManager, ASENSOR_TYPE_ACCELEROMETER ); m_pSensorEventQueue = ASensorManager_createEventQueue( m_pSensorManager, m_pApp->looper, LOOPER_ID_USER, NULL, NULL ); } void CAndroidHandler::ProcessSensors( int32_t id ) { // If a sensor has data, process it now. if( id == LOOPER_ID_USER ) { if( m_pAccelerometerSensor != NULL ) { ASensorEvent event; while( ASensorEventQueue_getEvents( m_pSensorEventQueue, &event, 1 ) > 0 ) { if (event.type == ASENSOR_TYPE_GRAVITY) { CPlatformHelper::GetInstance()->OnGravity(event.vector.x/ASENSOR_STANDARD_GRAVITY , event.vector.y/ASENSOR_STANDARD_GRAVITY, event.vector.z/ASENSOR_STANDARD_GRAVITY); } else if (event.type == ASENSOR_TYPE_ACCELEROMETER) { CPlatformHelper::GetInstance()->OnAccelerometer(event.acceleration.x/ASENSOR_STANDARD_GRAVITY , event.acceleration.y/ASENSOR_STANDARD_GRAVITY, event.acceleration.z/ASENSOR_STANDARD_GRAVITY); } } } } } void CAndroidHandler::SuspendAccelerometerSensor() { // When our app loses focus, we stop monitoring the accelerometer. // This is to avoid consuming battery while not being used. if( m_pAccelerometerSensor != NULL ) { ASensorEventQueue_disableSensor( m_pSensorEventQueue, m_pAccelerometerSensor ); } } void CAndroidHandler::ResumeAccelerometerSensor() { // When our app gains focus, we start monitoring the accelerometer. if( m_pAccelerometerSensor != NULL ) { ASensorEventQueue_enableSensor( m_pSensorEventQueue, m_pAccelerometerSensor ); ASensorEventQueue_setEventRate( m_pSensorEventQueue, m_pAccelerometerSensor, (1000L / 60 * 1000)); } } void CAndroidHandler::SuspendGravitySensors() { if( m_pGravitySensor != NULL ) { ASensorEventQueue_disableSensor( m_pSensorEventQueue, m_pGravitySensor ); } } void CAndroidHandler::ResumeGravitySensors() { if( m_pGravitySensor != NULL ) { ASensorEventQueue_enableSensor( m_pSensorEventQueue, m_pGravitySensor ); ASensorEventQueue_setEventRate( m_pSensorEventQueue, m_pGravitySensor, (1000L / 60 * 1000)); } } void CAndroidHandler::ShowLoginWindow(const TString& strDefaultUserName, const TString& strDefaultPassword) { JniMethodInfo methodInfo; #ifdef _SUPER_SDK if (JniHelper::getStaticMethodInfo(methodInfo, SDK_ACTIVITY_CLASS_NAME, "showLoginWindowSdk", "(Ljava/lang/String;Ljava/lang/String;)V")) #else if (JniHelper::getStaticMethodInfo(methodInfo, ACTIVITY_CLASS_NAME, "showLoginWindow", "(Ljava/lang/String;Ljava/lang/String;)V")) #endif { jstring strUserName = methodInfo.env->NewStringUTF(strDefaultUserName.c_str()); jstring strPassword = methodInfo.env->NewStringUTF(strDefaultPassword.c_str()); methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, strUserName, strPassword); methodInfo.env->DeleteLocalRef(strUserName); methodInfo.env->DeleteLocalRef(strPassword); } } void CAndroidHandler::TransformPosition( ndk_helper::Vec2& vec ) { vec = ndk_helper::Vec2( 2.0f, 2.0f ) * vec / ndk_helper::Vec2( m_glContext->GetScreenWidth(), m_glContext->GetScreenHeight() ) - ndk_helper::Vec2( 1.f, 1.f ); } ndk_helper::GLContext* CAndroidHandler::GetGLContext() const { return m_glContext; } void CAndroidHandler::HandleCmd( struct android_app* app, int32_t cmd ) { CAndroidHandler* pHandler = CAndroidHandler::GetInstance(); BEATS_PRINT("StartHandle android cmd %d\n", cmd); switch( cmd ) { case APP_CMD_SAVE_STATE: BEATS_PRINT("APP_CMD_SAVE_STATE %d\n", cmd); break; case APP_CMD_INIT_WINDOW: BEATS_PRINT("APP_CMD_INIT_WINDOW %d\n", cmd); // The window is being shown, get it ready. if( pHandler->m_pApp->window != NULL ) { pHandler->m_glContext->Resume( pHandler->m_pApp->window ); if (!CApplication::GetInstance()->IsInitialized()) { pHandler->InitVAOFunction(); int32_t screenWidth = pHandler->GetGLContext()->GetScreenWidth(); int32_t screenHeight = pHandler->GetGLContext()->GetScreenHeight(); CRenderTarget* pRenderWindow = new CRenderTarget(screenWidth, screenHeight); CRenderManager::GetInstance()->SetCurrentRenderTarget(pRenderWindow); CApplication::GetInstance()->Initialize(); } } break; case APP_CMD_TERM_WINDOW: BEATS_PRINT("APP_CMD_TERM_WINDOW %d\n", cmd); pHandler->m_glContext->Suspend(); pHandler->m_bHasFocus = false; break; case APP_CMD_STOP: BEATS_PRINT("APP_CMD_STOP %d\n", cmd); CAudioEngine::Pause(CStarRaidersCenter::GetInstance()->GetBackGroundMusic()); break; case APP_CMD_START: BEATS_PRINT("APP_CMD_START %d\n", cmd); break; case APP_CMD_RESUME: BEATS_PRINT("APP_CMD_RESUME %d\n", cmd); CApplication::GetInstance()->OnSwitchToForeground(); break; case APP_CMD_PAUSE: BEATS_PRINT("APP_CMD_PAUSE %d\n", cmd); CApplication::GetInstance()->OnSwitchToBackground(); break; case APP_CMD_GAINED_FOCUS: BEATS_PRINT("APP_CMD_GAINED_FOCUS %d\n", cmd); pHandler->m_bHasFocus = true; break; case APP_CMD_LOST_FOCUS: BEATS_PRINT("APP_CMD_LOST_FOCUS %d\n", cmd); pHandler->m_bHasFocus = false; break; case APP_CMD_DESTROY: BEATS_PRINT("APP_CMD_DESTROY %d\n", cmd); break; case APP_CMD_CONFIG_CHANGED: BEATS_PRINT("APP_CMD_CONFIG_CHANGED %d\n", cmd); break; case APP_CMD_CONTENT_RECT_CHANGED: BEATS_PRINT("APP_CMD_CONTENT_RECT_CHANGED %d\n", cmd); break; case APP_CMD_WINDOW_REDRAW_NEEDED: BEATS_PRINT("APP_CMD_WINDOW_REDRAW_NEEDED %d\n", cmd); break; case APP_CMD_WINDOW_RESIZED: BEATS_PRINT("APP_CMD_WINDOW_RESIZED %d\n", cmd); break; case APP_CMD_LOW_MEMORY: CResourceManager::GetInstance()->CleanUp(); BEATS_ASSERT(false, _T("Memory is too low!")); break; } BEATS_PRINT("Finish Handle android cmd %d\n", cmd); } int32_t CAndroidHandler::HandleInput( android_app* app, AInputEvent* event ) { int32_t nRet = 0; CAndroidHandler* pHandler = CAndroidHandler::GetInstance(); CTouchDelegate* pTouchDelegate = CTouchDelegate::GetInstance(); if( AInputEvent_getType( event ) == AINPUT_EVENT_TYPE_MOTION ) { ndk_helper::GESTURE_STATE pinchState = pHandler->m_pinchDetector.Detect(event); int32_t action = AMotionEvent_getAction( event ); int32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; uint32_t flags = action & AMOTION_EVENT_ACTION_MASK; intptr_t pointerCount = AMotionEvent_getPointerCount( event ); CRenderTarget* pCurrRenderTarget = CRenderManager::GetInstance()->GetCurrentRenderTarget(); BEATS_ASSERT(pCurrRenderTarget != NULL); float fScaleFactor = pCurrRenderTarget->GetScaleFactor(); switch (flags) { case AMOTION_EVENT_ACTION_DOWN: { BEATS_ASSERT(pointerCount == 1, _T("There should be only one pointer in AMOTION_EVENT_ACTION_DOWN")); BEATS_WARNING(index == 0, _T("index should be 0")); size_t pointerId = AMotionEvent_getPointerId(event, 0); float x = AMotionEvent_getX( event, 0 ); float y = AMotionEvent_getY( event, 0 ); x /= fScaleFactor; y /= fScaleFactor; pTouchDelegate->OnTouchBegan(1, &pointerId, &x, &y); } break; case AMOTION_EVENT_ACTION_UP: { BEATS_ASSERT(pointerCount == 1, _T("There should be only one pointer in AMOTION_EVENT_ACTION_UP")); BEATS_WARNING(index == 0, _T("index should be 0")); size_t pointerId = AMotionEvent_getPointerId(event, 0); float x = AMotionEvent_getX( event, 0 ); float y = AMotionEvent_getY( event, 0 ); x /= fScaleFactor; y /= fScaleFactor; size_t id[1] = { pointerId }; pTouchDelegate->OnTouchEnded(1, id, &x, &y); } break; case AMOTION_EVENT_ACTION_POINTER_DOWN: { BEATS_ASSERT(pointerCount > 1, _T("There should be greater than one pointer in AMOTION_EVENT_ACTION_POINTER_DOWN")); size_t pointerId = AMotionEvent_getPointerId(event, index); float x = AMotionEvent_getX( event, index ); float y = AMotionEvent_getY( event, index ); x /= fScaleFactor; y /= fScaleFactor; pTouchDelegate->OnTouchBegan(1, &pointerId, &x, &y); } break; case AMOTION_EVENT_ACTION_POINTER_UP: { BEATS_ASSERT(pointerCount > 1, _T("There should be greater than one pointer in AMOTION_EVENT_ACTION_POINTER_DOWN")); size_t pointerId = AMotionEvent_getPointerId(event, index); float x = AMotionEvent_getX( event, index ); float y = AMotionEvent_getY( event, index ); x /= fScaleFactor; y /= fScaleFactor; size_t id[1] = { pointerId }; pTouchDelegate->OnTouchEnded(1, id, &x, &y); } break; case AMOTION_EVENT_ACTION_MOVE: { size_t pointerIds[TOUCH_MAX_NUM] = { 0 }; float xs[TOUCH_MAX_NUM] = {0.0f}; float ys[TOUCH_MAX_NUM] = {0.0f}; for (uint32_t i = 0; i < pointerCount && i < TOUCH_MAX_NUM; ++i) { pointerIds[i] = AMotionEvent_getPointerId( event, i ); xs[i] = AMotionEvent_getX(event, i); ys[i] = AMotionEvent_getY(event, i); xs[i] /= fScaleFactor; ys[i] /= fScaleFactor; } pTouchDelegate->OnTouchMoved(pointerCount, pointerIds, xs, ys); } break; case AMOTION_EVENT_ACTION_CANCEL: { size_t pointerIds[TOUCH_MAX_NUM] = { 0 }; float xs[TOUCH_MAX_NUM] = {0.0f}; float ys[TOUCH_MAX_NUM] = {0.0f}; for (uint32_t i = 0; i < pointerCount && i < TOUCH_MAX_NUM; ++i) { pointerIds[i] = AMotionEvent_getPointerId( event, i ); xs[i] = AMotionEvent_getX(event, i); ys[i] = AMotionEvent_getY(event, i); xs[i] /= fScaleFactor; ys[i] /= fScaleFactor; } pTouchDelegate->OnTouchCancelled(pointerCount, pointerIds, xs, ys); } break; default: BEATS_ASSERT(false, _T("Unknown flags of motion event %d"), flags); break; } if (pinchState & ndk_helper::GESTURE_STATE_START || pinchState & ndk_helper::GESTURE_STATE_MOVE) { ndk_helper::Vec2 v1; ndk_helper::Vec2 v2; pHandler->m_pinchDetector.GetPointers( v1, v2 ); v1 -= v2; float fDistance = v1.Length(); if (BEATS_FLOAT_GREATER(fDistance, 0.f)) { pTouchDelegate->OnPinched((pinchState & ndk_helper::GESTURE_STATE_START) ? EGestureState::eGS_BEGAN : EGestureState::eGS_CHANGED, fDistance); } } return 1; } return 0; } void CAndroidHandler::FillDirectory(SDirectory& directory) { JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, BEYONDENGINE_HELPER_CLASS_NAME, _T("GetDirectoryData"), _T("(Ljava/lang/String;)[B"))) { jstring str = methodInfo.env->NewStringUTF(directory.m_strPath.c_str()); jbyteArray jret = (jbyteArray)methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID, str); methodInfo.env->DeleteLocalRef(str); jbyte* pData = methodInfo.env->GetByteArrayElements(jret, 0); uint32_t uSize = (uint32_t)methodInfo.env->GetArrayLength(jret); CSerializer serializer(uSize, pData); FillDirectoryWithData(directory, serializer); methodInfo.env->ReleaseByteArrayElements(jret, pData, 0); methodInfo.env->DeleteLocalRef(jret); BEATS_ASSERT(serializer.GetReadPos() == serializer.GetWritePos()); } } const TString& CAndroidHandler::GetAndroidPath(EAndroidPathType type) const { BEATS_ASSERT(type < eAPT_Count); return m_strAndroidPath[type]; } void CAndroidHandler::SetAndroidPath(EAndroidPathType type, const TString& strPath) { BEATS_ASSERT(type < eAPT_Count); m_strAndroidPath[type] = CStringHelper::GetInstance()->ToLower(strPath); } const TString& CAndroidHandler::GetPackageName()const { return m_strPackageName; } void CAndroidHandler::SetPackageName(const TString& strPackageName) { m_strPackageName = strPackageName; } void CAndroidHandler::InitVAOFunction() { bool bNoNeedTry = glGenVertexArrays != NULL && glBindVertexArray != NULL && glDeleteVertexArrays != NULL; if (!bNoNeedTry) { bool bTryVAOExtension = false; if (glGenVertexArrays == NULL) { typedef void(*TGenVertexArrayFunc)(GLsizei,GLuint*); glGenVertexArrays = (TGenVertexArrayFunc)eglGetProcAddress("glGenVertexArraysOES"); bTryVAOExtension = glGenVertexArrays != NULL; } if (glBindVertexArray == NULL) { typedef void(*TBindVertexArrayFunc)(GLuint); glBindVertexArray = (TBindVertexArrayFunc)eglGetProcAddress("glBindVertexArrayOES"); bTryVAOExtension = bTryVAOExtension && glBindVertexArray != NULL; } if (glDeleteVertexArrays == NULL) { typedef void(*TDeleteVertexArrayFunc)(GLsizei, const GLuint*); glDeleteVertexArrays = (TDeleteVertexArrayFunc)eglGetProcAddress("glDeleteVertexArraysOES"); bTryVAOExtension = bTryVAOExtension && glDeleteVertexArrays != NULL; } if (bTryVAOExtension) { BEATS_PRINT(_T("VAO is supported by OES!")); } else { CConfiguration::GetInstance()->SetSupportShareableVAO(false); BEATS_PRINT(_T("VAO is disabled!")); } } } void CAndroidHandler::FillDirectoryWithData(SDirectory& directory, CSerializer& serializer) { unsigned short uStringLength = 0; serializer >> uStringLength; uStringLength = (unsigned short)ntohs(uStringLength);//Java use big-endian. TCHAR szBuffer[MAX_PATH]; serializer.Deserialize(szBuffer, uStringLength); szBuffer[uStringLength] = 0; directory.m_strPath = szBuffer; uint32_t uFileListCount = 0; serializer >> uFileListCount; uFileListCount = (uint32_t)ntohl((long)uFileListCount);//Java use big-endian. for (uint32_t i = 0; i < uFileListCount; ++i) { TFileData* pFileData = new TFileData; serializer >> uStringLength; uStringLength = (uint32_t)ntohs(uStringLength);//Java use big-endian. BEATS_ASSERT(uStringLength < MAX_PATH); serializer.Deserialize(pFileData->cFileName, uStringLength); pFileData->cFileName[uStringLength] = 0; AAssetManager* pAssetManager = CFilePathTool::GetInstance()->GetAssetManager(); TString strFileFullPath = directory.m_strPath; if (!strFileFullPath.empty()) { strFileFullPath.append(_T("/")); } strFileFullPath.append(pFileData->cFileName); AAsset* pFileAsset = AAssetManager_open(pAssetManager, strFileFullPath.c_str(), AASSET_MODE_UNKNOWN); pFileData->nFileSizeLow = AAsset_getLength(pFileAsset); directory.m_data.nFileSizeLow += pFileData->nFileSizeLow; AAsset_close(pFileAsset); directory.m_pFileList->push_back(pFileData); } uint32_t uDirectoryListCount = 0; serializer >> uDirectoryListCount; uDirectoryListCount = (uint32_t)ntohl((long)uDirectoryListCount);//Java use big-endian. for (uint32_t i = 0; i < uDirectoryListCount; ++i) { SDirectory* pNewDirectory = new SDirectory(&directory, nullptr); directory.m_pDirectories->push_back(pNewDirectory); FillDirectoryWithData(*pNewDirectory, serializer); directory.m_data.nFileSizeLow += pNewDirectory->m_data.nFileSizeLow; } } int CAndroidHandler::GetSDKVersion() { int ret = -1; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, ACTIVITY_CLASS_NAME, _T("GetSdkVersion"), _T("()I"))) { ret = methodInfo.env->CallStaticIntMethod(methodInfo.classID, methodInfo.methodID); } return ret; } TString CAndroidHandler::GetOsVersion() { TString ret; ret = CallJavaStringMethod(ACTIVITY_CLASS_NAME, _T("GenerateOsVersion"), _T("()Ljava/lang/String;")); return ret; } TString CAndroidHandler::GetModelInfo() { TString ret; ret = CallJavaStringMethod(ACTIVITY_CLASS_NAME, _T("GenerateModelInfo"), _T("()Ljava/lang/String;")); return ret; } void CAndroidHandler::CallJavaVoidMethodParamString(const TString& classPath, const TString& func, const TString& param, const TString& strParam) { JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, classPath.c_str(), func.c_str(), param.c_str())) { jstring jstrParam = methodInfo.env->NewStringUTF(strParam.c_str()); methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, jstrParam); methodInfo.env->DeleteLocalRef(jstrParam); } } void CAndroidHandler::CallJavaVoidMethod(const TString& classPath, const TString& func, const TString& param) { JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, classPath.c_str(), func.c_str(), param.c_str())) { methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID); } } bool CAndroidHandler::CallJavaBooleanMethod(const TString& classPath, const TString& func, const TString& param) { bool ret = false; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, classPath.c_str(), func.c_str(), param.c_str())) { ret = methodInfo.env->CallStaticBooleanMethod(methodInfo.classID, methodInfo.methodID); } return ret; } TString CAndroidHandler::CallJavaStringMethod(const TString& classPath, const TString& func, const TString& param) { TString ret; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, classPath.c_str(), func.c_str(), param.c_str())) { jobject jobj = methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID); ret = JniHelper::jstring2string((jstring)jobj); methodInfo.env->DeleteLocalRef(jobj); } return ret; } float CAndroidHandler::CallJavaFloatMethod(const TString& classPath, const TString& func, const TString& param) { float ret = 0; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, classPath.c_str(), func.c_str(), param.c_str())) { ret = methodInfo.env->CallStaticFloatMethod(methodInfo.classID, methodInfo.methodID); } return ret; } int CAndroidHandler::GetNetState() { int ret = -1; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, ACTIVITY_CLASS_NAME, _T("GenerateNetInfo"), _T("()I"))) { ret = methodInfo.env->CallStaticIntMethod(methodInfo.classID, methodInfo.methodID); } return ret; } int CAndroidHandler::GetDeviceType()//1:pad 2:phone { int ret = -1; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, ACTIVITY_CLASS_NAME, _T("GetDeviceType"), _T("()I"))) { ret = methodInfo.env->CallStaticIntMethod(methodInfo.classID, methodInfo.methodID); } return ret; } void CAndroidHandler::SetTextBoxStr(const TString& str) { m_TextBoxStr = str; } void CAndroidHandler::RefreshTextBoxStr() { if( !m_TextBoxStr.empty() ) { CIMEManager::GetInstance()->OnCharReplace(m_TextBoxStr.c_str()); m_TextBoxStr.clear(); } } void CAndroidHandler::ShowLogin() { const TString& strUserName = CPlayerPrefs::GetInstance()->GetString(PlayerPrefGlobalKey[ePPGK_LastLoginUserName]); const TString& strPassword = CPlayerPrefs::GetInstance()->GetString(PlayerPrefGlobalKey[ePPGK_LastLoginPassword]); CAndroidHandler::GetInstance()->ShowLoginWindow(strUserName, strPassword); } void CAndroidHandler::ExtractAndroidAssets() { // Extract some basic file. TString strDirectoryAbsolutePath = CAndroidHandler::GetInstance()->GetAndroidPath(eAPT_FilesDirectory); strDirectoryAbsolutePath.append("/assets/resource/font"); BEATS_PRINT("Start extract basic file to %s\n", strDirectoryAbsolutePath.c_str()); CFilePathTool::GetInstance()->MakeDirectory(strDirectoryAbsolutePath.c_str()); SDirectory fontDirectory(nullptr, "resource/font"); CAndroidHandler::GetInstance()->FillDirectory(fontDirectory); uint32_t uExtractSize = 0; CExtractAndroidAssets::ExtractAssetsFromDirectory(&fontDirectory, uExtractSize); BEATS_PRINT("Extract basic file to %s\n", strDirectoryAbsolutePath.c_str()); } TString CAndroidHandler::GetVersionName() { TString strVersionName; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, BEYONDENGINE_HELPER_CLASS_NAME, "getVersionName", "()Ljava/lang/String;")) { jstring strRet = (jstring)methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID); strVersionName = JniHelper::jstring2string(strRet); methodInfo.env->DeleteLocalRef(strRet); } return strVersionName; }
e62373314512888f03f0b328400a5dc9e4563c82
02cd67235f286cb56c2b52eec5f08851121d7c5a
/banjo/declaration.hpp
a75d24475be9d19a7ea7ec7b5b3c67c41bc19354
[ "MIT" ]
permissive
Jenny-fa/banjo
787142a3b9f3050edb25dcaea137100d55192d05
26c8675b510ce3bdc73f6d999b904b0fc6005700
refs/heads/master
2021-01-18T05:17:06.374467
2016-02-14T18:23:24
2016-02-14T18:23:24
50,858,948
0
0
null
2016-02-01T17:58:09
2016-02-01T17:58:08
null
UTF-8
C++
false
false
287
hpp
declaration.hpp
// Copyright (c) 2015-2016 Andrew Sutton // All rights reserved #ifndef BANJO_DECLARATION_HPP #define BANJO_DECLARATION_HPP #include "prelude.hpp" namespace banjo { struct Context; struct Decl; struct Scope; Decl* declare(Context&, Scope&, Decl&); } // namespace banjo #endif
cc6aa64d066c7f22a7c12b6708c6b19de3489af8
15a7b4cbf97b803775b26d8a1a7094cea114cff2
/Client/include/Text.hh
2d16d2f52828ab0186a8a81d5915363e8b6ec033
[]
no_license
AGuismo/G-BALLS-Rtype
5ba71039a5b7c5bc31f950ff5e6f8758f4e963e5
75ba8ee5cded3e450c884a1c222699b8415e5973
refs/heads/master
2021-01-17T02:34:34.274163
2014-12-30T20:46:31
2014-12-30T20:46:31
13,957,123
0
0
null
null
null
null
UTF-8
C++
false
false
1,771
hh
Text.hh
// // Text.hh for text in /home/brigno/Projects/R-Type/r-type/Client // // Made by brigno // Login <brigno@epitech.net> // // Started on Thu Oct 24 10:55:11 2013 brigno // Last update Sat Nov 23 18:29:45 2013 brigno // #ifndef __TEXT_HH__ # define __TEXT_HH__ #include "AWidget.hh" class Text : public AWidget { public: static const sf::Uint32 BACKSPACE = 8; private: bool _enable; int _cursor; sf::Font _font; sf::String _sentenceTmp; sf::String _sentence; std::string _tmp; sf::Text _text; std::string _fontPath; std::size_t _sizeLimit; int _flag; public: Text(const std::string &fontPath, const std::string &name, const sf::Event &, const sf::Vector2f &posTopLeft, const sf::Vector2f &focusTopLeft, const sf::Vector2f &focusBotRight, const size_t &size, const bool &enable); Text(const std::string &fontPath, const std::string &name, const sf::Event &, const sf::Vector2f &posTopLeft, const sf::Vector2f &focusTopLeft, const sf::Vector2f &focusBotRight, const size_t &size, const bool &enable, const std::string &); Text &operator=(const Text &other); private: Text(const Text &other); public: const sf::Font &getFont(void) const; const std::string &getTmp(void) const; const sf::Text &getText(void) const; const bool &getEnable(void) const; const int &getCursor(void) const; const std::size_t &getSizeLimit(void) const; const sf::String &getSentence(void) const; const sf::String &getSentenceTmp(void) const; const std::string &getFontPath(void) const; const int &getFlag(void) const; void clearText(void); AScreen::Status onFocus(void); void stopFocus(void); void onHover(void); void stopHover(void); void draw(sf::RenderWindow &); }; #endif /* !__TEXT_HH__ */
424fc88f2c4d0ce6e0ba3564f2046195f610d055
1fa89d7de3e9acf432cf11356de319669df3dfa0
/01/c++/prog.cpp
4d358174188751533ee3bf8058b7764cc108125a
[ "MIT" ]
permissive
flopp/aoc2019
58b51ac4855171596415283ff373cd1707a86d12
d9dae3b88866e0817e643bcd929575c284e074c1
refs/heads/master
2020-09-22T00:46:24.745404
2019-12-15T12:12:08
2019-12-15T12:12:08
224,991,127
0
0
null
null
null
null
UTF-8
C++
false
false
1,880
cpp
prog.cpp
#include <cmath> #include <iostream> #include <string> int fuel_for_mass(int mass) { return static_cast<int>(floor(mass / 3.0)) - 2; } int total_fuel_for_mass(int mass) { const int fuel = fuel_for_mass(mass); if (fuel < 0) { return 0; } return fuel + total_fuel_for_mass(fuel); } int main(int argc, const char **argv) { if (argc != 2) { std::cerr << "USAGE: " << argv[0] << " <MODE>" << std::endl; return 1; } const std::string mode = argv[1]; if (mode == "test1") { std::cout << "12: " << fuel_for_mass(12) << " (expected: 2)" << std::endl; std::cout << "14: " << fuel_for_mass(14) << " (expected: 2)" << std::endl; std::cout << "1969: " << fuel_for_mass(1969) << " (expected: 654)" << std::endl; std::cout << "100756: " << fuel_for_mass(100756) << " (expected: 33583)" << std::endl; } else if (mode == "test2") { std::cout << "14: " << total_fuel_for_mass(14) << " (expected: 2)" << std::endl; std::cout << "1969: " << total_fuel_for_mass(1969) << " (expected: 966)" << std::endl; std::cout << "100756: " << total_fuel_for_mass(100756) << " (expected: 50346)" << std::endl; } else if (mode == "puzzle1") { int fuel_sum = 0; int mass = 0; while (std::cin >> mass) { fuel_sum += fuel_for_mass(mass); } std::cout << fuel_sum << std::endl; } else if (mode == "puzzle2") { int fuel_sum = 0; int mass = 0; while (std::cin >> mass) { fuel_sum += total_fuel_for_mass(mass); } std::cout << fuel_sum << std::endl; } else { std::cerr << "bad <MODE>: " << mode << std::endl; return 1; } return 0; }
435ae37ad846cccad0ee5685546bde484cd81a9e
e1a579d31a579ac5b76af45ff85e5e593e1ed1f1
/4-5. Disjoint Set/problem3.cpp
f83bdbdbbe78cf111736730121a33eb45ac560ac
[]
no_license
kangyul/CodingTestPrep
6e60903a8906a62c9babd636baef825f56a777ad
4b944cb8821de159fce50c1b0ea82726ee40e08e
refs/heads/master
2023-08-05T01:47:26.999894
2021-09-24T05:15:19
2021-09-24T05:15:19
405,547,000
1
0
null
null
null
null
UTF-8
C++
false
false
947
cpp
problem3.cpp
#include <iostream> #include <numeric> using namespace std; const int maxn = 40004; int arr[maxn]; void initialize() { iota(arr, arr+maxn, 0); } int root(int x) { if(arr[x] == x) return x; else return arr[x] = root(arr[x]); } void connect(int x, int y) { x = root(x); y = root(y); if(x == y) return; else arr[x] = y; } int main() { initialize(); int n, m; cin >> n >> m; for(int i=1; i<=n; i++) { for(int j=1; j<=n; j++) { int x; cin >> x; if(x == 1) { connect(i, j); } } } int current=0, prev=0; for(int i=0; i<m; i++) { cin >> current; if(i == 0) { prev = current; continue; } if(root(arr[current]) != root(arr[prev])) { cout << "NO"; return 0; } prev = current; } cout << "YES"; return 0; }
f25c54b69f1be1dab2f3e0eb1bca0d6affa30d72
3ffea2e3fc43fe1d59d66f0b72e0d66723ba9e81
/mookCalculator.cpp
4394b986b78af53a33d22fa049343bbe437d8fe1
[]
no_license
ZeeMastermind/Mook-Calculator
8d267dc35dc7da14ec052a51be1db9ad3a4b0ef0
1ef4270499878513e010dc69d09542294d8c2cfa
refs/heads/master
2020-06-29T13:04:56.727143
2019-08-04T23:51:32
2019-08-04T23:51:32
200,545,412
0
0
null
null
null
null
UTF-8
C++
false
false
3,650
cpp
mookCalculator.cpp
#include <iostream> #include <cmath> using namespace std; int pascal(int x, int y) { /* Taken from https://stackoverflow.com/questions/15601867/how-can-i-calculate-the-number-at-a-given-row-and-column-in-pascals-triangle */ if((x+1)==1 || (y+1)==1 || x==y) { return 1; } else { return pascal(x-1,y-1)+ pascal(x-1,y); } } float combinations(int pool, int threshold) { //threshold is 'actual number', must hit threshold+1 to succeed. float result = 0; while (threshold <= pool) { float a = pow((float)1/3, threshold); float b = pow((float)2/3, pool - threshold); int c = pascal(pool,threshold); //pool is row, threshold is column result += a * b * (float)c; threshold++; } return result; } int main() { int defensePool; int soakPool; int toHit; int defenseRate; int soakRate; cout.precision(4); cout << "MOOK CALCULATOR!" << endl; cout << "Calculates chance that at least one of your mooks will do 1 point of damage." << endl; cout << endl; cout << "Enter Defender Defense roll: "; cin >> defensePool; cout << "Enter Defender Soak roll: "; cin >> soakPool; cout << "Finally, enter Mook to-hit roll: "; cin >> toHit; cout << endl; defenseRate = defensePool/3; soakRate = soakPool/3; cout << "MOOKS\t"; for (int i=1; i<=5; i++) { cout << i << "DV\t\t"; } cout << endl; for (int i=1; i<=10; i++) { cout << i << "\t"; for (int j=1; j<=5; j++) { int netHitsNeeded = soakRate - j; if (netHitsNeeded < 1) netHitsNeeded = 1; float output = combinations(toHit, defenseRate + netHitsNeeded); output = 1 - pow(1-output,i); output *= 100; if (output <= 0.00000001) cout << output << "%\t\t"; else if (output < 0.1) cout << output << "%\t"; else cout << output << "%\t\t"; } cout << endl; } cout << endl; cout << "MOOKS\t"; for (int i=6; i<=10; i++) { cout << i << "DV\t\t"; } cout << endl; for (int i=1; i<=10; i++) { cout << i << "\t"; for (int j=6; j<=10; j++) { int netHitsNeeded = soakRate - j; if (netHitsNeeded < 1) netHitsNeeded = 1; float output = combinations(toHit, defenseRate + netHitsNeeded); output = 1 - pow(1-output,i); output *= 100; if (output <= 0.00000001) cout << output << "%\t\t"; else if (output < 0.1) cout << output << "%\t"; else cout << output << "%\t\t"; } cout << endl; } cout << endl; cout << "MOOKS\t"; for (int i=11; i<=15; i++) { cout << i << "DV\t\t"; } cout << endl; for (int i=1; i<=10; i++) { cout << i << "\t"; for (int j=11; j<=15; j++) { int netHitsNeeded = soakRate - j; if (netHitsNeeded < 1) netHitsNeeded = 1; float output = combinations(toHit, defenseRate + netHitsNeeded); output = 1 - pow(1-output,i); output *= 100; if (output <= 0.00000001) cout << output << "%\t\t"; else if (output < 0.1) cout << output << "%\t"; else cout << output << "%\t\t"; } cout << endl; } return 0; }
8696507b4e6636b1214507240078fd28cb13785a
0140aae256c803510c8ffa2cba2c0597bad5e9ed
/DP- Longest Repeating Subsequence.cpp
7b0d2b48454b8a457040cc199a4b578a00ea9ea0
[]
no_license
ks-kushagra/Algorithms
4d54cad638ed461a8a289a86802b17eea3c43b8e
8508b4780bb4cb42efd4ad5474c906a4241af4f1
refs/heads/master
2022-05-28T00:34:47.861290
2022-03-30T17:06:08
2022-03-30T17:06:08
252,371,902
1
0
null
null
null
null
UTF-8
C++
false
false
1,399
cpp
DP- Longest Repeating Subsequence.cpp
/* Longest Repeating Subsequence Given a string, find length of the longest repeating subseequence such that the two subsequence don’t have same string character at same position, i.e., any i’th character in the two subsequences shouldn’t have the same index in the original string. Input: str = "abc" Output: 0 There is no repeating subsequence Input: str = "aab" Output: 1 The two subssequence are 'a'(first) and 'a'(second). Note that 'b' cannot be considered as part of subsequence as it would be at same index in both. Input: str = "aabb" Output: 2 Input: str = "axxxy" Output: 2 */ _____________________________________________________________________________________________________________________________________________________________________________________________ #include<bits/stdc++.h> using namespace std; int lcs(string a ,string b ,int n) { vector <vector <int> > t(n+1 , vector <int> (n+1 , 0)); for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { if(i!=j && a[i-1] == b[j-1]) { t[i][j] = 1+t[i-1][j-1]; } else { t[i][j] = max(t[i-1][j] , t[i][j-1]); } } } return t[n][n]; } int main() { string a; cin>>a; cout<<lcs(a,a,a.length()); return 0; }
ad197c37193f5ffa4309f131d06fe151eef5aa64
9f1c4f342a9f52bb25ebda466c529f3eeddc910f
/Cplus/cProject64/traderJni/TraderJniClient.h
cf7c0e3691653b6c17e6e8247c1f95ac956f65b0
[]
no_license
jamesmasika/JNI
b2562bc472c2cc2ae190db74fb9f5dd8ce5b655c
fd653afe81ae7ba8de1fe83657df861675d66abf
refs/heads/master
2021-01-23T05:24:53.450390
2017-03-28T05:26:19
2017-03-28T05:26:19
86,304,703
0
0
null
null
null
null
GB18030
C++
false
false
650
h
TraderJniClient.h
#ifndef _TraderJniClient_H_ #define _TraderJniClient_H_ #include <jni.h> #include "TraderJniApi.h" #include "TraderJniSpi.h" class TraderJniClient { public: TraderJniClient(){}; ~TraderJniClient(){}; TraderJniApi * getTraderJniApi(){ return this->m_traderJniApi; }; TraderJniSpi * getTraderJniSpi(){ return this->m_traderJniSpi; }; //交易系统初始化 virtual bool InitInstance(char *frontAddr,char *userId,char *password,char *brokerId,JavaVM *vm,jobject jniTemplate); //交易系统退出 virtual void ExitInstance(); private: TraderJniSpi *m_traderJniSpi; CQTFtdcUserApi *m_userApi; TraderJniApi *m_traderJniApi; }; #endif
648176605e0bf9d7382163156a4cbe5f0fde8bec
0014d8cfd3f5b4d383bb1dd4b1f89d9dfb16a575
/src/experiments/server.cpp
c90d63a05f9a04852b0b0406d88b9f34d3756638
[ "MIT" ]
permissive
BADAL244/jetson
697a5780206cc18c077a4f1195524c8499c9ebdb
63e3b5be2eeb80e842ee2549c0bd4439580c7890
refs/heads/master
2020-09-16T03:09:46.556197
2015-07-01T02:50:21
2015-07-01T02:50:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,765
cpp
server.cpp
#include <stdlib.h> #include <iostream> #include <string.h> #include <arpa/inet.h> #include <netinet/in.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #define BUFLEN 512 #define PORT 8888 int main(int argc, char* argv[]) { struct sockaddr_in si_me; struct sockaddr_in si_other; int s; socklen_t slen = sizeof(si_other); int recv_len; char buf[BUFLEN]; // Create a UDP socket if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { std::cerr << "UDP socket creation failed" << std::endl; exit(1); } // Zero out my socket address memset((char*) &si_me, 0, sizeof(si_me)); // Set my socket address si_me.sin_family = AF_INET; si_me.sin_port = htons(PORT); si_me.sin_addr.s_addr = htonl(INADDR_ANY); // Bind socket to port if (bind(s, (struct sockaddr*)&si_me, sizeof(si_me)) == -1) { std::cerr << "Binding to UDP socket failed" << std::endl; exit(1); } // Listen for data for (;;) { std::cout << "Waiting for data from client..." << std::endl; // Receive data if ((recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr*)&si_other, &slen)) == -1) { std::cerr << "Receiving data from UDP socket failed" << std::endl; } // Print received data std::cout << "Received packet from " << inet_ntoa(si_other.sin_addr) << ": " << ntohs(si_other.sin_port) << std::endl; std::cout << "Data: " << buf << std::endl; // Send data if (sendto(s, buf, recv_len, 0, (struct sockaddr*)&si_other, slen) == -1) { std::cout << "Sending data to UDP socket failed" << std::endl; } } close(s); return EXIT_SUCCESS; }
2ed37aad8f7479831a80e3b8462d8c1b3ec97a52
da7abd64fc212f4f64c9e46c856a35be3546685f
/notes/module2/examples/exclusiveOr/main.cpp
eaec16422d737a0d456b065a5e13ac7b60c3eba8
[]
no_license
mortenoj/mathematics
6b15e800d768464065e57eab1348bc1cb7d85efc
be699a018f0b580af37266852309a31b700d10bd
refs/heads/master
2020-04-26T10:02:16.047873
2019-05-05T17:12:21
2019-05-05T17:12:21
173,475,855
0
0
null
null
null
null
UTF-8
C++
false
false
1,014
cpp
main.cpp
#include <iostream> int main(int argc, char const *argv[]) { int a = 4, b = 3; std::cout << "initial values of a and b: a = " << a << " b = " << b << std::endl; a = a^b; b = a^b; a = a^b; std::cout << "new values of a and b: a = " << a << " b = " << b << std::endl; // Clearing and setting bits int x = 10; std::cout << "initial x" << x << std::endl; x = x & ~(1 << 10); x = x | (1 << 10); x = x ^ (1 << 10); std::cout << "after bit logic: x" << x << std::endl; // std::cout << "in hex: " << std::hex << x << std::endl; // Multiply, divide and modulo 2^n x = 10; int y; int n = 4; y = x << n; y = x >> n; y = x & ((1<<n) - 1); std::cout << "Multiply, divide and modulo 2^n: " << y << "\n"; int x = 12124; int c = 0; while(x) { c++; // we clear least signifiant bit x = x & (x-1); } std::cout << "X: " << x <<"\nc: " << c <<"\n\n"; return 0; }
6227e83b2cfbf186d825730dea93af875c51621b
0b5011eb29a90517f9e229233e52d30a2e82133d
/ESP8266 Module Firmware/V2/ESPCraftModulesV2/wifi_.h
dc90b9ec529b6f9e81a23c361fc609278337f16d
[]
no_license
immakermatty/ESPCraft
e595bc5f66d7f208f1c067a92d2532074e33358c
c10381d407f5e8d2e7757936447ee883ef88c75e
refs/heads/master
2020-04-01T09:54:30.411465
2019-03-20T16:43:27
2019-03-20T16:43:27
153,094,430
0
0
null
null
null
null
UTF-8
C++
false
false
1,475
h
wifi_.h
#ifndef MODULEWIFI_H #define MODULEWIFI_H #include "module.h" #include <ESP8266WiFi.h> class ModuleWifi { private: String _ssid = MY_WIFI_SSID; String _pass = MY_WIFI_PASSWORD; String _name = BOARD_NAME; protected: Control *control; public: ModuleWifi(Control *c) { control = c; } ModuleWifi(Control *c, String ssid, String pass, String name) { control = c; _ssid = ssid; _pass = pass; _name = name; } void begin() { log_logln(); log_log(F("Connecting to ")); log_logln(_ssid); int count = 0; WiFi.begin(_ssid.c_str(), _pass.c_str()); while (WiFi.status() != WL_CONNECTED) { count++; if (count > 120) { control->fireEvent(Events::EV_MODULE_ERROR, YELLOW_ERROR_CODE, "Can't connect to a wifi network"); control->fireEvent(Events::EV_MODULE_RESTART, 0, ""); return; } else { log_log("."); } delay(1000); } //WiFi.hostname(WIFI_NAME); log_log(F(" IP address: ")); log_logln(WiFi.localIP()); } void loop() { int count = 0; if (WiFi.status() != WL_CONNECTED) { log_logln(); log_log(F("Connecting to ")); log_logln(_ssid); while (WiFi.status() != WL_CONNECTED) { count++; if (count > 60) { control->fireEvent(Events::EV_MODULE_ERROR, YELLOW_ERROR_CODE, "Can't connect to a wifi network"); control->fireEvent(Events::EV_MODULE_RESTART, 0, ""); return; } else { log_log("."); } delay(1000); } } } }; #endif // WIFI_ENABLE
cdc02c9faff40236b7da2f09edce1df4fa62c7aa
a04b6b706aed29af28139e57aeba853dd659d827
/src/interface/lib-cpp.h
e21de9b58c6b221ee859fc681ef6e4bf95254654
[ "MIT" ]
permissive
samuell/cell-runtime
21e749e7d873600c5fd00cbe7ddd1801cccdb889
033680ecf9d554fbd55666f05c76cc8e23e0eb25
refs/heads/master
2023-03-20T08:20:24.932847
2018-08-21T09:39:07
2018-08-21T09:39:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,153
h
lib-cpp.h
#include <vector> #include <string> #include <tuple> #include <memory> #include <sstream> #include "cell-lang.h" using std::vector; using std::string; using std::tuple; using std::unique_ptr; using std::make_tuple; /////////////////////////////////// value.cpp ////////////////////////////////// unique_ptr<cell::Value> export_as_value(OBJ); //////////////////////////////// conversion.cpp //////////////////////////////// string export_as_std_string(OBJ); ////////////////////////////////// lib-cpp.cpp ///////////////////////////////// bool table_contains(UNARY_TABLE &, VALUE_STORE &, OBJ); bool table_contains(BINARY_TABLE &, VALUE_STORE &, VALUE_STORE &, OBJ, OBJ); bool table_contains(TERNARY_TABLE &, VALUE_STORE &, VALUE_STORE &, VALUE_STORE &, OBJ, OBJ, OBJ); //////////////////////////////////////////////////////////////////////////////// template <typename T> vector<typename T::type> export_as_vector(OBJ obj) { assert(is_seq(obj) | is_set(obj)); vector<typename T::type> result; if (is_ne_seq(obj)) { uint32 len = get_seq_length(obj); OBJ *buffer = get_seq_buffer_ptr(obj); result.resize(len); for (uint32 i=0 ; i < len ; i++) result[i] = T::get_value(buffer[i]); return result; } else if (is_ne_set(obj)) { SET_OBJ *ptr = get_set_ptr(obj); uint32 size = ptr->size; OBJ *buffer = ptr->buffer; result.resize(size); for (uint32 i=0 ; i < size ; i++) result[i] = T::get_value(buffer[i]); } return result; } //////////////////////////////////////////////////////////////////////////////// struct bool_conv { typedef bool type; static bool get_value(OBJ obj) { return get_bool(obj); } }; struct int_conv { typedef long long type; static long long get_value(OBJ obj) { return get_int(obj); } }; struct float_conv { typedef double type; static double get_value(OBJ obj) { return get_float(obj); } }; struct symb_conv { typedef const char *type; static const char *get_value(OBJ obj) { return symb_to_raw_str(obj); } }; struct string_conv { typedef string type; static string get_value(OBJ obj) { return export_as_std_string(obj); } }; template <typename T> struct vector_conv { typedef vector<typename T::type> type; static type get_value(OBJ obj) { return export_as_vector<T>(obj); } }; template <typename T> struct tagged_conv { typedef typename T::type type; static type get_value(OBJ obj) { return T::get_value(get_inner_obj(obj)); } }; // template <typename... Ts> struct tuple_conv { // typedef tuple<typename Ts::type...> type; // static type get_value(OBJ obj) { // } // }; struct generic_conv { typedef unique_ptr<cell::Value> type; static type get_value(OBJ obj) { return export_as_value(obj); } }; //////////////////////////////////////////////////////////////////////////////// template <typename T0, typename T1> struct tuple_2_conv { typedef tuple<typename T0::type, typename T1::type> type; static type get_value(OBJ obj) { return make_tuple( T0::get_value(at(obj, 0)), T1::get_value(at(obj, 1)) ); } }; template <typename T0, typename T1, typename T2> struct tuple_3_conv { typedef tuple<typename T0::type, typename T1::type, typename T2::type> type; static type get_value(OBJ obj) { return make_tuple( T0::get_value(at(obj, 0)), T1::get_value(at(obj, 1)), T2::get_value(at(obj, 2)) ); } }; template <typename T0, typename T1, typename T2, typename T3> struct tuple_4_conv { typedef tuple<typename T0::type, typename T1::type, typename T2::type, typename T3::type> type; static type get_value(OBJ obj) { return make_tuple( T0::get_value(at(obj, 0)), T1::get_value(at(obj, 1)), T2::get_value(at(obj, 2)), T3::get_value(at(obj, 3)) ); } }; template <typename T0, typename T1, typename T2, typename T3, typename T4> struct tuple_5_conv { typedef tuple<typename T0::type, typename T1::type, typename T2::type, typename T3::type, typename T4::type> type; static type get_value(OBJ obj) { return make_tuple( T0::get_value(at(obj, 0)), T1::get_value(at(obj, 1)), T2::get_value(at(obj, 2)), T3::get_value(at(obj, 3)), T4::get_value(at(obj, 4)) ); } }; template <typename T0, typename T1, typename T2, typename T3, typename T4, typename T5> struct tuple_6_conv { typedef tuple< typename T0::type, typename T1::type, typename T2::type, typename T3::type, typename T4::type, typename T5::type > type; static type get_value(OBJ obj) { return make_tuple( T0::get_value(at(obj, 0)), T1::get_value(at(obj, 1)), T2::get_value(at(obj, 2)), T3::get_value(at(obj, 3)), T4::get_value(at(obj, 4)), T5::get_value(at(obj, 5)) ); } }; //////////////////////////////////////////////////////////////////////////////// template <typename T> vector<typename T::type> get_unary_rel(UNARY_TABLE &table, VALUE_STORE &store) { uint32 size = table.count; vector<typename T::type> result(size); UNARY_TABLE_ITER iter; unary_table_get_iter(&table, &iter); for (uint32 i=0 ; i < size ; i++) { assert(!unary_table_iter_is_out_of_range(&iter)); OBJ obj = lookup_surrogate(&store, unary_table_iter_get_field(&iter)); result[i] = T::get_value(obj); release(obj); unary_table_iter_next(&iter); } assert(unary_table_iter_is_out_of_range(&iter)); return result; } template <typename T0, typename T1> vector<tuple<typename T0::type, typename T1::type> > get_binary_rel(BINARY_TABLE &table, VALUE_STORE &store0, VALUE_STORE &store1, bool flipped) { uint32 size = table.left_to_right.size(); vector<tuple<typename T0::type, typename T1::type> > result(size); BINARY_TABLE_ITER iter; binary_table_get_iter(&table, &iter); for (uint32 i=0 ; i < size ; i++) { assert(!binary_table_iter_is_out_of_range(&iter)); OBJ obj0 = lookup_surrogate(&store0, binary_table_iter_get_left_field(&iter)); OBJ obj1 = lookup_surrogate(&store1, binary_table_iter_get_right_field(&iter)); result[i] = make_tuple(T0::get_value(flipped ? obj1 : obj0), T1::get_value(flipped ? obj0 : obj1)); release(obj0); release(obj1); binary_table_iter_next(&iter); } assert(binary_table_iter_is_out_of_range(&iter)); return result; } template <typename T0, typename T1, typename T2> vector<tuple<typename T0::type, typename T1::type, typename T2::type> > get_ternary_rel(TERNARY_TABLE &table, VALUE_STORE &store0, VALUE_STORE &store1, VALUE_STORE &store2, int idx0, int idx1, int idx2) { uint32 size = table.unshifted.size(); vector<tuple<typename T0::type, typename T1::type, typename T2::type> > result(size); TERNARY_TABLE_ITER iter; ternary_table_get_iter(&table, &iter); for (uint32 i=0 ; i < size ; i++) { assert(!ternary_table_iter_is_out_of_range(&iter)); OBJ objs[3]; objs[0] = lookup_surrogate(&store0, ternary_table_iter_get_left_field(&iter)); objs[1] = lookup_surrogate(&store1, ternary_table_iter_get_middle_field(&iter)); objs[2] = lookup_surrogate(&store2, ternary_table_iter_get_right_field(&iter)); result[i] = make_tuple(T0::get_value(objs[idx0]), T1::get_value(objs[idx1]), T2::get_value(objs[idx2])); for (int i=0 ; i < 3 ; i++) release(objs[i]); ternary_table_iter_next(&iter); } assert(ternary_table_iter_is_out_of_range(&iter)); return result; } //////////////////////////////////////////////////////////////////////////////// template <typename T> bool lookup_by_left_col(BINARY_TABLE &table, VALUE_STORE &store0, VALUE_STORE &store1, OBJ key, typename T::type &value) { int64 surr = lookup_value(&store0, key); release(key); if (surr == -1) return false; BINARY_TABLE_ITER iter; binary_table_get_iter_by_col_0(&table, &iter, surr); if (binary_table_iter_is_out_of_range(&iter)) return false; OBJ obj = lookup_surrogate(&store1, binary_table_iter_get_right_field(&iter)); value = T::get_value(obj); release(obj); #ifndef NDEBUG binary_table_iter_next(&iter); assert(binary_table_iter_is_out_of_range(&iter)); #endif return true; }
7d8b8254e94fed5377234a0bc2f80419e9f49ba8
5e9044c1032ccfa3fd9e216dcd255cc908e7e92b
/D3DXCamera.h
ea25187c9a8efcf357512fcba1b92a8c181766ff
[]
no_license
AspenDove/SolarSystem
ded88d172a5369673aa88198a8e1cff1e8e8129d
324deab9e6c718ac02a4ae835e032fc7898577ac
refs/heads/master
2020-11-25T20:36:20.712785
2019-12-18T12:21:29
2019-12-18T12:21:29
228,834,399
0
0
null
null
null
null
GB18030
C++
false
false
3,123
h
D3DXCamera.h
#ifndef _D3DXCAMERA_ #define _D3DXCAMERA_ #include <d3dx9.h> class D3DXCamera { private: D3DXVECTOR3 m_vCameraPos; //相机位置 D3DXVECTOR3 m_vCameraLook; //视线方向 D3DXVECTOR3 m_vCameraUp; //竖直方向 D3DXVECTOR3 m_vCameraRight; //右手方向 LPDIRECT3DDEVICE9 m_pd3dDevice; D3DXMATRIX m_matView; bool bLookAt = false; bool bWatchMode = false; public: D3DXCamera(LPDIRECT3DDEVICE9 pd3dDevice) :D3DXCamera(D3DXVECTOR3(0.0f, 0.0f, -5000.0f)) { m_pd3dDevice = pd3dDevice; D3DXMatrixIdentity(&m_matView); } D3DXCamera(D3DXVECTOR3 vPos); void SetCameraPos(float x, float y, float z); void GetCameraPos(float *x, float *y, float *z); D3DXVECTOR3 GetCameraPos(void); void SetCameraPos(D3DXVECTOR3 vPos); void MoveCameraLR(float fLR); void MoveCameraFB(float fFB); void MoveCameraUD(float fUD); void RotateCameraLR(float fYaw); void RotateCameraUD(float fPitch); void SlopeCameraLR(float fAngle); void CameraLookAtRotating(bool *bAimAt, bool *bWatchAt, D3DXVECTOR3 vPos, float fRadius, float timeDelta); void KeyBoardMove(float fMoveRatio, float RotateRatio); void SetCamera(D3DXVECTOR3 vPos, D3DXVECTOR3 vLook, D3DXVECTOR3 vUp, D3DXVECTOR3 vRight); void SetCamera(void); }; struct LensFlare { IDirect3DTexture9 *m_pTexFlare; float m_fPosition, m_fSize; D3DXCOLOR m_crColor; D3DXVECTOR3 m_Center; LensFlare(){} LensFlare(int iId,IDirect3DTexture9* pTexFlare, float fPos, float fSize, D3DXCOLOR crColor) : m_pTexFlare(pTexFlare), m_fPosition(fPos), m_fSize(fSize), m_crColor(crColor) { switch (iId) { case 0:m_Center = D3DXVECTOR3(16.0f, 16.0f,0.0f); break; case 1:m_Center = D3DXVECTOR3(32.0f, 32.0f,0.0f); break; case 2:m_Center = D3DXVECTOR3(60.0f, 60.0f,0.0f); break; case 3:m_Center = D3DXVECTOR3(75.0f, 75.0f, 0.0f); break; } } }; class D3DXCameraLensFlare { public: IDirect3DDevice9 *m_pd3dDevice; IDirect3DTexture9 *m_pTexFlares[5]; D3DXVECTOR3 m_vLightPos, m_vScrCenterPos, m_vLightScrPos; ID3DXSprite *m_pFlare; LensFlare *m_pLensFlare; public: D3DXCameraLensFlare(IDirect3DDevice9 *pd3dDevice, int cxClient, int cyClient) :m_vScrCenterPos(cxClient / 2.0f, cyClient / 2.0f, 0.0f) { m_pd3dDevice = pd3dDevice; m_vLightPos = D3DXVECTOR3(0.0f, 0.0f, 0.0f); D3DXCreateTextureFromFile(m_pd3dDevice, TEXT("flare1.png"), &m_pTexFlares[0]); D3DXCreateTextureFromFile(m_pd3dDevice, TEXT("flare2.png"), &m_pTexFlares[1]); D3DXCreateTextureFromFile(m_pd3dDevice, TEXT("flare3.png"), &m_pTexFlares[2]); D3DXCreateTextureFromFile(m_pd3dDevice, TEXT("flare4.png"), &m_pTexFlares[3]); D3DXCreateSprite(m_pd3dDevice, &m_pFlare); m_pLensFlare = new LensFlare[10]; ZeroMemory(m_pLensFlare, 10 * sizeof(LensFlare)); InitializeFlares(); } ~D3DXCameraLensFlare() { d3d::Release<ID3DXSprite*>(m_pFlare); d3d::Release<IDirect3DTexture9*>(m_pTexFlares[0]); d3d::Release<IDirect3DTexture9*>(m_pTexFlares[1]); d3d::Release<IDirect3DTexture9*>(m_pTexFlares[2]); d3d::Release<IDirect3DTexture9*>(m_pTexFlares[3]); }; void InitializeFlares(void); HRESULT ComputeLightScreenPos(void); void Render(void); }; #endif //_D3DXCAMERA_
e99e3ab440f3bbb5ff88ab18ae328505d9bfefcb
6fe17c32ba5bb492e276e13128c516a3f85f01ff
/beginagain/beginagain2/915B. Browser.cpp
ef015e68958f0ff8cc14f1f2e05886eb6ccd298f
[]
no_license
YaminArafat/Codeforces
35c5c527c8edd51c7f591bfe6474060934241d86
3d72ba0b5c9408a8e2491b25b5b643e9f9be728b
refs/heads/master
2023-08-17T03:12:04.596632
2021-10-06T14:49:29
2021-10-06T14:49:29
351,042,898
0
0
null
null
null
null
UTF-8
C++
false
false
678
cpp
915B. Browser.cpp
#include<bits/stdc++.h> using namespace std; int main() { int n,pos,l,r,ans=0; cin>>n>>pos>>l>>r; if(pos>=l && pos<=r) { if(l>1 && r<n) { ans=((pos-l)<=(r-pos)?(pos-l)*2+(r-pos):(r-pos)*2+(pos-l))+2; } else if(r<n) { ans=r-pos+1; } else if (l>1) { ans=pos-l+1; } } else { if(pos<l) { ans=l-pos+1; if(r<n) ans+=r-l+1; } else if(pos>r) { ans=pos-r+1; if(l>1) ans+=r-l+1; } } cout<<ans<<endl; return 0; }