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
b6ed6b2a9fd5ffb84efc910fb22de7b63032c805
6,033
hpp
C++
cpp-cgdk/debug_strategy.hpp
elsid/CodeWizards
6c7b5df632ec3d0a26fbf9b7f5fa8a3d5e0316ca
[ "MIT" ]
null
null
null
cpp-cgdk/debug_strategy.hpp
elsid/CodeWizards
6c7b5df632ec3d0a26fbf9b7f5fa8a3d5e0316ca
[ "MIT" ]
null
null
null
cpp-cgdk/debug_strategy.hpp
elsid/CodeWizards
6c7b5df632ec3d0a26fbf9b7f5fa8a3d5e0316ca
[ "MIT" ]
null
null
null
#pragma once #include "optimal_position.hpp" #include "base_strategy.hpp" #include "russian-ai-cup-visual/Debug.h" #ifdef ELSID_STRATEGY_DEBUG #include "debug/output.hpp" #include <iostream> #endif namespace strategy { std::int32_t get_color(double red, double green, double blue); std::int32_t get_color(double heat); class DebugStrategy : public AbstractStrategy { public: DebugStrategy(std::unique_ptr<AbstractStrategy> component, const BaseStrategy& base) : component_(std::move(component)), base_(base) {} void apply(Context& context) override final; private: struct UnitsStats { std::size_t hits_count = 0; std::size_t target_hits_count = 0; std::size_t target_casts_count = 0; std::size_t target_ticks_count = 0; }; const std::unique_ptr<AbstractStrategy> component_; const BaseStrategy& base_; Debug debug_; double max_target_score = 0; double min_target_score = 0; void visualize(const Context& context); void visualize_graph(const Context& context); void visualize_graph_path(const Context& context); void visualize_positions_penalties(const Context& context); void visualize_path(const Context& context); void visualize_destination(const Context& context); void visualize_points(const Context& context); void visualize_target(const Context& context); void visualize_units(const Context& context); void visualize_unit(const Context& context, const model::Wizard& unit); void visualize_unit(const Context& context, const model::Building& unit); void visualize_unit(const Context& context, const model::Minion& unit); void visualize_unit(const Context& context, const model::Tree& unit); void visualize_unit(const Context& context, const model::Projectile& unit); void visualize_states(const Context& context); void visualize_ticks_states(const Context& context); template <class Unit> void visualize_unit_mean_speed(const Context& context, const Unit& unit) { const auto cached_unit = get_units<Unit>(context.cache()).at(unit.getId()); const auto mean_speed = cached_unit.mean_speed(); const auto mean_speed_end = get_position(unit) + mean_speed.normalized() * (10 * mean_speed.norm() + unit.getRadius()); debug_.line(unit.getX(), unit.getY(), mean_speed_end.x(), mean_speed_end.y(), 0x0); std::ostringstream stream; stream << mean_speed.x() << ", " << mean_speed.y() << " (" << mean_speed.norm() << ')'; const auto text_position = mean_speed_end + mean_speed.normalized() * 10; debug_.text(text_position.x(), text_position.y(), stream.str().c_str(), 0x0); } template <class Unit> void visualize_unit_speed(const Unit& unit) { const auto speed = get_speed(unit); const auto speed_end = get_position(unit) + speed.normalized() * (10 * speed.norm() + unit.getRadius()); debug_.line(unit.getX(), unit.getY(), speed_end.x(), speed_end.y(), 0x990000); std::ostringstream stream; stream << speed.x() << ", " << speed.y() << " (" << speed.norm() << ')'; const auto text_position = speed_end + speed.normalized() * 10; debug_.text(text_position.x(), text_position.y(), stream.str().c_str(), 0x990000); } template <class Unit> void visualize_unit_mean_life_change_speed(const Context& context, const Unit& unit) { const auto cached_unit = get_units<Unit>(context.cache()).at(unit.getId()); const auto mean_life_change_speed = cached_unit.mean_life_change_speed(); std::int32_t color; if (mean_life_change_speed > 0) { color = get_color(0, 1, 0); } else if (mean_life_change_speed < 0) { color = get_color(1, 0, 0); } else { color = get_color(0, 0, 0); } std::ostringstream stream; stream << mean_life_change_speed; debug_.text(unit.getX() - unit.getRadius(), unit.getY() + unit.getRadius() + 10, stream.str().c_str(), color); } template <class T> void visualize_positions_penalties(const Context& context, const T* target) { const double max_distance = context.self().getVisionRange(); const GetPositionPenalty<T> get_position_penalty(context, target, get_max_distance_for_optimal_position(context)); const auto self_position = get_position(context.self()); std::vector<std::pair<Point, double>> penalties; penalties.reserve(max_distance * max_distance * 4); const int step = 2 * context.self().getRadius(); const int count = std::round(max_distance / step); const auto origin = self_position.to_int() - self_position.to_int() % step; for (int x = -count; x < count; ++x) { for (int y = -count; y < count; ++y) { const auto position = (origin + PointInt(x, y) * step).to_double(); if (0 < position.x() && position.x() < context.world().getWidth() && 0 < position.y() && position.y() < context.world().getHeight() && position.distance(self_position) <= max_distance) { penalties.emplace_back(position, get_position_penalty.get_units_danger_penalty(position)); } } } const auto min_max = std::minmax_element(penalties.begin(), penalties.end(), [] (const auto& lhs, const auto& rhs) { return lhs.second < rhs.second; }); const double min = min_max.first->second; const double max = min_max.second->second; const double norm = max_distance != min ? std::abs(max - min) : 1.0; for (const auto& v : penalties) { Point position; double penalty; std::tie(position, penalty) = v; const double normalized = (penalty - min) / norm; const auto color = get_color(normalized); debug_.fillCircle(position.x(), position.y(), 4, color); } } }; }
41.321918
127
0.64661
elsid
b6efaa635845b973b93fecf7dc5b35d5a17f31a6
632
cpp
C++
queue/exp.cpp
JN513/intensivo-geduc-obi-2021
056a0f4d1f44bee2097da63e753ddd198527f941
[ "MIT" ]
1
2021-12-06T23:47:13.000Z
2021-12-06T23:47:13.000Z
queue/exp.cpp
JN513/intensivo-geduc-obi-2021
056a0f4d1f44bee2097da63e753ddd198527f941
[ "MIT" ]
null
null
null
queue/exp.cpp
JN513/intensivo-geduc-obi-2021
056a0f4d1f44bee2097da63e753ddd198527f941
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define ll long long int #define nl endl using namespace std; int main(void){ queue<int> fila; //fila.push(1); //fila.push(2); //cout << fila.front() << nl; //fila.pop(); //cout << fila.front() << nl; for(int i = 10; i <= 100; i += 10){ fila.push(i); } //Após o caixa quebrar queremos saber as pessoas que ainda estão na fila. while(fila.empty() == false){ //Enquanto a fila não for vazia int p = fila.front(); //Pego a pessoa na frente da fila e imprimo cout << p <<" "; fila.pop(); //Removo a pessoa que está na frente da fila. } return 0; }
19.75
74
0.580696
JN513
b6f307c0eb2a2f173253c48e745d65544e4280c3
3,905
cc
C++
platforms/stm/event_handler_test/src/dartino_entry.cc
dartino/fletch
aa7aba8473f405dd49b9c81b0faeeebfa6e94fc8
[ "BSD-3-Clause" ]
144
2016-01-29T00:14:04.000Z
2021-02-20T09:36:11.000Z
platforms/stm/event_handler_test/src/dartino_entry.cc
akashfoss/sdk
aa7aba8473f405dd49b9c81b0faeeebfa6e94fc8
[ "BSD-3-Clause" ]
241
2016-01-27T15:37:56.000Z
2016-09-09T07:34:07.000Z
platforms/stm/event_handler_test/src/dartino_entry.cc
akashfoss/sdk
aa7aba8473f405dd49b9c81b0faeeebfa6e94fc8
[ "BSD-3-Clause" ]
30
2016-02-23T18:14:54.000Z
2020-10-18T13:49:34.000Z
// Copyright (c) 2015, the Dartino project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE.md file. #include <stdlib.h> #include <cmsis_os.h> extern "C" { #include <lcd_log.h> } #include <stm32746g_discovery.h> #include <stm32746g_discovery_lcd.h> #include "include/dartino_api.h" #include "include/static_ffi.h" #include "platforms/stm/disco_dartino/src/dartino_entry.h" #include "platforms/stm/disco_dartino/src/page_allocator.h" #include "platforms/stm/disco_dartino/src/uart.h" #include "src/shared/utils.h" #include "src/shared/platform.h" extern unsigned char _binary_event_handler_test_snapshot_start; extern unsigned char _binary_event_handler_test_snapshot_end; extern unsigned char _binary_event_handler_test_snapshot_size; extern PageAllocator* page_allocator; // `MessageQueueProducer` will send a message every `kMessageFrequency` // millisecond. const int kMessageFrequency = 400; // Sends a message on a port_id with a fixed interval. static void MessageQueueProducer(const void *argument) { int handle = reinterpret_cast<int>(argument); dartino::Device *device = dartino::DeviceManager::GetDeviceManager()->GetDevice(handle); uint16_t counter = 0; for (;;) { counter++; device->SetFlag(1); osDelay(kMessageFrequency); } for (;;) {} } void NotifyRead(int handle) { dartino::Device *device = dartino::DeviceManager::GetDeviceManager()->GetDevice(handle); device->ClearFlag(1); } int InitializeProducer() { dartino::Device *device = new dartino::Device(NULL); int handle = dartino::DeviceManager::GetDeviceManager()->InstallDevice(device); osThreadDef(PRODUCER, MessageQueueProducer, osPriorityNormal, 0, 2 * 1024); osThreadCreate(osThread(PRODUCER), reinterpret_cast<void*>(handle)); return handle; } DARTINO_EXPORT_STATIC_RENAME(BSP_LED_On, BSP_LED_On) DARTINO_EXPORT_STATIC_RENAME(BSP_LED_Off, BSP_LED_Off) DARTINO_EXPORT_STATIC_RENAME(initialize_producer, InitializeProducer) DARTINO_EXPORT_STATIC_RENAME(notify_read, NotifyRead) // LCDLogPutchar is defined by the STM LCD log utility // (Utilities/Log/lcd_log.c) by means of the macro definitions of // LCD_LOG_PUTCHAR in lcd_log_conf.h. extern "C" int LCDLogPutchar(int ch); void LCDPrintIntercepter(const char* message, int out, void* data) { int len = strlen(message); if (out == 3) { LCD_LineColor = LCD_COLOR_RED; } else { LCD_LineColor = LCD_COLOR_BLACK; } for (int i = 0; i < len; i++) { LCDLogPutchar(message[i]); } } // Implementation of write used from syscalls.c to redirect all printf // calls to the print interceptors. extern "C" int Write(int file, char *ptr, int len) { for (int i = 0; i < len; i++) { if (file == 2) { dartino::Print::Error("%c", *ptr++); } else { dartino::Print::Out("%c", *ptr++); } } return len; } // Run Dartino on the linked in snapshot. void StartDartino(void const * argument) { dartino::Print::Out("Setup Dartino\n"); DartinoSetup(); dartino::Print::Out("Read Dartino snapshot\n"); unsigned char *snapshot = &_binary_event_handler_test_snapshot_start; int snapshot_size = reinterpret_cast<int>(&_binary_event_handler_test_snapshot_size); DartinoProgram program = DartinoLoadSnapshot(snapshot, snapshot_size); dartino::Print::Out("Run Dartino program\n"); DartinoRunMain(program, 0, NULL); dartino::Print::Out("Dartino program exited\n"); } // Main entry point from FreeRTOS. Running in the default task. void DartinoEntry(void const * argument) { BSP_LED_Init(LED1); // Always disable standard out, as this will cause infinite // recursion in the syscalls.c handling of write. dartino::Print::DisableStandardOutput(); StartDartino(argument); // No more to do right now. for (;;) { osDelay(1); } }
30.271318
79
0.732907
dartino
b6f5c1412e66019b23ff971ae9a9ed28e868d6b4
7,333
cpp
C++
src/FastRoute/third_party/pdrev/src/pdrev.cpp
ax3ghazy/OpenROAD
2d41acd184d2fb5c551fbdb1f74bbe73a782de6f
[ "BSD-3-Clause-Clear" ]
null
null
null
src/FastRoute/third_party/pdrev/src/pdrev.cpp
ax3ghazy/OpenROAD
2d41acd184d2fb5c551fbdb1f74bbe73a782de6f
[ "BSD-3-Clause-Clear" ]
null
null
null
src/FastRoute/third_party/pdrev/src/pdrev.cpp
ax3ghazy/OpenROAD
2d41acd184d2fb5c551fbdb1f74bbe73a782de6f
[ "BSD-3-Clause-Clear" ]
null
null
null
#include "pdrev.h" #include "aux.h" namespace PD{ void PdRev::setAlphaPDII(float alpha){ alpha2 = alpha; } void PdRev::addNet(int numPins, std::vector<unsigned> x, std::vector<unsigned> y){ my_graphs.push_back(new Graph(numPins, verbose, alpha1, alpha2, alpha3, alpha4, root_idx, beta, margin, seed, dist, x, y)); } void PdRev::config(){ num_nets = my_graphs.size(); // measure.start_clock(); // cout << "\nGenerating nearest neighbor graph..." << endl; for (unsigned i = 0; i < num_nets; ++i) { // Guibas-Stolfi algorithm for computing nearest NE (north-east) neighbors if (i == net_num || !runOneNet) { my_graphs[i]-> buildNearestNeighborsForSPT(my_graphs[i]->num_terminals); } } // cout << "\nFinished generating nearest neighbor graph..." << endl; // measure.stop_clock("Graph generation"); } void PdRev::runPDII(){ config(); // measure.start_clock(); // cout << "\nRunning PD-II... alpha = " // << alpha2 << endl; for (unsigned i = 0; i < num_nets; ++i) { if (i == net_num || !runOneNet) { my_graphs[i]-> PDBU_new_NN(); } } /* for (unsigned i = 0; i < num_nets; ++i) { cout << " Net " << i << " WL = " << my_graphs[i]->pdbu_wl << " PL = " << my_graphs[i]->pdbu_pl << " DC = " << my_graphs[i]->pdbu_dc << endl; } cout << "Finished running PD-II..." << endl; measure.stop_clock("PD-II"); */ runDAS(); } void PdRev::runDAS(){ //measure.start_clock(); //cout << "\nRunning Steiner algorithm..." << endl; for (unsigned i = 0; i < num_nets; ++i) { if (i == net_num || !runOneNet) { my_graphs[i]-> doSteiner_HoVW(); } } /* for (unsigned i = 0; i < num_nets; ++i) { cout << " Net " << i << " WL = " << my_graphs[i]->st_wl << " PL = " << my_graphs[i]->st_pl << " DC = " << my_graphs[i]->st_dc << endl; } cout << "Finished Steiner algorithm..." << endl; measure.stop_clock("HVW Steinerization"); cout << "\nRunning DAS algorithm..." << endl; */ for (unsigned i = 0; i < num_nets; ++i) { if (i == net_num || !runOneNet) { my_graphs[i]-> fix_max_dc(); } } /*for (unsigned i = 0; i < num_nets; ++i) { cout << " Net " << i << " WL = " << my_graphs[i]->daf_wl << " PL = " << my_graphs[i]->daf_pl << " DC = " << my_graphs[i]->daf_dc << endl; } cout << "Finished DAS algorithm..." << endl; measure.stop_clock("DAS"); */ } void PdRev::replaceNode(int graph, int originalNode){ Graph * tree = my_graphs[graph]; std::vector<Node> & nodes = tree->nodes; Node & node = nodes[originalNode]; int nodeParent = node.parent; std::vector<int> & nodeChildren = node.children; int newNode = tree->nodes.size(); Node newSP(newNode, node.x, node.y); //Replace parent in old node children //Add children to new node for (int child : nodeChildren){ tree->replaceParent(tree->nodes[child], originalNode, newNode); tree->addChild(newSP, child); } //Delete children from old node nodeChildren.clear(); //Set new node as old node's parent node.parent = newNode; //Set new node parent if (nodeParent != originalNode){ newSP.parent = nodeParent; //Replace child in parent tree->replaceChild(tree->nodes[nodeParent], originalNode, newNode); } else newSP.parent = newNode; //Add old node as new node's child tree->addChild(newSP, originalNode); nodes.push_back(newSP); } void PdRev::transferChildren(int graph, int originalNode){ Graph * tree = my_graphs[graph]; std::vector<Node> & nodes = tree->nodes; Node & node = nodes[originalNode]; std::vector<int> nodeChildren = node.children; int newNode = tree->nodes.size(); Node newSP(newNode, node.x, node.y); //Replace parent in old node children //Add children to new node int count = 0; node.children.clear(); for (int child : nodeChildren){ if (count < 2){ tree->replaceParent(tree->nodes[child], originalNode, newNode); tree->addChild(newSP, child); } else { tree->addChild(node, child); } count++; } newSP.parent = originalNode; tree->addChild(node, newNode); nodes.push_back(newSP); } Tree PdRev::translateTree(int nTree){ Graph* pdTree = my_graphs[nTree]; Tree fluteTree; fluteTree.deg = pdTree->orig_num_terminals; fluteTree.branch = (Branch *)malloc((2* fluteTree.deg -2 )* sizeof(Branch)); fluteTree.length = pdTree->daf_wl; if (pdTree->orig_num_terminals > 2){ for (int i = 0; i < pdTree->orig_num_terminals; ++i){ Node & child = pdTree->nodes[i]; if (child.children.size() == 0 || (child.parent == i && child.children.size() == 1 && child.children[0] >= pdTree->orig_num_terminals)) continue; replaceNode(nTree, i); } int nNodes = pdTree->nodes.size(); for (int i = pdTree->orig_num_terminals; i < nNodes; ++i){ Node & child = pdTree->nodes[i]; while (pdTree->nodes[i].children.size() > 3 || (pdTree->nodes[i].parent != i && pdTree->nodes[i].children.size() == 3)){ transferChildren(nTree,i); } } pdTree->RemoveSTNodes(); } for (int i = 0; i < pdTree->nodes.size(); ++i){ Node & child = pdTree->nodes[i]; int parent = child.parent; Branch & newBranch = fluteTree.branch[i]; newBranch.x = (DTYPE) child.x; newBranch.y = (DTYPE) child.y; newBranch.n = parent; } my_graphs.clear(); return fluteTree; } void PdRev::printTree(Tree fluteTree){ int i; for (i = 0; i < 2* fluteTree.deg-2; i++) { printf("%d \n", i); printf("%d %d\n", fluteTree.branch[i].x, fluteTree.branch[i].y); printf("%d %d\n\n", fluteTree.branch[fluteTree.branch[i].n].x, fluteTree.branch[fluteTree.branch[i].n].y); } } }
37.798969
159
0.472931
ax3ghazy
b6f62a62f0c999235107a02630803ec86914787a
20,782
cpp
C++
enduser/netmeeting/ui/msconfft/applet.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
enduser/netmeeting/ui/msconfft/applet.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
enduser/netmeeting/ui/msconfft/applet.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "mbftpch.h" #include <it120app.h> #include <regentry.h> #include <iappldr.h> #include <version.h> HINSTANCE g_hDllInst; DWORD g_dwWorkThreadID = 0; HANDLE g_hWorkThread = NULL; CFileTransferApplet *g_pFileXferApplet = NULL; CRITICAL_SECTION g_csWorkThread; TCHAR g_szMBFTWndClassName[32]; const TCHAR g_cszFtHiddenWndClassName[] = _TEXT("FtHiddenWindow"); extern CFtLoader *g_pFtLoader; extern T120Error CALLBACK CreateAppletLoaderInterface(IAppletLoader**); BOOL g_fSendAllowed = FALSE; BOOL g_fRecvAllowed = FALSE; UINT_PTR g_cbMaxSendFileSize = 0; BOOL g_fShutdownByT120 = FALSE; // Local functions void ReadSettingsFromRegistry(void); void BuildAppletCapabilities(void); void BuildDefaultAppletSessionKey(void); DWORD __stdcall FTWorkThreadProc(LPVOID lpv); #define FT_VERSION_STR "MS FT Version" OSTR FT_VERSION_ID = {sizeof(FT_VERSION_STR), (unsigned char*)FT_VERSION_STR}; BOOL WINAPI DllMain(HINSTANCE hDllInst, DWORD fdwReason, LPVOID lpv) { switch (fdwReason) { case DLL_PROCESS_ATTACH: g_hDllInst = hDllInst; ::DisableThreadLibraryCalls(hDllInst); InitDebug(); DBG_INIT_MEMORY_TRACKING(hDllInst); ::InitializeCriticalSection(&g_csWorkThread); ::wsprintf(&g_szMBFTWndClassName[0], TEXT("MBFTWnd%0X_%0X"), ::GetCurrentProcessId(), ::GetTickCount()); ASSERT(::lstrlenA(&g_szMBFTWndClassName[0]) < sizeof(g_szMBFTWndClassName)); ::BuildAppletCapabilities(); ::BuildDefaultAppletSessionKey(); TRACE_OUT(("*** MSCONFFT.DLL: Attached process thread %X", GetCurrentThreadId())); ::T120_AppletStatus(APPLET_ID_FT, APPLET_LIBRARY_LOADED); break; case DLL_PROCESS_DETACH: TRACE_OUT(("*** NMFT.DLL: Detaching process thread %X", GetCurrentThreadId())); if (NULL != g_hWorkThread) { ::CloseHandle(g_hWorkThread); } ::T120_AppletStatus(APPLET_ID_FT, APPLET_LIBRARY_FREED); ::DeleteCriticalSection(&g_csWorkThread); DBG_CHECK_MEMORY_TRACKING(hDllInst); DeInitDebugMbft(); break; default: break; } return TRUE; } HRESULT WINAPI FT_CreateInterface(IMbftControl **ppMbft, IMbftEvents *pEvents) { HRESULT hr; if (NULL != ppMbft && NULL != pEvents) { if (NULL != g_pFileXferApplet) { ReadSettingsFromRegistry(); DBG_SAVE_FILE_LINE MBFTInterface *pObject = new MBFTInterface(pEvents, &hr); if (NULL != pObject) { if (S_OK == hr) { *ppMbft = (IMbftControl *) pObject; return S_OK; } ERROR_OUT(("CreateMbftObject: cannot create MBFTInterface")); pObject->Release(); *ppMbft = NULL; return hr; } ERROR_OUT(("CreateMbftObject: cannot allocate MBFTInterface")); return E_OUTOFMEMORY; } WARNING_OUT(("CreateMbftObject: applet object is not created")); } else { ERROR_OUT(("CreateMbftObject: invalid pointer, ppMbft=0x%x, pEvents=0x%x", ppMbft, pEvents)); } return E_POINTER; } void CALLBACK FileXferAppletCallback ( T120AppletMsg *pMsg ) { CFileTransferApplet *pThisApplet = (CFileTransferApplet *) pMsg->pAppletContext; if (pThisApplet == g_pFileXferApplet && NULL != g_pFileXferApplet) { pThisApplet->T120Callback(pMsg); } } BOOL CFtHiddenWindow::Create(void) { return(CGenWindow::Create(NULL, NULL, WS_POPUP, // not visible! 0, 0, 0, 0, 0, g_hDllInst, NULL, g_cszFtHiddenWndClassName )); } CFileTransferApplet::CFileTransferApplet(HRESULT *pHr) : m_pHwndHidden(NULL) { T120Error rc = ::T120_CreateAppletSAP(&m_pAppletSAP); if (T120_NO_ERROR == rc) { m_pAppletSAP->Advise(FileXferAppletCallback, this); *pHr = S_OK; } else { ERROR_OUT(("CFileTransferApplet::CFileTransferApplet: cannot create app sap, rc=%u", rc)); *pHr = E_OUTOFMEMORY; } // Create Hidden Window for processing MBFTMSG DBG_SAVE_FILE_LINE m_pHwndHidden = new CFtHiddenWindow(); if (m_pHwndHidden) { *pHr = (m_pHwndHidden->Create())?S_OK:E_FAIL; } else { *pHr = E_OUTOFMEMORY; } } CFileTransferApplet::~CFileTransferApplet(void) { m_EngineList.Clear(); CAppletWindow *pWindow; while (NULL != (pWindow = m_WindowList.Get())) { pWindow->Release(); // add ref while being put to the list pWindow->OnExit(); } if (NULL != m_pAppletSAP) { m_pAppletSAP->ReleaseInterface(); } if (NULL != m_pHwndHidden) { HWND hwndHidden = m_pHwndHidden->GetWindow(); DestroyWindow(hwndHidden); m_pHwndHidden->Release(); m_pHwndHidden = NULL; } } BOOL CFileTransferApplet::QueryShutdown(BOOL fGoAheadShutdown) { CAppletWindow *pWindow; m_WindowList.Reset(); while (NULL != (pWindow = m_WindowList.Iterate())) { if (! pWindow->QueryShutdown(fGoAheadShutdown)) { return FALSE; // do not shut down now } } return TRUE; } void CFileTransferApplet::T120Callback ( T120AppletMsg *pMsg ) { switch (pMsg->eMsgType) { case GCC_PERMIT_TO_ENROLL_INDICATION: { MBFTEngine *pEngine = m_EngineList.FindByConfID(pMsg->PermitToEnrollInd.nConfID); if (NULL == pEngine) { pEngine = m_EngineList.FindByConfID(0); if (NULL == pEngine) { if (pMsg->PermitToEnrollInd.fPermissionGranted) { DBG_SAVE_FILE_LINE pEngine = new MBFTEngine(NULL, MBFT_STATIC_MODE, _iMBFT_DEFAULT_SESSION); ASSERT(NULL != pEngine); } } } if (NULL != pEngine) { pEngine->OnPermitToEnrollIndication(&pMsg->PermitToEnrollInd); } // deal with unattended conference if (pMsg->PermitToEnrollInd.fPermissionGranted) { if (NULL == pEngine) { m_UnattendedConfList.Append(pMsg->PermitToEnrollInd.nConfID); } } else { m_UnattendedConfList.Remove(pMsg->PermitToEnrollInd.nConfID); } } break; case T120_JOIN_SESSION_CONFIRM: break; default: ERROR_OUT(("CFileTransferApplet::T120Callback: unknown t120 msg type=%u", pMsg->eMsgType)); break; } } void CFileTransferApplet::RegisterEngine(MBFTEngine *p) { m_EngineList.Append(p); // relay any unattended conference if (! m_UnattendedConfList.IsEmpty()) { GCCAppPermissionToEnrollInd Ind; Ind.nConfID = m_UnattendedConfList.Get(); Ind.fPermissionGranted = TRUE; p->OnPermitToEnrollIndication(&Ind); } } void CFileTransferApplet::UnregisterEngine(MBFTEngine *p) { if (m_EngineList.Remove(p)) { CAppletWindow *pWindow; m_WindowList.Reset(); while (NULL != (pWindow = m_WindowList.Iterate())) { if (pWindow->GetEngine() == p) { pWindow->UnregisterEngine(); break; } } p->Release(); // AddRef in MBFTEngine() } } MBFTEngine * CFileTransferApplet::FindEngineWithIntf(void) { MBFTEngine *pEngine; m_EngineList.Reset(); while (NULL != (pEngine = m_EngineList.Iterate())) { if (pEngine->GetInterfacePointer()) { break; } } return pEngine; } MBFTEngine * CFileTransferApplet::FindEngineWithNoIntf(void) { MBFTEngine *pEngine; m_EngineList.Reset(); while (NULL != (pEngine = m_EngineList.Iterate())) { if (! pEngine->GetInterfacePointer()) { break; } } return pEngine; } void CFileTransferApplet::RegisterWindow(CAppletWindow *pWindow) { pWindow->AddRef(); m_WindowList.Append(pWindow); if (1 == m_WindowList.GetCount() && 1 == m_EngineList.GetCount()) { MBFTEngine *pEngine = m_EngineList.PeekHead(); pWindow->RegisterEngine(pEngine); pEngine->SetWindow(pWindow); pEngine->AddAllPeers(); } } void CFileTransferApplet::UnregisterWindow(CAppletWindow *pWindow) { if (m_WindowList.Remove(pWindow)) { pWindow->Release(); } if (m_WindowList.IsEmpty()) { g_fNoUI = FALSE; ::T120_AppletStatus(APPLET_ID_FT, APPLET_CLOSING); BOOL fRet = ::PostMessage(GetHiddenWnd(), WM_QUIT, 0, 0); ASSERT(fRet); } } CAppletWindow *CFileTransferApplet::GetUnattendedWindow(void) { CAppletWindow *pWindow; m_WindowList.Reset(); while (NULL != (pWindow = m_WindowList.Iterate())) { if (! pWindow->IsInConference()) { return pWindow; } } return NULL; } LRESULT CFileTransferApplet::BringUIToFront(void) { CAppletWindow *pWindow; if (m_WindowList.IsEmpty()) { // The g_pFileXferApplet was created by fNoUI == TRUE, // Now we need to create the UI HRESULT hr; DBG_SAVE_FILE_LINE pWindow = new CAppletWindow(g_fNoUI, &hr); if (NULL != pWindow) { if (S_OK != hr) { ERROR_OUT(("BringUIToFrong: cannot create CAppletWindow")); pWindow->Release(); pWindow = NULL; } else { g_pFileXferApplet->RegisterWindow(pWindow); } } else { ERROR_OUT(("FTBringUIToFrong: cannot allocate CAppletWindow")); hr = E_OUTOFMEMORY; } } m_WindowList.Reset(); while (NULL != (pWindow = m_WindowList.Iterate())) { pWindow->BringToFront(); } return 0; } BOOL CFileTransferApplet::Has2xNodeInConf(void) { MBFTEngine *pEngine; m_EngineList.Reset(); while (NULL != (pEngine = m_EngineList.Iterate())) { if (pEngine->Has2xNodeInConf()) { return TRUE; } } return FALSE; } BOOL CFileTransferApplet::InConf(void) { MBFTEngine *pEngine; m_EngineList.Reset(); while (NULL != (pEngine = m_EngineList.Iterate())) { if (pEngine->GetPeerCount() > 1) { return TRUE; } } return FALSE; } BOOL CFileTransferApplet::HasSDK(void) { MBFTEngine *pEngine; m_EngineList.Reset(); while (NULL != (pEngine = m_EngineList.Iterate())) { if (pEngine->HasSDK()) { return TRUE; } } return FALSE; } MBFTEngine * CEngineList::FindByConfID(T120ConfID nConfID) { MBFTEngine *p; Reset(); while (NULL != (p = Iterate())) { if (nConfID == p->GetConfID()) { return p; } } return NULL; } #ifdef ENABLE_HEARTBEAT_TIMER MBFTEngine * CEngineList::FindByTimerID(UINT_PTR nTimerID) { MBFTEngine *p; Reset(); while (NULL != (p = Iterate())) { if (nTimerID == p->GetTimerID()) { return p; } } return NULL; } #endif // // File Transfer Capabilities // static GCCAppCap s_CapArray[4]; const GCCAppCap* g_aAppletCaps[4] = { &s_CapArray[0], &s_CapArray[1], &s_CapArray[2], &s_CapArray[3] }; static GCCNonCollCap s_NCCapArray[2]; const GCCNonCollCap* g_aAppletNonCollCaps[2] = { &s_NCCapArray[0], &s_NCCapArray[1] }; static const OSTR s_AppData[2] = { { sizeof(PROSHARE_STRING) + sizeof(MY_APP_STR), (LPBYTE) PROSHARE_STRING "\0" MY_APP_STR }, { sizeof(PROSHARE_FILE_END_STRING), (LPBYTE) PROSHARE_FILE_END_STRING }, }; void BuildAppletCapabilities(void) { // // Capabilities // //Say that we can handle a max. of 4GBs... s_CapArray[0].capability_id.capability_id_type = GCC_STANDARD_CAPABILITY; s_CapArray[0].capability_id.standard_capability = _MBFT_MAX_FILE_SIZE_ID; s_CapArray[0].capability_class.eType = GCC_UNSIGNED_MAXIMUM_CAPABILITY; s_CapArray[0].capability_class.nMinOrMax = _iMBFT_MAX_FILE_SIZE; s_CapArray[0].number_of_entities = 0; //And that we can handle only about 25K of data per //FileData PDU s_CapArray[1].capability_id.capability_id_type = GCC_STANDARD_CAPABILITY; s_CapArray[1].capability_id.standard_capability = _MBFT_MAX_DATA_PAYLOAD_ID; s_CapArray[1].capability_class.eType = GCC_UNSIGNED_MAXIMUM_CAPABILITY; s_CapArray[1].capability_class.nMinOrMax = _iMBFT_MAX_FILEDATA_PDU_LENGTH; s_CapArray[1].number_of_entities = 0; //and that we don't support V.42.. s_CapArray[2].capability_id.capability_id_type = GCC_STANDARD_CAPABILITY; s_CapArray[2].capability_id.standard_capability = _MBFT_V42_COMPRESSION_ID; s_CapArray[2].capability_class.eType = GCC_LOGICAL_CAPABILITY; s_CapArray[2].capability_class.nMinOrMax = 0; s_CapArray[2].number_of_entities = 0; //Tell other node about this node's version number s_CapArray[3].capability_id.capability_id_type = GCC_NON_STANDARD_CAPABILITY; s_CapArray[3].capability_id.non_standard_capability.key_type = GCC_H221_NONSTANDARD_KEY; s_CapArray[3].capability_id.non_standard_capability.h221_non_standard_id = FT_VERSION_ID; //s_CapArray[3].capability_id.non_standard_capability.h221_non_standard_id.value = (unsigned char *)FT_VERSION_ID; s_CapArray[3].capability_class.eType = GCC_UNSIGNED_MINIMUM_CAPABILITY; s_CapArray[3].capability_class.nMinOrMax = VER_PRODUCTVERSION_DW; s_CapArray[3].number_of_entities = 0; // // Non-Collapsed Capabilities // s_NCCapArray[0].capability_id.capability_id_type = GCC_STANDARD_CAPABILITY; s_NCCapArray[0].capability_id.standard_capability = _iMBFT_FIRST_PROSHARE_CAPABILITY_ID; s_NCCapArray[0].application_data = (OSTR *) &s_AppData[0]; s_NCCapArray[1].capability_id.capability_id_type = GCC_STANDARD_CAPABILITY; s_NCCapArray[1].capability_id.standard_capability = _iMBFT_PROSHARE_FILE_EOF_ACK_ID; s_NCCapArray[1].application_data = (OSTR *) &s_AppData[1]; } GCCSessionKey g_AppletSessionKey; static ULONG s_MBFTKeyNodes[] = {0,0,20,127,0,1}; void BuildDefaultAppletSessionKey(void) { ::ZeroMemory(&g_AppletSessionKey, sizeof(g_AppletSessionKey)); // SessionID is zero g_AppletSessionKey.application_protocol_key.key_type = GCC_OBJECT_KEY; g_AppletSessionKey.application_protocol_key.object_id.long_string = s_MBFTKeyNodes; g_AppletSessionKey.application_protocol_key.object_id.long_string_length = sizeof(s_MBFTKeyNodes) / sizeof(s_MBFTKeyNodes[0]); } void ReadSettingsFromRegistry(void) { static BOOL s_fReadAlready = FALSE; if (! s_fReadAlready) { s_fReadAlready = TRUE; RegEntry rePolicies(POLICIES_KEY, HKEY_CURRENT_USER); g_fSendAllowed = (0 == rePolicies.GetNumber(REGVAL_POL_NO_FILETRANSFER_SEND, DEFAULT_POL_NO_FILETRANSFER_SEND)); g_fRecvAllowed = (0 == rePolicies.GetNumber(REGVAL_POL_NO_FILETRANSFER_RECEIVE, DEFAULT_POL_NO_FILETRANSFER_RECEIVE)); g_cbMaxSendFileSize = rePolicies.GetNumber(REGVAL_POL_MAX_SENDFILESIZE, DEFAULT_POL_MAX_FILE_SIZE); // initialize the delays RegEntry reFt(FILEXFER_KEY, HKEY_CURRENT_USER); g_nSendDisbandDelay = reFt.GetNumber(REGVAL_FILEXFER_DISBAND, g_nSendDisbandDelay); g_nChannelResponseDelay = reFt.GetNumber(REGVAL_FILEXFER_CH_RESPONSE, g_nChannelResponseDelay); } } ///////////////////////////////////////////////////////////////// // // Hidden windows procedure // LRESULT CFtHiddenWindow::ProcessMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { LRESULT rc = T120_NO_ERROR; MBFTEngine *pEngine = (MBFTEngine *) lParam; MBFTMsg *pMsg = (MBFTMsg *) wParam; MBFTInterface *pIntf; switch(uMsg) { case WM_BRING_TO_FRONT: g_pFileXferApplet->BringUIToFront(); break; case MBFTMSG_CREATE_ENGINE: pIntf = (MBFTInterface *) lParam; pEngine = g_pFileXferApplet->FindEngineWithNoIntf(); if (NULL == pEngine) { DBG_SAVE_FILE_LINE pEngine = new MBFTEngine(NULL, MBFT_STATIC_MODE, _iMBFT_DEFAULT_SESSION); ASSERT(NULL != pEngine); } if (NULL != pEngine) { pIntf->SetEngine(pEngine); pEngine->SetInterfacePointer(pIntf); } ::SetEvent((HANDLE) wParam); break; case MBFTMSG_DELETE_ENGINE: ASSERT(NULL != g_pFileXferApplet); pIntf = pEngine->GetInterfacePointer(); g_pFileXferApplet->UnregisterEngine(pEngine); break; case MBFTMSG_HEART_BEAT: pEngine->DoStateMachine(NULL); break; case MBFTMSG_BASIC: ASSERT(NULL != pMsg); if (pEngine->DoStateMachine(pMsg)) { delete pMsg; pEngine->Release(); } else { // put it back to the queue ::PostMessage(g_pFileXferApplet->GetHiddenWnd(), uMsg, wParam, lParam); } break; default: return ::DefWindowProc(hwnd, uMsg, wParam, lParam); } return FALSE; } DWORD __stdcall FTWorkThreadProc(LPVOID lpv) { HRESULT hr; CAppletWindow *pAppletWnd; // allocate the applet object first DBG_SAVE_FILE_LINE g_pFileXferApplet = new CFileTransferApplet(&hr); ::SetEvent((HANDLE) lpv); // signaling that the work hread has been started if (NULL != g_pFileXferApplet) { if (S_OK == hr) { // CAppletWindow's constructor will register itself to g_pFileXferApplet DBG_SAVE_FILE_LINE CAppletWindow *pWindow = new CAppletWindow(g_fNoUI, &hr); if (NULL != pWindow) { if (S_OK != hr) { ERROR_OUT(("FTWorkThreadProc: cannot create CAppletWindow")); pWindow->Release(); pWindow = NULL; } else { g_pFileXferApplet->RegisterWindow(pWindow); } } else { ERROR_OUT(("FTWorkThreadProc: cannot allocate CAppletWindow")); hr = E_OUTOFMEMORY; } } else { ERROR_OUT(("FTWorkThreadProc: cannot create CFileTransferApplet")); delete g_pFileXferApplet; g_pFileXferApplet = NULL; } } else { ERROR_OUT(("FTWorkThreadProc: cannot allocate CFileTransferApplet")); hr = E_OUTOFMEMORY; } ::T120_AppletStatus(APPLET_ID_FT, APPLET_WORK_THREAD_STARTED); // the work thread loop if (S_OK == hr) { ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); MSG msg; while (::GetMessage(&msg, NULL, 0, 0)) { ::EnterCriticalSection(&g_csWorkThread); pAppletWnd = g_pFileXferApplet->GetMainUI(); if (!pAppletWnd || !pAppletWnd->FilterMessage(&msg)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } ::LeaveCriticalSection(&g_csWorkThread); } CGenWindow::DeleteStandardPalette(); delete g_pFileXferApplet; g_pFileXferApplet = NULL; ::CoUninitialize(); } ::T120_AppletStatus(APPLET_ID_FT, APPLET_WORK_THREAD_EXITED); g_dwWorkThreadID = 0; if (! g_fShutdownByT120) { // Wait for other dependent threads to finish their work ::Sleep(100); ::FreeLibraryAndExitThread(g_hDllInst, 0); } return 0; }
27.416887
131
0.596766
npocmaka
b6f8076d7844f29d7572fd5a4900bdf2923288ef
9,797
cpp
C++
EMA_HFODE/src/EMA_main.cpp
NctuICLab/GREMA
1ded5168e644b6cf4e219e28320f7e84aa3dba84
[ "MIT" ]
3
2019-04-27T10:34:27.000Z
2021-11-08T12:20:59.000Z
EMA_HFODE/src/EMA_main.cpp
NctuICLab/GREMA
1ded5168e644b6cf4e219e28320f7e84aa3dba84
[ "MIT" ]
null
null
null
EMA_HFODE/src/EMA_main.cpp
NctuICLab/GREMA
1ded5168e644b6cf4e219e28320f7e84aa3dba84
[ "MIT" ]
null
null
null
// // EMA_main.cpp // EMA_Hillsum_mask // // Created by Mingju on 2017/3/10. // Copyright (c) 2015 Mingju. All rights reserved. // #include "Define.h" #include "IGA.h" #include "OrthogonalArray.h" #include "Model.h" #include "Getknowledge.h" #include "Objfunction.h" using namespace std; int iteration; int test_mode,cc_mode; int ExecutionRuns; int FUNC; int GeneIndex; int POP_SIZE; int GENERATION; int NO_timepoints; int init_file_idx; int knowledge_idx; //test void exit_with_help(); void parse_command_line(int argc, char **argv); int main(int argc, char **argv) { parse_command_line(argc, argv); Getknowledge *knowledge; Model *hill; COrthogonalArray *OA; IGA *iga; Objfunction *obj; double **Chromosomes; Chromosomes = NULL; double **ModelParameters; ModelParameters = NULL; double *PopFitness; PopFitness = NULL; PopFitness = new double[POP_SIZE]; memset(PopFitness, 0, POP_SIZE*sizeof(double)); unsigned int seed; seed = (unsigned int)time(NULL); srand(seed); //char DataFileName[30]; int i,j; int time_step; int bestIndex; int NumReg = 0; int NumVars; int NumTFs; int NumEncodeParam; int TimePoints; int ExpRepeat; int *range = NULL; int *choose = NULL; int *LocMask = NULL; //unsigned int ChromSize; unsigned int execution_times; unsigned int NumOrigParam; //char str1[100]; char str2[100]; //FILE *ptr1,*ptr2,*ptr3; FILE *ptr_Inputprofile; FILE *ptr_EMAcalProfile; //sprintf(str1,"%d_step%d.txt",GeneIndex,iteration); //ptr2=fopen(str1,"w"); sprintf(str2,"calprofile%d_step%d.txt",GeneIndex,iteration); ptr_EMAcalProfile=fopen(str2,"w"); hill = new Model(); //strcpy(DataFileName,"./data/GNdata.txt"); hill->SetGeneIndex(GeneIndex); hill->ReadInitFromFile(argv[init_file_idx]); if(hill->IsSimulated()){ hill->CalAllExpValues(); //produce simulated data and perturbation set } ptr_Inputprofile=fopen("printdata.txt","w"); hill->PrintAllExpXs(ptr_Inputprofile);//print expression data //exit(0); if(hill->IsSimulated()){time_step = hill->NumTrials()/NO_timepoints;} else{time_step = 1;} NumVars = hill->NumVariables(); NumTFs = hill->NumTFsVariables(); TimePoints = hill->NumTrials(); ExpRepeat = hill->NumRuns(); range = new int [NumVars]; memset(range,0,NumVars*sizeof(int)); choose = new int [NumVars]; memset(choose, 0, NumVars*sizeof(int)); LocMask = new int [NumVars]; memset(LocMask, 0, NumVars*sizeof(int)); /* printf("initial\n"); for(int i=0; i<NumVars; i++){ printf("LockMask[%d]=%d\trange[%d]=%d\tchoose[%d]=%d\n",i,LocMask[i],i,range[i],i,choose[i]); } PAUSE; */ //============ knowledge = new Getknowledge(); knowledge->NumVars = NumVars; knowledge->NumTFs = NumTFs; //knowledge->initial_knowledge(); knowledge->Readknowledge(GeneIndex, iteration, LocMask, range, choose, argv[knowledge_idx]); /* printf("read knowledge of regulations file\n"); for(int i=0; i<NumVars; i++){ printf("LockMask[%d]=%d\trange[%d]=%d\tchoose[%d]=%d\n",i,LocMask[i],i,range[i],i,choose[i]); } PAUSE; */ NumReg = knowledge->get_Numconnections(); NumEncodeParam = 3*NumReg + 4;//Location, Nij, kij + bi, betai, degi NumOrigParam = 2*NumVars +3;//Nij,kij + bi, betai, degi //ChromSize = POP_SIZE * NumEncodeParam; Chromosomes = new double* [POP_SIZE]; for(i=0; i<POP_SIZE; i++){ Chromosomes[i] = new double [NumEncodeParam]; memset(Chromosomes[i], 0, NumEncodeParam*sizeof(double)); } ModelParameters = new double* [ExecutionRuns]; for(i=0; i<ExecutionRuns; i++){ ModelParameters[i] = new double [NumOrigParam+1]; memset(ModelParameters[i], 0, (NumOrigParam+1)*sizeof(double)); } /* printf("initial the chromosome value\n"); for(int i=0; i<POP_SIZE; i++){ for(int j=0; j<NumEncodeParam; j++){ printf("%f ",Chromosomes[i][j]); } printf("\n"); } PAUSE; */ obj = new Objfunction(); obj->NumVars = NumVars; obj->NumTFs = NumTFs; obj->NumTrials = TimePoints; obj->NumRuns = ExpRepeat; obj->PARAM_NUM = NumEncodeParam; obj->NumGeneParam = NumOrigParam; obj->NO_POP = POP_SIZE; obj->init_obj(time_step,FUNC,ExecutionRuns,cc_mode, NumReg,GeneIndex,hill,Chromosomes); //========================================== OA = new COrthogonalArray(); OA->initialOA(obj, Chromosomes, PopFitness); //=========================================== //iga = new IGA(OA,hill,knowledge,obj); iga = new IGA(); iga->NumVars = NumVars; iga->NumTFs = NumTFs; iga->NumRuns = ExpRepeat; iga->NumTrials = TimePoints; iga->Num_nochange = hill->NumNochange(); iga->NO_REG = NumReg; iga->NO_POP = POP_SIZE; iga->NO_GEN = GENERATION; iga->PARAM_NUM = NumEncodeParam; iga->NumGeneParam = NumOrigParam; iga->set_parameter(GeneIndex,iteration,test_mode,OA,hill,knowledge,obj,Chromosomes,PopFitness,LocMask,choose,range, ModelParameters); iga->initialIGA(); iga->RangeVariable(); //---------------------------------------------------------------------------- fprintf(ptr_EMAcalProfile,"Seed:%d\n",seed); for(execution_times=0;execution_times<ExecutionRuns;execution_times++) { if(knowledge->get_noregulation()) { for(i=0; i<POP_SIZE; i++){ for(j=0; j<NumEncodeParam; j++){ Chromosomes[i][j] = 0; //printf("%f ",Chromosomes[i][j]); } //printf("\n"); } }else{ iga->initialpop(); iga->run(execution_times); } for(i=0; i<ExpRepeat; i++) { fprintf(ptr_EMAcalProfile,"N:%d Run:%d ",execution_times,i); for(j=0; j<TimePoints; j+=time_step) { fprintf(ptr_EMAcalProfile,"%g ",obj->cal_profile[i][j]); }//end of NumTrials bestIndex = iga->get_BestOne(); fprintf(ptr_EMAcalProfile,"%e %1.3f\n", PopFitness[bestIndex], obj->best_cc); } } for(i=0;i<ExecutionRuns;i++) { for(j=0;j<=NumOrigParam;j++) { if(j==NumOrigParam) printf("%e ",ModelParameters[i][j]); else printf("%f ",ModelParameters[i][j]); } printf("%1.3f\n",obj->best_cc); } if(ModelParameters) { for(i=0;i<ExecutionRuns;i++) delete [] ModelParameters[i]; delete [] ModelParameters; } if(Chromosomes) { for(i=0;i<POP_SIZE;i++) delete [] Chromosomes[i]; delete [] Chromosomes; } if(PopFitness) delete [] PopFitness; if(range) delete [] range; if(choose) delete [] choose; if(LocMask) delete [] LocMask; if(knowledge) delete knowledge; if(hill) delete hill; if(OA) delete OA; if(iga) delete iga; if(obj) delete obj; fclose(ptr_EMAcalProfile); fclose(ptr_Inputprofile); return 0; } void exit_with_help() { printf( "Usage: HFODE_multiply [options] init_file kowledge_file\n" "options:\n" "-i : No.[?] of gene to run (Start from 0)\n" "-n : Number of run (default 30)\n" "-G : Number of generation (default 10000)\n" "-I : set the iteration of EMA (default 0)\n" "-F : Objective function (default 2)\n" " 0 -- (Xcal-Xexp)/Xexp\n" " 1 -- (Xcal-Xexp)\n" " 2 -- delta_diff + f0\n" " 3 -- delta_diff + f1\n" " 4 -- delta_diff\n" "-P : Number of popluation size (default 100)\n" "-t : Time points (necessary in simulated exp., default 10)\n" "-m change_mode : Test mode or RUN mode (default 1)\n" " 0 -- RUN mode\n" " 1 -- TEST mode\n" "-c cc_mode : set the fitness function with cc or not (default 0)\n" " 0 -- without cc mode\n" " 1 -- with cc mode\n" ); exit(1); } void parse_command_line(int argc, char **argv) { int i; if(argc <= 1) exit_with_help(); //===default values=====// GeneIndex=0; ExecutionRuns=30; GENERATION=10000; NO_timepoints=10; POP_SIZE=100; FUNC=2; test_mode=1; cc_mode=0; iteration = 0; init_file_idx = 2; knowledge_idx = 3; i = 1; //======================// while(1) { if(argv[i][0] != '-') break; switch(argv[i][1]) { case 'i': GeneIndex = atoi(argv[i+1]); i++; break; case 'n': ExecutionRuns = atoi(argv[i+1]); i++; break; case 'G': GENERATION = atoi(argv[i+1]); i++; break; case 'I': iteration = atoi(argv[i+1]); i++; break; case 'F': FUNC = atoi(argv[i+1]); i++; break; case 'P': POP_SIZE = atoi(argv[i+1]); i++; break; case 't': NO_timepoints = atoi(argv[i+1]); i++; break; case 'm': test_mode = atoi(argv[i+1]); i++; break; case 'c': cc_mode = atoi(argv[i+1]); i++; break; default: fprintf(stderr,"Unknown option!!\n"); exit_with_help(); break; } i++; } if(i < argc) init_file_idx = i++; else{ fprintf(stderr, "No initial file!!\n"); exit_with_help(); } if(i < argc) knowledge_idx = i; else{ fprintf(stderr, "No knowledge file!!\n"); exit_with_help(); } }
27.213889
137
0.557109
NctuICLab
b6fa6bb10e760f6a1214161ac9d0ab9518d9fbcd
12,390
cpp
C++
Codegen/RVInst.cpp
Yveh/Compiler-Mx_star
e00164537528858ed128dbc5a5c4cf7006d6276e
[ "MIT" ]
1
2020-01-23T14:34:11.000Z
2020-01-23T14:34:11.000Z
Codegen/RVInst.cpp
Yveh/Compiler-Mx_star
e00164537528858ed128dbc5a5c4cf7006d6276e
[ "MIT" ]
null
null
null
Codegen/RVInst.cpp
Yveh/Compiler-Mx_star
e00164537528858ed128dbc5a5c4cf7006d6276e
[ "MIT" ]
null
null
null
#include "RVInst.h" RVFunction::RVFunction(std::string _name) : name(_name) { regcnt = 0; paramInStackOffset = 0; } std::string RVFunction::to_string() { return name; } RVBlock::RVBlock(int _label) : label(_label) {} std::string RVBlock::to_string() { return "." + funcName + "_.bb" + std::to_string(label); } RVReg::RVReg(int _id, int _size, bool _is_global, bool _is_constString, bool _is_special) : id(_id), size(_size), is_global(_is_global), is_constString(_is_constString), is_special(_is_special) {} std::string RVReg::to_string() { if (is_special) return regNames[id]; else if (is_constString) return ".str." + std::to_string(id); else if (is_global) return "g" + std::to_string(id); else return "%" + std::to_string(id); } RVReg RVGReg(int _id, int _size) {return RVReg(_id, _size, 1, 0);} RVReg RVSReg(int _id, int _size) {return RVReg(_id, _size, 1, 1);} RVReg RVPReg(int _id) {return RVReg(_id, 0, 0, 0, 1);} RVReg RVReg_zero() {return RVReg(0, 0, 0, 0, 1);} RVReg RVReg_ra() {return RVReg(1, 0, 0, 0, 1);}; RVReg RVReg_a(int _id) {return RVReg(10 + _id, 0, 0, 0, 1);} RVReg RVReg_sp() {return RVReg(2, 0, 0, 0, 1);} RVImm::RVImm(int _id, Rop _op, bool _is_stack, bool _is_neg) : id(_id), op(_op), is_stack(_is_stack), is_neg(_is_neg) {} std::string RVImm::to_string() { if (op == Imm) return std::to_string(id); else if (op == Hi) return "%hi(g" + std::to_string(id) + ")"; else return "%lo(g" + std::to_string(id) + ")"; } RVLi::RVLi(RVReg _rd, RVImm _value) : rd(_rd), value(_value) {} RVSt::RVSt(RVReg _value, RVReg _addr, RVImm _offset, int _width) : value(_value), addr(_addr), offset(_offset), width(_width) {} RVLui::RVLui(RVReg _rd, RVImm _value) : rd(_rd), value(_value) {} RVMv::RVMv(RVReg _rd, RVReg _rs) : rd(_rd), rs(_rs) {} RVLd::RVLd(RVReg _rd, RVReg _addr, RVImm _offset, int _width) : rd(_rd), addr(_addr), offset(_offset), width(_width) {} RVJump::RVJump(std::shared_ptr<RVBlock> _offset) : offset(_offset) {} RVBr::RVBr(RVReg _rs1, RVReg _rs2, Bop _op, std::shared_ptr<RVBlock> _offset) : rs1(_rs1), rs2(_rs2), op(_op), offset(_offset) {} RVItype::RVItype(RVReg _rd, RVReg _rs, RVImm _imm, Sop _op) : rd(_rd), rs(_rs), imm(_imm), op(_op) {} RVRtype::RVRtype(RVReg _rd, RVReg _rs1, RVReg _rs2, Sop _op) : rd(_rd), rs1(_rs1), rs2(_rs2), op(_op) {} RVSz::RVSz(RVReg _rd, RVReg _rs, Szop _op) : rd(_rd), rs(_rs), op(_op) {} RVCall::RVCall(std::shared_ptr<RVFunction> _func) : func(_func) {} std::string RVBr::to_string() { std::string ret = "b"; switch (op) { case Bop::Eq : ret += "eq"; break; case Bop::Ne : ret += "ne"; break; case Bop::Ge : ret += "ge"; break; case Bop::Gt : ret += "gt"; break; case Bop::Le : ret += "le"; break; case Bop::Lt : ret += "lt"; break; } ret += " " + rs1.to_string() + ", " + rs2.to_string() + ", " + offset->to_string(); return ret; } std::set<int> RVBr::getUse() { return std::set<int>{rs1.is_special ? -rs1.id : rs1.id, rs2.is_special ? -rs2.id : rs2.id}; } std::set<int> RVBr::getDef() { return std::set<int>(); } void RVBr::replaceUse(int a, int b) { if (!rs1.is_special && rs1.id == a) rs1.id = b; if (!rs2.is_special && rs2.id == a) rs2.id = b; } void RVBr::replaceDef(int a, int b) {} void RVBr::replaceColor(int a, int b) { if (!rs1.is_special && rs1.id == a) { rs1.id = b; rs1.is_special = 1; } if (!rs2.is_special && rs2.id == a) { rs2.id = b; rs2.is_special = 1; } } std::string RVJump::to_string() { return "j " + offset->to_string(); } std::set<int> RVJump::getUse() { return std::set<int>(); } std::set<int> RVJump::getDef() { return std::set<int>(); } void RVJump::replaceUse(int a, int b) {} void RVJump::replaceDef(int a, int b) {} void RVJump::replaceColor(int a, int b) {} std::string RVLd::to_string() { if (width == 1) { return "lb " + rd.to_string() + ", " + offset.to_string() + "(" + addr.to_string() + ")"; } else { return "lw " + rd.to_string() + ", " + offset.to_string() + "(" + addr.to_string() + ")"; } } std::set<int> RVLd::getUse() { return std::set<int>{addr.is_special ? -addr.id : addr.id}; } std::set<int> RVLd::getDef() { return std::set<int>{rd.is_special ? -rd.id : rd.id}; } void RVLd::replaceUse(int a, int b) { if (!addr.is_special && addr.id == a) addr.id = b; } void RVLd::replaceDef(int a, int b) { if (!rd.is_special && rd.id == a) rd.id = b; } void RVLd::replaceColor(int a, int b) { if (!rd.is_special && rd.id == a) { rd.id = b; rd.is_special = 1; } if (!addr.is_special && addr.id == a) { addr.id = b; addr.is_special = 1; } } std::string RVLui::to_string() { return "lui " + rd.to_string() + ", " + value.to_string(); } std::set<int> RVLui::getUse() { return std::set<int>(); } std::set<int> RVLui::getDef() { return std::set<int>{rd.is_special ? -rd.id : rd.id}; } void RVLui::replaceUse(int a, int b) {} void RVLui::replaceDef(int a, int b) { if (!rd.is_special && rd.id == a) rd.id = b; } void RVLui::replaceColor(int a, int b) { if (!rd.is_special && rd.id == a) { rd.id = b; rd.is_special = 1; } } std::string RVLi::to_string() { return "li " + rd.to_string() + ", " + value.to_string(); } std::set<int> RVLi::getUse() { return std::set<int>{}; } std::set<int> RVLi::getDef() { return std::set<int>{rd.is_special ? -rd.id : rd.id}; } void RVLi::replaceUse(int a, int b) {} void RVLi::replaceDef(int a, int b) { if (!rd.is_special && rd.id == a) rd.id = b; } void RVLi::replaceColor(int a, int b) { if (!rd.is_special && rd.id == a) { rd.id = b; rd.is_special = 1; } } std::string RVSt::to_string() { if (width == 1) { return "sb " + value.to_string() + ", " + offset.to_string() + "(" + addr.to_string() + ")"; } else { return "sw " + value.to_string() + ", " + offset.to_string() + "(" + addr.to_string() + ")"; } } std::set<int> RVSt::getUse() { return std::set<int>{addr.is_special ? -addr.id : addr.id, value.is_special ? -value.id : value.id}; } std::set<int> RVSt::getDef() { return std::set<int>(); } void RVSt::replaceUse(int a, int b) { if (!addr.is_special && addr.id == a) addr.id = b; if (!value.is_special && value.id == a) value.id = b; } void RVSt::replaceDef(int a, int b) {} void RVSt::replaceColor(int a, int b) { if (!addr.is_special && addr.id == a) { addr.id = b; addr.is_special = 1; } if (!value.is_special && value.id == a) { value.id = b; value.is_special = 1; } } std::string RVSz::to_string() { if (op == Seqz) { return "seqz " + rd.to_string() + ", " + rs.to_string(); } else { return "snez " + rd.to_string() + ", " + rs.to_string(); } } std::set<int> RVSz::getUse() { return std::set<int>{rs.is_special ? -rs.id : rs.id}; } std::set<int> RVSz::getDef() { return std::set<int>{rd.is_special ? -rd.id : rd.id}; } void RVSz::replaceUse(int a, int b) { if (!rs.is_special && rs.id == a) rs.id = b; } void RVSz::replaceDef(int a, int b) { if (!rd.is_special && rd.id == a) rd.id = b; } void RVSz::replaceColor(int a, int b) { if (!rd.is_special && rd.id == a) { rd.id = b; rd.is_special = 1; } if (!rs.is_special && rs.id == a) { rs.id = b; rs.is_special = 1; } } std::string RVMv::to_string() { return "mv " + rd.to_string() + ", " + rs.to_string(); } std::set<int> RVMv::getUse() { return std::set<int>{rs.is_special ? -rs.id : rs.id}; } std::set<int> RVMv::getDef() { return std::set<int>{rd.is_special ? -rd.id : rd.id}; } void RVMv::replaceUse(int a, int b) { if (!rs.is_special && rs.id == a) rs.id = b; } void RVMv::replaceDef(int a, int b) { if (!rd.is_special && rd.id == a) rd.id = b; } void RVMv::replaceColor(int a, int b) { if (!rd.is_special && rd.id == a) { rd.id = b; rd.is_special = 1; } if (!rs.is_special && rs.id == a) { rs.id = b; rs.is_special = 1; } } std::string RVItype::to_string() { std::string ret; switch (op) { case Sop::And: ret = "andi "; break; case Sop::Or: ret = "ori "; break; case Sop::Xor: ret = "xori "; break; case Sop::Add: ret = "addi "; break; case Sop::Sll: ret = "slli "; break; case Sop::Sra: ret = "srli "; break; case Sop::Slt: ret = "slti "; break; } ret += rd.to_string() + ", " + rs.to_string() + ", " + imm.to_string(); return ret; } std::set<int> RVItype::getUse() { return std::set<int>{rs.is_special ? -rs.id : rs.id}; } std::set<int> RVItype::getDef() { return std::set<int>{rd.is_special ? -rd.id : rd.id}; } void RVItype::replaceUse(int a, int b) { if (!rs.is_special && rs.id == a) rs.id = b; } void RVItype::replaceDef(int a, int b) { if (!rd.is_special && rd.id == a) rd.id = b; } void RVItype::replaceColor(int a, int b) { if (!rs.is_special && rs.id == a) { rs.id = b; rs.is_special = 1; } if (!rd.is_special && rd.id == a) { rd.id = b; rd.is_special = 1; } } std::string RVRtype::to_string() { std::string ret; switch (op) { case Sop::And: ret = "and "; break; case Sop::Or: ret = "or "; break; case Sop::Xor: ret = "xor "; break; case Sop::Add: ret = "add "; break; case Sop::Sub: ret = "sub "; break; case Sop::Sll: ret = "sll "; break; case Sop::Sra: ret = "srl "; break; case Sop::Mul: ret = "mul "; break; case Sop::Div: ret = "div "; break; case Sop::Rem: ret = "rem "; break; case Sop::Slt: ret = "slt "; break; } ret += rd.to_string() + ", " + rs1.to_string() + ", " + rs2.to_string(); return ret; } std::set<int> RVRtype::getUse() { return std::set<int>{rs1.is_special ? -rs1.id : rs1.id, rs2.is_special ? -rs2.id : rs2.id}; } std::set<int> RVRtype::getDef() { return std::set<int>{rd.is_special ? -rd.id : rd.id}; } void RVRtype::replaceUse(int a, int b) { if (!rs1.is_special && rs1.id == a) rs1.id = b; if (!rs2.is_special && rs2.id == a) rs2.id = b; } void RVRtype::replaceDef(int a, int b) { if (!rd.is_special && rd.id == a) rd.id = b; } void RVRtype::replaceColor(int a, int b) { if (!rs1.is_special && rs1.id == a) { rs1.id = b; rs1.is_special = 1; } if (!rs2.is_special && rs2.id == a) { rs2.id = b; rs2.is_special = 1; } if (!rd.is_special && rd.id == a) { rd.id = b; rd.is_special = 1; } } std::string RVCall::to_string() { return "call " + func->to_string(); } std::set<int> RVCall::getUse() { std::set<int> ret; for (int i = 0; i < std::min(8, int(func->paras.size())); ++i) { ret.insert(-10 - i); } return ret; } std::set<int> RVCall::getDef() { return std::set<int>{-1, -5, -6, -7, -10, -11, -12, -13, -14, -15, -16, -17, -28, -29, -30, -31}; } void RVCall::replaceUse(int a, int b) {} void RVCall::replaceDef(int a, int b) {} void RVCall::replaceColor(int a, int b) {} RVRet::RVRet() {} std::string RVRet::to_string() { return std::string("ret"); } std::set<int> RVRet::getUse() { return std::set<int>{-1}; } std::set<int> RVRet::getDef() { return std::set<int>(); } void RVRet::replaceUse(int a, int b) {} void RVRet::replaceDef(int a, int b) {} void RVRet::replaceColor(int a, int b) {} RVLa::RVLa(RVReg _rd, RVReg _rs) : rd(_rd), rs(_rs) {} std::string RVLa::to_string() { return "la " + rd.to_string() + ", " + rs.to_string(); } std::set<int> RVLa::getUse() { return std::set<int>(); } std::set<int> RVLa::getDef() { return std::set<int>{rd.is_special ? -rd.id : rd.id}; } void RVLa::replaceUse(int a, int b) {} void RVLa::replaceDef(int a, int b) { if (!rd.is_special && rd.id == a) rd.id = b; } void RVLa::replaceColor(int a, int b) { if (!rd.is_special && rd.id == a) { rd.id = b; rd.is_special = 1; } }
25.030303
196
0.549395
Yveh
b6fa9c62c5ec2b10ecd62b2efd9b9de8589c0575
9,317
cc
C++
third_party/blink/renderer/core/script/dynamic_module_resolver.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
third_party/blink/renderer/core/script/dynamic_module_resolver.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
third_party/blink/renderer/core/script/dynamic_module_resolver.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2017 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 "third_party/blink/renderer/core/script/dynamic_module_resolver.h" #include "third_party/blink/public/platform/web_url_request.h" #include "third_party/blink/renderer/bindings/core/v8/exception_state.h" #include "third_party/blink/renderer/bindings/core/v8/referrer_script_info.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" #include "third_party/blink/renderer/core/loader/modulescript/module_script_fetch_request.h" #include "third_party/blink/renderer/core/script/modulator.h" #include "third_party/blink/renderer/core/script/module_script.h" #include "third_party/blink/renderer/platform/bindings/v8_throw_exception.h" #include "v8/include/v8.h" namespace blink { namespace { class DynamicImportTreeClient final : public ModuleTreeClient { public: static DynamicImportTreeClient* Create( const KURL& url, Modulator* modulator, ScriptPromiseResolver* promise_resolver) { return new DynamicImportTreeClient(url, modulator, promise_resolver); } void Trace(blink::Visitor*) override; private: DynamicImportTreeClient(const KURL& url, Modulator* modulator, ScriptPromiseResolver* promise_resolver) : url_(url), modulator_(modulator), promise_resolver_(promise_resolver) {} // Implements ModuleTreeClient: void NotifyModuleTreeLoadFinished(ModuleScript*) final; const KURL url_; const Member<Modulator> modulator_; const Member<ScriptPromiseResolver> promise_resolver_; }; // Implements steps 2.[5-8] of // https://html.spec.whatwg.org/multipage/webappapis.html#hostimportmoduledynamically(referencingscriptormodule,-specifier,-promisecapability) void DynamicImportTreeClient::NotifyModuleTreeLoadFinished( ModuleScript* module_script) { // [nospec] Abort the steps if the browsing context is discarded. if (!modulator_->HasValidContext()) { // The promise_resolver_ should have ::Detach()-ed at this point, // so ::Reject() is not necessary. return; } ScriptState* script_state = modulator_->GetScriptState(); ScriptState::Scope scope(script_state); v8::Isolate* isolate = script_state->GetIsolate(); // Step 2.5. "If result is null, then:" [spec text] if (!module_script) { // Step 2.5.1. "Let completion be Completion { [[Type]]: throw, [[Value]]: a // new TypeError, [[Target]]: empty }." [spec text] v8::Local<v8::Value> error = V8ThrowException::CreateTypeError( isolate, "Failed to fetch dynamically imported module: " + url_.GetString()); // Step 2.5.2. "Perform FinishDynamicImport(referencingScriptOrModule, // specifier, promiseCapability, completion)." [spec text] promise_resolver_->Reject(error); // Step 2.5.3. "Abort these steps." return; } // Step 2.6. "Run the module script module script, with the rethrow errors // boolean set to true." [spec text] ScriptValue error = modulator_->ExecuteModule( module_script, Modulator::CaptureEvalErrorFlag::kCapture); // Step 2.7. "If running the module script throws an exception, ..." [spec // text] if (!error.IsEmpty()) { // "... then perform FinishDynamicImport(referencingScriptOrModule, // specifier, promiseCapability, the thrown exception completion)." // [spec text] // Note: "the thrown exception completion" is |error|. // https://tc39.github.io/proposal-dynamic-import/#sec-finishdynamicimport // Step 1. "If completion is an abrupt completion, then perform ! // Call(promiseCapability.[[Reject]], undefined, << completion.[[Value]] // >>)." [spec text] promise_resolver_->Reject(error); return; } // Step 2.8. "Otherwise, perform // FinishDynamicImport(referencingScriptOrModule, specifier, // promiseCapability, NormalCompletion(undefined))." [spec text] // https://tc39.github.io/proposal-dynamic-import/#sec-finishdynamicimport // Step 2.a. "Assert: completion is a normal completion and // completion.[[Value]] is undefined." [spec text] DCHECK(error.IsEmpty()); // Step 2.b. "Let moduleRecord be // !HostResolveImportedModule(referencingScriptOrModule, specifierString)." // [spec text] // Note: We skip invocation of ScriptModuleResolver here. The // result of HostResolveImportedModule is guaranteed to be |module_script|. ScriptModule record = module_script->Record(); DCHECK(!record.IsNull()); // Step 2.c. "Assert: ModuleEvaluation has already been invoked on // moduleRecord and successfully completed." [spec text] // // Because |error| is empty, we are sure that ExecuteModule() above was // successfully completed. // Step 2.d. "Let namespace be GetModuleNamespace(moduleRecord)." [spec text] v8::Local<v8::Value> module_namespace = record.V8Namespace(isolate); // Step 2.e. "If namespace is an abrupt completion, perform // !Call(promiseCapability.[[Reject]], undefined, << namespace.[[Value]] >>)." // [spec text] // Note: Blink's implementation never allows |module_namespace| to be // an abrupt completion. // Step 2.f "Otherwise, perform ! Call(promiseCapability.[[Resolve]], // undefined, << namespace.[[Value]] >>)." [spec text] promise_resolver_->Resolve(module_namespace); } void DynamicImportTreeClient::Trace(blink::Visitor* visitor) { visitor->Trace(modulator_); visitor->Trace(promise_resolver_); ModuleTreeClient::Trace(visitor); } } // namespace void DynamicModuleResolver::Trace(blink::Visitor* visitor) { visitor->Trace(modulator_); } // https://html.spec.whatwg.org/multipage/webappapis.html#hostimportmoduledynamically(referencingscriptormodule,-specifier,-promisecapability) void DynamicModuleResolver::ResolveDynamically( const String& specifier, const KURL& referrer_resource_url, const ReferrerScriptInfo& referrer_info, ScriptPromiseResolver* promise_resolver) { DCHECK(modulator_->GetScriptState()->GetIsolate()->InContext()) << "ResolveDynamically should be called from V8 callback, within a valid " "context."; // Step 1. "Let referencing script be // referencingScriptOrModule.[[HostDefined]]." [spec text] // Step 2. "Run the following steps in parallel:" // Step 2.1. "Let url be the result of resolving a module specifier // given referencing script and specifier." [spec text] KURL base_url = referrer_info.BaseURL(); if (base_url.IsNull()) { // ReferrerScriptInfo::BaseURL returns null if it should defer to referrer // resource url. base_url = referrer_resource_url; } if (base_url.IsNull()) { // In some cases, "referencing script" may not exist. Use the document's // base URL as last resort. // TODO(kouhei): Revisit this after // https://github.com/whatwg/html/issues/3295 resolved. base_url = ExecutionContext::From(modulator_->GetScriptState())->BaseURL(); } DCHECK(!base_url.IsNull()); KURL url = Modulator::ResolveModuleSpecifier(specifier, base_url); if (!url.IsValid()) { // Step 2.2.1. "If the result is failure, then:" [spec text] // Step 2.2.2.1. "Let completion be Completion { [[Type]]: throw, [[Value]]: // a new TypeError, [[Target]]: empty }." [spec text] v8::Isolate* isolate = modulator_->GetScriptState()->GetIsolate(); v8::Local<v8::Value> error = V8ThrowException::CreateTypeError( isolate, "Failed to resolve module specifier '" + specifier + "'"); // Step 2.2.2.2. "Perform FinishDynamicImport(referencingScriptOrModule, // specifier, promiseCapability, completion)" [spec text] // https://tc39.github.io/proposal-dynamic-import/#sec-finishdynamicimport // Step 1. "If completion is an abrupt completion, then perform // !Call(promiseCapability.[[Reject]], undefined, <<completion.[[Value]]>>). // " [spec text] promise_resolver->Reject(error); // Step 2.2.2.3. "Abort these steps." [spec text] return; } // Step 2.3. "Let options be the descendant script fetch options for // referencing script's fetch options." [spec text] // // <spec // href="https://html.spec.whatwg.org/multipage/webappapis.html#descendant-script-fetch-options"> // For any given script fetch options options, the descendant script fetch // options are a new script fetch options whose items all have the same // values, except for the integrity metadata, which is instead the empty // string.</spec> ScriptFetchOptions options(referrer_info.Nonce(), IntegrityMetadataSet(), String(), referrer_info.ParserState(), referrer_info.CredentialsMode()); // Step 2.4. "Fetch a module script graph given url, settings object, // "script", and options. Wait until the algorithm asynchronously completes // with result." auto* tree_client = DynamicImportTreeClient::Create(url, modulator_.Get(), promise_resolver); modulator_->FetchTree(url, WebURLRequest::kRequestContextScript, options, tree_client); // Steps 2.[5-8] are implemented at // DynamicImportTreeClient::NotifyModuleLoadFinished. // Step 3. "Return undefined." [spec text] } } // namespace blink
41.225664
142
0.711602
zipated
b6fe175e57a621f051f8f4632fb5265364b39c73
245
hpp
C++
Kmer.hpp
harkoslav/BioInformatics-Project-2019
65ce99e834c73cb1efc8021dbe2c5065050dd7f1
[ "MIT" ]
null
null
null
Kmer.hpp
harkoslav/BioInformatics-Project-2019
65ce99e834c73cb1efc8021dbe2c5065050dd7f1
[ "MIT" ]
null
null
null
Kmer.hpp
harkoslav/BioInformatics-Project-2019
65ce99e834c73cb1efc8021dbe2c5065050dd7f1
[ "MIT" ]
null
null
null
#include <string> #ifndef KMER #define KMER /* Class representing k-mer substring and it's index in the reference string. */ class Kmer { public: std::string str; int index; Kmer(std::string, int i); }; #endif
13.611111
49
0.616327
harkoslav
8e0183724f10147652421c6c5ab724dee80d1cec
1,547
cpp
C++
tests/Game/Utilities/test_Database.cpp
maspe36/WhispererEngine
ff118f91506576e251c16b1f13ba38696c09e7c1
[ "Apache-2.0" ]
3
2017-09-21T18:58:11.000Z
2018-03-07T06:54:17.000Z
tests/Game/Utilities/test_Database.cpp
maspe36/WhispererEngine
ff118f91506576e251c16b1f13ba38696c09e7c1
[ "Apache-2.0" ]
null
null
null
tests/Game/Utilities/test_Database.cpp
maspe36/WhispererEngine
ff118f91506576e251c16b1f13ba38696c09e7c1
[ "Apache-2.0" ]
null
null
null
// // Created by Sam on 11/18/2017. // #include <iostream> #include "../../../build/catch-src/include/catch.hpp" #include "../../../include/Game/Utilities/Database.h" #include "../../../include/Game/Python/Factory.h" TEST_CASE("Create database") { Database database; } TEST_CASE("Verify get CardIDs for Deck SQL") { std::string steamID = "76561198026041712"; std::string deckID = "1"; std::ostringstream expectedQuery; expectedQuery << "SELECT " << R"("Card"."className" )" << "FROM " << R"(public."Card", )" << R"(public."CardToUser", )" << R"(public."CardUserToDeck", )" << R"(public."Deck", )" << R"(public."DeckToUser", )" << R"(public."User" )" << "WHERE " << R"("Card"."id" = "CardToUser"."CardId" AND )" << R"("CardUserToDeck"."CardToUserId" = "CardToUser"."id" AND )" << R"("CardUserToDeck"."DeckId" = "Deck"."id" AND )" << R"("Deck"."id" = "DeckToUser"."DeckId" AND )" << R"("DeckToUser"."UserId" = "User"."id" AND )" << R"("User"."id" = "CardToUser"."UserId" AND )" << R"("User"."steamId" = '76561198026041712' AND "Deck"."id" = 1;)"; Database database; std::string query = database.formatGetDeckCardsQuery(steamID, deckID); REQUIRE(query == expectedQuery.str()); }
35.159091
85
0.477699
maspe36
8e028d821a1e056348937e629dbb15b7cf0b9b05
2,775
hpp
C++
src/Main/mixing.hpp
pwang234/lsms
6044153b6138512093e457bdc0c15c699c831778
[ "BSD-3-Clause" ]
16
2018-04-03T15:35:47.000Z
2022-03-01T03:19:23.000Z
src/Main/mixing.hpp
pwang234/lsms
6044153b6138512093e457bdc0c15c699c831778
[ "BSD-3-Clause" ]
8
2019-07-30T13:59:18.000Z
2022-03-31T17:43:35.000Z
src/Main/mixing.hpp
pwang234/lsms
6044153b6138512093e457bdc0c15c699c831778
[ "BSD-3-Clause" ]
9
2018-06-30T00:30:48.000Z
2022-01-31T09:14:29.000Z
/* -*- c-file-style: "bsd"; c-basic-offset: 2; indent-tabs-mode: nil -*- */ #ifndef LSMS_MIXING_H #define LSMS_MIXING_H #include "Real.hpp" #include "SystemParameters.hpp" #include "SingleSite/AtomData.hpp" // #include "Communication/LSMSCommunication.hpp" #include <vector> #include <deque> #include <cmath> #include "LAPACK.hpp" struct MixingParameters { // Different mixing quantities and algorithms static const int numQuantities = 5; enum mixQuantity {no_mixing = 0, charge = 1, potential = 2, moment_magnitude = 3, moment_direction = 4}; enum mixAlgorithm {noAlgorithm = 0, simple = 1, broyden = 2}; // These parameters specify the which quantity(ies) is (are) being mixed and which algorithm(s) to used. // The correspondances of the indices are specified in mixQuantity. // bool values: // 0 : quantity is not used for mixing // 1 : quantity is used for mixing bool quantity[numQuantities]; mixAlgorithm algorithm[numQuantities]; Real mixingParameter[numQuantities]; }; #include "Communication/LSMSCommunication.hpp" template <typename T> void simpleMixing(T *fold, T* fnew, int n, Real alpha) { if(alpha>1.0) alpha = 1.0; if(alpha<0.0) alpha = 0.0; Real beta = 1.0 - alpha; for(int i=0; i<n; i++) fold[i] = alpha * fnew[i] + beta * fold[i]; } class MomentMixing { public: virtual void update(LSMSCommunication &comm, LSMSSystemParameters &lsms, std::vector<AtomData> &as) = 0; }; class Mixing { public: MomentMixing *momentMixing = nullptr; virtual ~Mixing() = 0; // virtual void updateChargeDensity(LSMSSystemParameters &lsms, AtomData &a) = 0; virtual void updateChargeDensity(LSMSCommunication &comm, LSMSSystemParameters &lsms, std::vector<AtomData> &as) = 0; // virtual void updatePotential(LSMSSystemParameters &lsms, AtomData &a) = 0; virtual void updatePotential(LSMSCommunication &comm, LSMSSystemParameters &lsms, std::vector<AtomData> &as) = 0; void updateMoments(LSMSCommunication &comm, LSMSSystemParameters &lsms, std::vector<AtomData> &as) { if(momentMixing != nullptr) momentMixing->update(comm, lsms, as); else { for(int i=0; i<as.size(); i++) { Real evecMagnitude = std::sqrt(as[i].evec[0] * as[i].evec[0] + as[i].evec[1] * as[i].evec[1] + as[i].evec[2] * as[i].evec[2]); as[i].evecNew[0] = as[i].evec[0] / evecMagnitude; as[i].evecNew[1] = as[i].evec[1] / evecMagnitude; as[i].evecNew[2] = as[i].evec[2] / evecMagnitude; } } } virtual void prepare(LSMSCommunication &comm, LSMSSystemParameters &lsms, std::vector<AtomData> &as) = 0; }; void setupMixing(MixingParameters &mix, Mixing* &mixing, int iprint); #endif
33.035714
119
0.667387
pwang234
8e029220884062c1ec415c51f364117ed200c02a
495
cpp
C++
lib/dtrsm.cpp
langou/latl
df838fb44a1ef5c77b57bf60bd46eaeff8db3492
[ "BSD-3-Clause-Open-MPI" ]
6
2015-12-13T09:10:11.000Z
2022-02-09T23:18:22.000Z
lib/dtrsm.cpp
langou/latl
df838fb44a1ef5c77b57bf60bd46eaeff8db3492
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
lib/dtrsm.cpp
langou/latl
df838fb44a1ef5c77b57bf60bd46eaeff8db3492
[ "BSD-3-Clause-Open-MPI" ]
2
2019-02-01T06:46:36.000Z
2022-02-09T23:18:24.000Z
// // dtrsm.cpp // Linear Algebra Template Library // // Created by Rodney James on 1/1/13. // Copyright (c) 2013 University of Colorado Denver. All rights reserved. // #include "blas.h" #include "trsm.h" using LATL::TRSM; int dtrsm_(char& side, char& uplo, char& trans, char& diag, int &m, int &n, double &alpha, double *A, int &ldA, double *B, int &ldB) { int info=-TRSM<double>(side,uplo,trans,diag,m,n,alpha,A,ldA,B,ldB); if(info>0) xerbla_("DTRSM ",info); return 0; }
23.571429
132
0.650505
langou
8e03ea38d25c8473485c5684c18025236108bbe2
3,260
cpp
C++
source_code/system_sys/source_code/gui/_Sys_Abstract_Base_Wid.cpp
dabachma/ProMaIDes_src
3fa6263c46f89abbdb407f2e1643843d54eb6ccc
[ "BSD-3-Clause" ]
null
null
null
source_code/system_sys/source_code/gui/_Sys_Abstract_Base_Wid.cpp
dabachma/ProMaIDes_src
3fa6263c46f89abbdb407f2e1643843d54eb6ccc
[ "BSD-3-Clause" ]
null
null
null
source_code/system_sys/source_code/gui/_Sys_Abstract_Base_Wid.cpp
dabachma/ProMaIDes_src
3fa6263c46f89abbdb407f2e1643843d54eb6ccc
[ "BSD-3-Clause" ]
null
null
null
//#include "_Sys_Abstract_Base_Wid.h" #include "Sys_Headers_Precompiled.h" #include <QScrollBar> //Default constructor _Sys_Abstract_Base_Wid::_Sys_Abstract_Base_Wid(QWidget *parent): _Sys_Data_Wid(parent) { //Qt stuff this->setupUi(this); this->ptr_database=NULL; this->edit_icon = QIcon(":hydro/Preferences"); this->edit_action = new QAction(this->edit_icon, "Edit", &this->context_menu); this->context_menu.addAction(this->edit_action); this->context_menu.insertSeparator(this->edit_action); this->set_spinBox->setKeyboardTracking(false); QObject::connect(this->edit_action, SIGNAL(triggered()), this, SLOT(show_as_dialog())); } //Default destructor _Sys_Abstract_Base_Wid::~_Sys_Abstract_Base_Wid(void) { } //__________ //public //Set the possibility to edit the data to the given state void _Sys_Abstract_Base_Wid::set_edit_action_disabled(const bool state) { this->edit_action->setDisabled(state); } //Common getter for editable state bool _Sys_Abstract_Base_Wid::is_editable(void) { return this->editable; } //Set the spinbox range in the head widget void _Sys_Abstract_Base_Wid::set_head_spinBox_range(const int max, const int min) { if (max > 0) { this->set_spinBox->setEnabled(true); this->set_spinBox->setRange(min, max); QString qtext; QString qnum; qtext = "(" + qnum.setNum(max) + ")"; this->behind_spinBox_label->setText(qtext); } else { this->set_spinBox->setEnabled(false); } } //Set the head spin box value void _Sys_Abstract_Base_Wid::set_head_spinBox_value(const int value){ this->set_spinBox->setValue(value); QObject::connect(this->set_spinBox, SIGNAL(valueChanged(int )), this, SLOT(recieve_head_spin_box_changed(int )), Qt::QueuedConnection); } //Get a pointer to the head spin box QSpinBox* _Sys_Abstract_Base_Wid::get_ptr_head_spinbox(void){ return this->set_spinBox; } //Set the spinbox text in the head widget void _Sys_Abstract_Base_Wid::set_head_spinBox_text(const string text) { QString qtext = text.c_str(); this->spinBox_label->setText(qtext); } //this method sets the text of the big label on top of the widget void _Sys_Abstract_Base_Wid::set_headLabel_text(const string title) { QString qtext = title.c_str(); this->head_label->setText(qtext); } //this method sets the icon on top of the widget (left) void _Sys_Abstract_Base_Wid::set_headPixmap(const QPixmap pic) { this->head_pixmap->setPixmap(pic); } //Set the child widget void _Sys_Abstract_Base_Wid::set_child(QWidget *child) { this->mainLayout->addWidget(child); } //Set current scroll bars position (vertical, horizontal) void _Sys_Abstract_Base_Wid::set_current_scroll_bar(const int ver_pos, const int hor_pos){ if(this->scroll_area!=NULL){ this->scroll_area->verticalScrollBar()->setSliderPosition(ver_pos); this->scroll_area->horizontalScrollBar()->setSliderPosition(hor_pos); } } //_____________ //private slots //Recieve if the head spin box value is changed void _Sys_Abstract_Base_Wid::recieve_head_spin_box_changed(int index){ if(this->scroll_area==NULL){ emit send_change_widget(index, this->id_item, 0, 0); } else{ emit send_change_widget(index, this->id_item, this->scroll_area->verticalScrollBar()->sliderPosition(), this->scroll_area->horizontalScrollBar()->sliderPosition()); } }
33.265306
166
0.767485
dabachma
8e0a2401c22f8a95df0558dda25b75607c7c5ccb
1,029
cpp
C++
main/minimum-swaps-2-hr/minimum-swaps-2-hr.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/minimum-swaps-2-hr/minimum-swaps-2-hr.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/minimum-swaps-2-hr/minimum-swaps-2-hr.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
#include <algorithm> #include <iostream> #include <iterator> #include <utility> #include <vector> namespace { std::vector<int> read_fixed_zero_permutation() { std::vector<int>::size_type n {}; std::cin >> n; std::vector<int> a (n + 1); std::for_each(std::next(begin(a)), end(a), [](auto& x) noexcept { std::cin >> x; }); return a; } int count_inversions(std::vector<int>& a) noexcept { auto ret = 0; static constexpr auto visited = 0; const auto n = static_cast<int>(a.size()); for (auto i = 1; i != n; ++i) { if (!a[i]) continue; auto j = std::exchange(a[i], visited); while (a[j] != visited) { ++ret; j = std::exchange(a[j], visited); } } return ret; } } int main() { std::ios_base::sync_with_stdio(false); auto a = read_fixed_zero_permutation(); std::cout << count_inversions(a) << '\n'; }
21.4375
63
0.500486
EliahKagan
8e0afdfe586781c6848373db847af2aa113a764e
753
cpp
C++
txttobmp.cpp
DBFritz/ParticleDetections
cd05979c58b79c27259479e948c445867a7a838f
[ "MIT" ]
1
2018-04-05T02:26:57.000Z
2018-04-05T02:26:57.000Z
txttobmp.cpp
DBFritz/ParticleDetections
cd05979c58b79c27259479e948c445867a7a838f
[ "MIT" ]
null
null
null
txttobmp.cpp
DBFritz/ParticleDetections
cd05979c58b79c27259479e948c445867a7a838f
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include "rawImages.hpp" #include "rawFilters.hpp" int main(int argc, char *argv[]) { using namespace std; using namespace raw; if (argc <= 2) { cout << "usage: " << argv[0] << " /path/to/photo.txt /path/to/new/photo.bmp [minValue] [maxValue]"; return -1; } rawPhoto_t photo(argv[1]); pixelValue_t minimum = photo.minimum(); pixelValue_t maximum = photo.maximum(); if (argc>=4) minimum = strtol(argv[3],NULL,10); else cout << "Minimum: " << minimum; if (argc>=5) maximum = strtol(argv[4],NULL,10); else cout << "\tMaximum: " << maximum; photo.toBitMap_grayscale(argv[2],minimum,maximum); //photo.toBitMap_grayscale(argv[2]); return 0; }
25.1
107
0.616202
DBFritz
8e0d4933e3646a21e4003398ef93fed144a2becf
886
cpp
C++
problem-solving-strategies/packing/main.cpp
sunho/algorithms
f1b05d1dba70d8bda884cd80188ce3bcedfeac56
[ "MIT" ]
null
null
null
problem-solving-strategies/packing/main.cpp
sunho/algorithms
f1b05d1dba70d8bda884cd80188ce3bcedfeac56
[ "MIT" ]
1
2021-01-27T05:21:37.000Z
2021-01-27T05:21:37.000Z
problem-solving-strategies/packing/main.cpp
sunho/algorithms
f1b05d1dba70d8bda884cd80188ce3bcedfeac56
[ "MIT" ]
null
null
null
#include <iostream> #include <array> #include <vector> using namespace std; typedef struct { string name; int volume; int desire; } item; array< array<int, 1000>, 100> memory; vector<item> items; int pack(int n, int w) { auto& m = memory[n][w]; if (n == items.size()) { return 0; } if (w == 0) { return 0; } if (m != -1) { return m; } auto i = items[n]; auto cand = pack(n+1, w); if (w >= i.volume) { auto cand2 = pack(n+1, w - i.volume) + i.desire; if (cand2 > cand) { return m = cand2; } } return m = cand; } int main() { int s; cin >> s; for (int i = 0; i < s; i++) { for (auto& a : memory) { fill(a.begin(), a.end(), -1); } items.clear(); int n, w; cin >> n >> w; for (int j = 0; j < n; j++) { item it; cin >> it.name >> it.volume >> it.desire; items.push_back(it); } cout << pack(0, w) << endl; } return 0; }
14.52459
50
0.525959
sunho
8e0ef9add2847f1e92644c7e0dfbc0dd17287b3c
9,211
cpp
C++
HTTPProxy.cpp
kytvi2p/i2pd
73d402525636276ac78aa92ea88535911e21928c
[ "BSD-3-Clause" ]
4
2015-09-28T16:01:55.000Z
2021-04-08T19:26:50.000Z
HTTPProxy.cpp
kytvi2p/i2pd
73d402525636276ac78aa92ea88535911e21928c
[ "BSD-3-Clause" ]
null
null
null
HTTPProxy.cpp
kytvi2p/i2pd
73d402525636276ac78aa92ea88535911e21928c
[ "BSD-3-Clause" ]
null
null
null
#include <cstring> #include <cassert> #include <boost/lexical_cast.hpp> #include <boost/regex.hpp> #include <string> #include <atomic> #include "HTTPProxy.h" #include "util.h" #include "Identity.h" #include "Streaming.h" #include "Destination.h" #include "ClientContext.h" #include "I2PEndian.h" #include "I2PTunnel.h" namespace i2p { namespace proxy { static const size_t http_buffer_size = 8192; class HTTPProxyHandler: public i2p::client::I2PServiceHandler, public std::enable_shared_from_this<HTTPProxyHandler> { private: enum state { GET_METHOD, GET_HOSTNAME, GET_HTTPV, GET_HTTPVNL, //TODO: fallback to finding HOst: header if needed DONE }; void EnterState(state nstate); bool HandleData(uint8_t *http_buff, std::size_t len); void HandleSockRecv(const boost::system::error_code & ecode, std::size_t bytes_transfered); void Terminate(); void AsyncSockRead(); void HTTPRequestFailed(/*std::string message*/); void ExtractRequest(); bool ValidateHTTPRequest(); void HandleJumpServices(); bool CreateHTTPRequest(uint8_t *http_buff, std::size_t len); void SentHTTPFailed(const boost::system::error_code & ecode); void HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream); uint8_t m_http_buff[http_buffer_size]; std::shared_ptr<boost::asio::ip::tcp::socket> m_sock; std::string m_request; //Data left to be sent std::string m_url; //URL std::string m_method; //Method std::string m_version; //HTTP version std::string m_address; //Address std::string m_path; //Path int m_port; //Port state m_state;//Parsing state public: HTTPProxyHandler(HTTPProxyServer * parent, std::shared_ptr<boost::asio::ip::tcp::socket> sock) : I2PServiceHandler(parent), m_sock(sock) { EnterState(GET_METHOD); } ~HTTPProxyHandler() { Terminate(); } void Handle () { AsyncSockRead(); } }; void HTTPProxyHandler::AsyncSockRead() { LogPrint(eLogDebug,"--- HTTP Proxy async sock read"); if(m_sock) { m_sock->async_receive(boost::asio::buffer(m_http_buff, http_buffer_size), std::bind(&HTTPProxyHandler::HandleSockRecv, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } else { LogPrint(eLogError,"--- HTTP Proxy no socket for read"); } } void HTTPProxyHandler::Terminate() { if (Kill()) return; if (m_sock) { LogPrint(eLogDebug,"--- HTTP Proxy close sock"); m_sock->close(); m_sock = nullptr; } Done(shared_from_this()); } /* All hope is lost beyond this point */ //TODO: handle this apropriately void HTTPProxyHandler::HTTPRequestFailed(/*HTTPProxyHandler::errTypes error*/) { static std::string response = "HTTP/1.0 500 Internal Server Error\r\nContent-type: text/html\r\nContent-length: 0\r\n"; boost::asio::async_write(*m_sock, boost::asio::buffer(response,response.size()), std::bind(&HTTPProxyHandler::SentHTTPFailed, shared_from_this(), std::placeholders::_1)); } void HTTPProxyHandler::EnterState(HTTPProxyHandler::state nstate) { m_state = nstate; } void HTTPProxyHandler::ExtractRequest() { LogPrint(eLogDebug,"--- HTTP Proxy method is: ", m_method, "\nRequest is: ", m_url); std::string server=""; std::string port="80"; boost::regex rHTTP("http://(.*?)(:(\\d+))?(/.*)"); boost::smatch m; std::string path; if(boost::regex_search(m_url, m, rHTTP, boost::match_extra)) { server=m[1].str(); if (m[2].str() != "") port=m[3].str(); path=m[4].str(); } LogPrint(eLogDebug,"--- HTTP Proxy server is: ",server, " port is: ", port, "\n path is: ",path); m_address = server; m_port = boost::lexical_cast<int>(port); m_path = path; } bool HTTPProxyHandler::ValidateHTTPRequest() { if ( m_version != "HTTP/1.0" && m_version != "HTTP/1.1" ) { LogPrint(eLogError,"--- HTTP Proxy unsupported version: ", m_version); HTTPRequestFailed(); //TODO: send right stuff return false; } return true; } void HTTPProxyHandler::HandleJumpServices() { static const char * helpermark1 = "?i2paddresshelper="; static const char * helpermark2 = "&i2paddresshelper="; size_t addressHelperPos1 = m_path.rfind (helpermark1); size_t addressHelperPos2 = m_path.rfind (helpermark2); size_t addressHelperPos; if (addressHelperPos1 == std::string::npos) { if (addressHelperPos2 == std::string::npos) return; //Not a jump service else addressHelperPos = addressHelperPos2; } else { if (addressHelperPos2 == std::string::npos) addressHelperPos = addressHelperPos1; else if ( addressHelperPos1 > addressHelperPos2 ) addressHelperPos = addressHelperPos1; else addressHelperPos = addressHelperPos2; } auto base64 = m_path.substr (addressHelperPos + strlen(helpermark1)); base64 = i2p::util::http::urlDecode(base64); //Some of the symbols may be urlencoded LogPrint (eLogDebug,"Jump service for ", m_address, " found at ", base64, ". Inserting to address book"); //TODO: this is very dangerous and broken. We should ask the user before doing anything see http://pastethis.i2p/raw/pn5fL4YNJL7OSWj3Sc6N/ //TODO: we could redirect the user again to avoid dirtiness in the browser i2p::client::context.GetAddressBook ().InsertAddress (m_address, base64); m_path.erase(addressHelperPos); } bool HTTPProxyHandler::CreateHTTPRequest(uint8_t *http_buff, std::size_t len) { ExtractRequest(); //TODO: parse earlier if (!ValidateHTTPRequest()) return false; HandleJumpServices(); m_request = m_method; m_request.push_back(' '); m_request += m_path; m_request.push_back(' '); m_request += m_version; m_request.push_back('\r'); m_request.push_back('\n'); m_request.append("Connection: close\r\n"); m_request.append(reinterpret_cast<const char *>(http_buff),len); return true; } bool HTTPProxyHandler::HandleData(uint8_t *http_buff, std::size_t len) { assert(len); // This should always be called with a least a byte left to parse while (len > 0) { //TODO: fallback to finding HOst: header if needed switch (m_state) { case GET_METHOD: switch (*http_buff) { case ' ': EnterState(GET_HOSTNAME); break; default: m_method.push_back(*http_buff); break; } break; case GET_HOSTNAME: switch (*http_buff) { case ' ': EnterState(GET_HTTPV); break; default: m_url.push_back(*http_buff); break; } break; case GET_HTTPV: switch (*http_buff) { case '\r': EnterState(GET_HTTPVNL); break; default: m_version.push_back(*http_buff); break; } break; case GET_HTTPVNL: switch (*http_buff) { case '\n': EnterState(DONE); break; default: LogPrint(eLogError,"--- HTTP Proxy rejected invalid request ending with: ", ((int)*http_buff)); HTTPRequestFailed(); //TODO: add correct code return false; } break; default: LogPrint(eLogError,"--- HTTP Proxy invalid state: ", m_state); HTTPRequestFailed(); //TODO: add correct code 500 return false; } http_buff++; len--; if (m_state == DONE) return CreateHTTPRequest(http_buff,len); } return true; } void HTTPProxyHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len) { LogPrint(eLogDebug,"--- HTTP Proxy sock recv: ", len); if(ecode) { LogPrint(eLogWarning," --- HTTP Proxy sock recv got error: ", ecode); Terminate(); return; } if (HandleData(m_http_buff, len)) { if (m_state == DONE) { LogPrint(eLogInfo,"--- HTTP Proxy requested: ", m_url); GetOwner()->CreateStream (std::bind (&HTTPProxyHandler::HandleStreamRequestComplete, shared_from_this(), std::placeholders::_1), m_address, m_port); } else AsyncSockRead(); } } void HTTPProxyHandler::SentHTTPFailed(const boost::system::error_code & ecode) { if (!ecode) Terminate(); else { LogPrint (eLogError,"--- HTTP Proxy Closing socket after sending failure because: ", ecode.message ()); Terminate(); } } void HTTPProxyHandler::HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream) { if (stream) { if (Kill()) return; LogPrint (eLogInfo,"--- HTTP Proxy New I2PTunnel connection"); auto connection = std::make_shared<i2p::client::I2PTunnelConnection>(GetOwner(), m_sock, stream); GetOwner()->AddHandler (connection); connection->I2PConnect (reinterpret_cast<const uint8_t*>(m_request.data()), m_request.size()); Done(shared_from_this()); } else { LogPrint (eLogError,"--- HTTP Proxy Issue when creating the stream, check the previous warnings for more info."); HTTPRequestFailed(); // TODO: Send correct error message host unreachable } } HTTPProxyServer::HTTPProxyServer(int port, std::shared_ptr<i2p::client::ClientDestination> localDestination): TCPIPAcceptor(port, localDestination ? localDestination : i2p::client::context.GetSharedLocalDestination ()) { } std::shared_ptr<i2p::client::I2PServiceHandler> HTTPProxyServer::CreateHandler(std::shared_ptr<boost::asio::ip::tcp::socket> socket) { return std::make_shared<HTTPProxyHandler> (this, socket); } } }
30.703333
140
0.685159
kytvi2p
8e117d7bc41858c16639b98bc114ae97ae96e560
11,765
cpp
C++
src/xrGame/CarInput.cpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
2
2015-02-23T10:43:02.000Z
2015-06-11T14:45:08.000Z
src/xrGame/CarInput.cpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
17
2022-01-25T08:58:23.000Z
2022-03-28T17:18:28.000Z
src/xrGame/CarInput.cpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
1
2015-06-05T20:04:00.000Z
2015-06-05T20:04:00.000Z
#include "StdAfx.h" #pragma hdrstop #ifdef DEBUG #include "PHDebug.h" #endif #include "alife_space.h" #include "Hit.h" #include "PHDestroyable.h" #include "Car.h" #include "Actor.h" #include "CameraLook.h" #include "CameraFirstEye.h" #include "script_entity_action.h" #include "xrEngine/xr_level_controller.h" #include "Include/xrRender/Kinematics.h" #include "Level.h" #include "CarWeapon.h" void CCar::OnAxisMove(float x, float y, float scale, bool invert) { CCameraBase* C = active_camera; if (!fis_zero(x)) { const float d = x * scale; C->Move((d < 0) ? kLEFT : kRIGHT, _abs(d)); } if (!fis_zero(y)) { const float d = (invert ? -1.f : 1.f) * y * scale * 3.f / 4.f; C->Move((d > 0) ? kUP : kDOWN, _abs(d)); } } void CCar::OnMouseMove(int dx, int dy) { if (Remote()) return; const float scale = (active_camera->f_fov / g_fov) * psMouseSens * psMouseSensScale / 50.f; OnAxisMove(float(dx), float(dy), scale, psMouseInvert.test(1)); } bool CCar::bfAssignMovement(CScriptEntityAction* tpEntityAction) { if (tpEntityAction->m_tMovementAction.m_bCompleted) return (false); u32 l_tInput = tpEntityAction->m_tMovementAction.m_tInputKeys; vfProcessInputKey(kFWD, !!(l_tInput & CScriptMovementAction::eInputKeyForward)); vfProcessInputKey(kBACK, !!(l_tInput & CScriptMovementAction::eInputKeyBack)); vfProcessInputKey(kL_STRAFE, !!(l_tInput & CScriptMovementAction::eInputKeyLeft)); vfProcessInputKey(kR_STRAFE, !!(l_tInput & CScriptMovementAction::eInputKeyRight)); vfProcessInputKey(kACCEL, !!(l_tInput & CScriptMovementAction::eInputKeyShiftUp)); vfProcessInputKey(kCROUCH, !!(l_tInput & CScriptMovementAction::eInputKeyShiftDown)); vfProcessInputKey(kJUMP, !!(l_tInput & CScriptMovementAction::eInputKeyBreaks)); if (!!(l_tInput & CScriptMovementAction::eInputKeyEngineOn)) StartEngine(); if (!!(l_tInput & CScriptMovementAction::eInputKeyEngineOff)) StopEngine(); // if (_abs(tpEntityAction->m_tMovementAction.m_fSpeed) > EPS_L) // m_current_rpm = _abs(tpEntityAction->m_tMovementAction.m_fSpeed*m_current_gear_ratio); return (true); } bool CCar::bfAssignObject(CScriptEntityAction* tpEntityAction) { CScriptObjectAction& l_tObjectAction = tpEntityAction->m_tObjectAction; if (l_tObjectAction.m_bCompleted || !xr_strlen(l_tObjectAction.m_caBoneName)) return ((l_tObjectAction.m_bCompleted = true) == false); s16 l_sBoneID = smart_cast<IKinematics*>(Visual())->LL_BoneID(l_tObjectAction.m_caBoneName); if (is_Door(l_sBoneID)) { switch (l_tObjectAction.m_tGoalType) { case MonsterSpace::eObjectActionActivate: { if (!DoorOpen(l_sBoneID)) return ((l_tObjectAction.m_bCompleted = true) == false); break; } case MonsterSpace::eObjectActionDeactivate: { if (!DoorClose(l_sBoneID)) return ((l_tObjectAction.m_bCompleted = true) == false); break; } case MonsterSpace::eObjectActionUse: { if (!DoorSwitch(l_sBoneID)) return ((l_tObjectAction.m_bCompleted = true) == false); break; } default: return ((l_tObjectAction.m_bCompleted = true) == false); } return (false); } SCarLight* light = NULL; if (m_lights.findLight(l_sBoneID, light)) { switch (l_tObjectAction.m_tGoalType) { case MonsterSpace::eObjectActionActivate: { light->TurnOn(); return ((l_tObjectAction.m_bCompleted = true) == false); } case MonsterSpace::eObjectActionDeactivate: { light->TurnOff(); return ((l_tObjectAction.m_bCompleted = true) == false); } case MonsterSpace::eObjectActionUse: { light->Switch(); return ((l_tObjectAction.m_bCompleted = true) == false); } default: return ((l_tObjectAction.m_bCompleted = true) == false); } } return (false); } void CCar::vfProcessInputKey(int iCommand, bool bPressed) { if (bPressed) OnKeyboardPress(iCommand); else OnKeyboardRelease(iCommand); } void CCar::OnKeyboardPress(int cmd) { if (Remote()) return; switch (cmd) { case kCAM_1: OnCameraChange(ectFirst); break; case kCAM_2: OnCameraChange(ectChase); break; case kCAM_3: OnCameraChange(ectFree); break; case kACCEL: TransmissionUp(); break; case kCROUCH: TransmissionDown(); break; case kFWD: PressForward(); break; case kBACK: PressBack(); break; case kR_STRAFE: PressRight(); if (OwnerActor()) OwnerActor()->steer_Vehicle(1); break; case kL_STRAFE: PressLeft(); if (OwnerActor()) OwnerActor()->steer_Vehicle(-1); break; case kJUMP: PressBreaks(); break; case kENGINE: [[fallthrough]]; case kDETECTOR: SwitchEngine(); break; case kTORCH: m_lights.SwitchHeadLights(); break; case kUSE: break; }; } void CCar::OnKeyboardRelease(int cmd) { if (Remote()) return; switch (cmd) { case kACCEL: break; case kFWD: ReleaseForward(); break; case kBACK: ReleaseBack(); break; case kL_STRAFE: ReleaseLeft(); if (OwnerActor()) OwnerActor()->steer_Vehicle(0); break; case kR_STRAFE: ReleaseRight(); if (OwnerActor()) OwnerActor()->steer_Vehicle(0); break; case kJUMP: ReleaseBreaks(); break; }; } void CCar::OnKeyboardHold(int cmd) { if (Remote()) return; switch (cmd) { case kCAM_ZOOM_IN: case kCAM_ZOOM_OUT: case kUP: case kDOWN: case kLEFT: case kRIGHT: active_camera->Move(cmd); break; /* case kFWD: if (ectFree==active_camera->tag) active_camera->Move(kUP); else m_vCamDeltaHP.y += active_camera->rot_speed.y*Device.fTimeDelta; break; case kBACK: if (ectFree==active_camera->tag) active_camera->Move(kDOWN); else m_vCamDeltaHP.y -= active_camera->rot_speed.y*Device.fTimeDelta; break; case kL_STRAFE: if (ectFree==active_camera->tag) active_camera->Move(kLEFT); else m_vCamDeltaHP.x -= active_camera->rot_speed.x*Device.fTimeDelta; break; case kR_STRAFE: if (ectFree==active_camera->tag) active_camera->Move(kRIGHT); else m_vCamDeltaHP.x += active_camera->rot_speed.x*Device.fTimeDelta; break; */ } // clamp(m_vCamDeltaHP.x, -PI_DIV_2, PI_DIV_2); // clamp(m_vCamDeltaHP.y, active_camera->lim_pitch.x, active_camera->lim_pitch.y); } void CCar::OnControllerPress(int cmd, float x, float y) { if (Remote()) return; switch (cmd) { case kLOOK_AROUND: { const float scale = (active_camera->f_fov / g_fov) * psControllerStickSens * psControllerStickSensScale / 50.f; OnAxisMove(x, y, scale, psControllerInvertY.test(1)); break; } case kMOVE_AROUND: { if (!fis_zero(x)) { if (x > 35.f) OnKeyboardPress(kR_STRAFE); else if (x < -35.f) OnKeyboardPress(kL_STRAFE); } if (!fis_zero(y)) { if (y > 35.f) OnKeyboardPress(kBACK); else if (y < -35.f) OnKeyboardPress(kFWD); } break; } default: OnKeyboardPress(cmd); break; }; } void CCar::OnControllerRelease(int cmd, float x, float y) { if (Remote()) return; switch (cmd) { case kLOOK_AROUND: break; case kMOVE_AROUND: OnKeyboardRelease(kFWD); OnKeyboardRelease(kBACK); OnKeyboardRelease(kL_STRAFE); OnKeyboardRelease(kR_STRAFE); break; default: OnKeyboardPress(cmd); break; }; } void CCar::OnControllerHold(int cmd, float x, float y) { if (Remote()) return; switch (cmd) { case kLOOK_AROUND: { const float scale = (active_camera->f_fov / g_fov) * psControllerStickSens * psControllerStickSensScale / 50.f; OnAxisMove(x, y, scale, psControllerInvertY.test(1)); break; } case kMOVE_AROUND: { if (!fis_zero(x)) { if (x > 35.f && !rsp) // right { OnKeyboardRelease(kL_STRAFE); OnKeyboardPress(kR_STRAFE); } else if (x < -35.f && !lsp) // left { OnKeyboardRelease(kR_STRAFE); OnKeyboardPress(kL_STRAFE); } else { if (lsp) OnKeyboardRelease(kL_STRAFE); if (rsp) OnKeyboardRelease(kR_STRAFE); } } if (!fis_zero(y)) { if (y > 35.f && !bkp) // backward { OnKeyboardRelease(kFWD); OnKeyboardPress(kBACK); } else if (y < -35.f && !fwp) // forward { OnKeyboardRelease(kBACK); OnKeyboardPress(kFWD); } else { if (fwp) OnKeyboardRelease(kFWD); if (bkp) OnKeyboardRelease(kBACK); } } break; } default: OnKeyboardPress(cmd); break; } } void CCar::OnControllerAttitudeChange(Fvector change) { const float scale = (active_camera->f_fov / g_fov) * psControllerSensorSens / 50.f; OnAxisMove(change.x, change.y, scale, psControllerInvertY.test(1)); } void CCar::Action(u16 id, u32 flags) { if (m_car_weapon) m_car_weapon->Action(id, flags); } void CCar::SetParam(int id, Fvector2 val) { if (m_car_weapon) m_car_weapon->SetParam(id, val); } void CCar::SetParam(int id, Fvector val) { if (m_car_weapon) m_car_weapon->SetParam(id, val); } bool CCar::WpnCanHit() { if (m_car_weapon) return m_car_weapon->AllowFire(); return false; } float CCar::FireDirDiff() { if (m_car_weapon) return m_car_weapon->FireDirDiff(); return 0.0f; } #include "script_game_object.h" #include "script_game_object_impl.h" #include "car_memory.h" #include "visual_memory_manager.h" bool CCar::isObjectVisible(CScriptGameObject* O_) { if (m_memory) { return m_memory->visual().visible_now(&O_->object()); } else { if (!O_) { Msg("Attempt to call CCar::isObjectVisible method wihth passed NULL parameter"); return false; } IGameObject* O = &O_->object(); Fvector dir_to_object; Fvector to_point; O->Center(to_point); Fvector from_point; Center(from_point); if (HasWeapon()) { from_point.y = XFORM().c.y + m_car_weapon->_height(); } dir_to_object.sub(to_point, from_point).normalize_safe(); float ray_length = from_point.distance_to(to_point); BOOL res = Level().ObjectSpace.RayTest(from_point, dir_to_object, ray_length, collide::rqtStatic, NULL, NULL); return (0 == res); } } bool CCar::HasWeapon() { return (m_car_weapon != NULL); } Fvector CCar::CurrentVel() { Fvector lin_vel; m_pPhysicsShell->get_LinearVel(lin_vel); return lin_vel; }
26.860731
119
0.58317
clayne
8e14d135e6b5fcd11430de516e3b4204aab09577
1,179
cpp
C++
GazeTracker/GazeTracker_Qt/GazeTracker.cpp
bernhardrieder/GazeTracker
b468a03cb986a4950ee1d2a49df759e17a80c5cc
[ "MIT" ]
null
null
null
GazeTracker/GazeTracker_Qt/GazeTracker.cpp
bernhardrieder/GazeTracker
b468a03cb986a4950ee1d2a49df759e17a80c5cc
[ "MIT" ]
null
null
null
GazeTracker/GazeTracker_Qt/GazeTracker.cpp
bernhardrieder/GazeTracker
b468a03cb986a4950ee1d2a49df759e17a80c5cc
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "GazeTracker.h" GazeTracker::GazeTracker(int argc, char* argv[]) : qApplication(argc, argv) { CreateDirectory(LPWSTR(std::wstring(L"C:/GazeTracker").c_str()), NULL); CreateDirectory(LPWSTR(std::wstring(L"C:/GazeTracker/Output").c_str()), NULL); CreateDirectory(LPWSTR(std::wstring(L"C:/GazeTracker/tmp").c_str()), NULL); //DONT CHANGE CreateDirectory(LPWSTR(std::wstring(L"C:/GazeTracker/tmp/template_matching").c_str()), NULL); //DONT CHANGE - OR CHANGE AND CHANGE DIR IN FACEDETECTION TEMPLATE MATCHING strings gt::DataTrackingSystem::GetInstance()->DefaultStorageFolder = "C:\\GazeTracker\\Output"; } GazeTracker::~GazeTracker() { gt::DataTrackingSystem::GetInstance()->CloseFile(); } void GazeTracker::StartApplication() const { gt::UISystem::GetInstance()->GetStartUI()->show(); //gt::UISystem::GetInstance()->GetGazeTrackerUI()->show(); } void GazeTracker::StopApplication() const { } bool GazeTracker::IsDetecting() const { return gt::GazeTrackerManager::GetInstance()->GetActiveState() == gt::Running; //should check if application is in config or running mode } int GazeTracker::exec() const { return qApplication.exec(); }
31.026316
178
0.737913
bernhardrieder
8e14d6363768e8360a9e08995d1ef621c8b61e7a
2,508
cpp
C++
beringei/lib/BucketUtils.cpp
pidb/Gorilla
75c3002b179d99c8709323d605e7d4b53484035c
[ "BSD-3-Clause" ]
2,780
2016-12-22T19:25:26.000Z
2018-05-21T11:29:42.000Z
beringei/lib/BucketUtils.cpp
pidb/Gorilla
75c3002b179d99c8709323d605e7d4b53484035c
[ "BSD-3-Clause" ]
57
2016-12-23T09:22:18.000Z
2018-05-04T06:26:48.000Z
beringei/lib/BucketUtils.cpp
pidb/Gorilla
75c3002b179d99c8709323d605e7d4b53484035c
[ "BSD-3-Clause" ]
254
2016-12-22T20:53:12.000Z
2018-05-16T06:14:10.000Z
/** * Copyright (c) 2016-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 "BucketUtils.h" #include <folly/Format.h> #include <glog/logging.h> DEFINE_int32(gorilla_shards, 100, "Number of maps for gorilla to use"); namespace facebook { namespace gorilla { uint32_t BucketUtils::bucket(uint64_t unixTime, uint64_t windowSize, int shardId) { if (unixTime < shardId * windowSize / FLAGS_gorilla_shards) { LOG(ERROR) << folly::sformat( "Shard: {}. Window size: {}. TS {} falls into a negative bucket", shardId, windowSize, unixTime); return 0; } return (uint32_t)( (unixTime - (shardId * windowSize / FLAGS_gorilla_shards)) / windowSize); } uint64_t BucketUtils::timestamp(uint32_t bucket, uint64_t windowSize, int shardId) { return bucket * windowSize + (shardId * windowSize / FLAGS_gorilla_shards); } uint64_t BucketUtils::duration(uint32_t buckets, uint64_t windowSize) { return buckets * windowSize; } uint32_t BucketUtils::buckets(uint64_t duration, uint64_t windowSize) { return duration / windowSize; } uint64_t BucketUtils::floorTimestamp( uint64_t unixTime, uint64_t windowSize, int shardId) { return timestamp(bucket(unixTime, windowSize, shardId), windowSize, shardId); } uint64_t BucketUtils::ceilTimestamp( uint64_t unixTime, uint64_t windowSize, int shardId) { // Check against first timestamp to avoid underflow, should never happen. auto firstTimestamp = timestamp(0, windowSize, shardId); if (unixTime <= firstTimestamp) { return firstTimestamp; } auto b = bucket(unixTime - 1, windowSize, shardId); return timestamp(b + 1, windowSize, shardId); } uint32_t BucketUtils::alignedBucket(uint64_t unixTime, uint64_t windowSize) { return (uint32_t)(unixTime / windowSize); } uint64_t BucketUtils::alignedTimestamp(uint32_t bucket, uint64_t windowSize) { return bucket * windowSize; } uint64_t BucketUtils::floorAlignedTimestamp( uint64_t unixTime, uint64_t windowSize) { return alignedTimestamp(alignedBucket(unixTime, windowSize), windowSize); } bool BucketUtils::isAlignedBucketTimestamp( uint64_t unixTime, uint64_t windowSize) { return unixTime % windowSize == 0; } } // namespace gorilla } // namespace facebook
28.179775
79
0.732057
pidb
8e1749e57da027882ab38db68c14e6d9f1808363
2,545
hpp
C++
storage/include/s3/s3_metrics.hpp
definitelyNotFBI/utt
1695e3a1f81848e19b042cdc4db9cf1d263c26a9
[ "Apache-2.0" ]
340
2018-08-27T16:30:45.000Z
2022-03-28T14:31:44.000Z
storage/include/s3/s3_metrics.hpp
definitelyNotFBI/utt
1695e3a1f81848e19b042cdc4db9cf1d263c26a9
[ "Apache-2.0" ]
706
2018-09-02T17:50:32.000Z
2022-03-31T13:03:15.000Z
storage/include/s3/s3_metrics.hpp
glevkovich/concord-bft
a1b7b57472f5375230428d16c613a760b33233fa
[ "Apache-2.0" ]
153
2018-08-29T05:37:25.000Z
2022-03-23T14:08:45.000Z
#pragma once #include "Metrics.hpp" #include "sliver.hpp" #include "Logger.hpp" namespace concord::storage::s3 { class Metrics { public: Metrics() : metrics_component{concordMetrics::Component("s3", std::make_shared<concordMetrics::Aggregator>())}, num_keys_transferred{metrics_component.RegisterCounter("keys_transferred")}, bytes_transferred{ metrics_component.RegisterCounter("bytes_transferred"), }, last_saved_block_id_{ metrics_component.RegisterGauge("last_saved_block_id", 0), } { metrics_component.Register(); } void updateLastSavedBlockId(const concordUtils::Sliver& key) { if (!isBlockKey(key.string_view())) return; // tokenize the key std::vector<std::string> elems; std::istringstream key_stream(key.toString()); std::string e; while (std::getline(key_stream, e, '/')) { elems.push_back(e); } // There should be at least two elements - block id and key // the format is: "PREFIX/BLOCK_ID/KEY", where PREFIX is optional if (elems.size() < 2) return; uint64_t lastSavedBlockVal = 0; try { lastSavedBlockVal = stoull(elems[elems.size() - 2]); } catch (std::invalid_argument& e) { LOG_ERROR(logger_, "Can't convert lastSavedBlockId (" << elems[elems.size() - 2] << ") to numeric value."); return; } catch (std::out_of_range& e) { LOG_ERROR(logger_, "lastSavedBlockId value (" << elems[elems.size() - 2] << ") doesn't fit in unsigned 64bit integer."); return; } catch (std::exception& e) { LOG_ERROR(logger_, "Unexpected error occured while converting lastSavedBlockId (" << elems[elems.size() - 2] << ") to numeric value."); return; } last_saved_block_id_.Get().Set(lastSavedBlockVal); } uint64_t getLastSavedBlockId() { return last_saved_block_id_.Get().Get(); } concordMetrics::Component metrics_component; concordMetrics::CounterHandle num_keys_transferred; concordMetrics::CounterHandle bytes_transferred; private: // This function "guesses" if metadata or block is being updated. // In the latter case it updates the metric bool isBlockKey(std::string_view key) { return key.find("metadata") == std::string_view::npos; } concordMetrics::GaugeHandle last_saved_block_id_; logging::Logger logger_ = logging::getLogger("concord.storage.s3.metrics"); }; } // namespace concord::storage::s3
34.391892
117
0.653045
definitelyNotFBI
8e1d27d157cca0f5c76c77c661ae3e821bd5b046
1,641
hh
C++
transformations/base/ViewHistBased.hh
gnafit/gna
c1a58dac11783342c97a2da1b19c97b85bce0394
[ "MIT" ]
5
2019-10-14T01:06:57.000Z
2021-02-02T16:33:06.000Z
transformations/base/ViewHistBased.hh
gnafit/gna
c1a58dac11783342c97a2da1b19c97b85bce0394
[ "MIT" ]
null
null
null
transformations/base/ViewHistBased.hh
gnafit/gna
c1a58dac11783342c97a2da1b19c97b85bce0394
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include "GNAObject.hh" #include "GNAObjectBind1N.hh" #include <boost/optional.hpp> namespace GNA{ namespace GNAObjectTemplates{ template<typename FloatType> class ViewHistBasedT: public GNAObjectBind1N<FloatType>, public TransformationBind<ViewHistBasedT<FloatType>,FloatType,FloatType> { private: using BaseClass = GNAObjectT<FloatType,FloatType>; using typename BaseClass::TypesFunctionArgs; using typename BaseClass::FunctionArgs; public: using ViewHistBasedType = ViewHistBasedT<FloatType>; using typename BaseClass::SingleOutput; using TransformationDescriptor = typename BaseClass::TransformationDescriptorType; using OutputDescriptor = typename BaseClass::OutputDescriptor; ViewHistBasedT(FloatType threshold, FloatType ceiling); ViewHistBasedT(SingleOutput& output, FloatType threshold, FloatType ceiling); void set(SingleOutput& hist){ hist.single() >> this->transformations.front().inputs.front(); } TransformationDescriptor add_transformation(const std::string& name=""); protected: void histTypes(TypesFunctionArgs& fargs); void types(TypesFunctionArgs& fargs); void init(); boost::optional<FloatType> m_threshold; boost::optional<FloatType> m_ceiling; boost::optional<size_t> m_start; boost::optional<size_t> m_len; size_t m_full_length; }; } }
34.914894
104
0.645338
gnafit
8e1d3a807ecef95bcc4335e51e90a4ef97c347d4
3,767
cpp
C++
src/HistoryImp.cpp
esrille/escudo
1ba68f6930f1ddb97385a5b488644b6dfa132152
[ "Apache-2.0" ]
29
2015-01-25T15:12:02.000Z
2021-12-01T17:58:17.000Z
src/HistoryImp.cpp
esrille/escudo
1ba68f6930f1ddb97385a5b488644b6dfa132152
[ "Apache-2.0" ]
null
null
null
src/HistoryImp.cpp
esrille/escudo
1ba68f6930f1ddb97385a5b488644b6dfa132152
[ "Apache-2.0" ]
7
2015-04-15T02:05:21.000Z
2020-06-16T03:53:37.000Z
/* * Copyright 2011-2013 Esrille 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 "HistoryImp.h" #include <org/w3c/dom/html/Location.h> #include <iostream> #include "utf.h" #include "DocumentImp.h" #include "WindowProxy.h" namespace org { namespace w3c { namespace dom { namespace bootstrap { HistoryImp:: SessionHistoryEntry::SessionHistoryEntry(const URL& url, const WindowPtr& window) : url(url), window(window) { } HistoryImp:: SessionHistoryEntry::SessionHistoryEntry(const WindowPtr& window) : url(window->getDocument()->getURL()), window(window) { } HistoryImp:: SessionHistoryEntry::SessionHistoryEntry(const SessionHistoryEntry& other) : url(other.url), window(other.window) { } void HistoryImp::removeAfterCurrent() { if (!sessionHistory.empty()) { if (!replace) { Document currentDocument = sessionHistory.back().window->getDocument(); if (sessionHistory.size() == 1 && currentDocument.getURL() == u"about:blank") replace = true; else if (currentDocument.getReadyState() != u"complete") replace = true; } sessionHistory.erase(sessionHistory.begin() + currentSession + (replace ? 0 : 1), sessionHistory.end()); } } void HistoryImp::update(const URL& url, const WindowPtr& window) { removeAfterCurrent(); replace = false; SessionHistoryEntry e(url, window); sessionHistory.push_back(e); currentSession = getLength() - 1; if (auto document = window->getDocument()) document->setURL(static_cast<std::u16string>(url)); } void HistoryImp::update(const WindowPtr& window) { removeAfterCurrent(); replace = false; SessionHistoryEntry e(window); sessionHistory.push_back(e); currentSession = getLength() - 1; } int HistoryImp::getLength() { return static_cast<int>(sessionHistory.size()); } Any HistoryImp::getState() { // TODO: implement me! return 0; } void HistoryImp::go() { if (sessionHistory.empty()) return; SessionHistoryEntry& e = sessionHistory[currentSession]; if (auto document = e.window->getDocument()) document->getLocation().reload(); } void HistoryImp::go(int delta) { if (sessionHistory.empty()) return; if (delta == 0) { go(); return; } int nextSession = currentSession + delta; if (getLength() <= nextSession) nextSession = getLength() - 1; else if (nextSession < 0) nextSession = 0; if (nextSession != currentSession) { currentSession = nextSession; SessionHistoryEntry& e = sessionHistory[currentSession]; window->setWindowPtr(e.window); } } void HistoryImp::back() { go(-1); } void HistoryImp::forward() { go(1); } void HistoryImp::pushState(Any data, const std::u16string& title) { // TODO: implement me! } void HistoryImp::pushState(Any data, const std::u16string& title, const std::u16string& url) { // TODO: implement me! } void HistoryImp::replaceState(Any data, const std::u16string& title) { // TODO: implement me! } void HistoryImp::replaceState(Any data, const std::u16string& title, const std::u16string& url) { // TODO: implement me! } } } } }
22.692771
112
0.667109
esrille
8e219bc206519d8fe58f1ff69aa00afd382bec18
294
cc
C++
solution_06/src/DetParticle.cc
williamhbell/HepCppIntro
975535e4daef8fa25f143731db62304a3812ee5f
[ "MIT" ]
null
null
null
solution_06/src/DetParticle.cc
williamhbell/HepCppIntro
975535e4daef8fa25f143731db62304a3812ee5f
[ "MIT" ]
null
null
null
solution_06/src/DetParticle.cc
williamhbell/HepCppIntro
975535e4daef8fa25f143731db62304a3812ee5f
[ "MIT" ]
null
null
null
/* W. H. Bell ** A simple detector particle container class */ #include "DetParticle.h" #include "Particle.h" DetParticle::DetParticle (int id, double *p3vec, int trackId): Particle(id, p3vec), m_trackId(trackId) { } int DetParticle::trackId(void) { return m_trackId; }
16.333333
45
0.670068
williamhbell
8e2507614b8b9737a2144fc1895036e25ae7e119
32,910
cpp
C++
sdktools/sdv/sdview.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
sdktools/sdv/sdview.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
sdktools/sdv/sdview.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/***************************************************************************** * * sdview.cpp * * Lame SD Viewer app. * *****************************************************************************/ #include "sdview.h" HINSTANCE g_hinst; HCURSOR g_hcurWait; HCURSOR g_hcurArrow; HCURSOR g_hcurAppStarting; LONG g_lThreads; UINT g_wShowWindow; CGlobals GlobalSettings; /***************************************************************************** * * Stubs - will be filled in with goodies eventually * *****************************************************************************/ DWORD CALLBACK CFileOut_ThreadProc(LPVOID lpParameter) { MessageBox(NULL, RECAST(LPTSTR, lpParameter), TEXT("fileout"), MB_OK); return EndThreadTask(0); } #if 0 DWORD CALLBACK COpened_ThreadProc(LPVOID lpParameter) { MessageBox(NULL, RECAST(LPTSTR, lpParameter), TEXT("opened"), MB_OK); return EndThreadTask(0); } /***************************************************************************** * * Eschew the C runtime. Also, bonus-initialize memory to zero. * *****************************************************************************/ void * __cdecl operator new(size_t cb) { return RECAST(LPVOID, LocalAlloc(LPTR, cb)); } void __cdecl operator delete(void *pv) { LocalFree(RECAST(HLOCAL, pv)); } int __cdecl _purecall(void) { return 0; } #endif /***************************************************************************** * * Assertion goo * *****************************************************************************/ #ifdef DEBUG void AssertFailed(char *psz, char *pszFile, int iLine) { static BOOL fAsserting = FALSE; if (!fAsserting) { fAsserting = TRUE; String strTitle(TEXT("Assertion failed - ")); strTitle << pszFile << TEXT(" - line ") << iLine; MessageBox(NULL, psz, strTitle, MB_OK); fAsserting = FALSE; } } #endif /***************************************************************************** * * LaunchThreadTask * *****************************************************************************/ BOOL LaunchThreadTask(LPTHREAD_START_ROUTINE pfn, LPCTSTR pszArgs) { BOOL fSuccess = FALSE; LPTSTR psz = StrDup(pszArgs); if (psz) { InterlockedIncrement(&g_lThreads); if (_QueueUserWorkItem(pfn, CCAST(LPTSTR, psz), WT_EXECUTELONGFUNCTION)) { fSuccess = TRUE; } else { LocalFree(psz); InterlockedDecrement(&g_lThreads); } } return fSuccess; } /***************************************************************************** * * EndThreadTask * * When a task finishes, exit with "return EndThreadTask(dwExitCode)". * This decrements the count of active thread tasks and terminates * the process if this is the last one. * *****************************************************************************/ DWORD EndThreadTask(DWORD dwExitCode) { if (InterlockedDecrement(&g_lThreads) <= 0) { ExitProcess(dwExitCode); } return dwExitCode; } /***************************************************************************** * * Listview stuff * *****************************************************************************/ int ListView_GetCurSel(HWND hwnd) { return ListView_GetNextItem(hwnd, -1, LVNI_FOCUSED); } void ListView_SetCurSel(HWND hwnd, int iIndex) { ListView_SetItemState(hwnd, iIndex, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); } int ListView_GetSubItemText(HWND hwnd, int iItem, int iSubItem, LPTSTR pszBuf, int cch) { LVITEM lvi; lvi.iSubItem = iSubItem; lvi.pszText= pszBuf; lvi.cchTextMax = cch; return (int)::SendMessage(hwnd, LVM_GETITEMTEXT, iItem, RECAST(LPARAM, &lvi)); } void ChangeTabsToSpaces(LPTSTR psz) { while ((psz = StrChr(psz, TEXT('\t'))) != NULL) *psz = TEXT(' '); } /***************************************************************************** * * LoadPopupMenu * *****************************************************************************/ HMENU LoadPopupMenu(LPCTSTR pszMenu) { HMENU hmenuParent = LoadMenu(g_hinst, pszMenu); if (hmenuParent) { HMENU hmenuPopup = GetSubMenu(hmenuParent, 0); RemoveMenu(hmenuParent, 0, MF_BYPOSITION); DestroyMenu(hmenuParent); return hmenuPopup; } else { return NULL; } } /***************************************************************************** * * EnableDisableOrRemoveMenuItem * * Enable, disable or remove, accordingly. * *****************************************************************************/ void EnableDisableOrRemoveMenuItem(HMENU hmenu, UINT id, BOOL fEnable, BOOL fDelete) { if (fEnable) { EnableMenuItem(hmenu, id, MF_BYCOMMAND | MF_ENABLED); } else if (fDelete) { DeleteMenu(hmenu, id, MF_BYCOMMAND); } else { EnableMenuItem(hmenu, id, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } } /***************************************************************************** * * MakeMenuPretty * * Remove separators at the top and at the bottom, and collapse * multiple consecutive separators. * *****************************************************************************/ void MakeMenuPretty(HMENU hmenu) { BOOL fPrevSep = TRUE; int iCount = GetMenuItemCount(hmenu); for (int iItem = 0; iItem < iCount; iItem++) { UINT uiState = GetMenuState(hmenu, 0, MF_BYPOSITION); if (uiState & MF_SEPARATOR) { if (fPrevSep) { DeleteMenu(hmenu, iItem, MF_BYPOSITION); iCount--; iItem--; // Will be incremented by loop control } fPrevSep = TRUE; } else { fPrevSep = FALSE; } } if (iCount && fPrevSep) { DeleteMenu(hmenu, iCount - 1, MF_BYPOSITION); } } /***************************************************************************** * * JiggleMouse * * * Jiggle the mouse to force a cursor recomputation. * *****************************************************************************/ void JiggleMouse() { POINT pt; if (GetCursorPos(&pt)) { SetCursorPos(pt.x, pt.y); } } /***************************************************************************** * * BGTask * *****************************************************************************/ BGTask::~BGTask() { if (_hDone) { /* * Theoretically we don't need to pump messages because * we destroyed all the windows we created so our thread * should be clear of any windows. Except that Cicero will * secretly create a window on our thread, so we have * to pump messages anyway... */ while (MsgWaitForMultipleObjects(1, &_hDone, FALSE, INFINITE, QS_ALLINPUT) == WAIT_OBJECT_0+1) { MSG msg; while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } } CloseHandle(_hDone); } } BOOL BGTask::BGStartTask(LPTHREAD_START_ROUTINE pfn, LPVOID Context) { ASSERT(!_fPending); if (BGConstructed()) { /* * Must reset before queueing the work item to avoid a race where * the work item completes before we return from the Queue call. */ ResetEvent(_hDone); _fPending = QueueUserWorkItem(pfn, Context, WT_EXECUTELONGFUNCTION); if (_fPending) { JiggleMouse(); } else { BGEndTask(); // pretend task completed (because it never started) } } return _fPending; } void BGTask::BGEndTask() { SetEvent(_hDone); _fPending = FALSE; JiggleMouse(); } LRESULT BGTask::BGFilterSetCursor(LRESULT lres) { if (BGTaskPending()) { if (GetCursor() == g_hcurArrow) { SetCursor(g_hcurAppStarting); lres = TRUE; } } return lres; } /***************************************************************************** * * PremungeFileSpec * * Due to complex view specifications this can be led astray when "..." * gets involved. As a workaround (HACK!) we change "..." to "???", * do the mapping, then map back. * * We choose "???" because it has so many magical properties... * * - not a valid filename, so cannot match a local file specification. * - not a valid Source Depot wildcard, so cannot go wild on the server, * - not a single question mark, which SD treats as equivalent to "help". * - same length as "..." so can be updated in place. * * Any revision specifiers remain attached to the string. * *****************************************************************************/ void _ChangeTo(LPTSTR psz, LPCTSTR pszFrom, LPCTSTR pszTo) { ASSERT(lstrlen(pszFrom) == lstrlen(pszTo)); while ((psz = StrStr(psz, pszFrom)) != NULL) { memcpy(psz, pszTo, lstrlen(pszTo) * sizeof(pszTo[0])); } } void PremungeFilespec(LPTSTR psz) { _ChangeTo(psz, TEXT("..."), TEXT("???")); } void PostmungeFilespec(LPTSTR psz) { _ChangeTo(psz, TEXT("???"), TEXT("...")); } /***************************************************************************** * * MapToXPath * *****************************************************************************/ BOOL MapToXPath(LPCTSTR pszSD, String& strOut, MAPTOX X) { if (X == MAPTOX_DEPOT) { // // Early-out: Is it already a full depot path? // if (pszSD[0] == TEXT('/')) { strOut = pszSD; return TRUE; } } // // Borrow strOut to compose the query string. // Substring ssPath; strOut.Reset(); if (Parse(TEXT("$p"), pszSD, &ssPath) && ssPath.Length() > 0) { strOut << ssPath; } else { return FALSE; } PremungeFilespec(strOut); String str; str << TEXT("where ") << QuoteSpaces(strOut); WaitCursor wait; SDChildProcess proc(str); IOBuffer buf(proc.Handle()); while (buf.NextLine(str)) { str.Chomp(); Substring rgss[3]; if (rgss[2].SetStart(Parse(TEXT("$P $P "), str, rgss))) { PostmungeFilespec(str); rgss[2].SetEnd(str + str.Length()); strOut.Reset(); strOut << rgss[X] << ssPath._pszMax; return TRUE; } } return FALSE; } /***************************************************************************** * * MapToLocalPath * * MapToXPath does most of the work, but then we have to do some * magic munging if we are running from a fake directory. * *****************************************************************************/ BOOL MapToLocalPath(LPCTSTR pszSD, String& strOut) { BOOL fSuccess = MapToXPath(pszSD, strOut, MAPTOX_LOCAL); if (fSuccess && !GlobalSettings.GetFakeDir().IsEmpty()) { if (strOut.BufferLength() < MAX_PATH) { if (!strOut.Grow(MAX_PATH - strOut.BufferLength())) { return FALSE; // Out of memory } } LPCTSTR pszRest = strOut + lstrlen(GlobalSettings.GetFakeDir()); if (*pszRest == TEXT('\\')) { pszRest++; } PathCombine(strOut.Buffer(), GlobalSettings.GetLocalRoot(), pszRest); fSuccess = TRUE; } return fSuccess; } /***************************************************************************** * * SpawnProcess * *****************************************************************************/ BOOL SpawnProcess(LPTSTR pszCommand) { STARTUPINFO si = { 0 }; PROCESS_INFORMATION pi; BOOL fSuccess = CreateProcess(NULL, pszCommand, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); if (fSuccess) { CloseHandle(pi.hThread); CloseHandle(pi.hProcess); } return fSuccess; } /***************************************************************************** * * WindiffChangelist * *****************************************************************************/ void WindiffChangelist(int iChange) { if (iChange > 0) { String str; str << TEXT("windiff.exe -ld") << iChange; SpawnProcess(str); } } /***************************************************************************** * * WindiffOneChange * *****************************************************************************/ void WindiffOneChange(LPTSTR pszPath) { Substring rgss[2]; if (Parse(TEXT("$P#$d$e"), pszPath, rgss)) { String str; str << TEXT("windiff.exe "); rgss[0].Finalize(); int iVersion = StrToInt(rgss[1].Start()); if (iVersion > 1) { /* Edit is easy */ str << QuoteSpaces(rgss[0].Start()) << TEXT("#") << (iVersion - 1); } else { /* Add uses NUL as the base file */ str << TEXT("NUL"); } str << TEXT(' '); str << QuoteSpaces(rgss[0].Start()) << TEXT("#") << iVersion; SpawnProcess(str); } } /***************************************************************************** * * ParseBugNumber * * See if there's a bug number in there. * * Digits at the beginning - bug number. * Digits after a space or punctuation mark - bug number. * Digits after the word "bug" or the letter "B" - bug number. * * A valid bug number must begin with a nonzero digit. * *****************************************************************************/ int ParseBugNumber(LPCTSTR psz) { Substring ss; LPCTSTR pszStart = psz; while (*psz) { if (IsDigit(*psz)) { if (*psz == TEXT('0')) { // Nope, cannot begin with zero } else if (psz == pszStart) { return StrToInt(psz); // woo-hoo! } else switch (psz[-1]) { case 'B': case 'g': case 'G': return StrToInt(psz); // Comes after a B or a G default: if (!IsAlpha(psz[-1])) { return StrToInt(psz); // Comes after a space or punctuation } } // Phooey, a digit string beginning with 0; not a bug. while (IsDigit(*psz)) psz++; } else { psz++; } } return 0; } /***************************************************************************** * * ParseBugNumberFromSubItem * * Sometimes we use this just to parse regular numbers since regular * numbers pass the Bug Number Test. * *****************************************************************************/ int ParseBugNumberFromSubItem(HWND hwnd, int iItem, int iSubItem) { TCHAR sz[MAX_PATH]; sz[0] = TEXT('\0'); if (iItem >= 0) { ListView_GetSubItemText(hwnd, iItem, iSubItem, sz, ARRAYSIZE(sz)); } return ParseBugNumber(sz); } /***************************************************************************** * * AdjustBugMenu * *****************************************************************************/ inline void _TrimAtTab(LPTSTR psz) { psz = StrChr(psz, TEXT('\t')); if (psz) *psz = TEXT('\0'); } void AdjustBugMenu(HMENU hmenu, int iBug, BOOL fContextMenu) { TCHAR sz[MAX_PATH]; String str; if (iBug) { str << StringResource(IDS_VIEWBUG_FORMAT); wnsprintf(sz, ARRAYSIZE(sz), str, iBug); if (fContextMenu) { _TrimAtTab(sz); } ModifyMenu(hmenu, IDM_VIEWBUG, MF_BYCOMMAND, IDM_VIEWBUG, sz); } else { str << StringResource(IDS_VIEWBUG_NONE); ModifyMenu(hmenu, IDM_VIEWBUG, MF_BYCOMMAND, IDM_VIEWBUG, str); } EnableDisableOrRemoveMenuItem(hmenu, IDM_VIEWBUG, iBug, fContextMenu); } /***************************************************************************** * * OpenBugWindow * *****************************************************************************/ void OpenBugWindow(HWND hwnd, int iBug) { String str; GlobalSettings.FormatBugUrl(str, iBug); LPCTSTR pszArgs = PathGetArgs(str); PathRemoveArgs(str); PathUnquoteSpaces(str); _AllowSetForegroundWindow(-1); ShellExecute(hwnd, NULL, str, pszArgs, 0, SW_NORMAL); } /***************************************************************************** * * SetClipboardText * *****************************************************************************/ #ifdef UNICODE #define CF_TSTR CF_UNICODETEXT #else #define CF_TSTR CF_TEXT #endif void SetClipboardText(HWND hwnd, LPCTSTR psz) { if (OpenClipboard(hwnd)) { EmptyClipboard(); int cch = lstrlen(psz) + 1; HGLOBAL hglob = GlobalAlloc(GMEM_MOVEABLE, cch * sizeof(*psz)); if (hglob) { LPTSTR pszCopy = RECAST(LPTSTR, GlobalLock(hglob)); if (pszCopy) { lstrcpy(pszCopy, psz); GlobalUnlock(hglob); if (SetClipboardData(CF_TSTR, hglob)) { hglob = NULL; // ownership transfer } } if (hglob) { GlobalFree(hglob); } } CloseClipboard(); } } /***************************************************************************** * * ContainsWildcards * * The SD wildcards are * * * (asterisk) * ... (ellipsis) * %n (percent sign followed by anything) * (null) (null string -- shorthand for "//...") * *****************************************************************************/ BOOL ContainsWildcards(LPCTSTR psz) { if (*psz == TEXT('#') || *psz == TEXT('@') || *psz == TEXT('\0')) { return TRUE; // Null string wildcard } for (; *psz; psz++) { if (*psz == TEXT('*') || *psz == TEXT('%')) { return TRUE; } if (psz[0] == TEXT('.') && psz[1] == TEXT('.') && psz[2] == TEXT('.')) { return TRUE; } } return FALSE; } /***************************************************************************** * * Downlevel support * *****************************************************************************/ #ifdef SUPPORT_DOWNLEVEL /* * If there is no thread pool, then chew an entire thread. */ BOOL WINAPI Emulate_QueueUserWorkItem(LPTHREAD_START_ROUTINE pfn, LPVOID Context, ULONG Flags) { DWORD dwId; HANDLE hThread = CreateThread(NULL, 0, pfn, Context, 0, &dwId); if (hThread) { CloseHandle(hThread); return TRUE; } return FALSE; } BOOL WINAPI Emulate_AllowSetForegroundWindow(DWORD dwProcessId) { return FALSE; } QUEUEUSERWORKITEM _QueueUserWorkItem; ALLOWSETFOREGROUNDWINDOW _AllowSetForegroundWindow; template<class T> T GetProcFromModule(LPCTSTR pszModule, LPCSTR pszProc, T Default) { T t; HMODULE hmod = GetModuleHandle(pszModule); if (pszModule) { t = RECAST(T, GetProcAddress(hmod, pszProc)); if (!t) { t = Default; } } else { t = Default; } return t; } #define GetProc(mod, fn) \ _##fn = GetProcFromModule(TEXT(mod), #fn, Emulate_##fn) void InitDownlevel() { GetProc("KERNEL32", QueueUserWorkItem); GetProc("USER32", AllowSetForegroundWindow); } #undef GetProc #else #define InitDownlevel() #endif /***************************************************************************** * * Main program stuff * *****************************************************************************/ LONG GetDllVersion(LPCTSTR pszDll) { HINSTANCE hinst = LoadLibrary(pszDll); DWORD dwVersion = 0; if (hinst) { DLLGETVERSIONPROC DllGetVersion; DllGetVersion = (DLLGETVERSIONPROC)GetProcAddress(hinst, "DllGetVersion"); if (DllGetVersion) { DLLVERSIONINFO dvi; dvi.cbSize = sizeof(dvi); if (SUCCEEDED(DllGetVersion(&dvi))) { dwVersion = MAKELONG(dvi.dwMinorVersion, dvi.dwMajorVersion); } } // Leak the DLL - we're going to use him anyway } return dwVersion; } /***************************************************************************** * * Globals * *****************************************************************************/ BOOL InitGlobals() { g_hinst = GetModuleHandle(0); g_hcurWait = LoadCursor(NULL, IDC_WAIT); g_hcurArrow = LoadCursor(NULL, IDC_ARROW); g_hcurAppStarting = LoadCursor(NULL, IDC_APPSTARTING); if (GetDllVersion(TEXT("Comctl32.dll")) < MAKELONG(71, 4) || GetDllVersion(TEXT("Shlwapi.dll")) < MAKELONG(71, 4)) { TCHAR sz[MAX_PATH]; LoadString(g_hinst, IDS_IE4, sz, ARRAYSIZE(sz)); //$$//BUGBUG// MessageBox(NULL, sz, g_szTitle, MB_OK); return FALSE; } InitDownlevel(); InitCommonControls(); /* * Get the SW_ flag for the first window. */ STARTUPINFOA si; si.cb = sizeof(si); si.dwFlags = 0; GetStartupInfoA(&si); if (si.dwFlags & STARTF_USESHOWWINDOW) { g_wShowWindow = si.wShowWindow; } else { g_wShowWindow = SW_SHOWDEFAULT; } return TRUE; } void TermGlobals() { } /***************************************************************************** * * Help * *****************************************************************************/ void Help(HWND hwnd, LPCTSTR pszAnchor) { TCHAR szSelf[MAX_PATH]; GetModuleFileName(g_hinst, szSelf, ARRAYSIZE(szSelf)); String str; str << TEXT("res://") << szSelf << TEXT("/tips.htm"); if (pszAnchor) { str << pszAnchor; } _AllowSetForegroundWindow(-1); ShellExecute(hwnd, NULL, str, 0, 0, SW_NORMAL); } /***************************************************************************** * * CGlobals::Initialize * *****************************************************************************/ void CGlobals::Initialize() { /* * The order of these three steps is important. * * - We have to get the path before we can call sd. * * - We need the "sd info" in order to determine what * the proper fake directory is. */ _InitSdPath(); _InitInfo(); _InitFakeDir(); _InitServerVersion(); _InitBugPage(); } /***************************************************************************** * * CGlobals::_InitSdPath * * The environment variable "SD" provides the path to the program to use. * The default is "sd", but for debugging, you can set it to "fakesd", * or if you're using that other company's product, you might even want * to set it to that other company's program... * *****************************************************************************/ void CGlobals::_InitSdPath() { TCHAR szSd[MAX_PATH]; LPTSTR pszSdExe; DWORD cb = GetEnvironmentVariable(TEXT("SD"), szSd, ARRAYSIZE(szSd)); if (cb == 0 || cb > ARRAYSIZE(szSd)) { pszSdExe = TEXT("SD.EXE"); // Default value } else { pszSdExe = szSd; } cb = SearchPath(NULL, pszSdExe, TEXT(".exe"), ARRAYSIZE(_szSd), _szSd, NULL); if (cb == 0 || cb > ARRAYSIZE(_szSd)) { /* * Not found on path, eek! Just use sd.exe and wait for the * fireworks. */ lstrcpyn(_szSd, TEXT("SD.EXE"), ARRAYSIZE(_szSd)); } } /***************************************************************************** * * CGlobals::_InitInfo * * Collect the results of the "sd info" command. * *****************************************************************************/ void CGlobals::_InitInfo() { static const LPCTSTR s_rgpsz[] = { TEXT("User name: "), TEXT("Client name: "), TEXT("Client root: "), TEXT("Current directory: "), TEXT("Server version: "), }; COMPILETIME_ASSERT(ARRAYSIZE(s_rgpsz) == ARRAYSIZE(_rgpszSettings)); WaitCursor wait; SDChildProcess proc(TEXT("info")); IOBuffer buf(proc.Handle()); String str; while (buf.NextLine(str)) { str.Chomp(); int i; for (i = 0; i < ARRAYSIZE(s_rgpsz); i++) { LPTSTR pszRest = Parse(s_rgpsz[i], str, NULL); if (pszRest) { _rgpszSettings[i] = pszRest; } } } } /***************************************************************************** * * CGlobals::_InitFakeDir * * See if the user is borrowing another person's enlistment. * If so, then virtualize the directory (by walking the tree * looking for an sd.ini file) to keep sd happy. * * DO NOT WHINE if anything is wrong. Magical resolution of * borrowed directories is just a nicety. * *****************************************************************************/ void CGlobals::_InitFakeDir() { /* * If the client root is not a prefix of the current directory, * then cook up a virtual current directory that will keep sd happy. */ _StringCache& pszClientRoot = _rgpszSettings[SETTING_CLIENTROOT]; _StringCache& pszLocalDir = _rgpszSettings[SETTING_LOCALDIR]; if (!pszClientRoot.IsEmpty() && !pszLocalDir.IsEmpty() && !PathIsPrefix(pszClientRoot, pszLocalDir)) { TCHAR szDir[MAX_PATH]; TCHAR szOriginalDir[MAX_PATH]; TCHAR szSdIni[MAX_PATH]; szDir[0] = TEXT('\0'); GetCurrentDirectory(ARRAYSIZE(szDir), szDir); if (!szDir[0]) return; // Freaky lstrcpyn(szOriginalDir, szDir, ARRAYSIZE(szOriginalDir)); do { PathCombine(szSdIni, szDir, TEXT("sd.ini")); if (PathFileExists(szSdIni)) { _pszLocalRoot = szDir; // // Now work from the root back to the current directory. // LPTSTR pszSuffix = szOriginalDir + lstrlen(szDir); if (pszSuffix[0] == TEXT('\\')) { pszSuffix++; } PathCombine(szSdIni, _rgpszSettings[SETTING_CLIENTROOT], pszSuffix); _pszFakeDir = szSdIni; break; } } while (PathRemoveFileSpec(szDir)); } } /***************************************************************************** * * CGlobals::_InitServerVersion * *****************************************************************************/ void CGlobals::_InitServerVersion() { Substring rgss[5]; if (Parse(TEXT("$w $d.$d.$d.$d"), _rgpszSettings[SETTING_SERVERVERSION], rgss)) { for (int i = 0; i < VERSION_MAX; i++) { _rguiVer[i] = StrToInt(rgss[1+i].Start()); } } } /***************************************************************************** * * CGlobals::_InitBugPage * *****************************************************************************/ void CGlobals::_InitBugPage() { TCHAR szRaid[MAX_PATH]; DWORD cb = GetEnvironmentVariable(TEXT("SDVRAID"), szRaid, ARRAYSIZE(szRaid)); if (cb == 0 || cb > ARRAYSIZE(szRaid)) { LoadString(g_hinst, IDS_DEFAULT_BUGPAGE, szRaid, ARRAYSIZE(szRaid)); } LPTSTR pszSharp = StrChr(szRaid, TEXT('#')); if (pszSharp) { *pszSharp++ = TEXT('\0'); } _pszBugPagePre = szRaid; _pszBugPagePost = pszSharp; } /***************************************************************************** * * CommandLineParser * *****************************************************************************/ class CommandLineParser { public: CommandLineParser() : _tok(GetCommandLine()) {} BOOL ParseCommandLine(); void Invoke(); private: BOOL ParseMetaParam(); BOOL TokenWithUndo(); void UndoToken() { _tok.Restart(_pszUndo); } private: Tokenizer _tok; LPCTSTR _pszUndo; LPTHREAD_START_ROUTINE _pfn; String _str; }; BOOL CommandLineParser::TokenWithUndo() { _pszUndo = _tok.Unparsed(); return _tok.Token(_str); } BOOL CommandLineParser::ParseMetaParam() { switch (_str[2]) { case TEXT('s'): if (_str[3] == TEXT('\0')) { _tok.Token(_str); GlobalSettings.SetSdOpts(_str); } else { GlobalSettings.SetSdOpts(_str+3); } break; case TEXT('#'): switch (_str[3]) { case TEXT('+'): case TEXT('\0'): GlobalSettings.SetChurn(TRUE); break; case TEXT('-'): GlobalSettings.SetChurn(FALSE); break; default: return FALSE; } break; default: return FALSE; } return TRUE; } BOOL CommandLineParser::ParseCommandLine() { _tok.Token(_str); // Throw away program name /* * First collect the meta-parameters. These begin with two dashes. */ while (TokenWithUndo()) { if (_str[0] == TEXT('-') && _str[1] == TEXT('-')) { if (!ParseMetaParam()) { return FALSE; } } else { break; } } /* * Next thing had better be a command! */ if (_stricmp(_str, TEXT("changes")) == 0) { _pfn = CChanges_ThreadProc; } else if (_stricmp(_str, TEXT("describe")) == 0) { _pfn = CDescribe_ThreadProc; } else if (_stricmp(_str, TEXT("filelog")) == 0) { _pfn = CFileLog_ThreadProc; } else if (_stricmp(_str, TEXT("fileout")) == 0) { _pfn = CFileOut_ThreadProc; } else if (_stricmp(_str, TEXT("opened")) == 0) { _pfn = COpened_ThreadProc; } else { /* * Eek! Must use psychic powers! */ Substring ss; if (_str[0] == TEXT('\0')) { /* * If no args, then it's "changes". */ _pfn = CChanges_ThreadProc; } else if (_str[0] == TEXT('-')) { /* * If it begins with a dash, then it's "changes". */ _pfn = CChanges_ThreadProc; } else if (Parse(TEXT("$d$e"), _str, &ss)) { /* * If first word is all digits, then it's "describe". */ _pfn = CDescribe_ThreadProc; } else if (_tok.Finished() && !ContainsWildcards(_str)) { /* * If only one argument that contains no wildcards, * then it's "filelog". */ _pfn = CFileLog_ThreadProc; } else { /* * If all else fails, assume "changes". */ _pfn = CChanges_ThreadProc; } UndoToken(); /* Undo all the tokens we accidentally ate */ } return TRUE; } void CommandLineParser::Invoke() { LPTSTR psz = StrDup(_tok.Unparsed()); if (psz) { InterlockedIncrement(&g_lThreads); ExitThread(_pfn(psz)); } } /***************************************************************************** * * Entry * * Program entry point. * *****************************************************************************/ int WINAPI WinMain( IN HINSTANCE hInstance, IN HINSTANCE hPrevInstance, IN LPSTR lpCmdLine, IN int nShowCmd ) { if (InitGlobals()) { CommandLineParser parse; if (!parse.ParseCommandLine()) { Help(NULL, NULL); } else { GlobalSettings.Initialize(); parse.Invoke(); } } ExitProcess(0); }
27.60906
88
0.450076
npocmaka
8e26a0fcbb823784a5633a2804b8d1e894e4486b
1,562
cpp
C++
packages/+GT/GenericTargetCode/source/GenericTarget/TargetTime.cpp
RobertDamerius/GenericTarget
6b26793c2d580797ac8104ca5368987cbb570ef8
[ "MIT" ]
1
2021-02-02T09:01:24.000Z
2021-02-02T09:01:24.000Z
packages/+GT/GenericTargetCode/source/GenericTarget/TargetTime.cpp
RobertDamerius/GenericTarget
6b26793c2d580797ac8104ca5368987cbb570ef8
[ "MIT" ]
null
null
null
packages/+GT/GenericTargetCode/source/GenericTarget/TargetTime.cpp
RobertDamerius/GenericTarget
6b26793c2d580797ac8104ca5368987cbb570ef8
[ "MIT" ]
2
2021-02-02T09:01:45.000Z
2021-10-02T13:08:16.000Z
#include <TargetTime.hpp> TimeInfo::TimeInfo(){ nanoseconds = 0; second = 0; minute = 0; hour = 0; mday = 1; mon = 0; year = 0; wday = 1; yday = 0; isdst = -1; } TimeInfo::TimeInfo(const TimeInfo& time){ this->nanoseconds = time.nanoseconds; this->second = time.second; this->minute = time.minute; this->hour = time.hour; this->mday = time.mday; this->mon = time.mon; this->year = time.year; this->wday = time.wday; this->yday = time.yday; this->isdst = time.isdst; } TimeInfo::~TimeInfo(){} TimeInfo& TimeInfo::operator=(const TimeInfo& rhs){ this->nanoseconds = rhs.nanoseconds; this->second = rhs.second; this->minute = rhs.minute; this->hour = rhs.hour; this->mday = rhs.mday; this->mon = rhs.mon; this->year = rhs.year; this->wday = rhs.wday; this->yday = rhs.yday; this->isdst = rhs.isdst; return *this; } TargetTime::TargetTime(){ model = 0.0; ticks = 0; simulation = 0.0; unix = 0.0; } TargetTime::TargetTime(const TargetTime& time){ this->utc = time.utc; this->local = time.local; this->model = time.model; this->ticks = time.ticks; this->simulation = time.simulation; this->unix = time.unix; } TargetTime::~TargetTime(){} TargetTime& TargetTime::operator=(const TargetTime& rhs){ this->utc = rhs.utc; this->local = rhs.local; this->model = rhs.model; this->ticks = rhs.ticks; this->simulation = rhs.simulation; this->unix = rhs.unix; return *this; }
21.108108
57
0.597951
RobertDamerius
8e2723d7eeb9e5ed1dd60ab8288dda838ad6fd53
7,864
hpp
C++
include/tacklelib/utility/memory.hpp
andry81/tacklelib
e77216839a6c2397b31e8f7a278892bb90b58d4b
[ "MIT" ]
4
2021-03-11T07:10:52.000Z
2022-01-01T22:36:31.000Z
include/tacklelib/utility/memory.hpp
andry81/tacklelib
e77216839a6c2397b31e8f7a278892bb90b58d4b
[ "MIT" ]
null
null
null
include/tacklelib/utility/memory.hpp
andry81/tacklelib
e77216839a6c2397b31e8f7a278892bb90b58d4b
[ "MIT" ]
null
null
null
#pragma once // DO NOT REMOVE, exists to avoid private/public headers mixing! #ifndef UTILITY_MEMORY_HPP #define UTILITY_MEMORY_HPP #include <tacklelib/tacklelib.hpp> #include <tacklelib/utility/platform.hpp> #include <tacklelib/utility/type_traits.hpp> #include <tacklelib/utility/addressof.hpp> #include <tacklelib/utility/assert.hpp> #include <tacklelib/utility/debug.hpp> #include <fmt/format.h> #include <type_traits> #include <cstdint> #include <cstdio> #include <memory> #include <stdexcept> #undef LIBRARY_API_NAMESPACE #define LIBRARY_API_NAMESPACE TACKLELIB #include <tacklelib/utility/library_api_define.hpp> #ifndef UTILITY_PLATFORM_FEATURE_CXX_STANDARD_MAKE_UNIQUE // std::make_unique is supported from C++14. // implementation taken from C++ ISO papers: https://isocpp.org/files/papers/N3656.txt // namespace std { template <typename T, typename D> class unique_ptr; namespace detail { template<class T> struct _unique_if { typedef unique_ptr<T> _single_object; }; template<class T> struct _unique_if<T[]> { typedef unique_ptr<T[]> _unknown_bound; }; template<class T, size_t N> struct _unique_if<T[N]> { typedef void _known_bound; }; } template<class T, class... Args> inline typename detail::_unique_if<T>::_single_object make_unique(Args &&... args) { return unique_ptr<T>(new T(std::forward<Args>(args)...)); } template<class T> inline typename detail::_unique_if<T>::_unknown_bound make_unique(size_t n) { typedef typename remove_extent<T>::type U; return unique_ptr<T>(new U[n]()); } template<class T, class... Args> typename detail::_unique_if<T>::_known_bound make_unique(Args &&...) = delete; } #endif namespace utility { enum LIBRARY_API_DECL MemoryType { MemType_VirtualMemory = 1, MemType_PhysicalMemory = 2 }; // proc_id: // 0 - current process // * - target process size_t LIBRARY_API_DECL get_process_memory_size(MemoryType mem_type, size_t proc_id); // simple buffer to reallocate memory on demand // // CAUTION: // Because the buffer class does not reallocate memory if requested buffer size less than already existed, then out of size read/write access WOULD NOT BE CATCHED! // To workaround that we must AT LEAST do guard the end of the buffer in the DEBUG. // class LIBRARY_API_DECL Buffer { public: // memory power-of-2 sizes enum : uint64_t { _1KB = 1 * 1024, _2KB = 2 * 1024, _4KB = 4 * 1024, _8KB = 8 * 1024, _16KB = 16 * 1024, _32KB = 32 * 1024, _64KB = 64 * 1024, _128KB = 128 * 1024, _256KB = 256 * 1024, _512KB = 512 * 1024, _1MB = 1 * 1024 * 1024, _2MB = 2 * 1024 * 1024, _4MB = 4 * 1024 * 1024, _8MB = 8 * 1024 * 1024, _16MB = 16 * 1024 * 1024, _32MB = 32 * 1024 * 1024, _64MB = 64 * 1024 * 1024, _128MB = 128 * 1024 * 1024, _256MB = 256 * 1024 * 1024, _512MB = 512 * 1024 * 1024, _1GB = 1 * 1024 * 1024 * 1024, _2GB = 2ULL * 1024 * 1024 * 1024, _4GB = 4ULL * 1024 * 1024 * 1024, _8GB = 8ULL * 1024 * 1024 * 1024, }; protected: using BufPtr = std::unique_ptr<uint8_t[]>; using GuardSequenceStr_t = char[49]; static FORCE_INLINE CONSTEXPR_FUNC const GuardSequenceStr_t & _guard_sequence_str() { return "XYZXYZXYZXYZXYZXYZXYZXYZXYZXYZXYZXYZXYZXYZXYZXYZ"; } static FORCE_INLINE CONSTEXPR_FUNC const size_t _guard_max_len() { return 256; // to avoid comparison slow down on big arrays } public: FORCE_INLINE Buffer(size_t size = 0) : m_offset(0), m_size(0), m_reserve(0), m_is_reallocating(false) { if (size) { // optimization to avoid an empty call in constructor reset(size); } } FORCE_INLINE ~Buffer() { #if !ERROR_IF_EMPTY_PP_DEF(DISABLE_BUFFER_GUARD_CHECK) && (ERROR_IF_EMPTY_PP_DEF(ENABLE_PERSISTENT_BUFFER_GUARD_CHECK) || defined(_DEBUG)) check_buffer_guards(); #endif } void check_buffer_guards(); private: void _fill_buffer_guards(); public: FORCE_INLINE void reset(size_t size) { #if !ERROR_IF_EMPTY_PP_DEF(DISABLE_BUFFER_GUARD_CHECK) && (ERROR_IF_EMPTY_PP_DEF(ENABLE_PERSISTENT_BUFFER_GUARD_CHECK) || defined(_DEBUG)) check_buffer_guards(); // minimum 16 bytes or 1% of allocation size for guard sections on the left and right, but not greater than `s_guard_max_len` const size_t offset = (std::min)((std::max)(size / 100, size_t(16U)), _guard_max_len()); const size_t size_extra = size ? (size + offset * 2) : 0; #else const size_t offset = 0; const size_t size_extra = size; #endif // reallocate only if greater, deallocate only if 0 if (size_extra) { if (m_reserve < size_extra) { m_buf_ptr = BufPtr(new uint8_t[size_t(size_extra)], std::default_delete<uint8_t[]>()); m_reserve = size_extra; } m_offset = offset; m_size = size; #if !ERROR_IF_EMPTY_PP_DEF(DISABLE_BUFFER_GUARD_CHECK) && (ERROR_IF_EMPTY_PP_DEF(ENABLE_PERSISTENT_BUFFER_GUARD_CHECK) || defined(_DEBUG)) _fill_buffer_guards(); #endif } else { m_buf_ptr.reset(); m_offset = m_reserve = m_size = 0; } } FORCE_INLINE size_t size() const { return m_size; } FORCE_INLINE uint8_t * get() { DEBUG_ASSERT_TRUE(m_size); return m_buf_ptr.get() + m_offset; } FORCE_INLINE const uint8_t * get() const { DEBUG_ASSERT_TRUE(m_size); return m_buf_ptr.get() + m_offset; } FORCE_INLINE uint8_t * realloc_get(size_t size) { reset(size); #if ERROR_IF_EMPTY_PP_DEF(ENABLE_BUFFER_REALLOC_AFTER_ALLOC) if (!m_is_reallocating) { Buffer local_buf; local_buf.set_reallocating(true); realloc_debug(local_buf); } #endif return m_buf_ptr.get() + m_offset; } FORCE_INLINE void set_reallocating(bool is_reallocating) { m_is_reallocating = is_reallocating; } FORCE_INLINE uint8_t * release() { m_offset = m_size = m_reserve = 0; return m_buf_ptr.release(); } // for memory debugging on a moment of deallocation FORCE_INLINE void realloc_debug(Buffer & to_buf) { uint8_t * to_buf_ptr = to_buf.realloc_get(m_size); memcpy(to_buf_ptr - to_buf.m_offset, m_buf_ptr.get(), size_t(m_reserve)); m_buf_ptr.reset(to_buf.release()); } private: size_t m_offset; size_t m_size; size_t m_reserve; BufPtr m_buf_ptr; bool m_is_reallocating; }; } #endif
31.838057
173
0.55913
andry81
8e28917a8f45659fb1a3bad446e4d35c8d6d5044
755
cpp
C++
cpp/vmethods.cpp
Rugang/scraps
5c93bc84de32a7b8011258c0371f2a132ace3f5f
[ "BSD-3-Clause" ]
35
2015-04-19T16:18:11.000Z
2022-03-14T18:16:06.000Z
cpp/vmethods.cpp
Rugang/scraps
5c93bc84de32a7b8011258c0371f2a132ace3f5f
[ "BSD-3-Clause" ]
null
null
null
cpp/vmethods.cpp
Rugang/scraps
5c93bc84de32a7b8011258c0371f2a132ace3f5f
[ "BSD-3-Clause" ]
22
2015-04-07T07:28:35.000Z
2022-03-14T18:31:08.000Z
#include <iostream> class Foo { public: void f() { std::cout << "Foo::f()" << std::endl; } virtual void g() { std::cout << "Foo::g()" << std::endl; } } class Bar : public Foo { public: void f() { std::cout << "Bar::f()" << std::endl; } virtual void g() { std::cout << "Bar::g()" << std::endl; } } int main() { Foo foo; Bar bar; Foo *baz = &bar; Bar *quux = &bar; foo.f(); // "Foo::f()" foo.g(); // "Foo::g()" bar.f(); // "Bar::f()" bar.g(); // "Bar::g()" // So far everything we would expect... baz->f(); // "Foo::f()" baz->g(); // "Bar::g()" quux->f(); // "Bar::f()" quux->g(); // "Bar::g()" return 0; }
13.981481
45
0.393377
Rugang
8e29bd542577cb6885007975f0ac9c79f5b4dcee
1,010
cpp
C++
1.cpp
nitin-maharana/CODE
126826c36d8b7fa578c8e78e570117c53327e461
[ "MIT" ]
1
2016-03-05T11:40:39.000Z
2016-03-05T11:40:39.000Z
1.cpp
nitin-maharana/CODE
126826c36d8b7fa578c8e78e570117c53327e461
[ "MIT" ]
null
null
null
1.cpp
nitin-maharana/CODE
126826c36d8b7fa578c8e78e570117c53327e461
[ "MIT" ]
null
null
null
/* * Written by Nitin Kumar Maharana * nitin.maharana@gmail.com */ #include <iostream> using namespace std; template <class T> struct node { T val; struct node *next; }; template <class T> class Stack { struct node<T> *top; public: Stack() { top = nullptr; } void push(T item) { struct node<T> *t; t = new struct node<T>; t->val = item; t->next = top; top = t; } void pop(void) { if(empty()) throw "There are no items in stack to pop!!!"; struct node<T> *t; t = top; top = top->next; delete t; } T peek(void) { if(empty()) throw "There are no items in stack to peek!!!"; T item; item = top->val; return item; } bool empty(void) { return top == nullptr ? true : false; } }; int main(void) { Stack<int> s; s.push(1); s.push(2); s.push(3); cout << s.peek() << endl; s.pop(); cout << s.peek() << endl; cout << s.empty() << endl; s.pop(); s.pop(); cout << s.empty() << endl; return 0; }
11.609195
51
0.541584
nitin-maharana
8e2dcdcaad06eec9461def636d8c13e1cabd2840
1,537
cpp
C++
Full.cpp
satans404/Project-2--CS205-C-C-Program-Design
53f555145858bfa58564c57eee2706be60becf78
[ "Apache-2.0" ]
null
null
null
Full.cpp
satans404/Project-2--CS205-C-C-Program-Design
53f555145858bfa58564c57eee2706be60becf78
[ "Apache-2.0" ]
null
null
null
Full.cpp
satans404/Project-2--CS205-C-C-Program-Design
53f555145858bfa58564c57eee2706be60becf78
[ "Apache-2.0" ]
null
null
null
#include "Full.h" #include "Matrix.h" using namespace std; Full::Full():Layer(Layer::Type::Full) { this->inX=0; this->inY=0; this->inDimX=0; this->inDimY=0; this->outX=0; this->outY=0; this->outDimX=0; this->outDimY=0; this->pad=0; } Full::Full(int inDimX,int inDimY,int inX,int inY):Layer(Layer::Type::Full) { this->inX=inX; this->inY=inY; this->inDimX=inDimX; this->inDimY=inDimY; this->outX=1; this->outY=1; this->outDimX=inDimX; this->outDimY=1; this->pad=0; this->result=Matrix(this->outDimX,this->outDimY,1,1); } void Full::setArgs(Matrix* bias, Matrix* kernal) { this->bias=bias; this->kernal=kernal; } void Full::work(Matrix &input) { if(this->bias== nullptr || this->kernal== nullptr) { throw "Error!"; } else { this->work(input,*(this->kernal),*(this->bias)); } } void Full::work(Matrix& input,Matrix& kernal,Matrix& bias) { int len=input.getLen(),start=0,len2=kernal.getLen(); float ans=0; for(int t=0;t<this->inDimX;t++) { ans=0; for(int i=0;i<len;i++) { ans+=input.getNum(i)*kernal.getNum(t*len+i); } this->result.setNum(t,0,0,0,ans+bias.getNum(t)); } } Matrix& Full::getResult() { return this->result; } void Full::display() { cout<<"Full: "<<endl; this->result.display(); } void Full::structure() { cout<<"Full"<<endl; }
18.975309
75
0.540664
satans404
8e2df932bba2d46cdf5d6f96337cb20fadb4dd7b
36,310
cc
C++
src/client/client.cc
septicmk/v6d
3c64e0a324adfe71feb4bfda51d0e55724bfde8d
[ "Apache-2.0" ]
null
null
null
src/client/client.cc
septicmk/v6d
3c64e0a324adfe71feb4bfda51d0e55724bfde8d
[ "Apache-2.0" ]
null
null
null
src/client/client.cc
septicmk/v6d
3c64e0a324adfe71feb4bfda51d0e55724bfde8d
[ "Apache-2.0" ]
null
null
null
/** Copyright 2020-2021 Alibaba Group Holding Limited. 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 "client/client.h" #include <sys/mman.h> #include <cstddef> #include <cstdint> #include <iostream> #include <limits> #include <map> #include <mutex> #include <set> #include <unordered_map> #include <utility> #include "boost/range/combine.hpp" #include "client/ds/blob.h" #include "client/io.h" #include "client/utils.h" #include "common/memory/fling.h" #include "common/util/boost.h" #include "common/util/logging.h" #include "common/util/protocols.h" #include "common/util/status.h" #include "common/util/uuid.h" namespace vineyard { BasicIPCClient::BasicIPCClient() : shm_(new detail::SharedMemoryManager(-1)) {} Status BasicIPCClient::Connect(const std::string& ipc_socket, std::string const& store_type) { std::lock_guard<std::recursive_mutex> guard(client_mutex_); RETURN_ON_ASSERT(!connected_ || ipc_socket == ipc_socket_); if (connected_) { return Status::OK(); } ipc_socket_ = ipc_socket; RETURN_ON_ERROR(connect_ipc_socket_retry(ipc_socket, vineyard_conn_)); std::string message_out; WriteRegisterRequest(message_out, store_type); RETURN_ON_ERROR(doWrite(message_out)); json message_in; RETURN_ON_ERROR(doRead(message_in)); std::string ipc_socket_value, rpc_endpoint_value; bool store_match; RETURN_ON_ERROR(ReadRegisterReply(message_in, ipc_socket_value, rpc_endpoint_value, instance_id_, session_id_, server_version_, store_match)); rpc_endpoint_ = rpc_endpoint_value; connected_ = true; if (!compatible_server(server_version_)) { std::clog << "[warn] Warning: this version of vineyard client may be " "incompatible with connected server: " << "client's version is " << vineyard_version() << ", while the server's version is " << server_version_ << std::endl; } shm_.reset(new detail::SharedMemoryManager(vineyard_conn_)); if (!store_match) { Disconnect(); return Status::Invalid("Mismatched store type"); } return Status::OK(); } Status BasicIPCClient::Open(std::string const& ipc_socket, std::string const& bulk_store_type) { RETURN_ON_ASSERT(!this->connected_, "The client has already been connected to vineyard server"); std::string socket_path; VINEYARD_CHECK_OK(Connect(ipc_socket, "Any")); { std::lock_guard<std::recursive_mutex> guard(client_mutex_); std::string message_out; WriteNewSessionRequest(message_out, bulk_store_type); RETURN_ON_ERROR(doWrite(message_out)); json message_in; RETURN_ON_ERROR(doRead(message_in)); RETURN_ON_ERROR(ReadNewSessionReply(message_in, socket_path)); } Disconnect(); VINEYARD_CHECK_OK(Connect(socket_path, bulk_store_type)); return Status::OK(); } Client::~Client() { Disconnect(); } Status Client::Connect() { auto ep = read_env("VINEYARD_IPC_SOCKET"); if (!ep.empty()) { return Connect(ep); } return Status::ConnectionError( "Environment variable VINEYARD_IPC_SOCKET does't exists"); } Status Client::Connect(const std::string& ipc_socket) { return BasicIPCClient::Connect(ipc_socket, /*bulk_store_type=*/"Normal"); } Status Client::Open(std::string const& ipc_socket) { return BasicIPCClient::Open(ipc_socket, /*bulk_store_type=*/"Normal"); } Status Client::Fork(Client& client) { RETURN_ON_ASSERT(!client.Connected(), "The client has already been connected to vineyard server"); return client.Connect(ipc_socket_); } Client& Client::Default() { static std::once_flag flag; static Client* client = new Client(); std::call_once(flag, [&] { VINEYARD_CHECK_OK(client->Connect()); }); return *client; } Status Client::GetMetaData(const ObjectID id, ObjectMeta& meta, const bool sync_remote) { ENSURE_CONNECTED(this); json tree; RETURN_ON_ERROR(GetData(id, tree, sync_remote)); meta.Reset(); meta.SetMetaData(this, tree); std::map<ObjectID, std::shared_ptr<arrow::Buffer>> buffers; RETURN_ON_ERROR(GetBuffers(meta.GetBufferSet()->AllBufferIds(), buffers)); for (auto const& id : meta.GetBufferSet()->AllBufferIds()) { const auto& buffer = buffers.find(id); if (buffer != buffers.end()) { meta.SetBuffer(id, buffer->second); } } return Status::OK(); } Status Client::GetMetaData(const std::vector<ObjectID>& ids, std::vector<ObjectMeta>& metas, const bool sync_remote) { ENSURE_CONNECTED(this); std::vector<json> trees; RETURN_ON_ERROR(GetData(ids, trees, sync_remote)); metas.resize(trees.size()); std::set<ObjectID> blob_ids; for (size_t idx = 0; idx < trees.size(); ++idx) { metas[idx].Reset(); metas[idx].SetMetaData(this, trees[idx]); for (const auto& id : metas[idx].GetBufferSet()->AllBufferIds()) { blob_ids.emplace(id); } } std::map<ObjectID, std::shared_ptr<arrow::Buffer>> buffers; RETURN_ON_ERROR(GetBuffers(blob_ids, buffers)); for (auto& meta : metas) { for (auto const id : meta.GetBufferSet()->AllBufferIds()) { const auto& buffer = buffers.find(id); if (buffer != buffers.end()) { meta.SetBuffer(id, buffer->second); } } } return Status::OK(); } Status Client::CreateBlob(size_t size, std::unique_ptr<BlobWriter>& blob) { ENSURE_CONNECTED(this); ObjectID object_id = InvalidObjectID(); Payload object; std::shared_ptr<arrow::MutableBuffer> buffer = nullptr; RETURN_ON_ERROR(CreateBuffer(size, object_id, object, buffer)); blob.reset(new BlobWriter(object_id, object, buffer)); return Status::OK(); } Status Client::GetNextStreamChunk(ObjectID const id, size_t const size, std::unique_ptr<arrow::MutableBuffer>& blob) { ENSURE_CONNECTED(this); std::string message_out; WriteGetNextStreamChunkRequest(id, size, message_out); RETURN_ON_ERROR(doWrite(message_out)); json message_in; RETURN_ON_ERROR(doRead(message_in)); Payload object; int fd_sent = -1, fd_recv = -1; RETURN_ON_ERROR(ReadGetNextStreamChunkReply(message_in, object, fd_sent)); RETURN_ON_ASSERT(size == static_cast<size_t>(object.data_size), "The size of returned chunk doesn't match"); uint8_t *mmapped_ptr = nullptr, *dist = nullptr; if (object.data_size > 0) { fd_recv = shm_->PreMmap(object.store_fd); if (message_in.contains("fd") && fd_recv != fd_sent) { json error = json::object(); error["error"] = "GetNextStreamChunk: the fd is not matched between client and server"; error["fd_sent"] = fd_sent; error["fd_recv"] = fd_recv; error["response"] = message_in; return Status::Invalid(error.dump()); } RETURN_ON_ERROR(shm_->Mmap(object.store_fd, object.map_size, object.pointer - object.data_offset, false, true, &mmapped_ptr)); dist = mmapped_ptr + object.data_offset; } blob.reset(new arrow::MutableBuffer(dist, object.data_size)); return Status::OK(); } Status Client::PullNextStreamChunk(ObjectID const id, std::unique_ptr<arrow::Buffer>& chunk) { std::shared_ptr<Object> buffer; RETURN_ON_ERROR(ClientBase::PullNextStreamChunk(id, buffer)); if (auto casted = std::dynamic_pointer_cast<vineyard::Blob>(buffer)) { chunk.reset( new arrow::Buffer(reinterpret_cast<const uint8_t*>(casted->data()), casted->allocated_size())); return Status::OK(); } return Status::Invalid("Expect buffer, but got '" + buffer->meta().GetTypeName() + "'"); } std::shared_ptr<Object> Client::GetObject(const ObjectID id) { ObjectMeta meta; VINEYARD_CHECK_OK(this->GetMetaData(id, meta, true)); VINEYARD_ASSERT(!meta.MetaData().empty()); auto object = ObjectFactory::Create(meta.GetTypeName()); if (object == nullptr) { object = std::unique_ptr<Object>(new Object()); } object->Construct(meta); return object; } Status Client::GetObject(const ObjectID id, std::shared_ptr<Object>& object) { ObjectMeta meta; RETURN_ON_ERROR(this->GetMetaData(id, meta, true)); RETURN_ON_ASSERT(!meta.MetaData().empty()); object = ObjectFactory::Create(meta.GetTypeName()); if (object == nullptr) { object = std::unique_ptr<Object>(new Object()); } object->Construct(meta); return Status::OK(); } std::vector<std::shared_ptr<Object>> Client::GetObjects( const std::vector<ObjectID>& ids) { std::vector<ObjectMeta> metas; VINEYARD_CHECK_OK(this->GetMetaData(ids, metas, true)); for (auto const& meta : metas) { if (meta.MetaData().empty()) { VINEYARD_ASSERT(!meta.MetaData().empty()); } } std::vector<std::shared_ptr<Object>> objects; objects.reserve(ids.size()); for (auto const& meta : metas) { auto object = ObjectFactory::Create(meta.GetTypeName()); if (object == nullptr) { object = std::unique_ptr<Object>(new Object()); } object->Construct(meta); objects.emplace_back(std::shared_ptr<Object>(object.release())); } return objects; } std::vector<ObjectMeta> Client::ListObjectMeta(std::string const& pattern, const bool regex, size_t const limit, bool nobuffer) { std::unordered_map<ObjectID, json> meta_trees; VINEYARD_CHECK_OK(ListData(pattern, regex, limit, meta_trees)); std::vector<ObjectMeta> metas; std::set<ObjectID> blob_ids; metas.resize(meta_trees.size()); size_t cnt = 0; for (auto const& kv : meta_trees) { metas[cnt].SetMetaData(this, kv.second); for (auto const& id : metas[cnt].GetBufferSet()->AllBufferIds()) { blob_ids.emplace(id); } cnt += 1; } if (nobuffer) { return metas; } // retrive blobs std::map<ObjectID, std::shared_ptr<arrow::Buffer>> buffers; VINEYARD_CHECK_OK(GetBuffers(blob_ids, buffers)); // construct objects std::vector<std::shared_ptr<Object>> objects; objects.reserve(metas.size()); for (auto& meta : metas) { for (auto const id : meta.GetBufferSet()->AllBufferIds()) { const auto& buffer = buffers.find(id); if (buffer != buffers.end()) { meta.SetBuffer(id, buffer->second); } } } return metas; } std::vector<std::shared_ptr<Object>> Client::ListObjects( std::string const& pattern, const bool regex, size_t const limit) { std::unordered_map<ObjectID, json> meta_trees; VINEYARD_CHECK_OK(ListData(pattern, regex, limit, meta_trees)); std::vector<ObjectMeta> metas; std::set<ObjectID> blob_ids; metas.resize(meta_trees.size()); size_t cnt = 0; for (auto const& kv : meta_trees) { metas[cnt].SetMetaData(this, kv.second); for (auto const& id : metas[cnt].GetBufferSet()->AllBufferIds()) { blob_ids.emplace(id); } cnt += 1; } // retrive blobs std::map<ObjectID, std::shared_ptr<arrow::Buffer>> buffers; VINEYARD_CHECK_OK(GetBuffers(blob_ids, buffers)); // construct objects std::vector<std::shared_ptr<Object>> objects; objects.reserve(metas.size()); for (auto& meta : metas) { for (auto const id : meta.GetBufferSet()->AllBufferIds()) { const auto& buffer = buffers.find(id); if (buffer != buffers.end()) { meta.SetBuffer(id, buffer->second); } } auto object = ObjectFactory::Create(meta.GetTypeName()); if (object == nullptr) { object = std::unique_ptr<Object>(new Object()); } object->Construct(meta); objects.emplace_back(std::shared_ptr<Object>(object.release())); } return objects; } bool Client::IsSharedMemory(const void* target) const { return shm_->Exists(target); } bool Client::IsSharedMemory(const uintptr_t target) const { return shm_->Exists(target); } bool Client::IsSharedMemory(const void* target, ObjectID& object_id) const { return shm_->Exists(target, object_id); } bool Client::IsSharedMemory(const uintptr_t target, ObjectID& object_id) const { return shm_->Exists(target, object_id); } Status Client::AllocatedSize(const ObjectID id, size_t& size) { ENSURE_CONNECTED(this); json tree; RETURN_ON_ERROR(GetData(id, tree, false)); ObjectMeta meta; meta.SetMetaData(this, tree); std::map<ObjectID, size_t> sizes; RETURN_ON_ERROR(GetBufferSizes(meta.GetBufferSet()->AllBufferIds(), sizes)); size = 0; for (auto const& sz : sizes) { if (sz.second > 0) { size += sz.second; } } return Status::OK(); } Status Client::CreateArena(const size_t size, int& fd, size_t& available_size, uintptr_t& base, uintptr_t& space) { ENSURE_CONNECTED(this); std::string message_out; WriteMakeArenaRequest(size, message_out); RETURN_ON_ERROR(doWrite(message_out)); json message_in; RETURN_ON_ERROR(doRead(message_in)); RETURN_ON_ERROR(ReadMakeArenaReply(message_in, fd, available_size, base)); VINEYARD_ASSERT(size == std::numeric_limits<size_t>::max() || size == available_size); uint8_t* mmapped_ptr = nullptr; VINEYARD_CHECK_OK( shm_->Mmap(fd, available_size, nullptr, false, false, &mmapped_ptr)); space = reinterpret_cast<uintptr_t>(mmapped_ptr); return Status::OK(); } Status Client::ReleaseArena(const int fd, std::vector<size_t> const& offsets, std::vector<size_t> const& sizes) { ENSURE_CONNECTED(this); std::string message_out; WriteFinalizeArenaRequest(fd, offsets, sizes, message_out); RETURN_ON_ERROR(doWrite(message_out)); json message_in; RETURN_ON_ERROR(doRead(message_in)); RETURN_ON_ERROR(ReadFinalizeArenaReply(message_in)); return Status::OK(); } Status Client::CreateBuffer(const size_t size, ObjectID& id, Payload& payload, std::shared_ptr<arrow::MutableBuffer>& buffer) { ENSURE_CONNECTED(this); std::string message_out; WriteCreateBufferRequest(size, message_out); RETURN_ON_ERROR(doWrite(message_out)); json message_in; int fd_sent = -1, fd_recv = -1; RETURN_ON_ERROR(doRead(message_in)); RETURN_ON_ERROR(ReadCreateBufferReply(message_in, id, payload, fd_sent)); RETURN_ON_ASSERT(static_cast<size_t>(payload.data_size) == size); uint8_t *shared = nullptr, *dist = nullptr; if (payload.data_size > 0) { fd_recv = shm_->PreMmap(payload.store_fd); if (message_in.contains("fd") && fd_recv != fd_sent) { json error = json::object(); error["error"] = "CreateBuffer: the fd is not matched between client and server"; error["fd_sent"] = fd_sent; error["fd_recv"] = fd_recv; error["response"] = message_in; return Status::Invalid(error.dump()); } RETURN_ON_ERROR(shm_->Mmap(payload.store_fd, payload.map_size, payload.pointer - payload.data_offset, false, true, &shared)); dist = shared + payload.data_offset; } buffer = std::make_shared<arrow::MutableBuffer>(dist, payload.data_size); return Status::OK(); } Status Client::GetBuffer(const ObjectID id, std::shared_ptr<arrow::Buffer>& buffer) { std::map<ObjectID, std::shared_ptr<arrow::Buffer>> buffers; RETURN_ON_ERROR(GetBuffers({id}, buffers)); if (buffers.empty()) { return Status::ObjectNotExists("buffer not exists: " + ObjectIDToString(id)); } buffer = buffers.at(id); return Status::OK(); } Status Client::GetBuffers( const std::set<ObjectID>& ids, std::map<ObjectID, std::shared_ptr<arrow::Buffer>>& buffers) { if (ids.empty()) { return Status::OK(); } ENSURE_CONNECTED(this); std::string message_out; WriteGetBuffersRequest(ids, message_out); RETURN_ON_ERROR(doWrite(message_out)); json message_in; RETURN_ON_ERROR(doRead(message_in)); std::vector<Payload> payloads; std::vector<int> fd_sent, fd_recv; std::set<int> fd_recv_dedup; RETURN_ON_ERROR(ReadGetBuffersReply(message_in, payloads, fd_sent)); for (auto const& item : payloads) { if (item.data_size > 0) { shm_->PreMmap(item.store_fd, fd_recv, fd_recv_dedup); } } if (message_in.contains("fds") && fd_sent != fd_recv) { json error = json::object(); error["error"] = "GetBuffers: the fd set is not matched between client and server"; error["fd_sent"] = fd_sent; error["fd_recv"] = fd_recv; error["response"] = message_in; return Status::UnknownError(error.dump()); } for (auto const& item : payloads) { std::shared_ptr<arrow::Buffer> buffer = nullptr; uint8_t *shared = nullptr, *dist = nullptr; if (item.data_size > 0) { VINEYARD_CHECK_OK(shm_->Mmap(item.store_fd, item.map_size, item.pointer - item.data_offset, true, true, &shared)); dist = shared + item.data_offset; } buffer = std::make_shared<arrow::Buffer>(dist, item.data_size); buffers.emplace(item.object_id, buffer); } return Status::OK(); } Status Client::GetBufferSizes(const std::set<ObjectID>& ids, std::map<ObjectID, size_t>& sizes) { if (ids.empty()) { return Status::OK(); } ENSURE_CONNECTED(this); std::string message_out; WriteGetBuffersRequest(ids, message_out); RETURN_ON_ERROR(doWrite(message_out)); json message_in; RETURN_ON_ERROR(doRead(message_in)); std::vector<Payload> payloads; std::vector<int> fd_sent, fd_recv; std::set<int> fd_recv_dedup; RETURN_ON_ERROR(ReadGetBuffersReply(message_in, payloads, fd_sent)); for (auto const& item : payloads) { if (item.data_size > 0) { shm_->PreMmap(item.store_fd, fd_recv, fd_recv_dedup); } } if (message_in.contains("fds") && fd_sent != fd_recv) { json error = json::object(); error["error"] = "GetBufferSizes: the fd set is not matched between client and server"; error["fd_sent"] = fd_sent; error["fd_recv"] = fd_recv; error["response"] = message_in; return Status::UnknownError(error.dump()); } for (auto const& item : payloads) { uint8_t* shared = nullptr; if (item.data_size > 0) { VINEYARD_CHECK_OK(shm_->Mmap(item.store_fd, item.map_size, item.pointer - item.data_offset, true, true, &shared)); } sizes.emplace(item.object_id, item.data_size); } return Status::OK(); } Status Client::DropBuffer(const ObjectID id, const int fd) { ENSURE_CONNECTED(this); // unmap from client // // FIXME: the erase may cause re-recv fd problem, needs further inspection. // auto entry = mmap_table_.find(fd); // if (entry != mmap_table_.end()) { // mmap_table_.erase(entry); // } // free on server std::string message_out; WriteDropBufferRequest(id, message_out); RETURN_ON_ERROR(doWrite(message_out)); json message_in; RETURN_ON_ERROR(doRead(message_in)); RETURN_ON_ERROR(ReadDropBufferReply(message_in)); return Status::OK(); } Status Client::Seal(ObjectID const& object_id) { ENSURE_CONNECTED(this); std::string message_out; WriteSealRequest(object_id, message_out); RETURN_ON_ERROR(doWrite(message_out)); json message_in; RETURN_ON_ERROR(doRead(message_in)); RETURN_ON_ERROR(ReadSealReply(message_in)); return Status::OK(); } Status Client::ShallowCopy(ObjectID const id, ObjectID& target_id, Client& source_client) { ENSURE_CONNECTED(this); ObjectMeta meta; json tree; RETURN_ON_ERROR(source_client.GetData(id, tree, /*sync_remote==*/true)); meta.SetMetaData(this, tree); auto bids = meta.GetBufferSet()->AllBufferIds(); std::map<ObjectID, ObjectID> mapping; for (auto const& id : bids) { mapping.emplace(id, id); } // create buffers in normal bulk store. std::string message_out; WriteMoveBuffersOwnershipRequest(mapping, source_client.session_id(), message_out); RETURN_ON_ERROR(doWrite(message_out)); json message_in; RETURN_ON_ERROR(doRead(message_in)); RETURN_ON_ERROR(ReadMoveBuffersOwnershipReply(message_in)); // reconstruct meta tree auto meta_tree = meta.MutMetaData(); std::function<ObjectID(json&)> reconstruct = [&](json& meta_tree) -> ObjectID { for (auto& item : meta_tree.items()) { if (item.value().is_object() && !item.value().empty()) { auto sub_id = ObjectIDFromString( item.value()["id"].get_ref<std::string const&>()); auto new_sub_id = sub_id; if (mapping.find(sub_id) == mapping.end()) { new_sub_id = reconstruct(item.value()); mapping.emplace(sub_id, new_sub_id); } else { new_sub_id = mapping[sub_id]; } if (!IsBlob(new_sub_id)) { ObjectMeta sub_meta; VINEYARD_CHECK_OK(GetMetaData(new_sub_id, sub_meta)); meta_tree[item.key()] = sub_meta.MetaData(); } } } ObjectMeta new_meta; ObjectID new_id; new_meta.SetMetaData(this, meta_tree); VINEYARD_CHECK_OK(CreateMetaData(new_meta, new_id)); return new_id; }; target_id = reconstruct(meta_tree); return Status::OK(); } Status Client::ShallowCopy(PlasmaID const plasma_id, ObjectID& target_id, PlasmaClient& source_client) { ENSURE_CONNECTED(this); std::set<PlasmaID> plasma_ids; std::map<PlasmaID, PlasmaPayload> plasma_payloads; plasma_ids.emplace(plasma_id); // get PlasmaPayload to get the object_id and data_size VINEYARD_CHECK_OK(source_client.GetPayloads(plasma_ids, plasma_payloads)); std::map<PlasmaID, ObjectID> mapping; for (auto const& item : plasma_payloads) { mapping.emplace(item.first, item.second.object_id); } // create buffers in normal bulk store. std::string message_out; WriteMoveBuffersOwnershipRequest(mapping, source_client.session_id(), message_out); RETURN_ON_ERROR(doWrite(message_out)); json message_in; RETURN_ON_ERROR(doRead(message_in)); RETURN_ON_ERROR(ReadMoveBuffersOwnershipReply(message_in)); /// no need to reconstruct meta_tree since we do not support composable object /// for plasma store. target_id = plasma_payloads.at(plasma_id).object_id; return Status::OK(); } PlasmaClient::~PlasmaClient() {} // dummy implementation Status PlasmaClient::GetMetaData(const ObjectID id, ObjectMeta& meta_data, const bool sync_remote) { return Status::Invalid("Unsupported."); } Status PlasmaClient::Seal(PlasmaID const& plasma_id) { ENSURE_CONNECTED(this); std::string message_out; WritePlasmaSealRequest(plasma_id, message_out); RETURN_ON_ERROR(doWrite(message_out)); json message_in; RETURN_ON_ERROR(doRead(message_in)); RETURN_ON_ERROR(ReadSealReply(message_in)); RETURN_ON_ERROR(SealUsage(plasma_id)); return Status::OK(); } Status PlasmaClient::Open(std::string const& ipc_socket) { return BasicIPCClient::Open(ipc_socket, /*bulk_store_type=*/"Plasma"); } Status PlasmaClient::Connect(const std::string& ipc_socket) { return BasicIPCClient::Connect(ipc_socket, /*bulk_store_type=*/"Plasma"); } Status PlasmaClient::CreateBuffer(PlasmaID plasma_id, size_t size, size_t plasma_size, std::unique_ptr<BlobWriter>& blob) { ENSURE_CONNECTED(this); ObjectID object_id = InvalidObjectID(); PlasmaPayload plasma_payload; std::shared_ptr<arrow::MutableBuffer> buffer = nullptr; std::string message_out; WriteCreateBufferByPlasmaRequest(plasma_id, size, plasma_size, message_out); RETURN_ON_ERROR(doWrite(message_out)); json message_in; int fd_sent = -1, fd_recv = -1; RETURN_ON_ERROR(doRead(message_in)); RETURN_ON_ERROR(ReadCreateBufferByPlasmaReply(message_in, object_id, plasma_payload, fd_sent)); RETURN_ON_ASSERT(static_cast<size_t>(plasma_payload.data_size) == size); uint8_t *shared = nullptr, *dist = nullptr; if (plasma_payload.data_size > 0) { fd_recv = shm_->PreMmap(plasma_payload.store_fd); if (message_in.contains("fd") && fd_recv != fd_sent) { json error = json::object(); error["error"] = "PlasmaClient::CreateBuffer: the fd is not matched between client " "and server"; error["fd_sent"] = fd_sent; error["fd_recv"] = fd_recv; error["response"] = message_in; return Status::Invalid(error.dump()); } RETURN_ON_ERROR( this->shm_->Mmap(plasma_payload.store_fd, plasma_payload.map_size, plasma_payload.pointer - plasma_payload.data_offset, false, true, &shared)); dist = shared + plasma_payload.data_offset; } buffer = std::make_shared<arrow::MutableBuffer>(dist, plasma_payload.data_size); auto payload = plasma_payload.ToNormalPayload(); object_id = payload.object_id; blob.reset(new BlobWriter(object_id, payload, buffer)); RETURN_ON_ERROR(AddUsage(plasma_id, plasma_payload)); return Status::OK(); } Status PlasmaClient::GetPayloads( std::set<PlasmaID> const& plasma_ids, std::map<PlasmaID, PlasmaPayload>& plasma_payloads) { if (plasma_ids.empty()) { return Status::OK(); } ENSURE_CONNECTED(this); std::set<PlasmaID> remote_ids; std::vector<PlasmaPayload> local_payloads; std::vector<PlasmaPayload> _payloads; /// Lookup in local cache for (auto const& id : plasma_ids) { PlasmaPayload tmp; if (FetchOnLocal(id, tmp).ok()) { local_payloads.emplace_back(tmp); } else { remote_ids.emplace(id); } } /// Lookup in remote server std::string message_out; WriteGetBuffersByPlasmaRequest(remote_ids, message_out); RETURN_ON_ERROR(doWrite(message_out)); json message_in; RETURN_ON_ERROR(doRead(message_in)); RETURN_ON_ERROR(ReadGetBuffersByPlasmaReply(message_in, _payloads)); _payloads.insert(_payloads.end(), local_payloads.begin(), local_payloads.end()); for (auto const& item : _payloads) { plasma_payloads.emplace(item.plasma_id, item); } return Status::OK(); } Status PlasmaClient::GetBuffers( std::set<PlasmaID> const& plasma_ids, std::map<PlasmaID, std::shared_ptr<arrow::Buffer>>& buffers) { std::map<PlasmaID, PlasmaPayload> plasma_payloads; RETURN_ON_ERROR(GetPayloads(plasma_ids, plasma_payloads)); for (auto const& item : plasma_payloads) { std::shared_ptr<arrow::Buffer> buffer = nullptr; uint8_t *shared = nullptr, *dist = nullptr; if (item.second.data_size > 0) { VINEYARD_CHECK_OK(this->shm_->Mmap( item.second.store_fd, item.second.map_size, item.second.pointer - item.second.data_offset, true, true, &shared)); dist = shared + item.second.data_offset; } buffer = std::make_shared<arrow::Buffer>(dist, item.second.data_size); buffers.emplace(item.second.plasma_id, buffer); RETURN_ON_ERROR(AddUsage(item.second.plasma_id, item.second)); } return Status::OK(); } Status PlasmaClient::ShallowCopy(PlasmaID const plasma_id, PlasmaID& target_pid, PlasmaClient& source_client) { ENSURE_CONNECTED(this); std::map<PlasmaID, PlasmaID> mapping; mapping.emplace(plasma_id, plasma_id); // create a new plasma object in plasma bulk store. std::string message_out; WriteMoveBuffersOwnershipRequest(mapping, source_client.session_id(), message_out); RETURN_ON_ERROR(doWrite(message_out)); json message_in; RETURN_ON_ERROR(doRead(message_in)); RETURN_ON_ERROR(ReadMoveBuffersOwnershipReply(message_in)); /// no need to reconstruct meta_tree since we do not support composable object /// for plasma store. target_pid = plasma_id; return Status::OK(); } Status PlasmaClient::ShallowCopy(ObjectID const id, std::set<PlasmaID>& target_pids, Client& source_client) { ENSURE_CONNECTED(this); ObjectMeta meta; json tree; RETURN_ON_ERROR(source_client.GetData(id, tree, /*sync_remote==*/true)); meta.SetMetaData(this, tree); auto bids = meta.GetBufferSet()->AllBufferIds(); std::map<ObjectID, PlasmaID> mapping; for (auto const& bid : bids) { PlasmaID new_pid = PlasmaIDFromString(ObjectIDToString(bid)); mapping.emplace(bid, new_pid); } // create a new plasma object in plasma bulk store. std::string message_out; WriteMoveBuffersOwnershipRequest(mapping, source_client.session_id(), message_out); RETURN_ON_ERROR(doWrite(message_out)); json message_in; RETURN_ON_ERROR(doRead(message_in)); RETURN_ON_ERROR(ReadMoveBuffersOwnershipReply(message_in)); /// no need to reconstruct meta_tree since we do not support composable object /// for plasma store. return Status::OK(); } /// Release an plasma blob. Status PlasmaClient::OnRelease(PlasmaID const& plasma_id) { ENSURE_CONNECTED(this); std::string message_out; WritePlasmaReleaseRequest(plasma_id, message_out); RETURN_ON_ERROR(doWrite(message_out)); json message_in; RETURN_ON_ERROR(doRead(message_in)); RETURN_ON_ERROR(ReadPlasmaReleaseReply(message_in)); return Status::OK(); } /// Delete an plasma blob. Status PlasmaClient::OnDelete(PlasmaID const& plasma_id) { ENSURE_CONNECTED(this); std::string message_out; WritePlasmaDelDataRequest(plasma_id, message_out); RETURN_ON_ERROR(doWrite(message_out)); json message_in; RETURN_ON_ERROR(doRead(message_in)); RETURN_ON_ERROR(ReadPlasmaDelDataReply(message_in)); return Status::OK(); } Status PlasmaClient::Release(const PlasmaID& id) { return RemoveUsage(id); } Status PlasmaClient::Delete(const PlasmaID& id) { return PreDelete(id); } namespace detail { MmapEntry::MmapEntry(int fd, int64_t map_size, uint8_t* pointer, bool readonly, bool realign) : fd_(fd), pointer(pointer), ro_pointer_(nullptr), rw_pointer_(nullptr), length_(0) { // fake_mmap in malloc.h leaves a gap between memory segments, to make // map_size page-aligned again. if (realign) { length_ = map_size - sizeof(size_t); } else { length_ = map_size; } } MmapEntry::~MmapEntry() { if (ro_pointer_) { int r = munmap(ro_pointer_, length_); if (r != 0) { std::clog << "[error] munmap returned " << r << ", errno = " << errno << ": " << strerror(errno) << std::endl; } } if (rw_pointer_) { int r = munmap(rw_pointer_, length_); if (r != 0) { std::clog << "[error] munmap returned " << r << ", errno = " << errno << ": " << strerror(errno) << std::endl; } } close(fd_); } uint8_t* MmapEntry::map_readonly() { if (!ro_pointer_) { ro_pointer_ = reinterpret_cast<uint8_t*>( mmap(NULL, length_, PROT_READ, MAP_SHARED, fd_, 0)); if (ro_pointer_ == MAP_FAILED) { std::clog << "[error] mmap failed: errno = " << errno << ": " << strerror(errno) << std::endl; ro_pointer_ = nullptr; } } return ro_pointer_; } uint8_t* MmapEntry::map_readwrite() { if (!rw_pointer_) { rw_pointer_ = reinterpret_cast<uint8_t*>( mmap(NULL, length_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0)); if (rw_pointer_ == MAP_FAILED) { std::clog << "[error] mmap failed: errno = " << errno << ": " << strerror(errno) << std::endl; rw_pointer_ = nullptr; } } return rw_pointer_; } SharedMemoryManager::SharedMemoryManager(int vineyard_conn) : vineyard_conn_(vineyard_conn) {} Status SharedMemoryManager::Mmap(int fd, int64_t map_size, uint8_t* pointer, bool readonly, bool realign, uint8_t** ptr) { auto entry = mmap_table_.find(fd); if (entry == mmap_table_.end()) { int client_fd = recv_fd(vineyard_conn_); if (fd <= 0) { return Status::IOError( "Failed to receieve file descriptor from the socket"); } auto mmap_entry = std::unique_ptr<MmapEntry>( new MmapEntry(client_fd, map_size, pointer, readonly, realign)); entry = mmap_table_.emplace(fd, std::move(mmap_entry)).first; } if (readonly) { *ptr = entry->second->map_readonly(); if (*ptr == nullptr) { return Status::IOError("Failed to mmap received fd as a readonly buffer"); } } else { *ptr = entry->second->map_readwrite(); if (*ptr == nullptr) { return Status::IOError("Failed to mmap received fd as a writable buffer"); } } segments_.emplace(reinterpret_cast<uintptr_t>(*ptr), entry->second.get()); return Status::OK(); } int SharedMemoryManager::PreMmap(int fd) { return mmap_table_.find(fd) == mmap_table_.end() ? fd : (-1); } void SharedMemoryManager::PreMmap(int fd, std::vector<int>& fds, std::set<int>& dedup) { if (dedup.find(fd) == dedup.end()) { if (mmap_table_.find(fd) == mmap_table_.end()) { fds.emplace_back(fd); dedup.emplace(fd); } } } bool SharedMemoryManager::Exists(const uintptr_t target) { ObjectID id; return Exists(target, id); } bool SharedMemoryManager::Exists(const void* target) { ObjectID id; return Exists(target, id); } bool SharedMemoryManager::Exists(const uintptr_t target, ObjectID& object_id) { if (segments_.empty()) { return false; } #if defined(WITH_VERBOSE) std::clog << "[trace] ---------------- shared memory segments: ----------------" << std::endl; std::clog << "[trace] pointer that been queried: " << reinterpret_cast<void*>(target) << std::endl; for (auto const& item : segments_) { std::clog << "[trace] [" << reinterpret_cast<void*>(item.first) << ", " << reinterpret_cast<void*>(item.first + item.second->length_) << ")" << std::endl; } #endif auto loc = segments_.upper_bound(target); if (segments_.empty()) { return false; } else if (loc == segments_.begin()) { return false; } else if (loc == segments_.end()) { // check rbegin auto const item = segments_.rbegin(); object_id = resolveObjectID(target, item->first, item->second); return object_id != InvalidObjectID(); } else { // check prev auto const item = std::prev(loc); object_id = resolveObjectID(target, item->first, item->second); return object_id != InvalidObjectID(); } } bool SharedMemoryManager::Exists(const void* target, ObjectID& object_id) { return Exists(reinterpret_cast<const uintptr_t>(target), object_id); } ObjectID SharedMemoryManager::resolveObjectID(const uintptr_t target, const uintptr_t key, const MmapEntry* entry) { if (key <= target && target < key + entry->length_) { ptrdiff_t offset = 0; if (key == reinterpret_cast<uintptr_t>(entry->ro_pointer_)) { offset = target - reinterpret_cast<uintptr_t>(entry->ro_pointer_); } else if (key == reinterpret_cast<uintptr_t>(entry->rw_pointer_)) { offset = target - reinterpret_cast<uintptr_t>(entry->rw_pointer_); } else { return InvalidObjectID(); } ObjectID object_id = GenerateBlobID(entry->pointer + offset); #if defined(WITH_VERBOSE) std::clog << "[trace] resuing blob " << ObjectIDToString(object_id) << " (offset is " << offset << ")" << " for pointer " << reinterpret_cast<void*>(target) << std::endl; #endif return object_id; } else { return InvalidObjectID(); } } } // namespace detail } // namespace vineyard
32.800361
80
0.663839
septicmk
8e2e58e183d0f3a0a3d3db1b893fa692e22e758c
3,126
cpp
C++
Boss2D/element/boss_matrix.cpp
Yash-Wasalwar-07/Boss2D
37c5ba0f1c83c89810359a207cabfa0905f803d2
[ "MIT" ]
null
null
null
Boss2D/element/boss_matrix.cpp
Yash-Wasalwar-07/Boss2D
37c5ba0f1c83c89810359a207cabfa0905f803d2
[ "MIT" ]
null
null
null
Boss2D/element/boss_matrix.cpp
Yash-Wasalwar-07/Boss2D
37c5ba0f1c83c89810359a207cabfa0905f803d2
[ "MIT" ]
null
null
null
#include <boss.hpp> #include "boss_matrix.hpp" namespace BOSS { Matrix::Matrix() { m11 = 1; m12 = 0; m21 = 0; m22 = 1; dx = 0; dy = 0; } Matrix::Matrix(const Matrix& rhs) { operator=(rhs); } Matrix::Matrix(float m11, float m12, float m21, float m22, float dx, float dy) { this->m11 = m11; this->m12 = m12; this->m21 = m21; this->m22 = m22; this->dx = dx; this->dy = dy; } Matrix::~Matrix() { } Matrix& Matrix::operator=(const Matrix& rhs) { m11 = rhs.m11; m12 = rhs.m12; m21 = rhs.m21; m22 = rhs.m22; dx = rhs.dx; dy = rhs.dy; return *this; } Matrix& Matrix::operator*=(const Matrix& rhs) { const float New_m11 = m11 * rhs.m11 + m12 * rhs.m21; const float New_m12 = m11 * rhs.m12 + m12 * rhs.m22; const float New_m21 = m21 * rhs.m11 + m22 * rhs.m21; const float New_m22 = m21 * rhs.m12 + m22 * rhs.m22; const float New_dx = dx * rhs.m11 + dy * rhs.m21 + rhs.dx; const float New_dy = dx * rhs.m12 + dy * rhs.m22 + rhs.dy; m11 = New_m11; m12 = New_m12; m21 = New_m21; m22 = New_m22; dx = New_dx; dy = New_dy; return *this; } Matrix Matrix::operator*(const Matrix& rhs) const { return Matrix(*this).operator*=(rhs); } bool Matrix::operator==(const Matrix& rhs) const { return (m11 == rhs.m11 && m12 == rhs.m12 && m21 == rhs.m21 && m22 == rhs.m22 && dx == rhs.dx && dy == rhs.dy); } bool Matrix::operator!=(const Matrix& rhs) const { return !operator==(rhs); } void Matrix::AddOffset(const float x, const float y) { operator*=(Matrix(1, 0, 0, 1, x, y)); } void Matrix::AddRotate(const float angle, const float cx, const float cy) { const float c = Math::Cos(angle); const float s = Math::Sin(angle); operator*=(Matrix(c, s, -s, c, (1 - c) * cx + s * cy, (1 - c) * cy - s * cx)); } void Matrix::AddScale(const float w, const float h, const float cx, const float cy) { operator*=(Matrix(w, 0, 0, h, (1 - w) * cx, (1 - h) * cy)); } void Matrix::AddByTouch(const float a1x, const float a1y, const float a2x, const float a2y, const float b1x, const float b1y, const float b2x, const float b2y) { const float amx = (a1x + a2x) / 2; const float amy = (a1y + a2y) / 2; const float bmx = (b1x + b2x) / 2; const float bmy = (b1y + b2y) / 2; const float rotate = Math::Atan(b1x - bmx, b1y - bmy) - Math::Atan(a1x - amx, a1y - amy); const float scale = Math::Distance(b1x, b1y, b2x, b2y) / Math::Distance(a1x, a1y, a2x, a2y); AddOffset(bmx - amx, bmy - amy); AddRotate(rotate, bmx, bmy); AddScale(scale, scale, bmx, bmy); } }
28.162162
98
0.493282
Yash-Wasalwar-07
8e31828098ed45870d9495348664e2465ce1179c
1,182
hpp
C++
Compiler/boost/boost/signals2/detail/replace_slot_function.hpp
davidov541/MiniC
d3b16a1568b97a4d801880b110a8be04fe848adb
[ "Apache-2.0" ]
2
2015-04-16T01:05:53.000Z
2019-08-26T07:38:43.000Z
LibsExternes/Includes/boost/signals2/detail/replace_slot_function.hpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
LibsExternes/Includes/boost/signals2/detail/replace_slot_function.hpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
// Copyright Frank Mori Hess 2007-2009 // // Use, modification and // distribution is subject to 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) // For more information, see http://www.boost.org #ifndef BOOST_SIGNALS2_DETAIL_REPLACE_SLOT_FUNCTION_HPP #define BOOST_SIGNALS2_DETAIL_REPLACE_SLOT_FUNCTION_HPP #include <boost/signals2/slot_base.hpp> namespace boost { namespace signals2 { namespace detail { template<typename ResultSlot, typename SlotIn, typename SlotFunction> ResultSlot replace_slot_function(const SlotIn &slot_in, const SlotFunction &fun) { ResultSlot slot(fun); slot_base::tracked_container_type tracked_objects = slot_in.tracked_objects(); slot_base::tracked_container_type::const_iterator it; for(it = tracked_objects.begin(); it != tracked_objects.end(); ++it) { slot.track(*it); } return slot; } } // namespace detail } // namespace signals2 } // namespace boost #endif // BOOST_SIGNALS2_DETAIL_REPLACE_SLOT_FUNCTION_HPP
31.105263
89
0.693739
davidov541
8e33160405802224bf3cf0d56c8a29ca37336602
2,887
hpp
C++
libs/dmlf/include/dmlf/colearn/update_store.hpp
marcuswin/ledger
b79c5c4e7e92ff02ea4328fcc0885bf8ded2b8b2
[ "Apache-2.0" ]
1
2019-09-11T09:46:04.000Z
2019-09-11T09:46:04.000Z
libs/dmlf/include/dmlf/colearn/update_store.hpp
qati/ledger
e05a8f2d62ea1b79a704867d220cf307ef6b93b9
[ "Apache-2.0" ]
null
null
null
libs/dmlf/include/dmlf/colearn/update_store.hpp
qati/ledger
e05a8f2d62ea1b79a704867d220cf307ef6b93b9
[ "Apache-2.0" ]
1
2019-09-19T12:38:46.000Z
2019-09-19T12:38:46.000Z
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // 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 "dmlf/colearn/update_store_interface.hpp" #include <queue> #include <unordered_set> #include <utility> #include <vector> #include "core/mutex.hpp" namespace fetch { namespace dmlf { namespace colearn { class UpdateStore : public UpdateStoreInterface { public: UpdateStore() = default; ~UpdateStore() override = default; UpdateStore(UpdateStore const &other) = delete; UpdateStore &operator=(UpdateStore const &other) = delete; void PushUpdate(ColearnURI const &uri, Data &&data, Metadata &&metadata) override; void PushUpdate(Algorithm const &algo, UpdateType type, Data &&data, Source source, Metadata &&metadata) override; UpdatePtr GetUpdate(ColearnURI const &uri, Consumer consumer = "learner0") override; UpdatePtr GetUpdate(Algorithm const &algo, UpdateType const &type, Consumer consumer = "learner0") override; UpdatePtr GetUpdate(ColearnURI const &uri, Criteria criteria, Consumer consumer = "learner0") override; UpdatePtr GetUpdate(Algorithm const &algo, UpdateType const &type, Criteria criteria, Consumer consumer = "learner0") override; std::size_t GetUpdateCount() const override; std::size_t GetUpdateCount(Algorithm const &algo, UpdateType const &type) const override; private: using QueueId = std::string; QueueId Id(Algorithm const &algo, UpdateType const &type) const; Criteria Lifo = [](UpdatePtr const &update) -> double { return static_cast<double>(-update->TimeSinceCreation().count()); }; using Mutex = fetch::Mutex; using Lock = std::unique_lock<Mutex>; using Store = std::vector<UpdatePtr>; using AlgoMap = std::unordered_map<QueueId, Store>; using Fingerprint = Update::Fingerprint; using UpdateConsumers = std::unordered_set<Consumer>; AlgoMap algo_map_; mutable Mutex global_m_; std::unordered_map<Fingerprint, UpdateConsumers> consumed_; }; } // namespace colearn } // namespace dmlf } // namespace fetch
35.641975
91
0.656044
marcuswin
8e347e5be5d2d3f3c9e4cf2410cc925090f906a3
4,771
cpp
C++
test/network/TcpClient.cpp
kubasejdak/utils
efc491e5f682f365bf4752a26f086910c89d6b25
[ "BSD-2-Clause" ]
null
null
null
test/network/TcpClient.cpp
kubasejdak/utils
efc491e5f682f365bf4752a26f086910c89d6b25
[ "BSD-2-Clause" ]
null
null
null
test/network/TcpClient.cpp
kubasejdak/utils
efc491e5f682f365bf4752a26f086910c89d6b25
[ "BSD-2-Clause" ]
null
null
null
///////////////////////////////////////////////////////////////////////////////////// /// /// @file /// @author Kuba Sejdak /// @copyright BSD 2-Clause License /// /// Copyright (c) 2021-2021, Kuba Sejdak <kuba.sejdak@gmail.com> /// All rights reserved. /// /// Redistribution and use in source and binary forms, with or without /// modification, are permitted provided that the following conditions are met: /// /// 1. Redistributions of source code must retain the above copyright notice, this /// list of conditions and the following disclaimer. /// /// 2. Redistributions in binary form must reproduce the above copyright notice, /// this list of conditions and the following disclaimer in the documentation /// and/or other materials provided with the distribution. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" /// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE /// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE /// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE /// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL /// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR /// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER /// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, /// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE /// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /// ///////////////////////////////////////////////////////////////////////////////////// #include <utils/network/Error.hpp> #include <utils/network/TcpClient.hpp> #include <utils/network/TcpServer.hpp> #include <catch2/catch.hpp> #include <cstdint> #include <vector> TEST_CASE("1. Create TcpClient", "[unit][TcpClient]") { SECTION("1.1. Client is uninitialized") { utils::network::TcpClient client; } SECTION("1.2. Client is initialized") { constexpr int cPort = 10101; utils::network::TcpClient client("localhost", cPort); } } TEST_CASE("2. Moving TcpClient around", "[unit][TcpClient]") { constexpr int cPort = 10101; utils::network::TcpServer server(cPort); auto error = server.start(); REQUIRE(!error); utils::network::TcpClient client1("localhost", cPort); utils::network::TcpClient client2(std::move(client1)); error = client2.connect(); REQUIRE(!error); } TEST_CASE("3. Performing operations in incorrect TcpClient state", "[unit][TcpClient]") { constexpr int cPort = 10101; utils::network::TcpClient client("localhost", cPort); SECTION("3.1. No remote endpoint") { auto error = client.connect(); REQUIRE(error == utils::network::Error::eConnectError); } SECTION("3.2. Client is already running") { utils::network::TcpServer server(cPort); auto error = server.start(); REQUIRE(!error); error = client.connect(); REQUIRE(!error); error = client.connect(); REQUIRE(error == utils::network::Error::eClientRunning); } SECTION("3.3. Bad endpoint address") { auto error = client.connect("badAddress", cPort); REQUIRE(error == utils::network::Error::eInvalidArgument); } SECTION("3.4. Getting local/remote endpoints when client is not connected") { auto localEndpoint = client.localEndpoint(); REQUIRE(localEndpoint.ip.empty()); REQUIRE(localEndpoint.port == 0); REQUIRE(!localEndpoint.name); auto remoteEndpoint = client.remoteEndpoint(); REQUIRE(remoteEndpoint.ip.empty()); REQUIRE(remoteEndpoint.port == 0); REQUIRE(!remoteEndpoint.name); } SECTION("3.5. Reading when client is not connected") { constexpr std::size_t cSize = 15; std::vector<std::uint8_t> bytes; auto error = client.read(bytes, cSize); REQUIRE(error == utils::network::Error::eClientDisconnected); bytes.reserve(cSize); std::size_t actualReadSize{}; error = client.read(bytes.data(), cSize, actualReadSize); REQUIRE(error == utils::network::Error::eClientDisconnected); } SECTION("3.6. Writing when client is not connected") { std::vector<std::uint8_t> bytes{1, 2, 3}; auto error = client.write({1, 2, 3}); REQUIRE(error == utils::network::Error::eClientDisconnected); error = client.write(bytes.data(), bytes.size()); REQUIRE(error == utils::network::Error::eClientDisconnected); error = client.write("Hello world"); REQUIRE(error == utils::network::Error::eClientDisconnected); } }
35.340741
87
0.646405
kubasejdak
8e39bbf4687cfa58e7db8d9236e27f8c64514864
5,443
cpp
C++
solver.cpp
georgekouzi/solver-a
594ea86eda750d20f6befe78b629a5c6bf06c6da
[ "MIT" ]
null
null
null
solver.cpp
georgekouzi/solver-a
594ea86eda750d20f6befe78b629a5c6bf06c6da
[ "MIT" ]
null
null
null
solver.cpp
georgekouzi/solver-a
594ea86eda750d20f6befe78b629a5c6bf06c6da
[ "MIT" ]
null
null
null
#include <iostream> #include "solver.hpp" using namespace std; namespace solver{ double solve(RealVariable t){ return 1.0; } complex<double> solve(ComplexVariable) { return complex<double>(); } ////////////////////////// func ComplexVariable///////////////////////// ///////////////////////////operator ==//////////////////////////////////////// ComplexVariable operator==(double num,ComplexVariable& t){ return ComplexVariable(); } // ComplexVariable operator==(ComplexVariable& t,double num){ // return ComplexVariable(); // } // ComplexVariable operator==(const std::complex<double>,const double num){ // return ComplexVariable(); // } // ComplexVariable operator==(ComplexVariable& t,ComplexVariable& d){ // return ComplexVariable(); // } /////////////////////// opertors+/////////////////////////// ComplexVariable operator+(double num,ComplexVariable t){ return ComplexVariable(); } // ComplexVariable operator+(ComplexVariable& t,double num){ // return ComplexVariable(); // } // ComplexVariable operator+(ComplexVariable& t,ComplexVariable& d){ // return ComplexVariable(); // } /////////////////////// opertors*/////////////////////////// ComplexVariable operator*(double num,ComplexVariable& t){ cout<<"num-op:*: "<<num<<endl; return ComplexVariable(); } // ComplexVariable operator*(ComplexVariable& t,double num){ // return ComplexVariable(); // } // ComplexVariable operator*(ComplexVariable& t,ComplexVariable& d){ // return ComplexVariable(); // } ////////////////////////////operator-/////////////////// ComplexVariable operator-(double num,ComplexVariable& t){ return ComplexVariable(); } // ComplexVariable operator-(ComplexVariable& t,double num){ // return ComplexVariable(); // } // ComplexVariable operator-(ComplexVariable& t,ComplexVariable& d){ // return ComplexVariable(); // } /////////////////////// opertors^/////////////////////////// // ComplexVariable operator^(double num,ComplexVariable& t){ // return ComplexVariable(); // } ComplexVariable operator^(ComplexVariable& t,double num){ return ComplexVariable(); } // ComplexVariable operator^(ComplexVariable& t,ComplexVariable& d){ // return ComplexVariable(); // } /////////////////////// opertors/ /////////////////////////// // ComplexVariable operator/(double num,ComplexVariable& t){ // return ComplexVariable(); // } // ComplexVariable operator/(ComplexVariable& t,double num){ // return ComplexVariable(); // } // ComplexVariable operator/(ComplexVariable& t,ComplexVariable& d){ // return ComplexVariable(); // } ////////////////////////// func RealVariable///////////////////////// ///////////////////////////operator ==//////////////////////////////////////// // RealVariable operator ==(double& num,double num1){ // return RealVariable(); // } RealVariable operator ==(double num,RealVariable& t){ return RealVariable(); } // RealVariable operator ==(RealVariable& t,double num){ // return RealVariable(); // } // RealVariable operator ==(RealVariable& t,RealVariable& d){ // return RealVariable(); // } /////////////////////// opertors+/////////////////////////// RealVariable operator+(double num,RealVariable& t){ cout<<"double-num-op:+ "<<num<<endl; return RealVariable(t._a,t._b,t._c+num); } // RealVariable operator+(RealVariable& t,double num){ // cout<<"RealVariable-num-op:+: "<<num<<endl; // return RealVariable(); // } // RealVariable operator+(RealVariable& t,RealVariable& d){ // return RealVariable(); // } ////////////////////////////operator-/////////////////// RealVariable operator-(double num,RealVariable& t){ return RealVariable(); } // RealVariable operator-(RealVariable& t,int num){ // return RealVariable(); // } // RealVariable operator-(RealVariable& t,RealVariable& d){ // return RealVariable(); // } ////////////////////////operator ^////////////////// // RealVariable operator^(double num,RealVariable& t){ // return RealVariable(); // } RealVariable operator^(RealVariable& t,double num){ return RealVariable(); } // RealVariable operator^(RealVariable& t,RealVariable& d){ // return RealVariable(); // } /////////////////////// operator/ ////////////// // RealVariable operator/(double num,RealVariable& t){ // return RealVariable(); // } // RealVariable operator/(RealVariable& t,double num){ // return RealVariable(); // } // RealVariable operator/(RealVariable& t,RealVariable& d){ // return RealVariable(); // } ////////////////////////operator*//////////////////// RealVariable operator*(double num, RealVariable& t){ cout<<"-00-double-num-op:*: "<<endl; return RealVariable(t._a,t._b+num-1,t._c); } // RealVariable operator*(RealVariable& t,double num){ // return RealVariable(); // } // RealVariable operator*(RealVariable& t,RealVariable& d){ // return RealVariable(); // } };
28.952128
80
0.534815
georgekouzi
8e3c17ab62f7f4cf40a3db6d1d785865b2eeaa69
1,811
cpp
C++
CvGameCoreDLL/Boost-1.32.0/include/boost/regex/src.cpp
macaurther/DOCUSA
40586727c351d1b1130c05c2d4648cca3a8bacf5
[ "MIT" ]
93
2015-11-20T04:13:36.000Z
2022-03-24T00:03:08.000Z
CvGameCoreDLL/Boost-1.32.0/include/boost/regex/src.cpp
macaurther/DOCUSA
40586727c351d1b1130c05c2d4648cca3a8bacf5
[ "MIT" ]
206
2015-11-09T00:27:15.000Z
2021-12-04T19:05:18.000Z
CvGameCoreDLL/Boost-1.32.0/include/boost/regex/src.cpp
dguenms/Dawn-of-Civilization
1c4f510af97a869637cddb4c0859759158cea5ce
[ "MIT" ]
117
2015-11-08T02:43:46.000Z
2022-02-12T06:29:00.000Z
/* * * Copyright (c) 1998-2002 * Dr John Maddock * * Use, modification and distribution are subject to 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) * */ /* * LOCATION: see http://www.boost.org for most recent version. * FILE src.cpp * VERSION see <boost/version.hpp> * DESCRIPTION: Includes all the regex source files, include this * file only if you need to build the regex library * as a single file. You must include this file * before any other regex header. * * CAUTION: THIS FILE IS DEPRICATED AND WILL CAUSE * UNNECESSARY CODE BLOAT. */ #if (!defined(BOOST_REGEX_NO_LIB) || !defined(BOOST_REGEX_NO_EXTERNAL_TEMPLATES)) && defined(BOOST_REGEX_CONFIG_HPP) #error too late you have already included a regex header - make sure that you include this header before any other boost header #endif #define BOOST_REGEX_NO_LIB #define BOOST_REGEX_STATIC_LINK #define BOOST_REGEX_NO_EXTERNAL_TEMPLATES #include <boost/regex.hpp> // // include library source files: // #ifdef BOOST_REGEX_USE_WIN32_LOCALE #include "libs/regex/src/w32_regex_traits.cpp" #elif defined(BOOST_REGEX_USE_C_LOCALE) #include "libs/regex/src/c_regex_traits.cpp" #else #include "libs/regex/src/cpp_regex_traits.cpp" #endif #include "libs/regex/src/c_regex_traits_common.cpp" #include "libs/regex/src/cregex.cpp" #include "libs/regex/src/fileiter.cpp" #include "libs/regex/src/posix_api.cpp" #include "libs/regex/src/wide_posix_api.cpp" #include "libs/regex/src/regex.cpp" #include "libs/regex/src/regex_debug.cpp" #include "libs/regex/src/regex_synch.cpp"
32.339286
128
0.694092
macaurther
8e3c304af56aa9d35b80d3624e903c87bb898124
1,515
cpp
C++
libz/types/real64.cpp
kmc7468/zlang
08f9ba5dab502224bea5baa6f7a78c546094b7d0
[ "MIT" ]
5
2017-01-11T03:20:57.000Z
2017-01-15T11:20:30.000Z
libz/types/real64.cpp
kmc7468/zlang
08f9ba5dab502224bea5baa6f7a78c546094b7d0
[ "MIT" ]
null
null
null
libz/types/real64.cpp
kmc7468/zlang
08f9ba5dab502224bea5baa6f7a78c546094b7d0
[ "MIT" ]
null
null
null
#include "real64.hpp" namespace libz::types { int real64::compare(const instance& ins) const { if (ins.type() == type::real64) { const real64& ins_conv = (const real64&)ins; if (this->m_data == ins_conv.m_data) return 0; else if (this->m_data > ins_conv.m_data) return 1; else return -1; } throw exces::invalid_call(); } ptr<instance> real64::add(const instance& ins) const { if (ins.type() == type::real64) { return std::make_shared<real64>(this->m_data + ((const real64&)ins).m_data); } throw exces::invalid_call(); } ptr<instance> real64::sub(const instance& ins) const { if (ins.type() == type::real64) { return std::make_shared<real64>(this->m_data - ((const real64&)ins).m_data); } throw exces::invalid_call(); } ptr<instance> real64::mul(const instance& ins) const { if (ins.type() == type::real64) { return std::make_shared<real64>(this->m_data * ((const real64&)ins).m_data); } throw exces::invalid_call(); } ptr<instance> real64::div(const instance& ins) const { if (ins.type() == type::real64) { return std::make_shared<real64>(this->m_data / ((const real64&)ins).m_data); } throw exces::invalid_call(); } ptr<instance> real64::mod(const instance& ins) const { if (ins.type() == type::real64) { return std::make_shared<real64>(fmod(this->m_data, ((const real64&)ins).m_data)); } throw exces::invalid_call(); } ptr<instance> real64::sign() const { return std::make_shared<real64>(-this->m_data); } }
22.61194
84
0.648185
kmc7468
8e40af3902e91b0044e56e6e8e3b1f00f27d7706
1,734
hpp
C++
openscenario/openscenario_interpreter/include/openscenario_interpreter/syntax/infrastructure_action.hpp
autocore-ai/scenario_simulator_v2
bb9569043e20649f0e4390e9225b6bb7b4de10b6
[ "Apache-2.0" ]
null
null
null
openscenario/openscenario_interpreter/include/openscenario_interpreter/syntax/infrastructure_action.hpp
autocore-ai/scenario_simulator_v2
bb9569043e20649f0e4390e9225b6bb7b4de10b6
[ "Apache-2.0" ]
null
null
null
openscenario/openscenario_interpreter/include/openscenario_interpreter/syntax/infrastructure_action.hpp
autocore-ai/scenario_simulator_v2
bb9569043e20649f0e4390e9225b6bb7b4de10b6
[ "Apache-2.0" ]
null
null
null
// Copyright 2015-2020 Tier IV, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef OPENSCENARIO_INTERPRETER__SYNTAX__INFRASTRUCTURE_ACTION_HPP_ #define OPENSCENARIO_INTERPRETER__SYNTAX__INFRASTRUCTURE_ACTION_HPP_ #include <openscenario_interpreter/syntax/traffic_signal_action.hpp> #include <utility> namespace openscenario_interpreter { inline namespace syntax { /* ---- InfrastructureAction --------------------------------------------------- * * <xsd:complexType name="InfrastructureAction"> * <xsd:all> * <xsd:element name="TrafficSignalAction" type="TrafficSignalAction"/> * </xsd:all> * </xsd:complexType> * * -------------------------------------------------------------------------- */ struct InfrastructureAction : public ComplexType { template <typename... Ts> explicit InfrastructureAction(Ts &&... xs) : ComplexType( readElement<TrafficSignalAction>("TrafficSignalAction", std::forward<decltype(xs)>(xs)...)) { } bool endsImmediately() const { return as<TrafficSignalAction>().endsImmediately(); } }; } // namespace syntax } // namespace openscenario_interpreter #endif // OPENSCENARIO_INTERPRETER__SYNTAX__INFRASTRUCTURE_ACTION_HPP_
35.387755
97
0.700115
autocore-ai
8e4161ac8b1ff3c0ea278995007a8a776e1d52d0
3,909
cpp
C++
persist/tests/test_core/test_fsm/test_fsl.cpp
ketgo/persist
623a5c32a9a0fd3e43987421aa1f91ab8284d356
[ "MIT" ]
null
null
null
persist/tests/test_core/test_fsm/test_fsl.cpp
ketgo/persist
623a5c32a9a0fd3e43987421aa1f91ab8284d356
[ "MIT" ]
11
2020-09-30T07:33:10.000Z
2021-05-01T05:59:13.000Z
persist/tests/test_core/test_fsm/test_fsl.cpp
ketgo/persist
623a5c32a9a0fd3e43987421aa1f91ab8284d356
[ "MIT" ]
null
null
null
/** * test_fsl.cpp - Persist * * Copyright 2021 Ketan Goyal * * 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. */ /** * Free space list unit tests. */ #include <gtest/gtest.h> #include <memory> #include <string> #include <persist/core/fsm/fsl.hpp> #include <persist/core/page/creator.hpp> #include <persist/core/storage/creator.hpp> #include "persist/test/simple_page.hpp" using namespace persist; using namespace persist::test; class FSLTestFixture : public ::testing::Test { protected: ByteBuffer input; const size_t cache_size = 2; const std::set<PageId> free_pages = {1, 2, 3}; const std::string path = "test_fsl_manager"; const PageId fsl_page_id = 1; PageId full_page_id, empty_page_id_1, empty_page_id_2; std::unique_ptr<FSLManager> fsl_manager; std::unique_ptr<Storage<FSLPage>> storage; std::unique_ptr<FSLPage> fsl_page; std::unique_ptr<SimplePage> full_page, empty_page_1, empty_page_2; void SetUp() override { // Setup FSL Storage storage = persist::CreateStorage<FSLPage>("file://" + path); // Setup FSL page fsl_page = persist::CreatePage<FSLPage>(1, DEFAULT_PAGE_SIZE); fsl_page->free_pages = free_pages; Insert(); // Setup FSL Manager fsl_manager = std::make_unique<FSLManager>(*storage, cache_size); fsl_manager->Start(); // Setup empty page empty_page_id_1 = fsl_page->GetMaxPageId(); empty_page_1 = persist::CreatePage<SimplePage>(empty_page_id_1, DEFAULT_PAGE_SIZE); empty_page_id_2 = fsl_page->GetMaxPageId() + 1; empty_page_2 = persist::CreatePage<SimplePage>(empty_page_id_2, DEFAULT_PAGE_SIZE); // Setup full page full_page_id = 3; full_page = persist::CreatePage<SimplePage>(full_page_id, DEFAULT_PAGE_SIZE); ByteBuffer record(full_page->GetFreeSpaceSize(Operation::INSERT), 'A'); full_page->SetRecord(record); } void TearDown() override { storage->Remove(); fsl_manager->Stop(); } private: /** * @brief Insert test data */ void Insert() { storage->Open(); storage->Write(*fsl_page); storage->Close(); } }; TEST_F(FSLTestFixture, TestManagerGetPageId) { ASSERT_EQ(fsl_manager->GetPageId(0), 3); } TEST_F(FSLTestFixture, TestManagerEmptyPage) { fsl_manager->Manage(*empty_page_1); ASSERT_EQ(storage->GetPageCount(), 1); ASSERT_EQ(fsl_manager->GetPageId(0), empty_page_id_1); // Test duplicate fsl_manager->Manage(*empty_page_1); ASSERT_EQ(storage->GetPageCount(), 1); ASSERT_EQ(fsl_manager->GetPageId(0), empty_page_id_1); // Test entry in new FSLPage fsl_manager->Manage(*empty_page_2); ASSERT_EQ(storage->GetPageCount(), 2); ASSERT_EQ(fsl_manager->GetPageId(0), empty_page_id_2); } TEST_F(FSLTestFixture, TestManagerFullPage) { fsl_manager->Manage(*full_page); ASSERT_EQ(storage->GetPageCount(), 1); ASSERT_EQ(fsl_manager->GetPageId(0), 2); }
30.779528
80
0.724482
ketgo
8e41825b206c4b4d2de955950434199dd3f3720b
4,864
cpp
C++
ige/src/plugin/physics/bullet3/BulletWorld.cpp
Arcahub/ige
b9f61209c924c7b683d2429a07e76251e6eb7b1b
[ "MIT" ]
3
2021-06-05T00:36:50.000Z
2022-02-27T10:23:53.000Z
ige/src/plugin/physics/bullet3/BulletWorld.cpp
Arcahub/ige
b9f61209c924c7b683d2429a07e76251e6eb7b1b
[ "MIT" ]
11
2021-05-08T22:00:24.000Z
2021-11-11T22:33:43.000Z
ige/src/plugin/physics/bullet3/BulletWorld.cpp
Arcahub/ige
b9f61209c924c7b683d2429a07e76251e6eb7b1b
[ "MIT" ]
4
2021-05-20T12:41:23.000Z
2021-11-09T14:19:18.000Z
#include "igepch.hpp" #include "BulletGhostObject.hpp" #include "BulletRigidBody.hpp" #include "BulletWorld.hpp" #include "ige/ecs/Entity.hpp" #include "ige/ecs/World.hpp" #include "ige/plugin/TransformPlugin.hpp" #include "ige/plugin/physics/Constraint.hpp" #include "ige/plugin/physics/GhostObject.hpp" #include "ige/plugin/physics/PhysicsWorld.hpp" #include "ige/plugin/physics/RigidBody.hpp" using ige::bt::BulletGhostObject; using ige::bt::BulletWorld; using ige::ecs::EntityId; using ige::ecs::World; using ige::plugin::physics::Constraint; using ige::plugin::physics::GhostObject; using ige::plugin::physics::PhysicsWorld; using ige::plugin::physics::RigidBody; using ige::plugin::transform::Transform; BulletWorld::BulletWorld(btVector3 gravity) : m_dispatcher(&m_collision_config) , m_broadphase(new btDbvtBroadphase) , m_world(new btDiscreteDynamicsWorld( &m_dispatcher, m_broadphase.get(), &m_solver, &m_collision_config)) { m_world->setGravity(gravity); m_world->setInternalTickCallback(tick_update, this); } void BulletWorld::clean_world() { for (int i = m_world->getNumConstraints() - 1; i >= 0; i--) { m_world->removeConstraint(m_world->getConstraint(i)); } for (int i = m_world->getNumCollisionObjects() - 1; i >= 0; i--) { btCollisionObject* obj = m_world->getCollisionObjectArray()[i]; m_world->removeCollisionObject(obj); } } void BulletWorld::new_rigidbody( World& wld, const EntityId& entity, const RigidBody& rigidbody, const Transform& transform) { wld.emplace_component<BulletRigidBody>( entity, rigidbody, transform, m_world); } void BulletWorld::new_ghost_object( World& wld, const EntityId& entity, const GhostObject& object, const Transform& transform) { wld.emplace_component<BulletGhostObject>( entity, object, transform, m_world); } void BulletWorld::new_constraint(World& wld, const Constraint& constraint) { auto rigidbody = wld.get_component<BulletRigidBody>(constraint.entity); if (!rigidbody) return; auto constraint_ptr = static_cast<btGeneric6DofConstraint*>( m_constraints .insert(std::make_unique<btGeneric6DofConstraint>( *rigidbody->body(), btTransform::getIdentity(), false)) .first->get()); m_world->addConstraint(constraint_ptr); constraint_ptr->setDbgDrawSize(5.0f); constraint_ptr->setAngularLowerLimit({ constraint.angular_lower_limit.x, constraint.angular_lower_limit.y, constraint.angular_lower_limit.z, }); constraint_ptr->setAngularUpperLimit({ constraint.angular_upper_limit.x, constraint.angular_upper_limit.y, constraint.angular_upper_limit.z, }); constraint_ptr->setLinearLowerLimit({ constraint.linear_lower_limit.x, constraint.linear_lower_limit.y, constraint.linear_lower_limit.z, }); constraint_ptr->setLinearUpperLimit({ constraint.linear_upper_limit.x, constraint.linear_upper_limit.y, constraint.linear_upper_limit.z, }); } void BulletWorld::simulate(float time_step) { m_world->stepSimulation(time_step); } void BulletWorld::get_collisions(World& wld, PhysicsWorld& phys_world) { auto rigidbodies = wld.query<BulletRigidBody>(); auto ghost_objects = wld.query<BulletGhostObject>(); for (auto [fst_body, snd_body] : m_collisions) { std::optional<EntityId> entity1; std::optional<EntityId> entity2; for (const auto& [entity, body] : rigidbodies) { if (body == fst_body) { entity1 = entity; } if (body == snd_body) { entity2 = entity; } if (entity1 && entity2) { break; } } for (const auto& [entity, object] : ghost_objects) { if (object == fst_body) { entity1 = entity; } if (object == snd_body) { entity2 = entity; } if (entity1 && entity2) { break; } } if (entity1 && entity2) { phys_world.add_collision(entity1.value(), entity2.value()); } } } void BulletWorld::tick_update(btDynamicsWorld* dynamicsWorld, btScalar) { auto self = static_cast<BulletWorld*>(dynamicsWorld->getWorldUserInfo()); self->m_collisions.clear(); auto& dispatcher = *dynamicsWorld->getDispatcher(); const int num_manifolds = dispatcher.getNumManifolds(); for (int manifold_idx = 0; manifold_idx < num_manifolds; ++manifold_idx) { auto& manifold = *dispatcher.getManifoldByIndexInternal(manifold_idx); self->m_collisions.push_back({ manifold.getBody0(), manifold.getBody1(), }); } }
30.21118
78
0.657484
Arcahub
8e42ea4ea3f9f071a18200c6f3982101826ab673
44,791
cpp
C++
spheroidal/sphwv/common_spheroidal.cpp
SabininGV/scattering
68ffea5605d9da87db0593ba7c56c7f60f6b3fae
[ "BSD-2-Clause" ]
5
2016-05-02T11:51:54.000Z
2021-10-04T14:35:58.000Z
spheroidal/sphwv/common_spheroidal.cpp
SabininGV/scattering
68ffea5605d9da87db0593ba7c56c7f60f6b3fae
[ "BSD-2-Clause" ]
null
null
null
spheroidal/sphwv/common_spheroidal.cpp
SabininGV/scattering
68ffea5605d9da87db0593ba7c56c7f60f6b3fae
[ "BSD-2-Clause" ]
10
2016-03-17T03:58:52.000Z
2021-10-04T14:36:00.000Z
// // Copyright (c) 2014, Ross Adelman, Nail A. Gumerov, and Ramani Duraiswami // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include "adder.hpp" #include "common_spheroidal.hpp" #include <iostream> #include "real.hpp" #include <vector> static real calculate_alphar(const real & c, const real & m, const real & r); static real calculate_betar(const real & c, const real & m, const real & r); static real calculate_gammar(const real & c, const real & m, const real & r); static real calculate_betarm(const real & c, const real & m, const real & r); static real calculate_gammarm(const real & c, const real & m, const real & r); static real calculate_U(bool verbose, const real & c, const real & m, const real & n, const real & lambda); static void calculate_zero(real & x, real & Ux, bool verbose, const real & c, const real & m, const real & n, real a, real Ua, real b, real Ub); static real calculate_Nrm(bool verbose, const real & c, const real & m, const real & r, const real & lambda); static real calculate_Arm(const real & c, const real & m, const real & r); static real calculate_Brm(const real & c, const real & m, const real & lambda, const real & r); static real calculate_Crm(const real & c, const real & m, const real & r); static real get_dr(bool verbose, const real & c, const real & m, const real & n, const real & lambda, real & n_dr, std::vector<real> & dr, const real & r); static real get_dr_neg(bool verbose, const real & c, const real & m, const real & n, const real & lambda, const real & n_dr, const std::vector<real> & dr, real & n_dr_neg, std::vector<real> & dr_neg, const real & r); static real calculate_alphar(const real & c, const real & m, const real & r) { return (((real::TWO * m + r + real::TWO) * (real::TWO * m + r + real::ONE)) / ((real::TWO * m + real::TWO * r + real::FIVE) * (real::TWO * m + real::TWO * r + real::THREE))) * calculate_c_squared(c); } static real calculate_betar(const real & c, const real & m, const real & r) { return (m + r) * (m + r + real::ONE) + ((real::TWO * (m + r) * (m + r + real::ONE) - real::TWO * m * m - real::ONE) / ((real::TWO * m + real::TWO * r - real::ONE) * (real::TWO * m + real::TWO * r + real::THREE))) * calculate_c_squared(c); } static real calculate_gammar(const real & c, const real & m, const real & r) { return ((r * (r - real::ONE)) / ((real::TWO * m + real::TWO * r - real::THREE) * (real::TWO * m + real::TWO * r - real::ONE))) * calculate_c_squared(c); } static real calculate_betarm(const real & c, const real & m, const real & r) { return calculate_gammar(c, m, r) * calculate_alphar(c, m, r - real::TWO); } static real calculate_gammarm(const real & c, const real & m, const real & r) { return calculate_betar(c, m, r); } real calculate_continued_fraction(const real & b0, const std::vector<real> & a, const std::vector<real> & b) { real x; x = real::ZERO; if ((int)a.size() < (int)b.size()) { for (int i = (int)a.size() - 1; i >= 0; --i) { x = a[i] / (b[i] - x); } } else { for (int i = (int)b.size() - 1; i >= 0; --i) { x = a[i] / (b[i] - x); } } x = b0 - x; return x; } static real calculate_U(bool verbose, const real & c, const real & m, const real & n, const real & lambda) { real r; real b0; std::vector<real> a; std::vector<real> b; real U1; real prev_U2; real U2; real U; r = n - m; b0 = calculate_gammarm(c, m, r) - lambda; a.clear(); b.clear(); if (remainder(n - m, real::TWO) == real::ZERO) { for (real i = r; i >= real::TWO; i = i - real::TWO) { a.push_back(calculate_betarm(c, m, i)); b.push_back(calculate_gammarm(c, m, i - real::TWO) - lambda); } } else { for (real i = r; i >= real::THREE; i = i - real::TWO) { a.push_back(calculate_betarm(c, m, i)); b.push_back(calculate_gammarm(c, m, i - real::TWO) - lambda); } } U1 = calculate_continued_fraction(b0, a, b); b0 = real::ZERO; a.clear(); b.clear(); prev_U2 = real::NAN; for (real i = r + real::TWO; ; i = i + real::TWO) { a.push_back(calculate_betarm(c, m, i)); b.push_back(calculate_gammarm(c, m, i) - lambda); if (remainder(i - (r + real::TWO), real("100.0")) == real::ZERO) { U2 = calculate_continued_fraction(b0, a, b); if (prev_U2 == prev_U2) { if (abs((U2 - prev_U2) / prev_U2) < real::SMALL_ENOUGH) { if (verbose) { std::cout << "calculate_U: " << ((U2 - prev_U2) / prev_U2).get_string(10) << std::endl; } break; } } prev_U2 = U2; } } U = U1 + U2; return U; } static void calculate_zero(real & x, real & Ux, bool verbose, const real & c, const real & m, const real & n, real a, real Ua, real b, real Ub) { real prev_x; for (int i = 0; ; ++i) { x = a - (Ua / (Ub - Ua)) * (b - a); Ux = calculate_U(verbose, c, m, n, x); if (Ux != real::ZERO) { if (Ua < real::ZERO && Ub > real::ZERO) { if (Ux < real::ZERO) { a = x; Ua = Ux; } else { b = x; Ub = Ux; } } else { if (Ux > real::ZERO) { a = x; Ua = Ux; } else { b = x; Ub = Ux; } } } else { std::cout << "calculate_zero: U = 0.0" << std::endl; return; } if (i > 0) { if (verbose) { std::cout << "calculate_zero: " << ((x - prev_x) / prev_x).get_string(10) << std::endl; } if (abs((x - prev_x) / prev_x) < real::SMALL_ENOUGH) { break; } } prev_x = x; } } void calculate_lambdamn(real & lambda, bool verbose, const real & c, const real & m, const real & n, const real & lambda_approx) { real x; real Ux; real d; real a; real Ua; real b; real Ub; x = lambda_approx; Ux = calculate_U(verbose, c, m, n, x); d = pow(real::TWO, -real("100.0")) * x; while (true) { a = x - d; Ua = calculate_U(verbose, c, m, n, a); b = x + d; Ub = calculate_U(verbose, c, m, n, b); if (verbose) { std::cout << "calculate_lambdamn: " << Ua.get_string(10) << ", " << Ub.get_string(10) << std::endl; } if ((Ua < real::ZERO && Ub > real::ZERO) || (Ua > real::ZERO && Ub < real::ZERO)) { break; } d = real::TWO * d; } calculate_zero(x, Ux, verbose, c, m, n, a, Ua, b, Ub); lambda = x; } static real calculate_Nrm(bool verbose, const real & c, const real & m, const real & r, const real & lambda) { real b0; std::vector<real> a; std::vector<real> b; real N; real prev_N; b0 = real::ZERO; a.clear(); b.clear(); for (real i = r; ; i = i + real::TWO) { a.push_back(calculate_betarm(c, m, i)); b.push_back(calculate_gammarm(c, m, i) - lambda); N = -calculate_continued_fraction(b0, a, b); if (i > r) { if (abs((N - prev_N) / prev_N) < real::SMALL_ENOUGH) { if (verbose) { std::cout << "calculate_Nrm: " << ((N - prev_N) / prev_N).get_string(10) << std::endl; } break; } } prev_N = N; } return N; } void calculate_drmn(std::vector<real> & dr, bool verbose, const real & c, const real & m, const real & n, const real & lambda, real & n_dr, const real & dr_min) { real n_dr_orig; real N; bool converged; real x; adder x_adder; real a; real change; real s; real remove_where; n_dr_orig = n_dr; for ( ; ; n_dr = real::TWO * n_dr) { if (n_dr > n_dr_orig) { for (real r = n_dr / real::TWO; r <= n_dr - real::ONE; r = r + real::ONE) { dr.push_back(real::ZERO); } } else { dr.clear(); for (real r = real::ZERO; r <= n_dr_orig - real::ONE; r = r + real::ONE) { dr.push_back(real::ZERO); } } if (remainder(n - m, real::TWO) == real::ZERO) { dr[gzbi(n_dr - real::TWO)] = real::ONE; for (real r = n_dr - real::TWO; r >= real::TWO; r = r - real::TWO) { if (r < n_dr - real::TWO) { N = calculate_betarm(c, m, r) / (calculate_gammarm(c, m, r) - lambda - N); } else { N = calculate_Nrm(verbose, c, m, r, lambda); } dr[gzbi(r - real::TWO)] = -(calculate_alphar(c, m, r - real::TWO) / N) * dr[gzbi(r)]; } converged = false; x = real::ZERO; x_adder.clear(); for (real r = real::ZERO; r <= n_dr - real::TWO; r = r + real::TWO) { if (r > real::ZERO) { a = a * ((-real::ONE * (real::TWO * m + r - real::ONE) * (real::TWO * m + r)) / (real::FOUR * (m + r / real::TWO) * (r / real::TWO))); } else { a = factorial(real::TWO * m) / factorial(m); } change = dr[gzbi(r)] * a; x = x + change; x_adder.add(change); if (r > real::ZERO && abs(change) > real::ZERO && abs(change / x) < real::SMALL_ENOUGH) { converged = true; if (verbose) { std::cout << "calculate_drmn: " << (change / x).get_string(10) << ", " << ((x - x_adder.calculate_sum()) / x_adder.calculate_sum()).get_string(10) << ", " << (change / x_adder.calculate_sum()).get_string(10) << std::endl; } break; } } x = x_adder.calculate_sum(); if (!converged) { if (verbose) { std::cout << "calculate_drmn: warning: x did not converge" << std::endl; } } s = ((pow(-real::ONE, (n - m) / real::TWO) * factorial(n + m)) / (pow(real::TWO, n - m) * factorial((n + m) / real::TWO) * factorial((n - m) / real::TWO))) / x; for (real r = real::ZERO; r <= n_dr - real::TWO; r = r + real::TWO) { dr[gzbi(r)] = s * dr[gzbi(r)]; } if (converged && (dr_min == real::ZERO || abs(dr[gzbi(n_dr - real::TWO)]) < dr_min)) { break; } } else { dr[gzbi(n_dr - real::ONE)] = real::ONE; for (real r = n_dr - real::ONE; r >= real::THREE; r = r - real::TWO) { if (r < n_dr - real::ONE) { N = calculate_betarm(c, m, r) / (calculate_gammarm(c, m, r) - lambda - N); } else { N = calculate_Nrm(verbose, c, m, r, lambda); } dr[gzbi(r - real::TWO)] = -(calculate_alphar(c, m, r - real::TWO) / N) * dr[gzbi(r)]; } converged = false; x = real::ZERO; x_adder.clear(); for (real r = real::ONE; r <= n_dr - real::ONE; r = r + real::TWO) { if (r > real::ONE) { a = a * ((-real::ONE * (real::TWO * m + r) * (real::TWO * m + r + real::ONE)) / (real::FOUR * (m + r / real::TWO + real::ONE / real::TWO) * (r / real::TWO - real::ONE / real::TWO))); } else { a = factorial(real::TWO * m + real::TWO) / (real::TWO * factorial(m + real::ONE)); } change = dr[gzbi(r)] * a; x = x + change; x_adder.add(change); if (r > real::ZERO && abs(change) > real::ZERO && abs(change / x) < real::SMALL_ENOUGH) { converged = true; if (verbose) { std::cout << "calculate_drmn: " << (change / x).get_string(10) << ", " << ((x - x_adder.calculate_sum()) / x_adder.calculate_sum()).get_string(10) << ", " << (change / x_adder.calculate_sum()).get_string(10) << std::endl; } break; } } x = x_adder.calculate_sum(); if (!converged) { if (verbose) { std::cout << "calculate_drmn: warning: x did not converge" << std::endl; } } s = ((pow(-real::ONE, (n - m - real::ONE) / real::TWO) * factorial(n + m + real::ONE)) / (pow(real::TWO, n - m) * factorial((n + m + real::ONE) / real::TWO) * factorial((n - m - real::ONE) / real::TWO))) / x; for (real r = real::ONE; r <= n_dr - real::ONE; r = r + real::TWO) { dr[gzbi(r)] = s * dr[gzbi(r)]; } if (converged && (dr_min == real::ZERO || abs(dr[gzbi(n_dr - real::ONE)]) < dr_min)) { break; } } } if (dr_min > real::ZERO) { if (remainder(n - m, real::TWO) == real::ZERO) { for (real r = n_dr - real::TWO; r >= real::ZERO; r = r - real::TWO) { if (abs(dr[gzbi(r)]) >= dr_min) { remove_where = r + real::FOUR; if (remove_where >= n_dr_orig && remove_where <= n_dr - real::TWO) { dr.erase(dr.begin() + gzbi(remove_where), dr.end()); n_dr = real((int)dr.size()); } break; } } } else { for (real r = n_dr - real::ONE; r >= real::ONE; r = r - real::TWO) { if (abs(dr[gzbi(r)]) >= dr_min) { remove_where = r + real::THREE; if (remove_where >= n_dr_orig && remove_where <= n_dr - real::TWO) { dr.erase(dr.begin() + gzbi(remove_where), dr.end()); n_dr = real((int)dr.size()); } break; } } } } } static real calculate_Arm(const real & c, const real & m, const real & r) { return calculate_alphar(c, m, r - real::TWO); } static real calculate_Brm(const real & c, const real & m, const real & lambda, const real & r) { return calculate_betar(c, m, r) - lambda; } static real calculate_Crm(const real & c, const real & m, const real & r) { return calculate_gammar(c, m, r + real::TWO); } void calculate_drmn_neg(std::vector<real> & dr_neg, bool verbose, const real & c, const real & m, const real & n, const real & lambda, const real & n_dr, const std::vector<real> & dr, real & n_dr_neg, const real & dr_neg_min) { real n_dr_neg_orig; real b0; std::vector<real> a; std::vector<real> b; real N; real prev_N; real s; real remove_where; n_dr_neg_orig = n_dr_neg; for ( ; ; n_dr_neg = real::TWO * n_dr_neg) { if (n_dr_neg > n_dr_neg_orig) { for (real r = -n_dr_neg / real::TWO - real::ONE; r >= -n_dr_neg; r = r - real::ONE) { dr_neg.push_back(real::ZERO); } } else { dr_neg.clear(); for (real r = -real::ONE; r >= -n_dr_neg_orig; r = r - real::ONE) { dr_neg.push_back(real::ZERO); } } if (remainder(n - m, real::TWO) == real::ZERO) { dr_neg[gnobi(-n_dr_neg)] = real::ONE; for (real r = -n_dr_neg; r <= -real::TWO; r = r + real::TWO) { if (r > -n_dr_neg) { if (r != -real::TWO * m - real::TWO) { N = -calculate_Arm(c, m, r + real::TWO) / (calculate_Brm(c, m, lambda, r) + calculate_Crm(c, m, r - real::TWO) * N); } else { N = (calculate_c_squared(c) / ((real::TWO * m - real::ONE) * (real::TWO * m + real::ONE))) / (calculate_Brm(c, m, lambda, r) + calculate_Crm(c, m, r - real::TWO) * N); } } else { b0 = real::ZERO; a.clear(); b.clear(); if (r != -real::TWO * m - real::TWO) { a.push_back(calculate_Arm(c, m, r + real::TWO)); } else { a.push_back(-calculate_c_squared(c) / ((real::TWO * m - real::ONE) * (real::TWO * m + real::ONE))); } b.push_back(calculate_Brm(c, m, lambda, r)); for (real i = r - real::TWO; ; i = i - real::TWO) { a.push_back(calculate_Crm(c, m, i) * calculate_Arm(c, m, i + real::TWO)); b.push_back(calculate_Brm(c, m, lambda, i)); N = calculate_continued_fraction(b0, a, b); if (i < r - real::TWO) { if (abs((N - prev_N) / prev_N) < real::SMALL_ENOUGH) { if (verbose) { std::cout << "calculate_drmn_neg: " << ((N - prev_N) / prev_N).get_string(10) << std::endl; } break; } } prev_N = N; } } if (r < -real::TWO) { dr_neg[gnobi(r + real::TWO)] = dr_neg[gnobi(r)] / N; if (r == -real::TWO * m - real::TWO) { N = real::ZERO; } } } s = dr[gzbi(real::ZERO)] / (dr_neg[gnobi(-real::TWO)] / N); for (real r = -n_dr_neg; r <= -real::TWO; r = r + real::TWO) { dr_neg[gnobi(r)] = s * dr_neg[gnobi(r)]; } if (dr_neg_min == real::ZERO || abs(dr_neg[gnobi(-n_dr_neg)]) < dr_neg_min) { break; } } else { dr_neg[gnobi(-n_dr_neg + real::ONE)] = real::ONE; for (real r = -n_dr_neg + real::ONE; r <= -real::ONE; r = r + real::TWO) { if (r > -n_dr_neg + real::ONE) { if (r != -real::TWO * m - real::ONE) { N = -calculate_Arm(c, m, r + real::TWO) / (calculate_Brm(c, m, lambda, r) + calculate_Crm(c, m, r - real::TWO) * N); } else { N = -(calculate_c_squared(c) / ((real::TWO * m - real::ONE) * (real::TWO * m - real::THREE))) / (calculate_Brm(c, m, lambda, r) + calculate_Crm(c, m, r - real::TWO) * N); } } else { b0 = real::ZERO; a.clear(); b.clear(); if (r != -real::TWO * m - real::ONE) { a.push_back(calculate_Arm(c, m, r + real::TWO)); } else { a.push_back(calculate_c_squared(c) / ((real::TWO * m - real::ONE) * (real::TWO * m - real::THREE))); } b.push_back(calculate_Brm(c, m, lambda, r)); for (real i = r - real::TWO; ; i = i - real::TWO) { a.push_back(calculate_Crm(c, m, i) * calculate_Arm(c, m, i + real::TWO)); b.push_back(calculate_Brm(c, m, lambda, i)); N = calculate_continued_fraction(b0, a, b); if (i < r - real::TWO) { if (abs((N - prev_N) / prev_N) < real::SMALL_ENOUGH) { if (verbose) { std::cout << "calculate_drmn_neg: " << ((N - prev_N) / prev_N).get_string(10) << std::endl; } break; } } prev_N = N; } } if (r < -real::ONE) { dr_neg[gnobi(r + real::TWO)] = dr_neg[gnobi(r)] / N; if (r == -real::TWO * m - real::ONE) { N = real::ZERO; } } } s = dr[gzbi(real::ONE)] / (dr_neg[gnobi(-real::ONE)] / N); for (real r = -n_dr_neg + real::ONE; r <= -real::ONE; r = r + real::TWO) { dr_neg[gnobi(r)] = s * dr_neg[gnobi(r)]; } if (dr_neg_min == real::ZERO || abs(dr_neg[gnobi(-n_dr_neg + real::ONE)]) < dr_neg_min) { break; } } } if (dr_neg_min > real::ZERO) { if (remainder(n - m, real::TWO) == real::ZERO) { for (real r = -n_dr_neg; r <= -real::TWO; r = r + real::TWO) { if (abs(dr_neg[gnobi(r)]) >= dr_neg_min) { remove_where = r - real::THREE; if (remove_where <= -n_dr_neg_orig - real::ONE && remove_where >= -n_dr_neg + real::ONE) { dr_neg.erase(dr_neg.begin() + gnobi(remove_where), dr_neg.end()); n_dr_neg = real((int)dr_neg.size()); } break; } } } else { for (real r = -n_dr_neg + real::ONE; r <= -real::ONE; r = r + real::TWO) { if (abs(dr_neg[gnobi(r)]) >= dr_neg_min) { remove_where = r - real::FOUR; if (remove_where <= -n_dr_neg_orig - real::ONE && remove_where >= -n_dr_neg + real::ONE) { dr_neg.erase(dr_neg.begin() + gnobi(remove_where), dr_neg.end()); n_dr_neg = real((int)dr_neg.size()); } break; } } } } } static real get_dr(bool verbose, const real & c, const real & m, const real & n, const real & lambda, real & n_dr, std::vector<real> & dr, const real & r) { if (r >= n_dr) { while (r >= n_dr) { n_dr = real::TWO * n_dr; } calculate_drmn(dr, verbose, c, m, n, lambda, n_dr, real::ZERO); } return dr[gzbi(r)]; } real calculate_Nmn(bool verbose, const real & c, const real & m, const real & n, const real & lambda, real & n_dr, std::vector<real> & dr) { real N; adder N_adder; real a; real change; N = real::ZERO; N_adder.clear(); if (remainder(n - m, real::TWO) == real::ZERO) { for (real r = real::ZERO; ; r = r + real::TWO) { if (r > real::ZERO) { a = a * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r)) / ((r - real::ONE) * r)); } else { a = factorial(real::TWO * m); } change = get_dr(verbose, c, m, n, lambda, n_dr, dr, r) * get_dr(verbose, c, m, n, lambda, n_dr, dr, r) * (a / (real::TWO * m + real::TWO * r + real::ONE)); N = N + change; N_adder.add(change); if (r > real::ZERO && abs(change) > real::ZERO && abs(change / N) < real::SMALL_ENOUGH) { if (verbose) { std::cout << "calculate_Nmn: " << (change / N).get_string(10) << ", " << ((N - N_adder.calculate_sum()) / N_adder.calculate_sum()).get_string(10) << ", " << (change / N_adder.calculate_sum()).get_string(10) << std::endl; } break; } } } else { for (real r = real::ONE; ; r = r + real::TWO) { if (r > real::ONE) { a = a * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r)) / ((r - real::ONE) * r)); } else { a = factorial(real::TWO * m + real::ONE); } change = get_dr(verbose, c, m, n, lambda, n_dr, dr, r) * get_dr(verbose, c, m, n, lambda, n_dr, dr, r) * (a / (real::TWO * m + real::TWO * r + real::ONE)); N = N + change; N_adder.add(change); if (r > real::ONE && abs(change) > real::ZERO && abs(change / N) < real::SMALL_ENOUGH) { if (verbose) { std::cout << "calculate_Nmn: " << (change / N).get_string(10) << ", " << ((N - N_adder.calculate_sum()) / N_adder.calculate_sum()).get_string(10) << ", " << (change / N_adder.calculate_sum()).get_string(10) << std::endl; } break; } } } N = N_adder.calculate_sum(); N = real::TWO * N; return N; } real calculate_Fmn(bool verbose, const real & c, const real & m, const real & n, const real & lambda, real & n_dr, std::vector<real> & dr) { real F; adder F_adder; real a; real change; F = real::ZERO; F_adder.clear(); if (remainder(n - m, real::TWO) == real::ZERO) { for (real r = real::ZERO; ; r = r + real::TWO) { if (r > real::ZERO) { a = a * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r)) / ((r - real::ONE) * r)); } else { a = factorial(real::TWO * m); } change = get_dr(verbose, c, m, n, lambda, n_dr, dr, r) * a; F = F + change; F_adder.add(change); if (r > real::ZERO && abs(change) > real::ZERO && abs(change / F) < real::SMALL_ENOUGH) { if (verbose) { std::cout << "calculate_Fmn: " << (change / F).get_string(10) << ", " << ((F - F_adder.calculate_sum()) / F_adder.calculate_sum()).get_string(10) << ", " << (change / F_adder.calculate_sum()).get_string(10) << std::endl; } break; } } } else { for (real r = real::ONE; ; r = r + real::TWO) { if (r > real::ONE) { a = a * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r)) / ((r - real::ONE) * r)); } else { a = factorial(real::TWO * m + real::ONE); } change = get_dr(verbose, c, m, n, lambda, n_dr, dr, r) * a; F = F + change; F_adder.add(change); if (r > real::ONE && abs(change) > real::ZERO && abs(change / F) < real::SMALL_ENOUGH) { if (verbose) { std::cout << "calculate_Fmn: " << (change / F).get_string(10) << ", " << ((F - F_adder.calculate_sum()) / F_adder.calculate_sum()).get_string(10) << ", " << (change / F_adder.calculate_sum()).get_string(10) << std::endl; } break; } } } F = F_adder.calculate_sum(); return F; } // // In the oblate case, there's an implicit factor of 1i ^ m when n - m is even // and 1i ^ (m + 1) when n - m is odd. // real calculate_kmn1(bool verbose, const real & c, const real & m, const real & n, const real & n_dr, const std::vector<real> & dr, const real & F) { real k1; if (remainder(n - m, real::TWO) == real::ZERO) { k1 = ((real::TWO * m + real::ONE) * factorial(m + n) * F) / (pow(real::TWO, m + n) * dr[gzbi(real::ZERO)] * pow(c, m) * factorial(m) * factorial((n - m) / real::TWO) * factorial((m + n) / real::TWO)); } else { k1 = ((real::TWO * m + real::THREE) * factorial(m + n + real::ONE) * F) / (pow(real::TWO, m + n) * dr[gzbi(real::ONE)] * pow(c, m + real::ONE) * factorial(m) * factorial((n - m - real::ONE) / real::TWO) * factorial((m + n + real::ONE) / real::TWO)); } return k1; } static real get_dr_neg(bool verbose, const real & c, const real & m, const real & n, const real & lambda, const real & n_dr, const std::vector<real> & dr, real & n_dr_neg, std::vector<real> & dr_neg, const real & r) { if (r <= -n_dr_neg - real::ONE) { while (r <= -n_dr_neg - real::ONE) { n_dr_neg = real::TWO * n_dr_neg; } calculate_drmn_neg(dr_neg, verbose, c, m, n, lambda, n_dr, dr, n_dr_neg, real::ZERO); } return dr_neg[gnobi(r)]; } real calculate_kmn2(bool verbose, const real & c, const real & m, const real & n, const real & lambda, const real & n_dr, const std::vector<real> & dr, real & n_dr_neg, std::vector<real> & dr_neg, const real & F) { real dr1; real k2; if (remainder(n - m, real::TWO) == real::ZERO) { if (-real::TWO * m < real::ZERO) { dr1 = get_dr_neg(verbose, c, m, n, lambda, n_dr, dr, n_dr_neg, dr_neg, -real::TWO * m); } else { dr1 = dr[gzbi(real::ZERO)]; } k2 = (pow(real::TWO, n - m) * factorial(real::TWO * m) * factorial((n - m) / real::TWO) * factorial((m + n) / real::TWO) * dr1 * F) / ((real::TWO * m - real::ONE) * factorial(m) * factorial(m + n) * pow(c, m - real::ONE)); } else { if (-real::TWO * m + real::ONE < real::ONE) { dr1 = get_dr_neg(verbose, c, m, n, lambda, n_dr, dr, n_dr_neg, dr_neg, -real::TWO * m + real::ONE); } else { dr1 = dr[gzbi(real::ONE)]; } k2 = -((pow(real::TWO, n - m) * factorial(real::TWO * m) * factorial((n - m - real::ONE) / real::TWO) * factorial((m + n + real::ONE) / real::TWO) * dr1 * F) / ((real::TWO * m - real::THREE) * (real::TWO * m - real::ONE) * factorial(m) * factorial(m + n + real::ONE) * pow(c, m - real::TWO))); } return k2; } void calculate_c2kmn(std::vector<real> & c2k, bool verbose, const real & c, const real & m, const real & n, const real & lambda, real & n_dr, std::vector<real> & dr, real & n_c2k, const real & c2k_min) { real n_c2k_orig; real prev_n_c2k; adder c2k_adder; real a; real a0; real change; real remove_where; n_c2k_orig = n_c2k; for (prev_n_c2k = real((int)c2k.size()); ; prev_n_c2k = n_c2k, n_c2k = real::TWO * n_c2k) { for (real k = prev_n_c2k; k <= n_c2k - real::ONE; k = k + real::ONE) { c2k.push_back(real::ZERO); } for (real k = prev_n_c2k; k <= n_c2k - real::ONE; k = k + real::ONE) { c2k[gzbi(k)] = real::ZERO; c2k_adder.clear(); if (remainder(n - m, real::TWO) == real::ZERO) { for (real r = real::TWO * k; ; r = r + real::TWO) { if (r > real::TWO * k) { a = a * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r) * (-r / real::TWO) * (m + r / real::TWO + k - real::ONE / real::TWO)) / ((r - real::ONE) * r * (-r / real::TWO + k) * (m + r / real::TWO - real::ONE / real::TWO))); if (r == real::TWO * k + real::TWO) { a0 = a; } } else { if (k > prev_n_c2k) { a = a0 * (-real::ONE) * (m + real::TWO * k - real::ONE / real::TWO); } else { a = (factorial(real::TWO * m + r) / factorial(r)) * pochhammer(-r / real::TWO, prev_n_c2k) * pochhammer(m + r / real::TWO + real::ONE / real::TWO, prev_n_c2k); } } change = get_dr(verbose, c, m, n, lambda, n_dr, dr, r) * a; c2k[gzbi(k)] = c2k[gzbi(k)] + change; c2k_adder.add(change); if (r > real::TWO * k && abs(change) > real::ZERO && abs(change / c2k[gzbi(k)]) < real::SMALL_ENOUGH) { if (verbose) { std::cout << "calculate_c2kmn: k = " << k.get_int() << ": " << (change / c2k[gzbi(k)]).get_string(10) << ", " << ((c2k[gzbi(k)] - c2k_adder.calculate_sum()) / c2k_adder.calculate_sum()).get_string(10) << ", " << (change / c2k_adder.calculate_sum()).get_string(10) << std::endl; } break; } } } else { for (real r = real::TWO * k + real::ONE; ; r = r + real::TWO) { if (r > real::TWO * k + real::ONE) { a = a * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r) * (-r / real::TWO + real::ONE / real::TWO) * (m + r / real::TWO + k)) / ((r - real::ONE) * r * (-r / real::TWO + k + real::ONE / real::TWO) * (m + r / real::TWO))); if (r == real::TWO * k + real::THREE) { a0 = a; } } else { if (k > prev_n_c2k) { a = a0 * (-real::ONE) * (m + real::TWO * k + real::ONE / real::TWO); } else { a = (factorial(real::TWO * m + r) / factorial(r)) * pochhammer(-(r - real::ONE) / real::TWO, prev_n_c2k) * pochhammer(m + r / real::TWO + real::ONE, prev_n_c2k); } } change = get_dr(verbose, c, m, n, lambda, n_dr, dr, r) * a; c2k[gzbi(k)] = c2k[gzbi(k)] + change; c2k_adder.add(change); if (r > real::TWO * k + real::ONE && abs(change) > real::ZERO && abs(change / c2k[gzbi(k)]) < real::SMALL_ENOUGH) { if (verbose) { std::cout << "calculate_c2kmn: k = " << k.get_int() << ": " << (change / c2k[gzbi(k)]).get_string(10) << ", " << ((c2k[gzbi(k)] - c2k_adder.calculate_sum()) / c2k_adder.calculate_sum()).get_string(10) << ", " << (change / c2k_adder.calculate_sum()).get_string(10) << std::endl; } break; } } } c2k[gzbi(k)] = c2k_adder.calculate_sum(); c2k[gzbi(k)] = (real::ONE / (pow(real::TWO, m) * factorial(m + k) * factorial(k))) * c2k[gzbi(k)]; } if (c2k_min == real::ZERO || abs(c2k[gzbi(n_c2k - real::ONE)]) < c2k_min) { break; } } if (c2k_min > real::ZERO) { for (real k = n_c2k - real::ONE; k >= real::ZERO; k = k - real::ONE) { if (abs(c2k[gzbi(k)]) >= c2k_min) { remove_where = k + real::TWO; if (remove_where >= n_c2k_orig && remove_where <= n_c2k - real::ONE) { c2k.erase(c2k.begin() + gzbi(remove_where), c2k.end()); n_c2k = real((int)c2k.size()); } break; } } } } void calculate_Smn1_1(real & S1, real & S1p, bool verbose, const real & c, const real & m, const real & n, const real & n_dr, const std::vector<real> & dr, const real & eta) { adder S1_adder; adder S1p_adder; real P0; real P1; real P0p; real change; real changep; real P1p; S1 = real::ZERO; S1_adder.clear(); S1p = real::ZERO; S1p_adder.clear(); P0 = real::ONE; for (real v = real::ONE; v <= m; v = v + real::ONE) { P0 = -(real::TWO * v - real::ONE) * pow(real::ONE - eta * eta, real::ONE / real::TWO) * P0; } P1 = (real::TWO * m + real::ONE) * eta * P0; if (remainder(n - m, real::TWO) == real::ZERO) { for (real r = real::ZERO; r <= n_dr - real::TWO; r = r + real::TWO) { if (r > real::ZERO) { P0 = (real::ONE / r) * (-(real::TWO * m + r - real::ONE) * P0 + (real::TWO * m + real::TWO * r - real::ONE) * eta * P1); P1 = (real::ONE / (r + real::ONE)) * (-(real::TWO * m + r) * P1 + (real::TWO * m + real::TWO * r + real::ONE) * eta * P0); } if (abs(eta) < real::ONE) { P0p = (real::ONE / (real::ONE - eta * eta)) * ((m + r + real::ONE) * eta * P0 - (r + real::ONE) * P1); } else { if (m > real::TWO) { P0p = real::ZERO; } else if (m > real::ONE) { P0p = -((m + r - real::ONE) * (m + r) * (m + r + real::ONE) * (m + r + real::TWO)) / real::FOUR; } else if (m > real::ZERO) { P0p = real::INF; } else { P0p = ((m + r) * (m + r + real::ONE)) / real::TWO; } if (eta == -real::ONE) { P0p = -P0p; } } change = dr[gzbi(r)] * P0; S1 = S1 + change; S1_adder.add(change); changep = dr[gzbi(r)] * P0p; S1p = S1p + changep; S1p_adder.add(changep); if (r > real::ZERO && abs(change) > real::ZERO && abs(change / S1) < real::SMALL_ENOUGH && abs(changep) > real::ZERO && abs(changep / S1p) < real::SMALL_ENOUGH) { if (verbose) { std::cout << "calculate_Smn1_1: " << (change / S1).get_string(10) << ", " << (changep / S1p).get_string(10) << ", " << ((S1 - S1_adder.calculate_sum()) / S1_adder.calculate_sum()).get_string(10) << ", " << ((S1p - S1p_adder.calculate_sum()) / S1p_adder.calculate_sum()).get_string(10) << ", " << (change / S1_adder.calculate_sum()).get_string(10) << ", " << (changep / S1p_adder.calculate_sum()).get_string(10) << std::endl; } break; } } } else { for (real r = real::ONE; r <= n_dr - real::ONE; r = r + real::TWO) { if (r > real::ONE) { P0 = (real::ONE / (r - real::ONE)) * (-(real::TWO * m + r - real::TWO) * P0 + (real::TWO * m + real::TWO * r - real::THREE) * eta * P1); P1 = (real::ONE / r) * (-(real::TWO * m + r - real::ONE) * P1 + (real::TWO * m + real::TWO * r - real::ONE) * eta * P0); } if (abs(eta) < real::ONE) { P1p = (real::ONE / (real::ONE - eta * eta)) * ((real::TWO * m + r) * P0 - (m + r) * eta * P1); } else { if (m > real::TWO) { P1p = real::ZERO; } else if (m > real::ONE) { P1p = -((m + r - real::ONE) * (m + r) * (m + r + real::ONE) * (m + r + real::TWO)) / real::FOUR; } else if (m > real::ZERO) { P1p = real::INF; } else { P1p = ((m + r) * (m + r + real::ONE)) / real::TWO; } } change = dr[gzbi(r)] * P1; S1 = S1 + change; S1_adder.add(change); changep = dr[gzbi(r)] * P1p; S1p = S1p + changep; S1p_adder.add(changep); if (r > real::ONE && abs(change) > real::ZERO && abs(change / S1) < real::SMALL_ENOUGH && abs(changep) > real::ZERO && abs(changep / S1p) < real::SMALL_ENOUGH) { if (verbose) { std::cout << "calculate_Smn1_1: " << (change / S1).get_string(10) << ", " << (changep / S1p).get_string(10) << ", " << ((S1 - S1_adder.calculate_sum()) / S1_adder.calculate_sum()).get_string(10) << ", " << ((S1p - S1p_adder.calculate_sum()) / S1p_adder.calculate_sum()).get_string(10) << ", " << (change / S1_adder.calculate_sum()).get_string(10) << ", " << (changep / S1p_adder.calculate_sum()).get_string(10) << std::endl; } break; } } } S1 = S1_adder.calculate_sum(); S1p = S1p_adder.calculate_sum(); } void calculate_Smn1_2(real & S1, real & S1p, bool verbose, const real & c, const real & m, const real & n, const real & n_c2k, const std::vector<real> & c2k, const real & eta) { adder S1_adder; real a; real change; adder S1p_adder; real ap; real changep; S1 = real::ZERO; S1_adder.clear(); for (real k = real::ZERO; k <= n_c2k - real::ONE; k = k + real::ONE) { if (k > real::ZERO) { a = a * (real::ONE - eta * eta); } else { a = real::ONE; } change = c2k[gzbi(k)] * a; S1 = S1 + change; S1_adder.add(change); if (k > real::ZERO && abs(change) > real::ZERO && abs(change / S1) < real::SMALL_ENOUGH) { if (verbose) { std::cout << "calculate_Smn1_2: " << (change / S1).get_string(10) << ", " << ((S1 - S1_adder.calculate_sum()) / S1_adder.calculate_sum()).get_string(10) << ", " << (change / S1_adder.calculate_sum()).get_string(10) << std::endl; } break; } } S1 = S1_adder.calculate_sum(); S1p = real::ZERO; S1p_adder.clear(); for (real k = real::ONE; k <= n_c2k - real::ONE; k = k + real::ONE) { if (k > real::ONE) { ap = ap * (real::ONE - eta * eta); } else { ap = real::ONE; } changep = c2k[gzbi(k)] * k * ap * (-real::TWO * eta); S1p = S1p + changep; S1p_adder.add(changep); if (k > real::ONE && abs(changep) > real::ZERO && abs(changep / S1p) < real::SMALL_ENOUGH) { if (verbose) { std::cout << "calculate_Smn1_2: " << (changep / S1p).get_string(10) << ", " << ((S1p - S1p_adder.calculate_sum()) / S1p_adder.calculate_sum()).get_string(10) << ", " << (changep / S1p_adder.calculate_sum()).get_string(10) << std::endl; } break; } } S1p = S1p_adder.calculate_sum(); if (remainder(n - m, real::TWO) == real::ZERO) { if (m > real::ZERO) { S1p = pow(-real::ONE, m) * (m / real::TWO) * pow(real::ONE - eta * eta, m / real::TWO - real::ONE) * (-real::TWO * eta) * S1 + pow(-real::ONE, m) * pow(real::ONE - eta * eta, m / real::TWO) * S1p; } else { S1p = pow(-real::ONE, m) * S1p; } S1 = pow(-real::ONE, m) * pow(real::ONE - eta * eta, m / real::TWO) * S1; } else { if (m > real::ZERO) { S1p = pow(-real::ONE, m) * pow(real::ONE - eta * eta, m / real::TWO) * S1 + pow(-real::ONE, m) * eta * (m / real::TWO) * pow(real::ONE - eta * eta, m / real::TWO - real::ONE) * (-real::TWO * eta) * S1 + pow(-real::ONE, m) * eta * pow(real::ONE - eta * eta, m / real::TWO) * S1p; } else { S1p = pow(-real::ONE, m) * S1 + pow(-real::ONE, m) * eta * S1p; } S1 = pow(-real::ONE, m) * eta * pow(real::ONE - eta * eta, m / real::TWO) * S1; } } void calculate_Rmn1_1_shared(real & R1, real & R1p, bool verbose, const real & c, const real & m, const real & n, const real & n_dr, const std::vector<real> & dr, const real & xi) { std::vector<real> jn; real b0; std::vector<real> a; std::vector<real> b; real N; real prev_N; real s; std::vector<real> jnp; adder R1_adder; adder R1p_adder; real d; real change; real changep; if (xi > real::ZERO) { jn.clear(); for (real v = real::ZERO; v <= m + n_dr; v = v + real::ONE) { jn.push_back(real::ZERO); } jn[gzbi(m + n_dr)] = real::ONE; for (real v = m + n_dr; v >= real::ONE; v = v - real::ONE) { if (v < m + n_dr) { N = real::ONE / ((real::TWO * v + real::ONE) / (c * xi) - N); } else { b0 = real::ZERO; a.clear(); b.clear(); for (real i = v; i < v + real("10000.0"); i = i + real::ONE) { a.push_back(real::ONE); b.push_back((real::TWO * i + real::ONE) / (c * xi)); N = -calculate_continued_fraction(b0, a, b); if (i > v) { if (abs((N - prev_N) / prev_N) < real::SMALL_ENOUGH) { if (verbose) { std::cout << "calculate_Rmn1_1: " << ((N - prev_N) / prev_N).get_string(10) << std::endl; } break; } } prev_N = N; } } jn[gzbi(v - real::ONE)] = jn[gzbi(v)] / N; } s = (sin(c * xi) / (c * xi)) / jn[gzbi(real::ZERO)]; for (real v = real::ZERO; v <= m + n_dr; v = v + real::ONE) { jn[gzbi(v)] = s * jn[gzbi(v)]; } jnp.clear(); for (real v = real::ZERO; v <= m + n_dr - real::ONE; v = v + real::ONE) { jnp.push_back(real::ZERO); } for (real v = real::ZERO; v <= m + n_dr - real::ONE; v = v + real::ONE) { jnp[gzbi(v)] = (v / (c * xi)) * jn[gzbi(v)] - jn[gzbi(v + real::ONE)]; } } else { jn.clear(); jnp.clear(); for (real v = real::ZERO; v <= m + n_dr - real::ONE; v = v + real::ONE) { jn.push_back(real::ZERO); jnp.push_back(real::ZERO); } jn[gzbi(real::ZERO)] = real::ONE; jnp[gzbi(real::ONE)] = real::ONE / real::THREE; } R1 = real::ZERO; R1_adder.clear(); R1p = real::ZERO; R1p_adder.clear(); if (remainder(n - m, real::TWO) == real::ZERO) { for (real r = real::ZERO; r <= n_dr - real::TWO; r = r + real::TWO) { if (r > real::ZERO) { d = d * -real::ONE * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r)) / ((r - real::ONE) * r)); } else { d = pow(-real::ONE, -(n - m) / real::TWO) * factorial(real::TWO * m); } change = d * dr[gzbi(r)] * jn[gzbi(m + r)]; R1 = R1 + change; R1_adder.add(change); changep = d * dr[gzbi(r)] * jnp[gzbi(m + r)] * c; R1p = R1p + changep; R1p_adder.add(changep); if (r > real::ZERO && abs(change) > real::ZERO && abs(change / R1) < real::SMALL_ENOUGH && abs(changep) > real::ZERO && abs(changep / R1p) < real::SMALL_ENOUGH) { if (verbose) { std::cout << "calculate_Rmn1_1: " << (change / R1).get_string(10) << ", " << (changep / R1p).get_string(10) << ", " << ((R1 - R1_adder.calculate_sum()) / R1_adder.calculate_sum()).get_string(10) << ", " << ((R1p - R1p_adder.calculate_sum()) / R1p_adder.calculate_sum()).get_string(10) << ", " << (change / R1_adder.calculate_sum()).get_string(10) << ", " << (changep / R1p_adder.calculate_sum()).get_string(10) << std::endl; } break; } } } else { for (real r = real::ONE; r <= n_dr - real::ONE; r = r + real::TWO) { if (r > real::ONE) { d = d * -real::ONE * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r)) / ((r - real::ONE) * r)); } else { d = pow(-real::ONE, (real::ONE - (n - m)) / real::TWO) * factorial(real::TWO * m + real::ONE); } change = d * dr[gzbi(r)] * jn[gzbi(m + r)]; R1 = R1 + change; R1_adder.add(change); changep = d * dr[gzbi(r)] * jnp[gzbi(m + r)] * c; R1p = R1p + changep; R1p_adder.add(changep); if (r > real::ONE && abs(change) > real::ZERO && abs(change / R1) < real::SMALL_ENOUGH && abs(changep) > real::ZERO && abs(changep / R1p) < real::SMALL_ENOUGH) { if (verbose) { std::cout << "calculate_Rmn1_1: " << (change / R1).get_string(10) << ", " << (changep / R1p).get_string(10) << ", " << ((R1 - R1_adder.calculate_sum()) / R1_adder.calculate_sum()).get_string(10) << ", " << ((R1p - R1p_adder.calculate_sum()) / R1p_adder.calculate_sum()).get_string(10) << ", " << (change / R1_adder.calculate_sum()).get_string(10) << ", " << (changep / R1p_adder.calculate_sum()).get_string(10) << std::endl; } break; } } } R1 = R1_adder.calculate_sum(); R1p = R1p_adder.calculate_sum(); } void calculate_Rmn2_1_shared(real & R2, real & R2p, bool verbose, const real & c, const real & m, const real & n, const real & n_dr, const std::vector<real> & dr, const real & xi) { real y0; real y1; real y2; adder R2_adder; adder R2p_adder; real a; real y0p; real change; real changep; real y1p; y0 = -cos(c * xi) / (c * xi); y1 = -cos(c * xi) / ((c * xi) * (c * xi)) - sin(c * xi) / (c * xi); for (real v = real::ZERO; v <= m - real::ONE; v = v + real::ONE) { y2 = -y0 + ((real::TWO * v + real::THREE) / (c * xi)) * y1; y0 = y1; y1 = y2; } R2 = real::ZERO; R2_adder.clear(); R2p = real::ZERO; R2p_adder.clear(); if (remainder(n - m, real::TWO) == real::ZERO) { for (real r = real::ZERO; r <= n_dr - real::TWO; r = r + real::TWO) { if (r > real::ZERO) { a = a * -real::ONE * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r)) / ((r - real::ONE) * r)); } else { a = pow(-real::ONE, -(n - m) / real::TWO) * factorial(real::TWO * m); } y0p = ((m + r) / (c * xi)) * y0 - y1; change = a * dr[gzbi(r)] * y0; R2 = R2 + change; R2_adder.add(change); changep = a * dr[gzbi(r)] * y0p * c; R2p = R2p + changep; R2p_adder.add(changep); if (r > real::ZERO && abs(change) > real::ZERO && abs(change / R2) < real::SMALL_ENOUGH && abs(changep) > real::ZERO && abs(changep / R2p) < real::SMALL_ENOUGH) { if (verbose) { std::cout << "calculate_Rmn2_1: " << (change / R2).get_string(10) << ", " << (changep / R2p).get_string(10) << ", " << ((R2 - R2_adder.calculate_sum()) / R2_adder.calculate_sum()).get_string(10) << ", " << ((R2p - R2p_adder.calculate_sum()) / R2p_adder.calculate_sum()).get_string(10) << ", " << (change / R2_adder.calculate_sum()).get_string(10) << ", " << (changep / R2p_adder.calculate_sum()).get_string(10) << std::endl; } break; } y0 = -y0 + ((real::TWO * (m + r) + real::THREE) / (c * xi)) * y1; y1 = -y1 + ((real::TWO * (m + r + real::ONE) + real::THREE) / (c * xi)) * y0; } } else { for (real r = real::ONE; r <= n_dr - real::ONE; r = r + real::TWO) { if (r > real::ONE) { a = a * -real::ONE * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r)) / ((r - real::ONE) * r)); } else { a = pow(-real::ONE, (real::ONE - (n - m)) / real::TWO) * factorial(real::TWO * m + real::ONE); } y1p = y0 - ((m + r + real::ONE) / (c * xi)) * y1; change = a * dr[gzbi(r)] * y1; R2 = R2 + change; R2_adder.add(change); changep = a * dr[gzbi(r)] * y1p * c; R2p = R2p + changep; R2p_adder.add(changep); if (r > real::ONE && abs(change) > real::ZERO && abs(change / R2) < real::SMALL_ENOUGH && abs(changep) > real::ZERO && abs(changep / R2p) < real::SMALL_ENOUGH) { if (verbose) { std::cout << "calculate_Rmn2_1: " << (change / R2).get_string(10) << ", " << (changep / R2p).get_string(10) << ", " << ((R2 - R2_adder.calculate_sum()) / R2_adder.calculate_sum()).get_string(10) << ", " << ((R2p - R2p_adder.calculate_sum()) / R2p_adder.calculate_sum()).get_string(10) << ", " << (change / R2_adder.calculate_sum()).get_string(10) << ", " << (changep / R2p_adder.calculate_sum()).get_string(10) << std::endl; } break; } y0 = -y0 + ((real::TWO * (m + r - real::ONE) + real::THREE) / (c * xi)) * y1; y1 = -y1 + ((real::TWO * (m + r) + real::THREE) / (c * xi)) * y0; } } R2 = R2_adder.calculate_sum(); R2p = R2p_adder.calculate_sum(); }
30.826566
429
0.540979
SabininGV
8e4850d32d9150a7bd458a3aac406739d0b10131
1,900
cpp
C++
example/sqlite.cpp
vashman/data_pattern_sqlite
8ed3d1fe3e86ea7165d43277feb05d84189f696e
[ "BSL-1.0" ]
null
null
null
example/sqlite.cpp
vashman/data_pattern_sqlite
8ed3d1fe3e86ea7165d43277feb05d84189f696e
[ "BSL-1.0" ]
null
null
null
example/sqlite.cpp
vashman/data_pattern_sqlite
8ed3d1fe3e86ea7165d43277feb05d84189f696e
[ "BSL-1.0" ]
null
null
null
// // Copyright Sundeep S. Sangha 2015 - 2017. // 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) #include <cassert> #include <data_pattern/raw.hpp> #include "../src/sqlite.cpp" using data_pattern_sqlite::sqlite; using data_pattern_sqlite::open_database; using data_pattern_sqlite::sqlite_statement; int main () { sqlite db = open_database("testdata"); /* Create the table if it does not exist yet. */ sqlite_statement s1 ( db , "CREATE TABLE IF NOT EXISTS test3" "(Value INT, str TEXT, dec REAL, raw Blob);" ); sqlite_statement query1 ( db , "CREATE TABLE IF NOT EXISTS test" "(ID INT PRIMARY KEY NOT NULL, Value INT);" ); auto query2 = sqlite_statement ( db , "INSERT INTO test3 " "(Value, str, dec, raw) Values (?,?,?,?);" ); bind(query2, 45); bind(query2, std::string("test string")); bind(query2, 12.04); bind(query2, data_pattern::raw<>("0101", 4)); if (is_bind_done(query2)) step(query2); auto query3 ( sqlite_statement ( db, "INSERT INTO test (ID, Value) Values (?, ?);" )); bind(query3, 2); bind(query3, 28); if (is_bind_done(query3)) step(query3); // Retrive data auto select1 ( sqlite_statement (db, "SELECT ID, Value FROM test;")); int tmp_int (column_int(select1)); int temp_int = column_int(select1); assert (tmp_int == 2); assert (temp_int == 28); auto select2 ( sqlite_statement ( db , "SELECT Value, dec, str, raw FROM test3;" )); temp_int = column_int(select2); double temp_dbl (column_double(select2)); auto temp_str = column_string(select2); data_pattern::raw<> temp_raw = column_raw(select2); assert (temp_int == 45); assert (temp_str == sqlite_statement::string_t(reinterpret_cast<const unsigned char*>("test string"))); assert (temp_dbl == 12.04); assert (temp_raw == data_pattern::raw<>("0101", 4)); return 0; }
24.675325
103
0.692632
vashman
8e4ecf58b810f2b9892fe1870855da6f26b49c8c
1,040
hpp
C++
src/renhook/exception.hpp
fengjixuchui/RenHook-1
6b4c305573a0d1356c41f86f6419d55043150c64
[ "MIT" ]
77
2017-06-14T22:11:41.000Z
2022-03-26T21:06:29.000Z
deps/renhook/src/renhook/exception.hpp
Jdiablo/RED4ext-BulkCraft
ca10f8a3b294dfe63fadd73875b1a59992332190
[ "MIT" ]
null
null
null
deps/renhook/src/renhook/exception.hpp
Jdiablo/RED4ext-BulkCraft
ca10f8a3b294dfe63fadd73875b1a59992332190
[ "MIT" ]
23
2017-06-16T02:30:32.000Z
2022-03-26T21:06:31.000Z
#ifndef RENHOOK_EXCEPTION_H #define RENHOOK_EXCEPTION_H #include <cstdint> #include <stdexcept> #include <string> namespace renhook { /** * @brief The general exception of the library. */ class exception : public std::runtime_error { public: /** * @brief Construct a new exception. * * @param[in] message The message. */ exception(const char* message); /** * @brief Construct a new exception. * * @param[in] message The message. */ exception(const std::string& message); /** * @brief Construct a new exception. * * @param[in] message The message. * @param[in] last_error The error code returned by <a href="https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror">GetLastError</a>. */ exception(const std::string& message, uint32_t last_error); ~exception() = default; }; } #endif
24.186047
187
0.579808
fengjixuchui
8e4fadd04b317d1cc26373ba4f4585b22cdfda35
13,209
cpp
C++
ovr_sdk_mobile/VrAppFramework/Src/GlSetup_Windows.cpp
ejeinc/Meganekko
c62d82e8a5d2eb67af056282f4ff7c90cbd73494
[ "Apache-2.0" ]
25
2015-10-08T09:35:35.000Z
2018-09-14T06:53:39.000Z
ovr_sdk_mobile/VrAppFramework/Src/GlSetup_Windows.cpp
ejeinc/Meganekko
c62d82e8a5d2eb67af056282f4ff7c90cbd73494
[ "Apache-2.0" ]
16
2015-09-28T07:21:55.000Z
2017-04-25T02:31:57.000Z
ovr_sdk_mobile/VrAppFramework/Src/GlSetup_Windows.cpp
ejeinc/Meganekko
c62d82e8a5d2eb67af056282f4ff7c90cbd73494
[ "Apache-2.0" ]
11
2016-03-17T02:34:17.000Z
2022-01-19T08:10:35.000Z
/************************************************************************************ Filename : GlSetup.cpp Content : GL Setup Created : August 24, 2013 Authors : John Carmack Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. ************************************************************************************/ #include "GlSetup.h" #include "Kernel/OVR_Types.h" #if defined( OVR_OS_WIN32 ) #include <string.h> #include <stdlib.h> #include "Kernel/OVR_LogUtils.h" #include "OVR_Input.h" #include "AppLocal.h" namespace OVR { #define OPENGL_VERSION_MAJOR 4 #define OPENGL_VERSION_MINOR 1 #define GLSL_PROGRAM_VERSION "410" typedef GLuint64 Microseconds_t; static Microseconds_t GetTimeMicroseconds() { static Microseconds_t ticksPerSecond = 0; static Microseconds_t timeBase = 0; if ( ticksPerSecond == 0 ) { LARGE_INTEGER li; QueryPerformanceFrequency( &li ); ticksPerSecond = (Microseconds_t) li.QuadPart; QueryPerformanceCounter( &li ); timeBase = (Microseconds_t) li.LowPart + 0xFFFFFFFFLL * li.HighPart; } LARGE_INTEGER li; QueryPerformanceCounter( &li ); Microseconds_t counter = (Microseconds_t) li.LowPart + 0xFFFFFFFFLL * li.HighPart; return ( counter - timeBase ) * 1000000LL / ticksPerSecond; } typedef enum { MOUSE_LEFT = 0, MOUSE_RIGHT = 1 } MouseButton_t; typedef struct { HDC hDC; HGLRC hGLRC; } GlContext_t; typedef struct { const GLubyte * glRenderer; const GLubyte * glVersion; GlContext_t glContext; int windowWidth; int windowHeight; float windowRefreshRate; bool windowFullscreen; bool windowActive; bool keyInput[OVR_KEY_MAX]; bool mouseInput[8]; int mouseInputX[8]; int mouseInputY[8]; Microseconds_t lastSwapTime; HINSTANCE hInstance; HWND hWnd; } GlWindow_t; GlWindow_t glWindow; static const int MIN_SLOTS_AVAILABLE_FOR_INPUT = 12; AppLocal * app; LRESULT APIENTRY WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ) { GlWindow_t * window = (GlWindow_t *) GetWindowLongPtr( hWnd, GWLP_USERDATA ); switch ( message ) { case WM_SIZE: { if ( window != NULL ) { window->windowWidth = (int) LOWORD( lParam ); window->windowHeight = (int) HIWORD( lParam ); } return 0; } case WM_ACTIVATE: { if ( window != NULL ) { window->windowActive = !HIWORD( wParam ); } return 0; } case WM_ERASEBKGND: { return 0; } case WM_SETFOCUS: { return 0; } case WM_CLOSE: { PostQuitMessage( 0 ); return 0; } case WM_KEYDOWN: { if ( window != NULL ) { const ovrKeyCode key = OSKeyToKeyCode( (int)wParam ); if ( app && !window->keyInput[key] ) { app->GetMessageQueue().PostPrintfIfSpaceAvailable( MIN_SLOTS_AVAILABLE_FOR_INPUT, "key %i %i %i", key, 1, 0 ); } window->keyInput[key] = true; LOG( "%s down\n", GetNameForKeyCode( key ) ); } break; } case WM_KEYUP: { if ( window != NULL ) { const ovrKeyCode key = OSKeyToKeyCode( ( int ) wParam ); window->keyInput[key] = false; LOG( "%s up\n", GetNameForKeyCode( key ) ); if ( app ) { app->GetMessageQueue().PostPrintfIfSpaceAvailable( MIN_SLOTS_AVAILABLE_FOR_INPUT, "key %i %i %i", key, 0, 0 ); } } break; } case WM_LBUTTONDOWN: { window->mouseInput[MOUSE_LEFT] = true; window->mouseInputX[MOUSE_LEFT] = LOWORD( lParam ); window->mouseInputY[MOUSE_LEFT] = window->windowHeight - HIWORD( lParam ); break; } case WM_RBUTTONDOWN: { window->mouseInput[MOUSE_RIGHT] = true; window->mouseInputX[MOUSE_RIGHT] = LOWORD( lParam ); window->mouseInputY[MOUSE_RIGHT] = window->windowHeight - HIWORD( lParam ); break; } } return DefWindowProc( hWnd, message, wParam, lParam ); } static bool GlWindow_ProcessEvents( GlWindow_t * window, int32_t & exitCode ) { OVR_UNUSED( window ); bool quit = false; exitCode = 0; MSG msg; while ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) > 0 ) { if ( msg.message == WM_QUIT ) { quit = true; exitCode = static_cast<int32_t>( msg.wParam ); break; } else { TranslateMessage( &msg ); DispatchMessage( &msg ); } } return quit; } #if 0 static void GlWindow_SwapInterval( GlWindow_t * window, const int swapInterval ) { OVR_UNUSED( window ); wglSwapIntervalEXT( swapInterval ); } static void GlWindow_SwapBuffers( GlWindow_t * window ) { SwapBuffers( window->glContext.hDC ); window->lastSwapTime = GetTimeMicroseconds(); } static Microseconds_t GlWindow_GetNextSwapTime( GlWindow_t * window ) { return window->lastSwapTime + (Microseconds_t)( 1000.0f * 1000.0f / window->windowRefreshRate ); } static bool GlWindow_CheckMouseButton( GlWindow_t * window, const MouseButton_t button ) { if ( window->mouseInput[button] ) { window->mouseInput[button] = false; return true; } return false; } static bool GlWindow_CheckKeyboardKey( GlWindow_t * window, const ovrKeyCode keyCode ) { if ( window->keyInput[keyCode] ) { window->keyInput[keyCode] = false; return true; } return false; } #endif static void GlWindow_Destroy( GlWindow_t * window ) { if ( window->windowFullscreen ) { ChangeDisplaySettings( NULL, 0 ); ShowCursor( TRUE ); } if ( window->glContext.hGLRC ) { if ( !wglMakeCurrent( NULL, NULL ) ) { FAIL( "Failed to release context." ); } if ( !wglDeleteContext( window->glContext.hGLRC ) ) { FAIL( "Failed to delete context." ); } window->glContext.hGLRC = NULL; } if ( window->glContext.hDC ) { if ( !ReleaseDC( window->hWnd, window->glContext.hDC ) ) { FAIL( "Failed to release device context." ); } window->glContext.hDC = NULL; } if ( window->hWnd ) { if ( !DestroyWindow( window->hWnd ) ) { FAIL( "Failed to destroy the window." ); } window->hWnd = NULL; } if ( window->hInstance ) { if ( !UnregisterClass( "OpenGL", window->hInstance ) ) { FAIL( "Failed to unregister window class." ); } window->hInstance = NULL; } } static bool GlWindow_Create( GlWindow_t * window, const int width, const int height, const int colorBits, const int depthBits, const bool fullscreen, const char * title, const unsigned int iconResId ) { memset( window, 0, sizeof( GlWindow_t ) ); window->windowWidth = width; window->windowHeight = height; window->windowRefreshRate = 60; window->windowFullscreen = fullscreen; window->windowActive = true; window->lastSwapTime = GetTimeMicroseconds(); window->hInstance = GetModuleHandle( NULL ); WNDCLASS wc; wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = (WNDPROC) WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = window->hInstance; wc.hIcon = LoadIcon( window->hInstance, MAKEINTRESOURCE( iconResId ) ); wc.hCursor = LoadCursor( NULL, IDC_ARROW ); wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = "OpenGL"; if ( !RegisterClass( &wc ) ) { FAIL( "Failed to register window class." ); } if ( fullscreen ) { DEVMODE dmScreenSettings; memset( &dmScreenSettings, 0, sizeof( dmScreenSettings ) ); dmScreenSettings.dmSize = sizeof( dmScreenSettings ); dmScreenSettings.dmPelsWidth = width; dmScreenSettings.dmPelsHeight = height; dmScreenSettings.dmBitsPerPel = 32; dmScreenSettings.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL; if ( ChangeDisplaySettings( &dmScreenSettings, CDS_FULLSCREEN ) != DISP_CHANGE_SUCCESSFUL ) { FAIL( "The requested fullscreen mode is not supported." ); } } DEVMODE lpDevMode; memset( &lpDevMode, 0, sizeof( DEVMODE ) ); lpDevMode.dmSize = sizeof( DEVMODE ); lpDevMode.dmDriverExtra = 0; if ( EnumDisplaySettings( NULL, ENUM_CURRENT_SETTINGS, &lpDevMode ) != FALSE ) { window->windowRefreshRate = (float)lpDevMode.dmDisplayFrequency; } DWORD dwExStyle = 0; DWORD dwStyle = 0; if ( fullscreen ) { dwExStyle = WS_EX_APPWINDOW; dwStyle = WS_POPUP; ShowCursor( FALSE ); } else { // Fixed size window. dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; dwStyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX; } RECT windowRect; windowRect.left = (long)0; windowRect.right = (long)width; windowRect.top = (long)0; windowRect.bottom = (long)height; AdjustWindowRectEx( &windowRect, dwStyle, FALSE, dwExStyle ); if ( !fullscreen ) { RECT desktopRect; GetWindowRect( GetDesktopWindow(), &desktopRect ); const int offsetX = ( desktopRect.right - ( windowRect.right - windowRect.left ) ) / 2; const int offsetY = ( desktopRect.bottom - ( windowRect.bottom - windowRect.top ) ) / 2; windowRect.left += offsetX; windowRect.right += offsetX; windowRect.top += offsetY; windowRect.bottom += offsetY; } window->hWnd = CreateWindowEx( dwExStyle, // Extended style for the window "OpenGL", // Class name title, // Window title dwStyle | // Defined window style WS_CLIPSIBLINGS | // Required window style WS_CLIPCHILDREN, // Required window style windowRect.left, // Window X position windowRect.top, // Window Y position windowRect.right - windowRect.left, // Window width windowRect.bottom - windowRect.top, // Window height NULL, // No parent window NULL, // No menu window->hInstance, // Instance NULL ); if ( !window->hWnd ) { GlWindow_Destroy( window ); FAIL( "Failed to create window." ); } SetWindowLongPtr( window->hWnd, GWLP_USERDATA, (LONG_PTR) window ); window->glContext.hDC = GetDC( window->hWnd ); if ( !window->glContext.hDC ) { GlWindow_Destroy( window ); FAIL( "Failed to acquire device context." ); } PIXELFORMATDESCRIPTOR pfd = { sizeof( PIXELFORMATDESCRIPTOR ), 1, // version PFD_DRAW_TO_WINDOW | // must support windowed PFD_SUPPORT_OPENGL | // must support OpenGL PFD_DOUBLEBUFFER, // must support double buffering PFD_TYPE_RGBA, // iPixelType (BYTE)colorBits, // cColorBits 0, 0, // cRedBits, cRedShift 0, 0, // cGreenBits, cGreenShift 0, 0, // cBlueBits, cBlueShift 0, 0, // cAlphaBits, cAlphaShift 0, // cAccumBits 0, // cAccumRedBits 0, // cAccumGreenBits 0, // cAccumBlueBits 0, // cAccumAlphaBits (BYTE)depthBits, // cDepthBits 0, // cStencilBits 0, // cAuxBuffers PFD_MAIN_PLANE, // iLayerType 0, // bReserved 0, // dwLayerMask 0, // dwVisibleMask 0 // dwDamageMask }; GLuint pixelFormat = ChoosePixelFormat( window->glContext.hDC, &pfd ); if ( pixelFormat == 0 ) { GlWindow_Destroy( window ); FAIL( "Failed to find a suitable PixelFormat." ); } if ( !SetPixelFormat( window->glContext.hDC, pixelFormat, &pfd ) ) { GlWindow_Destroy( window ); FAIL( "Failed to set the PixelFormat." ); } // temporarily create a context to get the extensions { HGLRC hGLRC = wglCreateContext( window->glContext.hDC ); wglMakeCurrent( window->glContext.hDC, hGLRC ); GL_InitExtensions(); wglMakeCurrent( NULL, NULL ); wglDeleteContext( hGLRC ); } int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, OPENGL_VERSION_MAJOR, WGL_CONTEXT_MINOR_VERSION_ARB, OPENGL_VERSION_MINOR, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, 0 }; window->glContext.hGLRC = wglCreateContextAttribsARB( window->glContext.hDC, NULL, attribs ); if ( !window->glContext.hGLRC ) { GlWindow_Destroy( window ); FAIL( "Failed to create GL context." ); } if ( !wglMakeCurrent( window->glContext.hDC, window->glContext.hGLRC ) ) { GlWindow_Destroy( window ); FAIL( "Failed to activate GL context." ); } ShowWindow( window->hWnd, SW_SHOW ); SetForegroundWindow( window->hWnd ); SetFocus( window->hWnd ); window->glRenderer = glGetString( GL_RENDERER ); window->glVersion = glGetString( GL_VERSION ); LOG( "--------------------------------\n" ); //LOG( "OS : %s\n", GetOSVersion() ); LOG( "GPU : %s\n", window->glRenderer ); LOG( "DRIVER : %s\n", window->glVersion ); LOG( "MODE : %s %dx%d %1.0f Hz\n", fullscreen ? "fullscreen" : "windowed", window->windowWidth, window->windowHeight, window->windowRefreshRate ); return true; } glSetup_t GL_Setup( const int windowWidth, const int windowHeight, const bool fullscreen, const char * windowTitle, const unsigned int iconResId, AppLocal * appLocal ) { glSetup_t gl = {}; app = appLocal; GlWindow_Create( &glWindow, windowWidth, windowHeight, 32, 0, fullscreen, windowTitle, iconResId ); return gl; } void GL_Shutdown( glSetup_t & glSetup ) { app = NULL; GlWindow_Destroy( &glWindow ); } bool GL_ProcessEvents( int32_t & exitCode ) { bool exit = false; //const Microseconds_t time = GetTimeMicroseconds(); if ( GlWindow_ProcessEvents( &glWindow, exitCode ) ) { exit = true; } if ( glWindow.windowActive ) { //GlWindow_SwapBuffers( &glWindow ); //sceneThreadData.nextSwapTime = GlWindow_GetNextSwapTime( &glWindow ); } return exit; } } // namespace OVR #endif // OVR_OS_WIN32
24.236697
149
0.663184
ejeinc
8e56dacb9ee6afeda813d52865390d9dae70ab66
956
hpp
C++
boost/network/protocol/http/message/wrappers/uri.hpp
sureandrew/cpp-netlib
a4dabd50dcd42f46ac152c733a3d39f32040185d
[ "BSL-1.0" ]
null
null
null
boost/network/protocol/http/message/wrappers/uri.hpp
sureandrew/cpp-netlib
a4dabd50dcd42f46ac152c733a3d39f32040185d
[ "BSL-1.0" ]
null
null
null
boost/network/protocol/http/message/wrappers/uri.hpp
sureandrew/cpp-netlib
a4dabd50dcd42f46ac152c733a3d39f32040185d
[ "BSL-1.0" ]
1
2018-08-07T07:27:49.000Z
2018-08-07T07:27:49.000Z
#ifndef BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_WRAPPERS_URI_HPP_20100620 #define BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_WRAPPERS_URI_HPP_20100620 // Copyright 2010 (c) Dean Michael Berris. // Copyright 2010 (c) Sinefunc, Inc. // 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) #include <network/uri/uri.hpp> #include <boost/network/protocol/http/request/request_base.hpp> namespace boost { namespace network { namespace http { struct uri_wrapper { explicit uri_wrapper(request_base const & request_); operator std::string() const; operator ::network::uri() const; private: request_base const & request_; }; inline uri_wrapper const uri(request_base const & request) { return uri_wrapper(request); } } // namespace http } // namespace network } // namespace boost #endif // BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_WRAPPERS_URI_HPP_20100620
26.555556
71
0.781381
sureandrew
8e57e7856a533c08f12ef719a0868f644ad6d3f9
1,331
cpp
C++
core/main_thread.cpp
mail-ru-im/im-desktop
d6bb606650ad84b31046fe39b81db1fec4e6050b
[ "Apache-2.0" ]
81
2019-09-18T13:53:17.000Z
2022-03-19T00:44:20.000Z
core/main_thread.cpp
mail-ru-im/im-desktop
d6bb606650ad84b31046fe39b81db1fec4e6050b
[ "Apache-2.0" ]
4
2019-10-03T15:17:00.000Z
2019-11-03T01:05:41.000Z
core/main_thread.cpp
mail-ru-im/im-desktop
d6bb606650ad84b31046fe39b81db1fec4e6050b
[ "Apache-2.0" ]
25
2019-09-27T16:56:02.000Z
2022-03-14T07:11:14.000Z
#include "stdafx.h" #include "main_thread.h" #include "core.h" #include "network_log.h" using namespace core; main_thread::main_thread() : threadpool("core main", 1 ) { set_task_finish_callback([](std::chrono::milliseconds _task_execute_time, const stack_vec& _st, std::string_view _name) { if (_task_execute_time > std::chrono::milliseconds(200) && !_st.empty()) { std::stringstream ss; ss << "ATTENTION! Core locked, "; if (!_name.empty()) ss << "task name: " << _name << ", "; ss << _task_execute_time.count() << " milliseconds\r\n\r\n"; for (const auto& s : _st) { ss << *s; ss << "\r\n - - - - - \r\n"; } g_core->write_string_to_network_log(ss.str()); } }); } main_thread::~main_thread() = default; void main_thread::execute_core_context(stacked_task task) { push_back(std::move(task)); } std::thread::id main_thread::get_core_thread_id() const { if (const auto& thread_ids = get_threads_ids(); thread_ids.size() == 1) { return thread_ids[0]; } else { im_assert(thread_ids.size() == 1); return std::thread::id(); // nobody } }
24.648148
124
0.53118
mail-ru-im
8e5abab2793e3ecc6caf804343f73b68f68383e0
1,327
cpp
C++
atcoder/panasonic2020_e.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
1
2020-04-04T14:56:12.000Z
2020-04-04T14:56:12.000Z
atcoder/panasonic2020_e.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
atcoder/panasonic2020_e.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; const int Z = 100005; const int N = 100005; bool ab[N+Z], ac[N+Z], bc[N+Z]; bool match(char c0, char c1){ return (c0=='?'||c1=='?'||c0==c1); } // prep ab/ac/bc possible shift // brute-force ab,ac shift, since which decide bc shift. void solve() { string a,b,c; cin >> a >> b >> c; int A = a.size(); int B = b.size(); int C = c.size(); int res = A+B+C; for (int i = 0; i < A; i++) { for (int j = 0; j < B; j++) { if (!match(a[i], b[j])) ab[i-j + Z] = 1; } } for (int i = 0; i < A; i++) { for (int j = 0; j < C; j++) { if (!match(a[i], c[j])) ac[i-j + Z] = 1; } } for (int i = 0; i < B; i++) { for (int j = 0; j < C; j++) { if (!match(b[i], c[j])) bc[i-j + Z] = 1; } } const int M = 2020 * 2; for (int i = -M; i < M; i++) { for (int j = -M; j < M; j++) { if (!ab[i+Z] && !ac[j+Z] && !bc[j-i+Z]) { int L = min({0,i,j}); int R = max({A,i+B,j+C}); res = min(res, R-L); } } } cout << res; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); return 0; }
22.116667
56
0.379804
sogapalag
8e5cd80a6c178aa7527c6a86043feb6b5f7019f2
10,986
cpp
C++
src/entity/RTraceEntity.cpp
ouxianghui/ezcam
195fb402202442b6d035bd70853f2d8c3f615de1
[ "MIT" ]
12
2021-03-26T03:23:30.000Z
2021-12-31T10:05:44.000Z
src/entity/RTraceEntity.cpp
15831944/ezcam
195fb402202442b6d035bd70853f2d8c3f615de1
[ "MIT" ]
null
null
null
src/entity/RTraceEntity.cpp
15831944/ezcam
195fb402202442b6d035bd70853f2d8c3f615de1
[ "MIT" ]
9
2021-06-23T08:26:40.000Z
2022-01-20T07:18:10.000Z
/** * Copyright (c) 2011-2016 by Andrew Mustun. All rights reserved. * * This file is part of the QCAD project. * * QCAD 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. * * QCAD 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 QCAD. */ #include "RTraceEntity.h" #include "RExporter.h" #include "RLine.h" RPropertyTypeId RTraceEntity::PropertyCustom; RPropertyTypeId RTraceEntity::PropertyHandle; RPropertyTypeId RTraceEntity::PropertyProtected; RPropertyTypeId RTraceEntity::PropertyType; RPropertyTypeId RTraceEntity::PropertyBlock; RPropertyTypeId RTraceEntity::PropertyLayer; RPropertyTypeId RTraceEntity::PropertyLinetype; RPropertyTypeId RTraceEntity::PropertyLinetypeScale; RPropertyTypeId RTraceEntity::PropertyLineweight; RPropertyTypeId RTraceEntity::PropertyColor; RPropertyTypeId RTraceEntity::PropertyDisplayedColor; RPropertyTypeId RTraceEntity::PropertyDrawOrder; RPropertyTypeId RTraceEntity::PropertyPoint1X; RPropertyTypeId RTraceEntity::PropertyPoint1Y; RPropertyTypeId RTraceEntity::PropertyPoint1Z; RPropertyTypeId RTraceEntity::PropertyPoint2X; RPropertyTypeId RTraceEntity::PropertyPoint2Y; RPropertyTypeId RTraceEntity::PropertyPoint2Z; RPropertyTypeId RTraceEntity::PropertyPoint3X; RPropertyTypeId RTraceEntity::PropertyPoint3Y; RPropertyTypeId RTraceEntity::PropertyPoint3Z; RPropertyTypeId RTraceEntity::PropertyPoint4X; RPropertyTypeId RTraceEntity::PropertyPoint4Y; RPropertyTypeId RTraceEntity::PropertyPoint4Z; RPropertyTypeId RTraceEntity::PropertyLength; RPropertyTypeId RTraceEntity::PropertyTotalLength; RTraceEntity::RTraceEntity(RDocument* document, const RTraceData& data) : REntity(document), data(document, data) { } RTraceEntity::~RTraceEntity() { } void RTraceEntity::init() { RTraceEntity::PropertyCustom.generateId(typeid(RTraceEntity), RObject::PropertyCustom); RTraceEntity::PropertyHandle.generateId(typeid(RTraceEntity), RObject::PropertyHandle); RTraceEntity::PropertyProtected.generateId(typeid(RTraceEntity), RObject::PropertyProtected); RTraceEntity::PropertyType.generateId(typeid(RTraceEntity), REntity::PropertyType); RTraceEntity::PropertyBlock.generateId(typeid(RTraceEntity), REntity::PropertyBlock); RTraceEntity::PropertyLayer.generateId(typeid(RTraceEntity), REntity::PropertyLayer); RTraceEntity::PropertyLinetype.generateId(typeid(RTraceEntity), REntity::PropertyLinetype); RTraceEntity::PropertyLinetypeScale.generateId(typeid(RTraceEntity), REntity::PropertyLinetypeScale); RTraceEntity::PropertyLineweight.generateId(typeid(RTraceEntity), REntity::PropertyLineweight); RTraceEntity::PropertyColor.generateId(typeid(RTraceEntity), REntity::PropertyColor); RTraceEntity::PropertyDisplayedColor.generateId(typeid(RTraceEntity), REntity::PropertyDisplayedColor); RTraceEntity::PropertyDrawOrder.generateId(typeid(RTraceEntity), REntity::PropertyDrawOrder); RTraceEntity::PropertyPoint1X.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 1"), QT_TRANSLATE_NOOP("REntity", "X")); RTraceEntity::PropertyPoint1Y.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 1"), QT_TRANSLATE_NOOP("REntity", "Y")); RTraceEntity::PropertyPoint1Z.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 1"), QT_TRANSLATE_NOOP("REntity", "Z")); RTraceEntity::PropertyPoint2X.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 2"), QT_TRANSLATE_NOOP("REntity", "X")); RTraceEntity::PropertyPoint2Y.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 2"), QT_TRANSLATE_NOOP("REntity", "Y")); RTraceEntity::PropertyPoint2Z.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 2"), QT_TRANSLATE_NOOP("REntity", "Z")); RTraceEntity::PropertyPoint3X.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 3"), QT_TRANSLATE_NOOP("REntity", "X")); RTraceEntity::PropertyPoint3Y.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 3"), QT_TRANSLATE_NOOP("REntity", "Y")); RTraceEntity::PropertyPoint3Z.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 3"), QT_TRANSLATE_NOOP("REntity", "Z")); RTraceEntity::PropertyPoint4X.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 4"), QT_TRANSLATE_NOOP("REntity", "X")); RTraceEntity::PropertyPoint4Y.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 4"), QT_TRANSLATE_NOOP("REntity", "Y")); RTraceEntity::PropertyPoint4Z.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 4"), QT_TRANSLATE_NOOP("REntity", "Z")); RTraceEntity::PropertyLength.generateId(typeid(RTraceEntity), "", QT_TRANSLATE_NOOP("REntity", "Length")); RTraceEntity::PropertyTotalLength.generateId(typeid(RTraceEntity), "", QT_TRANSLATE_NOOP("REntity", "Total Length")); } bool RTraceEntity::setProperty(RPropertyTypeId propertyTypeId, const QVariant& value, RTransaction* transaction) { bool ret = REntity::setProperty(propertyTypeId, value, transaction); if (propertyTypeId==PropertyPoint1X || propertyTypeId==PropertyPoint1Y || propertyTypeId==PropertyPoint1Z) { RVector v = data.getVertexAt(0); if (propertyTypeId==PropertyPoint1X) { v.x = value.toDouble(); } else if (propertyTypeId==PropertyPoint1Y) { v.y = value.toDouble(); } else if (propertyTypeId==PropertyPoint1Z) { v.z = value.toDouble(); } data.setVertexAt(0, v); ret = true; } else if (propertyTypeId==PropertyPoint2X || propertyTypeId==PropertyPoint2Y || propertyTypeId==PropertyPoint2Z) { RVector v = data.getVertexAt(1); if (propertyTypeId==PropertyPoint2X) { v.x = value.toDouble(); } else if (propertyTypeId==PropertyPoint2Y) { v.y = value.toDouble(); } else if (propertyTypeId==PropertyPoint2Z) { v.z = value.toDouble(); } data.setVertexAt(1, v); ret = true; } else if (propertyTypeId==PropertyPoint3X || propertyTypeId==PropertyPoint3Y || propertyTypeId==PropertyPoint3Z) { RVector v = data.getVertexAt(2); if (propertyTypeId==PropertyPoint3X) { v.x = value.toDouble(); } else if (propertyTypeId==PropertyPoint3Y) { v.y = value.toDouble(); } else if (propertyTypeId==PropertyPoint3Z) { v.z = value.toDouble(); } data.setVertexAt(2, v); ret = true; } else if (propertyTypeId==PropertyPoint4X || propertyTypeId==PropertyPoint4Y || propertyTypeId==PropertyPoint4Z) { if (data.countVertices()<4) { data.appendVertex(RVector(0,0,0)); } RVector v = data.getVertexAt(3); if (propertyTypeId==PropertyPoint4X) { v.x = value.toDouble(); } else if (propertyTypeId==PropertyPoint4Y) { v.y = value.toDouble(); } else if (propertyTypeId==PropertyPoint4Z) { v.z = value.toDouble(); } data.setVertexAt(3, v); ret = true; } return ret; } QPair<QVariant, RPropertyAttributes> RTraceEntity::getProperty( RPropertyTypeId& propertyTypeId, bool humanReadable, bool noAttributes) { if (propertyTypeId == PropertyPoint1X) { return qMakePair(QVariant(data.getVertexAt(0).x), RPropertyAttributes()); } else if (propertyTypeId == PropertyPoint1Y) { return qMakePair(QVariant(data.getVertexAt(0).y), RPropertyAttributes()); } else if (propertyTypeId == PropertyPoint1Z) { return qMakePair(QVariant(data.getVertexAt(0).z), RPropertyAttributes()); } else if (propertyTypeId == PropertyPoint2X) { return qMakePair(QVariant(data.getVertexAt(1).x), RPropertyAttributes()); } else if (propertyTypeId == PropertyPoint2Y) { return qMakePair(QVariant(data.getVertexAt(1).y), RPropertyAttributes()); } else if (propertyTypeId == PropertyPoint2Z) { return qMakePair(QVariant(data.getVertexAt(1).z), RPropertyAttributes()); }else if (propertyTypeId == PropertyPoint3X) { return qMakePair(QVariant(data.getVertexAt(2).x), RPropertyAttributes()); } else if (propertyTypeId == PropertyPoint3Y) { return qMakePair(QVariant(data.getVertexAt(2).y), RPropertyAttributes()); } else if (propertyTypeId == PropertyPoint3Z) { return qMakePair(QVariant(data.getVertexAt(2).z), RPropertyAttributes()); }else if (propertyTypeId == PropertyPoint4X) { if (data.countVertices()<4) { return qMakePair(QVariant(), RPropertyAttributes()); } return qMakePair(QVariant(data.getVertexAt(3).x), RPropertyAttributes()); } else if (propertyTypeId == PropertyPoint4Y) { if (data.countVertices()<4) { return qMakePair(QVariant(), RPropertyAttributes()); } return qMakePair(QVariant(data.getVertexAt(3).y), RPropertyAttributes()); } else if (propertyTypeId == PropertyPoint4Z) { if (data.countVertices()<4) { return qMakePair(QVariant(), RPropertyAttributes()); } return qMakePair(QVariant(data.getVertexAt(3).z), RPropertyAttributes()); } else if (propertyTypeId==PropertyLength) { return qMakePair(QVariant(data.getLength()), RPropertyAttributes(RPropertyAttributes::ReadOnly)); } else if (propertyTypeId==PropertyTotalLength) { return qMakePair(QVariant(data.getLength()), RPropertyAttributes(RPropertyAttributes::Sum)); } return REntity::getProperty(propertyTypeId, humanReadable, noAttributes); } void RTraceEntity::exportEntity(RExporter& e, bool preview, bool forceSelected) const { Q_UNUSED(preview); Q_UNUSED(forceSelected); // note that order of fourth and third vertex is swapped: RPolyline pl; pl.appendVertex(data.getVertexAt(0)); pl.appendVertex(data.getVertexAt(1)); if (data.countVertices()>3) { pl.appendVertex(data.getVertexAt(3)); } pl.appendVertex(data.getVertexAt(2)); pl.setClosed(true); e.exportPolyline(pl); } void RTraceEntity::print(QDebug dbg) const { dbg.nospace() << "RTraceEntity("; REntity::print(dbg); dbg.nospace() << ", p1: " << getData().getVertexAt(0) << ", p2: " << getData().getVertexAt(1) << ", p3: " << getData().getVertexAt(2) << ", p4: " << getData().getVertexAt(3); dbg.nospace() << ")"; }
47.558442
143
0.712725
ouxianghui
769defd8740a99022c6aa54d6f2c3fa273a2c056
2,595
cpp
C++
include/h3api/H3AdventureMap/H3TileVision.cpp
Patrulek/H3API
91f10de37c6b86f3160706c1fdf4792f927e9952
[ "MIT" ]
14
2020-09-07T21:49:26.000Z
2021-11-29T18:09:41.000Z
include/h3api/H3AdventureMap/H3TileVision.cpp
Day-of-Reckoning/H3API
a82d3069ec7d5127b13528608d5350d2b80d57be
[ "MIT" ]
2
2021-02-12T15:52:31.000Z
2021-02-12T16:21:24.000Z
include/h3api/H3AdventureMap/H3TileVision.cpp
Day-of-Reckoning/H3API
a82d3069ec7d5127b13528608d5350d2b80d57be
[ "MIT" ]
8
2021-02-12T15:52:41.000Z
2022-01-31T15:28:10.000Z
////////////////////////////////////////////////////////////////////// // // // Created by RoseKavalier: // // rosekavalierhc@gmail.com // // Created or last updated on: 2021-02-02 // // ***You may use or distribute these files freely // // so long as this notice remains present.*** // // // ////////////////////////////////////////////////////////////////////// #include "h3api/H3AdventureMap/H3TileVision.hpp" #include "h3api/H3GameData/H3Main.hpp" #include "h3api/H3Defines/H3PrimitivePointers.hpp" namespace h3 { _H3API_ H3TileVision& H3TileVision::GetTile(INT32 x, INT32 y, INT32 z) { return FASTCALL_3(H3TileVision&, 0x4F8070, x, y, z); } _H3API_ H3TileVision& H3TileVision::GetTile(const H3Point& p) { return GetTile(p.x, p.y, p.z); } _H3API_ H3TileVision& H3TileVision::GetTile(const H3Position& p) { return GetTile(p.Unpack()); } _H3API_ BOOL H3TileVision::CanViewTile(INT32 x, INT32 y, INT32 z, INT32 player /*= -1*/) { if (player < 0) player = H3CurrentPlayerID::Get(); return GetTile(x, y, z).vision.bits & (1 << player); } _H3API_ BOOL H3TileVision::CanViewTile(const H3Point& p, INT32 player /*= -1*/) { return CanViewTile(p.x, p.y, p.z, player); } _H3API_ BOOL H3TileVision::CanViewTile(const H3Position& p, INT32 player /*= -1*/) { return CanViewTile(p.Unpack(), player); } _H3API_ VOID H3TileVision::RevealTile(INT32 x, INT32 y, INT32 z, INT32 player /*= -1*/) { if (player < 0) player = H3CurrentPlayerID::Get(); GetTile(x, y, z).vision.bits |= (1 << player); } _H3API_ VOID H3TileVision::RevealTile(const H3Point& p, INT32 player /*= -1*/) { RevealTile(p.x, p.y, p.z, player); } _H3API_ VOID H3TileVision::RevealTile(const H3Position& p, INT32 player /*= -1*/) { RevealTile(p.Unpack(), player); } _H3API_ H3Map<H3TileVision> H3TileVision::GetMap() { return H3Map<H3TileVision>(Get(), H3MapSize::Get(), H3Main::Get()->mainSetup.hasUnderground); } _H3API_ H3FastMap<H3TileVision> H3TileVision::GetFastMap() { return H3FastMap<H3TileVision>(Get(), H3MapSize::Get(), H3Main::Get()->mainSetup.hasUnderground); } } /* namespace h3 */
34.144737
105
0.522158
Patrulek
769ed23d7bc17685b900dd6605268355e92b9783
450
cpp
C++
src/editor/Game/entity.cpp
mkRPGDev/mkRPG
154e5d264dc1cc5fba78980da430e9d7ca0ccc22
[ "Beerware" ]
2
2016-10-06T10:09:10.000Z
2016-10-07T14:16:19.000Z
src/editor/Game/entity.cpp
mkRPGDev/mkRPG
154e5d264dc1cc5fba78980da430e9d7ca0ccc22
[ "Beerware" ]
17
2016-12-01T10:10:23.000Z
2017-01-12T16:41:51.000Z
src/editor/Game/entity.cpp
mkRPGDev/mkRPG
154e5d264dc1cc5fba78980da430e9d7ca0ccc22
[ "Beerware" ]
null
null
null
#include "entity.h" EntityType::EntityType(EntityType &ancestor) : Type(ancestor), aImage(nullptr) { } EntityType::EntityType(DefaultTypes &parent) : Type(parent), aImage(nullptr) { setName(QObject::tr("EntityTypes")); setName(typeName()); SetFlag(sleeping, true); setParam("life", 79); setParam("x", 5); setParam("y", 5); } Entity::Entity(EntityType &type, GameObject &parent) : TypedObject(type,parent) { }
18
54
0.657778
mkRPGDev
76a0f911415009e618f4e6ef65547f4a0aa9124e
19,086
cpp
C++
src/odb/src/def/cdef/xdefiPinCap.cpp
erictaur/OpenROAD
438dbb41316fc7fe27e2c405078aa465395125ba
[ "BSD-3-Clause" ]
525
2019-11-20T00:21:42.000Z
2022-03-31T05:38:44.000Z
src/odb/src/def/cdef/xdefiPinCap.cpp
erictaur/OpenROAD
438dbb41316fc7fe27e2c405078aa465395125ba
[ "BSD-3-Clause" ]
741
2019-11-20T15:19:38.000Z
2022-03-31T23:09:17.000Z
src/odb/src/def/cdef/xdefiPinCap.cpp
erictaur/OpenROAD
438dbb41316fc7fe27e2c405078aa465395125ba
[ "BSD-3-Clause" ]
215
2019-11-25T13:37:43.000Z
2022-03-28T00:51:29.000Z
// ***************************************************************************** // ***************************************************************************** // ATTENTION: THIS IS AN AUTO-GENERATED FILE. DO NOT CHANGE IT! // ***************************************************************************** // ***************************************************************************** // Copyright 2012, Cadence Design Systems // // This file is part of the Cadence LEF/DEF Open Source // Distribution, Product Version 5.8. // // 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. // // // For updates, support, or to become part of the LEF/DEF Community, // check www.openeda.org for details. // // $Author: xxx $ // $Revision: xxx $ // $Date: xxx $ // $State: xxx $ // ***************************************************************************** // ***************************************************************************** #define EXTERN extern "C" #include "defiPinCap.h" #include "defiPinCap.hpp" // Wrappers definitions. int defiPinCap_pin (const ::defiPinCap* obj) { return ((LefDefParser::defiPinCap*)obj)->pin(); } double defiPinCap_cap (const ::defiPinCap* obj) { return ((LefDefParser::defiPinCap*)obj)->cap(); } void defiPinCap_print (const ::defiPinCap* obj, FILE* f) { ((LefDefParser::defiPinCap*)obj)->print(f); } char* defiPinAntennaModel_antennaOxide (const ::defiPinAntennaModel* obj) { return ((LefDefParser::defiPinAntennaModel*)obj)->antennaOxide(); } int defiPinAntennaModel_hasAPinGateArea (const ::defiPinAntennaModel* obj) { return ((LefDefParser::defiPinAntennaModel*)obj)->hasAPinGateArea(); } int defiPinAntennaModel_numAPinGateArea (const ::defiPinAntennaModel* obj) { return ((LefDefParser::defiPinAntennaModel*)obj)->numAPinGateArea(); } int defiPinAntennaModel_APinGateArea (const ::defiPinAntennaModel* obj, int index) { return ((LefDefParser::defiPinAntennaModel*)obj)->APinGateArea(index); } int defiPinAntennaModel_hasAPinGateAreaLayer (const ::defiPinAntennaModel* obj, int index) { return ((LefDefParser::defiPinAntennaModel*)obj)->hasAPinGateAreaLayer(index); } const char* defiPinAntennaModel_APinGateAreaLayer (const ::defiPinAntennaModel* obj, int index) { return ((const LefDefParser::defiPinAntennaModel*)obj)->APinGateAreaLayer(index); } int defiPinAntennaModel_hasAPinMaxAreaCar (const ::defiPinAntennaModel* obj) { return ((LefDefParser::defiPinAntennaModel*)obj)->hasAPinMaxAreaCar(); } int defiPinAntennaModel_numAPinMaxAreaCar (const ::defiPinAntennaModel* obj) { return ((LefDefParser::defiPinAntennaModel*)obj)->numAPinMaxAreaCar(); } int defiPinAntennaModel_APinMaxAreaCar (const ::defiPinAntennaModel* obj, int index) { return ((LefDefParser::defiPinAntennaModel*)obj)->APinMaxAreaCar(index); } int defiPinAntennaModel_hasAPinMaxAreaCarLayer (const ::defiPinAntennaModel* obj, int index) { return ((LefDefParser::defiPinAntennaModel*)obj)->hasAPinMaxAreaCarLayer(index); } const char* defiPinAntennaModel_APinMaxAreaCarLayer (const ::defiPinAntennaModel* obj, int index) { return ((const LefDefParser::defiPinAntennaModel*)obj)->APinMaxAreaCarLayer(index); } int defiPinAntennaModel_hasAPinMaxSideAreaCar (const ::defiPinAntennaModel* obj) { return ((LefDefParser::defiPinAntennaModel*)obj)->hasAPinMaxSideAreaCar(); } int defiPinAntennaModel_numAPinMaxSideAreaCar (const ::defiPinAntennaModel* obj) { return ((LefDefParser::defiPinAntennaModel*)obj)->numAPinMaxSideAreaCar(); } int defiPinAntennaModel_APinMaxSideAreaCar (const ::defiPinAntennaModel* obj, int index) { return ((LefDefParser::defiPinAntennaModel*)obj)->APinMaxSideAreaCar(index); } int defiPinAntennaModel_hasAPinMaxSideAreaCarLayer (const ::defiPinAntennaModel* obj, int index) { return ((LefDefParser::defiPinAntennaModel*)obj)->hasAPinMaxSideAreaCarLayer(index); } const char* defiPinAntennaModel_APinMaxSideAreaCarLayer (const ::defiPinAntennaModel* obj, int index) { return ((const LefDefParser::defiPinAntennaModel*)obj)->APinMaxSideAreaCarLayer(index); } int defiPinAntennaModel_hasAPinMaxCutCar (const ::defiPinAntennaModel* obj) { return ((LefDefParser::defiPinAntennaModel*)obj)->hasAPinMaxCutCar(); } int defiPinAntennaModel_numAPinMaxCutCar (const ::defiPinAntennaModel* obj) { return ((LefDefParser::defiPinAntennaModel*)obj)->numAPinMaxCutCar(); } int defiPinAntennaModel_APinMaxCutCar (const ::defiPinAntennaModel* obj, int index) { return ((LefDefParser::defiPinAntennaModel*)obj)->APinMaxCutCar(index); } int defiPinAntennaModel_hasAPinMaxCutCarLayer (const ::defiPinAntennaModel* obj, int index) { return ((LefDefParser::defiPinAntennaModel*)obj)->hasAPinMaxCutCarLayer(index); } const char* defiPinAntennaModel_APinMaxCutCarLayer (const ::defiPinAntennaModel* obj, int index) { return ((const LefDefParser::defiPinAntennaModel*)obj)->APinMaxCutCarLayer(index); } int defiPinPort_numLayer (const ::defiPinPort* obj) { return ((LefDefParser::defiPinPort*)obj)->numLayer(); } const char* defiPinPort_layer (const ::defiPinPort* obj, int index) { return ((const LefDefParser::defiPinPort*)obj)->layer(index); } void defiPinPort_bounds (const ::defiPinPort* obj, int index, int* xl, int* yl, int* xh, int* yh) { ((LefDefParser::defiPinPort*)obj)->bounds(index, xl, yl, xh, yh); } int defiPinPort_hasLayerSpacing (const ::defiPinPort* obj, int index) { return ((LefDefParser::defiPinPort*)obj)->hasLayerSpacing(index); } int defiPinPort_hasLayerDesignRuleWidth (const ::defiPinPort* obj, int index) { return ((LefDefParser::defiPinPort*)obj)->hasLayerDesignRuleWidth(index); } int defiPinPort_layerSpacing (const ::defiPinPort* obj, int index) { return ((LefDefParser::defiPinPort*)obj)->layerSpacing(index); } int defiPinPort_layerMask (const ::defiPinPort* obj, int index) { return ((LefDefParser::defiPinPort*)obj)->layerMask(index); } int defiPinPort_layerDesignRuleWidth (const ::defiPinPort* obj, int index) { return ((LefDefParser::defiPinPort*)obj)->layerDesignRuleWidth(index); } int defiPinPort_numPolygons (const ::defiPinPort* obj) { return ((LefDefParser::defiPinPort*)obj)->numPolygons(); } const char* defiPinPort_polygonName (const ::defiPinPort* obj, int index) { return ((const LefDefParser::defiPinPort*)obj)->polygonName(index); } ::defiPoints defiPinPort_getPolygon (const ::defiPinPort* obj, int index) { LefDefParser::defiPoints tmp; tmp = ((LefDefParser::defiPinPort*)obj)->getPolygon(index); return *((::defiPoints*)&tmp); } int defiPinPort_hasPolygonSpacing (const ::defiPinPort* obj, int index) { return ((LefDefParser::defiPinPort*)obj)->hasPolygonSpacing(index); } int defiPinPort_hasPolygonDesignRuleWidth (const ::defiPinPort* obj, int index) { return ((LefDefParser::defiPinPort*)obj)->hasPolygonDesignRuleWidth(index); } int defiPinPort_polygonSpacing (const ::defiPinPort* obj, int index) { return ((LefDefParser::defiPinPort*)obj)->polygonSpacing(index); } int defiPinPort_polygonDesignRuleWidth (const ::defiPinPort* obj, int index) { return ((LefDefParser::defiPinPort*)obj)->polygonDesignRuleWidth(index); } int defiPinPort_polygonMask (const ::defiPinPort* obj, int index) { return ((LefDefParser::defiPinPort*)obj)->polygonMask(index); } int defiPinPort_numVias (const ::defiPinPort* obj) { return ((LefDefParser::defiPinPort*)obj)->numVias(); } const char* defiPinPort_viaName (const ::defiPinPort* obj, int index) { return ((const LefDefParser::defiPinPort*)obj)->viaName(index); } int defiPinPort_viaPtX (const ::defiPinPort* obj, int index) { return ((LefDefParser::defiPinPort*)obj)->viaPtX(index); } int defiPinPort_viaPtY (const ::defiPinPort* obj, int index) { return ((LefDefParser::defiPinPort*)obj)->viaPtY(index); } int defiPinPort_viaTopMask (const ::defiPinPort* obj, int index) { return ((LefDefParser::defiPinPort*)obj)->viaTopMask(index); } int defiPinPort_viaCutMask (const ::defiPinPort* obj, int index) { return ((LefDefParser::defiPinPort*)obj)->viaCutMask(index); } int defiPinPort_viaBottomMask (const ::defiPinPort* obj, int index) { return ((LefDefParser::defiPinPort*)obj)->viaBottomMask(index); } int defiPinPort_hasPlacement (const ::defiPinPort* obj) { return ((LefDefParser::defiPinPort*)obj)->hasPlacement(); } int defiPinPort_isPlaced (const ::defiPinPort* obj) { return ((LefDefParser::defiPinPort*)obj)->isPlaced(); } int defiPinPort_isCover (const ::defiPinPort* obj) { return ((LefDefParser::defiPinPort*)obj)->isCover(); } int defiPinPort_isFixed (const ::defiPinPort* obj) { return ((LefDefParser::defiPinPort*)obj)->isFixed(); } int defiPinPort_placementX (const ::defiPinPort* obj) { return ((LefDefParser::defiPinPort*)obj)->placementX(); } int defiPinPort_placementY (const ::defiPinPort* obj) { return ((LefDefParser::defiPinPort*)obj)->placementY(); } int defiPinPort_orient (const ::defiPinPort* obj) { return ((LefDefParser::defiPinPort*)obj)->orient(); } const char* defiPinPort_orientStr (const ::defiPinPort* obj) { return ((const LefDefParser::defiPinPort*)obj)->orientStr(); } const char* defiPin_pinName (const ::defiPin* obj) { return ((const LefDefParser::defiPin*)obj)->pinName(); } const char* defiPin_netName (const ::defiPin* obj) { return ((const LefDefParser::defiPin*)obj)->netName(); } int defiPin_hasDirection (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->hasDirection(); } int defiPin_hasUse (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->hasUse(); } int defiPin_hasLayer (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->hasLayer(); } int defiPin_hasPlacement (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->hasPlacement(); } int defiPin_isUnplaced (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->isUnplaced(); } int defiPin_isPlaced (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->isPlaced(); } int defiPin_isCover (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->isCover(); } int defiPin_isFixed (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->isFixed(); } int defiPin_placementX (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->placementX(); } int defiPin_placementY (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->placementY(); } const char* defiPin_direction (const ::defiPin* obj) { return ((const LefDefParser::defiPin*)obj)->direction(); } const char* defiPin_use (const ::defiPin* obj) { return ((const LefDefParser::defiPin*)obj)->use(); } int defiPin_numLayer (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->numLayer(); } const char* defiPin_layer (const ::defiPin* obj, int index) { return ((const LefDefParser::defiPin*)obj)->layer(index); } void defiPin_bounds (const ::defiPin* obj, int index, int* xl, int* yl, int* xh, int* yh) { ((LefDefParser::defiPin*)obj)->bounds(index, xl, yl, xh, yh); } int defiPin_layerMask (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->layerMask(index); } int defiPin_hasLayerSpacing (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->hasLayerSpacing(index); } int defiPin_hasLayerDesignRuleWidth (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->hasLayerDesignRuleWidth(index); } int defiPin_layerSpacing (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->layerSpacing(index); } int defiPin_layerDesignRuleWidth (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->layerDesignRuleWidth(index); } int defiPin_numPolygons (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->numPolygons(); } const char* defiPin_polygonName (const ::defiPin* obj, int index) { return ((const LefDefParser::defiPin*)obj)->polygonName(index); } ::defiPoints defiPin_getPolygon (const ::defiPin* obj, int index) { LefDefParser::defiPoints tmp; tmp = ((LefDefParser::defiPin*)obj)->getPolygon(index); return *((::defiPoints*)&tmp); } int defiPin_polygonMask (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->polygonMask(index); } int defiPin_hasPolygonSpacing (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->hasPolygonSpacing(index); } int defiPin_hasPolygonDesignRuleWidth (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->hasPolygonDesignRuleWidth(index); } int defiPin_polygonSpacing (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->polygonSpacing(index); } int defiPin_polygonDesignRuleWidth (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->polygonDesignRuleWidth(index); } int defiPin_hasNetExpr (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->hasNetExpr(); } int defiPin_hasSupplySensitivity (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->hasSupplySensitivity(); } int defiPin_hasGroundSensitivity (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->hasGroundSensitivity(); } const char* defiPin_netExpr (const ::defiPin* obj) { return ((const LefDefParser::defiPin*)obj)->netExpr(); } const char* defiPin_supplySensitivity (const ::defiPin* obj) { return ((const LefDefParser::defiPin*)obj)->supplySensitivity(); } const char* defiPin_groundSensitivity (const ::defiPin* obj) { return ((const LefDefParser::defiPin*)obj)->groundSensitivity(); } int defiPin_orient (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->orient(); } const char* defiPin_orientStr (const ::defiPin* obj) { return ((const LefDefParser::defiPin*)obj)->orientStr(); } int defiPin_hasSpecial (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->hasSpecial(); } int defiPin_numVias (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->numVias(); } const char* defiPin_viaName (const ::defiPin* obj, int index) { return ((const LefDefParser::defiPin*)obj)->viaName(index); } int defiPin_viaTopMask (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->viaTopMask(index); } int defiPin_viaCutMask (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->viaCutMask(index); } int defiPin_viaBottomMask (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->viaBottomMask(index); } int defiPin_viaPtX (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->viaPtX(index); } int defiPin_viaPtY (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->viaPtY(index); } int defiPin_hasAPinPartialMetalArea (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->hasAPinPartialMetalArea(); } int defiPin_numAPinPartialMetalArea (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->numAPinPartialMetalArea(); } int defiPin_APinPartialMetalArea (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->APinPartialMetalArea(index); } int defiPin_hasAPinPartialMetalAreaLayer (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->hasAPinPartialMetalAreaLayer(index); } const char* defiPin_APinPartialMetalAreaLayer (const ::defiPin* obj, int index) { return ((const LefDefParser::defiPin*)obj)->APinPartialMetalAreaLayer(index); } int defiPin_hasAPinPartialMetalSideArea (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->hasAPinPartialMetalSideArea(); } int defiPin_numAPinPartialMetalSideArea (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->numAPinPartialMetalSideArea(); } int defiPin_APinPartialMetalSideArea (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->APinPartialMetalSideArea(index); } int defiPin_hasAPinPartialMetalSideAreaLayer (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->hasAPinPartialMetalSideAreaLayer(index); } const char* defiPin_APinPartialMetalSideAreaLayer (const ::defiPin* obj, int index) { return ((const LefDefParser::defiPin*)obj)->APinPartialMetalSideAreaLayer(index); } int defiPin_hasAPinDiffArea (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->hasAPinDiffArea(); } int defiPin_numAPinDiffArea (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->numAPinDiffArea(); } int defiPin_APinDiffArea (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->APinDiffArea(index); } int defiPin_hasAPinDiffAreaLayer (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->hasAPinDiffAreaLayer(index); } const char* defiPin_APinDiffAreaLayer (const ::defiPin* obj, int index) { return ((const LefDefParser::defiPin*)obj)->APinDiffAreaLayer(index); } int defiPin_hasAPinPartialCutArea (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->hasAPinPartialCutArea(); } int defiPin_numAPinPartialCutArea (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->numAPinPartialCutArea(); } int defiPin_APinPartialCutArea (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->APinPartialCutArea(index); } int defiPin_hasAPinPartialCutAreaLayer (const ::defiPin* obj, int index) { return ((LefDefParser::defiPin*)obj)->hasAPinPartialCutAreaLayer(index); } const char* defiPin_APinPartialCutAreaLayer (const ::defiPin* obj, int index) { return ((const LefDefParser::defiPin*)obj)->APinPartialCutAreaLayer(index); } int defiPin_numAntennaModel (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->numAntennaModel(); } const ::defiPinAntennaModel* defiPin_antennaModel (const ::defiPin* obj, int index) { return (const ::defiPinAntennaModel*) ((LefDefParser::defiPin*)obj)->antennaModel(index); } int defiPin_hasPort (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->hasPort(); } int defiPin_numPorts (const ::defiPin* obj) { return ((LefDefParser::defiPin*)obj)->numPorts(); } const ::defiPinPort* defiPin_pinPort (const ::defiPin* obj, int index) { return (const ::defiPinPort*) ((LefDefParser::defiPin*)obj)->pinPort(index); } void defiPin_print (const ::defiPin* obj, FILE* f) { ((LefDefParser::defiPin*)obj)->print(f); }
34.576087
104
0.711726
erictaur
76a3676d5276c8e84253235937490cf38949fa66
19,999
cpp
C++
modules/soft/soft_blender_tasks_priv.cpp
DennissimOS/platform_external_libxcam
97f8476916e67917026de4c6e43c12d2fa1d68c7
[ "Apache-2.0" ]
1
2021-08-10T09:44:52.000Z
2021-08-10T09:44:52.000Z
modules/soft/soft_blender_tasks_priv.cpp
DennissimOS/platform_external_libxcam
97f8476916e67917026de4c6e43c12d2fa1d68c7
[ "Apache-2.0" ]
null
null
null
modules/soft/soft_blender_tasks_priv.cpp
DennissimOS/platform_external_libxcam
97f8476916e67917026de4c6e43c12d2fa1d68c7
[ "Apache-2.0" ]
null
null
null
/* * soft_blender_tasks_priv.cpp - soft blender tasks private class implementation * * Copyright (c) 2017 Intel Corporation * * 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. * * Author: Wind Yuan <feng.yuan@intel.com> */ #include "soft_blender_tasks_priv.h" namespace XCam { namespace XCamSoftTasks { const float GaussScaleGray::coeffs[GAUSS_DOWN_SCALE_SIZE] = {0.152f, 0.222f, 0.252f, 0.222f, 0.152f}; void GaussScaleGray::gauss_luma_2x2 ( UcharImage *in_luma, UcharImage *out_luma, uint32_t x, uint32_t y) { /* * o o o o o o o * o o o o o o o * o o Y(UV) o Y o o * o o o o o o o * o o Y o Y o o * o o o o o o o * o o o o o o o */ uint32_t in_x = x * 4, in_y = y * 4; float line[7]; float sum0[7] = {0.0f}; float sum1[7] = {0.0f}; in_luma->read_array<float, 7> (in_x - 2, in_y - 2, line); multiply_coeff_y (sum0, line, coeffs[0]); in_luma->read_array<float, 7> (in_x - 2, in_y - 1, line); multiply_coeff_y (sum0, line, coeffs[1]); in_luma->read_array<float, 7> (in_x - 2, in_y, line); multiply_coeff_y (sum0, line, coeffs[2]); multiply_coeff_y (sum1, line, coeffs[0]); in_luma->read_array<float, 7> (in_x - 2, in_y + 1, line); multiply_coeff_y (sum0, line, coeffs[3]); multiply_coeff_y (sum1, line, coeffs[1]); in_luma->read_array<float, 7> (in_x - 2, in_y + 2, line); multiply_coeff_y (sum0, line, coeffs[4]); multiply_coeff_y (sum1, line, coeffs[2]); in_luma->read_array<float, 7> (in_x - 2, in_y + 3, line); multiply_coeff_y (sum1, line, coeffs[3]); in_luma->read_array<float, 7> (in_x - 2, in_y + 4, line); multiply_coeff_y (sum1, line, coeffs[4]); float value[2]; Uchar out[2]; value[0] = gauss_sum (&sum0[0]); value[1] = gauss_sum (&sum0[2]); out[0] = convert_to_uchar (value[0]); out[1] = convert_to_uchar (value[1]); out_luma->write_array_no_check<2> (x * 2, y * 2, out); value[0] = gauss_sum (&sum1[0]); value[1] = gauss_sum (&sum1[2]); out[0] = convert_to_uchar(value[0]); out[1] = convert_to_uchar(value[1]); out_luma->write_array_no_check<2> (x * 2, y * 2 + 1, out); } XCamReturn GaussScaleGray::work_range (const SmartPtr<Worker::Arguments> &base, const WorkRange &range) { SmartPtr<GaussScaleGray::Args> args = base.dynamic_cast_ptr<GaussScaleGray::Args> (); XCAM_ASSERT (args.ptr ()); UcharImage *in_luma = args->in_luma.ptr (), *out_luma = args->out_luma.ptr (); XCAM_ASSERT (in_luma && out_luma); for (uint32_t y = range.pos[1]; y < range.pos[1] + range.pos_len[1]; ++y) for (uint32_t x = range.pos[0]; x < range.pos[0] + range.pos_len[0]; ++x) { gauss_luma_2x2 (in_luma, out_luma, x, y); } return XCAM_RETURN_NO_ERROR; } XCamReturn GaussDownScale::work_range (const SmartPtr<Worker::Arguments> &base, const WorkRange &range) { SmartPtr<GaussDownScale::Args> args = base.dynamic_cast_ptr<GaussDownScale::Args> (); XCAM_ASSERT (args.ptr ()); UcharImage *in_luma = args->in_luma.ptr (), *out_luma = args->out_luma.ptr (); Uchar2Image *in_uv = args->in_uv.ptr (), *out_uv = args->out_uv.ptr (); XCAM_ASSERT (in_luma && in_uv); XCAM_ASSERT (out_luma && out_uv); for (uint32_t y = range.pos[1]; y < range.pos[1] + range.pos_len[1]; ++y) for (uint32_t x = range.pos[0]; x < range.pos[0] + range.pos_len[0]; ++x) { gauss_luma_2x2 (in_luma, out_luma, x, y); // calculate UV int32_t in_x = x * 2, in_y = y * 2; Float2 uv_line[5]; Float2 uv_sum [5]; in_uv->read_array<Float2, 5> (in_x - 2, in_y - 2, uv_line); multiply_coeff_uv (uv_sum, uv_line, coeffs[0]); in_uv->read_array<Float2, 5> (in_x - 2, in_y - 1, uv_line); multiply_coeff_uv (uv_sum, uv_line, coeffs[1]); in_uv->read_array<Float2, 5> (in_x - 2, in_y , uv_line); multiply_coeff_uv (uv_sum, uv_line, coeffs[2]); in_uv->read_array<Float2, 5> (in_x - 2, in_y + 1, uv_line); multiply_coeff_uv (uv_sum, uv_line, coeffs[3]); in_uv->read_array<Float2, 5> (in_x - 2, in_y + 2, uv_line); multiply_coeff_uv (uv_sum, uv_line, coeffs[4]); Float2 uv_value; uv_value = gauss_sum (&uv_sum[0]); Uchar2 uv_out(convert_to_uchar(uv_value.x), convert_to_uchar(uv_value.y)); out_uv->write_data_no_check (x, y, uv_out); } //printf ("done\n"); XCAM_LOG_DEBUG ("GaussDownScale work on range:[x:%d, width:%d, y:%d, height:%d]", range.pos[0], range.pos_len[0], range.pos[1], range.pos_len[1]); return XCAM_RETURN_NO_ERROR; } static inline void blend_luma_8 (const float *luma0, const float *luma1, const float *mask, float *out) { //out[0] = luma0[0] * mask + luma1[0] * ( 1.0f - mask[0]); #define BLEND_LUMA_8(idx) out[idx] = (luma0[idx] - luma1[idx]) * mask[idx] + luma1[idx] BLEND_LUMA_8 (0); BLEND_LUMA_8 (1); BLEND_LUMA_8 (2); BLEND_LUMA_8 (3); BLEND_LUMA_8 (4); BLEND_LUMA_8 (5); BLEND_LUMA_8 (6); BLEND_LUMA_8 (7); } static inline void normalize_8 (float *value, const float max) { value[0] /= max; value[1] /= max; value[2] /= max; value[3] /= max; value[4] /= max; value[5] /= max; value[6] /= max; value[7] /= max; } static inline void read_and_blend_pixel_luma_8 ( const UcharImage *in0, const UcharImage *in1, const UcharImage *mask, const uint32_t in_x, const uint32_t in_y, float *out_luma, float *out_mask) { float luma0_line[8], luma1_line[8]; mask->read_array_no_check<float, 8> (in_x, in_y, out_mask); in0->read_array_no_check<float, 8> (in_x, in_y, luma0_line); in1->read_array_no_check<float, 8> (in_x, in_y, luma1_line); normalize_8 (out_mask, 255.0f); blend_luma_8 (luma0_line, luma1_line, out_mask, out_luma); } static inline void read_and_blend_uv_4 ( const Uchar2Image *in_a, const Uchar2Image *in_b, const float *mask, const uint32_t in_x, const uint32_t in_y, Float2 *out_uv) { Float2 line_a[4], line_b[4]; in_a->read_array_no_check<Float2, 4> (in_x, in_y, line_a); in_b->read_array_no_check<Float2, 4> (in_x, in_y, line_b); //out_uv[0] = line_a[0] * mask + line_b[0] * ( 1.0f - mask[0]); #define BLEND_UV_4(i) out_uv[i] = (line_a[i] - line_b[i]) * mask[i] + line_b[i] BLEND_UV_4 (0); BLEND_UV_4 (1); BLEND_UV_4 (2); BLEND_UV_4 (3); } XCamReturn BlendTask::work_range (const SmartPtr<Arguments> &base, const WorkRange &range) { SmartPtr<BlendTask::Args> args = base.dynamic_cast_ptr<BlendTask::Args> (); XCAM_ASSERT (args.ptr ()); UcharImage *in0_luma = args->in_luma[0].ptr (), *in1_luma = args->in_luma[1].ptr (), *out_luma = args->out_luma.ptr (); Uchar2Image *in0_uv = args->in_uv[0].ptr (), *in1_uv = args->in_uv[1].ptr (), *out_uv = args->out_uv.ptr (); UcharImage *mask = args->mask.ptr (); XCAM_ASSERT (in0_luma && in0_uv && in1_luma && in1_uv); XCAM_ASSERT (out_luma && out_uv); XCAM_ASSERT (mask); for (uint32_t y = range.pos[1]; y < range.pos[1] + range.pos_len[1]; ++y) for (uint32_t x = range.pos[0]; x < range.pos[0] + range.pos_len[0]; ++x) { // 8x2 -pixels each time for luma uint32_t in_x = x * 8; uint32_t in_y = y * 2; float luma_blend[8], luma_mask[8]; Uchar luma_uc[8]; // process luma (in_x, in_y) read_and_blend_pixel_luma_8 (in0_luma, in1_luma, mask, in_x, in_y, luma_blend, luma_mask); convert_to_uchar_N<float, 8> (luma_blend, luma_uc); out_luma->write_array_no_check<8> (in_x, in_y, luma_uc); // process luma (in_x, in_y + 1) read_and_blend_pixel_luma_8 (in0_luma, in1_luma, mask, in_x, in_y + 1, luma_blend, luma_mask); convert_to_uchar_N<float, 8> (luma_blend, luma_uc); out_luma->write_array_no_check<8> (in_x, in_y + 1, luma_uc); // process uv(4x1) (uv_x, uv_y) uint32_t uv_x = x * 4, uv_y = y; Float2 uv_blend[4]; Uchar2 uv_uc[4]; luma_mask[1] = luma_mask[2]; luma_mask[2] = luma_mask[4]; luma_mask[3] = luma_mask[6]; read_and_blend_uv_4 (in0_uv, in1_uv, luma_mask, uv_x, uv_y, uv_blend); convert_to_uchar2_N<Float2, 4> (uv_blend, uv_uc); out_uv->write_array_no_check<4> (uv_x, uv_y, uv_uc); } XCAM_LOG_DEBUG ("BlendTask work on range:[x:%d, width:%d, y:%d, height:%d]", range.pos[0], range.pos_len[0], range.pos[1], range.pos_len[1]); return XCAM_RETURN_NO_ERROR; } static inline void minus_array_8 (float *orig, float *gauss, Uchar *ret) { #define ORG_MINUS_GAUSS(i) ret[i] = convert_to_uchar<float> ((orig[i] - gauss[i]) * 0.5f + 128.0f) ORG_MINUS_GAUSS(0); ORG_MINUS_GAUSS(1); ORG_MINUS_GAUSS(2); ORG_MINUS_GAUSS(3); ORG_MINUS_GAUSS(4); ORG_MINUS_GAUSS(5); ORG_MINUS_GAUSS(6); ORG_MINUS_GAUSS(7); } static inline void interpolate_luma_int_row_8x1 (UcharImage* image, uint32_t fixed_x, uint32_t fixed_y, float *gauss_v, float* ret) { image->read_array<float, 5> (fixed_x, fixed_y, gauss_v); ret[0] = gauss_v[0]; ret[1] = (gauss_v[0] + gauss_v[1]) * 0.5f; ret[2] = gauss_v[1]; ret[3] = (gauss_v[1] + gauss_v[2]) * 0.5f; ret[4] = gauss_v[2]; ret[5] = (gauss_v[2] + gauss_v[3]) * 0.5f; ret[6] = gauss_v[3]; ret[7] = (gauss_v[3] + gauss_v[4]) * 0.5f; } static inline void interpolate_luma_half_row_8x1 (UcharImage* image, uint32_t fixed_x, uint32_t next_y, float *last_gauss_v, float* ret) { float next_gauss_v[5]; float tmp; image->read_array<float, 5> (fixed_x, next_y, next_gauss_v); ret[0] = (last_gauss_v[0] + next_gauss_v[0]) / 2.0f; ret[2] = (last_gauss_v[1] + next_gauss_v[1]) / 2.0f; ret[4] = (last_gauss_v[2] + next_gauss_v[2]) / 2.0f; ret[6] = (last_gauss_v[3] + next_gauss_v[3]) / 2.0f; tmp = (last_gauss_v[4] + next_gauss_v[4]) / 2.0f; ret[1] = (ret[0] + ret[2]) / 2.0f; ret[3] = (ret[2] + ret[4]) / 2.0f; ret[5] = (ret[4] + ret[6]) / 2.0f; ret[7] = (ret[6] + tmp) / 2.0f; } void LaplaceTask::interplate_luma_8x2 ( UcharImage *orig_luma, UcharImage *gauss_luma, UcharImage *out_luma, uint32_t out_x, uint32_t out_y) { uint32_t gauss_x = out_x / 2, first_gauss_y = out_y / 2; float inter_value[8]; float gauss_v[5]; float orig_v[8]; Uchar lap_ret[8]; //interplate instaed of coefficient interpolate_luma_int_row_8x1 (gauss_luma, gauss_x, first_gauss_y, gauss_v, inter_value); orig_luma->read_array_no_check<float, 8> (out_x, out_y, orig_v); minus_array_8 (orig_v, inter_value, lap_ret); out_luma->write_array_no_check<8> (out_x, out_y, lap_ret); uint32_t next_gauss_y = first_gauss_y + 1; interpolate_luma_half_row_8x1 (gauss_luma, gauss_x, next_gauss_y, gauss_v, inter_value); orig_luma->read_array_no_check<float, 8> (out_x, out_y + 1, orig_v); minus_array_8 (orig_v, inter_value, lap_ret); out_luma->write_array_no_check<8> (out_x, out_y + 1, lap_ret); } static inline void minus_array_uv_4 (Float2 *orig, Float2 *gauss, Uchar2 *ret) { #define ORG_MINUS_GAUSS_UV(i) orig[i] -= gauss[i]; orig[i] *= 0.5f; orig[i] += 128.0f ORG_MINUS_GAUSS_UV(0); ORG_MINUS_GAUSS_UV(1); ORG_MINUS_GAUSS_UV(2); ORG_MINUS_GAUSS_UV(3); convert_to_uchar2_N<Float2, 4> (orig, ret); } static inline void interpolate_uv_int_row_4x1 (Uchar2Image *image, uint32_t x, uint32_t y, Float2 *gauss_value, Float2 *ret) { image->read_array<Float2, 3> (x, y, gauss_value); ret[0] = gauss_value[0]; ret[1] = gauss_value[0] + gauss_value[1]; ret[1] *= 0.5f; ret[2] = gauss_value[1]; ret[3] = gauss_value[1] + gauss_value[2]; ret[3] *= 0.5f; } static inline void interpolate_uv_half_row_4x1 (Uchar2Image *image, uint32_t x, uint32_t y, Float2 *gauss_value, Float2 *ret) { Float2 next_gauss_uv[3]; image->read_array<Float2, 3> (x, y, next_gauss_uv); ret[0] = (gauss_value[0] + next_gauss_uv[0]) * 0.5f; ret[2] = (gauss_value[1] + next_gauss_uv[1]) * 0.5f; Float2 tmp = (gauss_value[2] + next_gauss_uv[2]) * 0.5f; ret[1] = (ret[0] + ret[2]) * 0.5f; ret[3] = (ret[2] + tmp) * 0.5f; } XCamReturn LaplaceTask::work_range (const SmartPtr<Arguments> &base, const WorkRange &range) { SmartPtr<LaplaceTask::Args> args = base.dynamic_cast_ptr<LaplaceTask::Args> (); XCAM_ASSERT (args.ptr ()); UcharImage *orig_luma = args->orig_luma.ptr (), *gauss_luma = args->gauss_luma.ptr (), *out_luma = args->out_luma.ptr (); Uchar2Image *orig_uv = args->orig_uv.ptr (), *gauss_uv = args->gauss_uv.ptr (), *out_uv = args->out_uv.ptr (); XCAM_ASSERT (orig_luma && orig_uv); XCAM_ASSERT (gauss_luma && gauss_uv); XCAM_ASSERT (out_luma && out_uv); for (uint32_t y = range.pos[1]; y < range.pos[1] + range.pos_len[1]; ++y) for (uint32_t x = range.pos[0]; x < range.pos[0] + range.pos_len[0]; ++x) { // 8x4 -pixels each time for luma uint32_t out_x = x * 8, out_y = y * 4; interplate_luma_8x2 (orig_luma, gauss_luma, out_luma, out_x, out_y); interplate_luma_8x2 (orig_luma, gauss_luma, out_luma, out_x, out_y + 2); // 4x2 uv uint32_t out_uv_x = x * 4, out_uv_y = y * 2; uint32_t gauss_uv_x = out_uv_x / 2, gauss_uv_y = out_uv_y / 2; Float2 gauss_uv_value[3]; Float2 orig_uv_value[4]; Float2 inter_uv_value[4]; Uchar2 lap_uv_ret[4]; interpolate_uv_int_row_4x1 (gauss_uv, gauss_uv_x, gauss_uv_y, gauss_uv_value, inter_uv_value); orig_uv->read_array_no_check<Float2, 4> (out_uv_x , out_uv_y, orig_uv_value); minus_array_uv_4 (orig_uv_value, inter_uv_value, lap_uv_ret); out_uv->write_array_no_check<4> (out_uv_x , out_uv_y, lap_uv_ret); interpolate_uv_half_row_4x1 (gauss_uv, gauss_uv_x, gauss_uv_y + 1, gauss_uv_value, inter_uv_value); orig_uv->read_array_no_check<Float2, 4> (out_uv_x , out_uv_y + 1, orig_uv_value); minus_array_uv_4 (orig_uv_value, inter_uv_value, lap_uv_ret); out_uv->write_array_no_check<4> (out_uv_x, out_uv_y + 1, lap_uv_ret); } return XCAM_RETURN_NO_ERROR; } static inline void reconstruct_luma_8x1 (float *lap, float *up_sample, Uchar *result) { #define RECONSTRUCT_UP_SAMPLE(i) result[i] = convert_to_uchar<float>(up_sample[i] + lap[i] * 2.0f - 256.0f) RECONSTRUCT_UP_SAMPLE(0); RECONSTRUCT_UP_SAMPLE(1); RECONSTRUCT_UP_SAMPLE(2); RECONSTRUCT_UP_SAMPLE(3); RECONSTRUCT_UP_SAMPLE(4); RECONSTRUCT_UP_SAMPLE(5); RECONSTRUCT_UP_SAMPLE(6); RECONSTRUCT_UP_SAMPLE(7); } static inline void reconstruct_luma_4x1 (Float2 *lap, Float2 *up_sample, Uchar2 *uv_uc) { #define RECONSTRUCT_UP_SAMPLE_UV(i) \ uv_uc[i].x = convert_to_uchar<float>(up_sample[i].x + lap[i].x * 2.0f - 256.0f); \ uv_uc[i].y = convert_to_uchar<float>(up_sample[i].y + lap[i].y * 2.0f - 256.0f) RECONSTRUCT_UP_SAMPLE_UV (0); RECONSTRUCT_UP_SAMPLE_UV (1); RECONSTRUCT_UP_SAMPLE_UV (2); RECONSTRUCT_UP_SAMPLE_UV (3); } XCamReturn ReconstructTask::work_range (const SmartPtr<Arguments> &base, const WorkRange &range) { SmartPtr<ReconstructTask::Args> args = base.dynamic_cast_ptr<ReconstructTask::Args> (); XCAM_ASSERT (args.ptr ()); UcharImage *lap_luma[2] = {args->lap_luma[0].ptr (), args->lap_luma[1].ptr ()}; UcharImage *gauss_luma = args->gauss_luma.ptr (), *out_luma = args->out_luma.ptr (); Uchar2Image *lap_uv[2] = {args->lap_uv[0].ptr (), args->lap_uv[1].ptr ()}; Uchar2Image *gauss_uv = args->gauss_uv.ptr (), *out_uv = args->out_uv.ptr (); UcharImage *mask_image = args->mask.ptr (); XCAM_ASSERT (lap_luma[0] && lap_luma[1] && lap_uv[0] && lap_uv[1]); XCAM_ASSERT (gauss_luma && gauss_uv); XCAM_ASSERT (out_luma && out_uv); XCAM_ASSERT (mask_image); for (uint32_t y = range.pos[1]; y < range.pos[1] + range.pos_len[1]; ++y) for (uint32_t x = range.pos[0]; x < range.pos[0] + range.pos_len[0]; ++x) { // 8x4 -pixels each time for luma float luma_blend[8], luma_mask1[8], luma_mask2[8]; float luma_sample[8]; float gauss_data[5]; Uchar luma_uchar[8]; uint32_t in_x = x * 8, in_y = y * 4; // luma 1st - line read_and_blend_pixel_luma_8 (lap_luma[0], lap_luma[1], mask_image, in_x, in_y, luma_blend, luma_mask1); interpolate_luma_int_row_8x1 (gauss_luma, in_x / 2, in_y / 2, gauss_data, luma_sample); reconstruct_luma_8x1 (luma_blend, luma_sample, luma_uchar); out_luma->write_array_no_check<8> (in_x, in_y, luma_uchar); // luma 2nd -line in_y += 1; read_and_blend_pixel_luma_8 (lap_luma[0], lap_luma[1], mask_image, in_x, in_y, luma_blend, luma_mask1); interpolate_luma_half_row_8x1 (gauss_luma, in_x / 2, in_y / 2 + 1, gauss_data, luma_sample); reconstruct_luma_8x1 (luma_blend, luma_sample, luma_uchar); out_luma->write_array_no_check<8> (in_x, in_y, luma_uchar); // luma 3rd -line in_y += 1; read_and_blend_pixel_luma_8 (lap_luma[0], lap_luma[1], mask_image, in_x, in_y, luma_blend, luma_mask2); interpolate_luma_int_row_8x1 (gauss_luma, in_x / 2, in_y / 2, gauss_data, luma_sample); reconstruct_luma_8x1 (luma_blend, luma_sample, luma_uchar); out_luma->write_array_no_check<8> (in_x, in_y, luma_uchar); // luma 4th -line in_y += 1; read_and_blend_pixel_luma_8 (lap_luma[0], lap_luma[1], mask_image, in_x, in_y, luma_blend, luma_mask2); interpolate_luma_half_row_8x1 (gauss_luma, in_x / 2, in_y / 2 + 1, gauss_data, luma_sample); reconstruct_luma_8x1 (luma_blend, luma_sample, luma_uchar); out_luma->write_array_no_check<8> (in_x, in_y, luma_uchar); // 4x2-UV process UV uint32_t uv_x = x * 4, uv_y = y * 2; Float2 uv_blend[4]; Float2 gauss_uv_value[3]; Float2 up_sample_uv[4]; Uchar2 uv_uc[4]; luma_mask1[1] = luma_mask1[2]; luma_mask1[2] = luma_mask1[4]; luma_mask1[3] = luma_mask1[6]; luma_mask2[1] = luma_mask2[2]; luma_mask2[2] = luma_mask2[4]; luma_mask2[3] = luma_mask1[6]; //1st-line UV read_and_blend_uv_4 (lap_uv[0], lap_uv[1], luma_mask1, uv_x, uv_y, uv_blend); interpolate_uv_int_row_4x1 (gauss_uv, uv_x / 2, uv_y / 2, gauss_uv_value, up_sample_uv); reconstruct_luma_4x1 (uv_blend, up_sample_uv, uv_uc); out_uv->write_array_no_check<4> (uv_x, uv_y, uv_uc); //2nd-line UV uv_y += 1; read_and_blend_uv_4 (lap_uv[0], lap_uv[1], luma_mask2, uv_x, uv_y, uv_blend); interpolate_uv_half_row_4x1 (gauss_uv, uv_x / 2, uv_y / 2 + 1, gauss_uv_value, up_sample_uv); reconstruct_luma_4x1 (uv_blend, up_sample_uv, uv_uc); out_uv->write_array_no_check<4> (uv_x, uv_y, uv_uc); } return XCAM_RETURN_NO_ERROR; } } }
39.60198
125
0.631782
DennissimOS
76a4a8d39e38ef58764175532ad4276f5d8d865f
13,908
cpp
C++
src/gui-qt4/libs/seiscomp3/gui/datamodel/publicobjectevaluator.cpp
yannikbehr/seiscomp3
ebb44c77092555eef7786493d00ac4efc679055f
[ "Naumen", "Condor-1.1", "MS-PL" ]
94
2015-02-04T13:57:34.000Z
2021-11-01T15:10:06.000Z
src/gui-qt4/libs/seiscomp3/gui/datamodel/publicobjectevaluator.cpp
yannikbehr/seiscomp3
ebb44c77092555eef7786493d00ac4efc679055f
[ "Naumen", "Condor-1.1", "MS-PL" ]
233
2015-01-28T15:16:46.000Z
2021-08-23T11:31:37.000Z
src/gui-qt4/libs/seiscomp3/gui/datamodel/publicobjectevaluator.cpp
yannikbehr/seiscomp3
ebb44c77092555eef7786493d00ac4efc679055f
[ "Naumen", "Condor-1.1", "MS-PL" ]
95
2015-02-13T15:53:30.000Z
2021-11-02T14:54:54.000Z
/*************************************************************************** * Copyright (C) by GFZ Potsdam * * * * You can redistribute and/or modify this program under the * * terms of the SeisComP Public License. * * * * 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 * * SeisComP Public License for more details. * ***************************************************************************/ #define SEISCOMP_COMPONENT EventList #include <QMutexLocker> #include <streambuf> #include <seiscomp3/gui/datamodel/publicobjectevaluator.h> #include <seiscomp3/datamodel/publicobject.h> //#include <seiscomp3/io/archive/xmlarchive.h> #include <seiscomp3/io/archive/binarchive.h> #include <seiscomp3/logging/log.h> namespace { class ByteArrayBuf : public std::streambuf { public: ByteArrayBuf(QByteArray &array) : _array(array) {} protected: int_type overflow (int_type c) { _array.append((char)c); return c; } std::streamsize xsputn(const char* s, std::streamsize n) { _array += QByteArray(s, n); return n; } private: QByteArray &_array; }; } namespace Seiscomp { namespace Gui { PublicObjectEvaluator *PublicObjectEvaluator::_instance = NULL; PublicObjectEvaluator::PublicObjectEvaluator() : _reader(NULL) { } PublicObjectEvaluator &PublicObjectEvaluator::Instance() { if ( _instance == NULL ) _instance = new PublicObjectEvaluator; return *_instance; } bool PublicObjectEvaluator::setDatabaseURI(const char *uri) { _databaseURI = uri; // Protect the list QMutexLocker locker(&_mutexJobList); if ( !_jobs.isEmpty() && !isRunning() ) { if ( !connect() ) return false; start(); } return true; } bool PublicObjectEvaluator::connect() { _reader.close(); _reader.setDriver(NULL); IO::DatabaseInterfacePtr db = IO::DatabaseInterface::Open(_databaseURI.c_str()); if ( db == NULL ) { SEISCOMP_WARNING("[obj eval] setting database %s failed", _databaseURI.c_str()); return false; } _reader.setDriver(db.get()); _reader.setPublicObjectCacheLookupEnabled(false); SEISCOMP_DEBUG("[obj eval] set database %s", _databaseURI.c_str()); return true; } bool PublicObjectEvaluator::append(void *owner, const QString &publicID, const Core::RTTI& classType, const QString &script) { // Protect the list QMutexLocker locker(&_mutexJobList); JobIDMap::iterator it = _jobIDLookup.find(publicID); // publicID not yet registered if ( it == _jobIDLookup.end() ) { Job job(publicID, classType); job.scripts[script] = owner; _jobIDLookup[publicID] = _jobs.insert(_jobs.end(), job); } else { Scripts::iterator jit = it.value()->scripts.find(script); if ( jit != it.value()->scripts.end() ) { if ( jit.value() != owner ) jit.value() = NULL; } else it.value()->scripts.insert(script, owner); } if ( !_jobs.isEmpty() && !isRunning() ) { if ( !connect() ) return false; start(); } return true; } bool PublicObjectEvaluator::append(void *owner, const QString &publicID, const Core::RTTI& classType, const QStringList &scripts) { // Protect the list QMutexLocker locker(&_mutexJobList); JobIDMap::iterator it = _jobIDLookup.find(publicID); // publicID not yet registered if ( it == _jobIDLookup.end() ) { Job job(publicID, classType); foreach ( const QString &script, scripts ) job.scripts[script] = owner; _jobIDLookup[publicID] = _jobs.insert(_jobs.end(), job); } else { foreach ( const QString &script, scripts ) { Scripts::iterator jit = it.value()->scripts.find(script); if ( jit != it.value()->scripts.end() ) { if ( jit.value() != owner ) jit.value() = NULL; } else it.value()->scripts.insert(script, owner); } } if ( !_jobs.isEmpty() && !isRunning() ) { if ( !connect() ) return false; start(); } return true; } bool PublicObjectEvaluator::prepend(void *owner, const QString &publicID, const Core::RTTI& classType, const QString &script) { // Protect the list QMutexLocker locker(&_mutexJobList); JobIDMap::iterator it = _jobIDLookup.find(publicID); // publicID not yet registered if ( it == _jobIDLookup.end() ) { Job job(publicID, classType); job.scripts[script] = owner; _jobIDLookup[publicID] = _jobs.insert(_jobs.begin(), job); } else { Scripts::iterator jit = it.value()->scripts.find(script); if ( jit != it.value()->scripts.end() ) { if ( jit.value() != owner ) jit.value() = NULL; } else it.value()->scripts.insert(script, owner); // Not the first item, make it the first if ( it.value() != _jobs.begin() ) { Job job = *it.value(); _jobs.erase(it.value()); it.value() = _jobs.insert(_jobs.begin(), job); } } if ( !_jobs.isEmpty() && !isRunning() ) { if ( !connect() ) return false; start(); } return true; } bool PublicObjectEvaluator::prepend(void *owner, const QString &publicID, const Core::RTTI& classType, const QStringList &scripts) { // Protect the list QMutexLocker locker(&_mutexJobList); JobIDMap::iterator it = _jobIDLookup.find(publicID); // publicID not yet registered if ( it == _jobIDLookup.end() ) { Job job(publicID, classType); foreach ( const QString &script, scripts ) job.scripts[script] = owner; _jobIDLookup[publicID] = _jobs.insert(_jobs.begin(), job); } else { foreach ( const QString &script, scripts ) { Scripts::iterator jit = it.value()->scripts.find(script); if ( jit != it.value()->scripts.end() ) { if ( jit.value() != owner ) jit.value() = NULL; } else it.value()->scripts.insert(script, owner); } // Not the first item, make it the first if ( it.value() != _jobs.begin() ) { Job job = *it.value(); _jobs.erase(it.value()); it.value() = _jobs.insert(_jobs.begin(), job); } } if ( !_jobs.isEmpty() && !isRunning() ) { if ( !connect() ) return false; start(); } return true; } bool PublicObjectEvaluator::moveToFront(const QString &publicID) { // Protect the list QMutexLocker locker(&_mutexJobList); JobIDMap::iterator it = _jobIDLookup.find(publicID); // publicID not yet registered if ( it == _jobIDLookup.end() ) return false; // Not the first item, make it the first if ( it.value() != _jobs.begin() ) { Job job = *it.value(); _jobs.erase(it.value()); it.value() = _jobs.insert(_jobs.begin(), job); } return true; } bool PublicObjectEvaluator::erase(void *owner, const QString &publicID, const QString &script) { // Protect the list QMutexLocker locker(&_mutexJobList); JobIDMap::iterator it = _jobIDLookup.find(publicID); if ( it == _jobIDLookup.end() ) return false; Scripts::iterator jit = it.value()->scripts.find(script); if ( jit == it.value()->scripts.end() ) return false; // Owner set and script has different owner? if ( owner != NULL && jit.value() != owner ) return false; it.value()->scripts.erase(jit); if ( it.value()->scripts.isEmpty() ) { _jobs.erase(it.value()); _jobIDLookup.erase(it); } return true; } bool PublicObjectEvaluator::erase(void *owner, const QString &publicID) { // Protect the list QMutexLocker locker(&_mutexJobList); JobIDMap::iterator it = _jobIDLookup.find(publicID); if ( it == _jobIDLookup.end() ) return false; if ( owner != NULL ) { Scripts::iterator jit; for ( jit = it.value()->scripts.begin(); jit != it.value()->scripts.end(); ) { if ( jit.value() != owner ) ++jit; else jit = it.value()->scripts.erase(jit); } if ( it.value()->scripts.isEmpty() ) { _jobs.erase(it.value()); _jobIDLookup.erase(it); } } else { _jobs.erase(it.value()); _jobIDLookup.erase(it); } return true; } int PublicObjectEvaluator::pendingJobs() const { // Protect the list QMutexLocker locker(&_mutexJobList); return _jobs.size(); } void PublicObjectEvaluator::clear(void *owner) { // Protect the list _mutexJobList.lock(); if ( owner == NULL ) { _jobs = JobList(); _jobIDLookup = JobIDMap(); _mutexJobList.unlock(); wait(); return; } JobIDMap::iterator it; for ( it = _jobIDLookup.begin(); it != _jobIDLookup.end(); ) { Scripts::iterator jit; for ( jit = it.value()->scripts.begin(); jit != it.value()->scripts.end(); ) { if ( jit.value() != owner ) ++jit; else jit = it.value()->scripts.erase(jit); } if ( it.value()->scripts.isEmpty() ) { _jobs.erase(it.value()); it = _jobIDLookup.erase(it); } else ++it; } _mutexJobList.unlock(); } bool PublicObjectEvaluator::eval(DataModel::PublicObject *po, const QStringList &scripts) { QByteArray data; { ByteArrayBuf buf(data); IO::BinaryArchive ar; ar.create(&buf); ar << po; ar.close(); } QStringList::const_iterator sit; for ( sit = scripts.begin(); sit != scripts.end(); ++sit ) { QProcess proc; proc.start(*sit); if ( !proc.waitForStarted() ) { SEISCOMP_ERROR("%s: failed to start", qPrintable(*sit)); emit resultError(po->publicID().c_str(), po->typeInfo().className(), *sit, proc.error()); continue; } proc.write(data); //qint64 written = proc.write(data); //SEISCOMP_DEBUG("... sent %d bytes to process", (int)written); proc.closeWriteChannel(); proc.setReadChannel(QProcess::StandardOutput); if ( !proc.waitForFinished() ) { SEISCOMP_ERROR("%s: problem with finishing", qPrintable(*sit)); emit resultError(po->publicID().c_str(), po->typeInfo().className(), *sit, proc.error()); continue; } if ( proc.exitCode() != 0 ) { SEISCOMP_ERROR("%s: exit code: %d", qPrintable(*sit), proc.exitCode()); emit resultError(po->publicID().c_str(), po->typeInfo().className(), *sit, -proc.exitCode()); continue; } QByteArray result = proc.readAll(); QString text = QString(result).trimmed(); emit resultAvailable(po->publicID().c_str(), po->typeInfo().className(), *sit, text); } return true; } void PublicObjectEvaluator::run() { // Protect the list _mutexJobList.lock(); SEISCOMP_INFO("[obj eval] started"); // Disable object registration only in this thread DataModel::PublicObject::SetRegistrationEnabled(false); while ( !_jobs.empty() ) { Job job = _jobs.front(); _jobs.pop_front(); JobIDMap::iterator it = _jobIDLookup.find(job.publicID); if ( it != _jobIDLookup.end() ) _jobIDLookup.erase(it); // Unlock the mutex and call the scripts _mutexJobList.unlock(); // Load the entire object including childs from database DataModel::PublicObjectPtr o = _reader.loadObject(job.classType, job.publicID.toStdString()); DataModel::PublicObject *po = o.get(); if ( po == NULL ) { SEISCOMP_ERROR("[obj eval] %s not found in database", qPrintable(job.publicID)); _mutexJobList.lock(); continue; } QByteArray data; { ByteArrayBuf buf(data); IO::BinaryArchive ar; ar.create(&buf); ar << po; ar.close(); } //SEISCOMP_DEBUG("... generated %d bytes of XML", (int)data.size()); Scripts::iterator sit; for ( sit = job.scripts.begin(); sit != job.scripts.end(); ++sit ) { QProcess proc; proc.start(sit.key()); if ( !proc.waitForStarted() ) { SEISCOMP_ERROR("%s: failed to start", qPrintable(sit.key())); emit resultError(job.publicID, job.classType.className(), sit.key(), proc.error()); continue; } proc.write(data); //qint64 written = proc.write(data); //SEISCOMP_DEBUG("... sent %d bytes to process", (int)written); proc.closeWriteChannel(); proc.setReadChannel(QProcess::StandardOutput); if ( !proc.waitForFinished() ) { SEISCOMP_ERROR("%s: problem with finishing", qPrintable(sit.key())); emit resultError(job.publicID, job.classType.className(), sit.key(), proc.error()); continue; } if ( proc.exitCode() != 0 ) { QByteArray errMsg = proc.readAllStandardError(); SEISCOMP_ERROR("%s (exit code %d): %s", qPrintable(sit.key()), proc.exitCode(), qPrintable(QString(errMsg).trimmed())); emit resultError(job.publicID, job.classType.className(), sit.key(), -proc.exitCode()); continue; } QByteArray result = proc.readAll(); QString text = QString(result).trimmed(); emit resultAvailable(job.publicID, job.classType.className(), sit.key(), text); } // Lock it again _mutexJobList.lock(); } SEISCOMP_INFO("[obj eval] finished"); // Unlock finally _mutexJobList.unlock(); } QString PublicObjectEvaluator::errorMsg(int error) const { QString msg; if ( error < 0 ) return QString("Invalid exit code: %1: 0 expected").arg(-error); switch ( error ) { case QProcess::FailedToStart: msg = "The process failed to start. Either the invoked\n" "program is missing, or you may have insufficient\n" "permissions to invoke the program."; break; case QProcess::Crashed: msg = "The process crashed some time after\n" "starting successfully."; break; case QProcess::Timedout: msg = "The last waitFor...() function timed\n" "out. Process was killed."; break; case QProcess::WriteError: msg = "An error occurred when attempting to write\n" "to the process. For example, the process may\n" "not be running, or it may have closed its\n" "input channel."; break; case QProcess::ReadError: msg = "An error occurred when attempting to read from the\n" "process. For example, the process may not be running."; break; default: msg = "An unknown error occurred."; break; } return msg; } } }
26.291115
96
0.634958
yannikbehr
76a737fb754ed01d961158bf576bab13ca7e6ebe
887
cpp
C++
MPI2Send/MPI2Send27.cpp
bru1t/pt-for-mpi-2-answers
81595465725db4cce848a1c45b3695203d97db03
[ "Unlicense" ]
2
2021-12-26T20:18:24.000Z
2021-12-28T10:49:42.000Z
MPI2Send/MPI2Send27.cpp
bru1t/pt-for-mpi-2-answers
81595465725db4cce848a1c45b3695203d97db03
[ "Unlicense" ]
null
null
null
MPI2Send/MPI2Send27.cpp
bru1t/pt-for-mpi-2-answers
81595465725db4cce848a1c45b3695203d97db03
[ "Unlicense" ]
null
null
null
#include "pt4.h" #include "mpi.h" void Solve() { Task("MPI2Send27"); int flag; MPI_Initialized(&flag); if (flag == 0) return; int rank, size; MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); int n; pt >> n; if (n == -1) { int num = 0; for (int i = 0; i < size - 1; ++i) { if (rank == num) ++num; double t; MPI_Recv(&t, 1, MPI_DOUBLE, MPI_ANY_SOURCE, num, MPI_COMM_WORLD, MPI_STATUSES_IGNORE); pt << t; ++num; } } else { double a; pt >> a; int num = 0; MPI_Request req; MPI_Issend(&a, 1, MPI_DOUBLE, n, rank, MPI_COMM_WORLD, &req); MPI_Status status; int check = 0; while (check == 0) { MPI_Test(&req, &check, &status); ++num; } Show(num); } }
16.127273
93
0.487035
bru1t
76a7965ffae35f6c73dacb9213b012580a657853
735
cpp
C++
include/general.cpp
denisjackman/Cee
2176e9dccc17ac93463bd5473f437f1c76ba9c3c
[ "CC-BY-4.0" ]
null
null
null
include/general.cpp
denisjackman/Cee
2176e9dccc17ac93463bd5473f437f1c76ba9c3c
[ "CC-BY-4.0" ]
2
2016-06-30T14:31:43.000Z
2016-07-01T08:43:03.000Z
include/general.cpp
denisjackman/game
2176e9dccc17ac93463bd5473f437f1c76ba9c3c
[ "CC-BY-4.0" ]
null
null
null
#include <cstdlib> #include <ctime> #include <cmath> #include <string> #include <iostream> #include <fstream> #include <vector> #include <list> using namespace std; bool gDebugMode = false; string gDebugLogFileLocation = "debug.log"; ofstream gDebugLogFile; void DebugModeInitialise() { if (gDebugMode) { gDebugLogFile.open(gDebugLogFileLocation); } } void DebugModeTerminate() { if (gDebugMode) { gDebugLogFile.close(); } } void Print(string OutputString) { if (gDebugMode) { gDebugLogFile << OutputString << endl; } cout << OutputString << endl; } void Pause() { do { cout << endl << "Press the Enter key to continue."; } while (cin.get() != '\n'); }
15.978261
58
0.634014
denisjackman
76a7fad4d057925cfa08390226478c081f689f57
103
cxx
C++
tests/TestUtil/message_for_assert.cxx
SergeyKleyman/elastic-apm-agent-cpp-prototype
67d2c7ad5a50e1a6b75d6725a89ae3fc5a92d517
[ "Apache-2.0" ]
null
null
null
tests/TestUtil/message_for_assert.cxx
SergeyKleyman/elastic-apm-agent-cpp-prototype
67d2c7ad5a50e1a6b75d6725a89ae3fc5a92d517
[ "Apache-2.0" ]
null
null
null
tests/TestUtil/message_for_assert.cxx
SergeyKleyman/elastic-apm-agent-cpp-prototype
67d2c7ad5a50e1a6b75d6725a89ae3fc5a92d517
[ "Apache-2.0" ]
null
null
null
// TODO: Sergey Kleyman: Remove if I don't need it anymore // #include "message_for_assert.hxx" //
20.6
58
0.68932
SergeyKleyman
76a995b55aba98ae09015b150c7896960361cf93
15,342
hpp
C++
INCLUDE/Vcl/ibinstall.hpp
earthsiege2/borland-cpp-ide
09bcecc811841444338e81b9c9930c0e686f9530
[ "Unlicense", "FSFAP", "Apache-1.1" ]
1
2022-01-13T01:03:55.000Z
2022-01-13T01:03:55.000Z
INCLUDE/Vcl/ibinstall.hpp
earthsiege2/borland-cpp-ide
09bcecc811841444338e81b9c9930c0e686f9530
[ "Unlicense", "FSFAP", "Apache-1.1" ]
null
null
null
INCLUDE/Vcl/ibinstall.hpp
earthsiege2/borland-cpp-ide
09bcecc811841444338e81b9c9930c0e686f9530
[ "Unlicense", "FSFAP", "Apache-1.1" ]
null
null
null
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'IBInstall.pas' rev: 6.00 #ifndef IBInstallHPP #define IBInstallHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <IBXConst.hpp> // Pascal unit #include <IBIntf.hpp> // Pascal unit #include <IBInstallHeader.hpp> // Pascal unit #include <IB.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <SysUtils.hpp> // Pascal unit #include <TypInfo.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Ibinstall { //-- type declarations ------------------------------------------------------- typedef int TIscError; #pragma option push -b- enum TIBInstallerError { ieSuccess, ieDelphiException, ieNoOptionsSet, ieNoDestinationDirectory, ieNosourceDirectory, ieNoUninstallFile, ieOptionNeedsClient, ieOptionNeedsServer, ieInvalidOption, ieInvalidOnErrorResult, ieInvalidOnStatusResult }; #pragma option pop #pragma option push -b- enum TMainOption { moServer, moClient, moConServer, moGuiTools, moDocumentation, moDevelopment }; #pragma option pop #pragma option push -b- enum TExamplesOption { exDB, exAPI }; #pragma option pop #pragma option push -b- enum TCmdOption { cmDBMgmt, cmDBQuery, cmUsrMgmt }; #pragma option pop #pragma option push -b- enum TConnectivityOption { cnODBC, cnOLEDB, cnJDBC }; #pragma option pop typedef Set<TMainOption, moServer, moDevelopment> TMainOptions; typedef Set<TExamplesOption, exDB, exAPI> TExamplesOptions; typedef Set<TCmdOption, cmDBMgmt, cmUsrMgmt> TCmdOptions; typedef Set<TConnectivityOption, cnODBC, cnJDBC> TConnectivityOptions; #pragma option push -b- enum TErrorResult { erAbort, erContinue, erRetry }; #pragma option pop #pragma option push -b- enum TStatusResult { srAbort, srContinue }; #pragma option pop #pragma option push -b- enum TWarningResult { wrAbort, wrContinue }; #pragma option pop typedef TStatusResult __fastcall (__closure *TIBSetupOnStatus)(System::TObject* Sender, AnsiString StatusComment); typedef TWarningResult __fastcall (__closure *TIBSetupOnWarning)(System::TObject* Sender, int WarningCode, AnsiString WarningMessage); typedef TErrorResult __fastcall (__closure *TIBSetupOnError)(System::TObject* Sender, int IscCode, AnsiString ErrorMessage, AnsiString ErrorComment); class DELPHICLASS EIBInstall; class PASCALIMPLEMENTATION EIBInstall : public Sysutils::Exception { typedef Sysutils::Exception inherited; private: int FIscError; TIBInstallerError FInstallerError; public: __fastcall virtual EIBInstall(int IscCode, AnsiString IscMessage)/* overload */; __fastcall virtual EIBInstall(TIBInstallerError ECode, AnsiString EMessage)/* overload */; __property int InstallError = {read=FIscError, nodefault}; __property TIBInstallerError InstallerError = {read=FInstallerError, nodefault}; public: #pragma option push -w-inl /* Exception.CreateFmt */ inline __fastcall EIBInstall(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size) : Sysutils::Exception(Msg, Args, Args_Size) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateRes */ inline __fastcall EIBInstall(int Ident)/* overload */ : Sysutils::Exception(Ident) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResFmt */ inline __fastcall EIBInstall(int Ident, const System::TVarRec * Args, const int Args_Size)/* overload */ : Sysutils::Exception(Ident, Args, Args_Size) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateHelp */ inline __fastcall EIBInstall(const AnsiString Msg, int AHelpContext) : Sysutils::Exception(Msg, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateFmtHelp */ inline __fastcall EIBInstall(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size, int AHelpContext) : Sysutils::Exception(Msg, Args, Args_Size, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResHelp */ inline __fastcall EIBInstall(int Ident, int AHelpContext)/* overload */ : Sysutils::Exception(Ident, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResFmtHelp */ inline __fastcall EIBInstall(System::PResStringRec ResStringRec, const System::TVarRec * Args, const int Args_Size, int AHelpContext)/* overload */ : Sysutils::Exception(ResStringRec, Args, Args_Size, AHelpContext) { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~EIBInstall(void) { } #pragma option pop }; class DELPHICLASS EIBInstallError; class PASCALIMPLEMENTATION EIBInstallError : public EIBInstall { typedef EIBInstall inherited; public: #pragma option push -w-inl /* EIBInstall.Create */ inline __fastcall virtual EIBInstallError(int IscCode, AnsiString IscMessage)/* overload */ : EIBInstall(IscCode, IscMessage) { } #pragma option pop public: #pragma option push -w-inl /* Exception.CreateFmt */ inline __fastcall EIBInstallError(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size) : EIBInstall(Msg, Args, Args_Size) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateRes */ inline __fastcall EIBInstallError(int Ident)/* overload */ : EIBInstall(Ident) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResFmt */ inline __fastcall EIBInstallError(int Ident, const System::TVarRec * Args, const int Args_Size)/* overload */ : EIBInstall(Ident, Args, Args_Size) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateHelp */ inline __fastcall EIBInstallError(const AnsiString Msg, int AHelpContext) : EIBInstall(Msg, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateFmtHelp */ inline __fastcall EIBInstallError(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size, int AHelpContext) : EIBInstall(Msg, Args, Args_Size, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResHelp */ inline __fastcall EIBInstallError(int Ident, int AHelpContext)/* overload */ : EIBInstall(Ident, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResFmtHelp */ inline __fastcall EIBInstallError(System::PResStringRec ResStringRec, const System::TVarRec * Args, const int Args_Size, int AHelpContext)/* overload */ : EIBInstall(ResStringRec, Args, Args_Size, AHelpContext) { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~EIBInstallError(void) { } #pragma option pop }; class DELPHICLASS EIBInstallerError; class PASCALIMPLEMENTATION EIBInstallerError : public EIBInstall { typedef EIBInstall inherited; public: #pragma option push -w-inl /* EIBInstall.Create */ inline __fastcall virtual EIBInstallerError(int IscCode, AnsiString IscMessage)/* overload */ : EIBInstall(IscCode, IscMessage) { } #pragma option pop public: #pragma option push -w-inl /* Exception.CreateFmt */ inline __fastcall EIBInstallerError(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size) : EIBInstall(Msg, Args, Args_Size) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateRes */ inline __fastcall EIBInstallerError(int Ident)/* overload */ : EIBInstall(Ident) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResFmt */ inline __fastcall EIBInstallerError(int Ident, const System::TVarRec * Args, const int Args_Size)/* overload */ : EIBInstall(Ident, Args, Args_Size) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateHelp */ inline __fastcall EIBInstallerError(const AnsiString Msg, int AHelpContext) : EIBInstall(Msg, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateFmtHelp */ inline __fastcall EIBInstallerError(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size, int AHelpContext) : EIBInstall(Msg, Args, Args_Size, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResHelp */ inline __fastcall EIBInstallerError(int Ident, int AHelpContext)/* overload */ : EIBInstall(Ident, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResFmtHelp */ inline __fastcall EIBInstallerError(System::PResStringRec ResStringRec, const System::TVarRec * Args, const int Args_Size, int AHelpContext)/* overload */ : EIBInstall(ResStringRec, Args, Args_Size, AHelpContext) { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~EIBInstallerError(void) { } #pragma option pop }; class DELPHICLASS TInstallOptions; class PASCALIMPLEMENTATION TInstallOptions : public Classes::TPersistent { typedef Classes::TPersistent inherited; private: TMainOptions FMainComponents; TExamplesOptions FExamples; TCmdOptions FCmdLineTools; TConnectivityOptions FConnectivityClients; __published: __property TMainOptions MainComponents = {read=FMainComponents, write=FMainComponents, nodefault}; __property TCmdOptions CmdLineTools = {read=FCmdLineTools, write=FCmdLineTools, nodefault}; __property TConnectivityOptions ConnectivityClients = {read=FConnectivityClients, write=FConnectivityClients, nodefault}; __property TExamplesOptions Examples = {read=FExamples, write=FExamples, nodefault}; public: #pragma option push -w-inl /* TPersistent.Destroy */ inline __fastcall virtual ~TInstallOptions(void) { } #pragma option pop public: #pragma option push -w-inl /* TObject.Create */ inline __fastcall TInstallOptions(void) : Classes::TPersistent() { } #pragma option pop }; class DELPHICLASS TIBSetup; class PASCALIMPLEMENTATION TIBSetup : public Classes::TComponent { typedef Classes::TComponent inherited; private: bool FIBInstallLoaded; bool FRebootToComplete; int FProgress; AnsiString FMsgFilePath; TIBSetupOnStatus FOnStatusChange; void *FStatusContext; TIBSetupOnError FOnError; void *FErrorContext; TIBSetupOnWarning FOnWarning; void __fastcall SetMsgFilePath(const AnsiString Value); protected: int __fastcall StatusInternal(int Status, const char * ActionDescription); int __fastcall ErrorInternal(int IscCode, const char * ActionDescription); void __fastcall Call(int IscCode); void __fastcall IBInstallError(int IscCode); AnsiString __fastcall GetInstallMessage(int IscCode); public: __fastcall virtual TIBSetup(Classes::TComponent* AOwner); __property bool RebootToComplete = {read=FRebootToComplete, nodefault}; __property int Progress = {read=FProgress, nodefault}; __property void * StatusContext = {read=FStatusContext, write=FStatusContext}; __property void * ErrorContext = {read=FErrorContext, write=FErrorContext}; __property AnsiString MsgFilePath = {read=FMsgFilePath, write=SetMsgFilePath}; __published: __property TIBSetupOnWarning OnWarning = {read=FOnWarning, write=FOnWarning}; __property TIBSetupOnError OnError = {read=FOnError, write=FOnError}; __property TIBSetupOnStatus OnStatusChange = {read=FOnStatusChange, write=FOnStatusChange}; public: #pragma option push -w-inl /* TComponent.Destroy */ inline __fastcall virtual ~TIBSetup(void) { } #pragma option pop }; class DELPHICLASS TIBInstall; class PASCALIMPLEMENTATION TIBInstall : public TIBSetup { typedef TIBSetup inherited; private: AnsiString FUnInstallFile; AnsiString FSourceDir; AnsiString FDestinationDir; AnsiString FSuggestedDestination; TInstallOptions* FInstallOptions; void __fastcall GetOptionProperty(int InfoType, TExamplesOption Option, void * Buffer, unsigned BufferLen)/* overload */; void __fastcall GetOptionProperty(int InfoType, TMainOption Option, void * Buffer, unsigned BufferLen)/* overload */; void __fastcall GetOptionProperty(int InfoType, TConnectivityOption Option, void * Buffer, unsigned BufferLen)/* overload */; void __fastcall GetOptionProperty(int InfoType, TCmdOption Option, void * Buffer, unsigned BufferLen)/* overload */; void __fastcall InternalSetOptions(Ibinstallheader::POPTIONS_HANDLE pHandle); void __fastcall SetDestination(const AnsiString Value); void __fastcall SetSource(const AnsiString Value); void __fastcall SetInstallOptions(const TInstallOptions* Value); void __fastcall SuggestDestination(void); public: __fastcall virtual TIBInstall(Classes::TComponent* AOwner); __fastcall virtual ~TIBInstall(void); void __fastcall InstallCheck(void); void __fastcall InstallExecute(void); AnsiString __fastcall GetOptionDescription(TExamplesOption Option)/* overload */; AnsiString __fastcall GetOptionDescription(TMainOption Option)/* overload */; AnsiString __fastcall GetOptionDescription(TConnectivityOption Option)/* overload */; AnsiString __fastcall GetOptionDescription(TCmdOption Option)/* overload */; AnsiString __fastcall GetOptionName(TExamplesOption Option)/* overload */; AnsiString __fastcall GetOptionName(TMainOption Option)/* overload */; AnsiString __fastcall GetOptionName(TConnectivityOption Option)/* overload */; AnsiString __fastcall GetOptionName(TCmdOption Option)/* overload */; unsigned __fastcall GetOptionSpaceRequired(TExamplesOption Option)/* overload */; unsigned __fastcall GetOptionSpaceRequired(TMainOption Option)/* overload */; unsigned __fastcall GetOptionSpaceRequired(TConnectivityOption Option)/* overload */; unsigned __fastcall GetOptionSpaceRequired(TCmdOption Option)/* overload */; __property AnsiString UnInstallFile = {read=FUnInstallFile}; __property AnsiString SuggestedDestination = {read=FSuggestedDestination}; __published: __property AnsiString SourceDirectory = {read=FSourceDir, write=SetSource}; __property AnsiString DestinationDirectory = {read=FDestinationDir, write=SetDestination}; __property TInstallOptions* InstallOptions = {read=FInstallOptions, write=SetInstallOptions}; }; class DELPHICLASS TIBUnInstall; class PASCALIMPLEMENTATION TIBUnInstall : public TIBSetup { typedef TIBSetup inherited; private: AnsiString FUnInstallFile; public: void __fastcall UnInstallCheck(void); void __fastcall UnInstallExecute(void); __property AnsiString UnInstallFile = {read=FUnInstallFile, write=FUnInstallFile}; public: #pragma option push -w-inl /* TIBSetup.Create */ inline __fastcall virtual TIBUnInstall(Classes::TComponent* AOwner) : TIBSetup(AOwner) { } #pragma option pop public: #pragma option push -w-inl /* TComponent.Destroy */ inline __fastcall virtual ~TIBUnInstall(void) { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- } /* namespace Ibinstall */ using namespace Ibinstall; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // IBInstall
42.735376
253
0.752118
earthsiege2
76acc3d1f3fc1fae3a91b4e5aad3849fa39c9059
12,439
cpp
C++
modules/Alexa/SSSDKCommon/src/ConfigValidator.cpp
isabella232/alexa-smart-screen-sdk
fca0701fc5020a2ae3787cd8a2052e7291982fd0
[ "Apache-2.0" ]
null
null
null
modules/Alexa/SSSDKCommon/src/ConfigValidator.cpp
isabella232/alexa-smart-screen-sdk
fca0701fc5020a2ae3787cd8a2052e7291982fd0
[ "Apache-2.0" ]
1
2022-02-08T19:12:45.000Z
2022-02-08T19:12:45.000Z
modules/Alexa/SSSDKCommon/src/ConfigValidator.cpp
isabella232/alexa-smart-screen-sdk
fca0701fc5020a2ae3787cd8a2052e7291982fd0
[ "Apache-2.0" ]
null
null
null
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 <AVSCommon/Utils/Logger/Logger.h> #include <AVSCommon/Utils/Configuration/ConfigurationNode.h> #include <SSSDKCommon/ConfigValidator.h> #include <rapidjson/document.h> #include <rapidjson/schema.h> #include <rapidjson/stringbuffer.h> namespace alexaSmartScreenSDK { namespace sssdkCommon { using namespace rapidjson; using namespace std; /// String to identify log entries originating from this file. static const std::string TAG("ConfigValidator"); /** * Create a LogEntry using this file's TAG and the specified event string. * * @param The event string for this @c LogEntry. */ #define LX(event) alexaClientSDK::avsCommon::utils::logger::LogEntry(TAG, event) static const std::string GUI_CONFIG_ROOT_KEY{"gui"}; static const std::string APPCONFIG_CONFIG_ROOT_KEY{"appConfig"}; static const std::string WINDOWS_CONFIG_ROOT_KEY{"windows"}; static const std::string DEVICEKEYS_CONFIG_ROOT_KEY{"deviceKeys"}; static const std::string VISUALCHARACTERISTICS_CONFIG_ROOT_KEY = "visualCharacteristics"; static const std::string APPCONFIG_DEFAULT_WINDOW_ID_KEY{"defaultWindowId"}; static const std::string WINDOWS_ID_KEY{"id"}; static const std::string WINDOWS_TEMPLATEID_KEY{"templateId"}; static const std::string WINDOWS_SIZECONFIGURATIONID_KEY{"sizeConfigurationId"}; static const std::string WINDOWS_INTERACTION_MODE_KEY{"interactionMode"}; static const std::string VISUALCHARACTERISTICS_INTERFACE_KEY{"interface"}; static const std::string ALEXADISPLAYWINDOW_INTERFACE_NAME{"Alexa.Display.Window"}; static const std::string ALEXADISPLAYWINDOW_CONFIGURATIONS_KEY{"configurations"}; static const std::string ALEXADISPLAYWINDOW_TEMPLATES_KEY{"templates"}; static const std::string ALEXADISPLAYWINDOW_TEMPLATE_ID_KEY{"id"}; static const std::string ALEXADISPLAYWINDOW_TEMPLATE_CONFIGURATION_KEY{"configuration"}; static const std::string ALEXADISPLAYWINDOW_TEMPLATE_SIZES_KEY{"sizes"}; static const std::string ALEXADISPLAYWINDOW_TEMPLATE_SIZES_ID_KEY{"id"}; static const std::string ALEXADISPLAYWINDOW_TEMPLATE_INTERACTIONMODES_KEY{"interactionModes"}; static const std::string ALEXAINTERACTIONMODE_INTERFACE_NAME{"Alexa.InteractionMode"}; static const std::string ALEXAINTERACTIONMODE_CONFIGURATIONS_KEY{"configurations"}; static const std::string ALEXAINTERACTIONMODE_INTERFACTIONMODES_KEY{"interactionModes"}; static const std::string ALEXAINTERACTIONMODE_INTERFACTIONMODE_ID_KEY{"id"}; static const std::string APPCONFIG_DEVICEKEYS_KEYCODE_KEY{"keyCode"}; static const std::string APPCONFIG_DEVICEKEYS_KEYS[] = {"talkKey", "backKey", "exitKey", "toggleCaptionsKey", "toggleDoNotDisturbKey"}; ConfigValidator::ConfigValidator() { } std::shared_ptr<ConfigValidator> ConfigValidator::create() { std::shared_ptr<ConfigValidator> configValidator(new ConfigValidator()); return configValidator; } bool ConfigValidator::validate( alexaClientSDK::avsCommon::utils::configuration::ConfigurationNode& configuration, rapidjson::Document& jsonSchema) { rapidjson::SchemaDocument schema(jsonSchema); rapidjson::SchemaValidator validator(schema); rapidjson::Document doc; if (doc.Parse(configuration.serialize().c_str()).HasParseError()) { ACSDK_ERROR(LX(__func__).d("reason", "invalidConfigurationNode!")); return false; } // Validate configuration against schema if (!doc.Accept(validator)) { rapidjson::StringBuffer docBuffer, schemaBuffer; std::string validatorErrorMessage; validator.GetInvalidSchemaPointer().StringifyUriFragment(schemaBuffer); validator.GetInvalidDocumentPointer().StringifyUriFragment(docBuffer); // Get the first error message validatorErrorMessage = std::string("configuration validation failed at ") + docBuffer.GetString() + " against schema " + schemaBuffer.GetString() + " with keyword '" + validator.GetInvalidSchemaKeyword() + "'"; ACSDK_ERROR(LX(__func__).d("reason", "validationFailed").d("message", validatorErrorMessage)); return false; } // Validate configuration against business logic auto guiConfig = configuration[GUI_CONFIG_ROOT_KEY]; auto appConfig = guiConfig[APPCONFIG_CONFIG_ROOT_KEY]; auto windowsConfig = appConfig.getArray(WINDOWS_CONFIG_ROOT_KEY); auto visualCharacteristicsConfig = guiConfig.getArray(VISUALCHARACTERISTICS_CONFIG_ROOT_KEY); auto deviceKeysConfig = appConfig[DEVICEKEYS_CONFIG_ROOT_KEY]; // Extract gui app config default window id std::string defaultWindowId; appConfig.getString(APPCONFIG_DEFAULT_WINDOW_ID_KEY, &defaultWindowId); // Extract Alexa display window templates, Alexa interaction modes alexaClientSDK::avsCommon::utils::configuration::ConfigurationNode alexaDisplayWindowInterface; alexaClientSDK::avsCommon::utils::configuration::ConfigurationNode alexaInteractionModeInterface; for (size_t i = 0; i < visualCharacteristicsConfig.getArraySize(); i++) { std::string interfaceName; visualCharacteristicsConfig[i].getString(VISUALCHARACTERISTICS_INTERFACE_KEY, &interfaceName); if (interfaceName == ALEXADISPLAYWINDOW_INTERFACE_NAME) { alexaDisplayWindowInterface = visualCharacteristicsConfig[i]; } else if (interfaceName == ALEXAINTERACTIONMODE_INTERFACE_NAME) { alexaInteractionModeInterface = visualCharacteristicsConfig[i]; } } if (!alexaDisplayWindowInterface) { ACSDK_ERROR(LX(__func__).d("reason", "Alexa display window interface not found")); return false; } if (!alexaInteractionModeInterface) { ACSDK_ERROR(LX(__func__).d("reason", "Alexa interaction mode interface not found")); return false; } auto alexaDisplayWindowTemplates = alexaDisplayWindowInterface[ALEXADISPLAYWINDOW_CONFIGURATIONS_KEY].getArray(ALEXADISPLAYWINDOW_TEMPLATES_KEY); auto alexaInteractionModes = alexaInteractionModeInterface[ALEXADISPLAYWINDOW_CONFIGURATIONS_KEY].getArray( ALEXAINTERACTIONMODE_INTERFACTIONMODES_KEY); // Extract Alexa interaction mode ids; std::vector<std::string> alexaInteractionModeIds; for (size_t i = 0; i < alexaInteractionModes.getArraySize(); i++) { std::string alexaInteractionModeId; alexaInteractionModes[i].getString(ALEXAINTERACTIONMODE_INTERFACTIONMODE_ID_KEY, &alexaInteractionModeId); alexaInteractionModeIds.push_back(alexaInteractionModeId); } // Construct Alexa display window interface template map std::unordered_map<std::string, alexaClientSDK::avsCommon::utils::configuration::ConfigurationNode> alexaDisplayWindowInterfaceTemplateMap; for (size_t i = 0; i < alexaDisplayWindowTemplates.getArraySize(); i++) { std::string alexaDisplayWindowTemplateId; alexaDisplayWindowTemplates[i].getString(ALEXADISPLAYWINDOW_TEMPLATE_ID_KEY, &alexaDisplayWindowTemplateId); alexaDisplayWindowInterfaceTemplateMap.insert({alexaDisplayWindowTemplateId, alexaDisplayWindowTemplates[i]}); } // Validate Alexa display window interface templates interactionModes for (size_t i = 0; i < alexaDisplayWindowTemplates.getArraySize(); i++) { std::set<std::string> windowTemplateInteractionModes; alexaDisplayWindowTemplates[i][ALEXADISPLAYWINDOW_TEMPLATE_CONFIGURATION_KEY].getStringValues( ALEXADISPLAYWINDOW_TEMPLATE_INTERACTIONMODES_KEY, &windowTemplateInteractionModes); for (auto windowTemplateInteractionMode : windowTemplateInteractionModes) { if (std::find( alexaInteractionModeIds.begin(), alexaInteractionModeIds.end(), windowTemplateInteractionMode) == alexaInteractionModeIds.end()) { ACSDK_ERROR(LX(__func__) .d("reason", "validationFailed") .d("message", "InteractionModes ID not found in Alexa.InteractionMode interface")); return false; } } } // Gui app config should have valid default window id // Each gui app config window should have valid template id, size config id and interaction mode bool isDefaultWindowDefined = false; for (std::size_t i = 0; i < windowsConfig.getArraySize(); i++) { std::string windowId; std::string templateId; std::string sizeConfigurationId; std::string interactionMode; windowsConfig[i].getString(WINDOWS_ID_KEY, &windowId); windowsConfig[i].getString(WINDOWS_TEMPLATEID_KEY, &templateId); windowsConfig[i].getString(WINDOWS_SIZECONFIGURATIONID_KEY, &sizeConfigurationId); windowsConfig[i].getString(WINDOWS_INTERACTION_MODE_KEY, &interactionMode); if (windowId == defaultWindowId) { isDefaultWindowDefined = true; } // Extract target window template auto windowTemplate = alexaDisplayWindowInterfaceTemplateMap[templateId]; if (!windowTemplate) { ACSDK_ERROR(LX(__func__).d("reason", "validationFailed").d("message", "Target window template not found")); return false; } // Validate sizeConfigurationId bool isSizeConfigurationDefined = false; auto windowTemplateSizes = windowTemplate[ALEXADISPLAYWINDOW_TEMPLATE_CONFIGURATION_KEY].getArray( ALEXADISPLAYWINDOW_TEMPLATE_SIZES_KEY); for (size_t i = 0; i < windowTemplateSizes.getArraySize(); i++) { std::string sizeId; windowTemplateSizes[i].getString(ALEXADISPLAYWINDOW_TEMPLATE_SIZES_ID_KEY, &sizeId); if (sizeId == sizeConfigurationId) { isSizeConfigurationDefined = true; break; } } if (!isSizeConfigurationDefined) { ACSDK_ERROR(LX(__func__) .d("reason", "validationFailed") .d("message", "Size configuration not found in target window template")); return false; } // Validate interactionMode std::set<std::string> windowTemplateInteractionModes; windowTemplate[ALEXADISPLAYWINDOW_TEMPLATE_CONFIGURATION_KEY].getStringValues( ALEXADISPLAYWINDOW_TEMPLATE_INTERACTIONMODES_KEY, &windowTemplateInteractionModes); if (windowTemplateInteractionModes.find(interactionMode) == windowTemplateInteractionModes.end()) { ACSDK_ERROR(LX(__func__) .d("reason", "validationFailed") .d("message", "Interaction mode not supported by target window template")); return false; } } if (!isDefaultWindowDefined) { ACSDK_ERROR(LX(__func__) .d("reason", "validationFailed") .d("message", "Default window not found in APL window configurations")); return false; } // Detect collision in gui app config device keys config std::unordered_map<int, std::string> deviceKeysKeyCodeMap; for (std::string deviceKey : APPCONFIG_DEVICEKEYS_KEYS) { int keyCode; deviceKeysConfig[deviceKey].getInt(APPCONFIG_DEVICEKEYS_KEYCODE_KEY, &keyCode); if (deviceKeysKeyCodeMap.find(keyCode) != deviceKeysKeyCodeMap.end()) { std::string keyCollisionMessage = deviceKeysKeyCodeMap[keyCode] + ", " + deviceKey; ACSDK_WARN(LX(__func__) .d("reason", "validationIssueDetected") .d("message", "Found collision in app config device key codes") .d("keyCodes", keyCollisionMessage)); } else { deviceKeysKeyCodeMap.insert({keyCode, deviceKey}); } } return true; } }; // namespace sssdkCommon }; // namespace alexaSmartScreenSDK
48.213178
119
0.71726
isabella232
76ad7c947d4264f5fa2762a3d199e6addfc13541
5,471
cpp
C++
test/fibex/out.cpp
cepsdev/sm4ceps
e333a133ac3b3aff066a63046f0f8f7b339110e1
[ "Apache-2.0" ]
7
2021-02-25T19:06:27.000Z
2022-01-18T03:46:27.000Z
test/fibex/out.cpp
cepsdev/sm4ceps
e333a133ac3b3aff066a63046f0f8f7b339110e1
[ "Apache-2.0" ]
10
2021-04-18T22:29:48.000Z
2022-01-26T11:07:13.000Z
test/fibex/out.cpp
cepsdev/sm4ceps
e333a133ac3b3aff066a63046f0f8f7b339110e1
[ "Apache-2.0" ]
1
2021-09-16T14:21:14.000Z
2021-09-16T14:21:14.000Z
/* out.cpp CREATED Fri Mar 17 05:02:44 2017 GENERATED BY THE sm4ceps C++ GENERATOR VERSION 0.90. BASED ON cepS (c) 2017 Tomas Prerovsky <tomas.prerovsky@gmail.com> VERSION 1.1 (Mar 10 2017) BUILT WITH GCC 5.2.1 20151010 on GNU/LINUX 64BIT (C) BY THE AUTHORS OF ceps (ceps is hosted at github: https://github.com/cepsdev/ceps.git) Input files: prelude.ceps can3.xml THIS IS A GENERATED FILE. *** DO NOT MODIFY. *** */ #include "out.hpp" #include<cmath> using namespace std; std::ostream& systemstates::operator << (std::ostream& o, systemstates::State<int> & v){ o << v.value(); return o; } std::ostream& systemstates::operator << (std::ostream& o, systemstates::State<double> & v){ o << v.value(); return o; } systemstates::State<int>& systemstates::set_value(systemstates::State<int>& lhs, Variant const & rhs){ if (rhs.what_ == sm4ceps_plugin_int::Variant::Double) { int v = rhs.dv_; lhs.set_changed(lhs.value() != v); lhs.value() = v; } else if (rhs.what_ == sm4ceps_plugin_int::Variant::Int) { lhs.set_changed(lhs.value() != rhs.iv_); lhs.value() = rhs.iv_; } return lhs; } systemstates::State<int>& systemstates::set_value(systemstates::State<int>& lhs, int rhs){lhs.set_changed(lhs.value() != rhs);lhs.value() = rhs; return lhs;} systemstates::State<double>& systemstates::set_value(systemstates::State<double>& lhs, double rhs){lhs.set_changed(lhs.value() != rhs);lhs.value() = rhs; return lhs;} systemstates::State<double>& systemstates::set_value(systemstates::State<double>& lhs, Variant const & rhs){ if (rhs.what_ == sm4ceps_plugin_int::Variant::Int) { lhs.set_changed(lhs.value() != rhs.iv_); lhs.value() = rhs.iv_;} else if (rhs.what_ == sm4ceps_plugin_int::Variant::Double){ lhs.set_changed(lhs.value() != rhs.dv_); lhs.value() = rhs.dv_;} return lhs; } systemstates::State<std::string>& systemstates::set_value(systemstates::State<std::string>& lhs, std::string rhs){lhs.set_changed(lhs.value() != rhs);lhs.value() = rhs; return lhs;} void init_frame_ctxts(); void user_defined_init(){ set_value(systemstates::rpm , 0); set_value(systemstates::rpm_speed_src , 0); set_value(systemstates::speed , 0); init_frame_ctxts(); } systemstates::State<double> systemstates::rpm; systemstates::State<double> systemstates::rpm_speed_src; systemstates::State<double> systemstates::speed; void init_frame_ctxts(){ systemstates::Engine_RPM_in_ctxt.init(); } //Frame Context Definitions void systemstates::Engine_RPM_in_ctxt_t::update_sysstates(){ systemstates::rpm = rpm_; systemstates::rpm_speed_src = rpm_speed_src_; systemstates::speed = speed_; } void systemstates::Engine_RPM_in_ctxt_t::read_chunk(void* chunk,size_t){ raw_frm_dcls::Engine_RPM_in& in = *((raw_frm_dcls::Engine_RPM_in*)chunk); rpm_ = in.pos_1; speed_ = in.pos_2; rpm_speed_src_ = in.pos_3; } bool systemstates::Engine_RPM_in_ctxt_t::match_chunk(void* chunk,size_t chunk_size){ if(chunk_size != 4) return false; raw_frm_dcls::Engine_RPM_in& in = *((raw_frm_dcls::Engine_RPM_in*)chunk); return true; } void systemstates::Engine_RPM_in_ctxt_t::init(){ rpm_ = systemstates::rpm; rpm_speed_src_ = systemstates::rpm_speed_src; speed_ = systemstates::speed; } sm4ceps_plugin_int::Framecontext* systemstates::Engine_RPM_in_ctxt_t::clone(){ return new Engine_RPM_in_ctxt_t(*this); } systemstates::Engine_RPM_in_ctxt_t::~Engine_RPM_in_ctxt_t (){ } systemstates::Engine_RPM_in_ctxt_t systemstates::Engine_RPM_in_ctxt; extern "C" void init_plugin(IUserdefined_function_registry* smc){ smcore_interface = smc->get_plugin_interface(); smc->register_global_init(user_defined_init); } std::ostream& operator << (std::ostream& o, systemstates::Variant const & v) { if (v.what_ == systemstates::Variant::Int) o << v.iv_; else if (v.what_ == systemstates::Variant::Double) o << std::to_string(v.dv_); else if (v.what_ == systemstates::Variant::String) o << v.sv_; else o << "(Undefined)"; return o; } size_t globfuncs::argc(){ return smcore_interface->argc(); }sm4ceps_plugin_int::Variant globfuncs::argv(size_t j){ return smcore_interface->argv(j); } void globfuncs::start_timer(double t,sm4ceps_plugin_int::ev ev_){ smcore_interface->start_timer(t,ev_); } void globfuncs::start_timer(double t,sm4ceps_plugin_int::ev ev_,sm4ceps_plugin_int::id id_){smcore_interface->start_timer(t,ev_,id_);} void globfuncs::start_periodic_timer(double t ,sm4ceps_plugin_int::ev ev_){smcore_interface->start_periodic_timer(t,ev_);} void globfuncs::start_periodic_timer(double t,sm4ceps_plugin_int::ev ev_,sm4ceps_plugin_int::id id_){smcore_interface->start_periodic_timer(t,ev_,id_);} void globfuncs::start_periodic_timer(double t,sm4ceps_plugin_int::Variant (*fp)(),sm4ceps_plugin_int::id id_){smcore_interface->start_periodic_timer(t,fp,id_);} void globfuncs::start_periodic_timer(double t,sm4ceps_plugin_int::Variant (*fp)()){smcore_interface->start_periodic_timer(t,fp);} void globfuncs::stop_timer(sm4ceps_plugin_int::id id_){smcore_interface->stop_timer(id_);} bool globfuncs::in_state(std::initializer_list<sm4ceps_plugin_int::id> state_ids){return smcore_interface->in_state(state_ids);} raw_frm_dcls::Engine_RPM_out create_frame_Engine_RPM(){ raw_frm_dcls::Engine_RPM_out out = {0}; out.pos_1 = systemstates::rpm.value(); out.pos_2 = systemstates::speed.value(); out.pos_3 = systemstates::rpm_speed_src.value(); return out; }
36.473333
236
0.735149
cepsdev
76add05f31a823cb55f1e87e4914d8e3d2b4f9c1
2,299
cpp
C++
src/join.cpp
robhz786/strf-benchmarks
e783700317ef1fea0d9e7217c8c42884c3c0371e
[ "BSL-1.0" ]
1
2021-07-19T11:07:24.000Z
2021-07-19T11:07:24.000Z
src/join.cpp
robhz786/strf-benchmarks
e783700317ef1fea0d9e7217c8c42884c3c0371e
[ "BSL-1.0" ]
null
null
null
src/join.cpp
robhz786/strf-benchmarks
e783700317ef1fea0d9e7217c8c42884c3c0371e
[ "BSL-1.0" ]
null
null
null
// Distributed under the Boost Software License, Version 1.0. // ( See accompanying file LICENSE or copy at // http://www.boost.org/LICENSE_1_0.txt ) #include <benchmark/benchmark.h> #include <strf/to_cfile.hpp> #define CREATE_BENCHMARK(PREFIX) \ static void PREFIX (benchmark::State& state) { \ char dest[100]; \ for(auto _ : state) { \ (void) PREFIX ## _OP ; \ benchmark::DoNotOptimize(dest); \ benchmark::ClobberMemory(); \ } \ } #define REGISTER_BENCHMARK(X) benchmark::RegisterBenchmark(STR(X ## _OP), X); #define STR2(X) #X #define STR(X) STR2(X) #define BM_JOIN_4_OP strf::to(dest) (strf::join('a', 'b', 'c', 'd')) #define BM_4_OP strf::to(dest) ('a', 'b', 'c', 'd') #define BM_JOIN_8_OP strf::to(dest) (strf::join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')) #define BM_8_OP strf::to(dest) ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') #define BM_JR_8_OP strf::to(dest) (strf::join_right(15)('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')) #define BM_JR_STR_OP strf::to(dest) (strf::join_right(15)("Hello World")) #define BM_JR2_STR_OP strf::to(dest) (strf::join("Hello World") > 15) #define BM_STR_OP strf::to(dest) (strf::fmt("Hello World") > 15) #define BM_JRI_OP strf::to(dest) (strf::join_right(4)(25)) #define BM_RI_OP strf::to(dest) (strf::dec(25) > 4) CREATE_BENCHMARK(BM_JOIN_4); CREATE_BENCHMARK(BM_4); CREATE_BENCHMARK(BM_JOIN_8); CREATE_BENCHMARK(BM_8); CREATE_BENCHMARK(BM_JR_8); CREATE_BENCHMARK(BM_JR_STR); CREATE_BENCHMARK(BM_JR2_STR); CREATE_BENCHMARK(BM_STR); CREATE_BENCHMARK(BM_JRI); CREATE_BENCHMARK(BM_RI); int main(int argc, char** argv) { REGISTER_BENCHMARK(BM_JOIN_4); REGISTER_BENCHMARK(BM_4); REGISTER_BENCHMARK(BM_JOIN_8); REGISTER_BENCHMARK(BM_8); REGISTER_BENCHMARK(BM_JR_8); REGISTER_BENCHMARK(BM_JR_STR); REGISTER_BENCHMARK(BM_JR2_STR); REGISTER_BENCHMARK(BM_STR); REGISTER_BENCHMARK(BM_JRI); REGISTER_BENCHMARK(BM_RI); benchmark::Initialize(&argc, argv); benchmark::RunSpecifiedBenchmarks(); return 0; }
35.921875
100
0.597216
robhz786
76b1757a87800c7b549d40adfcab3a6320719bd1
7,292
cpp
C++
2004/samples/graphics/traits_dg/traits.cpp
kevinzhwl/ObjectARXMod
ef4c87db803a451c16213a7197470a3e9b40b1c6
[ "MIT" ]
1
2021-06-25T02:58:47.000Z
2021-06-25T02:58:47.000Z
2004/samples/graphics/traits_dg/traits.cpp
kevinzhwl/ObjectARXMod
ef4c87db803a451c16213a7197470a3e9b40b1c6
[ "MIT" ]
null
null
null
2004/samples/graphics/traits_dg/traits.cpp
kevinzhwl/ObjectARXMod
ef4c87db803a451c16213a7197470a3e9b40b1c6
[ "MIT" ]
3
2020-05-23T02:47:44.000Z
2020-10-27T01:26:53.000Z
// (C) Copyright 1996,1998 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // // traits.cpp // // This sample demonstrates using many of the AcGiSubEntityTraits // class functions for controlling the properties of the graphics // primitives drawn during entity elaboration. #include <string.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include "aced.h" #include "dbsymtb.h" #include "dbapserv.h" #include "acgi.h" // function prototypes // // THE FOLLOWING CODE APPEARS IN THE SDK DOCUMENT. static Acad::ErrorStatus getLinetypeIdFromString(const char* str, AcDbObjectId& id); static Acad::ErrorStatus getLayerIdFromString(const char* str, AcDbObjectId& id); // END CODE APPEARING IN SDK DOCUMENT. // Helpful constants for setting attributes: // COLOR // static const Adesk::UInt16 kColorByBlock = 0; static const Adesk::UInt16 kRed = 1; static const Adesk::UInt16 kYellow = 2; static const Adesk::UInt16 kGreen = 3; static const Adesk::UInt16 kCyan = 4; static const Adesk::UInt16 kBlue = 5; static const Adesk::UInt16 kMagenta = 6; static const Adesk::UInt16 kWhite = 7; static const Adesk::UInt16 kColorByLayer = 256; class AsdkTraitsSamp: public AcDbEntity { public: ACRX_DECLARE_MEMBERS(AsdkTraitsSamp); virtual Adesk::Boolean worldDraw(AcGiWorldDraw *); Acad::ErrorStatus transformBy(const AcGeMatrix3d &); }; ACRX_DXF_DEFINE_MEMBERS(AsdkTraitsSamp,AcDbEntity, AcDb::kDHL_CURRENT, AcDb::kMReleaseCurrent, 0,\ ASDKTRAITSSAMP,AsdkTraits Sample); Acad::ErrorStatus AsdkTraitsSamp::transformBy( const AcGeMatrix3d &xfm) { return Acad::eOk; } // THE FOLLOWING CODE APPEARS IN THE SDK DOCUMENT. Adesk::Boolean AsdkTraitsSamp::worldDraw(AcGiWorldDraw* pW) { // At this point, the current property traits are // the entity's property traits. If the current // property traits are changed and you want to // reapply the entity's property traits, this is // the place to save them. // Adesk::UInt16 entity_color = pW->subEntityTraits().color(); AcDbObjectId entity_linetype = pW->subEntityTraits().lineTypeId(); AcDbObjectId entity_layer = pW->subEntityTraits().layerId(); // Override the current color and make it blue. // pW->subEntityTraits().setColor(kBlue); // Draw a blue 3-point polyline. // int num_pts = 3; AcGePoint3d *pVerts = new AcGePoint3d[num_pts]; pVerts[0] = AcGePoint3d(0.0, 0.0, 0); pVerts[1] = AcGePoint3d(1.0, 0.0, 0); pVerts[2] = AcGePoint3d(1.0, 1.0, 0); pW->geometry().polyline(num_pts, pVerts); // Force the current color to use current layer's color. // pW->subEntityTraits().setColor(kColorByLayer); // Force current line type to "DASHDOT". If // "DASHDOT" is not loaded, the current line // type will still be in effect. // AcDbObjectId dashdotId; if (getLinetypeIdFromString("DASHDOT", dashdotId) == Acad::eOk) { pW->subEntityTraits().setLineType(dashdotId); } // Force current layer to "MY_LAYER". If // "MY_LAYER" is not loaded, the current layer // will still be in effect. // AcDbObjectId layerId; if (getLayerIdFromString("MY_LAYER", layerId) == Acad::eOk) { pW->subEntityTraits().setLayer(layerId); } // Draw a dashdot'd xline in "MY_LAYER"'s color. // pW->geometry().xline(pVerts[0], pVerts[2]); delete [] pVerts; return Adesk::kTrue; } // A useful function that gets the linetype ID from the // linetype's name -- must be in upper case. // static Acad::ErrorStatus getLinetypeIdFromString(const char* str, AcDbObjectId& id) { Acad::ErrorStatus err; // Get the table of currently loaded linetypes. // AcDbLinetypeTable *pLinetypeTable; err = acdbHostApplicationServices()->workingDatabase() ->getSymbolTable(pLinetypeTable, AcDb::kForRead); if (err != Acad::eOk) return err; // Get the id of the linetype with the name that // 'str' contains. // err = pLinetypeTable->getAt(str, id, Adesk::kTrue); pLinetypeTable->close(); return err; } // A useful function that gets the layer ID from the // layer's name -- must be in upper case. // static Acad::ErrorStatus getLayerIdFromString(const char* str, AcDbObjectId& id) { Acad::ErrorStatus err; // Get the table of currently loaded layers. // AcDbLayerTable *pLayerTable; err = acdbHostApplicationServices()->workingDatabase() ->getSymbolTable(pLayerTable, AcDb::kForRead); if (err != Acad::eOk) return err; // Get the ID of the layer with the name that 'str' // contains. // err = pLayerTable->getAt(str, id, Adesk::kTrue); pLayerTable->close(); return err; } // END CODE APPEARING IN SDK DOCUMENT. void addAsdkTraitsSampObject() { AsdkTraitsSamp *pNewObj = new AsdkTraitsSamp; AcDbBlockTable *pBlockTable; acdbHostApplicationServices()->workingDatabase() ->getSymbolTable(pBlockTable, AcDb::kForRead); AcDbBlockTableRecord *pBlock; pBlockTable->getAt(ACDB_MODEL_SPACE, pBlock, AcDb::kForWrite); AcDbObjectId objId; pBlock->appendAcDbEntity(objId, pNewObj); pBlockTable->close(); pBlock->close(); pNewObj->close(); } static void initAsdkTraitsSamp() { AsdkTraitsSamp::rxInit(); acrxBuildClassHierarchy(); acedRegCmds->addCommand("ASDK_TRAITS_SAMP", "ASDKTRAITSSAMP", "TRAITSSAMP", ACRX_CMD_TRANSPARENT, addAsdkTraitsSampObject); } extern "C" AcRx::AppRetCode acrxEntryPoint(AcRx::AppMsgCode msg, void* appId) { switch(msg) { case AcRx::kInitAppMsg: acrxDynamicLinker->unlockApplication(appId); acrxDynamicLinker->registerAppMDIAware(appId); initAsdkTraitsSamp(); break; case AcRx::kUnloadAppMsg: acedRegCmds->removeGroup("ASDK_TRAITS_SAMP"); deleteAcRxClass(AsdkTraitsSamp::desc()); } return AcRx::kRetOK; }
28.936508
73
0.652907
kevinzhwl
76b17f81649a6999c1a3fce0974c4946ee13a356
3,264
cpp
C++
src/StartUpDialog.cpp
Nodens-LOTGA/CircuitTester
23438f49651f537c43cd78f64e61c2a5024ec8c8
[ "MIT" ]
null
null
null
src/StartUpDialog.cpp
Nodens-LOTGA/CircuitTester
23438f49651f537c43cd78f64e61c2a5024ec8c8
[ "MIT" ]
null
null
null
src/StartUpDialog.cpp
Nodens-LOTGA/CircuitTester
23438f49651f537c43cd78f64e61c2a5024ec8c8
[ "MIT" ]
null
null
null
#include "startupdialog.h" #include "./ui_startupdialog.h" #include "Settings.h" #include "tools.h" #include <QCryptographicHash> #include <QMessageBox> #include <QRegExpValidator> #include <QSerialPort> #include <QSerialPortInfo> #include <QSettings> #include <QStyledItemDelegate> StartUpDialog::StartUpDialog(QWidget *parent) : QDialog(parent), ui(new Ui::StartUpDialog) { ui->setupUi(this); connect(ui->enterPB, SIGNAL(clicked()), this, SLOT(tryAccept())); ui->pwLE->setValidator(new QRegExpValidator(QRegExp(".{8,32}"), this)); ui->nameLE->setValidator( new QRegExpValidator(QRegExp(tr("[\\w\\s]+")), this)); // QSettings set; // set.clear(); // ui->portCB->setItemDelegate(new QStyledItemDelegate()); // ui->userCB->setItemDelegate(new QStyledItemDelegate()); Settings sett; ui->newUserChkB->setEnabled(sett.newUsers); updateNames(); updatePorts(); } StartUpDialog::~StartUpDialog() { delete ui; } void StartUpDialog::updateNames() { Settings sett; int lastUserIndex{}; ui->userCB->clear(); QMap<QString, QVariant>::const_iterator i = sett.users.constBegin(); while (i != sett.users.constEnd()) { ui->userCB->addItem(i.key(), i.value()); if (i.key() == sett.userName) lastUserIndex = ui->userCB->count() - 1; i++; } ui->userCB->setCurrentIndex(lastUserIndex); } void StartUpDialog::updatePorts() { auto ports = QSerialPortInfo::availablePorts(); for (auto &i : ports) ui->portCB->addItem(i.portName()); } void StartUpDialog::tryAccept() { Settings sett; QString pw = ui->pwLE->text(); if (pw.length() < 8) { QMessageBox::warning( this, RU("Неверный пароль"), RU("Пароль должен состоять не менее чем из 8 символов")); return; } if (ui->newUserChkB->isChecked()) { QString newUserName = ui->nameLE->text().simplified(); if (newUserName.isEmpty()) { QMessageBox::warning(this, RU("Неверный пользователь"), RU("Имя пользователя не должно быть пустым")); return; } if (sett.users.contains(newUserName)) { QMessageBox::warning(this, RU("Неверный пользователь"), RU("Пользователь с таким именем уже существует")); return; } sett.users[newUserName] = pw; sett.userName = newUserName; sett.isAdmin = false; sett.save(); updateNames(); } else { if (ui->userCB->currentText() == "") { QMessageBox::warning(this, RU("Неверный пользователь"), RU("Пожалуйста, выберите пользователя")); return; } QString userName = ui->userCB->currentText(); if (sett.users.contains(userName)) { if (sett.users[userName] != pw) { QMessageBox::warning(this, RU("Неверный пароль"), RU("Пароль не совпадает")); return; } else { sett.userName = userName; } } if (userName == sett.adminName) sett.isAdmin = true; else sett.isAdmin = false; } // TODO: if (ui->portCB->currentText() == "") { QMessageBox::warning(this, RU("Неверный порт"), RU("Пожалуйста, выберетие порт")); return; } else sett.portName = ui->portCB->currentText(); sett.save(); accept(); }
28.631579
77
0.620098
Nodens-LOTGA
76b77d61d5250abb66815a3a211cdeb245b2e6a8
25,942
cc
C++
Modules/PointSet/src/SurfaceCollisions.cc
lisurui6/MIRTK
5a06041102d7205b5aac147ff768df6e9415bd03
[ "Apache-2.0" ]
null
null
null
Modules/PointSet/src/SurfaceCollisions.cc
lisurui6/MIRTK
5a06041102d7205b5aac147ff768df6e9415bd03
[ "Apache-2.0" ]
null
null
null
Modules/PointSet/src/SurfaceCollisions.cc
lisurui6/MIRTK
5a06041102d7205b5aac147ff768df6e9415bd03
[ "Apache-2.0" ]
null
null
null
/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2013-2016 Imperial College London * Copyright 2013-2016 Andreas Schuh * * 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 "mirtk/SurfaceCollisions.h" #include "mirtk/Assert.h" #include "mirtk/Math.h" #include "mirtk/Triangle.h" #include "mirtk/PointSetUtils.h" #include "mirtk/PointLocator.h" #include "mirtk/Parallel.h" #include "mirtk/Profiling.h" #include "mirtk/Vtk.h" #include "mirtk/VtkMath.h" #include "vtkPlane.h" #include "vtkTriangle.h" #include "vtkPolyData.h" #include "vtkCellData.h" #include "vtkDataArray.h" #include "vtkFloatArray.h" #include "vtkUnsignedCharArray.h" #include "vtkAbstractPointLocator.h" #include "vtkOctreePointLocator.h" namespace mirtk { // ============================================================================= // Names of data arrays // ============================================================================= MIRTK_PointSet_EXPORT const char * const SurfaceCollisions::BOUNDING_SPHERE_CENTER = "BoundingSphereCenter"; MIRTK_PointSet_EXPORT const char * const SurfaceCollisions::BOUNDING_SPHERE_RADIUS = "BoundingSphereRadius"; MIRTK_PointSet_EXPORT const char * const SurfaceCollisions::COLLISION_TYPE = "CollisionType"; // ============================================================================= // Auxiliary functors // ============================================================================= namespace SurfaceCollisionsUtils { // ----------------------------------------------------------------------------- /// Compute center and radius of each bounding spheres class ComputeBoundingSpheres { vtkPolyData *_Surface; vtkDataArray *_Center; vtkDataArray *_Radius; ComputeBoundingSpheres(vtkPolyData *surface, vtkDataArray *center, vtkDataArray *radius) : _Surface(surface), _Center(center), _Radius(radius) {} public: /// Compute bounding spheres of specified range of cells void operator ()(const blocked_range<vtkIdType> &re) const { vtkNew<vtkIdList> ptIds; double a[3], b[3], c[3], origin[3], radius; for (vtkIdType cellId = re.begin(); cellId != re.end(); ++cellId) { // Get triangle vertices _Surface->GetCellPoints(cellId, ptIds.GetPointer()); mirtkAssert(ptIds->GetNumberOfIds() == 3, "surface is triangular mesh"); // Get triangle vertex positions _Surface->GetPoint(ptIds->GetId(0), a); _Surface->GetPoint(ptIds->GetId(1), b); _Surface->GetPoint(ptIds->GetId(2), c); // Get center of bounding sphere vtkTriangle::TriangleCenter(a, b, c, origin); _Center->SetTuple(cellId, origin); // Compute radius of bounding sphere radius = sqrt(max(max(vtkMath::Distance2BetweenPoints(a, origin), vtkMath::Distance2BetweenPoints(b, origin)), vtkMath::Distance2BetweenPoints(c, origin))); _Radius->SetTuple1(cellId, radius); } } /// Compute bounding spheres of surface faces static void Run(vtkPolyData *surface, vtkDataArray *center, vtkDataArray *radius) { center->SetNumberOfComponents(3); center->SetNumberOfTuples(surface->GetNumberOfCells()); radius->SetNumberOfComponents(1); radius->SetNumberOfTuples(surface->GetNumberOfCells()); if (surface->GetNumberOfCells() == 0) return; ComputeBoundingSpheres eval(surface, center, radius); parallel_for(blocked_range<vtkIdType>(0, surface->GetNumberOfCells()), eval); } }; // ----------------------------------------------------------------------------- /// Check for collisions such as self-intersections and faces too close class FindCollisions { typedef SurfaceCollisions::IntersectionInfo IntersectionInfo; typedef SurfaceCollisions::IntersectionsArray IntersectionsArray; typedef SurfaceCollisions::CollisionType CollisionType; typedef SurfaceCollisions::CollisionsArray CollisionsArray; typedef SurfaceCollisions::CollisionInfo CollisionInfo; SurfaceCollisions *_Filter; vtkAbstractPointLocator *_Locator; IntersectionsArray *_Intersections; CollisionsArray *_Collisions; double _MaxRadius; double _MinFrontfaceDistance; double _MinBackfaceDistance; double _MinAngleCos; /// Check whether point c is on the "left" of the line defined by a and b inline int IsLeft(const double a[2], const double b[2], const double c[2]) const { return sgn((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])); } public: void operator ()(const blocked_range<vtkIdType> &re) const { const double TOL = 1e-6; // Tolerance for point coordinate equality check vtkDataArray *mask = _Filter->Mask(); vtkPolyData *surface = _Filter->Output(); vtkDataArray *center = _Filter->GetCenterArray(); vtkDataArray *radius = _Filter->GetRadiusArray(); vtkDataArray *coll_type = _Filter->GetCollisionTypeArray(); const bool coll_test = (_MinFrontfaceDistance > .0 || _MinBackfaceDistance > .0); const double min_distance = max(_MinFrontfaceDistance, _MinBackfaceDistance); const double R = _MaxRadius + 1.1 * min_distance; double tri1[3][3], tri2[3][3], tri1_2D[3][2], tri2_2D[3][2]; double n1[3], n2[3], p1[3], p2[3], r1, c1[3], d[3], search_radius, dot; int tri12[3], i1, i2, shared_vertex1, shared_vertex2, coplanar, s1, s2; vtkNew<vtkIdList> ptIds, cellIds, triPtIds1, triPtIds2, triCellIds; vtkIdType cellId1, cellId2; CollisionInfo collision; CollisionType type; for (cellId1 = re.begin(); cellId1 != re.end(); ++cellId1) { // No collision if none detected type = CollisionType::NoCollision; if (mask && mask->GetComponent(cellId1, 0) == .0) { continue; // Skip cell if (un)masked and keep collision type unmodified } // Get vertices and normal of this triangle surface->GetCellPoints(cellId1, triPtIds1.GetPointer()); mirtkAssert(triPtIds1->GetNumberOfIds() == 3, "surface is triangular mesh"); surface->GetPoint(triPtIds1->GetId(0), tri1[0]); surface->GetPoint(triPtIds1->GetId(1), tri1[1]); surface->GetPoint(triPtIds1->GetId(2), tri1[2]); vtkTriangle::ComputeNormal(tri1[0], tri1[1], tri1[2], n1); // Get bounding sphere center->GetTuple(cellId1, c1); r1 = radius->GetComponent(cellId1, 0); // Find other triangles within search radius search_radius = min(max(_Filter->MinSearchRadius(), r1 + R), _Filter->MaxSearchRadius()); _Locator->FindPointsWithinRadius(search_radius, c1, ptIds.GetPointer()); cellIds->Reset(); for (vtkIdType i = 0; i < ptIds->GetNumberOfIds(); ++i) { surface->GetPointCells(ptIds->GetId(i), triCellIds.GetPointer()); for (vtkIdType j = 0; j < triCellIds->GetNumberOfIds(); ++j) { if (triCellIds->GetId(j) != cellId1) cellIds->InsertUniqueId(triCellIds->GetId(j)); } } // Check for collisions between this triangle and the found nearby triangles for (vtkIdType i = 0; i < cellIds->GetNumberOfIds(); ++i) { cellId2 = cellIds->GetId(i); // Get vertex positions of nearby candidate triangle surface->GetCellPoints(cellId2, triPtIds2.GetPointer()); surface->GetPoint(triPtIds2->GetId(0), tri2[0]); surface->GetPoint(triPtIds2->GetId(1), tri2[1]); surface->GetPoint(triPtIds2->GetId(2), tri2[2]); // Get corresponding indices of shared vertices for (i1 = 0; i1 < 3; ++i1) { tri12[i1] = -1; for (i2 = 0; i2 < 3; ++i2) { if (triPtIds1->GetId(i1) == triPtIds2->GetId(i2)) { tri12[i1] = i2; break; } } } // Determine whether triangles share one vertex or even an edge shared_vertex1 = shared_vertex2 = -1; for (i1 = 0; i1 < 3; ++i1) { if (tri12[i1] != -1) { shared_vertex1 = i1; for (i2 = i1 + 1; i2 < 3; ++i2) { if (tri12[i2] != -1) { shared_vertex2 = i2; break; } } break; } } // Triangles with a shared edge can only overlap, but not intersect if (shared_vertex2 != -1) { if (_Filter->AdjacentIntersectionTest()) { coplanar = 0; for (i2 = 0; i2 < 3; ++i2) { if (i2 != tri12[shared_vertex1] && i2 != tri12[shared_vertex2]) { coplanar = int(vtkPlane::DistanceToPlane(tri2[i2], tri1[0], n1) < TOL); break; } } if (coplanar) { // Project triangles into their common plane vtkTriangle::ProjectTo2D(tri1 [0], tri1 [1], tri1 [2], tri1_2D[0], tri1_2D[1], tri1_2D[2]); vtkTriangle::ProjectTo2D(tri2 [0], tri2 [1], tri2 [2], tri2_2D[0], tri2_2D[1], tri2_2D[2]); // Check on which side of the shared edge the non-shared vertices are s1 = 0; for (i1 = 0; i1 < 3; ++i1) { if (i1 != shared_vertex1 && i1 != shared_vertex2) { s1 = IsLeft(tri1_2D[shared_vertex1], tri1_2D[shared_vertex2], tri1_2D[i1]); break; } } // Note: re-uses i2 index found outside of this if-block s2 = IsLeft(tri1_2D[shared_vertex1], tri1_2D[shared_vertex2], tri2_2D[i2]); // If they are on the same side of the edge, the triangles must overlap if (s1 == s2) { //intersections.insert(IntersectionInfo(cellId2, true)); if (_Filter->IsCollision(type)) { type = CollisionType::Ambiguous; } else if (type == CollisionType::SelfIntersection) { type = CollisionType::Intersection; } else { type = CollisionType::AdjacentIntersection; } } } } } // If triangles share a single vertex, use different triangle/triangle // intersection check which gives us the points forming the line/point // of intersection, but does not handle the coplanar case itself else if (shared_vertex1 != -1) { if (_Filter->AdjacentIntersectionTest()) { // Perform coplanarity test with our TOL instead of the smaller // tolerance value used by vtkIntersectionPolyDataFilter coplanar = 0; Triangle::Normal(tri2[0], tri2[1], tri2[2], n2); if (fequal(n1[0], n2[0], TOL) && fequal(n1[1], n2[1], TOL) && fequal(n1[2], n2[2], TOL)) { const double b1 = -vtkMath::Dot(n1, tri1[0]); const double b2 = -vtkMath::Dot(n2, tri2[0]); if (fequal(b1, b2, TOL)) coplanar = 1; } if (coplanar) { // TODO: Either one triangle fully contained within the other // or one edge of the first triangle intersects an edge of // the second triangle. } else if (Triangle::TriangleTriangleIntersection(tri1[0], tri1[1], tri1[2], tri2[0], tri2[1], tri2[2], coplanar, p1, p2)) { // Ignore valid intersection of single shared vertex if (!fequal(p1[0], p2[0], TOL) || !fequal(p1[1], p2[1], TOL) || !fequal(p1[2], p2[2], TOL)) { if (_Intersections) { (*_Intersections)[cellId1].insert(IntersectionInfo(cellId2, true)); } if (_Filter->IsCollision(type)) { type = CollisionType::Ambiguous; } else if (type == CollisionType::SelfIntersection) { type = CollisionType::Intersection; } else { type = CollisionType::AdjacentIntersection; } } } } } // In case of non-adjacent triangles, use fast intersection test which // also checks for overlap of coplanar triangles else if (_Filter->NonAdjacentIntersectionTest() && Triangle::TriangleTriangleIntersection(tri1[0], tri1[1], tri1[2], tri2[0], tri2[1], tri2[2])) { if (_Intersections) { (*_Intersections)[cellId1].insert(IntersectionInfo(cellId2, false)); } if (_Filter->IsCollision(type)) { type = CollisionType::Ambiguous; } else if (type == CollisionType::AdjacentIntersection) { type = CollisionType::Intersection; } else { type = CollisionType::SelfIntersection; } } // If self-intersection check of non-adjacent triangles disabled or negative, // check for near miss collision if minimum distance set else if (coll_test) { if (_Filter->FastCollisionTest()) { collision._Distance = Triangle::DistanceBetweenCenters( tri1[0], tri1[1], tri1[2], tri2[0], tri2[1], tri2[2], collision._Point1, collision._Point2); } else { Triangle::Normal(tri2[0], tri2[1], tri2[2], n2); collision._Distance = Triangle::DistanceBetweenTriangles( tri1[0], tri1[1], tri1[2], n1, tri2[0], tri2[1], tri2[2], n2, collision._Point1, collision._Point2); } if (collision._Distance < min_distance) { if (collision._Distance > 0.) { vtkMath::Subtract(collision._Point2, collision._Point1, d); dot = vtkMath::Dot(d, n1) / vtkMath::Norm(d); } else { dot = 0.; } if (abs(dot) >= _MinAngleCos) { if (dot < .0) { if (_Filter->BackfaceCollisionTest() && collision._Distance < _MinBackfaceDistance) { collision._Type = CollisionType::BackfaceCollision; } else { collision._Type = CollisionType::NoCollision; } } else { if (_Filter->FrontfaceCollisionTest() && collision._Distance < _MinFrontfaceDistance) { collision._Type = CollisionType::FrontfaceCollision; } else { collision._Type = CollisionType::NoCollision; } } if (collision._Type != CollisionType::NoCollision) { collision._CellId = cellId2; if (_Collisions) { (*_Collisions)[cellId1].insert(collision); } if (_Filter->IsIntersection(type)) { type = CollisionType::Ambiguous; } else if (type != CollisionType::NoCollision) { if (type != collision._Type) type = CollisionType::Collision; } else { type = collision._Type; } } } } } } // Set collision type of this cell coll_type->SetComponent(cellId1, 0, type); } } /// Find collision and self-intersections static void Run(SurfaceCollisions *filter, IntersectionsArray *intersections, CollisionsArray *collisions) { vtkDataArray *radius = filter->GetRadiusArray(); vtkSmartPointer<vtkAbstractPointLocator> locator; locator = vtkSmartPointer<vtkOctreePointLocator>::New(); locator->SetDataSet(filter->Output()); locator->BuildLocator(); FindCollisions body; body._Filter = filter; body._Locator = locator; body._Intersections = intersections; body._Collisions = collisions; body._MaxRadius = radius->GetRange(0)[1]; body._MinAngleCos = cos(filter->MaxAngle() * rad_per_deg); body._MinFrontfaceDistance = filter->MinFrontfaceDistance(); body._MinBackfaceDistance = filter->MinBackfaceDistance(); if (!filter->BackfaceCollisionTest()) body._MinFrontfaceDistance = .0; if (!filter->FrontfaceCollisionTest()) body._MinBackfaceDistance = .0; blocked_range<vtkIdType> cellIds(0, filter->Output()->GetNumberOfCells()); parallel_for(cellIds, body); } }; } // namespace SurfaceCollisionsUtils using namespace SurfaceCollisionsUtils; // ============================================================================= // Construction/destruction // ============================================================================= // ----------------------------------------------------------------------------- void SurfaceCollisions::CopyAttributes(const SurfaceCollisions &other) { _Mask = other._Mask; _UseInputBoundingSpheres = other._UseInputBoundingSpheres; _MinSearchRadius = other._MinSearchRadius; _MaxSearchRadius = other._MaxSearchRadius; _MinFrontfaceDistance = other._MinFrontfaceDistance; _MinBackfaceDistance = other._MinBackfaceDistance; _MaxAngle = other._MaxAngle; _AdjacentIntersectionTest = other._AdjacentIntersectionTest; _NonAdjacentIntersectionTest = other._NonAdjacentIntersectionTest; _FrontfaceCollisionTest = other._FrontfaceCollisionTest; _BackfaceCollisionTest = other._BackfaceCollisionTest; _FastCollisionTest = other._FastCollisionTest; _StoreIntersectionDetails = other._StoreIntersectionDetails; _StoreCollisionDetails = other._StoreCollisionDetails; _ResetCollisionType = other._ResetCollisionType; _Intersections = other._Intersections; _Collisions = other._Collisions; } // ----------------------------------------------------------------------------- SurfaceCollisions::SurfaceCollisions() : _UseInputBoundingSpheres(false), _MinSearchRadius(.0), _MaxSearchRadius(inf), _MinFrontfaceDistance(.0), _MinBackfaceDistance(.0), _MaxAngle(90.0), _AdjacentIntersectionTest(false), _NonAdjacentIntersectionTest(false), _FrontfaceCollisionTest(false), _BackfaceCollisionTest(false), _FastCollisionTest(false), _StoreIntersectionDetails(true), _StoreCollisionDetails(true), _ResetCollisionType(true) { } // ----------------------------------------------------------------------------- SurfaceCollisions::SurfaceCollisions(const SurfaceCollisions &other) : SurfaceFilter(other) { CopyAttributes(other); } // ----------------------------------------------------------------------------- SurfaceCollisions &SurfaceCollisions::operator =(const SurfaceCollisions &other) { if (this != &other) { SurfaceFilter::operator =(other); CopyAttributes(other); } return *this; } // ----------------------------------------------------------------------------- SurfaceCollisions::~SurfaceCollisions() { } // ============================================================================= // Output attributes // ============================================================================= // ----------------------------------------------------------------------------- vtkDataArray *SurfaceCollisions::GetCenterArray() const { return _Output->GetCellData()->GetArray(BOUNDING_SPHERE_CENTER); } // ----------------------------------------------------------------------------- vtkDataArray *SurfaceCollisions::GetRadiusArray() const { return _Output->GetCellData()->GetArray(BOUNDING_SPHERE_RADIUS); } // ----------------------------------------------------------------------------- vtkDataArray *SurfaceCollisions::GetCollisionTypeArray() const { return _Output->GetCellData()->GetArray(COLLISION_TYPE); } // ----------------------------------------------------------------------------- SurfaceCollisions::CollisionType SurfaceCollisions::GetCollisionType(int cellId) const { return static_cast<CollisionType>(static_cast<int>(GetCollisionTypeArray()->GetComponent(cellId, 0))); } // ----------------------------------------------------------------------------- #ifdef VTK_USE_64BIT_IDS SurfaceCollisions::CollisionType SurfaceCollisions::GetCollisionType(vtkIdType cellId) const { return static_cast<CollisionType>(static_cast<int>(GetCollisionTypeArray()->GetComponent(cellId, 0))); } #endif // VTK_USE_64BIT_IDS // ============================================================================= // Execution // ============================================================================= // ----------------------------------------------------------------------------- void SurfaceCollisions::Initialize() { // Initialize base class SurfaceFilter::Initialize(); // Check input mesh if (!IsTriangularMesh(_Input)) { cerr << this->NameOfType() << "::Initialize: Input mesh must have triangular faces!" << endl; exit(1); } // Check mask if (_Mask != nullptr) { if (_Mask->GetNumberOfTuples() != _Input->GetNumberOfCells() || _Mask->GetNumberOfComponents() == 0) { cerr << this->NameOfType() << "::Initialize: Input mask must have one entry for each triangular face of input mesh" << endl; exit(1); } } // Reset stored collisions from previous run _Intersections.clear(); _Collisions.clear(); // Enable default collision tests if none selected if (!_AdjacentIntersectionTest && !_NonAdjacentIntersectionTest && !_BackfaceCollisionTest && !_FrontfaceCollisionTest) { _AdjacentIntersectionTest = true; _NonAdjacentIntersectionTest = true; _FrontfaceCollisionTest = (_MinFrontfaceDistance > .0); _BackfaceCollisionTest = (_MinBackfaceDistance > .0); } // Ensure that any collision tests are enabled if (!_AdjacentIntersectionTest && !_NonAdjacentIntersectionTest && (_MinFrontfaceDistance <= .0 || !_FrontfaceCollisionTest) && (_MinBackfaceDistance <= .0 || !_BackfaceCollisionTest)) { cerr << this->NameOfType() << "::Initialize: No collision tests enabled or minimum distances not positive" << endl; exit(1); } // Ensure distance/radius parameters are non-negative if (_MinFrontfaceDistance < .0) _MinFrontfaceDistance = .0; if (_MinBackfaceDistance < .0) _MinBackfaceDistance = .0; if (_MinSearchRadius < .0) _MinSearchRadius = .0; // Precompute bounding spheres and prepare auxiliary data arrays bool compute_bounding_spheres = !_UseInputBoundingSpheres; bool reset_collision_types = _ResetCollisionType; vtkSmartPointer<vtkDataArray> center, radius, types; center = _Output->GetCellData()->GetArray(BOUNDING_SPHERE_CENTER); radius = _Output->GetCellData()->GetArray(BOUNDING_SPHERE_RADIUS); types = _Output->GetCellData()->GetArray(COLLISION_TYPE); if (!center || !radius) { if (!center) { center = vtkSmartPointer<vtkFloatArray>::New(); center->SetName(BOUNDING_SPHERE_CENTER); _Output->GetCellData()->AddArray(center); } if (!radius) { radius = vtkSmartPointer<vtkFloatArray>::New(); radius->SetName(BOUNDING_SPHERE_RADIUS); _Output->GetCellData()->AddArray(radius); } compute_bounding_spheres = true; } if (compute_bounding_spheres) { ComputeBoundingSpheres::Run(_Output, center, radius); } if (!types) { types = vtkSmartPointer<vtkUnsignedCharArray>::New(); types->SetNumberOfComponents(1); types->SetNumberOfTuples(_Output->GetNumberOfCells()); types->SetName(COLLISION_TYPE); _Output->GetCellData()->AddArray(types); reset_collision_types = true; } if (reset_collision_types) { types->FillComponent(0, static_cast<double>(NoCollision)); } if (_StoreIntersectionDetails && (_AdjacentIntersectionTest || _NonAdjacentIntersectionTest)) { _Intersections.resize(_Output->GetNumberOfCells()); } if (_StoreCollisionDetails && (_FrontfaceCollisionTest || _BackfaceCollisionTest)) { _Collisions.resize(_Output->GetNumberOfCells()); } } // ----------------------------------------------------------------------------- void SurfaceCollisions::Execute() { if (_Output->GetNumberOfCells() > 0) { FindCollisions::Run(this, _StoreIntersectionDetails ? &_Intersections : nullptr, _StoreCollisionDetails ? &_Collisions : nullptr); } } // ----------------------------------------------------------------------------- bool SurfaceCollisions::FoundIntersections() const { for (vtkIdType cellId = 0; cellId < _Output->GetNumberOfCells(); ++cellId) { if (IsIntersection(GetCollisionType(cellId))) return true; } return false; } // ----------------------------------------------------------------------------- bool SurfaceCollisions::FoundCollisions() const { for (vtkIdType cellId = 0; cellId < _Output->GetNumberOfCells(); ++cellId) { if (IsCollision(GetCollisionType(cellId))) return true; } return false; } } // namespace mirtk
39.727412
130
0.573587
lisurui6
76ba78818bce81f78b28ff925d2246870e8539c3
336
cc
C++
src/value/number_value.cc
scouter-project/scouter-cxx-lib
cf5971bd6dfd47e07fb7152ffbbaf95b69f53797
[ "Apache-2.0" ]
null
null
null
src/value/number_value.cc
scouter-project/scouter-cxx-lib
cf5971bd6dfd47e07fb7152ffbbaf95b69f53797
[ "Apache-2.0" ]
null
null
null
src/value/number_value.cc
scouter-project/scouter-cxx-lib
cf5971bd6dfd47e07fb7152ffbbaf95b69f53797
[ "Apache-2.0" ]
null
null
null
/* * number_value.cc * * Created on: 2015. 5. 11. * Author: windfree */ #include "value/number_value.h" namespace scouter { number_value::number_value() { // TODO Auto-generated constructor stub } number_value::~number_value() { // TODO Auto-generated destructor stub } } /* namespace scouter */
15.272727
41
0.630952
scouter-project
76bb2431e419143dc82acfe5b01f13ac38400962
397
cpp
C++
anagram_checks/solution.cpp
kasyap1234/codingproblems
7368222c5fb67b4796410597f68401654878fee0
[ "MIT" ]
1
2021-04-15T16:09:52.000Z
2021-04-15T16:09:52.000Z
anagram_checks/solution.cpp
kasyap1234/codingproblems
7368222c5fb67b4796410597f68401654878fee0
[ "MIT" ]
null
null
null
anagram_checks/solution.cpp
kasyap1234/codingproblems
7368222c5fb67b4796410597f68401654878fee0
[ "MIT" ]
null
null
null
bool solve(string s0, string s1) { if(s0.length()!=s1.length()){ return false; } unordered_map<char,int>mp1; unordered_map<char,int>mp2; for(int i=0;i<s0.length();i++){ mp1[s0[i]]++; } for(int i=0;i<s1.length();i++){ mp2[s1[i]]++; } if(mp1==mp2){ return true; } else{ return false; } }
17.26087
35
0.455919
kasyap1234
76bc8541fdab340404c8957ff292fec175c6d853
163
cpp
C++
src/common.cpp
sdadia/deep-learning-and-optimization
b44be79de116e2d4b203452a161641519f18f580
[ "MIT" ]
1
2018-10-02T15:29:14.000Z
2018-10-02T15:29:14.000Z
src/common.cpp
sdadia/deep-learning-and-optimization
b44be79de116e2d4b203452a161641519f18f580
[ "MIT" ]
null
null
null
src/common.cpp
sdadia/deep-learning-and-optimization
b44be79de116e2d4b203452a161641519f18f580
[ "MIT" ]
null
null
null
#include "common.hpp" #include <xtensor/xarray.hpp> #include <xtensor/xio.hpp> #include <xtensor/xtensor.hpp> #include <glog/logging.h> // for check macro
20.375
50
0.705521
sdadia
76be6d95a394ee5b6cfde07d2c60451e0870e7f8
2,128
cpp
C++
Starfarm/src/Entity/Player/PlayerBehaviour.cpp
fossabot/Starfarm
2d03fcdd2fa59f6061d523f69f2653134c9d0c64
[ "MIT" ]
null
null
null
Starfarm/src/Entity/Player/PlayerBehaviour.cpp
fossabot/Starfarm
2d03fcdd2fa59f6061d523f69f2653134c9d0c64
[ "MIT" ]
2
2019-04-17T15:22:46.000Z
2019-05-06T10:13:08.000Z
Starfarm/src/Entity/Player/PlayerBehaviour.cpp
fossabot/Starfarm
2d03fcdd2fa59f6061d523f69f2653134c9d0c64
[ "MIT" ]
2
2019-04-19T08:23:13.000Z
2019-05-06T10:17:52.000Z
// // Created by Tiphaine on 19/04/2019. // #include <cmath> #include <SFML/Graphics.hpp> #include <EntityManager.hpp> #include "PlayerBehaviour.hpp" #include "../GameObject.hpp" #include "../../Component/TransformComponent.hpp" #include "../../Component/SpriteComponent.hpp" #include "../Missile/Missile.hpp" namespace game { PlayerBehaviour::PlayerBehaviour(GameObject *gameObject) : MonoBehaviourComponent(gameObject) { } void PlayerBehaviour::update() { upFlag = sf::Keyboard::isKeyPressed(sf::Keyboard::Up); downFlag = sf::Keyboard::isKeyPressed(sf::Keyboard::Down); leftFlag = sf::Keyboard::isKeyPressed(sf::Keyboard::Left); rightFlag = sf::Keyboard::isKeyPressed(sf::Keyboard::Right); if (leftFlag) { _transform->move(-_speed, 0); } if (rightFlag) { _transform->move(_speed, 0); } if (upFlag) { _transform->move(0, -_speed); } if (downFlag) { _transform->move(0, _speed); } _transform->setRotations(0, 0, getAngleMouse()); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) { auto &missile = ecs::EntityManager::createEntity<Missile>(); missile._transform->setPositions(_transform->getPositions()); missile._transform->setRotations(_transform->getRotations()); } } float PlayerBehaviour::getAngleMouse() { auto mousePosition = sf::Mouse::getPosition(); auto position = _transform->getPositions(); auto angle = atan2( mousePosition.y - position.y, mousePosition.x - position.x ); float dx = position.x - mousePosition.x; float dy = position.y - mousePosition.y; return atan2(dy, dx) * RAD_TO_DEG; } void PlayerBehaviour::awake() { _transform->linkToRenderer (_gameObject->getComponent<SpriteComponent>()); _transform->setPositions(250, 250); } }
29.555556
79
0.576128
fossabot
76bf34c486ee92c78bf855f06a705c386d700b6e
202
cpp
C++
application/src/main.cpp
EgorSidorov/EasySiteCreator
100203b49386d6905a6e9456c9f2b7644f7f6ff0
[ "Apache-2.0" ]
1
2019-01-23T18:34:33.000Z
2019-01-23T18:34:33.000Z
application/src/main.cpp
EgorSidorov/EasySiteCreator
100203b49386d6905a6e9456c9f2b7644f7f6ff0
[ "Apache-2.0" ]
null
null
null
application/src/main.cpp
EgorSidorov/EasySiteCreator
100203b49386d6905a6e9456c9f2b7644f7f6ff0
[ "Apache-2.0" ]
null
null
null
#include <QApplication> #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication *app=new QApplication(argc,argv); MainWindow window(app); window.show(); app->exec(); }
16.833333
50
0.658416
EgorSidorov
76c93f51cbe86587f1467e4b4da18f7e80e39978
1,633
hpp
C++
AVLWordTree.hpp
SinaRaoufi/AVLWordTree
87e18951175b9cf93fa9d2323e8df52de2e3c2ab
[ "MIT" ]
null
null
null
AVLWordTree.hpp
SinaRaoufi/AVLWordTree
87e18951175b9cf93fa9d2323e8df52de2e3c2ab
[ "MIT" ]
null
null
null
AVLWordTree.hpp
SinaRaoufi/AVLWordTree
87e18951175b9cf93fa9d2323e8df52de2e3c2ab
[ "MIT" ]
null
null
null
#ifndef AVL_WORD_TREE_IG #define AVL_WORD_TREE_IG #include <string> #include <vector> class AVLNode { public: explicit AVLNode(const std::string &); void setValue(const std::string &); std::string getValue() const; void setHeight(int); int getHeight() const; void setRightChild(AVLNode *); void setLeftChild(AVLNode *); AVLNode *getRightChild() const; AVLNode *getLeftChild() const; private: std::string value; int height; AVLNode *rightChild; AVLNode *leftChild; }; class AVLWordTree { public: void insert(std::string); bool search(const std::string &) const; void remove(const std::string &); std::vector<std::string> start_with(const char &) const; std::vector<std::string> end_with(const char &) const; std::vector<std::string> contains(const std::string &) const; void traversePreOrder() const; void traverseInOrder() const; void traversePostOrder() const; void traverseLevelOrder() const; bool isEmpty() const; void clear(); ~AVLWordTree(); private: AVLNode *root = nullptr; AVLNode *insert(AVLNode *, std::string); AVLNode *remove(AVLNode *, const std::string &); AVLNode *minNode(AVLNode *); int compareTwoString(const std::string &, const std::string &) const; void traversePreOrder(AVLNode *) const; void traverseInOrder(AVLNode *) const; void traversePostOrder(AVLNode *) const; int heightOfAVLNode(AVLNode *) const; int balanceFactor(AVLNode *) const; AVLNode *balance(AVLNode *); AVLNode *rightRotation(AVLNode *); AVLNode *leftRotation(AVLNode *); }; #endif
27.216667
73
0.679731
SinaRaoufi
76caf89b9574be170f7fa9d2acaf3db9a0213ef2
10,283
cpp
C++
packages/Search/test/tstBoostGeometryAdapters.cpp
dalg24/DataTransferKit
35c5943d8f2f516b1da5f4004cbd05d476a8744e
[ "BSD-3-Clause" ]
null
null
null
packages/Search/test/tstBoostGeometryAdapters.cpp
dalg24/DataTransferKit
35c5943d8f2f516b1da5f4004cbd05d476a8744e
[ "BSD-3-Clause" ]
4
2017-03-27T12:17:42.000Z
2018-12-04T19:44:44.000Z
packages/Search/test/tstBoostGeometryAdapters.cpp
dalg24/DataTransferKit
35c5943d8f2f516b1da5f4004cbd05d476a8744e
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** * Copyright (c) 2012-2019 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit 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 <DTK_DetailsAlgorithms.hpp> #include <Teuchos_UnitTestHarness.hpp> #include "DTK_BoostGeometryAdapters.hpp" namespace bg = boost::geometry; namespace dtk = DataTransferKit::Details; // Conveniently importing Point and Box in DataTransferKit::Details:: namespace // and declaring type aliases within boost::geometry:: so that we are able to // just use dtk:: and bg:: to specify what geometry or algorithm we mean. namespace DataTransferKit { namespace Details { using DataTransferKit::Box; using DataTransferKit::Point; } // namespace Details } // namespace DataTransferKit namespace boost { namespace geometry { using Point = model::point<double, 3, cs::cartesian>; using Box = model::box<Point>; } // namespace geometry } // namespace boost TEUCHOS_UNIT_TEST( BoostGeometryAdapters, equals ) { dtk::Point point = {{1., 2., 3.}}; TEST_ASSERT( dtk::equals( point, {{1., 2., 3.}} ) ); TEST_ASSERT( !dtk::equals( point, {{0., 0., 0.}} ) ); TEST_ASSERT( bg::equals( point, bg::make<dtk::Point>( 1., 2., 3. ) ) ); TEST_ASSERT( !bg::equals( point, bg::make<dtk::Point>( 4., 5., 6. ) ) ); TEST_ASSERT( bg::equals( point, bg::make<bg::Point>( 1., 2., 3. ) ) ); TEST_ASSERT( !bg::equals( point, bg::make<bg::Point>( 0., 0., 0. ) ) ); dtk::Box box = {{{1., 2., 3.}}, {{4., 5., 6.}}}; TEST_ASSERT( dtk::equals( box, {{{1., 2., 3.}}, {{4., 5., 6.}}} ) ); TEST_ASSERT( !dtk::equals( box, {{{0., 0., 0.}}, {{1., 1., 1.}}} ) ); TEST_ASSERT( bg::equals( box, dtk::Box{{{1., 2., 3.}}, {{4., 5., 6.}}} ) ); TEST_ASSERT( !bg::equals( box, dtk::Box{{{0., 0., 0.}}, {{1., 1., 1.}}} ) ); TEST_ASSERT( bg::equals( box, bg::Box( bg::make<bg::Point>( 1., 2., 3. ), bg::make<bg::Point>( 4., 5., 6. ) ) ) ); TEST_ASSERT( !bg::equals( box, bg::Box( bg::make<bg::Point>( 0., 0., 0. ), bg::make<bg::Point>( 1., 1., 1. ) ) ) ); // Now just for fun compare the DTK box to a Boost.Geometry box composed of // DTK points. TEST_ASSERT( bg::equals( box, bg::model::box<dtk::Point>( {{1., 2., 3.}}, {{4., 5., 6.}} ) ) ); TEST_ASSERT( !bg::equals( box, bg::model::box<dtk::Point>( {{0., 0., 0.}}, {{0., 0., 0.}} ) ) ); } TEUCHOS_UNIT_TEST( BoostGeometryAdapters, distance ) { // NOTE unsure if should test for floating point equality here dtk::Point a = {{0., 0., 0.}}; dtk::Point b = {{0., 1., 0.}}; TEST_EQUALITY( dtk::distance( a, b ), 1. ); TEST_EQUALITY( bg::distance( a, b ), 1. ); std::tie( a, b ) = std::make_pair<dtk::Point, dtk::Point>( {{0., 0., 0.}}, {{1., 1., 1.}} ); TEST_EQUALITY( dtk::distance( a, b ), std::sqrt( 3. ) ); TEST_EQUALITY( bg::distance( a, b ), std::sqrt( 3. ) ); TEST_EQUALITY( dtk::distance( a, a ), 0. ); TEST_EQUALITY( bg::distance( a, a ), 0. ); dtk::Box unit_box = {{{0., 0., 0.}}, {{1., 1., 1.}}}; dtk::Point p = {{.5, .5, .5}}; // NOTE DTK has no overload distance( Box, Point ) TEST_EQUALITY( dtk::distance( p, unit_box ), 0. ); // TEST_EQUALITY( dtk::distance( unit_box, p ), 0. ); TEST_EQUALITY( bg::distance( p, unit_box ), 0. ); TEST_EQUALITY( bg::distance( unit_box, p ), 0. ); p = {{-1., -1., -1.}}; TEST_EQUALITY( dtk::distance( p, unit_box ), std::sqrt( 3. ) ); TEST_EQUALITY( bg::distance( p, unit_box ), std::sqrt( 3. ) ); p = {{-1., .5, -1.}}; TEST_EQUALITY( dtk::distance( p, unit_box ), std::sqrt( 2. ) ); TEST_EQUALITY( bg::distance( p, unit_box ), std::sqrt( 2. ) ); p = {{-1., .5, .5}}; TEST_EQUALITY( dtk::distance( p, unit_box ), 1. ); TEST_EQUALITY( bg::distance( p, unit_box ), 1. ); } TEUCHOS_UNIT_TEST( BoostGeometryAdapters, expand ) { using dtk::equals; dtk::Box box; // NOTE even though not considered valid, default constructed DTK box can be // expanded using Boost.Geometry algorithm. TEST_ASSERT( !bg::is_valid( box ) ); bg::expand( box, dtk::Point{{0., 0., 0.}} ); dtk::expand( box, {{1., 1., 1.}} ); TEST_ASSERT( equals( box, {{{0., 0., 0.}}, {{1., 1., 1.}}} ) ); bg::expand( box, dtk::Box{{{1., 2., 3.}}, {{4., 5., 6.}}} ); dtk::expand( box, {{{-1., -2., -3.}}, {{0., 0., 0.}}} ); TEST_ASSERT( equals( box, {{{-1., -2., -3.}}, {{4., 5., 6.}}} ) ); } TEUCHOS_UNIT_TEST( BoostGeometryAdapters, centroid ) { using dtk::equals; // For convenience define a function that returns the centroid. // Boost.Geometry defines both `void centroid(Geometry const & geometry, // Point &c )` and `Point return_centroid(Geometry const& geometry)` auto const dtkReturnCentroid = []( dtk::Box b ) { dtk::Point c; dtk::centroid( b, c ); return c; }; // Interestingly enough, even though for Boost.Geometry, the DTK default // constructed "empty" box is not valid, it will still calculate its // centroid. Admittedly, the result (centroid at origin) is garbage :) dtk::Box empty_box = {}; TEST_ASSERT( !bg::is_valid( empty_box ) ); TEST_ASSERT( equals( bg::return_centroid<dtk::Point>( empty_box ), {{0., 0., 0.}} ) ); TEST_ASSERT( equals( dtkReturnCentroid( empty_box ), {{0., 0., 0.}} ) ); dtk::Box unit_box = {{{0., 0., 0.}}, {{1., 1., 1.}}}; TEST_ASSERT( equals( bg::return_centroid<dtk::Point>( unit_box ), {{.5, .5, .5}} ) ); TEST_ASSERT( equals( dtkReturnCentroid( unit_box ), {{.5, .5, .5}} ) ); // NOTE DTK does not have an overload of centroid() for Point at the // moment. dtk::Point a_point = {{1., 2., 3.}}; TEST_ASSERT( equals( bg::return_centroid<dtk::Point>( a_point ), a_point ) ); // TEST_ASSERT( equals( dtk::centroid( // []( dtk::Point p ) { // dtk::Point c; // dtk::centroid( p, c ); // return c; // }( a_point ), // a_point ) ) ); } TEUCHOS_UNIT_TEST( BoostGeometryAdapters, is_valid ) { // NOTE "empty" box is considered as valid in DataTransferKit but it is // not according to Boost.Geometry dtk::Box empty_box = {}; TEST_ASSERT( dtk::isValid( empty_box ) ); std::string message; TEST_ASSERT( !bg::is_valid( empty_box, message ) ); TEST_EQUALITY( message, "Box has corners in wrong order" ); // Same issue with infinitesimal box around a point (here the origin) dtk::Box a_box = {{{0., 0., 0.}}, {{0., 0., 0.}}}; TEST_ASSERT( dtk::isValid( a_box ) ); TEST_ASSERT( !bg::is_valid( a_box, message ) ); TEST_EQUALITY( message, "Geometry has wrong topological dimension" ); dtk::Box unit_box = {{{0., 0., 0.}}, {{1., 1., 1.}}}; TEST_ASSERT( dtk::isValid( unit_box ) ); TEST_ASSERT( bg::is_valid( unit_box ) ); dtk::Box invalid_box = {{{1., 2., 3.}}, {{4., NAN, 6.}}}; TEST_ASSERT( !dtk::isValid( invalid_box ) ); TEST_ASSERT( !bg::is_valid( invalid_box, message ) ); TEST_EQUALITY( message, "Geometry has point(s) with invalid coordinate(s)" ); dtk::Point a_point = {{1., 2., 3.}}; TEST_ASSERT( dtk::isValid( a_point ) ); TEST_ASSERT( bg::is_valid( a_point ) ); auto const infty = std::numeric_limits<double>::infinity(); dtk::Point invalid_point = {{infty, 1.41, 3.14}}; TEST_ASSERT( !dtk::isValid( invalid_point ) ); TEST_ASSERT( !bg::is_valid( invalid_point, message ) ); TEST_EQUALITY( message, "Geometry has point(s) with invalid coordinate(s)" ); // Also Boost.Geometry has a is_empty() algorithm but it has a different // meaning, it checks whether a geometry is an empty set and always returns // false for a point or a box. TEST_ASSERT( !bg::is_empty( empty_box ) ); TEST_ASSERT( !bg::is_empty( a_box ) ); TEST_ASSERT( !bg::is_empty( unit_box ) ); } TEUCHOS_UNIT_TEST( BoostGeometryAdapters, intersects ) { dtk::Box const unit_box = {{{0., 0., 0.}}, {{1., 1., 1.}}}; // self-intersection TEST_ASSERT( dtk::intersects( unit_box, unit_box ) ); TEST_ASSERT( bg::intersects( unit_box, unit_box ) ); // share a corner dtk::Box other_box = {{{1., 1., 1.}}, {{2., 2., 2.}}}; TEST_ASSERT( dtk::intersects( unit_box, other_box ) ); TEST_ASSERT( bg::intersects( unit_box, other_box ) ); // share an edge other_box = {{{1., 0., 1.}}, {{2., 1., 2.}}}; TEST_ASSERT( dtk::intersects( unit_box, other_box ) ); TEST_ASSERT( bg::intersects( unit_box, other_box ) ); // share a face other_box = {{{0., -1., 0.}}, {{1., 0., 1.}}}; TEST_ASSERT( dtk::intersects( unit_box, other_box ) ); TEST_ASSERT( bg::intersects( unit_box, other_box ) ); // contains the other box other_box = {{{.3, .3, .3}}, {{.6, .6, .6}}}; TEST_ASSERT( dtk::intersects( unit_box, other_box ) ); TEST_ASSERT( bg::intersects( unit_box, other_box ) ); // within the other box other_box = {{{-1., -1., -1.}}, {{2., 2., 2.}}}; TEST_ASSERT( dtk::intersects( unit_box, other_box ) ); TEST_ASSERT( bg::intersects( unit_box, other_box ) ); // overlapping other_box = {{{.5, .5, .5}}, {{2., 2., 2.}}}; TEST_ASSERT( dtk::intersects( unit_box, other_box ) ); TEST_ASSERT( bg::intersects( unit_box, other_box ) ); // disjoint other_box = {{{1., 2., 3.}}, {{4., 5., 6.}}}; TEST_ASSERT( !dtk::intersects( unit_box, other_box ) ); TEST_ASSERT( !bg::intersects( unit_box, other_box ) ); }
41.297189
80
0.550715
dalg24
76ccbf5bfac42b9745d142340f704e261e1b6276
119
cpp
C++
server/instance.cpp
irl-game/irl
ba507a93371ab172b705c1ede8cd062123fc96f5
[ "MIT" ]
null
null
null
server/instance.cpp
irl-game/irl
ba507a93371ab172b705c1ede8cd062123fc96f5
[ "MIT" ]
null
null
null
server/instance.cpp
irl-game/irl
ba507a93371ab172b705c1ede8cd062123fc96f5
[ "MIT" ]
null
null
null
#include "instance.hpp" Instance::Instance() : SimServer(static_cast<Sched &>(*this), static_cast<World &>(*this)) {}
29.75
93
0.697479
irl-game
76ce217b72a19bb05df50f736e02594e4669b538
2,493
cpp
C++
libs/server/server_base.cpp
caodhuan/CHServer
823c4a006528a3aa1c88575c499eecda45d9022d
[ "Apache-2.0" ]
6
2017-11-16T06:12:20.000Z
2021-02-06T06:58:20.000Z
libs/server/server_base.cpp
caodhuan/CHServer
823c4a006528a3aa1c88575c499eecda45d9022d
[ "Apache-2.0" ]
null
null
null
libs/server/server_base.cpp
caodhuan/CHServer
823c4a006528a3aa1c88575c499eecda45d9022d
[ "Apache-2.0" ]
null
null
null
#include "server_base.h" #include "event_dispatcher.h" #include "session.h" #include "log.h" #include "socket_tcp.h" #include "uv.h" #include "timer_factory.h" #include "resource _manager.h" #include "config.h" namespace CHServer { template<> ServerBase* SingletonInheritable<ServerBase>::m_Instance = 0; ServerBase::ServerBase() : m_dispatcher(NULL) , m_Server(NULL) { } ServerBase::~ServerBase() { } bool ServerBase::Initilize(const char* path, const char* tableName) { if (!BeforeInitilize()) { return false; } if (m_dispatcher) { CHERRORLOG("reinitilzed"); return false; } // 初始化脚本的搜索路径之类的 if (!ResourceManager::Instance()->Initialize(path, tableName)) { CHERRORLOG("resource initialize failed!"); return false; } Config* config = ResourceManager::Instance()->GetConfig(); std::string logPath, logFileName; if (config && config->ReadString("sLogPath", logPath) && config->ReadString("sLogFileName", logFileName)) { CHLog::Instance()->InitLog(logPath.c_str(), logFileName.c_str()); } else { CHERRORLOG("log initialize failed!"); return false; } m_dispatcher = new EventDispatcher(); TimerFactory::Instance()->InitTimerFactory(m_dispatcher); m_Server = new SocketTCP(m_dispatcher); m_Server->SetCallback(nullptr, [&] { SocketTCP* tcpClient = m_Server->Accept(); Session* session = CreateSession(tcpClient); CHDEBUGLOG("new client connected %s:%d", tcpClient->GetIP().c_str(), tcpClient->GetPort()); }, [&] { // 这里目前没搞清楚为啥delete后,会造成this变量变得不可访问。 SocketBase* tmp = m_Server; m_Server = nullptr; CHWARNINGLOG("before delete %ld", this); delete tmp; CHWARNINGLOG("after delete %ld", this); }); int32_t internalPort; std::string internalIP; if (!config->ReadInt("nInternalPort", internalPort)) { CHERRORLOG("read internal port failed!"); return false; } if (!config->ReadString("sInternalIP", internalIP)) { CHERRORLOG("read internal ip failed!"); return false; } std::vector<std::string> whiteList; if (!config->ReadVector("sWhiteList", whiteList)) { CHERRORLOG("read white list failed!"); return false; } m_Server->Listen(internalIP.c_str(), internalPort); return AfterInitilize(); } void ServerBase::Finalize() { BeforeFinalize(); if (m_dispatcher) { delete m_dispatcher; m_dispatcher = NULL; } AfterFinalize(); CHLog::Instance()->UninitLog(); } void ServerBase::Run() { m_dispatcher->Run(); } }
21.307692
109
0.680706
caodhuan
76d55a9f58257315c5914ab7967a59c03c78b85c
5,612
cc
C++
lesson4/compression.cc
Frzifus/hoema
c5f9ab6760f4a3f044c008b08e62eaab5760fb7b
[ "BSD-2-Clause" ]
null
null
null
lesson4/compression.cc
Frzifus/hoema
c5f9ab6760f4a3f044c008b08e62eaab5760fb7b
[ "BSD-2-Clause" ]
null
null
null
lesson4/compression.cc
Frzifus/hoema
c5f9ab6760f4a3f044c008b08e62eaab5760fb7b
[ "BSD-2-Clause" ]
null
null
null
// BSD 2-Clause License // // Copyright (c) 2016, frzifus // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <sys/stat.h> #include <cmath> #include <fstream> #include <iomanip> #include <iostream> #include <vector> #include "./compression.h" #define PI 3.1415926536 std::vector<Complex> Compression::transform(const std::vector<Complex> &vec, std::size_t N, bool back) { std::vector<Complex> n_vec; const double AS = back ? 1 : -1; for (std::size_t n = 0; n < N; n++) { Complex res; for (std::size_t k = 0; k < N; k++) { res += vec.at(k) * Complex((AS * 2 * PI * static_cast<double>(k) * static_cast<double>(n)) / static_cast<double>(N)); } res *= (1 / sqrt(static_cast<double>(N))); n_vec.push_back(res); } return n_vec; } void Compression::compressFile(const std::string &src, const std::string &dest) { std::vector<Complex> vec = Compression::readFile(src); std::vector<Complex> n_vec = Compression::transform(vec, vec.size()); Compression::writeFile(dest, n_vec, 0.1); } void Compression::decompressFile(const std::string &src, const std::string &dest) { std::vector<Complex> n_vec = Compression::readFile(src); std::vector<Complex> o_vec = Compression::transform(n_vec, n_vec.size(), DECOMPRESS); Compression::writeFile(dest, o_vec); } std::vector<Complex> Compression::readFile(const std::string &file) { std::size_t N, idx; double re, im; std::vector<Complex> value; std::ifstream fp; fp.open(file); if(!fp) { std::cout << "File not found." << std::endl; exit(1); } fp >> N; value.resize(N); while (!fp.eof()) { fp >> idx >> re >> im; value[idx] = Complex(re, im); } fp.close(); return value; } void Compression::writeFile(const std::string &file, const std::vector<Complex> &values, const double &epsilon) { std::ofstream fp; fp.open(file); fp << values.size() << std::endl; for (std::size_t i{}; i < values.size(); ++i) { if (values[i].length() > epsilon) fp << i << "\t" << values[i].Re() << "\t" << values[i].Im() << std::endl; } fp.close(); } long GetFileSize(std::string filename) { struct stat stat_buf; int rc = stat(filename.c_str(), &stat_buf); return rc == 0 ? stat_buf.st_size : -1; } double Compression::testCompression(const std::string &src, const double &start, const double &delta, const double &steps, const double &tolerance) { const std::string tmp = src + ".tmp"; std::cout << std::fixed; double best_epsilon = start; const long src_length = GetFileSize(src); std::vector<Complex> origData = Compression::readFile(src); for (double epsilon = start; epsilon < (start + delta * steps); epsilon += delta) { std::vector<Complex> comprData = Compression::transform(origData, origData.size()); Compression::writeFile(tmp, comprData, epsilon); comprData = Compression::readFile(tmp); const long dest_lenght = GetFileSize(tmp); std::vector<Complex> decomprData = Compression::transform(comprData, comprData.size(), DECOMPRESS); Compression::writeFile(tmp, decomprData); decomprData = Compression::readFile(tmp); double max_diff = 0; for (unsigned int i = 0; i < origData.size(); i++) { double diff = origData[i].Re() - decomprData[i].Re(); // std::cout << diff << std::endl; // abs() if (diff < 0) { diff -= 2 * diff; // * -1 trololol.... } if (diff > max_diff) max_diff = diff; } double compression = 100 - static_cast<double>(dest_lenght) / static_cast<double>(src_length) * 100; std::cout << "Max deviation for ε = " << std::setprecision(2) << epsilon << ": " << std::setprecision(5) << max_diff << "\tCompression Rate: " << std::setprecision(2) << compression << "%" << (max_diff < tolerance ? "\t OK" : "\tFAIL") << std::endl; if (max_diff < tolerance) best_epsilon = epsilon; } remove(tmp.c_str()); return best_epsilon; }
34.219512
80
0.619922
Frzifus
76d8f508e50a3ea1a907ea0847bd10b4754c935d
650
cpp
C++
src/Utilization.cpp
mansonjones/CppND-System-Monitor
269f9e189234cf7479f9eb1652af5600554cc017
[ "MIT" ]
null
null
null
src/Utilization.cpp
mansonjones/CppND-System-Monitor
269f9e189234cf7479f9eb1652af5600554cc017
[ "MIT" ]
null
null
null
src/Utilization.cpp
mansonjones/CppND-System-Monitor
269f9e189234cf7479f9eb1652af5600554cc017
[ "MIT" ]
null
null
null
#include "Utilization.h" #include "linux_parser.h" #include <vector> #include <thread> #include <chrono> long Utilization::Jiffies() const { return LinuxParser::Jiffies(); } long Utilization::IdleJiffies() const { return LinuxParser::IdleJiffies(); } void Utilization::setCachedActiveJiffies(long activeJiffies) { cached_active_jiffies_ = activeJiffies; } long Utilization::getCachedActiveJiffies() const { return cached_active_jiffies_; } void Utilization::setCachedIdleJiffies(long idleJiffies) { cached_idle_jiffies_ = idleJiffies; } long Utilization::getCachedIdleJiffies() const { return cached_idle_jiffies_; }
20.967742
62
0.76
mansonjones
76d9734bce727a9fcf5d1b07749d242516a83d38
651
cpp
C++
Dynamic Programming/best-time-to-buy-sell-stock-121.cpp
devangi2000/Data-Structures-Algorithms-Handbook
ce0f00de89af5da7f986e65089402dc6908a09b5
[ "MIT" ]
38
2021-10-14T09:36:53.000Z
2022-01-27T02:36:19.000Z
Dynamic Programming/best-time-to-buy-sell-stock-121.cpp
devangi2000/Data-Structures-Algorithms-Handbook
ce0f00de89af5da7f986e65089402dc6908a09b5
[ "MIT" ]
null
null
null
Dynamic Programming/best-time-to-buy-sell-stock-121.cpp
devangi2000/Data-Structures-Algorithms-Handbook
ce0f00de89af5da7f986e65089402dc6908a09b5
[ "MIT" ]
4
2021-12-06T15:47:12.000Z
2022-02-04T04:25:00.000Z
// You are given an array prices where prices[i] is the price of a given stock on the ith day. // You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. // Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. class Solution { public: int maxProfit(vector<int>& prices) { int profit = 0, curr = INT_MAX; for(int i=0; i<prices.size(); i++){ curr = min(curr, prices[i]); profit = max(profit, prices[i]-curr); } return profit; } };
36.166667
141
0.631336
devangi2000
76db8866e4ef3b62abd03eb7c6d2101f35333389
19,878
cpp
C++
src/UserMenu.cpp
gryffyn/USW20_P2
bfad201375a6388453b5b03633a12b5bba45c141
[ "MIT" ]
null
null
null
src/UserMenu.cpp
gryffyn/USW20_P2
bfad201375a6388453b5b03633a12b5bba45c141
[ "MIT" ]
null
null
null
src/UserMenu.cpp
gryffyn/USW20_P2
bfad201375a6388453b5b03633a12b5bba45c141
[ "MIT" ]
null
null
null
// // Created by gryffyn on 10/03/2020. // #include "UserMenu.hpp" #include <mhash.h> #include <Admin.hpp> #include <DataTools.hpp> #include <Lecturer.hpp> #include <Student.hpp> #include <User.hpp> #include <boost/algorithm/string.hpp> #include <ios> #include <iostream> #include <limits> #include <mariadb++/connection.hpp> #include <sstream> #include "Announcement.hpp" #include "Key.hpp" #include "ObjStore.hpp" namespace Color { enum Code { // enum of terminal ASCII codes FG_RED = 31, FG_GREEN = 32, FG_BLUE = 34, FG_DEFAULT = 39, ST_INVIS = 8, ST_DEF = 0, ST_BOLD = 1, ST_UNDER = 4 }; // sets text style to given code std::string startval(Code code) { std::stringstream ss; ss << "\033[" << code << "m"; return ss.str(); } // resets text style to normal std::string endval(Code code) { std::string str; if (code < 30) { str = "\033[0m"; } else { str = "\033[39m"; } return str; } // sets input to whatever code std::string setval(Code code, const std::string& input) { std::stringstream ss; ss << "\033[" << code << "m" << input << endval(code); return ss.str(); } std::string make_box(std::string msg) { std::stringstream box_u, box_l, box_m, box_complete; box_u << "┏━"; box_m << "┃ "; box_l << "┗━"; for (int i = 0; i < msg.length(); i++) { box_u << "━"; box_l << "━"; } box_u << "━┓"; box_m << setval(ST_BOLD, msg) << " ┃"; box_l << "━┛"; box_complete << box_u.str() << "\n" << box_m.str() << "\n" << box_l.str() << "\n"; return box_complete.str(); } } // namespace Color using namespace Color; // clears console void clr() { std::cout << "\033[2J\033[1;1H"; } // removes all characters that aren't alphanum std::string sanitize_username(std::string input) { std::stringstream output; for (char c : input) { if (isalnum(c)) { output << c; } } return output.str(); } namespace Login { // checks if user exists and if it does, returns true and the user_id. If not, returns false and -1 std::pair<bool, int> check_user(ObjStore& db, const std::string& username) { std::pair<bool, int> retval; retval.first = false; try { mariadb::result_set_ref user_result = db.select("SELECT user_id, user FROM Users WHERE user = '" + username + "';"); user_result->next(); if (username == user_result->get_string(1)) { retval.first = true; retval.second = user_result->get_unsigned16(0); } } catch (std::out_of_range& e) { retval.second = -1; } return retval; } // checks password bool login(ObjStore& db, const int& user_id, std::string pass) { bool valid = false; mariadb::result_set_ref pass_result; std::stringstream sql; sql << "SELECT user_id, pwhash FROM Users WHERE user_id = " << user_id << ";"; try { pass_result = db.select(sql.str()); pass_result->next(); std::string pwhash = pass_result->get_string(1); valid = Key::verify_key(pwhash, pass); } catch (std::out_of_range& e) { } return valid; } // gets name based on user_id std::string get_name(ObjStore& db, const int& user_id) { std::stringstream sql; sql << "SELECT user_id, name FROM Users WHERE user_id = " << user_id << ";"; mariadb::result_set_ref result = db.select(sql.str()); result->next(); return result->get_string(1); } std::pair<std::string, int> login_menu(ObjStore& db) { clr(); std::string username; int user_id = 0; bool user_success = false, pass_success = false; std::string password; std::cout << make_box("Welcome to the USW Cyber Lab."); while (!user_success) { std::cout << setval(ST_BOLD, "Username: "); std::getline(std::cin, username); std::string san_uname = sanitize_username(username); std::pair<bool, int> check = check_user(db, san_uname); if (!check.first) { std::cout << std::endl << setval(FG_RED, "🗙") << " Username not found. Please try again.\n"; } else { user_id = check.second; user_success = true; while (!pass_success) { std::cout << setval(ST_BOLD, "Password: "); std::getline(std::cin, password); if (!login(db, user_id, password)) { std::cout << std::endl; std::cout << setval(FG_RED, "🗙") << " Password incorrect. Please try again.\n"; } else { pass_success = true; std::string name = get_name(db, user_id); std::cout << "Logging in....." << std::endl; // sleep(1); clr(); std::cout << "Welcome, " << name.substr(0, name.find(' ')) << "."; } } } } std::pair<std::string, int> final; final.first = password; final.second = user_id; return final; } } // namespace Login namespace UserMenu { std::string getstring(std::string output) { std::string str; std::cout << output; std::getline(std::cin, str); return str; } // returns if row exists or not bool exists_row(ObjStore& db, std::string sql) { mariadb::result_set_ref result = db.select(sql); if (result->next()) { return true; } else { return false; } } // checks the user type by looking in what table(s) the user_id exists, returns the types std::vector<std::string> check_user_type(ObjStore& db, const int& user_id) { std::vector<std::string> user_types{"Student", "Lecturer", "Admin"}, output; std::stringstream sql; for (std::string type : user_types) { sql << "SELECT * from " << type << "s WHERE user_id = " << user_id << ";"; if (exists_row(db, sql.str())) { output.emplace_back(type); } std::stringstream().swap(sql); } return output; } std::string set_user_type(const int& choice) { if (choice == 1) { return "Student"; } else if (choice == 2) { return "Lecturer"; } else if (choice == 3) { return "Admin"; } else { std::cout << "Invalid choice."; return ""; } } void create_user(ObjStore& db) { std::cout << make_box("Create User"); std::string username, name, password, typechoice; std::vector<int> typechoices; // get user info bool user_success = false; while (!user_success) { username = getstring(setval(ST_BOLD, "Username: ")); std::pair<bool, int> user_exists = Login::check_user(db, username); if (user_exists.first) { user_success = true; } else { std::cout << "Username has already been chosen. Please choose another username."; } } name = getstring(setval(ST_BOLD, "Name: ")); Key pwhash; bool pass_success{}; while (!pass_success) { try { pwhash.create_key(getstring(setval(ST_BOLD, "Password: "))); pass_success = true; } catch (Key::pass_exception& e) { std::cout << e.what(); } } std::cout << setval(ST_BOLD, "User type(s):\n") << "1. Student\n" << "2. Lecturer\n" << "3. Admin\n"; typechoice = getstring("Enter comma separated list of user types: "); for (char c : typechoice) { if (isdigit(c)) { typechoices.emplace_back(c - '0'); } } std::cout << "\nCreating user..."; for (int i : typechoices) { if (i == 1) { Student student(db, name, username, pwhash.get_key()); } else if (i == 2) { Lecturer lecturer(db, name, username, pwhash.get_key()); } else if (i == 3) { Admin admin(db, name, username, pwhash.get_key()); } } std::cout << "\nUser created."; } void list_users(ObjStore& db) { std::cout << make_box("User List"); std::cout << setval(ST_UNDER, setval(ST_BOLD, "Username")); std::cout << " " << setval(ST_BOLD, "-") << " "; std::cout << setval(ST_UNDER, setval(ST_BOLD, "Name")) << std::endl; mariadb::result_set_ref result = db.select("SELECT user, name FROM Users;"); while (result->next()) { std::cout<< result->get_string("user") << " - " << result->get_string("name") << std::endl; } } void delete_user(ObjStore& db) { std::cout << make_box("Delete User"); std::string username = getstring("Username: "); std::cout << "\nSelected username: " << username; std::string confirm = getstring("Are you sure you want to delete this user?\nYou can't undo this action. (y/N)"); if (!confirm.empty()) { boost::algorithm::to_lower(confirm); } if (confirm[0] == 'n' || confirm.empty()) { std::cout << setval(ST_BOLD, "NOT") << " deleting user \"" << username << "\"."; } else if (confirm[0] == 'y') { std::cout << "Deleting user \"" << username << "\"..."; db.execute("DELETE FROM Users WHERE user = '" + username + "';"); std::cout << std::endl << "User \"" << username << "\" deleted."; } } void show_data(ObjStore& db, const int& user_id, const std::string& user_type, std::string password) { std::stringstream sql; sql << "SELECT data FROM " << user_type << "s WHERE user_id = " << user_id << ";"; std::string sql_s(sql.str()); mariadb::result_set_ref result = db.select(sql.str()); result->next(); std::cout << make_box("Data"); std::string data = result->get_string(0); if (data.empty()) { std::cout << setval(FG_RED, "🗙") << "No data found."; } else { std::cout << DataTools::get_data_xor(db, user_id, user_type, std::move(password)); } } void edit_data(ObjStore& db, const int& user_id, const std::string& user_type, std::string password) { std::cout << make_box("Data"); std::stringstream sql; std::string data; std::string choice; int choice_i = 0; std::cout << setval(ST_BOLD, "1. ") << "Create data\n"; std::cout << setval(ST_BOLD, "2. ") << "Add to data\n"; std::cout << setval(ST_BOLD, "3. ") << "Go back\n"; std::cout << "\nSelect action: "; // std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); std::getline(std::cin, choice); choice_i = stoi(choice); if (choice_i == 1) { data = getstring("Input data: "); DataTools::save_data_xor(db, user_id, user_type, data, std::move(password)); } else if (choice_i == 2) { data = getstring("Data will be added to your existing data.\nInput data: "); std::getline(std::cin, data); std::string total_data = DataTools::get_data_xor(db, user_id, user_type, std::move(password)) + data; sql << "UPDATE " << user_type << "s SET data = '" << DataTools::return_data_xor(db, user_id, total_data, std::move(password)) << "' WHERE user_id = " << user_id << ";"; db.execute(sql.str()); } } bool back_or_exit() { std::cout << "\nGo back (9) or exit (0): "; char c; std::cin >> c; return (c == '9'); } void show_announcements(ObjStore& db, const int& user_id, std::string user_type) { std::cout << make_box("Announcements"); std::stringstream sql, sql2; std::string data; std::string choice; int choice_i = 0; std::cout << setval(ST_BOLD, "1. ") << "Show unread announcements\n"; std::cout << setval(ST_BOLD, "2. ") << "Show announcement by ID\n"; std::cout << setval(ST_BOLD, "3. ") << "Go back\n"; std::cout << "\nSelect action: "; // std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); std::getline(std::cin, choice); choice_i = stoi(choice); if (choice_i == 1) { clr(); std::cout << make_box("Announcements"); sql << "SELECT last_notif FROM " << user_type << "s WHERE user_id = " << user_id << ";"; mariadb::result_set_ref result = db.select(sql.str()); result->next(); mariadb::date_time last = result->get_date_time(0); sql2 << "SELECT * FROM Announcements WHERE ann_time >= '" << last << "';"; mariadb::result_set_ref result2 = db.select(sql2.str()); while (result2->next()) { std::stringstream time, sql3; sql3 << "SELECT name FROM Users WHERE user_id = " << result2->get_string("ann_author") << ";"; mariadb::result_set_ref result3 = db.select(sql3.str()); result3->next(); time << result2->get_date_time("ann_time"); std::cout << std::endl << setval(ST_BOLD, result2->get_string("ann_title")) << std::endl << result3->get_string("name") << std::endl << setval(ST_UNDER, time.str()) << std::endl << result->get_string("ann_text"); } std::stringstream newtime; newtime << "UPDATE " << user_type << "s SET last_notif = '" << mariadb::date_time::now_utc() << "' WHERE user_id = " << user_id << ";"; db.insert(newtime.str()); std::cout << std::endl << "\nPress enter to continue..."; std::cin.ignore(); } else if (choice_i == 2) { std::string ann_number = getstring("Enter announcement number: "); /* std::stringstream ss; for (char c : ann_number) { if (isdigit(c)) { ss << (c + '0'); } } */ int ann_id = stoi(ann_number); // Announcement ann(db); std::stringstream ss; ss << "SELECT * FROM Announcements WHERE ann_id = " << ann_id << ";"; try { mariadb::result_set_ref result = db.select(ss.str()); result->next(); clr(); std::stringstream sql3; sql3 << "SELECT name FROM Users WHERE user_id = " << result->get_string("ann_author") << ";"; mariadb::result_set_ref result3 = db.select(sql3.str()); result3->next(); std::cout << make_box("Announcement"); std::stringstream time2; time2 << result->get_date_time("ann_time"); std::cout << std::endl << setval(ST_BOLD, result->get_string("ann_title")) << std::endl << result3->get_string("name") << std::endl << setval(ST_UNDER, time2.str()) << std::endl << result->get_string("ann_text"); std::cout << std::endl << "\nPress enter to continue..."; std::cin.ignore(); } catch (std::out_of_range& e) { std::cout << std::endl << "No announcement found with that number."; std::cout << std::endl << "Press enter to continue..."; std::cin.ignore(); } } } void create_announcement(ObjStore& db, const int& user_id) { make_box("Create Announcement"); std::string title,text; title = getstring("Title: "); text = getstring("Text: "); Announcement ann(db, user_id, title, text); std::cout << std::endl << "Announcement created.\nPress enter to continue..."; std::cin.ignore(); } bool menu_admin(ObjStore& db, int& count, const int& user_id, std::string user_type) { std::string choice; int choice_i = 0; std::cout << setval(ST_BOLD, "1. ") << "List Users\n"; std::cout << setval(ST_BOLD, "2. ") << "Create User\n"; std::cout << setval(ST_BOLD, "3. ") << "Delete User\n"; std::cout << setval(ST_BOLD, "4. ") << "Show announcements\n"; std::cout << setval(ST_BOLD, "5. ") << "Create announcement\n"; std::cout << setval(ST_BOLD, "6. ") << "Exit\n"; std::cout << "\nSelect action: "; if (count != 0) { std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); } std::getline(std::cin, choice); choice_i = stoi(choice); if (choice_i == 1) { clr(); list_users(db); if (!back_or_exit()) { return true; } else { clr(); return false; } // exits, or clears the screen and shows menu again } else if (choice_i == 2) { clr(); create_user(db); if (!back_or_exit()) { return true; } else { clr(); return false; } } else if (choice_i == 3) { clr(); delete_user(db); if (!back_or_exit()) { return true; } else { clr(); return false; } } else if (choice_i == 4) { clr(); show_announcements(db, user_id, user_type); clr(); return false; } else if (choice_i == 5) { clr(); create_announcement(db, user_id); clr(); return false; } else { return true; } } bool menu_student(ObjStore& db, int& count, const int& user_id, const std::string& student, std::string password) { std::string choice; int choice_i = 0; std::cout << setval(ST_BOLD, "1. ") << "Show data\n"; std::cout << setval(ST_BOLD, "2. ") << "Set/edit data\n"; std::cout << setval(ST_BOLD, "3. ") << "Show announcements\n"; std::cout << setval(ST_BOLD, "4. ") << "Exit\n"; std::cout << "\nSelect action: "; if (count != 0) { std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); } std::getline(std::cin, choice); choice_i = stoi(choice); if (choice_i == 1) { clr(); show_data(db, user_id, student, password); if (!back_or_exit()) { return true; } else { clr(); return false;} } else if (choice_i == 2) { clr(); edit_data(db, user_id, student, password); if (!back_or_exit()) { return true; } else { clr(); return false; } } else if (choice_i == 3) { clr(); show_announcements(db, user_id, student); clr(); return false; } else { return true; } } bool menu_lecturer(ObjStore& db, int& count, const int& user_id, const std::string& lecturer, std::string password) { std::string choice; int choice_i = 0; std::cout << setval(ST_BOLD, "1. ") << "Show data\n"; std::cout << setval(ST_BOLD, "2. ") << "Set/edit data\n"; std::cout << setval(ST_BOLD, "3. ") << "Show announcements\n"; std::cout << setval(ST_BOLD, "4. ") << "Create announcement\n"; std::cout << setval(ST_BOLD, "5. ") << "Exit\n"; std::cout << "\nSelect action: "; if (count != 0) { std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); } std::getline(std::cin, choice); choice_i = stoi(choice); if (choice_i == 1) { clr(); show_data(db, user_id, lecturer, password); if (!back_or_exit()) { return true; } else { clr(); return false; } } else if (choice_i == 2) { clr(); edit_data(db, user_id, lecturer, password); if (!back_or_exit()) { return true; } else { clr(); return false; } } else if (choice_i == 3) { clr(); show_announcements(db, user_id, lecturer); clr(); return false; } else if (choice_i == 4) { clr(); create_announcement(db, user_id); clr(); return false; } else { return true; } } void show_menu(ObjStore& db, const int& user_id, std::string password) { std::vector<std::string> user_type = check_user_type(db, user_id); std::cout << std::endl << make_box("Menu Options:") << std::endl; bool exit = false; int count = 0; while (!exit) { if (std::find(user_type.begin(), user_type.end(), "Admin") != user_type.end()) { exit = menu_admin(db, count, user_id, "Admin"); } else if (std::find(user_type.begin(), user_type.end(), "Lecturer") != user_type.end()) { exit = menu_lecturer(db, count, user_id, "Lecturer", password); } else if (std::find(user_type.begin(), user_type.end(), "Student") != user_type.end()) { exit = menu_student(db, count, user_id, "Student", password); } ++count; } } } // namespace UserMenu
36.141818
127
0.558054
gryffyn
76de9b00dede0667b957bf2f899b7ced86658ac2
853
cc
C++
media/capture/video/linux/scoped_v4l2_device_fd.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
media/capture/video/linux/scoped_v4l2_device_fd.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
media/capture/video/linux/scoped_v4l2_device_fd.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2018 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 "media/capture/video/linux/scoped_v4l2_device_fd.h" namespace media { ScopedV4L2DeviceFD::ScopedV4L2DeviceFD(V4L2CaptureDevice* v4l2) : device_fd_(kInvalidId), v4l2_(v4l2) {} ScopedV4L2DeviceFD::ScopedV4L2DeviceFD(V4L2CaptureDevice* v4l2, int device_fd) : device_fd_(device_fd), v4l2_(v4l2) {} ScopedV4L2DeviceFD::~ScopedV4L2DeviceFD() { if (is_valid()) reset(); } int ScopedV4L2DeviceFD::get() const { return device_fd_; } void ScopedV4L2DeviceFD::reset(int fd /*= kInvalidId*/) { if (is_valid()) v4l2_->close(device_fd_); device_fd_ = fd; } bool ScopedV4L2DeviceFD::is_valid() const { return device_fd_ != kInvalidId; } } // namespace media
24.371429
78
0.736225
zealoussnow
76e4bf332ff7106217b8ccef74c531a75e8aa3fa
377
hh
C++
pipeline/include/hooya/pipeline/CountingSemaphore.hh
hooya-network/libhooya
bbc7b0f85b616bdbed99914023a45fe9a9adf2e9
[ "MIT" ]
1
2021-07-26T06:24:22.000Z
2021-07-26T06:24:22.000Z
pipeline/include/hooya/pipeline/CountingSemaphore.hh
hooya-network/libhooya
bbc7b0f85b616bdbed99914023a45fe9a9adf2e9
[ "MIT" ]
1
2021-08-05T03:45:52.000Z
2021-08-05T03:45:52.000Z
pipeline/include/hooya/pipeline/CountingSemaphore.hh
hooya-network/libhooya
bbc7b0f85b616bdbed99914023a45fe9a9adf2e9
[ "MIT" ]
null
null
null
#pragma once #include <cassert> #include <mutex> namespace hooya::pipeline { /** * A semaphore that counts how many times it has been raised */ class CountingSemaphore { public: CountingSemaphore(); /** * Increment the semaphore */ void Raise(); /** * Decrement the semaphore */ void Lower(); private: std::mutex semGuard; std::mutex sem; int count; }; }
13.464286
60
0.668435
hooya-network
76e64d1c519b3be8a71102594e35a23b1c6a7dec
10,279
hxx
C++
the/lib/common/errors.hxx
deni64k/the
c9451f03fe690d456bae89ac2d4a9303317dd8cd
[ "Apache-2.0" ]
null
null
null
the/lib/common/errors.hxx
deni64k/the
c9451f03fe690d456bae89ac2d4a9303317dd8cd
[ "Apache-2.0" ]
null
null
null
the/lib/common/errors.hxx
deni64k/the
c9451f03fe690d456bae89ac2d4a9303317dd8cd
[ "Apache-2.0" ]
null
null
null
#pragma once #include <variant> #include <utility> #include "common.hxx" // #define _GNU_SOURCE // #define try // #define catch(...) // #include <boost/stacktrace.hpp> // #undef _GNU_SOURCE // #undef try // #undef catch namespace the { struct Error { virtual ~Error(); virtual void What(std::ostream &os) const noexcept = 0; } __attribute__ ((packed)); std::ostream & operator << (std::ostream &, Error const &); struct RuntimeError: public Error { RuntimeError(char const *msg): message_(msg) {} RuntimeError(std::string const &msg): message_(msg) {} RuntimeError(std::string &&msg): message_(msg) {} virtual ~RuntimeError() = default; void What(std::ostream &os) const noexcept override { os << message_; } // virtual boost::stacktrace::stacktrace const & Where() const noexcept; protected: std::string message_; // boost::stacktrace::stacktrace stacktrace_; }; /* namespace details { template <typename T, bool = std::is_literal_type_v<T>> struct Uninitialized; template <typename T> struct Uninitialized<T, true> { using ValueType = T; template <typename ...Args> constexpr Unnitialized(InPlaceIndexT<0>, Args && ...args) : value_{std::forward<Args>(args)...} {} constexpr ValueType const & Get() const & { return value_; } constexpr ValueType & Get() & { return value_; } constexpr ValueType const && Get() const && { return std::move(value_); } constexpr ValueType && Get() && { return std::move(value_); } ValueType value_; }; template <typename T> struct Uninitialized<T, false> { using ValueType = T; template <typename ...Args> constexpr Unnitialized(InPlaceIndexT<0>, Args && ...args) { ::new (&value_) ValueType{std::forward<Args>(args)...}; } constexpr ValueType const & Get() const & { return *value_._M_ptr(); } constexpr ValueType & Get() & { return *value_._M_ptr(); } constexpr ValueType const && Get() const && { return std::move(*value_._M_ptr()); } constexpr ValueType && Get() && { return std::move(*value_._M_ptr()); } // TODO: Portable way? __gnu_cxx::__aligned_membuf<ValueType> value_; }; struct InPlaceT { explicit InPlaceT() = default; }; inline constexpr InPlaceT InPlace{}; template <typename T> struct InPlaceTypeT { explicit InPlaceTypeT() = default; }; template <typename T> inline constexpr InPlaceTypeT<T> InPlaceType{}; template <std::size_t Index> struct InPlaceIndexT { explicit InPlaceIndexT() = default; }; template <std::size_t Index> inline constexpr InPlaceIndexT<Index> InPlaceIndex{}; template <typename ...Ts> union VariadicUnion {}; template <typename T, typename ...Ts> union VariadicUnion<T, ...Ts> { constexpr VariadicUnion(): ts_{} {} template <typename ...Args> constexpr VariadicUnion(InPlaceIndexT<0>, Args && ...args) : t{InPlaceIndex<0, std::forward<Args>(args)...} {} template <std::size_t Index, typename ...Args> constexpr VariadicUnion(InPlaceIndexT<Index>, Args && ...args) : ts{InPlaceIndex<Index - 1>, std::forward<Args>(args)...} {} template <std::size_t I> constexpr T const & Get() const & { return ts.Get<I-1>(); } template <std::size_t I> constexpr T & Get() & { return ts.Get<I-1>(); } template <> constexpr T const & Get<0>() const & { return t.Get(); } template <> constexpr T & Get<0>() & { return t.Get(); } template <std::size_t I> constexpr T const && Get() const && { return std::move(ts.Get<I-1>()); } template <std::size_t I> constexpr T && Get() && { return std::move(ts.Get<I-1>()); } template <> constexpr T const && Get<0>() const && { return std::move(t.Get()); } template <> constexpr T && Get<0>() && { return std::move(t.Get()); } template <typename U> constexpr U const & Get() const & { return ts.Get<U>(); } template <typename U> constexpr U & Get() & { return ts.Get<U>(); } template <> constexpr T const & Get() const & { return t.Get(); } template <> constexpr T & Get() & { return t.Get(); } template <typename U> constexpr U const & Get() const & { return std::move(ts.Get<U>()); } template <typename U> constexpr U & Get() & { return std::move(ts.Get<U>()); } template <> constexpr T const & Get() const & { return std::move(t.Get()); } template <> constexpr T & Get() & { return std::move(t.Get()); } Uninitialized<T> t; VariadicUnion<Ts...> ts; }; template <typename T, typename ...Es> union FallibleStorage { friend struct Fallible<T, Es...>; using ValueType = T; using ErrorType = VariadicUnion<Es...>; FallibleStorage() {} ~FallibleStorage() {} void ConstructValue(ValueType const &value) { new (&value_) ValueType(value); } void ConstructValue(ValueType &&value) { new (&value_) ValueType(std::move(value)); } void DestructValue() { &value_.~ValueType(); } constexpr ValueType const & Value() const & { return value_; } ValueType & Value() & { return value_; } ValueType && Value() && { return std::move(value_); } void ConstructError(ErrorType const &error) { new (&error_) ErrorType(error); } void ConstructError(ErrorType &&error) { new (&error_) ErrorType(std::move(error)); } void DestructError() { &error_.~ErrorType(); } constexpr ErrorType const & Error() const { return error_; } ErrorType & Error() { return error_; } private: ValueType value_; ErrorType error_; }; template <typename E> union FallibleStorage<void, E> final { friend struct Fallible<void, E>; using ValueType = void; using ErrorType = E; FallibleStorage() {} ~FallibleStorage() {} void ConstructError(ErrorType const &error) { new (&error_) ErrorType(error); } void ConstructError(ErrorType &&error) { new (&error_) ErrorType(std::move(error)); } void DestructError() { &error_.~ErrorType(); } constexpr ErrorType const & Error() const { return error_; } ErrorType & Error() { return error_; } private: ErrorType error_; }; } */ template <typename T, typename ...Es> struct [[nodiscard]] FallibleBase final { using ValueType = T; using ErrorTypes = std::tuple<Es...>; using ErrorBaseType = Error; constexpr FallibleBase() noexcept: storage_{ValueType{}} {} // constexpr FallibleBase(FallibleBase const &) = delete; constexpr FallibleBase(FallibleBase const &other) noexcept: storage_{other.storage_} {} constexpr FallibleBase(FallibleBase &&other) noexcept: storage_{std::move(other.storage_)} {} constexpr FallibleBase(ValueType const &v) noexcept: storage_{v} {} constexpr FallibleBase(ValueType &&v) noexcept: storage_{std::forward<ValueType>(v)} {} template <typename U> constexpr FallibleBase(U &&u) noexcept requires (std::is_same<std::remove_cv_t<std::remove_reference_t<U>>, Es>::value || ...) : storage_{std::forward<U>(u)} {} operator bool () const { return std::holds_alternative<ValueType>(storage_); } ErrorBaseType const & Err() const & { return std::get<1>(storage_); } ErrorBaseType & Err() & { return std::get<1>(storage_); } ErrorBaseType const && Err() const && { return std::move(std::get<1>(storage_)); } ErrorBaseType && Err() && { return std::move(std::get<1>(storage_)); } ValueType * operator -> () { return &std::get<0>(storage_); } ValueType const * operator -> () const { return &std::get<0>(storage_); } ValueType & operator * () & { return std::get<0>(storage_); } ValueType const & operator * () const & { return std::get<0>(storage_); } // std::pair<ValueType *, ErrorType *> Lift() { // return std::make_pair(std::get_if<0>(this), std::get_if<1>(this)); // } // std::pair<ValueType const *, ErrorType *> Lift() const { // return std::make_pair(std::get_if<0>(this), std::get_if<1>(this)); // } // template <typename ...Ess> operator FallibleBase<std::monostate, Es...> () const & requires (!std::is_same<ValueType, std::monostate>::value) { using RetType = FallibleBase<std::monostate, Es...>; return std::visit([](auto const &arg) -> decltype(auto) { using Arg = std::decay_t<decltype(arg)>; if constexpr (std::is_same_v<Arg, ValueType>) { return RetType{}; } else { return RetType{arg}; } }, storage_); } // template <typename ...Ess> operator FallibleBase<std::monostate, Es...> () & requires (!std::is_same<ValueType, std::monostate>::value) { using RetType = FallibleBase<std::monostate, Es...>; return std::visit([](auto &arg) -> decltype(auto) { using Arg = std::decay_t<decltype(arg)>; if constexpr (std::is_same_v<Arg, ValueType>) { return RetType{}; } else { return RetType{arg}; } }, storage_); } // operator FallibleBase<std::monostate, Es...> && () && // requires (!std::is_same<T, std::monostate>::value) { // if (!*this) // return {std::move(*this)}; // return std::move(FallibleBase<std::monostate, Es...>{}); // } private: std::variant<ValueType, Es...> storage_; }; template <typename ...Es> struct [[nodiscard]] FallibleBase<std::monostate, Es...> final { using ErrorTypes = std::tuple<Es...>; using ErrorBaseType = Error; constexpr FallibleBase(): storage_{} {} // constexpr FallibleBase(FallibleBase const &) = delete; constexpr FallibleBase(FallibleBase const &other) noexcept: storage_{other.storage_} {} constexpr FallibleBase(FallibleBase &&other) noexcept: storage_{std::move(other.storage_)} {} template <typename U> constexpr FallibleBase(U &&u) noexcept requires (std::is_same<std::remove_cv_t<std::remove_reference_t<U>>, Es>::value || ...) : storage_{std::forward<U>(u)} {} operator bool () const { return std::holds_alternative<std::monostate>(storage_); } ErrorBaseType const & Err() const & { return std::get<1>(storage_); } ErrorBaseType & Err() & { return std::get<1>(storage_); } private: std::variant<std::monostate, Es...> storage_; }; template <typename Value = std::monostate, typename ...Errors> using Fallible = FallibleBase<Value, RuntimeError, Errors...>; // template <> explicit Fallible() -> Fallible<void, Error>; // template <typename T> explicit Fallible(T &&) -> Fallible<T, Error>; // template <typename T, typename E> explicit Fallible(E &&) -> Fallible<T, E>; [[noreturn]] void Panic(Error const &err) noexcept; }
32.222571
99
0.651814
deni64k
76e83752bd4eaae14a2a423fcefeb64120f5a041
339
cpp
C++
Grade XI/Assignments/asg3_prog3.cpp
SR42-dev/CPP-Practice-Programs
7639790c3d8950250f00ae1c69170c581a8eaf91
[ "CC0-1.0" ]
null
null
null
Grade XI/Assignments/asg3_prog3.cpp
SR42-dev/CPP-Practice-Programs
7639790c3d8950250f00ae1c69170c581a8eaf91
[ "CC0-1.0" ]
null
null
null
Grade XI/Assignments/asg3_prog3.cpp
SR42-dev/CPP-Practice-Programs
7639790c3d8950250f00ae1c69170c581a8eaf91
[ "CC0-1.0" ]
null
null
null
#include <iostream.h> #include <stdio.h> void main() { char str1[32], str2[32]; int i; cout<<"Enter a string : "<<endl; gets (str1); for (i=0;str1[i]!=0;i++) { str2[i] = str1[i]; if (str2[i]==32) str2[i] = '\n'; } str2[i] = 0; cout<<endl; cout<<"Input : "<<str1<<endl; cout<<"Output : "<<str2<<endl; }
16.95
34
0.504425
SR42-dev
76e955ca1bbb753640623213e01ccc4e7537ab77
980
cpp
C++
UVA/UltraQuickSort.cpp
sourav025/algorithms-practices
987932fe0b995c61fc40d1b5a7da18dce8492752
[ "MIT" ]
null
null
null
UVA/UltraQuickSort.cpp
sourav025/algorithms-practices
987932fe0b995c61fc40d1b5a7da18dce8492752
[ "MIT" ]
null
null
null
UVA/UltraQuickSort.cpp
sourav025/algorithms-practices
987932fe0b995c61fc40d1b5a7da18dce8492752
[ "MIT" ]
null
null
null
#include <iostream> #include <string.h> #include <algorithm> #include <stdio.h> using namespace std; #define MX 500009 #define ll long long ll tree[MX+7],ar[MX+7],br[MX+7],n; ll query(ll idx); void update(ll idx, int x); int main() { while(scanf("%lld",&n)==1 && n) { memset(tree, 0, sizeof(tree)); for(int i=0;i<n;i++) cin>>ar[i], br[i] = ar[i]; sort(br, br+n); for(int i=0;i<n;i++){ int idx = (int) (lower_bound(br, br+n, ar[i])- br); ar[i] = idx+1; } ll sm = 0; for(ll i=n-1;i>=0;i--) { sm += query(ar[i]-1); update(ar[i], 1); } cout<<sm<<endl; } return 0; } ll query(ll idx) { ll sum=0; while(idx>0) { sum+=tree[idx]; idx -= (idx&-idx); } return sum; } void update(ll idx, int x) { while(idx<=n+1) { tree[idx]+=x; idx += idx & (-idx); } }
16.896552
63
0.443878
sourav025
76ee08def2eddbb5be400dfeaf049036bfd49505
6,223
cpp
C++
src/qastle.cpp
Epono/qastle
8f5c7b352103e484ebd20f95178d47b8bad4dccc
[ "MIT" ]
null
null
null
src/qastle.cpp
Epono/qastle
8f5c7b352103e484ebd20f95178d47b8bad4dccc
[ "MIT" ]
null
null
null
src/qastle.cpp
Epono/qastle
8f5c7b352103e484ebd20f95178d47b8bad4dccc
[ "MIT" ]
null
null
null
#include "../include/qastle.h" #include "../include/import_export.h" #include "../include/utils.h" #include <QDebug> #include <QFileDialog> #include <QInputDialog> #include <QDir> #include <QListWidget> Qastle::Qastle(QWidget* parent) : QMainWindow(parent) { ui.setupUi(this); setWindowTitle(QApplication::applicationDisplayName()); ui.statusbar->showMessage(QString("This is the status bar")); m_plusTab = std::make_unique<QWidget>(ui.tabWidget->widget(0)); // Add one (TODO: default) tab //auto defaultTableModel = std::make_unique<TableModel>(); auto defaultTableModel = new TableModel(); defaultTableModel->addFirstColumnAndRow(); addTab(0, defaultTableModel); // TABS connect(ui.tabWidget, &QTabWidget::currentChanged, this, &Qastle::slotTabSelected); connect(ui.tabWidget, &QTabWidget::tabBarDoubleClicked, this, &Qastle::slotTabDoubleClicked); ui.tabWidget->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui.tabWidget, &QWidget::customContextMenuRequested, this, &Qastle::showContextMenuTab); // ACTIONS connect(ui.actionLoadFromJson, &QAction::triggered, this, &Qastle::slotLoadFromJson); connect(ui.actionSaveToJson, &QAction::triggered, this, &Qastle::slotSaveToJson); connect(ui.actionQuit, &QAction::triggered, this, &QApplication::quit); } Qastle::Qastle(QString fileName, QWidget* parent) : Qastle(parent) { if (Utils::fileExists(fileName)) { loadFromJson(fileName); } else { qDebug() << "File not found, ignoring and loading blank data"; } } /////////////////////////////////////////////////////////////////////////////////////////////////// // LOAD / SAVE void Qastle::slotLoadFromJson() { // TODO: "Do you want to save current session?" QString fileName = QFileDialog::getOpenFileName(this, QString("Load file"), QString(), QString("JSON file (*.json);; Binary file (*.dat)")); // Cancelled dialog if (fileName.isEmpty()) { return; } // Make sur the file exists if (!Utils::fileExists(fileName)) { return; } loadFromJson(fileName); } bool Qastle::loadFromJson(const QString& fileName) { ui.tabWidget->blockSignals(true); // Delete views m_tableViews.clear(); // Remove and delete old tabs (except not deleting "+" tab) // TODO: Still useful with the way Qt manages memory? int temp = 0; while (ui.tabWidget->count() > 1) { QWidget* tab = ui.tabWidget->widget(temp); if (ui.tabWidget->tabText(temp).compare(QString("+")) == 0) { continue; } else { delete tab; } } ui.tabWidget->clear(); // QVector<TableModel*> tableModels = ImportExport::loadFromJson(fileName); for (int i = 0; i < tableModels.size(); ++i) { addTab(i, tableModels[i]); } ui.tabWidget->addTab(m_plusTab.get(), "+"); ui.tabWidget->tabBar()->setCurrentIndex(0); ui.tabWidget->blockSignals(false); return true; } void Qastle::slotSaveToJson() { // TODO: check if a filepath is known or if it's a new one (save as vs save) QString fileName = QFileDialog::getSaveFileName(this, QString("Save file"), QString(), QString("JSON file (*.json)")); saveToJson(fileName); } bool Qastle::saveToJson(const QString& fileName) { QVector<TableModel*> tableModels; // https://stackoverflow.com/questions/8237502/iterating-over-a-container-of-unique-ptrs/27231261 for (auto&& tableView : m_tableViews) { tableModels.append(tableView->tableModel()); } bool result = ImportExport::saveToJson(fileName, tableModels, ui.actionCheck->isChecked()); return result; } /////////////////////////////////////////////////////////////////////////////////////////////////// // TABS void Qastle::slotTabDoubleClicked(const int selectedTabIndex) { if (ui.tabWidget->tabText(selectedTabIndex).compare(QString("+")) == 0) { // "+" tab double clicked, ignore return; } bool ok; QString text = QInputDialog::getText(this, QString("Change name"), QString("Sheet name"), QLineEdit::Normal, ui.tabWidget->tabText(selectedTabIndex), &ok); if (ok && !text.isEmpty()) { m_tableViews[selectedTabIndex]->tableModel()->setSheetName(text); ui.tabWidget->setTabText(selectedTabIndex, text); } } void Qastle::addTab(const int selectedTabIndex, TableModel* tableModel) { // TODO: handle sheets with "@" (meaning sub sheet) if (tableModel->sheetName().contains("@")) { return; } // Block signals to avoid infinite loop with "+" tab ui.tabWidget->blockSignals(true); QWidget* newTab = new QWidget(ui.tabWidget); QGridLayout* layout = new QGridLayout(newTab); auto tableView = std::make_unique<TableView>(tableModel, newTab); layout->addWidget(tableView.get()); // Init table view // TODO: add default name m_tableViews.push_back(std::move(tableView)); ui.tabWidget->insertTab(selectedTabIndex, newTab, tableModel->sheetName()); //ui.tabWidget->setTabText(selectedTabIndex, tableModel->sheetName()); ui.tabWidget->tabBar()->setCurrentIndex(selectedTabIndex); ui.tabWidget->blockSignals(false); } //https://stackoverflow.com/questions/8308588/how-to-identify-when-the-current-tab-is-changing-in-a-qtabwidget void Qastle::slotTabSelected(const int selectedTabIndex) { // TODO: string compare or last place compare? if (ui.tabWidget->tabText(selectedTabIndex).compare(QString("+")) == 0) { TableModel* tableModel = new TableModel(); tableModel->addFirstColumnAndRow(); addTab(selectedTabIndex, tableModel); } } void Qastle::showContextMenuTab(const QPoint& pos) { int tabIndex = ui.tabWidget->tabBar()->tabAt(pos); if (tabIndex == -1 || tabIndex == ui.tabWidget->count()) { // Outside or "+", ignore return; } QPoint globalPos = mapToGlobal(pos); m_menu = std::make_unique<QMenu>(this); QAction* actionAppendColumn; actionAppendColumn = new QAction(QString("Delete sheet")); actionAppendColumn->setData(tabIndex); connect(actionAppendColumn, &QAction::triggered, this, &Qastle::slotDeleteSheet); m_menu->addAction(actionAppendColumn); m_menu->popup(globalPos); } void Qastle::slotDeleteSheet() { // TODO: handle when only one real sheet int tabIndex = qobject_cast<QAction*>(sender())->data().toInt(); if (ui.tabWidget->currentIndex() == tabIndex) { ui.tabWidget->tabBar()->setCurrentIndex(tabIndex - 1); } m_tableViews.erase(m_tableViews.begin() + tabIndex); ui.tabWidget->removeTab(tabIndex); }
30.356098
156
0.699663
Epono
76f05c5e35cca34f4f2e973bcc27c57aeb13181b
632
cpp
C++
tools/CodeFromTemplate/item_modules/Module/templates/TemplateModuleFactory.cpp
ConnectedVision/ConnectedVision
210e49205ca50f73584178b6cedb298a74cea798
[ "MIT" ]
3
2017-08-12T18:14:00.000Z
2018-11-19T09:15:35.000Z
tools/CodeFromTemplate/item_modules/Module/templates/TemplateModuleFactory.cpp
ConnectedVision/ConnectedVision
210e49205ca50f73584178b6cedb298a74cea798
[ "MIT" ]
null
null
null
tools/CodeFromTemplate/item_modules/Module/templates/TemplateModuleFactory.cpp
ConnectedVision/ConnectedVision
210e49205ca50f73584178b6cedb298a74cea798
[ "MIT" ]
1
2018-11-09T15:57:13.000Z
2018-11-09T15:57:13.000Z
{%- autoescape false -%}{%- include global.macroPath -%} #include "{{Module.moduleID}}ModuleFactory.h" #include "{{Module.moduleID}}Module.h" {{ openNamespace(global.namespace) }} ConnectedVision::shared_ptr<IModule> {{Module.moduleID}}ModuleFactory::createModule() { ConnectedVision::shared_ptr<IModule> moduleInstance = boost::dynamic_pointer_cast<IModule>(ConnectedVision::make_shared<{{Module.moduleID}}Module>()); if ( !moduleInstance ) throw std::runtime_error("{{Module.moduleID}}ModuleFactory: error creating instance for module: {{Module.name}}"); return moduleInstance; } {{ closeNamespace(global.namespace) }}
35.111111
151
0.753165
ConnectedVision
76f10ee3b54fdd34398caa407a9cc96c8ec5322e
8,764
cpp
C++
mr.Sadman/Classes/GameAct/Objects/Tech/Saw.cpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
null
null
null
mr.Sadman/Classes/GameAct/Objects/Tech/Saw.cpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
3
2020-12-11T10:01:27.000Z
2022-02-13T22:12:05.000Z
mr.Sadman/Classes/GameAct/Objects/Tech/Saw.cpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
null
null
null
#include "Director.hpp" #include "GameAct/Act.hpp" #include "GameAct/Objects/Factories/ObjectsFactory.hpp" #include "Saw.hpp" #include "Resources/Cache/Cache.hpp" #include <cmath> namespace GameAct { namespace Tech { Saw::Saw() : _decorator( Director::getInstance().getGameAct()->getObjectsFactory()->create( "Line" ) ) { } std::string Saw::getName() const { return "Saw"; } void Saw::setPosition( cocos2d::Vec2 position ) { float koef = 1.0f / sqrt( 2.0f ); cocos2d::Vec2 decPosit = position; switch ( _direction ) { case Direction::Right: decPosit.x += _decorator->getSize().width / 2.0f; break; case Direction::Left: decPosit.x -= _decorator->getSize().width / 2.0f; break; case Direction::Top: decPosit.y += _decorator->getSize().width / 2.0f; break; case Direction::Bottom: decPosit.y -= _decorator->getSize().width / 2.0f; break; case Direction::D45: decPosit.y += _decorator->getSize().width / 2.0f * koef; decPosit.x -= _decorator->getSize().width / 2.0f * koef; break; case Direction::D135: decPosit.y += _decorator->getSize().width / 2.0f * koef; decPosit.x += _decorator->getSize().width / 2.0f * koef; break; case Direction::D225: decPosit.y -= _decorator->getSize().width / 2.0f * koef; decPosit.x += _decorator->getSize().width / 2.0f * koef; break; case Direction::D315: decPosit.y -= _decorator->getSize().width / 2.0f * koef; decPosit.x -= _decorator->getSize().width / 2.0f * koef; break; case Direction::Circle: decPosit.x += _decorator->getSize().width; break; default: break; } _decorator->setPosition( decPosit ); Object::setPosition( position ); } void Saw::setSize( cocos2d::Size size ) { float koef = 1.0f / sqrt( 2.0f ); cocos2d::Size decSize = size; switch ( _direction ) { case Direction::Left: case Direction::Right: case Direction::Top: case Direction::Bottom: case Direction::Circle: decSize.width *= _lenth; decSize.height /= 2.0f; break; case Direction::D45: case Direction::D135: case Direction::D225: case Direction::D315: decSize.width *= _lenth / koef; decSize.height /= 2.0f; break; default: break; } _decorator->setSize( decSize ); Object::setSize( size ); } void Saw::setAdditionalParam( std::string additionalParam ) { int posit = additionalParam.find( ';' ); _lenth = std::stof( additionalParam.substr( 0, posit ) ); _time = std::stof( additionalParam.substr( posit + 1, additionalParam.length() - posit - 1 ) ); _decorator->setAdditionalParam( std::to_string( _time ) ); } void Saw::setDirection( Direction direction ) { _decorator->setDirection( direction ); Object::setDirection( direction ); } void Saw::hide() { _decorator->hide(); Object::hide(); } void Saw::show() { _decorator->show(); Object::show(); } void Saw::attachToChunk( Chunk & chunk, int zIndex ) { _decorator->attachToChunk( chunk, zIndex - 1 ); Object::attachToChunk( chunk, zIndex ); } void Saw::runAction( const std::string & action ) { // horizontal init cocos2d::Vec2 rightPos = cocos2d::Vec2( getSize().width * _lenth, 0.0f ); cocos2d::Vec2 leftPos = cocos2d::Vec2( getSize().width * -_lenth, 0.0f ); auto rotate = cocos2d::RotateBy::create( _time, 360.0f ); auto goRight = cocos2d::MoveBy::create( _time * 5.0f, rightPos ); auto goLeft = cocos2d::MoveBy::create( _time * 5.0f, leftPos ); auto spawnRight = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goRight, nullptr ); auto spawnLeft = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goLeft, nullptr ); // vertiacal init cocos2d::Vec2 upPos = cocos2d::Vec2( 0.0f, getSize().width * _lenth ); cocos2d::Vec2 downPos = cocos2d::Vec2( 0.0f, getSize().width * -_lenth ); auto goUp = cocos2d::MoveBy::create( _time * 5.0f, upPos ); auto goDown = cocos2d::MoveBy::create( _time * 5.0f, downPos ); auto spawnUp = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goUp, nullptr ); auto spawnDown = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goDown, nullptr ); // angle init float lineLenth = getSize().width * _lenth; cocos2d::Action * sequence; if( action == "Run" ) { switch ( _direction ) { case Direction::Left: sequence = cocos2d::RepeatForever::create( cocos2d::Sequence::create( spawnLeft, spawnRight, nullptr ) ); break; case Direction::Right: sequence = cocos2d::RepeatForever::create( cocos2d::Sequence::create( spawnRight, spawnLeft, nullptr ) ); break; case Direction::Top: sequence = cocos2d::RepeatForever::create( cocos2d::Sequence::create( spawnUp, spawnDown, nullptr ) ); break; case Direction::Bottom: sequence = cocos2d::RepeatForever::create( cocos2d::Sequence::create( spawnDown, spawnUp, nullptr ) ); break; case Direction::D45: { cocos2d::Vec2 pos1 = cocos2d::Vec2( -lineLenth, lineLenth ); cocos2d::Vec2 pos2 = cocos2d::Vec2( lineLenth, -lineLenth ); auto goPos1 = cocos2d::MoveBy::create( _time * 5.0f, pos1 ); auto goPos2 = cocos2d::MoveBy::create( _time * 5.0f, pos2 ); auto spawnPos1 = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goPos1, nullptr ); auto spawnPos2 = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goPos2, nullptr ); sequence = cocos2d::RepeatForever::create( cocos2d::Sequence::create( spawnPos1, spawnPos2, nullptr ) ); } break; case Direction::D135: { cocos2d::Vec2 pos1 = cocos2d::Vec2( lineLenth, lineLenth ); cocos2d::Vec2 pos2 = cocos2d::Vec2( -lineLenth, -lineLenth ); auto goPos1 = cocos2d::MoveBy::create( _time * 5.0f, pos1 ); auto goPos2 = cocos2d::MoveBy::create( _time * 5.0f, pos2 ); auto spawnPos1 = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goPos1, nullptr ); auto spawnPos2 = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goPos2, nullptr ); sequence = cocos2d::RepeatForever::create( cocos2d::Sequence::create( spawnPos1, spawnPos2, nullptr ) ); } break; case Direction::D225: { cocos2d::Vec2 pos1 = cocos2d::Vec2( lineLenth, -lineLenth ); cocos2d::Vec2 pos2 = cocos2d::Vec2( -lineLenth, lineLenth ); auto goPos1 = cocos2d::MoveBy::create( _time * 5.0f, pos1 ); auto goPos2 = cocos2d::MoveBy::create( _time * 5.0f, pos2 ); auto spawnPos1 = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goPos1, nullptr ); auto spawnPos2 = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goPos2, nullptr ); sequence = cocos2d::RepeatForever::create( cocos2d::Sequence::create( spawnPos1, spawnPos2, nullptr ) ); } break; case Direction::D315: { cocos2d::Vec2 pos1 = cocos2d::Vec2( -lineLenth, -lineLenth ); cocos2d::Vec2 pos2 = cocos2d::Vec2( lineLenth, lineLenth ); auto goPos1 = cocos2d::MoveBy::create( _time * 5.0f, pos1 ); auto goPos2 = cocos2d::MoveBy::create( _time * 5.0f, pos2 ); auto spawnPos1 = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goPos1, nullptr ); auto spawnPos2 = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goPos2, nullptr ); sequence = cocos2d::RepeatForever::create( cocos2d::Sequence::create( spawnPos1, spawnPos2, nullptr ) ); } break; case Direction::Circle: { cocos2d::Vec2 center = getPosition(); center.x += getSize().width * _lenth; cocos2d::Vector< cocos2d::FiniteTimeAction * > _rotate; auto posit = getPosition(); for( int i = 0; i < 100; ++i ) { _rotate.pushBack( cocos2d::MoveTo::create( _time / 100, posit ) ); posit = rotatePoint( posit, center, 3.6f ); } sequence = cocos2d::RepeatForever::create( cocos2d::Sequence::create( _rotate ) ); _decorator->runAction( "Rotate" ); } default: break; } _sprite->runAction( sequence ); _audio = Resources::Cache::getInstance().getObjectSound( getName(), "Def" ); } if( action == "Stop" ) { _sprite->stopAllActions(); _decorator->runAction( "Stop" ); } } cocos2d::Vec2 Saw::rotatePoint( cocos2d::Vec2 point, cocos2d::Vec2 center, float angle ) const { angle = (angle ) * ( M_PI / 180 ); float rotatedX = cos( angle ) * (point.x - center.x) + sin( angle ) * ( point.y - center.y ) + center.x; float rotatedY = -sin( angle ) * ( point.x - center.x ) + cos( angle ) * ( point.y - center.y ) + center.y; return cocos2d::Vec2( rotatedX, rotatedY ); } } }
28.828947
112
0.637608
1pkg
76f964cabbe329b0e3c09bcdbc775200858ce885
2,767
cpp
C++
Shader.cpp
HeckMina/CGI
976dfe064ec8021ef615354c46ca93637c56b8c6
[ "MIT" ]
2
2021-07-06T01:01:55.000Z
2021-07-07T01:30:31.000Z
Shader.cpp
HeckMina/CGI
976dfe064ec8021ef615354c46ca93637c56b8c6
[ "MIT" ]
null
null
null
Shader.cpp
HeckMina/CGI
976dfe064ec8021ef615354c46ca93637c56b8c6
[ "MIT" ]
1
2021-03-31T05:36:27.000Z
2021-03-31T05:36:27.000Z
#include "Shader.h" #if ALICE_OGL_RENDERER #include "utils.h" namespace Alice { void Shader::Init(const char* vs, const char* fs) { int nFileSize = 0; const char* vsCode = (char*)LoadFileContent(vs, nFileSize); const char* fsCode = (char*)LoadFileContent(fs, nFileSize); GLuint vsShader = CompileShader(GL_VERTEX_SHADER, vsCode); if (vsShader == 0) { return; } GLuint fsShader = CompileShader(GL_FRAGMENT_SHADER, fsCode); if (fsShader == 0) { return; } OGL_CALL(mProgram = CreateProgram(vsShader, fsShader)); OGL_CALL(glDeleteShader(vsShader)); OGL_CALL(glDeleteShader(fsShader)); if (mProgram != 0) { OGL_CALL(mModelMatrixLocation = glGetUniformLocation(mProgram, "ModelMatrix")); OGL_CALL(mViewMatrixLocation = glGetUniformLocation(mProgram, "ViewMatrix")); OGL_CALL(mProjectionMatrixLocation = glGetUniformLocation(mProgram, "ProjectionMatrix")); OGL_CALL(mITModelMatrixLocation = glGetUniformLocation(mProgram, "U_NormalMatrix")); OGL_CALL(mPositionLocation = glGetAttribLocation(mProgram, "position")); OGL_CALL(mTangentLocation = glGetAttribLocation(mProgram, "tangent")); OGL_CALL(mTexcoordLocation = glGetAttribLocation(mProgram, "texcoord")); OGL_CALL(mNormalLocation = glGetAttribLocation(mProgram, "normal")); } } void Shader::BeginDraw(Camera* camera, const glm::mat4& model) { OGL_CALL(glUseProgram(mProgram)); if (camera != nullptr) { if (mViewMatrixLocation != -1) { OGL_CALL(glUniformMatrix4fv(mViewMatrixLocation, 1, GL_FALSE, glm::value_ptr(camera->mViewMatrix))); } if (mProjectionMatrixLocation != -1) { OGL_CALL(glUniformMatrix4fv(mProjectionMatrixLocation, 1, GL_FALSE, glm::value_ptr(camera->mProjectionMatrix))); } } if (mModelMatrixLocation != -1) { OGL_CALL(glUniformMatrix4fv(mModelMatrixLocation, 1, GL_FALSE, glm::value_ptr(model))); } if (mPositionLocation != -1) { OGL_CALL(glEnableVertexAttribArray(mPositionLocation)); OGL_CALL(glVertexAttribPointer(mPositionLocation, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0)); } if (mTexcoordLocation != -1) { OGL_CALL(glEnableVertexAttribArray(mTexcoordLocation)); OGL_CALL(glVertexAttribPointer(mTexcoordLocation, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(float) * 4))); } if (mNormalLocation != -1) { OGL_CALL(glEnableVertexAttribArray(mNormalLocation)); OGL_CALL(glVertexAttribPointer(mNormalLocation, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(float) * 8))); } if (mTangentLocation != -1) { OGL_CALL(glEnableVertexAttribArray(mTangentLocation)); OGL_CALL(glVertexAttribPointer(mTangentLocation, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(float) * 12))); } } void Shader::EndDraw() { OGL_CALL(glUseProgram(0)); } } #endif
42.569231
121
0.738345
HeckMina
76fa55402ca7a632e7ada9de58d2ed61ae6bf37f
2,207
cpp
C++
src/main.cpp
clayne/HookShareSSE
f448d82412a86dcd286e8630d4af87638303aae6
[ "MIT" ]
8
2019-06-15T16:19:03.000Z
2020-05-14T10:21:51.000Z
src/main.cpp
SniffleMan/HookShareSSE
f448d82412a86dcd286e8630d4af87638303aae6
[ "MIT" ]
3
2019-12-03T15:28:04.000Z
2020-04-25T23:30:11.000Z
src/main.cpp
SniffleMan/HookShareSSE
f448d82412a86dcd286e8630d4af87638303aae6
[ "MIT" ]
13
2019-06-15T16:19:04.000Z
2021-01-05T10:56:43.000Z
#include "skse64_common/BranchTrampoline.h" // g_localTrampoline #include "skse64_common/skse_version.h" // RUNTIME_VERSION #include "Hooks.h" // InstallHooks #include "HookShare.h" // RegisterHook #include "version.h" // VERSION_VERSTRING #include "SKSE/API.h" void MessageHandler(SKSE::MessagingInterface::Message* a_msg) { switch (a_msg->type) { case SKSE::MessagingInterface::kDataLoaded: { auto messaging = SKSE::GetMessagingInterface(); messaging->Dispatch(HookShare::kType_CanProcess, HookShare::RegisterForCanProcess, HookShare::kAPIVersionMajor, 0); } break; } } extern "C" { bool SKSEPlugin_Query(const SKSE::QueryInterface* a_skse, SKSE::PluginInfo* a_info) { SKSE::Logger::OpenRelative(FOLDERID_Documents, L"\\My Games\\Skyrim Special Edition\\SKSE\\HookShareSSE.log"); SKSE::Logger::SetPrintLevel(SKSE::Logger::Level::kDebugMessage); SKSE::Logger::SetFlushLevel(SKSE::Logger::Level::kDebugMessage); SKSE::Logger::UseLogStamp(true); _MESSAGE("HookShareSSE v%s", HSHR_VERSION_VERSTRING); a_info->infoVersion = SKSE::PluginInfo::kVersion; a_info->name = "HookShareSSE"; a_info->version = HookShare::kAPIVersionMajor; if (a_skse->IsEditor()) { _FATALERROR("Loaded in editor, marking as incompatible!\n"); return false; } switch (a_skse->RuntimeVersion()) { case RUNTIME_VERSION_1_5_73: case RUNTIME_VERSION_1_5_80: break; default: _FATALERROR("Unsupported runtime version %08X!\n", a_skse->RuntimeVersion()); return false; } return true; } bool SKSEPlugin_Load(const SKSE::LoadInterface* a_skse) { _MESSAGE("HookShareSSE loaded"); if (!SKSE::Init(a_skse)) { return false; } if (g_localTrampoline.Create(1024 * 8)) { _MESSAGE("Local trampoline creation successfull"); } else { _MESSAGE("Local trampoline creation failed!\n"); return false; } auto messaging = SKSE::GetMessagingInterface(); if (messaging->RegisterListener("SKSE", MessageHandler)) { _MESSAGE("Messaging interface registration successful"); } else { _FATALERROR("Messaging interface registration failed!\n"); return false; } Hooks::InstallHooks(); _MESSAGE("Hooks installed"); return true; } };
25.964706
118
0.722247
clayne
76ff857c51d1eb1d85d931501a33f857f1fb6a9a
849
cpp
C++
1549.cpp
yyong119/ACM-OnlineJudge
5871993b15231c6615bfa3e7c2b04f0f6a23e9dc
[ "MIT" ]
22
2017-08-12T11:56:19.000Z
2022-03-27T10:04:31.000Z
1549.cpp
yyong119/ACM-OnlineJudge
5871993b15231c6615bfa3e7c2b04f0f6a23e9dc
[ "MIT" ]
2
2017-12-17T02:52:59.000Z
2018-02-09T02:10:43.000Z
1549.cpp
yyong119/ACM-OnlineJudge
5871993b15231c6615bfa3e7c2b04f0f6a23e9dc
[ "MIT" ]
4
2017-12-22T15:24:38.000Z
2020-05-18T14:51:16.000Z
#include <iostream> #include <cstring> #include <cstdio> using namespace std; char str[110],cha[110]; int point; int main() { while (scanf("%s", str) != EOF) { point = 0; int len = strlen(str); for (int i = 0; i < len; ++i) { cha[i] = ' '; if (str[i] == '(') ++point; if (str[i] == ')') { --point; if (point < 0) { point = 0; cha[i] = '?'; } } } point = 0; for (int i = len - 1; i >= 0; --i) { if (str[i] == ')') ++point; if (str[i] == '(') { --point; if (point < 0) { point = 0; cha[i] = '$'; } } } printf("%s\n%s\n", str, cha); } }
24.257143
48
0.30742
yyong119
76ff94f16827ae359da180fdd96235a16c288456
2,154
hpp
C++
include/ecst/context/storage/component/chunk/impl/hash_map.hpp
SuperV1234/ecst
b3c42e2c28978f1cd8ea620ade62613c6c875432
[ "AFL-3.0" ]
475
2016-05-03T13:34:30.000Z
2021-11-26T07:02:47.000Z
include/ecst/context/storage/component/chunk/impl/hash_map.hpp
vittorioromeo/ecst
b3c42e2c28978f1cd8ea620ade62613c6c875432
[ "AFL-3.0" ]
28
2016-08-30T06:37:40.000Z
2017-11-24T11:14:07.000Z
include/ecst/context/storage/component/chunk/impl/hash_map.hpp
vittorioromeo/ecst
b3c42e2c28978f1cd8ea620ade62613c6c875432
[ "AFL-3.0" ]
60
2016-05-11T22:16:15.000Z
2021-08-02T20:42:35.000Z
// Copyright (c) 2015-2016 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: http://opensource.org/licenses/AFL-3.0 // http://vittorioromeo.info | vittorio.romeo@outlook.com // TODO: /* #pragma once #include <unordered_map> #include <ecst/config.hpp> #include <ecst/aliases.hpp> #include <ecst/context/types.hpp> ECST_CONTEXT_STORAGE_COMPONENT_NAMESPACE { namespace chunk { template <typename TComponent> class hash_map { public: using component_type = TComponent; struct metadata { }; private: std::unordered_map<sz_t, TComponent> _data; auto valid_index(sz_t i) const noexcept { return _data.count(i) > 0; } auto entity_id_to_index(entity_id eid) const noexcept { return vrmc::to_sz_t(eid); } template <typename TSelf> decltype(auto) get_impl( TSelf&& self, entity_id eid, const metadata&) noexcept { auto i = self.entity_id_to_index(eid); ECST_ASSERT(self.valid_index(i)); return vrmc::forward_like<TSelf>(_data[i]); } template <typename TSelf> decltype(auto) add_impl( TSelf&& self, entity_id eid, metadata&) noexcept { auto i = self.entity_id_to_index(eid); return vrmc::forward_like<TSelf>(_data[i]); } public: template <typename... Ts> auto& get(Ts&&... xs) & noexcept { return get_impl(*this, FWD(xs)...); } template <typename... Ts> const auto& get(Ts&&... xs) const& noexcept { return get_impl(*this, FWD(xs)...); } template <typename... Ts> auto& add(Ts&&... xs) { return add_impl(*this, FWD(xs)...); } }; } } ECST_CONTEXT_STORAGE_COMPONENT_NAMESPACE_END */
25.642857
70
0.510678
SuperV1234
0a012814f275542a7122359c744a11b78c54fc76
5,675
cpp
C++
src/cl-utils/str-args.cpp
codalogic/cl-utils
996452272d4c09b8df7928abdaea75b0e786a244
[ "BSD-3-Clause" ]
null
null
null
src/cl-utils/str-args.cpp
codalogic/cl-utils
996452272d4c09b8df7928abdaea75b0e786a244
[ "BSD-3-Clause" ]
null
null
null
src/cl-utils/str-args.cpp
codalogic/cl-utils
996452272d4c09b8df7928abdaea75b0e786a244
[ "BSD-3-Clause" ]
null
null
null
//---------------------------------------------------------------------------- // Copyright (c) 2016, Codalogic Ltd (http://www.codalogic.com) // All rights reserved. // // The license for this file is based on the BSD-3-Clause license // (http://www.opensource.org/licenses/BSD-3-Clause). // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // - Neither the name Codalogic Ltd nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //---------------------------------------------------------------------------- #include "cl-utils/str-args.h" #include <cassert> #include <cstring> #include <algorithm> namespace clutils { namespace { // Implementation detail class str_args_detail { private: size_t i; std::string * p_result; const char * format; const str_args::args_t & args; public: str_args_detail( std::string * p_out, const char * format, const str_args::args_t & args ) : p_result( p_out ), format( format ), args( args ) { try { p_result->reserve( p_result->size() + strlen( format ) ); for( i=0; format[i] != '\0'; safe_advance() ) { if( format[i] != '%' ) p_result->append( 1, format[i] ); else process_parameter_decl(); } } catch( std::out_of_range & ) { assert( 0 ); // We've done something like %1 in our args string when args[1] doesn't exist. N.B. args are 0 based. throw str_argsOutOfRangeException( "str_args args[] index out of range" ); } } void safe_advance() { if( format[i] != '\0' ) ++i; } void process_parameter_decl() { safe_advance(); if( format[i] == '\0' ) // Malformed case, but be tolerant p_result->append( 1, '%' ); else if( format[i] == '%' ) // %% -> % p_result->append( 1, '%' ); else if( is_numerical_parameter() ) p_result->append( args.at( format[i] - '0' ) ); else if( format[i] == '{' ) process_long_form_parameter_decl(); else silently_accept_standalone_parameter_indicator(); } bool is_numerical_parameter() { return format[i] >= '0' && format[i] <= '9'; } void process_long_form_parameter_decl() { safe_advance(); if( format[i] != '\0' ) { if( is_numerical_parameter() ) process_numbered_long_form_parameter_decl(); else process_named_long_form_parameter_decl(); } } void process_numbered_long_form_parameter_decl() { // Long form %{0:a description} size_t index = read_numerical_parameter_index(); p_result->append( args.at( index ) ); skip_remainder_of_parameter_decl(); } size_t read_numerical_parameter_index() { size_t index = 0; while( is_numerical_parameter() ) index = 10 * index + format[i++] - '0'; return index; } void skip_remainder_of_parameter_decl() { for( ; format[i] != '\0' && format[i] != '}'; safe_advance() ) {} // Skip over rest of characters in format specifier } void process_named_long_form_parameter_decl() { // Named long form %{var-name} std::string name = read_parameter_name(); str_args::args_t::const_iterator key_index = std::find( args.begin(), args.end(), name ); if( key_index != args.end() ) p_result->append( *(++key_index) ); skip_remainder_of_parameter_decl(); } std::string read_parameter_name() { std::string name; for( ; format[i] != '\0' && format[i] != '}'; safe_advance() ) name.append( 1, format[i] ); return name; } void silently_accept_standalone_parameter_indicator() { p_result->append( 1, '%' ); p_result->append( 1, format[i] ); } std::string * result() const { return p_result; } }; } // End of namespace { // Implementation detail std::string * str_args::expand_append( std::string * p_out, const char * format ) const { return str_args_detail( p_out, format, args ).result(); } } // namespace clutils
32.614943
127
0.597181
codalogic
0a023ff0a7846fabea47bb9f8bbce6955f1a5ffc
734
hpp
C++
libs/options/include/fcppt/options/base_unique_ptr_fwd.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/options/include/fcppt/options/base_unique_ptr_fwd.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/options/include/fcppt/options/base_unique_ptr_fwd.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2018. // 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 FCPPT_OPTIONS_BASE_UNIQUE_PTR_FWD_HPP_INCLUDED #define FCPPT_OPTIONS_BASE_UNIQUE_PTR_FWD_HPP_INCLUDED #include <fcppt/unique_ptr_fwd.hpp> #include <fcppt/options/base_fwd.hpp> namespace fcppt { namespace options { /** \brief A unique pointer for #fcppt::options::base. \ingroup fcpptoptions \tparam Result The result type of the parser. Must be an #fcppt::record::object. */ template< typename Result > using base_unique_ptr = fcppt::unique_ptr< fcppt::options::base< Result > >; } } #endif
17.47619
80
0.741144
pmiddend
0a03a946c20c717fe20cc7d004609c60901afc6f
1,061
cc
C++
pytorch/caffe2/operators/experimental/c10/cpu/enforce_finite_cpu.cc
raghavnauhria/whatmt
c20483a437c82936cb0fb8080925e37b9c4bba87
[ "MIT" ]
null
null
null
pytorch/caffe2/operators/experimental/c10/cpu/enforce_finite_cpu.cc
raghavnauhria/whatmt
c20483a437c82936cb0fb8080925e37b9c4bba87
[ "MIT" ]
1
2019-07-22T09:48:46.000Z
2019-07-22T09:48:46.000Z
pytorch/caffe2/operators/experimental/c10/cpu/enforce_finite_cpu.cc
raghavnauhria/whatmt
c20483a437c82936cb0fb8080925e37b9c4bba87
[ "MIT" ]
null
null
null
#include <ATen/core/op_registration/op_registration.h> #include "caffe2/core/export_c10_op_to_caffe2.h" #include "caffe2/core/tensor.h" #include "caffe2/utils/math.h" using caffe2::CPUContext; using caffe2::Tensor; namespace caffe2 { namespace { template <class DataType> void enforce_finite_op_impl_cpu(const at::Tensor& input_) { Tensor input(input_); const DataType* input_data = input.template data<DataType>(); auto size = input.numel(); for (auto i = 0; i < size; i++) { CAFFE_ENFORCE( std::isfinite(input_data[i]), "Index ", i, " is not finite (e.g., NaN, Inf): ", input_data[i]); } } static auto registry = c10::RegisterOperators().op( "_c10_experimental::EnforceFinite", c10::RegisterOperators::options() .kernel< decltype(enforce_finite_op_impl_cpu<float>), &enforce_finite_op_impl_cpu<float>>(CPUTensorId())); } // namespace C10_EXPORT_C10_OP_TO_CAFFE2_CPU( "_c10_experimental::EnforceFinite", C10EnforceFinite_DontUseThisOpYet) } // namespace caffe2
25.878049
63
0.694628
raghavnauhria
0a117fdeca03b2c8e3f53053fbe68a19b9187031
8,533
cpp
C++
008_social_distancing.cpp
DreamVu/Code-Samples
2fccd9e649fbe7d9895df7d799cb1ec33066d1c2
[ "MIT" ]
null
null
null
008_social_distancing.cpp
DreamVu/Code-Samples
2fccd9e649fbe7d9895df7d799cb1ec33066d1c2
[ "MIT" ]
null
null
null
008_social_distancing.cpp
DreamVu/Code-Samples
2fccd9e649fbe7d9895df7d799cb1ec33066d1c2
[ "MIT" ]
null
null
null
/* CODE SAMPLE # 008: Social Distancing This code sample allows users to check if the distance between two people is within a limit or not. >>>>>> Compile this code using the following command.... g++ 008_social_distancing.cpp /usr/src/tensorrt/bin/common/logger.o ../lib/libPAL.so ../lib/libPAL_CAMERA.so ../lib/libPAL_DEPTH_HQ.so ../lib/libPAL_DEPTH_128.so ../lib/libPAL_DE.so ../lib/libPAL_EDET.so `pkg-config --libs --cflags opencv` -g -o 008_social_distancing.out -I../include/ -lv4l2 -lpthread -lcudart -L/usr/local/cuda/lib64 -lnvinfer -lnvvpi -lnvparsers -lnvinfer_plugin -lnvonnxparser -lmyelin -lnvrtc -lcudart -lcublas -lcudnn -lrt -ldl -lstdc++fs >>>>>> Execute the binary file by typing the following command... ./008_social_distancing.out >>>>>> KEYBOARD CONTROLS: Press ESC to close the window Press f/F to toggle filter rgb property Press d/D to toggle fast depth property Press v/V to toggle vertical flip property Press r/R to toggle near range property Press l/L to switch floor mode Press i/I to switch intermediate mode Press t/T to switch table top mode Press c/C to switch ceiling mode Press a/A to switch auto mode */ # include <stdio.h> # include <opencv2/opencv.hpp> # include "PAL.h" using namespace cv; using namespace std; namespace PAL { namespace Internal { void EnableDepth(bool flag); void MinimiseCompute(bool flag); } } //Function to compute distance between two persons bool IsSociallyDistant(PAL::Loc3D p1, PAL::Loc3D p2, int threshold) { if((sqrt(pow(p1.x-p2.x,2.0)+pow(p1.y-p2.y,2.0)+pow(p1.z-p2.z,2.0))) <= threshold) return false; return true; } //Function to compute whether the detected persons are socially distant or not void ComputeDistanceMatrix(std::vector<PAL::Loc3D> Loc3Ds, std::vector<bool>& DistantData, float threshold_distance) { int num_persons = Loc3Ds.size(); bool b = true; for(int i=0; i<num_persons; i++) { for(int j = i+1; j<num_persons; j++) { //checking if location of two persons are larger or not than 100cm b = IsSociallyDistant(Loc3Ds[i], Loc3Ds[j], threshold_distance); if(!b) DistantData[i] = DistantData[j] = false; } } } int main( int argc, char** argv ) { namedWindow( "PAL Social Distancing", WINDOW_NORMAL ); // Create a window for display. //Depth should be enabled for this code sample as a prerequisite bool isDepthEnabled = true; PAL::Internal::EnableDepth(isDepthEnabled); PAL::Internal::MinimiseCompute(false); int width, height; if(PAL::Init(width, height,-1) != PAL::SUCCESS) //Connect to the PAL camera { printf("Camera Init failed\n"); return 1; } PAL::CameraProperties data; PAL::Acknowledgement ack = PAL::LoadProperties("../Explorer/SavedPalProperties.txt"); if(ack != PAL::SUCCESS) { printf("Error Loading settings\n"); } PAL::CameraProperties prop; unsigned int flag = PAL::MODE; flag = flag | PAL::FD; flag = flag | PAL::NR; flag = flag | PAL::FILTER_SPOTS; flag = flag | PAL::VERTICAL_FLIP; prop.mode = PAL::Mode::DETECTION; prop.fd = 1; prop.nr = 0; prop.filter_spots = 1; prop.vertical_flip =0; PAL::SetCameraProperties(&prop, &flag); float threshold = (argc>1) ? atof(argv[1]) : 0.35; float threshold_distance = (argc>2) ? atof(argv[2]) : 100.0f; //threshold_distane should be between 1m to 2m. if(threshold_distance > 200) { threshold_distance = 200; printf("threshold distance set above maximum range. Setting to 2m"); } else if(threshold_distance < 100) { threshold_distance = 100; printf("threshold distance set below minumum range. Setting to 1m"); } if(PAL::InitPersonDetection(threshold)!= PAL::SUCCESS) //Initialise object detection pipeline { printf("Social Distancing Init failed\n"); return 1; } //width and height are the dimensions of each panorama. //Each of the panoramas are displayed at quarter their original resolution. //Since the left+right+disparity are vertically stacked, the window height should be thrice the quarter-height resizeWindow("PAL Social Distancing", width/4, (height/4)*3); int key = ' '; printf("Press ESC to close the window\n"); printf("Press f/F to toggle filter rgb property\n"); printf("Press d/D to toggle fast depth property\n"); printf("Press v/V to toggle vertical flip property\n"); printf("Press r/R to toggle near range property\n"); printf("Press l/L to switch floor mode\n"); printf("Press i/I to switch intermediate mode\n"); printf("Press t/T to switch table top mode\n"); printf("Press c/C to switch ceiling mode\n"); printf("Press a/A to switch auto mode\n"); bool flip = false; bool fd = true; bool nr = false; bool filter_spots = true; //27 = esc key. Run the loop until the ESC key is pressed while(key != 27) { cv::Mat rgb, depth, output,right; std::vector<PAL::BoundingBox> Boxes; vector<float> DepthValues; vector<PAL::Loc3D> Loc3Ds; //Function to Query //Image data: rgb & depth panoramas //Person detection data: Bounding boxes and 3-D locations of each person detected. PAL::GetPeopleDetection(rgb,right, depth, &Boxes, DepthValues, &Loc3Ds); int num_of_persons = Boxes.size(); std::vector<bool> DistantData(num_of_persons, true); //Computing if persons are socially distant or not in case of multiple detections using 3-D locations if(num_of_persons>=2) { ComputeDistanceMatrix(Loc3Ds, DistantData, threshold_distance); for(int i=0; i<num_of_persons; i++) { if(DistantData[i]) cv::rectangle(rgb,Point(Boxes[i].x1, Boxes[i].y1), Point(Boxes[i].x2, Boxes[i].y2), cv::Scalar(0,255,0),2); //Drawing GREEN box indicating the person is socially distant else cv::rectangle(rgb,Point(Boxes[i].x1, Boxes[i].y1), Point(Boxes[i].x2, Boxes[i].y2), cv::Scalar(0,0,255),2); //Drawing RED box indicating the person is not socially distant } } else if(num_of_persons==1) { cv::rectangle(rgb,Point(Boxes[0].x1, Boxes[0].y1), Point(Boxes[0].x2, Boxes[0].y2), cv::Scalar(0,255,0), 2); } //Display the final output image imshow( "PAL Social Distancing", rgb); //Wait for the keypress - with a timeout of 1 ms key = waitKey(1) & 255; if (key == 'f' || key == 'F') { PAL::CameraProperties prop; filter_spots = !filter_spots; prop.filter_spots = filter_spots; unsigned int flags = PAL::FILTER_SPOTS; PAL::SetCameraProperties(&prop, &flags); } if (key == 'v' || key == 'V') { PAL::CameraProperties prop; flip = !flip; prop.vertical_flip = flip; unsigned int flags = PAL::VERTICAL_FLIP; PAL::SetCameraProperties(&prop, &flags); } if (key == 'l' || key == 'L') { PAL::CameraProperties prop; prop.mode = PAL::Mode::DETECTION; prop.detection_mode = PAL::FLOOR; unsigned int flags = PAL::DETECTION_MODE | PAL::MODE; PAL::SetCameraProperties(&prop, &flags); } if (key == 't' || key == 'T') { PAL::CameraProperties prop; prop.mode = PAL::Mode::DETECTION; prop.detection_mode = PAL::TABLE_TOP; unsigned int flags = PAL::DETECTION_MODE | PAL::MODE; PAL::SetCameraProperties(&prop, &flags); } if (key == 'c' || key == 'C') { PAL::CameraProperties prop; prop.mode = PAL::Mode::DETECTION; prop.detection_mode = PAL::CEILING; unsigned int flags = PAL::DETECTION_MODE | PAL::MODE; PAL::SetCameraProperties(&prop, &flags); } if (key == 'i' || key == 'I') { PAL::CameraProperties prop; prop.mode = PAL::Mode::DETECTION; prop.detection_mode = PAL::INTERMEDIATE; unsigned int flags = PAL::DETECTION_MODE | PAL::MODE; PAL::SetCameraProperties(&prop, &flags); } if (key == 'a' || key == 'A') { PAL::CameraProperties prop; prop.mode = PAL::Mode::DETECTION; prop.detection_mode = PAL::AUTO; unsigned int flags = PAL::DETECTION_MODE | PAL::MODE; PAL::SetCameraProperties(&prop, &flags); } if(key == 'd' || key == 'D') { PAL::CameraProperties prop; fd = !fd; prop.fd = fd; unsigned int flags = PAL::FD; PAL::SetCameraProperties(&prop, &flags); } if(key == 'r' || key == 'R') { PAL::CameraProperties prop; nr = !nr; prop.nr = nr; unsigned int flags = PAL::NR; PAL::SetCameraProperties(&prop, &flags); } PAL::CameraProperties properties; GetCameraProperties(&properties); filter_spots = properties.filter_spots; flip = properties.vertical_flip; fd = properties.fd; nr = properties.nr; } printf("exiting the application\n"); PAL::Destroy(); return 0; }
30.475
471
0.677253
DreamVu
0a119fc12cfcae022b721e0096cda6eac2b5ab21
1,470
cpp
C++
Rush/Platform.cpp
kayru/librush
70fe4af6c8a635f4eac6ab20dbc1f251d299dc3a
[ "MIT" ]
49
2015-01-18T17:24:44.000Z
2022-03-31T01:31:38.000Z
Rush/Platform.cpp
kayru/librush
70fe4af6c8a635f4eac6ab20dbc1f251d299dc3a
[ "MIT" ]
null
null
null
Rush/Platform.cpp
kayru/librush
70fe4af6c8a635f4eac6ab20dbc1f251d299dc3a
[ "MIT" ]
4
2015-05-22T21:22:18.000Z
2019-07-31T23:18:04.000Z
#include "Platform.h" #include "GfxDevice.h" #include "UtilLog.h" #include "Window.h" namespace Rush { Window* g_mainWindow = nullptr; GfxDevice* g_mainGfxDevice = nullptr; GfxContext* g_mainGfxContext = nullptr; void Platform_Startup(const AppConfig& cfg) { RUSH_ASSERT(g_mainWindow == nullptr); RUSH_ASSERT(g_mainGfxDevice == nullptr); RUSH_ASSERT(g_mainGfxContext == nullptr); WindowDesc windowDesc; windowDesc.width = cfg.width; windowDesc.height = cfg.height; windowDesc.resizable = cfg.resizable; windowDesc.caption = cfg.name; windowDesc.fullScreen = cfg.fullScreen; windowDesc.maximized = cfg.maximized; Window* window = Platform_CreateWindow(windowDesc); g_mainWindow = window; GfxConfig gfxConfig; if (cfg.gfxConfig) { gfxConfig = *cfg.gfxConfig; } else { gfxConfig = GfxConfig(cfg); } g_mainGfxDevice = Gfx_CreateDevice(window, gfxConfig); g_mainGfxContext = Gfx_AcquireContext(); } void Platform_Shutdown() { RUSH_ASSERT(g_mainWindow != nullptr); RUSH_ASSERT(g_mainGfxDevice != nullptr); RUSH_ASSERT(g_mainGfxContext != nullptr); Gfx_Release(g_mainGfxContext); Gfx_Release(g_mainGfxDevice); g_mainWindow->release(); } int Platform_Main(const AppConfig& cfg) { Platform_Startup(cfg); if (cfg.onStartup) { cfg.onStartup(cfg.userData); } Platform_Run(cfg.onUpdate, cfg.userData); if (cfg.onShutdown) { cfg.onShutdown(cfg.userData); } Platform_Shutdown(); return 0; } }
18.846154
56
0.734694
kayru
0a13d15d930cc8b2f5140ad360b68e166490c565
1,594
cpp
C++
Chapter02/vector_access_fast_or_safe.cpp
raakasf/Cpp17-STL-Cookbook
bf889164c515094d37f18023af48fe86fcbb1824
[ "MIT" ]
480
2017-06-29T14:58:34.000Z
2022-03-29T03:22:49.000Z
Chapter02/vector_access_fast_or_safe.cpp
raakasf/Cpp17-STL-Cookbook
bf889164c515094d37f18023af48fe86fcbb1824
[ "MIT" ]
10
2017-09-06T10:33:38.000Z
2021-05-31T11:54:23.000Z
Chapter02/vector_access_fast_or_safe.cpp
raakasf/Cpp17-STL-Cookbook
bf889164c515094d37f18023af48fe86fcbb1824
[ "MIT" ]
133
2017-07-04T01:55:22.000Z
2022-03-20T12:44:54.000Z
#include <iostream> #include <vector> #include <array> #include <numeric> // for std::iota int main() { constexpr size_t container_size {1000}; #if 0 std::vector<int> v (container_size); // Fill the vector with rising numbers std::iota(std::begin(v), std::end(v), 0); // Chances are, that the following line will not lead to a crash... std::cout << "Out of range element value: " << v[container_size + 10] << "\n"; try { // This out of bounds access DOES lead to an exception... std::cout << "Out of range element value: " << v.at(container_size + 10) << "\n"; } catch (const std::out_of_range &e) { // ...which we catch here. std::cout << "Ooops, out of range access detected: " << e.what() << "\n"; } #endif // The same access methods and rules apply to std::array: std::array<int, container_size> a; // Fill the vector with rising numbers std::iota(std::begin(a), std::end(a), 0); // Chances are, that the following line will not lead to a crash... std::cout << "Out of range element value: " << a[container_size + 10] << "\n"; #if 0 try { #endif // This out of bounds access DOES lead to an exception... std::cout << "Out of range element value: " << a.at(container_size + 10) << "\n"; #if 0 } catch (const std::out_of_range &e) { // ...which we catch here. std::cout << "Ooops, out of range access detected: " << e.what() << "\n"; } #endif }
27.964912
71
0.55207
raakasf
0a14c30de50b2dc372bf05919adb74bb0807fd16
12,170
cc
C++
src/analytics/main.cc
sysbot/contrail-controller
893de3e41aa7b8e40092fba4a5da34284f5ee00f
[ "Apache-2.0" ]
1
2015-11-08T07:28:10.000Z
2015-11-08T07:28:10.000Z
src/analytics/main.cc
sysbot/contrail-controller
893de3e41aa7b8e40092fba4a5da34284f5ee00f
[ "Apache-2.0" ]
null
null
null
src/analytics/main.cc
sysbot/contrail-controller
893de3e41aa7b8e40092fba4a5da34284f5ee00f
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #include <fstream> #include <boost/asio/ip/host_name.hpp> #include <boost/program_options.hpp> #include <boost/tokenizer.hpp> #include "base/cpuinfo.h" #include "boost/python.hpp" #include "base/logging.h" #include "base/contrail_ports.h" #include "base/task.h" #include "base/task_trigger.h" #include "base/timer.h" #include "io/event_manager.h" #include <sandesh/sandesh_types.h> #include <sandesh/sandesh.h> #include <sandesh/common/vns_types.h> #include <sandesh/common/vns_constants.h> #include "gendb_if.h" #include "viz_collector.h" #include "viz_sandesh.h" #include "ruleeng.h" #include "viz_types.h" #include "analytics_cpuinfo_types.h" #include "generator.h" #include "Thrift.h" #include <base/misc_utils.h> #include <analytics/buildinfo.h> #include "discovery_client.h" #include "boost/python.hpp" using namespace ::apache::thrift; using namespace std; using boost::system::error_code; using namespace boost::asio::ip; namespace opt = boost::program_options; static TaskTrigger *collector_info_trigger; static Timer *collector_info_log_timer; static EventManager evm; bool CollectorInfoLogTimer() { collector_info_trigger->Set(); return false; } bool CollectorVersion(string &version) { return MiscUtils::GetBuildInfo(MiscUtils::Analytics, BuildInfo, version); } bool CollectorCPULogger(const string & hostname) { ModuleCpuState state; state.set_name(hostname); ModuleCpuInfo cinfo; cinfo.set_module_id( g_vns_constants.ModuleNames.find(Module::COLLECTOR)->second); CpuLoadInfo cpu_load_info; CpuLoadData::FillCpuInfo(cpu_load_info, false); cinfo.set_cpu_info(cpu_load_info); vector<ModuleCpuInfo> cciv; cciv.push_back(cinfo); state.set_module_cpu_info(cciv); state.set_collector_cpu_share(cpu_load_info.get_cpu_share()); state.set_collector_mem_virt(cpu_load_info.get_meminfo().get_virt()); ModuleCpuStateTrace::Send(state); return true; } void HandleGenCleanup(int count) { if (count) LOG(INFO, "Cleaned up " << count << " abandoned generators"); } bool CollectorSummaryLogger(Collector *collector, const string & hostname, OpServerProxy * osp) { CollectorState state; static bool first = true, build_info_set = false; state.set_name(hostname); if (first) { vector<string> ip_list; ip_list.push_back(Collector::GetSelfIp()); state.set_self_ip_list(ip_list); vector<string> list; MiscUtils::GetCoreFileList(Collector::GetProgramName(), list); if (list.size()) { state.set_core_files_list(list); } first = false; } if (!build_info_set) { string build_info_str; build_info_set = CollectorVersion(build_info_str); state.set_build_info(build_info_str); } std::vector<GeneratorSummaryInfo> infos; collector->GetGeneratorSummaryInfo(infos); // The generator keys must be refreshed to prove that this Vizd // instance owns its generators for (vector<GeneratorSummaryInfo>::const_iterator it = infos.begin(); it != infos.end(); it++) { osp->RefreshGenerator(it->get_source(), it->get_module_id()); } osp->GeneratorCleanup(HandleGenCleanup); state.set_generator_infos(infos); CollectorInfo::Send(state); return true; } bool CollectorInfoLogger(VizSandeshContext &ctx) { VizCollector *analytics = ctx.Analytics(); CollectorState state; CollectorCPULogger(analytics->name()); CollectorSummaryLogger(analytics->GetCollector(), analytics->name(), analytics->GetOsp()); state.set_name(analytics->name()); vector<ModuleServerState> sinfos; analytics->GetCollector()->GetGeneratorSandeshStatsInfo(sinfos); for (uint i =0 ; i< sinfos.size(); i++) { SandeshModuleServerTrace::Send(sinfos[i]); } collector_info_log_timer->Cancel(); collector_info_log_timer->Start(60*1000, boost::bind(&CollectorInfoLogTimer), NULL); return true; } // Trigger graceful shutdown of collector process. // // IO (evm) is shutdown first. Afterwards, main() resumes, shutting down rest of the // objects, and eventually exit()s. void CollectorShutdown() { static bool shutdown_; if (shutdown_) return; shutdown_ = true; // Shutdown event manager first to stop all IO activities. evm.Shutdown(); } static void terminate(int param) { CollectorShutdown(); } static void ShutdownDiscoveryClient(DiscoveryServiceClient *client) { if (client) { client->Shutdown(); delete client; } } // Shutdown various objects used in the collector. static void ShutdownServers(VizCollector *viz_collector, DiscoveryServiceClient *client) { // Shutdown discovery client first ShutdownDiscoveryClient(client); viz_collector->Shutdown(); TimerManager::DeleteTimer(collector_info_log_timer); delete collector_info_trigger; VizCollector::WaitForIdle(); Sandesh::Uninit(); VizCollector::WaitForIdle(); } // This is to force vizd to wait for a gdbattach // before proceeding. // It will make it easier to debug vizd during systest volatile int gdbhelper = 1; int main(int argc, char *argv[]) { const string default_log_file = "<stdout>"; while (gdbhelper==0) { usleep(1000); } opt::options_description desc("Command line options"); desc.add_options() ("help", "help message") ("cassandra-server-list", opt::value<vector<string> >()->default_value( std::vector<std::string>(), "127.0.0.1:9160"), "cassandra server list") ("analytics-data-ttl", opt::value<int>()->default_value(g_viz_constants.AnalyticsTTL), "global TTL(days) for analytics data") ("discovery-server", opt::value<string>(), "IP address of Discovery Server") ("discovery-port", opt::value<int>()->default_value(ContrailPorts::DiscoveryServerPort), "Port of Discovery Server") ("redis-ip", opt::value<string>()->default_value("127.0.0.1"), "redis server ip") ("redis-port", opt::value<int>()->default_value(ContrailPorts::RedisUvePort), "redis server port") ("listen-port", opt::value<int>()->default_value(ContrailPorts::CollectorPort), "vizd listener port") ("host-ip", opt::value<string>(), "IP address of Analytics Node") ("http-server-port", opt::value<int>()->default_value(ContrailPorts::HttpPortCollector), "Sandesh HTTP listener port") ("dup", "Internal use") ("gen-timeout", opt::value<int>()->default_value(80), "Expiration timeout for generators") ("log-local", "Enable local logging of sandesh messages") ("log-level", opt::value<string>()->default_value("SYS_DEBUG"), "Severity level for local logging of sandesh messages") ("log-category", opt::value<string>()->default_value(""), "Category filter for local logging of sandesh messages") ("log-file", opt::value<string>()->default_value(default_log_file), "Filename for the logs to be written to") ("version", "Display version information") ; opt::variables_map var_map; opt::store(opt::parse_command_line(argc, argv, desc), var_map); opt::notify(var_map); if (var_map.count("help")) { cout << desc << endl; exit(0); } if (var_map.count("version")) { string build_info_str; CollectorVersion(build_info_str); cout << build_info_str << endl; exit(0); } Collector::SetProgramName(argv[0]); if (var_map["log-file"].as<string>() == default_log_file) { LoggingInit(); } else { LoggingInit(var_map["log-file"].as<string>()); } vector<string> cassandra_server_list( var_map["cassandra-server-list"].as<vector<string> >()); string cassandra_server; if (cassandra_server_list.empty()) { cassandra_server = "127.0.0.1:9160"; } else { cassandra_server = cassandra_server_list[0]; } typedef boost::tokenizer<boost::char_separator<char> > tokenizer; boost::char_separator<char> sep(":"); tokenizer tokens(cassandra_server, sep); tokenizer::iterator it = tokens.begin(); std::string cassandra_ip(*it); ++it; std::string port(*it); int cassandra_port; stringToInteger(port, cassandra_port); bool dup = false; if (var_map.count("dup")) { dup = true; } LOG(INFO, "COLLECTOR LISTEN PORT: " << var_map["listen-port"].as<int>()); LOG(INFO, "COLLECTOR REDIS SERVER: " << var_map["redis-ip"].as<string>()); LOG(INFO, "COLLECTOR REDIS PORT: " << var_map["redis-port"].as<int>()); LOG(INFO, "COLLECTOR CASSANDRA SERVER: " << cassandra_ip); LOG(INFO, "COLLECTOR CASSANDRA PORT: " << cassandra_port); VizCollector analytics(&evm, var_map["listen-port"].as<int>(), cassandra_ip, cassandra_port, var_map["redis-ip"].as<string>(), var_map["redis-port"].as<int>(), var_map["gen-timeout"].as<int>(), dup, var_map["analytics-data-ttl"].as<int>()); #if 0 // initialize python/c++ API Py_InitializeEx(0); // insert the patch where scripts are placed // temporary it is env variable RULEENGPATH char *rpath = getenv("RULEENGPATH"); if (rpath != NULL) { PyObject* sysPath = PySys_GetObject((char*)"path"); PyList_Insert(sysPath, 0, PyString_FromString(rpath)); } #endif analytics.Init(); VizSandeshContext vsc(&analytics); Sandesh::InitCollector( g_vns_constants.ModuleNames.find(Module::COLLECTOR)->second, analytics.name(), &evm, "127.0.0.1", var_map["listen-port"].as<int>(), var_map["http-server-port"].as<int>(), &vsc); Sandesh::SetLoggingParams(var_map.count("log"), var_map["log-category"].as<string>(), var_map["log-level"].as<string>()); //Publish services to Discovery Service Servee DiscoveryServiceClient *ds_client = NULL; if (var_map.count("discovery-server")) { tcp::endpoint dss_ep; error_code error; dss_ep.address(address::from_string(var_map["discovery-server"].as<string>(), error)); dss_ep.port(var_map["discovery-port"].as<int>()); ds_client = new DiscoveryServiceClient(&evm, dss_ep); ds_client->Init(); // Get local ip address string self_ip; if (var_map.count("host-ip")) { self_ip = var_map["host-ip"].as<string>(); } else { tcp::resolver resolver(*evm.io_service()); tcp::resolver::query query(boost::asio::ip::host_name(), ""); tcp::resolver::iterator iter = resolver.resolve(query); self_ip = iter->endpoint().address().to_string(); } Collector::SetSelfIp(self_ip); stringstream pub_ss; string sname = g_vns_constants.ModuleNames.find(Module::COLLECTOR)->second; pub_ss << "<" << sname << "><ip-address>" << self_ip << "</ip-address><port>" << var_map["listen-port"].as<int>() << "</port></" << sname << ">"; std::string pub_msg; pub_msg = pub_ss.str(); ds_client->Publish(DiscoveryServiceClient::CollectorService, pub_msg); } CpuLoadData::Init(); collector_info_trigger = new TaskTrigger(boost::bind(&CollectorInfoLogger, vsc), TaskScheduler::GetInstance()->GetTaskId("vizd::Stats"), 0); collector_info_log_timer = TimerManager::CreateTimer(*evm.io_service(), "Collector Info log timer"); collector_info_log_timer->Start(5*1000, boost::bind(&CollectorInfoLogTimer), NULL); signal(SIGTERM, terminate); evm.Run(); ShutdownServers(&analytics, ds_client); return 0; }
32.98103
94
0.642317
sysbot
0a168dcda9d9249f937af3534e479e275c1f2bfb
2,429
cpp
C++
test/testjson.cpp
StuffByDavid/Base
d37713fcf48655cb49032c576a1586c135e2e83d
[ "MIT" ]
null
null
null
test/testjson.cpp
StuffByDavid/Base
d37713fcf48655cb49032c576a1586c135e2e83d
[ "MIT" ]
null
null
null
test/testjson.cpp
StuffByDavid/Base
d37713fcf48655cb49032c576a1586c135e2e83d
[ "MIT" ]
null
null
null
#include "test.hpp" #include "file/json.hpp" #include "util/timer.hpp" void Base::TestApp::testJSON() { cout << "testJSON" << endl; // Loading and saving try { Timer t1("JSON load"); JsonFile jf(((TextFile*)resHandler->get("hello.json"))->getText()); t1.stopAndPrint(); Timer t2("JSON save"); jf.save(FilePath("C:/Dev/Builds/base/out.json")); t2.stopAndPrint(); cout << "foo: " << jf.getString("foo") << endl; cout << "Bar: " << jf.getNumber("Bar") << endl; JsonArray* arr = jf.getArray("Array"); cout << "Array length: " << arr->getCount() << endl; cout << " 0: " << arr->getNumber(0) << endl; cout << " 1: " << arr->getNumber(1) << endl; cout << " 2: " << arr->getString(2) << endl; cout << " 2 isNull: " << (arr->isNull(2) ? "true": "false") << endl; JsonObject* obj = jf.getArray("Objects")->getObject(0); cout << "Object int: " << obj->getNumber("int") << endl; cout << "Object float: " << obj->getNumber("float") << endl; cout << "Object str: " << obj->getString("str") << endl; cout << "Object multilinestr: " << obj->getString("multilinestr") << endl; cout << "Object multilinestr isNull: " << (obj->isNull("multilinestr") ? "true": "false") << endl; cout << "Object null isNull: " << (obj->isNull("null") ? "true": "false") << endl; cout << "Object bool: " << (obj->getBool("bool") ? "true": "false") << endl; //JsonObject* nonExistant = jf.getArray("Objects")->getObject(1); jf.save(FilePath("C:/Dev/Builds/base/out1.json")); } catch (const JsonException& ex) { cout << ex.what() << endl; } // Generating try { Timer t1("JSON generate"); JsonFile jf; JsonArray* arr = jf.addArray("elements"); repeat (5) { JsonObject* obj = arr->addObject(); obj->addString("name", "HelloWorld"); obj->addNumber("value", 14052); obj->addObject("sub")->addNumber("cost", 100); obj->addNull("null example"); } t1.stopAndPrint(); Timer t2("JSON save"); jf.save(FilePath("C:/Dev/Builds/base/out2.json")); t2.stopAndPrint(); } catch (const JsonException& ex) { cout << ex.what() << endl; } cout << std::flush; }
32.824324
106
0.515438
StuffByDavid
0a174cfa21c3f4ce6d344c80a5f79f8b13fc4911
2,179
cpp
C++
kernel/archive/vga_text_buffer.cpp
drali/danos
874438cf8c3331baaa3e6250fbadcbeaf240d75e
[ "MIT" ]
null
null
null
kernel/archive/vga_text_buffer.cpp
drali/danos
874438cf8c3331baaa3e6250fbadcbeaf240d75e
[ "MIT" ]
null
null
null
kernel/archive/vga_text_buffer.cpp
drali/danos
874438cf8c3331baaa3e6250fbadcbeaf240d75e
[ "MIT" ]
null
null
null
#include "vga_text_buffer.h" #include "kernel/io.h" #include "core/types.h" namespace danos { VgaTextBuffer::VgaTextBuffer(const VgaColor background, const VgaColor foreground) { this->Clear(); this->SetColors(background, foreground); this->UpdateCursor(); } void VgaTextBuffer::UpdateCursor() const { const Uint16 pos = current_row_ * kVgaWidth + current_column_; IO::Out(0x3D4, 0x0F); IO::Out(0x3D5, (Uint8) (pos & 0xFF)); IO::Out(0x3D4, 0x0E); IO::Out(0x3D5, (Uint8) ((pos >> 8) & 0xFF)); } void VgaTextBuffer::SetColors(const VgaColor background, const VgaColor foreground) { for (Uint32 height = 0; height < kVgaHeight; ++height) { for (Uint32 width = 0; width < kVgaWidth; ++width) { buffer_[height * kVgaWidth + width].color = (Uint8)((Uint8)background << 4) | ((Uint8)foreground & 0x0f); } } } void VgaTextBuffer::Clear() { for (Uint32 height = 0; height < kVgaHeight; ++height) { for (Uint32 width = 0; width < kVgaWidth; ++width) { buffer_[height * kVgaWidth + width].value = ' '; } } current_column_ = 0; current_row_ = 0; this->UpdateCursor(); } void VgaTextBuffer::IncreaseRow() { if ((current_row_ + 1) == kVgaHeight) { for (Uint32 i = 0; i < (kVgaHeight - 1); ++i) { for (Uint32 j = 0; j < kVgaWidth; ++j) { buffer_[i * kVgaWidth + j] = buffer_[(i + 1) * kVgaWidth + j]; } } for (Uint32 i = 0; i < kVgaWidth; ++i) { buffer_[(kVgaHeight - 1) * kVgaWidth + i].value = ' '; } } else { current_row_++; } current_column_ = 0; } void VgaTextBuffer::Print(const Char value) { if (value == '\n') { this->IncreaseRow(); this->UpdateCursor(); return; } buffer_[current_row_ * kVgaWidth + current_column_].value = value; current_column_++; if (current_column_ == kVgaWidth) { this->IncreaseRow(); } this->UpdateCursor(); } void VgaTextBuffer::Print(const Char* string) { while (*string != '\0') { this->Print(*string); string++; } } } // namespace danos
26.901235
117
0.57687
drali
0a1a92656c83521198200ea0471eb3cf9e33d76e
15,622
cpp
C++
project/Harman_T500/testform.cpp
happyrabbit456/Qt5_dev
1812df2f04d4b6d24eaf0195ae25d4c67d4f3da2
[ "MIT" ]
null
null
null
project/Harman_T500/testform.cpp
happyrabbit456/Qt5_dev
1812df2f04d4b6d24eaf0195ae25d4c67d4f3da2
[ "MIT" ]
null
null
null
project/Harman_T500/testform.cpp
happyrabbit456/Qt5_dev
1812df2f04d4b6d24eaf0195ae25d4c67d4f3da2
[ "MIT" ]
null
null
null
#include "testform.h" #include "ui_testform.h" #include "mainwindow.h" TestForm::TestForm(QWidget *parent) : QWidget(parent), ui(new Ui::TestForm) { ui->setupUi(this); m_mapString.insert(1,tr("Please set the parameters, then click Test button, the test can begin to go. ")); resetTestHandle(); clearMessagebox(); appendMessagebox(m_mapString[1]); } TestForm::~TestForm() { delete ui; } bool TestForm::updateIdleCurrent(bool bOK, string str) { if(bOK){ double d=atof(str.c_str()); d=qAbs(d*1000*1000); //uA QString qstr=QString().sprintf("%5.3f",qAbs(d)); ui->editIdleCurrent->setText(qstr); m_idlecurrent=qstr; if(d<m_dMinIdleCurrent || d>m_dMaxIdleCurrent){ m_idlecurrentpf="F"; ui->labelIdleCurrentStatus->setVisible(true); ui->labelIdleCurrentStatus->setStyleSheet("color: rgb(255, 192, 128);background:red"); ui->labelIdleCurrentStatus->setText("Fail"); QString strValue=QString("The idle current value is %1 uA , threshold exceeded, the test fail.").arg(qstr); appendMessagebox(strValue); } else{ m_idlecurrentpf="P"; ui->labelIdleCurrentStatus->setVisible(true); ui->labelIdleCurrentStatus->setStyleSheet("color: rgb(255, 192, 128);background:green"); ui->labelIdleCurrentStatus->setText("Pass"); QString strValue=QString("The idle current value is %1 uA , the test pass.").arg(qstr); appendMessagebox(strValue); } return true; } return false; } bool TestForm::updateWorkCurrent(bool bOK, string str) { if(bOK){ double d=atof(str.c_str()); d=qAbs(d*1000); //mA QString qstr=QString().sprintf("%5.3f",qAbs(d)); ui->editWorkCurrent->setText(qstr); m_workcurrent=qstr; if(d<m_dMinWorkCurrent || d>m_dMaxWorkCurrent){ m_workcurrentpf="F"; ui->labelWorkCurrentStatus->setVisible(true); ui->labelWorkCurrentStatus->setStyleSheet("color: rgb(255, 192, 128);background:red"); ui->labelWorkCurrentStatus->setText("Fail"); QString strValue=QString("The work current value is %1 mA , threshold exceeded, the test fail.").arg(qstr); appendMessagebox(strValue); } else{ m_workcurrentpf="P"; ui->labelWorkCurrentStatus->setVisible(true); ui->labelWorkCurrentStatus->setStyleSheet("color: rgb(255, 192, 128);background:green"); ui->labelWorkCurrentStatus->setText("Pass"); QString strValue=QString("The work current value is %1 mA , the test pass.").arg(qstr); appendMessagebox(strValue); } return true; } return false; } bool TestForm::updateChargeCurrent(bool bOK, string str) { if(bOK){ double d=atof(str.c_str()); d=qAbs(d*1000); //mA QString qstr=QString().sprintf("%5.3f",qAbs(d)); ui->editChargeCurrent->setText(qstr); m_chargecurrent=qstr; if(d<m_dMinChargeCurrent || d>m_dMaxChargeCurrent){ m_chargecurrentpf="F"; ui->labelChargeCurrentStatus->setVisible(true); ui->labelChargeCurrentStatus->setStyleSheet("color: rgb(255, 192, 128);background:red"); ui->labelChargeCurrentStatus->setText("Fail"); QString strValue=QString("The charge current value is %1 mA , threshold exceeded, the test fail.").arg(qstr); appendMessagebox(strValue); } else{ m_chargecurrentpf="P"; ui->labelChargeCurrentStatus->setVisible(true); ui->labelChargeCurrentStatus->setStyleSheet("color: rgb(255, 192, 128);background:green"); ui->labelChargeCurrentStatus->setText("Pass"); QString strValue=QString("The charge current value is %1 mA , the test pass.").arg(qstr); appendMessagebox(strValue); } //update result label if(m_idlecurrentpf.compare("P")==0 &&m_workcurrentpf.compare("P")==0 &&m_chargecurrentpf.compare("P")==0){ m_pf="P"; ui->labelResultStatus->setVisible(true); ui->labelResultStatus->setStyleSheet("color: rgb(255, 192, 128);background:green"); ui->labelResultStatus->setText("Pass"); } else{ m_pf="F"; ui->labelResultStatus->setVisible(true); ui->labelResultStatus->setStyleSheet("color: rgb(255, 192, 128);background:red"); ui->labelResultStatus->setText("Fail"); } return true; } return false; } bool TestForm::insertRecordHandle() { QString strQuery; bool ret=false; MainWindow* pMainWindow=MainWindow::getMainWindow(); int nSupportDatabase =pMainWindow->getSupportDatabase(); if(pMainWindow!=nullptr && (nSupportDatabase==enum_SQLite||nSupportDatabase==enum_SQLite_MSSQL)){ if(pMainWindow->m_bSQLLiteConnection){ // QString strTIME="(select strftime('%Y/%m/%d %H:%M','now','localtime'))"; QDateTime z_curDateTime = QDateTime::currentDateTime(); QString strTIME = z_curDateTime.toString(tr("yyyy/MM/dd hh:mm")); // strQuery = QString("%1 %2 '%3', '%4', '%5', '%6', '%7', '%8', '%9', '%10', '%11', '%12', '%13', '%14', '%15', '%16')") strQuery = QString("%1 '%2', '%3', '%4', '%5', '%6', '%7', '%8', '%9', '%10', '%11', '%12', '%13', '%14', '%15', '%16')") .arg("insert into currentrecord values(NULL,") // .arg("(select strftime('%Y/%m/%d %H:%M','now','localtime')),") .arg(strTIME) .arg(m_sn) .arg(m_idlecurrent) .arg(m_idlecurrentpf) .arg(m_workcurrent) .arg(m_workcurrentpf) .arg(m_chargecurrent) .arg(m_chargecurrentpf) .arg(QString().sprintf("%5.3f",m_dMinIdleCurrent)) .arg(QString().sprintf("%5.3f",m_dMaxIdleCurrent)) .arg(QString().sprintf("%5.3f",m_dMinWorkCurrent)) .arg(QString().sprintf("%5.3f",m_dMaxWorkCurrent)) .arg(QString().sprintf("%5.3f",m_dMinChargeCurrent)) .arg(QString().sprintf("%5.3f",m_dMaxChargeCurrent)) .arg(m_pf); qDebug()<<strQuery; bool bInsertRecord=pMainWindow->m_querySQLite.exec(strQuery); if(!bInsertRecord){ qDebug() << pMainWindow->m_querySQLite.lastError(); QMessageBox::warning(this,"warning",pMainWindow->m_querySQLite.lastError().text()); } else{ //直接写到文件 writeRecordToExcel(strTIME); return true; } } } if(pMainWindow!=nullptr && (nSupportDatabase==enum_MSSQL||nSupportDatabase==enum_SQLite_MSSQL)){ if(pMainWindow->m_bMSSQLConnection){ QString strTIME="(select CONVERT(varchar(100) , getdate(), 111 )+' '+ Datename(hour,GetDate())+ ':'+Datename(minute,GetDate()))"; } } return ret; } bool TestForm::conclusionHandle() { // ui->tableView->setUpdatesEnabled(false);//暂停界面刷新 bool bInsert=insertRecordHandle(); if(bInsert){ appendMessagebox("The test record is success to insert database."); QString str=QString().sprintf("The test record is success to save to local file. The dir path: %s .","D:\\database\\Harman_T500"); appendMessagebox(str); emit updateDatabaseTabelView(); } else{ appendMessagebox("The test record is fail to insert database and save to local file. "); } return bInsert; } bool TestForm::getCurrentTestConclusion(QString &idleDCStatus, QString &workDCStatus, QString &chargeDCStatus) { idleDCStatus=m_idlecurrentpf; workDCStatus=m_workcurrentpf; chargeDCStatus=m_chargecurrentpf; return true; } void TestForm::writeOnewRecord(QXlsx::Document &xlsx,int rowCount,int columnCount, QString strTIME,QVariant newIDValue) { int i=rowCount; for(int j=1;j<=columnCount;j++){ switch (j) { case 1: xlsx.write(i + 1, j,newIDValue); break; case 2: xlsx.write(i + 1, j,strTIME); break; case 3: xlsx.write(i + 1, j,m_sn); break; case 4: xlsx.write(i + 1, j,m_idlecurrent); break; case 5: xlsx.write(i + 1, j,m_idlecurrentpf); break; case 6: xlsx.write(i + 1, j,m_workcurrent); break; case 7: xlsx.write(i + 1, j,m_workcurrentpf); break; case 8: xlsx.write(i + 1, j,m_chargecurrent); break; case 9: xlsx.write(i + 1, j,m_chargecurrentpf); break; case 10: xlsx.write(i + 1, j,QString().sprintf("%5.3f",m_dMinIdleCurrent)); break; case 11: xlsx.write(i + 1, j,QString().sprintf("%5.3f",m_dMaxIdleCurrent)); break; case 12: xlsx.write(i + 1, j,QString().sprintf("%5.3f",m_dMinWorkCurrent)); break; case 13: xlsx.write(i + 1, j,QString().sprintf("%5.3f",m_dMaxWorkCurrent)); break; case 14: xlsx.write(i + 1, j,QString().sprintf("%5.3f",m_dMinChargeCurrent)); break; case 15: xlsx.write(i + 1, j,QString().sprintf("%5.3f",m_dMaxChargeCurrent)); break; case 16: xlsx.write(i + 1, j,m_pf); break; } } } void TestForm::appendMessagebox(QString str) { ui->editMessagebox->appendPlainText(str); } void TestForm::clearMessagebox() { ui->editMessagebox->clear(); } void TestForm::writeRecordToExcel(QString strTIME) { //直接写到文件 QString strDatabaseDir=QString().sprintf("%s","D:\\database\\Harman_T500"); QDateTime z_curDateTime = QDateTime::currentDateTime(); QString z_strCurTime = z_curDateTime.toString(tr("yyyyMMdd")); QString fileName = strDatabaseDir+"\\"+QString("dc") + "_" + z_strCurTime + tr(".xlsx"); qDebug()<<"fileName:"<<fileName; QDir dir(strDatabaseDir); if(!dir.exists()){ bool ok = dir.mkpath(strDatabaseDir);//创建多级目录 qDebug()<<"dir.mkpath(strDatabaseDir) ok:"<<ok; } qDebug()<<"dir.exists() true"; QFile file(fileName); if(file.exists()) { qDebug()<<"file.exists() true"; //存在文件 QXlsx::Document xlsx(fileName); //OK QXlsx::Workbook *workBook = xlsx.workbook(); QXlsx::Worksheet *workSheet = static_cast<QXlsx::Worksheet*>(workBook->sheet(0)); qDebug()<<"rowCount:"<<workSheet->dimension().rowCount(); qDebug()<<"columnCount:"<<workSheet->dimension().columnCount(); int rowCount=workSheet->dimension().rowCount(); int columnCount=workSheet->dimension().columnCount(); QVariant lastid= xlsx.read(rowCount,1); int newid=lastid.toInt()+1; QVariant newIDValue(newid); writeOnewRecord(xlsx,rowCount,columnCount, strTIME,newIDValue); xlsx.save(); } else{ //不存在文件 QXlsx::Document z_xlsx; QStringList z_titleList; QXlsx::Format format1;/*设置该单元的样式*/ format1.setFontColor(QColor(Qt::blue));/*文字为红色*/ // format1.setPatternBackgroundColor(QColor(152,251,152));/*北京颜色*/ format1.setFontSize(15);/*设置字体大小*/ format1.setHorizontalAlignment(QXlsx::Format::AlignHCenter);/*横向居中*/ format1.setBorderStyle(QXlsx::Format::BorderThin);//QXlsx::Format::BorderDashDotDot);/*边框样式*/ // 设置excel任务标题 z_titleList << "id" << "time" << "sn" << "idlecurrent"<<"idlecurrentpf" <<"workcurrent"<<"workcurrentpf"<<"chargecurrent"<< "chargecurrentpf" << "idlemincurrent"<<"idlemaxcurrent"<<"workmincurrent"<<"workmaxcurrent" <<"chargemincurrent"<<"chargemaxcurrent"<<"pf"; for (int i = 0; i < z_titleList.size(); i++) { // z_xlsx.write(1, i+1, z_titleList.at(i)); z_xlsx.write(1, i+1, z_titleList.at(i),format1); } // 设置烈宽 for(int i=1;i<17;i++){ if(i==2 || i==3){ z_xlsx.setColumnWidth(i, 30); } else{ z_xlsx.setColumnWidth(i, 30); } } int rowCount=2; int columnCount=16; int newid=1; QVariant newIDValue(newid); writeOnewRecord(z_xlsx,rowCount,columnCount, strTIME,newIDValue); // 保存文件 z_xlsx.saveAs(fileName); } } void TestForm::resetTestHandle() { ui->labelIdleCurrentStatus->setVisible(false); ui->labelWorkCurrentStatus->setVisible(false); ui->labelChargeCurrentStatus->setVisible(false); ui->editIdleCurrent->setText("0.000"); ui->editWorkCurrent->setText("0.000"); ui->editChargeCurrent->setText("0.000"); ui->labelResultStatus->setVisible(false); } void TestForm::on_btnReset_clicked() { resetTestHandle(); clearMessagebox(); appendMessagebox(m_mapString[1]); #ifdef USE_WIZARD if(m_wizard!=nullptr){ if(m_wizard->currentId()>-1){ m_wizard->setVisible(false); m_wizard->close(); } } #endif } void TestForm::on_btnTest_clicked() { resetTestHandle(); MainWindow *pMainWindow=MainWindow::getMainWindow(); if(pMainWindow->m_niVisaGPIB.m_mapGPIB.count()<=0){ QMessageBox::warning(nullptr,"warning","Could not open a session to the VISA Resource Manager!\n"); return; } #ifdef USE_WIZARD m_wizard=new QWizard(this); m_wizard->addPage(new SNPage(this)); m_wizard->addPage(new IdleCurrentPage(this)); m_wizard->addPage(new WorkCurrentPage(this)); m_wizard->addPage(new ChargeCurrentPage(this)); m_wizard->addPage(new ConclusionPage(this)); //设置导航样式 m_wizard->setWizardStyle( QWizard::ModernStyle ); //去掉向导页面按钮 m_wizard->setOption( QWizard::NoBackButtonOnStartPage ); m_wizard->setOption( QWizard::NoBackButtonOnLastPage ); m_wizard->setOption( QWizard::NoCancelButton ); //去掉BackButton QList<QWizard::WizardButton> layout; layout << QWizard::Stretch // << QWizard::BackButton << QWizard::CancelButton << QWizard::NextButton << QWizard::FinishButton; m_wizard->setButtonLayout(layout); m_wizard->resize(320,160); QPoint pos=pMainWindow->pos(); QSize size=pMainWindow->size(); pos.setX(pos.x()+size.width()+5); pos.setY(pos.y()); m_wizard->move(pos); //禁用/隐藏/删除Qt对话框“标题栏”上的“?”帮助按钮这些按钮! Qt::WindowFlags flags = m_wizard->windowFlags(); Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint; flags = flags & (~helpFlag); m_wizard->setWindowFlags(flags); m_wizard->setWindowTitle(QString::fromLocal8Bit("电流测试向导")); m_wizard->show(); #else m_snDlg=new SNDialog(this); //禁用/隐藏/删除Qt对话框“标题栏”上的“?”帮助按钮这些按钮! Qt::WindowFlags flags = m_snDlg->windowFlags(); Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint; flags = flags & (~helpFlag); m_snDlg->setWindowFlags(flags); m_snDlg->setWindowTitle("Get scan code"); m_snDlg->show(); #endif }
32.545833
144
0.588657
happyrabbit456
0a1acd486ffe2573706c39d2cc80b8c72acee621
307
cpp
C++
examples/example1.cpp
Lallapallooza/YACL
4f2d56b5aef835e3da9aacf018e63f1a41316df7
[ "MIT" ]
11
2018-08-19T00:07:12.000Z
2021-01-08T05:28:11.000Z
examples/example1.cpp
Lallapallooza/YACL
4f2d56b5aef835e3da9aacf018e63f1a41316df7
[ "MIT" ]
null
null
null
examples/example1.cpp
Lallapallooza/YACL
4f2d56b5aef835e3da9aacf018e63f1a41316df7
[ "MIT" ]
2
2018-08-19T08:01:33.000Z
2018-08-22T15:50:18.000Z
#include <iostream> #include <YACL/config.h> // CONFIG_PATH setted in CMakeLists.txt const std::string config_path = CONFIG_PATH; int main() { const yacl::SettingsUniquePtr root = yacl::Config::parseConfigFromFile(config_path + "/example.yacl"); yacl::Config::printConfig(*root); return 0; }
19.1875
69
0.71987
Lallapallooza