hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
9108955b49f7f48dea454530454dc867462dd24c
2,495
cpp
C++
libvast/src/system/signal_monitor.cpp
vast-io/vast
6c9c787adc54079202dba85ea4a929004063f1ba
[ "BSD-3-Clause" ]
63
2016-04-22T01:50:03.000Z
2019-07-31T15:50:36.000Z
libvast/src/system/signal_monitor.cpp
vast-io/vast
6c9c787adc54079202dba85ea4a929004063f1ba
[ "BSD-3-Clause" ]
216
2017-01-24T16:25:43.000Z
2019-08-01T19:37:00.000Z
libvast/src/system/signal_monitor.cpp
vast-io/vast
6c9c787adc54079202dba85ea4a929004063f1ba
[ "BSD-3-Clause" ]
28
2016-05-19T13:09:19.000Z
2019-04-12T15:11:42.000Z
// _ _____ __________ // | | / / _ | / __/_ __/ Visibility // | |/ / __ |_\ \ / / Across // |___/_/ |_/___/ /_/ Space and Time // // SPDX-FileCopyrightText: (c) 2016 The VAST Contributors // SPDX-License-Identifier: BSD-3-Clause #include "vast/system/signal_monitor.hpp" #include "vast/fwd.hpp" #include "vast/atoms.hpp" #include "vast/logger.hpp" #include <caf/actor.hpp> #include <caf/send.hpp> #include <atomic> #include <csignal> #include <cstdlib> #include <cstring> #include <iostream> #include <thread> using namespace caf; namespace { // Keeps track of all signals by their value from 1 to 31. The flag at index 0 // is used to tell whether a signal has been raised or not. std::atomic<bool> signals[32]; extern "C" void signal_monitor_handler(int sig) { // Catch termination signals only once to allow forced termination by the OS // upon sending the signal a second time. if (sig == SIGINT || sig == SIGTERM) { std::cerr << "\rinitiating graceful shutdown... (repeat request to " "terminate immediately)\n"; std::signal(sig, SIG_DFL); } signals[0] = true; signals[sig] = true; } } // namespace namespace vast::system { std::atomic<bool> signal_monitor::stop; void signal_monitor::run(std::chrono::milliseconds monitoring_interval, actor receiver) { [[maybe_unused]] static constexpr auto class_name = "signal_monitor"; VAST_DEBUG("{} sends signals to {}", class_name, receiver); for (auto s : {SIGHUP, SIGINT, SIGQUIT, SIGTERM, SIGUSR1, SIGUSR2}) { VAST_DEBUG("{} registers signal handler for {}", class_name, strsignal(s)); std::signal(s, &signal_monitor_handler); } while (!stop) { std::this_thread::sleep_for(monitoring_interval); if (signals[0]) { // TODO: this handling of singals is fundamentally unsafe, because we // always have a race between the singal handler and this loop on // singals[0]. This needs to be re-implemented in a truly atomic // fashion, probably via CAS operaions and a single 32-bit integer. signals[0] = false; for (int i = 1; i < 32; ++i) { if (signals[i]) { VAST_DEBUG("{} caught signal {}", class_name, strsignal(i)); signals[i] = false; caf::anon_send<caf::message_priority::high>(receiver, atom::signal_v, i); } } } } } } // namespace vast::system
30.802469
79
0.625651
vast-io
910affbde23fb26cd3aaa8866651a6385ef9f13f
20,815
cpp
C++
src/mme-app/utils/mmeContextManagerUtils.cpp
aggarwalanubhav/Nucleus
107113cd9a1b68b1a28b35091ed17785ed32d319
[ "Apache-2.0" ]
null
null
null
src/mme-app/utils/mmeContextManagerUtils.cpp
aggarwalanubhav/Nucleus
107113cd9a1b68b1a28b35091ed17785ed32d319
[ "Apache-2.0" ]
null
null
null
src/mme-app/utils/mmeContextManagerUtils.cpp
aggarwalanubhav/Nucleus
107113cd9a1b68b1a28b35091ed17785ed32d319
[ "Apache-2.0" ]
1
2021-05-18T07:21:24.000Z
2021-05-18T07:21:24.000Z
/* * Copyright (c) 2019, Infosys Ltd. * * SPDX-License-Identifier: Apache-2.0 */ #include <cmath> #include <controlBlock.h> #include <contextManager/subsDataGroupManager.h> #include <err_codes.h> #include <log.h> #include <mmeStates/createBearerProcedureStates.h> #include <mmeStates/dedBearerActProcedureStates.h> #include <mmeStates/dedBearerDeactProcedureStates.h> #include <mmeStates/deleteBearerProcedureStates.h> #include <mmeStates/ueInitDetachStates.h> #include <mmeStates/networkInitDetachStates.h> #include <mmeStates/s1HandoverStates.h> #include <mmeStates/serviceRequestStates.h> #include <mmeStates/tauStates.h> #include <mmeStates/erabModIndicationStates.h> #include <utils/mmeContextManagerUtils.h> #include <utils/mmeCommonUtils.h> #include <utils/mmeTimerUtils.h> #include "mmeStatsPromClient.h" #define BEARER_ID_OFFSET 4 #define FIRST_SET_BIT(bits) log2(bits & -bits) + 1 #define CLEAR_BIT(bits,pos) bits &= ~(1 << pos) #define SET_BIT(bits,pos) bits |= (1 << pos) using namespace mme; MmeDetachProcedureCtxt* MmeContextManagerUtils::allocateDetachProcedureCtxt(SM::ControlBlock& cb_r, DetachType detachType) { log_msg(LOG_DEBUG, "allocateDetachProcedureCtxt: Entry"); MmeDetachProcedureCtxt *prcdCtxt_p = SubsDataGroupManager::Instance()->getMmeDetachProcedureCtxt(); if (prcdCtxt_p != NULL) { prcdCtxt_p->setCtxtType(ProcedureType::detach_c); prcdCtxt_p->setDetachType(detachType); if (detachType == ueInitDetach_c) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_DETACH_PROC_UE_INIT); prcdCtxt_p->setNextState(DetachStart::Instance()); } else { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_DETACH_PROC_NETWORK_INIT); prcdCtxt_p->setNextState(NiDetachStart::Instance()); } cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } MmeSvcReqProcedureCtxt* MmeContextManagerUtils::allocateServiceRequestProcedureCtxt(SM::ControlBlock& cb_r, PagingTrigger pagingTrigger) { log_msg(LOG_DEBUG, "allocateServiceRequestProcedureCtxt: Entry"); MmeSvcReqProcedureCtxt *prcdCtxt_p = SubsDataGroupManager::Instance()->getMmeSvcReqProcedureCtxt(); if (prcdCtxt_p != NULL) { prcdCtxt_p->setCtxtType(ProcedureType::serviceRequest_c); prcdCtxt_p->setPagingTrigger(pagingTrigger); if (pagingTrigger == ddnInit_c) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_SERVICE_REQUEST_PROC_DDN_INIT); prcdCtxt_p->setNextState(PagingStart::Instance()); } else if(pagingTrigger == pgwInit_c) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_SERVICE_REQUEST_PROC_PGW_INIT); prcdCtxt_p->setNextState(PagingStart::Instance()); } else { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_SERVICE_REQUEST_PROC_UE_INIT); prcdCtxt_p->setNextState(ServiceRequestStart::Instance()); } cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } MmeTauProcedureCtxt* MmeContextManagerUtils::allocateTauProcedureCtxt(SM::ControlBlock& cb_r) { log_msg(LOG_DEBUG, "allocateTauRequestProcedureCtxt: Entry"); MmeTauProcedureCtxt *prcdCtxt_p = SubsDataGroupManager::Instance()->getMmeTauProcedureCtxt(); if (prcdCtxt_p != NULL) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_TAU_PROC); prcdCtxt_p->setCtxtType(ProcedureType::tau_c); prcdCtxt_p->setNextState(TauStart::Instance()); cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } MmeErabModIndProcedureCtxt* MmeContextManagerUtils::allocateErabModIndProcedureCtxt(SM::ControlBlock& cb_r) { log_msg(LOG_DEBUG, "allocateErabModIndRequestProcedureCtxt: Entry"); MmeErabModIndProcedureCtxt *prcdCtxt_p = SubsDataGroupManager::Instance()->getMmeErabModIndProcedureCtxt(); if (prcdCtxt_p != NULL) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_ERAB_MOD_IND_PROC); prcdCtxt_p->setCtxtType(ProcedureType::erabModInd_c); prcdCtxt_p->setNextState(ErabModIndStart::Instance()); cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } S1HandoverProcedureContext* MmeContextManagerUtils::allocateHoContext(SM::ControlBlock& cb_r) { log_msg(LOG_DEBUG, "allocateHoProcedureCtxt: Entry"); S1HandoverProcedureContext *prcdCtxt_p = SubsDataGroupManager::Instance()->getS1HandoverProcedureContext(); if (prcdCtxt_p != NULL) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_S1_ENB_HANDOVER_PROC); prcdCtxt_p->setCtxtType(ProcedureType::s1Handover_c); prcdCtxt_p->setNextState(IntraS1HoStart::Instance()); prcdCtxt_p->setHoType(intraMmeS1Ho_c); cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } SrvccProcedureContext* MmeContextManagerUtils::allocateSrvccContext(SM::ControlBlock& cb_r) { log_msg(LOG_DEBUG, "allocateSrvccContext: Entry"); SrvccProcedureContext *prcdCtxt_p = SubsDataGroupManager::Instance()->getSrvccProcedureContext(); if (prcdCtxt_p != NULL) { //mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_S1_ENB_HANDOVER_PROC); prcdCtxt_p->setCtxtType(ProcedureType::srvcc_c); //prcdCtxt_p->setNextState(IntraS1HoStart::Instance()); //prcdCtxt_p->setHoType(intraMmeS1Ho_c); cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } MmeSmCreateBearerProcCtxt* MmeContextManagerUtils::allocateCreateBearerRequestProcedureCtxt(SM::ControlBlock& cb_r, uint8_t bearerId) { log_msg(LOG_DEBUG, "allocateCreateBearerRequestProcedureCtxt: Entry"); MmeSmCreateBearerProcCtxt *prcdCtxt_p = SubsDataGroupManager::Instance()->getMmeSmCreateBearerProcCtxt(); if (prcdCtxt_p != NULL) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_CREATE_BEARER_PROC); prcdCtxt_p->setCtxtType(ProcedureType::cbReq_c); prcdCtxt_p->setNextState(CreateBearerStart::Instance()); prcdCtxt_p->setBearerId(bearerId); cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } MmeSmDeleteBearerProcCtxt* MmeContextManagerUtils::allocateDeleteBearerRequestProcedureCtxt(SM::ControlBlock& cb_r, uint8_t bearerId) { log_msg(LOG_DEBUG, "allocateDeleteBearerRequestProcedureCtxt: Entry"); MmeSmDeleteBearerProcCtxt *prcdCtxt_p = SubsDataGroupManager::Instance()->getMmeSmDeleteBearerProcCtxt(); if (prcdCtxt_p != NULL) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_DELETE_BEARER_PROC); prcdCtxt_p->setCtxtType(ProcedureType::dbReq_c); prcdCtxt_p->setNextState(DeleteBearerStart::Instance()); prcdCtxt_p->setBearerId(bearerId); cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } SmDedActProcCtxt* MmeContextManagerUtils::allocateDedBrActivationProcedureCtxt(SM::ControlBlock& cb_r, uint8_t bearerId) { log_msg(LOG_DEBUG, "allocateDedBrActivationProcedureCtxt: Entry"); SmDedActProcCtxt *prcdCtxt_p = SubsDataGroupManager::Instance()->getSmDedActProcCtxt(); if (prcdCtxt_p != NULL) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_DED_BEARER_ACTIVATION_PROC); prcdCtxt_p->setCtxtType(ProcedureType::dedBrActivation_c); prcdCtxt_p->setNextState(DedActStart::Instance()); prcdCtxt_p->setBearerId(bearerId); cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } SmDedDeActProcCtxt* MmeContextManagerUtils::allocateDedBrDeActivationProcedureCtxt(SM::ControlBlock& cb_r, uint8_t bearerId) { log_msg(LOG_DEBUG, "allocateDedBrDeActivationProcedureCtxt: Entry"); SmDedDeActProcCtxt *prcdCtxt_p = SubsDataGroupManager::Instance()->getSmDedDeActProcCtxt(); if (prcdCtxt_p != NULL) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_DED_BEARER_DEACTIVATION_PROC); prcdCtxt_p->setCtxtType(ProcedureType::dedBrDeActivation_c); prcdCtxt_p->setNextState(DedDeactStart::Instance()); prcdCtxt_p->setBearerId(bearerId); cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } bool MmeContextManagerUtils::deleteProcedureCtxt(MmeProcedureCtxt* procedure_p) { log_msg(LOG_DEBUG, "deleteProcedureCtxt: Entry"); if (procedure_p == NULL) { log_msg(LOG_INFO, "Procedure Context is NULL"); return false; } SubsDataGroupManager* subsDgMgr_p = SubsDataGroupManager::Instance(); log_msg(LOG_INFO, "Procedure Type is %d", procedure_p->getCtxtType()); bool rc = true; switch (procedure_p->getCtxtType()) { case attach_c: { MmeAttachProcedureCtxt* atchProc_p = static_cast<MmeAttachProcedureCtxt *>(procedure_p); subsDgMgr_p->deleteMmeAttachProcedureCtxt(atchProc_p); break; } case s1Release_c: { MmeS1RelProcedureCtxt* s1RelProc_p = static_cast<MmeS1RelProcedureCtxt *>(procedure_p); subsDgMgr_p->deleteMmeS1RelProcedureCtxt(s1RelProc_p); break; } case detach_c: { MmeDetachProcedureCtxt* detachProc_p = static_cast<MmeDetachProcedureCtxt *>(procedure_p); subsDgMgr_p->deleteMmeDetachProcedureCtxt(detachProc_p); break; } case serviceRequest_c: { MmeSvcReqProcedureCtxt* svcReqProc_p = static_cast<MmeSvcReqProcedureCtxt*>(procedure_p); subsDgMgr_p->deleteMmeSvcReqProcedureCtxt(svcReqProc_p); break; } case tau_c: { MmeTauProcedureCtxt* tauProc_p = static_cast<MmeTauProcedureCtxt*>(procedure_p); subsDgMgr_p->deleteMmeTauProcedureCtxt(tauProc_p); break; } case s1Handover_c: { S1HandoverProcedureContext* s1HoProc_p = static_cast<S1HandoverProcedureContext*>(procedure_p); subsDgMgr_p->deleteS1HandoverProcedureContext(s1HoProc_p); break; } case srvcc_c: { SrvccProcedureContext* srvcc_p = static_cast<SrvccProcedureContext*>(procedure_p); subsDgMgr_p->deleteSrvccProcedureContext(srvcc_p); break; } case erabModInd_c: { MmeErabModIndProcedureCtxt* erabModIndProc_p = static_cast<MmeErabModIndProcedureCtxt*>(procedure_p); subsDgMgr_p->deleteMmeErabModIndProcedureCtxt(erabModIndProc_p); break; } case cbReq_c: { MmeSmCreateBearerProcCtxt* cbReqProc_p = static_cast<MmeSmCreateBearerProcCtxt*>(procedure_p); subsDgMgr_p->deleteMmeSmCreateBearerProcCtxt(cbReqProc_p); break; } case dedBrActivation_c: { SmDedActProcCtxt* dedActProc_p = static_cast<SmDedActProcCtxt*>(procedure_p); subsDgMgr_p->deleteSmDedActProcCtxt(dedActProc_p); break; } case dbReq_c: { MmeSmDeleteBearerProcCtxt* dbReqProc_p = static_cast<MmeSmDeleteBearerProcCtxt*>(procedure_p); subsDgMgr_p->deleteMmeSmDeleteBearerProcCtxt(dbReqProc_p); break; } case dedBrDeActivation_c: { SmDedDeActProcCtxt* dedDeActProc_p = static_cast<SmDedDeActProcCtxt*>(procedure_p); subsDgMgr_p->deleteSmDedDeActProcCtxt(dedDeActProc_p); break; } default: { log_msg(LOG_INFO, "Unsupported procedure type %d", procedure_p->getCtxtType()); rc = false; } } return rc; } bool MmeContextManagerUtils::deallocateProcedureCtxt(SM::ControlBlock& cb_r, MmeProcedureCtxt* procedure_p) { if (procedure_p == NULL) { log_msg(LOG_DEBUG, "procedure_p is NULL "); return true; } if (procedure_p->getCtxtType() == defaultMmeProcedure_c) { log_msg(LOG_ERROR, "CB %d trying to delete default procedure context ", cb_r.getCBIndex()); return true; } bool rc = false; // Remove the procedure from the temp data block list // maintained by the control block cb_r.removeTempDataBlock(procedure_p); // Stop any timers running MmeTimerUtils::stopTimer(procedure_p->getStateGuardTimerCtxt()); // return the procedure context to mem-pool deleteProcedureCtxt(procedure_p); return rc; } bool MmeContextManagerUtils::deallocateAllProcedureCtxts(SM::ControlBlock& cb_r) { bool rc = false; MmeProcedureCtxt* procedure_p = static_cast<MmeProcedureCtxt*>(cb_r.getFirstTempDataBlock()); MmeProcedureCtxt* nextProcedure_p = NULL; while (procedure_p != NULL) { nextProcedure_p = static_cast<MmeProcedureCtxt*>(procedure_p->getNextTempDataBlock()); if (procedure_p->getCtxtType() != defaultMmeProcedure_c) { // stop state guard timer if any running deallocateProcedureCtxt(cb_r, procedure_p); } procedure_p = nextProcedure_p; } return rc; } MmeProcedureCtxt* MmeContextManagerUtils::findProcedureCtxt(SM::ControlBlock& cb_r, ProcedureType procType, uint8_t bearerId) { MmeProcedureCtxt* mmeProcCtxt_p = NULL; MmeProcedureCtxt* currentProcedure_p = static_cast<MmeProcedureCtxt*>(cb_r.getFirstTempDataBlock()); MmeProcedureCtxt* nextProcedure_p = NULL; while (currentProcedure_p != NULL) { nextProcedure_p = static_cast<MmeProcedureCtxt*>( currentProcedure_p->getNextTempDataBlock()); if (currentProcedure_p->getCtxtType() == procType) { mmeProcCtxt_p = currentProcedure_p; break; } currentProcedure_p = nextProcedure_p; } return mmeProcCtxt_p; } void MmeContextManagerUtils::deleteAllSessionContext(SM::ControlBlock& cb_r) { UEContext *ueCtxt_p = static_cast<UEContext*>(cb_r.getPermDataBlock()); if (ueCtxt_p == NULL) { log_msg(LOG_DEBUG, "Failed to retrieve UEContext from control block %u", cb_r.getCBIndex()); return; } auto &sessionCtxtContainer = ueCtxt_p->getSessionContextContainer(); if (sessionCtxtContainer.size() < 1) { log_msg(LOG_ERROR, "Session context list is empty for UE IDX %d", cb_r.getCBIndex()); return; } auto it = sessionCtxtContainer.begin(); SessionContext *session_p = NULL; while (it != sessionCtxtContainer.end()) { session_p = *it; it++; deallocateSessionContext(cb_r, session_p, ueCtxt_p); } } void MmeContextManagerUtils::deleteUEContext(uint32_t cbIndex, bool deleteControlBlockFlag) { SM::ControlBlock* cb_p = SubsDataGroupManager::Instance()->findControlBlock(cbIndex); if (cb_p == NULL) { log_msg(LOG_DEBUG, "Failed to find control block for index %u", cbIndex); return; } deallocateAllProcedureCtxts(*cb_p); deleteAllSessionContext(*cb_p); UEContext* ueCtxt_p = static_cast<UEContext *>(cb_p->getPermDataBlock()); if (ueCtxt_p == NULL) { log_msg(LOG_DEBUG, "Unable to retrieve UEContext from control block %u", cbIndex); } else { MmContext* mmContext_p = ueCtxt_p->getMmContext(); if (mmContext_p != NULL) { SubsDataGroupManager::Instance()->deleteMmContext(mmContext_p); ueCtxt_p->setMmContext(NULL); } // Remove IMSI -> CBIndex key mapping const DigitRegister15& ue_imsi = ueCtxt_p->getImsi(); SubsDataGroupManager::Instance()->deleteimsikey(ue_imsi); // Remove mTMSI -> CBIndex mapping SubsDataGroupManager::Instance()->deletemTmsikey(ueCtxt_p->getMTmsi()); SubsDataGroupManager::Instance()->deleteUEContext(ueCtxt_p); cb_p->setPermDataBlock(NULL); } if (deleteControlBlockFlag) SubsDataGroupManager::Instance()->deAllocateCB(cb_p->getCBIndex()); } SessionContext* MmeContextManagerUtils::allocateSessionContext(SM::ControlBlock &cb_r, UEContext &ueCtxt) { SessionContext *sessionCtxt_p = SubsDataGroupManager::Instance()->getSessionContext(); if (sessionCtxt_p != NULL) { BearerContext *bearerCtxt_p = MmeContextManagerUtils::allocateBearerContext(cb_r, ueCtxt, *sessionCtxt_p); if (bearerCtxt_p == NULL) { log_msg(LOG_DEBUG, "Failed to allocate bearer context"); SubsDataGroupManager::Instance()->deleteSessionContext( sessionCtxt_p); return NULL; } sessionCtxt_p->setLinkedBearerId(bearerCtxt_p->getBearerId()); ueCtxt.addSessionContext(sessionCtxt_p); } return sessionCtxt_p; } BearerContext* MmeContextManagerUtils::allocateBearerContext(SM::ControlBlock &cb_r, UEContext &uectxt, SessionContext &sessionCtxt) { BearerContext *bearerCtxt_p = NULL; uint16_t bitmap = uectxt.getBearerIdBitMap(); // 0x7FF : All bearers ids are allocated. uint8_t id = (bitmap == 0x7FF) ? 0 : (FIRST_SET_BIT(~bitmap)); if (id > 0 && id <= 11) { bearerCtxt_p = SubsDataGroupManager::Instance()->getBearerContext(); if (bearerCtxt_p != NULL) { bearerCtxt_p->setBearerId(id + BEARER_ID_OFFSET); // Bearer id start 5 id--; SET_BIT(bitmap, id); uectxt.setBearerIdBitMap(bitmap); sessionCtxt.addBearerContext(bearerCtxt_p); } } mmeStats::Instance()->increment( mmeStatsCounter::MME_NUM_BEARERS); return bearerCtxt_p; } void MmeContextManagerUtils::deallocateSessionContext(SM::ControlBlock &cb_r, SessionContext *sessionCtxt_p, UEContext* ueContext_p) { if (sessionCtxt_p != NULL) { if (ueContext_p != NULL) ueContext_p ->removeSessionContext(sessionCtxt_p); auto &bearerCtxtContainer = sessionCtxt_p->getBearerContextContainer(); if (bearerCtxtContainer.size() < 1) { log_msg(LOG_ERROR, "Bearer context list is empty for UE IDX %d", cb_r.getCBIndex()); return; } auto it = bearerCtxtContainer.begin(); BearerContext *bearer_p = NULL; while (it != bearerCtxtContainer.end()) { bearer_p = *it; it++; deallocateBearerContext(cb_r, bearer_p, sessionCtxt_p, ueContext_p); } SubsDataGroupManager::Instance()->deleteSessionContext(sessionCtxt_p); } } void MmeContextManagerUtils::deallocateBearerContext(SM::ControlBlock &cb_r, BearerContext *bearerCtxt_p, SessionContext *sessionCtxt_p, UEContext *ueCtxt_p) { if (bearerCtxt_p != NULL) { // Remove from bearer context container if (sessionCtxt_p != NULL) sessionCtxt_p->removeBearerContext(bearerCtxt_p); // clear the id in the bitmap if (ueCtxt_p != NULL) { uint16_t bitmap = ueCtxt_p->getBearerIdBitMap(); uint8_t bearerId = bearerCtxt_p->getBearerId(); if (bearerId >= 5 && bearerId <= 15) { uint8_t id = bearerId - BEARER_ID_OFFSET - 1; CLEAR_BIT(bitmap, id); ueCtxt_p->setBearerIdBitMap(bitmap); } } SubsDataGroupManager::Instance()->deleteBearerContext(bearerCtxt_p); mmeStats::Instance()->decrement( mmeStatsCounter::MME_NUM_BEARERS); } } BearerContext* MmeContextManagerUtils::findBearerContext(uint8_t bearerId, UEContext *ueCtxt_p, SessionContext *sessionCtxt_p) { BearerContext *bearerCtxt_p = NULL; if (sessionCtxt_p != NULL) { bearerCtxt_p = sessionCtxt_p->findBearerContextByBearerId(bearerId); } else { auto &sessionCtxtContainer = ueCtxt_p->getSessionContextContainer(); for (auto sessEntry : sessionCtxtContainer) { bearerCtxt_p = sessEntry->findBearerContextByBearerId(bearerId); if (bearerCtxt_p != NULL) break; } } return bearerCtxt_p; } SessionContext* MmeContextManagerUtils::findSessionCtxtForEpsBrId(uint8_t bearerId, UEContext *ueCtxt_p) { SessionContext *sessCtxt_p = NULL; BearerContext *bearerCtxt_p = NULL; auto &sessionCtxtContainer = ueCtxt_p->getSessionContextContainer(); for (auto sessEntry : sessionCtxtContainer) { bearerCtxt_p = sessEntry->findBearerContextByBearerId(bearerId); if (bearerCtxt_p != NULL) { sessCtxt_p = sessEntry; break; } } return sessCtxt_p; }
30.386861
125
0.684122
aggarwalanubhav
510454def85f339ae7c3e550d51c096e69e7b911
750
cpp
C++
ros2_mod_ws/build/std_srvs/rosidl_typesupport_c/std_srvs/srv/empty__type_support.cpp
mintforpeople/robobo-ros2-ios-port
1a5650304bd41060925ebba41d6c861d5062bfae
[ "Apache-2.0" ]
1
2020-05-19T14:33:49.000Z
2020-05-19T14:33:49.000Z
ros2_mod_ws/build/std_srvs/rosidl_typesupport_c/std_srvs/srv/empty__type_support.cpp
mintforpeople/robobo-ros2-ios-port
1a5650304bd41060925ebba41d6c861d5062bfae
[ "Apache-2.0" ]
null
null
null
ros2_mod_ws/build/std_srvs/rosidl_typesupport_c/std_srvs/srv/empty__type_support.cpp
mintforpeople/robobo-ros2-ios-port
1a5650304bd41060925ebba41d6c861d5062bfae
[ "Apache-2.0" ]
null
null
null
// generated from rosidl_typesupport_c/resource/srv__type_support.cpp.em // generated code does not contain a copyright notice #include <cstddef> #include "rosidl_generator_c/service_type_support_struct.h" #include "std_srvs/msg/rosidl_typesupport_c__visibility_control.h" #include "rosidl_typesupport_interface/macros.h" #include "std_srvs/srv/empty__rosidl_typesupport_introspection_c.h" #ifdef __cplusplus extern "C" { #endif ROSIDL_TYPESUPPORT_C_EXPORT_std_srvs const rosidl_service_type_support_t * ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME(rosidl_typesupport_c, std_srvs, Empty)() { return ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME(rosidl_typesupport_introspection_c, std_srvs, Empty)(); } #ifdef __cplusplus } #endif
26.785714
114
0.849333
mintforpeople
5105961852b2abe6f1b5cdda2d2d9fd01fe5ca34
317
cpp
C++
models/model_robertson/model_robertson_M.cpp
paszkow/AMICI
a0407673453d6e18a9abec5b6f73758dd09f7aaf
[ "BSD-3-Clause" ]
null
null
null
models/model_robertson/model_robertson_M.cpp
paszkow/AMICI
a0407673453d6e18a9abec5b6f73758dd09f7aaf
[ "BSD-3-Clause" ]
null
null
null
models/model_robertson/model_robertson_M.cpp
paszkow/AMICI
a0407673453d6e18a9abec5b6f73758dd09f7aaf
[ "BSD-3-Clause" ]
null
null
null
#include "amici/symbolic_functions.h" #include "amici/defines.h" //realtype definition typedef amici::realtype realtype; #include <cmath> using namespace amici; void M_model_robertson(realtype *M, const realtype t, const realtype *x, const realtype *p, const realtype *k) { M[0+0*3] = 1.0; M[1+1*3] = 1.0; }
22.642857
112
0.712934
paszkow
51066701eaff539f3f66d545f3214ad8a0d6ddef
6,239
cpp
C++
quic/api/QuicBatchWriter.cpp
neko-suki/mvfst
275edda5be49742221dfb0072e93786eb79cdc43
[ "MIT" ]
1
2020-01-29T06:41:43.000Z
2020-01-29T06:41:43.000Z
quic/api/QuicBatchWriter.cpp
neko-suki/mvfst
275edda5be49742221dfb0072e93786eb79cdc43
[ "MIT" ]
null
null
null
quic/api/QuicBatchWriter.cpp
neko-suki/mvfst
275edda5be49742221dfb0072e93786eb79cdc43
[ "MIT" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ #include <quic/api/QuicBatchWriter.h> namespace quic { // BatchWriter bool BatchWriter::needsFlush(size_t /*unused*/) { return false; } // SinglePacketBatchWriter void SinglePacketBatchWriter::reset() { buf_.reset(); } bool SinglePacketBatchWriter::append( std::unique_ptr<folly::IOBuf>&& buf, size_t /*unused*/) { buf_ = std::move(buf); // needs to be flushed return true; } ssize_t SinglePacketBatchWriter::write( folly::AsyncUDPSocket& sock, const folly::SocketAddress& address) { return sock.write(address, buf_); } // GSOPacketBatchWriter GSOPacketBatchWriter::GSOPacketBatchWriter(size_t maxBufs) : maxBufs_(maxBufs) {} void GSOPacketBatchWriter::reset() { buf_.reset(nullptr); currBufs_ = 0; prevSize_ = 0; } bool GSOPacketBatchWriter::needsFlush(size_t size) { // if we get a buffer with a size that is greater // than the prev one we need to flush return (prevSize_ && (size > prevSize_)); } bool GSOPacketBatchWriter::append( std::unique_ptr<folly::IOBuf>&& buf, size_t size) { // first buffer if (!buf_) { DCHECK_EQ(currBufs_, 0); buf_ = std::move(buf); prevSize_ = size; currBufs_ = 1; return false; // continue } // now we've got an additional buffer // append it to the chain buf_->prependChain(std::move(buf)); currBufs_++; // see if we've added a different size if (size != prevSize_) { CHECK_LT(size, prevSize_); return true; } // reached max buffers if (FOLLY_UNLIKELY(currBufs_ == maxBufs_)) { return true; } // does not need to be flushed yet return false; } ssize_t GSOPacketBatchWriter::write( folly::AsyncUDPSocket& sock, const folly::SocketAddress& address) { return (currBufs_ > 1) ? sock.writeGSO(address, buf_, static_cast<int>(prevSize_)) : sock.write(address, buf_); } // SendmmsgPacketBatchWriter SendmmsgPacketBatchWriter::SendmmsgPacketBatchWriter(size_t maxBufs) : maxBufs_(maxBufs) { bufs_.reserve(maxBufs); } bool SendmmsgPacketBatchWriter::empty() const { return !currSize_; } size_t SendmmsgPacketBatchWriter::size() const { return currSize_; } void SendmmsgPacketBatchWriter::reset() { bufs_.clear(); currSize_ = 0; } bool SendmmsgPacketBatchWriter::append( std::unique_ptr<folly::IOBuf>&& buf, size_t size) { CHECK_LT(bufs_.size(), maxBufs_); bufs_.emplace_back(std::move(buf)); currSize_ += size; // reached max buffers if (FOLLY_UNLIKELY(bufs_.size() == maxBufs_)) { return true; } // does not need to be flushed yet return false; } ssize_t SendmmsgPacketBatchWriter::write( folly::AsyncUDPSocket& sock, const folly::SocketAddress& address) { CHECK_GT(bufs_.size(), 0); if (bufs_.size() == 1) { return sock.write(address, bufs_[0]); } int ret = sock.writem(address, bufs_.data(), bufs_.size()); if (ret <= 0) { return ret; } if (static_cast<size_t>(ret) == bufs_.size()) { return currSize_; } // this is a partial write - we just need to // return a different number than currSize_ return 0; } // SendmmsgGSOPacketBatchWriter SendmmsgGSOPacketBatchWriter::SendmmsgGSOPacketBatchWriter(size_t maxBufs) : maxBufs_(maxBufs) { bufs_.reserve(maxBufs); } bool SendmmsgGSOPacketBatchWriter::empty() const { return !currSize_; } size_t SendmmsgGSOPacketBatchWriter::size() const { return currSize_; } void SendmmsgGSOPacketBatchWriter::reset() { bufs_.clear(); gso_.clear(); currBufs_ = 0; currSize_ = 0; prevSize_ = 0; } bool SendmmsgGSOPacketBatchWriter::append( std::unique_ptr<folly::IOBuf>&& buf, size_t size) { currSize_ += size; // see if we need to start a new chain if (size > prevSize_) { bufs_.emplace_back(std::move(buf)); // set the gso_ value to 0 for now // this will change if we append to this chain gso_.emplace_back(0); prevSize_ = size; currBufs_++; // reached max buffers if (FOLLY_UNLIKELY(currBufs_ == maxBufs_)) { return true; } return false; } gso_.back() = prevSize_; bufs_.back()->prependChain(std::move(buf)); currBufs_++; // reached max buffers if (FOLLY_UNLIKELY(currBufs_ == maxBufs_)) { return true; } if (size < prevSize_) { // reset the prevSize_ so in the next loop // we will start a new chain prevSize_ = 0; } return false; } ssize_t SendmmsgGSOPacketBatchWriter::write( folly::AsyncUDPSocket& sock, const folly::SocketAddress& address) { CHECK_GT(bufs_.size(), 0); if (bufs_.size() == 1) { return (currBufs_ > 1) ? sock.writeGSO(address, bufs_[0], gso_[0]) : sock.write(address, bufs_[0]); } int ret = sock.writemGSO(address, bufs_.data(), bufs_.size(), gso_.data()); if (ret <= 0) { return ret; } if (static_cast<size_t>(ret) == bufs_.size()) { return currSize_; } // this is a partial write - we just need to // return a different number than currSize_ return 0; } // BatchWriterFactory std::unique_ptr<BatchWriter> BatchWriterFactory::makeBatchWriter( folly::AsyncUDPSocket& sock, const quic::QuicBatchingMode& batchingMode, uint32_t batchSize) { switch (batchingMode) { case quic::QuicBatchingMode::BATCHING_MODE_NONE: return std::make_unique<SinglePacketBatchWriter>(); case quic::QuicBatchingMode::BATCHING_MODE_GSO: { if (sock.getGSO() >= 0) { return std::make_unique<GSOPacketBatchWriter>(batchSize); } return std::make_unique<SinglePacketBatchWriter>(); } case quic::QuicBatchingMode::BATCHING_MODE_SENDMMSG: return std::make_unique<SendmmsgPacketBatchWriter>(batchSize); case quic::QuicBatchingMode::BATCHING_MODE_SENDMMSG_GSO: { if (sock.getGSO() >= 0) { return std::make_unique<SendmmsgGSOPacketBatchWriter>(batchSize); } return std::make_unique<SendmmsgPacketBatchWriter>(batchSize); } // no default so we can catch missing case at compile time } folly::assume_unreachable(); } } // namespace quic
23.279851
77
0.677032
neko-suki
51067fb7034721216304f1ce1b0206557d544038
38,851
cpp
C++
src/etl/ETLSource.cpp
crypticrabbit/clio
ffc8779a14f22e25830e801487e898cec6c2f5c2
[ "ISC" ]
null
null
null
src/etl/ETLSource.cpp
crypticrabbit/clio
ffc8779a14f22e25830e801487e898cec6c2f5c2
[ "ISC" ]
null
null
null
src/etl/ETLSource.cpp
crypticrabbit/clio
ffc8779a14f22e25830e801487e898cec6c2f5c2
[ "ISC" ]
null
null
null
#include <ripple/beast/net/IPEndpoint.h> #include <ripple/protocol/STLedgerEntry.h> #include <boost/asio/strand.hpp> #include <boost/beast/http.hpp> #include <boost/beast/ssl.hpp> #include <boost/json.hpp> #include <boost/json/src.hpp> #include <boost/log/trivial.hpp> #include <backend/DBHelpers.h> #include <etl/ETLSource.h> #include <etl/ReportingETL.h> #include <thread> // Create ETL source without grpc endpoint // Fetch ledger and load initial ledger will fail for this source // Primarly used in read-only mode, to monitor when ledgers are validated template <class Derived> ETLSourceImpl<Derived>::ETLSourceImpl( boost::json::object const& config, boost::asio::io_context& ioContext, std::shared_ptr<BackendInterface> backend, std::shared_ptr<SubscriptionManager> subscriptions, std::shared_ptr<NetworkValidatedLedgers> networkValidatedLedgers, ETLLoadBalancer& balancer) : resolver_(boost::asio::make_strand(ioContext)) , networkValidatedLedgers_(networkValidatedLedgers) , backend_(backend) , subscriptions_(subscriptions) , balancer_(balancer) , ioc_(ioContext) , timer_(ioContext) { if (config.contains("ip")) { auto ipJs = config.at("ip").as_string(); ip_ = {ipJs.c_str(), ipJs.size()}; } if (config.contains("ws_port")) { auto portjs = config.at("ws_port").as_string(); wsPort_ = {portjs.c_str(), portjs.size()}; } if (config.contains("grpc_port")) { auto portjs = config.at("grpc_port").as_string(); grpcPort_ = {portjs.c_str(), portjs.size()}; try { boost::asio::ip::tcp::endpoint endpoint{ boost::asio::ip::make_address(ip_), std::stoi(grpcPort_)}; std::stringstream ss; ss << endpoint; stub_ = org::xrpl::rpc::v1::XRPLedgerAPIService::NewStub( grpc::CreateChannel( ss.str(), grpc::InsecureChannelCredentials())); BOOST_LOG_TRIVIAL(debug) << "Made stub for remote = " << toString(); } catch (std::exception const& e) { BOOST_LOG_TRIVIAL(debug) << "Exception while creating stub = " << e.what() << " . Remote = " << toString(); } } } template <class Derived> void ETLSourceImpl<Derived>::reconnect(boost::beast::error_code ec) { connected_ = false; // These are somewhat normal errors. operation_aborted occurs on shutdown, // when the timer is cancelled. connection_refused will occur repeatedly std::string err = ec.message(); // if we cannot connect to the transaction processing process if (ec.category() == boost::asio::error::get_ssl_category()) { err = std::string(" (") + boost::lexical_cast<std::string>(ERR_GET_LIB(ec.value())) + "," + boost::lexical_cast<std::string>(ERR_GET_REASON(ec.value())) + ") "; // ERR_PACK /* crypto/err/err.h */ char buf[128]; ::ERR_error_string_n(ec.value(), buf, sizeof(buf)); err += buf; std::cout << err << std::endl; } if (ec != boost::asio::error::operation_aborted && ec != boost::asio::error::connection_refused) { BOOST_LOG_TRIVIAL(error) << __func__ << " : " << "error code = " << ec << " - " << toString(); } else { BOOST_LOG_TRIVIAL(warning) << __func__ << " : " << "error code = " << ec << " - " << toString(); } // exponentially increasing timeouts, with a max of 30 seconds size_t waitTime = std::min(pow(2, numFailures_), 30.0); numFailures_++; timer_.expires_after(boost::asio::chrono::seconds(waitTime)); timer_.async_wait([this](auto ec) { bool startAgain = (ec != boost::asio::error::operation_aborted); BOOST_LOG_TRIVIAL(trace) << __func__ << " async_wait : ec = " << ec; derived().close(startAgain); }); } void PlainETLSource::close(bool startAgain) { timer_.cancel(); ioc_.post([this, startAgain]() { if (closing_) return; if (derived().ws().is_open()) { // onStop() also calls close(). If the async_close is called twice, // an assertion fails. Using closing_ makes sure async_close is only // called once closing_ = true; derived().ws().async_close( boost::beast::websocket::close_code::normal, [this, startAgain](auto ec) { if (ec) { BOOST_LOG_TRIVIAL(error) << __func__ << " async_close : " << "error code = " << ec << " - " << toString(); } closing_ = false; if (startAgain) run(); }); } else if (startAgain) { run(); } }); } void SslETLSource::close(bool startAgain) { timer_.cancel(); ioc_.post([this, startAgain]() { if (closing_) return; if (derived().ws().is_open()) { // onStop() also calls close(). If the async_close is called twice, // an assertion fails. Using closing_ makes sure async_close is only // called once closing_ = true; derived().ws().async_close( boost::beast::websocket::close_code::normal, [this, startAgain](auto ec) { if (ec) { BOOST_LOG_TRIVIAL(error) << __func__ << " async_close : " << "error code = " << ec << " - " << toString(); } closing_ = false; if (startAgain) { ws_ = std::make_unique<boost::beast::websocket::stream< boost::beast::ssl_stream< boost::beast::tcp_stream>>>( boost::asio::make_strand(ioc_), *sslCtx_); run(); } }); } else if (startAgain) { ws_ = std::make_unique<boost::beast::websocket::stream< boost::beast::ssl_stream<boost::beast::tcp_stream>>>( boost::asio::make_strand(ioc_), *sslCtx_); run(); } }); } template <class Derived> void ETLSourceImpl<Derived>::onResolve( boost::beast::error_code ec, boost::asio::ip::tcp::resolver::results_type results) { BOOST_LOG_TRIVIAL(trace) << __func__ << " : ec = " << ec << " - " << toString(); if (ec) { // try again reconnect(ec); } else { boost::beast::get_lowest_layer(derived().ws()) .expires_after(std::chrono::seconds(30)); boost::beast::get_lowest_layer(derived().ws()) .async_connect(results, [this](auto ec, auto ep) { derived().onConnect(ec, ep); }); } } void PlainETLSource::onConnect( boost::beast::error_code ec, boost::asio::ip::tcp::resolver::results_type::endpoint_type endpoint) { BOOST_LOG_TRIVIAL(trace) << __func__ << " : ec = " << ec << " - " << toString(); if (ec) { // start over reconnect(ec); } else { numFailures_ = 0; // Turn off timeout on the tcp stream, because websocket stream has it's // own timeout system boost::beast::get_lowest_layer(derived().ws()).expires_never(); // Set suggested timeout settings for the websocket derived().ws().set_option( boost::beast::websocket::stream_base::timeout::suggested( boost::beast::role_type::client)); // Set a decorator to change the User-Agent of the handshake derived().ws().set_option( boost::beast::websocket::stream_base::decorator( [](boost::beast::websocket::request_type& req) { req.set( boost::beast::http::field::user_agent, std::string(BOOST_BEAST_VERSION_STRING) + " clio-client"); req.set("X-User", "coro-client"); })); // Update the host_ string. This will provide the value of the // Host HTTP header during the WebSocket handshake. // See https://tools.ietf.org/html/rfc7230#section-5.4 auto host = ip_ + ':' + std::to_string(endpoint.port()); // Perform the websocket handshake derived().ws().async_handshake( host, "/", [this](auto ec) { onHandshake(ec); }); } } void SslETLSource::onConnect( boost::beast::error_code ec, boost::asio::ip::tcp::resolver::results_type::endpoint_type endpoint) { BOOST_LOG_TRIVIAL(trace) << __func__ << " : ec = " << ec << " - " << toString(); if (ec) { // start over reconnect(ec); } else { numFailures_ = 0; // Turn off timeout on the tcp stream, because websocket stream has it's // own timeout system boost::beast::get_lowest_layer(derived().ws()).expires_never(); // Set suggested timeout settings for the websocket derived().ws().set_option( boost::beast::websocket::stream_base::timeout::suggested( boost::beast::role_type::client)); // Set a decorator to change the User-Agent of the handshake derived().ws().set_option( boost::beast::websocket::stream_base::decorator( [](boost::beast::websocket::request_type& req) { req.set( boost::beast::http::field::user_agent, std::string(BOOST_BEAST_VERSION_STRING) + " clio-client"); req.set("X-User", "coro-client"); })); // Update the host_ string. This will provide the value of the // Host HTTP header during the WebSocket handshake. // See https://tools.ietf.org/html/rfc7230#section-5.4 auto host = ip_ + ':' + std::to_string(endpoint.port()); // Perform the websocket handshake ws().next_layer().async_handshake( boost::asio::ssl::stream_base::client, [this, endpoint](auto ec) { onSslHandshake(ec, endpoint); }); } } void SslETLSource::onSslHandshake( boost::beast::error_code ec, boost::asio::ip::tcp::resolver::results_type::endpoint_type endpoint) { if (ec) { reconnect(ec); } else { // Perform the websocket handshake auto host = ip_ + ':' + std::to_string(endpoint.port()); // Perform the websocket handshake ws().async_handshake(host, "/", [this](auto ec) { onHandshake(ec); }); } } template <class Derived> void ETLSourceImpl<Derived>::onHandshake(boost::beast::error_code ec) { BOOST_LOG_TRIVIAL(trace) << __func__ << " : ec = " << ec << " - " << toString(); if (ec) { // start over reconnect(ec); } else { boost::json::object jv{ {"command", "subscribe"}, {"streams", {"ledger", "manifests", "validations", "transactions_proposed"}}}; std::string s = boost::json::serialize(jv); BOOST_LOG_TRIVIAL(trace) << "Sending subscribe stream message"; derived().ws().set_option( boost::beast::websocket::stream_base::decorator( [](boost::beast::websocket::request_type& req) { req.set( boost::beast::http::field::user_agent, std::string(BOOST_BEAST_VERSION_STRING) + " clio-client"); req.set("X-User", "coro-client"); })); // Send the message derived().ws().async_write( boost::asio::buffer(s), [this](auto ec, size_t size) { onWrite(ec, size); }); } } template <class Derived> void ETLSourceImpl<Derived>::onWrite( boost::beast::error_code ec, size_t bytesWritten) { BOOST_LOG_TRIVIAL(trace) << __func__ << " : ec = " << ec << " - " << toString(); if (ec) { // start over reconnect(ec); } else { derived().ws().async_read( readBuffer_, [this](auto ec, size_t size) { onRead(ec, size); }); } } template <class Derived> void ETLSourceImpl<Derived>::onRead(boost::beast::error_code ec, size_t size) { BOOST_LOG_TRIVIAL(trace) << __func__ << " : ec = " << ec << " - " << toString(); // if error or error reading message, start over if (ec) { reconnect(ec); } else { handleMessage(); boost::beast::flat_buffer buffer; swap(readBuffer_, buffer); BOOST_LOG_TRIVIAL(trace) << __func__ << " : calling async_read - " << toString(); derived().ws().async_read( readBuffer_, [this](auto ec, size_t size) { onRead(ec, size); }); } } template <class Derived> bool ETLSourceImpl<Derived>::handleMessage() { BOOST_LOG_TRIVIAL(trace) << __func__ << " : " << toString(); setLastMsgTime(); connected_ = true; try { std::string msg{ static_cast<char const*>(readBuffer_.data().data()), readBuffer_.size()}; BOOST_LOG_TRIVIAL(trace) << __func__ << msg; boost::json::value raw = boost::json::parse(msg); BOOST_LOG_TRIVIAL(trace) << __func__ << " parsed"; boost::json::object response = raw.as_object(); uint32_t ledgerIndex = 0; if (response.contains("result")) { boost::json::object result = response["result"].as_object(); if (result.contains("ledger_index")) { ledgerIndex = result["ledger_index"].as_int64(); } if (result.contains("validated_ledgers")) { boost::json::string const& validatedLedgers = result["validated_ledgers"].as_string(); setValidatedRange( {validatedLedgers.c_str(), validatedLedgers.size()}); } BOOST_LOG_TRIVIAL(debug) << __func__ << " : " << "Received a message on ledger " << " subscription stream. Message : " << response << " - " << toString(); } else if ( response.contains("type") && response["type"] == "ledgerClosed") { BOOST_LOG_TRIVIAL(debug) << __func__ << " : " << "Received a message on ledger " << " subscription stream. Message : " << response << " - " << toString(); if (response.contains("ledger_index")) { ledgerIndex = response["ledger_index"].as_int64(); } if (response.contains("validated_ledgers")) { boost::json::string const& validatedLedgers = response["validated_ledgers"].as_string(); setValidatedRange( {validatedLedgers.c_str(), validatedLedgers.size()}); } } else { if (balancer_.shouldPropagateTxnStream(this)) { if (response.contains("transaction")) { subscriptions_->forwardProposedTransaction(response); } else if ( response.contains("type") && response["type"] == "validationReceived") { subscriptions_->forwardValidation(response); } else if ( response.contains("type") && response["type"] == "manifestReceived") { subscriptions_->forwardManifest(response); } } } if (ledgerIndex != 0) { BOOST_LOG_TRIVIAL(trace) << __func__ << " : " << "Pushing ledger sequence = " << ledgerIndex << " - " << toString(); networkValidatedLedgers_->push(ledgerIndex); } return true; } catch (std::exception const& e) { BOOST_LOG_TRIVIAL(error) << "Exception in handleMessage : " << e.what(); return false; } } class AsyncCallData { std::unique_ptr<org::xrpl::rpc::v1::GetLedgerDataResponse> cur_; std::unique_ptr<org::xrpl::rpc::v1::GetLedgerDataResponse> next_; org::xrpl::rpc::v1::GetLedgerDataRequest request_; std::unique_ptr<grpc::ClientContext> context_; grpc::Status status_; unsigned char nextPrefix_; std::string lastKey_; public: AsyncCallData( uint32_t seq, ripple::uint256 const& marker, std::optional<ripple::uint256> const& nextMarker) { request_.mutable_ledger()->set_sequence(seq); if (marker.isNonZero()) { request_.set_marker(marker.data(), marker.size()); } request_.set_user("ETL"); nextPrefix_ = 0x00; if (nextMarker) nextPrefix_ = nextMarker->data()[0]; unsigned char prefix = marker.data()[0]; BOOST_LOG_TRIVIAL(debug) << "Setting up AsyncCallData. marker = " << ripple::strHex(marker) << " . prefix = " << ripple::strHex(std::string(1, prefix)) << " . nextPrefix_ = " << ripple::strHex(std::string(1, nextPrefix_)); assert(nextPrefix_ > prefix || nextPrefix_ == 0x00); cur_ = std::make_unique<org::xrpl::rpc::v1::GetLedgerDataResponse>(); next_ = std::make_unique<org::xrpl::rpc::v1::GetLedgerDataResponse>(); context_ = std::make_unique<grpc::ClientContext>(); } enum class CallStatus { MORE, DONE, ERRORED }; CallStatus process( std::unique_ptr<org::xrpl::rpc::v1::XRPLedgerAPIService::Stub>& stub, grpc::CompletionQueue& cq, BackendInterface& backend, bool abort, bool cacheOnly = false) { BOOST_LOG_TRIVIAL(trace) << "Processing response. " << "Marker prefix = " << getMarkerPrefix(); if (abort) { BOOST_LOG_TRIVIAL(error) << "AsyncCallData aborted"; return CallStatus::ERRORED; } if (!status_.ok()) { BOOST_LOG_TRIVIAL(error) << "AsyncCallData status_ not ok: " << " code = " << status_.error_code() << " message = " << status_.error_message(); return CallStatus::ERRORED; } if (!next_->is_unlimited()) { BOOST_LOG_TRIVIAL(warning) << "AsyncCallData is_unlimited is false. Make sure " "secure_gateway is set correctly at the ETL source"; } std::swap(cur_, next_); bool more = true; // if no marker returned, we are done if (cur_->marker().size() == 0) more = false; // if returned marker is greater than our end, we are done unsigned char prefix = cur_->marker()[0]; if (nextPrefix_ != 0x00 && prefix >= nextPrefix_) more = false; // if we are not done, make the next async call if (more) { request_.set_marker(std::move(cur_->marker())); call(stub, cq); } BOOST_LOG_TRIVIAL(trace) << "Writing objects"; std::vector<Backend::LedgerObject> cacheUpdates; cacheUpdates.reserve(cur_->ledger_objects().objects_size()); for (int i = 0; i < cur_->ledger_objects().objects_size(); ++i) { auto& obj = *(cur_->mutable_ledger_objects()->mutable_objects(i)); if (!more && nextPrefix_ != 0x00) { if (((unsigned char)obj.key()[0]) >= nextPrefix_) continue; } cacheUpdates.push_back( {*ripple::uint256::fromVoidChecked(obj.key()), {obj.mutable_data()->begin(), obj.mutable_data()->end()}}); if (!cacheOnly) { if (lastKey_.size()) backend.writeSuccessor( std::move(lastKey_), request_.ledger().sequence(), std::string{obj.key()}); lastKey_ = obj.key(); backend.writeLedgerObject( std::move(*obj.mutable_key()), request_.ledger().sequence(), std::move(*obj.mutable_data())); } } backend.cache().update( cacheUpdates, request_.ledger().sequence(), cacheOnly); BOOST_LOG_TRIVIAL(trace) << "Wrote objects"; return more ? CallStatus::MORE : CallStatus::DONE; } void call( std::unique_ptr<org::xrpl::rpc::v1::XRPLedgerAPIService::Stub>& stub, grpc::CompletionQueue& cq) { context_ = std::make_unique<grpc::ClientContext>(); std::unique_ptr<grpc::ClientAsyncResponseReader< org::xrpl::rpc::v1::GetLedgerDataResponse>> rpc(stub->PrepareAsyncGetLedgerData(context_.get(), request_, &cq)); rpc->StartCall(); rpc->Finish(next_.get(), &status_, this); } std::string getMarkerPrefix() { if (next_->marker().size() == 0) return ""; else return ripple::strHex(std::string{next_->marker().data()[0]}); } std::string getLastKey() { return lastKey_; } }; template <class Derived> bool ETLSourceImpl<Derived>::loadInitialLedger( uint32_t sequence, uint32_t numMarkers, bool cacheOnly) { if (!stub_) return false; grpc::CompletionQueue cq; void* tag; bool ok = false; std::vector<AsyncCallData> calls; auto markers = getMarkers(numMarkers); for (size_t i = 0; i < markers.size(); ++i) { std::optional<ripple::uint256> nextMarker; if (i + 1 < markers.size()) nextMarker = markers[i + 1]; calls.emplace_back(sequence, markers[i], nextMarker); } BOOST_LOG_TRIVIAL(debug) << "Starting data download for ledger " << sequence << ". Using source = " << toString(); for (auto& c : calls) c.call(stub_, cq); size_t numFinished = 0; bool abort = false; size_t incr = 500000; size_t progress = incr; std::vector<std::string> edgeKeys; while (numFinished < calls.size() && cq.Next(&tag, &ok)) { assert(tag); auto ptr = static_cast<AsyncCallData*>(tag); if (!ok) { BOOST_LOG_TRIVIAL(error) << "loadInitialLedger - ok is false"; return false; // handle cancelled } else { BOOST_LOG_TRIVIAL(trace) << "Marker prefix = " << ptr->getMarkerPrefix(); auto result = ptr->process(stub_, cq, *backend_, abort, cacheOnly); if (result != AsyncCallData::CallStatus::MORE) { numFinished++; BOOST_LOG_TRIVIAL(debug) << "Finished a marker. " << "Current number of finished = " << numFinished; std::string lastKey = ptr->getLastKey(); if (lastKey.size()) edgeKeys.push_back(ptr->getLastKey()); } if (result == AsyncCallData::CallStatus::ERRORED) { abort = true; } if (backend_->cache().size() > progress) { BOOST_LOG_TRIVIAL(info) << "Downloaded " << backend_->cache().size() << " records from rippled"; progress += incr; } } } BOOST_LOG_TRIVIAL(info) << __func__ << " - finished loadInitialLedger. cache size = " << backend_->cache().size(); size_t numWrites = 0; if (!abort) { backend_->cache().setFull(); if (!cacheOnly) { auto start = std::chrono::system_clock::now(); for (auto& key : edgeKeys) { BOOST_LOG_TRIVIAL(debug) << __func__ << " writing edge key = " << ripple::strHex(key); auto succ = backend_->cache().getSuccessor( *ripple::uint256::fromVoidChecked(key), sequence); if (succ) backend_->writeSuccessor( std::move(key), sequence, uint256ToString(succ->key)); } ripple::uint256 prev = Backend::firstKey; while (auto cur = backend_->cache().getSuccessor(prev, sequence)) { assert(cur); if (prev == Backend::firstKey) { backend_->writeSuccessor( uint256ToString(prev), sequence, uint256ToString(cur->key)); } if (isBookDir(cur->key, cur->blob)) { auto base = getBookBase(cur->key); // make sure the base is not an actual object if (!backend_->cache().get(cur->key, sequence)) { auto succ = backend_->cache().getSuccessor(base, sequence); assert(succ); if (succ->key == cur->key) { BOOST_LOG_TRIVIAL(debug) << __func__ << " Writing book successor = " << ripple::strHex(base) << " - " << ripple::strHex(cur->key); backend_->writeSuccessor( uint256ToString(base), sequence, uint256ToString(cur->key)); } } ++numWrites; } prev = std::move(cur->key); if (numWrites % 100000 == 0 && numWrites != 0) BOOST_LOG_TRIVIAL(info) << __func__ << " Wrote " << numWrites << " book successors"; } backend_->writeSuccessor( uint256ToString(prev), sequence, uint256ToString(Backend::lastKey)); ++numWrites; auto end = std::chrono::system_clock::now(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(end - start) .count(); BOOST_LOG_TRIVIAL(info) << __func__ << " - Looping through cache and submitting all writes took " << seconds << " seconds. numWrites = " << std::to_string(numWrites); } } return !abort; } template <class Derived> std::pair<grpc::Status, org::xrpl::rpc::v1::GetLedgerResponse> ETLSourceImpl<Derived>::fetchLedger( uint32_t ledgerSequence, bool getObjects, bool getObjectNeighbors) { org::xrpl::rpc::v1::GetLedgerResponse response; if (!stub_) return {{grpc::StatusCode::INTERNAL, "No Stub"}, response}; // ledger header with txns and metadata org::xrpl::rpc::v1::GetLedgerRequest request; grpc::ClientContext context; request.mutable_ledger()->set_sequence(ledgerSequence); request.set_transactions(true); request.set_expand(true); request.set_get_objects(getObjects); request.set_get_object_neighbors(getObjectNeighbors); request.set_user("ETL"); grpc::Status status = stub_->GetLedger(&context, request, &response); if (status.ok() && !response.is_unlimited()) { BOOST_LOG_TRIVIAL(warning) << "ETLSourceImpl::fetchLedger - is_unlimited is " "false. Make sure secure_gateway is set " "correctly on the ETL source. source = " << toString() << " status = " << status.error_message(); } // BOOST_LOG_TRIVIAL(debug) // << __func__ << " Message size = " << response.ByteSizeLong(); return {status, std::move(response)}; } static std::unique_ptr<ETLSource> make_ETLSource( boost::json::object const& config, boost::asio::io_context& ioContext, std::optional<std::reference_wrapper<boost::asio::ssl::context>> sslCtx, std::shared_ptr<BackendInterface> backend, std::shared_ptr<SubscriptionManager> subscriptions, std::shared_ptr<NetworkValidatedLedgers> networkValidatedLedgers, ETLLoadBalancer& balancer) { std::unique_ptr<ETLSource> src = nullptr; if (sslCtx) { src = std::make_unique<SslETLSource>( config, ioContext, sslCtx, backend, subscriptions, networkValidatedLedgers, balancer); } else { src = std::make_unique<PlainETLSource>( config, ioContext, backend, subscriptions, networkValidatedLedgers, balancer); } src->run(); return src; } ETLLoadBalancer::ETLLoadBalancer( boost::json::object const& config, boost::asio::io_context& ioContext, std::optional<std::reference_wrapper<boost::asio::ssl::context>> sslCtx, std::shared_ptr<BackendInterface> backend, std::shared_ptr<SubscriptionManager> subscriptions, std::shared_ptr<NetworkValidatedLedgers> nwvl) { if (config.contains("num_markers") && config.at("num_markers").is_int64()) { downloadRanges_ = config.at("num_markers").as_int64(); downloadRanges_ = std::clamp(downloadRanges_, {1}, {256}); } else if (backend->fetchLedgerRange()) { downloadRanges_ = 4; } for (auto& entry : config.at("etl_sources").as_array()) { std::unique_ptr<ETLSource> source = make_ETLSource( entry.as_object(), ioContext, sslCtx, backend, subscriptions, nwvl, *this); sources_.push_back(std::move(source)); BOOST_LOG_TRIVIAL(info) << __func__ << " : added etl source - " << sources_.back()->toString(); } } void ETLLoadBalancer::loadInitialLedger(uint32_t sequence, bool cacheOnly) { execute( [this, &sequence, cacheOnly](auto& source) { bool res = source->loadInitialLedger(sequence, downloadRanges_, cacheOnly); if (!res) { BOOST_LOG_TRIVIAL(error) << "Failed to download initial ledger." << " Sequence = " << sequence << " source = " << source->toString(); } return res; }, sequence); } std::optional<org::xrpl::rpc::v1::GetLedgerResponse> ETLLoadBalancer::fetchLedger( uint32_t ledgerSequence, bool getObjects, bool getObjectNeighbors) { org::xrpl::rpc::v1::GetLedgerResponse response; bool success = execute( [&response, ledgerSequence, getObjects, getObjectNeighbors]( auto& source) { auto [status, data] = source->fetchLedger( ledgerSequence, getObjects, getObjectNeighbors); response = std::move(data); if (status.ok() && (response.validated() || true)) { BOOST_LOG_TRIVIAL(info) << "Successfully fetched ledger = " << ledgerSequence << " from source = " << source->toString(); return true; } else { BOOST_LOG_TRIVIAL(warning) << "Error getting ledger = " << ledgerSequence << " Reply : " << response.DebugString() << " error_code : " << status.error_code() << " error_msg : " << status.error_message() << " source = " << source->toString(); return false; } }, ledgerSequence); if (success) return response; else return {}; } std::optional<boost::json::object> ETLLoadBalancer::forwardToRippled( boost::json::object const& request, std::string const& clientIp, boost::asio::yield_context& yield) const { srand((unsigned)time(0)); auto sourceIdx = rand() % sources_.size(); auto numAttempts = 0; while (numAttempts < sources_.size()) { if (auto res = sources_[sourceIdx]->forwardToRippled(request, clientIp, yield)) return res; sourceIdx = (sourceIdx + 1) % sources_.size(); ++numAttempts; } return {}; } template <class Derived> std::optional<boost::json::object> ETLSourceImpl<Derived>::forwardToRippled( boost::json::object const& request, std::string const& clientIp, boost::asio::yield_context& yield) const { BOOST_LOG_TRIVIAL(debug) << "Attempting to forward request to tx. " << "request = " << boost::json::serialize(request); boost::json::object response; if (!connected_) { BOOST_LOG_TRIVIAL(error) << "Attempted to proxy but failed to connect to tx"; return {}; } namespace beast = boost::beast; // from <boost/beast.hpp> namespace http = beast::http; // from <boost/beast/http.hpp> namespace websocket = beast::websocket; // from namespace net = boost::asio; // from using tcp = boost::asio::ip::tcp; // from try { boost::beast::error_code ec; // These objects perform our I/O tcp::resolver resolver{ioc_}; BOOST_LOG_TRIVIAL(debug) << "Creating websocket"; auto ws = std::make_unique<websocket::stream<beast::tcp_stream>>(ioc_); // Look up the domain name auto const results = resolver.async_resolve(ip_, wsPort_, yield[ec]); if (ec) return {}; ws->next_layer().expires_after(std::chrono::seconds(3)); BOOST_LOG_TRIVIAL(debug) << "Connecting websocket"; // Make the connection on the IP address we get from a lookup ws->next_layer().async_connect(results, yield[ec]); if (ec) return {}; // Set a decorator to change the User-Agent of the handshake // and to tell rippled to charge the client IP for RPC // resources. See "secure_gateway" in // // https://github.com/ripple/rippled/blob/develop/cfg/rippled-example.cfg ws->set_option(websocket::stream_base::decorator( [&clientIp](websocket::request_type& req) { req.set( http::field::user_agent, std::string(BOOST_BEAST_VERSION_STRING) + " websocket-client-coro"); req.set(http::field::forwarded, "for=" + clientIp); })); BOOST_LOG_TRIVIAL(debug) << "client ip: " << clientIp; BOOST_LOG_TRIVIAL(debug) << "Performing websocket handshake"; // Perform the websocket handshake ws->async_handshake(ip_, "/", yield[ec]); if (ec) return {}; BOOST_LOG_TRIVIAL(debug) << "Sending request"; // Send the message ws->async_write( net::buffer(boost::json::serialize(request)), yield[ec]); if (ec) return {}; beast::flat_buffer buffer; ws->async_read(buffer, yield[ec]); if (ec) return {}; auto begin = static_cast<char const*>(buffer.data().data()); auto end = begin + buffer.data().size(); auto parsed = boost::json::parse(std::string(begin, end)); if (!parsed.is_object()) { BOOST_LOG_TRIVIAL(error) << "Error parsing response: " << std::string{begin, end}; return {}; } BOOST_LOG_TRIVIAL(debug) << "Successfully forward request"; response = parsed.as_object(); response["forwarded"] = true; return response; } catch (std::exception const& e) { BOOST_LOG_TRIVIAL(error) << "Encountered exception : " << e.what(); return {}; } } template <class Func> bool ETLLoadBalancer::execute(Func f, uint32_t ledgerSequence) { srand((unsigned)time(0)); auto sourceIdx = rand() % sources_.size(); auto numAttempts = 0; while (true) { auto& source = sources_[sourceIdx]; BOOST_LOG_TRIVIAL(debug) << __func__ << " : " << "Attempting to execute func. ledger sequence = " << ledgerSequence << " - source = " << source->toString(); if (source->hasLedger(ledgerSequence) || true) { bool res = f(source); if (res) { BOOST_LOG_TRIVIAL(debug) << __func__ << " : " << "Successfully executed func at source = " << source->toString() << " - ledger sequence = " << ledgerSequence; break; } else { BOOST_LOG_TRIVIAL(warning) << __func__ << " : " << "Failed to execute func at source = " << source->toString() << " - ledger sequence = " << ledgerSequence; } } else { BOOST_LOG_TRIVIAL(warning) << __func__ << " : " << "Ledger not present at source = " << source->toString() << " - ledger sequence = " << ledgerSequence; } sourceIdx = (sourceIdx + 1) % sources_.size(); numAttempts++; if (numAttempts % sources_.size() == 0) { BOOST_LOG_TRIVIAL(error) << __func__ << " : " << "Error executing function " << " - ledger sequence = " << ledgerSequence << " - Tried all sources. Sleeping and trying again"; std::this_thread::sleep_for(std::chrono::seconds(2)); } } return true; }
32.896698
81
0.524337
crypticrabbit
510a8912d1fb1aadb57f069a27baad9adb0206fc
2,279
cpp
C++
Practica2/ProyectosOGREvc15x86/IG2App/AspasMolino.cpp
nicoFdez/PracticasIG2
cae65f0020e9231b5575cabcc86280a26ab3ba6e
[ "MIT" ]
null
null
null
Practica2/ProyectosOGREvc15x86/IG2App/AspasMolino.cpp
nicoFdez/PracticasIG2
cae65f0020e9231b5575cabcc86280a26ab3ba6e
[ "MIT" ]
null
null
null
Practica2/ProyectosOGREvc15x86/IG2App/AspasMolino.cpp
nicoFdez/PracticasIG2
cae65f0020e9231b5575cabcc86280a26ab3ba6e
[ "MIT" ]
null
null
null
#include "AspasMolino.h" #include <OgreSceneManager.h> #include <OgreEntity.h> #include <SDL_keycode.h> #include "Avion.h" AspasMolino::AspasMolino(Ogre::SceneNode* rootNode, int numAspas, int number) : EntidadIG(), numAspas(numAspas) { Ogre::Entity* ent; if(modoGiro == 0) mNode = rootNode->createChildSceneNode("aspas" + std::to_string(number)); else { nodoFicticio = rootNode->createChildSceneNode("molino_aspas_ficticio" + std::to_string(number)); nodoFicticio->setPosition(0, 0, 0); mNode = nodoFicticio->createChildSceneNode("aspas" + std::to_string(number)); } mSM = mNode->getCreator(); arrayAspas = new Aspa*[numAspas]; for (int i = 0; i < numAspas; ++i) { Ogre::SceneNode* aspaNode = mNode->createChildSceneNode("aspa_" + std::to_string(number) + std::to_string(i)); Ogre::SceneNode* tableroNode = aspaNode->createChildSceneNode("tablero_" + std::to_string(number) + std::to_string(i)); Ogre::SceneNode* cilindroNode = aspaNode->createChildSceneNode("adorno_" + std::to_string(number) + std::to_string(i)); arrayAspas[i] = new Aspa(aspaNode, tableroNode, cilindroNode); aspaNode->roll(Ogre::Degree(-360.0/numAspas * i)); cilindroNode->roll(Ogre::Degree(360.0 / numAspas * i)); } ejeNode = mNode->createChildSceneNode("ejeAspasMolino" + std::to_string(number)); ent = mSM->createEntity("Barrel.mesh"); ent->setMaterialName("Practica1/hierro"); ejeNode->attachObject(ent); ejeNode->pitch(Ogre::Degree(90.0)); ejeNode->scale(20, 10, 20); ejeNode->setPosition(0, 0, 0); } void AspasMolino::move() { mNode->roll(Ogre::Degree(1.0)); for (int i = 0; i < numAspas; ++i) { arrayAspas[i]->move(-1.0); } } void AspasMolino::moveAxis() { ejeNode->setPosition({ 0, 0, -25 }); } void AspasMolino::rotate() { if (modoGiro == 0) { //truco mNode->setPosition(0, mNode->getPosition().y, 0); mNode->yaw(Ogre::Degree(2), Ogre::Node::TS_PARENT); rotationY += 2; mNode->translate(0, 0, 250, Ogre::Node::TS_LOCAL); } else { //Nodo ficticio nodoFicticio->yaw(Ogre::Degree(2)); } } void AspasMolino::hideOrnaments() { for (int i = 0; i < numAspas; ++i) { arrayAspas[i]->hideOrnament(); } } void AspasMolino::volar() { mNode->roll(Ogre::Degree(-25)); for (int i = 0; i < numAspas; ++i) { arrayAspas[i]->move(25); } }
27.792683
121
0.679684
nicoFdez
510c760baa2b3dae99bf5e0bafe5e7e8011aff1f
2,907
cpp
C++
character/character.cpp
Jay2645/character
8bd6943c39b7c859e054c2df6b274ba8b8de787d
[ "MIT" ]
2
2020-09-14T02:28:06.000Z
2022-01-27T23:57:24.000Z
character/character.cpp
Jay2645/character
8bd6943c39b7c859e054c2df6b274ba8b8de787d
[ "MIT" ]
null
null
null
character/character.cpp
Jay2645/character
8bd6943c39b7c859e054c2df6b274ba8b8de787d
[ "MIT" ]
2
2020-09-14T02:28:15.000Z
2021-01-08T03:38:12.000Z
#include "character.h" #include "scene/3d/camera.h" #include "scene/3d/collision_shape.h" #include "scene/3d/spatial.h" Character::Character() { connect("ready", this, "_character_ready"); set_physics_process(true); _command_manager = NULL; _movement = NULL; } void Character::_character_ready() { if (has_node(command_manager_path)) { _command_manager = cast_to<CommandManager>(get_node(command_manager_path)); if (_command_manager != NULL) { _command_manager->set_reciever(this); } } if (has_node(character_movement_path)) { _movement = cast_to<CharacterMovement>(get_node(character_movement_path)); } } void Character::_notification(int p_notification) { if (p_notification == NOTIFICATION_PHYSICS_PROCESS) { _physics_process(get_physics_process_delta_time()); } KinematicBody::_notification(p_notification); } void Character::_physics_process(float delta_time) { if (_command_manager != NULL) { _command_manager->execute_all_commands(delta_time); } if (_movement != NULL) { _movement->process_movement(delta_time); } } void Character::_bind_methods() { ClassDB::bind_method(D_METHOD("_character_ready"), &Character::_character_ready); ClassDB::bind_method(D_METHOD("set_command_manager_path", "command_paths"), &Character::set_command_manager_path); ClassDB::bind_method(D_METHOD("get_command_manager_path"), &Character::get_command_manager_path); ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "command_manager_path", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "CommandManager"), "set_command_manager_path", "get_command_manager_path"); ClassDB::bind_method(D_METHOD("set_character_movement_path", "movement_path"), &Character::set_character_movement_path); ClassDB::bind_method(D_METHOD("get_character_movement_path"), &Character::get_character_movement_path); ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "character_movement_path", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "CharacterMovement"), "set_character_movement_path", "get_character_movement_path"); ClassDB::bind_method(D_METHOD("get_character_movement"), &Character::get_character_movement); } void Character::set_command_manager_path(const NodePath &new_path) { command_manager_path = new_path; if (has_node(command_manager_path)) { _command_manager = cast_to<CommandManager>(get_node(command_manager_path)); } } NodePath Character::get_command_manager_path() const { return command_manager_path; } void Character::set_character_movement_path(const NodePath &new_path) { character_movement_path = new_path; if (has_node(character_movement_path)) { _movement = cast_to<CharacterMovement>(get_node(character_movement_path)); } } NodePath Character::get_character_movement_path() const { return character_movement_path; } CharacterMovement *Character::get_character_movement() const { return _movement; }
35.888889
196
0.778122
Jay2645
510d6f1f2c6977dc0579f719731dd5a7c2234321
3,339
hpp
C++
deps/boost/libs/beast/test/beast/core/file_test.hpp
alexhenrie/poedit
b9b31a111d9e8a84cf1e698aff2c922a79bdd859
[ "MIT" ]
1,155
2015-01-10T19:04:33.000Z
2022-03-30T12:30:30.000Z
deps/boost/libs/beast/test/beast/core/file_test.hpp
alexhenrie/poedit
b9b31a111d9e8a84cf1e698aff2c922a79bdd859
[ "MIT" ]
618
2015-01-02T01:39:26.000Z
2022-03-28T15:18:40.000Z
deps/boost/libs/beast/test/beast/core/file_test.hpp
alexhenrie/poedit
b9b31a111d9e8a84cf1e698aff2c922a79bdd859
[ "MIT" ]
228
2015-01-13T12:55:42.000Z
2022-03-30T11:11:05.000Z
// // Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/boostorg/beast // #ifndef BOOST_BEAST_TEST_CORE_FILE_TEST_HPP #define BOOST_BEAST_TEST_CORE_FILE_TEST_HPP #include <boost/beast/core/type_traits.hpp> #include <boost/beast/unit_test/suite.hpp> #include <boost/config.hpp> #include <boost/filesystem.hpp> #include <string> namespace boost { namespace beast { template<class File> void doTestFile(beast::unit_test::suite& test) { BOOST_STATIC_ASSERT(is_file<File>::value); error_code ec; auto const temp = boost::filesystem::unique_path(); { { File f1; test.BEAST_EXPECT(! f1.is_open()); f1.open(temp.string<std::string>().c_str(), file_mode::write, ec); test.BEAST_EXPECT(! ec); File f2{std::move(f1)}; test.BEAST_EXPECT(! f1.is_open()); test.BEAST_EXPECT(f2.is_open()); File f3; f3 = std::move(f2); test.BEAST_EXPECT(! f2.is_open()); test.BEAST_EXPECT(f3.is_open()); f1.close(ec); test.BEAST_EXPECT(! ec); auto const temp2 = boost::filesystem::unique_path(); f3.open(temp2.string<std::string>().c_str(), file_mode::read, ec); test.BEAST_EXPECT(ec); ec.assign(0, ec.category()); } boost::filesystem::remove(temp, ec); test.BEAST_EXPECT(! ec); } File f; test.BEAST_EXPECT(! f.is_open()); f.size(ec); test.BEAST_EXPECT(ec == errc::invalid_argument); ec.assign(0, ec.category()); f.pos(ec); test.BEAST_EXPECT(ec == errc::invalid_argument); ec.assign(0, ec.category()); f.seek(0, ec); test.BEAST_EXPECT(ec == errc::invalid_argument); ec.assign(0, ec.category()); char tmp[1]; f.read(tmp, 0, ec); test.BEAST_EXPECT(ec == errc::invalid_argument); ec.assign(0, ec.category()); f.write(tmp, 0, ec); test.BEAST_EXPECT(ec == errc::invalid_argument); ec.assign(0, ec.category()); f.open(temp.string<std::string>().c_str(), file_mode::write, ec); test.BEAST_EXPECT(! ec); std::string const s = "Hello, world!"; f.write(s.data(), s.size(), ec); test.BEAST_EXPECT(! ec); auto size = f.size(ec); test.BEAST_EXPECT(! ec); test.BEAST_EXPECT(size == s.size()); auto pos = f.pos(ec); test.BEAST_EXPECT(! ec); test.BEAST_EXPECT(pos == size); f.close(ec); test.BEAST_EXPECT(! ec); f.open(temp.string<std::string>().c_str(), file_mode::read, ec); test.BEAST_EXPECT(! ec); std::string buf; buf.resize(s.size()); f.read(&buf[0], buf.size(), ec); test.BEAST_EXPECT(! ec); test.BEAST_EXPECT(buf == s); f.seek(1, ec); test.BEAST_EXPECT(! ec); buf.resize(3); f.read(&buf[0], buf.size(), ec); test.BEAST_EXPECT(! ec); test.BEAST_EXPECT(buf == "ell"); pos = f.pos(ec); test.BEAST_EXPECT(! ec); test.BEAST_EXPECT(pos == 4); f.close(ec); test.BEAST_EXPECT(! ec); boost::filesystem::remove(temp, ec); test.BEAST_EXPECT(! ec); } } // beast } // boost #endif
25.883721
79
0.604373
alexhenrie
510d87800f34aa4a9523b96fe5dca8ba92f0c3e6
65
cpp
C++
TileDeck.cpp
kengonakajima/moyai
70077449eb2446de6c24de928050ad8affc6df3d
[ "Zlib" ]
37
2015-07-23T04:02:51.000Z
2021-09-23T08:39:12.000Z
TileDeck.cpp
kengonakajima/moyai
70077449eb2446de6c24de928050ad8affc6df3d
[ "Zlib" ]
1
2018-08-30T08:33:38.000Z
2018-08-30T08:33:38.000Z
TileDeck.cpp
kengonakajima/moyai
70077449eb2446de6c24de928050ad8affc6df3d
[ "Zlib" ]
8
2015-07-23T04:02:58.000Z
2020-11-10T14:52:12.000Z
#include "client.h" #include "TileDeck.h" int Deck::idgen = 1;
10.833333
21
0.661538
kengonakajima
510e94ca8586abf80c106ea9f05427606c552c32
368
hpp
C++
plugins/community/repos/rcm/include/PianoRoll/Auditioner.hpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
233
2018-07-02T16:49:36.000Z
2022-02-27T21:45:39.000Z
plugins/community/repos/rcm/include/PianoRoll/Auditioner.hpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
24
2018-07-09T11:32:15.000Z
2022-01-07T01:45:43.000Z
plugins/community/repos/rcm/include/PianoRoll/Auditioner.hpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
24
2018-07-14T21:55:30.000Z
2021-05-04T04:20:34.000Z
namespace rack_plugin_rcm { class Auditioner { public: void start(int step); void retrigger(); void stop(); bool isAuditioning(); int stepToAudition(); bool consumeRetrigger(); bool consumeStopEvent(); private: int step = -1; bool needsRetrigger = false; bool auditioning = false; bool stopPending = false; }; } // namespace rack_plugin_rcm
16
30
0.701087
guillaume-plantevin
510fda49aa3667dd2c2520ce53abf5e216995981
304
cc
C++
tensorflow/core/kernels/cwise_op_square.cc
vsilyaev/tensorflow
f41959ccb2d9d4c722fe8fc3351401d53bcf4900
[ "Apache-2.0" ]
4
2021-06-11T09:43:32.000Z
2021-11-17T11:15:52.000Z
tensorflow/core/kernels/cwise_op_square.cc
cleargraphinc/tensorflow
21fac39c471dede0e4ae62dd60e2b0b85db48415
[ "Apache-2.0" ]
null
null
null
tensorflow/core/kernels/cwise_op_square.cc
cleargraphinc/tensorflow
21fac39c471dede0e4ae62dd60e2b0b85db48415
[ "Apache-2.0" ]
2
2016-05-18T12:48:06.000Z
2019-03-30T03:56:31.000Z
#include "tensorflow/core/kernels/cwise_ops_common.h" namespace tensorflow { REGISTER5(UnaryOp, CPU, "Square", functor::square, float, double, int32, complex64, int64); #if GOOGLE_CUDA REGISTER3(UnaryOp, GPU, "Square", functor::square, float, double, int64); #endif } // namespace tensorflow
30.4
73
0.733553
vsilyaev
511027f32a168ea3f82a4b64a1562b217e3865be
1,842
hpp
C++
include/eagine/memory/buffer_pool.hpp
ford442/oglplu2
abf1e28d9bcd0d2348121e8640d9611a94112a83
[ "BSL-1.0" ]
103
2015-10-15T07:09:22.000Z
2022-03-20T03:39:32.000Z
include/eagine/memory/buffer_pool.hpp
ford442/oglplu2
abf1e28d9bcd0d2348121e8640d9611a94112a83
[ "BSL-1.0" ]
11
2015-11-25T11:39:49.000Z
2021-06-18T08:06:06.000Z
include/eagine/memory/buffer_pool.hpp
ford442/oglplu2
abf1e28d9bcd0d2348121e8640d9611a94112a83
[ "BSL-1.0" ]
10
2016-02-28T00:13:20.000Z
2021-09-06T05:21:38.000Z
/// @file /// /// Copyright Matus Chochlik. /// Distributed under the Boost Software License, Version 1.0. /// See accompanying file LICENSE_1_0.txt or copy at /// http://www.boost.org/LICENSE_1_0.txt /// #ifndef EAGINE_MEMORY_BUFFER_POOL_HPP #define EAGINE_MEMORY_BUFFER_POOL_HPP #include "buffer.hpp" #include <algorithm> #include <vector> namespace eagine::memory { //------------------------------------------------------------------------------ /// @brief Class storing multiple reusable memory buffer instances. /// @ingroup memory /// @see buffer class buffer_pool { public: /// @brief Gets a buffer with the specified required size. /// @param req_size The returned buffer will have at least this number of bytes. /// @see eat auto get(span_size_t req_size = 0) -> memory::buffer { auto pos = std::lower_bound( _pool.begin(), _pool.end(), req_size, [](auto& buf, auto req) { return buf.capacity() < req; }); if(pos != _pool.end()) { memory::buffer result{std::move(*pos)}; _pool.erase(pos); result.resize(req_size); return result; } memory::buffer result{}; result.resize(req_size); return result; } /// @brief Returns the specified buffer back to the pool for further reuse. /// @see get void eat(memory::buffer used) { auto pos = std::lower_bound( _pool.begin(), _pool.end(), used.capacity(), [](auto& buf, auto capacity) { return buf.capacity() < capacity; }); _pool.emplace(pos, std::move(used)); } private: std::vector<memory::buffer> _pool; }; //------------------------------------------------------------------------------ } // namespace eagine::memory #endif // EAGINE_MEMORY_BUFFER_POOL_HPP
30.7
84
0.565689
ford442
511158aad9b954dfa26a6b4b65ef6b6eb0430a4b
445
hpp
C++
include/innovatrics/ansiiso_accuracy_test.hpp
tomas-krupa/ansi_iso_accuracy_test
a87600c1ff8997cd689539432e5badaa1bf8a776
[ "Apache-2.0" ]
null
null
null
include/innovatrics/ansiiso_accuracy_test.hpp
tomas-krupa/ansi_iso_accuracy_test
a87600c1ff8997cd689539432e5badaa1bf8a776
[ "Apache-2.0" ]
null
null
null
include/innovatrics/ansiiso_accuracy_test.hpp
tomas-krupa/ansi_iso_accuracy_test
a87600c1ff8997cd689539432e5badaa1bf8a776
[ "Apache-2.0" ]
null
null
null
/** * @file ansiiso_accuracy_test.hpp * * @copyright Copyright (c) 2020 Innovatrics s.r.o. All rights reserved. * * @maintainer Tomas Krupa <tomas.krupa@innovatrics.com> * @created 10.08.2020 * */ #pragma once #include <string> #include <innovatrics/config.hpp> namespace Innovatrics { class AnsiIsoAccuracyTest { public: static const std::string GetProductString() { return ANSSIISO_ACCURACY_TEST_PRODUCT_STRING; } }; }
15.344828
72
0.719101
tomas-krupa
5111d99b1f96f7fcfc98f238e3bfa2f2fb06cebc
6,072
cxx
C++
IO/ParallelXML/vtkXMLPTableWriter.cxx
michaelchanwahyan/vtk-8.1.2
243225b750443f76dcb119c1bb8e72d41e505bc0
[ "BSD-3-Clause" ]
2
2017-12-08T07:50:51.000Z
2018-07-22T19:12:56.000Z
IO/ParallelXML/vtkXMLPTableWriter.cxx
sakjain92/VTK
1c32f7a180e2750d4678744d7fc47a00f0eb4780
[ "BSD-3-Clause" ]
1
2019-06-03T17:04:59.000Z
2019-06-05T15:13:28.000Z
IO/ParallelXML/vtkXMLPTableWriter.cxx
sakjain92/VTK
1c32f7a180e2750d4678744d7fc47a00f0eb4780
[ "BSD-3-Clause" ]
1
2020-07-20T06:43:49.000Z
2020-07-20T06:43:49.000Z
/*========================================================================= Program: Visualization Toolkit Module: vtkXMLPTableWriter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkXMLPTableWriter.h" #include "vtkCallbackCommand.h" #include "vtkDataSetAttributes.h" #include "vtkErrorCode.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkTable.h" #include "vtkXMLTableWriter.h" #include <vtksys/SystemTools.hxx> #include <cassert> vtkStandardNewMacro(vtkXMLPTableWriter); //---------------------------------------------------------------------------- vtkXMLPTableWriter::vtkXMLPTableWriter() { } //---------------------------------------------------------------------------- vtkXMLPTableWriter::~vtkXMLPTableWriter() { } //---------------------------------------------------------------------------- void vtkXMLPTableWriter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //---------------------------------------------------------------------------- vtkTable* vtkXMLPTableWriter::GetInput() { return vtkTable::SafeDownCast(this->Superclass::GetInput()); } //---------------------------------------------------------------------------- const char* vtkXMLPTableWriter::GetDataSetName() { return "PTable"; } //---------------------------------------------------------------------------- const char* vtkXMLPTableWriter::GetDefaultFileExtension() { return "pvtt"; } //---------------------------------------------------------------------------- vtkXMLWriter* vtkXMLPTableWriter::CreatePieceWriter(int index) { // Create the writer for the piece. vtkXMLTableWriter* pWriter = vtkXMLTableWriter::New(); pWriter->SetInputConnection(this->GetInputConnection(0, 0)); pWriter->SetNumberOfPieces(this->NumberOfPieces); pWriter->SetWritePiece(index); return pWriter; } //---------------------------------------------------------------------------- void vtkXMLPTableWriter::WritePData(vtkIndent indent) { vtkTable* input = this->GetInput(); this->WritePRowData(input->GetRowData(), indent); } //---------------------------------------------------------------------------- int vtkXMLPTableWriter::WritePieceInternal() { int piece = this->GetCurrentPiece(); vtkTable* inputTable = this->GetInput(); if (inputTable && inputTable->GetNumberOfRows() > 0) { if (!this->WritePiece(piece)) { vtkErrorMacro("Could not write the current piece."); this->DeleteFiles(); return 0; } this->PieceWrittenFlags[piece] = static_cast<unsigned char>(0x1); } return 1; } //---------------------------------------------------------------------------- int vtkXMLPTableWriter::WritePiece(int index) { // Create the writer for the piece. Its configuration should match // our own writer. vtkXMLWriter* pWriter = this->CreatePieceWriter(index); pWriter->AddObserver(vtkCommand::ProgressEvent, this->InternalProgressObserver); char* fileName = this->CreatePieceFileName(index, this->PathName); std::string path = vtksys::SystemTools::GetParentDirectory(fileName); if (!path.empty() && !vtksys::SystemTools::PathExists(path)) { vtksys::SystemTools::MakeDirectory(path); } pWriter->SetFileName(fileName); delete[] fileName; // Copy the writer settings. pWriter->SetDebug(this->Debug); pWriter->SetCompressor(this->Compressor); pWriter->SetDataMode(this->DataMode); pWriter->SetByteOrder(this->ByteOrder); pWriter->SetEncodeAppendedData(this->EncodeAppendedData); pWriter->SetHeaderType(this->HeaderType); pWriter->SetBlockSize(this->BlockSize); // Write the piece. int result = pWriter->Write(); this->SetErrorCode(pWriter->GetErrorCode()); // Cleanup. pWriter->RemoveObserver(this->InternalProgressObserver); pWriter->Delete(); return result; } //---------------------------------------------------------------------------- void vtkXMLPTableWriter::WritePRowData(vtkDataSetAttributes* ds, vtkIndent indent) { if (ds->GetNumberOfArrays() == 0) { return; } ostream& os = *this->Stream; char** names = this->CreateStringArray(ds->GetNumberOfArrays()); os << indent << "<PRowData"; this->WriteAttributeIndices(ds, names); if (this->ErrorCode != vtkErrorCode::NoError) { this->DestroyStringArray(ds->GetNumberOfArrays(), names); return; } os << ">\n"; for (int i = 0; i < ds->GetNumberOfArrays(); ++i) { this->WritePArray(ds->GetAbstractArray(i), indent.GetNextIndent(), names[i]); if (this->ErrorCode != vtkErrorCode::NoError) { this->DestroyStringArray(ds->GetNumberOfArrays(), names); return; } } os << indent << "</PRowData>\n"; os.flush(); if (os.fail()) { this->SetErrorCode(vtkErrorCode::GetLastSystemError()); } this->DestroyStringArray(ds->GetNumberOfArrays(), names); } //---------------------------------------------------------------------------- void vtkXMLPTableWriter::SetupPieceFileNameExtension() { this->Superclass::SetupPieceFileNameExtension(); // Create a temporary piece writer and then initialize the extension. vtkXMLWriter* writer = this->CreatePieceWriter(0); const char* ext = writer->GetDefaultFileExtension(); this->PieceFileNameExtension = new char[strlen(ext) + 2]; this->PieceFileNameExtension[0] = '.'; strcpy(this->PieceFileNameExtension + 1, ext); writer->Delete(); } //---------------------------------------------------------------------------- int vtkXMLPTableWriter::FillInputPortInformation(int, vtkInformation* info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkTable"); return 1; }
30.36
82
0.583333
michaelchanwahyan
51125d409e5de20a38e78ff2acfd56a4d9e69bc6
2,924
cpp
C++
src/sequence.cpp
entn-at/JSGFKit_Plus_Plus
dd8a414f6eb4b48be3546aa3377ba49d86634c8a
[ "Unlicense" ]
9
2019-08-09T08:45:35.000Z
2022-03-11T12:25:05.000Z
src/sequence.cpp
entn-at/JSGFKit_Plus_Plus
dd8a414f6eb4b48be3546aa3377ba49d86634c8a
[ "Unlicense" ]
9
2019-01-29T18:49:18.000Z
2020-03-20T23:45:43.000Z
src/sequence.cpp
entn-at/JSGFKit_Plus_Plus
dd8a414f6eb4b48be3546aa3377ba49d86634c8a
[ "Unlicense" ]
2
2019-08-07T06:48:32.000Z
2019-08-09T09:48:39.000Z
#include "sequence.h" #include <iostream> Sequence::Sequence() { //ctor } Sequence::~Sequence() { } Expansion * Sequence::clone() { Sequence * s = new Sequence(); std::vector<std::shared_ptr<Expansion>> c = this->getChildren(); for(std::vector<std::shared_ptr<Expansion>>::iterator childIterator = c.begin(); childIterator != c.end(); childIterator++) { s->addChild(std::shared_ptr<Expansion>((*childIterator)->clone())); } return s; } void Sequence::addChild(std::shared_ptr<Expansion> e) { children.push_back(e); } ///TODO: Implement this, and probably should be done better void Sequence::removeChild(Expansion & e) { if(std::count(children.begin(), children.end(), std::shared_ptr<Expansion>(&e)) != 0) { std::find(children.begin(), children.end(), std::shared_ptr<Expansion>(&e)); } } std::string Sequence::getText() const { std::vector<std::shared_ptr<Expansion>>::const_iterator it; std::string s = ""; for(it = children.begin(); it != children.end(); it++) { s.append((*it)->getText()); s.append(" "); } return s; } unsigned int Sequence::childCount() const { return distance(children.begin(), children.end()); } /** Access children * \return The current value of children */ std::vector<std::shared_ptr<Expansion>> Sequence::getChildren() const { return children; } bool Sequence::hasChild() const { return children.empty(); } ///Returns true if every child can be optional bool Sequence::isOptional() const { std::vector<std::shared_ptr<Expansion>>::const_iterator it; for(it = children.begin(); it != children.end(); it++) { if(!(*it)->isOptional()) { return false; } } return true; } std::shared_ptr<Expansion> Sequence::getChild(const unsigned int index) const { return children[index]; } /** * Static Helper function that checks to see if the provided expansion is a sequence, and if it is, checks to see if the Sequence has only one child. If it has only one child, it sets the provided shared_pointer to point to the child Expansion. * TLDR; Simplifies singular child Sequence's to singular Expansions * \param [in,out] s Expansion that will be simplified if it is a Sequence with 1 child expansion */ void Sequence::simplifySequence(std::shared_ptr<Expansion> s) { if(s->getType() == SEQUENCE) { Sequence * sq = (Sequence*) s.get(); if(sq->childCount() == 1) { // We have a sequence that has only one child. We need to extract the child, destroy the sequence, and set the expansion to the extracted child s = sq->getChild(); // clone() makes a deep copy } else { //Do nothing to s } } } void Sequence::replaceChild(std::shared_ptr<Expansion> newChild, const unsigned long index) { children[index] = newChild; } ExpansionType Sequence::getType() const { return SEQUENCE; }
30.14433
245
0.658345
entn-at
511307c7d5ebd32269ebb54010987c6873d834ae
7,453
cpp
C++
Examples/GrandBlimpBastards/SceneDirector.cpp
radical-bumblebee/bumblebee-engine
c5b7eb4bcd825bc2c5be66d6306912c519a56a2d
[ "MIT" ]
1
2017-08-15T03:56:22.000Z
2017-08-15T03:56:22.000Z
Examples/GrandBlimpBastards/SceneDirector.cpp
radical-bumblebee/bumblebee-engine
c5b7eb4bcd825bc2c5be66d6306912c519a56a2d
[ "MIT" ]
null
null
null
Examples/GrandBlimpBastards/SceneDirector.cpp
radical-bumblebee/bumblebee-engine
c5b7eb4bcd825bc2c5be66d6306912c519a56a2d
[ "MIT" ]
null
null
null
#include "SceneDirector.h" #include "SceneInfo.h" #include <sstream> void SceneDirector::tick() { if (_world->config->game_over < 1.0f && _world->config->game_over > 0.0f) { _world->config->game_over -= 0.3f * _world->dt; if (_world->config->game_over < 0.0f) { _world->config->game_over = 0.0f; _world->scene()->ui->add(std::make_shared<BumblebeeUIElement>("Game Over", "assets/fonts/times.ttf", _world->window_w / 2.0f - 35.0f, _world->window_h / 2.0f - 50.0f, &glm::vec4(1.0f))); _world->scene()->ui->add(std::make_shared<BumblebeeUIElement>("Hit R to retry", "assets/fonts/times.ttf", _world->window_w / 2.0f - 40.0f, _world->window_h / 2.0f - 20.0f, &glm::vec4(1.0f))); } } if (_world->config->game_over > 0.0f) { difficulty += _world->dt; //clean up destroyed blimps by setting them to unused for (unsigned int i = 0; i < _world->scene()->objects->size(); i++) { switch (_world->scene()->objects->at(i)->state) { case BumblebeeObject::INACTIVE: if (_world->scene()->objects->at(i)->model->info->name == _scene_info->blimp_name) { _world->scene()->objects->at(i)->state = BumblebeeObject::UNUSED; high_score++; } break; } } _scene_info->scene_timer -= _world->dt; std::string high_score_string = "Your Score: "; high_score_string += std::to_string(high_score); _world->scene()->ui->at(0)->text = high_score_string; if (_scene_info->rotate) { _world->scene()->camera()->rotate_radians(rotation); rotation += 0.2f; if (rotation > 360.0f) { rotation = 0.0f; } } // Color the skies as time goes on if (_world->scene()->objects->at(_scene_info->skybox_id)->model->info->transparency < 3.0f) { _world->scene()->objects->at(_scene_info->skybox_id)->model->info->transparency += (difficulty / 2000.0f) * _world->dt; } else { if (_world->scene()->objects->at(_scene_info->skybox_id)->model->info->shininess > 0.2f) { _world->scene()->objects->at(_scene_info->skybox_id)->model->info->shininess -= (difficulty / 3000.0f) * _world->dt; } } // Updates player blimp location _scene_info->cannon_origin.x = _world->scene()->objects->at(_world->scene()->player_id)->spatial->position.x; _scene_info->cannon_origin.y = _world->scene()->objects->at(_world->scene()->player_id)->spatial->position.y - 2.0f; _scene_info->cannon_origin.z = _world->scene()->objects->at(_world->scene()->player_id)->spatial->position.z + 3.0f; auto data_ptr = _world->scene()->objects->at(_scene_info->line_id)->model->info->vertices.data(); data_ptr->x = _scene_info->cannon_origin.x; data_ptr->y = _scene_info->cannon_origin.y; data_ptr->z = _scene_info->cannon_origin.z; data_ptr++; int x = 0; int y = 0; SDL_GetMouseState(&x, &y); // Transforms mouse position to 3D space float depth = 0.0f; glReadPixels((GLint)x, (GLint)(_world->window_h - y - 1.0f), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth); depth = glm::clamp(depth, 0.8f, 0.95f); glm::vec4 viewport = glm::vec4(0.0f, 0.0f, _world->window_w, _world->window_h); glm::vec3 window_coordinates = glm::vec3(x, _world->window_h - y - 1.0f, depth); _scene_info->target_direction = glm::unProject(window_coordinates, _world->scene()->camera()->view_matrix, _world->projection_matrix, viewport); // Updates player blimp targetting system data_ptr->x = _scene_info->target_direction.x; data_ptr->y = _scene_info->target_direction.y; data_ptr->z = _scene_info->target_direction.z; } } // Spawns a cannonball and fires it towards mouse position void SceneDirector::fire_cannon() { if (_scene_info->scene_timer < 0.0f) { auto cannonball_id = _world->scene()->objects->add(factory::create_sphere(_scene_info->cannon_origin, _world->proxy->models["assets/models/sphere.ply"], _world->proxy->textures["assets/textures/metal.dds"])); float modifier = 2.0f; auto impulse = btVector3(btScalar(_scene_info->target_direction.x * (modifier * 1.15f)), btScalar((_scene_info->target_direction.y * modifier * 1.15f) + 5.0f), btScalar(_scene_info->target_direction.z * modifier)); auto torque = btVector3(btScalar(20), btScalar(20), btScalar(0)); _world->scene()->objects->at(cannonball_id)->model->info->shininess = 20.0f; _world->scene()->objects->at(cannonball_id)->bullet->body->applyCentralImpulse(impulse); _world->scene()->objects->at(cannonball_id)->bullet->body->applyTorque(torque); _scene_info->scene_timer = RESET_PERIOD; } } void SceneDirector::blimp_collision(BumblebeeObject* obj, glm::vec3 contact_point) { obj->bullet->body->setFlags(obj->bullet->body->getFlags() & ~BT_DISABLE_WORLD_GRAVITY); if (obj->model->info->name == _scene_info->blimp_name) { obj->particle = std::make_shared<ParticleComponent>(); obj->particle->info = _world->proxy->particles["assets/textures/smoke.dds"]; obj->particle->particle_offset = glm::vec4(obj->spatial->position - (contact_point), 1.0f); if (obj->state == BumblebeeObject::ACTIVE) obj->state = BumblebeeObject::INACTIVE; } } void SceneDirector::collision_callback(unsigned int id_a, unsigned int id_b, glm::vec3 contact_point) { auto obj_a = _world->scene()->objects->at(id_a); auto obj_b = _world->scene()->objects->at(id_b); if (_world->scene()->player_id == id_a || _world->scene()->player_id == id_b) { _world->config->game_over -= 0.0000001f; if (high_score > (unsigned int)_scene_info->highest_score) { BumblebeePersist::get()->set_high_score(0, high_score); } } // Drops blimps from the sky upon impact blimp_collision(obj_a, contact_point); blimp_collision(obj_b, contact_point); } void SceneDirector::init_scene() { // Initialize scene _scene_info->scene_id = _world->create_scene(); _world->activate_scene(_scene_info->scene_id); _world->scene()->camera()->eye = glm::vec3(0.0f, 2.0f, 0.0f); _world->scene()->camera()->target = glm::vec3(0.0f, 0.0f, 5.0f); // Create player blimp auto obj = factory::create_blimp(glm::vec3(0.0f), _world->proxy->models["assets/models/capsule.ply"], _world->proxy->textures["assets/textures/marble.dds"]); _world->scene()->player_id = _world->scene()->objects->add(obj); obj->ai->ai_group = AIComponent::PLAYER; _scene_info->line_id = _world->scene()->objects->add(factory::create_soft(_world->proxy->models["line"])); _scene_info->skybox_id = _world->scene()->objects->add(factory::create_skybox(_world->proxy->models["assets/models/cube.ply"], _world->proxy->textures["skybox"])); // Create lights _world->scene()->lights->add(factory::create_light(DIRECTIONAL_LIGHT, glm::vec3(0.0f, 10.0f, 0.0f))); _world->scene()->lights->add(factory::create_light(POINT_LIGHT, glm::vec3(0.0f, 5.0f, 20.0f))); // Create ui _world->scene()->ui->add(std::make_shared<BumblebeeUIElement>("Your Score: ", "assets/fonts/times.ttf", 10.0f, _world->window_h - 30.0f, &glm::vec4(1.0f))); _scene_info->highest_score = BumblebeePersist::get()->get_high_score(0); std::string highest_score_string; if (_scene_info->highest_score > 0) { highest_score_string = std::to_string(_scene_info->highest_score); } else { highest_score_string = "-"; } _world->scene()->ui->add(std::make_shared<BumblebeeUIElement>("High Score: " + highest_score_string, "assets/fonts/times.ttf", 10.0f, _world->window_h - 55.0f, &glm::vec4(1.0f))); } bool SceneDirector::init(BumblebeeWorld::ptr world) { _world = world; rotation = 0.0f; high_score = 0; difficulty = 0.0f; return true; } void SceneDirector::destroy() { _world.reset(); }
43.331395
216
0.695693
radical-bumblebee
5114fdf5e436670aa4f96417aa6beb7218245e57
1,791
hpp
C++
teas/teaport_utils/shell.hpp
benman64/buildhl
137f53d3817928d67b898653b612bbaa669d0112
[ "MIT" ]
null
null
null
teas/teaport_utils/shell.hpp
benman64/buildhl
137f53d3817928d67b898653b612bbaa669d0112
[ "MIT" ]
null
null
null
teas/teaport_utils/shell.hpp
benman64/buildhl
137f53d3817928d67b898653b612bbaa669d0112
[ "MIT" ]
null
null
null
#pragma once // this is a good item to be it's own library. Cross platform process // creation library. #include <string> #include <initializer_list> #include <vector> #include <cstdint> #include "Version.hpp" namespace tea { struct CompletedProcess { int exit_code = 1; std::vector<uint8_t> stdout_data; explicit operator bool() const { return exit_code == 0; } }; typedef std::vector<std::string> CommandLine; std::string find_program(const std::string& name); std::string escape_shell_arg(std::string arg); int system(std::vector<std::string> args); CompletedProcess system_capture(std::vector<std::string> argsIn, bool capture_stderr=false); // these 2 throw CommandError if exit status is not 0 int system_checked(std::vector<std::string> args); CompletedProcess system_capture_checked(std::vector<std::string> argsIn, bool capture_stderr=false); /* because of windows we won't allow this form int system(const std::string& str); */ bool unzip(const std::string& zipfile, const std::string& output_dir); /** runs the command and tries to parse the version. @param command Either command name or path to command. @returns The version of the command parsed. or 0.0.0 if could not parse. @throw CommandError If there is an error executing the command. @throw FileNotFoundError If the command could not be found. */ StrictVersion command_version(std::string command); CommandLine parse_shebang(const std::string& line); CommandLine parse_shebang_file(const std::string& filepath); CommandLine process_shebang_recursively(CommandLine args); CommandLine process_env(CommandLine args); }
34.442308
104
0.691234
benman64
511b09a85aa534798dbe47e96104be64727a5eb9
17,078
cpp
C++
src/tests/accuracy_test_mixed_callback.cpp
ddeka2910/clFFT
7b060b4f27ac22f95c17790476503f622ffea4c6
[ "Apache-2.0" ]
406
2015-02-01T07:32:29.000Z
2022-03-31T15:21:54.000Z
src/tests/accuracy_test_mixed_callback.cpp
ddeka2910/clFFT
7b060b4f27ac22f95c17790476503f622ffea4c6
[ "Apache-2.0" ]
169
2015-01-01T00:06:42.000Z
2021-12-01T19:15:45.000Z
src/tests/accuracy_test_mixed_callback.cpp
ddeka2910/clFFT
7b060b4f27ac22f95c17790476503f622ffea4c6
[ "Apache-2.0" ]
183
2015-01-05T02:21:16.000Z
2022-03-14T08:25:39.000Z
/* ************************************************************************ * Copyright 2015 Advanced Micro Devices, 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. * ************************************************************************/ #include <gtest/gtest.h> #include<math.h> #include "test_constants.h" #include "fftw_transform.h" #include "cl_transform.h" #include "typedefs.h" #include "accuracy_test_common.h" #include <stdexcept> #include <vector> /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ class accuracy_test_callback_single : public ::testing::Test { protected: accuracy_test_callback_single(){} virtual ~accuracy_test_callback_single(){} virtual void SetUp(){} virtual void TearDown(){ } }; class accuracy_test_precallback_double : public ::testing::Test { protected: accuracy_test_precallback_double(){} virtual ~accuracy_test_precallback_double(){} virtual void SetUp(){} virtual void TearDown(){ } }; class mixed_radix_precallback : public ::testing::TestWithParam<size_t> { protected: mixed_radix_precallback(){} virtual ~mixed_radix_precallback(){} virtual void SetUp(){} virtual void TearDown(){} }; class mixed_radix_postcallback : public ::testing::TestWithParam<size_t> { protected: mixed_radix_postcallback(){} virtual ~mixed_radix_postcallback(){} virtual void SetUp(){} virtual void TearDown(){} }; class Supported_Fft_Sizes_Callback { public: std::vector<size_t> sizes; const size_t max_mixed_radices_to_test; Supported_Fft_Sizes_Callback() : max_mixed_radices_to_test( 4096 ) { size_t i=0, j=0, k=0, l=0; size_t sum, sumi, sumj, sumk, suml; sumi = 1; i = 0; while(1) { sumj = 1; j = 0; while(1) { sumk = 1; k = 0; while(1) { suml = 1; l = 0; while(1) { sum = (sumi*sumj*sumk*suml); if( sum > max_mixed_radices_to_test ) break; sizes.push_back(sum); l++; suml *= 2; } if(l == 0) break; k++; sumk *= 3; } if( (k == 0) && (l == 0) ) break; j++; sumj *= 5; } if( (j == 0) && (k == 0) && (l == 0) ) break; i++; sumi *= 7; } } } supported_sizes_callback; INSTANTIATE_TEST_CASE_P( mixed_radices_precallback, mixed_radix_precallback, ::testing::ValuesIn( supported_sizes_callback.sizes ) ); INSTANTIATE_TEST_CASE_P( mixed_radices_postcallback, mixed_radix_postcallback, ::testing::ValuesIn( supported_sizes_callback.sizes ) ); namespace callback_mixed { /********************************************************************************************** **************************************Complex To Complex*************************************** **********************************************************************************************/ #pragma region Complex_To_Complex template< typename T, typename cl_T, typename fftw_T > void mixed_radix_complex_to_complex_precallback( size_t problem_size ) { try { if(verbose) std::cout << "Now testing problem size " << problem_size << std::endl; std::vector<size_t> lengths; lengths.push_back( problem_size ); size_t batch = 1; std::vector<size_t> input_strides; std::vector<size_t> output_strides; size_t input_distance = 0; size_t output_distance = 0; layout::buffer_layout_t in_layout = layout::complex_planar; layout::buffer_layout_t out_layout = layout::complex_planar; placeness::placeness_t placeness = placeness::in_place; direction::direction_t direction = direction::forward; data_pattern pattern = sawtooth; precallback_complex_to_complex<T, cl_T, fftw_T>( pattern, direction, lengths, batch, input_strides, output_strides, input_distance, output_distance, in_layout, out_layout, placeness ); } catch( const std::exception& err ) { handle_exception(err); } } TEST_P( mixed_radix_precallback, single_precision_complex_to_complex_auto_generated ) { size_t problem_size = GetParam(); RecordProperty("problem_size", (int)problem_size); mixed_radix_complex_to_complex_precallback<float, cl_float, fftwf_complex>(problem_size); } TEST_P( mixed_radix_precallback, double_precision_complex_to_complex_auto_generated ) { size_t problem_size = GetParam(); RecordProperty("problem_size", (int)problem_size); mixed_radix_complex_to_complex_precallback<double, cl_double, fftw_complex>(problem_size); } template< typename T, typename cl_T, typename fftw_T > void mixed_radix_complex_to_complex_postcallback( size_t problem_size ) { try { if(verbose) std::cout << "Now testing problem size " << problem_size << std::endl; std::vector<size_t> lengths; lengths.push_back( problem_size ); size_t batch = 1; std::vector<size_t> input_strides; std::vector<size_t> output_strides; size_t input_distance = 0; size_t output_distance = 0; layout::buffer_layout_t in_layout = layout::complex_planar; layout::buffer_layout_t out_layout = layout::complex_planar; placeness::placeness_t placeness = placeness::in_place; direction::direction_t direction = direction::forward; data_pattern pattern = sawtooth; postcallback_complex_to_complex<T, cl_T, fftw_T>( pattern, direction, lengths, batch, input_strides, output_strides, input_distance, output_distance, in_layout, out_layout, placeness ); } catch( const std::exception& err ) { handle_exception(err); } } TEST_P( mixed_radix_postcallback, single_precision_complex_to_complex_auto_generated ) { size_t problem_size = GetParam(); RecordProperty("problem_size", (int)problem_size); mixed_radix_complex_to_complex_postcallback<float, cl_float, fftwf_complex>(problem_size); } TEST_P( mixed_radix_postcallback, double_precision_complex_to_complex_auto_generated ) { size_t problem_size = GetParam(); RecordProperty("problem_size", (int)problem_size); mixed_radix_complex_to_complex_postcallback<double, cl_double, fftw_complex>(problem_size); } // ***************************************************** // ***************************************************** template< class T, class cl_T, class fftw_T > void precall_normal_1D_forward_in_place_complex_to_complex_userdatatype() { std::vector<size_t> lengths; lengths.push_back( normal2 ); size_t batch = 1; std::vector<size_t> input_strides; std::vector<size_t> output_strides; size_t input_distance = 0; size_t output_distance = 0; layout::buffer_layout_t in_layout = layout::complex_interleaved; layout::buffer_layout_t out_layout = layout::complex_interleaved; placeness::placeness_t placeness = placeness::in_place; direction::direction_t direction = direction::forward; data_pattern pattern = impulse; precallback_complex_to_complex<T, cl_T, fftw_T>( pattern, direction, lengths, batch, input_strides, output_strides, input_distance, output_distance, in_layout, out_layout, placeness, 1.0f, true ); } TEST_F(accuracy_test_callback_single, precall_normal_1D_forward_in_place_complex_to_complex_userdatatype) { try { precall_normal_1D_forward_in_place_complex_to_complex_userdatatype< float, cl_float, fftwf_complex >(); } catch( const std::exception& err ) { handle_exception(err); } } //Precallback with LDS template< class T, class cl_T, class fftw_T > void precall_lds_1D_forward_64_in_place_complex_to_complex() { std::vector<size_t> lengths; lengths.push_back( 64 ); size_t batch = 1; std::vector<size_t> input_strides; std::vector<size_t> output_strides; size_t input_distance = 0; size_t output_distance = 0; layout::buffer_layout_t in_layout = layout::complex_interleaved; layout::buffer_layout_t out_layout = layout::complex_interleaved; placeness::placeness_t placeness = placeness::in_place; direction::direction_t direction = direction::forward; data_pattern pattern = impulse; precallback_complex_to_complex_lds<T, cl_T, fftw_T>( pattern, direction, lengths, batch, input_strides, output_strides, input_distance, output_distance, in_layout, out_layout, placeness ); } TEST_F(accuracy_test_callback_single, precall_lds_1D_forward_64_in_place_complex_to_complex) { try { precall_lds_1D_forward_64_in_place_complex_to_complex< float, cl_float, fftwf_complex >(); } catch( const std::exception& err ) { handle_exception(err); } } //Postcallback with LDS template< class T, class cl_T, class fftw_T > void postcall_lds_1D_forward_64_in_place_complex_to_complex() { std::vector<size_t> lengths; lengths.push_back( 64 ); size_t batch = 1; std::vector<size_t> input_strides; std::vector<size_t> output_strides; size_t input_distance = 0; size_t output_distance = 0; layout::buffer_layout_t in_layout = layout::complex_interleaved; layout::buffer_layout_t out_layout = layout::complex_interleaved; placeness::placeness_t placeness = placeness::in_place; direction::direction_t direction = direction::forward; data_pattern pattern = impulse; postcallback_complex_to_complex_lds<T, cl_T, fftw_T>( pattern, direction, lengths, batch, input_strides, output_strides, input_distance, output_distance, in_layout, out_layout, placeness ); } TEST_F(accuracy_test_callback_single, postcall_lds_1D_forward_64_in_place_complex_to_complex) { try { postcall_lds_1D_forward_64_in_place_complex_to_complex< float, cl_float, fftwf_complex >(); } catch( const std::exception& err ) { handle_exception(err); } } template< class T, class cl_T, class fftw_T > void pre_and_post_callback_lds_1D_forward_64_in_place_complex_to_complex() { std::vector<size_t> lengths; lengths.push_back( 64 ); size_t batch = 1; std::vector<size_t> input_strides; std::vector<size_t> output_strides; size_t input_distance = 0; size_t output_distance = 0; layout::buffer_layout_t in_layout = layout::complex_interleaved; layout::buffer_layout_t out_layout = layout::complex_interleaved; placeness::placeness_t placeness = placeness::in_place; direction::direction_t direction = direction::forward; data_pattern pattern = impulse; pre_and_post_callback_complex_to_complex<T, cl_T, fftw_T>( pattern, direction, lengths, batch, input_strides, output_strides, input_distance, output_distance, in_layout, out_layout, placeness, 1.0f, true ); } TEST_F(accuracy_test_callback_single, pre_and_post_callback_lds_1D_forward_64_in_place_complex_to_complex) { try { pre_and_post_callback_lds_1D_forward_64_in_place_complex_to_complex< float, cl_float, fftwf_complex >(); } catch( const std::exception& err ) { handle_exception(err); } } #pragma endregion /********************************************************************************************** **************************************Complex To Real*************************************** **********************************************************************************************/ #pragma region Complex_To_Real template< typename T, typename cl_T, typename fftw_T > void mixed_radix_hermitian_to_real_precallback( size_t problem_size ) { try { if(verbose) std::cout << "Now testing problem size " << problem_size << std::endl; std::vector<size_t> lengths; lengths.push_back( problem_size ); size_t batch = 1; std::vector<size_t> input_strides; std::vector<size_t> output_strides; size_t input_distance = 0; size_t output_distance = 0; layout::buffer_layout_t layout = layout::hermitian_interleaved; placeness::placeness_t placeness = placeness::in_place; data_pattern pattern = sawtooth; precallback_complex_to_real<T, cl_T, fftw_T>( pattern, lengths, batch, input_strides, output_strides, input_distance, output_distance, layout, placeness ); } catch( const std::exception& err ) { handle_exception(err); } } TEST_P( mixed_radix_precallback, single_precision_hermitian_to_real_auto_generated ) { size_t problem_size = GetParam(); RecordProperty("problem_size", (int)problem_size); mixed_radix_hermitian_to_real_precallback<float, cl_float, fftwf_complex>(problem_size); } TEST_P( mixed_radix_precallback, double_precision_hermitian_to_real_auto_generated ) { size_t problem_size = GetParam(); RecordProperty("problem_size", (int)problem_size); mixed_radix_hermitian_to_real_precallback<double, cl_double, fftw_complex>(problem_size); } template< typename T, typename cl_T, typename fftw_T > void mixed_radix_hermitian_to_real_postcallback( size_t problem_size ) { try { if(verbose) std::cout << "Now testing problem size " << problem_size << std::endl; std::vector<size_t> lengths; lengths.push_back( problem_size ); size_t batch = 1; std::vector<size_t> input_strides; std::vector<size_t> output_strides; size_t input_distance = 0; size_t output_distance = 0; layout::buffer_layout_t layout = layout::hermitian_interleaved; placeness::placeness_t placeness = placeness::in_place; data_pattern pattern = sawtooth; postcallback_complex_to_real<T, cl_T, fftw_T>( pattern, lengths, batch, input_strides, output_strides, input_distance, output_distance, layout, placeness ); } catch( const std::exception& err ) { handle_exception(err); } } TEST_P( mixed_radix_postcallback, single_precision_hermitian_to_real_auto_generated ) { size_t problem_size = GetParam(); RecordProperty("problem_size", (int)problem_size); mixed_radix_hermitian_to_real_postcallback<float, cl_float, fftwf_complex>(problem_size); } TEST_P( mixed_radix_postcallback, double_precision_hermitian_to_real_auto_generated ) { size_t problem_size = GetParam(); RecordProperty("problem_size", (int)problem_size); mixed_radix_hermitian_to_real_postcallback<double, cl_double, fftw_complex>(problem_size); } #pragma endregion /********************************************************************************************** **************************************Real To Complex*************************************** **********************************************************************************************/ #pragma region Real_To_Complex template< typename T, typename cl_T, typename fftw_T > void mixed_radix_real_to_hermitian_precallback( size_t problem_size ) { try { if(verbose) std::cout << "Now testing problem size " << problem_size << std::endl; std::vector<size_t> lengths; lengths.push_back( problem_size ); size_t batch = 1; std::vector<size_t> input_strides; std::vector<size_t> output_strides; size_t input_distance = 0; size_t output_distance = 0; layout::buffer_layout_t layout = layout::hermitian_interleaved; placeness::placeness_t placeness = placeness::in_place; data_pattern pattern = sawtooth; precallback_real_to_complex<T, cl_T, fftw_T>( pattern, lengths, batch, input_strides, output_strides, input_distance, output_distance, layout, placeness ); } catch( const std::exception& err ) { handle_exception(err); } } TEST_P( mixed_radix_precallback, single_precision_real_to_hermitian_auto_generated ) { size_t problem_size = GetParam(); RecordProperty("problem_size", (int)problem_size); mixed_radix_real_to_hermitian_precallback<float, cl_float, fftwf_complex>(problem_size); } TEST_P( mixed_radix_precallback, double_precision_real_to_hermitian_auto_generated ) { size_t problem_size = GetParam(); RecordProperty("problem_size", (int)problem_size); mixed_radix_real_to_hermitian_precallback<double, cl_double, fftw_complex>(problem_size); } template< typename T, typename cl_T, typename fftw_T > void mixed_radix_real_to_hermitian_postcallback( size_t problem_size ) { try { if(verbose) std::cout << "Now testing problem size " << problem_size << std::endl; std::vector<size_t> lengths; lengths.push_back( problem_size ); size_t batch = 1; std::vector<size_t> input_strides; std::vector<size_t> output_strides; size_t input_distance = 0; size_t output_distance = 0; layout::buffer_layout_t layout = layout::hermitian_interleaved; placeness::placeness_t placeness = placeness::in_place; data_pattern pattern = sawtooth; postcallback_real_to_complex<T, cl_T, fftw_T>( pattern, lengths, batch, input_strides, output_strides, input_distance, output_distance, layout, placeness ); } catch( const std::exception& err ) { handle_exception(err); } } TEST_P( mixed_radix_postcallback, single_precision_real_to_hermitian_auto_generated ) { size_t problem_size = GetParam(); RecordProperty("problem_size", (int)problem_size); mixed_radix_real_to_hermitian_postcallback<float, cl_float, fftwf_complex>(problem_size); } TEST_P( mixed_radix_postcallback, double_precision_real_to_hermitian_auto_generated ) { size_t problem_size = GetParam(); RecordProperty("problem_size", (int)problem_size); mixed_radix_real_to_hermitian_postcallback<double, cl_double, fftw_complex>(problem_size); } #pragma endregion }
33.750988
207
0.720752
ddeka2910
511b6d995a3b75d481537e76c838e03be7d0f323
743
hh
C++
src/decoder-phrasebased/src/native/decoder/util/pool.hh
ugermann/MMT
715ad16b4467f44c8103e16165261d1391a69fb8
[ "Apache-2.0" ]
3
2020-02-28T21:42:44.000Z
2021-03-12T13:56:16.000Z
tools/mosesdecoder-master/util/pool.hh
Pangeamt/nectm
6b84f048698f2530b9fdbb30695f2e2217c3fbfe
[ "Apache-2.0" ]
2
2020-11-06T14:40:10.000Z
2020-12-29T19:03:11.000Z
tools/mosesdecoder-master/util/pool.hh
Pangeamt/nectm
6b84f048698f2530b9fdbb30695f2e2217c3fbfe
[ "Apache-2.0" ]
2
2019-11-26T05:27:16.000Z
2019-12-17T01:53:43.000Z
// Very simple pool. It can only allocate memory. And all of the memory it // allocates must be freed at the same time. #ifndef UTIL_POOL_H #define UTIL_POOL_H #include <vector> #include <stdint.h> namespace util { class Pool { public: Pool(); ~Pool(); void *Allocate(std::size_t size) { void *ret = current_; current_ += size; if (current_ < current_end_) { return ret; } else { return More(size); } } void FreeAll(); private: void *More(std::size_t size); std::vector<void *> free_list_; uint8_t *current_, *current_end_; // no copying Pool(const Pool &); Pool &operator=(const Pool &); }; } // namespace util #endif // UTIL_POOL_H
16.511111
76
0.602961
ugermann
511f43175f952e74575897bf2d3b2b1fe2a41c12
8,476
cpp
C++
src/GShaderProgram.cpp
mallocc/glw
5fe808e1bcd8559ad1fa0a5b8a58279b5e59b246
[ "Apache-2.0" ]
3
2019-04-08T19:17:29.000Z
2019-09-22T05:35:47.000Z
src/GShaderProgram.cpp
mallocc/glw
5fe808e1bcd8559ad1fa0a5b8a58279b5e59b246
[ "Apache-2.0" ]
null
null
null
src/GShaderProgram.cpp
mallocc/glw
5fe808e1bcd8559ad1fa0a5b8a58279b5e59b246
[ "Apache-2.0" ]
null
null
null
#include "GShaderProgram.h" #include "Logger.h" #include "StringFormat.h" #include "GReturnCode.h" #include <fstream> using glw::engine::glsl::GShaderProgram; using glw::engine::glsl::GShaderProgramId; using glw::engine::glsl::GShaderVariableHandle; using glw::engine::glsl::GShaderVariableHandleId; using glw::engine::glsl::GShaderHandle_T; using util::StringFormat; using glw::GReturnCode::GLW_SUCCESS; using glw::GReturnCode::GLW_FAIL; namespace { const char * TRG = "GSPR"; const char * __CLASSNAME__ = "GShaderProgram"; const char * VAR_NAME_MODEL_MAT = "u_m"; const char * VAR_NAME_VIEW_MAT = "u_v"; const char * VAR_NAME_PROJ_MAT = "u_p"; const char * VAR_NAME_COLOR_VEC = "u_c"; const char * VAR_NAME_TEX0 = "u_tex"; const char * VAR_NAME_TEX1 = "u_tex1"; const char * VAR_NAME_FLAG = "u_flag"; } GShaderProgram::GShaderProgram() { } GShaderProgram::GShaderProgram(const char * vertexFilePath, const char * fragmentFilePath) : m_valid(true) { GReturnCode returnCode = GLW_SUCCESS; LINFO("Creating new program..."); this->m_vertexFilePath = vertexFilePath; this->m_fragmentFilePath = fragmentFilePath; // Create the shaders m_vertexShaderId = glCreateShader(GL_VERTEX_SHADER); m_fragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER); // Read the Vertex Shader code from the file std::string VertexShaderCode; std::ifstream VertexShaderStream(vertexFilePath, std::ios::in); if (VertexShaderStream.is_open()) { std::string Line = ""; while (getline(VertexShaderStream, Line)) VertexShaderCode += "\n" + Line; VertexShaderStream.close(); } else { returnCode = GLW_FAIL; LERROR(StringFormat("Failed to open %0.") .arg(vertexFilePath).str()); } // Read the Fragment Shader code from the file std::string FragmentShaderCode; std::ifstream FragmentShaderStream(fragmentFilePath, std::ios::in); if (FragmentShaderStream.is_open()) { std::string Line = ""; while (getline(FragmentShaderStream, Line)) FragmentShaderCode += "\n" + Line; FragmentShaderStream.close(); } else { returnCode = GLW_FAIL; LERROR(StringFormat("Failed to open %0.") .arg(fragmentFilePath).str()); } GLint Result = GL_FALSE; int InfoLogLength; // Compile Vertex Shader char const * VertexSourcePointer = VertexShaderCode.c_str(); glShaderSource(m_vertexShaderId, 1, &VertexSourcePointer, NULL); glCompileShader(m_vertexShaderId); // Check Vertex Shader glGetShaderiv(m_vertexShaderId, GL_COMPILE_STATUS, &Result); glGetShaderiv(m_vertexShaderId, GL_INFO_LOG_LENGTH, &InfoLogLength); if (InfoLogLength > 0) { returnCode = GLW_FAIL; std::vector<char> VertexShaderErrorMessage(InfoLogLength + 1); glGetShaderInfoLog(m_vertexShaderId, InfoLogLength, NULL, &VertexShaderErrorMessage[0]); LERROR(StringFormat("Vertex shader compilation failed: \n%0") .arg(&VertexShaderErrorMessage[0]).str()); } else LINFO(StringFormat("%0 compiled succesfully.").arg(vertexFilePath).str()); // Compile Fragment Shader char const * FragmentSourcePointer = FragmentShaderCode.c_str(); glShaderSource(m_fragmentShaderId, 1, &FragmentSourcePointer, NULL); glCompileShader(m_fragmentShaderId); // Check Fragment Shader glGetShaderiv(m_fragmentShaderId, GL_COMPILE_STATUS, &Result); glGetShaderiv(m_fragmentShaderId, GL_INFO_LOG_LENGTH, &InfoLogLength); if (InfoLogLength > 0) { returnCode = GLW_FAIL; std::vector<char> FragmentShaderErrorMessage(InfoLogLength + 1); glGetShaderInfoLog(m_fragmentShaderId, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]); LERROR(StringFormat("Fragment shader compilation failed: \n%0") .arg(&FragmentShaderErrorMessage[0]).str()); } else LINFO(StringFormat("%0 compiled succesfully.").arg(fragmentFilePath).str()); // Link the program GLuint ProgramId = glCreateProgram(); glAttachShader(ProgramId, m_vertexShaderId); glAttachShader(ProgramId, m_fragmentShaderId); glLinkProgram(ProgramId); // Check the program glGetProgramiv(ProgramId, GL_LINK_STATUS, &Result); glGetProgramiv(ProgramId, GL_INFO_LOG_LENGTH, &InfoLogLength); if (InfoLogLength > 0) { returnCode = GLW_FAIL; std::vector<char> ProgramErrorMessage(InfoLogLength + 1); glGetProgramInfoLog(ProgramId, InfoLogLength, NULL, &ProgramErrorMessage[0]); LERROR(StringFormat("Linking failed:\n%0\n") .arg(&ProgramErrorMessage[0]).str()); } else LINFO("Program linked succesfully."); glDetachShader(ProgramId, m_vertexShaderId); glDetachShader(ProgramId, m_fragmentShaderId); glDeleteShader(m_vertexShaderId); glDeleteShader(m_fragmentShaderId); this->m_id = ProgramId; if (GLW_FAIL == returnCode) { m_valid = false; LERROR(StringFormat("Loaded GShaderProgram %0 unsuccessfully.").arg(ProgramId).str()); } else { LINFO(StringFormat("Loaded GShaderProgram %0 succesfully.").arg(ProgramId).str()); } } GShaderProgram::~GShaderProgram() { } GReturnCode GShaderProgram::addHandle(GShaderVariableHandle handle) { GReturnCode success = handle.init(m_id); if(GLW_SUCCESS == success) { m_handles.insert({ handle.getHandleId(), handle }); } else { LERROR(StringFormat("Failed to add handle.").str()); } return success; } GReturnCode GShaderProgram::addHandle(GShaderVariableHandle handle, GShaderVariableHandleId& id) { GReturnCode success = handle.init(m_id); if(GLW_SUCCESS == success) { id = handle.getHandleId(); m_handles.insert({ handle.getHandleId(), handle }); } else { LERROR(StringFormat("Failed to add handle.").str()); } return success; } void GShaderProgram::load() { glUseProgram(m_id); for (auto& sm_pair : m_handles) { sm_pair.second.load(); } } GShaderVariableHandle * GShaderProgram::getHandle(GShaderVariableHandleId id) { GShaderVariableHandle * handle = NULL; if (m_handles.find(id) != m_handles.end()) { handle = &m_handles[id]; } return handle; } GShaderProgramId GShaderProgram::getId() { return m_id; } GReturnCode GShaderProgram::setModelMat4Handle(glm::mat4 * mat) { GShaderVariableHandle handle = GShaderVariableHandle(VAR_NAME_MODEL_MAT, mat); GReturnCode success = handle.init(m_id); if(GLW_SUCCESS == success) { m_modelMat = handle.getHandleId(); m_handles.insert({ handle.getHandleId(), handle }); } else { LERROR(StringFormat("Failed to set ModelMat4Handle.").str()); } return success; } GReturnCode GShaderProgram::setViewMat4Handle(glm::mat4 * mat) { GShaderVariableHandle handle = GShaderVariableHandle(VAR_NAME_VIEW_MAT, mat); GReturnCode success = handle.init(m_id); if(GLW_SUCCESS == success) { m_viewMat = handle.getHandleId(); m_handles.insert({ handle.getHandleId(), handle }); } else { LERROR(StringFormat("Failed to set ViewMat4Handle.").str()); } return success; } GReturnCode GShaderProgram::setProjMat4Handle(glm::mat4 * mat) { GShaderVariableHandle handle = GShaderVariableHandle(VAR_NAME_PROJ_MAT, mat); GReturnCode success = handle.init(m_id); if(GLW_SUCCESS == success) { m_projMat = handle.getHandleId(); m_handles.insert({ handle.getHandleId(), handle }); } else { LERROR(StringFormat("Failed to set ProjMat4Handle.").str()); } return success; } GReturnCode GShaderProgram::setTexHandle() { GShaderVariableHandle handle = GShaderVariableHandle(VAR_NAME_TEX0); GReturnCode success = handle.init(m_id); if(GLW_SUCCESS == success) { m_tex = handle.getHandleId(); m_handles.insert({ handle.getHandleId(), handle }); } else { LERROR(StringFormat("Failed to set TexHandle.").str()); } return success; } GShaderVariableHandle * GShaderProgram::getModelMat4Handle() { return getHandle(m_modelMat); } GShaderVariableHandle * GShaderProgram::getViewMat4Handle() { return getHandle(m_viewMat); } GShaderVariableHandle * GShaderProgram::getProjMat4Handle() { return getHandle(m_projMat); } GShaderVariableHandle * GShaderProgram::getTexHandle() { return getHandle(m_tex); } GShaderHandle_T GShaderProgram::getShaderHandle() { return { getTexHandle(), getModelMat4Handle(), getViewMat4Handle(), getProjMat4Handle()}; } void GShaderProgram::getShaderHandle(GShaderHandle_T& shaderHandle) { shaderHandle.textureHandle = getTexHandle(); shaderHandle.modelMatHandle = getModelMat4Handle(); shaderHandle.viewMatHandle = getViewMat4Handle(); shaderHandle.projMatHandle = getProjMat4Handle(); } bool GShaderProgram::isValid() const { return m_valid; }
26.160494
96
0.737494
mallocc
5120e6e419be763070c899b65998040423d525ca
5,502
cpp
C++
OpenGL-SOFT/OpenGL-SOFT/Chunk.cpp
Tom-Todd/OpenGL-Height-Map-Generation
1004b945557071b1e65b441510dc8c144320140b
[ "Unlicense" ]
null
null
null
OpenGL-SOFT/OpenGL-SOFT/Chunk.cpp
Tom-Todd/OpenGL-Height-Map-Generation
1004b945557071b1e65b441510dc8c144320140b
[ "Unlicense" ]
null
null
null
OpenGL-SOFT/OpenGL-SOFT/Chunk.cpp
Tom-Todd/OpenGL-Height-Map-Generation
1004b945557071b1e65b441510dc8c144320140b
[ "Unlicense" ]
null
null
null
#include "Chunk.h" #include "glm/gtc/matrix_transform.hpp" #include <glm/glm.hpp> #include <vector> #include <iostream> #include "FastNoise.h" #include "texture.hpp" const int w = 150; const int h = 150; Chunk::Chunk() { } Chunk::~Chunk() { delete[] heightMap; glDeleteProgram(shadersID); } Chunk::Chunk(GLuint shadersID, float offsetX, float offsetZ, float seed) { GLuint programID = LoadShaders("vertex.glsl", "fragment.glsl"); MatrixID = glGetUniformLocation(programID, "MVP"); setShaders(programID); Texture = loadBMP("grassTextures.bmp"); TextureID = glGetUniformLocation(shadersID, "texture_sampler"); setTexture(Texture, TextureID); glm::mat4 Model = glm::mat4(1.0f); this->offsetx = offsetX; this->offsetz = offsetZ; heightMap = new float*[w+1]; for (int i = 0; i < h+1; ++i) { heightMap[i] = new float[h+1]; } genTerrain(seed); glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW); glGenBuffers(1, &normalbuffer); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW); glGenBuffers(1, &uvbuffer); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(glm::vec2), &uvs[0], GL_STATIC_DRAW); LightI = glGetUniformLocation(programID, "world_lPos"); } float Chunk::checkHeight(glm::vec3 playerPosition) { float pX = ((playerPosition.x) / 2) - offsetx; float pZ = ((playerPosition.z) / 2) - offsetz; float height = 0; int x = std::floor(pX); int z = std::floor(pZ); float fTX = pX - x; float fTZ = pZ - z; float h1 = heightMap[z][x]; float h2 = heightMap[z + 1][x]; float h3 = heightMap[z][x + 1]; float h4 = heightMap[z + 1][x + 1]; if (pX > 0 && pX < w) { if (pZ > 0 && pZ < h-1) { height = (h1 * (1.0 - fTX) + h2 * fTX)*(1.0 - fTZ) + (h3 * (1.0 - fTX) + h4 * fTX)*(fTZ); } } return height; } void Chunk::genTerrain(float seed) { float size = 2; int heightLevel = 0; int u = 0; int v = 0; FastNoise myNoise; myNoise.SetNoiseType(FastNoise::SimplexFractal); myNoise.SetSeed(seed); glm::vec3 verts[w+1][h+1]; glm::vec2 uvR[w+1][h+1]; for (int i = 0; i < w+1; i++) { for (int j = 0; j < h+1; j++) { float h = myNoise.GetNoise(offsetz+i, offsetx+j) * 100; heightMap[i][j] = h; glm::vec3 vertex = glm::vec3((offsetx+j)*size, h, (offsetz+i)*size); heightLevel = 0; if (heightMap[i][j] > 20)heightLevel = 2; uvR[i][j] = glm::vec2(((float)u / 3.0) + (heightLevel*(1.0 / 3.0)), v); verts[i][j] = vertex; u++; if (u > 1)u = 0; } v++; if (v > 1)v = 0; } glm::vec3 *norms = new glm::vec3[(w+1)*(h+1)]; glm::vec3 Tnormals[2][w+1][h+1]; glm::vec3 vert1 = glm::vec3(0, 0, 0); glm::vec3 vert2 = glm::vec3(0, 0, 0); glm::vec3 vert3 = glm::vec3(0, 0, 0); for (int j = 0; j < w+1; j++) { for (int i = 0; i < h+1; i++) { glm::vec3 vTriangle0[] = { verts[i][j], verts[i + 1][j], verts[i + 1][j + 1] }; glm::vec3 vTriangle1[] = { verts[i + 1][j + 1], verts[i][j + 1], verts[i][j] }; glm::vec3 TriangleNorm0 = glm::cross(vTriangle0[0] - vTriangle0[1], vTriangle0[1] - vTriangle0[2]); glm::vec3 TriangleNorm1 = glm::cross(vTriangle1[0] - vTriangle1[1], vTriangle1[1] - vTriangle1[2]); Tnormals[0][i][j] = glm::normalize(TriangleNorm0); Tnormals[1][i][j] = glm::normalize(TriangleNorm1); } } for (int i = 0; i < w+1; i++) { for (int j = 0; j < h+1; j++) { glm::vec3 finalNormal = glm::vec3(0, 0, 0); //Top Left Triangle if (i != 0 && j != 0) { finalNormal += Tnormals[0][i - 1][j - 1]; finalNormal += Tnormals[1][i - 1][j - 1]; } //Top Right Triangles if (i != 0 && j != h) { finalNormal += Tnormals[0][i - 1][j]; } //Bottom Right Triangles if (i != w && j != h) { finalNormal += Tnormals[0][i][j]; finalNormal += Tnormals[1][i][j]; } //Bottom Left Triangles if (i != w && j != 0) { finalNormal += Tnormals[1][i][j - 1]; } norms[j + (i*h)] = finalNormal; } } for (int i = 0; i < (w+1)*(h); i++) { for (int k = 0; k < 2; k++) { int ind = i + (k*h); vertices.push_back(verts[ind / w][ind % w]); uvs.push_back(uvR[ind / w][ind % w]); normals.push_back(norms[ind]); } } myNoise.~FastNoise(); } void Chunk::render(glm::mat4 * Projection, Camera camera) { glUseProgram(shadersID); glUniform3f(LightI, 350, 1000, 200); MVP = *Projection * camera.getView() * Model; glUniformMatrix4fv(MVPID, 1, GL_FALSE, &MVP[0][0]); glUniformMatrix4fv(MODELID, 1, GL_FALSE, &Model[0][0]); glUniformMatrix4fv(VIEWID, 1, GL_FALSE, &camera.getView()[0][0]); if (hasTexture) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Texture); glUniform1i(TextureID, 0); } glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); if (hasTexture) { glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (void*)0); } glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); for (int i = 0; i < w; i++) { glDrawArrays(GL_TRIANGLE_STRIP, i*w * 2, w * 2); } glDisableVertexAttribArray(0); if (hasTexture)glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); }
27.103448
102
0.622501
Tom-Todd
5120fed4befbeb143a9526102c6a639bf65349fd
5,051
cc
C++
src/ptr_matrix.cc
Charles-Chao-Chen/fastSolver2
60eed8825f05c29919f7153497a4b57dec1ef76d
[ "MIT" ]
1
2020-11-28T12:41:51.000Z
2020-11-28T12:41:51.000Z
src/ptr_matrix.cc
Charles-Chao-Chen/fastSolver2
60eed8825f05c29919f7153497a4b57dec1ef76d
[ "MIT" ]
2
2017-09-15T23:39:34.000Z
2017-11-21T21:43:00.000Z
src/ptr_matrix.cc
Charles-Chao-Chen/fastSolver2
60eed8825f05c29919f7153497a4b57dec1ef76d
[ "MIT" ]
3
2016-10-04T04:34:32.000Z
2017-09-15T22:16:11.000Z
#include "ptr_matrix.hpp" #include "utility.hpp" #include <assert.h> #include <stdlib.h> // for srand48_r(), lrand48_r() and drand48_r() PtrMatrix::PtrMatrix() : mRows(-1), mCols(-1), leadD(-1), ptr(NULL), has_memory(false), trans('n') {} PtrMatrix::PtrMatrix(int r, int c) : mRows(r), mCols(c), leadD(r), has_memory(true), trans('n') { ptr = new double[mRows*mCols]; } PtrMatrix::PtrMatrix(int r, int c, int l, double *p, char trans_) : mRows(r), mCols(c), leadD(l), ptr(p), has_memory(false), trans(trans_) { assert(trans_ == 't' || trans_ == 'n'); } PtrMatrix::~PtrMatrix() { if (has_memory) delete[] ptr; ptr = NULL; } // legion uses column major storage, // which is consistant with blas and lapack layout double PtrMatrix::operator()(int r, int c) const { return ptr[r+c*leadD]; } double& PtrMatrix::operator()(int r, int c) { return ptr[r+c*leadD]; } double* PtrMatrix::pointer() const {return ptr;} double* PtrMatrix::pointer(int r, int c) { return &ptr[r+c*leadD]; } void PtrMatrix::set_trans(char trans_) { assert(trans_ == 't' || trans_ == 'n'); this->trans=trans_; } void PtrMatrix::clear(double value) { for (int j=0; j<mCols; j++) for (int i=0; i<mRows; i++) (*this)(i, j) = value; } void PtrMatrix::scale(double alpha) { for (int j=0; j<mCols; j++) for (int i=0; i<mRows; i++) (*this)(i, j) *= alpha; } void PtrMatrix::rand(long seed, int offset) { struct drand48_data buffer; assert( srand48_r( seed, &buffer ) == 0 ); for (int i=0; i<mRows; i++) { for (int j=0; j<mCols; j++) { assert( drand48_r(&buffer, this->pointer(i,j) ) == 0 ); (*this)(i,j) += offset; } } } void PtrMatrix::display(const std::string& name) { std::cout << name << ":" << std::endl; for(int ri = 0; ri < mRows; ri++) { for(int ci = 0; ci < mCols; ci++) { std::cout << (*this)(ri, ci) << "\t"; } std::cout << std::endl; } } int PtrMatrix::LD() const {return leadD;} int PtrMatrix::rows() const { switch (trans) { case 'n': return mRows; break; case 't': return mCols; break; default: assert(false); break; } } int PtrMatrix::cols() const { switch (trans) { case 't': return mRows; break; case 'n': return mCols; break; default: assert(false); break; } } void PtrMatrix::solve(PtrMatrix& B) { int N = this->mRows; int NRHS = B.cols(); int LDA = leadD; int LDB = B.LD(); int IPIV[N]; int INFO; lapack::dgesv_(&N, &NRHS, ptr, &LDA, IPIV, B.pointer(), &LDB, &INFO); assert(INFO==0); /* std::cout << "Permutation:" << std::endl; for (int i=0; i<N; i++) std::cout << IPIV[i] << "\t"; std::cout << std::endl; */ } void PtrMatrix::identity() { assert(mRows==mCols); assert(mRows==leadD); memset(ptr, 0, mRows*mCols*sizeof(double)); // initialize to 0's for (int i=0; i<mRows; i++) (*this)(i, i) = 1.0; } void PtrMatrix::add (double alpha, const PtrMatrix& A, double beta, const PtrMatrix& B, PtrMatrix& C) { assert(A.rows() == B.rows() && A.rows() == C.rows()); assert(A.rows() == B.rows() && A.rows() == C.rows()); assert(A.cols() == B.cols() && A.cols() == C.cols()); for (int j=0; j<C.cols(); j++) for (int i=0; i<C.rows(); i++) { C(i, j) = alpha*A(i,j) + beta*B(i,j); //printf("(%f, %f, %f)\n", A(i, j), B(i, j), C(i, j)); } } void PtrMatrix::gemm (const PtrMatrix& U, const PtrMatrix& V, const PtrMatrix& D, PtrMatrix& res) { assert(U.cols() == V.rows()); char transa = U.trans; char transb = V.trans; int M = U.rows(); int N = V.cols(); int K = U.cols(); int LDA = U.LD(); int LDB = V.LD(); int LDC = res.LD(); double alpha = 1.0, beta = 0.0; //double alpha = 0.0, beta = 0.0; blas::dgemm_(&transa, &transb, &M, &N, &K, &alpha, U.pointer(), &LDA, V.pointer(), &LDB, &beta, res.pointer(), &LDC); // add the diagonal assert(res.rows() == res.cols()); for (int i=0; i<res.rows(); i++) res(i, i) += D(i, 0); } void PtrMatrix::gemm (double alpha, const PtrMatrix& U, const PtrMatrix& V, PtrMatrix& W) { assert(U.cols() == V.rows()); assert(U.rows() == W.rows()); assert(V.cols() == W.cols()); char transa = U.trans; char transb = V.trans; int M = U.rows(); int N = V.cols(); int K = U.cols(); int LDA = U.LD(); int LDB = V.LD(); int LDC = W.LD(); double beta = 1.0; blas::dgemm_(&transa, &transb, &M, &N, &K, &alpha, U.pointer(), &LDA, V.pointer(), &LDB, &beta, W.pointer(), &LDC); } void PtrMatrix::gemm (double alpha, const PtrMatrix& U, const PtrMatrix& V, double beta, PtrMatrix& W) { assert(U.cols() == V.rows()); assert(U.rows() == W.rows()); assert(V.cols() == W.cols()); char transa = U.trans; char transb = V.trans; int M = U.rows(); int N = V.cols(); int K = U.cols(); int LDA = U.LD(); int LDB = V.LD(); int LDC = W.LD(); blas::dgemm_(&transa, &transb, &M, &N, &K, &alpha, U.pointer(), &LDA, V.pointer(), &LDB, &beta, W.pointer(), &LDC); }
24.519417
67
0.559097
Charles-Chao-Chen
512301f537ba191042486d680edab9c600e5d49b
15,210
cpp
C++
2dSpriteGame/Monkey/Level_Editor/Classes/AppFrame.cpp
ScottRMcleod/CPLUSPLUS
94352ddf374b048fab960c1e7d5b2000d08ab399
[ "Unlicense" ]
null
null
null
2dSpriteGame/Monkey/Level_Editor/Classes/AppFrame.cpp
ScottRMcleod/CPLUSPLUS
94352ddf374b048fab960c1e7d5b2000d08ab399
[ "Unlicense" ]
null
null
null
2dSpriteGame/Monkey/Level_Editor/Classes/AppFrame.cpp
ScottRMcleod/CPLUSPLUS
94352ddf374b048fab960c1e7d5b2000d08ab399
[ "Unlicense" ]
null
null
null
#include "AppFrame.h" #define TOOLBAR_SIZE 16 #define GRID_SIZE 32 BEGIN_EVENT_TABLE(AppFrame, wxFrame) EVT_MENU( ID_New_Package, AppFrame::OnNewPackage) EVT_MENU( ID_New_Level, AppFrame::OnNewLevel) EVT_MENU( ID_Save, AppFrame::OnSave) EVT_MENU( ID_Load, AppFrame::OnLoad) EVT_MENU( ID_About, AppFrame::OnAbout) EVT_MENU( ID_Exit, AppFrame::OnExit) EVT_TOOL_RANGE( TLB_PREVIOUS_LEVEL, TLB_TEST_LEVEL, AppFrame::OnToolBarClicked) END_EVENT_TABLE() AppFrame::AppFrame(const wxString &title, const wxPoint &pos, const wxSize &size) : wxFrame((wxFrame*)NULL,-1,title,pos,size, wxDEFAULT_FRAME_STYLE | wxCLIP_CHILDREN) { mouse_grid_x = mouse_grid_y = -1; finalBackBuffer = NULL; backBuffer = NULL; package = NULL; wxMenuBar *menuBar = new wxMenuBar; menuFile = new wxMenu; menuFile->Append(ID_New_Package, "New &Package"); menuFile->Append(ID_New_Level, "&New Level"); menuFile->AppendSeparator(); menuFile->Append(ID_Load, "&Load"); menuFile->Append(ID_Save, "&Save"); menuFile->AppendSeparator(); menuFile->Append(ID_About, "&About"); menuFile->AppendSeparator(); menuFile->Append(ID_Exit, "E&xit"); menuBar->Append(menuFile, "&File"); SetMenuBar(menuBar); gameWindow = new wxWindow(this, -1); gameWindow->Connect(-1,-1, wxEVT_SIZE, (wxObjectEventFunction) &AppFrame::OnSize, NULL, this); gameWindow->Connect(-1,-1, wxEVT_PAINT, (wxObjectEventFunction) &AppFrame::OnPaint, NULL, this); gameWindow->Connect(-1,-1, wxEVT_MOTION, (wxObjectEventFunction) &AppFrame::OnMotion, NULL, this); gameWindow->Connect(-1,-1, wxEVT_LEFT_DOWN, (wxObjectEventFunction) &AppFrame::OnMouseLeft, NULL, this); CreateStatusBar(3); SetStatusText("Create a New Pakage to begin creating levels..."); toolbar = CreateToolBar(wxTB_FLAT); wxImage wallImage = wxBITMAP(WallTile).ConvertToImage().Scale(TOOLBAR_SIZE,TOOLBAR_SIZE); wallImage.SetMask(false); wxBitmap wallBitmap = (wxBitmap)wallImage; wxImage playerImage = wxBITMAP(PlayerTile).ConvertToImage().Scale(TOOLBAR_SIZE,TOOLBAR_SIZE); playerImage.SetMaskColour(255,255,255); wxBitmap playerBitmap = (wxBitmap)playerImage; wxImage enemyImage = wxBITMAP(EnemyTile).ConvertToImage().Scale(TOOLBAR_SIZE,TOOLBAR_SIZE); enemyImage.SetMaskColour(255,255,255); wxBitmap enemyBitmap = (wxBitmap)enemyImage; wxImage potionImage = wxBITMAP(PotionTile).ConvertToImage().Scale(TOOLBAR_SIZE,TOOLBAR_SIZE); potionImage.SetMaskColour(255,255,255); wxBitmap potionBitmap = (wxBitmap)potionImage; wxBitmap eraseBitmap = wxBITMAP(Eraser).ConvertToImage().Scale(TOOLBAR_SIZE,TOOLBAR_SIZE); wxBitmap arrowLeftBitmap = (wxBitmap)wxBITMAP(ArrowLeft); wxBitmap arrowRightBitmap = (wxBitmap)wxBITMAP(ArrowRight); wxBitmap executeBitmap = (wxBitmap)wxBITMAP(Execute); toolbar->AddRadioTool(TLB_WALL, "Place Wall", wallBitmap, wxNullBitmap, "Place walls"); toolbar->AddRadioTool(TLB_PLAYER, "Place Player", playerBitmap, wxNullBitmap, "Place Player"); toolbar->AddRadioTool(TLB_ENEMY, "Place Enemy", enemyBitmap, wxNullBitmap, "Place Enemy"); toolbar->AddRadioTool(TLB_POTION, "Place Potion", potionBitmap, wxNullBitmap, "Place Potion"); toolbar->AddRadioTool(TLB_ERASE, "Erase Items", eraseBitmap, wxNullBitmap, "Erase Items"); toolbar->AddSeparator(); toolbar->AddTool(TLB_PREVIOUS_LEVEL, "Previous Level", arrowLeftBitmap,"Previous Level"); toolbar->AddTool(TLB_NEXT_LEVEL, "Next Level", arrowRightBitmap,"Next Level"); toolbar->AddTool(TLB_TEST_LEVEL, "Test Level", executeBitmap,"Test Level"); toolbar->EnableTool(TLB_PREVIOUS_LEVEL, false); toolbar->EnableTool(TLB_NEXT_LEVEL, false); toolbar->Realize(); wallImage = wxBITMAP(WallTile).ConvertToImage(); wallImage.SetMask(false); wallBitmap = (wxBitmap)wallImage; playerImage = wxBITMAP(PlayerTile).ConvertToImage(); playerImage.SetMaskColour(255,255,255); playerBitmap = (wxBitmap)playerImage; enemyImage = wxBITMAP(EnemyTile).ConvertToImage(); enemyImage.SetMaskColour(255,255,255); enemyBitmap = (wxBitmap)enemyImage; potionImage = wxBITMAP(PotionTile).ConvertToImage(); potionImage.SetMaskColour(255,255,255); potionBitmap = (wxBitmap)potionImage; wxBitmap emptyBitmap = wxBITMAP(EmptyTile); items[0] = emptyBitmap; items[1] = wallBitmap; items[2] = playerBitmap; items[3] = enemyBitmap; items[4] = potionBitmap; } void AppFrame::OnNewPackage(wxCommandEvent &event) { Package *old_package = package; int old_levelIndex = levelIndex; package = new Package; levelIndex = 0; if(!createNewLevel()) { delete package; package = old_package; levelIndex = old_levelIndex; } else { delete old_package; menuFile->Enable(ID_New_Level, true); toolbar->EnableTool(TLB_PREVIOUS_LEVEL, false); toolbar->EnableTool(TLB_NEXT_LEVEL, false); } } void AppFrame::OnNewLevel(wxCommandEvent &event) { createNewLevel(); } void AppFrame::OnSave(wxCommandEvent &event) { wxFileDialog dialog(this, _T("Save Package"), _T(""), _T("Package1.pkg"), _T("Package (*.pkg)|*.pkg"), wxSAVE|wxOVERWRITE_PROMPT); if(dialog.ShowModal() == wxID_OK) { savePackage(dialog.GetPath().c_str()); } } void AppFrame::OnLoad(wxCommandEvent &event) { wxFileDialog dialog(this, _T("Load Package"), _T(""), _T(""), _T("Package (*.pkg)|*.pkg"), 0); if(dialog.ShowModal() == wxID_OK) { FILE *stream; const wxChar *filename = dialog.GetPath().c_str(); stream = fopen(filename, "r+b"); int numLevels; fread(&numLevels, sizeof(int), 1, stream); if(package) delete package; package = new Package; for(int i = 0; i < numLevels; i++) { Level_Info *level = new Level_Info; fread(&level->grid_x, sizeof(int), 1, stream); fread(&level->grid_y, sizeof(int), 1, stream); level->grid = new char *[level->grid_x]; for(int x = 0; x < level->grid_x; x++) { level->grid[x] = new char[level->grid_y]; } for (int x = 0; x < level->grid_x; x++) fread(level->grid[x], sizeof(char), level->grid_y, stream); package->push_back(level); if(i == 0) { levelIndex = 1; setCurrentLevel(level); } } fclose(stream); toolbar->EnableTool(TLB_PREVIOUS_LEVEL, levelIndex != 1); toolbar->EnableTool(TLB_NEXT_LEVEL, levelIndex != package->size()); menuFile->Enable(ID_New_Level, true); updateView(); } } void AppFrame::OnAbout(wxCommandEvent &event) { } void AppFrame::OnExit(wxCommandEvent &event) { } void AppFrame::OnToolBarClicked(wxCommandEvent &event) { bool changed = false; switch(event.GetId()) { case TLB_TEST_LEVEL: { savePackage("temp.pkg"); wxExecute(wxString::Format("EvilMonkeys.exe temp.pkg %d", levelIndex)); break; } case TLB_PREVIOUS_LEVEL: { if(levelIndex > 1) levelIndex--; changed = true; } break; case TLB_NEXT_LEVEL: { if(levelIndex < (int)package->size()) levelIndex++; changed = true; } break; } if(changed) { list<Level_Info *>::iterator it; int i = 0; for(it = package->begin(); it != package->end(); it++, i++) { if(i == levelIndex - 1) { setCurrentLevel((*it)); break; } } toolbar->EnableTool(TLB_PREVIOUS_LEVEL, levelIndex != 1); toolbar->EnableTool(TLB_NEXT_LEVEL, levelIndex != package->size()); } } void AppFrame::OnSize(wxSizeEvent &event) { event.Skip(); if(finalBackBuffer) { delete finalBackBuffer; } wxSize clientArea = gameWindow->GetClientSize(); finalBackBuffer = new wxBitmap(clientArea.GetWidth(), clientArea.GetHeight()); if(backBuffer) { stretchGameView(); flipBackBuffer(); } } void AppFrame::OnPaint(wxPaintEvent &event) { wxPaintDC dc(gameWindow); wxSize clientArea = gameWindow->GetClientSize(); if(!backBuffer) { wxClientDC screenDC(gameWindow); screenDC.Clear(); screenDC.DrawRectangle(0,0, clientArea.GetWidth(), clientArea.GetHeight()); } else { stretchGameView(); flipBackBuffer(); } } void AppFrame::updateView(void) { if(!backBuffer) { return; } wxMemoryDC backBufferDC; backBufferDC.SelectObject(*backBuffer); backBufferDC.Clear(); for(int x = 0; x < currentLevel->grid_x; x++) { for(int y = 0; y < currentLevel->grid_y; y++) { int item = currentLevel->grid[x][y]; if(item >= 0 && item <= 4) { backBufferDC.DrawBitmap(items[0], x *(GRID_SIZE + 1) + 1, y * (GRID_SIZE + 1)); backBufferDC.DrawBitmap(items[item], x *(GRID_SIZE + 1) + 1, y * (GRID_SIZE + 1), true); } } } backBufferDC.SetPen(wxPen(wxColour(128,128,128))); for(int x = 0; x <= currentLevel->grid_x; x++) backBufferDC.DrawLine(wxPoint(x*(GRID_SIZE + 1), 0), wxPoint(x * (GRID_SIZE + 1), currentLevel->grid_y * (GRID_SIZE + 1))); for(int y = 0; y <= currentLevel->grid_y; y++) backBufferDC.DrawLine(wxPoint(0, y*(GRID_SIZE + 1)), wxPoint(currentLevel->grid_x * (GRID_SIZE + 1 ), y * (GRID_SIZE + 1))); backBufferDC.SelectObject(wxNullBitmap); stretchGameView(); flipBackBuffer(); } void AppFrame::stretchGameView(void) { wxSize clientArea = gameWindow->GetClientSize(); wxSize stretchedSize; if(clientArea.GetWidth() * currentLevel->grid_y / currentLevel->grid_x < clientArea.GetHeight()) { stretchedSize.Set(clientArea.GetWidth(), clientArea.GetWidth() * currentLevel->grid_y / currentLevel->grid_x); } else { stretchedSize.Set(clientArea.GetHeight() * currentLevel->grid_x / currentLevel->grid_y, clientArea.GetHeight()); } wxImage stretchedImage = backBuffer->ConvertToImage(); stretchedImage = stretchedImage.Scale(stretchedSize.GetWidth(), stretchedSize.GetHeight()); wxMemoryDC finalDC; wxMemoryDC imageDC; finalDC.SelectObject(*finalBackBuffer); imageDC.SelectObject(stretchedImage); finalDC.SetBackground(*wxBLACK_BRUSH); finalDC.Clear(); wxPoint center; center.x = (clientArea.GetWidth() - stretchedSize.GetWidth()) / 2; center.y = (clientArea.GetHeight() - stretchedSize.GetHeight()) / 2; finalDC.Blit(center, stretchedSize, &imageDC, wxPoint(0,0)); finalDC.SetBrush(*wxTRANSPARENT_BRUSH); finalDC.DrawRectangle(wxPoint(0,0), clientArea); imageDC.SelectObject(wxNullBitmap); finalDC.SelectObject(wxNullBitmap); pos_x = center.x; pos_y = center.y; grid_width = stretchedSize.GetWidth(); grid_height = stretchedSize.GetHeight(); } void AppFrame::flipBackBuffer(void) { wxSize clientArea = gameWindow->GetClientSize(); wxMemoryDC finalDC; wxClientDC screenDC(gameWindow); finalDC.SelectObject(*finalBackBuffer); screenDC.Blit(wxPoint(0,0), clientArea, &finalDC, wxPoint(0,0)); finalDC.SelectObject(wxNullBitmap); } bool AppFrame::createNewLevel(void) { long x = wxGetNumberFromUser(_T("Enter the number of colums for the new level."), _T("Colums"),_T("New Level"), 10, 0, 100, this); if(x < 1) { return false; } long y = wxGetNumberFromUser(_T("Enter the number of rows for the new level."), _T("Rows"),_T("New Level"), 10, 0, 100, this); if(y < 1) { return false; } currentLevel = new Level_Info; package->push_back(currentLevel); levelIndex = (int)package->size(); currentLevel->grid_x = x; currentLevel->grid_y = y; currentLevel->grid = new char *[currentLevel->grid_x]; for(int i = 0; i < currentLevel->grid_x; i++) { currentLevel->grid[i] = new char[currentLevel->grid_y]; } for (int x = 0; x < currentLevel->grid_x; x++) { for(int y = 0; y < currentLevel->grid_y; y++) currentLevel->grid[x][y] = 0; } setCurrentLevel(currentLevel); if(levelIndex >= 2) { toolbar->EnableTool(TLB_PREVIOUS_LEVEL, true); toolbar->EnableTool(TLB_NEXT_LEVEL, false); } return true; } void AppFrame::setCurrentLevel(Level_Info *level) { currentLevel = level; backBuffer = new wxBitmap(currentLevel->grid_x * (GRID_SIZE + 1) + 1, currentLevel->grid_y * (GRID_SIZE + 1) + 1); wxString new_title = "Level Editor for Evil Monkeys - level"; new_title += wxString::Format("%d", levelIndex); SetTitle(new_title); wxString status_info = "Level Size"; status_info += wxString::Format("%dx%d", currentLevel->grid_x, currentLevel->grid_y); SetStatusText(status_info, 1); status_info = "Current Level"; status_info += wxString::Format("%d", levelIndex); SetStatusText(status_info, 2); updateView(); } void AppFrame::OnMotion(wxMouseEvent &event) { wxPoint mp = event.GetPosition(); if (mp.x >= pos_x && mp.x <= pos_x + grid_width && mp.y >= pos_y && mp.y <= pos_y + grid_height) { int tempX = (mp.x - pos_x) / (grid_width / currentLevel->grid_x); int tempY = (mp.y - pos_y) / (grid_height / currentLevel->grid_y); if(tempX != mouse_grid_x || tempY != mouse_grid_y) { mouse_grid_x = tempX; mouse_grid_y = tempY; if(event.LeftIsDown()) OnMouseLeft(event); } } else { if(mouse_grid_x != -1 && mouse_grid_y != -1) { mouse_grid_x = mouse_grid_y = -1; updateView(); } } } void AppFrame::OnMouseLeft(wxMouseEvent &event) { if(mouse_grid_x != -1 && mouse_grid_y != -1) { int selected = 0; if(toolbar->GetToolState(TLB_ERASE)) selected = TILE_EMPTY; else if(toolbar->GetToolState(TLB_WALL)) selected = TILE_WALL; else if(toolbar->GetToolState(TLB_PLAYER)) selected = TILE_PLAYER; else if(toolbar->GetToolState(TLB_ENEMY)) selected = TILE_ENEMY; else if(toolbar->GetToolState(TLB_POTION)) selected = TILE_POTION; else return; if(backBuffer) { wxMemoryDC backBufferDC; backBufferDC.SelectObject(*backBuffer); if(selected == 2) { for(int x = 0; x < currentLevel->grid_x; x++) for(int y = 0; y < currentLevel->grid_y; y++) if(currentLevel->grid[x][y] == 2) { currentLevel->grid[x][y] = 0; backBufferDC.DrawBitmap(items[0], x * (GRID_SIZE + 1) + 1, y * (GRID_SIZE + 1) + 1); } } if(mouse_grid_x < currentLevel->grid_x && mouse_grid_y < currentLevel->grid_y) currentLevel->grid[mouse_grid_x][mouse_grid_y] = selected; backBufferDC.DrawBitmap(items[0], mouse_grid_x * (GRID_SIZE + 1) + 1, mouse_grid_y * (GRID_SIZE + 1) + 1); backBufferDC.DrawBitmap(items[selected], mouse_grid_x * (GRID_SIZE + 1) + 1, mouse_grid_y * (GRID_SIZE + 1) + 1, true); backBufferDC.SelectObject(wxNullBitmap); stretchGameView(); flipBackBuffer(); } } } void AppFrame::savePackage(wxString filename) { FILE *stream; stream = fopen(filename, "w+b"); int numLevels = (int)package->size(); fwrite(&numLevels, sizeof(int), 1, stream); list<Level_Info *>::iterator it; for(it = package->begin(); it != package->end(); it++) { Level_Info *level = (*it); fwrite(&level->grid_x, sizeof(int), 1, stream); fwrite(&level->grid_y, sizeof(int), 1, stream); for(int x = 0; x < level->grid_x; x++) fwrite(level->grid[x], sizeof(char), level->grid_y, stream); } fclose(stream); }
25.955631
132
0.673044
ScottRMcleod
512306955fcd3f467b3442d6632e987902f2d21f
3,439
cpp
C++
desktop-ui/program/drivers.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
desktop-ui/program/drivers.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
245
2021-10-08T09:14:46.000Z
2022-03-31T08:53:13.000Z
desktop-ui/program/drivers.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
auto Program::videoDriverUpdate() -> void { ruby::video.create(settings.video.driver); ruby::video.setContext(presentation.viewport.handle()); videoMonitorUpdate(); videoFormatUpdate(); ruby::video.setExclusive(settings.video.exclusive); ruby::video.setBlocking(settings.video.blocking); ruby::video.setFlush(settings.video.flush); ruby::video.setShader(settings.video.shader); if(!ruby::video.ready()) { MessageDialog().setText({"Failed to initialize ", settings.video.driver, " video driver."}).setAlignment(presentation).error(); settings.video.driver = "None"; driverSettings.videoDriverUpdate(); } presentation.loadShaders(); } auto Program::videoMonitorUpdate() -> void { if(!ruby::video.hasMonitor(settings.video.monitor)) { settings.video.monitor = ruby::video.monitor(); } ruby::video.setMonitor(settings.video.monitor); } auto Program::videoFormatUpdate() -> void { if(!ruby::video.hasFormat(settings.video.format)) { settings.video.format = ruby::video.format(); } ruby::video.setFormat(settings.video.format); } auto Program::videoFullScreenToggle() -> void { if(!ruby::video.hasFullScreen()) return; ruby::video.clear(); if(!ruby::video.fullScreen()) { ruby::video.setFullScreen(true); if(!ruby::input.acquired()) { if(ruby::video.exclusive() || ruby::video.hasMonitors().size() == 1) { ruby::input.acquire(); } } } else { if(ruby::input.acquired()) { ruby::input.release(); } ruby::video.setFullScreen(false); presentation.viewport.setFocused(); } } // auto Program::audioDriverUpdate() -> void { ruby::audio.create(settings.audio.driver); ruby::audio.setContext(presentation.viewport.handle()); audioDeviceUpdate(); audioFrequencyUpdate(); audioLatencyUpdate(); ruby::audio.setExclusive(settings.audio.exclusive); ruby::audio.setBlocking(settings.audio.blocking); ruby::audio.setDynamic(settings.audio.dynamic); if(!ruby::audio.ready()) { MessageDialog().setText({"Failed to initialize ", settings.audio.driver, " audio driver."}).setAlignment(presentation).error(); settings.audio.driver = "None"; driverSettings.audioDriverUpdate(); } } auto Program::audioDeviceUpdate() -> void { if(!ruby::audio.hasDevice(settings.audio.device)) { settings.audio.device = ruby::audio.device(); } ruby::audio.setDevice(settings.audio.device); } auto Program::audioFrequencyUpdate() -> void { if(!ruby::audio.hasFrequency(settings.audio.frequency)) { settings.audio.frequency = ruby::audio.frequency(); } ruby::audio.setFrequency(settings.audio.frequency); for(auto& stream : streams) { stream->setResamplerFrequency(ruby::audio.frequency()); } } auto Program::audioLatencyUpdate() -> void { if(!ruby::audio.hasLatency(settings.audio.latency)) { settings.audio.latency = ruby::audio.latency(); } ruby::audio.setLatency(settings.audio.latency); } // auto Program::inputDriverUpdate() -> void { ruby::input.create(settings.input.driver); ruby::input.setContext(presentation.viewport.handle()); ruby::input.onChange({&InputManager::eventInput, &inputManager}); if(!ruby::input.ready()) { MessageDialog().setText({"Failed to initialize ", settings.input.driver, " input driver."}).setAlignment(presentation).error(); settings.input.driver = "None"; driverSettings.inputDriverUpdate(); } inputManager.poll(true); }
30.433628
131
0.700785
CasualPokePlayer
512398c8e1c780d5fd682f014a3e27bb0eb3e881
2,684
hpp
C++
modules/boost/simd/base/include/boost/simd/operator/functions/shift_right.hpp
feelpp/nt2
4d121e2c7450f24b735d6cff03720f07b4b2146c
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/boost/simd/base/include/boost/simd/operator/functions/shift_right.hpp
feelpp/nt2
4d121e2c7450f24b735d6cff03720f07b4b2146c
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/base/include/boost/simd/operator/functions/shift_right.hpp
feelpp/nt2
4d121e2c7450f24b735d6cff03720f07b4b2146c
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_SIMD_OPERATOR_FUNCTIONS_SHIFT_RIGHT_HPP_INCLUDED #define BOOST_SIMD_OPERATOR_FUNCTIONS_SHIFT_RIGHT_HPP_INCLUDED #include <boost/simd/include/functor.hpp> namespace boost { namespace simd { namespace tag { /*! @brief shift_right generic tag Represents the shift_right function in generic contexts. @par Models: Hierarchy **/ struct shift_right_ : ext::elementwise_<shift_right_> { /// @brief Parent hierarchy typedef ext::elementwise_<shift_right_> parent; template<class... Args> static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args) BOOST_AUTO_DECLTYPE_BODY( dispatching_shift_right_( ext::adl_helper(), static_cast<Args&&>(args)... ) ) }; } namespace ext { template<class Site> BOOST_FORCEINLINE generic_dispatcher<tag::shift_right_, Site> dispatching_shift_right_(adl_helper, boost::dispatch::meta::unknown_<Site>, ...) { return generic_dispatcher<tag::shift_right_, Site>(); } template<class... Args> struct impl_shift_right_; } /*! return right shift of the first operand by the second that must be of integer type and of the same number of elements as the first parameter Infix notation can be used with operator '>>' @par Semantic: For every parameters of types respectively T0, T1: @code T0 r = shift_right(a0,a1); @endcode is similar to: @code T0 r = a0 >> a1; @endcode @par Alias: @c shra, @c shar, @c shrai @see @funcref{shift_left}, @funcref{shr}, @funcref{rshl}, @funcref{rshr}, @funcref{rol}, @funcref{ror} @param a0 @param a1 @return a value of the same type as the second parameter **/ BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::shift_right_ , shift_right , 2 ) BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::shift_right_ , shra , 2 ) BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::shift_right_ , shar , 2 ) BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::shift_right_ , shrai , 2 ) } } #include <boost/simd/operator/specific/common.hpp> #endif
31.952381
145
0.625931
feelpp
5124183a50986bde23dacf6d7b946a55c22a9d59
16,733
cpp
C++
src/main.cpp
MlsDmitry/RakNet-samples
05873aecb5c8dac0c0f822845c764bd5f8dc6a6d
[ "MIT" ]
null
null
null
src/main.cpp
MlsDmitry/RakNet-samples
05873aecb5c8dac0c0f822845c764bd5f8dc6a6d
[ "MIT" ]
null
null
null
src/main.cpp
MlsDmitry/RakNet-samples
05873aecb5c8dac0c0f822845c764bd5f8dc6a6d
[ "MIT" ]
null
null
null
// #include <iostream> // #include <thread> // #include <chrono> // #include <string> // #include <iomanip> // #include <cstring> // #include "RakPeerInterface.h" // #include "RakNetTypes.h" // #include "RakNetDefines.h" // #include "RakNetStatistics.h" // #include "BitStream.h" // #include "StringCompressor.h" // #include "GetTime.h" // #include "MessageIdentifiers.h" // #include "NetworkIDManager.h" // #include "RakSleep.h" // #include "sys/socket.h" // #define SERVER_PORT 30000 // #define CLIENT_PORT 40000 // unsigned char get_packet_identifier(RakNet::Packet *p) // { // if ((unsigned char)p->data[0] == ID_TIMESTAMP) // return (unsigned char)p->data[sizeof(RakNet::MessageID) + sizeof(RakNet::Time)]; // else // return (unsigned char)p->data[0]; // } // int main() // { // bool listening = true; // bool b; // RakNet::RakPeerInterface *server = RakNet::RakPeerInterface::GetInstance(); // RakNet::RakPeerInterface *client = RakNet::RakPeerInterface::GetInstance(); // printf("Server is at: %p\n", server); // RakNet::SocketDescriptor server_socket_descriptor(SERVER_PORT, "127.0.0.1"); // RakNet::SocketDescriptor client_socket_descriptor(CLIENT_PORT, "127.0.0.1"); // // start client // b = client->Startup(2, &client_socket_descriptor, 1); // RakAssert(b == RakNet::RAKNET_STARTED); // // start server // b = server->Startup(100, &server_socket_descriptor, 1); // RakAssert(b == RakNet::RAKNET_STARTED); // server->SetMaximumIncomingConnections(100); // // connect client // b = client->Connect("127.0.0.1", (unsigned short)SERVER_PORT, 0, 0); // RakAssert(b == RakNet::ID_CONNECTION_REQUEST_ACCEPTED); // std::cout << "Client connected!" << std::endl; // // send first packet // RakNet::BitStream bs; // RakNet::RakString server_blob("Hello, it's RakString here from server!"); // RakNet::RakString client_blob("Hello, it's RakString here from client!"); // bs.Write((unsigned char)ID_USER_PACKET_ENUM); // bs.WriteCompressed(server_blob); // client->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_RAKNET_GUID, true); // RakNet::Packet *packet; // bool waiting = true; // while (true) // { // while (waiting) { // packet = server->Receive(); // if (packet) { // waiting = false; // printf("Server packet id is: %d\n", get_packet_identifier(packet)); // if (get_packet_identifier(packet) == ID_USER_PACKET_ENUM) { // RakNet::BitStream data(packet->data, packet->length, true); // RakNet::RakString out; // unsigned char packetTypeID; // data.Read(packetTypeID); // data.ReadCompressed(out); // printf("Server packet data: %s\n", out.C_String()); // } // RakNet::BitStream bs; // bs.Write((unsigned char)ID_USER_PACKET_ENUM); // bs.WriteCompressed(server_blob); // server->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_RAKNET_GUID, true); // } // server->DeallocatePacket(packet); // RakSleep(500); // } // waiting = true; // while (waiting) { // packet = client->Receive(); // if (packet) { // waiting = false; // printf("Client packet id is: %d\n", get_packet_identifier(packet)); // if (get_packet_identifier(packet) == ID_USER_PACKET_ENUM) { // RakNet::BitStream data(packet->data, packet->length, true); // RakNet::RakString out; // unsigned char packetTypeID; // data.Read(packetTypeID); // data.ReadCompressed(out); // printf("Client packet data: %s\n", out.C_String()); // } // RakNet::BitStream bs; // bs.Write((unsigned char)ID_USER_PACKET_ENUM); // bs.WriteCompressed(client_blob); // client->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_RAKNET_GUID, true); // } // client->DeallocatePacket(packet); // RakSleep(500); // } // waiting = true; // } // // RakNet::RakNetGUID guid = server->GetGuidFromSystemAddress(RakNet::UNASSIGNED_SYSTEM_ADDRESS); // // RakNet::SystemAddress address("127.0.0.1", 30002); // // server->Ping(address); // // // // std::cout << "* Your GUID is: " << guid.ToString() << std::endl; // // client->Send() // // char blob_data[50]; // // for (unsigned int i = 0; i < 50; i++) // // { // // blob_data[i] = i + 10; // // std::cout << std::hex << std::setw(2) << (i + 10) << " "; // // } // // std::cout << std::endl; // // std::string blob = std::string(400, 41); // // client->Send((blob.c_str()), 401, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true); // // RakNet::Packet *packet; // // while (true) // // { // // packet = client->Receive(); // // while (packet) // // { // // printf("Data %s", packet->data); // // client->Send((const char *)&blob_data, 50, HIGH_PRIORITY, RELIABLE_SEQUENCED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS,true); // // client->DeallocatePacket(packet); // // packet = client->Receive(); // // } // // packet = server->Receive(); // // while (packet) // // { // // printf("Data %s", packet->data); // // server->Send((const char *)&blob_data, (const int)strlen(blob_data), HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true); // // server->DeallocatePacket(packet); // // packet = server->Receive(); // // } // // packet = client->Receive(); // // while (packet) // // { // // printf("Data %s", packet->data); // // // server->Send((const char *)&blob_data, (const int)strlen(blob_data), HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS,true); // // server->DeallocatePacket(packet); // // packet = server->Receive(); // // } // // } // printf("Last packet was: %p\n", packet); // RakNet::RakPeerInterface::DestroyInstance(server); // RakNet::RakPeerInterface::DestroyInstance(client); // return 0; // } // /* // * Copyright (c) 2014, Oculus VR, Inc. // * All rights reserved. // * // * This source code is licensed under the BSD-style license found in the // * LICENSE file in the root directory of this source tree. An additional grant // * of patent rights can be found in the PATENTS file in the same directory. // * // */ // // #include "RakPeerInterface.h" // // #include "BitStream.h" // // #include <stdlib.h> // For atoi // // #include <cstring> // For strlen // // #include "Rand.h" // // #include "RakNetStatistics.h" // // #include "MessageIdentifiers.h" // // #include <stdio.h> // // #include "Kbhit.h" // // #include "GetTime.h" // // #include "RakAssert.h" // // #include "RakSleep.h" // // #include "Gets.h" // // using namespace RakNet; // // #ifdef _WIN32 // // #include "WindowsIncludes.h" // Sleep64 // // #else // // #include <unistd.h> // usleep // // #include <cstdio> // // #include "Getche.h" // // #endif // // static const int NUM_CLIENTS=100; // // #define SERVER_PORT 1234 // // #define RANDOM_DATA_SIZE_1 50 // // char randomData1[RANDOM_DATA_SIZE_1]; // // #define RANDOM_DATA_SIZE_2 100 // // char randomData2[RANDOM_DATA_SIZE_2]; // // char *remoteIPAddress=0; // // // Connects, sends data over time, disconnects, repeat // // // class Client // // { // // public: // // Client() // // { // // peer = RakNet::RakPeerInterface::GetInstance(); // // } // // ~Client() // // { // // RakNet::RakPeerInterface::DestroyInstance(peer); // // } // // void Startup(void) // // { // // RakNet::SocketDescriptor socketDescriptor; // // socketDescriptor.port=0; // // nextSendTime=0; // // StartupResult b = peer->Startup(1,&socketDescriptor,1); // // RakAssert(b==RAKNET_STARTED); // // isConnected=false; // // } // // void Connect(void) // // { // // bool b; // // b=peer->Connect(remoteIPAddress, (unsigned short) SERVER_PORT, 0, 0, 0)==RakNet::CONNECTION_ATTEMPT_STARTED; // // if (b==false) // // { // // printf("Client connect call failed!\n"); // // } // // } // // void Disconnect(void) // // { // // peer->CloseConnection(peer->GetSystemAddressFromIndex(0),true,0); // // isConnected=false; // // } // // void Update(RakNet::TimeMS curTime) // // { // // Packet *p = peer->Receive(); // // while (p) // // { // // switch (p->data[0]) // // { // // case ID_CONNECTION_REQUEST_ACCEPTED: // // printf("ID_CONNECTION_REQUEST_ACCEPTED\n"); // // isConnected=true; // // break; // // // print out errors // // case ID_CONNECTION_ATTEMPT_FAILED: // // printf("Client Error: ID_CONNECTION_ATTEMPT_FAILED\n"); // // isConnected=false; // // break; // // case ID_ALREADY_CONNECTED: // // printf("Client Error: ID_ALREADY_CONNECTED\n"); // // break; // // case ID_CONNECTION_BANNED: // // printf("Client Error: ID_CONNECTION_BANNED\n"); // // break; // // case ID_INVALID_PASSWORD: // // printf("Client Error: ID_INVALID_PASSWORD\n"); // // break; // // case ID_INCOMPATIBLE_PROTOCOL_VERSION: // // printf("Client Error: ID_INCOMPATIBLE_PROTOCOL_VERSION\n"); // // break; // // case ID_NO_FREE_INCOMING_CONNECTIONS: // // printf("Client Error: ID_NO_FREE_INCOMING_CONNECTIONS\n"); // // isConnected=false; // // break; // // case ID_DISCONNECTION_NOTIFICATION: // // //printf("ID_DISCONNECTION_NOTIFICATION\n"); // // isConnected=false; // // break; // // case ID_CONNECTION_LOST: // // printf("Client Error: ID_CONNECTION_LOST\n"); // // isConnected=false; // // break; // // } // // peer->DeallocatePacket(p); // // p = peer->Receive(); // // } // // if (curTime>nextSendTime && isConnected) // // { // // if (randomMT()%10==0) // // { // // peer->Send((const char*)&randomData2,RANDOM_DATA_SIZE_2,HIGH_PRIORITY,RELIABLE_ORDERED,0,RakNet::UNASSIGNED_SYSTEM_ADDRESS,true); // // } // // else // // { // // peer->Send((const char*)&randomData1,RANDOM_DATA_SIZE_1,HIGH_PRIORITY,RELIABLE_ORDERED,0,RakNet::UNASSIGNED_SYSTEM_ADDRESS,true); // // } // // nextSendTime=curTime+50; // // } // // } // // bool isConnected; // // RakPeerInterface *peer; // // RakNet::TimeMS nextSendTime; // // }; // // // Just listens for ID_USER_PACKET_ENUM and validates its integrity // // class Server // // { // // public: // // Server() // // { // // peer = RakNet::RakPeerInterface::GetInstance(); // // nextSendTime=0; // // } // // ~Server() // // { // // RakNet::RakPeerInterface::DestroyInstance(peer); // // } // // void Start(void) // // { // // RakNet::SocketDescriptor socketDescriptor; // // socketDescriptor.port=(unsigned short) SERVER_PORT; // // bool b = peer->Startup((unsigned short) 600,&socketDescriptor,1)==RakNet::RAKNET_STARTED; // // RakAssert(b); // // peer->SetMaximumIncomingConnections(600); // // } // // unsigned ConnectionCount(void) const // // { // // unsigned short numberOfSystems; // // peer->GetConnectionList(0,&numberOfSystems); // // return numberOfSystems; // // } // // void Update(RakNet::TimeMS curTime) // // { // // Packet *p = peer->Receive(); // // while (p) // // { // // switch (p->data[0]) // // { // // case ID_CONNECTION_LOST: // // case ID_DISCONNECTION_NOTIFICATION: // // case ID_NEW_INCOMING_CONNECTION: // // printf("Connections = %i\n", ConnectionCount()); // // break; // // // case ID_USER_PACKET_ENUM: // // // { // // // peer->Send((const char*) p->data, p->length, HIGH_PRIORITY, RELIABLE_ORDERED, 0, p->guid, true); // // // break; // // // } // // } // // peer->DeallocatePacket(p); // // p = peer->Receive(); // // } // // if (curTime>nextSendTime) // // { // // if (randomMT()%10==0) // // { // // peer->Send((const char*)&randomData2,RANDOM_DATA_SIZE_2,HIGH_PRIORITY,RELIABLE_ORDERED,0,RakNet::UNASSIGNED_SYSTEM_ADDRESS,true); // // } // // else // // { // // peer->Send((const char*)&randomData1,RANDOM_DATA_SIZE_1,HIGH_PRIORITY,RELIABLE_ORDERED,0,RakNet::UNASSIGNED_SYSTEM_ADDRESS,true); // // } // // nextSendTime=curTime+100; // // } // // } // // RakNet::TimeMS nextSendTime; // // RakPeerInterface *peer; // // }; // // int main(void) // // { // // Client clients[NUM_CLIENTS]; // // Server server; // // // int clientIndex; // // int mode; // // printf("Connects many clients to a single server.\n"); // // printf("Difficulty: Intermediate\n\n"); // // printf("Run as (S)erver or (C)lient or (B)oth? "); // // char ch = getche(); // // static char *defaultRemoteIP="127.0.0.1"; // // char remoteIP[128]; // // static char *localIP="127.0.0.1"; // // if (ch=='s' || ch=='S') // // { // // mode=0; // // } // // else if (ch=='c' || ch=='c') // // { // // mode=1; // // remoteIPAddress=remoteIP; // // } // // else // // { // // mode=2; // // remoteIPAddress=localIP; // // } // // printf("\n"); // // if (mode==1 || mode==2) // // { // // printf("Enter remote IP: "); // // Gets(remoteIP, sizeof(remoteIP)); // // if (remoteIP[0]==0) // // { // // strcpy(remoteIP, defaultRemoteIP); // // printf("Using %s\n", defaultRemoteIP); // // } // // } // // unsigned i; // // randomData1[0]=(char) ID_USER_PACKET_ENUM; // // for (i=0; i < RANDOM_DATA_SIZE_1-1; i++) // // randomData1[i+1]=i; // // randomData2[0]=(char) ID_USER_PACKET_ENUM; // // for (i=0; i < RANDOM_DATA_SIZE_2-1; i++) // // randomData2[i+1]=i; // // if (mode==0 || mode==2) // // { // // server.Start(); // // printf("Started server\n"); // // } // // if (mode==1 || mode==2) // // { // // printf("Starting clients...\n"); // // for (i=0; i < NUM_CLIENTS; i++) // // clients[i].Startup(); // // printf("Started clients\n"); // // printf("Connecting clients...\n"); // // for (i=0; i < NUM_CLIENTS; i++) // // clients[i].Connect(); // // printf("Done.\n"); // // } // // RakNet::TimeMS endTime = RakNet::GetTimeMS()+60000*5; // // RakNet::TimeMS time = RakNet::GetTimeMS(); // // while (time < endTime) // // { // // if (mode==0 || mode==2) // // server.Update(time); // // if (mode==1 || mode==2) // // { // // for (i=0; i < NUM_CLIENTS; i++) // // clients[i].Update(time); // // } // // if (kbhit()) // // { // // char ch = getch(); // // if (ch==' ') // // { // // FILE *fp; // // char text[2048]; // // if (mode==0 || mode==2) // // { // // printf("Logging server statistics to ServerStats.txt\n"); // // fp=fopen("ServerStats.txt","wt"); // // for (i=0; i < NUM_CLIENTS; i++) // // { // // RakNetStatistics *rssSender; // // rssSender=server.peer->GetStatistics(server.peer->GetSystemAddressFromIndex(i)); // // StatisticsToString(rssSender, text, 3); // // fprintf(fp,"==== System %i ====\n", i+1); // // fprintf(fp,"%s\n\n", text); // // } // // fclose(fp); // // } // // if (mode==1 || mode==2) // // { // // printf("Logging client statistics to ClientStats.txt\n"); // // fp=fopen("ClientStats.txt","wt"); // // for (i=0; i < NUM_CLIENTS; i++) // // { // // RakNetStatistics *rssSender; // // rssSender=clients[i].peer->GetStatistics(clients[i].peer->GetSystemAddressFromIndex(0)); // // StatisticsToString(rssSender, text, 3); // // fprintf(fp,"==== Client %i ====\n", i+1); // // fprintf(fp,"%s\n\n", text); // // } // // fclose(fp); // // } // // } // // if (ch=='q' || ch==0) // // break; // // } // // time = RakNet::GetTimeMS(); // // RakSleep(30); // // } // // if (mode==0 || mode==2) // // server.peer->Shutdown(0); // // if (mode==1 || mode==2) // // for (i=0; i < NUM_CLIENTS; i++) // // clients[i].peer->Shutdown(0); // // printf("Test completed"); // // return 0; // // }
32.874263
166
0.541804
MlsDmitry
51286344076bc3d1c2da743388d15ea6578679af
142
cpp
C++
bmi-calculator-flutter/build/app/intermediates/javac/debug/classes/C++ & C/2.cpp
Bijitakc/Hacktoberfest2021-2
167e7c81dc9c5cc83fd604ea1d4bce52aa882605
[ "MIT" ]
20
2021-10-06T13:51:46.000Z
2021-11-11T16:12:17.000Z
bmi-calculator-flutter/build/app/intermediates/javac/debug/classes/C++ & C/2.cpp
Bijitakc/Hacktoberfest2021-2
167e7c81dc9c5cc83fd604ea1d4bce52aa882605
[ "MIT" ]
42
2021-10-08T09:49:17.000Z
2021-10-21T23:18:39.000Z
bmi-calculator-flutter/build/app/intermediates/javac/debug/classes/C++ & C/2.cpp
Bijitakc/Hacktoberfest2021-2
167e7c81dc9c5cc83fd604ea1d4bce52aa882605
[ "MIT" ]
97
2021-10-06T13:04:34.000Z
2021-11-11T16:12:21.000Z
#include<iostream> using namespace std; int main(){ int a,b; int result; a=5; b=6; a=a+1; result=a-b; cout<<"result : "<<result; return 0; }
10.142857
26
0.640845
Bijitakc
512a7d29217fb2d99e3193711c74406cc93e23ad
18,686
cpp
C++
NeoMathEngine/src/CPU/x86/CpuX86MathEngineBlas.cpp
sergesk/neoml
cca05584ef3d892cb00d23a105bac6674b3d50ef
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
NeoMathEngine/src/CPU/x86/CpuX86MathEngineBlas.cpp
sergesk/neoml
cca05584ef3d892cb00d23a105bac6674b3d50ef
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
NeoMathEngine/src/CPU/x86/CpuX86MathEngineBlas.cpp
sergesk/neoml
cca05584ef3d892cb00d23a105bac6674b3d50ef
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* Copyright © 2017-2020 ABBYY Production LLC 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 <common.h> #pragma hdrstop #include <NeoMathEngine/NeoMathEngineDefs.h> #ifdef NEOML_USE_SSE #include <CpuMathEngine.h> #include <CpuExecutionScope.h> #include <CpuX86.h> #include <float.h> #include <MemoryHandleInternal.h> #include <MathEngineCommon.h> #include <CpuX86MathEngineVectorMathPrivate.h> namespace NeoML { void CCpuMathEngine::MatrixRowsToVectorSquaredL2Distance( const CConstFloatHandle& matrixHandle, const int matrixHeight, const int matrixWidth, const CConstFloatHandle& vectorHandle, const CFloatHandle& resultHandle ) { ASSERT_EXPR( matrixHandle.GetMathEngine() == this ); ASSERT_EXPR( vectorHandle.GetMathEngine() == this ); ASSERT_EXPR( resultHandle.GetMathEngine() == this ); CCpuExecutionScope scope; const float* matrix = GetRaw( matrixHandle ); float* result = GetRaw( resultHandle ); for( int i = 0; i < matrixHeight; i++ ) { const float* rawVector = GetRaw( vectorHandle ); *result++ = euclidianSSE( matrix, rawVector, matrixWidth ); matrix += matrixWidth; } } static void findMaxValueWorker(const __m128& value, const __m128i& index, __m128& maxValue, __m128i& maxIndex) { __m128i cmp = _mm_castps_si128(_mm_cmpgt_ps(value, maxValue)); maxIndex = _mm_or_si128(_mm_andnot_si128(cmp, maxIndex), _mm_and_si128(cmp, index)); maxValue = _mm_max_ps(value, maxValue); } void CCpuMathEngine::FindMaxValueInRows(const CConstFloatHandle& matrixHandle, int matrixHeight, int matrixWidth, const CFloatHandle& resultHandle, const CIntHandle& columnIndices, int vectorSize) { ASSERT_EXPR( matrixHandle.GetMathEngine() == this ); ASSERT_EXPR( resultHandle.GetMathEngine() == this ); ASSERT_EXPR( columnIndices.GetMathEngine() == this ); ASSERT_EXPR( vectorSize >= matrixHeight ); CCpuExecutionScope scope; const float* matrix = GetRaw(matrixHandle); float* result = GetRaw(resultHandle); int* indices = GetRaw(columnIndices); int sseSize; int nonSseSize; checkSse(matrixWidth, sseSize, nonSseSize); __m128i iStep = _mm_set1_epi32(4); __m128 maxValueAcc = _mm_setzero_ps(); __m128i maxIndexAcc = _mm_setzero_si128(); for(int j = 0; j < matrixHeight; ++j) { // Find the maximum in the row __m128i index = _mm_set_epi32(3, 2, 1, 0); __m128 maxValue = _mm_set1_ps(-FLT_MAX); __m128i maxIndex = index; for(int i = 0; i < sseSize; ++i) { __m128 value = LoadSse4(matrix); findMaxValueWorker(value, index, maxValue, maxIndex); index = _mm_add_epi32(index, iStep); matrix += 4; } if(nonSseSize > 0) { __m128 value = LoadSse(matrix, nonSseSize, -FLT_MAX); findMaxValueWorker(value, index, maxValue, maxIndex); matrix += nonSseSize; } // Find the maximum inside maxValue __m128 value = _mm_shuffle_ps(maxValue, maxValue, _MM_SHUFFLE(1, 0, 3, 2)); index = _mm_shuffle_epi32(maxIndex, _MM_SHUFFLE(1, 0, 3, 2)); findMaxValueWorker(value, index, maxValue, maxIndex); value = _mm_shuffle_ps(maxValue, maxValue, _MM_SHUFFLE(2, 3, 0, 1)); index = _mm_shuffle_epi32(maxIndex, _MM_SHUFFLE(2, 3, 0, 1)); findMaxValueWorker(value, index, maxValue, maxIndex); // Maximum is stored in maxValue fields, put it into maxValueAcc int phase = j % 4; __m128 mask = GetPhaseMask4(phase); maxValueAcc = _mm_or_ps(_mm_andnot_ps(mask, maxValueAcc), _mm_and_ps(mask, maxValue)); maxIndexAcc = _mm_or_si128(_mm_andnot_si128(_mm_castps_si128(mask), maxIndexAcc), _mm_and_si128(_mm_castps_si128(mask), maxIndex)); // Save the result if necessary if(phase == 3) { StoreSse4(maxValueAcc, result); StoreIntSse4(maxIndexAcc, indices); result += 4; indices += 4; } else if(j == matrixHeight - 1) { StoreSse(maxValueAcc, result, phase + 1); StoreIntSse(maxIndexAcc, indices, phase + 1); } } } void CCpuMathEngine::FindMaxValueInRows(const CConstFloatHandle& matrixHandle, int matrixHeight, int matrixWidth, const CFloatHandle& resultHandle, int vectorSize) { ASSERT_EXPR( matrixHandle.GetMathEngine() == this ); ASSERT_EXPR( resultHandle.GetMathEngine() == this ); ASSERT_EXPR( vectorSize >= matrixHeight ); CCpuExecutionScope scope; const float* matrix = GetRaw(matrixHandle); float* result = GetRaw(resultHandle); int sseSize; int nonSseSize; checkSse(matrixWidth, sseSize, nonSseSize); __m128 maxValueAcc = _mm_setzero_ps(); for(int j = 0; j < matrixHeight; ++j) { // Find the maximum in the row __m128 maxValue = _mm_set1_ps(-FLT_MAX); for(int i = 0; i < sseSize; ++i) { __m128 value = LoadSse4(matrix); maxValue = _mm_max_ps(value, maxValue); matrix += 4; } if(nonSseSize > 0) { __m128 value = LoadSse(matrix, nonSseSize, -FLT_MAX); maxValue = _mm_max_ps(value, maxValue); matrix += nonSseSize; } // Find the maximum inside maxValue __m128 value = _mm_shuffle_ps(maxValue, maxValue, _MM_SHUFFLE(1, 0, 3, 2)); maxValue = _mm_max_ps(value, maxValue); value = _mm_shuffle_ps(maxValue, maxValue, _MM_SHUFFLE(2, 3, 0, 1)); maxValue = _mm_max_ps(value, maxValue); // Maximum is stored in maxValue fields, put it into maxValueAcc int phase = j % 4; __m128 mask = GetPhaseMask4(phase); maxValueAcc = _mm_or_ps(_mm_andnot_ps(mask, maxValueAcc), _mm_and_ps(mask, maxValue)); // Save the result if necessary if(phase == 3) { StoreSse4(maxValueAcc, result); result += 4; } else if(j == matrixHeight - 1) { StoreSse(maxValueAcc, result, phase + 1); } } } void CCpuMathEngine::FindMaxValueInColumns( int batchSize, const CConstFloatHandle& matrixHandle, int matrixHeight, int matrixWidth, const CFloatHandle& resultHandle, const CIntHandle& rowIndices, int vectorSize ) { ASSERT_EXPR( matrixHandle.GetMathEngine() == this ); ASSERT_EXPR( resultHandle.GetMathEngine() == this ); ASSERT_EXPR( rowIndices.GetMathEngine() == this ); CCpuExecutionScope scope; if( matrixWidth == 1 ) { // For x86 FindMaxValueInRows would be more optimal, // because it uses SSE differently FindMaxValueInRows( matrixHandle, batchSize, matrixHeight, resultHandle, rowIndices, vectorSize ); return; } ASSERT_EXPR( vectorSize >= batchSize * matrixWidth ); int sseSize; int nonSseSize; checkSse( matrixWidth, sseSize, nonSseSize ); // The pointer moves over the first row of the matrix const float* firstRow = GetRaw( matrixHandle ); float* result = GetRaw( resultHandle ); int* indices = GetRaw( rowIndices ); for( int b = 0; b < batchSize; ++b ) { // Process 4 columns at once for( int i = 0; i < sseSize; ++i ) { const float* data = firstRow; __m128 maxValue = LoadSse4( data ); __m128i maxIndices = _mm_set1_epi32( 0 ); data += matrixWidth; for( int h = 1; h < matrixHeight; ++h ) { __m128 value = LoadSse4( data ); __m128i currIndices = _mm_set1_epi32( h ); findMaxValueWorker( value, currIndices, maxValue, maxIndices ); data += matrixWidth; } StoreSse4( maxValue, result ); StoreIntSse4( maxIndices, indices ); result += 4; indices += 4; firstRow += 4; } if( nonSseSize > 0 ) { // Process the rest of the columns in the same way const float* data = firstRow; __m128 maxValue = LoadSse( data, nonSseSize ); __m128i maxIndices = _mm_set1_epi32( 0 ); data += matrixWidth; for( int h = 1; h < matrixHeight; ++h ) { __m128 value = LoadSse( data, nonSseSize ); __m128i currIndices = _mm_set1_epi32( h ); findMaxValueWorker( value, currIndices, maxValue, maxIndices ); data += matrixWidth; } StoreSse( maxValue, result, nonSseSize ); StoreIntSse( maxIndices, indices, nonSseSize ); result += nonSseSize; indices += nonSseSize; firstRow += nonSseSize; } // firstRow points to the start of the second row of the current matrix // Move it to the start of the first row of the next matrix in the batch firstRow += matrixWidth * ( matrixHeight - 1 ); } } static inline void findMinValueWorker(const __m128& value, const __m128i& index, __m128& minValue, __m128i& minIndex) { __m128i cmp = _mm_castps_si128(_mm_cmplt_ps(value, minValue)); minIndex = _mm_or_si128(_mm_andnot_si128(cmp, minIndex), _mm_and_si128(cmp, index)); minValue = _mm_min_ps(value, minValue); } void CCpuMathEngine::FindMinValueInColumns( const CConstFloatHandle& matrixHandle, int matrixHeight, int matrixWidth, const CFloatHandle& resultHandle, const CIntHandle& rowIndices ) { ASSERT_EXPR( matrixHandle.GetMathEngine() == this ); ASSERT_EXPR( resultHandle.GetMathEngine() == this ); ASSERT_EXPR( rowIndices.GetMathEngine() == this ); CCpuExecutionScope scope; // Split matrix horizontally into blocks of smaller size and pray that it will fit into cache const int cacheSize = 0x60000; int blockHeight = min( matrixHeight, max( 1, static_cast<int>( cacheSize / ( matrixWidth * sizeof( float ) ) ) ) ); const int minBlockHeight = 2; if( blockHeight < minBlockHeight ) { // There will be too much excessive read/write operations // That's whuy processing whoel matrix at once blockHeight = matrixHeight; } const int blockCount = ( matrixHeight + blockHeight - 1 ) / blockHeight; const int lastBlockHeight = matrixHeight % blockHeight == 0 ? blockHeight : matrixHeight % blockHeight; int sseSize; int nonSseSize; checkSse( matrixWidth, sseSize, nonSseSize ); // The pointer moves over the first row of the matrix const float* firstRow = GetRaw( matrixHandle ); float* firstResult = GetRaw( resultHandle ); int* firstIndices = GetRaw( rowIndices ); for( int block = 0; block < blockCount; ++block ) { const int currBlockHeight = block == blockCount - 1 ? lastBlockHeight : blockHeight; const int firstRowIndex = block == 0 ? 1 : 0; float* result = firstResult; int* indices = firstIndices; // Process 16 columns at once int currSse = 0; for( ; currSse + 4 <= sseSize; currSse += 4 ) { const float* data = firstRow; __m128 minValue0, minValue1, minValue2, minValue3; __m128i minIndices0, minIndices1, minIndices2, minIndices3; if( block == 0 ) { minValue0 = LoadSse4( data ); minValue1 = LoadSse4( data + 4 ); minValue2 = LoadSse4( data + 8 ); minValue3 = LoadSse4( data + 12 ); minIndices0 = _mm_set1_epi32( 0 ); minIndices1 = _mm_set1_epi32( 0 ); minIndices2 = _mm_set1_epi32( 0 ); minIndices3 = _mm_set1_epi32( 0 ); data += matrixWidth; } else { minValue0 = LoadSse4( result ); minValue1 = LoadSse4( result + 4 ); minValue2 = LoadSse4( result + 8 ); minValue3 = LoadSse4( result + 12 ); minIndices0 = LoadIntSse4( indices ); minIndices1 = LoadIntSse4( indices + 4 ); minIndices2 = LoadIntSse4( indices + 8 ); minIndices3 = LoadIntSse4( indices + 12 ); } for( int h = firstRowIndex; h < currBlockHeight; ++h ) { __m128 value0 = LoadSse4( data ); __m128 value1 = LoadSse4( data + 4 ); __m128 value2 = LoadSse4( data + 8 ); __m128 value3 = LoadSse4( data + 12 ); __m128i currIndices = _mm_set1_epi32( h + block * blockHeight ); findMinValueWorker( value0, currIndices, minValue0, minIndices0 ); findMinValueWorker( value1, currIndices, minValue1, minIndices1 ); findMinValueWorker( value2, currIndices, minValue2, minIndices2 ); findMinValueWorker( value3, currIndices, minValue3, minIndices3 ); data += matrixWidth; } StoreSse4( minValue0, result ); StoreSse4( minValue1, result + 4 ); StoreSse4( minValue2, result + 8 ); StoreSse4( minValue3, result + 12 ); StoreIntSse4( minIndices0, indices ); StoreIntSse4( minIndices1, indices + 4 ); StoreIntSse4( minIndices2, indices + 8 ); StoreIntSse4( minIndices3, indices + 12 ); result += 16; indices += 16; firstRow += 16; } // Process 4 columns at once for( ; currSse < sseSize; ++currSse ) { const float* data = firstRow; __m128 minValue; __m128i minIndices; if( block == 0 ) { minValue = LoadSse4( data ); minIndices = _mm_set1_epi32( 0 ); data += matrixWidth; } else { minValue = LoadSse4( result ); minIndices = LoadIntSse4( indices ); } for( int h = firstRowIndex; h < currBlockHeight; ++h ) { __m128 value = LoadSse4( data ); __m128i currIndices = _mm_set1_epi32( h + block * blockHeight ); findMinValueWorker( value, currIndices, minValue, minIndices ); data += matrixWidth; } StoreSse4( minValue, result ); StoreIntSse4( minIndices, indices ); result += 4; indices += 4; firstRow += 4; } if( nonSseSize > 0 ) { // Process the rest of the columns in the same way const float* data = firstRow; __m128 minValue; __m128i minIndices; if( block == 0 ) { minValue = LoadSse( data, nonSseSize ); minIndices = _mm_set1_epi32( 0 ); data += matrixWidth; } else { minValue = LoadSse( result, nonSseSize ); minIndices = LoadIntSse( indices, nonSseSize ); } for( int h = firstRowIndex; h < currBlockHeight; ++h ) { __m128 value = LoadSse( data, nonSseSize ); __m128i currIndices = _mm_set1_epi32( h + block * blockHeight ); findMinValueWorker( value, currIndices, minValue, minIndices ); data += matrixWidth; } StoreSse( minValue, result, nonSseSize ); StoreIntSse( minIndices, indices, nonSseSize ); firstRow += nonSseSize; } firstRow += matrixWidth * ( currBlockHeight - 1 ); } } void CCpuMathEngine::MultiplyDiagMatrixByMatrixAndAdd(int batchSize, const CConstFloatHandle& firstHandle, int firstSize, const CConstFloatHandle& secondHandle, int secondWidth, const CFloatHandle& resultHandle) { ASSERT_EXPR( firstHandle.GetMathEngine() == this ); ASSERT_EXPR( secondHandle.GetMathEngine() == this ); ASSERT_EXPR( resultHandle.GetMathEngine() == this ); CCpuExecutionScope scope; const float* first = GetRaw(firstHandle); const float* second = GetRaw(secondHandle); float* resultStart = GetRaw(resultHandle); int sseSize; int nonSseSize; checkSse(secondWidth, sseSize, nonSseSize); for(int b = 0; b < batchSize; ++b) { float* result = resultStart; __m128 firstValBuf = _mm_setzero_ps(); for(int j = 0; j < firstSize; ++j) { int phase = j % 4; if(phase == 0) { int loadSize = firstSize - j; if(loadSize >= 4) { loadSize = 4; firstValBuf = LoadSse4(first); } else { firstValBuf = LoadSse(first, loadSize); } first += loadSize; } __m128 firstVal = GetPhaseValue4(firstValBuf, phase); for(int i = 0; i < sseSize; ++i) { __m128 secondVal = LoadSse4(second); __m128 val = _mm_mul_ps(firstVal, secondVal); __m128 resultVal = LoadSse4(result); resultVal = _mm_add_ps(resultVal, val); StoreSse4(resultVal, result); second += 4; result += 4; } if(nonSseSize > 0) { __m128 secondVal = LoadSse(second, nonSseSize); __m128 val = _mm_mul_ps(firstVal, secondVal); __m128 resultVal = LoadSse(result, nonSseSize); resultVal = _mm_add_ps(resultVal, val); StoreSse(resultVal, result, nonSseSize); second += nonSseSize; result += nonSseSize; } } } } void CCpuMathEngine::MultiplyLookupMatrixByLookupVector(int batchSize, const CLookupMatrix& matrix, const CLookupVector& vector, const CFloatHandle& resultHandle, int resultSize) { ASSERT_EXPR( resultHandle.GetMathEngine() == this ); ASSERT_EXPR(matrix.Width() == vector.VectorSize()); ASSERT_EXPR(resultSize >= batchSize * matrix.Height()); CCpuExecutionScope scope; int sseSize; int nonSseSize; checkSse(matrix.Width(), sseSize, nonSseSize); int height4 = matrix.Height() / 4; int height = matrix.Height() % 4; const float* matrixTable = GetRaw(matrix.Table); const int* matrixRows = GetRaw(matrix.Rows); const float* vectorTable = GetRaw(vector.Table); const int* vectors = GetRaw(vector.Vector); float* result = GetRaw(resultHandle); for(int b = 0; b < batchSize; ++b) { const float* vectorData = vectorTable + (*vectors++) * vector.VectorSize(); for(int j = 0; j < height4; ++j) { // Multiply 4 matrix rows const float* rows[4]; rows[0] = matrixTable + (*matrixRows++) * matrix.Width(); rows[1] = matrixTable + (*matrixRows++) * matrix.Width(); rows[2] = matrixTable + (*matrixRows++) * matrix.Width(); rows[3] = matrixTable + (*matrixRows++) * matrix.Width(); const float* vec = vectorData; __m128 prods[4]; prods[3] = prods[2] = prods[1] = prods[0] = _mm_setzero_ps(); for(int i = 0; i < sseSize; ++i) { __m128 vecVal = LoadSse4(vec); prods[0] = _mm_add_ps(prods[0], _mm_mul_ps(vecVal, LoadSse4(rows[0]))); prods[1] = _mm_add_ps(prods[1], _mm_mul_ps(vecVal, LoadSse4(rows[1]))); prods[2] = _mm_add_ps(prods[2], _mm_mul_ps(vecVal, LoadSse4(rows[2]))); prods[3] = _mm_add_ps(prods[3], _mm_mul_ps(vecVal, LoadSse4(rows[3]))); vec += 4; rows[0] += 4; rows[1] += 4; rows[2] += 4; rows[3] += 4; } if(nonSseSize > 0) { __m128 vecVal = LoadSse(vec, nonSseSize); prods[0] = _mm_add_ps(prods[0], _mm_mul_ps(vecVal, LoadSse(rows[0], nonSseSize))); prods[1] = _mm_add_ps(prods[1], _mm_mul_ps(vecVal, LoadSse(rows[1], nonSseSize))); prods[2] = _mm_add_ps(prods[2], _mm_mul_ps(vecVal, LoadSse(rows[2], nonSseSize))); prods[3] = _mm_add_ps(prods[3], _mm_mul_ps(vecVal, LoadSse(rows[3], nonSseSize))); } _MM_TRANSPOSE4_PS(prods[0], prods[1], prods[2], prods[3]); __m128 res = _mm_add_ps(_mm_add_ps(prods[0], prods[1]), _mm_add_ps(prods[2], prods[3])); StoreSse4(res, result); result += 4; } for(int j = 0; j < height; ++j) { // Multiply the rows one by one const float* row; row = matrixTable + (*matrixRows++) * matrix.Width(); const float* vec = vectorData; __m128 prod; prod = _mm_setzero_ps(); for(int i = 0; i < sseSize; ++i) { __m128 vecVal = LoadSse4(vec); prod = _mm_add_ps(prod, _mm_mul_ps(vecVal, LoadSse4(row))); vec += 4; row += 4; } if(nonSseSize > 0) { __m128 vecVal = LoadSse(vec, nonSseSize); prod = _mm_add_ps(prod, _mm_mul_ps(vecVal, LoadSse(row, nonSseSize))); } __m128 res = HorizontalAddSse(prod); *result++ = _mm_cvtss_f32(res); } } } } // namespace NeoML #endif // NEOML_USE_SSE
33.367857
117
0.689393
sergesk
512d3330eec97e0ad717464069a9d579312c05f3
750
cpp
C++
acmicpc/20006.cpp
juseongkr/BOJ
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
7
2020-02-03T10:00:19.000Z
2021-11-16T11:03:57.000Z
acmicpc/20006.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2021-01-03T06:58:24.000Z
2021-01-03T06:58:24.000Z
acmicpc/20006.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2020-01-22T14:34:03.000Z
2020-01-22T14:34:03.000Z
#include <iostream> #include <algorithm> #include <vector> using namespace std; #define MAX 301 int p, m, l, idx, lv[MAX]; vector<pair<string, int>> vec[MAX]; string n; int main() { cin >> p >> m; for (int i=0; i<p; ++i) { cin >> l >> n; for (int j=0; j<MAX; ++j) { if (lv[j] == 0) { lv[j] = l; vec[j].push_back({n, l}); idx++; break; } else if (abs(lv[j] - l) <= 10 && vec[j].size() < m) { vec[j].push_back({n, l}); break; } } } for (int i=0; i<idx; ++i) { if (vec[i].size() == m) cout << "Started!\n"; else cout << "Waiting!\n"; sort(vec[i].begin(), vec[i].end()); for (int j=0; j<vec[i].size(); ++j) { cout << vec[i][j].second << " " << vec[i][j].first << '\n'; } } return 0; }
17.44186
62
0.48
juseongkr
512d3ec39e3fa15402e93f461609be030e11f815
7,821
cc
C++
benchmarks/benchmark.cc
jlquinn/intgemm
a56f8225c2ebade4a742b1e691514c7d6c9def3d
[ "MIT" ]
37
2018-06-25T07:08:05.000Z
2022-03-30T05:10:19.000Z
benchmarks/benchmark.cc
jlquinn/intgemm
a56f8225c2ebade4a742b1e691514c7d6c9def3d
[ "MIT" ]
50
2019-03-20T10:34:34.000Z
2022-03-30T16:49:10.000Z
benchmarks/benchmark.cc
jlquinn/intgemm
a56f8225c2ebade4a742b1e691514c7d6c9def3d
[ "MIT" ]
16
2018-10-10T11:58:32.000Z
2022-01-28T23:19:05.000Z
#include "../intgemm/aligned.h" #include "intgemm/intgemm_config.h" #include "../intgemm/avx512_gemm.h" #include "../intgemm/sse2_gemm.h" #include "../intgemm/avx2_gemm.h" #include "../intgemm/ssse3_gemm.h" #include "../intgemm/intgemm.h" #include "../intgemm/stats.h" #include "../intgemm/callbacks.h" #include <algorithm> #include <cassert> #include <chrono> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iomanip> #include <iostream> #include <random> namespace intgemm { namespace { struct RandomMatrices { RandomMatrices(Index A_rows_in, Index width_in, Index B_cols_in) : A_rows(A_rows_in), width(width_in), B_cols(B_cols_in), A(A_rows * width), B(width * B_cols) { std::mt19937 gen; std::uniform_real_distribution<float> dist(-1.f, 1.f); gen.seed(45678); for (auto& it : A) { it = dist(gen); } for (auto& it : B) { it = dist(gen); } } const Index A_rows, width, B_cols; AlignedVector<float> A, B; }; template <class Backend> double Run(const RandomMatrices &m) { using Integer = typename Backend::Integer; float quant_mult = 127.0f / 2.0f; float unquant_mult = 1.0f / (quant_mult * quant_mult); AlignedVector<Integer> A_prepared(m.A_rows * m.width); Backend::PrepareA(m.A.begin(), A_prepared.begin(), quant_mult, m.A_rows, m.width); AlignedVector<Integer> B_prepared(m.width * m.B_cols); Backend::PrepareB(m.B.begin(), B_prepared.begin(), quant_mult, m.width, m.B_cols); AlignedVector<float> output(m.A_rows * m.B_cols); // Burn in Backend::Multiply(A_prepared.begin(), B_prepared.begin(), m.A_rows, m.width, m.B_cols, callbacks::UnquantizeAndWrite(unquant_mult, output.begin())); auto start = std::chrono::steady_clock::now(); Backend::Multiply(A_prepared.begin(), B_prepared.begin(), m.A_rows, m.width, m.B_cols, callbacks::UnquantizeAndWrite(unquant_mult, output.begin())); return std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count(); } template <class Backend> void RunAll(RandomMatrices *matrices, RandomMatrices *matrices_end, std::vector<std::vector<double>> &stats) { if (Backend::kUses > kCPU) return; std::size_t size = matrices_end - matrices; if (stats.size() < size) stats.resize(size); for (std::size_t i = 0; i < size; ++i) { stats[i].push_back(Run<Backend>(matrices[i])); } } struct BackendStats { std::vector<std::vector<double>> ssse3_8bit; std::vector<std::vector<double>> avx2_8bit; std::vector<std::vector<double>> avx512_8bit; std::vector<std::vector<double>> avx512vnni_8bit; std::vector<std::vector<double>> sse2_16bit; std::vector<std::vector<double>> avx2_16bit; std::vector<std::vector<double>> avx512_16bit; }; const float kOutlierThreshold = 0.75; void Summarize(std::vector<double> &stats) { // Throw out outliers. std::vector<double>::iterator keep = stats.begin() + static_cast<std::size_t>(static_cast<float>(stats.size()) * kOutlierThreshold); std::nth_element(stats.begin(), keep, stats.end()); double avg = 0.0; for (std::vector<double>::const_iterator i = stats.begin(); i != keep; ++i) { avg += *i; } avg /= (keep - stats.begin()); double stddev = 0.0; for (std::vector<double>::const_iterator i = stats.begin(); i != keep; ++i) { double off = (double)*i - avg; stddev += off * off; } stddev = sqrt(stddev / (keep - stats.begin() - 1)); std::cout << std::setw(10) << *std::min_element(stats.begin(), stats.end()) << '\t' << std::setw(8) << avg << '\t' << std::setw(8) << stddev; } template <class Backend> void Print(std::vector<std::vector<double>> &stats, std::size_t index) { if (stats.empty()) return; std::cout << std::setw(16) << Backend::kName << '\t'; Summarize(stats[index]); std::cout << '\n'; } } // namespace intgemm } // namespace // Program takes no input int main(int, char ** argv) { std::cerr << "Remember to run this on a specific core:\ntaskset --cpu-list 0 " << argv[0] << std::endl; using namespace intgemm; RandomMatrices matrices[] = { {1, 64, 8}, {8, 256, 256}, {8, 2048, 256}, {8, 256, 2048}, {320, 256, 256}, {472, 256, 256}, {248, 256, 256}, {200, 256, 256}, // Additional stuff {256, 256, 256}, {512, 512, 512}, {1024, 1024, 1024}, /* {4096, 4096, 4096}, {4096, 4096, 2048}, {4096, 4096, 1024}, {4096, 4096, 512}, {4096, 4096, 256},*/ {4096, 4096, 128} }; RandomMatrices *matrices_end = (RandomMatrices*)matrices + sizeof(matrices) / sizeof(RandomMatrices); // Only do full sampling for <1024 rows. RandomMatrices *full_sample; for (full_sample = matrices_end - 1; full_sample >= matrices && full_sample->A_rows >= 1024; --full_sample) {} ++full_sample; BackendStats stats; const int kSamples = 100; // Realistically, we don't expect different architectures or different precisions to run in the // same run of an application. Benchmark per architecture and per precision level. std::cerr << "SSSE3 8bit, 100 samples..." << std::endl; for (int samples = 0; samples < kSamples; ++samples) { RandomMatrices *end = (samples < 4) ? matrices_end : full_sample; RunAll<SSSE3::Kernels8>(matrices, end, stats.ssse3_8bit); } std::cerr << "SSE2 16bit, 100 samples..." << std::endl; for (int samples = 0; samples < kSamples; ++samples) { RandomMatrices *end = (samples < 4) ? matrices_end : full_sample; RunAll<SSE2::Kernels16>(matrices, end, stats.sse2_16bit); } #ifdef INTGEMM_COMPILER_SUPPORTS_AVX2 std::cerr << "AVX2 8bit, 100 samples..." << std::endl; for (int samples = 0; samples < kSamples; ++samples) { RandomMatrices *end = (samples < 4) ? matrices_end : full_sample; RunAll<AVX2::Kernels8>(matrices, end, stats.avx2_8bit); } std::cerr << "AVX2 16bit, 100 samples..." << std::endl; for (int samples = 0; samples < kSamples; ++samples) { RandomMatrices *end = (samples < 4) ? matrices_end : full_sample; RunAll<AVX2::Kernels16>(matrices, end, stats.avx2_16bit); } #endif #ifdef INTGEMM_COMPILER_SUPPORTS_AVX512BW std::cerr << "AVX512 8bit, 100 samples..." << std::endl; for (int samples = 0; samples < kSamples; ++samples) { RandomMatrices *end = (samples < 4) ? matrices_end : full_sample; RunAll<AVX512BW::Kernels8>(matrices, end, stats.avx512_8bit); } std::cerr << "AVX512 16bit, 100 samples..." << std::endl; for (int samples = 0; samples < kSamples; ++samples) { RandomMatrices *end = (samples < 4) ? matrices_end : full_sample; RunAll<AVX512BW::Kernels16>(matrices, end, stats.avx512_16bit); } #endif #ifdef INTGEMM_COMPILER_SUPPORTS_AVX512VNNI std::cerr << "AVX512VNNI 8bit, 100 samples..." << std::endl; for (int samples = 0; samples < kSamples; ++samples) { RandomMatrices *end = (samples < 4) ? matrices_end : full_sample; RunAll<AVX512VNNI::Kernels8>(matrices, end, stats.avx512vnni_8bit); } #endif if (stats.sse2_16bit.empty()) { std::cerr << "No CPU support." << std::endl; return 1; } for (std::size_t i = 0; i < sizeof(matrices) / sizeof(RandomMatrices); ++i) { std::cout << "Multiply\t" << matrices[i].A_rows << '\t' << matrices[i].width << '\t' << matrices[i].B_cols << '\t' << "Samples=" << (kOutlierThreshold * stats.sse2_16bit[i].size()) << '\n'; Print<SSSE3::Kernels8>(stats.ssse3_8bit, i); Print<AVX2::Kernels8>(stats.avx2_8bit, i); #ifdef INTGEMM_COMPILER_SUPPORTS_AVX512BW Print<AVX512BW::Kernels8>(stats.avx512_8bit, i); #endif #ifdef INTGEMM_COMPILER_SUPPORTS_AVX512VNNI Print<AVX512VNNI::Kernels8>(stats.avx512vnni_8bit, i); #endif Print<SSE2::Kernels16>(stats.sse2_16bit, i); Print<AVX2::Kernels16>(stats.avx2_16bit, i); #ifdef INTGEMM_COMPILER_SUPPORTS_AVX512BW Print<AVX512BW::Kernels16>(stats.avx512_16bit, i); #endif } return 0; }
36.376744
193
0.664749
jlquinn
512f0745860519e583a559b258a8aecc0b41b6a7
905
cpp
C++
mp32wav/tests/LittleBigEndian_Test.cpp
dissabte/mp32wav
6b3e8e08f94df0db84ff99fe4bdf5f6aa92c7cee
[ "MIT" ]
3
2018-03-26T03:54:14.000Z
2021-12-27T14:04:03.000Z
mp32wav/tests/LittleBigEndian_Test.cpp
dissabte/mp32wav
6b3e8e08f94df0db84ff99fe4bdf5f6aa92c7cee
[ "MIT" ]
null
null
null
mp32wav/tests/LittleBigEndian_Test.cpp
dissabte/mp32wav
6b3e8e08f94df0db84ff99fe4bdf5f6aa92c7cee
[ "MIT" ]
null
null
null
#include <UnitTest++/UnitTest++.h> #include "../src/LittleBigEndian.h" #include <cstring> SUITE(AudilFileTest) { TEST(LittleEndianTest) { const uint32_t testValue = 0x00AACCBB; LittleEndian<uint32_t> leValue; std::memcpy(leValue.bytes, &testValue, sizeof(uint32_t)); uint32_t leCheckValue = leValue; CHECK_EQUAL(leCheckValue, testValue); unsigned char buffer[4] = {0xAA, 0xBB, 0xCC, 0xDD}; leCheckValue = LittleEndian<uint32_t>::fromBuffer(buffer); CHECK_EQUAL(leCheckValue, 0xDDCCBBAA); } TEST(BigEndianTest) { const uint32_t testValue = 0x00AACCBB; BigEndian<uint32_t> beValue; std::memcpy(beValue.bytes, &testValue, sizeof(uint32_t)); uint32_t beCheckValue = beValue; CHECK_EQUAL(beCheckValue, 0xBBCCAA00); unsigned char buffer[4] = {0xAA, 0xBB, 0xCC, 0xDD}; beCheckValue = BigEndian<uint32_t>::fromBuffer(buffer); CHECK_EQUAL(beCheckValue, 0xAABBCCDD); } }
25.857143
60
0.740331
dissabte
5130edb3dd55fe64a3752239e9d9ca4d6f82a649
10,497
cc
C++
unittests/libtests/meshio/TestMeshIO.cc
joegeisz/pylith
f74060b7b19d7e90abf8597bbe9250c96593c0ad
[ "MIT" ]
1
2021-09-09T06:24:11.000Z
2021-09-09T06:24:11.000Z
unittests/libtests/meshio/TestMeshIO.cc
joegeisz/pylith
f74060b7b19d7e90abf8597bbe9250c96593c0ad
[ "MIT" ]
null
null
null
unittests/libtests/meshio/TestMeshIO.cc
joegeisz/pylith
f74060b7b19d7e90abf8597bbe9250c96593c0ad
[ "MIT" ]
null
null
null
// -*- C++ -*- // // ---------------------------------------------------------------------- // // Brad T. Aagaard, U.S. Geological Survey // Charles A. Williams, GNS Science // Matthew G. Knepley, University of Chicago // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2017 University of California, Davis // // See COPYING for license information. // // ---------------------------------------------------------------------- // #include <portinfo> #include "TestMeshIO.hh" // Implementation of class methods #include "pylith/topology/Mesh.hh" // USES Mesh #include "pylith/topology/MeshOps.hh" // USES MeshOps::nondimensionalize() #include "pylith/topology/Stratum.hh" // USES Stratum #include "pylith/topology/CoordsVisitor.hh" // USES CoordsVisitor #include "pylith/meshio/MeshIO.hh" // USES MeshIO #include "pylith/utils/array.hh" // USES int_array #include "data/MeshData.hh" #include "spatialdata/geocoords/CSCart.hh" // USES CSCart #include "spatialdata/units/Nondimensional.hh" // USES Nondimensional #include <strings.h> // USES strcasecmp() #include <stdexcept> // USES std::logic_error // ---------------------------------------------------------------------- // Setup testing data. void pylith::meshio::TestMeshIO::setUp(void) { // setUp PYLITH_METHOD_BEGIN; _mesh = 0; PYLITH_METHOD_END; } // setUp // ---------------------------------------------------------------------- // Tear down testing data. void pylith::meshio::TestMeshIO::tearDown(void) { // tearDown PYLITH_METHOD_BEGIN; delete _mesh; _mesh = 0; PYLITH_METHOD_END; } // tearDown // ---------------------------------------------------------------------- // Get simple mesh for testing I/O. void pylith::meshio::TestMeshIO::_createMesh(const MeshData& data) { // _createMesh PYLITH_METHOD_BEGIN; // buildTopology() requires zero based index CPPUNIT_ASSERT_EQUAL(true, data.useIndexZero); CPPUNIT_ASSERT(data.vertices); CPPUNIT_ASSERT(data.cells); CPPUNIT_ASSERT(data.materialIds); if (data.numGroups > 0) { CPPUNIT_ASSERT(data.groups); CPPUNIT_ASSERT(data.groupSizes); CPPUNIT_ASSERT(data.groupNames); CPPUNIT_ASSERT(data.groupTypes); } // if delete _mesh; _mesh = new topology::Mesh(data.cellDim);CPPUNIT_ASSERT(_mesh); // Cells and vertices const bool interpolate = false; PetscDM dmMesh = NULL; PetscBool interpolateMesh = interpolate ? PETSC_TRUE : PETSC_FALSE; PetscInt bound = data.numCells*data.numCorners; PetscErrorCode err; int *cells = new int[bound]; for (PetscInt coff = 0; coff < bound; ++coff) {cells[coff] = data.cells[coff];} for (PetscInt coff = 0; coff < bound; coff += data.numCorners) { err = DMPlexInvertCell(data.cellDim, data.numCorners, &cells[coff]);PYLITH_CHECK_ERROR(err); } err = DMPlexCreateFromCellList(_mesh->comm(), data.cellDim, data.numCells, data.numVertices, data.numCorners, interpolateMesh, cells, data.spaceDim, data.vertices, &dmMesh);PYLITH_CHECK_ERROR(err); delete [] cells; _mesh->dmMesh(dmMesh); // Material ids PetscInt cStart, cEnd; err = DMPlexGetHeightStratum(dmMesh, 0, &cStart, &cEnd);PYLITH_CHECK_ERROR(err); for(PetscInt c = cStart; c < cEnd; ++c) { err = DMSetLabelValue(dmMesh, "material-id", c, data.materialIds[c-cStart]);PYLITH_CHECK_ERROR(err); } // for // Groups for (int iGroup=0, index=0; iGroup < data.numGroups; ++iGroup) { err = DMCreateLabel(dmMesh, data.groupNames[iGroup]);PYLITH_CHECK_ERROR(err); MeshIO::GroupPtType type; const int numPoints = data.groupSizes[iGroup]; if (0 == strcasecmp("cell", data.groupTypes[iGroup])) { type = MeshIO::CELL; for(int i=0; i < numPoints; ++i, ++index) { err = DMSetLabelValue(dmMesh, data.groupNames[iGroup], data.groups[index], 1);PYLITH_CHECK_ERROR(err); } // for } else if (0 == strcasecmp("vertex", data.groupTypes[iGroup])) { type = MeshIO::VERTEX; PetscInt numCells; err = DMPlexGetHeightStratum(dmMesh, 0, NULL, &numCells);PYLITH_CHECK_ERROR(err); for(int i=0; i < numPoints; ++i, ++index) { err = DMSetLabelValue(dmMesh, data.groupNames[iGroup], data.groups[index]+numCells, 1);PYLITH_CHECK_ERROR(err); } // for } else throw std::logic_error("Could not parse group type."); } // for // Set coordinate system spatialdata::geocoords::CSCart cs; cs.setSpaceDim(data.spaceDim); cs.initialize(); _mesh->coordsys(&cs); spatialdata::units::Nondimensional normalizer; normalizer.lengthScale(10.0); topology::MeshOps::nondimensionalize(_mesh, normalizer); PYLITH_METHOD_END; } // _createMesh // ---------------------------------------------------------------------- // Check values in mesh against data. void pylith::meshio::TestMeshIO::_checkVals(const MeshData& data) { // _checkVals PYLITH_METHOD_BEGIN; CPPUNIT_ASSERT(_mesh); // Check mesh dimension CPPUNIT_ASSERT_EQUAL(data.cellDim, _mesh->dimension()); const int spaceDim = data.spaceDim; PetscDM dmMesh = _mesh->dmMesh();CPPUNIT_ASSERT(dmMesh); // Check vertices topology::Stratum verticesStratum(dmMesh, topology::Stratum::DEPTH, 0); const PetscInt vStart = verticesStratum.begin(); const PetscInt vEnd = verticesStratum.end(); CPPUNIT_ASSERT_EQUAL(data.numVertices, verticesStratum.size()); topology::CoordsVisitor coordsVisitor(dmMesh); const PetscScalar* coordsArray = coordsVisitor.localArray(); const PylithScalar tolerance = 1.0e-06; for (PetscInt v = vStart, index = 0; v < vEnd; ++v) { const PetscInt off = coordsVisitor.sectionOffset(v); CPPUNIT_ASSERT_EQUAL(spaceDim, coordsVisitor.sectionDof(v)); for (int iDim=0; iDim < spaceDim; ++iDim, ++index) { if (data.vertices[index] < 1.0) { CPPUNIT_ASSERT_DOUBLES_EQUAL(data.vertices[index], coordsArray[off+iDim], tolerance); } else { CPPUNIT_ASSERT_DOUBLES_EQUAL(1.0, coordsArray[off+iDim]/data.vertices[index], tolerance); } // if/else } // for } // for // Check cells topology::Stratum cellsStratum(dmMesh, topology::Stratum::HEIGHT, 0); const PetscInt cStart = cellsStratum.begin(); const PetscInt cEnd = cellsStratum.end(); const PetscInt numCells = cellsStratum.size(); CPPUNIT_ASSERT_EQUAL(data.numCells, numCells); const int offset = numCells; PetscErrorCode err = 0; for(PetscInt c = cStart, index = 0; c < cEnd; ++c) { PetscInt *closure = PETSC_NULL; PetscInt closureSize, numCorners = 0; err = DMPlexGetTransitiveClosure(dmMesh, c, PETSC_TRUE, &closureSize, &closure);PYLITH_CHECK_ERROR(err); for(PetscInt p = 0; p < closureSize*2; p += 2) { const PetscInt point = closure[p]; if ((point >= vStart) && (point < vEnd)) { closure[numCorners++] = point; } // if } // for err = DMPlexInvertCell(data.cellDim, numCorners, closure);PYLITH_CHECK_ERROR(err); CPPUNIT_ASSERT_EQUAL(data.numCorners, numCorners); for(PetscInt p = 0; p < numCorners; ++p, ++index) { CPPUNIT_ASSERT_EQUAL(data.cells[index], closure[p]-offset); } // for err = DMPlexRestoreTransitiveClosure(dmMesh, c, PETSC_TRUE, &closureSize, &closure);PYLITH_CHECK_ERROR(err); } // for // check materials PetscInt matId = 0; for(PetscInt c = cStart; c < cEnd; ++c) { err = DMGetLabelValue(dmMesh, "material-id", c, &matId);PYLITH_CHECK_ERROR(err); CPPUNIT_ASSERT_EQUAL(data.materialIds[c-cStart], matId); } // for // Check groups PetscInt numGroups, pStart, pEnd; err = DMPlexGetChart(dmMesh, &pStart, &pEnd);PYLITH_CHECK_ERROR(err); err = DMGetNumLabels(dmMesh, &numGroups);PYLITH_CHECK_ERROR(err); numGroups -= 2; // Remove depth and material labels. CPPUNIT_ASSERT_EQUAL(data.numGroups, numGroups); PetscInt index = 0; for(PetscInt iGroup = 0, iLabel = numGroups-1; iGroup < numGroups; ++iGroup, --iLabel) { const char *name = NULL; PetscInt firstPoint = 0; err = DMGetLabelName(dmMesh, iLabel, &name);PYLITH_CHECK_ERROR(err); CPPUNIT_ASSERT_EQUAL(std::string(data.groupNames[iGroup]), std::string(name)); for(PetscInt p = pStart; p < pEnd; ++p) { PetscInt val; err = DMGetLabelValue(dmMesh, name, p, &val);PYLITH_CHECK_ERROR(err); if (val >= 0) { firstPoint = p; break; } // if } // for std::string groupType = (firstPoint >= cStart && firstPoint < cEnd) ? "cell" : "vertex"; CPPUNIT_ASSERT_EQUAL(std::string(data.groupTypes[iGroup]), groupType); PetscInt numPoints, numVertices = 0; err = DMGetStratumSize(dmMesh, name, 1, &numPoints);PYLITH_CHECK_ERROR(err); PetscIS pointIS = NULL; const PetscInt *points = NULL; const PetscInt offset = ("vertex" == groupType) ? numCells : 0; err = DMGetStratumIS(dmMesh, name, 1, &pointIS);PYLITH_CHECK_ERROR(err); err = ISGetIndices(pointIS, &points);PYLITH_CHECK_ERROR(err); for(PetscInt p = 0; p < numPoints; ++p) { const PetscInt pStart = ("vertex" == groupType) ? vStart : cStart; const PetscInt pEnd = ("vertex" == groupType) ? vEnd : cEnd; if ((points[p] >= pStart) && (points[p] < pEnd)) { CPPUNIT_ASSERT_EQUAL(data.groups[index++], points[p]-offset); ++numVertices; } } // for CPPUNIT_ASSERT_EQUAL(data.groupSizes[iGroup], numVertices); err = ISRestoreIndices(pointIS, &points);PYLITH_CHECK_ERROR(err); err = ISDestroy(&pointIS);PYLITH_CHECK_ERROR(err); } // for PYLITH_METHOD_END; } // _checkVals // ---------------------------------------------------------------------- // Test debug() void pylith::meshio::TestMeshIO::_testDebug(MeshIO& iohandler) { // _testDebug PYLITH_METHOD_BEGIN; bool debug = false; iohandler.debug(debug); CPPUNIT_ASSERT_EQUAL(debug, iohandler.debug()); debug = true; iohandler.debug(debug); CPPUNIT_ASSERT_EQUAL(debug, iohandler.debug()); PYLITH_METHOD_END; } // _testDebug // ---------------------------------------------------------------------- // Test interpolate() void pylith::meshio::TestMeshIO::_testInterpolate(MeshIO& iohandler) { // _testInterpolate PYLITH_METHOD_BEGIN; bool interpolate = false; iohandler.interpolate(interpolate); CPPUNIT_ASSERT_EQUAL(interpolate, iohandler.interpolate()); interpolate = true; iohandler.interpolate(interpolate); CPPUNIT_ASSERT_EQUAL(interpolate, iohandler.interpolate()); PYLITH_METHOD_END; } // _testInterpolate // End of file
34.758278
199
0.656187
joegeisz
51338ae50e20e8f5e0911e3e850ce9cf8888c6c4
500
cpp
C++
1 semester/AP/Labs/2/Code/2_1.cpp
kurpenok/Labs
069c92b7964a1445d093313b38ebdc56318d2a73
[ "MIT" ]
1
2022-02-06T17:50:25.000Z
2022-02-06T17:50:25.000Z
1 semester/AP/Labs/2/Code/2_1.cpp
kurpenok/Labs
069c92b7964a1445d093313b38ebdc56318d2a73
[ "MIT" ]
null
null
null
1 semester/AP/Labs/2/Code/2_1.cpp
kurpenok/Labs
069c92b7964a1445d093313b38ebdc56318d2a73
[ "MIT" ]
1
2022-03-02T06:45:06.000Z
2022-03-02T06:45:06.000Z
#include <iostream> #include <cmath> double f(double x) { double b = 1.3; if (x < 1.3) { return log(b * x) - (1 / (b * x + 1)); } else if ((x >= 1.3) && (x <= 1.7)) { return b * x + 1; } else if (x > 1.7) { return log(b * x) + (1 / (b * x + 1)); } return 0; } int main() { double x; std::cout << "[>] Enter X [1, 2]: "; std::cin >> x; double result = f(x); std::cout << "[+] Result: " << result << std::endl; return 0; }
17.241379
55
0.41
kurpenok
51374e254f627a0689f573774ad92185f041b855
275
cpp
C++
src/qlift-c-api/qlift-QHBoxLayout.cpp
msenol86/qlift-c-api
b591f1f020a6f35fdaf2a3ffee25aa98662cc027
[ "MIT" ]
null
null
null
src/qlift-c-api/qlift-QHBoxLayout.cpp
msenol86/qlift-c-api
b591f1f020a6f35fdaf2a3ffee25aa98662cc027
[ "MIT" ]
null
null
null
src/qlift-c-api/qlift-QHBoxLayout.cpp
msenol86/qlift-c-api
b591f1f020a6f35fdaf2a3ffee25aa98662cc027
[ "MIT" ]
1
2020-08-18T19:17:21.000Z
2020-08-18T19:17:21.000Z
#include <QHBoxLayout> #include "qlift-QHBoxLayout.h" void* QHBoxLayout_new(void *parent) { return static_cast<void*>(new QHBoxLayout {static_cast<QWidget*>(parent)}); } void QHBoxLayout_delete(void *hBoxLayout) { delete static_cast<QHBoxLayout*>(hBoxLayout); }
19.642857
79
0.741818
msenol86
51382e19cbcbdfcb6b312e8d57c035f52a61d321
21,914
hpp
C++
unit_test/tstGridOperator3d.hpp
abisner/picasso
06c1ae58e75f7da4c3eb2421c3297e5258c2ad90
[ "BSD-3-Clause" ]
null
null
null
unit_test/tstGridOperator3d.hpp
abisner/picasso
06c1ae58e75f7da4c3eb2421c3297e5258c2ad90
[ "BSD-3-Clause" ]
null
null
null
unit_test/tstGridOperator3d.hpp
abisner/picasso
06c1ae58e75f7da4c3eb2421c3297e5258c2ad90
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** * Copyright (c) 2021 by the Picasso authors * * All rights reserved. * * * * This file is part of the Picasso library. Picasso is distributed under a * * BSD 3-clause license. For the licensing terms see the LICENSE file in * * the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #include <Picasso_FieldManager.hpp> #include <Picasso_FieldTypes.hpp> #include <Picasso_GridOperator.hpp> #include <Picasso_InputParser.hpp> #include <Picasso_ParticleInit.hpp> #include <Picasso_ParticleInterpolation.hpp> #include <Picasso_ParticleList.hpp> #include <Picasso_Types.hpp> #include <Cajita.hpp> #include <Cabana_Core.hpp> #include <Kokkos_Core.hpp> #include <gtest/gtest.h> using namespace Picasso; namespace Test { //---------------------------------------------------------------------------// // Field tags. struct FooP : Field::Vector<double, 3> { static std::string label() { return "foo_p"; } }; struct FooIn : Field::Vector<double, 3> { static std::string label() { return "foo_in"; } }; struct FezIn : Field::Vector<double, 3> { static std::string label() { return "fez_in"; } }; struct FooOut : Field::Vector<double, 3> { static std::string label() { return "foo_out"; } }; struct BarP : Field::Scalar<double> { static std::string label() { return "bar_p"; } }; struct BarIn : Field::Scalar<double> { static std::string label() { return "bar_in"; } }; struct BarOut : Field::Scalar<double> { static std::string label() { return "bar_out"; } }; struct Baz : Field::Matrix<double, 3, 3> { static std::string label() { return "baz"; } }; struct MatI : Field::Matrix<double, 3, 3> { static std::string label() { return "mat_I"; } }; struct MatJ : Field::Matrix<double, 3, 3> { static std::string label() { return "mat_J"; } }; struct MatK : Field::Matrix<double, 3, 3> { static std::string label() { return "mat_K"; } }; struct Boo : Field::Tensor3<double, 3, 3, 3> { static std::string label() { return "boo"; } }; struct Cam : Field::Tensor4<double, 3, 3, 3, 3> { static std::string label() { return "cam"; } }; //---------------------------------------------------------------------------// // Particle operation. struct ParticleFunc { template <class LocalMeshType, class GatherDependencies, class ScatterDependencies, class LocalDependencies, class ParticleViewType> KOKKOS_INLINE_FUNCTION void operator()( const LocalMeshType& local_mesh, const GatherDependencies& gather_deps, const ScatterDependencies& scatter_deps, const LocalDependencies&, ParticleViewType& particle ) const { // Get input dependencies. auto foo_in = gather_deps.get( FieldLocation::Cell(), FooIn() ); auto bar_in = gather_deps.get( FieldLocation::Cell(), BarIn() ); // Get output dependencies. auto foo_out = scatter_deps.get( FieldLocation::Cell(), FooOut() ); auto bar_out = scatter_deps.get( FieldLocation::Cell(), BarOut() ); // Get particle data. auto foop = get( particle, FooP() ); auto& barp = get( particle, BarP() ); // Zero-order cell interpolant. auto spline = createSpline( FieldLocation::Cell(), InterpolationOrder<0>(), local_mesh, get( particle, Field::LogicalPosition<3>() ), SplineValue() ); // Interpolate to the particles. G2P::value( spline, foo_in, foop ); G2P::value( spline, bar_in, barp ); // Interpolate back to the grid. P2G::value( spline, foop, foo_out ); P2G::value( spline, barp, bar_out ); } }; //---------------------------------------------------------------------------// // Grid operation. struct GridFunc { struct Tag { }; template <class LocalMeshType, class GatherDependencies, class ScatterDependencies, class LocalDependencies> KOKKOS_INLINE_FUNCTION void operator()( Tag, const LocalMeshType&, const GatherDependencies& gather_deps, const ScatterDependencies& scatter_deps, const LocalDependencies& local_deps, const int i, const int j, const int k ) const { // Get input dependencies. auto foo_in = gather_deps.get( FieldLocation::Cell(), FooIn() ); auto bar_in = gather_deps.get( FieldLocation::Cell(), BarIn() ); // Get output dependencies. auto foo_out = scatter_deps.get( FieldLocation::Cell(), FooOut() ); auto bar_out = scatter_deps.get( FieldLocation::Cell(), BarOut() ); // Get scatter view accessors. auto foo_out_access = foo_out.access(); auto bar_out_access = bar_out.access(); // Get local dependencies. auto baz = local_deps.get( FieldLocation::Cell(), Baz() ); // Set up the local dependency to be the identity. baz( i, j, k ) = { { 1.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0 }, { 0.0, 0.0, 1.0 } }; // Assign foo_out - build a point-wise expression to do this. Test out // both separate index and array-based indices. const int index[3] = { i, j, k }; auto baz_t_foo_in_t_2 = baz( index ) * ( foo_in( index ) + foo_in( i, j, k ) ); for ( int d = 0; d < 3; ++d ) foo_out_access( i, j, k, d ) += baz_t_foo_in_t_2( d ) + i + j + k; // Assign the bar_out - use mixture of field dimension indices // or direct ijk access. bar_out_access( i, j, k, 0 ) += bar_in( i, j, k, 0 ) + bar_in( i, j, k ) + i + j + k; } }; //---------------------------------------------------------------------------// // Grid operation using a Tensor3 struct GridTensor3Func { struct Tag { }; template <class LocalMeshType, class GatherDependencies, class ScatterDependencies, class LocalDependencies> KOKKOS_INLINE_FUNCTION void operator()( Tag, const LocalMeshType&, const GatherDependencies& gather_deps, const ScatterDependencies& scatter_deps, const LocalDependencies& local_deps, const int i, const int j, const int k ) const { // Get input dependencies auto foo_in = gather_deps.get( FieldLocation::Cell(), FooIn() ); auto fez_in = gather_deps.get( FieldLocation::Cell(), FezIn() ); // Get output dependencies auto foo_out = scatter_deps.get( FieldLocation::Cell(), FooOut() ); auto foo_out_access = foo_out.access(); // Get local dependencies auto boo = local_deps.get( FieldLocation::Cell(), Boo() ); auto mat_i_out = local_deps.get( FieldLocation::Cell(), MatI() ); auto mat_j_out = local_deps.get( FieldLocation::Cell(), MatJ() ); auto mat_k_out = local_deps.get( FieldLocation::Cell(), MatK() ); foo_in( i, j, k, 0 ) = 1.0; foo_in( i, j, k, 1 ) = 2.0; foo_in( i, j, k, 2 ) = 3.0; fez_in( i, j, k, 0 ) = 3.0; fez_in( i, j, k, 1 ) = 4.0; fez_in( i, j, k, 2 ) = 3.0; // Set up the local dependency to be the Levi-Civita tensor. Picasso::LinearAlgebra::Tensor3<double, 3, 3, 3> levi_civita; Picasso::LinearAlgebra::permutation( levi_civita ); boo( i, j, k ) = levi_civita; const int index[3] = { i, j, k }; auto boo_t_foo_in = LinearAlgebra::contract( boo( index ), foo_in( index ), SpaceDim<2>{} ); auto boo_t_foo_in_t_fez_in = boo_t_foo_in * fez_in( index ); for ( int d = 0; d < 3; ++d ) { foo_out_access( i, j, k, d ) += boo_t_foo_in_t_fez_in( d ); } // Now test contraction along the other dimensions of a Tensor3 Picasso::LinearAlgebra::Tensor3<double, 3, 3, 3> tensor = { { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 } }, { { 9, 10, 11 }, { 12, 13, 14 }, { 15, 16, 17 } }, { { 18, 19, 20 }, { 21, 22, 23 }, { 24, 25, 26 } } }; mat_i_out( index ) = LinearAlgebra::contract( tensor, foo_in( index ), SpaceDim<0>() ); mat_j_out( index ) = LinearAlgebra::contract( tensor, foo_in( index ), SpaceDim<1>() ); mat_k_out( index ) = LinearAlgebra::contract( tensor, foo_in( index ), SpaceDim<2>() ); } }; // Grid operation using a Tensor4 struct GridTensor4Func { struct Tag { }; template <class LocalMeshType, class GatherDependencies, class ScatterDependencies, class LocalDependencies> KOKKOS_INLINE_FUNCTION void operator()( Tag, const LocalMeshType&, const GatherDependencies& gather_deps, const ScatterDependencies& scatter_deps, const LocalDependencies& local_deps, const int i, const int j, const int k ) const { // // Get input dependencies auto foo_in = gather_deps.get( FieldLocation::Cell(), FooIn() ); auto fez_in = gather_deps.get( FieldLocation::Cell(), FezIn() ); // Get output dependencies auto foo_out = scatter_deps.get( FieldLocation::Cell(), FooOut() ); auto foo_out_access = foo_out.access(); // Get local dependencies auto cam = local_deps.get( FieldLocation::Cell(), Cam() ); auto baz_out = local_deps.get( FieldLocation::Cell(), Baz() ); // Set up the local dependency to be the linear elasticity tensor // (3x3x3x3) double mu = 1; double lam = 0.5; cam( i, j, k ) = { { { { lam + 2 * mu, 0.0, 0.0 }, { 0.0, lam, 0.0 }, { 0.0, 0.0, lam } }, { { 0.0, mu, 0.0 }, { mu, 0.0, 0.0 }, { 0.0, 0.0, 0.0 } }, { { 0.0, 0.0, mu }, { 0.0, 0.0, 0.0 }, { mu, 0.0, 0.0 } } }, { { { 0.0, mu, 0.0 }, { mu, 0.0, 0.0 }, { 0.0, 0.0, 0.0 } }, { { lam, 0.0, 0.0 }, { 0.0, lam + 2 * mu, 0.0 }, { 0.0, 0.0, lam } }, { { 0.0, 0.0, 0.0 }, { 0.0, 0.0, mu }, { 0.0, mu, 0.0 } } }, { { { 0.0, 0.0, mu }, { 0.0, 0.0, 0.0 }, { mu, 0.0, 0.0 } }, { { 0.0, 0.0, 0.0 }, { 0.0, 0.0, mu }, { 0.0, mu, 0.0 } }, { { lam, 0.0, 0.0 }, { 0.0, lam, 0.0 }, { 0.0, 0.0, lam + 2 * mu } } } }; Picasso::Mat3<double> strain = { { 0.5, 1.0, 0 }, { 1.0, 0, 0 }, { 0, 0, 0 } }; const int index[3] = { i, j, k }; // This operation represents a stress tensor evaluation from the // "generalized" Hook's law, which is just a double contraction of a // fourth-order stiffness tensor with a strain tensor. baz_out is the // stress tensor in this example baz_out( index ) = LinearAlgebra::contract( cam( index ), strain ); } }; //---------------------------------------------------------------------------// void gatherScatterTest() { // Global bounding box. double cell_size = 0.23; std::array<int, 3> global_num_cell = { 43, 32, 39 }; std::array<double, 3> global_low_corner = { 1.2, 3.3, -2.8 }; std::array<double, 3> global_high_corner = { global_low_corner[0] + cell_size * global_num_cell[0], global_low_corner[1] + cell_size * global_num_cell[1], global_low_corner[2] + cell_size * global_num_cell[2] }; // Get inputs for mesh. InputParser parser( "particle_init_test.json", "json" ); Kokkos::Array<double, 6> global_box = { global_low_corner[0], global_low_corner[1], global_low_corner[2], global_high_corner[0], global_high_corner[1], global_high_corner[2] }; int minimum_halo_size = 0; // Make mesh. auto mesh = createUniformMesh( TEST_MEMSPACE(), parser.propertyTree(), global_box, minimum_halo_size, MPI_COMM_WORLD ); // Make a particle list. using list_type = ParticleList<UniformMesh<TEST_MEMSPACE>, Field::LogicalPosition<3>, FooP, BarP>; list_type particles( "test_particles", mesh ); using particle_type = typename list_type::particle_type; // Particle initialization functor. Make particles everywhere. auto particle_init_func = KOKKOS_LAMBDA( const double x[3], const double, particle_type& p ) { for ( int d = 0; d < 3; ++d ) get( p, Field::LogicalPosition<3>(), d ) = x[d]; return true; }; // Initialize particles. int ppc = 10; initializeParticles( InitRandom(), TEST_EXECSPACE(), ppc, particle_init_func, particles ); // Make an operator. using gather_deps = GatherDependencies<FieldLayout<FieldLocation::Cell, FooIn>, FieldLayout<FieldLocation::Cell, FezIn>, FieldLayout<FieldLocation::Cell, BarIn>>; using scatter_deps = ScatterDependencies<FieldLayout<FieldLocation::Cell, FooOut>, FieldLayout<FieldLocation::Cell, BarOut>>; using local_deps = LocalDependencies<FieldLayout<FieldLocation::Cell, Baz>, FieldLayout<FieldLocation::Cell, Boo>, FieldLayout<FieldLocation::Cell, Cam>, FieldLayout<FieldLocation::Cell, MatI>, FieldLayout<FieldLocation::Cell, MatJ>, FieldLayout<FieldLocation::Cell, MatK>>; auto grid_op = createGridOperator( mesh, gather_deps(), scatter_deps(), local_deps() ); // Make a field manager. auto fm = createFieldManager( mesh ); // Setup the field manager. grid_op->setup( *fm ); // Initialize gather fields. Kokkos::deep_copy( fm->view( FieldLocation::Cell(), FooIn() ), 2.0 ); Kokkos::deep_copy( fm->view( FieldLocation::Cell(), BarIn() ), 3.0 ); // Initialize scatter fields to wrong data to make sure they get reset to // zero and then overwritten with the data we assign in the operator. Kokkos::deep_copy( fm->view( FieldLocation::Cell(), FooOut() ), -1.1 ); Kokkos::deep_copy( fm->view( FieldLocation::Cell(), BarOut() ), -2.2 ); // Apply the particle operator. ParticleFunc particle_func; grid_op->apply( "particle_op", FieldLocation::Particle(), TEST_EXECSPACE(), *fm, particles, particle_func ); // Check the particle results. auto host_aosoa = Cabana::create_mirror_view_and_copy( Kokkos::HostSpace(), particles.aosoa() ); auto foo_p_host = Cabana::slice<1>( host_aosoa ); auto bar_p_host = Cabana::slice<2>( host_aosoa ); for ( std::size_t p = 0; p < particles.size(); ++p ) { for ( int d = 0; d < 3; ++d ) EXPECT_EQ( foo_p_host( p, d ), 2.0 ); EXPECT_EQ( bar_p_host( p ), 3.0 ); } // Check the grid results. auto foo_out_host = Kokkos::create_mirror_view_and_copy( Kokkos::HostSpace(), fm->view( FieldLocation::Cell(), FooOut() ) ); auto bar_out_host = Kokkos::create_mirror_view_and_copy( Kokkos::HostSpace(), fm->view( FieldLocation::Cell(), BarOut() ) ); Cajita::grid_parallel_for( "check_grid_out", Kokkos::DefaultHostExecutionSpace(), *( mesh->localGrid() ), Cajita::Own(), Cajita::Cell(), KOKKOS_LAMBDA( const int i, const int j, const int k ) { for ( int d = 0; d < 3; ++d ) EXPECT_EQ( foo_out_host( i, j, k, d ), ppc * 2.0 ); EXPECT_EQ( bar_out_host( i, j, k, 0 ), ppc * 3.0 ); } ); // Apply the grid operator. Use a tag. GridFunc grid_func; grid_op->apply( "grid_op", FieldLocation::Cell(), TEST_EXECSPACE(), *fm, GridFunc::Tag(), grid_func ); // Check the grid results. Kokkos::deep_copy( foo_out_host, fm->view( FieldLocation::Cell(), FooOut() ) ); Kokkos::deep_copy( bar_out_host, fm->view( FieldLocation::Cell(), BarOut() ) ); Cajita::grid_parallel_for( "check_grid_out", Kokkos::DefaultHostExecutionSpace(), *( mesh->localGrid() ), Cajita::Own(), Cajita::Cell(), KOKKOS_LAMBDA( const int i, const int j, const int k ) { for ( int d = 0; d < 3; ++d ) EXPECT_EQ( foo_out_host( i, j, k, d ), 4.0 + i + j + k ); EXPECT_EQ( bar_out_host( i, j, k, 0 ), 6.0 + i + j + k ); } ); // Re-initialize gather fields Kokkos::deep_copy( fm->view( FieldLocation::Cell(), FooIn() ), 0.0 ); Kokkos::deep_copy( fm->view( FieldLocation::Cell(), FezIn() ), 0.0 ); // Re-initialize scatter field to wrong value. Kokkos::deep_copy( fm->view( FieldLocation::Cell(), FooOut() ), -1.1 ); // Apply the tensor3 grid operator. Use a tag. GridTensor3Func grid_tensor3_func; grid_op->apply( "grid_tensor3_op", FieldLocation::Cell(), TEST_EXECSPACE(), *fm, GridTensor3Func::Tag(), grid_tensor3_func ); // Check the grid results. Kokkos::deep_copy( foo_out_host, fm->view( FieldLocation::Cell(), FooOut() ) ); auto mi_out_host = Kokkos::create_mirror_view_and_copy( Kokkos::HostSpace(), fm->view( FieldLocation::Cell(), MatI() ) ); auto mj_out_host = Kokkos::create_mirror_view_and_copy( Kokkos::HostSpace(), fm->view( FieldLocation::Cell(), MatJ() ) ); auto mk_out_host = Kokkos::create_mirror_view_and_copy( Kokkos::HostSpace(), fm->view( FieldLocation::Cell(), MatK() ) ); // Expect the correct cross-product for the given vector fields Cajita::grid_parallel_for( "check_tensor3_cross_product", Kokkos::DefaultHostExecutionSpace(), *( mesh->localGrid() ), Cajita::Own(), Cajita::Cell(), KOKKOS_LAMBDA( const int i, const int j, const int k ) { EXPECT_EQ( foo_out_host( i, j, k, 0 ), -6.0 ); EXPECT_EQ( foo_out_host( i, j, k, 1 ), 6.0 ); EXPECT_EQ( foo_out_host( i, j, k, 2 ), -2.0 ); } ); // Expect the correct matrices from the various Tensor3 contractions Cajita::grid_parallel_for( "check_tensor3_vector_contract", Kokkos::DefaultHostExecutionSpace(), *( mesh->localGrid() ), Cajita::Own(), Cajita::Cell(), KOKKOS_LAMBDA( const int i, const int j, const int k ) { EXPECT_EQ( mi_out_host( i, j, k, 0 ), 72 ); EXPECT_EQ( mi_out_host( i, j, k, 1 ), 78 ); EXPECT_EQ( mi_out_host( i, j, k, 2 ), 84 ); EXPECT_EQ( mi_out_host( i, j, k, 3 ), 90 ); EXPECT_EQ( mi_out_host( i, j, k, 4 ), 96 ); EXPECT_EQ( mi_out_host( i, j, k, 5 ), 102 ); EXPECT_EQ( mi_out_host( i, j, k, 6 ), 108 ); EXPECT_EQ( mi_out_host( i, j, k, 7 ), 114 ); EXPECT_EQ( mi_out_host( i, j, k, 8 ), 120 ); EXPECT_EQ( mj_out_host( i, j, k, 0 ), 24 ); EXPECT_EQ( mj_out_host( i, j, k, 1 ), 30 ); EXPECT_EQ( mj_out_host( i, j, k, 2 ), 36 ); EXPECT_EQ( mj_out_host( i, j, k, 3 ), 78 ); EXPECT_EQ( mj_out_host( i, j, k, 4 ), 84 ); EXPECT_EQ( mj_out_host( i, j, k, 5 ), 90 ); EXPECT_EQ( mj_out_host( i, j, k, 6 ), 132 ); EXPECT_EQ( mj_out_host( i, j, k, 7 ), 138 ); EXPECT_EQ( mj_out_host( i, j, k, 8 ), 144 ); EXPECT_EQ( mk_out_host( i, j, k, 0 ), 8 ); EXPECT_EQ( mk_out_host( i, j, k, 1 ), 26 ); EXPECT_EQ( mk_out_host( i, j, k, 2 ), 44 ); EXPECT_EQ( mk_out_host( i, j, k, 3 ), 62 ); EXPECT_EQ( mk_out_host( i, j, k, 4 ), 80 ); EXPECT_EQ( mk_out_host( i, j, k, 5 ), 98 ); EXPECT_EQ( mk_out_host( i, j, k, 6 ), 116 ); EXPECT_EQ( mk_out_host( i, j, k, 7 ), 134 ); EXPECT_EQ( mk_out_host( i, j, k, 8 ), 152 ); } ); GridTensor4Func grid_tensor4_func; grid_op->apply( "grid_tensor4_op", FieldLocation::Cell(), TEST_EXECSPACE(), *fm, GridTensor4Func::Tag(), grid_tensor4_func ); auto baz_out_host = Kokkos::create_mirror_view_and_copy( Kokkos::HostSpace(), fm->view( FieldLocation::Cell(), Baz() ) ); // Expect the correct matrices from the various tensor contractions Cajita::grid_parallel_for( "check_tensor4_matrix_contract", Kokkos::DefaultHostExecutionSpace(), *( mesh->localGrid() ), Cajita::Own(), Cajita::Cell(), KOKKOS_LAMBDA( const int i, const int j, const int k ) { EXPECT_EQ( baz_out_host( i, j, k, 0 ), 1.25 ); EXPECT_EQ( baz_out_host( i, j, k, 1 ), 2 ); EXPECT_EQ( baz_out_host( i, j, k, 2 ), 0 ); EXPECT_EQ( baz_out_host( i, j, k, 3 ), 2 ); EXPECT_EQ( baz_out_host( i, j, k, 4 ), 0.25 ); EXPECT_EQ( baz_out_host( i, j, k, 5 ), 0 ); EXPECT_EQ( baz_out_host( i, j, k, 6 ), 0 ); EXPECT_EQ( baz_out_host( i, j, k, 7 ), 0 ); EXPECT_EQ( baz_out_host( i, j, k, 8 ), 0.25 ); } ); } //---------------------------------------------------------------------------// // RUN TESTS //---------------------------------------------------------------------------// TEST( TEST_CATEGORY, gather_scatter_test ) { gatherScatterTest(); } //---------------------------------------------------------------------------// } // end namespace Test
39.843636
80
0.544401
abisner
513838948060ea5b2cd034b2115cdf228725fc6b
1,158
cpp
C++
cpp/string_multibyte_mbrlen.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
cpp/string_multibyte_mbrlen.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
cpp/string_multibyte_mbrlen.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
/* g++ --std=c++20 -pthread -o ../_build/cpp/string_multibyte_mbrlen.exe ./cpp/string_multibyte_mbrlen.cpp && (cd ../_build/cpp/;./string_multibyte_mbrlen.exe) https://en.cppreference.com/w/cpp/string/multibyte/mbrlen */ #include <clocale> #include <string> #include <iostream> #include <cwchar> int main() { // allow mbrlen() to work with UTF-8 multibyte encoding std::setlocale(LC_ALL, "en_US.utf8"); // UTF-8 narrow multibyte encoding std::string str = "水"; // or u8"\u6c34" or "\xe6\xb0\xb4" std::mbstate_t mb = std::mbstate_t(); int len1 = std::mbrlen(&str[0], 1, &mb); if(len1 == -2) { std::cout << "The first 1 byte of " << str << " is an incomplete multibyte char (mbrlen returns -2)\n"; } int len2 = std::mbrlen(&str[1], str.size()-1, &mb); std::cout << "The remaining " << str.size()-1 << " bytes of " << str << " hold " << len2 << " bytes of the multibyte character\n"; std::cout << "Attempting to call mbrlen() in the middle of " << str << " while in initial shift state returns " << (int)mbrlen(&str[1], str.size(), &mb) << '\n'; }
39.931034
156
0.587219
rpuntaie
5138a09ebc9f4012bdbaa539c9546a9ea4fa182c
1,368
cpp
C++
tests/transactions/helpers.cpp
brett19/couchbase-transactions-cxx
468342818a62b8648798b112618afb47ed229c0b
[ "Apache-2.0" ]
null
null
null
tests/transactions/helpers.cpp
brett19/couchbase-transactions-cxx
468342818a62b8648798b112618afb47ed229c0b
[ "Apache-2.0" ]
null
null
null
tests/transactions/helpers.cpp
brett19/couchbase-transactions-cxx
468342818a62b8648798b112618afb47ed229c0b
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 Couchbase, 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. */ #include "helpers.hxx" bool operator==(const SimpleObject& lhs, const SimpleObject& rhs) { return (rhs.name == lhs.name) && (rhs.number == lhs.number); } void to_json(nlohmann::json& j, const SimpleObject& o) { j = nlohmann::json{ { "name", o.name }, { "number", o.number } }; } void from_json(const nlohmann::json& j, SimpleObject& o) { j.at("name").get_to(o.name); j.at("number").get_to(o.number); } bool operator==(const AnotherSimpleObject& lhs, const AnotherSimpleObject& rhs) { return lhs.foo == rhs.foo; } void to_json(nlohmann::json& j, const AnotherSimpleObject& o) { j = nlohmann::json{ { "foo", o.foo } }; } void from_json(const nlohmann::json& j, AnotherSimpleObject& o) { j.at("foo").get_to(o.foo); }
25.811321
77
0.679094
brett19
5138e1dd4b3e47239ee7e34d93c4a6a94b85d575
4,062
cc
C++
content/browser/android/navigation_handle_proxy.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
content/browser/android/navigation_handle_proxy.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
content/browser/android/navigation_handle_proxy.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2019 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. #include "content/browser/android/navigation_handle_proxy.h" #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "content/public/android/content_jni_headers/NavigationHandle_jni.h" #include "content/public/browser/navigation_handle.h" #include "url/android/gurl_android.h" #include "url/gurl.h" using base::android::AttachCurrentThread; using base::android::ConvertUTF8ToJavaString; using base::android::JavaParamRef; using base::android::ScopedJavaLocalRef; namespace content { NavigationHandleProxy::NavigationHandleProxy( NavigationHandle* cpp_navigation_handle) : cpp_navigation_handle_(cpp_navigation_handle) { JNIEnv* env = AttachCurrentThread(); java_navigation_handle_ = Java_NavigationHandle_Constructor( env, reinterpret_cast<jlong>(this), url::GURLAndroid::FromNativeGURL(env, cpp_navigation_handle_->GetURL()), cpp_navigation_handle_->IsInMainFrame(), cpp_navigation_handle_->IsInPrimaryMainFrame(), cpp_navigation_handle_->IsSameDocument(), cpp_navigation_handle_->IsRendererInitiated()); } void NavigationHandleProxy::DidRedirect() { JNIEnv* env = AttachCurrentThread(); Java_NavigationHandle_didRedirect( env, java_navigation_handle_, url::GURLAndroid::FromNativeGURL(env, cpp_navigation_handle_->GetURL())); } void NavigationHandleProxy::DidFinish() { JNIEnv* env = AttachCurrentThread(); // Matches logic in // components/navigation_interception/navigation_params_android.cc const GURL& gurl = cpp_navigation_handle_->GetBaseURLForDataURL().is_empty() ? cpp_navigation_handle_->GetURL() : cpp_navigation_handle_->GetBaseURLForDataURL(); bool is_fragment_navigation = cpp_navigation_handle_->IsSameDocument(); if (cpp_navigation_handle_->HasCommitted()) { // See http://crbug.com/251330 for why it's determined this way. url::Replacements<char> replacements; replacements.ClearRef(); bool urls_same_ignoring_fragment = cpp_navigation_handle_->GetURL().ReplaceComponents(replacements) == cpp_navigation_handle_->GetPreviousMainFrameURL().ReplaceComponents( replacements); is_fragment_navigation &= urls_same_ignoring_fragment; } bool is_valid_search_form_url = cpp_navigation_handle_->GetSearchableFormURL() != "" ? cpp_navigation_handle_->GetSearchableFormURL().is_valid() : false; Java_NavigationHandle_didFinish( env, java_navigation_handle_, url::GURLAndroid::FromNativeGURL(env, gurl), cpp_navigation_handle_->IsErrorPage(), cpp_navigation_handle_->HasCommitted(), is_fragment_navigation, cpp_navigation_handle_->IsDownload(), is_valid_search_form_url, cpp_navigation_handle_->HasCommitted() ? cpp_navigation_handle_->GetPageTransition() : -1, cpp_navigation_handle_->GetNetErrorCode(), // TODO(shaktisahu): Change default status to -1 after fixing // crbug/690041. cpp_navigation_handle_->GetResponseHeaders() ? cpp_navigation_handle_->GetResponseHeaders()->response_code() : 200); } NavigationHandleProxy::~NavigationHandleProxy() { JNIEnv* env = AttachCurrentThread(); Java_NavigationHandle_release(env, java_navigation_handle_); } // Called from Java. void NavigationHandleProxy::SetRequestHeader( JNIEnv* env, const JavaParamRef<jstring>& name, const JavaParamRef<jstring>& value) { cpp_navigation_handle_->SetRequestHeader(ConvertJavaStringToUTF8(name), ConvertJavaStringToUTF8(value)); } // Called from Java. void NavigationHandleProxy::RemoveRequestHeader( JNIEnv* env, const JavaParamRef<jstring>& name) { cpp_navigation_handle_->RemoveRequestHeader(ConvertJavaStringToUTF8(name)); } } // namespace content
38.320755
80
0.745692
DamieFC
513cb0f1884a2eef048bfab38cebff17d8cc5262
6,671
cc
C++
RAVL2/OS/Network/SocketAddr.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/OS/Network/SocketAddr.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/OS/Network/SocketAddr.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
#include "Ravl/OS/SocketAddr.hh" #if RAVL_OS_SOLARIS #define __EXTENSIONS__ 1 #include <string.h> #include <netdir.h> #endif #ifdef __linux__ #define _REENTRANT 1 #define _BSD_SOURCE 1 #define _XOPEN_SOURCE_EXTENDED 1 #endif #include "Ravl/OS/SocketAddr.hh" #include "Ravl/OS/Date.hh" #include "Ravl/OS/SktError.hh" #include "Ravl/MTLocks.hh" #include "Ravl/OS/SysLog.hh" #if RAVL_HAVE_NETDB_H #include <netdb.h> #endif #include <sys/types.h> #if !RAVL_USE_WINSOCK #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #endif #if RAVL_HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #include <string.h> #include <stdlib.h> #include <errno.h> #if RAVL_HAVE_UNISTD_H #include <unistd.h> #endif #if !RAVL_USE_WINSOCK #include <sys/uio.h> #include <poll.h> #endif #include <fcntl.h> #define DODEBUG 0 #if DODEBUG #define ONDEBUG(x) x #else #define ONDEBUG(x) #endif #if !RAVL_HAVE_SOCKLEN_T #define socklen_t int #endif namespace RavlN { //: Attempt to get info about named host. // returns true on success. bool GetHostByName(const char *name,struct sockaddr_in &sin) { #if RAVL_USE_WINSOCK RavlAssertMsg(0,"Not implemented. "); return false; #else int opErrno = 0; int buffSize = 1024; char *hostentData = new char [buffSize]; struct hostent ent; struct hostent *result = 0; if(*name == 0) name = "localhost"; ent.h_addrtype = 0; while(1) { ONDEBUG(SysLog(SYSLOG_DEBUG) << " Looking for '" << name << "'\n"); opErrno = 0; #if RAVL_OS_LINUX || RAVL_OS_LINUX64 if(gethostbyname_r(name,&ent,hostentData,buffSize,&result, &opErrno) == 0 && result != 0) break; #elif RAVL_OS_OSF if((gethostbyname_r(name,&ent,(struct hostent_data *) hostentData)) != 0) { result = &ent; break; } opErrno = h_errno; #elif RAVL_OS_MACOSX || RAVL_OS_FREEBSD if((result = gethostbyname(name)) != 0) break; #else if((result = gethostbyname_r(name,&ent,hostentData,buffSize,&opErrno)) != 0) break; #endif if(opErrno == ERANGE) { delete [] hostentData; buffSize *= 2; if(buffSize > 100000) { delete [] hostentData; throw ExceptionNetC("GetHostByName(),ERROR: Buffer requested too large. Failing.\n"); } hostentData = new char [buffSize]; continue; } if(opErrno < 0) { SysLog(SYSLOG_WARNING) << "Can't understand hostname '" << name << "', Malformed address?"; delete [] hostentData; throw ExceptionNetC("Failed to unstanderstand find host name.\n"); } #if 0 if(opErrno == TRY_AGAIN) { ONDEBUG(SysLog(SYSLOG_DEBUG) << "Failed to get hostname, retrying. \n"); DateC::Sleep(0.5); // Thread safe sleep. continue; } #endif if(opErrno == HOST_NOT_FOUND) { SysLog(SYSLOG_WARNING) << "Can't find host '" << name << "' ."; delete [] hostentData; throw ExceptionNetC("Can't find host name.\n"); } SysLog(SYSLOG_WARNING) << "Can't find host '" << name << "' for some reason. Errno:" << opErrno << " '" #if RAVL_HAVE_HSTRERROR << hstrerror(opErrno) << "'"; #else << strerror(opErrno) << "'"; #endif delete [] hostentData; throw ExceptionNetC("Can't find host name for some reason."); } RavlAssert(result != 0); // char *addr = inet_ntoa(*((struct in_addr *)(result->h_addr_list[0]))); //sin.sin_addr.s_addr = inet_addr(addr); #if DODEBUG SysLog(SYSLOG_DEBUG) << "Offical hostname: '" << result->h_name << "' h_length: '" << result->h_length << "' "; //SysLog(SYSLOG_DEBUG) << "h_addr_list: '" << result->h_addr_list[0] << "' "; #endif sin.sin_addr.s_addr = ((struct in_addr *)result->h_addr_list[0])->s_addr; sin.sin_family = ent.h_addrtype; ONDEBUG(SysLog(SYSLOG_DEBUG) << "Got host data.. Addr:'" << inet_ntoa(sin.sin_addr) << "' "); delete [] hostentData; return true; #endif } //: Attempt to find hostname by the address. // returns true on success and assignes the hostname to name. bool GetHostByAddr(struct sockaddr &sin,int sinLen,StringC &name) { #if RAVL_USE_WINSOCK #if 0 char strHostName[1024]; if(getnameinfo(&sin,1024, strHostName, 1024, 0,0,NI_NUMERICSERV) == SOCKET_ERROR) return false; strRet = StringC(strHostName); return true; #else RavlAssertMsg(0,"Not implemetned. "); return false; #endif #else int buffSize = 1024; char *hostentData = new char [buffSize]; struct hostent ent; ent.h_name = 0; int error = 0; while(1) { #if RAVL_OS_LINUX || RAVL_OS_LINUX64 struct hostent *result = 0; int retcode; // Hack to detect the difference between red-hat 6.x and 7.x boxes. #if (_XOPEN_SOURCE - 0) <= 500 // For red-hat 6.2 if((retcode = gethostbyaddr_r((char *) &(((sockaddr_in &)sin).sin_addr),sinLen,AF_INET,&ent,hostentData,buffSize,&result,&error)) != 0) break; #else // For red-hat 7.2 if((retcode = gethostbyaddr_r(&(((sockaddr_in &)sin).sin_addr),sinLen,AF_INET,&ent,hostentData,buffSize,&result,&error)) != 0) break; #endif #elif RAVL_OS_OSF if(gethostbyaddr_r((const char *) &((sockaddr_in &)sin).sin_addr,sinLen,AF_INET,&ent,(struct hostent_data *)hostentData) == 0) break; error = h_errno; #elif RAVL_OS_IRIX ulong tmp_addr = ((sockaddr_in &)sin).sin_addr.s_addr ; gethostbyaddr_r ((const char *) & tmp_addr, sizeof(tmp_addr), AF_INET, &ent, hostentData, buffSize, &error) ; #elif RAVL_OS_MACOSX || RAVL_OS_FREEBSD { struct hostent *pHostent = gethostbyaddr((const char *) &((sockaddr_in &)sin).sin_addr,sinLen,AF_INET); if (pHostent == 0) break; } #else gethostbyaddr_r((const char *) &((sockaddr_in &)sin).sin_addr,sinLen,AF_INET,&ent,hostentData,buffSize,&error); #endif if(error == 0) break; if(error == ERANGE) { // Buffer not big enough. delete [] hostentData; buffSize *= 2; if(buffSize > 100000) { delete [] hostentData; throw ExceptionNetC("GetHostByName(),ERROR: Buffer requested too large. Failing. "); } hostentData = new char [buffSize]; continue; } SysLog(SYSLOG_ERR) << "WARNING: Error while attempting to find hostname from ip address. errno=" << error << " "; break; // Unknown error. } if(error == 0) { // If we got the name ok. name = StringC(ent.h_name); delete [] hostentData; return true; } delete [] hostentData; MTWriteLockC hold; // this call isn't MT safe. name = inet_ntoa(((sockaddr_in &)sin).sin_addr); // Convert to a dot notation string. #endif return true; } }
28.387234
141
0.641733
isuhao
513d3587339e31c9de95dc67bba5ced73c4966b9
19,821
cpp
C++
gtest/containers/set_test.cpp
public-jun/42_ft_containers
28e32632ebf7100537fc2c0bc85438ada9f0e4f0
[ "MIT" ]
null
null
null
gtest/containers/set_test.cpp
public-jun/42_ft_containers
28e32632ebf7100537fc2c0bc85438ada9f0e4f0
[ "MIT" ]
40
2022-02-12T06:50:14.000Z
2022-03-31T14:43:29.000Z
gtest/containers/set_test.cpp
public-jun/42_ft_containers
28e32632ebf7100537fc2c0bc85438ada9f0e4f0
[ "MIT" ]
null
null
null
#if STL // -DTEST=1 #else // -DTEST=0 #include <set.hpp> #endif #if __cplusplus >= 201103L #include <gtest/gtest.h> #else #include "../ft_test.hpp" #endif #include <set> #include <time.h> // 内部構造はmapと同じなのでテストは簡易 template <class T> void compare_set_iterator(T first1, T end1, T first2) { for (; first1 != end1; ++first1, ++first2) EXPECT_EQ(*first1, *first2); } TEST(Set, Constructor) { // set(); { ft::set<int> s; EXPECT_EQ(0, s.size()); EXPECT_EQ(true, s.empty()); EXPECT_EQ(s.begin(), s.end()); EXPECT_EQ(s.rbegin(), s.rend()); } // explicit set(const Compare& comp, const Allocator& alloc = Allocator()); { ft::set<int, std::greater<int> > s((std::greater<int>()), (std::allocator<int>())); EXPECT_EQ(0, s.size()); EXPECT_EQ(true, s.empty()); } // template< class InputIt > // set(InputIt first, InputIt last, const Compare& comp = Compare(), // const Allocator& alloc = Allocator()); { ft::set<int> s1; for (int i = 0; i < 10; ++i) s1.insert(i); ft::set<int> s2(s1.begin(), s1.end(), (std::less<int>()), (std::allocator<int>())); compare_set_iterator(s1.begin(), s1.end(), s2.begin()); EXPECT_EQ(s1.size(), s2.size()); EXPECT_EQ(s1.get_allocator(), s2.get_allocator()); } // set( const set& other ); { ft::set<int> s1; for (int i = 0; i < 10; ++i) s1.insert(i); ft::set<int> s2(s1); compare_set_iterator(s1.begin(), s1.end(), s2.begin()); EXPECT_EQ(s1.size(), s2.size()); EXPECT_EQ(s1.get_allocator(), s2.get_allocator()); } // operator=(const set& other); { ft::set<int> s1; for (int i = 0; i < 10; ++i) s1.insert(i); ft::set<int> s2; s2 = s1; compare_set_iterator(s1.begin(), s1.end(), s2.begin()); EXPECT_EQ(s1.size(), s2.size()); EXPECT_EQ(s1.get_allocator(), s2.get_allocator()); ft::set<int> s3; for (int i = 10; i < 30; ++i) s3.insert(i); s2 = s3; compare_set_iterator(s3.begin(), s3.end(), s2.begin()); EXPECT_EQ(s3.size(), s2.size()); EXPECT_EQ(s3.get_allocator(), s2.get_allocator()); } } TEST(Set, Iterator) { ft::set<int> s; for (int i = 0; i < 10; ++i) s.insert(i); // Non const map && Non const iterator ft::set<int>::iterator it = s.begin(); EXPECT_EQ(0, *it); ++it; EXPECT_EQ(1, *it); it = s.end(); --it; EXPECT_EQ(9, *it); // Non const map && const iterator ft::set<int>::const_iterator cit = s.begin(); EXPECT_EQ(0, *cit); ++cit; EXPECT_EQ(1, *cit); cit = s.end(); --cit; EXPECT_EQ(9, *cit); // const map && const iterator const ft::set<int> cs1(s); ft::set<int>::const_iterator cit2 = cs1.begin(); EXPECT_EQ(0, *cit2); const ft::set<int> cs2(cs1); cit2 = cs2.begin(); EXPECT_EQ(0, *cit2); ft::set<int>::const_iterator cit3; cit3 = cit2; EXPECT_EQ(0, *cit3); cit3++; EXPECT_EQ(1, *cit3); cit3 = cs1.end(); --cit3; EXPECT_EQ(9, *cit3); } TEST(Set, ReverseIterator) { // reverse_iterator ft::set<int> s; for (int i = 0; i < 10; ++i) s.insert(i); ft::set<int>::reverse_iterator rit = s.rbegin(); int j = 9; for (ft::set<int>::reverse_iterator end = s.rend(); rit != end; ++rit, --j) { EXPECT_EQ(j, *rit); } // const_reverse_iterator const ft::set<int> cs(s); ft::set<int>::const_reverse_iterator crit = cs.rbegin(); j = 9; for (ft::set<int>::const_reverse_iterator end = cs.rend(); crit != end; ++crit, --j) { EXPECT_EQ(j, *crit); } } TEST(Set, CapacitySizeAndEmpty) { ft::set<int> s; EXPECT_TRUE(s.empty()); for (std::size_t i = 0; i < 10; ++i) { s.insert(i); EXPECT_EQ(i + 1, s.size()); } EXPECT_FALSE(s.empty()); const ft::set<int> cs(s); EXPECT_EQ(s.size(), cs.size()); } TEST(Set, CapacityMaxSize) { { ft::set<int> ft_s; std::set<int> stl_s; EXPECT_EQ(stl_s.max_size(), ft_s.max_size()); } { ft::set<std::string, std::less<std::string> > ft_s; std::set<std::string, std::less<std::string> > stl_s; EXPECT_EQ(stl_s.max_size(), ft_s.max_size()); } { ft::set<std::string, std::less<std::string> > ft_s; std::set<std::string, std::less<std::string> > stl_s; EXPECT_EQ(stl_s.max_size(), ft_s.max_size()); } { ft::set<double, std::less<double> > ft_s; std::set<double, std::less<double> > stl_s; EXPECT_EQ(stl_s.max_size(), ft_s.max_size()); } } TEST(Set, ModifiersInsert) { // std::pair<iterator,bool> insert( const value_type& value ); std::srand(time(NULL)); { std::vector<int> v; ft::set<int> s; ft::pair<ft::set<int>::iterator, bool> ret; for (int i = 0; i < SIZE; ++i) { int key = std::rand(); ret = s.insert(key); EXPECT_EQ(*(ret.first), key); if (ret.second == true) v.insert(v.begin(), key); } std::sort(v.begin(), v.end()); ft::set<int>::iterator it = s.begin(); ft::set<int>::iterator end = s.end(); int i = 0; while (it != end) { EXPECT_EQ((*it), v.at(i++)); ++it; } } // iterator insert( iterator hint, const value_type& value ); { std::set<int> stl_s; std::set<int>::iterator sit; ft::set<int> s; ft::set<int>::iterator it = s.begin(); ft::set<int>::iterator end; for (int i = 0; i < SIZE; ++i) { int key = std::rand() / SIZE; it = s.insert(it, key); EXPECT_EQ(*it, key); ++it; stl_s.insert(key); } it = s.begin(); end = s.end(); sit = stl_s.begin(); while (it != end) { EXPECT_EQ(*it, *sit); ++sit; ++it; } } // template< class InputIt > // void insert(InputIt first, InputIt last) { ft::set<int> s; for (int i = 1; i <= 20; ++i) s.insert(i); for (int i = 41; i <= 60; ++i) s.insert(i); ft::set<int> s1; for (int i = 21; i <= 40; ++i) s1.insert(i); s.insert(s1.begin(), s1.end()); ft::set<int>::iterator it = s.begin(); for (int i = 1; i <= 60; ++i) EXPECT_EQ(i, *(it++)); } } TEST(Set, ModifiersErase) { std::srand(time(NULL)); // void erase( iterator pos ); { std::vector<int> v; ft::set<int> s; ft::pair<ft::set<int>::iterator, bool> ret; for (int i = 0; i < SIZE; ++i) { int key = std::rand() % SIZE; ret = s.insert(key); EXPECT_EQ(*(ret.first), key); if (ret.second == true) v.insert(v.begin(), key); } std::vector<int>::iterator it = v.begin(); for (std::vector<int>::iterator end = v.end(); it != end; ++it) { s.erase(s.find(*it)); } EXPECT_EQ(s.size(), 0); EXPECT_TRUE(s.empty()); } // void erase( iterator first, iterator last ); { std::vector<int> v; ft::set<int> s; ft::pair<ft::set<int>::iterator, bool> ret; for (int i = 0; i < SIZE; ++i) { int key = std::rand() % SIZE; ret = s.insert(key); EXPECT_EQ(*(ret.first), key); if (ret.second == true) v.insert(v.begin(), key); } std::sort(v.begin(), v.end()); std::vector<int>::iterator vf, vl, vtmp; // 削除する範囲の値を得る while (true) { vf = find(v.begin(), v.end(), std::rand() % SIZE); vl = find(vf, v.end(), std::rand() % SIZE); if (vf != v.end() && vl != v.end()) break; } ft::set<int>::iterator first, last, stmp; first = s.find(*vf); last = s.find(*vl); s.erase(first, last); vtmp = v.begin(); stmp = s.begin(); std::size_t size = 0; bool is_removed_range = false; for (; vtmp != v.end(); ++vtmp) { if (vtmp == vf) is_removed_range = true; if (vtmp == vl) is_removed_range = false; if (is_removed_range == false) { EXPECT_EQ(*vtmp, *stmp); ++size; ++stmp; } // [first, last) が消去されているか確認 if (is_removed_range == true) EXPECT_EQ(s.end(), s.find(*vtmp)); } EXPECT_EQ(size, s.size()); EXPECT_FALSE(s.empty()); } // size_type erase( const key_type& key ); { std::vector<int> v; ft::set<int> s; int key; ft::pair<ft::set<int>::iterator, bool> ret; for (int i = 0; i < SIZE; ++i) { key = std::rand() % SIZE; ret = s.insert(key); EXPECT_EQ(*ret.first, key); if (ret.second == true) v.insert(v.begin(), key); } std::sort(v.begin(), v.end()); for (int i = 0; i < SIZE; ++i) { key = std::rand() % SIZE; std::vector<int>::iterator it = find(v.begin(), v.end(), key); if (it != v.end()) { EXPECT_EQ(1, s.erase(key)); v.erase(it); } else EXPECT_EQ(0, s.erase(key)); EXPECT_EQ(v.size(), s.size()); } } } TEST(Set, ModifiersClear) { ft::set<int> s; for (int i = 0; i < 10; ++i) s.insert(i); s.clear(); s.clear(); EXPECT_EQ(0, s.size()); EXPECT_TRUE(s.empty()); } TEST(Set, ModifiersMemberSwap) { ft::set<char> s1; for (int i = 0; i < 10; ++i) s1.insert('a' + i); ft::set<char> s2; for (int i = -10; i < -4; ++i) s2.insert('z' - i); ft::set<char>::iterator prev_s1_it = s1.begin(); ft::set<char>::iterator prev_s2_it = s2.begin(); ft::set<char>::iterator tmp_it; s1.swap(s2); tmp_it = s2.begin(); for (ft::set<char>::iterator end = s2.end(); tmp_it != end; ++tmp_it, ++prev_s1_it) { EXPECT_EQ(prev_s1_it, tmp_it); EXPECT_EQ(*prev_s1_it, *tmp_it); } tmp_it = s1.begin(); for (ft::set<char>::iterator end = s1.end(); tmp_it != end; ++tmp_it, ++prev_s2_it) { EXPECT_EQ(prev_s2_it, tmp_it); EXPECT_EQ(*prev_s2_it, *tmp_it); } prev_s1_it = s1.begin(); ft::set<char> empty1; ft::set<char>::iterator prev_empty_it = empty1.begin(); ft::set<char>::iterator prev_empty_end = empty1.end(); empty1.swap(s1); tmp_it = empty1.begin(); for (ft::set<char>::iterator end = empty1.end(); tmp_it != end; ++tmp_it, ++prev_s1_it) { EXPECT_EQ(prev_s1_it, tmp_it); EXPECT_EQ(*prev_s1_it, *tmp_it); } EXPECT_NE(prev_empty_it, s1.begin()); EXPECT_NE(prev_empty_end, s1.end()); for (int i = 0; i < 10; ++i) s1.insert('a' + i); tmp_it = s1.begin(); for (int i = 0; i < 10; ++i, ++tmp_it) { EXPECT_EQ('a' + i, *tmp_it); } } TEST(Set, LookupCount) { ft::set<int> s; for (int i = 0; i < 10; ++i) s.insert(i); EXPECT_EQ(1, s.count(1)); EXPECT_EQ(0, s.count(42)); s.insert(42); EXPECT_EQ(1, s.count(42)); } TEST(Set, Lookupfind) { ft::set<int> s; for (int i = 1; i < 20; i *= 2) s.insert(i); ft::set<int>::iterator it = s.find(2); EXPECT_EQ(2, *it); it = s.find(3); EXPECT_EQ(s.end(), it); const ft::set<int> cs(s); ft::set<int>::const_iterator cit = cs.find(2); EXPECT_EQ(2, *cit); cit = cs.find(3); EXPECT_EQ(cs.end(), cit); } TEST(Set, LookupEqualRange) { // Non Const // std::pair<iterator,iterator> equal_range( const Key& key ); ft::set<int> s; for (int i = 0; i < 100; i += 10) s.insert(i); ft::pair<ft::set<int>::iterator, ft::set<int>::iterator> ret; ret = s.equal_range(-10); EXPECT_EQ(0, *ret.first); EXPECT_EQ(0, *ret.second); ret = s.equal_range(0); EXPECT_EQ(0, *ret.first); EXPECT_EQ(10, *ret.second); ret = s.equal_range(42); EXPECT_EQ(50, *ret.first); EXPECT_EQ(50, *ret.second); ret = s.equal_range(50); EXPECT_EQ(50, *ret.first); EXPECT_EQ(60, *ret.second); ret = s.equal_range(90); EXPECT_EQ(90, *ret.first); EXPECT_EQ(s.end(), ret.second); ret = s.equal_range(100); EXPECT_EQ(s.end(), ret.first); EXPECT_EQ(s.end(), ret.second); // Const // ft::pair<const_iterator, const_iterator> equal_range(const Key& key) // const; const ft::set<int> cs(s); ft::pair<ft::set<int>::const_iterator, ft::set<int>::const_iterator> cret; cret = cs.equal_range(-10); EXPECT_EQ(0, *cret.first); EXPECT_EQ(0, *cret.second); cret = cs.equal_range(0); EXPECT_EQ(0, *cret.first); EXPECT_EQ(10, *cret.second); cret = cs.equal_range(42); EXPECT_EQ(50, *cret.first); EXPECT_EQ(50, *cret.second); cret = cs.equal_range(50); EXPECT_EQ(50, *cret.first); EXPECT_EQ(60, *cret.second); cret = cs.equal_range(90); EXPECT_EQ(90, *cret.first); EXPECT_EQ(cs.end(), cret.second); cret = cs.equal_range(100); EXPECT_EQ(cs.end(), cret.first); EXPECT_EQ(cs.end(), cret.second); } TEST(Set, LookupLowerBound) { // Non const ft::set<int> s; for (int i = 0; i < 50; i += 10) s.insert(i); ft::set<int>::iterator it; it = s.lower_bound(0); EXPECT_EQ(0, *it); it = s.lower_bound(23); EXPECT_EQ(30, *it); it = s.lower_bound(53); EXPECT_TRUE(s.end() == it); // Const ft::set<int> cs = s; ft::set<int>::const_iterator cit; cit = cs.lower_bound(0); EXPECT_EQ(0, *cit); cit = s.lower_bound(23); EXPECT_EQ(30, *cit); cit = cs.lower_bound(53); EXPECT_TRUE(cs.end() == cit); } TEST(Set, LookupUpperBound) { // Non const // iterator upper_bound( const Key& key ); ft::set<int> s; for (int i = 0; i < 50; i += 10) s.insert(i); ft::set<int>::iterator it; it = s.upper_bound(-100); EXPECT_EQ(s.begin(), it); EXPECT_EQ(0, *it); it = s.upper_bound(10); EXPECT_EQ(20, *it); it = s.upper_bound(100); EXPECT_EQ(s.end(), it); // Const // const_iterator upper_bound( const Key& key ) const; const ft::set<int> cs(s); ft::set<int>::const_iterator cit; cit = cs.upper_bound(-100); EXPECT_EQ(cs.begin(), cit); EXPECT_EQ(0, *cit); cit = cs.upper_bound(10); EXPECT_EQ(20, *cit); cit = cs.upper_bound(100); EXPECT_EQ(cs.end(), cit); } TEST(Set, ObserversKeyComp) { { ft::set<int> s; ft::set<int>::key_compare comp; comp = s.key_comp(); EXPECT_TRUE(comp(1, 2)); EXPECT_FALSE(comp(2, 2)); EXPECT_FALSE(comp(3, 2)); } { ft::set<int, std::greater<int> > s; ft::set<int, std::greater<int> >::key_compare comp; comp = s.key_comp(); EXPECT_FALSE(comp(1, 2)); EXPECT_FALSE(comp(2, 2)); EXPECT_TRUE(comp(3, 2)); } { ft::set<std::string, std::less<std::string> > s; ft::set<std::string, std::less<std::string> >::key_compare comp; comp = s.key_comp(); EXPECT_TRUE(comp("abc", "xyz")); EXPECT_FALSE(comp("abc", "abc")); EXPECT_FALSE(comp("xyz", "abc")); } { ft::set<std::string, std::greater<std::string> > s; ft::set<std::string, std::greater<std::string> >::key_compare comp; comp = s.key_comp(); EXPECT_FALSE(comp("abc", "xyz")); EXPECT_FALSE(comp("abc", "abc")); EXPECT_TRUE(comp("xyz", "abc")); } } TEST(Set, ObserversValueComp) { { ft::set<int> s; ft::set<int>::value_compare comp; comp = s.key_comp(); EXPECT_TRUE(comp(1, 2)); EXPECT_FALSE(comp(2, 2)); EXPECT_FALSE(comp(3, 2)); } { ft::set<int, std::greater<int> > s; ft::set<int, std::greater<int> >::value_compare comp; comp = s.key_comp(); EXPECT_FALSE(comp(1, 2)); EXPECT_FALSE(comp(2, 2)); EXPECT_TRUE(comp(3, 2)); } { ft::set<std::string, std::less<std::string> > s; ft::set<std::string, std::less<std::string> >::value_compare comp; comp = s.key_comp(); EXPECT_TRUE(comp("abc", "xyz")); EXPECT_FALSE(comp("abc", "abc")); EXPECT_FALSE(comp("xyz", "abc")); } { ft::set<std::string, std::greater<std::string> > s; ft::set<std::string, std::greater<std::string> >::value_compare comp; comp = s.key_comp(); EXPECT_FALSE(comp("abc", "xyz")); EXPECT_FALSE(comp("abc", "abc")); EXPECT_TRUE(comp("xyz", "abc")); } } TEST(Set, NonMemberFunctionsLexicographical) { ft::set<int> s1; ft::set<int> s2; s1.insert(10); s2.insert(10); EXPECT_TRUE(s1 == s2); EXPECT_FALSE(s1 != s2); EXPECT_FALSE(s1 < s2); EXPECT_TRUE(s1 <= s2); EXPECT_FALSE(s1 > s2); EXPECT_TRUE(s1 >= s2); s2.insert(20); EXPECT_FALSE(s1 == s2); EXPECT_TRUE(s1 != s2); EXPECT_TRUE(s1 < s2); EXPECT_TRUE(s1 <= s2); EXPECT_FALSE(s1 > s2); EXPECT_FALSE(s1 >= s2); s1.insert(30); EXPECT_FALSE(s1 == s2); EXPECT_TRUE(s1 != s2); EXPECT_FALSE(s1 < s2); EXPECT_FALSE(s1 <= s2); EXPECT_TRUE(s1 > s2); EXPECT_TRUE(s1 >= s2); } TEST(Set, NonMemberFunctionsSwap) { ft::set<char> s1; for (int i = 0; i < 10; ++i) s1.insert('a' + i); ft::set<char> s2; for (int i = -10; i < -4; ++i) s2.insert('z' - i); ft::set<char>::iterator prev_s1_it = s1.begin(); ft::set<char>::iterator prev_s2_it = s2.begin(); ft::set<char>::iterator tmp_it; ft::swap(s1, s2); tmp_it = s2.begin(); for (ft::set<char>::iterator end = s2.end(); tmp_it != end; ++tmp_it, ++prev_s1_it) { EXPECT_EQ(prev_s1_it, tmp_it); EXPECT_EQ(*prev_s1_it, *tmp_it); } tmp_it = s1.begin(); for (ft::set<char>::iterator end = s1.end(); tmp_it != end; ++tmp_it, ++prev_s2_it) { EXPECT_EQ(prev_s2_it, tmp_it); EXPECT_EQ(*prev_s2_it, *tmp_it); } prev_s1_it = s1.begin(); ft::set<char> empty1; ft::set<char>::iterator prev_empty_it = empty1.begin(); ft::set<char>::iterator prev_empty_end = empty1.end(); ft::swap(empty1, s1); tmp_it = empty1.begin(); for (ft::set<char>::iterator end = empty1.end(); tmp_it != end; ++tmp_it, ++prev_s1_it) { EXPECT_EQ(prev_s1_it, tmp_it); EXPECT_EQ(*prev_s1_it, *tmp_it); } EXPECT_NE(prev_empty_it, s1.begin()); EXPECT_NE(prev_empty_end, s1.end()); for (int i = 0; i < 10; ++i) s1.insert('a' + i); tmp_it = s1.begin(); for (int i = 0; i < 10; ++i, ++tmp_it) { EXPECT_EQ('a' + i, *tmp_it); } }
27.152055
79
0.498007
public-jun
5148c105f61a8d9a40261bdc33f36e846b1d9c63
1,030
hpp
C++
src/controls/color_picker.hpp
AndrewGrim/Agro
f065920ab665938852bc8aa7e38d4d73f7e3ec0d
[ "MIT" ]
null
null
null
src/controls/color_picker.hpp
AndrewGrim/Agro
f065920ab665938852bc8aa7e38d4d73f7e3ec0d
[ "MIT" ]
null
null
null
src/controls/color_picker.hpp
AndrewGrim/Agro
f065920ab665938852bc8aa7e38d4d73f7e3ec0d
[ "MIT" ]
1
2021-04-18T12:06:55.000Z
2021-04-18T12:06:55.000Z
#pragma once #include "widget.hpp" #include "label.hpp" #include "line_edit.hpp" #define COLOR_PICKER_WIDTH 300 #define COLOR_PICKER_HEIGHT 200 class ColorPicker : public Widget { public: EventListener<Widget*, Color> onColorChanged = EventListener<Widget*, Color>(); ColorPicker(); ~ColorPicker(); virtual const char* name() override; virtual void draw(DrawingContext &dc, Rect rect, int state) override; virtual Size sizeHint(DrawingContext &dc) override; bool isLayout() override; int isFocusable() override; Widget* handleFocusEvent(FocusEvent event, State *state, FocusPropagationData data) override; Color color(); int m_cursor_width = 10; Color m_color = COLOR_NONE; Point m_position = Point(0, 0); TextureCoordinates m_coords; LineEdit *m_color_edit = nullptr; Label *m_color_label = nullptr; float *m_texture_data = new float[COLOR_PICKER_HEIGHT * COLOR_PICKER_WIDTH * 4]; };
32.1875
101
0.675728
AndrewGrim
514c8365dd9993283844233c553e94c886391f7a
1,453
cpp
C++
aws-cpp-sdk-lexv2-runtime/source/model/DialogAction.cpp
blinemedical/aws-sdk-cpp
c7c814b2d6862b4cb48f3fb3ac083a9e419674e8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-lexv2-runtime/source/model/DialogAction.cpp
blinemedical/aws-sdk-cpp
c7c814b2d6862b4cb48f3fb3ac083a9e419674e8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-lexv2-runtime/source/model/DialogAction.cpp
blinemedical/aws-sdk-cpp
c7c814b2d6862b4cb48f3fb3ac083a9e419674e8
[ "Apache-2.0" ]
null
null
null
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/lexv2-runtime/model/DialogAction.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace LexRuntimeV2 { namespace Model { DialogAction::DialogAction() : m_type(DialogActionType::NOT_SET), m_typeHasBeenSet(false), m_slotToElicitHasBeenSet(false) { } DialogAction::DialogAction(JsonView jsonValue) : m_type(DialogActionType::NOT_SET), m_typeHasBeenSet(false), m_slotToElicitHasBeenSet(false) { *this = jsonValue; } DialogAction& DialogAction::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("type")) { m_type = DialogActionTypeMapper::GetDialogActionTypeForName(jsonValue.GetString("type")); m_typeHasBeenSet = true; } if(jsonValue.ValueExists("slotToElicit")) { m_slotToElicit = jsonValue.GetString("slotToElicit"); m_slotToElicitHasBeenSet = true; } return *this; } JsonValue DialogAction::Jsonize() const { JsonValue payload; if(m_typeHasBeenSet) { payload.WithString("type", DialogActionTypeMapper::GetNameForDialogActionType(m_type)); } if(m_slotToElicitHasBeenSet) { payload.WithString("slotToElicit", m_slotToElicit); } return payload; } } // namespace Model } // namespace LexRuntimeV2 } // namespace Aws
19.118421
93
0.73159
blinemedical
5150a860afb3aa8901f132cbdf37307813c7e933
3,867
cc
C++
dash/test/meta/RangeTest.cc
RuhanDev/dash
c56193149c334e552df6f8439c3fb1510048b7f1
[ "BSD-3-Clause" ]
1
2019-05-19T20:31:20.000Z
2019-05-19T20:31:20.000Z
dash/test/meta/RangeTest.cc
RuhanDev/dash
c56193149c334e552df6f8439c3fb1510048b7f1
[ "BSD-3-Clause" ]
null
null
null
dash/test/meta/RangeTest.cc
RuhanDev/dash
c56193149c334e552df6f8439c3fb1510048b7f1
[ "BSD-3-Clause" ]
2
2019-10-02T23:19:22.000Z
2020-06-27T09:23:31.000Z
#include "RangeTest.h" #include <gtest/gtest.h> #include <dash/View.h> #include <dash/Array.h> #include <dash/Matrix.h> #include <dash/internal/StreamConversion.h> #include <array> #include <iterator> TEST_F(RangeTest, RangeTraits) { dash::Array<int> array(dash::size() * 10); auto v_sub = dash::sub(0, 10, array); auto i_sub = dash::index(v_sub); auto v_ssub = dash::sub(0, 5, (dash::sub(0, 10, array))); auto v_loc = dash::local(array); auto i_loc = dash::index(dash::local(array)); // auto v_gloc = dash::global(dash::local(array)); // auto i_glo = dash::global(dash::index(dash::local(array))); auto v_bsub = *dash::begin(dash::blocks(v_sub)); static_assert(dash::is_range< dash::Array<int> >::value == true, "dash::is_range<dash::Array>::value not matched"); static_assert(dash::is_range< typename dash::Array<int>::local_type >::value == true, "dash::is_range<dash::Array::local_type>::value not matched"); static_assert(dash::is_range< typename dash::Array<int>::iterator >::value == false, "dash::is_range<dash::Array<...>>::value not matched"); static_assert(dash::is_range<decltype(array)>::value == true, "range type trait for dash::Array not matched"); static_assert(dash::is_range<decltype(v_loc)>::value == true, "range type trait for local(dash::Array) not matched"); static_assert(dash::is_range<decltype(v_sub)>::value == true, "range type trait for sub(dash::Array) not matched"); static_assert(dash::is_range<decltype(v_ssub)>::value == true, "range type trait for sub(sub(dash::Array)) not matched"); static_assert(dash::is_range<decltype(v_bsub)>::value == true, "range type trait for begin(blocks(sub(dash::Array))) " "not matched"); static_assert(dash::is_range<decltype(i_sub)>::value == true, "range type trait for index(sub(dash::Array)) not matched"); static_assert(dash::is_range<decltype(i_loc)>::value == true, "range type trait for index(local(dash::Array)) not matched"); // Index set iterators implement random access iterator concept: // static_assert(std::is_same< typename std::iterator_traits< decltype(i_sub.begin()) >::iterator_category, std::random_access_iterator_tag >::value == true, "iterator trait iterator_category of " "index(local(dash::Array))::iterator not matched"); static_assert(std::is_same< typename std::iterator_traits< decltype(i_loc.begin()) >::iterator_category, std::random_access_iterator_tag >::value == true, "iterator trait iterator_category of " "index(local(dash::Array))::iterator not matched"); //static_assert(std::is_same< // typename std::iterator_traits< // decltype(i_glo.begin()) // >::iterator_category, // std::random_access_iterator_tag // >::value == true, // "iterator trait iterator_category of " // "global(index(local(dash::Array)))::iterator not matched"); static_assert( dash::is_range<decltype(array)>::value == true, "dash::is_range<dash::Array<...>>::value not matched"); auto l_range = dash::make_range(array.local.begin(), array.local.end()); static_assert( dash::is_range<decltype(l_range)>::value == true, "dash::is_range<dash::make_range(...)>::value not matched"); }
39.865979
78
0.57564
RuhanDev
51519fac19dcbe9973762850e55c65a79c3c9ff2
1,550
cpp
C++
src/efscape/utils/type.cpp
clinejc/efscape
ef8bbf272827c7b364aa02af33dc5d239f070e0b
[ "0BSD" ]
1
2019-07-29T07:44:13.000Z
2019-07-29T07:44:13.000Z
src/efscape/utils/type.cpp
clinejc/efscape
ef8bbf272827c7b364aa02af33dc5d239f070e0b
[ "0BSD" ]
null
null
null
src/efscape/utils/type.cpp
clinejc/efscape
ef8bbf272827c7b364aa02af33dc5d239f070e0b
[ "0BSD" ]
1
2019-07-11T10:49:48.000Z
2019-07-11T10:49:48.000Z
// __COPYRIGHT_START__ // Package Name : efscape // File Name : type.cpp // Copyright (C) 2006-2018 Jon C. Cline // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. // __COPYRIGHT_END__ #include <efscape/utils/type.hpp> #ifdef __GNUG__ #include <cstdlib> #include <memory> #include <cxxabi.h> namespace efscape { namespace utils { struct handle { char* p; handle(char* ptr) : p(ptr) { } ~handle() { std::free(p); } }; std::string demangle(const char* name) { int status = -4; // some arbitrary value to eliminate the compiler warning handle result( abi::__cxa_demangle(name, NULL, NULL, &status) ); return (status==0) ? result.p : name ; } } } #else namespace efscape { namespace utils { // does nothing if not g++ std::string demangle(const char* name) { return name; } } } #endif
27.678571
158
0.694194
clinejc
51594205af499ec87806554cc33848bb3ce7283d
1,124
cpp
C++
dbus-cxx/standard-interfaces/peerinterfaceproxy.cpp
tvladax/dbus-cxx
396041a2130985acd72bb801b7137ec06e04b161
[ "BSD-3-Clause" ]
null
null
null
dbus-cxx/standard-interfaces/peerinterfaceproxy.cpp
tvladax/dbus-cxx
396041a2130985acd72bb801b7137ec06e04b161
[ "BSD-3-Clause" ]
null
null
null
dbus-cxx/standard-interfaces/peerinterfaceproxy.cpp
tvladax/dbus-cxx
396041a2130985acd72bb801b7137ec06e04b161
[ "BSD-3-Clause" ]
null
null
null
// SPDX-License-Identifier: LGPL-3.0-or-later OR BSD-3-Clause /*************************************************************************** * Copyright (C) 2020 by Robert Middleton * * robert.middleton@rm5248.com * * * * This file is part of the dbus-cxx library. * ***************************************************************************/ #include "peerinterfaceproxy.h" using DBus::PeerInterfaceProxy; PeerInterfaceProxy::PeerInterfaceProxy() : DBus::InterfaceProxy( DBUS_CXX_PEER_INTERFACE ){ m_ping_method = this->create_method<void()>( "Ping" ); m_get_machine_method = this->create_method<std::string()>( "GetMachineId" ); } std::shared_ptr<PeerInterfaceProxy> PeerInterfaceProxy::create(){ return std::shared_ptr<PeerInterfaceProxy>( new PeerInterfaceProxy() ); } void PeerInterfaceProxy::Ping(){ (*m_ping_method)(); } std::string PeerInterfaceProxy::GetMachineId(){ return (*m_get_machine_method)(); }
37.466667
80
0.513345
tvladax
515aaa5bb2e69a154d85f4fdd3dc3f16729dcffa
403
cpp
C++
Dataset/Leetcode/train/62/677.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/62/677.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/62/677.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: int XXX(int m, int n) { if(m==1||n==1) return 1; vector<vector<int>> v(m,vector<int>(n,0)); v[0][1]=1; v[1][0]=1; for(int i=0;i<m;i++){ for(int ii=0;ii<n;ii++){ if(i-1>=0) v[i][ii]+=v[i-1][ii]; if(ii-1>=0) v[i][ii]+=v[i][ii-1]; } } return v[m-1][n-1]; } };
22.388889
50
0.364764
kkcookies99
515b7518098672ff18f2ff1ec2ade048038696b1
2,540
cpp
C++
src/xray/editor/world/sources/command_delete_object.cpp
ixray-team/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
3
2021-10-30T09:36:14.000Z
2022-03-26T17:00:06.000Z
src/xray/editor/world/sources/command_delete_object.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
null
null
null
src/xray/editor/world/sources/command_delete_object.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:08.000Z
2022-03-26T17:00:08.000Z
//////////////////////////////////////////////////////////////////////////// // Created : 02.04.2009 // Author : Armen Abroyan // Copyright (C) GSC Game World - 2009 //////////////////////////////////////////////////////////////////////////// #include "pch.h" #include "command_delete_object.h" #include "level_editor.h" #include "tool_base.h" #include "object_base.h" #include "project.h" #include "command_select.h" #include "project_items.h" namespace xray { namespace editor { command_delete_selected_objects::command_delete_selected_objects( level_editor^ le ): m_level_editor(le) { } bool command_delete_selected_objects::commit () { id_list^ ids = gcnew id_list; object_list objects = m_level_editor->get_project()->selection_list(); for each(object_base^ o in objects) ids->Add( o->id() ); m_level_editor->get_command_engine()->run( gcnew command_select(m_level_editor) ); return m_level_editor->get_command_engine()->run( gcnew command_delete_object_impl(m_level_editor, ids )); } command_delete_object::command_delete_object( level_editor^ le, int id ): m_level_editor ( le ), m_id ( id ) { } bool command_delete_object::commit () { m_level_editor->get_command_engine()->run( gcnew command_select(m_level_editor) ); id_list^ ids = gcnew id_list; ids->Add ( m_id ); return m_level_editor->get_command_engine()->run( gcnew command_delete_object_impl(m_level_editor, ids )); } command_delete_object_impl::command_delete_object_impl (level_editor^ le, id_list^ objects_id ): m_level_editor ( le ) { m_ids = objects_id; m_objects = gcnew object_list; m_configs = NEW (configs::lua_config_ptr)(); *m_configs = configs::create_lua_config( "d:\\asd.lua"); } command_delete_object_impl::~command_delete_object_impl() { DELETE (m_configs); } bool command_delete_object_impl::commit () { xray::configs::lua_config_value value = (*m_configs)->get_root(); u32 index = 0; id_list^ idlist = m_ids; for each (System::UInt32^ it in idlist) { object_base^ o = object_base::object_by_id(*it); m_objects->Add (o); m_level_editor->get_project()->save_to_config(value, o, true ); m_level_editor->get_project()->remove_item( o->m_owner_project_item, true ); ++index; } return true; } void command_delete_object_impl::rollback () { configs::lua_config_value value = (*m_configs)->get_root(); m_level_editor->get_project()->load( value, true ); } }// namespace editor }// namespace xray
26.736842
108
0.666929
ixray-team
5160a119e018d97e0d7c700ff5632049d9c9de36
447
cpp
C++
nhn_next_gameserver_lab_2017_IocpServer/Samples/ObjectPoolTest/main.cpp
jacking75/Netowrok_Projects
7788a9265818db6d781620fd644124aca425fe3c
[ "MIT" ]
25
2019-05-20T08:07:39.000Z
2021-08-17T11:25:02.000Z
nhn_next_gameserver_lab_2017_IocpServer/Samples/ObjectPoolTest/main.cpp
jacking75/Netowrok_Projects
7788a9265818db6d781620fd644124aca425fe3c
[ "MIT" ]
null
null
null
nhn_next_gameserver_lab_2017_IocpServer/Samples/ObjectPoolTest/main.cpp
jacking75/Netowrok_Projects
7788a9265818db6d781620fd644124aca425fe3c
[ "MIT" ]
17
2019-07-07T12:20:16.000Z
2022-01-11T08:27:44.000Z
#include <iostream> #include <vector> #include "ClientSession.h" int main() { std::vector<ClientSession*> sessions; for (int i = 0; i < 3; ++i) { auto session = new ClientSession(); sessions.push_back(session); } for (int i = 0; i < 3; ++i) { delete sessions[i]; } sessions.clear(); for (int i = 0; i < 3; ++i) { auto session = new ClientSession(); sessions.push_back(session); } return 0; }
15.413793
39
0.572707
jacking75
51615861ba867c2962b7b31451910795c6ca3751
3,290
cpp
C++
src/Map/CompressionTools.cpp
Lexicality/Wulf2012
5bcf42797e6fb0db16107ab134e8b977fc99daed
[ "MIT" ]
6
2015-01-06T13:04:52.000Z
2020-04-21T05:50:01.000Z
src/Map/CompressionTools.cpp
Lexicality/Wulf2012
5bcf42797e6fb0db16107ab134e8b977fc99daed
[ "MIT" ]
null
null
null
src/Map/CompressionTools.cpp
Lexicality/Wulf2012
5bcf42797e6fb0db16107ab134e8b977fc99daed
[ "MIT" ]
null
null
null
// // WulfGame/Map/CompressionTools.cpp // Copyright (C) 2012 Lexi Robinson // This code is freely available under the MIT licence. // #include "Map/CompressionTools.h" #include <stdexcept> using Wulf::word; using Wulf::byte; using namespace Wulf; word LEconcat(byte low, byte high); static const byte NEARTAG = 0xA7; static const byte FARTAG = 0xA8; typedef std::vector<byte>::const_iterator byte_itr; typedef std::vector<word>::const_iterator word_itr; std::vector<word> CompressionTools::CarmackExpand(const std::vector<byte>& rawdata) { /* This is a series of two byte numbers. The first two byte number is the number of uncompressed bytes we will end up with. The rest are compressed dat awith occasional missfits: Every so often, a three byte number will turn up in the form xx A7 yy. If xx is 0, the number is the two byte number yyA7. Otherwise, this means "Repeat 0xXX two byte numbers from the uncompressed data, starting 0xYY numbers ago." Sometimes you will also get four byte numbers in the form xx A8 yy yy. If xx is 0, it is only a three byte number, the same as 00A7 but now 00A8. Otherwise, this is "repeat 0xXX numbers from the uncompressed data, starting 0xYYYY numbers from the start." Easy peasy */ if (rawdata.size() < 2) throw std::runtime_error("Not enough raw data!"); std::vector<word> output; byte_itr itr = rawdata.begin(); byte_itr end = rawdata.end(); word length = LEconcat(*itr++, *itr++); if (length == 0) return output; output.reserve(length / 2); byte lowbyte = 0; byte highbyte = 0; bool getlower = true; for (; itr < end; ++itr) { if (getlower) { // low byte not got lowbyte = *itr; getlower = false; } else { getlower = true; highbyte = *itr; if (highbyte == NEARTAG) { byte ptr = *++itr; if (lowbyte == 0) { output.push_back(LEconcat(ptr, highbyte)); continue; } word_itr outdata = output.end() - ptr; while (lowbyte-- > 0) output.push_back(*outdata++); } else if (highbyte == FARTAG) { byte lptr = *++itr; if (lowbyte == 0) { output.push_back(LEconcat(lptr, highbyte)); continue; } word ptr = LEconcat(lptr, *++itr); word_itr outdata = output.begin() + ptr; while (lowbyte-- > 0) output.push_back(*outdata++); } else { output.push_back(LEconcat(lowbyte, highbyte)); } } } return output; } std::vector<word> CompressionTools::RLEWExpand(const std::vector<word>& data, const word tag) { /* This is RLEW. It's very simple 1) Read a word 2) Is it the tag? NO: Add it to the output and restart YES: Read the next two words. Add word #2 to the output word #1 times and restart Simple eh? */ if (data.size() < 2) throw std::runtime_error("Not enough data!"); std::vector<word> output; word_itr itr = data.begin(); word_itr end = data.end(); word size = *itr++; if (size == 0) return std::vector<word>(); output.reserve(size); for (; itr < end; ++itr) { word cword = *itr; if (cword == tag) { word reps = *++itr; word data = *++itr; while (reps-- > 0) output.push_back(data); } else { output.push_back(cword); } } return output; } // Little endian concatination. inline word LEconcat(byte low, byte high) { return low | high << 8; }
24.37037
93
0.660486
Lexicality
5162729d357122aa639de9b836496c5469f72068
2,113
cpp
C++
test/training_data/plag_original_codes/abc037_c_6420655_827.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
13
2021-01-20T19:53:16.000Z
2021-11-14T16:30:32.000Z
test/training_data/plag_original_codes/abc037_c_6420655_827.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
null
null
null
test/training_data/plag_original_codes/abc037_c_6420655_827.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
null
null
null
/* 引用元:https://atcoder.jp/contests/abc037/tasks/abc037_c C - 総和Editorial // ソースコードの引用元 : https://atcoder.jp/contests/abc037/submissions/6420655 // 提出ID : 6420655 // 問題ID : abc037_c // コンテストID : abc037 // ユーザID : xryuseix // コード長 : 1857 // 実行時間 : 11 */ #include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <vector> #include <list> #include <set> #include <map> #include <queue> #include <stack> #include <cctype> #include <climits> #include <string> #include <bitset> using namespace std; typedef long double ld; typedef long long int ll; typedef unsigned long long int ull; typedef vector<int> vi; typedef vector<char> vc; typedef vector<string> vs; typedef vector<ll> vll; typedef vector<pair<int, int>> vpii; typedef vector<vector<int>> vvi; typedef vector<vector<char>> vvc; typedef vector<vector<string>> vvs; typedef vector<vector<ll>> vvll; #define rep(i, n) for (int i = 0; i < (n); ++i) #define rrep(i, n) for (int i = 1; i <= (n); ++i) #define drep(i, n) for (int i = (n)-1; i >= 0; --i) #define fin(ans) cout << (ans) << endl #define STI(s) atoi(s.c_str()) #define mp(p, q) make_pair(p, q) #define pb(n) push_back(n) #define Sort(a) sort(a.begin(), a.end()) #define Rort(a) sort(a.rbegin(), a.rend()) template <class T> inline bool chmax(T &a, T b) { if (a < b) { a = b; return 1; } return 0; } template <class T> inline bool chmin(T &a, T b) { if (a > b) { a = b; return 1; } return 0; } const int P = 1000000007; const int INF = INT_MAX; const ll LLINF = 1LL << 60; // g++ -std=c++1z temp.cpp //./a.out int main(void) { ios::sync_with_stdio(false); cin.tie(0); ////////////////////////////////////////////////////// ll n, k; cin >> n >> k; vll v(n), w(n, INF); rep(i, n) cin >> v[i]; ll ans = 0; ll l = 1, r = k; ll sum = 0; for (int i = 0; i < k; i++) { sum += v[i]; } ans += sum; // fin(ans); for (int i = 1; r < n; i++) { sum += v[r]; r++; sum -= v[l - 1]; l++; ans += sum; // fin(ans); } fin(ans); ////////////////////////////////////////////////////// return 0; }
20.920792
70
0.563654
xryuseix
516441de661be2abaab3cbf612dac08b81f2820d
11,487
cpp
C++
libRaftExt/protobuffer/RaftProtoBufferSerializer.cpp
ZhenYongFan/libRaft
7da0b124d9eed800bebaff39b01c9d1ae36c1ccd
[ "Apache-2.0" ]
4
2019-08-21T06:32:36.000Z
2021-12-16T09:30:48.000Z
libRaftExt/protobuffer/RaftProtoBufferSerializer.cpp
ZhenYongFan/libRaft
7da0b124d9eed800bebaff39b01c9d1ae36c1ccd
[ "Apache-2.0" ]
1
2019-08-20T07:11:42.000Z
2019-08-26T00:03:22.000Z
libRaftExt/protobuffer/RaftProtoBufferSerializer.cpp
ZhenYongFan/libRaft
7da0b124d9eed800bebaff39b01c9d1ae36c1ccd
[ "Apache-2.0" ]
2
2020-03-09T06:03:02.000Z
2021-02-03T03:21:57.000Z
#include "stdafx.h" #include "RaftProtoBufferSerializer.h" #include "raft.pb.h" #include "rpc.pb.h" #include <RaftEntry.h> #include <RequestOp.h> void LocalToPb(const CRaftEntry &entry, raftpb::Entry &entryPb) { entryPb.set_term(entry.m_u64Term); entryPb.set_index(entry.m_u64Index); entryPb.set_type(raftpb::EntryType(entry.m_eType)); entryPb.set_data(entry.m_strData); } void LocalToPb(const CConfState &stateConf, raftpb::ConfState &stateConfPb) { for (int nIndex = 0; nIndex < stateConf.m_nNum; nIndex++) stateConfPb.add_nodes(stateConf.m_pnNodes[nIndex]); } void LocalToPb(const CSnapshotMetadata &metaDat, raftpb::SnapshotMetadata &metaDatPb) { metaDatPb.set_index(metaDat.m_u64Index); metaDatPb.set_term(metaDat.m_u64Term); raftpb::ConfState* pConfStatePb = metaDatPb.mutable_conf_state(); LocalToPb(metaDat.m_stateConf, *pConfStatePb); } void LocalToPb(const CSnapshot &snapshot, raftpb::Snapshot &snapshotPb) { if (snapshot.m_u32DatLen > 0) snapshotPb.set_data(std::string((char *)snapshot.m_pData, snapshot.m_u32DatLen)); raftpb::SnapshotMetadata * pMetaData = snapshotPb.mutable_metadata(); LocalToPb(snapshot.m_metaDat, *pMetaData); } void LocalToPb(const CMessage &msg, raftpb::Message &msgPb) { msgPb.set_index(msg.m_u64Index); msgPb.set_commit(msg.m_u64Committed); msgPb.set_context(msg.m_strContext); msgPb.set_from(msg.m_nFromID); msgPb.set_logterm(msg.m_u64LogTerm); msgPb.set_reject(msg.m_bReject); msgPb.set_rejecthint(msg.m_u64RejectHint); msgPb.set_term(msg.m_u64Term); msgPb.set_to(msg.m_nToID); msgPb.set_type(raftpb::MessageType(msg.m_typeMsg)); raftpb::Snapshot *pSnapshot = msgPb.mutable_snapshot(); if (NULL != pSnapshot) LocalToPb(msg.m_snapshotLog, *pSnapshot); for (int nIndex = 0 ; nIndex < msg.m_nEntryNum ; nIndex ++) { raftpb::Entry *pEntry = msgPb.add_entries(); LocalToPb(msg.m_pEntry[nIndex], *pEntry); } } void LocalToPb(const CConfChange &conf, raftpb::ConfChange &confPb) { confPb.set_id(conf.m_nID); confPb.set_nodeid(conf.m_nRaftID); confPb.set_type(raftpb::ConfChangeType(conf.m_typeChange)); if (conf.m_u32Len > 0) confPb.set_context(std::string((char *)conf.m_pContext, conf.m_u32Len)); } void PbToLocal(const raftpb::Entry &entryPb, CRaftEntry &entry) { entry.set_term(entryPb.term()); entry.set_index(entryPb.index()); entry.set_type(CRaftEntry::EType(entryPb.type())); entry.set_data(entryPb.data()); } void PbToLocal(const raftpb::ConfState &stateConfPb,CConfState &stateConf) { for (int nIndex = 0; nIndex < stateConfPb.nodes_size(); nIndex++) stateConf.add_nodes(stateConfPb.nodes(nIndex)); } void PbToLocal(const raftpb::SnapshotMetadata &metaDatPb, CSnapshotMetadata &metaDat) { metaDat.set_index(metaDatPb.index()); metaDat.set_term(metaDatPb.term()); if(metaDatPb.has_conf_state()) PbToLocal(metaDatPb.conf_state(), metaDat.m_stateConf); } void PbToLocal(const raftpb::Snapshot &snapshotPb, CSnapshot &snapshot) { snapshot.set_data(snapshotPb.data()); if (snapshotPb.has_metadata()) PbToLocal(snapshotPb.metadata(), snapshot.m_metaDat); } void PbToLocal(const raftpb::Message &msgPb, CMessage &msg) { msg.set_index(msgPb.index()); msg.set_commit(msgPb.commit()); msg.set_context(msgPb.context()); msg.set_from(msgPb.from()); msg.set_logterm(msgPb.logterm()); msg.set_reject(msgPb.reject()); msg.set_rejecthint(msgPb.rejecthint()); msg.set_term(msgPb.term()); msg.set_to(msgPb.to()); msg.set_type(CMessage::EMessageType(msgPb.type())); if (msgPb.has_snapshot()) PbToLocal(msgPb.snapshot(), msg.m_snapshotLog); if (msgPb.entries_size() > 0) { msg.m_nEntryNum = msgPb.entries_size(); msg.m_pEntry = new CRaftEntry[msg.m_nEntryNum]; for (int nIndex = 0; nIndex < msgPb.entries_size(); nIndex++) PbToLocal(msgPb.entries(nIndex), msg.m_pEntry[nIndex]); } } void PbToLocal(const raftpb::ConfChange &confPb, CConfChange &conf) { conf.set_id(confPb.id()); conf.set_nodeid(confPb.nodeid()); conf.set_type(CConfChange::EConfChangeType(confPb.type())); conf.set_context(confPb.context()); } void RequestOpLocalToPb(const CRequestOp &opRequest, raftserverpb::RequestOp &opRequestPb) { opRequestPb.set_clientid(opRequest.clientid()); opRequestPb.set_subsessionid(opRequest.subsessionid()); if (opRequest.has_request_delete_range()) { raftserverpb::DeleteRangeRequest* pRequest = opRequestPb.mutable_request_delete_range(); const CDeleteRangeRequest &request = opRequest.request_delete_range(); pRequest->set_key(request.key()); } else if (opRequest.has_request_put()) { raftserverpb::PutRequest* pRequest = opRequestPb.mutable_request_put(); const CPutRequest &request = opRequest.request_put(); pRequest->set_key(request.key()); pRequest->set_value(request.value()); } else if (opRequest.has_request_range()) { raftserverpb::RangeRequest* pRequest = opRequestPb.mutable_request_range(); const CRangeRequest &request = opRequest.request_range(); pRequest->set_key(request.key()); } } void RequestOpPbToLocal(const raftserverpb::RequestOp &opRequestPb, CRequestOp &opRequest) { opRequest.set_clientid(opRequestPb.clientid()); opRequest.set_subsessionid(opRequestPb.subsessionid()); if (opRequestPb.has_request_delete_range()) { CDeleteRangeRequest* pRequest = opRequest.mutable_request_delete_range(); const raftserverpb::DeleteRangeRequest &request = opRequestPb.request_delete_range(); pRequest->set_key(request.key()); } else if (opRequestPb.has_request_put()) { CPutRequest* pRequest = opRequest.mutable_request_put(); const raftserverpb::PutRequest &request = opRequestPb.request_put(); pRequest->set_key(request.key()); pRequest->set_value(request.value()); } else if (opRequestPb.has_request_range()) { CRangeRequest* pRequest = opRequest.mutable_request_range(); const raftserverpb::RangeRequest &request = opRequestPb.request_range(); pRequest->set_key(request.key()); } } void ResponseOpLocalToPb(const CResponseOp &opResponse, raftserverpb::ResponseOp &opResponsePb) { opResponsePb.set_errorno(opResponse.errorno()); opResponsePb.set_subsessionid(opResponse.subsessionid()); if (opResponse.has_response_delete_range()) { raftserverpb::DeleteRangeResponse* pResponse = opResponsePb.mutable_response_delete_range(); const CDeleteRangeResponse &response = opResponse.response_delete_range(); } else if (opResponse.has_response_put()) { raftserverpb::PutResponse* pResponse = opResponsePb.mutable_response_put(); const CPutResponse &response = opResponse.response_put(); } else if (opResponse.has_response_range()) { raftserverpb::RangeResponse* pResponse = opResponsePb.mutable_response_range(); const CRangeResponse &response = opResponse.response_range(); const std::list<CKeyValue *> &listKeyvalues = response.GetKeyValues(); for (auto pKeyValue : listKeyvalues) { raftserverpb::KeyValue* pPbKeyValue = pResponse->add_kvs(); pPbKeyValue->set_key(pKeyValue->key()); pPbKeyValue->set_value(pKeyValue->value()); } } } void ResponseOpPbToLocal(const raftserverpb::ResponseOp &opResponsePb, CResponseOp &opResponse) { opResponse.set_errorno(opResponsePb.errorno()); opResponse.set_subsessionid(opResponsePb.subsessionid()); if (opResponsePb.has_response_delete_range()) { CDeleteRangeResponse* pResponse = opResponse.mutable_response_delete_range(); const raftserverpb::DeleteRangeResponse &response = opResponsePb.response_delete_range(); } else if (opResponsePb.has_response_put()) { CPutResponse* pResponse = opResponse.mutable_response_put(); const raftserverpb::PutResponse &response = opResponsePb.response_put(); } else if (opResponsePb.has_response_range()) { CRangeResponse* pResponse = opResponse.mutable_response_range(); const raftserverpb::RangeResponse &response = opResponsePb.response_range(); for (int nIndex = 0 ; nIndex < response.kvs_size(); nIndex ++) { const raftserverpb::KeyValue &keyValue = response.kvs(nIndex); CKeyValue* pKeyValue = pResponse->add_kvs(); pKeyValue->set_key(keyValue.key()); pKeyValue->set_value(keyValue.value()); } } } CRaftProtoBufferSerializer::CRaftProtoBufferSerializer() { } CRaftProtoBufferSerializer::~CRaftProtoBufferSerializer() { } size_t CRaftProtoBufferSerializer::ByteSize(const CRaftEntry &entry) const { raftpb::Entry entryPb; LocalToPb(entry, entryPb); return entryPb.ByteSize(); } void CRaftProtoBufferSerializer::SerializeEntry(const CRaftEntry &entry, std::string &strValue) { raftpb::Entry entryPb; LocalToPb(entry, entryPb); strValue = entryPb.SerializeAsString(); } bool CRaftProtoBufferSerializer::ParseEntry(CRaftEntry &entry, const std::string &strValue) { raftpb::Entry entryPb; bool bParse = entryPb.ParseFromString(strValue); if (bParse) PbToLocal(entryPb, entry); return bParse; } void CRaftProtoBufferSerializer::SerializeMessage(const CMessage &msg, std::string &strValue) { raftpb::Message msgPb; LocalToPb(msg, msgPb); strValue = msgPb.SerializeAsString(); } bool CRaftProtoBufferSerializer::ParseMessage(CMessage &msg, const std::string &strValue) { raftpb::Message msgPb; bool bParse = msgPb.ParseFromString(strValue); if (bParse) PbToLocal(msgPb, msg); return bParse; } void CRaftProtoBufferSerializer::SerializeConfChangee(const CConfChange &conf, std::string &strValue) { raftpb::ConfChange confPb; LocalToPb(conf, confPb); strValue = confPb.SerializeAsString(); } bool CRaftProtoBufferSerializer::ParseConfChange(CConfChange &conf, const std::string &strValue) { raftpb::ConfChange confPb; bool bParse = confPb.ParseFromString(strValue); if (bParse) PbToLocal(confPb, conf); return bParse; } void CRaftProtoBufferSerializer::SerializeRequestOp(const CRequestOp &opRequest, std::string &strValue) { raftserverpb::RequestOp opRequestPb; RequestOpLocalToPb(opRequest, opRequestPb); strValue = opRequestPb.SerializeAsString(); } bool CRaftProtoBufferSerializer::ParseRequestOp(CRequestOp &opRequest, const std::string &strValue) { raftserverpb::RequestOp opRequestPb; bool bParse = opRequestPb.ParseFromString(strValue); if (bParse) RequestOpPbToLocal(opRequestPb, opRequest); return bParse; } void CRaftProtoBufferSerializer::SerializeResponseOp(const CResponseOp &opResponse, std::string &strValue) { raftserverpb::ResponseOp opResponsePb; ResponseOpLocalToPb(opResponse, opResponsePb); strValue = opResponsePb.SerializeAsString(); } bool CRaftProtoBufferSerializer::ParseResponseOp(CResponseOp &opResponse, const std::string &strValue) { raftserverpb::ResponseOp opResponsePb; bool bParse = opResponsePb.ParseFromString(strValue); if (bParse) ResponseOpPbToLocal(opResponsePb, opResponse); return bParse; }
34.809091
106
0.716984
ZhenYongFan
5164704f47f0e300f549eb6be63bc4f345237968
9,796
cpp
C++
fboss/agent/hw/bcm/BcmPortIngressBufferManager.cpp
TomMD/fboss
30654277076e1f1f50c9b756e9690737dc1476e0
[ "BSD-3-Clause" ]
null
null
null
fboss/agent/hw/bcm/BcmPortIngressBufferManager.cpp
TomMD/fboss
30654277076e1f1f50c9b756e9690737dc1476e0
[ "BSD-3-Clause" ]
null
null
null
fboss/agent/hw/bcm/BcmPortIngressBufferManager.cpp
TomMD/fboss
30654277076e1f1f50c9b756e9690737dc1476e0
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/hw/bcm/BcmPortIngressBufferManager.h" #include "fboss/agent/hw/bcm/BcmCosQueueFBConvertors.h" #include "fboss/agent/hw/bcm/BcmError.h" #include "fboss/agent/hw/bcm/BcmPlatform.h" #include "fboss/agent/hw/bcm/BcmSwitch.h" #include "fboss/agent/state/Port.h" #include <folly/logging/xlog.h> extern "C" { #include <bcm/cosq.h> #include <bcm/types.h> } namespace { // defaults in mmu_lossless=1 mode constexpr bcm_cosq_control_drop_limit_alpha_value_t kDefaultPgAlpha = bcmCosqControlDropLimitAlpha_8; constexpr int kDefaultPortPgId = 0; constexpr int kDefaultMinLimitBytes = 0; constexpr int kDefaultHeadroomLimitBytes = 0; constexpr int kdefaultResumeOffsetBytes = 0; } // unnamed namespace namespace facebook::fboss { BcmPortIngressBufferManager::BcmPortIngressBufferManager( BcmSwitch* hw, const std::string& portName, bcm_gport_t portGport) : hw_(hw), portName_(portName), gport_(portGport), unit_(hw_->getUnit()) {} void BcmPortIngressBufferManager::writeCosqTypeToHw( const int cosq, const bcm_cosq_control_t type, const int value, const std::string& typeStr) { auto rv = bcm_cosq_control_set(unit_, gport_, cosq, type, value); bcmCheckError( rv, "failed to set ", typeStr, " for port ", portName_, " cosq ", cosq, " value ", value); } void BcmPortIngressBufferManager::readCosqTypeFromHw( const int cosq, const bcm_cosq_control_t type, int* value, const std::string& typeStr) { *value = 0; auto rv = bcm_cosq_control_get(unit_, gport_, cosq, type, value); bcmCheckError( rv, "failed to get ", typeStr, " for port ", portName_, " cosq ", cosq); } void BcmPortIngressBufferManager::programPg( const PortPgConfig* portPgCfg, const int cosq) { int sharedDynamicEnable = 1; const auto& scalingFactor = portPgCfg->getScalingFactor(); XLOG(DBG2) << "Program port PG config for cosq: " << cosq << " on port: " << portName_; if (!scalingFactor) { sharedDynamicEnable = 0; } writeCosqTypeToHw( cosq, bcmCosqControlIngressPortPGSharedDynamicEnable, sharedDynamicEnable, "bcmCosqControlIngressPortPGSharedDynamicEnable"); if (sharedDynamicEnable) { auto alpha = utility::cfgAlphaToBcmAlpha(*scalingFactor); writeCosqTypeToHw( cosq, bcmCosqControlDropLimitAlpha, alpha, "bcmCosqControlDropLimitAlpha"); } int pgMinLimitBytes = portPgCfg->getMinLimitBytes(); writeCosqTypeToHw( cosq, bcmCosqControlIngressPortPGMinLimitBytes, pgMinLimitBytes, "bcmCosqControlIngressPortPGMinLimitBytes"); auto hdrmBytes = portPgCfg->getHeadroomLimitBytes(); int headroomBytes = hdrmBytes ? *hdrmBytes : 0; writeCosqTypeToHw( cosq, bcmCosqControlIngressPortPGHeadroomLimitBytes, headroomBytes, "bcmCosqControlIngressPortPGHeadroomLimitBytes"); auto resumeBytes = portPgCfg->getResumeOffsetBytes(); if (resumeBytes) { writeCosqTypeToHw( cosq, bcmCosqControlIngressPortPGResetOffsetBytes, *resumeBytes, "bcmCosqControlIngressPortPGResetOffsetBytes"); } } void BcmPortIngressBufferManager::resetPgToDefault(int pgId) { const auto& portPg = getDefaultPgSettings(); programPg(&portPg, pgId); } void BcmPortIngressBufferManager::resetPgsToDefault() { XLOG(DBG2) << "Reset all programmed PGs to default for port " << portName_; auto pgIdList = getPgIdListInHw(); for (const auto& pgId : pgIdList) { resetPgToDefault(pgId); } pgIdList.clear(); setPgIdListInHw(pgIdList); } void BcmPortIngressBufferManager::reprogramPgs( const std::shared_ptr<Port> port) { PgIdSet newPgList = {}; const auto portPgCfgs = port->getPortPgConfigs(); const auto pgIdList = getPgIdListInHw(); if (portPgCfgs) { for (const auto& portPgCfg : *portPgCfgs) { programPg(portPgCfg.get(), portPgCfg->getID()); newPgList.insert(portPgCfg->getID()); } // find pgs in original list but not in new list // so we know which ones to reset PgIdSet resetPgList; std::set_difference( pgIdList.begin(), pgIdList.end(), newPgList.begin(), newPgList.end(), std::inserter(resetPgList, resetPgList.end())); for (const auto pg : resetPgList) { XLOG(DBG2) << "Reset PG " << pg << " to default for port " << portName_; resetPgToDefault(pg); } } // update to latest PG list setPgIdListInHw(newPgList); XLOG(DBG2) << "New PG list programmed for port " << portName_; } // there are 4 possible cases // case 1: No prev cfg, no new cfg // case 2: Prev cfg, no new cfg // case 3: No prev cfg, new cfg // case 4: Prev cfg, new cfg void BcmPortIngressBufferManager::programIngressBuffers( const std::shared_ptr<Port>& port) { const auto pgIdList = getPgIdListInHw(); const auto& portPgCfgs = port->getPortPgConfigs(); if (!portPgCfgs && (pgIdList.size() == 0)) { // there is nothing to program or unprogram // case 1 return; } if (!portPgCfgs) { // unprogram the existing pgs // case 2 resetPgsToDefault(); return; } // simply reprogram based on new config // case 3, 4 reprogramPgs(port); } const PortPgConfig& getTH3DefaultPgSettings() { static const PortPgConfig portPgConfig{PortPgFields{ .id = kDefaultPortPgId, .scalingFactor = utility::bcmAlphaToCfgAlpha(kDefaultPgAlpha), .name = std::nullopt, .minLimitBytes = kDefaultMinLimitBytes, .headroomLimitBytes = kDefaultHeadroomLimitBytes, .resumeOffsetBytes = kdefaultResumeOffsetBytes, .bufferPoolName = "", }}; return portPgConfig; } const PortPgConfig& BcmPortIngressBufferManager::getDefaultChipPgSettings( utility::BcmChip chip) { switch (chip) { case utility::BcmChip::TOMAHAWK3: return getTH3DefaultPgSettings(); default: // currently ony supported for TH3 throw FbossError("Unsupported platform for PG settings: ", chip); } } const PortPgConfig& BcmPortIngressBufferManager::getDefaultPgSettings() { return hw_->getPlatform()->getDefaultPortPgSettings(); } void BcmPortIngressBufferManager::getPgParamsHw( const int pgId, const std::shared_ptr<PortPgConfig>& pg) { getIngressAlpha(pgId, pg); getPgMinLimitBytes(pgId, pg); getPgResumeOffsetBytes(pgId, pg); getPgHeadroomLimitBytes(pgId, pg); } PortPgConfigs BcmPortIngressBufferManager::getCurrentPgSettingsHw() { PortPgConfigs pgs = {}; // walk all pgs in HW and derive the programmed values for (auto pgId = 0; pgId <= cfg::switch_config_constants::PORT_PG_VALUE_MAX(); pgId++) { auto pg = std::make_shared<PortPgConfig>(static_cast<uint8_t>(pgId)); getPgParamsHw(pgId, pg); pgs.emplace_back(pg); } return pgs; } PortPgConfigs BcmPortIngressBufferManager::getCurrentProgrammedPgSettingsHw() { PortPgConfigs pgs = {}; // walk all programmed list of the pgIds in the order {0 -> 7} // Retrive copy of pgIdsListInHw_ // But if pgIdsListInHw_ is not programmed, we return back empty auto pgIdList = getPgIdListInHw(); for (const auto pgId : pgIdList) { auto pg = std::make_shared<PortPgConfig>(static_cast<uint8_t>(pgId)); getPgParamsHw(pgId, pg); pgs.emplace_back(pg); } return pgs; } void BcmPortIngressBufferManager::getPgHeadroomLimitBytes( bcm_cos_queue_t cosQ, std::shared_ptr<PortPgConfig> pgConfig) { int headroomBytes = 0; readCosqTypeFromHw( cosQ, bcmCosqControlIngressPortPGHeadroomLimitBytes, &headroomBytes, "bcmCosqControlIngressPortPGHeadroomLimitBytes"); pgConfig->setHeadroomLimitBytes(headroomBytes); } void BcmPortIngressBufferManager::getIngressAlpha( bcm_cos_queue_t cosQ, std::shared_ptr<PortPgConfig> pgConfig) { int sharedDynamicEnable = 0; readCosqTypeFromHw( cosQ, bcmCosqControlIngressPortPGSharedDynamicEnable, &sharedDynamicEnable, "bcmCosqControlIngressPortPGSharedDynamicEnable"); if (sharedDynamicEnable) { int bcmAlpha = 0; readCosqTypeFromHw( cosQ, bcmCosqControlDropLimitAlpha, &bcmAlpha, "bcmCosqControlDropLimitAlpha"); auto scalingFactor = utility::bcmAlphaToCfgAlpha( static_cast<bcm_cosq_control_drop_limit_alpha_value_e>(bcmAlpha)); pgConfig->setScalingFactor(scalingFactor); } } void BcmPortIngressBufferManager::getPgMinLimitBytes( bcm_cos_queue_t cosQ, std::shared_ptr<PortPgConfig> pgConfig) { int minBytes = 0; readCosqTypeFromHw( cosQ, bcmCosqControlIngressPortPGMinLimitBytes, &minBytes, "bcmCosqControlIngressPortPGMinLimitBytes"); pgConfig->setMinLimitBytes(minBytes); } void BcmPortIngressBufferManager::getPgResumeOffsetBytes( bcm_cos_queue_t cosQ, std::shared_ptr<PortPgConfig> pgConfig) { int resumeBytes = 0; readCosqTypeFromHw( cosQ, bcmCosqControlIngressPortPGResetOffsetBytes, &resumeBytes, "bcmCosqControlIngressPortPGResetOffsetBytes"); pgConfig->setResumeOffsetBytes(resumeBytes); } PgIdSet BcmPortIngressBufferManager::getPgIdListInHw() { std::lock_guard<std::mutex> g(pgIdListLock_); return std::set<int>(pgIdListInHw_.begin(), pgIdListInHw_.end()); } void BcmPortIngressBufferManager::setPgIdListInHw(PgIdSet& newPgIdList) { std::lock_guard<std::mutex> g(pgIdListLock_); pgIdListInHw_ = std::move(newPgIdList); } } // namespace facebook::fboss
29.684848
80
0.713352
TomMD
5166174d985515dd0a3fa627f1c1736d6b152600
4,659
cpp
C++
src/generic_cpu/b_ipc_target.cpp
cicerone/kosim
a9f718a19019c11fd6e6c6fc0164d4d214bbb5e2
[ "BSL-1.0" ]
2
2019-11-15T19:15:36.000Z
2022-03-14T12:53:18.000Z
src/generic_cpu/b_ipc_target.cpp
cicerone/kosim
a9f718a19019c11fd6e6c6fc0164d4d214bbb5e2
[ "BSL-1.0" ]
null
null
null
src/generic_cpu/b_ipc_target.cpp
cicerone/kosim
a9f718a19019c11fd6e6c6fc0164d4d214bbb5e2
[ "BSL-1.0" ]
null
null
null
/*=============================================================================================== Copyright (c) 2009 Kotys LLC. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) Author: Cicerone Mihalache Support: kosim@kotys.biz ===============================================================================================*/ #include "b_ipc_target.h" #include "memory_map_builder.h" #include "memory_map.h" using namespace sc_core; using namespace sc_dt; using namespace std; // BIPCTarget - blocking target (the target that used TLM2 blocking interface) ///////////////////////////////////////////////////////////////////////////////////////////////// // // IN: // OUT: // RET: BIPCTarget::BIPCTarget(sc_module_name name_, uint32_t id_) : sc_module(name_), socket("gc_target_socket"), DMI_LATENCY(10, SC_NS), mp_memory_map(0), m_id(id_), mp_last_tlm_payload(0) { // Register callbacks for incoming interface method calls socket.register_b_transport( this, &BIPCTarget::b_transport); socket.register_get_direct_mem_ptr(this, &BIPCTarget::get_direct_mem_ptr); socket.register_transport_dbg( this, &BIPCTarget::transport_dbg); mp_memory_map = MemoryMapBuilder::GetInstance()->GetMemoryMap(m_id); } ///////////////////////////////////////////////////////////////////////////////////////////////// // TLM-2 blocking transport method // IN: // OUT: // RET: void BIPCTarget::b_transport( tlm::tlm_generic_payload& payload_, sc_time& delay_ ) { tlm::tlm_command command = payload_.get_command(); // sc_dt::uint64 mem_address = payload_.get_address() / sizeof(mem[0]); sc_dt::uint64 mem_address = payload_.get_address(); uint8_t* data_ptr = payload_.get_data_ptr(); uint32_t data_length = payload_.get_data_length(); uint8_t* byte_enable = payload_.get_byte_enable_ptr(); uint32_t stream_width = payload_.get_streaming_width(); // Generate the appropriate error response if (mem_address >= mp_memory_map->get_memory_space()) { payload_.set_response_status( tlm::TLM_ADDRESS_ERROR_RESPONSE ); return; } if (byte_enable != 0) { payload_.set_response_status( tlm::TLM_BYTE_ENABLE_ERROR_RESPONSE ); return; } mp_last_tlm_payload = &payload_; // Set DMI hint to indicated that DMI is supported // payload_.set_dmi_allowed(true); // Obliged to set response status to indicate successful completion // payload_.set_response_status( tlm::TLM_OK_RESPONSE ); m_io_event.notify(SC_ZERO_TIME); wait(SC_ZERO_TIME); // let the target adaptor to use the payload wait(delay_); // implement the delay from initiator delay_ = SC_ZERO_TIME; } ///////////////////////////////////////////////////////////////////////////////////////////////// // TLM-2 forward DMI method // IN: // OUT: // RET: bool BIPCTarget::get_direct_mem_ptr(tlm::tlm_generic_payload& payload_, tlm::tlm_dmi& dmi_data_) { /* // Permit read and write access dmi_data_.allow_read_write(); // Set other details of DMI region dmi_data_.set_dmi_ptr( reinterpret_cast<unsigned char*>( &mem[0] ) ); dmi_data_.set_start_address( 0 ); dmi_data_.set_end_address( SIZE * sizeof(mem[0]) - 1 ); dmi_data_.set_read_latency( DMI_LATENCY ); dmi_data_.set_write_latency( DMI_LATENCY ); return true; */ return false; } ///////////////////////////////////////////////////////////////////////////////////////////////// // TLM-2 debug transaction method // IN: // OUT: // RET: unsigned int BIPCTarget::transport_dbg(tlm::tlm_generic_payload& payload_) { fprintf(stderr, "ERROR! %s not implemented!\n"); exit(1); tlm::tlm_command command = payload_.get_command(); sc_dt::uint64 mem_address = payload_.get_address(); uint8_t* data_ptr = payload_.get_data_ptr(); uint32_t data_length = payload_.get_data_length(); // Calculate the number of bytes to be actually copied sc_dt::uint64 length_to_end = mp_memory_map->get_memory_space() - mem_address; sc_dt::uint64 num_bytes = data_length < length_to_end ? data_length : length_to_end ; if ( command == tlm::TLM_READ_COMMAND ) { memcpy(data_ptr, mp_memory_map->GetPhysicalAddress(mem_address), data_length); } else if ( command == tlm::TLM_WRITE_COMMAND ) { memcpy(mp_memory_map->GetPhysicalAddress(mem_address), data_ptr, data_length); } return num_bytes; }
36.116279
97
0.605924
cicerone
51681500c39ac4640164102458d08cbc89d5e7c2
807
cpp
C++
Codeforces/r217d2/B.cpp
s9v/toypuct
68e65e6da5922af340de72636a9a4f136454c70d
[ "MIT" ]
null
null
null
Codeforces/r217d2/B.cpp
s9v/toypuct
68e65e6da5922af340de72636a9a4f136454c70d
[ "MIT" ]
null
null
null
Codeforces/r217d2/B.cpp
s9v/toypuct
68e65e6da5922af340de72636a9a4f136454c70d
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <queue> #include <vector> #define sz(X) (int)X.size() using namespace std; typedef vector<int> vi; int n; vi m[100]; int main() { cin >> n; for (int i = 0; i < n; i++) { int x; cin >> x; m[i].resize(x); for (int j = 0; j < x; j++) cin >> m[i][j]; sort(m[i].begin(), m[i].end()); } for (int i = 0; i < n; i++) { bool ok = true; for (int j = 0; j < n; j++) { if (i == j) continue; if (sz(m[i]) < sz(m[j])) continue; int l = 0; int r = 0; while (l < sz(m[i]) && r < sz(m[j])) { if (m[i][l] == m[j][r]) { l++; r++; } else { l++; } } if (r == sz(m[j])) { ok = false; break; } } cout << (ok ?"YES" :"NO") << "\n"; } return 0; }
13.016129
41
0.408922
s9v
516925e539cd8565aac25799d06e8cbc361665ad
3,003
cc
C++
src/lib/util/tests/base64_unittest.cc
svenauhagen/kea
8a575ad46dee1487364fad394e7a325337200839
[ "Apache-2.0" ]
273
2015-01-22T14:14:42.000Z
2022-03-13T10:27:44.000Z
src/lib/util/tests/base64_unittest.cc
jxiaobin/kea
1987a50a458921f9e5ac84cb612782c07f3b601d
[ "Apache-2.0" ]
104
2015-01-16T16:37:06.000Z
2021-08-08T19:38:45.000Z
src/lib/util/tests/base64_unittest.cc
jxiaobin/kea
1987a50a458921f9e5ac84cb612782c07f3b601d
[ "Apache-2.0" ]
133
2015-02-21T14:06:39.000Z
2022-02-27T08:56:40.000Z
// Copyright (C) 2010-2015 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <config.h> #include <string> #include <utility> #include <vector> #include <exceptions/exceptions.h> #include <util/encode/base64.h> #include <gtest/gtest.h> using namespace std; using namespace isc; using namespace isc::util::encode; namespace { typedef pair<string, string> StringPair; class Base64Test : public ::testing::Test { protected: Base64Test() { // test vectors from RFC4648 test_sequence.push_back(StringPair("", "")); test_sequence.push_back(StringPair("f", "Zg==")); test_sequence.push_back(StringPair("fo", "Zm8=")); test_sequence.push_back(StringPair("foo", "Zm9v")); test_sequence.push_back(StringPair("foob", "Zm9vYg==")); test_sequence.push_back(StringPair("fooba", "Zm9vYmE=")); test_sequence.push_back(StringPair("foobar", "Zm9vYmFy")); } vector<StringPair> test_sequence; vector<uint8_t> decoded_data; }; void decodeCheck(const string& input_string, vector<uint8_t>& output, const string& expected) { decodeBase64(input_string, output); EXPECT_EQ(expected, string(output.begin(), output.end())); } TEST_F(Base64Test, decode) { for (vector<StringPair>::const_iterator it = test_sequence.begin(); it != test_sequence.end(); ++it) { decodeCheck((*it).second, decoded_data, (*it).first); } // whitespace should be allowed decodeCheck("Zm 9v\tYmF\ny", decoded_data, "foobar"); decodeCheck("Zm9vYg==", decoded_data, "foob"); decodeCheck("Zm9vYmE=\n", decoded_data, "fooba"); decodeCheck(" Zm9vYmE=\n", decoded_data, "fooba"); decodeCheck(" ", decoded_data, ""); decodeCheck("\n\t", decoded_data, ""); // incomplete input EXPECT_THROW(decodeBase64("Zm9vYmF", decoded_data), BadValue); // only up to 2 padding characters are allowed EXPECT_THROW(decodeBase64("A===", decoded_data), BadValue); EXPECT_THROW(decodeBase64("A= ==", decoded_data), BadValue); // intermediate padding isn't allowed EXPECT_THROW(decodeBase64("YmE=YmE=", decoded_data), BadValue); // Non canonical form isn't allowed. // Z => 25(011001), m => 38(100110), 9 => 60(111101), so the padding // byte would be 0100 0000. EXPECT_THROW(decodeBase64("Zm9=", decoded_data), BadValue); // Same for the 1st padding byte. This would make it 01100000. EXPECT_THROW(decodeBase64("Zm==", decoded_data), BadValue); } TEST_F(Base64Test, encode) { for (vector<StringPair>::const_iterator it = test_sequence.begin(); it != test_sequence.end(); ++it) { decoded_data.assign((*it).first.begin(), (*it).first.end()); EXPECT_EQ((*it).second, encodeBase64(decoded_data)); } } }
31.946809
72
0.664336
svenauhagen
516c38a4b97ddbfc803afb36b00d4f0bc1e3ace6
265
cc
C++
Sources/pyTheGame/Tasks/StackTask.cc
JYPark09/TheGame
2af0bbe1199df794bd1688837c0f814479deded8
[ "MIT" ]
null
null
null
Sources/pyTheGame/Tasks/StackTask.cc
JYPark09/TheGame
2af0bbe1199df794bd1688837c0f814479deded8
[ "MIT" ]
null
null
null
Sources/pyTheGame/Tasks/StackTask.cc
JYPark09/TheGame
2af0bbe1199df794bd1688837c0f814479deded8
[ "MIT" ]
null
null
null
#include <pyTheGame/Tasks/StackTask.hpp> #include <TheGame/Tasks/StackTask.hpp> namespace py = pybind11; using namespace TheGame; void buildStackTask(py::module& m) { py::class_<StackTask, Task>(m, "StackTask") .def(py::init<Card, std::size_t>()); }
20.384615
47
0.69434
JYPark09
516c8c98979cb71a25f3b40f2ed3b4509106adba
600
hpp
C++
include/kjq_navigation/BiPridgeNode.hpp
CtfChan/kjq_navigation
4969fe633c74fa19ab3330e30a561efbcacc6b03
[ "BSD-3-Clause" ]
null
null
null
include/kjq_navigation/BiPridgeNode.hpp
CtfChan/kjq_navigation
4969fe633c74fa19ab3330e30a561efbcacc6b03
[ "BSD-3-Clause" ]
null
null
null
include/kjq_navigation/BiPridgeNode.hpp
CtfChan/kjq_navigation
4969fe633c74fa19ab3330e30a561efbcacc6b03
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <ros/ros.h> #include <sensor_msgs/LaserScan.h> #include <geometry_msgs/Pose.h> #include <tf/transform_broadcaster.h> namespace kjq_navigation { class PiBridgeNode { public: PiBridgeNode(ros::NodeHandle& nh); private: void scanCallback(sensor_msgs::LaserScan::Ptr msg); void odomCallback(geometry_msgs::Pose::Ptr msg); ros::NodeHandle n_; geometry_msgs::TransformStamped t_; tf::TransformBroadcaster broadcaster_; ros::Subscriber laser_sub_; ros::Subscriber odom_sub_; ros::Publisher laser_pub_; ros::Publisher odom_pub_; }; }
17.142857
55
0.728333
CtfChan
516ce0b27fa09d3a1ea844c0cb55c514f66746ed
1,870
cpp
C++
Code/C++/Search/vj1910.cpp
EdmundLuan/NOIP14-16
c4277dfc7467346d6c67dd4cfae9a9caa08b487c
[ "MIT" ]
null
null
null
Code/C++/Search/vj1910.cpp
EdmundLuan/NOIP14-16
c4277dfc7467346d6c67dd4cfae9a9caa08b487c
[ "MIT" ]
null
null
null
Code/C++/Search/vj1910.cpp
EdmundLuan/NOIP14-16
c4277dfc7467346d6c67dd4cfae9a9caa08b487c
[ "MIT" ]
null
null
null
#include <cstdio> #include <cctype> #include <algorithm> #include <cstring> using namespace std; #define mnum 5 const int mod[mnum] = {8233, 9067, 9337, 20929, 10007}; int n, m, a[110][mnum]; int ans[1001000]; bool check[1001000]; void read(int &x) { char chr = getchar(); int minus = 1; x = 0; while (!isdigit(chr) && chr != '-') chr = getchar(); if (chr == '-') { minus = -1; chr = getchar(); } while (isdigit(chr)) { x *= 10; x += chr - 48; chr = getchar(); } } void readc(int *s) { char chr = getchar(); int minus = 1; for (int i = 0; i < mnum; i++) s[i] = 0; while (!isdigit(chr) && chr != '-') chr = getchar(); if (chr == '-') { minus = -1; chr = getchar(); } while (isdigit(chr)) { chr -= 48; for (int i = 0; i < mnum; i++) { s[i] = (s[i] * 10 % mod[i] + chr % mod[i]) % mod[i]; } chr = getchar(); } for (int i = 0; i < mnum; i++) s[i] *= minus; } void init() { read(n); read(m); memset(a, 0, sizeof(a)); memset(check, 0, sizeof(check)); for (int i = 0; i <= n; i++) readc(a[i]); } int qinjiushao(const int root, const int m, const int num) { int r = root % m; int tmp = a[n][num]; for (int i = n; i > 0; i--) { tmp = (tmp * r % m + a[i - 1][num]) % m; } return tmp; } int solve(int root) { int state = 0; for (int i = 0; i < mnum; i++) { state <<= 1; if (qinjiushao(root, mod[i], i)) { state++; } } return state; } int main() { int cnt = 0; //freopen("input.txt", "r", stdin); init(); for (int i = 1; i <= m; i++) { if (check[i]) continue; int v = solve(i); if (!v) ans[++cnt] = i; else { for (int j = mnum - 1; j >= 0; j--) { if (v & 1) { for (int k = i + mod[j]; k <= m; k += mod[j]) check[k] = true; } v >>= 1; } } } printf("%d\n", cnt); for (int i = 1; i <= cnt; i++) printf("%d\n", ans[i]); //fclose(stdin); return 0; }
17.809524
60
0.491979
EdmundLuan
516d06a3b4c1c5d214b2de1e4313584fe89cae16
54,826
cpp
C++
include/enki/viewer/objects/EPuckBody.cpp
ou-real/nevil-grandparent
38324705678afac77d002391da753c6f10ee95e2
[ "MIT" ]
null
null
null
include/enki/viewer/objects/EPuckBody.cpp
ou-real/nevil-grandparent
38324705678afac77d002391da753c6f10ee95e2
[ "MIT" ]
null
null
null
include/enki/viewer/objects/EPuckBody.cpp
ou-real/nevil-grandparent
38324705678afac77d002391da753c6f10ee95e2
[ "MIT" ]
null
null
null
/* Enki - a fast 2D robot simulator Copyright (C) 1999-2013 Stephane Magnenat <stephane at magnenat dot net> Copyright (C) 2004-2005 Markus Waibel <markus dot waibel at epfl dot ch> Copyright (c) 2004-2005 Antoine Beyeler <abeyeler at ab-ware dot com> Copyright (C) 2005-2006 Laboratory of Intelligent Systems, EPFL, Lausanne Copyright (C) 2006 Laboratory of Robotics Systems, EPFL, Lausanne See AUTHORS for details This program is free software; the authors of any publication arising from research using this software are asked to add the following reference: Enki - a fast 2D robot simulator http://home.gna.org/enki Stephane Magnenat <stephane at magnenat dot net>, Markus Waibel <markus dot waibel at epfl dot ch> Laboratory of Intelligent Systems, EPFL, Lausanne. You can redistribute this program and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // E-puck object file #include <QtOpenGL> namespace Enki { // 262 Verticies // 610 Texture Coordinates // 275 Normals // 536 Triangles static short face_indicies[536][9] = { // (unnamed) {204,188,217 ,0,1,2 ,0,1,2 }, {179,162,172 ,3,4,5 ,3,4,5 }, {179,180,162 ,3,0,4 ,3,6,4 }, {235,261,233 ,6,7,8 ,7,8,9 }, {235,244,261 ,6,9,7 ,7,10,8 }, {231,261,1 ,10,7,11 ,11,8,12 }, {231,233,261 ,10,8,7 ,11,9,8 }, {257,1,261 ,12,11,7 ,13,12,8 }, {234,247,235 ,13,14,6 ,14,15,7 }, {234,246,247 ,13,15,14 ,14,16,15 }, {215,234,196 ,16,13,0 ,17,14,18 }, {215,245,234 ,16,17,13 ,17,19,14 }, {245,246,234 ,17,15,13 ,19,16,14 }, {216,196,205 ,18,0,0 ,20,18,21 }, {216,215,196 ,18,16,0 ,20,17,18 }, {162,150,172 ,4,19,5 ,4,22,5 }, {162,149,150 ,4,20,19 ,4,23,22 }, {205,204,216 ,0,0,18 ,21,24,20 }, {188,179,172 ,1,3,5 ,1,3,5 }, {188,189,179 ,1,21,3 ,1,25,3 }, {247,244,235 ,14,9,6 ,15,10,7 }, {216,204,217 ,18,0,2 ,20,24,26 }, {217,188,172 ,2,1,5 ,2,1,5 }, {231,222,223 ,10,22,23 ,11,27,28 }, {231,0,222 ,10,24,22 ,11,29,27 }, {2,231,1 ,25,10,11 ,30,11,12 }, {2,0,231 ,25,24,10 ,30,29,11 }, {183,199,211 ,26,21,27 ,31,32,33 }, {154,176,166 ,28,29,30 ,34,35,36 }, {154,175,176 ,28,21,29 ,34,37,35 }, {249,226,225 ,31,32,33 ,38,39,40 }, {249,238,226 ,31,34,32 ,38,41,39 }, {249,229,3 ,31,35,36 ,38,42,43 }, {249,225,229 ,31,33,35 ,38,40,42 }, {249,3,253 ,31,36,37 ,38,43,44 }, {241,227,226 ,38,39,32 ,45,46,39 }, {241,240,227 ,38,40,39 ,45,47,46 }, {227,209,192 ,39,41,21 ,46,48,49 }, {227,239,209 ,39,42,41 ,46,50,48 }, {240,239,227 ,40,42,39 ,47,50,46 }, {192,210,200 ,21,43,21 ,49,51,52 }, {192,209,210 ,21,41,43 ,49,48,51 }, {142,154,166 ,44,28,30 ,53,34,36 }, {142,143,154 ,44,45,28 ,53,54,34 }, {199,200,210 ,21,21,43 ,32,52,51 }, {176,183,166 ,29,26,30 ,35,31,36 }, {176,184,183 ,29,0,26 ,35,55,31 }, {238,241,226 ,34,38,32 ,41,45,39 }, {199,210,211 ,21,43,27 ,32,51,33 }, {183,211,166 ,26,27,30 ,31,33,36 }, {222,229,219 ,22,35,46 ,27,42,56 }, {222,0,229 ,22,24,35 ,27,29,42 }, {3,0,2 ,36,24,25 ,43,29,30 }, {3,229,0 ,36,35,24 ,43,42,29 }, {257,259,1 ,12,47,11 ,13,57,12 }, {2,259,258 ,25,47,48 ,30,57,58 }, {2,1,259 ,25,11,47 ,30,12,57 }, {252,2,258 ,49,25,48 ,59,30,58 }, {252,3,2 ,49,36,25 ,59,43,30 }, {3,252,253 ,36,49,37 ,43,59,44 }, {163,173,172 ,50,51,5 ,60,61,5 }, {163,158,173 ,50,52,51 ,60,62,61 }, {150,163,172 ,19,50,5 ,22,60,5 }, {150,151,163 ,19,53,50 ,22,63,60 }, {173,159,169 ,51,54,55 ,61,64,65 }, {173,158,159 ,51,52,54 ,61,62,64 }, {167,155,166 ,56,57,30 ,66,67,36 }, {167,156,155 ,56,58,57 ,66,68,67 }, {155,142,166 ,57,44,30 ,67,53,36 }, {155,144,142 ,57,59,44 ,67,69,53 }, {159,167,169 ,54,56,55 ,64,66,65 }, {159,156,167 ,54,58,56 ,64,68,66 }, {195,196,234 ,0,0,13 ,70,18,14 }, {192,191,227 ,21,21,39 ,49,71,46 }, {151,148,163 ,53,60,50 ,63,72,60 }, {141,144,155 ,61,59,57 ,73,69,67 }, {234,235,232 ,62,62,62 ,74,75,76 }, {226,227,224 ,62,62,62 ,77,78,79 }, {203,205,196 ,63,64,65 ,80,81,82 }, {228,219,229 ,21,21,21 ,83,84,85 }, {228,218,219 ,21,21,21 ,83,86,84 }, {158,163,159 ,62,62,62 ,87,88,89 }, {146,163,148 ,21,21,21 ,90,91,92 }, {146,160,163 ,21,21,21 ,90,93,91 }, {180,161,162 ,62,62,62 ,94,95,96 }, {180,178,161 ,62,62,62 ,94,97,95 }, {161,149,162 ,66,66,66 ,98,99,100 }, {161,145,149 ,66,66,66 ,98,101,99 }, {233,231,235 ,62,62,62 ,102,103,104 }, {230,232,231 ,62,62,62 ,105,106,107 }, {232,235,231 ,62,62,62 ,106,108,109 }, {223,230,231 ,0,0,0 ,110,111,112 }, {223,221,230 ,0,0,0 ,110,113,111 }, {234,194,195 ,62,62,62 ,114,115,116 }, {234,232,194 ,62,62,62 ,114,117,115 }, {189,187,179 ,67,68,69 ,118,119,120 }, {186,189,188 ,70,67,71 ,121,122,123 }, {186,187,189 ,70,68,67 ,121,124,122 }, {204,186,188 ,72,70,71 ,125,126,127 }, {204,202,186 ,72,73,70 ,125,128,126 }, {205,202,204 ,64,73,72 ,129,130,131 }, {205,203,202 ,64,63,73 ,129,132,130 }, {148,147,146 ,62,62,62 ,133,134,135 }, {148,151,147 ,62,62,62 ,133,136,134 }, {147,149,145 ,62,62,62 ,134,137,138 }, {147,150,149 ,62,62,62 ,134,139,137 }, {150,147,151 ,62,62,62 ,140,141,142 }, {159,160,157 ,62,62,62 ,143,144,145 }, {159,163,160 ,62,62,62 ,143,146,144 }, {222,4,223 ,62,62,62 ,147,148,149 }, {223,220,221 ,62,62,62 ,150,151,152 }, {223,4,220 ,62,62,62 ,150,148,151 }, {179,185,5 ,69,74,75 ,153,154,155 }, {179,187,185 ,69,68,74 ,153,119,154 }, {8,196,195 ,76,65,76 ,156,82,157 }, {8,7,196 ,76,77,65 ,156,158,82 }, {6,178,180 ,62,62,62 ,159,160,161 }, {6,177,178 ,62,62,62 ,159,162,160 }, {5,180,179 ,75,66,69 ,155,163,153 }, {5,6,180 ,75,66,66 ,155,159,163 }, {195,193,8 ,62,62,62 ,157,164,156 }, {195,194,193 ,62,62,62 ,157,165,164 }, {7,203,196 ,77,63,65 ,158,166,167 }, {7,201,203 ,77,78,63 ,158,168,166 }, {155,156,159 ,62,62,62 ,169,170,171 }, {155,140,141 ,0,0,0 ,172,173,174 }, {155,153,140 ,0,0,0 ,172,175,173 }, {152,175,154 ,62,62,62 ,176,177,178 }, {152,174,175 ,62,62,62 ,176,179,177 }, {143,152,154 ,66,66,66 ,180,181,182 }, {143,138,152 ,66,66,66 ,180,183,181 }, {229,225,226 ,62,62,62 ,184,185,186 }, {224,228,229 ,62,62,62 ,187,188,184 }, {226,224,229 ,62,62,62 ,189,190,191 }, {190,227,191 ,62,62,62 ,192,193,194 }, {190,224,227 ,62,62,62 ,192,195,193 }, {182,184,176 ,79,80,81 ,196,197,198 }, {184,181,183 ,80,82,83 ,199,200,201 }, {184,182,181 ,80,79,82 ,199,196,200 }, {181,199,183 ,82,84,83 ,202,203,204 }, {181,197,199 ,82,85,84 ,202,205,203 }, {197,200,199 ,85,86,84 ,206,207,208 }, {197,198,200 ,85,87,86 ,206,209,207 }, {139,141,140 ,62,62,62 ,210,211,212 }, {139,144,141 ,62,62,62 ,210,213,211 }, {143,139,138 ,62,62,62 ,214,215,216 }, {143,142,139 ,62,62,62 ,214,217,215 }, {139,142,144 ,62,62,62 ,218,219,220 }, {200,198,192 ,86,87,88 ,221,222,223 }, {153,159,157 ,62,62,62 ,224,225,226 }, {153,155,159 ,62,62,62 ,224,227,225 }, {4,222,219 ,62,62,62 ,148,228,229 }, {220,219,218 ,62,62,62 ,230,229,231 }, {220,4,219 ,62,62,62 ,230,148,229 }, {185,176,5 ,74,81,75 ,232,233,155 }, {185,182,176 ,74,79,81 ,232,234,233 }, {192,8,191 ,88,76,76 ,235,156,194 }, {192,7,8 ,88,77,76 ,235,158,156 }, {174,6,175 ,62,62,62 ,236,159,237 }, {174,177,6 ,62,62,62 ,236,238,159 }, {175,5,176 ,66,75,81 ,239,155,198 }, {175,6,5 ,66,66,75 ,239,159,155 }, {193,191,8 ,62,62,62 ,240,241,156 }, {193,190,191 ,62,62,62 ,240,242,241 }, {198,7,192 ,87,77,88 ,243,158,244 }, {198,201,7 ,87,78,77 ,243,245,158 }, {51,48,60 ,0,0,0 ,246,247,248 }, {51,46,48 ,0,0,0 ,246,249,247 }, {44,48,46 ,89,90,91 ,250,247,249 }, {44,45,48 ,89,92,90 ,250,251,247 }, {42,44,40 ,93,94,95 ,252,250,253 }, {42,45,44 ,93,93,94 ,252,251,250 }, {25,68,20 ,96,97,98 ,254,255,256 }, {25,55,68 ,96,99,97 ,254,257,255 }, {31,37,36 ,100,101,102 ,258,259,260 }, {31,30,37 ,100,103,101 ,258,261,259 }, {53,31,36 ,104,100,102 ,262,258,260 }, {53,24,31 ,104,105,100 ,262,263,258 }, {68,173,20 ,97,51,98 ,255,264,256 }, {68,172,173 ,97,5,51 ,255,265,264 }, {247,63,244 ,14,106,107 ,266,267,268 }, {247,244,63 ,14,107,106 ,266,10,267 }, {244,61,261 ,107,108,109 ,269,270,271 }, {244,63,61 ,107,106,108 ,269,267,270 }, {58,257,62 ,110,111,112 ,272,273,274 }, {58,259,257 ,110,113,111 ,272,275,273 }, {61,257,261 ,108,111,109 ,270,273,276 }, {61,62,257 ,108,112,111 ,270,274,273 }, {50,259,58 ,114,113,110 ,277,278,272 }, {50,49,259 ,114,115,113 ,277,279,278 }, {63,242,243 ,106,116,21 ,267,280,281 }, {63,56,242 ,106,117,116 ,267,282,280 }, {242,23,212 ,116,118,119 ,280,283,284 }, {242,56,23 ,116,117,118 ,280,282,283 }, {212,27,213 ,119,120,121 ,284,285,286 }, {212,23,27 ,119,118,120 ,284,283,285 }, {24,213,27 ,122,121,120 ,263,287,285 }, {24,53,213 ,122,104,121 ,263,262,287 }, {21,245,215 ,123,17,16 ,288,289,290 }, {21,57,245 ,123,124,17 ,288,291,289 }, {28,215,216 ,125,16,18 ,292,290,293 }, {28,21,215 ,125,123,16 ,292,288,290 }, {245,247,246 ,17,14,15 ,294,295,296 }, {245,57,247 ,17,124,14 ,294,291,295 }, {256,40,44 ,126,95,94 ,297,253,250 }, {256,41,40 ,126,127,95 ,297,298,253 }, {44,43,256 ,94,128,126 ,250,299,300 }, {254,61,260 ,129,108,130 ,301,270,302 }, {254,62,61 ,129,112,108 ,301,274,270 }, {256,62,254 ,126,112,129 ,300,274,303 }, {256,43,62 ,126,128,112 ,300,299,274 }, {61,63,260 ,108,106,130 ,270,267,304 }, {247,57,39 ,14,124,131 ,305,291,306 }, {39,244,247 ,131,107,14 ,306,307,308 }, {39,38,244 ,131,132,107 ,306,309,307 }, {38,35,32 ,132,133,134 ,309,310,311 }, {38,39,35 ,132,131,133 ,309,306,310 }, {35,28,34 ,133,125,135 ,310,292,312 }, {35,21,28 ,133,123,125 ,310,288,292 }, {32,34,33 ,134,135,136 ,311,312,313 }, {32,35,34 ,134,133,135 ,311,310,312 }, {39,21,35 ,131,123,133 ,306,288,310 }, {39,57,21 ,131,124,123 ,306,291,288 }, {30,33,34 ,103,136,135 ,261,313,312 }, {30,31,33 ,103,100,136 ,261,258,313 }, {28,30,34 ,125,103,135 ,292,261,312 }, {28,22,30 ,125,137,103 ,292,314,261 }, {32,56,38 ,134,117,132 ,311,282,309 }, {32,23,56 ,134,118,117 ,311,283,282 }, {33,23,32 ,136,118,134 ,313,283,311 }, {33,27,23 ,136,120,118 ,313,285,283 }, {38,63,244 ,132,106,107 ,309,267,315 }, {38,56,63 ,132,117,106 ,309,282,267 }, {44,47,43 ,89,138,139 ,250,316,299 }, {44,46,47 ,89,91,138 ,250,249,316 }, {59,49,50 ,140,115,114 ,317,279,277 }, {52,50,58 ,141,142,143 ,318,277,272 }, {52,51,50 ,141,144,142 ,318,246,277 }, {33,24,27 ,136,122,120 ,313,263,285 }, {33,31,24 ,136,100,122 ,313,258,263 }, {37,22,29 ,101,145,146 ,259,314,319 }, {37,30,22 ,101,103,145 ,259,261,314 }, {51,47,46 ,0,0,0 ,246,316,249 }, {51,52,47 ,0,0,0 ,246,318,316 }, {51,59,50 ,144,147,142 ,246,317,277 }, {51,60,59 ,144,148,147 ,246,248,317 }, {22,216,29 ,145,18,146 ,314,320,319 }, {22,28,216 ,145,125,18 ,314,292,320 }, {10,25,20 ,149,96,98 ,321,254,256 }, {10,69,25 ,149,150,96 ,321,322,254 }, {10,173,169 ,149,51,55 ,321,323,324 }, {10,20,173 ,149,98,51 ,321,256,323 }, {49,258,259 ,151,48,47 ,279,325,326 }, {49,9,258 ,151,152,48 ,279,327,325 }, {18,60,48 ,153,148,90 ,328,248,247 }, {18,19,60 ,153,154,148 ,328,329,248 }, {18,48,45 ,62,62,62 ,328,247,251 }, {17,45,42 ,155,92,156 ,330,251,252 }, {17,18,45 ,155,153,92 ,330,328,251 }, {16,42,40 ,157,156,158 ,331,252,253 }, {16,17,42 ,157,155,156 ,331,330,252 }, {12,54,26 ,159,160,161 ,332,333,334 }, {12,15,54 ,159,162,160 ,332,335,333 }, {14,171,170 ,62,62,62 ,336,337,338 }, {14,168,171 ,62,62,62 ,336,339,337 }, {15,170,54 ,162,163,160 ,335,340,333 }, {15,14,170 ,162,163,163 ,335,336,340 }, {256,13,41 ,62,62,62 ,341,342,298 }, {256,255,13 ,62,62,62 ,341,343,342 }, {13,40,41 ,164,158,165 ,342,253,298 }, {13,16,40 ,164,157,158 ,342,331,253 }, {59,9,49 ,166,152,151 ,317,327,279 }, {59,60,9 ,166,148,152 ,317,248,327 }, {60,19,9 ,148,154,152 ,248,329,327 }, {58,47,52 ,167,167,167 ,272,316,318 }, {58,43,47 ,167,167,167 ,272,299,316 }, {58,62,43 ,110,112,128 ,272,274,299 }, {260,63,243 ,76,76,76 ,344,267,345 }, {55,65,64 ,99,168,169 ,257,346,347 }, {55,26,65 ,99,161,168 ,257,334,346 }, {64,36,37 ,169,102,101 ,347,260,259 }, {64,65,36 ,169,168,102 ,347,346,260 }, {66,37,29 ,170,101,146 ,348,259,319 }, {66,64,37 ,170,169,101 ,348,347,259 }, {64,68,55 ,169,97,99 ,347,255,257 }, {64,66,68 ,169,170,97 ,347,348,255 }, {26,67,65 ,161,171,168 ,334,349,346 }, {26,54,67 ,161,160,171 ,334,333,349 }, {65,53,36 ,168,104,102 ,346,262,260 }, {65,67,53 ,168,171,104 ,346,349,262 }, {214,53,67 ,172,104,171 ,350,262,349 }, {214,213,53 ,172,121,104 ,350,286,262 }, {170,67,54 ,173,171,160 ,351,349,333 }, {170,214,67 ,173,172,171 ,351,350,349 }, {29,217,66 ,146,2,170 ,319,352,348 }, {29,216,217 ,146,18,2 ,319,353,352 }, {66,172,68 ,170,5,97 ,348,354,255 }, {66,217,172 ,170,2,5 ,348,355,354 }, {55,69,11 ,99,150,167 ,257,322,356 }, {55,25,69 ,99,96,150 ,257,254,322 }, {11,26,55 ,167,161,99 ,356,334,257 }, {11,12,26 ,167,159,161 ,356,332,334 }, {98,101,110 ,21,21,21 ,357,358,359 }, {98,96,101 ,21,21,21 ,357,360,358 }, {98,94,96 ,174,175,176 ,357,361,360 }, {98,95,94 ,174,92,175 ,357,362,361 }, {94,92,90 ,177,178,179 ,361,363,364 }, {94,95,92 ,177,178,178 ,361,362,363 }, {118,75,70 ,180,181,182 ,365,366,367 }, {118,105,75 ,180,183,181 ,365,368,366 }, {87,81,86 ,184,185,186 ,369,370,371 }, {87,80,81 ,184,187,185 ,369,372,370 }, {81,103,86 ,185,188,186 ,370,373,371 }, {81,74,103 ,185,189,188 ,370,374,373 }, {167,118,70 ,56,180,182 ,375,365,367 }, {167,166,118 ,56,30,180 ,375,376,365 }, {113,241,238 ,190,38,191 ,377,378,379 }, {113,238,241 ,190,191,38 ,377,41,378 }, {111,238,249 ,192,191,193 ,380,381,382 }, {111,113,238 ,192,190,191 ,380,377,381 }, {253,108,112 ,194,195,196 ,383,384,385 }, {253,252,108 ,194,197,195 ,383,386,384 }, {253,111,249 ,194,192,193 ,387,380,388 }, {253,112,111 ,194,196,192 ,387,385,380 }, {252,100,108 ,197,198,195 ,389,390,384 }, {252,99,100 ,197,199,198 ,389,391,390 }, {236,113,237 ,200,190,0 ,392,377,393 }, {236,106,113 ,200,201,190 ,392,394,377 }, {73,236,206 ,202,200,203 ,395,392,396 }, {73,106,236 ,202,201,200 ,395,394,392 }, {77,206,207 ,204,203,205 ,397,396,398 }, {77,73,206 ,204,202,203 ,397,395,396 }, {207,74,77 ,205,206,204 ,399,374,397 }, {207,103,74 ,205,188,206 ,399,373,374 }, {239,71,209 ,42,207,41 ,400,401,402 }, {239,107,71 ,42,208,207 ,400,403,401 }, {209,78,210 ,41,209,43 ,402,404,405 }, {209,71,78 ,41,207,209 ,402,401,404 }, {241,239,240 ,38,42,40 ,406,407,408 }, {241,107,239 ,38,208,42 ,406,403,407 }, {90,250,94 ,179,210,177 ,364,409,361 }, {90,91,250 ,179,211,210 ,364,410,409 }, {93,94,250 ,212,177,210 ,411,361,412 }, {111,251,248 ,192,213,214 ,380,413,414 }, {111,112,251 ,192,196,213 ,380,385,413 }, {112,250,251 ,196,210,213 ,385,412,415 }, {112,93,250 ,196,212,210 ,385,411,412 }, {113,111,248 ,190,192,214 ,377,380,416 }, {107,241,89 ,208,38,215 ,403,417,418 }, {238,89,241 ,191,215,38 ,419,418,420 }, {238,88,89 ,191,216,215 ,419,421,418 }, {85,88,82 ,217,216,218 ,422,421,423 }, {85,89,88 ,217,215,216 ,422,418,421 }, {78,85,84 ,209,217,219 ,404,422,424 }, {78,71,85 ,209,207,217 ,404,401,422 }, {84,82,83 ,219,218,220 ,424,423,425 }, {84,85,82 ,219,217,218 ,424,422,423 }, {71,89,85 ,207,215,217 ,401,418,422 }, {71,107,89 ,207,208,215 ,401,403,418 }, {83,80,84 ,220,187,219 ,425,372,424 }, {83,81,80 ,220,185,187 ,425,370,372 }, {80,78,84 ,187,209,219 ,372,404,424 }, {80,72,78 ,187,221,209 ,372,426,404 }, {106,82,88 ,201,218,216 ,394,423,421 }, {106,73,82 ,201,202,218 ,394,395,423 }, {73,83,82 ,202,220,218 ,395,425,423 }, {73,77,83 ,202,204,220 ,395,397,425 }, {113,88,238 ,190,216,191 ,377,421,427 }, {113,106,88 ,190,201,216 ,377,394,421 }, {97,94,93 ,222,175,139 ,428,361,411 }, {97,96,94 ,222,176,175 ,428,360,361 }, {99,109,100 ,199,223,198 ,391,429,390 }, {100,102,108 ,224,225,226 ,390,430,384 }, {100,101,102 ,224,227,225 ,390,358,430 }, {74,83,77 ,206,220,204 ,374,425,397 }, {74,81,83 ,206,185,220 ,374,370,425 }, {72,87,79 ,228,184,229 ,426,369,431 }, {72,80,87 ,228,187,184 ,426,372,369 }, {97,101,96 ,21,21,21 ,428,358,360 }, {97,102,101 ,21,21,21 ,428,430,358 }, {109,101,100 ,230,227,224 ,429,358,390 }, {109,110,101 ,230,231,227 ,429,359,358 }, {210,72,79 ,43,228,229 ,432,426,431 }, {210,78,72 ,43,209,228 ,432,404,426 }, {75,10,70 ,181,149,182 ,366,321,367 }, {75,69,10 ,181,150,149 ,366,322,321 }, {167,10,169 ,56,149,55 ,433,321,434 }, {167,70,10 ,56,182,149 ,433,367,321 }, {258,99,252 ,48,232,49 ,435,391,436 }, {258,9,99 ,48,152,232 ,435,327,391 }, {110,18,98 ,231,153,174 ,359,328,357 }, {110,19,18 ,231,154,153 ,359,329,328 }, {98,18,95 ,62,62,62 ,357,328,362 }, {95,17,92 ,92,155,233 ,362,330,363 }, {95,18,17 ,92,153,155 ,362,328,330 }, {92,16,90 ,233,157,234 ,363,331,364 }, {92,17,16 ,233,155,157 ,363,330,331 }, {104,12,76 ,235,159,236 ,437,332,438 }, {104,15,12 ,235,162,159 ,437,335,332 }, {165,14,164 ,62,62,62 ,439,336,440 }, {165,168,14 ,62,62,62 ,439,441,336 }, {164,15,104 ,163,162,235 ,442,335,437 }, {164,14,15 ,163,163,162 ,442,336,335 }, {13,250,91 ,62,62,62 ,342,443,410 }, {13,255,250 ,62,62,62 ,342,444,443 }, {90,13,91 ,234,164,165 ,364,342,410 }, {90,16,13 ,234,157,164 ,364,331,342 }, {9,109,99 ,152,237,232 ,327,429,391 }, {9,110,109 ,152,231,237 ,327,359,429 }, {19,110,9 ,154,231,152 ,329,359,327 }, {97,108,102 ,167,167,167 ,428,384,430 }, {97,93,108 ,167,167,167 ,428,411,384 }, {112,108,93 ,196,195,212 ,385,384,411 }, {113,248,237 ,76,76,76 ,377,445,446 }, {115,105,114 ,238,183,239 ,447,368,448 }, {115,76,105 ,238,236,183 ,447,438,368 }, {86,114,87 ,186,239,184 ,371,448,369 }, {86,115,114 ,186,238,239 ,371,447,448 }, {87,116,79 ,184,240,229 ,369,449,431 }, {87,114,116 ,184,239,240 ,369,448,449 }, {118,114,105 ,180,239,183 ,365,448,368 }, {118,116,114 ,180,240,239 ,365,449,448 }, {117,76,115 ,241,236,238 ,450,438,447 }, {117,104,76 ,241,235,236 ,450,437,438 }, {103,115,86 ,188,238,186 ,373,447,371 }, {103,117,115 ,188,241,238 ,373,450,447 }, {103,208,117 ,188,242,241 ,373,451,450 }, {103,207,208 ,188,205,242 ,373,398,451 }, {117,164,104 ,241,243,235 ,450,452,437 }, {117,208,164 ,241,242,243 ,450,453,452 }, {211,79,116 ,27,229,240 ,454,431,449 }, {211,210,79 ,27,43,229 ,454,405,431 }, {166,116,118 ,30,240,180 ,455,449,365 }, {166,211,116 ,30,27,240 ,455,456,449 }, {69,105,11 ,150,183,167 ,322,368,356 }, {69,75,105 ,150,181,183 ,322,366,368 }, {76,11,105 ,236,167,183 ,438,356,368 }, {76,12,11 ,236,159,167 ,438,332,356 }, {171,146,147 ,244,245,66 ,457,458,459 }, {171,160,146 ,244,246,245 ,457,460,458 }, {147,170,171 ,21,173,21 ,461,462,463 }, {147,161,170 ,21,21,173 ,461,464,462 }, {260,232,230 ,76,76,76 ,465,466,467 }, {260,243,232 ,76,76,76 ,465,468,466 }, {256,254,230 ,76,76,76 ,469,470,471 }, {232,242,194 ,21,116,21 ,472,473,474 }, {232,243,242 ,21,21,116 ,472,475,473 }, {168,160,171 ,247,246,244 ,476,477,478 }, {168,157,160 ,247,247,246 ,476,479,477 }, {256,119,255 ,76,76,76 ,480,481,482 }, {256,230,119 ,76,76,76 ,480,483,481 }, {220,230,221 ,76,76,76 ,484,485,486 }, {220,119,230 ,76,76,76 ,484,487,485 }, {254,260,230 ,76,76,76 ,488,489,490 }, {120,131,127 ,248,249,248 ,491,492,493 }, {120,125,131 ,248,250,249 ,491,494,492 }, {130,123,129 ,251,252,252 ,495,496,497 }, {130,124,123 ,251,253,252 ,495,498,496 }, {123,128,129 ,254,255,256 ,496,499,497 }, {123,122,128 ,254,257,255 ,496,500,499 }, {201,130,203 ,78,251,63 ,501,495,502 }, {201,124,130 ,78,253,251 ,501,498,495 }, {125,187,131 ,250,68,249 ,494,503,492 }, {125,185,187 ,250,74,68 ,494,504,503 }, {121,127,126 ,258,259,260 ,505,493,506 }, {121,120,127 ,258,261,259 ,505,491,493 }, {122,194,128 ,257,262,255 ,500,507,499 }, {122,193,194 ,257,263,262 ,500,508,507 }, {121,178,177 ,258,264,265 ,505,509,510 }, {121,126,178 ,258,260,264 ,505,506,509 }, {130,213,214 ,21,121,172 ,495,511,512 }, {130,129,213 ,21,21,121 ,495,497,511 }, {203,130,202 ,21,21,21 ,513,495,514 }, {202,130,214 ,21,21,172 ,515,516,517 }, {131,187,186 ,21,21,21 ,492,518,519 }, {186,202,214 ,21,21,172 ,520,521,522 }, {131,186,214 ,21,21,172 ,492,523,524 }, {170,131,214 ,173,21,172 ,525,492,526 }, {170,127,131 ,173,21,21 ,525,493,492 }, {213,128,212 ,121,21,119 ,527,499,528 }, {213,129,128 ,121,21,21 ,527,497,499 }, {212,194,242 ,119,21,116 ,529,530,531 }, {212,128,194 ,119,21,21 ,529,499,530 }, {170,126,127 ,173,21,21 ,462,506,493 }, {178,170,161 ,21,173,21 ,532,533,534 }, {178,126,170 ,21,21,173 ,532,506,533 }, {140,165,139 ,266,267,66 ,535,536,537 }, {140,153,165 ,266,268,267 ,535,538,536 }, {164,139,165 ,243,0,0 ,539,540,541 }, {164,152,139 ,243,0,0 ,539,542,540 }, {224,248,228 ,76,76,76 ,543,544,545 }, {224,237,248 ,76,76,76 ,543,546,544 }, {251,250,228 ,76,76,76 ,547,548,549 }, {236,224,190 ,200,0,0 ,550,551,552 }, {236,237,224 ,200,0,0 ,550,553,551 }, {153,168,165 ,268,247,267 ,554,555,556 }, {153,157,168 ,268,247,247 ,554,557,555 }, {119,250,255 ,76,76,76 ,481,558,559 }, {119,228,250 ,76,76,76 ,481,560,558 }, {228,220,218 ,76,76,76 ,561,562,563 }, {228,119,220 ,76,76,76 ,561,564,562 }, {248,251,228 ,76,76,76 ,565,566,567 }, {137,120,133 ,249,248,248 ,568,491,569 }, {137,125,120 ,249,250,248 ,568,494,491 }, {123,136,135 ,252,251,252 ,496,570,571 }, {123,124,136 ,252,253,251 ,496,498,570 }, {134,123,135 ,269,254,256 ,572,496,571 }, {134,122,123 ,269,257,254 ,572,500,496 }, {136,201,198 ,251,78,87 ,570,573,574 }, {136,124,201 ,251,253,78 ,570,498,573 }, {182,125,137 ,79,250,249 ,575,494,568 }, {182,185,125 ,79,74,250 ,575,576,494 }, {133,121,132 ,270,258,271 ,569,505,577 }, {133,120,121 ,270,261,258 ,569,491,505 }, {190,122,134 ,272,257,269 ,578,500,572 }, {190,193,122 ,272,263,257 ,578,579,500 }, {174,121,177 ,273,258,265 ,580,505,581 }, {174,132,121 ,273,271,258 ,580,577,505 }, {207,136,208 ,205,0,242 ,582,570,583 }, {207,135,136 ,205,0,0 ,582,571,570 }, {136,198,197 ,0,0,0 ,570,584,585 }, {136,197,208 ,0,0,242 ,570,586,587 }, {182,137,181 ,0,0,0 ,588,568,589 }, {197,181,208 ,0,0,242 ,590,591,592 }, {181,137,208 ,0,0,242 ,593,568,592 }, {137,164,208 ,0,243,242 ,568,594,595 }, {137,133,164 ,0,0,243 ,568,569,594 }, {134,207,206 ,0,205,203 ,572,596,597 }, {134,135,207 ,0,0,205 ,572,571,596 }, {190,206,236 ,0,203,200 ,598,599,600 }, {190,134,206 ,0,0,203 ,598,572,599 }, {132,164,133 ,0,243,0 ,577,601,569 }, {164,174,152 ,243,0,0 ,602,603,604 }, {164,132,174 ,243,0,0 ,602,577,603 }, {147,145,161 ,21,21,21 ,605,606,607 }, {138,139,152 ,0,0,0 ,608,540,609 } }; static GLfloat vertices [262][3] = { {0.0f,-3.49998f,0.35235f},{-0.789509f,-3.40949f,-1.38255f},{0.0f,-3.5f,-1.33903f}, {0.790101f,-3.40936f,-1.38255f},{0.0f,-3.42929f,1.60235f},{0.0f,0.775f,0.00235001f}, {0.0f,0.775f,0.35235f},{0.0f,-0.775f,0.00235001f},{0.0f,-0.775f,0.35235f}, {0.0f,-3.4799f,-1.92265f},{0.0f,3.44142f,-1.93907f},{0.0f,2.58603f,-1.99765f}, {0.0f,2.05f,-1.99765f},{0.0f,-2.55f,-1.84765f},{0.0f,1.9f,-1.84765f}, {0.0f,1.93867f,-1.94817f},{0.0f,-2.59428f,-1.95406f},{0.0f,-2.7f,-1.99765f}, {0.0f,-2.75f,-1.99765f},{0.0f,-3.4f,-1.98255f},{-1.1183f,3.25465f,-1.93907f}, {-2.15607f,-1.6893f,-1.40561f},{-2.12344f,-1.51075f,-1.93083f},{-1.84393f,-1.6893f,-1.40561f}, {-1.87653f,-1.47911f,-1.95856f},{-1.0865f,3.11599f,-1.99765f},{-1.95f,2.05f,-1.99765f}, {-1.84393f,-1.51498f,-1.86148f},{-2.15607f,-1.51498f,-1.86148f},{-2.15607f,-1.40982f,-1.95372f}, {-2.05f,-1.50873f,-1.96042f},{-1.95f,-1.50873f,-1.96042f},{-1.95f,-1.731f,-1.42385f}, {-1.95f,-1.55854f,-1.86722f},{-2.05f,-1.55854f,-1.86722f},{-2.05f,-1.73096f,-1.42391f}, {-1.95f,-1.40982f,-1.99765f},{-2.05f,-1.40982f,-1.99765f},{-1.95f,-2.08797f,-1.11079f}, {-2.05f,-2.08779f,-1.11088f},{-0.800937f,-2.5946f,-1.95438f},{-0.811314f,-2.55f,-1.84765f}, {-0.8f,-2.7f,-1.99765f},{-0.811314f,-2.9f,-1.84765f},{-0.800937f,-2.8554f,-1.95438f}, {-0.8f,-2.75f,-1.99765f},{-0.2f,-2.85603f,-1.95375f},{-0.2f,-2.9f,-1.84765f}, {-0.2f,-2.75f,-1.99765f},{-0.802028f,-3.37875f,-1.934f},{-0.802002f,-3.22955f,-1.9344f}, {-0.2f,-3.32142f,-1.93412f},{-0.2f,-3.29393f,-1.84765f},{-1.83058f,-1.40982f,-1.93842f}, {-1.83867f,1.93867f,-1.94817f},{-2.05f,2.58603f,-1.99765f},{-1.84393f,-2.04195f,-1.04672f}, {-2.15607f,-2.04195f,-1.04672f},{-0.811314f,-3.19871f,-1.84765f},{-0.800037f,-3.30454f,-1.98904f}, {-0.2f,-3.39411f,-1.98907f},{-1.28094f,-3.04125f,-1.14291f},{-0.998289f,-3.14538f,-1.39994f}, {-1.8f,-2.7f,-0.99765f},{-2.05f,0.0f,-1.99765f},{-1.95f,0.0f,-1.99765f}, {-2.15607f,0.0f,-1.95372f},{-1.83398f,0.0f,-1.94253f},{-2.15607f,2.66025f,-1.93818f}, {0.0f,3.29998f,-1.99765f},{1.1183f,3.25465f,-1.93907f},{2.15607f,-1.6893f,-1.40561f}, {2.12344f,-1.51075f,-1.93083f},{1.84393f,-1.6893f,-1.40561f},{1.87653f,-1.47911f,-1.95856f}, {1.0865f,3.11599f,-1.99765f},{1.95f,2.05f,-1.99765f},{1.84393f,-1.51498f,-1.86148f}, {2.15607f,-1.51498f,-1.86148f},{2.15607f,-1.40982f,-1.95372f},{2.05f,-1.50873f,-1.96042f}, {1.95f,-1.50873f,-1.96042f},{1.95f,-1.731f,-1.42385f},{1.95f,-1.55854f,-1.86722f}, {2.05f,-1.55854f,-1.86722f},{2.05f,-1.73096f,-1.42391f},{1.95f,-1.40982f,-1.99765f}, {2.05f,-1.40982f,-1.99765f},{1.95f,-2.08797f,-1.11079f},{2.05f,-2.08779f,-1.11088f}, {0.800937f,-2.5946f,-1.95438f},{0.811314f,-2.55f,-1.84765f},{0.8f,-2.7f,-1.99765f}, {0.811314f,-2.9f,-1.84765f},{0.800937f,-2.8554f,-1.95438f},{0.8f,-2.75f,-1.99765f}, {0.2f,-2.85603f,-1.95375f},{0.2f,-2.9f,-1.84765f},{0.2f,-2.75f,-1.99765f}, {0.802028f,-3.37875f,-1.934f},{0.802002f,-3.22955f,-1.9344f},{0.2f,-3.32142f,-1.93412f}, {0.2f,-3.29393f,-1.84765f},{1.83058f,-1.40982f,-1.93842f},{1.83867f,1.93867f,-1.94817f}, {2.05f,2.58603f,-1.99765f},{1.84393f,-2.04195f,-1.04672f},{2.15607f,-2.04195f,-1.04672f}, {0.811314f,-3.19871f,-1.84765f},{0.800037f,-3.30454f,-1.98904f},{0.2f,-3.39411f,-1.98907f}, {1.28094f,-3.04125f,-1.14291f},{0.998289f,-3.14538f,-1.39994f},{1.8f,-2.7f,-0.99765f}, {2.05f,0.0f,-1.99765f},{1.95f,0.0f,-1.99765f},{2.15607f,0.0f,-1.95372f}, {1.83398f,0.0f,-1.94253f},{2.15607f,2.66025f,-1.93818f},{0.0f,-2.7f,0.35235f}, {0.0f,1.0f,-0.74765f},{0.0f,1.18582f,-0.392925f},{0.0f,-1.18582f,-0.392925f}, {0.0f,-1.0f,-0.74765f},{0.0f,-0.672987f,-0.697837f},{0.0f,0.672987f,-0.697837f}, {-1.8f,1.1858f,-0.392915f},{-1.8f,1.0f,-0.74765f},{-1.8f,-1.1858f,-0.392915f}, {-1.8f,-1.0f,-0.74765f},{-1.8f,-0.672987f,-0.697837f},{-1.8f,0.672987f,-0.697837f}, {1.8f,1.1858f,-0.392915f},{1.8f,1.0f,-0.74765f},{1.8f,-1.1858f,-0.392915f}, {1.8f,-1.0f,-0.74765f},{1.8f,-0.672987f,-0.697837f},{1.8f,0.672987f,-0.697837f}, {1.8f,2.15f,1.60235f},{1.8f,2.67f,1.60235f},{1.4f,2.67f,1.60235f}, {1.4f,3.2078f,1.60235f},{2.18467f,2.71558f,1.60235f},{2.2f,2.15f,1.60235f}, {1.78458f,3.01085f,1.60235f},{-1.8f,2.15f,1.60235f},{-1.4f,2.67f,1.60235f}, {-1.8f,2.67f,1.60235f},{-1.4f,3.2078f,1.60235f},{-2.2f,2.15f,1.60235f}, {-2.18467f,2.71558f,1.60235f},{-1.78458f,3.01085f,1.60235f},{1.8f,2.15f,0.35235f}, {1.4f,2.7f,0.35235f},{2.2f,2.15f,0.35235f},{1.4f,3.2078f,0.35235f}, {0.948198f,3.36911f,0.35235f},{0.0f,2.7f,0.35235f},{-0.948198f,3.36911f,0.35235f}, {0.0f,3.48711f,0.35235f},{-1.4f,2.7f,0.35235f},{-1.8f,2.15f,0.35235f}, {-2.2f,2.15f,0.35235f},{-1.4f,3.2078f,0.35235f},{1.8f,1.9f,-1.84765f}, {1.8f,2.67f,-1.84765f},{2.18466f,2.7156f,-1.79765f},{1.13241f,3.31174f,-1.79765f}, {0.0f,2.67f,-1.84765f},{0.0f,3.5f,-1.79765f},{-1.8f,1.9f,-1.84765f}, {-1.8f,2.67f,-1.84765f},{-2.18466f,2.7156f,-1.79765f},{-1.13241f,3.31174f,-1.79765f}, {1.8f,1.25f,0.35235f},{2.2f,0.775f,0.35235f},{2.2f,0.775f,0.00235001f}, {0.0f,1.25f,0.35235f},{-1.8f,1.25f,0.35235f},{-2.2f,0.775f,0.00235001f}, {-2.2f,0.775f,0.35235f},{1.8f,0.2465f,-0.732382f},{1.8f,0.606556f,-0.572051f}, {2.2f,0.239526f,-0.734681f},{2.2f,0.627035f,-0.453101f},{0.0f,0.606556f,-0.572051f}, {-1.8f,0.2465f,-0.732382f},{-1.8f,0.606556f,-0.572051f},{-2.2f,0.239526f,-0.734681f}, {-2.2f,0.627035f,-0.453101f},{1.8f,-1.25f,0.35235f},{2.2f,-0.775f,0.35235f}, {2.2f,-0.775f,0.00235001f},{0.0f,-1.25f,0.35235f},{-1.8f,-1.25f,0.35235f}, {-2.2f,-0.775f,0.35235f},{-2.2f,-0.775f,0.00235001f},{1.8f,-0.246935f,-0.732237f}, {1.8f,-0.606556f,-0.572051f},{2.2f,-0.239526f,-0.734681f},{2.2f,-0.627035f,-0.453101f}, {0.0f,-0.606556f,-0.572051f},{-1.8f,-0.246935f,-0.732237f},{-1.8f,-0.606556f,-0.572051f}, {-2.2f,-0.239526f,-0.734681f},{-2.2f,-0.627035f,-0.453101f},{1.8f,-1.60818f,-1.33776f}, {1.8f,-1.40982f,-1.84765f},{1.8f,0.0f,-1.84765f},{2.2f,-1.6081f,-1.33787f}, {2.2f,-1.40982f,-1.84765f},{2.2f,0.0f,-1.84765f},{-1.8f,-1.60818f,-1.33776f}, {-1.8f,-1.40982f,-1.84765f},{-1.8f,0.0f,-1.84765f},{-2.2f,-1.6081f,-1.33787f}, {-2.2f,-1.40982f,-1.84765f},{-2.2f,0.0f,-1.84765f},{0.7f,-2.7f,1.60235f}, {0.7f,-3.42929f,1.60235f},{0.0f,-2.7f,1.60235f},{-0.7f,-2.7f,1.60235f}, {0.0f,-3.49997f,1.60235f},{-0.7f,-3.42929f,1.60235f},{1.8f,-2.7f,0.35235f}, {1.45894f,-3.18143f,0.35235f},{2.14179f,-2.76816f,0.35235f},{2.2f,-2.64953f,0.35235f}, {0.7f,-2.7f,0.35235f},{0.7f,-3.42929f,0.35235f},{-0.7f,-2.7f,0.35235f}, {-0.7f,-3.42929f,0.35235f},{-1.8f,-2.7f,0.35235f},{-1.45894f,-3.18143f,0.35235f}, {-2.2f,-2.64953f,0.35235f},{-2.14179f,-2.76816f,0.35235f},{1.8f,-2.01865f,-0.97777f}, {1.8f,-2.7f,-0.84765f},{1.92676f,-2.92192f,-0.99765f},{2.2f,-2.01835f,-0.977926f}, {2.2f,-2.64953f,-0.84765f},{2.14179f,-2.76816f,-0.966286f},{-1.8f,-2.01865f,-0.97777f}, {-1.8f,-2.7f,-0.84765f},{-1.92676f,-2.92192f,-0.99765f},{-2.2f,-2.01835f,-0.977926f}, {-2.2f,-2.64953f,-0.84765f},{-2.14179f,-2.76816f,-0.966286f},{1.34394f,-2.7f,-1.1077f}, {1.35582f,-3.22672f,-1.10171f},{0.811314f,-2.7f,-1.84765f},{0.988348f,-2.7f,-1.41351f}, {0.811314f,-3.40467f,-1.84765f},{0.994882f,-3.35562f,-1.40454f},{-0.988348f,-2.7f,-1.41351f}, {0.0f,-2.7f,-1.84765f},{-0.811314f,-2.7f,-1.84765f},{-0.994882f,-3.35562f,-1.40454f}, {0.0f,-3.5f,-1.84765f},{-0.811314f,-3.40467f,-1.84765f},{-1.34394f,-2.7f,-1.1077f}, {-1.35582f,-3.22672f,-1.10171f} }; static GLfloat normals [274][3] = { {-1.0f,0.0f,0.0f},{-0.999984f,0.00519551f,-0.00232515f},{-0.980741f,0.00304722f,-0.195287f}, {-0.999982f,0.00321145f,-0.0050577f},{-0.999901f,0.0139735f,-0.00167206f},{-0.936619f,0.325635f,-0.129252f}, {-0.635574f,-0.772028f,0.00417741f},{-0.374979f,-0.926692f,0.0251491f},{-0.416825f,-0.908986f,-0.00124481f}, {-0.525586f,-0.850639f,0.0131636f},{-0.172574f,-0.984996f,0.00117284f},{-0.210513f,-0.977414f,0.0185848f}, {-0.258321f,-0.96481f,0.0491156f},{-0.988643f,-0.150284f,0.0f},{-0.823776f,-0.351623f,-0.444696f}, {-0.975233f,-0.179062f,-0.129837f},{-0.980566f,-0.16978f,-0.0983098f},{-0.952236f,-0.138993f,-0.271897f}, {-0.976766f,-0.13269f,-0.168292f},{-0.877679f,0.478993f,-0.0156877f},{-0.999633f,0.0270911f,0.0f}, {1.0f,0.0f,0.0f},{-1.87212e-009f,-1.0f,3.52859e-006f},{-0.100472f,-0.99494f,0.0f}, {0.0229096f,-0.999737f,-0.0012419f},{-0.014379f,-0.999894f,-0.00219243f},{0.999984f,0.00519551f,-0.00232515f}, {0.980741f,0.00304722f,-0.195287f},{0.999901f,0.0139735f,-0.00167206f},{0.999982f,0.00321145f,-0.0050577f}, {0.936619f,0.325635f,-0.129252f},{0.375017f,-0.926677f,0.0251251f},{0.635574f,-0.772028f,0.00417741f}, {0.416825f,-0.908986f,-0.00124481f},{0.525586f,-0.850639f,0.0131636f},{0.184376f,-0.982855f,0.00126651f}, {0.19241f,-0.981194f,0.0153646f},{0.258434f,-0.964785f,0.0490148f},{0.823776f,-0.351623f,-0.444696f}, {0.988643f,-0.150284f,0.0f},{0.975233f,-0.179062f,-0.129837f},{0.980566f,-0.16978f,-0.0983098f}, {0.952236f,-0.138993f,-0.271897f},{0.976766f,-0.13269f,-0.168292f},{0.877679f,0.478993f,-0.0156877f}, {0.999633f,0.0270911f,0.0f},{0.100472f,-0.99494f,0.0f},{-0.150459f,-0.985712f,-0.0757187f}, {-1.26142e-009f,-0.982267f,-0.187487f},{0.150508f,-0.985707f,-0.0756957f},{-0.48425f,0.874812f,-0.0143577f}, {-0.3013f,0.931914f,-0.201876f},{-0.231256f,0.972873f,-0.00614353f},{-0.526289f,0.849844f,-0.0280189f}, {1.88271e-009f,0.999987f,-0.00504398f},{0.0f,0.981327f,-0.192344f},{0.3013f,0.931914f,-0.201876f}, {0.48425f,0.874812f,-0.0143577f},{0.231256f,0.972873f,-0.00614353f},{0.526289f,0.849844f,-0.0280189f}, {-0.455821f,0.890072f,0.0f},{0.455821f,0.890072f,0.0f},{0.0f,0.0f,1.0f}, {0.0657879f,0.952791f,0.296413f},{0.10445f,0.69044f,0.715809f},{0.0109124f,0.988743f,0.149229f}, {0.0f,-1.0f,0.0f},{0.104335f,-0.690422f,0.715843f},{0.0695468f,-0.988856f,0.131634f}, {0.0108787f,-0.975504f,0.219712f},{0.0618815f,-0.25638f,0.964593f},{-7.68889e-005f,-0.309048f,0.951047f}, {-0.00205735f,0.204931f,0.978774f},{0.0844502f,0.341379f,0.936124f},{0.0f,-0.999417f,0.0341539f}, {0.0f,-0.99551f,0.0946543f},{0.0f,1.0f,0.0f},{0.0f,0.981918f,0.189309f}, {0.0f,0.972561f,-0.232648f},{-0.0695468f,-0.988856f,0.131634f},{-0.104335f,-0.690422f,0.715843f}, {-0.0108787f,-0.975504f,0.219712f},{-0.0618815f,-0.25638f,0.964593f},{7.68889e-005f,-0.309048f,0.951047f}, {0.00205735f,0.204931f,0.978774f},{-0.0844502f,0.341379f,0.936124f},{-0.10445f,0.69044f,0.715809f}, {-0.0657879f,0.952791f,0.296413f},{-0.0109124f,0.988743f,0.149229f},{-2.695e-006f,-0.70594f,-0.708272f}, {0.000192697f,-0.262692f,-0.96488f},{-5.38999e-006f,-0.707003f,-0.707211f},{0.0f,-0.128752f,-0.991677f}, {-0.999766f,0.0f,-0.0216409f},{-0.998243f,0.0f,-0.0592487f},{-0.997421f,0.0f,-0.0717738f}, {-0.110602f,0.30484f,-0.94596f},{-0.5256f,0.388284f,-0.756954f},{-0.238354f,0.664347f,-0.7084f}, {-0.104052f,0.0586272f,-0.992842f},{0.125063f,-0.459593f,-0.87928f},{-0.217416f,-0.199415f,-0.955492f}, {0.180023f,-0.139748f,-0.973685f},{-0.1298f,-0.788311f,-0.60143f},{0.652009f,-0.0742063f,-0.754571f}, {-0.116753f,0.347918f,-0.930227f},{0.447525f,0.0067279f,-0.894246f},{-0.0972002f,-0.0882603f,-0.991344f}, {-0.485837f,0.0128693f,-0.873955f},{-0.443782f,-0.019869f,-0.895914f},{-0.948313f,-0.00164689f,-0.317333f}, {-0.808553f,0.0200673f,-0.588081f},{-0.858391f,8.64955e-005f,-0.512997f},{-0.979669f,-3.89778e-005f,-0.20062f}, {-0.996525f,-1.42301e-005f,-0.0832893f},{-0.997437f,-2.13467e-005f,-0.0715458f},{0.978716f,-0.0949488f,-0.181931f}, {0.67714f,-0.343528f,-0.650745f},{0.686377f,-0.616067f,-0.386455f},{0.980566f,-0.169777f,-0.0983178f}, {0.74217f,-0.592683f,-0.312907f},{0.977835f,-0.147992f,-0.148113f},{0.639882f,-0.647718f,-0.413536f}, {-0.715589f,-0.549052f,-0.431825f},{-0.73778f,-0.301487f,-0.603976f},{-0.610268f,-0.733583f,-0.299047f}, {-0.97708f,0.00185179f,-0.212865f},{-0.995307f,0.0f,-0.0967725f},{-0.956401f,0.0f,-0.292057f}, {-0.768622f,-0.0137886f,-0.639555f},{-0.456092f,0.00761986f,-0.8899f},{-0.315155f,-0.404027f,-0.858743f}, {0.242533f,-0.386677f,-0.889752f},{-0.197382f,-0.801534f,-0.564432f},{0.24008f,-0.806336f,-0.54054f}, {-0.149757f,-0.90336f,-0.401889f},{0.214947f,-0.884715f,-0.413614f},{0.00361947f,-0.998239f,-0.0592032f}, {-0.000289462f,-0.923248f,-0.384205f},{0.0f,-0.922669f,-0.385593f},{-0.99935f,7.32087e-005f,-0.0360433f}, {0.145011f,0.940077f,-0.308588f},{0.132303f,0.859023f,-0.494545f},{0.145949f,0.936997f,-0.317387f}, {0.112723f,0.742104f,-0.660738f},{-0.647982f,-0.349544f,-0.676712f},{-0.75514f,-0.147652f,-0.638719f}, {0.0898762f,0.594363f,-0.799159f},{0.00381381f,-0.184719f,-0.982784f},{0.0f,0.703645f,-0.710552f}, {0.0f,0.129579f,-0.991569f},{-0.102191f,-0.87449f,-0.474155f},{3.63993e-010f,-0.758864f,-0.651249f}, {0.0f,-0.0121772f,-0.999926f},{-2.44554e-010f,-0.327201f,-0.944955f},{0.0f,0.129244f,-0.991613f}, {7.33698e-005f,0.257996f,-0.966146f},{0.0f,0.602021f,-0.79848f},{-7.75359e-008f,0.795583f,-0.605844f}, {0.0f,-0.276074f,-0.961136f},{0.326394f,-0.425868f,-0.843862f},{0.143616f,-0.0702339f,-0.987138f}, {0.0f,-0.812299f,-0.583242f},{0.0f,-0.933328f,-0.359024f},{0.0f,0.922958f,-0.384901f}, {0.0f,0.922669f,-0.385593f},{-0.0891187f,-0.681542f,-0.726332f},{0.0f,0.0f,-1.0f}, {0.222711f,-0.000272707f,-0.974885f},{-0.214215f,0.000921458f,-0.976786f},{-0.728642f,0.00345042f,-0.684886f}, {0.735846f,-0.00014084f,-0.677148f},{0.992044f,0.00016362f,-0.125893f},{0.99694f,0.000135919f,-0.0781646f}, {-0.000192697f,-0.262692f,-0.96488f},{2.695e-006f,-0.70594f,-0.708272f},{5.38999e-006f,-0.707003f,-0.707211f}, {0.998243f,0.0f,-0.0592487f},{0.999766f,0.0f,-0.0216409f},{0.997421f,0.0f,-0.0717738f}, {0.5256f,0.388284f,-0.756954f},{0.110602f,0.30484f,-0.94596f},{0.238354f,0.664347f,-0.7084f}, {0.104052f,0.0586272f,-0.992842f},{0.217416f,-0.199415f,-0.955492f},{-0.125063f,-0.459593f,-0.87928f}, {-0.180023f,-0.139748f,-0.973685f},{0.1298f,-0.788311f,-0.60143f},{-0.652009f,-0.0742063f,-0.754571f}, {0.116753f,0.347918f,-0.930227f},{-0.447525f,0.0067279f,-0.894246f},{0.0972002f,-0.0882603f,-0.991344f}, {0.485837f,0.0128693f,-0.873955f},{0.443782f,-0.019869f,-0.895914f},{0.808553f,0.0200673f,-0.588081f}, {0.948313f,-0.00164689f,-0.317333f},{0.858391f,8.64955e-005f,-0.512997f},{0.979669f,-3.89778e-005f,-0.20062f}, {0.996525f,-1.42301e-005f,-0.0832893f},{0.997437f,-2.13467e-005f,-0.0715458f},{-0.978716f,-0.0949488f,-0.181931f}, {-0.67714f,-0.343528f,-0.650745f},{-0.686377f,-0.616067f,-0.386455f},{-0.980566f,-0.169777f,-0.0983178f}, {-0.74217f,-0.592683f,-0.312907f},{-0.977835f,-0.147992f,-0.148113f},{-0.639882f,-0.647718f,-0.413536f}, {0.715589f,-0.549052f,-0.431825f},{0.73778f,-0.301487f,-0.603976f},{0.610268f,-0.733583f,-0.299047f}, {0.97708f,0.00185179f,-0.212865f},{0.995307f,0.0f,-0.0967725f},{0.956401f,0.0f,-0.292057f}, {0.768622f,-0.0137886f,-0.639555f},{0.456092f,0.00761986f,-0.8899f},{0.315155f,-0.404027f,-0.858743f}, {-0.242533f,-0.386677f,-0.889752f},{0.197382f,-0.801534f,-0.564432f},{-0.24008f,-0.806336f,-0.54054f}, {0.149757f,-0.90336f,-0.401889f},{-0.214947f,-0.884715f,-0.413614f},{-0.00361947f,-0.998239f,-0.0592032f}, {0.000289462f,-0.923248f,-0.384205f},{0.99935f,7.32087e-005f,-0.0360433f},{-0.132303f,0.859023f,-0.494545f}, {-0.145011f,0.940077f,-0.308588f},{-0.145949f,0.936997f,-0.317387f},{-0.112723f,0.742104f,-0.660738f}, {0.647982f,-0.349544f,-0.676712f},{0.75514f,-0.147652f,-0.638719f},{-0.0898762f,0.594363f,-0.799159f}, {-0.00381381f,-0.184719f,-0.982784f},{0.102191f,-0.87449f,-0.474155f},{-7.33698e-005f,0.257996f,-0.966146f}, {7.75359e-008f,0.795583f,-0.605844f},{-0.326394f,-0.425868f,-0.843862f},{-0.143616f,-0.0702339f,-0.987138f}, {0.0891187f,-0.681542f,-0.726332f},{-0.222711f,-0.000272707f,-0.974885f},{0.214215f,0.000921458f,-0.976786f}, {0.728642f,0.00345042f,-0.684886f},{-0.735846f,-0.00014084f,-0.677148f},{-0.992044f,0.00016362f,-0.125893f}, {-0.99694f,0.000135919f,-0.0781646f},{0.0678716f,-0.997689f,-0.00330243f},{0.101862f,-0.994729f,-0.0118101f}, {0.0678741f,-0.997693f,0.00126437f},{0.0f,-0.999907f,0.0136353f},{0.0f,-0.150591f,-0.988596f}, {0.0f,-0.436386f,-0.89976f},{0.0f,-0.706465f,-0.707748f},{0.0f,0.579434f,-0.815019f}, {0.0f,0.150591f,-0.988596f},{0.0f,0.579434f,-0.815019f},{0.0f,-0.885832f,-0.464006f}, {-1.14482e-005f,-0.938995f,-0.343931f},{0.0f,-0.88585f,-0.463972f},{0.0f,-0.976473f,-0.215641f}, {0.0f,0.959882f,-0.280404f},{-8.40575e-006f,0.885832f,-0.464005f},{-1.702e-005f,0.959885f,-0.280395f}, {0.0f,0.885815f,-0.464039f},{-8.37983e-006f,-0.996311f,-0.0858118f},{0.0f,-0.996313f,-0.0857917f}, {-8.28085e-006f,0.996311f,-0.085812f},{0.0f,0.996313f,-0.0857922f},{-0.101862f,-0.994729f,-0.0118101f}, {-0.0678716f,-0.997689f,-0.00330243f},{-0.0678741f,-0.997693f,0.00126437f},{1.14482e-005f,-0.938995f,-0.343931f}, {8.40575e-006f,0.885832f,-0.464005f},{1.702e-005f,0.959885f,-0.280395f},{8.37983e-006f,-0.996311f,-0.0858118f}, {8.28085e-006f,0.996311f,-0.085812f} }; static GLfloat textures [610][2] = { {0.340065f,0.804648f},{0.328884f,0.804648f},{0.334475f,0.764f}, {0.317013f,0.831565f},{0.294577f,0.844348f},{0.28842f,0.765826f}, {0.317013f,0.844348f},{0.0575824f,0.844348f},{0.0710239f,0.791243f}, {0.0693647f,0.844348f},{0.061477f,0.795044f},{0.0811505f,0.844348f}, {0.0798001f,0.780986f},{0.0766721f,0.780183f},{0.055806f,0.844348f}, {0.0575824f,0.796189f},{0.055806f,0.800522f},{0.0430913f,0.782618f}, {0.0280116f,0.831565f},{0.0488222f,0.795764f},{0.039931f,0.764f}, {0.0248645f,0.814931f},{0.28842f,0.89f},{0.294577f,0.89f}, {0.0161413f,0.804648f},{0.32016f,0.814931f},{0.0105503f,0.764f}, {0.0915314f,0.89f},{0.0811505f,0.89f},{0.0915314f,0.844348f}, {0.0915314f,0.782576f},{0.178103f,0.804648f},{0.166921f,0.804648f}, {0.172512f,0.764f},{0.21241f,0.844348f},{0.189974f,0.831565f}, {0.218567f,0.765826f},{0.189974f,0.844348f},{0.112039f,0.791243f}, {0.12548f,0.844348f},{0.113698f,0.844348f},{0.121586f,0.795044f}, {0.101912f,0.844348f},{0.103272f,0.780986f},{0.106391f,0.780183f}, {0.12548f,0.796189f},{0.127257f,0.844348f},{0.127257f,0.800522f}, {0.139971f,0.782618f},{0.155051f,0.831565f},{0.134241f,0.795764f}, {0.143132f,0.764f},{0.158198f,0.814931f},{0.218567f,0.89f}, {0.21241f,0.89f},{0.186827f,0.814931f},{0.101912f,0.89f}, {0.0794712f,0.764f},{0.0915314f,0.764f},{0.103592f,0.764f}, {0.274709f,0.844348f},{0.270479f,0.765826f},{0.267637f,0.844348f}, {0.281077f,0.89f},{0.253494f,0.844348f},{0.253494f,0.765826f}, {0.236508f,0.765826f},{0.232278f,0.844348f},{0.23935f,0.844348f}, {0.22591f,0.89f},{0.0280116f,0.844348f},{0.155051f,0.844348f}, {0.274709f,0.89f},{0.232278f,0.89f},{0.008048f,0.861444f}, {0.00884048f,0.860022f},{0.0134938f,0.860839f},{0.0671595f,0.860022f}, {0.067952f,0.861444f},{0.0625062f,0.860839f},{0.0134938f,0.887895f}, {0.008048f,0.887711f},{0.008048f,0.886381f},{0.0475302f,0.860839f}, {0.0439019f,0.852099f},{0.0475302f,0.852099f},{0.0439019f,0.860839f}, {0.0250907f,0.933573f},{0.0189396f,0.93164f},{0.038f,0.934748f}, {0.0165435f,0.925242f},{0.0189396f,0.93164f},{0.0165435f,0.928851f}, {0.0189396f,0.925555f},{0.008048f,0.902485f},{0.0134938f,0.918963f}, {0.008048f,0.918963f},{0.0134938f,0.908177f},{0.0134938f,0.918963f}, {0.0104442f,0.921752f},{0.008048f,0.918963f},{0.0134938f,0.921752f}, {0.0181371f,0.85507f},{0.0284698f,0.852099f},{0.00884048f,0.860022f}, {0.0284698f,0.860839f},{0.0134938f,0.860839f},{0.0284698f,0.852099f}, {0.00884048f,0.860022f},{0.0284698f,0.852099f},{0.0326563f,0.852099f}, {0.0284698f,0.860839f},{0.0284698f,0.852099f},{0.0326563f,0.860839f}, {0.008048f,0.861444f},{0.0134938f,0.878217f},{0.008048f,0.883909f}, {0.0134938f,0.860839f},{0.008048f,0.898983f},{0.0134938f,0.898799f}, {0.008048f,0.900313f},{0.0134938f,0.895562f},{0.008048f,0.898983f}, {0.008048f,0.8955f},{0.0134938f,0.898799f},{0.008048f,0.891194f}, {0.0134938f,0.895562f},{0.008048f,0.8955f},{0.0134938f,0.891127f}, {0.008048f,0.887711f},{0.0134938f,0.891127f},{0.008048f,0.891194f}, {0.0134938f,0.887895f},{0.0165435f,0.928851f},{0.0134938f,0.925242f}, {0.0165435f,0.925242f},{0.0136114f,0.92753f},{0.0104442f,0.921752f}, {0.0134938f,0.921752f},{0.010561f,0.925548f},{0.010561f,0.925548f}, {0.0134938f,0.925242f},{0.0136114f,0.92753f},{0.038f,0.934748f}, {0.0189396f,0.925555f},{0.038f,0.925555f},{0.0189396f,0.93164f}, {0.0382791f,0.851252f},{0.0382791f,0.852099f},{0.0326563f,0.852099f}, {0.0326563f,0.852099f},{0.0382791f,0.860839f},{0.0326563f,0.860839f}, {0.008048f,0.900313f},{0.038f,0.898799f},{0.038f,0.900313f}, {0.038f,0.883909f},{0.008048f,0.883909f},{0.038f,0.886381f}, {0.038f,0.902485f},{0.0134938f,0.908177f},{0.008048f,0.902485f}, {0.038f,0.908177f},{0.008048f,0.902485f},{0.038f,0.878217f}, {0.0134938f,0.878217f},{0.0134938f,0.887895f},{0.008048f,0.886381f}, {0.038f,0.887895f},{0.0570604f,0.93164f},{0.0509093f,0.933573f}, {0.038f,0.934748f},{0.0570604f,0.93164f},{0.0594565f,0.925242f}, {0.0594565f,0.928851f},{0.0570604f,0.925555f},{0.0625062f,0.918963f}, {0.067952f,0.902485f},{0.067952f,0.918963f},{0.0625062f,0.908177f}, {0.0655558f,0.921752f},{0.0625062f,0.918963f},{0.067952f,0.918963f}, {0.0625062f,0.921752f},{0.0475302f,0.852099f},{0.0578629f,0.85507f}, {0.0671595f,0.860022f},{0.0625062f,0.860839f},{0.0475302f,0.860839f}, {0.0671595f,0.860022f},{0.0625062f,0.860839f},{0.0475302f,0.852099f}, {0.0625062f,0.878217f},{0.067952f,0.861444f},{0.067952f,0.883909f}, {0.0625062f,0.860839f},{0.0625062f,0.898799f},{0.067952f,0.898983f}, {0.067952f,0.900313f},{0.067952f,0.898983f},{0.0625062f,0.895562f}, {0.067952f,0.8955f},{0.0625062f,0.895562f},{0.067952f,0.891194f}, {0.067952f,0.8955f},{0.0625062f,0.891127f},{0.0625062f,0.891127f}, {0.067952f,0.887711f},{0.067952f,0.891194f},{0.0625062f,0.887895f}, {0.0625062f,0.925242f},{0.0594565f,0.928851f},{0.0594565f,0.925242f}, {0.0623886f,0.92753f},{0.0655558f,0.921752f},{0.0625062f,0.925242f}, {0.0625062f,0.921752f},{0.065439f,0.925548f},{0.0625062f,0.925242f}, {0.065439f,0.925548f},{0.0623886f,0.92753f},{0.067952f,0.887711f}, {0.0625062f,0.887895f},{0.067952f,0.886381f},{0.0570604f,0.925555f}, {0.038f,0.934748f},{0.038f,0.925555f},{0.0570604f,0.93164f}, {0.0382791f,0.851252f},{0.0439019f,0.852099f},{0.0382791f,0.860839f}, {0.0439019f,0.860839f},{0.038f,0.898799f},{0.067952f,0.900313f}, {0.0625062f,0.898799f},{0.067952f,0.886381f},{0.0625062f,0.908177f}, {0.067952f,0.902485f},{0.038f,0.908177f},{0.067952f,0.902485f}, {0.038f,0.878217f},{0.067952f,0.883909f},{0.0625062f,0.878217f}, {0.0625062f,0.887895f},{0.067952f,0.886381f},{0.038f,0.887895f}, {0.162107f,0.851171f},{0.162107f,0.858711f},{0.162107f,0.850212f}, {0.162107f,0.857312f},{0.153415f,0.857321f},{0.153428f,0.858711f}, {0.153428f,0.859371f},{0.153415f,0.860762f},{0.149284f,0.936118f}, {0.133814f,0.930104f},{0.148824f,0.937948f},{0.135348f,0.929125f}, {0.136794f,0.875091f},{0.135348f,0.876396f},{0.136794f,0.876396f}, {0.135348f,0.875091f},{0.138522f,0.876396f},{0.137857f,0.875482f}, {0.14862f,0.938701f},{0.1334f,0.930835f},{0.13402f,0.858472f}, {0.138964f,0.859371f},{0.137131f,0.856443f},{0.137131f,0.856443f}, {0.146472f,0.854868f},{0.145389f,0.852421f},{0.153265f,0.85279f}, {0.15061f,0.85072f},{0.15056f,0.853494f},{0.153265f,0.850073f}, {0.145389f,0.852421f},{0.1534f,0.852383f},{0.153265f,0.850073f}, {0.153399f,0.850415f},{0.138964f,0.868362f},{0.138964f,0.859371f}, {0.138329f,0.868055f},{0.138329f,0.8735f},{0.138964f,0.873779f}, {0.138329f,0.875009f},{0.138964f,0.876396f},{0.138964f,0.876396f}, {0.133814f,0.8735f},{0.133178f,0.868366f},{0.133178f,0.87378f}, {0.133814f,0.868055f},{0.133814f,0.875009f},{0.133178f,0.876396f}, {0.133178f,0.868366f},{0.13402f,0.858472f},{0.133178f,0.860037f}, {0.153265f,0.859371f},{0.153265f,0.861351f},{0.153265f,0.856732f}, {0.153265f,0.859371f},{0.150704f,0.859371f},{0.145561f,0.859371f}, {0.150704f,0.859371f},{0.145561f,0.859371f},{0.13402f,0.858472f}, {0.135348f,0.86745f},{0.137131f,0.856443f},{0.13402f,0.858472f}, {0.136794f,0.867448f},{0.135348f,0.872158f},{0.136794f,0.872158f}, {0.135348f,0.874434f},{0.136794f,0.874434f},{0.134286f,0.875064f}, {0.137131f,0.856443f},{0.162107f,0.856732f},{0.153428f,0.851394f}, {0.162107f,0.851534f},{0.133814f,0.876396f},{0.133178f,0.876396f}, {0.165f,0.940413f},{0.165f,0.938546f},{0.14862f,0.938701f}, {0.165f,0.941186f},{0.165f,0.848815f},{0.153265f,0.850073f}, {0.165f,0.84908f},{0.165f,0.858711f},{0.165f,0.850134f}, {0.165f,0.859371f},{0.165f,0.860766f},{0.165f,0.922052f}, {0.138405f,0.920582f},{0.136794f,0.922052f},{0.165f,0.920582f}, {0.165f,0.920072f},{0.138964f,0.930233f},{0.138964f,0.920072f}, {0.165f,0.930233f},{0.138964f,0.920072f},{0.153265f,0.859371f}, {0.165f,0.861351f},{0.165f,0.859371f},{0.145561f,0.859371f}, {0.138964f,0.859371f},{0.136794f,0.895f},{0.135348f,0.895f}, {0.133814f,0.895f},{0.138472f,0.895f},{0.138964f,0.895f}, {0.138964f,0.920072f},{0.133178f,0.895f},{0.133178f,0.876396f}, {0.1334f,0.930835f},{0.133178f,0.895f},{0.165f,0.929125f}, {0.167893f,0.858711f},{0.167893f,0.851171f},{0.167893f,0.850212f}, {0.167893f,0.857312f},{0.176585f,0.857321f},{0.176572f,0.858711f}, {0.176572f,0.859371f},{0.176585f,0.860762f},{0.196186f,0.930104f}, {0.180716f,0.936118f},{0.181176f,0.937948f},{0.194652f,0.929125f}, {0.194652f,0.876396f},{0.193206f,0.875091f},{0.193206f,0.876396f}, {0.194652f,0.875091f},{0.191478f,0.876396f},{0.192143f,0.875482f}, {0.18138f,0.938701f},{0.1966f,0.930835f},{0.191036f,0.859371f}, {0.19598f,0.858472f},{0.192869f,0.856443f},{0.183528f,0.854868f}, {0.192869f,0.856443f},{0.184611f,0.852421f},{0.17939f,0.85072f}, {0.176735f,0.85279f},{0.17944f,0.853494f},{0.176735f,0.850073f}, {0.17939f,0.85072f},{0.184611f,0.852421f},{0.176735f,0.850073f}, {0.176601f,0.852383f},{0.176601f,0.850415f},{0.191036f,0.868362f}, {0.191036f,0.859371f},{0.191671f,0.868055f},{0.191671f,0.8735f}, {0.191036f,0.873779f},{0.191671f,0.875009f},{0.191036f,0.876396f}, {0.191036f,0.876396f},{0.196822f,0.868366f},{0.196186f,0.8735f}, {0.196822f,0.87378f},{0.196186f,0.868055f},{0.196186f,0.875009f}, {0.196822f,0.876396f},{0.19598f,0.858472f},{0.196822f,0.868366f}, {0.196822f,0.860037f},{0.176735f,0.859371f},{0.176735f,0.861351f}, {0.176735f,0.856732f},{0.176735f,0.859371f},{0.179296f,0.859371f}, {0.184439f,0.859371f},{0.179296f,0.859371f},{0.184439f,0.859371f}, {0.19598f,0.858472f},{0.194652f,0.86745f},{0.192869f,0.856443f}, {0.19598f,0.858472f},{0.193206f,0.867448f},{0.194652f,0.872158f}, {0.193206f,0.872158f},{0.194652f,0.874434f},{0.193206f,0.874434f}, {0.195714f,0.875064f},{0.192869f,0.856443f},{0.167893f,0.856732f}, {0.176572f,0.851394f},{0.167893f,0.851534f},{0.196186f,0.876396f}, {0.196822f,0.876396f},{0.18138f,0.938701f},{0.165f,0.941186f}, {0.165f,0.848815f},{0.176735f,0.850073f},{0.191595f,0.920582f}, {0.193206f,0.922052f},{0.191036f,0.930233f},{0.191036f,0.920072f}, {0.165f,0.930233f},{0.191036f,0.920072f},{0.176735f,0.859371f}, {0.165f,0.859371f},{0.184439f,0.859371f},{0.191036f,0.859371f}, {0.193206f,0.895f},{0.194652f,0.895f},{0.196186f,0.895f}, {0.191528f,0.895f},{0.191036f,0.895f},{0.191036f,0.920072f}, {0.191036f,0.895f},{0.196822f,0.895f},{0.1966f,0.930835f}, {0.196822f,0.895f},{0.28202f,0.9905f},{0.276337f,0.99941f}, {0.28202f,0.99941f},{0.277101f,0.990239f},{0.28202f,0.99941f}, {0.290538f,0.9905f},{0.28202f,0.9905f},{0.287374f,0.996384f}, {0.0656675f,0.985714f},{0.0651311f,0.974239f},{0.0789199f,0.974239f}, {0.0591638f,0.983435f},{0.074429f,0.9905f},{0.0713872f,0.988395f}, {0.0789199f,0.974239f},{0.0651311f,0.974239f},{0.051936f,0.984575f}, {0.0496316f,0.974239f},{0.0591638f,0.983435f},{0.25144f,0.9905f}, {0.276101f,0.966239f},{0.28202f,0.9905f},{0.25144f,0.966239f}, {0.074429f,0.9905f},{0.0893823f,0.974239f},{0.0894779f,0.9905f}, {0.0789199f,0.974239f},{0.0644779f,0.988f},{0.0539199f,0.991239f}, {0.0513999f,0.988f},{0.0643823f,0.991239f},{0.0713872f,0.988395f}, {0.0656675f,0.985714f},{0.0789199f,0.974239f},{0.25144f,0.96337f}, {0.313976f,0.959005f},{0.306278f,0.96337f},{0.25144f,0.959005f}, {0.0269423f,0.959005f},{0.0894779f,0.96037f},{0.0346399f,0.96037f}, {0.0894779f,0.959005f},{0.0455281f,0.968653f},{0.0894779f,0.968653f}, {0.0894779f,0.94556f},{0.0252532f,0.94656f},{0.315665f,0.95556f}, {0.25144f,0.95556f},{0.25144f,0.965653f},{0.30339f,0.965653f}, {0.0496316f,0.974239f},{0.0893823f,0.974239f},{0.301128f,0.966239f}, {0.25144f,0.966239f},{0.0427511f,0.9905f},{0.00144966f,0.9905f}, {0.0252532f,0.94656f},{0.0155255f,0.959947f},{0.0155255f,0.959947f}, {0.0269423f,0.959005f},{0.00144966f,0.9905f},{0.315665f,0.95556f}, {0.325405f,0.959951f},{0.00846608f,0.959951f},{0.0155255f,0.959947f}, {0.00144966f,0.9905f},{0.325405f,0.959951f},{0.332421f,0.9905f}, {0.290538f,0.9905f},{0.332421f,0.9905f},{0.0427511f,0.9905f}, {0.0460888f,0.987731f},{0.0460888f,0.987731f},{0.0496316f,0.974239f}, {0.051936f,0.984575f},{0.301128f,0.966239f},{0.290538f,0.9905f}, {0.287374f,0.966239f},{0.226543f,0.999f},{0.22086f,0.9905f}, {0.22086f,0.999f},{0.226779f,0.990739f},{0.219342f,0.99f}, {0.22086f,0.999f},{0.22086f,0.9905f},{0.215506f,0.990239f}, {0.113633f,0.974239f},{0.113288f,0.985714f},{0.0998447f,0.974239f}, {0.119792f,0.983435f},{0.107568f,0.988395f},{0.104527f,0.9905f}, {0.0998447f,0.974239f},{0.12702f,0.984575f},{0.113633f,0.974239f}, {0.129133f,0.974239f},{0.119792f,0.983435f},{0.223779f,0.985239f}, {0.25144f,0.9905f},{0.22086f,0.9905f},{0.25144f,0.966239f}, {0.104527f,0.9905f},{0.0894779f,0.9905f},{0.0998447f,0.974239f}, {0.124845f,0.990739f},{0.114478f,0.9875f},{0.127556f,0.9875f}, {0.114382f,0.990739f},{0.113288f,0.985714f},{0.107568f,0.988395f}, {0.0998447f,0.974239f},{0.188904f,0.959005f},{0.196602f,0.96337f}, {0.152013f,0.959005f},{0.144316f,0.96037f},{0.132428f,0.968653f}, {0.0894779f,0.94556f},{0.153703f,0.94656f},{0.187215f,0.95556f}, {0.25144f,0.95556f},{0.20049f,0.965653f},{0.129133f,0.974239f}, {0.0893823f,0.974239f},{0.201752f,0.966239f},{0.25144f,0.966239f}, {0.136205f,0.9905f},{0.170459f,0.9905f},{0.153703f,0.94656f}, {0.16343f,0.959947f},{0.16343f,0.959947f},{0.170459f,0.9905f}, {0.187215f,0.95556f},{0.177475f,0.959951f},{0.16343f,0.959947f}, {0.177475f,0.959951f},{0.170459f,0.9905f},{0.177475f,0.959951f}, {0.212342f,0.9905f},{0.170459f,0.9905f},{0.136205f,0.9905f}, {0.132867f,0.987731f},{0.129133f,0.974239f},{0.132867f,0.987731f}, {0.12702f,0.984575f},{0.212342f,0.9905f},{0.212342f,0.9905f}, {0.201752f,0.966239f},{0.215506f,0.990239f},{0.28202f,0.99941f}, {0.287374f,0.99941f},{0.287374f,0.996384f},{0.215506f,0.996094f}, {0.215506f,0.990239f} }; GLint GenEPuckBody() { unsigned i; unsigned j; GLint lid=glGenLists(1); glNewList(lid, GL_COMPILE); glBegin (GL_TRIANGLES); for(i=0;i<sizeof(face_indicies)/sizeof(face_indicies[0]);i++) { for(j=0;j<3;j++) { int vi=face_indicies[i][j]; int ni=face_indicies[i][j+3];//Normal index int ti=face_indicies[i][j+6];//Texture index /*glNormal3f (normals[ni][0],normals[ni][1],normals[ni][2]); glTexCoord2f(textures[ti][0],textures[ti][1]); glVertex3f (vertices[vi][0],vertices[vi][1],vertices[vi][2]);*/ // rotate 90 deg around z glNormal3f (normals[ni][1],-normals[ni][0],normals[ni][2]); glTexCoord2f(textures[ti][0],textures[ti][1]); glVertex3f (vertices[vi][1],-vertices[vi][0],vertices[vi][2]); } } glEnd (); glEndList(); return lid; }; }
74.189445
117
0.6378
ou-real
516ee4d8d4246c315aa8525ee046b6e0ae3f44e7
1,962
cpp
C++
tree/search_tree/best_fit/bestFit.cpp
vectordb-io/vstl
1cd35add1a28cc1bcac560629b4a49495fe2b065
[ "Apache-2.0" ]
null
null
null
tree/search_tree/best_fit/bestFit.cpp
vectordb-io/vstl
1cd35add1a28cc1bcac560629b4a49495fe2b065
[ "Apache-2.0" ]
null
null
null
tree/search_tree/best_fit/bestFit.cpp
vectordb-io/vstl
1cd35add1a28cc1bcac560629b4a49495fe2b065
[ "Apache-2.0" ]
null
null
null
// best fit bin packing #include <iostream> #include "dBinarySearchTreeWithGE.h" using namespace std; void bestFitPack(int *objectSize, int numberOfObjects, int binCapacity) {// Output best-fit packing into bins of size binCapacity. // objectSize[1:numberOfObjects] are the object sizes. int n = numberOfObjects; int binsUsed = 0; dBinarySearchTreeWithGE<int,int> theTree; // tree of bin capacities pair<int, int> theBin; // pack objects one by one for (int i = 1; i <= n; i++) {// pack object i // find best bin pair<const int, int> *bestBin = theTree.findGE(objectSize[i]); if (bestBin == NULL) {// no bin large enough, start a new bin theBin.first = binCapacity; theBin.second = ++binsUsed; } else {// remove best bin from theTree theBin = *bestBin; theTree.erase(bestBin->first); } cout << "Pack object " << i << " in bin " << theBin.second << endl; // insert bin in tree unless bin is full theBin.first -= objectSize[i]; if (theBin.first > 0) theTree.insert(theBin); } } // test program int main(void) { cout << "Enter number of objects and bin capacity" << endl; int numberOfObjects, binCapacity; cin >> numberOfObjects >> binCapacity; if (numberOfObjects < 2) { cout << "Too few objects" << endl; exit(1); } // input the object sizes objectSize[1:numberOfObjects] int *objectSize = new int [numberOfObjects + 1]; for (int i = 1; i <= numberOfObjects; i++) { cout << "Enter space requirement of object " << i << endl; cin >> objectSize[i]; if (objectSize[i] > binCapacity) { cout << "Object too large to fit in a bin" << endl; exit(1); } } // output the packing bestFitPack(objectSize, numberOfObjects, binCapacity); }
27.633803
72
0.583588
vectordb-io
516fb1cfc8317517817557bd7bd6fe676725cda1
5,187
cpp
C++
ethernet_bridge/src/tcp_client/node.cpp
UniBwTAS/ethernet_bridge
c13c537b0c08326728911687dddfcdf14a727798
[ "BSD-3-Clause" ]
5
2021-06-06T18:38:35.000Z
2021-08-09T22:31:13.000Z
ethernet_bridge/src/tcp_client/node.cpp
UniBwTAS/ethernet_bridge
c13c537b0c08326728911687dddfcdf14a727798
[ "BSD-3-Clause" ]
null
null
null
ethernet_bridge/src/tcp_client/node.cpp
UniBwTAS/ethernet_bridge
c13c537b0c08326728911687dddfcdf14a727798
[ "BSD-3-Clause" ]
4
2021-08-08T23:50:59.000Z
2021-08-09T22:31:39.000Z
#include "node.h" #include <QTcpSocket> #include <QHostAddress> #include <ethernet_msgs/Event.h> #include <ethernet_msgs/EventType.h> #include <ethernet_msgs/ProtocolType.h> #include <ethernet_msgs/utils.h> Node::Node(ros::NodeHandle& nh, ros::NodeHandle& private_nh) : nh_(nh), private_nh_(nh) { /// Parameter // Topics private_nh.param<std::string>("topic_busToHost", configuration_.topic_busToHost, "bus_to_host"); private_nh.param<std::string>("topic_hostToBus", configuration_.topic_hostToBus, "host_to_bus"); private_nh.param<std::string>("topic_event", configuration_.topic_event, "event"); // Frame private_nh.param<std::string>("frame", configuration_.frame, ""); // Ethernet connection private_nh.param<std::string>("ethernet_peerAddress", configuration_.ethernet_peerAddress, "127.0.0.1"); private_nh.param<int>("ethernet_peerPort", configuration_.ethernet_peerPort, 55555); private_nh.param<int>("ethernet_bufferSize", configuration_.ethernet_bufferSize, 0); private_nh.param<int>("ethernet_reconnectInterval", configuration_.ethernet_reconnectInterval, 500); /// Subscribing & Publishing subscriber_ethernet_ = nh.subscribe(configuration_.topic_hostToBus, 100, &Node::rosCallback_ethernet, this); publisher_ethernet_packet_ = nh.advertise<ethernet_msgs::Packet>(configuration_.topic_busToHost, 100); publisher_ethernet_event_ = nh.advertise<ethernet_msgs::Event>(configuration_.topic_event, 100, true); /// Bring up socket // Initialiazation socket_ = new QTcpSocket(this); connect(socket_, SIGNAL(readyRead()), this, SLOT(slotEthernetNewData())); connect(socket_, SIGNAL(connected()), this, SLOT(slotEthernetConnected())); connect(socket_, SIGNAL(disconnected()), this, SLOT(slotEthernetDisconnected())); #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)) connect(socket_, SIGNAL(errorOccured(QAbstractSocket::SocketError)), this, SLOT(slotEthernetError(QAbstractSocket::SocketError))); #endif // Publish unconnected state slotEthernetDisconnected(); // Configuration if (configuration_.ethernet_bufferSize > 0) socket_->setReadBufferSize(configuration_.ethernet_bufferSize); // Initial connection ROS_INFO("Connecting to %s:%u ...", configuration_.ethernet_peerAddress.data(), configuration_.ethernet_peerPort); socket_->connectToHost(QString::fromStdString(configuration_.ethernet_peerAddress), configuration_.ethernet_peerPort); /// Initialize timer for reconnecting on connection loss connect(&timer_, SIGNAL(timeout()), this, SLOT(slotTimer())); if (configuration_.ethernet_reconnectInterval > 0) { timer_.setInterval(configuration_.ethernet_reconnectInterval); timer_.start(); } } Node::~Node() { delete socket_; } void Node::rosCallback_ethernet(const ethernet_msgs::Packet::ConstPtr &msg) { socket_->write(reinterpret_cast<const char*>(msg->payload.data()), msg->payload.size()); } void Node::slotEthernetNewData() { while (socket_->bytesAvailable()) { packet.header.stamp = ros::Time::now(); packet.header.frame_id = configuration_.frame; packet.sender_ip = ethernet_msgs::arrayByNativeIp4(socket_->peerAddress().toIPv4Address()); packet.sender_port = socket_->peerPort(); packet.receiver_ip = ethernet_msgs::arrayByNativeIp4(socket_->localAddress().toIPv4Address()); packet.receiver_port = socket_->localPort(); packet.payload.clear(); packet.payload.reserve(socket_->bytesAvailable()); QByteArray payload = socket_->readAll(); std::copy(payload.constBegin(), payload.constEnd(), std::back_inserter(packet.payload)); publisher_ethernet_packet_.publish(packet); } } void Node::slotEthernetConnected() { ethernet_msgs::Event event; event.header.stamp = ros::Time::now(); event.header.frame_id = configuration_.frame; event.type = ethernet_msgs::EventType::CONNECTED; publisher_ethernet_event_.publish(event); ROS_INFO("Connected."); } void Node::slotEthernetDisconnected() { ethernet_msgs::Event event; event.header.stamp = ros::Time::now(); event.header.frame_id = configuration_.frame; event.type = ethernet_msgs::EventType::DISCONNECTED; publisher_ethernet_event_.publish(event); ROS_INFO("Disconnected."); } void Node::slotEthernetError(int error_code) { ethernet_msgs::Event event; event.header.stamp = ros::Time::now(); event.header.frame_id = configuration_.frame; event.type = ethernet_msgs::EventType::SOCKETERROR; event.value = error_code; publisher_ethernet_event_.publish(event); ROS_WARN("Connection error occured, socket error code: %i", error_code); } void Node::slotTimer() { if (socket_->state() != QAbstractSocket::ConnectedState) // also covers deadlocks in other states like "ConnectingState" socket_->connectToHost(QString::fromStdString(configuration_.ethernet_peerAddress), configuration_.ethernet_peerPort); }
36.787234
135
0.710816
UniBwTAS
51706b4bc2a573e50ce30f7eebe1e9225cc7608a
196
cpp
C++
Floating_Point_Instructions/DP_Instructions/Conversion_and_Move/FMV.D.X.cpp
vinodganesan/shaktiISS
fb48e202596989004136b3d44e6fcfa191ba6ea8
[ "BSD-3-Clause" ]
null
null
null
Floating_Point_Instructions/DP_Instructions/Conversion_and_Move/FMV.D.X.cpp
vinodganesan/shaktiISS
fb48e202596989004136b3d44e6fcfa191ba6ea8
[ "BSD-3-Clause" ]
null
null
null
Floating_Point_Instructions/DP_Instructions/Conversion_and_Move/FMV.D.X.cpp
vinodganesan/shaktiISS
fb48e202596989004136b3d44e6fcfa191ba6ea8
[ "BSD-3-Clause" ]
null
null
null
#include<stdio.h> #include<sstream> #include<iostream> #include<string> void fmvdx(int rd, int rs1, std::string rm) { getrounding(rm); for(int i= 0; i < 64 ; ++i) Rreg[rs1][i] = Freg[rd][i]; }
15.076923
43
0.642857
vinodganesan
517089bb21af2202511875938970efe499b93c99
2,469
cpp
C++
2021day21/run.cpp
AntonJoha/AdventOfCode
3349f789adf3dc1d8062d56ba3efb20fbb0ee335
[ "MIT" ]
null
null
null
2021day21/run.cpp
AntonJoha/AdventOfCode
3349f789adf3dc1d8062d56ba3efb20fbb0ee335
[ "MIT" ]
null
null
null
2021day21/run.cpp
AntonJoha/AdventOfCode
3349f789adf3dc1d8062d56ba3efb20fbb0ee335
[ "MIT" ]
null
null
null
#include "run.h" #include <iostream> #define STARTONE 1 #define STARTTWO 7 //FIRST PROBLEM HERE #ifdef FIRST #define MAXSIZE 10 #define WINNING 1000 std::string run::solve(std::ifstream* file){ unsigned int point1 = 0; unsigned int point2 = 0; unsigned int pos1 = STARTONE; unsigned int pos2 = STARTTWO; unsigned int count = 1; while (true){ for (size_t i = 0; i < 3; ++i){ pos1 = ((count%100) + pos1) % 10; ++count; } point1 += 1 + pos1; if (point1 >= WINNING){ return std::to_string( (count - 1)*point2); } for (size_t i = 0; i < 3; ++i){ pos2 = ((count%100) + pos2) % 10; ++count; } point2 += 1 + pos2; if (point2 >= WINNING){ return std::to_string( (count - 1)*point1); } } return ""; } #endif //SECOND PROBLEM HERE #ifdef SECOND #define WINNING 21 unsigned long points(unsigned int val1, unsigned int val2, unsigned int pos1, unsigned int pos2, bool turnP1, bool retP1); unsigned long callNew(unsigned int val1, unsigned int val2, unsigned int pos1, unsigned int pos2, bool turnP1, bool retP1, unsigned int add){ if (turnP1){ pos1 = (pos1 + add)%10; val1 += pos1 + 1; } else{ pos2 = (pos2 + add)%10; val2 += pos2 + 1; } return points(val1, val2, pos1, pos2, !turnP1, retP1); } unsigned long points(unsigned int val1, unsigned int val2, unsigned int pos1, unsigned int pos2, bool turnP1, bool retP1){ if (val1 >= WINNING){ if (retP1) return 1; else return 0; } if (val2 >= WINNING){ if (retP1) return 0; else return 1; } unsigned long toReturn = 0; #define MORE(x, y, z) x += y*callNew(val1, val2, pos1, pos2, turnP1, retP1, z) //There are 21 different combinations // 3 3 3 one time 9 //9 , 1 MORE(toReturn, 1, 9); // 3 3 2 three times 8 // 8, 3 MORE(toReturn, 3, 8); // 3 3 1 three times 7 // 2 2 3 three times 7 // 7, 6 MORE(toReturn, 6, 7); // 2 2 2 one time 6 // 3 2 1 six times 6 // 6, 7 MORE(toReturn, 7, 6); // 2 2 1 three times 5 // 1 1 3 three times 5 // 5, 6 MORE(toReturn, 6, 5); // 1 1 2 three times 4 // 4, 3 MORE(toReturn, 3, 4); // 1 1 1 one time 3 // 3, 1 MORE(toReturn, 1, 3); return toReturn; } std::string run::solve(std::ifstream* file){ unsigned long first = points(0,0, STARTONE, STARTTWO, true, true); unsigned long second = points(0,0, STARTONE, STARTTWO, true, false); if (first < second) return std::to_string(second); return std::to_string(first); } #endif
16.243421
141
0.617659
AntonJoha
5170919522b3f04f6b03e3ee51c44c1cace9b9be
1,244
hpp
C++
SummaryDlg.hpp
chrisoldwood/UTSvrBrowser
341d8b09afdcab5a296df6f074cae47c10637f0f
[ "MIT" ]
3
2017-08-17T15:10:43.000Z
2021-02-27T04:47:49.000Z
SummaryDlg.hpp
chrisoldwood/UTSvrBrowser
341d8b09afdcab5a296df6f074cae47c10637f0f
[ "MIT" ]
null
null
null
SummaryDlg.hpp
chrisoldwood/UTSvrBrowser
341d8b09afdcab5a296df6f074cae47c10637f0f
[ "MIT" ]
null
null
null
/****************************************************************************** ** (C) Chris Oldwood ** ** MODULE: SUMMARYDLG.HPP ** COMPONENT: The Application ** DESCRIPTION: The CSummaryDlg class declaration. ** ******************************************************************************* */ // Check for previous inclusion #ifndef SUMMARYDLG_HPP #define SUMMARYDLG_HPP #if _MSC_VER > 1000 #pragma once #endif #include <WCL/CommonUI.hpp> /****************************************************************************** ** ** The dialog used to display the servers summary. ** ******************************************************************************* */ class CSummaryDlg : public CDialog { public: // // Constructors/Destructor. // CSummaryDlg(); protected: // // Controls. // CListView m_lvGrid; // // Column indices. // enum Column { MOD_NAME, SERVERS, PLAYERS, NUM_COLUMNS, }; // // Message handlers. // virtual void OnInitDialog(); virtual bool OnOk(); }; /****************************************************************************** ** ** Implementation of inline functions. ** ******************************************************************************* */ #endif // SUMMARYDLG_HPP
18.028986
79
0.410772
chrisoldwood
5173e92a9eb31c020877e4977fa7b300b03d04e5
14,528
cpp
C++
src/server/qgsserver.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/server/qgsserver.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/server/qgsserver.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
1
2021-12-25T08:40:30.000Z
2021-12-25T08:40:30.000Z
/*************************************************************************** qgsserver.cpp A server application supporting WMS / WFS / WCS ------------------- begin : July 04, 2006 copyright : (C) 2006 by Marco Hugentobler & Ionut Iosifescu Enescu : (C) 2015 by Alessandro Pasotti email : marco dot hugentobler at karto dot baug dot ethz dot ch : elpaso at itopen dot it ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ //for CMAKE_INSTALL_PREFIX #include "qgsconfig.h" #include "qgsserver.h" #include "qgsauthmanager.h" #include "qgscapabilitiescache.h" #include "qgsfontutils.h" #include "qgsrequesthandler.h" #include "qgsproject.h" #include "qgsproviderregistry.h" #include "qgslogger.h" #include "qgsmapserviceexception.h" #include "qgsnetworkaccessmanager.h" #include "qgsserverlogger.h" #include "qgsserverrequest.h" #include "qgsfilterresponsedecorator.h" #include "qgsservice.h" #include "qgsserverparameters.h" #include "qgsapplication.h" #include <QDomDocument> #include <QNetworkDiskCache> #include <QSettings> #include <QDateTime> // TODO: remove, it's only needed by a single debug message #include <fcgi_stdio.h> #include <cstdlib> // Server status static initializers. // Default values are for C++, SIP bindings will override their // options in in init() QString *QgsServer::sConfigFilePath = nullptr; QgsCapabilitiesCache *QgsServer::sCapabilitiesCache = nullptr; QgsServerInterfaceImpl *QgsServer::sServerInterface = nullptr; // Initialization must run once for all servers bool QgsServer::sInitialized = false; QgsServerSettings QgsServer::sSettings; QgsServiceRegistry *QgsServer::sServiceRegistry = nullptr; QgsServer::QgsServer() { // QgsApplication must exist if ( qobject_cast<QgsApplication *>( qApp ) == nullptr ) { qFatal( "A QgsApplication must exist before a QgsServer instance can be created." ); abort(); } init(); mConfigCache = QgsConfigCache::instance(); } QString &QgsServer::serverName() { static QString *name = new QString( QStringLiteral( "qgis_server" ) ); return *name; } QFileInfo QgsServer::defaultAdminSLD() { return QFileInfo( QStringLiteral( "admin.sld" ) ); } void QgsServer::setupNetworkAccessManager() { QSettings settings; QgsNetworkAccessManager *nam = QgsNetworkAccessManager::instance(); QNetworkDiskCache *cache = new QNetworkDiskCache( nullptr ); qint64 cacheSize = sSettings.cacheSize(); QString cacheDirectory = sSettings.cacheDirectory(); cache->setCacheDirectory( cacheDirectory ); cache->setMaximumCacheSize( cacheSize ); QgsMessageLog::logMessage( QStringLiteral( "cacheDirectory: %1" ).arg( cache->cacheDirectory() ), QStringLiteral( "Server" ), Qgis::Info ); QgsMessageLog::logMessage( QStringLiteral( "maximumCacheSize: %1" ).arg( cache->maximumCacheSize() ), QStringLiteral( "Server" ), Qgis::Info ); nam->setCache( cache ); } QFileInfo QgsServer::defaultProjectFile() { QDir currentDir; fprintf( FCGI_stderr, "current directory: %s\n", currentDir.absolutePath().toUtf8().constData() ); QStringList nameFilterList; nameFilterList << QStringLiteral( "*.qgs" ) << QStringLiteral( "*.qgz" ); QFileInfoList projectFiles = currentDir.entryInfoList( nameFilterList, QDir::Files, QDir::Name ); for ( int x = 0; x < projectFiles.size(); x++ ) { QgsMessageLog::logMessage( projectFiles.at( x ).absoluteFilePath(), QStringLiteral( "Server" ), Qgis::Info ); } if ( projectFiles.isEmpty() ) { return QFileInfo(); } return projectFiles.at( 0 ); } void QgsServer::printRequestParameters( const QMap< QString, QString> &parameterMap, Qgis::MessageLevel logLevel ) { if ( logLevel > Qgis::Info ) { return; } QMap< QString, QString>::const_iterator pIt = parameterMap.constBegin(); for ( ; pIt != parameterMap.constEnd(); ++pIt ) { QgsMessageLog::logMessage( pIt.key() + ":" + pIt.value(), QStringLiteral( "Server" ), Qgis::Info ); } } QString QgsServer::configPath( const QString &defaultConfigPath, const QString &configPath ) { QString cfPath( defaultConfigPath ); QString projectFile = sSettings.projectFile(); if ( !projectFile.isEmpty() ) { cfPath = projectFile; QgsDebugMsg( QStringLiteral( "QGIS_PROJECT_FILE:%1" ).arg( cfPath ) ); } else { if ( configPath.isEmpty() ) { QgsMessageLog::logMessage( QStringLiteral( "Using default configuration file path: %1" ).arg( defaultConfigPath ), QStringLiteral( "Server" ), Qgis::Info ); } else { cfPath = configPath; QgsDebugMsg( QStringLiteral( "MAP:%1" ).arg( cfPath ) ); } } return cfPath; } void QgsServer::initLocale() { // System locale override if ( ! sSettings.overrideSystemLocale().isEmpty() ) { QLocale::setDefault( QLocale( sSettings.overrideSystemLocale() ) ); } // Number group separator settings QLocale currentLocale; if ( sSettings.showGroupSeparator() ) { currentLocale.setNumberOptions( currentLocale.numberOptions() &= ~QLocale::NumberOption::OmitGroupSeparator ); } else { currentLocale.setNumberOptions( currentLocale.numberOptions() |= QLocale::NumberOption::OmitGroupSeparator ); } QLocale::setDefault( currentLocale ); } bool QgsServer::init() { if ( sInitialized ) { return false; } QCoreApplication::setOrganizationName( QgsApplication::QGIS_ORGANIZATION_NAME ); QCoreApplication::setOrganizationDomain( QgsApplication::QGIS_ORGANIZATION_DOMAIN ); QCoreApplication::setApplicationName( QgsApplication::QGIS_APPLICATION_NAME ); QgsApplication::init(); #if defined(SERVER_SKIP_ECW) QgsMessageLog::logMessage( "Skipping GDAL ECW drivers in server.", "Server", Qgis::Info ); QgsApplication::skipGdalDriver( "ECW" ); QgsApplication::skipGdalDriver( "JP2ECW" ); #endif // reload settings to take into account QCoreApplication and QgsApplication // configuration sSettings.load(); // init and configure logger QgsServerLogger::instance(); QgsServerLogger::instance()->setLogLevel( sSettings.logLevel() ); if ( ! sSettings.logFile().isEmpty() ) { QgsServerLogger::instance()->setLogFile( sSettings.logFile() ); } else if ( sSettings.logStderr() ) { QgsServerLogger::instance()->setLogStderr(); } // Configure locale initLocale(); // log settings currently used sSettings.logSummary(); setupNetworkAccessManager(); QDomImplementation::setInvalidDataPolicy( QDomImplementation::DropInvalidChars ); // Instantiate the plugin directory so that providers are loaded QgsProviderRegistry::instance( QgsApplication::pluginPath() ); QgsMessageLog::logMessage( "Prefix PATH: " + QgsApplication::prefixPath(), QStringLiteral( "Server" ), Qgis::Info ); QgsMessageLog::logMessage( "Plugin PATH: " + QgsApplication::pluginPath(), QStringLiteral( "Server" ), Qgis::Info ); QgsMessageLog::logMessage( "PkgData PATH: " + QgsApplication::pkgDataPath(), QStringLiteral( "Server" ), Qgis::Info ); QgsMessageLog::logMessage( "User DB PATH: " + QgsApplication::qgisUserDatabaseFilePath(), QStringLiteral( "Server" ), Qgis::Info ); QgsMessageLog::logMessage( "Auth DB PATH: " + QgsApplication::qgisAuthDatabaseFilePath(), QStringLiteral( "Server" ), Qgis::Info ); QgsMessageLog::logMessage( "SVG PATHS: " + QgsApplication::svgPaths().join( QDir::separator() ), QStringLiteral( "Server" ), Qgis::Info ); QgsApplication::createDatabase(); //init qgis.db (e.g. necessary for user crs) // Initialize the authentication system // creates or uses qgis-auth.db in ~/.qgis3/ or directory defined by QGIS_AUTH_DB_DIR_PATH env variable // set the master password as first line of file defined by QGIS_AUTH_PASSWORD_FILE env variable // (QGIS_AUTH_PASSWORD_FILE variable removed from environment after accessing) QgsApplication::authManager()->init( QgsApplication::pluginPath(), QgsApplication::qgisAuthDatabaseFilePath() ); QString defaultConfigFilePath; QFileInfo projectFileInfo = defaultProjectFile(); //try to find a .qgs/.qgz file in the server directory if ( projectFileInfo.exists() ) { defaultConfigFilePath = projectFileInfo.absoluteFilePath(); QgsMessageLog::logMessage( "Using default project file: " + defaultConfigFilePath, QStringLiteral( "Server" ), Qgis::Info ); } else { QFileInfo adminSLDFileInfo = defaultAdminSLD(); if ( adminSLDFileInfo.exists() ) { defaultConfigFilePath = adminSLDFileInfo.absoluteFilePath(); } } // Store the config file path sConfigFilePath = new QString( defaultConfigFilePath ); //create cache for capabilities XML sCapabilitiesCache = new QgsCapabilitiesCache(); QgsFontUtils::loadStandardTestFonts( QStringList() << QStringLiteral( "Roman" ) << QStringLiteral( "Bold" ) ); sServiceRegistry = new QgsServiceRegistry(); sServerInterface = new QgsServerInterfaceImpl( sCapabilitiesCache, sServiceRegistry, &sSettings ); // Load service module QString modulePath = QgsApplication::libexecPath() + "server"; qDebug() << "Initializing server modules from " << modulePath << endl; sServiceRegistry->init( modulePath, sServerInterface ); sInitialized = true; QgsMessageLog::logMessage( QStringLiteral( "Server initialized" ), QStringLiteral( "Server" ), Qgis::Info ); return true; } void QgsServer::putenv( const QString &var, const QString &val ) { #ifdef _MSC_VER _putenv_s( var.toStdString().c_str(), val.toStdString().c_str() ); #else setenv( var.toStdString().c_str(), val.toStdString().c_str(), 1 ); #endif sSettings.load( var ); } void QgsServer::handleRequest( QgsServerRequest &request, QgsServerResponse &response, const QgsProject *project ) { Qgis::MessageLevel logLevel = QgsServerLogger::instance()->logLevel(); QTime time; //used for measuring request time if loglevel < 1 qApp->processEvents(); if ( logLevel == Qgis::Info ) { time.start(); } // Pass the filters to the requestHandler, this is needed for the following reasons: // Allow server request to call sendResponse plugin hook if enabled QgsFilterResponseDecorator responseDecorator( sServerInterface->filters(), response ); //Request handler QgsRequestHandler requestHandler( request, response ); try { // TODO: split parse input into plain parse and processing from specific services requestHandler.parseInput(); } catch ( QgsMapServiceException &e ) { QgsMessageLog::logMessage( "Parse input exception: " + e.message(), QStringLiteral( "Server" ), Qgis::Critical ); requestHandler.setServiceException( e ); } // Set the request handler into the interface for plugins to manipulate it sServerInterface->setRequestHandler( &requestHandler ); // Initialize configfilepath so that is is available // before calling plugin methods // Note that plugins may still change that value using // setConfigFilePath() interface method if ( ! project ) { QString configFilePath = configPath( *sConfigFilePath, request.serverParameters().map() ); sServerInterface->setConfigFilePath( configFilePath ); } else { sServerInterface->setConfigFilePath( project->fileName() ); } // Call requestReady() method (if enabled) responseDecorator.start(); // Plugins may have set exceptions if ( !requestHandler.exceptionRaised() ) { try { const QgsServerParameters params = request.serverParameters(); printRequestParameters( params.toMap(), logLevel ); //Config file path if ( ! project ) { // load the project if needed and not empty project = mConfigCache->project( sServerInterface->configFilePath() ); if ( ! project ) { throw QgsServerException( QStringLiteral( "Project file error" ) ); } } if ( ! params.fileName().isEmpty() ) { const QString value = QString( "attachment; filename=\"%1\"" ).arg( params.fileName() ); requestHandler.setResponseHeader( QStringLiteral( "Content-Disposition" ), value ); } // Lookup for service QgsService *service = sServiceRegistry->getService( params.service(), params.version() ); if ( service ) { service->executeRequest( request, responseDecorator, project ); } else { throw QgsOgcServiceException( QStringLiteral( "Service configuration error" ), QStringLiteral( "Service unknown or unsupported" ) ); } } catch ( QgsServerException &ex ) { responseDecorator.write( ex ); QString format; QgsMessageLog::logMessage( ex.formatResponse( format ), QStringLiteral( "Server" ), Qgis::Info ); } catch ( QgsException &ex ) { // Internal server error response.sendError( 500, QStringLiteral( "Internal Server Error" ) ); QgsMessageLog::logMessage( ex.what(), QStringLiteral( "Server" ), Qgis::Critical ); } } // Terminate the response responseDecorator.finish(); // We are done using requestHandler in plugins, make sure we don't access // to a deleted request handler from Python bindings sServerInterface->clearRequestHandler(); if ( logLevel == Qgis::Info ) { QgsMessageLog::logMessage( "Request finished in " + QString::number( time.elapsed() ) + " ms", QStringLiteral( "Server" ), Qgis::Info ); } } #ifdef HAVE_SERVER_PYTHON_PLUGINS void QgsServer::initPython() { // Init plugins if ( ! QgsServerPlugins::initPlugins( sServerInterface ) ) { QgsMessageLog::logMessage( QStringLiteral( "No server python plugins are available" ), QStringLiteral( "Server" ), Qgis::Info ); } else { QgsMessageLog::logMessage( QStringLiteral( "Server python plugins loaded" ), QStringLiteral( "Server" ), Qgis::Info ); } } #endif
34.755981
162
0.677657
dyna-mis
517a331d2e94d35e5628b728cf86f2f6feaa6f64
1,724
cpp
C++
Chapter11/clang-plugin/NamingPlugin.cpp
PacktPublishing/Learn-LLVM-12
e53e4ce5ecabeecc42a61acad9b707e3424dc472
[ "MIT" ]
149
2021-04-24T05:39:42.000Z
2022-03-31T02:02:39.000Z
Chapter11/clang-plugin/NamingPlugin.cpp
PacktPublishing/Learn-LLVM-12
e53e4ce5ecabeecc42a61acad9b707e3424dc472
[ "MIT" ]
7
2021-06-03T00:44:13.000Z
2022-01-06T23:05:50.000Z
Chapter11/clang-plugin/NamingPlugin.cpp
PacktPublishing/Learn-LLVM-9
e53e4ce5ecabeecc42a61acad9b707e3424dc472
[ "MIT" ]
42
2021-05-18T11:41:05.000Z
2022-03-29T02:11:53.000Z
#include "clang/AST/ASTConsumer.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendPluginRegistry.h" using namespace clang; namespace { class NamingASTConsumer : public ASTConsumer { CompilerInstance &CI; public: NamingASTConsumer(CompilerInstance &CI) : CI(CI) {} bool HandleTopLevelDecl(DeclGroupRef DG) override { for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) { const Decl *D = *I; if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { std::string Name = FD->getNameInfo().getName().getAsString(); assert(Name.length() > 0 && "Unexpected empty identifier"); char &First = Name.at(0); if (!(First >= 'a' && First <= 'z')) { DiagnosticsEngine &Diag = CI.getDiagnostics(); unsigned ID = Diag.getCustomDiagID( DiagnosticsEngine::Warning, "Function name should start with " "lowercase letter"); Diag.Report(FD->getLocation(), ID); } } } return true; } }; class PluginNamingAction : public PluginASTAction { public: std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef file) override { return std::make_unique<NamingASTConsumer>(CI); } bool ParseArgs( const CompilerInstance &CI, const std::vector<std::string> &args) override { return true; } PluginASTAction::ActionType getActionType() override { return AddAfterMainAction; } }; } // namespace static FrontendPluginRegistry::Add<PluginNamingAction> X("naming-plugin", "naming plugin");
26.9375
56
0.614849
PacktPublishing
517baa146ec5a67f6b1353188db116e52cd8b024
2,861
hpp
C++
libtbag/tiled/details/TmxImageLayer.hpp
osom8979/tbag
c31e2d884907d946df0836a70d8d5d69c4bf3c27
[ "MIT" ]
21
2016-04-05T06:08:41.000Z
2022-03-28T10:20:22.000Z
libtbag/tiled/details/TmxImageLayer.hpp
osom8979/tbag
c31e2d884907d946df0836a70d8d5d69c4bf3c27
[ "MIT" ]
null
null
null
libtbag/tiled/details/TmxImageLayer.hpp
osom8979/tbag
c31e2d884907d946df0836a70d8d5d69c4bf3c27
[ "MIT" ]
2
2019-07-16T00:37:21.000Z
2021-11-10T06:14:09.000Z
/** * @file TmxImageLayer.hpp * @brief TmxImageLayer class prototype. * @author zer0 * @date 2019-08-11 */ #ifndef __INCLUDE_LIBTBAG__LIBTBAG_TILED_DETAILS_TMXIMAGELAYER_HPP__ #define __INCLUDE_LIBTBAG__LIBTBAG_TILED_DETAILS_TMXIMAGELAYER_HPP__ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <libtbag/config.h> #include <libtbag/predef.hpp> #include <libtbag/Err.hpp> #include <libtbag/dom/xml/XmlHelper.hpp> #include <libtbag/tiled/details/TmxImage.hpp> #include <libtbag/tiled/details/TmxProperties.hpp> #include <string> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace tiled { namespace details { /** * TmxImageLayer class prototype. * * @author zer0 * @date 2019-08-11 * * A layer consisting of a single image. */ struct TBAG_API TmxImageLayer : protected libtbag::dom::xml::XmlHelper { TBAG_CONSTEXPR static char const * const TAG_NAME = "imagelayer"; /** * Unique ID of the layer. * Each layer that added to a map gets a unique id. * Even if a layer is deleted, no layer ever gets the same ID. * Can not be changed in Tiled. (since Tiled 1.2) */ TBAG_CONSTEXPR static char const * const ATT_ID = "id"; /** The name of the image layer. */ TBAG_CONSTEXPR static char const * const ATT_NAME = "name"; /** Rendering offset of the image layer in pixels. Defaults to 0. (since 0.15) */ TBAG_CONSTEXPR static char const * const ATT_OFFSETX = "offsetx"; /** Rendering offset of the image layer in pixels. Defaults to 0. (since 0.15) */ TBAG_CONSTEXPR static char const * const ATT_OFFSETY = "offsety"; /** The x position of the image layer in pixels. (deprecated since 0.15) */ TBAG_CONSTEXPR static char const * const ATT_X = "x"; /** The y position of the image layer in pixels. (deprecated since 0.15) */ TBAG_CONSTEXPR static char const * const ATT_Y = "y"; /** The opacity of the layer as a value from 0 to 1. Defaults to 1. */ TBAG_CONSTEXPR static char const * const ATT_OPACITY = "opacity"; /** Whether the layer is shown (1) or hidden (0). Defaults to 1. */ TBAG_CONSTEXPR static char const * const ATT_VISIBLE = "visible"; int id = 0; std::string name; int offsetx = 0; int offsety = 0; int x = 0; int y = 0; int opacity = 1; int visible = 1; TmxProperties properties; TmxImage image; TmxImageLayer(); ~TmxImageLayer(); Err read(Element const & elem); Err read(std::string const & xml); Err write(Element & elem) const; Err write(std::string & xml) const; }; } // namespace details } // namespace tiled // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- #endif // __INCLUDE_LIBTBAG__LIBTBAG_TILED_DETAILS_TMXIMAGELAYER_HPP__
27.509615
85
0.6669
osom8979
517cdf24c59a46b068950e8bc45dd38309516b2b
19,361
cpp
C++
gsa/wit/COIN/Coin/Test/CoinPackedMatrixTest.cpp
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
1
2019-10-25T05:25:23.000Z
2019-10-25T05:25:23.000Z
gsa/wit/COIN/Coin/Test/CoinPackedMatrixTest.cpp
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
2
2019-09-04T17:34:59.000Z
2020-09-16T08:10:57.000Z
gsa/wit/COIN/Coin/Test/CoinPackedMatrixTest.cpp
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
18
2019-07-22T19:01:25.000Z
2022-03-03T15:36:11.000Z
// Copyright (C) 2000, International Business Machines // Corporation and others. All Rights Reserved. #if defined(_MSC_VER) // Turn off compiler warning about long names # pragma warning(disable:4786) #endif #include <cassert> #include "CoinFloatEqual.hpp" #include "CoinPackedVector.hpp" #include "CoinPackedMatrix.hpp" //############################################################################# #ifdef NDEBUG #undef NDEBUG #endif void CoinPackedMatrixUnitTest() { CoinRelFltEq eq; { // Test construction on empty matrices CoinPackedMatrix m; CoinPackedMatrix lhs = m; CoinPackedMatrix mCopy(m); assert( eq(m.getExtraGap(),.25) ); assert( eq(lhs.getExtraGap(),.25) ); assert( eq(mCopy.getExtraGap(),.25) ); assert( eq(m.getExtraMajor(),.25) ); assert( eq(lhs.getExtraMajor(),.25) ); assert( eq(mCopy.getExtraMajor(),.25) ); assert( m.isColOrdered() ); assert( lhs.isColOrdered() ); assert( mCopy.isColOrdered() ); assert( m.getNumElements() == 0 ); assert( lhs.getNumElements() == 0 ); assert( mCopy.getNumElements() == 0 ); assert( m.getNumCols() == 0 ); assert( lhs.getNumCols() == 0 ); assert( mCopy.getNumCols() == 0 ); assert( m.getNumRows() == 0 ); assert( lhs.getNumRows() == 0 ); assert( mCopy.getNumRows() == 0 ); assert( m.getElements() == 0 ); assert( lhs.getElements() == 0 ); assert( mCopy.getElements() == 0 ); assert( m.getIndices() == 0 ); assert( lhs.getIndices() == 0 ); assert( mCopy.getIndices() == 0 ); assert( m.getSizeVectorStarts()==0 ); assert( lhs.getSizeVectorStarts()==0 ); assert( mCopy.getSizeVectorStarts()==0 ); assert( m.getSizeVectorLengths()==0 ); assert( lhs.getSizeVectorLengths()==0 ); assert( mCopy.getSizeVectorLengths()==0 ); // out as empty matrix still has one start //assert( m.getVectorStarts()==NULL ); //assert( lhs.getVectorStarts()==NULL ); //assert( mCopy.getVectorStarts()==NULL ); assert( m.getVectorLengths()==NULL ); assert( lhs.getVectorLengths()==NULL ); assert( mCopy.getVectorLengths()==NULL ); assert( m.getMajorDim() == 0 ); assert( lhs.getMajorDim() == 0 ); assert( mCopy.getMajorDim() == 0 ); assert( m.getMinorDim() == 0 ); assert( lhs.getMinorDim() == 0 ); assert( mCopy.getMinorDim() == 0 ); } { CoinPackedMatrix * globalP; { /************************************************************************* * Setup data to represent this matrix by rows * * 3x1 + x2 - 2x4 - x5 - x8 * 2x2 + 1.1x3 * x3 + x6 * 2.8x4 -1.2x7 * 5.6x1 + x5 + 1.9x8 * *************************************************************************/ #if 0 // By columns const int minor=5; const int major=8; const int numels=14; const double elemBase[numels]={3., 5.6, 1., 2., 1.1, 1., -2., 2.8, -1., 1., 1., -1.2, -1., 1.9}; const int indBase[numels]={0,4,0,1,1,2,0,3,0,4,2,3,0,4}; const CoinBigIndex startsBase[major+1]={0,2,4,6,8,10,11,12,14}; const int lenBase[major]={2,2,2,2,2,1,1,2}; #else // By rows const int minor=8; const int major=5; const int numels=14; const double elemBase[numels]={3., 1., -2., -1., -1., 2., 1.1, 1., 1., 2.8, -1.2, 5.6, 1., 1.9 }; const int indBase[numels]={0,1,3,4,7,1,2,2,5,3,6,0,4,7}; const CoinBigIndex startsBase[major+1]={0,5,7,9,11,14}; const int lenBase[major]={5,2,2,2,3}; #endif double * elem = new double[numels]; int * ind = new int[numels]; CoinBigIndex * starts = new CoinBigIndex[major+1]; int * lens = new int[major]; std::copy(elemBase,elemBase+numels,elem); std::copy(indBase,indBase+numels,ind); std::copy(startsBase,startsBase+major+1,starts); std::copy(lenBase,lenBase+major,lens); CoinPackedMatrix pm(false,minor,major,numels,elem,ind,starts,lens, .25,.25); assert( elem!=NULL ); assert( ind!=NULL ); assert( starts!=NULL ); assert( lens!=NULL ); delete[] elem; delete[] ind; delete[] starts; delete[] lens; assert( eq(pm.getExtraGap(),.25) ); assert( eq(pm.getExtraMajor(),.25) ); assert( !pm.isColOrdered() ); assert( pm.getNumElements()==numels ); assert( pm.getNumCols()==minor ); assert( pm.getNumRows()==major); assert( pm.getSizeVectorStarts()==major+1 ); assert( pm.getSizeVectorLengths()==major ); const double * ev = pm.getElements(); assert( eq(ev[0], 3.0) ); assert( eq(ev[1], 1.0) ); assert( eq(ev[2], -2.0) ); assert( eq(ev[3], -1.0) ); assert( eq(ev[4], -1.0) ); assert( eq(ev[7], 2.0) ); assert( eq(ev[8], 1.1) ); assert( eq(ev[10], 1.0) ); assert( eq(ev[11], 1.0) ); assert( eq(ev[13], 2.8) ); assert( eq(ev[14], -1.2) ); assert( eq(ev[16], 5.6) ); assert( eq(ev[17], 1.0) ); assert( eq(ev[18], 1.9) ); const CoinBigIndex * mi = pm.getVectorStarts(); assert( mi[0]==0 ); assert( mi[1]==7 ); assert( mi[2]==10 ); assert( mi[3]==13 ); assert( mi[4]==16 ); assert( mi[5]==20 ); const int * vl = pm.getVectorLengths(); assert( vl[0]==5 ); assert( vl[1]==2 ); assert( vl[2]==2 ); assert( vl[3]==2 ); assert( vl[4]==3 ); const int * ei = pm.getIndices(); assert( ei[0] == 0 ); assert( ei[1] == 1 ); assert( ei[2] == 3 ); assert( ei[3] == 4 ); assert( ei[4] == 7 ); assert( ei[7] == 1 ); assert( ei[8] == 2 ); assert( ei[10] == 2 ); assert( ei[11] == 5 ); assert( ei[13] == 3 ); assert( ei[14] == 6 ); assert( ei[16] == 0 ); assert( ei[17] == 4 ); assert( ei[18] == 7 ); assert( pm.getMajorDim() == 5 ); assert( pm.getMinorDim() == 8 ); assert( pm.getNumElements() == 14 ); assert( pm.getSizeVectorStarts()==6 ); { // Test copy constructor CoinPackedMatrix pmC(pm); assert( eq(pmC.getExtraGap(),.25) ); assert( eq(pmC.getExtraMajor(),.25) ); assert( !pmC.isColOrdered() ); assert( pmC.getNumElements()==numels ); assert( pmC.getNumCols()==minor ); assert( pmC.getNumRows()==major); assert( pmC.getSizeVectorStarts()==major+1 ); assert( pmC.getSizeVectorLengths()==major ); // Test that osm has the correct values assert( pm.getElements() != pmC.getElements() ); const double * ev = pmC.getElements(); assert( eq(ev[0], 3.0) ); assert( eq(ev[1], 1.0) ); assert( eq(ev[2], -2.0) ); assert( eq(ev[3], -1.0) ); assert( eq(ev[4], -1.0) ); assert( eq(ev[7], 2.0) ); assert( eq(ev[8], 1.1) ); assert( eq(ev[10], 1.0) ); assert( eq(ev[11], 1.0) ); assert( eq(ev[13], 2.8) ); assert( eq(ev[14], -1.2) ); assert( eq(ev[16], 5.6) ); assert( eq(ev[17], 1.0) ); assert( eq(ev[18], 1.9) ); assert( pm.getVectorStarts() != pmC.getVectorStarts() ); const CoinBigIndex * mi = pmC.getVectorStarts(); assert( mi[0]==0 ); assert( mi[1]==7 ); assert( mi[2]==10 ); assert( mi[3]==13 ); assert( mi[4]==16 ); assert( mi[5]==20 ); assert( pm.getVectorLengths() != pmC.getVectorLengths() ); const int * vl = pmC.getVectorLengths(); assert( vl[0]==5 ); assert( vl[1]==2 ); assert( vl[2]==2 ); assert( vl[3]==2 ); assert( vl[4]==3 ); assert( pm.getIndices() != pmC.getIndices() ); const int * ei = pmC.getIndices(); assert( ei[0] == 0 ); assert( ei[1] == 1 ); assert( ei[2] == 3 ); assert( ei[3] == 4 ); assert( ei[4] == 7 ); assert( ei[7] == 1 ); assert( ei[8] == 2 ); assert( ei[10] == 2 ); assert( ei[11] == 5 ); assert( ei[13] == 3 ); assert( ei[14] == 6 ); assert( ei[16] == 0 ); assert( ei[17] == 4 ); assert( ei[18] == 7 ); assert( pmC.isEquivalent(pm) ); // Test assignment { CoinPackedMatrix pmA; // Gap should be 0.25 assert( eq(pmA.getExtraGap(),0.25) ); assert( eq(pmA.getExtraMajor(),0.25) ); pmA = pm; assert( eq(pmA.getExtraGap(),0.25) ); assert( eq(pmA.getExtraMajor(),0.25) ); assert( !pmA.isColOrdered() ); assert( pmA.getNumElements()==numels ); assert( pmA.getNumCols()==minor ); assert( pmA.getNumRows()==major); assert( pmA.getSizeVectorStarts()==major+1 ); assert( pmA.getSizeVectorLengths()==major ); // Test that osm1 has the correct values assert( pm.getElements() != pmA.getElements() ); const double * ev = pmA.getElements(); assert( eq(ev[0], 3.0) ); assert( eq(ev[1], 1.0) ); assert( eq(ev[2], -2.0) ); assert( eq(ev[3], -1.0) ); assert( eq(ev[4], -1.0) ); assert( eq(ev[7], 2.0) ); assert( eq(ev[8], 1.1) ); assert( eq(ev[10], 1.0) ); assert( eq(ev[11], 1.0) ); assert( eq(ev[13], 2.8) ); assert( eq(ev[14], -1.2) ); assert( eq(ev[16], 5.6) ); assert( eq(ev[17], 1.0) ); assert( eq(ev[18], 1.9) ); // Test modification of a single element pmA.modifyCoefficient(2,5,-7.0); assert( eq(ev[11], -7.0) ); // and back pmA.modifyCoefficient(2,5,1.0); assert( eq(ev[11], 1.0) ); assert( pm.getVectorStarts() != pmA.getVectorStarts() ); const CoinBigIndex * mi = pmA.getVectorStarts(); assert( mi[0]==0 ); assert( mi[1]==7 ); assert( mi[2]==10 ); assert( mi[3]==13 ); assert( mi[4]==16 ); assert( mi[5]==20 ); assert( pm.getVectorLengths() != pmA.getVectorLengths() ); const int * vl = pmC.getVectorLengths(); assert( vl[0]==5 ); assert( vl[1]==2 ); assert( vl[2]==2 ); assert( vl[3]==2 ); assert( vl[4]==3 ); assert( pm.getIndices() != pmA.getIndices() ); const int * ei = pmA.getIndices(); assert( ei[0] == 0 ); assert( ei[1] == 1 ); assert( ei[2] == 3 ); assert( ei[3] == 4 ); assert( ei[4] == 7 ); assert( ei[7] == 1 ); assert( ei[8] == 2 ); assert( ei[10] == 2 ); assert( ei[11] == 5 ); assert( ei[13] == 3 ); assert( ei[14] == 6 ); assert( ei[16] == 0 ); assert( ei[17] == 4 ); assert( ei[18] == 7 ); assert( pmA.isEquivalent(pm) ); assert( pmA.isEquivalent(pmC) ); // Test new to global globalP = new CoinPackedMatrix(pmA); assert( eq(globalP->getElements()[0], 3.0) ); assert( globalP->isEquivalent(pmA) ); } assert( eq(globalP->getElements()[0], 3.0) ); } assert( eq(globalP->getElements()[0], 3.0) ); } // Test that cloned matrix contains correct values const double * ev = globalP->getElements(); assert( eq(ev[0], 3.0) ); assert( eq(ev[1], 1.0) ); assert( eq(ev[2], -2.0) ); assert( eq(ev[3], -1.0) ); assert( eq(ev[4], -1.0) ); assert( eq(ev[7], 2.0) ); assert( eq(ev[8], 1.1) ); assert( eq(ev[10], 1.0) ); assert( eq(ev[11], 1.0) ); assert( eq(ev[13], 2.8) ); assert( eq(ev[14], -1.2) ); assert( eq(ev[16], 5.6) ); assert( eq(ev[17], 1.0) ); assert( eq(ev[18], 1.9) ); const CoinBigIndex * mi = globalP->getVectorStarts(); assert( mi[0]==0 ); assert( mi[1]==7 ); assert( mi[2]==10 ); assert( mi[3]==13 ); assert( mi[4]==16 ); assert( mi[5]==20 ); const int * ei = globalP->getIndices(); assert( ei[0] == 0 ); assert( ei[1] == 1 ); assert( ei[2] == 3 ); assert( ei[3] == 4 ); assert( ei[4] == 7 ); assert( ei[7] == 1 ); assert( ei[8] == 2 ); assert( ei[10] == 2 ); assert( ei[11] == 5 ); assert( ei[13] == 3 ); assert( ei[14] == 6 ); assert( ei[16] == 0 ); assert( ei[17] == 4 ); assert( ei[18] == 7 ); assert( globalP->getMajorDim() == 5 ); assert( globalP->getMinorDim() == 8 ); assert( globalP->getNumElements() == 14 ); assert( globalP->getSizeVectorStarts()==6 ); // Test method which returns length of vectors assert( globalP->getVectorSize(0)==5 ); assert( globalP->getVectorSize(1)==2 ); assert( globalP->getVectorSize(2)==2 ); assert( globalP->getVectorSize(3)==2 ); assert( globalP->getVectorSize(4)==3 ); // Test getVectorSize exceptions { bool errorThrown = false; try { globalP->getVectorSize(-1); } catch (CoinError e) { errorThrown = true; } assert( errorThrown ); } { bool errorThrown = false; try { globalP->getVectorSize(5); } catch (CoinError e) { errorThrown = true; } assert( errorThrown ); } // Test vector method { // 3x1 + x2 - 2x4 - x5 - x8 CoinShallowPackedVector pv = globalP->getVector(0); assert( pv.getNumElements() == 5 ); assert( eq(pv[0], 3.0) ); assert( eq(pv[1], 1.0) ); assert( eq(pv[3],-2.0) ); assert( eq(pv[4],-1.0) ); assert( eq(pv[7],-1.0) ); // 2x2 + 1.1x3 pv = globalP->getVector(1); assert( pv.getNumElements() == 2 ); assert( eq(pv[1], 2.0) ); assert( eq(pv[2], 1.1) ); // x3 + x6 pv = globalP->getVector(2); assert( pv.getNumElements() == 2 ); assert( eq(pv[2], 1.0) ); assert( eq(pv[5], 1.0) ); // 2.8x4 -1.2x7 pv = globalP->getVector(3); assert( pv.getNumElements() == 2 ); assert( eq(pv[3], 2.8) ); assert( eq(pv[6],-1.2) ); // 5.6x1 + x5 + 1.9x8 pv = globalP->getVector(4); assert( pv.getNumElements() == 3 ); assert( eq(pv[0], 5.6) ); assert( eq(pv[4], 1.0) ); assert( eq(pv[7], 1.9) ); } // Test vector method exceptions { bool errorThrown = false; try { CoinShallowPackedVector v = globalP->getVector(-1); } catch (CoinError e) { errorThrown = true; } assert( errorThrown ); } { bool errorThrown = false; try { CoinShallowPackedVector vs = globalP->getVector(5); } catch (CoinError e) { errorThrown = true; } assert( errorThrown ); } { CoinPackedMatrix pm(*globalP); assert( pm.getExtraGap() != 0.0 ); assert( pm.getExtraMajor() != 0.0 ); pm.setExtraGap(0.0); pm.setExtraMajor(0.0); assert( pm.getExtraGap() == 0.0 ); assert( pm.getExtraMajor() == 0.0 ); pm.reverseOrdering(); assert( pm.getExtraGap() == 0.0 ); assert( pm.getExtraMajor() == 0.0 ); } // Test ordered triples constructor { /************************************************************************* * Setup data to represent this matrix by rows * * 3x1 + x2 - 2x4 - x5 - x8 * 2x2y+ 1.1x3 * x3 + x6y * 2.8x4 -1.2x7 * 5.6x1 + x5 + 1.9x8 * *************************************************************************/ const int ne=17; int ri[ne]; int ci[ne]; double el[ne]; ri[ 0]=1; ci[ 0]=2; el[ 0]=1.1; ri[ 1]=0; ci[ 1]=3; el[ 1]=-2.0; ri[ 2]=4; ci[ 2]=7; el[ 2]=1.9; ri[ 3]=3; ci[ 3]=6; el[ 3]=-1.2; ri[ 4]=2; ci[ 4]=5; el[ 4]=1.0; ri[ 5]=4; ci[ 5]=0; el[ 5]=5.6; ri[ 6]=0; ci[ 6]=7; el[ 6]=-1.0; ri[ 7]=0; ci[ 7]=0; el[ 7]=3.0; ri[ 8]=0; ci[ 8]=4; el[ 8]=-1.0; ri[ 9]=4; ci[ 9]=4; el[ 9]=1.0; ri[10]=3; ci[10]=3; el[10]=2.0; // (3,3) is a duplicate element ri[11]=1; ci[11]=1; el[11]=2.0; ri[12]=0; ci[12]=1; el[12]=1.0; ri[13]=2; ci[13]=2; el[13]=1.0; ri[14]=3; ci[14]=3; el[14]=0.8; // (3,3) is a duplicate element ri[15]=2; ci[15]=0; el[15]=-3.1415; ri[16]=2; ci[16]=0; el[16]= 3.1415; assert(!globalP->isColOrdered()); // create col ordered matrix from triples CoinPackedMatrix pmtco(true,ri,ci,el,ne); // Test that duplicates got the correct value assert( eq( pmtco.getVector(3)[3] , 2.8 ) ); assert( eq( pmtco.getVector(0)[2] , 0.0 ) ); // Test to make sure there are no gaps in the created matrix assert( pmtco.getVectorStarts()[0]==0 ); assert( pmtco.getVectorStarts()[1]==2 ); assert( pmtco.getVectorStarts()[2]==4 ); assert( pmtco.getVectorStarts()[3]==6 ); assert( pmtco.getVectorStarts()[4]==8 ); assert( pmtco.getVectorStarts()[5]==10 ); assert( pmtco.getVectorStarts()[6]==11 ); assert( pmtco.getVectorStarts()[7]==12 ); assert( pmtco.getVectorStarts()[8]==14 ); // Test the whole matrix CoinPackedMatrix globalco; globalco.reverseOrderedCopyOf(*globalP); assert(pmtco.isEquivalent(globalco)); // create row ordered matrix from triples CoinPackedMatrix pmtro(false,ri,ci,el,ne); assert(!pmtro.isColOrdered()); assert( eq( pmtro.getVector(3)[3] , 2.8 ) ); assert( eq( pmtro.getVector(2)[0] , 0.0 ) ); assert( pmtro.getVectorStarts()[0]==0 ); assert( pmtro.getVectorStarts()[1]==5 ); assert( pmtro.getVectorStarts()[2]==7 ); assert( pmtro.getVectorStarts()[3]==9 ); assert( pmtro.getVectorStarts()[4]==11 ); assert( pmtro.getVectorStarts()[5]==14 ); assert(globalP->isEquivalent(pmtro)); } delete globalP; } #if 0 { // test append CoinPackedMatrix pm; const int ne = 4; int inx[ne] = { 1, -4, 0, 2 }; double el[ne] = { 10., 40., 1., 50. }; CoinPackedVector r(ne,inx,el); pm.appendRow(r); // This line fails } #endif }
31.687398
103
0.469449
kant
517d4a1a62061ad5166536ef1e0a5fd4a610adcc
708
cpp
C++
src/plugins/monocle/plugins/dik/util.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/monocle/plugins/dik/util.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/monocle/plugins/dik/util.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "util.h" #include <QByteArray> namespace LC { namespace Monocle { namespace Dik { quint32 Read32 (const QByteArray& data, int offset) { quint32 result = 0; for (int i = 0; i < 4; ++i) { result <<= 8; result += static_cast<uchar> (data [offset + i]); } return result; } } } }
22.83871
83
0.538136
Maledictus
517dc23312aef835ebeb65f481f6b9e7f0cfea00
18,480
cpp
C++
src/editor/BMC-Editor.midi.utility.cpp
neroroxxx/BMC
ec85174f5398e548c829821f75a14edfeabfecf1
[ "MIT" ]
36
2020-07-16T02:19:21.000Z
2022-03-21T22:11:41.000Z
src/editor/BMC-Editor.midi.utility.cpp
neroroxxx/BMC
ec85174f5398e548c829821f75a14edfeabfecf1
[ "MIT" ]
1
2021-11-24T05:49:19.000Z
2021-11-24T15:01:57.000Z
src/editor/BMC-Editor.midi.utility.cpp
neroroxxx/BMC
ec85174f5398e548c829821f75a14edfeabfecf1
[ "MIT" ]
null
null
null
/* See https://www.RoxXxtar.com/bmc for more details Copyright (c) 2020 RoxXxtar.com Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include "editor/BMC-Editor.h" void BMCEditor::utilityCommand(){ dataForBMC.reset(); if(dataForBMC.set(isWriteMessage(), incoming)){ flags.on(BMC_EDITOR_FLAG_DATA_FOR_BMC_AVAILABLE); } } // on all the following functions onlyIfConnected is used by // BMC when buttons are being read or leds have changed states. // all those functions will notify the editor but with onlyIfConnected set to "true" // This is so that these are skipped when the editor is not connected, however // if another BMC build is connected to this BMC build they can request data // from each other thru other means, those requests would have onlyIfConnected set to "false" // Additionally BMC can enable/disabled editor real time feedback which turns leds on/off // lights up buttons when pressed etc on the editor app. // this option is not store in EEPROM instead is stored in the editor app local settings // and the editor app will send it as needed. This is so that the PERFORMANCE mode // don't get these messages making the MIDI traffic less. #if BMC_MAX_BUTTONS > 32 void BMCEditor::utilitySendButtonActivity(uint32_t states, uint32_t states2, bool onlyIfConnected){ #else void BMCEditor::utilitySendButtonActivity(uint32_t states, bool onlyIfConnected){ #endif #if BMC_MAX_BUTTONS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_BUTTON ); buff.appendToSysEx32Bits(states); #if BMC_MAX_BUTTONS > 32 buff.appendToSysEx32Bits(states2); #endif // don't show midi activity sendToEditor(buff,true,false); } #endif } void BMCEditor::utilitySendGlobalButtonActivity(uint32_t states, bool onlyIfConnected){ #if BMC_MAX_GLOBAL_BUTTONS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_GLOBAL_BUTTON ); buff.appendToSysEx32Bits(states); // don't show midi activity sendToEditor(buff,true,false); } #endif } void BMCEditor::utilitySendLedActivity(uint32_t data, bool onlyIfConnected){ #if BMC_MAX_LEDS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_LED ); buff.appendToSysEx32Bits(data); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendAuxJackActivity(uint8_t data, bool onlyIfConnected){ #if BMC_MAX_AUX_JACKS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_AUX_JACK ); buff.appendToSysEx7Bits(data); sendToEditor(buff, true, false); // don't show midi activity } #endif } void BMCEditor::utilitySendFasState(uint8_t data, bool onlyIfConnected){ #if defined(BMC_USE_FAS) if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_FAS_STATE ); buff.appendToSysEx7Bits(data); sendToEditor(buff, true, false); // don't show midi activity } #endif } void BMCEditor::utilitySendNLRelayActivity(uint16_t data, bool onlyIfConnected){ #if BMC_MAX_NL_RELAYS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_NL_RELAY ); buff.appendToSysEx16Bits(data); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendLRelayActivity(uint16_t data, bool onlyIfConnected){ #if BMC_MAX_L_RELAYS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_L_RELAY ); buff.appendToSysEx16Bits(data); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendPixelActivity(uint32_t data, bool onlyIfConnected){ #if BMC_MAX_PIXELS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_PIXEL ); buff.appendToSysEx32Bits(data); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendRgbPixelActivity(uint32_t red, uint32_t green, uint32_t blue, bool onlyIfConnected){ #if BMC_MAX_RGB_PIXELS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_RGB_PIXEL ); buff.appendToSysEx32Bits(red); buff.appendToSysEx32Bits(green); buff.appendToSysEx32Bits(blue); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendGlobalLedActivity(uint16_t data, bool onlyIfConnected){ #if BMC_MAX_GLOBAL_LEDS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_GLOBAL_LED ); buff.appendToSysEx16Bits(data); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendPwmLedActivity(uint32_t data, bool onlyIfConnected){ #if BMC_MAX_PWM_LEDS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_PWM_LED ); buff.appendToSysEx32Bits(data); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendPotActivity(uint8_t index, uint8_t value, bool onlyIfConnected){ #if BMC_MAX_POTS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing() && index < BMC_MAX_POTS){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_POT); buff.appendToSysEx7Bits(index); buff.appendToSysEx7Bits(value); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendPotsActivity(uint8_t *values, uint8_t length, bool onlyIfConnected){ #if BMC_MAX_POTS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_POTS ); buff.appendToSysEx7Bits(length); for(uint8_t i = 0; i < length; i++){ buff.appendToSysEx7Bits(values[i]); } sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendGlobalPotActivity(uint8_t index, uint8_t value, bool onlyIfConnected){ #if BMC_MAX_GLOBAL_POTS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing() && index < BMC_MAX_GLOBAL_POTS){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_GLOBAL_POT); buff.appendToSysEx7Bits(index); buff.appendToSysEx7Bits(value); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendGlobalPotsActivity(uint8_t *values, uint8_t length, bool onlyIfConnected){ #if BMC_MAX_GLOBAL_POTS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_GLOBAL_POTS ); buff.appendToSysEx7Bits(length); for(uint8_t i = 0; i < length; i++){ buff.appendToSysEx7Bits(values[i]); } sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendEncoderActivity(uint8_t index, bool increased, bool onlyIfConnected){ #if BMC_MAX_ENCODERS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing() && index < BMC_MAX_ENCODERS){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_ENCODER ); buff.appendToSysEx7Bits(index); buff.appendToSysEx7Bits(increased); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendGlobalEncoderActivity(uint8_t index, bool increased, bool onlyIfConnected){ #if BMC_MAX_GLOBAL_ENCODERS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing() && index < BMC_MAX_GLOBAL_ENCODERS){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_GLOBAL_ENCODER ); buff.appendToSysEx7Bits(index); buff.appendToSysEx7Bits(increased); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendPreset(bmcPreset_t presetNumber, bool onlyIfConnected){ #if BMC_MAX_PRESETS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } if(presetNumber >= BMC_MAX_PRESETS){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_PRESET ); buff.appendToSysEx8Bits(presetNumber); #if BMC_NAME_LEN_PRESETS > 1 bmcStoreGlobalPresets& item = store.global.presets[presetNumber]; buff.appendToSysEx7Bits(BMC_NAME_LEN_PRESETS); buff.appendCharArrayToSysEx(item.name, BMC_NAME_LEN_PRESETS); #endif sendToEditor(buff,true,false); // don't show midi activity #endif } void BMCEditor::utilitySendClickTrackData(uint16_t freq, uint8_t level, uint8_t state, bool onlyIfConnected){ #ifdef BMC_USE_CLICK_TRACK if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_CLICK_TRACK ); buff.appendToSysEx16Bits(freq); buff.appendToSysEx7Bits(level); buff.appendToSysEx7Bits(state); sendToEditor(buff,true,false); // don't show midi activity #endif } void BMCEditor::utilitySendPotCalibrationStatus(bool status, bool canceled, bool onlyIfConnected){ #if BMC_MAX_POTS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, 0, BMC_UTILF_POT_CALIBRATION_STATUS ); buff.appendToSysEx7Bits(status?1:0); buff.appendToSysEx7Bits(canceled?1:0); // don't show midi activity sendToEditor(buff,true,false); #endif } void BMCEditor::utilitySendGlobalPotCalibrationStatus(bool status, bool canceled, bool onlyIfConnected){ #if BMC_MAX_GLOBAL_POTS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, 0, BMC_UTILF_GLOBAL_POT_CALIBRATION_STATUS ); buff.appendToSysEx7Bits(status?1:0); buff.appendToSysEx7Bits(canceled?1:0); // don't show midi activity sendToEditor(buff,true,false); #endif } // send a message to the editor with the sketchbytes // used when sketch bytes are updated by the Sketch API void BMCEditor::utilitySendSketchBytes(bool onlyIfConnected){ #if BMC_MAX_SKETCH_BYTES > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, 0, BMC_UTILF_SKETCH_BYTES ); buff.appendToSysEx7Bits(BMC_MAX_SKETCH_BYTES); for(uint8_t i = 0 ; i < BMC_MAX_SKETCH_BYTES ; i++){ buff.appendToSysEx8Bits(store.global.sketchBytes[i]); } // don't show midi activity sendToEditor(buff,true,false); #endif }
29.010989
93
0.695238
neroroxxx
517efa2467c899b605c19800a56ab2b618abba44
8,412
cpp
C++
newweb/browser/render_process/webengine/dom/Document.cpp
cauthu/shadow-browser-plugin
e1eb930b1bdf71cb3cdcbb1d70467e6e6203c298
[ "BSD-3-Clause" ]
null
null
null
newweb/browser/render_process/webengine/dom/Document.cpp
cauthu/shadow-browser-plugin
e1eb930b1bdf71cb3cdcbb1d70467e6e6203c298
[ "BSD-3-Clause" ]
null
null
null
newweb/browser/render_process/webengine/dom/Document.cpp
cauthu/shadow-browser-plugin
e1eb930b1bdf71cb3cdcbb1d70467e6e6203c298
[ "BSD-3-Clause" ]
null
null
null
#include <event2/event.h> #include <strings.h> #include <boost/bind.hpp> #include "../../../../utility/easylogging++.h" #include "../../../../utility/common.hpp" #include "../../../../utility/folly/ScopeGuard.h" #include "Document.hpp" #include "../webengine.hpp" #include "../events/EventTypeNames.hpp" #include "../html/HTMLScriptElement.hpp" #include "../html/HTMLLinkElement.hpp" #include "../html/HTMLImageElement.hpp" using std::make_pair; using std::shared_ptr; #define _LOG_PREFIX(inst) << "doc= " << (inst)->objId() << ": " /* "inst" stands for instance, as in, instance of a class */ #define vloginst(level, inst) VLOG(level) _LOG_PREFIX(inst) #define vlogself(level) vloginst(level, this) #define dvloginst(level, inst) DVLOG(level) _LOG_PREFIX(inst) #define dvlogself(level) dvloginst(level, this) #define loginst(level, inst) LOG(level) _LOG_PREFIX(inst) #define logself(level) loginst(level, this) namespace blink { Document::Document(struct ::event_base* evbase, const uint32_t& instNum, Webengine* webengine, const PageModel* page_model, ResourceFetcher* resource_fetcher) : EventTarget(instNum, webengine) , evbase_(evbase) , webengine_(webengine) , page_model_(page_model) , resource_fetcher_(resource_fetcher) , state_(ReadyState::Initial) , executeScriptsWaitingForResourcesTimer_( new Timer(evbase, true, boost::bind(&Document::_executeScriptsWaitingForResourcesTimerFired, this, _1))) , has_body_element_(false) , finished_parsing_(false) , load_start_time_ms_(0) { CHECK_NOTNULL(evbase_); PageModel::DocumentInfo doc_info; auto rv = page_model_->get_main_doc_info(doc_info); CHECK(rv); add_event_handling_scopes(doc_info.event_handling_scopes); vlogself(2) << "number of event handling scopes: " << doc_info.event_handling_scopes.size(); parser_.reset( new HTMLDocumentParser(page_model, this, webengine_, resource_fetcher_)); } void Document::load() { CHECK_EQ(state_, ReadyState::Initial); state_ = ReadyState::Loading; load_start_time_ms_ = common::gettimeofdayMs(); _load_main_resource(); } void Document::setReadyState(ReadyState readyState) { if (readyState == state_) { return; } state_ = readyState; switch (readyState) { case ReadyState::Initial: case ReadyState::Loading: case ReadyState::Interactive: break; case ReadyState::Complete: fireEventHandlingScopes(EventTypeNames::readystatechange_complete); break; } } void Document::implicitClose() { CHECK_EQ(state_, ReadyState::Complete); // in real webkit, this will be done by LocalDOMWindow, i.e., the // window, not the document, fires "load" event. but we'll // approximate it here fireEventHandlingScopes(EventTypeNames::load); } bool Document::parsing() const { return !finished_parsing_; } void Document::add_elem(const uint32_t& elemInstNum) { PageModel::ElementInfo elem_info; vlogself(2) << "begin, elem:" << elemInstNum; CHECK(!inMap(elements_, elemInstNum)); const auto rv = page_model_->get_element_info(elemInstNum, elem_info); CHECK(rv); Element* element = nullptr; SCOPE_EXIT { // should have cleared element before exiting this func CHECK(!element); }; if (elem_info.tag == "script") { element = new HTMLScriptElement(elemInstNum, this, elem_info); HTMLScriptElement* script_elem = (HTMLScriptElement*)element; if (script_elem->is_parser_blocking()) { vlogself(2) << "this script blocks parser"; parser_->set_parser_blocking_script(script_elem); } } else if (elem_info.tag == "link") { element = new HTMLLinkElement(elemInstNum, this, elem_info); } else if (elem_info.tag == "img") { element = new HTMLImageElement(elemInstNum, this, elem_info); } else if (elem_info.tag == "body") { CHECK(!has_body_element_); has_body_element_ = true; webengine_->maybe_sched_INITIAL_render_update_scope(); return; } else { logself(FATAL) << "element tag [" << elem_info.tag << "] not supported"; } CHECK_NOTNULL(element); std::shared_ptr<Element> elem_shptr( element, [](Element* e) { e->destroy(); } ); element = nullptr; const auto ret = elements_.insert(make_pair(elemInstNum, elem_shptr)); CHECK(ret.second); vlogself(2) << "done"; } void Document::set_elem_res(const uint32_t elemInstNum, const uint32_t resInstNum) { VLOG(2) << "begin, elem:" << elemInstNum << " res:" << resInstNum; if (inMap(elements_, elemInstNum)) { shared_ptr<Element> element = elements_[elemInstNum]; CHECK_NOTNULL(element.get()); element->setResInstNum(resInstNum); } else { // this can happen because scripts can set diff elems // depending on their existence. but that is something we // cannot model yet LOG(WARNING) << "elem:" << elemInstNum << " does not (yet) exist"; } VLOG(2) << "done"; } bool Document::isScriptExecutionReady() const { return pendingStylesheets_.empty(); } void Document::addPendingSheet(Element* element) { const auto elemInstNum = element->instNum(); const auto it = pendingStylesheets_.find(elemInstNum); CHECK(it == pendingStylesheets_.end()) << "elem:" << elemInstNum << " already a pending stylesheet"; pendingStylesheets_.insert(elemInstNum); vlogself(2) << "elem:" << elemInstNum << " increments pendingStylesheets_ to " << pendingStylesheets_.size(); } void Document::removePendingSheet(Element* element) { const auto elemInstNum = element->instNum(); const auto it = pendingStylesheets_.find(elemInstNum); CHECK(it != pendingStylesheets_.end()) << "elem:" << element->instNum() << " not a pending stylesheet"; pendingStylesheets_.erase(it); vlogself(2) << "elem:" << elemInstNum << " decrements pendingStylesheets_ to " << pendingStylesheets_.size(); if (pendingStylesheets_.size()) { return; } vlogself(2) << "schedule timer to execute scripts"; _didLoadAllScriptBlockingResources(); } void Document::finishedParsing() { const auto elapsed_ms = common::gettimeofdayMs() - load_start_time_ms_; logself(INFO) << "has finished parsing (after " << elapsed_ms << " ms)"; finished_parsing_ = true; fireEventHandlingScopes(EventTypeNames::DOMContentLoaded); webengine_->finishedParsing(); } void Document::_didLoadAllScriptBlockingResources() { if (!executeScriptsWaitingForResourcesTimer_->is_running()) { // fire asap static const uint32_t delayMs = 0; const auto rv = executeScriptsWaitingForResourcesTimer_->start(delayMs, false); CHECK(rv); } } void Document::_executeScriptsWaitingForResourcesTimerFired(Timer*) { // after the timer is scheduled but before it fires, more blocking // style sheets can be added (e.g., by script) if (pendingStylesheets_.empty()) { parser_->executeScriptsWaitingForResources(); } } void Document::_load_main_resource() { main_resource_ = resource_fetcher_->getMainResource(); CHECK(main_resource_); // make sure it's not being loaded yet CHECK(!main_resource_->isFinished()); CHECK(!main_resource_->isLoading()); main_resource_->addClient(this); main_resource_->load(); } void Document::notifyFinished(Resource* resource, bool success) { /* the only resource we watch is our main resource */ vlogself(2) << "begin, success= " << success; CHECK_EQ(main_resource_.get(), resource); CHECK(success) << "TODO: deal with failure of main resource"; parser_->finish_receive(); vlogself(2) << "done"; } void Document::dataReceived(Resource* resource, size_t length) { vlogself(2) << "begin, " << length << " more bytes"; CHECK_EQ(main_resource_.get(), resource); vlogself(2) << "pump the parser"; parser_->appendBytes(length); parser_->pumpTokenizerIfPossible(); vlogself(2) << "done"; } void Document::responseReceived(Resource* resource) { CHECK_EQ(main_resource_.get(), resource); } } // end namespace blink
26.620253
98
0.666429
cauthu
5183065061469c4b6fdb4010bde946649fdbeff5
1,487
cpp
C++
src/search/searchdata.cpp
l1422586361/vnote
606dcef16f882350cc2be2fd108625894d13143b
[ "MIT" ]
1
2021-09-13T04:38:27.000Z
2021-09-13T04:38:27.000Z
src/search/searchdata.cpp
micalstanley/vnote-1
606dcef16f882350cc2be2fd108625894d13143b
[ "MIT" ]
null
null
null
src/search/searchdata.cpp
micalstanley/vnote-1
606dcef16f882350cc2be2fd108625894d13143b
[ "MIT" ]
null
null
null
#include "searchdata.h" #include <QJsonObject> using namespace vnotex; SearchOption::SearchOption() : m_objects(SearchObject::SearchName | SearchObject::SearchContent), m_targets(SearchTarget::SearchFile | SearchTarget::SearchFolder) { } QJsonObject SearchOption::toJson() const { QJsonObject obj; obj["file_pattern"] = m_filePattern; obj["scope"] = static_cast<int>(m_scope); obj["objects"] = static_cast<int>(m_objects); obj["targets"] = static_cast<int>(m_targets); obj["engine"] = static_cast<int>(m_engine); obj["find_options"] = static_cast<int>(m_findOptions); return obj; } void SearchOption::fromJson(const QJsonObject &p_obj) { if (p_obj.isEmpty()) { return; } m_filePattern = p_obj["file_pattern"].toString(); m_scope = static_cast<SearchScope>(p_obj["scope"].toInt()); m_objects = static_cast<SearchObjects>(p_obj["objects"].toInt()); m_targets = static_cast<SearchTargets>(p_obj["targets"].toInt()); m_engine = static_cast<SearchEngine>(p_obj["engine"].toInt()); m_findOptions = static_cast<FindOptions>(p_obj["find_options"].toInt()); } bool SearchOption::operator==(const SearchOption &p_other) const { return m_filePattern == p_other.m_filePattern && m_scope == p_other.m_scope && m_objects == p_other.m_objects && m_targets == p_other.m_targets && m_engine == p_other.m_engine && m_findOptions == p_other.m_findOptions; }
30.979167
76
0.68191
l1422586361
3d5ffe41d3f816c7d51e08c18ec2dc430aaa3e70
9,469
hpp
C++
include/pokemaze/util/algebra/Matrices.hpp
williamniemiec/PokeMaze
f5e8376cfd536610e432725d0c4f7c4474238b5b
[ "0BSD" ]
null
null
null
include/pokemaze/util/algebra/Matrices.hpp
williamniemiec/PokeMaze
f5e8376cfd536610e432725d0c4f7c4474238b5b
[ "0BSD" ]
null
null
null
include/pokemaze/util/algebra/Matrices.hpp
williamniemiec/PokeMaze
f5e8376cfd536610e432725d0c4f7c4474238b5b
[ "0BSD" ]
null
null
null
#pragma once #include <cstdio> #include <cstdlib> #include <glm/mat4x4.hpp> #include <glm/vec4.hpp> #include <glm/gtc/matrix_transform.hpp> namespace pokemaze { namespace util { namespace algebra { /** * Responsible for performing matrix operations. */ class Matrices { //------------------------------------------------------------------------- // Constructor //------------------------------------------------------------------------- private: Matrices(); //------------------------------------------------------------------------- // Methods //------------------------------------------------------------------------- public: /** * Creates matrix by defining its lines. * * @param m00 Line 0 Column 0 * @param m01 Line 0 Column 1 * @param m02 Line 0 Column 2 * @param m03 Line 0 Column 3 * @param m10 Line 1 Column 0 * @param m11 Line 1 Column 1 * @param m12 Line 1 Column 2 * @param m13 Line 1 Column 3 * @param m20 Line 2 Column 0 * @param m21 Line 2 Column 1 * @param m22 Line 2 Column 2 * @param m23 Line 2 Column 3 * @param m30 Line 3 Column 0 * @param m31 Line 3 Column 1 * @param m32 Line 3 Column 2 * @param m33 Line 3 Column 3 * * @return Matrix */ static glm::mat4 matrix( float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33 ); /** * Computes the inverse of a 4x4 matrix. * * @param matrix Matrix to be inverted * * @return Inverse of the matrix * * @see https://stackoverflow.com/questions/1148309/inverting-a-4x4-matrix/1148405 */ static glm::mat4 inverse_4x4(glm::mat4 matrix); /** * Generates identity matrix. * * @return Identity matrix */ static glm::mat4 identity(); /** * Translates a matrix. * * Example: * Let p = [px, py, pz, pw] be a point and t = [tx, ty, tz, 0] a vector * in homogeneous coordinates, defined in a Cartesian coordinate system. * Then, the matrix T is defined by the following equality: * T*p = p+t * * @param tx X-axis translation * @param ty Y-axis translation * @param tz Z-axis translation * * @return Translated matrix */ static glm::mat4 translate(float tx, float ty, float tz); /** * Performs the "scaling of a point" in relation to the origin of the * coordinate system. * * Example: * Let p = [px, py, pz, pw] be a point in homogeneous coordinates. Then, * the matrix S is defined by the following equality: * S*p = [sx*px, sy*py, sz*pz, pw] * * @param sx X-axis scale * @param sy Y-axis scale * @param sz Z-axis scale * * @return Scaled matrix */ static glm::mat4 scale(float sx, float sy, float sz); /** * Performs "rotation of a point" in relation to the origin of the * coordinate system and around the X axis (first vector of the base of * the coordinate system). * * Example: * Let p = [px, py, pz, pw] be a point in homogeneous coordinates. Then, * the matrix R is defined by the following equality: * R*p = [ px, c*py-s*pz, s*py+c*pz, pw ] * where 'c' and 's' are the cosine and the sine of the rotation angle, * respectively. * * @param angle Rotation angle * * @return Transformed matrix */ static glm::mat4 rotate_x(float angle); /** * Performs "rotation of a point" in relation to the origin of the * coordinate system and around the Y axis (second vector of the base of * the coordinate system). * * Example: * Let p = [px, py, pz, pw] be a point in homogeneous coordinates. Then, * the matrix R is defined by the following equality: * R*p = [ c*px+s*pz, py, -s*px+c*pz, pw ] * where 'c' and 's' are the cosine and the sine of the rotation angle, * respectively. * * @param angle Rotation angle * * @return Transformed matrix */ static glm::mat4 rotate_y(float angle); /** * Performs "rotation of a point" in relation to the origin of the * coordinate system and around the Z axis (third vector of the base of * the coordinate system). * * Example: * Let p = [px, py, pz, pw] be a point in homogeneous coordinates. Then, * the matrix R is defined by the following equality: * R*p = [ c*px-s*py, s*px+c*py, pz, pw ] * where 'c' and 's' are the cosine and the sine of the rotation angle, * respectively. * * @param angle Rotation angle * * @return Transformed matrix */ static glm::mat4 rotate_z(float angle); /** * Calculates the Euclidean norm of a vector whose coefficients are * defined on any orthonormal basis. * * @param v Vector * * @return Norm */ static float norm(glm::vec4 v); /** * Performs "rotation of a point" in relation to the origin of the * coordinate system and around an axis. * * @param angle Rotation angle * @param axis Reference axis (must be normalized) * * @return Transformed matrix */ static glm::mat4 rotate(float angle, glm::vec4 axis); /** * Vector product between two vectors u and v defined in an orthonormal * coordinate system. * * @param u A vector * @param v Another vector * * @return Vector product between u and v */ static glm::vec4 cross_product(glm::vec4 u, glm::vec4 v); /** * Dot product between two vectors u and v defined in an orthonormal * coordinate system. * * @param u A vector * @param v Another vector * * @return Dot product between u and v * * @throw std::invalid_argument If u or v is a point */ static float dot_product(glm::vec4 u, glm::vec4 v); /** * Coordinate change matrix for the Camera coordinate system. * * @param position_c Camera position * @param view_vector Camera direction * @param up_vector Camera up vector */ static glm::mat4 camera_view(glm::vec4 position_c, glm::vec4 view_vector, glm::vec4 up_vector); /** * Orthographic parallel projection matrix. * * @param l X-axis of the lower left rear point of the frustum * @param r X-axis of the upper right frontal point of the frustum * @param b Y-axis of the lower left rear point of the frustum * @param t Y-axis of the upper right frontal point of the frustum * @param n Z-axis of the lower left rear point of the frustum * @param f Z-axis of the upper right frontal point of the frustum */ static glm::mat4 orthographic_view(float l, float r, float b, float t, float n, float f); /** * Perspective projection matrix. * * @param field_of_view Field of view angle * @param aspect Screen ratio * @param n Near plane width * @param f Far plane width */ static glm::mat4 perspective_view(float field_of_view, float aspect, float n, float f); /** * Prints a matrix on the console. * * @param matrix Matrix to be printed */ static void print_matrix(glm::mat4 matrix); /** * Prints a vector on the console. * * @param vector Vector to be printed */ static void print_vector(glm::vec4 vector); /** * Prints a vector product between a matrix and a vector on the console. * * @param M Matrix * @param v Vector */ static void print_matrix_vector_product(glm::mat4 M, glm::vec4 v); /** * Prints a vector product between a matrix and a vector on the console * along with division by W on the console. * * @param M Matrix * @param v Vector */ static void print_matrix_vector_product_div_w(glm::mat4 M, glm::vec4 v); }; }}}
35.07037
103
0.498363
williamniemiec
3d608433952d01a65822d48f19c38e763ebce34c
168
cpp
C++
isode++/code/iso/itu/osi/als/tsap/tpdu/CC.cpp
Kampbell/ISODE
37f161e65f11348ef6fca2925d399d611df9f31b
[ "Apache-2.0" ]
3
2016-01-18T17:00:00.000Z
2021-06-25T03:18:13.000Z
isode++/code/iso/itu/osi/als/tsap/tpdu/CC.cpp
Kampbell/ISODE
37f161e65f11348ef6fca2925d399d611df9f31b
[ "Apache-2.0" ]
null
null
null
isode++/code/iso/itu/osi/als/tsap/tpdu/CC.cpp
Kampbell/ISODE
37f161e65f11348ef6fca2925d399d611df9f31b
[ "Apache-2.0" ]
null
null
null
/* * CC.cpp * * Created on: 29 juil. 2014 * Author: FrancisANDRE */ #include "als/tsap/tpdu/CC.h" namespace ALS { namespace TSAP { namespace TPDU { } } }
9.882353
29
0.60119
Kampbell
3d640ab8ac368d076aa3a34db363bad6f3a6c4e5
10,418
cpp
C++
common/src/algo_factory/algo_factory.cpp
ane-community/botan-crypto-ane
71056f5f0d5fd706e6d42e2f7ec0f7f55d86fb74
[ "MIT" ]
5
2018-01-03T06:43:07.000Z
2020-07-30T13:15:29.000Z
common/src/algo_factory/algo_factory.cpp
ane-community/botan-crypto-ane
71056f5f0d5fd706e6d42e2f7ec0f7f55d86fb74
[ "MIT" ]
null
null
null
common/src/algo_factory/algo_factory.cpp
ane-community/botan-crypto-ane
71056f5f0d5fd706e6d42e2f7ec0f7f55d86fb74
[ "MIT" ]
2
2019-11-04T02:54:49.000Z
2020-04-24T17:50:46.000Z
/* * Algorithm Factory * (C) 2008-2010 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/algo_factory.h> #include <botan/internal/algo_cache.h> #include <botan/internal/stl_util.h> #include <botan/engine.h> #include <botan/exceptn.h> #include <botan/block_cipher.h> #include <botan/stream_cipher.h> #include <botan/hash.h> #include <botan/mac.h> #include <botan/pbkdf.h> #include <algorithm> namespace Botan { namespace { /* * Template functions for the factory prototype/search algorithm */ template<typename T> T* engine_get_algo(Engine*, const SCAN_Name&, Algorithm_Factory&) { return 0; } template<> BlockCipher* engine_get_algo(Engine* engine, const SCAN_Name& request, Algorithm_Factory& af) { return engine->find_block_cipher(request, af); } template<> StreamCipher* engine_get_algo(Engine* engine, const SCAN_Name& request, Algorithm_Factory& af) { return engine->find_stream_cipher(request, af); } template<> HashFunction* engine_get_algo(Engine* engine, const SCAN_Name& request, Algorithm_Factory& af) { return engine->find_hash(request, af); } template<> MessageAuthenticationCode* engine_get_algo(Engine* engine, const SCAN_Name& request, Algorithm_Factory& af) { return engine->find_mac(request, af); } template<> PBKDF* engine_get_algo(Engine* engine, const SCAN_Name& request, Algorithm_Factory& af) { return engine->find_pbkdf(request, af); } template<typename T> const T* factory_prototype(const std::string& algo_spec, const std::string& provider, const std::vector<Engine*>& engines, Algorithm_Factory& af, Algorithm_Cache<T>* cache) { if(const T* cache_hit = cache->get(algo_spec, provider)) return cache_hit; SCAN_Name scan_name(algo_spec); if(scan_name.cipher_mode() != "") return 0; for(size_t i = 0; i != engines.size(); ++i) { if(provider == "" || engines[i]->provider_name() == provider) { if(T* impl = engine_get_algo<T>(engines[i], scan_name, af)) cache->add(impl, algo_spec, engines[i]->provider_name()); } } return cache->get(algo_spec, provider); } } /* * Setup caches */ Algorithm_Factory::Algorithm_Factory(Mutex_Factory& mf) { block_cipher_cache = new Algorithm_Cache<BlockCipher>(mf.make()); stream_cipher_cache = new Algorithm_Cache<StreamCipher>(mf.make()); hash_cache = new Algorithm_Cache<HashFunction>(mf.make()); mac_cache = new Algorithm_Cache<MessageAuthenticationCode>(mf.make()); pbkdf_cache = new Algorithm_Cache<PBKDF>(mf.make()); } /* * Delete all engines */ Algorithm_Factory::~Algorithm_Factory() { delete block_cipher_cache; delete stream_cipher_cache; delete hash_cache; delete mac_cache; delete pbkdf_cache; std::for_each(engines.begin(), engines.end(), del_fun<Engine>()); } void Algorithm_Factory::clear_caches() { block_cipher_cache->clear_cache(); stream_cipher_cache->clear_cache(); hash_cache->clear_cache(); mac_cache->clear_cache(); pbkdf_cache->clear_cache(); } void Algorithm_Factory::add_engine(Engine* engine) { clear_caches(); engines.push_back(engine); } /* * Set the preferred provider for an algorithm */ void Algorithm_Factory::set_preferred_provider(const std::string& algo_spec, const std::string& provider) { if(prototype_block_cipher(algo_spec)) block_cipher_cache->set_preferred_provider(algo_spec, provider); else if(prototype_stream_cipher(algo_spec)) stream_cipher_cache->set_preferred_provider(algo_spec, provider); else if(prototype_hash_function(algo_spec)) hash_cache->set_preferred_provider(algo_spec, provider); else if(prototype_mac(algo_spec)) mac_cache->set_preferred_provider(algo_spec, provider); else if(prototype_pbkdf(algo_spec)) pbkdf_cache->set_preferred_provider(algo_spec, provider); } /* * Get an engine out of the list */ Engine* Algorithm_Factory::get_engine_n(size_t n) const { if(n >= engines.size()) return 0; return engines[n]; } /* * Return the possible providers of a request * Note: assumes you don't have different types by the same name */ std::vector<std::string> Algorithm_Factory::providers_of(const std::string& algo_spec) { /* The checks with if(prototype_X(algo_spec)) have the effect of forcing a full search, since otherwise there might not be any providers at all in the cache. */ if(prototype_block_cipher(algo_spec)) return block_cipher_cache->providers_of(algo_spec); else if(prototype_stream_cipher(algo_spec)) return stream_cipher_cache->providers_of(algo_spec); else if(prototype_hash_function(algo_spec)) return hash_cache->providers_of(algo_spec); else if(prototype_mac(algo_spec)) return mac_cache->providers_of(algo_spec); else if(prototype_pbkdf(algo_spec)) return pbkdf_cache->providers_of(algo_spec); else return std::vector<std::string>(); } /* * Return the prototypical block cipher corresponding to this request */ const BlockCipher* Algorithm_Factory::prototype_block_cipher(const std::string& algo_spec, const std::string& provider) { return factory_prototype<BlockCipher>(algo_spec, provider, engines, *this, block_cipher_cache); } /* * Return the prototypical stream cipher corresponding to this request */ const StreamCipher* Algorithm_Factory::prototype_stream_cipher(const std::string& algo_spec, const std::string& provider) { return factory_prototype<StreamCipher>(algo_spec, provider, engines, *this, stream_cipher_cache); } /* * Return the prototypical object corresponding to this request (if found) */ const HashFunction* Algorithm_Factory::prototype_hash_function(const std::string& algo_spec, const std::string& provider) { return factory_prototype<HashFunction>(algo_spec, provider, engines, *this, hash_cache); } /* * Return the prototypical object corresponding to this request */ const MessageAuthenticationCode* Algorithm_Factory::prototype_mac(const std::string& algo_spec, const std::string& provider) { return factory_prototype<MessageAuthenticationCode>(algo_spec, provider, engines, *this, mac_cache); } /* * Return the prototypical object corresponding to this request */ const PBKDF* Algorithm_Factory::prototype_pbkdf(const std::string& algo_spec, const std::string& provider) { return factory_prototype<PBKDF>(algo_spec, provider, engines, *this, pbkdf_cache); } /* * Return a new block cipher corresponding to this request */ BlockCipher* Algorithm_Factory::make_block_cipher(const std::string& algo_spec, const std::string& provider) { if(const BlockCipher* proto = prototype_block_cipher(algo_spec, provider)) return proto->clone(); throw Algorithm_Not_Found(algo_spec); } /* * Return a new stream cipher corresponding to this request */ StreamCipher* Algorithm_Factory::make_stream_cipher(const std::string& algo_spec, const std::string& provider) { if(const StreamCipher* proto = prototype_stream_cipher(algo_spec, provider)) return proto->clone(); throw Algorithm_Not_Found(algo_spec); } /* * Return a new object corresponding to this request */ HashFunction* Algorithm_Factory::make_hash_function(const std::string& algo_spec, const std::string& provider) { if(const HashFunction* proto = prototype_hash_function(algo_spec, provider)) return proto->clone(); throw Algorithm_Not_Found(algo_spec); } /* * Return a new object corresponding to this request */ MessageAuthenticationCode* Algorithm_Factory::make_mac(const std::string& algo_spec, const std::string& provider) { if(const MessageAuthenticationCode* proto = prototype_mac(algo_spec, provider)) return proto->clone(); throw Algorithm_Not_Found(algo_spec); } /* * Return a new object corresponding to this request */ PBKDF* Algorithm_Factory::make_pbkdf(const std::string& algo_spec, const std::string& provider) { if(const PBKDF* proto = prototype_pbkdf(algo_spec, provider)) return proto->clone(); throw Algorithm_Not_Found(algo_spec); } /* * Add a new block cipher */ void Algorithm_Factory::add_block_cipher(BlockCipher* block_cipher, const std::string& provider) { block_cipher_cache->add(block_cipher, block_cipher->name(), provider); } /* * Add a new stream cipher */ void Algorithm_Factory::add_stream_cipher(StreamCipher* stream_cipher, const std::string& provider) { stream_cipher_cache->add(stream_cipher, stream_cipher->name(), provider); } /* * Add a new hash */ void Algorithm_Factory::add_hash_function(HashFunction* hash, const std::string& provider) { hash_cache->add(hash, hash->name(), provider); } /* * Add a new mac */ void Algorithm_Factory::add_mac(MessageAuthenticationCode* mac, const std::string& provider) { mac_cache->add(mac, mac->name(), provider); } /* * Add a new PBKDF */ void Algorithm_Factory::add_pbkdf(PBKDF* pbkdf, const std::string& provider) { pbkdf_cache->add(pbkdf, pbkdf->name(), provider); } }
29.596591
82
0.637934
ane-community
3d64a056be5621c19644728ac7b032c6a8a76f9c
2,440
cpp
C++
emulator/src/devices/cpu/sh/sh7604_wdt.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/devices/cpu/sh/sh7604_wdt.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/devices/cpu/sh/sh7604_wdt.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:BSD-3-Clause // copyright-holders:Angelo Salese /*************************************************************************** SH7604 Watchdog Timer Controller TODO: - Host CPU setter (clock and callback for irq and reset lines); - memory map (needs to verify if ID write is ok); ***************************************************************************/ #include "emu.h" #include "sh7604_wdt.h" //************************************************************************** // GLOBAL VARIABLES //************************************************************************** // device type definition DEFINE_DEVICE_TYPE(SH7604_WDT, sh7604_wdt_device, "sh7604wdt", "SH7604 Watchdog Timer") //************************************************************************** // LIVE DEVICE //************************************************************************** ADDRESS_MAP_START(sh7604_wdt_device::wdt_regs) // AM_RANGE(0x00, 0x00) timer control/status // AM_RANGE(0x01, 0x01) timer counter // AM_RANGE(0x02, 0x02) write only, reset control register // AM_RANGE(0x03, 0x03) read status register, write reset status register ADDRESS_MAP_END //------------------------------------------------- // sh7604_wdt_device - constructor //------------------------------------------------- sh7604_wdt_device::sh7604_wdt_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : device_t(mconfig, SH7604_WDT, tag, owner, clock) { } //------------------------------------------------- // device_start - device-specific startup //------------------------------------------------- void sh7604_wdt_device::device_start() { } //------------------------------------------------- // device_reset - device-specific reset //------------------------------------------------- void sh7604_wdt_device::device_reset() { } //************************************************************************** // READ/WRITE HANDLERS //************************************************************************** READ8_MEMBER( sh7604_wdt_device::read ) { return space.read_byte(offset); } WRITE16_MEMBER( sh7604_wdt_device::write ) { uint8_t id_param = data >> 8; switch(id_param) { case 0xa5: space.write_byte(offset*2+0,data & 0xff); break; case 0x5a: space.write_byte(offset*2+1,data & 0xff); break; default: throw emu_fatalerror("%s: invalid id param write = %02x\n",tag(),id_param); } }
29.047619
117
0.458607
rjw57
3d674e75f4301f260f133e265014501c3167b91e
20,853
cpp
C++
module/mpc-be/SRC/src/filters/source/SubtitleSource/SubtitleSource.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
module/mpc-be/SRC/src/filters/source/SubtitleSource/SubtitleSource.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
module/mpc-be/SRC/src/filters/source/SubtitleSource/SubtitleSource.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
/* * (C) 2003-2006 Gabest * (C) 2006-2020 see Authors.txt * * This file is part of MPC-BE. * * MPC-BE is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * MPC-BE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "stdafx.h" #include "SubtitleSource.h" #include "../../../DSUtil/DSUtil.h" #include <moreuuids.h> #include <basestruct.h> static int _WIDTH = 640; static int _HEIGHT = 480; static int _ATPF = 400000; #ifdef REGISTER_FILTER const AMOVIESETUP_MEDIATYPE sudPinTypesOut[] = { {&MEDIATYPE_Subtitle, &MEDIASUBTYPE_NULL}, {&MEDIATYPE_Text, &MEDIASUBTYPE_NULL}, {&MEDIATYPE_Video, &MEDIASUBTYPE_RGB32}, }; const AMOVIESETUP_PIN sudOpPin[] = { {L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, nullptr, _countof(sudPinTypesOut), sudPinTypesOut}, }; const AMOVIESETUP_FILTER sudFilter[] = { {&__uuidof(CSubtitleSourceASCII), L"MPC SubtitleSource (S_TEXT/ASCII)", MERIT_NORMAL, _countof(sudOpPin), sudOpPin, CLSID_LegacyAmFilterCategory}, {&__uuidof(CSubtitleSourceUTF8), L"MPC SubtitleSource (S_TEXT/UTF8)", MERIT_NORMAL, _countof(sudOpPin), sudOpPin, CLSID_LegacyAmFilterCategory}, {&__uuidof(CSubtitleSourceSSA), L"MPC SubtitleSource (S_TEXT/SSA)", MERIT_NORMAL, _countof(sudOpPin), sudOpPin, CLSID_LegacyAmFilterCategory}, {&__uuidof(CSubtitleSourceASS), L"MPC SubtitleSource (S_TEXT/ASS)", MERIT_NORMAL, _countof(sudOpPin), sudOpPin, CLSID_LegacyAmFilterCategory}, {&__uuidof(CSubtitleSourceUSF), L"MPC SubtitleSource (S_TEXT/USF)", MERIT_NORMAL, _countof(sudOpPin), sudOpPin, CLSID_LegacyAmFilterCategory}, {&__uuidof(CSubtitleSourcePreview), L"MPC SubtitleSource (Preview)", MERIT_NORMAL, _countof(sudOpPin), sudOpPin, CLSID_LegacyAmFilterCategory}, {&__uuidof(CSubtitleSourceARGB), L"MPC SubtitleSource (ARGB)", MERIT_NORMAL, _countof(sudOpPin), sudOpPin, CLSID_LegacyAmFilterCategory}, }; CFactoryTemplate g_Templates[] = { {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CSubtitleSourceASCII>, nullptr, &sudFilter[0]}, {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CSubtitleSourceUTF8>, nullptr, &sudFilter[1]}, {sudFilter[2].strName, sudFilter[2].clsID, CreateInstance<CSubtitleSourceSSA>, nullptr, &sudFilter[2]}, {sudFilter[3].strName, sudFilter[3].clsID, CreateInstance<CSubtitleSourceASS>, nullptr, &sudFilter[3]}, // {sudFilter[4].strName, sudFilter[4].clsID, CreateInstance<CSubtitleSourceUSF>, nullptr, &sudFilter[4]}, {sudFilter[5].strName, sudFilter[5].clsID, CreateInstance<CSubtitleSourcePreview>, nullptr, &sudFilter[5]}, {sudFilter[6].strName, sudFilter[6].clsID, CreateInstance<CSubtitleSourceARGB>, nullptr, &sudFilter[6]}, }; int g_cTemplates = _countof(g_Templates); STDAPI DllRegisterServer() { /*CString clsid = CStringFromGUID(__uuidof(CSubtitleSourcePreview)); SetRegKeyValue( L"Media Type\\Extensions", L".sub", L"Source Filter", clsid); SetRegKeyValue( L"Media Type\\Extensions", L".srt", L"Source Filter", clsid); SetRegKeyValue( L"Media Type\\Extensions", L".smi", L"Source Filter", clsid); SetRegKeyValue( L"Media Type\\Extensions", L".ssa", L"Source Filter", clsid); SetRegKeyValue( L"Media Type\\Extensions", L".ass", L"Source Filter", clsid); SetRegKeyValue( L"Media Type\\Extensions", L".xss", L"Source Filter", clsid); SetRegKeyValue( L"Media Type\\Extensions", L".usf", L"Source Filter", clsid);*/ return AMovieDllRegisterServer2(TRUE); } STDAPI DllUnregisterServer() { DeleteRegKey(L"Media Type\\Extensions", L".sub"); DeleteRegKey(L"Media Type\\Extensions", L".srt"); DeleteRegKey(L"Media Type\\Extensions", L".smi"); DeleteRegKey(L"Media Type\\Extensions", L".ssa"); DeleteRegKey(L"Media Type\\Extensions", L".ass"); DeleteRegKey(L"Media Type\\Extensions", L".xss"); DeleteRegKey(L"Media Type\\Extensions", L".usf"); /**/ return AMovieDllRegisterServer2(FALSE); } #include "../../filters/Filters.h" class CSubtitleSourceApp : public CFilterApp { public: BOOL InitInstance() { if (!__super::InitInstance()) { return FALSE; } _WIDTH = GetProfileInt(L"SubtitleSource", L"w", 640); _HEIGHT = GetProfileInt(L"SubtitleSource", L"h", 480); _ATPF = GetProfileInt(L"SubtitleSource", L"atpf", 400000); if (_ATPF <= 0) { _ATPF = 400000; } WriteProfileInt(L"SubtitleSource", L"w", _WIDTH); WriteProfileInt(L"SubtitleSource", L"h", _HEIGHT); WriteProfileInt(L"SubtitleSource", L"atpf", _ATPF); return TRUE; } }; CSubtitleSourceApp theApp; #endif // // CSubtitleSource // CSubtitleSource::CSubtitleSource(LPUNKNOWN lpunk, HRESULT* phr, const CLSID& clsid) : CSource(L"CSubtitleSource", lpunk, clsid) { } CSubtitleSource::~CSubtitleSource() { } STDMETHODIMP CSubtitleSource::NonDelegatingQueryInterface(REFIID riid, void** ppv) { CheckPointer(ppv, E_POINTER); return QI(IFileSourceFilter) QI(IAMFilterMiscFlags) __super::NonDelegatingQueryInterface(riid, ppv); } // IFileSourceFilter STDMETHODIMP CSubtitleSource::Load(LPCOLESTR pszFileName, const AM_MEDIA_TYPE* pmt) { if (GetPinCount() > 0) { return VFW_E_ALREADY_CONNECTED; } HRESULT hr = S_OK; if (!(DNew CSubtitleStream(pszFileName, this, &hr))) { return E_OUTOFMEMORY; } if (FAILED(hr)) { return hr; } m_fn = pszFileName; return S_OK; } STDMETHODIMP CSubtitleSource::GetCurFile(LPOLESTR* ppszFileName, AM_MEDIA_TYPE* pmt) { CheckPointer(ppszFileName, E_POINTER); size_t nCount = m_fn.GetLength() + 1; *ppszFileName = (LPOLESTR)CoTaskMemAlloc(nCount * sizeof(WCHAR)); CheckPointer(*ppszFileName, E_OUTOFMEMORY); wcscpy_s(*ppszFileName, nCount, m_fn); return S_OK; } // IAMFilterMiscFlags ULONG CSubtitleSource::GetMiscFlags() { return AM_FILTER_MISC_FLAGS_IS_SOURCE; } STDMETHODIMP CSubtitleSource::QueryFilterInfo(FILTER_INFO* pInfo) { CheckPointer(pInfo, E_POINTER); ValidateReadWritePtr(pInfo, sizeof(FILTER_INFO)); wcscpy_s(pInfo->achName, SubtitleSourceName); pInfo->pGraph = m_pGraph; if (m_pGraph) { m_pGraph->AddRef(); } return S_OK; } // // CSubtitleStream // CSubtitleStream::CSubtitleStream(const WCHAR* wfn, CSubtitleSource* pParent, HRESULT* phr) : CSourceStream(L"SubtitleStream", phr, pParent, L"Output") , CSourceSeeking(L"SubtitleStream", (IPin*)this, phr, &m_cSharedState) , m_bDiscontinuity(FALSE), m_bFlushing(FALSE) , m_nPosition(0) , m_rts(nullptr) { CAutoLock cAutoLock(&m_cSharedState); CString fn(wfn); if (!m_rts.Open(fn, DEFAULT_CHARSET)) { if (phr) { *phr = E_FAIL; } return; } m_rts.CreateDefaultStyle(DEFAULT_CHARSET); m_rts.ConvertToTimeBased(25); m_rts.Sort(); m_rtDuration = 0; for (size_t i = 0, cnt = m_rts.GetCount(); i < cnt; i++) { m_rtDuration = std::max(m_rtDuration.GetUnits(), 10000i64*m_rts[i].end); } m_rtStop = m_rtDuration; if (phr) { *phr = m_rtDuration > 0 ? S_OK : E_FAIL; } } CSubtitleStream::~CSubtitleStream() { CAutoLock cAutoLock(&m_cSharedState); } STDMETHODIMP CSubtitleStream::NonDelegatingQueryInterface(REFIID riid, void** ppv) { CheckPointer(ppv, E_POINTER); return (riid == IID_IMediaSeeking) ? CSourceSeeking::NonDelegatingQueryInterface(riid, ppv) //GetInterface((IMediaSeeking*)this, ppv) : CSourceStream::NonDelegatingQueryInterface(riid, ppv); } void CSubtitleStream::UpdateFromSeek() { if (ThreadExists()) { // next time around the loop, the worker thread will // pick up the position change. // We need to flush all the existing data - we must do that here // as our thread will probably be blocked in GetBuffer otherwise m_bFlushing = TRUE; DeliverBeginFlush(); // make sure we have stopped pushing Stop(); // complete the flush DeliverEndFlush(); m_bFlushing = FALSE; // restart Run(); } } HRESULT CSubtitleStream::SetRate(double dRate) { if (dRate <= 0) { return E_INVALIDARG; } { CAutoLock lock(CSourceSeeking::m_pLock); m_dRateSeeking = dRate; } UpdateFromSeek(); return S_OK; } HRESULT CSubtitleStream::OnThreadStartPlay() { m_bDiscontinuity = TRUE; return DeliverNewSegment(m_rtStart, m_rtStop, m_dRateSeeking); } HRESULT CSubtitleStream::ChangeStart() { { CAutoLock lock(CSourceSeeking::m_pLock); OnThreadCreate(); /*if (m_mt.majortype == MEDIATYPE_Video && m_mt.subtype == MEDIASUBTYPE_ARGB32) { m_nPosition = (int)(m_rtStart/10000)*1/1000; } else if (m_mt.majortype == MEDIATYPE_Video && m_mt.subtype == MEDIASUBTYPE_RGB32) { int m_nSegments = 0; if (!m_rts.SearchSubs((int)(m_rtStart/10000), 25, &m_nPosition, &m_nSegments)) m_nPosition = m_nSegments; } else { m_nPosition = m_rts.SearchSub((int)(m_rtStart/10000), 25); if (m_nPosition < 0) m_nPosition = 0; else if (m_rts[m_nPosition].end <= (int)(m_rtStart/10000)) m_nPosition++; }*/ } UpdateFromSeek(); return S_OK; } HRESULT CSubtitleStream::ChangeStop() { /*{ CAutoLock lock(CSourceSeeking::m_pLock); if (m_rtPosition < m_rtStop) return S_OK; }*/ // We're already past the new stop time -- better flush the graph. UpdateFromSeek(); return S_OK; } HRESULT CSubtitleStream::OnThreadCreate() { CAutoLock cAutoLockShared(&m_cSharedState); if (m_mt.majortype == MEDIATYPE_Video && m_mt.subtype == MEDIASUBTYPE_ARGB32) { m_nPosition = (int)(m_rtStart/_ATPF); } else if (m_mt.majortype == MEDIATYPE_Video && m_mt.subtype == MEDIASUBTYPE_RGB32) { int m_nSegments = 0; if (!m_rts.SearchSubs((int)(m_rtStart/10000), 10000000.0/_ATPF, &m_nPosition, &m_nSegments)) { m_nPosition = m_nSegments; } } else { m_nPosition = m_rts.SearchSub((int)(m_rtStart/10000), 25); if (m_nPosition < 0) { m_nPosition = 0; } else if (m_rts[m_nPosition].end <= (int)(m_rtStart/10000)) { m_nPosition++; } } return CSourceStream::OnThreadCreate(); } HRESULT CSubtitleStream::DecideBufferSize(IMemAllocator* pAlloc, ALLOCATOR_PROPERTIES* pProperties) { //CAutoLock cAutoLock(m_pFilter->pStateLock()); ASSERT(pAlloc); ASSERT(pProperties); HRESULT hr = NOERROR; if (m_mt.majortype == MEDIATYPE_Video) { pProperties->cBuffers = 2; pProperties->cbBuffer = ((VIDEOINFOHEADER*)m_mt.pbFormat)->bmiHeader.biSizeImage; } else { pProperties->cBuffers = 1; pProperties->cbBuffer = 0x10000; } ALLOCATOR_PROPERTIES Actual; if (FAILED(hr = pAlloc->SetProperties(pProperties, &Actual))) { return hr; } if (Actual.cbBuffer < pProperties->cbBuffer) { return E_FAIL; } ASSERT(Actual.cBuffers == pProperties->cBuffers); return NOERROR; } HRESULT CSubtitleStream::FillBuffer(IMediaSample* pSample) { HRESULT hr; { CAutoLock cAutoLockShared(&m_cSharedState); BYTE* pData = nullptr; if (FAILED(hr = pSample->GetPointer(&pData)) || !pData) { return S_FALSE; } AM_MEDIA_TYPE* pmt; if (SUCCEEDED(pSample->GetMediaType(&pmt)) && pmt) { CMediaType mt(*pmt); SetMediaType(&mt); DeleteMediaType(pmt); } int len = 0; REFERENCE_TIME rtStart, rtStop; if (m_mt.majortype == MEDIATYPE_Video && m_mt.subtype == MEDIASUBTYPE_ARGB32) { rtStart = (REFERENCE_TIME)((m_nPosition*_ATPF - m_rtStart) / m_dRateSeeking); rtStop = (REFERENCE_TIME)(((m_nPosition+1)*_ATPF - m_rtStart) / m_dRateSeeking); if (m_rtStart+rtStart >= m_rtDuration) { return S_FALSE; } BITMAPINFOHEADER& bmi = ((VIDEOINFOHEADER*)m_mt.pbFormat)->bmiHeader; SubPicDesc spd; spd.w = _WIDTH; spd.h = _HEIGHT; spd.bpp = 32; spd.pitch = bmi.biWidth*4; spd.bits = pData; len = spd.h*spd.pitch; for (int y = 0; y < spd.h; y++) { memsetd((DWORD*)(pData + spd.pitch*y), 0xff000000, spd.w*4); } RECT bbox; m_rts.Render(spd, m_nPosition*_ATPF, 10000000.0/_ATPF, bbox); for (int y = 0; y < spd.h; y++) { DWORD* p = (DWORD*)(pData + spd.pitch*y); for (int x = 0; x < spd.w; x++, p++) { *p = (0xff000000-(*p&0xff000000))|(*p&0xffffff); } } } else if (m_mt.majortype == MEDIATYPE_Video && m_mt.subtype == MEDIASUBTYPE_RGB32) { const STSSegment* stss = m_rts.GetSegment(m_nPosition); if (!stss) { return S_FALSE; } BITMAPINFOHEADER& bmi = ((VIDEOINFOHEADER*)m_mt.pbFormat)->bmiHeader; SubPicDesc spd; spd.w = _WIDTH; spd.h = _HEIGHT; spd.bpp = 32; spd.pitch = bmi.biWidth*4; spd.bits = pData; len = spd.h*spd.pitch; for (int y = 0; y < spd.h; y++) { DWORD c1 = 0xff606060, c2 = 0xffa0a0a0; if (y&32) { c1 ^= c2, c2 ^= c1, c1 ^= c2; } DWORD* p = (DWORD*)(pData + spd.pitch*y); for (int x = 0; x < spd.w; x+=32, p+=32) { memsetd(p, (x&32) ? c1 : c2, std::min(spd.w-x, 32) * 4); } } RECT bbox; m_rts.Render(spd, 10000i64*(stss->start+stss->end)/2, 10000000.0/_ATPF, bbox); rtStart = (REFERENCE_TIME)((10000i64*stss->start - m_rtStart) / m_dRateSeeking); rtStop = (REFERENCE_TIME)((10000i64*stss->end - m_rtStart) / m_dRateSeeking); } else { if ((size_t)m_nPosition >= m_rts.GetCount()) { return S_FALSE; } STSEntry& stse = m_rts[m_nPosition]; if (stse.start >= m_rtStop/10000) { return S_FALSE; } if (m_mt.majortype == MEDIATYPE_Subtitle && m_mt.subtype == MEDIASUBTYPE_UTF8) { CStringA str = WStrToUTF8(m_rts.GetStrW(m_nPosition, false)); memcpy((char*)pData, str, len = str.GetLength()); } else if (m_mt.majortype == MEDIATYPE_Subtitle && (m_mt.subtype == MEDIASUBTYPE_SSA || m_mt.subtype == MEDIASUBTYPE_ASS)) { CStringW line; line.Format(L"%d,%d,%s,%s,%d,%d,%d,%s,%s", stse.readorder, stse.layer, CStringW(stse.style), CStringW(stse.actor), stse.marginRect.left, stse.marginRect.right, (stse.marginRect.top+stse.marginRect.bottom)/2, CStringW(stse.effect), m_rts.GetStrW(m_nPosition, true)); CStringA str = WStrToUTF8(line); memcpy((char*)pData, str, len = str.GetLength()); } else if (m_mt.majortype == MEDIATYPE_Text && m_mt.subtype == MEDIASUBTYPE_NULL) { CStringA str = m_rts.GetStrA(m_nPosition, false); memcpy((char*)pData, str, len = str.GetLength()); } else { return S_FALSE; } rtStart = (REFERENCE_TIME)((10000i64*stse.start - m_rtStart) / m_dRateSeeking); rtStop = (REFERENCE_TIME)((10000i64*stse.end - m_rtStart) / m_dRateSeeking); } pSample->SetTime(&rtStart, &rtStop); pSample->SetActualDataLength(len); m_nPosition++; } pSample->SetSyncPoint(TRUE); if (m_bDiscontinuity) { pSample->SetDiscontinuity(TRUE); m_bDiscontinuity = FALSE; } return S_OK; } HRESULT CSubtitleStream::GetMediaType(CMediaType* pmt) { return (static_cast<CSubtitleSource*>(m_pFilter))->GetMediaType(pmt); } HRESULT CSubtitleStream::CheckMediaType(const CMediaType* pmt) { CAutoLock lock(m_pFilter->pStateLock()); CMediaType mt; GetMediaType(&mt); if (mt.majortype == pmt->majortype && mt.subtype == pmt->subtype) { return NOERROR; } return E_FAIL; } STDMETHODIMP CSubtitleStream::Notify(IBaseFilter* pSender, Quality q) { return E_NOTIMPL; } // // CSubtitleSourceASCII // CSubtitleSourceASCII::CSubtitleSourceASCII(LPUNKNOWN lpunk, HRESULT* phr) : CSubtitleSource(lpunk, phr, __uuidof(this)) { } HRESULT CSubtitleSourceASCII::GetMediaType(CMediaType* pmt) { CAutoLock cAutoLock(pStateLock()); pmt->InitMediaType(); pmt->SetType(&MEDIATYPE_Text); pmt->SetSubtype(&MEDIASUBTYPE_NULL); pmt->SetFormatType(&FORMAT_None); pmt->ResetFormatBuffer(); return NOERROR; } // // CSubtitleSourceUTF8 // CSubtitleSourceUTF8::CSubtitleSourceUTF8(LPUNKNOWN lpunk, HRESULT* phr) : CSubtitleSource(lpunk, phr, __uuidof(this)) { } HRESULT CSubtitleSourceUTF8::GetMediaType(CMediaType* pmt) { CAutoLock cAutoLock(pStateLock()); pmt->InitMediaType(); pmt->SetType(&MEDIATYPE_Subtitle); pmt->SetSubtype(&MEDIASUBTYPE_UTF8); pmt->SetFormatType(&FORMAT_SubtitleInfo); SUBTITLEINFO* psi = (SUBTITLEINFO*)pmt->AllocFormatBuffer(sizeof(SUBTITLEINFO)); memset(psi, 0, pmt->FormatLength()); strcpy_s(psi->IsoLang, "eng"); return NOERROR; } // // CSubtitleSourceSSA // CSubtitleSourceSSA::CSubtitleSourceSSA(LPUNKNOWN lpunk, HRESULT* phr) : CSubtitleSource(lpunk, phr, __uuidof(this)) { } HRESULT CSubtitleSourceSSA::GetMediaType(CMediaType* pmt) { CAutoLock cAutoLock(pStateLock()); pmt->InitMediaType(); pmt->SetType(&MEDIATYPE_Subtitle); pmt->SetSubtype(&MEDIASUBTYPE_SSA); pmt->SetFormatType(&FORMAT_SubtitleInfo); CSimpleTextSubtitle sts; sts.Open(CString(m_fn), DEFAULT_CHARSET); sts.RemoveAll(); CFile f; WCHAR path[MAX_PATH], fn[MAX_PATH]; if (!GetTempPath(MAX_PATH, path) || !GetTempFileName(path, L"mpc_sts", 0, fn)) { return E_FAIL; } _wremove(fn); wcscat_s(fn, L".ssa"); if (!sts.SaveAs(fn, Subtitle::SSA, -1, 0, CTextFile::UTF8, false) || !f.Open(fn, CFile::modeRead)) { return E_FAIL; } int len = (int)f.GetLength() - 3; f.Seek(3, CFile::begin); SUBTITLEINFO* psi = (SUBTITLEINFO*)pmt->AllocFormatBuffer(sizeof(SUBTITLEINFO) + len); memset(psi, 0, pmt->FormatLength()); psi->dwOffset = sizeof(SUBTITLEINFO); strcpy_s(psi->IsoLang, "eng"); f.Read(pmt->pbFormat + psi->dwOffset, len); f.Close(); _wremove(fn); return NOERROR; } // // CSubtitleSourceASS // CSubtitleSourceASS::CSubtitleSourceASS(LPUNKNOWN lpunk, HRESULT* phr) : CSubtitleSource(lpunk, phr, __uuidof(this)) { } HRESULT CSubtitleSourceASS::GetMediaType(CMediaType* pmt) { CAutoLock cAutoLock(pStateLock()); pmt->InitMediaType(); pmt->SetType(&MEDIATYPE_Subtitle); pmt->SetSubtype(&MEDIASUBTYPE_ASS); pmt->SetFormatType(&FORMAT_SubtitleInfo); CSimpleTextSubtitle sts; sts.Open(CString(m_fn), DEFAULT_CHARSET); sts.RemoveAll(); CFile f; WCHAR path[MAX_PATH], fn[MAX_PATH]; if (!GetTempPath(MAX_PATH, path) || !GetTempFileName(path, L"mpc_sts", 0, fn)) { return E_FAIL; } _wremove(fn); wcscat_s(fn, L".ass"); if (!sts.SaveAs(fn, Subtitle::ASS, -1, CTextFile::UTF8) || !f.Open(fn, CFile::modeRead)) { return E_FAIL; } int len = (int)f.GetLength(); SUBTITLEINFO* psi = (SUBTITLEINFO*)pmt->AllocFormatBuffer(sizeof(SUBTITLEINFO) + len); memset(psi, 0, pmt->FormatLength()); psi->dwOffset = sizeof(SUBTITLEINFO); strcpy_s(psi->IsoLang, "eng"); f.Read(pmt->pbFormat + psi->dwOffset, len); f.Close(); _wremove(fn); return NOERROR; } // // CSubtitleSourceUSF // CSubtitleSourceUSF::CSubtitleSourceUSF(LPUNKNOWN lpunk, HRESULT* phr) : CSubtitleSource(lpunk, phr, __uuidof(this)) { } HRESULT CSubtitleSourceUSF::GetMediaType(CMediaType* pmt) { CAutoLock cAutoLock(pStateLock()); pmt->InitMediaType(); pmt->SetType(&MEDIATYPE_Subtitle); pmt->SetSubtype(&MEDIASUBTYPE_USF); pmt->SetFormatType(&FORMAT_SubtitleInfo); SUBTITLEINFO* psi = (SUBTITLEINFO*)pmt->AllocFormatBuffer(sizeof(SUBTITLEINFO)); memset(psi, 0, pmt->FormatLength()); strcpy_s(psi->IsoLang, "eng"); // TODO: ... return NOERROR; } // // CSubtitleSourcePreview // CSubtitleSourcePreview::CSubtitleSourcePreview(LPUNKNOWN lpunk, HRESULT* phr) : CSubtitleSource(lpunk, phr, __uuidof(this)) { } HRESULT CSubtitleSourcePreview::GetMediaType(CMediaType* pmt) { CAutoLock cAutoLock(pStateLock()); pmt->InitMediaType(); pmt->SetType(&MEDIATYPE_Video); pmt->SetSubtype(&MEDIASUBTYPE_RGB32); pmt->SetFormatType(&FORMAT_VideoInfo); VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)pmt->AllocFormatBuffer(sizeof(VIDEOINFOHEADER)); memset(pvih, 0, pmt->FormatLength()); pvih->bmiHeader.biSize = sizeof(pvih->bmiHeader); pvih->bmiHeader.biWidth = _WIDTH; pvih->bmiHeader.biHeight = _HEIGHT; pvih->bmiHeader.biBitCount = 32; pvih->bmiHeader.biCompression = BI_RGB; pvih->bmiHeader.biPlanes = 1; pvih->bmiHeader.biSizeImage = DIBSIZE(pvih->bmiHeader); return NOERROR; } // // CSubtitleSourceARGB // CSubtitleSourceARGB::CSubtitleSourceARGB(LPUNKNOWN lpunk, HRESULT* phr) : CSubtitleSource(lpunk, phr, __uuidof(this)) { } HRESULT CSubtitleSourceARGB::GetMediaType(CMediaType* pmt) { CAutoLock cAutoLock(pStateLock()); pmt->InitMediaType(); pmt->SetType(&MEDIATYPE_Video); pmt->SetSubtype(&MEDIASUBTYPE_ARGB32); pmt->SetFormatType(&FORMAT_VideoInfo); VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)pmt->AllocFormatBuffer(sizeof(VIDEOINFOHEADER)); memset(pvih, 0, pmt->FormatLength()); pvih->bmiHeader.biSize = sizeof(pvih->bmiHeader); // TODO: read w,h,fps from a config file or registry pvih->bmiHeader.biWidth = _WIDTH; pvih->bmiHeader.biHeight = _HEIGHT; pvih->bmiHeader.biBitCount = 32; pvih->bmiHeader.biCompression = BI_RGB; pvih->bmiHeader.biPlanes = 1; pvih->bmiHeader.biSizeImage = pvih->bmiHeader.biWidth*abs(pvih->bmiHeader.biHeight)*pvih->bmiHeader.biBitCount>>3; return NOERROR; }
26.06625
147
0.714669
1aq
3d6b7d93ea70ca5f0d91a162cb8c03dc2179ee6c
1,496
cc
C++
src/Queue/lockFreeQueue.cc
josebrandao13/MDTs
923251280beebb10127c5216c2ef6d7789261e94
[ "MIT" ]
null
null
null
src/Queue/lockFreeQueue.cc
josebrandao13/MDTs
923251280beebb10127c5216c2ef6d7789261e94
[ "MIT" ]
null
null
null
src/Queue/lockFreeQueue.cc
josebrandao13/MDTs
923251280beebb10127c5216c2ef6d7789261e94
[ "MIT" ]
null
null
null
#include <boost/lockfree/queue.hpp> #include <boost/thread/thread.hpp> #include <thread> #include <iostream> #define LOOP 500000 #define BENCH_RUNS 5 using namespace std; boost::lockfree::queue<int> q{LOOP}; vector<int> NTHREADS; int poped; void lockFree(){ for (int i=0; i < LOOP; i++){ q.push(i); if(i%1000==0){ q.pop(poped); } } } void benchmark(void (*function)()){ using namespace std::chrono; for(int k = 0; k < NTHREADS.size(); k++){ std::list<double> times; for(int i = 0; i< BENCH_RUNS; i++){ steady_clock::time_point t1 = steady_clock::now(); boost::thread_group threads; for (int a=0; a < NTHREADS[k]; a++){ threads.create_thread(function); } threads.join_all(); steady_clock::time_point t2 = steady_clock::now(); duration<double> ti = duration_cast<duration<double>>(t2 - t1); times.push_back(ti.count()); } double sumTimes = 0; for(double t: times){ sumTimes += t; } double finalTime = sumTimes/times.size(); cout << fixed; cout << "Time: " << finalTime << endl << endl; cout << "THREADS NO: " << NTHREADS[k] << endl; cout << "Throughput: " << (int)(LOOP/finalTime) << endl; } } int main(int argc, char** argv){ for(int i=1; i<argc; i++){ NTHREADS.push_back(atoi(argv[i])); } cout << "***************** LOCK FREE *********************" << endl; benchmark(lockFree); }
22.666667
71
0.556818
josebrandao13
3d6dd30c1e48578bce39c83660ffea14e92d3371
3,227
cpp
C++
ordered_set.cpp
shiningflash/Advance-Data-Structure
87f1813c5bcfb2ad77b8f1f2d8f0259d3f87371a
[ "MIT" ]
3
2020-11-09T18:36:48.000Z
2020-12-31T03:51:08.000Z
ordered_set.cpp
shiningflash/data-structure
87f1813c5bcfb2ad77b8f1f2d8f0259d3f87371a
[ "MIT" ]
null
null
null
ordered_set.cpp
shiningflash/data-structure
87f1813c5bcfb2ad77b8f1f2d8f0259d3f87371a
[ "MIT" ]
3
2019-04-30T22:11:19.000Z
2020-04-11T18:34:27.000Z
/* +> Ordered set is a policy based data structure in g++ that keeps the unique elements in sorted order. It performs all the operations as performed by the set data structure in STL in log(n) complexity and performs two additional operations also in log(n) complexity. - order_of_key (k) : Number of items strictly smaller than k - find_by_order(k) : K-th element in a set (counting from zero) +> For implementing ordered_set and GNU C++ library contains other Policy based data structures we need to include: include <ext/pb_ds/assoc_container.hpp> include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; +> The ordered set implementation is: tree < int , null_type , less , rb_tree_tag , tree_order_statistics_node_update > Here, - int : It is the type of the data that we want to insert (KEY).It can be integer, float or pair of int etc - null_type : It is the mapped policy. It is null here to use it as a set - less : It is the basis for comparison of two functions - rb_tree_tag : type of tree used. It is generally Red black trees because it takes log(n) time for insertion and deletion - tree_order_statistics_node__update : It contains various operations for updating the node variants of a tree-based container Along with the previous operations of the set, it supports two main important operations ** find_by_order(k): It returns to an iterator to the kth element (counting from zero) in the set in O(logn) time. To find the first element k must be zero. Let us assume we have a set s : {1, 5, 6, 17, 88}, then : *(s.find_by_order(2)) : 3rd element in the set i.e. 6 *(s.find_by_order(4)) : 5th element in the set i.e. 88 ** order_of_key(k) : It returns to the number of items that are strictly smaller than our item k in O(logn) time. Let us assume we have a set s : {1, 5, 6, 17, 88}, then : s.order_of_key(6) : Count of elements strictly smaller than 6 is 2. s.order_of_key(25) : Count of elements strictly smaller than 25 is 4. ** count of elements between l and r can be found by: o_set.order_of_key(r+1) – o_set.order_of_key(l) ref: https://www.geeksforgeeks.org/ordered-set-gnu-c-pbds */ /* two fundamental operations INSERT(S,x): if x is not in S, insert x into S DELETE(S,x): if x is in S, delete x from S and the two type of queries K-TH(S) : return the k-th smallest element of S COUNT(S,x): return the number of elements of S smaller than x */ #include <bits/stdc++.h> using namespace std; #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; #define ordered_set tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> int main() { //freopen("in", "r", stdin); int t, n; char ch; ordered_set s; for (cin >> t; t--; ) { cin >> ch >> n; if (ch == 'I') s.insert(n); else if (ch == 'D') s.erase(n); else if (ch == 'C') cout << s.order_of_key(n) << "\n"; else if (ch == 'K') { if (n > s.size()) cout << "invalid\n"; else cout << *s.find_by_order(n-1) << "\n"; } } return 0; } /* Input: 8 I -1 I -1 I 2 C 0 K 2 D -1 K 1 K 2 Output: 1 2 2 invalid ref: https://www.spoj.com/problems/ORDERSET */
30.158879
156
0.693214
shiningflash
3d6f0857c27d0df23cf4ec4b97b2490c8e3547fe
1,590
hpp
C++
src/config.hpp
IronySuzumiya/NiuDianNao
b6c157807129653e8d9e46238dff80a230ff4928
[ "MIT" ]
6
2019-03-05T07:49:09.000Z
2022-01-20T21:45:53.000Z
src/config.hpp
IronySuzumiya/NiuDianNao
b6c157807129653e8d9e46238dff80a230ff4928
[ "MIT" ]
null
null
null
src/config.hpp
IronySuzumiya/NiuDianNao
b6c157807129653e8d9e46238dff80a230ff4928
[ "MIT" ]
2
2019-03-05T02:23:28.000Z
2022-01-20T22:14:54.000Z
#ifndef __DNN_CONFIG__ #define __DNN_CONFIG__ #include "option_parser.hpp" class DnnConfig { public: DnnConfig() {}; ~DnnConfig() {}; void reg_options(option_parser_t opp); // Bit-width unsigned bit_width; // Pipeline stage buffer size unsigned max_buffer_size; // SB unsigned sb_line_length; unsigned sb_num_lines; unsigned sb_access_cycles; unsigned sb_num_ports; // NBin unsigned nbin_line_length; unsigned nbin_num_lines; unsigned nbin_access_cycles; unsigned nbin_num_ports; // NBout unsigned nbout_line_length; unsigned nbout_num_lines; unsigned nbout_access_cycles; unsigned nbout_num_ports; // NFU-1 unsigned num_nfu1_pipeline_stages; unsigned num_nfu1_multipliers; // NFU-2 unsigned num_nfu2_pipeline_stages; unsigned num_nfu2_adders; unsigned num_nfu2_shifters; unsigned num_nfu2_max; // NFU-3 unsigned num_nfu3_pipeline_stages; unsigned num_nfu3_multipliers; unsigned num_nfu3_adders; // N_o need to change for each layer // this probably shouldn't be a parameter but I don't know how you can infer it from the instructions unsigned num_outputs; // Simple power model (factor in pJ) // SRAM Arrays float sb_acc_eng; float nbin_acc_eng; float nbout_acc_eng; // Functional units float int_mult_16_eng; float fp_mult_16_eng; float int_add_16_eng; float fp_add_16_eng; }; #endif
22.714286
106
0.664151
IronySuzumiya
3d6f50e094123507a09b9784d36d9a35c3bf0f29
2,157
cpp
C++
modules/OCULUS/external/oculusSDK/LibOVRKernel/Src/Kernel/OVR_Rand.cpp
Mithsen/Gallbladder
981cec68ca9e9af8613a6bf5a71048f86c16a070
[ "BSD-3-Clause" ]
3
2016-01-18T06:15:18.000Z
2016-05-23T22:21:16.000Z
modules/OCULUS/external/oculusSDK/LibOVRKernel/Src/Kernel/OVR_Rand.cpp
Mithsen/Gallbladder
981cec68ca9e9af8613a6bf5a71048f86c16a070
[ "BSD-3-Clause" ]
null
null
null
modules/OCULUS/external/oculusSDK/LibOVRKernel/Src/Kernel/OVR_Rand.cpp
Mithsen/Gallbladder
981cec68ca9e9af8613a6bf5a71048f86c16a070
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************** Filename : OVR_Rand.cpp Content : Random number generator Created : Aug 28, 2014 Author : Chris Taylor Copyright : Copyright 2014 Oculus VR, Inc. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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 "OVR_Rand.h" #include "OVR_Timer.h" namespace OVR { void RandomNumberGenerator::SeedRandom() { uint64_t seed = Timer::GetTicksNanos(); uint32_t x = (uint32_t)seed, y = (uint32_t)(seed >> 32); Seed(x, y); } void RandomNumberGenerator::Seed(uint32_t x, uint32_t y) { // Based on the mixing functions of MurmurHash3 static const uint64_t C1 = 0xff51afd7ed558ccdULL; static const uint64_t C2 = 0xc4ceb9fe1a85ec53ULL; x += y; y += x; uint64_t seed_x = 0x9368e53c2f6af274ULL ^ x; uint64_t seed_y = 0x586dcd208f7cd3fdULL ^ y; seed_x *= C1; seed_x ^= seed_x >> 33; seed_x *= C2; seed_x ^= seed_x >> 33; seed_y *= C1; seed_y ^= seed_y >> 33; seed_y *= C2; seed_y ^= seed_y >> 33; Rx = seed_x; Ry = seed_y; // Inlined Next(): Discard first output Rx = (uint64_t)0xfffd21a7 * (uint32_t)Rx + (uint32_t)(Rx >> 32); Ry = (uint64_t)0xfffd1361 * (uint32_t)Ry + (uint32_t)(Ry >> 32); // Throw away any saved RandN() state HaveRandN = false; Seeded = true; } } // namespace OVR
26.9625
85
0.634678
Mithsen
3d72496566cba8a43ec58fa6b46a0c16ae1a5f8f
3,791
cpp
C++
src/osvr/Common/CommonComponent.cpp
stephengroat/OSVR-Core
35e0967b18c8d6cb4caa152ebcbcb6cc473c9bf1
[ "Apache-2.0" ]
369
2015-03-08T03:12:41.000Z
2022-02-08T22:15:39.000Z
src/osvr/Common/CommonComponent.cpp
DavidoRotho/OSVR-Core
b2fbb44e7979d9ebdf4bd8f00267cc267edbb465
[ "Apache-2.0" ]
486
2015-03-09T13:29:00.000Z
2020-10-16T00:41:26.000Z
src/osvr/Common/CommonComponent.cpp
DavidoRotho/OSVR-Core
b2fbb44e7979d9ebdf4bd8f00267cc267edbb465
[ "Apache-2.0" ]
166
2015-03-08T12:03:56.000Z
2021-12-03T13:56:21.000Z
/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, 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. // Internal Includes #include <osvr/Common/CommonComponent.h> // Library/third-party includes // - none // Standard includes // - none namespace osvr { namespace common { namespace messages { // These messages all must match the ones in VRPN exactly. /// @todo add test to verify that this matches VRPN: message type string /// not accessible as a constant, so we have to extract the message ID /// instead. const char *VRPNPing::identifier() { return "vrpn_Base ping_message"; } /// @todo add test to verify that this matches VRPN: message type string /// not accessible as a constant, so we have to extract the message ID /// instead. const char *VRPNPong::identifier() { return "vrpn_Base pong_message"; } const char *VRPNGotFirstConnection::identifier() { return "VRPN_Connection_Got_First_Connection"; } const char *VRPNGotConnection::identifier() { return "VRPN_Connection_Got_Connection"; } const char *VRPNDroppedConnection::identifier() { return "VRPN_Connection_Dropped_Connection"; } const char *VRPNDroppedLastConnection::identifier() { return "VRPN_Connection_Dropped_Last_Connection"; } } // namespace messages shared_ptr<CommonComponent> CommonComponent::create() { shared_ptr<CommonComponent> ret(new CommonComponent); return ret; } CommonComponent::~CommonComponent() = default; void CommonComponent::registerPingHandler(Handler const &handler) { /// Just forward to the templated implementation. registerHandler(ping, handler); } void CommonComponent::registerPongHandler(Handler const &handler) { /// Just forward to the templated implementation. registerHandler(pong, handler); } void CommonComponent::m_registerHandlerImpl( HandlerList &handlers, osvr::common::RawMessageType rawMessageType, Handler const &handler) { if (handlers.empty()) { m_registerHandler(&CommonComponent::m_baseHandler, &handlers, rawMessageType); } handlers.push_back(handler); } CommonComponent::CommonComponent() {} void CommonComponent::m_parentSet() { m_getParent().registerMessageType(ping); m_getParent().registerMessageType(pong); m_getParent().registerMessageType(gotFirstConnection); m_getParent().registerMessageType(gotConnection); m_getParent().registerMessageType(droppedConnection); m_getParent().registerMessageType(droppedLastConnection); } int CommonComponent::m_baseHandler(void *userdata, vrpn_HANDLERPARAM) { /// Our userdata here is a pointer to a vector of handlers - it doesn't /// matter to us what kind. auto &handlers = *static_cast<std::vector<Handler> *>(userdata); for (auto const &cb : handlers) { cb(); } return 0; } } // namespace common } // namespace osvr
33.548673
80
0.666843
stephengroat
3d73f71afaf2e57b2d8224491cd80507a053becb
22,080
cpp
C++
src/fred2/campaigneditordlg.cpp
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
1
2020-07-14T07:29:18.000Z
2020-07-14T07:29:18.000Z
src/fred2/campaigneditordlg.cpp
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
2
2019-01-01T22:35:56.000Z
2022-03-14T07:34:00.000Z
src/fred2/campaigneditordlg.cpp
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
2
2021-03-07T11:40:42.000Z
2021-12-26T21:40:39.000Z
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on * the source. */ // CampaignEditorDlg.cpp : implementation file // #include <setjmp.h> #include "stdafx.h" #include "fred.h" #include "campaigneditordlg.h" #include "campaigntreeview.h" #include "campaigntreewnd.h" #include "management.h" #include "freddoc.h" #include "parselo.h" #include "missiongoals.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif int Cur_campaign_mission = -1; int Cur_campaign_link = -1; // determine the node number that would be allocated without actually allocating it yet. int campaign_sexp_tree::get_new_node_position() { int i; for (i=0; i<MAX_SEXP_TREE_SIZE; i++){ if (nodes[i].type == SEXPT_UNUSED){ return i; } } return -1; } // construct tree nodes for an sexp, adding them to the list and returning first node int campaign_sexp_tree::load_sub_tree(int index) { int cur; if (index < 0) { cur = allocate_node(-1); set_node(cur, (SEXPT_OPERATOR | SEXPT_VALID), "do-nothing"); // setup a default tree if none return cur; } // assumption: first token is an operator. I require this because it would cause problems // with child/parent relations otherwise, and it should be this way anyway, since the // return type of the whole sexp is boolean, and only operators can satisfy this. Assert(Sexp_nodes[index].subtype == SEXP_ATOM_OPERATOR); cur = get_new_node_position(); load_branch(index, -1); return cur; } ///////////////////////////////////////////////////////////////////////////// // campaign_editor IMPLEMENT_DYNCREATE(campaign_editor, CFormView) campaign_editor *Campaign_tree_formp; campaign_editor::campaign_editor() : CFormView(campaign_editor::IDD) { //{{AFX_DATA_INIT(campaign_editor) m_name = _T(""); m_type = -1; m_num_players = _T(""); m_desc = _T(""); m_loop_desc = _T(""); m_loop_brief_anim = _T(""); m_loop_brief_sound = _T(""); //}}AFX_DATA_INIT m_tree.m_mode = MODE_CAMPAIGN; m_num_links = 0; m_tree.link_modified(&Campaign_modified); m_last_mission = -1; } campaign_editor::~campaign_editor() { } void campaign_editor::DoDataExchange(CDataExchange* pDX) { CFormView::DoDataExchange(pDX); //{{AFX_DATA_MAP(campaign_editor) DDX_Control(pDX, IDC_SEXP_TREE, m_tree); DDX_Control(pDX, IDC_FILELIST, m_filelist); DDX_Text(pDX, IDC_NAME, m_name); DDX_CBIndex(pDX, IDC_CAMPAIGN_TYPE, m_type); DDX_Text(pDX, IDC_NUM_PLAYERS, m_num_players); DDX_Text(pDX, IDC_DESC2, m_desc); DDX_Text(pDX, IDC_MISSISON_LOOP_DESC, m_loop_desc); DDX_Text(pDX, IDC_LOOP_BRIEF_ANIM, m_loop_brief_anim); DDX_Text(pDX, IDC_LOOP_BRIEF_SOUND, m_loop_brief_sound); //}}AFX_DATA_MAP DDV_MaxChars(pDX, m_desc, MISSION_DESC_LENGTH - 1); DDV_MaxChars(pDX, m_loop_desc, MISSION_DESC_LENGTH - 1); } BEGIN_MESSAGE_MAP(campaign_editor, CFormView) //{{AFX_MSG_MAP(campaign_editor) ON_BN_CLICKED(ID_LOAD, OnLoad) ON_BN_CLICKED(IDC_ALIGN, OnAlign) ON_BN_CLICKED(ID_CPGN_CLOSE, OnCpgnClose) ON_NOTIFY(NM_RCLICK, IDC_SEXP_TREE, OnRclickTree) ON_NOTIFY(TVN_BEGINLABELEDIT, IDC_SEXP_TREE, OnBeginlabeleditSexpTree) ON_NOTIFY(TVN_ENDLABELEDIT, IDC_SEXP_TREE, OnEndlabeleditSexpTree) ON_NOTIFY(TVN_SELCHANGED, IDC_SEXP_TREE, OnSelchangedSexpTree) ON_BN_CLICKED(IDC_MOVE_UP, OnMoveUp) ON_BN_CLICKED(IDC_MOVE_DOWN, OnMoveDown) ON_COMMAND(ID_END_EDIT, OnEndEdit) ON_EN_CHANGE(IDC_BRIEFING_CUTSCENE, OnChangeBriefingCutscene) ON_CBN_SELCHANGE(IDC_CAMPAIGN_TYPE, OnSelchangeType) ON_BN_CLICKED(IDC_GALATEA, OnGalatea) ON_BN_CLICKED(IDC_BASTION, OnBastion) ON_BN_CLICKED(IDC_TOGGLE_LOOP, OnToggleLoop) ON_BN_CLICKED(IDC_LOOP_BRIEF_BROWSE, OnBrowseLoopAni) ON_BN_CLICKED(IDC_LOOP_BRIEF_SOUND_BROWSE, OnBrowseLoopSound) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // campaign_editor diagnostics #ifdef _DEBUG void campaign_editor::AssertValid() const { CFormView::AssertValid(); } void campaign_editor::Dump(CDumpContext& dc) const { CFormView::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // campaign_editor message handlers void campaign_editor::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { UpdateData(FALSE); } void campaign_editor::OnLoad() { char buf[512]; if (Cur_campaign_mission < 0){ return; } if (Campaign_modified){ if (Campaign_wnd->save_modified()){ return; } } GetCurrentDirectory(512, buf); strcat(buf, "\\"); strcat(buf, Campaign.missions[Cur_campaign_mission].name); FREDDoc_ptr->SetPathName(buf); Campaign_wnd->DestroyWindow(); // if (FREDDoc_ptr->OnOpenDocument(Campaign.missions[Cur_campaign_mission].name)) { // Bypass_clear_mission = 1; // Campaign_wnd->DestroyWindow(); // // } else { // MessageBox("Failed to load mission!", "Error"); // } } BOOL campaign_editor::Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext) { int i; BOOL r; CComboBox *box; r = CFormView::Create(lpszClassName, lpszWindowName, dwStyle, rect, pParentWnd, nID, pContext); if (r) { box = (CComboBox *) GetDlgItem(IDC_CAMPAIGN_TYPE); box->ResetContent(); for (i=0; i<MAX_CAMPAIGN_TYPES; i++){ box->AddString(campaign_types[i]); } } return r; } void campaign_editor::load_campaign() { Cur_campaign_mission = Cur_campaign_link = -1; load_tree(0); if (!strlen(Campaign.filename)) strcpy(Campaign.filename, BUILTIN_CAMPAIGN); if (mission_campaign_load(Campaign.filename, 0)) { MessageBox("Couldn't open Campaign file!", "Error"); Campaign_wnd->OnCpgnFileNew(); return; } Campaign_modified = 0; Campaign_tree_viewp->construct_tree(); initialize(); } void campaign_editor::OnAlign() { Campaign_tree_viewp->sort_elements(); Campaign_tree_viewp->realign_tree(); Campaign_tree_viewp->Invalidate(); } void campaign_editor::initialize( int init_files ) { Cur_campaign_mission = Cur_campaign_link = -1; m_tree.setup((CEdit *) GetDlgItem(IDC_HELP_BOX)); load_tree(0); Campaign_tree_viewp->initialize(); // only initialize the file dialog box when the parameter says to. This should // only happen when a campaign type changes if ( init_files ){ m_filelist.initialize(); } m_name = Campaign.name; m_type = Campaign.type; m_num_players.Format("%d", Campaign.num_players); if (Campaign.desc) { m_desc = convert_multiline_string(Campaign.desc); } else { m_desc = _T(""); } m_loop_desc = _T(""); m_loop_brief_anim = _T(""); m_loop_brief_sound = _T(""); // single player should hide the two dialog items about number of players allowed if ( m_type == CAMPAIGN_TYPE_SINGLE ) { GetDlgItem(IDC_NUM_PLAYERS)->ShowWindow( SW_HIDE ); GetDlgItem(IDC_PLAYERS_LABEL)->ShowWindow( SW_HIDE ); } else { GetDlgItem(IDC_NUM_PLAYERS)->ShowWindow( SW_SHOW ); GetDlgItem(IDC_PLAYERS_LABEL)->ShowWindow( SW_SHOW ); } UpdateData(FALSE); } void campaign_editor::mission_selected(int num) { CEdit *bc_dialog; bc_dialog = (CEdit *) GetDlgItem(IDC_BRIEFING_CUTSCENE); // clear out the text for the briefing cutscene, and put in new text if specified bc_dialog->SetWindowText(""); if ( strlen(Campaign.missions[num].briefing_cutscene) ) bc_dialog->SetWindowText(Campaign.missions[num].briefing_cutscene); if (Campaign.missions[num].flags & CMISSION_FLAG_BASTION) { ((CButton *) GetDlgItem(IDC_GALATEA)) -> SetCheck(0); ((CButton *) GetDlgItem(IDC_BASTION)) -> SetCheck(1); } else { ((CButton *) GetDlgItem(IDC_GALATEA)) -> SetCheck(1); ((CButton *) GetDlgItem(IDC_BASTION)) -> SetCheck(0); } } void campaign_editor::update() { char buf[MISSION_DESC_LENGTH]; // get data from dlog box UpdateData(TRUE); // update campaign name string_copy(Campaign.name, m_name, NAME_LENGTH); Campaign.type = m_type; // update campaign desc deconvert_multiline_string(buf, m_desc, MISSION_DESC_LENGTH); if (Campaign.desc) { free(Campaign.desc); } Campaign.desc = NULL; if (strlen(buf)) { Campaign.desc = strdup(buf); } // maybe update mission loop text save_loop_desc_window(); // set the number of players in a multiplayer mission equal to the number of players in the first mission if ( Campaign.type != CAMPAIGN_TYPE_SINGLE ) { if ( Campaign.num_missions == 0 ) { Campaign.num_players = 0; } else { mission a_mission; get_mission_info(Campaign.missions[0].name, &a_mission); Campaign.num_players = a_mission.num_players; } } } void campaign_editor::OnCpgnClose() { Campaign_wnd->OnClose(); } void campaign_editor::load_tree(int save_first) { char text[80]; int i; HTREEITEM h; if (save_first) save_tree(); m_tree.clear_tree(); m_tree.DeleteAllItems(); m_num_links = 0; UpdateData(TRUE); update_loop_desc_window(); m_last_mission = Cur_campaign_mission; if (Cur_campaign_mission < 0) { GetDlgItem(IDC_SEXP_TREE)->EnableWindow(FALSE); GetDlgItem(IDC_BRIEFING_CUTSCENE)->EnableWindow(FALSE); return; } GetDlgItem(IDC_SEXP_TREE)->EnableWindow(TRUE); GetDlgItem(IDC_BRIEFING_CUTSCENE)->EnableWindow(TRUE); GetDlgItem(IDC_MISSISON_LOOP_DESC)->EnableWindow(FALSE); GetDlgItem(IDC_LOOP_BRIEF_ANIM)->EnableWindow(FALSE); GetDlgItem(IDC_LOOP_BRIEF_SOUND)->EnableWindow(FALSE); GetDlgItem(IDC_LOOP_BRIEF_BROWSE)->EnableWindow(FALSE); GetDlgItem(IDC_LOOP_BRIEF_SOUND_BROWSE)->EnableWindow(FALSE); for (i=0; i<Total_links; i++) { if (Links[i].from == Cur_campaign_mission) { Links[i].node = m_tree.load_sub_tree(Links[i].sexp); m_num_links++; if (Links[i].from == Links[i].to) { strcpy(text, "Repeat mission"); } else if ( (Links[i].to == -1) && (Links[i].from != -1) ) { strcpy(text, "End of Campaign"); } else { sprintf(text, "Branch to %s", Campaign.missions[Links[i].to].name); } // insert item into tree int image, sel_image; if (Links[i].mission_loop) { image = BITMAP_BLUE_DOT; sel_image = BITMAP_GREEN_DOT; } else { image = BITMAP_BLACK_DOT; sel_image = BITMAP_RED_DOT; } h = m_tree.insert(text, image, sel_image); m_tree.SetItemData(h, Links[i].node); m_tree.add_sub_tree(Links[i].node, h); } } } void campaign_editor::OnRclickTree(NMHDR* pNMHDR, LRESULT* pResult) { m_tree.right_clicked(MODE_CAMPAIGN); *pResult = 0; } void campaign_editor::OnBeginlabeleditSexpTree(NMHDR* pNMHDR, LRESULT* pResult) { TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR; if (m_tree.edit_label(pTVDispInfo->item.hItem) == 1) { *pResult = 0; Campaign_modified = 1; } else { *pResult = 1; } } void campaign_editor::OnEndlabeleditSexpTree(NMHDR* pNMHDR, LRESULT* pResult) { TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR; *pResult = m_tree.end_label_edit(pTVDispInfo->item.hItem, pTVDispInfo->item.pszText); } int campaign_editor::handler(int code, int node, char *str) { int i; switch (code) { case ROOT_DELETED: for (i=0; i<Total_links; i++){ if ((Links[i].from == Cur_campaign_mission) && (Links[i].node == node)){ break; } } Campaign_tree_viewp->delete_link(i); m_num_links--; return node; default: Int3(); } return -1; } void campaign_editor::save_tree(int clear) { int i; if (m_last_mission < 0){ return; // nothing to save } for (i=0; i<Total_links; i++){ if (Links[i].from == m_last_mission) { sexp_unmark_persistent(Links[i].sexp); free_sexp2(Links[i].sexp); Links[i].sexp = m_tree.save_tree(Links[i].node); sexp_mark_persistent(Links[i].sexp); } } if (clear){ m_last_mission = -1; } } void campaign_editor::OnSelchangedSexpTree(NMHDR* pNMHDR, LRESULT* pResult) { int i, node; HTREEITEM h, h2; // get handle of selected item NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR; h = pNMTreeView->itemNew.hItem; Assert(h); // update help on sexp m_tree.update_help(h); // get handle of parent while ((h2 = m_tree.GetParentItem(h))>0){ h = h2; } // get identifier of parent node = m_tree.GetItemData(h); for (i=0; i<Total_links; i++){ if ((Links[i].from == Cur_campaign_mission) && (Links[i].node == node)){ break; } } if (i == Total_links) { Cur_campaign_link = -1; return; } // update mission loop text UpdateData(TRUE); save_loop_desc_window(); Cur_campaign_link = i; update_loop_desc_window(); Campaign_tree_viewp->Invalidate(); *pResult = 0; } void campaign_editor::OnMoveUp() { int i, last = -1; campaign_tree_link temp; HTREEITEM h1, h2; if (Cur_campaign_link >= 0) { save_tree(); for (i=0; i<Total_links; i++){ if (Links[i].from == Cur_campaign_mission) { if (i == Cur_campaign_link){ break; } last = i; } } if ((last != -1) && (i < Total_links)) { h1 = m_tree.GetParentItem(m_tree.handle(Links[i].node)); h2 = m_tree.GetParentItem(m_tree.handle(Links[last].node)); m_tree.swap_roots(h1, h2); m_tree.SelectItem(m_tree.GetParentItem(m_tree.handle(Links[i].node))); temp = Links[last]; Links[last] = Links[i]; Links[i] = temp; Cur_campaign_link = last; } } GetDlgItem(IDC_SEXP_TREE)->SetFocus(); } void campaign_editor::OnMoveDown() { int i, j; campaign_tree_link temp; HTREEITEM h1, h2; if (Cur_campaign_link >= 0) { save_tree(); for (i=0; i<Total_links; i++) if (Links[i].from == Cur_campaign_mission) if (i == Cur_campaign_link) break; for (j=i+1; j<Total_links; j++) if (Links[j].from == Cur_campaign_mission) break; if (j < Total_links) { h1 = m_tree.GetParentItem(m_tree.handle(Links[i].node)); h2 = m_tree.GetParentItem(m_tree.handle(Links[j].node)); m_tree.swap_roots(h1, h2); m_tree.SelectItem(m_tree.GetParentItem(m_tree.handle(Links[i].node))); temp = Links[j]; Links[j] = Links[i]; Links[i] = temp; Cur_campaign_link = j; } } GetDlgItem(IDC_SEXP_TREE)->SetFocus(); } void campaign_editor::swap_handler(int node1, int node2) { int index1, index2; campaign_tree_link temp; for (index1=0; index1<Total_links; index1++){ if ((Links[index1].from == Cur_campaign_mission) && (Links[index1].node == node1)){ break; } } Assert(index1 < Total_links); for (index2=0; index2<Total_links; index2++){ if ((Links[index2].from == Cur_campaign_mission) && (Links[index2].node == node2)){ break; } } Assert(index2 < Total_links); temp = Links[index1]; // Links[index1] = Links[index2]; while (index1 < index2) { Links[index1] = Links[index1 + 1]; index1++; } while (index1 > index2 + 1) { Links[index1] = Links[index1 - 1]; index1--; } // update Cur_campaign_link Cur_campaign_link = index1; Links[index1] = temp; } void campaign_editor::insert_handler(int old, int node) { int i; for (i=0; i<Total_links; i++){ if ((Links[i].from == Cur_campaign_mission) && (Links[i].node == old)){ break; } } Assert(i < Total_links); Links[i].node = node; return; } void campaign_editor::OnEndEdit() { HWND h; CWnd *w; w = GetFocus(); if (w) { h = w->m_hWnd; GetDlgItem(IDC_SEXP_TREE)->SetFocus(); ::SetFocus(h); } } void campaign_editor::OnChangeBriefingCutscene() { CEdit *bc_dialog; bc_dialog = (CEdit *) GetDlgItem(IDC_BRIEFING_CUTSCENE); // maybe save off the current cutscene names. if ( Cur_campaign_mission != -1 ) { // see if the contents of the edit box have changed. Luckily, this returns 0 when the edit box is // cleared. if ( bc_dialog->GetModify() ) { bc_dialog->GetWindowText( Campaign.missions[Cur_campaign_mission].briefing_cutscene, NAME_LENGTH ); Campaign_modified = 1; } } } // what to do when changing campaign type void campaign_editor::OnSelchangeType() { // if campaign type is single player, then disable the multiplayer items update(); initialize(); Campaign_modified = 1; } void campaign_editor::OnGalatea() { if (Cur_campaign_mission >= 0){ Campaign.missions[Cur_campaign_mission].flags &= ~CMISSION_FLAG_BASTION; } } void campaign_editor::OnBastion() { if (Cur_campaign_mission >= 0){ Campaign.missions[Cur_campaign_mission].flags |= CMISSION_FLAG_BASTION; } } // update the loop mission text void campaign_editor::save_loop_desc_window() { char buffer[MISSION_DESC_LENGTH]; // update only if active link and there is a mission has mission loop if ( (Cur_campaign_link >= 0) && Links[Cur_campaign_link].mission_loop ) { deconvert_multiline_string(buffer, m_loop_desc, MISSION_DESC_LENGTH); if (Links[Cur_campaign_link].mission_loop_txt) { free(Links[Cur_campaign_link].mission_loop_txt); } if (Links[Cur_campaign_link].mission_loop_brief_anim) { free(Links[Cur_campaign_link].mission_loop_brief_anim); } if (Links[Cur_campaign_link].mission_loop_brief_sound) { free(Links[Cur_campaign_link].mission_loop_brief_sound); } if (strlen(buffer)) { Links[Cur_campaign_link].mission_loop_txt = strdup(buffer); } else { Links[Cur_campaign_link].mission_loop_txt = NULL; } deconvert_multiline_string(buffer, m_loop_brief_anim, MAX_FILENAME_LEN); if(strlen(buffer)){ Links[Cur_campaign_link].mission_loop_brief_anim = strdup(buffer); } else { Links[Cur_campaign_link].mission_loop_brief_anim = NULL; } deconvert_multiline_string(buffer, m_loop_brief_sound, MAX_FILENAME_LEN); if(strlen(buffer)){ Links[Cur_campaign_link].mission_loop_brief_sound = strdup(buffer); } else { Links[Cur_campaign_link].mission_loop_brief_sound = NULL; } } } void campaign_editor::update_loop_desc_window() { bool enable_loop_desc_window; enable_loop_desc_window = false; if ((Cur_campaign_link >= 0) && Links[Cur_campaign_link].mission_loop) { enable_loop_desc_window = true; } // maybe enable description window GetDlgItem(IDC_MISSISON_LOOP_DESC)->EnableWindow(enable_loop_desc_window); GetDlgItem(IDC_LOOP_BRIEF_ANIM)->EnableWindow(enable_loop_desc_window); GetDlgItem(IDC_LOOP_BRIEF_SOUND)->EnableWindow(enable_loop_desc_window); GetDlgItem(IDC_LOOP_BRIEF_BROWSE)->EnableWindow(enable_loop_desc_window); GetDlgItem(IDC_LOOP_BRIEF_SOUND_BROWSE)->EnableWindow(enable_loop_desc_window); // set new text if ((Cur_campaign_link >= 0) && Links[Cur_campaign_link].mission_loop_txt && enable_loop_desc_window) { m_loop_desc = convert_multiline_string(Links[Cur_campaign_link].mission_loop_txt); } else { m_loop_desc = _T(""); } // set new text if ((Cur_campaign_link >= 0) && Links[Cur_campaign_link].mission_loop_brief_anim && enable_loop_desc_window) { m_loop_brief_anim = convert_multiline_string(Links[Cur_campaign_link].mission_loop_brief_anim); } else { m_loop_brief_anim = _T(""); } // set new text if ((Cur_campaign_link >= 0) && Links[Cur_campaign_link].mission_loop_brief_sound && enable_loop_desc_window) { m_loop_brief_sound = convert_multiline_string(Links[Cur_campaign_link].mission_loop_brief_sound); } else { m_loop_brief_sound = _T(""); } // reset text UpdateData(FALSE); } void campaign_editor::OnToggleLoop() { // check if branch selected if (Cur_campaign_link == -1) { return; } // store mission looop text UpdateData(TRUE); if ( (Cur_campaign_link >= 0) && Links[Cur_campaign_link].mission_loop ) { if (Links[Cur_campaign_link].mission_loop_txt) { free(Links[Cur_campaign_link].mission_loop_txt); } if (Links[Cur_campaign_link].mission_loop_brief_anim) { free(Links[Cur_campaign_link].mission_loop_brief_anim); } if (Links[Cur_campaign_link].mission_loop_brief_sound) { free(Links[Cur_campaign_link].mission_loop_brief_sound); } char buffer[MISSION_DESC_LENGTH]; deconvert_multiline_string(buffer, m_loop_desc, MISSION_DESC_LENGTH); if (m_loop_desc && strlen(buffer)) { Links[Cur_campaign_link].mission_loop_txt = strdup(buffer); } else { Links[Cur_campaign_link].mission_loop_txt = NULL; } deconvert_multiline_string(buffer, m_loop_brief_anim, MISSION_DESC_LENGTH); if (m_loop_brief_anim && strlen(buffer)) { Links[Cur_campaign_link].mission_loop_brief_anim = strdup(buffer); } else { Links[Cur_campaign_link].mission_loop_brief_anim = NULL; } deconvert_multiline_string(buffer, m_loop_brief_sound, MISSION_DESC_LENGTH); if (m_loop_brief_sound && strlen(buffer)) { Links[Cur_campaign_link].mission_loop_brief_sound = strdup(buffer); } else { Links[Cur_campaign_link].mission_loop_brief_sound = NULL; } } // toggle to mission_loop setting Links[Cur_campaign_link].mission_loop = !Links[Cur_campaign_link].mission_loop; // reset loop desc window (gray if inactive) update_loop_desc_window(); // set root icon int bitmap1, bitmap2; if (Links[Cur_campaign_link].mission_loop) { bitmap2 = BITMAP_GREEN_DOT; bitmap1 = BITMAP_BLUE_DOT; } else { bitmap1 = BITMAP_BLACK_DOT; bitmap2 = BITMAP_RED_DOT; } // Search for item and update bitmap HTREEITEM h = m_tree.GetRootItem(); while (h) { if ((int) m_tree.GetItemData(h) == Links[Cur_campaign_link].node) { m_tree.SetItemImage(h, bitmap1, bitmap2); break; } h = m_tree.GetNextSiblingItem(h); } // set to redraw Campaign_tree_viewp->Invalidate(); } void campaign_editor::OnBrowseLoopAni() { int pushed_dir; UpdateData(TRUE); // switch directories pushed_dir = cfile_push_chdir(CF_TYPE_INTERFACE); CFileDialog dlg(TRUE, "ani", NULL, OFN_HIDEREADONLY | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR, "Ani Files (*.ani)|*.ani"); if (dlg.DoModal() == IDOK) { m_loop_brief_anim = dlg.GetFileName(); UpdateData(FALSE); } // move back to the proper directory if (!pushed_dir){ cfile_pop_dir(); } } void campaign_editor::OnBrowseLoopSound() { int pushed_dir; UpdateData(TRUE); // switch directories pushed_dir = cfile_push_chdir(CF_TYPE_VOICE_CMD_BRIEF); CFileDialog dlg(TRUE, "wav", NULL, OFN_HIDEREADONLY | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR, "Wave Files (*.wav)|*.wav||"); if (dlg.DoModal() == IDOK) { m_loop_brief_sound = dlg.GetFileName(); UpdateData(FALSE); } // move back to the proper directory if (!pushed_dir){ cfile_pop_dir(); } }
24.949153
163
0.71721
ptitSeb
3d75c6be53f8faf936c05a7ea8f4ebbaa3cf55d7
10,769
hpp
C++
rapi_core/include/core/port.hpp
csitarichie/someip_cyclone_dds_bridge
2ccaaa6e2484a938b08562497431df61ab23769f
[ "MIT" ]
null
null
null
rapi_core/include/core/port.hpp
csitarichie/someip_cyclone_dds_bridge
2ccaaa6e2484a938b08562497431df61ab23769f
[ "MIT" ]
null
null
null
rapi_core/include/core/port.hpp
csitarichie/someip_cyclone_dds_bridge
2ccaaa6e2484a938b08562497431df61ab23769f
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> #include <cassert> #include <condition_variable> #include <deque> #include <functional> #include <limits> #include <map> #include <memory> #include <mutex> #include <iostream> #include "adstlog_cxx/adstlog.hpp" #include "adstutil_cxx/compiler_diagnostics.hpp" #include "core/impl/async_call_back_vector.hpp" #include "core/impl/common.hpp" #include "core/network.hpp" namespace adst::ep::test_engine::core { class Actor; /** * Used by an actor to represent an incoming entity. * * Listen on the port registers the actor in the network with the given event. * * Handles event callback dispatching when an event is received by an actor from a network. */ class Port { public: /** * ctor. * * A port is always owned by an actor. * * Port schedules itself on an actor when there is a command or event to dispatch. * * The actor schedule function makes sure that the actor only exists once in the dispatching * queue of the priority. * * @param actor Actor which ownes this port. * @param network The network this port is connected to. */ explicit Port(Actor& actor, Network& network); ~Port() { std::lock_guard<std::mutex> guard{callbacksMutex_}; callbacks_.clear(); } Port() = delete; Port(const Port&) = delete; Port(Port&&) = delete; Port& operator=(Port&&) = delete; Port& operator=(const Port&) = delete; /** * Creates unique handle for each listen registration. * * @return A unique handle. */ CallBackHandle newHandle() { std::lock_guard<std::mutex> guard{eventMutex_}; auto handle = ++handleCounter_; return handle; } /** * Used by the actor to register a callback to a given port (network). * * @tparam Event The event type used for callback (and for registration). * @param callback The callback to be called when a publish happens on a network. * @return Unique ID to identify the callback during unlisten. */ template <typename Event> CallBackHandle listen(std::function<void(const Event&)> callback) { static_assert(impl::validateEvent<Event>(), "Invalid event"); auto handle = newHandle(); listen<Event>(handle, std::move(callback)); return handle; } /** * Listen can be changed to a different function by providing the unique id and a new callback. * * @tparam Event the event type used for dispatch. * @param handle Unique handle of the initial listen. * @param callback The callback to register under for handle. */ template <typename Event> void listen(const CallBackHandle handle, std::function<void(const Event&)> callback); /** * Removes all callback from all event type with a given handle. * * @param handle Unique handle of the initial listen. */ void unlistenAll(const CallBackHandle handle) { std::lock_guard<std::mutex> unListenCmdQueueGuard{eventMutex_}; commandsQueue_.emplace_back([this, handle]() { std::lock_guard<std::mutex> lambdaCallbacksGuard{callbacksMutex_}; for (auto& element : callbacks_) { element.second->remove(handle); } }); } /** * Removes callback from the listen container. * * @tparam Event Type of the event used in the callback. * @param handle Unique id (from the listen call). */ template <typename Event> void unlisten(CallBackHandle handle); /** * Called by the the Actor when it has a message to be dispatched. * * @tparam Event The type of the message. * @param event A unique_ptr to Event/Message. */ template <typename Event> void schedule(Event event); // ToDo type it to unique ptr. /** * Allows direct message dispatch to self. Not used for now. * * @tparam Event The event type to dispatch. * @param event A unique_ptr to Event/Message. */ template <typename Event> void notify(const Event& event) { schedule(event); consume(1); } /** * Consumes all commands and event from the queue which was pushed by schedule to the port. * * @param max might be that not all event needs to be dispatched so a maximum number of event to dispatch * @return the number of event has been dispatched. */ int consume(int max = std::numeric_limits<int>::max()); /** * The number of events in the queue (waiting to be dispatched). * * @return size of the event queue */ std::size_t getQueueEventCount() const { std::lock_guard<std::mutex> guard{eventMutex_}; return eventQueue_.size(); } private: /** * Stores the AsyncCallBackVector by base class CallbackVector event is hidden. */ using CallBackVector = std::unique_ptr<impl::CallbackVector>; /** * Mapping of type_id and CallBackVector is used at runtime to get back the callbacks for a * specific event type. */ using TypeIdToCallBackVector = std::map<impl::type_id_t, CallBackVector>; /** * Helper to process the CommandQueue and return the event queue size as a single operation * used in a while loop during consume * * Since the logic is first process all Commands (CallBack manipulation) then process the * events. * * @return Size of the event queue. */ std::size_t processCommandsAndGetQueuedEventsCount(); /** * If Port has either Command or Message to dispatch it schedules itself on the Actor. * * All prot activity is processed in actor context. */ void scheduleOnOwner(); // must be called from locked queue mutex content; ToDo RSZRSZ Add enforcement. CallBackHandle handleCounter_ = 0; /// used as a counter to generate unique callback handles TypeIdToCallBackVector callbacks_ = {}; /// the store for the callbacks registered for an event mutable std::mutex callbacksMutex_; /// guard for the command queue mutable std::mutex eventMutex_; /// quard for the event queue /** * Queue stores all events for dispatching */ std::deque<std::function<void()>> eventQueue_; /** * Queue stores all commands for dispatching */ std::deque<std::function<void()>> commandsQueue_; Actor& owner_; // it is a reference because ports are owned by actor and port schedules itself on an actor. Network& network_; // it is now a reference it probably ones dynamic connections are allowed must change to some /** * A state has to be maintained that the port is already in the actors queue. If it is there is * no need to add to it since it is already waiting for scheduling. */ bool scheduled_ = false; ADSTLOG_DEF_ACTOR_TRACE_MODULES(); }; } // namespace adst::ep::test_engine::core #include "core/actor.hpp" namespace adst::ep::test_engine::core { template <typename Event> void Port::listen(const CallBackHandle handle, std::function<void(const Event&)> callback) { static_assert(impl::validateEvent<Event>(), "Invalid event"); std::lock_guard<std::mutex> listenCmdQueueGuard{eventMutex_}; commandsQueue_.push_back([this, handle, callback = std::move(callback)]() { // it is not shadowing since the lambda is not executed in the listen call context std::lock_guard<std::mutex> lambdaCallbacksGuard{callbacksMutex_}; using Vector = impl::AsyncCallbackVector<Event>; // GCOVR_EXCL_START assert(callback && "callback should be valid"); // Check for valid object // GCOVR_EXCL_STOP auto& vector = callbacks_[impl::type_id<Event>()]; // GCOVR_EXCL_START if (vector == nullptr) { // GCOVR_EXCL_STOP vector.reset(new Vector{}); network_.listen<Event>([this](const std::shared_ptr<Event> event) { schedule(event); }); } // assert(dynamic_cast<Vector*>(vector.get())); // ToDo RSZRSZ Create ifdef for RTTI enabled ... auto callbacks = static_cast<Vector*>(vector.get()); LOG_C_D("Port::listen:{%s}", impl::getTypeName<Event>().c_str()); callbacks->add(handle, callback); }); scheduleOnOwner(); } template <typename Event> void Port::schedule(Event event) { using EventT = typename std::remove_reference<decltype(*Event())>::type; static_assert(impl::validateEvent<EventT>(), "Invalid event"); std::shared_ptr<EventT> shareableEvent = std::move(event); std::lock_guard<std::mutex> scheduleCmdQueueGuard{eventMutex_}; LOG_C_D("Port::schedule, dispatch:{%s}", impl::getTypeName<EventT>().c_str()); eventQueue_.push_back([this, event = std::move(shareableEvent)]() { std::lock_guard<std::mutex> lambdaCallbacksGuard{callbacksMutex_}; using Vector = impl::AsyncCallbackVector<EventT>; auto found = callbacks_.find(impl::type_id<EventT>()); LOG_C_D("Port::schedule, dispatch:{%s}", impl::getTypeName<EventT>().c_str()); // GCOVR_EXCL_START if (found == callbacks_.end()) { // GCOVR_EXCL_STOP LOG_C_D("Port::schedule, no listener:{%s}", impl::getTypeName<EventT>().c_str()); return; // no such notifications } std::unique_ptr<impl::CallbackVector>& vector = found->second; // assert(dynamic_cast<Vector*>(vector.get())); auto callbacks = static_cast<Vector*>(vector.get()); LOG_C_D("Port::schedule, dispatch:{%s}, callbacks.size=%d", impl::getTypeName<EventT>().c_str(), callbacks->container_.size()); for (const auto& element : callbacks->container_) { LOG_CH_D(MSG_RX, "%s", impl::getTypeName<EventT>().c_str()); element.second(*event); } }); scheduleOnOwner(); } template <typename Event> void Port::unlisten(const CallBackHandle handle) { static_assert(impl::validateEvent<Event>(), "Invalid event"); std::lock_guard<std::mutex> unListenCmdQueueGuard{eventMutex_}; commandsQueue_.push_back([this, handle]() { std::lock_guard<std::mutex> lambdaCallbacksGuard{callbacksMutex_}; auto found = callbacks_.find(impl::type_id<Event>()); if (found != callbacks_.end()) { LOG_C_D("Port::unlisten:{%s}", impl::getTypeName<Event>().c_str()); found->second->remove(handle); // ToDo RSZRSZ unlisten from Network. } }); scheduleOnOwner(); } } // namespace adst::ep::test_engine::core
34.73871
116
0.642957
csitarichie
3d76b3c08ae3f2a41530a971feadd39696ef51a6
374
hpp
C++
lib/include/messages/at.hpp
WojciechMigda/TCO-Ringbeller
8447e6ff44bba84b85250bdd3905180fcf1a96aa
[ "MIT" ]
null
null
null
lib/include/messages/at.hpp
WojciechMigda/TCO-Ringbeller
8447e6ff44bba84b85250bdd3905180fcf1a96aa
[ "MIT" ]
null
null
null
lib/include/messages/at.hpp
WojciechMigda/TCO-Ringbeller
8447e6ff44bba84b85250bdd3905180fcf1a96aa
[ "MIT" ]
null
null
null
#pragma once #ifndef LIB_INCLUDE_MESSAGES_AT_HPP_ #define LIB_INCLUDE_MESSAGES_AT_HPP_ #include "create.hpp" #include "message.hpp" namespace Ringbeller { /* * Prepare "AT" command */ template<typename Body = string_body> basic_request<Body> make_at() { return make_basic<Body>("", ""); } } // namespace Ringbeller #endif /* LIB_INCLUDE_MESSAGES_AT_HPP_ */
13.357143
41
0.729947
WojciechMigda
3d7869bd5c391ebe2d762a9c9e55ea7f6c9dd705
2,884
cc
C++
CondFormats/PhysicsToolsObjects/test/SiStripDeDx2DReader.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
CondFormats/PhysicsToolsObjects/test/SiStripDeDx2DReader.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
CondFormats/PhysicsToolsObjects/test/SiStripDeDx2DReader.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#ifndef SiStripDeDx2DReader_H #define SiStripDeDx2DReader_H // system include files //#include <memory> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "CondFormats/PhysicsToolsObjects/interface/Histogram2D.h" #include "CondFormats/DataRecord/interface/SiStripDeDxProton_2D_Rcd.h" #include <iostream> #include <stdio.h> #include <sys/time.h> class SiStripDeDx2DReader : public edm::EDAnalyzer { public: explicit SiStripDeDx2DReader(const edm::ParameterSet&); ~SiStripDeDx2DReader(); void analyze(const edm::Event&, const edm::EventSetup&); private: // uint32_t printdebug_; }; SiStripDeDx2DReader::SiStripDeDx2DReader(const edm::ParameterSet& iConfig) {} //: printdebug_(iConfig.getUntrackedParameter<uint32_t>("printDebug",1)){} SiStripDeDx2DReader::~SiStripDeDx2DReader() {} void SiStripDeDx2DReader::analyze(const edm::Event& e, const edm::EventSetup& iSetup) { edm::ESHandle<PhysicsTools::Calibration::VHistogramD2D> SiStripDeDx2D_; iSetup.get<SiStripDeDxProton_2D_Rcd>().get(SiStripDeDx2D_); edm::LogInfo("SiStripDeDx2DReader") << "[SiStripDeDx2DReader::analyze] End Reading SiStripDeDxProton_2D" << std::endl; for (int ihisto = 0; ihisto < 3; ihisto++) { std::cout << (SiStripDeDx2D_->vHist)[ihisto].numberOfBinsX() << " " << (SiStripDeDx2D_->vHist)[ihisto].numberOfBinsY() << std::endl; for (int ix = 0; ix < 300; ix++) { for (int iy = 0; iy < 1000; iy++) { std::cout << (SiStripDeDx2D_->vHist)[ihisto].binContent(ix, iy) << " " << (SiStripDeDx2D_->vHist)[ihisto].value(ix / 100., iy) << std::endl; } } std::cout << "Value = " << (SiStripDeDx2D_->vValues)[ihisto] << std::endl; } // std::vector<uint32_t> detid; // SiStripDeDx2D_->getDetIds(detid); // edm::LogInfo("Number of detids ") << detid.size() << std::endl; // if (printdebug_) // for (size_t id=0;id<detid.size() && id<printdebug_;id++) // { // SiStripDeDx2D::Range range=SiStripDeDx2D_->getRange(detid[id]); // int apv=0; // for(int it=0;it<range.second-range.first;it++){ // edm::LogInfo("SiStripDeDx2DReader") << "detid " << detid[id] << " \t" // << " apv " << apv++ << " \t" // << SiStripDeDx2D_->getDeDx2D(it,range) << " \t" // << std::endl; // } // } } #include "FWCore/PluginManager/interface/ModuleDef.h" #include "FWCore/Framework/interface/MakerMacros.h" DEFINE_FWK_MODULE(SiStripDeDx2DReader); #endif
34.746988
120
0.679612
ckamtsikis
3d7a945d5c2782cee1353075fa0211fbc70be92d
3,371
cpp
C++
2JCIE-EV01/OPT3001DNP.cpp
takjn/GRMOmronTest
26478958be0c623ac8c1cbc9bbfd607f7c9bf245
[ "MIT" ]
null
null
null
2JCIE-EV01/OPT3001DNP.cpp
takjn/GRMOmronTest
26478958be0c623ac8c1cbc9bbfd607f7c9bf245
[ "MIT" ]
null
null
null
2JCIE-EV01/OPT3001DNP.cpp
takjn/GRMOmronTest
26478958be0c623ac8c1cbc9bbfd607f7c9bf245
[ "MIT" ]
1
2020-02-14T06:49:41.000Z
2020-02-14T06:49:41.000Z
// SPDX-License-Identifier: MIT /* * MIT License * Copyright (c) 2019, 2018 - present OMRON Corporation * Copyright (c) 2019 Renesas Electronics Corporation * All rights reserved. * * 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 "OPT3001DNP.h" #define OPT3001_ADDR (0x45 << 1) #define OPT3001_REG_RESULT 0x00 #define OPT3001_REG_CONFIG 0x01 #define OPT3001_REG_LOLIMIT 0x02 #define OPT3001_REG_HILIMIT 0x03 #define OPT3001_REG_MANUFACTUREID 0x7E #define OPT3001_DEVICEID 0x7F #define OPT3001_CMD_CONFIG_MSB 0xC6 #define OPT3001_CMD_CONFIG_LSB 0x10 #define conv8s_u16_be(b, n) \ (uint16_t)(((uint16_t)b[n] << 8) | (uint16_t)b[n + 1]) // OPT3001DNP implementation OPT3001DNP::OPT3001DNP(PinName sda, PinName scl, int hz) : mI2c_(sda, scl) { mAddr = OPT3001_ADDR; mI2c_.frequency(hz); } bool OPT3001DNP::setup(void) { int ret; uint8_t wk_buf[3]; wk_buf[0] = OPT3001_REG_CONFIG; wk_buf[1] = OPT3001_CMD_CONFIG_MSB; wk_buf[2] = OPT3001_CMD_CONFIG_LSB; ret = mI2c_.write(mAddr, (char *)wk_buf, 3); if (ret != 0) { return false; } return true; } bool OPT3001DNP::read(uint32_t* light) { int ret; uint8_t rbuf[2]; uint16_t raw_data; ret = read_reg(OPT3001_REG_CONFIG, rbuf, sizeof(rbuf)); if (ret != 0) { return false; } if ((rbuf[1] & 0x80) == 0) { return false; // sensor is working... } ret = read_reg(OPT3001_REG_RESULT, rbuf, sizeof(rbuf)); if (ret != 0) { return false; } raw_data = conv8s_u16_be(rbuf, 0); if (light != NULL) { *light = convert_lux_value_x100(raw_data); } return true; } uint32_t OPT3001DNP::convert_lux_value_x100(uint16_t value_raw) { uint32_t value_converted; uint32_t lsb_size_x100; uint32_t data; // Convert the value to centi-percent RH lsb_size_x100 = 1 << ((value_raw >> 12) & 0x0F); data = value_raw & 0x0FFF; value_converted = lsb_size_x100 * data; return value_converted; } int OPT3001DNP::read_reg(uint8_t reg, uint8_t* pbuf, uint8_t len) { int ret; mI2c_.lock(); ret = mI2c_.write(mAddr, (char *)&reg, 1); if (ret == 0) { ret = mI2c_.read(mAddr, (char *)pbuf, len); } mI2c_.unlock(); return ret; }
27.185484
78
0.677544
takjn
3d7b0b4c14ef977d5aad1ddab068dd5a80480113
18,514
hh
C++
Kaskade/io/lossystorageDUNE.hh
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
3
2019-07-03T14:03:31.000Z
2021-12-19T10:18:49.000Z
Kaskade/io/lossystorageDUNE.hh
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
6
2020-02-17T12:01:31.000Z
2021-12-09T22:02:36.000Z
Kaskade/io/lossystorageDUNE.hh
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
2
2020-12-03T04:41:18.000Z
2021-01-11T21:44:42.000Z
#ifndef LOSSYSTORAGEDUNE_HH #define LOSSYSTORAGEDUNE_HH #include <map> #include <cassert> #include "dune/grid/common/grid.hh" #include "dune/grid/common/entitypointer.hh" #include "dune/grid/common/entity.hh" #include "dune/grid/io/file/dgfparser/dgfparser.hh" #include "dune/istl/matrix.hh" #include "dune/istl/bcrsmatrix.hh" #include "dune/common/fmatrix.hh" #include "dune/common/iteratorfacades.hh" #include "dune/istl/matrixindexset.hh" #include "rangecoder.hh" #include "lossy_helper.hh" // #define USEBOUNDS #define USEFREQ // #define LEVELWISE template <class Grid, class CoeffVector> class LossyStorage { public: static const int dim = Grid::dimension ; // degree of interpolation polynomials; currently only linear interpolation is supported static const int order = 1 ; // some typedefs used throughout the class typedef typename Grid::template Codim<dim>::LevelIterator VertexLevelIterator ; typedef typename Grid::template Codim<dim>::LeafIterator VertexLeafIterator ; typedef typename Grid::LeafIndexSet IndexSet; typedef typename Grid::LevelGridView::IndexSet::IndexType IndexType; typedef typename Grid::LeafGridView::IndexSet::IndexType LeafIndexType; typedef typename Grid::Traits::GlobalIdSet::IdType IdType; typedef unsigned long int ULong; LossyStorage( int coarseLevel_, double aTol_) : ps(NULL), coarseLevel(coarseLevel_), aTol(aTol_), accumulatedEntropy(0), accumulatedOverhead(0), accumulatedUncompressed(0), accumulatedCompressed(0) { /*#ifdef USEFREQ std::cout << "USES PRECOMPUTED FREQUENCIES FOR ENCODING A SINGLE FUNCTION!\nBEWARE OF THE OVERHEAD!\n"; std::cout << "Due to implementation, not using pre-computed frequencies fails, as the vectors used for\n" << "Alphabet are too large.\n"; #else std::cout << "Uses dictionary for encoding. Beware of the overhead!\n"; std::cout << "Due to implementation, not using the dictionary fails, as the vectors used for\n" << "Alphabet would be too large for fine quantization.\n"; #endif*/ } ~LossyStorage() { if( ps != NULL ) delete ps; } // returns the entropy (summed since the last call to resetEntropy/resetSizes) // of the data (= average symbol size in byte needed to store the file) double reportEntropy() { return accumulatedEntropy; } void resetEntropy() { accumulatedEntropy = 0; } // reports the overhead (summed since last call to resetOverhead/resetSizes) // i.e. interval bounds, frequencies, etc. double reportOverhead() { return accumulatedOverhead; } void resetOverhead() { accumulatedOverhead = 0; } // returns the compressed size // which is (in the best case) the size of the encoded, compressed file // without the overhead from storing intervals etc. double reportCompressedSize() { return accumulatedCompressed; } void resetCompressedSize() { accumulatedCompressed = 0 ; } // returns the compressed size + overhead, which is (in the best case/in the limit) // the size of the compressed file (including all side information) double reportOverallSize() { return accumulatedCompressed + accumulatedOverhead; } // reset everything void resetSizes() { accumulatedEntropy = 0; accumulatedOverhead = 0; accumulatedCompressed = 0; accumulatedUncompressed = 0; } // returns the size needed for uncompressed storage of the data double reportUncompressedSize() { return accumulatedUncompressed; } void resetUncompressedSize() { accumulatedUncompressed = 0 ; } // returns the compression factor (=uncompressed size/compressed size) double reportRatio() { if( accumulatedCompressed + accumulatedOverhead > 0 ) return accumulatedUncompressed / (accumulatedCompressed + accumulatedOverhead ); return -1; } // TODO: has to be faster for adaptive meshes! void setup( Grid const& grid ) { if( ps != NULL ) delete ps; ps = new Lossy_Detail::Prolongation<Grid>(grid); // auto foo = Lossy_Detail::ProlongationStack<Grid>(grid); // for debugging, should use ps = new Prolongation<Grid> instead! typename Grid::GlobalIdSet const& idSet = grid.globalIdSet(); levelInfo.clear(); for( int level = grid.maxLevel(); level >= 0; --level ) { VertexLevelIterator lEnd = grid.template lend <dim>( level ); for( VertexLevelIterator it = grid.template lbegin <dim>( level ); it != lEnd; ++it ) { levelInfo[idSet.id( *it )] = level ; } } } /** * Encode a given state, e.g. the difference between to timesteps. * Quantized values are written to a file specified by fn. */ void encode( Grid const& grid, CoeffVector const& sol, std::string fn, double aTol_ = 0, int maxLevel_ = -1 ) { std::ofstream out( fn.c_str(), std::ios::binary ) ; encode( grid, sol, out, aTol_, maxLevel_); out.close(); } void encode( Grid const& grid, CoeffVector const& sol, std::ostream& out, double aTol_ = 0, int maxLevel_ = -1 ) { double aTolSave = aTol ; if( aTol_ > 0 ) aTol = aTol_ ; // use maxLevel_ instead of maxLevel member int maxLevel = maxLevel_; if( maxLevel < 0 ) maxLevel = grid.maxLevel() ; double overhead = 0, entropy = 0, compressed = 0 ; size_t nNodes = grid.size(dim); typename Grid::GlobalIdSet const& idSet = grid.globalIdSet(); typename Grid::LeafGridView::IndexSet const& leafIndexSet = grid.leafIndexSet(); std::vector<long int> indices ; std::vector<double> predictionError ; std::vector<std::vector<long int> > levelIndices; VertexLevelIterator itEnd = grid.template lend<dim>(coarseLevel); for( VertexLevelIterator it = grid.template lbegin<dim>( coarseLevel ) ; it != itEnd; ++it ) { predictionError.push_back( -sol[leafIndexSet.index(*it)] ) ; } quantize( predictionError, indices) ; reconstruct( predictionError, indices ) ; levelIndices.push_back(indices); CoeffVector reconstruction(grid.size(coarseLevel, dim) ) ; // assign reconstructed coarse grid values size_t nEntries = sol.size(); std::vector<long int> intervalIndicesTmp( nEntries ); long int minIndex = 0; size_t vertexCount = 0 ; for( VertexLevelIterator it = grid.template lbegin<dim>(coarseLevel); it != itEnd; ++it) { reconstruction[vertexCount] = -predictionError[vertexCount] ; long int tmpIndex = indices[vertexCount]; intervalIndicesTmp[leafIndexSet.index(*it)] = tmpIndex; if( tmpIndex < minIndex ) minIndex = tmpIndex; vertexCount++ ; } CoeffVector prediction; for( int l = coarseLevel ; l < maxLevel ; l++ ) { ps->mv(l, reconstruction, prediction) ; std::vector<std::vector<size_t> > vertexInfo( prediction.size(), std::vector<size_t>(3) ); predictionError.clear(); predictionError.reserve( prediction.size() ); // avoid reallocations vertexCount = 0 ; typename Grid::LevelGridView::IndexSet const& levelIndexSet = grid.levelGridView(l+1).indexSet(); itEnd = grid.template lend<dim>(l+1); for( VertexLevelIterator it = grid.template lbegin<dim>(l+1); it != itEnd; ++it) { unsigned char vertexLevel = levelInfo[idSet.id( *it )] ; if( vertexLevel == l+1 ) { predictionError.push_back(prediction[levelIndexSet.index(*it)] - sol[leafIndexSet.index(*it)] ); } vertexInfo[vertexCount][0] = levelIndexSet.index(*it) ; vertexInfo[vertexCount][1] = leafIndexSet.index(*it) ; vertexInfo[vertexCount][2] = vertexLevel ; vertexCount++; } quantize( predictionError, indices) ; reconstruct( predictionError, indices) ; levelIndices.push_back(indices); if( (l+1) < maxLevel ) { // prepare prediction on next level -- use reconstructed values reconstruction.resize( prediction.size() ); vertexCount = 0 ; for( size_t ii = 0 ; ii < vertexInfo.size(); ii++ ) { // correction only for the nodes on level l+1 unsigned char vertexLevel = vertexInfo[ii][2]; IndexType levelIndex = vertexInfo[ii][0]; if( vertexLevel < l+1 ) { reconstruction[levelIndex] = prediction[levelIndex]; } else { long int tmpIndex = indices[vertexCount]; intervalIndicesTmp[vertexInfo[ii][1] ] = tmpIndex; if( tmpIndex < minIndex ) minIndex = tmpIndex; reconstruction[levelIndex] = prediction[levelIndex]-predictionError[vertexCount] ; vertexCount++; } } } else { vertexCount = 0 ; for( size_t ii = 0 ; ii < vertexInfo.size(); ii++ ) { unsigned char vertexLevel = vertexInfo[ii][2];//levelInfo[idSet.id( *it )] ; if( vertexLevel < l+1 ) continue; long int tmpIndex = indices[vertexCount]; intervalIndicesTmp[vertexInfo[ii][1] ] = tmpIndex; if( tmpIndex < minIndex ) minIndex = tmpIndex; vertexCount++ ; } } } std::vector<ULong> intervalIndices( nEntries ) ; for( size_t i = 0; i < nEntries; i++ ) intervalIndices[i] = intervalIndicesTmp[i] - minIndex ; out.write(reinterpret_cast<char*>( &minIndex ), sizeof(long int) ) ; overhead += sizeof(long int); std::map<unsigned long, unsigned long> freqMap; unsigned int nnz = 0; for( size_t i = 0 ; i < nEntries ; i++ ) { if( freqMap.find(intervalIndices[i] ) != freqMap.end() ) // already there, increment { freqMap[intervalIndices[i]]++ ; } else // new nonzero, add to map { nnz++; freqMap[intervalIndices[i]] = 1; } } out.write(reinterpret_cast<char*>( &nnz ), sizeof(unsigned int) ) ; overhead += sizeof(unsigned int); std::vector<unsigned long> frequenciesForRangeCoder(nnz); std::map<unsigned long, unsigned long> dictMap; unsigned long curNo = 0 ; std::map<unsigned long,unsigned long>::iterator mapIt; std::map<unsigned long,unsigned long>::iterator mapEnd = freqMap.end(); for( mapIt = freqMap.begin(); mapIt != mapEnd; ++mapIt ) { unsigned long lv = mapIt->first; frequenciesForRangeCoder[curNo] = mapIt->second; dictMap.insert( dictMap.begin(), std::pair<unsigned long, unsigned long>(lv, curNo) ) ; out.write(reinterpret_cast<char*>( &lv ), sizeof(unsigned long) ) ; overhead += sizeof(unsigned long); curNo++; } for( unsigned int i = 0 ; i < nnz ; i++ ) { #ifdef USEFREQ out.write(reinterpret_cast<char*>( &frequenciesForRangeCoder[i] ), sizeof(unsigned long) ) ; overhead += sizeof(unsigned long); #endif double tmp = -ld(frequenciesForRangeCoder[i]/((double)nNodes)) * frequenciesForRangeCoder[i]/((double)nNodes); entropy += tmp; compressed += tmp; } accumulatedCompressed += compressed/8*nNodes; compressed = 0; #ifndef USEFREQ frequenciesForRangeCoder.clear(); freqMap.clear(); #endif std::cout.flush(); #ifdef USEFREQ Alphabet<unsigned long> alphabet( frequenciesForRangeCoder.begin(), frequenciesForRangeCoder.end() ) ; RangeEncoder<unsigned long> encoder( out ) ; for( size_t i = 0 ; i < nEntries; i++ ) { encodeSymbol( encoder, alphabet, dictMap.find(intervalIndices[i])->second/* dictMap[intervalIndices[i]]*/ ); } #else size_t symbolCounter = 0 ; std::vector<unsigned long> count(nnz, 1) ; Alphabet<unsigned long> alphabet( count.begin(), count.end() ) ; RangeEncoder<unsigned long> encoder(out) ; for( size_t i = 0 ; i < nEntries; i++ ) { encodeSymbol( encoder, alphabet, dictMap.find(intervalIndices[i])->second); ++count[dictMap[intervalIndices[i]]]; ++symbolCounter ; if (symbolCounter>0.1*nEntries) { alphabet.update(count.begin(),count.end()); symbolCounter=0; } } #endif accumulatedEntropy += entropy/8 ; accumulatedOverhead += overhead; accumulatedUncompressed += 8*nNodes; aTol = aTolSave; } /** * Decode quantized values and store in a VariableSet::Representation. * The file to be read is specified by fn. */ void decode( Grid const& gridState, CoeffVector& sol, std::string fn, double aTol_ = 0, int maxLevel_ = -1 ) { std::ifstream in( fn.c_str(), std::ios::binary ) ; decode(gridState, sol, in, aTol_, maxLevel_); in.close() ; } void decode( Grid const& gridState, CoeffVector& sol, std::istream& in, double aTol_ = 0, int maxLevel_ = -1 ) { double aTolSave = aTol ; if( aTol_ > 0 ) aTol = aTol_ ; int maxLevel = maxLevel_; if( maxLevel < 0 ) maxLevel = gridState.maxLevel(); // prepare prediction typename Grid::GlobalIdSet const& idSet = gridState.globalIdSet(); IndexSet const& indexSet = gridState.leafIndexSet(); std::vector<double> values ; std::vector<long int> intervalIndices( gridState.size(dim) ); size_t nEntries = intervalIndices.size(); VertexLevelIterator itEnd = gridState.template lend<dim>(coarseLevel); // read in indices from file long int minIndex ; in.read(reinterpret_cast<char*>( &minIndex ), sizeof(long int) ) ; unsigned int nnz ; in.read(reinterpret_cast<char*>( &nnz ), sizeof(unsigned int) ) ; // # non-empty intervals std::vector<long int> dictionary( nnz ) ; for( int i = 0 ; i < nnz ; i++ ) { in.read(reinterpret_cast<char*>( &dictionary[i] ), sizeof(unsigned long) ) ; // existing intervals (dictionary) } #ifdef USEFREQ std::vector<unsigned long> frequencies( nnz, 0 ) ; for( int i = 0 ; i < nnz ; i++ ) { in.read(reinterpret_cast<char*>( &frequencies[i] ), sizeof(unsigned long) ) ; // frequencies } Alphabet<unsigned long> alphabet( frequencies.begin(), frequencies.end() ) ; try { RangeDecoder<unsigned long> decoder( in ) ; for( int i = 0 ; i < intervalIndices.size() ; i++ ) { unsigned long s = decodeSymbol(decoder,alphabet) ; intervalIndices[i] = dictionary[s] + minIndex ; } } catch( std::ios_base::failure& e ) { if (in.rdstate() & std::ifstream::eofbit) { std::cout << "EOF reached.\n"; } else { std::cout << " Decoding error\n" << e.what() << "\n"; } } #else size_t symbolCounter = 0 ; std::vector<unsigned long> symcount(nnz, 1) ; Alphabet<unsigned long> alphabet( symcount.begin(), symcount.end() ) ; try { RangeDecoder<unsigned long> decoder( in ) ; for( size_t i = 0 ; i < nEntries ; i++ ) { unsigned long s = decodeSymbol(decoder,alphabet) ; intervalIndices[i] = dictionary[s] + minIndex ; ++symcount[s]; ++symbolCounter ; if (symbolCounter>0.1*nEntries) { alphabet.update(symcount.begin(),symcount.end()); symbolCounter=0; } } } catch( std::ios_base::failure& e ) { if (in.rdstate() & std::ifstream::eofbit) { std::cout << "EOF reached.\n"; } else { std::cout << " Decoding error\n" << e.what() << "\n"; } } #endif // in.close() ; // start reconstruction int vertexCount = 0; CoeffVector reconstruction( gridState.size(coarseLevel, dim) ); sol.resize( gridState.size(dim) ); for( VertexLevelIterator it = gridState.template lbegin<dim>( coarseLevel ); it != itEnd; ++it) { double recVal = reconstruct( intervalIndices[indexSet.index(*it)]); reconstruction[gridState.levelGridView(coarseLevel).indexSet().index(*it)] = -recVal ; // store predicted values for the coarse grid in solution vector sol[ indexSet.index(*it) ] = -recVal ; vertexCount++ ; } CoeffVector prediction; // perform prediction and correction for( int l = coarseLevel ; l < maxLevel ; l++ ) { ps->mv( l, reconstruction, prediction ) ; reconstruction.resize( prediction.size() ); typename Grid::LevelGridView::IndexSet const& levelIndexSet = gridState.levelGridView(l+1).indexSet(); vertexCount = 0 ; itEnd = gridState.template lend<dim>(l+1); for( VertexLevelIterator it = gridState.template lbegin<dim>(l+1); it != itEnd ; ++it) { IndexType levelIndex = levelIndexSet.index(*it); if(levelInfo[gridState.globalIdSet().id(*it)] == l+1) //correct only vertices on level l+1 { reconstruction[levelIndex] = prediction[levelIndex] - reconstruct( intervalIndices[indexSet.index(*it)]); } else { reconstruction[levelIndex] = prediction[levelIndex]; } sol[indexSet.index(*it)] = reconstruction[ levelIndex] ; vertexCount++ ; } } aTol = aTolSave ; } private: LossyStorage( LossyStorage const& ); LossyStorage& operator=( LossyStorage const& ) ; /** Helper method to perform the actual quantization for a whole level. */ void quantize( std::vector<double> const& values, std::vector<long int>& indices) { indices.clear() ; indices.resize( values.size(), 0 ) ; for( size_t i = 0 ; i < values.size() ; i++ ) { indices[i] = static_cast<long int>( floor( values[i] / (2*aTol) + 0.5 ) ); } } /** Helper method to perform the actual reconstruction of quantized values without lb, ub. */ void reconstruct( std::vector<double>& values, std::vector<long int> const& indices) { values.clear() ; values.resize( indices.size() ) ; for( size_t i = 0 ; i < indices.size() ; i++ ) { values[i] = indices[i] * 2* aTol ; } } /** Helper method to perform the actual reconstruction of quantized values without lb, ub. */ double reconstruct( long int const& index ) { return index*2*aTol; } /** Helper method returning the base 2-logarithm. */ double ld( double val ) { return log(val)/log(2.0) ; } Lossy_Detail::Prolongation<Grid> * ps; std::map<IdType, unsigned char> levelInfo ; int coarseLevel ; double aTol ; double accumulatedEntropy, accumulatedOverhead, accumulatedUncompressed, accumulatedCompressed; } ; #endif
30.35082
128
0.633737
chenzongxiong
3d7b49ae1d91f630dd24ca58761b05eec3f2eb85
841
cpp
C++
Leetcode/Coding Interviews/56_01_Single_Numbers.cpp
ZR-Huang/AlgorithmPractices
226cecde136531341ce23cdf88529345be1912fc
[ "BSD-3-Clause" ]
1
2019-11-26T11:52:25.000Z
2019-11-26T11:52:25.000Z
Leetcode/Coding Interviews/56_01_Single_Numbers.cpp
ZR-Huang/AlgorithmPractices
226cecde136531341ce23cdf88529345be1912fc
[ "BSD-3-Clause" ]
null
null
null
Leetcode/Coding Interviews/56_01_Single_Numbers.cpp
ZR-Huang/AlgorithmPractices
226cecde136531341ce23cdf88529345be1912fc
[ "BSD-3-Clause" ]
null
null
null
/* 一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。 要求时间复杂度是O(n),空间复杂度是O(1)。 示例 1: 输入:nums = [4,1,4,6] 输出:[1,6] 或 [6,1] 示例 2: 输入:nums = [1,2,10,4,1,4,3,3] 输出:[2,10] 或 [10,2] 限制: 2 <= nums <= 10000 */ #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> singleNumbers(vector<int>& nums) { // https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/solution/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-by-leetcode/ vector<int> ans = {0, 0}; int sum = 0; for(int num: nums) sum ^= num; int flag = 1; while((flag & sum) == 0) flag <<= 1; for(int num: nums) if(num & flag) ans[0] ^= num; else ans[1] ^= num; return ans; } };
21.564103
148
0.525565
ZR-Huang
3d7dc2702f89d2573a9aa8f59d12c1217bcd3428
2,199
hpp
C++
plugins/history_plugin/include/eosio/history_plugin/public_key_history_object.hpp
linapex/eos-chinese
33539709c30940b6489cec1ed2d982ff76da5cc5
[ "MIT" ]
null
null
null
plugins/history_plugin/include/eosio/history_plugin/public_key_history_object.hpp
linapex/eos-chinese
33539709c30940b6489cec1ed2d982ff76da5cc5
[ "MIT" ]
null
null
null
plugins/history_plugin/include/eosio/history_plugin/public_key_history_object.hpp
linapex/eos-chinese
33539709c30940b6489cec1ed2d982ff76da5cc5
[ "MIT" ]
null
null
null
//<developer> // <name>linapex 曹一峰</name> // <email>linapex@163.com</email> // <wx>superexc</wx> // <qqgroup>128148617</qqgroup> // <url>https://jsq.ink</url> // <role>pku engineer</role> // <date>2019-03-16 19:44:17</date> //</624457052034437120> /* *@文件 *@eos/license中定义的版权 **/ #pragma once #include <chainbase/chainbase.hpp> #include <fc/array.hpp> namespace eosio { using chain::account_name; using chain::public_key_type; using chain::permission_name; using namespace boost::multi_index; class public_key_history_object : public chainbase::object<chain::public_key_history_object_type, public_key_history_object> { OBJECT_CTOR(public_key_history_object) id_type id; public_key_type public_key; account_name name; permission_name permission; }; struct by_id; struct by_pub_key; struct by_account_permission; using public_key_history_multi_index = chainbase::shared_multi_index_container< public_key_history_object, indexed_by< ordered_unique<tag<by_id>, BOOST_MULTI_INDEX_MEMBER(public_key_history_object, public_key_history_object::id_type, id)>, ordered_unique<tag<by_pub_key>, composite_key< public_key_history_object, member<public_key_history_object, public_key_type, &public_key_history_object::public_key>, member<public_key_history_object, public_key_history_object::id_type, &public_key_history_object::id> > >, ordered_unique<tag<by_account_permission>, composite_key< public_key_history_object, member<public_key_history_object, account_name, &public_key_history_object::name>, member<public_key_history_object, permission_name, &public_key_history_object::permission>, member<public_key_history_object, public_key_history_object::id_type, &public_key_history_object::id> > > > >; typedef chainbase::generic_index<public_key_history_multi_index> public_key_history_index; } CHAINBASE_SET_INDEX_TYPE( eosio::public_key_history_object, eosio::public_key_history_multi_index ) FC_REFLECT( eosio::public_key_history_object, (public_key)(name)(permission) )
31.869565
126
0.740791
linapex
3d80126b6396cea31dd30fb9995176cb44122e00
280
hpp
C++
ch5/stack5assign.hpp
silenc3502/cpp_examples
cee147ac92e68c9086b7a2465e8fe360d3a594dd
[ "MIT" ]
null
null
null
ch5/stack5assign.hpp
silenc3502/cpp_examples
cee147ac92e68c9086b7a2465e8fe360d3a594dd
[ "MIT" ]
null
null
null
ch5/stack5assign.hpp
silenc3502/cpp_examples
cee147ac92e68c9086b7a2465e8fe360d3a594dd
[ "MIT" ]
null
null
null
template <typename T> template <typename T2> Stack<T>& Stack<T>::operator=(Stack<T2> const& op2) { if((void*)this == (void*)&op2) { return *this; } Stack<T2> tmp(op2); elems.clear(); while (!tmp.empty()) { elems.push_front(tmp.top()); tmp.pop(); } return *this; }
15.555556
53
0.607143
silenc3502
3d8369e2d74a6da787ed278e972c1233294725a3
1,117
cpp
C++
oclint-core/lib/RuleBase.cpp
BGU-AiDnD/oclint
484fed44ca0e34532745b3d4f04124cbf5bb42fa
[ "BSD-3-Clause" ]
3,128
2015-01-01T06:00:31.000Z
2022-03-29T23:43:20.000Z
oclint-core/lib/RuleBase.cpp
BGU-AiDnD/oclint
484fed44ca0e34532745b3d4f04124cbf5bb42fa
[ "BSD-3-Clause" ]
432
2015-01-03T15:43:08.000Z
2022-03-29T02:32:48.000Z
oclint-core/lib/RuleBase.cpp
BGU-AiDnD/oclint
484fed44ca0e34532745b3d4f04124cbf5bb42fa
[ "BSD-3-Clause" ]
454
2015-01-06T03:11:12.000Z
2022-03-22T05:49:38.000Z
#include "oclint/RuleBase.h" using namespace oclint; void RuleBase::takeoff(RuleCarrier *carrier) { _carrier = carrier; apply(); } const std::string RuleBase::attributeName() const { return name(); } const std::string RuleBase::identifier() const { std::string copy = name(); if (copy.empty()) { return copy; } copy[0] = toupper(copy[0]); for (std::string::iterator it = copy.begin() + 1; it != copy.end(); ++it) { if (!isalpha(*(it - 1)) && islower(*it)) { *it = toupper(*it); } } copy.erase(std::remove_if(copy.begin(), copy.end(), [](char eachChar){return !isalpha(eachChar);}), copy.end()); return copy; } #ifdef DOCGEN const std::string RuleBase::fileName() const { return identifier() + "Rule.cpp"; } bool RuleBase::enableSuppress() const { return false; } const std::map<std::string, std::string> RuleBase::thresholds() const { std::map<std::string, std::string> emptyMap; return emptyMap; } const std::string RuleBase::additionalDocument() const { return ""; } #endif
18.616667
77
0.59803
BGU-AiDnD
3d8535d3e6a7fd259ed2c5d332e77902c3c882e5
6,902
cc
C++
test/gtest/uct/test_ib.cc
abouteiller/ucx
f4196de7b4be0a78412d548a025d46ec3163767a
[ "BSD-3-Clause" ]
null
null
null
test/gtest/uct/test_ib.cc
abouteiller/ucx
f4196de7b4be0a78412d548a025d46ec3163767a
[ "BSD-3-Clause" ]
null
null
null
test/gtest/uct/test_ib.cc
abouteiller/ucx
f4196de7b4be0a78412d548a025d46ec3163767a
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (C) Mellanox Technologies Ltd. 2001-2014. ALL RIGHTS RESERVED. * Copyright (C) UT-Battelle, LLC. 2014. ALL RIGHTS RESERVED. * See file LICENSE for terms. */ extern "C" { #include <poll.h> #include <uct/api/uct.h> #include <ucs/time/time.h> #include <uct/ib/base/ib_device.h> #include <uct/ib/base/ib_iface.h> } #include <common/test.h> #include "uct_test.h" class test_uct_ib : public uct_test { public: void initialize() { uct_test::init(); m_e1 = uct_test::create_entity(0); m_entities.push_back(m_e1); m_e2 = uct_test::create_entity(0); m_entities.push_back(m_e2); m_e1->connect(0, *m_e2, 0); m_e2->connect(0, *m_e1, 0); } typedef struct { unsigned length; /* data follows */ } recv_desc_t; static ucs_status_t ib_am_handler(void *arg, void *data, size_t length, void *desc) { recv_desc_t *my_desc = (recv_desc_t *) arg; uint64_t *test_ib_hdr = (uint64_t *) data; uint64_t *actual_data = (uint64_t *) test_ib_hdr + 1; unsigned data_length = length - sizeof(test_ib_hdr); my_desc->length = data_length; if (*test_ib_hdr == 0xbeef) { memcpy(my_desc + 1, actual_data , data_length); } return UCS_OK; } ucs_status_t pkey_test(const char *dev_name, unsigned port_num) { struct ibv_device **device_list; struct ibv_context *ibctx = NULL; struct ibv_port_attr port_attr; uct_ib_iface_config_t *ib_config = ucs_derived_of(m_iface_config, uct_ib_iface_config_t); int num_devices, i, found = 0; uint16_t table_idx, pkey, pkey_partition; /* get device list */ device_list = ibv_get_device_list(&num_devices); if (device_list == NULL) { UCS_TEST_ABORT("Failed to get the device list."); } /* search for the given device in the device list */ for (i = 0; i < num_devices; ++i) { if (strcmp(device_list[i]->name, dev_name)) { continue; } /* found this dev_name on the host - open it */ ibctx = ibv_open_device(device_list[i]); if (ibctx == NULL) { UCS_TEST_ABORT("Failed to open the device."); } found = 1; break; } if (found != 1) { UCS_TEST_ABORT("The requested device: " << dev_name << ", wasn't found in the device list."); } found = 0; /* check if the configured pkey exists in the port's pkey table */ if (ibv_query_port(ibctx, port_num, &port_attr) != 0) { UCS_TEST_ABORT("Failed to query port " << port_num << " on device: " << dev_name); } #if HAVE_DECL_IBV_LINK_LAYER_ETHERNET if (port_attr.link_layer == IBV_LINK_LAYER_ETHERNET) { found = 0; goto out; } #endif for (table_idx = 0; table_idx < port_attr.pkey_tbl_len; table_idx++) { if(ibv_query_pkey(ibctx, port_num, table_idx, &pkey)) { UCS_TEST_ABORT("Failed to query pkey on port " << port_num << " on device: " << dev_name); } pkey_partition = ntohs(pkey) & UCT_IB_PKEY_PARTITION_MASK; if (pkey_partition == (ib_config->pkey_value & UCT_IB_PKEY_PARTITION_MASK)) { found = 1; break; } } #if HAVE_DECL_IBV_LINK_LAYER_ETHERNET out: #endif ibv_close_device(ibctx); ibv_free_device_list(device_list); if (found) { return UCS_OK; } else { return UCS_ERR_NO_ELEM; } } ucs_status_t test_pkey_avail() { char *p, *dev_name; unsigned port_num; ucs_status_t ret; dev_name = strdup(GetParam()->dev_name.c_str()); /* device name and port number */ /* split dev_name */ p = strchr(dev_name, ':'); EXPECT_TRUE(p != NULL); *p = 0; /* dev_name holds the device name */ /* port number */ if (sscanf(p + 1, "%d", &port_num) != 1) { UCS_TEST_ABORT("Failed to get the port number on device: " << dev_name); } ret = pkey_test(dev_name, port_num); free(dev_name); return ret; } void test_address_pack(uct_ib_address_type_t scope, uint64_t subnet_prefix) { static const uint16_t lid_in = 0x1ee7; union ibv_gid gid_in, gid_out; uct_ib_address_t *ib_addr; uint16_t lid_out; uint8_t is_global; ib_addr = (uct_ib_address_t*)malloc(uct_ib_address_size(scope)); gid_in.global.subnet_prefix = subnet_prefix; gid_in.global.interface_id = 0xdeadbeef; uct_ib_address_pack(ib_device(m_e1), scope, &gid_in, lid_in, ib_addr); uct_ib_address_unpack(ib_addr, &lid_out, &is_global, &gid_out); EXPECT_EQ((scope != UCT_IB_ADDRESS_TYPE_LINK_LOCAL), is_global); EXPECT_EQ(lid_in, lid_out); if (is_global) { EXPECT_EQ(gid_in.global.subnet_prefix, gid_out.global.subnet_prefix); EXPECT_EQ(gid_in.global.interface_id, gid_out.global.interface_id); } free(ib_addr); } uct_ib_device_t *ib_device(entity *entity) { uct_ib_iface_t *iface = ucs_derived_of(entity->iface(), uct_ib_iface_t); return uct_ib_iface_device(iface); } protected: entity *m_e1, *m_e2; }; UCS_TEST_P(test_uct_ib, non_default_pkey, "IB_PKEY=0x2") { uint64_t send_data = 0xdeadbeef; uint64_t test_ib_hdr = 0xbeef; recv_desc_t *recv_buffer; ucs_status_t ret; /* check if the configured pkey exists in the port's pkey table. * skip this test if it doesn't. */ ret = test_pkey_avail(); if (ret == UCS_OK) { initialize(); } else { UCS_TEST_SKIP_R("pkey not found or not an IB port"); } check_caps(UCT_IFACE_FLAG_AM_SHORT); recv_buffer = (recv_desc_t *) malloc(sizeof(*recv_buffer) + sizeof(uint64_t)); recv_buffer->length = 0; /* Initialize length to 0 */ /* set a callback for the uct to invoke for receiving the data */ uct_iface_set_am_handler(m_e2->iface(), 0, ib_am_handler , recv_buffer, UCT_AM_CB_FLAG_SYNC); /* send the data */ uct_ep_am_short(m_e1->ep(0), 0, test_ib_hdr, &send_data, sizeof(send_data)); short_progress_loop(100.0); ASSERT_EQ(sizeof(send_data), recv_buffer->length); EXPECT_EQ(send_data, *(uint64_t*)(recv_buffer+1)); free(recv_buffer); } UCS_TEST_P(test_uct_ib, address_pack) { initialize(); test_address_pack(UCT_IB_ADDRESS_TYPE_LINK_LOCAL, UCT_IB_LINK_LOCAL_PREFIX); test_address_pack(UCT_IB_ADDRESS_TYPE_SITE_LOCAL, UCT_IB_SITE_LOCAL_PREFIX | htonll(0x7200)); test_address_pack(UCT_IB_ADDRESS_TYPE_GLOBAL, 0xdeadfeedbeefa880ul); } UCT_INSTANTIATE_IB_TEST_CASE(test_uct_ib);
31.230769
106
0.619096
abouteiller
3d85a355c011f71f3f8f59494c3b6a539c6ba3c6
6,869
cpp
C++
src/Huffman.cpp
taleroangel/ProyeccionesEDD
d246dc22776fca09b2a36c82b3db682f3af3a155
[ "MIT" ]
null
null
null
src/Huffman.cpp
taleroangel/ProyeccionesEDD
d246dc22776fca09b2a36c82b3db682f3af3a155
[ "MIT" ]
null
null
null
src/Huffman.cpp
taleroangel/ProyeccionesEDD
d246dc22776fca09b2a36c82b3db682f3af3a155
[ "MIT" ]
null
null
null
#include "Huffman.h" #include <cstdlib> #include <cstring> #include <exception> #include <fstream> #include <map> #include <queue> #include <sstream> #include <stdexcept> #include <string> #include <utility> #include "ArbolCodificacion.hxx" #include "CodigoElemento.hxx" #include "Imagen.h" #include "NodoCodificacion.hxx" #include "NodoElemento.hxx" #include "NodoFrecuencia.hxx" Huffman::Huffman(const Imagen &img) : ancho(img.get_ancho()), alto(img.get_alto()), maximo(img.get_max_tam()), imagen(&img) { // Verificar normalización if (img.get_max_tam() > 255) throw std::invalid_argument("La imagen no está normalizada"); // Construir mapa de frecuencias std::map<byte_t, freq_t> frecuencias{}; for (int i = 0; i <= 255; i++) frecuencias[i] = 0; // Calcular frecuencias en la imágen Imagen::matriz_t pixeles = img.get_pixeles(); for (int i = 0; i < img.get_alto(); i++) for (int j = 0; j < img.get_ancho(); j++) frecuencias[(byte_t)pixeles[i][j]]++; // Cada vez que se encuentra un // pixel, le suma 1 a su frecuencia // Se crea el árbol de codificacion this->arbol = new ArbolCodificacion<byte_t>{frecuencias}; std::vector<CodigoElemento<byte_t>> datos = arbol->codigos_elementos(); // Se obtienen las frecuencias y valores de los bytes for (int i = 0; i < datos.size(); i++) codigos[datos[i].elemento] = datos[i]; } Huffman::Huffman(const std::string nombre_archivo, std::string salida) : imagen{nullptr} { //* Abrir el archivo std::ifstream archivo(nombre_archivo, std::ios::binary | std::ios::in); // Verificar que se pudo abrir if (!archivo.is_open()) throw std::runtime_error("No se pudo abrir el archivo"); //* Header archivo.read((char *)(&this->ancho), sizeof(word_t)); archivo.read((char *)(&this->alto), sizeof(word_t)); archivo.read((char *)(&this->maximo), sizeof(byte_t)); //* Frecuencias // Escribir todas las frecuencias for (byte_t i = 0; i < 255; i++) { if (!codigos.count(i)) codigos[i] = CodigoElemento<byte_t>{i, 0, ""}; // Read binary archivo.read((char *)&codigos[i].frecuencia, sizeof(lword_t)); } //* Construir el árbol std::map<byte_t, freq_t> frecuencias{}; for (std::pair<byte_t, CodigoElemento<byte_t>> codigo : codigos) frecuencias[codigo.first] = codigo.second.frecuencia; this->arbol = new ArbolCodificacion<byte_t>{frecuencias}; //* Obtener los bits std::vector<byte_t> bytes{}; std::queue<int> cadenabits{}; while (!archivo.eof()) { byte_t byte = 0x0000; archivo.read((char *)&byte, sizeof(byte_t)); // If there's nothing to read if (archivo.gcount() == 0) break; // Transform every bit for (int k = 8; k > 0; k--) cadenabits.push(static_cast<int>((byte >> (k - 1)) & 1)); } std::queue<byte_t> pixeles{}; NodoCodificacion<byte_t> *actual = arbol->raiz; std::vector<CodigoElemento<byte_t>> codigos = arbol->codigos_elementos(); int total_leer = 0; for (auto cod : codigos) total_leer += cod.codigo.size() * cod.frecuencia; for (int leidos = 0; leidos <= total_leer;) { // Si es una hoja if (typeid(*actual) == typeid(NodoElemento<byte_t>)) { pixeles.push(dynamic_cast<NodoElemento<byte_t> *>(actual)->dato); actual = arbol->raiz; } else { // Si es 1 int bit = cadenabits.front(); if (bit == 1) actual = dynamic_cast<NodoFrecuencia<byte_t> *>(actual)->hijoDer; // Si es 0 else if (bit == 0) actual = dynamic_cast<NodoFrecuencia<byte_t> *>(actual)->hijoIzq; cadenabits.pop(); leidos++; } } // Pasar los datos a la imagen Imagen::matriz_t matriz = Imagen::matriz_vacia(this->ancho, this->alto); for (int i = 0; i < this->alto; i++) for (int j = 0; j < this->ancho; j++) { matriz[i][j] = pixeles.front(); pixeles.pop(); } Imagen imgp{matriz}; imgp.set_max_tam(static_cast<int>(this->maximo)); imgp.set_nombre_archivo(salida); imgp.guardar_archivo(salida); //* Cerrar archivos archivo.close(); } Huffman::~Huffman() { if (this->arbol != nullptr) { delete arbol; arbol = nullptr; } } void Huffman::guardar_archivo(std::string nombre_archivo) { //* Abrir el archivo std::ofstream archivo(nombre_archivo, std::ios::binary | std::ios::out); #ifdef _DEBUG_ std::ofstream debugf(nombre_archivo + ".debug.txt", std::ios::out); #endif // Verificar que se pudo abrir if (!archivo.is_open()) throw std::runtime_error("No se pudo abrir el archivo"); //* Header archivo.write((char *)(&this->ancho), sizeof(word_t)); archivo.write((char *)(&this->alto), sizeof(word_t)); archivo.write((char *)(&this->maximo), sizeof(byte_t)); #ifdef _DEBUG_ debugf << "# HEADER #\n"; debugf << "WIDTH\t" << (int)this->ancho << '\t' << "WORD (2)" << '\n'; debugf << "HEIGHT\t" << (int)this->alto << '\t' << "WORD (2)" << '\n'; debugf << "VALMAX\t" << (int)this->maximo << '\t' << "BYTE (1)" << '\n'; debugf << "# FREQ TABLE #\n"; #endif //* Frecuencias // Escribir todas las frecuencias for (byte_t i = 0; i < 255; i++) { if (!codigos.count(i)) codigos[i] = CodigoElemento<byte_t>{i, 0, ""}; // Write binary archivo.write((char *)&codigos[i].frecuencia, sizeof(lword_t)); #ifdef _DEBUG_ debugf << static_cast<int>(codigos[i].elemento) << "\tBYTE (1)\t" << codigos[i].frecuencia << "\t\tDWORD (4)\t" << codigos[i].codigo << "\t\t\t\t BITS(" << codigos[i].codigo.size() << ")\n"; #endif } //* Calcular codigo general std::stringstream generalss; Imagen::matriz_t pixels = imagen->get_pixeles(); // Tomar todos los elementos de la imagen y colocarlos en codigo for (int i = 0; i < imagen->get_alto(); i++) for (int j = 0; j < imagen->get_ancho(); j++) generalss << codigos[pixels[i][j]].codigo; const std::string general = generalss.str(); #ifdef _DEBUG_ debugf << "# CODE #\n" << general << "\n# END #"; #endif //* Transformar a bytes for (int i = 0; i < general.size();) { byte_t byte = 0x0000; // Transform every bit for (int k = 8; k > 0; k--, i++) { if (i >= general.size()) break; if (general.at(i) == '1') (byte |= (1 << (k - 1))); } // Escribir el bit archivo.write((char *)&byte, sizeof(byte_t)); } //* Cerrar archivos archivo.close(); #ifdef _DEBUG_ debugf.close(); #endif }
31.081448
78
0.579706
taleroangel
3d85a65106b3b1cbf38d423250ae88c711eb6ae9
22,475
cpp
C++
Blizzlike/ArcEmu/C++/Battlegrounds/StrandOfTheAncient.cpp
499453466/Lua-Other
43fd2b72405faf3f2074fd2a2706ef115d16faa6
[ "Unlicense" ]
2
2015-06-23T16:26:32.000Z
2019-06-27T07:45:59.000Z
Blizzlike/ArcEmu/C++/Battlegrounds/StrandOfTheAncient.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
null
null
null
Blizzlike/ArcEmu/C++/Battlegrounds/StrandOfTheAncient.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
3
2015-01-10T18:22:59.000Z
2021-04-27T21:28:28.000Z
/* * ArcEmu MMORPG Server * Copyright (C) 2008-2011 <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /*********************************************************************** Strand of the Ancients ====================== * Other Game Objects * Defender's Portal, 190763 * Defender's Portal, 191575 * Defender's Portal, 192819 -gps at: -gps to: * Titan Relic, 194083 (different one, not supported atm) * Collision PC Size, 188215 * The Coffin Carrier, 193184 * The Blightbringer, 193183 * The Frostbreaker, 193185 * The Graceful Maiden (boat?), 193182 * Doodad_WG_Keep_Door01_collision01, 194162 (Not implemented atm) * Revive everyone after round one * bg->EventResurrectPlayers() * Setup index 34 in worldstring_tables to equal "Strand of the Ancients" * Fix level requirements to join the battleground. And fix which npc text is used for the battlemaster gossip scripts, displaying the proper of 3 messages npc_text 13832 = You are not yet strong enough to do battle in the Strand of the Ancients. Return when you have gained more experience. 13834 = We cannot allow the Alliance to turn the hidden secrets of the Strand of the Ancients against us. Will you join our brave warriors there? +13833 = We cannot allow the Horde to turn the hidden secrets of the Strand of the Ancients against us. Will you join our brave warriors there? * Increase the view distance on map 607 to 500 or 0 (Unlimited). See the transporter patch... Need a way to see the gates from as far away as the boats. * Besure to spawn, platforms, vehicels, and relic so only the proper faction can use them. * Fix it where a BG is instanced as soon as the first player joins, only after one faction has field their entire queue for a particular battlefield, would a new BG instance be created. It might actually be this way, if so just patch so that these pre-loaded instances appear in the battlemaster lists. * Also change so numbers are reused, once SOTA instance 1 is deleted, there is no reason why that instance id can't be reused. Also each BG needs it own unique numbering, instead of a shared pool. ************************************************************************/ #include "StdAfx.h" #include "StrandOfTheAncient.h" #define GO_RELIC 192834 const float sotaTitanRelic[4] = { 836.5f, -108.8f, 111.59f, 0.0f }; const uint32 GateGOIds[6] = { 190722, // Gate of the Green Emerald 190727, // Gate of the Yellow Moon 190724, // Gate of the Blue Sapphire 190726, // Gate of the Red Sun 190723, // Gate of the Purple Amethyst 192549, // Chamber of Ancient Relics }; const float sotaGates[GATE_COUNT][4] = { { 1411.57f, 108.163f, 28.692f, 5.441f }, { 1055.452f, -108.1f, 82.134f, 0.034f }, { 1431.3413f, -219.437f, 30.893f, 0.9736f }, { 1227.667f, -212.555f, 55.372f, 0.5023f }, { 1214.681f, 81.21f, 53.413f, 5.745f }, }; const float sotaChamberGate[4] = { 878.555f, -108.989f, 119.835f, 0.0565f }; // Things radiating out from the gates... same orientation as door. const uint32 GateSigilGOIds[5] = { 192687, 192685, 192689, 192690, 192691, }; const float sotaGateSigils[GATE_COUNT][4] = { { 1414.054f, 106.72f, 41.442f, 5.441f }, { 1060.63f, -107.8f, 94.7f, 0.034f }, { 1433.383f, -216.4f, 43.642f, 0.9736f }, { 1230.75f, -210.724f, 67.611f, 0.5023f }, { 1217.8f, 79.532f, 66.58f, 5.745f }, }; // Defender transporter platform locations const float sotaTransporters[GATE_COUNT][4] = { { 1394.0444f, 72.586f, 31.0535f, 0.0f }, { 1065.0f, -89.7f, 81.08f, 0.0f }, { 1467.95f, -225.67f, 30.9f, 0.0f }, { 1255.93f, -233.382f, 56.44f, 0.0f }, { 1215.679f, 47.47f, 54.281f, 0.0f }, }; // Defender transporter destination locations const float sotaTransporterDestination[GATE_COUNT][4] = { { 1388.94f, 103.067f, 34.49f, 5.4571f }, { 1043.69f, -87.95f, 87.12f, 0.003f }, { 1441.0411f, -240.974f, 35.264f, 0.949f }, { 1228.342f, -235.234f, 60.03f, 0.4584f }, { 1193.857f, 69.9f, 58.046f, 5.7245f }, }; // Two guns per gate, GUN_LEFT and GUN_RIGHT static LocationVector CanonLocations[ SOTA_NUM_CANONS ] = { LocationVector( 1436.429f, 110.05f, 41.407f, 5.4f ), LocationVector( 1404.9023f, 84.758f, 41.183f, 5.46f ), LocationVector( 1068.693f, -86.951f, 93.81f, 0.02f ), LocationVector( 1068.83f, -127.56f, 96.45f, 0.0912f ), LocationVector( 1422.115f, -196.433f, 42.1825f, 1.0222f ), LocationVector( 1454.887f, -220.454f, 41.956f, 0.9627f ), LocationVector( 1232.345f, -187.517f, 66.945f, 0.45f ), LocationVector( 1249.634f, -224.189f, 66.72f, 0.635f ), LocationVector( 1236.213f, 92.287f, 64.965f, 5.751f ), LocationVector( 1215.11f, 57.772f, 64.739f, 5.78f ) }; static LocationVector DemolisherLocations[ SOTA_NUM_DEMOLISHERS ] = { LocationVector( 1620.71f, 64.04f, 7.19f, 3.78f ), LocationVector( 1593.59f, 40.8f, 7.52f, 0.86f ), LocationVector( 1582.42f, -93.75f, 8.49f, 5.7f ), LocationVector( 1611.19f, -117.4f, 8.77f, 2.55f ), LocationVector( 1353.34f, 224.01f, 35.24f, 4.236f ), LocationVector( 1371.03f, -317.06f, 35.01f, 1.85f ) }; // ---- Verify remaining ----- // // There should only be two boats. boats three and four here // are a lazy hack for not wanting to program the boats to move via waypoints const float sotaBoats[4][4] = { { 1623.34f, 37.0f, 1.0f, 3.65f }, { 2439.4f, 845.38f, 1.0f, 3.35f }, { 1623.34f, 37.0f, 1.0f, 3.65f }, { 2439.4f, 845.38f, 1.0f, 3.35f }, }; static LocationVector sotaAttackerStartingPosition[ SOTA_NUM_ROUND_STAGES ] = { LocationVector( 2445.288f, 849.35f, 10.0f, 3.76f ), LocationVector( 1624.7f, 42.93f, 10.0f, 2.63f ) }; static LocationVector sotaDefenderStartingPosition = LocationVector( 1209.7f, -65.16f, 70.1f, 0.0f ); static LocationVector FlagPolePositions[ NUM_SOTA_CONTROL_POINTS ] = { LocationVector( 1338.863892f, -153.336533f, 30.895121f, -2.530723f ), LocationVector( 1309.124268f, 9.410645f, 30.893402f, -1.623156f ), LocationVector( 1215.114258f, -65.711861f, 70.084267f, -3.124123f ) }; static LocationVector FlagPositions[ NUM_SOTA_CONTROL_POINTS ] = { LocationVector( 1338.859253f, -153.327316f, 30.895077f, -2.530723f ), LocationVector( 1309.192017f, 9.416233f, 30.893402f, 1.518436f ), LocationVector( 1215.108032f, -65.715767f, 70.084267f, -3.124123f ) }; static const uint32 FlagIDs[ NUM_SOTA_CONTROL_POINTS ][ MAX_PLAYER_TEAMS ] = { { 191306, 191305 }, { 191308, 191307 }, { 191310, 191309 } }; static const uint32 CPWorldstates[ NUM_SOTA_CONTROL_POINTS ][ MAX_PLAYER_TEAMS ] = { { WORLDSTATE_SOTA_GY_E_A, WORLDSTATE_SOTA_GY_E_H }, { WORLDSTATE_SOTA_GY_W_A, WORLDSTATE_SOTA_GY_W_H }, { WORLDSTATE_SOTA_GY_S_A, WORLDSTATE_SOTA_GY_S_H } }; static const uint32 SOTA_FLAGPOLE_ID = 191311; const char* ControlPointNames[ NUM_SOTA_CONTROL_POINTS ] = { "East Graveyard", "West Graveyard", "South Graveyard" }; static LocationVector GraveyardLocations[ NUM_SOTA_GRAVEYARDS ] = { LocationVector( 1396.06018066f, -288.036895752f, 32.0815124512f, 0.0f ), LocationVector( 1388.80358887f, 203.354873657f, 32.1526679993f, 0.0f ), LocationVector( 1122.27844238f, 4.41617822647f, 68.9358291626f, 0.0f ), LocationVector( 964.595275879f, -189.784011841f, 90.6604995728f, 0.0f ), LocationVector( 1457.19372559f, -53.7132720947f, 5.18109416962f, 0.0f ), }; static const uint32 TeamFactions[ MAX_PLAYER_TEAMS ] = { 1, 2 }; StrandOfTheAncient::StrandOfTheAncient( MapMgr* mgr, uint32 id, uint32 lgroup, uint32 t ) : CBattleground( mgr, id, lgroup, t ){ m_zoneid = 4384; std::fill( &canon[ 0 ], &canon[ SOTA_NUM_CANONS ], reinterpret_cast< Creature* >( NULL ) ); std::fill( &demolisher[ 0 ], &demolisher[ SOTA_NUM_DEMOLISHERS ], reinterpret_cast< Creature* >( NULL ) ); } StrandOfTheAncient::~StrandOfTheAncient(){ std::fill( &canon[ 0 ], &canon[ SOTA_NUM_CANONS ], reinterpret_cast< Creature* >( NULL ) ); std::fill( &demolisher[ 0 ], &demolisher[ SOTA_NUM_DEMOLISHERS ], reinterpret_cast< Creature* >( NULL ) ); } void StrandOfTheAncient::HookOnAreaTrigger(Player* plr, uint32 id) { } void StrandOfTheAncient::HookOnPlayerKill(Player* plr, Player* pVictim) { plr->m_bgScore.KillingBlows++; UpdatePvPData(); } void StrandOfTheAncient::HookOnHK(Player* plr) { plr->m_bgScore.HonorableKills++; UpdatePvPData(); } void StrandOfTheAncient::OnPlatformTeleport(Player* plr) { } void StrandOfTheAncient::OnAddPlayer(Player* plr) { if(!m_started) plr->CastSpell(plr, BG_PREPARATION, true); } void StrandOfTheAncient::OnRemovePlayer(Player* plr) { if(!m_started) plr->RemoveAura(BG_PREPARATION); } LocationVector StrandOfTheAncient::GetStartingCoords( uint32 team ){ if( team == Attackers ) return sotaAttackerStartingPosition[ roundprogress ]; else return sotaDefenderStartingPosition; } void StrandOfTheAncient::HookOnPlayerDeath(Player* plr) { plr->m_bgScore.Deaths++; UpdatePvPData(); } void StrandOfTheAncient::HookOnMount(Player* plr) { /* Allowed */ } bool StrandOfTheAncient::HookHandleRepop( Player *plr ){ float dist = 999999.0f; LocationVector dest_pos; uint32 id = 0; // Let's find the closests GY for( uint32 i = SOTA_GY_EAST; i < NUM_SOTA_GRAVEYARDS; i++ ){ if( graveyard[ i ].faction == plr->GetTeam() ){ if( graveyard[ i ].spiritguide == NULL ) continue; float gydist = plr->CalcDistance( graveyard[ i ].spiritguide ); if( gydist > dist ) continue; dist = gydist; dest_pos = graveyard[ i ].spiritguide->GetPosition(); id = i; } } if( id >= NUM_SOTA_GRAVEYARDS ) return false; // port to it and queue for auto-resurrect plr->SafeTeleport( plr->GetMapId(), plr->GetInstanceID(), dest_pos ); QueuePlayerForResurrect( plr, graveyard[ id ].spiritguide ); return true; } void StrandOfTheAncient::OnCreate() { { uint32 i; BattleRound = 1; roundprogress = SOTA_ROUND_PREPARATION; for(i = 0; i < 2; i++) { m_players[i].clear(); m_pendPlayers[i].clear(); RoundFinishTime[ i ] = 10 * 60; } m_pvpData.clear(); m_resurrectMap.clear(); // Boats for(i = 0; i < 4; i++) { m_boats[i] = m_mapMgr->CreateAndSpawnGameObject(20808, sotaBoats[i][0], sotaBoats[i][1], sotaBoats[i][2], sotaBoats[i][3], 1.0f); m_boats[i]->PushToWorld( m_mapMgr ); } /* Relic */ m_relic = m_mapMgr->CreateAndSpawnGameObject(GO_RELIC, sotaTitanRelic[0], sotaTitanRelic[1], sotaTitanRelic[2], sotaTitanRelic[3], 1.0f); for(i = 0; i < GATE_COUNT; i++) { m_gates[i] = m_mapMgr->CreateAndSpawnGameObject(GateGOIds[i], sotaGates[i][0], sotaGates[i][1], sotaGates[i][2], sotaGates[i][3], 1.0f); m_gateSigils[i] = m_mapMgr->CreateAndSpawnGameObject(GateSigilGOIds[i], sotaGateSigils[i][0], sotaGateSigils[i][1], sotaGateSigils[i][2], sotaGateSigils[i][3], 1.0f); m_gateTransporters[i] = m_mapMgr->CreateAndSpawnGameObject(192819, sotaTransporters[i][0], sotaTransporters[i][1], sotaTransporters[i][2], sotaTransporters[i][3], 1.0f); } // Spawn door for Chamber of Ancient Relics m_endgate = m_mapMgr->CreateAndSpawnGameObject(GateGOIds[i], sotaChamberGate[0], sotaChamberGate[1], sotaChamberGate[2], sotaChamberGate[3], 1.0f); } PrepareRound(); } void StrandOfTheAncient::OnStart(){ m_started = true; StartRound(); } void StrandOfTheAncient::HookGenerateLoot(Player* plr, Object* pOCorpse) { LOG_DEBUG("*** StrandOfTheAncient::HookGenerateLoot"); } void StrandOfTheAncient::HookOnUnitKill( Player* plr, Unit* pVictim ){ } void StrandOfTheAncient::HookOnUnitDied( Unit *victim ){ if( victim->IsCreature() ){ for( uint32 i = 0; i < SOTA_NUM_DEMOLISHERS; i++ ){ Creature *c = demolisher[ i ]; if( c == NULL ) continue; if( victim->GetGUID() != c->GetGUID() ) continue; demolisher[ i ] = SpawnCreature( 28781, DemolisherLocations[ i ], TeamFactions[ Attackers ] ); c->Despawn( 1, 0 ); } for( uint32 i = 0; i < SOTA_NUM_CANONS; i++ ){ if( canon[ i ] == NULL ) continue; if( victim->GetGUID() != canon[ i ]->GetGUID() ) continue; canon[ i ]->Despawn( 1, 0 ); canon[ i ] = NULL; } } } void StrandOfTheAncient::SetIsWeekend(bool isweekend) { LOG_DEBUG("*** StrandOfTheAncient::SetIsWeekend"); m_isWeekend = isweekend; } bool StrandOfTheAncient::HookSlowLockOpen( GameObject *go, Player *player, Spell *spell ){ uint32 goentry = go->GetEntry(); switch( goentry ){ case 191305: case 191306: CaptureControlPoint( SOTA_CONTROL_POINT_EAST_GY ); return true; break; case 191307: case 191308: CaptureControlPoint( SOTA_CONTROL_POINT_WEST_GY ); return true; break; case 191309: case 191310: CaptureControlPoint( SOTA_CONTROL_POINT_SOUTH_GY ); return true; break; } return true; } bool StrandOfTheAncient::HookQuickLockOpen( GameObject *go, Player *player, Spell *spell ){ uint32 entry = go->GetEntry(); if( entry == GO_RELIC ) FinishRound(); return true; } // For banners void StrandOfTheAncient::HookFlagStand(Player* plr, GameObject* obj) { } // time in seconds void StrandOfTheAncient::SetTime( uint32 secs ){ uint32 minutes = secs / TIME_MINUTE; uint32 seconds = secs % TIME_MINUTE; uint32 digits[3]; digits[0] = minutes; digits[1] = seconds / 10; digits[2] = seconds % 10; SetWorldState(WORLDSTATE_SOTA_TIMER_1, digits[0]); SetWorldState(WORLDSTATE_SOTA_TIMER_2, digits[1]); SetWorldState(WORLDSTATE_SOTA_TIMER_3, digits[2]); SetRoundTime(secs); } void StrandOfTheAncient::PrepareRound(){ roundprogress = SOTA_ROUND_PREPARATION; if( BattleRound == 1 ){ Attackers = RandomUInt( 1 ); if( Attackers == TEAM_ALLIANCE ) Defenders = TEAM_HORDE; else Defenders = TEAM_ALLIANCE; }else{ std::swap( Attackers, Defenders ); } for( uint32 i = 0; i < GATE_COUNT; i++ ){ m_gates[ i ]->Rebuild(); m_gates[ i ]->SetFaction( TeamFactions[ Defenders ] ); } m_endgate->Rebuild(); m_endgate->SetFaction( TeamFactions[ Defenders ] ); m_relic->SetFaction( TeamFactions[ Attackers ] ); for( uint32 i = 0; i < GATE_COUNT; i++ ) m_gateTransporters[ i ]->SetFaction( TeamFactions[ Defenders ] ); for( uint32 i = 0; i < SOTA_NUM_CANONS; i++ ){ if( canon[ i ] != NULL ) canon[ i ]->Despawn( 0, 0 ); canon[ i ] = SpawnCreature( 27894, CanonLocations[ i ], TeamFactions[ Defenders ] ); } for( uint32 i = 0; i < SOTA_NUM_DOCK_DEMOLISHERS; i++ ){ Creature *c = demolisher[ i ]; demolisher[ i ] = SpawnCreature( 28781, DemolisherLocations[ i ], TeamFactions[ Attackers ] ); if( c != NULL ) c->Despawn( 0, 0 ); } for( uint32 i = SOTA_WEST_WS_DEMOLISHER_INDEX; i < SOTA_NUM_DEMOLISHERS; i++ ){ if( demolisher[ i ] != NULL ){ demolisher[ i ]->Despawn( 0, 0 ); demolisher[ i ] = NULL; } } SOTACPStates state; if( Attackers == TEAM_ALLIANCE ){ state = SOTA_CP_STATE_HORDE_CONTROL; SetWorldState( WORLDSTATE_SOTA_HORDE_ATTACKER, 0 ); SetWorldState( WORLDSTATE_SOTA_ALLIANCE_ATTACKER, 1 ); SetWorldState( WORLDSTATE_SOTA_SHOW_ALLY_ROUND, 1 ); SetWorldState( WORLDSTATE_SOTA_SHOW_HORDE_ROUND, 0 ); SetWorldState( WORLDSTATE_SOTA_SHOW_ALLY_DEFENSE, 0 ); SetWorldState( WORLDSTATE_SOTA_SHOW_HORDE_DEFENSE, 1 ); SetWorldState( WORLDSTATE_SOTA_SHOW_ALLY_BEACHHEAD1, 1 ); SetWorldState( WORLDSTATE_SOTA_SHOW_ALLY_BEACHHEAD2, 1 ); SetWorldState( WORLDSTATE_SOTA_SHOW_HORDE_BEACHHEAD1, 0 ); SetWorldState( WORLDSTATE_SOTA_SHOW_HORDE_BEACHHEAD2, 0 ); }else{ state = SOTA_CP_STATE_ALLY_CONTROL; SetWorldState( WORLDSTATE_SOTA_HORDE_ATTACKER, 1 ); SetWorldState( WORLDSTATE_SOTA_ALLIANCE_ATTACKER, 0 ); SetWorldState( WORLDSTATE_SOTA_SHOW_ALLY_ROUND, 0 ); SetWorldState( WORLDSTATE_SOTA_SHOW_HORDE_ROUND, 1 ); SetWorldState( WORLDSTATE_SOTA_SHOW_ALLY_DEFENSE, 1 ); SetWorldState( WORLDSTATE_SOTA_SHOW_HORDE_DEFENSE, 0 ); SetWorldState( WORLDSTATE_SOTA_SHOW_ALLY_BEACHHEAD1, 0 ); SetWorldState( WORLDSTATE_SOTA_SHOW_ALLY_BEACHHEAD2, 0 ); SetWorldState( WORLDSTATE_SOTA_SHOW_HORDE_BEACHHEAD1, 1 ); SetWorldState( WORLDSTATE_SOTA_SHOW_HORDE_BEACHHEAD2, 1 ); } SpawnControlPoint( SOTA_CONTROL_POINT_EAST_GY, state ); SpawnControlPoint( SOTA_CONTROL_POINT_WEST_GY, state ); SpawnControlPoint( SOTA_CONTROL_POINT_SOUTH_GY, state ); SpawnGraveyard( SOTA_GY_ATTACKER_BEACH, Attackers ); SpawnGraveyard( SOTA_GY_DEFENDER, Defenders ); if( BattleRound == 2 ){ // Teleport players to their place and cast preparation on them m_mainLock.Acquire(); for( std::set< Player* >::iterator itr = m_players[ Attackers ].begin(); itr != m_players[ Attackers ].end(); ++itr ){ Player *p = *itr; p->SafeTeleport( p->GetMapId(), p->GetInstanceID(), sotaAttackerStartingPosition[ 0 ] ); p->CastSpell( p, BG_PREPARATION, true ); } for( std::set< Player* >::iterator itr = m_players[ Defenders ].begin(); itr != m_players[ Defenders ].end(); ++itr ){ Player *p = *itr; p->SafeTeleport( p->GetMapId(), p->GetInstanceID(), sotaDefenderStartingPosition ); p->CastSpell( p, BG_PREPARATION, true ); } m_mainLock.Release(); sEventMgr.AddEvent( this, &StrandOfTheAncient::StartRound, EVENT_SOTA_START_ROUND, 1 * 10 * 1000, 1, 0 ); } }; void StrandOfTheAncient::StartRound(){ roundprogress = SOTA_ROUND_STARTED; m_mainLock.Acquire(); for( std::set< Player* >::iterator itr = m_players[ Attackers ].begin(); itr != m_players[ Attackers ].end(); itr++ ){ Player *p = *itr; p->SafeTeleport( p->GetMapId(), p->GetInstanceID(), sotaAttackerStartingPosition[ SOTA_ROUND_STARTED ] ); p->RemoveAura( BG_PREPARATION ); } m_mainLock.Release(); RemoveAuraFromTeam( Defenders, BG_PREPARATION ); SetWorldState( WORLDSTATE_SOTA_TIMER_1, 10 ); SetTime( ROUND_LENGTH ); sEventMgr.AddEvent( this, &StrandOfTheAncient::TimeTick, EVENT_SOTA_TIMER, MSTIME_SECOND * 5, 0, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT ); UpdatePvPData(); } void StrandOfTheAncient::FinishRound(){ sEventMgr.RemoveEvents( this, EVENT_SOTA_TIMER ); EventResurrectPlayers(); RoundFinishTime[ BattleRound - 1 ] = RoundTime; if( BattleRound == 1 ){ BattleRound = 2; PrepareRound(); }else{ if( RoundFinishTime[ 0 ] < RoundFinishTime[ 1 ] ) Finish( Attackers ); else Finish( Defenders ); } } void StrandOfTheAncient::Finish( uint32 winningteam ){ sEventMgr.RemoveEvents( this ); m_ended = true; m_winningteam = winningteam; uint32 losingteam; if( winningteam == TEAM_ALLIANCE ) losingteam = TEAM_HORDE; else losingteam = TEAM_ALLIANCE; AddHonorToTeam( winningteam, 3 * 185 ); AddHonorToTeam( losingteam, 1 * 185 ); CastSpellOnTeam( m_winningteam, 61213 ); UpdatePvPData(); sEventMgr.AddEvent( TO< CBattleground* >( this ), &CBattleground::Close, EVENT_BATTLEGROUND_CLOSE, 120 * 1000, 1,0 ); } void StrandOfTheAncient::TimeTick(){ SetTime( RoundTime - 5 ); if( RoundTime == 0){ sEventMgr.RemoveEvents(this, EVENT_SOTA_TIMER); FinishRound(); } }; // Not used? void StrandOfTheAncient::HookOnFlagDrop(Player* plr) { } void StrandOfTheAncient::HookFlagDrop(Player* plr, GameObject* obj) { } void StrandOfTheAncient::HookOnShadowSight() { } void StrandOfTheAncient::SpawnControlPoint( SOTAControlPoints point, SOTACPStates state ){ if( state >= MAX_SOTA_CP_STATES ) return; SOTAControlPoint &cp = controlpoint[ point ]; if( cp.worldstate != 0 ) SetWorldState( cp.worldstate, 0 ); uint32 team = TEAM_ALLIANCE; uint32 faction = 0; switch( state ){ case SOTA_CP_STATE_ALLY_CONTROL: team = TEAM_ALLIANCE; faction = 2; break; case SOTA_CP_STATE_HORDE_CONTROL: team = TEAM_HORDE; faction = 1; break; default: return; break; } // First time spawning if( cp.pole == NULL ){ cp.pole = SpawnGameObject( SOTA_FLAGPOLE_ID, FlagPolePositions[ point ], 0, 35, 1.0f ); cp.pole->PushToWorld( m_mapMgr ); }else{ Arcemu::Util::ArcemuAssert( cp.banner != NULL ); cp.banner->Despawn( 0, 0 ); } cp.banner = SpawnGameObject( FlagIDs[ point ][ team ], FlagPositions[ point ], 0, faction, 1.0f ); cp.banner->PushToWorld( m_mapMgr ); cp.state = state; cp.worldstate = CPWorldstates[ point ][ team ]; SetWorldState( cp.worldstate, 1 ); //Spawn graveyard SpawnGraveyard( SOTAGraveyards( uint32( point ) ), team ); } void StrandOfTheAncient::CaptureControlPoint( SOTAControlPoints point ){ if( point >= NUM_SOTA_CONTROL_POINTS ) return; SOTAControlPoint &cp = controlpoint[ point ]; if( cp.banner->GetFaction() == 14 ) return; switch( cp.state ){ case SOTA_CP_STATE_ALLY_CONTROL: SpawnControlPoint( point, SOTA_CP_STATE_HORDE_CONTROL ); PlaySoundToAll( SOUND_HORDE_CAPTURE ); SendChatMessage( CHAT_MSG_BG_EVENT_HORDE, 0, "The horde has captured the %s!", ControlPointNames[ point ] ); break; case SOTA_CP_STATE_HORDE_CONTROL: SpawnControlPoint( point, SOTA_CP_STATE_ALLY_CONTROL ); PlaySoundToAll( SOUND_ALLIANCE_CAPTURE ); SendChatMessage( CHAT_MSG_BG_EVENT_ALLIANCE, 0, "The alliance has captured the %s!", ControlPointNames[ point ] ); break; } cp.banner->SetFaction( 14 ); // So they cannot be recaptured as per SOTA rules //Spawn workshop demolisher switch( point ){ case SOTA_CONTROL_POINT_EAST_GY: demolisher[ SOTA_EAST_WS_DEMOLISHER_INDEX ] = SpawnCreature( 28781, DemolisherLocations[ SOTA_EAST_WS_DEMOLISHER_INDEX ], TeamFactions[ Attackers ] ); break; case SOTA_CONTROL_POINT_WEST_GY: demolisher[ SOTA_WEST_WS_DEMOLISHER_INDEX ] = SpawnCreature( 28781, DemolisherLocations[ SOTA_WEST_WS_DEMOLISHER_INDEX ], TeamFactions[ Attackers ] ); break; } } void StrandOfTheAncient::SpawnGraveyard( SOTAGraveyards gyid, uint32 team ){ if( gyid >= NUM_SOTA_GRAVEYARDS ) return; SOTAGraveyard &gy = graveyard[ gyid ]; gy.faction = team; if( gy.spiritguide != NULL ) gy.spiritguide->Despawn( 0, 0 ); gy.spiritguide = SpawnSpiritGuide( GraveyardLocations[ gyid ], team ); AddSpiritGuide( gy.spiritguide ); }
30.127346
153
0.703671
499453466
3d863b82983aeee62a5aacb13b2ba80e00c330b0
2,932
cc
C++
tests/test_routing_table2.cc
telosprotocol/xkad
f3591d5544bf26ba486cb4a7f141d9500422206e
[ "MIT" ]
13
2019-09-16T13:34:35.000Z
2020-01-13T08:06:17.000Z
tests/test_routing_table2.cc
telosprotocol/xkad
f3591d5544bf26ba486cb4a7f141d9500422206e
[ "MIT" ]
null
null
null
tests/test_routing_table2.cc
telosprotocol/xkad
f3591d5544bf26ba486cb4a7f141d9500422206e
[ "MIT" ]
null
null
null
// Copyright (c) 2017-2019 Telos Foundation & contributors // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <stdio.h> #include <string.h> #include <string> #include <memory> #include <fstream> #include <gtest/gtest.h> #include "xpbase/base/top_utils.h" #include "xpbase/base/top_timer.h" #include "xpbase/base/line_parser.h" #include "xpbase/base/kad_key/platform_kadmlia_key.h" #include "xtransport/udp_transport/udp_transport.h" #include "xtransport/src/message_manager.h" #include "node_mgr.h" namespace top { namespace kadmlia { namespace test { class TestRoutingTable2 : public testing::Test { public: static void SetUpTestCase() { mgr1_ = std::make_shared<NodeMgr>(); ASSERT_TRUE(mgr1_->Init(true, "1")); } static void TearDownTestCase() { mgr1_ = nullptr; } virtual void SetUp() {} virtual void TearDown() {} protected: static std::shared_ptr<NodeMgr> mgr1_; }; std::shared_ptr<NodeMgr> TestRoutingTable2::mgr1_; TEST_F(TestRoutingTable2, NatDetect) { auto mgr2 = std::make_shared<NodeMgr>(); ASSERT_TRUE(mgr2->Init(false, "2")); ASSERT_TRUE(mgr2->NatDetect(mgr1_->LocalIp(), mgr1_->RealLocalPort())); mgr2 = nullptr; } TEST_F(TestRoutingTable2, Join) { auto mgr2 = std::make_shared<NodeMgr>(); ASSERT_TRUE(mgr2->Init(false, "3")); ASSERT_TRUE(mgr2->JoinRt(mgr1_->LocalIp(), mgr1_->RealLocalPort())); mgr2 = nullptr; } // handle message TEST_F(TestRoutingTable2, kKadConnectRequest) { transport::protobuf::RoutingMessage message; message.set_type(kKadConnectRequest); base::xpacket_t packet; mgr1_->HandleMessage(message, packet); } TEST_F(TestRoutingTable2, kKadNatDetectRequest) { transport::protobuf::RoutingMessage message; message.set_type(kKadNatDetectRequest); base::xpacket_t packet; mgr1_->HandleMessage(message, packet); } TEST_F(TestRoutingTable2, kKadNatDetectResponse) { transport::protobuf::RoutingMessage message; message.set_type(kKadNatDetectResponse); base::xpacket_t packet; mgr1_->HandleMessage(message, packet); } TEST_F(TestRoutingTable2, kKadNatDetectHandshake2Node) { transport::protobuf::RoutingMessage message; message.set_type(kKadNatDetectHandshake2Node); base::xpacket_t packet; mgr1_->HandleMessage(message, packet); } TEST_F(TestRoutingTable2, kKadNatDetectHandshake2Boot) { transport::protobuf::RoutingMessage message; message.set_type(kKadNatDetectHandshake2Boot); base::xpacket_t packet; mgr1_->HandleMessage(message, packet); } TEST_F(TestRoutingTable2, kKadNatDetectFinish) { transport::protobuf::RoutingMessage message; message.set_type(kKadNatDetectFinish); base::xpacket_t packet; mgr1_->HandleMessage(message, packet); } } // namespace test } // namespace kadmlia } // namespace top
27.401869
75
0.731924
telosprotocol
3d87c5e1fe983ea58070d1ad289737234e5e097d
2,452
cpp
C++
src/datastructures/LinkedList.cpp
tkaleas/cpp-sandbox
9501619421edc8ced6023ab6b83908c43b26f134
[ "MIT" ]
1
2019-12-13T03:39:57.000Z
2019-12-13T03:39:57.000Z
src/datastructures/LinkedList.cpp
tkaleas/cpp-sandbox
9501619421edc8ced6023ab6b83908c43b26f134
[ "MIT" ]
null
null
null
src/datastructures/LinkedList.cpp
tkaleas/cpp-sandbox
9501619421edc8ced6023ab6b83908c43b26f134
[ "MIT" ]
null
null
null
#include "LinkedList.h" #include <sstream> SinglyLinkedList::SinglyLinkedList() : head(nullptr) { } SinglyLinkedList::SinglyLinkedList(int startValue): head(new ListNode(startValue)) { } SinglyLinkedList::~SinglyLinkedList() { this->clearList(); delete head; } void SinglyLinkedList::clearList() { } int SinglyLinkedList::getFirst() { if (head != nullptr) { return head->data; } } int SinglyLinkedList::getValue(size_t position) { int k = 0; ListNode* curr = head; while (k < position && curr->next != nullptr) { k++; curr = curr->next; }; return curr->data; } string SinglyLinkedList::toString() const{ //Traverse List and Format to String std::stringstream ss; ListNode *c = head; ss << "["; while (c != nullptr) { ss << c->data; if(c->next) ss << ", "; c = c->next; } ss << "]"; return ss.str(); } void SinglyLinkedList::insertIntoList(size_t position, int value) { int k = 0; ListNode* curr = this->head; ListNode* prev = nullptr; //Insert at beginning if no other items or inserting at position 0 if (curr == nullptr || position == 0) { ListNode* temp = curr; this->head = new ListNode(value); this->head->next = temp; return; } while (k < position && curr != nullptr) { k++; prev = curr; curr = curr->next; } //Insert At Position (including back) if (curr != nullptr) { ListNode* newNode = new ListNode(value); ListNode* temp = curr; prev->next = newNode; newNode->next = temp; } //Insert at End else { ListNode* newNode = new ListNode(value); prev->next = newNode; } } void SinglyLinkedList::deleteFromList(size_t position) { //Delete Head if (position == 0){ if (this->head == nullptr || this->head->next == nullptr) { delete this->head; this->head = nullptr; } else { ListNode* temp = this->head->next; delete this->head; this->head = temp; } return; } int k = 0; ListNode* curr = this->head; ListNode* prev = nullptr; while (k < position && curr->next != nullptr) { k++; prev = curr; curr = curr->next; } //Delete Middle (or back if correct position) if (curr->next != nullptr) { //delete curr prev->next = curr->next; delete curr; } //Delete Very End else { //delete curr prev->next = nullptr; delete curr; } } void SinglyLinkedList::popFromList(size_t position) { } std::ostream & operator<<(std::ostream & os, const SinglyLinkedList &ll) { os << ll.toString(); return os; }
17.89781
74
0.633768
tkaleas
3d89f6dcde802a8916d36a1458bb44f2f1f00192
1,772
cc
C++
libinternalfield/test/test.cc
mattkjames7/libinternalfield
3b590c278b59c600a8b3d9d532e466b6a54433e1
[ "MIT" ]
null
null
null
libinternalfield/test/test.cc
mattkjames7/libinternalfield
3b590c278b59c600a8b3d9d532e466b6a54433e1
[ "MIT" ]
null
null
null
libinternalfield/test/test.cc
mattkjames7/libinternalfield
3b590c278b59c600a8b3d9d532e466b6a54433e1
[ "MIT" ]
null
null
null
#include "test.h" int main() { /* some input coordinates to test a few models with */ std::array<double,16> r = {3,3,3,3, 3,3,3,3, 3,3,3,3, 3,3,3,3}; std::array<double,16> tdeg = {10,10,10,10,55,55,55,55,90,90,90,90,130,130,130,130}; std::array<double,16> pdeg = {0,27,180,340, 0,27,180,340, 0,27,180,340, 0,27,180,340}; std::array<double,16> t; std::array<double,16> p; /* convert to radians */ int i; double deg2rad = M_PI/180.0; for (i=0;i<t.size();i++) { t[i] = deg2rad*tdeg[i]; p[i] = deg2rad*pdeg[i]; } /*output arrays */ std::array<double,16> Br; std::array<double,16> Bt; std::array<double,16> Bp; /* output strings */ const char s0[] = " R | Theta | Phi | Br | Bt | Bp \n"; const char s1[] = "-----|-------|-------|--------------------|--------------------|--------------------\n"; const char *fmt = " %3.1f | %5.1f | %5.1f | %18.11f | %18.11f | %18.11f\n"; /* set model to VIP4 */ internalModel.SetModel("vip4"); internalModel.SetCartIn(false); internalModel.SetCartOut(false); /* call model */ internalModel.Field((int) r.size(),r.data(),t.data(),p.data(),Br.data(),Bt.data(),Bp.data()); /* print output */ printf("VIP4 output...\n"); printf(s0); printf(s1); for (i=0;i<r.size();i++) { printf(fmt,r[i],tdeg[i],pdeg[i],Br[i],Bt[i],Bp[i]); } /* set model to JRM09 */ internalModel.SetModel("jrm09"); internalModel.SetCartIn(false); internalModel.SetCartOut(false); /* call model */ internalModel.Field((int) r.size(),r.data(),t.data(),p.data(),Br.data(),Bt.data(),Bp.data()); /* print output */ printf("JRM09 output...\n"); printf(s0); printf(s1); for (i=0;i<r.size();i++) { printf(fmt,r[i],tdeg[i],pdeg[i],Br[i],Bt[i],Bp[i]); } }
26.058824
109
0.549097
mattkjames7
3d8b9179a7bc8e45d7a7a15a1fa954ca8e555e82
4,822
cpp
C++
P9/BST/main.cpp
summerwish/DataStructure_homework
7ba86f69edd413643679aba3cf9da5e987b14055
[ "MIT" ]
null
null
null
P9/BST/main.cpp
summerwish/DataStructure_homework
7ba86f69edd413643679aba3cf9da5e987b14055
[ "MIT" ]
null
null
null
P9/BST/main.cpp
summerwish/DataStructure_homework
7ba86f69edd413643679aba3cf9da5e987b14055
[ "MIT" ]
null
null
null
// // main.cpp // BST // // Created by Breezewish on 11/24/14. // Copyright (c) 2014 BW. All rights reserved. // #include <iostream> #include <string> using namespace std; class Node { public: int key; int n; Node* left; Node* right; Node(int k):key(k),n(1),left(NULL),right(NULL){}; }; void insert(Node* &node, int key) { if (node == NULL) { node = new Node(key); return; } if (key < node->key) { insert(node->left, key); } else if (key > node->key) { insert(node->right, key); } else { node->n++; } } Node* find(Node* node, int key) { if (node == NULL) { return NULL; } if (key < node->key) { return find(node->left, key); } else if (key > node->key) { return find(node->right, key); } else { return node; } } void remove(Node* &node, int key) { if (node == NULL) { return; } if (key < node->key) { remove(node->left, key); } else if (key > node->key) { remove(node->right, key); } else { if (node->n > 1) { node->n--; return; } if (node->left == NULL) { Node *temp = node; node = node->right; delete temp; } else if (node->right == NULL) { Node *temp = node; node = node->left; delete temp; } else { Node *min = node->right; while (min->left != NULL) min = min->left; node->key = min->key; node->n = min->n; remove(node->right, min->key); } } } string inorder(Node* node) { string ret = ""; if (node != NULL) { ret += inorder(node->left); for (int i = 0; i < node->n; ++i) { ret += to_string(node->key); ret += " "; } ret += inorder(node->right); } return ret; } const int OP_CREATE = 1; const int OP_INSERT = 2; const int OP_SEARCH = 3; const int OP_DELETE = 4; const int OP_EXIT = 5; #include <vector> #include <sstream> #include <algorithm> #include <iterator> Node* root = NULL; int main(int argc, const char * argv[]) { cout << "Binary Search Tree Demo" << endl; cout << "1 -- Create BST" << endl; cout << "2 -- Insert element" << endl; cout << "3 -- Search element" << endl; cout << "4 -- Delete element" << endl; cout << "5 -- Exit" << endl; int operation; do { string opl; cout << endl; cout << ">> "; getline(cin, opl); operation = stoi(opl); switch (operation) { case OP_CREATE: { cout << "Input initial elements: "; string line; getline(cin, line); vector<int> elements; istringstream iss(line); copy(istream_iterator<int>(iss), istream_iterator<int>(), back_inserter(elements)); for (int i = 0; i < elements.size(); ++i) { insert(root, elements[i]); } cout << endl << "Operation done." << endl; cout << "Inorder Tree: " << inorder(root) << endl; break; } case OP_INSERT: { cout << "Input the element to insert: "; int el; cin >> el; getchar(); insert(root, el); cout << endl << "Operation done." << endl; cout << "Inorder Tree: " << inorder(root) << endl; break; } case OP_SEARCH: { cout << "Input the element to find: "; int el; cin >> el; getchar(); Node* n = find(root, el); if (n == NULL) { cout << "Cannot find element in the tree!" << endl; } else { cout << "Element found in the tree." << endl; } break; } case OP_DELETE: { cout << "Input the element to delete: "; int el; cin >> el; getchar(); remove(root, el); cout << endl << "Operation done." << endl; cout << "Inorder Tree: " << inorder(root) << endl; break; } case OP_EXIT: { break; } default: { cout << "Unknown operation." << endl; break; } } } while (operation != OP_EXIT); cout << "bye!" << endl; return 0; }
24.602041
71
0.421609
summerwish