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
d78d1b0b34b8318286f233a42437759cf5b5c652
15,254
cpp
C++
src/system/kernel/posix/realtime_sem.cpp
waddlesplash/haiku
68d1b97e4f99fa0f190579f7ffd16fceda23ebce
[ "MIT" ]
2
2021-11-30T22:17:42.000Z
2022-02-04T20:57:17.000Z
src/system/kernel/posix/realtime_sem.cpp
grexe/haiku
4b0d8831c29fde017869ac7e77fdf7871bbc4b10
[ "MIT" ]
null
null
null
src/system/kernel/posix/realtime_sem.cpp
grexe/haiku
4b0d8831c29fde017869ac7e77fdf7871bbc4b10
[ "MIT" ]
null
null
null
/* * Copyright 2008-2011, Ingo Weinhold, ingo_weinhold@gmx.de. * Distributed under the terms of the MIT License. */ #include <posix/realtime_sem.h> #include <string.h> #include <new> #include <OS.h> #include <AutoDeleter.h> #include <fs/KPath.h> #include <kernel.h> #include <lock.h> #include <syscall_restart.h> #include <team.h> #include <thread.h> #include <util/atomic.h> #include <util/AutoLock.h> #include <util/OpenHashTable.h> #include <util/StringHash.h> namespace { class SemInfo { public: SemInfo() : fSemaphoreID(-1) { } virtual ~SemInfo() { if (fSemaphoreID >= 0) delete_sem(fSemaphoreID); } sem_id SemaphoreID() const { return fSemaphoreID; } status_t Init(int32 semCount, const char* name) { fSemaphoreID = create_sem(semCount, name); if (fSemaphoreID < 0) return fSemaphoreID; return B_OK; } virtual sem_id ID() const = 0; virtual SemInfo* Clone() = 0; virtual void Delete() = 0; private: sem_id fSemaphoreID; }; class NamedSem : public SemInfo { public: NamedSem() : fName(NULL), fRefCount(1) { } virtual ~NamedSem() { free(fName); } const char* Name() const { return fName; } status_t Init(const char* name, mode_t mode, int32 semCount) { status_t error = SemInfo::Init(semCount, name); if (error != B_OK) return error; fName = strdup(name); if (fName == NULL) return B_NO_MEMORY; fUID = geteuid(); fGID = getegid(); fPermissions = mode; return B_OK; } void AcquireReference() { atomic_add(&fRefCount, 1); } void ReleaseReference() { if (atomic_add(&fRefCount, -1) == 1) delete this; } bool HasPermissions() const { if ((fPermissions & S_IWOTH) != 0) return true; uid_t uid = geteuid(); if (uid == 0 || (uid == fUID && (fPermissions & S_IWUSR) != 0)) return true; gid_t gid = getegid(); if (gid == fGID && (fPermissions & S_IWGRP) != 0) return true; return false; } virtual sem_id ID() const { return SemaphoreID(); } virtual SemInfo* Clone() { AcquireReference(); return this; } virtual void Delete() { ReleaseReference(); } NamedSem*& HashLink() { return fHashLink; } private: char* fName; int32 fRefCount; uid_t fUID; gid_t fGID; mode_t fPermissions; NamedSem* fHashLink; }; struct NamedSemHashDefinition { typedef const char* KeyType; typedef NamedSem ValueType; size_t HashKey(const KeyType& key) const { return hash_hash_string(key); } size_t Hash(NamedSem* semaphore) const { return HashKey(semaphore->Name()); } bool Compare(const KeyType& key, NamedSem* semaphore) const { return strcmp(key, semaphore->Name()) == 0; } NamedSem*& GetLink(NamedSem* semaphore) const { return semaphore->HashLink(); } }; class GlobalSemTable { public: GlobalSemTable() : fSemaphoreCount(0) { mutex_init(&fLock, "global named sem table"); } ~GlobalSemTable() { mutex_destroy(&fLock); } status_t Init() { return fNamedSemaphores.Init(); } status_t OpenNamedSem(const char* name, int openFlags, mode_t mode, uint32 semCount, NamedSem*& _sem, bool& _created) { MutexLocker _(fLock); NamedSem* sem = fNamedSemaphores.Lookup(name); if (sem != NULL) { if ((openFlags & O_EXCL) != 0) return EEXIST; if (!sem->HasPermissions()) return EACCES; sem->AcquireReference(); _sem = sem; _created = false; return B_OK; } if ((openFlags & O_CREAT) == 0) return ENOENT; // does not exist yet -- create if (fSemaphoreCount >= MAX_POSIX_SEMS) return ENOSPC; sem = new(std::nothrow) NamedSem; if (sem == NULL) return B_NO_MEMORY; status_t error = sem->Init(name, mode, semCount); if (error != B_OK) { delete sem; return error; } error = fNamedSemaphores.Insert(sem); if (error != B_OK) { delete sem; return error; } // add one reference for the table sem->AcquireReference(); fSemaphoreCount++; _sem = sem; _created = true; return B_OK; } status_t UnlinkNamedSem(const char* name) { MutexLocker _(fLock); NamedSem* sem = fNamedSemaphores.Lookup(name); if (sem == NULL) return ENOENT; if (!sem->HasPermissions()) return EACCES; fNamedSemaphores.Remove(sem); sem->ReleaseReference(); // release the table reference fSemaphoreCount--; return B_OK; } private: typedef BOpenHashTable<NamedSemHashDefinition, true> NamedSemTable; mutex fLock; NamedSemTable fNamedSemaphores; int32 fSemaphoreCount; }; static GlobalSemTable sSemTable; class TeamSemInfo { public: TeamSemInfo(SemInfo* semaphore, sem_t* userSem) : fSemaphore(semaphore), fUserSemaphore(userSem), fOpenCount(1) { } ~TeamSemInfo() { if (fSemaphore != NULL) fSemaphore->Delete(); } sem_id ID() const { return fSemaphore->ID(); } sem_id SemaphoreID() const { return fSemaphore->SemaphoreID(); } sem_t* UserSemaphore() const { return fUserSemaphore; } void Open() { fOpenCount++; } bool Close() { return --fOpenCount == 0; } TeamSemInfo* Clone() const { SemInfo* sem = fSemaphore->Clone(); if (sem == NULL) return NULL; TeamSemInfo* clone = new(std::nothrow) TeamSemInfo(sem, fUserSemaphore); if (clone == NULL) { sem->Delete(); return NULL; } clone->fOpenCount = fOpenCount; return clone; } TeamSemInfo*& HashLink() { return fHashLink; } private: SemInfo* fSemaphore; sem_t* fUserSemaphore; int32 fOpenCount; TeamSemInfo* fHashLink; }; struct TeamSemHashDefinition { typedef sem_id KeyType; typedef TeamSemInfo ValueType; size_t HashKey(const KeyType& key) const { return (size_t)key; } size_t Hash(TeamSemInfo* semaphore) const { return HashKey(semaphore->ID()); } bool Compare(const KeyType& key, TeamSemInfo* semaphore) const { return key == semaphore->ID(); } TeamSemInfo*& GetLink(TeamSemInfo* semaphore) const { return semaphore->HashLink(); } }; } // namespace struct realtime_sem_context { realtime_sem_context() : fSemaphoreCount(0) { mutex_init(&fLock, "realtime sem context"); } ~realtime_sem_context() { mutex_lock(&fLock); // delete all semaphores. SemTable::Iterator it = fSemaphores.GetIterator(); while (TeamSemInfo* sem = it.Next()) { // Note, this uses internal knowledge about how the iterator works. // Ugly, but there's no good alternative. fSemaphores.RemoveUnchecked(sem); delete sem; } mutex_destroy(&fLock); } status_t Init() { fNextPrivateSemID = -1; return fSemaphores.Init(); } realtime_sem_context* Clone() { // create new context realtime_sem_context* context = new(std::nothrow) realtime_sem_context; if (context == NULL) return NULL; ObjectDeleter<realtime_sem_context> contextDeleter(context); MutexLocker _(fLock); context->fNextPrivateSemID = fNextPrivateSemID; // clone all semaphores SemTable::Iterator it = fSemaphores.GetIterator(); while (TeamSemInfo* sem = it.Next()) { TeamSemInfo* clonedSem = sem->Clone(); if (clonedSem == NULL) return NULL; if (context->fSemaphores.Insert(clonedSem) != B_OK) { delete clonedSem; return NULL; } context->fSemaphoreCount++; } contextDeleter.Detach(); return context; } status_t OpenSem(const char* name, int openFlags, mode_t mode, uint32 semCount, sem_t* userSem, sem_t*& _usedUserSem, int32_t& _id, bool& _created) { NamedSem* sem = NULL; status_t error = sSemTable.OpenNamedSem(name, openFlags, mode, semCount, sem, _created); if (error != B_OK) return error; MutexLocker _(fLock); TeamSemInfo* teamSem = fSemaphores.Lookup(sem->ID()); if (teamSem != NULL) { // already open -- just increment the open count teamSem->Open(); sem->ReleaseReference(); _usedUserSem = teamSem->UserSemaphore(); _id = teamSem->ID(); return B_OK; } // not open yet -- create a new team sem // first check the semaphore limit, though if (fSemaphoreCount >= MAX_POSIX_SEMS_PER_TEAM) { sem->ReleaseReference(); if (_created) sSemTable.UnlinkNamedSem(name); return ENOSPC; } teamSem = new(std::nothrow) TeamSemInfo(sem, userSem); if (teamSem == NULL) { sem->ReleaseReference(); if (_created) sSemTable.UnlinkNamedSem(name); return B_NO_MEMORY; } error = fSemaphores.Insert(teamSem); if (error != B_OK) { delete teamSem; if (_created) sSemTable.UnlinkNamedSem(name); return error; } fSemaphoreCount++; _usedUserSem = teamSem->UserSemaphore(); _id = teamSem->ID(); return B_OK; } status_t CloseSem(sem_id id, sem_t*& deleteUserSem) { deleteUserSem = NULL; MutexLocker _(fLock); TeamSemInfo* sem = fSemaphores.Lookup(id); if (sem == NULL) return B_BAD_VALUE; if (sem->Close()) { // last reference closed fSemaphores.Remove(sem); fSemaphoreCount--; deleteUserSem = sem->UserSemaphore(); delete sem; } return B_OK; } status_t AcquireSem(sem_id id, uint32 flags, bigtime_t timeout) { MutexLocker locker(fLock); TeamSemInfo* sem = fSemaphores.Lookup(id); if (sem == NULL) return B_BAD_VALUE; else id = sem->SemaphoreID(); locker.Unlock(); status_t error = acquire_sem_etc(id, 1, flags | B_CAN_INTERRUPT, timeout); return error == B_BAD_SEM_ID ? B_BAD_VALUE : error; } status_t ReleaseSem(sem_id id) { MutexLocker locker(fLock); TeamSemInfo* sem = fSemaphores.Lookup(id); if (sem == NULL) return B_BAD_VALUE; else id = sem->SemaphoreID(); locker.Unlock(); status_t error = release_sem(id); return error == B_BAD_SEM_ID ? B_BAD_VALUE : error; } status_t GetSemCount(sem_id id, int& _count) { MutexLocker locker(fLock); TeamSemInfo* sem = fSemaphores.Lookup(id); if (sem == NULL) return B_BAD_VALUE; else id = sem->SemaphoreID(); locker.Unlock(); int32 count; status_t error = get_sem_count(id, &count); if (error != B_OK) return error; _count = count; return B_OK; } private: sem_id _NextPrivateSemID() { while (true) { if (fNextPrivateSemID >= 0) fNextPrivateSemID = -1; sem_id id = fNextPrivateSemID--; if (fSemaphores.Lookup(id) == NULL) return id; } } private: typedef BOpenHashTable<TeamSemHashDefinition, true> SemTable; mutex fLock; SemTable fSemaphores; int32 fSemaphoreCount; sem_id fNextPrivateSemID; }; // #pragma mark - implementation private static realtime_sem_context* get_current_team_context() { Team* team = thread_get_current_thread()->team; // get context realtime_sem_context* context = atomic_pointer_get( &team->realtime_sem_context); if (context != NULL) return context; // no context yet -- create a new one context = new(std::nothrow) realtime_sem_context; if (context == NULL || context->Init() != B_OK) { delete context; return NULL; } // set the allocated context realtime_sem_context* oldContext = atomic_pointer_test_and_set( &team->realtime_sem_context, context, (realtime_sem_context*)NULL); if (oldContext == NULL) return context; // someone else was quicker delete context; return oldContext; } static status_t copy_sem_name_to_kernel(const char* userName, KPath& buffer, char*& name) { if (userName == NULL) return B_BAD_VALUE; if (!IS_USER_ADDRESS(userName)) return B_BAD_ADDRESS; if (buffer.InitCheck() != B_OK) return B_NO_MEMORY; // copy userland path to kernel name = buffer.LockBuffer(); ssize_t actualLength = user_strlcpy(name, userName, buffer.BufferSize()); if (actualLength < 0) return B_BAD_ADDRESS; if ((size_t)actualLength >= buffer.BufferSize()) return ENAMETOOLONG; return B_OK; } // #pragma mark - kernel internal void realtime_sem_init() { new(&sSemTable) GlobalSemTable; if (sSemTable.Init() != B_OK) panic("realtime_sem_init() failed to init global sem table"); } void delete_realtime_sem_context(realtime_sem_context* context) { delete context; } realtime_sem_context* clone_realtime_sem_context(realtime_sem_context* context) { if (context == NULL) return NULL; return context->Clone(); } // #pragma mark - syscalls status_t _user_realtime_sem_open(const char* userName, int openFlagsOrShared, mode_t mode, uint32 semCount, sem_t* userSem, sem_t** _usedUserSem) { realtime_sem_context* context = get_current_team_context(); if (context == NULL) return B_NO_MEMORY; if (semCount > MAX_POSIX_SEM_VALUE) return B_BAD_VALUE; // userSem must always be given if (userSem == NULL) return B_BAD_VALUE; if (!IS_USER_ADDRESS(userSem)) return B_BAD_ADDRESS; // check user pointers if (_usedUserSem == NULL) return B_BAD_VALUE; if (!IS_USER_ADDRESS(_usedUserSem) || !IS_USER_ADDRESS(userName)) return B_BAD_ADDRESS; // copy name to kernel KPath nameBuffer(B_PATH_NAME_LENGTH); char* name; status_t error = copy_sem_name_to_kernel(userName, nameBuffer, name); if (error != B_OK) return error; // open the semaphore sem_t* usedUserSem; bool created = false; int32_t id; error = context->OpenSem(name, openFlagsOrShared, mode, semCount, userSem, usedUserSem, id, created); if (error != B_OK) return error; // copy results back to userland if (user_memcpy(&userSem->u.named_sem_id, &id, sizeof(int32_t)) != B_OK || user_memcpy(_usedUserSem, &usedUserSem, sizeof(sem_t*)) != B_OK) { if (created) sSemTable.UnlinkNamedSem(name); sem_t* dummy; context->CloseSem(id, dummy); return B_BAD_ADDRESS; } return B_OK; } status_t _user_realtime_sem_close(sem_id semID, sem_t** _deleteUserSem) { if (_deleteUserSem != NULL && !IS_USER_ADDRESS(_deleteUserSem)) return B_BAD_ADDRESS; realtime_sem_context* context = get_current_team_context(); if (context == NULL) return B_BAD_VALUE; // close sem sem_t* deleteUserSem; status_t error = context->CloseSem(semID, deleteUserSem); if (error != B_OK) return error; // copy back result to userland if (_deleteUserSem != NULL && user_memcpy(_deleteUserSem, &deleteUserSem, sizeof(sem_t*)) != B_OK) { return B_BAD_ADDRESS; } return B_OK; } status_t _user_realtime_sem_unlink(const char* userName) { // copy name to kernel KPath nameBuffer(B_PATH_NAME_LENGTH); char* name; status_t error = copy_sem_name_to_kernel(userName, nameBuffer, name); if (error != B_OK) return error; return sSemTable.UnlinkNamedSem(name); } status_t _user_realtime_sem_get_value(sem_id semID, int* _value) { if (_value == NULL) return B_BAD_VALUE; if (!IS_USER_ADDRESS(_value)) return B_BAD_ADDRESS; realtime_sem_context* context = get_current_team_context(); if (context == NULL) return B_BAD_VALUE; // get sem count int count; status_t error = context->GetSemCount(semID, count); if (error != B_OK) return error; // copy back result to userland if (user_memcpy(_value, &count, sizeof(int)) != B_OK) return B_BAD_ADDRESS; return B_OK; } status_t _user_realtime_sem_post(sem_id semID) { realtime_sem_context* context = get_current_team_context(); if (context == NULL) return B_BAD_VALUE; return context->ReleaseSem(semID); } status_t _user_realtime_sem_wait(sem_id semID, uint32 flags, bigtime_t timeout) { realtime_sem_context* context = get_current_team_context(); if (context == NULL) return B_BAD_VALUE; return syscall_restart_handle_post(context->AcquireSem(semID, flags, timeout)); }
18.739558
80
0.694375
waddlesplash
d78d1f9b1158a759beaa71ee7d7691a379527856
302
cpp
C++
src/Eigen-3.3/failtest/sparse_ref_1.cpp
shareq2005/CarND-MPC-Project
f4094e8b446d2fac2ca0a4c5054d5058621595b0
[ "MIT" ]
3,457
2018-06-09T15:36:42.000Z
2020-06-01T22:09:25.000Z
src/Eigen-3.3/failtest/sparse_ref_1.cpp
shareq2005/CarND-MPC-Project
f4094e8b446d2fac2ca0a4c5054d5058621595b0
[ "MIT" ]
851
2017-11-27T15:09:56.000Z
2022-03-31T22:26:38.000Z
src/Eigen-3.3/failtest/sparse_ref_1.cpp
shareq2005/CarND-MPC-Project
f4094e8b446d2fac2ca0a4c5054d5058621595b0
[ "MIT" ]
1,380
2017-06-12T23:58:23.000Z
2022-03-31T14:52:48.000Z
#include "../Eigen/Sparse" #ifdef EIGEN_SHOULD_FAIL_TO_BUILD #define CV_QUALIFIER const #else #define CV_QUALIFIER #endif using namespace Eigen; void call_ref(Ref<SparseMatrix<float> > a) { } int main() { SparseMatrix<float> a(10,10); CV_QUALIFIER SparseMatrix<float>& ac(a); call_ref(ac); }
15.894737
46
0.735099
shareq2005
d78d95b076ac1e3067c4aa1b2e0061376c602737
367
cpp
C++
ace/tao/tao/LF_Event_Loop_Thread_Helper.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
ace/tao/tao/LF_Event_Loop_Thread_Helper.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
ace/tao/tao/LF_Event_Loop_Thread_Helper.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
// -*- C++ -*- // LF_Event_Loop_Thread_Helper.cpp,v 1.2 2001/08/01 23:39:46 coryan Exp #include "tao/LF_Event_Loop_Thread_Helper.h" #if !defined (__ACE_INLINE__) # include "tao/LF_Event_Loop_Thread_Helper.inl" #endif /* __ACE_INLINE__ */ ACE_RCSID(tao, LF_Event_Loop_Thread_Helper, "LF_Event_Loop_Thread_Helper.cpp,v 1.2 2001/08/01 23:39:46 coryan Exp")
33.363636
116
0.741144
tharindusathis
d78f2fb20a09ee0b8d8f582b63c44362766ad366
2,140
cpp
C++
src/utils/i3.cpp
HughJass/polybar
a78edc667b2c347898787348c27322710d357ce6
[ "MIT" ]
102
2020-07-24T03:33:01.000Z
2022-03-29T01:21:47.000Z
src/utils/i3.cpp
HughJass/polybar
a78edc667b2c347898787348c27322710d357ce6
[ "MIT" ]
35
2020-07-17T05:46:16.000Z
2022-03-21T08:56:00.000Z
src/utils/i3.cpp
HughJass/polybar
a78edc667b2c347898787348c27322710d357ce6
[ "MIT" ]
19
2020-07-24T08:36:15.000Z
2021-12-19T18:46:47.000Z
#include <xcb/xcb.h> #include <i3ipc++/ipc.hpp> #include "common.hpp" #include "settings.hpp" #include "utils/i3.hpp" #include "utils/socket.hpp" #include "utils/string.hpp" #include "x11/connection.hpp" #include "x11/ewmh.hpp" #include "x11/icccm.hpp" POLYBAR_NS namespace i3_util { /** * Get all workspaces for given output */ vector<shared_ptr<workspace_t>> workspaces(const connection_t& conn, const string& output) { vector<shared_ptr<workspace_t>> result; for (auto&& ws : conn.get_workspaces()) { if (output.empty() || ws->output == output) { result.emplace_back(forward<decltype(ws)>(ws)); } } return result; } /** * Get currently focused workspace */ shared_ptr<workspace_t> focused_workspace(const connection_t& conn) { for (auto&& ws : conn.get_workspaces()) { if (ws->focused) { return ws; } } return nullptr; } /** * Get main root window */ xcb_window_t root_window(connection& conn) { auto children = conn.query_tree(conn.screen()->root).children(); const auto wm_name = [&](xcb_connection_t* conn, xcb_window_t win) -> string { string title; if (!(title = ewmh_util::get_wm_name(win)).empty()) { return title; } else if (!(title = icccm_util::get_wm_name(conn, win)).empty()) { return title; } else { return ""; } }; for (auto it = children.begin(); it != children.end(); it++) { if (wm_name(conn, *it) == "i3") { return *it; } } return XCB_NONE; } /** * Restack given window relative to the i3 root window * defined for the given monitor * * Fixes the issue with always-on-top window's */ bool restack_to_root(connection& conn, const xcb_window_t win) { const unsigned int value_mask = XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE; const unsigned int value_list[2]{root_window(conn), XCB_STACK_MODE_ABOVE}; if (value_list[0] != XCB_NONE) { conn.configure_window_checked(win, value_mask, value_list); return true; } return false; } } POLYBAR_NS_END
25.47619
94
0.634112
HughJass
d7909edf6498859f58ec5b5b0829689a0491d8fd
3,455
hpp
C++
src/tools/joystick_vehicle_interface_nodes/include/joystick_vehicle_interface_nodes/joystick_vehicle_interface_node.hpp
ruvus/auto
25ae62d6e575cae40212356eed43ec3e76e9a13e
[ "Apache-2.0" ]
1
2021-07-29T01:28:10.000Z
2021-07-29T01:28:10.000Z
src/tools/joystick_vehicle_interface_nodes/include/joystick_vehicle_interface_nodes/joystick_vehicle_interface_node.hpp
ruvus/auto
25ae62d6e575cae40212356eed43ec3e76e9a13e
[ "Apache-2.0" ]
null
null
null
src/tools/joystick_vehicle_interface_nodes/include/joystick_vehicle_interface_nodes/joystick_vehicle_interface_node.hpp
ruvus/auto
25ae62d6e575cae40212356eed43ec3e76e9a13e
[ "Apache-2.0" ]
1
2021-12-09T15:44:10.000Z
2021-12-09T15:44:10.000Z
// Copyright 2020-2021 the Autoware Foundation // // 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. // // Co-developed by Tier IV, Inc. and Apex.AI, Inc. #ifndef JOYSTICK_VEHICLE_INTERFACE_NODES__JOYSTICK_VEHICLE_INTERFACE_NODE_HPP_ #define JOYSTICK_VEHICLE_INTERFACE_NODES__JOYSTICK_VEHICLE_INTERFACE_NODE_HPP_ #include <joystick_vehicle_interface/joystick_vehicle_interface.hpp> #include <joystick_vehicle_interface_nodes/visibility_control.hpp> #include <mpark_variant_vendor/variant.hpp> #include <rclcpp/rclcpp.hpp> #include <memory> #include <string> #include "autoware_auto_vehicle_msgs/msg/headlights_command.hpp" using autoware::common::types::bool8_t; using joystick_vehicle_interface::Axes; using joystick_vehicle_interface::Buttons; using joystick_vehicle_interface::AxisMap; using joystick_vehicle_interface::AxisScaleMap; using joystick_vehicle_interface::ButtonMap; namespace joystick_vehicle_interface_nodes { /// A node which translates sensor_msgs/msg/Joy messages into messages compatible with the vehicle /// interface. All participants use SensorDataQoS class JOYSTICK_VEHICLE_INTERFACE_NODES_PUBLIC JoystickVehicleInterfaceNode : public ::rclcpp::Node { public: /// ROS 2 parameter constructor explicit JoystickVehicleInterfaceNode(const rclcpp::NodeOptions & node_options); private: std::unique_ptr<joystick_vehicle_interface::JoystickVehicleInterface> m_core; JOYSTICK_VEHICLE_INTERFACE_NODES_LOCAL void init( const std::string & control_command, const std::string & state_command_topic, const std::string & joy_topic, const bool8_t & recordreplay_command_enabled, const AxisMap & axis_map, const AxisScaleMap & axis_scale_map, const AxisScaleMap & axis_offset_map, const ButtonMap & button_map); /// Callback for joystick subscription: compute control and state command and publish JOYSTICK_VEHICLE_INTERFACE_NODES_LOCAL void on_joy(const sensor_msgs::msg::Joy::SharedPtr msg); using HighLevelControl = autoware_auto_control_msgs::msg::HighLevelControlCommand; using BasicControl = autoware_auto_vehicle_msgs::msg::VehicleControlCommand; using RawControl = autoware_auto_vehicle_msgs::msg::RawControlCommand; template<typename T> using PubT = typename rclcpp::Publisher<T>::SharedPtr; using ControlPub = mpark::variant<PubT<RawControl>, PubT<BasicControl>, PubT<HighLevelControl>>; ControlPub m_cmd_pub{}; rclcpp::Publisher<autoware_auto_vehicle_msgs::msg::VehicleStateCommand>::SharedPtr m_state_cmd_pub {}; rclcpp::Publisher<autoware_auto_vehicle_msgs::msg::HeadlightsCommand>::SharedPtr m_headlights_cmd_pub{}; rclcpp::Publisher<std_msgs::msg::UInt8>::SharedPtr m_recordreplay_cmd_pub{}; rclcpp::Subscription<sensor_msgs::msg::Joy>::SharedPtr m_joy_sub{nullptr}; }; // class JoystickVehicleInterfaceNode } // namespace joystick_vehicle_interface_nodes #endif // JOYSTICK_VEHICLE_INTERFACE_NODES__JOYSTICK_VEHICLE_INTERFACE_NODE_HPP_
41.626506
100
0.807236
ruvus
d79577c5d9c6f3afc6f313e5c51fdd6ce1920fce
5,235
cpp
C++
modules/base/rotation/constantrotation.cpp
bridger-herman/OpenSpace
e3afd82c4700536a2221fc76f64fdc873c93e964
[ "MIT" ]
1
2019-10-27T12:42:40.000Z
2019-10-27T12:42:40.000Z
modules/base/rotation/constantrotation.cpp
bridger-herman/OpenSpace
e3afd82c4700536a2221fc76f64fdc873c93e964
[ "MIT" ]
null
null
null
modules/base/rotation/constantrotation.cpp
bridger-herman/OpenSpace
e3afd82c4700536a2221fc76f64fdc873c93e964
[ "MIT" ]
1
2020-04-29T01:34:22.000Z
2020-04-29T01:34:22.000Z
/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2019 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include <modules/base/rotation/constantrotation.h> #include <openspace/documentation/documentation.h> #include <openspace/documentation/verifier.h> #include <openspace/util/updatestructures.h> #include <glm/gtx/quaternion.hpp> namespace { constexpr openspace::properties::Property::PropertyInfo RotationInfo = { "RotationAxis", "Rotation Axis", "This value is the rotation axis around which the object will rotate." }; constexpr openspace::properties::Property::PropertyInfo RotationRateInfo = { "RotationRate", "Rotation Rate", "This value determines the number of revolutions per in-game second" }; } // namespace namespace openspace { documentation::Documentation ConstantRotation::Documentation() { using namespace openspace::documentation; return { "Static Rotation", "base_transform_rotation_constant", { { "Type", new StringEqualVerifier("ConstantRotation"), Optional::No }, { RotationInfo.identifier, new DoubleVector3Verifier(), Optional::Yes, RotationInfo.description }, { RotationRateInfo.identifier, new DoubleVerifier(), Optional::Yes, RotationRateInfo.description } } }; } ConstantRotation::ConstantRotation(const ghoul::Dictionary& dictionary) : _rotationAxis( RotationInfo, glm::dvec3(0.0, 0.0, 1.0), glm::dvec3(-1.0), glm::dvec3(1.0) ) , _rotationRate(RotationRateInfo, 1.f, -1000.f, 1000.f) { addProperty(_rotationAxis); addProperty(_rotationRate); if (dictionary.hasKeyAndValue<glm::dvec3>(RotationInfo.identifier)) { _rotationAxis = dictionary.value<glm::dvec3>(RotationInfo.identifier); } if (dictionary.hasKeyAndValue<double>(RotationRateInfo.identifier)) { _rotationRate = static_cast<float>( dictionary.value<double>(RotationRateInfo.identifier) ); } } glm::dmat3 ConstantRotation::matrix(const UpdateData& data) const { if (data.time.j2000Seconds() == data.previousFrameTime.j2000Seconds()) { return glm::dmat3(); } const double rotPerSec = _rotationRate; const double secPerFrame = data.time.j2000Seconds() - data.previousFrameTime.j2000Seconds(); const double rotPerFrame = rotPerSec * secPerFrame; const double radPerFrame = rotPerFrame * glm::tau<double>(); _accumulatedRotation += radPerFrame; // Renormalize the rotation to prevent potential overflow (which probably will never // happen, but whatever) if (_accumulatedRotation > glm::tau<double>()) { _accumulatedRotation -= glm::tau<double>(); } if (_accumulatedRotation < -glm::tau<double>()) { _accumulatedRotation += glm::tau<double>(); } glm::dquat q = glm::angleAxis(_accumulatedRotation, _rotationAxis.value()); return glm::toMat3(q); } } // namespace openspace
41.88
90
0.541547
bridger-herman
d79a5d199c99aa9d81e70250399d07094b4d264f
4,363
cc
C++
src/media/audio/audio_core/test/service/message_transceiver.cc
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
1
2019-04-21T18:02:26.000Z
2019-04-21T18:02:26.000Z
src/media/audio/audio_core/test/service/message_transceiver.cc
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
16
2020-09-04T19:01:11.000Z
2021-05-28T03:23:09.000Z
src/media/audio/audio_core/test/service/message_transceiver.cc
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia 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 "src/media/audio/audio_core/test/service/message_transceiver.h" #include <lib/async/default.h> namespace media::audio::test { MessageTransceiver::MessageTransceiver(){}; MessageTransceiver::~MessageTransceiver() { Close(); }; zx_status_t MessageTransceiver::Init(zx::channel channel, IncomingMessageCallback incoming_message_callback, ErrorCallback error_callback) { channel_ = std::move(channel); incoming_message_callback_ = std::move(incoming_message_callback); error_callback_ = std::move(error_callback); read_wait_.set_object(channel_.get()); read_wait_.set_trigger(ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED); write_wait_.set_object(channel_.get()); write_wait_.set_trigger(ZX_CHANNEL_WRITABLE | ZX_CHANNEL_PEER_CLOSED); return read_wait_.Begin(async_get_default_dispatcher()); } void MessageTransceiver::Close() { read_wait_.Cancel(); write_wait_.Cancel(); channel_.reset(); incoming_message_callback_ = nullptr; error_callback_ = nullptr; } zx_status_t MessageTransceiver::SendMessage(Message message) { if (!channel_) { return ZX_ERR_NOT_CONNECTED; } outbound_messages_.push(std::move(message)); if (channel_ && !write_wait_.is_pending()) { WriteChannelMessages(async_get_default_dispatcher(), &write_wait_, ZX_OK, nullptr); } return ZX_OK; } void MessageTransceiver::OnError(zx_status_t status) { if (error_callback_) { error_callback_(status); } Close(); } void MessageTransceiver::ReadChannelMessages(async_dispatcher_t* dispatcher, async::WaitBase* wait, zx_status_t status, const zx_packet_signal_t* signal) { while (channel_) { uint32_t actual_byte_count; uint32_t actual_handle_count; zx_status_t status = channel_.read(0, nullptr, nullptr, 0, 0, &actual_byte_count, &actual_handle_count); if (status == ZX_ERR_SHOULD_WAIT) { status = wait->Begin(dispatcher); if (status != ZX_OK) { FXL_PLOG(ERROR, status) << "async::WaitMethod::Begin failed"; OnError(status); } break; } if (status == ZX_ERR_PEER_CLOSED) { // Remote end of the channel closed. OnError(status); break; } if (status != ZX_ERR_BUFFER_TOO_SMALL) { FXL_PLOG(ERROR, status) << "Failed to read (peek) from a zx::channel"; OnError(status); break; } Message message(actual_byte_count, actual_handle_count); status = channel_.read(0, message.bytes_.data(), message.handles_.data(), message.bytes_.size(), message.handles_.size(), &actual_byte_count, &actual_handle_count); if (status != ZX_OK) { FXL_PLOG(ERROR, status) << "zx::channel::read failed"; OnError(status); break; } FXL_CHECK(message.bytes_.size() == actual_byte_count); FXL_CHECK(message.handles_.size() == actual_handle_count); if (incoming_message_callback_) { incoming_message_callback_(std::move(message)); } } } void MessageTransceiver::WriteChannelMessages(async_dispatcher_t* dispatcher, async::WaitBase* wait, zx_status_t status, const zx_packet_signal_t* signal) { if (!channel_) { return; } while (!outbound_messages_.empty()) { const Message& message = outbound_messages_.front(); zx_status_t status = channel_.write(0, message.bytes_.data(), message.bytes_.size(), message.handles_.data(), message.handles_.size()); if (status == ZX_ERR_SHOULD_WAIT) { status = wait->Begin(dispatcher); if (status != ZX_OK) { FXL_PLOG(ERROR, status) << "async::WaitMethod::Begin failed"; OnError(status); } break; } if (status == ZX_ERR_PEER_CLOSED) { // Remote end of the channel closed. OnError(status); break; } if (status != ZX_OK) { FXL_PLOG(ERROR, status) << "zx::channel::write failed"; OnError(status); break; } outbound_messages_.pop(); } } } // namespace media::audio::test
29.47973
100
0.654137
OpenTrustGroup
d79ae1b7bbda5efa225f13b85126be3c08ab891c
2,699
hpp
C++
include/IDetection.hpp
Arjung27/Irona
456d6cbddafbdca5ba6a8a862614e07a536bdb17
[ "MIT" ]
1
2021-06-15T16:53:47.000Z
2021-06-15T16:53:47.000Z
include/IDetection.hpp
Arjung27/Irona
456d6cbddafbdca5ba6a8a862614e07a536bdb17
[ "MIT" ]
null
null
null
include/IDetection.hpp
Arjung27/Irona
456d6cbddafbdca5ba6a8a862614e07a536bdb17
[ "MIT" ]
3
2019-11-25T16:45:07.000Z
2021-11-27T02:56:43.000Z
/****************************************************************************** * MIT License * * Copyright (c) 2019 Kartik Madhira, Aruna Baijal, Arjun Gupta * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ /** * @file IDectection.hpp * @author Kartik Madhira * @author Arjun Gupta * @author Aruna Baijal * @copyright MIT License (c) 2019 Kartik Madhira, Aruna Baijal, Arjun Gupta * @brief Declares IDetection class */ #ifndef INCLUDE_IDETECTION_HPP_ #define INCLUDE_IDETECTION_HPP_ #include <ros/ros.h> #include <tf/transform_listener.h> #include <iostream> #include <vector> #include "geometry_msgs/PoseStamped.h" #include "std_msgs/Bool.h" /** * @brief Virtual Class for implementing the detection aspect of the bot */ class IDetection { public: /** * @brief function to set the tag ID for the tag * @param id associated with the ArUco marker of the object * @return void */ virtual void setTagId(int id) = 0; /** * @brief function to check if the tag is detected or not * @return bool if the tag is detected or not (true for yes) */ virtual bool detectTag() = 0; /** * @brief function to publish the pose of the detected object * @return void */ virtual void publishBoxPoses() = 0; /** * @brief function to check if the marker ID is same as the order * @return void */ virtual void detectionCallback(const \ std_msgs::Bool::ConstPtr& checkDetect) = 0; }; #endif // INCLUDE_IDETECTION_HPP_
36.472973
82
0.651723
Arjung27
d79b80f4d459ad3d60ee43d9795f898860024633
3,872
cpp
C++
src/PERI/compute_dilatation_atom.cpp
luwei0917/GlpG_Nature_Communication
a7f4f8b526e633b158dc606050e8993d70734943
[ "MIT" ]
1
2018-11-28T15:04:55.000Z
2018-11-28T15:04:55.000Z
src/PERI/compute_dilatation_atom.cpp
luwei0917/GlpG_Nature_Communication
a7f4f8b526e633b158dc606050e8993d70734943
[ "MIT" ]
null
null
null
src/PERI/compute_dilatation_atom.cpp
luwei0917/GlpG_Nature_Communication
a7f4f8b526e633b158dc606050e8993d70734943
[ "MIT" ]
null
null
null
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing author: Rezwanur Rahman, John Foster (UTSA) ------------------------------------------------------------------------- */ #include <string.h> #include "compute_dilatation_atom.h" #include "atom.h" #include "update.h" #include "modify.h" #include "comm.h" #include "force.h" #include "pair.h" #include "pair_peri_lps.h" #include "pair_peri_pmb.h" #include "pair_peri_ves.h" #include "pair_peri_eps.h" #include "fix_peri_neigh.h" #include "memory.h" #include "error.h" using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ ComputeDilatationAtom:: ComputeDilatationAtom(LAMMPS *lmp, int narg, char **arg) : Compute(lmp, narg, arg) { if (narg != 3) error->all(FLERR,"Illegal compute Dilatation/atom command"); peratom_flag = 1; size_peratom_cols = 0; nmax = 0; dilatation = NULL; } /* ---------------------------------------------------------------------- */ ComputeDilatationAtom::~ComputeDilatationAtom() { memory->destroy(dilatation); } /* ---------------------------------------------------------------------- */ void ComputeDilatationAtom::init() { int count = 0; for (int i = 0; i < modify->ncompute; i++) if (strcmp(modify->compute[i]->style,"dilatation/peri") == 0) count++; if (count > 1 && comm->me == 0) error->warning(FLERR,"More than one compute dilatation/atom"); // check PD pair style isPMB = isLPS = isVES = isEPS = 0; if (force->pair_match("peri/pmb",1)) isPMB = 1; if (force->pair_match("peri/lps",1)) isLPS = 1; if (force->pair_match("peri/ves",1)) isVES = 1; if (force->pair_match("peri/eps",1)) isEPS = 1; if (isPMB) error->all(FLERR,"Compute dilatation/atom cannot be used " "with this pair style"); // find associated PERI_NEIGH fix that must exist int ifix_peri = -1; for (int i = 0; i < modify->nfix; i++) if (strcmp(modify->fix[i]->style,"PERI_NEIGH") == 0) ifix_peri = i; if (ifix_peri == -1) error->all(FLERR,"Compute dilatation/atom requires Peridynamic pair style"); } /* ---------------------------------------------------------------------- */ void ComputeDilatationAtom::compute_peratom() { invoked_peratom = update->ntimestep; // grow dilatation array if necessary if (atom->nmax > nmax) { memory->destroy(dilatation); nmax = atom->nmax; memory->create(dilatation,nmax,"dilatation/atom:dilatation"); vector_atom = dilatation; } // extract dilatation for each atom in group double *theta; Pair *anypair = force->pair_match("peri",0); if (isLPS) theta = ((PairPeriLPS *) anypair)->theta; if (isVES) theta = ((PairPeriVES *) anypair)->theta; if (isEPS) theta = ((PairPeriEPS *) anypair)->theta; int *mask = atom->mask; int nlocal = atom->nlocal; for (int i = 0; i < nlocal; i++) if (mask[i] & groupbit) dilatation[i] = theta[i]; } /* ---------------------------------------------------------------------- memory usage of local atom-based array ------------------------------------------------------------------------- */ double ComputeDilatationAtom::memory_usage() { double bytes = nmax * sizeof(double); return bytes; }
30.25
80
0.550878
luwei0917
d79ba9ac235a959ca0320e14e1486102d3b7c011
365
cpp
C++
ARRAY/check subarray with given sum.cpp
ghostumar/DSA
ca8ca00d1c2cb132c46ace68f862c09883491f3c
[ "Apache-2.0" ]
null
null
null
ARRAY/check subarray with given sum.cpp
ghostumar/DSA
ca8ca00d1c2cb132c46ace68f862c09883491f3c
[ "Apache-2.0" ]
null
null
null
ARRAY/check subarray with given sum.cpp
ghostumar/DSA
ca8ca00d1c2cb132c46ace68f862c09883491f3c
[ "Apache-2.0" ]
null
null
null
#include<iostream> using namespace std; bool isgiven_sum(int arr[],int n,int givsum){ int sum=0; for(int i=0;i<n;i++){ for(int j=i;j<n;j++){//not working sum+=arr[j]; } if(givsum==sum){ return true; } } return false; } int main(){ int arr[]={1,4,20,3,10,5},n=6,givsum=33; cout<<isgiven_sum(arr,n,givsum)? "true": "false"; }
18.25
51
0.572603
ghostumar
d79c12c931ba3aa302a304f314b2a489500bea61
1,319
hpp
C++
rice/Symbol.hpp
ankane/rice
e291bf18270b0d60a0366f2854d12fe46d215b41
[ "BSD-2-Clause" ]
null
null
null
rice/Symbol.hpp
ankane/rice
e291bf18270b0d60a0366f2854d12fe46d215b41
[ "BSD-2-Clause" ]
null
null
null
rice/Symbol.hpp
ankane/rice
e291bf18270b0d60a0366f2854d12fe46d215b41
[ "BSD-2-Clause" ]
null
null
null
#ifndef Rice__Symbol__hpp_ #define Rice__Symbol__hpp_ #include "Identifier.hpp" #include "Object_defn.hpp" #include "detail/ruby.hpp" #include <string> namespace Rice { //! A wrapper for ruby's Symbol class. /*! Symbols are internal identifiers in ruby. They are singletons and * can be thought of as frozen strings. They differ from an Identifier * in that they are in fact real Objects, but they can be converted * back and forth between Identifier and Symbol. */ class Symbol : public Object { public: //! Wrap an existing symbol. Symbol(VALUE v); //! Wrap an existing symbol. Symbol(Object v); //! Construct a Symbol from an Identifier. Symbol(Identifier id); //! Construct a Symbol from a null-terminated C string. Symbol(char const * s = ""); //! Construct a Symbol from an std::string. Symbol(std::string const & s); //! Return a string representation of the Symbol. char const * c_str() const; //! Return a string representation of the Symbol. std::string str() const; //! Return the Symbol as an Identifier. Identifier to_id() const; }; } // namespace Rice template<> struct Rice::detail::From_Ruby<Rice::Symbol> { static Rice::Symbol convert(VALUE value) { return Rice::Symbol(value); } }; #include "Symbol.ipp" #endif // Rice__Symbol__hpp_
21.274194
72
0.701289
ankane
d7a04cc8f2b9bc17331acb5bb62bfc755d3c7e16
727
cpp
C++
Level-1/8. Recursion-with-ArrayList/GetSubsequence.cpp
anubhvshrma18/PepCoding
1d5ebd43e768ad923bf007c8dd584e217df1f017
[ "Apache-2.0" ]
22
2021-06-02T04:25:55.000Z
2022-01-30T06:25:07.000Z
Level-1/8. Recursion-with-ArrayList/GetSubsequence.cpp
amitdubey6261/PepCoding
1d5ebd43e768ad923bf007c8dd584e217df1f017
[ "Apache-2.0" ]
2
2021-10-17T19:26:10.000Z
2022-01-14T18:18:12.000Z
Level-1/8. Recursion-with-ArrayList/GetSubsequence.cpp
amitdubey6261/PepCoding
1d5ebd43e768ad923bf007c8dd584e217df1f017
[ "Apache-2.0" ]
8
2021-07-21T09:55:15.000Z
2022-01-31T10:32:51.000Z
#include <iostream> #include <vector> using namespace std; vector<string> gss(string s){ // write your code here vector<string> x; if(s.length()==0){ x.push_back(""); return x; } string small=s.substr(0,s.length()-1); vector<string> getsub=gss(small); for(int i=0;i<getsub.size();i++){ x.push_back(getsub[i]+""); x.push_back(getsub[i]+s[s.length()-1]); } return x; } int main(){ string s; cin >> s; vector<string> ans = gss(s); int cnt = 0; cout << '['; for (string str : ans){ if (cnt != ans.size() - 1) cout << str << ", "; else cout << str; cnt++; } cout << ']'; }
19.648649
47
0.47868
anubhvshrma18
d7a2b17a1f66f7913737db71e7bb32adf02ce6e3
1,966
hpp
C++
pose_refinement/SA-LMPE/ba/openMVG/sfm/sfm_data_BA_ceres.hpp
Aurelio93/satellite-pose-estimation
46957a9bc9f204d468f8fe3150593b3db0f0726a
[ "MIT" ]
90
2019-05-19T03:48:23.000Z
2022-02-02T15:20:49.000Z
pose_refinement/SA-LMPE/ba/openMVG/sfm/sfm_data_BA_ceres.hpp
Aurelio93/satellite-pose-estimation
46957a9bc9f204d468f8fe3150593b3db0f0726a
[ "MIT" ]
11
2019-05-22T07:45:46.000Z
2021-05-20T01:48:26.000Z
pose_refinement/SA-LMPE/ba/openMVG/sfm/sfm_data_BA_ceres.hpp
Aurelio93/satellite-pose-estimation
46957a9bc9f204d468f8fe3150593b3db0f0726a
[ "MIT" ]
18
2019-05-19T03:48:32.000Z
2021-05-29T18:19:16.000Z
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2015 Pierre Moulon. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef OPENMVG_SFM_SFM_DATA_BA_CERES_HPP #define OPENMVG_SFM_SFM_DATA_BA_CERES_HPP #include "openMVG/numeric/eigen_alias_definition.hpp" #include "openMVG/sfm/sfm_data_BA.hpp" namespace ceres { class CostFunction; } namespace openMVG { namespace cameras { struct IntrinsicBase; } } namespace openMVG { namespace sfm { struct SfM_Data; } } namespace openMVG { namespace sfm { /// Create the appropriate cost functor according the provided input camera intrinsic model /// Can be residual cost functor can be weighetd if desired (default 0.0 means no weight). ceres::CostFunction * IntrinsicsToCostFunction ( cameras::IntrinsicBase * intrinsic, const Vec2 & observation, const double weight = 0.0 ); class Bundle_Adjustment_Ceres : public Bundle_Adjustment { public: struct BA_Ceres_options { bool bVerbose_; unsigned int nb_threads_; bool bCeres_summary_; int linear_solver_type_; int preconditioner_type_; int sparse_linear_algebra_library_type_; double parameter_tolerance_; bool bUse_loss_function_; BA_Ceres_options(const bool bVerbose = true, bool bmultithreaded = true); }; private: BA_Ceres_options ceres_options_; public: explicit Bundle_Adjustment_Ceres ( const Bundle_Adjustment_Ceres::BA_Ceres_options & options = std::move(BA_Ceres_options()) ); BA_Ceres_options & ceres_options(); bool Adjust ( // the SfM scene to refine sfm::SfM_Data & sfm_data, // tell which parameter needs to be adjusted const Optimize_Options & options ) override; }; } // namespace sfm } // namespace openMVG #endif // OPENMVG_SFM_SFM_DATA_BA_CERES_HPP
27.305556
91
0.749746
Aurelio93
d7a3cab3d65cc1c3f9223dcc911714ac4b1e8059
2,438
cpp
C++
src/ubik/maze/example.cpp
jedrzejboczar/ubik-micromouse
6470368de0c3207fc278bcfa604d1fdd74aaeb8f
[ "MIT" ]
3
2019-10-30T07:37:47.000Z
2021-01-21T11:50:20.000Z
src/ubik/maze/example.cpp
jedrzejboczar/ubik-micromouse
6470368de0c3207fc278bcfa604d1fdd74aaeb8f
[ "MIT" ]
null
null
null
src/ubik/maze/example.cpp
jedrzejboczar/ubik-micromouse
6470368de0c3207fc278bcfa604d1fdd74aaeb8f
[ "MIT" ]
null
null
null
#define MAZE_TESTING #include "maze.h" #include "maze.cpp" #include "maze_generator.h" size_t size = 0; maze::Cell *real_cells; Directions maze::read_walls(maze::Position pos) { if (real_cells == nullptr) return Directions(); maze::Cell *cell = &real_cells[pos.y * size + pos.x]; return cell->walls; } Dir maze::choose_best_direction(Directions possible) { if (possible & Dir::N) return Dir::N; if (possible & Dir::S) return Dir::S; if (possible & Dir::E) return Dir::E; if (possible & Dir::W) return Dir::W; assert(0); } void maze::move_in_direction(Dir dir) { std::printf("Moving in direction %s\n", dir == Dir::N ? "N" : dir == Dir::S ? "S" : dir == Dir::E ? "E" : dir == Dir::W ? "W" : "ERROR"); } int main() { size = 4; const float mid = (size - 1) / 2.0; auto from = maze::Position(0, 0); auto to = maze::TargetPosition(int(mid)+1, int(mid)+1); // auto to = maze::TargetPosition(size-1, size-1); maze::Cell cells[size * size]; StaticStack<maze::Position, 64> stack; maze::Maze maze(size, size, cells, stack, from); // RANDOM MAZE GENERATION srand(time(NULL)); maze_gen::MazeGenerator generator; generator.create(size); real_cells = new maze::Cell[size * size]; for (int y = 0; y < generator._s; y++) { int yy = y * generator._s; for (int x = 0; x < generator._s; x++) { uint8_t b = generator._world[x + yy]; // change the Y addressing as they used standard gui addresing (y=0 at top) if( !( b & maze_gen::NOR ) ) real_cells[(size - y - 1) * size + x].walls |= Dir::N; if( !( b & maze_gen::SOU ) ) real_cells[(size - y - 1) * size + x].walls |= Dir::S; if( !( b & maze_gen::EAS ) ) real_cells[(size - y - 1) * size + x].walls |= Dir::E; if( !( b & maze_gen::WES ) ) real_cells[(size - y - 1) * size + x].walls |= Dir::W; } } StaticStack<maze::Position, 1> dummy_stack; maze::Maze real_maze(size, size, real_cells, dummy_stack, {0, 0}); real_maze.print(from, maze::Position(to.x, to.y)); std::cout << "Press enter to start." << std::endl; std::cin.get(); // RANDOM MAZE GENERATION bool success = maze.go_to(to); if (!success) std::cerr << "ERROR: could not finish maze!"; maze.print(maze.position(), maze::Position(to.x, to.y)); }
32.506667
95
0.566858
jedrzejboczar
d7a8e1ba84d571405b8c0f43e34128044661cb4e
1,880
cpp
C++
main/m8rscript.cpp
cmarrin/m8rscript
4e24800e1be2c2c5e2ec1b7b52aa6df787e6460c
[ "MIT" ]
1
2018-01-30T19:37:27.000Z
2018-01-30T19:37:27.000Z
main/m8rscript.cpp
cmarrin/m8rscript
4e24800e1be2c2c5e2ec1b7b52aa6df787e6460c
[ "MIT" ]
null
null
null
main/m8rscript.cpp
cmarrin/m8rscript
4e24800e1be2c2c5e2ec1b7b52aa6df787e6460c
[ "MIT" ]
3
2017-04-01T23:41:35.000Z
2019-12-14T23:26:24.000Z
/*------------------------------------------------------------------------- This source file is a part of m8rscript For the latest info, see http:www.marrin.org/ Copyright (c) 2018-2019, Chris Marrin All rights reserved. Use of this source code is governed by the MIT license that can be found in the LICENSE file. -------------------------------------------------------------------------*/ #include "Application.h" #include "M8rscript.h" static constexpr const char* WebServerRoot = "/sys/bin"; static m8r::Duration MainTaskSleepDuration = 10ms; m8r::Vector<const char*> fileList = { "scripts/mem.m8r", "scripts/mrsh.m8r", "scripts/examples/NTPClient.m8r", "scripts/examples/NTPClient.m8r", "scripts/examples/TimeZoneDBClient.m8r", "scripts/simple/basic.m8r", "scripts/simple/blink.m8r", "scripts/simple/hello.m8r", "scripts/simple/simpleFunction.m8r", "scripts/simple/simpleTest.m8r", "scripts/simple/simpleTest2.m8r", "scripts/timing/timing-esp.m8r", "scripts/timing/timing.m8r", "scripts/tests/TestBase64.m8r", "scripts/tests/TestClass.m8r", "scripts/tests/TestClosure.m8r", "scripts/tests/TestGibberish.m8r", "scripts/tests/TestIterator.m8r", "scripts/tests/TestLoop.m8r", "scripts/tests/TestTCPSocket.m8r", "scripts/tests/TestUDPSocket.m8r", }; m8rscript::M8rscriptScriptingLanguage m8rscriptScriptingLanguage; void m8rmain() { m8r::Application application(m8r::Application::HeartbeatType::Status, WebServerRoot, 23); // Upload files needed by web server m8r::Application::uploadFiles(fileList, WebServerRoot); m8r::system()->registerScriptingLanguage(&m8rscriptScriptingLanguage); application.runAutostartTask("/sys/bin/hello.m8r"); while(1) { application.runOneIteration(); MainTaskSleepDuration.sleep(); } }
31.864407
93
0.653723
cmarrin
d7a8ecaf32b327a527131adfd3093aa64dd3d4c4
3,544
cpp
C++
src/Internal/Entity/EntityManager.cpp
NT-Bourgeois-Iridescence-Technologies/PSP-Craft-Server
35f47ca9d8a5e4f83f94bcce5cecf5c3d4573d87
[ "MIT" ]
11
2020-05-12T05:46:45.000Z
2020-07-13T13:11:56.000Z
src/Internal/Entity/EntityManager.cpp
NT-Bourgeois-Iridescence-Technologies/Craft-Server
35f47ca9d8a5e4f83f94bcce5cecf5c3d4573d87
[ "MIT" ]
6
2020-05-18T22:34:28.000Z
2020-07-11T01:17:55.000Z
src/Internal/Entity/EntityManager.cpp
NT-Bourgeois-Iridescence-Technologies/Craft-Server
35f47ca9d8a5e4f83f94bcce5cecf5c3d4573d87
[ "MIT" ]
1
2020-07-04T02:19:01.000Z
2020-07-04T02:19:01.000Z
#include "EntityManager.h" #include "../../Protocol/Play.h" #include "../World.h" #include "../../Utilities/Utils.h" #include <iostream> namespace Minecraft::Server::Internal::Entity { EntityManager::EntityManager() { } EntityManager::~EntityManager() { } void generateBaseObjectMeta(ByteBuffer* meta, Entity* obj){ //IDX meta->WriteBEInt8(0); //TYPE meta->WriteBEInt8(0); //VAL meta->WriteBEInt8(obj->flags); //IDX meta->WriteBEInt8(1); //TYPE meta->WriteBEInt8(1); //VAL meta->WriteVarInt32(obj->air); //IDX meta->WriteBEInt8(2); //TYPE meta->WriteBEInt8(5); //VAL if (obj->customName == "") { meta->WriteBool(false); }else{ meta->WriteBool(true); meta->WriteVarUTF8String(obj->customName); } //IDX meta->WriteBEInt8(3); //TYPE meta->WriteBEInt8(7); //VAL meta->WriteBool(obj->isCustomNameAvailable); //IDX meta->WriteBEInt8(4); //TYPE meta->WriteBEInt8(7); //VAL meta->WriteBool(obj->silent); //IDX meta->WriteBEInt8(5); //TYPE meta->WriteBEInt8(7); //VAL meta->WriteBool(obj->noGravity); } void generateEndMeta(ByteBuffer* meta) { //IDX meta->WriteBEInt8(0xFF); } void generateItemMeta(ByteBuffer* meta, Inventory::Slot* slot){ //IDX meta->WriteBEInt8(6); //TYPE meta->WriteBEInt8(6); //SLOT DATA meta->WriteBool(slot->present); if(slot->present){ meta->WriteVarInt32(slot->id); meta->WriteBEInt8(slot->item_count); meta->WriteBEInt8(0); } } int EntityManager::addEntity(Entity* entity) { if (entity->objData != NULL) { //Spawn Protocol::Play::PacketsOut::send_spawn_object(entityCounter, entityCounter, entityCounter, entity->id, entity->objData->x, entity->objData->y, entity->objData->z, entity->objData->pitch, entity->objData->yaw, 1, entity->objData->vx, entity->objData->vy, entity->objData->vz); //Metadata ByteBuffer* meta = new ByteBuffer(128); //Meta generateBaseObjectMeta(meta, entity); if(entity->id == 2){ generateItemMeta(meta, &((ItemEntity*)entity)->item); } generateEndMeta(meta); Protocol::Play::PacketsOut::send_entity_metadata(entityCounter, *meta); //Velocity Protocol::Play::PacketsOut::send_entity_velocity(entityCounter, 0, 0, 0); } entities.emplace(entityCounter, entity); return entityCounter++; } void EntityManager::clearEntity() { //Probably should send client some info if this is called! //Probably should free ram too... entityCounter = 0; entities.clear(); } void EntityManager::init() { entityCounter = 0; entities.clear(); } void EntityManager::cleanup() { //TODO: DELETE! entityCounter = 0; entities.clear(); } void EntityManager::deleteEntity(int id) { Protocol::Play::PacketsOut::send_destroy_entities({ id }); if (entities.find(id) != entities.end()) { delete entities[id]; entities[id] = NULL; entities.erase(id); } } void EntityManager::update() { //Do something for (int i = 0; i < entities.size(); i++) { auto e = entities[i]; if (e != NULL) { if (e->id == 2) { if (Player::g_Player.x > e->objData->x - 1.0f && Player::g_Player.x < e->objData->x + 1.0f) { if (Player::g_Player.z > e->objData->z - 1.0f && Player::g_Player.z < e->objData->z + 1.0f) { if (Player::g_Player.y > e->objData->y - 2.75f && Player::g_Player.y < e->objData->y + 0.75f) { if (g_World->inventory.addItem(((ItemEntity*)e)->item)) { deleteEntity(i); } continue; } } } } } } } }
21.221557
278
0.634594
NT-Bourgeois-Iridescence-Technologies
d7a9a5e3a8f3f42f92d1e3e4e2b0c8bbe4437736
144
cpp
C++
Solutions/NOCODINGTEST.cpp
nikramakrishnan/codechef-solutions
f7ab2199660275e972a387541ecfc24fd358e03e
[ "MIT" ]
1
2022-03-26T09:38:02.000Z
2022-03-26T09:38:02.000Z
Solutions/NOCODINGTEST.cpp
nikramakrishnan/codechef-solutions
f7ab2199660275e972a387541ecfc24fd358e03e
[ "MIT" ]
null
null
null
Solutions/NOCODINGTEST.cpp
nikramakrishnan/codechef-solutions
f7ab2199660275e972a387541ecfc24fd358e03e
[ "MIT" ]
null
null
null
#include<iostream> #include<ctype.h> #include<cstring> #include<string> using namespace std; int main(){ char x[1001]; cin>>x; cout<<x[0]-97; }
13.090909
20
0.694444
nikramakrishnan
d7aa2a204942b0c3203fd3fe003c1c246ac98bdf
7,754
cpp
C++
platforms/agl/alexa-voiceagent-service/src/plugins/aac-services/aasb/aac-platform/cbl/src/CBLHandler.cpp
dl9pf/alexa-auto-sdk
86916d2d8c1702a8be3c88a9012ca56583bcc0c8
[ "Apache-2.0" ]
null
null
null
platforms/agl/alexa-voiceagent-service/src/plugins/aac-services/aasb/aac-platform/cbl/src/CBLHandler.cpp
dl9pf/alexa-auto-sdk
86916d2d8c1702a8be3c88a9012ca56583bcc0c8
[ "Apache-2.0" ]
null
null
null
platforms/agl/alexa-voiceagent-service/src/plugins/aac-services/aasb/aac-platform/cbl/src/CBLHandler.cpp
dl9pf/alexa-auto-sdk
86916d2d8c1702a8be3c88a9012ca56583bcc0c8
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2018-2019 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 "CBLHandler.h" #include <fstream> #include <iostream> #include <rapidjson/document.h> #include <rapidjson/prettywriter.h> #include <rapidjson/stringbuffer.h> #include <aasb/Consts.h> #include "ResponseDispatcher.h" #include "PlatformSpecificLoggingMacros.h" /** * Specifies the severity level of a log message * @sa @c aace::logger::LoggerEngineInterface::Level */ using Level = aace::logger::LoggerEngineInterface::Level; namespace aasb { namespace cbl { using namespace rapidjson; const std::string TAG = "aasb::alexa::CBLHandler"; std::shared_ptr<CBLHandler> CBLHandler::create( std::shared_ptr<aasb::core::logger::LoggerHandler> logger, std::weak_ptr<aasb::bridge::ResponseDispatcher> responseDispatcher, std::string refresh_token_file) { auto cblHandler = std::shared_ptr<CBLHandler>(new CBLHandler(logger, responseDispatcher, refresh_token_file)); return cblHandler; } CBLHandler::CBLHandler(std::shared_ptr<aasb::core::logger::LoggerHandler> logger, std::weak_ptr<aasb::bridge::ResponseDispatcher> responseDispatcher, std::string refresh_token_file) : m_logger(logger), m_responseDispatcher(responseDispatcher), m_refresh_token_file(refresh_token_file) { loadRefreshTokenFromFile(); } void CBLHandler::loadRefreshTokenFromFile() { std::ifstream file(m_refresh_token_file, std::ifstream::in); if(file.is_open()) { m_RefreshToken = std::string((std::istreambuf_iterator<char>(file)), (std::istreambuf_iterator<char>())); file.close(); } else { m_RefreshToken = ""; m_logger->log(Level::WARN, TAG, "loadRefreshTokenFromFile: Error opening refresh token file"); } } void CBLHandler::cblStateChanged(CBLState state, CBLStateChangedReason reason, const std::string& url, const std::string& code) { std::string info = std::string(": CBLState: ") + std::string(convertCBLStateToString(state)) + std::string(": CBLStateChangedReason: ") + std::string(convertCBLStateChangedReasonToString(reason) + std::string(": url: ") + url + std::string(": code: ") + code); m_logger->log(Level::INFO, TAG, info); if (auto responseDispatcher = m_responseDispatcher.lock()) { if (state == CBLState::CODE_PAIR_RECEIVED) { rapidjson::Document document; document.SetObject(); rapidjson::Value payloadElement; payloadElement.SetObject(); payloadElement.AddMember("url", rapidjson::Value().SetString(url.c_str(), url.length()), document.GetAllocator()); payloadElement.AddMember("code", rapidjson::Value().SetString(code.c_str(), code.length()), document.GetAllocator()); document.AddMember("payload", payloadElement, document.GetAllocator()); // create event string rapidjson::StringBuffer buffer; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer( buffer ); document.Accept( writer ); responseDispatcher->sendDirective( aasb::bridge::TOPIC_CBL, aasb::bridge::ACTION_CBL_CODEPAIR_RECEIVED, buffer.GetString()); } else if ((state == CBLState::STOPPING) && (reason == CBLStateChangedReason::CODE_PAIR_EXPIRED)) { m_logger->log(Level::WARN, TAG, "The code has expired. Retry to generate a new code."); responseDispatcher->sendDirective( aasb::bridge::TOPIC_CBL, aasb::bridge::ACTION_CBL_CODEPAIR_EXPIRED, ""); } } } void CBLHandler::clearRefreshToken() { m_logger->log(Level::VERBOSE, TAG, "clearRefreshToken"); clearRefreshTokenInternal(); } void CBLHandler::setRefreshToken(const std::string& refreshToken) { m_logger->log(Level::VERBOSE, TAG, "setRefreshToken"); setRefreshTokenInternal(refreshToken); } std::string CBLHandler::getRefreshToken() { m_logger->log(Level::VERBOSE, TAG, "getRefreshToken"); // Return available refresh token return getRefreshTokenInternal(); } void CBLHandler::setUserProfile(const std::string& name, const std::string& email) { m_logger->log(Level::VERBOSE, TAG, "setUserProfile" + name + "email" + email); if (auto responseDispatcher = m_responseDispatcher.lock()) { if (!name.empty()) { responseDispatcher->sendDirective( aasb::bridge::TOPIC_CBL, aasb::bridge::ACTION_CBL_SET_PROFILE_NAME, name); } } } void CBLHandler::onReceivedEvent(const std::string& action, const std::string& payload) { m_logger->log(Level::INFO, TAG, "onReceivedEvent: " + action); if (action == aasb::bridge::ACTION_CBL_START) { start(); } else if (action == aasb::bridge::ACTION_CBL_CANCEL) { cancel(); } else { AASB_ERROR("CBLHandler: action %s is unknown.", action.c_str()); } return; } std::string CBLHandler::convertCBLStateToString(CBLState state) { switch (state) { case CBLState::STARTING: return "STARTING"; case CBLState::REQUESTING_CODE_PAIR: return "REQUESTING_CODE_PAIR"; case CBLState::CODE_PAIR_RECEIVED: return "CODE_PAIR_RECEIVED"; case CBLState::REFRESHING_TOKEN: return "REFRESHING_TOKEN"; case CBLState::REQUESTING_TOKEN: return "REQUESTING_TOKEN"; case CBLState::STOPPING: return "STOPPING"; default: return std::string("UNKNOWN"); } } std::string CBLHandler::convertCBLStateChangedReasonToString(CBLStateChangedReason reason) { switch (reason) { case CBLStateChangedReason::SUCCESS: return "SUCCESS"; case CBLStateChangedReason::ERROR: return "ERROR"; case CBLStateChangedReason::TIMEOUT: return "TIMEOUT"; case CBLStateChangedReason::CODE_PAIR_EXPIRED: return "CODE_PAIR_EXPIRED"; case CBLStateChangedReason::NONE: return "NONE"; default: return std::string("UNKNOWN"); } } void CBLHandler::setRefreshTokenInternal(const std::string& refreshToken) { std::lock_guard<std::mutex> lock(m_mutex); m_RefreshToken = refreshToken; std::ofstream file(m_refresh_token_file, std::ofstream::trunc); if(file.is_open()) { file << refreshToken; file.close(); } else { m_logger->log(Level::ERROR, TAG, "setRefreshTokenInternal: Error opening refresh token file"); } } std::string CBLHandler::getRefreshTokenInternal() { std::lock_guard<std::mutex> lock(m_mutex); return m_RefreshToken; } void CBLHandler::clearRefreshTokenInternal() { std::lock_guard<std::mutex> lock(m_mutex); m_RefreshToken.clear(); // Remove refresh token file if(remove(m_refresh_token_file.c_str()) != 0) { m_logger->log(Level::ERROR, TAG, "clearRefreshTokenInternal: Error clearing refresh token file"); } } } // namespace cbl } // namespace aasb
35.406393
129
0.654888
dl9pf
92e4306b8a5fc7c904646aa26f8424a0ec5091ef
799
cpp
C++
code/race/solution/racing.sol.cpp
krasznaa/cpluspluscourse
bb2f6c5f112b6b78db80449f4660dda75bf609f2
[ "Apache-2.0" ]
null
null
null
code/race/solution/racing.sol.cpp
krasznaa/cpluspluscourse
bb2f6c5f112b6b78db80449f4660dda75bf609f2
[ "Apache-2.0" ]
null
null
null
code/race/solution/racing.sol.cpp
krasznaa/cpluspluscourse
bb2f6c5f112b6b78db80449f4660dda75bf609f2
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <thread> #include <mutex> /* * This program tries to increment an integer 200 times in two threads. * We fix the race condition by locking a mutex before each increment. */ int main() { int nError = 0; for (int j = 0; j < 1000; j++) { int a = 0; std::mutex aMutex; // Increment the variable a 100 times: auto inc100 = [&a,&aMutex](){ for (int i = 0; i < 100; ++i) { std::scoped_lock lock{aMutex}; a++; } }; // Run with two threads std::thread t1(inc100); std::thread t2(inc100); for (auto t : {&t1,&t2}) t->join(); // Check if (a != 200) { std::cout << "Race: " << a << ' '; nError++; } else { std::cout << '.'; } } std::cout << '\n'; return nError; }
19.02381
71
0.516896
krasznaa
92e7559b377adb9470f9ccb982a8782a7aa5163d
1,076
cc
C++
src/warp_map_bilinear/warp_map_bilinear_generator.cc
fixstars/Halide-elements
0e9d1f27628c2626a4f4468fcacac8f71d70f525
[ "MIT" ]
76
2017-10-19T07:16:55.000Z
2022-03-23T00:04:39.000Z
src/warp_map_bilinear/warp_map_bilinear_generator.cc
tufei/Halide-elements
d9354213920441d4d3e1b0757e9354db48c9fbcc
[ "MIT" ]
3
2017-11-17T19:50:38.000Z
2021-08-07T07:39:05.000Z
src/warp_map_bilinear/warp_map_bilinear_generator.cc
tufei/Halide-elements
d9354213920441d4d3e1b0757e9354db48c9fbcc
[ "MIT" ]
15
2017-11-09T18:52:10.000Z
2021-12-11T03:33:23.000Z
#include <cstdint> #include "Halide.h" #include "Element.h" using namespace Halide; using Halide::Element::schedule; template<typename T> class WarpMapBilinear : public Halide::Generator<WarpMapBilinear<T>> { public: ImageParam src0{type_of<T>(), 2, "src0"}; ImageParam src1{type_of<float>(), 2, "src1"}; ImageParam src2{type_of<float>(), 2, "src2"}; GeneratorParam<int32_t> border_type{"border_type", 0}; //0 or 1 Param<T> border_value{"border_value", 1}; GeneratorParam<int32_t> width{"width", 1024}; GeneratorParam<int32_t> height{"height", 768}; Func build() { Func dst{"dst"}; dst = Element::warp_map_bilinear<T>(src0, src1, src2, border_type, border_value, width, height); schedule(src0, {width, height}); schedule(src1, {width, height}); schedule(src2, {width, height}); schedule(dst, {width, height}); return dst; } }; HALIDE_REGISTER_GENERATOR(WarpMapBilinear<uint8_t>, warp_map_bilinear_u8); HALIDE_REGISTER_GENERATOR(WarpMapBilinear<uint16_t>, warp_map_bilinear_u16);
32.606061
104
0.684944
fixstars
92eb006f07967cf8f11e35ea97f495edce2841c9
962
hpp
C++
src/AttachmentNya.hpp
Akela1101/nya_smtp
6613fd90a335e361471072cd7e958ac9c3940ce3
[ "MIT" ]
1
2015-09-29T12:20:42.000Z
2015-09-29T12:20:42.000Z
src/AttachmentNya.hpp
Akela1101/nya_smtp
6613fd90a335e361471072cd7e958ac9c3940ce3
[ "MIT" ]
null
null
null
src/AttachmentNya.hpp
Akela1101/nya_smtp
6613fd90a335e361471072cd7e958ac9c3940ce3
[ "MIT" ]
null
null
null
#ifndef ATTACHMENTNYA_H #define ATTACHMENTNYA_H #include "CommonMail.hpp" #include <QIODevice> #include <QHash> #include <QByteArray> #include <QStringList> namespace Nya { class Attachment { QByteArray contentType; mutable s_p<QIODevice> content; QHash<QByteArray, QByteArray> extraHeaders; public: Attachment() : contentType("application/octet-stream") {} Attachment(const QString& filePath, const QByteArray& contentType = "application/octet-stream"); Attachment(QIODevice* device, const QByteArray& contentType = "application/octet-stream"); Attachment(const QByteArray* ba, const QByteArray& contentType = "application/octet-stream"); virtual ~Attachment(); QByteArray GetContentType() const { return contentType; } QHash<QByteArray, QByteArray>& GetExtraHeaders() { return extraHeaders; } void SetContentType(const QByteArray& contentType) { this->contentType = contentType;} QByteArray MimeData() const; }; } #endif // ATTACHMENTNYA_H
26.722222
97
0.774428
Akela1101
92eee5a17f2abd600bab5ca1cbc276ad3f1be60a
1,395
cpp
C++
tests/static_callable.test.cpp
HuangDave/libembeddedhal
536a0acd9920361cc85c4b2bce0e0c6834ed4719
[ "Apache-2.0" ]
25
2021-11-03T17:53:46.000Z
2022-03-29T00:52:47.000Z
tests/static_callable.test.cpp
HuangDave/libembeddedhal
536a0acd9920361cc85c4b2bce0e0c6834ed4719
[ "Apache-2.0" ]
70
2021-09-17T23:02:24.000Z
2022-03-30T02:30:16.000Z
tests/static_callable.test.cpp
HuangDave/libembeddedhal
536a0acd9920361cc85c4b2bce0e0c6834ed4719
[ "Apache-2.0" ]
5
2022-01-18T03:35:55.000Z
2022-03-20T09:35:40.000Z
#include <boost/ut.hpp> #include <libembeddedhal/static_callable.hpp> namespace embed { boost::ut::suite static_callable_test = []() { using namespace boost::ut; // Setup class dummy_driver {}; "static_callable void(void)"_test = []() { // Setup using callback1_signature = void (*)(void); bool callback1_was_called = false; auto callable1 = static_callable<dummy_driver, 1, void(void)>( [&callback1_was_called]() { callback1_was_called = true; }); callback1_signature callback1 = callable1.get_handler(); // Exercise & Verify expect(that % false == callback1_was_called); callback1(); expect(that % true == callback1_was_called); }; "static_callable void(bool)"_test = []() { // Setup using callback2_signature = void (*)(bool); bool callback2_was_called = false; bool captured_bool = false; auto callable2 = static_callable<dummy_driver, 2, void(bool)>( [&callback2_was_called, &captured_bool](bool value) { callback2_was_called = true; captured_bool = value; }); callback2_signature callback2 = callable2.get_handler(); // Exercise & Verify expect(that % false == captured_bool); callback2(true); expect(that % true == callback2_was_called); expect(that % true == captured_bool); callback2(false); expect(that % false == captured_bool); }; }; }
27.352941
66
0.664516
HuangDave
92f038cf12cbcd29310718cdc0ff8b67c9b6a4f3
7,685
cpp
C++
printscan/ui/shellext/src/propset.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
printscan/ui/shellext/src/propset.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
printscan/ui/shellext/src/propset.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/***************************************************************************** * * (C) COPYRIGHT MICROSOFT CORPORATION, 1999 * * TITLE: propset.cpp * * VERSION: 1 * * * DATE: 06/15/1999 * * DESCRIPTION: This code implements the IPropertySetStorage interface * for the WIA shell extension. * *****************************************************************************/ #include "precomp.hxx" #pragma hdrstop const GUID FMTID_ImageAcquisitionItemProperties = {0x38276c8a,0xdcad,0x49e8,{0x85, 0xe2, 0xb7, 0x38, 0x92, 0xff, 0xfc, 0x84}}; const GUID *SUPPORTED_FMTS[] = { &FMTID_ImageAcquisitionItemProperties, }; /****************************************************************************** CPropSet constructor/destructor Init or destroy private data ******************************************************************************/ CPropSet::CPropSet (LPITEMIDLIST pidl) { m_pidl = ILClone (pidl); } CPropSet::~CPropSet () { DoILFree (m_pidl); } /****************************************************************************** CPropSet::QueryInterface ******************************************************************************/ STDMETHODIMP CPropSet::QueryInterface (REFIID riid, LPVOID *pObj) { INTERFACES iFace[] = { &IID_IPropertySetStorage, (IPropertySetStorage *)(this), }; return HandleQueryInterface (riid, pObj, iFace, ARRAYSIZE(iFace)); } #undef CLASS_NAME #define CLASS_NAME CPropSet #include "unknown.inc" /****************************************************************************** CPropSet::Create Create the requested IPropertyStorage sub-object. Not supported; our properties are read-only ******************************************************************************/ STDMETHODIMP CPropSet::Create (REFFMTID rfmtid, const CLSID *pclsid, DWORD dwFlags, DWORD dwMode, IPropertyStorage **ppstg) { TraceEnter (TRACE_PROPS, "CPropSet::Create"); TraceLeaveResult (E_UNEXPECTED); } /****************************************************************************** CPropSet::Open Return the requested IPropertyStorage ******************************************************************************/ #define VALID_MODES STGM_DIRECT | STGM_READ | STGM_WRITE | STGM_READWRITE | STGM_SHARE_DENY_NONE STDMETHODIMP CPropSet::Open (REFFMTID rfmtid, DWORD dwMode, IPropertyStorage **ppStg) { HRESULT hr = STG_E_FILENOTFOUND; TraceEnter (TRACE_PROPS, "CPropSet::Open"); if (IsEqualGUID (rfmtid, FMTID_ImageAcquisitionItemProperties)) { if ((!VALID_MODES) & dwMode) { hr = STG_E_INVALIDFUNCTION; } else { CComPtr<IWiaItem> pItem; IMGetItemFromIDL (m_pidl, &pItem); hr = pItem->QueryInterface (IID_IPropertyStorage, reinterpret_cast<LPVOID*>(ppStg)); } } TraceLeaveResult (hr); } /****************************************************************************** CPropSet::Delete Delete the specified property set. Not supported. ******************************************************************************/ STDMETHODIMP CPropSet::Delete (REFFMTID rfmtid) { return STG_E_ACCESSDENIED; } /****************************************************************************** CPropSet::Enum Return an enumerator of our property sets ******************************************************************************/ STDMETHODIMP CPropSet::Enum (IEnumSTATPROPSETSTG **ppEnum) { HRESULT hr = S_OK; TraceEnter (TRACE_PROPS, "CPropSet::Enum"); *ppEnum = new CPropStgEnum (m_pidl); if (!*ppEnum) { hr = STG_E_INSUFFICIENTMEMORY; } TraceLeaveResult (hr); } /****************************************************************************** CPropStgEnum constructor ******************************************************************************/ CPropStgEnum::CPropStgEnum (LPITEMIDLIST pidl, ULONG idx) : m_cur(idx) { ZeroMemory (&m_stat, sizeof(m_stat)); m_pidl = ILClone (pidl); } /****************************************************************************** CPropStgEnum::QueryInterface ******************************************************************************/ STDMETHODIMP CPropStgEnum::QueryInterface (REFIID riid, LPVOID* pObj) { INTERFACES iFace[] = {&IID_IEnumSTATPROPSETSTG, (IEnumSTATPROPSETSTG *)this,}; return HandleQueryInterface (riid, pObj, iFace, ARRAYSIZE(iFace)); } #undef CLASS_NAME #define CLASS_NAME CPropStgEnum #include "unknown.inc" /****************************************************************************** CPropStgEnum::Next Return the next STATPROPSETSTG struct in our list ******************************************************************************/ STDMETHODIMP CPropStgEnum::Next (ULONG celt, STATPROPSETSTG *rgelt, ULONG *pceltFetched) { HRESULT hr = S_OK; ULONG i=0; CComPtr<IWiaItem> pItem; CComQIPtr<IPropertyStorage, &IID_IPropertyStorage> pps; TraceEnter (TRACE_PROPS, "CPropStgEnum::Next"); if (!celt || !rgelt || (celt > 1 && !pceltFetched)) { TraceLeaveResult (E_INVALIDARG); } if (!m_cur) { // init our STATPROPSETSTG struct if (SUCCEEDED(IMGetItemFromIDL(m_pidl, &pItem))) { pps = pItem; pps->Stat(&m_stat); } } // We use the same STATPROPSETSTG given us by WIA but replace the FMTID if (celt && m_cur < ARRAYSIZE(SUPPORTED_FMTS)) { for (i = 1;i<=celt && m_cur < ARRAYSIZE(SUPPORTED_FMTS);i++,rgelt++,m_cur++) { *rgelt = m_stat; (*rgelt).fmtid = *(SUPPORTED_FMTS[m_cur]); } } if (i<celt) { hr = S_FALSE; } if (pceltFetched) { *pceltFetched = i; } TraceLeaveResult (hr); } /****************************************************************************** CPropStgEnum::Skip Skips items in the enumeration ******************************************************************************/ STDMETHODIMP CPropStgEnum::Skip (ULONG celt) { HRESULT hr = S_OK; ULONG maxSkip = ARRAYSIZE(SUPPORTED_FMTS) - m_cur; TraceEnter (TRACE_PROPS, "CPropStgEnum::Skip"); m_cur = min (ARRAYSIZE(SUPPORTED_FMTS), m_cur+celt); if (maxSkip < celt) { hr = S_FALSE; } TraceLeaveResult (hr); } /****************************************************************************** CPropStgEnum::Reset Reset the enumeration index to 0 ******************************************************************************/ STDMETHODIMP CPropStgEnum::Reset () { TraceEnter (TRACE_PROPS, "CPropStgEnum::Reset"); m_cur = 0; TraceLeaveResult (S_OK); } /****************************************************************************** CPropStgEnum::Clone Copy the enumeration object ******************************************************************************/ STDMETHODIMP CPropStgEnum::Clone (IEnumSTATPROPSETSTG **ppEnum) { HRESULT hr = S_OK; TraceEnter (TRACE_PROPS, "CPropStgEnum::Clone"); *ppEnum = new CPropStgEnum (m_pidl, m_cur); if (!*ppEnum) { hr = E_OUTOFMEMORY; } TraceLeaveResult (hr); }
25.114379
127
0.447235
npocmaka
92f1187cbd7ec304bc0c541237d6949e7e72fe75
3,939
hh
C++
src/mmutil_annotate_embedding.hh
YPARK/mmutil
21729fc50ac4cefff58c1b71e8c5740d2045b111
[ "MIT" ]
null
null
null
src/mmutil_annotate_embedding.hh
YPARK/mmutil
21729fc50ac4cefff58c1b71e8c5740d2045b111
[ "MIT" ]
null
null
null
src/mmutil_annotate_embedding.hh
YPARK/mmutil
21729fc50ac4cefff58c1b71e8c5740d2045b111
[ "MIT" ]
null
null
null
#include <getopt.h> #include "mmutil.hh" #include "io.hh" #include "mmutil_embedding.hh" #ifndef MMUTIL_ANNOTATE_EMBEDDING_HH_ #define MMUTIL_ANNOTATE_EMBEDDING_HH_ struct embedding_options_t { using Str = std::string; typedef enum { UNIFORM, CV, MEAN } sampling_method_t; const std::vector<Str> METHOD_NAMES; embedding_options_t() { out = "output.txt.gz"; embedding_dim = 2; embedding_epochs = 1000; exaggeration = 100; tol = 1e-8; verbose = false; l2_penalty = 1e-4; } Str data_file; Str prob_file; Str out; Index embedding_dim; Index embedding_epochs; Index exaggeration; Scalar tol; Scalar l2_penalty; bool verbose; }; template <typename T> int parse_embedding_options(const int argc, // const char *argv[], // T &options) { const char *_usage = "\n" "[Arguments]\n" "--data (-m) : data matrix file\n" "--prob (-p) : probability matrix file\n" "--out (-o) : Output file header\n" "\n" "--embedding_dim (-d) : latent dimensionality (default: 2)\n" "--embedding_epochs (-i) : Maximum iteration (default: 100)\n" "--l2 (-l) : L2 penalty (default: 1e-4)\n" "--tol (-t) : Convergence criterion (default: 1e-4)\n" "--verbose (-v) : Set verbose (default: false)\n" "\n"; const char *const short_opts = "m:p:o:d:i:t:l:hv"; const option long_opts[] = { { "data", required_argument, nullptr, 'm' }, // { "prob", required_argument, nullptr, 'p' }, // { "out", required_argument, nullptr, 'o' }, // { "embedding_dim", required_argument, nullptr, 'd' }, // { "embed_dim", required_argument, nullptr, 'd' }, // { "dim", required_argument, nullptr, 'd' }, // { "embedding_epochs", required_argument, nullptr, 'i' }, // { "l2", required_argument, nullptr, 'l' }, // { "l2_penalty", required_argument, nullptr, 'l' }, // { "tol", required_argument, nullptr, 't' }, // { "verbose", no_argument, nullptr, 'v' }, // { nullptr, no_argument, nullptr, 0 } }; while (true) { const auto opt = getopt_long(argc, // const_cast<char **>(argv), // short_opts, // long_opts, // nullptr); if (-1 == opt) break; switch (opt) { case 'm': options.data_file = std::string(optarg); break; case 'p': options.prob_file = std::string(optarg); break; case 'o': options.out = std::string(optarg); break; case 'd': options.embedding_dim = std::stoi(optarg); break; case 'i': options.embedding_epochs = std::stoi(optarg); break; case 't': options.tol = std::stof(optarg); break; case 'l': options.l2_penalty = std::stof(optarg); break; case 'v': // -v or --verbose options.verbose = true; break; case 'h': // -h or --help case '?': // Unrecognized option std::cerr << _usage << std::endl; return EXIT_FAILURE; default: // ; } } ERR_RET(!file_exists(options.data_file), "No data matrix file"); ERR_RET(!file_exists(options.prob_file), "No probability file"); return EXIT_SUCCESS; } #endif
28.751825
75
0.475248
YPARK
92f19fedfbad7ade5b9e148509bdae67ac704c43
5,809
cpp
C++
src/ppm.cpp
GhostatSpirit/hdrview
61596f8ba45554db23ae1b214354ab40da065638
[ "MIT" ]
94
2021-04-23T03:31:15.000Z
2022-03-29T08:20:26.000Z
src/ppm.cpp
GhostatSpirit/hdrview
61596f8ba45554db23ae1b214354ab40da065638
[ "MIT" ]
64
2021-05-05T21:51:15.000Z
2022-02-08T17:06:52.000Z
src/ppm.cpp
GhostatSpirit/hdrview
61596f8ba45554db23ae1b214354ab40da065638
[ "MIT" ]
3
2021-07-06T04:58:27.000Z
2022-02-08T16:53:48.000Z
// // Copyright (C) Wojciech Jarosz <wjarosz@gmail.com>. All rights reserved. // Use of this source code is governed by a BSD-style license that can // be found in the LICENSE.txt file. // #include "ppm.h" #include <cmath> #include <cstdio> #include <iostream> #include <stdexcept> #include <string> using namespace std; namespace { struct RGB { unsigned char r; unsigned char g; unsigned char b; }; } // end namespace bool is_ppm_image(const char *filename) { FILE *infile = nullptr; int numInputsRead = 0; char buffer[256]; try { infile = fopen(filename, "rb"); if (!infile) throw std::runtime_error("cannot open file."); if ((fgets(buffer, sizeof(buffer), infile) == nullptr) || (buffer[0] != 'P') || (buffer[1] != '6')) throw std::runtime_error("image is not a binary PPM file."); // skip comments do { if (fgets(buffer, sizeof(buffer), infile) == nullptr) throw std::runtime_error("image is not a valid PPM file: read error while parsing comment line."); } while (buffer[0] == '#'); // read image size int width, height; numInputsRead = sscanf(buffer, "%d %d", &width, &height); if (numInputsRead != 2) throw runtime_error("could not read number of channels in header."); // skip comments do { if (fgets(buffer, sizeof(buffer), infile) == nullptr) throw std::runtime_error("image is not a valid PPM file: read error while parsing comment line."); } while (buffer[0] == '#'); // read maximum pixel value (usually 255) int colors; numInputsRead = sscanf(buffer, "%d", &colors); if (numInputsRead != 1) throw runtime_error("could not read max color value."); if (colors != 255) throw std::runtime_error("max color value must be 255."); fclose(infile); return true; } catch (const std::exception &e) { if (infile) fclose(infile); return false; } } float *load_ppm_image(const char *filename, int *width, int *height, int *numChannels) { FILE * infile = nullptr; float *img = nullptr; int colors; int numInputsRead = 0; float invColors; char buffer[256]; RGB * buf = nullptr; try { infile = fopen(filename, "rb"); if (!infile) throw std::runtime_error("cannot open file."); if ((fgets(buffer, sizeof(buffer), infile) == nullptr) || (buffer[0] != 'P') || (buffer[1] != '6')) throw std::runtime_error("image is not a binary PPM file."); *numChannels = 3; // skip comments do { if (fgets(buffer, sizeof(buffer), infile) == nullptr) throw std::runtime_error("image is not a valid PPM file: read error while parsing comment line."); } while (buffer[0] == '#'); // read image size numInputsRead = sscanf(buffer, "%d %d", width, height); if (numInputsRead != 2) throw runtime_error("could not read number of channels in header."); // skip comments do { if (fgets(buffer, sizeof(buffer), infile) == nullptr) throw std::runtime_error("image is not a valid PPM file: read error while parsing comment line."); } while (buffer[0] == '#'); // read maximum pixel value (usually 255) numInputsRead = sscanf(buffer, "%d", &colors); if (numInputsRead != 1) throw runtime_error("could not read max color value."); invColors = 1.0f / colors; if (colors != 255) throw std::runtime_error("max color value must be 255."); img = new float[*width * *height * 3]; buf = new RGB[*width]; for (int y = 0; y < *height; ++y) { if (fread(buf, *width * sizeof(RGB), 1, infile) != 1) throw std::runtime_error("cannot read pixel data."); RGB * cur = buf; float *curLine = &img[y * *width * 3]; for (int x = 0; x < *width; x++) { curLine[3 * x + 0] = cur->r * invColors; curLine[3 * x + 1] = cur->g * invColors; curLine[3 * x + 2] = cur->b * invColors; cur++; } } delete[] buf; fclose(infile); return img; } catch (const std::exception &e) { delete[] buf; delete[] img; if (infile) fclose(infile); throw std::runtime_error(string("ERROR in load_ppm_image: ") + string(e.what()) + string(" Unable to read PPM file '") + filename + "'"); } } bool write_ppm_image(const char *filename, int width, int height, int numChannels, const unsigned char *data) { FILE *outfile = nullptr; try { outfile = fopen(filename, "wb"); if (!outfile) throw std::runtime_error("cannot open file."); // write header fprintf(outfile, "P6\n"); fprintf(outfile, "%d %d\n", width, height); fprintf(outfile, "255\n"); auto numChars = static_cast<size_t>(numChannels * width * height); if (fwrite(data, sizeof(unsigned char), numChars, outfile) != numChars) throw std::runtime_error("cannot write pixel data."); fclose(outfile); return true; } catch (const std::exception &e) { if (outfile) fclose(outfile); throw std::runtime_error(string("ERROR in write_ppm_image: ") + string(e.what()) + string(" Unable to write PPM file '") + string(filename) + "'"); } }
29.943299
114
0.542262
GhostatSpirit
92f49b08d0b67c77daad20287e89fd0574fd0434
16,314
cpp
C++
src/graph/executor/test/ProduceSemiShortestPathTest.cpp
heyanlong/nebula
07ccfde198c978b8c86b7091773e3238bfcdf454
[ "Apache-2.0" ]
1
2022-03-09T10:01:13.000Z
2022-03-09T10:01:13.000Z
src/graph/executor/test/ProduceSemiShortestPathTest.cpp
heyanlong/nebula
07ccfde198c978b8c86b7091773e3238bfcdf454
[ "Apache-2.0" ]
1
2021-11-18T02:16:15.000Z
2021-11-18T03:16:57.000Z
src/graph/executor/test/ProduceSemiShortestPathTest.cpp
heyanlong/nebula
07ccfde198c978b8c86b7091773e3238bfcdf454
[ "Apache-2.0" ]
3
2021-11-08T16:21:16.000Z
2021-11-10T06:39:48.000Z
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #include <gtest/gtest.h> #include "graph/context/QueryContext.h" #include "graph/executor/algo/ProduceSemiShortestPathExecutor.h" #include "graph/planner/plan/Algo.h" namespace nebula { namespace graph { class ProduceSemiShortestPathTest : public testing::Test { protected: static bool compareShortestPath(Row& row1, Row& row2) { // row : dst | src | cost | {paths} if (row1.values[0] != row2.values[0]) { return row1.values[0] < row2.values[0]; } if (row1.values[1] != row2.values[1]) { return row1.values[1] < row2.values[1]; } if (row1.values[2] != row2.values[2]) { return row1.values[2] < row2.values[2]; } auto& pathList1 = row1.values[3].getList(); auto& pathList2 = row2.values[3].getList(); if (pathList1.size() != pathList2.size()) { return pathList1.size() < pathList2.size(); } for (size_t i = 0; i < pathList1.size(); i++) { if (pathList1.values[i] != pathList2.values[i]) { return pathList1.values[i] < pathList2.values[i]; } } return false; } void SetUp() override { qctx_ = std::make_unique<QueryContext>(); /* * 0->1->5->7; * 1->6->7 * 2->6->7 * 3->4->7 * startVids {0, 1, 2, 3} */ { DataSet ds1; ds1.colNames = {kVid, "_stats", "_edge:+edge1:_type:_dst:_rank", "_expr"}; { // 0->1 Row row; row.values.emplace_back("0"); // _stats = empty row.values.emplace_back(Value()); // edges List edges; List edge; edge.values.emplace_back(1); edge.values.emplace_back("1"); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds1.rows.emplace_back(std::move(row)); } { // 1->5, 1->6; Row row; row.values.emplace_back("1"); // _stats = empty row.values.emplace_back(Value()); // edges List edges; for (auto i = 5; i < 7; i++) { List edge; edge.values.emplace_back(1); edge.values.emplace_back(folly::to<std::string>(i)); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); } row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds1.rows.emplace_back(std::move(row)); } { // 2->6 Row row; row.values.emplace_back("2"); // _stats = empty row.values.emplace_back(Value()); // edges List edges; List edge; edge.values.emplace_back(1); edge.values.emplace_back("6"); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds1.rows.emplace_back(std::move(row)); } { // 3->4 Row row; row.values.emplace_back("3"); // _stats = empty row.values.emplace_back(Value()); // edges List edges; List edge; edge.values.emplace_back(1); edge.values.emplace_back("4"); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds1.rows.emplace_back(std::move(row)); } firstStepResult_ = std::move(ds1); DataSet ds2; ds2.colNames = {kVid, "_stats", "_edge:+edge1:_type:_dst:_rank", "_expr"}; { // 1->5, 1->6; Row row; row.values.emplace_back("1"); // _stats = empty row.values.emplace_back(Value()); // edges List edges; for (auto i = 5; i < 7; i++) { List edge; edge.values.emplace_back(1); edge.values.emplace_back(folly::to<std::string>(i)); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); } row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds2.rows.emplace_back(std::move(row)); } { // 4->7, 5->7, 6->7 for (auto i = 4; i < 7; i++) { Row row; row.values.emplace_back(folly::to<std::string>(i)); // _stats = empty row.values.emplace_back(Value()); // edges List edges; List edge; edge.values.emplace_back(1); edge.values.emplace_back("7"); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds2.rows.emplace_back(std::move(row)); } } secondStepResult_ = std::move(ds2); DataSet ds3; ds3.colNames = {kVid, "_stats", "_edge:+edge1:_type:_dst:_rank", "_expr"}; { // 5->7, 6->7 for (auto i = 5; i < 7; i++) { Row row; row.values.emplace_back(folly::to<std::string>(i)); // _stats = empty row.values.emplace_back(Value()); // edges List edges; List edge; edge.values.emplace_back(1); edge.values.emplace_back("7"); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds3.rows.emplace_back(std::move(row)); } } thridStepResult_ = std::move(ds3); { DataSet ds; ds.colNames = {kVid, "_stats", "_tag:tag1:prop1:prop2", "_edge:+edge1:prop1:prop2:_dst:_rank", "_expr"}; qctx_->symTable()->newVariable("empty_get_neighbors"); qctx_->ectx()->setResult("empty_get_neighbors", ResultBuilder() .value(Value(std::move(ds))) .iter(Iterator::Kind::kGetNeighbors) .build()); } } } protected: std::unique_ptr<QueryContext> qctx_; DataSet firstStepResult_; DataSet secondStepResult_; DataSet thridStepResult_; }; TEST_F(ProduceSemiShortestPathTest, ShortestPath) { qctx_->symTable()->newVariable("input"); auto* pssp = ProduceSemiShortestPath::make(qctx_.get(), nullptr); pssp->setInputVar("input"); pssp->setColNames({"_dst", "_src", "cost", "paths"}); auto psspExe = std::make_unique<ProduceSemiShortestPathExecutor>(pssp, qctx_.get()); // Step 1 { ResultBuilder builder; List datasets; datasets.values.emplace_back(std::move(firstStepResult_)); builder.value(std::move(datasets)).iter(Iterator::Kind::kGetNeighbors); qctx_->ectx()->setResult("input", builder.build()); auto future = psspExe->execute(); auto status = std::move(future).get(); EXPECT_TRUE(status.ok()); auto& result = qctx_->ectx()->getResult(pssp->outputVar()); DataSet expected; expected.colNames = {"_dst", "_src", "cost", "paths"}; auto cost = 1; { // 0->1 Row row; Path path; path.src = Vertex("0", {}); path.steps.emplace_back(Step(Vertex("1", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("1"); row.values.emplace_back("0"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 1->5 Row row; Path path; path.src = Vertex("1", {}); path.steps.emplace_back(Step(Vertex("5", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("5"); row.values.emplace_back("1"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 1->6 Row row; Path path; path.src = Vertex("1", {}); path.steps.emplace_back(Step(Vertex("6", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("6"); row.values.emplace_back("1"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 2->6 Row row; Path path; path.src = Vertex("2", {}); path.steps.emplace_back(Step(Vertex("6", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("6"); row.values.emplace_back("2"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 3->4 Row row; Path path; path.src = Vertex("3", {}); path.steps.emplace_back(Step(Vertex("4", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("4"); row.values.emplace_back("3"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } std::sort(expected.rows.begin(), expected.rows.end(), compareShortestPath); auto resultDs = result.value().getDataSet(); std::sort(resultDs.rows.begin(), resultDs.rows.end(), compareShortestPath); EXPECT_EQ(resultDs, expected); EXPECT_EQ(result.state(), Result::State::kSuccess); } // Step 2 { ResultBuilder builder; List datasets; datasets.values.emplace_back(std::move(secondStepResult_)); builder.value(std::move(datasets)).iter(Iterator::Kind::kGetNeighbors); qctx_->ectx()->setResult("input", builder.build()); auto future = psspExe->execute(); auto status = std::move(future).get(); EXPECT_TRUE(status.ok()); auto& result = qctx_->ectx()->getResult(pssp->outputVar()); DataSet expected; expected.colNames = {"_dst", "_src", "cost", "paths"}; auto cost = 2; { // 0->1->5 Row row; Path path; path.src = Vertex("0", {}); path.steps.emplace_back(Step(Vertex("1", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("5", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("5"); row.values.emplace_back("0"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 0->1->6 Row row; Path path; path.src = Vertex("0", {}); path.steps.emplace_back(Step(Vertex("1", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("6", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("6"); row.values.emplace_back("0"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 2->6->7 Row row; Path path; path.src = Vertex("2", {}); path.steps.emplace_back(Step(Vertex("6", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("7", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("7"); row.values.emplace_back("2"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 3->4->7 Row row; Path path; path.src = Vertex("3", {}); path.steps.emplace_back(Step(Vertex("4", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("7", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("7"); row.values.emplace_back("3"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 1->5->7, 1->6->7 List paths; { Path path; path.src = Vertex("1", {}); path.steps.emplace_back(Step(Vertex("5", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("7", {}), 1, "edge1", 0, {})); paths.values.emplace_back(std::move(path)); } { Path path; path.src = Vertex("1", {}); path.steps.emplace_back(Step(Vertex("6", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("7", {}), 1, "edge1", 0, {})); paths.values.emplace_back(std::move(path)); } Row row; row.values.emplace_back("7"); row.values.emplace_back("1"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } std::sort(expected.rows.begin(), expected.rows.end(), compareShortestPath); auto resultDs = result.value().getDataSet(); std::sort(resultDs.rows.begin(), resultDs.rows.end(), compareShortestPath); EXPECT_EQ(resultDs, expected); EXPECT_EQ(result.state(), Result::State::kSuccess); } // Step3 { ResultBuilder builder; List datasets; datasets.values.emplace_back(std::move(thridStepResult_)); builder.value(std::move(datasets)).iter(Iterator::Kind::kGetNeighbors); qctx_->ectx()->setResult("input", builder.build()); auto future = psspExe->execute(); auto status = std::move(future).get(); EXPECT_TRUE(status.ok()); auto& result = qctx_->ectx()->getResult(pssp->outputVar()); DataSet expected; expected.colNames = {"_dst", "_src", "cost", "paths"}; auto cost = 3; { // 0->1->5->7, 0->1->6->7 List paths; { Path path; path.src = Vertex("0", {}); path.steps.emplace_back(Step(Vertex("1", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("5", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("7", {}), 1, "edge1", 0, {})); paths.values.emplace_back(std::move(path)); } { Path path; path.src = Vertex("0", {}); path.steps.emplace_back(Step(Vertex("1", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("6", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("7", {}), 1, "edge1", 0, {})); paths.values.emplace_back(std::move(path)); } Row row; row.values.emplace_back("7"); row.values.emplace_back("0"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } std::sort(expected.rows.begin(), expected.rows.end(), compareShortestPath); auto resultDs = result.value().getDataSet(); std::sort(resultDs.rows.begin(), resultDs.rows.end(), compareShortestPath); EXPECT_EQ(resultDs, expected); EXPECT_EQ(result.state(), Result::State::kSuccess); } } TEST_F(ProduceSemiShortestPathTest, EmptyInput) { auto* pssp = ProduceSemiShortestPath::make(qctx_.get(), nullptr); pssp->setInputVar("empty_get_neighbors"); pssp->setColNames({"_dst", "_src", "cost", "paths"}); auto psspExe = std::make_unique<ProduceSemiShortestPathExecutor>(pssp, qctx_.get()); auto future = psspExe->execute(); auto status = std::move(future).get(); EXPECT_TRUE(status.ok()); auto& result = qctx_->ectx()->getResult(pssp->outputVar()); DataSet expected; expected.colNames = {"_dst", "_src", "cost", "paths"}; EXPECT_EQ(result.value().getDataSet(), expected); EXPECT_EQ(result.state(), Result::State::kSuccess); } } // namespace graph } // namespace nebula
31.988235
86
0.567243
heyanlong
92f4c3b7352e774f179677b257a58c2c49d7783a
4,947
hh
C++
tce/src/applibs/ProGe/ProGeScriptGenerator.hh
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
74
2015-10-22T15:34:10.000Z
2022-03-25T07:57:23.000Z
tce/src/applibs/ProGe/ProGeScriptGenerator.hh
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
79
2015-11-19T09:23:08.000Z
2022-01-12T14:15:16.000Z
tce/src/applibs/ProGe/ProGeScriptGenerator.hh
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
38
2015-11-17T10:12:23.000Z
2022-03-25T07:57:24.000Z
/* Copyright (c) 2002-2009 Tampere University. This file is part of TTA-Based Codesign Environment (TCE). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @file ProGeScriptGenerator.hh * * Declaration of ProGeScriptGenerator class. * * @author Esa Määttä 2007 (esa.maatta-no.spam-tut.fi) * @author Vinogradov Viacheslav(added Verilog generating) 2012 * @note rating: red */ #ifndef TTA_PROGE_SCRIPT_GENERATOR_HH #define TTA_PROGE_SCRIPT_GENERATOR_HH #include <list> #include "Exception.hh" #include "ProGeTypes.hh" namespace IDF { class MachineImplementation; } /** * Class for script generating objects. * * Base class for script generating. */ class ProGeScriptGenerator { public: ProGeScriptGenerator( const ProGe::HDL language, const IDF::MachineImplementation& idf, const std::string& dstDir, const std::string& progeOutDir, const std::string& sharedOutDir, const std::string& testBenchDir, const std::string& toplevelEntity); virtual ~ProGeScriptGenerator(); void generateAll(); void generateModsimCompile(); void generateGhdlCompile(); void generateIverilogCompile(); void generateModsimSimulate(); void generateGhdlSimulate(); void generateIverilogSimulate(); private: void generateStart( std::ostream& stream); void createExecutableFile(const std::string& fileName); void outputScriptCommands( std::ostream& stream, const std::list<std::string>& files, const std::string& cmdPrefix, const std::string& cmdPostfix); template<typename T> void findFiles( const std::string& perlre, T files, std::list<std::string>& found); template<typename T> void findFiles(const std::string& perlre, T& files); void findText( const std::string& perlre, const unsigned int& matchRegion, const std::string& fileName, std::list<std::string>& found); void getBlockOrder( std::list<std::string>& order); void sortFilesFirst( std::list<std::string>& toSort, std::list<std::string>& acSort); void sortFilesLast( std::list<std::string>& toSort, std::list<std::string>& acSort); template <typename CONT> void uniqueFileNames( CONT& files, const std::string& rootDirectory); void prefixStrings( std::list<std::string>& tlist, const std::string& prefix, int start = 0, int end = -1); void fetchFiles(); void prepareFiles(); // destination directory where scripts are generated. std::string dstDir_; // directory where processor generators output vhdl files are std::string progeOutDir_; // directory where processor generators shared HDL files are std::string sharedOutDir_; // directories where to read test bench vhdl files. std::string testBenchDir_; // lists for file names std::list<std::string> vhdlFiles_; std::list<std::string> gcuicFiles_; std::list<std::string> testBenchFiles_; // directory used by ghdl/modelsim as work directory when compiling const std::string workDir_; const std::string vhdlDir_; const std::string verDir_; const std::string gcuicDir_; const std::string tbDir_; // file names for scripts to be generated const std::string modsimCompileScriptName_; const std::string ghdlCompileScriptName_; const std::string iverilogCompileScriptName_; const std::string modsimSimulateScriptName_; const std::string ghdlSimulateScriptName_; const std::string iverilogSimulateScriptName_; // test bench name const std::string testbenchName_; const std::string toplevelEntity_; const IDF::MachineImplementation& idf_; const ProGe::HDL language_; }; #include "ProGeScriptGenerator.icc" #endif
31.310127
78
0.695573
kanishkan
92f81a3f201aae9487ca7105f8d1f813eead65b8
4,090
cpp
C++
sources/imgmod/main.cpp
ucpu/qasmint
a25714bca69fc6ce893e9472daf4a1eb03bd56a6
[ "MIT" ]
3
2022-02-12T06:54:20.000Z
2022-02-26T21:54:59.000Z
sources/imgmod/main.cpp
ucpu/qasmint
a25714bca69fc6ce893e9472daf4a1eb03bd56a6
[ "MIT" ]
null
null
null
sources/imgmod/main.cpp
ucpu/qasmint
a25714bca69fc6ce893e9472daf4a1eb03bd56a6
[ "MIT" ]
null
null
null
#include <cage-core/logger.h> #include <cage-core/ini.h> #include <cage-core/config.h> #include <cage-core/files.h> #include <cage-core/image.h> #include <qasm/qasm.h> using namespace qasm; int main(int argc, const char *args[]) { try { Holder<Logger> logger = newLogger(); logger->format.bind<logFormatConsole>(); logger->output.bind<logOutputStdOut>(); ConfigString programPath("imgmod/path/program", "imgmod.qasm"); ConfigString limitsPath("imgmod/path/limits"); ConfigString inputPath("imgmod/path/input"); ConfigString outputPath("imgmod/path/output"); { Holder<Ini> ini = newIni(); ini->parseCmd(argc, args); programPath = ini->cmdString('p', "program", programPath); limitsPath = ini->cmdString('l', "limits", limitsPath); inputPath = ini->cmdString('i', "input", inputPath); outputPath = ini->cmdString('o', "output", outputPath); ini->checkUnusedWithHelp(); } if (string(inputPath).empty() || string(outputPath).empty()) CAGE_THROW_ERROR(Exception, "no input or output path"); Holder<Image> img = newImage(); ImageFormatEnum originalFormat = ImageFormatEnum::Default; { CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "loading image at path: '" + string(inputPath) + "'"); img->importFile(inputPath); CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "resolution: " + img->width() + "x" + img->height()); CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "channels: " + img->channels()); originalFormat = img->format(); imageConvert(+img, ImageFormatEnum::Float); } Holder<Program> program; { CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "loading program at path: '" + string(programPath) + "'"); Holder<File> file = readFile(programPath); Holder<Compiler> compiler = newCompiler(); program = compiler->compile(file->readAll()); CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "program has: " + program->instructionsCount() + " instructions"); } Holder<Cpu> cpu; { CpuCreateConfig cfg; for (uint32 i = 0; i < 4; i++) cfg.limits.memoryCapacity[i] = img->width() * img->height() * img->channels(); if (!string(limitsPath).empty()) { CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "loading limits at path: '" + string(limitsPath) + "'"); Holder<Ini> limits = newIni(); limits->importFile(limitsPath); cfg.limits = qasm::limitsFromIni(+limits, cfg.limits); } cpu = newCpu(cfg); cpu->program(+program); } { auto fv = img->rawViewFloat(); cpu->memory(0, { (const uint32 *)fv.begin(), (const uint32 *)fv.end() }); uint32 regs[26]; regs['W' - 'A'] = img->width(); regs['H' - 'A'] = img->height(); regs['C' - 'A'] = img->channels(); cpu->registers(regs); } try { cpu->run(); CAGE_LOG(SeverityEnum::Note, "imgmod", stringizer() + "finished in " + cpu->stepIndex() + " steps"); } catch (...) { CAGE_LOG(SeverityEnum::Note, "imgmod", stringizer() + "function: " + program->functionName(cpu->functionIndex())); CAGE_LOG(SeverityEnum::Note, "imgmod", stringizer() + "source: " + program->sourceCodeLine(cpu->sourceLine())); CAGE_LOG(SeverityEnum::Note, "imgmod", stringizer() + "line: " + (cpu->sourceLine() + 1)); CAGE_LOG(SeverityEnum::Note, "imgmod", stringizer() + "step: " + cpu->stepIndex()); throw; } { Holder<Image> img = newImage(); const auto mem = cpu->memory(0); const auto regs = cpu->registers(); img->importRaw({ (const char *)mem.begin(), (const char *)mem.end() }, regs['W' - 'A'], regs['H' - 'A'], regs['C' - 'A'], ImageFormatEnum::Float); CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "resolution: " + img->width() + "x" + img->height()); CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "channels: " + img->channels()); imageConvert(+img, originalFormat); CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "saving image at path: '" + string(outputPath) + "'"); img->exportFile(outputPath); } return 0; } catch (...) { detail::logCurrentCaughtException(); } return 1; }
34.369748
149
0.641565
ucpu
92f8e1f6514e85c5bf42a3993e7f18e326dabcdc
2,120
cpp
C++
Linked_List/Circular_Linked_List/circular_linked_list.cpp
AshishS-1123/Data-Structures
58c36b7f1e0bc72064aac5ff53f96c7df34e52b5
[ "MIT" ]
null
null
null
Linked_List/Circular_Linked_List/circular_linked_list.cpp
AshishS-1123/Data-Structures
58c36b7f1e0bc72064aac5ff53f96c7df34e52b5
[ "MIT" ]
null
null
null
Linked_List/Circular_Linked_List/circular_linked_list.cpp
AshishS-1123/Data-Structures
58c36b7f1e0bc72064aac5ff53f96c7df34e52b5
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; // structure to denote node in list typedef struct node { // member to hold data of node int data; // pointer to next node struct node* next; }node; // a node to point to some element in the list node* start; /* Function: preety_print Desc: utility for printing elements in intuitive format Args: element -> element if list that is going to be printed Returns: preety_string -> prettified string version for element */ string preety_print(int element) { int dashes = to_string(element).size() + 6; string preety_string; for(int i = 0; i < dashes; ++i) preety_string += "_"; return preety_string; } /* Function: print_list Desc: prints the given circular linked list Args: start -> any pointer pointing to a node in the list Returns: None */ void print_list(node* start) { // node for traversing the list node* end = start; // if there is a single element in the list if(start->next == start) { cout << "\t" << start->data << "\n\n"; return; } cout << "\t"; string line_below(" |"); // keep traversing the list until we reach the start node do { // print the current node cout << end->data; if(end->next != start) { line_below += preety_print(end->data); cout << " ---> "; } // move end to next node end = end->next; }while(end != start); line_below[line_below.size()-1] = '|'; cout << "\n" << line_below <<"\n\n"; } /* Function: cleanup Desc: deallocates memory of all nodes in list Args: start -> pointer to any node in list Returns: None */ void cleanup(node* start) { // pointer for traversal node* end = start; // loop through all the nodes do { cout << "\tDelete " << end->data << "\n"; // temporarily hold location of end node node* temp = end; // increment the end node end = end->next; // deallocate the current node free(temp); }while(end != start); }
20.784314
63
0.586792
AshishS-1123
92f9ba892087484ba5827bf1cf0cd0e1e6ce6b69
473
cpp
C++
src/behaviours/src/StraightLineBehavior.cpp
BCLab-UNM/SwarmBaseCode-Modular-Public
2061796570baf65deeb74f29444fcaf3b6464aa1
[ "MIT" ]
null
null
null
src/behaviours/src/StraightLineBehavior.cpp
BCLab-UNM/SwarmBaseCode-Modular-Public
2061796570baf65deeb74f29444fcaf3b6464aa1
[ "MIT" ]
null
null
null
src/behaviours/src/StraightLineBehavior.cpp
BCLab-UNM/SwarmBaseCode-Modular-Public
2061796570baf65deeb74f29444fcaf3b6464aa1
[ "MIT" ]
null
null
null
#include "StraightLineBehavior.hpp" #include "Velocity.hpp" StraightLineBehavior::StraightLineBehavior() {} void StraightLineBehavior::Update(const SwarmieSensors& sensors, const SwarmieAction& ll_action) { _action = ll_action; // TODO: guard against waypoint actions if(ll_action.GetVelocity().GetAngularMagnitude() < 0.75) { core::VelocityAction v = ll_action.GetVelocity(); v.SetLinear(LinearVelocity(0.5)); _action.SetAction(v); } }
24.894737
96
0.727273
BCLab-UNM
92fddcb009cb6a3a4adfe664713c50e01256f673
1,666
cc
C++
src/pika_cmd_table_manager.cc
yihaoDeng/pika
7ddc45483c9df05672a118e99844e4dc19552c79
[ "MIT" ]
6
2019-01-11T04:11:33.000Z
2019-12-12T09:01:46.000Z
src/pika_cmd_table_manager.cc
yihaoDeng/pika
7ddc45483c9df05672a118e99844e4dc19552c79
[ "MIT" ]
null
null
null
src/pika_cmd_table_manager.cc
yihaoDeng/pika
7ddc45483c9df05672a118e99844e4dc19552c79
[ "MIT" ]
5
2019-01-11T03:38:00.000Z
2019-12-04T11:08:01.000Z
// Copyright (c) 2018-present, Qihoo, 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 "include/pika_cmd_table_manager.h" PikaCmdTableManager::PikaCmdTableManager() { pthread_rwlock_init(&map_protector_, NULL); } PikaCmdTableManager::~PikaCmdTableManager() { pthread_rwlock_destroy(&map_protector_); for (const auto& item : thread_table_map_) { CmdTable* cmd_table = item.second; CmdTable::const_iterator it = cmd_table->begin(); for (; it != cmd_table->end(); ++it) { delete it->second; } delete cmd_table; } } Cmd* PikaCmdTableManager::GetCmd(const std::string& opt) { pid_t tid = gettid(); CmdTable* cmd_table = nullptr; if (!CheckCurrentThreadCmdTableExist(tid)) { InsertCurrentThreadCmdTable(); } slash::RWLock l(&map_protector_, false); cmd_table = thread_table_map_[tid]; CmdTable::const_iterator iter = cmd_table->find(opt); if (iter != cmd_table->end()) { return iter->second; } return NULL; } bool PikaCmdTableManager::CheckCurrentThreadCmdTableExist(const pid_t& tid) { slash::RWLock l(&map_protector_, false); if (thread_table_map_.find(tid) == thread_table_map_.end()) { return false; } return true; } void PikaCmdTableManager::InsertCurrentThreadCmdTable() { pid_t tid = gettid(); CmdTable* cmds = new CmdTable(); cmds->reserve(300); InitCmdTable(cmds); slash::RWLock l(&map_protector_, true); thread_table_map_.insert(make_pair(tid, cmds)); }
29.75
78
0.719088
yihaoDeng
1301337f01aafee340f9e4a5c8fe665d85b1e92b
13,052
cpp
C++
sdk/transmission/ipc/standard/src/trans_server_proxy_standard.cpp
openharmony-gitee-mirror/communication_dsoftbus
afae96a6c8674d6ac7de307fccfa2dd205e5bcf6
[ "Apache-2.0" ]
2
2021-11-22T15:58:06.000Z
2021-12-03T13:57:01.000Z
sdk/transmission/ipc/standard/src/trans_server_proxy_standard.cpp
openharmony-gitee-mirror/communication_dsoftbus
afae96a6c8674d6ac7de307fccfa2dd205e5bcf6
[ "Apache-2.0" ]
null
null
null
sdk/transmission/ipc/standard/src/trans_server_proxy_standard.cpp
openharmony-gitee-mirror/communication_dsoftbus
afae96a6c8674d6ac7de307fccfa2dd205e5bcf6
[ "Apache-2.0" ]
4
2021-09-13T11:17:56.000Z
2022-03-31T01:28:33.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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 "trans_server_proxy_standard.h" #include "ipc_skeleton.h" #include "system_ability_definition.h" #include "message_parcel.h" #include "softbus_errcode.h" #include "softbus_ipc_def.h" #include "softbus_log.h" namespace OHOS { static uint32_t g_getSystemAbilityId = 2; static sptr<IRemoteObject> GetSystemAbility() { MessageParcel data; data.WriteInt32(SOFTBUS_SERVER_SA_ID); MessageParcel reply; MessageOption option; sptr<IRemoteObject> samgr = IPCSkeleton::GetContextObject(); int32_t err = samgr->SendRequest(g_getSystemAbilityId, data, reply, option); if (err != 0) { LOG_ERR("Get GetSystemAbility failed!\n"); return nullptr; } return reply.ReadRemoteObject(); } int32_t TransServerProxy::StartDiscovery(const char *pkgName, const SubscribeInfo *subInfo) { return SOFTBUS_OK; } int32_t TransServerProxy::StopDiscovery(const char *pkgName, int subscribeId) { return SOFTBUS_OK; } int32_t TransServerProxy::PublishService(const char *pkgName, const PublishInfo *pubInfo) { return SOFTBUS_OK; } int32_t TransServerProxy::UnPublishService(const char *pkgName, int publishId) { return SOFTBUS_OK; } int32_t TransServerProxy::SoftbusRegisterService(const char *clientPkgName, const sptr<IRemoteObject>& object) { return SOFTBUS_OK; } int32_t TransServerProxy::CreateSessionServer(const char *pkgName, const char *sessionName) { if (pkgName == nullptr || sessionName == nullptr) { return SOFTBUS_ERR; } sptr<IRemoteObject> remote = GetSystemAbility(); if (remote == nullptr) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "remote is nullptr!"); return SOFTBUS_ERR; } MessageParcel data; if (!data.WriteCString(pkgName)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "CreateSessionServer write pkg name failed!"); return SOFTBUS_ERR; } if (!data.WriteCString(sessionName)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "CreateSessionServer write session name failed!"); return SOFTBUS_ERR; } MessageParcel reply; MessageOption option; if (remote->SendRequest(SERVER_CREATE_SESSION_SERVER, data, reply, option) != 0) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "CreateSessionServer send request failed!"); return SOFTBUS_ERR; } int32_t serverRet = 0; if (!reply.ReadInt32(serverRet)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "CreateSessionServer read serverRet failed!"); return SOFTBUS_ERR; } return serverRet; } int32_t TransServerProxy::RemoveSessionServer(const char *pkgName, const char *sessionName) { if (pkgName == nullptr || sessionName == nullptr) { return SOFTBUS_ERR; } sptr<IRemoteObject> remote = GetSystemAbility(); if (remote == nullptr) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "remote is nullptr!"); return SOFTBUS_ERR; } MessageParcel data; if (!data.WriteCString(pkgName)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "RemoveSessionServer write pkg name failed!"); return SOFTBUS_ERR; } if (!data.WriteCString(sessionName)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "RemoveSessionServer session name failed!"); return SOFTBUS_ERR; } MessageParcel reply; MessageOption option; if (remote->SendRequest(SERVER_REMOVE_SESSION_SERVER, data, reply, option) != 0) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "RemoveSessionServer send request failed!"); return SOFTBUS_ERR; } int32_t serverRet = 0; if (!reply.ReadInt32(serverRet)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "RemoveSessionServer read serverRet failed!"); return SOFTBUS_ERR; } return serverRet; } int32_t TransServerProxy::OpenSession(const SessionParam *param, TransInfo *info) { if (param->sessionName == nullptr || param->peerSessionName == nullptr || param->peerDeviceId == nullptr || param->groupId == nullptr) { return SOFTBUS_ERR; } sptr<IRemoteObject> remote = GetSystemAbility(); if (remote == nullptr) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "remote is nullptr!"); return SOFTBUS_ERR; } MessageParcel data; if (!data.WriteCString(param->sessionName)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession write my session name failed!"); return SOFTBUS_ERR; } if (!data.WriteCString(param->peerSessionName)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession write peer session name failed!"); return SOFTBUS_ERR; } if (!data.WriteCString(param->peerDeviceId)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession write addr type length failed!"); return SOFTBUS_ERR; } if (!data.WriteCString(param->groupId)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession write addr type length failed!"); return SOFTBUS_ERR; } if (!data.WriteRawData(param->attr, sizeof(SessionAttribute))) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession write addr type length failed!"); return SOFTBUS_ERR; } MessageParcel reply; MessageOption option; if (remote->SendRequest(SERVER_OPEN_SESSION, data, reply, option) != 0) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession send request failed!"); return SOFTBUS_ERR; } TransSerializer *transSerializer = (TransSerializer *)reply.ReadRawData(sizeof(TransSerializer)); if (transSerializer == nullptr) { SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "OpenSession read TransSerializer failed!"); return SOFTBUS_ERR; } info->channelId = transSerializer->transInfo.channelId; info->channelType = transSerializer->transInfo.channelType; return transSerializer->ret; } int32_t TransServerProxy::OpenAuthSession(const char *sessionName, const ConnectionAddr *addrInfo) { if (sessionName == nullptr || addrInfo == nullptr) { return SOFTBUS_INVALID_PARAM; } SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, "%s ServerIpcOpenAuthSession begin", sessionName); sptr<IRemoteObject> remote = Remote(); if (remote == nullptr) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "remote is nullptr!"); return SOFTBUS_ERR; } MessageParcel data; if (!data.WriteCString(sessionName)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession write my session name failed!"); return SOFTBUS_ERR; } if (!data.WriteRawData((void *)addrInfo, sizeof(ConnectionAddr))) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession write ConnectionAddr failed!"); return SOFTBUS_ERR; } MessageParcel reply; MessageOption option; if (remote->SendRequest(SERVER_OPEN_AUTH_SESSION, data, reply, option) != 0) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession send request failed!"); return SOFTBUS_ERR; } int32_t channelId = 0; if (!reply.ReadInt32(channelId)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession read channelId failed!"); return SOFTBUS_ERR; } return channelId; } int32_t TransServerProxy::NotifyAuthSuccess(int channelId) { sptr<IRemoteObject> remote = GetSystemAbility(); if (remote == nullptr) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "remote is nullptr!"); return SOFTBUS_ERR; } MessageParcel data; if (!data.WriteInt32(channelId)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "ServerIpcNotifyAuthSuccess write channel id failed!"); return SOFTBUS_ERR; } MessageParcel reply; MessageOption option; if (remote->SendRequest(SERVER_NOTIFY_AUTH_SUCCESS, data, reply, option) != 0) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "ServerIpcNotifyAuthSuccess send request failed!"); return SOFTBUS_ERR; } int32_t serverRet = 0; if (!reply.ReadInt32(serverRet)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "ServerIpcNotifyAuthSuccess read serverRet failed!"); return SOFTBUS_ERR; } return serverRet; } int32_t TransServerProxy::CloseChannel(int32_t channelId, int32_t channelType) { sptr<IRemoteObject> remote = GetSystemAbility(); if (remote == nullptr) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "remote is nullptr!"); return SOFTBUS_ERR; } MessageParcel data; if (!data.WriteInt32(channelId)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "CloseChannel write channel id failed!"); return SOFTBUS_ERR; } if (!data.WriteInt32(channelType)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "CloseChannel write channel type failed!"); return SOFTBUS_ERR; } MessageParcel reply; MessageOption option; if (remote->SendRequest(SERVER_CLOSE_CHANNEL, data, reply, option) != 0) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "CloseChannel send request failed!"); return SOFTBUS_ERR; } int32_t serverRet = 0; if (!reply.ReadInt32(serverRet)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "CloseChannel read serverRet failed!"); return SOFTBUS_ERR; } return serverRet; } int32_t TransServerProxy::SendMessage(int32_t channelId, int32_t channelType, const void *dataInfo, uint32_t len, int32_t msgType) { sptr<IRemoteObject> remote = GetSystemAbility(); if (remote == nullptr) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "remote is nullptr!"); return SOFTBUS_ERR; } MessageParcel data; if (!data.WriteInt32(channelId)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "SendMessage write channel id failed!"); return SOFTBUS_ERR; } if (!data.WriteInt32(channelType)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "SendMessage write channel type failed!"); return SOFTBUS_ERR; } if (!data.WriteUint32(len)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "SendMessage write dataInfo len failed!"); return SOFTBUS_ERR; } if (!data.WriteRawData(dataInfo, len)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "SendMessage write dataInfo failed!"); return SOFTBUS_ERR; } if (!data.WriteInt32(msgType)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "SendMessage msgType failed!"); return SOFTBUS_ERR; } MessageParcel reply; MessageOption option; if (remote->SendRequest(SERVER_SESSION_SENDMSG, data, reply, option) != 0) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "SendMessage send request failed!"); return SOFTBUS_ERR; } int32_t serverRet = 0; if (!reply.ReadInt32(serverRet)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "SendMessage read serverRet failed!"); return SOFTBUS_ERR; } return serverRet; } int32_t TransServerProxy::JoinLNN(const char *pkgName, void *addr, uint32_t addrTypeLen) { return SOFTBUS_OK; } int32_t TransServerProxy::LeaveLNN(const char *pkgName, const char *networkId) { return SOFTBUS_OK; } int32_t TransServerProxy::GetAllOnlineNodeInfo(const char *pkgName, void **info, uint32_t infoTypeLen, int *infoNum) { return SOFTBUS_OK; } int32_t TransServerProxy::GetLocalDeviceInfo(const char *pkgName, void *info, uint32_t infoTypeLen) { return SOFTBUS_OK; } int32_t TransServerProxy::GetNodeKeyInfo(const char *pkgName, const char *networkId, int key, unsigned char *buf, uint32_t len) { return SOFTBUS_OK; } int32_t TransServerProxy::StartTimeSync(const char *pkgName, const char *targetNetworkId, int32_t accuracy, int32_t period) { return SOFTBUS_OK; } int32_t TransServerProxy::StopTimeSync(const char *pkgName, const char *targetNetworkId) { return SOFTBUS_OK; } }
36.255556
117
0.689933
openharmony-gitee-mirror
1302950cea1520981d3001bc8f8d5fcc6cf19c5e
110,231
cpp
C++
src/ConEmuHk/SetHook.cpp
Maximus5/git-bug-1
a52853b683dde57cbd29e943299ab46451c542f4
[ "BSD-3-Clause" ]
1
2015-05-08T22:47:13.000Z
2015-05-08T22:47:13.000Z
src/ConEmuHk/SetHook.cpp
Maximus5/git-bug-1
a52853b683dde57cbd29e943299ab46451c542f4
[ "BSD-3-Clause" ]
null
null
null
src/ConEmuHk/SetHook.cpp
Maximus5/git-bug-1
a52853b683dde57cbd29e943299ab46451c542f4
[ "BSD-3-Clause" ]
null
null
null
 /* Copyright (c) 2009-2015 Maximus5 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. 3. The name of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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. */ #define DROP_SETCP_ON_WIN2K3R2 //#define SKIPHOOKLOG //#define USE_ONLY_INT_CHECK_PTR #undef USE_ONLY_INT_CHECK_PTR // Иначе не опередяется GetConsoleAliases (хотя он должен быть доступен в Win2k) #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 #define DEFINE_HOOK_MACROS #ifdef _DEBUG #define HOOK_ERROR_PROC //#undef HOOK_ERROR_PROC #define HOOK_ERROR_NO ERROR_INVALID_DATA #else #undef HOOK_ERROR_PROC #endif #define USECHECKPROCESSMODULES //#define ASSERT_ON_PROCNOTFOUND #include <windows.h> #include <Tlhelp32.h> #ifndef __GNUC__ #include <intrin.h> #else #define _InterlockedIncrement InterlockedIncrement #endif #include "../common/common.hpp" #include "../common/ConEmuCheck.h" #include "../common/MSection.h" #include "../common/WObjects.h" //#include "../common/MArray.h" #include "ShellProcessor.h" #include "SetHook.h" #include "ConEmuHooks.h" #include "Ansi.h" #ifdef _DEBUG //WARNING!!! OutputDebugString must NOT be used from ConEmuHk::DllMain(DLL_PROCESS_DETACH). See Issue 465 #define DebugString(x) //if ((gnDllState != ds_DllProcessDetach) || gbIsSshProcess) OutputDebugString(x) #define DebugStringA(x) //if ((gnDllState != ds_DllProcessDetach) || gbIsSshProcess) OutputDebugStringA(x) #else #define DebugString(x) #define DebugStringA(x) #endif HMODULE ghOurModule = NULL; // Хэндл нашей dll'ки (здесь хуки не ставятся) DWORD gnHookMainThreadId = 0; MMap<DWORD,BOOL> gStartedThreads; extern HWND ghConWnd; // RealConsole extern BOOL gbDllStopCalled; extern BOOL gbHooksWasSet; extern bool gbPrepareDefaultTerminal; #ifdef _DEBUG bool gbSuppressShowCall = false; bool gbSkipSuppressShowCall = false; bool gbSkipCheckProcessModules = false; #endif bool gbHookExecutableOnly = false; //!!!All dll names MUST BE LOWER CASE!!! //!!!WARNING!!! Добавляя в этот список - не забыть добавить и в GetPreloadModules() !!! const wchar_t *kernelbase = L"kernelbase.dll", *kernelbase_noext = L"kernelbase"; const wchar_t *kernel32 = L"kernel32.dll", *kernel32_noext = L"kernel32"; const wchar_t *user32 = L"user32.dll", *user32_noext = L"user32"; const wchar_t *gdi32 = L"gdi32.dll", *gdi32_noext = L"gdi32"; const wchar_t *shell32 = L"shell32.dll", *shell32_noext = L"shell32"; const wchar_t *advapi32 = L"advapi32.dll", *advapi32_noext = L"advapi32"; const wchar_t *comdlg32 = L"comdlg32.dll", *comdlg32_noext = L"comdlg32"; //!!!WARNING!!! Добавляя в этот список - не забыть добавить и в GetPreloadModules() !!! HMODULE ghKernelBase = NULL, ghKernel32 = NULL, ghUser32 = NULL, ghGdi32 = NULL, ghShell32 = NULL, ghAdvapi32 = NULL, ghComdlg32 = NULL; HMODULE* ghSysDll[] = {&ghKernelBase, &ghKernel32, &ghUser32, &ghGdi32, &ghShell32, &ghAdvapi32, &ghComdlg32}; //!!!WARNING!!! Добавляя в этот список - не забыть добавить и в GetPreloadModules() !!! struct UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; }; enum LDR_DLL_NOTIFICATION_REASON { LDR_DLL_NOTIFICATION_REASON_LOADED = 1, LDR_DLL_NOTIFICATION_REASON_UNLOADED = 2, }; struct LDR_DLL_LOADED_NOTIFICATION_DATA { ULONG Flags; //Reserved. const UNICODE_STRING* FullDllName; //The full path name of the DLL module. const UNICODE_STRING* BaseDllName; //The base file name of the DLL module. PVOID DllBase; //A pointer to the base address for the DLL in memory. ULONG SizeOfImage; //The size of the DLL image, in bytes. }; struct LDR_DLL_UNLOADED_NOTIFICATION_DATA { ULONG Flags; //Reserved. const UNICODE_STRING* FullDllName; //The full path name of the DLL module. const UNICODE_STRING* BaseDllName; //The base file name of the DLL module. PVOID DllBase; //A pointer to the base address for the DLL in memory. ULONG SizeOfImage; //The size of the DLL image, in bytes. }; union LDR_DLL_NOTIFICATION_DATA { LDR_DLL_LOADED_NOTIFICATION_DATA Loaded; LDR_DLL_UNLOADED_NOTIFICATION_DATA Unloaded; }; typedef VOID (CALLBACK* PLDR_DLL_NOTIFICATION_FUNCTION)(ULONG NotificationReason, const LDR_DLL_NOTIFICATION_DATA* NotificationData, PVOID Context); VOID CALLBACK LdrDllNotification(ULONG NotificationReason, const LDR_DLL_NOTIFICATION_DATA* NotificationData, PVOID Context); typedef NTSTATUS (NTAPI* LdrRegisterDllNotification_t)(ULONG Flags, PLDR_DLL_NOTIFICATION_FUNCTION NotificationFunction, PVOID Context, PVOID *Cookie); typedef NTSTATUS (NTAPI* LdrUnregisterDllNotification_t)(PVOID Cookie); static LdrRegisterDllNotification_t LdrRegisterDllNotification = NULL; static LdrUnregisterDllNotification_t LdrUnregisterDllNotification = NULL; static PVOID gpLdrDllNotificationCookie = NULL; static NTSTATUS gnLdrDllNotificationState = (NTSTATUS)-1; static bool gbLdrDllNotificationUsed = false; // Forwards bool PrepareNewModule(HMODULE module, LPCSTR asModuleA, LPCWSTR asModuleW, BOOL abNoSnapshoot = FALSE, BOOL abForceHooks = FALSE); void UnprepareModule(HMODULE hModule, LPCWSTR pszModule, int iStep); //typedef LONG (WINAPI* RegCloseKey_t)(HKEY hKey); RegCloseKey_t RegCloseKey_f = NULL; //typedef LONG (WINAPI* RegOpenKeyEx_t)(HKEY hKey, LPCWSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult); RegOpenKeyEx_t RegOpenKeyEx_f = NULL; //typedef LONG (WINAPI* RegCreateKeyEx_t(HKEY hKey, LPCWSTR lpSubKey, DWORD Reserved, LPWSTR lpClass, DWORD dwOptions, REGSAM samDesired, LPSECURITY_ATTRIBUTES lpSecurityAttributes, PHKEY phkResult, LPDWORD lpdwDisposition); RegCreateKeyEx_t RegCreateKeyEx_f = NULL; //typedef BOOL (WINAPI* OnChooseColorA_t)(LPCHOOSECOLORA lpcc); OnChooseColorA_t ChooseColorA_f = NULL; //typedef BOOL (WINAPI* OnChooseColorW_t)(LPCHOOSECOLORW lpcc); OnChooseColorW_t ChooseColorW_f = NULL; struct PreloadFuncs { LPCSTR sFuncName; void** pFuncPtr; }; struct PreloadModules { LPCWSTR sModule, sModuleNoExt; HMODULE *pModulePtr; PreloadFuncs Funcs[5]; }; size_t GetPreloadModules(PreloadModules** ppModules) { static PreloadModules Checks[] = { {gdi32, gdi32_noext, &ghGdi32}, {shell32, shell32_noext, &ghShell32}, {advapi32, advapi32_noext, &ghAdvapi32, {{"RegOpenKeyExW", (void**)&RegOpenKeyEx_f}, {"RegCreateKeyExW", (void**)&RegCreateKeyEx_f}, {"RegCloseKey", (void**)&RegCloseKey_f}} }, {comdlg32, comdlg32_noext, &ghComdlg32, {{"ChooseColorA", (void**)&ChooseColorA_f}, {"ChooseColorW", (void**)&ChooseColorW_f}} }, }; *ppModules = Checks; return countof(Checks); } void CheckLoadedModule(LPCWSTR asModule) { if (!asModule || !*asModule) return; PreloadModules* Checks = NULL; size_t nChecks = GetPreloadModules(&Checks); for (size_t m = 0; m < nChecks; m++) { if ((*Checks[m].pModulePtr) != NULL) continue; if (!lstrcmpiW(asModule, Checks[m].sModule) || !lstrcmpiW(asModule, Checks[m].sModuleNoExt)) { *Checks[m].pModulePtr = LoadLibraryW(Checks[m].sModule); // LoadLibrary, т.к. и нам он нужен - накрутить счетчик if ((*Checks[m].pModulePtr) != NULL) { _ASSERTEX(Checks[m].Funcs[countof(Checks[m].Funcs)-1].sFuncName == NULL); for (size_t f = 0; f < countof(Checks[m].Funcs) && Checks[m].Funcs[f].sFuncName; f++) { *Checks[m].Funcs[f].pFuncPtr = (void*)GetProcAddress(*Checks[m].pModulePtr, Checks[m].Funcs[f].sFuncName); } } } } } void FreeLoadedModule(HMODULE hModule) { if (!hModule) return; PreloadModules* Checks = NULL; size_t nChecks = GetPreloadModules(&Checks); for (size_t m = 0; m < nChecks; m++) { if ((*Checks[m].pModulePtr) != hModule) continue; if (GetModuleHandle(Checks[m].sModule) == NULL) { // По идее, такого быть не должно, т.к. счетчик мы накрутили, библиотека не должна была выгрузиться _ASSERTEX(*Checks[m].pModulePtr == NULL); *Checks[m].pModulePtr = NULL; _ASSERTEX(Checks[m].Funcs[countof(Checks[m].Funcs)-1].sFuncName == NULL); for (size_t f = 0; f < countof(Checks[m].Funcs) && Checks[m].Funcs[f].sFuncName; f++) { *Checks[m].Funcs[f].pFuncPtr = NULL; } } } } #define MAX_HOOKED_PROCS 255 // Использовать GetModuleFileName или CreateToolhelp32Snapshot во время загрузки библиотек нельзя // Однако, хранить список модулей нужно // 1. для того, чтобы знать, в каких модулях хуки уже ставились // 2. для информации, чтобы передать в ConEmu если пользователь включил "Shell and processes log" struct HkModuleInfo { BOOL bUsed; // ячейка занята int Hooked; // 1-модуль обрабатывался (хуки установлены), 2-хуки сняты HMODULE hModule; // хэндл wchar_t sModuleName[128]; // Только информационно, в обработке не участвует HkModuleInfo* pNext; HkModuleInfo* pPrev; size_t nAdrUsed; struct StrAddresses { DWORD_PTR* ppAdr; #ifdef _DEBUG DWORD_PTR ppAdrCopy1, ppAdrCopy2; DWORD_PTR pModulePtr, nModuleSize; #endif DWORD_PTR pOld; DWORD_PTR pOur; union { BOOL bHooked; LPVOID Dummy; }; #ifdef _DEBUG char sName[32]; #endif } Addresses[MAX_HOOKED_PROCS]; }; WARNING("Хорошо бы выделять память под gpHookedModules через VirtualProtect, чтобы защитить ее от изменений дурными программами"); HkModuleInfo *gpHookedModules = NULL, *gpHookedModulesLast = NULL; size_t gnHookedModules = 0; MSectionSimple *gpHookedModulesSection = NULL; void InitializeHookedModules() { _ASSERTE(gpHookedModules==NULL && gpHookedModulesSection==NULL); if (!gpHookedModulesSection) { //MessageBox(NULL, L"InitializeHookedModules", L"Hooks", MB_SYSTEMMODAL); gpHookedModulesSection = new MSectionSimple(true); //WARNING: "new" вызывать из DllStart нельзя! DllStart вызывается НЕ из главной нити, //WARNING: причем, когда главная нить еще не была запущена. В итоге, если это //WARNING: попытаться сделать мы получим: //WARNING: runtime error R6030 - CRT not initialized // -- gpHookedModules = new MArray<HkModuleInfo>; // -- поэтому тупо через массив //#ifdef _DEBUG //gnHookedModules = 16; //#else //gnHookedModules = 256; //#endif gpHookedModules = (HkModuleInfo*)calloc(sizeof(HkModuleInfo),1); if (!gpHookedModules) { _ASSERTE(gpHookedModules!=NULL); } gpHookedModulesLast = gpHookedModules; } } void FinalizeHookedModules() { HLOG1("FinalizeHookedModules",0); if (gpHookedModules) { MSectionLockSimple CS; if (gpHookedModulesSection) CS.Lock(gpHookedModulesSection); HkModuleInfo *p = gpHookedModules; gpHookedModules = NULL; while (p) { HkModuleInfo *pNext = p->pNext; free(p); p = pNext; } } SafeDelete(gpHookedModulesSection); HLOGEND1(); } HkModuleInfo* IsHookedModule(HMODULE hModule, LPWSTR pszName = NULL, size_t cchNameMax = 0) { if (!gpHookedModulesSection) InitializeHookedModules(); if (!gpHookedModules) { _ASSERTE(gpHookedModules!=NULL); return false; } //bool lbHooked = false; //_ASSERTE(gpHookedModules && gpHookedModulesSection); //if (bSection) // Enter Critical Section(gpHookedModulesSection); HkModuleInfo* p = gpHookedModules; while (p) { if (p->bUsed && (p->hModule == hModule)) { _ASSERTE(p->Hooked == 1 || p->Hooked == 2); //lbHooked = true; // Если хотят узнать имя модуля (по hModule) if (pszName && (cchNameMax > 0)) lstrcpyn(pszName, p->sModuleName, (int)cchNameMax); break; } p = p->pNext; } //if (bSection) // Leave Critical Section(gpHookedModulesSection); return p; } HkModuleInfo* AddHookedModule(HMODULE hModule, LPCWSTR sModuleName) { if (!gpHookedModulesSection) InitializeHookedModules(); _ASSERTE(gpHookedModules && gpHookedModulesSection); if (!gpHookedModules) { _ASSERTE(gpHookedModules!=NULL); return NULL; } HkModuleInfo* p = IsHookedModule(hModule); if (!p) { MSectionLockSimple CS; CS.Lock(gpHookedModulesSection); p = gpHookedModules; while (p) { if (!p->bUsed) { p->bUsed = TRUE; // сразу зарезервируем gnHookedModules++; memset(p->Addresses, 0, sizeof(p->Addresses)); p->nAdrUsed = 0; p->Hooked = 1; lstrcpyn(p->sModuleName, sModuleName?sModuleName:L"", countof(p->sModuleName)); // hModule - последним, чтобы не было проблем с другими потоками p->hModule = hModule; goto wrap; } p = p->pNext; } p = (HkModuleInfo*)calloc(sizeof(HkModuleInfo),1); if (!p) { _ASSERTE(p!=NULL); } else { gnHookedModules++; p->bUsed = TRUE; // ячейка занята. тут можно первой, т.к. в цепочку еще не добавили p->Hooked = 1; // модуль обрабатывался (хуки установлены) p->hModule = hModule; // хэндл lstrcpyn(p->sModuleName, sModuleName?sModuleName:L"", countof(p->sModuleName)); //_ASSERTEX(lstrcmpi(p->sModuleName,L"dsound.dll")); p->pNext = NULL; p->pPrev = gpHookedModulesLast; gpHookedModulesLast->pNext = p; gpHookedModulesLast = p; } } wrap: return p; } void RemoveHookedModule(HMODULE hModule) { if (!gpHookedModulesSection) InitializeHookedModules(); _ASSERTE(gpHookedModules && gpHookedModulesSection); if (!gpHookedModules) { _ASSERTE(gpHookedModules!=NULL); return; } HkModuleInfo* p = gpHookedModules; while (p) { if (p->bUsed && (p->hModule == hModule)) { gnHookedModules--; // Именно в такой последовательности, чтобы с другими потоками не драться p->Hooked = 0; p->bUsed = FALSE; break; } p = p->pNext; } } BOOL gbHooksTemporaryDisabled = FALSE; //BOOL gbInShellExecuteEx = FALSE; //typedef VOID (WINAPI* OnLibraryLoaded_t)(HMODULE ahModule); HMODULE ghOnLoadLibModule = NULL; OnLibraryLoaded_t gfOnLibraryLoaded = NULL; OnLibraryLoaded_t gfOnLibraryUnLoaded = NULL; // Forward declarations of the hooks FARPROC WINAPI OnGetProcAddress(HMODULE hModule, LPCSTR lpProcName); FARPROC WINAPI OnGetProcAddressExp(HMODULE hModule, LPCSTR lpProcName); HMODULE WINAPI OnLoadLibraryA(const char* lpFileName); HMODULE WINAPI OnLoadLibraryW(const WCHAR* lpFileName); HMODULE WINAPI OnLoadLibraryExA(const char* lpFileName, HANDLE hFile, DWORD dwFlags); HMODULE WINAPI OnLoadLibraryExW(const WCHAR* lpFileName, HANDLE hFile, DWORD dwFlags); BOOL WINAPI OnFreeLibrary(HMODULE hModule); #ifdef HOOK_ERROR_PROC DWORD WINAPI OnGetLastError(); VOID WINAPI OnSetLastError(DWORD dwErrCode); #endif HookItem *gpHooks = NULL; size_t gnHookedFuncs = 0; //bool gbHooksSorted = false; #if 0 struct HookItemNode { const char* Name; HookItem *p; HookItemNode *pLeft; HookItemNode *pRight; #ifdef _DEBUG size_t nLeftCount; size_t nRightCount; #endif }; HookItemNode *gpHooksTree = NULL; // [MAX_HOOKED_PROCS] HookItemNode *gpHooksRoot = NULL; // Pointer to the "root" item in gpHooksTree #endif //struct HookItemNodePtr //{ // const void* Address; // HookItem *p; // HookItemNodePtr *pLeft; // HookItemNodePtr *pRight; //#ifdef _DEBUG // size_t nLeftCount; // size_t nRightCount; //#endif //}; //HookItemNodePtr *gpHooksTreePtr = NULL; // [MAX_HOOKED_PROCS] //HookItemNodePtr *gpHooksRootPtr = NULL; // Pointer to the "root" item in gpHooksTreePtr //MSectionSimple* gpcsHooksRootPtr = NULL; //HookItemNodePtr *gpHooksTreeNew = NULL; // [MAX_HOOKED_PROCS] //HookItemNodePtr *gpHooksRootNew = NULL; // Pointer to the "root" item in gpHooksTreePtr const char *szGetProcAddress = "GetProcAddress"; const char *szLoadLibraryA = "LoadLibraryA"; const char *szLoadLibraryW = "LoadLibraryW"; const char *szLoadLibraryExA = "LoadLibraryExA"; const char *szLoadLibraryExW = "LoadLibraryExW"; const char *szFreeLibrary = "FreeLibrary"; const char *szWriteConsoleW = "WriteConsoleW"; #ifdef HOOK_ERROR_PROC const char *szGetLastError = "GetLastError"; const char *szSetLastError = "SetLastError"; #endif #define HOOKEXPADDRESSONLY enum HookLibFuncs { hlfGetProcAddress = 0, hlfKernelLast, }; struct HookItemWork { HMODULE hLib; FARPROC OldAddress; FARPROC NewAddress; const char* Name; } gKernelFuncs[hlfKernelLast] = {};/* = { {NULL, OnGetProcAddressExp, szGetProcAddress}, };*/ void InitKernelFuncs() { #undef SETFUNC #define SETFUNC(m,i,f,n) \ gKernelFuncs[i].hLib = m; \ gKernelFuncs[i].OldAddress = NULL; \ gKernelFuncs[i].NewAddress = (FARPROC)f; \ gKernelFuncs[i].Name = n; WARNING("Захукать бы LdrGetProcAddressEx в ntdll.dll, но там нужно не просто экспорты менять, а ставить jmp на входе в функцию"); SETFUNC(ghKernel32/*(ghKernelBase?ghKernelBase:ghKernel32)*/, hlfGetProcAddress, OnGetProcAddressExp, szGetProcAddress); // Индексы первых функций должны совпадать, т.к. там инфа по callback-ам #ifdef _DEBUG if (!gpHooks) { _ASSERTEX(gpHooks!=NULL); } else { for (int f = 0; f < hlfKernelLast; f++) { _ASSERTEX(gpHooks[f].Name==gKernelFuncs[f].Name); } } #endif #undef SETFUNC } bool InitHooksLibrary() { #ifndef HOOKS_SKIP_LIBRARY if (!gpHooks) { _ASSERTE(gpHooks!=NULL); return false; } if (gpHooks[0].NewAddress != NULL) { _ASSERTE(gpHooks[0].NewAddress==NULL); return false; } gnHookedFuncs = 0; #define ADDFUNC(pProc,szName,szDll) \ gpHooks[gnHookedFuncs].NewAddress = pProc; \ gpHooks[gnHookedFuncs].Name = szName; \ gpHooks[gnHookedFuncs].DllName = szDll; \ if (pProc/*need to be, ignore GCC warn*/) gnHookedFuncs++; /* ************************ */ ADDFUNC((void*)OnGetProcAddress, szGetProcAddress, kernel32); // eGetProcAddress, ... // No need to hook these functions in Vista+ if (!gbLdrDllNotificationUsed) { ADDFUNC((void*)OnLoadLibraryA, szLoadLibraryA, kernel32); // ... ADDFUNC((void*)OnLoadLibraryExA, szLoadLibraryExA, kernel32); ADDFUNC((void*)OnLoadLibraryExW, szLoadLibraryExW, kernel32); ADDFUNC((void*)OnFreeLibrary, szFreeLibrary, kernel32); // OnFreeLibrary тоже нужен! } // With only exception of LoadLibraryW - it handles "ExtendedConsole.dll" loading in Far 64 if (gbIsFarProcess || !gbLdrDllNotificationUsed) { ADDFUNC((void*)OnLoadLibraryW, szLoadLibraryW, kernel32); } #ifdef HOOK_ERROR_PROC // Для отладки появления системных ошибок ADDFUNC((void*)OnGetLastError, szGetLastError, kernel32); ADDFUNC((void*)OnSetLastError, szSetLastError, kernel32); // eSetLastError #endif ADDFUNC(NULL,NULL,NULL); #undef ADDFUNC /* ************************ */ #endif return true; } #define MAX_EXCLUDED_MODULES 40 // Skip/ignore/don't set hooks in modules... const wchar_t* ExcludedModules[MAX_EXCLUDED_MODULES] = { L"ntdll.dll", L"kernelbase.dll", L"kernel32.dll", L"user32.dll", L"advapi32.dll", // L"shell32.dll", -- shell нужно обрабатывать обязательно. по крайней мере в WinXP/Win2k3 (ShellExecute должен звать наш CreateProcess) L"wininet.dll", // какой-то криминал с этой библиотекой? //#ifndef _DEBUG L"mssign32.dll", L"crypt32.dll", L"setupapi.dll", // "ConEmu\Bugs\2012\z120711\" L"uxtheme.dll", // подозрение на exception на некоторых Win7 & Far3 (Bugs\2012\120124\Info.txt, пункт 3) WIN3264TEST(L"ConEmuCD.dll",L"ConEmuCD64.dll"), // Loaded in-process when AlternativeServer is started WIN3264TEST(L"ExtendedConsole.dll",L"ExtendedConsole64.dll"), // Our API for Far Manager TrueColor support /* // test L"twext.dll", L"propsys.dll", L"ntmarta.dll", L"Wldap32.dll", L"userenv.dll", L"zipfldr.dll", L"shdocvw.dll", L"linkinfo.dll", L"ntshrui.dll", L"cscapi.dll", */ //#endif // А также исключаются все "API-MS-Win-..." в функции IsModuleExcluded 0 }; BOOL gbLogLibraries = FALSE; DWORD gnLastLogSetChange = 0; // Используется в том случае, если требуется выполнить оригинальную функцию, без нашей обертки // пример в OnPeekConsoleInputW void* __cdecl GetOriginalAddress(void* OurFunction, void* DefaultFunction, BOOL abAllowModified, HookItem** ph) { if (gpHooks) { for (int i = 0; gpHooks[i].NewAddress; i++) { if (gpHooks[i].NewAddress == OurFunction) { *ph = &(gpHooks[i]); // По идее, ExeOldAddress должен совпадать с OldAddress, если включен "Inject ConEmuHk" return (abAllowModified && gpHooks[i].ExeOldAddress) ? gpHooks[i].ExeOldAddress : gpHooks[i].OldAddress; } } } _ASSERT(!gbHooksWasSet || gbLdrDllNotificationUsed && !gbIsFarProcess); // сюда мы попадать не должны return DefaultFunction; } FARPROC WINAPI GetLoadLibraryW() { HookItem* ph; return (FARPROC)GetOriginalAddress((void*)(FARPROC)OnLoadLibraryW, (void*)(FARPROC)LoadLibraryW, FALSE, &ph); } FARPROC WINAPI GetWriteConsoleW() { HookItem* ph; return (FARPROC)GetOriginalAddress((void*)(FARPROC)CEAnsi::OnWriteConsoleW, (void*)(FARPROC)WriteConsoleW, FALSE, &ph); } CInFuncCall::CInFuncCall() { mpn_Counter = NULL; } BOOL CInFuncCall::Inc(int* pnCounter) { BOOL lbFirstCall = FALSE; mpn_Counter = pnCounter; if (mpn_Counter) { lbFirstCall = (*mpn_Counter) == 0; (*mpn_Counter)++; } return lbFirstCall; } CInFuncCall::~CInFuncCall() { if (mpn_Counter && (*mpn_Counter)>0)(*mpn_Counter)--; } MSection* gpHookCS = NULL; bool SetExports(HMODULE Module); DWORD CalculateNameCRC32(const char *apszName) { #if 1 DWORD nCRC32 = 0xFFFFFFFF; static DWORD CRCtable[] = { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D }; DWORD dwRead = lstrlenA(apszName); for (LPBYTE p = (LPBYTE)apszName; (dwRead--);) { nCRC32 = ( nCRC32 >> 8 ) ^ CRCtable[(unsigned char) ((unsigned char) nCRC32 ^ *p++ )]; } // т.к. нас интересует только сравнение - последний XOR необязателен! //nCRC32 = ( nCRC32 ^ 0xFFFFFFFF ); #else // Этот "облегченный" алгоритм был расчитан на wchar_t DWORD nDwordCount = (anNameLen+1) >> 1; DWORD nCRC32 = 0x7A3B91F4; for (DWORD i = 0; i < nDwordCount; i++) nCRC32 ^= ((LPDWORD)apszName)[i]; #endif return nCRC32; } // Заполнить поле HookItem.OldAddress (реальные процедуры из внешних библиотек) // apHooks->Name && apHooks->DllName MUST be for a lifetime bool __stdcall InitHooks(HookItem* apHooks) { size_t i, j; bool skip; static bool bLdrWasChecked = false; if (!bLdrWasChecked) { #ifndef _WIN32_WINNT_WIN8 #define _WIN32_WINNT_WIN8 0x602 #endif _ASSERTE(_WIN32_WINNT_WIN8==0x602); OSVERSIONINFOEXW osvi = {sizeof(osvi), HIBYTE(_WIN32_WINNT_WIN8), LOBYTE(_WIN32_WINNT_WIN8)}; DWORDLONG const dwlConditionMask = VerSetConditionMask(VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL), VER_MINORVERSION, VER_GREATER_EQUAL); BOOL isAllowed = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION, dwlConditionMask); // LdrDllNotification работает так как нам надо начиная с Windows 8 // В предыдущих версиях Windows нотификатор вызывается из LdrpFindOrMapDll // ДО того, как были обработаны импорты функцией LdrpProcessStaticImports (а точнее LdrpSnapThunk) if (isAllowed) { HMODULE hNtDll = GetModuleHandle(L"ntdll.dll"); if (hNtDll) { LdrRegisterDllNotification = (LdrRegisterDllNotification_t)GetProcAddress(hNtDll, "LdrRegisterDllNotification"); LdrUnregisterDllNotification = (LdrUnregisterDllNotification_t)GetProcAddress(hNtDll, "LdrUnregisterDllNotification"); if (LdrRegisterDllNotification && LdrUnregisterDllNotification) { gnLdrDllNotificationState = LdrRegisterDllNotification(0, LdrDllNotification, NULL, &gpLdrDllNotificationCookie); gbLdrDllNotificationUsed = (gnLdrDllNotificationState == 0/*STATUS_SUCCESS*/); } } } bLdrWasChecked = true; } #if 0 if (gbHooksSorted && apHooks) { _ASSERTEX(FALSE && "Hooks are already initialized and blocked"); return false; } #endif if (!gpHookCS) { gpHookCS = new MSection; } //if (!gpcsHooksRootPtr) //{ // gpcsHooksRootPtr = (LPCRITICAL_SECTION)calloc(1,sizeof(*gpcsHooksRootPtr)); // Initialize Critical Section(gpcsHooksRootPtr); //} if (gpHooks == NULL) { gpHooks = (HookItem*)calloc(sizeof(HookItem),MAX_HOOKED_PROCS); if (!gpHooks) return false; if (!InitHooksLibrary()) return false; } if (apHooks && gpHooks) { for (i = 0; apHooks[i].NewAddress; i++) { DWORD NameCRC = CalculateNameCRC32(apHooks[i].Name); if (apHooks[i].Name==NULL || apHooks[i].DllName==NULL) { _ASSERTE(apHooks[i].Name!=NULL && apHooks[i].DllName!=NULL); break; } skip = false; for (j = 0; gpHooks[j].NewAddress; j++) { if (gpHooks[j].NewAddress == apHooks[i].NewAddress) { skip = true; break; } } if (skip) continue; j = 0; // using while, because of j while (gpHooks[j].NewAddress) { if (gpHooks[j].NameCRC == NameCRC && strcmp(gpHooks[j].Name, apHooks[i].Name) == 0 && wcscmp(gpHooks[j].DllName, apHooks[i].DllName) == 0) { // Не должно быть такого - функции должны только добавляться _ASSERTEX(lstrcmpiA(gpHooks[j].Name, apHooks[i].Name) && lstrcmpiW(gpHooks[j].DllName, apHooks[i].DllName)); gpHooks[j].NewAddress = apHooks[i].NewAddress; if (j >= gnHookedFuncs) gnHookedFuncs = j+1; skip = true; break; } j++; } if (skip) continue; if ((j+1) >= MAX_HOOKED_PROCS) { // Превышено допустимое количество _ASSERTE((j+1) < MAX_HOOKED_PROCS); continue; // может какие другие хуки удастся обновить, а не добавить } gpHooks[j].Name = apHooks[i].Name; gpHooks[j].NameOrdinal = apHooks[i].NameOrdinal; gpHooks[j].DllName = apHooks[i].DllName; gpHooks[j].NewAddress = apHooks[i].NewAddress; gpHooks[j].NameCRC = NameCRC; _ASSERTEX(j >= gnHookedFuncs); gnHookedFuncs = j+1; gpHooks[j+1].Name = NULL; // на всякий gpHooks[j+1].NewAddress = NULL; // на всякий } } // Для добавленных в gpHooks функций определить "оригинальный" адрес экспорта for (i = 0; gpHooks[i].NewAddress; i++) { if (gpHooks[i].DllNameA[0] == 0) { int nLen = WideCharToMultiByte(CP_ACP, 0, gpHooks[i].DllName, -1, gpHooks[i].DllNameA, (int)countof(gpHooks[i].DllNameA), 0,0); if (nLen > 0) CharLowerBuffA(gpHooks[i].DllNameA, nLen); } if (!gpHooks[i].OldAddress) { // Сейчас - не загружаем HMODULE mod = GetModuleHandle(gpHooks[i].DllName); if (mod == NULL) { _ASSERTE(mod != NULL // Библиотеки, которые могут быть НЕ подлинкованы на старте || (gpHooks[i].DllName == shell32 || gpHooks[i].DllName == user32 || gpHooks[i].DllName == gdi32 || gpHooks[i].DllName == advapi32 || gpHooks[i].DllName == comdlg32 )); } else { WARNING("Тут часто возвращается XXXStub вместо самой функции!"); const char* ExportName = gpHooks[i].NameOrdinal ? ((const char*)gpHooks[i].NameOrdinal) : gpHooks[i].Name; gpHooks[i].OldAddress = (void*)GetProcAddress(mod, ExportName); // WinXP does not have many hooked functions, will not show dozens of asserts #ifdef _DEBUG if (gpHooks[i].OldAddress == NULL) { static int isWin7 = 0; if (isWin7 == 0) { OSVERSIONINFOEXW osvi = {sizeof(osvi), HIBYTE(_WIN32_WINNT_WIN7), LOBYTE(_WIN32_WINNT_WIN7)}; DWORDLONG const dwlConditionMask = VerSetConditionMask(VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL), VER_MINORVERSION, VER_GREATER_EQUAL); BOOL isGrEq = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION, dwlConditionMask); isWin7 = isGrEq ? 1 : -1; } _ASSERTE((isWin7 == -1) || (gpHooks[i].OldAddress != NULL)); } #endif gpHooks[i].hDll = mod; } } } // Обработать экспорты в Kernel32.dll static bool KernelHooked = false; if (!KernelHooked) { KernelHooked = true; _ASSERTEX(ghKernel32!=NULL); if (IsWin7()) { ghKernelBase = LoadLibrary(kernelbase); } InitKernelFuncs(); WARNING("Без перехвата экспорта в kernel не работает поддержка UPX-нутых модулей"); // Но при такой обработке валится EMenu на Win8 TODO("Нужно вставлять jmp в начало функции LdrGetProcAddressEx в ntdll.dll"); #if 0 // Необходимо для обработки UPX-нутых модулей SetExports(ghKernel32); #endif /* if (ghKernelBase) { WARNING("will fail on Win7 x64"); SetExports(ghKernelBase); } */ } return true; } #if 0 void AddHooksNode(HookItemNode* pRoot, HookItem* p, HookItemNode*& ppNext) { int iCmp = strcmp(p->Name, pRoot->Name); _ASSERTEX(iCmp!=0); // All function names must be unique! if (iCmp < 0) { pRoot->nLeftCount++; if (!pRoot->pLeft) { ppNext->p = p; ppNext->Name = p->Name; pRoot->pLeft = ppNext++; return; } AddHooksNode(pRoot->pLeft, p, ppNext); } else { pRoot->nRightCount++; if (!pRoot->pRight) { ppNext->p = p; ppNext->Name = p->Name; pRoot->pRight = ppNext++; return; } AddHooksNode(pRoot->pRight, p, ppNext); } } #endif #if 0 void BuildTree(HookItemNode*& pRoot, HookItem** pSorted, size_t nCount, HookItemNode*& ppNext) { size_t n = nCount>>1; // Init root pRoot = ppNext++; pRoot->p = pSorted[n]; pRoot->Name = pSorted[n]->Name; if (n > 0) { BuildTree(pRoot->pLeft, pSorted, n, ppNext); #ifdef _DEBUG _ASSERTEX(pRoot->pLeft!=NULL); pRoot->nLeftCount = 1 + pRoot->pLeft->nLeftCount + pRoot->pLeft->nRightCount; #endif } if ((n + 1) < nCount) { BuildTree(pRoot->pRight, pSorted+n+1, nCount-n-1, ppNext); #ifdef _DEBUG _ASSERTEX(pRoot->pRight!=NULL); pRoot->nRightCount = 1 + pRoot->pRight->nLeftCount + pRoot->pRight->nRightCount; #endif } } #endif //void BuildTreePtr(HookItemNodePtr*& pRoot, HookItem** pSorted, size_t nCount, HookItemNodePtr*& ppNext) //{ // size_t n = nCount>>1; // // // Init root // pRoot = ppNext++; // pRoot->p = pSorted[n]; // pRoot->Address = pSorted[n]->OldAddress; // // if (n > 0) // { // BuildTreePtr(pRoot->pLeft, pSorted, n, ppNext); // #ifdef _DEBUG // _ASSERTEX(pRoot->pLeft!=NULL); // pRoot->nLeftCount = 1 + pRoot->pLeft->nLeftCount + pRoot->pLeft->nRightCount; // #endif // } // else // { // pRoot->pLeft = NULL; // #ifdef _DEBUG // pRoot->nLeftCount = 0; // #endif // } // // if ((n + 1) < nCount) // { // BuildTreePtr(pRoot->pRight, pSorted+n+1, nCount-n-1, ppNext); // #ifdef _DEBUG // _ASSERTEX(pRoot->pRight!=NULL); // pRoot->nRightCount = 1 + pRoot->pRight->nLeftCount + pRoot->pRight->nRightCount; // #endif // } // else // { // pRoot->pRight = NULL; // #ifdef _DEBUG // pRoot->nRightCount = 0; // #endif // } //} //void BuildTreeNew(HookItemNodePtr*& pRoot, HookItem** pSorted, size_t nCount, HookItemNodePtr*& ppNext) //{ // size_t n = nCount>>1; // // // Init root // pRoot = ppNext++; // pRoot->p = pSorted[n]; // pRoot->Address = pSorted[n]->NewAddress; // // if (n > 0) // { // BuildTreeNew(pRoot->pLeft, pSorted, n, ppNext); // #ifdef _DEBUG // _ASSERTEX(pRoot->pLeft!=NULL); // pRoot->nLeftCount = 1 + pRoot->pLeft->nLeftCount + pRoot->pLeft->nRightCount; // #endif // } // else // { // pRoot->pLeft = NULL; // #ifdef _DEBUG // pRoot->nLeftCount = 0; // #endif // } // // if ((n + 1) < nCount) // { // BuildTreeNew(pRoot->pRight, pSorted+n+1, nCount-n-1, ppNext); // #ifdef _DEBUG // _ASSERTEX(pRoot->pRight!=NULL); // pRoot->nRightCount = 1 + pRoot->pRight->nLeftCount + pRoot->pRight->nRightCount; // #endif // } // else // { // pRoot->pRight = NULL; // #ifdef _DEBUG // pRoot->nRightCount = 0; // #endif // } //} #if 0 HookItemNode* FindFunctionNode(HookItemNode* pRoot, const char* pszFuncName) { if (!pRoot) return NULL; int nCmp = strcmp(pszFuncName, pRoot->Name); if (!nCmp) return pRoot; // BinTree is sorted HookItemNode* pc; if (nCmp < 0) { pc = FindFunctionNode(pRoot->pLeft, pszFuncName); //#ifdef _DEBUG //if (!pc) // _ASSERTEX(FindFunctionNode(pRoot->pRight, pszFuncName)==NULL); //#endif } else { pc = FindFunctionNode(pRoot->pRight, pszFuncName); //#ifdef _DEBUG //if (!pc) // _ASSERTEX(FindFunctionNode(pRoot->pLeft, pszFuncName)==NULL); //#endif } return pc; } #endif //HookItemNodePtr* FindFunctionNodePtr(HookItemNodePtr* pRoot, const void* ptrFunc) //{ // if (!pRoot) // return NULL; // // if (ptrFunc == pRoot->Address) // return pRoot; // // // BinTree is sorted // // HookItemNodePtr* pc; // if (ptrFunc < pRoot->Address) // { // pc = FindFunctionNodePtr(pRoot->pLeft, ptrFunc); // #ifdef _DEBUG // if (!pc) // _ASSERTEX(FindFunctionNodePtr(pRoot->pRight, ptrFunc)==NULL); // #endif // } // else // { // pc = FindFunctionNodePtr(pRoot->pRight, ptrFunc); // #ifdef _DEBUG // if (!pc) // _ASSERTEX(FindFunctionNodePtr(pRoot->pLeft, ptrFunc)==NULL); // #endif // } // // return pc; //} HookItem* FindFunction(const char* pszFuncName) { DWORD NameCRC = CalculateNameCRC32(pszFuncName); for (HookItem* p = gpHooks; p->NewAddress; ++p) { if (p->NameCRC == NameCRC) { if (strcmp(p->Name, pszFuncName) == 0) return p; } } //HookItemNode* pc = FindFunctionNode(gpHooksRoot, pszFuncName); //if (pc) // return pc->p; return NULL; } //HookItem* FindFunctionPtr(HookItemNodePtr *pRoot, const void* ptrFunction) //{ // HookItemNodePtr* pc = FindFunctionNodePtr(pRoot, ptrFunction); // if (pc) // return pc->p; // return NULL; //} //// Unfortunately, tree must be rebuilded when new modules are loaded //// (e.g. "shell32.dll", when it is not statically linked to exe) //void InitHooksSortAddress() //{ // if (!gpHooks) // { // _ASSERTEX(gpHooks!=NULL); // return; // } // _ASSERTEX(gpHooks && gpHooks->Name); // // HLOG0("InitHooksSortAddress",gnHookedFuncs); // // // *** !!! *** // Enter Critical Section(gpcsHooksRootPtr); // // // Sorted by address vector // HookItem** pSort = (HookItem**)malloc(gnHookedFuncs*sizeof(*pSort)); // if (!pSort) // { // Leave Critical Section(gpcsHooksRootPtr); // _ASSERTEX(pSort!=NULL && "Memory allocation failed"); // return; // } // size_t iMax = 0; // for (size_t i = 0; i < gnHookedFuncs; i++) // { // if (gpHooks[i].OldAddress) // pSort[iMax++] = (gpHooks+i); // } // if (iMax) iMax--; // // Go sorting // for (size_t i = 0; i < iMax; i++) // { // size_t m = i; // const void* ptrM = pSort[i]->OldAddress; // for (size_t j = i+1; j <= iMax; j++) // { // _ASSERTEX(pSort[j]->OldAddress != ptrM && pSort[j]->OldAddress); // if (pSort[j]->OldAddress < ptrM) // { // m = j; ptrM = pSort[j]->OldAddress; // } // } // if (m != i) // { // HookItem* p = pSort[i]; // pSort[i] = pSort[m]; // pSort[m] = p; // } // } // // if (!gpHooksTreePtr) // { // gpHooksTreePtr = (HookItemNodePtr*)calloc(gnHookedFuncs,sizeof(HookItemNodePtr)); // if (!gpHooksTreePtr) // { // Leave Critical Section(gpcsHooksRootPtr); // return; // } // } // // // Go to building // HookItemNodePtr *ppNext = gpHooksTreePtr; // BuildTreePtr(gpHooksRootPtr, pSort, iMax, ppNext); // // free(pSort); // //#ifdef _DEBUG // // Validate tree // _ASSERTEX(gpHooksRoot->nLeftCount>0 && gpHooksRoot->nRightCount>0); // _ASSERTEX((gpHooksRoot->nLeftCount<gpHooksRoot->nRightCount) ? ((gpHooksRoot->nRightCount-gpHooksRoot->nLeftCount)<=2) : ((gpHooksRoot->nLeftCount-gpHooksRoot->nRightCount)<=2)); // _ASSERTEX(FindFunction("Not Existed")==NULL); // for (size_t i = 0; i < gnHookedFuncs; i++) // { // HookItem* pFind = FindFunction(gpHooks[i].Name); // _ASSERTEX(pFind == (gpHooks+i)); // } //#endif // // HLOGEND(); // // Leave Critical Section(gpcsHooksRootPtr); //} // //void InitHooksSortNewAddress() //{ // if (!gpHooks) // { // _ASSERTEX(gpHooks!=NULL); // return; // } // _ASSERTEX(gpHooks && gpHooks->Name); // // HLOG0("InitHooksSortNewAddress",gnHookedFuncs); // // // // Sorted by address vector // HookItem** pSort = (HookItem**)malloc(gnHookedFuncs*sizeof(*pSort)); // if (!pSort) // { // _ASSERTEX(pSort!=NULL && "Memory allocation failed"); // return; // } // // for (size_t i = 0; i < gnHookedFuncs; i++) // { // pSort[i] = (gpHooks+i); // } // size_t iMax = gnHookedFuncs - 1; // // Go sorting // for (size_t i = 0; i < iMax; i++) // { // size_t m = i; // const void* ptrM = pSort[i]->NewAddress; // for (size_t j = i+1; j < gnHookedFuncs; j++) // { // _ASSERTEX(pSort[j]->NewAddress != ptrM && pSort[j]->NewAddress); // if (pSort[j]->NewAddress < ptrM) // { // m = j; ptrM = pSort[j]->NewAddress; // } // } // if (m != i) // { // HookItem* p = pSort[i]; // pSort[i] = pSort[m]; // pSort[m] = p; // } // } // // if (!gpHooksTreeNew) // { // gpHooksTreeNew = (HookItemNodePtr*)calloc(gnHookedFuncs,sizeof(HookItemNodePtr)); // if (!gpHooksTreeNew) // { // return; // } // } // // // Go to building // HookItemNodePtr *ppNext = gpHooksTreeNew; // BuildTreeNew(gpHooksRootNew, pSort, iMax, ppNext); // // free(pSort); // //#ifdef _DEBUG // // Validate tree // _ASSERTEX(gpHooksRoot->nLeftCount>0 && gpHooksRoot->nRightCount>0); // _ASSERTEX((gpHooksRoot->nLeftCount<gpHooksRoot->nRightCount) ? ((gpHooksRoot->nRightCount-gpHooksRoot->nLeftCount)<=2) : ((gpHooksRoot->nLeftCount-gpHooksRoot->nRightCount)<=2)); // _ASSERTEX(FindFunction("Not Existed")==NULL); // for (size_t i = 0; i < gnHookedFuncs; i++) // { // HookItem* pFind = FindFunction(gpHooks[i].Name); // _ASSERTEX(pFind == (gpHooks+i)); // } //#endif // // HLOGEND(); //} #if 0 void __stdcall InitHooksSort() { if (!gpHooks) { _ASSERTEX(gpHooks!=NULL); return; } if (gbHooksSorted) { _ASSERTEX(FALSE && "Hooks are already sorted"); return; } gbHooksSorted = true; _ASSERTEX(gpHooks && gpHooks->Name); HLOG0("InitHooksSort",gnHookedFuncs); #if 1 // Sorted by name vector HookItem** pSort = (HookItem**)malloc(gnHookedFuncs*sizeof(*pSort)); if (!pSort) { _ASSERTEX(pSort!=NULL && "Memory allocation failed"); return; } for (size_t i = 0; i < gnHookedFuncs; i++) { pSort[i] = (gpHooks+i); } // Go sorting size_t iMax = (gnHookedFuncs-1); for (size_t i = 0; i < iMax; i++) { size_t m = i; LPCSTR pszM = pSort[i]->Name; for (size_t j = i+1; j < gnHookedFuncs; j++) { int iCmp = strcmp(pSort[j]->Name, pszM); _ASSERTEX(iCmp!=0); if (iCmp < 0) { m = j; pszM = pSort[j]->Name; } } if (m != i) { HookItem* p = pSort[i]; pSort[i] = pSort[m]; pSort[m] = p; } } gpHooksTree = (HookItemNode*)calloc(gnHookedFuncs,sizeof(HookItemNode)); if (!gpHooksTree) return; // Go to building HookItemNode *ppNext = gpHooksTree; BuildTree(gpHooksRoot, pSort, gnHookedFuncs, ppNext); free(pSort); #else gpHooksTree = (HookItemNode*)calloc(MAX_HOOKED_PROCS,sizeof(HookItemNode)); // Init root gpHooksRoot = gpHooksTree; gpHooksRoot->p = gpHooks; gpHooksRoot->Name = gpHooks->Name; HookItemNode *ppNext = gpHooksTree+1; // Go to building for (size_t i = 1; i < MAX_HOOKED_PROCS; ++i) { if (!gpHooks[i].Name) break; AddHooksNode(gpHooksRoot, gpHooks+i, ppNext); } #endif #ifdef _DEBUG // Validate tree _ASSERTEX(gpHooksRoot->nLeftCount>0 && gpHooksRoot->nRightCount>0); _ASSERTEX((gpHooksRoot->nLeftCount<gpHooksRoot->nRightCount) ? ((gpHooksRoot->nRightCount-gpHooksRoot->nLeftCount)<=2) : ((gpHooksRoot->nLeftCount-gpHooksRoot->nRightCount)<=2)); _ASSERTEX(FindFunction("Not Existed")==NULL); for (size_t i = 0; i < gnHookedFuncs; i++) { HookItem* pFind = FindFunction(gpHooks[i].Name); _ASSERTEX(pFind == (gpHooks+i)); } #endif HLOGEND(); //// Tree with our NewAddress //InitHooksSortNewAddress(); //// First call to address tree. But it may be rebuilded... //InitHooksSortAddress(); } #endif void ShutdownHooks() { HLOG1("ShutdownHooks.UnsetAllHooks",0); UnsetAllHooks(); HLOGEND1(); //// Завершить работу с реестром //DoneHooksReg(); // Уменьшение счетчиков загрузок (а надо ли?) HLOG1_("ShutdownHooks.FreeLibrary",1); for (size_t s = 0; s < countof(ghSysDll); s++) { if (ghSysDll[s] && *ghSysDll[s]) { FreeLibrary(*ghSysDll[s]); *ghSysDll[s] = NULL; } } HLOGEND1(); if (gpHookCS) { MSection *p = gpHookCS; gpHookCS = NULL; delete p; } //if (gpcsHooksRootPtr) //{ // Delete Critical Section(gpcsHooksRootPtr); // SafeFree(gpcsHooksRootPtr); //} FinalizeHookedModules(); } void __stdcall SetLoadLibraryCallback(HMODULE ahCallbackModule, OnLibraryLoaded_t afOnLibraryLoaded, OnLibraryLoaded_t afOnLibraryUnLoaded) { ghOnLoadLibModule = ahCallbackModule; gfOnLibraryLoaded = afOnLibraryLoaded; gfOnLibraryUnLoaded = afOnLibraryUnLoaded; } bool __stdcall SetHookCallbacks(const char* ProcName, const wchar_t* DllName, HMODULE hCallbackModule, HookItemPreCallback_t PreCallBack, HookItemPostCallback_t PostCallBack, HookItemExceptCallback_t ExceptCallBack) { if (!ProcName|| !DllName) { _ASSERTE(ProcName!=NULL && DllName!=NULL); return false; } _ASSERTE(ProcName[0]!=0 && DllName[0]!=0); bool bFound = false; if (gpHooks) { for (int i = 0; i<MAX_HOOKED_PROCS && gpHooks[i].NewAddress; i++) { if (!strcmp(gpHooks[i].Name, ProcName) && !lstrcmpW(gpHooks[i].DllName,DllName)) { gpHooks[i].hCallbackModule = hCallbackModule; gpHooks[i].PreCallBack = PreCallBack; gpHooks[i].PostCallBack = PostCallBack; gpHooks[i].ExceptCallBack = ExceptCallBack; bFound = true; //break; // перехватов может быть более одного (деление хуков на exe/dll) } } } return bFound; } bool FindModuleFileName(HMODULE ahModule, LPWSTR pszName, size_t cchNameMax) { bool lbFound = false; if (pszName && cchNameMax) { //*pszName = 0; #ifdef _WIN64 msprintf(pszName, cchNameMax, L"<HMODULE=0x%08X%08X> ", (DWORD)((((u64)ahModule) & 0xFFFFFFFF00000000) >> 32), //-V112 (DWORD)(((u64)ahModule) & 0xFFFFFFFF)); //-V112 #else msprintf(pszName, cchNameMax, L"<HMODULE=0x%08X> ", (DWORD)ahModule); #endif INT_PTR nLen = lstrlen(pszName); pszName += nLen; cchNameMax -= nLen; _ASSERTE(cchNameMax>0); } //TH32CS_SNAPMODULE - может зависать при вызовах из LoadLibrary/FreeLibrary. lbFound = (IsHookedModule(ahModule, pszName, cchNameMax) != NULL); return lbFound; } bool IsModuleExcluded(HMODULE module, LPCSTR asModuleA, LPCWSTR asModuleW) { if (module == ghOurModule) return true; BOOL lbResource = LDR_IS_RESOURCE(module); if (lbResource) return true; // игнорировать системные библиотеки вида // API-MS-Win-Core-Util-L1-1-0.dll if (asModuleA) { char szTest[12]; lstrcpynA(szTest, asModuleA, 12); if (lstrcmpiA(szTest, "API-MS-Win-") == 0) return true; } else if (asModuleW) { wchar_t szTest[12]; lstrcpynW(szTest, asModuleW, 12); if (lstrcmpiW(szTest, L"API-MS-Win-") == 0) return true; } #if 1 for (int i = 0; ExcludedModules[i]; i++) if (module == GetModuleHandle(ExcludedModules[i])) return true; #else wchar_t szModule[MAX_PATH*2]; szModule[0] = 0; DWORD nLen = GetModuleFileNameW(module, szModule, countof(szModule)); if ((nLen == 0) || (nLen >= countof(szModule))) { //_ASSERTE(nLen>0 && nLen<countof(szModule)); return true; // Что-то с модулем не то... } LPCWSTR pszName = wcsrchr(szModule, L'\\'); if (pszName) pszName++; else pszName = szModule; for (int i = 0; ExcludedModules[i]; i++) { if (lstrcmpi(ExcludedModules[i], pszName) == 0) return true; // указан в исключениях } #endif return false; } #define GetPtrFromRVA(rva,pNTHeader,imageBase) (PVOID)((imageBase)+(rva)) extern BOOL gbInCommonShutdown; bool LockHooks(HMODULE Module, LPCWSTR asAction, MSectionLock* apCS) { #ifdef _DEBUG DWORD nCurTID = GetCurrentThreadId(); #endif //while (nHookMutexWait != WAIT_OBJECT_0) BOOL lbLockHooksSection = FALSE; while (!(lbLockHooksSection = apCS->Lock(gpHookCS, TRUE, 10000))) { #ifdef _DEBUG if (!IsDebuggerPresent()) { _ASSERTE(lbLockHooksSection); } #endif if (gbInCommonShutdown) return false; wchar_t* szTrapMsg = (wchar_t*)calloc(1024,2); wchar_t* szName = (wchar_t*)calloc((MAX_PATH+1),2); if (!FindModuleFileName(Module, szName, MAX_PATH+1)) szName[0] = 0; DWORD nTID = GetCurrentThreadId(); DWORD nPID = GetCurrentProcessId(); msprintf(szTrapMsg, 1024, L"Can't %s hooks in module '%s'\nCurrent PID=%u, TID=%i\nCan't lock hook section\nPress 'Retry' to repeat locking", asAction, szName, nPID, nTID); int nBtn = #ifdef CONEMU_MINIMAL GuiMessageBox #else MessageBoxW #endif (GetConEmuHWND(TRUE), szTrapMsg, L"ConEmu", MB_RETRYCANCEL|MB_ICONSTOP|MB_SYSTEMMODAL); free(szTrapMsg); free(szName); if (nBtn != IDRETRY) return false; //nHookMutexWait = WaitForSingleObject(ghHookMutex, 10000); //continue; } #ifdef _DEBUG wchar_t szDbg[80]; msprintf(szDbg, countof(szDbg), L"ConEmuHk: LockHooks, TID=%u\n", nCurTID); if (nCurTID != gnHookMainThreadId) { int nDbg = 0; } DebugString(szDbg); #endif return true; } bool SetExportsSEH(HMODULE Module) { bool lbRc = false; DWORD ExportDir = 0; IMAGE_DOS_HEADER* dos_header = (IMAGE_DOS_HEADER*)Module; IMAGE_NT_HEADERS* nt_header = 0; if (dos_header->e_magic == IMAGE_DOS_SIGNATURE /*'ZM'*/) { nt_header = (IMAGE_NT_HEADERS*)((char*)Module + dos_header->e_lfanew); if (nt_header->Signature == 0x004550) { ExportDir = (DWORD)(nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress); } } if (ExportDir != 0) { IMAGE_SECTION_HEADER* section = (IMAGE_SECTION_HEADER*)IMAGE_FIRST_SECTION(nt_header); for (WORD s = 0; s < nt_header->FileHeader.NumberOfSections; s++) { if (!((section[s].VirtualAddress == ExportDir) || ((section[s].VirtualAddress < ExportDir) && ((section[s].Misc.VirtualSize + section[s].VirtualAddress) > ExportDir)))) { // Эта секция не содержит ExportDir continue; } //int nDiff = 0;//section[s].VirtualAddress - section[s].PointerToRawData; IMAGE_EXPORT_DIRECTORY* Export = (IMAGE_EXPORT_DIRECTORY*)((char*)Module + (ExportDir/*-nDiff*/)); if (!Export->AddressOfNames || !Export->AddressOfNameOrdinals || !Export->AddressOfFunctions) { _ASSERTEX(Export->AddressOfNames && Export->AddressOfNameOrdinals && Export->AddressOfFunctions); continue; } DWORD* Name = (DWORD*)(((BYTE*)Module) + Export->AddressOfNames); WORD* Ordn = (WORD*)(((BYTE*)Module) + Export->AddressOfNameOrdinals); DWORD* Shift = (DWORD*)(((BYTE*)Module) + Export->AddressOfFunctions); DWORD nCount = Export->NumberOfNames; // Export->NumberOfFunctions; DWORD old_protect = 0xCDCDCDCD; if (VirtualProtect(Shift, nCount * sizeof( DWORD ), PAGE_READWRITE, &old_protect )) { for (DWORD i = 0; i < nCount; i++) { char* pszExpName = ((char*)Module) + Name[i]; DWORD nFnOrdn = Ordn[i]; if (nFnOrdn > Export->NumberOfFunctions) { _ASSERTEX(nFnOrdn <= Export->NumberOfFunctions); continue; } void* ptrOldAddr = ((BYTE*)Module) + Shift[nFnOrdn]; for (DWORD j = 0; j <= countof(gKernelFuncs); j++) { if ((Module == gKernelFuncs[j].hLib) && gKernelFuncs[j].NewAddress && !strcmp(gKernelFuncs[j].Name, pszExpName)) { gKernelFuncs[j].OldAddress = (FARPROC)ptrOldAddr; INT_PTR NewShift = ((BYTE*)gKernelFuncs[j].NewAddress) - ((BYTE*)Module); #ifdef _WIN64 if (NewShift <= 0 || NewShift > (DWORD)-1) { _ASSERTEX((NewShift > 0) && (NewShift < (DWORD)-1)); break; } #endif Shift[nFnOrdn] = (DWORD)NewShift; lbRc = true; break; } } } VirtualProtect( Shift, nCount * sizeof( DWORD ), old_protect, &old_protect ); } } } return lbRc; } bool SetExports(HMODULE Module) { _ASSERTEX((Module == ghKernel32 || Module == ghKernelBase) && Module); #ifdef _DEBUG if (Module == ghKernel32) { static bool KernelHooked = false; if (KernelHooked) { _ASSERTEX(KernelHooked==false); return false; } KernelHooked = true; } else if (Module == ghKernelBase) { static bool KernelBaseHooked = false; if (KernelBaseHooked) { _ASSERTEX(KernelBaseHooked==false); return false; } KernelBaseHooked = true; } #endif bool lbValid = IsModuleValid(Module); if ((Module == ghOurModule) || !lbValid) { _ASSERTEX(Module != ghOurModule); _ASSERTEX(IsModuleValid(Module)); return false; } //InitKernelFuncs(); -- уже должно быть выполнено! _ASSERTEX(gKernelFuncs[0].NewAddress!=NULL); // переопределяем только первые 6 экспортов, и через gKernelFuncs //_ASSERTEX(gpHooks[0].Name == szGetProcAddress && gpHooks[5].Name == szFreeLibrary); //_ASSERTEX(gpHooks[1].Name == szLoadLibraryA && gpHooks[2].Name == szLoadLibraryW); //_ASSERTEX(gpHooks[3].Name == szLoadLibraryExA && gpHooks[4].Name == szLoadLibraryExW); #ifdef _WIN64 if (((DWORD_PTR)Module) >= ((DWORD_PTR)ghOurModule)) { //_ASSERTEX(((DWORD_PTR)Module) < ((DWORD_PTR)ghOurModule)) wchar_t* pszMsg = (wchar_t*)malloc(MAX_PATH*3*sizeof(wchar_t)); if (pszMsg) { wchar_t szTitle[64]; OSVERSIONINFO osv = {sizeof(osv)}; GetOsVersionInformational(&osv); msprintf(szTitle, countof(szTitle), L"ConEmuHk64, PID=%u, TID=%u", GetCurrentProcessId(), GetCurrentThreadId()); msprintf(pszMsg, 250, L"ConEmuHk64.dll was loaded below Kernel32.dll\n" L"Some important features may be not available!\n" L"Please, report to developer!\n\n" L"OS version: %u.%u.%u (%s)\n" L"<ConEmuHk64.dll=0x%08X%08X>\n" L"<%s=0x%08X%08X>\n", osv.dwMajorVersion, osv.dwMinorVersion, osv.dwBuildNumber, osv.szCSDVersion, WIN3264WSPRINT(ghOurModule), (Module==ghKernelBase) ? kernelbase : kernel32, WIN3264WSPRINT(Module) ); GetModuleFileName(ghOurModule, pszMsg+lstrlen(pszMsg), MAX_PATH); lstrcat(pszMsg, L"\n"); GetModuleFileName(Module, pszMsg+lstrlen(pszMsg), MAX_PATH); GuiMessageBox(NULL, pszMsg, szTitle, MB_OK|MB_ICONSTOP|MB_SYSTEMMODAL); free(pszMsg); } return false; } #endif bool lbRc = false; SAFETRY { // В отдельной функции, а то компилятор глюкавит (под отладчиком во всяком случае куда-то не туда прыгает) lbRc = SetExportsSEH(Module); } SAFECATCH { lbRc = false; } return lbRc; } bool SetHookPrep(LPCWSTR asModule, HMODULE Module, IMAGE_NT_HEADERS* nt_header, BOOL abForceHooks, bool bExecutable, IMAGE_IMPORT_DESCRIPTOR* Import, size_t ImportCount, bool (&bFnNeedHook)[MAX_HOOKED_PROCS], HkModuleInfo* p); bool SetHookChange(LPCWSTR asModule, HMODULE Module, BOOL abForceHooks, bool (&bFnNeedHook)[MAX_HOOKED_PROCS], HkModuleInfo* p); // Подменить Импортируемые функции в модуле (Module) // если (abForceHooks == FALSE) то хуки не ставятся, если // будет обнаружен импорт, не совпадающий с оригиналом // Это для того, чтобы не выполнять множественные хуки при множественных LoadLibrary bool SetHook(LPCWSTR asModule, HMODULE Module, BOOL abForceHooks) { IMAGE_IMPORT_DESCRIPTOR* Import = NULL; DWORD Size = 0; HMODULE hExecutable = GetModuleHandle(0); if (!gpHooks) return false; if (!Module) Module = hExecutable; // Если он уже хукнут - не проверять больше ничего HkModuleInfo* p = IsHookedModule(Module); if (p) return true; if (!IsModuleValid(Module)) return false; bool bExecutable = (Module == hExecutable); IMAGE_DOS_HEADER* dos_header = (IMAGE_DOS_HEADER*)Module; IMAGE_NT_HEADERS* nt_header = NULL; HLOG0("SetHook.Init",(DWORD)Module); // Валидность адреса размером sizeof(IMAGE_DOS_HEADER) проверяется в IsModuleValid. if (dos_header->e_magic == IMAGE_DOS_SIGNATURE /*'ZM'*/) { nt_header = (IMAGE_NT_HEADERS*)((char*)Module + dos_header->e_lfanew); if (IsBadReadPtr(nt_header, sizeof(IMAGE_NT_HEADERS))) return false; if (nt_header->Signature != 0x004550) return false; else { Import = (IMAGE_IMPORT_DESCRIPTOR*)((char*)Module + (DWORD)(nt_header->OptionalHeader. DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]. VirtualAddress)); Size = nt_header->OptionalHeader. DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size; } HLOGEND(); } else return false; // if wrong module or no import table if (!Import) return false; #ifdef _DEBUG PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(nt_header); //-V220 #endif #ifdef _WIN64 _ASSERTE(sizeof(DWORD_PTR)==8); #else _ASSERTE(sizeof(DWORD_PTR)==4); #endif #ifdef _WIN64 #define TOP_SHIFT 60 #else #define TOP_SHIFT 28 #endif //DWORD nHookMutexWait = WaitForSingleObject(ghHookMutex, 10000); HLOG("SetHook.Lock",(DWORD)Module); MSectionLock CS; if (!gpHookCS->isLockedExclusive() && !LockHooks(Module, L"install", &CS)) return false; HLOGEND(); if (!p) { HLOG("SetHook.Add",(DWORD)Module); p = AddHookedModule(Module, asModule); HLOGEND(); if (!p) return false; } HLOG("SetHook.Prepare",(DWORD)Module); TODO("!!! Сохранять ORDINAL процедур !!!"); bool res = false, bHooked = false; //INT_PTR i; INT_PTR nCount = Size / sizeof(IMAGE_IMPORT_DESCRIPTOR); bool bFnNeedHook[MAX_HOOKED_PROCS] = {}; // в отдельной функции, т.к. __try res = SetHookPrep(asModule, Module, nt_header, abForceHooks, bExecutable, Import, nCount, bFnNeedHook, p); HLOGEND(); HLOG("SetHook.Change",(DWORD)Module); // в отдельной функции, т.к. __try bHooked = SetHookChange(asModule, Module, abForceHooks, bFnNeedHook, p); HLOGEND(); #ifdef _DEBUG if (bHooked) { HLOG("SetHook.FindModuleFileName",(DWORD)Module); wchar_t* szDbg = (wchar_t*)calloc(MAX_PATH*3, 2); wchar_t* szModPath = (wchar_t*)calloc(MAX_PATH*2, 2); FindModuleFileName(Module, szModPath, MAX_PATH*2); _wcscpy_c(szDbg, MAX_PATH*3, L" ## Hooks was set by conemu: "); _wcscat_c(szDbg, MAX_PATH*3, szModPath); _wcscat_c(szDbg, MAX_PATH*3, L"\n"); DebugString(szDbg); free(szDbg); free(szModPath); HLOGEND(); } #endif HLOG("SetHook.Unlock",(DWORD)Module); //ReleaseMutex(ghHookMutex); CS.Unlock(); HLOGEND(); // Плагин ConEmu может выполнить дополнительные действия if (gfOnLibraryLoaded) { HLOG("SetHook.gfOnLibraryLoaded",(DWORD)Module); gfOnLibraryLoaded(Module); HLOGEND(); } return res; } bool isBadModulePtr(const void *lp, UINT_PTR ucb, HMODULE Module, const IMAGE_NT_HEADERS* nt_header) { bool bTestValid = (((LPBYTE)lp) >= ((LPBYTE)Module)) && ((((LPBYTE)lp) + ucb) <= (((LPBYTE)Module) + nt_header->OptionalHeader.SizeOfImage)); #ifdef USE_ONLY_INT_CHECK_PTR bool bApiValid = bTestValid; #else bool bApiValid = !IsBadReadPtr(lp, ucb); #ifdef _DEBUG static bool bFirstAssert = false; if (bTestValid != bApiValid) { if (!bFirstAssert) { bFirstAssert = true; _ASSERTE(bTestValid != bApiValid); } } #endif #endif return !bApiValid; } bool isBadModuleStringA(LPCSTR lpsz, UINT_PTR ucchMax, HMODULE Module, IMAGE_NT_HEADERS* nt_header) { bool bTestStrValid = (((LPBYTE)lpsz) >= ((LPBYTE)Module)) && ((((LPBYTE)lpsz) + ucchMax) <= (((LPBYTE)Module) + nt_header->OptionalHeader.SizeOfImage)); #ifdef USE_ONLY_INT_CHECK_PTR bool bApiStrValid = bTestStrValid; #else bool bApiStrValid = !IsBadStringPtrA(lpsz, ucchMax); #ifdef _DEBUG static bool bFirstAssert = false; if (bTestStrValid != bApiStrValid) { if (!bFirstAssert) { bFirstAssert = true; _ASSERTE(bTestStrValid != bApiStrValid); } } #endif #endif return !bApiStrValid; } bool SetHookPrep(LPCWSTR asModule, HMODULE Module, IMAGE_NT_HEADERS* nt_header, BOOL abForceHooks, bool bExecutable, IMAGE_IMPORT_DESCRIPTOR* Import, size_t ImportCount, bool (&bFnNeedHook)[MAX_HOOKED_PROCS], HkModuleInfo* p) { bool res = false; size_t i; //api-ms-win-core-libraryloader-l1-1-1.dll //api-ms-win-core-console-l1-1-0.dll //... char szCore[18]; const char szCorePrefix[] = "api-ms-win-core-"; // MUST BE LOWER CASE! const int nCorePrefLen = lstrlenA(szCorePrefix); _ASSERTE((nCorePrefLen+1)<countof(szCore)); bool lbIsCoreModule = false; char mod_name[MAX_PATH]; //_ASSERTEX(lstrcmpi(asModule, L"dsound.dll")); SAFETRY { HLOG0("SetHookPrep.Begin",ImportCount); //if (!gpHooksRootPtr) //{ // InitHooksSortAddress(); //} //_ASSERTE(Size == (nCount * sizeof(IMAGE_IMPORT_DESCRIPTOR))); -- ровно быть не обязано for (i = 0; i < ImportCount; i++) { if (Import[i].Name == 0) break; HLOG0("SetHookPrep.Import",i); HLOG1("SetHookPrep.CheckModuleName",i); //DebugString( ToTchar( (char*)Module + Import[i].Name ) ); char* mod_name_ptr = (char*)Module + Import[i].Name; DWORD_PTR rvaINT = Import[i].OriginalFirstThunk; DWORD_PTR rvaIAT = Import[i].FirstThunk; //-V101 lstrcpynA(mod_name, mod_name_ptr, countof(mod_name)); CharLowerBuffA(mod_name, lstrlenA(mod_name)); // MUST BE LOWER CASE! lstrcpynA(szCore, mod_name, nCorePrefLen+1); lbIsCoreModule = (strcmp(szCore, szCorePrefix) == 0); bool bHookExists = false; for (size_t j = 0; gpHooks[j].Name; j++) { if ((strcmp(mod_name, gpHooks[j].DllNameA) != 0) && !(lbIsCoreModule && (gpHooks[j].DllName == kernel32))) // Имя модуля не соответствует continue; bHookExists = true; break; } // Этот модуль вообще не хукается if (!bHookExists) { HLOGEND1(); HLOGEND(); continue; } if (rvaINT == 0) // No Characteristics field? { // Yes! Gotta have a non-zero FirstThunk field then. rvaINT = rvaIAT; if (rvaINT == 0) // No FirstThunk field? Ooops!!! { _ASSERTE(rvaINT!=0); HLOGEND1(); HLOGEND(); break; } } //PIMAGE_IMPORT_BY_NAME pOrdinalName = NULL, pOrdinalNameO = NULL; PIMAGE_IMPORT_BY_NAME pOrdinalNameO = NULL; //IMAGE_IMPORT_BY_NAME** byname = (IMAGE_IMPORT_BY_NAME**)((char*)Module + rvaINT); //IMAGE_THUNK_DATA* thunk = (IMAGE_THUNK_DATA*)((char*)Module + rvaIAT); IMAGE_THUNK_DATA* thunk = (IMAGE_THUNK_DATA*)GetPtrFromRVA(rvaIAT, nt_header, (PBYTE)Module); IMAGE_THUNK_DATA* thunkO = (IMAGE_THUNK_DATA*)GetPtrFromRVA(rvaINT, nt_header, (PBYTE)Module); if (!thunk || !thunkO) { _ASSERTE(thunk && thunkO); HLOGEND1(); HLOGEND(); continue; } HLOGEND1(); // ***** >>>>>> go HLOG1_("SetHookPrep.ImportThunksSteps",i); size_t f, s; for (s = 0; s <= 1; s++) { if (s) { thunk = (IMAGE_THUNK_DATA*)GetPtrFromRVA(rvaIAT, nt_header, (PBYTE)Module); thunkO = (IMAGE_THUNK_DATA*)GetPtrFromRVA(rvaINT, nt_header, (PBYTE)Module); } for (f = 0;; thunk++, thunkO++, f++) { //111127 - ..\GIT\lib\perl5\site_perl\5.8.8\msys\auto\SVN\_Core\_Core.dll // похоже, в этой длл кривая таблица импортов #ifndef USE_SEH HLOG("SetHookPrep.lbBadThunk",f); bool lbBadThunk = isBadModulePtr(thunk, sizeof(*thunk), Module, nt_header); if (lbBadThunk) { _ASSERTEX(!lbBadThunk); break; } #endif if (!thunk->u1.Function) break; #ifndef USE_SEH HLOG("SetHookPrep.lbBadThunkO",f); bool lbBadThunkO = isBadModulePtr(thunkO, sizeof(*thunkO), Module, nt_header); if (lbBadThunkO) { _ASSERTEX(!lbBadThunkO); break; } #endif const char* pszFuncName = NULL; //ULONGLONG ordinalO = -1; // Получили адрес функции, и (на втором шаге) имя функции // Теперь нужно подобрать (если есть) адрес перехвата HookItem* ph = gpHooks; INT_PTR jj = -1; if (!s) { HLOG1("SetHookPrep.ImportThunks0",s); //HLOG2("SetHookPrep.FuncTreeNew",f); //ph = FindFunctionPtr(gpHooksRootNew, (void*)thunk->u1.Function); //HLOGEND2(); //if (ph) //{ // // Already hooked, this is our function address // HLOGEND1(); // continue; //} //HLOG2_("SetHookPrep.FuncTreeOld",f); //ph = FindFunctionPtr(gpHooksRootPtr, (void*)thunk->u1.Function); //HLOGEND2(); //if (!ph) //{ // // This address (Old) does not exists in our tables // HLOGEND1(); // continue; //} //jj = (ph - gpHooks); for (size_t j = 0; ph->Name; ++j, ++ph) { _ASSERTEX(j<gnHookedFuncs && gnHookedFuncs<=MAX_HOOKED_PROCS); // Если не удалось определить оригинальный адрес процедуры (kernel32/WriteConsoleOutputW, и т.п.) if (ph->OldAddress == NULL) { continue; } // Если адрес импорта в модуле уже совпадает с адресом одной из наших функций if (ph->NewAddress == (void*)thunk->u1.Function) { res = true; // это уже захучено break; } #ifdef _DEBUG //const void* ptrNewAddress = ph->NewAddress; //const void* ptrOldAddress = (void*)thunk->u1.Function; #endif // Проверяем адрес перехватываемой функции if ((void*)thunk->u1.Function == ph->OldAddress) { jj = j; break; // OK, Hook it! } } // for (size_t j = 0; ph->Name; ++j, ++ph), (s==0) HLOGEND1(); } else { HLOG1("SetHookPrep.ImportThunks1",s); if (!abForceHooks) { //_ASSERTEX(abForceHooks); //HLOGEND1(); HLOG2("!!!Function skipped of (!abForceHooks)",f); continue; // запрещен перехват, если текущий адрес в модуле НЕ совпадает с оригинальным экспортом! } // искать имя функции if ((thunk->u1.Function != thunkO->u1.Function) && !IMAGE_SNAP_BY_ORDINAL(thunkO->u1.Ordinal)) { pOrdinalNameO = (PIMAGE_IMPORT_BY_NAME)GetPtrFromRVA(thunkO->u1.AddressOfData, nt_header, (PBYTE)Module); #ifdef USE_SEH pszFuncName = (LPCSTR)pOrdinalNameO->Name; #else HLOG("SetHookPrep.pOrdinalNameO",f); //WARNING!!! Множественные вызовы IsBad???Ptr могут глючить и тормозить bool lbValidPtr = !isBadModulePtr(pOrdinalNameO, sizeof(IMAGE_IMPORT_BY_NAME), Module, nt_header); _ASSERTE(lbValidPtr); if (lbValidPtr) { lbValidPtr = !isBadModuleStringA((LPCSTR)pOrdinalNameO->Name, 10, Module, nt_header); _ASSERTE(lbValidPtr); if (lbValidPtr) pszFuncName = (LPCSTR)pOrdinalNameO->Name; } #endif } if (!pszFuncName || !*pszFuncName) { continue; // This import does not have "Function name" } HLOG2("SetHookPrep.FindFunction",f); ph = FindFunction(pszFuncName); HLOGEND2(); if (!ph) { HLOGEND1(); continue; } // Имя модуля HLOG2_("SetHookPrep.Module",f); if ((strcmp(mod_name, ph->DllNameA) != 0) && !(lbIsCoreModule && (ph->DllName == kernel32))) { HLOGEND2(); HLOGEND1(); // Имя модуля не соответствует continue; // И дубли имен функций не допускаются. Пропускаем } HLOGEND2(); jj = (ph - gpHooks); HLOGEND1(); } if (jj >= 0) { HLOG1("SetHookPrep.WorkExport",f); if (bExecutable && !ph->ExeOldAddress) { // OldAddress уже может отличаться от оригинального экспорта библиотеки //// Это происходит например с PeekConsoleIntputW при наличии плагина Anamorphosis // Про Anamorphosis несколько устарело. При включенном "Inject ConEmuHk" // хуки ставятся сразу при запуске процесса. // Но, теоретически, кто-то может успеть раньше, или флажок "Inject" выключен. // Также это может быть в новой архитектуре Win7 ("api-ms-win-core-..." и др.) ph->ExeOldAddress = (void*)thunk->u1.Function; } // When we get here - jj matches pszFuncName or FuncPtr if (p->Addresses[jj].ppAdr != NULL) { HLOGEND1(); continue; // уже обработали, следующий импорт } //#ifdef _DEBUG //// Это НЕ ORDINAL, это Hint!!! //if (ph->nOrdinal == 0 && ordinalO != (ULONGLONG)-1) // ph->nOrdinal = (DWORD)ordinalO; //#endif _ASSERTE(sizeof(thunk->u1.Function)==sizeof(DWORD_PTR)); if (thunk->u1.Function == (DWORD_PTR)ph->NewAddress) { // оказалось захучено в другой нити? такого быть не должно, блокируется секцией // Но может быть захучено в прошлый раз, если не все модули были загружены при старте _ASSERTE(thunk->u1.Function != (DWORD_PTR)ph->NewAddress); } else { bFnNeedHook[jj] = true; p->Addresses[jj].ppAdr = &thunk->u1.Function; #ifdef _DEBUG p->Addresses[jj].ppAdrCopy1 = (DWORD_PTR)p->Addresses[jj].ppAdr; p->Addresses[jj].ppAdrCopy2 = (DWORD_PTR)*p->Addresses[jj].ppAdr; p->Addresses[jj].pModulePtr = (DWORD_PTR)p->hModule; IMAGE_NT_HEADERS* nt_header = (IMAGE_NT_HEADERS*)((char*)p->hModule + ((IMAGE_DOS_HEADER*)p->hModule)->e_lfanew); p->Addresses[jj].nModuleSize = nt_header->OptionalHeader.SizeOfImage; #endif //Для проверки, а то при UnsetHook("cscapi.dll") почему-то возникла ошибка ERROR_INVALID_PARAMETER в VirtualProtect _ASSERTEX(p->hModule==Module); HLOG2("SetHookPrep.CheckCallbackPtr.1",f); _ASSERTEX(CheckCallbackPtr(p->hModule, 1, (FARPROC*)&p->Addresses[jj].ppAdr, TRUE)); HLOGEND2(); p->Addresses[jj].pOld = thunk->u1.Function; p->Addresses[jj].pOur = (DWORD_PTR)ph->NewAddress; #ifdef _DEBUG lstrcpynA(p->Addresses[jj].sName, ph->Name, countof(p->Addresses[jj].sName)); #endif _ASSERTEX(p->nAdrUsed < countof(p->Addresses)); p->nAdrUsed++; //информационно } #ifdef _DEBUG if (bExecutable) ph->ReplacedInExe = TRUE; #endif //DebugString( ToTchar( ph->Name ) ); res = true; HLOGEND1(); } // if (jj >= 0) HLOGEND1(); } // for (f = 0;; thunk++, thunkO++, f++) } // for (s = 0; s <= 1; s++) HLOGEND1(); HLOGEND(); } // for (i = 0; i < nCount; i++) HLOGEND(); } SAFECATCH { } return res; } bool SetHookChange(LPCWSTR asModule, HMODULE Module, BOOL abForceHooks, bool (&bFnNeedHook)[MAX_HOOKED_PROCS], HkModuleInfo* p) { bool bHooked = false; size_t j = 0; DWORD dwErr = (DWORD)-1; _ASSERTEX(j<gnHookedFuncs && gnHookedFuncs<=MAX_HOOKED_PROCS); SAFETRY { while (j < gnHookedFuncs) { // Может быть NULL, если импортируются не все функции if (p->Addresses[j].ppAdr && bFnNeedHook[j]) { if (*p->Addresses[j].ppAdr == p->Addresses[j].pOur) { // оказалось захучено в другой нити или раньше _ASSERTEX(*p->Addresses[j].ppAdr != p->Addresses[j].pOur); } else { DWORD old_protect = 0xCDCDCDCD; if (!VirtualProtect(p->Addresses[j].ppAdr, sizeof(*p->Addresses[j].ppAdr), PAGE_READWRITE, &old_protect)) { dwErr = GetLastError(); _ASSERTEX(FALSE); } else { bHooked = true; *p->Addresses[j].ppAdr = p->Addresses[j].pOur; p->Addresses[j].bHooked = TRUE; VirtualProtect(p->Addresses[j].ppAdr, sizeof(*p->Addresses[j].ppAdr), old_protect, &old_protect); } } } j++; } } SAFECATCH { // Ошибка назначения p->Addresses[j].pOur = 0; } return bHooked; } DWORD GetMainThreadId(bool bUseCurrentAsMain) { // Найти ID основной нити if (!gnHookMainThreadId) { if (bUseCurrentAsMain) { gnHookMainThreadId = GetCurrentThreadId(); } else { DWORD dwPID = GetCurrentProcessId(); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, dwPID); if (snapshot != INVALID_HANDLE_VALUE) { THREADENTRY32 module = {sizeof(THREADENTRY32)}; if (Thread32First(snapshot, &module)) { while (!gnHookMainThreadId) { if (module.th32OwnerProcessID == dwPID) { gnHookMainThreadId = module.th32ThreadID; break; } if (!Thread32Next(snapshot, &module)) break; } } CloseHandle(snapshot); } } } #ifdef _DEBUG char szInfo[100]; msprintf(szInfo, countof(szInfo), "GetMainThreadId()=%u, TID=%u\n", gnHookMainThreadId, GetCurrentThreadId()); //OutputDebugStringA(szInfo); #endif _ASSERTE(gnHookMainThreadId!=0); return gnHookMainThreadId; } VOID CALLBACK LdrDllNotification(ULONG NotificationReason, const LDR_DLL_NOTIFICATION_DATA* NotificationData, PVOID Context) { DWORD dwSaveErrCode = GetLastError(); wchar_t szModule[MAX_PATH*2] = L""; HMODULE hModule; BOOL bMainThread = (GetCurrentThreadId() == gnHookMainThreadId); const UNICODE_STRING* FullDllName; //The full path name of the DLL module. const UNICODE_STRING* BaseDllName; //The base file name of the DLL module. switch (NotificationReason) { case LDR_DLL_NOTIFICATION_REASON_LOADED: FullDllName = NotificationData->Loaded.FullDllName; BaseDllName = NotificationData->Loaded.BaseDllName; hModule = (HMODULE)NotificationData->Loaded.DllBase; break; case LDR_DLL_NOTIFICATION_REASON_UNLOADED: FullDllName = NotificationData->Unloaded.FullDllName; BaseDllName = NotificationData->Unloaded.BaseDllName; hModule = (HMODULE)NotificationData->Unloaded.DllBase; break; default: return; } if (FullDllName && FullDllName->Buffer) memmove(szModule, FullDllName->Buffer, min(sizeof(szModule)-2,FullDllName->Length)); else if (BaseDllName && BaseDllName->Buffer) memmove(szModule, BaseDllName->Buffer, min(sizeof(szModule)-2,BaseDllName->Length)); #ifdef _DEBUG wchar_t szDbgInfo[MAX_PATH*3]; _wsprintf(szDbgInfo, SKIPLEN(countof(szDbgInfo)) L"ConEmuHk: Ldr(%s) " WIN3264TEST(L"0x%08X",L"0x%08X%08X") L" '%s'\n", (NotificationReason==LDR_DLL_NOTIFICATION_REASON_LOADED) ? L"Loaded" : L"Unload", WIN3264WSPRINT(hModule), szModule); DebugString(szDbgInfo); #endif switch (NotificationReason) { case LDR_DLL_NOTIFICATION_REASON_LOADED: if (PrepareNewModule(hModule, NULL, szModule, TRUE, TRUE)) { HookItem* ph = NULL;; GetOriginalAddress((void*)(FARPROC)OnLoadLibraryW, (void*)(FARPROC)LoadLibraryW, FALSE, &ph); if (ph && ph->PostCallBack) { SETARGS1(&hModule,szModule); ph->PostCallBack(&args); } } break; case LDR_DLL_NOTIFICATION_REASON_UNLOADED: UnprepareModule(hModule, szModule, 0); UnprepareModule(hModule, szModule, 2); break; } SetLastError(dwSaveErrCode); } // Подменить Импортируемые функции во всех модулях процесса, загруженных ДО conemuhk.dll // *aszExcludedModules - должны указывать на константные значения (program lifetime) bool __stdcall SetAllHooks(HMODULE ahOurDll, const wchar_t** aszExcludedModules /*= NULL*/, BOOL abForceHooks) { // т.к. SetAllHooks может быть вызван из разных dll - запоминаем однократно if (!ghOurModule) ghOurModule = ahOurDll; if (!gpHooks) { HLOG1("SetAllHooks.InitHooks",0); InitHooks(NULL); if (!gpHooks) return false; HLOGEND1(); } #if 0 if (!gbHooksSorted) { HLOG1("InitHooksSort",0); InitHooksSort(); HLOGEND1(); } #endif #ifdef _DEBUG wchar_t szHookProc[128]; for (int i = 0; gpHooks[i].NewAddress; i++) { msprintf(szHookProc, countof(szHookProc), L"## %S -> 0x%08X (exe: 0x%X)\n", gpHooks[i].Name, (DWORD)gpHooks[i].NewAddress, (DWORD)gpHooks[i].ExeOldAddress); DebugString(szHookProc); } #endif // Запомнить aszExcludedModules if (aszExcludedModules) { INT_PTR j; bool skip; for (INT_PTR i = 0; aszExcludedModules[i]; i++) { j = 0; skip = false; while (ExcludedModules[j]) { if (lstrcmpi(ExcludedModules[j], aszExcludedModules[i]) == 0) { skip = true; break; } j++; } if (skip) continue; if (j > 0) { if ((j+1) >= MAX_EXCLUDED_MODULES) { // Превышено допустимое количество _ASSERTE((j+1) < MAX_EXCLUDED_MODULES); continue; } ExcludedModules[j] = aszExcludedModules[i]; ExcludedModules[j+1] = NULL; // на всякий } } } // Для исполняемого файла могут быть заданы дополнительные inject-ы (сравнение в FAR) HMODULE hExecutable = GetModuleHandle(0); HANDLE snapshot; HLOG0("SetAllHooks.GetMainThreadId",0); // Найти ID основной нити GetMainThreadId(false); _ASSERTE(gnHookMainThreadId!=0); HLOGEND(); wchar_t szInfo[MAX_PATH+2] = {}; // Если просили хукать только exe-шник if (gbHookExecutableOnly) { GetModuleFileName(NULL, szInfo, countof(szInfo)-2); wcscat_c(szInfo, L"\n"); DebugString(szInfo); // Go HLOG("SetAllHooks.SetHook(exe)",0); SetHook(szInfo, hExecutable, abForceHooks); HLOGEND(); } else { #ifdef _DEBUG msprintf(szInfo, countof(szInfo), L"!!! TH32CS_SNAPMODULE, TID=%u, SetAllHooks, hOurModule=" WIN3264TEST(L"0x%08X\n",L"0x%08X%08X\n"), GetCurrentThreadId(), WIN3264WSPRINT(ahOurDll)); DebugString(szInfo); #endif HLOG("SetAllHooks.CreateSnap",0); // Начались замены во всех загруженных (linked) модулях snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, 0); HLOGEND(); if (snapshot != INVALID_HANDLE_VALUE) { MODULEENTRY32 module = {sizeof(MODULEENTRY32)}; HLOG("SetAllHooks.EnumStart",0); HLOG("SetAllHooks.Module32First/Module32Next",0); for (BOOL res = Module32First(snapshot, &module); res; res = Module32Next(snapshot, &module)) { HLOGEND(); if (module.hModule && !IsModuleExcluded(module.hModule, NULL, module.szModule)) { lstrcpyn(szInfo, module.szModule, countof(szInfo)-2); wcscat_c(szInfo, L"\n"); DebugString(szInfo); // Go HLOG1("SetAllHooks.SetHook",(DWORD)module.hModule); SetHook(module.szModule, module.hModule/*, (module.hModule == hExecutable)*/, abForceHooks); HLOGEND1(); } HLOG("SetAllHooks.Module32First/Module32Next",0); } HLOGEND(); HLOG("SetAllHooks.CloseSnap",0); CloseHandle(snapshot); HLOGEND(); } } DebugString(L"SetAllHooks finished\n"); return true; } bool UnsetHookInt(HMODULE Module) { bool bUnhooked = false, res = false; IMAGE_IMPORT_DESCRIPTOR* Import = 0; size_t Size = 0; _ASSERTE(Module!=NULL); IMAGE_DOS_HEADER* dos_header = (IMAGE_DOS_HEADER*)Module; IMAGE_NT_HEADERS* nt_header; SAFETRY { if (dos_header->e_magic == IMAGE_DOS_SIGNATURE /*'ZM'*/) { nt_header = (IMAGE_NT_HEADERS*)((char*)Module + dos_header->e_lfanew); if (nt_header->Signature != 0x004550) goto wrap; else { Import = (IMAGE_IMPORT_DESCRIPTOR*)((char*)Module + (DWORD)(nt_header->OptionalHeader. DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]. VirtualAddress)); Size = nt_header->OptionalHeader. DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size; } } else goto wrap; // if wrong module or no import table if (Module == INVALID_HANDLE_VALUE || !Import) goto wrap; size_t i, s, nCount; nCount = Size / sizeof(IMAGE_IMPORT_DESCRIPTOR); //_ASSERTE(Size == (nCount * sizeof(IMAGE_IMPORT_DESCRIPTOR))); -- ровно быть не обязано for (s = 0; s <= 1; s++) { for (i = 0; i < nCount; i++) { if (Import[i].Name == 0) break; #ifdef _DEBUG char* mod_name = (char*)Module + Import[i].Name; #endif DWORD_PTR rvaINT = Import[i].OriginalFirstThunk; DWORD_PTR rvaIAT = Import[i].FirstThunk; //-V101 if (rvaINT == 0) // No Characteristics field? { // Yes! Gotta have a non-zero FirstThunk field then. rvaINT = rvaIAT; if (rvaINT == 0) // No FirstThunk field? Ooops!!! { _ASSERTE(rvaINT!=0); break; } } //PIMAGE_IMPORT_BY_NAME pOrdinalName = NULL, pOrdinalNameO = NULL; PIMAGE_IMPORT_BY_NAME pOrdinalNameO = NULL; //IMAGE_IMPORT_BY_NAME** byname = (IMAGE_IMPORT_BY_NAME**)((char*)Module + rvaINT); //IMAGE_THUNK_DATA* thunk = (IMAGE_THUNK_DATA*)((char*)Module + rvaIAT); IMAGE_THUNK_DATA* thunk = (IMAGE_THUNK_DATA*)GetPtrFromRVA(rvaIAT, nt_header, (PBYTE)Module); IMAGE_THUNK_DATA* thunkO = (IMAGE_THUNK_DATA*)GetPtrFromRVA(rvaINT, nt_header, (PBYTE)Module); if (!thunk || !thunkO) { _ASSERTE(thunk && thunkO); continue; } int f = 0; for (f = 0 ;; thunk++, thunkO++, f++) { //110220 - something strange. валимся при выходе из некоторых программ (AddFont.exe) // смысл в том, что thunk указывает на НЕ валидную область памяти. // Разбор полетов показал, что программа сама порушила таблицу импортов. //Issue 466: We must check every thunk, not first (perl.exe fails?) //111127 - ..\GIT\lib\perl5\site_perl\5.8.8\msys\auto\SVN\_Core\_Core.dll // похоже, в этой длл кривая таблица импортов #ifndef USE_SEH if (isBadModulePtr(thunk, sizeof(IMAGE_THUNK_DATA), Module, nt_header)) { _ASSERTE(thunk && FALSE); break; } #endif if (!thunk->u1.Function) { break; } #ifndef USE_SEH if (isBadModulePtr(thunkO, sizeof(IMAGE_THUNK_DATA), Module, nt_header)) { _ASSERTE(thunkO && FALSE); break; } #endif const char* pszFuncName = NULL; // Имя функции проверяем на втором шаге if (s && thunk->u1.Function != thunkO->u1.Function && !IMAGE_SNAP_BY_ORDINAL(thunkO->u1.Ordinal)) { pOrdinalNameO = (PIMAGE_IMPORT_BY_NAME)GetPtrFromRVA(thunkO->u1.AddressOfData, nt_header, (PBYTE)Module); #ifdef USE_SEH pszFuncName = (LPCSTR)pOrdinalNameO->Name; #else #ifdef _DEBUG bool bTestValid = (((LPBYTE)pOrdinalNameO) >= ((LPBYTE)Module)) && (((LPBYTE)pOrdinalNameO) <= (((LPBYTE)Module) + nt_header->OptionalHeader.SizeOfImage)); #endif //WARNING!!! Множественные вызовы IsBad???Ptr могут глючить и тормозить bool lbValidPtr = !isBadModulePtr(pOrdinalNameO, sizeof(IMAGE_IMPORT_BY_NAME), Module, nt_header); #ifdef _DEBUG static bool bFirstAssert = false; if (!lbValidPtr && !bFirstAssert) { bFirstAssert = true; //_ASSERTE(lbValidPtr); } #endif if (lbValidPtr) { //WARNING!!! Множественные вызовы IsBad???Ptr могут глючить и тормозить lbValidPtr = !isBadModuleStringA((LPCSTR)pOrdinalNameO->Name, 10, Module, nt_header); _ASSERTE(lbValidPtr); if (lbValidPtr) pszFuncName = (LPCSTR)pOrdinalNameO->Name; } #endif } int j; for (j = 0; gpHooks[j].Name; j++) { if (!gpHooks[j].OldAddress) continue; // Эту функцию не обрабатывали (хотя должны были?) // Нужно найти функцию (thunk) в gpHooks через NewAddress или имя if ((void*)thunk->u1.Function != gpHooks[j].NewAddress) { if (!pszFuncName) { continue; } else { if (strcmp(pszFuncName, gpHooks[j].Name)!=0) continue; } // OldAddress уже может отличаться от оригинального экспорта библиотеки // Это если функцию захукали уже после нас } #ifdef _DEBUG // Может ли такое быть? Модуль был "захукан" без нашего ведома? // Наблюдается в Win2k8R2 static bool bWarned = false; if (!bWarned) { bWarned = true; _ASSERTE(FALSE && "Unknown function replacement was found (external hook?)"); } #endif // Если мы дошли сюда - значит функция найдена (или по адресу или по имени) // BugBug: в принципе, эту функцию мог захукать и другой модуль (уже после нас), // но лучше вернуть оригинальную, чем потом свалиться DWORD old_protect = 0xCDCDCDCD; if (VirtualProtect(&thunk->u1.Function, sizeof(thunk->u1.Function), PAGE_READWRITE, &old_protect)) { // BugBug: ExeOldAddress может отличаться от оригинального, если функция была перехвачена ДО нас //if (abExecutable && gpHooks[j].ExeOldAddress) // thunk->u1.Function = (DWORD_PTR)gpHooks[j].ExeOldAddress; //else thunk->u1.Function = (DWORD_PTR)gpHooks[j].OldAddress; VirtualProtect(&thunk->u1.Function, sizeof(thunk->u1.Function), old_protect, &old_protect); bUnhooked = true; } //DebugString( ToTchar( gpHooks[j].Name ) ); break; // перейти к следующему thunk-у } } } } wrap: res = bUnhooked; } SAFECATCH { } return res; } // Подменить Импортируемые функции в модуле bool UnsetHook(HMODULE Module) { if (!gpHooks) return false; if (!IsModuleValid(Module)) return false; MSectionLock CS; if (!gpHookCS->isLockedExclusive() && !LockHooks(Module, L"uninstall", &CS)) return false; HkModuleInfo* p = IsHookedModule(Module); bool bUnhooked = false; DWORD dwErr = (DWORD)-1; if (!p) { // Хотя модуль и не обрабатывался нами, но может получиться, что у него переопределенные импорты // Зовем в отдельной функции, т.к. __try HLOG1("UnsetHook.Int",0); bUnhooked = UnsetHookInt(Module); HLOGEND1(); } else { if (p->Hooked == 1) { HLOG1("UnsetHook.Var",0); for (size_t i = 0; i < MAX_HOOKED_PROCS; i++) { if (p->Addresses[i].pOur == 0) continue; // Этот адрес поменять не смогли #ifdef _DEBUG //Для проверки, а то при UnsetHook("cscapi.dll") почему-то возникла ошибка ERROR_INVALID_PARAMETER в VirtualProtect CheckCallbackPtr(p->hModule, 1, (FARPROC*)&p->Addresses[i].ppAdr, TRUE); #endif DWORD old_protect = 0xCDCDCDCD; if (!VirtualProtect(p->Addresses[i].ppAdr, sizeof(*p->Addresses[i].ppAdr), PAGE_READWRITE, &old_protect)) { dwErr = GetLastError(); //Один раз выскочило ERROR_INVALID_PARAMETER // При этом, (p->Addresses[i].ppAdr==0x04cde0e0), (p->Addresses[i].ppAdr==0x912edebf) // что было полной пургой. Ни одного модуля в этих адресах не было _ASSERTEX(dwErr==ERROR_INVALID_ADDRESS); } else { bUnhooked = true; // BugBug: ExeOldAddress может отличаться от оригинального, если функция была перехвачена без нас //if (abExecutable && gpHooks[j].ExeOldAddress) // thunk->u1.Function = (DWORD_PTR)gpHooks[j].ExeOldAddress; //else *p->Addresses[i].ppAdr = p->Addresses[i].pOld; p->Addresses[i].bHooked = FALSE; VirtualProtect(p->Addresses[i].ppAdr, sizeof(*p->Addresses[i].ppAdr), old_protect, &old_protect); } } // Хуки сняты p->Hooked = 2; HLOGEND1(); } } #ifdef _DEBUG if (bUnhooked && p) { wchar_t* szDbg = (wchar_t*)calloc(MAX_PATH*3, 2); lstrcpy(szDbg, L" ## Hooks was UNset by conemu: "); lstrcat(szDbg, p->sModuleName); lstrcat(szDbg, L"\n"); DebugString(szDbg); free(szDbg); } #endif return bUnhooked; } void __stdcall UnsetAllHooks() { HMODULE hExecutable = GetModuleHandle(0); wchar_t szInfo[MAX_PATH+2] = {}; if (gbLdrDllNotificationUsed) { _ASSERTEX(LdrUnregisterDllNotification!=NULL); LdrUnregisterDllNotification(gpLdrDllNotificationCookie); } // Если просили хукать только exe-шник if (gbHookExecutableOnly) { GetModuleFileName(NULL, szInfo, countof(szInfo)-2); #ifdef _DEBUG wcscat_c(szInfo, L"\n"); //WARNING!!! OutputDebugString must NOT be used from ConEmuHk::DllMain(DLL_PROCESS_DETACH). See Issue 465 DebugString(szInfo); #endif // Go UnsetHook(hExecutable); } else { #ifdef _DEBUG //WARNING!!! OutputDebugString must NOT be used from ConEmuHk::DllMain(DLL_PROCESS_DETACH). See Issue 465 msprintf(szInfo, countof(szInfo), L"!!! TH32CS_SNAPMODULE, TID=%u, UnsetAllHooks\n", GetCurrentThreadId()); DebugString(szInfo); #endif //Warning: TH32CS_SNAPMODULE - может зависать при вызовах из LoadLibrary/FreeLibrary. HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, 0); WARNING("Убрать перехват экспортов из Kernel32.dll"); if (snapshot != INVALID_HANDLE_VALUE) { MODULEENTRY32 module = {sizeof(module)}; for (BOOL res = Module32First(snapshot, &module); res; res = Module32Next(snapshot, &module)) { if (module.hModule && !IsModuleExcluded(module.hModule, NULL, module.szModule)) { lstrcpyn(szInfo, module.szModule, countof(szInfo)-2); //WARNING!!! OutputDebugString must NOT be used from ConEmuHk::DllMain(DLL_PROCESS_DETACH). See Issue 465 #ifdef _DEBUG wcscat_c(szInfo, L"\n"); DebugString(szInfo); #endif // Go UnsetHook(module.hModule/*, (module.hModule == hExecutable)*/); } } CloseHandle(snapshot); } } #ifdef _DEBUG DebugStringA("UnsetAllHooks finished\n"); #endif } /* **************************** * * * * Далее идут собственно хуки * * * * **************************** */ void LoadModuleFailed(LPCSTR asModuleA, LPCWSTR asModuleW) { DWORD dwErrCode = GetLastError(); if (!gnLastLogSetChange) { CShellProc* sp = new CShellProc(); if (sp) { gnLastLogSetChange = GetTickCount(); gbLogLibraries = sp->LoadSrvMapping() && sp->GetLogLibraries(); delete sp; } SetLastError(dwErrCode); } if (!gbLogLibraries) return; CESERVER_REQ* pIn = NULL; wchar_t szModule[MAX_PATH+1]; szModule[0] = 0; wchar_t szErrCode[64]; szErrCode[0] = 0; msprintf(szErrCode, countof(szErrCode), L"ErrCode=0x%08X", dwErrCode); if (!asModuleA && !asModuleW) { wcscpy_c(szModule, L"<NULL>"); asModuleW = szModule; } else if (asModuleA) { MultiByteToWideChar(AreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, asModuleA, -1, szModule, countof(szModule)); szModule[countof(szModule)-1] = 0; asModuleW = szModule; } pIn = ExecuteNewCmdOnCreate(NULL, ghConWnd, eLoadLibrary, L"Fail", asModuleW, szErrCode, NULL, NULL, NULL, NULL, #ifdef _WIN64 64 #else 32 #endif , 0, NULL, NULL, NULL); if (pIn) { HWND hConWnd = GetConsoleWindow(); CESERVER_REQ* pOut = ExecuteGuiCmd(hConWnd, pIn, hConWnd); ExecuteFreeResult(pIn); if (pOut) ExecuteFreeResult(pOut); } SetLastError(dwErrCode); } #ifdef USECHECKPROCESSMODULES // В процессе загрузки модуля (module) могли подгрузиться // (статически или динамически) и другие библиотеки! void CheckProcessModules(HMODULE hFromModule); #endif // Заменить в модуле Module ЭКСпортируемые функции на подменяемые плагином нихрена // НЕ получится, т.к. в Win32 библиотека shell32 может быть загружена ПОСЛЕ conemu.dll // что вызовет некорректные смещения функций, // а в Win64 смещения вообще должны быть 64битными, а структура модуля хранит только 32битные смещения bool PrepareNewModule(HMODULE module, LPCSTR asModuleA, LPCWSTR asModuleW, BOOL abNoSnapshoot /*= FALSE*/, BOOL abForceHooks /*= FALSE*/) { bool lbAllSysLoaded = true; for (size_t s = 0; s < countof(ghSysDll); s++) { if (ghSysDll[s] && (*ghSysDll[s] == NULL)) { lbAllSysLoaded = false; break; } } if (!lbAllSysLoaded) { // Некоторые перехватываемые библиотеки могли быть // не загружены во время первичной инициализации // Соответственно для них (если они появились) нужно // получить "оригинальные" адреса процедур InitHooks(NULL); } if (!module) { LoadModuleFailed(asModuleA, asModuleW); #ifdef USECHECKPROCESSMODULES // В процессе загрузки модуля (module) могли подгрузиться // (статически или динамически) и другие библиотеки! CheckProcessModules(module); #endif return false; } // Проверить по gpHookedModules а не был ли модуль уже обработан? if (IsHookedModule(module)) { // Этот модуль уже обработан! return false; } bool lbModuleOk = false; BOOL lbResource = LDR_IS_RESOURCE(module); CShellProc* sp = new CShellProc(); if (sp != NULL) { if (!gnLastLogSetChange || ((GetTickCount() - gnLastLogSetChange) > 2000)) { gnLastLogSetChange = GetTickCount(); gbLogLibraries = sp->LoadSrvMapping(TRUE) && sp->GetLogLibraries(); } if (gbLogLibraries) { CESERVER_REQ* pIn = NULL; LPCWSTR pszModuleW = asModuleW; wchar_t szModule[MAX_PATH+1]; szModule[0] = 0; if (!asModuleA && !asModuleW) { wcscpy_c(szModule, L"<NULL>"); pszModuleW = szModule; } else if (asModuleA) { MultiByteToWideChar(AreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, asModuleA, -1, szModule, countof(szModule)); szModule[countof(szModule)-1] = 0; pszModuleW = szModule; } wchar_t szInfo[64]; szInfo[0] = 0; #ifdef _WIN64 if ((DWORD)((DWORD_PTR)module >> 32)) msprintf(szInfo, countof(szInfo), L"Module=0x%08X%08X", (DWORD)((DWORD_PTR)module >> 32), (DWORD)((DWORD_PTR)module & 0xFFFFFFFF)); //-V112 else msprintf(szInfo, countof(szInfo), L"Module=0x%08X", (DWORD)((DWORD_PTR)module & 0xFFFFFFFF)); //-V112 #else msprintf(szInfo, countof(szInfo), L"Module=0x%08X", (DWORD)module); #endif pIn = sp->NewCmdOnCreate(eLoadLibrary, NULL, pszModuleW, szInfo, NULL, NULL, NULL, NULL, #ifdef _WIN64 64 #else 32 #endif , 0, NULL, NULL, NULL); if (pIn) { HWND hConWnd = GetConsoleWindow(); CESERVER_REQ* pOut = ExecuteGuiCmd(hConWnd, pIn, hConWnd); ExecuteFreeResult(pIn); if (pOut) ExecuteFreeResult(pOut); } } delete sp; sp = NULL; } #ifdef USECHECKPROCESSMODULES if (!lbResource) { if (!abNoSnapshoot /*&& !lbResource*/) { #if 0 // -- уже выполнено выше // Некоторые перехватываемые библиотеки могли быть // не загружены во время первичной инициализации // Соответственно для них (если они появились) нужно // получить "оригинальные" адреса процедур InitHooks(NULL); #endif // В процессе загрузки модуля (module) могли подгрузиться // (статически или динамически) и другие библиотеки! CheckProcessModules(module); } if (!gbHookExecutableOnly && !IsModuleExcluded(module, asModuleA, asModuleW)) { wchar_t szModule[128] = {}; if (asModuleA) { LPCSTR pszNameA = strrchr(asModuleA, '\\'); if (!pszNameA) pszNameA = asModuleA; else pszNameA++; MultiByteToWideChar(CP_ACP, 0, pszNameA, -1, szModule, countof(szModule)-1); } else if (asModuleW) { LPCWSTR pszNameW = wcsrchr(asModuleW, L'\\'); if (!pszNameW) pszNameW = asModuleW; else pszNameW++; lstrcpyn(szModule, pszNameW, countof(szModule)); } lbModuleOk = true; // Подмена импортируемых функций в module SetHook(szModule, module, FALSE); } } #else lbModuleOk = true; #endif return lbModuleOk; } #ifdef USECHECKPROCESSMODULES // В процессе загрузки модуля (module) могли подгрузиться // (статически или динамически) и другие библиотеки! void CheckProcessModules(HMODULE hFromModule) { // Если просили хукать только exe-шник if (gbHookExecutableOnly) { return; } #ifdef _DEBUG if (gbSkipCheckProcessModules) { return; } #endif #ifdef _DEBUG char szDbgInfo[100]; msprintf(szDbgInfo, countof(szDbgInfo), "!!! TH32CS_SNAPMODULE, TID=%u, CheckProcessModules, hFromModule=" WIN3264TEST("0x%08X\n","0x%08X%08X\n"), GetCurrentThreadId(), WIN3264WSPRINT(hFromModule)); DebugStringA(szDbgInfo); #endif WARNING("TH32CS_SNAPMODULE - может зависать при вызовах из LoadLibrary/FreeLibrary!!!"); // Может, имеет смысл запустить фоновую нить, в которой проверить все загруженные модули? //Warning: TH32CS_SNAPMODULE - может зависать при вызовах из LoadLibrary/FreeLibrary. HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId()); MODULEENTRY32 mi = {sizeof(mi)}; if (h && h != INVALID_HANDLE_VALUE && Module32First(h, &mi)) { BOOL lbAddMod = FALSE; do { //CheckLoadedModule(mi.szModule); //if (!ghUser32) //{ // // Если на старте exe-шника user32 НЕ подлинковался - нужно загрузить из него требуемые процедуры! // if (*mi.szModule && (!lstrcmpiW(mi.szModule, L"user32.dll") || !lstrcmpiW(mi.szModule, L"user32"))) // { // ghUser32 = LoadLibraryW(user32); // LoadLibrary, т.к. и нам он нужен - накрутить счетчик // //InitHooks(NULL); -- ниже и так будет выполнено // } //} //if (!ghShell32) //{ // // Если на старте exe-шника shell32 НЕ подлинковался - нужно загрузить из него требуемые процедуры! // if (*mi.szModule && (!lstrcmpiW(mi.szModule, L"shell32.dll") || !lstrcmpiW(mi.szModule, L"shell32"))) // { // ghShell32 = LoadLibraryW(shell32); // LoadLibrary, т.к. и нам он нужен - накрутить счетчик // //InitHooks(NULL); -- ниже и так будет выполнено // } //} //if (!ghAdvapi32) //{ // // Если на старте exe-шника advapi32 НЕ подлинковался - нужно загрузить из него требуемые процедуры! // if (*mi.szModule && (!lstrcmpiW(mi.szModule, L"advapi32.dll") || !lstrcmpiW(mi.szModule, L"advapi32"))) // { // ghAdvapi32 = LoadLibraryW(advapi32); // LoadLibrary, т.к. и нам он нужен - накрутить счетчик // if (ghAdvapi32) // { // RegOpenKeyEx_f = (RegOpenKeyEx_t)GetProcAddress(ghAdvapi32, "RegOpenKeyExW"); // RegCreateKeyEx_f = (RegCreateKeyEx_t)GetProcAddress(ghAdvapi32, "RegCreateKeyExW"); // RegCloseKey_f = (RegCloseKey_t)GetProcAddress(ghAdvapi32, "RegCloseKey"); // } // //InitHooks(NULL); -- ниже и так будет выполнено // } //} if (lbAddMod) { if (PrepareNewModule(mi.hModule, NULL, mi.szModule, TRUE/*не звать CheckProcessModules*/)) CheckLoadedModule(mi.szModule); } else if (mi.hModule == hFromModule) { lbAddMod = TRUE; } } while (Module32Next(h, &mi)); CloseHandle(h); } } #endif #ifdef _DEBUG void OnLoadLibraryLog(LPCSTR lpLibraryA, LPCWSTR lpLibraryW) { #if 0 if ((lpLibraryA && strncmp(lpLibraryA, "advapi32", 8)==0) || (lpLibraryW && wcsncmp(lpLibraryW, L"advapi32", 8)==0)) { extern HANDLE ghDebugSshLibs, ghDebugSshLibsRc; if (ghDebugSshLibs) { SetEvent(ghDebugSshLibs); WaitForSingleObject(ghDebugSshLibsRc, 1000); } } #endif } #else #define OnLoadLibraryLog(lpLibraryA,lpLibraryW) #endif /* ************** */ HMODULE WINAPI OnLoadLibraryAWork(FARPROC lpfn, HookItem *ph, BOOL bMainThread, const char* lpFileName) { typedef HMODULE(WINAPI* OnLoadLibraryA_t)(const char* lpFileName); OnLoadLibraryLog(lpFileName,NULL); HMODULE module = ((OnLoadLibraryA_t)lpfn)(lpFileName); DWORD dwLoadErrCode = GetLastError(); if (gbHooksTemporaryDisabled) return module; // Issue 1079: Almost hangs with PHP if (lstrcmpiA(lpFileName, "kernel32.dll") == 0) return module; if (PrepareNewModule(module, lpFileName, NULL)) { if (ph && ph->PostCallBack) { SETARGS1(&module,lpFileName); ph->PostCallBack(&args); } } SetLastError(dwLoadErrCode); return module; } HMODULE WINAPI OnLoadLibraryA(const char* lpFileName) { typedef HMODULE(WINAPI* OnLoadLibraryA_t)(const char* lpFileName); ORIGINAL(LoadLibraryA); return OnLoadLibraryAWork((FARPROC)F(LoadLibraryA), ph, bMainThread, lpFileName); } /* ************** */ HMODULE WINAPI OnLoadLibraryWWork(FARPROC lpfn, HookItem *ph, BOOL bMainThread, const wchar_t* lpFileName) { typedef HMODULE(WINAPI* OnLoadLibraryW_t)(const wchar_t* lpFileName); HMODULE module = NULL; OnLoadLibraryLog(NULL,lpFileName); // Спрятать ExtendedConsole.dll с глаз долой, в сервисную папку "ConEmu" if (lpFileName && ((lstrcmpiW(lpFileName, L"ExtendedConsole.dll") == 0) || lstrcmpiW(lpFileName, L"ExtendedConsole64.dll") == 0)) { CESERVER_CONSOLE_MAPPING_HDR *Info = (CESERVER_CONSOLE_MAPPING_HDR*)calloc(1,sizeof(*Info)); if (Info && ::LoadSrvMapping(ghConWnd, *Info)) { size_t cchMax = countof(Info->ComSpec.ConEmuBaseDir)+64; wchar_t* pszFullPath = (wchar_t*)calloc(cchMax,sizeof(*pszFullPath)); if (pszFullPath) { _wcscpy_c(pszFullPath, cchMax, Info->ComSpec.ConEmuBaseDir); _wcscat_c(pszFullPath, cchMax, WIN3264TEST(L"\\ExtendedConsole.dll",L"\\ExtendedConsole64.dll")); module = ((OnLoadLibraryW_t)lpfn)(pszFullPath); SafeFree(pszFullPath); } } SafeFree(Info); } if (!module) module = ((OnLoadLibraryW_t)lpfn)(lpFileName); DWORD dwLoadErrCode = GetLastError(); if (gbHooksTemporaryDisabled || gbLdrDllNotificationUsed) return module; // Issue 1079: Almost hangs with PHP if (lstrcmpi(lpFileName, L"kernel32.dll") == 0) return module; if (PrepareNewModule(module, NULL, lpFileName)) { if (ph && ph->PostCallBack) { SETARGS1(&module,lpFileName); ph->PostCallBack(&args); } } SetLastError(dwLoadErrCode); return module; } HMODULE WINAPI OnLoadLibraryW(const wchar_t* lpFileName) { typedef HMODULE(WINAPI* OnLoadLibraryW_t)(const wchar_t* lpFileName); ORIGINAL(LoadLibraryW); return OnLoadLibraryWWork((FARPROC)F(LoadLibraryW), ph, bMainThread, lpFileName); } /* ************** */ HMODULE WINAPI OnLoadLibraryExAWork(FARPROC lpfn, HookItem *ph, BOOL bMainThread, const char* lpFileName, HANDLE hFile, DWORD dwFlags) { typedef HMODULE(WINAPI* OnLoadLibraryExA_t)(const char* lpFileName, HANDLE hFile, DWORD dwFlags); OnLoadLibraryLog(lpFileName,NULL); HMODULE module = ((OnLoadLibraryExA_t)lpfn)(lpFileName, hFile, dwFlags); DWORD dwLoadErrCode = GetLastError(); if (gbHooksTemporaryDisabled) return module; if (PrepareNewModule(module, lpFileName, NULL)) { if (ph && ph->PostCallBack) { SETARGS3(&module,lpFileName,hFile,dwFlags); ph->PostCallBack(&args); } } SetLastError(dwLoadErrCode); return module; } HMODULE WINAPI OnLoadLibraryExA(const char* lpFileName, HANDLE hFile, DWORD dwFlags) { typedef HMODULE(WINAPI* OnLoadLibraryExA_t)(const char* lpFileName, HANDLE hFile, DWORD dwFlags); ORIGINAL(LoadLibraryExA); return OnLoadLibraryExAWork((FARPROC)F(LoadLibraryExA), ph, bMainThread, lpFileName, hFile, dwFlags); } /* ************** */ HMODULE WINAPI OnLoadLibraryExWWork(FARPROC lpfn, HookItem *ph, BOOL bMainThread, const wchar_t* lpFileName, HANDLE hFile, DWORD dwFlags) { typedef HMODULE(WINAPI* OnLoadLibraryExW_t)(const wchar_t* lpFileName, HANDLE hFile, DWORD dwFlags); OnLoadLibraryLog(NULL,lpFileName); HMODULE module = ((OnLoadLibraryExW_t)lpfn)(lpFileName, hFile, dwFlags); DWORD dwLoadErrCode = GetLastError(); if (gbHooksTemporaryDisabled) return module; if (PrepareNewModule(module, NULL, lpFileName)) { if (ph && ph->PostCallBack) { SETARGS3(&module,lpFileName,hFile,dwFlags); ph->PostCallBack(&args); } } SetLastError(dwLoadErrCode); return module; } HMODULE WINAPI OnLoadLibraryExW(const wchar_t* lpFileName, HANDLE hFile, DWORD dwFlags) { typedef HMODULE(WINAPI* OnLoadLibraryExW_t)(const wchar_t* lpFileName, HANDLE hFile, DWORD dwFlags); ORIGINAL(LoadLibraryExW); return OnLoadLibraryExWWork((FARPROC)F(LoadLibraryExW), ph, bMainThread, lpFileName, hFile, dwFlags); } /* ************** */ FARPROC WINAPI OnGetProcAddressWork(FARPROC lpfn, HookItem *ph, BOOL bMainThread, HMODULE hModule, LPCSTR lpProcName) { typedef FARPROC(WINAPI* OnGetProcAddress_t)(HMODULE hModule, LPCSTR lpProcName); FARPROC lpfnRc = NULL; #ifdef LOG_ORIGINAL_CALL char gszLastGetProcAddress[255], lsProcNameCut[64]; if (((DWORD_PTR)lpProcName) <= 0xFFFF) msprintf(lsProcNameCut, countof(lsProcNameCut), "%u", LOWORD(lpProcName)); else lstrcpynA(lsProcNameCut, lpProcName, countof(lsProcNameCut)); #endif WARNING("Убрать gbHooksTemporaryDisabled?"); if (gbHooksTemporaryDisabled) { TODO("!!!"); #ifdef LOG_ORIGINAL_CALL msprintf(gszLastGetProcAddress, countof(gszLastGetProcAddress), " OnGetProcAddress(x%08X,%s,%u)", (DWORD)hModule, (((DWORD_PTR)lpProcName) <= 0xFFFF) ? "" : lsProcNameCut, (((DWORD_PTR)lpProcName) <= 0xFFFF) ? (UINT)(DWORD_PTR)lsProcNameCut : 0); #endif } else if (gbDllStopCalled) { //-- assert нельзя, т.к. все уже деинициализировано! //_ASSERTE(ghHeap!=NULL); //-- lpfnRc = NULL; -- уже } else if (((DWORD_PTR)lpProcName) <= 0xFFFF) { TODO("!!! Обрабатывать и ORDINAL values !!!"); #ifdef LOG_ORIGINAL_CALL msprintf(gszLastGetProcAddress, countof(gszLastGetProcAddress), " OnGetProcAddress(x%08X,%u)", (DWORD)hModule, (UINT)(DWORD_PTR)lsProcNameCut); #endif // Ordinal - пока используется только для "ShellExecCmdLine" if (gpHooks && gbPrepareDefaultTerminal) { for (int i = 0; gpHooks[i].Name; i++) { // The spelling and case of a function name pointed to by lpProcName must be identical // to that in the EXPORTS statement of the source DLL's module-definition (.Def) file if (gpHooks[i].hDll == hModule && gpHooks[i].NameOrdinal && (gpHooks[i].NameOrdinal == (DWORD)(DWORD_PTR)lpProcName)) { lpfnRc = (FARPROC)gpHooks[i].NewAddress; break; } } } } else { #ifdef LOG_ORIGINAL_CALL msprintf(gszLastGetProcAddress, countof(gszLastGetProcAddress), " OnGetProcAddress(x%08X,%s)", (DWORD)hModule, lsProcNameCut); #endif if (gpHooks) { for (int i = 0; gpHooks[i].Name; i++) { // The spelling and case of a function name pointed to by lpProcName must be identical // to that in the EXPORTS statement of the source DLL's module-definition (.Def) file if (gpHooks[i].hDll == hModule && strcmp(gpHooks[i].Name, lpProcName) == 0) { lpfnRc = (FARPROC)gpHooks[i].NewAddress; break; } } } } #ifdef LOG_ORIGINAL_CALL if (lpfnRc) lstrcatA(gszLastGetProcAddress, " - hooked"); #endif if (!lpfnRc) { lpfnRc = ((OnGetProcAddress_t)lpfn)(hModule, lpProcName); #ifdef _DEBUG #ifdef ASSERT_ON_PROCNOTFOUND DWORD dwErr = GetLastError(); _ASSERTEX(lpfnRc != NULL); SetLastError(dwErr); #endif #endif } #ifdef LOG_ORIGINAL_CALL int nLeft = lstrlenA(gszLastGetProcAddress); msprintf(gszLastGetProcAddress+nLeft, countof(gszLastGetProcAddress)-nLeft, WIN3264TEST(" - 0x%08X\n"," - 0x%08X%08X\n"), WIN3264WSPRINT(lpfnRc)); DebugStringA(gszLastGetProcAddress); #endif return lpfnRc; } FARPROC WINAPI OnGetProcAddress(HMODULE hModule, LPCSTR lpProcName) { typedef FARPROC(WINAPI* OnGetProcAddress_t)(HMODULE hModule, LPCSTR lpProcName); ORIGINALFAST(GetProcAddress); return OnGetProcAddressWork((FARPROC)F(GetProcAddress), ph, FALSE, hModule, lpProcName); } FARPROC WINAPI OnGetProcAddressExp(HMODULE hModule, LPCSTR lpProcName) { return OnGetProcAddressWork(gKernelFuncs[hlfGetProcAddress].OldAddress, gpHooks+hlfGetProcAddress, FALSE, hModule, lpProcName); } /* ************** */ void UnprepareModule(HMODULE hModule, LPCWSTR pszModule, int iStep) { BOOL lbResource = LDR_IS_RESOURCE(hModule); // lbResource получается TRUE например при вызовах из version.dll wchar_t szModule[MAX_PATH*2]; szModule[0] = 0; if ((iStep == 0) && gbLogLibraries && !gbDllStopCalled) { CShellProc* sp = new CShellProc(); if (sp->LoadSrvMapping()) { CESERVER_REQ* pIn = NULL; if (pszModule && *pszModule) { lstrcpyn(szModule, pszModule, countof(szModule)); } else { wchar_t szHandle[32] = {}; #ifdef _WIN64 msprintf(szHandle, countof(szModule), L", <HMODULE=0x%08X%08X>", (DWORD)((((u64)hModule) & 0xFFFFFFFF00000000) >> 32), //-V112 (DWORD)(((u64)hModule) & 0xFFFFFFFF)); //-V112 #else msprintf(szHandle, countof(szModule), L", <HMODULE=0x%08X>", (DWORD)hModule); #endif // GetModuleFileName в некоторых случаях зависает O_O. Поэтому, запоминаем в локальном массиве имя загруженного ранее модуля if (FindModuleFileName(hModule, szModule, countof(szModule)-lstrlen(szModule)-1)) wcscat_c(szModule, szHandle); else wcscpy_c(szModule, szHandle+2); } pIn = sp->NewCmdOnCreate(eFreeLibrary, NULL, szModule, NULL, NULL, NULL, NULL, NULL, #ifdef _WIN64 64 #else 32 #endif , 0, NULL, NULL, NULL); if (pIn) { HWND hConWnd = GetConsoleWindow(); CESERVER_REQ* pOut = ExecuteGuiCmd(hConWnd, pIn, hConWnd); ExecuteFreeResult(pIn); if (pOut) ExecuteFreeResult(pOut); } } delete sp; } // Далее только если !LDR_IS_RESOURCE if ((iStep > 0) && !lbResource && !gbDllStopCalled) { // Попробуем определить, действительно ли модуль выгружен, или только счетчик уменьшился // iStep == 2 comes from LdrDllNotification(Unload) // Похоже, что если библиотека была реально выгружена, то FreeLibrary выставляет SetLastError(ERROR_GEN_FAILURE) // Актуально только для Win2k/XP так что не будем на это полагаться BOOL lbModulePost = (iStep == 2) ? FALSE : IsModuleValid(hModule); // GetModuleFileName(hModule, szModule, countof(szModule)); #ifdef _DEBUG DWORD dwErr = lbModulePost ? 0 : GetLastError(); #endif if (!lbModulePost) { RemoveHookedModule(hModule); if (ghOnLoadLibModule == hModule) { ghOnLoadLibModule = NULL; gfOnLibraryLoaded = NULL; gfOnLibraryUnLoaded = NULL; } if (gpHooks) { for (int i = 0; i<MAX_HOOKED_PROCS && gpHooks[i].NewAddress; i++) { if (gpHooks[i].hCallbackModule == hModule) { gpHooks[i].hCallbackModule = NULL; gpHooks[i].PreCallBack = NULL; gpHooks[i].PostCallBack = NULL; gpHooks[i].ExceptCallBack = NULL; } } } TODO("Тоже на цикл переделать, как в CheckLoadedModule"); if (gfOnLibraryUnLoaded) { gfOnLibraryUnLoaded(hModule); } // Если выгружена библиотека ghUser32/ghAdvapi32/ghComdlg32... // проверить, может какие наши импорты стали невалидными FreeLoadedModule(hModule); } } } BOOL WINAPI OnFreeLibraryWork(FARPROC lpfn, HookItem *ph, BOOL bMainThread, HMODULE hModule) { typedef BOOL (WINAPI* OnFreeLibrary_t)(HMODULE hModule); BOOL lbRc = FALSE; BOOL lbResource = LDR_IS_RESOURCE(hModule); // lbResource получается TRUE например при вызовах из version.dll UnprepareModule(hModule, NULL, 0); #ifdef _DEBUG BOOL lbModulePre = IsModuleValid(hModule); // GetModuleFileName(hModule, szModule, countof(szModule)); #endif // Section locking is inadmissible. One FreeLibrary may cause another FreeLibrary in _different_ thread. lbRc = ((OnFreeLibrary_t)lpfn)(hModule); DWORD dwFreeErrCode = GetLastError(); // Далее только если !LDR_IS_RESOURCE if (lbRc && !lbResource) UnprepareModule(hModule, NULL, 1); SetLastError(dwFreeErrCode); return lbRc; } BOOL WINAPI OnFreeLibrary(HMODULE hModule) { typedef BOOL (WINAPI* OnFreeLibrary_t)(HMODULE hModule); ORIGINALFAST(FreeLibrary); return OnFreeLibraryWork((FARPROC)F(FreeLibrary), ph, FALSE, hModule); } #ifdef HOOK_ERROR_PROC DWORD WINAPI OnGetLastError() { typedef DWORD (WINAPI* OnGetLastError_t)(); SUPPRESSORIGINALSHOWCALL; ORIGINALFAST(GetLastError); DWORD nErr = 0; if (F(GetLastError)) nErr = F(GetLastError)(); if (nErr == HOOK_ERROR_NO) { nErr = HOOK_ERROR_NO; } return nErr; } VOID WINAPI OnSetLastError(DWORD dwErrCode) { typedef DWORD (WINAPI* OnSetLastError_t)(DWORD dwErrCode); SUPPRESSORIGINALSHOWCALL; ORIGINALFAST(SetLastError); if (dwErrCode == HOOK_ERROR_NO) { dwErrCode = HOOK_ERROR_NO; } if (F(SetLastError)) F(SetLastError)(dwErrCode); } #endif /* ***************** Logging ****************** */ #ifdef LOG_ORIGINAL_CALL void LogFunctionCall(LPCSTR asFunc, LPCSTR asFile, int anLine) { if (!gbSuppressShowCall || gbSkipSuppressShowCall) { DWORD nErr = GetLastError(); char sFunc[128]; _wsprintfA(sFunc, SKIPLEN(countof(sFunc)) "Hook[%u]: %s\n", GetCurrentThreadId(), asFunc); DebugStringA(sFunc); SetLastError(nErr); } else { gbSuppressShowCall = false; } } #endif
27.984514
226
0.684435
Maximus5
130398d3495b5d3ce6d79ab0a1f9bcdffb37d82d
7,146
cc
C++
chrome/browser/ui/meegotouch/browser_toolbar_qt.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2015-10-12T09:14:22.000Z
2015-10-12T09:14:22.000Z
chrome/browser/ui/meegotouch/browser_toolbar_qt.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/meegotouch/browser_toolbar_qt.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2020-11-04T07:22:28.000Z
2020-11-04T07:22:28.000Z
// Copyright (c) 2010 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 "chrome/browser/ui/meegotouch/browser_toolbar_qt.h" #include "chrome/browser/ui/meegotouch/browser_window_qt.h" #include "chrome/browser/ui/meegotouch/back_forward_button_qt.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "base/base_paths.h" #include "base/command_line.h" #include "base/i18n/rtl.h" #include "base/logging.h" #include "base/path_service.h" #include "base/memory/singleton.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/ui/browser.h" #include "content/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view_qt.h" #include "chrome/browser/ui/meegotouch/tab_list_qt.h" #include "chrome/browser/upgrade_detector.h" #include "chrome/common/chrome_switches.h" #include "content/common/notification_details.h" #include "content/common/notification_service.h" #include "content/common/notification_type.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include <QDeclarativeEngine> #include <QDeclarativeView> #include <QDeclarativeContext> #include <QDeclarativeItem> #include <QGraphicsLineItem> #undef signals #include "ui/gfx/canvas_skia_paint.h" class BrowserToolbarQtImpl: public QObject { Q_OBJECT public: BrowserToolbarQtImpl(BrowserToolbarQt* toolbar): QObject(NULL), toolbar_(toolbar) { } public slots: void wrenchButtonClicked() { toolbar_->ShowWrenchMenu(); } void tabButtonClicked() { TabContents* tab_contents = toolbar_->browser()->GetSelectedTabContents(); toolbar_->TabSideBarToggle(); } void closeButtonClicked() { toolbar_->browser()->ExecuteCommandWithDisposition(IDC_CLOSE_WINDOW, CURRENT_TAB); } void backwardButtonClicked() { toolbar_->browser()->ExecuteCommandWithDisposition(IDC_BACK, CURRENT_TAB); } void forwardButtonClicked() { toolbar_->browser()->ExecuteCommandWithDisposition(IDC_FORWARD, CURRENT_TAB); } // back/forward/back-forward button is tapped void bfButtonTapped() { toolbar_->bfButtonTapped(); } // back/forward/back-forward button is tapped and held void bfButtonTappedAndHeld() { toolbar_->bfButtonTappedAndHeld(); } void reloadButtonClicked() { // toolbar_->browser()->ExecuteCommandWithDisposition(IDC_RELOAD, CURRENT_TAB); toolbar_->ReloadButtonClicked(); } void starButtonClicked() { toolbar_->browser()->ExecuteCommandWithDisposition(IDC_BOOKMARK_PAGE, CURRENT_TAB); } void UpdateStarButton(bool is_starred) { emit updateStarButton(is_starred); } void ShowStarButton(bool show) { emit showStarButton(show); } void refreshBfButton(int kind, bool active) { emit updateBfButton(kind, active); } void showHistory( int count) { emit showHistoryStack(count); } void goButtonClicked() { toolbar_->window()->GetLocationBar()->AcceptInput(); } void UpdateReloadButton(bool is_loading) { emit updateReloadButton(is_loading); } public: void enableEvents() { // enable toolbar emit enabled(); } Q_SIGNALS: // update SatButton void updateStarButton(bool is_starred); void showStarButton(bool show); // update backward, forward, back-forward buttons void updateBfButton(int kind, bool active); // update reload/stop button void updateReloadButton(bool is_loading); void showHistoryStack(int count); void enabled(); private: BrowserToolbarQt* toolbar_; }; BrowserToolbarQt::BrowserToolbarQt(Browser* browser, BrowserWindowQt* window): location_bar_(new LocationBarViewQt(browser, window)), wrench_menu_model_(this, browser), back_forward_(this, browser, window), browser_(browser), window_(window), tab_sidebar_(new TabListQt(browser, window)) { browser_->command_updater()->AddCommandObserver(IDC_BACK, this); browser_->command_updater()->AddCommandObserver(IDC_FORWARD, this); browser_->command_updater()->AddCommandObserver(IDC_HOME, this); browser_->command_updater()->AddCommandObserver(IDC_BOOKMARK_PAGE, this); impl_ = new BrowserToolbarQtImpl(this); QDeclarativeView* view = window->DeclarativeView(); QDeclarativeContext *context = view->rootContext(); context->setContextProperty("browserToolbarModel", impl_); } BrowserToolbarQt::~BrowserToolbarQt() { delete impl_; delete tab_sidebar_; } void BrowserToolbarQt::Init(Profile* profile) { // Make sure to tell the location bar the profile before calling its Init. SetProfile(profile); location_bar_->Init(false); } void BrowserToolbarQt::enableEvents() { impl_->enableEvents(); } void BrowserToolbarQt::ShowWrenchMenu() { TabStripModel* model = browser_->tabstrip_model(); browser_->command_updater()->UpdateCommandEnabled(IDC_NEW_TAB, !model->IsReachTabsLimit()); gfx::Point p; window_->ShowContextMenu(&wrench_menu_model_, p); } void BrowserToolbarQt::UpdateTabContents(TabContents* contents, bool should_restore_state) { location_bar_->Update(contents); } void BrowserToolbarQt::TabSideBarToggle() { if (tab_sidebar_->isVisible() ) { tab_sidebar_->Hide(); } else { tab_sidebar_->Show(); } } LocationBar* BrowserToolbarQt::GetLocationBar() const { return location_bar_.get(); } bool BrowserToolbarQt::GetAcceleratorForCommandId( int id, ui::Accelerator* accelerator) { return false; } //// CommandUpdater::CommandObserver --------------------------------------------- // void BrowserToolbarQt::EnabledStateChangedForCommand(int id, bool enabled) { switch (id) { case IDC_BACK: case IDC_FORWARD: back_forward_.updateStatus(); break; case IDC_HOME: break; } DNOTIMPLEMENTED(); } void BrowserToolbarQt::SetProfile(Profile* profile) { if (profile == profile_) return; profile_ = profile; location_bar_->SetProfile(profile); } void BrowserToolbarQt::SetStarred(bool is_starred) { if (browser_->GetSelectedTabContents()->GetURL()==GURL(chrome::kChromeUINewTabURL)) { impl_->ShowStarButton(false); } else { impl_->ShowStarButton(true); } impl_->UpdateStarButton(is_starred); } void BrowserToolbarQt::bfButtonTapped() { back_forward_.tap(); } void BrowserToolbarQt::bfButtonTappedAndHeld() { back_forward_.tapAndHold(); } void BrowserToolbarQt::updateBfButton(int kind, bool active) { impl_->refreshBfButton(kind, active); } void BrowserToolbarQt::showHistory(int count) { impl_->showHistory(count); } void BrowserToolbarQt::UpdateReloadStopState(bool is_loading, bool force) { _is_loading = is_loading; impl_->UpdateReloadButton(is_loading); } void BrowserToolbarQt::ReloadButtonClicked() { if (_is_loading) { browser_->Stop(); _is_loading = false; impl_->UpdateReloadButton(false); } else browser_->ExecuteCommandWithDisposition(IDC_RELOAD, CURRENT_TAB); } void BrowserToolbarQt::UpdateTitle() { location_bar_->UpdateTitle(); } #include "moc_browser_toolbar_qt.cc"
23.82
93
0.737476
meego-tablet-ux
13049abd6de0ff146e5cb53fc3e3ef511415faa8
7,923
cpp
C++
kquotedprintable.cpp
ridgeware/dekaf2
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
[ "MIT" ]
null
null
null
kquotedprintable.cpp
ridgeware/dekaf2
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
[ "MIT" ]
null
null
null
kquotedprintable.cpp
ridgeware/dekaf2
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
[ "MIT" ]
1
2021-08-20T16:15:01.000Z
2021-08-20T16:15:01.000Z
/* // // DEKAF(tm): Lighter, Faster, Smarter(tm) // // Copyright (c) 2017, Ridgeware, Inc. // // +-------------------------------------------------------------------------+ // | /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\| // |/+---------------------------------------------------------------------+/| // |/| |/| // |\| ** THIS NOTICE MUST NOT BE REMOVED FROM THE SOURCE CODE MODULE ** |\| // |/| |/| // |\| OPEN SOURCE LICENSE |\| // |/| |/| // |\| Permission is hereby granted, free of charge, to any person |\| // |/| obtaining a copy of this software and associated |/| // |\| documentation files (the "Software"), to deal in the |\| // |/| Software without restriction, including without limitation |/| // |\| the rights to use, copy, modify, merge, publish, |\| // |/| distribute, sublicense, and/or sell copies of the Software, |/| // |\| and to permit persons to whom the Software is furnished to |\| // |/| do so, subject to the following conditions: |/| // |\| |\| // |/| The above copyright notice and this permission notice shall |/| // |\| be included in all copies or substantial portions of the |\| // |/| Software. |/| // |\| |\| // |/| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY |/| // |\| KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE |\| // |/| WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR |/| // |\| PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS |\| // |/| OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR |/| // |\| OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR |\| // |/| OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |/| // |\| SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |\| // |/| |/| // |/+---------------------------------------------------------------------+/| // |\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ | // +-------------------------------------------------------------------------+ // */ #include "kquotedprintable.h" #include "kstringutils.h" #include "klog.h" #include <cctype> namespace dekaf2 { constexpr char sxDigit[] = "0123456789ABCDEF"; enum ETYPE : uint8_t { NO, // no, do not encode YY, // yes, encode LF, // linefeed SL, // encode if at start of line MH // encode if used in mail headers }; constexpr ETYPE sEncodeCodepoints[256] = { // 0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 0xA 0xB 0xC 0xD 0xE 0xF YY, YY, YY, YY, YY, YY, YY, YY, YY, MH, LF, YY, YY, LF, YY, YY, // 0x00 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0x10 MH, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, SL, NO, // 0x20 NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, YY, NO, MH, // 0x30 NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, // 0x40 NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, MH, // 0x50 NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, // 0x60 NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, YY, YY, // 0x70 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0x80 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0x90 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0xA0 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0xB0 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0xC0 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0xD0 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0xE0 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0xF0 }; //----------------------------------------------------------------------------- KString KQuotedPrintable::Encode(KStringView sInput, bool bForMailHeaders) //----------------------------------------------------------------------------- { KString out; out.reserve(sInput.size()); uint16_t iLineLen { 0 }; uint16_t iMaxLineLen { 75 }; if (bForMailHeaders) { out += "=?UTF-8?Q?"; // we already add the 2 chars we need to close the encoding, and reserve 15 // chars for the 'Header: ' iMaxLineLen = 75 - (10 + 2 + 15); } for (auto byte : sInput) { if (iLineLen >= iMaxLineLen) { if (bForMailHeaders) { out += "?=\r\n "; out += "=?UTF-8?Q?"; iMaxLineLen = 75 - (1 + 10 + 2); } else { out += "=\r\n"; iMaxLineLen = 75 - 1; } iLineLen = 0; } switch (sEncodeCodepoints[static_cast<uint8_t>(byte)]) { case NO: // do not encode out += byte; ++iLineLen; continue; case SL: // encode if at start of line if (iLineLen > 0) { out += byte; ++iLineLen; continue; } // yes, encode break; case LF: // copy, reset line counter out += byte; iLineLen = 0; continue; case MH: // encode if in mail headers if (!bForMailHeaders) { out += byte; ++iLineLen; continue; } // yes, encode break; case YY: // yes, encode break; } out += '='; out += sxDigit[(byte >> 4) & 0x0f]; out += sxDigit[(byte ) & 0x0f]; iLineLen += 3; } if (bForMailHeaders) { out += "?="; } return out; } // Encode //----------------------------------------------------------------------------- void FlushRaw(KString& out, uint16_t iDecode, KString::value_type LeadChar, KString::value_type ch = 'f') //----------------------------------------------------------------------------- { out += '='; if (iDecode == 1) { out += LeadChar; } // 'f' signals that the input starved, as 'f' is a valid xdigit if (ch != 'f') { out += ch; } } // FlushRaw //----------------------------------------------------------------------------- KString KQuotedPrintable::Decode(KStringView sInput, bool bDotStuffing) //----------------------------------------------------------------------------- { KString out; out.reserve(sInput.size()); KString::value_type LeadChar { 0 }; uint16_t iDecode { 0 }; bool bStartOfLine { true }; for (auto ch : sInput) { if (iDecode) { if (iDecode == 2 && (ch == '\r' || ch == '\n')) { bStartOfLine = true; if (ch == '\n') { iDecode = 0; } } else if (!KASCII::kIsXDigit(ch)) { if (ch == '\r' || ch == '\n') { bStartOfLine = true; } else { kDebug(2, "illegal encoding, flushing raw"); FlushRaw(out, iDecode, LeadChar, ch); } iDecode = 0; } else if (--iDecode == 1) { LeadChar = ch; } else { uint16_t iValue = kFromBase36(LeadChar) << 4; iValue += kFromBase36(ch); out += static_cast<KString::value_type>(iValue); } } else { switch (ch) { case '\r': case '\n': bStartOfLine = true; out += ch; break; case '=': bStartOfLine = false; iDecode = 2; break; default: if (bStartOfLine) { bStartOfLine = false; if (bDotStuffing && ch == '.') { break; } } out += ch; break; } } } if (iDecode) { kDebug(2, "QuotedPrintable decoding ended prematurely, flushing raw"); FlushRaw(out, iDecode, LeadChar); } return out; } // Decode } // end of namespace dekaf2
28.296429
105
0.441247
ridgeware
1305140acf354adfd6937fa2a62fd7e80801d0da
4,817
cpp
C++
Development/Plugin/Warcraft3/yd_lua_engine/lua_engine/common.cpp
alanoooaao/YDWE
fa9c6dc24d01f78919b5c8b2c69252291536424a
[ "Apache-2.0" ]
2
2021-05-21T11:18:30.000Z
2021-05-24T14:44:34.000Z
Development/Plugin/Warcraft3/yd_lua_engine/lua_engine/common.cpp
alanoooaao/YDWE
fa9c6dc24d01f78919b5c8b2c69252291536424a
[ "Apache-2.0" ]
null
null
null
Development/Plugin/Warcraft3/yd_lua_engine/lua_engine/common.cpp
alanoooaao/YDWE
fa9c6dc24d01f78919b5c8b2c69252291536424a
[ "Apache-2.0" ]
null
null
null
#include "common.h" #include "jassbind.h" #include "class_handle.h" #include "class_array.h" #include "libs_runtime.h" #include <base/warcraft3/hashtable.h> #include <base/warcraft3/war3_searcher.h> #include <base/warcraft3/jass.h> #include <base/warcraft3/jass/trampoline_function.h> #include <base/util/singleton.h> namespace base { namespace warcraft3 { namespace lua_engine { bool is_gaming() { return 0 != get_jass_vm(); } bool jass_push(lua_State* L, jass::variable_type vt, uint32_t value) { switch (vt) { case jass::TYPE_NOTHING: return false; case jass::TYPE_BOOLEAN: jassbind::push_boolean(L, value); return true; case jass::TYPE_CODE: jassbind::push_code(L, value); return true; case jass::TYPE_HANDLE: jassbind::push_handle(L, value); return true; case jass::TYPE_INTEGER: jassbind::push_integer(L, value); return true; case jass::TYPE_REAL: jassbind::push_real(L, value); return true; case jass::TYPE_STRING: jassbind::push_string(L, value); return true; default: assert(false); return false; } } uintptr_t jass_read(lua_State* L, jass::variable_type opt, int idx) { switch (opt) { case jass::TYPE_NOTHING: return 0; case jass::TYPE_CODE: return jassbind::read_code(L, idx); case jass::TYPE_INTEGER: return jassbind::read_integer(L, idx); case jass::TYPE_REAL: return jassbind::read_real(L, idx); case jass::TYPE_STRING: return jassbind::read_string(L, idx); case jass::TYPE_HANDLE: return jassbind::read_handle(L, idx); case jass::TYPE_BOOLEAN: return jassbind::read_boolean(L, idx); default: assert(false); return 0; } } static const char* jass_function_name(uintptr_t func_address) { for (auto it = jass::jass_function.begin(); it != jass::jass_function.end(); ++it) { if (func_address == it->second.get_address()) { return it->first.c_str(); } } return 0; } uintptr_t safe_jass_call(lua_State* L, uintptr_t func_address, const uintptr_t* param_list, size_t param_list_size) { __try { return jass::call(func_address, param_list, param_list_size); } __except (EXCEPTION_EXECUTE_HANDLER){ const char* name = jass_function_name(func_address); if (!name) { name = "unknown"; } return luaL_error(L, "Call jass function crash.<%s>", name); } return 0; } int jass_call_native_function(lua_State* L, const jass::func_value* nf, uintptr_t func_address) { LUA_PERFTRACE(kJassCall); if (!lua_isyieldable(L) && nf->has_sleep()) { printf("Wanring: %s is disable.\n", lua_tostring(L, lua_upvalueindex(1))); lua_pushnil(L); return 1; } size_t param_size = nf->get_param().size(); if ((int)param_size > lua_gettop(L)) { lua_pushnil(L); return 1; } jass::call_param param(param_size); for (size_t i = 0; i < param_size; ++i) { jass::variable_type vt = nf->get_param()[i]; switch (vt) { case jass::TYPE_BOOLEAN: param.push(i, jassbind::read_boolean(L, i + 1)); break; case jass::TYPE_CODE: param.push(i, jassbind::read_code(L, i + 1)); break; case jass::TYPE_HANDLE: param.push(i, jassbind::read_handle(L, i + 1)); break; case jass::TYPE_INTEGER: param.push(i, jassbind::read_integer(L, i + 1)); break; case jass::TYPE_REAL: param.push_real(i, jassbind::read_real(L, i + 1)); break; case jass::TYPE_STRING: param.push(i, lua_tostring(L, i + 1)); break; default: param.push(i, 0); break; } } if (func_address == 0) func_address = nf->get_address(); uintptr_t retval = 0; if (runtime::catch_crash) { retval = safe_jass_call(L, func_address, param.data(), param_size); } else { retval = jass::call(func_address, param.data(), param_size); } if (nf->get_return() == jass::TYPE_STRING) { retval = get_jass_vm()->string_table->get(retval); } return jass_push(L, nf->get_return(), retval) ? 1 : 0; } int jass_call_closure(lua_State* L) { if (!is_gaming()) { lua_pushnil(L); return 1; } int result = jass_call_native_function(L, (const jass::func_value*)lua_tointeger(L, lua_upvalueindex(1))); if (lua_isyieldable(L)) { uintptr_t thread = get_jass_thread(); if (thread && *(uintptr_t*)(thread + 0x34)) { *(uintptr_t*)(thread + 0x20) -= jass::trampoline_size(); return lua_yield(L, 0); } } return result; } lua_State* get_mainthread(lua_State* thread) { lua_rawgeti(thread, LUA_REGISTRYINDEX, LUA_RIDX_MAINTHREAD); lua_State* ml = lua_tothread(thread, - 1); lua_pop(thread, 1); return ml; } }}}
24.085
117
0.637119
alanoooaao
130656ebfd5782d237a2f086194f4ea64f042312
1,994
hpp
C++
Modules-old/freenect2/libfreenect2/frame_listener.hpp
ToyotaResearchInstitute/rad-robot
9a47e4d88382719ab9bf142932fbcc83dcbcd665
[ "MIT" ]
null
null
null
Modules-old/freenect2/libfreenect2/frame_listener.hpp
ToyotaResearchInstitute/rad-robot
9a47e4d88382719ab9bf142932fbcc83dcbcd665
[ "MIT" ]
null
null
null
Modules-old/freenect2/libfreenect2/frame_listener.hpp
ToyotaResearchInstitute/rad-robot
9a47e4d88382719ab9bf142932fbcc83dcbcd665
[ "MIT" ]
2
2018-06-04T12:38:54.000Z
2018-09-22T10:31:27.000Z
/* * This file is part of the OpenKinect Project. http://www.openkinect.org * * Copyright (c) 2014 individual OpenKinect contributors. See the CONTRIB file * for details. * * This code is licensed to you under the terms of the Apache License, version * 2.0, or, at your option, the terms of the GNU General Public License, * version 2.0. See the APACHE20 and GPL2 files for the text of the licenses, * or the following URLs: * http://www.apache.org/licenses/LICENSE-2.0 * http://www.gnu.org/licenses/gpl-2.0.txt * * If you redistribute this file in source form, modified or unmodified, you * may: * 1) Leave this header intact and distribute it under the same terms, * accompanying it with the APACHE20 and GPL20 files, or * 2) Delete the Apache 2.0 clause and accompany it with the GPL2 file, or * 3) Delete the GPL v2 clause and accompany it with the APACHE20 file * In all cases you must keep the copyright notice intact and include a copy * of the CONTRIB file. * * Binary distributions must follow the binary distribution requirements of * either License. */ #ifndef FRAME_LISTENER_HPP_ #define FRAME_LISTENER_HPP_ #include <map> namespace libfreenect2 { struct Frame { enum Type { Color = 1, Ir = 2, Depth = 4 }; size_t width, height, bytes_per_pixel; unsigned char* data; Frame(size_t width, size_t height, size_t bytes_per_pixel) : width(width), height(height), bytes_per_pixel(bytes_per_pixel) { data = new unsigned char[width * height * bytes_per_pixel]; } ~Frame() { delete[] data; } }; typedef std::map<Frame::Type, Frame*> FrameMap; class FrameListener { public: virtual ~FrameListener(); virtual bool onNewFrame(Frame::Type type, Frame *frame) = 0; virtual void waitForNewFrame(FrameMap &frame) = 0; virtual void release(FrameMap &frame) = 0; static FrameListener* create(unsigned int frame_types); }; } /* namespace libfreenect2 */ #endif /* FRAME_LISTENER_HPP_ */
24.925
78
0.709629
ToyotaResearchInstitute
130db2d01bcc433a4136d339f02a47b3bf3c8c89
5,423
cc
C++
components/policy/core/browser/configuration_policy_pref_store.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/policy/core/browser/configuration_policy_pref_store.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/policy/core/browser/configuration_policy_pref_store.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright (c) 2012 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 "components/policy/core/browser/configuration_policy_pref_store.h" #include <string> #include <vector> #include "base/bind.h" #include "base/location.h" #include "base/logging.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "components/policy/core/browser/browser_policy_connector_base.h" #include "components/policy/core/browser/configuration_policy_handler_list.h" #include "components/policy/core/browser/policy_conversions_client.h" #include "components/policy/core/browser/policy_error_map.h" #include "components/prefs/pref_value_map.h" #include "components/strings/grit/components_strings.h" #include "ui/base/l10n/l10n_util.h" namespace policy { namespace { void LogErrors(std::unique_ptr<PolicyErrorMap> errors, PoliciesSet deprecated_policies, PoliciesSet future_policies) { DCHECK(errors->IsReady()); for (auto& pair : *errors) { base::string16 policy = base::ASCIIToUTF16(pair.first); DLOG(WARNING) << "Policy " << policy << ": " << pair.second; } for (const auto& policy : deprecated_policies) { DLOG(WARNING) << "Policy " << policy << " has been deprecated."; } for (const auto& policy : future_policies) { DLOG(WARNING) << "Policy " << policy << " has not been released yet."; } } bool IsLevel(PolicyLevel level, const PolicyMap::const_iterator iter) { return iter->second.level == level; } } // namespace ConfigurationPolicyPrefStore::ConfigurationPolicyPrefStore( BrowserPolicyConnectorBase* policy_connector, PolicyService* service, const ConfigurationPolicyHandlerList* handler_list, PolicyLevel level) : policy_connector_(policy_connector), policy_service_(service), handler_list_(handler_list), level_(level) { // Read initial policy. prefs_.reset(CreatePreferencesFromPolicies()); policy_service_->AddObserver(POLICY_DOMAIN_CHROME, this); } void ConfigurationPolicyPrefStore::AddObserver(PrefStore::Observer* observer) { observers_.AddObserver(observer); } void ConfigurationPolicyPrefStore::RemoveObserver( PrefStore::Observer* observer) { observers_.RemoveObserver(observer); } bool ConfigurationPolicyPrefStore::HasObservers() const { return observers_.might_have_observers(); } bool ConfigurationPolicyPrefStore::IsInitializationComplete() const { return policy_service_->IsInitializationComplete(POLICY_DOMAIN_CHROME); } bool ConfigurationPolicyPrefStore::GetValue(const std::string& key, const base::Value** value) const { const base::Value* stored_value = nullptr; if (!prefs_ || !prefs_->GetValue(key, &stored_value)) return false; if (value) *value = stored_value; return true; } std::unique_ptr<base::DictionaryValue> ConfigurationPolicyPrefStore::GetValues() const { if (!prefs_) return std::make_unique<base::DictionaryValue>(); return prefs_->AsDictionaryValue(); } void ConfigurationPolicyPrefStore::OnPolicyUpdated( const PolicyNamespace& ns, const PolicyMap& previous, const PolicyMap& current) { DCHECK_EQ(POLICY_DOMAIN_CHROME, ns.domain); DCHECK(ns.component_id.empty()); Refresh(); } void ConfigurationPolicyPrefStore::OnPolicyServiceInitialized( PolicyDomain domain) { if (domain == POLICY_DOMAIN_CHROME) { for (auto& observer : observers_) observer.OnInitializationCompleted(true); } } ConfigurationPolicyPrefStore::~ConfigurationPolicyPrefStore() { policy_service_->RemoveObserver(POLICY_DOMAIN_CHROME, this); } void ConfigurationPolicyPrefStore::Refresh() { std::unique_ptr<PrefValueMap> new_prefs(CreatePreferencesFromPolicies()); std::vector<std::string> changed_prefs; new_prefs->GetDifferingKeys(prefs_.get(), &changed_prefs); prefs_.swap(new_prefs); // Send out change notifications. for (std::vector<std::string>::const_iterator pref(changed_prefs.begin()); pref != changed_prefs.end(); ++pref) { for (auto& observer : observers_) observer.OnPrefValueChanged(*pref); } } PrefValueMap* ConfigurationPolicyPrefStore::CreatePreferencesFromPolicies() { std::unique_ptr<PrefValueMap> prefs(new PrefValueMap); PolicyMap filtered_policies; filtered_policies.CopyFrom(policy_service_->GetPolicies( PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))); filtered_policies.EraseNonmatching(base::BindRepeating(&IsLevel, level_)); std::unique_ptr<PolicyErrorMap> errors = std::make_unique<PolicyErrorMap>(); PoliciesSet deprecated_policies; PoliciesSet future_policies; handler_list_->ApplyPolicySettings(filtered_policies, prefs.get(), errors.get(), &deprecated_policies, &future_policies); if (!errors->empty()) { if (errors->IsReady()) { LogErrors(std::move(errors), std::move(deprecated_policies), std::move(future_policies)); } else if (policy_connector_) { // May be null in tests. policy_connector_->NotifyWhenResourceBundleReady(base::BindOnce( &LogErrors, std::move(errors), std::move(deprecated_policies), std::move(future_policies))); } } return prefs.release(); } } // namespace policy
33.067073
80
0.727826
mghgroup
130dbe195be31dbd01aecfe588348a9bdb32a587
4,401
hpp
C++
ROLE/hls/udp_shell_if/test/simu_udp_shell_if_env.hpp
cloudFPGA/cFp_HelloKale
949f8c3005d2824b8bc65345b77ea97bd0b6e692
[ "Apache-2.0" ]
null
null
null
ROLE/hls/udp_shell_if/test/simu_udp_shell_if_env.hpp
cloudFPGA/cFp_HelloKale
949f8c3005d2824b8bc65345b77ea97bd0b6e692
[ "Apache-2.0" ]
6
2022-01-22T10:04:18.000Z
2022-02-01T21:28:19.000Z
ROLE/hls/udp_shell_if/test/simu_udp_shell_if_env.hpp
cloudFPGA/cFp_HelloKale
949f8c3005d2824b8bc65345b77ea97bd0b6e692
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2016 -- 2021 IBM 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. */ /******************************************************************************* * @file : simu_udp_shell_if_env.hpp * @brief : Simulation environment for the UDP Shell Interface (USIF). * * System: : cloudFPGA * Component : cFp_HelloKale/ROLE/UdpShellInterface (USIF) * Language : Vivado HLS * * \ingroup udp_shell_if * \addtogroup udp_shell_if * \{ *******************************************************************************/ #ifndef _SIMU_USIF_H_ #define _SIMU_USIF_H_ #include <cstdlib> #include <hls_stream.h> #include <iostream> #include "../src/udp_shell_if.hpp" #include "../../../../cFDK/SRA/LIB/SHELL/LIB/hls/NTS/SimNtsUtils.hpp" //------------------------------------------------------ //-- TESTBENCH DEFINITIONS //------------------------------------------------------ const int cUoeInitCycles = 100; // FYI - It takes 0xFFFF cycles to initialize UOE. const int cGraceTime = 500; // Give the TB some time to finish //--------------------------------------------------------- //-- DEFAULT LOCAL FPGA AND FOREIGN HOST SOCKETS //-- By default, the following sockets will be used by the //-- testbench, unless the user specifies new ones via one //-- of the test vector files. //--------------------------------------------------------- #define DEFAULT_FPGA_IP4_ADDR 0x0A0CC801 // FPGA's local IP Address = 10.12.200.01 #define DEFAULT_FPGA_LSN_PORT 0x2263 // UDP-ROLE listens on port = 8803 #define DEFAULT_FPGA_SND_PORT 0xA263 // UDP-ROLE sends on port = 41571 #define DEFAULT_HOST_IP4_ADDR 0x0A0CC832 // HOST's foreign IP Address = 10.12.200.50 #define DEFAULT_HOST_LSN_PORT 0x80 // HOST listens on port = 128 #define DEFAULT_HOST_SND_PORT 0x8080 // HOST sends on port = 32896 #define DEFAULT_DATAGRAM_LEN 32 /******************************************************************************* * SIMULATION UTILITY HELPERS ********************************************************************************/ void stepSim(); void increaseSimTime(unsigned int cycles); /****************************************************************************** * SIMULATION ENVIRONMENT FUNCTIONS *******************************************************************************/ void pUAF( //-- USIF / Rx Data Interface stream<UdpAppData> &siUSIF_Data, stream<UdpAppMeta> &siUSIF_Meta, //-- USIF / Tx Data Interface stream<UdpAppData> &soUSIF_Data, stream<UdpAppMeta> &soUSIF_Meta, stream<UdpAppDLen> &soUSIF_DLen); void pMMIO( //-- SHELL / Ready Signal StsBit *piSHL_Ready, //-- MMIO / Enable Layer-7 (.i.e APP alias ROLE) CmdBit *poUSIF_Enable); void pUOE( int &nrErr, ofstream &dataGoldFile, ofstream &dataFile, ofstream &metaGoldFile, ofstream &metaFile, int echoDgrmLen, SockAddr testSock, int testDgrmLen, //-- MMIO / Ready Signal StsBit *poMMIO_Ready, //-- UOE->USIF / UDP Rx Data Interfaces stream<UdpAppData> &soUSIF_Data, stream<UdpAppMeta> &soUSIF_Meta, stream<UdpAppDLen> &soUSIF_DLen, //-- USIF->UOE / UDP Tx Data Interfaces stream<UdpAppData> &siUSIF_Data, stream<UdpAppMeta> &siUSIF_Meta, stream<UdpAppDLen> &siUSIF_DLen, //-- USIF<->UOE / Listen Interfaces stream<UdpPort> &siUSIF_LsnReq, stream<StsBool> &soUSIF_LsnRep, //-- USIF<->UOE / Close Interfaces stream<UdpPort> &siUSIF_ClsReq); #endif /*! \} */
36.983193
87
0.52988
cloudFPGA
130e5e20b9a66a6dcb2494ab4d26aa45b505a623
17
cpp
C++
Directory_Operation_Scripts/Mixed/E.cpp
PRASAD-DANGARE/Python_Automation
178e9728c41aa8ea12c91981152f9a86b9c060ca
[ "MIT" ]
1
2021-07-23T09:44:43.000Z
2021-07-23T09:44:43.000Z
Directory_Operation_Scripts/Mixed/E.cpp
PRASAD-DANGARE/Python_Automation
178e9728c41aa8ea12c91981152f9a86b9c060ca
[ "MIT" ]
null
null
null
Directory_Operation_Scripts/Mixed/E.cpp
PRASAD-DANGARE/Python_Automation
178e9728c41aa8ea12c91981152f9a86b9c060ca
[ "MIT" ]
null
null
null
cout << "Hello";
8.5
16
0.529412
PRASAD-DANGARE
131225564493d521c005ae83f0b3a9a1ebd1edb1
96,834
cpp
C++
src/services/pcn-bridge/src/api/BridgeApi.cpp
mbertrone/polycube
b35a6aa13273c000237d53c5f1bf286f12e4b9bd
[ "ECL-2.0", "Apache-2.0" ]
1
2020-07-16T04:49:29.000Z
2020-07-16T04:49:29.000Z
src/services/pcn-bridge/src/api/BridgeApi.cpp
mbertrone/polycube
b35a6aa13273c000237d53c5f1bf286f12e4b9bd
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/services/pcn-bridge/src/api/BridgeApi.cpp
mbertrone/polycube
b35a6aa13273c000237d53c5f1bf286f12e4b9bd
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/** * bridge API * bridge API generated from bridge.yang * * OpenAPI spec version: 1.0.0 * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git */ /* Do not edit this file manually */ #include "BridgeApi.h" namespace io { namespace swagger { namespace server { namespace api { using namespace io::swagger::server::model; BridgeApi::BridgeApi() { setupRoutes(); }; void BridgeApi::control_handler(const HttpHandleRequest &request, HttpHandleResponse &response) { try { auto s = router.route(request, response); if (s == Rest::Router::Status::NotFound) { response.send(Http::Code::Not_Found); } } catch (std::runtime_error &e) { response.send(polycube::service::Http::Code::Bad_Request, e.what()); } } void BridgeApi::setupRoutes() { using namespace polycube::service::Rest; Routes::Post(router, base + "/bridge/:name/", Routes::bind(&BridgeApi::create_bridge_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/", Routes::bind(&BridgeApi::create_bridge_filteringdatabase_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/filteringdatabase/", Routes::bind(&BridgeApi::create_bridge_filteringdatabase_list_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/access/", Routes::bind(&BridgeApi::create_bridge_ports_access_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/", Routes::bind(&BridgeApi::create_bridge_ports_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/", Routes::bind(&BridgeApi::create_bridge_ports_list_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/", Routes::bind(&BridgeApi::create_bridge_ports_stp_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/stp/", Routes::bind(&BridgeApi::create_bridge_ports_stp_list_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/:vlanid/", Routes::bind(&BridgeApi::create_bridge_ports_trunk_allowed_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/", Routes::bind(&BridgeApi::create_bridge_ports_trunk_allowed_list_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/trunk/", Routes::bind(&BridgeApi::create_bridge_ports_trunk_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/stp/:vlan/", Routes::bind(&BridgeApi::create_bridge_stp_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/stp/", Routes::bind(&BridgeApi::create_bridge_stp_list_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/", Routes::bind(&BridgeApi::delete_bridge_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/", Routes::bind(&BridgeApi::delete_bridge_filteringdatabase_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/filteringdatabase/", Routes::bind(&BridgeApi::delete_bridge_filteringdatabase_list_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/access/", Routes::bind(&BridgeApi::delete_bridge_ports_access_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/", Routes::bind(&BridgeApi::delete_bridge_ports_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/", Routes::bind(&BridgeApi::delete_bridge_ports_list_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/", Routes::bind(&BridgeApi::delete_bridge_ports_stp_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/stp/", Routes::bind(&BridgeApi::delete_bridge_ports_stp_list_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/:vlanid/", Routes::bind(&BridgeApi::delete_bridge_ports_trunk_allowed_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/", Routes::bind(&BridgeApi::delete_bridge_ports_trunk_allowed_list_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/trunk/", Routes::bind(&BridgeApi::delete_bridge_ports_trunk_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/stp/:vlan/", Routes::bind(&BridgeApi::delete_bridge_stp_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/stp/", Routes::bind(&BridgeApi::delete_bridge_stp_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/agingtime/", Routes::bind(&BridgeApi::read_bridge_agingtime_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/", Routes::bind(&BridgeApi::read_bridge_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/age/", Routes::bind(&BridgeApi::read_bridge_filteringdatabase_age_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/", Routes::bind(&BridgeApi::read_bridge_filteringdatabase_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/entrytype/", Routes::bind(&BridgeApi::read_bridge_filteringdatabase_entrytype_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/filteringdatabase/", Routes::bind(&BridgeApi::read_bridge_filteringdatabase_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/port/", Routes::bind(&BridgeApi::read_bridge_filteringdatabase_port_by_id_handler, this)); Routes::Get(router, base + "/bridge/", Routes::bind(&BridgeApi::read_bridge_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/access/", Routes::bind(&BridgeApi::read_bridge_ports_access_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/access/vlanid/", Routes::bind(&BridgeApi::read_bridge_ports_access_vlanid_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/address/", Routes::bind(&BridgeApi::read_bridge_ports_address_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/", Routes::bind(&BridgeApi::read_bridge_ports_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/", Routes::bind(&BridgeApi::read_bridge_ports_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/mode/", Routes::bind(&BridgeApi::read_bridge_ports_mode_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/peer/", Routes::bind(&BridgeApi::read_bridge_ports_peer_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/status/", Routes::bind(&BridgeApi::read_bridge_ports_status_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/", Routes::bind(&BridgeApi::read_bridge_ports_stp_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/stp/", Routes::bind(&BridgeApi::read_bridge_ports_stp_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/pathcost/", Routes::bind(&BridgeApi::read_bridge_ports_stp_pathcost_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/portpriority/", Routes::bind(&BridgeApi::read_bridge_ports_stp_portpriority_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/state/", Routes::bind(&BridgeApi::read_bridge_ports_stp_state_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/:vlanid/", Routes::bind(&BridgeApi::read_bridge_ports_trunk_allowed_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/", Routes::bind(&BridgeApi::read_bridge_ports_trunk_allowed_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/trunk/", Routes::bind(&BridgeApi::read_bridge_ports_trunk_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/trunk/nativevlan/", Routes::bind(&BridgeApi::read_bridge_ports_trunk_nativevlan_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/uuid/", Routes::bind(&BridgeApi::read_bridge_ports_uuid_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/:vlan/address/", Routes::bind(&BridgeApi::read_bridge_stp_address_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/:vlan/", Routes::bind(&BridgeApi::read_bridge_stp_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/:vlan/forwarddelay/", Routes::bind(&BridgeApi::read_bridge_stp_forwarddelay_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/:vlan/hellotime/", Routes::bind(&BridgeApi::read_bridge_stp_hellotime_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/", Routes::bind(&BridgeApi::read_bridge_stp_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/:vlan/maxmessageage/", Routes::bind(&BridgeApi::read_bridge_stp_maxmessageage_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/:vlan/priority/", Routes::bind(&BridgeApi::read_bridge_stp_priority_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stpenabled/", Routes::bind(&BridgeApi::read_bridge_stpenabled_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/uuid/", Routes::bind(&BridgeApi::read_bridge_uuid_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/type/", Routes::bind(&BridgeApi::read_bridge_type_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/agingtime/", Routes::bind(&BridgeApi::update_bridge_agingtime_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/", Routes::bind(&BridgeApi::update_bridge_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/", Routes::bind(&BridgeApi::update_bridge_filteringdatabase_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/entrytype/", Routes::bind(&BridgeApi::update_bridge_filteringdatabase_entrytype_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/filteringdatabase/", Routes::bind(&BridgeApi::update_bridge_filteringdatabase_list_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/port/", Routes::bind(&BridgeApi::update_bridge_filteringdatabase_port_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/access/", Routes::bind(&BridgeApi::update_bridge_ports_access_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/access/vlanid/", Routes::bind(&BridgeApi::update_bridge_ports_access_vlanid_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/address/", Routes::bind(&BridgeApi::update_bridge_ports_address_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/", Routes::bind(&BridgeApi::update_bridge_ports_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/", Routes::bind(&BridgeApi::update_bridge_ports_list_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/mode/", Routes::bind(&BridgeApi::update_bridge_ports_mode_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/peer/", Routes::bind(&BridgeApi::update_bridge_ports_peer_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/status/", Routes::bind(&BridgeApi::update_bridge_ports_status_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/", Routes::bind(&BridgeApi::update_bridge_ports_stp_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/stp/", Routes::bind(&BridgeApi::update_bridge_ports_stp_list_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/pathcost/", Routes::bind(&BridgeApi::update_bridge_ports_stp_pathcost_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/portpriority/", Routes::bind(&BridgeApi::update_bridge_ports_stp_portpriority_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/:vlanid/", Routes::bind(&BridgeApi::update_bridge_ports_trunk_allowed_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/", Routes::bind(&BridgeApi::update_bridge_ports_trunk_allowed_list_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/trunk/", Routes::bind(&BridgeApi::update_bridge_ports_trunk_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/trunk/nativevlan/", Routes::bind(&BridgeApi::update_bridge_ports_trunk_nativevlan_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/:vlan/address/", Routes::bind(&BridgeApi::update_bridge_stp_address_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/:vlan/", Routes::bind(&BridgeApi::update_bridge_stp_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/:vlan/forwarddelay/", Routes::bind(&BridgeApi::update_bridge_stp_forwarddelay_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/:vlan/hellotime/", Routes::bind(&BridgeApi::update_bridge_stp_hellotime_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/", Routes::bind(&BridgeApi::update_bridge_stp_list_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/:vlan/maxmessageage/", Routes::bind(&BridgeApi::update_bridge_stp_maxmessageage_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/:vlan/priority/", Routes::bind(&BridgeApi::update_bridge_stp_priority_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stpenabled/", Routes::bind(&BridgeApi::update_bridge_stpenabled_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/type/", Routes::bind(&BridgeApi::update_bridge_type_by_id_handler, this)); } void BridgeApi::create_bridge_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param BridgeSchema bridge; nlohmann::json request_body = nlohmann::json::parse(request.body()); bridge.fromJson(request_body); auto x = create_bridge_by_id(name, bridge); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_filteringdatabase_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); // Getting the body param FilteringdatabaseSchema filteringdatabase; nlohmann::json request_body = nlohmann::json::parse(request.body()); filteringdatabase.fromJson(request_body); auto x = create_bridge_filteringdatabase_by_id(name, vlan, address, filteringdatabase); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_filteringdatabase_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<FilteringdatabaseSchema> filteringdatabase; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { FilteringdatabaseSchema a; a.fromJson(j); filteringdatabase.push_back(a); } auto x = create_bridge_filteringdatabase_list_by_id(name, filteringdatabase); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_access_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param PortsAccessSchema access; nlohmann::json request_body = nlohmann::json::parse(request.body()); access.fromJson(request_body); auto x = create_bridge_ports_access_by_id(name, portsName, access); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param PortsSchema ports; nlohmann::json request_body = nlohmann::json::parse(request.body()); ports.fromJson(request_body); auto x = create_bridge_ports_by_id(name, portsName, ports); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<PortsSchema> ports; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsSchema a; a.fromJson(j); ports.push_back(a); } auto x = create_bridge_ports_list_by_id(name, ports); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param PortsStpSchema stp; nlohmann::json request_body = nlohmann::json::parse(request.body()); stp.fromJson(request_body); auto x = create_bridge_ports_stp_by_id(name, portsName, vlan, stp); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::vector<PortsStpSchema> stp; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsStpSchema a; a.fromJson(j); stp.push_back(a); } auto x = create_bridge_ports_stp_list_by_id(name, portsName, stp); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_trunk_allowed_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlanid = request.param(":vlanid").as<std::string>(); // Getting the body param PortsTrunkAllowedSchema allowed; nlohmann::json request_body = nlohmann::json::parse(request.body()); allowed.fromJson(request_body); auto x = create_bridge_ports_trunk_allowed_by_id(name, portsName, vlanid, allowed); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_trunk_allowed_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::vector<PortsTrunkAllowedSchema> allowed; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsTrunkAllowedSchema a; a.fromJson(j); allowed.push_back(a); } auto x = create_bridge_ports_trunk_allowed_list_by_id(name, portsName, allowed); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_trunk_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param PortsTrunkSchema trunk; nlohmann::json request_body = nlohmann::json::parse(request.body()); trunk.fromJson(request_body); auto x = create_bridge_ports_trunk_by_id(name, portsName, trunk); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param StpSchema stp; nlohmann::json request_body = nlohmann::json::parse(request.body()); stp.fromJson(request_body); auto x = create_bridge_stp_by_id(name, vlan, stp); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<StpSchema> stp; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { StpSchema a; a.fromJson(j); stp.push_back(a); } auto x = create_bridge_stp_list_by_id(name, stp); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::delete_bridge_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); delete_bridge_by_id(name); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_filteringdatabase_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); delete_bridge_filteringdatabase_by_id(name, vlan, address); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_filteringdatabase_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER delete_bridge_filteringdatabase_list_by_id(name); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_access_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); delete_bridge_ports_access_by_id(name, portsName); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); delete_bridge_ports_by_id(name, portsName); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER delete_bridge_ports_list_by_id(name); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); delete_bridge_ports_stp_by_id(name, portsName, vlan); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER delete_bridge_ports_stp_list_by_id(name, portsName); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_trunk_allowed_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlanid = request.param(":vlanid").as<std::string>(); delete_bridge_ports_trunk_allowed_by_id(name, portsName, vlanid); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_trunk_allowed_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER delete_bridge_ports_trunk_allowed_list_by_id(name, portsName); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_trunk_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); delete_bridge_ports_trunk_by_id(name, portsName); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); delete_bridge_stp_by_id(name, vlan); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER delete_bridge_stp_list_by_id(name); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::read_bridge_agingtime_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto x = read_bridge_agingtime_by_id(name); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getKeys(); val["elements"] = read_bridge_by_id_get_list(); #else // element is complex val["params"] = BridgeSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getKeys(); val["elements"] = read_bridge_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = BridgeSchema::getKeys(); val["elements"] = read_bridge_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = BridgeSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_by_id(name); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_filteringdatabase_age_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); auto x = read_bridge_filteringdatabase_age_by_id(name, vlan, address); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_filteringdatabase_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getKeys(); val["elements"] = read_bridge_filteringdatabase_by_id_get_list(); #else // element is complex val["params"] = FilteringdatabaseSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getKeys(); val["elements"] = read_bridge_filteringdatabase_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = FilteringdatabaseSchema::getKeys(); val["elements"] = read_bridge_filteringdatabase_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = FilteringdatabaseSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_filteringdatabase_by_id(name, vlan, address); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_filteringdatabase_entrytype_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); auto x = read_bridge_filteringdatabase_entrytype_by_id(name, vlan, address); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_filteringdatabase_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); #define NODE_IS_LIST_CONTAINER using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getKeys(); val["elements"] = read_bridge_filteringdatabase_list_by_id_get_list(); #else // element is complex val["params"] = FilteringdatabaseSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getKeys(); val["elements"] = read_bridge_filteringdatabase_list_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = FilteringdatabaseSchema::getKeys(); val["elements"] = read_bridge_filteringdatabase_list_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = FilteringdatabaseSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } #undef NODE_IS_LIST_CONTAINER auto x = read_bridge_filteringdatabase_list_by_id(name); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_filteringdatabase_port_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); auto x = read_bridge_filteringdatabase_port_by_id(name, vlan, address); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { #define NODE_IS_LIST_CONTAINER using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getKeys(); val["elements"] = read_bridge_list_by_id_get_list(); #else // element is complex val["params"] = BridgeSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getKeys(); val["elements"] = read_bridge_list_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = BridgeSchema::getKeys(); val["elements"] = read_bridge_list_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = BridgeSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } #undef NODE_IS_LIST_CONTAINER auto x = read_bridge_list_by_id(); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_access_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsAccessSchema::getKeys(); val["elements"] = read_bridge_ports_access_by_id_get_list(); #else // element is complex val["params"] = PortsAccessSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsAccessSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsAccessSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsAccessSchema::getKeys(); val["elements"] = read_bridge_ports_access_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsAccessSchema::getKeys(); val["elements"] = read_bridge_ports_access_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsAccessSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_ports_access_by_id(name, portsName); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_access_vlanid_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_access_vlanid_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_address_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_address_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getKeys(); val["elements"] = read_bridge_ports_by_id_get_list(); #else // element is complex val["params"] = PortsSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getKeys(); val["elements"] = read_bridge_ports_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsSchema::getKeys(); val["elements"] = read_bridge_ports_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_ports_by_id(name, portsName); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); #define NODE_IS_LIST_CONTAINER using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getKeys(); val["elements"] = read_bridge_ports_list_by_id_get_list(); #else // element is complex val["params"] = PortsSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getKeys(); val["elements"] = read_bridge_ports_list_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsSchema::getKeys(); val["elements"] = read_bridge_ports_list_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } #undef NODE_IS_LIST_CONTAINER auto x = read_bridge_ports_list_by_id(name); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_mode_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_mode_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_peer_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_peer_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_status_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_status_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getKeys(); val["elements"] = read_bridge_ports_stp_by_id_get_list(); #else // element is complex val["params"] = PortsStpSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getKeys(); val["elements"] = read_bridge_ports_stp_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsStpSchema::getKeys(); val["elements"] = read_bridge_ports_stp_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsStpSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_ports_stp_by_id(name, portsName, vlan); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); #define NODE_IS_LIST_CONTAINER using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getKeys(); val["elements"] = read_bridge_ports_stp_list_by_id_get_list(); #else // element is complex val["params"] = PortsStpSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getKeys(); val["elements"] = read_bridge_ports_stp_list_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsStpSchema::getKeys(); val["elements"] = read_bridge_ports_stp_list_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsStpSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } #undef NODE_IS_LIST_CONTAINER auto x = read_bridge_ports_stp_list_by_id(name, portsName); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_stp_pathcost_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_ports_stp_pathcost_by_id(name, portsName, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_stp_portpriority_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_ports_stp_portpriority_by_id(name, portsName, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_stp_state_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_ports_stp_state_by_id(name, portsName, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_trunk_allowed_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlanid = request.param(":vlanid").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_allowed_by_id_get_list(); #else // element is complex val["params"] = PortsTrunkAllowedSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_allowed_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsTrunkAllowedSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_allowed_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsTrunkAllowedSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_ports_trunk_allowed_by_id(name, portsName, vlanid); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_trunk_allowed_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); #define NODE_IS_LIST_CONTAINER using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_allowed_list_by_id_get_list(); #else // element is complex val["params"] = PortsTrunkAllowedSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_allowed_list_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsTrunkAllowedSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_allowed_list_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsTrunkAllowedSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } #undef NODE_IS_LIST_CONTAINER auto x = read_bridge_ports_trunk_allowed_list_by_id(name, portsName); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_trunk_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_by_id_get_list(); #else // element is complex val["params"] = PortsTrunkSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsTrunkSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsTrunkSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_ports_trunk_by_id(name, portsName); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_trunk_nativevlan_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_trunk_nativevlan_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_uuid_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_uuid_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_address_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_stp_address_by_id(name, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getKeys(); val["elements"] = read_bridge_stp_by_id_get_list(); #else // element is complex val["params"] = StpSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getKeys(); val["elements"] = read_bridge_stp_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = StpSchema::getKeys(); val["elements"] = read_bridge_stp_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = StpSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_stp_by_id(name, vlan); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_forwarddelay_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_stp_forwarddelay_by_id(name, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_hellotime_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_stp_hellotime_by_id(name, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); #define NODE_IS_LIST_CONTAINER using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getKeys(); val["elements"] = read_bridge_stp_list_by_id_get_list(); #else // element is complex val["params"] = StpSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getKeys(); val["elements"] = read_bridge_stp_list_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = StpSchema::getKeys(); val["elements"] = read_bridge_stp_list_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = StpSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } #undef NODE_IS_LIST_CONTAINER auto x = read_bridge_stp_list_by_id(name); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_maxmessageage_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_stp_maxmessageage_by_id(name, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_priority_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_stp_priority_by_id(name, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stpenabled_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto x = read_bridge_stpenabled_by_id(name); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_type_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto x = read_bridge_type_by_id(name); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_uuid_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto x = read_bridge_uuid_by_id(name); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::update_bridge_agingtime_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param int32_t agingtime; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library agingtime = request_body; update_bridge_agingtime_by_id(name, agingtime); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param BridgeSchema bridge; nlohmann::json request_body = nlohmann::json::parse(request.body()); bridge.fromJson(request_body); update_bridge_by_id(name, bridge); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_filteringdatabase_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); // Getting the body param FilteringdatabaseSchema filteringdatabase; nlohmann::json request_body = nlohmann::json::parse(request.body()); filteringdatabase.fromJson(request_body); update_bridge_filteringdatabase_by_id(name, vlan, address, filteringdatabase); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_filteringdatabase_entrytype_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); // Getting the body param std::string entrytype; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library entrytype = request_body; update_bridge_filteringdatabase_entrytype_by_id(name, vlan, address, entrytype); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_filteringdatabase_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<FilteringdatabaseSchema> filteringdatabase; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { FilteringdatabaseSchema a; a.fromJson(j); filteringdatabase.push_back(a); } update_bridge_filteringdatabase_list_by_id(name, filteringdatabase); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_filteringdatabase_port_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); // Getting the body param std::string port; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library port = request_body; update_bridge_filteringdatabase_port_by_id(name, vlan, address, port); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_access_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param PortsAccessSchema access; nlohmann::json request_body = nlohmann::json::parse(request.body()); access.fromJson(request_body); update_bridge_ports_access_by_id(name, portsName, access); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_access_vlanid_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param int32_t vlanid; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library vlanid = request_body; update_bridge_ports_access_vlanid_by_id(name, portsName, vlanid); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_address_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::string address; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library address = request_body; update_bridge_ports_address_by_id(name, portsName, address); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param PortsSchema ports; nlohmann::json request_body = nlohmann::json::parse(request.body()); ports.fromJson(request_body); update_bridge_ports_by_id(name, portsName, ports); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<PortsSchema> ports; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsSchema a; a.fromJson(j); ports.push_back(a); } update_bridge_ports_list_by_id(name, ports); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_mode_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::string mode; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library mode = request_body; update_bridge_ports_mode_by_id(name, portsName, mode); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_peer_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::string peer; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library peer = request_body; update_bridge_ports_peer_by_id(name, portsName, peer); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_status_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::string status; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library status = request_body; update_bridge_ports_status_by_id(name, portsName, status); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param PortsStpSchema stp; nlohmann::json request_body = nlohmann::json::parse(request.body()); stp.fromJson(request_body); update_bridge_ports_stp_by_id(name, portsName, vlan, stp); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::vector<PortsStpSchema> stp; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsStpSchema a; a.fromJson(j); stp.push_back(a); } update_bridge_ports_stp_list_by_id(name, portsName, stp); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_stp_pathcost_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param int32_t pathcost; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library pathcost = request_body; update_bridge_ports_stp_pathcost_by_id(name, portsName, vlan, pathcost); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_stp_portpriority_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param int32_t portpriority; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library portpriority = request_body; update_bridge_ports_stp_portpriority_by_id(name, portsName, vlan, portpriority); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_trunk_allowed_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlanid = request.param(":vlanid").as<std::string>(); // Getting the body param PortsTrunkAllowedSchema allowed; nlohmann::json request_body = nlohmann::json::parse(request.body()); allowed.fromJson(request_body); update_bridge_ports_trunk_allowed_by_id(name, portsName, vlanid, allowed); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_trunk_allowed_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::vector<PortsTrunkAllowedSchema> allowed; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsTrunkAllowedSchema a; a.fromJson(j); allowed.push_back(a); } update_bridge_ports_trunk_allowed_list_by_id(name, portsName, allowed); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_trunk_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param PortsTrunkSchema trunk; nlohmann::json request_body = nlohmann::json::parse(request.body()); trunk.fromJson(request_body); update_bridge_ports_trunk_by_id(name, portsName, trunk); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_trunk_nativevlan_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param int32_t nativevlan; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library nativevlan = request_body; update_bridge_ports_trunk_nativevlan_by_id(name, portsName, nativevlan); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_address_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param std::string address; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library address = request_body; update_bridge_stp_address_by_id(name, vlan, address); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param StpSchema stp; nlohmann::json request_body = nlohmann::json::parse(request.body()); stp.fromJson(request_body); update_bridge_stp_by_id(name, vlan, stp); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_forwarddelay_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param int32_t forwarddelay; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library forwarddelay = request_body; update_bridge_stp_forwarddelay_by_id(name, vlan, forwarddelay); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_hellotime_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param int32_t hellotime; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library hellotime = request_body; update_bridge_stp_hellotime_by_id(name, vlan, hellotime); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<StpSchema> stp; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { StpSchema a; a.fromJson(j); stp.push_back(a); } update_bridge_stp_list_by_id(name, stp); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_maxmessageage_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param int32_t maxmessageage; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library maxmessageage = request_body; update_bridge_stp_maxmessageage_by_id(name, vlan, maxmessageage); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_priority_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param int32_t priority; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library priority = request_body; update_bridge_stp_priority_by_id(name, vlan, priority); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stpenabled_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param bool stpenabled; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library stpenabled = request_body; update_bridge_stpenabled_by_id(name, stpenabled); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_type_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::string type; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library type = request_body; update_bridge_type_by_id(name, type); response.send(polycube::service::Http::Code::Ok); } } } } }
41.101019
181
0.679988
mbertrone
1312ed1ff18236a2ce4147f4ffda7089fba07bb5
3,908
cpp
C++
install/TexGen/UnitTests/XMLTests.cpp
dalexa10/puma
ca02309c9f5c71e2e80ad8d64155dd6ca936c667
[ "NASA-1.3" ]
14
2021-06-17T17:17:07.000Z
2022-03-26T05:20:20.000Z
install/TexGen/UnitTests/XMLTests.cpp
dalexa10/puma
ca02309c9f5c71e2e80ad8d64155dd6ca936c667
[ "NASA-1.3" ]
6
2021-11-01T20:37:39.000Z
2022-03-11T17:18:53.000Z
install/TexGen/UnitTests/XMLTests.cpp
dalexa10/puma
ca02309c9f5c71e2e80ad8d64155dd6ca936c667
[ "NASA-1.3" ]
8
2021-07-20T09:24:23.000Z
2022-02-26T16:32:00.000Z
/*============================================================================= TexGen: Geometric textile modeller. Copyright (C) 2006 Martin Sherburn This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. =============================================================================*/ #include "XMLTests.h" #include "TestUtilities.h" CPPUNIT_TEST_SUITE_REGISTRATION(CXMLTests); void CXMLTests::setUp() { } void CXMLTests::tearDown() { TEXGEN.DeleteTextiles(); } bool CXMLTests::TestOutput(string Prefix, OUTPUT_TYPE Type) { // Set up some file names string OriginalFile = Prefix + "1.tg3"; string CompareFile = Prefix + "2.tg3"; // Save to xml file TEXGEN.SaveToXML(OriginalFile, "", Type); TEXGEN.DeleteTextiles(); // Read it back in TEXGEN.ReadFromXML(OriginalFile); // Save it back to disk again TEXGEN.SaveToXML(CompareFile, "", Type); // Check the two files are the same return CompareFiles(OriginalFile, CompareFile); } void CXMLTests::TestTextile2DWeaveMin() { TEXGEN.AddTextile(m_TextileFactory.SatinWeave()); CPPUNIT_ASSERT(TestOutput("2dweavemin", OUTPUT_MINIMAL)); } void CXMLTests::TestTextile2DWeaveStandard() { TEXGEN.AddTextile(m_TextileFactory.SatinWeave()); CPPUNIT_ASSERT(TestOutput("2dweavestan", OUTPUT_STANDARD)); } void CXMLTests::TestTextile2DWeaveFull() { TEXGEN.AddTextile(m_TextileFactory.SatinWeave()); CPPUNIT_ASSERT(TestOutput("2dweavefull", OUTPUT_FULL)); } void CXMLTests::TestTextile3DWeaveMin() { TEXGEN.AddTextile(m_TextileFactory.Weave3D8x4()); CPPUNIT_ASSERT(TestOutput("3dweavemin", OUTPUT_MINIMAL)); } void CXMLTests::TestTextile3DWeaveStandard() { TEXGEN.AddTextile(m_TextileFactory.Weave3D8x4()); CPPUNIT_ASSERT(TestOutput("3dweavestan", OUTPUT_STANDARD)); } void CXMLTests::TestTextile3DWeaveFull() { TEXGEN.AddTextile(m_TextileFactory.Weave3D8x4()); CPPUNIT_ASSERT(TestOutput("3dweavefull", OUTPUT_FULL)); } void CXMLTests::TestYarnMin() { TEXGEN.AddTextile(m_TextileFactory.InterpTest()); CPPUNIT_ASSERT(TestOutput("yarnmin", OUTPUT_MINIMAL)); } void CXMLTests::TestYarnStandard() { TEXGEN.AddTextile(m_TextileFactory.InterpTest()); CPPUNIT_ASSERT(TestOutput("yarnstan", OUTPUT_STANDARD)); } void CXMLTests::TestYarnFull() { TEXGEN.AddTextile(m_TextileFactory.InterpTest()); CPPUNIT_ASSERT(TestOutput("yarnfull", OUTPUT_FULL)); } void CXMLTests::TestSectionsMin() { TEXGEN.AddTextile(m_TextileFactory.SectionsTest()); CPPUNIT_ASSERT(TestOutput("sectionsmin", OUTPUT_MINIMAL)); } void CXMLTests::TestSectionsStandard() { TEXGEN.AddTextile(m_TextileFactory.SectionsTest()); CPPUNIT_ASSERT(TestOutput("sectionsstan", OUTPUT_STANDARD)); } void CXMLTests::TestSectionsFull() { TEXGEN.AddTextile(m_TextileFactory.SectionsTest()); CPPUNIT_ASSERT(TestOutput("sectionsfull", OUTPUT_FULL)); } void CXMLTests::TestDomain() { CTextile Textile; CDomainPlanes Domain(XYZ(0,0,0), XYZ(1,2,3)); Textile.AssignDomain(Domain); TEXGEN.AddTextile(Textile); CPPUNIT_ASSERT(TestOutput("domain", OUTPUT_FULL)); } /* void CXMLTests::TestMeshing() { CTextileWeave2D Text = m_TextileFactory.MeshedWeave(); Text.SetResolution(8); // Text.OutputAbaqus("test.inp"); // TEXGEN.AddTextile(m_TextileFactory.MeshedWeave()); // CPPUNIT_ASSERT(TestOutput("meshedweave", OUTPUT_FULL)); }*/
24.425
79
0.743347
dalexa10
13160379f3ae6bae62e83f610ee3f43beb4cdab3
1,158
cpp
C++
src/Channel.cpp
Apriluestc/web.d
eaf9bab7f6096f10e104d49d917c318fc5a46e0d
[ "MIT" ]
74
2019-07-29T11:45:33.000Z
2021-08-20T00:08:48.000Z
src/Channel.cpp
Apriluestc/web.d
eaf9bab7f6096f10e104d49d917c318fc5a46e0d
[ "MIT" ]
null
null
null
src/Channel.cpp
Apriluestc/web.d
eaf9bab7f6096f10e104d49d917c318fc5a46e0d
[ "MIT" ]
14
2019-09-04T09:04:02.000Z
2021-08-02T17:08:39.000Z
/********************************************************** * Author : Apriluestc * Email : 13669186256@163.com * Last modified : 2019-07-28 13:24 * Filename : Channel.cpp * Description : 事件和描述符的封装 * 包括文件描述符的获取、设置 * 事件的设置、获取 * 以及读、写、异常、错误事件的分发处理 * *******************************************************/ #include <unistd.h> #include <queue> #include <cstdlib> #include <iostream> #include "Channel.h" #include "Util.h" #include "Epoll.h" #include "EventLoop.h" Channel::Channel(EventLoop *loop) :loop_(loop), events_(0), lastEvents_(0) {} Channel::Channel(EventLoop *loop, int fd) :loop_(loop), fd_(fd), events_(0), lastEvents_(0) {} Channel::~Channel() {} int Channel::getFd() { return fd_; } void Channel::setFd(int fd) { fd_ = fd; } void Channel::handleRead() { if (readHandler_) { readHandler_(); } } void Channel::handleWrite() { if (writeHandler_) { writeHandler_(); } } void Channel::handleConn() { if (connHandler_) { connHandler_(); } }
18.983607
60
0.497409
Apriluestc
1317e280190edb91978fe893cfc6b86a8d4920be
7,300
hpp
C++
include/ff/distributed/ff_dreceiver.hpp
gerzin/parallel-cellular-automata
dcaf220fa89e8348486aa17d46a864d6ee64e46d
[ "MIT" ]
null
null
null
include/ff/distributed/ff_dreceiver.hpp
gerzin/parallel-cellular-automata
dcaf220fa89e8348486aa17d46a864d6ee64e46d
[ "MIT" ]
null
null
null
include/ff/distributed/ff_dreceiver.hpp
gerzin/parallel-cellular-automata
dcaf220fa89e8348486aa17d46a864d6ee64e46d
[ "MIT" ]
null
null
null
#ifndef FF_DRECEIVER_H #define FF_DRECEIVER_H #include <iostream> #include <sstream> #include <ff/ff.hpp> #include <ff/distributed/ff_network.hpp> #include <sys/socket.h> #include <sys/un.h> #include <sys/types.h> #include <sys/uio.h> #include <arpa/inet.h> #include <cereal/cereal.hpp> #include <cereal/archives/portable_binary.hpp> #include <cereal/types/vector.hpp> #include <cereal/types/polymorphic.hpp> using namespace ff; class ff_dreceiver: public ff_monode_t<message_t> { private: int sendRoutingTable(int sck){ dataBuffer buff; std::ostream oss(&buff); cereal::PortableBinaryOutputArchive oarchive(oss); std::vector<int> reachableDestinations; for(auto const& p : this->routingTable) reachableDestinations.push_back(p.first); oarchive << reachableDestinations; size_t sz = htobe64(buff.getLen()); struct iovec iov[1]; iov[0].iov_base = &sz; iov[0].iov_len = sizeof(sz); if (writevn(sck, iov, 1) < 0 || writen(sck, buff.getPtr(), buff.getLen()) < 0){ error("Error writing on socket the routing Table\n"); return -1; } return 0; } int handleRequest(int sck){ int sender; int chid; size_t sz; struct iovec iov[3]; iov[0].iov_base = &sender; iov[0].iov_len = sizeof(sender); iov[1].iov_base = &chid; iov[1].iov_len = sizeof(chid); iov[2].iov_base = &sz; iov[2].iov_len = sizeof(sz); switch (readvn(sck, iov, 3)) { case -1: error("Error reading from socket\n"); // fatal error case 0: return -1; // connection close } // convert values to host byte order sender = ntohl(sender); chid = ntohl(chid); sz = be64toh(sz); if (sz > 0){ char* buff = new char [sz]; assert(buff); if(readn(sck, buff, sz) < 0){ error("Error reading from socket\n"); delete [] buff; return -1; } message_t* out = new message_t(buff, sz, true); assert(out); out->sender = sender; out->chid = chid; //std::cout << "received something from " << sender << " directed to " << chid << std::endl; ff_send_out_to(out, this->routingTable[chid]); // assume the routing table is consistent WARNING!!! return 0; } neos++; // increment the eos received return -1; } public: ff_dreceiver(const int dGroup_id, ff_endpoint acceptAddr, size_t input_channels, std::map<int, int> routingTable = {std::make_pair(0,0)}, int coreid=-1) : input_channels(input_channels), acceptAddr(acceptAddr), routingTable(routingTable), distributedGroupId(dGroup_id), coreid(coreid) {} int svc_init() { if (coreid!=-1) ff_mapThreadToCpu(coreid); #ifdef LOCAL if ((listen_sck=socket(AF_LOCAL, SOCK_STREAM, 0)) < 0){ error("Error creating the socket\n"); return -1; } struct sockaddr_un serv_addr; memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sun_family = AF_LOCAL; strncpy(serv_addr.sun_path, acceptAddr.address.c_str(), acceptAddr.address.size()+1); #endif #ifdef REMOTE if ((listen_sck=socket(AF_INET, SOCK_STREAM, 0)) < 0){ error("Error creating the socket\n"); return -1; } int enable = 1; // enable the reuse of the address if (setsockopt(listen_sck, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) error("setsockopt(SO_REUSEADDR) failed\n"); struct sockaddr_in serv_addr; serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; // still listening from any interface serv_addr.sin_port = htons( acceptAddr.port ); #endif if (bind(listen_sck, (struct sockaddr*)&serv_addr,sizeof(serv_addr)) < 0){ error("Error binding\n"); return -1; } if (listen(listen_sck, MAXBACKLOG) < 0){ error("Error listening\n"); return -1; } /*for (const auto& e : routingTable) std::cout << "Entry: " << e.first << " -> " << e.second << std::endl; */ return 0; } void svc_end() { close(this->listen_sck); #ifdef LOCAL unlink(this->acceptAddr.address.c_str()); #endif } /* Here i should not care of input type nor input data since they come from a socket listener. Everything will be handled inside a while true in the body of this node where data is pulled from network */ message_t *svc(message_t* task) { /* here i should receive the task via socket */ fd_set set, tmpset; // intialize both sets (master, temp) FD_ZERO(&set); FD_ZERO(&tmpset); // add the listen socket to the master set FD_SET(this->listen_sck, &set); // hold the greater descriptor int fdmax = this->listen_sck; while(neos < input_channels){ // copy the master set to the temporary tmpset = set; switch(select(fdmax+1, &tmpset, NULL, NULL, NULL)){ case -1: error("Error on selecting socket\n"); return EOS; case 0: continue; } // iterate over the file descriptor to see which one is active for(int i=0; i <= fdmax; i++) if (FD_ISSET(i, &tmpset)){ if (i == this->listen_sck) { int connfd = accept(this->listen_sck, (struct sockaddr*)NULL ,NULL); if (connfd == -1){ error("Error accepting client\n"); } else { FD_SET(connfd, &set); if(connfd > fdmax) fdmax = connfd; this->sendRoutingTable(connfd); // here i should check the result of the call! and handle possible errors! } continue; } // it is not a new connection, call receive and handle possible errors if (this->handleRequest(i) < 0){ close(i); FD_CLR(i, &set); // update the maximum file descriptor if (i == fdmax) for(int i=(fdmax-1);i>=0;--i) if (FD_ISSET(i, &set)){ fdmax = i; break; } } } } /* In theory i should never return because of the while true. In our first example this is necessary */ return this->EOS; } private: size_t neos = 0; size_t input_channels; int listen_sck; ff_endpoint acceptAddr; std::map<int, int> routingTable; int distributedGroupId; int coreid; }; #endif
31.877729
156
0.528904
gerzin
131a20758fd043b7fe5fb163495c0361ca90b29d
5,312
cpp
C++
ace/tao/orbsvcs/orbsvcs/Time/TAO_Time_Service_Clerk.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
ace/tao/orbsvcs/orbsvcs/Time/TAO_Time_Service_Clerk.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
ace/tao/orbsvcs/orbsvcs/Time/TAO_Time_Service_Clerk.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
// -*- C++ -*- // TAO_Time_Service_Clerk.cpp,v 1.20 2001/03/26 21:17:04 coryan Exp #include "TAO_Time_Service_Clerk.h" #include "TAO_TIO.h" #include "TAO_UTO.h" #include "tao/ORB_Core.h" // Constructor. TAO_Time_Service_Clerk::TAO_Time_Service_Clerk (int timer_value, int timer_value_usecs, const IORS& servers) : server_ (servers), helper_ (this) { // Schedule the helper to be invoked by the reactor // periodically. if (TAO_ORB_Core_instance ()->reactor ()->schedule_timer (&helper_, 0, ACE_Time_Value::zero, ACE_Time_Value(timer_value,timer_value_usecs)) == -1) ACE_ERROR ((LM_ERROR, "%p\n", "schedule_timer ()")); } // Destructor. TAO_Time_Service_Clerk::~TAO_Time_Service_Clerk (void) { } // This method returns the global time and an estimate of inaccuracy // in a UTO. CosTime::UTO_ptr TAO_Time_Service_Clerk::universal_time (CORBA::Environment &ACE_TRY_ENV) ACE_THROW_SPEC ((CORBA::SystemException, CosTime::TimeUnavailable)) { TAO_UTO *uto = 0; ACE_NEW_THROW_EX (uto, TAO_UTO (this->get_time (), this->inaccuracy (), this->time_displacement_factor ()), CORBA::NO_MEMORY ()); ACE_CHECK_RETURN (CosTime::UTO::_nil ()); // Return the global time as a UTO. return uto->_this (); } // This method returns the global time in a UTO only if the time can // be guaranteed to have been obtained securely. This method is not // implemented currently. CosTime::UTO_ptr TAO_Time_Service_Clerk::secure_universal_time (CORBA::Environment &ACE_TRY_ENV) ACE_THROW_SPEC ((CORBA::SystemException, CosTime::TimeUnavailable)) { ACE_THROW_RETURN (CORBA::NO_IMPLEMENT (), 0); } // This creates a new UTO based on the given parameters. CosTime::UTO_ptr TAO_Time_Service_Clerk::new_universal_time (TimeBase::TimeT time, TimeBase::InaccuracyT inaccuracy, TimeBase::TdfT tdf, CORBA::Environment &ACE_TRY_ENV) ACE_THROW_SPEC ((CORBA::SystemException)) { TAO_UTO *uto = 0; ACE_NEW_THROW_EX (uto, TAO_UTO (time, inaccuracy, tdf), CORBA::NO_MEMORY ()); ACE_CHECK_RETURN (CosTime::UTO::_nil ()); return uto->_this (); } // This creates a new UTO given a time in the UtcT form. CosTime::UTO_ptr TAO_Time_Service_Clerk::uto_from_utc (const TimeBase::UtcT &utc, CORBA::Environment &ACE_TRY_ENV) ACE_THROW_SPEC ((CORBA::SystemException)) { TAO_UTO *uto = 0; // Use the low and high values of inaccuracy // to calculate the total inaccuracy. TimeBase::InaccuracyT inaccuracy = utc.inacchi; inaccuracy <<= 32; inaccuracy |= utc.inacclo; ACE_NEW_THROW_EX (uto, TAO_UTO (utc.time, inaccuracy, utc.tdf), CORBA::NO_MEMORY ()); ACE_CHECK_RETURN (CosTime::UTO::_nil ()); return uto->_this (); } // This creates a new TIO with the given parameters. CosTime::TIO_ptr TAO_Time_Service_Clerk::new_interval (TimeBase::TimeT lower, TimeBase::TimeT upper, CORBA::Environment &ACE_TRY_ENV) ACE_THROW_SPEC ((CORBA::SystemException)) { TAO_TIO *tio = 0; ACE_NEW_THROW_EX (tio, TAO_TIO (lower, upper), CORBA::NO_MEMORY ()); ACE_CHECK_RETURN (CosTime::TIO::_nil ()); return tio->_this (); } CORBA::ULongLong TAO_Time_Service_Clerk::get_time (void) { // Globally sync. time is the latest global time plus the time // elapsed since last updation was done. CORBA::ULongLong time; time = (CORBA::ULongLong) (ACE_static_cast (CORBA::ULongLong, ACE_OS::gettimeofday ().sec ()) * ACE_static_cast (ACE_UINT32, 10000000) + ACE_static_cast (CORBA::ULongLong, ACE_OS::gettimeofday ().usec () * 10)) - this->update_timestamp_ + this->time_; return time; } // Returns the time displacement factor in minutes. // This is displacement from the GMT. CORBA::Short TAO_Time_Service_Clerk::time_displacement_factor (void) { return time_displacement_factor_; } // Sets the TDF. void TAO_Time_Service_Clerk::time_displacement_factor (CORBA::Short tdf) { this->time_displacement_factor_ = tdf; } // GET method for inaccuracy. TimeBase::InaccuracyT TAO_Time_Service_Clerk::inaccuracy (void) { return this->inaccuracy_; } // SET method for inaccuracy. void TAO_Time_Service_Clerk::inaccuracy (TimeBase::InaccuracyT inaccuracy) { this->inaccuracy_ = inaccuracy; }
29.675978
85
0.572666
tharindusathis
131c7c8119834813aeca5fa393e4aa9b9e9352fb
350
cpp
C++
1]. DSA + CP/2]. Competitive Programming/13]. CodeForces/1]. Problem Set/Levels/A/0069) Young Physicist.cpp
geeknarendra/The-Complete-FAANG-Preparation
3ed22719022bc66bd05c5c1ed091fe605e979908
[ "MIT" ]
1
2022-01-26T01:11:10.000Z
2022-01-26T01:11:10.000Z
1]. DSA + CP/2]. Competitive Programming/13]. CodeForces/1]. Problem Set/Levels/A/0069) Young Physicist.cpp
geeknarendra/The-Complete-FAANG-Preparation
3ed22719022bc66bd05c5c1ed091fe605e979908
[ "MIT" ]
null
null
null
1]. DSA + CP/2]. Competitive Programming/13]. CodeForces/1]. Problem Set/Levels/A/0069) Young Physicist.cpp
geeknarendra/The-Complete-FAANG-Preparation
3ed22719022bc66bd05c5c1ed091fe605e979908
[ "MIT" ]
null
null
null
#include <iostream> #include <bits/stdc++.h> using namespace std; int main() { int n ,point , input = 0; cin >> n; while (n > 0){ for(int i = 0 ; i <3 ;i++){ cin>>input; point = point + input; } n--; } if(point == 0){ cout<<"YES"; }else{ cout<<"NO"; } }
15.217391
39
0.402857
geeknarendra
131eafafe73796cd97b62318f880e8e98da80e17
235
cpp
C++
expression_test/win/expression_test.cpp
ddf/evaluator
60ed46fd4b59e395605dd7182e7f619ce52fc08a
[ "Zlib" ]
16
2018-02-05T15:01:35.000Z
2022-01-21T10:21:43.000Z
expression_test/win/expression_test.cpp
ddf/evaluator
60ed46fd4b59e395605dd7182e7f619ce52fc08a
[ "Zlib" ]
2
2016-11-15T03:32:43.000Z
2019-04-21T23:11:10.000Z
expression_test/win/expression_test.cpp
ddf/evaluator
60ed46fd4b59e395605dd7182e7f619ce52fc08a
[ "Zlib" ]
3
2018-03-06T01:32:42.000Z
2021-01-27T07:25:37.000Z
// expression_test.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <chrono> #pragma warning(disable:4996) #pragma warning(disable:4146) #include "../../Program.cpp" #include "../main.cpp"
18.076923
77
0.714894
ddf
13207fec8453cb578236e50af99ae43cf26e59cc
5,176
cpp
C++
src/Nazara/Graphics/SlicedSprite.cpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
11
2019-11-27T00:40:43.000Z
2020-01-29T14:31:52.000Z
src/Nazara/Graphics/SlicedSprite.cpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
7
2019-11-27T00:29:08.000Z
2020-01-08T18:53:39.000Z
src/Nazara/Graphics/SlicedSprite.cpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
7
2019-11-27T10:27:40.000Z
2020-01-15T17:43:33.000Z
// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Graphics/SlicedSprite.hpp> #include <Nazara/Graphics/BasicMaterial.hpp> #include <Nazara/Graphics/Material.hpp> #include <Nazara/Graphics/RenderSpriteChain.hpp> #include <Nazara/Graphics/Debug.hpp> namespace Nz { SlicedSprite::SlicedSprite(std::shared_ptr<Material> material) : m_material(std::move(material)), m_color(Color::White), m_textureCoords(0.f, 0.f, 1.f, 1.f), m_size(64.f, 64.f) { UpdateVertices(); } void SlicedSprite::BuildElement(std::size_t passIndex, const WorldInstance& worldInstance, std::vector<std::unique_ptr<RenderElement>>& elements, const Recti& scissorBox) const { const auto& materialPass = m_material->GetPass(passIndex); if (!materialPass) return; const std::shared_ptr<VertexDeclaration>& vertexDeclaration = VertexDeclaration::Get(VertexLayout::XYZ_Color_UV); std::vector<RenderPipelineInfo::VertexBufferData> vertexBufferData = { { { 0, vertexDeclaration } } }; const auto& renderPipeline = materialPass->GetPipeline()->GetRenderPipeline(vertexBufferData); const auto& whiteTexture = Graphics::Instance()->GetDefaultTextures().whiteTextures[UnderlyingCast(ImageType::E2D)]; elements.emplace_back(std::make_unique<RenderSpriteChain>(GetRenderLayer(), materialPass, renderPipeline, worldInstance, vertexDeclaration, whiteTexture, m_spriteCount, m_vertices.data(), scissorBox)); } const std::shared_ptr<Material>& SlicedSprite::GetMaterial(std::size_t i) const { assert(i == 0); NazaraUnused(i); return m_material; } std::size_t SlicedSprite::GetMaterialCount() const { return 1; } inline auto SlicedSprite::GetTopLeftCorner() const -> const Corner& { return m_topLeftCorner; } Vector3ui SlicedSprite::GetTextureSize() const { assert(m_material); //TODO: Cache index in registry? if (const auto& material = m_material->FindPass("ForwardPass")) { BasicMaterial mat(*material); if (mat.HasDiffuseMap()) { // Material should always have textures but we're better safe than sorry if (const auto& texture = mat.GetDiffuseMap()) return texture->GetSize(); } } // Couldn't get material pass or texture return Vector3ui::Unit(); //< prevents division by zero } void SlicedSprite::UpdateVertices() { VertexStruct_XYZ_Color_UV* vertices = m_vertices.data(); std::array<float, 3> heights = { m_topLeftCorner.size.y, m_size.y - m_topLeftCorner.size.y - m_bottomRightCorner.size.y, m_bottomRightCorner.size.y }; std::array<float, 3> widths = { m_topLeftCorner.size.x, m_size.x - m_topLeftCorner.size.x - m_bottomRightCorner.size.x, m_bottomRightCorner.size.x }; std::array<float, 3> texCoordsX = { m_topLeftCorner.textureCoords.x * m_textureCoords.width, m_textureCoords.width - m_topLeftCorner.textureCoords.x * m_textureCoords.width - m_bottomRightCorner.textureCoords.x * m_textureCoords.width, m_bottomRightCorner.textureCoords.x * m_textureCoords.width }; std::array<float, 3> texCoordsY = { m_topLeftCorner.textureCoords.y * m_textureCoords.height, m_textureCoords.height - m_topLeftCorner.textureCoords.y * m_textureCoords.height - m_bottomRightCorner.textureCoords.y * m_textureCoords.height, m_bottomRightCorner.textureCoords.y * m_textureCoords.height }; Vector3f origin = Vector3f::Zero(); Vector2f topLeftUV = m_textureCoords.GetCorner(RectCorner::LeftTop); m_spriteCount = 0; for (std::size_t y = 0; y < 3; ++y) { float height = heights[y]; if (height > 0.f) { for (std::size_t x = 0; x < 3; ++x) { float width = widths[x]; if (width > 0.f) { vertices->color = m_color; vertices->position = origin; vertices->uv = topLeftUV; vertices++; vertices->color = m_color; vertices->position = origin + width * Vector3f::Right(); vertices->uv = topLeftUV + Vector2f(texCoordsX[x], 0.f); vertices++; vertices->color = m_color; vertices->position = origin + height * Vector3f::Up(); vertices->uv = topLeftUV + Vector2f(0.f, texCoordsY[y]); vertices++; vertices->color = m_color; vertices->position = origin + width * Vector3f::Right() + height * Vector3f::Up(); vertices->uv = topLeftUV + Vector2f(texCoordsX[x], texCoordsY[y]); vertices++; origin.x += width; m_spriteCount++; } topLeftUV.x += texCoordsX[x]; } origin.y += height; } origin.x = 0; topLeftUV.x = m_textureCoords.x; topLeftUV.y += texCoordsY[y]; } Boxf aabb = Boxf::Zero(); std::size_t vertexCount = 4 * m_spriteCount; if (vertexCount > 0) { // Reverse texcoords Y for (std::size_t i = 0; i < vertexCount; ++i) m_vertices[i].uv.y = m_textureCoords.height - m_vertices[i].uv.y; aabb.Set(m_vertices[0].position); for (std::size_t i = 1; i < vertexCount; ++i) aabb.ExtendTo(m_vertices[i].position); } UpdateAABB(aabb); OnElementInvalidated(this); } }
28.916201
203
0.695131
jayrulez
13230742986a87e5308b881255e4353bfde12556
884
hpp
C++
Framework/Common/PipelineStateManager.hpp
Hengle/GameEngineFromScratch
2c1cce4902fc80d0f55442ad6422508f829f912e
[ "MIT" ]
1,217
2017-08-18T02:41:11.000Z
2022-03-30T01:48:46.000Z
Framework/Common/PipelineStateManager.hpp
gangzi4494/GameEngineFromScratch
2c1cce4902fc80d0f55442ad6422508f829f912e
[ "MIT" ]
16
2017-09-05T15:04:37.000Z
2021-09-09T13:59:38.000Z
Framework/Common/PipelineStateManager.hpp
gangzi4494/GameEngineFromScratch
2c1cce4902fc80d0f55442ad6422508f829f912e
[ "MIT" ]
285
2017-08-18T04:53:55.000Z
2022-03-30T00:02:15.000Z
#include <map> #include "IPipelineStateManager.hpp" namespace My { class PipelineStateManager : _implements_ IPipelineStateManager { public: PipelineStateManager() = default; virtual ~PipelineStateManager(); int Initialize() override; void Finalize() override; void Tick() override {} bool RegisterPipelineState(PipelineState& pipelineState) override; void UnregisterPipelineState(PipelineState& pipelineState) override; void Clear() override; const std::shared_ptr<PipelineState> GetPipelineState( std::string name) const final; protected: virtual bool InitializePipelineState(PipelineState** ppPipelineState) { return true; } virtual void DestroyPipelineState(PipelineState& pipelineState) {} protected: std::map<std::string, std::shared_ptr<PipelineState>> m_pipelineStates; }; } // namespace My
27.625
75
0.734163
Hengle
1324c0ab3291680f29249f7e68cbe45480148702
683
cpp
C++
max_diff.cpp
AALEKH/solutions
88abb36641b8ea0c0e13d492b7dc69411ce2795e
[ "MIT" ]
null
null
null
max_diff.cpp
AALEKH/solutions
88abb36641b8ea0c0e13d492b7dc69411ce2795e
[ "MIT" ]
null
null
null
max_diff.cpp
AALEKH/solutions
88abb36641b8ea0c0e13d492b7dc69411ce2795e
[ "MIT" ]
null
null
null
// Maximum Difference between two elements such that smaller number always appear before larger one. // Complexity : O(n) and O(1) in terms of space #include <iostream> #include <vector> int max_diff(std::vector<int> elements) { int max = -10, min = 1000, sm = 2000; for(int i = 0; i < elements.size(); i++) { if(min > elements[i]){ min = elements[i]; } else if(max < elements[i]){ max = elements[i]; sm = min; } } std::cout << " Max: " << max << " Min: " << sm <<std::endl; return max-sm; } int main() { std::vector<int> vec = {2, 7, 9, 5, 1, 3, 5}; std::cout << "Max diff between two elements in a vector is " << max_diff(vec) << std::endl; return 0; }
26.269231
100
0.600293
AALEKH
1328669babfe2cc45cf20890d326188aa9410400
1,990
hpp
C++
src/cs-gui/ScreenSpaceGuiArea.hpp
bernstein/cosmoscout-vr
4243384a0f96853dc12fc8e9d5862c9c37f7cadf
[ "MIT" ]
null
null
null
src/cs-gui/ScreenSpaceGuiArea.hpp
bernstein/cosmoscout-vr
4243384a0f96853dc12fc8e9d5862c9c37f7cadf
[ "MIT" ]
null
null
null
src/cs-gui/ScreenSpaceGuiArea.hpp
bernstein/cosmoscout-vr
4243384a0f96853dc12fc8e9d5862c9c37f7cadf
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of CosmoScout VR // // and may be used under the terms of the MIT license. See the LICENSE file for details. // // Copyright: (c) 2019 German Aerospace Center (DLR) // //////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef CS_GUI_VISTA_SCREENSPACEGUIAREA_HPP #define CS_GUI_VISTA_SCREENSPACEGUIAREA_HPP #include "GuiArea.hpp" #include <VistaAspects/VistaObserver.h> #include <VistaKernel/GraphicsManager/VistaOpenGLDraw.h> #include <vector> class VistaTransformNode; class VistaTransformMatrix; class VistaVector3D; class VistaQuaternion; class VistaProjection; class VistaViewport; class VistaGLSLShader; class VistaVertexArrayObject; class VistaBufferObject; namespace cs::gui { /// This class is used to render static UI elements, which are always at the same position of the /// screen. class CS_GUI_EXPORT ScreenSpaceGuiArea : public GuiArea, public IVistaOpenGLDraw, public IVistaObserver { public: explicit ScreenSpaceGuiArea(VistaViewport* pViewport); ~ScreenSpaceGuiArea() override; int getWidth() const override; int getHeight() const override; /// Draws the UI to screen. bool Do() override; bool GetBoundingBox(VistaBoundingBox& bb) override; /// Handles changes to the screen size. void ObserverUpdate(IVistaObserveable* pObserveable, int nMsg, int nTicket) override; private: virtual void onViewportChange(); VistaViewport* mViewport; VistaGLSLShader* mShader = nullptr; bool mShaderDirty = true; int mWidth = 0; int mHeight = 0; }; } // namespace cs::gui #endif // CS_GUI_VISTA_SCREENSPACEGUIAREA_HPP
32.622951
100
0.598995
bernstein
132a036afe04926a94eb42c1bdf7e3d766df16c1
594
hpp
C++
modules/PrimusEditor/source/EditorMap.hpp
DarebacK/Primus
3d8bfe2b1466bf692d2cf9d6dcd9acd9e2625efa
[ "MIT" ]
null
null
null
modules/PrimusEditor/source/EditorMap.hpp
DarebacK/Primus
3d8bfe2b1466bf692d2cf9d6dcd9acd9e2625efa
[ "MIT" ]
null
null
null
modules/PrimusEditor/source/EditorMap.hpp
DarebacK/Primus
3d8bfe2b1466bf692d2cf9d6dcd9acd9e2625efa
[ "MIT" ]
null
null
null
#pragma once #include "Core/Core.hpp" #include "Core/Image.hpp" #include "Primus/Map.hpp" struct Colormap { Image image; }; // Holds data related to map to be used in the editor. struct EditorMap : public Map { int16 heightmapTileXMin = 66; int16 heightmapTileXMax = 70; int16 heightmapTileYMin = 45; int16 heightmapTileYMax = 50; int16 heightmapTileZoom = 7; int16 heightmapTileSize = 512; Colormap colormap; bool tryLoad(const wchar_t* mapDirectoryPath, float verticalFieldOfViewRadians, float aspectRatio); bool tryFixLandElevation(); };
21.214286
102
0.712121
DarebacK
132a3d777bcb9e34e5aa3ad46643ab4ba9ab9655
407
cc
C++
cses/1090.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
506
2018-08-22T10:30:38.000Z
2022-03-31T10:01:49.000Z
cses/1090.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
13
2019-08-07T18:31:18.000Z
2020-12-15T21:54:41.000Z
cses/1090.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
234
2018-08-06T17:11:41.000Z
2022-03-26T10:56:42.000Z
// https://cses.fi/problemset/task/1090/ #include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { int n, w; cin >> n >> w; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; sort(a.begin(), a.end()); int i = 0; int j = n - 1; int c = 0; while (i <= j) { if (a[j] + a[i] > w) j--; else { i++; j--; } c++; } cout << c << endl; }
16.958333
42
0.479115
Ashindustry007
132b753443e1d4475bc08a149c635bec49733ecc
9,588
hpp
C++
src/liblanelet/lanelet_point.hpp
brand666/liblanelet
252e436ae9f705f8004d86b504be6a5f0c8bcc19
[ "BSD-3-Clause" ]
24
2017-11-29T12:44:44.000Z
2022-03-06T12:45:52.000Z
src/liblanelet/lanelet_point.hpp
brand666/liblanelet
252e436ae9f705f8004d86b504be6a5f0c8bcc19
[ "BSD-3-Clause" ]
3
2018-11-02T09:21:27.000Z
2020-03-16T20:03:17.000Z
src/liblanelet/lanelet_point.hpp
brand666/liblanelet
252e436ae9f705f8004d86b504be6a5f0c8bcc19
[ "BSD-3-Clause" ]
12
2017-10-26T08:42:06.000Z
2022-03-06T12:45:52.000Z
// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*- // -- BEGIN LICENSE BLOCK ---------------------------------------------- // Copyright (c) 2018, FZI Forschungszentrum Informatik // // 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. // // 3. Neither the name of the copyright holder 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. // -- END LICENSE BLOCK ------------------------------------------------ //---------------------------------------------------------------------- /*!\file * * \author Philipp Bender <philipp.bender@fzi.de> * \date 2014-01-01 * */ //---------------------------------------------------------------------- #pragma once #include <boost/math/special_functions.hpp> #include <cmath> #include <boost/tuple/tuple.hpp> #include <boost/variant/get.hpp> #include "LocalGeographicCS.hpp" #include "normalize_angle.hpp" #include "Attribute.hpp" namespace LLet { enum LATLON_COORDS { LAT = 0, LON = 1, ID = 2 }; enum XY_COORDS { X = 0, Y = 1 }; class point_with_id_t : public boost::tuple<double, double, int64_t>, public HasAttributes { public: point_with_id_t(const boost::tuple<double, double, int64_t> &tuple = boost::tuple<double, double, int64_t>(0.0, 0.0, -1)) : boost::tuple<double, double, int64_t>(tuple) { // nothing to do } #ifdef _WIN32 // The tuple implementation of MSVC10 fails on the auto-generated copy ctor point_with_id_t(const point_with_id_t &other) : HasAttributes(other) { boost::get<LLet::LAT>(*this) = boost::get<LLet::LAT>(other); boost::get<LLet::LON>(*this) = boost::get<LLet::LON>(other); boost::get<LLet::ID>(*this) = boost::get<LLet::ID>(other); } #endif }; inline bool operator==(const point_with_id_t& lhs, const point_with_id_t& rhs) { return boost::get<0>(lhs) == boost::get<0>(rhs) && boost::get<1>(lhs) == boost::get<1>(rhs) && boost::get<2>(lhs) == boost::get<2>(rhs); } inline bool operator!=(const point_with_id_t& lhs, const point_with_id_t& rhs){return !(lhs == rhs);} typedef boost::tuple< double, double > point_xy_t; typedef std::vector<point_xy_t> vertex_container_t; inline boost::tuple< double, double > vec( const point_with_id_t& a, const point_with_id_t& b ) { using boost::get; LocalGeographicCS cs(get<LAT>(a), get<LON>(a)); double ax, ay, bx, by; boost::tie(ax, ay) = cs.ll2xy(get<LAT>(a), get<LON>(a)); boost::tie(bx, by) = cs.ll2xy(get<LAT>(b), get<LON>(b)); double dx = bx - ax; double dy = by - ay; return boost::make_tuple(dx, dy); } //! Calculate the absolute point from absolute point \a a with relative offset \a vec and the given id \a id inline point_with_id_t from_vec(const point_with_id_t& a, const point_xy_t& vec, const int64_t id = -1) { using boost::get; LocalGeographicCS cs(get<LAT>(a), get<LON>(a)); const boost::tuple<double, double>& ll = cs.xy2ll(get<X>(vec), get<Y>(vec)); return boost::make_tuple(get<LAT>(ll), get<LON>(ll), id); } inline double abs( const boost::tuple< double, double > &v ) { using boost::get; using boost::math::hypot; return hypot( get<X>(v), get<Y>(v) ); } //! Calculate the distance between (metric) a and b inline double dist(const point_xy_t& a, const point_xy_t& b) { using boost::get; return abs(boost::make_tuple(get<X>(b) - get<X>(a), get<Y>(b) - get<Y>(a))); } //! Normalize the vector \a vec inline void normalize(boost::tuple<double, double>& vec) { using boost::get; const double length = abs(vec); assert(length != 0 && "The given vector's length is 0."); vec = boost::make_tuple(get<X>(vec) / length, get<Y>(vec) / length); } //! Calculate the distance between (gnss) a and b inline double dist( const point_with_id_t& a, const point_with_id_t& b ) { return abs(vec(a, b)); } inline double scalar_product( const boost::tuple< double, double >& a, const boost::tuple< double, double >& b ) { using boost::get; return get<X>(a) * get<X>(b) + get<Y>(a) * get<Y>(b); } //! Project p on line inline point_xy_t projected(const point_xy_t& p, const vertex_container_t &line, double* angle=0, std::size_t* index=0, std::size_t* previous_index=0, std::size_t* subsequent_index=0) { double min_distance = -1.0; double const px = boost::get<LLet::X>(p); double const py = boost::get<LLet::Y>(p); point_xy_t min_point = p; size_t const size = line.size(); for (std::size_t i=1; i<size; ++i) { const double& ax = boost::get<LLet::X>(line[i-1]); const double& ay = boost::get<LLet::Y>(line[i-1]); const double& bx = boost::get<LLet::X>(line[i]); const double& by = boost::get<LLet::Y>(line[i]); point_xy_t const AP = point_xy_t(px-ax, py-ay); point_xy_t const AB = point_xy_t(bx-ax, by-ay); double const scalar_product_ab = scalar_product(AB, AB); double const lambda = scalar_product(AP, AB) / ( scalar_product_ab == 0.0 ? 1.0 : scalar_product_ab ); double distance = 0.0; point_xy_t c; if (lambda <= 0.0) { c = line[i-1]; } else if (lambda < 1.0) { c = point_xy_t(ax + lambda*(bx-ax), ay + lambda*(by-ay)); } else { c = line[i]; } distance = dist(p, c); if (min_distance < 0.0 || distance < min_distance) { min_distance = distance; min_point = c; if (angle) { *angle = atan2(boost::get<Y>(line[i])-boost::get<Y>(line[i-1]), boost::get<X>(line[i])-boost::get<X>(line[i-1])); } if (index) { *index = lambda < 0.5? i-1 : i; } if (subsequent_index) { *subsequent_index = i; } if (previous_index) { *previous_index = i-1; } } } return min_point; } inline double angle( const boost::tuple< double, double >& a, const boost::tuple< double, double >& b ) { using boost::get; double sp = scalar_product(a, b); double cos_phi = sp / (abs(a) * abs(b)); // sign for angle: test cross product double crossp_z = get<X>(a) * get<Y>(b) - get<Y>(a) * get<X>(b); double signum = boost::math::sign(crossp_z); double phi = normalize_angle(signum * std::acos(cos_phi)); return phi; } template< typename T1, typename T2 > inline bool inrange(const T1& val, const T2& lo, const T2& hi) { return val >= lo && val <= hi; } /*! Interpolate the given points using a Catmull-Rom polygon. * Any \a ratio between 0 and 1 will interpolate in between \a p1 and \a p2. */ inline point_xy_t interpolate_spline(const point_xy_t& p0, const point_xy_t& p1, const point_xy_t& p2, const point_xy_t& p3, double ratio) { /* Catmull-Rom coefficients: * * a0 = -0.5*p0 + 1.5*p1 - 1.5*p2 + 0.5*p3 * a1 = p0 - 2.5*p1 + 2*p2 - 0.5*p3 * a2 = -0.5*p0 + 0.5*p2 */ const point_xy_t a0 = boost::make_tuple(-0.5 * boost::get<X>(p0) + 1.5 * boost::get<X>(p1) - 1.5 * boost::get<X>(p2) + 0.5 * boost::get<X>(p3), -0.5 * boost::get<Y>(p0) + 1.5 * boost::get<Y>(p1) - 1.5 * boost::get<Y>(p2) + 0.5 * boost::get<Y>(p3)); const point_xy_t a1 = boost::make_tuple(boost::get<X>(p0) - 2.5 * boost::get<X>(p1) + 2. * boost::get<X>(p2) - 0.5 * boost::get<X>(p3), boost::get<Y>(p0) - 2.5 * boost::get<Y>(p1) + 2. * boost::get<Y>(p2) - 0.5 * boost::get<Y>(p3)); const point_xy_t a2 = boost::make_tuple(-0.5 * boost::get<X>(p0) + 0.5 * boost::get<X>(p2), -0.5 * boost::get<Y>(p0) + 0.5 * boost::get<Y>(p2)); const double ratio_square = ratio * ratio; // Catmull-Rom polynom: result = a0 * ratio³ + a1 * ratio² + a2 * ratio + p1 return boost::make_tuple(boost::get<X>(a0) * ratio * ratio_square + boost::get<X>(a1) * ratio_square + boost::get<X>(a2) * ratio + boost::get<X>(p1), boost::get<Y>(a0) * ratio * ratio_square + boost::get<Y>(a1) * ratio_square + boost::get<Y>(a2) * ratio + boost::get<Y>(p1)); } //! Calculate the dot product for vector \a and vector \b inline double dot(const point_xy_t& a, const point_xy_t& b) { return boost::get<LLet::X>(a) * boost::get<LLet::X>(b) + boost::get<LLet::Y>(a) * boost::get<LLet::Y>(b); } }
34
176
0.618481
brand666
132c0abf222827a78c779e15a77a5978f342774e
29,723
cpp
C++
src/plugPikiNishimura/Spider.cpp
doldecomp/pikmin
8c8c20721ecb2a19af8e50a4bdebdba90c9a27ed
[ "Unlicense" ]
27
2021-09-28T00:33:11.000Z
2021-11-18T19:38:40.000Z
src/plugPikiNishimura/Spider.cpp
doldecomp/pikmin
8c8c20721ecb2a19af8e50a4bdebdba90c9a27ed
[ "Unlicense" ]
null
null
null
src/plugPikiNishimura/Spider.cpp
doldecomp/pikmin
8c8c20721ecb2a19af8e50a4bdebdba90c9a27ed
[ "Unlicense" ]
null
null
null
#include "types.h" /* * --INFO-- * Address: ........ * Size: 00009C */ void _Error(char*, ...) { // UNUSED FUNCTION } /* * --INFO-- * Address: ........ * Size: 0000F0 */ void _Print(char*, ...) { // UNUSED FUNCTION } /* * --INFO-- * Address: 80152794 * Size: 0009C8 */ SpiderProp::SpiderProp() { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x370(r1) stw r31, 0x36C(r1) mr r31, r3 stw r30, 0x368(r1) stw r29, 0x364(r1) stw r28, 0x360(r1) bl -0x4EE8 lis r3, 0x8022 addi r0, r3, 0x738C lis r3, 0x8022 stw r0, 0x1EC(r31) addi r0, r3, 0x737C stw r0, 0x1EC(r31) li r7, 0 lis r3, 0x802D stw r7, 0x1FC(r31) subi r6, r3, 0xBA0 lis r4, 0x802D stw r7, 0x1F8(r31) subi r3, r4, 0xE84 addi r0, r6, 0xC stw r7, 0x1F4(r31) addi r5, r1, 0x1B0 addi r4, r31, 0x200 stw r3, 0x1F0(r31) addi r3, r31, 0x204 stw r6, 0x54(r31) stw r0, 0x1EC(r31) stw r7, 0x200(r31) lwz r0, -0x398(r13) stw r0, 0x1B8(r1) lwz r0, 0x1B8(r1) stw r0, 0x1B0(r1) bl -0xF3DA0 lis r3, 0x802A addi r30, r3, 0x6098 stw r30, 0x20C(r31) addi r5, r1, 0x1AC addi r3, r31, 0x214 lfs f0, -0x5780(r2) addi r4, r31, 0x200 stfs f0, 0x210(r31) lwz r0, -0x394(r13) stw r0, 0x1C0(r1) lwz r0, 0x1C0(r1) stw r0, 0x1AC(r1) bl -0xF3DD4 stw r30, 0x21C(r31) addi r5, r1, 0x1A8 addi r3, r31, 0x224 lfs f0, -0x577C(r2) addi r4, r31, 0x200 stfs f0, 0x220(r31) lwz r0, -0x390(r13) stw r0, 0x1C8(r1) lwz r0, 0x1C8(r1) stw r0, 0x1A8(r1) bl -0xF3E00 stw r30, 0x22C(r31) addi r5, r1, 0x1A4 addi r3, r31, 0x234 lfs f0, -0x5778(r2) addi r4, r31, 0x200 stfs f0, 0x230(r31) lwz r0, -0x38C(r13) stw r0, 0x1D0(r1) lwz r0, 0x1D0(r1) stw r0, 0x1A4(r1) bl -0xF3E2C stw r30, 0x23C(r31) addi r5, r1, 0x1A0 addi r3, r31, 0x244 lfs f0, -0x5774(r2) addi r4, r31, 0x200 stfs f0, 0x240(r31) lwz r0, -0x388(r13) stw r0, 0x1D8(r1) lwz r0, 0x1D8(r1) stw r0, 0x1A0(r1) bl -0xF3E58 stw r30, 0x24C(r31) addi r5, r1, 0x19C addi r3, r31, 0x254 lfs f0, -0x5770(r2) addi r4, r31, 0x200 stfs f0, 0x250(r31) lwz r0, -0x384(r13) stw r0, 0x1E0(r1) lwz r0, 0x1E0(r1) stw r0, 0x19C(r1) bl -0xF3E84 stw r30, 0x25C(r31) addi r5, r1, 0x198 addi r3, r31, 0x264 lfs f0, -0x576C(r2) addi r4, r31, 0x200 stfs f0, 0x260(r31) lwz r0, -0x380(r13) stw r0, 0x1E8(r1) lwz r0, 0x1E8(r1) stw r0, 0x198(r1) bl -0xF3EB0 stw r30, 0x26C(r31) addi r5, r1, 0x194 addi r3, r31, 0x274 lfs f0, -0x5768(r2) addi r4, r31, 0x200 stfs f0, 0x270(r31) lwz r0, -0x37C(r13) stw r0, 0x1F0(r1) lwz r0, 0x1F0(r1) stw r0, 0x194(r1) bl -0xF3EDC stw r30, 0x27C(r31) addi r5, r1, 0x190 addi r3, r31, 0x284 lfs f0, -0x5764(r2) addi r4, r31, 0x200 stfs f0, 0x280(r31) lwz r0, -0x378(r13) stw r0, 0x1F8(r1) lwz r0, 0x1F8(r1) stw r0, 0x190(r1) bl -0xF3F08 stw r30, 0x28C(r31) addi r5, r1, 0x18C addi r3, r31, 0x294 lfs f0, -0x5760(r2) addi r4, r31, 0x200 stfs f0, 0x290(r31) lwz r0, -0x374(r13) stw r0, 0x200(r1) lwz r0, 0x200(r1) stw r0, 0x18C(r1) bl -0xF3F34 stw r30, 0x29C(r31) addi r5, r1, 0x188 addi r3, r31, 0x2A4 lfs f0, -0x5764(r2) addi r4, r31, 0x200 stfs f0, 0x2A0(r31) lwz r0, -0x370(r13) stw r0, 0x208(r1) lwz r0, 0x208(r1) stw r0, 0x188(r1) bl -0xF3F60 stw r30, 0x2AC(r31) addi r5, r1, 0x184 addi r3, r31, 0x2B4 lfs f0, -0x575C(r2) addi r4, r31, 0x200 stfs f0, 0x2B0(r31) lwz r0, -0x36C(r13) stw r0, 0x210(r1) lwz r0, 0x210(r1) stw r0, 0x184(r1) bl -0xF3F8C stw r30, 0x2BC(r31) addi r5, r1, 0x180 addi r3, r31, 0x2C4 lfs f0, -0x5758(r2) addi r4, r31, 0x200 stfs f0, 0x2C0(r31) lwz r0, -0x368(r13) stw r0, 0x218(r1) lwz r0, 0x218(r1) stw r0, 0x180(r1) bl -0xF3FB8 stw r30, 0x2CC(r31) addi r5, r1, 0x17C addi r3, r31, 0x2D4 lfs f0, -0x5754(r2) addi r4, r31, 0x200 stfs f0, 0x2D0(r31) lwz r0, -0x364(r13) stw r0, 0x220(r1) lwz r0, 0x220(r1) stw r0, 0x17C(r1) bl -0xF3FE4 stw r30, 0x2DC(r31) addi r5, r1, 0x178 addi r3, r31, 0x2E4 lfs f0, -0x5754(r2) addi r4, r31, 0x200 stfs f0, 0x2E0(r31) lwz r0, -0x360(r13) stw r0, 0x228(r1) lwz r0, 0x228(r1) stw r0, 0x178(r1) bl -0xF4010 stw r30, 0x2EC(r31) addi r5, r1, 0x174 addi r3, r31, 0x2F4 lfs f0, -0x5750(r2) addi r4, r31, 0x200 stfs f0, 0x2F0(r31) lwz r0, -0x35C(r13) stw r0, 0x230(r1) lwz r0, 0x230(r1) stw r0, 0x174(r1) bl -0xF403C stw r30, 0x2FC(r31) addi r5, r1, 0x170 addi r3, r31, 0x304 lfs f0, -0x574C(r2) addi r4, r31, 0x200 stfs f0, 0x300(r31) lwz r0, -0x358(r13) stw r0, 0x238(r1) lwz r0, 0x238(r1) stw r0, 0x170(r1) bl -0xF4068 stw r30, 0x30C(r31) addi r5, r1, 0x16C addi r3, r31, 0x314 lfs f0, -0x5748(r2) addi r4, r31, 0x200 stfs f0, 0x310(r31) lwz r0, -0x354(r13) stw r0, 0x240(r1) lwz r0, 0x240(r1) stw r0, 0x16C(r1) bl -0xF4094 stw r30, 0x31C(r31) addi r5, r1, 0x168 addi r3, r31, 0x324 lfs f0, -0x5744(r2) addi r4, r31, 0x200 stfs f0, 0x320(r31) lwz r0, -0x350(r13) stw r0, 0x248(r1) lwz r0, 0x248(r1) stw r0, 0x168(r1) bl -0xF40C0 stw r30, 0x32C(r31) addi r5, r1, 0x164 addi r3, r31, 0x334 lfs f0, -0x5740(r2) addi r4, r31, 0x200 stfs f0, 0x330(r31) lwz r0, -0x34C(r13) stw r0, 0x250(r1) lwz r0, 0x250(r1) stw r0, 0x164(r1) bl -0xF40EC stw r30, 0x33C(r31) addi r5, r1, 0x160 addi r3, r31, 0x344 lfs f0, -0x573C(r2) addi r4, r31, 0x200 stfs f0, 0x340(r31) lwz r0, -0x348(r13) stw r0, 0x258(r1) lwz r0, 0x258(r1) stw r0, 0x160(r1) bl -0xF4118 stw r30, 0x34C(r31) addi r5, r1, 0x15C addi r3, r31, 0x354 lfs f0, -0x5738(r2) addi r4, r31, 0x200 stfs f0, 0x350(r31) lwz r0, -0x344(r13) stw r0, 0x260(r1) lwz r0, 0x260(r1) stw r0, 0x15C(r1) bl -0xF4144 stw r30, 0x35C(r31) addi r5, r1, 0x158 addi r3, r31, 0x364 lfs f0, -0x5734(r2) addi r4, r31, 0x200 stfs f0, 0x360(r31) lwz r0, -0x340(r13) stw r0, 0x268(r1) lwz r0, 0x268(r1) stw r0, 0x158(r1) bl -0xF4170 stw r30, 0x36C(r31) addi r5, r1, 0x154 addi r3, r31, 0x374 lfs f0, -0x5754(r2) addi r4, r31, 0x200 stfs f0, 0x370(r31) lwz r0, -0x33C(r13) stw r0, 0x270(r1) lwz r0, 0x270(r1) stw r0, 0x154(r1) bl -0xF419C stw r30, 0x37C(r31) addi r5, r1, 0x150 addi r3, r31, 0x384 lfs f0, -0x5730(r2) addi r4, r31, 0x200 stfs f0, 0x380(r31) lwz r0, -0x338(r13) stw r0, 0x278(r1) lwz r0, 0x278(r1) stw r0, 0x150(r1) bl -0xF41C8 stw r30, 0x38C(r31) addi r5, r1, 0x14C addi r3, r31, 0x394 lfs f0, -0x572C(r2) addi r4, r31, 0x200 stfs f0, 0x390(r31) lwz r0, -0x334(r13) stw r0, 0x280(r1) lwz r0, 0x280(r1) stw r0, 0x14C(r1) bl -0xF41F4 stw r30, 0x39C(r31) addi r5, r1, 0x148 addi r3, r31, 0x3A4 lfs f0, -0x5728(r2) addi r4, r31, 0x200 stfs f0, 0x3A0(r31) lwz r0, -0x330(r13) stw r0, 0x288(r1) lwz r0, 0x288(r1) stw r0, 0x148(r1) bl -0xF4220 stw r30, 0x3AC(r31) addi r5, r1, 0x144 addi r3, r31, 0x3B4 lfs f0, -0x572C(r2) addi r4, r31, 0x200 stfs f0, 0x3B0(r31) lwz r0, -0x32C(r13) stw r0, 0x290(r1) lwz r0, 0x290(r1) stw r0, 0x144(r1) bl -0xF424C stw r30, 0x3BC(r31) addi r5, r1, 0x140 addi r3, r31, 0x3C4 lfs f0, -0x5724(r2) addi r4, r31, 0x200 stfs f0, 0x3C0(r31) lwz r0, -0x328(r13) stw r0, 0x298(r1) lwz r0, 0x298(r1) stw r0, 0x140(r1) bl -0xF4278 stw r30, 0x3CC(r31) addi r5, r1, 0x13C addi r3, r31, 0x3D4 lfs f0, -0x5720(r2) addi r4, r31, 0x200 stfs f0, 0x3D0(r31) lwz r0, -0x324(r13) stw r0, 0x2A0(r1) lwz r0, 0x2A0(r1) stw r0, 0x13C(r1) bl -0xF42A4 stw r30, 0x3DC(r31) addi r5, r1, 0x138 addi r3, r31, 0x3E4 lfs f0, -0x571C(r2) addi r4, r31, 0x200 stfs f0, 0x3E0(r31) lwz r0, -0x320(r13) stw r0, 0x2A8(r1) lwz r0, 0x2A8(r1) stw r0, 0x138(r1) bl -0xF42D0 stw r30, 0x3EC(r31) addi r5, r1, 0x134 addi r3, r31, 0x3F4 lfs f0, -0x5720(r2) addi r4, r31, 0x200 stfs f0, 0x3F0(r31) lwz r0, -0x31C(r13) stw r0, 0x2B0(r1) lwz r0, 0x2B0(r1) stw r0, 0x134(r1) bl -0xF42FC stw r30, 0x3FC(r31) addi r5, r1, 0x130 addi r3, r31, 0x404 lfs f0, -0x5728(r2) addi r4, r31, 0x200 stfs f0, 0x400(r31) lwz r0, -0x318(r13) stw r0, 0x2B8(r1) lwz r0, 0x2B8(r1) stw r0, 0x130(r1) bl -0xF4328 stw r30, 0x40C(r31) addi r5, r1, 0x12C addi r3, r31, 0x414 lfs f0, -0x5718(r2) addi r4, r31, 0x200 stfs f0, 0x410(r31) lwz r0, -0x314(r13) stw r0, 0x2C0(r1) lwz r0, 0x2C0(r1) stw r0, 0x12C(r1) bl -0xF4354 stw r30, 0x41C(r31) addi r5, r1, 0x128 addi r3, r31, 0x424 lfs f0, -0x5714(r2) addi r4, r31, 0x200 stfs f0, 0x420(r31) lwz r0, -0x310(r13) stw r0, 0x2C8(r1) lwz r0, 0x2C8(r1) stw r0, 0x128(r1) bl -0xF4380 stw r30, 0x42C(r31) addi r5, r1, 0x124 addi r3, r31, 0x434 lfs f0, -0x5710(r2) addi r4, r31, 0x200 stfs f0, 0x430(r31) lwz r0, -0x30C(r13) stw r0, 0x2D0(r1) lwz r0, 0x2D0(r1) stw r0, 0x124(r1) bl -0xF43AC stw r30, 0x43C(r31) addi r5, r1, 0x120 addi r3, r31, 0x444 lfs f0, -0x570C(r2) addi r4, r31, 0x200 stfs f0, 0x440(r31) lwz r0, -0x308(r13) stw r0, 0x2D8(r1) lwz r0, 0x2D8(r1) stw r0, 0x120(r1) bl -0xF43D8 stw r30, 0x44C(r31) addi r5, r1, 0x11C addi r3, r31, 0x454 lfs f0, -0x5708(r2) addi r4, r31, 0x200 stfs f0, 0x450(r31) lwz r0, -0x304(r13) stw r0, 0x2E0(r1) lwz r0, 0x2E0(r1) stw r0, 0x11C(r1) bl -0xF4404 stw r30, 0x45C(r31) addi r5, r1, 0x118 addi r3, r31, 0x464 lfs f0, -0x5704(r2) addi r4, r31, 0x200 stfs f0, 0x460(r31) lwz r0, -0x300(r13) stw r0, 0x2E8(r1) lwz r0, 0x2E8(r1) stw r0, 0x118(r1) bl -0xF4430 stw r30, 0x46C(r31) addi r5, r1, 0x114 addi r3, r31, 0x474 lfs f0, -0x5700(r2) addi r4, r31, 0x200 stfs f0, 0x470(r31) lwz r0, -0x2FC(r13) stw r0, 0x2F0(r1) lwz r0, 0x2F0(r1) stw r0, 0x114(r1) bl -0xF445C stw r30, 0x47C(r31) addi r5, r1, 0x110 addi r3, r31, 0x484 lfs f0, -0x56FC(r2) addi r4, r31, 0x200 stfs f0, 0x480(r31) lwz r0, -0x2F8(r13) stw r0, 0x2F8(r1) lwz r0, 0x2F8(r1) stw r0, 0x110(r1) bl -0xF4488 stw r30, 0x48C(r31) addi r5, r1, 0x10C addi r3, r31, 0x494 lfs f0, -0x5770(r2) addi r4, r31, 0x200 stfs f0, 0x490(r31) lwz r0, -0x2F4(r13) stw r0, 0x300(r1) lwz r0, 0x300(r1) stw r0, 0x10C(r1) bl -0xF44B4 stw r30, 0x49C(r31) addi r5, r1, 0x108 addi r3, r31, 0x4A4 lfs f0, -0x5770(r2) addi r4, r31, 0x200 stfs f0, 0x4A0(r31) lwz r0, -0x2F0(r13) stw r0, 0x308(r1) lwz r0, 0x308(r1) stw r0, 0x108(r1) bl -0xF44E0 stw r30, 0x4AC(r31) addi r5, r1, 0x104 addi r3, r31, 0x4B4 lfs f0, -0x5754(r2) addi r4, r31, 0x200 stfs f0, 0x4B0(r31) lwz r0, -0x2EC(r13) stw r0, 0x310(r1) lwz r0, 0x310(r1) stw r0, 0x104(r1) bl -0xF450C stw r30, 0x4BC(r31) addi r5, r1, 0x100 addi r3, r31, 0x4C4 lfs f0, -0x5754(r2) addi r4, r31, 0x200 stfs f0, 0x4C0(r31) lwz r0, -0x2E8(r13) stw r0, 0x318(r1) lwz r0, 0x318(r1) stw r0, 0x100(r1) bl -0xF4538 stw r30, 0x4CC(r31) addi r5, r1, 0xFC addi r3, r31, 0x4D4 lfs f0, -0x56F8(r2) addi r4, r31, 0x200 stfs f0, 0x4D0(r31) lwz r0, -0x2E4(r13) stw r0, 0x320(r1) lwz r0, 0x320(r1) stw r0, 0xFC(r1) bl -0xF4564 stw r30, 0x4DC(r31) addi r5, r1, 0xF8 addi r3, r31, 0x4E4 lfs f0, -0x5714(r2) addi r4, r31, 0x200 stfs f0, 0x4E0(r31) lwz r0, -0x2E0(r13) stw r0, 0x328(r1) lwz r0, 0x328(r1) stw r0, 0xF8(r1) bl -0xF4590 stw r30, 0x4EC(r31) addi r5, r1, 0xF4 addi r3, r31, 0x4F4 lfs f0, -0x56F4(r2) addi r4, r31, 0x200 stfs f0, 0x4F0(r31) lwz r0, -0x2DC(r13) stw r0, 0x330(r1) lwz r0, 0x330(r1) stw r0, 0xF4(r1) bl -0xF45BC lis r3, 0x802A addi r29, r3, 0x60C4 stw r29, 0x4FC(r31) li r30, 0x1 addi r5, r1, 0xF0 stw r30, 0x500(r31) addi r3, r31, 0x504 addi r4, r31, 0x200 lwz r0, -0x2D8(r13) stw r0, 0x338(r1) lwz r0, 0x338(r1) stw r0, 0xF0(r1) bl -0xF45F0 stw r29, 0x50C(r31) li r28, 0x2 addi r5, r1, 0xEC stw r28, 0x510(r31) addi r3, r31, 0x514 addi r4, r31, 0x200 lwz r0, -0x2D4(r13) stw r0, 0x340(r1) lwz r0, 0x340(r1) stw r0, 0xEC(r1) bl -0xF461C stw r29, 0x51C(r31) addi r5, r1, 0xE8 addi r3, r31, 0x524 stw r28, 0x520(r31) addi r4, r31, 0x200 lwz r0, -0x2D0(r13) stw r0, 0x348(r1) lwz r0, 0x348(r1) stw r0, 0xE8(r1) bl -0xF4644 stw r29, 0x52C(r31) li r0, 0x4 addi r5, r1, 0xE4 stw r0, 0x530(r31) addi r3, r31, 0x534 addi r4, r31, 0x200 lwz r0, -0x2CC(r13) stw r0, 0x350(r1) lwz r0, 0x350(r1) stw r0, 0xE4(r1) bl -0xF4670 stw r29, 0x53C(r31) addi r5, r1, 0xE0 addi r3, r31, 0x544 stw r30, 0x540(r31) addi r4, r31, 0x200 lwz r0, -0x2C8(r13) stw r0, 0x358(r1) lwz r0, 0x358(r1) stw r0, 0xE0(r1) bl -0xF4698 stw r29, 0x54C(r31) mr r3, r31 stw r30, 0x550(r31) lfs f1, -0x5718(r2) stfs f1, 0x10(r31) lfs f0, -0x5730(r2) stfs f0, 0x30(r31) stfs f1, 0x40(r31) lwz r0, 0x374(r1) lwz r31, 0x36C(r1) lwz r30, 0x368(r1) lwz r29, 0x364(r1) lwz r28, 0x360(r1) addi r1, r1, 0x370 mtlr r0 blr */ } /* * --INFO-- * Address: 8015315C * Size: 000140 */ Spider::Spider(CreatureProp*) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x20(r1) stw r31, 0x1C(r1) mr r31, r3 stw r30, 0x18(r1) stw r29, 0x14(r1) bl -0x5300 lis r3, 0x802D subi r0, r3, 0xD80 stw r0, 0x0(r31) addi r3, r31, 0x3CC bl -0xE9C5C li r3, 0x14 bl -0x10C190 addi r30, r3, 0 mr. r3, r30 beq- .loc_0x50 li r4, 0x18 bl -0xCA578 .loc_0x50: stw r30, 0x220(r31) li r3, 0xC bl -0x10C1B0 addi r30, r3, 0 mr. r3, r30 beq- .loc_0x70 mr r4, r31 bl 0x678 .loc_0x70: stw r30, 0x3C0(r31) li r3, 0x68C bl -0x10C1D0 addi r30, r3, 0 mr. r3, r30 beq- .loc_0x90 mr r4, r31 bl 0x3908 .loc_0x90: stw r30, 0x3C4(r31) li r30, 0 subi r0, r13, 0x2C4 stw r30, 0x3DC(r31) addi r3, r31, 0x3CC stw r30, 0x3D8(r31) stw r30, 0x3D4(r31) stw r0, 0x3D0(r31) bl -0xE9BA8 li r3, 0x24 bl -0x10C210 mr. r29, r3 beq- .loc_0x11C lis r3, 0x8022 addi r0, r3, 0x738C lis r3, 0x8022 stw r0, 0x0(r29) addi r0, r3, 0x737C stw r0, 0x0(r29) addi r3, r29, 0 subi r4, r13, 0x2C4 stw r30, 0x10(r29) stw r30, 0xC(r29) stw r30, 0x8(r29) bl -0x12E378 lis r3, 0x8023 subi r0, r3, 0x71E0 stw r0, 0x0(r29) addi r3, r29, 0 subi r4, r13, 0x2C4 bl -0x112B28 lis r3, 0x802D subi r0, r3, 0xE2C stw r0, 0x0(r29) stw r31, 0x20(r29) .loc_0x11C: stw r29, 0x760(r31) mr r3, r31 lwz r0, 0x24(r1) lwz r31, 0x1C(r1) lwz r30, 0x18(r1) lwz r29, 0x14(r1) addi r1, r1, 0x20 mtlr r0 blr */ } /* * --INFO-- * Address: 8015329C * Size: 000008 */ void Spider::getiMass() { /* .loc_0x0: lfs f1, -0x5770(r2) blr */ } /* * --INFO-- * Address: 801532A4 * Size: 0000C4 */ void Spider::init(Vector3f&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) li r0, 0x1 stwu r1, -0x18(r1) stw r31, 0x14(r1) li r31, 0 stw r30, 0x10(r1) addi r30, r3, 0 addi r4, r30, 0 lfs f0, -0x56F0(r2) stfs f0, 0x270(r3) stb r0, 0x2BC(r3) stb r31, 0x2BB(r3) stb r31, 0x3B8(r3) stb r0, 0x3B9(r3) stb r31, 0x3BA(r3) stb r0, 0x3BB(r3) stw r31, 0x3BC(r3) lwz r3, 0x3C0(r3) bl 0x570 lwz r3, 0x3C4(r30) mr r4, r30 bl 0x399C stb r31, 0x3C9(r30) lis r31, 0x6C65 addi r4, r31, 0x6731 lfs f0, -0x56EC(r2) li r5, 0x3 stfs f0, 0x5AC(r30) lwz r3, 0x220(r30) bl -0xC9714 lwz r3, 0x220(r30) addi r4, r31, 0x6732 li r5, 0x3 bl -0xC9724 lwz r3, 0x220(r30) addi r4, r31, 0x6733 li r5, 0x3 bl -0xC9734 lwz r3, 0x220(r30) addi r4, r31, 0x6734 li r5, 0x3 bl -0xC9744 lwz r0, 0x1C(r1) lwz r31, 0x14(r1) lwz r30, 0x10(r1) addi r1, r1, 0x18 mtlr r0 blr */ } /* * --INFO-- * Address: 80153368 * Size: 000058 */ void Spider::doKill() { /* .loc_0x0: mflr r0 li r4, 0 stw r0, 0x4(r1) li r0, 0 stwu r1, -0x18(r1) stw r31, 0x14(r1) addi r31, r3, 0 stb r0, 0x3B8(r3) stb r0, 0x2B8(r3) stb r0, 0x2B9(r3) lwz r3, 0x3C4(r3) bl 0x3444 addi r3, r31, 0x3CC bl -0x112D8C lwz r3, 0x3168(r13) mr r4, r31 bl -0x1210 lwz r0, 0x1C(r1) lwz r31, 0x14(r1) addi r1, r1, 0x18 mtlr r0 blr */ } /* * --INFO-- * Address: 801533C0 * Size: 000028 */ void Spider::exitCourse() { /* .loc_0x0: mflr r0 li r4, 0x1 stw r0, 0x4(r1) stwu r1, -0x8(r1) lwz r3, 0x3C4(r3) bl 0x3404 lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr */ } /* * --INFO-- * Address: 801533E8 * Size: 00006C */ void Spider::update() { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x20(r1) stw r31, 0x1C(r1) mr r31, r3 lwz r12, 0x0(r31) lwz r12, 0x104(r12) mtlr r12 blrl lwz r3, 0x3C4(r31) bl 0x635C mr r3, r31 bl -0xC641C lwz r4, 0x2DEC(r13) mr r3, r31 lfs f1, 0x28C(r4) bl -0xC4E4C mr r3, r31 lwz r12, 0x0(r31) lwz r12, 0x108(r12) mtlr r12 blrl lwz r0, 0x24(r1) lwz r31, 0x1C(r1) addi r1, r1, 0x20 mtlr r0 blr */ } /* * --INFO-- * Address: ........ * Size: 000100 */ void Spider::draw(Graphics&) { // UNUSED FUNCTION } /* * --INFO-- * Address: 80153454 * Size: 00014C */ void Spider::refresh(Graphics&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x60(r1) stfd f31, 0x58(r1) addi r0, r1, 0x14 addi r6, r1, 0x1C stfd f30, 0x50(r1) stw r31, 0x4C(r1) addi r31, r4, 0 mr r4, r0 stw r30, 0x48(r1) addi r30, r3, 0 lwz r5, 0x2F00(r13) lfs f0, 0x9C(r3) lwz r3, 0x4(r5) addi r5, r1, 0x18 lfs f1, 0x1410(r3) addi r7, r3, 0x1408 addi r3, r1, 0x34 fsubs f0, f1, f0 stfs f0, 0x1C(r1) lfs f1, 0x4(r7) lfs f0, 0x98(r30) fsubs f0, f1, f0 stfs f0, 0x18(r1) lfs f1, 0x0(r7) lfs f0, 0x94(r30) fsubs f0, f1, f0 stfs f0, 0x14(r1) bl -0x11C3AC lfs f31, 0x34(r1) lfs f0, -0x5730(r2) fmuls f1, f31, f31 lfs f30, 0x3C(r1) fmuls f0, f0, f0 fmuls f2, f30, f30 fadds f0, f1, f0 fadds f1, f2, f0 bl -0x1458AC lfs f0, -0x5730(r2) fcmpu cr0, f0, f1 beq- .loc_0xB0 fdivs f31, f31, f1 fdivs f30, f30, f1 .loc_0xB0: lfs f1, -0x56E8(r2) mr r5, r31 lwz r3, 0x3C4(r30) fmuls f31, f31, f1 lfs f2, -0x56E4(r2) lfs f0, 0x264(r3) fmuls f30, f30, f1 lfs f1, 0x98(r30) fadds f0, f0, f31 lfs f3, 0x26C(r3) fadds f2, f2, f1 fadds f1, f3, f30 stfs f0, 0x748(r30) stfs f2, 0x74C(r30) stfs f1, 0x750(r30) lwz r4, 0x3C4(r30) lfs f2, -0x575C(r2) lfs f1, 0x98(r30) lfs f0, 0x264(r4) fadds f1, f2, f1 stfs f0, 0x754(r30) stfs f1, 0x758(r30) lfs f0, 0x26C(r4) stfs f0, 0x75C(r30) lwz r3, 0x3C4(r30) lwz r4, 0x390(r30) bl 0x64EC lwz r3, 0x220(r30) addi r4, r31, 0 li r5, 0 bl -0xC9A90 lwz r0, 0x64(r1) lfd f31, 0x58(r1) lfd f30, 0x50(r1) lwz r31, 0x4C(r1) lwz r30, 0x48(r1) addi r1, r1, 0x60 mtlr r0 blr */ } /* * --INFO-- * Address: 801535A0 * Size: 000078 */ void Spider::drawShape(Graphics&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x18(r1) stw r31, 0x14(r1) mr r31, r4 stw r30, 0x10(r1) mr r30, r3 lwz r3, 0x390(r3) lwz r3, 0x0(r3) bl -0x11DFD0 lwz r12, 0x3B4(r31) lis r4, 0x803A mr r3, r31 lwz r12, 0x74(r12) subi r4, r4, 0x77C0 li r5, 0 mtlr r12 blrl lwz r3, 0x390(r30) mr r4, r31 lwz r5, 0x2E4(r31) li r6, 0 lwz r3, 0x0(r3) bl -0x123190 lwz r0, 0x1C(r1) lwz r31, 0x14(r1) lwz r30, 0x10(r1) addi r1, r1, 0x18 mtlr r0 blr */ } /* * --INFO-- * Address: 80153618 * Size: 000024 */ void Spider::doAI() { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x8(r1) lwz r3, 0x3C0(r3) bl 0x9E8 lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr */ } /* * --INFO-- * Address: 8015363C * Size: 000044 */ void Spider::doAnimation() { /* .loc_0x0: mflr r0 mr r4, r3 stw r0, 0x4(r1) stwu r1, -0x8(r1) lwz r0, 0x390(r3) cmplwi r0, 0 beq- .loc_0x34 lwz r12, 0x36C(r4) addi r3, r4, 0x33C lfs f1, 0x2D8(r4) lwz r12, 0xC(r12) mtlr r12 blrl .loc_0x34: lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr */ } /* * --INFO-- * Address: 80153680 * Size: 000160 */ void SpiderDrawer::draw(Graphics&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x68(r1) stfd f31, 0x60(r1) addi r0, r1, 0x14 addi r6, r1, 0x1C stfd f30, 0x58(r1) stw r31, 0x54(r1) stw r30, 0x50(r1) addi r30, r4, 0 mr r4, r0 stw r29, 0x4C(r1) mr r29, r3 lwz r5, 0x2F00(r13) lwz r31, 0x20(r3) lwz r3, 0x4(r5) addi r5, r1, 0x18 lfs f0, 0x9C(r31) lfs f1, 0x1410(r3) addi r7, r3, 0x1408 addi r3, r1, 0x34 fsubs f0, f1, f0 stfs f0, 0x1C(r1) lfs f1, 0x4(r7) lfs f0, 0x98(r31) fsubs f0, f1, f0 stfs f0, 0x18(r1) lfs f1, 0x0(r7) lfs f0, 0x94(r31) fsubs f0, f1, f0 stfs f0, 0x14(r1) bl -0x11C5E0 lfs f31, 0x34(r1) lfs f0, -0x5730(r2) fmuls f1, f31, f31 lfs f30, 0x3C(r1) fmuls f0, f0, f0 fmuls f2, f30, f30 fadds f0, f1, f0 fadds f1, f2, f0 bl -0x145AE0 lfs f0, -0x5730(r2) fcmpu cr0, f0, f1 beq- .loc_0xB8 fdivs f31, f31, f1 fdivs f30, f30, f1 .loc_0xB8: lfs f1, -0x56E8(r2) mr r5, r30 lwz r3, 0x3C4(r31) fmuls f31, f31, f1 lfs f2, -0x56E4(r2) lfs f0, 0x264(r3) fmuls f30, f30, f1 lfs f1, 0x98(r31) fadds f0, f0, f31 lfs f3, 0x26C(r3) fadds f2, f2, f1 fadds f1, f3, f30 stfs f0, 0x748(r31) stfs f2, 0x74C(r31) stfs f1, 0x750(r31) lwz r4, 0x3C4(r31) lfs f2, -0x575C(r2) lfs f1, 0x98(r31) lfs f0, 0x264(r4) fadds f1, f2, f1 stfs f0, 0x754(r31) stfs f1, 0x758(r31) lfs f0, 0x26C(r4) stfs f0, 0x75C(r31) lwz r3, 0x3C4(r31) lwz r4, 0x390(r31) bl 0x62B8 lwz r3, 0x20(r29) mr r4, r30 lwz r12, 0x0(r3) lwz r12, 0x120(r12) mtlr r12 blrl lwz r0, 0x6C(r1) lfd f31, 0x60(r1) lfd f30, 0x58(r1) lwz r31, 0x54(r1) lwz r30, 0x50(r1) lwz r29, 0x4C(r1) addi r1, r1, 0x68 mtlr r0 blr */ } /* * --INFO-- * Address: 801537E0 * Size: 000008 */ void Spider::isBossBgm() { /* .loc_0x0: lbz r3, 0x3B8(r3) blr */ } /* * --INFO-- * Address: 801537E8 * Size: 000050 */ void SpiderProp::read(RandomAccessStream&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x18(r1) stw r31, 0x14(r1) addi r31, r4, 0 stw r30, 0x10(r1) addi r30, r3, 0 bl -0xF4C6C addi r3, r30, 0x58 addi r4, r31, 0 bl -0xF4C78 addi r3, r30, 0x200 addi r4, r31, 0 bl -0xF4C84 lwz r0, 0x1C(r1) lwz r31, 0x14(r1) lwz r30, 0x10(r1) addi r1, r1, 0x18 mtlr r0 blr */ } /* * --INFO-- * Address: 80153838 * Size: 000008 */ void SpiderProp::@492 @read(RandomAccessStream&) { /* .loc_0x0: subi r3, r3, 0x1EC b -0x54 */ }
22.987626
48
0.459409
doldecomp
132ca133b0ff4c2658fd9fe83df277add8dd6e64
643
hpp
C++
DoremiEngine/Graphic/Include/Interface/Manager/CameraManager.hpp
meraz/doremi
452d08ebd10db50d9563c1cf97699571889ab18f
[ "MIT" ]
1
2020-03-23T15:42:05.000Z
2020-03-23T15:42:05.000Z
DoremiEngine/Graphic/Include/Interface/Manager/CameraManager.hpp
Meraz/ssp15
452d08ebd10db50d9563c1cf97699571889ab18f
[ "MIT" ]
null
null
null
DoremiEngine/Graphic/Include/Interface/Manager/CameraManager.hpp
Meraz/ssp15
452d08ebd10db50d9563c1cf97699571889ab18f
[ "MIT" ]
1
2020-03-23T15:42:06.000Z
2020-03-23T15:42:06.000Z
#pragma once #include <string> #include <DirectXMath.h> namespace DoremiEngine { namespace Graphic { class Camera; /** Builds new cameras and pushes cameras to the GPU */ class CameraManager { public: /** Creates a new Camera from the given projection matrix. */ virtual Camera* BuildNewCamera(DirectX::XMFLOAT4X4& p_projectionMatrix) = 0; /** Sends the matrices in the given camera class to the GPU */ virtual void PushCameraToDevice(const Camera& p_camera) = 0; }; } }
24.730769
88
0.553655
meraz
133148d1843538d811af1bca551d3c5e8334af9a
37
cpp
C++
test/autogen/list@take_back.cpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
9
2020-07-04T16:46:13.000Z
2022-01-09T21:59:31.000Z
test/autogen/list@take_back.cpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
null
null
null
test/autogen/list@take_back.cpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
1
2021-05-23T13:37:40.000Z
2021-05-23T13:37:40.000Z
#include "jln/mp/list/take_back.hpp"
18.5
36
0.756757
jonathanpoelen
1333f5dbe3611b240f862f1623adfd9346383c98
11,112
cpp
C++
genetics/grammar/SpaceShipGrammar.cpp
crest01/ShapeGenetics
7321f6484be668317ad763c0ca5e4d6cbfef8cd1
[ "MIT" ]
18
2017-04-26T13:53:43.000Z
2021-05-29T03:55:27.000Z
genetics/grammar/SpaceShipGrammar.cpp
crest01/ShapeGenetics
7321f6484be668317ad763c0ca5e4d6cbfef8cd1
[ "MIT" ]
null
null
null
genetics/grammar/SpaceShipGrammar.cpp
crest01/ShapeGenetics
7321f6484be668317ad763c0ca5e4d6cbfef8cd1
[ "MIT" ]
2
2017-10-17T10:32:01.000Z
2019-11-11T07:23:54.000Z
/* * SpaceShipGrammar.cpp * * Created on: Nov 2, 2015 * Author: Karl Haubenwallner */ #include <iostream> #include "operators/Generator.impl" #include "operators/ScopeOperators.impl" #include "operators/Resize.impl" #include "operators/Repeat.impl" #include "operators/Subdivide.impl" #include "operators/ComponentSplit.impl" #include "operators/Extrude.impl" #include "operators/RandomPath.impl" #include "operators/Duplicate.impl" #include "parameters/StaticParameter.h" #include "parameters/StaticRandom.h" #include "parameters/ParameterConversion.h" #include "parameters/Random.h" #include "parameters/ShapeParameter.h" #include "parameters/ScopeParameter.h" #include "parameters/ParameterOperations.h" #include "modifiers/DirectCall.h" #include "modifiers/RandomReseed.h" #include "modifiers/Discard.h" #include "modifiers/ScopeModifier.h" #include "CPU/StaticCall.h" #include "GeometryGeneratorInstanced.h" #include "SpaceShipGrammar.h" using namespace PGG; using namespace Shapes; using namespace Parameters; using namespace Scope; using namespace Operators; using namespace Modifiers; using namespace CPU; namespace PGA { namespace SpaceShip { void SpaceShipGrammar::initSymbols(SymbolManager& sm) { // start symbol, has no shape S = sm.createStart("S"); // Body element B = sm.createTerminal("B"); sm.addParameter<math::float3>(B, "size", math::float3(0.6f, 0.6f, 0.6f), math::float3(1.5f, 1.5f, 1.5f)); // Top (pyramid) element on top of body T_start = sm.createTerminal("T"); sm.addParameter<math::float3>(T_start, "size", math::float3(0.3f, 0.1f, 0.3f), math::float3(0.8f, 0.2f, 0.8f)); // Top (pyramid) element on top of body T_recursion = sm.createTerminal("t"); sm.addParameter<math::float3>(T_recursion, "size", math::float3(0.6f, 0.8f, 0.6f), math::float3(1.1f, 1.1f, 1.1f)); // Wing element W_start = sm.createTerminal("W"); sm.addParameter<math::float3>(W_start, "size", math::float3(0.3f, 0.2f, 0.2f), math::float3(1.2f, 0.5f, 1.0f)); sm.addParameter<float>(W_start, "forward/backward movement", -0.5f, 0.5f); W_recursion = sm.createTerminal("w"); sm.addParameter<math::float3>(W_recursion, "size", math::float3(0.6f, 0.9f, 0.7f), math::float3(1.2f, 1.0f, 1.2f)); sm.addParameter<float>(W_recursion, "forward/backward movement", -0.5f, 0.5f); sm.addPossibleChild(S, B, 1, 1.0f); sm.addPossibleChild(B, B, 1, 1.0f/3.0f); sm.addPossibleChild(B, W_start, 1, 1.0f/3.0f); sm.addPossibleChild(B, T_start, 1, 1.0f/3.0f); sm.addPossibleChild(W_start, W_recursion, 1, 1.0f); sm.addPossibleChild(W_recursion, W_recursion, 1, 0.9f); sm.addPossibleChild(T_start, T_recursion, 1, 1.0f); sm.addPossibleChild(T_recursion, T_recursion, 1, 1.0f); if (getNumPreparedShapes() != 1) { throw std::invalid_argument("Wrong number of shapes for the Grammar"); } } int SpaceShipGrammar::storeParameter(Symbol* symbol, PGG::Parameters::ParameterTable& pt) { if (symbol->id() == S) return -1; if (symbol->id() == B) { return storeBodyParameter(symbol, pt); } if (symbol->id() == T_start || symbol->id() == T_recursion) { return storeTopParameter(symbol, pt); } if (symbol->id() == W_start || symbol->id() == W_recursion) { return storeWingParameter(symbol, pt); } //std::cout << "no Parameters for Symbol id " << symbol->id() << std::endl; return -1; } int SpaceShipGrammar::storeBodyParameter(Symbol* s, PGG::Parameters::ParameterTable& pt) { int body_child = 0; int body_child_offset = 0; int top_child = 0; int top_child_offset = 0; int wing_child = 0; int wing_child_offset = 0; for (int i = 0; i < s->getChildren().size(); ++i) { Symbol* c = s->getChildren().at(i); if (c->id() == B) { body_child = 1; body_child_offset = c->getParamTableOffset(); continue; } if (c->id() == T_start) { top_child = 1; top_child_offset = c->getParamTableOffset(); continue; } if (c->id() == W_start) { wing_child = 1; wing_child_offset = c->getParamTableOffset(); continue; } } math::float3 size = s->getParameter()[0]->getValue<math::float3>(); int pt_offset = pt.storeParameters( size, // size of body part body_child, // attach another body part body_child_offset, // Param Layer of new body part top_child, // attach a top part top_child_offset, // Param Layer of top part wing_child, // attach a top part wing_child_offset); // Param Layer of top part return pt_offset; } int SpaceShipGrammar::storeTopParameter(Symbol* s, PGG::Parameters::ParameterTable& pt) { int top_child = 0; int top_child_offset = 0; for (int i = 0; i < s->getChildren().size(); ++i) { Symbol* c = s->getChildren().at(i); if (c->id() == T_recursion) { top_child = 1; top_child_offset = c->getParamTableOffset(); break; } } math::float3 size = s->getParameter()[0]->getValue<math::float3>(); int pt_offset = pt.storeParameters( size, // size of top part top_child, // attach a top part top_child_offset); // Param Layer of top part return pt_offset; } int SpaceShipGrammar::storeWingParameter(Symbol* s, PGG::Parameters::ParameterTable& pt) { int wing_child = 0; int wing_child_offset = 0; for (int i = 0; i < s->getChildren().size(); ++i) { Symbol* c = s->getChildren().at(i); if (c->id() == W_recursion) { wing_child = 1; wing_child_offset = c->getParamTableOffset(); break; } } math::float3 size = s->getParameter()[0]->getValue<math::float3>(); float movement = s->getParameter()[1]->getValue<float>(); int pt_offset = pt.storeParameters( size, // size of wing part movement, // movement of wing wing_child, // attach a top part wing_child_offset); // Param Layer of top part return pt_offset; } void SpaceShipGrammar::createAxiom(PGG::CPU::GrammarSystem& system, const int axiomId) { //forward declaratons for recursion class BodyRuleRecusion; class TopRule; class TopRuleRecursion; class WingRule; class WingRuleRecursion; class BodyRule; typedef CoordinateframeScope<int> SpaceShipscope; typedef PGA::InstancedShapeGenerator<SpaceShipscope, 0, true> SpaceShipGenerator; typedef Operators::Generator<SpaceShipGenerator> MyGenerate; static const int ParamLayer = 0; // offset 0: float3 size class SpaceShip : public Resize<DynamicFloat3<0, ParamLayer>, DirectCall<BodyRule> > { }; // offset 3: int 1/0 to enable next body part // offset 4: int to change paramtable for next body part // offset 5: int 1/0 to enable top part // offset 6: int to change paramtable for top part // offset 7: int 1/0 to build wings // offset 8: int to change paramtable for wings (equal for both) class BodyRule : public Translate<VecEx<math::float3, StaticFloat<0_p>, StaticFloat<0_p>, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::ZAxis>> >, //0 is starting point, so move the box half the size to the front StaticCall < Duplicate < DirectCall<MyGenerate>, // body part is being generated DirectCall < ChoosePath < DynamicInt<3, ParamLayer>, // extend body part DirectCall<Translate<VecEx<math::float3, StaticFloat<0_p>, StaticFloat<0_p>, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::ZAxis>> >, SetScopeAttachment<ParamLayer, DynamicInt<4, ParamLayer>, StaticCall<BodyRuleRecusion> > > > > // next body part >, DirectCall< ChoosePath < DynamicInt<5, ParamLayer>, // build top part DirectCall<Translate<VecEx<math::float3, StaticFloat<0_p>, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::YAxis>>, StaticFloat<0_p>>, SetScopeAttachment<ParamLayer, DynamicInt<6, ParamLayer>, StaticCall<TopRule> > > > > // start top >, DirectCall< ChoosePath < DynamicInt<7, ParamLayer>, //generate wings SetScopeAttachment<ParamLayer, DynamicInt<8, ParamLayer>, DirectCall< Duplicate < // mirror DirectCall<Translate<VecEx<math::float3, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::XAxis> >, StaticFloat<0_p>, StaticFloat<0_p>>, StaticCall<WingRule> > >, // wing right DirectCall<Rotate<StaticAxes<Axes::ZAxis>, StaticFloat<3.14159265359_p>, DirectCall<Translate<VecEx<math::float3, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::XAxis> >, StaticFloat<0_p>, StaticFloat<0_p>>, StaticCall<WingRule> > > > > >// wing left > > > > > > > { }; // offset 0: float3 size class BodyRuleRecusion : public Resize<DynamicFloat3<0, ParamLayer>, //adjust body part size DirectCall<BodyRule> // execute the recursion > { }; // offset 0: float3 size class TopRule : public Resize<DynamicFloat3<0, ParamLayer>, // initial top scale DirectCall<TopRuleRecursion > > {}; // offset 3: int 1/0 to enable next top part // offset 4: int to change paramtable for next top part class TopRuleRecursion : public Translate< VecEx<math::float3, StaticFloat<0_p>, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::YAxis>>, StaticFloat<0_p> >, //0 is starting point, so move the box half the size up Duplicate < DirectCall<MyGenerate>, // top part is being generated DirectCall<ChoosePath< DynamicInt<3, ParamLayer>, DirectCall< Translate< VecEx<math::float3, StaticFloat<0_p>, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::YAxis>>, StaticFloat<0_p> >, SetScopeAttachment<ParamLayer, DynamicInt<4, ParamLayer>, DirectCall< Resize<DynamicFloat3<0, ParamLayer>, DirectCall<TopRuleRecursion> > > > > > > > > > {}; // offset 0: float3 size // offset 3: float forward backward move class WingRule : public Resize<DynamicFloat3<0, ParamLayer>, // initial wing scale DirectCall<Translate<VecEx<math::float3, StaticFloat<0_p>, StaticFloat<0_p>, Mul<ShapeSizeAxis<Axes::ZAxis>, DynamicFloat<3, ParamLayer>>>, DirectCall<WingRuleRecursion > > > > {}; // offset 4: int 1/0 to enable next wing part // offset 5: int to change paramtable for next top part class WingRuleRecursion : public Translate< VecEx<math::float3, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::XAxis>>, StaticFloat<0_p>, StaticFloat<0_p> >, //0 is starting point, so move the box half the size up Duplicate < DirectCall<MyGenerate>, // wing part is being generated DirectCall<ChoosePath< DynamicInt<4, ParamLayer>, DirectCall< Translate< VecEx<math::float3, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::XAxis>>, StaticFloat<0_p>, StaticFloat<0_p> >, SetScopeAttachment<ParamLayer, DynamicInt<5, ParamLayer>, DirectCall< Resize<DynamicFloat3<0, ParamLayer>, DirectCall<Translate<VecEx<math::float3, StaticFloat<0_p>, StaticFloat<0_p>, Mul<ShapeSizeAxis<Axes::ZAxis>, DynamicFloat<3, ParamLayer>>>, // backward and forward move DirectCall<WingRuleRecursion> > > > > > > > > > > > {}; ScopedShape<Box, SpaceShipscope > spaceShipAxiom(Box(math::float3(1.0f)), SpaceShipscope(math::identity<math::float3x4>(), axiomId)); system.addAxiom<SpaceShip>(spaceShipAxiom); } }; // namespace SpaceShip }; // namespace PGA
32.491228
255
0.687635
crest01
1334b74368c4ff41bcb7911601ff771fd6f913bc
1,030
cpp
C++
leetcode.com/0187 Repeated DNA Sequences/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0187 Repeated DNA Sequences/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0187 Repeated DNA Sequences/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <iostream> #include <vector> #include <unordered_map> using namespace std; // https://leetcode.com/problems/repeated-dna-sequences/discuss/420527/Easy-Hashmap-bit-manipulation-solution-C%2B%2B class Solution { public: int char_to_bit(char c){ if(c=='A') return 0; if(c=='C') return 1; if(c=='G') return 2; if(c=='T') return 3; return 0; } vector<string> findRepeatedDnaSequences(string s) { int n= s.size(), mask=0, bitmask=(1<<20)-1; if(n==0) return {}; unordered_map<int, int> ht; vector<string> result; for(int i=0; i<10; i++){ mask= (mask<<2) | char_to_bit(s[i]); } ht[mask]++; for(int i=10; i<n; i++){ mask= ((mask<<2) & bitmask) | char_to_bit(s[i]); if(ht.find(mask)!=ht.end() && ht[mask]==1) result.push_back(s.substr(i-9, 10)); ht[mask]++; } return result; } };
25.75
117
0.500971
sky-bro
1336aa43e85bceb9b7c089950fe218bfcae5cd27
19,494
cpp
C++
src/Cello/test_Parameters.cpp
aoife-flood/enzo-e
ab8ebc4716fff22bed9f692daf0472ae6ffffe73
[ "BSD-3-Clause" ]
26
2019-02-12T19:39:13.000Z
2022-03-31T01:52:29.000Z
src/Cello/test_Parameters.cpp
aoife-flood/enzo-e
ab8ebc4716fff22bed9f692daf0472ae6ffffe73
[ "BSD-3-Clause" ]
128
2019-02-13T20:22:30.000Z
2022-03-29T20:21:00.000Z
src/Cello/test_Parameters.cpp
aoife-flood/enzo-e
ab8ebc4716fff22bed9f692daf0472ae6ffffe73
[ "BSD-3-Clause" ]
29
2019-02-12T19:37:51.000Z
2022-03-14T14:02:45.000Z
// See LICENSE_CELLO file for license and copyright information /// @file test_Parameters.cpp /// @author James Bordner (jobordner@ucsd.edu) /// @date Thu Feb 21 16:04:03 PST 2008 /// @brief Program implementing unit tests for the Parameters class //---------------------------------------------------------------------- #include <fstream> #include "main.hpp" #include "test.hpp" #include "parameters.hpp" //---------------------------------------------------------------------- /// @def CLOSE /// @brief Local definition for testing whether two scalars are close #define MACH_EPS cello::machine_epsilon(default_precision) #define CLOSE(a,b) ( cello::err_rel(a,b) < 2*MACH_EPS ) //---------------------------------------------------------------------- void generate_input() { std::fstream fp; fp.open ("test.in",std::fstream::out); // Groups // // Logical: // Integer: // Float: // Float:const_float_1 // Float:const_float_2 // Float:const_float_3 // Float:const_float_4 // String // Float_expr // Float_expr:var_float_1 // Float_expr:var_float_2 // Logical_expr // Logical_expr:var_logical // List fp << "Logical {\n"; fp << " logical_1_true = true;\n"; fp << " logical_2_false = false;\n"; fp << "}\n"; fp << " \n"; fp << "Integer {\n"; fp << " integer_1_1 = 1;\n"; fp << " integer_2_m37 = -37;\n"; fp << "}\n"; fp << "Float {\n"; fp << " float_1_1p5 = 1.5;\n"; fp << " test_m37_25 = -37.25;\n"; fp << "}\n"; fp << "Float {\n"; fp << " group_float_1 {\n"; fp << " num1 = 24.5 + 6.125;\n"; fp << " num2 = 24.5 - 6.125;\n"; fp << " num3 = 24.5 * 6.125;\n"; fp << " num4 = 24.5 / 6.125;\n"; fp << " }\n"; fp << " const_float_2 {\n"; fp << " num1 = 24.5 + 6.125*2.0;\n"; fp << " num2 = 24.5*3.0 - 6.125;\n"; fp << " num3 = (24.5 + 6.125*2.0 - (24.5*3.0 - 6.125));\n"; fp << " }\n"; fp << " const_float_3 {\n"; fp << " num1 = 2.0 ^ 3.0;\n"; fp << " num2 = 2.0 ^ 3.0 * 4.0;\n"; fp << " num3 = 2.0 ^ 3.0 + 4.0;\n"; fp << " num4 = 3.0 * 2.0 ^ 3.0;\n"; fp << " num5 = 3.0 + 2.0 ^ 3.0;\n"; fp << " num6 = 4.0 ^ 2.0 ^ 3.0;\n"; fp << " }\n"; fp << " const_float_4 {\n"; fp << " num1 = 4.0*pi;\n"; fp << " }\n"; fp << "}\n"; fp << "String {\n"; fp << " str1 = \"testing\";\n"; fp << " str2 = \"one\";\n"; fp << "}\n"; fp << "Float_expr {\n"; fp << " var_float_1 {\n"; fp << " num1 = x;\n"; fp << " num2 = x - 3.0;\n"; fp << " num3 = x+y+z+t;\n"; fp << " }\n"; fp << "}\n"; fp << " Float_expr {\n"; fp << " var_float_2 {\n"; fp << " num1 = sin(x);\n"; fp << " num2 = atan(y/3.0+3.0*t);\n"; fp << " }\n"; fp << " }\n"; fp << " Logical_expr {\n"; fp << " var_logical {\n"; fp << " num1 = x < y;\n"; fp << " num2 = x + y >= t + 3.0;\n"; fp << " num3 = x == y;\n"; fp << " }\n"; fp << "}\n"; fp << " List {\n"; fp << " num1 = [1.0, true, -37, \"string\", x-y+2.0*z, x+y+t > 0.0 ];\n"; fp << " num2 = [1.0, 3.0];\n"; fp << " num1 = [1.0, true, -37, \"string\", x-y+2.0*z, x+y+t > 0.0 ];\n"; fp << " num2 += [5.0, 7.0];\n"; fp << " num2 = [9.0, 11.0];\n"; fp << " num1 = [1.0, true, -37, \"string\", x-y+2.0*z, x+y+t > 0.0 ];\n"; fp << " num2 += [13.0, 15.0];\n"; fp << "}\n"; fp << " Duplicate {\n"; fp << " duplicate = 1.0;\n"; fp << " duplicate = 2.0;\n"; fp << "}\n"; fp.close(); } void check_parameters(Parameters * parameters) { //-------------------------------------------------- unit_func("group_push"); //-------------------------------------------------- parameters->group_push("Group"); unit_assert(parameters->group(0) == "Group"); unit_assert(parameters->group_depth() == 1); parameters->group_push("subgroup_1"); unit_assert(parameters->group_depth() == 2); unit_assert(parameters->group(0) == "Group"); unit_assert(parameters->group(1) == "subgroup_1"); //-------------------------------------------------- unit_func("group_pop"); //-------------------------------------------------- parameters->group_pop("subgroup_1"); unit_assert(parameters->group(0) == "Group"); unit_assert(parameters->group_depth() == 1); parameters->group_push("subgroup_2"); unit_assert(parameters->group_depth() == 2); unit_assert(parameters->group(0) == "Group"); unit_assert(parameters->group(1) == "subgroup_2"); parameters->group_pop(); parameters->group_pop(); unit_assert(parameters->group_depth() == 0); parameters->group_push("Group2"); unit_assert(parameters->group(0) == "Group2"); unit_assert(parameters->group_depth() == 1); parameters->group_pop(); //-------------------------------------------------- unit_func("value_logical"); //-------------------------------------------------- parameters->group_set(0,"Logical"); unit_assert (parameters->value_logical("logical_1_true") == true); unit_assert (parameters->value_logical("logical_2_false") == false); unit_assert (parameters->value_logical("none",true) == true); unit_assert (parameters->value_logical("none",false) == false); unit_assert(parameters->value_logical("Logical:logical_1_true") == true); unit_assert(parameters->value_logical("Logical:logical_2_false") == false); //-------------------------------------------------- unit_func("set_logical"); //-------------------------------------------------- parameters->set_logical("logical_1_true",false); unit_assert (parameters->value_logical("Logical:logical_1_true") == false); unit_assert (parameters->value_logical("logical_1_true") == false); parameters->set_logical("logical_1_true",true); unit_assert (parameters->value_logical("Logical:logical_1_true") == true); unit_assert (parameters->value_logical("logical_1_true") == true); parameters->set_logical("Logical:logical_1_true",false); unit_assert (parameters->value_logical("Logical:logical_1_true") == false); unit_assert (parameters->value_logical("logical_1_true") == false); parameters->set_logical("Logical:logical_1_true",true); unit_assert (parameters->value_logical("Logical:logical_1_true") == true); unit_assert (parameters->value_logical("logical_1_true") == true); parameters->set_logical("none_l1",true); unit_assert (parameters->value_logical("none_l1") == true); parameters->set_logical("none_l2",false); unit_assert (parameters->value_logical("none_l2") == false); //-------------------------------------------------- unit_func("value_integer"); //-------------------------------------------------- parameters->group_set(0,"Integer"); unit_assert (parameters->value_integer("integer_1_1") == 1); unit_assert (parameters->value_integer("integer_2_m37") == -37); unit_assert (parameters->value_integer("none",58) == 58); // int i,id; // parameters->value("integer_1_1",parameter_integer,&i); // unit_assert (i == 1); // parameters->value("test_37",parameter_integer,&i); // unit_assert (i == 37); // id = 58; // parameters->value("none",parameter_integer,&i,&id); // unit_assert (i == id); //-------------------------------------------------- unit_func("set_integer"); //-------------------------------------------------- parameters->set_integer("integer_1_1",2); unit_assert (parameters->value_integer("integer_1_1") == 2); parameters->set_integer("integer_1_1",1); parameters->set_integer("none1",3); unit_assert (parameters->value_integer("none1") == 3); parameters->set_integer("none2",4); unit_assert (parameters->value_integer("none2") == 4); //-------------------------------------------------- unit_func("value_float"); //-------------------------------------------------- parameters->group_set(0,"Float"); unit_assert (parameters->value_float("float_1_1p5") == 1.5); unit_assert (parameters->value_float("test_m37_25") == -37.25); unit_assert (parameters->value_float("none",58.75) == 58.75); // double d,dd; // parameters->value("float_1_1p5",parameter_float,&d); // unit_assert (d == 1.5); // parameters->value("test_37_25",parameter_float,&d); // unit_assert (d == 37.25); // dd = 58.75; // parameters->value("none",parameter_float,&d,&dd); // unit_assert (d == dd); // set_float() //-------------------------------------------------- unit_func("set_float"); //-------------------------------------------------- parameters->set_float("float_1_1p5",27.0); unit_assert (parameters->value_float("float_1_1p5") == 27.0); parameters->set_float("float_1_1p5",1.5); parameters->set_float("none_s",1.5); unit_assert (parameters->value_float("none_s") == 1.5); // Constant float expressions // subgroups //-------------------------------------------------- unit_func("value_float"); //-------------------------------------------------- parameters->group_set(0,"Float"); parameters->group_set(1,"group_float_1"); unit_assert(parameters->value_float("num1") == 24.5+6.125); unit_assert(parameters->value_float("num2") == 24.5-6.125); unit_assert(parameters->value_float("num3") == 24.5*6.125); unit_assert(parameters->value_float("num4") == 24.5/6.125); unit_assert(parameters->value_float("Float:group_float_1:num1") == 24.5+6.125); unit_assert(parameters->value_float("Float:group_float_1:num2") == 24.5-6.125); unit_assert(parameters->value_float("Float:group_float_1:num3") == 24.5*6.125); unit_assert(parameters->value_float("Float:group_float_1:num4") == 24.5/6.125); parameters->group_set(1,"const_float_2"); unit_assert(parameters->value_float("num1") == 24.5 + 6.125*2.0); unit_assert(parameters->value_float("num2") == 24.5*3.0 - 6.125); unit_assert(parameters->value_float("num3") == (24.5 + 6.125*2.0 - (24.5*3.0 - 6.125))); parameters->group_set(1,"const_float_3"); unit_assert(parameters->value_float("num1") == pow(2.0,3.0)); unit_assert(parameters->value_float("num2") == pow(2.0 , 3.0) * 4.0); unit_assert(parameters->value_float("num3") == pow(2.0 , 3.0) + 4.0); unit_assert(parameters->value_float("num4") == 3.0 * pow(2.0 , 3.0)); unit_assert(parameters->value_float("num5") == 3.0 + pow(2.0 , 3.0)); unit_assert(parameters->value_float("num6") == pow(4.0 , pow (2.0 , 3.0))); parameters->group_set(1,"const_float_4"); unit_assert(CLOSE(parameters->value_float("num1"),4.0*M_PI)); //-------------------------------------------------- unit_func("value_string"); //-------------------------------------------------- parameters->group_set(0,"String"); unit_assert(parameters->group_depth()==1); unit_assert(parameters->group(0)=="String"); unit_assert(parameters->value_string("str1") == "testing"); unit_assert(parameters->value_string("str2","blah") == "one"); unit_assert(parameters->value_string("none","blah") == "blah"); // const char *s, *sd = "blah"; // parameters->value("str1",parameter_string,&s); // unit_assert(strcmp(s,"testing")==0); // parameters->value("str2",parameter_string,&s,&sd); // unit_assert(strcmp(s,"one")==0); // parameters->value("none",parameter_string,&s,&sd); // unit_assert(strcmp(s,"blah")==0); // set_string() //-------------------------------------------------- unit_func("set_string"); //-------------------------------------------------- parameters->set_string("str1","yahoo"); unit_assert (parameters->value_string("str1") == "yahoo"); parameters->set_string("str1","testing"); parameters->set_string("none_str","hello"); unit_assert (parameters->value_string("none_str") == "hello"); //-------------------------------------------------- unit_func("evaluate_float"); //-------------------------------------------------- double x[] = { 1, 2, 3}; double y[] = {5 , 4, 3}; double z[] = {8, 9, 10}; double t = -1; double values_float[] = {0,0,0}; double deflts_float[] = {-1,-2,-3}; parameters->group_set(0,"Float_expr"); parameters->group_set(1,"var_float_1"); parameters->evaluate_float("num1",3,values_float,deflts_float,x,y,z,t); unit_assert (values_float[0]==x[0]); unit_assert (values_float[1]==x[1]); unit_assert (values_float[2]==x[2]); parameters->evaluate_float("num2",3,values_float,deflts_float,x,y,z,t); unit_assert (values_float[0]==x[0]-3.0); unit_assert (values_float[1]==x[1]-3.0); unit_assert (values_float[2]==x[2]-3.0); parameters->evaluate_float("num3",3,values_float,deflts_float,x,y,z,t); unit_assert (values_float[0]==x[0]+y[0]+z[0]+t); unit_assert (values_float[1]==x[1]+y[1]+z[1]+t); unit_assert (values_float[2]==x[2]+y[2]+z[2]+t); parameters->group_set(1,"var_float_2"); parameters->evaluate_float("num1",3,values_float,deflts_float,x,y,z,t); unit_assert (CLOSE(values_float[0],sin(x[0]))); unit_assert (CLOSE(values_float[1],sin(x[1]))); unit_assert (CLOSE(values_float[2],sin(x[2]))); parameters->evaluate_float("num2",3,values_float,deflts_float,x,y,z,t); unit_assert (CLOSE(values_float[0],atan(y[0]/3.0+3*t))); unit_assert (CLOSE(values_float[1],atan(y[1]/3.0+3*t))); unit_assert (CLOSE(values_float[2],atan(y[2]/3.0+3*t))); //-------------------------------------------------- unit_func("evaluate_logical"); //-------------------------------------------------- bool values_logical[] = {false, false, false}; bool deflts_logical[] = {true, false,true}; parameters->group_set(0,"Logical_expr"); parameters->group_set(1,"var_logical"); parameters->evaluate_logical("num1",3,values_logical,deflts_logical,x,y,z,t); unit_assert (values_logical[0] == (x[0] < y[0])); unit_assert (values_logical[1] == (x[1] < y[1])); unit_assert (values_logical[2] == (x[2] < y[2])); parameters->evaluate_logical("num2",3,values_logical,deflts_logical,x,y,z,t); unit_assert (values_logical[0] == (x[0] + y[0] >= t + 3.0)); unit_assert (values_logical[1] == (x[1] + y[1] >= t + 3.0)); unit_assert (values_logical[2] == (x[2] + y[2] >= t + 3.0)); parameters->evaluate_logical("num3",3,values_logical,deflts_logical,x,y,z,t); unit_assert (values_logical[0] == (x[0] == y[0])); unit_assert (values_logical[1] == (x[1] == y[1])); unit_assert (values_logical[2] == (x[2] == y[2])); //-------------------------------------------------- // Lists //-------------------------------------------------- parameters->group_set(0,"List"); unit_func("list_length"); unit_assert(parameters->list_length("num1") == 6); unit_func("list_value_float"); unit_assert(parameters->list_value_float(0,"num1") == 1.0); unit_func("list_value_logical"); unit_assert(parameters->list_value_logical(1,"num1") == true); unit_func("list_value_integer"); unit_assert(parameters->list_value_integer(2,"num1") == -37); unit_func("list_value_string"); unit_assert(parameters->list_value_string(3,"num1") == "string"); //-------------------------------------------------- unit_func("list_evaluate_float"); //-------------------------------------------------- parameters->list_evaluate_float (4,"num1",3,values_float, deflts_float,x,y,z,t); unit_assert (values_float[0] == (x[0]-y[0]+2.0*z[0])); unit_assert (values_float[1] == (x[1]-y[1]+2.0*z[1])); unit_assert (values_float[2] == (x[2]-y[2]+2.0*z[2])); //-------------------------------------------------- unit_func("list_evaluate_logical"); //-------------------------------------------------- parameters->list_evaluate_logical (5,"num1",3,values_logical, deflts_logical,x,y,z,t); unit_assert (values_logical[0] == (x[0]+y[0]+t > 0 )); unit_assert (values_logical[1] == (x[1]+y[1]+t > 0 )); unit_assert (values_logical[2] == (x[2]+y[2]+t > 0 )); //-------------------------------------------------- unit_func("set_list elements"); //-------------------------------------------------- parameters->set_list_length ("list",5); parameters->set_list_integer(0,"list",12); parameters->set_list_float (1,"list",24.0); parameters->set_list_logical(2,"list",true); parameters->set_list_logical(3,"list",false); parameters->set_list_string (4,"list","a string"); unit_assert(parameters->list_length("list")==5); unit_assert(parameters->list_value_integer(0,"list")==12); unit_assert(parameters->list_value_float (1,"list")==24.0); unit_assert(parameters->list_value_logical(2,"list")==true); unit_assert(parameters->list_value_logical(3,"list")==false); unit_assert(parameters->list_value_string (4,"list") == "a string"); //-------------------------------------------------- unit_func("append_list elements"); unit_assert(parameters->list_length("num2") == 4); unit_assert(parameters->list_value_float(0,"num2") == 9.0); unit_assert(parameters->list_value_float(1,"num2") == 11.0); unit_assert(parameters->list_value_float(2,"num2") == 13.0); unit_assert(parameters->list_value_float(3,"num2") == 15.0); //-------------------------------------------------- //-------------------------------------------------- unit_func("group_count"); //-------------------------------------------------- // delete parameters; // parameters = new Parameters; // parameters->read ("test.in"); const int NUM_GROUPS = 8; struct { std::string group; int count; } child_count[NUM_GROUPS] = { {"Float", 4 + 3}, {"Float_expr", 2}, {"Integer", 2 + 2}, {"List", 3}, {"Logical", 2 + 2}, {"Logical_expr",1}, {"String", 2 + 1}, {"Duplicate", 1} }; parameters->group_clear(); int num_groups = parameters->group_count(); unit_assert (num_groups == NUM_GROUPS); for (int i=0; i<NUM_GROUPS; i++) { parameters->group_set(0,child_count[i].group); unit_assert (parameters->group_count() == child_count[i].count); } // Duplicate assignments should take latter value unit_func ("duplicates"); parameters->group_set(0,"Duplicate"); unit_assert (parameters->value_float ("duplicate",0.0) == 2.0); //-------------------------------------------------- unit_func("write"); //-------------------------------------------------- // TODO // // read test.out // compare all parameters between test.in & test.out // loop parameters1 // test p1 subset p2 // loop parameters2 // test p2 subset p1 // pass iff p1 subset p2 && p2 subset p1 } //====================================================================== PARALLEL_MAIN_BEGIN { PARALLEL_INIT; unit_init (CkMyPe(), CkNumPes()); unit_class("Parameters"); Monitor::instance()->set_mode(monitor_mode_all); //---------------------------------------------------------------------- // test parameter //---------------------------------------------------------------------- Parameters * parameters1 = new Parameters; Parameters * parameters2 = new Parameters; Parameters * parameters3 = new Parameters; generate_input(); //-------------------------------------------------- unit_func("read"); //-------------------------------------------------- parameters1->read ( "test.in" ); check_parameters(parameters1); parameters1->write ( "test1.out", param_write_cello ); parameters2->read("test1.out"); check_parameters(parameters2); parameters2->write ("test2.out"); parameters3->read("test2.out"); check_parameters(parameters3); delete parameters3; delete parameters2; delete parameters1; unit_finalize(); exit_(); } PARALLEL_MAIN_END
32.328358
90
0.546476
aoife-flood
1336f604e5d0695b03d02286099e03b4501adf02
4,924
cpp
C++
Ouroboros/Source/oBase/stringize_hlsl.cpp
jiangzhu1212/oooii
fc00ff81e74adaafd9c98ba7c055f55d95a36e3b
[ "MIT" ]
null
null
null
Ouroboros/Source/oBase/stringize_hlsl.cpp
jiangzhu1212/oooii
fc00ff81e74adaafd9c98ba7c055f55d95a36e3b
[ "MIT" ]
null
null
null
Ouroboros/Source/oBase/stringize_hlsl.cpp
jiangzhu1212/oooii
fc00ff81e74adaafd9c98ba7c055f55d95a36e3b
[ "MIT" ]
null
null
null
// Copyright (c) 2014 Antony Arciuolo. See License.txt regarding use. // This cpp contains implemenations of to_string and from_string for intrinsic // types as well as ouro types. #include <oHLSL/oHLSLMath.h> #include <oString/stringize.h> namespace ouro { bool from_string(float2* _pValue, const char* src) { return from_string_float_array((float*)_pValue, 2, src); } bool from_string(float3* _pValue, const char* src) { return from_string_float_array((float*)_pValue, 3, src); } bool from_string(float4* _pValue, const char* src) { return from_string_float_array((float*)_pValue, 4, src); } bool from_string(float4x4* _pValue, const char* src) { // Read in-order, then transpose bool result = from_string_float_array((float*)_pValue, 16, src); if (result) transpose(*_pValue); return result; } bool from_string(double4x4* _pValue, const char* src) { // Read in-order, then transpose bool result = from_string_double_array((double*)_pValue, 16, src); if (result) transpose(*_pValue); return result; } #define CHK_MV() do \ { if (!_pValue || !src) return false; \ src += strcspn(src, oDIGIT_SIGNED); \ if (!*src) return false; \ } while (false) #define CHK_MV_U() do \ { if (!_pValue || !src) return false; \ src += strcspn(src, oDIGIT_UNSIGNED); \ if (!*src) return false; \ } while (false) bool from_string(int2* _pValue, const char* src) { CHK_MV(); return 2 == sscanf_s(src, "%d %d", &_pValue->x, &_pValue->y); } bool from_string(int3* _pValue, const char* src) { CHK_MV(); return 3 == sscanf_s(src, "%d %d %d", &_pValue->x, &_pValue->y, &_pValue->z); } bool from_string(int4* _pValue, const char* src) { CHK_MV(); return 4 == sscanf_s(src, "%d %d %d %d", &_pValue->x, &_pValue->y, &_pValue->z, &_pValue->w); } bool from_string(uint2* _pValue, const char* src) { CHK_MV_U(); return 2 == sscanf_s(src, "%u %u", &_pValue->x, &_pValue->y); } bool from_string(uint3* _pValue, const char* src) { CHK_MV_U(); return 3 == sscanf_s(src, "%u %u %u", &_pValue->x, &_pValue->y, &_pValue->z); } bool from_string(uint4* _pValue, const char* src) { CHK_MV(); return 4 == sscanf_s(src, "%u %u %u %u", &_pValue->x, &_pValue->y, &_pValue->z, &_pValue->w); } char* to_string(char* dst, size_t dst_size, const float2& value) { return -1 != snprintf(dst, dst_size, "%f %f", value.x, value.y) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const float3& value) { return -1 != snprintf(dst, dst_size, "%f %f %f", value.x, value.y, value.z) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const float4& value) { return -1 != snprintf(dst, dst_size, "%f %f %f %f", value.x, value.y, value.z, value.w) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const double2& value) { return -1 != snprintf(dst, dst_size, "%f %f", value.x, value.y) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const double3& value) { return -1 != snprintf(dst, dst_size, "%f %f %f", value.x, value.y, value.z) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const double4& value) { return -1 != snprintf(dst, dst_size, "%f %f %f %f", value.x, value.y, value.z, value.w) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const int2& value) { return -1 != snprintf(dst, dst_size, "%d %d", value.x, value.y) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const int3& value) { return -1 != snprintf(dst, dst_size, "%d %d %d", value.x, value.y, value.z) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const int4& value) { return -1 != snprintf(dst, dst_size, "%d %d %d %d", value.x, value.y, value.z, value.w) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const uint2& value) { return -1 != snprintf(dst, dst_size, "%u %u", value.x, value.y) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const uint3& value) { return -1 != snprintf(dst, dst_size, "%u %u %u", value.x, value.y, value.z) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const uint4& value) { return -1 != snprintf(dst, dst_size, "%u %u %u %u", value.x, value.y, value.z, value.w) ? dst : nullptr; } template<typename T> char* to_stringT(char* dst, size_t dst_size, const TMAT4<T>& value) { return -1 != snprintf(dst, dst_size, "%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f" , value.Column0.x, value.Column1.x, value.Column2.x, value.Column3.x , value.Column0.y, value.Column1.y, value.Column2.y, value.Column3.y , value.Column0.z, value.Column1.z, value.Column2.z, value.Column3.z , value.Column0.w, value.Column1.w, value.Column2.w, value.Column3.w) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const float4x4& value) { return to_stringT(dst, dst_size, value); } char* to_string(char* dst, size_t dst_size, const double4x4& value) { return to_stringT(dst, dst_size, value); } }
55.325843
175
0.662063
jiangzhu1212
133aaa33eb89ce773dd33adadad28c03f1b8edc2
4,881
cpp
C++
Disruptor.PerfTests/TestRepository.cpp
ulricheck/Disruptor-cpp
fd2cef124f5bf2dbbe399137fd69e85844b90a6b
[ "Apache-2.0" ]
250
2017-12-21T15:19:30.000Z
2022-03-30T05:55:24.000Z
Disruptor.PerfTests/TestRepository.cpp
ulricheck/Disruptor-cpp
fd2cef124f5bf2dbbe399137fd69e85844b90a6b
[ "Apache-2.0" ]
14
2018-06-21T22:57:47.000Z
2022-01-26T07:48:47.000Z
Disruptor.PerfTests/TestRepository.cpp
ulricheck/Disruptor-cpp
fd2cef124f5bf2dbbe399137fd69e85844b90a6b
[ "Apache-2.0" ]
84
2018-01-06T13:55:54.000Z
2022-01-20T07:15:55.000Z
#include "stdafx.h" #include "TestRepository.h" #include <boost/algorithm/string.hpp> // Raw #include "OneToOneRawBatchThroughputTest.h" #include "OneToOneRawThroughputTest.h" // Sequenced #include "OneToOneSequencedBatchThroughputTest.h" #include "OneToOneSequencedLongArrayThroughputTest.h" #include "OneToOneSequencedPollerThroughputTest.h" #include "OneToOneSequencedThroughputTest.h" #include "OneToThreeDiamondSequencedThroughputTest.h" #include "OneToThreePipelineSequencedThroughputTest.h" #include "OneToThreeSequencedThroughputTest.h" #include "PingPongSequencedLatencyTest.h" #include "ThreeToOneSequencedBatchThroughputTest.h" #include "ThreeToOneSequencedThroughputTest.h" #include "ThreeToThreeSequencedThroughputTest.h" // Translator #include "OneToOneTranslatorThroughputTest.h" // WorkHandler #include "OneToThreeReleasingWorkerPoolThroughputTest.h" #include "OneToThreeWorkerPoolThroughputTest.h" #include "TwoToTwoWorkProcessorThroughputTest.h" namespace Disruptor { namespace PerfTests { TestRepository::TestRepository() { // Raw registerTest< OneToOneRawBatchThroughputTest >(); registerTest< OneToOneRawThroughputTest >(); // Sequenced registerTest< OneToOneSequencedBatchThroughputTest >(); registerTest< OneToOneSequencedLongArrayThroughputTest >(); registerTest< OneToOneSequencedPollerThroughputTest >(); registerTest< OneToOneSequencedThroughputTest >(); registerTest< OneToThreeDiamondSequencedThroughputTest >(); registerTest< OneToThreePipelineSequencedThroughputTest >(); registerTest< OneToThreeSequencedThroughputTest >(); registerTest< PingPongSequencedLatencyTest >(); registerTest< ThreeToOneSequencedBatchThroughputTest >(); registerTest< ThreeToOneSequencedThroughputTest >(); registerTest< ThreeToThreeSequencedThroughputTest >(); // Translator registerTest< OneToOneTranslatorThroughputTest >(); // WorkHandler registerTest< OneToThreeReleasingWorkerPoolThroughputTest >(); registerTest< OneToThreeWorkerPoolThroughputTest >(); registerTest< TwoToTwoWorkProcessorThroughputTest >(); } void TestRepository::registerTest(const TypeInfo& typeInfo, const std::function<std::shared_ptr< IThroughputTest >()>& testFactory) { ThroughputTestInfo info{ typeInfo.name(), testFactory }; m_throughputTestInfosByName.insert(std::make_pair(boost::algorithm::to_lower_copy(typeInfo.fullyQualifiedName()), info)); m_throughputTestInfosByName.insert(std::make_pair(boost::algorithm::to_lower_copy(typeInfo.name()), info)); } void TestRepository::registerTest(const TypeInfo& typeInfo, const std::function<std::shared_ptr< ILatencyTest >()>& testFactory) { LatencyTestInfo info{ typeInfo.name(), testFactory }; m_latencyTestInfosByName.insert(std::make_pair(boost::algorithm::to_lower_copy(typeInfo.fullyQualifiedName()), info)); m_latencyTestInfosByName.insert(std::make_pair(boost::algorithm::to_lower_copy(typeInfo.name()), info)); } const TestRepository& TestRepository::instance() { static TestRepository instance; return instance; } std::vector< ThroughputTestInfo > TestRepository::allThrougputTests() const { std::vector< ThroughputTestInfo > result; std::set< std::string > testNames; for (auto&& x : m_throughputTestInfosByName) { if (testNames.count(x.second.name) > 0) continue; testNames.insert(x.second.name); result.push_back(x.second); } return result; } bool TestRepository::tryGetThroughputTest(const std::string& testName, ThroughputTestInfo& testInfo) const { auto it = m_throughputTestInfosByName.find(boost::algorithm::to_lower_copy(testName)); if (it == m_throughputTestInfosByName.end()) return false; testInfo = it->second; return true; } std::vector< LatencyTestInfo > TestRepository::allLatencyTests() const { std::vector< LatencyTestInfo > result; std::set< std::string > testNames; for (auto&& x : m_latencyTestInfosByName) { if (testNames.count(x.second.name) > 0) continue; testNames.insert(x.second.name); result.push_back(x.second); } return result; } bool TestRepository::tryGetLatencyTest(const std::string& testName, LatencyTestInfo& testInfo) const { auto it = m_latencyTestInfosByName.find(boost::algorithm::to_lower_copy(testName)); if (it == m_latencyTestInfosByName.end()) return false; testInfo = it->second; return true; } } // namespace PerfTests } // namespace Disruptor
34.617021
135
0.707642
ulricheck
133c51e766e72feba1686d3c089a7f36daa28a82
185
hpp
C++
lib/log/log.hpp
thorsten-l/ESP8266-OpenHAB-Wifi-Socket
7b7f709b5a5a218202b339f6610b9a4f557ab2c2
[ "Apache-2.0" ]
2
2018-03-01T19:12:30.000Z
2018-03-08T18:31:45.000Z
lib/log/log.hpp
thorsten-l/ESP8266-OpenHAB-Wifi-Socket
7b7f709b5a5a218202b339f6610b9a4f557ab2c2
[ "Apache-2.0" ]
null
null
null
lib/log/log.hpp
thorsten-l/ESP8266-OpenHAB-Wifi-Socket
7b7f709b5a5a218202b339f6610b9a4f557ab2c2
[ "Apache-2.0" ]
null
null
null
#ifndef __LOG_HPP__ #define __LOG_HPP__ #define LOG0( format ) Serial.printf( "(%ld) " format, millis()) #define LOG1( format, x) Serial.printf( "(%ld) " format, millis(), x ) #endif
23.125
70
0.675676
thorsten-l
133cc7ead15c4c65ed0d5419ab92574e9557397e
380
hpp
C++
quicksort.hpp
bottomupmergesort/Quicksort
19d2f57341890a010f4de1f9b19f2319b4e0fffb
[ "MIT" ]
null
null
null
quicksort.hpp
bottomupmergesort/Quicksort
19d2f57341890a010f4de1f9b19f2319b4e0fffb
[ "MIT" ]
null
null
null
quicksort.hpp
bottomupmergesort/Quicksort
19d2f57341890a010f4de1f9b19f2319b4e0fffb
[ "MIT" ]
null
null
null
#ifndef QUICKSORT_HPP #define QUICKSORT_HPP #include "partition.hpp" template <typename T> void quicksort(T a[], int l, int r, int (*piv)(T a[], int l, int r, bool (*cmp)(T& a, T& b)), bool (*cmp)(T& a, T& b)) { if (r > l) { int pivot = piv(a, l, r, cmp); quicksort(a, l, pivot - 1, piv, cmp); quicksort(a, pivot + 1, r, piv, cmp); } } #endif
23.75
118
0.544737
bottomupmergesort
133eecface7ed1e8e7019196ef11e127d73645d8
1,375
cpp
C++
test/optional/from.cpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
13
2015-02-21T18:35:14.000Z
2019-12-29T14:08:29.000Z
test/optional/from.cpp
cpreh/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
5
2016-08-27T07:35:47.000Z
2019-04-21T10:55:34.000Z
test/optional/from.cpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
8
2015-01-10T09:22:37.000Z
2019-12-01T08:31:12.000Z
// Copyright Carl Philipp Reh 2009 - 2021. // 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 <fcppt/make_ref.hpp> #include <fcppt/catch/begin.hpp> #include <fcppt/catch/end.hpp> #include <fcppt/catch/movable.hpp> #include <fcppt/optional/from.hpp> #include <fcppt/optional/make.hpp> #include <fcppt/optional/object_impl.hpp> #include <fcppt/optional/reference.hpp> #include <fcppt/config/external_begin.hpp> #include <catch2/catch.hpp> #include <fcppt/config/external_end.hpp> FCPPT_CATCH_BEGIN TEST_CASE("optional::from", "[optiona]") { using optional_int = fcppt::optional::object<int>; using optional_int_ref = fcppt::optional::reference<int>; CHECK(fcppt::optional::from(optional_int(), [] { return 42; }) == 42); CHECK(fcppt::optional::from(optional_int(100), [] { return 42; }) == 100); int x{42}; int y{0}; fcppt::optional::from(optional_int_ref{fcppt::make_ref(x)}, [&y]() { return fcppt::make_ref(y); }).get() = 100; CHECK(x == 100); } TEST_CASE("optional::from move", "[optiona;]") { using int_movable = fcppt::catch_::movable<int>; CHECK(fcppt::optional::from(fcppt::optional::make(int_movable{42}), [] { return int_movable{10}; }) == int_movable{42}); } FCPPT_CATCH_END
26.960784
76
0.683636
freundlich
133fb8e1dc755a01fec4f49a740f8b825244e846
454
cpp
C++
MPAGSCipher/CipherFactory.cpp
MPAGS-CPP-2019/mpags-day-5-GarethBird96
2c7bf86a586c0774f57981b02a552af1ecbdcf56
[ "MIT" ]
null
null
null
MPAGSCipher/CipherFactory.cpp
MPAGS-CPP-2019/mpags-day-5-GarethBird96
2c7bf86a586c0774f57981b02a552af1ecbdcf56
[ "MIT" ]
null
null
null
MPAGSCipher/CipherFactory.cpp
MPAGS-CPP-2019/mpags-day-5-GarethBird96
2c7bf86a586c0774f57981b02a552af1ecbdcf56
[ "MIT" ]
1
2019-11-29T09:38:17.000Z
2019-11-29T09:38:17.000Z
#include "CipherFactory.hpp" std::unique_ptr<Cipher> cipherFactory( const CipherType type, const std::string key){ switch(type){ case CipherType::Caesar: return std::make_unique<CaesarCipher>(key); case CipherType::Playfair: return std::make_unique<PlayfairCipher>(key); case CipherType::Vigenere: return std::make_unique<VigenereCipher>(key); default: throw; } }
28.375
85
0.629956
MPAGS-CPP-2019
134119285d8744b3f9fc8ee9ccb4b6c5de2b641f
2,525
cpp
C++
Completed__SceneGraph_version_one/OpenGL_Scene_Node_Implementation_version_one/OpenGL_Starter_Kit/Starter_Class.cpp
CarloAlbino/GameEngineDevelopment2
cc1d8b18eefdfb0abcdfc491bbad51a1438961d2
[ "MIT" ]
null
null
null
Completed__SceneGraph_version_one/OpenGL_Scene_Node_Implementation_version_one/OpenGL_Starter_Kit/Starter_Class.cpp
CarloAlbino/GameEngineDevelopment2
cc1d8b18eefdfb0abcdfc491bbad51a1438961d2
[ "MIT" ]
null
null
null
Completed__SceneGraph_version_one/OpenGL_Scene_Node_Implementation_version_one/OpenGL_Starter_Kit/Starter_Class.cpp
CarloAlbino/GameEngineDevelopment2
cc1d8b18eefdfb0abcdfc491bbad51a1438961d2
[ "MIT" ]
null
null
null
// Includes #include <math.h> #include <ctime> // #include "Primitives.h" #include "CompositeModels.h" //// // Forward declarations void Update(void); void Render(void); void InitializeModels(void); void CalculateDeltaSeconds(void); //// // Global variables time_t g_lastFrameTime; float g_deltaSeconds = 0.01f; const float SWITCH_TIME = 4.0f; float g_switchTimer = 0.0f; float g_rotationAngle = 0.0f; int g_modelToShow = 0; std::vector<SceneNode*> g_models; //// int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(700, 700); glutInitWindowPosition(100, 100); glutCreateWindow("My First Application"); glClearColor(0.0, 0.0, 0.0, 0.0); InitializeModels(); time(&g_lastFrameTime); glutDisplayFunc(Render); glutIdleFunc(Update); glutMainLoop(); return 0; } void Update(void) { // DeltaSeconds CalculateDeltaSeconds(); // Functionality if (g_modelToShow == 2) { g_rotationAngle += 0.001f; } else { g_rotationAngle += 0.0001f; } g_switchTimer += g_deltaSeconds; if (g_switchTimer > SWITCH_TIME) { g_switchTimer = 0.0f; g_modelToShow++; if (g_modelToShow >= g_models.size()) { g_modelToShow = 0; } } // Render glutPostRedisplay(); } void Render(void) { glClear(GL_COLOR_BUFFER_BIT); //Ready to Draw glMatrixMode(GL_MODELVIEW); glLoadIdentity(); if (g_models.size() > 0) { // Rotate glm::mat4 rot = glm::rotate(glm::mat4(1.0), g_rotationAngle, glm::vec3(1, 1, 1)); g_models[g_modelToShow]->SetTransform(rot); g_models[g_modelToShow]->Render(); } glFlush(); } void InitializeModels(void) { Cube* cube = new Cube(glm::mat4(1.0f), 1.0f); cube->SetColor(1.0f, 0.0f, 0.0f); cube->SetScale(1, 1, 1); g_models.push_back(cube); Cone* cone = new Cone(glm::mat4(1.0f), 1.0f); cone->SetColor(1.0f, 0.0f, 0.0f); cone->SetScale(1, 1, 1); g_models.push_back(cone); Sphere* sphere = new Sphere(glm::mat4(1.0f), 1.0f); sphere->SetColor(1.0f, 0.0f, 0.0f); sphere->SetScale(1, 1, 1); g_models.push_back(sphere); Cylinder* cylinder = new Cylinder(glm::mat4(1.0f), 1.0f); cylinder->SetColor(1.0f, 0.0f, 0.0f); cylinder->SetScale(1, 1, 1); g_models.push_back(cylinder); StairCase* staircase = new StairCase(glm::mat4(1.0f), 1.0f); staircase->SetColor(1.0f, 0.0f, 0.0f); staircase->SetScale(1, 1, 1); g_models.push_back(staircase); } void CalculateDeltaSeconds(void) { time_t timer; time(&timer); g_deltaSeconds = difftime(timer, g_lastFrameTime); g_lastFrameTime = timer; }
19.128788
83
0.690693
CarloAlbino
13428441e34415493c57e96c300426c10b55178f
1,116
cpp
C++
src/prod/src/client/ClientServerTransport/uploadchunkrequest.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/client/ClientServerTransport/uploadchunkrequest.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/client/ClientServerTransport/uploadchunkrequest.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace Common; using namespace std; using namespace Management::FileStoreService; UploadChunkRequest::UploadChunkRequest() : stagingRelativePath_() , sessionId_() , startPosition_() , endPosition_() { } UploadChunkRequest::UploadChunkRequest( std::wstring const & stagingRelativePath, Common::Guid const & sessionId, uint64 startPosition, uint64 endPosition) : stagingRelativePath_(stagingRelativePath) , sessionId_(sessionId) , startPosition_(startPosition) , endPosition_(endPosition) { } void UploadChunkRequest::WriteTo(Common::TextWriter & w, Common::FormatOptions const &) const { w.Write("UploadChunkRequest{StagingRelativePath={0},SessionId={1},StartPosition={2},EndPosition={3}}", stagingRelativePath_, sessionId_, startPosition_, endPosition_); }
31
171
0.676523
gridgentoo
13438ed201eadec8a63d5c1a892345d34d0bfeb2
739
hpp
C++
B-CPP-300-LYN-3-1-CPPrush3/include/network.hpp
Neotoxic-off/Epitech2024
8b3dd04fa9ac2b7019c0b5b1651975a7252d929b
[ "Apache-2.0" ]
2
2022-02-07T12:44:51.000Z
2022-02-08T12:04:08.000Z
B-CPP-300-LYN-3-1-CPPrush3/include/network.hpp
Neotoxic-off/Epitech2024
8b3dd04fa9ac2b7019c0b5b1651975a7252d929b
[ "Apache-2.0" ]
null
null
null
B-CPP-300-LYN-3-1-CPPrush3/include/network.hpp
Neotoxic-off/Epitech2024
8b3dd04fa9ac2b7019c0b5b1651975a7252d929b
[ "Apache-2.0" ]
1
2022-01-23T21:26:06.000Z
2022-01-23T21:26:06.000Z
/* ** EPITECH PROJECT, 2020 ** B-CPP-300-LYN-3-1-CPPrush3- ** File description: ** network.hpp */ #ifndef _NETWORK_HPP_ #define _NETWORK_HPP_ #include "main.hpp" class network { public: network(); ~network(); void set_WLP(std::string); void set_LO(std::string); std::string get_WLP(); std::string get_LO(); bool getActivate() const {return _activate_module;} void set(); void setActivate(bool choice) {_activate_module = choice;} void display(); private: std::string wlp; std::string lo; bool _activate_module; }; #endif /* !_NETWORK_HPP_ */
21.114286
70
0.530447
Neotoxic-off
1344583d723f954d83425f8cbe933db23bd00a2b
35,597
cpp
C++
isis/src/qisis/objs/AdvancedTrackTool/AdvancedTrackTool.cpp
Kelvinrr/ISIS3
6e2df9c22d8d11564c0c3cda5d1606da58af547f
[ "CC0-1.0" ]
null
null
null
isis/src/qisis/objs/AdvancedTrackTool/AdvancedTrackTool.cpp
Kelvinrr/ISIS3
6e2df9c22d8d11564c0c3cda5d1606da58af547f
[ "CC0-1.0" ]
null
null
null
isis/src/qisis/objs/AdvancedTrackTool/AdvancedTrackTool.cpp
Kelvinrr/ISIS3
6e2df9c22d8d11564c0c3cda5d1606da58af547f
[ "CC0-1.0" ]
null
null
null
/** This is free and unencumbered software released into the public domain. The authors of ISIS do not claim copyright on the contents of this file. For more details about the LICENSE terms and the AUTHORS, you will find files of those names at the top level of this repository. **/ /* SPDX-License-Identifier: CC0-1.0 */ #include "AdvancedTrackTool.h" #include <QAction> #include <QApplication> #include <QLabel> #include <QListIterator> #include <QMenu> #include <QMenuBar> #include <QMessageBox> #include <QPushButton> #include <QScrollArea> #include <QSize> #include <QTableWidget> #include <QTableWidgetItem> #include <QToolBar> #include <QVBoxLayout> #include "Angle.h" #include "Camera.h" #include "CameraDistortionMap.h" #include "CameraFocalPlaneMap.h" #include "Distance.h" #include "iTime.h" #include "Longitude.h" #include "MdiCubeViewport.h" #include "Projection.h" #include "RingPlaneProjection.h" #include "SerialNumber.h" #include "SpecialPixel.h" #include "TableMainWindow.h" #include "Target.h" #include "TProjection.h" #include "TrackingTable.h" namespace Isis { // For mosaic tracking #define FLOAT_MIN -16777215 /** * Constructs an AdvancedTrackTool object * * @param parent */ AdvancedTrackTool::AdvancedTrackTool(QWidget *parent) : Tool(parent) { p_tableWin = new TableMainWindow("Advanced Tracking", parent); p_tableWin->setTrackListItems(true); connect(p_tableWin, SIGNAL(fileLoaded()), this, SLOT(updateID())); p_action = new QAction(parent); p_action->setText("Tracking ..."); p_action->setIcon(QPixmap(toolIconDir() + "/goto.png")); p_action->setShortcut(Qt::CTRL + Qt::Key_T); p_action->setWhatsThis("<b>Function: </b> Opens the Advanced Tracking Tool \ window. This window will track sample/line positions,\ lat/lon positions, and many other pieces of \ information. All of the data in the window can be \ saved to a text file. <p><b>Shortcut: </b> Ctrl+T</p>"); connect(p_action, SIGNAL(triggered()), p_tableWin, SLOT(showTable())); activate(true); connect(p_action, SIGNAL(triggered()), p_tableWin, SLOT(raise())); connect(p_action, SIGNAL(triggered()), p_tableWin, SLOT(syncColumns())); p_tableWin->installEventFilter(this); // Adds each item of checkBoxItems to the table. // If a tool tip is specified, we cannot skip parameters, so -1 and // Qt::Horizontal are specified. QList< QList<QString> >::iterator iter; for (iter = checkBoxItems.begin(); iter != checkBoxItems.end(); ++iter) { QList<QString> currentList = *iter; QString header = currentList[0]; QString menuText = currentList[2]; QString toolTip = currentList[3]; bool onByDefault; if (currentList[1] == QString("true")) { onByDefault = true; } else { onByDefault = false; } if (toolTip != QString("")) { p_tableWin->addToTable(onByDefault, header, menuText, -1, Qt::Horizontal, toolTip); } else { p_tableWin->addToTable(onByDefault, header, menuText); } } //This variable will keep track of how many times // the user has issued the 'record' command. p_id = 0; // Setup 10 blank rows in the table for(int r = 0; r < 10; r++) { p_tableWin->table()->insertRow(r); for(int c = 0; c < p_tableWin->table()->columnCount(); c++) { QTableWidgetItem *item = new QTableWidgetItem(""); p_tableWin->table()->setItem(r, c, item); } } // Create the action for recording points QAction *recordAction = new QAction(parent); recordAction->setShortcut(Qt::Key_R); parent->addAction(recordAction); connect(recordAction, SIGNAL(triggered()), this, SLOT(record())); p_tableWin->setStatusMessage("To record press the R key" " --- Double click on a cell to enable crtl+c (copy) and" " ctrl+v (paste)."); // Add a help menu to the menu bar QMenuBar *menuBar = p_tableWin->menuBar(); QMenu *helpMenu = menuBar->addMenu("&Help"); QAction *help = new QAction(p_tableWin); help->setText("&Tool Help"); help->setShortcut(Qt::CTRL + Qt::Key_H); connect(help, SIGNAL(triggered()), this, SLOT(helpDialog())); helpMenu->addAction(help); p_tableWin->setMenuBar(menuBar); installEventFilter(p_tableWin); m_showHelpOnStart = true; readSettings(); } /** * An event filter that calls methods on certain events. * * @param o * @param e * * @return bool */ bool AdvancedTrackTool::eventFilter(QObject *o, QEvent *e) { if(e->type() == QEvent::Show) { activate(true); if (m_showHelpOnStart) { helpDialog(); m_showHelpOnStart = false; writeSettings(); } } else if(e->type() == QEvent::Hide) { activate(false); } return Tool::eventFilter(o, e); } /** * This method adds the action to bring up the track tool to the menu. * * @param menu */ void AdvancedTrackTool::addTo(QMenu *menu) { menu->addAction(p_action); } /** * This method adds the action to bring up the track tool to the permanent tool * bar. * * @param perm */ void AdvancedTrackTool::addToPermanent(QToolBar *perm) { perm->addAction(p_action); } /** * This method is called when the mouse has moved across the viewport and * updates the row accordingly. * * @param p */ void AdvancedTrackTool::mouseMove(QPoint p) { updateRow(p); } /** * This method is called when the mouse leaves the viewport and clears any rows * accordingly. * */ void AdvancedTrackTool::mouseLeave() { if(cubeViewport()->isLinked()) { for(int i = 0; i < p_numRows; i++) { p_tableWin->clearRow(i + p_tableWin->currentRow()); } } else { p_tableWin->clearRow(p_tableWin->currentRow()); } } /** * This method updates the row with data from the point given. * * @param p */ void AdvancedTrackTool::updateRow(QPoint p) { MdiCubeViewport *cvp = cubeViewport(); if(cvp == NULL) { p_tableWin->clearRow(p_tableWin->currentRow()); return; } if(!cubeViewport()->isLinked()) { updateRow(cvp, p, p_tableWin->currentRow()); p_numRows = 1; } else { p_numRows = 0; for(int i = 0; i < (int)cubeViewportList()->size(); i++) { MdiCubeViewport *d = (*(cubeViewportList()))[i]; if(d->isLinked()) { updateRow(d, p, p_tableWin->currentRow() + p_numRows); p_numRows++; } } } } /** * This method finds the index of the header in checkBoxItems by looping * through checkBoxItems, grabbing the header from each QList, and parsing * the header at ":" to account for check boxes selecting multiple columns. * * @param keyword Header to be found * @return int The index of the item to be added */ int AdvancedTrackTool::getIndex(QString keyword) { int index = 0; QList< QList<QString> >::iterator iter; for (iter = checkBoxItems.begin(); iter != checkBoxItems.end(); ++iter) { QList<QString> currentList = *iter; QList<QString> splitHeader = currentList[0].split(":"); QList<QString>::iterator headerIter; for (headerIter = splitHeader.begin(); headerIter != splitHeader.end(); ++headerIter) { QString header = *headerIter; if (header.toLower() == keyword.toLower()) { return index; } index++; } } IString msg = "Header [" + keyword + "] not found; make sure spelling is correct"; throw IException(IException::Io, msg, _FILEINFO_); } /** * This method updates the row given with data from the viewport cvp at point p. * * @param cvp CubeViewPort that contains p * @param p QPoint from which the row will be updated * @param row Row to be updated */ void AdvancedTrackTool::updateRow(MdiCubeViewport *cvp, QPoint p, int row) { // Get the sample line position to report double sample, line; cvp->viewportToCube(p.x(), p.y(), sample, line); int isample = int (sample + 0.5); int iline = int (line + 0.5); /*if there are linked cvp's then we want to highlight (select) the row of the active cvp.*/ if(cvp->isLinked()) { if(cvp == cubeViewport()) { p_tableWin->table()->selectRow(row); } } // Do we need more rows? if(row + 1 > p_tableWin->table()->rowCount()) { p_tableWin->table()->insertRow(row); for(int c = 0; c < p_tableWin->table()->columnCount(); c++) { QTableWidgetItem *item = new QTableWidgetItem(""); p_tableWin->table()->setItem(row, c, item); if(c == 0) p_tableWin->table()->scrollToItem(item); } } // Blank out the row to remove stuff left over from previous cvps for(int c = 0; c < p_tableWin->table()->columnCount(); c++) { p_tableWin->table()->item(row, c)->setText(""); } // Don't write anything if we are outside the cube if(sample < 0.5) return; if(line < 0.5) return; if(sample > cvp->cubeSamples() + 0.5) return; if(line > cvp->cubeLines() + 0.5) return; // Write cols 0-2 (id, sample, line) p_tableWin->table()->item(row, getIndex("ID"))->setText(QString::number(p_id)); p_tableWin->table()->item(row, getIndex("Sample"))->setText(QString::number(sample)); p_tableWin->table()->item(row, getIndex("Line"))->setText(QString::number(line)); // Write col 3 (band) if (cvp->isGray()) { p_tableWin->table()->item(row, getIndex("Band"))->setText(QString::number(cvp->grayBand())); } else { p_tableWin->table()->item(row, getIndex("Band"))->setText(QString::number(cvp->redBand())); } // Write out the path, filename, and serial number FileName fname = FileName(cvp->cube()->fileName()).expanded(); QString fnamePath = fname.path(); QString fnameName = fname.name(); p_tableWin->table()->item(row, getIndex("Path"))->setText(fnamePath); p_tableWin->table()->item(row, getIndex("FileName"))->setText(fnameName); if (!cvp->cube()->hasGroup("Tracking") && !cvp->cube()->hasTable("InputImages")){ p_tableWin->table()->item(row, getIndex("Serial Number"))->setText(SerialNumber::Compose(*cvp->cube())); } // If we are outside of the image then we are done if((sample < 0.5) || (line < 0.5) || (sample > cvp->cubeSamples() + 0.5) || (line > cvp->cubeLines() + 0.5)) { return; } // Otherwise write out col 4 (Pixel value) if(cvp->isGray()) { QString grayPixel = PixelToString(cvp->grayPixel(isample, iline)); QString p = grayPixel; p_tableWin->table()->item(row, getIndex("Pixel"))->setText(p); } else { QString redPixel = PixelToString(cvp->redPixel(isample, iline)); QString p = redPixel; p_tableWin->table()->item(row, getIndex("Pixel"))->setText(p); } // Do we have a camera model? if(cvp->camera() != NULL) { if(cvp->camera()->SetImage(sample, line)) { // Write columns ocentric lat/lon, and radius, only if set image succeeds double lat = cvp->camera()->UniversalLatitude(); double lon = cvp->camera()->UniversalLongitude(); double radius = cvp->camera()->LocalRadius().meters(); p_tableWin->table()->item(row, getIndex("Planetocentric Latitude"))-> setText(QString::number(lat, 'f', 15)); p_tableWin->table()->item(row, getIndex("360 Positive East Longitude"))-> setText(QString::number(lon, 'f', 15)); p_tableWin->table()->item(row, getIndex("Local Radius"))-> setText(QString::number(radius, 'f', 15)); /* 180 Positive East Lon. */ p_tableWin->table()->item(row, getIndex("180 Positive East Longitude"))-> setText(QString::number(TProjection::To180Domain(lon), 'f', 15)); // Write out the planetographic and positive west values, only if set image succeeds lon = -lon; while(lon < 0.0) lon += 360.0; Distance radii[3]; cvp->camera()->radii(radii); lat = TProjection::ToPlanetographic(lat, radii[0].meters(), radii[2].meters()); p_tableWin->table()->item(row, getIndex("Planetographic Latitude"))-> setText(QString::number(lat, 'f', 15)); p_tableWin->table()->item(row, getIndex("360 Positive West Longitude"))-> setText(QString::number(lon, 'f', 15)); /*180 Positive West Lon. */ p_tableWin->table()->item(row, getIndex("180 Positive West Longitude"))->setText( QString::number(TProjection::To180Domain(lon), 'f', 15)); // Next write out columns, the x/y/z position of the lat/lon, only if set image succeeds double pos[3]; cvp->camera()->Coordinate(pos); p_tableWin->table()->item(row, getIndex("Point X"))->setText(QString::number(pos[0])); p_tableWin->table()->item(row, getIndex("Point Y"))->setText(QString::number(pos[1])); p_tableWin->table()->item(row, getIndex("Point Z"))->setText(QString::number(pos[2])); // Write out columns resolution, only if set image succeeds double res = cvp->camera()->PixelResolution(); if (res != -1.0) { p_tableWin->table()->item(row, getIndex("Resolution"))->setText(QString::number(res)); } else { p_tableWin->table()->item(row, getIndex("Resolution"))->setText(""); } // Write out columns, oblique pixel resolution, only if set image succeeds double obliquePRes = cvp->camera()->ObliquePixelResolution(); if (obliquePRes != Isis::Null) { p_tableWin->table()->item(row, getIndex("Oblique Pixel Resolution"))-> setText(QString::number(obliquePRes)); } else { p_tableWin->table()->item(row, getIndex("Oblique Pixel Resolution"))->setText(""); } // Write out columns photometric angle values, only if set image succeeds double phase = cvp->camera()->PhaseAngle(); p_tableWin->table()->item(row, getIndex("Phase"))->setText(QString::number(phase)); double incidence = cvp->camera()->IncidenceAngle(); p_tableWin->table()->item(row, getIndex("Incidence"))->setText(QString::number(incidence)); double emission = cvp->camera()->EmissionAngle(); p_tableWin->table()->item(row, getIndex("Emission"))->setText(QString::number(emission)); // Write out columns local incidence and emission, only if set image // succeeds. This might fail if there are holes in the DEM. // Calculates the angles local to the slope for the DEMs, compare against // the incidence and emission angles calculated for the sphere Angle phaseAngle, incidenceAngle, emissionAngle; bool bSuccess = false; cvp->camera()->LocalPhotometricAngles(phaseAngle, incidenceAngle, emissionAngle, bSuccess); if(bSuccess) { p_tableWin->table()->item(row, getIndex("LocalIncidence"))-> setText(QString::number(incidenceAngle.degrees())); p_tableWin->table()->item(row, getIndex("LocalEmission"))-> setText(QString::number(emissionAngle.degrees())); } else { p_tableWin->table()->item(row, getIndex("LocalIncidence"))->setText(""); p_tableWin->table()->item(row, getIndex("LocalEmission"))->setText(""); } // If set image succeeds, write out columns north azimuth, sun azimuth, solar longitude // north azimuth is meaningless for ring plane projections double northAzi = cvp->camera()->NorthAzimuth(); if (cvp->camera()->target()->shape()->name() != "Plane" && Isis::IsValidPixel(northAzi)) { p_tableWin->table()->item(row, getIndex("North Azimuth"))-> setText(QString::number(northAzi)); } else { // north azimuth is meaningless for ring plane projections p_tableWin->table()->item(row, getIndex("North Azimuth"))->setText(""); } double sunAzi = cvp->camera()->SunAzimuth(); if (Isis::IsValidPixel(sunAzi)) { p_tableWin->table()->item(row, getIndex("Sun Azimuth"))-> setText(QString::number(sunAzi)); } else { // sun azimuth is null p_tableWin->table()->item(row, getIndex("Sun Azimuth"))->setText(""); } double spacecraftAzi = cvp->camera()->SpacecraftAzimuth(); if (Isis::IsValidPixel(spacecraftAzi)) { p_tableWin->table()->item(row, getIndex("Spacecraft Azimuth"))-> setText(QString::number(spacecraftAzi)); } else { // spacecraft azimuth is null p_tableWin->table()->item(row, getIndex("Spacecraft Azimuth"))->setText(""); } // Write out columns solar lon, slant distance, local solar time double solarLon = cvp->camera()->solarLongitude().degrees(); p_tableWin->table()->item(row, getIndex("Solar Longitude"))-> setText(QString::number(solarLon)); double slantDistance = cvp->camera()->SlantDistance(); p_tableWin->table()->item(row, getIndex("Slant Distance"))-> setText(QString::number(slantDistance)); double lst = cvp->camera()->LocalSolarTime(); p_tableWin->table()->item(row, getIndex("Local Solar Time"))-> setText(QString::number(lst)); } // end if set image succeeds // Always write out the x/y/z of the undistorted focal plane CameraDistortionMap *distortedMap = cvp->camera()->DistortionMap(); double undistortedFocalPlaneX = distortedMap->UndistortedFocalPlaneX(); p_tableWin->table()->item(row, getIndex("Undistorted Focal X"))-> setText(QString::number(undistortedFocalPlaneX)); double undistortedFocalPlaneY = distortedMap->UndistortedFocalPlaneY(); p_tableWin->table()->item(row, getIndex("Undistorted Focal Y"))-> setText(QString::number(undistortedFocalPlaneY)); double undistortedFocalPlaneZ = distortedMap->UndistortedFocalPlaneZ(); p_tableWin->table()->item(row, getIndex("Undistorted Focal Z"))-> setText(QString::number(undistortedFocalPlaneZ)); // Always write out the x/y of the distorted focal plane CameraFocalPlaneMap *focalPlaneMap = cvp->camera()->FocalPlaneMap(); double distortedFocalPlaneX = focalPlaneMap->FocalPlaneX(); p_tableWin->table()->item(row, getIndex("Focal Plane X"))-> setText(QString::number(distortedFocalPlaneX)); double distortedFocalPlaneY = focalPlaneMap->FocalPlaneY(); p_tableWin->table()->item(row, getIndex("Focal Plane Y"))-> setText(QString::number(distortedFocalPlaneY)); // Always write out columns ra/dec, regardless of whether set image succeeds double ra = cvp->camera()->RightAscension(); p_tableWin->table()->item(row, getIndex("Right Ascension"))->setText(QString::number(ra)); double dec = cvp->camera()->Declination(); p_tableWin->table()->item(row, getIndex("Declination"))->setText(QString::number(dec)); // Always write out columns et and utc, regardless of whether set image succeeds iTime time(cvp->camera()->time()); p_tableWin->table()->item(row, getIndex("Ephemeris Time"))-> setText(QString::number(time.Et(), 'f', 15)); QString time_utc = time.UTC(); p_tableWin->table()->item(row, getIndex("UTC"))->setText(time_utc); // Always out columns spacecraft position, regardless of whether set image succeeds double pos[3]; cvp->camera()->instrumentPosition(pos); p_tableWin->table()->item(row, getIndex("Spacecraft X"))->setText(QString::number(pos[0])); p_tableWin->table()->item(row, getIndex("Spacecraft Y"))->setText(QString::number(pos[1])); p_tableWin->table()->item(row, getIndex("Spacecraft Z"))->setText(QString::number(pos[2])); } else if (cvp->projection() != NULL) { // Determine the projection type Projection::ProjectionType projType = cvp->projection()->projectionType(); if (cvp->projection()->SetWorld(sample, line)) { if (projType == Projection::Triaxial) { TProjection *tproj = (TProjection *) cvp->projection(); double lat = tproj->UniversalLatitude(); double lon = tproj->UniversalLongitude(); double glat = tproj->ToPlanetographic(lat); double wlon = -lon; while(wlon < 0.0) wlon += 360.0; if (tproj->IsSky()) { lon = tproj->Longitude(); p_tableWin->table()->item(row, getIndex("Right Ascension"))-> setText(QString::number(lon, 'f', 15)); p_tableWin->table()->item(row, getIndex("Declination"))-> setText(QString::number(lat, 'f', 15)); } else { double radius = tproj->LocalRadius(); p_tableWin->table()->item(row, getIndex("Planetocentric Latitude"))-> setText(QString::number(lat, 'f', 15)); p_tableWin->table()->item(row, getIndex("Planetographic Latitude"))-> setText(QString::number(glat, 'f', 15)); p_tableWin->table()->item(row, getIndex("360 Positive East Longitude"))-> setText(QString::number(lon, 'f', 15)); p_tableWin->table()->item(row, getIndex("180 Positive East Longitude"))-> setText(QString::number(TProjection::To180Domain(lon), 'f', 15)); p_tableWin->table()->item(row, getIndex("360 Positive West Longitude"))-> setText(QString::number(wlon, 'f', 15)); p_tableWin->table()->item(row, getIndex("180 Positive East Longitude"))-> setText(QString::number(TProjection::To180Domain(wlon), 'f', 15)); p_tableWin->table()->item(row, getIndex("Local Radius"))->setText(QString::number(radius, 'f', 15)); } } else { // RingPlane RingPlaneProjection *rproj = (RingPlaneProjection *) cvp->projection(); double lat = rproj->UniversalRingRadius(); double lon = rproj->UniversalRingLongitude(); double wlon = -lon; while(wlon < 0.0) wlon += 360.0; double radius = lat; p_tableWin->table()->item(row, getIndex("Planetocentric Latitude"))->setText("0.0"); p_tableWin->table()->item(row, getIndex("Planetographic Latitude"))->setText("0.0"); p_tableWin->table()->item(row, getIndex("360 Positive East Longitude"))-> setText(QString::number(lon, 'f', 15)); p_tableWin->table()->item(row, getIndex("180 Positive East Longitude"))-> setText(QString::number(RingPlaneProjection::To180Domain(lon), 'f', 15)); p_tableWin->table()->item(row, getIndex("360 Positive West Longitude"))-> setText(QString::number(wlon, 'f', 15)); p_tableWin->table()->item(row, getIndex("180 Positive West Longitude"))-> setText(QString::number(RingPlaneProjection::To180Domain(wlon), 'f', 15)); p_tableWin->table()->item(row, getIndex("Local Radius"))-> setText(QString::number(radius, 'f', 15)); } } } //If there is a projection add the Projected X and Y coords to the table if(cvp->projection() != NULL) { if(cvp->projection()->SetWorld(sample, line)) { double projX = cvp->projection()->XCoord(); double projY = cvp->projection()->YCoord(); p_tableWin->table()->item(row, getIndex("Projected X"))-> setText(QString::number(projX, 'f', 15)); p_tableWin->table()->item(row, getIndex("Projected Y"))-> setText(QString::number(projY, 'f', 15)); } } // Track the Mosaic Origin - Index (Zero based) and FileName if (cvp->cube()->hasTable("InputImages") || cvp->cube()->hasGroup("Tracking")) { int iMosaicOrigin = -1; QString sSrcFileName = ""; QString sSrcSerialNum = ""; TrackMosaicOrigin(cvp, iline, isample, iMosaicOrigin, sSrcFileName, sSrcSerialNum); p_tableWin->table()->item(row, getIndex("Track Mosaic Index"))-> setText(QString::number(iMosaicOrigin)); p_tableWin->table()->item(row, getIndex("Track Mosaic FileName"))-> setText(QString(sSrcFileName)); p_tableWin->table()->item(row, getIndex("Track Mosaic Serial Number"))-> setText(QString(sSrcSerialNum)); } } /** * TrackMosaicOrigin - Given the pointer to Cube and line and * sample index, finds the origin of the mosaic if the TRACKING * band and Mosaic Origin Table exists. * * @author sprasad (11/16/2009) * * @param cvp - Points to the CubeViewPort * @param piLine - Line Index * @param piSample - Sample Index * @param piOrigin - Contains the Src Index (zero based) * @param psSrcFileName - Contains the Src FileName * @param psSrcSerialNum- Contains the Src Serial Number * * @return void */ void AdvancedTrackTool::TrackMosaicOrigin(MdiCubeViewport *cvp, int piLine, int piSample, int &piOrigin, QString &psSrcFileName, QString &psSrcSerialNum) { try { Cube *cCube = cvp->cube(); int iTrackBand = -1; // This is a mosaic in the new format or the external tracking cube itself if(cCube->hasGroup("Tracking") || (cCube->hasTable(trackingTableName) && cCube->bandCount() == 1)) { Cube *trackingCube; if(cCube->hasGroup("Tracking")) { trackingCube = cvp->trackingCube(); } else { trackingCube = cCube; } // Read the cube DN value from TRACKING cube at location (piLine, piSample) Portal trackingPortal(trackingCube->sampleCount(), 1, trackingCube->pixelType()); trackingPortal.SetPosition(piSample, piLine, 1); trackingCube->read(trackingPortal); unsigned int currentPixel = trackingPortal[0]; if (currentPixel != NULLUI4) { // If from an image Table table(trackingTableName); // trackingTableName from TrackingTable trackingCube->read(table); TrackingTable trackingTable(table); FileName trackingFileName = trackingTable.pixelToFileName(currentPixel); psSrcFileName = trackingFileName.name(); psSrcSerialNum = trackingTable.pixelToSN(currentPixel); piOrigin = trackingTable.fileNameToIndex(trackingFileName, psSrcSerialNum); } } // Backwards compatability. Have this tool work with attached TRACKING bands else if(cCube->hasTable(trackingTableName)) { Pvl *cPvl = cCube->label(); PvlObject cObjIsisCube = cPvl->findObject("IsisCube"); PvlGroup cGrpBandBin = cObjIsisCube.findGroup("BandBin"); for(int i = 0; i < cGrpBandBin.keywords(); i++) { PvlKeyword &cKeyTrackBand = cGrpBandBin[i]; for(int j = 0; j < cKeyTrackBand.size(); j++) { if(cKeyTrackBand[j] == "TRACKING") { iTrackBand = j; break; } } } if(iTrackBand > 0 && iTrackBand <= cCube->bandCount()) { Portal cOrgPortal(cCube->sampleCount(), 1, cCube->pixelType()); cOrgPortal.SetPosition(piSample, piLine, iTrackBand + 1); // 1 based cCube->read(cOrgPortal); piOrigin = (int)cOrgPortal[0]; switch(SizeOf(cCube->pixelType())) { case 1: piOrigin -= VALID_MIN1; break; case 2: piOrigin -= VALID_MIN2; break; case 4: piOrigin -= FLOAT_MIN; break; } // Get the input file name and serial number Table cFileTable(trackingTableName); cCube->read(cFileTable); int iRecs = cFileTable.Records(); if(piOrigin >= 0 && piOrigin < iRecs) { psSrcFileName = QString(cFileTable[piOrigin][0]); psSrcSerialNum = QString(cFileTable[piOrigin][1]); } } } } catch (IException &e) { // This gets called too frequently to raise a warning; so, suppress the error // and return invalid. piOrigin = -1; } if (piOrigin == -1) { // If not from an image, display N/A psSrcFileName = "N/A"; psSrcSerialNum = "N/A"; } } /** * This method creates a dialog box that shows help tips. It is displayed when the tool is * opened the first time (unless the user says otherwise) and when the user opens it through * the help menu. */ void AdvancedTrackTool::helpDialog() { QDialog *helpDialog = new QDialog(p_tableWin); QVBoxLayout *dialogLayout = new QVBoxLayout; helpDialog->setLayout(dialogLayout); QLabel *dialogTitle = new QLabel("<h3>Advanced Tracking Tool</h3>"); dialogLayout->addWidget(dialogTitle); QTabWidget *tabArea = new QTabWidget; dialogLayout->addWidget(tabArea); QScrollArea *recordTab = new QScrollArea; QWidget *recordContainer = new QWidget; QVBoxLayout *recordLayout = new QVBoxLayout; recordContainer->setLayout(recordLayout); QLabel *recordText = new QLabel("To record, click on the viewport of interest and" " press (r) while the mouse is hovering over the image."); recordText->setWordWrap(true); recordLayout->addWidget(recordText); recordTab->setWidget(recordContainer); QScrollArea *helpTab = new QScrollArea; QWidget *helpContainer = new QWidget; QVBoxLayout *helpLayout = new QVBoxLayout; helpContainer->setLayout(helpLayout); QLabel *helpText = new QLabel("In order to use <i>ctrl+c</i> to copy and <i>ctrl+v</i> to" " paste, you need to double click on the cell you are copying" " from (the text should be highlighted). Then double click on" " the cell you are pasting to (you should see a cursor if the" " cell is blank). When a cell is in this editing mode, most" " keyboard shortcuts work."); helpText->setWordWrap(true); recordText->setWordWrap(true); helpLayout->addWidget(helpText); helpTab->setWidget(helpContainer); tabArea->addTab(recordTab, "Record"); tabArea->addTab(helpTab, "Table Help"); QPushButton *okButton = new QPushButton("OK"); dialogLayout->addStretch(); dialogLayout->addWidget(okButton); helpDialog->show(); connect(okButton, SIGNAL(clicked()), helpDialog, SLOT(accept())); } /** * This method records data to the current row. * */ void AdvancedTrackTool::record() { if(p_tableWin->table()->isHidden()) return; if(p_tableWin->table()->item(p_tableWin->currentRow(), 0)->text() == "") return; int row = 0; p_tableWin->setCurrentRow(p_tableWin->currentRow() + p_numRows); p_tableWin->setCurrentIndex(p_tableWin->currentIndex() + p_numRows); while(p_tableWin->currentRow() >= p_tableWin->table()->rowCount()) { row = p_tableWin->table()->rowCount(); p_tableWin->table()->insertRow(row); for(int c = 0; c < p_tableWin->table()->columnCount(); c++) { QTableWidgetItem *item = new QTableWidgetItem(""); p_tableWin->table()->setItem(row, c, item); } } QApplication::sendPostedEvents(p_tableWin->table(), 0); p_tableWin->table()->scrollToItem(p_tableWin->table()->item(p_tableWin->currentRow(), 0), QAbstractItemView::PositionAtBottom); //Keep track of number times user presses 'R' (record command) p_id = p_tableWin->table()->item(p_tableWin->currentRow() - 1, 0)->text().toInt() + 1; } /** * This slot updates the row with data from the point given and * records data to the current row. * * @param p QPoint from which the row(s) will be updated and * recorded. * @return void * @author Jeannie Walldren * * @internal * @history 2010-03-08 - Jeannie Walldren - This slot was * added to be connected to the FindTool recordPoint() * signal in qview. * @history 2010-05-07 - Eric Hyer - Now shows the table as well * @history 2017-11-13 - Adam Goins - Made the call to showTable() first * So that the table draws the recorded point if * the point is the first point record. Fixes #5143. */ void AdvancedTrackTool::record(QPoint p) { p_tableWin->showTable(); updateRow(p); record(); } /** * This method updates the record ID. * */ void AdvancedTrackTool::updateID() { //Check if the current row is 0 if(p_tableWin->currentRow() == 0) p_id = 0; else p_id = p_tableWin->table()->item(p_tableWin->currentRow() - 1, getIndex("ID"))->text().toInt() + 1; } /** * Read this tool's preserved state. This uses the current state as defaults, * so please make sure your variables are initialized before calling this * method. */ void AdvancedTrackTool::readSettings() { QSettings settings(settingsFilePath() , QSettings::NativeFormat); m_showHelpOnStart = settings.value("showHelpOnStart", m_showHelpOnStart).toBool(); } /** * Write out this tool's preserved state between runs. This is NOT called on * close, so you should call this any time you change the preserved state. */ void AdvancedTrackTool::writeSettings() { QSettings settings(settingsFilePath(), QSettings::NativeFormat); settings.setValue("showHelpOnStart", m_showHelpOnStart); } /** * Generate the correct path for the config file. * * @return the config file path */ QString AdvancedTrackTool::settingsFilePath() const { if (QApplication::applicationName() == "") { throw IException(IException::Programmer, "You must set QApplication's " "application name before using the Isis::MainWindow class. Window " "state and geometry can not be saved and restored", _FILEINFO_); } FileName config(FileName("$HOME/.Isis/" + QApplication::applicationName() + "/").path() + "/" + "advancedTrackTool.config"); return config.expanded(); } }
40.131905
112
0.599657
Kelvinrr
134d2b9693ec58d51aa48cc110876430e7cda0f0
446
cpp
C++
lib/Ntreev.Windows.Forms.Grid/GridRow.cpp
NtreevSoft/GridControl
decb1169d9b230ce93be1f0e96305161f2a8d655
[ "MIT" ]
2
2018-04-30T06:25:37.000Z
2018-05-12T20:29:10.000Z
lib/Ntreev.Windows.Forms.Grid/GridRow.cpp
NtreevSoft/GridControl
decb1169d9b230ce93be1f0e96305161f2a8d655
[ "MIT" ]
null
null
null
lib/Ntreev.Windows.Forms.Grid/GridRow.cpp
NtreevSoft/GridControl
decb1169d9b230ce93be1f0e96305161f2a8d655
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "GridRow.h" #include "NativeGridRow.h" namespace Ntreev { namespace Windows { namespace Forms { namespace Grid { GridRow::GridRow(Native::GrGridRow* pGridRow) : m_pGridRow(pGridRow), RowBase(pGridRow) { } _GridControl^ GridRow::ChildGrid::get() { return m_pGridRow->GetChildGrid(); } } /*namespace Grid*/ } /*namespace Forms*/ } /*namespace Windows*/ } /*namespace Ntreev*/
24.777778
89
0.661435
NtreevSoft
134f667091dd80fc625fcf4521b880bb8c4cd13b
9,169
cpp
C++
src/hal/HAL.cpp
RicoPauli/eeros
3cc2802253c764b16c6368ad7bdaef1e3c683367
[ "Apache-2.0" ]
null
null
null
src/hal/HAL.cpp
RicoPauli/eeros
3cc2802253c764b16c6368ad7bdaef1e3c683367
[ "Apache-2.0" ]
null
null
null
src/hal/HAL.cpp
RicoPauli/eeros
3cc2802253c764b16c6368ad7bdaef1e3c683367
[ "Apache-2.0" ]
null
null
null
#include <eeros/hal/HAL.hpp> #include <eeros/core/Fault.hpp> #include <dlfcn.h> #include <getopt.h> using namespace eeros; using namespace eeros::hal; HAL::HAL() : log('H') { } HAL::HAL(const HAL&) : log('H') { } HAL& HAL::operator=(const HAL&) { } HAL& HAL::instance() { static HAL halInstance; return halInstance; } bool HAL::readConfigFromFile(std::string file) { parser = JsonParser(file); parser.createHalObjects(hwLibraries); return true; } bool HAL::readConfigFromFile(int* argc, char** argv) { // available long_options static struct option long_options_hal[] = { {"config", required_argument, NULL, 'c'}, {"configFile", required_argument, NULL, 'f'}, {NULL, 0, NULL, 0 } }; // Error message if long dashes (en dash) are used int i; for (i=0; i < *argc; i++) { if ((argv[i][0] == 226) && (argv[i][1] == 128) && (argv[i][2] == 147)) { fprintf(stderr, "Error: Invalid arguments. En dashes are used.\n"); return -1; } } /* Compute command line arguments */ int c; std::string configPath; while ((c = getopt_long(*argc, argv, "c:f:", long_options_hal, NULL)) != -1) { switch(c) { case 'c': // config found if(optarg){ configPath = optarg; } else{ throw eeros::Fault("optarg empty, no path given!"); } break; case 'f': // configFile found if(optarg){ configPath = optarg; } else{ throw eeros::Fault("optarg empty, no path given!"); } break; case '?': if(optopt == 'c') log.trace() << "Option -" << optopt << " requires an argument."; else if(isprint(optopt)) log.trace() << "Unknown option `-" << optopt <<"'."; else log.trace() << "Unknown option character `\\x" << optopt << "'."; break; default: // ignore all other args break; } } parser = JsonParser(configPath); parser.createHalObjects(hwLibraries); return true; } bool HAL::loadModule(std::string moduleName) { // TODO return false; } bool HAL::addInput(InputInterface* systemInput) { if(systemInput != nullptr) { if( inputs.find(systemInput->getId()) != inputs.end() ){ throw Fault("Could not add Input to HAL, signal id '" + systemInput->getId() + "' already exists!"); } inputs.insert(std::pair<std::string, InputInterface*>(systemInput->getId(), systemInput)); return true; } throw Fault("System input is null"); } bool HAL::addOutput(OutputInterface* systemOutput) { if(systemOutput != nullptr) { if( outputs.find(systemOutput->getId()) != outputs.end() ){ throw Fault("Could not add Output to HAL, signal id '" + systemOutput->getId() + "' already exists!"); } outputs.insert(std::pair<std::string, OutputInterface*>(systemOutput->getId(), systemOutput)); return true; } throw Fault("System output is null"); } void HAL::releaseInput(std::string name) { bool found = false; auto inIt = nonExclusiveInputs.find(inputs[name]); if(inIt != nonExclusiveInputs.end()){ nonExclusiveInputs.erase(inIt); found = true; } inIt = exclusiveReservedInputs.find(inputs[name]); if(inIt != exclusiveReservedInputs.end()){ exclusiveReservedInputs.erase(inIt); found = true; } if(!found){ throw Fault("Could not release system input '" + name + "', id not found."); } } void HAL::releaseOutput(std::string name) { bool found = false; auto outIt = nonExclusiveOutputs.find(outputs[name]); if(outIt != nonExclusiveOutputs.end()){ nonExclusiveOutputs.erase(outIt); found = true; } outIt = exclusiveReservedOutputs.find(outputs[name]); if(outIt != exclusiveReservedOutputs.end()){ exclusiveReservedOutputs.erase(outIt); found = true; } if(!found){ throw Fault("Could not release system output '" + name + "', id not found."); } } OutputInterface* HAL::getOutput(std::string name, bool exclusive) { if( exclusiveReservedOutputs.find(outputs[name]) != exclusiveReservedOutputs.end() ) throw Fault("System output '" + name + "' is exclusive reserved!"); if(exclusive) { if( nonExclusiveOutputs.find(outputs[name]) != nonExclusiveOutputs.end() ){ throw Fault("System output '" + name + "' is already claimed as non-exclusive output!"); } if(!exclusiveReservedOutputs.insert(outputs[name]).second) throw Fault("System output '" + name + "' is exclusive reserved!"); // should not fail here because already checked at the beginning } else{ nonExclusiveOutputs.insert(outputs[name]).second; } return outputs[name]; } Output<bool>* HAL::getLogicOutput(std::string name, bool exclusive) { Output<bool>* out = dynamic_cast<Output<bool>*>(outputs[name]); if(out == nullptr) throw Fault("Logic system output '" + name + "' not found!"); if( exclusiveReservedOutputs.find(outputs[name]) != exclusiveReservedOutputs.end() ) throw Fault("Logic system output '" + name + "' is exclusive reserved!"); if(exclusive) { if( nonExclusiveOutputs.find(outputs[name]) != nonExclusiveOutputs.end() ){ throw Fault("Logic system output '" + name + "' is already claimed as non-exclusive output!"); } if(!exclusiveReservedOutputs.insert(outputs[name]).second) throw Fault("Logic system output '" + name + "' is exclusive reserved!"); // should not fail here because already checked at the beginning } else{ nonExclusiveOutputs.insert(outputs[name]).second; } return out; } ScalableOutput<double>* HAL::getScalableOutput(std::string name, bool exclusive) { ScalableOutput<double>* out = dynamic_cast<ScalableOutput<double>*>(outputs[name]); if(out == nullptr) throw Fault("Scalable system output '" + name + "' not found!"); if( exclusiveReservedOutputs.find(outputs[name]) != exclusiveReservedOutputs.end() ) throw Fault("Scalable system output '" + name + "' is exclusive reserved!"); if(exclusive) { if( nonExclusiveOutputs.find(outputs[name]) != nonExclusiveOutputs.end() ){ throw Fault("Scalable system output '" + name + "' is already claimed as non-exclusive output!"); } if(!exclusiveReservedOutputs.insert(outputs[name]).second) throw Fault("Scalable system output '" + name + "' is exclusive reserved!"); // should not fail here because already checked at the beginning } else{ nonExclusiveOutputs.insert(outputs[name]).second; } return out; } InputInterface* HAL::getInput(std::string name, bool exclusive) { if( exclusiveReservedInputs.find(inputs[name]) != exclusiveReservedInputs.end() ) throw Fault("System input '" + name + "' is exclusive reserved!"); if(exclusive) { if( nonExclusiveInputs.find(inputs[name]) != nonExclusiveInputs.end() ){ throw Fault("System input '" + name + "' is already claimed as non-exclusive input!"); } if(!exclusiveReservedInputs.insert(inputs[name]).second) throw Fault("System input '" + name + "' is exclusive reserved!"); // should not fail here because already checked at the beginning } else{ nonExclusiveInputs.insert(inputs[name]).second; } return inputs[name]; } Input<bool>* HAL::getLogicInput(std::string name, bool exclusive) { Input<bool>* in = dynamic_cast<Input<bool>*>(inputs[name]); if(in == nullptr) throw Fault("Logic system input '" + name + "' not found!"); if( exclusiveReservedInputs.find(inputs[name]) != exclusiveReservedInputs.end() ) throw Fault("Logic system input '" + name + "' is exclusive reserved!"); if(exclusive) { if( nonExclusiveInputs.find(inputs[name]) != nonExclusiveInputs.end() ){ throw Fault("Logic system input '" + name + "' is already claimed as non-exclusive input!"); } if(!exclusiveReservedInputs.insert(inputs[name]).second) throw Fault("Logic system input '" + name + "' is exclusive reserved!"); // should not fail here because already checked at the beginning } else{ nonExclusiveInputs.insert(inputs[name]).second; } return in; } ScalableInput<double>* HAL::getScalableInput(std::string name, bool exclusive) { ScalableInput<double>* in = dynamic_cast<ScalableInput<double>*>(inputs[name]); if(in == nullptr) throw Fault("Scalable system input '" + name + "' not found!"); if( exclusiveReservedInputs.find(inputs[name]) != exclusiveReservedInputs.end() ) throw Fault("Scalable system input '" + name + "' is exclusive reserved!"); if(exclusive) { if( nonExclusiveInputs.find(inputs[name]) != nonExclusiveInputs.end() ){ throw Fault("Scalable system input '" + name + "' is already claimed as non-exclusive input!"); } if(!exclusiveReservedInputs.insert(inputs[name]).second) throw Fault("Scalable system input '" + name + "' is exclusive reserved!"); // should not fail here because already checked at the beginning } else{ nonExclusiveInputs.insert(inputs[name]).second; } return in; } void * HAL::getOutputFeature(std::string name, std::string featureName){ auto outObj = outputs[name]; return getOutputFeature(outObj, featureName); } void* HAL::getOutputFeature(OutputInterface * obj, std::string featureName){ return dlsym(obj->getLibHandle(), featureName.c_str()); } void * HAL::getInputFeature(std::string name, std::string featureName){ auto inObj = inputs[name]; return getInputFeature(inObj, featureName); } void* HAL::getInputFeature(InputInterface * obj, std::string featureName){ return dlsym(obj->getLibHandle(), featureName.c_str()); }
34.996183
202
0.688625
RicoPauli
13502d61d18808546218ac9b923bdec14ae48b9c
1,794
cpp
C++
ImageCubeTexture.cpp
tdriggs/ETGG2802
fd30a4663bb22eda6f97427d3259d53d93af5071
[ "MIT" ]
null
null
null
ImageCubeTexture.cpp
tdriggs/ETGG2802
fd30a4663bb22eda6f97427d3259d53d93af5071
[ "MIT" ]
null
null
null
ImageCubeTexture.cpp
tdriggs/ETGG2802
fd30a4663bb22eda6f97427d3259d53d93af5071
[ "MIT" ]
null
null
null
#include "ImageCubeTexture.h" ImageCubeTexture::ImageCubeTexture(const vector<string>& filenames) { if (filenames.size() != 6) throw runtime_error("Bad size for filenames"); bind(0); this->size = 0; for (int m = 0; m<6; ++m) { vector<uint8_t> pdata; map<string, int> meta; int w, h; png_read(filenames[m], w, h, pdata, meta); int bytesperpixel = meta["planes"]; int fmt; if (bytesperpixel == 3) fmt = GL_RGB; else if (bytesperpixel == 4) fmt = GL_RGBA; else assert(0); vector<uint8_t> pix; pix.resize(pdata.size()); //need to flip vertically int i = 0; for (int row = 0; row<h; ++row) { int j = (h - row - 1)*w*bytesperpixel; for (int k = 0; k<w; ++k) { for (int n = 0; n<bytesperpixel; ++n) { pix[j++] = pdata[i++]; } } } if (w != h) throw runtime_error("Cube map images must be square"); if (this->size != 0 && this->size != w) throw runtime_error("Mismatched sizes"); else this->size = w; glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + m, 0, GL_RGBA, size, size, 0, fmt, GL_UNSIGNED_BYTE, &pix[0]); } if (isPowerOf2(size)) { glGenerateMipmap(GL_TEXTURE_CUBE_MAP); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } }
25.267606
87
0.693423
tdriggs
1353697eb8a748bba9b039f92cf47a941ea7aedd
354
hpp
C++
src/Evolution/Systems/GrMhd/ValenciaDivClean/BoundaryConditions/Factory.hpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
1
2018-10-01T06:07:16.000Z
2018-10-01T06:07:16.000Z
src/Evolution/Systems/GrMhd/ValenciaDivClean/BoundaryConditions/Factory.hpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
4
2018-06-04T20:26:40.000Z
2018-07-27T14:54:55.000Z
src/Evolution/Systems/GrMhd/ValenciaDivClean/BoundaryConditions/Factory.hpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include "Evolution/Systems/GrMhd/ValenciaDivClean/BoundaryConditions/BoundaryCondition.hpp" #include "Evolution/Systems/GrMhd/ValenciaDivClean/BoundaryConditions/DirichletAnalytic.hpp" #include "Evolution/Systems/GrMhd/ValenciaDivClean/BoundaryConditions/Outflow.hpp"
39.333333
92
0.841808
macedo22
1357b814f8585a2bea089cef99b2afcb72ad9ed4
16,143
cpp
C++
src/optimizer/optimizer.cpp
rntlqvnf/peloton
23bdfa6fa3c02c7bad0182b0aa7ddd8cc99ab872
[ "Apache-2.0" ]
null
null
null
src/optimizer/optimizer.cpp
rntlqvnf/peloton
23bdfa6fa3c02c7bad0182b0aa7ddd8cc99ab872
[ "Apache-2.0" ]
null
null
null
src/optimizer/optimizer.cpp
rntlqvnf/peloton
23bdfa6fa3c02c7bad0182b0aa7ddd8cc99ab872
[ "Apache-2.0" ]
null
null
null
//===----------------------------------------------------------------------===// // // Peloton // // optimizer.cpp // // Identification: src/optimizer/optimizer.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include "catalog/manager.h" #include "optimizer/binding.h" #include "optimizer/child_property_generator.h" #include "optimizer/cost_and_stats_calculator.h" #include "optimizer/operator_to_plan_transformer.h" #include "optimizer/operator_visitor.h" #include "optimizer/optimizer.h" #include "optimizer/property_enforcer.h" #include "optimizer/query_property_extractor.h" #include "optimizer/query_to_operator_transformer.h" #include "optimizer/rule_impls.h" #include "parser/sql_statement.h" #include "planner/order_by_plan.h" #include "planner/projection_plan.h" #include "planner/seq_scan_plan.h" namespace peloton { namespace optimizer { //===--------------------------------------------------------------------===// // Optimizer //===--------------------------------------------------------------------===// Optimizer::Optimizer() { logical_transformation_rules_.emplace_back(new InnerJoinCommutativity()); physical_implementation_rules_.emplace_back(new GetToScan()); physical_implementation_rules_.emplace_back(new LogicalFilterToPhysical()); physical_implementation_rules_.emplace_back(new InnerJoinToInnerNLJoin()); physical_implementation_rules_.emplace_back(new LeftJoinToLeftNLJoin()); physical_implementation_rules_.emplace_back(new RightJoinToRightNLJoin()); physical_implementation_rules_.emplace_back(new OuterJoinToOuterNLJoin()); // rules.emplace_back(new InnerJoinToInnerHashJoin()); } std::shared_ptr<planner::AbstractPlan> Optimizer::BuildPelotonPlanTree( const std::unique_ptr<parser::SQLStatementList> &parse_tree_list) { // Base Case if (parse_tree_list->GetStatements().size() == 0) return nullptr; std::unique_ptr<planner::AbstractPlan> child_plan = nullptr; auto parse_tree = parse_tree_list->GetStatements().at(0); // Generate initial operator tree from query tree std::shared_ptr<GroupExpression> gexpr = InsertQueryTree(parse_tree); GroupID root_id = gexpr->GetGroupID(); // Get the physical properties the final plan must output PropertySet properties = GetQueryRequiredProperties(parse_tree); // Explore the logically equivalent plans from the root group ExploreGroup(root_id); // Implement all the physical operators ImplementGroup(root_id); // Find least cost plan for root group OptimizeGroup(root_id, properties); auto best_plan = ChooseBestPlan(root_id, properties); if (best_plan == nullptr) return nullptr; // return std::shared_ptr<planner::AbstractPlan>(best_plan.release()); return std::move(best_plan); } void Optimizer::Reset() { memo_ = std::move(Memo()); column_manager_ = std::move(ColumnManager()); } std::shared_ptr<GroupExpression> Optimizer::InsertQueryTree( parser::SQLStatement *tree) { QueryToOperatorTransformer converter(column_manager_); std::shared_ptr<OperatorExpression> initial = converter.ConvertToOpExpression(tree); std::shared_ptr<GroupExpression> gexpr; RecordTransformedExpression(initial, gexpr); return gexpr; } PropertySet Optimizer::GetQueryRequiredProperties(parser::SQLStatement *tree) { QueryPropertyExtractor converter(column_manager_); return std::move(converter.GetProperties(tree)); } std::unique_ptr<planner::AbstractPlan> Optimizer::OptimizerPlanToPlannerPlan( std::shared_ptr<OperatorExpression> plan, PropertySet &requirements, std::vector<PropertySet> &required_input_props) { OperatorToPlanTransformer transformer; return transformer.ConvertOpExpression(plan, &requirements, &required_input_props); } std::unique_ptr<planner::AbstractPlan> Optimizer::ChooseBestPlan( GroupID id, PropertySet requirements) { LOG_TRACE("Choosing best plan for group %d", id); Group *group = memo_.GetGroupByID(id); std::shared_ptr<GroupExpression> gexpr = group->GetBestExpression(requirements); LOG_TRACE("Choosing best plan for group %d with op %s", gexpr->GetGroupID(), gexpr->Op().name().c_str()); std::vector<GroupID> child_groups = gexpr->GetChildGroupIDs(); std::vector<PropertySet> required_input_props = std::move(gexpr->GetInputProperties(requirements)); PL_ASSERT(required_input_props.size() == child_groups.size()); std::shared_ptr<OperatorExpression> op = std::make_shared<OperatorExpression>(gexpr->Op()); auto plan = OptimizerPlanToPlannerPlan(op, requirements, required_input_props); for (size_t i = 0; i < child_groups.size(); ++i) { auto child_plan = ChooseBestPlan(child_groups[i], required_input_props[i]); plan->AddChild(std::move(child_plan)); } return plan; } void Optimizer::OptimizeGroup(GroupID id, PropertySet requirements) { LOG_TRACE("Optimizing group %d", id); Group *group = memo_.GetGroupByID(id); // Whether required properties have already been optimized for the group if (group->GetBestExpression(requirements) != nullptr) return; const std::vector<std::shared_ptr<GroupExpression>> exprs = group->GetExpressions(); for (size_t i = 0; i < exprs.size(); ++i) { if (exprs[i]->Op().IsPhysical()) OptimizeExpression(exprs[i], requirements); } } void Optimizer::OptimizeExpression(std::shared_ptr<GroupExpression> gexpr, PropertySet requirements) { LOG_TRACE("Optimizing expression of group %d with op %s", gexpr->GetGroupID(), gexpr->Op().name().c_str()); // Only optimize and cost physical expression PL_ASSERT(gexpr->Op().IsPhysical()); std::vector<std::pair<PropertySet, std::vector<PropertySet>>> output_input_property_pairs = std::move(DeriveChildProperties(gexpr, requirements)); size_t num_property_pairs = output_input_property_pairs.size(); auto child_group_ids = gexpr->GetChildGroupIDs(); for (size_t pair_offset = 0; pair_offset < num_property_pairs; ++pair_offset) { auto output_properties = output_input_property_pairs[pair_offset].first; const auto &input_properties_list = output_input_property_pairs[pair_offset].second; std::vector<std::shared_ptr<Stats>> best_child_stats; std::vector<double> best_child_costs; for (size_t i = 0; i < child_group_ids.size(); ++i) { GroupID child_group_id = child_group_ids[i]; const PropertySet &input_properties = input_properties_list[i]; // Optimize child OptimizeGroup(child_group_id, input_properties); // Find best child expression std::shared_ptr<GroupExpression> best_expression = memo_.GetGroupByID(child_group_id) ->GetBestExpression(input_properties); // TODO(abpoms): we should allow for failure in the case where no // expression // can provide the required properties PL_ASSERT(best_expression != nullptr); best_child_stats.push_back(best_expression->GetStats(input_properties)); best_child_costs.push_back(best_expression->GetCost(input_properties)); } // Perform costing DeriveCostAndStats(gexpr, output_properties, input_properties_list, best_child_stats, best_child_costs); Group *group = this->memo_.GetGroupByID(gexpr->GetGroupID()); // Add to group as potential best cost group->SetExpressionCost(gexpr, gexpr->GetCost(output_properties), output_properties); // enforce missing properties for (auto property : requirements.Properties()) { if (output_properties.HasProperty(*property) == false) { gexpr = EnforceProperty(gexpr, output_properties, property); group->SetExpressionCost(gexpr, gexpr->GetCost(output_properties), output_properties); } } // After the enforcement it must have met the property requirements, so // notice here we set the best cost plan for 'requirements' instead of // 'output_properties' group->SetExpressionCost(gexpr, gexpr->GetCost(output_properties), requirements); } } std::shared_ptr<GroupExpression> Optimizer::EnforceProperty( std::shared_ptr<GroupExpression> gexpr, PropertySet &output_properties, const std::shared_ptr<Property> property) { // new child input is the old output auto child_input_properties = std::vector<PropertySet>(); child_input_properties.push_back(output_properties); auto child_stats = std::vector<std::shared_ptr<Stats>>(); child_stats.push_back(gexpr->GetStats(output_properties)); auto child_costs = std::vector<double>(); child_costs.push_back(gexpr->GetCost(output_properties)); PropertyEnforcer enforcer(column_manager_); auto enforced_expr = enforcer.EnforceProperty(gexpr, &output_properties, property); std::shared_ptr<GroupExpression> enforced_gexpr; RecordTransformedExpression(enforced_expr, enforced_gexpr, gexpr->GetGroupID()); // new output property would have the enforced Property output_properties.AddProperty(std::shared_ptr<Property>(property)); DeriveCostAndStats(enforced_gexpr, output_properties, child_input_properties, child_stats, child_costs); return enforced_gexpr; } std::vector<std::pair<PropertySet, std::vector<PropertySet>>> Optimizer::DeriveChildProperties(std::shared_ptr<GroupExpression> gexpr, PropertySet requirements) { ChildPropertyGenerator converter(column_manager_); return std::move(converter.GetProperties(gexpr, requirements)); } void Optimizer::DeriveCostAndStats( std::shared_ptr<GroupExpression> gexpr, const PropertySet &output_properties, const std::vector<PropertySet> &input_properties_list, std::vector<std::shared_ptr<Stats>> child_stats, std::vector<double> child_costs) { CostAndStatsCalculator calculator(column_manager_); calculator.CalculateCostAndStats(gexpr, &output_properties, &input_properties_list, child_stats, child_costs); gexpr->SetLocalHashTable(output_properties, input_properties_list, calculator.GetOutputCost(), calculator.GetOutputStats()); } void Optimizer::ExploreGroup(GroupID id) { LOG_TRACE("Exploring group %d", id); if (memo_.GetGroupByID(id)->HasExplored()) return; for (std::shared_ptr<GroupExpression> gexpr : memo_.GetGroupByID(id)->GetExpressions()) { ExploreExpression(gexpr); } memo_.GetGroupByID(id)->SetExplorationFlag(); } void Optimizer::ExploreExpression(std::shared_ptr<GroupExpression> gexpr) { LOG_TRACE("Exploring expression of group %d with op %s", gexpr->GetGroupID(), gexpr->Op().name().c_str()); PL_ASSERT(gexpr->Op().IsLogical()); // Explore logically equivalent plans by applying transformation rules for (const std::unique_ptr<Rule> &rule : logical_transformation_rules_) { // Apply all rules to operator which match. We apply all rules to one // operator before moving on to the next operator in the group because // then we avoid missing the application of a rule e.g. an application // of some rule creates a match for a previously applied rule, but it is // missed because the prev rule was already checked std::vector<std::shared_ptr<GroupExpression>> candidates = TransformExpression(gexpr, *(rule.get())); for (std::shared_ptr<GroupExpression> candidate : candidates) { // Explore the expression ExploreExpression(candidate); } } // Explore child groups for (auto child_id : gexpr->GetChildGroupIDs()) { if (!memo_.GetGroupByID(child_id)->HasExplored()) ExploreGroup(child_id); } } void Optimizer::ImplementGroup(GroupID id) { LOG_TRACE("Implementing group %d", id); if (memo_.GetGroupByID(id)->HasImplemented()) return; for (std::shared_ptr<GroupExpression> gexpr : memo_.GetGroupByID(id)->GetExpressions()) { if (gexpr->Op().IsLogical()) ImplementExpression(gexpr); } memo_.GetGroupByID(id)->SetImplementationFlag(); } void Optimizer::ImplementExpression(std::shared_ptr<GroupExpression> gexpr) { LOG_TRACE("Implementing expression of group %d with op %s", gexpr->GetGroupID(), gexpr->Op().name().c_str()); // Explore implement physical expressions for (const std::unique_ptr<Rule> &rule : physical_implementation_rules_) { TransformExpression(gexpr, *(rule.get())); } // Explore child groups for (auto child_id : gexpr->GetChildGroupIDs()) { if (!memo_.GetGroupByID(child_id)->HasImplemented()) ImplementGroup(child_id); } } ////////////////////////////////////////////////////////////////////////////// /// Rule application std::vector<std::shared_ptr<GroupExpression>> Optimizer::TransformExpression( std::shared_ptr<GroupExpression> gexpr, const Rule &rule) { std::shared_ptr<Pattern> pattern = rule.GetMatchPattern(); std::vector<std::shared_ptr<GroupExpression>> output_plans; ItemBindingIterator iterator(*this, gexpr, pattern); while (iterator.HasNext()) { std::shared_ptr<OperatorExpression> plan = iterator.Next(); // Check rule condition function if (rule.Check(plan)) { LOG_TRACE("Rule matched expression of group %d with op %s", gexpr->GetGroupID(), gexpr->Op().name().c_str()); // Apply rule transformations // We need to be able to analyze the transformations performed by this // rule in order to perform deduplication and launch an exploration of // the newly applied rule std::vector<std::shared_ptr<OperatorExpression>> transformed_plans; rule.Transform(plan, transformed_plans); // Integrate transformed plans back into groups and explore/cost if new for (std::shared_ptr<OperatorExpression> plan : transformed_plans) { LOG_TRACE("Trying to integrate expression with op %s", plan->Op().name().c_str()); std::shared_ptr<GroupExpression> new_gexpr; bool new_expression = RecordTransformedExpression(plan, new_gexpr, gexpr->GetGroupID()); if (new_expression) { LOG_TRACE("Expression with op %s was inserted into group %d", plan->Op().name().c_str(), new_gexpr->GetGroupID()); output_plans.push_back(new_gexpr); } } } } return output_plans; } ////////////////////////////////////////////////////////////////////////////// /// Memo insertion std::shared_ptr<GroupExpression> Optimizer::MakeGroupExpression( std::shared_ptr<OperatorExpression> expr) { std::vector<GroupID> child_groups = MemoTransformedChildren(expr); return std::make_shared<GroupExpression>(expr->Op(), child_groups); } std::vector<GroupID> Optimizer::MemoTransformedChildren( std::shared_ptr<OperatorExpression> expr) { std::vector<GroupID> child_groups; for (std::shared_ptr<OperatorExpression> child : expr->Children()) { child_groups.push_back(MemoTransformedExpression(child)); } return child_groups; } GroupID Optimizer::MemoTransformedExpression( std::shared_ptr<OperatorExpression> expr) { std::shared_ptr<GroupExpression> gexpr = MakeGroupExpression(expr); // Ignore whether this expression is new or not as we only care about that // at the top level (void)memo_.InsertExpression(gexpr); return gexpr->GetGroupID(); } bool Optimizer::RecordTransformedExpression( std::shared_ptr<OperatorExpression> expr, std::shared_ptr<GroupExpression> &gexpr) { return RecordTransformedExpression(expr, gexpr, UNDEFINED_GROUP); } bool Optimizer::RecordTransformedExpression( std::shared_ptr<OperatorExpression> expr, std::shared_ptr<GroupExpression> &gexpr, GroupID target_group) { gexpr = MakeGroupExpression(expr); return memo_.InsertExpression(gexpr, target_group); } } // namespace optimizer } // namespace peloton
38.253555
80
0.70018
rntlqvnf
1357d44339ada7f10cf9335bf6f5a498e47c6944
8,830
cpp
C++
workshop11/translator.cpp
raymondsim/Computer-System
0b4de4d55157d92e64cae4af048933e39cb09c1f
[ "MIT" ]
null
null
null
workshop11/translator.cpp
raymondsim/Computer-System
0b4de4d55157d92e64cae4af048933e39cb09c1f
[ "MIT" ]
null
null
null
workshop11/translator.cpp
raymondsim/Computer-System
0b4de4d55157d92e64cae4af048933e39cb09c1f
[ "MIT" ]
null
null
null
#include "iobuffer.h" #include "symbols.h" #include "abstract-syntax-tree.h" using namespace std ; using namespace CS_IO_Buffers ; using namespace CS_Symbol_Tables ; using namespace Workshop_Compiler ; // ignore unused-function warnings in this source file #pragma clang diagnostic ignored "-Wunused-function" // keep global counters so we can create unique labels in while and if statements static int while_counter = 0 ; static int if_counter = 0 ; // we have a legal infix operator, translate into VM command equivalent static string translate_op(string op) { int oplen = op.length() ; if ( oplen == 1 ) { switch(op[0]) { case '+': return "add" ; case '-': return "sub" ; case '*': return "call Math.multiply 2" ; case '/': return "call Math.divide 2" ; case '<': return "lt" ; case '>': return "gt" ; default:; } } else if ( oplen == 2 && op[1] == '=' ) { switch(op[0]) { case '<': return "gt\nnot" ; case '>': return "lt\nnot" ; case '=': return "eq" ; case '!': return "eq\nnot" ; default:; } } fatal_error(-1,"translate_op passed unknown op: " + op + "\n") ; return op ; } // the grammar we are recognising // rules containing text literals are written using the matching tk_* or tg_* names // // TERM: DEFINITION // program: declarations statement tk_eoi // declarations: declaration* // declaration: tk_var tg_type tk_identifier tk_semi // statement: while | if | let | sequence // while: tk_while tk_lrb condition tk_rrb statement // if: tk_if tk_lrb condition tk_rrb statement (tk_else statement)? // let: tk_let tk_identifier tk_assign expression tk_semi // sequence: tk_lcb statement* tk_rcb // expression: term (tg_infix_op term)? // condition: term tg_relop term // term: tk_identifier | tk_integer // // Token groups for use with have()/have_next()/mustbe()/did_not_find(): // tg_statement - matches any token that can start a statement // tg_term - matches any token that can start a term // tg_infix_op - matches any token that can be used as an infix_op // tg_relop - matches any token that can be used as a relop // tg_type - matches any token that can be used as a type // since parsing is recursive, forward declare one function to walk each non-terminal: // note: conditions are represented by expressions static void walk_program(ast) ; static int walk_declarations(ast) ; static void walk_statement(ast) ; static void walk_while(ast) ; static void walk_if(ast) ; static void walk_if_else(ast) ; static void walk_let(ast) ; static void walk_sequence(ast) ; static void walk_expression(ast) ; static void walk_term(ast) ; // now implement the parsing functions // ast create_program(ast declarations,ast statement) static void walk_program(ast n) { push_error_context("walk_program()") ; int nlocals = walk_declarations(get_program_declarations(n)) ; // if the programs starts with x variable declarations, we must start with: // function Main.main x // nextlocal is effectively a variable count so ... write_to_output("function Main.main " + to_string(nlocals) + "\n") ; walk_statement(get_program_statement(n)) ; // always finish with return so the VM code is a complete void function write_to_output("push constant 0\n") ; write_to_output("return\n") ; pop_error_context() ; } // ast create_declarations(vector<ast> variables) static int walk_declarations(ast n) { push_error_context("walk_declarations()") ; int ndecls = size_of_declarations(n) ; pop_error_context() ; return ndecls ; } // statement nodes can contain one of ast_while, ast_if, ast_if_else, ast_let or ast_statements static void walk_statement(ast n) { push_error_context("walk_statement()") ; ast stat = get_statement_statement(n) ; switch(ast_node_kind(stat)) { case ast_while: walk_while(stat) ; break ; case ast_if: walk_if(stat) ; break ; case ast_if_else: walk_if_else(stat) ; break ; case ast_let: walk_let(stat) ; break ; case ast_statements: walk_sequence(stat) ; break ; default: fatal_error(0,"Unknown kind of statement node found") ; break ; } pop_error_context() ; } // ast create_while(ast condition,ast body) static void walk_while(ast n) { push_error_context("walk_while()") ; string label = to_string(while_counter++) ; // label write_to_output("label WHILE_EXP" + label + "\n"); walk_expression(get_while_condition(n)) ; // not write_to_output("not\n"); // if-goto end write_to_output("if-goto WHILE_END" + label + "\n"); walk_sequence(get_while_body(n)) ; // goto label write_to_output("goto WHILE_EXP" + label + "\n"); // label end write_to_output("label WHILE_END" + label + "\n"); pop_error_context() ; } // ast create_if(ast condition,ast if_true) static void walk_if(ast n) { push_error_context("walk_if()") ; string label = to_string(if_counter++) ; walk_expression(get_if_condition(n)) ; // if-go then write_to_output("if-goto IF_TRUE" + label + '\n'); // goto else write_to_output("goto IF_FALSE" + label + '\n'); // label then write_to_output("label IF_TRUE" + label + '\n'); walk_sequence(get_if_if_true(n)) ; // label else write_to_output("label IF_FALSE" + label + '\n'); pop_error_context() ; } // ast create_if_else(ast condition,ast if_true,ast if_false) static void walk_if_else(ast n) { push_error_context("walk_if_else()") ; string label = to_string(if_counter++) ; walk_expression(get_if_else_condition(n)) ; // if-go then write_to_output("if-goto IF_TRUE" + label + '\n'); // goto else write_to_output("goto IF_FALSE" + label + '\n'); // label then write_to_output("label IF_TRUE" + label + '\n'); walk_sequence(get_if_else_if_true(n)) ; // goto_ end write_to_output("goto IF_END" + label + '\n'); // label else write_to_output("label IF_FALSE" + label + '\n'); walk_sequence(get_if_else_if_false(n)) ; // label end write_to_output("label IF_END" + label + '\n'); pop_error_context() ; } // ast create_let(ast variable,ast expression) static void walk_let(ast n) { ast var = get_let_variable(n) ; string segment = get_variable_segment(var) ; int offset = get_variable_offset(var) ; walk_expression(get_let_expression(n)) ; write_to_output("pop " + segment + ' ' + std::to_string(offset) + "\n") ; } // ast create_statements(vector<ast> statements) ; static void walk_sequence(ast n) { push_error_context("walk_sequence()") ; int children = size_of_statements(n) ; for ( int i = 0 ; i < children ; i++ ){ walk_statement(get_statements(n,i)) ; } pop_error_context() ; } // there are no expression nodes, only ast_infix_op, ast_variable and ast_int nodes // ast create_infix_op(ast lhs,string op,ast rhs) static void walk_expression(ast n) { push_error_context("walk_expression()") ; ast expr = get_expression_expression(n) ; if ( ast_have_kind(expr,ast_infix_op) ){ walk_term(get_infix_op_lhs(expr)) ; walk_term(get_infix_op_rhs(expr)) ; string op = get_infix_op_op(expr) ; write_to_output(translate_op(op) + '\n') ; }else{ walk_term(expr) ; } pop_error_context() ; } // there are no term nodes, only ast_variable and ast_int nodes // ast create_variable(string name,string segment,int offset,string type) static void walk_term(ast n) { push_error_context("walk_term()") ; ast term = get_term_term(n) ; switch(ast_node_kind(term)) { case ast_variable: { string segment = get_variable_segment(term) ; int offset = get_variable_offset(term) ; write_to_output("push " + segment + ' ' + std::to_string(offset) + "\n"); break ; } case ast_int: { int number = get_int_constant(term) ; write_to_output("push constant " + std::to_string(number) + "\n"); break ; } default: fatal_error(0,"Unknown kind of term node found") ; break ; } pop_error_context() ; } // main program for workshop 11 XML to VM code translator int main(int argc,char **argv) { // make all output and errors appear immediately config_output(iob_immediate) ; config_errors(iob_immediate) ; walk_program(ast_parse_xml()) ; // flush the output and any errors print_output() ; print_errors() ; }
25.818713
95
0.648471
raymondsim
13588cd320048959df57a64a854159f42709ed18
578
cpp
C++
LGPOperators/LGPOperator_Division.cpp
chen0040/cpp-linear-genetic-programming
8b0bc8701110af0b7506546e527bd03f57d972fe
[ "MIT" ]
3
2018-01-09T06:03:23.000Z
2020-12-29T20:09:44.000Z
LGPOperators/LGPOperator_Division.cpp
chen0040/cpp-linear-genetic-programming
8b0bc8701110af0b7506546e527bd03f57d972fe
[ "MIT" ]
1
2017-11-15T04:24:43.000Z
2017-11-18T02:17:12.000Z
LGPOperators/LGPOperator_Division.cpp
chen0040/cpp-linear-genetic-programming
8b0bc8701110af0b7506546e527bd03f57d972fe
[ "MIT" ]
2
2017-09-17T04:24:24.000Z
2020-01-29T05:35:49.000Z
#include "LGPOperator_Division.h" #include "../LGPConstants/LGPProtectedDefinition.h" LGPOperator_Division::LGPOperator_Division() : LGPOperator("/") { } LGPOperator_Division::~LGPOperator_Division() { } int LGPOperator_Division::Execute(const LGPRegister* operand1, const LGPRegister* operand2, LGPRegister* destination_register) { if(operand2->ToDouble() == 0) { destination_register->SetValue(operand1->ToDouble() + LGP_UNDEFINED); } else { destination_register->SetValue(operand1->ToDouble() / operand2->ToDouble()); } return LGP_EXECUTE_NEXT_INSTRUCTION; }
21.407407
126
0.768166
chen0040
1358c027fd241943d2d4940191d014559b6cdedb
723
cpp
C++
Codeforces/ProblemSet/489C.cpp
Binary-bug/CP
f9f356d36bd252c71ee3ed2d0585cc372f2baf5e
[ "MIT" ]
null
null
null
Codeforces/ProblemSet/489C.cpp
Binary-bug/CP
f9f356d36bd252c71ee3ed2d0585cc372f2baf5e
[ "MIT" ]
null
null
null
Codeforces/ProblemSet/489C.cpp
Binary-bug/CP
f9f356d36bd252c71ee3ed2d0585cc372f2baf5e
[ "MIT" ]
null
null
null
//'''This code is from after reading tutorial''' #include<iostream> #include<vector> #include<string> #include<algorithm> using namespace std; bool can(int m,int s){ return s >=0 && s <= 9*m; } int main(){ int a,b,c,d,i,m,s; cin >> m >> s; string minn; a = s; for(i=0 ; i < m; i++){ for(d=0; d < 10; d++){ if((i > 0 || d > 0 || (m == 1 && d==0)) && can(m-i-1,s-d)){ minn += char('0'+d); s-=d; break; } } } if(minn.size() != m){ cout << -1 << " " << -1 << endl; return 0; } cout << minn << " "; string maxx; for(i=0; i < m; i++){ for(d=9; d >=0; d--){ if(can(m-i-1,a-d)){ maxx += char('0'+ d); a -=d ; break ; } } } cout << maxx << endl; return 0; }
15.0625
62
0.453665
Binary-bug
13618be9f365b65ad584ba2d5f342c91624a25b1
750
cpp
C++
closest-binary-search-tree-value/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
closest-binary-search-tree-value/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
closest-binary-search-tree-value/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int closestValue(TreeNode* root, double target) { double diff = target - root->val; if (diff < 0 && root->left != NULL) { int leftVal = closestValue(root->left, target); return fabs(diff) < fabs(leftVal - target) ? root->val : leftVal; } else if (diff > 0 && root->right != NULL) { int rightVal = closestValue(root->right, target); return fabs(diff) < fabs(rightVal - target) ? root->val : rightVal; } return root->val; } };
31.25
79
0.545333
tsenmu
1361d73e414a7eb886e778b7ec7d7616f15662f4
97
cc
C++
day23/main.cc
fniksic/adventofcode
ac09d08bea149f2aab353be2aa0ed16bf3fc47fa
[ "MIT" ]
null
null
null
day23/main.cc
fniksic/adventofcode
ac09d08bea149f2aab353be2aa0ed16bf3fc47fa
[ "MIT" ]
null
null
null
day23/main.cc
fniksic/adventofcode
ac09d08bea149f2aab353be2aa0ed16bf3fc47fa
[ "MIT" ]
null
null
null
#include <iostream> #include "day23.h" int main() { day23(std::cin, std::cout); return 0; }
12.125
29
0.618557
fniksic
1361ec821c5d44ab4679467069b90fd421660b6a
2,416
cpp
C++
src/property/pvAlarm.cpp
hir12111/pvDataCPP
d12571b4cdaaf8010b2e11e04905fde85b287299
[ "MIT" ]
null
null
null
src/property/pvAlarm.cpp
hir12111/pvDataCPP
d12571b4cdaaf8010b2e11e04905fde85b287299
[ "MIT" ]
null
null
null
src/property/pvAlarm.cpp
hir12111/pvDataCPP
d12571b4cdaaf8010b2e11e04905fde85b287299
[ "MIT" ]
null
null
null
/* pvAlarm.cpp */ /* * Copyright information and license terms for this software can be * found in the file LICENSE that is included with the distribution */ /** * @author mrk */ #include <string> #include <stdexcept> #define epicsExportSharedSymbols #include <pv/pvType.h> #include <pv/pvIntrospect.h> #include <pv/pvData.h> #include <pv/pvAlarm.h> using std::tr1::static_pointer_cast; using std::string; namespace epics { namespace pvData { string PVAlarm::noAlarmFound("No alarm structure found"); string PVAlarm::notAttached("Not attached to an alarm structure"); bool PVAlarm::attach(PVFieldPtr const & pvField) { if(pvField->getField()->getType()!=structure) return false; PVStructurePtr pvStructure = static_pointer_cast<PVStructure>(pvField); pvSeverity = pvStructure->getSubField<PVInt>("severity"); if(pvSeverity.get()==NULL) return false; pvStatus = pvStructure->getSubField<PVInt>("status"); if(pvStatus.get()==NULL) { pvSeverity.reset(); return false; } pvMessage = pvStructure->getSubField<PVString>("message"); if(pvMessage.get()==NULL) { pvSeverity.reset(); pvStatus.reset(); return false; } return true; } void PVAlarm::detach() { pvSeverity.reset(); pvStatus.reset(); pvMessage.reset(); } bool PVAlarm::isAttached() { if(pvSeverity.get()==NULL) return false; return true; } void PVAlarm::get(Alarm & alarm) const { if(pvSeverity.get()==NULL) { throw std::logic_error(notAttached); } alarm.setSeverity(AlarmSeverityFunc::getSeverity(pvSeverity->get())); alarm.setStatus(AlarmStatusFunc::getStatus(pvStatus->get())); alarm.setMessage(pvMessage->get()); } bool PVAlarm::set(Alarm const & alarm) { if(pvSeverity.get()==NULL) { throw std::logic_error(notAttached); } if(pvSeverity->isImmutable() || pvMessage->isImmutable()) return false; Alarm current; get(current); bool returnValue = false; if(current.getSeverity()!=alarm.getSeverity()) { pvSeverity->put(alarm.getSeverity()); returnValue = true; } if(current.getStatus()!=alarm.getStatus()) { pvStatus->put(alarm.getStatus()); returnValue = true; } if(current.getMessage()!=alarm.getMessage()) { pvMessage->put(alarm.getMessage()); returnValue = true; } return returnValue; } }}
24.907216
75
0.66101
hir12111
13647431df0d0e33c3f278fa19c5923de23b3073
6,245
cpp
C++
src/States/LoadState.cpp
thibautcornolti/IndieStudio
1d0b76b1ca7b4e35b7c9d251fdb3f7ff96debfd7
[ "MIT" ]
null
null
null
src/States/LoadState.cpp
thibautcornolti/IndieStudio
1d0b76b1ca7b4e35b7c9d251fdb3f7ff96debfd7
[ "MIT" ]
null
null
null
src/States/LoadState.cpp
thibautcornolti/IndieStudio
1d0b76b1ca7b4e35b7c9d251fdb3f7ff96debfd7
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2018 ** bomberman ** File description: ** LoadState.cpp */ #ifdef __linux__ #include <glob.h> #elif _WIN32 #include <windows.h> #endif #include "../../include/States/LoadState.hpp" #include "../../include/Singletons/StateMachine.hpp" #include "../../include/Singletons/IrrManager.hpp" #include "../../include/Singletons/EventReceiver.hpp" #include "../../include/Singletons/AssetsPool.hpp" #include "../../include/States/TransitionToGameState.hpp" #include "../../include/PathManager.hpp" const std::map<LoadState::Actions, LoadState::ButtonsDesc> LoadState::_descs { {LoadState::SAVE1, { {610, 250, 1300, 300}, "default", [](LoadState *self) { StateMachine::getInstance().push( new TransitionToGameState(self->_share, self->_saves[self->_idx * 4 + 0]), false); return true; } }}, {LoadState::SAVE2, { {610, 350, 1300, 400}, "default", [](LoadState *self) { StateMachine::getInstance().push( new TransitionToGameState(self->_share, self->_saves[self->_idx * 4 + 1]), false); return true; } }}, {LoadState::SAVE3, { {610, 450, 1300, 500}, "default", [](LoadState *self) { StateMachine::getInstance().push( new TransitionToGameState(self->_share, self->_saves[self->_idx * 4 + 2]), false); return true; } }}, {LoadState::SAVE4, { {610, 550, 1300, 600}, "default", [](LoadState *self) { StateMachine::getInstance().push( new TransitionToGameState(self->_share, self->_saves[self->_idx * 4 + 3]), false); return true; } }}, {LoadState::CANCEL, { {1570, 850, 1870, 900}, "cancel", [](LoadState *self) { self->externalEventsClean(); StateMachine::getInstance().pop(); return false; } }}, {LoadState::PREV, { {785, 850, 935, 900}, "prev", [](LoadState *self) { self->_idx -= 1; self->setSaveButtons(); return true; } }}, {LoadState::NEXT, { {985, 850, 1135, 900}, "next", [](LoadState *self) { self->_idx += 1; self->setSaveButtons(); return true; } }} }; LoadState::LoadState(AStateShare &_share) : AState(_share), AMenuSound(), _idx(0), _eventsActivate(false) { } LoadState::~LoadState() { eventsClean(); } void LoadState::loadButtons() { auto gui = IrrManager::getInstance().getGuienv(); auto &er = EventReceiver::getInstance(); auto &ap = AssetsPool::getInstance(); for (auto &n : _descs) { auto b = gui->addButton(n.second.pos, nullptr, n.first); auto name = n.second.name; b->setImage(ap.loadTexture("buttons/" + name + ".png")); b->setPressedImage(ap.loadTexture("buttons/" + name + "_hover.png")); b->setOverrideFont(_share.getFont()); _buttons.push_back(b); } #ifdef __linux__ glob_t glob_result; glob(PathManager::getHomePath("save/*.dat").c_str(), GLOB_TILDE, NULL, &glob_result); for (unsigned int i = 0; i < glob_result.gl_pathc; ++i) _saves.emplace_back(glob_result.gl_pathv[i]); _idx = 0; #elif _WIN32 HANDLE hFind; WIN32_FIND_DATA data; auto path = PathManager::getHomePath("save/"); auto pattern = PathManager::getHomePath("save/*.dat"); hFind = FindFirstFile(pattern.c_str(), &data); if (hFind != INVALID_HANDLE_VALUE) { do { _saves.emplace_back(path + std::string(data.cFileName)); } while (FindNextFile(hFind, &data)); FindClose(hFind); } #endif setSaveButtons(); } void LoadState::unloadButtons() { for (auto &n : _buttons) n->remove(); _buttons.clear(); } void LoadState::load() { eventsSetup(); loadButtons(); AState::load(); } void LoadState::unload() { unloadButtons(); AState::unload(); } void LoadState::update() { _share.getFunc("rotateMenu")(); AState::update(); AssetsPool::getInstance().cleanSound(); if (getSharedResources().isKeyDown(irr::KEY_ESCAPE)) StateMachine::getInstance().pop(); } void LoadState::draw() { auto &im = IrrManager::getInstance(); im.getSmgr()->drawAll(); im.getGuienv()->drawAll(); } bool LoadState::applyEventButton(const irr::SEvent &ev, LoadState::Actions id) { auto b = getButton(id); auto hover_name = "buttons/" + _descs.at(id).name + "_hover.png"; auto name = "buttons/" + _descs.at(id).name + ".png"; auto &ap = AssetsPool::getInstance(); switch (ev.GUIEvent.EventType) { case irr::gui::EGET_BUTTON_CLICKED: playSelect(); return LoadState::_descs.at(id).fct(this); case irr::gui::EGET_ELEMENT_HOVERED: playCursor(); b->setImage(ap.loadTexture(hover_name)); break; case irr::gui::EGET_ELEMENT_LEFT: b->setImage(ap.loadTexture(name)); break; default: break; } return true; } irr::gui::IGUIButton *LoadState::getButton(LoadState::Actions id) const { if (id < SAVE1 || id > SAVE1 + LOAD_BUTTON_NUMBER) return nullptr; return (_buttons.at(id - SAVE1)); } void LoadState::setSaveButtons() { size_t i = _idx * 4; std::string empty = "- Empty Slot -"; for (; i < _saves.size() && (i == (_idx * 4) || i%4); ++i) { #ifdef _WIN32 std::string temp(_saves[i].substr(_saves[i].rfind('\\') + 1)); #else std::string temp(_saves[i].substr(_saves[i].rfind('/') + 1)); #endif _buttons[i%4]->setText(std::wstring(temp.begin(), temp.end()).c_str()); _buttons[i%4]->setEnabled(true); } for (; i == _idx * 4 || i%4; ++i) { _buttons[i%4]->setEnabled(false); _buttons[i%4]->setText(std::wstring(empty.begin(), empty.end()).c_str()); } _buttons[PREV - SAVE1]->setEnabled(_idx > 0); _buttons[NEXT - SAVE1]->setEnabled((_idx + 1) * 4 < _saves.size()); } void LoadState::eventsSetup() { _eventsActivate = true; auto &er = EventReceiver::getInstance(); er.registerEvent(20, irr::EEVENT_TYPE::EET_GUI_EVENT, [this](const irr::SEvent &ev) { if (!this->isLoaded() || !this->isEnable()) return true; auto id = static_cast<Actions >(ev.GUIEvent.Caller->getID()); if (LoadState::_descs.count(id) > 0) return this->applyEventButton(ev, id); return true; }); } void LoadState::eventsClean() { if (!_eventsActivate) return; auto &er = EventReceiver::getInstance(); er.unregisterEvent(20, irr::EEVENT_TYPE::EET_GUI_EVENT); _eventsActivate = false; } void LoadState::externalEventsClean() { if (!_eventsActivate) return; _eventsActivate = false; } const std::string LoadState::getName() const { return "load"; }
22.959559
86
0.651241
thibautcornolti
1365abbfb679234773f5cd66886d8e2ba8ad6c76
1,049
cpp
C++
contest/1407/b/b2.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
contest/1407/b/b2.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
contest/1407/b/b2.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define watch(x) std::cout << (#x) << " is " << (x) << std::endl #define print(x) std::cout << (x) << std::endl using LL = long long; int main() { //freopen("in", "r", stdin); std::cin.tie(nullptr)->sync_with_stdio(false); int cas; std::cin >> cas; while (cas--) { int n; std::cin >> n; int a[n]; bool v[n] = {}; for (int i = 0; i < n; ++i) std::cin >> a[i]; int id = std::max_element(a, a + n) - a; std::vector<int> ans; ans.push_back(a[id]); v[id] = 1; int now = a[id]; while (ans.size() != n) { int mx = 0, mi = 1e9 + 2; for (int i = 0; i < n; ++i) if (!v[i]) { mx = std::max(mx, std::__gcd(now, a[i])); mi = std::max(mi, std::__gcd(now, a[i])); } if (mx == mi) break; for (int i = 0; i < n; ++i) if (!v[i]) { if(mx == std::__gcd(now, a[i])) { ans.push_back(a[i]); v[i] = 1; } } now = mx; } for (auto x : ans) std::cout << x << " "; for (int i = 0; i < n; ++i) if (!v[i]) std::cout << a[i] << " "; std::cout << std::endl; } return 0; }
24.97619
66
0.468065
GoatGirl98
13674626a7fb2e173d738ed72266a3b6fb0e5872
6,963
cpp
C++
src/string_utils.cpp
sweetkristas/anura
5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd
[ "CC0-1.0" ]
null
null
null
src/string_utils.cpp
sweetkristas/anura
5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd
[ "CC0-1.0" ]
null
null
null
src/string_utils.cpp
sweetkristas/anura
5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd
[ "CC0-1.0" ]
null
null
null
/* Copyright (C) 2003-2013 by David White <davewx7@gmail.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "string_utils.hpp" #include "unit_test.hpp" #include <algorithm> #include <stdio.h> #include "compat.hpp" namespace util { bool c_isalnum(int c) { return ::isalnum(static_cast<unsigned char>(c)); } bool c_isalpha(int c) { return ::isalpha(static_cast<unsigned char>(c)); } bool c_isascii(int c) { return isascii(static_cast<unsigned char>(c)); } bool c_isblank(int c) { #if defined(_WINDOWS) return __isblank(c); #else return ::isblank(static_cast<unsigned char>(c)); #endif } bool c_iscntrl(int c) { return ::iscntrl(static_cast<unsigned char>(c)); } bool c_isdigit(int c) { return ::isdigit(static_cast<unsigned char>(c)); } bool c_isgraph(int c) { return ::isgraph(static_cast<unsigned char>(c)); } bool c_islower(int c) { return ::islower(static_cast<unsigned char>(c)); } bool c_isprint(int c) { return ::isprint(static_cast<unsigned char>(c)); } bool c_ispunct(int c) { return ::ispunct(static_cast<unsigned char>(c)); } bool c_isspace(int c) { return ::isspace(static_cast<unsigned char>(c)); } bool c_isupper(int c) { return ::isupper(static_cast<unsigned char>(c)); } bool c_isxdigit(int c) { return ::isxdigit(static_cast<unsigned char>(c)); } bool c_isnewline(char c) { return c == '\r' || c == '\n'; } bool portable_isspace(char c) { return c_isnewline(c) || c_isspace(c); } bool notspace(char c) { return !portable_isspace(c); } std::string &strip(std::string &str) { std::string::iterator it = std::find_if(str.begin(), str.end(), notspace); str.erase(str.begin(), it); str.erase(std::find_if(str.rbegin(), str.rend(), notspace).base(), str.end()); return str; } std::vector<std::string> split(std::string const &val, const std::string& delim) { std::vector<std::string> result; if(delim.empty()) { foreach(char c, val) { result.push_back(std::string(1, c)); } return result; } const char* ptr = val.c_str(); for(;;) { const char* end = strstr(ptr, delim.c_str()); if(end == NULL) { result.push_back(std::string(ptr)); return result; } result.push_back(std::string(ptr, end)); ptr = end + delim.size(); } return result; } std::vector<std::string> split(std::string const &val, char c, int flags) { std::vector<std::string> res; split(val, res, c, flags); return res; } void split(std::string const &val, std::vector<std::string>& res, char c, int flags) { std::string::const_iterator i1 = val.begin(); std::string::const_iterator i2 = val.begin(); while (i2 != val.end()) { if (*i2 == c) { std::string new_val(i1, i2); if (flags & STRIP_SPACES) strip(new_val); if (!(flags & REMOVE_EMPTY) || !new_val.empty()) res.push_back(new_val); ++i2; if (flags & STRIP_SPACES) { while (i2 != val.end() && *i2 == ' ') ++i2; } i1 = i2; } else { ++i2; } } std::string new_val(i1, i2); if (flags & STRIP_SPACES) strip(new_val); if (!(flags & REMOVE_EMPTY) || !new_val.empty()) res.push_back(new_val); } std::string join(const std::vector<std::string>& v, char j) { std::string res; for(int n = 0; n != v.size(); ++n) { if(n != 0) { res.push_back(j); } res += v[n]; } return res; } const char* split_into_ints(const char* s, int* output, int* output_size) { char* endptr = NULL; int index = 0; for(;;) { int result = strtol(s, &endptr, 10); if(endptr == s) { break; } if(index < *output_size) { output[index] = result; } ++index; if(*endptr != ',') { break; } s = endptr+1; } *output_size = index; return endptr; } std::vector<int> split_into_vector_int(const std::string& s) { std::vector<std::string> v = util::split(s); std::vector<int> result(v.size()); for(int n = 0; n != v.size(); ++n) { result[n] = atoi(v[n].c_str()); } return result; } std::string join_ints(const int* ints, int size) { std::string result; char buf[256]; for(int n = 0; n != size; ++n) { if(n != 0) { result += ","; } sprintf(buf, "%d", ints[n]); result += buf; } return result; } bool string_starts_with(const std::string& target, const std::string& prefix) { if(target.length() < prefix.length()) { return false; } std::string target_pfx = target.substr(0,prefix.length()); return target_pfx == prefix; } std::string strip_string_prefix(const std::string& target, const std::string& prefix) { if(target.length() < prefix.length()) { return ""; } return target.substr(prefix.length()); } bool wildcard_pattern_match(std::string::const_iterator p1, std::string::const_iterator p2, std::string::const_iterator i1, std::string::const_iterator i2) { if(i1 == i2) { while(p1 != p2) { if(*p1 != '*') { return false; } ++p1; } return true; } if(p1 == p2) { return false; } if(*p1 == '*') { ++p1; if(p1 == p2) { return true; } while(i1 != i2) { if(wildcard_pattern_match(p1, p2, i1, i2)) { return true; } ++i1; } return false; } if(*p1 != *i1) { return false; } return wildcard_pattern_match(p1+1, p2, i1+1, i2); } bool wildcard_pattern_match(const std::string& pattern, const std::string& str) { return wildcard_pattern_match(pattern.begin(), pattern.end(), str.begin(), str.end()); } } UNIT_TEST(test_wildcard_matches) { CHECK_EQ(util::wildcard_pattern_match("abc", "abc"), true); CHECK_EQ(util::wildcard_pattern_match("abc", "abcd"), false); CHECK_EQ(util::wildcard_pattern_match("abc*", "abcd"), true); CHECK_EQ(util::wildcard_pattern_match("*", "abcwj;def"), true); CHECK_EQ(util::wildcard_pattern_match("**", "abcwj;def"), true); CHECK_EQ(util::wildcard_pattern_match("*x", "abcwj;def"), false); CHECK_EQ(util::wildcard_pattern_match("abc*def", "abcwj;def"), true); CHECK_EQ(util::wildcard_pattern_match("abc*def", "abcwj;eef"), false); } UNIT_TEST(test_split_into_ints) { int buf[6]; int buf_size = 6; const char* str = "4,18,7,245"; const char* res = util::split_into_ints(str, buf, &buf_size); CHECK_EQ(buf_size, 4); CHECK_EQ(res, str + strlen(str)); CHECK_EQ(buf[0], 4); CHECK_EQ(buf[1], 18); CHECK_EQ(buf[2], 7); CHECK_EQ(buf[3], 245); buf[1] = 0; buf_size = 1; res = util::split_into_ints(str, buf, &buf_size); CHECK_EQ(buf_size, 4); CHECK_EQ(res, str + strlen(str)); CHECK_EQ(buf[0], 4); CHECK_EQ(buf[1], 0); }
19.951289
155
0.648571
sweetkristas
1367e9d59b01776daa3604a820132a84b69951dd
3,930
cc
C++
ext/candc/src/lib/io/reader_multi_horiz.cc
TeamSPoon/logicmoo_nlu
5c3e5013a3048da7d68a8a43476ad84d3ea4bb47
[ "MIT" ]
6
2020-01-27T12:08:02.000Z
2020-02-28T19:30:28.000Z
pack/logicmoo_nlu/prolog/candc/src/lib/io/reader_multi_horiz.cc
logicmoo/old_logicmoo_workspace
44025b6e389e2f2f7d86b46c1301cab0604bba26
[ "MIT" ]
2
2017-03-13T02:56:09.000Z
2019-07-27T02:47:29.000Z
ext/candc/src/lib/io/reader_multi_horiz.cc
TeamSPoon/logicmoo_nlu
5c3e5013a3048da7d68a8a43476ad84d3ea4bb47
[ "MIT" ]
1
2020-11-25T06:09:33.000Z
2020-11-25T06:09:33.000Z
// C&C NLP tools // Copyright (c) Universities of Edinburgh, Oxford and Sydney // Copyright (c) James R. Curran // // This software is covered by a non-commercial use licence. // See LICENCE.txt for the full text of the licence. // // If LICENCE.txt is not included in this distribution // please email candc@it.usyd.edu.au to obtain a copy. #include "base.h" #include "io/reader.h" #include "io/reader_horiz.h" #include "io/reader_multi_horiz.h" namespace NLP { namespace IO { typedef Sentence::FieldNames FN; static std::string build_name(const std::string &name, const FN &fieldnames){ if(name.length()) return name; else return "MultiHReader(" + fieldnames + ')'; } MultiHReader::MultiHReader(std::istream &in, const std::string &uri, const FN &fieldnames, char SEP, const std::string &name): HReader(in, uri, SEP, build_name(name, fieldnames)), fieldnames(fieldnames){ if(fieldnames.size() == 0) die(msg << "fieldnames must be contain at least one field descriptor"); for(FN::const_iterator i = fieldnames.begin(); i != fieldnames.end(); ++i) if(Sentence::type(*i) == Sentence::TYPE_INVALID) die(msg << '\'' << *i << "' is not a valid fieldname"); } bool MultiHReader::next(NLP::Sentence &sentence, bool add, bool expect){ if(!add) sentence.reset(); if(!next_line()) return check(add, expect, false); char *begin = buffer; char *i = begin; char *end = begin + len; if(*begin == '\0') return check(add, expect, true); if(*begin == ' ') die(msg << "whitespace at the beginning of the sentence is illegal"); ulong current = 0; const FN::const_iterator last_field = fieldnames.end() - 1; while(begin < end){ FN::const_iterator field = fieldnames.begin(); for( ; field != fieldnames.end(); ++field){ switch(begin[0]){ case '\0': switch(begin[-1]){ case '\0': die(msg << "unexpected end of sentence (missing separator and field '" << *field << "')"); case ' ': die(msg << "whitespace at the end of the sentence is illegal"); default: if(begin[-1] == SEP) die(msg << "unexpected end of sentence (missing field '" << *field << "')"); } break; case ' ': if(begin[-1] == ' '){ while(*begin == ' ') ++begin; if(*begin) die(msg << "multiple whitespaces between words is illegal"); else die(msg << "whitespace at the end of the sentence is illegal"); }else if(begin[-1] == SEP) die(msg << "unexpected end of token (missing field '" << *field << "')"); break; default: if(begin[0] == SEP){ if(begin[-1] == SEP && Sentence::type(*field) > Sentence::TYPE_OPTIONAL) die(msg << "empty fields (except [0-9?]) are illegal (empty field '" << *field << "')"); else if(begin[-1] == ' ') die(msg << "unexpected sep before field " << *field); } } for( ; *i; ++i) if(*i == SEP || *i == ' ') break; if(*i == ' ' && field != last_field) die(msg << "unexpected end of token (missing sep and " << field[1] << " field)"); if(*i == '\0' && field != last_field) die(msg << "unexpected end of sentence (missing sep and " << field[1] << " field)"); if(*field != '?'){ std::vector<std::string> &tokens = sentence.get_single(*field); std::string token(begin, i - begin); if(add){ if(current >= tokens.size()) die(msg << "sentence is not aligned (token " << current + 1 << " '" << token << "' makes sentence too long)"); if(tokens[current] != token) die(msg << "field " << *field << " is not aligned (token " << current + 1 << " is '" << token << "' but should be '" << tokens[current] << "\')"); ++current; }else tokens.push_back(token); } begin = ++i; } if(i[-1] == SEP) die(msg << "too many fields in token"); if(field != fieldnames.end()) die(msg << "unexpected end of token (missing sep and " << *field << " field)"); } return check(add, expect, true); } } }
29.772727
102
0.59771
TeamSPoon
136cb002fcf18db52a3301f4640947a991159b3f
9,051
cpp
C++
src/Examples/BillboardedSprite/BillboardedSpriteExample.cpp
wrld3d/eegeo-sdk-samples
eb1a1e4d4b7d3eb79ad454cc5a09d1847018269d
[ "BSD-2-Clause" ]
11
2017-06-26T08:59:03.000Z
2021-09-28T13:12:22.000Z
src/Examples/BillboardedSprite/BillboardedSpriteExample.cpp
wrld3d/eegeo-sdk-samples
eb1a1e4d4b7d3eb79ad454cc5a09d1847018269d
[ "BSD-2-Clause" ]
4
2016-07-09T14:54:22.000Z
2017-04-26T14:02:53.000Z
src/Examples/BillboardedSprite/BillboardedSpriteExample.cpp
wrld3d/eegeo-sdk-samples
eb1a1e4d4b7d3eb79ad454cc5a09d1847018269d
[ "BSD-2-Clause" ]
9
2016-04-08T03:43:13.000Z
2016-12-12T02:07:49.000Z
#include "BillboardedSpriteExample.h" #include "BatchedSpriteRenderable.h" #include "BatchedSpriteShader.h" #include "BatchedSpriteMaterial.h" #include "RenderingModule.h" #include "ShaderIdGenerator.h" #include "MaterialIdGenerator.h" #include "VertexLayoutPool.h" #include "VertexBindingPool.h" #include "RenderableFilters.h" #include "RenderQueue.h" #include "RenderContext.h" #include "LatLongAltitude.h" #include "GlobeCameraController.h" #include "CameraHelpers.h" #include "IWebLoadRequestFactory.h" #include "IWebLoadRequest.h" #include <string> namespace Examples { namespace { const float TimeDelayUntilWebRequestInSeconds = 5.0f; const Eegeo::Space::LatLongAltitude SanFranBayLatLong = Eegeo::Space::LatLongAltitude::FromDegrees(37.778747, -122.384463, 0.0); } BillboardedSpriteExample::BillboardedSpriteExample(Eegeo::Camera::GlobeCamera::GlobeCameraController* pCameraController, Eegeo::Camera::GlobeCamera::GlobeCameraTouchController& cameraTouchController, Eegeo::Modules::Core::RenderingModule& renderingModule, Eegeo::Helpers::ITextureFileLoader& textureFileLoader, Eegeo::Web::IWebLoadRequestFactory& webRequestFactory) : GlobeCameraExampleBase(pCameraController, cameraTouchController) , m_renderingModule(renderingModule) , m_textureFileLoader(textureFileLoader) , m_pBatchedSpriteRenderable(NULL) , m_pBatchedSpriteShader(NULL) , m_pBatchedSpriteMaterial(NULL) , m_pAsyncBatchedSpriteMaterial(NULL) , m_spriteEcefPosition(SanFranBayLatLong.ToECEF()) , m_spriteDimensions(Eegeo::v2(100.0, 100.0)) , m_spriteUvBounds(Eegeo::Geometry::Bounds2D(Eegeo::v2::Zero(), Eegeo::v2::One())) , m_spriteColor(Eegeo::v4::One()) , m_hasMadeWebRequest(false) , m_webRequestFactory(webRequestFactory) , m_webLoadCallback(this, &BillboardedSpriteExample::OnWebLoadCompleted) , m_webRequestDelayTimer(0.0f) { m_textureInfo.textureId = 0; m_textureInfo.height = 0; m_textureInfo.width = 0; m_asyncTextureInfo.textureId = 0; m_asyncTextureInfo.height = 0; m_asyncTextureInfo.width = 0; } BillboardedSpriteExample::~BillboardedSpriteExample() { Eegeo::Rendering::RenderableFilters& renderableFilters = m_renderingModule.GetRenderableFilters(); renderableFilters.RemoveRenderableFilter(*this); Eegeo_DELETE m_pBatchedSpriteRenderable; Eegeo_DELETE m_pBatchedSpriteMaterial; Eegeo_DELETE m_pAsyncBatchedSpriteMaterial; Eegeo_DELETE m_pBatchedSpriteShader; Eegeo_GL(glDeleteTextures(1, &m_textureInfo.textureId)); Eegeo_GL(glDeleteTextures(1, &m_asyncTextureInfo.textureId)); } void BillboardedSpriteExample::Start() { Eegeo::Rendering::Shaders::ShaderIdGenerator& shaderIdGenerator = m_renderingModule.GetShaderIdGenerator(); m_pBatchedSpriteShader = Eegeo::Rendering::Shaders::BatchedSpriteShader::Create(shaderIdGenerator.GetNextId()); std::string localTextureFile = "billboarded_sprite_example/placeholder.png"; bool success = m_textureFileLoader.LoadTexture(m_textureInfo, localTextureFile, false); Eegeo_ASSERT(success, "failed to load texture"); Eegeo::Rendering::Materials::MaterialIdGenerator& materialIdGenerator = m_renderingModule.GetMaterialIdGenerator(); m_pBatchedSpriteMaterial = Eegeo_NEW(Eegeo::Rendering::Materials::BatchedSpriteMaterial)(materialIdGenerator.GetNextId(), "ExampleBatchedSpriteMaterial", *m_pBatchedSpriteShader, m_textureInfo.textureId); Eegeo::Rendering::VertexLayouts::VertexLayoutPool& vertexLayoutPool = m_renderingModule.GetVertexLayoutPool(); Eegeo::Rendering::VertexLayouts::VertexBindingPool& vertexBindingPool = m_renderingModule.GetVertexBindingPool(); const Eegeo::Rendering::VertexLayouts::VertexBinding& vertexBinding = vertexBindingPool.GetVertexBinding(vertexLayoutPool.GetForTexturedColoredVertex(), m_pBatchedSpriteShader->GetVertexAttributes()); m_pBatchedSpriteRenderable = Eegeo_NEW(Eegeo::Rendering::Renderables::BatchedSpriteRenderable)(Eegeo::Rendering::LayerIds::AfterAll, m_pBatchedSpriteMaterial, vertexBinding, m_renderingModule.GetGlBufferPool(), Eegeo::Rendering::Renderables::BatchedSpriteAnchor::Centre); Eegeo::Rendering::RenderableFilters& renderableFilters = m_renderingModule.GetRenderableFilters(); renderableFilters.AddRenderableFilter(*this); Eegeo::Space::EcefTangentBasis cameraInterestBasis; Eegeo::Camera::CameraHelpers::EcefTangentBasisFromPointAndHeading(m_spriteEcefPosition, 0.0, cameraInterestBasis); GetGlobeCameraController().SetView(cameraInterestBasis, 1000.f); } void BillboardedSpriteExample::Update(float dt) { if (!m_hasMadeWebRequest && m_webRequestDelayTimer > TimeDelayUntilWebRequestInSeconds) { std::string webRequestUrl = "http://cdn1.eegeo.com/mobile-sdk-harness-data/eegeo-tile.png"; Eegeo::Web::IWebLoadRequest* pWebLoadRequest = m_webRequestFactory.Begin(Eegeo::Web::HttpVerbs::GET, webRequestUrl, m_webLoadCallback).Build(); pWebLoadRequest->Load(); m_hasMadeWebRequest = true; } else { m_webRequestDelayTimer += dt; } } void BillboardedSpriteExample::EnqueueRenderables(const Eegeo::Rendering::RenderContext& renderContext, Eegeo::Rendering::RenderQueue& renderQueue) { m_pBatchedSpriteRenderable->Reset(); const Eegeo::Camera::RenderCamera& renderCamera = renderContext.GetRenderCamera(); m_pBatchedSpriteRenderable->SetModelViewProjection(renderCamera.GetViewProjectionMatrix()); m_pBatchedSpriteRenderable->AddSprite(renderCamera, m_spriteEcefPosition, m_spriteUvBounds.min, m_spriteUvBounds.max, m_spriteColor, m_spriteDimensions); renderQueue.EnqueueRenderable(*m_pBatchedSpriteRenderable); } void BillboardedSpriteExample::OnWebLoadCompleted(Eegeo::Web::IWebResponse& webResponse) { if (!webResponse.IsSucceeded()) { Eegeo_TTY("Failed to fetch texture %s", webResponse.GetUrl().c_str()); return; } const bool generateMipmaps = true; std::string filenameExtension = webResponse.GetUrl().substr(webResponse.GetUrl().find_last_of(".")); bool success = m_textureFileLoader.LoadFromBuffer(m_asyncTextureInfo, filenameExtension, webResponse.GetBodyData().data(), webResponse.GetBodyData().size(), generateMipmaps); if (!success) { Eegeo_TTY("Failed to load texture %s", webResponse.GetUrl().c_str()); return; } Eegeo::Rendering::Materials::MaterialIdGenerator& materialIdGenerator = m_renderingModule.GetMaterialIdGenerator(); m_pAsyncBatchedSpriteMaterial = Eegeo_NEW(Eegeo::Rendering::Materials::BatchedSpriteMaterial)(materialIdGenerator.GetNextId(), "ExampleAsyncBatchedSpriteMaterial", *m_pBatchedSpriteShader, m_asyncTextureInfo.textureId); m_pBatchedSpriteRenderable->SetMaterial(m_pAsyncBatchedSpriteMaterial, m_renderingModule.GetVertexBindingPool()); } }
52.622093
163
0.596067
wrld3d
1370cbb219e5f0117e1fad56afdfdb8db4f3e237
3,282
cpp
C++
Zinc/src/Core/Main.cpp
DragonJT/Zinc
f76ca4f292c30c7c6e1313d3b656f9f1cac972bf
[ "Apache-2.0" ]
null
null
null
Zinc/src/Core/Main.cpp
DragonJT/Zinc
f76ca4f292c30c7c6e1313d3b656f9f1cac972bf
[ "Apache-2.0" ]
null
null
null
Zinc/src/Core/Main.cpp
DragonJT/Zinc
f76ca4f292c30c7c6e1313d3b656f9f1cac972bf
[ "Apache-2.0" ]
null
null
null
#include "Main.h" #include "Log.h" #include <glad/glad.h> #include "imgui.h" #include "imgui_impl_glfw.h" #include "imgui_impl_opengl3.h" #include "Layers.h" #include "Box2DLayer.h" #include "FirstTriangleLayer.h" #include "Core\Input.h" int main() { float lastTimeFrame = 0; Zinc::Log::Init(); ZINC_CORE_WARN("Initialized Log"); if (!glfwInit()) return -1; GLFWwindow *window = glfwCreateWindow(1024, 800, "Hello World", NULL, NULL); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); Zinc::Input::Init(window); glfwSetKeyCallback(window, Zinc::Input::KeyCallBack); ZINC_CORE_ASSERT(gladLoadGL(), "glad not loaded!"); ZINC_CORE_INFO("OpenGL Renderer:"); ZINC_CORE_INFO("Vendor: {0}", glGetString(GL_VENDOR)); ZINC_CORE_INFO("Renderer: {0}", glGetString(GL_RENDERER)); ZINC_CORE_INFO("Version: {0}", glGetString(GL_VERSION)); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows //io.ConfigViewportsNoAutoMerge = true; //io.ConfigViewportsNoTaskBarIcon = true; // Setup Dear ImGui style ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones. ImGuiStyle& style = ImGui::GetStyle(); if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { style.WindowRounding = 0.0f; style.Colors[ImGuiCol_WindowBg].w = 1.0f; } // Setup Platform/Renderer bindings ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplOpenGL3_Init(); Zinc::Layers *layers = new Zinc::Layers(); //layers->Add(new Zinc::Box2DLayer()); layers->Add(new Zinc::FirstTriangleLayer()); layers->Awake(); while (!glfwWindowShouldClose(window)) { float time = glfwGetTime(); float timeStep = time - lastTimeFrame; lastTimeFrame = time; int display_w, display_h; glfwMakeContextCurrent(window); glfwGetFramebufferSize(window, &display_w, &display_h); //glViewport(0, 0, display_w, display_h); glClearColor(0.1f, 0.1f, 0.1f, 1); glClear(GL_COLOR_BUFFER_BIT); ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); layers->Update(timeStep); ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); // Update and Render additional Platform Windows // (Platform functions may change the current OpenGL context, so we save/restore it to make it easier to paste this code elsewhere. // For this specific demo app we could also call glfwMakeContextCurrent(window) directly) if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { GLFWwindow* backup_current_context = glfwGetCurrentContext(); ImGui::UpdatePlatformWindows(); ImGui::RenderPlatformWindowsDefault(); glfwMakeContextCurrent(backup_current_context); } glfwSwapBuffers(window); //Zinc::Input::Update(); glfwPollEvents(); } layers->OnDestroy(); delete layers; glfwTerminate(); return 0; }
29.836364
133
0.736746
DragonJT
137135179aa583b819fa292e3e9c01b82b0e3393
5,427
hpp
C++
SPS-Variants/tsf/tsf/rgsmanager.hpp
RapidsAtHKUST/SimRank
3a601b08f9a3c281e2b36b914e06aba3a3a36118
[ "MIT" ]
8
2020-04-14T23:17:00.000Z
2021-06-21T12:34:04.000Z
SPS-Variants/tsf/tsf/rgsmanager.hpp
RapidsAtHKUST/SimRank
3a601b08f9a3c281e2b36b914e06aba3a3a36118
[ "MIT" ]
null
null
null
SPS-Variants/tsf/tsf/rgsmanager.hpp
RapidsAtHKUST/SimRank
3a601b08f9a3c281e2b36b914e06aba3a3a36118
[ "MIT" ]
1
2021-01-17T16:26:50.000Z
2021-01-17T16:26:50.000Z
#ifndef __RGSMANAGER_H__ #define __RGSMANAGER_H__ #include <cmath> #include <map> #include <algorithm> #include "rsamplegraph.hpp" #include "simrankvalue.hpp" #include "../util/mytime.h" using namespace std; class RGSManager { public: RGSManager(int sn, int mvid, bool isfm) : sampleGraphNum(sn), maxVertexId(mvid), isFm(isfm) { rsg = new RSampleGraph *[sn]; for (int i = 0; i < sn; ++i) { rsg[i] = new RSampleGraph(maxVertexId); } } ~RGSManager() { for (int i = 0; i < sampleGraphNum; ++i) delete rsg[i]; delete[] rsg; } void insertEdge(int sid, int src, int dst) { /*revserse the edge (src, dst) here. */ #ifdef SINGLE_SOURCE rsg[sid]->addEdge(dst, src); #else rsg[sid]->addEdge(src, dst); #endif } void analysis() { double totalMemCost = 0; for (int i = 0; i < sampleGraphNum; ++i) { rsg[i]->preprocess(); totalMemCost += rsg[i]->getMemSize(); } printf("Index MEM cost: %.5lfMB\n", totalMemCost); } void computeSimrank(int sid, vector<SimRankValue> &sim, map<int, vector<pair<int, int>> *> &timestamp, int maxSteps, double df, int qv, int sqn) { map<int, vector<pair<int, int> > *> meetmap; double buildCost = 0.0; Time timer; /* 1. reverse graph */ for (auto iter = timestamp.begin(); iter != timestamp.end(); ++iter) { sort((*(iter->second)).begin(), (*(iter->second)).end()); } timer.start(); /* 2. compute simrank. */ int comp = 0; int traverse_cnt = 0; /* enumerate meeting points here. */ int *hasMeet = new int[sqn];//hasMeet[i] records whether random walk i has met at vid for (auto iter = timestamp.begin(); iter != timestamp.end(); ++iter) { vector<pair<int, int> > *tsv = iter->second; int vid = iter->first; /* one meeting points. */ int idx = 0; int stepLim; queue<int> cand[2]; int step = 0, cur, cnt; int tsvLen = tsv->size(); cand[step].push(vid); while (idx < tsvLen) { stepLim = (*tsv)[idx].first; memset(hasMeet, 0, sizeof(int) * sqn); cnt = 0; while (idx < tsvLen && stepLim == (*tsv)[idx].first) { int randomWalkId = (*tsv)[idx].second; hasMeet[randomWalkId] = 1; cnt++; idx++; } /* traverse the tree. */ do { while (cand[step & 1].empty() == false) { cur = cand[step & 1].front(); cand[step & 1].pop(); traverse_cnt++; if (qv != cur && step == stepLim) { comp += cnt; /* update SimRank */ //sim[cur].setVid(cur); /* non-first meeting guarantee. */ //sim[cur].incValue(pow(df, step)*cnt); if (meetmap.find(cur) == meetmap.end()) { meetmap[cur] = new vector<pair<int, int> >(); } for (int rid = 0; rid < sqn; rid++) { if (hasMeet[rid] == 1) { meetmap[cur]->push_back(make_pair(stepLim, rid)); } } } /* enumerate edge here! */ rsg[sid]->expand(cur, cand[(step + 1) & 1]); } step++; } while (step <= stepLim); } } //compute simrank value with first-meeting or not for (auto iter2 = meetmap.begin(); iter2 != meetmap.end(); iter2++) { int cur = iter2->first; memset(hasMeet, 0, sizeof(int) * sqn); sort((*(iter2->second)).begin(), (*(iter2->second)).end()); vector<pair<int, int> > *mm = iter2->second; int mmLen = mm->size(); int idx = 0; while (idx < mmLen) { int stepNum = (*mm)[idx].first; int rid = (*mm)[idx].second; if (isFm) { if (hasMeet[rid] == 0) { sim[cur].setVid(cur); sim[cur].incValue(pow(df, stepNum)); hasMeet[rid] = 1; } else { } } else { sim[cur].setVid(cur); sim[cur].incValue(pow(df, stepNum)); } idx++; } } timer.stop(); buildCost = timer.getElapsedTime(); delete[] hasMeet; for (auto iter2 = meetmap.begin(); iter2 != meetmap.end(); iter2++) { delete iter2->second; } } public: RSampleGraph **rsg; private: int sampleGraphNum; int maxVertexId; bool isFm; }; #endif
33.708075
121
0.418832
RapidsAtHKUST
13734d1e1e53785cb219edad331049fe97eae7b1
10,541
cpp
C++
src/AppInstallerRepositoryCore/Rest/Schema/1_0/Interface.cpp
sarvex/winget-cli
e03eb11c81fc1c559ac01572d00c5ea58bb03974
[ "MIT" ]
2
2021-06-09T01:20:23.000Z
2021-06-10T00:53:39.000Z
src/AppInstallerRepositoryCore/Rest/Schema/1_0/Interface.cpp
pseudo-windows/winget-cli
12f100c7920c0d971fbcdd8279f4162b132a18cb
[ "MIT" ]
1
2021-02-05T02:43:54.000Z
2021-02-05T02:43:54.000Z
src/AppInstallerRepositoryCore/Rest/Schema/1_0/Interface.cpp
pseudo-windows/winget-cli
12f100c7920c0d971fbcdd8279f4162b132a18cb
[ "MIT" ]
6
2020-05-25T04:35:53.000Z
2021-03-30T01:57:17.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "pch.h" #include "Rest/Schema/1_0/Interface.h" #include "Rest/Schema/IRestClient.h" #include "Rest/HttpClientHelper.h" #include "Rest/Schema/JsonHelper.h" #include "winget/ManifestValidation.h" #include "Rest/Schema/RestHelper.h" #include "Rest/Schema/CommonRestConstants.h" #include "Rest/Schema/1_0/Json/CommonJsonConstants.h" #include "Rest/Schema/1_0/Json/ManifestDeserializer.h" #include "Rest/Schema/1_0/Json/SearchResponseDeserializer.h" #include "Rest/Schema/1_0/Json/SearchRequestSerializer.h" using namespace std::string_view_literals; using namespace AppInstaller::Repository::Rest::Schema::V1_0::Json; namespace AppInstaller::Repository::Rest::Schema::V1_0 { // Endpoint constants constexpr std::string_view ManifestSearchPostEndpoint = "/manifestSearch"sv; constexpr std::string_view ManifestByVersionAndChannelGetEndpoint = "/packageManifests/"sv; // Query params constexpr std::string_view VersionQueryParam = "Version"sv; constexpr std::string_view ChannelQueryParam = "Channel"sv; namespace { web::json::value GetSearchBody(const SearchRequest& searchRequest) { SearchRequestSerializer serializer; return serializer.Serialize(searchRequest); } utility::string_t GetSearchEndpoint(const std::string& restApiUri) { return RestHelper::AppendPathToUri(JsonHelper::GetUtilityString(restApiUri), JsonHelper::GetUtilityString(ManifestSearchPostEndpoint)); } utility::string_t GetManifestByVersionEndpoint( const std::string& restApiUri, const std::string& packageId, const std::map<std::string_view, std::string>& queryParameters) { utility::string_t versionEndpoint = RestHelper::AppendPathToUri( JsonHelper::GetUtilityString(restApiUri), JsonHelper::GetUtilityString(ManifestByVersionAndChannelGetEndpoint)); utility::string_t packageIdPath = RestHelper::AppendPathToUri(versionEndpoint, JsonHelper::GetUtilityString(packageId)); // Create the endpoint with query parameters return RestHelper::AppendQueryParamsToUri(packageIdPath, queryParameters); } } Interface::Interface(const std::string& restApi, const HttpClientHelper& httpClientHelper) : m_restApiUri(restApi), m_httpClientHelper(httpClientHelper) { THROW_HR_IF(APPINSTALLER_CLI_ERROR_RESTSOURCE_INVALID_URL, !RestHelper::IsValidUri(JsonHelper::GetUtilityString(restApi))); m_searchEndpoint = GetSearchEndpoint(m_restApiUri); m_requiredRestApiHeaders.emplace(JsonHelper::GetUtilityString(ContractVersion), JsonHelper::GetUtilityString(GetVersion().ToString())); } Utility::Version Interface::GetVersion() const { return Version_1_0_0; } IRestClient::SearchResult Interface::Search(const SearchRequest& request) const { // Optimization if (MeetsOptimizedSearchCriteria(request)) { return OptimizedSearch(request); } return SearchInternal(request); } IRestClient::SearchResult Interface::SearchInternal(const SearchRequest& request) const { SearchResult results; utility::string_t continuationToken; std::unordered_map<utility::string_t, utility::string_t> searchHeaders = m_requiredRestApiHeaders; do { if (!continuationToken.empty()) { AICLI_LOG(Repo, Verbose, << "Received continuation token. Retrieving more results."); searchHeaders.insert_or_assign(JsonHelper::GetUtilityString(ContinuationToken), continuationToken); } std::optional<web::json::value> jsonObject = m_httpClientHelper.HandlePost(m_searchEndpoint, GetSearchBody(request), searchHeaders); utility::string_t ct; if (jsonObject) { SearchResponseDeserializer searchResponseDeserializer; SearchResult currentResult = searchResponseDeserializer.Deserialize(jsonObject.value()); size_t insertElements = !request.MaximumResults ? currentResult.Matches.size() : std::min(currentResult.Matches.size(), request.MaximumResults - results.Matches.size()); std::move(currentResult.Matches.begin(), std::next(currentResult.Matches.begin(), insertElements), std::inserter(results.Matches, results.Matches.end())); ct = RestHelper::GetContinuationToken(jsonObject.value()).value_or(L""); } continuationToken = ct; } while (!continuationToken.empty() && (!request.MaximumResults || results.Matches.size() < request.MaximumResults)); if (results.Matches.empty()) { AICLI_LOG(Repo, Verbose, << "No search results returned by rest source"); } return results; } std::optional<Manifest::Manifest> Interface::GetManifestByVersion(const std::string& packageId, const std::string& version, const std::string& channel) const { std::map<std::string_view, std::string> queryParams; if (!version.empty()) { queryParams.emplace(VersionQueryParam, version); } if (!channel.empty()) { queryParams.emplace(ChannelQueryParam, channel); } std::vector<Manifest::Manifest> manifests = GetManifests(packageId, queryParams); if (!manifests.empty()) { for (Manifest::Manifest manifest : manifests) { if (Utility::CaseInsensitiveEquals(manifest.Version, version) && Utility::CaseInsensitiveEquals(manifest.Channel, channel)) { return manifest; } } } return {}; } bool Interface::MeetsOptimizedSearchCriteria(const SearchRequest& request) const { // Optimization: If the user wants to install a certain package with an exact match on package id and a particular rest source, we will // call the package manifest endpoint to get the manifest directly instead of running a search for it. if (!request.Query && request.Inclusions.size() == 0 && request.Filters.size() == 1 && request.Filters[0].Field == PackageMatchField::Id && request.Filters[0].Type == MatchType::Exact) { AICLI_LOG(Repo, Verbose, << "Search request meets optimized search criteria."); return true; } return false; } IRestClient::SearchResult Interface::OptimizedSearch(const SearchRequest& request) const { SearchResult searchResult; std::vector<Manifest::Manifest> manifests = GetManifests(request.Filters[0].Value); if (!manifests.empty()) { auto& manifest = manifests.at(0); PackageInfo packageInfo = PackageInfo{ manifest.Id, manifest.DefaultLocalization.Get<AppInstaller::Manifest::Localization::PackageName>(), manifest.DefaultLocalization.Get<AppInstaller::Manifest::Localization::Publisher>() }; // Add all the versions to the package info object std::vector<VersionInfo> versions; for (auto& manifestVersion : manifests) { std::vector<std::string> packageFamilyNames; std::vector<std::string> productCodes; for (auto& installer : manifestVersion.Installers) { if (!installer.PackageFamilyName.empty()) { packageFamilyNames.emplace_back(installer.PackageFamilyName); } if (!installer.ProductCode.empty()) { productCodes.emplace_back(installer.ProductCode); } } std::vector<std::string> uniquePackageFamilyNames = RestHelper::GetUniqueItems(packageFamilyNames); std::vector<std::string> uniqueProductCodes = RestHelper::GetUniqueItems(productCodes); versions.emplace_back( VersionInfo{ AppInstaller::Utility::VersionAndChannel {manifestVersion.Version, manifestVersion.Channel}, manifestVersion, std::move(uniquePackageFamilyNames), std::move(uniqueProductCodes) }); } Package package = Package{ std::move(packageInfo), std::move(versions) }; searchResult.Matches.emplace_back(std::move(package)); } return searchResult; } std::vector<Manifest::Manifest> Interface::GetManifests(const std::string& packageId, const std::map<std::string_view, std::string>& params) const { std::vector<Manifest::Manifest> results; std::optional<web::json::value> jsonObject = m_httpClientHelper.HandleGet(GetManifestByVersionEndpoint(m_restApiUri, packageId, params), m_requiredRestApiHeaders); if (!jsonObject) { AICLI_LOG(Repo, Verbose, << "No results were returned by the rest source for package id: " << packageId); return results; } // Parse json and return Manifests ManifestDeserializer manifestDeserializer; std::vector<Manifest::Manifest> manifests = manifestDeserializer.Deserialize(jsonObject.value()); // Manifest validation for (auto& manifestItem : manifests) { std::vector<AppInstaller::Manifest::ValidationError> validationErrors = AppInstaller::Manifest::ValidateManifest(manifestItem); int errors = 0; for (auto& error : validationErrors) { if (error.ErrorLevel == Manifest::ValidationError::Level::Error) { AICLI_LOG(Repo, Error, << "Received manifest contains validation error: " << error.Message); errors++; } } THROW_HR_IF(APPINSTALLER_CLI_ERROR_RESTSOURCE_INVALID_DATA, errors > 0); results.emplace_back(manifestItem); } return results; } }
41.996016
172
0.629447
sarvex
13735ee477db0faeaa68db3aaa223f05e78889cb
13,509
hpp
C++
tests/helics/application_api/ValueFederateTestTemplates.hpp
corinnegroth/HELICS
b8eda371b081a7d391d019c14bba5cf5042ae590
[ "BSD-3-Clause" ]
null
null
null
tests/helics/application_api/ValueFederateTestTemplates.hpp
corinnegroth/HELICS
b8eda371b081a7d391d019c14bba5cf5042ae590
[ "BSD-3-Clause" ]
null
null
null
tests/helics/application_api/ValueFederateTestTemplates.hpp
corinnegroth/HELICS
b8eda371b081a7d391d019c14bba5cf5042ae590
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2017-2020, Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See the top-level NOTICE for additional details. All rights reserved. SPDX-License-Identifier: BSD-3-Clause */ #pragma once #include "helics/application_api/Publications.hpp" #include "helics/application_api/Subscriptions.hpp" #include "helics/application_api/ValueFederate.hpp" #ifndef HELICS_SHARED_LIBRARY # include "testFixtures.hpp" #else # include "testFixtures_shared.hpp" #endif #include <future> #include <gtest/gtest.h> #include <string> template<class X> void runFederateTest( const std::string& core_type_str, const X& defaultValue, const X& testValue1, const X& testValue2) { FederateTestFixture fixture; fixture.SetupTest<helics::ValueFederate>(core_type_str, 1); auto vFed = fixture.GetFederateAs<helics::ValueFederate>(0); // register the publications auto& pubid = vFed->registerGlobalPublication<X>("pub1"); auto& subid = vFed->registerSubscription("pub1"); vFed->setProperty(helics_property_time_delta, 1.0); subid.setDefault(defaultValue); vFed->enterExecutingMode(); // publish string1 at time=0.0; pubid.publish(testValue1); auto val = subid.getValue<X>(); EXPECT_EQ(val, defaultValue); auto gtime = vFed->requestTime(1.0); EXPECT_EQ(gtime, 1.0); // get the value subid.getValue(val); // make sure the string is what we expect EXPECT_EQ(val, testValue1); // publish a second string pubid.publish(testValue2); // make sure the value is still what we expect subid.getValue(val); EXPECT_EQ(val, testValue1); // advance time gtime = vFed->requestTime(2.0); // make sure the value was updated EXPECT_EQ(gtime, 2.0); subid.getValue(val); EXPECT_EQ(val, testValue2); vFed->finalize(); EXPECT_TRUE(vFed->getCurrentMode() == helics::Federate::modes::finalize); helics::cleanupHelicsLibrary(); } template<class X> void runFederateTestObj( const std::string& core_type_str, const X& defaultValue, const X& testValue1, const X& testValue2) { FederateTestFixture fixture; fixture.SetupTest<helics::ValueFederate>(core_type_str, 1); auto vFed = fixture.GetFederateAs<helics::ValueFederate>(0); // register the publications helics::PublicationT<X> pubid(helics::GLOBAL, vFed.get(), "pub1"); auto subid = helics::make_subscription<X>(*vFed, "pub1"); vFed->setProperty(helics_property_time_delta, 1.0); subid.setDefault(defaultValue); vFed->enterExecutingMode(); // publish string1 at time=0.0; pubid.publish(testValue1); X val; subid.getValue(val); EXPECT_EQ(val, defaultValue); auto gtime = vFed->requestTime(1.0); EXPECT_EQ(gtime, 1.0); // get the value subid.getValue(val); // make sure the string is what we expect EXPECT_EQ(val, testValue1); // publish a second string pubid.publish(testValue2); // make sure the value is still what we expect val = subid.getValue(); EXPECT_EQ(val, testValue1); // advance time gtime = vFed->requestTime(2.0); // make sure the value was updated EXPECT_EQ(gtime, 2.0); val = subid.getValue(); EXPECT_EQ(val, testValue2); vFed->finalize(); } template<class X> void runFederateTestv2( const std::string& core_type_str, const X& defaultValue, const X& testValue1, const X& testValue2) { FederateTestFixture fixture; fixture.SetupTest<helics::ValueFederate>(core_type_str, 1); auto vFed = fixture.GetFederateAs<helics::ValueFederate>(0); // register the publications auto& pubid = vFed->registerGlobalPublication<X>("pub1"); auto& subid = vFed->registerSubscription("pub1"); vFed->setProperty(helics_property_time_delta, 1.0); subid.setDefault(defaultValue); vFed->enterExecutingMode(); // publish string1 at time=0.0; pubid.publish(testValue1); X val = subid.getValue<X>(); EXPECT_TRUE(val == defaultValue); auto gtime = vFed->requestTime(1.0); EXPECT_EQ(gtime, 1.0); // get the value subid.getValue(val); // make sure the string is what we expect EXPECT_TRUE(val == testValue1); // publish a second string pubid.publish(testValue2); // make sure the value is still what we expect subid.getValue(val); EXPECT_TRUE(val == testValue1); // advance time gtime = vFed->requestTime(2.0); // make sure the value was updated EXPECT_EQ(gtime, 2.0); subid.getValue(val); EXPECT_TRUE(val == testValue2); vFed->finalize(); helics::cleanupHelicsLibrary(); } template<class X> void runFederateTestObjv2( const std::string& core_type_str, const X& defaultValue, const X& testValue1, const X& testValue2) { FederateTestFixture fixture; fixture.SetupTest<helics::ValueFederate>(core_type_str, 1); auto vFed = fixture.GetFederateAs<helics::ValueFederate>(0); // register the publications helics::PublicationT<X> pubid(helics::GLOBAL, vFed.get(), "pub1"); auto sub = helics::make_subscription<X>(vFed.get(), "pub1"); vFed->setProperty(helics_property_time_delta, 1.0); sub.setDefault(defaultValue); vFed->enterExecutingMode(); // publish string1 at time=0.0; pubid.publish(testValue1); auto val = sub.getValue(); EXPECT_TRUE(val == defaultValue); auto gtime = vFed->requestTime(1.0); EXPECT_EQ(gtime, 1.0); // get the value sub.getValue(val); // make sure the string is what we expect EXPECT_TRUE(val == testValue1); // publish a second string pubid.publish(testValue2); // make sure the value is still what we expect val = sub.getValue(); EXPECT_TRUE(val == testValue1); // advance time gtime = vFed->requestTime(2.0); // make sure the value was updated EXPECT_EQ(gtime, 2.0); val = sub.getValue(); EXPECT_TRUE(val == testValue2); vFed->finalize(); } template<class X> void runDualFederateTest( const std::string& core_type_str, const X& defaultValue, const X& testValue1, const X& testValue2) { FederateTestFixture fixture; fixture.SetupTest<helics::ValueFederate>(core_type_str, 2); auto fedA = fixture.GetFederateAs<helics::ValueFederate>(0); auto fedB = fixture.GetFederateAs<helics::ValueFederate>(1); // register the publications auto& pubid = fedA->registerGlobalPublication<X>("pub1"); auto& subid = fedB->registerSubscription("pub1"); fedA->setProperty(helics_property_time_delta, 1.0); fedB->setProperty(helics_property_time_delta, 1.0); subid.setDefault(defaultValue); auto f1finish = std::async(std::launch::async, [&]() { fedA->enterExecutingMode(); }); fedB->enterExecutingMode(); f1finish.wait(); // publish string1 at time=0.0; pubid.publish(testValue1); X val = subid.getValue<X>(); EXPECT_EQ(val, defaultValue); auto f1time = std::async(std::launch::async, [&]() { return fedA->requestTime(1.0); }); auto gtime = fedB->requestTime(1.0); EXPECT_EQ(gtime, 1.0); EXPECT_EQ(f1time.get(), 1.0); // get the value subid.getValue(val); // make sure the string is what we expect EXPECT_EQ(val, testValue1); // publish a second string pubid.publish(testValue2); // make sure the value is still what we expect subid.getValue(val); EXPECT_EQ(val, testValue1); // advance time f1time = std::async(std::launch::async, [&]() { return fedA->requestTime(2.0); }); gtime = fedB->requestTime(2.0); EXPECT_EQ(gtime, 2.0); EXPECT_EQ(f1time.get(), 2.0); // make sure the value was updated subid.getValue(val); EXPECT_EQ(val, testValue2); fedA->finalizeAsync(); fedB->finalize(); fedA->finalizeComplete(); helics::cleanupHelicsLibrary(); } template<class X> void runDualFederateTestv2( const std::string& core_type_str, X& defaultValue, const X& testValue1, const X& testValue2) { FederateTestFixture fixture; fixture.SetupTest<helics::ValueFederate>(core_type_str, 2); auto fedA = fixture.GetFederateAs<helics::ValueFederate>(0); auto fedB = fixture.GetFederateAs<helics::ValueFederate>(1); // register the publications auto& pubid = fedA->registerGlobalPublication<X>("pub1"); auto& subid = fedB->registerSubscription("pub1"); fedA->setProperty(helics_property_time_delta, 1.0); fedB->setProperty(helics_property_time_delta, 1.0); subid.setDefault(defaultValue); auto f1finish = std::async(std::launch::async, [&]() { fedA->enterExecutingMode(); }); fedB->enterExecutingMode(); f1finish.wait(); // publish string1 at time=0.0; pubid.publish(testValue1); X val = subid.getValue<X>(); EXPECT_TRUE(val == defaultValue); auto f1time = std::async(std::launch::async, [&]() { return fedA->requestTime(1.0); }); auto gtime = fedB->requestTime(1.0); EXPECT_EQ(gtime, 1.0); EXPECT_EQ(f1time.get(), 1.0); // get the value subid.getValue(val); // make sure the string is what we expect EXPECT_TRUE(val == testValue1); // publish a second string pubid.publish(testValue2); // make sure the value is still what we expect subid.getValue(val); EXPECT_TRUE(val == testValue1); // advance time f1time = std::async(std::launch::async, [&]() { return fedA->requestTime(2.0); }); gtime = fedB->requestTime(2.0); EXPECT_EQ(gtime, 2.0); EXPECT_EQ(f1time.get(), 2.0); // make sure the value was updated subid.getValue(val); EXPECT_TRUE(val == testValue2); fedA->finalizeAsync(); fedB->finalize(); fedA->finalizeComplete(); helics::cleanupHelicsLibrary(); } template<class X> void runDualFederateTestObj( const std::string& core_type_str, const X& defaultValue, const X& testValue1, const X& testValue2) { FederateTestFixture fixture; using namespace helics; fixture.SetupTest<ValueFederate>(core_type_str, 2); auto fedA = fixture.GetFederateAs<ValueFederate>(0); auto fedB = fixture.GetFederateAs<ValueFederate>(1); // register the publications PublicationT<X> pubid(GLOBAL, fedA, "pub1"); auto subid = make_subscription<X>(*fedB, "pub1"); fedA->setProperty(helics_property_time_delta, 1.0); fedB->setProperty(helics_property_time_delta, 1.0); subid.setDefault(defaultValue); auto f1finish = std::async(std::launch::async, [&]() { fedA->enterExecutingMode(); }); fedB->enterExecutingMode(); f1finish.wait(); // publish string1 at time=0.0; pubid.publish(testValue1); X val; subid.getValue(val); EXPECT_EQ(val, defaultValue); auto f1time = std::async(std::launch::async, [&]() { return fedA->requestTime(1.0); }); auto gtime = fedB->requestTime(1.0); EXPECT_EQ(gtime, 1.0); EXPECT_EQ(f1time.get(), 1.0); // get the value subid.getValue(val); // make sure the string is what we expect EXPECT_EQ(val, testValue1); // publish a second string pubid.publish(testValue2); subid.getValue(val); EXPECT_EQ(val, testValue1); // advance time f1time = std::async(std::launch::async, [&]() { return fedA->requestTime(2.0); }); gtime = fedB->requestTime(2.0); EXPECT_EQ(gtime, 2.0); EXPECT_EQ(f1time.get(), 2.0); // make sure the value was updated subid.getValue(val); EXPECT_EQ(val, testValue2); fedA->finalizeAsync(); fedB->finalize(); fedA->finalizeComplete(); helics::cleanupHelicsLibrary(); } template<class X> void runDualFederateTestObjv2( const std::string& core_type_str, const X& defaultValue, const X& testValue1, const X& testValue2) { FederateTestFixture fixture; using namespace helics; fixture.SetupTest<helics::ValueFederate>(core_type_str, 2); auto fedA = fixture.GetFederateAs<helics::ValueFederate>(0); auto fedB = fixture.GetFederateAs<helics::ValueFederate>(1); // register the publications PublicationT<X> pubid(GLOBAL, fedA.get(), "pub1"); auto subid = helics::make_subscription<X>(fedB.get(), "pub1"); fedA->setProperty(helics_property_time_delta, 1.0); fedB->setProperty(helics_property_time_delta, 1.0); subid.setDefault(defaultValue); auto f1finish = std::async(std::launch::async, [&]() { fedA->enterExecutingMode(); }); fedB->enterExecutingMode(); f1finish.wait(); // publish string1 at time=0.0; pubid.publish(testValue1); X val = subid.getValue(); EXPECT_TRUE(val == defaultValue); auto f1time = std::async(std::launch::async, [&]() { return fedA->requestTime(1.0); }); auto gtime = fedB->requestTime(1.0); EXPECT_EQ(gtime, 1.0); EXPECT_EQ(f1time.get(), 1.0); // get the value subid.getValue(val); // make sure the string is what we expect EXPECT_TRUE(val == testValue1); // publish a second string pubid.publish(testValue2); subid.getValue(val); EXPECT_TRUE(val == testValue1); // advance time f1time = std::async(std::launch::async, [&]() { return fedA->requestTime(2.0); }); gtime = fedB->requestTime(2.0); EXPECT_EQ(gtime, 2.0); EXPECT_EQ(f1time.get(), 2.0); // make sure the value was updated subid.getValue(val); EXPECT_TRUE(val == testValue2); fedA->finalizeAsync(); fedB->finalize(); fedA->finalizeComplete(); helics::cleanupHelicsLibrary(); }
29.114224
114
0.6717
corinnegroth
1376203b3e543d90650b383202db7efd815ac8b5
6,523
cpp
C++
src/unity/toolkits/ml_data_2/row_slicing_utilities.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1
2018-12-15T20:03:51.000Z
2018-12-15T20:03:51.000Z
src/unity/toolkits/ml_data_2/row_slicing_utilities.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1
2018-12-11T10:37:10.000Z
2018-12-11T10:37:10.000Z
src/unity/toolkits/ml_data_2/row_slicing_utilities.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1
2019-06-01T18:49:28.000Z
2019-06-01T18:49:28.000Z
/* Copyright © 2017 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #include <unity/toolkits/ml_data_2/row_slicing_utilities.hpp> #include <logger/assertions.hpp> #include <string> namespace turi { namespace v2 { /** Constructor -- provide ml_metadata class and a subset of column * indices to use in this particular row. The _columns_to_pick must * be in sorted order. * * If the chosen columns are from untranslated columns, then they * must be all untranslated columns. In this case, only the * flexible_type slice method below can be used. Otherwise, none * of the columns must be untranslated, and either the sparse or * dense slicing methods must be used. */ row_slicer::row_slicer(const std::shared_ptr<ml_metadata>& metadata, const std::vector<size_t>& _columns_to_pick) { if(_columns_to_pick.empty()) { pick_from_flexible_type = false; return; } if(!std::is_sorted(_columns_to_pick.begin(), _columns_to_pick.end())) { ASSERT_MSG(false, "Selected columns must be in sorted order."); return; } //////////////////////////////////////////////////////////// // First go through and get the types of the given columns. pick_from_flexible_type = metadata->is_untranslated_column(_columns_to_pick.front()) ; // Make sure this is consistent for(size_t c : _columns_to_pick) { ASSERT_MSG(pick_from_flexible_type == metadata->is_untranslated_column(c), (std::string("Cannot mix untranslated and translated columns in single slice. (") + metadata->column_name(c) + ")").c_str()); } auto is_included = [&](size_t i) { for(size_t c : _columns_to_pick) { if(c == i) return true; } return false; }; if(pick_from_flexible_type) { // Go through and get the ones that flex_type_columns_to_pick.clear(); // The indexing on the untranslated columns is dependent on the // untranslated ordering and count, so we have to translate the indices. size_t untranslated_column_count = 0; for(size_t c_idx = 0; c_idx < metadata->num_columns(); ++c_idx) { if(is_included(c_idx)) flex_type_columns_to_pick.push_back(untranslated_column_count); if(metadata->is_untranslated_column(c_idx)) ++untranslated_column_count; } } else { // We can just copy the indices over. column_pick_mask.assign(metadata->num_columns(), false); for(size_t c : _columns_to_pick) column_pick_mask[c] = true; // Now build the index counts and offsets index_offsets.assign(metadata->num_columns(), 0); index_sizes.assign(metadata->num_columns(), 0); size_t cum_sum = 0; for(size_t i = 0; i < metadata->num_columns(); ++i) { if(column_pick_mask[i]) { index_sizes[i] = metadata->index_size(i); index_offsets[i] = cum_sum; cum_sum += index_sizes[i]; } } // Finally, set the number of dimensions _num_dimensions = cum_sum; } } /** Take a row, represented by a pair of translated and * untranslated columns (either of which may be empty), and * use it to fill a sparse vector with the result. */ void row_slicer::slice(sparse_vector& dest, const std::vector<ml_data_entry>& x_t, const std::vector<flexible_type>&) const { ASSERT_MSG(!pick_from_flexible_type, "Cannot be used for untranslated columns."); dest.resize(_num_dimensions); dest.zeros(); for(const ml_data_entry& v : x_t) { DASSERT_LT(v.column_index, index_sizes.size()); if(!column_pick_mask[v.column_index]) continue; // Gracefully disregard new values if(v.index >= index_sizes[v.column_index]) continue; dest(v.index + index_offsets[v.column_index]) = v.value; } } /** Take a row, represented by a pair of translated and * untranslated columns (either of which may be empty), and * use it to fill a dense vector with the result. */ void row_slicer::slice(dense_vector& dest, const std::vector<ml_data_entry>& x_t, const std::vector<flexible_type>& x_u) const { ASSERT_MSG(!pick_from_flexible_type, "Cannot be used for untranslated columns."); dest.resize(_num_dimensions); dest.zeros(); for(const ml_data_entry& v : x_t) { DASSERT_LT(v.column_index, index_sizes.size()); if(!column_pick_mask[v.column_index]) continue; // Gracefully disregard new values if(v.index >= index_sizes[v.column_index]) continue; dest[v.index + index_offsets[v.column_index]] = v.value; } } /** Take a row, represented by a pair of translated and * untranslated columns (either of which may be empty), and * use it to fill an untranslated row with the result. */ void row_slicer::slice(std::vector<flexible_type>& dest, const std::vector<ml_data_entry>& x_t, const std::vector<flexible_type>& x_u) const { ASSERT_MSG(pick_from_flexible_type, "Can only be used for untranslated columns."); dest.resize(flex_type_columns_to_pick.size()); for(size_t i = 0; i < flex_type_columns_to_pick.size(); ++i) { DASSERT_LT(flex_type_columns_to_pick[i], x_u.size()); dest[i] = x_u[flex_type_columns_to_pick[i]]; } } /** Serialization -- save. */ void row_slicer::save(turi::oarchive& oarc) const { size_t version = 0; std::map<std::string, variant_type> data; data["version"] = to_variant(version); data["pick_from_flexible_type"] = to_variant(pick_from_flexible_type); data["flex_type_columns_to_pick"] = to_variant(flex_type_columns_to_pick); data["column_pick_mask"] = to_variant(column_pick_mask); data["index_offsets"] = to_variant(index_offsets); data["index_sizes"] = to_variant(index_sizes); data["_num_dimensions"] = to_variant(_num_dimensions); variant_deep_save(data, oarc); } /** Serialization -- load. */ void row_slicer::load(turi::iarchive& iarc) { #define __EXTRACT(var) var = variant_get_value<decltype(var)>(data.at(#var)); std::map<std::string, variant_type> data; variant_deep_load(data, iarc); __EXTRACT(pick_from_flexible_type); __EXTRACT(flex_type_columns_to_pick); __EXTRACT(column_pick_mask); __EXTRACT(index_offsets); __EXTRACT(index_sizes); __EXTRACT(_num_dimensions); #undef __EXTRACT } }}
31.360577
108
0.676683
shreyasvj25
1376a613e70c699d3bcf53a8db7debf8f5c5050a
1,616
hpp
C++
include/universal/number/decimal/math/sqrt.hpp
FloEdelmann/universal
c5b83f251ad91229399b7f97e4eeefcf718819d4
[ "MIT" ]
null
null
null
include/universal/number/decimal/math/sqrt.hpp
FloEdelmann/universal
c5b83f251ad91229399b7f97e4eeefcf718819d4
[ "MIT" ]
null
null
null
include/universal/number/decimal/math/sqrt.hpp
FloEdelmann/universal
c5b83f251ad91229399b7f97e4eeefcf718819d4
[ "MIT" ]
null
null
null
#pragma once // sqrt.hpp: sqrt functions for decimals // // Copyright (C) 2017-2021 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include <universal/native/ieee754.hpp> #include <universal/number/decimal/numeric_limits.hpp> #ifndef DECIMAL_NATIVE_SQRT #define DECIMAL_NATIVE_SQRT 0 #endif namespace sw { namespace universal { #if DECIMAL_NATIVE_SQRT // native sqrt for decimal inline decimal sqrt(const decimal& f) { if (f < 0) throw decimal_negative_sqrt_arg(); using Decimal = decimal; constexpr Decimal eps = std::numeric_limits<Rational>::epsilon(); Decimal y(f); Decimal x(f); x >>= 1; // divide by 2 Decimal diff = (x * x - y); int iterations = 0; while (sw::universal::abs(diff) > eps) { x = (x + y); x >>= 1; y = f / x; diff = x - y; // std::cout << " x: " << x << " y: " << y << " diff " << diff << '\n'; if (++iterations > rbits) break; } if (iterations > rbits) std::cerr << "sqrt(" << double(f) << ") failed to converge\n"; return x; } #else inline decimal sqrt(const decimal& f) { #if DECIMAL_THROW_ARITHMETIC_EXCEPTION if (f.isneg()) { throw decimal_negative_sqrt_arg(); } #else std::cerr << "decimal_negative_sqrt_arg\n"; #endif return decimal(std::sqrt((double)f)); } #endif // reciprocal sqrt // inline decimal rsqrt(const decimal& f) { // decimal rsqrt = sqrt(f); // return rsqrt.reciprocate(); // } /////////////////////////////////////////////////////////////////// // specialized sqrt configurations }} // namespace sw::universal
26.491803
106
0.631807
FloEdelmann
137a09c0cb887244c39f387501118f6858253fd5
142
cpp
C++
src/framework/library1.cpp
BalderOdinson/kalman-cuda
b2d9979b7ff5bfb481c95c9a38139ec5f7fd9331
[ "MIT" ]
1
2021-07-31T15:53:53.000Z
2021-07-31T15:53:53.000Z
src/framework/library1.cpp
BalderOdinson/kalman-cuda
b2d9979b7ff5bfb481c95c9a38139ec5f7fd9331
[ "MIT" ]
null
null
null
src/framework/library1.cpp
BalderOdinson/kalman-cuda
b2d9979b7ff5bfb481c95c9a38139ec5f7fd9331
[ "MIT" ]
1
2021-07-31T15:53:59.000Z
2021-07-31T15:53:59.000Z
#include "library1.hpp" #include "library2/library2.hpp" #include <cstdio> void hello_world() { printf("Hello World"); new_line(); }
15.777778
32
0.676056
BalderOdinson
137d3514d48dc026fc167de562323c1c7da50196
2,436
cpp
C++
CMSIS/DSP/SDFTools/examples/example6/generated/scheduler.cpp
DavidLesnjak/CMSIS_5
e0848410d137758a3356a5ee94ca4501cea708a8
[ "Apache-2.0" ]
2,293
2016-02-25T06:47:33.000Z
2022-03-29T16:44:02.000Z
CMSIS/DSP/SDFTools/examples/example6/generated/scheduler.cpp
DavidLesnjak/CMSIS_5
e0848410d137758a3356a5ee94ca4501cea708a8
[ "Apache-2.0" ]
1,125
2016-02-27T09:56:01.000Z
2022-03-31T13:57:05.000Z
CMSIS/DSP/SDFTools/examples/example6/generated/scheduler.cpp
DavidLesnjak/CMSIS_5
e0848410d137758a3356a5ee94ca4501cea708a8
[ "Apache-2.0" ]
1,160
2016-02-27T09:06:10.000Z
2022-03-31T19:06:24.000Z
/* Generated with CMSIS-DSP SDF Scripts. The generated code is not covered by CMSIS-DSP license. The support classes and code is covered by CMSIS-DSP license. */ #include "arm_math.h" #include "custom.h" #include "GenericNodes.h" #include "AppNodes.h" #include "scheduler.h" /*********** FIFO buffers ************/ #define FIFOSIZE0 256 #define FIFOSIZE1 256 #define FIFOSIZE2 13 #define FIFOSIZE3 26 #define BUFFERSIZE0 256 float32_t buf0[BUFFERSIZE0]={0}; #define BUFFERSIZE1 256 float32_t buf1[BUFFERSIZE1]={0}; #define BUFFERSIZE2 13 float32_t buf2[BUFFERSIZE2]={0}; #define BUFFERSIZE3 26 float32_t buf3[BUFFERSIZE3]={0}; uint32_t scheduler(int *error,arm_mfcc_instance_f32 *mfccConfig) { int sdfError=0; uint32_t nbSchedule=0; int32_t debugCounter=1; /* Create FIFOs objects */ FIFO<float32_t,FIFOSIZE0,0> fifo0(buf0); FIFO<float32_t,FIFOSIZE1,1> fifo1(buf1); FIFO<float32_t,FIFOSIZE2,1> fifo2(buf2); FIFO<float32_t,FIFOSIZE3,0> fifo3(buf3); /* Create node objects */ SlidingBuffer<float32_t,256,128> audioWin(fifo0,fifo1); MFCC<float32_t,256,float32_t,13> mfcc(fifo1,fifo2,mfccConfig); SlidingBuffer<float32_t,26,13> mfccWin(fifo2,fifo3); FileSink<float32_t,13> sink(fifo3,"output_example6.txt"); FileSource<float32_t,192> src(fifo0,"input_example6.txt"); /* Run several schedule iterations */ while((sdfError==0) && (debugCounter > 0)) { /* Run a schedule iteration */ sdfError = src.run(); CHECKERROR; sdfError = audioWin.run(); CHECKERROR; sdfError = mfcc.run(); CHECKERROR; sdfError = mfccWin.run(); CHECKERROR; sdfError = sink.run(); CHECKERROR; sdfError = sink.run(); CHECKERROR; sdfError = src.run(); CHECKERROR; sdfError = audioWin.run(); CHECKERROR; sdfError = mfcc.run(); CHECKERROR; sdfError = mfccWin.run(); CHECKERROR; sdfError = sink.run(); CHECKERROR; sdfError = sink.run(); CHECKERROR; sdfError = audioWin.run(); CHECKERROR; sdfError = mfcc.run(); CHECKERROR; sdfError = mfccWin.run(); CHECKERROR; sdfError = sink.run(); CHECKERROR; sdfError = sink.run(); CHECKERROR; debugCounter--; nbSchedule++; } *error=sdfError; return(nbSchedule); }
22.555556
66
0.633005
DavidLesnjak
13835e1be5cbc376d80aa3ae1000cabecfae8863
899
cpp
C++
code/midpoint_circle.cpp
VishalGupta0609/algorithms
1dd704a8e8c8e96aeaa43928258e806da3192a6c
[ "MIT" ]
2
2020-10-28T15:02:41.000Z
2021-10-02T13:18:24.000Z
code/midpoint_circle.cpp
VishalGupta0609/algorithms
1dd704a8e8c8e96aeaa43928258e806da3192a6c
[ "MIT" ]
4
2020-10-07T05:59:13.000Z
2021-10-02T08:01:27.000Z
code/midpoint_circle.cpp
VishalGupta0609/algorithms
1dd704a8e8c8e96aeaa43928258e806da3192a6c
[ "MIT" ]
51
2020-10-01T03:07:30.000Z
2021-10-05T16:25:22.000Z
//Mid Point Circle Drawing Algorithm #include<iostream> #include<graphics.h> #include<conio.h> #include<stdlib.h> #include<stdio.h> using namespace std; void symPlot(int xc, int yc, int x, int y) { putpixel(x+xc,y+yc,RED); putpixel(x+xc,-y+yc,YELLOW); putpixel(-x+xc,-y+yc,GREEN); putpixel(-x+xc,y+yc,BLUE); putpixel(y+xc,x+yc,BLUE); putpixel(y+xc,-x+yc,GREEN); putpixel(-y+xc,-x+yc,YELLOW); putpixel(-y+xc,x+yc,RED); } void solve(int x, int y, int r){ int X=0, Y=r; int d = 5/4 - r; while(X <= Y) { symPlot(x,y,X,Y); if(d < 0) { d = d + 2*X + 3; } else{ d = d + 2*(X - Y) + 5; Y--; } X++; } } int main() { int x1, y1, radius; cout<<"Enter X Y (Center of Circle)"<<endl; cin>>x1>>y1; cout<<"Enter Radius of Circle"<<endl; cin>>radius; initwindow(500,500); solve(x1,y1,radius); getch(); closegraph(); return 0; }
17.627451
44
0.571746
VishalGupta0609
1383e6fe074288fe9a2042fd4bc6e29ad0a6653e
194
cpp
C++
abc053_a.cpp
hakatashi/procon
254d0df4365b815c88e71cb3b4adb4c4bd7ea263
[ "MIT" ]
2
2019-06-28T04:54:47.000Z
2020-02-25T08:39:19.000Z
abc053_a.cpp
hakatashi/procon
254d0df4365b815c88e71cb3b4adb4c4bd7ea263
[ "MIT" ]
null
null
null
abc053_a.cpp
hakatashi/procon
254d0df4365b815c88e71cb3b4adb4c4bd7ea263
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(int argc, char const *argv[]) { int N; cin >> N; if (N < 1200) { cout << "ABC" << endl; } else { cout << "ARC" << endl; } return 0; }
14.923077
40
0.551546
hakatashi
13855053e1f8caae95cbd9e531cd093b9c4dabc0
763
cpp
C++
04-Sorting/InversionCount.cpp
alpha-neutr0n/C-plus-plus-Algorithms
838a2d4d6abe524b2be5ad85f6bd76ea565f3096
[ "MIT" ]
null
null
null
04-Sorting/InversionCount.cpp
alpha-neutr0n/C-plus-plus-Algorithms
838a2d4d6abe524b2be5ad85f6bd76ea565f3096
[ "MIT" ]
null
null
null
04-Sorting/InversionCount.cpp
alpha-neutr0n/C-plus-plus-Algorithms
838a2d4d6abe524b2be5ad85f6bd76ea565f3096
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int merge(int *a, int s, int e){ int mid= (s+e)/2; int i=s; int j=mid+1; int k=s; int temp[1000]; int cnt=0; while(i<=mid and j<=e){ if(a[i]<=a[j]){ temp[k++]=a[i++]; } else{ temp[k++]=a[i++]; cnt+= mid-i+1; } } while(i<=mid){ temp[k++]= a[i++]; } while(j<=e){ temp[k++]=a[i++]; } for(int i=s;i<=e;i++){ a[i]=temp[i]; } return cnt; } int inversion_count(int *a, int s, int e){ if(s>=e){ return 0; } int mid= (s+e)/2; int x= inversion_count(a,s,mid); int y= inversion_count(a,mid+1,e); int z= merge(a,s,e); return x+y+z; } int main() { int a[]= {1,3,4,6,8,0}; int n= sizeof(a)/sizeof(int); cout<<inversion_count(a,0,n-1)<<endl; }
16.586957
43
0.503277
alpha-neutr0n
138558479437968fdc997651caa726335995032f
298
cc
C++
src/swerc2018/11231.cc
chq-matteo/uva-oj
d0210a77711ad39c340f8321a8cbdc73e49d283f
[ "MIT" ]
1
2020-03-15T08:12:31.000Z
2020-03-15T08:12:31.000Z
src/swerc2018/11231.cc
chq-matteo/uva-oj
d0210a77711ad39c340f8321a8cbdc73e49d283f
[ "MIT" ]
null
null
null
src/swerc2018/11231.cc
chq-matteo/uva-oj
d0210a77711ad39c340f8321a8cbdc73e49d283f
[ "MIT" ]
null
null
null
// 11231 Black and white painting finding patterns harder // focus on the lower left tile #include <iostream> using namespace std; int main() { int n, m, c; while (cin >> n >> m >> c and n + m + c) { cout << ((n - 7) * (m - 7) / 2 + ((((n - 7) * (m - 7)) % 2) & c)) << '\n'; } }
29.8
82
0.496644
chq-matteo
13868b21220037ba8818a86835951a0d278ef5b8
723
cpp
C++
GumpEditor-0.32/GumpPaperdoll.cpp
zerodowned/Iris1_DeveloperTools
0b5510bb46824d8939846f73c7e63ed7eecf827d
[ "DOC" ]
1
2019-02-08T18:03:28.000Z
2019-02-08T18:03:28.000Z
GumpEditor-0.32/GumpPaperdoll.cpp
SiENcE/Iris1_DeveloperTools
0b5510bb46824d8939846f73c7e63ed7eecf827d
[ "DOC" ]
null
null
null
GumpEditor-0.32/GumpPaperdoll.cpp
SiENcE/Iris1_DeveloperTools
0b5510bb46824d8939846f73c7e63ed7eecf827d
[ "DOC" ]
7
2015-03-11T22:06:23.000Z
2019-12-21T09:49:57.000Z
#include "StdAfx.h" #include "GumpEditor.h" #include ".\gumppaperdoll.h" CGumpPaperdoll::CGumpPaperdoll(CGumpPtr pGump) : CGumpPicture(NULL) { SetGump(pGump); SetTitle("paperdoll"); SetType("paperdoll"); CString strName; strName.Format("paperdoll_%x", pGump ? pGump->GetGumpID() : 0); SetName(strName); //AddPropertyPage( &m_page ); } CGumpPaperdoll::~CGumpPaperdoll(void) { } CDiagramEntity* CGumpPaperdoll::Clone() { CGumpPaperdoll* obj = new CGumpPaperdoll(m_pGump); obj->Copy( this ); return obj; } CDiagramEntity* CGumpPaperdoll::CreateFromString( XML::Node* node ) { CGumpPaperdoll* obj = new CGumpPaperdoll(NULL); if(!obj->FromString( node ) ) { delete obj; obj = NULL; } return obj; }
16.813953
67
0.706777
zerodowned
13874a6193532cee306237b7ae3d1b9c558bd8ad
50
cpp
C++
test/units/detail/basic_unit_cmp.cpp
mfkiwl/marnav
53a1c987bf72d48df134c12dd1edc44d7f230921
[ "BSD-4-Clause" ]
62
2015-07-20T03:24:21.000Z
2022-03-30T10:39:24.000Z
test/units/detail/basic_unit_cmp.cpp
mfkiwl/marnav
53a1c987bf72d48df134c12dd1edc44d7f230921
[ "BSD-4-Clause" ]
37
2016-03-30T05:38:32.000Z
2021-12-26T18:11:38.000Z
test/units/detail/basic_unit_cmp.cpp
mfkiwl/marnav
53a1c987bf72d48df134c12dd1edc44d7f230921
[ "BSD-4-Clause" ]
39
2015-07-20T03:15:44.000Z
2022-02-03T07:32:23.000Z
#include <marnav/units/detail/basic_unit_cmp.hpp>
25
49
0.82
mfkiwl