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
109
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
48.5k
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
5796ad5d2a9b1d4dcfc478041a6f100cee3c3ef9
2,673
cpp
C++
SheepShaver/src/BeOS/SaveROM/SaveROM.cpp
jvernet/macemu
c616a0dae0f451fc15016765c896175fae3f46cf
[ "Intel", "X11" ]
940
2015-01-04T12:20:10.000Z
2022-03-29T12:35:27.000Z
SheepShaver/src/BeOS/SaveROM/SaveROM.cpp
Seanpm2001-virtual-machines/macemu
c616a0dae0f451fc15016765c896175fae3f46cf
[ "Intel", "X11" ]
163
2015-02-10T09:08:10.000Z
2022-03-13T05:48:10.000Z
SheepShaver/src/BeOS/SaveROM/SaveROM.cpp
Seanpm2001-virtual-machines/macemu
c616a0dae0f451fc15016765c896175fae3f46cf
[ "Intel", "X11" ]
188
2015-01-07T19:46:11.000Z
2022-03-26T19:06:00.000Z
/* * SaveROM - Save Mac ROM to file * * Copyright (C) 1998-2004 Christian Bauer * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <AppKit.h> #include <InterfaceKit.h> #include <StorageKit.h> #include <stdio.h> #include <unistd.h> // Constants const char APP_SIGNATURE[] = "application/x-vnd.cebix-SaveROM"; const char ROM_FILE_NAME[] = "ROM"; // Global variables static uint8 buf[0x400000]; // Application object class SaveROM : public BApplication { public: SaveROM() : BApplication(APP_SIGNATURE) { // Find application directory and cwd to it app_info the_info; GetAppInfo(&the_info); BEntry the_file(&the_info.ref); BEntry the_dir; the_file.GetParent(&the_dir); BPath the_path; the_dir.GetPath(&the_path); chdir(the_path.Path()); } virtual void ReadyToRun(void); }; /* * Create application object and start it */ int main(int argc, char **argv) { SaveROM *the_app = new SaveROM(); the_app->Run(); delete the_app; return 0; } /* * Display error alert */ static void ErrorAlert(const char *text) { BAlert *alert = new BAlert("SaveROM Error", text, "Quit", NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT); alert->Go(); } /* * Display OK alert */ static void InfoAlert(const char *text) { BAlert *alert = new BAlert("SaveROM Message", text, "Quit", NULL, NULL, B_WIDTH_AS_USUAL, B_INFO_ALERT); alert->Go(); } /* * Main program */ void SaveROM::ReadyToRun(void) { int fd = open("/dev/sheep", 0); if (fd < 0) { ErrorAlert("Cannot open '/dev/sheep'."); goto done; } if (read(fd, buf, 0x400000) != 0x400000) { ErrorAlert("Cannot read ROM."); close(fd); goto done; } FILE *f = fopen(ROM_FILE_NAME, "wb"); if (f == NULL) { ErrorAlert("Cannot open ROM file."); close(fd); goto done; } if (fwrite(buf, 1, 0x400000, f) != 0x400000) { ErrorAlert("Cannot write ROM."); fclose(f); close(fd); goto done; } InfoAlert("ROM saved."); fclose(f); close(fd); done: PostMessage(B_QUIT_REQUESTED); }
20.72093
105
0.683876
jvernet
5798404cf04b80c1f79e0868c850d6343ff875dc
1,689
cpp
C++
dart/pendulum.cpp
mxgrey/sandbox
6f3c316702a47053499222dbf293efe6c1f43f0c
[ "BSD-3-Clause" ]
null
null
null
dart/pendulum.cpp
mxgrey/sandbox
6f3c316702a47053499222dbf293efe6c1f43f0c
[ "BSD-3-Clause" ]
null
null
null
dart/pendulum.cpp
mxgrey/sandbox
6f3c316702a47053499222dbf293efe6c1f43f0c
[ "BSD-3-Clause" ]
null
null
null
#include <dart/dynamics/Skeleton.hpp> #include <dart/dynamics/WeldJoint.hpp> #include <dart/dynamics/RevoluteJoint.hpp> #include <dart/dynamics/CylinderShape.hpp> #include <dart/simulation/World.hpp> #include <dart/gui/osg/Viewer.hpp> #include <dart/gui/osg/WorldNode.hpp> int main() { dart::dynamics::RevoluteJoint::Properties p; p.mAxis = Eigen::Vector3d::UnitY(); auto skeleton = dart::dynamics::Skeleton::create(); auto parent = skeleton->createJointAndBodyNodePair< dart::dynamics::RevoluteJoint>(nullptr, p).second; p.mT_ParentBodyToJoint.translate(-Eigen::Vector3d::UnitZ()); auto child = skeleton->createJointAndBodyNodePair< dart::dynamics::RevoluteJoint>(parent, p).second; const double R = 0.1; const double h = 0.9; auto rod = std::make_shared<dart::dynamics::CylinderShape>(R, h); for(auto * const bn : {parent, child}) { const Eigen::Vector3d center = -0.5*Eigen::Vector3d::UnitZ(); const double mass = 1.0; bn->createShapeNodeWith<dart::dynamics::VisualAspect>(rod) ->setRelativeTranslation(center); dart::dynamics::Inertia inertia; inertia.setMass(mass); inertia.setMoment(rod->computeInertia(mass)); inertia.setLocalCOM(center); bn->setInertia(inertia); auto joint = bn->getParentJoint(); joint->setPosition(0, 60.0*M_PI/180.0); joint->setDampingCoefficient(0, 0.3); } auto world = std::make_shared<dart::simulation::World>(); world->addSkeleton(skeleton); dart::gui::osg::Viewer viewer; osg::ref_ptr<dart::gui::osg::WorldNode> node = new dart::gui::osg::WorldNode(world); node->setNumStepsPerCycle(100); viewer.addWorldNode(node); viewer.run(); }
27.688525
67
0.69923
mxgrey
579a28a9b11fcea0f166e7a2a201d0ba4012141f
2,334
hpp
C++
retrace/daemon/glframe_os.hpp
austriancoder/apitrace
5919778f7bcba82433f80bda4fb225e43183a62f
[ "MIT" ]
1
2021-03-05T10:49:37.000Z
2021-03-05T10:49:37.000Z
retrace/daemon/glframe_os.hpp
austriancoder/apitrace
5919778f7bcba82433f80bda4fb225e43183a62f
[ "MIT" ]
null
null
null
retrace/daemon/glframe_os.hpp
austriancoder/apitrace
5919778f7bcba82433f80bda4fb225e43183a62f
[ "MIT" ]
1
2018-10-05T03:09:13.000Z
2018-10-05T03:09:13.000Z
// Copyright (C) Intel Corp. 2014. All Rights Reserved. // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // The above copyright notice and this permission notice (including the // next paragraph) 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 COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS 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. // **********************************************************************/ // * Authors: // * Mark Janes <mark.a.janes@intel.com> // **********************************************************************/ #ifndef _GLFRAME_OS_H_ #define _GLFRAME_OS_H_ #include <time.h> #include <mutex> #include <condition_variable> #include <string> #include "glframe_traits.hpp" namespace glretrace { typedef std::lock_guard<std::mutex> ScopedLock; class Semaphore : NoCopy, NoAssign, NoMove { public: Semaphore() : m_count(0) {} void post() { std::lock_guard<std::mutex> lk(m_mutex); ++m_count; m_cv.notify_one(); } void wait() { std::unique_lock<std::mutex> lk(m_mutex); while (!m_count) m_cv.wait(lk); --m_count; } private: unsigned m_count; std::mutex m_mutex; std::condition_variable m_cv; }; int fork_execv(const char *path, const char *const argv[]); struct tm *glretrace_localtime(const time_t *timep, struct tm *result); std::string application_cache_directory(); int glretrace_rand(unsigned int *seedp); void glretrace_delay(unsigned int ms); } // namespace glretrace #endif // _GLFRAME_OS_H_
30.710526
75
0.68509
austriancoder
579ab1455cbf52753fad6884accb11eef0266ec4
33,348
cpp
C++
aes.cpp
sh-miyoshi/AES
6d82605189abcdeab1e4b1cbafce374c47117dd0
[ "MIT" ]
2
2017-06-01T19:49:24.000Z
2019-10-15T14:19:28.000Z
aes.cpp
sh-miyoshi/AES
6d82605189abcdeab1e4b1cbafce374c47117dd0
[ "MIT" ]
null
null
null
aes.cpp
sh-miyoshi/AES
6d82605189abcdeab1e4b1cbafce374c47117dd0
[ "MIT" ]
null
null
null
#include "aes.h" #include <random> #include <sstream> #include <string.h> using namespace aes; void AES::GenerateIV(unsigned char *iv, Mode mode) { std::random_device rand_dev; if (mode == AES_CTR) { // [8bit nonce][8bit counter] for (int i = 0; i < 8; i++) { iv[i] = (unsigned char)rand_dev(); } for (int i = 8; i < 15; i++) { iv[i] = 0; } iv[15] = 1; } else { // set all random data for (int i = 0; i < AES_BLOCK_SIZE; i++) { iv[i] = (unsigned char)rand_dev(); } } } void AES::GenerateIV(unsigned char *iv, std::string passpharse, Mode mode) { // TODO(this is not secure: seed is too small) // Use pseudo random number unsigned int seed = 0; for (char c : passpharse) { seed += (unsigned int)c; } std::mt19937 engine(seed); if (mode == AES_CTR) { // [8bit nonce][8bit counter] for (int i = 0; i < 8; i++) { iv[i] = (unsigned char)engine(); } for (int i = 8; i < 15; i++) { iv[i] = 0; } iv[15] = 1; } else { // set all random data for (int i = 0; i < AES_BLOCK_SIZE; i++) { iv[i] = (unsigned char)engine(); } } } AES::AES(Mode mode, const unsigned char *key, unsigned int keyBitLen, unsigned char *iv) { Init(mode, key, keyBitLen, iv); } Error AES::EncryptFile(std::string in_fname, std::string out_fname) { if (!initError.success) { return initError; } FILE *fp_in, *fp_out; Error err = FileOpen(&fp_in, in_fname, "rb"); if (!err.success) { return err; } err = FileOpen(&fp_out, out_fname, "wb"); if (!err.success) { return err; } EncryptBase *handler = nullptr; switch (mode) { case AES_ECB_ZERO: case AES_ECB_PKCS_5: handler = (EncryptBase *)new EncryptECB(this); break; case AES_CBC_ZERO: case AES_CBC_PKCS_5: handler = (EncryptBase *)new EncryptCBC(this, iv); break; case AES_CTR: handler = (EncryptBase *)new EncryptCTR(this, iv); break; } char buf[FILE_READ_SIZE], res[FILE_READ_SIZE]; while (1) { int readSize = fread(buf, sizeof(char), FILE_READ_SIZE, fp_in); if (readSize == 0) { if (handler->Finalize(res)) { fwrite(res, sizeof(char), AES_BLOCK_SIZE, fp_out); } break; } int writeSize = handler->Encrypt(res, buf, readSize); fwrite(res, sizeof(char), writeSize, fp_out); } fclose(fp_in); fclose(fp_out); delete handler; return err; } Error AES::DecryptFile(std::string in_fname, std::string out_fname) { if (!initError.success) { return initError; } FILE *fp_in, *fp_out; Error err = FileOpen(&fp_in, in_fname, "rb"); if (!err.success) { return err; } err = FileOpen(&fp_out, out_fname, "wb"); if (!err.success) { return err; } EncryptBase *handler = nullptr; switch (mode) { case AES_ECB_ZERO: case AES_ECB_PKCS_5: handler = (EncryptBase *)new EncryptECB(this); break; case AES_CBC_ZERO: case AES_CBC_PKCS_5: handler = (EncryptBase *)new EncryptCBC(this, iv); break; case AES_CTR: handler = (EncryptBase *)new EncryptCTR(this, iv); break; } char buf[FILE_READ_SIZE], res[FILE_READ_SIZE]; int readSize = fread(buf, sizeof(char), FILE_READ_SIZE, fp_in); if (readSize == 0) { err.success = false; err.message = "no readable data"; fclose(fp_in); fclose(fp_out); return err; } while (1) { handler->Decrypt(res, buf, readSize); if (readSize < FILE_READ_SIZE) { fwrite(res, sizeof(char), readSize - AES_BLOCK_SIZE, fp_out); int index = (readSize - AES_BLOCK_SIZE); // write last data (remove padding) int s = GetDataSizeWithoutPadding(res + index); fwrite(res + index, sizeof(char), s, fp_out); break; } else { int rs = fread(buf, sizeof(char), FILE_READ_SIZE, fp_in); if (rs == 0) { fwrite(res, sizeof(char), readSize - AES_BLOCK_SIZE, fp_out); int index = (readSize - AES_BLOCK_SIZE); // write last data (remove padding) int s = GetDataSizeWithoutPadding(res + index); fwrite(res + index, sizeof(char), s, fp_out); break; } readSize = rs; } } fclose(fp_in); fclose(fp_out); delete handler; return err; } Error AES::EncryptString(char *result, const char *data, unsigned int length) { if (!initError.success) { return initError; } EncryptBase *handler = nullptr; switch (mode) { case AES_ECB_ZERO: case AES_ECB_PKCS_5: handler = (EncryptBase *)new EncryptECB(this); break; case AES_CBC_ZERO: case AES_CBC_PKCS_5: handler = (EncryptBase *)new EncryptCBC(this, iv); break; case AES_CTR: handler = (EncryptBase *)new EncryptCTR(this, iv); break; } handler->Encrypt(result, data, length); delete handler; return Error(); } Error AES::DecryptString(char *result, const char *data, unsigned int length) { if (!initError.success) { return initError; } EncryptBase *handler = nullptr; switch (mode) { case AES_ECB_ZERO: case AES_ECB_PKCS_5: handler = (EncryptBase *)new EncryptECB(this); break; case AES_CBC_ZERO: case AES_CBC_PKCS_5: handler = (EncryptBase *)new EncryptCBC(this, iv); break; case AES_CTR: handler = (EncryptBase *)new EncryptCTR(this, iv); break; } handler->Decrypt(result, data, length); delete handler; return Error(); } void AES::Init(Mode mode, const unsigned char *key, unsigned int keyBitLen, unsigned char *iv) { this->mode = mode; unsigned int keyByteLen = keyBitLen / 8; // maybe 16, 24, 32 if (keyBitLen != 128 && keyBitLen != 192 && keyBitLen != 256) { initError.success = false; std::stringstream ss; ss << "Unexpected key length. "; ss << "AES just only support 128, 192, 256-bit, "; ss << "but got length: " << keyBitLen; initError.message = ss.str(); return; } this->Nr = 6 + (keyByteLen / 4); unsigned char userKey[32]; for (int i = 0; i < keyByteLen; i++) { userKey[i] = key[i]; } #if USE_AES_NI switch (keyBitLen) { case 128: AES_128_Key_Expansion(encKey, userKey); break; case 192: AES_192_Key_Expansion(encKey, userKey); break; case 256: AES_256_Key_Expansion(encKey, userKey); break; } decKey[Nr] = encKey[0]; for (int i = 1; i < Nr; i++) decKey[Nr - i] = _mm_aesimc_si128(encKey[i]); decKey[0] = encKey[Nr]; if (!iv) { this->iv = _mm_setzero_si128(); } else { this->iv = _mm_loadu_si128((__m128i *)iv); } #else for (int i = 0; i < AES_BLOCK_SIZE; i++) { if (!iv) { this->iv[i] = 0; } else { this->iv[i] = iv[i]; } } KeyExpansion(userKey, keyByteLen); #endif } void AES::SetPadding(char *data, int size) { for (int i = size; i < AES_BLOCK_SIZE; i++) { switch (mode) { case AES_ECB_ZERO: case AES_CBC_ZERO: data[i] = 0; break; case AES_ECB_PKCS_5: case AES_CBC_PKCS_5: data[i] = (AES_BLOCK_SIZE - size); break; } } } int AES::GetDataSizeWithoutPadding(const char *data) { int res = 0; switch (mode) { case AES_CTR: return AES_BLOCK_SIZE; case AES_ECB_PKCS_5: case AES_CBC_PKCS_5: res = AES_BLOCK_SIZE - data[AES_BLOCK_SIZE - 1]; break; case AES_ECB_ZERO: case AES_CBC_ZERO: for (res = AES_BLOCK_SIZE - 1; res >= 0; res--) { if (data[res] != 0) { res++; break; } } break; } return res; } Error AES::FileOpen(FILE **fp, std::string fname, std::string mode) { Error err; *fp = fopen(fname.c_str(), mode.c_str()); if (!(*fp)) { std::stringstream ss; ss << "Failed to open file: " << fname; err.success = false; err.message = ss.str(); } return err; } AES::EncryptECB::EncryptECB(AES *obj) : obj(obj), paddingFlag(false) {} AES::EncryptECB::~EncryptECB() {} int AES::EncryptECB::Encrypt(char *res, const char *readBuf, unsigned int readSize) { int writeSize = 0; for (int pointer = 0; pointer < readSize; pointer += AES_BLOCK_SIZE) { writeSize += AES_BLOCK_SIZE; int trs = readSize - pointer; int size = (trs > AES_BLOCK_SIZE) ? AES_BLOCK_SIZE : trs; char t[AES_BLOCK_SIZE] = { 0 }; for (int i = 0; i < size; i++) { t[i] = readBuf[pointer + i]; } obj->SetPadding(t, size); if (size != AES_BLOCK_SIZE) { paddingFlag = true; } #if USE_AES_NI __m128i data = _mm_set_epi8(t[15], t[14], t[13], t[12], t[11], t[10], t[9], t[8], t[7], t[6], t[5], t[4], t[3], t[2], t[1], t[0]); data = obj->EncryptCore(data); _mm_storeu_si128((__m128i *)(res + pointer), data); #else unsigned char data[AES_BLOCK_SIZE]; for (int i = 0; i < AES_BLOCK_SIZE; i++) { data[i] = (unsigned char)t[i]; } obj->EncryptCore(data); for (int i = 0; i < AES_BLOCK_SIZE; i++) { res[pointer + i] = data[i]; } #endif } return writeSize; } void AES::EncryptECB::Decrypt(char *res, const char *readBuf, unsigned int readSize) { char buf[FILE_READ_SIZE]; memcpy(buf, readBuf, readSize); for (int pointer = 0; pointer < readSize; pointer += AES_BLOCK_SIZE) { char t[AES_BLOCK_SIZE] = { 0 }; for (int i = 0; i < AES_BLOCK_SIZE; i++) { t[i] = buf[pointer + i]; } #if USE_AES_NI __m128i data = _mm_set_epi8(t[15], t[14], t[13], t[12], t[11], t[10], t[9], t[8], t[7], t[6], t[5], t[4], t[3], t[2], t[1], t[0]); data = obj->DecryptCore(data); _mm_storeu_si128((__m128i *)(res + pointer), data); #else unsigned char data[AES_BLOCK_SIZE]; for (int i = 0; i < AES_BLOCK_SIZE; i++) { data[i] = (unsigned char)t[i]; } obj->DecryptCore(data); for (int i = 0; i < AES_BLOCK_SIZE; i++) { res[pointer + i] = data[i]; } #endif } } bool AES::EncryptECB::Finalize(char *res) { if (obj->mode != AES_ECB_PKCS_5 && obj->mode != AES_CBC_PKCS_5) { return false; } if (!paddingFlag) { char t[AES_BLOCK_SIZE]; for (int i = 0; i < AES_BLOCK_SIZE; i++) t[i] = AES_BLOCK_SIZE; #if USE_AES_NI __m128i data = _mm_set_epi8(t[15], t[14], t[13], t[12], t[11], t[10], t[9], t[8], t[7], t[6], t[5], t[4], t[3], t[2], t[1], t[0]); data = obj->EncryptCore(data); _mm_storeu_si128((__m128i *)res, data); #else unsigned char data[AES_BLOCK_SIZE]; for (int i = 0; i < AES_BLOCK_SIZE; i++) { data[i] = (unsigned char)t[i]; } obj->EncryptCore(data); for (int i = 0; i < AES_BLOCK_SIZE; i++) { res[i] = data[i]; } #endif return true; } return false; } #if USE_AES_NI AES::EncryptCBC::EncryptCBC(AES *obj, __m128i iv) : obj(obj), vec(iv), paddingFlag(false) {} #else AES::EncryptCBC::EncryptCBC(AES *obj, const unsigned char *iv) : obj(obj), paddingFlag(false) { for (int i = 0; i < AES_BLOCK_SIZE; i++) { vec[i] = iv[i]; } } #endif AES::EncryptCBC::~EncryptCBC() {} int AES::EncryptCBC::Encrypt(char *res, const char *readBuf, unsigned int readSize) { int writeSize = 0; for (int pointer = 0; pointer < readSize; pointer += AES_BLOCK_SIZE) { writeSize += AES_BLOCK_SIZE; int trs = readSize - pointer; int size = (trs > AES_BLOCK_SIZE) ? AES_BLOCK_SIZE : trs; char t[AES_BLOCK_SIZE] = { 0 }; for (int i = 0; i < size; i++) { t[i] = readBuf[pointer + i]; } obj->SetPadding(t, size); if (size != AES_BLOCK_SIZE) { paddingFlag = true; } #if USE_AES_NI __m128i data = _mm_set_epi8(t[15], t[14], t[13], t[12], t[11], t[10], t[9], t[8], t[7], t[6], t[5], t[4], t[3], t[2], t[1], t[0]); data = _mm_xor_si128(data, vec); data = obj->EncryptCore(data); vec = data; _mm_storeu_si128((__m128i *)(res + pointer), data); #else unsigned char data[AES_BLOCK_SIZE]; for (int i = 0; i < AES_BLOCK_SIZE; i++) { data[i] = (unsigned char)t[i]; } for (int i = 0; i < AES_BLOCK_SIZE; i++) { data[i] ^= vec[i]; } obj->EncryptCore(data); for (int i = 0; i < AES_BLOCK_SIZE; i++) { vec[i] = data[i]; } for (int i = 0; i < AES_BLOCK_SIZE; i++) { res[pointer + i] = data[i]; } #endif } return writeSize; } void AES::EncryptCBC::Decrypt(char *res, const char *readBuf, unsigned int readSize) { char buf[FILE_READ_SIZE]; memcpy(buf, readBuf, readSize); for (int pointer = 0; pointer < readSize; pointer += AES_BLOCK_SIZE) { char t[AES_BLOCK_SIZE] = { 0 }; for (int i = 0; i < AES_BLOCK_SIZE; i++) { t[i] = buf[pointer + i]; } #if USE_AES_NI __m128i data = _mm_set_epi8(t[15], t[14], t[13], t[12], t[11], t[10], t[9], t[8], t[7], t[6], t[5], t[4], t[3], t[2], t[1], t[0]); __m128i prevVec = vec; vec = data; data = obj->DecryptCore(data); data = _mm_xor_si128(data, prevVec); _mm_storeu_si128((__m128i *)(res + pointer), data); #else unsigned char data[AES_BLOCK_SIZE]; for (int i = 0; i < AES_BLOCK_SIZE; i++) { data[i] = (unsigned char)t[i]; } unsigned char prevVec[AES_BLOCK_SIZE]; for (int i = 0; i < AES_BLOCK_SIZE; i++) prevVec[i] = vec[i]; for (int i = 0; i < AES_BLOCK_SIZE; i++) { vec[i] = data[i]; } obj->DecryptCore(data); for (int i = 0; i < AES_BLOCK_SIZE; i++) { data[i] ^= prevVec[i]; } for (int i = 0; i < AES_BLOCK_SIZE; i++) { res[pointer + i] = data[i]; } #endif } } bool AES::EncryptCBC::Finalize(char *res) { if (obj->mode != AES_ECB_PKCS_5 && obj->mode != AES_CBC_PKCS_5) { return false; } if (!paddingFlag) { char t[AES_BLOCK_SIZE]; for (int i = 0; i < AES_BLOCK_SIZE; i++) t[i] = AES_BLOCK_SIZE; #if USE_AES_NI __m128i data = _mm_set_epi8(t[15], t[14], t[13], t[12], t[11], t[10], t[9], t[8], t[7], t[6], t[5], t[4], t[3], t[2], t[1], t[0]); data = _mm_xor_si128(data, vec); data = obj->EncryptCore(data); _mm_storeu_si128((__m128i *)res, data); #else unsigned char data[AES_BLOCK_SIZE]; for (int i = 0; i < AES_BLOCK_SIZE; i++) { data[i] = (unsigned char)t[i]; } for (int i = 0; i < AES_BLOCK_SIZE; i++) { data[i] ^= vec[i]; } obj->EncryptCore(data); for (int i = 0; i < AES_BLOCK_SIZE; i++) { res[i] = data[i]; } #endif return true; } return false; } #if USE_AES_NI AES::EncryptCTR::EncryptCTR(AES *obj, __m128i iv) : obj(obj), vec(iv) {} #else AES::EncryptCTR::EncryptCTR(AES *obj, const unsigned char *iv) : obj(obj) { for (int i = 0; i < AES_BLOCK_SIZE; i++) { vec[i] = iv[i]; } } #endif AES::EncryptCTR::~EncryptCTR() {} int AES::EncryptCTR::Encrypt(char *res, const char *readBuf, unsigned int readSize) { for (int pointer = 0; pointer < readSize; pointer += AES_BLOCK_SIZE) { int trs = readSize - pointer; int size = (trs > AES_BLOCK_SIZE) ? AES_BLOCK_SIZE : trs; char t[AES_BLOCK_SIZE] = { 0 }; for (int i = 0; i < size; i++) { t[i] = readBuf[pointer + i]; } #if USE_AES_NI static const __m128i one = _mm_set_epi32(0, 0, 0, 1); __m128i encCounter = obj->EncryptCore(vec); __m128i data = _mm_set_epi8(t[15], t[14], t[13], t[12], t[11], t[10], t[9], t[8], t[7], t[6], t[5], t[4], t[3], t[2], t[1], t[0]); data = _mm_xor_si128(data, encCounter); _mm_storeu_si128((__m128i *)(res + pointer), data); vec = _mm_add_epi64(vec, one); #else unsigned char encCounter[AES_BLOCK_SIZE]; for (int i = 0; i < 16; i++) { encCounter[i] = vec[i]; } obj->EncryptCore(encCounter); for (int i = 0; i < AES_BLOCK_SIZE; i++) { res[pointer + i] = (char)((unsigned char)t[i] ^ encCounter[i]); } #endif } return readSize; } void AES::EncryptCTR::Decrypt(char *res, const char *readBuf, unsigned int readSize) { for (int pointer = 0; pointer < readSize; pointer += AES_BLOCK_SIZE) { int trs = readSize - pointer; int size = (trs > AES_BLOCK_SIZE) ? AES_BLOCK_SIZE : trs; char t[AES_BLOCK_SIZE] = { 0 }; for (int i = 0; i < size; i++) { t[i] = readBuf[pointer + i]; } #if USE_AES_NI const __m128i one = _mm_set_epi32(0, 0, 0, 1); __m128i encCounter = obj->EncryptCore(vec); __m128i data = _mm_set_epi8(t[15], t[14], t[13], t[12], t[11], t[10], t[9], t[8], t[7], t[6], t[5], t[4], t[3], t[2], t[1], t[0]); data = _mm_xor_si128(data, encCounter); _mm_storeu_si128((__m128i *)(res + pointer), data); vec = _mm_add_epi64(vec, one); #else unsigned char encCounter[AES_BLOCK_SIZE]; for (int i = 0; i < 16; i++) { encCounter[i] = vec[i]; } obj->EncryptCore(encCounter); for (int i = 0; i < AES_BLOCK_SIZE; i++) { res[pointer + i] = (char)((unsigned char)t[i] ^ encCounter[i]); } #endif } } #if USE_AES_NI __m128i AES::AES_128_ASSIST(__m128i temp1, __m128i temp2) { __m128i temp3; temp2 = _mm_shuffle_epi32(temp2, 0xff); temp3 = _mm_slli_si128(temp1, 0x4); temp1 = _mm_xor_si128(temp1, temp3); temp3 = _mm_slli_si128(temp3, 0x4); temp1 = _mm_xor_si128(temp1, temp3); temp3 = _mm_slli_si128(temp3, 0x4); temp1 = _mm_xor_si128(temp1, temp3); temp1 = _mm_xor_si128(temp1, temp2); return temp1; } void AES::AES_192_ASSIST(__m128i &temp1, __m128i &temp2, __m128i &temp3) { __m128i temp4; temp2 = _mm_shuffle_epi32(temp2, 0x55); temp4 = _mm_slli_si128(temp1, 0x4); temp1 = _mm_xor_si128(temp1, temp4); temp4 = _mm_slli_si128(temp4, 0x4); temp1 = _mm_xor_si128(temp1, temp4); temp4 = _mm_slli_si128(temp4, 0x4); temp1 = _mm_xor_si128(temp1, temp4); temp1 = _mm_xor_si128(temp1, temp2); temp2 = _mm_shuffle_epi32(temp1, 0xff); temp4 = _mm_slli_si128(temp3, 0x4); temp3 = _mm_xor_si128(temp3, temp4); temp3 = _mm_xor_si128(temp3, temp2); } void AES::AES_256_ASSIST_1(__m128i &temp1, __m128i &temp2) { __m128i temp4; temp2 = _mm_shuffle_epi32(temp2, 0xff); temp4 = _mm_slli_si128(temp1, 0x4); temp1 = _mm_xor_si128(temp1, temp4); temp4 = _mm_slli_si128(temp4, 0x4); temp1 = _mm_xor_si128(temp1, temp4); temp4 = _mm_slli_si128(temp4, 0x4); temp1 = _mm_xor_si128(temp1, temp4); temp1 = _mm_xor_si128(temp1, temp2); } void AES::AES_256_ASSIST_2(__m128i &temp1, __m128i &temp3) { __m128i temp2, temp4; temp4 = _mm_aeskeygenassist_si128(temp1, 0x0); temp2 = _mm_shuffle_epi32(temp4, 0xaa); temp4 = _mm_slli_si128(temp3, 0x4); temp3 = _mm_xor_si128(temp3, temp4); temp4 = _mm_slli_si128(temp4, 0x4); temp3 = _mm_xor_si128(temp3, temp4); temp4 = _mm_slli_si128(temp4, 0x4); temp3 = _mm_xor_si128(temp3, temp4); temp3 = _mm_xor_si128(temp3, temp2); } void AES::AES_128_Key_Expansion(__m128i *key, const unsigned char *userKey) { __m128i temp1 = _mm_loadu_si128((__m128i *)userKey), temp2; key[0] = temp1; for (int i = 1; i <= 10; i++) { switch (i) { case 1: temp2 = _mm_aeskeygenassist_si128(temp1, 0x1); break; case 2: temp2 = _mm_aeskeygenassist_si128(temp1, 0x2); break; case 3: temp2 = _mm_aeskeygenassist_si128(temp1, 0x4); break; case 4: temp2 = _mm_aeskeygenassist_si128(temp1, 0x8); break; case 5: temp2 = _mm_aeskeygenassist_si128(temp1, 0x10); break; case 6: temp2 = _mm_aeskeygenassist_si128(temp1, 0x20); break; case 7: temp2 = _mm_aeskeygenassist_si128(temp1, 0x40); break; case 8: temp2 = _mm_aeskeygenassist_si128(temp1, 0x80); break; case 9: temp2 = _mm_aeskeygenassist_si128(temp1, 0x1b); break; case 10: temp2 = _mm_aeskeygenassist_si128(temp1, 0x36); break; } temp1 = AES_128_ASSIST(temp1, temp2); key[i] = temp1; } } void AES::AES_192_Key_Expansion(__m128i *key, const unsigned char *userKey) { __m128i temp1, temp2, temp3; temp1 = _mm_loadu_si128((__m128i *)userKey); temp3 = _mm_loadu_si128((__m128i *)(userKey + 16)); for (int i = 0; i < 12; i += 3) { key[i] = temp1; key[i + 1] = temp3; switch (i) { case 0: temp2 = _mm_aeskeygenassist_si128(temp3, 0x1); break; case 3: temp2 = _mm_aeskeygenassist_si128(temp3, 0x4); break; case 6: temp2 = _mm_aeskeygenassist_si128(temp3, 0x10); break; case 9: temp2 = _mm_aeskeygenassist_si128(temp3, 0x40); break; } AES_192_ASSIST(temp1, temp2, temp3); key[i + 1] = (__m128i)_mm_shuffle_pd((__m128d)key[i + 1], (__m128d)temp1, 0); key[i + 2] = (__m128i)_mm_shuffle_pd((__m128d)temp1, (__m128d)temp3, 1); switch (i) { case 0: temp2 = _mm_aeskeygenassist_si128(temp3, 0x2); break; case 3: temp2 = _mm_aeskeygenassist_si128(temp3, 0x8); break; case 6: temp2 = _mm_aeskeygenassist_si128(temp3, 0x20); break; case 9: temp2 = _mm_aeskeygenassist_si128(temp3, 0x80); break; } AES_192_ASSIST(temp1, temp2, temp3); } key[12] = temp1; key[13] = temp3; } void AES::AES_256_Key_Expansion(__m128i *key, const unsigned char *userKey) { __m128i temp1, temp2, temp3; temp1 = _mm_loadu_si128((__m128i *)userKey); temp3 = _mm_loadu_si128((__m128i *)(userKey + 16)); key[0] = temp1; key[1] = temp3; for (int i = 2; i <= 12; i += 2) { switch (i) { case 2: temp2 = _mm_aeskeygenassist_si128(temp3, 0x01); break; case 4: temp2 = _mm_aeskeygenassist_si128(temp3, 0x02); break; case 6: temp2 = _mm_aeskeygenassist_si128(temp3, 0x04); break; case 8: temp2 = _mm_aeskeygenassist_si128(temp3, 0x08); break; case 10: temp2 = _mm_aeskeygenassist_si128(temp3, 0x010); break; case 12: temp2 = _mm_aeskeygenassist_si128(temp3, 0x020); break; } AES_256_ASSIST_1(temp1, temp2); key[i] = temp1; AES_256_ASSIST_2(temp1, temp3); key[i + 1] = temp3; } temp2 = _mm_aeskeygenassist_si128(temp3, 0x40); AES_256_ASSIST_1(temp1, temp2); key[14] = temp1; } __m128i AES::EncryptCore(__m128i data) { data = _mm_xor_si128(data, encKey[0]); for (int i = 1; i < Nr; i++) { data = _mm_aesenc_si128(data, encKey[i]); } return _mm_aesenclast_si128(data, encKey[Nr]); } __m128i AES::DecryptCore(__m128i data) { data = _mm_xor_si128(data, decKey[0]); for (int i = 1; i < Nr; i++) { data = _mm_aesdec_si128(data, decKey[i]); } return _mm_aesdeclast_si128(data, decKey[Nr]); } #else static const unsigned char SBOX[256] = { 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 }; static const unsigned char INV_SBOX[256] = { 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d }; void AES::SubBytes(unsigned char *data) { for (int i = 0; i < AES_BLOCK_SIZE; i++) data[i] = SBOX[data[i]]; } void AES::ShiftRows(unsigned char *data) { unsigned char temp = data[4]; // line 1 data[4] = data[5]; data[5] = data[6]; data[6] = data[7]; data[7] = temp; // line 2 temp = data[8]; data[8] = data[10]; data[10] = temp; temp = data[9]; data[9] = data[11]; data[11] = temp; // line 3 temp = data[15]; data[15] = data[14]; data[14] = data[13]; data[13] = data[12]; data[12] = temp; } void AES::MixColumns(unsigned char *data) { // 要改善 // SIMDみたいな感じで unsigned char buf[8]; for (int x = 0; x < 4; x++) { for (int y = 0; y < 4; y++) buf[y] = data[(y << 2) + x]; ExtMul(buf[4], buf[0], 2); ExtMul(buf[5], buf[1], 3); ExtMul(buf[6], buf[2], 1); ExtMul(buf[7], buf[3], 1); data[x + 0] = buf[4] ^ buf[5] ^ buf[6] ^ buf[7]; ExtMul(buf[4], buf[0], 1); ExtMul(buf[5], buf[1], 2); ExtMul(buf[6], buf[2], 3); ExtMul(buf[7], buf[3], 1); data[x + 4] = buf[4] ^ buf[5] ^ buf[6] ^ buf[7]; ExtMul(buf[4], buf[0], 1); ExtMul(buf[5], buf[1], 1); ExtMul(buf[6], buf[2], 2); ExtMul(buf[7], buf[3], 3); data[x + 8] = buf[4] ^ buf[5] ^ buf[6] ^ buf[7]; ExtMul(buf[4], buf[0], 3); ExtMul(buf[5], buf[1], 1); ExtMul(buf[6], buf[2], 1); ExtMul(buf[7], buf[3], 2); data[x + 12] = buf[4] ^ buf[5] ^ buf[6] ^ buf[7]; } } void AES::InvSubBytes(unsigned char *data) { for (int i = 0; i < AES_BLOCK_SIZE; i++) data[i] = INV_SBOX[data[i]]; } void AES::InvShiftRows(unsigned char *data) { // TODO(Required Improvement) unsigned char buf[AES_BLOCK_SIZE]; memcpy(buf, data, sizeof(buf)); for (int i = 1; i < 4; i++) { for (int j = 0; j < 4; j++) data[i * 4 + (j + i) % 4] = buf[i * 4 + j]; } } void AES::InvMixColumns(unsigned char *data) { // TODO(Required Improvement) unsigned char x; unsigned char buf[8]; for (int x = 0; x < 4; x++) { for (int y = 0; y < 4; y++) buf[y] = data[y * 4 + x]; ExtMul(buf[4], buf[0], 14); ExtMul(buf[5], buf[1], 11); ExtMul(buf[6], buf[2], 13); ExtMul(buf[7], buf[3], 9); data[x + 0] = buf[4] ^ buf[5] ^ buf[6] ^ buf[7]; ExtMul(buf[4], buf[0], 9); ExtMul(buf[5], buf[1], 14); ExtMul(buf[6], buf[2], 11); ExtMul(buf[7], buf[3], 13); data[x + 4] = buf[4] ^ buf[5] ^ buf[6] ^ buf[7]; ExtMul(buf[4], buf[0], 13); ExtMul(buf[5], buf[1], 9); ExtMul(buf[6], buf[2], 14); ExtMul(buf[7], buf[3], 11); data[x + 8] = buf[4] ^ buf[5] ^ buf[6] ^ buf[7]; ExtMul(buf[4], buf[0], 11); ExtMul(buf[5], buf[1], 13); ExtMul(buf[6], buf[2], 9); ExtMul(buf[7], buf[3], 14); data[x + 12] = buf[4] ^ buf[5] ^ buf[6] ^ buf[7]; } } void AES::AddRoundKey(unsigned char *data, int n) { for (int i = 0; i < AES_BLOCK_SIZE; i++) data[i] ^= roundKey[(n << 4) + i]; } void AES::ExtMul(unsigned char &x, unsigned char data, int n) { x = 0; if (n & 8) x = data; bool flag = x & 0x80; x <<= 1; if (flag) x ^= 0x1b; if (n & 4) x ^= data; flag = x & 0x80; x <<= 1; if (flag) x ^= 0x1b; if (n & 2) x ^= data; flag = x & 0x80; x <<= 1; if (flag) x ^= 0x1b; if (n & 1) x ^= data; } void AES::SubWord(unsigned char *w) { for (int i = 0; i < 4; i++) w[i] = SBOX[AES_BLOCK_SIZE * ((w[i] & 0xf0) >> 4) + (w[i] & 0x0f)]; } void AES::RotWord(unsigned char *w) { unsigned char temp = w[0]; for (int i = 0; i < 3; i++) w[i] = w[i + 1]; w[3] = temp; } void AES::KeyExpansion(const unsigned char *userKey, int wordKeyLength) { static const unsigned char Rcon[10] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36 }; unsigned char *w = roundKey, len = 4 * (Nr + 1), buf[4]; memcpy(w, userKey, wordKeyLength * 4); for (int i = wordKeyLength; i < len; i++) { buf[0] = w[4 * (i - 1) + 0]; buf[1] = w[4 * (i - 1) + 1]; buf[2] = w[4 * (i - 1) + 2]; buf[3] = w[4 * (i - 1) + 3]; if (i % wordKeyLength == 0) { RotWord(buf); SubWord(buf); buf[0] ^= Rcon[(i / wordKeyLength) - 1]; } else if (wordKeyLength > 6 && i % wordKeyLength == 4) SubWord(buf); w[4 * i + 0] = w[4 * (i - wordKeyLength) + 0] ^ buf[0]; w[4 * i + 1] = w[4 * (i - wordKeyLength) + 1] ^ buf[1]; w[4 * i + 2] = w[4 * (i - wordKeyLength) + 2] ^ buf[2]; w[4 * i + 3] = w[4 * (i - wordKeyLength) + 3] ^ buf[3]; } } void AES::EncryptCore(unsigned char *data) { AddRoundKey(data, 0); for (int i = 1; i < Nr; i++) { SubBytes(data); ShiftRows(data); MixColumns(data); AddRoundKey(data, i); } SubBytes(data); ShiftRows(data); AddRoundKey(data, Nr); } void AES::DecryptCore(unsigned char *data) { AddRoundKey(data, Nr); for (int i = Nr - 1; i > 0; i--) { InvShiftRows(data); InvSubBytes(data); AddRoundKey(data, i); InvMixColumns(data); } InvShiftRows(data); InvSubBytes(data); AddRoundKey(data, 0); } #endif
31.549669
138
0.5451
sh-miyoshi
579b80982ce287dd8b6614b60e3033054f7ecab7
57,965
cpp
C++
src/seal/he_seal_executable.cpp
kthur/he-transformer
5d3294473edba10f2789197043b8d8704409719e
[ "Apache-2.0" ]
null
null
null
src/seal/he_seal_executable.cpp
kthur/he-transformer
5d3294473edba10f2789197043b8d8704409719e
[ "Apache-2.0" ]
null
null
null
src/seal/he_seal_executable.cpp
kthur/he-transformer
5d3294473edba10f2789197043b8d8704409719e
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2018-2019 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include "seal/he_seal_executable.hpp" #include <functional> #include <limits> #include <tuple> #include <unordered_set> #include "he_op_annotations.hpp" #include "he_tensor.hpp" #include "ngraph/descriptor/layout/dense_tensor_layout.hpp" #include "ngraph/op/avg_pool.hpp" #include "ngraph/op/batch_norm.hpp" #include "ngraph/op/broadcast.hpp" #include "ngraph/op/concat.hpp" #include "ngraph/op/constant.hpp" #include "ngraph/op/convolution.hpp" #include "ngraph/op/divide.hpp" #include "ngraph/op/dot.hpp" #include "ngraph/op/exp.hpp" #include "ngraph/op/max.hpp" #include "ngraph/op/max_pool.hpp" #include "ngraph/op/pad.hpp" #include "ngraph/op/passthrough.hpp" #include "ngraph/op/power.hpp" #include "ngraph/op/reshape.hpp" #include "ngraph/op/result.hpp" #include "ngraph/op/reverse.hpp" #include "ngraph/op/slice.hpp" #include "ngraph/op/softmax.hpp" #include "ngraph/op/sum.hpp" #include "ngraph/pass/assign_layout.hpp" #include "ngraph/pass/constant_folding.hpp" #include "ngraph/pass/core_fusion.hpp" #include "ngraph/pass/like_replacement.hpp" #include "ngraph/pass/liveness.hpp" #include "ngraph/pass/manager.hpp" #include "ngraph/pass/memory_layout.hpp" #include "ngraph/pass/visualize_tree.hpp" #include "ngraph/runtime/backend.hpp" #include "ngraph/serializer.hpp" #include "ngraph/util.hpp" #include "nlohmann/json.hpp" #include "op/bounded_relu.hpp" #include "pass/he_fusion.hpp" #include "pass/he_liveness.hpp" #include "pass/propagate_he_annotations.hpp" #include "pass/supported_ops.hpp" #include "protos/message.pb.h" #include "seal/he_seal_backend.hpp" #include "seal/kernel/add_seal.hpp" #include "seal/kernel/avg_pool_seal.hpp" #include "seal/kernel/batch_norm_inference_seal.hpp" #include "seal/kernel/bounded_relu_seal.hpp" #include "seal/kernel/broadcast_seal.hpp" #include "seal/kernel/concat_seal.hpp" #include "seal/kernel/constant_seal.hpp" #include "seal/kernel/convolution_seal.hpp" #include "seal/kernel/divide_seal.hpp" #include "seal/kernel/dot_seal.hpp" #include "seal/kernel/exp_seal.hpp" #include "seal/kernel/max_pool_seal.hpp" #include "seal/kernel/max_seal.hpp" #include "seal/kernel/minimum_seal.hpp" #include "seal/kernel/multiply_seal.hpp" #include "seal/kernel/negate_seal.hpp" #include "seal/kernel/pad_seal.hpp" #include "seal/kernel/power_seal.hpp" #include "seal/kernel/relu_seal.hpp" #include "seal/kernel/rescale_seal.hpp" #include "seal/kernel/reshape_seal.hpp" #include "seal/kernel/result_seal.hpp" #include "seal/kernel/reverse_seal.hpp" #include "seal/kernel/slice_seal.hpp" #include "seal/kernel/softmax_seal.hpp" #include "seal/kernel/subtract_seal.hpp" #include "seal/kernel/sum_seal.hpp" #include "seal/seal_ciphertext_wrapper.hpp" #include "seal/seal_util.hpp" using json = nlohmann::json; using ngraph::descriptor::layout::DenseTensorLayout; namespace ngraph::he { HESealExecutable::HESealExecutable(const std::shared_ptr<Function>& function, bool enable_performance_collection, HESealBackend& he_seal_backend, bool enable_client) : m_he_seal_backend(he_seal_backend), m_enable_client{enable_client}, m_batch_size{1}, m_port{34000} { // TODO(fboemer): Use (void)enable_performance_collection; // Avoid unused parameter warning m_context = he_seal_backend.get_context(); // TODO(fboemer): use clone_function? (check // https://github.com/NervanaSystems/ngraph/pull/3773 is merged) m_function = function; NGRAPH_HE_LOG(3) << "Creating Executable"; for (const auto& param : m_function->get_parameters()) { NGRAPH_HE_LOG(3) << "Parameter " << param->get_name(); if (HEOpAnnotations::has_he_annotation(*param)) { std::string from_client_str = from_client(*param) ? "" : "not "; NGRAPH_HE_LOG(3) << "\tshape " << param->get_shape() << " is " << from_client_str << "from client"; } for (const auto& tag : param->get_provenance_tags()) { NGRAPH_HE_LOG(3) << "\tTag " << tag; } } if (std::getenv("NGRAPH_VOPS") != nullptr) { std::string verbose_ops_str(std::getenv("NGRAPH_VOPS")); verbose_ops_str = ngraph::to_lower(verbose_ops_str); if (verbose_ops_str == "all") { m_verbose_all_ops = true; } std::vector<std::string> verbose_ops_vec = split(verbose_ops_str, ',', true); m_verbose_ops = std::set<std::string>{verbose_ops_vec.begin(), verbose_ops_vec.end()}; if (m_verbose_ops.find("all") != m_verbose_ops.end()) { m_verbose_all_ops = true; } } NGRAPH_HE_LOG(3) << "Running optimization passes"; ngraph::pass::Manager pass_manager; pass_manager.set_pass_visualization(false); pass_manager.set_pass_serialization(false); pass_manager.register_pass<ngraph::pass::LikeReplacement>(); pass_manager.register_pass<ngraph::pass::AssignLayout<DenseTensorLayout>>(); pass_manager.register_pass<ngraph::pass::CoreFusion>(); if (!m_stop_const_fold) { NGRAPH_HE_LOG(4) << "Registering constant folding pass"; pass_manager.register_pass<ngraph::pass::ConstantFolding>(); } NGRAPH_HE_LOG(4) << "Running passes"; pass_manager.run_passes(m_function); ngraph::pass::Manager pass_manager_he; pass_manager_he.set_pass_visualization(false); pass_manager_he.set_pass_serialization(false); pass_manager_he.register_pass<pass::HEFusion>(); pass_manager_he.register_pass<pass::HELiveness>(); pass_manager_he.register_pass<pass::SupportedOps>( [this](const ngraph::Node& op) { return m_he_seal_backend.is_supported(op); }); NGRAPH_HE_LOG(4) << "Running HE passes"; pass_manager_he.run_passes(m_function); update_he_op_annotations(); } HESealExecutable::~HESealExecutable() noexcept { NGRAPH_HE_LOG(3) << "~HESealExecutable()"; if (m_server_setup) { if (m_message_handling_thread.joinable()) { NGRAPH_HE_LOG(5) << "Waiting for m_message_handling_thread to join"; try { m_message_handling_thread.join(); } catch (std::exception& e) { NGRAPH_ERR << "Exception closing executable thread " << e.what(); } NGRAPH_HE_LOG(5) << "m_message_handling_thread joined"; } // m_acceptor and m_io_context both free the socket? Avoid double-free try { m_acceptor->close(); } catch (std::exception& e) { NGRAPH_ERR << "Exception closing m_acceptor " << e.what(); } m_acceptor = nullptr; m_session = nullptr; } } void HESealExecutable::update_he_op_annotations() { NGRAPH_HE_LOG(3) << "Upadting HE op annotations"; ngraph::pass::Manager pass_manager_he; pass_manager_he.register_pass<pass::PropagateHEAnnotations>(); pass_manager_he.run_passes(m_function); m_is_compiled = true; m_wrapped_nodes.clear(); for (const std::shared_ptr<Node>& node : m_function->get_ordered_ops()) { m_wrapped_nodes.emplace_back(node); } set_parameters_and_results(*m_function); } void HESealExecutable::set_batch_size(size_t batch_size) { size_t max_batch_size = m_he_seal_backend.get_ckks_encoder()->slot_count(); if (complex_packing()) { max_batch_size *= 2; } NGRAPH_CHECK(batch_size <= max_batch_size, "Batch size ", batch_size, " too large (maximum ", max_batch_size, ")"); m_batch_size = batch_size; NGRAPH_HE_LOG(5) << "Server set batch size to " << m_batch_size; } void HESealExecutable::check_client_supports_function() { // Check if single parameter is from client size_t from_client_count = 0; for (const auto& param : get_parameters()) { if (from_client(*param)) { from_client_count++; NGRAPH_HE_LOG(5) << "Parameter " << param->get_name() << " from client"; } } NGRAPH_CHECK(get_results().size() == 1, "HESealExecutable only supports output size 1 (got ", get_results().size(), ")"); NGRAPH_CHECK(from_client_count > 0, "Expected > 0 parameters from client"); } bool HESealExecutable::server_setup() { if (!m_server_setup) { NGRAPH_HE_LOG(1) << "Enable client"; check_client_supports_function(); NGRAPH_HE_LOG(1) << "Starting server"; start_server(); std::stringstream param_stream; m_he_seal_backend.get_encryption_parameters().save(param_stream); pb::EncryptionParameters proto_parms; *proto_parms.mutable_encryption_parameters() = param_stream.str(); pb::TCPMessage proto_msg; *proto_msg.mutable_encryption_parameters() = proto_parms; proto_msg.set_type(pb::TCPMessage_Type_RESPONSE); TCPMessage parms_message(std::move(proto_msg)); NGRAPH_HE_LOG(3) << "Server waiting until session started"; std::unique_lock<std::mutex> mlock(m_session_mutex); m_session_cond.wait(mlock, [this]() { return this->session_started(); }); NGRAPH_HE_LOG(3) << "Server writing parameters message"; m_session->write_message(std::move(parms_message)); m_server_setup = true; // Set client inputs to dummy values if (m_is_compiled) { m_client_inputs.clear(); m_client_inputs.resize(get_parameters().size()); } else { NGRAPH_HE_LOG(1) << "Client already setup"; } } return true; } void HESealExecutable::accept_connection() { NGRAPH_HE_LOG(1) << "Server accepting connections"; auto server_callback = std::bind(&HESealExecutable::handle_message, this, std::placeholders::_1); m_acceptor->async_accept( [this, server_callback](boost::system::error_code ec, boost::asio::ip::tcp::socket socket) { if (!ec) { NGRAPH_HE_LOG(1) << "Connection accepted"; m_session = std::make_shared<TCPSession>(std::move(socket), server_callback); m_session->start(); NGRAPH_HE_LOG(1) << "Session started"; std::lock_guard<std::mutex> guard(m_session_mutex); m_session_started = true; m_session_cond.notify_one(); } else { NGRAPH_ERR << "error accepting connection " << ec.message(); accept_connection(); } }); } void HESealExecutable::start_server() { boost::asio::ip::tcp::resolver resolver(m_io_context); boost::asio::ip::tcp::endpoint server_endpoints(boost::asio::ip::tcp::v4(), m_port); m_acceptor = std::make_unique<boost::asio::ip::tcp::acceptor>( m_io_context, server_endpoints); boost::asio::socket_base::reuse_address option(true); m_acceptor->set_option(option); accept_connection(); m_message_handling_thread = std::thread([this]() { try { m_io_context.run(); } catch (std::exception& e) { NGRAPH_CHECK(false, "Server error hanndling thread: ", e.what()); } }); } void HESealExecutable::load_public_key(const pb::TCPMessage& proto_msg) { NGRAPH_CHECK(proto_msg.has_public_key(), "proto_msg doesn't have public key"); seal::PublicKey key; const std::string& pk_str = proto_msg.public_key().public_key(); std::stringstream key_stream(pk_str); key.load(m_context, key_stream); m_he_seal_backend.set_public_key(key); m_client_public_key_set = true; } void HESealExecutable::load_eval_key(const pb::TCPMessage& proto_msg) { NGRAPH_CHECK(proto_msg.has_eval_key(), "proto_msg doesn't have eval key"); seal::RelinKeys keys; const std::string& evk_str = proto_msg.eval_key().eval_key(); std::stringstream key_stream(evk_str); keys.load(m_context, key_stream); m_he_seal_backend.set_relin_keys(keys); m_client_eval_key_set = true; } void HESealExecutable::send_inference_shape() { m_sent_inference_shape = true; const ParameterVector& input_parameters = get_parameters(); pb::TCPMessage proto_msg; proto_msg.set_type(pb::TCPMessage_Type_REQUEST); for (const auto& input_param : input_parameters) { if (from_client(*input_param)) { pb::HETensor* proto_he_tensor = proto_msg.add_he_tensors(); std::vector<uint64_t> shape{input_param->get_shape()}; *proto_he_tensor->mutable_shape() = {shape.begin(), shape.end()}; std::string name = input_param->get_provenance_tags().empty() ? input_param->get_name() : *input_param->get_provenance_tags().begin(); NGRAPH_HE_LOG(1) << "Server setting inference tensor name " << name << " (corresponding to Parameter " << input_param->get_name() << "), with " << input_param->get_shape(); proto_he_tensor->set_name(name); if (plaintext_packed(*input_param)) { NGRAPH_HE_LOG(1) << "Setting parameter " << input_param->get_name() << " to packed"; proto_he_tensor->set_packed(true); } } } NGRAPH_HE_LOG(1) << "Server sending inference of " << proto_msg.he_tensors_size() << " parameters"; json js = {{"function", "Parameter"}}; pb::Function f; f.set_function(js.dump()); NGRAPH_HE_LOG(3) << "js " << js.dump(); *proto_msg.mutable_function() = f; TCPMessage execute_msg(std::move(proto_msg)); m_session->write_message(std::move(execute_msg)); } void HESealExecutable::handle_relu_result(const pb::TCPMessage& proto_msg) { NGRAPH_HE_LOG(3) << "Server handling relu result"; std::lock_guard<std::mutex> guard(m_relu_mutex); NGRAPH_CHECK(proto_msg.he_tensors_size() == 1, "Can only handle one tensor at a time, got ", proto_msg.he_tensors_size()); const auto& proto_tensor = proto_msg.he_tensors(0); auto he_tensor = HETensor::load_from_proto_tensor( proto_tensor, *m_he_seal_backend.get_ckks_encoder(), m_he_seal_backend.get_context(), *m_he_seal_backend.get_encryptor(), *m_he_seal_backend.get_decryptor(), m_he_seal_backend.get_encryption_parameters()); size_t result_count = proto_tensor.data_size(); for (size_t result_idx = 0; result_idx < result_count; ++result_idx) { m_relu_data[m_unknown_relu_idx[result_idx + m_relu_done_count]] = he_tensor->data(result_idx); } m_relu_done_count += result_count; m_relu_cond.notify_all(); } void HESealExecutable::handle_bounded_relu_result( const pb::TCPMessage& proto_msg) { handle_relu_result(proto_msg); } void HESealExecutable::handle_max_pool_result(const pb::TCPMessage& proto_msg) { std::lock_guard<std::mutex> guard(m_max_pool_mutex); NGRAPH_CHECK(proto_msg.he_tensors_size() == 1, "Can only handle one tensor at a time, got ", proto_msg.he_tensors_size()); const auto& proto_tensor = proto_msg.he_tensors(0); size_t result_count = proto_tensor.data_size(); NGRAPH_CHECK(result_count == 1, "Maxpool only supports result_count 1, got ", result_count); auto he_tensor = HETensor::load_from_proto_tensor( proto_tensor, *m_he_seal_backend.get_ckks_encoder(), m_he_seal_backend.get_context(), *m_he_seal_backend.get_encryptor(), *m_he_seal_backend.get_decryptor(), m_he_seal_backend.get_encryption_parameters()); m_max_pool_data.emplace_back(he_tensor->data(0)); m_max_pool_done = true; m_max_pool_cond.notify_all(); } void HESealExecutable::handle_message(const TCPMessage& message) { NGRAPH_HE_LOG(3) << "Server handling message"; std::shared_ptr<pb::TCPMessage> proto_msg = message.proto_message(); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wswitch-enum" switch (proto_msg->type()) { case pb::TCPMessage_Type_RESPONSE: { if (proto_msg->has_public_key()) { load_public_key(*proto_msg); } if (proto_msg->has_eval_key()) { load_eval_key(*proto_msg); } if (!m_sent_inference_shape && m_client_public_key_set && m_client_eval_key_set) { send_inference_shape(); } if (proto_msg->has_function()) { const std::string& function = proto_msg->function().function(); json js = json::parse(function); auto name = js.at("function"); if (name == "Relu") { handle_relu_result(*proto_msg); } else if (name == "BoundedRelu") { handle_bounded_relu_result(*proto_msg); } else if (name == "MaxPool") { handle_max_pool_result(*proto_msg); } else { throw ngraph_error("Unknown function name"); } } break; } case pb::TCPMessage_Type_REQUEST: { if (proto_msg->he_tensors_size() > 0) { handle_client_ciphers(*proto_msg); } break; } case pb::TCPMessage_Type_UNKNOWN: default: NGRAPH_CHECK(false, "Unknonwn TCPMessage type"); } #pragma clang diagnostic pop } void HESealExecutable::handle_client_ciphers(const pb::TCPMessage& proto_msg) { NGRAPH_HE_LOG(3) << "Handling client tensors"; NGRAPH_CHECK(proto_msg.he_tensors_size() > 0, "Client received empty tensor message"); NGRAPH_CHECK(proto_msg.he_tensors_size() == 1, "Client only supports 1 client tensor"); // TODO(fboemer): check for uniqueness of batch size if > 1 input tensor const ParameterVector& input_parameters = get_parameters(); /// \brief Looks for a parameter which matches a given tensor name /// \param[in] tensor_name Tensor name to match against /// \param[out] matching_idx Will be populated if a match is found /// \returns Whether or not a matching parameter shape has been found auto find_matching_parameter_index = [&](const std::string& tensor_name, size_t& matching_idx) { NGRAPH_HE_LOG(5) << "Calling find_matching_parameter_index(" << tensor_name << ")"; for (size_t param_idx = 0; param_idx < input_parameters.size(); ++param_idx) { const auto& parameter = input_parameters[param_idx]; for (const auto& tag : parameter->get_provenance_tags()) { NGRAPH_HE_LOG(5) << "Tag " << tag; } if (param_originates_from_name(*parameter, tensor_name)) { NGRAPH_HE_LOG(5) << "Param " << tensor_name << " matches at index " << param_idx; matching_idx = param_idx; return true; } } NGRAPH_HE_LOG(5) << "Could not find tensor " << tensor_name; return false; }; auto& proto_tensor = proto_msg.he_tensors(0); ngraph::Shape shape{proto_tensor.shape().begin(), proto_tensor.shape().end()}; NGRAPH_HE_LOG(5) << "proto_tensor.packed() " << proto_tensor.packed(); set_batch_size(HETensor::batch_size(shape, proto_tensor.packed())); NGRAPH_HE_LOG(5) << "Offset " << proto_tensor.offset(); size_t param_idx; NGRAPH_CHECK(find_matching_parameter_index(proto_tensor.name(), param_idx), "Could not find matching parameter name ", proto_tensor.name()); if (m_client_inputs[param_idx] == nullptr) { auto he_tensor = HETensor::load_from_proto_tensor( proto_tensor, *m_he_seal_backend.get_ckks_encoder(), m_he_seal_backend.get_context(), *m_he_seal_backend.get_encryptor(), *m_he_seal_backend.get_decryptor(), m_he_seal_backend.get_encryption_parameters()); m_client_inputs[param_idx] = he_tensor; } else { HETensor::load_from_proto_tensor(m_client_inputs[param_idx], proto_tensor, m_he_seal_backend.get_context()); } auto done_loading = [&]() { for (size_t parm_idx = 0; parm_idx < input_parameters.size(); ++parm_idx) { const auto& param = input_parameters[parm_idx]; if (from_client(*param)) { NGRAPH_HE_LOG(5) << "From client param shape " << param->get_shape(); NGRAPH_HE_LOG(5) << "m_batch_size " << m_batch_size; if (m_client_inputs[parm_idx] == nullptr || !m_client_inputs[parm_idx]->done_loading()) { return false; } } } return true; }; if (done_loading()) { NGRAPH_HE_LOG(3) << "Done loading client ciphertexts"; std::lock_guard<std::mutex> guard(m_client_inputs_mutex); m_client_inputs_received = true; NGRAPH_HE_LOG(5) << "Notifying done loading client ciphertexts"; m_client_inputs_cond.notify_all(); } else { NGRAPH_HE_LOG(3) << "Not yet done loading client ciphertexts"; } } std::vector<ngraph::runtime::PerformanceCounter> HESealExecutable::get_performance_data() const { std::vector<runtime::PerformanceCounter> rc; for (const auto& [node, stop_watch] : m_timer_map) { rc.emplace_back(node, stop_watch.get_total_microseconds(), stop_watch.get_call_count()); } return rc; } bool HESealExecutable::call( const std::vector<std::shared_ptr<runtime::Tensor>>& outputs, const std::vector<std::shared_ptr<runtime::Tensor>>& server_inputs) { NGRAPH_HE_LOG(3) << "HESealExecutable::call"; validate(outputs, server_inputs); NGRAPH_HE_LOG(3) << "HESealExecutable::call validated inputs"; if (m_enable_client) { if (!server_setup()) { return false; } } if (complex_packing()) { NGRAPH_HE_LOG(1) << "Complex packing"; } if (m_enable_client) { NGRAPH_HE_LOG(1) << "Waiting for m_client_inputs"; std::unique_lock<std::mutex> mlock(m_client_inputs_mutex); m_client_inputs_cond.wait( mlock, std::bind(&HESealExecutable::client_inputs_received, this)); NGRAPH_HE_LOG(1) << "Client inputs_received"; } // convert inputs to HETensor NGRAPH_HE_LOG(3) << "Converting inputs to HETensor"; const auto& parameters = get_parameters(); std::vector<std::shared_ptr<HETensor>> he_inputs; for (size_t input_idx = 0; input_idx < server_inputs.size(); ++input_idx) { auto param_shape = server_inputs[input_idx]->get_shape(); auto& param = parameters[input_idx]; std::shared_ptr<HETensor> he_input; if (m_enable_client && from_client(*param)) { NGRAPH_HE_LOG(1) << "Processing parameter " << param->get_name() << "(shape {" << param_shape << "}) from client"; NGRAPH_CHECK(m_client_inputs.size() > input_idx, "Not enough client inputs"); he_input = std::static_pointer_cast<HETensor>(m_client_inputs[input_idx]); if (auto current_annotation = std::dynamic_pointer_cast<HEOpAnnotations>( param->get_op_annotations())) { NGRAPH_CHECK( current_annotation->packed() == he_input->is_packed(), "Parameter annotation ", *current_annotation, " does not match ", (he_input->is_packed() ? "packed" : "unpacked"), "input tensor"); current_annotation->set_encrypted(he_input->any_encrypted_data()); param->set_op_annotations(current_annotation); } else { NGRAPH_WARN << "Parameter " << param->get_name() << " has no HE op annotation"; } } else { NGRAPH_HE_LOG(1) << "Processing parameter " << param->get_name() << "(shape {" << param_shape << "}) from server"; auto he_server_input = std::static_pointer_cast<HETensor>(server_inputs[input_idx]); he_input = he_server_input; if (auto current_annotation = std::dynamic_pointer_cast<HEOpAnnotations>( param->get_op_annotations())) { NGRAPH_HE_LOG(5) << "Parameter " << param->get_name() << " has annotation " << *current_annotation; if (!he_input->any_encrypted_data()) { if (current_annotation->packed()) { he_input->pack(); } else { he_input->unpack(); } } if (current_annotation->encrypted()) { NGRAPH_HE_LOG(3) << "Encrypting parameter " << param->get_name() << " from server"; #pragma omp parallel for for (size_t he_type_idx = 0; he_type_idx < he_input->get_batched_element_count(); ++he_type_idx) { if (he_input->data(he_type_idx).is_plaintext()) { auto cipher = HESealBackend::create_empty_ciphertext(); m_he_seal_backend.encrypt( cipher, he_input->data(he_type_idx).get_plaintext(), he_input->get_element_type(), he_input->data(he_type_idx).complex_packing()); he_input->data(he_type_idx).set_ciphertext(cipher); } } NGRAPH_CHECK(he_input->is_packed() == current_annotation->packed(), "Mismatch between tensor input and annotation (", he_input->is_packed(), " != ", current_annotation->packed(), ")"); NGRAPH_HE_LOG(3) << "Done encrypting parameter " << param->get_name() << " from server"; } } } NGRAPH_CHECK(he_input != nullptr, "HE input is nullptr"); if (he_input->is_packed()) { set_batch_size(he_input->get_batch_size()); } he_inputs.emplace_back(he_input); } NGRAPH_HE_LOG(3) << "Updating HE op annotations"; update_he_op_annotations(); NGRAPH_HE_LOG(3) << "Converting outputs to HETensor"; std::vector<std::shared_ptr<HETensor>> he_outputs; he_outputs.reserve(outputs.size()); for (auto& tensor : outputs) { he_outputs.push_back(std::static_pointer_cast<HETensor>(tensor)); } NGRAPH_HE_LOG(3) << "Mapping function parameters to HETensor"; NGRAPH_CHECK(he_inputs.size() >= parameters.size(), "Not enough inputs in input map"); std::unordered_map<ngraph::descriptor::Tensor*, std::shared_ptr<HETensor>> tensor_map; size_t input_count = 0; for (const auto& param : parameters) { for (size_t param_out_idx = 0; param_out_idx < param->get_output_size(); ++param_out_idx) { descriptor::Tensor* tensor = param->get_output_tensor_ptr(param_out_idx).get(); tensor_map.insert({tensor, he_inputs[input_count++]}); } } NGRAPH_HE_LOG(3) << "Mapping function outputs to HETensor"; for (size_t output_count = 0; output_count < get_results().size(); ++output_count) { auto output = get_results()[output_count]; if (!std::dynamic_pointer_cast<op::Result>(output)) { throw ngraph_error("One of function's outputs isn't op::Result"); } ngraph::descriptor::Tensor* tv = output->get_output_tensor_ptr(0).get(); auto& he_output = he_outputs[output_count]; if (HEOpAnnotations::has_he_annotation(*output)) { auto he_op_annotation = HEOpAnnotations::he_op_annotation(*output); if (!he_output->any_encrypted_data()) { if (he_op_annotation->packed()) { he_output->pack(); } else { he_output->unpack(); } } } tensor_map.insert({tv, he_output}); } // for each ordered op in the graph for (const NodeWrapper& wrapped : m_wrapped_nodes) { auto op = wrapped.get_node(); auto type_id = wrapped.get_typeid(); bool verbose = verbose_op(*op); if (verbose) { NGRAPH_HE_LOG(3) << "\033[1;32m" << "[ " << op->get_name() << " ]" << "\033[0m"; if (type_id == OP_TYPEID::Constant) { NGRAPH_HE_LOG(3) << "Constant shape " << op->get_shape(); } } if (type_id == OP_TYPEID::Parameter) { if (verbose) { const auto param_op = std::static_pointer_cast<const ngraph::op::Parameter>(op); if (HEOpAnnotations::has_he_annotation(*param_op)) { std::string from_client_str = from_client(*param_op) ? "" : " not"; NGRAPH_HE_LOG(3) << "Parameter shape " << param_op->get_shape() << from_client_str << " from client"; } } continue; } m_timer_map[op].start(); // get op inputs from map std::vector<std::shared_ptr<HETensor>> op_inputs; for (auto input : op->inputs()) { descriptor::Tensor* tensor = &input.get_tensor(); op_inputs.push_back(tensor_map.at(tensor)); } if (m_enable_client && type_id == OP_TYPEID::Result) { // Client outputs don't have decryption performed, so skip result op NGRAPH_HE_LOG(3) << "Setting client outputs"; m_client_outputs = op_inputs; } // get op outputs from map or create std::vector<std::shared_ptr<HETensor>> op_outputs; for (size_t i = 0; i < op->get_output_size(); ++i) { auto tensor = &op->output(i).get_tensor(); auto it = tensor_map.find(tensor); if (it == tensor_map.end()) { // The output tensor is not in the tensor map so create a new tensor Shape shape = op->get_output_shape(i); const element::Type& element_type = op->get_output_element_type(i); std::string name = op->output(i).get_tensor().get_name(); NGRAPH_HE_LOG(3) << "Get output packing / encrypted"; // TODO(fboemer): remove case once Constant becomes an op // (https://github.com/NervanaSystems/ngraph/pull/3752) bool encrypted_out; bool packed_out; if (op->is_op()) { std::shared_ptr<HEOpAnnotations> he_op_annotation = HEOpAnnotations::he_op_annotation( *std::static_pointer_cast<const ngraph::op::Op>(op)); encrypted_out = he_op_annotation->encrypted(); packed_out = he_op_annotation->packed(); } else { NGRAPH_WARN << "Node " << op->get_name() << " is not op, using default encrypted / packing behavior"; encrypted_out = std::any_of( op_inputs.begin(), op_inputs.end(), [](const std::shared_ptr<ngraph::he::HETensor>& op_input) { return op_input->any_encrypted_data(); }); packed_out = std::any_of( op_inputs.begin(), op_inputs.end(), [](const std::shared_ptr<ngraph::he::HETensor>& he_tensor) { return he_tensor->is_packed(); }); } NGRAPH_HE_LOG(3) << "encrypted_out " << encrypted_out; NGRAPH_HE_LOG(3) << "packed_out " << packed_out; if (packed_out) { HETensor::unpack_shape(shape, m_batch_size); } NGRAPH_HE_LOG(5) << "Creating output tensor with shape " << shape; if (encrypted_out) { auto out_tensor = std::static_pointer_cast<HETensor>( m_he_seal_backend.create_cipher_tensor(element_type, shape, packed_out, name)); tensor_map.insert({tensor, out_tensor}); } else { auto out_tensor = std::static_pointer_cast<HETensor>( m_he_seal_backend.create_plain_tensor(element_type, shape, packed_out, name)); tensor_map.insert({tensor, out_tensor}); } } op_outputs.push_back(tensor_map.at(tensor)); } // get op type element::Type base_type; if (op->get_inputs().empty()) { base_type = op->get_element_type(); } else { base_type = op->get_inputs().at(0).get_tensor().get_element_type(); } generate_calls(base_type, wrapped, op_outputs, op_inputs); m_timer_map[op].stop(); // delete any obsolete tensors for (const descriptor::Tensor* t : op->liveness_free_list) { bool erased = false; for (auto it = tensor_map.begin(); it != tensor_map.end(); ++it) { const std::string& it_name = it->second->get_name(); if (it_name == t->get_name()) { tensor_map.erase(it); erased = true; break; } } if (!erased) { NGRAPH_DEBUG << "Failed to erase " << t->get_name() << " from tensor map"; } } if (verbose) { NGRAPH_HE_LOG(3) << "\033[1;31m" << op->get_name() << " took " << m_timer_map[op].get_milliseconds() << "ms" << "\033[0m"; } } size_t total_time = 0; for (const auto& elem : m_timer_map) { total_time += elem.second.get_milliseconds(); } if (verbose_op("total")) { NGRAPH_HE_LOG(3) << "\033[1;32m" << "Total time " << total_time << " (ms) \033[0m"; } // Send outputs to client. if (m_enable_client) { send_client_results(); } return true; } void HESealExecutable::send_client_results() { NGRAPH_HE_LOG(3) << "Sending results to client"; NGRAPH_CHECK(m_client_outputs.size() == 1, "HESealExecutable only supports output size 1 (got ", get_results().size(), ""); std::vector<pb::HETensor> proto_tensors; m_client_outputs[0]->write_to_protos(proto_tensors); for (const auto& proto_tensor : proto_tensors) { pb::TCPMessage result_msg; result_msg.set_type(pb::TCPMessage_Type_RESPONSE); *result_msg.add_he_tensors() = proto_tensor; auto result_shape = result_msg.he_tensors(0).shape(); NGRAPH_HE_LOG(3) << "Server sending result with shape " << Shape{result_shape.begin(), result_shape.end()}; m_session->write_message(TCPMessage(std::move(result_msg))); } // Wait until message is written std::unique_lock<std::mutex> mlock(m_result_mutex); std::condition_variable& writing_cond = m_session->is_writing_cond(); writing_cond.wait(mlock, [this] { return !m_session->is_writing(); }); } void HESealExecutable::generate_calls( const element::Type& type, const NodeWrapper& node_wrapper, const std::vector<std::shared_ptr<HETensor>>& out, const std::vector<std::shared_ptr<HETensor>>& args) { const Node& node = *node_wrapper.get_node(); bool verbose = verbose_op(node); std::string node_op = node.description(); // We want to check that every OP_TYPEID enumeration is included in the // list. These GCC flags enable compile-time checking so that if an // enumeration // is not in the list an error is generated. #pragma GCC diagnostic push #pragma GCC diagnostic error "-Wswitch" #pragma GCC diagnostic error "-Wswitch-enum" switch (node_wrapper.get_typeid()) { case OP_TYPEID::Add: { add_seal(args[0]->data(), args[1]->data(), out[0]->data(), out[0]->get_batched_element_count(), type, m_he_seal_backend); break; } case OP_TYPEID::AvgPool: { const auto avg_pool = static_cast<const op::AvgPool*>(&node); Shape op_in_shape = args[0]->get_packed_shape(); Shape op_out_shape = out[0]->get_packed_shape(); if (verbose) { NGRAPH_HE_LOG(3) << "AvgPool " << op_in_shape << " => " << op_out_shape; } avg_pool_seal( args[0]->data(), out[0]->data(), op_in_shape, op_out_shape, avg_pool->get_window_shape(), avg_pool->get_window_movement_strides(), avg_pool->get_padding_below(), avg_pool->get_padding_above(), avg_pool->get_include_padding_in_avg_computation(), out[0]->get_batch_size(), m_he_seal_backend); rescale_seal(out[0]->data(), m_he_seal_backend, verbose); break; } case OP_TYPEID::BatchNormInference: { const auto bn = static_cast<const ngraph::op::BatchNormInference*>(&node); double eps = bn->get_eps_value(); NGRAPH_CHECK(args.size() == 5, "BatchNormInference has ", args.size(), "arguments (expected 5)."); auto gamma = args[0]; auto beta = args[1]; auto input = args[2]; auto mean = args[3]; auto variance = args[4]; batch_norm_inference_seal(eps, gamma->data(), beta->data(), input->data(), mean->data(), variance->data(), out[0]->data(), args[2]->get_packed_shape(), m_batch_size, m_he_seal_backend); break; } case OP_TYPEID::BoundedRelu: { const auto bounded_relu = static_cast<const op::BoundedRelu*>(&node); float alpha = bounded_relu->get_alpha(); size_t output_size = args[0]->get_batched_element_count(); if (m_enable_client) { handle_server_relu_op(args[0], out[0], node_wrapper); } else { NGRAPH_WARN << "Performing BoundedRelu without client is not " "privacy-preserving "; NGRAPH_CHECK(output_size == args[0]->data().size(), "output size ", output_size, " doesn't match number of elements", out[0]->data().size()); bounded_relu_seal(args[0]->data(), out[0]->data(), alpha, output_size, m_he_seal_backend); } break; } case OP_TYPEID::Broadcast: { const auto broadcast = static_cast<const op::Broadcast*>(&node); broadcast_seal(args[0]->data(), out[0]->data(), args[0]->get_packed_shape(), out[0]->get_packed_shape(), broadcast->get_broadcast_axes()); break; } case OP_TYPEID::BroadcastLike: break; case OP_TYPEID::Concat: { const auto* concat = static_cast<const op::Concat*>(&node); std::vector<Shape> in_shapes; std::vector<std::vector<HEType>> in_args; for (auto& arg : args) { in_args.push_back(arg->data()); in_shapes.push_back(arg->get_packed_shape()); } concat_seal(in_args, out[0]->data(), in_shapes, out[0]->get_packed_shape(), concat->get_concatenation_axis()); break; } case OP_TYPEID::Constant: { const auto* constant = static_cast<const op::Constant*>(&node); constant_seal(out[0]->data(), type, constant->get_data_ptr(), m_he_seal_backend, out[0]->get_batched_element_count()); break; } case OP_TYPEID::Convolution: { const auto* c = static_cast<const op::Convolution*>(&node); const auto& window_movement_strides = c->get_window_movement_strides(); const auto& window_dilation_strides = c->get_window_dilation_strides(); const auto& padding_below = c->get_padding_below(); const auto& padding_above = c->get_padding_above(); const auto& data_dilation_strides = c->get_data_dilation_strides(); Shape in_shape0 = args[0]->get_packed_shape(); Shape in_shape1 = args[1]->get_packed_shape(); if (verbose) { NGRAPH_HE_LOG(3) << in_shape0 << " Conv " << in_shape1 << " => " << out[0]->get_packed_shape(); } convolution_seal(args[0]->data(), args[1]->data(), out[0]->data(), in_shape0, in_shape1, out[0]->get_packed_shape(), window_movement_strides, window_dilation_strides, padding_below, padding_above, data_dilation_strides, 0, 1, 1, 0, 0, 1, false, type, m_batch_size, m_he_seal_backend, verbose); rescale_seal(out[0]->data(), m_he_seal_backend, verbose); break; } case OP_TYPEID::Divide: { Shape in_shape0 = args[0]->get_packed_shape(); Shape in_shape1 = args[1]->get_packed_shape(); divide_seal(args[0]->data(), args[1]->data(), out[0]->data(), out[0]->get_batched_element_count(), type, m_he_seal_backend); break; } case OP_TYPEID::Dot: { const auto* dot = static_cast<const op::Dot*>(&node); Shape in_shape0 = args[0]->get_packed_shape(); Shape in_shape1 = args[1]->get_packed_shape(); if (verbose) { NGRAPH_HE_LOG(3) << in_shape0 << " dot " << in_shape1; } dot_seal(args[0]->data(), args[1]->data(), out[0]->data(), in_shape0, in_shape1, out[0]->get_packed_shape(), dot->get_reduction_axes_count(), type, m_he_seal_backend); rescale_seal(out[0]->data(), m_he_seal_backend, verbose); break; } case OP_TYPEID::Exp: { if (m_enable_client) { NGRAPH_CHECK(false, "Exp not implemented for client-aided model "); } else { NGRAPH_WARN << " Performing Exp without client is not privacy-preserving "; exp_seal(args[0]->data(), out[0]->data(), args[0]->get_batched_element_count(), m_he_seal_backend); } break; } case OP_TYPEID::Max: { const auto* max = static_cast<const op::Max*>(&node); auto reduction_axes = max->get_reduction_axes(); NGRAPH_CHECK(!args[0]->is_packed() || (reduction_axes.find(0) == reduction_axes.end()), "Max reduction axes cannot contain 0 for packed tensors"); if (m_enable_client) { NGRAPH_CHECK(false, "Max not implemented for client-aided model"); } else { NGRAPH_WARN << "Performing Max without client is not " "privacy-preserving"; size_t output_size = args[0]->get_batched_element_count(); NGRAPH_CHECK(output_size == args[0]->data().size(), "output size ", output_size, " doesn't match number of elements", out[0]->data().size()); max_seal(args[0]->data(), out[0]->data(), args[0]->get_packed_shape(), out[0]->get_packed_shape(), max->get_reduction_axes(), out[0]->get_batch_size(), m_he_seal_backend); } break; } case OP_TYPEID::MaxPool: { const auto* max_pool = static_cast<const op::MaxPool*>(&node); if (m_enable_client) { handle_server_max_pool_op(args[0], out[0], node_wrapper); } else { NGRAPH_WARN << "Performing MaxPool without client is not " "privacy-preserving"; size_t output_size = args[0]->get_batched_element_count(); NGRAPH_CHECK(output_size == args[0]->data().size(), "output size ", output_size, " doesn't match number of elements", out[0]->data().size()); max_pool_seal(args[0]->data(), out[0]->data(), args[0]->get_packed_shape(), out[0]->get_packed_shape(), max_pool->get_window_shape(), max_pool->get_window_movement_strides(), max_pool->get_padding_below(), max_pool->get_padding_above(), m_he_seal_backend); } break; } case OP_TYPEID::Minimum: { minimum_seal(args[0]->data(), args[1]->data(), out[0]->data(), out[0]->get_batched_element_count(), m_he_seal_backend); break; } case OP_TYPEID::Multiply: { multiply_seal(args[0]->data(), args[1]->data(), out[0]->data(), out[0]->get_batched_element_count(), type, m_he_seal_backend); rescale_seal(out[0]->data(), m_he_seal_backend, verbose); break; } case OP_TYPEID::Negative: { negate_seal(args[0]->data(), out[0]->data(), out[0]->get_batched_element_count(), type, m_he_seal_backend); break; } case OP_TYPEID::Pad: { const auto* pad = static_cast<const op::Pad*>(&node); pad_seal(args[0]->data(), args[1]->data(), out[0]->data(), args[0]->get_packed_shape(), out[0]->get_packed_shape(), pad->get_padding_below(), pad->get_padding_above(), pad->get_pad_mode()); break; } case OP_TYPEID::Parameter: { NGRAPH_HE_LOG(3) << "Skipping parameter"; break; } case OP_TYPEID::Passthrough: { const auto* passthrough = static_cast<const op::Passthrough*>(&node); throw unsupported_op{"Unsupported operation language: " + passthrough->language()}; } case OP_TYPEID::Power: { // TODO(fboemer): implement with client NGRAPH_WARN << "Performing Power without client is not privacy preserving "; power_seal(args[0]->data(), args[1]->data(), out[0]->data(), out[0]->data().size(), type, m_he_seal_backend); break; } case OP_TYPEID::Relu: { if (m_enable_client) { handle_server_relu_op(args[0], out[0], node_wrapper); } else { NGRAPH_WARN << "Performing Relu without client is not privacy preserving "; size_t output_size = args[0]->get_batched_element_count(); NGRAPH_CHECK(output_size == args[0]->data().size(), "output size ", output_size, "doesn't match number of elements", out[0]->data().size()); relu_seal(args[0]->data(), out[0]->data(), output_size, m_he_seal_backend); } break; } case OP_TYPEID::Reshape: { const auto* reshape = static_cast<const op::Reshape*>(&node); if (verbose) { NGRAPH_HE_LOG(3) << args[0]->get_packed_shape() << " reshape " << out[0]->get_packed_shape(); } reshape_seal(args[0]->data(), out[0]->data(), args[0]->get_packed_shape(), reshape->get_input_order(), out[0]->get_packed_shape()); break; } case OP_TYPEID::Result: { result_seal(args[0]->data(), out[0]->data(), out[0]->get_batched_element_count(), m_he_seal_backend); break; } case OP_TYPEID::Reverse: { const auto* reverse = static_cast<const op::Reverse*>(&node); if (verbose) { NGRAPH_HE_LOG(3) << args[0]->get_packed_shape() << " reshape " << out[0]->get_packed_shape(); } reverse_seal(args[0]->data(), out[0]->data(), args[0]->get_packed_shape(), out[0]->get_packed_shape(), reverse->get_reversed_axes()); break; } case OP_TYPEID::ScalarConstantLike: { break; } case OP_TYPEID::Slice: { const auto* slice = static_cast<const op::Slice*>(&node); const Shape& in_shape = args[0]->get_packed_shape(); const Shape& out_shape = out[0]->get_packed_shape(); const Coordinate& lower_bounds = slice->get_lower_bounds(); Coordinate upper_bounds = slice->get_upper_bounds(); const Strides& strides = slice->get_strides(); if (verbose) { NGRAPH_HE_LOG(3) << "in_shape " << in_shape; NGRAPH_HE_LOG(3) << "out_shape " << out_shape; NGRAPH_HE_LOG(3) << "lower_bounds " << lower_bounds; NGRAPH_HE_LOG(3) << "upper_bounds " << upper_bounds; NGRAPH_HE_LOG(3) << "strides " << strides; } if (!upper_bounds.empty() && !upper_bounds.empty() && (upper_bounds[0] > in_shape[0])) { NGRAPH_CHECK(upper_bounds[0] == out[0]->get_batch_size(), "Slice upper bound shape ", upper_bounds, " is not compatible with tensor output shape ", out[0]->get_shape()); upper_bounds[0] = 1; if (verbose) { NGRAPH_HE_LOG(3) << "new upper_bounds " << upper_bounds; } } slice_seal(args[0]->data(), out[0]->data(), in_shape, lower_bounds, upper_bounds, strides, out_shape); break; } case OP_TYPEID::Softmax: { const auto* softmax = static_cast<const op::Softmax*>(&node); auto axes = softmax->get_axes(); NGRAPH_CHECK(!args[0]->is_packed() || (axes.find(0) == axes.end()), "Softmax axes cannot contain 0 for packed tensors"); softmax_seal(args[0]->data(), out[0]->data(), args[0]->get_packed_shape(), softmax->get_axes(), type, m_he_seal_backend); break; } case OP_TYPEID::Subtract: { subtract_seal(args[0]->data(), args[1]->data(), out[0]->data(), out[0]->get_batched_element_count(), type, m_he_seal_backend); break; } case OP_TYPEID::Sum: { const auto* sum = static_cast<const op::Sum*>(&node); sum_seal(args[0]->data(), out[0]->data(), args[0]->get_packed_shape(), out[0]->get_packed_shape(), sum->get_reduction_axes(), type, m_he_seal_backend); break; } // Unsupported ops case OP_TYPEID::Abs: case OP_TYPEID::Acos: case OP_TYPEID::All: case OP_TYPEID::AllReduce: case OP_TYPEID::And: case OP_TYPEID::Any: case OP_TYPEID::ArgMax: case OP_TYPEID::ArgMin: case OP_TYPEID::Asin: case OP_TYPEID::Atan: case OP_TYPEID::AvgPoolBackprop: case OP_TYPEID::BatchMatMul: case OP_TYPEID::BatchNormTraining: case OP_TYPEID::BatchNormTrainingBackprop: case OP_TYPEID::BroadcastDistributed: case OP_TYPEID::Ceiling: case OP_TYPEID::Convert: case OP_TYPEID::ConvolutionBackpropData: case OP_TYPEID::ConvolutionBackpropFilters: case OP_TYPEID::Cos: case OP_TYPEID::Cosh: case OP_TYPEID::Dequantize: case OP_TYPEID::DynBroadcast: case OP_TYPEID::DynPad: case OP_TYPEID::DynReshape: case OP_TYPEID::DynSlice: case OP_TYPEID::DynReplaceSlice: case OP_TYPEID::EmbeddingLookup: case OP_TYPEID::Equal: case OP_TYPEID::Erf: case OP_TYPEID::Floor: case OP_TYPEID::Gather: case OP_TYPEID::GatherND: case OP_TYPEID::GenerateMask: case OP_TYPEID::GetOutputElement: case OP_TYPEID::Greater: case OP_TYPEID::GreaterEq: case OP_TYPEID::Less: case OP_TYPEID::LessEq: case OP_TYPEID::Log: case OP_TYPEID::LRN: case OP_TYPEID::Maximum: case OP_TYPEID::MaxPoolBackprop: case OP_TYPEID::Min: case OP_TYPEID::Not: case OP_TYPEID::NotEqual: case OP_TYPEID::OneHot: case OP_TYPEID::Or: case OP_TYPEID::Product: case OP_TYPEID::Quantize: case OP_TYPEID::QuantizedAvgPool: case OP_TYPEID::QuantizedConvolutionBias: case OP_TYPEID::QuantizedConvolutionBiasAdd: case OP_TYPEID::QuantizedConvolutionBiasSignedAdd: case OP_TYPEID::QuantizedConvolutionRelu: case OP_TYPEID::QuantizedConvolution: case OP_TYPEID::QuantizedDot: case OP_TYPEID::QuantizedDotBias: case OP_TYPEID::QuantizedMaxPool: case OP_TYPEID::Send: case OP_TYPEID::Recv: case OP_TYPEID::Range: case OP_TYPEID::ReluBackprop: case OP_TYPEID::ReplaceSlice: case OP_TYPEID::ReverseSequence: case OP_TYPEID::ScatterAdd: case OP_TYPEID::ScatterNDAdd: case OP_TYPEID::Select: case OP_TYPEID::ShapeOf: case OP_TYPEID::Sigmoid: case OP_TYPEID::SigmoidBackprop: case OP_TYPEID::Sign: case OP_TYPEID::Sin: case OP_TYPEID::Sinh: case OP_TYPEID::Sqrt: case OP_TYPEID::StopGradient: case OP_TYPEID::Tan: case OP_TYPEID::Tanh: case OP_TYPEID::Tile: case OP_TYPEID::TopK: case OP_TYPEID::Transpose: case OP_TYPEID::Xor: default: throw unsupported_op("Unsupported op '" + node.description() + "'"); #pragma GCC diagnostic pop } } void HESealExecutable::handle_server_max_pool_op( const std::shared_ptr<HETensor>& arg, const std::shared_ptr<HETensor>& out, const NodeWrapper& node_wrapper) { NGRAPH_HE_LOG(3) << "Server handle_server_max_pool_op"; const Node& node = *node_wrapper.get_node(); bool verbose = verbose_op(node); const auto* max_pool = static_cast<const op::MaxPool*>(&node); m_max_pool_done = false; Shape unpacked_arg_shape = node.get_input_shape(0); Shape out_shape = HETensor::pack_shape(node.get_output_shape(0)); // TODO(fboemer): call max_pool_seal directly? std::vector<std::vector<size_t>> maximize_lists = max_pool_seal_max_list( unpacked_arg_shape, out_shape, max_pool->get_window_shape(), max_pool->get_window_movement_strides(), max_pool->get_padding_below(), max_pool->get_padding_above()); m_max_pool_data.clear(); for (const auto& maximize_list : maximize_lists) { pb::TCPMessage proto_msg; proto_msg.set_type(pb::TCPMessage_Type_REQUEST); json js = {{"function", node.description()}}; pb::Function f; f.set_function(js.dump()); *proto_msg.mutable_function() = f; std::vector<HEType> cipher_batch; cipher_batch.reserve(maximize_list.size()); for (const size_t max_ind : maximize_list) { cipher_batch.emplace_back(arg->data(max_ind)); } NGRAPH_CHECK(!cipher_batch.empty(), "Maxpool cipher batch is empty"); HETensor max_pool_tensor( arg->get_element_type(), Shape{cipher_batch[0].batch_size(), cipher_batch.size()}, cipher_batch[0].plaintext_packing(), cipher_batch[0].complex_packing(), true, m_he_seal_backend); max_pool_tensor.data() = cipher_batch; std::vector<pb::HETensor> proto_tensors; max_pool_tensor.write_to_protos(proto_tensors); NGRAPH_CHECK(proto_tensors.size() == 1, "Only support MaxPool with 1 proto tensor"); *proto_msg.add_he_tensors() = proto_tensors[0]; // Send list of ciphertexts to maximize over to client if (verbose) { NGRAPH_HE_LOG(3) << "Sending " << cipher_batch.size() << " Maxpool ciphertexts to client"; } TCPMessage max_pool_message(std::move(proto_msg)); m_session->write_message(std::move(max_pool_message)); // Acquire lock std::unique_lock<std::mutex> mlock(m_max_pool_mutex); // Wait until max is done m_max_pool_cond.wait(mlock, std::bind(&HESealExecutable::max_pool_done, this)); // Reset for next max_pool call m_max_pool_done = false; } out->data() = m_max_pool_data; } void HESealExecutable::handle_server_relu_op( const std::shared_ptr<HETensor>& arg, const std::shared_ptr<HETensor>& out, const NodeWrapper& node_wrapper) { NGRAPH_HE_LOG(3) << "Server handle_server_relu_op"; auto type_id = node_wrapper.get_typeid(); NGRAPH_CHECK(type_id == OP_TYPEID::Relu || type_id == OP_TYPEID::BoundedRelu, "only support relu / bounded relu"); const Node& node = *node_wrapper.get_node(); bool verbose = verbose_op(node); size_t element_count = arg->data().size(); size_t smallest_ind = match_to_smallest_chain_index(arg->data(), m_he_seal_backend); if (verbose) { NGRAPH_HE_LOG(3) << "Matched moduli to chain ind " << smallest_ind; } m_relu_data.resize(element_count, HEType(HEPlaintext(), false)); // TODO(fboemer): tune const size_t max_relu_message_cnt = 1000; m_unknown_relu_idx.clear(); m_unknown_relu_idx.reserve(element_count); // Process known values for (size_t relu_idx = 0; relu_idx < element_count; ++relu_idx) { auto& he_type = arg->data(relu_idx); if (he_type.is_plaintext()) { m_relu_data[relu_idx].set_plaintext(HEPlaintext()); if (type_id == OP_TYPEID::Relu) { scalar_relu_seal(he_type.get_plaintext(), m_relu_data[relu_idx].get_plaintext()); } else { const auto* bounded_relu = static_cast<const op::BoundedRelu*>(&node); float alpha = bounded_relu->get_alpha(); scalar_bounded_relu_seal(he_type.get_plaintext(), m_relu_data[relu_idx].get_plaintext(), alpha); } } else { m_unknown_relu_idx.emplace_back(relu_idx); } } auto process_unknown_relu_ciphers_batch = [&](const std::vector<HEType>& cipher_batch) { if (verbose) { NGRAPH_HE_LOG(3) << "Sending relu request size " << cipher_batch.size(); } // TODO(fboemer): set complex_packing to correct values? HETensor relu_tensor( arg->get_element_type(), Shape{cipher_batch[0].batch_size(), cipher_batch.size()}, arg->is_packed(), false, true, m_he_seal_backend); relu_tensor.data() = cipher_batch; std::vector<pb::HETensor> proto_tensors; relu_tensor.write_to_protos(proto_tensors); for (const auto& proto_tensor : proto_tensors) { pb::TCPMessage proto_msg; proto_msg.set_type(pb::TCPMessage_Type_REQUEST); // TODO(fboemer): factor out serializing the function json js = {{"function", node.description()}}; if (type_id == OP_TYPEID::BoundedRelu) { const auto* bounded_relu = static_cast<const op::BoundedRelu*>(&node); float alpha = bounded_relu->get_alpha(); js["bound"] = alpha; } pb::Function f; f.set_function(js.dump()); *proto_msg.mutable_function() = f; *proto_msg.add_he_tensors() = proto_tensor; TCPMessage relu_message(std::move(proto_msg)); NGRAPH_HE_LOG(5) << "Server writing relu request message"; m_session->write_message(std::move(relu_message)); } }; // Process unknown values std::vector<HEType> relu_ciphers_batch; relu_ciphers_batch.reserve(max_relu_message_cnt); for (const auto& unknown_relu_idx : m_unknown_relu_idx) { NGRAPH_CHECK(arg->data(unknown_relu_idx).is_ciphertext(), "HEType should be ciphertext"); relu_ciphers_batch.emplace_back(arg->data(unknown_relu_idx)); if (relu_ciphers_batch.size() == max_relu_message_cnt) { process_unknown_relu_ciphers_batch(relu_ciphers_batch); relu_ciphers_batch.clear(); } } if (!relu_ciphers_batch.empty()) { process_unknown_relu_ciphers_batch(relu_ciphers_batch); relu_ciphers_batch.clear(); } // Wait until all batches have been processed std::unique_lock<std::mutex> mlock(m_relu_mutex); m_relu_cond.wait( mlock, [=]() { return m_relu_done_count == m_unknown_relu_idx.size(); }); m_relu_done_count = 0; out->data() = m_relu_data; } } // namespace ngraph::he
37.20475
80
0.637695
kthur
57a0b08ba6a9ba9643a36831c20cf301d4ff07f3
2,271
cpp
C++
leetcode/30_days_challenge/2021_4_April/7.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
1
2020-05-05T13:06:51.000Z
2020-05-05T13:06:51.000Z
leetcode/30_days_challenge/2021_4_April/7.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
null
null
null
leetcode/30_days_challenge/2021_4_April/7.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
null
null
null
/**************************************************** Date: April 7th link: https://leetcode.com/explore/challenge/card/april-leetcoding-challenge-2021/593/week-1-april-1st-april-7th/3693/ ****************************************************/ #include <iostream> #include <vector> #include <list> #include <algorithm> #include <string> #include <stack> #include <queue> #include <map> #include <unordered_map> #include <unordered_set> #include <cmath> #include <limits.h> using namespace std; /* Q: Determine if String Halves Are Alike You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters. Return true if a and b are alike. Otherwise, return false. Example 1: Input: s = "book" Output: true Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike. Example 2: Input: s = "textbook" Output: false Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. Example 3: Input: s = "MerryChristmas" Output: false Example 4: Input: s = "AbCdEfGh" Output: true Constraints: 2 <= s.length <= 1000 s.length is even. s consists of uppercase and lowercase letters. Hide Hint #1 Create a function that checks if a character is a vowel, either uppercase or lowercase. */ class Solution { private: bool isVoWel(char& ch) { switch(ch) { case 'a': case 'e': case 'i': case 'o': case 'u': case 'A': case 'E': case 'I': case 'O': case 'U': return true; } return false; } public: bool halvesAreAlike(string s) { int aCount = 0; int bCount = 0; int l = s.size(); for(int i = 0; i < l/2; ++i) { aCount = (isVoWel(s[i]) == true) ? aCount + 1 : aCount; bCount = (isVoWel(s[l-1-i]) == true) ? bCount + 1 : bCount; } return (aCount == bCount); } };
23.65625
170
0.57904
bvbasavaraju
57a0ee1b47f069211df1651b1d1c99c108f8c219
374
cpp
C++
Unlocker/src/platforms/uplay_r1/UplayR1.cpp
Lasssst/LXS
69562bf6c0e3f12fd05ae887df7ec0f65b80e340
[ "0BSD" ]
253
2021-03-12T15:11:27.000Z
2022-03-31T04:32:47.000Z
Unlocker/src/platforms/uplay_r1/UplayR1.cpp
Lasssst/LXS
69562bf6c0e3f12fd05ae887df7ec0f65b80e340
[ "0BSD" ]
8
2021-03-14T00:35:44.000Z
2022-03-24T21:58:13.000Z
Unlocker/src/platforms/uplay_r1/UplayR1.cpp
Lasssst/LXS
69562bf6c0e3f12fd05ae887df7ec0f65b80e340
[ "0BSD" ]
36
2021-03-29T20:43:21.000Z
2022-03-20T14:22:16.000Z
#include "pch.h" #include "UplayR1.h" #include "uplay_r1_hooks.h" #include "constants.h" #define HOOK(FUNC) installDetourHook(FUNC, #FUNC); void UplayR1::platformInit() { HOOK(UPLAY_USER_IsOwned); } string UplayR1::getPlatformName() { return UBISOFT_NAME; } LPCWSTR UplayR1::getModuleName() { return UPLAY_R1; } Hooks& UplayR1::getPlatformHooks() { return hooks; }
13.851852
50
0.735294
Lasssst
57a33110504aa5ec35e692213f6e5ce185c9d7d9
6,362
hpp
C++
modules/boost/simd/sdk/include/boost/simd/memory/functions/scalar/store.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/boost/simd/sdk/include/boost/simd/memory/functions/scalar/store.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/sdk/include/boost/simd/memory/functions/scalar/store.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // Copyright 2011 - 2012 MetaScale SAS // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_SIMD_MEMORY_FUNCTIONS_SCALAR_STORE_HPP_INCLUDED #define BOOST_SIMD_MEMORY_FUNCTIONS_SCALAR_STORE_HPP_INCLUDED #include <boost/simd/memory/functions/store.hpp> #include <boost/simd/sdk/functor/preprocessor/dispatch.hpp> #include <boost/simd/memory/functions/details/store.hpp> #include <boost/simd/memory/iterator_category.hpp> #include <boost/simd/sdk/meta/iterate.hpp> #include <boost/simd/sdk/simd/meta/is_native.hpp> #include <boost/mpl/not.hpp> namespace boost { namespace simd { namespace ext { /// INTERNAL ONLY - Scalar store and store are equivalent BOOST_DISPATCH_IMPLEMENT ( store_ , tag::cpu_ , (A0)(A1)(A2) , (unspecified_<A0>) (iterator_< unspecified_<A1> >) (scalar_< integer_<A2> >) ) { typedef void result_type; BOOST_FORCEINLINE result_type operator()(A0 const& a0, A1 a1, A2 a2) const { *(a1+a2) = a0; } }; /// INTERNAL ONLY - Scalar store and store are equivalent BOOST_DISPATCH_IMPLEMENT ( store_ , tag::cpu_ , (A0)(A1) , (unspecified_<A0>) (iterator_< unspecified_<A1> >) ) { typedef void result_type; BOOST_FORCEINLINE result_type operator()(A0 const& a0, A1 a1) const { *a1 = a0; } }; /// INTERNAL ONLY - scalar masked store BOOST_DISPATCH_IMPLEMENT ( store_ , tag::cpu_ , (A0)(A1)(A2) , (unspecified_<A0>) (iterator_< unspecified_<A1> >) (scalar_< fundamental_<A2> >) ) { typedef void result_type; BOOST_FORCEINLINE result_type operator()(A0 const& a0, A1 a1, A2 const& a2) const { if (a2) *a1 = a0; } }; /// INTERNAL ONLY - Scalar masked offset store BOOST_DISPATCH_IMPLEMENT ( store_ , tag::cpu_ , (A0)(A1)(A2)(A3) , (unspecified_<A0>) (iterator_< unspecified_<A1> >) (scalar_< integer_<A2> >) (scalar_< fundamental_<A3> >) ) { typedef void result_type; BOOST_FORCEINLINE result_type operator()(A0 const& a0, A1 a1, A2 a2, A3 const& a3) const { if (a3) *(a1+a2) = a0; } }; /// INTERNAL ONLY - Fusion sequence store with offset BOOST_DISPATCH_IMPLEMENT ( store_ , tag::cpu_ , (A0)(A1)(A2) , (fusion_sequence_<A0>) (fusion_sequence_<A1>) (generic_< integer_<A2> >) ) { typedef void result_type; BOOST_FORCEINLINE result_type operator()(A0 const& a0, A1 const& a1, A2 a2) const { meta::iterate < fusion::result_of::size<A1>::type::value> ( details::storer < boost::simd:: tag::store_(A0, A1, A2) >(a0, a1, a2) ); } }; /// INTERNAL ONLY - Scalar store and store are equivalent BOOST_DISPATCH_IMPLEMENT ( store_ , tag::cpu_ , (A0)(A1) , (fusion_sequence_<A0>) (fusion_sequence_<A1>) ) { typedef void result_type; BOOST_FORCEINLINE result_type operator()(A0 const& a0, A1 const& a1) const { meta::iterate < fusion::result_of::size<A1>::type::value> ( details::storer < boost::simd:: tag::store_(A0, A1) >(a0, a1) ); } }; /// Handles store( seq, seq'*) BOOST_DISPATCH_IMPLEMENT_IF ( store_ , tag::cpu_ , (A0)(A1) , (mpl::not_< simd::meta::is_native<A0> >) , (fusion_sequence_<A0>) (iterator_< fusion_sequence_<A1> >) ) { typedef void result_type; BOOST_SIMD_FUNCTOR_CALL(2) { static const int N = fusion::result_of::size<A0>::type::value; meta::iterate<N>( details::extractor<A0,A1>(a0,a1) ); } }; BOOST_DISPATCH_IMPLEMENT_IF ( store_ , tag::cpu_ , (A0)(A1)(A2) , (mpl::not_< simd::meta::is_native<A0> >) , (fusion_sequence_<A0>) (iterator_< fusion_sequence_<A1> >) (scalar_< integer_<A2> >) ) { typedef void result_type; BOOST_SIMD_FUNCTOR_CALL(3) { static const int N = fusion::result_of::size<A0>::type::value; meta::iterate<N>( details::extractor<A0,A1,A2>(a0,a1,a2) ); } }; } } } #endif
36.563218
85
0.422351
psiha
57ac4980533307774f4a739f7ad73f57ed2e0258
731
hpp
C++
pythran/pythonic/numpy/ndarray/tostring.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/ndarray/tostring.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/ndarray/tostring.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_NUMPY_NDARRAY_TOSTRING_HPP #define PYTHONIC_NUMPY_NDARRAY_TOSTRING_HPP #include "pythonic/include/numpy/ndarray/tostring.hpp" #include "pythonic/utils/proxy.hpp" #include "pythonic/utils/numpy_conversion.hpp" #include "pythonic/types/ndarray.hpp" #include "pythonic/types/str.hpp" namespace pythonic { namespace numpy { namespace ndarray { template <class T, size_t N> types::str tostring(types::ndarray<T, N> const &expr) { return types::str(reinterpret_cast<const char *>(expr.buffer), expr.flat_size() * sizeof(T)); } NUMPY_EXPR_TO_NDARRAY0_IMPL(tostring); PROXY_IMPL(pythonic::numpy::ndarray, tostring); } } } #endif
23.580645
70
0.689466
artas360
57af5f4b0162c9293409173576789a4295346b24
1,035
cpp
C++
Src/AlGlobals.cpp
Remag/GraphicsInversed
6dff72130891010774c37d1e44080261db3cdb8e
[ "MIT" ]
null
null
null
Src/AlGlobals.cpp
Remag/GraphicsInversed
6dff72130891010774c37d1e44080261db3cdb8e
[ "MIT" ]
null
null
null
Src/AlGlobals.cpp
Remag/GraphicsInversed
6dff72130891010774c37d1e44080261db3cdb8e
[ "MIT" ]
null
null
null
#include <common.h> #pragma hdrstop #ifndef GIN_NO_AUDIO #include <AlGlobals.h> #include <AlContextManager.h> #include <GinGlobals.h> #include <MainFrame.h> #include <AudioSequence.h> namespace Gin { namespace Audio { ////////////////////////////////////////////////////////////////////////// CAudioListener& GetAudioListener() { return *CAudioListener::GetInstance(); } GINAPI CVector3<float> GetListenerPos() { return GetAudioListener().GetPos(); } CAlContextManager& GetAudioContextManager() { return GinInternal::GetMainFrame().AlContextManager(); } void StopAllSounds() { GetAudioContextManager().StopAllRecords(); } CAudioRecord PlaySound( CSoundView seq, CVector3<float> pos, CVector3<float> velocity, bool isLooping, TSourcePriority priority ) { return GetAudioContextManager().CreateRecord( seq, priority, pos, velocity, isLooping ); } ////////////////////////////////////////////////////////////////////////// } // namespace Audio. } // namespace Gin. #endif
21.122449
130
0.614493
Remag
57b20ea2705d5995d202727a6fd4f489a204274b
1,020
hpp
C++
src/exceptions.hpp
tretre91/ccalc
3e13365855018314b798287967a978f4951783da
[ "Zlib" ]
null
null
null
src/exceptions.hpp
tretre91/ccalc
3e13365855018314b798287967a978f4951783da
[ "Zlib" ]
null
null
null
src/exceptions.hpp
tretre91/ccalc
3e13365855018314b798287967a978f4951783da
[ "Zlib" ]
null
null
null
#ifndef EXCEPTIONS_HPP #define EXCEPTIONS_HPP #include <stdexcept> namespace ccalc { /** * @brief Base class for ccalc exceptions */ class Exception : public std::runtime_error { public: Exception(const char* desc) : runtime_error(desc) {} Exception(const std::string& desc) : runtime_error(desc) {} }; /** * @brief Exception thrown when an identifier (function or variable name) is undefined */ class UndefinedIdentifier : public Exception { public: UndefinedIdentifier(const char* desc) : Exception(desc) {} UndefinedIdentifier(const std::string& desc) : Exception(desc) {} }; /** * @brief Exception thrown when an argument to a function call is invalid */ class InvalidArgument : public Exception { public: InvalidArgument(const char* desc) : Exception(desc) {} InvalidArgument(const std::string& desc) : Exception(desc) {} }; } // namespace ccalc #endif // !EXCEPTIONS_HPP
25.5
90
0.642157
tretre91
57b2c508f63619b3fa2a11565e66d56f6cd2a74b
10,369
cpp
C++
packages/python/pyfora/src/pyobjectwalkermodule.cpp
ufora/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
571
2015-11-05T20:07:07.000Z
2022-01-24T22:31:09.000Z
packages/python/pyfora/src/pyobjectwalkermodule.cpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
218
2015-11-05T20:37:55.000Z
2021-05-30T03:53:50.000Z
packages/python/pyfora/src/pyobjectwalkermodule.cpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
40
2015-11-07T21:42:19.000Z
2021-05-23T03:48:19.000Z
/*************************************************************************** Copyright 2016 Ufora Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************************/ #include <Python.h> #include <structmember.h> #include "PyBinaryObjectRegistry.hpp" #include "PyObjectUtils.hpp" #include "PyObjectWalker.hpp" #include "UnresolvedFreeVariableExceptions.hpp" #include "core/PyObjectPtr.hpp" #include "core/variant.hpp" #include "exceptions/PyforaErrors.hpp" #include <stdexcept> #include <stdint.h> /********************************* Defining a Python C-extension for the C++ class PyObjectWalker, from PyObjectWalker.hpp cribbed off https://docs.python.org/2.7/extending/newtypes.html **********************************/ typedef struct { PyObject_HEAD PyObject* binaryObjectRegistry; PyObjectWalker* nativePyObjectWalker; } PyObjectWalkerStruct; extern "C" { static PyObject* PyObjectWalkerStruct_new(PyTypeObject* type, PyObject* args, PyObject* kwds) { PyObjectWalkerStruct* self; self = (PyObjectWalkerStruct*)type->tp_alloc(type, 0); self->binaryObjectRegistry = nullptr; self->nativePyObjectWalker = nullptr; return (PyObject*) self; } static void PyObjectWalkerStruct_dealloc(PyObjectWalkerStruct* self) { Py_XDECREF(self->binaryObjectRegistry); delete self->nativePyObjectWalker; self->ob_type->tp_free((PyObject*)self); } static int PyObjectWalkerStruct_init(PyObjectWalkerStruct* self, PyObject* args, PyObject* kwds) { PyObjectPtr binaryObjectRegistryModule = PyObjectPtr::unincremented( PyImport_ImportModule("pyfora.BinaryObjectRegistry")); if (binaryObjectRegistryModule == nullptr) { return -1; } PyObjectPtr binaryObjectRegistryClass = PyObjectPtr::unincremented( PyObject_GetAttrString(binaryObjectRegistryModule.get(), "BinaryObjectRegistry") ); if (binaryObjectRegistryClass == nullptr) { return -1; } PyObject* purePythonClassMapping; if (!PyArg_ParseTuple(args, "OO!", &purePythonClassMapping, binaryObjectRegistryClass.get(), &self->binaryObjectRegistry)) { return -1; } Py_INCREF(self->binaryObjectRegistry); PyObjectPtr pyObjectWalkerDefaultsModule = PyObjectPtr::unincremented( PyImport_ImportModule("pyfora.PyObjectWalkerDefaults")); if (pyObjectWalkerDefaultsModule == nullptr) { return -1; } PyObjectPtr excludePredicateFun = PyObjectPtr::unincremented( PyObject_GetAttrString( pyObjectWalkerDefaultsModule.get(), "exclude_predicate_fun")); if (excludePredicateFun == nullptr) { return -1; } PyObjectPtr excludeList = PyObjectPtr::unincremented( PyObject_GetAttrString( pyObjectWalkerDefaultsModule.get(), "exclude_list")); if (excludeList == nullptr) { return -1; } PyObjectPtr terminalValueFilter = PyObjectPtr::unincremented( PyObject_GetAttrString( pyObjectWalkerDefaultsModule.get(), "terminal_value_filter")); if (terminalValueFilter == nullptr) { return -1; } PyObjectPtr traceback_type = PyObjectPtr::unincremented( PyObject_GetAttrString( pyObjectWalkerDefaultsModule.get(), "traceback_type")); if (traceback_type == nullptr) { return -1; } PyObjectPtr pythonTracebackToJsonFun = PyObjectPtr::unincremented( PyObject_GetAttrString( pyObjectWalkerDefaultsModule.get(), "pythonTracebackToJson")); if (pythonTracebackToJsonFun == nullptr) { return -1; } try { self->nativePyObjectWalker = new PyObjectWalker( PyObjectPtr::incremented(purePythonClassMapping), *(((PyBinaryObjectRegistry*)(self->binaryObjectRegistry))->nativeBinaryObjectRegistry), excludePredicateFun, excludeList, terminalValueFilter, traceback_type, pythonTracebackToJsonFun ); } catch (const std::runtime_error& e) { std::string err = std::string("error creating a PyObjectWalker: ") + e.what(); PyErr_SetString( PyExc_RuntimeError, err.c_str() ); return -1; } catch (const std::exception& e) { std::string err = std::string("error creating a PyObjectWalker: ") + e.what(); PyErr_SetString( PyExc_Exception, err.c_str() ); return -1; } return 0; } static PyObject* PyObjectWalkerStruct_walkPyObject(PyObjectWalkerStruct* self, PyObject* args) { PyObject* objToWalk; if (!PyArg_ParseTuple(args, "O", &objToWalk)) { return nullptr; } variant<int64_t, std::shared_ptr<PyforaError>> objectIdOrErr; try { objectIdOrErr = self->nativePyObjectWalker->walkPyObject(objToWalk); } catch (const UnresolvedFreeVariableExceptionWithTrace& e) { e.setPyErr(); return nullptr; } catch (const BadWithBlockError& e) { e.setPyErr(); return nullptr; } catch (const PythonToForaConversionError& e) { e.setPyErr(); return nullptr; } catch (const std::runtime_error& e) { PyErr_SetString( PyExc_RuntimeError, e.what() ); return nullptr; } catch (const std::exception& e) { PyErr_SetString( PyExc_Exception, e.what() ); return nullptr; } if (objectIdOrErr.is<int64_t>()) { return PyInt_FromLong(objectIdOrErr.get<int64_t>()); } else { objectIdOrErr.get<std::shared_ptr<PyforaError>>()->setPyErr(); return nullptr; } } } // extern "C" static PyMethodDef PyObjectWalkerStruct_methods[] = { {"walkPyObject", (PyCFunction)PyObjectWalkerStruct_walkPyObject, METH_VARARGS, "walk a python object"}, {nullptr} }; // it seems silly that the name attr in a PyMemberDef isn't a const char* // AFAIK, it's never modified by python static PyMemberDef PyObjectWalkerStruct_members[] = { {const_cast<char*>("objectRegistry"), T_OBJECT_EX, offsetof(PyObjectWalkerStruct, binaryObjectRegistry), 0, const_cast<char*>("object registry attribute")}, {nullptr} }; static PyTypeObject PyObjectWalkerStructType = { PyObject_HEAD_INIT(nullptr) 0, /* ob_size */ "PyObjectWalker.PyObjectWalker", /* tp_name */ sizeof(PyObjectWalkerStruct), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)PyObjectWalkerStruct_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "PyObjectWalker objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ PyObjectWalkerStruct_methods, /* tp_methods */ PyObjectWalkerStruct_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)PyObjectWalkerStruct_init, /* tp_init */ 0, /* tp_alloc */ PyObjectWalkerStruct_new, /* tp_new */ }; static PyMethodDef module_methods[] = { {nullptr} }; #ifndef PyMODINIT_FUNC/* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif extern "C" { PyMODINIT_FUNC initPyObjectWalker(void) { PyObject* m; if (PyType_Ready(&PyObjectWalkerStructType) < 0) return; m = Py_InitModule3("PyObjectWalker", module_methods, "expose PyObjectWalker C++ class"); if (m == nullptr) { return; } Py_INCREF(&PyObjectWalkerStructType); PyModule_AddObject( m, "PyObjectWalker", (PyObject*)&PyObjectWalkerStructType); } } // extern "C"
32.201863
99
0.539107
ufora
57b62315fe673e3bee9302ad827411f96e2953c2
3,559
cpp
C++
src/game/system/movement.cpp
jprochazk/platformer-server
d38eb5d8a22a1275c307d68742d288622750e0a4
[ "Unlicense" ]
1
2020-07-17T17:26:45.000Z
2020-07-17T17:26:45.000Z
src/game/system/movement.cpp
jprochazk/platformer-server
d38eb5d8a22a1275c307d68742d288622750e0a4
[ "Unlicense" ]
null
null
null
src/game/system/movement.cpp
jprochazk/platformer-server
d38eb5d8a22a1275c307d68742d288622750e0a4
[ "Unlicense" ]
null
null
null
#include "game/system/movement.h" #include "common/log.h" #include "game/collision.h" #include "game/component.h" #include "game/event.h" #include "game/world.h" namespace game { namespace system { movement::movement(std::shared_ptr<game::world> world) : world(world) { INFO("MOVEMENT", "Initialized"); } void movement::update() { // INFO("MOVEMENT", "Update"); auto& map = world->get_map(); auto& registry = world->get_registry(); using namespace component; registry.view<input, body>().each([&](const entt::entity&, const input& input, body& body) { if (body.mtype == body::mtype::WALK) { // jump state machine if (body.jump == body::jump_state::NONE) { body.vel.x = 0.0; if (input.left) body.vel.x += -body.speed; if (input.right) body.vel.x += body.speed; if (input.up) { body.vel.y = -body.jump_velocity; body.jump = body::jump_state::MID; } } else if (body.jump == body::jump_state::MID) { if (!input.up) { body.jump = body::jump_state::SINGLE; } } else if (body.jump == body::jump_state::SINGLE) { if (input.up) { body.vel.x = 0.0; if (input.left) body.vel.x += -body.speed; if (input.right) body.vel.x += body.speed; body.vel.y = -body.jump_velocity; body.jump = body::jump_state::DOUBLE; } } } else if (body.mtype == body::mtype::FLY) { body.vel.x = 0.0; body.vel.y = 0.0; if (input.left) body.vel.x -= body.speed; if (input.right) body.vel.x += body.speed; if (input.up) body.vel.y -= body.speed; if (input.down) body.vel.y += body.speed; } }); registry.view<body>().each([&](const entt::entity&, body& body) { body.lastPos = body.pos; body.pos += body.vel; }); registry.view<body, collider>().each([&](const entt::entity& e, body& body, collider& col) { using namespace collision; if (body.mtype == body::mtype::WALK) { body.vel.y += body.gravity; body.vel.y = glm::min(body.vel.y, body.gravity * 15); } col.box.center = body.pos; auto& zone = map.get_zone(e); // check against zone bounds auto bounds = zone.get_bounds(); auto min = col.box.center - col.box.half; auto max = col.box.center + col.box.half; if (min.x < 0) col.box.center.x = col.box.half.x; if (min.y < 0) col.box.center.y = col.box.half.y; if (max.x > bounds.x) col.box.center.x = bounds.x - col.box.half.x; if (max.y > bounds.y) { col.box.center.y = bounds.y - col.box.half.y; body.jump = body::jump_state::NONE; } // check against zone objects for (auto& object : zone.get_objects()) { auto result = hit(col.box, object); if (result.normal.y == -1) { body.jump = body::jump_state::NONE; } col.box.center -= result.pen; } body.pos = col.box.center; }); } } // namespace system } // namespace game
30.161017
96
0.483282
jprochazk
57b722e0ec46d73a63ea117dbbe5e458d8262888
208
cc
C++
tests/option_extra_delim_spec_split_test.cc
tegtmeye/cmd_options
03f2644e57413b38074545867ca539019201349e
[ "BSD-3-Clause" ]
null
null
null
tests/option_extra_delim_spec_split_test.cc
tegtmeye/cmd_options
03f2644e57413b38074545867ca539019201349e
[ "BSD-3-Clause" ]
null
null
null
tests/option_extra_delim_spec_split_test.cc
tegtmeye/cmd_options
03f2644e57413b38074545867ca539019201349e
[ "BSD-3-Clause" ]
null
null
null
#include "cmd_options.h" #include "test_detail.h" namespace co = cmd_options; int main(void) { co::split_opt_spec<detail::check_char_t>( _LIT("foo,f,key,"),detail::check_char_t(',')); return 0; }
14.857143
50
0.677885
tegtmeye
57b9150404cf445033791389fe7e87a0f65f6a34
277
cpp
C++
src/NullLoggingSink.cpp
Ishiko-Cpp/Logging
0de7ed435bb1ad4ae38a306ec3ecb2c166d6539d
[ "MIT" ]
null
null
null
src/NullLoggingSink.cpp
Ishiko-Cpp/Logging
0de7ed435bb1ad4ae38a306ec3ecb2c166d6539d
[ "MIT" ]
1
2021-09-18T23:30:27.000Z
2021-09-18T23:30:27.000Z
src/NullLoggingSink.cpp
ishiko-cpp/logging
0de7ed435bb1ad4ae38a306ec3ecb2c166d6539d
[ "MIT" ]
null
null
null
/* Copyright (c) 2022 Xavier Leclercq Released under the MIT License See https://github.com/ishiko-cpp/logging/blob/main/LICENSE.txt */ #include "NullLoggingSink.hpp" using namespace Ishiko; void NullLoggingSink::send(const Record& record) { // Do nothing }
18.466667
67
0.718412
Ishiko-Cpp
57b9b4e7fb4123866124921a2c0d664017db3cf3
767
cpp
C++
UVaOnlineJudge/Contest_Volumes(10000...)/Volume119(11900-11999)/11909/code.cpp
luiscbr92/algorithmic-challenges
bc35729e54e4284e9ade1aa61b51a1c2d72aa62c
[ "MIT" ]
3
2015-10-21T18:56:43.000Z
2017-06-06T10:44:22.000Z
UVaOnlineJudge/Contest_Volumes(10000...)/Volume119(11900-11999)/11909/code.cpp
luiscbr92/algorithmic-challenges
bc35729e54e4284e9ade1aa61b51a1c2d72aa62c
[ "MIT" ]
null
null
null
UVaOnlineJudge/Contest_Volumes(10000...)/Volume119(11900-11999)/11909/code.cpp
luiscbr92/algorithmic-challenges
bc35729e54e4284e9ade1aa61b51a1c2d72aa62c
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> using namespace std; int main(){ ios_base::sync_with_stdio (false); int length, width, height, theta; double areaA, areaB, projA, projB, volume, rad; double pi = 3.1415926535897; while(cin >> length >> width >> height >> theta){ if(theta > 0){ rad = theta * pi / 180.0; projA = height / tan(rad); projB = length * tan(rad); areaA = (projA * height) /2; areaB = (projB * length) /2; if(areaA > areaB) volume = (length * width * height) - (areaB * width); else volume = areaA * width; } else volume = length * width * height; printf("%.3f mL\n", volume); } return 0; }
23.242424
85
0.517601
luiscbr92
57bb500ec313f9b1b03505fb5922a63a90132ef6
635
hpp
C++
src/libmqtt-to-influxdb/datatype.hpp
DavidHamburg/mqtt-to-influxdb
5a306f1186433c7ee426959a53ea575c03d9a4a1
[ "MIT" ]
null
null
null
src/libmqtt-to-influxdb/datatype.hpp
DavidHamburg/mqtt-to-influxdb
5a306f1186433c7ee426959a53ea575c03d9a4a1
[ "MIT" ]
null
null
null
src/libmqtt-to-influxdb/datatype.hpp
DavidHamburg/mqtt-to-influxdb
5a306f1186433c7ee426959a53ea575c03d9a4a1
[ "MIT" ]
null
null
null
#pragma once #include <ostream> enum class datatype { string_type, boolean_type, integer_type, float_type }; inline std::ostream& operator << (std::ostream& os, const datatype& obj) { switch (obj) { case datatype::string_type: os << "string"; break; case datatype::boolean_type: os << "bool"; break; case datatype::integer_type: os << "int"; break; case datatype::float_type: os << "float"; break; default: os << "unknown data type"; break; } return os; }
21.166667
72
0.508661
DavidHamburg
57c04a10a9558cd5600cdd501b7321f6ce0d479b
425
cpp
C++
utility/utils.cpp
gurpinars/virtnd
bdf1f2bc2ae137117c75bfa75bde0813811a396f
[ "MIT" ]
1
2021-04-21T09:54:07.000Z
2021-04-21T09:54:07.000Z
utility/utils.cpp
gurpinars/virtnd
bdf1f2bc2ae137117c75bfa75bde0813811a396f
[ "MIT" ]
null
null
null
utility/utils.cpp
gurpinars/virtnd
bdf1f2bc2ae137117c75bfa75bde0813811a396f
[ "MIT" ]
null
null
null
#include <cstdint> #include <arpa/inet.h> #include <cstdio> #include <cstdlib> #include "utils.h" uint32_t inet_bf(const char *addr) { struct in_addr ia{}; if (inet_pton(AF_INET, addr, &ia) != 1) { perror("inet binary formatting failed"); exit(1); } return ntohl(ia.s_addr); } std::string inet_pf(uint32_t addr) { struct in_addr ia{}; ia.s_addr = addr; return inet_ntoa(ia); }
18.478261
48
0.625882
gurpinars
57c213f4d63620c34410ed50687ac2286129122b
71
inl
C++
plugins/gameplay/first_person/localizer_table.inl
geekrelief/sample-projects
51222521fa0821596c9434a4ae8ed96ddc00e88e
[ "CC-BY-4.0", "CC-BY-3.0", "CC0-1.0" ]
4
2021-09-10T13:37:43.000Z
2022-01-08T03:17:30.000Z
plugins/gameplay/first_person/localizer_table.inl
geekrelief/sample-projects
51222521fa0821596c9434a4ae8ed96ddc00e88e
[ "CC-BY-4.0", "CC-BY-3.0", "CC0-1.0" ]
2
2021-10-05T00:56:41.000Z
2022-01-10T12:08:07.000Z
plugins/gameplay/first_person/localizer_table.inl
geekrelief/sample-projects
51222521fa0821596c9434a4ae8ed96ddc00e88e
[ "CC-BY-4.0", "CC-BY-3.0", "CC0-1.0" ]
2
2021-08-17T11:58:10.000Z
2021-09-11T12:47:16.000Z
{0}, { .english = "Gameplay Sample First Person", .swedish = "" },
23.666667
65
0.56338
geekrelief
57c3dde224a2f11ebf3de24883b748b07d1603bb
2,595
cpp
C++
source/mango/image/image_jpg.cpp
heiligeslama/mango
6528e151fa70c1b02871f1e7972e6c162c945350
[ "Zlib" ]
null
null
null
source/mango/image/image_jpg.cpp
heiligeslama/mango
6528e151fa70c1b02871f1e7972e6c162c945350
[ "Zlib" ]
null
null
null
source/mango/image/image_jpg.cpp
heiligeslama/mango
6528e151fa70c1b02871f1e7972e6c162c945350
[ "Zlib" ]
null
null
null
/* MANGO Multimedia Development Platform Copyright (C) 2012-2018 Twilight Finland 3D Oy Ltd. All rights reserved. */ #include <mango/core/core.hpp> #include <mango/image/image.hpp> #include "../jpeg/jpeg.hpp" #define ID "ImageDecoder.JPG: " namespace { using namespace mango; // ------------------------------------------------------------ // ImageDecoder // ------------------------------------------------------------ struct Interface : ImageDecoderInterface { jpeg::Parser m_parser; Interface(Memory memory) : m_parser(memory) { } ~Interface() { } ImageHeader header() override { ImageHeader header; header.width = m_parser.header.width; header.height = m_parser.header.height; header.depth = 0; header.levels = 0; header.faces = 0; header.palette = false; header.format = m_parser.header.format; header.compression = TextureCompression::NONE; return header; } Exif exif() override { if (m_parser.exif_memory.address) { return Exif(m_parser.exif_memory); } return Exif(); } void decode(Surface& dest, Palette* palette, int level, int depth, int face) override { MANGO_UNREFERENCED_PARAMETER(palette); MANGO_UNREFERENCED_PARAMETER(level); MANGO_UNREFERENCED_PARAMETER(depth); MANGO_UNREFERENCED_PARAMETER(face); jpeg::Status s = m_parser.decode(dest); MANGO_UNREFERENCED_PARAMETER(s); } }; ImageDecoderInterface* createInterface(Memory memory) { ImageDecoderInterface* x = new Interface(memory); return x; } // ------------------------------------------------------------ // ImageEncoder // ------------------------------------------------------------ void imageEncode(Stream& stream, const Surface& surface, float quality) { jpeg::EncodeImage(stream, surface, quality); } } // namespace namespace mango { void registerImageDecoderJPG() { registerImageDecoder(createInterface, "jpg"); registerImageDecoder(createInterface, "jpeg"); registerImageDecoder(createInterface, "jfif"); registerImageDecoder(createInterface, "mpo"); registerImageEncoder(imageEncode, "jpg"); registerImageEncoder(imageEncode, "jpeg"); } } // namespace mango
25.441176
93
0.534489
heiligeslama
57c4a95193f094ea4e2cfb0fae12552bd26a4ce5
250
cpp
C++
Software/1Motor_refactor/src/utils.cpp
mx-robotics/motor_control_delete_me
fc538475af136f2cbf540d33605b425cf4b0a734
[ "BSD-2-Clause" ]
null
null
null
Software/1Motor_refactor/src/utils.cpp
mx-robotics/motor_control_delete_me
fc538475af136f2cbf540d33605b425cf4b0a734
[ "BSD-2-Clause" ]
null
null
null
Software/1Motor_refactor/src/utils.cpp
mx-robotics/motor_control_delete_me
fc538475af136f2cbf540d33605b425cf4b0a734
[ "BSD-2-Clause" ]
null
null
null
// // Created by firat on 25.01.20. // #include "utils.h" uint16_t utils::plot_counter=0; /* * @TODO : add a serial interface to send data for debugging * @TODO : -> plotting * @TODO : -> simple send -> wrap em up in a class * * * * * * */
14.705882
60
0.592
mx-robotics
57c8237fc7fd5bab1a6e597b25385cab554956f7
3,614
cpp
C++
CAPI/Communication/src/Communication.cpp
Timothy-LiuXuefeng/THUAI5
499232aaa05bccf752fc886810686d0a4a825bf8
[ "MIT" ]
1
2021-09-28T11:01:16.000Z
2021-09-28T11:01:16.000Z
CAPI/Communication/src/Communication.cpp
Timothy-LiuXuefeng/THUAI5
499232aaa05bccf752fc886810686d0a4a825bf8
[ "MIT" ]
null
null
null
CAPI/Communication/src/Communication.cpp
Timothy-LiuXuefeng/THUAI5
499232aaa05bccf752fc886810686d0a4a825bf8
[ "MIT" ]
null
null
null
#include "../include/Communication.h" #include <iostream> #include <thread> #include <chrono> EnHandleResult ClientCommunication::OnConnect(ITcpClient* pSender, CONNID dwConnID) { comm.OnConnect(); return HR_OK; } EnHandleResult ClientCommunication::OnReceive(ITcpClient* pSender, CONNID dwConnID, const BYTE* pData, int iLength) { pointer_m2c pm2c = GameMessage::Deserialize(pData, iLength); comm.OnReceive(std::move(pm2c)); return HR_OK; } EnHandleResult ClientCommunication::OnClose(ITcpClient* pSender, CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode) { comm.OnClose(); return HR_OK; } bool ClientCommunication::Connect(const char* address, uint16_t port) { std::cout << "Connecting......" << std::endl; while (!pclient->IsConnected()) { if (!pclient->Start(address,port)) { std::cerr << "Failed to connect with the server" << std::endl; return false; } std::this_thread::sleep_for(std::chrono::seconds(1)); } return true; } void ClientCommunication::Send(const Protobuf::MessageToServer& m2s) { unsigned char data[max_length]; int msgSize = m2s.ByteSizeLong(); GameMessage::Serialize(data,m2s); if (!pclient->Send(data, msgSize)) { std::cerr << "Failed to send the message. Error code:"; std::cerr << pclient->GetLastError() << std::endl; } } void ClientCommunication::Stop() { if (!pclient->HasStarted()) return; if (!pclient->Stop()) { std::cerr << "The client wasn`t stopped. Error code:"; std::cerr << pclient->GetLastError() << std::endl; } } void MultiThreadClientCommunication::OnConnect() { auto message = subscripter.OnConnect(); Send(message); } void MultiThreadClientCommunication::OnReceive(pointer_m2c p2M) { if (p2M.index() == TYPEM2C) { counter = 0; queue.emplace(p2M); UnBlock(); } } void MultiThreadClientCommunication::OnClose() { std::cout << "Connection was closed." << std::endl; loop = false; UnBlock(); subscripter.OnClose(); } void MultiThreadClientCommunication::init() { capi = std::make_unique<ClientCommunication>(*this); } void MultiThreadClientCommunication::UnBlock() { blocking = false; cv.notify_one(); // 唤醒一个线程 } void MultiThreadClientCommunication::ProcessMessage() { pointer_m2c pm2c; while (loop) { { std::unique_lock<std::mutex> lck(mtx); // 本质上和lock_guard类似,但cv类必须用unique_lock blocking = queue.empty(); // 如果消息队列为空就阻塞线程 cv.wait(lck, [this]() {return !blocking; }); // 翻译一下:1.只有当blocking==true时调用wait()时才会阻塞线程 2.在收到notify通知时只有blocking==false时才会解除阻塞 // 等价于 /* while([this](){return blocking;}) { cv.wait(lck); } */ } if (auto pm2c = queue.try_pop(); !pm2c.has_value()) // 接收信息,若获取失败则跳过处理信息的部分 { std::cerr << "failed to pop the message!" << std::endl; continue; // 避免处理空信息 } else subscripter.OnReceive(std::move(pm2c.value())); // 处理信息 } } bool MultiThreadClientCommunication::Start(const char* address, uint16_t port) { tPM = std::thread(&MultiThreadClientCommunication::ProcessMessage, this); // 单开一个线程处理信息 if (!capi->Connect(address, port)) { std::cerr << "unable to connect to server!" << std::endl; loop = false; // 终止循环 UnBlock(); // 若该线程阻塞则迅速解锁 tPM.join(); // 等待该子线程执行完才可以执行母线程 // 综合来看,上面两句话的含义是如若无法连接,则迅速把无用的tPM线程执行掉以后再退出 return false; } return true; } bool MultiThreadClientCommunication::Send(const Protobuf::MessageToServer& m2s) { if (counter >= Limit) { return false; } capi->Send(m2s); counter++; return true; } void MultiThreadClientCommunication::Join() { capi->Stop(); loop = false; UnBlock(); // 唤醒当前休眠的tPM线程 if (tPM.joinable()) { tPM.join(); // 等待其执行完毕 } }
22.447205
130
0.693968
Timothy-LiuXuefeng
57ca5f9f100f5aa4b44a0fe84c7b83c7ea93d8f7
13,749
cpp
C++
Source/FirstProject/MainCharacter.cpp
goksanisil23/UnrealCombat
e4d4cc546cb00d808ed7ee36dc15a74571a003b3
[ "MIT" ]
null
null
null
Source/FirstProject/MainCharacter.cpp
goksanisil23/UnrealCombat
e4d4cc546cb00d808ed7ee36dc15a74571a003b3
[ "MIT" ]
null
null
null
Source/FirstProject/MainCharacter.cpp
goksanisil23/UnrealCombat
e4d4cc546cb00d808ed7ee36dc15a74571a003b3
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "MainCharacter.h" #include "GameFramework/SpringArmComponent.h" #include "Camera/CameraComponent.h" #include "GameFramework/PlayerController.h" #include "Engine/World.h" #include "Components/CapsuleComponent.h" #include "GameFramework/CharacterMovementComponent.h" #include "Kismet/KismetSystemLibrary.h" #include "Weapon.h" #include "Components/SkeletalMeshComponent.h" #include "Animation/AnimInstance.h" #include "Kismet/GameplayStatics.h" #include "Sound/SoundCue.h" #include "Kismet/KismetMathLibrary.h" #include "Enemy.h" #include "MainPlayerController.h" // Sets default values AMainCharacter::AMainCharacter() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; // Create camera boom (pulls towards the player if there is a collision) CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); CameraBoom->SetupAttachment(GetRootComponent()); CameraBoom->TargetArmLength = 600.f; // Camera follows at this distance CameraBoom->bUsePawnControlRotation = true; // rotate arm based on controller // Create FollowCamera FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera")); FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation FollowCamera->bUsePawnControlRotation = false; BaseTurnRate = 65.f; BaseLookupRate = 65.f; // set size for collision capsule GetCapsuleComponent()->SetCapsuleSize(48.f, 150.f); // Don't rotate when the controller rotates, let that just affect the camera bUseControllerRotationYaw = false; bUseControllerRotationPitch = false; bUseControllerRotationRoll = false; // character moves in the direction of input GetCharacterMovement()->bOrientRotationToMovement = true; GetCharacterMovement()->RotationRate = FRotator(0.f, 540.f, 0.f); // only for yaw GetCharacterMovement()->JumpZVelocity = 650.f; GetCharacterMovement()->AirControl = 0.2f; MaxHealth = 100.0f; Health = 65.0f; MaxStamina = 150.0f; Stamina = 120.0f; Coins = 0; RunningSpeed = 650.0f; SprintingSpeed = 950.0f; bShiftKeyDown = false; bLMBDown = false; // Initialize Enums MovementStatus = EMovementStatus::EMS_Normal; StaminaStatus = EStaminaStatus::ESS_Normal; StaminaDrainRate = 25.0f; MinSprintStamina = 50.0f; InterpSpeed = 15.0f; bInterpToEnemy = false; bHasCombatTarget = false; bMovingRight = false; bMovingForward = false; } // Called when the game starts or when spawned void AMainCharacter::BeginPlay() { Super::BeginPlay(); MainPlayerController = Cast<AMainPlayerController>(GetController()); } FRotator AMainCharacter::GetLookAtRotationYaw(FVector Target) { // Finds the rotation required by this object, to be able look at a target location FRotator LookAtRotation = UKismetMathLibrary::FindLookAtRotation(GetActorLocation(), Target); FRotator LookAtRotationYaw(0.0f, LookAtRotation.Yaw, 0.0f); return LookAtRotation; } // Called every frame void AMainCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); if(MovementStatus == EMovementStatus::EMS_Dead) return; float DeltaStamina = StaminaDrainRate * DeltaTime; switch (StaminaStatus) { case EStaminaStatus::ESS_Normal: if(bShiftKeyDown) { if(Stamina - DeltaStamina <= MinSprintStamina) { SetStaminaStatus(EStaminaStatus::ESS_BelowMinimum); Stamina -= DeltaStamina; } else { Stamina -= DeltaStamina; } if (bMovingForward || bMovingRight) { SetMovementStatus(EMovementStatus::EMS_Sprinting); } else { SetMovementStatus(EMovementStatus::EMS_Normal); } } else { // Shift key up if (Stamina + DeltaStamina >= MaxStamina) { Stamina = MaxStamina; } else { Stamina += DeltaStamina; } SetMovementStatus(EMovementStatus::EMS_Normal); } break; case EStaminaStatus::ESS_BelowMinimum: if(bShiftKeyDown) { if (Stamina - DeltaStamina <= 0.0f) { SetStaminaStatus(EStaminaStatus::ESS_Exhausted); Stamina = 0; SetMovementStatus(EMovementStatus::EMS_Normal); } else { Stamina -= DeltaStamina; if (bMovingForward || bMovingRight) { SetMovementStatus(EMovementStatus::EMS_Sprinting); } else { SetMovementStatus(EMovementStatus::EMS_Normal); } } } else { // Shift key up if (Stamina + DeltaStamina >= MinSprintStamina) { SetStaminaStatus(EStaminaStatus::ESS_Normal); Stamina += DeltaStamina; } else { Stamina += DeltaStamina; } SetMovementStatus(EMovementStatus::EMS_Normal); } break; case EStaminaStatus::ESS_Exhausted: if(bShiftKeyDown) { Stamina = 0; } else { SetStaminaStatus(EStaminaStatus::ESS_ExhaustedRecovering); Stamina += DeltaStamina; } SetMovementStatus(EMovementStatus::EMS_Normal); break; case EStaminaStatus::ESS_ExhaustedRecovering: if (Stamina + DeltaStamina >= MinSprintStamina) { Stamina += DeltaStamina; SetStaminaStatus(EStaminaStatus::ESS_Normal); } else { Stamina += DeltaStamina; } SetMovementStatus(EMovementStatus::EMS_Normal); break; default: break; } // INterp to Enemy Logic if(bInterpToEnemy && CombatTarget) { FRotator LookAtYaw = GetLookAtRotationYaw(CombatTarget->GetActorLocation()); FRotator InterpRotation = FMath::RInterpTo(GetActorRotation(), LookAtYaw, DeltaTime, InterpSpeed); SetActorRotation(InterpRotation); } if(CombatTarget) { CombatTargetLocation = CombatTarget->GetActorLocation(); if(MainPlayerController) { MainPlayerController->EnemyLocation = CombatTargetLocation; } } } // Called to bind functionality to input void AMainCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); check(PlayerInputComponent); // Binding action only calls based on pressed/release PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &AMainCharacter::Jump); PlayerInputComponent->BindAction("Jump", IE_Released, this, &AMainCharacter::StopJumping); // Binding action only calls based on pressed/release PlayerInputComponent->BindAction("Sprint", IE_Pressed, this, &AMainCharacter::ShiftKeyDown); PlayerInputComponent->BindAction("Sprint", IE_Released, this, &AMainCharacter::ShiftKeyUp); // Binding action only calls based on pressed/release PlayerInputComponent->BindAction("LMB", IE_Pressed, this, &AMainCharacter::LMBDown); PlayerInputComponent->BindAction("LMB", IE_Released, this, &AMainCharacter::LMBUp); // Bind axis calls the function every frame, based on the value PlayerInputComponent->BindAxis("MoveForward", this, &AMainCharacter::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &AMainCharacter::MoveRight); PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput); PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput); PlayerInputComponent->BindAxis("TurnRate", this, &AMainCharacter::TurnAtRate); PlayerInputComponent->BindAxis("LookUpRate", this, &AMainCharacter::LookupAtRate); } void AMainCharacter::MoveForward(float Value) { bMovingForward = false; if((Controller != nullptr) && (Value != 0.0f) && !bAttacking && (MovementStatus != EMovementStatus::EMS_Dead)) { // Find out which way is forward const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0.f, Rotation.Yaw, 0.f); const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X); AddMovementInput(Direction, Value); bMovingForward = true; } } void AMainCharacter::MoveRight(float Value) { bMovingRight = false; if((Controller != nullptr) && (Value != 0.0f) && !bAttacking && (MovementStatus != EMovementStatus::EMS_Dead)) { // Find out which way is right const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0.f, Rotation.Yaw, 0.f); const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y); AddMovementInput(Direction, Value); bMovingRight = true; } } void AMainCharacter::TurnAtRate(float Rate) { AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds()); } void AMainCharacter::LookupAtRate(float Rate) { AddControllerPitchInput(Rate * BaseLookupRate * GetWorld()->GetDeltaSeconds()); } void AMainCharacter::LMBDown() { bLMBDown = true; if(MovementStatus == EMovementStatus::EMS_Dead) return; // Choosing to equip the collided weapon if(ActiveOverlappingItem) { AWeapon* Weapon = Cast<AWeapon>(ActiveOverlappingItem); if(Weapon) { Weapon->Equip(this); SetActiveOverlappingItem(nullptr); // once picked, no more overlapping item left } } else { // if weapon is picked up, LMB is attacking if(EquippedWepon) { Attack(); } } } void AMainCharacter::LMBUp() { bLMBDown = false; } void AMainCharacter::DecrementHealth(float Amount) { if (Health - Amount >= 0.0f) { Health -= Amount; } else { Health -= Amount; Die(); } } void AMainCharacter::IncrementCoins(int32 Amount) { Coins += Amount; } void AMainCharacter::IncrementHealth(float Amount) { if(Health + Amount >= MaxHealth) { Health = MaxHealth; } else { Health += Amount; } } void AMainCharacter::Die() { if (MovementStatus == EMovementStatus::EMS_Dead) // Against multiple enemies attacking and multiple deaths return; UAnimInstance* AnimInstance = GetMesh()->GetAnimInstance(); if (AnimInstance && CombatMontage) { AnimInstance->Montage_Play(CombatMontage, 1.0f); AnimInstance->Montage_JumpToSection(FName("Death"), CombatMontage); } SetMovementStatus(EMovementStatus::EMS_Dead); } void AMainCharacter::SetMovementStatus(EMovementStatus Status) { MovementStatus = Status; if (Status == EMovementStatus::EMS_Sprinting) { GetCharacterMovement()->MaxWalkSpeed = SprintingSpeed; } else { GetCharacterMovement()->MaxWalkSpeed = RunningSpeed; } } void AMainCharacter::ShiftKeyDown(){ bShiftKeyDown = true; } void AMainCharacter::ShiftKeyUp(){ bShiftKeyDown = false; } void AMainCharacter::ShowPickupLocations() { for(int32 i = 0; i < PickupLocations.Num(); i++) { // Draw a debug sphere at the coin pickup locations UKismetSystemLibrary::DrawDebugSphere(this, PickupLocations[i], 25.0f, 12, FLinearColor::Green, 10.0, 1.0); } } void AMainCharacter::SetEquippedWeapon(AWeapon* WeaponToSet) { if (EquippedWepon) { EquippedWepon->Destroy(); } EquippedWepon = WeaponToSet; } void AMainCharacter::Attack() { if(!bAttacking && MovementStatus != EMovementStatus::EMS_Dead) { bAttacking = true; SetInerpToEnemy(true); UAnimInstance* AnimInstance = GetMesh()->GetAnimInstance(); if(AnimInstance && CombatMontage) { int32 Section = FMath::RandRange(0, 1); switch(Section) { case 0: AnimInstance->Montage_Play(CombatMontage, 2.2f); AnimInstance->Montage_JumpToSection(FName("Attack_1"), CombatMontage); break; case 1: AnimInstance->Montage_Play(CombatMontage, 1.8f); AnimInstance->Montage_JumpToSection(FName("Attack_2"), CombatMontage); break; default:; } } } } void AMainCharacter::AttackEnd() { bAttacking = false; SetInerpToEnemy(false); if(bLMBDown) { Attack(); } } void AMainCharacter::PlaySwingSound(){ if(EquippedWepon->SwingSoundCue) { UGameplayStatics::PlaySound2D(this, EquippedWepon->SwingSoundCue); } } void AMainCharacter::SetInerpToEnemy(bool Interp) { bInterpToEnemy = Interp; } float AMainCharacter::TakeDamage(float DamageAmount,struct FDamageEvent const & DamageEvent, class AController * EventInstigator, AActor * DamageCauser) { if (Health - DamageAmount >= 0.0f) { Health -= DamageAmount; } else { Health -= DamageAmount; Die(); if (DamageCauser) { AEnemy* Enemy = Cast<AEnemy>(DamageCauser); if(Enemy){ Enemy->bHasValidTarget = false; // after the main char dies, enemies have no more valid target } } } return DamageAmount; } void AMainCharacter::DeathEnd() { GetMesh()->bPauseAnims = true; GetMesh()->bNoSkeletonUpdate = true; } void AMainCharacter::Jump() { if(MovementStatus != EMovementStatus::EMS_Dead) { Super::Jump(); } } void AMainCharacter::UpdateCombatTarget() { TArray<AActor*> OverlappingActors; GetOverlappingActors(OverlappingActors, EnemyFilter); if(OverlappingActors.Num() == 0) { if(MainPlayerController){ MainPlayerController->RemoveEnemyHealthBar(); } return; } AEnemy* ClosestEnemy = Cast<AEnemy>(OverlappingActors[0]); if(ClosestEnemy){ FVector Location = GetActorLocation(); float MinDistance = (ClosestEnemy->GetActorLocation() - Location).Size(); for(auto Actor: OverlappingActors) { AEnemy* Enemy = Cast<AEnemy>(Actor); if(Enemy) { float DistanceToActor = (Enemy->GetActorLocation() - Location).Size(); if(DistanceToActor < MinDistance) { MinDistance = DistanceToActor; ClosestEnemy = Enemy; } } } if(MainPlayerController){ MainPlayerController->DisplayEnemyHealthBar(); } SetCombatTarget(ClosestEnemy); bHasCombatTarget = true; } }
28.465839
120
0.70907
goksanisil23
57caa1a5ad8057fd6a418aafc65f5cd5a44e6e03
6,325
cpp
C++
tools/gmd/layers/ImportLayer.cpp
RuanauR/BetterEdit
9e4c031b8dec0c80f901f79d9f4a40173a52725b
[ "MIT" ]
30
2021-01-25T22:25:05.000Z
2022-01-22T13:18:19.000Z
tools/gmd/layers/ImportLayer.cpp
RuanauR/BetterEdit
9e4c031b8dec0c80f901f79d9f4a40173a52725b
[ "MIT" ]
9
2021-07-03T11:41:47.000Z
2022-03-30T15:14:46.000Z
tools/gmd/layers/ImportLayer.cpp
RuanauR/BetterEdit
9e4c031b8dec0c80f901f79d9f4a40173a52725b
[ "MIT" ]
3
2021-07-01T20:52:24.000Z
2022-01-13T16:16:58.000Z
#include "ImportLayer.hpp" #include "ImportListView.hpp" ImportLayer* g_pIsOpen = nullptr; bool ImportLayer::init(CCArray* arr) { if (!CCLayer::init()) return false; g_pIsOpen = this; this->m_pImportLevels = arr; this->m_pImportLevels->retain(); auto winSize = CCDirector::sharedDirector()->getWinSize(); auto sRight = CCDirector::sharedDirector()->getScreenRight(); auto bg = CCSprite::create("GJ_gradientBG.png"); auto bgSize = bg->getTextureRect().size; bg->setAnchorPoint({ 0.0f, 0.0f }); bg->setScaleX((winSize.width + 10.0f) / bgSize.width); bg->setScaleY((winSize.height + 10.0f) / bgSize.height); bg->setPosition({ -5.0f, -5.0f }); bg->setColor({ 0, 102, 255 }); this->addChild(bg); auto bottomLeft = CCSprite::createWithSpriteFrameName("GJ_sideArt_001.png"); auto cornerSize = bottomLeft->getTextureRect().size; bottomLeft->setPosition({ cornerSize.width / 2, cornerSize.height / 2 }); auto topRight = CCSprite::createWithSpriteFrameName("GJ_sideArt_001.png"); topRight->setFlipX(true); topRight->setFlipY(true); topRight->setPosition({ winSize.width - cornerSize.width / 2, winSize.height - cornerSize.height / 2 }); this->addChild(bottomLeft); this->addChild(topRight); this->m_pInfoLabel = CCLabelBMFont::create("", "bigFont.fnt"); this->m_pInfoLabel->setPosition(winSize / 2); this->m_pInfoLabel->setZOrder(99); this->m_pInfoLabel->setScale(.65f); this->addChild(this->m_pInfoLabel); this->m_pButtonMenu = CCMenu::create(); this->m_pButtonMenu->setZOrder(100); this->addChild(this->m_pButtonMenu); auto backBtn = CCMenuItemSpriteExtra::create( CCSprite::createWithSpriteFrameName("GJ_arrow_01_001.png"), this, menu_selector(ImportLayer::onExit) ); backBtn->setPosition(-winSize.width / 2 + 25.0f, winSize.height / 2 - 25.0f); this->m_pButtonMenu->addChild(backBtn); auto importSelectedBtnSpr = ButtonSprite::create( "Import Selected", 0, 0, "goldFont.fnt", "GJ_button_02.png", 0, .8f ); importSelectedBtnSpr->setScale(.6f); auto importSelectedBtn = CCMenuItemSpriteExtra::create( importSelectedBtnSpr, this, menu_selector(ImportLayer::onImportSelected) ); importSelectedBtn->setPosition(-65.f, - winSize.height / 2 + 30.0f); this->m_pButtonMenu->addChild(importSelectedBtn); auto deleteSelectedBtnSpr = ButtonSprite::create( "Delete Selected", 0, 0, "goldFont.fnt", "GJ_button_06.png", 0, .8f ); deleteSelectedBtnSpr->setScale(.6f); auto deleteSelectedBtn = CCMenuItemSpriteExtra::create( deleteSelectedBtnSpr, this, menu_selector(ImportLayer::onDeleteSelected) ); deleteSelectedBtn->setPosition(65.f, - winSize.height / 2 + 30.0f); this->m_pButtonMenu->addChild(deleteSelectedBtn); this->reloadList(); this->setKeyboardEnabled(true); this->setKeypadEnabled(true); return true; } void ImportLayer::reloadList() { if (this->m_pList) { this->m_pList->removeFromParent(); this->m_pList = nullptr; } this->m_pInfoLabel->setVisible(!this->m_pImportLevels->count()); this->m_pInfoLabel->setString("No Levels to Import"); auto winSize = CCDirector::sharedDirector()->getWinSize(); this->m_pList = GJListLayer::create( ImportListView::create(this, this->m_pImportLevels, 356.0f, 220.0f), "Import Levels", { 0, 0, 0, 180 }, 356.0f, 220.0f ); this->m_pList->setPosition( winSize / 2 - this->m_pList->getScaledContentSize() / 2 ); this->addChild(this->m_pList); } void ImportLayer::addItemsToList(CCArray* arr) { this->m_pImportLevels->addObjectsFromArray(arr); this->reloadList(); } void ImportLayer::removeItemFromList(ImportObject* obj) { this->m_pImportLevels->removeObject(obj); this->reloadList(); } void ImportLayer::onExit(CCObject*) { if (this->m_pImportLevels->count()) { // !note: might be too confusing. FLAlertLayer::create( this, "Warning", "Cancel", "Leave", "Exiting will cause levels not imported to " "be deleted, and you'll have to import them " "again. Continue?" )->show(); } else { this->exitForReal(); } } void ImportLayer::onImportSelected(CCObject*) { CCARRAY_FOREACH_B_BASE( this->m_pList->m_pListView->m_pTableView->m_pContentLayer->getChildren(), cell, ImportLevelCell*, ix ) { if (cell->isSelected()) { LocalLevelManager::sharedState()->m_pLevels->insertObject( cell->getObject()->m_pLevel, 0u ); this->m_pImportLevels->removeObject(cell->getObject()); } } this->reloadList(); } void ImportLayer::onDeleteSelected(CCObject*) { CCARRAY_FOREACH_B_BASE( this->m_pList->m_pListView->m_pTableView->m_pContentLayer->getChildren(), cell, ImportLevelCell*, ix ) { if (cell->isSelected()) { this->m_pImportLevels->removeObject(cell->getObject()); } } this->reloadList(); } void ImportLayer::exitForReal() { // CCDirector::sharedDirector()->replaceScene( // CCTransitionFade::create(.5f, MenuLayer::scene(false)) // ); LevelBrowserLayer::scene(GJSearchObject::create(kGJSearchTypeMyLevels)); } void ImportLayer::FLAlert_Clicked(FLAlertLayer*, bool btn2) { if (btn2) { this->exitForReal(); } } void ImportLayer::keyDown(enumKeyCodes key) { switch (key) { case KEY_Escape: this->onExit(nullptr); break; } } ImportLayer::~ImportLayer() { CC_SAFE_RELEASE(this->m_pImportLevels); g_pIsOpen = nullptr; } ImportLayer* ImportLayer::create(CCArray* arr) { auto ret = new ImportLayer; if (ret && ret->init(arr)) { ret->autorelease(); return ret; } CC_SAFE_DELETE(ret); return nullptr; } ImportLayer* ImportLayer::scene(CCArray* arr, bool transition) { auto scene = CCScene::create(); auto layer = ImportLayer::create(arr); scene->addChild(layer); if (transition) { scene = CCTransitionFade::create(.5f, scene); } CCDirector::sharedDirector()->replaceScene(scene); return layer; } ImportLayer* ImportLayer::isOpen() { return g_pIsOpen; }
27.986726
105
0.657075
RuanauR
57ccf881495168e448b289204595e7ea52f52e66
14,062
cc
C++
test/apps/sockaddr/sa_main.cc
RankoM/ucx
d8269f0141f97764c21d03235c0783f04a9864b7
[ "BSD-3-Clause" ]
5
2019-05-31T01:47:34.000Z
2022-01-10T11:59:53.000Z
test/apps/sockaddr/sa_main.cc
frontwing/ucx
e1eed19d973844198445ba822239f0b8a5be19a7
[ "BSD-3-Clause" ]
2
2019-04-22T12:49:59.000Z
2019-06-06T16:20:21.000Z
test/apps/sockaddr/sa_main.cc
frontwing/ucx
e1eed19d973844198445ba822239f0b8a5be19a7
[ "BSD-3-Clause" ]
1
2021-03-16T07:04:15.000Z
2021-03-16T07:04:15.000Z
/** * Copyright (C) Mellanox Technologies Ltd. 2018. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #include "sa_base.h" #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <cstring> #include <map> #include <sys/epoll.h> #include <getopt.h> #include <netdb.h> #include <unistd.h> class application { public: class usage_exception : public error { public: usage_exception(const std::string& message = ""); }; application(int argc, char **argv); int run(); static void usage(const std::string& error); private: typedef struct { std::string hostname; int port; } dest_t; typedef std::vector<dest_t> dest_vec_t; enum connection_type { CONNECTION_CLIENT, CONNECTION_SERVER }; struct params { params() : port(0), total_conns(1000), conn_ratio(1.5), request_size(32), response_size(1024) { } std::string mode; int port; int total_conns; double conn_ratio; size_t request_size; size_t response_size; dest_vec_t dests; }; struct connection_state { conn_ptr_t conn_ptr; connection_type conn_type; size_t bytes_sent; size_t bytes_recvd; std::string send_data; std::string recv_data; }; typedef std::shared_ptr<connection_state> conn_state_ptr_t; typedef std::map<uint64_t, conn_state_ptr_t> conn_map_t; void parse_hostfile(const std::string& filename); void initiate_connections(); int max_conns_inflight() const; void create_worker(); void add_connection(conn_ptr_t conn_ptr, connection_type conn_type); conn_ptr_t connect(const dest_t& dst); void advance_connection(conn_state_ptr_t s, uint32_t events); void connection_completed(conn_state_ptr_t s); static void pton(const dest_t& dst, struct sockaddr_storage& saddr, socklen_t &addrlen); template <typename O> friend typename O::__basic_ostream& operator<<(O& os, connection_type conn_type); params m_params; std::shared_ptr<worker> m_worker; evpoll_set m_evpoll; conn_map_t m_connections; int m_num_conns_inflight; int m_num_conns_started; }; application::usage_exception::usage_exception(const std::string& message) : error(message) { }; application::application(int argc, char **argv) : m_num_conns_inflight(0), m_num_conns_started(0) { int c; while ( (c = getopt(argc, argv, "p:f:m:r:n:S:s:vh")) != -1 ) { switch (c) { case 'p': m_params.port = atoi(optarg); break; case 'f': parse_hostfile(optarg); break; case 'm': m_params.mode = optarg; break; case 'r': m_params.conn_ratio = atof(optarg); break; case 'n': m_params.total_conns = atoi(optarg); break; case 'S': m_params.request_size = atoi(optarg); break; case 's': m_params.response_size = atoi(optarg); break; case 'v': log::more_verbose(); break; default: throw usage_exception(); } } if (m_params.mode.empty()) { throw usage_exception("missing mode argument"); } if (m_params.dests.empty()) { throw usage_exception("no remote destinations specified"); } if (m_params.port == 0) { throw usage_exception("local port not specified"); } } int application::run() { LOG_INFO << "starting application with " << max_conns_inflight() << " simultaneous connections, " << m_params.total_conns << " total"; create_worker(); while ((m_num_conns_started > m_params.total_conns) || !m_connections.empty()) { initiate_connections(); m_worker->wait(m_evpoll, [this](conn_ptr_t conn) { LOG_DEBUG << "accepted new connection"; add_connection(conn, CONNECTION_SERVER); }, [this](uint64_t conn_id, uint32_t events) { LOG_DEBUG << "new event on connection id " << conn_id << " events " << ((events & EPOLLIN ) ? "i" : "") << ((events & EPOLLOUT) ? "o" : "") << ((events & EPOLLERR) ? "e" : "") ; advance_connection(m_connections.at(conn_id), events); }, -1); } LOG_INFO << "all connections completed"; m_worker.reset(); return 0; } void application::create_worker() { struct sockaddr_in inaddr_any; memset(&inaddr_any, 0, sizeof(inaddr_any)); inaddr_any.sin_family = AF_INET; inaddr_any.sin_port = htons(m_params.port); inaddr_any.sin_addr.s_addr = INADDR_ANY; m_worker = worker::make(m_params.mode, reinterpret_cast<struct sockaddr *>(&inaddr_any), sizeof(inaddr_any)); m_worker->add_to_evpoll(m_evpoll); } std::shared_ptr<connection> application::connect(const dest_t& dst) { struct sockaddr_storage saddr; socklen_t addrlen; pton(dst, saddr, addrlen); return m_worker->connect(reinterpret_cast<const struct sockaddr*>(&saddr), addrlen); } template <typename O> typename O::__basic_ostream& operator<<(O& os, application::connection_type conn_type) { switch (conn_type) { case application::CONNECTION_CLIENT: return os << "client"; case application::CONNECTION_SERVER: return os << "server"; default: return os; } } void application::add_connection(conn_ptr_t conn_ptr, connection_type conn_type) { auto s = std::make_shared<connection_state>(); s->conn_type = conn_type; s->conn_ptr = conn_ptr; s->bytes_sent = 0; s->bytes_recvd = 0; switch (s->conn_type) { case CONNECTION_CLIENT: s->send_data.assign(m_params.request_size, 'r'); s->recv_data.resize(m_params.response_size); break; case CONNECTION_SERVER: s->send_data.resize(m_params.response_size); s->recv_data.resize(m_params.request_size); break; } LOG_DEBUG << "add " << conn_type << " connection with id " << conn_ptr->id(); conn_ptr->add_to_evpoll(m_evpoll); m_connections[conn_ptr->id()] = s; advance_connection(s, 0); } void application::initiate_connections() { int max = max_conns_inflight(); while ((m_num_conns_started < m_params.total_conns) && (m_num_conns_inflight < max)) { /* coverity[dont_call] */ const dest_t& dest = m_params.dests[::rand() % m_params.dests.size()]; ++m_num_conns_started; ++m_num_conns_inflight; LOG_DEBUG << "connecting to " << dest.hostname << ":" << dest.port; add_connection(connect(dest), CONNECTION_CLIENT); } } int application::max_conns_inflight() const { return m_params.conn_ratio * m_params.dests.size() + 0.5; } void application::advance_connection(conn_state_ptr_t s, uint32_t events) { LOG_DEBUG << "advance " << s->conn_type << " connection id " << s->conn_ptr->id() << " total sent " << s->bytes_sent << ", received " << s->bytes_recvd; switch (s->conn_type) { case CONNECTION_CLIENT: if (s->bytes_sent < m_params.request_size) { /* more data should be sent */ size_t nsent = s->conn_ptr->send(&s->send_data[s->bytes_sent], m_params.request_size - s->bytes_sent); LOG_DEBUG << "sent " << nsent << " bytes on connection id " << s->conn_ptr->id(); s->bytes_sent += nsent; } if (events & EPOLLIN) { size_t nrecv = s->conn_ptr->recv(&s->recv_data[s->bytes_recvd], m_params.response_size - s->bytes_recvd); LOG_DEBUG << "received " << nrecv << " bytes on connection id " << s->conn_ptr->id(); s->bytes_recvd += nrecv; } if (s->bytes_recvd == m_params.response_size) { connection_completed(s); } break; case CONNECTION_SERVER: if (events & EPOLLIN) { size_t nrecv = s->conn_ptr->recv(&s->recv_data[s->bytes_recvd], m_params.request_size - s->bytes_recvd); LOG_DEBUG << "received " << nrecv << " bytes on connection id " << s->conn_ptr->id(); s->bytes_recvd += nrecv; } if ((s->bytes_recvd == m_params.request_size) && (s->bytes_sent < m_params.response_size)) { /* more data should be sent */ size_t nsent = s->conn_ptr->send(&s->send_data[s->bytes_sent], m_params.response_size - s->bytes_sent); LOG_DEBUG << "sent " << nsent << " bytes on connection id " << s->conn_ptr->id(); s->bytes_sent += nsent; } if (s->conn_ptr->is_closed()) { connection_completed(s); } break; } } void application::connection_completed(conn_state_ptr_t s) { LOG_DEBUG << "completed " << s->conn_type << " connection id " << s->conn_ptr->id(); m_connections.erase(s->conn_ptr->id()); --m_num_conns_inflight; } void application::pton(const dest_t& dst, struct sockaddr_storage& saddr, socklen_t &addrlen) { struct hostent *he = gethostbyname(dst.hostname.c_str()); if (he == NULL || he->h_addr_list == NULL) { throw error("host " + dst.hostname + " not found: "+ hstrerror(h_errno)); } memset(&saddr, 0, sizeof(saddr)); saddr.ss_family = he->h_addrtype; void *addr; int addr_datalen = 0; switch (saddr.ss_family) { case AF_INET: reinterpret_cast<struct sockaddr_in*>(&saddr)->sin_port = htons(dst.port); addr = &reinterpret_cast<struct sockaddr_in*>(&saddr)->sin_addr; addrlen = sizeof(struct sockaddr_in); addr_datalen = sizeof(struct in_addr); break; case AF_INET6: reinterpret_cast<struct sockaddr_in6*>(&saddr)->sin6_port = htons(dst.port); addr = &reinterpret_cast<struct sockaddr_in6*>(&saddr)->sin6_addr; addrlen = sizeof(struct sockaddr_in6); addr_datalen = sizeof(struct in6_addr); break; default: throw error("unsupported address family"); } if (he->h_length != addr_datalen) { throw error("mismatching address length"); } memcpy(addr, he->h_addr_list[0], addr_datalen); } void application::usage(const std::string& error) { if (!error.empty()) { std::cout << "Error: " << error << std::endl; std::cout << std::endl; } params defaults; std::cout << "Usage: ./sa [ options ]" << std::endl; std::cout << "Options:" << std::endl; std::cout << " -m <mode> Application mode (tcp)" << std::endl; std::cout << " -p <port> Local port number to listen on" << std::endl; std::cout << " -f <file> File with list of hosts and ports to connect to" << std::endl; std::cout << " Each line in the file is formatter as follows:" << std::endl; std::cout << " <address> <port>" << std::endl; std::cout << " -r <ratio> How many in-flight connection to hold as multiple" << std::endl; std::cout << " of number of possible destinations (" << defaults.conn_ratio << ")" << std::endl; std::cout << " -n <count> How many total exchanges to perform (" << defaults.total_conns << ")" << std::endl; std::cout << " -S <size> Request message size, in bytes (" << defaults.request_size << ")" << std::endl; std::cout << " -s <size> Response message size, in bytes (" << defaults.response_size << ")" << std::endl; std::cout << " -v Increase verbosity level (may be specified several times)" << std::endl; } void application::parse_hostfile(const std::string& filename) { std::ifstream f(filename.c_str()); if (!f) { throw error("failed to open '" + filename + "'"); } /* * Each line in the file contains 2 whitespace-separated tokens: host-name * and port number. */ std::string line; int lineno = 1; while (std::getline(f, line)) { std::stringstream ss(line); if (line.empty()) { continue; } dest_t dest; if ((ss >> dest.hostname) && (ss >> dest.port)) { m_params.dests.push_back(dest); } else { std::stringstream errss; errss << "syntax error in file '" << filename << "' line " << lineno << " near `" << line << "'"; throw error(errss.str()); } ++lineno; } } int main(int argc, char **argv) { try { application app(argc, argv); return app.run(); } catch (application::usage_exception& e) { application::usage(e.what()); return -127; } catch (error& e) { std::cerr << "Error: " << e.what() << std::endl; } }
33.401425
118
0.543806
RankoM
57cf7e6ff8dd3044d18ed1feae897ff2a962cc70
6,723
cpp
C++
test/brpc_grpc_protocol_unittest.cpp
ambroff/brpc
ede2bf595915fcb9b5285ae8b6eb7ab46a5bac4f
[ "Apache-2.0" ]
1
2019-08-12T13:59:35.000Z
2019-08-12T13:59:35.000Z
test/brpc_grpc_protocol_unittest.cpp
ambroff/brpc
ede2bf595915fcb9b5285ae8b6eb7ab46a5bac4f
[ "Apache-2.0" ]
null
null
null
test/brpc_grpc_protocol_unittest.cpp
ambroff/brpc
ede2bf595915fcb9b5285ae8b6eb7ab46a5bac4f
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2018 brpc authors. // // 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. // Authors: Jiashun Zhu(zhujiashun@bilibili.com) #include <gtest/gtest.h> #include <gflags/gflags.h> #include "brpc/controller.h" #include "brpc/server.h" #include "brpc/channel.h" #include "brpc/grpc.h" #include "grpc.pb.h" int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); GFLAGS_NS::ParseCommandLineFlags(&argc, &argv, true); if (GFLAGS_NS::SetCommandLineOption("http_body_compress_threshold", "0").empty()) { std::cerr << "Fail to set -crash_on_fatal_log" << std::endl; return -1; } if (GFLAGS_NS::SetCommandLineOption("crash_on_fatal_log", "true").empty()) { std::cerr << "Fail to set -crash_on_fatal_log" << std::endl; return -1; } return RUN_ALL_TESTS(); } namespace { const std::string g_server_addr = "127.0.0.1:8011"; const std::string g_prefix = "Hello, "; const std::string g_req = "wyt"; const int64_t g_timeout_ms = 1000; const std::string g_protocol = "h2:grpc"; class MyGrpcService : public ::test::GrpcService { public: void Method(::google::protobuf::RpcController* cntl_base, const ::test::GrpcRequest* req, ::test::GrpcResponse* res, ::google::protobuf::Closure* done) { brpc::Controller* cntl = static_cast<brpc::Controller*>(cntl_base); brpc::ClosureGuard done_guard(done); EXPECT_EQ(g_req, req->message()); if (req->gzip()) { cntl->set_response_compress_type(brpc::COMPRESS_TYPE_GZIP); } res->set_message(g_prefix + req->message()); if (req->return_error()) { cntl->SetFailed(brpc::EINTERNAL, "%s", g_prefix.c_str()); return; } } void MethodTimeOut(::google::protobuf::RpcController* cntl_base, const ::test::GrpcRequest* req, ::test::GrpcResponse* res, ::google::protobuf::Closure* done) { brpc::ClosureGuard done_guard(done); bthread_usleep(2000000 /*2s*/); res->set_message(g_prefix + req->message()); return; } }; class GrpcTest : public ::testing::Test { protected: GrpcTest() { EXPECT_EQ(0, _server.AddService(&_svc, brpc::SERVER_DOESNT_OWN_SERVICE)); EXPECT_EQ(0, _server.Start(g_server_addr.c_str(), NULL)); brpc::ChannelOptions options; options.protocol = g_protocol; options.timeout_ms = g_timeout_ms; EXPECT_EQ(0, _channel.Init(g_server_addr.c_str(), "", &options)); } virtual ~GrpcTest() {}; virtual void SetUp() {}; virtual void TearDown() {}; void CallMethod(bool req_gzip, bool res_gzip) { test::GrpcRequest req; test::GrpcResponse res; brpc::Controller cntl; if (req_gzip) { cntl.set_request_compress_type(brpc::COMPRESS_TYPE_GZIP); } req.set_message(g_req); req.set_gzip(res_gzip); req.set_return_error(false); test::GrpcService_Stub stub(&_channel); stub.Method(&cntl, &req, &res, NULL); EXPECT_FALSE(cntl.Failed()) << cntl.ErrorCode() << ": " << cntl.ErrorText(); EXPECT_EQ(res.message(), g_prefix + g_req); } brpc::Server _server; MyGrpcService _svc; brpc::Channel _channel; }; TEST_F(GrpcTest, percent_encode) { std::string out; std::string s1("abcdefg !@#$^&*()/"); std::string s1_out("abcdefg%20%21%40%23%24%5e%26%2a%28%29%2f"); brpc::PercentEncode(s1, &out); EXPECT_TRUE(out == s1_out) << s1_out << " vs " << out; char s2_buf[] = "\0\0%\33\35 brpc"; std::string s2(s2_buf, sizeof(s2_buf) - 1); std::string s2_expected_out("%00%00%25%1b%1d%20brpc"); brpc::PercentEncode(s2, &out); EXPECT_TRUE(out == s2_expected_out) << s2_expected_out << " vs " << out; } TEST_F(GrpcTest, percent_decode) { std::string out; std::string s1("abcdefg%20%21%40%23%24%5e%26%2a%28%29%2f"); std::string s1_out("abcdefg !@#$^&*()/"); brpc::PercentDecode(s1, &out); EXPECT_TRUE(out == s1_out) << s1_out << " vs " << out; std::string s2("%00%00%1b%1d%20brpc"); char s2_expected_out_buf[] = "\0\0\33\35 brpc"; std::string s2_expected_out(s2_expected_out_buf, sizeof(s2_expected_out_buf) - 1); brpc::PercentDecode(s2, &out); EXPECT_TRUE(out == s2_expected_out) << s2_expected_out << " vs " << out; } TEST_F(GrpcTest, sanity) { for (int i = 0; i < 2; ++i) { // if req use gzip or not for (int j = 0; j < 2; ++j) { // if res use gzip or not CallMethod(i, j); } } } TEST_F(GrpcTest, return_error) { test::GrpcRequest req; test::GrpcResponse res; brpc::Controller cntl; req.set_message(g_req); req.set_gzip(false); req.set_return_error(true); test::GrpcService_Stub stub(&_channel); stub.Method(&cntl, &req, &res, NULL); EXPECT_TRUE(cntl.Failed()); EXPECT_EQ(cntl.ErrorCode(), brpc::EINTERNAL); EXPECT_TRUE(butil::StringPiece(cntl.ErrorText()).ends_with(butil::string_printf("%s", g_prefix.c_str()))); } TEST_F(GrpcTest, RpcTimedOut) { brpc::Channel channel; brpc::ChannelOptions options; options.protocol = g_protocol; options.timeout_ms = g_timeout_ms; EXPECT_EQ(0, channel.Init(g_server_addr.c_str(), "", &options)); test::GrpcRequest req; test::GrpcResponse res; brpc::Controller cntl; req.set_message(g_req); req.set_gzip(false); req.set_return_error(false); test::GrpcService_Stub stub(&_channel); stub.MethodTimeOut(&cntl, &req, &res, NULL); EXPECT_TRUE(cntl.Failed()); EXPECT_EQ(cntl.ErrorCode(), brpc::ERPCTIMEDOUT); } TEST_F(GrpcTest, MethodNotExist) { test::GrpcRequest req; test::GrpcResponse res; brpc::Controller cntl; req.set_message(g_req); req.set_gzip(false); req.set_return_error(false); test::GrpcService_Stub stub(&_channel); stub.MethodNotExist(&cntl, &req, &res, NULL); EXPECT_TRUE(cntl.Failed()); EXPECT_EQ(cntl.ErrorCode(), brpc::EINTERNAL); ASSERT_TRUE(butil::StringPiece(cntl.ErrorText()).ends_with("Method MethodNotExist() not implemented.")); } } // namespace
33.282178
110
0.639595
ambroff
57deb279115c2302d80c815cfb1d2e30f5dfeda7
2,008
cpp
C++
snippets/cpp/VS_Snippets_Winforms/DataFormats_UnicodeText1/CPP/dataformats_unicodetext.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
834
2017-06-24T10:40:36.000Z
2022-03-31T19:48:51.000Z
snippets/cpp/VS_Snippets_Winforms/DataFormats_UnicodeText1/CPP/dataformats_unicodetext.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
7,042
2017-06-23T22:34:47.000Z
2022-03-31T23:05:23.000Z
snippets/cpp/VS_Snippets_Winforms/DataFormats_UnicodeText1/CPP/dataformats_unicodetext.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
1,640
2017-06-23T22:31:39.000Z
2022-03-31T02:45:37.000Z
// System::Windows::Forms::DataFormats.UnicodeText;System::Windows::Forms::Text; /* * The following example demonstrates the 'UnicodeText' and 'Text' field of 'DataFormats' class. * It stores a String Object^ in Clipboard using the Clipboard's 'SetDataObject' method. * It retrieves the String Object^ stored in the Clipboard by using the GetDataObject method * which returns the 'IDataObject^'. It checks whether the Unicodetext data is present * or not by using the 'GetDataPresent' method of 'IDataObject^'. If data is there then it * displays the data to the console. It also checks 'Text' format data is present or not. If * the data is there it displays the data to the console. * */ #using <System.dll> #using <System.Drawing.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Drawing::Imaging; using namespace System::Windows::Forms; int main() { // <Snippet1> // <Snippet2> try { String^ myString = "This is a String from the ClipBoard"; // Sets the data into the Clipboard. Clipboard::SetDataObject( myString ); IDataObject^ myDataObject = Clipboard::GetDataObject(); // Checks whether the format of the data is 'UnicodeText' or not. if ( myDataObject->GetDataPresent( DataFormats::UnicodeText ) ) { Console::WriteLine( "Data in 'UnicodeText' format: " + myDataObject->GetData( DataFormats::UnicodeText ) ); } else { Console::WriteLine( "No String information was contained in the clipboard." ); } // Checks whether the format of the data is 'Text' or not. if ( myDataObject->GetDataPresent( DataFormats::Text ) ) { String^ clipString = (String^)(myDataObject->GetData( DataFormats::StringFormat )); Console::WriteLine( "Data in 'Text' format: {0}", clipString ); } } catch ( Exception^ e ) { Console::WriteLine( e->Message ); } // </Snippet2> // </Snippet1> }
34.62069
97
0.665837
BohdanMosiyuk
57e043bf44c0c5897f48e7a5075893a6249fe1a0
1,230
hpp
C++
NWNXLib/API/API/CNWSWaypoint.hpp
nwnstuff/unified
2da1201fdded07235f3d2809a3215315140d19da
[ "MIT" ]
null
null
null
NWNXLib/API/API/CNWSWaypoint.hpp
nwnstuff/unified
2da1201fdded07235f3d2809a3215315140d19da
[ "MIT" ]
null
null
null
NWNXLib/API/API/CNWSWaypoint.hpp
nwnstuff/unified
2da1201fdded07235f3d2809a3215315140d19da
[ "MIT" ]
null
null
null
#pragma once #include "nwn_api.hpp" #include "CExoLocString.hpp" #include "CResRef.hpp" #include "CNWSObject.hpp" #ifdef NWN_API_PROLOGUE NWN_API_PROLOGUE(CNWSWaypoint) #endif struct CExoString; struct CResStruct; struct CResGFF; struct CNWSArea; typedef int BOOL; typedef uint32_t OBJECT_ID; struct CNWSWaypoint : CNWSObject { BOOL m_bMapNote; BOOL m_bMapNoteEnabled; CExoLocString m_szMapNote; CExoLocString m_sLocalizedName; CNWSWaypoint(OBJECT_ID oidId = 0x7f000000); ~CNWSWaypoint(); void AddToArea(CNWSArea * pArea, float fX, float fY, float fZ, BOOL bRunScripts = true); void AIUpdate(); virtual CNWSWaypoint * AsNWSWaypoint(); void EventHandler(uint32_t nEventId, OBJECT_ID nCallerObjectId, void * pScript, uint32_t nCalendarDay, uint32_t nTimeOfDay); void RemoveFromArea(); BOOL LoadFromTemplate(CResRef cResRef, CExoString * pTag = nullptr); BOOL LoadWaypoint(CResGFF * pRes, CResStruct * cWaypointStruct, CExoString * pTag = nullptr); BOOL SaveWaypoint(CResGFF * pRes, CResStruct * cWaypointStruct); #ifdef NWN_CLASS_EXTENSION_CNWSWaypoint NWN_CLASS_EXTENSION_CNWSWaypoint #endif }; #ifdef NWN_API_EPILOGUE NWN_API_EPILOGUE(CNWSWaypoint) #endif
23.653846
128
0.766667
nwnstuff
57e33ed837de02da61f98160d5af9baf10c586ec
6,088
cpp
C++
Samples/XNA_XNB_Format/Example XNB Parser/ParseXnb/ContentReader.cpp
SimonDarksideJ/XNAGameStudio
5b79efb0b110140419056b0146ba066f2104f985
[ "MIT" ]
422
2018-03-20T07:46:35.000Z
2022-03-31T19:37:43.000Z
Samples/XNA_XNB_Format/Example XNB Parser/ParseXnb/ContentReader.cpp
SimonDarksideJ/XNAGameStudio
5b79efb0b110140419056b0146ba066f2104f985
[ "MIT" ]
11
2018-09-10T01:05:45.000Z
2022-03-10T17:27:02.000Z
Samples/XNA_XNB_Format/Example XNB Parser/ParseXnb/ContentReader.cpp
SimonDarksideJ/XNAGameStudio
5b79efb0b110140419056b0146ba066f2104f985
[ "MIT" ]
72
2018-09-08T09:51:55.000Z
2022-03-04T17:38:53.000Z
#include "stdafx.h" #include "ContentReader.h" ContentReader::ContentReader(FILE* file, TypeReaderManager* typeReaderManager) : BinaryReader(file), typeReaderManager(typeReaderManager) { } // Parses the entire contents of an XNB file. void ContentReader::ReadXnb() { // Read the XNB header. uint32_t endPosition = ReadHeader(); ReadTypeManifest(); uint32_t sharedResourceCount = Read7BitEncodedInt(); // Read the primary asset data. Log.WriteLine("Asset:"); ReadObject(); // Read any shared resource instances. for (uint32_t i = 0 ; i < sharedResourceCount; i++) { Log.WriteLine("Shared resource %d:", i); ReadObject(); } // Make sure we read the amount of data that the file header said we should. if (FilePosition() != endPosition) { throw exception("End position does not match XNB header: unexpected amount of data was read."); } } // Reads the XNB file header (version number, size, etc.). uint32_t ContentReader::ReadHeader() { uint32_t startPosition = FilePosition(); // Magic number. uint8_t magic1 = ReadByte(); uint8_t magic2 = ReadByte(); uint8_t magic3 = ReadByte(); if (magic1 != 'X' || magic2 != 'N' || magic3 != 'B') { throw exception("Not an XNB file."); } // Target platform. uint8_t targetPlatform = ReadByte(); switch (targetPlatform) { case 'w': Log.WriteLine("Target platform: Windows"); break; case 'm': Log.WriteLine("Target platform: Windows Phone"); break; case 'x': Log.WriteLine("Target platform: Xbox 360"); break; default: Log.WriteLine("Unknown target platform %d", targetPlatform); break; } // Format version. uint8_t formatVersion = ReadByte(); if (formatVersion != 5) { Log.WriteLine("Warning: not an XNA Game Studio version 4.0 XNB file. Parsing may fail unexpectedly."); } // Flags. uint8_t flags = ReadByte(); if (flags & 1) { Log.WriteLine("Graphics profile: HiDef"); } else { Log.WriteLine("Graphics profile: Reach"); } bool isCompressed = (flags & 0x80) != 0; // File size. uint32_t sizeOnDisk = ReadUInt32(); if (startPosition + sizeOnDisk > FileSize()) { throw exception("XNB file has been truncated."); } if (isCompressed) { uint32_t decompressedSize = ReadUInt32(); uint32_t compressedSize = startPosition + sizeOnDisk - FilePosition(); Log.WriteLine("%d bytes of asset data are compressed into %d", decompressedSize, compressedSize); throw exception("Don't support reading the contents of compressed XNB files."); } return startPosition + sizeOnDisk; } // Reads the manifest of what types are contained in this XNB file. void ContentReader::ReadTypeManifest() { Log.WriteLine("Type readers:"); Log.Indent(); // How many type readers does this .xnb use? uint32_t typeReaderCount = Read7BitEncodedInt(); typeReaders.clear(); for (uint32_t i = 0; i < typeReaderCount; i++) { // Read the type reader metadata. wstring readerName = ReadString(); int32_t readerVersion = ReadInt32(); Log.WriteLine("%S (version %d)", readerName.c_str(), readerVersion); // Look up and store this type reader implementation class. TypeReader* reader = typeReaderManager->GetByReaderName(readerName); typeReaders.push_back(reader); } // Initialize the readers in a separate pass after they are all registered, in case there are // circular dependencies between them (eg. an array of classes which themselves contain arrays). for each (TypeReader* reader in typeReaders) { reader->Initialize(typeReaderManager); } Log.Unindent(); } // Reads a single polymorphic object from the current location. void ContentReader::ReadObject() { Log.Indent(); // What type of object is this? TypeReader* typeReader = ReadTypeId(); if (typeReader) { Log.WriteLine("Type: %S", typeReader->TargetType().c_str()); // Call into the appropriate TypeReader to parse the object data. typeReader->Read(this); } else { Log.WriteLine("null"); } Log.Unindent(); } // Reads either a raw value or polymorphic object, depending on whether the specified typeReader represents a value type. void ContentReader::ReadValueOrObject(TypeReader* typeReader) { if (typeReader->IsValueType()) { // Read a value type. Log.Indent(); typeReader->Read(this); Log.Unindent(); } else { // Read a reference type. ReadObject(); } } // Reads the typeId from the start of a polymorphic object, and looks up the appropriate TypeReader implementation. TypeReader* ContentReader::ReadTypeId() { uint32_t typeId = Read7BitEncodedInt(); if (typeId > 0) { // Look up the reader for this type of object. typeId--; if (typeId >= typeReaders.size()) { throw exception("Invalid XNB file: typeId is out of range."); } return typeReaders[typeId]; } else { // A zero typeId indicates a null object. return nullptr; } } // Reads a typeId, and validates that it is the expected type. void ContentReader::ValidateTypeId(wstring const& expectedType) { TypeReader* reader = ReadTypeId(); if (!reader || reader->TargetType() != expectedType) { throw exception("Invalid XNB file: got an unexpected typeId."); } } // Reads a shared resource ID, which indexes into the table of shared object instances that come after the primary asset. void ContentReader::ReadSharedResource() { uint32_t resourceId = Read7BitEncodedInt(); if (resourceId) { Log.WriteLine("shared resource #%u", resourceId - 1); } else { Log.WriteLine("null"); } }
24.747967
121
0.630092
SimonDarksideJ
57e3d85f5d5b68ada950195da7220448128f9b2f
311
hpp
C++
Client/RoleSetup/General/include/RoleSetup/General/DebugConsole.hpp
siisgoo/siisty
66103c54e0d1b35b88177c290e2bf60012607309
[ "MIT" ]
null
null
null
Client/RoleSetup/General/include/RoleSetup/General/DebugConsole.hpp
siisgoo/siisty
66103c54e0d1b35b88177c290e2bf60012607309
[ "MIT" ]
null
null
null
Client/RoleSetup/General/include/RoleSetup/General/DebugConsole.hpp
siisgoo/siisty
66103c54e0d1b35b88177c290e2bf60012607309
[ "MIT" ]
null
null
null
#ifndef DEBUGCONSOLE_HPP #define DEBUGCONSOLE_HPP #include <QDialog> namespace Ui { class DebugConsole; } class DebugConsole : public QDialog { Q_OBJECT public: explicit DebugConsole(QWidget *parent = nullptr); ~DebugConsole(); private: Ui::DebugConsole *ui; }; #endif // DEBUGCONSOLE_HPP
13.521739
53
0.726688
siisgoo
57e9febb01126e6bf6c82b5f33496b94a69e01d9
50,487
cpp
C++
MK4duo/src/feature/tmc/tmc.cpp
DapDeveloper/MK4duo
385fdcd3cda94e73396dd12f23ff570c86d2eab5
[ "RSA-MD" ]
null
null
null
MK4duo/src/feature/tmc/tmc.cpp
DapDeveloper/MK4duo
385fdcd3cda94e73396dd12f23ff570c86d2eab5
[ "RSA-MD" ]
null
null
null
MK4duo/src/feature/tmc/tmc.cpp
DapDeveloper/MK4duo
385fdcd3cda94e73396dd12f23ff570c86d2eab5
[ "RSA-MD" ]
null
null
null
/** * MK4duo Firmware for 3D Printer, Laser and CNC * * Based on Marlin, Sprinter and grbl * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm * Copyright (C) 2019 Alberto Cotronei @MagoKimbra * * 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 3 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/>. * */ /** * tmc.cpp * * Copyright (C) 2019 Alberto Cotronei @MagoKimbra */ #include "../../../MK4duo.h" #if HAS_TRINAMIC #if HAVE_DRV(TMC2208) #include <HardwareSerial.h> #endif #if AXIS_HAS_TMC(X) MKTMC* stepperX = NULL; #endif #if AXIS_HAS_TMC(X2) MKTMC* stepperX2 = NULL; #endif #if AXIS_HAS_TMC(Y) MKTMC* stepperY = NULL; #endif #if AXIS_HAS_TMC(Y2) MKTMC* stepperY2 = NULL; #endif #if AXIS_HAS_TMC(Z) MKTMC* stepperZ = NULL; #endif #if AXIS_HAS_TMC(Z2) MKTMC* stepperZ2 = NULL; #endif #if AXIS_HAS_TMC(Z3) MKTMC* stepperZ3 = NULL; #endif #if AXIS_HAS_TMC(E0) MKTMC* stepperE0 = NULL; #endif #if AXIS_HAS_TMC(E1) MKTMC* stepperE1 = NULL; #endif #if AXIS_HAS_TMC(E2) MKTMC* stepperE2 = NULL; #endif #if AXIS_HAS_TMC(E3) MKTMC* stepperE3 = NULL; #endif #if AXIS_HAS_TMC(E4) MKTMC* stepperE4 = NULL; #endif #if AXIS_HAS_TMC(E5) MKTMC* stepperE5 = NULL; #endif TMC_Stepper tmc; /** Public Parameters */ /** Private Parameters */ uint16_t TMC_Stepper::report_status_interval = 0; /** Public Function */ void TMC_Stepper::init() { #if TMC_HAS_SPI init_cs_pins(); #endif #if HAVE_DRV(TMC2660) #if ENABLED(SOFT_SPI_TMC2660) #define _TMC2660_DEFINE(ST, L) stepper##ST = new MKTMC(L, ST##_CS_PIN, R_SENSE, TMC_SW_MOSI, TMC_SW_MISO, TMC_SW_SCK) #define TMC2660_DEFINE(ST) _TMC2660_DEFINE(ST, TMC_##ST##_LABEL) #else #define _TMC2660_DEFINE(ST, L) stepper##ST = new MKTMC(L, ST##_CS_PIN, R_SENSE) #define TMC2660_DEFINE(ST) _TMC2660_DEFINE(ST, TMC_##ST##_LABEL) #endif #if DISABLED(SOFT_SPI_TMC2130) SPI.begin(); #endif // Stepper objects of TMC2660 steppers used #if X_HAS_DRV(TMC2660) TMC2660_DEFINE(X); config(stepperX, X_STALL_SENSITIVITY); #endif #if X2_HAS_DRV(TMC2660) TMC2660_DEFINE(X2); config(stepperX2, X_STALL_SENSITIVITY); #endif #if Y_HAS_DRV(TMC2660) TMC2660_DEFINE(Y); config(stepperY, Y_STALL_SENSITIVITY); #endif #if Y2_HAS_DRV(TMC2660) TMC2660_DEFINE(Y2); config(stepperY2, Y_STALL_SENSITIVITY); #endif #if Z_HAS_DRV(TMC2660) TMC2660_DEFINE(Z); config(stepperZ, Z_STALL_SENSITIVITY); #endif #if Z2_HAS_DRV(TMC2660) TMC2660_DEFINE(Z2); config(stepperZ2, Z_STALL_SENSITIVITY); #endif #if Z3_HAS_DRV(TMC2660) TMC2660_DEFINE(Z3); config(stepperZ3, Z_STALL_SENSITIVITY); #endif #if E0_HAS_DRV(TMC2660) TMC2660_DEFINE(E0); config(stepperE0); #endif #if E1_HAS_DRV(TMC2660) TMC2660_DEFINE(E1); config(stepperE1); #endif #if E2_HAS_DRV(TMC2660) TMC2660_DEFINE(E2); config(stepperE2); #endif #if E3_HAS_DRV(TMC2660) TMC2660_DEFINE(E3); config(stepperE3); #endif #if E4_HAS_DRV(TMC2660) TMC2660_DEFINE(E4); config(stepperE4); #endif #if E5_HAS_DRV(TMC2660) TMC2660_DEFINE(E5); config(stepperE5); #endif TMC_ADV(); #elif HAVE_DRV(TMC2130) #if ENABLED(SOFT_SPI_TMC2130) #define _TMC2130_DEFINE(ST, L) stepper##ST = new MKTMC(L, ST##_CS_PIN, R_SENSE, SOFT_MOSI_PIN, SOFT_MISO_PIN, SOFT_SCK_PIN) #define TMC2130_DEFINE(ST) _TMC2130_DEFINE(ST, TMC_##ST##_LABEL) #else #define _TMC2130_DEFINE(ST, L) stepper##ST = new MKTMC(L, ST##_CS_PIN, R_SENSE) #define TMC2130_DEFINE(ST) _TMC2130_DEFINE(ST, TMC_##ST##_LABEL) #endif #if DISABLED(SOFT_SPI_TMC2130) SPI.begin(); #endif // Stepper objects of TMC2130 steppers used #if X_HAS_DRV(TMC2130) TMC2130_DEFINE(X); config(stepperX, X_STEALTHCHOP, X_STALL_SENSITIVITY); #endif #if X2_HAS_DRV(TMC2130) TMC2130_DEFINE(X2); config(stepperX2, X_STEALTHCHOP, X_STALL_SENSITIVITY); #endif #if Y_HAS_DRV(TMC2130) TMC2130_DEFINE(Y); config(stepperY, Y_STEALTHCHOP, Y_STALL_SENSITIVITY); #endif #if Y2_HAS_DRV(TMC2130) TMC2130_DEFINE(Y2); config(stepperY2, Y_STEALTHCHOP, Y_STALL_SENSITIVITY); #endif #if Z_HAS_DRV(TMC2130) TMC2130_DEFINE(Z); config(stepperZ, Z_STEALTHCHOP, Z_STALL_SENSITIVITY); #endif #if Z2_HAS_DRV(TMC2130) TMC2130_DEFINE(Z2); config(stepperZ2, Z_STEALTHCHOP, Z_STALL_SENSITIVITY); #endif #if Z3_HAS_DRV(TMC2130) TMC2130_DEFINE(Z3); config(stepperZ3, Z_STEALTHCHOP, Z_STALL_SENSITIVITY); #endif #if E0_HAS_DRV(TMC2130) TMC2130_DEFINE(E0); config(stepperE0, E0_STEALTHCHOP); #endif #if E1_HAS_DRV(TMC2130) TMC2130_DEFINE(E1); config(stepperE1, E1_STEALTHCHOP); #endif #if E2_HAS_DRV(TMC2130) TMC2130_DEFINE(E2); config(stepperE2, E2_STEALTHCHOP); #endif #if E3_HAS_DRV(TMC2130) TMC2130_DEFINE(E3); config(stepperE3, E3_STEALTHCHOP); #endif #if E4_HAS_DRV(TMC2130) TMC2130_DEFINE(E4); config(stepperE4, E4_STEALTHCHOP); #endif #if E5_HAS_DRV(TMC2130) TMC2130_DEFINE(E5); config(stepperE5, E5_STEALTHCHOP); #endif TMC_ADV(); #elif HAVE_DRV(TMC2208) #define _TMC2208_DEFINE_HARDWARE(ST, L) stepper##ST = new MKTMC(L, ST##_HARDWARE_SERIAL, R_SENSE) #define TMC2208_DEFINE_HARDWARE(ST) _TMC2208_DEFINE_HARDWARE(ST, TMC_##ST##_LABEL) #define _TMC2208_DEFINE_SOFTWARE(ST, L) stepper##ST = new MKTMC(L, ST##_SERIAL_RX_PIN, ST##_SERIAL_TX_PIN, R_SENSE, ST##_SERIAL_RX_PIN > -1) #define TMC2208_DEFINE_SOFTWARE(ST) _TMC2208_DEFINE_SOFTWARE(ST, TMC_##ST##_LABEL) // Stepper objects of TMC2208 steppers used #if X_HAS_DRV(TMC2208) #if ENABLED(X_HARDWARE_SERIAL) TMC2208_DEFINE_HARDWARE(X); X_HARDWARE_SERIAL.begin(115200); #else TMC2208_DEFINE_SOFTWARE(X); stepperX->beginSerial(115200); #endif config(stepperX, X_STEALTHCHOP); #endif #if X2_HAS_DRV(TMC2208) #if ENABLED(X2_HARDWARE_SERIAL) TMC2208_DEFINE_HARDWARE(X2); X2_HARDWARE_SERIAL.begin(115200); #else TMC2208_DEFINE_SOFTWARE(X2); stepperX2->beginSerial(115200); #endif config(stepperX2, X_STEALTHCHOP); #endif #if Y_HAS_DRV(TMC2208) #if ENABLED(Y_HARDWARE_SERIAL) TMC2208_DEFINE_HARDWARE(Y); Y_HARDWARE_SERIAL.begin(115200); #else TMC2208_DEFINE_SOFTWARE(Y); stepperY->beginSerial(115200); #endif config(stepperY, Y_STEALTHCHOP); #endif #if Y2_HAS_DRV(TMC2208) #if ENABLED(Y2_HARDWARE_SERIAL) TMC2208_DEFINE_HARDWARE(Y2); Y2_HARDWARE_SERIAL.begin(115200); #else TMC2208_DEFINE_SOFTWARE(Y2); stepperY2->beginSerial(115200); #endif config(stepperY2, Y_STEALTHCHOP); #endif #if Z_HAS_DRV(TMC2208) #if ENABLED(Z_HARDWARE_SERIAL) TMC2208_DEFINE_HARDWARE(Z); Z_HARDWARE_SERIAL.begin(115200); #else TMC2208_DEFINE_SOFTWARE(Z); stepperZ->beginSerial(115200); #endif config(stepperZ, Z_STEALTHCHOP); #endif #if Z2_HAS_DRV(TMC2208) #if ENABLED(Z2_HARDWARE_SERIAL) TMC2208_DEFINE_HARDWARE(Z2); Z2_HARDWARE_SERIAL.begin(115200); #else TMC2208_DEFINE_SOFTWARE(Z2); stepperZ2->beginSerial(115200); #endif config(stepperZ2, Z_STEALTHCHOP); #endif #if Z3_HAS_DRV(TMC2208) #if ENABLED(Z3_HARDWARE_SERIAL) TMC2208_DEFINE_HARDWARE(Z3); Z3_HARDWARE_SERIAL.begin(115200); #else TMC2208_DEFINE_SOFTWARE(Z3); stepperZ3->beginSerial(115200); #endif config(stepperZ3, Z_STEALTHCHOP); #endif #if E0_HAS_DRV(TMC2208) #if ENABLED(E0_HARDWARE_SERIAL) TMC2208_DEFINE_HARDWARE(E0); E0_HARDWARE_SERIAL.begin(115200); #else TMC2208_DEFINE_SOFTWARE(E0); stepperE0->beginSerial(115200); #endif config(stepperE0, E0_STEALTHCHOP); #endif #if E1_HAS_DRV(TMC2208) #if ENABLED(E1_HARDWARE_SERIAL) TMC2208_DEFINE_HARDWARE(E1); E1_HARDWARE_SERIAL.begin(115200); #else TMC2208_DEFINE_SOFTWARE(E1); stepperE1->beginSerial(115200); #endif config(stepperE1, E1_STEALTHCHOP); #endif #if E2_HAS_DRV(TMC2208) #if ENABLED(E2_HARDWARE_SERIAL) TMC2208_DEFINE_HARDWARE(E2); E2_HARDWARE_SERIAL.begin(115200); #else TMC2208_DEFINE_SOFTWARE(E2); stepperE2->beginSerial(115200); #endif config(stepperE2, E2_STEALTHCHOP); #endif #if E3_HAS_DRV(TMC2208) #if ENABLED(E3_HARDWARE_SERIAL) TMC2208_DEFINE_HARDWARE(E3); E3_HARDWARE_SERIAL.begin(115200); #else TMC2208_DEFINE_SOFTWARE(E3); stepperE3->beginSerial(115200); #endif config(stepperE3, E3_STEALTHCHOP); #endif #if E4_HAS_DRV(TMC2208) #if ENABLED(E4_HARDWARE_SERIAL) TMC2208_DEFINE_HARDWARE(E4); E4_HARDWARE_SERIAL.begin(115200); #else TMC2208_DEFINE_SOFTWARE(E4); stepperE4->beginSerial(115200); #endif config(stepperE4, E4_STEALTHCHOP); #endif #if E5_HAS_DRV(TMC2208) #if ENABLED(E5_HARDWARE_SERIAL) TMC2208_DEFINE_HARDWARE(E5); E5_HARDWARE_SERIAL.begin(115200); #else TMC2208_DEFINE_SOFTWARE(E5); stepperE5->beginSerial(115200); #endif config(stepperE5, E5_STEALTHCHOP); #endif #endif // HAVE_DRV(TMC2208) } // Use internal reference voltage for current calculations. This is the default. // Following values from Trinamic's spreadsheet with values for a NEMA17 (42BYGHW609) // https://www.trinamic.com/products/integrated-circuits/details/tmc2130/ void TMC_Stepper::current_init_to_defaults() { constexpr uint16_t tmc_stepper_current[TMC_AXIS] = { X_CURRENT, Y_CURRENT, Z_CURRENT, X_CURRENT, Y_CURRENT, Z_CURRENT, Z_CURRENT, E0_CURRENT, E1_CURRENT, E2_CURRENT, E3_CURRENT, E4_CURRENT, E5_CURRENT }; LOOP_TMC() { MKTMC* st = tmc.driver_by_index(t); if (st) st->rms_current(tmc_stepper_current[t]); } } void TMC_Stepper::microstep_init_to_defaults() { constexpr uint16_t tmc_stepper_microstep[TMC_AXIS] = { X_MICROSTEPS, Y_MICROSTEPS, Z_MICROSTEPS, X_MICROSTEPS, Y_MICROSTEPS, Z_MICROSTEPS, Z_MICROSTEPS, E0_MICROSTEPS, E1_MICROSTEPS, E2_MICROSTEPS, E3_MICROSTEPS, E4_MICROSTEPS, E5_MICROSTEPS }; LOOP_TMC() { MKTMC* st = tmc.driver_by_index(t); if (st) st->microsteps(tmc_stepper_microstep[t]); } } void TMC_Stepper::hybrid_threshold_init_to_defaults() { constexpr uint32_t tmc_hybrid_threshold[TMC_AXIS] = { X_HYBRID_THRESHOLD, Y_HYBRID_THRESHOLD, Z_HYBRID_THRESHOLD, X_HYBRID_THRESHOLD, Y_HYBRID_THRESHOLD, Z_HYBRID_THRESHOLD, Z_HYBRID_THRESHOLD, E0_HYBRID_THRESHOLD, E1_HYBRID_THRESHOLD, E2_HYBRID_THRESHOLD, E3_HYBRID_THRESHOLD, E4_HYBRID_THRESHOLD, E5_HYBRID_THRESHOLD }; LOOP_TMC() { MKTMC* st = tmc.driver_by_index(t); if (st) set_pwmthrs(st, tmc_hybrid_threshold[t], mechanics.data.axis_steps_per_mm[st->id]); } } void TMC_Stepper::restore() { LOOP_TMC() { MKTMC* st = tmc.driver_by_index(t); if (st) st->push(); } } void TMC_Stepper::test_connection(const bool test_x, const bool test_y, const bool test_z, const bool test_e) { uint8_t axis_connection = 0; if (test_x) { #if AXIS_HAS_TMC(X) axis_connection += test_connection(stepperX); #endif #if AXIS_HAS_TMC(X2) axis_connection += test_connection(stepperX2); #endif } if (test_y) { #if AXIS_HAS_TMC(Y) axis_connection += test_connection(stepperY); #endif #if AXIS_HAS_TMC(Y2) axis_connection += test_connection(stepperY2); #endif } if (test_z) { #if AXIS_HAS_TMC(Z) axis_connection += test_connection(stepperZ); #endif #if AXIS_HAS_TMC(Z2) axis_connection += test_connection(stepperZ2); #endif #if AXIS_HAS_TMC(Z3) axis_connection += test_connection(stepperZ3); #endif } if (test_e) { #if AXIS_HAS_TMC(E0) axis_connection += test_connection(stepperE0); #endif #if AXIS_HAS_TMC(E1) axis_connection += test_connection(stepperE1); #endif #if AXIS_HAS_TMC(E2) axis_connection += test_connection(stepperE2); #endif #if AXIS_HAS_TMC(E3) axis_connection += test_connection(stepperE3); #endif #if AXIS_HAS_TMC(E4) axis_connection += test_connection(stepperE4); #endif #if AXIS_HAS_TMC(E5) axis_connection += test_connection(stepperE5); #endif } if (axis_connection) lcdui.set_status_P(PSTR("TMC CONNECTION ERROR")); } #if ENABLED(MONITOR_DRIVER_STATUS) #define HAS_HW_COMMS(ST) ST##_HAS_DRV(TMC2130) || ST##_HAS_DRV(TMC2160) || ST##_HAS_DRV(TMC2660) || ST##_HAS_DRV(TMC5130) || (ST##_HAS_DRV(TMC2208) && ENABLED(ST##_HARDWARE_SERIAL)) void TMC_Stepper::monitor_driver() { static millis_t next_poll = 0; const millis_t ms = millis(); bool need_update_error_counters = ELAPSED(ms, next_poll); bool need_debug_reporting = false; if (need_update_error_counters) { next_poll = ms + MONITOR_DRIVER_STATUS_INTERVAL_MS; #if ENABLED(TMC_DEBUG) static millis_t next_debug_reporting = 0; if (report_status_interval && ELAPSED(ms, next_debug_reporting)) { need_debug_reporting = true; next_debug_reporting = ms + report_status_interval; } #endif if (need_update_error_counters || need_debug_reporting) { LOOP_TMC() { MKTMC* st = tmc.driver_by_index(t); if (st) monitor_driver(st, need_update_error_counters, need_debug_reporting); } #if ENABLED(TMC_DEBUG) if (need_debug_reporting) SERIAL_EOL(); #endif } } } #endif // ENABLED(MONITOR_DRIVER_STATUS) #if HAS_SENSORLESS bool TMC_Stepper::enable_stallguard(MKTMC* st) { bool old_stealthChop = st->en_pwm_mode(); st->TCOOLTHRS(0xFFFFF); st->en_pwm_mode(false); st->diag1_stall(true); return old_stealthChop; } void TMC_Stepper::disable_stallguard(MKTMC* st, const bool enable) { st->TCOOLTHRS(0); st->en_pwm_mode(enable); st->diag1_stall(false); } #endif #if ENABLED(TMC_DEBUG) /** * M922 [S<0|1>] [Pnnn] Enable periodic status reports */ #if ENABLED(MONITOR_DRIVER_STATUS) void TMC_Stepper::set_report_interval(const uint16_t update_interval) { if ((report_status_interval = update_interval)) { SERIAL_EM("axis:pwm_scale" #if TMC_HAS_STEALTHCHOP "/current_scale" #endif #if TMC_HAS_STALLGUARD "/mech_load" #endif "|flags|warncount" ); } } #endif /** * M922 report functions */ void TMC_Stepper::report_all(bool print_x, const bool print_y, const bool print_z, const bool print_e) { #define TMC_REPORT(LABEL, ITEM) do{ SERIAL_SM(ECHO, LABEL); debug_loop(ITEM, print_x, print_y, print_z, print_e); }while(0) #define DRV_REPORT(LABEL, ITEM) do{ SERIAL_SM(ECHO, LABEL); status_loop(ITEM, print_x, print_y, print_z, print_e); }while(0) TMC_REPORT("\t", TMC_CODES); TMC_REPORT("Enabled\t", TMC_ENABLED); TMC_REPORT("Set current", TMC_CURRENT); TMC_REPORT("RMS current", TMC_RMS_CURRENT); TMC_REPORT("MAX current", TMC_MAX_CURRENT); TMC_REPORT("Run current", TMC_IRUN); TMC_REPORT("Hold current", TMC_IHOLD); #if HAVE_DRV(TMC2160) || HAVE_DRV(TMC5160) TMC_REPORT("Global scaler", TMC_GLOBAL_SCALER); #endif TMC_REPORT("CS actual\t", TMC_CS_ACTUAL); TMC_REPORT("PWM scale", TMC_PWM_SCALE); TMC_REPORT("vsense\t", TMC_VSENSE); TMC_REPORT("stealthChop", TMC_STEALTHCHOP); TMC_REPORT("msteps\t", TMC_MICROSTEPS); TMC_REPORT("tstep\t", TMC_TSTEP); TMC_REPORT("pwm\threshold\t", TMC_TPWMTHRS); TMC_REPORT("[mm/s]\t", TMC_TPWMTHRS_MMS); TMC_REPORT("OT prewarn", TMC_OTPW); #if ENABLED(MONITOR_DRIVER_STATUS) TMC_REPORT("OT prewarn has\n" "been triggered", TMC_OTPW_TRIGGERED); #endif TMC_REPORT("off time\t", TMC_TOFF); TMC_REPORT("blank time", TMC_TBL); TMC_REPORT("hysteresis\n-end\t", TMC_HEND); TMC_REPORT("-start\t", TMC_HSTRT); TMC_REPORT("Stallguard thrs", TMC_SGT); DRV_REPORT("DRVSTATUS\t", TMC_DRV_CODES); #if HAVE_DRV(TMC2130) || HAVE_DRV(TMC2160) || HAVE_DRV(TMC5130) || HAVE_DRV(TMC5160) DRV_REPORT("stallguard\t", TMC_STALLGUARD); DRV_REPORT("sg_result\t", TMC_SG_RESULT); DRV_REPORT("fsactive\t", TMC_FSACTIVE); #endif DRV_REPORT("stst\t", TMC_STST); DRV_REPORT("olb\t", TMC_OLB); DRV_REPORT("ola\t", TMC_OLA); DRV_REPORT("s2gb\t", TMC_S2GB); DRV_REPORT("s2ga\t", TMC_S2GA); DRV_REPORT("otpw\t", TMC_DRV_OTPW); DRV_REPORT("ot\t", TMC_OT); #if HAVE_DRV(TMC2208) DRV_REPORT("157C\t", TMC_T157); DRV_REPORT("150C\t", TMC_T150); DRV_REPORT("143C\t", TMC_T143); DRV_REPORT("120C\t", TMC_T120); DRV_REPORT("s2vsa\t", TMC_S2VSA); DRV_REPORT("s2vsb\t", TMC_S2VSB); #endif DRV_REPORT("Driver registers:", TMC_DRV_STATUS_HEX); SERIAL_EOL(); } void TMC_Stepper::get_registers(bool print_x, bool print_y, bool print_z, bool print_e) { #define _TMC_GET_REG(LABEL, ITEM) do{ SERIAL_MSG(LABEL); get_registers(ITEM, print_x, print_y, print_z, print_e); }while(0) #define TMC_GET_REG(NAME, TABS) _TMC_GET_REG(STRINGIFY(NAME) TABS, TMC_GET_##NAME) _TMC_GET_REG("\t", TMC_AXIS_CODES); TMC_GET_REG(GCONF, "\t\t"); TMC_GET_REG(IHOLD_IRUN, "\t"); TMC_GET_REG(GSTAT, "\t\t"); TMC_GET_REG(IOIN, "\t\t"); TMC_GET_REG(TPOWERDOWN, "\t"); TMC_GET_REG(TSTEP, "\t\t"); TMC_GET_REG(TPWMTHRS, "\t"); TMC_GET_REG(TCOOLTHRS, "\t"); TMC_GET_REG(THIGH, "\t\t"); TMC_GET_REG(CHOPCONF, "\t"); TMC_GET_REG(COOLCONF, "\t"); TMC_GET_REG(PWMCONF, "\t"); TMC_GET_REG(PWM_SCALE, "\t"); TMC_GET_REG(DRV_STATUS, "\t"); } #endif // ENABLED(TMC_DEBUG) #if DISABLED(DISABLE_M503) void TMC_Stepper::print_M350() { SERIAL_LM(CFG, "Stepper driver microsteps"); #if AXIS_HAS_TMC(X) || AXIS_HAS_TMC(Y) || AXIS_HAS_TMC(Z) SERIAL_SM(CFG, " M350"); #if AXIS_HAS_TMC(X) SERIAL_MV(" X", stepperX->microsteps()); #endif #if AXIS_HAS_TMC(Y) SERIAL_MV(" Y", stepperY->microsteps()); #endif #if AXIS_HAS_TMC(Z) SERIAL_MV(" Z", stepperZ->microsteps()); #endif SERIAL_EOL(); #endif #if AXIS_HAS_TMC(E0) SERIAL_LMV(CFG, " M350 T0 E", stepperE0->microsteps()); #endif #if AXIS_HAS_TMC(E1) SERIAL_LMV(CFG, " M350 T1 E", stepperE1->microsteps()); #endif #if AXIS_HAS_TMC(E2) SERIAL_LMV(CFG, " M350 T2 E", stepperE2->microsteps()); #endif #if AXIS_HAS_TMC(E3) SERIAL_LMV(CFG, " M350 T3 E", stepperE3->microsteps()); #endif #if AXIS_HAS_TMC(E4) SERIAL_LMV(CFG, " M350 T4 E", stepperE4->microsteps()); #endif #if AXIS_HAS_TMC(E5) SERIAL_LMV(CFG, " M350 T5 E", stepperE5->microsteps()); #endif } void TMC_Stepper::print_M906() { SERIAL_LM(CFG, "Stepper driver current (mA)"); #if AXIS_HAS_TMC(X) || AXIS_HAS_TMC(Y) || AXIS_HAS_TMC(Z) SERIAL_SM(CFG, " M906"); #if AXIS_HAS_TMC(X) SERIAL_MV(" X", stepperX->getMilliamps()); #endif #if AXIS_HAS_TMC(Y) SERIAL_MV(" Y", stepperY->getMilliamps()); #endif #if AXIS_HAS_TMC(Z) SERIAL_MV(" Z", stepperZ->getMilliamps()); #endif SERIAL_EOL(); #endif #if AXIS_HAS_TMC(E0) SERIAL_LMV(CFG, " M906 T0 E", stepperE0->getMilliamps()); #endif #if AXIS_HAS_TMC(E1) SERIAL_LMV(CFG, " M906 T1 E", stepperE1->getMilliamps()); #endif #if AXIS_HAS_TMC(E2) SERIAL_LMV(CFG, " M906 T2 E", stepperE2->getMilliamps()); #endif #if AXIS_HAS_TMC(E3) SERIAL_LMV(CFG, " M906 T3 E", stepperE3->getMilliamps()); #endif #if AXIS_HAS_TMC(E4) SERIAL_LMV(CFG, " M906 T4 E", stepperE4->getMilliamps()); #endif #if AXIS_HAS_TMC(E5) SERIAL_LMV(CFG, " M906 T5 E", stepperE5->getMilliamps()); #endif } void TMC_Stepper::print_M913() { #if ENABLED(HYBRID_THRESHOLD) #define TMC_GET_PWMTHRS(ST) tmc_thrs(stepper##ST->microsteps(), stepper##ST->TPWMTHRS(), mechanics.data.axis_steps_per_mm[ST##_AXIS]) SERIAL_LM(CFG, "Stepper driver Hybrid Threshold"); #if AXIS_HAS_TMC(X) || AXIS_HAS_TMC(Y) || AXIS_HAS_TMC(Z) SERIAL_SM(CFG, " M913"); #if AXIS_HAS_TMC(X) SERIAL_MV(" X", TMC_GET_PWMTHRS(X)); #endif #if AXIS_HAS_TMC(Y) SERIAL_MV(" Y", TMC_GET_PWMTHRS(Y)); #endif #if AXIS_HAS_TMC(Z) SERIAL_MV(" Z", TMC_GET_PWMTHRS(Z)); #endif SERIAL_EOL(); #endif #if AXIS_HAS_TMC(E0) SERIAL_LMV(CFG, " M913 T0 E", TMC_GET_PWMTHRS(E0)); #endif #if AXIS_HAS_TMC(E1) SERIAL_LMV(CFG, " M913 T1 E", TMC_GET_PWMTHRS(E1)); #endif #if AXIS_HAS_TMC(E2) SERIAL_LMV(CFG, " M913 T2 E", TMC_GET_PWMTHRS(E2)); #endif #if AXIS_HAS_TMC(E3) SERIAL_LMV(CFG, " M913 T3 E", TMC_GET_PWMTHRS(E3)); #endif #if AXIS_HAS_TMC(E4) SERIAL_LMV(CFG, " M913 T4 E", TMC_GET_PWMTHRS(E4)); #endif #if AXIS_HAS_TMC(E5) SERIAL_LMV(CFG, " M913 T5 E", TMC_GET_PWMTHRS(E5)); #endif #endif // HYBRID_THRESHOLD } void TMC_Stepper::print_M914() { #if HAS_SENSORLESS SERIAL_LM(CFG, "Stepper driver StallGuard threshold:"); #if X_HAS_SENSORLESS || Y_HAS_SENSORLESS || Z_HAS_SENSORLESS SERIAL_SM(CFG, " M914"); #if X_HAS_SENSORLESS SERIAL_MV(" X", stepperX->sgt()); #endif #if Y_HAS_SENSORLESS SERIAL_MV(" Y", stepperY->sgt()); #endif #if Z_HAS_SENSORLESS SERIAL_MV(" Z", stepperZ->sgt()); #endif SERIAL_EOL(); #endif #endif // HAS_SENSORLESS } void TMC_Stepper::print_M940() { #if TMC_HAS_STEALTHCHOP SERIAL_LM(CFG, "Stepper driver StealthChop:"); SERIAL_SM(CFG, " M940"); #if AXIS_HAS_STEALTHCHOP(X) SERIAL_MV(" X", stepperX->get_stealthChop_status()); #endif #if AXIS_HAS_STEALTHCHOP(Y) SERIAL_MV(" Y", stepperY->get_stealthChop_status()); #endif #if AXIS_HAS_STEALTHCHOP(Z) SERIAL_MV(" Z", stepperZ->get_stealthChop_status()); #endif #if AXIS_HAS_STEALTHCHOP(E0) SERIAL_MV(" E", stepperE0->get_stealthChop_status()); #endif SERIAL_EOL(); #endif // TMC_HAS_STEALTHCHOP } #endif // DISABLED(DISABLE_M503) MKTMC* TMC_Stepper::driver_by_index(const uint8_t index) { switch (index) { #if AXIS_HAS_TMC(X) case 0: return stepperX; break; #endif #if AXIS_HAS_TMC(Y) case 1: return stepperY; break; #endif #if AXIS_HAS_TMC(Z) case 2: return stepperZ; break; #endif #if AXIS_HAS_TMC(X2) case 3: return stepperX2; break; #endif #if AXIS_HAS_TMC(Y2) case 4: return stepperY2; break; #endif #if AXIS_HAS_TMC(Z2) case 5: return stepperZ2; break; #endif #if AXIS_HAS_TMC(Z3) case 6: return stepperZ3; break; #endif #if AXIS_HAS_TMC(E0) case 7: return stepperE0; break; #endif #if AXIS_HAS_TMC(E1) case 8: return stepperE1; break; #endif #if AXIS_HAS_TMC(E2) case 9: return stepperE2; break; #endif #if AXIS_HAS_TMC(E3) case 10: return stepperE3; break; #endif #if AXIS_HAS_TMC(E4) case 11: return stepperE4; break; #endif #if AXIS_HAS_TMC(E5) case 12: return stepperE5; break; #endif default: return NULL; break; } } /** Private Function */ bool TMC_Stepper::test_connection(MKTMC* st) { SERIAL_MSG("Testing "); st->printLabel(); SERIAL_MSG(" connection... "); const uint8_t test_result = st->test_connection(); if (test_result > 0) SERIAL_MSG("Error: All "); const char *stat; switch (test_result) { default: case 0: stat = PSTR("OK"); break; case 1: stat = PSTR("HIGH"); break; case 2: stat = PSTR("LOW"); break; } SERIAL_STR(stat); SERIAL_EOL(); return test_result; } #if TMC_HAS_SPI void TMC_Stepper::init_cs_pins() { #if AXIS_HAS_SPI(X) OUT_WRITE(X_CS_PIN, HIGH); #endif #if AXIS_HAS_SPI(Y) OUT_WRITE(Y_CS_PIN, HIGH); #endif #if AXIS_HAS_SPI(Z) OUT_WRITE(Z_CS_PIN, HIGH); #endif #if AXIS_HAS_SPI(X2) OUT_WRITE(X2_CS_PIN, HIGH); #endif #if AXIS_HAS_SPI(Y2) OUT_WRITE(Y2_CS_PIN, HIGH); #endif #if AXIS_HAS_SPI(Z2) OUT_WRITE(Z2_CS_PIN, HIGH); #endif #if AXIS_HAS_SPI(Z3) OUT_WRITE(Z3_CS_PIN, HIGH); #endif #if AXIS_HAS_SPI(E0) OUT_WRITE(E0_CS_PIN, HIGH); #endif #if AXIS_HAS_SPI(E1) OUT_WRITE(E1_CS_PIN, HIGH); #endif #if AXIS_HAS_SPI(E2) OUT_WRITE(E2_CS_PIN, HIGH); #endif #if AXIS_HAS_SPI(E3) OUT_WRITE(E3_CS_PIN, HIGH); #endif #if AXIS_HAS_SPI(E4) OUT_WRITE(E4_CS_PIN, HIGH); #endif #if AXIS_HAS_SPI(E5) OUT_WRITE(E5_CS_PIN, HIGH); #endif } #endif // TMC_HAS_SPI #if HAVE_DRV(TMC2660) void TMC_Stepper::config(MKTMC* st, const int8_t sgt/*=0*/) { st->begin(); TMC2660_n::CHOPCONF_t chopconf{0}; chopconf.tbl = 1; chopconf.toff = chopper_timing.toff; chopconf.hend = chopper_timing.hend + 3; chopconf.hstrt = chopper_timing.hstrt - 1; st->CHOPCONF(chopconf.sr); st->intpol(INTERPOLATE); #if HAS_SENSORLESS st->sgt(sgt); homing_thrs = sgt; #endif st->diss2g(true); // Disable short to ground protection. Too many false readings? } #elif HAVE_DRV(TMC2130) void TMC_Stepper::config(MKTMC* st, const bool stealth/*=false*/, const int8_t sgt/*=0*/) { st->begin(); CHOPCONF_t chopconf{0}; chopconf.tbl = 1; chopconf.toff = chopper_timing.toff; chopconf.intpol = INTERPOLATE; chopconf.hend = chopper_timing.hend + 3; chopconf.hstrt = chopper_timing.hstrt - 1; st->CHOPCONF(chopconf.sr); st->iholddelay(10); st->TPOWERDOWN(128); st->en_pwm_mode(stealth); st->stealthChop_enabled = stealth; PWMCONF_t pwmconf{0}; pwmconf.pwm_freq = 0b01; // f_pwm = 2/683 f_clk pwmconf.pwm_autoscale = true; pwmconf.pwm_grad = 5; pwmconf.pwm_ampl = 180; st->PWMCONF(pwmconf.sr); #if HAS_SENSORLESS st->sgt(sgt); st->homing_thrs = sgt; #endif st->GSTAT(); // Clear GSTAT } #elif HAVE_DRV(TMC2208) void TMC_Stepper::config(MKTMC* st, const bool stealth/*=false*/) { TMC2208_n::GCONF_t gconf{0}; gconf.pdn_disable = true; // Use UART gconf.mstep_reg_select = true; // Select microsteps with UART gconf.i_scale_analog = false; gconf.en_spreadcycle = !stealth; st->GCONF(gconf.sr); st->stealthChop_enabled = stealth; TMC2208_n::CHOPCONF_t chopconf{0}; chopconf.tbl = 0b01; // blank_time = 24 chopconf.toff = chopper_timing.toff; chopconf.intpol = INTERPOLATE; chopconf.hend = chopper_timing.hend + 3; chopconf.hstrt = chopper_timing.hstrt - 1; st->CHOPCONF(chopconf.sr); st->iholddelay(10); st->TPOWERDOWN(128); TMC2208_n::PWMCONF_t pwmconf{0}; pwmconf.pwm_lim = 12; pwmconf.pwm_reg = 8; pwmconf.pwm_autograd = true; pwmconf.pwm_autoscale = true; pwmconf.pwm_freq = 0b01; pwmconf.pwm_grad = 14; pwmconf.pwm_ofs = 36; st->PWMCONF(pwmconf.sr); st->GSTAT(0b111); // Clear delay(200); } #endif #if ENABLED(MONITOR_DRIVER_STATUS) #if HAVE_DRV(TMC2660) TMC_driver_data TMC_Stepper::get_driver_data(MKTMC* st) { constexpr uint8_t STALL_GUARD_bp = 0; constexpr uint8_t OT_bp = 1, OTPW_bp = 2; constexpr uint8_t S2G_bm = 0b11000; constexpr uint8_t STST_bp = 7, SG_RESULT_sp = 10; constexpr uint32_t SG_RESULT_bm = 0xFFC00; // 10:19 TMC_driver_data data; data.drv_status = st->DRVSTATUS(); uint8_t spart = data.drv_status & 0xFF; data.is_otpw = !!(spart & _BV(OTPW_bp)); data.is_ot = !!(spart & _BV(OT_bp)); data.is_s2g = !!(data.drv_status & S2G_bm); #if ENABLED(TMC_DEBUG) data.is_stall = !!(spart & _BV(STALL_GUARD_bp)); data.is_standstill = !!(spart & _BV(STST_bp)); data.sg_result = (data.drv_status & SG_RESULT_bm) >> SG_RESULT_sp; data.sg_result_reasonable = true; #endif return data; } #elif HAS_TMCX1X0 TMC_driver_data TMC_Stepper::get_driver_data(MKTMC* st) { constexpr uint16_t SG_RESULT_bm = 0x3FF; // 0:9 constexpr uint8_t STEALTH_bp = 14, CS_ACTUAL_sb = 16; constexpr uint32_t CS_ACTUAL_bm = 0x1F0000; // 16:20 constexpr uint8_t STALL_GUARD_bp = 24, OT_bp = 25, OTPW_bp = 26; constexpr uint32_t S2G_bm = 0x18000000; constexpr uint8_t STST_bp = 31; TMC_driver_data data; data.drv_status = st->DRV_STATUS(); #ifdef __AVR__ // 8-bit optimization saves up to 70 bytes of PROGMEM per axis uint8_t spart; #if ENABLED(TMC_DEBUG) data.sg_result = data.drv_status & SG_RESULT_bm; spart = data.drv_status >> 8; data.is_stealth = !!(spart & _BV(STEALTH_bp - 8)); spart = data.drv_status >> 16; data.cs_actual = spart & (CS_ACTUAL_bm >> 16); #endif spart = data.drv_status >> 24; data.is_ot = !!(spart & _BV(OT_bp - 24)); data.is_otpw = !!(spart & _BV(OTPW_bp - 24)); data.is_s2g = !!(spart & (S2G_bm >> 24)); #if ENABLED(TMC_DEBUG) data.is_stall = !!(spart & _BV(STALL_GUARD_bp - 24)); data.is_standstill = !!(spart & _BV(STST_bp - 24)); data.sg_result_reasonable = !data.is_standstill; // sg_result has no reasonable meaning while standstill #endif #else // !__AVR__ data.is_ot = !!(data.drv_status & _BV(OT_bp)); data.is_otpw = !!(data.drv_status & _BV(OTPW_bp)); data.is_s2g = !!(data.drv_status & S2G_bm); #if ENABLED(TMC_DEBUG) data.sg_result = data.drv_status & SG_RESULT_bm; data.is_stealth = !!(data.drv_status & _BV(STEALTH_bp)); data.cs_actual = (data.drv_status & CS_ACTUAL_bm) >> CS_ACTUAL_sb; data.is_stall = !!(data.drv_status & _BV(STALL_GUARD_bp)); data.is_standstill = !!(data.drv_status & _BV(STST_bp)); data.sg_result_reasonable = !data.is_standstill; // sg_result has no reasonable meaning while standstill #endif #endif // !__AVR__ return data; } #elif HAVE_DRV(TMC2208) #if ENABLED(TMC_DEBUG) uint8_t TMC_Stepper::get_status_response(MKTMC* st, uint32_t drv_status) { uint8_t gstat = st->GSTAT(); uint8_t response = 0; response |= (drv_status >> (31 - 3)) & 0b1000; response |= gstat & 0b11; return response; } #endif TMC_driver_data TMC_Stepper::get_driver_data(MKTMC* st) { constexpr uint8_t OTPW_bp = 0, OT_bp = 1; constexpr uint8_t S2G_bm = 0b11110; // 2..5 constexpr uint8_t CS_ACTUAL_sb = 16; constexpr uint32_t CS_ACTUAL_bm = 0x1F0000; // 16:20 constexpr uint8_t STEALTH_bp = 30, STST_bp = 31; TMC_driver_data data; data.drv_status = st->DRV_STATUS(); data.is_otpw = !!(data.drv_status & _BV(OTPW_bp)); data.is_ot = !!(data.drv_status & _BV(OT_bp)); data.is_s2g = !!(data.drv_status & S2G_bm); #if ENABLED(TMC_DEBUG) #ifdef __AVR__ // 8-bit optimization saves up to 12 bytes of PROGMEM per axis uint8_t spart = data.drv_status >> 16; data.cs_actual = spart & (CS_ACTUAL_bm >> 16); spart = data.drv_status >> 24; data.is_stealth = !!(spart & _BV(STEALTH_bp - 24)); data.is_standstill = !!(spart & _BV(STST_bp - 24)); #else data.cs_actual = (data.drv_status & CS_ACTUAL_bm) >> CS_ACTUAL_sb; data.is_stealth = !!(data.drv_status & _BV(STEALTH_bp)); data.is_standstill = !!(data.drv_status & _BV(STST_bp)); #endif data.sg_result_reasonable = false; #endif return data; } #endif void TMC_Stepper::monitor_driver(MKTMC* st, const bool need_update_error_counters, const bool need_debug_reporting) { TMC_driver_data data = get_driver_data(st); if ((data.drv_status == 0xFFFFFFFF) || (data.drv_status == 0x0)) return; if (need_update_error_counters) { if (data.is_ot /* | data.s2ga | data.s2gb*/) st->error_count++; else if (st->error_count > 0) st->error_count--; #if ENABLED(STOP_ON_ERROR) if (st->error_count >= 10) { SERIAL_EOL(); st->printLabel(); SERIAL_MSG(" driver error detected: 0x"); SERIAL_EV(data.drv_status, HEX); if (data.is_ot) SERIAL_EM("overtemperature"); if (data.is_s2g) SERIAL_EM("coil short circuit"); #if ENABLED(TMC_DEBUG) report_all(true, true, true, true); #endif printer.kill(PSTR("Driver error")); } #endif // Report if a warning was triggered if (data.is_otpw && st->otpw_count == 0) { char timestamp[14]; duration_t elapsed = print_job_counter.duration(); (void)elapsed.toDigital(timestamp, true); SERIAL_EOL(); SERIAL_TXT(timestamp); SERIAL_MSG(": "); st->printLabel(); SERIAL_MSG(" driver overtemperature warning! ("); SERIAL_VAL(st->getMilliamps()); SERIAL_EM("mA)"); } #if CURRENT_STEP_DOWN > 0 // Decrease current if is_otpw is true and driver is enabled and there's been more than 4 warnings if (data.is_otpw && st->otpw_count > 4) { uint16_t I_rms = st->getMilliamps(); if (st->isEnabled() && I_rms > 100) { st->rms_current(I_rms - (CURRENT_STEP_DOWN)); #if ENABLED(REPORT_CURRENT_CHANGE) st->printLabel(); SERIAL_EMV(" current decreased to ", st->getMilliamps()); #endif } } #endif if (data.is_otpw) { st->otpw_count++; st->flag_otpw = true; } else if (st->otpw_count > 0) st->otpw_count = 0; } #if ENABLED(TMC_DEBUG) if (need_debug_reporting) { const uint32_t pwm_scale = get_pwm_scale(st); st->printLabel(); SERIAL_MV(":", pwm_scale); #if ENABLED(TMC_DEBUG) #if HAS_TMCX1X0 || HAVE_DRV(TMC2208) SERIAL_MV("/", data.cs_actual); #endif #if TMC_HAS_STALLGUARD SERIAL_CHR('/'); if (data.sg_result_reasonable) SERIAL_VAL(data.sg_result); else SERIAL_CHR('-'); #endif #endif SERIAL_CHR('|'); if (st->error_count) SERIAL_CHR('E'); // Error if (data.is_ot) SERIAL_CHR('O'); // Over-temperature if (data.is_otpw) SERIAL_CHR('W'); // over-temperature pre-Warning #if ENABLED(TMC_DEBUG) if (data.is_stall) SERIAL_CHR('G'); // stallGuard if (data.is_stealth) SERIAL_CHR('T'); // stealthChop if (data.is_standstill) SERIAL_CHR('I'); // standstIll #endif if (st->flag_otpw) SERIAL_CHR('F'); // otpw Flag SERIAL_CHR('|'); if (st->otpw_count > 0) SERIAL_VAL(st->otpw_count); SERIAL_CHR('\t'); } #endif } #endif // MONITOR_DRIVER_STATUS #if ENABLED(TMC_DEBUG) #define PRINT_TMC_REGISTER(REG_CASE) case TMC_GET_##REG_CASE: print_hex_long(st->REG_CASE(), ':'); break #if HAVE_DRV(TMC2660) void TMC_Stepper::status(MKTMC* st, const TMCdebugEnum i) {} void TMC_Stepper::parse_type_drv_status(MKTMC* st, const TMCdrvStatusEnum i) {} void TMC_Stepper::get_ic_registers(MKTMC* st, const TMCgetRegistersEnum i) {} void TMC_Stepper::get_registers(MKTMC* st, const TMCgetRegistersEnum i) { switch (i) { case TMC_AXIS_CODES: SERIAL_CHR('\t'); st->printLabel(); break; PRINT_TMC_REGISTER(DRVCONF); PRINT_TMC_REGISTER(DRVCTRL); PRINT_TMC_REGISTER(CHOPCONF); PRINT_TMC_REGISTER(DRVSTATUS); PRINT_TMC_REGISTER(SGCSCONF); PRINT_TMC_REGISTER(SMARTEN); default: SERIAL_CHR('\t'); break; } SERIAL_CHR('\t'); } #elif HAS_TMCX1X0 void TMC_Stepper::status(MKTMC* st, const TMCdebugEnum i) { switch (i) { case TMC_PWM_SCALE: SERIAL_VAL(st->PWM_SCALE()); break; case TMC_SGT: SERIAL_VAL(st->sgt()); break; case TMC_STEALTHCHOP: SERIAL_STR(st->en_pwm_mode() ? PSTR("true") : PSTR("false")); break; default: break; } } void TMC_Stepper::parse_type_drv_status(MKTMC* st, const TMCdrvStatusEnum i) { switch (i) { case TMC_STALLGUARD: if (st->stallguard()) SERIAL_CHR('X'); break; case TMC_SG_RESULT: SERIAL_VAL(st->sg_result()); break; case TMC_FSACTIVE: if (st->fsactive()) SERIAL_CHR('X'); break; case TMC_DRV_CS_ACTUAL: SERIAL_VAL(st->cs_actual()); break; default: break; } } void TMC_Stepper::get_ic_registers(MKTMC* st, const TMCgetRegistersEnum i) { switch (i) { PRINT_TMC_REGISTER(TCOOLTHRS); PRINT_TMC_REGISTER(THIGH); PRINT_TMC_REGISTER(COOLCONF); default: SERIAL_CHR('\t'); break; } } void TMC_Stepper::get_registers(MKTMC* st, const TMCgetRegistersEnum i) { switch (i) { case TMC_AXIS_CODES: SERIAL_CHR('\t'); st->printLabel(); break; PRINT_TMC_REGISTER(GCONF); PRINT_TMC_REGISTER(IHOLD_IRUN); PRINT_TMC_REGISTER(GSTAT); PRINT_TMC_REGISTER(IOIN); PRINT_TMC_REGISTER(TPOWERDOWN); PRINT_TMC_REGISTER(TSTEP); PRINT_TMC_REGISTER(TPWMTHRS); PRINT_TMC_REGISTER(CHOPCONF); PRINT_TMC_REGISTER(PWMCONF); PRINT_TMC_REGISTER(PWM_SCALE); PRINT_TMC_REGISTER(DRV_STATUS); default: get_ic_registers(st, i); break; } SERIAL_CHR('\t'); } #elif HAVE_DRV(TMC2208) void TMC_Stepper::status(MKTMC* st, const TMCdebugEnum i) { switch (i) { case TMC_PWM_SCALE: SERIAL_VAL(st->pwm_scale_sum()); break; case TMC_STEALTHCHOP: SERIAL_STR(st->stealth() ? PSTR("true") : PSTR("false")); break; case TMC_S2VSA: if (st->s2vsa()) SERIAL_CHR('X'); break; case TMC_S2VSB: if (st->s2vsb()) SERIAL_CHR('X'); break; default: break; } } void TMC_Stepper::parse_type_drv_status(MKTMC* st, const TMCdrvStatusEnum i) { switch (i) { case TMC_T157: if (st->t157()) SERIAL_CHR('X'); break; case TMC_T150: if (st->t150()) SERIAL_CHR('X'); break; case TMC_T143: if (st->t143()) SERIAL_CHR('X'); break; case TMC_T120: if (st->t120()) SERIAL_CHR('X'); break; case TMC_DRV_CS_ACTUAL: SERIAL_VAL(st->cs_actual()); break; default: break; } } void TMC_Stepper::get_ic_registers(MKTMC* st, const TMCgetRegistersEnum i) { SERIAL_CHR('\t'); } void TMC_Stepper::get_registers(MKTMC* st, const TMCgetRegistersEnum i) { switch (i) { case TMC_AXIS_CODES: SERIAL_CHR('\t'); st->printLabel(); break; PRINT_TMC_REGISTER(GCONF); PRINT_TMC_REGISTER(IHOLD_IRUN); PRINT_TMC_REGISTER(GSTAT); PRINT_TMC_REGISTER(IOIN); PRINT_TMC_REGISTER(TPOWERDOWN); PRINT_TMC_REGISTER(TSTEP); PRINT_TMC_REGISTER(TPWMTHRS); PRINT_TMC_REGISTER(CHOPCONF); PRINT_TMC_REGISTER(PWMCONF); PRINT_TMC_REGISTER(PWM_SCALE); PRINT_TMC_REGISTER(DRV_STATUS); default: get_ic_registers(st, i); break; } SERIAL_CHR('\t'); } #endif // HAVE_DRV(TMC2208) #if HAVE_DRV(TMC2660) void TMC_Stepper::status(MKTMC* st, const TMCdebugEnum i, const float spmm) { SERIAL_CHR('\t'); switch (i) { case TMC_CODES: st->printLabel(); break; case TMC_ENABLED: SERIAL_STR(st->isEnabled() ? PSTR("true") : PSTR("false")); break; case TMC_CURRENT: SERIAL_VAL(st->getMilliamps()); break; case TMC_RMS_CURRENT: SERIAL_VAL(st->rms_current()); break; case TMC_MAX_CURRENT: SERIAL_VAL((float)st->rms_current() * 1.41, 0); break; case TMC_IRUN: SERIAL_VAL(st->cs(), DEC); SERIAL_MSG("/31"); break; case TMC_VSENSE: SERIAL_STR(st->vsense() ? PSTR("1=.165") : PSTR("0=.310")); break; case TMC_MICROSTEPS: SERIAL_VAL(st->microsteps()); break; //case TMC_OTPW: SERIAL_STR(st->otpw() ? PSTR("true") : PSTR("false")); break; //case TMC_OTPW_TRIGGERED: SERIAL_STR(st->getOTPW() ? PSTR("true") : PSTR("false")); break; case TMC_SGT: SERIAL_VAL(st->sgt(), DEC); break; case TMC_TOFF: SERIAL_VAL(st->toff(), DEC); break; case TMC_TBL: SERIAL_VAL(st->blank_time(), DEC); break; case TMC_HEND: SERIAL_VAL(st->hysteresis_end(), DEC); break; case TMC_HSTRT: SERIAL_VAL(st->hysteresis_start(), DEC); break; default: break; } } #else void TMC_Stepper::status(MKTMC* st, const TMCdebugEnum i, const float spmm) { SERIAL_CHR('\t'); switch (i) { case TMC_CODES: st->printLabel(); break; case TMC_ENABLED: SERIAL_STR(st->isEnabled() ? PSTR("true") : PSTR("false")); break; case TMC_CURRENT: SERIAL_VAL(st->getMilliamps()); break; case TMC_RMS_CURRENT: SERIAL_VAL(st->rms_current()); break; case TMC_MAX_CURRENT: SERIAL_VAL((float)st->rms_current() * 1.41, 0); break; case TMC_IRUN: SERIAL_VAL(st->irun()); SERIAL_MSG("/31"); break; case TMC_IHOLD: SERIAL_VAL(st->ihold()); SERIAL_MSG("/31"); break; case TMC_CS_ACTUAL: SERIAL_VAL(st->cs_actual()); SERIAL_MSG("/31"); break; case TMC_VSENSE: print_vsense(st); break; case TMC_MICROSTEPS: SERIAL_VAL(st->microsteps()); break; case TMC_TSTEP: { uint32_t tstep_value = st->TSTEP(); if (tstep_value == 0xFFFFF) SERIAL_MSG("max"); else SERIAL_VAL(tstep_value); } break; case TMC_TPWMTHRS: { uint32_t tpwmthrs_val = st->TPWMTHRS(); SERIAL_VAL(tpwmthrs_val); } break; case TMC_TPWMTHRS_MMS: { uint32_t tpwmthrs_val = st->TPWMTHRS(); if (tpwmthrs_val) SERIAL_VAL(12650000UL * st->microsteps() / (256 * tpwmthrs_val * spmm)); else SERIAL_CHR('-'); } break; case TMC_OTPW: SERIAL_STR(st->otpw() ? PSTR("true") : PSTR("false")); break; #if ENABLED(MONITOR_DRIVER_STATUS) case TMC_OTPW_TRIGGERED: SERIAL_STR(st->getOTPW() ? PSTR("true") : PSTR("false")); break; #endif case TMC_TOFF: SERIAL_VAL(st->toff()); break; case TMC_TBL: SERIAL_VAL(st->blank_time()); break; case TMC_HEND: SERIAL_VAL(st->hysteresis_end()); break; case TMC_HSTRT: SERIAL_VAL(st->hysteresis_start()); break; default: status(st, i); break; } } #endif void TMC_Stepper::parse_drv_status(MKTMC* st, const TMCdrvStatusEnum i) { SERIAL_CHR('\t'); switch (i) { case TMC_DRV_CODES: st->printLabel(); break; case TMC_STST: if (st->stst()) SERIAL_CHR('X'); break; case TMC_OLB: if (st->olb()) SERIAL_CHR('X'); break; case TMC_OLA: if (st->ola()) SERIAL_CHR('X'); break; case TMC_S2GB: if (st->s2gb()) SERIAL_CHR('X'); break; case TMC_S2GA: if (st->s2ga()) SERIAL_CHR('X'); break; case TMC_DRV_OTPW: if (st->otpw()) SERIAL_CHR('X'); break; case TMC_OT: if (st->ot()) SERIAL_CHR('X'); break; case TMC_DRV_STATUS_HEX: { const uint32_t drv_status = st->DRV_STATUS(); SERIAL_CHR('\t'); st->printLabel(); SERIAL_CHR('\t'); print_hex_long(drv_status, ':'); if (drv_status == 0xFFFFFFFF || drv_status == 0) SERIAL_MSG("\t Bad response!"); SERIAL_EOL(); break; } default: parse_type_drv_status(st, i); break; } } void TMC_Stepper::debug_loop(const TMCdebugEnum i, const bool print_x, const bool print_y, const bool print_z, const bool print_e) { if (print_x) { #if AXIS_HAS_TMC(X) status(stepperX, i, mechanics.data.axis_steps_per_mm[X_AXIS]); #endif #if AXIS_HAS_TMC(X2) status(stepperX2, i, mechanics.data.axis_steps_per_mm[X_AXIS]); #endif } if (print_y) { #if AXIS_HAS_TMC(Y) status(stepperY, i, mechanics.data.axis_steps_per_mm[Y_AXIS]); #endif #if AXIS_HAS_TMC(Y2) status(stepperY2, i, mechanics.data.axis_steps_per_mm[Y_AXIS]); #endif } if (print_z) { #if AXIS_HAS_TMC(Z) status(stepperZ, i, mechanics.data.axis_steps_per_mm[Z_AXIS]); #endif #if AXIS_HAS_TMC(Z2) status(stepperZ2,i, mechanics.data.axis_steps_per_mm[Z_AXIS]); #endif #if AXIS_HAS_TMC(Z3) status(stepperZ3, i, mechanics.data.axis_steps_per_mm[Z_AXIS]); #endif } if (print_e) { #if AXIS_HAS_TMC(E0) status(stepperE0, i, mechanics.data.axis_steps_per_mm[E_AXIS_N(0)]); #endif #if AXIS_HAS_TMC(E1) status(stepperE1, i, mechanics.data.axis_steps_per_mm[E_AXIS_N(1)]); #endif #if AXIS_HAS_TMC(E2) status(stepperE2, i, mechanics.data.axis_steps_per_mm[E_AXIS_N(2)]); #endif #if AXIS_HAS_TMC(E3) status(stepperE3, i, mechanics.data.axis_steps_per_mm[E_AXIS_N(3)]); #endif #if AXIS_HAS_TMC(E4) status(stepperE4, i, mechanics.data.axis_steps_per_mm[E_AXIS_N(4)]); #endif #if AXIS_HAS_TMC(E5) status(stepperE5, i, mechanics.data.axis_steps_per_mm[E_AXIS_N(5)]); #endif } SERIAL_EOL(); } void TMC_Stepper::status_loop(const TMCdrvStatusEnum i, const bool print_x, const bool print_y, const bool print_z, const bool print_e) { if (print_x) { #if AXIS_HAS_TMC(X) parse_drv_status(stepperX, i); #endif #if AXIS_HAS_TMC(X2) parse_drv_status(stepperX2, i); #endif } if (print_y) { #if AXIS_HAS_TMC(Y) parse_drv_status(stepperY, i); #endif #if AXIS_HAS_TMC(Y2) parse_drv_status(stepperY2, i); #endif } if (print_z) { #if AXIS_HAS_TMC(Z) parse_drv_status(stepperZ, i); #endif #if AXIS_HAS_TMC(Z2) parse_drv_status(stepperZ2, i); #endif #if AXIS_HAS_TMC(Z3) parse_drv_status(stepperZ3, i); #endif } if (print_e) { #if AXIS_HAS_TMC(E0) parse_drv_status(stepperE0, i); #endif #if AXIS_HAS_TMC(E1) parse_drv_status(stepperE1, i); #endif #if AXIS_HAS_TMC(E2) parse_drv_status(stepperE2, i); #endif #if AXIS_HAS_TMC(E3) parse_drv_status(stepperE3, i); #endif #if AXIS_HAS_TMC(E4) parse_drv_status(stepperE4, i); #endif #if AXIS_HAS_TMC(E5) parse_drv_status(stepperE5, i); #endif } SERIAL_EOL(); } void TMC_Stepper::get_registers(const TMCgetRegistersEnum i, const bool print_x, const bool print_y, const bool print_z, const bool print_e) { if (print_x) { #if AXIS_HAS_TMC(X) get_registers(stepperX, i); #endif #if AXIS_HAS_TMC(X2) get_registers(stepperX2, i); #endif } if (print_y) { #if AXIS_HAS_TMC(Y) get_registers(stepperY, i); #endif #if AXIS_HAS_TMC(Y2) get_registers(stepperY2, i); #endif } if (print_z) { #if AXIS_HAS_TMC(Z) get_registers(stepperZ, i); #endif #if AXIS_HAS_TMC(Z2) get_registers(stepperZ2, i); #endif #if AXIS_HAS_TMC(Z3) get_registers(stepperZ3, i); #endif } if (print_e) { #if AXIS_HAS_TMC(E0) get_registers(stepperE0, i); #endif #if AXIS_HAS_TMC(E1) get_registers(stepperE1, i); #endif #if AXIS_HAS_TMC(E2) get_registers(stepperE2, i); #endif #if AXIS_HAS_TMC(E3) get_registers(stepperE3, i); #endif #if AXIS_HAS_TMC(E4) get_registers(stepperE4, i); #endif #if AXIS_HAS_TMC(E5) get_registers(stepperE5, i); #endif } SERIAL_EOL(); } #endif // TMC_DEBUG #endif // HAS_TRINAMIC
31.280669
184
0.622695
DapDeveloper
57eb25884e1da644a5f664841027b83bf269168e
4,660
cpp
C++
src/Library/Painters/MandelbrotPainter.cpp
aravindkrishnaswamy/rise
297d0339a7f7acd1418e322a30a21f44c7dbbb1d
[ "BSD-2-Clause" ]
1
2018-12-20T19:31:02.000Z
2018-12-20T19:31:02.000Z
src/Library/Painters/MandelbrotPainter.cpp
aravindkrishnaswamy/rise
297d0339a7f7acd1418e322a30a21f44c7dbbb1d
[ "BSD-2-Clause" ]
null
null
null
src/Library/Painters/MandelbrotPainter.cpp
aravindkrishnaswamy/rise
297d0339a7f7acd1418e322a30a21f44c7dbbb1d
[ "BSD-2-Clause" ]
null
null
null
////////////////////////////////////////////////////////////////////// // // MandelbrotPainter.cpp - Implementation of the Mandelbrot // Painter class // // Author: Aravind Krishnaswamy // Date of Birth: February 21, 2001 // Tabs: 4 // Comments: This implementation is similar to Dan McCormick's // from Swish // // License Information: Please see the attached LICENSE.TXT file // ////////////////////////////////////////////////////////////////////// #include "pch.h" #include "MandelbrotPainter.h" #include "../Utilities/SimpleInterpolators.h" #include "../Animation/KeyframableHelper.h" using namespace RISE; using namespace RISE::Implementation; MandelbrotPainter::MandelbrotPainter( const IPainter& cA_, const IPainter& cB_, const Scalar lower_x_, const Scalar upper_x_, const Scalar lower_y_, const Scalar upper_y_, const Scalar exp_ ) : a( cA_ ), b( cB_ ), lower_x( lower_x_ ), upper_x( upper_x_ ), lower_y( lower_y_ ), upper_y( upper_y_ ), x_range( upper_x - lower_x ), y_range( upper_y - lower_y ), exp( exp_ ), pInterp( 0 ) { pScalarInterp = new RealLinearInterpolator(); GlobalLog()->PrintNew( pScalarInterp, __FILE__, __LINE__, "Scalar Interpolator" ); pInterp = new LinearInterpolator<RISEPel>(); GlobalLog()->PrintNew( pInterp, __FILE__, __LINE__, "Color Interpolator" ); a.addref(); b.addref(); } MandelbrotPainter::~MandelbrotPainter( ) { safe_release( pScalarInterp ); safe_release( pInterp ); a.release(); b.release(); } static int count_mandelbrot_steps( const Scalar xn, const Scalar yn, const Scalar x, const Scalar y, const int count_so_far ) { const Scalar xnsq = xn * xn; const Scalar ynsq = yn * yn; const Scalar mag = xnsq + ynsq; if( count_so_far >= 256 ) { return count_so_far; } if( mag > 4 ) { return count_so_far; } return count_mandelbrot_steps( xnsq - ynsq + x, 2 * xn * yn + y, x, y, count_so_far + 1 ); } inline Scalar MandelbrotPainter::ComputeD( const RayIntersectionGeometric& ri ) const { const Scalar x = ri.ptCoord.x*x_range + lower_x; const Scalar y = ri.ptCoord.y*y_range + lower_y; const int count = count_mandelbrot_steps( x, y, x, y, 0 ); Scalar d = 1.0 - (count / 256.0); if( (exp > (1.0+NEARZERO)) || (exp < (1.0-NEARZERO)) ) { d = pow( d, exp ); } return d; } RISEPel MandelbrotPainter::GetColor( const RayIntersectionGeometric& ri ) const { return pInterp->InterpolateValues( a.GetColor(ri), b.GetColor(ri), ComputeD(ri) ); } Scalar MandelbrotPainter::GetColorNM( const RayIntersectionGeometric& ri, const Scalar nm ) const { return pScalarInterp->InterpolateValues( a.GetColorNM(ri,nm), b.GetColorNM(ri,nm), ComputeD(ri) ); } Scalar MandelbrotPainter::Evaluate( const Scalar x_, const Scalar y_ ) const { const Scalar x = x_*x_range + lower_x; const Scalar y = y_*y_range + lower_y; const int count = count_mandelbrot_steps( x, y, x, y, 0 ); Scalar d = 1.0 - (count / 256.0); if( (exp > (1.0+NEARZERO)) || (exp < (1.0-NEARZERO)) ) { d = pow( d, exp ); } return d; } static const unsigned int UPPERX_ID = 100; static const unsigned int LOWERX_ID = 101; static const unsigned int UPPERY_ID = 102; static const unsigned int LOWERY_ID = 103; static const unsigned int EXP_ID = 104; IKeyframeParameter* MandelbrotPainter::KeyframeFromParameters( const String& name, const String& value ) { IKeyframeParameter* p = 0; // Check the name and see if its something we recognize if( name == "xend" ) { p = new Parameter<Scalar>( atof(value.c_str()), UPPERX_ID ); } else if( name == "xstart" ) { p = new Parameter<Scalar>( atof(value.c_str()), LOWERX_ID ); } else if( name == "yend" ) { p = new Parameter<Scalar>( atof(value.c_str()), UPPERY_ID ); } else if( name == "ystart" ) { p = new Parameter<Scalar>( atof(value.c_str()), LOWERY_ID ); } else if( name == "exp" ) { p = new Parameter<Scalar>( atof(value.c_str()), EXP_ID ); } else { return 0; } GlobalLog()->PrintNew( p, __FILE__, __LINE__, "keyframe parameter" ); return p; } void MandelbrotPainter::SetIntermediateValue( const IKeyframeParameter& val ) { switch( val.getID() ) { case UPPERX_ID: { upper_x = *(Scalar*)val.getValue(); } break; case LOWERX_ID: { lower_x = *(Scalar*)val.getValue(); } break; case UPPERY_ID: { upper_y = *(Scalar*)val.getValue(); } break; case LOWERY_ID: { lower_y = *(Scalar*)val.getValue(); } break; case EXP_ID: { exp = *(Scalar*)val.getValue(); } break; } } void MandelbrotPainter::RegenerateData( ) { x_range = ( upper_x - lower_x ); y_range = ( upper_y - lower_y ); }
24.787234
125
0.648498
aravindkrishnaswamy
57ec0f74037278d25bf82a3262dc17af80de4b9f
1,141
cc
C++
test/mesh.cc
untaugh/geotree
4600a1cb4115094ed5c4c1500c6221a458e68be8
[ "MIT" ]
2
2018-07-27T00:58:07.000Z
2021-11-20T22:26:10.000Z
test/mesh.cc
untaugh/geotree
4600a1cb4115094ed5c4c1500c6221a458e68be8
[ "MIT" ]
null
null
null
test/mesh.cc
untaugh/geotree
4600a1cb4115094ed5c4c1500c6221a458e68be8
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include <Eigen/Core> #include "Mesh.h" #include "MeshFactory.h" namespace { using namespace Geotree; class MeshTest : public ::testing::Test { protected: }; TEST_F(MeshTest, getSegments) { MeshFactory factory; Mesh tetra = factory.tetra(1); std::vector<Segment> segments; tetra.getSegments(segments); EXPECT_EQ(segments.size(), 6); } TEST_F(MeshTest, boundingBox) { MeshFactory factory; Mesh tetra = factory.tetra(1); Cube box = tetra.boundingBox(); EXPECT_EQ(box.p0, Vector3d(0.0, 0.0, 0.0)); EXPECT_EQ(box.p1, Vector3d(1.0, 1.0, 1.0)); } TEST_F(MeshTest, boundingBoxNegative) { MeshFactory factory; Mesh tetra = factory.tetra(2); tetra.translate(Vector3d(-10, -20, -30)); Cube box = tetra.boundingBox(); EXPECT_EQ(box.p0, Vector3d(-10.0, -20.0, -30.0)); EXPECT_EQ(box.p1, Vector3d(-8.0, -18.0, -28.0)); } TEST_F(MeshTest, boundingBoxZero) { Mesh zero; Cube box = zero.boundingBox(); EXPECT_EQ(box.p0, Vector3d(0.0, 0.0, 0.0)); EXPECT_EQ(box.p1, Vector3d(0.0, 0.0, 0.0)); } }
20.017544
53
0.62489
untaugh
57f9dbdea06e52bd64d75779a06af8fa330a921d
1,407
cpp
C++
Laborator2/Problema2/Problema2/main.cpp
GeorgeDenis/oop-2022
45b026f762a85c4e683f413b5c785b7e8541de04
[ "MIT" ]
null
null
null
Laborator2/Problema2/Problema2/main.cpp
GeorgeDenis/oop-2022
45b026f762a85c4e683f413b5c785b7e8541de04
[ "MIT" ]
null
null
null
Laborator2/Problema2/Problema2/main.cpp
GeorgeDenis/oop-2022
45b026f762a85c4e683f413b5c785b7e8541de04
[ "MIT" ]
1
2022-02-23T16:38:17.000Z
2022-02-23T16:38:17.000Z
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include "Student.h" #include "global.h" int main() { Student denis; denis.set_name("Denis"); printf("Nume: %s \n", denis.get_name()); denis.set_gradeEnglish(9.5); denis.set_gradeMathematics(10); denis.set_gradeHistory(8.2); printf("Nota Engleza: %.2f \n", denis.get_gradeEnglish()); printf("Nota Matematica: %.2f \n", denis.get_gradeMathematics()); printf("Nota Istorie: %.2f \n", denis.get_gradeHistory()); printf("Media: %.3f \n", denis.average_grade()); Student marcel; marcel.set_name("Marcel"); printf("Nume: %s \n", marcel.get_name()); marcel.set_gradeEnglish(9.4); marcel.set_gradeMathematics(9); marcel.set_gradeHistory(8.3); printf("Nota Engleza: %.2f \n", marcel.get_gradeEnglish()); printf("Nota Matematica: %.2f \n", marcel.get_gradeMathematics()); printf("Nota Istorie: %.2f \n", marcel.get_gradeHistory()); printf("Media: %.3f \n", marcel.average_grade()); printf("Comparare nume: %d\n", comparatie_Name(denis, marcel)); printf("Comparare nota Engleza: %d\n", comparatie_gradeEnglish(denis, marcel)); printf("Comparare nota Matematica: %d\n", comparatie_gradeMathematics(denis, marcel)); printf("Comparare nota Istorie: %d\n", comparatie_gradeHistory(denis, marcel)); printf("Comparare medie: %d \n", comparatie_average(denis, marcel)); }
45.387097
90
0.683014
GeorgeDenis
57fbd29c39f03e3f842fe4dafd01f8cb9c7f6924
1,313
cpp
C++
13_CPP_CLASS_INHERITANCE.cpp
ugururesin/Cpp_Training
f111af0830ec1f77a00186335bd73b11a745ffdc
[ "BSD-3-Clause-Clear" ]
1
2020-05-30T21:03:02.000Z
2020-05-30T21:03:02.000Z
13_CPP_CLASS_INHERITANCE.cpp
ugururesin/Cpp-Training
f111af0830ec1f77a00186335bd73b11a745ffdc
[ "BSD-3-Clause-Clear" ]
null
null
null
13_CPP_CLASS_INHERITANCE.cpp
ugururesin/Cpp-Training
f111af0830ec1f77a00186335bd73b11a745ffdc
[ "BSD-3-Clause-Clear" ]
null
null
null
///////////////////////////////////////// // WELCOME TO C++ PROGRAMMING! - 2019 // ///////////////////////////////////////// /* This Code is Written By Ugur Uresin For training purposes! */ /* To compile the program: g++ filename.cpp -o executableName To execute the program: ./executableName */ // -------------------------------------------------- // // 13 - CLASS INHERITANCE // -------------------------------------------------- // //Example //The derived class with Student as base class class GradStudent : public Student { private: string degree; public: GradStudent(); void setDegree(string degreeIn); string getDegree(); }; /* In the line: class GradStudent: public Student The access control before the base class (in this case 'public') determines the access of the inherited class. There are three types of access control: public, private, and protected. Public Inheritance means all public members of the base class are accessible to the derived class Private Inheritance means all members of the base class are private to the derived class Protected Inheritance means all members of the base class are protected to the derived class. It is very rare to have a protected or private inheritance, the vast majority of the time inheritance is public.*/
31.261905
97
0.63214
ugururesin
520b6d1368defb9cbdffcb14068ec58e4d5dcf5c
3,937
hpp
C++
src/core/utils.hpp
llamerada-jp/colonio
8594d3131249eda59980faa281c353988469481a
[ "Apache-2.0" ]
5
2021-12-12T23:35:21.000Z
2022-01-09T22:01:53.000Z
src/core/utils.hpp
llamerada-jp/colonio
8594d3131249eda59980faa281c353988469481a
[ "Apache-2.0" ]
null
null
null
src/core/utils.hpp
llamerada-jp/colonio
8594d3131249eda59980faa281c353988469481a
[ "Apache-2.0" ]
1
2020-07-07T13:17:19.000Z
2020-07-07T13:17:19.000Z
/* * Copyright 2017 Yuji Ito <llamerada.jp@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #ifdef __clang__ # include <picojson.h> #else # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wmaybe-uninitialized" # include <picojson.h> # pragma GCC diagnostic pop #endif #include <cassert> #include <string> #include "colonio/error.hpp" namespace colonio { class Packet; #define colonio_error(CODE, FORMAT, ...) \ Error(false, CODE, Utils::format_string(FORMAT, 0, ##__VA_ARGS__), __LINE__, __FILE__) #define colonio_fatal(FORMAT, ...) \ Error(true, ErrorCode::UNDEFINED, Utils::format_string(FORMAT, 0, ##__VA_ARGS__), __LINE__, __FILE__) /** * THROW macro is helper function to throw exception with line number and file name. * @param FORMAT Format string of an exception message that similar to printf. */ #define colonio_throw_error(CODE, FORMAT, ...) \ throw Error(false, CODE, Utils::format_string(FORMAT, 0, ##__VA_ARGS__), __LINE__, __FILE__) /** * FATAL macro is helper function to throw fatal exception. * @param FORMAT Format string of an exception message that similar to printf. */ #define colonio_throw_fatal(FORMAT, ...) \ throw Error(true, ErrorCode::UNDEFINED, Utils::format_string(FORMAT, 0, ##__VA_ARGS__), __LINE__, __FILE__) namespace Utils { std::string format_string(const std::string& format, int dummy, ...); template<typename T> bool check_json_optional(const picojson::object& obj, const std::string& key, T* dst) { auto it = obj.find(key); if (it == obj.end() || it->second.is<picojson::null>()) { return false; } else if (it->second.is<T>()) { *dst = it->second.get<T>(); return true; } else { assert(false); return false; } } template<> bool check_json_optional<unsigned int>(const picojson::object& obj, const std::string& key, unsigned int* dst); template<typename T> T get_json(const picojson::object& obj, const std::string& key) { auto it = obj.find(key); if (it != obj.end() && it->second.is<T>()) { return it->second.get<T>(); } else { colonio_throw_fatal( "Key dose not exist in JSON.(key : %s, json : %s)", key.c_str(), picojson::value(obj).serialize().c_str()); } } template<typename T> T get_json(const picojson::object& obj, const std::string& key, const T& default_value) { auto it = obj.find(key); if (it != obj.end() && it->second.is<T>()) { return it->second.get<T>(); } else { return default_value; } } template<> unsigned int get_json<unsigned int>(const picojson::object& obj, const std::string& key, const unsigned int& default_value); template<typename F> class Defer { public: explicit Defer(F func) : func(func) { } ~Defer() { func(); } private: F func; }; template<typename F> static Defer<F> defer(F func) { return Defer<F>(func); } std::string dump_binary(const std::string* bin); std::string dump_packet(const Packet& packet, unsigned int indent = 2); int64_t get_current_msec(); template<typename T> const T* get_json_value(const picojson::object& parent, const std::string& key) { auto it = parent.find(key); if (it == parent.end()) { return nullptr; } else { return &(it->second.get<T>()); } } std::string file_basename(const std::string& path, bool cutoff_ext = false); bool is_safevalue(double v); double float_mod(double a, double b); } // namespace Utils } // namespace colonio
28.323741
115
0.693167
llamerada-jp
648ab73a2ab6af742aa32d86c1e8a899421f7ef4
606
cpp
C++
p1.cpp
darksidergod/CompetitiveProgramming
ea0ee53bddd87e41b4586dd30c1d4a6b8ae3a93a
[ "MIT" ]
null
null
null
p1.cpp
darksidergod/CompetitiveProgramming
ea0ee53bddd87e41b4586dd30c1d4a6b8ae3a93a
[ "MIT" ]
null
null
null
p1.cpp
darksidergod/CompetitiveProgramming
ea0ee53bddd87e41b4586dd30c1d4a6b8ae3a93a
[ "MIT" ]
1
2020-10-03T19:48:05.000Z
2020-10-03T19:48:05.000Z
#include <bits/stdc++.h> #include <cmath> using namespace std; #define mod 1000000007 #define int long long int #define pb push_back #define mk make_pair #define flp(i, k, n) for(int i=k; i<n; i++) #define rev(i, k) for(int i=k; i>=0; i--) #define F first #define S second #define pi pair<int, int> #define IOS ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define SIZE (int)(6e5) int dx[4] = {-1,1,0,0}; int dy[4] = {0,0,-1,1}; int res=0; int32_t main(void) { int t=1; cin>>t; while(t--) { int n; cin>>n; cout<<(n+1)/2<<"\n"; } return 0; }
20.2
74
0.594059
darksidergod
648efe473e6261dabd931ef116fd7e153d5e5025
2,734
cpp
C++
libs/lwwx/samples/generic_ui/genericuimainwindow.cpp
hajokirchhoff/litwindow
7f574d4e80ee8339ac11c35f075857c20391c223
[ "MIT", "BSD-3-Clause" ]
null
null
null
libs/lwwx/samples/generic_ui/genericuimainwindow.cpp
hajokirchhoff/litwindow
7f574d4e80ee8339ac11c35f075857c20391c223
[ "MIT", "BSD-3-Clause" ]
1
2017-01-07T09:44:20.000Z
2017-01-07T09:44:20.000Z
libs/lwwx/samples/generic_ui/genericuimainwindow.cpp
hajokirchhoff/litwindow
7f574d4e80ee8339ac11c35f075857c20391c223
[ "MIT", "BSD-3-Clause" ]
null
null
null
/* * Copyright 2004, Hajo Kirchhoff - Lit Window Productions, http://www.litwindow.com * This file is part of the Lit Window Library. All use of this material - copying * in full or part, including in other works, using in non-profit or for-profit work * and other uses - is governed by the licence contained in the Lit Window Library * distribution, file LICENCE.TXT * $Id: genericuimainwindow.cpp,v 1.1.1.1 2006/01/16 14:36:45 Hajo Kirchhoff Exp $ */ #include "stdwx.h" ///////////////////////////////////////////////////////////////////////////// // Name: genericuimainwindow.cpp // Purpose: // Author: Hajo Kirchhoff // Modified by: // Created: 05/14/04 09:09:51 // RCS-ID: // Copyright: Copyright 2004, Hajo Kirchhoff, Lit Window Productions // Licence: ///////////////////////////////////////////////////////////////////////////// #if defined(__GNUG__) && !defined(__APPLE__) #pragma implementation "genericuimainwindow.h" #endif // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif ////@begin includes ////@end includes #include "genericuimainwindow.h" ////@begin XPM images ////@end XPM images /*! * GenericUIMainWindow type definition */ IMPLEMENT_CLASS( GenericUIMainWindow, wxFrame ) /*! * GenericUIMainWindow event table definition */ BEGIN_EVENT_TABLE( GenericUIMainWindow, wxFrame ) ////@begin GenericUIMainWindow event table entries ////@end GenericUIMainWindow event table entries END_EVENT_TABLE() /*! * GenericUIMainWindow constructors */ GenericUIMainWindow::GenericUIMainWindow( ) { } GenericUIMainWindow::GenericUIMainWindow( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { Create( parent, id, caption, pos, size, style ); } /*! * GenericUIMainWindow creator */ bool GenericUIMainWindow::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { ////@begin GenericUIMainWindow member initialisation ////@end GenericUIMainWindow member initialisation ////@begin GenericUIMainWindow creation SetParent(parent); CreateControls(); Centre(); ////@end GenericUIMainWindow creation return TRUE; } /*! * Control creation for GenericUIMainWindow */ void GenericUIMainWindow::CreateControls() { ////@begin GenericUIMainWindow content construction wxXmlResource::Get()->LoadFrame(this, GetParent(), _T("ID_FRAME")); ////@end GenericUIMainWindow content construction } /*! * Should we show tooltips? */ bool GenericUIMainWindow::ShowToolTips() { return TRUE; }
24.630631
152
0.68398
hajokirchhoff
6490c6a9b18e4dfe5469833938e7dd48b24cd313
25,006
cpp
C++
code/contrafold/src/Contrafold.cpp
jialiasus2/RNA-Contest-2021
d8cd340061ac7a70e1c2bba67d36c89cbde2555c
[ "Apache-2.0" ]
null
null
null
code/contrafold/src/Contrafold.cpp
jialiasus2/RNA-Contest-2021
d8cd340061ac7a70e1c2bba67d36c89cbde2555c
[ "Apache-2.0" ]
null
null
null
code/contrafold/src/Contrafold.cpp
jialiasus2/RNA-Contest-2021
d8cd340061ac7a70e1c2bba67d36c89cbde2555c
[ "Apache-2.0" ]
null
null
null
///////////////////////////////////////////////////////////////// // Contrafold.cpp ///////////////////////////////////////////////////////////////// // include files #ifdef MULTI #include <mpi.h> #endif #include "Config.hpp" #include "Options.hpp" #include "Utilities.hpp" #include "ComputationWrapper.hpp" #include "FileDescription.hpp" #include "InferenceEngine.hpp" #include "ParameterManager.hpp" #include "OptimizationWrapper.hpp" // constants const double GAMMA_DEFAULT = 6; const double REGULARIZATION_DEFAULT = 0; // function prototypes void Usage(const Options &options); void Version(); void ParseArguments(int argc, char **argv, Options &options, std::vector<std::string> &filenames); void MakeFileDescriptions(const Options &options, const std::vector<std::string> &filenames, std::vector<FileDescription> &descriptions); template<class RealT> void RunGradientSanityCheck(const Options &options, const std::vector<FileDescription> &descriptions); template<class RealT> void RunTrainingMode(const Options &options, const std::vector<FileDescription> &descriptions); template<class RealT> void RunPredictionMode(const Options &options, const std::vector<FileDescription> &descriptions); // default parameters #include "Defaults.ipp" ///////////////////////////////////////////////////////////////// // main() // // Main program. ///////////////////////////////////////////////////////////////// int main(int argc, char **argv) { #ifdef MULTI MPI_Init(&argc, &argv); #endif // first, parse arguments Options options; std::vector<std::string> filenames; ParseArguments(argc, argv, options, filenames); // second, read input files std::vector<FileDescription> descriptions; MakeFileDescriptions(options, filenames, descriptions); // perform required task if (options.GetBoolValue("gradient_sanity_check")) { RunGradientSanityCheck<double>(options, descriptions); } else if (options.GetBoolValue("training_mode")) { RunTrainingMode<double>(options, descriptions); } else { RunPredictionMode<float>(options, descriptions); } #ifdef MULTI MPI_Finalize(); #endif } ///////////////////////////////////////////////////////////////// // Usage() // // Display program usage. ///////////////////////////////////////////////////////////////// void Usage(const Options &options) { std::cerr << std::endl << "Usage: contrafold [predict|train] [OPTION]... INFILE(s)" << std::endl << std::endl << " where [OPTION]... is a list of zero or more optional arguments" << std::endl << " INFILE(s) is the name of the input BPSEQ, plain text, or FASTA file(s)" << std::endl << std::endl << "Miscellaneous arguments:" << std::endl << " --version display program version information" << std::endl << " --verbose show detailed console output" << std::endl << " --logbase LOG_BASE set base of log-sum-exp" << std::endl << " --viterbi use Viterbi instead of posterior decoding for prediction, " << std::endl << " or max-margin instead of log-likelihood for training" << std::endl << " --noncomplementary allow non-{AU,CG,GU} pairs" << std::endl << std::endl << "Additional arguments for 'predict' mode:" << std::endl << " --params FILENAME use particular model parameters" << std::endl << " --constraints use existing constraints (requires BPSEQ or FASTA format input)" << std::endl << " --gamma GAMMA set sensivity/specificity tradeoff parameter (default: GAMMA=" << options.GetRealValue("gamma") << ")" << std::endl << " if GAMMA > 1, emphasize sensitivity" << std::endl << " if 0 <= GAMMA <= 1, emphasize specificity" << std::endl << " if GAMMA < 0, try tradeoff parameters of 2^k for k = -5,...,10" << std::endl << std::endl << " --parens OUTFILEORDIR write parenthesized output to file or directory" << std::endl << " --bpseq OUTFILEORDIR write BPSEQ output to file or directory" << std::endl << " --posteriors CUTOFF OUTFILEORDIR" << std::endl << " write posterior pairing probabilities to file or directory" << std::endl << " --partition compute the partition function or Viterbi score only" << std::endl << std::endl << "Additional arguments for training (many input files may be specified):" << std::endl << " --sanity perform gradient sanity check" << std::endl << " --holdout F use fraction F of training data for holdout cross-validation" << std::endl << " --regularize C perform BFGS training, using a single regularization coefficient C" << std::endl << std::endl; exit(0); } ///////////////////////////////////////////////////////////////// // Version() // // Display program version. ///////////////////////////////////////////////////////////////// void Version() { #if PROFILE std::cerr << "CONTRAFold(m) version 2.01 - Multiple sequence RNA secondary structure prediction" << std::endl << std::endl #else std::cerr << "CONTRAFold version 2.01 - RNA secondary structure prediction" << std::endl << std::endl #endif << "Written by Chuong B. Do" << std::endl; exit(0); } ///////////////////////////////////////////////////////////////// // ParseArguments() // // Parse command line parameters. ///////////////////////////////////////////////////////////////// void ParseArguments(int argc, char **argv, Options &options, std::vector<std::string> &filenames) { // register default options options.SetBoolValue("training_mode", false); options.SetBoolValue("verbose_output", false); options.SetRealValue("log_base", 1.0); options.SetBoolValue("viterbi_parsing", false); options.SetBoolValue("allow_noncomplementary", false); options.SetStringValue("parameter_filename", ""); options.SetBoolValue("use_constraints", false); options.SetRealValue("gamma", GAMMA_DEFAULT); options.SetStringValue("output_parens_destination", ""); options.SetStringValue("output_bpseq_destination", ""); options.SetRealValue("output_posteriors_cutoff", 0); options.SetStringValue("output_posteriors_destination", ""); options.SetBoolValue("partition_function_only", false); options.SetBoolValue("gradient_sanity_check", false); options.SetRealValue("holdout_ratio", 0); options.SetRealValue("regularization_coefficient", REGULARIZATION_DEFAULT); // check for sufficient arguments if (argc < 2) Usage(options); filenames.clear(); // check for prediction or training mode if (!strcmp(argv[1], "train")) options.SetBoolValue("training_mode", true); else if (strcmp(argv[1], "predict")) Error("CONTRAfold must be run in either 'predict' or 'train' mode."); // go through remaining arguments for (int argno = 2; argno < argc; argno++) { // parse optional arguments if (argv[argno][0] == '-') { // miscellaneous options if (!strcmp(argv[argno], "--version")) { Version(); } else if (!strcmp(argv[argno], "--verbose")) { options.SetBoolValue("verbose_output", true); } else if (!strcmp(argv[argno], "--logbase")) { if (argno == argc - 1) Error("Must specify log base LOG_BASE after --logbase."); double value; if (!ConvertToNumber(argv[++argno], value)) Error("Unable to parse log base."); if (value <= 0) Error("Log base must be positive."); options.SetRealValue("log_base", value); } else if (!strcmp(argv[argno], "--viterbi")) { options.SetBoolValue("viterbi_parsing", true); } else if (!strcmp(argv[argno], "--noncomplementary")) { options.SetBoolValue("allow_noncomplementary", true); } // prediction options else if (!strcmp(argv[argno], "--params")) { if (argno == argc - 1) Error("Must specify FILENAME after --params."); options.SetStringValue("parameter_filename", argv[++argno]); } else if (!strcmp(argv[argno], "--constraints")) { options.SetBoolValue("use_constraints", true); } else if (!strcmp(argv[argno], "--gamma")) { if (argno == argc - 1) Error("Must specify trade-off parameter GAMMA after --gamma."); double value; if (!ConvertToNumber(argv[++argno], value)) Error("Unable to parse value after --gamma."); options.SetRealValue("gamma", value); } else if (!strcmp(argv[argno], "--parens")) { if (argno == argc - 1) Error("Must specify output file or directory name after --parens."); options.SetStringValue("output_parens_destination", argv[++argno]); } else if (!strcmp(argv[argno], "--bpseq")) { if (argno == argc - 1) Error("Must specify output file or directory name after --bpseq."); options.SetStringValue("output_bpseq_destination", argv[++argno]); } else if (!strcmp(argv[argno], "--posteriors")) { if (argno == argc - 1) Error("Must specify posterior probability threshold CUTOFF after --posteriors."); double value; if (!ConvertToNumber(argv[++argno], value)) Error("Unable to parse cutoff value after --posteriors."); options.SetRealValue("output_posteriors_cutoff", value); if (argno == argc - 1) Error("Must specify output file or directory for --posteriors."); options.SetStringValue("output_posteriors_destination", argv[++argno]); } else if (!strcmp(argv[argno], "--partition")) { options.SetBoolValue("partition_function_only", true); } // training options else if (!strcmp(argv[argno], "--sanity")) { options.SetBoolValue("gradient_sanity_check", true); } else if (!strcmp(argv[argno], "--holdout")) { if (argno == argc - 1) Error("Must specify holdout ratio F after --holdout."); double value; if (!ConvertToNumber(argv[++argno], value)) Error("Unable to parse holdout ratio."); if (value < 0 || value > 1) Error("Holdout ratio must be between 0 and 1."); options.SetRealValue("holdout_ratio", value); } else if (!strcmp(argv[argno], "--regularize")) { if (argno == argc - 1) Error("Must specify regularization parameter C after --regularize."); double value; if (!ConvertToNumber(argv[++argno], value)) Error("Unable to parse regularization parameter after --regularize."); if (value < 0) Error("Regularization parameter should not be negative."); options.SetRealValue("regularization_coefficient", value); } else { Error("Unknown option \"%s\" specified. Run program without any arguments to see command-line options.", argv[argno]); } } else { filenames.push_back(argv[argno]); } } // ensure that at least one input file specified if (filenames.size() == 0) Error("No filenames specified."); // check to make sure that arguments make sense if (options.GetBoolValue("training_mode")) { if (options.GetStringValue("parameter_filename") != "") Error("Should not specify parameter file for training mode."); if (options.GetBoolValue("use_constraints")) Error("The --constraints flag has no effect in training mode."); if (options.GetRealValue("gamma") != GAMMA_DEFAULT) Error("Gamma parameter should not be specified in training mode."); if (options.GetStringValue("output_parens_destination") != "") Error("The --parens option cannot be used in training mode."); if (options.GetStringValue("output_bpseq_destination") != "") Error("The --bpseq option cannot be used in training mode."); if (options.GetStringValue("output_posteriors_destination") != "" || options.GetRealValue("output_posteriors_cutoff") != 0) Error("The --posteriors option cannot be used in training mode."); if (options.GetBoolValue("partition_function_only")) Error("The --partition flag cannot be used in training mode."); if (options.GetRealValue("regularization_coefficient") != REGULARIZATION_DEFAULT && options.GetRealValue("holdout_ratio") > 0) Error("The --holdout and --regularize options cannot be specified simultaneously."); } else { if (options.GetRealValue("gamma") < 0 && options.GetStringValue("output_parens_destination") == "" && options.GetStringValue("output_bpseq_destination") == "" && options.GetStringValue("output_posteriors_destination") == "") Error("Output directory must be specified when using GAMMA < 0."); #ifdef MULTI if (filenames.size() > 1 && options.GetStringValue("output_parens_destination") == "" && options.GetStringValue("output_bpseq_destination") == "" && options.GetStringValue("output_posteriors_destination") == "") Error("Output directory must be specified when performing predictions for multiple input files."); #endif if (options.GetBoolValue("viterbi_parsing") && options.GetStringValue("output_posteriors_destination") != "") Error("The --posteriors option cannot be used with Viterbi parsing."); } } ///////////////////////////////////////////////////////////////// // MakeFileDescriptions() // // Build file descriptions ///////////////////////////////////////////////////////////////// void MakeFileDescriptions(const Options &options, const std::vector<std::string> &filenames, std::vector<FileDescription> &descriptions) { descriptions.clear(); for (size_t i = 0; i < filenames.size(); i++) { auto format = SStruct::AnalyzeFormat(filenames[i]); if(format == SStruct::FileFormat_FASTA){ //TODO: read multi line auto seq = SStruct::SplitFASTA(filenames[i]); // printf("Get %lu data items.\n", seq.size()); for(auto &content:seq){ descriptions.push_back(FileDescription(filenames[i], content, format, options.GetBoolValue("allow_noncomplementary"))); } } else { descriptions.push_back(FileDescription(filenames[i], options.GetBoolValue("allow_noncomplementary"))); } } // printf("MakeFileDescriptions over, description size is %lu\n", descriptions.size()); // std::sort(descriptions.begin(), descriptions.end()); } ///////////////////////////////////////////////////////////////// // RunGradientSanityCheck() // // Compute gradient sanity check. ///////////////////////////////////////////////////////////////// template<class RealT> void RunGradientSanityCheck(const Options &options, const std::vector<FileDescription> &descriptions) { // The architecture of the code is somewhat complicated here, so // here's a quick explanation: // // ParameterManager: associates each parameter of the model // with a name and manages hyperparameter // groups // // InferenceEngine: performs application-specific // (loss-augmented) inference // // ComputationEngine: makes all necessary calls to dynamic // programming routines for processing // individual sequences and interfaces with // distributed computation module // // ComputationWrapper: provides a high-level interface for // performing computations on groups of // sequences // // OuterOptimizationWrapper / InnerOptimizationWrapper: // interface between computation routines // and optimization routines ParameterManager<RealT> parameter_manager; InferenceEngine<RealT> inference_engine(options.GetBoolValue("allow_noncomplementary")); inference_engine.RegisterParameters(parameter_manager); ComputationEngine<RealT> computation_engine(options, descriptions, inference_engine, parameter_manager); ComputationWrapper<RealT> computation_wrapper(computation_engine); // decide whether I'm a compute node or master node if (computation_engine.IsComputeNode()) { computation_engine.RunAsComputeNode(); return; } std::vector<RealT> w(parameter_manager.GetNumLogicalParameters(), RealT(0)); computation_wrapper.SanityCheckGradient(computation_wrapper.GetAllUnits(), w); computation_engine.StopComputeNodes(); } ///////////////////////////////////////////////////////////////// // RunTrainingMode() // // Run CONTRAfold in training mode. ///////////////////////////////////////////////////////////////// template<class RealT> void RunTrainingMode(const Options &options, const std::vector<FileDescription> &descriptions) { ParameterManager<RealT> parameter_manager; InferenceEngine<RealT> inference_engine(options.GetBoolValue("allow_noncomplementary")); inference_engine.RegisterParameters(parameter_manager); ComputationEngine<RealT> computation_engine(options, descriptions, inference_engine, parameter_manager); ComputationWrapper<RealT> computation_wrapper(computation_engine); // decide whether I'm a compute node or master node if (computation_engine.IsComputeNode()) { computation_engine.RunAsComputeNode(); return; } std::vector<RealT> w(parameter_manager.GetNumLogicalParameters(), RealT(0)); std::vector<int> units = computation_wrapper.FilterNonparsable(computation_wrapper.GetAllUnits()); OptimizationWrapper<RealT> optimization_wrapper(computation_wrapper); // decide between using a fixed regularization parameter or // using cross-validation to determine regularization parameters if (options.GetRealValue("holdout_ratio") <= 0) { std::vector<RealT> regularization_coefficients(parameter_manager.GetNumParameterGroups(), options.GetRealValue("regularization_coefficient")); optimization_wrapper.Train(units, w, regularization_coefficients); } else { optimization_wrapper.LearnHyperparameters(units, w); } parameter_manager.WriteToFile("optimize.params.final", w); computation_engine.StopComputeNodes(); } ///////////////////////////////////////////////////////////////// // RunPredictionMode() // // Run CONTRAfold in prediction mode. ///////////////////////////////////////////////////////////////// template<class RealT> void RunPredictionMode(const Options &options, const std::vector<FileDescription> &descriptions) { ParameterManager<RealT> parameter_manager; InferenceEngine<RealT> inference_engine(options.GetBoolValue("allow_noncomplementary")); inference_engine.RegisterParameters(parameter_manager); ComputationEngine<RealT> computation_engine(options, descriptions, inference_engine, parameter_manager); ComputationWrapper<RealT> computation_wrapper(computation_engine); // decide whether I'm a compute node or master node if (computation_engine.IsComputeNode()) { computation_engine.RunAsComputeNode(); return; } const std::string output_parens_destination = options.GetStringValue("output_parens_destination"); const std::string output_bpseq_destination = options.GetStringValue("output_bpseq_destination"); const std::string output_posteriors_destination = options.GetStringValue("output_posteriors_destination"); // load parameters std::vector<RealT> w; if (options.GetStringValue("parameter_filename") != "") { parameter_manager.ReadFromFile(options.GetStringValue("parameter_filename"), w); } else { #if PROFILE w = GetDefaultProfileValues<RealT>(); #else if (options.GetBoolValue("allow_noncomplementary")) w = GetDefaultNoncomplementaryValues<RealT>(); else w = GetDefaultComplementaryValues<RealT>(); #endif } if (options.GetRealValue("gamma") < 0) { // create directories for storing each run if (output_parens_destination != "") MakeDirectory(output_parens_destination); if (output_bpseq_destination != "") MakeDirectory(output_bpseq_destination); if (output_posteriors_destination != "") MakeDirectory(output_posteriors_destination); // try different values of gamma for (int k = -5; k <= 10; k++) { // create output subdirectories, if needed const double gamma = Pow(2.0, double(k)); if (descriptions.size() > 1) { if (output_parens_destination != "") MakeDirectory(SPrintF("%s%c%s.gamma=%lf", output_parens_destination.c_str(), DIR_SEPARATOR_CHAR, GetBaseName(output_parens_destination).c_str(), gamma)); if (output_bpseq_destination != "") MakeDirectory(SPrintF("%s%c%s.gamma=%lf", output_bpseq_destination.c_str(), DIR_SEPARATOR_CHAR, GetBaseName(output_bpseq_destination).c_str(), gamma)); if (output_posteriors_destination != "") MakeDirectory(SPrintF("%s%c%s.gamma=%lf", output_posteriors_destination.c_str(), DIR_SEPARATOR_CHAR, GetBaseName(output_posteriors_destination).c_str(), gamma)); } // perform predictions computation_wrapper.Predict(computation_wrapper.GetAllUnits(), w, gamma, options.GetRealValue("log_base")); } } else { // create output directories for output files, if needed if (descriptions.size() > 1) { if (output_parens_destination != "") MakeDirectory(output_parens_destination); if (output_bpseq_destination != "") MakeDirectory(output_bpseq_destination); if (output_posteriors_destination != "") MakeDirectory(output_posteriors_destination); } computation_wrapper.Predict(computation_wrapper.GetAllUnits(), w, options.GetRealValue("gamma"), options.GetRealValue("log_base")); } computation_engine.StopComputeNodes(); }
44.180212
161
0.557466
jialiasus2
649780371269bfc751ce1f64d782420a3730de25
368
cpp
C++
Sources/18_sdl_show_yuv_embed/playthread.cpp
youshihou/audio-video-learning
6f127d92f8cc9a21cb379bfb18da30d1cd997690
[ "MIT" ]
null
null
null
Sources/18_sdl_show_yuv_embed/playthread.cpp
youshihou/audio-video-learning
6f127d92f8cc9a21cb379bfb18da30d1cd997690
[ "MIT" ]
null
null
null
Sources/18_sdl_show_yuv_embed/playthread.cpp
youshihou/audio-video-learning
6f127d92f8cc9a21cb379bfb18da30d1cd997690
[ "MIT" ]
null
null
null
#include "playthread.h" #include <SDL2/SDL.h> #include <QDebug> PlayThread::PlayThread(QObject *parent) : QThread(parent) { connect(this, &PlayThread::finished, this, &PlayThread::deleteLater); } PlayThread::~PlayThread() { disconnect(); requestInterruption(); quit(); wait(); qDebug() << this << "deStruct"; } void PlayThread::run() { }
16.727273
73
0.646739
youshihou
6498e22a72588d48145243e7a40a214cb80adb84
4,199
cpp
C++
Runtime/RHI/Vulkan/Vulkan_IndexBuffer.cpp
PanosK92/Directus3D
2220548d87ef2795d54f739ab84121d4fb3b7ca2
[ "MIT" ]
278
2016-06-19T16:48:31.000Z
2019-04-10T05:52:47.000Z
Runtime/RHI/Vulkan/Vulkan_IndexBuffer.cpp
PanosK92/Directus3D
2220548d87ef2795d54f739ab84121d4fb3b7ca2
[ "MIT" ]
22
2016-09-11T20:57:56.000Z
2019-04-04T00:10:58.000Z
Runtime/RHI/Vulkan/Vulkan_IndexBuffer.cpp
PanosK92/Directus3D
2220548d87ef2795d54f739ab84121d4fb3b7ca2
[ "MIT" ]
31
2016-08-09T13:15:51.000Z
2019-03-27T13:25:07.000Z
/* Copyright(c) 2016-2021 Panos Karabelas 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. */ //= INCLUDES ===================== #include "Spartan.h" #include "../RHI_Implementation.h" #include "../RHI_Device.h" #include "../RHI_IndexBuffer.h" #include "../RHI_CommandList.h" //================================ //= NAMESPACES ===== using namespace std; //================== namespace Spartan { void RHI_IndexBuffer::_destroy() { // Wait m_rhi_device->QueueWaitAll(); // Destroy vulkan_utility::vma_allocator::destroy_buffer(m_resource); } bool RHI_IndexBuffer::_create(const void* indices) { // Destroy previous buffer _destroy(); m_is_mappable = indices == nullptr; if (m_is_mappable) { // Define memory properties VkMemoryPropertyFlags flags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; // mappable // Create vulkan_utility::vma_allocator::create_buffer(m_resource, m_object_size_gpu, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, flags, nullptr); // Get mapped data pointer m_mapped_data = vulkan_utility::vma_allocator::get_mapped_data_from_buffer(m_resource); } else // The reason we use staging is because memory with VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT is not mappable but it's fast, we want that. { // Create staging/source buffer and copy the indices to it void* staging_buffer = nullptr; vulkan_utility::vma_allocator::create_buffer(staging_buffer, m_object_size_gpu, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, indices); // Create destination buffer vulkan_utility::vma_allocator::create_buffer(m_resource, m_object_size_gpu, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr); // Copy staging buffer to destination buffer { // Create command buffer VkCommandBuffer cmd_buffer = vulkan_utility::command_buffer_immediate::begin(RHI_Queue_Type::Copy); VkBuffer* buffer_vk = reinterpret_cast<VkBuffer*>(&m_resource); VkBuffer* buffer_staging_vk = reinterpret_cast<VkBuffer*>(&staging_buffer); // Copy VkBufferCopy copy_region = {}; copy_region.size = m_object_size_gpu; vkCmdCopyBuffer(cmd_buffer, *buffer_staging_vk, *buffer_vk, 1, &copy_region); // Flush and free command buffer vulkan_utility::command_buffer_immediate::end(RHI_Queue_Type::Copy); // Destroy staging buffer vulkan_utility::vma_allocator::destroy_buffer(staging_buffer); } } // Set debug name vulkan_utility::debug::set_name(static_cast<VkBuffer>(m_resource), m_object_name.c_str()); return true; } void* RHI_IndexBuffer::Map() { return m_mapped_data; } void RHI_IndexBuffer::Unmap() { // buffer is mapped on creation and unmapped during destruction } }
38.522936
211
0.679686
PanosK92
649e22c0d735d6776cfd8dde33726dcb39329db1
2,376
cpp
C++
src/stl_manipulator.cpp
nerdmaennchen/stl_manipulator
5cf411b1474ee567562c1a02957935a6f009ff48
[ "MIT" ]
null
null
null
src/stl_manipulator.cpp
nerdmaennchen/stl_manipulator
5cf411b1474ee567562c1a02957935a6f009ff48
[ "MIT" ]
null
null
null
src/stl_manipulator.cpp
nerdmaennchen/stl_manipulator
5cf411b1474ee567562c1a02957935a6f009ff48
[ "MIT" ]
null
null
null
#include "sargparse/Parameter.h" #include "sargparse/File.h" #include "sargparse/ArgumentParsing.h" #include "stl/STLParser.h" #include "transformer.h" #include "global_parameters.h" #include <iostream> namespace { sargp::Parameter<std::string> outFile {"", "out", "the file to write to", []{}, sargp::completeFile("stl", sargp::File::Single)}; sargp::Flag invertVertexFanning {"invert_vertex_fanning", "reorder the vertices of all facets"}; sargp::Flag addInvertedVerteces {"add_inverted_vertices", "add reordered vertices of all facets (effectively copies all vertives once)"}; void stl_manipulator() { auto const& subC = sargp::getDefaultCommand().getSubCommands(); if (std::any_of(begin(subC), end(subC), [](auto const& c) -> bool {return *c;})) { return; } if (not inFiles) { throw std::runtime_error("in has to be specified!"); } if (not outFile) { throw std::runtime_error("out has to be specified!"); } kinematicTree::visual::stl::STLParser parser; kinematicTree::visual::mesh::Mesh mesh; for (auto const& file : *inFiles) { std::cout << "loading : " << file << "\n"; auto subMesh = parser.parse(file); for (auto const& facet : subMesh.getFacets()) { mesh.addFacet(facet); } } auto transform = getTransform(); transform.print("applying transform"); mesh.applyTransform(transform); if (addInvertedVerteces) { std::cout << "adding inverted vertices to the output mesh\n"; auto meshInverted = mesh; meshInverted.invertVertexFanning(); for (auto const& facet : meshInverted.getFacets()) { mesh.addFacet(facet); } } if (invertVertexFanning) { std::cout << "inverting the fanning\n"; mesh.invertVertexFanning(); } auto const inf = std::numeric_limits<double>::infinity(); arma::colvec3 bb_min {inf, inf, inf}; arma::colvec3 bb_max {-inf, -inf, -inf}; for (auto const& facet : mesh.getFacets()) { for (auto const& vertex : facet.mVertices) { bb_min = arma::min(bb_min, vertex); bb_max = arma::max(bb_max, vertex); } } std::cout << "\n\nbounding box min: \n" << bb_min; std::cout << "\n\nbounding box max: \n" << bb_max; std::cout << "\n\ndimensions: \n" << (bb_max - bb_min); std::cout << "writing output file " << *outFile << "\n"; parser.dump(mesh, *outFile); std::cout << "done" << std::endl; } sargp::Task task{stl_manipulator}; }
28.285714
137
0.6633
nerdmaennchen
64a09e318cce4f3ec002698953fd0b475e2db0db
943
cc
C++
TC-programs/CIS-D/readbin.cc
sklinkusch/scripts
a717cadb559db823a0d5172545661d5afa2715e7
[ "MIT" ]
null
null
null
TC-programs/CIS-D/readbin.cc
sklinkusch/scripts
a717cadb559db823a0d5172545661d5afa2715e7
[ "MIT" ]
null
null
null
TC-programs/CIS-D/readbin.cc
sklinkusch/scripts
a717cadb559db823a0d5172545661d5afa2715e7
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <math.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <unistd.h> #include <ctype.h> #include <sys/time.h> #include <sys/resource.h> #include <sstream> using namespace std; extern void read_bin(char* binfile, int nros, double& cisEgs, double* cisvals); int main(int argc, char* argv[]){ if(argc != 4){ cerr << "Usage: ./readbin binfile nros outfile\n"; exit(1); } char binfile[512]; sprintf(binfile, "%s", argv[1]); int nros = atoi(argv[2]); double cisEgs = 0.; double* cisvals = new double[nros]; read_bin(binfile, nros, cisEgs, cisvals); ofstream outf; outf.open(argv[3]); outf << nros << " States\n"; outf << "GS Energy: " << cisEgs << "\n"; outf << "Excitation Energies: " << "\n"; for(int i = 0; i < nros; i++){ outf << i << " " << cisvals[i] << "\n"; } outf.close(); }
23
79
0.589608
sklinkusch
64a16740e6cbeefe83a5d3322cb510e02ef81c21
4,096
cpp
C++
src/util/xpc/basehookinterconnector.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/util/xpc/basehookinterconnector.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/util/xpc/basehookinterconnector.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "basehookinterconnector.h" #include <QMetaMethod> #include <QtDebug> namespace LC { namespace Util { BaseHookInterconnector::BaseHookInterconnector (QObject *parent) : QObject (parent) { } BaseHookInterconnector::~BaseHookInterconnector () { } namespace { bool IsHookMethod (const QMetaMethod& method) { return method.parameterTypes ().value (0) == "LC::IHookProxy_ptr"; } auto BuildHookSlots (const QObject *obj) { const auto objMo = obj->metaObject (); QHash<QByteArray, QList<QMetaMethod>> hookSlots; for (int i = 0, size = objMo->methodCount (); i < size; ++i) { const auto& method = objMo->method (i); if (IsHookMethod (method)) hookSlots [method.name ()] << method; } return hookSlots; } bool ShouldBeVerbose () { static bool result = qEnvironmentVariableIsSet ("LC_VERBOSE_HOOK_CHECKS"); return result; } void CheckMatchingSigs (const QObject *snd, const QObject *rcv) { if (!ShouldBeVerbose ()) return; const auto& hookSlots = BuildHookSlots (snd); const auto rcvMo = rcv->metaObject (); for (int i = 0, size = rcvMo->methodCount (); i < size; ++i) { const auto& rcvMethod = rcvMo->method (i); if (!IsHookMethod (rcvMethod)) continue; const auto& rcvName = rcvMethod.name (); if (!hookSlots.contains (rcvName)) { qWarning () << Q_FUNC_INFO << "no method matching method" << rcvName << "(receiver" << rcv << ") in sender object" << snd; continue; } const auto& sndMethods = hookSlots [rcvName]; if (std::none_of (sndMethods.begin (), sndMethods.end (), [&rcvMethod] (const QMetaMethod& sndMethod) { return QMetaObject::checkConnectArgs (sndMethod, rcvMethod); })) qWarning () << Q_FUNC_INFO << "incompatible signatures for hook" << rcvName << "in" << snd << "and" << rcv; } } #define LC_N(a) (QMetaObject::normalizedSignature(a)) #define LC_TOSLOT(a) ('1' + QByteArray(a)) #define LC_TOSIGNAL(a) ('2' + QByteArray(a)) void ConnectHookSignals (QObject *sender, QObject *receiver, bool destSlot) { if (destSlot) CheckMatchingSigs (sender, receiver); const QMetaObject *mo = sender->metaObject (); for (int i = 0, size = mo->methodCount (); i < size; ++i) { QMetaMethod method = mo->method (i); if (method.methodType () != QMetaMethod::Signal) continue; if (!IsHookMethod (method)) continue; const auto& signature = method.methodSignature (); if (receiver->metaObject ()->indexOfMethod (LC_N (signature)) == -1) { if (!destSlot) { qWarning () << Q_FUNC_INFO << "not found meta method for" << signature << "in receiver object" << receiver; } continue; } if (!QObject::connect (sender, LC_TOSIGNAL (signature), receiver, destSlot ? LC_TOSLOT (signature) : LC_TOSIGNAL (signature), Qt::UniqueConnection)) qWarning () << Q_FUNC_INFO << "connect for" << sender << "->" << receiver << ":" << signature << "failed"; else if (ShouldBeVerbose ()) qDebug () << Q_FUNC_INFO << "connecting" << sender << "->" << receiver << "for" << signature; } } #undef LC_TOSIGNAL #undef LC_TOSLOT #undef LC_N } void BaseHookInterconnector::AddPlugin (QObject *plugin) { Plugins_.push_back (plugin); ConnectHookSignals (this, plugin, true); } void BaseHookInterconnector::RegisterHookable (QObject *object) { ConnectHookSignals (object, this, false); } } }
23.953216
83
0.590576
Maledictus
64a7613678ffbb0b4a94ae672403f89bdf53a067
5,755
cpp
C++
examples/0110-facade-class-and-rtti/exp/example.cpp
satya-das/cib
369333ea58b0530b8789a340e21096ba7d159d0e
[ "MIT" ]
30
2018-03-05T17:35:29.000Z
2022-03-17T18:59:34.000Z
examples/0110-facade-class-and-rtti/exp/example.cpp
satya-das/cib
369333ea58b0530b8789a340e21096ba7d159d0e
[ "MIT" ]
2
2016-05-26T04:47:13.000Z
2019-02-15T05:17:43.000Z
examples/0110-facade-class-and-rtti/exp/example.cpp
satya-das/cib
369333ea58b0530b8789a340e21096ba7d159d0e
[ "MIT" ]
5
2019-02-15T05:09:22.000Z
2021-04-14T12:10:16.000Z
#include "example.h" #include "__zz_cib_internal/__zz_cib_Example-generic.h" Facade::Facade(__zz_cib_AbiType h) : __zz_cib_h_(h) { __zz_cib_MyHelper::__zz_cib_AddProxy(this, __zz_cib_h_); } Facade::Facade(Facade&& rhs) : __zz_cib_h_(rhs.__zz_cib_h_) { rhs.__zz_cib_h_ = nullptr; __zz_cib_MyHelper::__zz_cib_AddProxy(this, __zz_cib_h_); } Facade::~Facade() { __zz_cib_MyHelper::__zz_cib_ReleaseProxy(this); auto h = __zz_cib_MyHelper::__zz_cib_ReleaseHandle(this); __zz_cib_MyHelper::__zz_cib_Delete_2( h ); } Facade::Facade() : Facade(__zz_cib_MyHelper::__zz_cib_New_0(this)) {} PublicFacadeImpl::PublicFacadeImpl(__zz_cib_AbiType h) : ::Facade(__zz_cib_MyHelper::__zz_cib_CastTo__zz_cib_Class258(h)) , __zz_cib_h_(h) { __zz_cib_MyHelper::__zz_cib_AddProxy(this, __zz_cib_h_); } PublicFacadeImpl::PublicFacadeImpl(PublicFacadeImpl&& rhs) : ::Facade(std::move(rhs)) , __zz_cib_h_(rhs.__zz_cib_h_) { rhs.__zz_cib_h_ = nullptr; __zz_cib_MyHelper::__zz_cib_AddProxy(this, __zz_cib_h_); } PublicFacadeImpl::PublicFacadeImpl(const ::PublicFacadeImpl& __zz_cib_param0) : PublicFacadeImpl(__zz_cib_MyHelper::__zz_cib_Copy_0( __zz_cib_::__zz_cib_ToAbiType<decltype(__zz_cib_param0)>(__zz_cib_param0))) {} PublicFacadeImpl::~PublicFacadeImpl() { auto h = __zz_cib_MyHelper::__zz_cib_ReleaseHandle(this); __zz_cib_MyHelper::__zz_cib_Delete_1( h ); } PublicFacadeImpl::PublicFacadeImpl() : PublicFacadeImpl(__zz_cib_MyHelper::__zz_cib_New_2()) {} void PublicFacadeImpl::F() { __zz_cib_MyHelper::F_3<__zz_cib_::__zz_cib_AbiType_t<void>>( __zz_cib_::__zz_cib_ToAbiType<decltype(this)>(this) ); } A::A(__zz_cib_AbiType h) : __zz_cib_h_(h) { __zz_cib_MyHelper::__zz_cib_AddProxy(this, __zz_cib_h_); } A::A(A&& rhs) : __zz_cib_h_(rhs.__zz_cib_h_) { rhs.__zz_cib_h_ = nullptr; __zz_cib_MyHelper::__zz_cib_AddProxy(this, __zz_cib_h_); } A::A(const ::A& __zz_cib_param0) : A(__zz_cib_MyHelper::__zz_cib_Copy_0( __zz_cib_::__zz_cib_ToAbiType<decltype(__zz_cib_param0)>(__zz_cib_param0))) {} A::~A() { auto h = __zz_cib_MyHelper::__zz_cib_ReleaseHandle(this); __zz_cib_MyHelper::__zz_cib_Delete_1( h ); } A::A() : A(__zz_cib_MyHelper::__zz_cib_New_2()) {} ::Facade* A::PublicFacade() { return __zz_cib_::__zz_cib_FromAbiType<::Facade*>( __zz_cib_MyHelper::PublicFacade_3<__zz_cib_::__zz_cib_AbiType_t<::Facade*>>( __zz_cib_::__zz_cib_ToAbiType<decltype(this)>(this) ) ); } ::Facade* A::PrivateFacade1() { return __zz_cib_::__zz_cib_FromAbiType<::Facade*>( __zz_cib_MyHelper::PrivateFacade1_4<__zz_cib_::__zz_cib_AbiType_t<::Facade*>>( __zz_cib_::__zz_cib_ToAbiType<decltype(this)>(this) ) ); } ::Facade* A::PrivateFacade2() { return __zz_cib_::__zz_cib_FromAbiType<::Facade*>( __zz_cib_MyHelper::PrivateFacade2_5<__zz_cib_::__zz_cib_AbiType_t<::Facade*>>( __zz_cib_::__zz_cib_ToAbiType<decltype(this)>(this) ) ); } namespace __zz_cib_ { template<> class __zz_cib_Generic<::Facade> : public ::Facade { using __zz_cib_MethodId = __zz_cib_::__zz_cib_ids::__zz_cib_Class258::__zz_cib_MethodId; static __zz_cib_MethodTableHelper& __zz_cib_GetMethodTableHelper() { static __zz_cib_MethodTableHelper mtableHelper(__zz_cib_ExampleGetMethodTable( __zz_cib_ids::__zz_cib_Class258::__zz_cib_classId)); return mtableHelper; } explicit __zz_cib_Generic(__zz_cib_AbiType h) : ::Facade(h) {} public: static ::Facade* __zz_cib_FromHandle(__zz_cib_AbiType h) { return new __zz_cib_Generic(h); } void F() override { auto __zz_cib_h = __zz_cib_h_; using __zz_cib_ProcType = __zz_cib_AbiType_t<void>(__zz_cib_decl *) (__zz_cib_AbiType); __zz_cib_GetMethodTableHelper().Invoke<__zz_cib_ProcType, __zz_cib_MethodId::F_1>( __zz_cib_h ); } ~__zz_cib_Generic() override { if (!__zz_cib_h_) return; auto __zz_cib_h = __zz_cib_Helper<::Facade>::__zz_cib_ReleaseHandle(this); using __zz_cib_ProcType = void(__zz_cib_decl *) (__zz_cib_AbiType); __zz_cib_GetMethodTableHelper().Invoke<__zz_cib_ProcType, __zz_cib_MethodId::__zz_cib_Delete_2>( __zz_cib_h ); } }; } namespace __zz_cib_ { template<> ::Facade* __zz_cib_Helper<::Facade>::__zz_cib_CreateProxy(__zz_cib_AbiType h) { switch(__zz_cib_GetClassId(&h)) { case __zz_cib_::__zz_cib_ids::__zz_cib_Class259::__zz_cib_classId: return __zz_cib_Helper<PublicFacadeImpl>::__zz_cib_FromHandle( __zz_cib_Helper<PublicFacadeImpl>::__zz_cib_CastFrom__zz_cib_Class258(h) ); default: break; } auto* const __zz_cib_obj = ::__zz_cib_::__zz_cib_Generic<::Facade>::__zz_cib_FromHandle(h); return __zz_cib_obj; } } namespace __zz_cib_ { template <> struct __zz_cib_Delegator<::Facade> { using __zz_cib_Delegatee = ::Facade; static __zz_cib_AbiType_t<void> __zz_cib_decl F_0(::Facade* __zz_cib_obj) { __zz_cib_obj->F(); } static void __zz_cib_decl __zz_cib_Delete_1(::Facade* __zz_cib_obj) { __zz_cib_Helper_t<::Facade>::__zz_cib_ReleaseHandle(__zz_cib_obj); delete __zz_cib_obj; } }; }; namespace __zz_cib_ { namespace __zz_cib_Class258 { static const __zz_cib_MethodTable* __zz_cib_GetMethodTable() { static const __zz_cib_MTableEntry methodArray[] = { reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::Facade>::F_0), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::Facade>::__zz_cib_Delete_1) }; static const __zz_cib_MethodTable methodTable = { methodArray, 2 }; return &methodTable; } }} namespace __zz_cib_ { template<> const __zz_cib_MethodTable* __zz_cib_Helper<::Facade>::__zz_cib_GetProxyMethodTable() { return __zz_cib_::__zz_cib_Class258::__zz_cib_GetMethodTable(); } }
28.490099
104
0.753779
satya-das
64a917d6c137a439723870cfc0b455028d6be22b
1,134
hpp
C++
inc/impl/melocker.hpp
slavalev/tstl
cb652ea982b96ab6e0fbd5fecc064256cfd4e797
[ "MIT" ]
null
null
null
inc/impl/melocker.hpp
slavalev/tstl
cb652ea982b96ab6e0fbd5fecc064256cfd4e797
[ "MIT" ]
null
null
null
inc/impl/melocker.hpp
slavalev/tstl
cb652ea982b96ab6e0fbd5fecc064256cfd4e797
[ "MIT" ]
null
null
null
/*****************************************************************************************************//** * * Module Name: \file melocker.hpp * * Abstract: \brief Non reenterable mutual exclusion locker. * * Author: \author Vyacheslav I. Levtchenko (mail-to: slavalev@gmail.com) * * Revision History: \date 12.11.2008 started * * Classes, methods and structures: \details * * External: mutex * Internal: melocker * * TODO: \todo * *********************************************************************************************************/ #ifndef __MELOCKER_HPP__ #define __MELOCKER_HPP__ #include "tstl.hpp" #include "impl/mutex/mutex.hpp" namespace tstl { /// Universal locker #if defined (USE_SPINLOCK) template <class Tlocker = spinlock :: mutex> #elif defined (USE_FAST_MUTEX) template <class Tlocker = fastlock :: mutex> #else template <class Tlocker = mutex> #endif struct melocker : Tlocker { void init () { Tlocker :: init (); } void lock () { Tlocker :: lock (); } void unlock () { Tlocker :: unlock (); } }; }; /* end of tstl namespace */ #endif /* __MELOCKER_HPP__ */
21.396226
107
0.537919
slavalev
64ab84387b0226dbe0d1300d9bdaafe5378ce196
52
hpp
C++
src/boost_units_systems_si_absorbed_dose.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_units_systems_si_absorbed_dose.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_units_systems_si_absorbed_dose.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/units/systems/si/absorbed_dose.hpp>
26
51
0.807692
miathedev
64ae3d9aa3b1b69c784e645e0b611a90c8ffada9
3,324
hpp
C++
include/VROSC/PredictiveHitter_PredictedHit.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/VROSC/PredictiveHitter_PredictedHit.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/VROSC/PredictiveHitter_PredictedHit.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: VROSC.PredictiveHitter #include "VROSC/PredictiveHitter.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: VROSC namespace VROSC { // Forward declaring type: PredictiveHittable class PredictiveHittable; } // Completed forward declares #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::VROSC::PredictiveHitter::PredictedHit); DEFINE_IL2CPP_ARG_TYPE(::VROSC::PredictiveHitter::PredictedHit*, "VROSC", "PredictiveHitter/PredictedHit"); // Type namespace: VROSC namespace VROSC { // Size: 0x20 #pragma pack(push, 1) // Autogenerated type: VROSC.PredictiveHitter/VROSC.PredictedHit // [TokenAttribute] Offset: FFFFFFFF class PredictiveHitter::PredictedHit : public ::Il2CppObject { public: #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // public VROSC.PredictiveHittable PredictiveHittable // Size: 0x8 // Offset: 0x10 ::VROSC::PredictiveHittable* PredictiveHittable; // Field size check static_assert(sizeof(::VROSC::PredictiveHittable*) == 0x8); // public System.Double PredictedDSPTime // Size: 0x8 // Offset: 0x18 double PredictedDSPTime; // Field size check static_assert(sizeof(double) == 0x8); public: // Get instance field reference: public VROSC.PredictiveHittable PredictiveHittable ::VROSC::PredictiveHittable*& dyn_PredictiveHittable(); // Get instance field reference: public System.Double PredictedDSPTime double& dyn_PredictedDSPTime(); // public System.Void .ctor(VROSC.PredictiveHittable predictiveHittable, System.Double predictedDspTime) // Offset: 0x134333C template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static PredictiveHitter::PredictedHit* New_ctor(::VROSC::PredictiveHittable* predictiveHittable, double predictedDspTime) { static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::PredictiveHitter::PredictedHit::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<PredictiveHitter::PredictedHit*, creationType>(predictiveHittable, predictedDspTime))); } }; // VROSC.PredictiveHitter/VROSC.PredictedHit #pragma pack(pop) static check_size<sizeof(PredictiveHitter::PredictedHit), 24 + sizeof(double)> __VROSC_PredictiveHitter_PredictedHitSizeCheck; static_assert(sizeof(PredictiveHitter::PredictedHit) == 0x20); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: VROSC::PredictiveHitter::PredictedHit::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
43.736842
134
0.746089
RedBrumbler
64af78cdb4c69ea64f66898d518bcd1adc5565ac
273
cpp
C++
2021.09.18/Project8/Source.cpp
HudzievaPolina/programming-c-2021-1course-
f4e0c769419d12f95c42913980bbdc053302b7c6
[ "Apache-2.0" ]
null
null
null
2021.09.18/Project8/Source.cpp
HudzievaPolina/programming-c-2021-1course-
f4e0c769419d12f95c42913980bbdc053302b7c6
[ "Apache-2.0" ]
null
null
null
2021.09.18/Project8/Source.cpp
HudzievaPolina/programming-c-2021-1course-
f4e0c769419d12f95c42913980bbdc053302b7c6
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int main(int argc, char* argv[]) { int a = 0; int b = 0; int c = 0; int d = 0; int e = 0; int f = 0; cin >> a >> b >> c >> d >> e >> f; cout << d * 3600 + e * 60 + f - a * 3600 - b * 60 - c << endl; return EXIT_SUCCESS; }
17.0625
63
0.501832
HudzievaPolina
64b06b7a8c3774a8b5e49893450616a1f3f6ce94
3,327
cpp
C++
EpicForceEngine/MagnumEngineLib/MagnumCore/ColorRGBA.cpp
MacgyverLin/MagnumEngine
975bd4504a1e84cb9698c36e06bd80c7b8ced0ff
[ "MIT" ]
1
2021-03-30T06:28:32.000Z
2021-03-30T06:28:32.000Z
EpicForceEngine/MagnumEngineLib/MagnumCore/ColorRGBA.cpp
MacgyverLin/MagnumEngine
975bd4504a1e84cb9698c36e06bd80c7b8ced0ff
[ "MIT" ]
null
null
null
EpicForceEngine/MagnumEngineLib/MagnumCore/ColorRGBA.cpp
MacgyverLin/MagnumEngine
975bd4504a1e84cb9698c36e06bd80c7b8ced0ff
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////////// // Copyright(c) 2016, Lin Koon Wing Macgyver, macgyvercct@yahoo.com.hk // // // // Author : Mac Lin // // Module : Magnum Engine v1.0.0 // // Date : 14/Jun/2016 // // // /////////////////////////////////////////////////////////////////////////////////// #include "ESystem.h" #include "ColorRGB.h" #include "ColorRGBA.h" using namespace Magnum; const ColorRGBA ColorRGBA::BLACK (0.0f, 0.0f, 0.0f, 1.0f); const ColorRGBA ColorRGBA::BLUE (0.0f, 0.0f, 0.5f, 1.0f); const ColorRGBA ColorRGBA::GREEN (0.0f, 0.5f, 0.0f, 1.0f); const ColorRGBA ColorRGBA::CYAN (0.0f, 0.5f, 0.5f, 1.0f); const ColorRGBA ColorRGBA::RED (0.5f, 0.0f, 0.0f, 1.0f); const ColorRGBA ColorRGBA::MANGENTA (0.5f, 0.0f, 0.5f, 1.0f); const ColorRGBA ColorRGBA::BROWN (0.5f, 0.5f, 0.0f, 1.0f); const ColorRGBA ColorRGBA::GREY (0.5f, 0.5f, 0.5f, 1.0f); const ColorRGBA ColorRGBA::BRIGHT_BLUE (0.0f, 0.0f, 1.0f, 1.0f); const ColorRGBA ColorRGBA::BRIGHT_GREEN (0.0f, 1.0f, 0.0f, 1.0f); const ColorRGBA ColorRGBA::BRIGHT_CYAN (0.0f, 1.0f, 1.0f, 1.0f); const ColorRGBA ColorRGBA::BRIGHT_RED (1.0f, 0.0f, 0.0f, 1.0f); const ColorRGBA ColorRGBA::BRIGHT_MANGENTA(1.0f, 0.0f, 1.0f, 1.0f); const ColorRGBA ColorRGBA::YELLOW (1.0f, 1.0f, 0.0f, 1.0f); const ColorRGBA ColorRGBA::WHITE (1.0f, 1.0f, 1.0f, 1.0f); ColorRGBA::ColorRGBA(float r_, float g_, float b_, float a_) { m_afTuple[0] = r_; m_afTuple[1] = g_; m_afTuple[2] = b_; m_afTuple[3] = a_; } ColorRGBA::ColorRGBA(const ColorRGBA &rgba_) { *this = rgba_; } ColorRGBA &ColorRGBA::operator = (const ColorRGB &rgb) { m_afTuple[0] = rgb[0]; m_afTuple[1] = rgb[1]; m_afTuple[2] = rgb[2]; m_afTuple[3] = 1.0f; return *this; } ColorRGBA &ColorRGBA::operator = (const ColorRGBA &rgba) { m_afTuple[0] = rgba[0]; m_afTuple[1] = rgba[1]; m_afTuple[2] = rgba[2]; m_afTuple[3] = rgba[3]; return *this; } ColorRGBA::~ColorRGBA() { } bool ColorRGBA::operator == (const ColorRGBA &rgba) const { return System::memcmp( (const void *)(m_afTuple), (const void *)(rgba.m_afTuple), sizeof(m_afTuple[0])*3) == 0; } bool ColorRGBA::operator < (const ColorRGBA &rgba) const { return System::memcmp( (const void *)(m_afTuple), (const void *)(rgba.m_afTuple), sizeof(m_afTuple[0])*3) < 0; } ColorRGBA ColorRGBA::operator+ (const ColorRGBA& rkC) const { return ColorRGBA(m_afTuple[0]+rkC.m_afTuple[0], m_afTuple[1]+rkC.m_afTuple[1], m_afTuple[2]+rkC.m_afTuple[2], m_afTuple[3]); } ColorRGBA ColorRGBA::operator* (float fScalar) const { return ColorRGBA(m_afTuple[0]*fScalar, m_afTuple[1]*fScalar, m_afTuple[2]*fScalar, m_afTuple[3]); } unsigned int ColorRGBA::toInteger() const { unsigned int rval = ( (unsigned int)((m_afTuple[3]*255))<<24 ) | ( ((unsigned int)(m_afTuple[2]*255))<<16 ) | ( (unsigned int)((m_afTuple[1]*255))<<8 ) | ( ((unsigned int)(m_afTuple[0]*255)) ); return rval; } void ColorRGBA::read(InputStream &is) { is >> m_afTuple[0] >> m_afTuple[1] >> m_afTuple[2] >> m_afTuple[3]; } void ColorRGBA::write(OutputStream &os) const { os << m_afTuple[0] << m_afTuple[1] << m_afTuple[2] << m_afTuple[3]; }
31.990385
125
0.599038
MacgyverLin
64b353e506880bfb22f481553dec773bffa49300
5,332
cpp
C++
CsWeapon/Source/CsWp/Public/Types/CsTypes_Weapon.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
2
2019-03-17T10:43:53.000Z
2021-04-20T21:24:19.000Z
CsWeapon/Source/CsWp/Public/Types/CsTypes_Weapon.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
CsWeapon/Source/CsWp/Public/Types/CsTypes_Weapon.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
// Copyright 2017-2021 Closed Sum Games, LLC. All Rights Reserved. #include "Types/CsTypes_Weapon.h" #include "CsWp.h" // Library #include "Level/CsLibrary_Level.h" #include "Library/CsLibrary_Valid.h" // Settings #include "Settings/CsDeveloperSettings.h" #include "Settings/CsWeaponSettings.h" // Data #include "Data/CsWpGetDataRootSet.h" // Utility #include "Utility/CsWpLog.h" #include "Utility/CsPopulateEnumMapFromSettings.h" #include "Utility/CsWpPopulateEnumMapFromSettings.h" // Interface #include "Types/CsGetWeaponTypes.h" // Level #include "Engine/LevelScriptActor.h" // Weapon #pragma region namespace NCsWeapon { namespace Str { const FString Weapon = TEXT("Weapon"); } void FromEnumSettings(const FString& Context) { FCsPopulateEnumMapFromSettings::FromEnumSettings<UCsWeaponSettings, EMCsWeapon, FECsWeapon>(Context, Str::Weapon, &NCsWeapon::FLog::Warning); } void FromDataTable(const FString& Context, UObject* ContextRoot) { const FCsWpDataRootSet* DataRootSet = FCsWpPopulateEnumMapFromSettings::GetDataRootSet(Context, ContextRoot); if (!DataRootSet) return; for (const FCsWeaponSettings_DataTable_Weapons& Weapons : DataRootSet->Weapons) { FCsPopulateEnumMapFromSettings::FromDataTable<EMCsWeapon>(Context, ContextRoot, Weapons.Weapons, Str::Weapon, &NCsWeapon::FLog::Warning); } } void PopulateEnumMapFromSettings(const FString& Context, UObject* ContextRoot) { UCsDeveloperSettings* Settings = GetMutableDefault<UCsDeveloperSettings>(); checkf(Settings, TEXT("%s: Failed to file settings of type: UCsDeveloperSettings."), *Context); UCsWeaponSettings* ModuleSettings = GetMutableDefault<UCsWeaponSettings>(); checkf(ModuleSettings, TEXT("%s: Failed to find settings of type: UCsWeaponSettings."), *Context); EMCsWeapon::Get().ClearUserDefinedEnums(); // Enum Settings if (ModuleSettings->ECsWeapon_PopulateEnumMapMethod == ECsPopulateEnumMapMethod::EnumSettings) { FromEnumSettings(Context); } // DataTable if (ModuleSettings->ECsWeapon_PopulateEnumMapMethod == ECsPopulateEnumMapMethod::DataTable) { FromDataTable(Context, ContextRoot); } } void GetSafeFromLevel(const FString& Context, const UObject* WorldContext, TSet<FECsWeapon>& OutWeaponTypes, void(*Log)(const FString&) /*=&NCsWeapon::FLog::Warning*/) { typedef NCsLevel::NPersistent::FLibrary LevelLibrary; ICsGetWeaponTypes* GetWeaponTypes = LevelLibrary::GetSafeScriptActor<ICsGetWeaponTypes>(Context, WorldContext, Log); if (!GetWeaponTypes) return; OutWeaponTypes = GetWeaponTypes->GetWeaponTypes(); CS_IS_ENUM_STRUCT_SET_UNIQUE_CHECKED(EMCsWeapon, FECsWeapon, OutWeaponTypes) } } #pragma endregion Weapon // WeaponClass #pragma region namespace NCsWeaponClass { namespace Str { const FString WeaponClass = TEXT("WeaponClass"); } void FromEnumSettings(const FString& Context) { FCsPopulateEnumMapFromSettings::FromEnumSettings<UCsWeaponSettings, EMCsWeaponClass, FECsWeaponClass>(Context, Str::WeaponClass, &NCsWeapon::FLog::Warning); } void FromDataTable(const FString& Context, UObject* ContextRoot) { const FCsWpDataRootSet* DataRootSet = FCsWpPopulateEnumMapFromSettings::GetDataRootSet(Context, ContextRoot); if (!DataRootSet) return; FCsPopulateEnumMapFromSettings::FromDataTable<EMCsWeaponClass>(Context, ContextRoot, DataRootSet->WeaponClasses, Str::WeaponClass, &NCsWeapon::FLog::Warning); } void PopulateEnumMapFromSettings(const FString& Context, UObject* ContextRoot) { UCsDeveloperSettings* Settings = GetMutableDefault<UCsDeveloperSettings>(); checkf(Settings, TEXT("%s: Failed to file settings of type: UCsDeveloperSettings."), *Context); UCsWeaponSettings* ModuleSettings = GetMutableDefault<UCsWeaponSettings>(); checkf(ModuleSettings, TEXT("%s: Failed to find settings of type: UCsWeaponSettings."), *Context); EMCsWeaponClass::Get().ClearUserDefinedEnums(); // Enum Settings if (ModuleSettings->ECsWeaponClass_PopulateEnumMapMethod == ECsPopulateEnumMapMethod::EnumSettings) { FromEnumSettings(Context); } // DataTable if (ModuleSettings->ECsWeaponClass_PopulateEnumMapMethod == ECsPopulateEnumMapMethod::DataTable) { FromDataTable(Context, ContextRoot); } } } #pragma endregion WeaponClass // WeaponState #pragma region namespace NCsWeaponState { namespace Str { const FString WeaponState = TEXT("WeaponState"); } void FromEnumSettings(const FString& Context) { FCsPopulateEnumMapFromSettings::FromEnumSettings<UCsWeaponSettings, EMCsWeaponState, FECsWeaponState>(Context, Str::WeaponState, &NCsWeapon::FLog::Warning); } void PopulateEnumMapFromSettings(const FString& Context, UObject* ContextRoot) { UCsWeaponSettings* ModuleSettings = GetMutableDefault<UCsWeaponSettings>(); checkf(ModuleSettings, TEXT("%s: Failed to find settings of type: UCsWeaponSettings."), *Context); EMCsWeaponState::Get().ClearUserDefinedEnums(); FromEnumSettings(Context); } } #pragma endregion WeaponState // WeaponData #pragma region namespace NCsWeaponData { CSWP_API CS_CREATE_ENUM_STRUCT_CUSTOM(Weapon, "ICsData_Weapon"); CSWP_API CS_CREATE_ENUM_STRUCT_CUSTOM(ProjectileWeapon, "ICsData_ProjectileWeapon"); CSWP_API CS_CREATE_ENUM_STRUCT_CUSTOM(ProjectileWeaponSound, "ICsData_ProjectileWeapon_SoundFire"); } #pragma endregion WeaponData
28.978261
168
0.783196
closedsum
64b9cfba7d60b06a99a07e02fcbf9be1c3f9ff0e
9,449
cpp
C++
sharper.cpp
dive155/SmartImage
75ad89d053027780bab9790122dfc77d5938dfa0
[ "MIT" ]
3
2016-11-01T09:56:06.000Z
2020-01-11T02:20:28.000Z
sharper.cpp
dive155/SmartImage
75ad89d053027780bab9790122dfc77d5938dfa0
[ "MIT" ]
1
2016-05-10T20:07:20.000Z
2016-05-10T21:56:22.000Z
sharper.cpp
dive155/SmartImage
75ad89d053027780bab9790122dfc77d5938dfa0
[ "MIT" ]
null
null
null
#include "sharper.h" #include "ui_sharper.h" Sharper::Sharper(QWidget *parent) : QWidget(parent), ui(new Ui::Sharper) { ui->setupUi(this); connect(ui->doubleSpinBox_5, SIGNAL(valueChanged(double)), this, SLOT(nChanged(double))); connect(ui->contBut, SIGNAL(clicked()), this, SLOT(contrastSlot())); connect(ui->contrastArea, SIGNAL(valueChanged(int)), this, SLOT(contAreaChanged(int))); connect(ui->uMaskBut, SIGNAL(clicked()), this, SLOT(uncertainSlot())); connect(ui->uSpin, SIGNAL(valueChanged(int)), this, SLOT(kgChanged(int))); connect(ui->slider, SIGNAL(valueChanged(int)), this, SLOT(sliderChanged(int))); connect(ui->kgSpinbox, SIGNAL(valueChanged(int)), this, SLOT(realKgChanged(int))); connect(ui->simpleSharpButton, SIGNAL(clicked()), this, SLOT(simpleSharp())); connect(ui->sRGButton, SIGNAL(clicked()), this, SLOT(simpleSharpRGB())); connect(ui->gausSpin, SIGNAL(valueChanged(int)), this, SLOT(setGausPower(int))); connect(ui->sigmaSpin, SIGNAL(valueChanged(double)), this, SLOT(setGausSigma(double))); kg=1; contArea = 2; realKg=1; gausPower = 1; gausSigma = 1; } Sharper::~Sharper() { delete ui; } void Sharper::setSource(MainWindow *source) { window = source; } void Sharper::setImage(QImage picture) { image = picture; result = image; } void Sharper::kgChanged(int spin) { kg = spin; } void Sharper::uncertainSlot() { uncertainMask(&image,2,1); window->receiveResult(result); } void Sharper::simpleSharp() { uncertainMask(&image,1, 1); window->receiveResult(result); } void Sharper::simpleSharpRGB() { uncertainMask(&image,1, 2); window->receiveResult(result); } void Sharper::setGausPower(int spin) { gausPower=spin; } void Sharper::setGausSigma(double spin) { gausSigma = spin; } QList<int> Sharper::vicinity(QImage *picture, int power, int curx, int cury, int chanel) { //функция возвращает окрестность заданного пикселя QList<int> proxArray; for (int y = cury - power; y <= cury+ power; y++) for (int x = curx - power; x <= curx+ power; x++) { //проверяем окрестные пиксели if ((0 <= x && x <= picture->width()-1) && (0 <= y && y <= picture->height()-1)) { //запоминаем их цвета QColor pixel = picture->pixel(x, y); if (chanel == 1) proxArray.append(pixel.red()); if (chanel == 2) proxArray.append(pixel.green()); if (chanel == 3) proxArray.append(pixel.blue()); if (chanel ==4) proxArray.append(pixel.lightness()); } else { //если мы за пределами изображения, то запоминаем чёрный цвет proxArray.append(0); } } return proxArray; } int Sharper::listAverage(QList<int> theArray) { //функция считает среднее арифметическое значение списка //qDebug() << "listaverage"; int aver = 0; for (int i = 0; i <= theArray.size()-1; i++) { aver = aver + theArray[i]; } aver = aver / theArray.size(); // среднее значение равно сумма значений/кол-во значений return aver; } double Sharper::listDisp(QList<int> theArray, int mu) { //функция считает дисперсию значений списка //qDebug() << "listdisp"; double aver = 0; //counting color value for (int i = 0; i <= theArray.size()-1; i++) { aver = aver + ((theArray[i]-mu)*(theArray[i]-mu)); } aver = aver / theArray.size(); return sqrt(aver); } QList<qreal> Sharper::genGauss(int power, qreal sigma) { QList<qreal>ohNo; for (int i = 1; i<=power*2+1; i++) { for (int j = 1; j<=power*2+1; j++) { ohNo.append( (1.0/sqrt(2.0*3.14159*sigma*sigma)) * qExp( -(qPow((j-power - 1.0), 2) + qPow((i-power - 1.0), 2))/(2.0*sigma*sigma) )); } } qreal sum = 0; for (int i = 0; i<ohNo.size(); i++) sum = sum+ohNo[i]; sum =1/sum; for (int i = 0; i<ohNo.size(); i++) ohNo[i]=ohNo[i]*sum; return ohNo; } int Sharper::applyKernel(QList<int> area, QList<qreal> kernel) { //функция, накладывающая маски int sum = 0; for (int i = 0; i < area.size(); i++) { //умножаем элемент окрестности на соответствующий элемент маски и sum = sum + area[i]*kernel[i]; //считаем сумму всех таких произведений } return sum ;// 16; //возвращаем Z } QColor Sharper::uncertainColor(QImage *picture, int mode, int tempKg, QColor sourcePixel, QList<qreal>gaussian, int x, int y, int hsl) { QColor pixel; int value = 0; if (hsl == 1) { QList<int> local = vicinity(picture, gausPower, x, y, 4); //получаем окрестность int gauss = applyKernel(local, gaussian); //применяем фильтр гаусса к окрестности if (mode == 2) tempKg=countKg(vicinity(picture, kg, x, y, 4)); int value = gauss + tempKg*(sourcePixel.lightness()-gauss); //считаем новую яркость if (value > 255) value = 255; if (value < 0) value = 0; pixel.setHsl(sourcePixel.hslHue(),sourcePixel.hslSaturation(),value); //задаем новую яркость*/ return pixel; } QList<int> local = vicinity(picture, gausPower, x, y, 1); //получаем окрестность int gauss = applyKernel(local, gaussian); //применяем фильтр гаусса к окрестности if (mode == 2) tempKg=countKg(vicinity(picture, kg, x, y, 1)); value = gauss + tempKg*(sourcePixel.red()-gauss); //считаем новую яркость if (value > 255) value = 255; if (value < 0) value = 0; pixel.setRed(value); local = vicinity(picture, gausPower, x, y, 2); //получаем окрестность gauss = applyKernel(local, gaussian); //применяем фильтр гаусса к окрестности if (mode == 2) tempKg=countKg(vicinity(picture, kg, x, y, 2)); value = gauss + tempKg*(sourcePixel.green()-gauss); //считаем новую яркость if (value > 255) value = 255; if (value < 0) value = 0; pixel.setGreen(value); local = vicinity(picture, gausPower, x, y, 3); //получаем окрестность gauss = applyKernel(local, gaussian); //применяем фильтр гаусса к окрестности if (mode == 2) tempKg=countKg(vicinity(picture, kg, x, y, 3)); value = gauss + tempKg*(sourcePixel.blue()-gauss); //считаем новую яркость if (value > 255) value = 255; if (value < 0) value = 0; pixel.setBlue(value); return pixel; } void Sharper::uncertainMask(QImage *picture, int mode, int hsl) { //нечеткое маскирование int tempKg = realKg; QList<qreal> gaussian; gaussian = genGauss(gausPower,gausSigma); window->setMaxProgress(picture->width()-1); for (int x = 0; x<picture->width();x++) { //обрабатываем всю картинку window->setProgress(x); for (int y = 0; y<picture->height();y++) { QColor pixel = uncertainColor(picture, mode, tempKg, picture->pixel(x,y),gaussian,x,y,hsl); // pixel.setHsl(pixel.hslHue(),pixel.hslSaturation(),value); //задаем новую яркость result.setPixel(x,y,pixel.rgb()); } } } double Sharper::countKg(QList<int> proxy) { //адаптивный коэффициент qreal disp = listDisp(proxy,listAverage(proxy)); if (abs(disp)<0.1) return kn; return kn / listDisp(proxy,listAverage(proxy)); } void Sharper::sliderChanged(int value) {//слот слайдера для коэффициента фильтра kn = value; } void Sharper::localContrast(QImage *picture) { //фильтрация с учётом локальной контрастности window->setMaxProgress(picture->width()-1); for (int x = 0; x<picture->width();x++) { window->setProgress(x); for (int y = 0; y<picture->height();y++) { QList<int> local = vicinity(picture, contArea, x, y, 4); //получаем локальную окрестность QColor pixel = picture->pixel(x, y); //делаем пиксель int value = contrastPixel(pixel.lightness(), listAverage(local)) ; //считаем фильтр if (value > 255) value = 255; if (value < 0) value = 0; //qDebug() << gauss << " + " << kg << " * (" << pixel.lightness() << " - " << gauss << ") = " << value; pixel.setHsl(pixel.hslHue(),pixel.hslSaturation(),value); result.setPixel(x,y,pixel.rgb()); //записываем } } } int Sharper::contrastPixel(int source, int proxBright) { //считаем выходное значение одного пикселя // qDebug() << "was " << source << proxBright; double kostil = source - proxBright; double Cz = qAbs(kostil)/(source+proxBright); // qDebug () << "cz" << Cz; if (source <= proxBright) { // qDebug() << "now " << 1.0 - qPow(Cz, N) ; return proxBright * ( (1.0 - qPow(Cz, N)) / (1.0 + qPow(Cz, N)) ); } //всё по формуле считаем в этой функции else { //qDebug() << "now " << (1.0 + qPow(Cz, N)) / (1.0 - qPow(Cz, N)); return proxBright * ( (1.0 + qPow(Cz, N)) / (1.0 - qPow(Cz, N)) ); } } void Sharper::nChanged(double spin) { //слот смнился N N = spin; } void Sharper::contrastSlot() { //вызвать функцию фильтрации localContrast(&image); window->receiveResult(result); } void Sharper::contAreaChanged(int spin) { //сменить размер окрестности contArea = spin; } void Sharper::realKgChanged(int spin) { realKg=spin; }
30.480645
145
0.598159
dive155
64ba93e30b5e84437bf28553db5fbcd15af49569
280
cpp
C++
XrsPalm/src/IO/SJFilter.cpp
bach5000/XRS
8b9169f8d52a441ddca87415963ea2fcfced1884
[ "MIT" ]
null
null
null
XrsPalm/src/IO/SJFilter.cpp
bach5000/XRS
8b9169f8d52a441ddca87415963ea2fcfced1884
[ "MIT" ]
null
null
null
XrsPalm/src/IO/SJFilter.cpp
bach5000/XRS
8b9169f8d52a441ddca87415963ea2fcfced1884
[ "MIT" ]
null
null
null
#include "SJFilter.h" SJFilter::SJFilter(){} bool SJFilter::Filter(const entry_ref *erf,BNode *node,struct stat_beos *st,const char *filetype) { bool rt; if(S_ISDIR(st->st_mode)) return true; if(strcmp(filetype,"audio/XRS-File")==0) rt=true; else rt=false; return rt; }
17.5
92
0.707143
bach5000
64bab72e968ae2f1d70ea695b6399d5dad2c2db1
426
cpp
C++
LeetCode/1010.cpp
jnvshubham7/CPP_Programming
a17c4a42209556495302ca305b7c3026df064041
[ "Apache-2.0" ]
1
2021-12-22T12:37:36.000Z
2021-12-22T12:37:36.000Z
LeetCode/1010.cpp
jnvshubham7/CPP_Programming
a17c4a42209556495302ca305b7c3026df064041
[ "Apache-2.0" ]
null
null
null
LeetCode/1010.cpp
jnvshubham7/CPP_Programming
a17c4a42209556495302ca305b7c3026df064041
[ "Apache-2.0" ]
null
null
null
class Solution { public: int numPairsDivisibleBy60(vector<int>& time) { int count=0; vector<int> v(60,0); for(int i=0;i<time.size();i++) { int a=time[i]%60; if(a==0) count+=v[0]; else count+=v[60-a]; v[a]++; } return count; } };
18.521739
50
0.338028
jnvshubham7
64bf9e061b510f7b92ed3b910d7199bc5c73d493
102
hpp
C++
include/XenoWS/Response.hpp
XenoBino/XenoWS
d2b2db4f16958d33284aba7679b93cf8d79e8678
[ "Apache-2.0" ]
null
null
null
include/XenoWS/Response.hpp
XenoBino/XenoWS
d2b2db4f16958d33284aba7679b93cf8d79e8678
[ "Apache-2.0" ]
null
null
null
include/XenoWS/Response.hpp
XenoBino/XenoWS
d2b2db4f16958d33284aba7679b93cf8d79e8678
[ "Apache-2.0" ]
null
null
null
#pragma once class Response { public: Response(unsigned char *version, unsigned short response); };
14.571429
59
0.754902
XenoBino
64bfffb2c5549bc6a55233f8de1ed465cc31e79a
5,181
cc
C++
src/utils.cc
ltlfuzzer/LTL-Fuzzer
9a5a6e771a720a06b3a14baac934e0eef72d138b
[ "Apache-2.0" ]
1
2022-01-21T07:57:03.000Z
2022-01-21T07:57:03.000Z
src/utils.cc
ltlfuzzer/LTL-Fuzzer
9a5a6e771a720a06b3a14baac934e0eef72d138b
[ "Apache-2.0" ]
null
null
null
src/utils.cc
ltlfuzzer/LTL-Fuzzer
9a5a6e771a720a06b3a14baac934e0eef72d138b
[ "Apache-2.0" ]
1
2022-02-02T11:55:04.000Z
2022-02-02T11:55:04.000Z
#include <utils.h> using std::cout; using std::endl; namespace utils{ std::string aDelimiter =","; std::string get_last_state(std::string aPath) { if(aPath.empty()){ cout << "the given automata path is empty" <<endl; } aPath=aPath.substr(0,aPath.size()-1); std::size_t found = aPath.find_last_of(aDelimiter); return aPath.substr(found+1); } int str2int(std::string s){ return std::stoi(s); } std::string get_current_time() { time_t now = time(0); struct tm tstruct; char buf[80]; tstruct = *localtime(&now); strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct); return buf; } std::string set_to_string(std::set<std::string> aSet){ std::ostringstream stream; std::copy(aSet.begin(), aSet.end(), std::ostream_iterator<std::string>(stream, ",")); std::string result = stream.str(); return result.substr(0, result.size()-1); } void gen_ltl_files(std::string script, std::string build_dir, std::string formula){ std::string cmd=script + " " + build_dir + " '" + formula +"'"; std::cout <<"script: " <<cmd << std::endl; system(cmd.c_str()); } void string_to_input_type(std::string p, std::vector<INPUT_TYPE>& results){ std::vector<std::string> v = string2vector(p); for (auto e : v){ if(!e.empty()){ results.push_back(std::stoi(e)); } } } void string_to_vector(std::string p, std::vector<std::string>& results){ std::string delimiter = ";;"; size_t pos = 0; std::string token; while ((pos = p.find(delimiter)) != std::string::npos) { token = p.substr(0, pos); p.erase(0, pos + delimiter.length()); results.push_back(token); } } std::vector<std::string> string2vector(std::string s){ std::vector<std::string> results; boost::split(results, s, [](char c){return c == ',';}); return results; } INPUT_TYPE* read_input(int* size, std::string input_file){ std::cout <<"file path: " <<input_file<<std::endl; std::ifstream ifs(input_file, std::ios::binary); if(ifs){ ifs.seekg(0, ifs.end); *size=ifs.tellg(); ifs.seekg(0,ifs.beg); INPUT_TYPE* input=new INPUT_TYPE[*size]; ifs.read((char*)(&input[0]), *size); if(ifs) std::cout << "all bytes are read!"<<std::endl; else std::cout <<"error: " << ifs.gcount() << std::endl; ifs.close(); return input; } else return nullptr; } void write_input(INPUT_TYPE* input, int size, std::string output_file){ std::ofstream ofs(output_file, std::ios::binary); if(ofs){ ofs.write((char*)(&input[0]), size); } ofs.close(); } //For RERS void write_to_shmem_common(INPUT_TYPE arr[], uint32_t arr_size){ int shmid = get_prefix_smem(); if(shmid == -1){ return; } else{ PREFIX_SMEM* shm = bind_prefix_smem(shmid); if(shm == (PREFIX_SMEM*)-1){ return; } else{ memcpy(shm->array[0], arr, arr_size*sizeof(INPUT_TYPE)); shm->arr_size = arr_size; printf("write to shared memory: %d\n", (shm->arr_size)); detach_prefix_shmem(shm); return; } } } //For protocol void write_to_shmem_protocol(std::vector<std::string> arr, uint32_t arr_size){ int shmid = get_prefix_smem(); if(shmid == -1){ std::cout << "Cannot Got Shared Memory. " << std::endl; return; } else{ PREFIX_SMEM* shm = bind_prefix_smem(shmid); if(shm == (PREFIX_SMEM*)-1){ return; } else{ if(arr_size > 30){ throw std::runtime_error("Total length at shared memory overflow"); } if(arr_size == 0){ shm->arr_size = 0; printf("write to shm size: %u\n", shm->arr_size); detach_prefix_shmem(shm); return; } //printf("write to shm length: %u; string: %s\n", arr_size, arr[0]); for(uint32_t i = 0; i < arr_size; i++){ if(arr[i].length() > 20000){ throw std::runtime_error("Single length at shared memory overflow"); } else{ stpcpy((shm->array)[i], arr[i].c_str()); } //printf("shm value: %s\n", (shm->array)[i]); } shm->arr_size = arr_size; printf("write to shm size: %u\n", shm->arr_size); detach_prefix_shmem(shm); return; } } } }//namepsace
29.605714
93
0.487937
ltlfuzzer
64c0900758be1abf962d029b23c40947a70d69bf
130
cpp
C++
app/src/machine/gCode_copy.cpp
smartDIYs/FABOOLDesktop_opensource
082fc12eacffed2b64f868064ed3809d06db831b
[ "MIT" ]
6
2019-02-17T02:17:45.000Z
2021-07-16T01:53:41.000Z
app/src/machine/gCode_copy.cpp
smartDIYs/FABOOLDesktop_opensource
082fc12eacffed2b64f868064ed3809d06db831b
[ "MIT" ]
null
null
null
app/src/machine/gCode_copy.cpp
smartDIYs/FABOOLDesktop_opensource
082fc12eacffed2b64f868064ed3809d06db831b
[ "MIT" ]
5
2018-08-28T07:29:08.000Z
2020-07-04T13:45:58.000Z
#include "gCode.h" const QString GCode::GoToOrigin = "~\nG30\n"; const QString GCode::ProcessStop = "!\n"; GCode::GCode() { }
13
46
0.646154
smartDIYs
64c34283515e89185dfb13cf53b7b9047b577488
1,510
hpp
C++
include/mist/it/EntropyMeasure.hpp
andbanman/mist
2546fb41bccea1f89a43dbdbed7ce3a257926b54
[ "MIT" ]
null
null
null
include/mist/it/EntropyMeasure.hpp
andbanman/mist
2546fb41bccea1f89a43dbdbed7ce3a257926b54
[ "MIT" ]
4
2021-03-30T21:40:44.000Z
2021-11-08T18:54:34.000Z
include/mist/it/EntropyMeasure.hpp
andbanman/mist
2546fb41bccea1f89a43dbdbed7ce3a257926b54
[ "MIT" ]
null
null
null
#pragma once #include "../Variable.hpp" #include "Entropy.hpp" #include "EntropyCalculator.hpp" #include "Measure.hpp" namespace mist { namespace it { class EntropyMeasure : public Measure { public: EntropyMeasure(){}; ~EntropyMeasure(){}; result_type compute(EntropyCalculator& ecalc, Variable::indexes const& tuple) const; void compute(EntropyCalculator& ecalc, Variable::indexes const& tuple, result_type& result) const; result_type compute(EntropyCalculator& ecalc, Variable::indexes const& tuple, Entropy const& e) const; void compute(EntropyCalculator& ecalc, Variable::indexes const& tuple, Entropy const& e, result_type& result) const; std::string header(int d, bool full_output) const; std::vector<std::string> const& names(int d, bool full_output) const; enum struct sub_calc_1d : int { entropy0, size }; enum struct sub_calc_2d : int { entropy01, size }; enum struct sub_calc_3d { entropy012, size }; bool full_entropy() const { return false; }; }; class EntropyMeasureException : public std::exception { private: std::string msg; public: EntropyMeasureException(std::string const& method, std::string const& msg) : msg("EntropyMeasure::" + method + " : " + msg) {} virtual const char* what() const throw() { return msg.c_str(); }; }; } // it } // mist
22.205882
76
0.624503
andbanman
64c573639fb18308cbcd10af7d10ca7d4b7cf9aa
153
hh
C++
src/retic/dotdumper.hh
enotnadoske/drunos
79b72078e613c9c5d4e5c37721b726ca3374299b
[ "Apache-2.0" ]
9
2019-04-04T18:03:36.000Z
2019-05-03T23:48:59.000Z
src/retic/dotdumper.hh
enotnadoske/drunos
79b72078e613c9c5d4e5c37721b726ca3374299b
[ "Apache-2.0" ]
16
2019-04-04T12:22:19.000Z
2019-04-09T19:04:42.000Z
src/retic/dotdumper.hh
enotnadoske/drunos
79b72078e613c9c5d4e5c37721b726ca3374299b
[ "Apache-2.0" ]
2
2019-10-11T14:17:26.000Z
2022-03-15T10:06:08.000Z
#pragma once #include <ostream> #include "fdd.hh" namespace runos { namespace retic { void dumpAsDot(const fdd::diagram& d, std::ostream& out); } }
10.928571
57
0.69281
enotnadoske
64c5a136567b9d94d985087bcbc04916f4e313d0
7,650
cpp
C++
bbs/prot/xmodemt.cpp
granitepenguin/wwiv
30669b21f45c5f534014a251f55568c86904f87e
[ "Apache-2.0" ]
157
2015-07-08T18:29:22.000Z
2022-03-10T10:22:58.000Z
bbs/prot/xmodemt.cpp
granitepenguin/wwiv
30669b21f45c5f534014a251f55568c86904f87e
[ "Apache-2.0" ]
1,037
2015-07-18T03:09:12.000Z
2022-03-13T17:39:55.000Z
bbs/prot/xmodemt.cpp
granitepenguin/wwiv
30669b21f45c5f534014a251f55568c86904f87e
[ "Apache-2.0" ]
74
2015-07-08T19:42:19.000Z
2021-12-22T06:15:46.000Z
#ifndef lint static const char rcsid[] = "$Id$"; #endif /* * Copyright (c) 1995 by Edward A. Falk */ /********** * * * @ @ @ @ @@@ @@@@ @@@@@ @ @ @@@@@ * @ @ @@ @@ @ @ @ @ @ @@ @@ @ * @ @ @ @ @ @ @ @ @@@ @ @ @ @ * @ @ @ @ @ @ @ @ @ @ @ @ @ @ * @ @ @ @ @ @@@ @@@@ @@@@@ @ @ @ @ * * XMODEMT - transmit side of xmodem protocol * * Caller sets flags defined in xmodem.h as appropriate. * (default is basic xmodem) * * This code is designed to be called from inside a larger * program, so it is implemented as a state machine where * practical. * * functions: * * XmodemTInit(char *filename, Protocol p) * Initiate a receive * * XmodemTTimeout() * called after timeout expired * * XmodemTRcv(char c) * called after character received * * XmodemTFinish() * last file (ymodem) * * XmodemTAbort() * abort transfer * * all functions return 0 on success, 1 on abort * * Edward A. Falk * * January, 1995 * * * **********/ #include "xmodem.h" #include <cstring> #include <stdio.h> #include <sys/types.h> bool fileInfo = False; /* TODO: WXmodem, YmodemG */ typedef enum { File, /* waiting for initial protocol character */ FileWait, /* sent file header, waiting for ACK */ Start, /* waiting to begin */ Wait, /* sent a packet, waiting for ACK */ Eot, /* sent an EOT, waiting for ACK */ EndWait, /* sent null filename, waiting for ACK */ } XmodemState; static XmodemState state = Start; static bool ymodem; static bool useCrc; /* receiver wants crc */ static int pktLen; /* length of this packet data */ static int pktMaxLen; static char packet[MAXPACKET]; static char pktHdr[3], pktCrc[2]; static int packetId; /* id of last received packet */ static int packetCount; /* # packets received */ static FILE* ifile = NULL; /* input file fd */ static int fileLen, fileDate, fileMode; static int sendFilename(); static int sendPacket(); static int buildPacket(); static int resendPacket(); int XmodemTInit(char* file, Protocol prot) { int err; protocol = prot; ymodem = prot == Ymodem || prot == YmodemG; state = ymodem ? File : Start; strcpy(xmFilename, file); if ((ifile = fopen(xmFilename, "r")) == NULL) { sendCancel(); return XmErrCantOpen; } packetId = 1; packetCount = 0; pktMaxLen = xmodem1k ? 1024 : 128; xmTimeout = 60; return 0; } int XmodemTRcv(char c) { if (c == CAN) { if (ifile != NULL) fclose(ifile); return XmErrCancel; } switch (state) { case File: /* waiting for command, ymodem */ switch (c) { case NAK: useCrc = False; return sendFilename(); case 'C': useCrc = True; return sendFilename(); } break; case FileWait: /* waiting for filename ACK */ switch (c) { case NAK: return resendPacket(); case ACK: state = Start; return 0; } case Start: /* waiting for command, data */ switch (c) { case NAK: /* wants checksums */ if (!ymodem) protocol = Xmodem; useCrc = False; return sendPacket(); case 'C': useCrc = True; return sendPacket(); case 'W': if (!ymodem) { protocol = WXmodem; useCrc = True; /* TODO: WXmodem */ } } break; case Wait: /* waiting for ACK */ switch (c) { case ACK: return sendPacket(); case NAK: return resendPacket(); } break; /* ignore all other characters */ case Eot: /* waiting for ACK after EOT */ switch (c) { case ACK: return XmDone; case NAK: return sendChr(EOT); } break; case EndWait: /* waiting for filename ACK */ switch (c) { case NAK: return resendPacket(); case ACK: return XmDone; } } return 0; } static int sendFilename() { int i; char* ptr; pktLen = 128; /* TODO: protect against long filenames */ strcpy(packet, xmFilename); ptr = packet + strlen(packet) + 1; /* TODO: get file info */ if (fileInfo) { sprintf(ptr, "%d %o %o %o", 0, 0, 0100644); ptr += strlen(ptr) + 1; } /* TODO: what if file desc buffer too big? */ if (ptr > packet + 128) pktLen = 1024; i = pktLen - (ptr - packet); bzero(ptr, i); state = FileWait; packetId = 0; return buildPacket(); } int XmodemTFinish() { int i; char* ptr; pktLen = 128; bzero(packet, pktLen); state = EndWait; packetId = 0; return buildPacket(); } static char* bufptr; static int buflen = 0; static int sendPacket() { int i; /* This code assumes that a incomplete reads can only happen * after EOF. This will fail with pipes. * TODO: try to make pipes work. */ state = Wait; if (buflen > 0) { /* previous incomplete packet */ memcpy(packet, bufptr, 128); bufptr += 128; if (buflen < 128) for (i = buflen; i < 128; ++i) packet[i] = 0x1a; buflen -= 128; pktLen = 128; return buildPacket(); } if ((i = fread(packet, 1, pktMaxLen, ifile)) <= 0) { /* EOF */ state = Eot; return sendChr(EOT); } else if (i == pktMaxLen) { /* full buffer */ pktLen = i; return buildPacket(); } buflen = i; bufptr = packet; pktLen = 128; return buildPacket(); } static int buildPacket() { int i; pktHdr[0] = pktLen == 128 ? SOH : STX; pktHdr[1] = (char)packetId; pktHdr[2] = (char)(255 - packetId); ++packetId; if (useCrc) { i = calcrc(packet, pktLen); pktCrc[0] = (char)(i >> 8); pktCrc[1] = (char)(i & 0xff); } else pktCrc[0] = (char)calcChecksum(packet, pktLen); return resendPacket(); } static int resendPacket() { int i; (i = sendStr(pktHdr, 3)) || (i = sendStr(packet, pktLen)) || (i = sendStr(pktCrc, useCrc ? 2 : 1)); return i; } int XmodemTTimeout() { switch (state) { case File: case Start: return XmErrInitTo; case FileWait: case Wait: case Eot: return XmErrRcvTo; } } int XmodemTAbort() { return sendCancel(); } //#include <unistd.h> #include <fcntl.h> #include <sys/types.h> //#include <sys/time.h> //#include <sys/termios.h> main(argc, argv) int argc; char** argv; { struct termios old_settings, new_settings; fd_set readfds; struct timeval timeout; int i; int len; char buffer[1024]; bool done = False; int filecount = 0; if (argc < 2) exit(2); xmTfd = xmRfd = open(argv[1], O_RDWR); if (xmTfd == -1) exit(1); tcgetattr(xmTfd, &old_settings); new_settings = old_settings; new_settings.c_iflag &= ~(ISTRIP | INLCR | IGNCR | ICRNL | IUCLC | IXON | IXOFF | IMAXBEL); new_settings.c_oflag = 0; new_settings.c_cflag = B300 | CS8 | CREAD | CLOCAL; new_settings.c_lflag = 0; new_settings.c_cc[VMIN] = 32; new_settings.c_cc[VTIME] = 1; tcsetattr(xmTfd, TCSADRAIN, &new_settings); xmodem1k = 1; done = XmodemTInit("xmodem.h", Ymodem) != 0; while (!done) { FD_ZERO(&readfds); FD_SET(xmTfd, &readfds); timeout.tv_sec = xmTimeout; timeout.tv_usec = 0; i = select(xmTfd + 1, &readfds, NULL, NULL, &timeout); if (i < 0) perror("select"); else if (i == 0) done = XmodemTTimeout() != 0; else { len = read(xmTfd, buffer, sizeof(buffer)); for (i = 0; !done && i < len; ++i) done = XmodemTRcv(buffer[i]) != 0; } if (done) { switch (++filecount) { case 1: done = XmodemTInit("crc.c", Ymodem) != 0; break; case 2: done = XmodemTFinish(); break; case 3: break; } } } tcsetattr(xmTfd, TCSADRAIN, &old_settings); exit(0); }
19.97389
93
0.573856
granitepenguin
64c8870e32bb42092057ecf7f9eb185e3d1ee285
226
cpp
C++
fileio/FileWriterFactory.cpp
lw983165/OpsMain
0bcb5dc8e222cd5f448953b0ce41367671326004
[ "Apache-2.0" ]
null
null
null
fileio/FileWriterFactory.cpp
lw983165/OpsMain
0bcb5dc8e222cd5f448953b0ce41367671326004
[ "Apache-2.0" ]
null
null
null
fileio/FileWriterFactory.cpp
lw983165/OpsMain
0bcb5dc8e222cd5f448953b0ce41367671326004
[ "Apache-2.0" ]
null
null
null
#include "FileWriterFactory.hpp" #include "JsonFileWriter.hpp" IFileWriter *FileWriterFactory::create(const std::string &format) { if (format == "json") { return new JsonFileWriter(); } return nullptr; }
18.833333
65
0.676991
lw983165
64cdffd116221a9d6babd928abf2c6992aa3892b
10,778
cpp
C++
coverage/explicit.cpp
m-tosch/mu
2d2baf242119fe5555a59d3d63bcc42acb477755
[ "MIT" ]
null
null
null
coverage/explicit.cpp
m-tosch/mu
2d2baf242119fe5555a59d3d63bcc42acb477755
[ "MIT" ]
109
2020-10-06T16:33:15.000Z
2021-02-08T10:54:56.000Z
coverage/explicit.cpp
m-tosch/mu
2d2baf242119fe5555a59d3d63bcc42acb477755
[ "MIT" ]
null
null
null
#include "mu/matrix.h" #include "mu/vector.h" #include "mu/vector2d.h" #include "mu/vector3d.h" /** * Instantiate this template class and template functions explicitly so that all * functions are generated and thus, the coverage report is accurate. */ /********************************* Vector **********************************/ /* class */ template class mu::Vector<2, float>; /* functions */ template float mu::Vector<2, float>::length<float>() const; template float mu::Vector<2, int>::mean<float>() const; template float mu::Vector<2, int>::dot<float>(const mu::Vector<2, int> &) const; template float mu::Vector<2, int>::std<float>() const; // workaround for "lambda functions are not allowed in unevaluated operands" struct LambdaCompare { bool operator()(int a, int b) const { return a > b; } }; template void mu::Vector<2, float>::sort(const LambdaCompare &); template mu::Vector<2, float> mu::Vector<2, float>::sorted( const LambdaCompare &) const; /* operators */ template std::ostream &mu::operator<<<2, float>(std::ostream &, const mu::Vector<2, float> &); /* convenience functions */ /* these functions take a single Vector as argument, so they're here. * functions that take e.g a combination of Vectors as argument are * elsewhere */ template float mu::min(const mu::Vector<2, float> &); template float mu::max(const mu::Vector<2, float> &); template float mu::sum(const mu::Vector<2, float> &); template float mu::mean<float>(const mu::Vector<2, int> &); template void mu::flip(mu::Vector<2, float> &); template mu::Vector<2, float> mu::flipped(const mu::Vector<2, float> &); template void mu::sort(mu::Vector<2, float> &); template void mu::sort(mu::Vector<2, float> &, const LambdaCompare &); template mu::Vector<2, float> mu::sorted(const mu::Vector<2, float> &); template mu::Vector<2, float> mu::sorted(const mu::Vector<2, float> &, const LambdaCompare &); template mu::Vector<2, int> mu::ones<2>(); template mu::Vector<2, int> mu::zeros<2>(); /******************************** Vector2D *********************************/ /* class */ template class mu::Vector2D<float>; /* functions */ template void mu::Vector2D<float>::rotate<float>(float); template mu::Vector2D<float> mu::Vector2D<float>::rotated<float>(float); /******************************** Vector3D *********************************/ /* class */ template class mu::Vector3D<float>; /**************************** Vector <> Scalar *****************************/ /* addition */ template mu::Vector<2, float> &mu::Vector<2, float>::operator+= <float>(const float &); template mu::Vector<2, float> mu::operator+ <2, float, float>(const mu::Vector<2, float> &, const float &); template mu::Vector<2, float> mu::operator+ <2, float, float>(const float &, const mu::Vector<2, float> &); /* subtraction */ template mu::Vector<2, float> &mu::Vector<2, float>::operator-= <float>(const float &); template mu::Vector<2, float> mu::operator- <2, float, float>(const mu::Vector<2, float> &, const float &); /* multiplication */ template mu::Vector<2, float> &mu::Vector<2, float>::operator*= <float>(const float &); template mu::Vector<2, float> mu::operator* <2, float, float>(const mu::Vector<2, float> &, const float &); template mu::Vector<2, float> mu::operator* <2, float, float>(const float &, const mu::Vector<2, float> &); /* division */ template mu::Vector<2, float> &mu::Vector<2, float>::operator/= <float>(const float &); template mu::Vector<2, float> mu::operator/ <2, float, float>(const mu::Vector<2, float> &, const float &); /**************************** Vector <> Vector *****************************/ /***** constructors *****/ /* constructor (construct-from-different-typed-vector) */ template mu::Vector<2, float>::Vector(const mu::Vector<2, int> &); /* constructor (construct-from-different-typed-array) */ template mu::Vector<2, float>::Vector(const std::array<int, 2> &); /* constructor (construct-from-different-typed-single-value) */ template mu::Vector<2, float>::Vector(const int &); /********* math ********/ /* note: +=, -=, *= and /= do not have to be explicitly instantiated */ /* addition */ template mu::Vector<2, float> mu::operator+ <2, float, int>(const mu::Vector<2, float> &, const mu::Vector<2, int> &); /* subtraction */ template mu::Vector<2, float> mu::operator- <2, float, int>(const mu::Vector<2, float> &, const mu::Vector<2, int> &); /* multiplication */ template mu::Vector<2, float> mu::operator* <2, float, int>(const mu::Vector<2, float> &, const mu::Vector<2, int> &); /* division */ template mu::Vector<2, float> mu::operator/ <2, float, int>(const mu::Vector<2, float> &, const mu::Vector<2, int> &); /* equality (this operator is also called by gtest. probably ContainerEq...) */ template bool mu::Vector<2, float>::operator== <int>(const mu::Vector<2, int> &) const; /* inequality */ template bool mu::Vector<2, float>::operator!= <int>(const mu::Vector<2, int> &) const; /********* vector specific ********/ /* convenience functions */ /* these functions should take a combination of Vectors, so they're here. * functions that take e.g a single Vector as argument are elsewhere */ template int mu::dot<int, 2, float, 2, float>(const mu::Vector<2, float> &, const mu::Vector<2, float> &); /**************************** Vector <> Matrix *****************************/ /* member functions */ template mu::Vector<3, int> mu::Vector<2, int>::dot( const mu::Matrix<2, 3, int> &) const; /* convenience functions */ template mu::Vector<3, int> mu::dot(const mu::Vector<2, int> &, const mu::Matrix<2, 3, int> &); /********************************* Matrix **********************************/ /* class */ template class mu::Matrix<2, 2, float>; /* functions */ template mu::Matrix<2, 2, int> mu::Matrix<2, 3, int>::dot( const mu::Matrix<3, 2, int> &) const; template float mu::Matrix<2, 2, int>::std<float>() const; /* operators */ template std::ostream &mu::operator<<<2, 2, float>( std::ostream &, const mu::Matrix<2, 2, float> &); /* convenience functions */ /* these functions take a single Matrix as argument, so they're here. functions * that take e.g a combination of Matrices as argument are elsewhere */ template float mu::min(const mu::Matrix<2, 2, float> &); template float mu::max(const mu::Matrix<2, 2, float> &); template float mu::sum(const mu::Matrix<2, 2, float> &); template float mu::mean<float>(const mu::Matrix<2, 2, float> &); template mu::Vector<2, float> mu::diag(const mu::Matrix<2, 2, float> &); template int mu::det(const mu::Matrix<2, 2, int> &); template void mu::transpose(mu::Matrix<2, 2, int> &); template mu::Matrix<2, 3, int> mu::transposed(const mu::Matrix<3, 2, int> &); template mu::Matrix<3, 3, int> mu::eye<3>(); template mu::Matrix<3, 3, int> mu::ones<3, 3>(); template mu::Matrix<3, 3, int> mu::zeros<3, 3>(); /**************************** Matrix <> Scalar *****************************/ /* addition */ template mu::Matrix<2, 2, float> &mu::Matrix<2, 2, float>::operator+= <float>(const float &); template mu::Matrix<2, 2, float> mu::operator+ <2, 2, float, float>(const mu::Matrix<2, 2, float> &, const float &); template mu::Matrix<2, 2, float> mu::operator+ <2, 2, float, float>(const float &, const mu::Matrix<2, 2, float> &); /* subtraction */ template mu::Matrix<2, 2, float> &mu::Matrix<2, 2, float>::operator-= <float>(const float &); template mu::Matrix<2, 2, float> mu::operator- <2, 2, float, float>(const mu::Matrix<2, 2, float> &, const float &); /* multiplication */ template mu::Matrix<2, 2, float> &mu::Matrix<2, 2, float>::operator*= <float>(const float &); template mu::Matrix<2, 2, float> mu::operator* <2, 2, float, float>(const mu::Matrix<2, 2, float> &, const float &); template mu::Matrix<2, 2, float> mu::operator* <2, 2, float, float>(const float &, const mu::Matrix<2, 2, float> &); /* division */ template mu::Matrix<2, 2, float> &mu::Matrix<2, 2, float>::operator/= <float>(const float &); template mu::Matrix<2, 2, float> mu::operator/ <2, 2, float, float>(const mu::Matrix<2, 2, float> &, const float &); /**************************** Matrix <> Matrix *****************************/ /***** constructors *****/ /* constructor (construct-from-different-typed-matrix) */ template mu::Matrix<2, 2, float>::Matrix(const mu::Matrix<2, 2, int> &); /* constructor (construct-from-different-typed-array) */ template mu::Matrix<2, 2, float>::Matrix( const std::array<mu::Vector<2, int>, 2> &); /* constructor (construct-from-different-typed-single-value) */ template mu::Matrix<2, 2, float>::Matrix(const int &); /********* math ********/ /* note: +=, -=, *= and /= do not have to be explicitly instantiated */ /* addition */ template mu::Matrix<2, 2, float> mu::operator+ <2, 2, float, int>(const mu::Matrix<2, 2, float> &, const mu::Matrix<2, 2, int> &); /* subtraction */ template mu::Matrix<2, 2, float> mu::operator- <2, 2, float, int>(const mu::Matrix<2, 2, float> &, const mu::Matrix<2, 2, int> &); /* multiplication */ template mu::Matrix<2, 2, float> mu::operator* <2, 2, float, int>(const mu::Matrix<2, 2, float> &, const mu::Matrix<2, 2, int> &); /* division */ template mu::Matrix<2, 2, float> mu::operator/ <2, 2, float, int>(const mu::Matrix<2, 2, float> &, const mu::Matrix<2, 2, int> &); /* equality (this operator is also called by gtest. probably ContainerEq...) */ template bool mu::Matrix<2, 2, float>::operator== <int>(const mu::Matrix<2, 2, int> &) const; /* inequality */ template bool mu::Matrix<2, 2, float>::operator!= <int>(const mu::Matrix<2, 2, int> &) const; /********* matrix specific ********/ /* constructor (construct-from-different-typed-array-of-array) */ template mu::Matrix<2, 2, float>::Matrix( const std::array<std::array<int, 2>, 2> &); /* convenience functions */ /* these functions should take a combination of Matrices, so they're here. * functions that take e.g a single Matrix as argument are elsewhere */ template mu::Matrix<2, 2, int> mu::dot(const mu::Matrix<2, 3, int> &, const mu::Matrix<3, 2, int> &); /**************************** Matrix <> Vector *****************************/ /* member functions */ template mu::Vector<2, int> mu::Matrix<2, 3, int>::dot( const mu::Vector<3, int> &) const; /* convenience functions */ template mu::Vector<2, int> mu::dot(const mu::Matrix<2, 3, int> &, const mu::Vector<3, int> &);
43.991837
80
0.592318
m-tosch
64d1c08f82af1a6ccde840e28dd76aed1addedc3
2,031
hh
C++
src/system/io/fileReader.hh
othieno/clockwork
ac2b7d2e0324fff1440df90670de181dce234dd0
[ "MIT" ]
6
2016-09-19T09:02:32.000Z
2021-03-01T05:50:53.000Z
src/system/io/fileReader.hh
othieno/clockwork
ac2b7d2e0324fff1440df90670de181dce234dd0
[ "MIT" ]
null
null
null
src/system/io/fileReader.hh
othieno/clockwork
ac2b7d2e0324fff1440df90670de181dce234dd0
[ "MIT" ]
2
2016-06-01T02:18:07.000Z
2021-06-25T13:32:22.000Z
/* * This file is part of Clockwork. * * Copyright (c) 2013-2016 Jeremy Othieno. * * The MIT License (MIT) * 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. */ #ifndef CLOCKWORK_FILE_READER_HH #define CLOCKWORK_FILE_READER_HH #include "Error.hh" /** * @see QFile. */ class QFile; /** * @see QString. */ class QString; namespace clockwork { /** * @see graphics/Material.hh. */ class Material; /** * @see graphics/Mesh.hh. */ class Mesh; /** * Parses a .mat file. * @param file the file containing the data to parse. * @param materialName the material name. * @param material a reference to the material where the data will be stored. */ Error parseMATFile(QFile& file, const QString& materialName, Material& material); /** * Parses a .obj file. * @param file the file containing the data to parse. * @param mesh a reference to the polygon mesh where the data will be stored. */ Error parseOBJFile(QFile& file, Mesh& mesh); } // namespace clockwork #endif // CLOCKWORK_FILE_READER_HH
31.734375
81
0.736583
othieno
64d2e0b165e52b8d8c186131c8f95a365c40bea1
8,064
cpp
C++
DreamDaq/VMElib/X742CorrectionRoutines.cpp
ivivarel/DREMTubes
ac768990b4c5e2c23d986284ed10189f31796b38
[ "MIT" ]
3
2021-07-22T12:17:48.000Z
2021-07-27T07:22:54.000Z
DreamDaq/VMElib/X742CorrectionRoutines.cpp
ivivarel/DREMTubes
ac768990b4c5e2c23d986284ed10189f31796b38
[ "MIT" ]
38
2021-07-14T15:41:04.000Z
2022-03-29T14:18:20.000Z
DreamDaq/VMElib/X742CorrectionRoutines.cpp
ivivarel/DREMTubes
ac768990b4c5e2c23d986284ed10189f31796b38
[ "MIT" ]
7
2021-07-21T12:00:33.000Z
2021-11-13T10:45:30.000Z
#include <string.h> #include "X742CorrectionRoutines.h" static void PeakCorrection(CAEN_DGTZ_X742_GROUP_t* dataout) { int32_t offset; int32_t chaux_en; uint32_t i; int32_t j; chaux_en = (dataout->ChSize[8] == 0)? 0:1; for(j=0; j<(8+chaux_en); j++){ dataout->DataChannel[j][0] = dataout->DataChannel[j][1]; } for(i=1; i<dataout->ChSize[0]; i++){ offset=0; for(j=0; j<8; j++){ if (i==1){ if ((dataout->DataChannel[j][2]- dataout->DataChannel[j][1])>30){ offset++; } else { if (((dataout->DataChannel[j][3]- dataout->DataChannel[j][1])>30)&&((dataout->DataChannel[j][3]- dataout->DataChannel[j][2])>30)){ offset++; } } } else{ if ((i==dataout->ChSize[j]-1)&&((dataout->DataChannel[j][dataout->ChSize[j]-2]- dataout->DataChannel[j][dataout->ChSize[j]-1])>30)){ offset++; } else{ if ((dataout->DataChannel[j][i-1]- dataout->DataChannel[j][i])>30){ if ((dataout->DataChannel[j][i+1]- dataout->DataChannel[j][i])>30) offset++; else { if ((i==dataout->ChSize[j]-2)||((dataout->DataChannel[j][i+2]-dataout->DataChannel[j][i])>30)) offset++; } } } } } if (offset==8){ for(j=0; j<(8+chaux_en); j++){ if (i==1){ if ((dataout->DataChannel[j][2]- dataout->DataChannel[j][1])>30) { dataout->DataChannel[j][0]=dataout->DataChannel[j][2]; dataout->DataChannel[j][1]=dataout->DataChannel[j][2]; } else{ dataout->DataChannel[j][0]=dataout->DataChannel[j][3]; dataout->DataChannel[j][1]=dataout->DataChannel[j][3]; dataout->DataChannel[j][2]=dataout->DataChannel[j][3]; } } else{ if (i==dataout->ChSize[j]-1){ dataout->DataChannel[j][dataout->ChSize[j]-1]=dataout->DataChannel[j][dataout->ChSize[j]-2]; } else{ if ((dataout->DataChannel[j][i+1]- dataout->DataChannel[j][i])>30) dataout->DataChannel[j][i]=((dataout->DataChannel[j][i+1]+dataout->DataChannel[j][i-1])/2); else { if (i==dataout->ChSize[j]-2){ dataout->DataChannel[j][dataout->ChSize[j]-2]=dataout->DataChannel[j][dataout->ChSize[j]-3]; dataout->DataChannel[j][dataout->ChSize[j]-1]=dataout->DataChannel[j][dataout->ChSize[j]-3]; } else { dataout->DataChannel[j][i]=((dataout->DataChannel[j][i+2]+dataout->DataChannel[j][i-1])/2); dataout->DataChannel[j][i+1]=( (dataout->DataChannel[j][i+2]+dataout->DataChannel[j][i-1])/2); } } } } } } } } static int32_t read_flash_page(int32_t handle, uint8_t gr, int8_t* page, uint32_t pagenum) { uint32_t flash_addr; uint16_t dd; uint32_t i,tmp[528]; uint32_t fl_a[528]; uint8_t addr0,addr1,addr2; int32_t ret; CAENComm_ErrorCode err[528]; flash_addr = pagenum<<9; addr0 = (uint8_t)flash_addr; addr1 = (uint8_t)(flash_addr>>8); addr2 = (uint8_t)(flash_addr>>16); dd=0xffff; while ((dd>>2)& 0x1) if ((ret = CAENComm_Read16(handle, STATUS(gr), &dd)) != CAENComm_Success) return -1; // enable flash (NCS = 0) if ((ret = CAENComm_Write16(handle, SEL_FLASH(gr), (int16_t)1)) != CAENComm_Success) return -1; // write opcode if ((ret = CAENComm_Write16(handle, FLASH(gr), (int16_t)MAIN_MEM_PAGE_READ)) != CAENComm_Success) return -1; // write address dd=0xffff; if ((ret = CAENComm_Write16(handle, FLASH(gr), (int16_t)addr2)) != CAENComm_Success) return -1; dd=0xffff; if ((ret = CAENComm_Write16(handle, FLASH(gr), (int16_t)addr1)) != CAENComm_Success) return -1; dd=0xffff; if ((ret = CAENComm_Write16(handle, FLASH(gr), (int16_t)addr0)) != CAENComm_Success) return -1; // additional don't care bytes for (i=0; i<4; i++) { dd=0xffff; if ((ret = CAENComm_Write16(handle, FLASH(gr), (int16_t)0)) != CAENComm_Success) return -1; } for (i=0; i<528; i+=2) { fl_a[i] = FLASH(gr); fl_a[i+1] = STATUS(gr); } if ((ret = CAENComm_MultiRead32(handle,fl_a,528,tmp,err)) != CAENComm_Success) return -1; for (i=0; i<528; i+=2) page[(int32_t)(i/2)] = (int8_t)tmp[i]; // disable flash (NCS = 1) if ((ret = CAENComm_Write16(handle, SEL_FLASH(gr), (int16_t)0)) != CAENComm_Success) return -1; return 0; } int32_t LoadCorrectionTables(int32_t handle, DataCorrection_t* Table, uint8_t group, uint32_t frequency) { uint32_t pagenum = 0,i,n,j,start; int8_t TempCell[264]; // int8_t* p; int32_t ret; int8_t tmp[0x1000]; // 256byte * 16 pagine for (n=0;n<MAX_X742_CHANNELS+1;n++) { pagenum = 0; pagenum = (group %2) ? 0xC00: 0x800; pagenum |= frequency << 8; pagenum |= n << 2; // load the Offset Cell Correction p = TempCell; start = 0; for (i=0;i<4;i++) { int32_t endidx = 256; if ((ret =read_flash_page(handle,group,p,pagenum)) != 0) return ret; // peak correction for (j=start;j<(start+256);j++) { if (p[j-start] != 0x7f) { Table->cell[n][j] = p[j-start]; } else { int16_t cel = (int16_t)((((uint8_t)(p[endidx+1])) << 0x08) |((uint8_t) p[endidx])); if (cel == 0) Table->cell[n][j] = p[j-start]; else Table->cell[n][j] = cel; endidx+=2; if (endidx > 263) endidx = 256; } } start +=256; pagenum++; } start = 0; // load the Offset Num Samples Correction p = TempCell; pagenum &= 0xF00; pagenum |= 0x40; pagenum |= n << 2; for (i=0;i<4;i++) { if ((ret =read_flash_page(handle,group,p,pagenum)) != 0) return ret; for (j=start;j<start+256;j++) Table->nsample[n][j] = p[j-start]; start +=256; pagenum++; } if (n == MAX_X742_CHANNELS) { // load the Time Correction p = TempCell; pagenum &= 0xF00; pagenum |= 0xA0; start = 0; for (i=0;i<16;i++) { if ((ret =read_flash_page(handle,group,p,pagenum)) != 0) return ret; for (j=start;j<start+256;j++) tmp[j] = p[j-start]; start +=256; pagenum++; } for (i=0;i<1024;i++) { p = (int8_t*) &(Table->time[i]); p[0] = tmp[i*4]; p[1] = tmp[(i*4)+1]; p[2] = tmp[(i*4)+2]; p[3] = tmp[(i*4)+3]; } } } return 0; } void ApplyDataCorrection(DataCorrection_t* CTable, CAEN_DGTZ_DRS4Frequency_t frequency, int32_t CorrectionLevelMask, CAEN_DGTZ_X742_GROUP_t* data) { int32_t i, j, size1, trg = 0,k; float Time[1024],t0; float Tsamp; float vcorr; uint16_t st_ind=0; float wave_tmp[1024]; int32_t cellCorrection =CorrectionLevelMask & 0x1; int32_t nsampleCorrection = (CorrectionLevelMask & 0x2) >> 1; int32_t timeCorrection = (CorrectionLevelMask & 0x4) >> 2; switch(frequency) { case CAEN_DGTZ_DRS4_2_5GHz: Tsamp =(float)((1.0/2500.0)*1000.0); break; case CAEN_DGTZ_DRS4_1GHz: Tsamp =(float)((1.0/1000.0)*1000.0); break; default: Tsamp =(float)((1.0/5000.0)*1000.0); break; } if (data->ChSize[8] != 0) trg = 1; st_ind =(uint16_t)(data->StartIndexCell); for (i=0;i<MAX_X742_CHANNEL_SIZE;i++) { size1 = data->ChSize[i]; for (j=0;j<size1;j++) { if (cellCorrection) data->DataChannel[i][j] -= CTable->cell[i][((st_ind+j) % 1024)]; if (nsampleCorrection) data->DataChannel[i][j] -= CTable->nsample[i][j]; } } if (cellCorrection) PeakCorrection(data); if (!timeCorrection) return; t0 = CTable->time[st_ind]; Time[0]=0.0; for(j=1; j < 1024; j++) { t0= CTable->time[(st_ind+j)%1024]-t0; if (t0 >0) Time[j] = Time[j-1]+ t0; else Time[j] = Time[j-1]+ t0 + (Tsamp*1024); t0 = CTable->time[(st_ind+j)%1024]; } for (j=0;j<8+trg;j++) { data->DataChannel[j][0] = data->DataChannel[j][1]; wave_tmp[0] = data->DataChannel[j][0]; vcorr = 0.0; k=0; i=0; for(i=1; i<1024; i++) { while ((k<1024-1) && (Time[k]<(i*Tsamp))) k++; vcorr =(((float)(data->DataChannel[j][k] - data->DataChannel[j][k-1])/(Time[k]-Time[k-1]))*((i*Tsamp)-Time[k-1])); wave_tmp[i]= data->DataChannel[j][k-1] + vcorr; k--; } memcpy(data->DataChannel[j],wave_tmp,1024*sizeof(float)); } }
30.315789
148
0.586682
ivivarel
64d57c21faa94656db73d848a7430425b162cddc
1,119
cpp
C++
codes/leetcode/BasicCalculatorll.cpp
smmehrab/problem-solving
4aeab1673f18d3270ee5fc9b64ed6805eacf4af5
[ "MIT" ]
null
null
null
codes/leetcode/BasicCalculatorll.cpp
smmehrab/problem-solving
4aeab1673f18d3270ee5fc9b64ed6805eacf4af5
[ "MIT" ]
null
null
null
codes/leetcode/BasicCalculatorll.cpp
smmehrab/problem-solving
4aeab1673f18d3270ee5fc9b64ed6805eacf4af5
[ "MIT" ]
null
null
null
/* ************************************************ username : smmehrab fullname : s.m.mehrabul islam email : mehrab.24csedu.001@gmail.com institute : university of dhaka, bangladesh session : 2017-2018 ************************************************ */ class Solution { public: int calculate(string input) { char operation = '+'; int operand, otherOperand, finalAnswer=0; stack<int> answers; istringstream inputstream(input); while(inputstream >> operand){ if(operation=='+') answers.push(operand); else if(operation=='-') answers.push(operand*(-1)); else{ otherOperand = answers.top(); answers.pop(); if(operation=='*') answers.push(otherOperand*operand); else if(operation=='/') answers.push(otherOperand/operand); } inputstream >> operation; } while(!answers.empty()){ finalAnswer += answers.top(); answers.pop(); } return finalAnswer; } };
31.083333
75
0.487042
smmehrab
64d752353088959200a39a2ff0477db3d8b97e3b
14,590
cpp
C++
Core/Unix/CoreUnix.cpp
screwjack/nemesis
8c2587d2aa60f8da6cf49e5f4f5740bf2666c6fd
[ "BSD-2-Clause" ]
2
2016-10-15T05:12:16.000Z
2016-11-06T16:19:53.000Z
Core/Unix/CoreUnix.cpp
screwjack/nemesis
8c2587d2aa60f8da6cf49e5f4f5740bf2666c6fd
[ "BSD-2-Clause" ]
14
2016-09-21T21:24:46.000Z
2016-11-15T07:54:21.000Z
Core/Unix/CoreUnix.cpp
screwjack/nemesis
8c2587d2aa60f8da6cf49e5f4f5740bf2666c6fd
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2016 nemesis project/mrn@sdf.org. All rights reserved. http://mrn.sixbit.org/ Governed by the BSD 2 Clause license, the full text of which is contained in the file License.txt included in nemesis binary and source code distribution packages. Based on TrueCrypt 7.1a, which was governed by the TrueCrypt license, which is also made available with nemesis. */ #include "CoreUnix.h" #include <errno.h> #include <iostream> #include <signal.h> #include <sys/stat.h> #include <sys/types.h> #include <stdio.h> #include <unistd.h> #include "Platform/FileStream.h" #include "Driver/Fuse/FuseService.h" #include "Volume/VolumePasswordCache.h" namespace nemesis { CoreUnix::CoreUnix () { signal (SIGPIPE, SIG_IGN); char *loc = setlocale (LC_ALL, ""); if (!loc || string (loc) == "C") setlocale (LC_ALL, "en_US.UTF-8"); } CoreUnix::~CoreUnix () { } void CoreUnix::CheckFilesystem (shared_ptr <VolumeInfo> mountedVolume, bool repair) const { if (!mountedVolume->MountPoint.IsEmpty()) DismountFilesystem (mountedVolume->MountPoint, false); list <string> args; args.push_back ("-T"); args.push_back ("fsck"); args.push_back ("-e"); string xargs = "fsck "; #ifdef TC_LINUX if (!repair) xargs += "-n "; else xargs += "-r "; #endif xargs += string (mountedVolume->VirtualDevice) + "; echo '[Done]'; read W"; args.push_back (xargs); try { Process::Execute ("xterm", args, 1000); } catch (TimeOut&) { } } void CoreUnix::DismountFilesystem (const DirectoryPath &mountPoint, bool force) const { list <string> args; #ifdef TC_MACOSX if (force) args.push_back ("-f"); #endif args.push_back ("--"); args.push_back (mountPoint); Process::Execute ("umount", args); } shared_ptr <VolumeInfo> CoreUnix::DismountVolume (shared_ptr <VolumeInfo> mountedVolume, bool ignoreOpenFiles, bool syncVolumeInfo) { if (!mountedVolume->MountPoint.IsEmpty()) { DismountFilesystem (mountedVolume->MountPoint, ignoreOpenFiles); // Delete mount directory if a default path has been used if (string (mountedVolume->MountPoint).find (GetDefaultMountPointPrefix()) == 0) mountedVolume->MountPoint.Delete(); } try { DismountNativeVolume (mountedVolume); } catch (NotApplicable &) { } if (!mountedVolume->LoopDevice.IsEmpty()) { try { DetachLoopDevice (mountedVolume->LoopDevice); } catch (ExecutedProcessFailed&) { } } if (syncVolumeInfo || mountedVolume->Protection == VolumeProtection::HiddenVolumeReadOnly) { sync(); VolumeInfoList ml = GetMountedVolumes (mountedVolume->Path); if (ml.size() > 0) mountedVolume = ml.front(); } list <string> args; args.push_back ("--"); args.push_back (mountedVolume->AuxMountPoint); for (int t = 0; true; t++) { try { Process::Execute ("umount", args); break; } catch (ExecutedProcessFailed&) { if (t > 10) throw; Thread::Sleep (200); } } try { mountedVolume->AuxMountPoint.Delete(); } catch (...) { } VolumeEventArgs eventArgs (mountedVolume); VolumeDismountedEvent.Raise (eventArgs); return mountedVolume; } bool CoreUnix::FilesystemSupportsLargeFiles (const FilePath &filePath) const { string path = filePath; size_t pos; while ((pos = path.find_last_of ('/')) != string::npos) { path = path.substr (0, pos); if (path.empty()) break; try { MountedFilesystemList filesystems = GetMountedFilesystems (DevicePath(), path); if (!filesystems.empty()) { const MountedFilesystem &fs = *filesystems.front(); if (fs.Type == "fat" || fs.Type == "fat32" || fs.Type == "vfat" || fs.Type == "fatfs" || fs.Type == "msdos" || fs.Type == "msdosfs" || fs.Type == "umsdos" || fs.Type == "dos" || fs.Type == "dosfs" || fs.Type == "pcfs" ) { return false; } return true; } } catch (...) { } } return true; // Prevent errors if the filesystem cannot be identified } bool CoreUnix::FilesystemSupportsUnixPermissions (const DevicePath &devicePath) const { File device; device.Open (devicePath); Buffer bootSector (device.GetDeviceSectorSize()); device.SeekAt (0); device.ReadCompleteBuffer (bootSector); byte *b = bootSector.Ptr(); return memcmp (b + 3, "NTFS", 4) != 0 && memcmp (b + 54, "FAT", 3) != 0 && memcmp (b + 82, "FAT32", 5) != 0 && memcmp (b + 3, "EXFAT", 5) != 0; } string CoreUnix::GetDefaultMountPointPrefix () const { const char *envPrefix = getenv ("TRUECRYPT_MOUNT_PREFIX"); if (envPrefix && !string (envPrefix).empty()) return envPrefix; if (FilesystemPath ("/media").IsDirectory()) return "/media/truecrypt"; if (FilesystemPath ("/mnt").IsDirectory()) return "/mnt/truecrypt"; return GetTempDirectory() + "/truecrypt_mnt"; } uint32 CoreUnix::GetDeviceSectorSize (const DevicePath &devicePath) const { File dev; dev.Open (devicePath); return dev.GetDeviceSectorSize(); } uint64 CoreUnix::GetDeviceSize (const DevicePath &devicePath) const { File dev; dev.Open (devicePath); return dev.Length(); } DirectoryPath CoreUnix::GetDeviceMountPoint (const DevicePath &devicePath) const { DevicePath devPath = devicePath; #ifdef TC_MACOSX if (string (devPath).find ("/dev/rdisk") != string::npos) devPath = string ("/dev/") + string (devicePath).substr (6); #endif MountedFilesystemList mountedFilesystems = GetMountedFilesystems (devPath); if (mountedFilesystems.size() < 1) return DirectoryPath(); return mountedFilesystems.front()->MountPoint; } VolumeInfoList CoreUnix::GetMountedVolumes (const VolumePath &volumePath) const { VolumeInfoList volumes; foreach_ref (const MountedFilesystem &mf, GetMountedFilesystems ()) { if (string (mf.MountPoint).find (GetFuseMountDirPrefix()) == string::npos) continue; shared_ptr <VolumeInfo> mountedVol; try { shared_ptr <File> controlFile (new File); controlFile->Open (string (mf.MountPoint) + FuseService::GetControlPath()); shared_ptr <Stream> controlFileStream (new FileStream (controlFile)); mountedVol = Serializable::DeserializeNew <VolumeInfo> (controlFileStream); } catch (...) { continue; } if (!volumePath.IsEmpty() && wstring (mountedVol->Path).compare (volumePath) != 0) continue; mountedVol->AuxMountPoint = mf.MountPoint; if (!mountedVol->VirtualDevice.IsEmpty()) { MountedFilesystemList mpl = GetMountedFilesystems (mountedVol->VirtualDevice); if (mpl.size() > 0) mountedVol->MountPoint = mpl.front()->MountPoint; } volumes.push_back (mountedVol); if (!volumePath.IsEmpty()) break; } return volumes; } gid_t CoreUnix::GetRealGroupId () const { const char *env = getenv ("SUDO_GID"); if (env) { try { string s (env); return static_cast <gid_t> (StringConverter::ToUInt64 (s)); } catch (...) { } } return getgid(); } uid_t CoreUnix::GetRealUserId () const { const char *env = getenv ("SUDO_UID"); if (env) { try { string s (env); return static_cast <uid_t> (StringConverter::ToUInt64 (s)); } catch (...) { } } return getuid(); } string CoreUnix::GetTempDirectory () const { char *envDir = getenv ("TMPDIR"); return envDir ? envDir : "/tmp"; } bool CoreUnix::IsMountPointAvailable (const DirectoryPath &mountPoint) const { return GetMountedFilesystems (DevicePath(), mountPoint).size() == 0; } void CoreUnix::MountFilesystem (const DevicePath &devicePath, const DirectoryPath &mountPoint, const string &filesystemType, bool readOnly, const string &systemMountOptions) const { if (GetMountedFilesystems (DevicePath(), mountPoint).size() > 0) throw MountPointUnavailable (SRC_POS); list <string> args; string options; if (!filesystemType.empty()) { #ifdef TC_SOLARIS args.push_back ("-F"); #else args.push_back ("-t"); #endif args.push_back (filesystemType); } if (readOnly) options = "-oro"; if (!systemMountOptions.empty()) { if (options.empty()) options = "-o"; else options += ","; options += systemMountOptions; } printf("debug: %s %s \n", options.c_str(), filesystemType.c_str()); if (!options.empty()) args.push_back (options); args.push_back ("--"); args.push_back (devicePath); args.push_back (mountPoint); Process::Execute ("mount", args); } VolumeSlotNumber CoreUnix::MountPointToSlotNumber (const DirectoryPath &mountPoint) const { string mountPointStr (mountPoint); if (mountPointStr.find (GetDefaultMountPointPrefix()) == 0) { try { return StringConverter::ToUInt32 (StringConverter::GetTrailingNumber (mountPointStr)); } catch (...) { } } return GetFirstFreeSlotNumber(); } shared_ptr <VolumeInfo> CoreUnix::MountVolume (MountOptions &options) { CoalesceSlotNumberAndMountPoint (options); if (IsVolumeMounted (*options.Path)) throw VolumeAlreadyMounted (SRC_POS); Cipher::EnableHwSupport (!options.NoHardwareCrypto); shared_ptr <Volume> volume; while (true) { try { volume = OpenVolume ( options.Path, options.PreserveTimestamps, options.Password, options.Keyfiles, options.Protection, options.ProtectionPassword, options.ProtectionKeyfiles, options.SharedAccessAllowed, VolumeType::Unknown, options.UseBackupHeaders, options.PartitionInSystemEncryptionScope ); options.Password.reset(); } catch (SystemException &e) { if (options.Protection != VolumeProtection::ReadOnly && (e.GetErrorCode() == EROFS || e.GetErrorCode() == EACCES || e.GetErrorCode() == EPERM)) { // Read-only filesystem options.Protection = VolumeProtection::ReadOnly; continue; } throw; } break; } if (options.Path->IsDevice()) { if (volume->GetFile()->GetDeviceSectorSize() != volume->GetSectorSize()) throw ParameterIncorrect (SRC_POS); #if defined (TC_LINUX) if (volume->GetSectorSize() != TC_SECTOR_SIZE_LEGACY) { if (options.Protection == VolumeProtection::HiddenVolumeReadOnly) throw UnsupportedSectorSizeHiddenVolumeProtection(); if (options.NoKernelCrypto) // how about no kernel crypto ever throw UnsupportedSectorSizeNoKernelCrypto(); } #endif } // Find a free mount point for FUSE service MountedFilesystemList mountedFilesystems = GetMountedFilesystems (); string fuseMountPoint; for (int i = 1; true; i++) { stringstream path; path << GetTempDirectory() << "/" << GetFuseMountDirPrefix() << i; FilesystemPath fsPath (path.str()); bool inUse = false; foreach_ref (const MountedFilesystem &mf, mountedFilesystems) { if (mf.MountPoint == path.str()) { inUse = true; break; } } if (!inUse) { try { if (fsPath.IsDirectory()) fsPath.Delete(); throw_sys_sub_if (mkdir (path.str().c_str(), S_IRUSR | S_IXUSR) == -1, path.str()); fuseMountPoint = fsPath; break; } catch (...) { if (i > 255) throw TemporaryDirectoryFailure (SRC_POS, StringConverter::ToWide (path.str())); } } } try { FuseService::Mount (volume, options.SlotNumber, fuseMountPoint); } catch (...) { try { DirectoryPath (fuseMountPoint).Delete(); } catch (...) { } throw; } try { // Create a mount directory if a default path has been specified bool mountDirCreated = false; string mountPoint; if (!options.NoFilesystem && options.MountPoint) { mountPoint = *options.MountPoint; #ifndef TC_MACOSX if (mountPoint.find (GetDefaultMountPointPrefix()) == 0 && !options.MountPoint->IsDirectory()) { Directory::Create (*options.MountPoint); try { throw_sys_sub_if (chown (mountPoint.c_str(), GetRealUserId(), GetRealGroupId()) == -1, mountPoint); } catch (ParameterIncorrect&) { } mountDirCreated = true; } #endif } try { try { MountVolumeNative (volume, options, fuseMountPoint); } catch (NotApplicable&) { MountAuxVolumeImage (fuseMountPoint, options); } } catch (...) { if (mountDirCreated) remove (mountPoint.c_str()); throw; } #ifdef TC_LINUX // set again correct ownership of the mount point to avoid any issues // thanks to veracrypt for this useful bit if (!options.NoFilesystem && options.MountPoint) { mountPoint = *options.MountPoint; if (mountPoint.find (GetDefaultMountPointPrefix()) == 0) { try { chown (mountPoint.c_str(), GetRealUserId(), GetRealGroupId()); } catch (...) { } } } #endif } catch (...) { try { VolumeInfoList mountedVolumes = GetMountedVolumes (*options.Path); if (mountedVolumes.size() > 0) { shared_ptr <VolumeInfo> mountedVolume (mountedVolumes.front()); DismountVolume (mountedVolume); } } catch (...) { } throw; } VolumeInfoList mountedVolumes = GetMountedVolumes (*options.Path); if (mountedVolumes.size() != 1) throw ParameterIncorrect (SRC_POS); VolumeEventArgs eventArgs (mountedVolumes.front()); VolumeMountedEvent.Raise (eventArgs); return mountedVolumes.front(); } void CoreUnix::MountAuxVolumeImage (const DirectoryPath &auxMountPoint, const MountOptions &options) const { DevicePath loopDev = AttachFileToLoopDevice (string (auxMountPoint) + FuseService::GetVolumeImagePath(), options.Protection == VolumeProtection::ReadOnly); try { FuseService::SendAuxDeviceInfo (auxMountPoint, loopDev, loopDev); } catch (...) { try { DetachLoopDevice (loopDev); } catch (...) { } throw; } if (!options.NoFilesystem && options.MountPoint && !options.MountPoint->IsEmpty()) { MountFilesystem (loopDev, *options.MountPoint, StringConverter::ToSingle (options.FilesystemType), options.Protection == VolumeProtection::ReadOnly, StringConverter::ToSingle (options.FilesystemOptions)); } } void CoreUnix::SetFileOwner (const FilesystemPath &path, const UserId &owner) const { throw_sys_if (chown (string (path).c_str(), owner.SystemId, (gid_t) -1) == -1); } DirectoryPath CoreUnix::SlotNumberToMountPoint (VolumeSlotNumber slotNumber) const { if (slotNumber < GetFirstSlotNumber() || slotNumber > GetLastSlotNumber()) throw ParameterIncorrect (SRC_POS); stringstream s; s << GetDefaultMountPointPrefix() << slotNumber; return s.str(); } }
22.868339
180
0.66011
screwjack
64d77eb1693cdb251bb0f6d2ab4ac3597fb47089
2,676
cpp
C++
src/TyroApp.cpp
timw4mail/Tyro
68624456f1922a986203d09739d88d42689aaee8
[ "MIT" ]
null
null
null
src/TyroApp.cpp
timw4mail/Tyro
68624456f1922a986203d09739d88d42689aaee8
[ "MIT" ]
11
2015-04-29T19:01:06.000Z
2015-07-24T19:25:06.000Z
src/TyroApp.cpp
timw4mail/Tyro
68624456f1922a986203d09739d88d42689aaee8
[ "MIT" ]
null
null
null
/** * Main application file */ #include "src/wx_common.h" #include "src/widgets/widget.h" #include <wx/app.h> #include <wx/sysopt.h> #include <wx/vidmode.h> #include "src/widgets/MainFrame.h" // All the ugly globals wxConfigBase *Glob_config = nullptr; LangConfig *Glob_lang_config = nullptr; ThemeConfig *Glob_theme_config = nullptr; MainFrame *Glob_main_frame = nullptr; TyroMenu *Glob_menu_bar = nullptr; wxStatusBar *Glob_status_bar = nullptr; /** * Class with main method */ class TyroApp : public wxApp { public: /** * Start the event loop and create the main window * * @return bool */ bool OnInit() final { TyroApp::SetSystemOptions(); this->SetAppName(APP_NAME); this->SetVendorName(APP_VENDOR); // Initialize globals Glob_config = wxConfigBase::Get(); Glob_lang_config = new LangConfig(); Glob_theme_config = new ThemeConfig(); Glob_menu_bar = new TyroMenu(); Glob_main_frame = new MainFrame(nullptr, APP_NAME, CalculateWindowSize()); // Setup Main Window Glob_main_frame->Layout(); Glob_main_frame->CenterOnScreen(); Glob_main_frame->Show(true); // Open passed files if (this->param_count > 0) { Glob_main_frame->OpenFiles(files); } SetTopWindow(Glob_main_frame); return true; } /** * Exit handler * * @return int */ int OnExit() final { wxLogDebug("Closing App..."); // Deallocate config object wxLogDebug("Deleting wxConfigBase"); delete wxConfigBase::Set((wxConfigBase *) nullptr); return close(true); } /** * Set up Command Line options * * @param wxCmdLineParser& parser * @return void */ void OnInitCmdLine(wxCmdLineParser &parser) final { parser.SetDesc(Glob_cmdLineDesc); // Set - as parameter delimeter, so raw file paths can be used parser.SetSwitchChars("-"); } /** * Handler for command line options * * @param wxCmdLineParser& parser * @return bool */ bool OnCmdLineParsed(wxCmdLineParser &parser) final { // Get un-named parameters this->param_count = parser.GetParamCount(); wxLogDebug("%i Parameters", this->param_count); for (auto i = 0; i < this->param_count; i++) { this->files.Add(parser.GetParam(i)); } return true; } private: // app loading variables wxArrayString files; size_t param_count = 0; /** * Toolkit-specific settings */ void static SetSystemOptions() { #ifdef __WXMAC__ wxSystemOptions::SetOption("osx.openfiledialog.always-show-types", 1); #endif #ifdef __WXMSW__ wxSystemOptions::SetOption("msw.remap", 0); wxSystemOptions::SetOption("msw.display.directdraw", 1); #endif } }; // Set up the main method and event loop wxIMPLEMENT_APP(TyroApp);
19.822222
76
0.69432
timw4mail
64d781a06c34f1ee45d63e1413945ec25894878b
709
cpp
C++
LeetCode/1201.ugly-number-iii.ac.cpp
Kresnt/AlgorithmTraining
3dec1e712f525b4f406fe669d97888f322dfca97
[ "MIT" ]
null
null
null
LeetCode/1201.ugly-number-iii.ac.cpp
Kresnt/AlgorithmTraining
3dec1e712f525b4f406fe669d97888f322dfca97
[ "MIT" ]
null
null
null
LeetCode/1201.ugly-number-iii.ac.cpp
Kresnt/AlgorithmTraining
3dec1e712f525b4f406fe669d97888f322dfca97
[ "MIT" ]
null
null
null
class Solution { public: int nthUglyNumber(int n, int a, int b, int c) { long long first = 0, len = 4e18; long long half, middle; while(len > 0) { half = len >> 1; middle = first + half; if(CountN(middle * 1ll, a * 1ll, b * 1ll, c * 1ll) < n) { first = middle + 1; len = len - half - 1; } else len = half; } return first; } /** * 小于等于 n 的丑数有几个 */ long long CountN(long long n, long long a, long long b, long long c) { return n / a + n / b + n / c - n / (a * b / __gcd(a, b)) - n / (a * c / __gcd(a, c)) - n / (b * c / __gcd(b, c)) + n / (a * b / __gcd(a, b) * c / (__gcd(__gcd(a, b), c))); } };
28.36
176
0.456982
Kresnt
64dd04b7b75e40642c12b95bba3f526087a4c479
2,145
hpp
C++
source/framework/algorithm/include/lue/framework/algorithm/policy/fill_halo_with_constant_value.hpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
2
2021-02-26T22:45:56.000Z
2021-05-02T10:28:48.000Z
source/framework/algorithm/include/lue/framework/algorithm/policy/fill_halo_with_constant_value.hpp
pcraster/lue
e64c18f78a8b6d8a602b7578a2572e9740969202
[ "MIT" ]
262
2016-08-11T10:12:02.000Z
2020-10-13T18:09:16.000Z
source/framework/algorithm/include/lue/framework/algorithm/policy/fill_halo_with_constant_value.hpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
1
2020-03-11T09:49:41.000Z
2020-03-11T09:49:41.000Z
#pragma once #include "lue/framework/core/define.hpp" #include <hpx/serialization.hpp> namespace lue::policy { /*! @brief Fill halo cells with a constant value */ template< typename Element> class FillHaloWithConstantValue { public: FillHaloWithConstantValue(): _fill_value{} { } FillHaloWithConstantValue( Element const fill_value): _fill_value{fill_value} { } Element north_west_corner() const { return _fill_value; } Element north_east_corner() const { return _fill_value; } Element south_west_corner() const { return _fill_value; } Element south_east_corner() const { return _fill_value; } Element west_side() const { return _fill_value; } Element east_side() const { return _fill_value; } Element north_side() const { return _fill_value; } Element south_side() const { return _fill_value; } private: friend class hpx::serialization::access; template<typename Archive> void serialize( Archive& archive, [[maybe_unused]] unsigned int const version) { archive & _fill_value; } Element _fill_value; }; namespace detail { template< typename E> class TypeTraits< FillHaloWithConstantValue<E>> { public: using Element = E; template< typename E_> using Policy = FillHaloWithConstantValue<E_>; }; } // namespace detail } // namespace lue::policy
18.02521
61
0.449883
computationalgeography
64e0f39332323de2baabe378e395fadc9e7f95c6
1,004
cxx
C++
cgv/render/stereo_view.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
11
2017-09-30T12:21:55.000Z
2021-04-29T21:31:57.000Z
cgv/render/stereo_view.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
2
2017-07-11T11:20:08.000Z
2018-03-27T12:09:02.000Z
cgv/render/stereo_view.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
24
2018-03-27T11:46:16.000Z
2021-05-01T20:28:34.000Z
#include <cgv/base/base.h> #include "stereo_view.h" namespace cgv { namespace render { /// stereo_view::stereo_view() { set_default_values(); } /// set distance between eyes void stereo_view::set_eye_distance(double e) { eye_distance = e; } /// void stereo_view::set_default_values() { set_default_view(); set_y_view_angle(45); set_z_near(0.01); set_z_far(10000.0); set_eye_distance(0.03); set_parallax_zero_scale(0.5); } /// query distance between eyes double stereo_view::get_eye_distance() const { return eye_distance; } /// query scale of parallax zero depth with respect to eye focus distance double stereo_view::get_parallax_zero_scale() const { return parallax_zero_scale; } /// query parallax zero depth double stereo_view::get_parallax_zero_depth() const { return (1.0 / (1.0 - parallax_zero_scale) - 1.0) * dot(get_focus() - get_eye(), view_dir); } /// set parallax zero scale void stereo_view::set_parallax_zero_scale(double pzs) { parallax_zero_scale = pzs; } } }
18.592593
91
0.736056
MarioHenze
64ebd14e238e3b8bf30762aff5d757f1ad471035
1,632
cpp
C++
src/plugins/monocle/plugins/mu/mu.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/monocle/plugins/mu/mu.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/monocle/plugins/mu/mu.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "mu.h" #include <QIcon> #include "document.h" namespace LC { namespace Monocle { namespace Mu { void Plugin::Init (ICoreProxy_ptr proxy) { MuCtx_ = fz_new_context (0, 0, FZ_STORE_DEFAULT); } void Plugin::SecondInit () { } QByteArray Plugin::GetUniqueID () const { return "org.LeechCraft.Monocle.Mu"; } void Plugin::Release () { } QString Plugin::GetName () const { return QString::fromUtf8 ("Monocle μ"); } QString Plugin::GetInfo () const { return tr ("PDF backend for Monocle using the mupdf library."); } QIcon Plugin::GetIcon () const { return QIcon (); } QSet<QByteArray> Plugin::GetPluginClasses () const { QSet<QByteArray> result; result << "org.LeechCraft.Monocle.IBackendPlugin"; return result; } auto Plugin::CanLoadDocument (const QString& file) -> LoadCheckResult { return file.toLower ().endsWith (".pdf") ? LoadCheckResult::Can : LoadCheckResult::Cannot; } IDocument_ptr Plugin::LoadDocument (const QString& file) { return IDocument_ptr (new Document (file, MuCtx_, this)); } QStringList Plugin::GetSupportedMimes () const { return { "application/pdf" }; } } } } LC_EXPORT_PLUGIN (leechcraft_monocle_mu, LC::Monocle::Mu::Plugin);
20.4
83
0.637255
Maledictus
64ef778b1ce8500428e0a0f05b0f36b01afa3267
4,937
hpp
C++
e-Paper/src/sdkconfig.hpp
PDA-UR/Dumb-e-Paper
99aecce5fbcb64d32b7e47809df393e0e2e7fab4
[ "MIT" ]
3
2018-06-20T12:13:11.000Z
2020-02-15T12:57:34.000Z
e-Paper/src/sdkconfig.hpp
PDA-UR/Dumb-e-Paper
99aecce5fbcb64d32b7e47809df393e0e2e7fab4
[ "MIT" ]
null
null
null
e-Paper/src/sdkconfig.hpp
PDA-UR/Dumb-e-Paper
99aecce5fbcb64d32b7e47809df393e0e2e7fab4
[ "MIT" ]
2
2021-01-16T13:19:02.000Z
2021-12-15T03:32:26.000Z
/* * * Automatically generated file; DO NOT EDIT. * Espressif IoT Development Framework Configuration * */ #define CONFIG_GATTC_ENABLE 1 #define CONFIG_ESP32_PHY_MAX_TX_POWER 20 #define CONFIG_PHY_ENABLED 1 #define CONFIG_TRACEMEM_RESERVE_DRAM 0x0 #define CONFIG_FREERTOS_MAX_TASK_NAME_LEN 16 #define CONFIG_BLE_SMP_ENABLE 1 #define CONFIG_IPC_TASK_STACK_SIZE 1024 #define CONFIG_ESPTOOLPY_FLASHFREQ "40m" #define CONFIG_NEWLIB_STDOUT_ADDCR 1 #define CONFIG_TASK_WDT_CHECK_IDLE_TASK 1 #define CONFIG_ESPTOOLPY_FLASHSIZE "2MB" #define CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER 1 #define CONFIG_ETHERNET 1 #define CONFIG_INT_WDT 1 #define CONFIG_ESPTOOLPY_FLASHFREQ_40M 1 #define CONFIG_LOG_BOOTLOADER_LEVEL_INFO 1 #define CONFIG_ESPTOOLPY_FLASHSIZE_2MB 1 #define CONFIG_AWS_IOT_MQTT_PORT 8883 #define CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS 1 #define CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM 10 #define CONFIG_LOG_DEFAULT_LEVEL_INFO 1 #define CONFIG_BT_RESERVE_DRAM 0x10000 #define CONFIG_ESP32_PANIC_PRINT_REBOOT 1 #define CONFIG_CONSOLE_UART_BAUDRATE 115200 #define CONFIG_LWIP_MAX_SOCKETS 10 #define CONFIG_EMAC_TASK_PRIORITY 20 #define CONFIG_TIMER_TASK_STACK_DEPTH 2048 #define CONFIG_FATFS_CODEPAGE 1 #define CONFIG_ESP32_DEFAULT_CPU_FREQ_160 1 #define CONFIG_ULP_COPROC_RESERVE_MEM 0 #define CONFIG_ESPTOOLPY_BAUD 115200 #define CONFIG_INT_WDT_CHECK_CPU1 1 #define CONFIG_FLASHMODE_DIO 1 #define CONFIG_ESPTOOLPY_AFTER_RESET 1 #define CONFIG_TOOLPREFIX "xtensa-esp32-elf-" #define CONFIG_FREERTOS_IDLE_TASK_STACKSIZE 1024 #define CONFIG_ESP32_WIFI_AMPDU_ENABLED 1 #define CONFIG_CONSOLE_UART_NUM 0 #define CONFIG_ESP32_RTC_CLOCK_SOURCE_INTERNAL_RC 1 #define CONFIG_ESPTOOLPY_BAUD_115200B 1 #define CONFIG_LWIP_THREAD_LOCAL_STORAGE_INDEX 0 #define CONFIG_FOUR_UNIVERSAL_MAC_ADDRESS 1 #define CONFIG_CONSOLE_UART_DEFAULT 1 #define CONFIG_MBEDTLS_SSL_MAX_CONTENT_LEN 16384 #define CONFIG_NUMBER_OF_UNIVERSAL_MAC_ADDRESS 4 #define CONFIG_ESPTOOLPY_FLASHSIZE_DETECT 1 #define CONFIG_ESP32_ENABLE_COREDUMP_TO_NONE 1 #define CONFIG_BTDM_CONTROLLER_RUN_CPU 0 #define CONFIG_TCPIP_TASK_STACK_SIZE 2560 #define CONFIG_TASK_WDT 1 #define CONFIG_MAIN_TASK_STACK_SIZE 4096 #define CONFIG_TASK_WDT_TIMEOUT_S 5 #define CONFIG_INT_WDT_TIMEOUT_MS 300 #define CONFIG_ESPTOOLPY_FLASHMODE "dio" #define CONFIG_BTC_TASK_STACK_SIZE 3072 #define CONFIG_BLUEDROID_ENABLED 1 #define CONFIG_ESPTOOLPY_BEFORE "default_reset" #define CONFIG_LOG_DEFAULT_LEVEL 3 #define CONFIG_FREERTOS_ASSERT_ON_UNTESTED_FUNCTION 1 #define CONFIG_TIMER_QUEUE_LENGTH 10 #define CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM 32 #define CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER 20 #define CONFIG_ESP32_RTC_CLK_CAL_CYCLES 1024 #define CONFIG_ESP32_WIFI_NVS_ENABLED 1 #define CONFIG_AWS_IOT_SDK 1 #define CONFIG_DMA_RX_BUF_NUM 10 #define CONFIG_TCP_SYNMAXRTX 6 #define CONFIG_PYTHON "python" #define CONFIG_ESP32_TIME_SYSCALL_USE_RTC_FRC1 1 #define CONFIG_ESPTOOLPY_COMPRESSED 1 #define CONFIG_PARTITION_TABLE_FILENAME "partitions_singleapp.csv" #define CONFIG_LWIP_DHCP_MAX_NTP_SERVERS 1 #define CONFIG_PARTITION_TABLE_SINGLE_APP 1 #define CONFIG_WIFI_ENABLED 1 #define CONFIG_LWIP_DHCP_DOES_ARP_CHECK 1 #define CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE 4096 #define CONFIG_ESP32_DEEP_SLEEP_WAKEUP_DELAY 2000 #define CONFIG_ESP32_APPTRACE_DEST_NONE 1 #define CONFIG_PARTITION_TABLE_CUSTOM_APP_BIN_OFFSET 0x10000 #define CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM 32 #define CONFIG_FATFS_CODEPAGE_ASCII 1 #define CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU1 1 #define CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ 160 #define CONFIG_FREERTOS_HZ 100 #define CONFIG_LOG_COLORS 1 #define CONFIG_ESP32_PHY_CALIBRATION_AND_DATA_STORAGE 1 #define CONFIG_FREERTOS_ASSERT_FAIL_ABORT 1 #define CONFIG_ESP32_XTAL_FREQ 0 #define CONFIG_MONITOR_BAUD_115200B 1 #define CONFIG_LOG_BOOTLOADER_LEVEL 3 #define CONFIG_SMP_ENABLE 1 #define CONFIG_ESPTOOLPY_BEFORE_RESET 1 #define CONFIG_ESPTOOLPY_BAUD_OTHER_VAL 115200 #define CONFIG_ESP32_XTAL_FREQ_AUTO 1 #define CONFIG_TCP_MAXRTX 12 #define CONFIG_ESPTOOLPY_AFTER "hard_reset" #define CONFIG_DMA_TX_BUF_NUM 10 #define CONFIG_ESP32_DEBUG_OCDAWARE 1 #define CONFIG_TIMER_TASK_PRIORITY 1 #define CONFIG_BT_ENABLED 1 #define CONFIG_MONITOR_BAUD 115200 #define CONFIG_FREERTOS_CORETIMER_0 1 #define CONFIG_PARTITION_TABLE_CUSTOM_FILENAME "partitions.csv" #define CONFIG_MBEDTLS_HAVE_TIME 1 #define CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY 1 #define CONFIG_GATTS_ENABLE 1 #define CONFIG_FREERTOS_ISR_STACKSIZE 1536 #define CONFIG_OPENSSL_ASSERT_DO_NOTHING 1 #define CONFIG_AWS_IOT_MQTT_HOST "" #define CONFIG_SYSTEM_EVENT_QUEUE_SIZE 32 #define CONFIG_BT_ACL_CONNECTIONS 4 #define CONFIG_FATFS_MAX_LFN 255 #define CONFIG_ESP32_WIFI_TX_BUFFER_TYPE 1 #define CONFIG_APP_OFFSET 0x10000 #define CONFIG_MEMMAP_SMP 1 #define CONFIG_SPI_FLASH_ROM_DRIVER_PATCH 1 #define CONFIG_MONITOR_BAUD_OTHER_VAL 115200 #define CONFIG_ESPTOOLPY_PORT "/dev/ttyUSB0" #define CONFIG_OPTIMIZATION_LEVEL_RELEASE 1
39.18254
66
0.891229
PDA-UR
64f2229e09e536f50b9415eaae72d0ba0d97f9f1
491
cpp
C++
Basic/1040.cpp
GodLovesJonny/PAT-Solutions
b32d7de549c6b0ad8dc2e48d8a0e5cbf2241ed77
[ "MIT" ]
6
2019-03-13T10:07:25.000Z
2019-09-29T14:10:11.000Z
Basic/1040.cpp
GodLovesJonny/PAT-Solutions
b32d7de549c6b0ad8dc2e48d8a0e5cbf2241ed77
[ "MIT" ]
null
null
null
Basic/1040.cpp
GodLovesJonny/PAT-Solutions
b32d7de549c6b0ad8dc2e48d8a0e5cbf2241ed77
[ "MIT" ]
null
null
null
#include <algorithm> #include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include <queue> #include <string> #include <vector> using namespace std; string s; int main() { ios::sync_with_stdio(false); cin >> s; long long cnt = 0, cntPAT = 0, cntAT = 0; int len = s.length(); while (len--) { if (s[len] == 'T') cntAT++; else if (s[len] == 'A') cntPAT += cntAT; else { cnt += cntPAT; cnt %= 1000000007; } } cout << cnt << endl; return 0; }
14.878788
42
0.590631
GodLovesJonny
64f4936b721cca8a97456321ef9bb98b3f6b4a4c
4,180
cpp
C++
src/param_initializers.cpp
afaji/Marian
1f6db367b4d380f7640c31a45ce855bd8dacbdae
[ "MIT" ]
null
null
null
src/param_initializers.cpp
afaji/Marian
1f6db367b4d380f7640c31a45ce855bd8dacbdae
[ "MIT" ]
null
null
null
src/param_initializers.cpp
afaji/Marian
1f6db367b4d380f7640c31a45ce855bd8dacbdae
[ "MIT" ]
null
null
null
// This file is part of the Marian toolkit. // Marian is copyright (c) 2016 Marcin Junczys-Dowmunt. // // 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 <random> #include <algorithm> #include <iterator> #include <stdint.h> #include "param_initializers.h" #include "svd/svd.h" namespace marian { namespace inits { float xor128() { static uint64_t x = 123456789; static uint64_t y = 362436069; static uint64_t z = 521288629; static uint64_t w = 88675123; uint64_t t; t = (x ^ (x << 11)) % 1000; x = y; y = z; z = w; w = (w ^ (w >> 19) ^ t ^ (t >> 8)) % 1000; return 0.1 * ((w % 1000) / 1000.f) - 0.05; } // Use a constant seed for deterministic behaviour. //std::default_random_engine engine(42); void zeros(Tensor t) { t->set(0.f); } void ones(Tensor t) { t->set(1.0f); } std::function<void(Tensor)> from_value(float v) { return [v](Tensor t) { t->set(v); }; } std::function<void(Tensor)> diag(float val) { return [val](Tensor t) { if(t->shape()[0] == t->shape()[1] && t->shape()[2] == 1 && t->shape()[3] == 1) { std::vector<float> vec(t->size(), 0); for(int i = 0; i < t->shape()[0]; ++i) vec[i * t->shape()[1] + i] = val; t->set(vec); } }; } std::function<void(Tensor)> normal(float scale, bool orto) { return [scale](Tensor t) { distribution<std::normal_distribution<float>>(t, 0, scale); }; } std::function<void(Tensor)> uniform(float scale) { return [scale](Tensor t) { distribution<std::uniform_real_distribution<float>>(t, -scale, scale); }; } void glorot_uniform(Tensor t) { float scale = sqrtf( 6.0f / (t->shape()[0] + t->shape()[1]) ); distribution<std::uniform_real_distribution<float>>(t, -scale, scale); } void xorshift(Tensor t) { std::vector<float> vals(t->size()); for(auto&& v : vals) v = xor128(); t << vals; } void glorot_normal(Tensor t) { float scale = sqrtf( 2.0f / (t->shape()[0] + t->shape()[1]) ); distribution<std::normal_distribution<float>>(t, 0, scale); } void svd(std::vector<float>& vec, Shape shape) { int rows = shape[0] * shape[2] * shape[3]; int cols = shape[1]; int n = std::min(rows, cols); int m = std::max(rows, cols); UTIL_THROW_IF2(m % n != 0, "Matrix dimensions must be equal or multiples of each other"); for(int i = 0; i < shape.elements(); i += n * n) { std::vector<float> t1(n); std::vector<float> t2(n * n); float* a = vec.data() + i; float* w = t1.data(); float* v = t2.data(); dsvd(a, n, n, w, v); } } void ortho(Tensor t) { std::vector<float> vec(t->size()); distribution<std::normal_distribution<float>>(vec, 0, 1); svd(vec, t->shape()); t->set(vec); } std::function<void(Tensor)> from_vector(const std::vector<float>& v) { return [v](Tensor t) { t->set(v); }; } std::function<void(Tensor)> from_numpy(const cnpy::NpyArray& np) { size_t size = 1; for(int i = 0; i < np.shape.size(); ++i) { size *= np.shape[i]; }; std::vector<float> npv(size); std::copy((float*)np.data, (float*)np.data + size, npv.begin()); return [npv](Tensor t) { t->set(npv); }; } } } // namespace marian
27.320261
91
0.635167
afaji
64fdbaf3d5bf0ea92748cfd812d29272aab0b1d2
1,380
hpp
C++
examples/advanced/game/include/Game.hpp
szszszsz/blue
a6a93d9a6c7bda6b4ed4fa3b9b4b01094c4915b8
[ "MIT" ]
4
2019-07-21T17:09:48.000Z
2021-02-20T03:34:10.000Z
examples/advanced/game/include/Game.hpp
szszszsz/blue
a6a93d9a6c7bda6b4ed4fa3b9b4b01094c4915b8
[ "MIT" ]
2
2019-07-25T08:29:18.000Z
2020-01-07T09:04:51.000Z
examples/advanced/game/include/Game.hpp
szszszsz/blue
a6a93d9a6c7bda6b4ed4fa3b9b4b01094c4915b8
[ "MIT" ]
1
2019-08-10T08:35:55.000Z
2019-08-10T08:35:55.000Z
#pragma once #include "terrain/Map.hpp" #include "terrain/Flora.hpp" #include "terrain/Water.hpp" #include "states/BaseState.hpp" #include <atomic> #include <memory> #include <states/MainMenu.hpp> class Game { public: static Game& instance(); static void init(); static void dispose(); void reset_state(); void enter_state(std::shared_ptr<BaseState> state); void shutdown(); void handle_input(); bool is_running(); Map& get_map(); Flora& get_flora(); Water& get_water(); struct { std::atomic_bool gesture{ false }; std::atomic<std::uint32_t> press_x{ 0 }; std::atomic<std::uint32_t> press_y{ 0 }; std::atomic<std::uint32_t> release_x{ 0 }; std::atomic<std::uint32_t> release_y{ 0 }; std::atomic<std::uint32_t> last_x{ 0 }; std::atomic<std::uint32_t> last_y{ 0 }; } input; struct { std::atomic_bool requested{ false }; std::atomic_bool found{ false }; std::atomic<std::uint32_t> x_tiles{ 0 }; std::atomic<std::uint32_t> y_tiles{ 0 }; std::atomic<std::uint32_t> x{ 0 }; std::atomic<std::uint32_t> y{ 0 }; } intersection; private: std::atomic_bool _running{ true }; std::shared_ptr<BaseState> _current_state = nullptr; std::shared_ptr<Map> _map = std::make_shared<Map>(); std::shared_ptr<Water> _water = std::make_shared<Water>(); std::shared_ptr<Flora> _flora = std::make_shared<Flora>(); static Game* _instance; };
20.597015
59
0.684783
szszszsz
64fddf4cf926caf8b58764f05559e36ba7c513bd
4,118
hpp
C++
include/otf2xx/definition/detail/comm_impl.hpp
dhinf/otf2xx
78d3c0eb0b201010b7436bbb235ebdbdabec17d2
[ "BSD-3-Clause" ]
8
2016-11-11T09:33:59.000Z
2022-03-11T12:34:01.000Z
include/otf2xx/definition/detail/comm_impl.hpp
dhinf/otf2xx
78d3c0eb0b201010b7436bbb235ebdbdabec17d2
[ "BSD-3-Clause" ]
38
2016-12-12T09:21:07.000Z
2022-03-11T12:18:36.000Z
include/otf2xx/definition/detail/comm_impl.hpp
dhinf/otf2xx
78d3c0eb0b201010b7436bbb235ebdbdabec17d2
[ "BSD-3-Clause" ]
5
2017-06-01T12:01:03.000Z
2022-03-11T11:00:00.000Z
/* * This file is part of otf2xx (https://github.com/tud-zih-energy/otf2xx) * otf2xx - A wrapper for the Open Trace Format 2 library * * Copyright (c) 2013-2016, Technische Universität Dresden, Germany * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * 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. * */ #ifndef INCLUDE_OTF2XX_DEFINITIONS_DETAIL_COMM_HPP #define INCLUDE_OTF2XX_DEFINITIONS_DETAIL_COMM_HPP #include <otf2xx/exception.hpp> #include <otf2xx/fwd.hpp> #include <otf2xx/reference.hpp> #include <otf2xx/definition/detail/ref_counted.hpp> #include <otf2xx/intrusive_ptr.hpp> #include <otf2xx/definition/group.hpp> #include <otf2xx/definition/string.hpp> #include <sstream> #include <variant> namespace otf2 { namespace definition { namespace detail { class comm_impl : public ref_counted { public: using tag_type = comm_base; private: using reference_type = otf2::reference_impl<comm, tag_type>; public: using comm_flag_type = otf2::common::comm_flag_type; using group_type = std::variant<otf2::definition::comm_group, otf2::definition::comm_self_group>; comm_impl(const otf2::definition::string& name, const group_type& group, comm_impl* parent, reference_type pref, comm_flag_type flags, std::int64_t retain_count = 0) : ref_counted(retain_count), name_(name), group_(group), parent_(parent), pref_(pref), flags_(flags) { } comm_impl(const otf2::definition::string& name, const group_type& group, comm_flag_type flags, std::int64_t retain_count = 0) : ref_counted(retain_count), name_(name), group_(group), parent_(), pref_(reference_type::undefined()), flags_(flags) { } otf2::definition::string& name() { return name_; } const group_type& group() const { return group_; } auto parent() const { return std::make_pair(parent_.get(), pref_); } comm_flag_type flags() const { return flags_; } private: otf2::definition::string name_; group_type group_; otf2::intrusive_ptr<comm_impl> parent_; reference_type pref_; comm_flag_type flags_; }; } // namespace detail } // namespace definition } // namespace otf2 #endif // INCLUDE_OTF2XX_DEFINITIONS_DETAIL_COMM_HPP
34.605042
98
0.660272
dhinf
64fee22060b6f533b1943a7af949b00e4321c47c
967
cc
C++
dev/g++/projects/embedded/httpserver/test/testlib.cc
YannGarcia/repo
0f3de24c71d942c752ada03c10861e83853fdf71
[ "MIT" ]
null
null
null
dev/g++/projects/embedded/httpserver/test/testlib.cc
YannGarcia/repo
0f3de24c71d942c752ada03c10861e83853fdf71
[ "MIT" ]
null
null
null
dev/g++/projects/embedded/httpserver/test/testlib.cc
YannGarcia/repo
0f3de24c71d942c752ada03c10861e83853fdf71
[ "MIT" ]
1
2017-01-27T12:53:50.000Z
2017-01-27T12:53:50.000Z
/** * @file testlib.cpp * @brief HTTP server test suite. * @author garciay.yann@gmail.com * @copyright Copyright (c) 2015 ygarcia. All rights reserved * @license This project is released under the MIT License * @version 0.1 */ #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> #include <gtest.h> #define ASSERT_TRUE_MSG(exp1, msg) ASSERT_TRUE(exp1) << msg #include "http_server.hh" using namespace std; /** * @class HTTP server test suite implementation */ class httpserver_test_suite : public ::testing::Test { protected: virtual void SetUp() { }; virtual void TearDown() { }; }; /** * @brief Test case for @see gps_parser_factory::create */ TEST(httpserver_test_suite, httpserver_1) { } /** * @brief Main test program * @param[in] p_argc Number of argumrnt * @param[in] p_argv List of the arguments */ int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
21.488889
61
0.698035
YannGarcia
64feeaf72b60a389747be21f5691be84269edb9c
2,828
hpp
C++
test/core/api/transport/listener_test.hpp
lamafab/kagome
988bc6d93314ca58b320a9d83dcbc4cd3b87b7bb
[ "Apache-2.0" ]
null
null
null
test/core/api/transport/listener_test.hpp
lamafab/kagome
988bc6d93314ca58b320a9d83dcbc4cd3b87b7bb
[ "Apache-2.0" ]
null
null
null
test/core/api/transport/listener_test.hpp
lamafab/kagome
988bc6d93314ca58b320a9d83dcbc4cd3b87b7bb
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef KAGOME_TEST_CORE_API_TRANSPORT_LISTENER_TEST_HPP #define KAGOME_TEST_CORE_API_TRANSPORT_LISTENER_TEST_HPP #include "api/transport/listener.hpp" #include <gtest/gtest.h> #include "api/jrpc/jrpc_processor.hpp" #include "api/jrpc/jrpc_server.hpp" #include "api/service/api_service.hpp" #include <core/api/client/http_client.hpp> #include "mock/core/api/transport/api_stub.hpp" #include "mock/core/api/transport/jrpc_processor_stub.hpp" #include "transaction_pool/transaction_pool_error.hpp" using kagome::api::ApiService; using kagome::api::ApiStub; using kagome::api::JRpcProcessor; using kagome::api::JrpcProcessorStub; using kagome::api::JRpcServer; using kagome::api::JRpcServerImpl; using kagome::api::Listener; template <typename ListenerImpl, typename = std::enable_if_t<std::is_base_of_v<Listener, ListenerImpl>, void>> struct ListenerTest : public ::testing::Test { template <class T> using sptr = std::shared_ptr<T>; protected: using Endpoint = boost::asio::ip::tcp::endpoint; using Context = boost::asio::io_context; using Socket = boost::asio::ip::tcp::socket; using Timer = boost::asio::steady_timer; using Streambuf = boost::asio::streambuf; using Duration = boost::asio::steady_timer::duration; using ErrorCode = boost::system::error_code; std::shared_ptr<Context> main_context = std::make_shared<Context>(1); std::shared_ptr<Context> client_context = std::make_shared<Context>(1); int64_t payload; std::string request; std::string response; void SetUp() override { payload = 0xABCDEF; request = R"({"jsonrpc":"2.0","method":"echo","id":0,"params":[)" + std::to_string(payload) + "]}"; response = R"({"jsonrpc":"2.0","id":0,"result":)" + std::to_string(payload) + "}"; } void TearDown() override { // main_context.reset(); // client_context.reset(); request.clear(); response.clear(); } Endpoint endpoint = {boost::asio::ip::address::from_string("127.0.0.1"), 4321}; typename ListenerImpl::SessionImpl::Configuration config{}; sptr<ApiStub> api = std::make_shared<ApiStub>(); sptr<JRpcServer> server = std::make_shared<JRpcServerImpl>(); std::vector<std::shared_ptr<JRpcProcessor>> processors{ std::make_shared<JrpcProcessorStub>(server, api)}; std::vector<std::shared_ptr<Listener>> listeners{ std::make_shared<ListenerImpl>( *main_context, typename ListenerImpl::Configuration{endpoint}, config)}; sptr<ApiService> service = std::make_shared<ApiService>( std::vector<std::shared_ptr<Listener>>(listeners), server, processors); }; #endif // KAGOME_TEST_CORE_API_TRANSPORT_LISTENER_TEST_HPP
32.136364
80
0.703324
lamafab
8f053fe905be4e54dd57eb47455ccdb86835d13e
1,177
cpp
C++
dominant-homozygous-lethal/code/solution1.cpp
Shenzhen-Middle-School-OI-team/QGeneCal
e40cf975d8bc5719a7bd8cd5d15df9ba952f2ad8
[ "MIT" ]
null
null
null
dominant-homozygous-lethal/code/solution1.cpp
Shenzhen-Middle-School-OI-team/QGeneCal
e40cf975d8bc5719a7bd8cd5d15df9ba952f2ad8
[ "MIT" ]
1
2021-06-13T10:48:53.000Z
2021-06-13T10:48:53.000Z
dominant-homozygous-lethal/code/solution1.cpp
Shenzhen-Middle-School-OI-team/QGeneCal
e40cf975d8bc5719a7bd8cd5d15df9ba952f2ad8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define MAXN (1<<17)+5 #define U 18 #define int long long using namespace std; inline int read(){ int x=0,f=1; char ch=getchar(); while(ch<'0'||ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0'&&ch<='9'){ x=x*10+ch-'0'; ch=getchar(); } return x*f; } int cnt[MAXN]; int n,m; int a[MAXN],b[MAXN],c[MAXN]; int F[U][MAXN],G[U][MAXN],H[U][MAXN]; void FMT(int *f,int op){ for (int i=0;i<n;++i){ for (int j=0;j<m;++j){ if ((j&(1<<i))==0){ f[j|(1<<i)]=f[j|(1<<i)]+op*f[j]; } } } } #define lowbit(x) (x&(-x)) void Init(){ cnt[0]=0; for (int i=1;i<MAXN;++i){ cnt[i]=cnt[i-lowbit(i)]+1; } } void SubsetMul(int *f,int *g,int *h){ for (int S=0;S<m;++S) F[cnt[S]][S]=f[S],G[cnt[S]][S]=g[S]; for (int i=0;i<=n;++i){ FMT(F[i],1),FMT(G[i],1); for (int S=0;S<m;++S){ for (int j=0;j<=i;++j){ H[i][S]+=F[j][S]*G[i-j][S]; } } FMT(H[i],-1); } for (int S=0;S<m;++S) h[S]=H[cnt[S]][S]; } #undef int int main(){ #define int long long Init(); n=read(),m=(1<<n); for (int i=0;i<m;++i) a[i]=read(); for (int i=0;i<m;++i) b[i]=read(); SubsetMul(a,b,c); for (int i=0;i<m;++i) printf("%lld ",c[i]); return 0; }
18.68254
59
0.497876
Shenzhen-Middle-School-OI-team
8f05e3e42594eef06546e4c56f69ddcba4097e67
1,973
cpp
C++
canvas.cpp
twareintor/CanvasText
2b1a1ffe6ac7fd65088fbde71566b910231ec426
[ "MIT" ]
null
null
null
canvas.cpp
twareintor/CanvasText
2b1a1ffe6ac7fd65088fbde71566b910231ec426
[ "MIT" ]
null
null
null
canvas.cpp
twareintor/CanvasText
2b1a1ffe6ac7fd65088fbde71566b910231ec426
[ "MIT" ]
null
null
null
//Permanent link: https://rextester.com/CCAB72954 //Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23506 for x64 //two-dim array of chars canvas to draw in //Code by Twareintor - Copyright (c) 2018 Claudiu Ciutacu #lt:mliato:ciutacu/0[gma!1?cOm#gt: #include "canvas.h" int main(void) { printf("Hello, world!\n"); char** canvas; int dims[] = {100, 100}; makeCanvas(&canvas, dims[0], dims[1]); // test_draw(&canvas); test_draw2(&canvas); printCanvas(canvas, dims[0], dims[1]); deleteCanvas(&canvas, dims[0], dims[1]); printf("Game Over\n"); return 0; } void makeCanvas(char*** ppcanvas, int width, int height) { int i; /* rows */ *ppcanvas = (char**)malloc(height*sizeof(char*)); for(i=0; i<height; i++) { (*ppcanvas)[i] = (char*)malloc((width+1)*sizeof(char)); memset((*ppcanvas)[i], ' ', width); (*ppcanvas)[i][width] = 0; } } void printCanvas(char** pcanvas, int width, int height) { int i; printf("/"); for(i=0; i<width; i++) printf("-"); printf("\\\n"); for(i=0; i<height; i++) { printf("|%s|\n", pcanvas[i]); } printf("\\"); for(i=0; i<width; i++) printf("-"); printf("/\n"); } void deleteCanvas(char*** ppcanvas, int width, int height) { int i; for(i=0; i<height; i++) { free((*ppcanvas)[i]); } free(*ppcanvas); } void test_draw2(char*** ppcanvas) { (*ppcanvas)[3][4] = 'A'; (*ppcanvas)[3][5] = 'B'; (*ppcanvas)[4][6] = 'C'; (*ppcanvas)[5][7] = 'D'; (*ppcanvas)[12][11] = 'X'; (*ppcanvas)[13][10] = 'Y'; (*ppcanvas)[14][9] = 'Z'; (*ppcanvas)[8][12] = '#'; } void test_draw(char*** ppcanvas) { int i, j; for(i=8; i<32; i++) { for(j=4; j<36; j++) { if(i==8 || i==31) (*ppcanvas)[i][j] = '#'; else if(j==4 || j==35) (*ppcanvas)[i][j] = '#'; } } }
22.678161
92
0.501267
twareintor
557e0b7a976fd118c3ed7bc2da074c8726e518af
687
cpp
C++
1-introduction/geometric_progression.cpp
mohsend/Magnificent-University-projects
4b0f9df939a60ace45eeccb331db85af77d83ee9
[ "MIT" ]
null
null
null
1-introduction/geometric_progression.cpp
mohsend/Magnificent-University-projects
4b0f9df939a60ace45eeccb331db85af77d83ee9
[ "MIT" ]
null
null
null
1-introduction/geometric_progression.cpp
mohsend/Magnificent-University-projects
4b0f9df939a60ace45eeccb331db85af77d83ee9
[ "MIT" ]
null
null
null
/* * https://en.wikipedia.org/wiki/Geometric_progression */ #include <iostream> using namespace std; int main() { long int x, n, x_n = 1, sum = 1; cout << "Enter two positive integers:\nX = "; cin >> x; cout << "N = "; cin >> n; cout << "Geometric sequence: " << endl; for (int i = 1; i <= n; i++) { x_n *= x; cout << x <<'^' << i << " = " << x_n <<'\n'; sum += x_n; } cout << "\nCalculated sum of the sequence: " << endl; cout << "1 + x + x^2 + ... + x^n = " << sum << endl; cout << "\nFormula for sum of geometric sequence: " << endl; cout << "(1 - x^(n+1) )/(1 - x) = " << ((1 - x_n * x) / (1 - x)) << endl; return 0; }
20.818182
75
0.465793
mohsend
5581d1c620c8131449aeb15269bbf14fe633134d
6,657
cpp
C++
MMOCoreORB/src/server/zone/ZoneClientSessionImplementation.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/src/server/zone/ZoneClientSessionImplementation.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/src/server/zone/ZoneClientSessionImplementation.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
/* Copyright <SWGEmu> See file COPYING for copying conditions.*/ #include "server/zone/ZoneClientSession.h" #include "server/zone/ZoneServer.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/player/events/ClearClientEvent.h" #include "server/zone/objects/player/events/DisconnectClientEvent.h" #include "server/zone/managers/player/PlayerManager.h" ZoneClientSessionImplementation::ZoneClientSessionImplementation(BaseClientProxy* session) : ManagedObjectImplementation() { ZoneClientSessionImplementation::session = session; ipAddress = session != nullptr ? session->getIPAddress() : ""; player = nullptr; sessionID = 0; accountID = 0; disconnecting = false; commandCount = 0; characters.setNullValue(0); characters.setAllowDuplicateInsertPlan(); bannedCharacters.setNullValue(0); bannedCharacters.setAllowDuplicateInsertPlan(); //session->setDebugLogLevel(); } void ZoneClientSessionImplementation::disconnect() { session->disconnect(); } void ZoneClientSessionImplementation::sendMessage(BasePacket* msg) { session->sendPacket(msg); } //this needs to be run in a different thread void ZoneClientSessionImplementation::disconnect(bool doLock) { Locker locker(_this.getReferenceUnsafeStaticCast()); if (disconnecting) { return; } disconnecting = true; ManagedReference<CreatureObject*> player = this->player.get(); Reference<ZoneClientSession*> zoneClientSession; if (session->hasError() || !session->isClientDisconnected()) { if (player != nullptr) { zoneClientSession = player->getClient(); if (zoneClientSession == _this.getReferenceUnsafeStaticCast()) { //((CreatureObject*)player.get())->disconnect(false, true); Reference<DisconnectClientEvent*> task = new DisconnectClientEvent(player, _this.getReferenceUnsafeStaticCast(), DisconnectClientEvent::DISCONNECT); Core::getTaskManager()->executeTask(task); } } closeConnection(true, false); } else if (player != nullptr) { zoneClientSession = player->getClient(); Reference<PlayerObject*> ghost = player->getSlottedObject("ghost").castTo<PlayerObject*>(); if (ghost->isLoggingOut() && zoneClientSession == _this.getReferenceUnsafeStaticCast()) { //((CreatureObject*)player.get())->logout(true); Reference<DisconnectClientEvent*> task = new DisconnectClientEvent(player, _this.getReferenceUnsafeStaticCast(), DisconnectClientEvent::LOGOUT); Core::getTaskManager()->executeTask(task); } else { try { //player->wlock(); zoneClientSession = player->getClient(); if (zoneClientSession == _this.getReferenceUnsafeStaticCast()) { //((CreatureObject*)player.get())->setLinkDead(); Reference<DisconnectClientEvent*> task = new DisconnectClientEvent(player, _this.getReferenceUnsafeStaticCast(), DisconnectClientEvent::SETLINKDEAD); Core::getTaskManager()->executeTask(task); } //player->unlock(); } catch (Exception& e) { //player->unlock(); } closeConnection(true, true); } } /*info("references left " + String::valueOf(_this.getReferenceUnsafeStaticCast()->getReferenceCount()), true); _this.getReferenceUnsafeStaticCast()->printReferenceHolders();*/ } void ZoneClientSessionImplementation::setPlayer(CreatureObject* playerCreature) { ManagedReference<CreatureObject*> player = this->player.get(); if (playerCreature != player) { if (playerCreature == nullptr && player != nullptr) { // TODO: find a proper way to acqure zone server ZoneServer* zoneServer = player->getZoneServer(); if (zoneServer != nullptr) { zoneServer->decreaseOnlinePlayers(); zoneServer->getPlayerManager()->decreaseOnlineCharCount(_this.getReferenceUnsafeStaticCast()); } } else if (playerCreature != nullptr) { // TODO: find a proper way to acqure zone server ZoneServer* zoneServer = playerCreature->getZoneServer(); if (zoneServer != nullptr) { zoneServer->increaseOnlinePlayers(); } } } this->player = playerCreature; } void ZoneClientSessionImplementation::closeConnection(bool lockPlayer, bool doLock) { Locker locker(_this.getReferenceUnsafeStaticCast()); Reference<BaseClientProxy* > session = this->session; if (session == nullptr) return; session->info("disconnecting client \'" + session->getIPAddress() + "\'"); ZoneServer* server = nullptr; ManagedReference<CreatureObject*> play = player.get(); if (play != nullptr) { server = play->getZoneServer(); Reference<ClearClientEvent*> task = new ClearClientEvent(play, _this.getReferenceUnsafeStaticCast()); Core::getTaskManager()->executeTask(task); setPlayer(nullptr); // we must call setPlayer to increase/decrease online player counter } session->disconnect(); if (server != nullptr) { server->addTotalSentPacket(session->getSentPacketCount()); server->addTotalResentPacket(session->getResentPacketCount()); } } void ZoneClientSessionImplementation::balancePacketCheckupTime() { session->balancePacketCheckupTime(); } void ZoneClientSessionImplementation::resetPacketCheckupTime() { session->resetPacketCheckupTime(); } void ZoneClientSessionImplementation::info(const String& msg, bool force) { session->info(msg, force); } void ZoneClientSessionImplementation::debug(const String& msg) { session->debug(msg); } void ZoneClientSessionImplementation::error(const String& msg) { session->error(msg); } String ZoneClientSessionImplementation::getAddress() { return session->getAddress(); } String ZoneClientSessionImplementation::getIPAddress() { return ipAddress.isEmpty() ? "0.0.0.0" : ipAddress; } BaseClientProxy* ZoneClientSessionImplementation::getSession() { return session; } int ZoneClientSessionImplementation::getCharacterCount(int galaxyId) { int count = 0; for (int i = 0; i < characters.size(); ++i) { if (characters.getKey(i) == galaxyId) ++count; } for (int i = 0; i < bannedCharacters.size(); ++i) { if (bannedCharacters.getKey(i) == galaxyId) ++count; } return count; } bool ZoneClientSessionImplementation::hasCharacter(uint64 cid, unsigned int galaxyId) { /* int lowerBound = characters.lowerBound(VectorMapEntry<uint32, uint64>(galaxyId)); if (lowerBound < 0) return false; for (int i = lowerBound; i < characters.size(); ++i) { if (characters.elementAt(i).getKey() != galaxyId) break; if (characters.elementAt(i).getValue() == cid) return true; } */ for (int i = 0; i < characters.size(); ++i) { if (characters.getKey(i) == galaxyId && characters.get(i) == cid) return true; } return false; } Reference<CreatureObject*> ZoneClientSessionImplementation::getPlayer() { return player.get(); }
27.7375
154
0.734415
V-Fib
558324554e272888d5c1810fd53e3185b576f930
406
cpp
C++
arrays/pivot.cpp
Mohitmauryagit/datastructures
df61f3f5b592dc4fe0b9d6a966b87f3348328e0a
[ "MIT" ]
8
2021-08-12T08:09:37.000Z
2021-12-30T10:45:54.000Z
arrays/pivot.cpp
Mohitmauryagit/datastructures
df61f3f5b592dc4fe0b9d6a966b87f3348328e0a
[ "MIT" ]
7
2021-06-09T05:13:23.000Z
2022-01-24T04:47:59.000Z
arrays/pivot.cpp
Mohitmauryagit/datastructures
df61f3f5b592dc4fe0b9d6a966b87f3348328e0a
[ "MIT" ]
4
2021-11-07T07:09:58.000Z
2022-02-08T11:43:56.000Z
#include <iostream> using namespace std; int main() { int a[] ={5,22,2,17,-5}; int size = sizeof(a)/sizeof(int); int pivot=a[0]; int i=1,lastsmall=0; int t; for (i=1;i<=size-1;i++) { if(a[i]>=pivot) continue; lastsmall++; t=a[i]; a[i]=a[lastsmall]; a[lastsmall]=t; } t=a[0]; a[0]=a[lastsmall]; a[lastsmall]=t; for (i=0;i<=size-1;i++) cout<<a[i]<<","; return 0; }
16.24
37
0.534483
Mohitmauryagit
5584c02e722d4c0a733f85473efbaa63f057552c
1,938
cpp
C++
src/umpire/op/GenericReallocateOperation.cpp
PhilipDeegan/Umpire
3f047822380435131a00a0c7e356c9e845bbfef3
[ "MIT-0", "MIT" ]
229
2018-03-12T19:16:04.000Z
2022-03-25T15:21:39.000Z
src/umpire/op/GenericReallocateOperation.cpp
PhilipDeegan/Umpire
3f047822380435131a00a0c7e356c9e845bbfef3
[ "MIT-0", "MIT" ]
504
2018-07-03T23:37:14.000Z
2022-03-23T20:15:26.000Z
src/umpire/op/GenericReallocateOperation.cpp
PhilipDeegan/Umpire
3f047822380435131a00a0c7e356c9e845bbfef3
[ "MIT-0", "MIT" ]
53
2018-06-29T23:37:19.000Z
2022-03-28T17:39:20.000Z
////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2016-21, Lawrence Livermore National Security, LLC and Umpire // project contributors. See the COPYRIGHT file for details. // // SPDX-License-Identifier: (MIT) ////////////////////////////////////////////////////////////////////////////// #include "umpire/op/GenericReallocateOperation.hpp" #include <cstdlib> #include "umpire/ResourceManager.hpp" #include "umpire/strategy/AllocationStrategy.hpp" #include "umpire/util/AllocationRecord.hpp" #include "umpire/util/Macros.hpp" namespace umpire { namespace op { void GenericReallocateOperation::transform(void* current_ptr, void** new_ptr, util::AllocationRecord* current_allocation, util::AllocationRecord* new_allocation, std::size_t new_size) { Allocator allocator{new_allocation->strategy}; *new_ptr = allocator.allocate(new_size); const std::size_t old_size = current_allocation->size; const std::size_t copy_size = (old_size > new_size) ? new_size : old_size; ResourceManager::getInstance().copy(*new_ptr, current_ptr, copy_size); allocator.deallocate(current_ptr); } camp::resources::EventProxy<camp::resources::Resource> GenericReallocateOperation::transform_async( void* current_ptr, void** new_ptr, util::AllocationRecord* current_allocation, util::AllocationRecord* new_allocation, std::size_t new_size, camp::resources::Resource& ctx) { Allocator allocator{new_allocation->strategy}; *new_ptr = allocator.allocate(new_size); const std::size_t old_size = current_allocation->size; const std::size_t copy_size = (old_size > new_size) ? new_size : old_size; auto event = ResourceManager::getInstance().copy(*new_ptr, current_ptr, ctx, copy_size); allocator.deallocate(current_ptr); return event; } } // end of namespace op } // end of namespace umpire
36.566038
104
0.673375
PhilipDeegan
55863f62c3619d5c5a6360bd6c8179447bd6a8bd
2,340
cpp
C++
EZOJ/Contests/1445/B.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
6
2019-09-30T16:11:00.000Z
2021-11-01T11:42:33.000Z
EZOJ/Contests/1445/B.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-11-21T08:17:42.000Z
2020-07-28T12:09:52.000Z
EZOJ/Contests/1445/B.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-07-26T05:54:06.000Z
2020-09-30T13:35:38.000Z
#include <iostream> #include <cstdio> #include <cstring> #include <cassert> #include <cctype> using namespace std; typedef long long lint; #define cout cerr #define ni (next_num<int>()) template<class T>inline T next_num(){ T i=0;char c; while(!isdigit(c=getchar())&&c!='-'); bool neg=c=='-'; neg?c=getchar():0; while(i=i*10-'0'+c,isdigit(c=getchar())); return neg?-i:i; } template<class T1,class T2>inline void apmax(T1 &a,const T2 &b){if(a<b)a=b;} template<class T1,class T2>inline void apmin(T1 &a,const T2 &b){if(b<a)a=b;} template<class T>inline void mset(T a,int v,int n){memset(a,v,n*sizeof(a[0]));} template<class T>inline void apabs(T &x){if(x<0)x=-x;} const int N=1010,O=1000000007,INF=0x7f7f7f7f; int n,m; namespace gmath{ inline int fpow(int x,int n){ int a=1; for(;n;n>>=1,x=(lint)x*x%O){ if(n&1){ a=(lint)a*x%O; } } return a; } inline int inv_pow(int x){ return fpow(x,O-2); } int fac[N],invfac[N]; inline int C(int n,int k){ assert(k<=n); return (lint)fac[n]*invfac[k]%O*invfac[n-k]%O; } inline void main(int n=N-1){ fac[0]=1; for(int i=1;i<=n;i++){ fac[i]=(lint)fac[i-1]*i%O; } invfac[n]=inv_pow(fac[n]); for(int i=n;i>=1;i--){ invfac[i-1]=(lint)invfac[i]*i%O; } } } int coor[2][N],nxt[N]; int f[N]; inline int gf(int x){ apabs(x); return x<=m?f[x]:0; } inline int calc2(int x[]){ int l=x[nxt[0]]-m,r=x[nxt[0]]+m; for(int i=0;i=nxt[i],i<=n;){ apmax(l,x[i]-m),apmin(r,x[i]+m); } lint ans=0; for(int i=l;i<=r;i++){ int cur=1; for(int j=0;j=nxt[j],j<=n&&cur;){ cur=(lint)cur*gf(i-x[j])%O; } ans+=cur; } return ans%O; } inline int calc(){ return (lint)calc2(coor[0])*calc2(coor[1])%O; } inline int Main(){ n=ni; const int p[4]={0,ni,p[1]+ni,n}; gmath::main(m=ni); for(int i=0;i<=m;i++){ f[i]=(m-i)&1?0:gmath::C(m,(m-i)>>1); } for(int i=1;i<=n;i++){ const int x=ni,y=ni; coor[0][i]=y+x,coor[1][i]=y-x; nxt[i]=i+1; } lint a[4],b[4]; lint ans=0; for(int i=1;i<=3;i++){ a[i]=(nxt[0]=p[i-1]+1,nxt[p[i]]=n+1,calc)(); b[i]=(nxt[0]=1,nxt[p[i-1]]=p[i]+1,calc)(); ans-=a[i]*b[i]%O; for(int j=0;j<=3;j++){ nxt[p[j]]=p[j]+1; } } ans+=a[1]*a[2]%O*a[3]%O+calc()*2; return (ans%O+O)%O; } int main(){ #ifndef ONLINE_JUDGE freopen("dark.in","r",stdin); freopen("dark.out","w",stdout); #endif printf("%d\n",Main()); return 0; }
21.272727
79
0.573932
sshockwave
55887c6adb51dc89b9e6d5ee5bb273543cf82c4d
4,994
hpp
C++
include/VBE/system/Keyboard.hpp
Dirbaio/VBE
539d222dcbbf565ab64dc5d2463b310fd4b75873
[ "MIT" ]
null
null
null
include/VBE/system/Keyboard.hpp
Dirbaio/VBE
539d222dcbbf565ab64dc5d2463b310fd4b75873
[ "MIT" ]
null
null
null
include/VBE/system/Keyboard.hpp
Dirbaio/VBE
539d222dcbbf565ab64dc5d2463b310fd4b75873
[ "MIT" ]
null
null
null
#ifndef KEYBOARD_HPP #define KEYBOARD_HPP /// /// \brief The Keyboard class provides support to read the keyboard. /// class Keyboard { public: /// /// \brief Contains all supported keys. /// enum Key { Num0, Num1, Num2, Num3, Num4, Num5, Num6, Num7, Num8, Num9, A, AC_BACK, AC_BOOKMARKS, AC_FORWARD, AC_HOME, AC_REFRESH, AC_SEARCH, AC_STOP, Again, AltErase, Quote, Application, AudioMute, AudioNext, AudioPlay, AudioPrev, AuidoStop, B, Backslash, Backspace, BrightnessDown, BrightnessUp, C, Calculator, Cancel, Capslock, Clear, ClearAgain, Comma, Computer, Copy, CrSel, CurrencySubUnit, CurrencyUnit, Cut, D, DecimalSeparator, Delete, DisplaySwitch, Down, E, Eject, End, Equals, Escape, Execute, Exsel, F, F1, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F2, F20, F21, F22, F23, F24, F3, F4, F5, F6, F7, F8, F9, Find, G, BackQuote, H, Help, Home, I, Insert, J, K, KBDIllumDown, KBDIllumToggle, KBDIllumUp, Keypad0, Keypad00, Keypad000, Keypad1, Keypad2, Keypad3, Keypad4, Keypad5, Keypad6, Keypad7, Keypad8, Keypad9, KeypadA, KeypadAmpersand, KeypadAt, KeypadB, KeypadBackspace, KeypadBinary, KeypadC, KeypadClear, KeypadClearEntry, KeypadColon, KeypadComma, KeypadD, KeypadDoubleAmpersand, KeypadDoubleVerticalBar, KeypadDecimal, KeypadDivide, KeypadE, KeypadEnter, KeypadEquals, KeypadEqualsAS400, KeypadExclamation, KeypadF, KeypadGreater, KeypadHash, KeypadHexadecimal, KeypadLBrace, KeypadLParenthesis, KeypadLess, KeypadMemAdd, KeypadMemClear, KeypadMemDivide, KeypadMemMultiply, KeypadMemRecall, KeypadMemStore, KeypadMemSubstract, KeypadMinus, KeypadMultiply, KeypadOctal, KeypadPercent, KeypadPeriod, KeypadPlus, KeypadPlusMinus, KeypadPower, KeypadRBrace, KeypadRParenthesis, KeypadSpace, KeypadTab, KeypadVerticalBar, KeypadXor, L, LAlt, LControl, Left, LBracket, LGUI, LShift, M, Mail, MediaSelect, Menu, Minus, Mode, Mute, N, NumLockClear, O, Oper, Out, P, PageDown, PageUp, Paste, Pause, Period, Power, PrintScren, Prior, Q, R, RAlt, RControl, Return, Return2, RGUI, Right, RBracket, RShift, S, ScrollLock, Select, Semicolont, Separator, Slash, Sleep, Space, Stop, Sysreq, T, Tab, ThousandsSeparator, U, Undo, Unknown, UP, V, VolumeDown, VolumeUp, W, WWW, X, Y, Z, Ampersand, Asterisk, At, Caret, Colon, Dollar, Exclamation, Greater, Hash, LParenthesis, Less, Percent, Plus, Question, DoubleQuote, RParenthesis, Underscore, KeyCount ///< Not an actual key }; /// /// \brief Tells whether the given key is pressed (held down) /// static bool pressed(Key k); /// /// \brief Tells whether the given key has just been pressed (It was not pressed on the last frame and now it is.) /// static bool justPressed(Key k); /// /// \brief Tells whether the given key has just been released (It was pressed on the last frame and it's now released.) /// static bool justReleased(Key k); private: static void init(); static void update(); static bool oldKeyPresses[Keyboard::KeyCount]; friend class Window; }; /// /// \class Keyboard Keyboard.hpp <VBE/system/Keyboard.hpp> /// \ingroup System /// /// You can use this class within an init environment (one that has a window) to access the current /// keyboard device's state. Not all keys are supported in all devices and may /// never be marked as pressed (depends on the driver). The state of this device will be updated to /// match recieved events whenever Window::update() is called. /// /// A Key will be 'just pressed' for only one frame (one update()) call. Then held for /// an indefinite number of frames and released right after. For Example, if the /// user pressed the A Key on frame 1 and released it on frame 4, this would /// register (updating the window every frame of course): /// /// - Frame 1 /// + Key Keyboard::A is just pressed /// + Key Keyboard::A is pressed /// + Key Keyboard::A is not just released /// - Frame 2 /// + Key Keyboard::A is not just pressed /// + Key Keyboard::A is pressed /// + Key Keyboard::A is not just released /// - Frame 3 /// + Key Keyboard::A is not just pressed /// + Key Keyboard::A is pressed /// + Key Keyboard::A is not just released /// - Frame 4 /// + Key Keyboard::A is not just pressed /// + Key Keyboard::A is not pressed /// + Key Keyboard::A is just released /// #endif // KEYBOARD_HPP
16.161812
121
0.621946
Dirbaio
55946f3858e6d120e6a15d0716ddd204b386e35a
33,121
cpp
C++
Libs/Math3D/BezierPatch.cpp
dns/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
3
2020-04-11T13:00:31.000Z
2020-12-07T03:19:10.000Z
Libs/Math3D/BezierPatch.cpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
null
null
null
Libs/Math3D/BezierPatch.cpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
1
2020-04-11T13:00:04.000Z
2020-04-11T13:00:04.000Z
/* Cafu Engine, http://www.cafu.de/ Copyright (c) Carsten Fuchs and other contributors. This project is licensed under the terms of the MIT license. */ #include "BezierPatch.hpp" using namespace cf::math; #if defined(_WIN32) && defined(_MSC_VER) && (_MSC_VER<1300) template class cf::math::BezierPatchT<float>; // VC++ 6 requires the cf::math:: here, template class cf::math::BezierPatchT<double>; // even though "using" is used above. template<float> void BezierPatchT<float>::VertexT::Average(const VertexT& A, const VertexT& B) { const float onehalf=0.5f; Coord =(A.Coord +B.Coord )*onehalf; TexCoord=(A.TexCoord+B.TexCoord)*onehalf; Normal =(A.Normal +B.Normal )*onehalf; TangentS=(A.TangentS+B.TangentS)*onehalf; TangentT=(A.TangentT+B.TangentT)*onehalf; } template<double> void BezierPatchT<double>::VertexT::Average(const VertexT& A, const VertexT& B) { const double onehalf=0.5; Coord =(A.Coord +B.Coord )*onehalf; TexCoord=(A.TexCoord+B.TexCoord)*onehalf; Normal =(A.Normal +B.Normal )*onehalf; TangentS=(A.TangentS+B.TangentS)*onehalf; TangentT=(A.TangentT+B.TangentT)*onehalf; } #endif /// Returns the unit vector of A if the length of A is greater than Epsilon, the null vector otherwise. template<class T> static Vector3T<T> myNormalize(const Vector3T<T>& A, const T Epsilon) { const T Length=length(A); return (Length>Epsilon) ? A/Length : Vector3T<T>(); } template<class T> void BezierPatchT<T>::VertexT::Average(const VertexT& A, const VertexT& B) { const T onehalf=T(0.5); Coord =(A.Coord +B.Coord )*onehalf; TexCoord=(A.TexCoord+B.TexCoord)*onehalf; Normal =(A.Normal +B.Normal )*onehalf; TangentS=(A.TangentS+B.TangentS)*onehalf; TangentT=(A.TangentT+B.TangentT)*onehalf; } template<class T> BezierPatchT<T>::BezierPatchT() : Width(0), Height(0) { } template<class T> BezierPatchT<T>::BezierPatchT(unsigned long Width_, unsigned long Height_, const ArrayT< Vector3T<T> >& Coords_) : Width(Width_), Height(Height_) { Mesh.PushBackEmpty(Width*Height); for (unsigned long VertexNr=0; VertexNr<Mesh.Size(); VertexNr++) { Mesh[VertexNr].Coord=Coords_[VertexNr]; } } template<class T> BezierPatchT<T>::BezierPatchT(unsigned long Width_, unsigned long Height_, const ArrayT< Vector3T<T> >& Coords_, const ArrayT< Vector3T<T> >& TexCoords_) : Width(Width_), Height(Height_) { Mesh.PushBackEmpty(Width*Height); for (unsigned long VertexNr=0; VertexNr<Mesh.Size(); VertexNr++) { Mesh[VertexNr].Coord =Coords_ [VertexNr]; Mesh[VertexNr].TexCoord=TexCoords_[VertexNr]; } } template<class T> void BezierPatchT<T>::ComputeTangentSpace() { assert(Width >=3); assert(Height>=3); assert((Width % 2)==1); assert((Height % 2)==1); // Make sure that we start with 0-vectors everywhere. for (unsigned long VertexNr=0; VertexNr<Mesh.Size(); VertexNr++) { Mesh[VertexNr].Normal =Vector3T<T>(); Mesh[VertexNr].TangentS=Vector3T<T>(); Mesh[VertexNr].TangentT=Vector3T<T>(); } // Loop over all 3x3 sub-patches. // Note that whereever two 3x3 sub-patches share common vertices, we have to average their tangent-space axes! for (unsigned long sp_j=0; sp_j+2<Height; sp_j+=2) for (unsigned long sp_i=0; sp_i+2<Width; sp_i+=2) { Vector3T<T> AverageOfGood[3]; bool IsGood[3][3]; for (unsigned long j=0; j<3; j++) for (unsigned long i=0; i<3; i++) { VertexT& v=GetVertex(sp_i+i, sp_j+j); Vector3T<T> Axes[3]; IsGood[i][j]=ComputeTangentSpaceInSubPatch(sp_i, sp_j, T(i)/2, T(j)/2, Axes); if (!IsGood[i][j]) continue; v.Normal +=Axes[0]; v.TangentS+=Axes[1]; v.TangentT+=Axes[2]; AverageOfGood[0]+=Axes[0]; AverageOfGood[1]+=Axes[1]; AverageOfGood[2]+=Axes[2]; } AverageOfGood[0]=myNormalize(AverageOfGood[0], T(0.0)); AverageOfGood[1]=myNormalize(AverageOfGood[1], T(0.0)); AverageOfGood[2]=myNormalize(AverageOfGood[2], T(0.0)); // Use the average of the non-degenerate axes whereever the axes were degenerate. for (unsigned long j=0; j<3; j++) for (unsigned long i=0; i<3; i++) if (!IsGood[i][j]) { VertexT& v=GetVertex(sp_i+i, sp_j+j); v.Normal +=AverageOfGood[0]; v.TangentS+=AverageOfGood[1]; v.TangentT+=AverageOfGood[2]; } } if (WrapsHorz()) { Vector3T<T> Temp; for (unsigned long j=0; j<Height; j++) { Temp=GetVertex(0, j).Normal +GetVertex(Width-1, j).Normal; GetVertex(0, j).Normal =Temp; GetVertex(Width-1, j).Normal =Temp; Temp=GetVertex(0, j).TangentS+GetVertex(Width-1, j).TangentS; GetVertex(0, j).TangentS=Temp; GetVertex(Width-1, j).TangentS=Temp; Temp=GetVertex(0, j).TangentT+GetVertex(Width-1, j).TangentT; GetVertex(0, j).TangentT=Temp; GetVertex(Width-1, j).TangentT=Temp; } } if (WrapsVert()) { Vector3T<T> Temp; for (unsigned long i=0; i<Width; i++) { Temp=GetVertex(i, 0).Normal +GetVertex(i, Height-1).Normal; GetVertex(i, 0).Normal =Temp; GetVertex(i, Height-1).Normal =Temp; Temp=GetVertex(i, 0).TangentS+GetVertex(i, Height-1).TangentS; GetVertex(i, 0).TangentS=Temp; GetVertex(i, Height-1).TangentS=Temp; Temp=GetVertex(i, 0).TangentT+GetVertex(i, Height-1).TangentT; GetVertex(i, 0).TangentT=Temp; GetVertex(i, Height-1).TangentT=Temp; } } // Renormalize all the interpolated tangent space axes. for (unsigned long VertexNr=0; VertexNr<Mesh.Size(); VertexNr++) { Mesh[VertexNr].Normal =myNormalize(Mesh[VertexNr].Normal, T(0.0)); Mesh[VertexNr].TangentS=myNormalize(Mesh[VertexNr].TangentS, T(0.0)); Mesh[VertexNr].TangentT=myNormalize(Mesh[VertexNr].TangentT, T(0.0)); } } template<class T> void BezierPatchT<T>::ComputeTangentSpace_Obsolete() { // NOTES: // 1) This method does not care whether the mesh has already been subdivided or not - it works either way. // 2) Special cases like wrapping and degeneracies are properly taken into account. #if 0 // I disabled this section of code because it's not well possible to generalize it to also deal with the tangents. // Moreover, I find it a lot nicer to not treat coplanar patches as a special case anyway. // If all points are coplanar (they all lie in a common plane), set all normals to that plane. { const Vector3T<T> Extent_Horz=GetVertex(Width-1, 0).Coord - GetVertex(0, 0).Coord; const Vector3T<T> Extent_Diag=GetVertex(Width-1, Height-1).Coord - GetVertex(0, 0).Coord; const Vector3T<T> Extent_Vert=GetVertex( 0, Height-1).Coord - GetVertex(0, 0).Coord; Vector3T<T> Normal=cross(Extent_Diag, Extent_Horz); if (Normal.GetLengthSqr()==0.0) { Normal=cross(Extent_Vert, Extent_Horz); if (Normal.GetLengthSqr()==0.0) { Normal=cross(Extent_Vert, Extent_Diag); // Note that if the patch is wrapped, the Normal may still be not valid here... } } const T Length=length(Normal); if (Length!=0.0) { Normal/=Length; // Distance0 is the distance of vertex (0, 0) to the plane through the origin with normal vector Normal. const T Distance0=dot(Mesh[0].Coord, Normal); unsigned long VertexNr; for (VertexNr=1; VertexNr<Mesh.Size(); VertexNr++) { const T Distance=dot(Mesh[VertexNr].Coord, Normal); if (fabs(Distance-Distance0)>T(1.0) /*COPLANAR_EPSILON*/) break; } if (VertexNr==Mesh.Size()) { // All mesh vertices are coplanar (lie in a common plane). for (unsigned long VertexNr=0; VertexNr<Mesh.Size(); VertexNr++) Mesh[VertexNr].Normal=Normal; return; } } } #endif // First check whether the patch mesh "wraps" in any direction. // This is done by checking of the left and right / top and bottom borders are identical. // If so, the tangent space should be averaged ("smoothed") across the wrap seam. const bool wrapWidth =WrapsHorz(); const bool wrapHeight=WrapsVert(); const int iWidth =int(Width ); const int iHeight=int(Height); static const int Neighbours[8][2]={ {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1}, {-1,-1}, {-1,0}, {-1,1} }; for (int i=0; i<iWidth; i++) { for (int j=0; j<iHeight; j++) { Vector3T<T> Around_Coords[8]; Vector3T<T> Around_TexCoords[8]; bool good[8]; for (unsigned long k=0; k<8; k++) { Around_Coords [k]=Vector3T<T>(0, 0, 0); Around_TexCoords[k]=Vector3T<T>(0, 0, 0); good [k]=false; for (int dist=1; dist<=3; dist++) { int x=i+Neighbours[k][0]*dist; int y=j+Neighbours[k][1]*dist; if (wrapWidth) { if (x< 0) x=iWidth-1+x; else if (x>=iWidth) x=1+x-iWidth; } if (wrapHeight) { if (y< 0) y=iHeight-1+y; else if (y>=iHeight) y=1+y-iHeight; } if (x<0 || x>=iWidth || y<0 || y>=iHeight) break; // edge of patch Around_Coords [k]=GetVertex(x, y).Coord -GetVertex(i, j).Coord; Around_TexCoords[k]=GetVertex(x, y).TexCoord-GetVertex(i, j).TexCoord; const T acLen=length(Around_Coords[k]); if (acLen>T(0.2)) { // This is a "good" edge. Around_Coords [k]/=acLen; Around_TexCoords[k]=myNormalize(Around_TexCoords[k], T(0.0)); good [k]=true; break; } // Else the edge is degenerate, continue to get more dist. } } // Finally compute the averages of the neighbourhood around the current vertex. GetVertex(i, j).Normal =Vector3T<T>(0, 0, 0); GetVertex(i, j).TangentS=Vector3T<T>(0, 0, 0); GetVertex(i, j).TangentT=Vector3T<T>(0, 0, 0); for (unsigned long k=0; k<8; k++) { if (!good[ k ]) continue; if (!good[(k+1) & 7]) continue; const Vector3T<T>& Edge01=Around_Coords[(k+1) & 7]; const Vector3T<T>& Edge02=Around_Coords[ k ]; const Vector3T<T> Normal =cross(Edge02, Edge01); const T NormalL=length(Normal); if (NormalL==0.0) continue; GetVertex(i, j).Normal+=Normal/NormalL; // Understanding what's going on here is easy. The key statement is // "The tangent vector is parallel to the direction of increasing S on a parametric surface." // First, there is a short explanation in "The Cg Tutorial", chapter 8. // Second, I have drawn a simple figure that leads to a simple 2x2 system of Gaussian equations, see my TechArchive. const Vector3T<T>& uv01=Around_TexCoords[(k+1) & 7]; const Vector3T<T>& uv02=Around_TexCoords[ k ]; const T f =uv01.x*uv02.y-uv01.y*uv02.x>0.0 ? T(1.0f) : T(-1.0f); GetVertex(i, j).TangentS+=myNormalize(Edge02.GetScaled(-uv01.y*f) + Edge01.GetScaled(uv02.y*f), T(0.0)); GetVertex(i, j).TangentT+=myNormalize(Edge02.GetScaled( uv01.x*f) - Edge01.GetScaled(uv02.x*f), T(0.0)); } GetVertex(i, j).Normal =myNormalize(GetVertex(i, j).Normal, T(0.0)); GetVertex(i, j).TangentS=myNormalize(GetVertex(i, j).TangentS, T(0.0)); GetVertex(i, j).TangentT=myNormalize(GetVertex(i, j).TangentT, T(0.0)); } } } // "Automatic" subdivision. template<class T> void BezierPatchT<T>::Subdivide(T MaxError, T MaxLength, bool OptimizeFlat) { assert(Width >=3); assert(Height>=3); assert((Width % 2)==1); assert((Height % 2)==1); const T maxHorizontalErrorSqr=MaxError*MaxError; const T maxVerticalErrorSqr =MaxError*MaxError; const T maxLengthSqr =MaxLength*MaxLength; // horizontal subdivisions for (unsigned long j=0; j+2<Width; j+=2) { unsigned long i; // check subdivided midpoints against control points for (i=0; i<Height; i++) { // Consider a point triple A, B, C, where A and B are the curve endpoints and C is the control point. // Let L=(A+C)/2, R=(B+C)/2, N=(L+R)/2, H=(A+B)/2. Then HN==NC==HC/2==(2C-A-B)/4. // Thus, take HN (the "error" in world units) as a measure for tesselation error, // as is cares both for the world size of the patch (ie. is the diameter of a pipe very big or very small), // as well as the severity of the deformation (almost flat curves get less triangles than very tight ones). const Vector3T<T>& A=GetVertex(j , i).Coord; const Vector3T<T>& B=GetVertex(j+2, i).Coord; const Vector3T<T>& C=GetVertex(j+1, i).Coord; const Vector3T<T> AC=C-A; const Vector3T<T> CB=B-C; const Vector3T<T> N =(A+B+C*T(2.0))*T(0.25); // if the span length is too long, force a subdivision if (MaxLength>0 && (AC.GetLengthSqr()>maxLengthSqr || CB.GetLengthSqr()>maxLengthSqr)) break; // const T lenHN = length((C * T(2.0) - A - B) * T(0.25)); // const T lenAB = length(B - A); // see if this midpoint is off far enough to subdivide if ((C-N).GetLengthSqr()>maxHorizontalErrorSqr) break; // This is an alternative to the above `if` test that seems to work very well, // but is prone to infinite looping if A, B and C are very close to each other, but not quite the same // (e.g. `lenAB > T(0.0001)` in the first half of the test freezes CaWE when loading the TechDemo map). // Maybe we should use something conservative like `lenAB > T(0.1) && lenAC > T(0.1) && lenBC > T(0.1)`? // if (lenAB > T(0.001) && // lenHN > T(0.2) * lenAB) break; } if (i==Height) continue; // didn't need subdivision SetMeshSize(Width+2, Height); // Insert two columns and replace the peak a la deCasteljau. for (i=0; i<Height; i++) { VertexT Left, Right, Center; Left .Average(GetVertex(j, i), GetVertex(j+1, i)); Right .Average(GetVertex(j+1, i), GetVertex(j+2, i)); Center.Average(Left, Right); for (unsigned long k=Width-1; k>j+3; k--) GetVertex(k, i)=GetVertex(k-2, i); GetVertex(j+1, i)=Left; GetVertex(j+2, i)=Center; GetVertex(j+3, i)=Right; } // back up and recheck this set again, it may need more subdivision j-=2; } // vertical subdivisions for (unsigned long j=0; j+2<Height; j+=2) { unsigned long i; // check subdivided midpoints against control points for (i=0; i<Width; i++) { const Vector3T<T>& A=GetVertex(i, j ).Coord; const Vector3T<T>& B=GetVertex(i, j+2).Coord; const Vector3T<T>& C=GetVertex(i, j+1).Coord; const Vector3T<T> AC=C-A; const Vector3T<T> CB=B-C; const Vector3T<T> N =(A+B+C*T(2.0))*T(0.25); // if the span length is too long, force a subdivision if (MaxLength>0 && (AC.GetLengthSqr()>maxLengthSqr || CB.GetLengthSqr()>maxLengthSqr)) break; // const T lenHN = length((C * T(2.0) - A - B) * T(0.25)); // const T lenAB = length(B - A); // see if this midpoint is off far enough to subdivide if ((C-N).GetLengthSqr()>maxVerticalErrorSqr) break; // This is an alternative to the above `if` test that seems to work very well, // but is prone to infinite looping if A, B and C are very close to each other, but not quite the same // (e.g. `lenAB > T(0.0001)` in the first half of the test freezes CaWE when loading the TechDemo map). // Maybe we should use something conservative like `lenAB > T(0.1) && lenAC > T(0.1) && lenBC > T(0.1)`? // if (lenAB > T(0.001) && // lenHN > T(0.2) * lenAB) break; } if (i==Width) continue; // didn't need subdivision SetMeshSize(Width, Height+2); // insert two columns and replace the peak for (i=0; i<Width; i++) { VertexT Left, Right, Center; Left .Average(GetVertex(i, j ), GetVertex(i, j+1)); Right .Average(GetVertex(i, j+1), GetVertex(i, j+2)); Center.Average(Left, Right); for (unsigned long k=Height-1; k>j+3; k--) GetVertex(i, k)=GetVertex(i, k-2); GetVertex(i, j+1)=Left; GetVertex(i, j+2)=Center; GetVertex(i, j+3)=Right; } // back up and recheck this set again, it may need more subdivision j-=2; } // Move all the "approximation" control vertices onto the true shape of the curve. // Note that the other vertices (the "interpolation" control vertices) already and always are on the curve per definition. for (unsigned long i=0; i<Width; i++) { for (unsigned long j=1; j<Height; j+=2) { VertexT Left, Right; Left .Average(GetVertex(i, j), GetVertex(i, j+1)); Right.Average(GetVertex(i, j), GetVertex(i, j-1)); GetVertex(i, j).Average(Left, Right); } } for (unsigned long j=0; j<Height; j++) { for (unsigned long i=1; i<Width; i+=2) { VertexT Left, Right; Left .Average(GetVertex(i, j), GetVertex(i+1, j)); Right.Average(GetVertex(i, j), GetVertex(i-1, j)); GetVertex(i, j).Average(Left, Right); } } if (OptimizeFlat) OptimizeFlatRowAndColumnStrips(); // Normalize all the lerped tangent space axes. for (unsigned long VertexNr=0; VertexNr<Mesh.Size(); VertexNr++) { Mesh[VertexNr].Normal =myNormalize(Mesh[VertexNr].Normal, T(0.0)); Mesh[VertexNr].TangentS=myNormalize(Mesh[VertexNr].TangentS, T(0.0)); Mesh[VertexNr].TangentT=myNormalize(Mesh[VertexNr].TangentT, T(0.0)); } // GenerateIndexes(); } // "Explicit" subdivision. template<class T> void BezierPatchT<T>::Subdivide(unsigned long SubDivsHorz, unsigned long SubDivsVert, bool OptimizeFlat) { assert(Width >=3); assert(Height>=3); assert((Width % 2)==1); assert((Height % 2)==1); const unsigned long TargetWidth =((Width -1)/2 * SubDivsHorz)+1; const unsigned long TargetHeight=((Height-1)/2 * SubDivsVert)+1; ArrayT<VertexT> TargetMesh; TargetMesh.PushBackEmpty(TargetWidth*TargetHeight); unsigned long baseCol=0; for (unsigned long i=0; i+2<Width; i+=2) { unsigned long baseRow=0; for (unsigned long j=0; j+2<Height; j+=2) { VertexT SubPatch[3][3]; for (unsigned long k=0; k<3; k++) for (unsigned long l=0; l<3; l++) SubPatch[k][l]=GetVertex(i+k, j+l); SampleSinglePatch(SubPatch, baseCol, baseRow, TargetWidth, SubDivsHorz, SubDivsVert, TargetMesh); baseRow+=SubDivsVert; } baseCol+=SubDivsHorz; } // Copy the target mesh back into our mesh. Width =TargetWidth; Height=TargetHeight; Mesh =TargetMesh; if (OptimizeFlat) OptimizeFlatRowAndColumnStrips(); // Normalize all the lerped tangent space axes. for (unsigned long VertexNr=0; VertexNr<Mesh.Size(); VertexNr++) { Mesh[VertexNr].Normal =myNormalize(Mesh[VertexNr].Normal, T(0.0)); Mesh[VertexNr].TangentS=myNormalize(Mesh[VertexNr].TangentS, T(0.0)); Mesh[VertexNr].TangentT=myNormalize(Mesh[VertexNr].TangentT, T(0.0)); } // GenerateIndexes(); } template<class T> void BezierPatchT<T>::ForceLinearMaxLength(T MaxLength) { const T MaxLengthSqr=MaxLength*MaxLength; for (unsigned long i=0; i+1<Width; i++) { unsigned long j; for (j=0; j<Height; j++) if ((GetVertex(i, j).Coord-GetVertex(i+1, j).Coord).GetLengthSqr() > MaxLengthSqr) break; // If the edges were all short enough, no need to subdivide - just consider the next column. if (j==Height) continue; // Make room for another column between i and i+1. SetMeshSize(Width+1, Height); for (j=0; j<Height; j++) { for (unsigned long k=Width-1; k>i+1; k--) GetVertex(k, j)=GetVertex(k-1, j); // Compute the contents of the new column. VertexT& NewV=GetVertex(i+1, j); NewV.Average(GetVertex(i, j), GetVertex(i+2, j)); NewV.Normal =myNormalize(NewV.Normal, T(0.0)); NewV.TangentS=myNormalize(NewV.TangentS, T(0.0)); NewV.TangentT=myNormalize(NewV.TangentT, T(0.0)); } i--; } for (unsigned long j=0; j+1<Height; j++) { unsigned long i; for (i=0; i<Width; i++) if ((GetVertex(i, j).Coord-GetVertex(i, j+1).Coord).GetLengthSqr() > MaxLengthSqr) break; // If the edges were all short enough, no need to subdivide - just consider the next column. if (i==Width) continue; // Make room for another row between j and j+1. SetMeshSize(Width, Height+1); for (i=0; i<Width; i++) { for (unsigned long k=Height-1; k>j+1; k--) GetVertex(i, k)=GetVertex(i, k-1); // Compute the contents of the new column. VertexT& NewV=GetVertex(i, j+1); NewV.Average(GetVertex(i, j), GetVertex(i, j+2)); NewV.Normal =myNormalize(NewV.Normal, T(0.0)); NewV.TangentS=myNormalize(NewV.TangentS, T(0.0)); NewV.TangentT=myNormalize(NewV.TangentT, T(0.0)); } j--; } // GenerateIndexes(); } template<class T> T BezierPatchT<T>::GetSurfaceAreaAtVertex(unsigned long i, unsigned long j) const { static const int Neighbours[8][2]={ {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1}, {-1,-1}, {-1,0}, {-1,1} }; const VertexT& Center=GetVertex(i, j); T Area =0; for (unsigned long NeighbourNr=0; NeighbourNr<8; NeighbourNr++) { const int Edge1_i=int(i)+Neighbours[NeighbourNr][0]; const int Edge1_j=int(j)+Neighbours[NeighbourNr][1]; const int Edge2_i=int(i)+Neighbours[(NeighbourNr+1) & 7][0]; const int Edge2_j=int(j)+Neighbours[(NeighbourNr+1) & 7][1]; if (Edge1_i<0 || Edge1_i>=int(Width )) continue; if (Edge1_j<0 || Edge1_j>=int(Height)) continue; if (Edge2_i<0 || Edge2_i>=int(Width )) continue; if (Edge2_j<0 || Edge2_j>=int(Height)) continue; // Note that we only take half of the edges into account - the other half "belongs" to other vertices! Vector3T<T> Edge1=(GetVertex(Edge1_i, Edge1_j).Coord-Center.Coord)*0.5; Vector3T<T> Edge2=(GetVertex(Edge2_i, Edge2_j).Coord-Center.Coord)*0.5; Area+=length(cross(Edge1, Edge2))/2.0f; // Area+=dot(Center.Normal, cross(Edge1, Edge2))/2.0f; // Vermutung: Dies ergibt die auf die Ebene (durch Center.Normal definiert) projezierte Fläche! Beweis?? } return Area; } /// Changes the size of the mesh to NewWidth times NewHeight. template<class T> void BezierPatchT<T>::SetMeshSize(unsigned long NewWidth, unsigned long NewHeight) { // Well, the implementation is really simple, stable, and covers all cases // (mesh gets broader/narrower and/or heigher/lower), but it's slow, too... ArrayT<VertexT> NewMesh; NewMesh.PushBackEmpty(NewWidth*NewHeight); for (unsigned long j=0; j<NewHeight && j<Height; j++) for (unsigned long i=0; i<NewWidth && i<Width; i++) NewMesh[j*NewWidth+i]=Mesh[j*Width+i]; Mesh =NewMesh; Width =NewWidth; Height=NewHeight; } template<class T> typename BezierPatchT<T>::VertexT BezierPatchT<T>::SampleSinglePatchPoint(const VertexT SubPatch[3][3], const T u, const T v) const { VertexT SubColumnAtU[3]; const T u_0=(1-u)*(1-u); const T u_1=2*u*(1-u); const T u_2=u*u; // Find the control points in u direction for the v coordinate. for (unsigned long RowNr=0; RowNr<3; RowNr++) { SubColumnAtU[RowNr].Coord =SubPatch[0][RowNr].Coord *u_0 + SubPatch[1][RowNr].Coord *u_1 + SubPatch[2][RowNr].Coord *u_2; SubColumnAtU[RowNr].TexCoord=SubPatch[0][RowNr].TexCoord*u_0 + SubPatch[1][RowNr].TexCoord*u_1 + SubPatch[2][RowNr].TexCoord*u_2; SubColumnAtU[RowNr].Normal =SubPatch[0][RowNr].Normal *u_0 + SubPatch[1][RowNr].Normal *u_1 + SubPatch[2][RowNr].Normal *u_2; SubColumnAtU[RowNr].TangentS=SubPatch[0][RowNr].TangentS*u_0 + SubPatch[1][RowNr].TangentS*u_1 + SubPatch[2][RowNr].TangentS*u_2; SubColumnAtU[RowNr].TangentT=SubPatch[0][RowNr].TangentT*u_0 + SubPatch[1][RowNr].TangentT*u_1 + SubPatch[2][RowNr].TangentT*u_2; } VertexT Result; const T v_0=(1-v)*(1-v); const T v_1=2*v*(1-v); const T v_2=v*v; Result.Coord =SubColumnAtU[0].Coord *v_0 + SubColumnAtU[1].Coord *v_1 + SubColumnAtU[2].Coord *v_2; Result.TexCoord=SubColumnAtU[0].TexCoord*v_0 + SubColumnAtU[1].TexCoord*v_1 + SubColumnAtU[2].TexCoord*v_2; Result.Normal =SubColumnAtU[0].Normal *v_0 + SubColumnAtU[1].Normal *v_1 + SubColumnAtU[2].Normal *v_2; Result.TangentS=SubColumnAtU[0].TangentS*v_0 + SubColumnAtU[1].TangentS*v_1 + SubColumnAtU[2].TangentS*v_2; Result.TangentT=SubColumnAtU[0].TangentT*v_0 + SubColumnAtU[1].TangentT*v_1 + SubColumnAtU[2].TangentT*v_2; return Result; } template<class T> void BezierPatchT<T>::SampleSinglePatch(const VertexT SubPatch[3][3], unsigned long baseCol, unsigned long baseRow, unsigned long TargetWidth, unsigned long SubDivsHorz, unsigned long SubDivsVert, ArrayT<VertexT>& TargetMesh) const { SubDivsHorz+=1; SubDivsVert+=1; for (unsigned long i=0; i<SubDivsHorz; i++) { for (unsigned long j=0; j<SubDivsVert; j++) { const T u=T(i)/(SubDivsHorz-1); const T v=T(j)/(SubDivsVert-1); TargetMesh[(baseRow+j)*TargetWidth + baseCol+i]=SampleSinglePatchPoint(SubPatch, u, v); } } } /// Returns the result of Point projected onto the vector from Start to End. template<class T> Vector3T<T> BezierPatchT<T>::ProjectPointOntoVector(const Vector3T<T>& Point, const Vector3T<T>& Start, const Vector3T<T>& End) const { Vector3T<T> Vec=End-Start; const T Len=length(Vec); if (Len!=0) Vec/=Len; return Start+Vec*dot(Point-Start, Vec); } /// This method removes unnecessary vertices of "flat" sub-strips from the mesh. /// That is, if a vertex is in the line through its left and right neighbour vertices, /// and the same is true for all vertices in the same column (or row) of that vertex, /// the entire column (or row) can be removed, because the left and right vertices alone /// are enough to define that flat column (or row). template<class T> void BezierPatchT<T>::OptimizeFlatRowAndColumnStrips() { for (unsigned long j=1; j<Width-1; j++) { T MaxSqrDist=0; for (unsigned long i=0; i<Height; i++) { const Vector3T<T> Offset =GetVertex(j, i).Coord-ProjectPointOntoVector(GetVertex(j, i).Coord, GetVertex(j-1, i).Coord, GetVertex(j+1, i).Coord); const T DistSqr=Offset.GetLengthSqr(); if (DistSqr>MaxSqrDist) MaxSqrDist=DistSqr; } if (MaxSqrDist<=T(0.2*0.2)) { for (unsigned long i=0; i<Height; i++) for (unsigned long k=j; k+1<Width; k++) GetVertex(k, i)=GetVertex(k+1, i); SetMeshSize(Width-1, Height); j--; } } for (unsigned long j=1; j<Height-1; j++) { T MaxSqrDist=0; for (unsigned long i=0; i<Width; i++) { const Vector3T<T> Offset =GetVertex(i, j).Coord-ProjectPointOntoVector(GetVertex(i, j).Coord, GetVertex(i, j-1).Coord, GetVertex(i, j+1).Coord); const T DistSqr=Offset.GetLengthSqr(); if (DistSqr>MaxSqrDist) MaxSqrDist=DistSqr; } if (MaxSqrDist<T(0.2*0.2)) { for (unsigned long i=0; i<Width; i++) for (unsigned long k=j; k+1<Height; k++) GetVertex(i, k)=GetVertex(i, k+1); SetMeshSize(Width, Height-1); j--; } } } /// Computes the three tangent-space axes (the normal and the two tangent vectors) /// of the 3x3 sub-patch whose upper left corner is at (sp_i, sp_j) at (s, t), where s and t are values between 0 and 1. /// The method returns true on success, false on failure (the normal vector (Axes[0]) could not be computed because it is degenerate). template<class T> bool BezierPatchT<T>::ComputeTangentSpaceInSubPatch(unsigned long sp_i, unsigned long sp_j, const T s, const T t, Vector3T<T> Axes[3]) const { const T B_s [3]={ (1.0f-s)*(1.0f-s), 2.0f*s*(1.0f-s), s*s }; const T B_t [3]={ (1.0f-t)*(1.0f-t), 2.0f*t*(1.0f-t), t*t }; const T B_s_[3]={ 2.0f*(s-1.0f), 2.0f-4.0f*s, 2.0f*s }; // Derivation along s. const T B_t_[3]={ 2.0f*(t-1.0f), 2.0f-4.0f*t, 2.0f*t }; // Derivation along t. Vector3T<T> TangentS; // Tangents of the spatial patch surface. Vector3T<T> TangentT; Vector3T<T> TexTangentS; // Tangents of the texture image in 2D texture space. Vector3T<T> TexTangentT; for (unsigned long i=0; i<3; i++) for (unsigned long j=0; j<3; j++) { const VertexT& v=GetVertex(sp_i+i, sp_j+j); // Origin =Origin +scale(v.Coord, B_s [i]*B_t [j]); // TexCoord =TexCoord +scale(v.TexCoord, B_s [i]*B_t [j]); TangentS =TangentS +scale(v.Coord, B_s_[i]*B_t [j]); TangentT =TangentT +scale(v.Coord, B_s [i]*B_t_[j]); TexTangentS=TexTangentS+scale(v.TexCoord, B_s_[i]*B_t [j]); TexTangentT=TexTangentT+scale(v.TexCoord, B_s [i]*B_t_[j]); } // This is documented in my Tech Archive, see "Computing the tangent space basis vectors". // Note that only the *sign* of d is really important (less its magnitude). const T d=TexTangentS.x*TexTangentT.y-TexTangentS.y*TexTangentT.x; Axes[0]=cross(TangentT, TangentS); // Normal Axes[1]=scale(TangentT, -TexTangentS.y) + scale(TangentS, TexTangentT.y); // Tangent Axes[2]=scale(TangentT, TexTangentS.x) - scale(TangentS, TexTangentT.x); // BiTangent if (d<0) { Axes[1]=-Axes[1]; Axes[2]=-Axes[2]; } const T a0=length(Axes[0]); if (a0<0.000001f) return false; Axes[0]/=a0; myNormalize(Axes[1], T(0.0)); myNormalize(Axes[2], T(0.0)); return true; } /// Returns whether the patch mesh wraps "in the width", i.e. if the left and right borders are identical. template<class T> bool BezierPatchT<T>::WrapsHorz() const { for (unsigned long j=0; j<Height; j++) if ((GetVertex(0, j).Coord-GetVertex(Width-1, j).Coord).GetLengthSqr() > T(1.0*1.0)) return false; return true; } /// Returns whether the patch mesh wraps "in the height", i.e. if the top and bottom borders are identical. template<class T> bool BezierPatchT<T>::WrapsVert() const { for (unsigned long i=0; i<Width; i++) if ((GetVertex(i, 0).Coord-GetVertex(i, Height-1).Coord).GetLengthSqr() > T(1.0*1.0)) return false; return true; } template class BezierPatchT<float>; template class BezierPatchT<double>;
36.356751
249
0.581836
dns
55949ee946167bf47457fbc3f6ac8136600ee336
19,344
hpp
C++
include/tesserae/term_feature.hpp
ansariyusuf/tesserae
7954b8af33f4378b3f94eaa2fe8c007c4836ac8d
[ "MIT" ]
1
2021-08-14T09:22:10.000Z
2021-08-14T09:22:10.000Z
include/tesserae/term_feature.hpp
ansariyusuf/tesserae
7954b8af33f4378b3f94eaa2fe8c007c4836ac8d
[ "MIT" ]
null
null
null
include/tesserae/term_feature.hpp
ansariyusuf/tesserae
7954b8af33f4378b3f94eaa2fe8c007c4836ac8d
[ "MIT" ]
null
null
null
/* * Copyright 2018 The Tesserae authors. * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ #pragma once #include <cmath> #include <cstdio> #include <numeric> #include <string.h> #include "features/bm25/bm25.hpp" #include "features/bose_einstein/be.hpp" #include "features/dfr/dfr.hpp" #include "features/dph/dph.hpp" #include "features/lmds/lm.hpp" #include "features/probability/prob.hpp" #include "features/tfidf/tfidf.hpp" namespace { constexpr double zeta = 1.960; } struct feature_t { std::string term; uint64_t cf; uint64_t cdf; double geo_mean; double tfidf_median; double tfidf_first; double tfidf_third; double tfidf_min; double tfidf_max; double tfidf_avg; double tfidf_variance; double tfidf_std_dev; double tfidf_confidence; double tfidf_hmean; double bm25_median; double bm25_first; double bm25_third; double bm25_min; double bm25_max; double bm25_avg; double bm25_variance; double bm25_std_dev; double bm25_confidence; double bm25_hmean; double lm_median; double lm_first; double lm_third; double lm_min; double lm_max; double lm_avg; double lm_variance; double lm_std_dev; double lm_confidence; double lm_hmean; double dfr_median; double dfr_first; double dfr_third; double dfr_min; double dfr_max; double dfr_avg; double dfr_variance; double dfr_std_dev; double dfr_confidence; double dfr_hmean; double dph_median; double dph_first; double dph_third; double dph_min; double dph_max; double dph_avg; double dph_variance; double dph_std_dev; double dph_confidence; double dph_hmean; double be_median; double be_first; double be_third; double be_min; double be_max; double be_avg; double be_variance; double be_std_dev; double be_confidence; double be_hmean; double pr_median; double pr_first; double pr_third; double pr_min; double pr_max; double pr_avg; double pr_variance; double pr_std_dev; double pr_confidence; double pr_hmean; friend std::ostream &operator<<(std::ostream &os, const feature_t &f); }; std::ostream &operator<<(std::ostream &os, const feature_t &f) { os << f.term << " "; os << f.cf << " "; os << f.cdf << " "; os << f.geo_mean << " "; os << f.bm25_median << " "; os << f.bm25_first << " "; os << f.bm25_third << " "; os << f.bm25_max << " "; os << f.bm25_min << " "; os << f.bm25_avg << " "; os << f.bm25_variance << " "; os << f.bm25_std_dev << " "; os << f.bm25_confidence << " "; os << f.bm25_hmean << " "; os << f.tfidf_median << " "; os << f.tfidf_first << " "; os << f.tfidf_third << " "; os << f.tfidf_max << " "; os << f.tfidf_min << " "; os << f.tfidf_avg << " "; os << f.tfidf_variance << " "; os << f.tfidf_std_dev << " "; os << f.tfidf_confidence << " "; os << f.tfidf_hmean << " "; os << f.lm_median << " "; os << f.lm_first << " "; os << f.lm_third << " "; os << f.lm_max << " "; os << f.lm_min << " "; os << f.lm_avg << " "; os << f.lm_variance << " "; os << f.lm_std_dev << " "; os << f.lm_confidence << " "; os << f.lm_hmean << " "; os << f.pr_median << " "; os << f.pr_first << " "; os << f.pr_third << " "; os << f.pr_max << " "; os << f.pr_min << " "; os << f.pr_avg << " "; os << f.pr_variance << " "; os << f.pr_std_dev << " "; os << f.pr_confidence << " "; os << f.pr_hmean << " "; os << f.be_median << " "; os << f.be_first << " "; os << f.be_third << " "; os << f.be_max << " "; os << f.be_min << " "; os << f.be_avg << " "; os << f.be_variance << " "; os << f.be_std_dev << " "; os << f.be_confidence << " "; os << f.be_hmean << " "; os << f.dph_median << " "; os << f.dph_first << " "; os << f.dph_third << " "; os << f.dph_max << " "; os << f.dph_min << " "; os << f.dph_avg << " "; os << f.dph_variance << " "; os << f.dph_std_dev << " "; os << f.dph_confidence << " "; os << f.dph_hmean << " "; os << f.dfr_median << " "; os << f.dfr_first << " "; os << f.dfr_third << " "; os << f.dfr_max << " "; os << f.dfr_min << " "; os << f.dfr_avg << " "; os << f.dfr_variance << " "; os << f.dfr_std_dev << " "; os << f.dfr_confidence << " "; os << f.dfr_hmean << " "; os << std::endl; return os; } double compute_geo_mean(const std::vector<uint32_t> &freqs) { double sum = 0.0; for (auto &&f : freqs) { sum += f; } return pow(sum, (1.0 / freqs.size())); } void compute_prob_stats(feature_t & f, const std::vector<size_t> & doclen, const std::pair<std::vector<uint32_t>, std::vector<uint32_t>> &list, double & max) { uint32_t size = list.first.size(); uint32_t mid = size / 2; uint32_t lq = size / 4; uint32_t uq = 3 * size / 4; std::vector<double> bmtmp; for (size_t i = 0; i < size; ++i) { double score = calculate_prob(list.second[i], doclen[list.first[i]]); bmtmp.push_back(score); if (score > max) max = score; } std::sort(bmtmp.begin(), bmtmp.end(), std::greater<double>()); f.pr_median = size % 2 == 0 ? (bmtmp[mid] + bmtmp[mid - 1]) / 2 : bmtmp[mid]; f.pr_first = size % 2 == 0 ? (bmtmp[lq] + bmtmp[lq - 1]) / 2 : bmtmp[lq]; f.pr_third = size % 2 == 0 ? (bmtmp[uq] + bmtmp[uq - 1]) / 2 : bmtmp[uq]; f.pr_max = bmtmp[0]; f.pr_min = bmtmp[size - 1]; double sum = std::accumulate(bmtmp.begin(), bmtmp.end(), 0.0); double sum_sqrs = std::inner_product(bmtmp.begin(), bmtmp.end(), bmtmp.begin(), 0.0); double hmsum = std::accumulate( bmtmp.begin(), bmtmp.end(), 0.0, [](double a, double b) { return a + (1.0 / b); }); double avg = sum / size; double variance = std::abs((sum_sqrs / size) - avg * avg); double std_dev = std::sqrt(variance); f.pr_avg = avg; f.pr_variance = variance; f.pr_std_dev = std_dev; f.pr_confidence = zeta * (std_dev / (std::sqrt(size))); f.pr_hmean = (double)size / hmsum; } void compute_be_stats(feature_t & f, const std::vector<size_t> & doclen, const std::pair<std::vector<uint32_t>, std::vector<uint32_t>> &list, uint64_t ndocs, double avg_dlen, uint64_t c_f, double & max) { uint32_t size = list.first.size(); uint32_t mid = size / 2; uint32_t lq = size / 4; uint32_t uq = 3 * size / 4; std::vector<double> bmtmp; for (size_t i = 0; i < size; ++i) { double score = calculate_be(list.second[i], c_f, ndocs, avg_dlen, doclen[list.first[i]]); bmtmp.push_back(score); if (score > max) max = score; } std::sort(bmtmp.begin(), bmtmp.end(), std::greater<double>()); f.be_median = size % 2 == 0 ? (bmtmp[mid] + bmtmp[mid - 1]) / 2 : bmtmp[mid]; f.be_first = size % 2 == 0 ? (bmtmp[lq] + bmtmp[lq - 1]) / 2 : bmtmp[lq]; f.be_third = size % 2 == 0 ? (bmtmp[uq] + bmtmp[uq - 1]) / 2 : bmtmp[uq]; f.be_max = bmtmp[0]; f.be_min = bmtmp[size - 1]; double sum = std::accumulate(bmtmp.begin(), bmtmp.end(), 0.0); double sum_sqrs = std::inner_product(bmtmp.begin(), bmtmp.end(), bmtmp.begin(), 0.0); double hmsum = std::accumulate( bmtmp.begin(), bmtmp.end(), 0.0, [](double a, double b) { return a + (1.0 / b); }); double avg = sum / size; double variance = std::abs((sum_sqrs / size) - avg * avg); double std_dev = std::sqrt(variance); f.be_avg = avg; f.be_variance = variance; f.be_std_dev = std_dev; f.be_confidence = zeta * (std_dev / (std::sqrt(size))); f.be_hmean = (double)size / hmsum; } void compute_dph_stats(feature_t & f, const std::vector<size_t> & doclen, const std::pair<std::vector<uint32_t>, std::vector<uint32_t>> &list, uint64_t ndocs, double avg_dlen, uint64_t c_f, double & max) { uint32_t size = list.first.size(); uint32_t mid = size / 2; uint32_t lq = size / 4; uint32_t uq = 3 * size / 4; std::vector<double> bmtmp; for (size_t i = 0; i < size; ++i) { double score = calculate_dph(list.second[i], c_f, ndocs, avg_dlen, doclen[list.first[i]]); bmtmp.push_back(score); if (score > max) max = score; } std::sort(bmtmp.begin(), bmtmp.end(), std::greater<double>()); f.dph_median = size % 2 == 0 ? (bmtmp[mid] + bmtmp[mid - 1]) / 2 : bmtmp[mid]; f.dph_first = size % 2 == 0 ? (bmtmp[lq] + bmtmp[lq - 1]) / 2 : bmtmp[lq]; f.dph_third = size % 2 == 0 ? (bmtmp[uq] + bmtmp[uq - 1]) / 2 : bmtmp[uq]; f.dph_max = bmtmp[0]; f.dph_min = bmtmp[size - 1]; double sum = std::accumulate(bmtmp.begin(), bmtmp.end(), 0.0); double sum_sqrs = std::inner_product(bmtmp.begin(), bmtmp.end(), bmtmp.begin(), 0.0); double hmsum = std::accumulate( bmtmp.begin(), bmtmp.end(), 0.0, [](double a, double b) { return a + (1.0 / b); }); double avg = sum / size; double variance = std::abs((sum_sqrs / size) - avg * avg); double std_dev = std::sqrt(variance); f.dph_avg = avg; f.dph_variance = variance; f.dph_std_dev = std_dev; f.dph_confidence = zeta * (std_dev / (std::sqrt(size))); f.dph_hmean = (double)size / hmsum; } void compute_dfr_stats(feature_t & f, const std::vector<size_t> & doclen, const std::pair<std::vector<uint32_t>, std::vector<uint32_t>> &list, uint64_t ndocs, double avg_dlen, uint64_t c_f, double & max) { uint32_t size = list.first.size(); uint32_t mid = size / 2; uint32_t lq = size / 4; uint32_t uq = 3 * size / 4; std::vector<double> bmtmp; for (size_t i = 0; i < size; ++i) { double score = calculate_dfr(list.second[i], c_f, size, ndocs, avg_dlen, doclen[list.first[i]]); bmtmp.push_back(score); if (score > max) max = score; } std::sort(bmtmp.begin(), bmtmp.end(), std::greater<double>()); f.dfr_median = size % 2 == 0 ? (bmtmp[mid] + bmtmp[mid - 1]) / 2 : bmtmp[mid]; f.dfr_first = size % 2 == 0 ? (bmtmp[lq] + bmtmp[lq - 1]) / 2 : bmtmp[lq]; f.dfr_third = size % 2 == 0 ? (bmtmp[uq] + bmtmp[uq - 1]) / 2 : bmtmp[uq]; f.dfr_max = bmtmp[0]; f.dfr_min = bmtmp[size - 1]; double sum = std::accumulate(bmtmp.begin(), bmtmp.end(), 0.0); double sum_sqrs = std::inner_product(bmtmp.begin(), bmtmp.end(), bmtmp.begin(), 0.0); double hmsum = std::accumulate( bmtmp.begin(), bmtmp.end(), 0.0, [](double a, double b) { return a + (1.0 / b); }); double avg = sum / size; double variance = std::abs((sum_sqrs / size) - avg * avg); double std_dev = std::sqrt(variance); f.dfr_avg = avg; f.dfr_variance = variance; f.dfr_std_dev = std_dev; f.dfr_confidence = zeta * (std_dev / (std::sqrt(size))); f.dfr_hmean = (double)size / hmsum; } void compute_tfidf_stats(feature_t & f, const std::vector<size_t> & doclen, const std::pair<std::vector<uint32_t>, std::vector<uint32_t>> &list, uint64_t ndocs, double & max) { size_t size = list.first.size(); uint32_t mid = size / 2; uint32_t lq = size / 4; uint32_t uq = 3 * size / 4; std::vector<double> bmtmp; for (size_t i = 0; i < size; ++i) { double score = calculate_tfidf(list.second[i], size, doclen[list.first[i]], ndocs); bmtmp.push_back(score); if (score > max) max = score; } std::sort(bmtmp.begin(), bmtmp.end(), std::greater<double>()); f.tfidf_median = size % 2 == 0 ? (bmtmp[mid] + bmtmp[mid - 1]) / 2 : bmtmp[mid]; f.tfidf_first = size % 2 == 0 ? (bmtmp[lq] + bmtmp[lq - 1]) / 2 : bmtmp[lq]; f.tfidf_third = size % 2 == 0 ? (bmtmp[uq] + bmtmp[uq - 1]) / 2 : bmtmp[uq]; f.tfidf_max = bmtmp[0]; f.tfidf_min = bmtmp[size - 1]; double sum = std::accumulate(bmtmp.begin(), bmtmp.end(), 0.0); double sum_sqrs = std::inner_product(bmtmp.begin(), bmtmp.end(), bmtmp.begin(), 0.0); double hmsum = std::accumulate( bmtmp.begin(), bmtmp.end(), 0.0, [](double a, double b) { return a + (1.0 / b); }); double avg = sum / size; double variance = std::abs((sum_sqrs / size) - avg * avg); double std_dev = std::sqrt(variance); f.tfidf_avg = avg; f.tfidf_variance = variance; f.tfidf_std_dev = std_dev; f.tfidf_confidence = zeta * (std_dev / (std::sqrt(size))); f.tfidf_hmean = (double)size / hmsum; } void compute_bm25_stats(feature_t & f, const std::vector<size_t> & doclen, const std::pair<std::vector<uint32_t>, std::vector<uint32_t>> &list, uint64_t ndocs, double avg_dlen, double & max) { uint32_t size = list.first.size(); uint32_t mid = size / 2; uint32_t lq = size / 4; uint32_t uq = 3 * size / 4; std::vector<double> bmtmp; rank_bm25 ranker; ranker.set_k1(90); ranker.set_b(40); ranker.num_docs = ndocs; ranker.avg_doc_len = avg_dlen; for (size_t i = 0; i < size; ++i) { double score = ranker.calculate_docscore(1, list.second[i], size, doclen[list.first[i]]); bmtmp.push_back(score); if (score > max) max = score; } std::sort(bmtmp.begin(), bmtmp.end(), std::greater<double>()); f.bm25_median = size % 2 == 0 ? (bmtmp[mid] + bmtmp[mid - 1]) / 2 : bmtmp[mid]; f.bm25_first = size % 2 == 0 ? (bmtmp[lq] + bmtmp[lq - 1]) / 2 : bmtmp[lq]; f.bm25_third = size % 2 == 0 ? (bmtmp[uq] + bmtmp[uq - 1]) / 2 : bmtmp[uq]; f.bm25_max = bmtmp[0]; f.bm25_min = bmtmp[size - 1]; double sum = std::accumulate(bmtmp.begin(), bmtmp.end(), 0.0); double sum_sqrs = std::inner_product(bmtmp.begin(), bmtmp.end(), bmtmp.begin(), 0.0); double hmsum = std::accumulate( bmtmp.begin(), bmtmp.end(), 0.0, [](double a, double b) { return a + (1.0 / b); }); double avg = sum / size; double variance = std::abs((sum_sqrs / size) - avg * avg); double std_dev = std::sqrt(variance); f.bm25_avg = avg; f.bm25_variance = variance; f.bm25_std_dev = std_dev; f.bm25_confidence = zeta * (std_dev / (std::sqrt(size))); f.bm25_hmean = (double)size / hmsum; } void compute_lm_stats(feature_t & f, const std::vector<size_t> & doclen, const std::pair<std::vector<uint32_t>, std::vector<uint32_t>> &list, uint64_t clen, uint64_t cf, double & max) { uint32_t size = list.first.size(); uint32_t mid = size / 2; uint32_t lq = size / 4; uint32_t uq = 3 * size / 4; double mu = 2500.00; std::vector<double> bmtmp; for (size_t i = 0; i < size; ++i) { double score = calculate_lm(list.second[i], cf, doclen[list.first[i]], clen, mu); bmtmp.push_back(score); if (score > max) max = score; } std::sort(bmtmp.begin(), bmtmp.end(), std::greater<double>()); f.lm_median = size % 2 == 0 ? (bmtmp[mid] + bmtmp[mid - 1]) / 2 : bmtmp[mid]; f.lm_first = size % 2 == 0 ? (bmtmp[lq] + bmtmp[lq - 1]) / 2 : bmtmp[lq]; f.lm_third = size % 2 == 0 ? (bmtmp[uq] + bmtmp[uq - 1]) / 2 : bmtmp[uq]; f.lm_max = bmtmp[0]; f.lm_min = bmtmp[size - 1]; double sum = std::accumulate(bmtmp.begin(), bmtmp.end(), 0.0); double sum_sqrs = std::inner_product(bmtmp.begin(), bmtmp.end(), bmtmp.begin(), 0.0); double hmsum = std::accumulate( bmtmp.begin(), bmtmp.end(), 0.0, [](double a, double b) { return a + (1.0 / b); }); double avg = sum / size; double variance = std::abs((sum_sqrs / size) - avg * avg); double std_dev = std::sqrt(variance); f.lm_avg = avg; f.lm_variance = variance; f.lm_std_dev = std_dev; f.lm_confidence = zeta * (std_dev / (std::sqrt(size))); f.lm_hmean = (double)size / hmsum; }
39.157895
98
0.472963
ansariyusuf
55a197ae946add412c2cb21f3cb25e1f7c1466e9
8,795
cxx
C++
resip/stack/WsFrameExtractor.cxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
1
2019-04-15T14:10:58.000Z
2019-04-15T14:10:58.000Z
resip/stack/WsFrameExtractor.cxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
null
null
null
resip/stack/WsFrameExtractor.cxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
2
2019-10-31T09:11:09.000Z
2021-09-17T01:00:49.000Z
#include "rutil/Logger.hxx" #include "resip/stack/WsFrameExtractor.hxx" #include "rutil/WinLeakCheck.hxx" using namespace resip; #define RESIPROCATE_SUBSYSTEM Subsystem::TRANSPORT const int WsFrameExtractor::mMaxHeaderLen = 14; WsFrameExtractor::WsFrameExtractor(Data::size_type maxMessage) : mMaxMessage(maxMessage), mMessageSize(0), mHaveHeader(false), mHeaderLen(0) { // we re-use this for multiple messages throughout // the lifetime of this parser object mWsHeader = new UInt8[mMaxHeaderLen]; } WsFrameExtractor::~WsFrameExtractor() { // FIXME - delete any objects left in the queues delete [] mWsHeader; while(!mFrames.empty()) { delete [] mFrames.front()->data(); delete mFrames.front(); mFrames.pop(); } while(!mMessages.empty()) { delete [] mMessages.front()->data(); delete mMessages.front(); mMessages.pop(); } } std::auto_ptr<Data> WsFrameExtractor::processBytes(UInt8 *input, Data::size_type len, bool& dropConnection) { std::auto_ptr<Data> ret(0); dropConnection = false; Data::size_type pos = 0; while(input != 0 && pos < len) { while(!mHaveHeader && pos < len) { StackLog(<<"Need a header, parsing bytes..."); // Append bytes to the header buffer int needed = parseHeader(); if(mHeaderLen >= mMaxHeaderLen) { WarningLog(<<"WS Frame header too long"); dropConnection = true; return ret; } for( ; needed > 0 && pos < len; needed-- ) { mWsHeader[mHeaderLen++] = input[pos++]; } if(needed > 0) { StackLog(<<"Not enough bytes available to form a full header"); return ret; } } if(mHaveHeader) { StackLog(<<"have header, parsing payload data..."); // Process input bytes to output buffer, unmasking if necessary if(mMessageSize + mPayloadLength > mMaxMessage) { WarningLog(<<"WS frame header describes a payload size bigger than messageSizeMax, max = " << mMaxMessage << ", dropping connection"); dropConnection = true; return ret; } Data::size_type takeBytes = len - pos; if(takeBytes > mPayloadLength) { takeBytes = mPayloadLength; } if(mPayload == 0) { StackLog(<<"starting new frame buffer"); // Include an extra byte at the end for null terminator mPayload = (UInt8*)new char[mPayloadLength + 1]; mPayloadPos = 0; } if(mMasked) { Data::size_type endOffset = mPayloadPos + takeBytes; for( ; mPayloadPos < endOffset; mPayloadPos++) { mPayload[mPayloadPos] = (input[pos++] ^ mWsMaskKey[(mPayloadPos & 3)]); } } else { memmove(&mPayload[mPayloadPos], &input[pos], takeBytes); pos += takeBytes; mPayloadPos += takeBytes; } if(mPayloadPos == mPayloadLength) { StackLog(<<"Got a whole frame, queueing it"); mMessageSize += mPayloadLength; Data *mFrame = new Data(Data::Borrow, (char *)mPayload, mPayloadLength, mPayloadLength + 1); mFrames.push(mFrame); mHaveHeader = false; mHeaderLen = 0; mPayload = 0; if(mFinalFrame) { joinFrames(); } } } } if(mMessages.empty()) { StackLog(<<"no full messages available in queue"); return ret; } ret = std::auto_ptr<Data>(mMessages.front()); mMessages.pop(); StackLog(<<"returning a message, size = " << ret->size()); return ret; } int WsFrameExtractor::parseHeader() { if(mHeaderLen < 2) { StackLog(<< "Too short to contain ws data [0]"); return (2 - mHeaderLen); } UInt64 hdrPos = 2; mFinalFrame = (mWsHeader[0] >> 7) != 0; mMasked = (mWsHeader[1] >> 7) != 0; if(mWsHeader[0] & 0x40 || mWsHeader[0] & 0x20 || mWsHeader[0] & 0x10) { WarningLog(<< "Unknown extension: " << ((mWsHeader[0] >> 4) & 0x07)); // do not exit } mPayloadLength = mWsHeader[1] & 0x7F; if(mPayloadLength == 126) { if(mHeaderLen < 4) { StackLog(<< "Too short to contain ws data [1]"); return (4 - mHeaderLen) + (mMasked ? 4 : 0); } mPayloadLength = (mWsHeader[hdrPos] << 8 | mWsHeader[hdrPos + 1]); hdrPos += 2; } else if(mPayloadLength == 127) { if(mHeaderLen < 8) { StackLog(<< "Too short to contain ws data [2]"); return (8 - mHeaderLen) + (mMasked ? 4 : 0); } mPayloadLength = (((UInt64)mWsHeader[hdrPos]) << 56 | ((UInt64)mWsHeader[hdrPos + 1]) << 48 | ((UInt64)mWsHeader[hdrPos + 2]) << 40 | ((UInt64)mWsHeader[hdrPos + 3]) << 32 | ((UInt64)mWsHeader[hdrPos + 4]) << 24 | ((UInt64)mWsHeader[hdrPos + 5]) << 16 | ((UInt64)mWsHeader[hdrPos + 6]) << 8 || ((UInt64)mWsHeader[hdrPos + 7])); hdrPos += 8; } if(mMasked) { if((mHeaderLen - hdrPos) < 4) { StackLog(<< "Too short to contain ws data [3]"); return (int)((hdrPos + 4) - mHeaderLen); } mWsMaskKey[0] = mWsHeader[hdrPos]; mWsMaskKey[1] = mWsHeader[hdrPos + 1]; mWsMaskKey[2] = mWsHeader[hdrPos + 2]; mWsMaskKey[3] = mWsHeader[hdrPos + 3]; hdrPos += 4; } StackLog(<< "successfully processed a WebSocket frame header, payload length = " << mPayloadLength << ", masked = "<< mMasked << ", final frame = "<< mFinalFrame); mHaveHeader = true; mPayload = 0; return 0; } void WsFrameExtractor::joinFrames() { StackLog(<<"trying to join frames"); if(mFrames.empty()) { ErrLog(<<"No frames to join!"); return; } Data *msg = mFrames.front(); mFrames.pop(); if(!mFrames.empty()) { // must expand buffer because there are multiple frames // can't use Data::reserve() to increase the buffer, because the // ShareEnum will change to Take when expanded char *_msg = (char *)msg->data(); Data::size_type frameSize = msg->size(); delete msg; // allow extra byte for null terminator char *newBuf = new char [mMessageSize + 1]; memcpy(newBuf, _msg, frameSize); msg = new Data(Data::Borrow, newBuf, frameSize, mMessageSize + 1); } while(!mFrames.empty()) { Data *mFrame = mFrames.front(); mFrames.pop(); msg->append(mFrame->data(), mFrame->size()); delete [] mFrame->data(); delete mFrame; } // It is safe to cast because we used Borrow: char *_msg = (char *)msg->data(); // MsgHeaderScanner expects space for an extra byte at the end: _msg[mMessageSize] = 0; mMessages.push(msg); // Ready to start examinging first frame of next message... mMessageSize = 0; } /* ==================================================================== * * Copyright 2013 Daniel Pocock. 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. Neither the name of the author(s) nor the names of any contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) 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 AUTHOR(S) 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. * * ==================================================================== * * */
30.327586
333
0.585901
dulton
55a44df223ceab063fff16a7c965c80e08da3c8f
16,901
cpp
C++
flash-graph/libgraph-algs/knn.back.cpp
kjhyun824/uncertain-graph-engine
17aa1b8b5d03b03200583797ab0cfb4a42ff8845
[ "Apache-2.0" ]
null
null
null
flash-graph/libgraph-algs/knn.back.cpp
kjhyun824/uncertain-graph-engine
17aa1b8b5d03b03200583797ab0cfb4a42ff8845
[ "Apache-2.0" ]
null
null
null
flash-graph/libgraph-algs/knn.back.cpp
kjhyun824/uncertain-graph-engine
17aa1b8b5d03b03200583797ab0cfb4a42ff8845
[ "Apache-2.0" ]
null
null
null
// // Created by kckjn97 on 17. 11. 22. // #ifndef VATTR_SAVE #define VATTR_SAVE 0 #endif #include <signal.h> #ifdef PROFILER #include <gperftools/profiler.h> #endif #include <set> #include <vector> #include "graph_engine.h" #include "graph_config.h" #include "FGlib.h" #include <mutex> /* KJH : For mmap() */ #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> using namespace safs; using namespace fg; #define partSize 1000 int key; int nResult; int nSample; int bound; int diff; vertex_id_t sv; std::set<vertex_id_t> res; std::mutex lock; struct distribution { int dist; double probability; struct distribution* next; // Linked list format }; // compute_directed_vertex_t; /* class vertex_part_t { compute_directed_vertex_t *vertices; int part_id; } class pwg_t { int seed; vertex_part_t* parts; } */ // KJH TODO : Where should these attributes stored? typedef struct { vertex_id_t vid; unsigned int distance; // Vertices distribution bool active; //Check the vertex is activated bool adaptation; // Distance used for distribution } vattr_t; typedef vattr_t* part_t; // TODO : pwgs_vertex_attr - (num_vertex, num_sample, partition list) & make folder for that PWG // TODO : partition - (buffer, attr) & make file for that PWG's partition class pwgs_vertex_attr{ unsigned int num_vertex; unsigned int num_sample; char* buf; vattr_t* attr; part_t* partitions; public: int key; ~pwgs_vertex_attr(){ } void init(unsigned int num_sample, unsigned int num_vertex){ char *file = NULL; int flag = PROT_WRITE | PROT_READ; int fd; struct stat fileInfo = {0}; this->num_sample = num_sample; this->num_vertex = num_vertex; int numParts = ((num_vertex / partSize) == 0) ? (num_vertex / partSize) : ((num_vertex / partSize) + 1); partitions = new part_t[numParts]; key = ~0; buf = (char*) malloc(partSize * sizeof(vattr_t)); attr = (vattr_t*) buf; for(int i=0; i < partSize; i++) { attr[i].vid = i; attr[i].distance = ~0; attr[i].active = true; attr[i].adaptation = false; } for(int i=0; i < num_sample; i++){ /* KJH */ for(int j = 0; j < numParts; j++) { std::string filename2 = "map" + std::to_string(i) + "_" + std::to_string(j) + ".txt"; if((fd=open(filename2.c_str() ,O_RDWR|O_CREAT,0664)) < 0) { perror("File Open Error"); exit(1); } if(fstat(fd,&fileInfo) == -1) { perror("Error for getting size"); exit(1); } if((file = (char*) mmap(0,partSize * sizeof(vattr_t), flag, MAP_SHARED, fd, 0)) == NULL) { perror("mmap error"); exit(1); } if(write(fd,buf,partSize*sizeof(vattr_t)) == -1) { perror("write error"); exit(1); } if (msync(file , partSize * sizeof(vattr_t), MS_SYNC) == -1) { perror("Could not sync the file to disk"); } if (munmap(file, partSize * sizeof(vattr_t)) == -1) { perror("munmap error"); exit(1); } close(fd); } } } // Use mmap, file per one partition // File descriptor list void save(unsigned int key, int partId) { assert(this->key == key); std::string filename2 = "map" + std::to_string(key) + "_" + std::to_string(partId) + ".txt"; int fd = open(filename2.c_str(), O_RDWR); write(fd,buf,partSize * sizeof(vattr_t)); close(fd); }; void load(unsigned int key, int partId) { this->key = key; std::string filename2 = "map" + std::to_string(key) + "_" + std::to_string(partId) + ".txt"; int fd = open(filename2.c_str(), O_RDWR); read(fd,buf,partSize * sizeof(vattr_t)); close(fd); }; vattr_t* get_value(vertex_id_t vid) { assert(attr[vid].vid==vid); return attr+vid; } }; pwgs_vertex_attr pwgs_vattr; namespace { class distance_message: public vertex_message{ public: unsigned int distance; distance_message(unsigned int distance): vertex_message(sizeof(distance_message), true){ this->distance = distance; } }; class knn_vertex: public compute_directed_vertex { public: #if VATTR_SAVE vattr_t* vattr; #else vertex_id_t vid; bool *active; //Check the vertex is activated unsigned int *distance; // Vertices distribution bool *adaptation; // Distance used for distribution #endif distribution distHead; // Distribution from source knn_vertex(vertex_id_t id): compute_directed_vertex(id) { #if VATTR_SAVE vattr = pwgs_vattr.get_value(id); // TODO : Maybe erase later #else vid = id; active = new bool[nSample]; distance = new unsigned int[nSample]; adaptation = new bool[nSample]; for(int i = 0; i < nSample; i++) { distance[i] = ~0; active[i] = true; adaptation[i] = false; } #endif distHead.next = NULL; } void run(vertex_program &prog) { #if VATTR_SAVE vertex_id_t vid = prog.get_vertex_id(*this); vattr = pwgs_vattr.get_value(vid); if(vid != sv && vattr->distance >= bound) { return; } // For non-visited vertices, request their edge list if (vattr->active) { directed_vertex_request req(vid, OUT_EDGE); request_partial_vertices(&req, 1); } #else if(vid != sv && distance[key] >= bound) { return; } // For non-visited vertices, request their edge list if (active[key]) { directed_vertex_request req(vid, OUT_EDGE); request_partial_vertices(&req, 1); } #endif } void run(vertex_program &prog, const page_vertex &vertex){ #if VATTR_SAVE vertex_id_t vid = prog.get_vertex_id(*this); vattr->active = false; int num_dests = vertex.get_num_edges(OUT_EDGE); if (num_dests == 0) return; srand(vid*(key+1)); // Give seed to generate random specific number; TODO: Add time instance to give randomness edge_iterator it_neighbor = vertex.get_neigh_begin(OUT_EDGE); edge_iterator it_neighbor_end = vertex.get_neigh_end(OUT_EDGE); safs::page_byte_array::const_iterator<float> it_data = ((const page_directed_vertex &) vertex).get_data_begin<float>(OUT_EDGE); // Iterates neighbors for (; it_neighbor != it_neighbor_end;) { float prob = *it_data - (int) *it_data; unsigned int weight = (unsigned int) *it_data; unsigned int distance_sum = weight ; if (vattr->distance != ~0) distance_sum += vattr->distance; distance_message msg(distance_sum); #define PRECISION 1000 float r = rand() % PRECISION; if(r <= prob * PRECISION) { prog.send_msg(*it_neighbor, msg); } it_neighbor += 1; it_data += 1; } #else active[key] = false; int num_dests = vertex.get_num_edges(OUT_EDGE); if (num_dests == 0) return; srand(vid*(key+1)); // Give seed to generate random specific number; TODO: Add time instance to give randomness edge_iterator it_neighbor = vertex.get_neigh_begin(OUT_EDGE); edge_iterator it_neighbor_end = vertex.get_neigh_end(OUT_EDGE); safs::page_byte_array::const_iterator<float> it_data = ((const page_directed_vertex &) vertex).get_data_begin<float>(OUT_EDGE); // Iterates neighbors for (; it_neighbor != it_neighbor_end;) { float prob = *it_data - (int) *it_data; unsigned int weight = (unsigned int) *it_data; unsigned int distance_sum = weight ; if (distance[key] != ~0) distance_sum += distance[key]; distance_message msg(distance_sum); #define PRECISION 1000 float r = rand() % PRECISION; if(r <= prob * PRECISION) { prog.send_msg(*it_neighbor, msg); } it_neighbor += 1; it_data += 1; } #endif }; void run_on_message(vertex_program &prog, const vertex_message &msg) { vertex_id_t vid = prog.get_vertex_id(*this); const distance_message &w_msg = (const distance_message&) msg; #if VATTR_SAVE if(vattr->distance > w_msg.distance){ vattr->distance = w_msg.distance; vattr->active = true; // Reactivation doesn't need prog.activate_vertex(vid); } #else if(distance[key] > w_msg.distance){ distance[key] = w_msg.distance; active[key] = true; // Reactivation doesn't need prog.activate_vertex(vid); } #endif } }; // KJH template<class vertex_type> class accum_vertex_query: public vertex_query { public: accum_vertex_query() { } virtual void run(graph_engine &graph, compute_vertex &v) { vertex_type &knn_v = (vertex_type &) v; // 1. check all samples that has adapted before (adaptation) // 2. Check the distance has set (distance) // 3. If it has set, add to distribution // 3.1 If it's in distribution, just add the PWG of the sample world // 3.2 If it's not, append one more node and add the PWG's prob to list double add_prob = 1.0 / (double) nSample; #if VATTR_SAVE if(!knn_v.vattr->adaptation && knn_v.vattr->distance != ~0) { int currDist = knn_v.vattr->distance; distribution *curr = &(knn_v.distHead); while(curr->next != NULL) { if(curr->next->dist <= currDist) break; curr = curr->next; } if(curr->next != NULL && curr->next->dist == currDist) { // Already distribution curr->next->probability += add_prob; } else { // New one distribution *node = new struct distribution; node->dist = currDist; node->probability = add_prob; node->next = curr->next; curr->next = node; } knn_v.vattr->adaptation = true; } #else if(!knn_v.adaptation[key] && knn_v.distance[key] != ~0) { int currDist = knn_v.distance[key]; distribution *curr = &knn_v.distHead; while(curr->next != NULL) { if(curr->next->dist <= currDist) break; curr = curr->next; } //std::cout <<curr->next<<"\n"; if(curr->next != NULL && curr->next->dist == currDist) { // Already distribution curr->next->probability += add_prob; } else { // New one distribution *node = new struct distribution; node->dist = currDist; node->probability = add_prob; node->next = curr->next; curr->next = node; } //std::cout << currDist << " " <<curr->next->probability<< " "<<curr->next->dist<<"\n"; knn_v.adaptation[key] = true; } #endif } virtual void merge(graph_engine &graph, vertex_query::ptr q) { } virtual ptr clone() { return vertex_query::ptr(new accum_vertex_query()); } }; template<class vertex_type> class res_vertex_query: public vertex_query { public: res_vertex_query() { } virtual void run(graph_engine &graph, compute_vertex &v) { if(res.size() >= nResult) return; vertex_type &knn_v = (vertex_type &) v; #if VATTR_SAVE vertex_id_t t_vid = knn_v.vattr->vid; if(res.find(t_vid) == res.end()) { distribution *curr = &knn_v.distHead; double probSum = 0.0; while(curr->next != NULL) { probSum += curr->next->probability; if(probSum > 0.5) break; curr = curr->next; } if(curr->next != NULL) { if(curr->next->dist < bound) { lock.lock(); res.insert(t_vid); lock.unlock(); } } } #else vertex_id_t t_vid = knn_v.vid; if(res.find(t_vid) == res.end()) { distribution *curr = &knn_v.distHead; double probSum = 0.0; while(curr->next != NULL) { probSum += curr->next->probability; if(probSum > 0.5) break; curr = curr->next; } if(curr->next != NULL) { if(curr->next->dist < bound) { lock.lock(); res.insert(t_vid); lock.unlock(); } } } #endif } virtual void merge(graph_engine &graph, vertex_query::ptr q) { } virtual ptr clone() { return vertex_query::ptr(new res_vertex_query()); } }; } std::set<vertex_id_t> knn(FG_graph::ptr fg, vertex_id_t start_vertex, int k, int _nSample) { nResult = k; nSample = _nSample; #if VATTR_SAVE pwgs_vattr.init(nSample, fg->get_index_data()->get_max_id()+1); #endif sv = start_vertex; bound = 0; diff = 1; // Just for accuracy, Maybe set by user graph_index::ptr index; index = NUMA_graph_index<knn_vertex>::create(fg->get_graph_header()); graph_engine::ptr graph = fg->create_engine(index); //graph->setNumSample(nSample); //graph->generatePWGs(); /* KJH */ vertex_query::ptr avq, rvq; avq = vertex_query::ptr(new accum_vertex_query<knn_vertex>()); rvq = vertex_query::ptr(new res_vertex_query<knn_vertex>()); bool start=true; while(res.size() < k) { for(int i=0; i < nSample; i++) { // TODO : Load PWG Vertex Attr key = i; #if VATTR_SAVE pwgs_vattr.load(key, 0); // TODO : partId instead 0 #endif if(start) graph->start(&start_vertex,1); else graph->start_all(); start=false; graph->wait4complete(); // Calculate distribution for a specific PWG graph->query_on_all(avq); // TODO : Save PWG Vertex Attr // Divide two things : According to how many updates have done // Many -> Full flush / Small -> Logging #if VATTR_SAVE pwgs_vattr.save(key, 0); // TODO : partId instead 0 #endif } // Aggregate results from all PWGs // Median Distance calc // Add to result set graph->query_on_all(rvq); bound += diff; } return res; }
31.414498
143
0.497308
kjhyun824
55a545259ca963cf5b134573911ecfef05a7f82c
3,086
cpp
C++
tools/test_kopter.cpp
dirkholz/libmikrokopter
d25b0b5e663776df0063e2b51d32f730ae7a12f0
[ "BSD-2-Clause" ]
1
2018-09-03T12:43:08.000Z
2018-09-03T12:43:08.000Z
tools/test_kopter.cpp
dirkholz/libmikrokopter
d25b0b5e663776df0063e2b51d32f730ae7a12f0
[ "BSD-2-Clause" ]
null
null
null
tools/test_kopter.cpp
dirkholz/libmikrokopter
d25b0b5e663776df0063e2b51d32f730ae7a12f0
[ "BSD-2-Clause" ]
null
null
null
/* -*- Mode: c++; tab-width: 2; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* vim:set softtabstop=2 shiftwidth=2 tabstop=2 expandtab: */ /* * Software License Agreement (BSD License) * * Copyright (c) 2012, Dirk Holz, University of Bonn. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <mikrokopter/kopter.h> #include <mikrokopter/io/console.h> #include <mikrokopter/io/serial.h> #include <mikrokopter/common/time.h> int main(int argc, char** argv) { try { std::string port = "/dev/ttyUSB0"; if (argc > 1) port = argv[1]; std::cout << "Opening MikroKopter communication on port " << port << std::endl; mikrokopter::io::IO::Ptr comm(new mikrokopter::io::Serial(port)); mikrokopter::Kopter kopter(comm); // set debug level to see all messages sent and received // comm->DEBUG_LEVEL = 1; // kopter.connectNaviCtrl(); kopter.connectFlightCtrl(); // kopter.connectMK3MAG(); /* left-handed frame, x front */ mikrokopter::protocol::ExternControl control; control.config = 1; control.pitch = control.roll = 0; control.yaw = 0; control.height = 0; control.gas = 0; mikrokopter::common::StopWatch stopwatch_total; while(1) { kopter.sendExternalControl(control); const int debug_request_interval = 50; DO_EVERY(1, kopter.requestDebugData(debug_request_interval)); DO_EVERY(0.1, kopter.printFlightControlDebugData()); boost::this_thread::sleep(boost::posix_time::milliseconds(debug_request_interval)); } } catch( boost::system::system_error& e) { std::cerr << "ERROR: " << e.what() << std::endl; } catch(...) { std::cerr << "Caught unhandled exception!" << std::endl; } return 0; }
33.182796
89
0.689566
dirkholz
55ac9a7721151e34a075b89f4434ebac421f77e3
1,390
cpp
C++
Love Babber OnGoing Placement/BinarySearch/PeakOfTheMountain.cpp
work-mohit/Placement-Practice
396e61f7980991b2d6392589f26f917981c135ab
[ "MIT" ]
null
null
null
Love Babber OnGoing Placement/BinarySearch/PeakOfTheMountain.cpp
work-mohit/Placement-Practice
396e61f7980991b2d6392589f26f917981c135ab
[ "MIT" ]
null
null
null
Love Babber OnGoing Placement/BinarySearch/PeakOfTheMountain.cpp
work-mohit/Placement-Practice
396e61f7980991b2d6392589f26f917981c135ab
[ "MIT" ]
null
null
null
class Solution { public: int peakIndexInMountainArray(vector<int>& arr) { int n = arr.size(); int s =0; int e = n-1; int mid= s + (e-s)/2; while(s < e){ if(arr[mid] < arr[mid+1]){ s = mid + 1; }else{ e = mid; } mid= s + (e-s)/2; } return mid; } }; ////////////////////////////////////////////////////// class Solution { public: int peakIndexInMountainArray(vector<int>& arr) { int start = 0; int end = arr.size()-1; int middle; int peak_index; while(start <= end) { middle = (start + end)/2; // Comparing with the next element if(arr[middle] > arr[middle + 1]) { peak_index = middle; end = middle - 1; } else if(arr[middle] < arr[middle + 1]) start = middle + 1; // Comparing with the previous element else if(arr[middle] > arr[middle - 1]) { peak_index = middle; start = middle + 1; } else if (arr[middle] < arr[middle -1]) end = middle - 1; } return peak_index; } };
23.965517
54
0.372662
work-mohit
55ae77cdf3fcf6be5eef89958c366cc122681030
5,425
cpp
C++
src/frameworks/av/media/libstagefright/bqhelper/tests/FrameDropper_test.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/av/media/libstagefright/bqhelper/tests/FrameDropper_test.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/av/media/libstagefright/bqhelper/tests/FrameDropper_test.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
2
2021-07-08T07:42:11.000Z
2021-07-09T21:56:10.000Z
/* * Copyright (C) 2015 The Android Open Source Project * * 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. */ //#define LOG_NDEBUG 0 #define LOG_TAG "FrameDropper_test" #include <utils/Log.h> #include <gtest/gtest.h> #include <media/stagefright/bqhelper/FrameDropper.h> #include <media/stagefright/foundation/ADebug.h> namespace android { struct TestFrame { int64_t timeUs; bool shouldDrop; }; static const TestFrame testFrames20Fps[] = { {1000000, false}, {1050000, false}, {1100000, false}, {1150000, false}, {1200000, false}, {1250000, false}, {1300000, false}, {1350000, false}, {1400000, false}, {1450000, false}, {1500000, false}, {1550000, false}, {1600000, false}, {1650000, false}, {1700000, false}, {1750000, false}, {1800000, false}, {1850000, false}, {1900000, false}, {1950000, false}, }; static const TestFrame testFrames30Fps[] = { {1000000, false}, {1033333, false}, {1066667, false}, {1100000, false}, {1133333, false}, {1166667, false}, {1200000, false}, {1233333, false}, {1266667, false}, {1300000, false}, {1333333, false}, {1366667, false}, {1400000, false}, {1433333, false}, {1466667, false}, {1500000, false}, {1533333, false}, {1566667, false}, {1600000, false}, {1633333, false}, }; static const TestFrame testFrames40Fps[] = { {1000000, false}, {1025000, true}, {1050000, false}, {1075000, false}, {1100000, false}, {1125000, true}, {1150000, false}, {1175000, false}, {1200000, false}, {1225000, true}, {1250000, false}, {1275000, false}, {1300000, false}, {1325000, true}, {1350000, false}, {1375000, false}, {1400000, false}, {1425000, true}, {1450000, false}, {1475000, false}, }; static const TestFrame testFrames60Fps[] = { {1000000, false}, {1016667, true}, {1033333, false}, {1050000, true}, {1066667, false}, {1083333, true}, {1100000, false}, {1116667, true}, {1133333, false}, {1150000, true}, {1166667, false}, {1183333, true}, {1200000, false}, {1216667, true}, {1233333, false}, {1250000, true}, {1266667, false}, {1283333, true}, {1300000, false}, {1316667, true}, }; static const TestFrame testFramesVariableFps[] = { // 40fps {1000000, false}, {1025000, true}, {1050000, false}, {1075000, false}, {1100000, false}, {1125000, true}, {1150000, false}, {1175000, false}, {1200000, false}, {1225000, true}, {1250000, false}, {1275000, false}, {1300000, false}, {1325000, true}, {1350000, false}, {1375000, false}, {1400000, false}, {1425000, true}, {1450000, false}, {1475000, false}, // a timestamp jump plus switch to 20fps {2000000, false}, {2050000, false}, {2100000, false}, {2150000, false}, {2200000, false}, {2250000, false}, {2300000, false}, {2350000, false}, {2400000, false}, {2450000, false}, {2500000, false}, {2550000, false}, {2600000, false}, {2650000, false}, {2700000, false}, {2750000, false}, {2800000, false}, {2850000, false}, {2900000, false}, {2950000, false}, // 60fps {2966667, false}, {2983333, true}, {3000000, false}, {3016667, true}, {3033333, false}, {3050000, true}, {3066667, false}, {3083333, true}, {3100000, false}, {3116667, true}, {3133333, false}, {3150000, true}, {3166667, false}, {3183333, true}, {3200000, false}, {3216667, true}, {3233333, false}, {3250000, true}, {3266667, false}, {3283333, true}, }; static const int kMaxTestJitterUs = 2000; // return one of 1000, 0, -1000 as jitter. static int GetJitter(size_t i) { return (1 - (i % 3)) * (kMaxTestJitterUs / 2); } class FrameDropperTest : public ::testing::Test { public: FrameDropperTest() : mFrameDropper(new FrameDropper()) { EXPECT_EQ(OK, mFrameDropper->setMaxFrameRate(30.0)); } protected: void RunTest(const TestFrame* frames, size_t size) { for (size_t i = 0; i < size; ++i) { int jitter = GetJitter(i); int64_t testTimeUs = frames[i].timeUs + jitter; printf("time %lld, testTime %lld, jitter %d\n", (long long)frames[i].timeUs, (long long)testTimeUs, jitter); EXPECT_EQ(frames[i].shouldDrop, mFrameDropper->shouldDrop(testTimeUs)); } } sp<FrameDropper> mFrameDropper; }; TEST_F(FrameDropperTest, TestInvalidMaxFrameRate) { EXPECT_NE(OK, mFrameDropper->setMaxFrameRate(-1.0)); EXPECT_NE(OK, mFrameDropper->setMaxFrameRate(0)); } TEST_F(FrameDropperTest, Test20Fps) { RunTest(testFrames20Fps, ARRAY_SIZE(testFrames20Fps)); } TEST_F(FrameDropperTest, Test30Fps) { RunTest(testFrames30Fps, ARRAY_SIZE(testFrames30Fps)); } TEST_F(FrameDropperTest, Test40Fps) { RunTest(testFrames40Fps, ARRAY_SIZE(testFrames40Fps)); } TEST_F(FrameDropperTest, Test60Fps) { RunTest(testFrames60Fps, ARRAY_SIZE(testFrames60Fps)); } TEST_F(FrameDropperTest, TestVariableFps) { RunTest(testFramesVariableFps, ARRAY_SIZE(testFramesVariableFps)); } } // namespace android
39.311594
83
0.669124
dAck2cC2
55b25a0239354cae0ada76baeff1bf2929c866f4
894
cpp
C++
test/Splines/CubicSpline.cpp
kurocha/splines
00ba452d378f71b26bddbfe787f68dea6e6160ad
[ "MIT", "Unlicense" ]
null
null
null
test/Splines/CubicSpline.cpp
kurocha/splines
00ba452d378f71b26bddbfe787f68dea6e6160ad
[ "MIT", "Unlicense" ]
null
null
null
test/Splines/CubicSpline.cpp
kurocha/splines
00ba452d378f71b26bddbfe787f68dea6e6160ad
[ "MIT", "Unlicense" ]
null
null
null
// // CubicSpline.cpp // This file is part of the "Splines" project and released under the MIT License. // // Created by Samuel Williams on 10/6/2020. // Copyright, 2020, by Samuel Williams. All rights reserved. // #include <UnitTest/UnitTest.hpp> #include <Splines/Polyline.hpp> #include <Splines/CubicSpline.hpp> namespace Splines { using namespace UnitTest::Expectations; UnitTest::Suite CubicSplineTestSuite { "Splines::CubicSpline", {"it can generate cubic points on the spline", [](UnitTest::Examiner & examiner) { using Point = Polyline<2>::Point; Polyline<2> polyline({ {0, 0}, {1, 0.5}, {2, 2}, {3, 1.5} }); CubicSpline spline(polyline); examiner.expect(spline[0]).to(be == Point{0, 0}); examiner.expect(spline[0.5]).to(be == Point{1.5, 1.375}); examiner.expect(spline[1.0]).to(be == Point{3, 1.5}); } }, }; }
23.526316
82
0.639821
kurocha
55b76686d2c928ea2465254237daae3e07052cb0
4,855
cpp
C++
test/ShrinkableTests.cpp
bgn9000/rapidcheck
593ada72f6938221973bf30bf7a7f7e6a24160de
[ "BSD-2-Clause" ]
null
null
null
test/ShrinkableTests.cpp
bgn9000/rapidcheck
593ada72f6938221973bf30bf7a7f7e6a24160de
[ "BSD-2-Clause" ]
1
2018-08-20T19:04:31.000Z
2018-08-20T19:04:31.000Z
test/ShrinkableTests.cpp
bantamtools/rapidcheck
4187d901e786b1d89ab30e6b72ac1c0fc3d902cf
[ "BSD-2-Clause" ]
1
2019-03-05T13:52:28.000Z
2019-03-05T13:52:28.000Z
#include <catch.hpp> #include <rapidcheck/catch.h> #include "rapidcheck/Shrinkable.h" #include "rapidcheck/shrinkable/Create.h" #include "util/TemplateProps.h" #include "util/Logger.h" #include "util/Generators.h" #include "util/DestructNotifier.h" using namespace rc; using namespace rc::test; namespace { template <typename ValueCallable, typename ShrinksCallable> class MockShrinkableImpl { public: MockShrinkableImpl(ValueCallable value, ShrinksCallable shrinks) : m_value(value) , m_shrinks(shrinks) {} typename std::result_of<ValueCallable()>::type value() const { return m_value(); } typename std::result_of<ShrinksCallable()>::type shrinks() const { return m_shrinks(); } private: ValueCallable m_value; ShrinksCallable m_shrinks; }; template <typename ValueCallable, typename ShrinksCallable> Shrinkable<Decay<typename std::result_of<ValueCallable()>::type>> makeMockShrinkable(ValueCallable value, ShrinksCallable shrinks) { return makeShrinkable<MockShrinkableImpl<ValueCallable, ShrinksCallable>>( value, shrinks); } class LoggingShrinkableImpl : public Logger { public: using IdLogPair = std::pair<std::string, std::vector<std::string>>; LoggingShrinkableImpl() : Logger() {} LoggingShrinkableImpl(std::string theId) : Logger(std::move(theId)) {} IdLogPair value() const { return {id, log}; } Seq<Shrinkable<IdLogPair>> shrinks() const { return Seq<Shrinkable<IdLogPair>>(); } }; using LoggingShrinkable = Shrinkable<std::pair<std::string, std::vector<std::string>>>; } // namespace TEST_CASE("Shrinkable") { SECTION("calls value() of the implementation object") { bool valueCalled = false; Shrinkable<int> shrinkable = makeMockShrinkable( [&] { valueCalled = true; return 1337; }, [] { return Seq<Shrinkable<int>>(); }); REQUIRE(shrinkable.value() == 1337); REQUIRE(valueCalled); } SECTION("calls shrinks() of the implementation object") { Shrinkable<int> shrink = makeMockShrinkable( [] { return 123; }, [] { return Seq<Shrinkable<int>>(); }); auto shrinks = seq::just(shrink); bool shrinksCalled = false; Shrinkable<int> shrinkable = makeMockShrinkable([] { return 0; }, [&] { shrinksCalled = true; return shrinks; }); REQUIRE(shrinkable.shrinks() == shrinks); REQUIRE(shrinksCalled); } SECTION("self assignment leaves value unchanged") { const auto shrinkable = shrinkable::just(13, seq::just(shrinkable::just(37))); auto x = shrinkable; x = x; REQUIRE(x == shrinkable); } SECTION("if shrinks() throws, an empty Seq is returned") { Shrinkable<int> shrinkable = makeMockShrinkable( [] { return 0; }, []() -> Seq<Shrinkable<int>> { throw std::string("foobar"); }); REQUIRE(!shrinkable.shrinks().next()); } SECTION("retains implementation object until no copies remain") { std::vector<std::string> log; Maybe<Shrinkable<DestructNotifier>> s1 = shrinkable::just(DestructNotifier("foobar", &log)); REQUIRE(log.empty()); Maybe<Shrinkable<DestructNotifier>> s2 = s1; REQUIRE(log.empty()); s1.reset(); REQUIRE(log.empty()); s2.reset(); REQUIRE(log.size() == 1); REQUIRE(log[0] == "foobar"); } SECTION("moving steals reference") { std::vector<std::string> log; auto s1 = shrinkable::just(DestructNotifier("foobar", &log)); { const auto s2 = std::move(s1); REQUIRE(log.empty()); } REQUIRE(log.size() == 1); REQUIRE(log[0] == "foobar"); } SECTION("operator==/operator!=") { propConformsToEquals<Shrinkable<int>>(); prop("different values yield inequal shrinkables", [](Seq<Shrinkable<int>> shrinks, int v1) { int v2 = *gen::distinctFrom(v1); RC_ASSERT(shrinkable::just(v1, shrinks) != shrinkable::just(v2, shrinks)); }); prop("different shrinks yield inequal shrinkables", [](int value, Seq<Shrinkable<int>> shrinks1) { Seq<Shrinkable<int>> shrinks2 = *gen::distinctFrom(shrinks1); RC_ASSERT(shrinkable::just(value, shrinks1) != shrinkable::just(value, shrinks2)); }); } SECTION("makeShrinkable") { SECTION("constructs implementation object in place") { auto shrinkable = makeShrinkable<LoggingShrinkableImpl>("foobar"); const auto value = shrinkable.value(); REQUIRE(value.first == "foobar"); std::vector<std::string> expectedLog{"constructed as foobar"}; REQUIRE(value.second == expectedLog); } } }
28.727811
76
0.621833
bgn9000
55ba5744f76d9ebb9e6f6cad90f4a1a37c2d3da7
141
cpp
C++
tests/concepts/concepts_test.cpp
JonathanCline/SAELib
8f9dca373b360e0fc91430ec6f18cf036ae69e2a
[ "MIT" ]
null
null
null
tests/concepts/concepts_test.cpp
JonathanCline/SAELib
8f9dca373b360e0fc91430ec6f18cf036ae69e2a
[ "MIT" ]
null
null
null
tests/concepts/concepts_test.cpp
JonathanCline/SAELib
8f9dca373b360e0fc91430ec6f18cf036ae69e2a
[ "MIT" ]
null
null
null
#define SAELIB_CXX_STANDARD 17 #include <SAELib/type_traits.h> #include <SAELib/concepts.h> #include <string> int main() { return 0; };
10.846154
31
0.716312
JonathanCline
55c0b69111e9e950971b5a7926d740e68d4d8a3d
7,917
cpp
C++
tst/math/uinterp.cpp
transpixel/TPQZcam
b44a97d44b49e9aa76c36efb6e4102091ff36c67
[ "MIT" ]
1
2017-06-01T00:21:16.000Z
2017-06-01T00:21:16.000Z
tst/math/uinterp.cpp
transpixel/TPQZcam
b44a97d44b49e9aa76c36efb6e4102091ff36c67
[ "MIT" ]
3
2017-06-01T00:26:16.000Z
2020-05-09T21:06:27.000Z
testmath/uinterp.cpp
transpixel/tpqz
2d8400b1be03292d0c5ab74710b87e798ae6c52c
[ "MIT" ]
null
null
null
// // // MIT License // // Copyright (c) 2017 Stellacore Corporation. // // 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 \brief This file contains unit test for math::interp */ #include "libmath/interp.h" #include "libdat/dat.h" #include "libio/stream.h" #include <cassert> #include <cmath> #include <functional> #include <iomanip> #include <iostream> #include <sstream> #include <string> namespace { //! Check basic 'fraction' functions.... std::string math_interp_test1a () { std::ostringstream oss; // synthesize linear data std::pair<double, double> range(-3., 7.); double const expValue(4.); double const expFrac(7./10.); // evaluate functions double const gotFrac(math::interp::fractionAtValid(expValue, range)); double const gotValue(math::interp::valueAtValid(expFrac, range)); // check results double const dFrac(gotFrac - expFrac); if (! (std::abs(dFrac) < math::eps)) { oss << "Failure of gotFrac test" << std::endl; oss << "expFrac: " << expFrac << std::endl; oss << "gotFrac: " << gotFrac << std::endl; } double const dX(gotValue - expValue); if (! (std::abs(dX) < math::eps)) { oss << "Failure of gotValue test" << std::endl; oss << "expValue: " << expValue << std::endl; oss << "gotValue: " << gotValue << std::endl; } return oss.str(); } //! Check linear interpolation std::string math_interp_test1b () { std::ostringstream oss; // synthesize linear data std::pair<double, double> xRange(-3., 7.); std::pair<double, double> yRange(17., 11.); double const expX(4.); // two-point formula for a line as check std::function<double(double const &)> const line ( [xRange, yRange] ( double const & xval) { double const dy(yRange.second - yRange.first); double const dx(xRange.second - xRange.first); return ((dy/dx) * (xval - xRange.first) + yRange.first); } ); // evaluate functions double const gotY(math::interp::linear(xRange, expX, yRange)); // check results double const expY(line(expX)); double const dY(gotY - expY); if (! (std::abs(dY) < math::eps)) { oss << "Failure of gotY test" << std::endl; oss << "expY: " << expY << std::endl; oss << "gotY: " << gotY << std::endl; } return oss.str(); } //! evaluate interpolated array value template <typename Value> void testArray ( std::ostream & oss , double const & subNdx , Value const & expValue , std::vector<Value> const & values , std::string const & tname , Value const & tolValue = dat::smallValue<Value>() ) { Value const gotValue (math::interp::linear<Value>(subNdx, values)); Value difValue(dat::nullValue<Value>()); bool haveError(false); if (dat::isValid(expValue)) { // case for expecting a valid expValue haveError= (! dat::nearlyEquals(gotValue, expValue, tolValue)); difValue = (gotValue - expValue); } else { // case for expecting bad value haveError = dat::isValid(gotValue); } if (haveError) { oss << "Failure of " << tname << " array test" << std::endl; oss << "exp: " << expValue << std::endl; oss << "got: " << gotValue << std::endl; oss << "dif: " << difValue << std::endl; oss << "tol: " << tolValue << std::endl; } } //! Check linear array interpolation std::string math_interp_test2 () { std::ostringstream oss; double const expNull(dat::nullValue<double>()); // check 'empty' case { std::vector<double> const values; testArray(oss, 0., expNull, values, "empty"); } // check degenerate case { double const datValue(-19.); std::vector<double> const values{ datValue }; testArray(oss, 0., datValue, values, "at one value"); testArray(oss, .5, expNull, values, "one value .5"); testArray(oss, 1., expNull, values, "one value 1."); testArray(oss, 2., expNull, values, "one value 2."); } // check general case { std::vector<double> const values{{ 0., 100., 200., 300., 400. }}; testArray(oss, .00, 0., values, ".000"); testArray(oss, .25, 25., values, ".250"); testArray(oss, .50, 50., values, ".500"); testArray(oss, .75, 75., values, ".750"); testArray(oss, 3.00, 300., values, "3.000"); // check 'open' end condition double const ep(8.*std::numeric_limits<double>::epsilon()); testArray(oss, 4.-ep, 400.-ep, values, "4.-ep", 400.*ep); testArray(oss, 4.000, expNull, values, "4.000"); testArray(oss, 4.+ep, expNull, values, "4.+ep"); } return oss.str(); } //! Check bi-directional interpolation std::string math_interp_test3 () { std::ostringstream oss; std::pair<double, double> const rangeInc{ 1., 2. }; std::pair<double, double> const rangeDec{ 2., 1. }; constexpr double outMin{ 1000. }; constexpr double outSpan{ 100. }; std::pair<double, double> const outRange{ outMin, outMin + outSpan }; constexpr double inVal{ 1.75 }; constexpr double expInc{ .75*outSpan + outMin }; constexpr double expDec{ .25*outSpan + outMin }; double const gotInc{ math::interp::linear(rangeInc, inVal, outRange) }; double const gotDec{ math::interp::linear(rangeDec, inVal, outRange) }; if (! dat::nearlyEquals(gotInc, expInc)) { oss << "Failure of increasing range test" << std::endl; } if (! dat::nearlyEquals(gotDec, expDec)) { oss << "Failure of decreasing range test" << std::endl; } return oss.str(); } //! Check 2D interpolations std::string math_interp_test4 () { std::ostringstream oss; dat::Range<double> const fromX( 10., 15.); dat::Range<double> const intoX( 100., 150.); dat::Range<double> const fromY( 20., 25.); dat::Range<double> const intoY(-200., 0.); dat::Area<double> const fromArea{ fromX, fromY }; dat::Area<double> const intoArea{ intoX, intoY }; dat::Spot const expFromSpot{{ 11., 22. }}; dat::Spot const expIntoSpot{{ 110., -120. }}; dat::Spot const gotIntoSpot (math::interp::linear(fromArea, expFromSpot, intoArea)); dat::Spot const gotFromSpot (math::interp::linear(intoArea, expIntoSpot, fromArea)); if (! dat::nearlyEquals(gotIntoSpot, expIntoSpot)) { oss << "Failure of Into test" << std::endl; oss << dat::infoString(expIntoSpot, "expIntoSpot") << std::endl; oss << dat::infoString(gotIntoSpot, "gotIntoSpot") << std::endl; } if (! dat::nearlyEquals(gotFromSpot, expFromSpot)) { oss << "Failure of From test" << std::endl; oss << dat::infoString(expFromSpot, "expFromSpot") << std::endl; oss << dat::infoString(gotFromSpot, "gotFromSpot") << std::endl; } return oss.str(); } } //! Unit test for math::interp int main ( int const /*argc*/ , char const * const * const /*argv*/ ) { std::ostringstream oss; // run tests oss << math_interp_test1a(); oss << math_interp_test1b(); oss << math_interp_test2(); oss << math_interp_test3(); oss << math_interp_test4(); // check/report results std::string const errMessages(oss.str()); if (! errMessages.empty()) { io::err() << errMessages << std::endl; return 1; } return 0; }
25.872549
72
0.660477
transpixel
55c2026bada5e5cb8dca1b69175584ce05d77e69
13,358
cpp
C++
src/cascadia/LocalTests_TerminalApp/ColorSchemeTests.cpp
lifeng1983/Terminal
1d35e180fdaacef731886bdb2cabca2ea4fe2b49
[ "MIT" ]
2
2020-07-26T17:01:47.000Z
2020-09-09T00:03:12.000Z
src/cascadia/LocalTests_TerminalApp/ColorSchemeTests.cpp
lifeng1983/Terminal
1d35e180fdaacef731886bdb2cabca2ea4fe2b49
[ "MIT" ]
1
2020-06-05T17:10:22.000Z
2020-06-05T17:10:22.000Z
src/cascadia/LocalTests_TerminalApp/ColorSchemeTests.cpp
lifeng1983/Terminal
1d35e180fdaacef731886bdb2cabca2ea4fe2b49
[ "MIT" ]
2
2020-05-13T16:56:46.000Z
2021-03-01T03:00:07.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #include "pch.h" #include "../TerminalApp/ColorScheme.h" #include "../TerminalApp/CascadiaSettings.h" #include "JsonTestClass.h" using namespace Microsoft::Console; using namespace TerminalApp; using namespace WEX::Logging; using namespace WEX::TestExecution; using namespace WEX::Common; namespace TerminalAppLocalTests { // TODO:microsoft/terminal#3838: // Unfortunately, these tests _WILL NOT_ work in our CI. We're waiting for // an updated TAEF that will let us install framework packages when the test // package is deployed. Until then, these tests won't deploy in CI. class ColorSchemeTests : public JsonTestClass { // Use a custom AppxManifest to ensure that we can activate winrt types // from our test. This property will tell taef to manually use this as // the AppxManifest for this test class. // This does not yet work for anything XAML-y. See TabTests.cpp for more // details on that. BEGIN_TEST_CLASS(ColorSchemeTests) TEST_CLASS_PROPERTY(L"RunAs", L"UAP") TEST_CLASS_PROPERTY(L"UAP:AppXManifest", L"TestHostAppXManifest.xml") END_TEST_CLASS() TEST_METHOD(CanLayerColorScheme); TEST_METHOD(LayerColorSchemeProperties); TEST_METHOD(LayerColorSchemesOnArray); TEST_CLASS_SETUP(ClassSetup) { InitializeJsonReader(); return true; } }; void ColorSchemeTests::CanLayerColorScheme() { const std::string scheme0String{ R"({ "name": "scheme0", "foreground": "#000000", "background": "#010101" })" }; const std::string scheme1String{ R"({ "name": "scheme1", "foreground": "#020202", "background": "#030303" })" }; const std::string scheme2String{ R"({ "name": "scheme0", "foreground": "#040404", "background": "#050505" })" }; const std::string scheme3String{ R"({ // "name": "scheme3", "foreground": "#060606", "background": "#070707" })" }; const auto scheme0Json = VerifyParseSucceeded(scheme0String); const auto scheme1Json = VerifyParseSucceeded(scheme1String); const auto scheme2Json = VerifyParseSucceeded(scheme2String); const auto scheme3Json = VerifyParseSucceeded(scheme3String); const auto scheme0 = ColorScheme::FromJson(scheme0Json); VERIFY_IS_TRUE(scheme0.ShouldBeLayered(scheme0Json)); VERIFY_IS_FALSE(scheme0.ShouldBeLayered(scheme1Json)); VERIFY_IS_TRUE(scheme0.ShouldBeLayered(scheme2Json)); VERIFY_IS_FALSE(scheme0.ShouldBeLayered(scheme3Json)); const auto scheme1 = ColorScheme::FromJson(scheme1Json); VERIFY_IS_FALSE(scheme1.ShouldBeLayered(scheme0Json)); VERIFY_IS_TRUE(scheme1.ShouldBeLayered(scheme1Json)); VERIFY_IS_FALSE(scheme1.ShouldBeLayered(scheme2Json)); VERIFY_IS_FALSE(scheme1.ShouldBeLayered(scheme3Json)); const auto scheme3 = ColorScheme::FromJson(scheme3Json); VERIFY_IS_FALSE(scheme3.ShouldBeLayered(scheme0Json)); VERIFY_IS_FALSE(scheme3.ShouldBeLayered(scheme1Json)); VERIFY_IS_FALSE(scheme3.ShouldBeLayered(scheme2Json)); VERIFY_IS_FALSE(scheme3.ShouldBeLayered(scheme3Json)); } void ColorSchemeTests::LayerColorSchemeProperties() { const std::string scheme0String{ R"({ "name": "scheme0", "foreground": "#000000", "background": "#010101", "selectionBackground": "#010100", "cursorColor": "#010001", "red": "#010000", "green": "#000100", "blue": "#000001" })" }; const std::string scheme1String{ R"({ "name": "scheme1", "foreground": "#020202", "background": "#030303", "selectionBackground": "#020200", "cursorColor": "#040004", "red": "#020000", "blue": "#000002" })" }; const std::string scheme2String{ R"({ "name": "scheme0", "foreground": "#040404", "background": "#050505", "selectionBackground": "#030300", "cursorColor": "#060006", "red": "#030000", "green": "#000300" })" }; const auto scheme0Json = VerifyParseSucceeded(scheme0String); const auto scheme1Json = VerifyParseSucceeded(scheme1String); const auto scheme2Json = VerifyParseSucceeded(scheme2String); auto scheme0 = ColorScheme::FromJson(scheme0Json); VERIFY_ARE_EQUAL(L"scheme0", scheme0._schemeName); VERIFY_ARE_EQUAL(ARGB(0, 0, 0, 0), scheme0._defaultForeground); VERIFY_ARE_EQUAL(ARGB(0, 1, 1, 1), scheme0._defaultBackground); VERIFY_ARE_EQUAL(ARGB(0, 1, 1, 0), scheme0._selectionBackground); VERIFY_ARE_EQUAL(ARGB(0, 1, 0, 1), scheme0._cursorColor); VERIFY_ARE_EQUAL(ARGB(0, 1, 0, 0), scheme0._table[XTERM_RED_ATTR]); VERIFY_ARE_EQUAL(ARGB(0, 0, 1, 0), scheme0._table[XTERM_GREEN_ATTR]); VERIFY_ARE_EQUAL(ARGB(0, 0, 0, 1), scheme0._table[XTERM_BLUE_ATTR]); Log::Comment(NoThrowString().Format( L"Layering scheme1 on top of scheme0")); scheme0.LayerJson(scheme1Json); VERIFY_ARE_EQUAL(ARGB(0, 2, 2, 2), scheme0._defaultForeground); VERIFY_ARE_EQUAL(ARGB(0, 3, 3, 3), scheme0._defaultBackground); VERIFY_ARE_EQUAL(ARGB(0, 2, 2, 0), scheme0._selectionBackground); VERIFY_ARE_EQUAL(ARGB(0, 4, 0, 4), scheme0._cursorColor); VERIFY_ARE_EQUAL(ARGB(0, 2, 0, 0), scheme0._table[XTERM_RED_ATTR]); VERIFY_ARE_EQUAL(ARGB(0, 0, 1, 0), scheme0._table[XTERM_GREEN_ATTR]); VERIFY_ARE_EQUAL(ARGB(0, 0, 0, 2), scheme0._table[XTERM_BLUE_ATTR]); Log::Comment(NoThrowString().Format( L"Layering scheme2Json on top of (scheme0+scheme1)")); scheme0.LayerJson(scheme2Json); VERIFY_ARE_EQUAL(ARGB(0, 4, 4, 4), scheme0._defaultForeground); VERIFY_ARE_EQUAL(ARGB(0, 5, 5, 5), scheme0._defaultBackground); VERIFY_ARE_EQUAL(ARGB(0, 3, 3, 0), scheme0._selectionBackground); VERIFY_ARE_EQUAL(ARGB(0, 6, 0, 6), scheme0._cursorColor); VERIFY_ARE_EQUAL(ARGB(0, 3, 0, 0), scheme0._table[XTERM_RED_ATTR]); VERIFY_ARE_EQUAL(ARGB(0, 0, 3, 0), scheme0._table[XTERM_GREEN_ATTR]); VERIFY_ARE_EQUAL(ARGB(0, 0, 0, 2), scheme0._table[XTERM_BLUE_ATTR]); } void ColorSchemeTests::LayerColorSchemesOnArray() { const std::string scheme0String{ R"({ "name": "scheme0", "foreground": "#000000", "background": "#010101" })" }; const std::string scheme1String{ R"({ "name": "scheme1", "foreground": "#020202", "background": "#030303" })" }; const std::string scheme2String{ R"({ "name": "scheme0", "foreground": "#040404", "background": "#050505" })" }; const std::string scheme3String{ R"({ // by not providing a name, the scheme will have the name "" "foreground": "#060606", "background": "#070707" })" }; const auto scheme0Json = VerifyParseSucceeded(scheme0String); const auto scheme1Json = VerifyParseSucceeded(scheme1String); const auto scheme2Json = VerifyParseSucceeded(scheme2String); const auto scheme3Json = VerifyParseSucceeded(scheme3String); CascadiaSettings settings; VERIFY_ARE_EQUAL(0u, settings._globals.GetColorSchemes().size()); VERIFY_IS_NULL(settings._FindMatchingColorScheme(scheme0Json)); VERIFY_IS_NULL(settings._FindMatchingColorScheme(scheme1Json)); VERIFY_IS_NULL(settings._FindMatchingColorScheme(scheme2Json)); VERIFY_IS_NULL(settings._FindMatchingColorScheme(scheme3Json)); settings._LayerOrCreateColorScheme(scheme0Json); { for (auto& kv : settings._globals._colorSchemes) { Log::Comment(NoThrowString().Format( L"kv:%s->%s", kv.first.data(), kv.second.GetName().data())); } VERIFY_ARE_EQUAL(1u, settings._globals.GetColorSchemes().size()); VERIFY_IS_TRUE(settings._globals._colorSchemes.find(L"scheme0") != settings._globals._colorSchemes.end()); auto scheme0 = settings._globals._colorSchemes.find(L"scheme0")->second; VERIFY_IS_NOT_NULL(settings._FindMatchingColorScheme(scheme0Json)); VERIFY_IS_NULL(settings._FindMatchingColorScheme(scheme1Json)); VERIFY_IS_NOT_NULL(settings._FindMatchingColorScheme(scheme2Json)); VERIFY_IS_NULL(settings._FindMatchingColorScheme(scheme3Json)); VERIFY_ARE_EQUAL(ARGB(0, 0, 0, 0), scheme0._defaultForeground); VERIFY_ARE_EQUAL(ARGB(0, 1, 1, 1), scheme0._defaultBackground); } settings._LayerOrCreateColorScheme(scheme1Json); { VERIFY_ARE_EQUAL(2u, settings._globals.GetColorSchemes().size()); VERIFY_IS_TRUE(settings._globals._colorSchemes.find(L"scheme0") != settings._globals._colorSchemes.end()); auto scheme0 = settings._globals._colorSchemes.find(L"scheme0")->second; VERIFY_IS_TRUE(settings._globals._colorSchemes.find(L"scheme1") != settings._globals._colorSchemes.end()); auto scheme1 = settings._globals._colorSchemes.find(L"scheme1")->second; VERIFY_IS_NOT_NULL(settings._FindMatchingColorScheme(scheme0Json)); VERIFY_IS_NOT_NULL(settings._FindMatchingColorScheme(scheme1Json)); VERIFY_IS_NOT_NULL(settings._FindMatchingColorScheme(scheme2Json)); VERIFY_IS_NULL(settings._FindMatchingColorScheme(scheme3Json)); VERIFY_ARE_EQUAL(ARGB(0, 0, 0, 0), scheme0._defaultForeground); VERIFY_ARE_EQUAL(ARGB(0, 1, 1, 1), scheme0._defaultBackground); VERIFY_ARE_EQUAL(ARGB(0, 2, 2, 2), scheme1._defaultForeground); VERIFY_ARE_EQUAL(ARGB(0, 3, 3, 3), scheme1._defaultBackground); } settings._LayerOrCreateColorScheme(scheme2Json); { VERIFY_ARE_EQUAL(2u, settings._globals.GetColorSchemes().size()); VERIFY_IS_TRUE(settings._globals._colorSchemes.find(L"scheme0") != settings._globals._colorSchemes.end()); auto scheme0 = settings._globals._colorSchemes.find(L"scheme0")->second; VERIFY_IS_TRUE(settings._globals._colorSchemes.find(L"scheme1") != settings._globals._colorSchemes.end()); auto scheme1 = settings._globals._colorSchemes.find(L"scheme1")->second; VERIFY_IS_NOT_NULL(settings._FindMatchingColorScheme(scheme0Json)); VERIFY_IS_NOT_NULL(settings._FindMatchingColorScheme(scheme1Json)); VERIFY_IS_NOT_NULL(settings._FindMatchingColorScheme(scheme2Json)); VERIFY_IS_NULL(settings._FindMatchingColorScheme(scheme3Json)); VERIFY_ARE_EQUAL(ARGB(0, 4, 4, 4), scheme0._defaultForeground); VERIFY_ARE_EQUAL(ARGB(0, 5, 5, 5), scheme0._defaultBackground); VERIFY_ARE_EQUAL(ARGB(0, 2, 2, 2), scheme1._defaultForeground); VERIFY_ARE_EQUAL(ARGB(0, 3, 3, 3), scheme1._defaultBackground); } settings._LayerOrCreateColorScheme(scheme3Json); { VERIFY_ARE_EQUAL(3u, settings._globals.GetColorSchemes().size()); VERIFY_IS_TRUE(settings._globals._colorSchemes.find(L"scheme0") != settings._globals._colorSchemes.end()); auto scheme0 = settings._globals._colorSchemes.find(L"scheme0")->second; VERIFY_IS_TRUE(settings._globals._colorSchemes.find(L"scheme1") != settings._globals._colorSchemes.end()); auto scheme1 = settings._globals._colorSchemes.find(L"scheme1")->second; VERIFY_IS_TRUE(settings._globals._colorSchemes.find(L"") != settings._globals._colorSchemes.end()); auto scheme2 = settings._globals._colorSchemes.find(L"")->second; VERIFY_IS_NOT_NULL(settings._FindMatchingColorScheme(scheme0Json)); VERIFY_IS_NOT_NULL(settings._FindMatchingColorScheme(scheme1Json)); VERIFY_IS_NOT_NULL(settings._FindMatchingColorScheme(scheme2Json)); VERIFY_IS_NULL(settings._FindMatchingColorScheme(scheme3Json)); VERIFY_ARE_EQUAL(ARGB(0, 4, 4, 4), scheme0._defaultForeground); VERIFY_ARE_EQUAL(ARGB(0, 5, 5, 5), scheme0._defaultBackground); VERIFY_ARE_EQUAL(ARGB(0, 2, 2, 2), scheme1._defaultForeground); VERIFY_ARE_EQUAL(ARGB(0, 3, 3, 3), scheme1._defaultBackground); VERIFY_ARE_EQUAL(ARGB(0, 6, 6, 6), scheme2._defaultForeground); VERIFY_ARE_EQUAL(ARGB(0, 7, 7, 7), scheme2._defaultBackground); } } }
46.706294
119
0.634227
lifeng1983
55c6cc29c297c970a4ee57d4a59af2745c9e502e
1,051
cpp
C++
lib/Runtime/PlatformAgnostic/Platform/Linux/SystemInfo.cpp
rekhadpr/demoazure1
394d777e507b171876734d871d50e47254636b9d
[ "MIT" ]
null
null
null
lib/Runtime/PlatformAgnostic/Platform/Linux/SystemInfo.cpp
rekhadpr/demoazure1
394d777e507b171876734d871d50e47254636b9d
[ "MIT" ]
null
null
null
lib/Runtime/PlatformAgnostic/Platform/Linux/SystemInfo.cpp
rekhadpr/demoazure1
394d777e507b171876734d871d50e47254636b9d
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include "Common.h" #include "ChakraPlatform.h" #include <sys/sysinfo.h> #include <sys/resource.h> namespace PlatformAgnostic { SystemInfo::PlatformData SystemInfo::data; SystemInfo::PlatformData::PlatformData() { struct sysinfo systemInfo; if (sysinfo(&systemInfo) == -1) { totalRam = 0; } else { totalRam = systemInfo.totalram; } } bool SystemInfo::GetMaxVirtualMemory(size_t *totalAS) { struct rlimit limit; if (getrlimit(RLIMIT_AS, &limit) != 0) { return false; } *totalAS = limit.rlim_cur; return true; } }
26.948718
105
0.475737
rekhadpr
55cc0c1dd1cc978931b0dda824d09f86e42f25b8
772
cpp
C++
src/analyzers/tokenizers/character_tokenizer.cpp
Lolik111/meta
c7019401185cdfa15e1193aad821894c35a83e3f
[ "MIT" ]
615
2015-01-31T17:14:03.000Z
2022-03-27T03:03:02.000Z
src/analyzers/tokenizers/character_tokenizer.cpp
Lolik111/meta
c7019401185cdfa15e1193aad821894c35a83e3f
[ "MIT" ]
167
2015-01-20T17:48:16.000Z
2021-12-20T00:15:29.000Z
src/analyzers/tokenizers/character_tokenizer.cpp
Lolik111/meta
c7019401185cdfa15e1193aad821894c35a83e3f
[ "MIT" ]
264
2015-01-30T00:08:01.000Z
2022-03-02T17:19:11.000Z
/** * @file character_tokenizer.cpp * @author Chase Geigle */ #include "meta/analyzers/tokenizers/character_tokenizer.h" #include "meta/corpus/document.h" #include "meta/io/mmap_file.h" namespace meta { namespace analyzers { namespace tokenizers { const util::string_view character_tokenizer::id = "character-tokenizer"; character_tokenizer::character_tokenizer() : idx_{0} { // nothing } void character_tokenizer::set_content(std::string&& content) { idx_ = 0; content_ = std::move(content); } std::string character_tokenizer::next() { if (!*this) throw token_stream_exception{"next() called with no tokens left"}; return {content_[idx_++]}; } character_tokenizer::operator bool() const { return idx_ < content_.size(); } } } }
17.155556
74
0.705959
Lolik111