hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
5da9227781eb96f71864d43896619633bcd7ce2b
725
hpp
C++
ProjectMajestic/Chunk.hpp
Edgaru089/ProjectMajestic
16cda6f86fd5ad02baedc9481609d6140cdda62a
[ "MIT" ]
1
2018-08-29T06:36:23.000Z
2018-08-29T06:36:23.000Z
ProjectMajestic/Chunk.hpp
Edgaru089/ProjectMajestic
16cda6f86fd5ad02baedc9481609d6140cdda62a
[ "MIT" ]
null
null
null
ProjectMajestic/Chunk.hpp
Edgaru089/ProjectMajestic
16cda6f86fd5ad02baedc9481609d6140cdda62a
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include "Main.hpp" #include "TextureManager.hpp" #include "Data.hpp" #include "Block.hpp" const int chunkSize = 16; class Chunk { public: friend class TerrainManager; ~Chunk(); void updateLogic(); void getRenderList(VertexArray & verts); void getLightMask(VertexArray& verts); void setChunkId(int x, int y); Vector2i getChunkId(); shared_ptr<Block> getBlock(Vector2i inChunkCoord); void setBlock(Vector2i inChunkCoord, shared_ptr<Block> block); void _resize(int width, int height); // First: pos(global coords); Second: strength map<Uuid, pair<Vector2i, int>> lightSources; vector<vector<shared_ptr<Block>>> blocks; vector<vector<int>> lightLevel; Vector2i id; };
18.125
63
0.736552
Edgaru089
5dad7dc4efc0d79571baeb86707000cbb1329e53
499
cpp
C++
0x7E9FB/hand file/Socket/Sockets.cpp
518651/0x7E9FB-Net-Project
ec6ad70aa8c0df1eaa318034b2513c6394d9fbe6
[ "MIT" ]
1
2022-02-28T02:57:30.000Z
2022-02-28T02:57:30.000Z
0x7E9FB/hand file/Socket/Sockets.cpp
518651/0x7E9FB-Net-Project
ec6ad70aa8c0df1eaa318034b2513c6394d9fbe6
[ "MIT" ]
null
null
null
0x7E9FB/hand file/Socket/Sockets.cpp
518651/0x7E9FB-Net-Project
ec6ad70aa8c0df1eaa318034b2513c6394d9fbe6
[ "MIT" ]
null
null
null
//#include "Sockets.h" #include "../../Un-main.h" bool GetSocketAddress(char* host, sockaddr_in* address) { struct addrinfo* result = NULL; struct addrinfo* ptr = NULL; struct addrinfo hints; ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; if (getaddrinfo(host, "http", &hints, &result)) return false; *address = *(sockaddr_in*)(result[0].ai_addr); freeaddrinfo(result); return true; }
24.95
63
0.687375
518651
5dadc621f94f523ed042108027e6464038868b02
1,826
cpp
C++
RegisterSystem/RegisterSystem/Register.cpp
vladislav-karamfilov/CPlusPlus-Playground
01827ed133b7033063f2859000c4c586acda910b
[ "MIT" ]
7
2016-02-13T05:47:50.000Z
2021-03-27T02:09:57.000Z
RegisterSystem/RegisterSystem/Register.cpp
vladislav-karamfilov/CPlusPlus-Playground
01827ed133b7033063f2859000c4c586acda910b
[ "MIT" ]
null
null
null
RegisterSystem/RegisterSystem/Register.cpp
vladislav-karamfilov/CPlusPlus-Playground
01827ed133b7033063f2859000c4c586acda910b
[ "MIT" ]
20
2016-02-08T05:44:02.000Z
2020-10-28T03:51:12.000Z
#include <iostream> #include <vector> #include <algorithm> #include "Register.h" #include "PeopleComparer.h" namespace RegisterSystem { using namespace std; Register::Register() { this->people = vector<Person*>(); } Register::~Register() { int peopleCount = this->people.size(); for (int i = 0; i < peopleCount; i++) { delete this->people[i]; } } void Register::AddPerson(Person* person) { if (person == NULL) { throw "Cannot add a null person in the register!"; } this->people.push_back(person); } void Register::RemovePerson(const char* ssn) { int searchedPersonIndex = -1; int peopleCount = this->people.size(); for (int i = 0; i < peopleCount; i++) { if (strcmp(this->people[i]->GetSsn(), ssn) == 0) { searchedPersonIndex = i; break; } } if (searchedPersonIndex >= 0) { this->people.erase(this->people.begin() + searchedPersonIndex); } } vector<Person*> Register::GetPeopleAlphabeticallyOrdered() { vector<Person*> alphabeticallyOrderedPeople = this->people; sort(alphabeticallyOrderedPeople.begin(), alphabeticallyOrderedPeople.end(), PeopleComparer()); return alphabeticallyOrderedPeople; } int Register::GetPeopleOnAddressCount(const char* address) { int peopleOnAddress = 0; int peopleCount = this->people.size(); for (int i = 0; i < peopleCount; i++) { if (strcmp(this->people[i]->GetAddress(), address)) { peopleCount++; } } return peopleCount; } ostream& operator << (ostream& output, const Register& peopleRegister) { int peopleCount = peopleRegister.people.size(); if (peopleCount > 0) { for (int i = 0; i < peopleCount; i++) { output << *peopleRegister.people[i] << endl; } } else { output << "No people in the register!" << endl; } return output; } }
18.824742
97
0.647864
vladislav-karamfilov
5dae506649ac8908d6e50a6c7f82b73af7cf6538
3,089
cpp
C++
Cpp/progs/ch03/customCC.cpp
ernestyalumni/CompPhys
1f5d7559146a14a21182653b77fd35e6d6829855
[ "Apache-2.0" ]
70
2017-07-24T04:09:27.000Z
2021-12-24T16:00:41.000Z
Cpp/progs/ch03/customCC.cpp
ernestyalumni/CompPhys
1f5d7559146a14a21182653b77fd35e6d6829855
[ "Apache-2.0" ]
3
2018-01-16T22:34:47.000Z
2019-01-29T22:37:10.000Z
Cpp/progs/ch03/customCC.cpp
ernestyalumni/CompPhys
1f5d7559146a14a21182653b77fd35e6d6829855
[ "Apache-2.0" ]
40
2017-01-24T19:18:42.000Z
2021-03-01T07:13:35.000Z
/* * cf. M. Hjorth-Jensen, Computational Physics, University of Oslo (2015) * http://www.mn.uio.no/fysikk/english/people/aca/mhjensen/ * Ernest Yeung (I typed it up and made modifications) * ernestyalumni@gmail.com * MIT License * cf. Chapter 3 Numerical differentiation and interpolation * 3.3 Classes in C++ * 3.3.1 The Complex class */ /* Example of program which uses our complex class To compile, do this (for example): $ g++ customCC.cpp complex.cpp I believe you need to include all the files you need, with complex.cpp containing the manually-crafted Complex class in the g++ command and you should be good to go! ./a.out */ #include <iostream> /* cout cin*/ #include <cmath> using namespace std; // include the complex numbers class #include "complex.h" int main() { /* This was Hjorth-Jensen's original code commented; it doesn't necessary work (out of the box)! Complex a(0.1,1.3); // we declare a complex variable a Complex b(3.0), c(5.0,-2.3); // we declare complex variables b and c Complex d = b; // we declare a new complex variable d cout << "d=" << d << ", a=" << a << ", b=" << b << endl; d = a*c + b/a; // we add, multiply and divide two complex numbers cout << "Re(d)=" << d.Re() << ", Im(d)=" << d.Im() << endl; // write out the real and imaginary parts */ Complex aa(0.1,1.3); // we declare a complex variable aa aa.print(); Complex bb(3.0), cc(5.0,-2.3); // we declare a complex variable bb and cc bb.print(); cc.print(); Complex dd = bb; // cout << "d=" << dd.print() << ", a=" << aa.print() << ", b=" << bb.print() << endl; /* You'll obtain this error message if you do the above cannot convert ‘dd.Complex::print()’ (type ‘void’) to type ‘const unsigned char*’ */ cout << "dd=" << endl; dd.print(); cout << "aa=" << endl; aa.print(); cout << "bb=" << endl; bb.print(); // dd = bb/aa ; // we add, multiply and divide 2 complex numbers // Complex tmp = aa*cc ; Once in the class definition in complex.cpp, using const, that // the operation overloading of + then was made into a lvalue and not a rvalue, then // it "acts the way it should". dd = bb/aa + aa*cc ; cout << "Re(dd)=" << dd.Re() << ", Im(dd) = " << dd.Im() << endl; // write out the real and imaginary parts // cf. http://bhattaca.github.io/cse2122/code/complex_main_cpp.html // a = 5 + 3i Complex a(5,3); cout << "Constructor with two values:\na = "; a.print(); // b = 3 - 4i Complex b(3,-4); cout << "b = "; b.print(); cout << endl; Complex c(4); cout << "Constructor with one value:\nc = "; c.print(); // c = a.add(b); c = a + b; cout << "\na + b = "; c.print(); Complex d; cout << "\nDefault constructor:\n d = "; d.print(); d = a - b; cout << "\na - b = "; d.print(); Complex e = a * b; cout << "\na * b = "; e.print(); Complex f = a / b; cout << "\na / b = "; f.print(); cout << "\nNorm of b: " << b.norm() << endl; Complex h = a.conj(); cout << "Complex conjugate of a = "; h.print(); return 0; }
26.62931
109
0.586921
ernestyalumni
5dae83510a21f412177fed4a4c7bcdab8c2d77d4
1,068
cpp
C++
debian/passenger-2.2.15/benchmark/ApplicationPool.cpp
brightbox/nginx-brightbox
cbb27b979ff8de2a6d3f57cebb214f0cde348d3f
[ "BSD-2-Clause" ]
4
2016-05-09T12:50:34.000Z
2020-10-08T07:28:46.000Z
benchmark/ApplicationPool.cpp
chad/passenger
74fb3cf821d5b5d5bae37e03ba7ccaffc13ce9d0
[ "MIT" ]
null
null
null
benchmark/ApplicationPool.cpp
chad/passenger
74fb3cf821d5b5d5bae37e03ba7ccaffc13ce9d0
[ "MIT" ]
1
2020-10-08T07:51:20.000Z
2020-10-08T07:51:20.000Z
//#define USE_SERVER #include <iostream> #include <boost/bind.hpp> #include <boost/thread.hpp> #ifdef USE_SERVER #include "ApplicationPoolServer.h" #else #include "StandardApplicationPool.h" #endif #include "Utils.h" #include "Logging.h" using namespace std; using namespace boost; using namespace Passenger; #define TRANSACTIONS 20000 #define CONCURRENCY 24 ApplicationPoolPtr pool; static void threadMain(unsigned int times) { for (unsigned int i = 0; i < times; i++) { Application::SessionPtr session(pool->get("test/stub/minimal-railsapp")); for (int x = 0; x < 200000; x++) { // Do nothing. } } } int main() { thread_group tg; #ifdef USE_SERVER ApplicationPoolServer server("ext/apache2/ApplicationPoolServerExecutable", "bin/passenger-spawn-server"); pool = server.connect(); #else pool = ptr(new StandardApplicationPool("bin/passenger-spawn-server")); #endif pool->setMax(6); for (int i = 0; i < CONCURRENCY; i++) { tg.create_thread(boost::bind(&threadMain, TRANSACTIONS / CONCURRENCY)); } tg.join_all(); return 0; }
20.150943
77
0.714419
brightbox
5db0bbdfba88122f208ca2ebbec62702bff460f5
13,180
cpp
C++
testsuite/core/file/TestCase_Core_File_Directory.cpp
caochunxi/llbc
2ff4af937f1635be67a7e24602d0a3e87c708ba7
[ "MIT" ]
83
2015-11-10T09:52:56.000Z
2022-01-12T11:53:01.000Z
testsuite/core/file/TestCase_Core_File_Directory.cpp
lailongwei/llbc
ec7e69bfa1f0afece8bb19dfa9a0a4578508a077
[ "MIT" ]
30
2017-09-30T07:43:20.000Z
2022-01-23T13:18:48.000Z
testsuite/core/file/TestCase_Core_File_Directory.cpp
caochunxi/llbc
2ff4af937f1635be67a7e24602d0a3e87c708ba7
[ "MIT" ]
34
2015-11-14T12:37:44.000Z
2021-12-16T02:38:36.000Z
// The MIT License (MIT) // Copyright (c) 2013 lailongwei<lailongwei@126.com> // // 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 "core/file/TestCase_Core_File_Directory.h" int TestCase_Core_File_Directory::Run(int argc, char *argv[]) { std::cout <<"core/file/Directory test:" <<std::endl; bool allTested = false; do { if (CurDirTest() != LLBC_OK) break; if (ExistsTest() != LLBC_OK) break; if (CreateRemoveTest() != LLBC_OK) break; if (AbsPathTest() != LLBC_OK) break; if (JoinTest() != LLBC_OK) break; if (SplitExtTest() != LLBC_OK) break; if (GetFilesTest() != LLBC_OK) break; if (GetDirectoriesTest() != LLBC_OK) break; if (ModuleFileTest() != LLBC_OK) break; if (DirNameBaseNameTest() != LLBC_OK) break; if (MiscTest() != LLBC_OK) break; allTested = true; } while(0); std::cout <<"All test done, press any key to exit..." <<std::endl; getchar(); return allTested ? LLBC_OK : LLBC_FAILED; } int TestCase_Core_File_Directory::CurDirTest() { LLBC_PrintLine("CurDir/SetCurDir test:"); #if LLBC_TARGET_PLATFORM_WIN32 const LLBC_String toPath = "C:\\"; #else const LLBC_String toPath = "/"; #endif const LLBC_String curDir = LLBC_Directory::CurDir(); LLBC_PrintLine("Current directory: %s", curDir.c_str()); LLBC_PrintLine("Set current directory To <%s>: ", toPath.c_str()); if (LLBC_Directory::SetCurDir(toPath) != LLBC_OK) { LLBC_PrintLine("Set current directory to <%s> failed, error: %s", toPath.c_str(), LLBC_FormatLastError()); return LLBC_FAILED; } LLBC_PrintLine("After set, current directory: %s", LLBC_Directory::CurDir().c_str()); LLBC_Directory::SetCurDir(curDir); LLBC_PrintLine(""); return LLBC_OK; } int TestCase_Core_File_Directory::ExistsTest() { LLBC_PrintLine("Exists test:"); LLBC_String path = "."; LLBC_PrintLine("%s exists? %d", path.c_str(), LLBC_Directory::Exists(path)); path = "~~~~~~~~"; LLBC_PrintLine("%s exists? %d", path.c_str(), LLBC_Directory::Exists(path)); path = LLBC_Directory::ModuleFileName(); LLBC_PrintLine("%s exists? %d", path.c_str(), LLBC_Directory::Exists(path)); LLBC_PrintLine(""); return LLBC_OK; } int TestCase_Core_File_Directory::CreateRemoveTest() { LLBC_PrintLine("Create/Remove test:"); LLBC_PrintLine("Create directory: a"); if (LLBC_Directory::Create("a") != LLBC_OK) { LLBC_PrintLine("Create directory a failed, error: %s", LLBC_FormatLastError()); return LLBC_FAILED; } for (int i = 0; i < 10; ++i) { const LLBC_String path = LLBC_String().format("a/b_%d", i); LLBC_PrintLine("Create directory: %s", path.c_str()); if (LLBC_Directory::Create(path) != LLBC_OK) { LLBC_PrintLine("Create directory %s failed, error: %s", path.c_str(), LLBC_FormatLastError()); return LLBC_FAILED; } } LLBC_PrintLine("Remove directory: a"); if (LLBC_Directory::Remove("a") != LLBC_OK) { LLBC_PrintLine("Remove directory a failed, error: %s", LLBC_FormatLastError()); return LLBC_FAILED; } // Complex path create/remove test. const LLBC_String complexPath = "a/b/c__d/d/add"; LLBC_PrintLine("Create directory: %s", complexPath.c_str()); if (LLBC_Directory::Create(complexPath) != LLBC_OK) { LLBC_PrintLine("Create directory %s faiiled, error: %s", complexPath.c_str(), LLBC_FormatLastError()); return LLBC_FAILED; } LLBC_PrintLine("Remove directory: %s", complexPath.c_str()); if (LLBC_Directory::Remove(complexPath) != LLBC_OK) { LLBC_PrintLine("Remove directory %s failed, error: %s", complexPath.c_str(), LLBC_FormatLastError()); return LLBC_FAILED; } LLBC_PrintLine(""); return LLBC_OK; } int TestCase_Core_File_Directory::AbsPathTest() { LLBC_PrintLine("AbsPath test:"); LLBC_String path = ""; LLBC_PrintLine("%s abspath: %s", path.c_str(), LLBC_Directory::AbsPath(path).c_str()); path = "."; LLBC_PrintLine("%s abspath: %s", path.c_str(), LLBC_Directory::AbsPath(path).c_str()); path = "/"; LLBC_PrintLine("%s abspath: %s", path.c_str(), LLBC_Directory::AbsPath(path).c_str()); #if LLBC_TARGET_PLATFORM_WIN32 path = "a/b\\c/..\\"; #else path = "a/b/c/../"; #endif LLBC_PrintLine("%s abspath: %s", path.c_str(), LLBC_Directory::AbsPath(path).c_str()); #if LLBC_TARGET_PLATFORM_WIN32 path = "c:\\"; LLBC_PrintLine("%s abspath: %s", path.c_str(), LLBC_Directory::AbsPath(path).c_str()); path = "c:\\windows\\.\\.\\..\\windows/././"; LLBC_PrintLine("%s abspath: %s", path.c_str(), LLBC_Directory::AbsPath(path).c_str()); #endif LLBC_PrintLine(""); return LLBC_OK; } int TestCase_Core_File_Directory::JoinTest() { LLBC_PrintLine("Join test:"); const auto p1 = LLBC_Directory::Join(LLBC_Directory::ModuleFileDir(), "test_prop.cfg"); const auto p2 = LLBC_Directory::Join(LLBC_Directory::ModuleFileDir(), "p1", "test_prop.cfg"); const auto p3 = LLBC_Directory::Join(LLBC_Directory::ModuleFileDir(), "p1", "p2", "test_prop.cfg"); LLBC_PrintLine("P1 Done, Result: %s", p1.c_str()); LLBC_PrintLine("P2 Done, Result: %s", p2.c_str()); LLBC_PrintLine("P3 Done, Result: %s", p3.c_str()); LLBC_Strings parts; parts.push_back("a"), parts.push_back("b"), parts.push_back("c"), JoinTest(parts); parts.clear(), parts.push_back("a/"), parts.push_back("b"), JoinTest(parts); parts.clear(), parts.push_back("a"), parts.push_back("/b"), JoinTest(parts); parts.clear(), parts.push_back("a/"), parts.push_back("/b/"), JoinTest(parts); #if LLBC_TARGET_PLATFORM_WIN32 parts.clear(), parts.push_back("c:\\"), parts.push_back("/b"), JoinTest(parts); #endif return LLBC_OK; } int TestCase_Core_File_Directory::SplitExtTest() { LLBC_PrintLine("SplitExt test:"); LLBC_String path("a/b"); LLBC_Strings parts = LLBC_Directory::SplitExt(path); LLBC_PrintLine("Split %s: part1: [%s], part2: [%s]", path.c_str(), parts[0].c_str(), parts[1].c_str()); path = ("a.exe/b"); parts = LLBC_Directory::SplitExt(path); LLBC_PrintLine("Split %s: part1: [%s], part2: [%s]", path.c_str(), parts[0].c_str(), parts[1].c_str()); path = ("a.exe/b.exe"); parts = LLBC_Directory::SplitExt(path); LLBC_PrintLine("Split %s: part1: [%s], part2: [%s]", path.c_str(), parts[0].c_str(), parts[1].c_str()); path = ("a.exe/b.exe.bk"); parts = LLBC_Directory::SplitExt(path); LLBC_PrintLine("Split %s: part1: [%s], part2: [%s]", path.c_str(), parts[0].c_str(), parts[1].c_str()); LLBC_PrintLine(""); return LLBC_OK; } int TestCase_Core_File_Directory::GetFilesTest() { LLBC_PrintLine("GetFiles test:"); LLBC_PrintLine("Create some directories and files for test:"); LLBC_Directory::Create("a/b"); LLBC_Directory::Create("a/c"); LLBC_Directory::Create("a/d"); LLBC_File::TouchFile("a/z"); LLBC_File::TouchFile("a/b/bb"); LLBC_File::TouchFile("a/c/cc"); LLBC_File::TouchFile("a/d/dd"); LLBC_Directory::Create("a/b/zz"); LLBC_PrintLine("Get files from directory a(recursive = false)"); if (GetFilesTest("a", false) != LLBC_OK) { LLBC_Directory::Remove("a"); return LLBC_FAILED; } LLBC_PrintLine("Get files from directory a(recursive = true)"); if (GetFilesTest("a", true) != LLBC_OK) { LLBC_Directory::Remove("a"); return LLBC_FAILED; } LLBC_Directory::Remove("a"); LLBC_PrintLine(""); return LLBC_OK; } int TestCase_Core_File_Directory::GetDirectoriesTest() { LLBC_PrintLine("GetDirectories test:"); LLBC_PrintLine("Create some directories and files for test:"); LLBC_Directory::Create("a/b"); LLBC_Directory::Create("a/c"); LLBC_Directory::Create("a/d"); LLBC_File::TouchFile("a/z"); LLBC_File::TouchFile("a/b/bb"); LLBC_File::TouchFile("a/c/cc"); LLBC_File::TouchFile("a/d/dd"); LLBC_Directory::Create("a/b/zz"); LLBC_PrintLine("Get directories from directory a(recursive = false)"); if (GetDirectoriesTest("a", false) != LLBC_OK) { LLBC_Directory::Remove("a"); return LLBC_FAILED; } LLBC_PrintLine("Get directories from directory a(recursive = true)"); if (GetDirectoriesTest("a", true) != LLBC_OK) { LLBC_Directory::Remove("a"); return LLBC_FAILED; } LLBC_Directory::Remove("a"); LLBC_PrintLine(""); return LLBC_OK; return LLBC_OK; } int TestCase_Core_File_Directory::ModuleFileTest() { LLBC_PrintLine("ModuleFile test:"); LLBC_PrintLine("Module file name: %s", LLBC_Directory::ModuleFileName().c_str()); LLBC_PrintLine("Module file directory: %s", LLBC_Directory::ModuleFileDir().c_str()); LLBC_PrintLine(""); return LLBC_OK; } int TestCase_Core_File_Directory::DirNameBaseNameTest() { LLBC_PrintLine("DirName/BaseName test:"); LLBC_String path = "a/b"; LLBC_PrintLine("path %s dirName: %s, baseName: %s", path.c_str(), LLBC_Directory::DirName(path).c_str(), LLBC_Directory::BaseName(path).c_str()); path = "/a/b.exe"; LLBC_PrintLine("path %s dirName: %s, baseName: %s", path.c_str(), LLBC_Directory::DirName(path).c_str(), LLBC_Directory::BaseName(path).c_str()); path = "a/b.exe/"; LLBC_PrintLine("path %s dirName: %s, baseName: %s", path.c_str(), LLBC_Directory::DirName(path).c_str(), LLBC_Directory::BaseName(path).c_str()); LLBC_PrintLine(""); return LLBC_OK; } int TestCase_Core_File_Directory::MiscTest() { LLBC_PrintLine("Misc test:"); LLBC_PrintLine("Document directory: %s", LLBC_Directory::DocDir().c_str()); LLBC_PrintLine("Home directory: %s", LLBC_Directory::HomeDir().c_str()); LLBC_PrintLine("Temporary directory: %s", LLBC_Directory::TempDir().c_str()); LLBC_PrintLine("Cache directory: %s", LLBC_Directory::CacheDir().c_str()); LLBC_PrintLine(""); return LLBC_OK; } int TestCase_Core_File_Directory::JoinTest(const LLBC_Strings &pathParts) { LLBC_Print("Join ["); for (size_t i = 0; i < pathParts.size(); ++i) { LLBC_Print("%s", pathParts[i].c_str()); if (i != pathParts.size() - 1) LLBC_Print(", "); } LLBC_Print("], "); const LLBC_String &joined = LLBC_Directory::Join(pathParts); LLBC_PrintLine("Done, Result: %s", joined.c_str()); return LLBC_OK; } int TestCase_Core_File_Directory::GetFilesTest(const LLBC_String &path, bool recursive) { LLBC_PrintLine("Get files from directory: %s, recursive: %d", path.c_str(), recursive); LLBC_Strings files; if (LLBC_Directory::GetFiles(path, files, recursive) != LLBC_OK) { LLBC_PrintLine("Failed, error: %s", LLBC_FormatLastError()); return LLBC_FAILED; } LLBC_Print("Directory %s files(count: %ld): ", path.c_str(), files.size()); for (size_t i = 0; i < files.size(); ++i) { LLBC_Print("%s", files[i].c_str()); if (i != files.size() - 1) LLBC_Print(", "); } LLBC_PrintLine(""); return LLBC_OK; } int TestCase_Core_File_Directory::GetDirectoriesTest(const LLBC_String &path, bool recursive) { LLBC_PrintLine("Get directories from directory: %s, recursive: %d", path.c_str(), recursive); LLBC_Strings directories; if (LLBC_Directory::GetDirectories(path, directories, recursive) != LLBC_OK) { LLBC_PrintLine("Failed, error: %s", LLBC_FormatLastError()); return LLBC_FAILED; } LLBC_Print("Directory %s subdirectories(count: %ld): ", path.c_str(), directories.size()); for (size_t i = 0; i < directories.size(); ++i) { LLBC_Print("%s", directories[i].c_str()); if (i != directories.size() - 1) LLBC_Print(", "); } LLBC_PrintLine(""); return LLBC_OK; }
31.682692
114
0.643778
caochunxi
5db573026e9f723c79f51e80fb795bac5e12d82c
2,381
cpp
C++
Paznici/main.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
11
2015-08-29T13:41:22.000Z
2020-01-08T20:34:06.000Z
Paznici/main.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
null
null
null
Paznici/main.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
5
2016-01-20T18:17:01.000Z
2019-10-30T11:57:15.000Z
#include <fstream> #include <vector> #include <bitset> #include <queue> #include <algorithm> #include <utility> #include <cstring> #include <string> #include <stack> #include <deque> #include <iomanip> #include <set> #include <map> #include <cassert> #include <ctime> #include <list> #include <iomanip> using namespace std; string file = "paznici"; ifstream cin( (file + ".in").c_str() ); ofstream cout( (file + ".out").c_str() ); const int MAXN = 100; const int oo = (1<<31)-1; typedef vector<int> Graph[MAXN]; typedef vector<int> :: iterator It; Graph G; int N, M, l, L[MAXN], Cuplaj[MAXN], Pereche[MAXN]; bitset<MAXN> Used, sr, sl; vector<char> v1, v2; inline bool pairUp(int Node) { if(Used[Node]) return false; Used[Node] = true; for(It it = G[Node].begin(), fin = G[Node].end() ; it != fin ; ++ it) if(!Pereche[*it]) { Pereche[*it] = Node; Cuplaj[Node] = *it; return true; } for(It it = G[Node].begin(), fin = G[Node].end() ; it != fin ; ++ it) if(pairUp(Pereche[*it])) { Pereche[*it] = Node; Cuplaj[Node] = *it; return true; } return false; } inline void MinVertexCover() { for(bool ok = true ; ok ; ) { ok = false; Used.reset(); for(int i = 1 ; i <= l ; ++ i) if(!Cuplaj[L[i]]) ok |= pairUp(L[i]); } } inline void support(int Node) { for(It it = G[Node].begin(); it != G[Node].end(); ++ it) if(!sr[*it]) { sr[*it] = 1; sl[Pereche[*it]] = 0; support(Pereche[*it]); } } int main() { cin >> N >> M; for(int i = 1 ; i <= N ; ++ i) for(int j = 1 ; j <= M ; ++ j) { char c; cin >> c; if(c == '1') { if(!G[i].size()) ++l, L[l] = i; G[i].push_back(j); } } MinVertexCover(); for(int i = 1 ; i <= l ; ++ i) if(Cuplaj[L[i]]) sl[L[i]] = true; for(int i = 1 ; i <= l ; ++ i) if(!sl[L[i]]) support(L[i]); for(int i = 1 ; i <= N ; ++ i) if(sl[i]) cout << (char)(i + 'A' - 1); for(int i = 1 ; i <= M ; ++ i) if(sr[i]) cout << (char)(i + 'a' - 1); cin.close(); cout.close(); return 0; }
22.67619
73
0.453171
rusucosmin
5db66d7a1f7ee5905f64100438a12008879295df
5,129
cxx
C++
examples/structure.cxx
elcuco/mimetic
00c46f7e25235ea6de9ddefc0b63c3249eb1d1da
[ "MIT" ]
null
null
null
examples/structure.cxx
elcuco/mimetic
00c46f7e25235ea6de9ddefc0b63c3249eb1d1da
[ "MIT" ]
null
null
null
examples/structure.cxx
elcuco/mimetic
00c46f7e25235ea6de9ddefc0b63c3249eb1d1da
[ "MIT" ]
1
2022-02-24T19:24:28.000Z
2022-02-24T19:24:28.000Z
/*************************************************************************** copyright : (C) 2002-2008 by Stefano Barbato email : stefano@codesink.org $Id: structure.cxx,v 1.6 2008-10-07 11:06:25 tat Exp $ ***************************************************************************/ /** \example structure.cc * Usage: structure [-ed] [in_file [out_file]] * * Reads in_file (or standard input) and writes its MIME structure to out_file * (or standard output) */ #include <iostream> #include <fstream> #include <sstream> #include <iterator> #include <streambuf> #include <mimetic/mimetic.h> #include <mimetic/utils.h> using namespace std; using namespace mimetic; int g_verbose; // verbose mode on/off int g_quiet; // quiet mode int g_entityCount; // num of entities found void printTabs(int c) { while(c--) cout << " "; } void printMimeStructure(const std::shared_ptr<MimeEntity>& pMe, int tabcount = 0) { ++g_entityCount; if(!g_quiet) { Header& h = pMe->header(); ContentType ct = h.contentType(); cout << g_entityCount << " "; printTabs(tabcount); cout << ct.type() << "/" << ct.subtype() << endl; if(g_verbose) { ContentType::ParamList::iterator bit, eit; bit = ct.paramList().begin(); eit = ct.paramList().end(); for(; bit != eit; ++bit) { printTabs(tabcount); cout << "param: " << bit->name() << " = " << bit->value() << endl; } if(h.hasField(ContentTransferEncoding::label)) { printTabs(tabcount); cout << "encoding: " << h.contentTransferEncoding().mechanism() << endl; } if(h.hasField(ContentDisposition::label)) { printTabs(tabcount); const ContentDisposition cd = h.contentDisposition(); cout << "disposition: " << cd.type() << endl; ContentDisposition::ParamList::const_iterator bit, eit; bit = cd.paramList().begin(); eit = cd.paramList().end(); for(; bit != eit; ++bit) { printTabs(tabcount); cout << "param: " << bit->name() << " = " << bit->value() << endl; } } Header::iterator hbit, heit; hbit = pMe->header().begin(); heit = pMe->header().end(); for(; hbit != heit; ++hbit) { printTabs(tabcount); cout << "h: " << hbit->name() << " = " << hbit->value() << endl; } if(pMe->body().preamble().length()) { printTabs(tabcount); cout << "preamble: " << pMe->body().preamble() << endl; } if(pMe->body().epilogue().length()) { printTabs(tabcount); cout << "epilogue: " << pMe->body().epilogue() << endl; } printTabs(tabcount); cout << "part size: " << pMe->size() << endl; printTabs(tabcount); cout << "body size: " << pMe->body().length() << endl; cout << endl; } } MimeEntityList::iterator mbit = pMe->body().parts().begin(), meit = pMe->body().parts().end(); for(;mbit!=meit;++mbit) printMimeStructure(*mbit, 1 + tabcount); } void usage() { cout << "structure [-v] [in_file]..." << endl; cout << " -v Verbose mode" << endl; cout << " -q totally quiet; exit code = num of entities" << endl; cout << endl; exit(1); } #if defined(BUILD_MONOLITHIC) #define main(cnt, arr) smime_structure_main(cnt, arr) #endif int main(int argc, const char** argv) { std::ios_base::sync_with_stdio(false); int fidx = 1; int iMask = imBody | imPreamble | imEpilogue; if(argc > 1) { g_verbose = 0; string first = argv[1]; if(first == "-h") usage(); else if(first == "-v") g_verbose = 1; else if(first == "-q") g_quiet = 1; fidx = (g_verbose || g_quiet ? 2 : 1); // first filename idx } if(argc == fidx) { istreambuf_iterator<char> bit(std::cin), eit; std::shared_ptr<MimeEntity> me = MimeEntity::create(bit, eit, iMask); printMimeStructure(me); } else { for(int fc = fidx; fc < argc; ++fc) { File in(argv[fc]); if(!in) { cerr << "ERR: unable to open file " << argv[fc] << endl; continue; } std::shared_ptr<MimeEntity> me = MimeEntity::create(in.begin(), in.end(), iMask); printMimeStructure(me); } } return g_entityCount; }
29.819767
93
0.454475
elcuco
5db6b84160fefe6dbb129a5b04cfe16bf03ac470
24,205
cpp
C++
example-hard-decode-pybind/src/ffhdd/cuvid_decoder.cpp
shouxieai/tensorRT_Pro
963c8250c3cefc568d7d13f3b1b6769393d7b94e
[ "MIT" ]
537
2021-10-03T10:51:49.000Z
2022-03-31T10:07:05.000Z
example-hard-decode-pybind/src/ffhdd/cuvid_decoder.cpp
shouxieai/tensorRT_Pro
963c8250c3cefc568d7d13f3b1b6769393d7b94e
[ "MIT" ]
52
2021-10-04T09:05:35.000Z
2022-03-31T07:35:22.000Z
example-hard-decode-pybind/src/ffhdd/cuvid_decoder.cpp
shouxieai/tensorRT_Pro
963c8250c3cefc568d7d13f3b1b6769393d7b94e
[ "MIT" ]
146
2021-10-11T00:46:19.000Z
2022-03-31T02:19:37.000Z
#include "cuvid_decoder.hpp" #include "cuda_tools.hpp" #include <nvcuvid.h> #include <mutex> #include <vector> #include <sstream> #include <string.h> #include <assert.h> using namespace std; void convert_nv12_to_bgr_invoker( const uint8_t* y, const uint8_t* uv, int width, int height, int linesize, uint8_t* dst_bgr, cudaStream_t stream ); namespace FFHDDecoder{ static float GetChromaHeightFactor(cudaVideoSurfaceFormat eSurfaceFormat) { float factor = 0.5; switch (eSurfaceFormat) { case cudaVideoSurfaceFormat_NV12: case cudaVideoSurfaceFormat_P016: factor = 0.5; break; case cudaVideoSurfaceFormat_YUV444: case cudaVideoSurfaceFormat_YUV444_16Bit: factor = 1.0; break; } return factor; } static int GetChromaPlaneCount(cudaVideoSurfaceFormat eSurfaceFormat) { int numPlane = 1; switch (eSurfaceFormat) { case cudaVideoSurfaceFormat_NV12: case cudaVideoSurfaceFormat_P016: numPlane = 1; break; case cudaVideoSurfaceFormat_YUV444: case cudaVideoSurfaceFormat_YUV444_16Bit: numPlane = 2; break; } return numPlane; } IcudaVideoCodec ffmpeg2NvCodecId(int ffmpeg_codec_id) { switch (ffmpeg_codec_id) { /*AV_CODEC_ID_MPEG1VIDEO*/ case 1 : return cudaVideoCodec_MPEG1; /*AV_CODEC_ID_MPEG2VIDEO*/ case 2 : return cudaVideoCodec_MPEG2; /*AV_CODEC_ID_MPEG4*/ case 12 : return cudaVideoCodec_MPEG4; /*AV_CODEC_ID_VC1*/ case 70 : return cudaVideoCodec_VC1; /*AV_CODEC_ID_H264*/ case 27 : return cudaVideoCodec_H264; /*AV_CODEC_ID_HEVC*/ case 173 : return cudaVideoCodec_HEVC; /*AV_CODEC_ID_VP8*/ case 139 : return cudaVideoCodec_VP8; /*AV_CODEC_ID_VP9*/ case 167 : return cudaVideoCodec_VP9; /*AV_CODEC_ID_MJPEG*/ case 7 : return cudaVideoCodec_JPEG; default : return cudaVideoCodec_NumCodecs; } } class CUVIDDecoderImpl : public CUVIDDecoder{ public: bool create(bool bUseDeviceFrame, int gpu_id, cudaVideoCodec eCodec, bool bLowLatency = false, const CropRect *pCropRect = nullptr, const ResizeDim *pResizeDim = nullptr, int max_cache = -1, int maxWidth = 0, int maxHeight = 0, unsigned int clkRate = 1000, bool output_bgr=false) { m_bUseDeviceFrame = bUseDeviceFrame; m_eCodec = eCodec; m_nMaxWidth = maxWidth; m_nMaxHeight = maxHeight; m_nMaxCache = max_cache; m_gpuID = gpu_id; m_output_bgr = output_bgr; if(m_gpuID == -1){ checkCudaRuntime(cudaGetDevice(&m_gpuID)); } CUDATools::AutoDevice auto_device_exchange(m_gpuID); if (pCropRect) m_cropRect = *pCropRect; if (pResizeDim) m_resizeDim = *pResizeDim; CUcontext cuContext = nullptr; checkCudaDriver(cuCtxGetCurrent(&cuContext)); if(cuContext == nullptr){ INFOE("Current Context is nullptr."); return false; } if(!checkCudaDriver(cuvidCtxLockCreate(&m_ctxLock, cuContext))) return false; if(!checkCudaRuntime(cudaStreamCreate(&m_cuvidStream))) return false; CUVIDPARSERPARAMS videoParserParameters = {}; videoParserParameters.CodecType = eCodec; videoParserParameters.ulMaxNumDecodeSurfaces = 1; videoParserParameters.ulClockRate = clkRate; videoParserParameters.ulMaxDisplayDelay = bLowLatency ? 0 : 1; videoParserParameters.pUserData = this; videoParserParameters.pfnSequenceCallback = handleVideoSequenceProc; videoParserParameters.pfnDecodePicture = handlePictureDecodeProc; videoParserParameters.pfnDisplayPicture = handlePictureDisplayProc; if(!checkCudaDriver(cuvidCreateVideoParser(&m_hParser, &videoParserParameters))) return false; return true; } int decode(const uint8_t *pData, int nSize, int64_t nTimestamp=0) override { m_nDecodedFrame = 0; m_nDecodedFrameReturned = 0; CUVIDSOURCEDATAPACKET packet = { 0 }; packet.payload = pData; packet.payload_size = nSize; packet.flags = CUVID_PKT_TIMESTAMP; packet.timestamp = nTimestamp; if (!pData || nSize == 0) { packet.flags |= CUVID_PKT_ENDOFSTREAM; } try{ CUDATools::AutoDevice auto_device_exchange(m_gpuID); if(!checkCudaDriver(cuvidParseVideoData(m_hParser, &packet))) return -1; }catch(...){ return -1; } return m_nDecodedFrame; } static int CUDAAPI handleVideoSequenceProc(void *pUserData, CUVIDEOFORMAT *pVideoFormat) { return ((CUVIDDecoderImpl *)pUserData)->handleVideoSequence(pVideoFormat); } static int CUDAAPI handlePictureDecodeProc(void *pUserData, CUVIDPICPARAMS *pPicParams) { return ((CUVIDDecoderImpl *)pUserData)->handlePictureDecode(pPicParams); } static int CUDAAPI handlePictureDisplayProc(void *pUserData, CUVIDPARSERDISPINFO *pDispInfo) { return ((CUVIDDecoderImpl *)pUserData)->handlePictureDisplay(pDispInfo); } virtual int device() override{ return this->m_gpuID; } virtual bool is_gpu_frame() override{ return this->m_bUseDeviceFrame; } int handleVideoSequence(CUVIDEOFORMAT *pVideoFormat){ int nDecodeSurface = pVideoFormat->min_num_decode_surfaces; CUVIDDECODECAPS decodecaps; memset(&decodecaps, 0, sizeof(decodecaps)); decodecaps.eCodecType = pVideoFormat->codec; decodecaps.eChromaFormat = pVideoFormat->chroma_format; decodecaps.nBitDepthMinus8 = pVideoFormat->bit_depth_luma_minus8; checkCudaDriver(cuvidGetDecoderCaps(&decodecaps)); if(!decodecaps.bIsSupported){ throw std::runtime_error("Codec not supported on this GPU"); return nDecodeSurface; } if ((pVideoFormat->coded_width > decodecaps.nMaxWidth) || (pVideoFormat->coded_height > decodecaps.nMaxHeight)){ std::ostringstream errorString; errorString << std::endl << "Resolution : " << pVideoFormat->coded_width << "x" << pVideoFormat->coded_height << std::endl << "Max Supported (wxh) : " << decodecaps.nMaxWidth << "x" << decodecaps.nMaxHeight << std::endl << "Resolution not supported on this GPU"; const std::string cErr = errorString.str(); throw std::runtime_error(cErr); return nDecodeSurface; } if ((pVideoFormat->coded_width>>4)*(pVideoFormat->coded_height>>4) > decodecaps.nMaxMBCount){ std::ostringstream errorString; errorString << std::endl << "MBCount : " << (pVideoFormat->coded_width >> 4)*(pVideoFormat->coded_height >> 4) << std::endl << "Max Supported mbcnt : " << decodecaps.nMaxMBCount << std::endl << "MBCount not supported on this GPU"; const std::string cErr = errorString.str(); throw std::runtime_error(cErr); return nDecodeSurface; } // eCodec has been set in the constructor (for parser). Here it's set again for potential correction m_eCodec = pVideoFormat->codec; m_eChromaFormat = pVideoFormat->chroma_format; m_nBitDepthMinus8 = pVideoFormat->bit_depth_luma_minus8; m_nBPP = m_nBitDepthMinus8 > 0 ? 2 : 1; // Set the output surface format same as chroma format if (m_eChromaFormat == cudaVideoChromaFormat_420) m_eOutputFormat = pVideoFormat->bit_depth_luma_minus8 ? cudaVideoSurfaceFormat_P016 : cudaVideoSurfaceFormat_NV12; else if (m_eChromaFormat == cudaVideoChromaFormat_444) m_eOutputFormat = pVideoFormat->bit_depth_luma_minus8 ? cudaVideoSurfaceFormat_YUV444_16Bit : cudaVideoSurfaceFormat_YUV444; else if (m_eChromaFormat == cudaVideoChromaFormat_422) m_eOutputFormat = cudaVideoSurfaceFormat_NV12; // no 4:2:2 output format supported yet so make 420 default // Check if output format supported. If not, check falback options if (!(decodecaps.nOutputFormatMask & (1 << m_eOutputFormat))) { if (decodecaps.nOutputFormatMask & (1 << cudaVideoSurfaceFormat_NV12)) m_eOutputFormat = cudaVideoSurfaceFormat_NV12; else if (decodecaps.nOutputFormatMask & (1 << cudaVideoSurfaceFormat_P016)) m_eOutputFormat = cudaVideoSurfaceFormat_P016; else if (decodecaps.nOutputFormatMask & (1 << cudaVideoSurfaceFormat_YUV444)) m_eOutputFormat = cudaVideoSurfaceFormat_YUV444; else if (decodecaps.nOutputFormatMask & (1 << cudaVideoSurfaceFormat_YUV444_16Bit)) m_eOutputFormat = cudaVideoSurfaceFormat_YUV444_16Bit; else throw std::runtime_error("No supported output format found"); } m_videoFormat = *pVideoFormat; CUVIDDECODECREATEINFO videoDecodeCreateInfo = { 0 }; videoDecodeCreateInfo.CodecType = pVideoFormat->codec; videoDecodeCreateInfo.ChromaFormat = pVideoFormat->chroma_format; videoDecodeCreateInfo.OutputFormat = m_eOutputFormat; videoDecodeCreateInfo.bitDepthMinus8 = pVideoFormat->bit_depth_luma_minus8; if (pVideoFormat->progressive_sequence) videoDecodeCreateInfo.DeinterlaceMode = cudaVideoDeinterlaceMode_Weave; else videoDecodeCreateInfo.DeinterlaceMode = cudaVideoDeinterlaceMode_Adaptive; videoDecodeCreateInfo.ulNumOutputSurfaces = 2; // With PreferCUVID, JPEG is still decoded by CUDA while video is decoded by NVDEC hardware videoDecodeCreateInfo.ulCreationFlags = cudaVideoCreate_PreferCUVID; videoDecodeCreateInfo.ulNumDecodeSurfaces = nDecodeSurface; videoDecodeCreateInfo.vidLock = m_ctxLock; videoDecodeCreateInfo.ulWidth = pVideoFormat->coded_width; videoDecodeCreateInfo.ulHeight = pVideoFormat->coded_height; if (m_nMaxWidth < (int)pVideoFormat->coded_width) m_nMaxWidth = pVideoFormat->coded_width; if (m_nMaxHeight < (int)pVideoFormat->coded_height) m_nMaxHeight = pVideoFormat->coded_height; videoDecodeCreateInfo.ulMaxWidth = m_nMaxWidth; videoDecodeCreateInfo.ulMaxHeight = m_nMaxHeight; if (!(m_cropRect.r && m_cropRect.b) && !(m_resizeDim.w && m_resizeDim.h)) { m_nWidth = pVideoFormat->display_area.right - pVideoFormat->display_area.left; m_nLumaHeight = pVideoFormat->display_area.bottom - pVideoFormat->display_area.top; videoDecodeCreateInfo.ulTargetWidth = pVideoFormat->coded_width; videoDecodeCreateInfo.ulTargetHeight = pVideoFormat->coded_height; } else { if (m_resizeDim.w && m_resizeDim.h) { videoDecodeCreateInfo.display_area.left = pVideoFormat->display_area.left; videoDecodeCreateInfo.display_area.top = pVideoFormat->display_area.top; videoDecodeCreateInfo.display_area.right = pVideoFormat->display_area.right; videoDecodeCreateInfo.display_area.bottom = pVideoFormat->display_area.bottom; m_nWidth = m_resizeDim.w; m_nLumaHeight = m_resizeDim.h; } if (m_cropRect.r && m_cropRect.b) { videoDecodeCreateInfo.display_area.left = m_cropRect.l; videoDecodeCreateInfo.display_area.top = m_cropRect.t; videoDecodeCreateInfo.display_area.right = m_cropRect.r; videoDecodeCreateInfo.display_area.bottom = m_cropRect.b; m_nWidth = m_cropRect.r - m_cropRect.l; m_nLumaHeight = m_cropRect.b - m_cropRect.t; } videoDecodeCreateInfo.ulTargetWidth = m_nWidth; videoDecodeCreateInfo.ulTargetHeight = m_nLumaHeight; } m_nChromaHeight = (int)(m_nLumaHeight * GetChromaHeightFactor(m_eOutputFormat)); m_nNumChromaPlanes = GetChromaPlaneCount(m_eOutputFormat); m_nSurfaceHeight = videoDecodeCreateInfo.ulTargetHeight; m_nSurfaceWidth = videoDecodeCreateInfo.ulTargetWidth; m_displayRect.b = videoDecodeCreateInfo.display_area.bottom; m_displayRect.t = videoDecodeCreateInfo.display_area.top; m_displayRect.l = videoDecodeCreateInfo.display_area.left; m_displayRect.r = videoDecodeCreateInfo.display_area.right; checkCudaDriver(cuvidCreateDecoder(&m_hDecoder, &videoDecodeCreateInfo)); return nDecodeSurface; } int handlePictureDecode(CUVIDPICPARAMS *pPicParams){ if (!m_hDecoder) { throw std::runtime_error("Decoder not initialized."); return false; } m_nPicNumInDecodeOrder[pPicParams->CurrPicIdx] = m_nDecodePicCnt++; checkCudaDriver(cuvidDecodePicture(m_hDecoder, pPicParams)); return 1; } int handlePictureDisplay(CUVIDPARSERDISPINFO *pDispInfo){ CUVIDPROCPARAMS videoProcessingParameters = {}; videoProcessingParameters.progressive_frame = pDispInfo->progressive_frame; videoProcessingParameters.second_field = pDispInfo->repeat_first_field + 1; videoProcessingParameters.top_field_first = pDispInfo->top_field_first; videoProcessingParameters.unpaired_field = pDispInfo->repeat_first_field < 0; videoProcessingParameters.output_stream = m_cuvidStream; CUdeviceptr dpSrcFrame = 0; unsigned int nSrcPitch = 0; checkCudaDriver(cuvidMapVideoFrame(m_hDecoder, pDispInfo->picture_index, &dpSrcFrame, &nSrcPitch, &videoProcessingParameters)); CUVIDGETDECODESTATUS DecodeStatus; memset(&DecodeStatus, 0, sizeof(DecodeStatus)); CUresult result = cuvidGetDecodeStatus(m_hDecoder, pDispInfo->picture_index, &DecodeStatus); if (result == CUDA_SUCCESS && (DecodeStatus.decodeStatus == cuvidDecodeStatus_Error || DecodeStatus.decodeStatus == cuvidDecodeStatus_Error_Concealed)) { printf("Decode Error occurred for picture %d\n", m_nPicNumInDecodeOrder[pDispInfo->picture_index]); } uint8_t *pDecodedFrame = nullptr; { if ((unsigned)++m_nDecodedFrame > m_vpFrame.size()) { /* 如果超过了缓存限制,则覆盖最后一个图 */ bool need_alloc = true; if(m_nMaxCache != -1){ if(m_vpFrame.size() >= m_nMaxCache){ --m_nDecodedFrame; need_alloc = false; } } if(need_alloc){ uint8_t *pFrame = nullptr; if (m_bUseDeviceFrame) //checkCudaDriver(cuMemAlloc((CUdeviceptr *)&pFrame, get_frame_bytes())); checkCudaRuntime(cudaMalloc(&pFrame, get_frame_bytes())); else checkCudaRuntime(cudaMallocHost(&pFrame, get_frame_bytes())); m_vpFrame.push_back(pFrame); m_vTimestamp.push_back(0); } } pDecodedFrame = m_vpFrame[m_nDecodedFrame - 1]; m_vTimestamp[m_nDecodedFrame - 1] = pDispInfo->timestamp; } if(m_output_bgr){ if(m_pYUVFrame == 0){ checkCudaDriver(cuMemAlloc(&m_pYUVFrame, m_nWidth * (m_nLumaHeight + m_nChromaHeight * m_nNumChromaPlanes) * m_nBPP)); } if(m_pBGRFrame == 0){ checkCudaDriver(cuMemAlloc(&m_pBGRFrame, m_nWidth * m_nLumaHeight * 3)); } CUDA_MEMCPY2D m = { 0 }; m.srcMemoryType = CU_MEMORYTYPE_DEVICE; m.srcDevice = dpSrcFrame; m.srcPitch = nSrcPitch; m.dstMemoryType = CU_MEMORYTYPE_DEVICE; m.dstDevice = (CUdeviceptr)(m.dstHost = (uint8_t*)m_pYUVFrame); m.dstPitch = m_nWidth * m_nBPP; m.WidthInBytes = m_nWidth * m_nBPP; m.Height = m_nLumaHeight; checkCudaDriver(cuMemcpy2DAsync(&m, m_cuvidStream)); m.srcDevice = (CUdeviceptr)((uint8_t *)dpSrcFrame + m.srcPitch * m_nSurfaceHeight); m.dstDevice = (CUdeviceptr)(m.dstHost = (uint8_t*)m_pYUVFrame + m.dstPitch * m_nLumaHeight); m.Height = m_nChromaHeight; checkCudaDriver(cuMemcpy2DAsync(&m, m_cuvidStream)); uint8_t* y = (uint8_t*)m_pYUVFrame; uint8_t* uv = y + m_nWidth * m_nLumaHeight; convert_nv12_to_bgr_invoker(y, uv, m_nWidth, m_nLumaHeight, m_nWidth, (uint8_t*)m_pBGRFrame, m_cuvidStream); if(m_bUseDeviceFrame){ checkCudaDriver(cuMemcpyDtoDAsync((CUdeviceptr)pDecodedFrame, m_pBGRFrame, m_nWidth * m_nLumaHeight * 3, m_cuvidStream)); }else{ checkCudaDriver(cuMemcpyDtoHAsync(pDecodedFrame, m_pBGRFrame, m_nWidth * m_nLumaHeight * 3, m_cuvidStream)); } }else{ CUDA_MEMCPY2D m = { 0 }; m.srcMemoryType = CU_MEMORYTYPE_DEVICE; m.srcDevice = dpSrcFrame; m.srcPitch = nSrcPitch; m.dstMemoryType = m_bUseDeviceFrame ? CU_MEMORYTYPE_DEVICE : CU_MEMORYTYPE_HOST; m.dstDevice = (CUdeviceptr)(m.dstHost = pDecodedFrame); m.dstPitch = m_nWidth * m_nBPP; m.WidthInBytes = m_nWidth * m_nBPP; m.Height = m_nLumaHeight; checkCudaDriver(cuMemcpy2DAsync(&m, m_cuvidStream)); m.srcDevice = (CUdeviceptr)((uint8_t *)dpSrcFrame + m.srcPitch * m_nSurfaceHeight); m.dstDevice = (CUdeviceptr)(m.dstHost = pDecodedFrame + m.dstPitch * m_nLumaHeight); m.Height = m_nChromaHeight; checkCudaDriver(cuMemcpy2DAsync(&m, m_cuvidStream)); if (m_nNumChromaPlanes == 2){ m.srcDevice = (CUdeviceptr)((uint8_t *)dpSrcFrame + m.srcPitch * m_nSurfaceHeight * 2); m.dstDevice = (CUdeviceptr)(m.dstHost = pDecodedFrame + m.dstPitch * m_nLumaHeight * 2); m.Height = m_nChromaHeight; checkCudaDriver(cuMemcpy2DAsync(&m, m_cuvidStream)); } } if(!m_bUseDeviceFrame){ // 确保数据是到位的 checkCudaDriver(cuStreamSynchronize(m_cuvidStream)); } checkCudaDriver(cuvidUnmapVideoFrame(m_hDecoder, dpSrcFrame)); return 1; } virtual ICUStream get_stream() override{ return m_cuvidStream; } int get_frame_bytes() override { assert(m_nWidth); if(m_output_bgr){ return m_nWidth * m_nLumaHeight * 3; } return m_nWidth * (m_nLumaHeight + m_nChromaHeight * m_nNumChromaPlanes) * m_nBPP; } int get_width() override { assert(m_nWidth); return m_nWidth; } int get_height() override { assert(m_nLumaHeight); return m_nLumaHeight; } unsigned int get_frame_index() override { return m_iFrameIndex; } unsigned int get_num_decoded_frame() override {return m_nDecodedFrame;} cudaVideoSurfaceFormat get_output_format() { return m_eOutputFormat; } uint8_t* get_frame(int64_t* pTimestamp = nullptr, unsigned int* pFrameIndex = nullptr) override{ if (m_nDecodedFrame > 0){ if (pFrameIndex) *pFrameIndex = m_iFrameIndex; if (pTimestamp) *pTimestamp = m_vTimestamp[m_nDecodedFrameReturned]; m_nDecodedFrame--; m_iFrameIndex++; return m_vpFrame[m_nDecodedFrameReturned++]; } return nullptr; } virtual ~CUVIDDecoderImpl(){ if (m_hParser) cuvidDestroyVideoParser(m_hParser); if (m_hDecoder) cuvidDestroyDecoder(m_hDecoder); for (uint8_t *pFrame : m_vpFrame){ if (m_bUseDeviceFrame) //cuMemFree((CUdeviceptr)pFrame); cudaFree(pFrame); else cudaFreeHost(pFrame); } if(m_pYUVFrame){ cuMemFree((CUdeviceptr)m_pYUVFrame); m_pYUVFrame = 0; } if(m_pBGRFrame){ cuMemFree((CUdeviceptr)m_pBGRFrame); m_pBGRFrame = 0; } cuvidCtxLockDestroy(m_ctxLock); } private: CUvideoctxlock m_ctxLock = nullptr; CUvideoparser m_hParser = nullptr; CUvideodecoder m_hDecoder = nullptr; bool m_bUseDeviceFrame = false; // dimension of the output unsigned int m_nWidth = 0, m_nLumaHeight = 0, m_nChromaHeight = 0; unsigned int m_nNumChromaPlanes = 0; // height of the mapped surface int m_nSurfaceHeight = 0; int m_nSurfaceWidth = 0; cudaVideoCodec m_eCodec = cudaVideoCodec_NumCodecs; cudaVideoChromaFormat m_eChromaFormat; cudaVideoSurfaceFormat m_eOutputFormat; int m_nBitDepthMinus8 = 0; int m_nBPP = 1; CUVIDEOFORMAT m_videoFormat = {}; CropRect m_displayRect = {}; mutex m_lock; // stock of frames std::vector<uint8_t *> m_vpFrame; CUdeviceptr m_pYUVFrame = 0; CUdeviceptr m_pBGRFrame = 0; // timestamps of decoded frames std::vector<int64_t> m_vTimestamp; int m_nDecodedFrame = 0, m_nDecodedFrameReturned = 0; int m_nDecodePicCnt = 0, m_nPicNumInDecodeOrder[32]; CUstream m_cuvidStream = 0; CropRect m_cropRect = {}; ResizeDim m_resizeDim = {}; unsigned int m_iFrameIndex = 0; int m_nMaxCache = -1; int m_gpuID = -1; unsigned int m_nMaxWidth = 0, m_nMaxHeight = 0; bool m_output_bgr = true; }; std::shared_ptr<CUVIDDecoder> create_cuvid_decoder( bool bUseDeviceFrame, IcudaVideoCodec eCodec, int max_cache, int gpu_id, const CropRect *pCropRect, const ResizeDim *pResizeDim, bool output_bgr){ shared_ptr<CUVIDDecoderImpl> instance(new CUVIDDecoderImpl()); if(!instance->create(bUseDeviceFrame, gpu_id, (cudaVideoCodec)eCodec, false, pCropRect, pResizeDim, max_cache, 0, 0, 1000, output_bgr)) instance.reset(); return instance; } }; //FFHDDecoder
45.842803
177
0.599215
shouxieai
5dbbb8e8f2cf49cd4bf76f284d059b5a80443409
1,347
cpp
C++
Dynamic Programming/139. Word Break/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
1
2021-11-19T19:58:33.000Z
2021-11-19T19:58:33.000Z
Dynamic Programming/139. Word Break/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
null
null
null
Dynamic Programming/139. Word Break/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
2
2021-11-26T12:47:27.000Z
2022-01-13T16:14:46.000Z
// // main.cpp // 139. Word Break // // Created by 边俊林 on 2019/8/22. // Copyright © 2019 Minecode.Link. All rights reserved. // /* ------------------------------------------------------ *\ https://leetcode.com/problems/word-break/ \* ------------------------------------------------------ */ #include <map> #include <set> #include <queue> #include <stack> #include <vector> #include <cstdio> #include <cstdlib> #include <iostream> #include <algorithm> #include <unordered_map> #include <unordered_set> using namespace std; /// Solution: // class Solution { public: bool wordBreak(string s, vector<string>& wordDict) { int len = s.length(); unordered_set<string> hasa (wordDict.begin(), wordDict.end()); vector<bool> dp (len+1, false); dp[0] = true; for (int i = 1; i <= len; ++i) { for (int j = 1; j <= i; ++j) { if (dp[j-1] && hasa.find(s.substr(j-1, i-j+1)) != hasa.end()) dp[i] = true; } } return dp[len]; } }; int main() { Solution sol = Solution(); // string s = "leetcode"; // vector<string> words = {"leet", "code"}; string s = "applepenapple"; vector<string> words = {"apple", "pen"}; auto res = sol.wordBreak(s, words); cout << (res ? "true" : "false") << endl; return 0; }
24.053571
77
0.504826
Minecodecraft
5dbd884ebe28d1e93dfd508f4f5d255aac30f0a8
6,663
cpp
C++
cwrapper/engine/src/renderer/DirectionalVolumetricRenderer.cpp
tippesi/Go-Atlas-Engine-Test
83aedf376802803eddded6363898f001e4e83c36
[ "BSD-3-Clause" ]
null
null
null
cwrapper/engine/src/renderer/DirectionalVolumetricRenderer.cpp
tippesi/Go-Atlas-Engine-Test
83aedf376802803eddded6363898f001e4e83c36
[ "BSD-3-Clause" ]
null
null
null
cwrapper/engine/src/renderer/DirectionalVolumetricRenderer.cpp
tippesi/Go-Atlas-Engine-Test
83aedf376802803eddded6363898f001e4e83c36
[ "BSD-3-Clause" ]
1
2019-11-28T08:45:09.000Z
2019-11-28T08:45:09.000Z
#include "DirectionalVolumetricRenderer.h" #include "../lighting/DirectionalLight.h" namespace Atlas { namespace Renderer { std::string DirectionalVolumetricRenderer::volumetricVertexPath = "volumetric.vsh"; std::string DirectionalVolumetricRenderer::volumetricFragmentPath = "volumetric.fsh"; std::string DirectionalVolumetricRenderer::bilateralBlurVertexPath = "bilateralBlur.vsh"; std::string DirectionalVolumetricRenderer::bilateralBlurFragmentPath = "bilateralBlur.fsh"; DirectionalVolumetricRenderer::DirectionalVolumetricRenderer() { blurKernel.CalculateBoxFilter(21); volumetricShader.AddStage(AE_VERTEX_STAGE, volumetricVertexPath); volumetricShader.AddStage(AE_FRAGMENT_STAGE, volumetricFragmentPath); volumetricShader.Compile(); GetVolumetricUniforms(); bilateralBlurShader.AddStage(AE_VERTEX_STAGE, bilateralBlurVertexPath); bilateralBlurShader.AddStage(AE_FRAGMENT_STAGE, bilateralBlurFragmentPath); bilateralBlurShader.AddMacro("BILATERAL"); bilateralBlurShader.AddMacro("BLUR_R"); bilateralBlurShader.Compile(); GetBilateralBlurUniforms(); } void DirectionalVolumetricRenderer::Render(Viewport *viewport, RenderTarget *target, Camera *camera, Scene::Scene *scene) { framebuffer.Bind(); volumetricShader.Bind(); inverseProjectionMatrix->SetValue(camera->inverseProjectionMatrix); target->geometryFramebuffer.GetComponentTexture(GL_DEPTH_ATTACHMENT)->Bind(GL_TEXTURE0); auto lights = scene->GetLights(); for (auto& light : lights) { if (light->type != AE_DIRECTIONAL_LIGHT || !light->GetShadow() || !light->GetVolumetric()) { continue; } auto directionalLight = (Lighting::DirectionalLight*)light; glViewport(0, 0, directionalLight->GetVolumetric()->map->width, directionalLight->GetVolumetric()->map->height); framebuffer.AddComponentTexture(GL_COLOR_ATTACHMENT0, directionalLight->GetVolumetric()->map); vec3 direction = normalize(vec3(camera->viewMatrix * vec4(directionalLight->direction, 0.0f))); lightDirection->SetValue(direction); shadowCascadeCount->SetValue(directionalLight->GetShadow()->componentCount); sampleCount->SetValue(directionalLight->GetVolumetric()->sampleCount); scattering->SetValue(glm::clamp(directionalLight->GetVolumetric()->scattering, -1.0f, 1.0f)); framebufferResolution->SetValue(vec2(directionalLight->GetVolumetric()->map->width, directionalLight->GetVolumetric()->map->height)); light->GetShadow()->maps.Bind(GL_TEXTURE1); for (int32_t i = 0; i < MAX_SHADOW_CASCADE_COUNT; i++) { if (i < light->GetShadow()->componentCount) { auto cascade = &directionalLight->GetShadow()->components[i]; cascades[i].distance->SetValue(cascade->farDistance); cascades[i].lightSpace->SetValue(cascade->projectionMatrix * cascade->viewMatrix * camera->inverseViewMatrix); } else { cascades[i].distance->SetValue(camera->farPlane); cascades[i].lightSpace->SetValue(mat4(1.0f)); } } glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } bilateralBlurShader.Bind(); target->geometryFramebuffer.GetComponentTexture(GL_DEPTH_ATTACHMENT)->Bind(GL_TEXTURE1); std::vector<float>* kernelWeights; std::vector<float>* kernelOffsets; blurKernel.GetLinearized(kernelWeights, kernelOffsets); weights->SetValue(kernelWeights->data(), (int32_t)kernelWeights->size()); offsets->SetValue(kernelOffsets->data(), (int32_t)kernelOffsets->size()); kernelSize->SetValue((int32_t)kernelWeights->size()); for (auto& light : lights) { if (light->type != AE_DIRECTIONAL_LIGHT || light->GetShadow() == nullptr || light->GetVolumetric() == nullptr) { continue; } auto directionalLight = (Lighting::DirectionalLight*)light; glViewport(0, 0, directionalLight->GetVolumetric()->map->width, directionalLight->GetVolumetric()->map->height); framebuffer.AddComponentTexture(GL_COLOR_ATTACHMENT0, directionalLight->GetVolumetric()->blurMap); directionalLight->GetVolumetric()->map->Bind(GL_TEXTURE0); blurDirection->SetValue(vec2(1.0f / (float)directionalLight->GetVolumetric()->map->width, 0.0f)); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); framebuffer.AddComponentTexture(GL_COLOR_ATTACHMENT0, directionalLight->GetVolumetric()->map); directionalLight->GetVolumetric()->blurMap->Bind(GL_TEXTURE0); blurDirection->SetValue(vec2(0.0f, 1.0f / (float)directionalLight->GetVolumetric()->map->height)); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } } void DirectionalVolumetricRenderer::GetVolumetricUniforms() { lightDirection = volumetricShader.GetUniform("light.direction"); inverseProjectionMatrix = volumetricShader.GetUniform("ipMatrix"); sampleCount = volumetricShader.GetUniform("sampleCount"); scattering = volumetricShader.GetUniform("scattering"); shadowCascadeCount = volumetricShader.GetUniform("light.shadow.cascadeCount"); framebufferResolution = volumetricShader.GetUniform("framebufferResolution"); for (int32_t i = 0; i < MAX_SHADOW_CASCADE_COUNT; i++) { cascades[i].distance = volumetricShader.GetUniform("light.shadow.cascades[" + std::to_string(i) + "].distance"); cascades[i].lightSpace = volumetricShader.GetUniform("light.shadow.cascades[" + std::to_string(i) + "].cascadeSpace"); } } void DirectionalVolumetricRenderer::GetBilateralBlurUniforms() { blurDirection = bilateralBlurShader.GetUniform("blurDirection"); offsets = bilateralBlurShader.GetUniform("offset"); weights = bilateralBlurShader.GetUniform("weight"); kernelSize = bilateralBlurShader.GetUniform("kernelSize"); } } }
42.170886
134
0.634849
tippesi
5dbed243bc1ef60853dcabaa4ecd87938ddc8c71
1,059
cpp
C++
Leetcode/Day026/add_2_num_LL_2.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
Leetcode/Day026/add_2_num_LL_2.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
Leetcode/Day026/add_2_num_LL_2.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
// not sure if this is not reversing the list. /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* ans = NULL; ListNode* prev = ans; stack<int> s1, s2; while(l1) { s1.push(l1->val); l1=l1->next; } while(l2) { s2.push(l2->val); l2=l2->next; } int carry=0; while(!s1.empty() || !s2.empty() || carry) { if(!s1.empty()) { carry+=s1.top(); s1.pop(); } if(!s2.empty()) { carry+=s2.top(); s2.pop(); } ans= new ListNode(carry%10); carry=carry/10; ans->next=prev; prev=ans; } return ans; } };
20.365385
56
0.390935
SujalAhrodia
5dbfb9eee1c05aef2e5a2211f35767cb136b519a
3,728
cpp
C++
PhysXChips_Dlg/PhysXMaterial_Dlg.cpp
snaxgameengine/PhysXForSnaX
aa18d93a30e6cfe11b0258af3733b65de0adf832
[ "BSD-3-Clause" ]
3
2021-04-27T08:52:40.000Z
2021-05-19T18:05:40.000Z
PhysXChips_Dlg/PhysXMaterial_Dlg.cpp
snaxgameengine/PhysXForSnaX
aa18d93a30e6cfe11b0258af3733b65de0adf832
[ "BSD-3-Clause" ]
null
null
null
PhysXChips_Dlg/PhysXMaterial_Dlg.cpp
snaxgameengine/PhysXForSnaX
aa18d93a30e6cfe11b0258af3733b65de0adf832
[ "BSD-3-Clause" ]
null
null
null
// Copyright(c) 2013-2019, mCODE A/S // 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 copyright holders 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 HOLDERS 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 "pch.h" #include "PhysXMaterial_Dlg.h" using namespace m3d; DIALOGDESC_DEF(PhysXMaterial_Dlg, PHYSXMATERIAL_GUID); void PhysXMaterial_Dlg::Init() { AddDoubleSpinBox(L"Static Friction", GetChip()->GetStaticFriction(), 0, FLT_MAX, 0.1f, [this](Id id, RVariant v) { SetDirty(); GetChip()->SetStaticFriction(v.ToFloat()); }); AddDoubleSpinBox(L"Dynamic Friction", GetChip()->GetDynamicFriction(), 0, FLT_MAX, 0.1f, [this](Id id, RVariant v) { SetDirty(); GetChip()->SetDynamicFriction(v.ToFloat()); }); AddDoubleSpinBox(L"Restitution", GetChip()->GetRestitution(), 0, 1, 0.1f, [this](Id id, RVariant v) { SetDirty(); GetChip()->SetRestitution(v.ToFloat()); }); AddCheckBox(1, L"Disable Friction", GetChip()->IsDisableFriction() ? RCheckState::Checked : RCheckState::Unchecked, [this](Id id, RVariant v) { SetDirty(); GetChip()->SetDisableFriction(v.ToUInt() == RCheckState::Checked); _enableButtons(); }); AddCheckBox(2, L"Disable Strong Friction", GetChip()->IsDisableStrongFriction() ? RCheckState::Checked : RCheckState::Unchecked, [this](Id id, RVariant v) { SetDirty(); GetChip()->SetDisableStrongFriction(v.ToUInt() == RCheckState::Checked); }); ComboBoxInitList lst; lst.push_back(std::make_pair(String(L"Average"), RVariant(physx::PxCombineMode::eAVERAGE))); lst.push_back(std::make_pair(String(L"Minimum"), RVariant(physx::PxCombineMode::eMIN))); lst.push_back(std::make_pair(String(L"Multiply"), RVariant(physx::PxCombineMode::eMULTIPLY))); lst.push_back(std::make_pair(String(L"Maximum"), RVariant(physx::PxCombineMode::eMAX))); AddComboBox(3, L"Friction Combine Mode", lst, GetChip()->GetFrictionCombineMode(), [this](Id id, RVariant v) { SetDirty(); GetChip()->SetFrictionCombineMode((physx::PxCombineMode::Enum)v.ToUInt()); }); AddComboBox(4, L"Restitution Combine Mode", lst, GetChip()->GetRestitutionCombineMode(), [this](Id id, RVariant v) { SetDirty(); GetChip()->SetRestitutionCombineMode((physx::PxCombineMode::Enum)v.ToUInt()); }); _enableButtons(); } void PhysXMaterial_Dlg::_enableButtons() { bool b = GetValueFromWidget(1).ToUInt() == RCheckState::Unchecked; SetWidgetEnabled(2, b); SetWidgetEnabled(3, b); }
63.186441
246
0.747049
snaxgameengine
5dc61414252ec404cb3226e3874203a9e52a4806
3,609
cpp
C++
third_party/omr/fvtest/porttest/cudaStream.cpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/fvtest/porttest/cudaStream.cpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/fvtest/porttest/cudaStream.cpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright (c) 2015, 2015 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at http://eclipse.org/legal/epl-2.0 * or the Apache License, Version 2.0 which accompanies this distribution * and is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License, v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception [1] and GNU General Public * License, version 2 with the OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ #include "cudaTests.hpp" static void streamCallback(J9CudaStream stream, int32_t error, uintptr_t userData) { *(J9CudaStream *)userData = stream; } /** * Verify streams API. */ TEST_F(CudaDeviceTest, streams) { OMRPORT_ACCESS_FROM_OMRPORT(getPortLibrary()); for (uint32_t deviceId = 0; deviceId < deviceCount; ++deviceId) { J9CudaStream callbackData = NULL; J9CudaEvent event = NULL; int32_t rc = 0; J9CudaStream stream1 = NULL; J9CudaStream stream2 = NULL; uint32_t streamFlags = 0; int32_t streamPriority = 0; rc = omrcuda_streamCreate(deviceId, &stream1); ASSERT_EQ(0, rc) << "omrcuda_streamCreate failed"; ASSERT_NOT_NULL(stream1) << "created null stream"; rc = omrcuda_streamCreateWithPriority(deviceId, -1, J9CUDA_STREAM_FLAG_NON_BLOCKING, &stream2); ASSERT_EQ(0, rc) << "omrcuda_streamCreateWithPriority failed"; ASSERT_NOT_NULL(stream2) << "created null stream"; rc = omrcuda_eventCreate(deviceId, J9CUDA_EVENT_FLAG_DEFAULT, &event); ASSERT_EQ(0, rc) << "omrcuda_eventCreate failed"; ASSERT_NOT_NULL(event) << "created null event"; rc = omrcuda_eventRecord(deviceId, event, stream1); ASSERT_EQ(0, rc) << "omrcuda_eventRecord failed"; rc = omrcuda_streamWaitEvent(deviceId, stream2, event); ASSERT_EQ(0, rc) << "omrcuda_streamWaitEvent failed"; rc = omrcuda_streamAddCallback(deviceId, stream2, streamCallback, (uintptr_t)&callbackData); ASSERT_EQ(0, rc) << "omrcuda_streamAddCallback failed"; rc = omrcuda_streamGetFlags(deviceId, stream2, &streamFlags); ASSERT_EQ(0, rc) << "omrcuda_streamGetFlags failed"; rc = omrcuda_streamGetPriority(deviceId, stream2, &streamPriority); ASSERT_EQ(0, rc) << "omrcuda_streamGetPriority failed"; rc = omrcuda_streamSynchronize(deviceId, stream2); ASSERT_EQ(0, rc) << "omrcuda_streamSynchronize failed"; rc = omrcuda_streamQuery(deviceId, stream2); ASSERT_EQ(0, rc) << "omrcuda_streamQuery failed"; ASSERT_EQ(stream2, callbackData) << "callback did not execute correctly"; if (NULL != stream1) { rc = omrcuda_streamDestroy(deviceId, stream1); ASSERT_EQ(0, rc) << "omrcuda_streamDestroy failed"; } if (NULL != stream2) { rc = omrcuda_streamDestroy(deviceId, stream2); ASSERT_EQ(0, rc) << "omrcuda_streamDestroy failed"; } if (NULL != event) { rc = omrcuda_eventDestroy(deviceId, event); ASSERT_EQ(0, rc) << "omrcuda_eventDestroy failed"; } } }
32.809091
135
0.704904
xiacijie
5dc70052ccbad732e8cd523f9614e99d7ff684d1
4,899
cpp
C++
moses/phrase-extract/extract-ghkm/ScfgRule.cpp
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
3
2018-01-25T00:51:56.000Z
2022-01-07T15:09:38.000Z
moses/phrase-extract/extract-ghkm/ScfgRule.cpp
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
1
2020-06-23T08:29:09.000Z
2020-06-24T12:11:47.000Z
moses/phrase-extract/extract-ghkm/ScfgRule.cpp
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
3
2018-06-08T08:36:27.000Z
2021-12-26T20:36:16.000Z
/*********************************************************************** Moses - statistical machine translation system Copyright (C) 2006-2011 University of Edinburgh This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "ScfgRule.h" #include "Node.h" #include "Subgraph.h" #include <algorithm> namespace Moses { namespace GHKM { ScfgRule::ScfgRule(const Subgraph &fragment) : m_sourceLHS("X", NonTerminal) , m_targetLHS(fragment.GetRoot()->GetLabel(), NonTerminal) , m_pcfgScore(fragment.GetPcfgScore()) { // Source RHS const std::set<const Node *> &leaves = fragment.GetLeaves(); std::vector<const Node *> sourceRHSNodes; sourceRHSNodes.reserve(leaves.size()); for (std::set<const Node *>::const_iterator p(leaves.begin()); p != leaves.end(); ++p) { const Node &leaf = **p; if (!leaf.GetSpan().empty()) { sourceRHSNodes.push_back(&leaf); } } std::sort(sourceRHSNodes.begin(), sourceRHSNodes.end(), PartitionOrderComp); // Build a mapping from target nodes to source-order indices, so that we // can construct the Alignment object later. std::map<const Node *, std::vector<int> > sourceOrder; m_sourceRHS.reserve(sourceRHSNodes.size()); int srcIndex = 0; for (std::vector<const Node *>::const_iterator p(sourceRHSNodes.begin()); p != sourceRHSNodes.end(); ++p, ++srcIndex) { const Node &sinkNode = **p; if (sinkNode.GetType() == TREE) { m_sourceRHS.push_back(Symbol("X", NonTerminal)); sourceOrder[&sinkNode].push_back(srcIndex); } else { assert(sinkNode.GetType() == SOURCE); m_sourceRHS.push_back(Symbol(sinkNode.GetLabel(), Terminal)); // Add all aligned target words to the sourceOrder map const std::vector<Node *> &parents(sinkNode.GetParents()); for (std::vector<Node *>::const_iterator q(parents.begin()); q != parents.end(); ++q) { if ((*q)->GetType() == TARGET) { sourceOrder[*q].push_back(srcIndex); } } } } // Target RHS + alignment std::vector<const Node *> targetLeaves; fragment.GetTargetLeaves(targetLeaves); m_alignment.reserve(targetLeaves.size()); // might be too much but that's OK m_targetRHS.reserve(targetLeaves.size()); for (std::vector<const Node *>::const_iterator p(targetLeaves.begin()); p != targetLeaves.end(); ++p) { const Node &leaf = **p; if (leaf.GetSpan().empty()) { // The node doesn't cover any source words, so we can only add // terminals to the target RHS (not a non-terminal). std::vector<std::string> targetWords(leaf.GetTargetWords()); for (std::vector<std::string>::const_iterator q(targetWords.begin()); q != targetWords.end(); ++q) { m_targetRHS.push_back(Symbol(*q, Terminal)); } } else if (leaf.GetType() == SOURCE) { // Do nothing } else { SymbolType type = (leaf.GetType() == TREE) ? NonTerminal : Terminal; m_targetRHS.push_back(Symbol(leaf.GetLabel(), type)); int tgtIndex = m_targetRHS.size()-1; std::map<const Node *, std::vector<int> >::iterator q(sourceOrder.find(&leaf)); assert(q != sourceOrder.end()); std::vector<int> &sourceNodes = q->second; for (std::vector<int>::iterator r(sourceNodes.begin()); r != sourceNodes.end(); ++r) { int srcIndex = *r; m_alignment.push_back(std::make_pair(srcIndex, tgtIndex)); } } } } int ScfgRule::Scope() const { int scope = 0; bool predIsNonTerm = false; if (m_sourceRHS[0].GetType() == NonTerminal) { ++scope; predIsNonTerm = true; } for (size_t i = 1; i < m_sourceRHS.size(); ++i) { bool isNonTerm = m_sourceRHS[i].GetType() == NonTerminal; if (isNonTerm && predIsNonTerm) { ++scope; } predIsNonTerm = isNonTerm; } if (predIsNonTerm) { ++scope; } return scope; } bool ScfgRule::PartitionOrderComp(const Node *a, const Node *b) { const Span &aSpan = a->GetSpan(); const Span &bSpan = b->GetSpan(); assert(!aSpan.empty() && !bSpan.empty()); return *(aSpan.begin()) < *(bSpan.begin()); } } // namespace GHKM } // namespace Moses
33.554795
85
0.635028
anshsarkar
5dc9027100b9729b1d99f263135cc6893f3370aa
758
hpp
C++
include/eve/function/operator.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
include/eve/function/operator.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
include/eve/function/operator.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #pragma once // **======================================================= // helper file to include all operators #include <eve/function/add.hpp> #include <eve/function/plus.hpp> #include <eve/function/sub.hpp> #include <eve/function/minus.hpp> #include <eve/function/div.hpp> #include <eve/function/rem.hpp> #include <eve/function/inc.hpp> #include <eve/function/dec.hpp> #include <eve/function/rshl.hpp> #include <eve/function/rshl.hpp>
36.095238
100
0.488127
orao
5dc95106d0d8836eb3ccd81f2f89ad1e45cd97a9
4,149
cpp
C++
nbr-mgr/src/nbr_mgr_main.cpp
open-switch/opx-nas-l3
c6fb3b1619bd09cebc60bd82120aa7c1a0557d58
[ "CC-BY-4.0" ]
1
2019-09-18T22:29:56.000Z
2019-09-18T22:29:56.000Z
nbr-mgr/src/nbr_mgr_main.cpp
open-switch/opx-nas-l3
c6fb3b1619bd09cebc60bd82120aa7c1a0557d58
[ "CC-BY-4.0" ]
18
2017-01-28T02:52:48.000Z
2021-06-11T04:31:29.000Z
nbr-mgr/src/nbr_mgr_main.cpp
open-switch/opx-nas-l3
c6fb3b1619bd09cebc60bd82120aa7c1a0557d58
[ "CC-BY-4.0" ]
13
2017-01-03T17:48:37.000Z
2019-01-09T21:42:49.000Z
/* * Copyright (c) 2018 Dell 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 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS * FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing * permissions and limitations under the License. */ /* * filename: nbr_mgr_main.cpp */ #include "nbr_mgr_main.h" #include "nbr_mgr_msgq.h" #include "std_thread_tools.h" #include <stdlib.h> #include <unistd.h> #include <iostream> #include <signal.h> /* signal() */ #include <systemd/sd-daemon.h> /* sd_notify() */ #include <stdbool.h> /* bool, true, false */ static std_thread_create_param_t nbr_mgr_resolve_thr; static std_thread_create_param_t nbr_mgr_delay_resolve_thr; static std_thread_create_param_t nbr_mgr_instant_resolve_thr; bool nbr_mgr_init() { /* Create message queues for nbr mgr threads communication */ if (nbr_mgr_msgq_create() == false) return false; /* Init CPS for sending/receiving the CPS messages with external modules like NAS-L3 */ if (nbr_mgr_cps_init() == false) return false; /* Init Process thread for processing all the nbr manager messages */ nbr_mgr_process_main(); /* Thread to process the messages from Q (posted by netlink thread (kernel) * and (CPS thread) NAS-L3) */ std_thread_init_struct(&nbr_mgr_resolve_thr); nbr_mgr_resolve_thr.name = "nbr_mgr_rslv"; nbr_mgr_resolve_thr.thread_function = (std_thread_function_t)nbr_mgr_resolve_main; if (std_thread_create(&nbr_mgr_resolve_thr)!=STD_ERR_OK) { return false; } /* Thread to read message from delay resolution Q (pushed by process thread) and * on delay time expiry, remove the blackhole in the NPU thru NAS-L3 to control * the DoS attack with the invalid destinations */ std_thread_init_struct(&nbr_mgr_delay_resolve_thr); nbr_mgr_delay_resolve_thr.name = "nbr_mgr_drslv"; nbr_mgr_delay_resolve_thr.thread_function = (std_thread_function_t)nbr_mgr_delay_resolve_main; if (std_thread_create(&nbr_mgr_delay_resolve_thr)!=STD_ERR_OK) { return false; } /* Thread to process the messages instantly (instead of rate-limit) from Q to get the response * from kernel quickly with ARP/Nbr failed state in the interface oper. down scenario. */ std_thread_init_struct(&nbr_mgr_instant_resolve_thr); nbr_mgr_instant_resolve_thr.name = "nbr_mgr_irslv"; nbr_mgr_instant_resolve_thr.thread_function = (std_thread_function_t)nbr_mgr_instant_resolve_main; if (std_thread_create(&nbr_mgr_instant_resolve_thr)!=STD_ERR_OK) { return false; } #if 0 /* Enable this if netlink events get-all is supported in the NAS-linux */ /* Get all the NHs to be resolved from NAS-L3 */ nbr_mgr_get_all_nh(HAL_INET4_FAMILY); nbr_mgr_get_all_nh(HAL_INET6_FAMILY); #endif return true; } volatile static bool shutdwn = false; /************************************************************************ * * Name: sigterm_hdlr * * This function is to handle the SIGTERM signal * * Input: Integer signo * * Return Values: None * ------------- * ************************************************************************/ static void sigterm_hdlr(int signo) { /* Avoid system calls at all cost */ shutdwn = true; } /* Nbr Mgr process entry function */ int main() { (void)signal(SIGTERM, sigterm_hdlr); if (!nbr_mgr_init()) { exit(1); } /* Service is in ready state */ sd_notify(0, "READY=1"); /* @@TODO threads join to be done */ while (!shutdwn) { pause(); } /* Let systemd know we got the shutdwn request * and that we're in the process of shutting down */ sd_notify(0, "STOPPING=1"); exit(EXIT_SUCCESS); }
34.289256
102
0.687154
open-switch
5dca8957b0adefb0f97ea423c205613b29fe073e
2,170
cpp
C++
src/common/port/gs_syscall_lock.cpp
opengauss-mirror/openGauss-graph
6beb138fd00abdbfddc999919f90371522118008
[ "MulanPSL-1.0" ]
360
2020-06-30T14:47:34.000Z
2022-03-31T15:21:53.000Z
src/common/port/gs_syscall_lock.cpp
opengauss-mirror/openGauss-graph
6beb138fd00abdbfddc999919f90371522118008
[ "MulanPSL-1.0" ]
4
2020-06-30T15:09:16.000Z
2020-07-14T06:20:03.000Z
src/common/port/gs_syscall_lock.cpp
opengauss-mirror/openGauss-graph
6beb138fd00abdbfddc999919f90371522118008
[ "MulanPSL-1.0" ]
133
2020-06-30T14:47:36.000Z
2022-03-25T15:29:00.000Z
/* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. * ------------------------------------------------------------------------- * * gs_syscall_lock.cpp * * IDENTIFICATION * src/common/port/gs_syscall_lock.cpp * * ------------------------------------------------------------------------- */ #include "utils/syscall_lock.h" #include "c.h" /* * syscall lock, should not be TLS */ syscalllock getpwuid_lock; syscalllock env_lock; syscalllock dlerror_lock; syscalllock kerberos_conn_lock; syscalllock read_cipher_lock; /* * @Description: Atomic set val into *ptr in a 32-bit address, and return the previous pointed by ptr * @IN ptr: int32 pointer * @IN val: value to set * @Return: old value * @See also: */ #ifndef WIN32 int32 gs_syscall_atomic_test_and_set(volatile int32* ptr, int32 val) { int32 oldValue = __sync_lock_test_and_set(ptr, val); return oldValue; } /* * @Description: Atomic increment in a 32-bit address, and return the incremented value. * @IN ptr: int32 pointer * @IN inc: increase value * @Return: new value * @See also: */ int32 gs_syscall_atomic_add_32(volatile int32* ptr, int32 inc) { volatile int32 newValue = 0; int32 oldValue = __sync_fetch_and_add(ptr, inc); newValue = oldValue + inc; return newValue; } /* * @Description: Atomic increment in a 64-bit address, and return the incremented value. * @IN ptr: int64 pointer * @IN inc: increase value * @Return: new value * @See also: */ int64 gs_syscall_atomic_add_64(int64* ptr, int64 inc) { volatile int64 newValue = 0; int64 oldValue = __sync_fetch_and_add(ptr, inc); newValue = oldValue + inc; return newValue; } #endif
25.529412
101
0.66129
opengauss-mirror
5dcb6f415d3d60d3f591f35cd1f585a5ae2cadc7
1,596
cpp
C++
crnlib/crn_checksum.cpp
HugoPeters/crunch
44c8402e24441c7524ca364941fd224ab3b971e9
[ "Zlib" ]
478
2015-01-04T16:59:53.000Z
2022-03-07T20:28:07.000Z
crnlib/crn_checksum.cpp
HugoPeters/crunch
44c8402e24441c7524ca364941fd224ab3b971e9
[ "Zlib" ]
83
2015-01-15T21:45:06.000Z
2021-11-08T11:01:48.000Z
crnlib/crn_checksum.cpp
HugoPeters/crunch
44c8402e24441c7524ca364941fd224ab3b971e9
[ "Zlib" ]
175
2015-01-04T03:30:39.000Z
2020-01-27T17:08:14.000Z
// File: crn_checksum.cpp #include "crn_core.h" namespace crnlib { // From the public domain stb.h header. uint adler32(const void* pBuf, size_t buflen, uint adler32) { const uint8* buffer = static_cast<const uint8*>(pBuf); const unsigned long ADLER_MOD = 65521; unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16; size_t blocklen; unsigned long i; blocklen = buflen % 5552; while (buflen) { for (i=0; i + 7 < blocklen; i += 8) { s1 += buffer[0], s2 += s1; s1 += buffer[1], s2 += s1; s1 += buffer[2], s2 += s1; s1 += buffer[3], s2 += s1; s1 += buffer[4], s2 += s1; s1 += buffer[5], s2 += s1; s1 += buffer[6], s2 += s1; s1 += buffer[7], s2 += s1; buffer += 8; } for (; i < blocklen; ++i) s1 += *buffer++, s2 += s1; s1 %= ADLER_MOD, s2 %= ADLER_MOD; buflen -= blocklen; blocklen = 5552; } return (s2 << 16) + s1; } uint16 crc16(const void* pBuf, size_t len, uint16 crc) { crc = ~crc; const uint8* p = reinterpret_cast<const uint8*>(pBuf); while (len) { const uint16 q = *p++ ^ (crc >> 8); crc <<= 8U; uint16 r = (q >> 4) ^ q; crc ^= r; r <<= 5U; crc ^= r; r <<= 7U; crc ^= r; len--; } return static_cast<uint16>(~crc); } } // namespace crnlib
24.9375
63
0.43609
HugoPeters
5dcbdd5bf5ae328f67ff8dc9898c6ee5ad78fa67
3,407
cpp
C++
libs/image/color_ops.cpp
kdt3rd/gecko
756a4e4587eb5023495294d9b6c6d80ebd79ebde
[ "MIT" ]
15
2017-10-18T05:08:16.000Z
2022-02-02T11:01:46.000Z
libs/image/color_ops.cpp
kdt3rd/gecko
756a4e4587eb5023495294d9b6c6d80ebd79ebde
[ "MIT" ]
null
null
null
libs/image/color_ops.cpp
kdt3rd/gecko
756a4e4587eb5023495294d9b6c6d80ebd79ebde
[ "MIT" ]
1
2018-11-10T03:12:57.000Z
2018-11-10T03:12:57.000Z
// SPDX-License-Identifier: MIT // Copyright contributors to the gecko project. #include "color_ops.h" #include "threading.h" #include <color/color.h> #include <sstream> //////////////////////////////////////// namespace color { engine::hash &operator<<( engine::hash &h, const state &p ); /// \todo { do something smarter (fewer memory allocs) here than serialize to a string } engine::hash &operator<<( engine::hash &h, const state &p ) { std::stringstream tmp; tmp << p; h << tmp.str(); return h; } } // namespace color //////////////////////////////////////// namespace image { //////////////////////////////////////// static void colorspace_line( size_t, int s, int e, image_buf & ret, const image_buf & src, const color::state &from, const color::state &to ) { plane & xOut = ret[0]; plane & yOut = ret[1]; plane & zOut = ret[2]; const plane &xIn = src[0]; const plane &yIn = src[1]; const plane &zIn = src[2]; int w = ret.width(); for ( int y = s; y < e; ++y ) { float * xLine = xOut.line( y ); float * yLine = yOut.line( y ); float * zLine = zOut.line( y ); const float *xInLine = xIn.line( y ); const float *yInLine = yIn.line( y ); const float *zInLine = zIn.line( y ); for ( int x = 0; x < w; ++x ) { float xV = xInLine[x]; float yV = yInLine[x]; float zV = zInLine[x]; /// \todo { extract the logic inside here out to a higher level... } color::convert( xV, yV, zV, from, to, 32 ); xLine[x] = xV; yLine[x] = yV; zLine[x] = zV; } for ( size_t i = 3; i < ret.size(); ++i ) std::copy( src[i].line( y ), src[i].line( y ) + w, ret[i].line( y ) ); } } //////////////////////////////////////// static image_buf compute_colorspace( const image_buf &a, color::state from, color::state to ) { image_buf ret; for ( size_t i = 0; i != a.size(); ++i ) ret.add_plane( plane( a.x1(), a.y1(), a.x2(), a.y2() ) ); threading::get().dispatch( std::bind( colorspace_line, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::ref( ret ), std::cref( a ), std::cref( from ), std::cref( to ) ), a.y1(), a.height() ); return ret; } //////////////////////////////////////// image_buf colorspace( const image_buf &a, const color::state &from, const color::state &to ) { if ( a.size() < 3 ) throw std::logic_error( "Attempt to convert color space on an image with fewer than 3 planes" ); engine::dimensions d = a.dims(); d.planes = static_cast<engine::dimensions::value_type>( a.size() ); d.images = 1; return image_buf( "i.colorspace", d, a, from, to ); } //////////////////////////////////////// void add_color_ops( engine::registry &r ) { using namespace engine; r.register_constant<color::state>(); // we will just do a threaded op so we can optimize the from / to operations applied once r.add( op( "i.colorspace", compute_colorspace, op::threaded ) ); } } // namespace image
26.207692
93
0.487526
kdt3rd
5dd1174a5b97fe10eb3ec2729a3225b446f3c65e
13,323
cpp
C++
src/kernel/Version.cpp
PHP-OPEN-HUB/polarphp
70ff4046e280fd99d718d4761686168fa8012aa5
[ "PHP-3.01" ]
null
null
null
src/kernel/Version.cpp
PHP-OPEN-HUB/polarphp
70ff4046e280fd99d718d4761686168fa8012aa5
[ "PHP-3.01" ]
null
null
null
src/kernel/Version.cpp
PHP-OPEN-HUB/polarphp
70ff4046e280fd99d718d4761686168fa8012aa5
[ "PHP-3.01" ]
null
null
null
//===--- Version.cpp - Swift Version Number -------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // //===----------------------------------------------------------------------===// // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // This source file is part of the polarphp.org open source project // // Copyright (c) 2017 - 2019 polarphp software foundation // Copyright (c) 2017 - 2019 zzu_softboy <zzu_softboy@163.com> // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://polarphp.org/LICENSE.txt for license information // See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors // // Created by polarboy on 2019/04/26. //===----------------------------------------------------------------------===// // // This file defines several version-related utility functions for polarphp. // //===----------------------------------------------------------------------===// #include "polarphp/basic/CharInfo.h" #include "polarphp/basic/adt/SmallString.h" #include "polarphp/basic/adt/StringExtras.h" #include "polarphp/utils/RawOutStream.h" #include "polarphp/kernel/Version.h" #include "polarphp/ast/DiagnosticsParse.h" #include <vector> #define TOSTR2(X) #X #define TOSTR(X) TOSTR2(X) #ifdef POLAR_VERSION_PATCHLEVEL /// Helper macro for POLAR_VERSION_STRING. #define POLAR_MAKE_VERSION_STRING(X, Y, Z) TOSTR(X) "." TOSTR(Y) "." TOSTR(Z) /// A string that describes the Swift version number, e.g., "1.0". #define POLAR_VERSION_STRING \ POLAR_MAKE_VERSION_STRING(POLAR_VERSION_MAJOR, POLAR_VERSION_MINOR, \ POLAR_VERSION_PATCHLEVEL) #else /// Helper macro for POLAR_VERSION_STRING. #define POLAR_MAKE_VERSION_STRING(X, Y) TOSTR(X) "." TOSTR(Y) /// A string that describes the Swift version number, e.g., "1.0". #define POLAR_VERSION_STRING \ POLAR_MAKE_VERSION_STRING(POLAR_VERSION_MAJOR, POLAR_VERSION_MINOR) #endif namespace polar::version { using polar::utils::RawOutStream; using polar::utils::RawStringOutStream; using polar::utils::RawSvectorOutStream; using polar::parser::SourceLoc; using polar::parser::SourceRange; using polar::basic::SmallVectorImpl; using polar::basic::SmallString; /// Print a string of the form "LLVM xxxxx, Clang yyyyy, Swift zzzzz", /// where each placeholder is the revision for the associated repository. //static void print_full_revision_string(RawOutStream &out) //{ //} static void split_version_components( SmallVectorImpl<std::pair<StringRef, SourceRange>> &splitComponents, StringRef &versionString, SourceLoc loc, bool skipQuote = false) { SourceLoc start = (loc.isValid() && skipQuote) ? loc.getAdvancedLoc(1) : loc; SourceLoc end = start; // Split the version string into tokens separated by the '.' character. while (!versionString.empty()) { StringRef SplitComponent, Rest; std::tie(SplitComponent, Rest) = versionString.split('.'); if (loc.isValid()) { end = end.getAdvancedLoc(SplitComponent.size()); } auto range = loc.isValid() ? SourceRange(start, end) : SourceRange(); if (loc.isValid()) { end = end.getAdvancedLoc(1); } start = end; splitComponents.push_back({SplitComponent, range}); versionString = Rest; } } std::optional<Version> Version::parseCompilerVersionString( StringRef versionString, SourceLoc loc, DiagnosticEngine *diags) { Version CV; SmallString<16> digits; RawSvectorOutStream OS(digits); SmallVector<std::pair<StringRef, SourceRange>, 5> splitComponents; split_version_components(splitComponents, versionString, loc, /*skipQuote=*/true); // uint64_t componentNumber; bool isValidVersion = true; // auto checkVersionComponent = [&](unsigned Component, SourceRange range) { // unsigned limit = CV.m_components.empty() ? 9223371 : 999; // if (Component > limit) { // if (diags) // diags->diagnose(range.start, // polar::ast::diag::compiler_version_component_out_of_range, limit); // isValidVersion = false; // } // }; // for (size_t i = 0; i < splitComponents.size(); ++i) { // StringRef SplitComponent; // SourceRange range; // std::tie(SplitComponent, range) = splitComponents[i]; // // Version components can't be empty. // if (SplitComponent.empty()) { // if (diags) // diags->diagnose(range.start, diag::empty_version_component); // isValidVersion = false; // continue; // } // // The second version component isn't used for comparison. // if (i == 1) { // if (!SplitComponent.equals("*")) { // if (diags) // diags->diagnose(range.start, diag::unused_compiler_version_component) // .fixItReplaceChars(range.start, range.end, "*"); // } // CV.m_components.push_back(0); // continue; // } // // All other version components must be numbers. // if (!SplitComponent.getAsInteger(10, componentNumber)) { // checkVersionComponent(componentNumber, range); // CV.m_components.push_back(componentNumber); // continue; // } else { // if (diags) // diags->diagnose(range.start, diag::version_component_not_number); // isValidVersion = false; // } // } // if (CV.m_components.size() > 5) { // if (diags) // diags->diagnose(loc, diag::compiler_version_too_many_components); // isValidVersion = false; // } return isValidVersion ? std::optional<Version>(CV) : std::nullopt; } std::optional<Version> Version::parseVersionString(StringRef versionString, SourceLoc loc, DiagnosticEngine *diags) { Version TheVersion; SmallString<16> digits; RawSvectorOutStream OS(digits); SmallVector<std::pair<StringRef, SourceRange>, 5> splitComponents; // Skip over quote character in string literal. // if (versionString.empty()) { // if (diags) // diags->diagnose(loc, diag::empty_version_string); // return None; // } split_version_components(splitComponents, versionString, loc, diags); // uint64_t componentNumber; bool isValidVersion = true; // for (size_t i = 0; i < splitComponents.size(); ++i) { // StringRef SplitComponent; // SourceRange range; // std::tie(SplitComponent, range) = splitComponents[i]; // // Version components can't be empty. // if (SplitComponent.empty()) { // if (diags) // diags->diagnose(range.start, diag::empty_version_component); // isValidVersion = false; // continue; // } // // All other version components must be numbers. // if (!SplitComponent.getAsInteger(10, componentNumber)) { // TheVersion.m_components.push_back(componentNumber); // continue; // } else { // if (diags) // diags->diagnose(range.start, // diag::version_component_not_number); // isValidVersion = false; // } // } return isValidVersion ? std::optional<Version>(TheVersion) : std::nullopt; } Version::Version(StringRef versionString, SourceLoc loc, DiagnosticEngine *diags) : Version(*parseVersionString(versionString, loc, diags)) {} Version Version::getCurrentCompilerVersion() { //#ifdef POLARPHP_VERSION // auto currentVersion = Version::parseVersionString( // POLARPHP_VERSION, SourceLoc(), nullptr); // assert(currentVersion.hasValue() && // "Embedded polarphp language version couldn't be parsed: '" // POLARPHP_VERSION // "'"); // return currentVersion.getValue(); //#else // return Version(); //#endif return Version(); } Version Version::getCurrentLanguageVersion() { #if POLAR_VERSION_PATCHLEVEL return {0, 1, 1}; #else return {0, 1}; #endif } RawOutStream &operator<<(RawOutStream &outStream, const Version &version) { if (version.empty()) { return outStream; } outStream << version[0]; for (size_t i = 1, e = version.size(); i != e; ++i) { outStream << '.' << version[i]; } return outStream; } std::string Version::preprocessorDefinition(StringRef macroName, ArrayRef<uint64_t> componentWeights) const { uint64_t versionConstant = 0; for (size_t i = 0, e = std::min(componentWeights.getSize(), m_components.size()); i < e; ++i) { versionConstant += componentWeights[i] * m_components[i]; } std::string define("-D"); RawStringOutStream(define) << macroName << '=' << versionConstant; // This isn't using stream.str() so that we get move semantics. return define; } Version::operator VersionTuple() const { switch (m_components.size()) { case 0: return VersionTuple(); case 1: return VersionTuple((unsigned)m_components[0]); case 2: return VersionTuple((unsigned)m_components[0], (unsigned)m_components[1]); case 3: return VersionTuple((unsigned)m_components[0], (unsigned)m_components[1], (unsigned)m_components[2]); case 4: case 5: return VersionTuple((unsigned)m_components[0], (unsigned)m_components[1], (unsigned)m_components[2], (unsigned)m_components[3]); default: polar_unreachable("polar::version::Version with 6 or more components"); } } std::optional<Version> Version::getEffectiveLanguageVersion() const { switch (size()) { case 0: return std::nullopt; case 1: break; case 2: // The only valid explicit language version with a minor // component is 4.2. if (m_components[0] == 4 && m_components[1] == 2) { break; } return std::nullopt; default: // We do not want to permit users requesting more precise effective language // versions since accepting such an argument promises more than we're able // to deliver. return std::nullopt; } // FIXME: When we switch to Swift 5 by default, the "4" case should return // a version newer than any released 4.x compiler, and the // "5" case should start returning getCurrentLanguageVersion. We should // also check for the presence of SWIFT_VERSION_PATCHLEVEL, and if that's // set apply it to the "3" case, so that Swift 4.0.1 will automatically // have a compatibility mode of 3.2.1. switch (m_components[0]) { case 4: // Version '4' on its own implies '4.1.50'. if (size() == 1) { return Version{4, 1, 50}; } // This should be true because of the check up above. assert(size() == 2 && m_components[0] == 4 && m_components[1] == 2); return Version{4, 2}; case 5: // static_assert(POLAR_VERSION_MAJOR == 5, // "getCurrentLanguageVersion is no longer correct here"); return Version::getCurrentLanguageVersion(); default: return std::nullopt; } } Version Version::asMajorVersion() const { if (empty()) { return {}; } Version res; res.m_components.push_back(m_components[0]); return res; } std::string Version::asAPINotesVersionString() const { // Other than for "4.2.x", map the Swift major version into // the API notes version for Swift. This has the effect of allowing // API notes to effect changes only on Swift major versions, // not minor versions. if (size() >= 2 && m_components[0] == 4 && m_components[1] == 2) { return "4.2"; } return polar::basic::itostr(m_components[0]); } bool operator>=(const class Version &lhs, const class Version &rhs) { // The empty compiler version represents the latest possible version, // usually built from the source repository. if (lhs.empty()) return true; auto n = std::max(lhs.size(), rhs.size()); for (size_t i = 0; i < n; ++i) { auto lv = i < lhs.size() ? lhs[i] : 0; auto rv = i < rhs.size() ? rhs[i] : 0; if (lv < rv) return false; else if (lv > rv) return true; } // Equality return true; } bool operator<(const class Version &lhs, const class Version &rhs) { return !(lhs >= rhs); } bool operator==(const class Version &lhs, const class Version &rhs) { auto n = std::max(lhs.size(), rhs.size()); for (size_t i = 0; i < n; ++i) { auto lv = i < lhs.size() ? lhs[i] : 0; auto rv = i < rhs.size() ? rhs[i] : 0; if (lv != rv) { return false; } } return true; } std::pair<unsigned, unsigned> retrieve_polarphp_numeric_version() { return { 0, 1 }; } std::string retrieve_polarphp_full_version(Version effectiveVersion) { return ""; } std::string retrieve_polarphp_revision() { return ""; } } // polar::version
31.201405
96
0.61953
PHP-OPEN-HUB
5dd14a1d5e434f04c1ee055a0d27bf099a7e7f5a
1,245
hpp
C++
sprout/numeric/dft/cxx14/spectrum.hpp
kevcadieux/Sprout
6b5addba9face0a6403e66e7db2aa94d87387f61
[ "BSL-1.0" ]
691
2015-01-15T18:52:23.000Z
2022-03-15T23:39:39.000Z
sprout/numeric/dft/cxx14/spectrum.hpp
kevcadieux/Sprout
6b5addba9face0a6403e66e7db2aa94d87387f61
[ "BSL-1.0" ]
22
2015-03-11T01:22:56.000Z
2021-03-29T01:51:45.000Z
sprout/numeric/dft/cxx14/spectrum.hpp
kevcadieux/Sprout
6b5addba9face0a6403e66e7db2aa94d87387f61
[ "BSL-1.0" ]
57
2015-03-11T07:52:29.000Z
2021-12-16T09:15:33.000Z
/*============================================================================= Copyright (c) 2011-2019 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_NUMERIC_DFT_CXX14_SPECTRUM_HPP #define SPROUT_NUMERIC_DFT_CXX14_SPECTRUM_HPP #include <sprout/config.hpp> #include <sprout/iterator/type_traits/is_iterator_of.hpp> #include <sprout/type_traits/enabler_if.hpp> #include <sprout/numeric/dft/cxx14/amplitude_spectrum.hpp> #include <sprout/numeric/dft/cxx14/phase_spectrum.hpp> namespace sprout { // // spectrum // template< typename InputIterator, typename OutputIterator, typename sprout::enabler_if<sprout::is_iterator_outputable<OutputIterator>::value>::type = sprout::enabler > inline SPROUT_CXX14_CONSTEXPR OutputIterator spectrum(InputIterator first, InputIterator last, OutputIterator result) { return sprout::amplitude_spectrum(first, last, result); } } // namespace sprout #endif // #ifndef SPROUT_NUMERIC_DFT_CXX14_SPECTRUM_HPP
38.90625
109
0.680321
kevcadieux
5dd25af28cae85b35d675bd16be94aaa95e5879c
2,892
cc
C++
chrome/browser/chromeos/frame/dom_browser_view.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-02-20T14:25:04.000Z
2019-12-13T13:58:28.000Z
chrome/browser/chromeos/frame/dom_browser_view.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-07-25T09:37:22.000Z
2017-08-04T07:18:56.000Z
chrome/browser/chromeos/frame/dom_browser_view.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2020-01-12T00:55:53.000Z
2020-11-04T06:36:41.000Z
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/frame/dom_browser_view.h" #include "chrome/browser/chromeos/frame/dom_browser_view_layout.h" #include "ui/gfx/rect.h" #include "views/widget/widget.h" namespace chromeos { // DOMBrowserView, public ------------------------------------------------------ DOMBrowserView::DOMBrowserView(Browser* browser) : chromeos::BrowserView(browser) {} DOMBrowserView::~DOMBrowserView() {} // static BrowserWindow* DOMBrowserView::CreateDOMWindow(Browser* browser) { DOMBrowserView* view = new DOMBrowserView(browser); BrowserFrame::Create(view, browser->profile()); return view; } void DOMBrowserView::WindowMoveOrResizeStarted() {} gfx::Rect DOMBrowserView::GetToolbarBounds() const { return gfx::Rect(); } int DOMBrowserView::GetTabStripHeight() const { return 0; } bool DOMBrowserView::IsTabStripVisible() const { return false; } bool DOMBrowserView::AcceleratorPressed(const views::Accelerator& accelerator) { return false; } void DOMBrowserView::SetStarredState(bool is_starred) {} LocationBar* DOMBrowserView::GetLocationBar() const { return NULL; } void DOMBrowserView::SetFocusToLocationBar(bool select_all) {} void DOMBrowserView::UpdateReloadStopState(bool is_loading, bool force) {} void DOMBrowserView::UpdateToolbar(TabContentsWrapper* contents, bool should_restore_state) {} void DOMBrowserView::FocusToolbar() {} void DOMBrowserView::FocusAppMenu() {} void DOMBrowserView::ShowBookmarkBubble(const GURL& url, bool already_bookmarked) {} void DOMBrowserView::ShowAppMenu() {} LocationBarView* DOMBrowserView::GetLocationBarView() const { return NULL; } ToolbarView* DOMBrowserView::GetToolbarView() const { return NULL; } bool DOMBrowserView::ShouldShowOffTheRecordAvatar() const { return false; } bool DOMBrowserView::GetAcceleratorForCommandId(int command_id, ui::Accelerator* accelerator) { return GetWidget()->GetAccelerator(command_id, accelerator); } bool DOMBrowserView::IsToolbarVisible() const { return false; } // DOMBrowserView, protected --------------------------------------------------- void DOMBrowserView::GetAccessiblePanes( std::vector<AccessiblePaneView*>* panes) {} void DOMBrowserView::PaintChildren(gfx::Canvas* canvas) { views::ClientView::PaintChildren(canvas); } void DOMBrowserView::InitTabStrip(TabStripModel* model) {} views::LayoutManager* DOMBrowserView::CreateLayoutManager() const { return new DOMBrowserViewLayout; } ToolbarView* DOMBrowserView::CreateToolbar() const { return NULL; } void DOMBrowserView::LoadingAnimationCallback() {} } // namespace chromeos
26.290909
80
0.713347
SlimKatLegacy
5dd7a523db90223a3c025dd6f203d0d8374852dc
52
cc
C++
vector/Vector.cc
me701/cpp_classes
302d10855069bbb818d317cc98d21ae9d7f8f3eb
[ "MIT" ]
null
null
null
vector/Vector.cc
me701/cpp_classes
302d10855069bbb818d317cc98d21ae9d7f8f3eb
[ "MIT" ]
null
null
null
vector/Vector.cc
me701/cpp_classes
302d10855069bbb818d317cc98d21ae9d7f8f3eb
[ "MIT" ]
null
null
null
#include "Vector.hh" // Member definitions go here
13
29
0.730769
me701
5ddf649cbcc500b7ebfe96f1e6cc58a638ac0ebf
4,661
cpp
C++
src/Devantech_CMPS11.cpp
sgparry/Devantech_Compass
d49fea0d03ff2adf0c9e527c81bab9ddfd728356
[ "MIT" ]
null
null
null
src/Devantech_CMPS11.cpp
sgparry/Devantech_Compass
d49fea0d03ff2adf0c9e527c81bab9ddfd728356
[ "MIT" ]
null
null
null
src/Devantech_CMPS11.cpp
sgparry/Devantech_Compass
d49fea0d03ff2adf0c9e527c81bab9ddfd728356
[ "MIT" ]
null
null
null
/*********************************************************************************** * Copyright (c) 2018 EduMake Limited and Stephen Parry (sgparry@mainscreen.com) * See file LICENSE for further details * MIT license, this line and all text above must be included in any redistribution ***********************************************************************************/ // Derived from code by Dirk Grappendorf (www.grappendorf.net) // for the SRF02 sensor. #if ARDUINO >= 100 #include "Arduino.h" #define WIRE_WRITE Wire.write #define WIRE_READ Wire.read #else #include "WProgram.h" #define WIRE_WRITE Wire.send #define WIRE_READ Wire.receive #endif #include "Wire.h" #include "Devantech_CMPS11.h" const int REG_MAGX_HIGH = 6; const int REG_MAGX_LOW = 7; const int REG_MAGY_HIGH = 8; const int REG_MAGY_LOW = 9; const int REG_MAGZ_HIGH = 10; const int REG_MAGZ_LOW = 11; const int REG_ACCX_HIGH = 12; const int REG_ACCX_LOW = 13; const int REG_ACCY_HIGH = 14; const int REG_ACCY_LOW = 15; const int REG_ACCZ_HIGH = 16; const int REG_ACCZ_LOW = 17; const int REG_GYRX_HIGH = 18; const int REG_GYRX_LOW = 19; const int REG_GYRY_HIGH = 20; const int REG_GYRY_LOW = 21; const int REG_GYRZ_HIGH = 22; const int REG_GYRZ_LOW = 23; const int REG_TEMP_HIGH = 24; const int REG_TEMP_LOW = 25; const int REG_PITCH_NK = 26; const int REG_ROLL_NK = 27; const int REG_CMD = 0; int16_t Devantech_CMPS11::magX() { return (int16_t)regReadWord(REG_MAGX_HIGH); } int16_t Devantech_CMPS11::magY() { return (int16_t)regReadWord(REG_MAGY_HIGH); } int16_t Devantech_CMPS11::magZ() { return (int16_t)regReadWord(REG_MAGZ_HIGH); } int16_t Devantech_CMPS11::accX() { return (int16_t)regReadWord(REG_ACCX_HIGH); } int16_t Devantech_CMPS11::accY() { return (int16_t)regReadWord(REG_ACCY_HIGH); } int16_t Devantech_CMPS11::accZ() { return (int16_t)regReadWord(REG_ACCZ_HIGH); } int16_t Devantech_CMPS11::gyrX() { return (int16_t)regReadWord(REG_GYRX_HIGH); } int16_t Devantech_CMPS11::gyrY() { return (int16_t)regReadWord(REG_GYRY_HIGH); } int16_t Devantech_CMPS11::gyrZ() { return (int16_t)regReadWord(REG_GYRZ_HIGH); } int8_t Devantech_CMPS11::pitchNK() { return (int8_t)(regReadByte(REG_PITCH_NK)); } int8_t Devantech_CMPS11::rollNK() { return (int8_t)(regReadByte(REG_ROLL_NK)); } int16_t Devantech_CMPS11::temp() { return (int16_t)(regReadWord(REG_TEMP_HIGH)); } Devantech_Compass::CompassStatus Devantech_CMPS11::doCalibration(CompassPoint cp) { if( regWriteByteFrame(REG_CMD,0xF0,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR; if( regWriteByteFrame(REG_CMD,0xF5,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR; if( regWriteByteFrame(REG_CMD,0xF7,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR; return CS_READY_COMMIT; } Devantech_Compass::CompassStatus Devantech_CMPS11::doCalibration3D() { if( regWriteByteFrame(REG_CMD,0xF0,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR; if( regWriteByteFrame(REG_CMD,0xF5,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR; if( regWriteByteFrame(REG_CMD,0xF6,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR; return CS_READY_COMMIT; } Devantech_Compass::CompassStatus Devantech_CMPS11::commitCalibration() { if( regWriteByteFrame(REG_CMD,0xF8,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR; return CS_ALL_COMPLETE; } Devantech_Compass::CompassStatus Devantech_CMPS11::resetCalibration() { if( regWriteByteFrame(REG_CMD,0x20,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR; if( regWriteByteFrame(REG_CMD,0x2A,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR; if( regWriteByteFrame(REG_CMD,0x60,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR; return CS_ALL_COMPLETE; } Devantech_Compass::CompassStatus Devantech_CMPS11::configureDeviceId(uint8_t newDeviceId) { if( regWriteByteFrame(REG_CMD,0xA0,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR; if( regWriteByteFrame(REG_CMD,0xAA,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR; if( regWriteByteFrame(REG_CMD,0xA5,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR; if( regWriteByteFrame(REG_CMD,newDeviceId << 1,100) != Devantech_Compass::CS_COMMS_OK) return CS_COMMS_ERROR; this->deviceId = newDeviceId; return CS_ALL_COMPLETE; } Devantech_Compass::CompassCaps Devantech_CMPS11::getCaps() { return CompassCaps( CC_CALIBRATE | CC_FACTORY_RESET | CC_CALIBRATE_3D | CC_PITCH_AND_ROLL | CC_MAG_XYZ | CC_ACC_XYZ | CC_GYRO_XYZ | CC_TEMP | CC_PITCH_AND_ROLL_NK | CC_CONFIG_DEVICE_ID); }
29.314465
111
0.750483
sgparry
5de3630a88b02043850ea8c06e3e3203199c0546
214
cpp
C++
reverse_strings.cpp
HeyIamJames/Learning-C-
623fad8cb50d71e7404f270f965c8915f8a02c64
[ "MIT" ]
null
null
null
reverse_strings.cpp
HeyIamJames/Learning-C-
623fad8cb50d71e7404f270f965c8915f8a02c64
[ "MIT" ]
null
null
null
reverse_strings.cpp
HeyIamJames/Learning-C-
623fad8cb50d71e7404f270f965c8915f8a02c64
[ "MIT" ]
null
null
null
void reverseChar(char* str) { const size_t len = strlen(str); for(size_t i=0; i<len/2; i++) swap(str[i], str[len-i-1]); } void reverseChar(char* str) { std::reverse(str, str + strlen(str)); }
19.454545
41
0.584112
HeyIamJames
5de59cb07f002d870ba38d424909ae56214de11f
6,492
hpp
C++
src/tpl/simpool/DynamicPoolAllocator.hpp
nanzifan/Umpire-edit
990895b527bef0716aaa0fbb0c0f2017e8e15882
[ "MIT" ]
null
null
null
src/tpl/simpool/DynamicPoolAllocator.hpp
nanzifan/Umpire-edit
990895b527bef0716aaa0fbb0c0f2017e8e15882
[ "MIT" ]
null
null
null
src/tpl/simpool/DynamicPoolAllocator.hpp
nanzifan/Umpire-edit
990895b527bef0716aaa0fbb0c0f2017e8e15882
[ "MIT" ]
null
null
null
#ifndef _DYNAMICPOOLALLOCATOR_HPP #define _DYNAMICPOOLALLOCATOR_HPP #include <cstddef> #include <cassert> #include "umpire/tpl/simpool/StdAllocator.hpp" #include "umpire/tpl/simpool/FixedPoolAllocator.hpp" #include "umpire/strategy/AllocationStrategy.hpp" template <class IA = StdAllocator> class DynamicPoolAllocator { protected: struct Block { char *data; std::size_t size; bool isHead; Block *next; }; // Allocator for the underlying data typedef FixedPoolAllocator<struct Block, IA, (1<<6)> BlockAlloc; BlockAlloc blockAllocator; // Start of the nodes of used and free block lists struct Block *usedBlocks; struct Block *freeBlocks; // Total size allocated (bytes) std::size_t totalBytes; // Allocated size (bytes) std::size_t allocBytes; // Minimum size for allocations std::size_t minBytes; // Pointer to our allocator's allocation strategy std::shared_ptr<umpire::strategy::AllocationStrategy> allocator; // Search the list of free blocks and return a usable one if that exists, else NULL void findUsableBlock(struct Block *&best, struct Block *&prev, std::size_t size) { best = prev = NULL; for ( struct Block *iter = freeBlocks, *iterPrev = NULL ; iter ; iter = iter->next ) { if ( iter->size >= size && (!best || iter->size < best->size) ) { best = iter; prev = iterPrev; } iterPrev = iter; } } inline std::size_t alignmentAdjust(const std::size_t size) { const std::size_t AlignmentBoundary = 16; return std::size_t (size + (AlignmentBoundary-1)) & ~(AlignmentBoundary-1); } // Allocate a new block and add it to the list of free blocks void allocateBlock(struct Block *&curr, struct Block *&prev, const std::size_t size) { const std::size_t sizeToAlloc = std::max(alignmentAdjust(size), minBytes); curr = prev = NULL; void *data = NULL; // Allocate data data = allocator->allocate(sizeToAlloc); totalBytes += sizeToAlloc; assert(data); // Find next and prev such that next->data is still smaller than data (keep ordered) struct Block *next; for ( next = freeBlocks; next && next->data < data; next = next->next ) { prev = next; } // Allocate the block curr = (struct Block *) blockAllocator.allocate(); if (!curr) return; curr->data = static_cast<char *>(data); curr->size = sizeToAlloc; curr->isHead = true; curr->next = next; // Insert if (prev) prev->next = curr; else freeBlocks = curr; } void splitBlock(struct Block *&curr, struct Block *&prev, const std::size_t size) { struct Block *next; const std::size_t alignedsize = alignmentAdjust(size); if ( curr->size == size || curr->size == alignedsize ) { // Keep it next = curr->next; } else { // Split the block std::size_t remaining = curr->size - alignedsize; struct Block *newBlock = (struct Block *) blockAllocator.allocate(); if (!newBlock) return; newBlock->data = curr->data + alignedsize; newBlock->size = remaining; newBlock->isHead = false; newBlock->next = curr->next; next = newBlock; curr->size = alignedsize; } if (prev) prev->next = next; else freeBlocks = next; } void releaseBlock(struct Block *curr, struct Block *prev) { assert(curr != NULL); if (prev) prev->next = curr->next; else usedBlocks = curr->next; // Find location to put this block in the freeBlocks list prev = NULL; for ( struct Block *temp = freeBlocks ; temp && temp->data < curr->data ; temp = temp->next ) { prev = temp; } // Keep track of the successor struct Block *next = prev ? prev->next : freeBlocks; // Check if prev and curr can be merged if ( prev && prev->data + prev->size == curr->data && !curr->isHead ) { prev->size = prev->size + curr->size; blockAllocator.deallocate(curr); // keep data curr = prev; } else if (prev) { prev->next = curr; } else { freeBlocks = curr; } // Check if curr and next can be merged if ( next && curr->data + curr->size == next->data && !next->isHead ) { curr->size = curr->size + next->size; curr->next = next->next; blockAllocator.deallocate(next); // keep data } else { curr->next = next; } } void freeAllBlocks() { // Release the used blocks while(usedBlocks) { releaseBlock(usedBlocks, NULL); } // Release the unused blocks while(freeBlocks) { assert(freeBlocks->isHead); allocator->deallocate(freeBlocks->data); totalBytes -= freeBlocks->size; struct Block *curr = freeBlocks; freeBlocks = freeBlocks->next; blockAllocator.deallocate(curr); } } public: DynamicPoolAllocator( std::shared_ptr<umpire::strategy::AllocationStrategy> strat, const std::size_t _minBytes = (1 << 8)) : blockAllocator(), usedBlocks(NULL), freeBlocks(NULL), totalBytes(0), allocBytes(0), minBytes(_minBytes), allocator(strat) { } ~DynamicPoolAllocator() { freeAllBlocks(); } void *allocate(std::size_t size) { struct Block *best, *prev; findUsableBlock(best, prev, size); // Allocate a block if needed if (!best) allocateBlock(best, prev, size); assert(best); // Split the free block splitBlock(best, prev, size); // Push node to the list of used nodes best->next = usedBlocks; usedBlocks = best; // Increment the allocated size allocBytes += size; // Return the new pointer return usedBlocks->data; } void deallocate(void *ptr) { assert(ptr); // Find the associated block struct Block *curr = usedBlocks, *prev = NULL; for ( ; curr && curr->data != ptr; curr = curr->next ) { prev = curr; } if (!curr) return; // Remove from allocBytes allocBytes -= curr->size; // Release it releaseBlock(curr, prev); } std::size_t allocatedSize() const { return allocBytes; } std::size_t totalSize() const { return totalBytes + blockAllocator.totalSize(); } std::size_t numFreeBlocks() const { std::size_t nb = 0; for (struct Block *temp = freeBlocks; temp; temp = temp->next) nb++; return nb; } std::size_t numUsedBlocks() const { std::size_t nb = 0; for (struct Block *temp = usedBlocks; temp; temp = temp->next) nb++; return nb; } }; #endif
26.606557
99
0.628928
nanzifan
5de9de20e00b94b067e4445dd7c48b5a84932e64
4,185
hpp
C++
include/itp/core_bits/core_fileio.hpp
TING2938/Gmx2020PostAnalysis
0859383946c05c7424adb1ffa72fd2f8066ce850
[ "MIT" ]
4
2021-11-23T15:02:13.000Z
2022-03-21T16:32:09.000Z
include/itp/core_bits/core_fileio.hpp
jianghuili/Gmx2020PostAnalysis
0859383946c05c7424adb1ffa72fd2f8066ce850
[ "MIT" ]
null
null
null
include/itp/core_bits/core_fileio.hpp
jianghuili/Gmx2020PostAnalysis
0859383946c05c7424adb1ffa72fd2f8066ce850
[ "MIT" ]
1
2021-11-23T15:01:49.000Z
2021-11-23T15:01:49.000Z
#ifndef __CORE_FILEIO_HPP__ #define __CORE_FILEIO_HPP__ #include <fstream> #include "../core" namespace itp { namespace inner { inline bool is_comment(std::string& line, std::string& comments) { auto np = line.find_first_not_of(" "); return np == std::string::npos || (comments.size() != 0 && comments.find_first_of(line[np]) != std::string::npos); } } /** * @brief 读取文本数据文件 * @tparam T 数据标量类型 * @param is 文件流 * @param nrows 行数,默认自动确定 * @param ncols 列数,默认自动确定 * @param comments 注释字符 * @param skiprows 跳过开头行数 * @return 数据矩阵 */ template <typename T = double> Eigen::Array<T, Dynamic, Dynamic> loadtxt(std::istream& is, int nrows = Dynamic, int ncols = Dynamic, std::string comments = "#@", int skiprows = 0) { std::string line; T buff; std::stringstream ss; for (int i = 0; i != skiprows; ++i) std::getline(is, line); if (ncols == Dynamic) { ncols = 0; while (std::getline(is, line)) if (!inner::is_comment(line, comments)) { ss.str(line); while (ss >> buff) ++ncols; break; } } else { std::getline(is, line); } if (nrows == Dynamic) { std::vector<T> vec; do { if (!inner::is_comment(line, comments)) { ss.clear(); ss.str(line); for (int i = 0; i != ncols; ++i) { ss >> buff; vec.push_back(buff); } } } while (std::getline(is, line)); Eigen::Array<T, Dynamic, Dynamic> res(vec.size() / ncols, ncols); for (int i = 0; i != res.rows(); ++i) { for (int j = 0; j != res.cols(); ++j) { res(i, j) = vec[ncols * i + j]; } } return res; } Eigen::Array<T, Dynamic, Dynamic> data(nrows, ncols); int i = 0; do { if (!inner::is_comment(line, comments)) { ss.clear(); ss.str(line); for (int j = 0; j != ncols; ++j) ss >> data(i, j); ++i; } } while (i != nrows && std::getline(is, line)); return data; } /** * @brief 读取文本数据文件 * @tparam T 数据标量类型 * @param fileName 文件名称 * @param nrows 行数,默认自动确定 * @param ncols 列数,默认自动确定 * @param comments 注释字符 * @param skiprows 跳过开头行数 * @return 数据矩阵 */ template <typename T = double> Eigen::Array<T, Dynamic, Dynamic> loadtxt(std::string fileName, int nrows = Dynamic, int ncols = Dynamic, std::string comments = "#@", int skiprows = 0) { std::ifstream is(fileName); ITP_ASSERT(is.is_open(), "Can not open this file: " + fileName); return loadtxt<T>(is, nrows, ncols, comments, skiprows); } /** * @brief 读取文本数据文件并写入到data中,写入量由data的大小决定 * @tparam T 数据标量类型 * @param is 文件流 * @param data 需要写入的容器 * @param comments 注释字符 * @param skiprows 跳过开头行数 */ template <typename T> bool loadtxt(std::istream& is, Eigen::Array<T, Dynamic, Dynamic>& data, std::string comments = "#@", int skiprows = 0) { std::string line; std::stringstream ss; for (int i = 0; i != skiprows; ++i) if (!std::getline(is, line)) { return false; } for (int i = 0; i != data.rows(); ) { if (!std::getline(is, line)) { return false; } if (!inner::is_comment(line, comments)) { ss.clear(); ss.str(line); for (int j = 0; j != data.cols(); ++j) ss >> data(i, j); ++i; } } return true; } } // !namespace itp; #endif // !__CORE_FILEIO_HPP__ /* vim: set filetype=cpp et sw=2 ts=2 ai: */
28.469388
122
0.45687
TING2938
5dea70019f2b53cda332b8cad86fefc279ad2e3c
77,691
cc
C++
src/cxx/libsparse/libsparse2d/MR_NoiseModel.cc
jstarck/cosmostat
f686efe4c00073272487417da15e207a529f07e7
[ "MIT" ]
null
null
null
src/cxx/libsparse/libsparse2d/MR_NoiseModel.cc
jstarck/cosmostat
f686efe4c00073272487417da15e207a529f07e7
[ "MIT" ]
null
null
null
src/cxx/libsparse/libsparse2d/MR_NoiseModel.cc
jstarck/cosmostat
f686efe4c00073272487417da15e207a529f07e7
[ "MIT" ]
null
null
null
/****************************************************************************** ** Copyright (C) 1996 by CEA ******************************************************************************* ** ** UNIT ** ** Version: 18:28:57 ** ** Author: Jean-Luc Starck ** ** Date: 97/05/06 ** ** File: MR_NoiseModel.cc ** ******************************************************************************* ** ** DESCRIPTION noise modelling ** ----------- ** ******************************************************************************* ** ** MRNoiseModel::MRNoiseModel(type_noise TNoise, int Nl_Imag, ** int Nc_Imag, int ScaleNumber, type_transform Trans) ** ** Class builder ** type_noise TNoise is the type of noise in the data ** Nl_Imag,Nc_Imag size of the image ** ScaleNumber: number of scales of the transform ** type_transform Trans: type of multiresoltuion transform ** ******************************************************************************/ #include "MR_Obj.h" #include "IM_Noise.h" #include "MR_Noise.h" #include "MR_NoiseModel.h" #include "MR_Sigma.h" #include "MR_Abaque.h" #include "MR_Psupport.h" #include "NR.h" #include "MR1D_Obj.h" #include "FFTN_2D.h" #include "Mr_FewEvent2d.h" #define WRITE_DATA 0 /************************************************************************/ Bool one_level_per_pos_2d(type_noise TNoise) // return True if we need only one level per position // in the multiresolution space { Bool ValRet= False; if ((TNoise == NOISE_EVENT_POISSON) || (TNoise == NOISE_NON_UNI_ADD) || (TNoise == NOISE_NON_UNI_MULT) || (TNoise == NOISE_UNDEFINED)) ValRet = True; return ValRet; } /************************************************************************/ void MRNoiseModel::init_param() { TabLevel = NULL; TabSupport = NULL; NbrScale = 0; NbrBand = 0; Nl = 0; Nc = 0; Size = 0; //CEventPois = NULL; CFewEventPoisson2d = NULL; CFewEvent2d = NULL; CSpeckle = NULL; CorrelNoiseMap = NULL; Transform=T_UNDEFINED; Set_Transform=S_UNDEFINED; SigmaApprox = False; FilterBank = NULL; TypeNorm = DEF_SB_NORM; NbrUndecimatedScale = -1; GradientAnalysis = False; NoCompDistrib = False; PoissonFisz = False; MadEstimFromCenter = False; TypeThreshold = DEF_THRESHOLD; U_Filter = DEF_UNDER_FILTER; mOldPoisson = False; mWriteThreshold = False; } /************************************************************************/ void MRNoiseModel::alloc(type_noise TNoise, int Nl_Imag, int Nc_Imag, int ScaleNumber, type_transform Trans, FilterAnaSynt *FAS, sb_type_norm Norm, int NbrUndec, int FCT_NDir) { int s, Nl_s=Nl_Imag, Nc_s=Nc_Imag; Nl = Nl_Imag; Nc = Nc_Imag; NbrScale = ScaleNumber; TypeNoise = TNoise; Transform = Trans; Set_Transform = SetTransform(Trans); NbrBand = NbrScale; FilterBank = FAS; TypeNorm = Norm; NbrUndecimatedScale = (NbrUndec >= 0) ? NbrUndec: NbrScale; if (Set_Transform == TRANSF_DIADIC_MALLAT) NbrBand = NbrScale*2-1; else if ((Set_Transform == TRANSF_UNDECIMATED_MALLAT)|| (Set_Transform == TRANSF_MALLAT)) NbrBand = (NbrScale-1)*3+1; if (Set_Transform != TRANSF_UNDECIMATED_MALLAT) { TabNl.alloc(NbrBand); TabNc.alloc(NbrBand); TabPos.alloc(NbrBand); TabBandScale.alloc(NbrBand); } switch (Set_Transform) { case TRANSF_UNDECIMATED_MALLAT: { if (Trans == TC_FCT) { NbrBand = fct_real_get_band_size(NbrScale, Nl, Nc, FCT_NDir, TabNl, TabNc); // cout << NbrScale << " " << NbrScale << " " << NbrBand << " " << FCT_NDir << endl; TabPos.alloc(NbrBand); TabBandScale.alloc(NbrBand); Size=0; for (s = 0; s < NbrBand-1; s++) { TabPos(s) = Size; Size += TabNl(s)*TabNc(s); } } else if (Trans == TO_LC) { NbrScale = get_nbr_scale(Nc_Imag); int NbrBandPerResol = get_nbr_scale(Nl_Imag); NbrBand = NbrScale * NbrBandPerResol; cout << NbrScale << " " << NbrBandPerResol << " " << NbrBand << endl; TabNl.alloc(NbrBand); TabNc.alloc(NbrBand); TabPos.alloc(NbrBand); TabBandScale.alloc(NbrBand); Size=0; for (int i=0; i < NbrBand; i++) { TabNl(i) =Nl_s; TabNc(i) = Nc_s; TabPos(i) = Size; Size += (Nl_s*Nc_s); } } else { Size=0; int NbrBandPerResol = 3; TabNl.alloc(NbrBand); TabNc.alloc(NbrBand); TabPos.alloc(NbrBand); TabBandScale.alloc(NbrBand); for (s = 0; s < NbrBand-1; s+=NbrBandPerResol) { if (s/NbrBandPerResol >= NbrUndecimatedScale) { TabNl(s) = (Nl_s+1)/2; TabNc(s) = Nc_s/2; TabPos(s) = Size; Size += TabNl(s)*TabNc(s); TabNl(s+1) = Nl_s/2; TabNc(s+1) = (Nc_s+1)/2; TabPos(s+1) = Size; Size += TabNl(s+1)*TabNc(s+1); TabNl(s+2) = Nl_s/2; TabNc(s+2) = Nc_s/2; TabPos(s+2) = Size; Size += TabNl(s+2)*TabNc(s+2); Nl_s = (Nl_s+1)/2; Nc_s = (Nc_s+1)/2; } else { TabNl(s) = TabNl(s+1) = TabNl(s+2) = Nl_s; TabNc(s) = TabNc(s+1) = TabNc(s+2) = Nc_s; TabPos(s) = Size; TabPos(s+1) = Size+Nl_s*Nc_s; TabPos(s+2) = Size+2*(Nl_s*Nc_s); Size += 3*(Nl_s*Nc_s); } } } } //for (s = 0; s < NbrBand-1; s++) // cout << "Band " << s+1 << " " << TabNl(s) << " " << TabNc(s) << endl; break; case TRANSF_DIADIC_MALLAT: case TRANSF_PAVE: Size = Nl*Nc*(NbrBand-1); for (s = 0; s < NbrBand-1; s++) { TabNl(s) = Nl; TabNc(s) = Nc; TabPos(s) = s*Nl*Nc; } break; case TRANSF_PYR: case TRANSF_SEMIPYR: Size=0; TabNl(0) = Nl_s; TabNc(0) = Nc_s; TabPos(0) = 0; for (s = 0; s < NbrScale-1; s++) { Size += Nl_s*Nc_s; TabPos(s+1) = TabPos(s)+Nl_s*Nc_s; if ((s != 0) || (Set_Transform != TRANSF_SEMIPYR)) { Nl_s = (Nl_s+1)/2; Nc_s = (Nc_s+1)/2; } TabNl(s+1) = Nl_s; TabNc(s+1) = Nc_s; } break; case TRANSF_MALLAT: NbrBand = 3*(NbrScale -1)+1; TabPos(0) = 0; // cout << Nl_s << " " << Nc_s << endl; Size = 0; for (s = 0; s < NbrBand-1; s+=3) { TabNl(s) = (Nl_s+1)/2; TabNc(s) = Nc_s/2; TabPos(s) = Size; Size += TabNl(s)*TabNc(s); TabNl(s+1) = Nl_s/2; TabNc(s+1) = (Nc_s+1)/2; TabPos(s+1) = Size; Size += TabNl(s+1)*TabNc(s+1); TabNl(s+2) = Nl_s/2; TabNc(s+2) = Nc_s/2; TabPos(s+2) = Size; Size += TabNl(s+2)*TabNc(s+2); Nl_s = (Nl_s+1)/2; Nc_s = (Nc_s+1)/2; // cout << "Band " << s << ": " << TabNl(s) << " " << TabNc(s) << " " << TabPos(s) << endl; // cout << "Band " << s+1 << ": " << TabNl(s+1) << " " << TabNc(s+1) << " " << TabPos(s+1) << endl; // cout << "Band " << s+2 << ": " << TabNl(s+2) << " " << TabNc(s+2) << " " << TabPos(s+2) << endl; } s= NbrBand-1; TabNl(s) = Nl_s; TabNc(s) = Nc_s; TabPos(s) = Size; Size = Nl*Nc; // for (s = 0; s < NbrBand-1; s++) cout << "bb " << s << ": " << TabNl(s) << " " << TabNc(s) << " " << TabPos(s) << endl; break; case TRANSF_FEAUVEAU: NbrBand = 2*( NbrScale-1)+1; TabPos(0) = 0; for (s = 0; s < NbrBand-1; s+=2) { int Nlw = Nl_s; int Ncw = Nc_s/2; TabNl(s) = Nlw; TabNc(s) = Ncw; TabPos(s+1) = TabPos(s) + Nlw*Ncw; Nlw /= 2; Ncw = (Nc_s+1)/2; TabNl(s+1) = Nlw; TabNc(s+1) = Ncw; TabPos(s+2) = TabPos(s+1) + Nlw*Ncw; Nl_s = (Nl_s+1)/2; Nc_s = (Nc_s+1)/2; } s= NbrBand-1; TabNl(s) = Nl_s; TabNc(s) = Nc_s; // Size = TabPos(s); Size=Nl*Nc; break; default: cerr << "Not implemented" << endl; exit (0); break; } // if (one_level_per_pos_2d(TNoise) == True) TabLevel = new float[Size]; if (one_level_per_pos_2d(TNoise) == True) { TabLevel = (float *) alloc_buffer((size_t) (Size*sizeof(float))); } else TabLevel = new float[NbrBand]; // TabSupport = new unsigned char [Size]; TabSupport = (unsigned char *) alloc_buffer((size_t) (Size*sizeof(char))); for (s = 0; s < Size; s++) TabSupport[s] = VAL_SupNull; // cout << "Size = " << Size << endl; CCD_Gain = 1.; CCD_ReadOutSigma=0.; CCD_ReadOutMean=0.; SigmaNoise=0.; for (s = 0; s < NbrBand-1; s++) { details which_detail; band2scale(s, Transform, NbrBand, TabBandScale(s), which_detail); NSigma[s] = DEF_NSIGMA_DETECT; TabEps[s] = DEFAULT_EPSILON; if (TabBandScale(s) == 0) NSigma[s] += 1; // cout << " band " << s+1 << " scale = " << TabBandScale(s) << " NSigma " << NSigma[s] << endl; } BadPixelVal=0.; BadPixel=False; MinEvent=False; SupIsol=False; FirstDectectScale = DEF_FIRST_DETECT_SCALE; OnlyPositivDetect=False; DilateSupport=False; GetEgde=False; MinEventNumber=DEF_MINEVENT_NUMBER; SigmaDetectionMethod = DEF_SIGMA_METHOD; NiterSigmaClip = 1; SizeBlockSigmaNoise = DEFAULT_SIZE_BLOCK_SIG; TransImag=False; NewStatNoise = TNoise; UseRmsMap = False; GetRmsCoeffGauss = True; //CEventPois = NULL; CFewEventPoisson2d = NULL; CFewEvent2d = NULL; CSpeckle = NULL; CorrelNoiseMap = NULL; Border = DEFAULT_BORDER; SigmaApprox = False; switch (TypeNoise) { case NOISE_GAUSSIAN: case NOISE_NON_UNI_ADD: case NOISE_UNDEFINED: TransImag=False; break; case NOISE_POISSON: case NOISE_GAUSS_POISSON: case NOISE_MULTI: case NOISE_NON_UNI_MULT: TransImag=True; SigmaNoise=1.; break; case NOISE_EVENT_POISSON: TransImag=True; MinEvent=True; // CEventPois = new StatEventPoisson; if( mOldPoisson ) { CFewEventPoisson2d = new FewEventPoisson; if (!NoCompDistrib) { // call from mr_pfilter (Abaque exist) // CEventPois->compute_distrib(); CFewEventPoisson2d->compute_distribution(); } } else{ CFewEvent2d = new FewEvent; CFewEvent2d->write_threshold( mWriteThreshold ); if (!NoCompDistrib) CFewEvent2d->compute_distribution(); } break; case NOISE_UNI_UNDEFINED: NiterSigmaClip = 3; break; case NOISE_CORREL: break; case NOISE_SPECKLE: TransImag=True; CSpeckle = new StatRayleigh(TSPECKLE, NbrScale, 1, Transform); break; } } /************************************************************************/ MRNoiseModel::MRNoiseModel() { (*this).init_param(); } /************************************************************************/ MRNoiseModel::MRNoiseModel(type_noise TNoise, int Nl_Imag, int Nc_Imag, int ScaleNumber, type_transform Trans) { (*this).init_param(); (*this).alloc(TNoise, Nl_Imag, Nc_Imag, ScaleNumber, Trans); } /****************************************************************************/ MRNoiseModel::MRNoiseModel (type_noise TNoise, MultiResol &MR_Data) { int Nl_s = MR_Data.size_ima_nl(); int Nc_s = MR_Data.size_ima_nc(); (*this).init_param(); (*this).alloc(TNoise, Nl_s, Nc_s, MR_Data.nbr_scale(), MR_Data.Type_Transform, MR_Data.filter_bank(), MR_Data.TypeNorm, MR_Data.nbr_undec_scale()); //MRNoiseModel(TNoise, Nl_s, Nc_s, // MR_Data.nbr_scale(), MR_Data.Type_Transform); } /****************************************************************************/ void MRNoiseModel::pos_mrcoeff(int NumCoef, int &b, int &i, int &j) { int PosCoef = NumCoef; b=0; while (PosCoef > TabNc(b)*TabNl(b)) { PosCoef -= TabNc(b)*TabNl(b); b++; } i = PosCoef / TabNc(b); j = PosCoef - i * TabNc(b); } /****************************************************************************/ Bool MRNoiseModel::operator() (int b,int i,int j) { Bool ValRet=False; int Ind = index(b,i,j); // cout << b << " " << i << " " << j << " ==> " << Ind << endl; if ((TabSupport[Ind] > 0) && (TabSupport[Ind] <= VAL_SupLastOK)) ValRet = True; return ValRet; } // *************** Bool MRNoiseModel::operator() (int s,int i,int j, details which_detail) { int b = scale2band(s,Transform, NbrBand,which_detail); return (*this)(b,i,j); } // *************** Bool MRNoiseModel::operator() (int NumCoef) { int b,i,j; pos_mrcoeff(NumCoef, b, i, j); return (*this)(b,i,j); } /****************************************************************************/ float & MRNoiseModel::sigma(int b, int i, int j) { int Ind; if (one_level_per_pos_2d(TypeNoise) == True) Ind = index(b,i,j); else Ind = b; return TabLevel[Ind]; } // *************** float & MRNoiseModel::sigma(int s,int i,int j, details which_detail) { int b = scale2band(s,Transform, NbrBand,which_detail); return sigma(b,i,j); } // *************** float & MRNoiseModel::sigma(int NumCoef) { if (one_level_per_pos_2d(TypeNoise) == True) { int i,j,b; pos_mrcoeff(NumCoef, b, i, j); return sigma(b,i,j); } else { return TabLevel[NumCoef]; } } /****************************************************************************/ float MRNoiseModel::nsigma(int b) { return NSigma[b]; } /****************************************************************************/ unsigned char & MRNoiseModel::support(int b,int i,int j) { int Ind = index(b,i,j); // cout << b << " " << i << " " << j << " ==> " << Ind << endl; return TabSupport[Ind]; } // *************** unsigned char & MRNoiseModel::support(int s,int i,int j, details which_detail) { int b = scale2band(s,Transform, NbrBand,which_detail); return support(b,i,j); } // *************** unsigned char & MRNoiseModel::support(int NumCoef) { int i,j,b; pos_mrcoeff(NumCoef, b, i, j); return support(b,i,j); } /****************************************************************************/ Bool MRNoiseModel::signif (float Val, int b, int i, int j, float LevelMin, float LevelMax) { Bool ValRet = False; float Level; Level = sigma(b,i,j)*NSigma[b]; if (OnlyPositivDetect == True) { if (Val > LevelMax) ValRet = True; } else if ((Val > LevelMax) || (Val < LevelMin)) ValRet = True; if ((TabBandScale(b) < FirstDectectScale) && (ValRet == True)) ValRet = False; return ValRet; } /****************************************************************************/ Bool MRNoiseModel::signif (float Val, int b, int i, int j) { Bool ValRet = False; float Level; Level = sigma(b,i,j)*NSigma[b]; if (OnlyPositivDetect == True) { if (Val > Level) ValRet = True; } else if (ABS(Val) > Level) ValRet = True; if ((TabBandScale(b) < FirstDectectScale) && (ValRet == True)) ValRet = False; return ValRet; } Bool MRNoiseModel::signif (float Val, int b, int i, int j, fltarray & TNsigma) { Bool ValRet = False; float Level; Level = sigma(b,i,j) * TNsigma(b); if (OnlyPositivDetect == True) { if (Val > Level) ValRet = True; } else if (ABS(Val) > Level) ValRet = True; if ((TabBandScale(b) < FirstDectectScale) && (ValRet == True)) ValRet = False; return ValRet; } // *************** Bool MRNoiseModel::signif (float Val, int s, int i, int j, details which_detail) { int b = scale2band(s,Transform, NbrBand,which_detail); return signif(Val, b,i,j); } /****************************************************************************/ float MRNoiseModel::prob(float Val, int b, int i, int j) { float Sig,P=0.; switch (TypeNoise) { case NOISE_EVENT_POISSON: { int k,l,Win = (int) (pow((double)2., (double)(b+2)) + 0.5); double Nevent = 0; for (k =i-Win; k <= i+Win; k++) for (l =j-Win; l <= j+Win; l++) Nevent += Event_Image(k, l, Border); if (NoCompDistrib) { cout << "Error: histogram have to be computed first ..." << endl; exit(-1); } //P = CEventPois->a_trou_prob(Val, Nevent, b); if( mOldPoisson ) P = CFewEventPoisson2d->a_trou_prob( Val, (int ) (Nevent+0.5), b ); else P = CFewEvent2d->a_trou_prob( Val, (int ) (Nevent+0.5), b ); } break; case NOISE_CORREL: P = CorrelNoiseMap->prob(b, Val); break; case NOISE_SPECKLE: P = CSpeckle->prob(b, Val); break; default: Sig = sigma(b,i,j); P = exp(-Val*Val / (2*Sig*Sig) ) / sqrt(2.*PI); break; } return P; } // *************** float MRNoiseModel::prob (float Val, int s, int i, int j, details which_detail) { int b = scale2band(s,Transform, NbrBand,which_detail); return prob(Val,b,i,j); } /****************************************************************************/ void MRNoiseModel::prob (MultiResol &MR_Data, Bool Complement) { float Sig,Val; int s,i,j; switch (TypeNoise) { case NOISE_EVENT_POISSON: { Ifloat EventCount(Nl,Nc,"ImagCount"); for (s = 0; s < MR_Data.nbr_band()-1; s++) { event_one_scale(Event_Image, s, EventCount, MR_Data.Border); for (i=0; i< MR_Data.size_band_nl(s); i++) for (j=0; j< MR_Data.size_band_nc(s); j++) { if (NoCompDistrib) { cout << "Error: histogram have to be computed first ... " << endl; exit(-1); } //MR_Data(s,i,j) = CEventPois->a_trou_prob(MR_Data(s,i,j), EventCount(i,j), s); if( mOldPoisson ) MR_Data(s,i,j) = CFewEventPoisson2d->a_trou_prob( MR_Data(s,i,j), (int) ( EventCount(i,j)+0.5), s ); else MR_Data(s,i,j) = CFewEvent2d->a_trou_prob( MR_Data(s,i,j), (int) ( EventCount(i,j)+0.5), s ); if (Complement == True) MR_Data(s,i,j) = 1. - MR_Data(s,i,j) ; } } } break; case NOISE_CORREL: for (s = 0; s < MR_Data.nbr_band()-1; s++) for (i=0; i< MR_Data.size_band_nl(s); i++) for (j=0; j< MR_Data.size_band_nc(s); j++) { Val = MR_Data(s,i,j); MR_Data(s,i,j) = CorrelNoiseMap->prob(s, Val); } break; case NOISE_SPECKLE: for (s = 0; s < MR_Data.nbr_band()-1; s++) for (i=0; i< MR_Data.size_band_nl(s); i++) for (j=0; j< MR_Data.size_band_nc(s); j++) { Val = MR_Data(s,i,j); MR_Data(s,i,j) = CSpeckle->prob(s, Val); } break; default: for (s = 0; s < MR_Data.nbr_band()-1; s++) for (i=0; i< MR_Data.size_band_nl(s); i++) for (j=0; j< MR_Data.size_band_nc(s); j++) { Val = MR_Data(s,i,j); Sig = sigma(s,i,j); if (Sig > FLOAT_EPSILON) Val = 1. / sqrt(2.*PI)*exp(-Val*Val / (2*Sig*Sig)); else Val = 0.; if (Complement == True) Val = 1. - Val; MR_Data(s,i,j) = Val; } break; } } /****************************************************************************/ void MRNoiseModel::prob_noise (MultiResol &MR_Data, Bool Complement) { int s,i,j; switch (TypeNoise) { case NOISE_EVENT_POISSON: { Ifloat EventCount(Nl,Nc,"ImagCount"); for (s = 0; s < MR_Data.nbr_band()-1; s++) { event_one_scale(Event_Image, s, EventCount, MR_Data.Border); for (i=0; i< MR_Data.size_band_nl(s); i++) for (j=0; j< MR_Data.size_band_nc(s); j++) { if (NoCompDistrib) { cout << "Error: histogram have to be computed first ..." << endl; exit(-1); } //float P = CEventPois->a_trou_repartition(MR_Data(s,i,j), // EventCount(i,j) , s); double P1, P2; //std::cout << "s:" << s << ", [x:" << i << ",y:" << j << "]" << std::endl; if( mOldPoisson ) { P1 = CFewEventPoisson2d->a_trou_repartition( MR_Data(s,i,j), (int) (EventCount(i,j)+0.5), s); if (MR_Data(s,i,j) > 0) P1 = 1. - P1; if (Complement == True) MR_Data(s,i,j) = 1. - P1; else MR_Data(s,i,j) = P1; } else { P1 = CFewEvent2d->a_trou_repartition( MR_Data(s,i,j), (int) (EventCount(i,j)+0.5), s); P2 = CFewEvent2d->a_trou_repartition( MR_Data(s,i,j), (int) (EventCount(i,j)+0.5), s, True); //std::cout << "MRNoiseModel::prob_noise : P1 = " << P1 << ", 1-P1 = " << 1. - P1 // << ", P2 = " << P2 << std::endl; if (Complement == True) MR_Data(s,i,j) = 1. - P2; else MR_Data(s,i,j) = P2; } } } } break; default: for (s = 0; s < MR_Data.nbr_band()-1; s++) for (i=0; i< MR_Data.size_band_nl(s); i++) for (j=0; j< MR_Data.size_band_nc(s); j++) { MR_Data(s,i,j) = prob_noise(MR_Data(s,i,j), s, i, j); if (Complement == True) MR_Data(s,i,j) = 1. - MR_Data(s,i,j); } break; } } /****************************************************************************/ float MRNoiseModel::prob_noise(float Val, int b, int i, int j) { float Sig,P=0.; double Vn=0.; switch (TypeNoise) { case NOISE_EVENT_POISSON: { if (NoCompDistrib) { cout << "Error: histogram have to be computed first ..." << endl; exit(-1); } int k,l,Win = (int) (pow((double)2., (double)(b+2)) + 0.5); float Nevent = 0; for (k =i-Win; k <= i+Win; k++) for (l =j-Win; l <= j+Win; l++) Nevent += Event_Image(k, l, Border); //P = CEventPois->a_trou_repartition(Val, Nevent, b); if( mOldPoisson ) { P = CFewEventPoisson2d->a_trou_repartition(Val, (int) (Nevent+0.5), b); if (Val > 0) P = 1. - P; } else { //double P1 = CFewEvent2d->a_trou_repartition(Val, Nevent, b); double P2 = CFewEvent2d->a_trou_repartition( Val, (int) (Nevent+0.5), b, True ); // std::cout << "MRNoiseModel::prob_noise : P1 = " << P1 << ", 1-P1 = " << 1. - P1 << ", P2 = " << P2 << std::endl; P = P2; } } break; case NOISE_CORREL: P = CorrelNoiseMap->repartition(b, Val); if (Val > 0) P = 1. - P; break; case NOISE_SPECKLE: P = CSpeckle-> repartition(b, Val); if (Val > 0) P = 1. - P; break; default: Sig = sigma(b,i,j); if (ABS(Val) < FLOAT_EPSILON) P = 1.; else { if (Sig < FLOAT_EPSILON) P = 0; else { Vn = ABS(Val) / (sqrt(2.)*Sig); if (Vn > 3.5) P = 0; else P = (float) erfc (Vn); } } break; } return P; } /****************************************************************************/ double MRNoiseModel:: prob_signal_few_event( float Val, int b, int i, int j ) { double P = 0 ; if( NoCompDistrib ) { std::cout << "Error: histogram have to be computed first ..." << std::endl ; exit( -1 ) ; } int k,l,Win = (int) ( pow((double)2., (double)( b+2 )) + 0.5) ; float Nevent = 0.; for( k =i-Win; k <= i+Win; k++ ) for( l =j-Win; l <= j+Win; l++ ) Nevent += Event_Image(k, l, Border) ; if( mOldPoisson ) { P = CFewEventPoisson2d->a_trou_repartition( Val, (int) (Nevent+0.5), b ) ; if( Val > 0 ) P = 1. - P ; } else { //double P1 = CFewEvent2d->a_trou_repartition(Val, Nevent, b); P = CFewEvent2d->a_trou_repartition( Val, (int) (Nevent+0.5), b, True ) ; //std::cout << "MRNoiseModel::prob_signal_few_event : P = " << std::endl ; } if (kill_coef( b, i, j, Val, False ) == True ) P = 1. ; return P; } // *************** float MRNoiseModel::prob_noise(float Val, int s, int i, int j, details which_detail) { int b = scale2band(s,Transform, NbrBand,which_detail); return prob_noise(Val,b,i,j); } /****************************************************************************/ float MRNoiseModel::prob_signal(float Val, int b, int i, int j) { return (1. - prob_noise(Val,b,i,j)); } /****************************************************************************/ float MRNoiseModel::prob_signal(float Val, int s, int i, int j, details which_detail) { int b = scale2band(s,Transform, NbrBand,which_detail); return (1. - prob_noise(Val,b,i,j)); } /****************************************************************************/ float MRNoiseModel::val_transform(float Val) { float ValRet = Val; switch (TypeNoise) { case NOISE_POISSON: case NOISE_GAUSS_POISSON: ValRet = Val*CCD_Gain + 3. / 8. * CCD_Gain*CCD_Gain + CCD_ReadOutSigma*CCD_ReadOutSigma - CCD_Gain*CCD_ReadOutMean; if (ValRet < 0.) ValRet=0; else ValRet = 2. / CCD_Gain *sqrt(ValRet); break; case NOISE_GAUSSIAN: case NOISE_NON_UNI_ADD: case NOISE_UNDEFINED: case NOISE_UNI_UNDEFINED: case NOISE_CORREL: break; case NOISE_MULTI: case NOISE_NON_UNI_MULT: case NOISE_SPECKLE: if (Val > 0) ValRet = log(Val+1.); else ValRet = 0.; break; case NOISE_EVENT_POISSON: break; } return ValRet; } /****************************************************************************/ float MRNoiseModel::val_invtransform(float Val) { float ValRet = Val; switch (TypeNoise) { case NOISE_POISSON: case NOISE_GAUSS_POISSON: ValRet = Val*Val/4.*CCD_Gain - ( 3./8.*CCD_Gain*CCD_Gain + CCD_ReadOutSigma*CCD_ReadOutSigma - CCD_Gain*CCD_ReadOutMean ) / CCD_Gain; break; case NOISE_GAUSSIAN: case NOISE_NON_UNI_ADD: case NOISE_UNDEFINED: case NOISE_UNI_UNDEFINED: case NOISE_CORREL: break; case NOISE_MULTI: case NOISE_NON_UNI_MULT: case NOISE_SPECKLE: if (Val > 0) ValRet = exp(Val) - 1.; else ValRet = 0.; break; case NOISE_EVENT_POISSON: break; } return ValRet; } /****************************************************************************/ void MRNoiseModel::im_transform(Ifloat &Image) { switch (TypeNoise) { case NOISE_POISSON: if (PoissonFisz == False) noise_poisson_transform (Image, Image); else fisz2d_trans(Image); SigmaNoise = 1.; break; case NOISE_GAUSS_POISSON: noise_poisson_transform (Image, Image); SigmaNoise = 1.; break; case NOISE_GAUSSIAN: case NOISE_NON_UNI_ADD: case NOISE_UNDEFINED: case NOISE_UNI_UNDEFINED: case NOISE_CORREL: break; case NOISE_MULTI: case NOISE_NON_UNI_MULT: case NOISE_SPECKLE: noise_log_transform (Image, Image); break; case NOISE_EVENT_POISSON: // event_poisson_transform (Image, Event_Image); building_imag_imag(Image, Event_Image); break; } } /****************************************************************************/ void MRNoiseModel::im_invtransform(Ifloat &Image) { switch (TypeNoise) { case NOISE_POISSON: if (PoissonFisz == False) noise_inverse_poisson_transform (Image, Image); else fisz2d_inv(Image); break; case NOISE_GAUSS_POISSON: noise_inverse_poisson_transform (Image, Image); break; case NOISE_GAUSSIAN: case NOISE_NON_UNI_ADD: case NOISE_UNDEFINED: case NOISE_UNI_UNDEFINED: case NOISE_CORREL: break; case NOISE_MULTI: case NOISE_NON_UNI_MULT: case NOISE_SPECKLE: noise_inv_log_transform (Image, Image); break; case NOISE_EVENT_POISSON: break; } } /****************************************************************************/ void MRNoiseModel::get_sigma_from_rms_map(Ifloat &Ima_Sigma) { int RmsNl = Ima_Sigma.nl(); int RmsNc = Ima_Sigma.nc(); Ifloat Ptr_Rms; Ifloat Dirac; int i,j,s; int Ind; FFTN_2D FFT; FFT.CenterZeroFreq = True; Dirac.alloc(RmsNl,RmsNc,"Dirac"); Ptr_Rms.alloc(RmsNl,RmsNc,"Ptr_Rms"); Dirac(RmsNl/2-1,RmsNc/2-1)=1.; // First we compute the square image of Rms for(i=0; i < RmsNl; i++) for(j=0; j < RmsNc; j++) Ptr_Rms(i,j) = Ima_Sigma(i,j)*Ima_Sigma(i,j); // Then we transform the dirac image : MultiResol MR_Dirac(RmsNl, RmsNc, NbrScale, Transform, "Dirac"); MR_Dirac.transform(Dirac); // Then we compute the square of the Dirac transform ... for (s=0 ; s < MR_Dirac.nbr_band()-1; s++) for (i=0 ; i < RmsNl; i++) for (j=0 ; j < RmsNc; j++) MR_Dirac(s,i,j) *= MR_Dirac(s,i,j); // Then we convolve the RMS by the Dirac (at each scale) // The problem is now to take the sqrt of the result image. The FFT may // produce some negative values. Since the result is lower for high number // of scales, we cannot use a test based on a comparision of FLOAT_EPSILON // or some power of it. We look simply if there was something at the place // on the original map ... for (s=0 ; s < MR_Dirac.nbr_band()-1 ; s++) { FFT.convolve(MR_Dirac.band(s), Ptr_Rms); for (i=0 ; i < RmsNl ; i++) for (j=0 ; j < RmsNc ; j++) { Ind = index(s,i,j); if (MR_Dirac(s,i,j) <= 0) TabLevel[Ind] = 0; else TabLevel[Ind] = sqrt(MR_Dirac(s,i,j)); } } } /****************************************************************/ void MRNoiseModel::max_sigma_in_scale(Ifloat &Ima_Sigma) { int s,i,j,Kb,Ke,Lb,Le,k,l; int Nls=Nl,Ncs=Nc,Nlp=Nl,Ncp=Nc; int Ind, Indp,Step,SizeWave=2; float Max; extern float mr_tab_noise(int s); // FIRST SCALE: // find the maximum noise standard deviation in a box // put the result in TabLevel for (i=0; i< Nl-1; i++) for (j=0; j< Nc-1; j++) { Max = Ima_Sigma(i,j); Kb = (i-SizeWave >= 0) ? i-SizeWave : 0; Ke = (i+SizeWave <= Nl-1) ? i+SizeWave : Nl-1; Lb = (j-SizeWave >= 0) ? j-SizeWave : 0; Le = (j+SizeWave <= Nc-1) ? j+SizeWave : Nc-1; for (k=Kb; k<= Ke; k++) for (l=Lb; l<= Le; l++) if (Max < Ima_Sigma(k,l)) Max =Ima_Sigma(k,l); Ind = index(0,i,j); TabLevel[Ind] = Max*mr_tab_noise(0) / 0.972463; } Step=1; for (s=1; s < NbrBand-1; s++) { Nls = TabNl(s); Ncs = TabNc(s); Nlp = TabNl(s-1); Ncp = TabNc(s-1); if ((Set_Transform == TRANSF_PAVE) || ((Set_Transform == TRANSF_SEMIPYR) && (s == 1))) { Step = 2*Step; } for (i=0; i< Nls-1; i++) for (j=0; j< Ncs-1; j++) { Max = 0.; if ((Set_Transform == TRANSF_PAVE) || ((Set_Transform == TRANSF_SEMIPYR) && (s == 1))) { Kb = (i-Step >= 0) ? i-Step : i; Ke = (i+Step <= Nl-1) ? i+Step : i; Lb = (j-Step >= 0) ? j-Step : j; Le = (j+Step <= Nc-1) ? j+Step : j; } else { Kb = (2*i-2 >= 0) ? 2*i-2 : 0; Ke = (2*i+2 <= Nlp-1) ? 2*i+2 : Nlp-1; Lb = (2*j-2 >= 0) ? 2*j-2 : 0; Le = (2*j+2 <= Ncp-1) ? 2*j+2 : Ncp-1; } for (k=Kb; k<= Ke; k+=Step) for (l=Lb; l<= Le; l+=Step) { Indp = index(s-1,k,l); if (Max < TabLevel[Indp]) Max = TabLevel[Indp]; } Ind = index(s,i,j); TabLevel[Ind] = Max*mr_tab_noise(s)/mr_tab_noise(s-1); } } } /****************************************************************************/ void MRNoiseModel::kill_isol(int s) { int i,j; Bool PutZero; int Nls=Nl; int Ncs=Nl; // cout << "kill_isol" << endl; if (Set_Transform == TRANSF_PYR) { Nls = TabNl(s); Ncs = TabNc(s); } if (Set_Transform == TRANSF_PAVE) { for (i = 1; i < Nl-1; i++) for (j = 1; j < Nc-1; j++) { PutZero = True; if (support(s,i,j) == VAL_SupOK) { if (support(s,i-1,j) == VAL_SupOK) PutZero = False; else if (support(s,i+1,j) == VAL_SupOK) PutZero = False; else if (support(s,i,j+1) == VAL_SupOK) PutZero = False; else if (support(s,i,j-1) == VAL_SupOK) PutZero = False; else if (support(s+1,i,j) == VAL_SupOK) PutZero = False; if (PutZero == True) support(s,i,j) = VAL_SupKill; } } } else if ((Set_Transform == TRANSF_PYR) || (Set_Transform == TRANSF_SEMIPYR) || (Set_Transform == TRANSF_DIADIC_MALLAT) || (Set_Transform == TRANSF_UNDECIMATED_MALLAT)) { Nls = TabNl(s); Ncs = TabNc(s); for (i = 1; i < Nls-1; i++) for (j = 1; j < Ncs-1; j++) { PutZero = True; if (support(s,i,j) == VAL_SupOK) { if (support(s,i-1,j) == VAL_SupOK) PutZero = False; else if (support(s,i+1,j) == VAL_SupOK) PutZero = False; else if (support(s,i,j+1) == VAL_SupOK) PutZero = False; else if (support(s,i,j-1) == VAL_SupOK) PutZero = False; // else if (support(s+1,i/2,j/2) == VAL_SupOK) PutZero = False; if (PutZero == True) support(s,i,j) = VAL_SupKill; } } } } /****************************************************************************/ void MRNoiseModel::dilate_support(int s) { int dim=1; int Ind; unsigned char *Buff; int i,j,k,l,Nls,Ncs; int kb,ke,lb,le; unsigned char Max; if ((Set_Transform == TRANSF_PYR) || (Set_Transform == TRANSF_PAVE) || (Set_Transform == TRANSF_SEMIPYR) || (Set_Transform == TRANSF_DIADIC_MALLAT) || (Set_Transform == TRANSF_UNDECIMATED_MALLAT)) { if (Set_Transform == TRANSF_PAVE) dim = (int)(pow((double)2., (double) (s+1)) + 0.5); Nls = TabNl(s); Ncs = TabNc(s); Buff = new unsigned char [Nls*Ncs]; for (i = 0; i < Nls*Ncs; i++) Buff[i] =0; for (i = 0; i < Nls; i++) for (j = 0; j < Ncs; j++) { Max = ( (*this)(s,i,j) == True ) ? 1 : 0; kb = (i-dim >= 0) ? i-dim: 0; lb = (j-dim >= 0) ? j-dim: 0; ke = (i+dim < Nls) ? i+dim: Nls-1; le = (j+dim < Ncs) ? j+dim: Ncs-1; k=kb; while ( (Max == 0) && (k <= ke)) { l = lb; while ( (Max == 0) && (l <= le)) { if ((*this)(s,k,l) == True) Max=1; l++; } k++; } Ind = i*Ncs+j; Buff[Ind] = Max; } for (i = 0; i < Nls; i++) for (j = 0; j < Ncs; j++) { Ind = i*Ncs+j; if ((support(s,i,j) != VAL_SupOK) && (Buff[Ind] == 1)) { support(s,i,j) = VAL_SupDill; } } delete [] Buff; } } /****************************************************************************/ void MRNoiseModel::hierarchical_dilate_support() { int dim=1; int i,j,k,l,Nls,Ncs; int kb,ke,lb,le; unsigned char Max; if (Set_Transform == TRANSF_PAVE) for (int s = NbrBand-3; s >= 0; s--) { int NextScale = s+1; dim = (int)(pow((double)2., (double) s) + 0.5); Nls = TabNl(s); Ncs = TabNc(s); for (i = 0; i < Nls; i++) for (j = 0; j < Ncs; j++) { Max = ( (*this)(NextScale,i,j) == True ) ? 1 : 0; kb = (i-dim >= 0) ? i-dim: 0; lb = (j-dim >= 0) ? j-dim: 0; ke = (i+dim < Nls) ? i+dim: Nls-1; le = (j+dim < Ncs) ? j+dim: Ncs-1; k=kb; if ((*this)(s,i,j) == False) { while ( (Max == 1) && (k <= ke)) { l = lb; while ( (Max == 1) && (l <= le)) { if ((*this)(NextScale,k,l) == False) Max=0; l++; } k++; } if (Max == 1) support(s,i,j) = VAL_SupDill; } } } } /****************************************************************************/ void MRNoiseModel::kill_event(int s, Ifloat &IEvent_Image, int FirstWin) { int i,j,k,l,kb,ke,Nls,Ncs,sc=0; int Step=1; int Win = FirstWin/2; float Total; if (Set_Transform == TRANSF_PAVE) { Nls = TabNl(s); Ncs = TabNc(s); while (sc++ < s) Win*=2; for (i =0; i < Nl; i++) { Total = 0; kb = (i-Win < 0) ? 0: i-Win; ke = (i+Win >= Nls) ? Nls-1: i+Win; for (k =kb; k <= ke; k++) for (l =0; l <= Win; l++) Total += IEvent_Image(k, l); if ((support(s,i,0) == VAL_SupOK) && (Total < MinEventNumber)) support(s,i,0) = VAL_SupMinEv; for (j =1; j < Nc; j+=Step) { for (k = -Win; k <= Win; k++) { Total -= (int) IEvent_Image(kb,j-Win-1,I_ZERO); Total += (int) IEvent_Image(kb,j+Win,I_ZERO); } if ((support(s,i,j) == VAL_SupOK) && (Total < MinEventNumber)) support(s,i,j) = VAL_SupMinEv; } } } } /****************************************************************************/ float MRNoiseModel::sure_estimation(MultiResol &MR_Data) { int s,i,j; int Ind = 1; unsigned long N = 0; for (s = 0; s < MR_Data.nbr_band()-1; s++) N += MR_Data.size_band_nl(s) * MR_Data.size_band_nc(s); float *Tab = new float [N+1]; for (s = 0; s < MR_Data.nbr_band()-1; s++) for (i = 0; i < MR_Data.size_band_nl(s) ; i++) for (j = 0; j < MR_Data.size_band_nc(s) ; j++) { float Coef = MR_Data(s,i,j) / sigma(s,i,j); Tab[Ind++] = Coef*Coef; } sort(N, Tab); double MinRisk=0.; double CumVal = 0; int IndRisk=0; for (i = 1; i <= (int) N; i++) { CumVal += Tab[i]; int c = N-i; double s = CumVal + c * Tab[i]; double r = ((double) N - (2.*i) + s) / (double) N; if ((i == 1) || (r < MinRisk)) { MinRisk = r; IndRisk = i; } } double T = sqrt(Tab[IndRisk]); delete [] Tab; return (float) T; } /********************************************************************/ float MRNoiseModel::multi_sure_estimation(MultiResol & MR_Data, int b) { int i,j; int Ind = 1; int Nl = MR_Data.size_band_nl(b); int Nc = MR_Data.size_band_nc(b); unsigned long N = Nl*Nc; float *Tab = new float [N+1]; for (i = 0; i < MR_Data.size_band_nl(b) ; i++) for (j = 0; j < MR_Data.size_band_nc(b) ; j++) { float Coef = MR_Data(b,i,j) / sigma(b,i,j); Tab[Ind++] = Coef*Coef; } sort(N, Tab); double MinRisk=0.; double CumVal = 0; int IndRisk=0; for (i = 1; i <= (int) N; i++) { CumVal += Tab[i]; int c = N-i; double s = CumVal + c * Tab[i]; double r = ((double) N - (2.*i) + s) / (double) N; if ((i == 1) || (r < MinRisk)) { MinRisk = r; IndRisk = i; } } double T = sqrt(Tab[IndRisk]); delete [] Tab; return (float) T; } /********************************************************************/ void MRNoiseModel::set_support(MultiResol &MR_Data) { int b,i,j; int Nls, Ncs; float SureLevel; if ((Transform == TO_DIADIC_MALLAT) && (GradientAnalysis == True)) { for (b = 0; b < NbrBand-1; b+=2) { Nls = MR_Data.size_band_nl(b); Ncs = MR_Data.size_band_nc(b); for (i = 0; i < Nls;i++) for (j = 0; j < Ncs; j++) { float Coef = sqrt(POW(MR_Data(b,i,j),2.)+POW(MR_Data(b+1,i,j), 2.)); if (signif(Coef, b,i,j) == True) { support(b,i,j)=VAL_SupOK; support(b+1,i,j)=VAL_SupOK; } else { support(b,i,j)=VAL_SupNull; support(b+1,i,j)=VAL_SupNull; } } } } else { switch (TypeThreshold) { case T_FDR: for (b = 0; b < NbrBand-1; b++) { Nls = MR_Data.size_band_nl(b); Ncs = MR_Data.size_band_nc(b); dblarray TabPValue(Ncs,Nls); for (i = 0; i < Nls;i++) for (j = 0; j < Ncs; j++) TabPValue(j,i) = prob_noise(MR_Data(b,i,j), b, i, j); float Alpha = (b==0) ? 1. - erf(NSigma[b] / sqrt(2.)): Alpha*2; if (Alpha > 0.5) Alpha = 0.5; double PDet = fdr_pvalue(TabPValue.buffer(), Nls*Ncs, Alpha); for (i = 0; i < Nls; i++) for (j = 0; j < Ncs; j++) { if (TabPValue(j,i) < PDet) { support(b,i,j) = VAL_SupOK; if ((OnlyPositivDetect == True) && (MR_Data(b,i,j) < 0)) support(b,i,j) = VAL_SupNull; if (TabBandScale(b) < FirstDectectScale) support(b,i,j) = VAL_SupFirstScale; } else support(b,i,j) = VAL_SupNull; } TabEps[b] = PDet; //if (PDet < DOUBLE_EPSILON) NSigma[b] = 5.; //else // NSigma[b] = ABS(xerf(PDet/2.)); NSigma[b] = ABS(xerfc(0.5+(1-PDet)/2.)); if((NSigma[b] < 5) && (NSigma[b] > 0)) NSigma[b] = ABS(xerfc(0.5+(1-PDet)/2.)); else NSigma[b] = 5; // if (Verbose == True) printf("FDR: band %d ==> Alpha = %f, NSigma = %f\n", b+1, Alpha, NSigma[b]); } break; case T_SURE: SureLevel = sure_estimation(MR_Data); break; case T_KSIGMA: break; case T_UNIVERSAL: for (b = 0; b < NbrBand-1; b++) NSigma[b] = sqrt(2.*log((float)(MR_Data.size_band_nl(b)*MR_Data.size_band_nc(b)))); break; case T_MRSURE: for (b = 0; b < NbrBand-1; b++) NSigma[b] = multi_sure_estimation(MR_Data,b); break; } if (TypeThreshold != T_FDR) { for (b = 0; b < NbrBand-1; b++) for (i = 0; i < MR_Data.size_band_nl(b); i++) for (j = 0; j < MR_Data.size_band_nc(b); j++) support(b,i,j) = (signif(MR_Data(b,i,j), b,i,j) == True) ? VAL_SupOK: VAL_SupNull; } } Bool SpatialAdaptiv = False; if ((Transform == TO_UNDECIMATED_NON_ORTHO) && (SpatialAdaptiv == True)) { // Here we compare the SNR for each coeff in the three bands to the // SNR of the sum of the coeff. If the SNR(SUM) > MAX(SNR_i) i=1,2,3 then we habe an isotropic feature // and we set the support to 1 in the three bands. for (b = 0; b < NbrBand-1; b+=3) { extern double TabNormPaveB3Spline[MAX_SCALE]; extern double TabNormUndecNonOrth_B3SPLINE_ISOTROP_2[MAX_SCALE]; float SumBand; Nls = MR_Data.size_band_nl(b); Ncs = MR_Data.size_band_nc(b); for (i = 0; i < Nls;i++) for (j = 0; j < Ncs;j++) { float Sig1 = sigma(b,i,j); // std of the noise in horiz band float Sig2 = sigma(b+1,i,j);// std of the noise in vertical band float Sig3 = sigma(b+2,i,j); //std of the noise in diag band float MaxSig = MAX(MR_Data(b,i,j)/Sig1, MR_Data(b+1,i,j)/Sig2); MaxSig = MAX(MaxSig, MR_Data(b+3,i,j)/Sig3); // get the MAX SNR of the three bands float NSigMIN = MIN(NSigma[b], NSigma[b+1]); // NSigMIN = MIN(NSigMIN,NSigma[b+2]); // get the detection level parameter float SigSum=0; SumBand = (MR_Data(b,i,j) + MR_Data(b+1,i,j) + MR_Data(b+2,i,j)); // Sum of the three bands if (NewStatNoise == NOISE_GAUSSIAN) { switch(U_Filter) { case U_B3SPLINE:SigSum = TabNormPaveB3Spline[b/3]*SigmaNoise; break; case U_B3SPLINE_2:SigSum = TabNormUndecNonOrth_B3SPLINE_ISOTROP_2[b/3]*SigmaNoise; break; default: SumBand = 0; SigSum = 1; break; } } else SigSum = sqrt(Sig1*Sig1+Sig2*Sig2+Sig3*Sig3)*1.23; // Correction because of the correlation of the coef. SumBand /= SigSum; if ((SumBand > MaxSig) && (SumBand > NSigMIN)) { support(b,i,j) = support(b+1,i,j) = support(b+2,i,j) = VAL_SupOK; } } } } /* if ((GetEgde == True) && (Transform == TO_PAVE_BSPLINE)) { for (b = 0; b < NbrBand-1; b++) { int b1,E_Nscale; Nls = MR_Data.size_band_nl(b); Ncs = MR_Data.size_band_nc(b); Ifloat Buff(Nls,Ncs,"Buff"); E_Nscale = iround((float)log((float) (MIN(Nls,Ncs) / 4. * 3.) / log(2.))); if (one_level_per_pos_2d(TypeNoise) == True) { cout << "Error: this noise model cannot be used with this option ... " << endl; exit(-1); } float Level = TabLevel[b] * NSigma[b]; MultiResol MR_EDGE(Nls, Ncs, E_Nscale, TO_MALLAT, "MR EDGE"); MR_EDGE.TypeNorm = NORM_L2; // MR_EDGE.SBFilter=F_HAAR; MR_EDGE.SBFilter=F_MALLAT_7_9; MR_EDGE.transform(MR_Data.band(b)); for (b1= 0; b1 < MR_EDGE.nbr_band(); b1 ++) for (i = 0; i < MR_EDGE.size_band_nl(b1); i++) for (j = 0; j < MR_EDGE.size_band_nc(b1); j++) if (ABS(MR_EDGE(b1,i,j)) < Level) MR_EDGE(b1,i,j) = 0.; MR_EDGE.recons(Buff); for (i = 0; i < Nls;i++) for (j = 0; j < Ncs; j++) if ((support(b,i,j)==VAL_SupNull) && (ABS(Buff(i,j)) > FLOAT_EPSILON)) support(b,i,j)=VAL_SupEdge; } } if ((GetEgde == True) && ((Set_Transform == TRANSF_DIADIC_MALLAT) || (Set_Transform == TRANSF_MALLAT))) { for (b = 0; b < NbrBand-1; b++) { int s,b1,w,Np,LC_Nscale; details which_detail; MR_Data.band_to_scale(b, s, which_detail); switch (which_detail) { case D_HORIZONTAL: LC_Nscale = iround((float)log((float) (Ncs / 4. * 3.) / log(2.))) - s ; Np = Ncs; break; case D_VERTICAL: LC_Nscale = iround((float)log((float) (Nls / 4. * 3.) / log(2.))) - s ; Np = Nls; break; default: LC_Nscale = 0; break; } if (LC_Nscale > 1) { MR_1D MR_LINE(Np, TO1_MALLAT, "line trans", LC_Nscale); MR_LINE.SB_Filter=F_HAAR; MR_LINE.Norm = NORM_L2; MR_LINE.Border = I_CONT; fltarray Col(Np); float Nsig = 2.*NSigma[b]; if (which_detail == D_HORIZONTAL) { for (j = 0; j < Ncs; j++) { for (i = 0; i < Np; i++) Col(i) = MR_Data(b,i,j); MR_LINE.transform(Col); // thresholding assuming Gaussian noise for (b1= 0; b1 < MR_LINE.nbr_band(); b1 ++) for (w = 0; w < MR_LINE.size_scale_np(b1); w++) if (ABS(MR_LINE(b1,w)) < Nsig*sigma(b,i,j)) MR_LINE(b1,w) = 0.; MR_LINE.recons(Col); for (i = 0; i < Np; i++) if ((support(b,i,j)==VAL_SupNull) && (ABS(Col(i)) > FLOAT_EPSILON)) support(b,i,j)=VAL_SupEdge; } } else { for (i = 0; i < Nls; i++) { for (j = 0; j < Np; j++) Col(j) = MR_Data(b,i,j); MR_LINE.transform(Col); // thresholding assuming Gaussian noise for (b1= 0; b1 < MR_LINE.nbr_band(); b1 ++) for (w = 0; w < MR_LINE.size_scale_np(b1); w++) if (ABS(MR_LINE(b1,w)) < Nsig*sigma(b,i,j)) MR_LINE(b1,w) = 0.; MR_LINE.recons(Col); for (j = 0; j < Np; j++) if ((support(b,i,j)==VAL_SupNull) && (ABS(Col(j)) > FLOAT_EPSILON)) support(b,i,j)=VAL_SupEdge; } } } } } */ if (SupIsol == True) for (b = 0; b < NbrBand-2; b++) kill_isol(b); if (DilateSupport == True) for (b = 0; b < NbrBand-1; b++) dilate_support(b); } /****************************************************************************/ void MRNoiseModel::mod_support(MultiResol &MR_Data, fltarray Nsigma) { int i,j,k,s; int Nls, Ncs; for (s = 0; s < NbrBand-1; s++) { Nls = MR_Data.size_band_nl(s); Ncs = MR_Data.size_band_nc(s); for (i = 0; i < Nls;i++) for (j = 0; j < Ncs; j++) { if (support(s,i,j) == VAL_SupOK) { for (k=0; k<NbrBand; k++) if (signif(MR_Data(k,i,j), k,i,j, Nsigma) == True) support(k,i,j)=VAL_SupOK; else support(k,i,j)=VAL_SupNull; } } } //if (SupIsol == True) for (s = 0; s < NbrBand-2; s++) kill_isol(s); //if (DilateSupport == True) // for (s = 0; s < NbrBand-1; s++) dilate_support(s); } /****************************************************************************/ Bool MRNoiseModel::kill_coef(int b,int i,int j, float Val, Bool SetSupport) { Bool ValRet=False; if ((*this)(b,i,j) == False) { if (SetSupport == False) ValRet = True; else { if ((support(b,i,j) == VAL_SupNull) && (signif(Val, b,i,j) == True)) { support(b,i,j)=VAL_SupOK; } else ValRet = True; } } return ValRet; } /****************************************************************************/ void MRNoiseModel::threshold(MultiResol &MR_Data, Bool SetSupport) { int i,j,b; int Nls, Ncs; for (b = 0; b < NbrBand-1; b++) { // int w, LC_Nscale, Np; int b1,s; details which_detail; MR_Data.band_to_scale(b, s, which_detail); Nls = TabNl(b); Ncs = TabNc(b); if ((GetEgde == True) && (Transform == TO_PAVE_BSPLINE)) { int E_Nscale; Ifloat Buff(Nls,Ncs,"Buff"); E_Nscale = iround((float)log((float) (MIN(Nls,Ncs) / 4. * 3.) / log(2.))); if (one_level_per_pos_2d(TypeNoise) == True) { cout << "Error: this noise model cannot be used with this option ... " << endl; exit(-1); } float Level = TabLevel[b] * NSigma[b]; MultiResol MR_EDGE(Nls, Ncs, E_Nscale, TO_MALLAT, "MR EDGE"); MR_EDGE.TypeNorm = NORM_L2; // MR_EDGE.SBFilter=F_HAAR; MR_EDGE.SBFilter=F_MALLAT_7_9; MR_EDGE.transform(MR_Data.band(b)); for (b1= 0; b1 < MR_EDGE.nbr_band(); b1 ++) for (i = 0; i < MR_EDGE.size_band_nl(b1); i++) for (j = 0; j < MR_EDGE.size_band_nc(b1); j++) if (ABS(MR_EDGE(b1,i,j)) < Level) MR_EDGE(b1,i,j) = 0.; MR_EDGE.recons(Buff); for (i = 0; i < Nls;i++) for (j = 0; j < Ncs; j++) if (kill_coef(b,i,j,MR_Data(b,i,j),SetSupport) == True) MR_Data(b,i,j) = Buff(i,j); } /* if ((GetEgde == True) && ((Set_Transform == TRANSF_DIADIC_MALLAT) || (Set_Transform == TRANSF_MALLAT))) { switch (which_detail) { case D_HORIZONTAL: LC_Nscale = iround((float)log((float) (Ncs / 4. * 3.) / log(2.))) - s ; Np = Ncs; break; case D_VERTICAL: LC_Nscale = iround((float)log((float) (Nls / 4. * 3.) / log(2.))) - s ; Np = Nls; break; default: LC_Nscale = 0; break; } } else LC_Nscale = 0; LC_Nscale = 0; if (LC_Nscale > 1) { MR_1D MR_LINE(Np, TO1_MALLAT, "line trans", LC_Nscale); MR_LINE.SB_Filter=F_HAAR; MR_LINE.Norm = NORM_L2; MR_LINE.Border = I_CONT; fltarray Col(Np); float Nsig = 2.*NSigma[b]; if (which_detail == D_HORIZONTAL) { for (j = 0; j < Ncs; j++) { for (i = 0; i < Np; i++) Col(i) = MR_Data(b,i,j); MR_LINE.transform(Col); // thresholding assuming Gaussian noise for (b1= 0; b1 < MR_LINE.nbr_band(); b1 ++) for (w = 0; w < MR_LINE.size_scale_np(b1); w++) if (ABS(MR_LINE(b1,w)) < Nsig*sigma(b,i,j)) MR_LINE(b1,w) = 0.; MR_LINE.recons(Col); for (i = 0; i < Np; i++) if (kill_coef(b,i,j,MR_Data(b,i,j),SetSupport) == True) MR_Data(b,i,j)=Col(i); } } else { for (i = 0; i < Nls; i++) { for (j = 0; j < Np; j++) Col(j) = MR_Data(b,i,j); MR_LINE.transform(Col); // thresholding assuming Gaussian noise for (b1= 0; b1 < MR_LINE.nbr_band(); b1 ++) for (w = 0; w < MR_LINE.size_scale_np(b1); w++) if (ABS(MR_LINE(b1,w)) < Nsig*sigma(b,i,j)) MR_LINE(b1,w) = 0.; MR_LINE.recons(Col); for (j = 0; j < Np; j++) if (kill_coef(b,i,j,MR_Data(b,i,j),SetSupport) == True) MR_Data(b,i,j)=Col(j); } } } */ else { for (i = 0; i < Nls; i++) for (j = 0; j < Ncs; j++) if (kill_coef(b,i,j,MR_Data(b,i,j),SetSupport) == True) MR_Data(b,i,j)=0.; } } } /****************************************************************************/ void MRNoiseModel::refresh_support(MultiResol &MR_Data) { int i,j,s; int ValSup; int Nls, Ncs; float CoefMr; for (s = 0; s < NbrBand-1; s++) { Nls = TabNl(s); Ncs = TabNc(s); for (i = 0; i < Nls; i++) for (j = 0; j < Ncs; j++) { CoefMr = MR_Data(s,i,j); ValSup = support(s,i,j); if ( (ValSup == VAL_SupNull) && (signif(CoefMr,s,i,j) == True)) support(s,i,j)=VAL_SupOK; } } } /****************************************************************************/ void MRNoiseModel::weight_snr(MultiResol &MR_Data, Bool SetSupport) { int i,j,s; int ValSup; int Nls, Ncs; float CoefMr,Weight; for (s = 0; s < NbrBand-1; s++) { Nls = TabNl(s); Ncs = TabNc(s); for (i = 0; i < Nls; i++) for (j = 0; j < Ncs; j++) { CoefMr = MR_Data(s, i, j); ValSup = support(s,i,j); if ( (SetSupport == True) && (ValSup == VAL_SupNull) && (signif(CoefMr,s,i,j) == True)) support(s,i,j)=VAL_SupOK; Weight = ABS(CoefMr) / (NSigma[s]*sigma(s,i,j)); if (Weight > 1.) Weight = 1.; MR_Data(s, i, j) *= Weight; } } } /****************************************************************************/ void MRNoiseModel::weight_invsnr(MultiResol &MR_Data, Bool SetSupport) { int i,j,s; float CoefMr,Weight; int ValSup; int Nls, Ncs; for (s = 0; s < NbrBand-1; s++) { Nls = TabNl(s); Ncs = TabNc(s); for (i = 0; i < Nls; i++) for (j = 0; j < Ncs; j++) { CoefMr = MR_Data(s, i, j); ValSup = support(s,i,j); if ( (SetSupport == True) && (ValSup == VAL_SupNull) && (signif(CoefMr,s,i,j) == True)) support(s,i,j)=VAL_SupOK; Weight = ABS(CoefMr) / (NSigma[s]*sigma(s,i,j)); if (Weight > 1.) Weight = 1.; MR_Data(s, i, j) *= (1. - Weight); } } } /****************************************************************************/ void MRNoiseModel::set_sigma(Ifloat & Imag, MultiResol &MR_Data) { extern float mr_tab_noise(int s); int b, s,i,j,Ind; noise_compute (MR_Data); // cout << "noise_compute: set_sigma : Noise = " << SigmaNoise << endl; //Imag.info("MM"); if ((SigmaNoise < FLOAT_EPSILON) && (NewStatNoise == NOISE_GAUSSIAN)) { switch (SigmaDetectionMethod) { case SIGMA_MEDIAN: SigmaNoise = detect_noise_from_med (Imag); break; case SIGMA_BSPLINE: SigmaNoise = detect_noise_from_bspline (Imag); break; case SIGMA_CLIPIMA:SigmaNoise = detect_noise_sigma (Imag); break; case SIGMA_SUPPORT: SigmaNoise=detect_noise_from_support(Imag,MR_Data,(*this)); break; default: cerr<< "Error: MRNoiseModel:set_sigma, unknown method" << endl; exit(0);break; } } // cout << "After set_sigma : Noise = " << SigmaNoise << endl; switch (NewStatNoise) { case NOISE_SPECKLE: { // we assume that the level at 3.719sigma (eps = 1e-4) gives // a good fit of the gaussian law to the rayley noise distribution fltarray R_Eps(NbrBand-1); fltarray Tmin(NbrBand-1); fltarray Tmax(NbrBand-1); for (s = 0; s < NbrBand-1; s++) R_Eps(NbrBand-1) = 1.e-04; CSpeckle->find_threshold(NbrBand,R_Eps, Tmin, Tmax); for (s = 0; s < NbrBand-1; s++) { float Max = ABS(Tmin(s)); if (ABS(Tmin(s)) < ABS(Tmax(s))) Max = Tmax(s); TabLevel[s] = Max / 3.719; } } break; case NOISE_CORREL: for (s = 0; s < NbrBand-1; s++) TabLevel[s] = CorrelNoiseMap->sigma_band(s); break; case NOISE_GAUSSIAN: if ((Transform == TO_DIADIC_MALLAT) && (GradientAnalysis == True)) { extern double TabNormGradDiadicMallat[MAX_SCALE]; for (s = 0; s < NbrBand-1; s++) TabLevel[s] = SigmaNoise*TabNormGradDiadicMallat[s/2]; } else for (s = 0; s < NbrBand-1; s++) TabLevel[s] = SigmaNoise*MR_Data.band_norm(s); break; case NOISE_NON_UNI_ADD: if ((Set_Transform == TRANSF_MALLAT) || (Set_Transform == TRANSF_FEAUVEAU)) { cerr << "Error: this kind of transform cannot be used " << endl; cerr << " with this noise model " << endl; exit(-1); } if (UseRmsMap == False) { // Ifloat ImaSigmaNoise(Nl, Nc, "ImaSigmaNoise"); Ifloat Buff(Nl, Nc, "Buff"); RmsMap.alloc(Nl, Nc, "ImaSigmaNoise"); smooth_mediane (Imag, Buff, I_MIRROR, 0, 3); Buff = Imag - Buff; im_sigma(Buff, RmsMap, SizeBlockSigmaNoise, NiterSigmaClip); // io_write_ima_float("xx_rms.fits", RmsMap); } // calculate the true sigma at each scale : if ((RmsMap.nl() != Nl) || (RmsMap.nc() != Nc)) { cerr << "Error: RMS map is not correctly initialized ... " << endl; exit(0); } if (((Transform == TO_PAVE_BSPLINE) && (GetRmsCoeffGauss == True)) || (Transform == TO_UNDECIMATED_MALLAT) || (Transform == TO_UNDECIMATED_NON_ORTHO) || (Transform == TO_PAVE_FEAUVEAU) || (Transform == TO_DIADIC_MALLAT)) get_sigma_from_rms_map(RmsMap); else max_sigma_in_scale(RmsMap); UseRmsMap=True; break; case NOISE_UNI_UNDEFINED: for (b = 0; b < NbrBand-1; b ++) { //float SigmaScale, MeanScale; //sigma_clip(MR_Data.band(b), MeanScale, SigmaScale, NiterSigmaClip); //TabLevel[b] = SigmaScale; TabLevel[b] = detect_noise_from_mad(MR_Data.band(b), MadEstimFromCenter); } break; case NOISE_UNDEFINED: { // cout << "NOISE_UNDEFINED " << endl; Ifloat ImaSigmaNoise(Nl, Nc, "ImaSigmaNoise"); int BlockSize = SizeBlockSigmaNoise; for (b = 0; b < NbrBand-1; b++) { // cout << "Band " << b+1 << endl; int Nlb = MR_Data.size_band_nl(b); int Ncb = MR_Data.size_band_nc(b); float SigmaScale, MeanScale; //details which_detail; //MR_Data.band_to_scale(b, s, which_detail); // cout << "sigma_clip " << Nlb << " " << Ncb << endl; sigma_clip(MR_Data.band(b), MeanScale, SigmaScale, NiterSigmaClip); ImaSigmaNoise.resize(Nlb, Ncb); // If we want the full resolution, we need to uncomment the next line. // Otherwise the noise standard deviation is calculated on for position // at a distance of BlockSize/2 // im_sigma(MR_Data.band(b), ImaSigmaNoise, BlockSize, NiterSigmaClip); // use the MAD instead of sigma_clipping: im_sigma_block_mad(MR_Data.band(b), ImaSigmaNoise, BlockSize, 32); // cout << "im_sigma_block " << BlockSize << " " << NiterSigmaClip << " " << BlockSize/2 << endl; im_sigma_block(MR_Data.band(b), ImaSigmaNoise, BlockSize, NiterSigmaClip, BlockSize/2); // cout << "out_sigma_block " << Nlb << " " << Ncb << endl; for (i = 0; i < Nlb;i++) for (j = 0; j < Ncb; j++) { Ind = index(b,i,j); TabLevel[Ind] = ImaSigmaNoise(i,j); // MAX(SigmaScale, ImaSigmaNoise(i,j)); } if ((Set_Transform == TRANSF_PAVE) || ((Set_Transform == TRANSF_UNDECIMATED_MALLAT) && (b%3 == 2)) || ((Set_Transform == TRANSF_DIADIC_MALLAT) && (b%2 == 1))) BlockSize *=2; } // cout << "END NOISE_UNDEFINED " << endl; } break; case NOISE_EVENT_POISSON: { Ifloat EventCount(Nl,Nc,"ImagCount"); float alpha; for (s = 0; s < MR_Data.nbr_band()-1; s++) { alpha=1.; for (int sc=0; sc < s; sc++) alpha *= 4.; event_one_scale(Event_Image, s, EventCount, MR_Data.Border); for (i=0;i<Nl;i++) for (j=0;j<Nc;j++) { Ind = index(s,i,j); TabLevel[Ind] = SIGMA_BSPLINE_WAVELET * sqrt((float) EventCount(i,j)) / alpha; } } } break; default: break; } } /****************************************************************************/ void MRNoiseModel::speckle_support(MultiResol &MR_Data) { int Nlb, Ncb, i,j,b; float Max; fltarray R_Eps(NbrBand-1); fltarray Tmin(NbrBand-1); fltarray Tmax(NbrBand-1); for (b = 0; b < NbrBand-1; b++) R_Eps(b) = TabEps[b]; CSpeckle->find_threshold(MR_Data.nbr_band(), R_Eps, Tmin, Tmax); for (b = 0; b < MR_Data.nbr_band()-1; b++) { Max = ABS(Tmin(b)); if (Max < ABS(Tmax(b))) Max = Tmax(b); TabLevel[b] = ABS(Max) / NSigma[b]; Nlb = MR_Data.size_band_nl(b); Ncb = MR_Data.size_band_nc(b); for (i = 0; i < Nlb;i++) for (j = 0; j < Ncb; j++) { if (signif(MR_Data(b,i,j), b,i,j,Tmin(b),Tmax(b)) == True) support(b,i,j)=VAL_SupOK; else support(b,i,j)=VAL_SupNull; } } if (SupIsol == True) for (b = 0; b < NbrBand-2; b++) kill_isol(b); if (DilateSupport == True) for (b = 0; b < NbrBand-1; b++) dilate_support(b); } /****************************************************************************/ void MRNoiseModel::correl_support(MultiResol &MR_Data) { int Nlb, Ncb, i,j,b; fltarray R_Eps(NbrBand-1); fltarray Tmin(NbrBand-1); fltarray Tmax(NbrBand-1); for (b = 0; b < NbrBand-1; b++) R_Eps(b) = TabEps[b]; CorrelNoiseMap->find_threshold(MR_Data.nbr_band(), R_Eps, Tmin, Tmax); for (b = 0; b < MR_Data.nbr_band()-1; b++) { TabLevel[b] = CorrelNoiseMap->sigma_band(b); Nlb = MR_Data.size_band_nl(b); Ncb = MR_Data.size_band_nc(b); for (i = 0; i < Nlb;i++) for (j = 0; j < Ncb; j++) { if (signif(MR_Data(b,i,j), b,i,j,Tmin(b),Tmax(b)) == True) support(b,i,j)=VAL_SupOK; else support(b,i,j)=VAL_SupNull; } } if (SupIsol == True) for (b = 0; b < NbrBand-2; b++) kill_isol(b); if (DilateSupport == True) for (b = 0; b < NbrBand-1; b++) dilate_support(b); } /****************************************************************************/ void MRNoiseModel::model(Ifloat & Imag, MultiResol &MR_Data) { NewStatNoise = TypeNoise; //int s; // if TypeNoise != NOISE_EVENT_POISSON and MinEvent == True // the parameter Event_Image must be intialized before the // call to model if ((MinEvent == True) && (TypeNoise != NOISE_EVENT_POISSON)) { if ( (TypeNoise == NOISE_EVENT_POISSON) && (Imag.nl() != Event_Image.nl()) && (Imag.nc() != Event_Image.nc())) { cerr << "Error: MRNoiseModel::model : Event_Image is not correctly Initialized ..." << endl; exit(-1); } } // if TypeNoise == NOISE_EVENT_POISSON and TransImag == False // the parameter Event_Image must be intialized before the // call to model if ( (TypeNoise == NOISE_EVENT_POISSON) && (TransImag == False) && ((Imag.nl() != Event_Image.nl()) || (Imag.nc() != Event_Image.nc()))) { cerr << "Error: MRNoiseModel::model : Event_Image is not correctly Initialized ..." << endl; exit(-1); } switch (TypeNoise) { case NOISE_POISSON: case NOISE_GAUSS_POISSON: SigmaNoise = 1.; case NOISE_MULTI: if (TransImag == True) im_transform(Imag); NewStatNoise = NOISE_GAUSSIAN; break; case NOISE_GAUSSIAN: case NOISE_NON_UNI_ADD: case NOISE_UNI_UNDEFINED: case NOISE_UNDEFINED: case NOISE_CORREL: break; case NOISE_NON_UNI_MULT: if (TransImag == True) im_transform(Imag); NewStatNoise = NOISE_NON_UNI_ADD; break; case NOISE_EVENT_POISSON: if (TransImag == True) im_transform(Imag); // in case of Poisson noise, the MIRROR border must be used MR_Data.Border = I_MIRROR; TransImag = False; SigmaNoise = 1.; break; case NOISE_SPECKLE: if (TransImag == True) im_transform(Imag); break; } // transform the input data Border = MR_Data.Border; U_Filter = MR_Data.U_Filter; TypeNorm = MR_Data.TypeNorm; FilterBank = MR_Data.filter_bank(); NbrUndecimatedScale = MR_Data.nbr_undec_scale(); MR_Data.SigmaNoise = SigmaNoise; // cout << "MR_Data.transform" << endl; MR_Data.transform(Imag); switch (TypeNoise) { case NOISE_POISSON: case NOISE_GAUSS_POISSON: case NOISE_MULTI: case NOISE_NON_UNI_MULT: set_sigma(Imag, MR_Data); set_support(MR_Data); if (TransImag == True) im_invtransform(Imag); break; case NOISE_GAUSSIAN: case NOISE_NON_UNI_ADD: case NOISE_UNDEFINED: case NOISE_UNI_UNDEFINED: // cout << "set_sigma" << endl; set_sigma(Imag, MR_Data); // cout << "set_support" << endl; set_support(MR_Data); // cout << "ok" << endl; break; case NOISE_CORREL: if (CorrelNoiseMap != NULL) delete CorrelNoiseMap; CorrelNoiseMap = new StatNoiseMap(RmsMap, NbrScale, Transform, FilterBank, TypeNorm, NbrUndecimatedScale, U_Filter); if (SigmaApprox == False) correl_support(MR_Data); else { set_sigma(Imag, MR_Data); set_support(MR_Data); } break; case NOISE_EVENT_POISSON: if (SigmaApprox == False) // Default { Bool WriteAllInfo = False; mr2d_psupport( MR_Data, (*this), MR_Data.Border, WriteAllInfo ); //mr_psupport(MR_Data, (*this), MR_Data.Border); if (SupIsol == True) for (int b = 0; b < NbrBand-2; b++) kill_isol(b); } else { set_sigma(Imag, MR_Data); set_support(MR_Data); } break; case NOISE_SPECKLE: if (SigmaApprox == False) speckle_support(MR_Data); else { set_sigma(Imag, MR_Data); set_support(MR_Data); } if (TransImag == True) im_invtransform(Imag); break; } // ALREADY done in MR_Psup.cc // verify if minimum number of count OK // if (MinEvent == True) // { // // if (TypeNoise == NOISE_EVENT_POISSON) // // for (int s=0; s < NbrBand-1; s++) kill_event(s, Imag); // } } /****************************************************************************/ void MRNoiseModel::model(Ifloat & Imag) { // MultiResol MR_Data(Nl, Nc, NbrScale, Transform, "MRNoiseModel"); MultiResol MR_Data; MR_Data.alloc (Nl, Nc, NbrScale, Transform, FilterBank, TypeNorm, NbrUndecimatedScale, U_Filter); model(Imag, MR_Data); } /****************************************************************************/ void MRNoiseModel::free() { if (Size > 0) { if (one_level_per_pos_2d(TypeNoise) == True) free_buffer((char *) TabLevel); else delete [] TabLevel; free_buffer((char *) TabSupport); NbrScale = 0; Nl = 0; Nc = 0; Size = 0; //if (CEventPois != NULL) delete CEventPois; if (CFewEventPoisson2d != NULL) delete CFewEventPoisson2d; if (CFewEvent2d != NULL) delete CFewEvent2d; if (CSpeckle != NULL) delete CSpeckle; if (CorrelNoiseMap != NULL) delete CorrelNoiseMap; } } /****************************************************************************/ MRNoiseModel::~MRNoiseModel() { (*this).free(); } /****************************************************************************/ void MRNoiseModel::mr_obj(MultiResol &MR_Data) { int i,j,s; for (s = 0; s < NbrBand-1; s++) for (i = 0; i < TabNl(s);i++) for (j = 0; j < TabNc(s); j++) { if ((*this)(s,i,j) == True) MR_Data(s,i,j) = 1.; else MR_Data(s,i,j) = 0.; } } /****************************************************************************/ void MRNoiseModel::write_support_mr(char *FileName) { MultiResol MR_Data; MR_Data.alloc (Nl, Nc, NbrScale, Transform, FilterBank, TypeNorm, NbrUndecimatedScale); (*this).mr_obj(MR_Data); MR_Data.write(FileName); } /****************************************************************************/ void MRNoiseModel::write_support_ima(char *FileName) { MultiResol MR_Data; MR_Data.alloc (Nl, Nc, NbrScale, Transform, FilterBank, TypeNorm, NbrUndecimatedScale); (*this).mr_obj(MR_Data); float Coef; Ifloat Ima(Nl, Nc, "MRNoiseModel write"); int s,i,j; Ima.init(); switch (Set_Transform) { case TRANSF_PAVE: case TRANSF_PYR: case TRANSF_DIADIC_MALLAT: case TRANSF_UNDECIMATED_MALLAT: case TRANSF_SEMIPYR: { Ifloat Dat(Nl, Nc, "MRNoiseModel write"); for (s = NbrBand-2; s >= 0; s--) { Coef = (float) ( 1 << (NbrBand-1-s)); im_block_extend(MR_Data.band(s), Dat); // cout << "Coef = " << Coef << endl; // cout << MR_Data.band(s).nl() << " to " << Dat.nl() << endl; // cout << MR_Data.band(s).nc() << " to " << Dat.nc() << endl; for (i = 0; i < Dat.nl();i++) for (j = 0; j < Dat.nc(); j++) if (Dat(i,j) > FLOAT_EPSILON) Ima(i,j) = Coef; } } break; case TRANSF_MALLAT: case TRANSF_FEAUVEAU: ortho_trans_to_ima(MR_Data, Ima); break; default: cerr << "Error: Unknown set transform ... " << endl; exit(0); break; } io_write_ima_float(FileName, Ima); } void MRNoiseModel::set_old_poisson( Bool Flag ) { mOldPoisson = Flag; if( mOldPoisson ) std::cout << "!!! Odl poisson few event class is used !!!" << std::endl; } Bool MRNoiseModel::old_poisson() { return mOldPoisson; } void MRNoiseModel::write_threshold( Bool Flag ) { mWriteThreshold = Flag; } void MRNoiseModel::write_in_few_event( Bool Write ) { if( CFewEvent2d != (FewEvent*)NULL ) CFewEvent2d->set_write_all( Write ) ; } /****************************************************************************/ void MRNoiseModel::trace() { cout << "class MRNoiseModel" << endl; cout << "------------------" << endl; cout << "NbrScale = " << NbrScale << endl; cout << "NbrBand = " << NbrBand << endl; cout << "Nl = " << Nl << endl; cout << "Nc = " << Nc << endl; cout << "Size = " << Size << endl; cout << "Transform = " << StringTransform(Transform) << endl; cout << "Set_Transform = " << StringSetTransform(Set_Transform) << endl; cout << "TypeNoise = " << StringNoise(TypeNoise) << endl; cout << "Border = " << (int)Border << endl; cout << "NSigma : " << endl; for (int i=0;i<NbrBand;i++) cout << " scale[i] : " << NSigma[i] << endl; if (SigmaApprox) cout << "SigmaApprox = true" << endl; cout << "TypeNorm = " << (int)DEF_SB_NORM << endl; cout << "NbrUndecimatedScale = " << (int)NbrUndecimatedScale << endl; if (GradientAnalysis) cout << "GradientAnalysis = true" << endl; if (NoCompDistrib) cout << "NoCompDistrib = true" << endl; cout << "Size = " << (int)Size << endl; cout << "BadPixelVal = " << BadPixelVal << endl; if (BadPixel) cout << "BadPixel = true" << endl; if (MinEvent) cout << "MinEvent = true" << endl; if (SupIsol) cout << "SupIsol = true" << endl; cout << "FirstDectectScale = " << FirstDectectScale << endl; if (OnlyPositivDetect) cout << "OnlyPositivDetect = true" << endl; if (DilateSupport) cout << "DilateSupport = true" << endl; if (GetEgde) cout << "GetEgde = true" << endl; cout << "MinEventNumber = " << MinEventNumber << endl; cout << "SigmaDetectionMethod = " << (int)SigmaDetectionMethod << endl; cout << "NiterSigmaClip = " << (int)NiterSigmaClip << endl; cout << "SizeBlockSigmaNoise = " << SizeBlockSigmaNoise << endl; if (TransImag) cout << "TransImag = true" << endl; if (UseRmsMap) cout << "UseRmsMap = true" << endl; if (GetRmsCoeffGauss) cout << "GetRmsCoeffGauss = true" << endl; if (SigmaApprox) cout << "SigmaApprox = true" << endl; if (TabLevel == NULL) cout << "TabLevel = NULL" << endl; if (TabSupport == NULL) cout << "TabSupport = NULL" << endl; //if (CEventPois == NULL) cout << "CEventPois = NULL" << endl; if (CFewEventPoisson2d == NULL) cout << "CFewEventPoisson2d = NULL" << endl; if (CFewEvent2d == NULL) cout << "CFewEventPoisson2d = NULL" << endl; if (CSpeckle == NULL) cout << "CSpeckle = NULL" << endl; if (CorrelNoiseMap == NULL) cout << "CorrelNoiseMap = NULL" << endl; if (FilterBank == NULL) cout << "FilterBank = NULL" << endl; cout << "end class MRNoiseModel" << endl; }
31.77546
129
0.477404
jstarck
5deb11b2b625dc4a762fa6ca09adcf714906b83c
1,519
cpp
C++
src/PlayMusicOnStartC.cpp
NoVariableGlobal/g.shift
35907cd4aa931dbef8d15cade76d8cab1d11716c
[ "MIT" ]
null
null
null
src/PlayMusicOnStartC.cpp
NoVariableGlobal/g.shift
35907cd4aa931dbef8d15cade76d8cab1d11716c
[ "MIT" ]
null
null
null
src/PlayMusicOnStartC.cpp
NoVariableGlobal/g.shift
35907cd4aa931dbef8d15cade76d8cab1d11716c
[ "MIT" ]
1
2020-10-07T15:09:57.000Z
2020-10-07T15:09:57.000Z
#include "PlayMusicOnStartC.h" #include "ComponentsManager.h" #include "Entity.h" #include "FactoriesFactory.h" #include "Scene.h" #include "SoundComponent.h" #include <json.h> // COMPONENT CODE void PlayMusicOnStartC::destroy() { stopCurrentMusic(music_); setActive(false); scene_->getComponentsManager()->eraseDC(this); } void PlayMusicOnStartC::setMusic(const std::string& sound) { if (music_ != sound) { reinterpret_cast<SoundComponent*>( father_->getComponent("SoundComponent")) ->stopSound(music_); music_ = sound; reinterpret_cast<SoundComponent*>( father_->getComponent("SoundComponent")) ->playSound(music_); } } void PlayMusicOnStartC::stopCurrentMusic(const std::string& sound) { reinterpret_cast<SoundComponent*>(father_->getComponent("SoundComponent")) ->stopSound(sound); } // FACTORY INFRASTRUCTURE DEFINITION PlayMusicOnStartCFactory::PlayMusicOnStartCFactory() = default; Component* PlayMusicOnStartCFactory::create(Entity* _father, Json::Value& _data, Scene* _scene) { PlayMusicOnStartC* play = new PlayMusicOnStartC(); _scene->getComponentsManager()->addDC(play); play->setFather(_father); play->setScene(_scene); if (!_data["sound"].isString()) throw std::exception("PlayMusicOnStartC: sound is not a string"); play->setMusic(_data["sound"].asString()); return play; } DEFINE_FACTORY(PlayMusicOnStartC)
27.618182
80
0.677419
NoVariableGlobal
5dec5ba4bc3a4d54edf53ad196833bb2c6cdb1e9
3,344
cpp
C++
searchcore/src/vespa/searchcore/fdispatch/common/timestat.cpp
yehzu/vespa
a439476f948f52a57485f5e7700b17bf9aa73417
[ "Apache-2.0" ]
1
2018-12-30T05:42:18.000Z
2018-12-30T05:42:18.000Z
searchcore/src/vespa/searchcore/fdispatch/common/timestat.cpp
yehzu/vespa
a439476f948f52a57485f5e7700b17bf9aa73417
[ "Apache-2.0" ]
1
2021-03-31T22:27:25.000Z
2021-03-31T22:27:25.000Z
searchcore/src/vespa/searchcore/fdispatch/common/timestat.cpp
yehzu/vespa
a439476f948f52a57485f5e7700b17bf9aa73417
[ "Apache-2.0" ]
1
2020-02-01T07:21:28.000Z
2020-02-01T07:21:28.000Z
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "timestat.h" void FastS_TimeStatHistory::Reset() { _sampleAccTime = 0.0; _totalAccTime = 0.0; _sampleIdx = 0; _sampleCount = 0; _totalCount = 0; for (uint32_t i = 0; i < _timestatssize; i++) _sampleTimes[i] = Sample(); } double FastS_TimeStatHistory::GetMaxTime() const { double max = 0.0; uint32_t idx = _sampleIdx; for (uint32_t residue = _sampleCount; residue > 0; residue--) { if (idx > 0) idx--; else idx = _timestatssize - 1; if (_sampleTimes[idx]._time > max) max = _sampleTimes[idx]._time; } return max; } void FastS_TimeStatHistory::Update(double tnow, double t, bool timedout) { uint32_t timeIdx = getTimeIdx(tnow); if (_slotCount == 0u) { _timeSlots[_slotIdx].init(timeIdx); ++_slotCount; } else { TimeSlot &ts = _timeSlots[_slotIdx]; if (ts._timeIdx > timeIdx) timeIdx = ts._timeIdx; if (ts._timeIdx < timeIdx) { if (_slotCount < NUM_TIMESLOTS) ++_slotCount; _slotIdx = nextTimeSlot(_slotIdx); _timeSlots[_slotIdx].init(timeIdx); } } _timeSlots[_slotIdx].update(t, timedout); _totalAccTime += t; ++_totalCount; if (timedout) ++_totalTimeouts; if (_sampleCount >= _timestatssize) { const Sample &s = _sampleTimes[_sampleIdx]; _sampleAccTime -= s._time; if (s._timedout) --_sampleTimeouts; --_sampleCount; } _sampleTimes[_sampleIdx] = Sample(t, timedout); _sampleAccTime += t; if (timedout) ++_sampleTimeouts; _sampleIdx++; if (_sampleIdx >= _timestatssize) _sampleIdx = 0; ++_sampleCount; } void FastS_TimeStatHistory::getRecentStats(double tsince, FastS_TimeStatTotals &totals) { uint32_t timeIdx = getTimeIdx(tsince); uint32_t slotCount = _slotCount; uint32_t slotIdx = _slotIdx; for (; slotCount > 0u && _timeSlots[slotIdx]._timeIdx >= timeIdx; --slotCount, slotIdx = prevTimeSlot(slotIdx)) { TimeSlot &ts = _timeSlots[slotIdx]; totals._totalCount += ts._count; totals._totalTimeouts += ts._timeouts; totals._totalAccTime += ts._accTime; } } double FastS_TimeStatHistory::getLoadTime(double tsince, double tnow) { const uint32_t holeSize = 2; // 2 missing slots => hole const uint32_t minSlotLoad = 4; // Mininum load for not being "missing" uint32_t sinceTimeIdx = getTimeIdx(tsince); uint32_t timeIdx = getTimeIdx(tnow); uint32_t slotCount = _slotCount; uint32_t slotIdx = _slotIdx; uint32_t doneTimeIdx = timeIdx; for (; slotCount > 0u; --slotCount, slotIdx = prevTimeSlot(slotIdx)) { TimeSlot &ts = _timeSlots[slotIdx]; if (ts._timeIdx + holeSize < doneTimeIdx) break; // Found hole, i.e. holeSize missing slots if (ts._timeIdx + holeSize < sinceTimeIdx) break; // No point in looking further back if (ts._count >= minSlotLoad) doneTimeIdx = ts._timeIdx; } return tnow - getTimeFromTimeIdx(doneTimeIdx); }
28.581197
118
0.614234
yehzu
5def05c6497532561c420c99e28ef891b12862e6
496
cpp
C++
source/main.cpp
Sticky-Bits/voxel_engine
d730c6bc652df11d0ca6cfe750bf32fb71906440
[ "MIT" ]
null
null
null
source/main.cpp
Sticky-Bits/voxel_engine
d730c6bc652df11d0ca6cfe750bf32fb71906440
[ "MIT" ]
null
null
null
source/main.cpp
Sticky-Bits/voxel_engine
d730c6bc652df11d0ca6cfe750bf32fb71906440
[ "MIT" ]
null
null
null
#include <stdlib.h> #include "Game.h" int main() { // Load settings Settings* p_settings = new Settings(); p_settings->load_settings(); // Create game using settings Game* p_game = Game::get_instance(); p_game->create(p_settings); // Main loop while (!p_game->should_close()) { // Poll input events p_game->poll_events(); // Update p_game->update(); // Render p_game->render(); } // Destroy objects, window etc. p_game->destroy(); // Exit exit(EXIT_SUCCESS); }
14.588235
39
0.65121
Sticky-Bits
5def8e8e8d39e584d096d1f97b7676a1d132b9bc
2,639
cpp
C++
graph-source-code/404-C/9402829.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/404-C/9402829.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/404-C/9402829.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: GNU C++0x //created by Yash Sadhwani //sadhwaniyash6 #include<stdio.h> #include<iostream> #include<vector> #include<string.h> #include<algorithm> #include<deque> #include<map> #include<set> #include<stdlib.h> #include<math.h> #include<queue> #include<functional> using namespace std; #define ll long long #define si(x) scanf("%d",&x) #define sc(x) scanf("%c",&x) #define vl vector<ll> #define vi vector<int> #define vvl vector< vl > #define vvi vector< vi > #define pb push_back #define mod 1000000009 #define mem(x,y) memset(x,y,sizeof(x)) #define f(i,a,b) for(int i=(a);i<(b);i++) #define max_int_value 2147483647 #define max_long_value 9223372036854775807 //qsort(ww,cc,sizeof(tp),compare); /*int compare(const void *a,const void *b){ ll y=((((tp*)a)->w)-(((tp*)b)->w)); if(y>0)return 1; else if(y==0)return 0; else return -1; }*/ #define MAXN 100010 #define ii pair<int,int> ii d[MAXN]; int N,K; int edges[MAXN]; vector<ii> ans; int len[MAXN]; inline void ReadInput(void){ si(N); si(K); for(int i=1;i<=N;i++){ int x; si(x); d[i]=ii(x,i); len[i]=x; } } inline void solve(void){ if(N==1 && K==0){ if(d[1].first==0){ cout<<"0\n"; return; }else{ cout<<"-1\n"; return; } } else if(N==1){ cout<<"-1\n"; return; } else if(K==0){ cout<<"-1\n"; return; } sort(d+1,d+N+1); queue<int> pp; pp.push(d[1].second); if(d[1].first!=0){ cout<<"-1\n"; return; } for(int i=2;i<=N;i++){ while(!pp.empty() && (edges[pp.front()]==K || len[pp.front()]<len[d[i].second]-1))pp.pop(); if(pp.empty()){ cout<<"-1\n"; return; } int u=pp.front(); //cout<<u<<" "<<d[i].second<<endl; if(len[u]==len[d[i].second]){ cout<<"-1\n"; return; } //cout<<"hello\n"; if(edges[u]<K && len[u]+1==len[d[i].second]){ edges[u]++; edges[d[i].second]++; pp.push(d[i].second); ans.pb(ii(u,d[i].second)); if(edges[u]==K)pp.pop(); //cout<<u<<" "<<d[i].second<<endl; } } cout<<ans.size()<<endl; for(int i=0;i<ans.size();i++)cout<<ans[i].first<<" "<<ans[i].second<<endl; } inline void Refresh(void){ fill(edges,edges+MAXN,0); } int main() { ReadInput(); Refresh(); solve(); return 0; }
21.991667
101
0.483516
AmrARaouf
5df362d247ca17517db8dc6d3d85858190dac9db
710
cpp
C++
Online Judges/CodeChef/NOLOGIC/9288037_AC_0ms_3276kB.cpp
moni-roy/COPC
f5918304815413c18574ef4af2e23a604bd9f704
[ "MIT" ]
4
2017-02-20T17:41:14.000Z
2019-07-15T14:15:34.000Z
Online Judges/CodeChef/NOLOGIC/9288037_AC_0ms_3276kB.cpp
moni-roy/COPC
f5918304815413c18574ef4af2e23a604bd9f704
[ "MIT" ]
null
null
null
Online Judges/CodeChef/NOLOGIC/9288037_AC_0ms_3276kB.cpp
moni-roy/COPC
f5918304815413c18574ef4af2e23a604bd9f704
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int ts,vs[30]; string s; cin>>ts; getchar(); while(ts--) { getline(cin,s); int l = s.size(); memset(vs,0,sizeof vs); for(int i=0; i<l; i++) { if(isalpha(s[i])) { s[i]= tolower(s[i]); vs[s[i]-'a']=1; } } int f = 0; char Ans ; for(int i=0; i<26; i++) { if(vs[i]==0) { f=1; Ans = (char)(i+'a'); break; } } if(f) cout<<Ans<<endl; else cout<<"~"<<endl; } return 0; }
18.205128
36
0.323944
moni-roy
5df3db5beeb54baf4b1d1c617d7f80cd345c849c
2,401
cpp
C++
src/qt/qtbase/tests/manual/widgets/itemviews/qtreeview/main.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
src/qt/qtbase/tests/manual/widgets/itemviews/qtreeview/main.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/tests/manual/widgets/itemviews/qtreeview/main.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtWidgets> int main(int argc, char *argv[]) { QApplication app(argc, argv); QFileSystemModel model; QWidget window; QTreeView *tree = new QTreeView(&window); tree->setMaximumSize(1000, 600); QHBoxLayout *layout = new QHBoxLayout; layout->setSizeConstraint(QLayout::SetFixedSize); layout->addWidget(tree); window.setLayout(layout); model.setRootPath(""); tree->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents); tree->setModel(&model); tree->setAnimated(false); tree->setIndentation(20); tree->setSortingEnabled(true); tree->header()->setStretchLastSection(false); window.setWindowTitle(QObject::tr("Dir View")); tree->header()->setSectionResizeMode(QHeaderView::ResizeToContents); window.show(); return app.exec(); }
36.938462
77
0.688047
power-electro
5df3f62863952cbba5581906d60a098a129cc588
436
hpp
C++
cpp/include/init_numpy.hpp
davidkleiven/WangLandau
0b253dd98033c53560fe95c76f5e38257834bdf6
[ "MIT" ]
2
2022-02-10T00:38:53.000Z
2022-03-17T22:08:40.000Z
cpp/include/init_numpy.hpp
davidkleiven/CEMC
0b253dd98033c53560fe95c76f5e38257834bdf6
[ "MIT" ]
30
2018-05-21T14:52:00.000Z
2021-02-24T07:45:09.000Z
cpp/include/init_numpy.hpp
davidkleiven/WangLandau
0b253dd98033c53560fe95c76f5e38257834bdf6
[ "MIT" ]
3
2018-10-09T14:03:32.000Z
2022-02-09T05:36:05.000Z
#ifndef INIT_NUMPY_H #define INIT_NUMPY_H #include <Python.h> #define PY_ARRAY_UNIQUE_SYMBOL CE_UPDATER_ARRAY_API #include "numpy/ndarrayobject.h" #if PY_MAJOR_VERSION >= 3 inline int* init_numpy() { import_array(); // Avoid compilation warning // import_array is a macro that inserts a return statement // so it has no practical effect return NULL; }; #else inline void init_numpy() { import_array(); }; #endif #endif
18.166667
61
0.743119
davidkleiven
5df5dd9b588e787cca0c343de28b3cd84fa752b7
443
cpp
C++
lectures/week-02/calc.cpp
programming-workshop-2/course-material
898ca41343f49c0c96e380bd569631e2be339a8c
[ "MIT" ]
1
2017-01-13T17:44:15.000Z
2017-01-13T17:44:15.000Z
lectures/week-02/calc.cpp
programming-workshop-2/course-material
898ca41343f49c0c96e380bd569631e2be339a8c
[ "MIT" ]
null
null
null
lectures/week-02/calc.cpp
programming-workshop-2/course-material
898ca41343f49c0c96e380bd569631e2be339a8c
[ "MIT" ]
2
2017-02-01T00:36:54.000Z
2017-03-14T16:01:00.000Z
#include <iostream> #include <fstream> using namespace std; int main(int argc, char** argv) { char op; double v1, v2, ans; op = argv[1][0]; v1 = atof(argv[2]); v2 = atof(argv[3]); switch (op) { case '+': ans = v1 + v2; break; case '-': ans = v1 - v2; break; case '/': ans = v1 / v2; break; case 'x': ans = v1 * v2; break; } cout << v1 << " " << op << " " << v2 << " = " << ans << endl; return 0; }
17.038462
63
0.48307
programming-workshop-2
5df70854e8ea8137f0b0b570138c80120d0cbee3
1,013
cpp
C++
cpp_kernels/port_width_widening/src/krnl_base.cpp
kapil2099/Vitis_Accel_Examples
05f898ab0fb808421316fad9fb7dd862d92eb623
[ "Apache-2.0" ]
null
null
null
cpp_kernels/port_width_widening/src/krnl_base.cpp
kapil2099/Vitis_Accel_Examples
05f898ab0fb808421316fad9fb7dd862d92eb623
[ "Apache-2.0" ]
null
null
null
cpp_kernels/port_width_widening/src/krnl_base.cpp
kapil2099/Vitis_Accel_Examples
05f898ab0fb808421316fad9fb7dd862d92eb623
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2020 Xilinx, Inc * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located at * * http://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 size 512 extern "C" { void krnl_base(const int *a, const int *b, int *res) { int X_accum = 0; int Y_accum = 0; int i, j; int X_aux[size]; int y_aux[size]; SUM_X: for (i = 0; i < size; i++) { X_accum += a[i]; X_aux[i] = X_accum; } SUM_Y: for (i = 0; i < size; i++) { Y_accum += b[i]; y_aux[i] = Y_accum; } MUL: for (i = 0; i < size; i++) { res[i] = X_aux[i] * y_aux[i]; } } }
22.021739
75
0.641658
kapil2099
5df728314923c9851bdf1ccd25adb5e7a4f0af19
506
cpp
C++
telegram/TMessagesProj/jni/voip/tgcalls/VideoCaptureInterface.cpp
SAFE-anwang/SafeWallet-android
ac1ddfc262b34e398b4504c65ac74911b7ca4381
[ "MIT" ]
null
null
null
telegram/TMessagesProj/jni/voip/tgcalls/VideoCaptureInterface.cpp
SAFE-anwang/SafeWallet-android
ac1ddfc262b34e398b4504c65ac74911b7ca4381
[ "MIT" ]
null
null
null
telegram/TMessagesProj/jni/voip/tgcalls/VideoCaptureInterface.cpp
SAFE-anwang/SafeWallet-android
ac1ddfc262b34e398b4504c65ac74911b7ca4381
[ "MIT" ]
2
2022-03-26T11:06:16.000Z
2022-03-26T11:13:21.000Z
#include "VideoCaptureInterface.h" #include "VideoCaptureInterfaceImpl.h" namespace tgcalls { std::unique_ptr<VideoCaptureInterface> VideoCaptureInterface::Create( std::shared_ptr<Threads> threads, std::string deviceId, bool isScreenCapture, std::shared_ptr<PlatformContext> platformContext) { return std::make_unique<VideoCaptureInterfaceImpl>(deviceId, isScreenCapture, platformContext, std::move(threads)); } VideoCaptureInterface::~VideoCaptureInterface() = default; } // namespace tgcalls
31.625
116
0.804348
SAFE-anwang
5df9810a6707fe3c44c98d9f45dc9f4044a81571
2,150
cpp
C++
apps/src/videostitch-live-gui/src/livesettings.cpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
182
2019-04-19T12:38:30.000Z
2022-03-20T16:48:20.000Z
apps/src/videostitch-live-gui/src/livesettings.cpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
107
2019-04-23T10:49:35.000Z
2022-03-02T18:12:28.000Z
apps/src/videostitch-live-gui/src/livesettings.cpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
59
2019-06-04T11:27:25.000Z
2022-03-17T23:49:49.000Z
// Copyright (c) 2012-2017 VideoStitch SAS // Copyright (c) 2018 stitchEm #include "livesettings.hpp" #include "guiconstants.hpp" #include "libvideostitch-base/common-config.hpp" #include <QDir> LiveSettings::LiveSettings(const QString& settingsName) : VSSettings(settingsName) {} LiveSettings* LiveSettings::createLiveSettings() { Q_ASSERT(qApp != nullptr); LiveSettings* liveSettings = getLiveSettings(); if (!liveSettings) { liveSettings = new LiveSettings(VAHANA_VR_SETTINGS_NAME); liveSettings->setParent(qApp); } return liveSettings; } LiveSettings* LiveSettings::getLiveSettings() { Q_ASSERT(qApp != nullptr); return qApp->findChild<LiveSettings*>(); } int LiveSettings::getLogLevel() const { return settings.value("logLevel", 0).toInt(); } int LiveSettings::getOutputConnectionTimeout() const { return settings.value("output/timeout", 10000).toInt(); } int LiveSettings::getOutputReconnectionTimeout() const { return settings.value("output/reconnectiontimeout", 6500).toInt(); } bool LiveSettings::getShowCalibrationCounter() const { return settings.value("showCalibrationCounter", true).toBool(); } bool LiveSettings::getMirrorModeEnabled() const { return settings.value("oculus/mirrorModeEnabled", false).toBool(); } QString LiveSettings::getSnapshotPath() const { QString defaultValue = QDir::toNativeSeparators(getSnapshotsPath()); return settings.value("snapshotPath", defaultValue).toString(); } void LiveSettings::setLogLevel(const int level) { settings.setValue("logLevel", level); } void LiveSettings::setOutputConnectionTimeout(const int timeout) { settings.setValue("output/timeout", timeout); } void LiveSettings::setOutputReconnectionTimeout(const int timeout) { settings.setValue("output/reconnectiontimeout", timeout); } void LiveSettings::setShowCalibrationCounter(const bool show) { settings.setValue("showCalibrationCounter", show); } void LiveSettings::setMirrorModeEnabled(const bool mirrorModeEnabled) { settings.setValue("oculus/mirrorModeEnabled", mirrorModeEnabled); } void LiveSettings::setSnapshotPath(const QString& path) { settings.setValue("snapshotPath", path); }
37.068966
120
0.775814
tlalexander
5dfa47f3c8891104f93dbb311354153378ac67ab
1,844
cpp
C++
LayZ/src/math/vec2.cpp
AliKhudiyev/LayZ-Renderer-Engine
8e8943295f6f80a05c1ba2b7c7c1b3e51779a272
[ "MIT" ]
11
2020-06-25T20:52:56.000Z
2021-04-27T05:37:22.000Z
LayZ/src/math/vec2.cpp
AliKhudiyev/LayZ-Renderer-Engine
8e8943295f6f80a05c1ba2b7c7c1b3e51779a272
[ "MIT" ]
3
2020-06-29T14:21:52.000Z
2020-07-06T17:41:45.000Z
LayZ/src/math/vec2.cpp
AliKhudiyev/LayZ-Renderer-Engine
8e8943295f6f80a05c1ba2b7c7c1b3e51779a272
[ "MIT" ]
2
2020-07-09T22:07:14.000Z
2021-02-05T22:04:57.000Z
#include "math/vec2.h" #include <cassert> namespace lyz { namespace math { vec2::vec2(float x, float y) { data[0] = x; data[1] = y; } vec2::vec2(const float* fdata) { data[0] = fdata[0]; data[1] = fdata[1]; } vec2::vec2(const vec2& vec) { data[0] = vec.data[0]; data[1] = vec.data[1]; } vec2::~vec2() { ; } float vec2::dist(const vec2 & vec) const { return powf(powf(data[0] - vec.data[0], 2) + pow(data[1] - vec.data[1], 2), 0.5); } float vec2::dot(const vec2 & vec) const { return data[0] * vec.data[0] + data[1] * vec.data[1]; } vec2 vec2::add(const vec2 & vec) const { return vec2(data[0] + vec.data[0], data[1] + vec.data[1]); } vec2 vec2::subtract(const vec2 & vec) const { return vec2(data[0] - vec.data[0], data[1] - vec.data[1]); } vec2 vec2::mult(const vec2& vec) const { return vec2(data[0] * vec.data[0], data[1] * vec.data[1]); } vec2 vec2::mult(float val) const { return vec2(val * data[0], val * data[1]); } float vec2::operator[](unsigned int i) const { assert(i < 2); return data[i]; } vec2 vec2::operator+(const vec2 & vec) const { return vec2(); } vec2 vec2::operator-(const vec2 & vec) const { return add(vec); } vec2& vec2::operator+=(const vec2 & vec) { *this = *this + vec; return *this; } vec2& vec2::operator-=(const vec2 & vec) { *this = *this - vec; return *this; } vec2& vec2::operator=(const vec2& vec) { data[0] = vec.data[0]; data[1] = vec.data[1]; return *this; } bool vec2::operator==(const vec2 & vec) const { return (data[0] == vec.data[0] && data[1] == vec.data[1]); } bool vec2::operator!=(const vec2 & vec) const { return !(*this == vec); } } } std::ostream &operator<<(std::ostream &stream, const lyz::math::vec2 &v) { stream << "(" << v[0] << ", " << v[1] << ")"; return stream; }
17.730769
83
0.574837
AliKhudiyev
b9012a8282cdeded891a00442d30a674680ee591
1,041
cpp
C++
lib/LuaObject.cpp
indie-zen-plugins/ZLua
6fff6e889a27152ed85b0c0c0786e6b8706f2247
[ "MIT" ]
null
null
null
lib/LuaObject.cpp
indie-zen-plugins/ZLua
6fff6e889a27152ed85b0c0c0786e6b8706f2247
[ "MIT" ]
null
null
null
lib/LuaObject.cpp
indie-zen-plugins/ZLua
6fff6e889a27152ed85b0c0c0786e6b8706f2247
[ "MIT" ]
null
null
null
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ // Lua plugin for Zen Scripting // // Copyright (C) 2001 - 2016 Raymond A. Richards //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ #include "LuaObject.hpp" //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ namespace Zen { namespace ZLua { //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ #if 0 LuaObject::LuaObject(PyObject* _pObj) : m_pObj(_pObj) { } #endif //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ LuaObject::~LuaObject() { } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ #if 0 PyObject* LuaObject::get() { return m_pObj; } #endif //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ } // namespace ZLua } // namespace Zen //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
26.692308
81
0.225744
indie-zen-plugins
b901c26952db884bb48ded53af470278af5655aa
4,108
cpp
C++
platform/android/Rhodes/jni/src/alert.cpp
oneEyedOdin/rhodes
3f855212cbbe3fc00ebb15193d9259e47e8c18b0
[ "MIT" ]
1
2019-10-18T09:44:40.000Z
2019-10-18T09:44:40.000Z
platform/android/Rhodes/jni/src/alert.cpp
sdwood/rhodes
8228aa40708dcbcc1d3967a479d1d84364022255
[ "MIT" ]
2
2019-09-16T09:45:10.000Z
2019-09-16T09:50:36.000Z
platform/android/Rhodes/jni/src/alert.cpp
sdwood/rhodes
8228aa40708dcbcc1d3967a479d1d84364022255
[ "MIT" ]
1
2021-07-03T18:19:38.000Z
2021-07-03T18:19:38.000Z
/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, Inc. * * 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. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include "rhodes/JNIRhodes.h" #include "rhodes/JNIRhoRuby.h" #include "rhodes/jni/com_rhomobile_rhodes_alert_Alert.h" #include "rhodes/jni/com_rhomobile_rhodes_alert_PopupActivity.h" #include <common/rhoparams.h> #include <common/RhodesApp.h> #undef DEFAULT_LOGCATEGORY #define DEFAULT_LOGCATEGORY "Alert" RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_alert_PopupActivity_doCallback (JNIEnv *env, jclass, jstring url, jstring id, jstring title) { rho_rhodesapp_callPopupCallback(rho_cast<std::string>(env, url).c_str(), rho_cast<std::string>(env, id).c_str(), rho_cast<std::string>(env, title).c_str()); } RHO_GLOBAL void alert_show_status(const char* szTitle, const char* szMessage, const char* szHide) { JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_ALERT); if (!cls) return; jmethodID mid = getJNIClassStaticMethod(env, cls, "showStatusPopup", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); if (!mid) return; RAWLOG_INFO("alert_show_status"); env->CallStaticVoidMethod(cls, mid, rho_cast<jhstring>(szTitle).get(), rho_cast<jhstring>(szMessage).get(), rho_cast<jhstring>(szHide).get()); } RHO_GLOBAL void alert_show_popup(rho_param *p) { JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_ALERT); if (!cls) return; jmethodID mid = getJNIClassStaticMethod(env, cls, "showPopup", "(Ljava/lang/Object;)V"); if (!mid) return; if (p->type != RHO_PARAM_STRING && p->type != RHO_PARAM_HASH) { RAWLOG_ERROR("show_popup: wrong input parameter (expect String or Hash)"); return; } jobject paramsObj = RhoValueConverter(env).createObject(p); env->CallStaticVoidMethod(cls, mid, paramsObj); env->DeleteLocalRef(paramsObj); } RHO_GLOBAL void alert_hide_popup() { JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_ALERT); if (!cls) return; jmethodID mid = getJNIClassStaticMethod(env, cls, "hidePopup", "()V"); if (!mid) return; env->CallStaticVoidMethod(cls, mid); } RHO_GLOBAL void alert_vibrate(int duration_ms) { JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_ALERT); if (!cls) return; jmethodID mid = getJNIClassStaticMethod(env, cls, "vibrate", "(I)V"); if (!mid) return; env->CallStaticVoidMethod(cls, mid, duration_ms); } RHO_GLOBAL void alert_play_file(char* file_name, char *media_type) { JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_ALERT); if (!cls) return; jmethodID mid = getJNIClassStaticMethod(env, cls, "playFile", "(Ljava/lang/String;Ljava/lang/String;)V"); if (!mid) return; env->CallStaticVoidMethod(cls, mid, rho_cast<jhstring>(file_name).get(), rho_cast<jhstring>(media_type).get()); }
37.345455
134
0.702045
oneEyedOdin
b9024d6f822e0d46413fe88d77b9fc56ebde2a91
1,380
cpp
C++
Hacker-Rank/contests/codeagon/1.cpp
kishorevarma369/Competitive-Programming
f2fd01b0168cb2908f2cc1794ba2c8a461b06838
[ "MIT" ]
1
2019-05-20T14:38:05.000Z
2019-05-20T14:38:05.000Z
Hacker-Rank/contests/codeagon/1.cpp
kishorevarma369/Competitive-Programming
f2fd01b0168cb2908f2cc1794ba2c8a461b06838
[ "MIT" ]
null
null
null
Hacker-Rank/contests/codeagon/1.cpp
kishorevarma369/Competitive-Programming
f2fd01b0168cb2908f2cc1794ba2c8a461b06838
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // Complete the solve function below. float slope(int x1,int y1,int x2,int y2) { return abs(float(y2-y1)/(x2-x1)) } void solve(vector<vector<int>> &grid) { for(int i=0;i<5;i++) { map<float,int> mymap; int nanc=0,c=0; for(int j=0;j<5;j++) { if(i==j) continue; auto v=abs(slope(grid[i][0],grid[i][1],grid[j][0],grid[j][1])); if(isnan(v)) nanc++; else { mymap[v]++; } } if(nanc) { if(nanc>2) { cout<<"No\n"; return; } else if(nanc==2) { c++; } } for(auto &p:mymap) { if(p.second>2) { cout<<"No\n"; return; } else if(p.second==2) { c++; } } if(c!=1) { cout<<"No\n"; return; } else if(c==2) { } } } int main() { int t; cin>>t; vector<vector<int>> v(5,vector<int>(2)) while(t--) { for(int i=0;i<5;i++) { cin>>v[i][0]>>v[i][1]; } solve(v) } }
17.922078
75
0.325362
kishorevarma369
b90880593142c92494ef2acf80ebcb1e20a9121e
1,287
cpp
C++
oneflow/core/ep/common/active_device_guard.cpp
LiPengze97/oneflow
1c1d2d3faa1c02d20e009046a290cf1095ee12e0
[ "Apache-2.0" ]
null
null
null
oneflow/core/ep/common/active_device_guard.cpp
LiPengze97/oneflow
1c1d2d3faa1c02d20e009046a290cf1095ee12e0
[ "Apache-2.0" ]
null
null
null
oneflow/core/ep/common/active_device_guard.cpp
LiPengze97/oneflow
1c1d2d3faa1c02d20e009046a290cf1095ee12e0
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "oneflow/core/ep/include/active_device_guard.h" #include "oneflow/core/ep/include/device_manager_registry.h" namespace oneflow { namespace ep { ActiveDeviceGuard::ActiveDeviceGuard(Device* device) { device_manager_ = // NOLINT Global<ep::DeviceManagerRegistry>::Get()->GetDeviceManager(device->device_type()); // NOLINT CHECK_NOTNULL(device_manager_); saved_active_device_ = device_manager_->GetActiveDeviceIndex(); device->SetAsActiveDevice(); } ActiveDeviceGuard::~ActiveDeviceGuard() { device_manager_->SetActiveDeviceByIndex(saved_active_device_); } } // namespace ep } // namespace oneflow
33.868421
99
0.738151
LiPengze97
b90893dc93ae8e7389089097e352775b5ef4e2bc
19,599
cpp
C++
src/pronet/pro_net/pro_net.cpp
libpronet/libpronet
78f52fbe002767915553bdf58fb10453e63bf502
[ "Apache-2.0" ]
35
2018-10-29T06:31:09.000Z
2022-03-21T08:13:39.000Z
src/pronet/pro_net/pro_net.cpp
libpronet/libpronet
78f52fbe002767915553bdf58fb10453e63bf502
[ "Apache-2.0" ]
null
null
null
src/pronet/pro_net/pro_net.cpp
libpronet/libpronet
78f52fbe002767915553bdf58fb10453e63bf502
[ "Apache-2.0" ]
11
2018-11-03T04:45:29.000Z
2021-11-23T06:09:20.000Z
/* * Copyright (C) 2018-2019 Eric Tung <libpronet@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. * * This file is part of LibProNet (https://github.com/libpronet/libpronet) */ #include "pro_net.h" #include "pro_acceptor.h" #include "pro_connector.h" #include "pro_mcast_transport.h" #include "pro_service_host.h" #include "pro_service_hub.h" #include "pro_ssl_handshaker.h" #include "pro_ssl_transport.h" #include "pro_tcp_handshaker.h" #include "pro_tcp_transport.h" #include "pro_tp_reactor_task.h" #include "pro_udp_transport.h" #include "../pro_util/pro_bsd_wrapper.h" #include "../pro_util/pro_version.h" #include "../pro_util/pro_z.h" #include <cassert> #include <cstddef> #if defined(__cplusplus) extern "C" { #endif ///////////////////////////////////////////////////////////////////////////// //// extern void PRO_CALLTYPE ProSslInit(); ///////////////////////////////////////////////////////////////////////////// //// PRO_NET_API void PRO_CALLTYPE ProNetInit() { static bool s_flag = false; if (s_flag) { return; } s_flag = true; pbsd_startup(); ProSslInit(); } PRO_NET_API void PRO_CALLTYPE ProNetVersion(unsigned char* major, /* = NULL */ unsigned char* minor, /* = NULL */ unsigned char* patch) /* = NULL */ { if (major != NULL) { *major = PRO_VER_MAJOR; } if (minor != NULL) { *minor = PRO_VER_MINOR; } if (patch != NULL) { *patch = PRO_VER_PATCH; } } PRO_NET_API IProReactor* PRO_CALLTYPE ProCreateReactor(unsigned long ioThreadCount, long ioThreadPriority) /* = 0 */ { ProNetInit(); CProTpReactorTask* const reactorTask = new CProTpReactorTask; if (!reactorTask->Start(ioThreadCount, ioThreadPriority)) { delete reactorTask; return (NULL); } return (reactorTask); } PRO_NET_API void PRO_CALLTYPE ProDeleteReactor(IProReactor* reactor) { if (reactor == NULL) { return; } CProTpReactorTask* const p = (CProTpReactorTask*)reactor; p->Stop(); delete p; } PRO_NET_API IProAcceptor* PRO_CALLTYPE ProCreateAcceptor(IProAcceptorObserver* observer, IProReactor* reactor, const char* localIp, /* = NULL */ unsigned short localPort) /* = 0 */ { ProNetInit(); CProAcceptor* const acceptor = CProAcceptor::CreateInstance(false); if (acceptor == NULL) { return (NULL); } if (!acceptor->Init( observer, (CProTpReactorTask*)reactor, localIp, localPort, 0)) { acceptor->Release(); return (NULL); } return ((IProAcceptor*)acceptor); } PRO_NET_API IProAcceptor* PRO_CALLTYPE ProCreateAcceptorEx(IProAcceptorObserver* observer, IProReactor* reactor, const char* localIp, /* = NULL */ unsigned short localPort, /* = 0 */ unsigned long timeoutInSeconds) /* = 0 */ { ProNetInit(); CProAcceptor* const acceptor = CProAcceptor::CreateInstance(true); if (acceptor == NULL) { return (NULL); } if (!acceptor->Init(observer, (CProTpReactorTask*)reactor, localIp, localPort, timeoutInSeconds)) { acceptor->Release(); return (NULL); } return ((IProAcceptor*)acceptor); } PRO_NET_API unsigned short PRO_CALLTYPE ProGetAcceptorPort(IProAcceptor* acceptor) { assert(acceptor != NULL); if (acceptor == NULL) { return (0); } CProAcceptor* const p = (CProAcceptor*)acceptor; return (p->GetLocalPort()); } PRO_NET_API void PRO_CALLTYPE ProDeleteAcceptor(IProAcceptor* acceptor) { if (acceptor == NULL) { return; } CProAcceptor* const p = (CProAcceptor*)acceptor; p->Fini(); p->Release(); } PRO_NET_API IProConnector* PRO_CALLTYPE ProCreateConnector(bool enableUnixSocket, IProConnectorObserver* observer, IProReactor* reactor, const char* remoteIp, unsigned short remotePort, const char* localBindIp, /* = NULL */ unsigned long timeoutInSeconds) /* = 0 */ { ProNetInit(); CProConnector* const connector = CProConnector::CreateInstance(enableUnixSocket, false, 0, 0); if (connector == NULL) { return (NULL); } if (!connector->Init(observer, (CProTpReactorTask*)reactor, remoteIp, remotePort, localBindIp, timeoutInSeconds)) { connector->Release(); return (NULL); } return ((IProConnector*)connector); } PRO_NET_API IProConnector* PRO_CALLTYPE ProCreateConnectorEx(bool enableUnixSocket, unsigned char serviceId, unsigned char serviceOpt, IProConnectorObserver* observer, IProReactor* reactor, const char* remoteIp, unsigned short remotePort, const char* localBindIp, /* = NULL */ unsigned long timeoutInSeconds) /* = 0 */ { ProNetInit(); CProConnector* const connector = CProConnector::CreateInstance( enableUnixSocket, true, serviceId, serviceOpt); if (connector == NULL) { return (NULL); } if (!connector->Init(observer, (CProTpReactorTask*)reactor, remoteIp, remotePort, localBindIp, timeoutInSeconds)) { connector->Release(); return (NULL); } return ((IProConnector*)connector); } PRO_NET_API void PRO_CALLTYPE ProDeleteConnector(IProConnector* connector) { if (connector == NULL) { return; } CProConnector* const p = (CProConnector*)connector; p->Fini(); p->Release(); } PRO_NET_API IProTcpHandshaker* PRO_CALLTYPE ProCreateTcpHandshaker(IProTcpHandshakerObserver* observer, IProReactor* reactor, PRO_INT64 sockId, bool unixSocket, const void* sendData, /* = NULL */ size_t sendDataSize, /* = 0 */ size_t recvDataSize, /* = 0 */ bool recvFirst, /* = false */ unsigned long timeoutInSeconds) /* = 0 */ { ProNetInit(); CProTcpHandshaker* const handshaker = CProTcpHandshaker::CreateInstance(); if (handshaker == NULL) { return (NULL); } if (!handshaker->Init(observer, (CProTpReactorTask*)reactor, sockId, unixSocket, sendData, sendDataSize, recvDataSize, recvFirst, timeoutInSeconds)) { handshaker->Release(); return (NULL); } return ((IProTcpHandshaker*)handshaker); } PRO_NET_API void PRO_CALLTYPE ProDeleteTcpHandshaker(IProTcpHandshaker* handshaker) { if (handshaker == NULL) { return; } CProTcpHandshaker* const p = (CProTcpHandshaker*)handshaker; p->Fini(); p->Release(); } PRO_NET_API IProSslHandshaker* PRO_CALLTYPE ProCreateSslHandshaker(IProSslHandshakerObserver* observer, IProReactor* reactor, PRO_SSL_CTX* ctx, PRO_INT64 sockId, bool unixSocket, const void* sendData, /* = NULL */ size_t sendDataSize, /* = 0 */ size_t recvDataSize, /* = 0 */ bool recvFirst, /* = false */ unsigned long timeoutInSeconds) /* = 0 */ { ProNetInit(); CProSslHandshaker* const handshaker = CProSslHandshaker::CreateInstance(); if (handshaker == NULL) { return (NULL); } if (!handshaker->Init(observer, (CProTpReactorTask*)reactor, ctx, sockId, unixSocket, sendData, sendDataSize, recvDataSize, recvFirst, timeoutInSeconds)) { handshaker->Release(); return (NULL); } return ((IProSslHandshaker*)handshaker); } PRO_NET_API void PRO_CALLTYPE ProDeleteSslHandshaker(IProSslHandshaker* handshaker) { if (handshaker == NULL) { return; } CProSslHandshaker* const p = (CProSslHandshaker*)handshaker; p->Fini(); p->Release(); } PRO_NET_API IProTransport* PRO_CALLTYPE ProCreateTcpTransport(IProTransportObserver* observer, IProReactor* reactor, PRO_INT64 sockId, bool unixSocket, size_t sockBufSizeRecv, /* = 0 */ size_t sockBufSizeSend, /* = 0 */ size_t recvPoolSize, /* = 0 */ bool suspendRecv) /* = false */ { ProNetInit(); CProTcpTransport* const trans = CProTcpTransport::CreateInstance(false, recvPoolSize); if (trans == NULL) { return (NULL); } if (!trans->Init(observer, (CProTpReactorTask*)reactor, sockId, unixSocket, sockBufSizeRecv, sockBufSizeSend, suspendRecv)) { trans->Release(); return (NULL); } return (trans); } PRO_NET_API IProTransport* PRO_CALLTYPE ProCreateUdpTransport(IProTransportObserver* observer, IProReactor* reactor, const char* localIp, /* = NULL */ unsigned short localPort, /* = 0 */ size_t sockBufSizeRecv, /* = 0 */ size_t sockBufSizeSend, /* = 0 */ size_t recvPoolSize, /* = 0 */ const char* defaultRemoteIp, /* = NULL */ unsigned short defaultRemotePort) /* = 0 */ { ProNetInit(); CProUdpTransport* const trans = CProUdpTransport::CreateInstance(recvPoolSize); if (trans == NULL) { return (NULL); } if (!trans->Init(observer, (CProTpReactorTask*)reactor, localIp, localPort, defaultRemoteIp, defaultRemotePort, sockBufSizeRecv, sockBufSizeSend)) { trans->Release(); return (NULL); } return (trans); } PRO_NET_API IProTransport* PRO_CALLTYPE ProCreateMcastTransport(IProTransportObserver* observer, IProReactor* reactor, const char* mcastIp, unsigned short mcastPort, /* = 0 */ const char* localBindIp, /* = NULL */ size_t sockBufSizeRecv, /* = 0 */ size_t sockBufSizeSend, /* = 0 */ size_t recvPoolSize) /* = 0 */ { ProNetInit(); CProMcastTransport* const trans = CProMcastTransport::CreateInstance(recvPoolSize); if (trans == NULL) { return (NULL); } if (!trans->Init(observer, (CProTpReactorTask*)reactor, mcastIp, mcastPort, localBindIp, sockBufSizeRecv, sockBufSizeSend)) { trans->Release(); return (NULL); } return (trans); } PRO_NET_API IProTransport* PRO_CALLTYPE ProCreateSslTransport(IProTransportObserver* observer, IProReactor* reactor, PRO_SSL_CTX* ctx, PRO_INT64 sockId, bool unixSocket, size_t sockBufSizeRecv, /* = 0 */ size_t sockBufSizeSend, /* = 0 */ size_t recvPoolSize, /* = 0 */ bool suspendRecv) /* = false */ { ProNetInit(); CProSslTransport* const trans = CProSslTransport::CreateInstance(recvPoolSize); if (trans == NULL) { return (NULL); } if (!trans->Init(observer, (CProTpReactorTask*)reactor, ctx, sockId, unixSocket, sockBufSizeRecv, sockBufSizeSend, suspendRecv)) { trans->Release(); return (NULL); } return (trans); } PRO_NET_API void PRO_CALLTYPE ProDeleteTransport(IProTransport* trans) { if (trans == NULL) { return; } const PRO_TRANS_TYPE type = trans->GetType(); if (type == PRO_TRANS_TCP) { CProTcpTransport* const p = (CProTcpTransport*)trans; p->Fini(); p->Release(); } else if (type == PRO_TRANS_UDP) { CProUdpTransport* const p = (CProUdpTransport*)trans; p->Fini(); p->Release(); } else if (type == PRO_TRANS_MCAST) { CProMcastTransport* const p = (CProMcastTransport*)trans; p->Fini(); p->Release(); } else if (type == PRO_TRANS_SSL) { CProSslTransport* const p = (CProSslTransport*)trans; p->Fini(); p->Release(); } else { } } PRO_NET_API IProServiceHub* PRO_CALLTYPE ProCreateServiceHub(IProReactor* reactor, unsigned short servicePort, bool enableLoadBalance) /* = false */ { ProNetInit(); CProServiceHub* const hub = CProServiceHub::CreateInstance( false, /* enableServiceExt is false */ enableLoadBalance ); if (hub == NULL) { return (NULL); } if (!hub->Init(reactor, servicePort, 0)) { hub->Release(); return (NULL); } return ((IProServiceHub*)hub); } PRO_NET_API IProServiceHub* PRO_CALLTYPE ProCreateServiceHubEx(IProReactor* reactor, unsigned short servicePort, bool enableLoadBalance, /* = false */ unsigned long timeoutInSeconds) /* = 0 */ { ProNetInit(); CProServiceHub* const hub = CProServiceHub::CreateInstance( true, /* enableServiceExt is true */ enableLoadBalance ); if (hub == NULL) { return (NULL); } if (!hub->Init(reactor, servicePort, timeoutInSeconds)) { hub->Release(); return (NULL); } return ((IProServiceHub*)hub); } PRO_NET_API void PRO_CALLTYPE ProDeleteServiceHub(IProServiceHub* hub) { if (hub == NULL) { return; } CProServiceHub* const p = (CProServiceHub*)hub; p->Fini(); p->Release(); } PRO_NET_API IProServiceHost* PRO_CALLTYPE ProCreateServiceHost(IProServiceHostObserver* observer, IProReactor* reactor, unsigned short servicePort) { ProNetInit(); CProServiceHost* const host = CProServiceHost::CreateInstance(0); /* serviceId is 0 */ if (host == NULL) { return (NULL); } if (!host->Init(observer, reactor, servicePort)) { host->Release(); return (NULL); } return ((IProServiceHost*)host); } PRO_NET_API IProServiceHost* PRO_CALLTYPE ProCreateServiceHostEx(IProServiceHostObserver* observer, IProReactor* reactor, unsigned short servicePort, unsigned char serviceId) { ProNetInit(); assert(serviceId > 0); if (serviceId == 0) { return (NULL); } CProServiceHost* const host = CProServiceHost::CreateInstance(serviceId); if (host == NULL) { return (NULL); } if (!host->Init(observer, reactor, servicePort)) { host->Release(); return (NULL); } return ((IProServiceHost*)host); } PRO_NET_API void PRO_CALLTYPE ProDeleteServiceHost(IProServiceHost* host) { if (host == NULL) { return; } CProServiceHost* const p = (CProServiceHost*)host; p->Fini(); p->Release(); } PRO_NET_API PRO_INT64 PRO_CALLTYPE ProOpenTcpSockId(const char* localIp, /* = NULL */ unsigned short localPort) { ProNetInit(); assert(localPort > 0); if (localPort == 0) { return (-1); } const char* const anyIp = "0.0.0.0"; if (localIp == NULL || localIp[0] == '\0') { localIp = anyIp; } pbsd_sockaddr_in localAddr; memset(&localAddr, 0, sizeof(pbsd_sockaddr_in)); localAddr.sin_family = AF_INET; localAddr.sin_port = pbsd_hton16(localPort); localAddr.sin_addr.s_addr = pbsd_inet_aton(localIp); if (localAddr.sin_addr.s_addr == (PRO_UINT32)-1) { return (-1); } PRO_INT64 sockId = pbsd_socket(AF_INET, SOCK_STREAM, 0); if (sockId == -1) { return (-1); } if (pbsd_bind(sockId, &localAddr, false) != 0) { ProCloseSockId(sockId); sockId = -1; } return (sockId); } PRO_NET_API PRO_INT64 PRO_CALLTYPE ProOpenUdpSockId(const char* localIp, /* = NULL */ unsigned short localPort) { ProNetInit(); assert(localPort > 0); if (localPort == 0) { return (-1); } const char* const anyIp = "0.0.0.0"; if (localIp == NULL || localIp[0] == '\0') { localIp = anyIp; } pbsd_sockaddr_in localAddr; memset(&localAddr, 0, sizeof(pbsd_sockaddr_in)); localAddr.sin_family = AF_INET; localAddr.sin_port = pbsd_hton16(localPort); localAddr.sin_addr.s_addr = pbsd_inet_aton(localIp); if (localAddr.sin_addr.s_addr == (PRO_UINT32)-1) { return (-1); } PRO_INT64 sockId = pbsd_socket(AF_INET, SOCK_DGRAM, 0); if (sockId == -1) { return (-1); } if (pbsd_bind(sockId, &localAddr, false) != 0) { ProCloseSockId(sockId); sockId = -1; } return (sockId); } PRO_NET_API void PRO_CALLTYPE ProCloseSockId(PRO_INT64 sockId, bool linger) /* = false */ { if (sockId == -1) { return; } ProDecServiceLoad(sockId); /* for load-balance */ pbsd_closesocket(sockId, linger); } ///////////////////////////////////////////////////////////////////////////// //// class CProNetDotCpp { public: CProNetDotCpp() { ProNetInit(); } }; static volatile CProNetDotCpp g_s_initiator; ///////////////////////////////////////////////////////////////////////////// //// #if defined(__cplusplus) } /* extern "C" */ #endif
23.641737
90
0.537987
libpronet
b90aa71724dc8fbd01144d97c285bdadbfc68866
11,045
cc
C++
tensorflow/compiler/mlir/lite/experimental/tac/hardwares/target_hardware.cc
vixadd/tensorflow
8c624204eb686a91779149dc500e6c8c60096074
[ "Apache-2.0" ]
190,993
2015-11-09T13:17:30.000Z
2022-03-31T23:05:27.000Z
tensorflow/compiler/mlir/lite/experimental/tac/hardwares/target_hardware.cc
vixadd/tensorflow
8c624204eb686a91779149dc500e6c8c60096074
[ "Apache-2.0" ]
48,461
2015-11-09T14:21:11.000Z
2022-03-31T23:17:33.000Z
tensorflow/compiler/mlir/lite/experimental/tac/hardwares/target_hardware.cc
vixadd/tensorflow
8c624204eb686a91779149dc500e6c8c60096074
[ "Apache-2.0" ]
104,981
2015-11-09T13:40:17.000Z
2022-03-31T19:51:54.000Z
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/mlir/lite/experimental/tac/hardwares/target_hardware.h" #include <algorithm> #include <cctype> #include <memory> #include "llvm/ADT/DenseMap.h" #include "llvm/Support/raw_ostream.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project #include "mlir/Support/TypeID.h" // from @llvm-project #include "tensorflow/compiler/mlir/lite/experimental/tac/common/targets.h" #include "tensorflow/compiler/mlir/lite/experimental/tac/common/utils.h" #include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h" namespace mlir { namespace TFL { namespace tac { namespace { struct RegisteredTargetHardware { // TODO(b/177376459): Remove this constructor. RegisteredTargetHardware(const std::string& name, const std::string& description, mlir::TypeID type_id, std::unique_ptr<TargetHardware> target_hardware) : unique_name(GetCanonicalHardwareName(name)), description(description), type_id(type_id), target_hardware(std::move(target_hardware)) {} RegisteredTargetHardware( const std::string& name, const std::string& description, mlir::TypeID type_id, std::function<std::unique_ptr<TargetHardware>()> target_hardware_factory) : unique_name(GetCanonicalHardwareName(name)), description(description), target_hardware_factory(target_hardware_factory) {} std::string unique_name; std::string description; mlir::TypeID type_id; std::unique_ptr<TargetHardware> target_hardware; std::function<std::unique_ptr<TargetHardware>()> target_hardware_factory; }; struct RegisteredTargetHardwareOps { explicit RegisteredTargetHardwareOps(mlir::TypeID hardware_type) : hardware_typeid(hardware_type) {} // Key is the Operation TypeID llvm::DenseMap<mlir::TypeID, std::unique_ptr<TargetHardwareOperation>> target_hardware_ops; // Key is the Operation TypeID llvm::DenseMap<mlir::TypeID, std::function<std::unique_ptr<TargetHardwareOperation>()>> target_hardware_ops_factory; mlir::TypeID hardware_typeid; }; std::vector<std::unique_ptr<RegisteredTargetHardwareOps>>* GetRegisteredTargetHardwareOps() { static std::vector<std::unique_ptr<RegisteredTargetHardwareOps>>* hardwares_ops = []() -> std::vector<std::unique_ptr<RegisteredTargetHardwareOps>>* { return new std::vector<std::unique_ptr<RegisteredTargetHardwareOps>>(); }(); return hardwares_ops; } std::vector<RegisteredTargetHardware>* GetRegisteredHardwares() { static std::vector<RegisteredTargetHardware>* hardwares = []() -> std::vector<RegisteredTargetHardware>* { return new std::vector<RegisteredTargetHardware>(); }(); return hardwares; } llvm::DenseMap<mlir::TypeID, std::unique_ptr<TargetHardwareOperation>>* getRegisteredOperationsForHardware(mlir::TypeID type_id) { auto* hardwares = GetRegisteredTargetHardwareOps(); for (auto& hardware : *hardwares) { if (hardware->hardware_typeid == type_id) { return &hardware->target_hardware_ops; } } return nullptr; } // A deny list for op cost computation since those ops are not arithemtic. inline bool IsNonArithmeticOp(mlir::Operation* op) { if (llvm::isa<ReturnOp, FuncOp>(op)) return true; if (op->hasTrait<OpTrait::ConstantLike>()) return true; if (llvm::isa<QConstOp, SparseQConstOp>(op)) return true; if (!IsTFLNonQuantDequantizeOp(op)) return true; return false; } } // namespace bool TargetHardware::Init() { auto* hardware_ops_factory = GetRegisteredTargetHardwareOps(); for (auto& hardware_ops : *hardware_ops_factory) { if (hardware_ops->hardware_typeid != this->GetTypeId()) continue; auto& op_factories = hardware_ops->target_hardware_ops_factory; for (auto& op_factory : op_factories) { hardware_ops_.emplace_back(op_factory.getSecond()()); } break; } return true; } double TargetHardware::GetOpCost(mlir::Operation* op) const { auto* registered_ops = getRegisteredOperationsForHardware(GetTypeId()); if (registered_ops == nullptr) { return kDefaultFixedValuedCost; } auto* abstract_op = op->getAbstractOperation(); auto hardware_op = registered_ops->find(abstract_op->typeID); if (hardware_op == registered_ops->end()) return kDefaultFixedValuedCost; return hardware_op->second->GetOpCost(op); } bool TargetHardware::IsOpSupported(mlir::Operation* op) const { auto* registered_ops = getRegisteredOperationsForHardware(GetTypeId()); if (registered_ops == nullptr) { return false; } auto* abstract_op = op->getAbstractOperation(); auto hardware_op = registered_ops->find(abstract_op->typeID); if (hardware_op == registered_ops->end()) return false; return hardware_op->second->IsOpSupported(op); } double TargetHardware::GetFuncCost(FuncOp* func) const { double total_cost = 0.0; func->walk([&](Operation* op) { if (IsNonArithmeticOp(op)) return; // We will always defer to the hardware to decide the cost. total_cost += GetOpCost(op); }); return total_cost; } const TargetHardware* GetTargetHardware(const std::string& hardware_name) { const std::string canonical_name = GetCanonicalHardwareName(hardware_name); // Just loop for now, we don't expect number of hardwares to be huge. // Revisit to have map if number of elements increased. auto* registered_hardwares = GetRegisteredHardwares(); for (const auto& hardware : *registered_hardwares) { if (hardware.unique_name == canonical_name) { return hardware.target_hardware.get(); } } return nullptr; } std::function<std::unique_ptr<TargetHardware>()> GetTargetHardwareFactory( const std::string& hardware_name) { const std::string canonical_name = GetCanonicalHardwareName(hardware_name); // Just loop for now, we don't expect number of hardwares to be huge. // Revisit to have map if number of elements increased. auto* registered_hardwares = GetRegisteredHardwares(); for (const auto& hardware : *registered_hardwares) { if (hardware.unique_name == canonical_name) { return hardware.target_hardware_factory; } } return nullptr; } namespace internal { void RegisterTargetHardware( const std::string& unique_name, const std::string& description, mlir::TypeID type_id, std::function<std::unique_ptr<TargetHardware>()> target_hardware_factory) { auto* registered_hardwares = GetRegisteredHardwares(); for (const auto& hardware : *registered_hardwares) { if (hardware.unique_name == unique_name) { llvm::errs() << "Ignoring duplicate hardware. Hardware " << unique_name << " already registered\n"; return; } } registered_hardwares->push_back(RegisteredTargetHardware( unique_name, description, type_id, target_hardware_factory())); } void RegisterTargetHardwareFactory( const std::string& unique_name, const std::string& description, mlir::TypeID type_id, std::function<std::unique_ptr<TargetHardware>()> target_hardware_factory) { auto* registered_hardwares = GetRegisteredHardwares(); for (auto& hardware : *registered_hardwares) { if (hardware.unique_name == unique_name) { llvm::errs() << "Ignoring duplicate hardware. Hardware " << unique_name << " already registered\n"; hardware.target_hardware_factory = target_hardware_factory; return; } } registered_hardwares->push_back(RegisteredTargetHardware( unique_name, description, type_id, target_hardware_factory)); } void RegisterTargetHardwareOp( mlir::TypeID hardware_type, mlir::TypeID op_type, std::function<std::unique_ptr<TargetHardwareOperation>()> target_hardware_op_factory) { auto* registered_hardware_ops = GetRegisteredTargetHardwareOps(); for (auto& hardware : *registered_hardware_ops) { if (hardware->hardware_typeid == hardware_type) { if (hardware->target_hardware_ops.count(op_type)) { llvm::errs() << "Trying to register duplicate Op"; return; } hardware->target_hardware_ops[op_type] = target_hardware_op_factory(); return; } } registered_hardware_ops->push_back( std::make_unique<RegisteredTargetHardwareOps>( RegisteredTargetHardwareOps(hardware_type))); registered_hardware_ops->back()->target_hardware_ops[op_type] = target_hardware_op_factory(); } void RegisterTargetHardwareOpFactory( mlir::TypeID hardware_type, mlir::TypeID op_type, std::function<std::unique_ptr<TargetHardwareOperation>()> target_hardware_op_factory) { auto* registered_hardware_ops = GetRegisteredTargetHardwareOps(); for (auto& hardware : *registered_hardware_ops) { if (hardware->hardware_typeid == hardware_type) { if (hardware->target_hardware_ops_factory.count(op_type)) { llvm::errs() << "Trying to register duplicate Op"; return; } hardware->target_hardware_ops_factory[op_type] = target_hardware_op_factory; return; } } registered_hardware_ops->push_back( std::make_unique<RegisteredTargetHardwareOps>( RegisteredTargetHardwareOps(hardware_type))); registered_hardware_ops->back()->target_hardware_ops_factory[op_type] = target_hardware_op_factory; } } // namespace internal bool ProcessTargetDevices(llvm::ArrayRef<std::string> specified_device_specs, std::vector<std::string>* device_specs) { bool cpu_include = false; for (auto& device_spec : specified_device_specs) { auto device = GetCanonicalHardwareName(device_spec); if (device == "CPU") cpu_include = true; device_specs->push_back(device); } if (!cpu_include) { device_specs->push_back("CPU"); } // Make sure all the devices are registered. for (const std::string& device : *device_specs) { if (GetTargetHardware(device) == nullptr) { llvm::errs() << "cannot get target hardware for device: " << device; return false; } } return true; } std::string GetHardwareName(const TargetHardware* hardware) { const auto* registered_hardwares = GetRegisteredHardwares(); for (const auto& registered_hardware : *registered_hardwares) { if (registered_hardware.type_id == hardware->GetTypeId()) return registered_hardware.unique_name; } return ""; } } // namespace tac } // namespace TFL } // namespace mlir
36.694352
85
0.72105
vixadd
b90b75b2c2ee62d27dd11fdb8f49398f1df80d9b
65,944
cpp
C++
Samples/Win7Samples/netds/tapi/tapi3/cpp/tapirecv/Processing.cpp
windows-development/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/Win7Samples/netds/tapi/tapi3/cpp/tapirecv/Processing.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
null
null
null
Samples/Win7Samples/netds/tapi/tapi3/cpp/tapirecv/Processing.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.000Z
/* Copyright (c) 1999 - 2000 Microsoft Corporation Module Name: Processing.cpp Abstract: Implementation of the ITTAPIEventNotification interface. An application must implement and register this interface in order to receive calls and events related to calls. See TAPI documentation for more information on this interface. This file also contains a collection of functions related to event processing */ #include "common.h" #include "Processing.h" #include "WorkerThread.h" #include "AVIFileWriter.h" // // the name of the file we will save the incoming audio to // #define SZ_OUTPUTFILENAME "recording.wav" // // the worker thread for asycnhronous message processing // CWorkerThread g_WorkerThread; /////////////////////////////////////////////////////////////////////////////// // // ITTAPIEventNotification::Event // // the method on the tapi callback object that will be called // when tapi notifies the application of an event // // this method should return as soon as possible, so we are not // going to actually process the events here. Instead, we will post // events to a worker thread for asynchronous processing. // // in a real life application that could be another thread, the // application's main thread, or we could post events to a window. // /////////////////////////////////////////////////////////////////////////////// HRESULT STDMETHODCALLTYPE CTAPIEventNotification::Event(IN TAPI_EVENT TapiEvent, IN IDispatch *pEvent) { LogMessage("CTAPIEventNotification::Event " "posting message for asynchronous processing"); // // AddRef the event so it doesn't go away after we return // pEvent->AddRef(); // // Post a message to our own worker thread to be processed asynchronously // g_WorkerThread.PostMessage(WM_PRIVATETAPIEVENT, (WPARAM) TapiEvent, (LPARAM) pEvent); return S_OK; } /////////////////////////////////////////////////////////////////////////////// // // GetTerminalFromStreamEvent // // // given pCallMediaEvent, find the one and only terminal selected on its stream // // return the terminal and S_OK if success, error otherwise // /////////////////////////////////////////////////////////////////////////////// HRESULT GetTerminalFromStreamEvent(IN ITCallMediaEvent *pCallMediaEvent, OUT ITTerminal **ppTerminal) { HRESULT hr = E_FAIL; // // don't return garbage // *ppTerminal = NULL; // // Get the stream for this event. // ITStream *pStream = NULL; hr = pCallMediaEvent->get_Stream(&pStream); if ( FAILED(hr) ) { LogMessage("GetTerminalFromStreamEvent: " "Failed to get stream from pCallMediaEvent hr = 0x%lx", hr); return hr; } // // Enumerate terminals on this stream. // IEnumTerminal *pEnumTerminal = NULL; hr = pStream->EnumerateTerminals(&pEnumTerminal); pStream->Release(); pStream = NULL; if ( FAILED(hr) ) { LogMessage("GetTerminalFromStreamEvent: " "Failed to enumerate terminals hr = 0x%lx", hr); return hr; } // // we should have at most one terminal selected on the stream, so // get the first terminal // ITTerminal *pTerminal = NULL; hr = pEnumTerminal->Next(1, &pTerminal, NULL); if ( hr != S_OK ) { LogMessage("GetTerminalFromStreamEvent: " "Failed to get a terminal from enumeration hr = 0x%lx", hr); pEnumTerminal->Release(); pEnumTerminal = NULL; return E_FAIL; } *ppTerminal = pTerminal; pTerminal = NULL; // // we should not have any more terminals on this stream, // double-check this. // hr = pEnumTerminal->Next(1, &pTerminal, NULL); if (hr == S_OK) { LogError("GetTerminalFromStreamEvent: " "more than one terminal on the stream!"); _ASSERTE(FALSE); pTerminal->Release(); pTerminal = NULL; } pEnumTerminal->Release(); pEnumTerminal = NULL; return S_OK; } /////////////////////////////////////////////////////////////////////////////// // // IsMessageForActiveCall // // return TRUE if the event received is for the currently active call // /////////////////////////////////////////////////////////////////////////////// BOOL IsMessageForActiveCall(IN ITCallStateEvent *pCallStateEvent) { EnterCriticalSection(&g_CurrentCallCritSection); // // if we don't have an active call we have not received call notification // for a call that we own, so return FALSE // if (NULL == g_pCurrentCall) { LogMessage("IsMessageForActiveCall: no active call. return FALSE"); LeaveCriticalSection(&g_CurrentCallCritSection); return FALSE; } // // get the call corresponding to the event // ITCallInfo *pCallInfo = NULL; HRESULT hr = pCallStateEvent->get_Call(&pCallInfo); if (FAILED(hr)) { LogError("IsMessageForActiveCall: failed to get call. " "returning FALSE"); LeaveCriticalSection(&g_CurrentCallCritSection); return FALSE; } // // get IUnknown of the call from the event // IUnknown *pIncomingCallUnk = NULL; hr = pCallInfo->QueryInterface(IID_IUnknown, (void**)&pIncomingCallUnk); pCallInfo->Release(); pCallInfo = NULL; if (FAILED(hr)) { LogError("IsMessageForActiveCall: " "failed to qi incoming call for IUnknown. returning FALSE"); LeaveCriticalSection(&g_CurrentCallCritSection); return FALSE; } // // get IUnknown of the call from the event // IUnknown *pCurrentCallUnk = NULL; hr = g_pCurrentCall->QueryInterface(IID_IUnknown, (void**)&pCurrentCallUnk); LeaveCriticalSection(&g_CurrentCallCritSection); if (FAILED(hr)) { LogError("IsMessageForActiveCall: " "Failed to QI current call for IUnknown. returning FALSE."); pIncomingCallUnk->Release(); pIncomingCallUnk = NULL; return FALSE; } // // compare IUnknowns of the current call and the event call // if they are the same, this is the same call // BOOL bSameCall = FALSE; if (pCurrentCallUnk == pIncomingCallUnk) { bSameCall = TRUE; } else { LogMessage("IsMessageForActiveCall: " "current and event calls are different. returning FALSE."); bSameCall = FALSE; } pCurrentCallUnk->Release(); pCurrentCallUnk = NULL; pIncomingCallUnk->Release(); pIncomingCallUnk = NULL; return bSameCall; } /////////////////////////////////////////////////////////////////////////////// // // GetAddressFromCall // // // return ITAddress of the address corresponding to the supplied // ITBasicCallControl // /////////////////////////////////////////////////////////////////////////////// HRESULT GetAddressFromCall(IN ITBasicCallControl *pCallControl, OUT ITAddress **ppAddress) { HRESULT hr = E_FAIL; // // don't return garbage // *ppAddress = NULL; // // get ITCallInfo so we can get the call's address // ITCallInfo *pCallInfo = NULL; hr = pCallControl->QueryInterface(IID_ITCallInfo, (void**)&pCallInfo); if (FAILED(hr)) { LogError("GetAddressFromCall: " "Failed to QI call for ITCallInfo"); return hr; } // // get the call's address // ITAddress *pAddress = NULL; hr = pCallInfo->get_Address(&pAddress); pCallInfo->Release(); pCallInfo = NULL; if (FAILED(hr)) { LogError("GetAddressFromCall: failed to get address"); } else { *ppAddress = pAddress; } return hr; } /////////////////////////////////////////////////////////////////////////////// // // CreateRenderMediaStreamingTerminal // // create rendering media streaming terminal. // // if success, return the pointer to the terminal // if failed, return NULL // /////////////////////////////////////////////////////////////////////////////// ITTerminal *CreateRenderMediaStreamingTerminal(IN ITBasicCallControl *pCallControl) { HRESULT hr = E_FAIL; // // get address from call // ITAddress *pAddress = NULL; hr = GetAddressFromCall(pCallControl, &pAddress); if (FAILED(hr)) { LogError("CreateRenderMediaStreamingTerminal: failed to get address from call"); return NULL; } // // get the terminal support interface from the address // ITTerminalSupport *pTerminalSupport = NULL; hr = pAddress->QueryInterface( IID_ITTerminalSupport, (void **)&pTerminalSupport ); pAddress->Release(); pAddress = NULL; if (FAILED(hr)) { LogError("CreateRenderMediaStreamingTerminal: " "failed to QI pAddress for ITTerminalSupport"); return NULL; } // // get string for the terminal's class id // WCHAR *pszTerminalClass = NULL; hr = StringFromIID(CLSID_MediaStreamTerminal, &pszTerminalClass); if (FAILED(hr)) { LogError("CreateRenderMediaStreamingTerminal: " "Failed to generate string from terminal's class id"); pTerminalSupport->Release(); pTerminalSupport = NULL; return NULL; } // // make bstr out of the class id // BSTR bstrTerminalClass = SysAllocString (pszTerminalClass); // // free the string returned by StringFromIID // CoTaskMemFree(pszTerminalClass); pszTerminalClass = NULL; // // create media streaming terminal for rendering // ITTerminal *pTerminal = NULL; hr = pTerminalSupport->CreateTerminal(bstrTerminalClass, TAPIMEDIATYPE_AUDIO, TD_RENDER, &pTerminal); // // release resources no longer needed // SysFreeString(bstrTerminalClass); bstrTerminalClass = NULL; pTerminalSupport->Release(); pTerminalSupport = NULL; if (FAILED(hr)) { LogError("CreateRenderMediaStreamingTerminal: " "failed to create media streaming terminal hr = 0x%lx", hr); return NULL; } // // successfully created media streaming terminal. return. // LogMessage("CreateRenderMediaStreamingTerminal: " "Terminal created successfully"); return pTerminal; } /////////////////////////////////////////////////////////////////////////////// // // SetAudioFormat // // tell media streaming terminal the audio format we would like // to receive // /////////////////////////////////////////////////////////////////////////////// HRESULT SetAudioFormat(IN ITTerminal *pTerminal) { HRESULT hr = E_FAIL; // // get ITAMMediaFormat interface on the terminal // ITAMMediaFormat *pITMediaFormat = NULL; hr = pTerminal->QueryInterface(IID_ITAMMediaFormat, (void **)&pITMediaFormat); if (FAILED(hr)) { LogError("SetAudioFormat: failed to QI terminal for ITAMMediaFormat"); return hr; } // // will ask media streaming terminal for audio in this format // WAVEFORMATEX WaveFormat; ZeroMemory(&WaveFormat, sizeof(WAVEFORMATEX)); WaveFormat.wFormatTag = WAVE_FORMAT_PCM; // pcm WaveFormat.nChannels = 1; // mono WaveFormat.nSamplesPerSec = 8000; // 8 khz WaveFormat.nAvgBytesPerSec = 16000; // 16000 bytes per sec WaveFormat.nBlockAlign = 2; // 2 bytes per block WaveFormat.wBitsPerSample = 16; // 16 bits per sample WaveFormat.cbSize = 0; // no extra format-specific data // // configure the wave format we want // AM_MEDIA_TYPE MediaType; MediaType.majortype = MEDIATYPE_Audio; MediaType.subtype = MEDIASUBTYPE_PCM; MediaType.bFixedSizeSamples = TRUE; MediaType.bTemporalCompression = FALSE; MediaType.lSampleSize = 0; MediaType.formattype = FORMAT_WaveFormatEx; MediaType.pUnk = NULL; MediaType.cbFormat = sizeof(WAVEFORMATEX); MediaType.pbFormat = (BYTE*)&WaveFormat; // // log the wave format we are setting on the terminal // LogMessage("SetAudioFormat: setting wave format on terminal. "); LogFormat(&WaveFormat); // // set the format // hr = pITMediaFormat->put_MediaFormat(&MediaType); if (FAILED(hr)) { // // try to see what format the terminal wanted // LogError("SetAudioFormat: failed to set format"); AM_MEDIA_TYPE *pMediaFormat = NULL; HRESULT hr2 = pITMediaFormat->get_MediaFormat(&pMediaFormat); if (SUCCEEDED(hr2)) { if (pMediaFormat->formattype == FORMAT_WaveFormatEx) { // // log the terminal's format // LogError("SetAudioFormat: terminal's format is"); LogFormat((WAVEFORMATEX*) pMediaFormat->pbFormat); } else { LogError("SetAudioFormat: " "terminal's format is not WAVEFORMATEX"); } // // note: we are responsible for deallocating the format returned by // get_MediaFormat // DeleteMediaType(pMediaFormat); } // succeeded getting terminal's format else { LogError("SetAudioFormat: failed to get terminal's format"); } } pITMediaFormat->Release(); pITMediaFormat = NULL; LogError("SetAudioFormat: completed"); return hr; } /////////////////////////////////////////////////////////////////////////////// // // SetAllocatorProperties // // suggest allocator properties to the terminal // /////////////////////////////////////////////////////////////////////////////// HRESULT SetAllocatorProperties(IN ITTerminal *pTerminal) { // // different buffer sizes may produce different sound quality, depending // on the underlying transport that is being used. // // this function illustrates how an app can control the number and size of // buffers. A multiple of 30 ms (480 bytes at 16-bit 8 KHz PCM) is the most // appropriate sample size for IP (especailly G.723.1). // // However, small buffers can cause poor audio quality on some voice boards. // // If this method is not called, the allocator properties suggested by the // connecting filter will be used. // HRESULT hr = E_FAIL; // // get ITAllocator properties interface on the terminal // ITAllocatorProperties *pITAllocatorProperties = NULL; hr = pTerminal->QueryInterface(IID_ITAllocatorProperties, (void **)&pITAllocatorProperties); if (FAILED(hr)) { LogError("SetAllocatorProperties: " "failed to QI terminal for ITAllocatorProperties"); return hr; } // // configure allocator properties // // suggest the size and number of the samples for MST to pre-allocate. // ALLOCATOR_PROPERTIES AllocProps; AllocProps.cBuffers = 5; // ask MST to allocate 5 buffers AllocProps.cbBuffer = 4800; // 4800 bytes each AllocProps.cbAlign = 1; // no need to align buffers AllocProps.cbPrefix = 0; // no extra memory preceeding the actual data hr = pITAllocatorProperties->SetAllocatorProperties(&AllocProps); if (FAILED(hr)) { LogError("SetAllocatorProperties: " "failed to set allocator properties. hr = 0x%lx", hr); pITAllocatorProperties->Release(); pITAllocatorProperties = NULL; return hr; } // // ask media streaming terminal to allocate buffers for us. // TRUE is the default, so strictly speaking, we didn't have to call // this method. // hr = pITAllocatorProperties->SetAllocateBuffers(TRUE); pITAllocatorProperties->Release(); pITAllocatorProperties = NULL; if (FAILED(hr)) { LogError("SetAllocatorProperties: " "failed to SetAllocateBuffers, hr = 0x%lx", hr); return hr; } // // succeeded setting allocator properties // LogMessage("SetAllocatorProperties: succeeded."); return S_OK; } /////////////////////////////////////////////////////////////////////////////// // // SelectAndInitializeTerminal // // // Set audio format and allocator properties on the terminal and // select the terminal on the stream // /////////////////////////////////////////////////////////////////////////////// HRESULT SelectAndInitializeTerminal(IN ITTerminal *pRecordTerminal, IN ITStream *pStream) { HRESULT hr = E_FAIL; // // set audio format on the created terminal // hr = SetAudioFormat(pRecordTerminal); if (FAILED(hr)) { // // the terminal does not support the wave format we wanted. // no big deal for the receiver, we'll just have to create the // file in the format requested by MST. // LogMessage("CreateAndSelectMST: " "Failed to set audio format on recording terminal. " "Continuing"); } // // set allocator properties for this terminal // hr = SetAllocatorProperties(pRecordTerminal); if (FAILED(hr)) { // // not a fatal error. our allocator props were rejected, // but this does not necessarily mean streaming will fail. // LogError("CreateAndSelectMST: Failed to set " "allocator properties on recording terminal"); } // // select terminal on the stream // hr = pStream->SelectTerminal(pRecordTerminal); if (FAILED(hr)) { LogError("CreateAndSelectMST: Failed to select " "terminal on the stream"); } return hr; } /////////////////////////////////////////////////////////////////////////////// // // IsRenderingStream // // returns TRUE if the stream's direction is TD_RENDER // /////////////////////////////////////////////////////////////////////////////// BOOL IsRenderingStream(ITStream *pStream) { // // check the stream's direction // TERMINAL_DIRECTION TerminalDirection; HRESULT hr = pStream->get_Direction(&TerminalDirection); if (FAILED(hr)) { LogError("IsRenderingStream: Failed to get stream direction"); return FALSE; } if (TD_RENDER == TerminalDirection) { return TRUE; } else { return FALSE; } } /////////////////////////////////////////////////////////////////////////////// // // IsAudioStream // // returns TRUE if the stream's type is TAPIMEDIATYPE_AUDIO // /////////////////////////////////////////////////////////////////////////////// BOOL IsAudioStream(ITStream *pStream) { // // check the stream's media type // long nMediaType = 0; HRESULT hr = pStream->get_MediaType(&nMediaType); if (FAILED(hr)) { LogError("IsAudioStream: Failed to get media type"); return FALSE; } // // return true if the stream is audio // if (TAPIMEDIATYPE_AUDIO == nMediaType) { return TRUE; } else { return FALSE; } } /////////////////////////////////////////////////////////////////////////////// // // CreateAndSelectMST // // check the call's streams. create media streaming terminal on the first // incoming audio stream // // returns: // // S_OK if a terminal was created and selected // S_FALSE if no appropriate stream was found // error if failed // /////////////////////////////////////////////////////////////////////////////// HRESULT CreateAndSelectMST() { LogMessage("CreateAndSelectMST: started"); // // we should already have the call // if (NULL == g_pCurrentCall) { LogError("CreateAndSelectMST: g_pCurrentCall is NULL"); return E_UNEXPECTED; } HRESULT hr = E_FAIL; // // get the ITStreamControl interface for this call // ITStreamControl *pStreamControl = NULL; hr = g_pCurrentCall->QueryInterface(IID_ITStreamControl, (void**)&pStreamControl); if (FAILED(hr)) { LogError("CreateAndSelectMST: failed to QI call for ITStreamControl"); return hr; } // // enumerate the streams on the call // IEnumStream *pEnumStreams = NULL; hr = pStreamControl->EnumerateStreams(&pEnumStreams); pStreamControl->Release(); pStreamControl = NULL; if (FAILED(hr)) { LogError("CreateAndSelectMST: failed to enumerate streams on call"); return hr; } // // walk through the list of streams on the call // for the first incoming audio stream, create a media streaming terminal // and select it on the stream // BOOL bTerminalCreatedAndSelected = FALSE; while (!bTerminalCreatedAndSelected) { ITStream *pStream = NULL; hr = pEnumStreams->Next(1, &pStream, NULL); if (S_OK != hr) { // // no more streams or error // LogError("CreateAndSelectMST: didn't find an incoming audio stream." " terminal not selected."); break; } // // create and select media streaming terminal on the first incoming // audio stream // if ( IsRenderingStream(pStream) && IsAudioStream(pStream)) { LogMessage("CreateAndSelectMST: creating mst"); // // create media streaming terminal and select it on the stream // ITTerminal *pRecordTerminal = NULL; pRecordTerminal = CreateRenderMediaStreamingTerminal(g_pCurrentCall); if (NULL != pRecordTerminal) { hr = SelectAndInitializeTerminal(pRecordTerminal, pStream); pRecordTerminal->Release(); pRecordTerminal = NULL; if (SUCCEEDED(hr)) { // // set the flag, so we can break out of the loop // bTerminalCreatedAndSelected = TRUE; } } // media streaming terminal created successfully } // stream is rendering and audio else { // // the stream is of wrong direction, or type // } pStream->Release(); pStream = NULL; } // while (enumerating streams on the call) // // done with the stream enumeration. release // pEnumStreams->Release(); pEnumStreams = NULL; if (bTerminalCreatedAndSelected) { LogMessage("CreateAndSelectMST: terminal selected"); return S_OK; } else { LogMessage("CreateAndSelectMST: no terminal selected"); return S_FALSE; } } /////////////////////////////////////////////////////////////////////////////// // // GetTerminalFromMediaEvent // // // get the terminal selected on the event's stream // /////////////////////////////////////////////////////////////////////////////// HRESULT GetTerminalFromMediaEvent(IN ITCallMediaEvent *pCallMediaEvent, OUT ITTerminal **ppTerminal) { HRESULT hr = E_FAIL; // // don't return garbage if we fail // *ppTerminal = NULL; // // get the stream corresponding to this event // ITStream *pStream = NULL; hr = pCallMediaEvent->get_Stream(&pStream); if ( FAILED(hr) ) { LogError("GetTerminalFromMediaEvent: " "failed to get stream hr = 0x%lx", hr); return hr; } // // find the terminal on this stream // // // get terminal enumeration on the stream // IEnumTerminal *pEnumTerminal = NULL; hr = pStream->EnumerateTerminals(&pEnumTerminal); pStream->Release(); pStream = NULL; if ( FAILED(hr) ) { LogError("GetTerminalFromMediaEvent: failed to enumerate terminals, " "hr = 0x%lx", hr); return hr; } // // walk through terminal enumeration // ULONG nTerminalsFetched = 0; ITTerminal *pStreamTerminal = NULL; // // assuming there is at most one terminal selected on the stream // hr = pEnumTerminal->Next(1, &pStreamTerminal, &nTerminalsFetched); pEnumTerminal->Release(); pEnumTerminal = NULL; if (S_OK != hr) { LogError("GetTerminalFromMediaEvent: enumeration returned no " "terminals, hr = 0x%lx", hr); return hr; } *ppTerminal = pStreamTerminal; LogMessage("GetTerminalFromMediaEvent: succeeded"); return S_OK; } /////////////////////////////////////////////////////////////////////////////// // // GetNumberOfSamplesOnStream // // read the terminal's allocator properties to return the number of samples // the terminal provides // /////////////////////////////////////////////////////////////////////////////// HRESULT GetNumberOfSamplesOnStream(IN IMediaStream *pTerminalMediaStream, IN OUT DWORD *pnNumberOfSamples) { HRESULT hr = S_OK; // // don't return garbage // *pnNumberOfSamples = 0; // // get allocator properties // ITAllocatorProperties *pAllocProperites = NULL; hr = pTerminalMediaStream->QueryInterface(IID_ITAllocatorProperties, (void **)&pAllocProperites); if (FAILED(hr)) { LogError("GetNumberOfSamplesOnStream: " "Failed to QI terminal for ITAllocatorProperties"); return hr; } // // we want to know the number of samples we will be getting // ALLOCATOR_PROPERTIES AllocProperties; hr = pAllocProperites->GetAllocatorProperties(&AllocProperties); pAllocProperites->Release(); pAllocProperites = NULL; if (FAILED(hr)) { LogError("GetNumberOfSamplesOnStream: " "Failed to get terminal's allocator properties"); return hr; } *pnNumberOfSamples = AllocProperties.cBuffers; // // log the number of buffers and their sizes // LogMessage("GetNumberOfSamplesOnStream: [%ld] samples, [%ld] bytes each", *pnNumberOfSamples, AllocProperties.cbBuffer); return S_OK; } /////////////////////////////////////////////////////////////////////////////// // // ReleaseEvents // // // close the handles passed into the function and release the array of handles // /////////////////////////////////////////////////////////////////////////////// void ReleaseEvents(IN OUT HANDLE *pEvents, // array of events to be freed IN DWORD nNumberOfEvents // number of events in the array ) { // // close all the handles in the array // for (DWORD i = 0; i < nNumberOfEvents; i++) { CloseHandle(pEvents[i]); pEvents[i] = NULL; } // // free the array itself // FreeMemory(pEvents); pEvents = NULL; } /////////////////////////////////////////////////////////////////////////////// // // AllocateEvents // // allocate the array of events of size nNumberOfSamples // // return pointer to the allocated and initialized array if success // or NULL if failed // /////////////////////////////////////////////////////////////////////////////// HANDLE *AllocateEvents(IN DWORD nNumberOfEvents) { // // pointer to an array of event handles // HANDLE *pSampleReadyEvents = NULL; pSampleReadyEvents = (HANDLE*)AllocateMemory(sizeof(HANDLE) * nNumberOfEvents); if (NULL == pSampleReadyEvents) { LogError("AllocateEvents: Failed to allocate sample ready events."); return NULL; } // // create an event for every allocated handle // for (DWORD i = 0; i < nNumberOfEvents; i++) { pSampleReadyEvents[i] = CreateEvent(NULL, FALSE, FALSE, NULL); if (NULL == pSampleReadyEvents[i]) { LogError("AllocateEvents: " "Failed to create event for sample %d", i); // // close handles we have created already // for (DWORD j = 0; j< i; j++) { CloseHandle(pSampleReadyEvents[j]); pSampleReadyEvents[j] = NULL; } FreeMemory(pSampleReadyEvents); pSampleReadyEvents = NULL; return NULL; } } // creating events for each sample // // succeded creating events. return the pointer to the array // return pSampleReadyEvents; } /////////////////////////////////////////////////////////////////////////////// // // ReleaseSamples // // aborts and releases every sample in the array of samples of size // nNumberOfSamples and deallocates the array itself // // ppStreamSamples becomes invalid when the function returns // /////////////////////////////////////////////////////////////////////////////// void ReleaseSamples(IN OUT IStreamSample **ppStreamSamples, IN DWORD nNumberOfSamples) { for (DWORD i = 0; i < nNumberOfSamples; i++) { ppStreamSamples[i]->CompletionStatus(COMPSTAT_WAIT | COMPSTAT_ABORT, INFINITE); // // regardless of the error code, release the sample // ppStreamSamples[i]->Release(); ppStreamSamples[i] = NULL; } FreeMemory(ppStreamSamples); ppStreamSamples = NULL; } /////////////////////////////////////////////////////////////////////////////// // // AllocateStreamSamples // // allocate the array of nNumberOfSamples samples, and initialize each sample // pointer in the array with samples from the supplied stream. // // return pointer to the allocated and initialized array if success // or NULL if failed // /////////////////////////////////////////////////////////////////////////////// IStreamSample **AllocateStreamSamples(IN IMediaStream *pMediaStream, IN DWORD nNumberOfSamples) { // // allocate stream sample array // IStreamSample **ppStreamSamples = (IStreamSample **) AllocateMemory( sizeof(IStreamSample*) * nNumberOfSamples ); if (NULL == ppStreamSamples) { LogError("AllocateStreamSamples: Failed to allocate stream sample array"); return NULL; } // // allocate samples from the stream and put them into the array // for (DWORD i = 0; i < nNumberOfSamples; i++) { HRESULT hr = pMediaStream->AllocateSample(0, &ppStreamSamples[i]); if (FAILED(hr)) { LogError("AllocateStreamSamples: Failed to allocateSample. " "Sample #%d", i); for (DWORD j = 0; j < i; j++) { ppStreamSamples[j]->Release(); ppStreamSamples[j] = NULL; } FreeMemory(ppStreamSamples); ppStreamSamples = NULL; return NULL; } // failed AllocateSample() } // allocating samples on the stream // // succeeded allocating samples // return ppStreamSamples; } /////////////////////////////////////////////////////////////////////////////// // // AssociateEventsWithSamples // // call Update() on every sample of the array of stream samples to associate it // with an event from the array of events. The events will be signaled when the // corresponding sample has data and is ready to be written to a file // /////////////////////////////////////////////////////////////////////////////// HRESULT AssociateEventsWithSamples(IN HANDLE *pSampleReadyEvents, IN IStreamSample **ppStreamSamples, IN DWORD nNumberOfSamples) { for (DWORD i = 0; i < nNumberOfSamples; i++) { // // the event passed to Update will be signaled when the sample is // filled with data // HRESULT hr = ppStreamSamples[i]->Update(0, pSampleReadyEvents[i], NULL, 0); if (FAILED(hr)) { LogError("AssociateEventsWithSamples: " "Failed to call update on sample #%d", i); // // abort the samples we have Update()'d // for (DWORD j = 0; j < i; j++) { // // no need to check the return code here -- best effort attempt // if failed -- too bad // ppStreamSamples[j]->CompletionStatus(COMPSTAT_WAIT | COMPSTAT_ABORT, INFINITE); } return hr; } // Update() failed } // Update()'ing all samples return S_OK; } /////////////////////////////////////////////////////////////////////////////// // // GetAudioFormat // // return a pointer to wave format structure for the audio data produced by // the stream. the caller is responsible for deallocating returned stucture // // returns NULL if failed // ////////////////////////////////////////////////////////////////////////////// WAVEFORMATEX *GetAudioFormat(IMediaStream *pTerminalMediaStream) { // // get ITAMMediaFormat interface on the terminal, so we can query for // audio format // ITAMMediaFormat *pITMediaFormat = NULL; HRESULT hr = pTerminalMediaStream->QueryInterface(IID_ITAMMediaFormat, (void **)&pITMediaFormat); if (FAILED(hr)) { LogError("GetAudioFormat: " "failed to QI terminal for ITAMMediaFormat"); return NULL; } // // use ITAMMediaFormat to get terminal's media format // AM_MEDIA_TYPE *pMediaType = NULL; hr = pITMediaFormat->get_MediaFormat(&pMediaType); pITMediaFormat->Release(); pITMediaFormat = NULL; if (FAILED(hr)) { LogError("GetAudioFormat: failed to get_MediaFormat hr = 0x%lx", hr); return NULL; } // // did we get back a format that we can use? // if ((pMediaType->pbFormat == NULL) || pMediaType->formattype != FORMAT_WaveFormatEx) { LogError("GetAudioFormat: invalid format"); DeleteMediaType(pMediaType); pMediaType = NULL; return NULL; } // // allocate and return wave format // WAVEFORMATEX *pFormat = (WAVEFORMATEX *)AllocateMemory(pMediaType->cbFormat); if (NULL != pFormat) { CopyMemory(pFormat, pMediaType->pbFormat, pMediaType->cbFormat); } else { LogError("GetAudioFormat: Failed to allocate memory for audio format"); } // // remember to release AM_MEDIA_TYPE that we no longer need // DeleteMediaType(pMediaType); pMediaType = NULL; return pFormat; } /////////////////////////////////////////////////////////////////////////////// // // WriteSampleToFile // // This function writes the data portion of the sample into the file // /////////////////////////////////////////////////////////////////////////////// HRESULT WriteSampleToFile(IN IStreamSample *pStreamSample, // sample to record IN CAVIFileWriter *pFileWriter) // file to record to { // // get the sample's IMemoryData interface so we can get to the // sample's data // IMemoryData *pSampleMemoryData = NULL; HRESULT hr = pStreamSample->QueryInterface(IID_IMemoryData, (void **)&pSampleMemoryData); if (FAILED(hr)) { LogError("WriteSampleToFile: " "Failed to qi sample for IMemoryData"); return hr; } // // get to the sample's data buffer // DWORD nBufferSize = 0; BYTE *pnDataBuffer = NULL; DWORD nActualDataSize = 0; hr = pSampleMemoryData->GetInfo(&nBufferSize, &pnDataBuffer, &nActualDataSize); pSampleMemoryData->Release(); pSampleMemoryData = NULL; if (FAILED(hr)) { LogError("WriteSampleToFile: " "Failed to get to the sample's data"); return hr; } // // write the data buffer to the avi file // LogMessage("WriteSampleToFile: received a sample of size %ld bytes", nActualDataSize); ULONG nBytesWritten = 0; hr = pFileWriter->Write(pnDataBuffer, nActualDataSize, &nBytesWritten); if (FAILED(hr) || (0 == nBytesWritten)) { LogError("WriteSampleToFile: FileWriter.Write() wrote no data."); return E_FAIL; } return hr; } /////////////////////////////////////////////////////////////////////////////// // // GetSampleID // // given the return code fom WaitForMultipleObjects, this function determines // which sample was signal and returns S_OK and the id of the signaled sample // or E_FAIL if WaitForMultipleEvents returned an error // /////////////////////////////////////////////////////////////////////////////// HRESULT GetSampleID(IN DWORD nWaitCode, // code from WaitForMultiple... IN DWORD nNumberOfSamples, // the total number of samples IN OUT DWORD *pnSampleID) // the calculated id of the // signaled sample { // // event abandoned? // if ( (nWaitCode >= WAIT_ABANDONED_0) && (nWaitCode < WAIT_ABANDONED_0 + nNumberOfSamples) ) { LogError("GetSampleID: event for sample #%lu abandoned.", nWaitCode - WAIT_ABANDONED_0); return E_FAIL; } // // any other error? // if ( (WAIT_OBJECT_0 > nWaitCode) || (WAIT_OBJECT_0 + nNumberOfSamples <= nWaitCode) ) { LogMessage("GetSampleID: " "waiting for samples failed or timed out. " "WaitForMultipleObjects returned %lu", nWaitCode); return E_FAIL; } // // which sample was signaled? // *pnSampleID = nWaitCode - WAIT_OBJECT_0; return S_OK; } /////////////////////////////////////////////////////////////////////////////// // // WriteStreamToFile // // extract samples from the terminal's media stream and write them into a file // // returns when the call is disconnected (call disconnect causes media streaming // terminal to abort the samples // /////////////////////////////////////////////////////////////////////////////// HRESULT WriteStreamToFile(IN IMediaStream *pTerminalMediaStream) { LogMessage("WriteStreamToFile: started"); HRESULT hr = E_FAIL; // // get the number of stream samples we will be using // DWORD nNumberOfSamples = 0; hr = GetNumberOfSamplesOnStream(pTerminalMediaStream, &nNumberOfSamples); if (FAILED(hr)) { LogError("WriteStreamToFile: failed to get the number of samples"); return hr; } // // the number of samples directly corresponds the number of events we will // be waiting on later. WaitForMultipleObjects has a limit of // MAXIMUM_WAIT_OBJECTS events. // if (nNumberOfSamples > MAXIMUM_WAIT_OBJECTS) { LogError("WriteStreamToFile: the number of samples [%ld] " "exceeds the number allowed by the design of this " "application [%ld]", nNumberOfSamples, MAXIMUM_WAIT_OBJECTS); return E_FAIL; } // // allocate events that will be signaled when each sample is ready to be // saved to a file // HANDLE *pSampleReadyEvents = NULL; pSampleReadyEvents = AllocateEvents(nNumberOfSamples); if (NULL == pSampleReadyEvents) { LogError("WriteStreamToFile: Failed to allocate sample ready events."); return E_OUTOFMEMORY; } // // allocate array of stream samples // IStreamSample **ppStreamSamples = NULL; ppStreamSamples = AllocateStreamSamples(pTerminalMediaStream, nNumberOfSamples); if (NULL == ppStreamSamples) { LogError("WriteStreamToFile: Failed to allocate stream sample array"); // // release events we have allocated // ReleaseEvents(pSampleReadyEvents, nNumberOfSamples); pSampleReadyEvents = NULL; return E_FAIL; } // // we have the samples, we have the events. // associate events with samples so events get signaled when the // corresponding samples are ready to be written to a file // hr = AssociateEventsWithSamples(pSampleReadyEvents, ppStreamSamples, nNumberOfSamples); if (FAILED(hr)) { LogError("WriteStreamToFile: Failed to associate events with samples"); // // release events and samples we have allocated // ReleaseEvents(pSampleReadyEvents, nNumberOfSamples); pSampleReadyEvents = NULL; ReleaseSamples(ppStreamSamples, nNumberOfSamples); ppStreamSamples = NULL; return E_FAIL; } // // get the format of the data delivered by media streaming terminal // WAVEFORMATEX *pAudioFormat = NULL; pAudioFormat = GetAudioFormat(pTerminalMediaStream); if (NULL == pAudioFormat) { LogError("WriteStreamToFile: Failed to get audio format"); // // release events and samples we have allocated // ReleaseEvents(pSampleReadyEvents, nNumberOfSamples); pSampleReadyEvents = NULL; ReleaseSamples(ppStreamSamples, nNumberOfSamples); ppStreamSamples = NULL; return E_FAIL; } // // create a file with the required name and format. // CAVIFileWriter FileWriter; hr = FileWriter.Initialize(SZ_OUTPUTFILENAME, *pAudioFormat); // // no longer need audio format // FreeMemory(pAudioFormat); pAudioFormat = NULL; if (FAILED(hr)) { LogError("WriteStreamToFile: open file"); // // release events and samples we have allocated // ReleaseEvents(pSampleReadyEvents, nNumberOfSamples); pSampleReadyEvents = NULL; ReleaseSamples(ppStreamSamples, nNumberOfSamples); ppStreamSamples = NULL; return hr; } // // just for logging, count the number of samples we have recorded // ULONG nStreamSamplesRecorded = 0; while(TRUE) { // // wait for the events associated with the samples // when a samples has data, the corresponding event will be // signaled // DWORD nWaitCode = WaitForMultipleObjects(nNumberOfSamples, pSampleReadyEvents, FALSE, INFINITE); // // get the id of the sample that was signaled. fail if Wait returned // error // DWORD nSampleID = 0; hr = GetSampleID(nWaitCode, nNumberOfSamples, &nSampleID); if (FAILED(hr)) { LogError("WriteStreamToFile: wait failed"); break; } // // we filtered out all invalid error codes. so nSampleID has no // choice but be a valid sample index. // _ASSERTE(nSampleID < nNumberOfSamples); // // make sure the sample is ready to be read // hr = ppStreamSamples[nSampleID]->CompletionStatus(COMPSTAT_WAIT, 0); // // check against S_OK explicitly -- not all success codes mean the // sample is ready to be used (MS_S_ENDOFSTREAM, etc) // if (S_OK != hr) { if (E_ABORT == hr) { // // recording was aborted, probably because // the call was disconnected // LogMessage("WriteStreamToFile: recording aborted"); } else { LogMessage("WriteStreamToFile: sample is not completed. " "hr = 0x%lx", hr); } break; } // // we have the sample that was signaled and which is now ready to be // saved to a file. Record the sample. // hr = WriteSampleToFile(ppStreamSamples[nSampleID], &FileWriter); if (FAILED(hr)) { LogError("WriteStreamToFile: failed to write sample to file"); break; } // // one more sample was recorded. update the count. // nStreamSamplesRecorded++; // // we are done with this sample. return it to the source stream // to be refilled with data // hr = ppStreamSamples[nSampleID]->Update(0, pSampleReadyEvents[nSampleID], NULL, 0); if (FAILED(hr)) { LogError("WriteStreamToFile: " "Failed to Update the sample recorded. " "hr = 0x%lx", hr); break; } } // sample-writing loop LogMessage("WriteStreamToFile: wrote the total of %lu samples", nStreamSamplesRecorded); // // release samples and events // ReleaseSamples(ppStreamSamples, nNumberOfSamples); ppStreamSamples = NULL; ReleaseEvents(pSampleReadyEvents, nNumberOfSamples); pSampleReadyEvents = NULL; // // deallocated samples and events. safe to exit. // LogMessage("WriteStreamToFile: completed, hr = 0x%lx", hr); return hr; } /////////////////////////////////////////////////////////////////////////////// // // RecordMessage // // record the terminal's stream into a file // /////////////////////////////////////////////////////////////////////////////// HRESULT RecordMessage(IN ITTerminal *pRecordTerm) { LogMessage("RecordMessage: started"); HRESULT hr = E_FAIL; // // get IMediaStream interface on the terminal // IMediaStream *pTerminalMediaStream = NULL; hr = pRecordTerm->QueryInterface(IID_IMediaStream, (void**)&pTerminalMediaStream); if (FAILED(hr)) { LogError("RecordMessage: Failed to qi terminal for IMediaStream."); return hr; } // // write terminal stream data to a file // hr = WriteStreamToFile(pTerminalMediaStream); // // done with the terminal stream, release. // pTerminalMediaStream->Release(); pTerminalMediaStream = NULL; LogMessage("RecordMessage: finished"); return hr; } /////////////////////////////////////////////////////////////////////////////// // // ProcessCallNotificationEvent // // processing for TE_CALLNOTIFICATION event // /////////////////////////////////////////////////////////////////////////////// HRESULT ProcessCallNotificationEvent(IDispatch *pEvent) { HRESULT hr = E_FAIL; // // we are being notified of a new call // // if we own the call and there is not other active call // consider this to be the active call // // wait for CS_OFFERING message before answering the call // ITCallNotificationEvent *pCallNotificationEvent = NULL; hr = pEvent->QueryInterface( IID_ITCallNotificationEvent, (void **)&pCallNotificationEvent); if (FAILED(hr)) { LogError("ProcessCallNotificationEvent: " "Failed to QI event for ITCallNotificationEvent"); return hr; } // // get the call from notification event // ITCallInfo *pCall = NULL; hr = pCallNotificationEvent->get_Call(&pCall); // // release the ITCallNotificationEvent interface // pCallNotificationEvent->Release(); pCallNotificationEvent = NULL; if (FAILED(hr)) { LogError("ProcessCallNotificationEvent: " "Failed to get call from Call notification event"); return hr; } // // if we already have an active call, reject the new incoming call // EnterCriticalSection(&g_CurrentCallCritSection); if (NULL != g_pCurrentCall) { LeaveCriticalSection(&g_CurrentCallCritSection); LogMessage("ProcessCallNotificationEvent: " "incoming call while another call in progress"); ITBasicCallControl *pSecondCall = NULL; hr = pCall->QueryInterface(IID_ITBasicCallControl, (void**)&pSecondCall); pCall->Release(); pCall = NULL; if (FAILED(hr)) { LogError("ProcessCallNotificationEvent: failed to qi incoming call " "for ITBasicCallConrtrol"); return hr; } // // reject the incoming call // LogMessage("ProcessCallNotificationEvent: rejecting the incoming call"); hr = pSecondCall->Disconnect(DC_REJECTED); pSecondCall->Release(); pSecondCall = NULL; return E_FAIL; } // // check to see if we own the call // CALL_PRIVILEGE cp; hr = pCall->get_Privilege( &cp ); if ( FAILED(hr) ) { LogError("ProcessCallNotificationEvent: Failed to get call owner info"); pCall->Release(); pCall = NULL; LeaveCriticalSection(&g_CurrentCallCritSection); return hr; } if ( CP_OWNER != cp ) { // // we don't own the call. ignore it. // LogMessage("ProcessCallNotificationEvent: We don't own the call."); pCall->Release(); pCall = NULL; LeaveCriticalSection(&g_CurrentCallCritSection); return E_FAIL; } else { LogMessage("ProcessCallNotificationEvent: Incoming call."); } // // keep the call for future use // hr = pCall->QueryInterface(IID_ITBasicCallControl, (void**)&g_pCurrentCall); if (FAILED(hr)) { LogError("ProcessCallNotificationEvent: failed to qi incoming call for" "ITBasicCallControl."); g_pCurrentCall = NULL; } LeaveCriticalSection(&g_CurrentCallCritSection); pCall->Release(); pCall = NULL; return hr; } // ProcessCallNotificationEvent /////////////////////////////////////////////////////////////////////////////// // // ProcessCallMediaEvent // // processing for TE_CALLMEDIA event. if stream is active, record the // incoming data // /////////////////////////////////////////////////////////////////////////////// HRESULT ProcessCallMediaEvent(IDispatch *pEvent) { // // Get ITCallMediaEvent interface from the event // ITCallMediaEvent *pCallMediaEvent = NULL; HRESULT hr = pEvent->QueryInterface( IID_ITCallMediaEvent, (void **)&pCallMediaEvent ); if (FAILED(hr)) { // // the event does not have the interface we want // LogError("ProcessCallMediaEvent: TE_CALLMEDIA. " "Failed to QI event for ITCallMediaEvent"); return hr; } // // get the CALL_MEDIA_EVENT that we are being notified of. // CALL_MEDIA_EVENT CallMediaEvent; hr = pCallMediaEvent->get_Event(&CallMediaEvent); if ( FAILED(hr) ) { // // failed to get call media event // LogError("ProcessCallMediaEvent: TE_CALLMEDIA. " "Failed to get call media event hr = 0x%lx", hr); pCallMediaEvent->Release(); pCallMediaEvent = NULL; return hr; } LogMessage("ProcessCallMediaEvent: processing call media event"); switch (CallMediaEvent) { case CME_STREAM_INACTIVE: { LogMessage("ProcessCallMediaEvent: CME_STREAM_INACTIVE"); break; } case CME_STREAM_NOT_USED: LogMessage("ProcessCallMediaEvent: CME_STREAM_NOT_USED"); break; case CME_NEW_STREAM: LogMessage("ProcessCallMediaEvent: CME_NEW_STREAM received"); break; case CME_STREAM_FAIL: LogError("ProcessCallMediaEvent: CME_STREAM_FAIL received"); break; case CME_TERMINAL_FAIL: LogError("ProcessCallMediaEvent: CME_STREAM_FAIL received"); break; case CME_STREAM_ACTIVE: { LogError("ProcessCallMediaEvent: CME_STREAM_ACTIVE received"); // // Get the terminal on the active stream // ITTerminal *pRecordStreamTerminal = NULL; hr = GetTerminalFromMediaEvent(pCallMediaEvent, &pRecordStreamTerminal); if ( FAILED(hr) ) { // // the stream has no terminals associated with it // LogError("ProcessCallMediaEvent: " "failed to get terminal on the active stream"); break; } // // make sure the direction is right -- we are recording, so the // terminal should be TD_RENDER // TERMINAL_DIRECTION td; hr = pRecordStreamTerminal->get_Direction( &td); if ( FAILED(hr) ) { LogError("ProcessCallMediaEvent: " "failed to get record terminal's direction."); pRecordStreamTerminal->Release(); pRecordStreamTerminal = NULL; break; } // // double check that the terminal is rendering terminal // since we are the recording side // if ( TD_RENDER != td ) { // // this should never ever happen // LogError("ProcessCallMediaEvent: bad terminal direction"); pRecordStreamTerminal->Release(); pRecordStreamTerminal = NULL; hr = E_FAIL; break; } // // Now do the actual streaming. // // // this will block until: // // the call is disconnected, or // the user chooses to close the app, or // there is an error // // Since we are in the message processing thread, // the application will not be able to process messages // (the messages will still be queued) until this call // returns. // // If it is important that messages are processed while // file is being recorded, recording should be done on // a different thread. // RecordMessage(pRecordStreamTerminal); pRecordStreamTerminal->Release(); pRecordStreamTerminal = NULL; break; } default: break; } // switch (call media event) // // We no longer need the event interface. // pCallMediaEvent->Release(); pCallMediaEvent = NULL; return S_OK; } /////////////////////////////////////////////////////////////////////////////// // // ProcessCallStateEvent // // processing for TE_CALLSTATE. if CS_OFFERING, creates and selects MST, // answers the call . Release call if disconnected. // // also verifies that the event is for the current call // /////////////////////////////////////////////////////////////////////////////// HRESULT ProcessCallStateEvent(IDispatch *pEvent) { HRESULT hr = S_OK; // // TE_CALLSTATE is a call state event. // pEvent is an ITCallStateEvent // ITCallStateEvent *pCallStateEvent = NULL; // // Get the interface // hr = pEvent->QueryInterface(IID_ITCallStateEvent, (void **)&pCallStateEvent); if ( FAILED(hr) ) { LogError("ProcessCallStateEvent: " "Failed to QI event for ITCallStateEvent"); return hr; } // // make sure the message is for the active call! // EnterCriticalSection(&g_CurrentCallCritSection); if (!IsMessageForActiveCall(pCallStateEvent)) { LogMessage("ProcessCallStateEvent: received TE_CALLSTATE message " "for a different call. ignoring."); pCallStateEvent->Release(); pCallStateEvent = NULL; LeaveCriticalSection(&g_CurrentCallCritSection); return E_FAIL; } // // get the CallState that we are being notified of. // CALL_STATE CallState; hr = pCallStateEvent->get_State(&CallState); // // no longer need the event // pCallStateEvent->Release(); pCallStateEvent = NULL; if (FAILED(hr)) { LogError("ProcessCallStateEvent: " "failed to get state from call state event."); LeaveCriticalSection(&g_CurrentCallCritSection); return hr; } // // log the new call state // if (CS_OFFERING == CallState) { LogMessage("ProcessCallStateEvent: call state is CS_OFFERING"); // // try to create and select media streaming terminal on one of // the call's incoming audio streams // hr = CreateAndSelectMST(); if (S_OK == hr) { // // we have selected a terminal on one of the streams // answer the call // LogMessage("ProcessCallStateEvent: answering the call"); hr = g_pCurrentCall->Answer(); if (FAILED(hr)) { LogError("ProcessCallStateEvent: Failed to answer the call"); } } else { // // we could not create mst on any of the streams of // the incoming call. reject the call. // LogMessage("ProcessCallStateEvent: rejecting the call"); HRESULT hr2 = g_pCurrentCall->Disconnect(DC_REJECTED); if (FAILED(hr2)) { LogError("ProcessCallStateEvent: Failed to reject the call"); } } } // CS_OFFERING else if (CS_DISCONNECTED == CallState) { LogMessage("ProcessCallStateEvent: call state is CS_DISCONNECTED. " "Releasing the call."); // // release the call -- no longer need it! // g_pCurrentCall->Release(); g_pCurrentCall = NULL; // // signal the main thread that it can exit if it is time to exit // LogMessage("ProcessCallStateEvent: signaling main thread."); SetEvent(g_hExitEvent); } // CS_DISCONNECTED else if (CS_CONNECTED == CallState) { LogMessage("ProcessCallStateEvent: call state is CS_CONNECTED"); } // CS_CONNECTED // // no longer need to protect current call // LeaveCriticalSection(&g_CurrentCallCritSection); return hr; } ///////////////////////////////////////////////////////////////////////////// // // OnTapiEvent // // handler for tapi events. called on a thread that provides asychronous // processing of tapi messages // ///////////////////////////////////////////////////////////////////////////// HRESULT OnTapiEvent(TAPI_EVENT TapiEvent, IDispatch *pEvent) { LogMessage("OnTapiEvent: message received"); HRESULT hr = S_OK; switch ( TapiEvent ) { case TE_CALLNOTIFICATION: { LogMessage("OnTapiEvent: received TE_CALLNOTIFICATION"); hr = ProcessCallNotificationEvent(pEvent); break; } // TE_CALLNOTIFICATION case TE_CALLSTATE: { LogMessage("OnTapiEvent: received TE_CALLSTATE"); hr = ProcessCallStateEvent(pEvent); break; } // TE_CALLSTATE case TE_CALLMEDIA: { LogMessage("OnTapiEvent: received TE_CALLMEDIA"); hr = ProcessCallMediaEvent(pEvent); break; } // case TE_CALLMEDIA default: LogMessage("OnTapiEvent: received message %d. not handled.", TapiEvent); break; } // // the event was AddRef()'ed when it was posted for asynchronous processing // no longer need the event, release it. // pEvent->Release(); pEvent = NULL; LogMessage("OnTapiEvent: exiting."); return hr; }
22.762858
89
0.50919
windows-development
b90d71ff73fe564644ad817975cdc885fc3f1562
12,961
cpp
C++
test/libfilsc_test/c_codegen_tests.cpp
GuillermoHernan/fil-s
33d2a8e1c0eb3a9fddd9e6e2dc02780a13fd2302
[ "MIT" ]
null
null
null
test/libfilsc_test/c_codegen_tests.cpp
GuillermoHernan/fil-s
33d2a8e1c0eb3a9fddd9e6e2dc02780a13fd2302
[ "MIT" ]
null
null
null
test/libfilsc_test/c_codegen_tests.cpp
GuillermoHernan/fil-s
33d2a8e1c0eb3a9fddd9e6e2dc02780a13fd2302
[ "MIT" ]
null
null
null
/// <summary> /// Tests for 'C' code generator /// </summary> #include "libfilsc_test_pch.h" #include "c_codeGenerator_internal.h" #include "codeGeneratorState.h" #include "semanticAnalysis.h" #include "utils.h" //#include <time.h> using namespace std; /// <summary> /// Fixture for code generation tests. /// </summary> class C_CodegenTests : public ::testing::Test { protected: string m_resultsDir; /// <summary>Test initialization</summary> virtual void SetUp()override { m_resultsDir = makeResultsDir(); } /// <summary> /// Compiles (both FIL-S and 'C') and executes a test script. /// </summary> /// <param name="name"></param> /// <param name="code"></param> /// <returns></returns> int runTest(const char* name, const char* code) { //clock_t t0 = clock(); auto parseRes = testParse(code); if (!parseRes.ok()) throw parseRes.errorDesc; writeAST(parseRes.result, name); auto semanticRes = semanticAnalysis(parseRes.result); if (!semanticRes.ok()) throw semanticRes.errors[0]; //Just the first error, as it is not the tested subsystem. writeAST(semanticRes.result, name); string Ccode = generateCode(semanticRes.result, configureCodeGenerator()); writeCcode(Ccode, name); _flushall(); //To ensure all generated files are written to the disk. //clock_t t1 = clock(); //cout << "FIL-S compile time: " << double(t1 - t0)*1000 / CLOCKS_PER_SEC << " msegs.\n"; //t0 = t1; compileC(name); //t1 = clock(); //cout << "'C' compile time: " << double(t1 - t0)*1000 / CLOCKS_PER_SEC << " msegs.\n"; //t0 = t1; int result = executeProgram(name); //t1 = clock(); //cout << "execution time: " << double(t1 - t0)*1000 / CLOCKS_PER_SEC << " msegs.\n"; return result; } private: /// <summary> /// Creates the directory for test results, if it does not exist. /// </summary> /// <returns></returns> static std::string makeResultsDir() { auto testInfo = ::testing::UnitTest::GetInstance()->current_test_info(); string path = string("results/") + testInfo->test_case_name() + "." + testInfo->name(); if (!createDirIfNotExist(path)) { string message = "Cannot create directory: " + path; throw exception(message.c_str()); } return path; } /// <summary> /// Writes the AST to a file in the test directory; /// </summary> /// <param name="node"></param> /// <param name="testName"></param> void writeAST(Ref<AstNode> node, const char* testName) { string path = buildOutputFilePath(testName, ".result"); string content = printAST(node); if (!writeTextFile(path, content)) { string message = "Cannot write file: " + path; throw exception(message.c_str()); } } /// <summary> /// Creates the code genrator configuration structure. /// </summary> /// <returns></returns> CodeGeneratorConfig configureCodeGenerator() { static const char * prolog = "#include <stdio.h>\n" "//************ Prolog\n" "\n" "typedef unsigned char bool;\n" "static const bool true = 1;\n" "static const bool false = 0;\n" "\n"; static const char * epilog = "\n//************ Epilog\n" "int main()\n" "{\n" " int result = test();\n" " printf (\"%d\\n\", result);\n" " \n" " return result;\n" "}\n"; //static const char * epilogActor = // "\n//************ Epilog\n" // "\n" // "Test mainActor;\n" // "\n" // "int main()\n" // "{\n" CodeGeneratorConfig result; result.prolog = prolog; result.epilog = epilog; result.predefNames["test"] = "test"; return result; } /// <summary> /// Writes the 'C' code to a file in the test directory; /// </summary> /// <param name="code"></param> /// <param name="testName"></param> void writeCcode(const std::string& code, const char* testName) { string path = buildOutputFilePath(testName, ".c"); if (!writeTextFile(path, code)) { string message = "Cannot write file: " + path; throw exception(message.c_str()); } } /// <summary> /// Compiles the resulting 'C' file with an external compiler. /// </summary> /// <param name="testName"></param> int executeProgram(const char* testName) { //TODO: The executable extension is also system-dependent. string path = buildOutputFilePath(testName, ".exe"); path = normalizePath(path); string command = "cmd /C \"" + path + "\" >\"" + path + ".out\""; return system(command.c_str()); } void compileC(const char* testName) { string scriptPath = createCompileScript(testName); string command = "cmd /C \"" + scriptPath + "\" >NUL"; _flushall(); int result = system(command.c_str()); if (result != 0) { string message = string("Error compiling 'C' code (") + testName + ".c)"; throw exception(message.c_str()); } } std::string buildOutputFilePath(const string& testName, const string& extension) { return m_resultsDir + "/" + testName + extension; } string createCompileScript(const char* testName) { //TODO: This function is very system dependent. static const char* base = "call \"H:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Auxiliary\\Build\\vcvars32.bat\"\n" "cd \"%s\"\n" "%s\n" "cl %s.c -nologo /FAs /Ox >%s.compiler.out\n"; char buffer[4096]; string absPath = joinPaths(getCurrentDirectory(), m_resultsDir); string drive = absPath.substr(0, 2); string scriptPath = buildOutputFilePath(testName, ".compile.bat"); absPath = normalizePath(absPath); scriptPath = normalizePath(scriptPath); sprintf_s(buffer, base, absPath.c_str(), drive.c_str(), testName, testName); if (!writeTextFile(scriptPath, buffer)) { string message = "Cannot write file: " + scriptPath; throw exception(message.c_str()); } return scriptPath; } }; //class C_CodegenTests #define EXPECT_RUN_OK(n,x) EXPECT_EQ(0, runTest((n),(x))) /// <summary> /// Tests 'generateCode' function. /// </summary> TEST_F(C_CodegenTests, generateCode) { int res = runTest("generate1", "function test ():int {0}"); ASSERT_EQ(0, res); } /// <summary> /// Test code generation for function definition nodes. /// Also tests 'genFunctionHeader' function. /// </summary> TEST_F(C_CodegenTests, functionCodegen) { //Function with a scalar return value. EXPECT_RUN_OK("function1", "function add (a:int, b: int):int {\n" " a+b\n" "}\n" "function test ():int {\n" " if (add(3,7) == 10) 0 else 1\n" "}" ); //Function with no return value EXPECT_RUN_OK("function2", "function t2 (a:int, b: int):() {\n" " a+b\n" "}\n" "function test ():int {\n" " t2(3,1);\n" " 0\n" "}" ); //Function with a tuple return value. EXPECT_RUN_OK("function3", "function stats (a:int, b: int, c: int):(sum: int, mean:int) {\n" " const sum = a+b+c\n" " (sum, sum/3)" "}\n" "function test ():int {\n" " const result = stats (7,5,6);" " if ((result.sum == 18) && (result.mean == 6))\n" " 0 else 1\n" "}" ); } /// <summary> /// Test code generation for block nodes. /// </summary> TEST_F(C_CodegenTests, blockCodegen) { EXPECT_RUN_OK("block1", "function ppc(p:int, p':int) {\n" " const alpha = (p * p) - 8\n" " const bravo = p' + {12}\n" " {}\n" " alpha % bravo\n" "}\n" "function test ():int {\n" " if (ppc(9,5) == 5) 0 else 1\n" "}\n" ); } /// <summary> /// Test code generation for Tuples. /// </summary> TEST_F(C_CodegenTests, tupleCodegen) { EXPECT_RUN_OK("tuple1", "function divide(a:int, b:int) {\n" " (a/b, a%b)\n" "}\n" "function doNothing() {\n" " ()\n" "}\n" "function test ():int {\n" " var x:(q:int, r:int)\n" " doNothing()\n" " x = divide (23, 7)\n" " if ( (x.q == 3) && (x.r == 2)) 0 else 1\n" "}\n" ); } /// <summary> /// Test code generation for return statements. /// </summary> TEST_F(C_CodegenTests, returnCodegen) { EXPECT_RUN_OK("return1", "function divide(a:int, b:int) {\n" " return (a/b, a%b)\n" "}\n" "function divide'(a:int, b:int):(r:int, q:int) {\n" " return (a/b, a%b)\n" "}\n" "function doNothing() {\n" " return;\n" "}\n" "function test ():int {\n" " var x:(q:int, r:int)\n" " doNothing()\n" " x = divide (23, 7)\n" " if ( (x.q != 3) || (x.r != 2)) return 1\n" " if ( divide'(14,2).r != 7) return 2\n" " if ( divide'(31,7).q != 3) return 3\n" "\n" " return 0" "}\n" ); } /// <summary> /// Test code generation for return assignment expressions. /// </summary> TEST_F(C_CodegenTests, assignmentCodegen) { EXPECT_RUN_OK("assign1", "function test ():int {\n" " var x:int\n" " var y:int\n" " x = y = 5\n" " if ((x*y) != 25) return 1\n" " \n" " var t:(var a:int, var b:int)\n" " t.a = 7;\n" " if (t.a != 7) return 2\n" " \n" " t.a = x = t.b = 8;\n" " const p = x * t.a * t.b;\n" " if (p != 512) return 3\n" " \n" " return 0\n" "}\n" ); } /// <summary> /// Test code generation for function call nodes. /// </summary> TEST_F(C_CodegenTests, callCodegen) { EXPECT_RUN_OK("call1", "function double(a:int):int {\n" " a * 2\n" "}\n" "function doNothing() {\n" " return;\n" "}\n" "function divide(a:int, b:int):(q:int, r:int) {\n" " (a/b, a%b)\n" "}\n" "function test ():int {\n" " doNothing()\n" " if (double(4) != 8) return 1\n" " if (divide(17, 5).q != 3) return 2\n" " if (divide(30, 5).r != 0) return 3\n" " \n" " return 0\n" "}\n" ); } /// <summary> /// Test code generation for literal expressions. /// Also tests 'varAccessCodegen' /// </summary> TEST_F(C_CodegenTests, literalCodegen) { EXPECT_RUN_OK("literal1", "function test ():int {\n" " var x:int\n" " x = 3\n" " 7\n" " x\n" " if (x!=3) return 1\n" " 0\n" "}\n" ); } /// <summary> /// Test code generation for prefix operators. /// </summary> TEST_F(C_CodegenTests, prefixOpCodegen) { EXPECT_RUN_OK("prefix1", "function test ():int {\n" " var x:int\n" " var y:int\n" " x = 3\n" " y = -x\n" " if ((x+y) != 0) return 1001\n" " if (!((x+y) == 0)) return 1002\n" " y = ++x\n" " if (y != 4) return 1003\n" " if (x != y) return 1031\n" " x = --y\n" " if ((x != 3) || (x != y)) return 1004\n" " \n" " ++y;\n" " if (y != 4) return 1005\n" " 0\n" "}\n" ); } /// <summary> /// Test code generation for postfix operators. /// </summary> TEST_F(C_CodegenTests, postfixOpCodegen) { EXPECT_RUN_OK("postfix1", "function test ():int {\n" " var x:int = 5\n" " var y:int\n" " y = x++\n" " if (y != 5) return 1010\n" " if (x != 6) return 1020\n" " \n" " x = y--\n" " if (y != 4) return 1030\n" " if (x != 5) return 1040\n" " \n" " ++y;\n" " if (y != 5) return 1050\n" " 0\n" "}\n" ); } /// <summary> /// Test actor code generation /// </summary> TEST_F(C_CodegenTests, DISABLED_actors) { //TODO: This test is disabled because code generation tests lack the infrastructure //to run actors. Decide to create suck infrastructure, or test actor code generation //with external tests. EXPECT_RUN_OK("actors1", "actor Test {\n" " output o1(int)\n" " input i1(a: int) {o1(a * 2)}\n" "}\n" ); }
26.559426
126
0.505671
GuillermoHernan
b90f7ecd38578fe8fd5de93ffdebca63eb03daa9
1,542
cpp
C++
leetcode/Algorithms/available-captures-for-rook.cpp
Doarakko/competitive-programming
5ae78c501664af08a3f16c81dbd54c68310adec8
[ "MIT" ]
1
2017-07-11T16:47:29.000Z
2017-07-11T16:47:29.000Z
leetcode/Algorithms/available-captures-for-rook.cpp
Doarakko/Competitive-Programming
10642a4bd7266c828dd2fc6e311284e86bdf2968
[ "MIT" ]
1
2021-02-07T09:10:26.000Z
2021-02-07T09:10:26.000Z
leetcode/Algorithms/available-captures-for-rook.cpp
Doarakko/Competitive-Programming
10642a4bd7266c828dd2fc6e311284e86bdf2968
[ "MIT" ]
null
null
null
class Solution { public: int numRookCaptures(vector<vector<char>>& board) { // search rook int x, y; for(int i = 0; i < board.size(); i++){ for(int j = 0; j < board[0].size(); j++){ if(board[i][j] == 'R'){ x = j; y = i; } } } int cnt = 0; // top for(int i = y - 1; i >= 0; i--){ if(board[i][x] == 'p'){ cnt++; break; }else if(board[i][x] == '.'){ continue; }else{ break; } } // bottom for(int i = y + 1; i < board.size(); i++){ if(board[i][x] == 'p'){ cnt++; break; }else if(board[i][x] == '.'){ continue; }else{ break; } } // left for(int i = x - 1; i >= 0; i--){ if(board[y][i] == 'p'){ cnt++; break; }else if(board[y][i] == '.'){ continue; }else{ break; } } // right for(int i = x + 1; i < board[0].size(); i++){ if(board[y][i] == 'p'){ cnt++; break; }else if(board[y][i] == '.'){ continue; }else{ break; } } return cnt; } };
24.870968
54
0.270428
Doarakko
b9114f53a4edef347073818413904c0a12028c20
2,005
cpp
C++
src/ripple/protocol/impl/Issue.cpp
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
5
2019-01-23T04:36:03.000Z
2020-02-04T07:10:39.000Z
src/ripple/protocol/impl/Issue.cpp
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
null
null
null
src/ripple/protocol/impl/Issue.cpp
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
2
2019-05-14T07:26:59.000Z
2020-06-15T07:25:01.000Z
//此源码被清华学神尹成大魔王专业翻译分析并修改 //尹成QQ77025077 //尹成微信18510341407 //尹成所在QQ群721929980 //尹成邮箱 yinc13@mails.tsinghua.edu.cn //尹成毕业于清华大学,微软区块链领域全球最有价值专家 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 //———————————————————————————————————————————————————————————————————————————————————————————————————————————————— /* 此文件是Rippled的一部分:https://github.com/ripple/rippled 版权所有(c)2012,2013 Ripple Labs Inc. 使用、复制、修改和/或分发本软件的权限 特此授予免费或不收费的目的,前提是 版权声明和本许可声明出现在所有副本中。 本软件按“原样”提供,作者不作任何保证。 关于本软件,包括 适销性和适用性。在任何情况下,作者都不对 任何特殊、直接、间接或后果性损害或任何损害 因使用、数据或利润损失而导致的任何情况,无论是在 合同行为、疏忽或其他侵权行为 或与本软件的使用或性能有关。 **/ //============================================================== #include <ripple/protocol/Issue.h> namespace ripple { bool isConsistent (Issue const& ac) { return isXRP (ac.currency) == isXRP (ac.account); } std::string to_string (Issue const& ac) { if (isXRP (ac.account)) return to_string (ac.currency); return to_string(ac.account) + "/" + to_string(ac.currency); } std::ostream& operator<< (std::ostream& os, Issue const& x) { os << to_string (x); return os; } /*有序比较。 资产先按货币订购,然后按账户订购。 如果货币不是XRP。 **/ int compare (Issue const& lhs, Issue const& rhs) { int diff = compare (lhs.currency, rhs.currency); if (diff != 0) return diff; if (isXRP (lhs.currency)) return 0; return compare (lhs.account, rhs.account); } /*平等比较。*/ /*@ {*/ bool operator== (Issue const& lhs, Issue const& rhs) { return compare (lhs, rhs) == 0; } bool operator!= (Issue const& lhs, Issue const& rhs) { return ! (lhs == rhs); } /*@ }*/ /*严格的弱排序。*/ /*@ {*/ bool operator< (Issue const& lhs, Issue const& rhs) { return compare (lhs, rhs) < 0; } bool operator> (Issue const& lhs, Issue const& rhs) { return rhs < lhs; } bool operator>= (Issue const& lhs, Issue const& rhs) { return ! (lhs < rhs); } bool operator<= (Issue const& lhs, Issue const& rhs) { return ! (rhs < lhs); } } //涟漪
17.743363
114
0.583541
yinchengtsinghua
b918d115b957255720f7138fa9c2839a7c379849
10,057
cpp
C++
sdbq_parser/sdbq_parser/sdbq_parser.cpp
w1n5t0n99/SdbqParser
d92f21bebbaaf02028b40b73f052198eb2c11858
[ "MIT" ]
null
null
null
sdbq_parser/sdbq_parser/sdbq_parser.cpp
w1n5t0n99/SdbqParser
d92f21bebbaaf02028b40b73f052198eb2c11858
[ "MIT" ]
null
null
null
sdbq_parser/sdbq_parser/sdbq_parser.cpp
w1n5t0n99/SdbqParser
d92f21bebbaaf02028b40b73f052198eb2c11858
[ "MIT" ]
null
null
null
#include "sdbq_parser.h" #include <algorithm> #include <iostream> #include <unordered_set> #include <map> #include "csv.h" namespace sdbq { struct QuestionDescriptorHasher { size_t operator() (const Question& val) const { return std::hash<std::string>()(val.descriptor+val.difficulty); } }; struct QuestionDescriptorComparer { bool operator() (const Question& lhs, const Question& rhs) const { return (lhs.descriptor == rhs.descriptor) & (lhs.difficulty == rhs.difficulty); }; }; struct QuestionTestHasher { size_t operator() (const Question& val) const { return std::hash<std::string>()(val.test_name); } }; struct QuestionTestComparer { bool operator() (const Question& lhs, const Question& rhs) const { return lhs.test_name == rhs.test_name; }; }; struct QuestionGradeHasher { size_t operator() (const Question& val) const { return std::hash<std::string>()(val.grade); } }; struct QuestionGradeComparer { bool operator() (const Question& lhs, const Question& rhs) const { return lhs.grade == rhs.grade; }; }; std::optional<std::vector<Question>> ParseSdbq(std::string file_name, int count_estimate) { std::vector<Question> questions; questions.reserve(count_estimate); try { io::CSVReader<12, typename io::trim_chars<' ', '\t'>, typename io::double_quote_escape<',', '\"'> > in(file_name); in.read_header(io::ignore_extra_column, "Last Name", "First Name", "MI", "Grade", "Div Name", "Sch Name", "Group Name", "Test", "Retest", "Item Descriptor", "Item Difficulty", "Response"); //child std::string last_name = {}; std::string first_name = {}; std::string middle_initial = {}; // question std::string item_descriptor = {}; item_descriptor.reserve(100); std::string response = {}; std::string difficulty = {}; // location std::string division_name = {}; std::string school_name = {}; std::string grade_str = {}; std::string test_name = {}; std::string retest = {}; std::string group_name = {}; while (in.read_row( last_name, first_name, middle_initial, grade_str, division_name, school_name, group_name, test_name, retest, item_descriptor, difficulty, response)) { // append quotes on descriptor item_descriptor.push_back('\"'); item_descriptor.insert(0, 1, '\"'); questions.push_back({grade_str, test_name, retest, group_name, response, difficulty,item_descriptor,last_name,first_name, middle_initial, division_name, school_name }); } } catch (io::error::can_not_open_file& err) { return {}; } return questions; } std::optional<std::vector<ResultStats>> ParseResults(std::string file_name, int count_estimate) { std::vector<ResultStats> stats; stats.reserve(count_estimate); try { io::CSVReader<6, typename io::trim_chars<' ', '\t'>, typename io::double_quote_escape<',', '\"'> > in(file_name); in.read_header(io::ignore_extra_column, "descriptor", "difficulty", "total correct", "total incorrect", "unique correct", "unique incorrect"); std::string descriptor = {}; descriptor.reserve(100); std::string difficulty = {}; int total_correct = {}; int total_incorrect = {}; int unique_correct = {}; int unique_incorrect = {}; while (in.read_row( descriptor, difficulty, total_correct, total_incorrect, unique_correct, unique_incorrect)) { // append quotes on descriptor descriptor.push_back('\"'); descriptor.insert(0, 1, '\"'); stats.push_back({ difficulty, descriptor, total_correct, total_incorrect, unique_correct, unique_incorrect }); } } catch (io::error::can_not_open_file& err) { return {}; } return stats; } std::vector<std::string> GetUniqueGrades(const std::vector<Question>& questions) { std::unordered_set<Question, QuestionGradeHasher, QuestionGradeComparer> unq_questions; for (const auto& q : questions) unq_questions.insert(q); std::vector<std::string> unq_questions_vec; unq_questions_vec.reserve(unq_questions.size()); std::for_each(unq_questions.begin(), unq_questions.end(), [&](const auto& q) {unq_questions_vec.push_back(q.grade); }); return unq_questions_vec; } std::vector<std::string> GetUniqueTests(const std::vector<Question>& questions) { std::unordered_set<Question, QuestionTestHasher, QuestionTestComparer> unq_questions; for (const auto& q : questions) unq_questions.insert(q); std::vector<std::string> unq_questions_vec; unq_questions_vec.reserve(unq_questions.size()); std::for_each(unq_questions.begin(), unq_questions.end(), [&](const auto& q) {unq_questions_vec.push_back(q.test_name); }); return unq_questions_vec; } std::vector<std::pair<std::string, std::vector<Question>>> GetUniqueTestsAndQuestions(const std::vector<Question>& questions) { std::map<std::string, std::vector<Question>> tests_map; for (const auto& q : questions) tests_map[q.test_name].push_back(q); std::vector<std::pair<std::string, std::vector<Question>>> tests; for (auto& t : tests_map) tests.push_back(std::make_pair(std::move(t.first), std::move(t.second))); return tests; } std::vector<std::string> GetUniqueDescriptors(const std::vector<Question>& questions) { std::unordered_set<Question, QuestionDescriptorHasher, QuestionDescriptorComparer> unq_questions; for (const auto& q : questions) unq_questions.insert(q); std::vector<std::string> unq_questions_vec; unq_questions_vec.reserve(unq_questions.size()); std::for_each(unq_questions.begin(), unq_questions.end(), [&](const auto& q) {unq_questions_vec.push_back(q.descriptor); }); return unq_questions_vec; } std::vector<Question> GetGradeQuestions(const std::vector<Question>& questions, std::string_view grade) { std::vector<Question> grade_questions; auto it = questions.begin(); auto end = questions.end(); while (it != end) { it = std::find_if(it, end, [&](const auto& val) { return val.grade == grade; }); if (it != end) { grade_questions.push_back(*it); it++; } } return grade_questions; } std::vector<Question> GetTestQuestions(const std::vector<Question>& questions, std::string_view test_name) { std::vector<Question> test_questions; auto it = questions.begin(); auto end = questions.end(); while (it != end) { it = std::find_if(it, end, [&](const auto& val) { return val.test_name == test_name; }); if (it != end) { test_questions.push_back(*it); it++; } } return test_questions; } std::vector<QuestionStats> GetQuestionStats(const std::vector<Question>& questions) { std::vector<QuestionStats> question_stats; // map the descriptor and difficulty to students std::map<std::pair<std::string, std::string>, std::vector<Question>> descriptors; for (const auto& q : questions) { descriptors[{q.descriptor, q.difficulty}].push_back(q); } for (const auto& [d, qs] : descriptors) { QuestionStats stats; stats.descriptor = d.first; stats.difficulty = d.second; std::map<Student, std::string> unique_students; for (const auto& q : qs) { const auto& res = q.response; Student student = { q.first_name, q.last_name }; if (res == "COR") { stats.total_correct.push_back(student); // we want to update an existing key to correct unique_students[student] = res; } else { stats.total_incorrect.push_back(student); // we dont want to change an existing key to incorrect unique_students.insert({ student, res }); } } for (const auto& s : unique_students) { if(s.second == "COR") stats.unique_correct.push_back(s.first); else stats.unique_incorrect.push_back(s.first); } //std::replace(stats.descriptor.begin(), stats.descriptor.end(), ',', ';'); question_stats.push_back(stats); } return question_stats; } std::vector<QuestionStats> MergeQuestionStats(const std::vector<QuestionStats>& stats0, const std::vector<QuestionStats>& stats1) { std::vector<QuestionStats> merged_questions; std::map<std::pair<std::string, std::string>, QuestionStats> question_map; for (const auto& q : stats0) question_map.insert({ {q.descriptor, q.difficulty}, q }); for (const auto& q : stats1) { auto& [it, success] = question_map.insert({ { q.descriptor, q.difficulty }, q }); if (!success) { auto& merged_total_correct = it->second.total_correct; merged_total_correct.insert(merged_total_correct.end(), q.total_correct.begin(), q.total_correct.end()); auto& merged_total_incorrect = it->second.total_incorrect; merged_total_incorrect.insert(merged_total_incorrect.end(), q.total_incorrect.begin(), q.total_incorrect.end()); auto& merged_unique_correct = it->second.unique_correct; merged_unique_correct.insert(merged_unique_correct.end(), q.unique_correct.begin(), q.unique_correct.end()); auto& merged_unique_incorrect = it->second.unique_incorrect; merged_unique_incorrect.insert(merged_unique_incorrect.end(), q.unique_incorrect.begin(), q.unique_incorrect.end()); } } for (auto& s : question_map) merged_questions.push_back(std::move(s.second)); return merged_questions; } void MergeResults(std::vector<ResultStats>& total_stats, const std::vector<ResultStats>& stats) { std::map<std::pair<std::string, std::string>, ResultStats> result_map; for (const auto& s : total_stats) result_map.insert({ { s.descriptor, s.difficulty }, s }); for (const auto& s : stats) { auto&[it, success] = result_map.insert({ {s.descriptor, s.difficulty}, s }); if (!success) { it->second.total_correct += s.total_correct; it->second.total_incorrect += s.total_incorrect; it->second.unique_correct += s.unique_correct; it->second.unique_incorrect += s.unique_incorrect; } } total_stats.clear(); for (auto& r : result_map) total_stats.push_back(std::move(r.second)); } }
26.60582
151
0.68062
w1n5t0n99
2c6e45870f582585cab579c82f1d9d0d79fcf9f5
3,387
cpp
C++
Nesis/Nesis/src/NesisBrowser.cpp
jpoirier/x-gauges
8261b19a9678ad27db44eb8c354f5e66bd061693
[ "BSD-3-Clause" ]
3
2015-11-08T07:17:46.000Z
2019-04-05T17:08:05.000Z
Nesis/Nesis/src/NesisBrowser.cpp
jpoirier/x-gauges
8261b19a9678ad27db44eb8c354f5e66bd061693
[ "BSD-3-Clause" ]
null
null
null
Nesis/Nesis/src/NesisBrowser.cpp
jpoirier/x-gauges
8261b19a9678ad27db44eb8c354f5e66bd061693
[ "BSD-3-Clause" ]
null
null
null
/*************************************************************************** * * * Copyright (C) 2007 by Kanardia d.o.o. [see www.kanardia.eu] * * Writen by: * * Ales Krajnc [ales.krajnc@kanardia.eu] * * * * Status: Open Source * * * * License: GPL - GNU General Public License * * See 'COPYING.html' for more details about the license. * * * ***************************************************************************/ #include <QtDebug> #include <QtGui> #include "NesisBrowser.h" // ----------------------------------------------------------------------- NesisBrowser::NesisBrowser(QWidget *pParent) : QTextBrowser(pParent) { } // ----------------------------------------------------------------------- NesisBrowser::~NesisBrowser() { } // ----------------------------------------------------------------------- bool NesisBrowser::HandleNesisInputEvent(PanelButton ePB) { switch(ePB) { // Back button case pbBtn1: backward(); break; // Forward button case pbBtn2: forward(); break; // Page Down button case pbBtn3: qApp->postEvent(this, new QKeyEvent(QEvent::KeyPress, Qt::Key_PageDown, Qt::NoModifier)); break; // Page Up button case pbBtn4: qApp->postEvent(this, new QKeyEvent(QEvent::KeyPress, Qt::Key_PageUp, Qt::NoModifier)); break; // Go to next link Knob CW = clockwise case pbKnobCW: qApp->postEvent(this, new QKeyEvent(QEvent::KeyPress, Qt::Key_Tab, Qt::NoModifier)); break; // Knob CCW = counterclockwise case pbKnobCCW: qApp->postEvent(this, new QKeyEvent(QEvent::KeyPress, Qt::Key_Tab, Qt::ShiftModifier)); break; // OK button was pressed case pbOk: qApp->postEvent(this, new QKeyEvent(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier)); break; // Cancel button was pressed case pbCancel: emit NesisCancel(); break; // Not handled here - forward this to interested objects. default: emit NesisButton(ePB-pbBtn1); break; } return true; } // ----------------------------------------------------------------------- QStringList NesisBrowser::GetButtonLabels() const { QStringList sl; sl << tr("Back"); sl << tr("Forward"); sl << tr("Pg Down"); sl << tr("Pg Up"); return sl; } // ----------------------------------------------------------------------- void NesisBrowser::focusInEvent(QFocusEvent* pEvent) { // Call base class handler. QTextBrowser::focusInEvent(pEvent); ShowButtons(true); } // ----------------------------------------------------------------------- void NesisBrowser::focusOutEvent(QFocusEvent* pEvent) { if(pEvent->reason() == Qt::TabFocusReason || pEvent->reason() == Qt::BacktabFocusReason) { // FIXME The following line may be causing problems. setFocus(Qt::OtherFocusReason); return; } QTextBrowser::focusOutEvent(pEvent); HideButtons(); } // -----------------------------------------------------------------------
29.710526
92
0.446118
jpoirier
2c6e46b7e07f7e232d9c0143b0f11f767452969a
447
hpp
C++
include/Sprite/Wall.hpp
VisualGMQ/Chaos_Dungeon
95f9b23934ee16573bf9289b9171958f750ffc93
[ "MIT" ]
2
2020-05-05T13:31:55.000Z
2022-01-16T15:38:00.000Z
include/Sprite/Wall.hpp
VisualGMQ/Chaos_Dungeon
95f9b23934ee16573bf9289b9171958f750ffc93
[ "MIT" ]
null
null
null
include/Sprite/Wall.hpp
VisualGMQ/Chaos_Dungeon
95f9b23934ee16573bf9289b9171958f750ffc93
[ "MIT" ]
1
2021-11-27T02:32:24.000Z
2021-11-27T02:32:24.000Z
#ifndef WALL_HPP #define WALL_HPP #include "Sprite.hpp" #include "Collision.hpp" #include "Colliable.hpp" #include "ColliSystem.hpp" #include "Texture.hpp" class Wall : public ColliableSprite{ public: static Wall* Create(); void Init() override; int Width() const; int Height() const; ~Wall(); private: Wall(); Vec topleft() const; void update() override; void draw() override; Texture texture; }; #endif
17.88
36
0.666667
VisualGMQ
2c6e74a9e357f3bf89c4ce9ba98b700eeb860dce
992
hpp
C++
src/micromamba/info.hpp
pbauwens-kbc/mamba
243bf801e99fc2215f88fd87c66574aeb85a52e9
[ "BSD-3-Clause" ]
null
null
null
src/micromamba/info.hpp
pbauwens-kbc/mamba
243bf801e99fc2215f88fd87c66574aeb85a52e9
[ "BSD-3-Clause" ]
null
null
null
src/micromamba/info.hpp
pbauwens-kbc/mamba
243bf801e99fc2215f88fd87c66574aeb85a52e9
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019, QuantStack and Mamba Contributors // // Distributed under the terms of the BSD 3-Clause License. // // The full license is in the file LICENSE, distributed with this software. #ifndef UMAMBA_INFO_HPP #define UMAMBA_INFO_HPP #include "mamba/context.hpp" #ifdef VENDORED_CLI11 #include "mamba/CLI.hpp" #else #include <CLI/CLI.hpp> #endif #include <string> #include <tuple> #include <vector> const char banner[] = R"MAMBARAW( __ __ ______ ___ ____ _____ ___ / /_ ____ _ / / / / __ `__ \/ __ `/ __ `__ \/ __ \/ __ `/ / /_/ / / / / / / /_/ / / / / / / /_/ / /_/ / / .___/_/ /_/ /_/\__,_/_/ /_/ /_/_.___/\__,_/ /_/ )MAMBARAW"; void init_info_parser(CLI::App* subcom); void set_info_command(CLI::App* subcom); void load_info_options(mamba::Context& ctx); void info_pretty_print(std::vector<std::tuple<std::string, std::vector<std::string>>> map); std::string version(); #endif
20.666667
86
0.607863
pbauwens-kbc
2c6ea8547eaf985577c74dba91007c36f665cfca
7,496
cc
C++
src/rbf/pfm.cc
moophis/CS222-Simple-Data-Management-System
55b34eccc4d66c0c0ed201992fd0a2cd4e4711d5
[ "Apache-2.0" ]
null
null
null
src/rbf/pfm.cc
moophis/CS222-Simple-Data-Management-System
55b34eccc4d66c0c0ed201992fd0a2cd4e4711d5
[ "Apache-2.0" ]
null
null
null
src/rbf/pfm.cc
moophis/CS222-Simple-Data-Management-System
55b34eccc4d66c0c0ed201992fd0a2cd4e4711d5
[ "Apache-2.0" ]
null
null
null
#include "pfm.h" #include <iostream> #include <cstdio> ///////////////////////////////////////////////////// PagedFileManager* PagedFileManager::_pf_manager = 0; PagedFileManager* PagedFileManager::instance() { if(!_pf_manager) _pf_manager = new PagedFileManager(); return _pf_manager; } PagedFileManager::PagedFileManager() { } PagedFileManager::~PagedFileManager() { } /** * Create a file. * * @param fileName * the name of the file to be created. * @return status */ RC PagedFileManager::createFile(const char *fileName) { // Test existence FILE *fp = fopen(fileName, "r"); if (fp) { return ERR_EXIST; } else { fp = fopen(fileName, "w"); if (!fp) { return ERR_NOT_EXIST; } return SUCCESSFUL; } } /** * Delete a file. * * @param fileName * the name of the file to be destroyed. * @return status */ RC PagedFileManager::destroyFile(const char *fileName) { if (remove(fileName) != 0) { __trace(); return ERR_NOT_EXIST; } else { // __trace(); return SUCCESSFUL; } } /** * Open a file. * * @param fileName * the name of the file to be opened. * @param fileHandle * the file handle associated with this file. * @return status */ RC PagedFileManager::openFile(const char *fileName, FileHandle &fileHandle) { FILE *fp = fopen(fileName, "r+"); if (!fp) { // __trace(); // std::cout << "-->Cannot open file: " << fileName << std::endl; return ERR_NOT_EXIST; } // get the file size in pages(should be multiple of PAGE_SIZE) long fileSize = 0l; if (fseek(fp, 0, SEEK_END)) { __trace(); return ERR_LOCATE; } if ((fileSize = ftell(fp)) == -1) { __trace(); return ERR_LOCATE; } if (fileSize % PAGE_SIZE != 0) { // File size is not a multiple of PAGE_SIZE // Probably this file has been damaged return ERR_ALIGN; } // fileHandle.setNumberOfPages(fileSize / PAGE_SIZE); fileHandle.setFilePointer(fp); fileHandle.setFileName(fileName); // std::cout << "### In PagedFileManager::openFile(), set fileHandle: -> name: " << fileHandle.getFileName() // << ", # of pages: " << fileHandle.getNumberOfPages() << std::endl; return SUCCESSFUL; } /** * Close a file. * * @param fileName * the name of the file to be closed. * @return status */ RC PagedFileManager::closeFile(FileHandle &fileHandle) { if (fclose(fileHandle.getFilePointer())) { return ERR_NOT_EXIST; } return SUCCESSFUL; } ///////////////////////////////////////////////////// FileHandle::FileHandle() { // pageCount = 0; filePtr = NULL; // fileName = NULL; readPageCounter = 0; writePageCounter = 0; appendPageCounter = 0; } FileHandle::~FileHandle() { } /** * Read a page of data from the file * @param pageNum * the page number to read * @param data * the pointer to the buffer for storing the read data * @return status */ RC FileHandle::readPage(PageNum pageNum, void *data) { if (!data) { return ERR_NULLPTR; } if (pageNum >= getNumberOfPages()) { __trace(); std::cout << "--> pageNum: " << pageNum << ", pageCount: " << getNumberOfPages() << std::endl; return ERR_LOCATE; } long curPos = pageNum * PAGE_SIZE; if (fseek(filePtr, curPos, SEEK_SET)) { __trace(); return ERR_LOCATE; } if (fread(data, sizeof(char), PAGE_SIZE, filePtr) != PAGE_SIZE) { return ERR_READ; } readPageCounter++; // std::cout << fileName << " readPageCounter " << readPageCounter << std::endl; return SUCCESSFUL; } /** * Write a page of data to the file given page number. * Here we assume that data size will not exceed the size of a page. * * @param pageNum * the number of the page to be written. * @param data * the data * @return status */ RC FileHandle::writePage(PageNum pageNum, const void *data) { bool append = false; unsigned totalPages = getNumberOfPages(); if (pageNum > totalPages || pageNum < 0) { __trace(); std::cout << "Trying to write page " << pageNum << " but total page count is " << totalPages << std::endl; return ERR_LOCATE; } if (pageNum == totalPages) { append = true; } long curPos = pageNum * PAGE_SIZE; if (fseek(filePtr, curPos, SEEK_SET)) { __trace(); return ERR_LOCATE; } if (fwrite(data, sizeof(char), PAGE_SIZE, filePtr) != PAGE_SIZE) { __trace(); return ERR_WRITE; } if (append) { appendPageCounter++; // std::cout << fileName << " appendPageCounter " << appendPageCounter << std::endl; } else { writePageCounter++; // std::cout << fileName << " writePageCounter " << writePageCounter << std::endl; } return SUCCESSFUL; } /** * Append a page of data to the file. * Here we assume that data size will not exceed the size of a page. * * @param data * the data * @return status */ RC FileHandle::appendPage(const void *data) { RC rc = writePage(getNumberOfPages(), data); if (rc == SUCCESSFUL) { // __trace(); // std::cout << "--> appended a new page, pageCount now is " << getNumberOfPages() << std::endl; } else { __trace(); std::cout << "--> Cannot write data in a new page, rc = " << rc << " current pageCount " << getNumberOfPages() << std::endl; } return rc; } /** * Get the number of pages. * * @return # of pages */ unsigned FileHandle::getNumberOfPages() { // get the file size in pages(should be multiple of PAGE_SIZE) long fileSize = 0l; FILE *fp = getFilePointer(); if (fseek(fp, 0, SEEK_END)) { __trace(); perror("Cannot locate"); exit(ERR_LOCATE); } if ((fileSize = ftell(fp)) == -1) { __trace(); exit(ERR_LOCATE); } if (fileSize % PAGE_SIZE != 0) { // File size is not a multiple of PAGE_SIZE // Probably this file has been damaged exit(ERR_ALIGN); } return fileSize / PAGE_SIZE; } /** * @Depreciated * Set the number of pages. * * @param pages * # of pages */ void FileHandle::setNumberOfPages(unsigned pages) { // pageCount = pages; } /** * Get the file pointer in this file handle. * * @return file pointer */ FILE *FileHandle::getFilePointer() { return filePtr; } /** * Set the file pointer in this file handle. * * @param ptr * the file pointer */ void FileHandle::setFilePointer(FILE *ptr) { filePtr = ptr; } /** * Get the file name. * * @return file name */ char *FileHandle::getFileName() { return (char *) fileName.c_str(); } /** * Set the file name. * * @param file name */ void FileHandle::setFileName(const char *name) { fileName = std::string((char *)name); } /** * Collect statistics. */ RC FileHandle::collectCounterValues(unsigned &readPageCount, unsigned &writePageCount, unsigned &appendPageCount) { readPageCount = readPageCounter; writePageCount = writePageCounter; appendPageCount = appendPageCounter; // __trace(); // std::cout << "fileName: " << fileName << " rc " << readPageCounter << " wc " << writePageCounter << " ac " << appendPageCounter << std::endl; return SUCCESSFUL; }
22.177515
147
0.584578
moophis
2c70e4268ed74f579b99de7c886ecc0d7b0d8723
2,003
cpp
C++
Algorithms/0088.MergeSortedArray/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
Algorithms/0088.MergeSortedArray/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
Algorithms/0088.MergeSortedArray/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
#include <queue> #include <vector> #include "gtest/gtest.h" namespace { class Solution { public: void merge(std::vector<int>& nums1, int m, std::vector<int> const &nums2, int n) { const size_t size1 = m; const size_t size2 = n; std::queue<int> nums1Queue; size_t index2 = 0; // merge from nums1, nums2 and nums1Queue into [0, m - 1] range for (size_t index1 = 0; index1 < size1; ++index1) { if (index2 < size2 && nums2[index2] < nums1[index1] && (nums1Queue.empty() || nums2[index2] < nums1Queue.front())) { nums1Queue.push(nums1[index1]); nums1[index1] = nums2[index2++]; } else if (!nums1Queue.empty()) { nums1Queue.push(nums1[index1]); nums1[index1] = nums1Queue.front(); nums1Queue.pop(); } } // merge from nums2 and nums1Queue into [m, m + n - 1] range for (size_t index1 = m; index1 < size1 + size2; ++index1) { if (nums1Queue.empty() || (index2 < size2 && nums2[index2] < nums1Queue.front())) nums1[index1] = nums2[index2++]; else { nums1[index1] = nums1Queue.front(); nums1Queue.pop(); } } } }; } namespace { void checkMerge(std::vector<int> &&nums1, int m, std::vector<int> const &nums2, int n, std::vector<int> const &expectedResult) { std::vector<int> data(nums1); Solution solution; solution.merge(data, m, nums2, n); ASSERT_EQ(expectedResult, data); } } namespace MergeSortedArrayTask { TEST(MergeSortedArrayTaskTests, Examples) { checkMerge({1, 2, 3, 0, 0, 0}, 3, {2, 5, 6}, 3, {1, 2, 2, 3, 5, 6}); } TEST(MergeSortedArrayTaskTests, FromWrongAnswers) { checkMerge({1}, 1, {}, 0, {1}); checkMerge({2, 0}, 1, {1}, 1, {1, 2}); checkMerge({1, 2, 4, 5, 6, 0}, 5, {3}, 1, {1, 2, 3, 4, 5, 6}); } }
26.012987
126
0.529206
stdstring
2c7234a4936f1166cc531c5961dc59e848b59b0a
2,657
cc
C++
cartographer_ros/cartographer_ros/node_options.cc
athtest800/cartographer
566899786d21f11ceeb8b4d51d6a53eca73c4058
[ "Apache-2.0" ]
null
null
null
cartographer_ros/cartographer_ros/node_options.cc
athtest800/cartographer
566899786d21f11ceeb8b4d51d6a53eca73c4058
[ "Apache-2.0" ]
null
null
null
cartographer_ros/cartographer_ros/node_options.cc
athtest800/cartographer
566899786d21f11ceeb8b4d51d6a53eca73c4058
[ "Apache-2.0" ]
1
2019-07-11T01:12:15.000Z
2019-07-11T01:12:15.000Z
/* * Copyright 2016 The Cartographer 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. */ #include "cartographer_ros/node_options.h" #include "glog/logging.h" namespace cartographer_ros { NodeOptions CreateNodeOptions( ::cartographer::common::LuaParameterDictionary* const lua_parameter_dictionary) { NodeOptions options; options.map_builder_options = ::cartographer::mapping::CreateMapBuilderOptions( lua_parameter_dictionary->GetDictionary("map_builder").get()); options.map_frame = lua_parameter_dictionary->GetString("map_frame"); options.tracking_frame = lua_parameter_dictionary->GetString("tracking_frame"); options.published_frame = lua_parameter_dictionary->GetString("published_frame"); options.odom_frame = lua_parameter_dictionary->GetString("odom_frame"); options.provide_odom_frame = lua_parameter_dictionary->GetBool("provide_odom_frame"); options.use_odometry = lua_parameter_dictionary->GetBool("use_odometry"); options.use_laser_scan = lua_parameter_dictionary->GetBool("use_laser_scan"); options.use_multi_echo_laser_scan = lua_parameter_dictionary->GetBool("use_multi_echo_laser_scan"); options.num_point_clouds = lua_parameter_dictionary->GetNonNegativeInt("num_point_clouds"); options.lookup_transform_timeout_sec = lua_parameter_dictionary->GetDouble("lookup_transform_timeout_sec"); options.submap_publish_period_sec = lua_parameter_dictionary->GetDouble("submap_publish_period_sec"); options.pose_publish_period_sec = lua_parameter_dictionary->GetDouble("pose_publish_period_sec"); CHECK_EQ(options.use_laser_scan + options.use_multi_echo_laser_scan + (options.num_point_clouds > 0), 1) << "Configuration error: 'use_laser_scan', " "'use_multi_echo_laser_scan' and 'num_point_clouds' are " "mutually exclusive, but one is required."; if (options.map_builder_options.use_trajectory_builder_2d()) { // Using point clouds is only supported in 3D. CHECK_EQ(options.num_point_clouds, 0); } return options; } } // namespace cartographer_ros
40.257576
79
0.75988
athtest800
2c73d6ed1bffe930c21c219d4bb3ac91bc8dbbd9
905
cpp
C++
006/main.cpp
Ponz-Tofu-N/ModernCppChallengePractice
c2003fc180fc28448a3ff5b3e0f0c2788154af8c
[ "MIT" ]
null
null
null
006/main.cpp
Ponz-Tofu-N/ModernCppChallengePractice
c2003fc180fc28448a3ff5b3e0f0c2788154af8c
[ "MIT" ]
null
null
null
006/main.cpp
Ponz-Tofu-N/ModernCppChallengePractice
c2003fc180fc28448a3ff5b3e0f0c2788154af8c
[ "MIT" ]
null
null
null
// 6. Abundant Numbers // Usage: Enter max number #include <iostream> #include <cmath> #include <string> int main(int argc, char const *argv[]) { std::cout << "input max number: "; unsigned int max; std::cin >> max; /*pick a num*/ /*sum divisors*/ /*print if abundant num and its abundance*/ for (size_t i = max; i > 1; i--) { unsigned int sum = 0; const unsigned int limit = static_cast<unsigned int>(std::sqrt(i)); for (size_t j = 1; j <= limit; j++) { if(i % j == 0){ sum += j; } } if (sum > i) { std::cout << "AbundantNum: " << i << " " << "Abundant: " << sum - i * 2 << "\n"; } } return 0; }
22.073171
76
0.390055
Ponz-Tofu-N
2c74542b046b20d23af5c42548f57bc40a88334f
5,842
cc
C++
Engine/foundation/io/memoryreader.cc
BikkyS/DreamEngine
47da4e22c65188c72f44591f6a96505d8ba5f5f3
[ "MIT" ]
26
2015-01-15T12:57:40.000Z
2022-02-16T10:07:12.000Z
Engine/foundation/io/memoryreader.cc
BikkyS/DreamEngine
47da4e22c65188c72f44591f6a96505d8ba5f5f3
[ "MIT" ]
null
null
null
Engine/foundation/io/memoryreader.cc
BikkyS/DreamEngine
47da4e22c65188c72f44591f6a96505d8ba5f5f3
[ "MIT" ]
17
2015-02-18T07:51:31.000Z
2020-06-01T01:10:12.000Z
/**************************************************************************** Copyright (c) 2006, Radon Labs GmbH Copyright (c) 2011-2013,WebJet Business Division,CYOU http://www.genesis-3d.com.cn 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 "stdneb.h" #include "io/memoryreader.h" #include "math/scalar.h" namespace IO { __ImplementClass(IO::MemoryReader, 'MMRD', IO::Stream); //------------------------------------------------------------------------------ /** */ MemoryReader::MemoryReader() : capacity(0), size(0), position(0), buffer(NULL) { // empty } //------------------------------------------------------------------------------ /** */ MemoryReader::~MemoryReader() { // close the stream if still open if (this->IsOpen()) { this->Close(); } // release memory buffer if allocated if ( NULL != this->buffer) this->buffer = NULL; } //------------------------------------------------------------------------------ Stream::Size MemoryReader::GetSize() const { return this->size; } //------------------------------------------------------------------------------ Stream::Position MemoryReader::GetPosition() const { return this->position; } //------------------------------------------------------------------------------ bool MemoryReader::Open() { n_assert(!this->IsOpen()); // nothing to do here, allocation happens in the first Write() call // if necessary, all we do is reset the read/write position to the // beginning of the stream if (Stream::Open()) { this->position = 0; return true; } return false; } //------------------------------------------------------------------------------ /** Close the stream. The contents of the stream will remain intact until destruction of the object, so that the same data may be accessed or modified during a later session. */ void MemoryReader::Close() { n_assert(this->IsOpen()); Stream::Close(); } //------------------------------------------------------------------------------ /** */ void MemoryReader::Write(const void* ptr, Size numBytes) { n_assert(this->IsOpen()); n_assert(ReadWriteAccess == this->accessMode); n_assert((this->position >= 0) && (this->position <= this->size)); buffer = (unsigned char*)ptr; size = numBytes; capacity = numBytes; this->position += numBytes; if (this->position > this->size) { this->size = this->position; } } //------------------------------------------------------------------------------ /** */ Stream::Size MemoryReader::Read(void* ptr, Size numBytes) { n_assert(this->IsOpen()); n_assert((ReadWriteAccess == this->accessMode)) n_assert((this->position >= 0) && (this->position <= this->size)); // check if end-of-stream is near Size readBytes = numBytes <= this->size - this->position ? numBytes : this->size - this->position; n_assert((this->position + readBytes) <= this->size); if (readBytes > 0) { Memory::Copy(this->buffer + this->position, ptr, readBytes); this->position += readBytes; } return readBytes; } //------------------------------------------------------------------------------ /** */ void MemoryReader::Seek(Offset offset, SeekOrigin origin) { n_assert(this->IsOpen()); n_assert(!this->IsMapped()); n_assert((this->position >= 0) && (this->position <= this->size)); switch (origin) { case Begin: this->position = offset; break; case Current: this->position += offset; break; case End: this->position = this->size + offset; break; } // make sure read/write position doesn't become invalid this->position = Math::n_iclamp(this->position, 0, this->size); } //------------------------------------------------------------------------------ /** */ bool MemoryReader::Eof() const { n_assert(this->IsOpen()); n_assert((this->position >= 0) && (this->position <= this->size)); return (this->position == this->size); } //------------------------------------------------------------------------------ /** */ bool MemoryReader::HasRoom(Size numBytes) const { return ((this->position + numBytes) <= this->capacity); } //------------------------------------------------------------------------------ /** Get a direct pointer to the raw data. This is a convenience method and only works for memory streams. NOTE: writing new data to the stream may/will result in an invalid pointer, don't keep the returned pointer around between writes! */ void* MemoryReader::GetRawPointer() const { n_assert( NULL != this->buffer ); return this->buffer; } } // namespace IO
28.778325
102
0.534235
BikkyS
2c77a65f0d36f156d472f93c2e9c568c65111e61
6,757
tcc
C++
radiomicsfeatureextractionpipeline/conquest/src/dgate/dicomlib/array.tcc
Maastro-CDS-Imaging-Group/SQLite4Radiomics
e3a7afc181eec0fe04c18da00edc3772064e6758
[ "Apache-2.0" ]
null
null
null
radiomicsfeatureextractionpipeline/conquest/src/dgate/dicomlib/array.tcc
Maastro-CDS-Imaging-Group/SQLite4Radiomics
e3a7afc181eec0fe04c18da00edc3772064e6758
[ "Apache-2.0" ]
6
2021-06-09T19:39:27.000Z
2021-09-30T16:41:40.000Z
radiomicsfeatureextractionpipeline/conquest/src/dgate/dicomlib/array.tcc
Maastro-CDS-Imaging-Group/SQLite4Radiomics
e3a7afc181eec0fe04c18da00edc3772064e6758
[ "Apache-2.0" ]
null
null
null
/* 20050125 ljz Added 'ReplaceAt()' to the 'Array' class 20100619 bcb Fix gcc4 warnings and improve speed. 20130429 lsp Corrected (unused) printf format string 20130812 mvh Removed non-thread safe caching of last value Does not seem to affect speed, throughput remains at 320 MB/s receive with 3 senders and receivers in same dgate on 8-core machine 20131016 mvh Merged */ /**************************************************************************** Copyright (C) 1995, University of California, Davis THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH THE USER. Copyright of the software and supporting documentation is owned by the University of California, and free access is hereby granted as a license to use this software, copy this software and prepare derivative works based upon this software. However, any distribution of this software source code or supporting documentation or derivative works (source code and supporting documentation) must include this copyright notice. ****************************************************************************/ /*************************************************************************** * * University of California, Davis * UCDMC DICOM Network Transport Libraries * Version 0.1 Beta * * Technical Contact: mhoskin@ucdavis.edu * ***************************************************************************/ /* template <class DATATYPE> Array<DATATYPE> :: Array () { ArraySize = 0; first = NULL; last = NULL; ClearType = 1; } */ template <class DATATYPE> Array<DATATYPE> :: Array (UINT CT) #ifdef __GNUC__ //Faster with member initialization. :first(NULL), last(NULL), //LastAccess(NULL), //LastAccessNumber(0), ArraySize(0), ClearType(CT) {} #else { ArraySize = 0; first = NULL; last = NULL; //LastAccess = NULL; //LastAccessNumber = 0; ClearType = CT; } #endif template <class DATATYPE> Array<DATATYPE> :: ~Array() { if(ClearType == 1) { while(ArraySize) RemoveAt(0); } } template <class DATATYPE> DATATYPE & Array<DATATYPE> :: Add(DATATYPE &Value) { // record current end-of-chain element DataLink<DATATYPE> *dl = last; // chain on new element at tail of chain last = new DataLink<DATATYPE>; last->Data = Value; // set new element's backward pointer to point to former // end-of-chain element last->prev = dl; // set former end-of-chain's next pointer to point to new element if(dl) { dl->next = last; } else { // there was previously no "last" element so the one just // allocated must be the first first = last; } ++ArraySize; return ( Value ); } template <class DATATYPE> DATATYPE & Array<DATATYPE> :: Get(unsigned int Index) { DataLink<DATATYPE> *dl; unsigned int rIndex = Index; if ( Index >= ArraySize ) { //fprintf(stderr, "Returning NULL Data\n"); //return ( NullData ); dl = NULL; return ( (DATATYPE &) *dl ); // Invoke a seg fault } /*if ( LastAccess ) { if ((LastAccessNumber + 1) == Index ) { LastAccess = LastAccess->next; ++LastAccessNumber; return ( LastAccess->Data ); } } */ // locate requested element by following pointer chain // decide which is faster -- scan from head or scan from tail if(Index < ArraySize / 2) { // requested element closer to head -- scan forward dl = first; ++Index; while(--Index > 0) { dl = dl->next; } } else { // requested element closer to tail -- scan backwards dl = last; Index = (ArraySize - Index); while(--Index > 0) { dl = dl->prev; } } //LastAccess = dl; //LastAccessNumber = rIndex; return ( dl->Data ); } template <class DATATYPE> DATATYPE & Array<DATATYPE> :: ReplaceAt(DATATYPE &Value, unsigned int Index) { DataLink<DATATYPE> *dl; unsigned int rIndex = Index; if ( Index >= ArraySize ) { //fprintf(stderr, "Returning NULL Data\n"); //return ( NullData ); dl = NULL; return ( (DATATYPE &) *dl ); // Invoke a seg fault } /*if ( LastAccess ) { if ((LastAccessNumber + 1) == Index ) { LastAccess = LastAccess->next; ++LastAccessNumber; LastAccess->Data = Value; return ( LastAccess->Data ); } } */ // locate requested element by following pointer chain // decide which is faster -- scan from head or scan from tail if(Index < ArraySize / 2) { // requested element closer to head -- scan forward dl = first; ++Index; while(--Index > 0) { dl = dl->next; } } else { // requested element closer to tail -- scan backwards dl = last; Index = (ArraySize - Index); while(--Index > 0) { dl = dl->prev; } } //LastAccess = dl; //LastAccessNumber = rIndex; dl->Data = Value; return ( dl->Data ); } template <class DATATYPE> BOOL Array<DATATYPE> :: RemoveAt(unsigned int Index) { DataLink<DATATYPE> *dl; //LastAccess = NULL; //LastAccessNumber = 0; if( Index >= ArraySize ) { //fprintf(stderr, "Attempting to remove non-existance node\n"); //return ( NullData ); return( FALSE ); } // follow pointer chain from head or tail to requested element // depending upon which chain is shorter if(Index < ArraySize / 2) { // element closer to head => follow chain forward from first dl = first; ++Index; while(--Index > 0) { dl = dl->next; } } else { // element closer to tail => follow chain backward from last dl = last; Index = (ArraySize - Index); while(--Index > 0) { dl = dl->prev; } } // relink chain around element to be deleted // fix first or last pointer if element to delete is first or last if(dl->prev) dl->prev->next = dl->next; else first = dl->next; if(dl->next) dl->next->prev = dl->prev; else last = dl->prev; delete dl; --ArraySize; return ( TRUE ); } /**************************************************************** * Test Functions * * ****************************************************************/ # ifdef BUILD_TEST_UNITS int testfunc() { unsigned int Index; Array<int> AInt; Index = 0; while(Index < 10) { AInt.Add(Index * 2); ++Index; } Index = 0; while(Index < 10) { printf("Val: %d : %d\n", Index, AInt.RemoveAt(0)); ++Index; } return ( 0 ); } int main() { testfunc(); fprintf(stderr, "Display Should be like 'Val: x: 2*x' with x[0..9]\n"); } # endif
20.537994
77
0.597159
Maastro-CDS-Imaging-Group
2c7b28cd370a850ec77649e471db05f1398aaa2e
138
hpp
C++
source/framework/algorithm/include/lue/framework/algorithm/definition/greater_than.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/definition/greater_than.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/definition/greater_than.hpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
1
2020-03-11T09:49:41.000Z
2020-03-11T09:49:41.000Z
#pragma once #include "lue/framework/algorithm/greater_than.hpp" #include "lue/framework/algorithm/definition/binary_local_operation.hpp"
34.5
72
0.84058
computationalgeography
2c7cfc0c08dd10e6631562000626193fc83d9992
3,308
cpp
C++
samples/win32/mfc/CanalDiagnostic/DocumentProperties.cpp
grodansparadis/vscp-samples
43becaafe267de0b772e99d9608e8ec4eb8343c8
[ "MIT" ]
2
2020-12-01T18:54:20.000Z
2022-01-24T20:18:33.000Z
samples/win32/mfc/CanalDiagnostic/DocumentProperties.cpp
grodansparadis/vscp-samples
43becaafe267de0b772e99d9608e8ec4eb8343c8
[ "MIT" ]
null
null
null
samples/win32/mfc/CanalDiagnostic/DocumentProperties.cpp
grodansparadis/vscp-samples
43becaafe267de0b772e99d9608e8ec4eb8343c8
[ "MIT" ]
null
null
null
// DocumentProperties.cpp : implementation file // // 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. // canald.cpp // // This file is part of the CANAL (http://www.vscp.org) // // Copyright (C) 2000-2010 Ake Hedman, eurosource, <akhe@eurosource.se> // // This file 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 file see the file COPYING. If not, write to // the Free Software Foundation, 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. // // $RCSfile: DocumentProperties.cpp,v $ // $Date: 2005/01/05 12:16:20 $ // $Author: akhe $ // $Revision: 1.2 $ #include "stdafx.h" #include "CanalDiagnostic.h" #include "DocumentProperties.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // DocumentProperties dialog CDocumentProperties::CDocumentProperties(CWnd* pParent /*=NULL*/) : CDialog(CDocumentProperties::IDD, pParent) { m_fileName = _T(""); //{{AFX_DATA_INIT(CDocumentProperties) m_strName = _T(""); m_strPath = _T(""); m_strDeviceString = _T(""); m_strDeviceFlags = _T(""); m_strInBufSize = _T(""); m_strOutBufSize = _T(""); //}}AFX_DATA_INIT } void CDocumentProperties::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDocumentProperties) DDX_Text(pDX, IDC_EDIT_NAME, m_strName); DDX_Text(pDX, IDC_EDIT_PATH, m_strPath); DDX_Text(pDX, IDC_EDIT_DEVICE_STRING, m_strDeviceString); DDX_Text(pDX, IDC_EDIT_DEVICE_FLAGS, m_strDeviceFlags); DDX_Text(pDX, IDC_EDIT_INBUF_SIZE, m_strInBufSize); DDX_Text(pDX, IDC_EDIT_OUTBUF_SIZE, m_strOutBufSize); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CDocumentProperties, CDialog) //{{AFX_MSG_MAP(CDocumentProperties) ON_BN_CLICKED(IDC_BUTTON_BROWSE, OnButtonBrowse) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDocumentProperties message handlers void CDocumentProperties::OnButtonBrowse() { CFileDialog dlg( true, NULL, NULL, OFN_EXPLORER | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "driver (*.dll) | *.dll|All Files (*.*)|*.*||" ); if ( IDOK == dlg.DoModal() ) { m_strPath = dlg.GetPathName(); if ( 0 == m_strName.GetLength() ) { m_fileName = dlg.GetFileTitle (); m_strName = dlg.GetFileTitle (); } UpdateData( false ); } } BOOL CDocumentProperties::OnInitDialog() { CDialog::OnInitDialog(); UpdateData( false ); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CDocumentProperties::OnOK() { UpdateData( true ); CDialog::OnOK(); }
28.273504
78
0.655985
grodansparadis
2c7eccb92b8799dde7d139354e501a01f7145075
13,600
cc
C++
src/common/time.cc
sergeyfilip/objectstore
e2d0c86134c46c77fb143f7198d13fab7f5b1ea5
[ "MIT" ]
null
null
null
src/common/time.cc
sergeyfilip/objectstore
e2d0c86134c46c77fb143f7198d13fab7f5b1ea5
[ "MIT" ]
null
null
null
src/common/time.cc
sergeyfilip/objectstore
e2d0c86134c46c77fb143f7198d13fab7f5b1ea5
[ "MIT" ]
null
null
null
// //! \file common/time.cc // //! Implementation of our time routines // // $Id: time.cc,v 1.17 2013/05/23 08:54:57 joe Exp $ // #include "time.hh" #include "error.hh" #include "string.hh" #include <vector> #include <iomanip> #include <istream> #include <ostream> #include <math.h> #include <time.h> #include <string.h> #if defined(__unix__) || defined(__APPLE__) # include <sys/time.h> #endif Time Time::now() { #if defined(__unix__) || defined(__APPLE__) timeval tv; if (gettimeofday(&tv,0)) throw syserror("gettimeofday", "retrieval of now"); return Time(tv.tv_sec,tv.tv_usec * 1000); #endif #if defined(_WIN32) SYSTEMTIME st; GetSystemTime(&st); FILETIME ft; if (SystemTimeToFileTime(&st,&ft) == 0) { std::cerr << "(TIME) Error getting system time " << std::endl; std::cerr << "(TIME) This may cause inaccurate measurements " << std::endl; }; /* tf holds a 64 bit time in it's 2 fields the number represents 100-nanosecs. since jan. 1 1601 */ uint64_t sec,nsec; uint64_t offset = uint64_t(10000000) * ((1970 - 1601) * 365 + 89) * 24 * 60 * 60; uint64_t file_time = (uint64_t(ft.dwHighDateTime) << 32) + ft.dwLowDateTime; file_time -= offset; sec = file_time / 10000000; nsec = (file_time % 10000000) * 100; return Time(sec, nsec); #endif } #ifdef _WIN32 Time::Time(const FILETIME &ft) : tim(0,0) { uint64_t offset = uint64_t(10000000) * ((1970 - 1601) * 365 + 89) * 24 * 60 * 60; uint64_t file_time = (uint64_t(ft.dwHighDateTime) << 32) + ft.dwLowDateTime; file_time -= offset; tim.sec = file_time / 10000000; tim.nsec = (file_time % 10000000) * 100; } FILETIME Time::toFileTime() const { FILETIME file_time; uint64_t offset = uint64_t(10000000) * ((1970 - 1601) * 365 + 89) * 24 * 60 * 60; uint64_t nano_secs = uint64_t(tim.sec) * 10000000 + uint64_t(tim.nsec) + offset; file_time.dwLowDateTime = DWORD(nano_secs); file_time.dwHighDateTime = nano_secs >> 32; return file_time; } #endif #ifdef __unix__ struct timespec Time::toTimespec() const { struct timespec ret; ret.tv_sec = tim.sec; ret.tv_nsec = tim.nsec; return ret; } #endif double Time::to_double() const { return tim.sec + tim.nsec / 1E9; } // // Utility stuff for the ISO8601 parser // namespace { // Reads exactly d characters from stream and parses unsigned // integer unsigned readDigits(std::istream &i, size_t d) { std::vector<char> buf(d); i.read(&buf[0], d); if (i.eof()) throw error("ISO8601: Premature end of data while reading digits"); // Fine, now parse as integer return string2Any<unsigned>(std::string(buf.begin(), buf.end())); } // Reads a single character and returns it char getChar(std::istream &i) { if (i.eof()) throw error("ISO8601: End of stream before get"); char tmp; i.get(tmp); if (i.gcount() != 1) throw error("ISO8601: Premature end of data while getting character"); return tmp; } // Reads a character and sees if it matches the test character. If // it does, the function returns true. If it does not, it puts back // the character onto the stream and returns false. bool testChar(std::istream &i, char test) { char t = getChar(i); if (t == test) return true; i.putback(t); return false; } // Reads a single character and expects it to match given character void skipKnown(std::istream &i, char known) { char tmp; i.get(tmp); if (i.gcount() != 1) throw error("ISO8601: Premature end of data while skipping character"); if (tmp != known) throw error("ISO8601: Unexpected character while parsing"); } // Reads a ISO8601 possibly-fractional number from the stream double readFractional(std::istream &i) { // Read digits and accept both '.' and ',' as fraction bool gotsome = false; double res = 0; size_t divider = 0; while (true) { char c = getChar(i); if (c >= '0' && c <= '9') { if (divider) { res += (c - '0') / double(divider); divider *= 10; } else { res *= 10; res += c - '0'; } gotsome = true; continue; } if (!divider && (c == '.' || c == ',')) { divider = 10; gotsome = true; continue; } // Ok, not a digit and not (first) fractional i.putback(c); break; } if (!gotsome) throw error("ISO8601: Not a fractional"); return res; } } #if defined(__sun__) // Solaris doesn't have the GNU specific timegm function, so we // implement it here using mktime() and gmtime(). Would be nice to // have it static, but mktime_utc_test uses this function as well. time_t timegm(struct tm* t) { time_t tl, tb; struct tm* tg; tl = mktime(t); if (tl == -1) return -1; tg = gmtime(&tl); if (!tg) return -1; tb = mktime(tg); if (tb == -1) return -1; return (tl - (tb - tl)); } #endif std::istream &operator>>(std::istream &i, Time &o) { struct tm t; memset(&t, 0, sizeof t); // YYYY-MM-DD t.tm_year = readDigits(i, 4) - 1900; skipKnown(i, '-'); t.tm_mon = readDigits(i, 2) - 1; skipKnown(i, '-'); t.tm_mday = readDigits(i, 2); // T or space { char sep = getChar(i); if (sep != 'T' && sep != ' ') throw error("Unexpected separator between date and time"); } // hh:mm:ss t.tm_hour = readDigits(i, 2); skipKnown(i, ':'); t.tm_min = readDigits(i, 2); skipKnown(i, ':'); t.tm_sec = readDigits(i, 2); // Optionally we have fractional seconds - ISO 8601 specifies that // both ',' and '.' can be used to designate the fraction char trailer = getChar(i); do { if (trailer != '.' && trailer != ',') break; // Good, we have fractional seconds... Fetch them and throw them // away do { trailer = getChar(i); } while (trailer >= '0' && trailer <= '9'); } while (false); // Assume Zulu time - either 'Z' or '+00' do { if (trailer == 'Z') break; if (trailer != '+') throw error("Expected Z or +00"); skipKnown(i, '0'); skipKnown(i, '0'); } while (false); // Just peek at the next character - this has the effect of // setting eof if we are really at the eof. i.peek(); // Fine, now convert #if defined (__unix__) || defined(__APPLE__) o = Time(timegm(&t)); #endif #if defined(_WIN32) o = Time(_mkgmtime(&t)); #endif return i; } std::ostream &operator<<(std::ostream &s, const Time &ts) { struct tm t; #if defined(__unix__) || defined(__APPLE__) const time_t ut(ts.to_timet()); if (!gmtime_r(&ut, &t)) throw error("Cannot output time"); #endif #if defined(_WIN32) const time_t in(ts.to_timet()); if (gmtime_s(&t, &in)) throw error("Cannot output time"); #endif s << std::setw(4) << std::setfill('0') << (t.tm_year + 1900) << "-" << std::setw(2) << std::setfill('0') << (t.tm_mon + 1) << "-" << std::setw(2) << std::setfill('0') << t.tm_mday << "T" << std::setw(2) << std::setfill('0') << t.tm_hour << ":" << std::setw(2) << std::setfill('0') << t.tm_min << ":" << std::setw(2) << std::setfill('0') << t.tm_sec << "Z"; return s; } const DiffTime Time::operator-(const Time& p2 ) const { // This calculation will never overflow, as Time contains only // positive values, whereas DiffTime allows the full signed scale. time_internal::time_rec res(tim); res.sec -= p2.tim.sec; res.nsec -= p2.tim.nsec; if (res.nsec < 0) { res.sec--; res.nsec += 1000000000; } if (res.nsec < 0) throw error("Time difference subtraction gave negative nsec"); return res; } const Time Time::operator-(const DiffTime& p2 ) const { return Time(*this) -= p2.tim; } const Time Time::operator+(const DiffTime& p2 ) const { return Time(*this) += p2.tim; } Time& Time::operator+=(const DiffTime& p2 ) { time_internal::time_rec res(tim); res.sec += p2.tim.sec; res.nsec += p2.tim.nsec; if (res.nsec >= 1000000000) { res.sec++; res.nsec -= 1000000000; } if (res.nsec >= 1000000000) throw error("Addition between non-normalized time and time difference"); // Check for overflows if (p2.tim.sec >= 0) { // Adding a positive value, res must have increased if (res.sec < tim.sec) { // sec has wrapped, clamp at END_OF_TIME *this = END_OF_TIME; } } else { // Adding a negative value, res must have decreased if (res.sec > tim.sec) { // sec has wrapped, clamp at BEGINNING_OF_TIME *this = BEGINNING_OF_TIME; } } tim = res; return *this; } const Time Time::BEGINNING_OF_TIME(0, 0); const Time Time::END_OF_TIME(0x7FFFFFFFFFFFFFFFLL, 0); // // Implementation of class DiffTime // DiffTime::DiffTime(const double& dt) : tim(int64_t(floor(dt)), int64_t((dt - floor(dt)) * 1E9)) { } DiffTime::DiffTime(time_t dt) : tim(dt, 0) { } DiffTime::DiffTime(int64_t sec, int64_t nsec) : tim(sec, nsec) { // If too many microseconds specified, add whole seconds to sec // and let usec contain the microseconds. if (tim.nsec >= 1000000000) { const lldiv_t res = lldiv(tim.nsec, 1000000000); tim.sec += res.quot; tim.nsec = res.rem; } if (tim.nsec < 0) throw error("Cannot normalize negative nanoseconds"); } double DiffTime::to_double() const { return tim.sec + tim.nsec / 1E9; } void DiffTime::zeroIfNegative() { if (*this < DiffTime(0,0)) *this = DiffTime(0,0); } std::string DiffTime::toFormattedString() const { std::ostringstream out; if (int64_t days = tim.sec / 60 / 60 / 24) out << days << " days "; if (int64_t hours = tim.sec / 60 / 60 % 24) out << hours << " hours "; if (int64_t minutes = tim.sec / 60 % 60) out << minutes << " minutes "; if (int64_t seconds = tim.sec % 60) out << seconds << " seconds "; return out.str(); } const DiffTime DiffTime::operator-() const { if (tim.nsec) { return DiffTime(-tim.sec - 1, 1000000000 - tim.nsec); } else { return DiffTime(-tim.sec, 0); } } const DiffTime DiffTime::operator-(const DiffTime& p2 ) const { return DiffTime(*this) -= p2.tim; } const DiffTime DiffTime::operator+(const DiffTime& p2 ) const { return DiffTime(*this) += p2.tim; } DiffTime& DiffTime::operator-=(const DiffTime& p2 ) { return *this += -p2; } DiffTime& DiffTime::operator+=(const DiffTime& p2 ) { time_internal::time_rec res(tim); res.sec += p2.tim.sec; res.nsec += p2.tim.nsec; if (res.nsec >= 1000000000) { res.sec++; res.nsec -= 1000000000; } if (res.nsec >= 1000000000) throw error("Sum of non-normalized difftimes - nsec too big"); // Check for overflows if (p2.tim.sec >= 0) { // Adding a positive value, res must have increased if (res.sec < tim.sec) { // sec has wrapped, clamp at END_OF_TIME *this = ENDLESS; } } else { // Adding a negative value, res must have decreased if (res.sec > tim.sec) { // sec has wrapped, clamp at BEGINNING_OF_TIME *this = -ENDLESS; } } tim = res; return *this; } DiffTime DiffTime::operator*(double scale) const { return DiffTime(this->to_double() * scale); } bool DiffTime::operator <(const DiffTime& p2) const { return to_double() < p2.to_double(); } bool DiffTime::operator >(const DiffTime& p2) const { return p2 < *this; } bool DiffTime::operator <=(const DiffTime& p2) const { return !(p2 < *this); } bool DiffTime::operator >=(const DiffTime& p2) const { return !(*this < p2); } bool DiffTime::operator==(const DiffTime& p2) const { return tim.sec == p2.tim.sec && tim.nsec == p2.tim.nsec; } DiffTime DiffTime::iso(const std::string &iso) { std::istringstream i(iso); DiffTime tmp; i >> tmp; return tmp; } const DiffTime DiffTime::SECOND(1, 0); const DiffTime DiffTime::MSEC(0, 1000000); const DiffTime DiffTime::USEC(0, 1000); const DiffTime DiffTime::NSEC(0, 1); const DiffTime DiffTime::ENDLESS(0x7FFFFFFFFFFFFFFFLL, 0); std::istream &operator>>(std::istream &i, DiffTime &o) { double secs = 0; bool gotsome = false; if (getChar(i) != 'P') throw error("Not a ISO8601 period designator"); // We may run into a 'T' - but until we do, we parse years, months // and days. while (true) { // Read some number double n; try { n = readFractional(i); } catch (error &) { break; } gotsome = true; // Get the designator switch (char c = getChar(i)) { case 'Y': secs += 365 * 24 * 3600 * n; break; case 'M': secs += 30 * 24 * 3600 * n; break; case 'D': secs += 24 * 3600 * n; break; default: throw error("Unexpected designator '" + std::string(1, c) + "' in left side of ISO 8601 period"); } } if (testChar(i, 'T')) { // Fine, we got our T (or we failed reading the next // fractional). Now read hours, minutes and seconds. while (true) { // Read some number double n; try { n = readFractional(i); } catch (error &) { break; } gotsome = true; // Get the designator switch (char c = getChar(i)) { case 'H': secs += 60 * 60 * n; break; case 'M': secs += 60 * n; break; case 'S': secs += n; break; default: throw error("Unexpected designator '" + std::string(1, c) + "' in right side of ISO 8601 period"); } } } if (!gotsome) throw error("No ISO8601 period data after period designator"); o = DiffTime(secs); return i; } std::ostream &operator<<(std::ostream &s, const DiffTime &ts) { s << "PT" << ts.to_double() << "S"; return s; }
23.776224
82
0.606691
sergeyfilip
2c811f7a86797f15c9801e7149dcc4e063114d22
7,276
cpp
C++
fkie_iop_pantilt_specification_service/src/PantiltCfgReader.cpp
fkie/iop_jaus_manipulator
d147d14a212fa57f52349c5ec937817591ef7d9c
[ "BSD-3-Clause" ]
null
null
null
fkie_iop_pantilt_specification_service/src/PantiltCfgReader.cpp
fkie/iop_jaus_manipulator
d147d14a212fa57f52349c5ec937817591ef7d9c
[ "BSD-3-Clause" ]
null
null
null
fkie_iop_pantilt_specification_service/src/PantiltCfgReader.cpp
fkie/iop_jaus_manipulator
d147d14a212fa57f52349c5ec937817591ef7d9c
[ "BSD-3-Clause" ]
null
null
null
/** ROS/IOP Bridge Copyright (c) 2017 Fraunhofer This program is dual licensed; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation, or enter into a proprietary license agreement with the copyright holder. 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; or you can read the full license at <http://www.gnu.de/documents/gpl-2.0.html> */ /** \author Alexander Tiderko */ #include <math.h> #include <ros/console.h> #include <tf/transform_datatypes.h> #include <fkie_iop_component/iop_config.h> #include "fkie_iop_pantilt_specification_service/PantiltCfgReader.h" using namespace urn_jaus_jss_manipulator_PanTiltSpecificationService; using namespace iop; PantiltCfgReader::PantiltCfgReader() { p_valid_joint1_profile = false; p_valid_joint2_profile = false; p_joint1_limits.has_acceleration_limits = false; p_joint1_limits.has_position_limits = false; p_joint1_limits.has_velocity_limits = false; p_joint2_limits.has_acceleration_limits = false; p_joint2_limits.has_position_limits = false; p_joint2_limits.has_velocity_limits = false; } PantiltCfgReader::~PantiltCfgReader() { } void PantiltCfgReader::readRosConfiguration() { /** <!-- the position of the pantilt on the robot [x y z roll pitch yaw] --> <param name="origin" type="str" value="0 0 0 0 0 0" /> <!-- the ROS name of the first joint and movement specifications [name (optional: minValue maxValue maxSpeed)] --> <param name="joint1" type="str" value="joint_name -3.14 3.14 1.57" /> <!-- the ROS name of the second joint and movement specifications [name (optional: minValue maxValue maxSpeed)] --> <param name="joint2" type="str" value="joint_name -3.14 3.14 1.57" /> **/ ReportPanTiltSpecificationsRec pspec; iop::Config cfg("~PanTiltSpecificationService"); std::string origin = "0 0 0 0 0 0"; cfg.param("origin", origin, origin, true, false); double x, y, z, roll, pitch, yaw = 0; int scan_result = std::sscanf(origin.c_str(), "%lf %lf %lf %lf %lf %lf", &x, &y, &z, &roll, &pitch, &yaw); if (scan_result == 6) { pspec.setPanTiltCoordinateSysX(x); pspec.setPanTiltCoordinateSysY(y); pspec.setPanTiltCoordinateSysZ(z); tf::Quaternion q = tf::createQuaternionFromRPY(roll, pitch, yaw); pspec.setAComponentOfUnitQuaternionQ(q.x()); pspec.setBComponentOfUnitQuaternionQ(q.y()); pspec.setCComponentOfUnitQuaternionQ(q.z()); pspec.setDComponentOfUnitQuaternionQ(q.w()); } else { ROS_WARN("invalid format in ~origin[str]: %s, should be x y z roll pitch yaw", origin.c_str()); } std::string joint1 = "pan_joint_name"; cfg.param("joint1", joint1, joint1, true, false); char joint_name[256]; double min_value = -3.14; double max_value = 3.14; double max_speed = 1.57; scan_result = std::sscanf(joint1.c_str(), "%s %lf %lf %lf", joint_name, &min_value, &max_value, &max_speed); if (scan_result == 4) { p_joint1 = std::string(joint_name); pspec.setJoint1MinValue(min_value); pspec.setJoint1MaxValue(max_value); pspec.setJoint1MaxSpeed(max_speed); } else if (scan_result == 1) { p_joint1 = std::string(joint_name); } else { throw std::runtime_error(std::string("invalid format in ~joint1[str]. Should be joint_name min_value max_value max_speed, got: ") + joint1.c_str()); } p_joint1_limits.joint_name = p_joint1; p_joint1_limits.has_position_limits = true; p_joint1_limits.max_position = max_value; p_joint1_limits.min_position = min_value; p_joint1_limits.has_velocity_limits = true; p_joint1_limits.max_velocity = max_speed; p_valid_joint1_profile = true; std::string joint2 = "tilt_joint_name"; cfg.param("joint2", joint2, joint2, true, false); min_value = -3.14; max_value = 3.14; max_speed = 1.57; scan_result = std::sscanf(joint2.c_str(), "%s %lf %lf %lf", joint_name, &min_value, &max_value, &max_speed); if (scan_result == 4) { p_joint2 = std::string(joint_name); pspec.setJoint2MinValue(min_value); pspec.setJoint2MaxValue(max_value); pspec.setJoint2MaxSpeed(max_speed); } else if (scan_result == 1) { p_joint2 = std::string(joint_name); } else { throw std::runtime_error(std::string("invalid format in ~joint2[str]. Should be joint_name min_value max_value max_speed, got: ") + joint2.c_str()); } p_joint2_limits.joint_name = p_joint2; p_joint2_limits.has_position_limits = true; p_joint2_limits.max_position = max_value; p_joint2_limits.min_position = min_value; p_joint2_limits.has_velocity_limits = true; p_joint2_limits.max_velocity = max_speed; p_valid_joint2_profile = true; p_pantilt_specification = pspec; p_jaus_msg.getBody()->setReportPanTiltSpecificationsRec(pspec); } std::pair<std::string, std::string> PantiltCfgReader::getJointNames() { return std::make_pair(p_joint1, p_joint2); } std::pair<moveit_msgs::JointLimits, moveit_msgs::JointLimits> PantiltCfgReader::getLimits() { return std::make_pair(p_joint1_limits, p_joint2_limits); } bool PantiltCfgReader::is_profile_valid() { return (p_valid_joint1_profile && p_valid_joint2_profile); } ReportPanTiltSpecifications& PantiltCfgReader::getJausMsg() { return p_jaus_msg; } ReportPanTiltSpecifications::Body::ReportPanTiltSpecificationsRec PantiltCfgReader::getPantiltSpecification() { return p_pantilt_specification; } void PantiltCfgReader::p_print_spec() { ROS_INFO_NAMED("PantiltCfgReader", "Specification"); ROS_INFO_NAMED("PantiltCfgReader", " Coordinate system: %.3f, %.3f , %.3f", p_pantilt_specification.getPanTiltCoordinateSysX(), p_pantilt_specification.getPanTiltCoordinateSysY(), p_pantilt_specification.getPanTiltCoordinateSysZ()); tf::Quaternion q(p_pantilt_specification.getAComponentOfUnitQuaternionQ(), p_pantilt_specification.getBComponentOfUnitQuaternionQ(), p_pantilt_specification.getCComponentOfUnitQuaternionQ(), p_pantilt_specification.getDComponentOfUnitQuaternionQ()); tf::Matrix3x3 m(q); double p_yaw, p_pitch, p_roll; m.getRPY(p_roll, p_pitch, p_yaw); ROS_INFO_NAMED("PantiltCfgReader", " Orientation RPY: %.3f, %.3f , %.3f", p_roll, p_pitch, p_yaw); if (!p_joint1.empty()) { ROS_INFO_NAMED("PantiltCfgReader", " FirstJoint:"); ROS_INFO_NAMED("PantiltCfgReader", " name: %s", p_joint1.c_str()); ROS_INFO_NAMED("PantiltCfgReader", " minValue: %.3f", p_pantilt_specification.getJoint1MinValue()); ROS_INFO_NAMED("PantiltCfgReader", " maxValue: %.3f", p_pantilt_specification.getJoint1MaxValue()); ROS_INFO_NAMED("PantiltCfgReader", " maxSpeed: %.3f", p_pantilt_specification.getJoint1MaxSpeed()); } if (!p_joint2.empty()) { ROS_INFO_NAMED("PantiltCfgReader", " SecondJoint:"); ROS_INFO_NAMED("PantiltCfgReader", " name: %s", p_joint2.c_str()); ROS_INFO_NAMED("PantiltCfgReader", " minValue: %.3f", p_pantilt_specification.getJoint2MinValue()); ROS_INFO_NAMED("PantiltCfgReader", " maxValue: %.3f", p_pantilt_specification.getJoint2MaxValue()); ROS_INFO_NAMED("PantiltCfgReader", " maxSpeed: %.3f", p_pantilt_specification.getJoint2MaxSpeed()); } }
39.978022
151
0.757559
fkie
2c8168440ba85f8160a3e3f7b75cfc16885e6fa2
1,957
cpp
C++
foe4.cpp
Loretac/ohlavache
2cbe309433cca0f7a61d8c08f6f4f383dd934f10
[ "MIT" ]
null
null
null
foe4.cpp
Loretac/ohlavache
2cbe309433cca0f7a61d8c08f6f4f383dd934f10
[ "MIT" ]
null
null
null
foe4.cpp
Loretac/ohlavache
2cbe309433cca0f7a61d8c08f6f4f383dd934f10
[ "MIT" ]
null
null
null
#include "foe4.h" #include "game.h" #include "bulletdirected.h" #include "bulletminesmall.h" #include <QTimer> extern Game *game; /********************************************************************* ** *********************************************************************/ Foe4::Foe4() { setStartingHealth(2); // setDimensions(100,53,10,-10); // setEnemyPix(QPixmap(":/images/images/ufo.png")); setDimensions(80,58,0,-10); setEnemyPix(QPixmap(":/images/images/fabian.png")); setHealthPix(QPixmap(":/images/images/Shb2.png")); setSize("S"); addToGroup(getEnemyPix()); addToGroup(getHealthPix()); positionHealth(); setPos(rand()% (800-getWidth()),-getHeight()); setMotion(); startShooting(); } void Foe4::move() { if(game->isPaused() == false){ setPos(x(),y()+1); checkStatus(); if(isDead()){ deleteLater(); } } } void Foe4::shoot() { if(game->isPaused() == false){ BulletMineSmall *Bullet = new BulletMineSmall(); Bullet->setSpeed(5); // coordinates of origin of bullet int xSource = x() + getWidth()/2 - Bullet->getWidth()/2; int ySource = y() + getHeight()/2 - Bullet->getHeight()/2; // coordinates of center of player (offset for center of bullet) int xPlayer = game->getPlayerXPos() + game->getPlayerWidth()/2 - Bullet->getWidth()/2; int yPlayer = game->getPlayerYPos() + game->getPlayerHeight()/2 - Bullet->getHeight()/2; // set the trajectory of the bullet Bullet->setXTrajectory(xPlayer-xSource); Bullet->setYTrajectory(yPlayer-ySource); // bullet starts at source Bullet->setPos(xSource,ySource); game->addToScene(Bullet); } } void Foe4::startShooting() { QTimer *timer = new QTimer(this); connect(timer,SIGNAL(timeout()), this,SLOT(shoot())); timer->start(1500); }
20.385417
96
0.552376
Loretac
2c844a4d5b4b4f7aaf9c25dc955654683e53893b
1,519
hh
C++
src/image/image.hh
kofuk/pixel-terrain
f39e2a0120aab5a11311f57cfd1ab46efa65fddd
[ "MIT" ]
2
2020-10-16T08:46:45.000Z
2020-11-04T02:19:19.000Z
src/image/image.hh
kofuk/minecraft-image-generator
ef2f7deb2daac7f7c2cfb468ef39e0cdc8b33db7
[ "MIT" ]
null
null
null
src/image/image.hh
kofuk/minecraft-image-generator
ef2f7deb2daac7f7c2cfb468ef39e0cdc8b33db7
[ "MIT" ]
null
null
null
// SPDX-License-Identifier: MIT #ifndef IMAGE_HH #define IMAGE_HH #include <filesystem> #include "image/containers.hh" #include "image/worker.hh" #include "logger/logger.hh" #include "nbt/chunk.hh" #include "nbt/region.hh" #include "utils/path_hack.hh" #include "utils/threaded_worker.hh" namespace pixel_terrain::image { class image_generator { image::worker *worker_; threaded_worker<region_container *> *thread_pool_; auto fetch() -> region_container *; void write_range_file(int start_x, int start_z, int end_x, int end_z, options const &options); public: image_generator(options const &options) { worker_ = new image::worker; thread_pool_ = new threaded_worker<region_container *>( options.n_jobs(), [this](region_container *item) { this->worker_->generate_region(item); logger::progress_bar_process_one(); delete item; }); } ~image_generator() { delete thread_pool_; delete worker_; } void start(); void queue(region_container *item); void queue_region(std::filesystem::path const &region_file, options const &options); void queue_all_in_dir(std::filesystem::path const &dir, options const &options); void finish(); }; } // namespace pixel_terrain::image #endif
29.211538
77
0.593153
kofuk
2c84bfe2d6f3a681f0b0ddf7a0eee48b60012c57
3,196
hpp
C++
src/oclVM.hpp
beehive-lab/ProtonVM
22636178d2b0bb6ddf2beaa0e381fb6d6ce3598c
[ "Apache-2.0" ]
5
2021-07-23T10:12:12.000Z
2022-02-08T19:38:45.000Z
src/oclVM.hpp
beehive-lab/ProtonVM
22636178d2b0bb6ddf2beaa0e381fb6d6ce3598c
[ "Apache-2.0" ]
null
null
null
src/oclVM.hpp
beehive-lab/ProtonVM
22636178d2b0bb6ddf2beaa0e381fb6d6ce3598c
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020-2021, APT Group, Department of Computer Science, * The University of Manchester. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef OCLVM_HPP #define OCLVM_HPP #define CL_TARGET_OPENCL_VERSION 300 #include <iostream> #include <string> #include <vector> #include "instruction.hpp" #include "bytecodes.hpp" #include "abstractVM.hpp" #define CL_USE_DEPRECATED_OPENCL_2_0_APIS #ifdef __APPLE__ #include <OpenCL/cl.h> #else #include <CL/cl.h> #endif using namespace std; class OCLVM : public AbstractVM { public: OCLVM() {}; OCLVM(vector<int> code, int mainByteCodeIndex); ~OCLVM(); virtual int initOpenCL(string kernelFilename, bool loadBinary); void createBuffers(); void setPlatform(int numPlatform); void useLocalMemory(); void usePrivateMemory(); long getKernelTime(); // Implementation of the Interpreter in OpenCL C virtual void runInterpreter(); protected: char* readSource(const char* sourceFilename); int readBinaryFile(unsigned char **output, size_t *size, const char *name); long getTime(cl_event event); string platformName; cl_uint numPlatforms; cl_platform_id *platforms; cl_device_id *devices; cl_context context; cl_command_queue commandQueue; cl_kernel kernel1; cl_program program; char *source; size_t localWorkSize[1]; size_t lWorkSize; cl_event writeEvent[5]; cl_event kernelEvent; cl_event readEvent[5]; int platformNumber = 0; char* buffer; bool useLocal = false; bool usePrivate = false; cl_mem d_code; cl_mem d_stack; cl_mem d_data; cl_mem d_buffer; bool buffersCreated = false; const int BUFFER_SIZE = 100000; }; class OCLVMPrivate : public OCLVM { public: OCLVMPrivate() {}; OCLVMPrivate(vector<int> code, int mainByteCodeIndex); void runInterpreter(); }; class OCLVMParallel : public OCLVM { public: OCLVMParallel() {}; OCLVMParallel(vector<int> code, int mainByteCodeIndex); void runInterpreter(size_t range); void setHeapSizes(int dataSize); void initHeap(); protected: vector<int> data1; vector<int> data2; vector<int> data3; }; class OCLVMParallelLoop : public OCLVMParallel { public: OCLVMParallelLoop() {}; OCLVMParallelLoop(vector<int> code, int mainByteCodeIndex); void runInterpreter(size_t globalWordItems, size_t localWorkItems); }; #endif
24.030075
83
0.661139
beehive-lab
2c8a4c69dfcad9e88a375b07312965a2600ff4bc
269
cpp
C++
cpp/Itterators/using_zad1.cpp
joro2404/Programming_problems
e0a6f5cbaed013ffde9ecaf3f6d266c582191e41
[ "MIT" ]
null
null
null
cpp/Itterators/using_zad1.cpp
joro2404/Programming_problems
e0a6f5cbaed013ffde9ecaf3f6d266c582191e41
[ "MIT" ]
null
null
null
cpp/Itterators/using_zad1.cpp
joro2404/Programming_problems
e0a6f5cbaed013ffde9ecaf3f6d266c582191e41
[ "MIT" ]
null
null
null
#include <iostream> #include <queue> #include <string> #include "zad1.cpp" using namespace std; using namespace brackets; int main() { Brackets Brackets; int checker = Brackets.countBrackets(); cout << "The string is balanced: " << checker << endl; }
14.944444
58
0.672862
joro2404
2c8cac1b9c33c8497d87479093a357bebbfa92f4
2,459
cc
C++
src/simplesat/parsers/dimacs_parser.cc
evmaus/ClusterSAT
d26ff539fe9789611e9ecd8ef5c14a19e150105b
[ "Apache-2.0" ]
null
null
null
src/simplesat/parsers/dimacs_parser.cc
evmaus/ClusterSAT
d26ff539fe9789611e9ecd8ef5c14a19e150105b
[ "Apache-2.0" ]
null
null
null
src/simplesat/parsers/dimacs_parser.cc
evmaus/ClusterSAT
d26ff539fe9789611e9ecd8ef5c14a19e150105b
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "src/simplesat/parsers/dimacs_parser.h" #include <vector> #include <string> #include <iostream> #include "absl/strings/str_split.h" #include <glog/logging.h> #include "src/simplesat/cnf/cnf_and_op.h" #include "src/simplesat/cnf/cnf_or_op.h" #include "src/simplesat/cnf/cnf_variable.h" namespace simplesat { cnf::Or ParseLine(std::string line) { std::vector<std::string> line_contents = absl::StrSplit(line, ' ', absl::SkipEmpty()); std::vector<cnf::Variable> variables; for (int j = 0; j < line_contents.size(); j++) { if (line_contents[j] == "0") { break; } else { int32_t var_index = stoi(line_contents[j]); if (var_index > 0){ cnf::Variable f(var_index); variables.push_back(f); } else { cnf::Variable f(-var_index, true); variables.push_back(f); } } } cnf::Or expr(variables); return expr; } cnf::And DiMacsParser::ParseCnf(std::istream& input) { std::string line; while ( getline (input,line) && line[0] == 'c') { LOG(INFO) << "Skipping line " << line; } LOG(INFO) << "Found starting line: " << line; // Parse first line: p cnf nvar nclause std::vector<std::string> line_contents = absl::StrSplit(line, ' ', absl::SkipEmpty()); // Expectation: line is in the form 'p cnf nvar nclause' LOG(INFO) << "nvar " << line_contents[2]; //uint32_t num_terms = std::stoi(line_contents[2]); LOG(INFO) << "nclause " << line_contents[3]; uint32_t num_clauses = std::stoi(line_contents[3]); std::list<cnf::Or> terms; for(int i = 0; i < num_clauses; i++) { if(!getline(input, line)){ // TODO error } LOG(INFO) << "Parsing line: " << line; auto term = ParseLine(line); terms.push_back(term); LOG(INFO) << "Parsed: " << term.to_string(); } cnf::And expr(terms); return expr; } } // namespace simplesat
30.7375
88
0.651891
evmaus
2c979c8325291c6061e2735370baa586ab05be42
234
cpp
C++
display/source/DisplayConstants.cpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
null
null
null
display/source/DisplayConstants.cpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
null
null
null
display/source/DisplayConstants.cpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
null
null
null
#include "DisplayConstants.hpp" using namespace std; const string DisplayIdentifier::DISPLAY_IDENTIFIER_CURSES = "curses"; const string DisplayIdentifier::DISPLAY_IDENTIFIER_SDL = "sdl"; DisplayIdentifier::DisplayIdentifier() { }
19.5
69
0.807692
sidav
2ca15fdd61c0a58f78d82d0e92b823c8ba841b67
285
cpp
C++
src/kitti/common.cpp
dzyswy/kitti_player
77f9d6266a05639da4ba9b943338a9f2304b9f5e
[ "MIT" ]
null
null
null
src/kitti/common.cpp
dzyswy/kitti_player
77f9d6266a05639da4ba9b943338a9f2304b9f5e
[ "MIT" ]
null
null
null
src/kitti/common.cpp
dzyswy/kitti_player
77f9d6266a05639da4ba9b943338a9f2304b9f5e
[ "MIT" ]
null
null
null
#include "kitti/common.h" namespace kitti { void GlobalInit(int* pargc, char*** pargv) { // Google logging. ::google::InitGoogleLogging(*(pargv)[0]); // Provide a backtrace on segfault. ::google::InstallFailureSignalHandler(); } }//namespace kitti
8.142857
43
0.631579
dzyswy
2ca2106ecd6bed73ee0215738d606f2a216e6f64
3,062
cpp
C++
src/Tools/ProjectBuilder/XmlToBinDecoder.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
39
2016-04-21T03:25:26.000Z
2022-01-19T14:16:38.000Z
src/Tools/ProjectBuilder/XmlToBinDecoder.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
23
2016-06-28T13:03:17.000Z
2022-02-02T10:11:54.000Z
src/Tools/ProjectBuilder/XmlToBinDecoder.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
14
2016-06-22T20:45:37.000Z
2021-07-05T12:25:19.000Z
#include "XmlToBinDecoder.h" #include "Interface/ServiceInterface.h" #include "Interface/StringizeServiceInterface.h" #include "Interface/ArchivatorInterface.h" #include "Interface/LoggerInterface.h" #include "Interface/CodecInterface.h" #include "Interface/ConverterInterface.h" #include "Interface/FileServiceInterface.h" #include "Interface/PluginInterface.h" #include "Interface/UnicodeSystemInterface.h" #include "Interface/CodecServiceInterface.h" #include "Plugins/XmlToBinPlugin/XmlToBinInterface.h" #include "Kernel/Logger.h" #include "Kernel/Document.h" #include "Kernel/ConstStringHelper.h" #include "Kernel/FilePathHelper.h" #include "Kernel/UnicodeHelper.h" #include "Xml2Metabuf.hpp" #include "Xml2Metacode.hpp" #include "Metacode/Metacode.h" #include "Config/Typedef.h" namespace Mengine { ////////////////////////////////////////////////////////////////////////// static bool s_writeBin( const WString & _protocolPath, const WString & _xmlPath, const WString & _binPath ) { String utf8_protocolPath; Helper::unicodeToUtf8( _protocolPath, &utf8_protocolPath ); String utf8_xmlPath; Helper::unicodeToUtf8( _xmlPath, &utf8_xmlPath ); String utf8_binPath; Helper::unicodeToUtf8( _binPath, &utf8_binPath ); XmlDecoderInterfacePtr decoder = CODEC_SERVICE() ->createDecoder( STRINGIZE_STRING_LOCAL( "xml2bin" ), MENGINE_DOCUMENT_FUNCTION ); if( decoder == nullptr ) { LOGGER_ERROR( "writeBin invalid create decoder xml2bin for %s" , utf8_xmlPath.c_str() ); return false; } if( decoder->prepareData( nullptr ) == false ) { LOGGER_ERROR( "writeBin invalid initialize decoder xml2bin for %s" , utf8_xmlPath.c_str() ); return false; } XmlDecoderData data; data.pathProtocol = Helper::stringizeFilePath( utf8_protocolPath ); data.pathXml = Helper::stringizeFilePath( utf8_xmlPath ); data.pathBin = Helper::stringizeFilePath( utf8_binPath ); data.useProtocolVersion = Metacode::get_metacode_protocol_version(); data.useProtocolCrc32 = Metacode::get_metacode_protocol_crc32(); if( decoder->decode( &data ) == 0 ) { LOGGER_ERROR( "writeBin invalid decode %s" , utf8_xmlPath.c_str() ); return false; } return true; } ////////////////////////////////////////////////////////////////////////// PyObject * writeBin( pybind::kernel_interface * _kernel, const wchar_t * protocolPath, const wchar_t * xmlPath, const wchar_t * binPath ) { if( s_writeBin( protocolPath, xmlPath, binPath ) == false ) { LOGGER_ERROR( "writeBin: error write bin" ); return nullptr; } return _kernel->ret_none(); } }
30.929293
142
0.599282
irov
2ca2e271039a5fffec046d722e2e2d7093237e3a
3,276
cpp
C++
poprithms/tests/tests/schedule/shift/graph_comparisons_0.cpp
graphcore/poprithms
9975a6a343891e3c5f8968a9507261c1185029ed
[ "MIT" ]
24
2020-07-06T17:11:30.000Z
2022-01-01T07:39:12.000Z
poprithms/tests/tests/schedule/shift/graph_comparisons_0.cpp
graphcore/poprithms
9975a6a343891e3c5f8968a9507261c1185029ed
[ "MIT" ]
null
null
null
poprithms/tests/tests/schedule/shift/graph_comparisons_0.cpp
graphcore/poprithms
9975a6a343891e3c5f8968a9507261c1185029ed
[ "MIT" ]
2
2020-07-15T12:33:22.000Z
2021-07-27T06:07:16.000Z
// Copyright (c) 2021 Graphcore Ltd. All rights reserved. #include <iostream> #include <string> #include <poprithms/error/error.hpp> #include <poprithms/schedule/shift/graph.hpp> namespace { using namespace poprithms::schedule::shift; void test0() { // check multiple comparison operators at the same time auto different = [](const Graph &g0, const Graph &g1) { return g0 != g1 && !g0.equalTo(g1, false) && ((g0 < g1) != (g1 < g0)); }; Graph g0; /* * * A B (allocs) * : : * : : * a --> b (ops) * | * v * c ==> d (ops) * * */ auto a = g0.insertOp("a"); auto b = g0.insertOp("b"); auto c = g0.insertOp("c"); auto d = g0.insertOp("d"); g0.insertConstraint(a, b); g0.insertConstraint(a, c); g0.insertLink(c, d); auto A = g0.insertAlloc(100.); auto B = g0.insertAlloc(200.); g0.insertOpAlloc(a, A); g0.insertOpAlloc(b, B); // Exact copy: { const auto g1 = g0; if (g0 != g1 || g0 < g1 || !g0.equalTo(g1, false) || g0.lessThan(g1, false)) { throw poprithms::test::error("g0 == g1"); } } // Extra constraint: { auto g1 = g0; g1.insertConstraint(b, d); if (!different(g0, g1)) { throw poprithms::test::error( "g1 has an extra constraint, not the same"); } } // Extra op: { auto g1 = g0; g1.insertOp("extra"); if (!different(g0, g1)) { throw poprithms::test::error("g1 has an extra op, not the same"); } } // Extra link: { auto g1 = g0; g1.insertLink(a, b); if (!different(g0, g1)) { throw poprithms::test::error("g1 has an extra link, not the same"); } } // Names differ on 1 op: { auto g1 = g0; g1.insertOp("foo"); auto g2 = g0; g2.insertOp("bar"); if (g1 == g2) { throw poprithms::test::error( "g1 and g2 are not equal, their ops don't have the same names"); } if (!g1.equalTo(g2, false)) { throw poprithms::test::error( "g1 and g2 are equal, if the names of ops are excluded"); } } // alloc values differ on 1 alloc { auto g1 = g0; g1.insertAlloc(5); auto g2 = g0; g2.insertAlloc(6); if (!different(g1, g2)) { throw poprithms::test::error("g1 and g2 do not have the same allocs"); } } // allocs assigned to different ops { auto g1 = g0; { auto C = g1.insertAlloc(5); g1.insertOpAlloc(c, C); } auto g2 = g0; { auto D = g2.insertAlloc(5); g2.insertOpAlloc(d, D); } if (g1 == g2 || g1.equalTo(g2, false)) { throw poprithms::test::error( "The 2 Graphs are not the same, the final alloc is " "assigned to different Ops"); } // Now, add allocs so that isomporphically the graphs are the same, but // this comparison doesn't do graph isomorphism (too slow). { auto C = g2.insertAlloc(5); g2.insertOpAlloc(c, C); auto D = g1.insertAlloc(5); g1.insertOpAlloc(d, D); if (!different(g1, g2)) { throw poprithms::test::error( "They shouldn't compare equal here, as we are not doing " "a true graph isomorphism."); } } } } } // namespace int main() { test0(); return 0; }
21.552632
76
0.547314
graphcore
2ca6a079c413fb203abe0b963e59036bf389350c
17,757
hpp
C++
Datastructures/Tree.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
2
2021-06-09T00:38:46.000Z
2021-09-04T21:55:33.000Z
Datastructures/Tree.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
null
null
null
Datastructures/Tree.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
1
2021-08-30T00:46:12.000Z
2021-08-30T00:46:12.000Z
// // Created by phoenixflower on 9/26/21. // #ifndef LANDESSDEVCORE_TREE_HPP #define LANDESSDEVCORE_TREE_HPP // // Tree.h // Foundation // // Created by James Landess on 1/6/14. // Copyright (c) 2014 LandessDev. All rights reserved. // #ifndef Foundation_Tree_h #define Foundation_Tree_h /*----------------------------------------------------------------------------- tree.h STL-like tree -----------------------------------------------------------------------------*/ #ifndef _TREE_H #define _TREE_H #include <memory> #include <iterator> #include <cassert> //----------------------------------------------------------------------------- namespace gems { //----------------------------------------------------------------------------- template <class T, class Alloc = std::allocator<T> > class tree { public: typedef tree<T, Alloc> TreeT; typedef TreeT value_type; typedef TreeT* pointer; typedef const TreeT* const_pointer; typedef TreeT& reference; typedef const TreeT& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; // provide special handling for non-standard VC6 allocators #if _MSC_VER < 1300 typedef Alloc allocator_type; #else typedef typename Alloc::template rebind<TreeT>::other allocator_type; #endif class iterator; class const_iterator; class child_iterator; class const_child_iterator; tree() { init(); } tree(const T& t) : value(t) { init(); } tree(const TreeT& copy) : value(copy.value) { init(); copy_children(copy); } ~tree() { clear(); } const tree& operator=(const TreeT& rhs) { TreeT temp(rhs); swap(temp); return *this; } // iterators class iterator : public std::iterator<std::bidirectional_iterator_tag, value_type, void> { public: iterator() : _ptr(0), _root(0) {} TreeT& operator*() const {return *_ptr;} TreeT* operator->() const {return _ptr;} bool operator==(const iterator& rhs) const {return _ptr == rhs._ptr;} bool operator!=(const iterator& rhs) const {return _ptr != rhs._ptr;} iterator& operator++() {_ptr = _ptr->_next; return *this;} iterator& operator--() {_ptr = (_ptr ? _ptr->prev() : _root->_last_descendant); return *this;} iterator operator++(int i) { iterator temp = *this; ++*this; return temp; } iterator operator--(int i) { iterator temp = *this; --*this; return temp; } // advance past current subtree friend void skip(iterator& it) { it._ptr = it._ptr->next_sibling(); } protected: TreeT* _ptr; TreeT* _root; iterator(TreeT* ptr, TreeT* root) : _ptr(ptr), _root(root) {} friend class tree<T, Alloc>; friend class const_iterator; friend class child_iterator; friend class const_child_iterator; }; class const_iterator : public std::iterator<std::bidirectional_iterator_tag, value_type, void> { public: const_iterator() : _ptr(0), _root(0) {} const_iterator(const iterator& it) : _ptr(it._ptr), _root(it._root) {} const TreeT& operator*() const {return *_ptr;} const TreeT* operator->() const {return _ptr;} bool operator==(const const_iterator& rhs) const {return _ptr == rhs._ptr;} bool operator!=(const const_iterator& rhs) const {return _ptr != rhs._ptr;} const_iterator& operator++() {_ptr = _ptr->_next; return *this;} const_iterator& operator--() {_ptr = (_ptr ? _ptr->prev() : _root->_last_descendant); return *this;} const_iterator operator++(int i) { const_iterator temp = *this; ++*this; return temp; } const_iterator operator--(int i) { const_iterator temp = *this; --*this; return temp; } protected: const TreeT* _ptr; const TreeT* _root; const_iterator(const TreeT* ptr, const TreeT* root) : _ptr(ptr), _root(root) {} friend class tree<T, Alloc>; friend class const_child_iterator; }; class child_iterator : public std::iterator<std::bidirectional_iterator_tag, value_type, void> { public: child_iterator() : _ptr(0), _root(0) {} child_iterator(const iterator& it) : _ptr(it._ptr), _root(it._root) {} operator iterator() const { return iterator(_ptr, _root); } TreeT& operator*() const {return *_ptr;} TreeT* operator->() const {return _ptr;} bool operator==(const child_iterator& rhs) const {return _ptr == rhs._ptr;} bool operator!=(const child_iterator& rhs) const {return _ptr != rhs._ptr;} child_iterator& operator++() {_ptr = _ptr->next_sibling(); return *this;} child_iterator& operator--() {_ptr = (_ptr ? _ptr->prev_sibling() : _root->last_child()); return *this;} child_iterator operator++(int i) { child_iterator temp = *this; ++*this; return temp; } child_iterator operator--(int i) { child_iterator temp = *this; --*this; return temp; } protected: TreeT* _ptr; TreeT* _root; child_iterator(TreeT* ptr, TreeT* root) : _ptr(ptr), _root(root) {} friend class tree<T, Alloc>; friend class const_child_iterator; }; class const_child_iterator : public std::iterator<std::bidirectional_iterator_tag, value_type, void> { public: const_child_iterator() : _ptr(0), _root(0) {} const_child_iterator(const child_iterator& it) : _ptr(it._ptr), _root(it._root) {} const_child_iterator(const iterator& it) : _ptr(it._ptr), _root(it._root) {} const_child_iterator(const const_iterator& it) : _ptr(it._ptr), _root(it._root) {} operator const_iterator() const { return iterator(_ptr, _root); } const TreeT& operator*() const {return *_ptr;} const TreeT* operator->() const {return _ptr;} bool operator==(const const_child_iterator& rhs) const {return _ptr == rhs._ptr;} bool operator!=(const const_child_iterator& rhs) const {return _ptr != rhs._ptr;} const_child_iterator& operator++() {_ptr = _ptr->next_sibling(); return *this;} const_child_iterator& operator--() {_ptr = (_ptr ? _ptr->prev_sibling() : _root->last_child()); return *this;} const_child_iterator operator++(int i) { const_child_iterator temp = *this; ++*this; return temp; } const_child_iterator operator--(int i) { const_child_iterator temp = *this; --*this; return temp; } protected: const TreeT* _ptr; const TreeT* _root; const_child_iterator(const TreeT* ptr, const TreeT* root) : _ptr(ptr), _root(root) {} friend class tree<T, Alloc>; }; //typedef std::is_bidirectional_iterator<iterator, //value_type, reference, pointer, difference_type> //reverse_iterator; //typedef std::is_bidirectional_iterator<const_iterator, // value_type, const_reference, const_pointer, difference_type> //const_reverse_iterator; // typedef std::is_bidirectional_iterator<child_iterator, // value_type, reference, pointer, difference_type> //reverse_child_iterator; // typedef std::is_bidirectional_iterator<const_child_iterator, //value_type, const_reference, const_pointer, difference_type> //const_reverse_child_iterator; const_iterator begin() const {return const_iterator(this, this);} const_iterator end() const {return const_iterator(0, this);} iterator begin() {return iterator(this, this);} iterator end() {return iterator(0, this);} void push_back(const TreeT& subtree) { TreeT* child = create_subtree(subtree); insert_subtree(*child, 0); } void push_front(const TreeT& subtree) { TreeT* child = create_subtree(subtree); TreeT* next = first_child(); insert_subtree(*child, next); } void pop_back() { TreeT* last = last_child(); assert(last); erase(iterator(last, this)); } void pop_front() { TreeT* first = first_child(); assert(first); erase(iterator(first, this)); } void clear() { destroy_descendants(); } TreeT& front() {return *first_child();} const TreeT& front() const {return *first_child();} TreeT& back() {return *last_child();} const TreeT& back() const {return *last_child();} iterator insert(const TreeT& subtree, iterator it) { TreeT* child = create_subtree(subtree); insert_subtree(*child, &*it); // if end(), append to this return iterator(child, this); } iterator erase(iterator it) { TreeT* child = &*it; assert(child); TreeT* parent = child->parent(); assert(parent); TreeT* next = child->next_sibling(); parent->remove_subtree(*child); child->destroy(); return iterator(next, this); } void splice(iterator it, child_iterator first, child_iterator last) { while (first != last) { TreeT* parent = first->parent(); child_iterator next = first; ++next; if (parent) { parent->remove_subtree(*first); insert_subtree(*first, &*it); // if it == end(), append to this; that's why this fn can't be static } first = next; } } friend bool operator==(const TreeT& lhs, const TreeT& rhs) { const TreeT* lChild = lhs.first_child(); const TreeT* rChild = rhs.first_child(); while (lChild && rChild && (*lChild == *rChild)) { lChild = lChild->next_sibling(); rChild = rChild->next_sibling(); } return (!lChild && !rChild && (lhs.value == rhs.value)); } friend bool operator!=(const TreeT& lhs, const TreeT& rhs) { return !(lhs == rhs); } bool is_root() const { return _parent == 0; } bool is_leaf() const { return _last_descendant == this; } bool is_descendant_of(const TreeT& ancestor) { TreeT * t; for (t = this; t; t = t->_parent) if (t == &ancestor) break; return (t != 0); } size_type size() const // number of descendants { size_type n = 1; for (const TreeT* t = this; t != _last_descendant; t = t->_next) n++; return n; } size_type degree() const // number of children { size_type n = 0; for (const TreeT* t = first_child(); t; t = t->next_sibling()) n++; return n; } size_type level() const // depth in tree { size_type l = 0; for (const TreeT* t = _parent; t; t = t->_parent) l++; return l; } TreeT* parent() const { return _parent; } TreeT* first_child() const { TreeT* child = 0; if (_next && (_next->_parent == this)) child = _next; return child; } TreeT* last_child() const { TreeT* child = first_child(); if (child) child = child->_prev_sibling; return child; } TreeT* next_sibling() const { TreeT* sib = _last_descendant->_next; if (sib && (sib->_parent != _parent)) sib = 0; return sib; } TreeT* prev_sibling() const { TreeT* sib = 0; if (_parent && (_parent->_next != this)) sib = _prev_sibling; return sib; } TreeT* last_descendant() const { return _last_descendant; } void swap(TreeT& other) { child_iterator it = other.begin_child(); //other.splice(it, begin_child(), end_child()); //splice(begin_child(), it, other.end_child()); std::swap(value, other.value); } Alloc get_allocator() const { return _alloc; } size_type max_size() const { return (_alloc.max_size()); } public: T value; private: TreeT* _parent; TreeT* _prev_sibling; TreeT* _next; TreeT* _last_descendant; static allocator_type _alloc; friend iterator; friend const_iterator; friend child_iterator; friend const_child_iterator; void init() { _parent = _next = 0; _prev_sibling = _last_descendant = this; } static TreeT* create_subtree(const TreeT& copy) { #if defined(__APPLE__) std::auto_ptr<TreeT> a((TreeT*)_alloc.allocate(1)); TreeT* t = a.get(); _alloc.construct(t, copy); #elif _MSC_VER < 1300 auto_ptr<TreeT> a((TreeT*)_alloc._Charalloc(sizeof(TreeT))); TreeT* t = a.get(); _alloc.construct(&t->value, copy.value); t->init(); t->copy_children(copy); #else auto_ptr<TreeT> a((TreeT*)_alloc.allocate(1)); TreeT* t = a.get(); _alloc.construct(t, copy); #endif return a.release(); } void copy_children(const TreeT& other) { for (TreeT* child = other.first_child(); child; child = child->next_sibling()) insert_subtree(*create_subtree(*child), 0); } void destroy() { #if _MSC_VER < 1300 destroy_descendants(); _alloc.destroy(&value); _alloc.deallocate((T*)this, 1); #else _alloc.destroy(this); _alloc.deallocate(this, 1); #endif } void destroy_descendants() { TreeT* descendant = first_child(); TreeT* end = last_descendant()->next(); while (descendant) { TreeT* next = descendant->next_sibling(); descendant->destroy(); descendant = next; } _next = end; _last_descendant = this; } void insert_subtree(TreeT& child, TreeT* next) { if (next == 0) { // append as last child child._parent = this; child._last_descendant->_next = _last_descendant->_next; _last_descendant->_next = &child; child._prev_sibling = last_child(); if (is_leaf()) _next = &child; first_child()->_prev_sibling = &child; change_last_descendant(child._last_descendant); } else { TreeT* parent = next->_parent; child._parent = parent; child._prev_sibling = next->_prev_sibling; child._last_descendant->_next = next; if (parent->_next == next) // inserting before first child? parent->_next = &child; else next->_prev_sibling->_last_descendant->_next = &child; next->_prev_sibling = &child; } } void remove_subtree(TreeT& child) { TreeT* sib = child.next_sibling(); if (sib) sib->_prev_sibling = child._prev_sibling; else first_child()->_prev_sibling = child._prev_sibling; if (_last_descendant == child._last_descendant) change_last_descendant(child.prev()); if (_next == &child) // deleting first child? _next = child._last_descendant->_next; else child._prev_sibling->_last_descendant->_next = child._last_descendant->_next; } void change_last_descendant(TreeT* newLast) { TreeT* oldLast = _last_descendant; TreeT* ancestor = this; do { ancestor->_last_descendant = newLast; ancestor = ancestor->_parent; } while (ancestor && (ancestor->_last_descendant == oldLast)); } TreeT* next() const { return _next; } TreeT* prev() const { TreeT* prev = 0; if (_parent) { if (_parent->_next == this) prev = _parent; else prev = _prev_sibling->_last_descendant; } return prev; } }; // class tree<T, Alloc> template <class T, class Alloc> typename tree<T, Alloc>::allocator_type tree<T, Alloc>::_alloc; //----------------------------------------------------------------------------- } // namespace gems #endif // _TREE_H #endif #endif //LANDESSDEVCORE_TREE_HPP
31.822581
122
0.525933
jlandess
2ca6bdbc6157547d62a3c5a0bcaad1b02cbb0113
1,137
cpp
C++
src/LongestValidParentheses.cpp
lzz5235/leetcode
8713b7924a84a0c7d6887e1c8052738b5a778d1f
[ "MIT" ]
null
null
null
src/LongestValidParentheses.cpp
lzz5235/leetcode
8713b7924a84a0c7d6887e1c8052738b5a778d1f
[ "MIT" ]
null
null
null
src/LongestValidParentheses.cpp
lzz5235/leetcode
8713b7924a84a0c7d6887e1c8052738b5a778d1f
[ "MIT" ]
null
null
null
//Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. // //For "(()", the longest valid parentheses substring is "()", which has length = 2. // //Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4. #include <iostream> #include <algorithm> #include <stack> #include <string> #include <vector> using namespace std; //()() //() //)()()) class Solution { public: int longestValidParentheses(string s) { int max_len=0,flag=-1;//flag is for "()...." int i=0; //if(s[0]=='('&&s[1]==')') // max_len=2; for(auto c:s){ if(c=='(') stk.push(i); else{ if(stk.empty()) flag = i ; else{ stk.pop(); if(stk.empty()) max_len = max(max_len,i-flag); else max_len = max(max_len,i-stk.top()); } } i++; } return max_len; } private: stack<int> stk; }; int main() { string s(")()()"); Solution solute; int count = solute.longestValidParentheses(s); printf("%d\n",count); return 0; }
21.45283
135
0.562005
lzz5235
2ca7b5bd693fd0599d411fb3c96a2b6adfc57565
2,000
hpp
C++
engine/include/io/logger.hpp
ValtoForks/Terminus-Engine
0c7381af84736ec7b029977843590453cde64b1d
[ "MIT" ]
44
2017-01-25T05:57:21.000Z
2021-09-21T13:36:49.000Z
engine/include/io/logger.hpp
ValtoForks/Terminus-Engine
0c7381af84736ec7b029977843590453cde64b1d
[ "MIT" ]
1
2017-04-05T01:50:18.000Z
2017-04-05T01:50:18.000Z
engine/include/io/logger.hpp
ValtoForks/Terminus-Engine
0c7381af84736ec7b029977843590453cde64b1d
[ "MIT" ]
3
2017-09-28T08:11:00.000Z
2019-03-27T03:38:47.000Z
#pragma once #include <core/terminus_macros.hpp> #include <string> // Macros for quick access. File and line are added through the respective macros. #define TE_LOG_INFO(x) te::logger::log(x, std::string(__FILE__), __LINE__, te::logger::LEVEL_INFO) #define TE_LOG_WARNING(x) te::logger::log(x, std::string(__FILE__), __LINE__, te::logger::LEVEL_WARNING) #define TE_LOG_ERROR(x) te::logger::log(x, std::string(__FILE__), __LINE__, te::logger::LEVEL_ERR) #define TE_LOG_FATAL(x) te::logger::log(x, std::string(__FILE__), __LINE__, te::logger::LEVEL_FATAL) TE_BEGIN_TERMINUS_NAMESPACE namespace logger { enum LogLevel { LEVEL_INFO = 0, LEVEL_WARNING = 1, LEVEL_ERR = 2, LEVEL_FATAL = 3 }; enum LogVerbosity { VERBOSITY_BASIC = 0x00, VERBOSITY_TIMESTAMP = 0x01, VERBOSITY_LEVEL = 0x02, VERBOSITY_FILE = 0x04, VERBOSITY_LINE = 0x08, VERBOSITY_ALL = 0x0f }; // Custom stream callback type. Use to implement your own logging stream such as through a network etc. typedef void(*CustomStreamCallback)(std::string, LogLevel); extern void initialize(); extern void set_verbosity(int flags); // Open streams. extern void open_file_stream(); extern void open_console_stream(); extern void open_custom_stream(CustomStreamCallback callback); // Close streams. extern void close_file_stream(); extern void close_console_stream(); extern void close_custom_stream(); // Debug mode. These will flush the stream immediately after each log. extern void enable_debug_mode(); extern void disable_debug_mode(); // Main log method. File, line and level are required in addition to log message. extern void log(std::string text, std::string file, int line, LogLevel level); // Simplified API. extern void log_info(std::string text); extern void log_error(std::string text); extern void log_warning(std::string text); extern void log_fatal(std::string text); // Explicitly flush all streams. extern void flush(); } // namespace logger TE_END_TERMINUS_NAMESPACE
29.411765
104
0.751
ValtoForks
2caa60a850f9f796a4bb0bf8d40e9537f2e24d5f
424
cpp
C++
ieee_sep/RateComponentListLink.cpp
Tylores/ieee_sep
1928bed8076f4bfe702d34e436c6a85f197b0832
[ "BSD-2-Clause" ]
null
null
null
ieee_sep/RateComponentListLink.cpp
Tylores/ieee_sep
1928bed8076f4bfe702d34e436c6a85f197b0832
[ "BSD-2-Clause" ]
null
null
null
ieee_sep/RateComponentListLink.cpp
Tylores/ieee_sep
1928bed8076f4bfe702d34e436c6a85f197b0832
[ "BSD-2-Clause" ]
null
null
null
/////////////////////////////////////////////////////////// // RateComponentListLink.cpp // Implementation of the Class RateComponentListLink // Created on: 13-Apr-2020 2:51:38 PM // Original author: svanausdall /////////////////////////////////////////////////////////// #include "RateComponentListLink.h" RateComponentListLink::RateComponentListLink(){ } RateComponentListLink::~RateComponentListLink(){ }
22.315789
59
0.54717
Tylores
2caae092e04eda8fe3c4320d39f468ae13e0f99f
3,705
cpp
C++
arduino/pcc2arduino.cpp
ncchandler42/pcc2arduino
ff67796d93760b1c2dd3dc9e9a02319d71ef6d7e
[ "MIT" ]
null
null
null
arduino/pcc2arduino.cpp
ncchandler42/pcc2arduino
ff67796d93760b1c2dd3dc9e9a02319d71ef6d7e
[ "MIT" ]
null
null
null
arduino/pcc2arduino.cpp
ncchandler42/pcc2arduino
ff67796d93760b1c2dd3dc9e9a02319d71ef6d7e
[ "MIT" ]
null
null
null
#include "pcc2arduino.h" /////////////////////// // reads in bytes from serial // returns true when the controller state is ready /////////////////////// bool PCController::update() { if (!ser || !ser->available()) return false; //find the start of a valid parsel while (ser->peek() != '<') { byte b = ser->read(); if (b == -1) return false; } byte parsel[10]; ser->readBytes(parsel, 10); if (parsel[0] == '<' && parsel[9] == '>') { //copies the data part of the parsel into the input, to be parsed memcpy(inp, parsel + 1, 8); parseButtons(); parseAxes(); ser->write('*'); return true; } return false; } bool PCController::updateInc() { static int i = 0; static bool reading = false; if(!ser) return false; //Notify the system ser->write('*'); byte b; //wait for response while(!ser->available()); b = ser->read(); if (i == 0 && b == '<') { reading = true; return false; } if (reading && i >= 0 && i < 8) { inp[i] = b; i++; return false; } if (reading && i == 8 && b == '>') { reading = false; i = 0; parseButtons(); parseAxes(); return true; } return false; } ///////////////////////////////////////////////// // Parses 2 bytes into 16 buttons (bools) ///////////////////////////////////////////////// void PCController::parseButtons() { dpad_up = inp[0] & 1; dpad_down = inp[0] & 2; dpad_left = inp[0] & 4; dpad_right = inp[0] & 8; a = inp[0] & 16; b = inp[0] & 32; x = inp[0] & 64; y = inp[0] & 128; lb = inp[1] & 1; rb = inp[1] & 2; lt = inp[1] & 4; rt = inp[1] & 8; select = inp[1] & 16; start = inp[1] & 32; ls_press = inp[1] & 64; rs_press = inp[1] & 128; } //////////////////////////////////////////////// // Parses 12 bytes into 6 axes, 2 bytes per axis // Serial architecture is "little-endian" // UPDATE: axis values are now 0-255, one byte // ... makes conversion a lot simpler //////////////////////////////////////////////// void PCController::parseAxes() { x_axis = inp[2]; y_axis = inp[3]; z_axis = inp[4]; r_axis = inp[5]; u_axis = inp[6]; v_axis = inp[7]; } void PCController::displayButtons() { if (ser) { ser->print("up: "); ser->print(dpad_up); ser->println(); ser->print("down: "); ser->print(dpad_down); ser->println(); ser->print("left: "); ser->print(dpad_left); ser->println(); ser->print("right: "); ser->print(dpad_right); ser->println(); ser->print("a: "); ser->print(a); ser->println(); ser->print("b: "); ser->print(b); ser->println(); ser->print("x: "); ser->print(x); ser->println(); ser->print("y: "); ser->print(y); ser->println(); ser->print("lb: "); ser->print(lb); ser->println(); ser->print("rb: "); ser->print(rb); ser->println(); ser->print("lt: "); ser->print(lt); ser->println(); ser->print("rt: "); ser->print(rt); ser->println(); ser->print("select: "); ser->print(select); ser->println(); ser->print("start: "); ser->print(start); ser->println(); ser->print("LS press: "); ser->print(ls_press); ser->println(); ser->print("RS press: "); ser->print(rs_press); ser->println(); ser->println(); } } void PCController::displayAxes() { if (ser) { ser->print("X axis: "); ser->print(x_axis); ser->println(); ser->print("Y axis: "); ser->print(y_axis); ser->println(); ser->print("Z axis: "); ser->print(z_axis); ser->println(); ser->print("R axis: "); ser->print(r_axis); ser->println(); ser->print("U axis: "); ser->print(u_axis); ser->println(); ser->print("V axis: "); ser->print(v_axis); ser->println(); ser->println(); } }
16.764706
67
0.516059
ncchandler42
2cadf91207f78b90cb5b8e80ead2ba9d1169e48b
10,520
cpp
C++
external/src/zxing/zxing/maxicode/MCDecoder.cpp
emarc99/SLib
4e492d6c550f845fd1b3f40bf10183097eb0e53c
[ "MIT" ]
1,049
2019-07-22T14:45:58.000Z
2022-03-17T15:42:31.000Z
external/src/zxing/zxing/maxicode/MCDecoder.cpp
Crasader/SLib
4e492d6c550f845fd1b3f40bf10183097eb0e53c
[ "MIT" ]
153
2019-07-23T08:01:14.000Z
2022-01-19T03:53:52.000Z
external/src/zxing/zxing/maxicode/MCDecoder.cpp
Crasader/SLib
4e492d6c550f845fd1b3f40bf10183097eb0e53c
[ "MIT" ]
169
2019-07-23T07:48:22.000Z
2022-03-30T09:01:34.000Z
/* * Copyright 2016 Nu-book Inc. * Copyright 2016 ZXing 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. */ #include "maxicode/MCDecoder.h" #include "maxicode/MCBitMatrixParser.h" #include "ByteArray.h" #include "DecoderResult.h" #include "ReedSolomonDecoder.h" #include "GenericGF.h" #include "DecodeStatus.h" #include "TextDecoder.h" #include "ZXStrConvWorkaround.h" #include <array> #include <sstream> #include <iomanip> #include <algorithm> namespace ZXing { namespace MaxiCode { static const int ALL = 0; static const int EVEN = 1; static const int ODD = 2; static bool CorrectErrors(ByteArray& codewordBytes, int start, int dataCodewords, int ecCodewords, int mode) { int codewords = dataCodewords + ecCodewords; // in EVEN or ODD mode only half the codewords int divisor = mode == ALL ? 1 : 2; // First read into an array of ints std::vector<int> codewordsInts(codewords / divisor, 0); for (int i = 0; i < codewords; i++) { if ((mode == ALL) || (i % 2 == (mode - 1))) { codewordsInts[i / divisor] = codewordBytes[i + start]; } } if (!ReedSolomonDecoder::Decode(GenericGF::MaxiCodeField64(), codewordsInts, ecCodewords / divisor)) return false; // Copy back into array of bytes -- only need to worry about the bytes that were data // We don't care about errors in the error-correction codewords for (int i = 0; i < dataCodewords; i++) { if ((mode == ALL) || (i % 2 == (mode - 1))) { codewordBytes[i + start] = static_cast<uint8_t>(codewordsInts[i / divisor]); } } return true; } /** * <p>MaxiCodes can encode text or structured information as bits in one of several modes, * with multiple character sets in one code. This class decodes the bits back into text.</p> * * @author mike32767 * @author Manuel Kasten */ namespace DecodedBitStreamParser { static const char SHI0 = 0x40; static const char SHI1 = 0x41; static const char SHI2 = 0x42; static const char SHI3 = 0x43; static const char SHI4 = 0x44; static const char TWSA = 0x45; // two shift A static const char TRSA = 0x46; // three shift A static const char LCHA = 0x47; // latch A static const char LCHB = 0x48; // latch B static const char LOCK = 0x49; static const char ECI = 0x4A; static const char NS = 0x4B; static const char PAD = 0x4C; static const char FS = 0x1C; static const char GS = 0x1D; static const char RS = 0x1E; const static std::array<char, 0x40> CHARSETS[] = { { // set 0 '\n', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ECI, FS, GS, RS, NS, ' ', PAD, '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', SHI1, SHI2, SHI3, SHI4, LCHB, }, { // set 1 '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ECI, FS, GS, RS, NS, '{', PAD, '}', '~', 0x7F, ';', '<', '=', '>', '?', '[', '\\', ']', '^', '_', ' ', ',', '.', '/', ':', '@', '!', '|', PAD, TWSA, TRSA, PAD, SHI0, SHI2, SHI3, SHI4, LCHA, }, { // set 2 '\xC0', '\xC1', '\xC2', '\xC3', '\xC4', '\xC5', '\xC6', '\xC7', '\xC8', '\xC9', '\xCA', '\xCB', '\xCC', '\xCD', '\xCE', '\xCF', '\xD0', '\xD1', '\xD2', '\xD3', '\xD4', '\xD5', '\xD6', '\xD7', '\xD8', '\xD9', '\xDA', ECI, FS, GS, RS, NS, // Note that in original code in Java, NS is not there, which seems to be a bug '\xDB', '\xDC', '\xDD', '\xDE', '\xDF', '\xAA', '\xAC', '\xB1', '\xB2', '\xB3', '\xB5', '\xB9', '\xBA', '\xBC', '\xBD', '\xBE', '\x80', '\x81', '\x82', '\x83', '\x84', '\x85', '\x86', '\x87', '\x88', '\x89', LCHA, '\x20', LOCK, SHI3, SHI4, LCHB, }, { // set 3 '\xE0', '\xE1', '\xE2', '\xE3', '\xE4', '\xE5', '\xE6', '\xE7', '\xE8', '\xE9', '\xEA', '\xEB', '\xEC', '\xED', '\xEE', '\xEF', '\xF0', '\xF1', '\xF2', '\xF3', '\xF4', '\xF5', '\xF6', '\xF7', '\xF8', '\xF9', '\xFA', ECI, FS, GS, RS, NS, '\xFB', '\xFC', '\xFD', '\xFE', '\xFF', '\xA1', '\xA8', '\xAB', '\xAF', '\xB0', '\xB4', '\xB7', '\xB8', '\xBB', '\xBF', '\x8A', '\x8B', '\x8C', '\x8D', '\x8E', '\x8F', '\x90', '\x91', '\x92', '\x93', '\x94', LCHA, '\x20', SHI2, LOCK, SHI4, LCHB, }, { // set 4 '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', '\x09', '\x0A', '\x0B', '\x0C', '\x0D', '\x0E', '\x0F', '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1A', ECI, PAD, PAD, '\x1B', NS, FS, GS, RS, '\x1F', '\x9F', '\xA0', '\xA2', '\xA3', '\xA4', '\xA5', '\xA6', '\xA7', '\xA9', '\xAD', '\xAE', '\xB6', '\x95', '\x96', '\x97', '\x98', '\x99', '\x9A', '\x9B', '\x9C', '\x9D', '\x9E', LCHA, '\x20', SHI2, SHI3, LOCK, LCHB, }, { // set 5 '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', '\x09', '\x0A', '\x0B', '\x0C', '\x0D', '\x0E', '\x0F', '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1A', '\x1B', '\x1C', '\x1D', '\x1E', '\x1F', '\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27', '\x28', '\x29', '\x2A', '\x2B', '\x2C', '\x2D', '\x2E', '\x2F', '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37', '\x38', '\x39', '\x3A', '\x3B', '\x3C', '\x3D', '\x3E', '\x3F', }, }; static int GetBit(int bit, const ByteArray& bytes) { bit--; return (bytes[bit / 6] & (1 << (5 - (bit % 6)))) == 0 ? 0 : 1; } static int GetInt(const ByteArray& bytes, const ByteArray& x) { int len = x.length(); int val = 0; for (int i = 0; i < len; i++) { val += GetBit(x[i], bytes) << (len - i - 1); } return val; } static int GetPostCode2(const ByteArray& bytes) { return GetInt(bytes, { 33, 34, 35, 36, 25, 26, 27, 28, 29, 30, 19, 20, 21, 22, 23, 24, 13, 14, 15, 16, 17, 18, 7, 8, 9, 10, 11, 12, 1, 2 }); } static int GetPostCode2Length(const ByteArray& bytes) { return GetInt(bytes, { 39, 40, 41, 42, 31, 32 }); } static std::string GetPostCode3(const ByteArray& bytes) { return { CHARSETS[0].at(GetInt(bytes, { 39, 40, 41, 42, 31, 32 })), CHARSETS[0].at(GetInt(bytes, { 33, 34, 35, 36, 25, 26 })), CHARSETS[0].at(GetInt(bytes, { 27, 28, 29, 30, 19, 20 })), CHARSETS[0].at(GetInt(bytes, { 21, 22, 23, 24, 13, 14 })), CHARSETS[0].at(GetInt(bytes, { 15, 16, 17, 18, 7, 8 })), CHARSETS[0].at(GetInt(bytes, { 9, 10, 11, 12, 1, 2 })), }; } static std::string ToString(int x, int width) { std::stringstream buf; buf << std::setw(width) << std::setfill('0') << x; return buf.str(); } static int GetCountry(const ByteArray& bytes) { return GetInt(bytes, { 53, 54, 43, 44, 45, 46, 47, 48, 37, 38 }); } static int GetServiceClass(const ByteArray& bytes) { return GetInt(bytes, { 55, 56, 57, 58, 59, 60, 49, 50, 51, 52 }); } static std::string GetMessage(const ByteArray& bytes, int start, int len) { std::string sb; int shift = -1; int set = 0; int lastset = 0; for (int i = start; i < start + len; i++) { char c = CHARSETS[set].at(bytes[i]); switch (c) { case LCHA: set = 0; shift = -1; break; case LCHB: set = 1; shift = -1; break; case SHI0: case SHI1: case SHI2: case SHI3: case SHI4: lastset = set; set = c - SHI0; shift = 1; break; case TWSA: lastset = set; set = 0; shift = 2; break; case TRSA: lastset = set; set = 0; shift = 3; break; case NS: sb.append(ToString((bytes[i+1] << 24) + (bytes[i+2] << 18) + (bytes[i+3] << 12) + (bytes[i+4] << 6) + bytes[i+5], 9)); i += 5; break; case LOCK: shift = -1; break; default: sb.push_back(c); } if (shift-- == 0) { set = lastset; } } while (sb.length() > 0 && sb.at(sb.length() - 1) == PAD) { sb.resize(sb.length() - 1); } return sb; } static DecoderResult Decode(ByteArray&& bytes, int mode) { std::string result; result.reserve(144); switch (mode) { case 2: case 3: { auto postcode = mode == 2 ? ToString(GetPostCode2(bytes), GetPostCode2Length(bytes)) : GetPostCode3(bytes); auto country = ToString(GetCountry(bytes), 3); auto service = ToString(GetServiceClass(bytes), 3); result.append(GetMessage(bytes, 10, 84)); if (result.compare(0, 7, std::string("[)>") + RS + std::string("01") + GS) == 0) { result.insert(9, postcode + GS + country + GS + service + GS); } else { result.insert(0, postcode + GS + country + GS + service + GS); } break; } case 4: result.append(GetMessage(bytes, 1, 93)); break; case 5: result.append(GetMessage(bytes, 1, 77)); break; } return DecoderResult(std::move(bytes), TextDecoder::FromLatin1(result)).setEcLevel(std::to_wstring(mode)); // really??? } } // DecodedBitStreamParser DecoderResult Decoder::Decode(const BitMatrix& bits) { ByteArray codewords = BitMatrixParser::ReadCodewords(bits); if (!CorrectErrors(codewords, 0, 10, 10, ALL)) { return DecodeStatus::ChecksumError; } int mode = codewords[0] & 0x0F; ByteArray datawords; switch (mode) { case 2: case 3: case 4: if (CorrectErrors(codewords, 20, 84, 40, EVEN) && CorrectErrors(codewords, 20, 84, 40, ODD)) { datawords.resize(94, 0); } else { return DecodeStatus::ChecksumError; } break; case 5: if (CorrectErrors(codewords, 20, 68, 56, EVEN) && CorrectErrors(codewords, 20, 68, 56, ODD)) { datawords.resize(78, 0); } else { return DecodeStatus::ChecksumError; } break; default: return DecodeStatus::FormatError; } std::copy_n(codewords.begin(), 10, datawords.begin()); std::copy_n(codewords.begin() + 20, datawords.size() - 10, datawords.begin() + 10); return DecodedBitStreamParser::Decode(std::move(datawords), mode); } } // MaxiCode } // ZXing
32.978056
211
0.545342
emarc99
2caeace24a8b6ba44157289ba3753368b9eb3993
16,647
cpp
C++
external/sbml/annotation/test/TestRDFAnnotation.cpp
dchandran/evolvenetworks
072f9e1292552f691a86457ffd16a5743724fb5e
[ "BSD-3-Clause" ]
1
2019-08-22T17:17:41.000Z
2019-08-22T17:17:41.000Z
external/sbml/annotation/test/TestRDFAnnotation.cpp
dchandran/evolvenetworks
072f9e1292552f691a86457ffd16a5743724fb5e
[ "BSD-3-Clause" ]
null
null
null
external/sbml/annotation/test/TestRDFAnnotation.cpp
dchandran/evolvenetworks
072f9e1292552f691a86457ffd16a5743724fb5e
[ "BSD-3-Clause" ]
null
null
null
/** * \file TestRDFAnnotation.cpp * \brief fomula units data unit tests * \author Ben Bornstein * * $Id: TestRDFAnnotation.cpp 10125 2009-08-28 12:14:18Z sarahkeating $ * $HeadURL: https://sbml.svn.sourceforge.net/svnroot/sbml/trunk/libsbml/src/annotation/test/TestRDFAnnotation.cpp $ */ /* Copyright 2002 California Institute of Technology and Japan Science and * Technology Corporation. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation. A copy of the license agreement is * provided in the file named "LICENSE.txt" included with this software * distribution. It is also available online at * http://sbml.org/software/libsbml/license.html * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <sbml/common/common.h> #include <sbml/common/extern.h> #include <sbml/SBMLReader.h> #include <sbml/SBMLTypes.h> #include <sbml/SBMLDocument.h> #include <sbml/Model.h> #include <sbml/SBMLTypeCodes.h> #include <sbml/annotation/RDFAnnotation.h> #include <sbml/annotation/ModelHistory.h> #include <check.h> LIBSBML_CPP_NAMESPACE_USE static Model *m; static SBMLDocument* d; extern char *TestDataDirectory; /* * tests the results from rdf annotations */ CK_CPPSTART void RDFAnnotation_setup (void) { char *filename = safe_strcat(TestDataDirectory, "annotation.xml"); // The following will return a pointer to a new SBMLDocument. d = readSBML(filename); m = d->getModel(); } void RDFAnnotation_teardown (void) { delete d; } static bool equals (const char* expected, const char* actual) { if ( !strcmp(expected, actual) ) return true; printf( "\nStrings are not equal:\n" ); printf( "Expected:\n[%s]\n", expected ); printf( "Actual:\n[%s]\n" , actual ); return false; } START_TEST (test_RDFAnnotation_getModelHistory) { fail_if(m == 0); ModelHistory * history = m->getModelHistory(); fail_unless(history != NULL); ModelCreator * mc = (ModelCreator * )(history->getCreator(0)); fail_unless(!strcmp(ModelCreator_getFamilyName(mc), "Le Novere")); fail_unless(!strcmp(ModelCreator_getGivenName(mc), "Nicolas")); fail_unless(!strcmp(ModelCreator_getEmail(mc), "lenov@ebi.ac.uk")); fail_unless(!strcmp(ModelCreator_getOrganisation(mc), "EMBL-EBI")); Date * date = history->getCreatedDate(); fail_unless(Date_getYear(date) == 2005); fail_unless(Date_getMonth(date) == 2); fail_unless(Date_getDay(date) == 2); fail_unless(Date_getHour(date) == 14); fail_unless(Date_getMinute(date) == 56); fail_unless(Date_getSecond(date) == 11); fail_unless(Date_getSignOffset(date) == 0); fail_unless(Date_getHoursOffset(date) == 0); fail_unless(Date_getMinutesOffset(date) == 0); fail_unless(!strcmp(Date_getDateAsString(date), "2005-02-02T14:56:11Z")); date = history->getModifiedDate(); fail_unless(Date_getYear(date) == 2006); fail_unless(Date_getMonth(date) == 5); fail_unless(Date_getDay(date) == 30); fail_unless(Date_getHour(date) == 10); fail_unless(Date_getMinute(date) == 46); fail_unless(Date_getSecond(date) == 2); fail_unless(Date_getSignOffset(date) == 0); fail_unless(Date_getHoursOffset(date) == 0); fail_unless(Date_getMinutesOffset(date) == 0); fail_unless(!strcmp(Date_getDateAsString(date), "2006-05-30T10:46:02Z")); } END_TEST START_TEST (test_RDFAnnotation_parseModelHistory) { XMLNode* node = RDFAnnotationParser::parseModelHistory(m); fail_unless(node->getNumChildren() == 1); const XMLNode_t* rdf = XMLNode_getChild(node, 0); fail_unless(!strcmp(XMLNode_getName(rdf), "RDF")); fail_unless(!strcmp(XMLNode_getPrefix(rdf), "rdf")); fail_unless(!strcmp(XMLNode_getURI(rdf), "http://www.w3.org/1999/02/22-rdf-syntax-ns#")); fail_unless(XMLNode_getNumChildren(rdf) == 1); const XMLNode_t* desc = XMLNode_getChild(rdf, 0); fail_unless(!strcmp(XMLNode_getName(desc), "Description")); fail_unless(!strcmp(XMLNode_getPrefix(desc), "rdf")); fail_unless(!strcmp(XMLNode_getURI(desc), "http://www.w3.org/1999/02/22-rdf-syntax-ns#")); fail_unless(XMLNode_getNumChildren(desc) == 3); const XMLNode_t * creator = XMLNode_getChild(desc, 0); fail_unless(!strcmp(XMLNode_getName(creator), "creator")); fail_unless(!strcmp(XMLNode_getPrefix(creator), "dc")); fail_unless(!strcmp(XMLNode_getURI(creator), "http://purl.org/dc/elements/1.1/")); fail_unless(XMLNode_getNumChildren(creator) == 1); const XMLNode_t * Bag = XMLNode_getChild(creator, 0); fail_unless(!strcmp(XMLNode_getName(Bag), "Bag")); fail_unless(!strcmp(XMLNode_getPrefix(Bag), "rdf")); fail_unless(!strcmp(XMLNode_getURI(Bag), "http://www.w3.org/1999/02/22-rdf-syntax-ns#")); fail_unless(XMLNode_getNumChildren(Bag) == 1); const XMLNode_t * li = XMLNode_getChild(Bag, 0); fail_unless(!strcmp(XMLNode_getName(li), "li")); fail_unless(!strcmp(XMLNode_getPrefix(li), "rdf")); fail_unless(!strcmp(XMLNode_getURI(li), "http://www.w3.org/1999/02/22-rdf-syntax-ns#")); fail_unless(XMLNode_getNumChildren(li) == 3); const XMLNode_t *N = XMLNode_getChild(li, 0); fail_unless(!strcmp(XMLNode_getName(N), "N")); fail_unless(!strcmp(XMLNode_getPrefix(N), "vCard")); fail_unless(!strcmp(XMLNode_getURI(N), "http://www.w3.org/2001/vcard-rdf/3.0#")); fail_unless(XMLNode_getNumChildren(N) == 2); const XMLNode_t *Family = XMLNode_getChild(N, 0); fail_unless(!strcmp(XMLNode_getName(Family), "Family")); fail_unless(!strcmp(XMLNode_getPrefix(Family), "vCard")); fail_unless(!strcmp(XMLNode_getURI(Family), "http://www.w3.org/2001/vcard-rdf/3.0#")); fail_unless(XMLNode_getNumChildren(Family) == 1); const XMLNode_t *Given = XMLNode_getChild(N, 1); fail_unless(!strcmp(XMLNode_getName(Given), "Given")); fail_unless(!strcmp(XMLNode_getPrefix(Given), "vCard")); fail_unless(!strcmp(XMLNode_getURI(Given), "http://www.w3.org/2001/vcard-rdf/3.0#")); fail_unless(XMLNode_getNumChildren(Given) == 1); const XMLNode_t *EMAIL = XMLNode_getChild(li, 1); fail_unless(!strcmp(XMLNode_getName(EMAIL), "EMAIL")); fail_unless(!strcmp(XMLNode_getPrefix(EMAIL), "vCard")); fail_unless(!strcmp(XMLNode_getURI(EMAIL), "http://www.w3.org/2001/vcard-rdf/3.0#")); fail_unless(XMLNode_getNumChildren(EMAIL) == 1); const XMLNode_t *ORG = XMLNode_getChild(li, 2); fail_unless(!strcmp(XMLNode_getName(ORG), "ORG")); fail_unless(!strcmp(XMLNode_getPrefix(ORG), "vCard")); fail_unless(!strcmp(XMLNode_getURI(ORG), "http://www.w3.org/2001/vcard-rdf/3.0#")); fail_unless(XMLNode_getNumChildren(ORG) == 1); const XMLNode_t *Orgname = XMLNode_getChild(ORG, 0); fail_unless(!strcmp(XMLNode_getName(Orgname), "Orgname")); fail_unless(!strcmp(XMLNode_getPrefix(Orgname), "vCard")); fail_unless(!strcmp(XMLNode_getURI(Orgname), "http://www.w3.org/2001/vcard-rdf/3.0#")); fail_unless(XMLNode_getNumChildren(Orgname) == 1); const XMLNode_t * created = XMLNode_getChild(desc, 1); fail_unless(!strcmp(XMLNode_getName(created), "created")); fail_unless(!strcmp(XMLNode_getPrefix(created), "dcterms")); fail_unless(!strcmp(XMLNode_getURI(created), "http://purl.org/dc/terms/")); fail_unless(XMLNode_getNumChildren(created) == 1); const XMLNode_t * cr_date = XMLNode_getChild(created, 0); fail_unless(!strcmp(XMLNode_getName(cr_date), "W3CDTF")); fail_unless(!strcmp(XMLNode_getPrefix(cr_date), "dcterms")); fail_unless(!strcmp(XMLNode_getURI(cr_date), "http://purl.org/dc/terms/")); fail_unless(XMLNode_getNumChildren(cr_date) == 1); const XMLNode_t * modified = XMLNode_getChild(desc, 2); fail_unless(!strcmp(XMLNode_getName(modified), "modified")); fail_unless(!strcmp(XMLNode_getPrefix(modified), "dcterms")); fail_unless(!strcmp(XMLNode_getURI(modified), "http://purl.org/dc/terms/")); fail_unless(XMLNode_getNumChildren(modified) == 1); const XMLNode_t * mo_date = XMLNode_getChild(created, 0); fail_unless(!strcmp(XMLNode_getName(mo_date), "W3CDTF")); fail_unless(!strcmp(XMLNode_getPrefix(mo_date), "dcterms")); fail_unless(!strcmp(XMLNode_getURI(mo_date), "http://purl.org/dc/terms/")); fail_unless(XMLNode_getNumChildren(mo_date) == 1); delete node; } END_TEST START_TEST (test_RDFAnnotation_parseCVTerms) { XMLNode* node = RDFAnnotationParser::parseCVTerms(m->getCompartment(0)); fail_unless(node->getNumChildren() == 1); const XMLNode_t* rdf = XMLNode_getChild(node, 0); fail_unless(!strcmp(XMLNode_getName(rdf), "RDF")); fail_unless(!strcmp(XMLNode_getPrefix(rdf), "rdf")); fail_unless(!strcmp(XMLNode_getURI(rdf), "http://www.w3.org/1999/02/22-rdf-syntax-ns#")); fail_unless(XMLNode_getNumChildren(rdf) == 1); const XMLNode_t* desc = XMLNode_getChild(rdf, 0); fail_unless(!strcmp(XMLNode_getName(desc), "Description")); fail_unless(!strcmp(XMLNode_getPrefix(desc), "rdf")); fail_unless(!strcmp(XMLNode_getURI(desc), "http://www.w3.org/1999/02/22-rdf-syntax-ns#")); fail_unless(XMLNode_getNumChildren(desc) == 1); const XMLNode_t * is1 = XMLNode_getChild(desc, 0); fail_unless(!strcmp(XMLNode_getName(is1), "is")); fail_unless(!strcmp(XMLNode_getPrefix(is1), "bqbiol")); fail_unless(XMLNode_getNumChildren(is1) == 1); const XMLNode_t * Bag = XMLNode_getChild(is1, 0); fail_unless(!strcmp(XMLNode_getName(Bag), "Bag")); fail_unless(!strcmp(XMLNode_getPrefix(Bag), "rdf")); fail_unless(!strcmp(XMLNode_getURI(Bag), "http://www.w3.org/1999/02/22-rdf-syntax-ns#")); fail_unless(XMLNode_getNumChildren(Bag) == 4); const XMLNode_t * li = XMLNode_getChild(Bag, 0); fail_unless(!strcmp(XMLNode_getName(li), "li")); fail_unless(!strcmp(XMLNode_getPrefix(li), "rdf")); fail_unless(!strcmp(XMLNode_getURI(li), "http://www.w3.org/1999/02/22-rdf-syntax-ns#")); fail_unless(XMLNode_getNumChildren(li) == 0); const XMLNode_t * li1 = XMLNode_getChild(Bag, 1); fail_unless(!strcmp(XMLNode_getName(li1), "li")); fail_unless(!strcmp(XMLNode_getPrefix(li1), "rdf")); fail_unless(!strcmp(XMLNode_getURI(li1), "http://www.w3.org/1999/02/22-rdf-syntax-ns#")); fail_unless(XMLNode_getNumChildren(li1) == 0); const XMLNode_t * li2 = XMLNode_getChild(Bag, 2); fail_unless(!strcmp(XMLNode_getName(li2), "li")); fail_unless(!strcmp(XMLNode_getPrefix(li2), "rdf")); fail_unless(!strcmp(XMLNode_getURI(li2), "http://www.w3.org/1999/02/22-rdf-syntax-ns#")); fail_unless(XMLNode_getNumChildren(li2) == 0); const XMLNode_t * li3 = XMLNode_getChild(Bag, 3); fail_unless(!strcmp(XMLNode_getName(li3), "li")); fail_unless(!strcmp(XMLNode_getPrefix(li3), "rdf")); fail_unless(!strcmp(XMLNode_getURI(li3), "http://www.w3.org/1999/02/22-rdf-syntax-ns#")); fail_unless(XMLNode_getNumChildren(li3) == 0); delete node; } END_TEST START_TEST (test_RDFAnnotation_delete) { XMLNode* node = RDFAnnotationParser::parseCVTerms(m->getCompartment(0)); XMLNode* n1 = RDFAnnotationParser::deleteRDFAnnotation(node); const char * expected = "<annotation/>"; fail_unless(n1->getNumChildren() == 0); fail_unless(n1->getName() == "annotation"); fail_unless( equals(expected, n1->toXMLString().c_str()) ); delete node; } END_TEST START_TEST (test_RDFAnnotation_deleteWithOther) { Compartment* c = m->getCompartment(1); XMLNode* node = RDFAnnotationParser::deleteRDFAnnotation(c->getAnnotation()); const char * expected = "<annotation>\n" " <jd2:JDesignerLayout version=\"2.0\" MajorVersion=\"2\" MinorVersion=\"0\" BuildVersion=\"41\">\n" " <jd2:header>\n" " <jd2:VersionHeader JDesignerVersion=\"2.0\"/>\n" " <jd2:ModelHeader Author=\"Mr Untitled\" ModelVersion=\"0.0\" ModelTitle=\"untitled\"/>\n" " <jd2:TimeCourseDetails timeStart=\"0\" timeEnd=\"10\" numberOfPoints=\"1000\"/>\n" " </jd2:header>\n" " </jd2:JDesignerLayout>\n" "</annotation>"; fail_unless( equals(expected,node->toXMLString().c_str()) ); } END_TEST START_TEST (test_RDFAnnotation_recreate) { Compartment* c = m->getCompartment(1); const char * expected = "<compartment id=\"A\">\n" " <annotation>\n" " <jd2:JDesignerLayout version=\"2.0\" MajorVersion=\"2\" MinorVersion=\"0\" BuildVersion=\"41\">\n" " <jd2:header>\n" " <jd2:VersionHeader JDesignerVersion=\"2.0\"/>\n" " <jd2:ModelHeader Author=\"Mr Untitled\" ModelVersion=\"0.0\" ModelTitle=\"untitled\"/>\n" " <jd2:TimeCourseDetails timeStart=\"0\" timeEnd=\"10\" numberOfPoints=\"1000\"/>\n" " </jd2:header>\n" " </jd2:JDesignerLayout>\n" " <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:vCard=\"http://www.w3.org/2001/vcard-rdf/3.0#\" xmlns:bqbiol=\"http://biomodels.net/biology-qualifiers/\" xmlns:bqmodel=\"http://biomodels.net/model-qualifiers/\">\n" " <rdf:Description rdf:about=\"#\">\n" " <bqbiol:is>\n" " <rdf:Bag>\n" " <rdf:li rdf:resource=\"http://www.geneontology.org/#GO:0007274\"/>\n" " </rdf:Bag>\n" " </bqbiol:is>\n" " </rdf:Description>\n" " </rdf:RDF>\n" " </annotation>\n" "</compartment>"; fail_unless( equals(expected, c->toSBML()) ); } END_TEST START_TEST (test_RDFAnnotation_recreateFromEmpty) { Compartment* c = m->getCompartment(3); const char * expected = "<compartment id=\"C\">\n" " <annotation>\n" " <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:vCard=\"http://www.w3.org/2001/vcard-rdf/3.0#\" xmlns:bqbiol=\"http://biomodels.net/biology-qualifiers/\" xmlns:bqmodel=\"http://biomodels.net/model-qualifiers/\">\n" " <rdf:Description rdf:about=\"#\">\n" " <bqbiol:is>\n" " <rdf:Bag>\n" " <rdf:li rdf:resource=\"http://www.geneontology.org/#GO:0007274\"/>\n" " </rdf:Bag>\n" " </bqbiol:is>\n" " </rdf:Description>\n" " </rdf:RDF>\n" " </annotation>\n" "</compartment>"; fail_unless( equals(expected, c->toSBML()) ); } END_TEST START_TEST (test_RDFAnnotation_deleteWithOutOther) { Compartment* c = m->getCompartment(2); XMLNode* node = c->getAnnotation(); const char * expected = "<annotation>\n" " <jd2:JDesignerLayout version=\"2.0\" MajorVersion=\"2\" MinorVersion=\"0\" BuildVersion=\"41\">\n" " <jd2:header>\n" " <jd2:VersionHeader JDesignerVersion=\"2.0\"/>\n" " <jd2:ModelHeader Author=\"Mr Untitled\" ModelVersion=\"0.0\" ModelTitle=\"untitled\"/>\n" " <jd2:TimeCourseDetails timeStart=\"0\" timeEnd=\"10\" numberOfPoints=\"1000\"/>\n" " </jd2:header>\n" " </jd2:JDesignerLayout>\n" "</annotation>"; fail_unless( equals(expected, node->toXMLString().c_str()) ); } END_TEST START_TEST (test_RDFAnnotation_recreateWithOutOther) { Compartment* c = m->getCompartment(2); const char * expected = "<compartment id=\"B\">\n" " <annotation>\n" " <jd2:JDesignerLayout version=\"2.0\" MajorVersion=\"2\" MinorVersion=\"0\" BuildVersion=\"41\">\n" " <jd2:header>\n" " <jd2:VersionHeader JDesignerVersion=\"2.0\"/>\n" " <jd2:ModelHeader Author=\"Mr Untitled\" ModelVersion=\"0.0\" ModelTitle=\"untitled\"/>\n" " <jd2:TimeCourseDetails timeStart=\"0\" timeEnd=\"10\" numberOfPoints=\"1000\"/>\n" " </jd2:header>\n" " </jd2:JDesignerLayout>\n" " </annotation>\n" "</compartment>"; fail_unless( equals(expected, c->toSBML()) ); } END_TEST Suite * create_suite_RDFAnnotation (void) { Suite *suite = suite_create("RDFAnnotation"); TCase *tcase = tcase_create("RDFAnnotation"); tcase_add_checked_fixture(tcase, RDFAnnotation_setup, RDFAnnotation_teardown); tcase_add_test(tcase, test_RDFAnnotation_getModelHistory ); tcase_add_test(tcase, test_RDFAnnotation_parseModelHistory ); tcase_add_test(tcase, test_RDFAnnotation_parseCVTerms ); tcase_add_test(tcase, test_RDFAnnotation_delete ); tcase_add_test(tcase, test_RDFAnnotation_deleteWithOther ); tcase_add_test(tcase, test_RDFAnnotation_recreate ); tcase_add_test(tcase, test_RDFAnnotation_recreateFromEmpty ); tcase_add_test(tcase, test_RDFAnnotation_deleteWithOutOther ); tcase_add_test(tcase, test_RDFAnnotation_recreateWithOutOther ); suite_add_tcase(suite, tcase); return suite; } CK_CPPEND
36.426696
336
0.698985
dchandran
2caffe97249eed511b7f5a9ee7f0aa9e296ee893
6,582
cpp
C++
Ouroboros/Source/oGUI/menu.cpp
igHunterKiller/ouroboros
5e2cde7e6365341da297da10d8927b091ecf5559
[ "MIT" ]
null
null
null
Ouroboros/Source/oGUI/menu.cpp
igHunterKiller/ouroboros
5e2cde7e6365341da297da10d8927b091ecf5559
[ "MIT" ]
null
null
null
Ouroboros/Source/oGUI/menu.cpp
igHunterKiller/ouroboros
5e2cde7e6365341da297da10d8927b091ecf5559
[ "MIT" ]
null
null
null
// Copyright (c) 2016 Antony Arciuolo. See License.txt regarding use. #include <oGUI/menu.h> #include <oCore/assert.h> #include <oSystem/windows/win_error.h> namespace ouro { namespace gui { namespace menu { #if 0 // not in use (yet?) static int find_position(menu_handle parent, int item) { const int n = num_items(parent); for (int i = 0; i < n; i++) { int ID = GetMenuItemID(parent, i); if (ID == item) return i; } return invalid; } #endif static int find_position(menu_handle parent, menu_handle submenu) { const int n = GetMenuItemCount((HMENU)parent); for (int i = 0; i < n; i++) { menu_handle hSubmenu = (menu_handle)GetSubMenu((HMENU)parent, i); if (hSubmenu == submenu) return i; } return -1; } #if oHAS_oASSERT // Returns true if the specified menu contains all IDs [first,last] static bool contains_range(menu_handle m, int item_range_first, int item_range_last) { MENUITEMINFO mii; mii.cbSize = sizeof(MENUITEMINFO); mii.fMask = MIIM_ID; int nFound = 0; const int n = num_items(m); for (int i = 0; i < n; i++) { UINT uID = GetMenuItemID((HMENU)m, i); if (uID == ~0u) return false; int ID = (int)uID; if (ID >= item_range_first && ID <= item_range_last) nFound++; } return nFound == (item_range_last - item_range_first + 1); } #endif char* get_text_by_position(char* out_text, size_t out_text_size, menu_handle m, int item_position) { if (!GetMenuStringA((HMENU)m, item_position, out_text, (int)out_text_size, MF_BYPOSITION)) return nullptr; return out_text; } menu_handle make_menu(bool top_level) { return (menu_handle)(top_level ? CreateMenu() : CreatePopupMenu()); } void unmake_menu(menu_handle m) { if (IsMenu((HMENU)m)) oVB(DestroyMenu((HMENU)m)); } void attach(window_handle _hWindow, menu_handle m) { oVB(SetMenu((HWND)_hWindow, (HMENU)m)); } int num_items(menu_handle m) { return GetMenuItemCount((HMENU)m); } void append_submenu(menu_handle parent, menu_handle submenu, const char* text) { oVB(AppendMenu((HMENU)parent, MF_STRING|MF_POPUP, (UINT_PTR)submenu, text)); } void remove_submenu(menu_handle parent, menu_handle submenu) { int p = find_position(parent, submenu); if (p != -1 && !RemoveMenu((HMENU)parent, p, MF_BYPOSITION)) { DWORD hr = GetLastError(); if (GetLastError() != ERROR_RESOURCE_TYPE_NOT_FOUND) oV(hr); } } void replace_item_with_submenu(menu_handle parent, int item, menu_handle submenu) { mstring text; if (!get_text(text, parent, item)) oThrow(std::errc::invalid_argument, ""); oVB(RemoveMenu((HMENU)parent, item, MF_BYCOMMAND)); oVB(InsertMenu((HMENU)parent, item, MF_STRING|MF_POPUP, (UINT_PTR)submenu, text)); } void replace_submenu_with_item(menu_handle parent, menu_handle submenu, int item, bool enabled) { int p = find_position(parent, submenu); oAssert(p != -1, "the specified submenu is not under the specified parent menu"); mstring text; if (!get_text_by_position(text, text.capacity(), parent, p)) oThrow(std::errc::invalid_argument, ""); oVB(DeleteMenu((HMENU)parent, p, MF_BYPOSITION)); UINT uFlags = MF_BYPOSITION|MF_STRING; if (!enabled) uFlags |= MF_GRAYED; oVB(InsertMenu((HMENU)parent, p, uFlags, (UINT_PTR)item, text.c_str())); } void append_item(menu_handle parent, int item, const char* text) { oVB(AppendMenu((HMENU)parent, MF_STRING, (UINT_PTR)item, text)); } void remove_item(menu_handle parent, int item) { if (!RemoveMenu((HMENU)parent, item, MF_BYCOMMAND)) { DWORD hr = GetLastError(); if (GetLastError() != ERROR_RESOURCE_TYPE_NOT_FOUND) oV(hr); } } void remove_all(menu_handle m) { int n = GetMenuItemCount((HMENU)m); while (n) { DeleteMenu((HMENU)m, n-1, MF_BYPOSITION); n = GetMenuItemCount((HMENU)m); } } void append_separator(menu_handle parent) { oVB(AppendMenu((HMENU)parent, MF_SEPARATOR, 0, nullptr)); } void check(menu_handle m, int item, bool checked) { oAssert(item >= 0, ""); if (-1 == CheckMenuItem((HMENU)m, static_cast<unsigned int>(item), MF_BYCOMMAND | (checked ? MF_CHECKED : MF_UNCHECKED))) oAssert(false, "MenuItemID not found in the specified menu"); } bool checked(menu_handle m, int item) { MENUITEMINFO mii; ZeroMemory(&mii, sizeof(mii)); mii.cbSize = sizeof(mii); mii.fMask = MIIM_STATE; oAssert(item >= 0, ""); if (!GetMenuItemInfo((HMENU)m, static_cast<unsigned int>(item), FALSE, &mii)) return false; if (mii.fState & MFS_CHECKED) return true; return false; } void check_radio(menu_handle m, int item_range_first, int item_range_last, int check_item) { // CheckMenuRadioItem returns false if the menu is wrong, but doesn't set a // useful last error (S_OK is returned when I ran into this) so add our own // check here. oAssert(num_items(m) >= (item_range_last-item_range_first+1), "A radio range was specified that is larger than the number of elements in the list (menu count=%d, range implies %d items)", num_items(m), (item_range_last-item_range_first+1)); oAssert(contains_range(m, item_range_first, item_range_last), "The specified menu 0x%p does not include the specified range [%d,%d] with selected %d. Most API works with an ancestor menu but this requires the immediate parent, so if the ranges look correct check the specified m.", m, item_range_first, item_range_last, check_item); oVB(CheckMenuRadioItem((HMENU)m, item_range_first, item_range_last, check_item, MF_BYCOMMAND)); } int checked_radio(menu_handle m, int item_range_first, int item_range_last) { for (int i = item_range_first; i <= item_range_last; i++) if (checked(m, i)) return i; return -1; } void enable(menu_handle m, int item, bool enabled) { oAssert(item >= 0, ""); if (-1 == EnableMenuItem((HMENU)m, static_cast<unsigned int>(item), MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED))) oAssert(false, "MenuItemID not found in the specified menu"); } bool enabled(menu_handle m, int item) { MENUITEMINFO mii; ZeroMemory(&mii, sizeof(mii)); mii.cbSize = sizeof(mii); mii.fMask = MIIM_STATE; oAssert(item >= 0, ""); oVB(GetMenuItemInfo((HMENU)m, static_cast<unsigned int>(item), FALSE, &mii)); if (mii.fState & (MF_GRAYED|MF_DISABLED)) return false; return true; } char* get_text(char* out_text, size_t out_text_size, menu_handle m, int item) { if (!GetMenuStringA((HMENU)m, item, out_text, (int)out_text_size, MF_BYCOMMAND)) return nullptr; return out_text; } char* get_text(char* out_text, size_t out_text_size, menu_handle parent, menu_handle submenu) { int pos = find_position(parent, submenu); if (pos == -1) return nullptr; return get_text_by_position(out_text, out_text_size, parent, pos); } }}}
27.655462
333
0.721513
igHunterKiller
2cb53b6db898cb0767dee7cc81f220cbab1273e6
3,401
inl
C++
include/IECore/FastFloat.inl
gcodebackups/cortex-vfx
72fa6c6eb3327fce4faf01361c8fcc2e1e892672
[ "BSD-3-Clause" ]
5
2016-07-26T06:09:28.000Z
2022-03-07T03:58:51.000Z
include/IECore/FastFloat.inl
turbosun/cortex
4bdc01a692652cd562f3bfa85f3dae99d07c0b15
[ "BSD-3-Clause" ]
null
null
null
include/IECore/FastFloat.inl
turbosun/cortex
4bdc01a692652cd562f3bfa85f3dae99d07c0b15
[ "BSD-3-Clause" ]
3
2015-03-25T18:45:24.000Z
2020-02-15T15:37:18.000Z
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2010, Image Engine Design Inc. 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 Image Engine Design nor the names of any // other contributors to this software 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 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. // ////////////////////////////////////////////////////////////////////////// #ifndef IE_CORE_FASTFLOAT_INL #define IE_CORE_FASTFLOAT_INL namespace IECore { #define IECORE_DOUBLEMAGICROUNDEPS (.5-1.4e-11) #if (defined(__linux__) && ( defined(__i386__) || defined(__x86_64__) ) ) || defined(WIN32) #define IECORE_DOUBLEMAGIC double (6755399441055744.0) inline int fastFloat2Int( double v ) { return ( v < 0.0 ) ? fastFloatRound( v + IECORE_DOUBLEMAGICROUNDEPS ) : fastFloatRound(v-IECORE_DOUBLEMAGICROUNDEPS ); } union FastFloatDoubleLong { double d; long l; }; inline int fastFloatRound( double v ) { FastFloatDoubleLong vv; vv.d = v + IECORE_DOUBLEMAGIC; return vv.l; } inline int fastFloatFloor( double v ) { return fastFloatRound( v - IECORE_DOUBLEMAGICROUNDEPS ); } inline int fastFloatCeil( double v ) { return fastFloatRound( v + IECORE_DOUBLEMAGICROUNDEPS ); } union FastFloatFloatInt { float f; int i; }; // From: http://www.beyond3d.com/articles/fastinvsqrt/ inline float fastFloatInvSqrt( float x ) { float xhalf = 0.5f * x; FastFloatFloatInt u; u.f = x; u.i = 0x5f3759df - (u.i >> 1 ); x = u.f; x = x*(1.5f - xhalf*x*x); return x; } #else inline int fastFloat2Int( double v ) { return (int)v; } inline int fastFloatRound( double v ) { return int( v+IECORE_DOUBLEMAGICROUNDEPS ); } inline int fastFloatFloor( double v ) { return (int)floorf( v ); } inline int fastFloatCeil( double v ) { return (int)ceilf( v ); } inline float fastFloatInvSqrt( float x ) { return 1.0f / sqrtf(x); } #endif } // namespace IECore #endif // IE_CORE_FASTFLOAT_INL
27.427419
121
0.68127
gcodebackups
2cb716fccda08419a28cc4b10ce7141c47468a28
3,110
cc
C++
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_model_engine/calc_astid.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_model_engine/calc_astid.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_model_engine/calc_astid.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
#ifndef INCLUDED_STDDEFX #include "stddefx.h" #define INCLUDED_STDDEFX #endif #ifndef INCLUDED_CALC_ASTID #include "calc_astid.h" #define INCLUDED_CALC_ASTID #endif // Library headers. // PCRaster library headers. // Module headers. #ifndef INCLUDED_CALC_QUOTE #include "calc_quote.h" #define INCLUDED_CALC_QUOTE #endif #ifndef INCLUDED_COM_STRCONV #include "com_strconv.h" #define INCLUDED_COM_STRCONV #endif #ifndef INCLUDED_CALC_ID #include "calc_id.h" #define INCLUDED_CALC_ID #endif /*! \file This file contains the implementation of the ASTId class. */ //------------------------------------------------------------------------------ /* namespace calc { class ASTIdPrivate { public: ASTIdPrivate() { } ~ASTIdPrivate() { } }; } // namespace calc */ //------------------------------------------------------------------------------ // DEFINITION OF STATIC ASTID MEMBERS //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // DEFINITION OF ASTID MEMBERS //------------------------------------------------------------------------------ calc::ASTId::ASTId() { setNrReturns(1); } calc::ASTId::ASTId(const std::string& name): d_name(name) { setNrReturns(1); } calc::ASTId::ASTId(const Id& id): d_name(id.name()) { setPosition(id.position()); setNrReturns(1); } calc::ASTId::~ASTId() { } //! Assignment operator. calc::ASTId& calc::ASTId::operator=(const ASTId& rhs) { if (this != &rhs) { setName(rhs.name()); setPosition(rhs.position()); } return *this; } //! Copy constructor. calc::ASTId::ASTId(const ASTId& rhs): ASTNode(rhs), d_name(rhs.d_name) { } //! set name void calc::ASTId::setName(const std::string& newName) { // When turning on some syntax errors generate failure: // DEVELOP_PRECOND(!newName.empty()); d_name=newName; } //! name of symbol const std::string& calc::ASTId::name() const { // When turning on some syntax errors generate failure: // DEVELOP_PRECOND(!d_name.empty()); return d_name; } //! as name(), surrounded with single quotes std::string calc::ASTId::qName() const { return quote(name()); } bool calc::ASTId::isNumber() const { return com::isDouble(name()); } double calc::ASTId::toNumber() const { return com::fromString<double>(name()); } //! only for debug purposes to check if already initialized with a name bool calc::ASTId::debugOnlyValid() const { return !d_name.empty(); } bool calc::operator<(const ASTId& lhs, const ASTId& rhs) { return lhs.name() < rhs.name(); } bool calc::operator==(const ASTId& lhs, const ASTId& rhs) { return lhs.name() == rhs.name(); } //------------------------------------------------------------------------------ // DEFINITION OF FREE OPERATORS //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // DEFINITION OF FREE FUNCTIONS //------------------------------------------------------------------------------
18.294118
80
0.526688
quanpands
2cb72f3d5e61bd976d875bc823bd7eb18db6b045
866
cpp
C++
Codeforces/Gym101002C.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
18
2019-01-01T13:16:59.000Z
2022-02-28T04:51:50.000Z
Codeforces/Gym101002C.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
null
null
null
Codeforces/Gym101002C.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
5
2019-09-13T08:48:17.000Z
2022-02-19T06:59:03.000Z
#include <bits/stdc++.h> #define MAXN 16 using namespace std; int n,k,w[MAXN],h[MAXN],q[MAXN]; long long dp[MAXN][1<<MAXN],mw[1<<MAXN],mh[1<<MAXN],cnt[1<<MAXN],all[1<<MAXN]; long long v[1<<MAXN],ans=~(1LL<<63); int main() { memset(dp,0x3f,sizeof dp);dp[0][0]=0; scanf("%d %d",&n,&k); for (int i=0;i<n;i++) scanf("%d %d %d",&w[i],&h[i],&q[i]); for (int i=0;i<(1<<n);i++) { for (int j=0;j<n;j++) if (i&(1<<j)) { mw[i]=max(mw[i],(long long)w[j]); mh[i]=max(mh[i],(long long)h[j]); all[i]+=1LL*w[j]*h[j]*q[j]; cnt[i]+=q[j]; } v[i]=mw[i]*mh[i]*cnt[i]-all[i]; } for (int i=1;i<=k;i++) for (int sta=0;sta<(1<<n);sta++) { long long t=0x3f3f3f3f3f3f3f3fLL; for (int j=sta;j;j=(j-1)&sta) t=min(t,dp[i-1][sta-j]+v[j]); dp[i][sta]=t; } for (int i=0;i<=k;i++) ans=min(ans,dp[i][(1<<n)-1]); printf("%lld\n",ans); return 0; }
24.055556
78
0.515012
HeRaNO
2cb936c9997e65bb6cdfc2d04b81b9a9838050ab
6,666
cpp
C++
qt-creator-opensource-src-4.6.1/tests/unit/unittest/clangtranslationunit-test.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
5
2018-12-22T14:49:13.000Z
2022-01-13T07:21:46.000Z
qt-creator-opensource-src-4.6.1/tests/unit/unittest/clangtranslationunit-test.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
null
null
null
qt-creator-opensource-src-4.6.1/tests/unit/unittest/clangtranslationunit-test.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
8
2018-07-17T03:55:48.000Z
2021-12-22T06:37:53.000Z
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "googletest.h" #include <clangtranslationunit.h> #include <clangtranslationunitupdater.h> #include <diagnosticcontainer.h> #include <utf8string.h> #include <clang-c/Index.h> using ClangBackEnd::DiagnosticContainer; using ClangBackEnd::TranslationUnit; using ClangBackEnd::TranslationUnitUpdateInput; using ClangBackEnd::TranslationUnitUpdateResult; using testing::ContainerEq; using testing::Eq; namespace { class TranslationUnit : public ::testing::Test { protected: void SetUp() override; void TearDown() override; void parse(); void reparse(); DiagnosticContainer createDiagnostic(const QString &text, ClangBackEnd::DiagnosticSeverity severity, uint line, uint column, const QString &filePath) const; QVector<DiagnosticContainer> diagnosticsFromMainFile() const; QVector<DiagnosticContainer> errorDiagnosticsFromHeaders() const; protected: Utf8String sourceFilePath = Utf8StringLiteral(TESTDATA_DIR"/diagnostic_erroneous_source.cpp"); Utf8String headerFilePath = Utf8StringLiteral(TESTDATA_DIR"/diagnostic_erroneous_header.h"); CXIndex cxIndex = nullptr; CXTranslationUnit cxTranslationUnit = nullptr; ::TranslationUnit translationUnit{Utf8String(), sourceFilePath, cxIndex, cxTranslationUnit}; DiagnosticContainer extractedFirstHeaderErrorDiagnostic; QVector<DiagnosticContainer> extractedMainFileDiagnostics; }; using TranslationUnitSlowTest = TranslationUnit; TEST_F(TranslationUnitSlowTest, HasExpectedMainFileDiagnostics) { translationUnit.extractDiagnostics(extractedFirstHeaderErrorDiagnostic, extractedMainFileDiagnostics); ASSERT_THAT(extractedMainFileDiagnostics, ContainerEq(diagnosticsFromMainFile())); } TEST_F(TranslationUnitSlowTest, HasExpectedMainFileDiagnosticsAfterReparse) { reparse(); translationUnit.extractDiagnostics(extractedFirstHeaderErrorDiagnostic, extractedMainFileDiagnostics); ASSERT_THAT(extractedMainFileDiagnostics, ContainerEq(diagnosticsFromMainFile())); } TEST_F(TranslationUnitSlowTest, HasErrorDiagnosticsInHeaders) { translationUnit.extractDiagnostics(extractedFirstHeaderErrorDiagnostic, extractedMainFileDiagnostics); ASSERT_THAT(extractedFirstHeaderErrorDiagnostic, Eq(errorDiagnosticsFromHeaders().first())); } TEST_F(TranslationUnitSlowTest, HasErrorDiagnosticsInHeadersAfterReparse) { reparse(); translationUnit.extractDiagnostics(extractedFirstHeaderErrorDiagnostic, extractedMainFileDiagnostics); ASSERT_THAT(extractedFirstHeaderErrorDiagnostic, Eq(errorDiagnosticsFromHeaders().first())); } void TranslationUnit::SetUp() { parse(); } void TranslationUnit::TearDown() { clang_disposeTranslationUnit(cxTranslationUnit); clang_disposeIndex(cxIndex); } void TranslationUnit::parse() { TranslationUnitUpdateInput parseInput; parseInput.filePath = sourceFilePath; parseInput.parseNeeded = true; const TranslationUnitUpdateResult parseResult = translationUnit.update(parseInput); ASSERT_TRUE(parseResult.hasParsed()); } void TranslationUnit::reparse() { TranslationUnitUpdateInput parseInput; parseInput.filePath = sourceFilePath; parseInput.reparseNeeded = true; const TranslationUnitUpdateResult parseResult = translationUnit.update(parseInput); ASSERT_TRUE(parseResult.hasReparsed()); } DiagnosticContainer TranslationUnit::createDiagnostic(const QString &text, ClangBackEnd::DiagnosticSeverity severity, uint line, uint column, const QString &filePath) const { return DiagnosticContainer( text, Utf8StringLiteral(""), {}, severity, {filePath, line, column}, {}, {}, {} ); } QVector<ClangBackEnd::DiagnosticContainer> TranslationUnit::diagnosticsFromMainFile() const { return { createDiagnostic( QStringLiteral("warning: enumeration value 'Three' not handled in switch"), ClangBackEnd::DiagnosticSeverity::Warning, 7, 13, sourceFilePath), createDiagnostic( QStringLiteral("error: void function 'g' should not return a value"), ClangBackEnd::DiagnosticSeverity::Error, 15, 5, sourceFilePath), createDiagnostic( QStringLiteral("warning: using the result of an assignment as a condition without parentheses"), ClangBackEnd::DiagnosticSeverity::Warning, 21, 11, sourceFilePath), }; } QVector<ClangBackEnd::DiagnosticContainer> TranslationUnit::errorDiagnosticsFromHeaders() const { return { createDiagnostic( QStringLiteral("error: C++ requires a type specifier for all declarations"), ClangBackEnd::DiagnosticSeverity::Error, 11, 1, headerFilePath), }; } } // anonymous namespace
33.837563
108
0.663966
kevinlq
2cba4a9acdf0794ca520d5900be289868bff8ea8
5,192
hpp
C++
vlite/strided_ref_vector.hpp
verri/vlite
c4677dad17070b8fb0cbabd06018b3bcbb162860
[ "Zlib" ]
null
null
null
vlite/strided_ref_vector.hpp
verri/vlite
c4677dad17070b8fb0cbabd06018b3bcbb162860
[ "Zlib" ]
null
null
null
vlite/strided_ref_vector.hpp
verri/vlite
c4677dad17070b8fb0cbabd06018b3bcbb162860
[ "Zlib" ]
null
null
null
#ifndef VLITE_STRIDED_REF_VECTOR_HPP_INCLUDED #define VLITE_STRIDED_REF_VECTOR_HPP_INCLUDED #include <vlite/common_vector_base.hpp> #include <vlite/slice.hpp> #include <vlite/strided_iterator.hpp> namespace vlite { template <typename T> class strided_ref_vector : public common_vector_base<strided_ref_vector<T>> { template <typename> friend class strided_ref_vector; public: using value_type = T; using iterator = strided_iterator<T>; using const_iterator = strided_iterator<const T>; using size_type = std::size_t; using difference_type = std::ptrdiff_t; strided_ref_vector(value_type* data, std::size_t size, std::size_t stride) : data_{data} , size_{size} , stride_{stride} { } ~strided_ref_vector() = default; template <typename Vector> auto operator=(const common_vector_base<Vector>& source) -> strided_ref_vector& { static_assert(std::is_assignable_v<value_type&, const typename Vector::value_type&>, "incompatible assignment"); if (source.size() != this->size()) throw std::runtime_error{"sizes mismatch"}; std::copy(source.begin(), source.end(), begin()); return *this; } template <typename U, typename = meta::fallback<CommonVector<U>>> auto operator=(const U& source) -> strided_ref_vector& { static_assert(std::is_assignable<value_type&, U>::value, "incompatible assignment"); std::fill(begin(), end(), source); for (auto& elem : *this) elem = source; return *this; } auto operator=(const strided_ref_vector& source) -> strided_ref_vector& { if (source.size() != size()) throw std::runtime_error{"sizes mismatch"}; std::copy(source.begin(), source.end(), this->begin()); return *this; } operator strided_ref_vector<const value_type>() const { return {data(), size(), stride()}; } auto operator[](size_type i) -> value_type& { assert(i < size()); return data()[i * stride()]; } auto operator[](size_type i) const -> const value_type& { assert(i < size()); return data()[i * stride()]; } auto operator[](every_index) -> strided_ref_vector<value_type> { return *this; } auto operator[](every_index) const -> strided_ref_vector<const value_type> { return *this; } auto operator[](slice s) -> strided_ref_vector<value_type> { assert(s.start < size()); assert(s.start + s.size <= size()); return {data() + s.start * stride_, s.size, stride_}; } auto operator[](slice s) const -> strided_ref_vector<const value_type> { assert(s.start < size()); assert(s.start + s.size <= size()); return {data() + s.start * stride_, s.size, stride_}; } auto operator[](strided_slice s) -> strided_ref_vector<value_type> { assert(s.start < size()); assert(s.start + s.stride * s.size <= size()); return {data() + s.start * stride_, s.size, s.stride * stride_}; } auto operator[](strided_slice s) const -> strided_ref_vector<const value_type> { assert(s.start < size()); assert(s.start + s.stride * s.size <= size()); return {data() + s.start * stride_, s.size, s.stride * stride_}; } auto operator[](bounded_slice s) -> strided_ref_vector<value_type> { assert(s.start < size()); return {data() + s.start * stride_, s.size(size() - s.start), stride_}; } auto operator[](bounded_slice s) const -> strided_ref_vector<const value_type> { assert(s.start < size()); return {data() + s.start * stride_, s.size(size() - s.start), stride_}; } auto operator[](strided_bounded_slice s) -> strided_ref_vector<value_type> { assert(s.start < size()); auto maximum_size = size() - s.start; maximum_size += maximum_size % s.stride == 0u ? 0u : 1u; maximum_size /= s.stride; return {data() + s.start * stride_, s.size(maximum_size), s.stride * stride_}; } auto operator[](strided_bounded_slice s) const -> strided_ref_vector<const value_type> { assert(s.start < size()); auto maximum_size = size() - s.start; maximum_size += maximum_size % s.stride == 0u ? 0u : 1u; maximum_size /= s.stride; return {data() + s.start * stride_, s.size(maximum_size), s.stride * stride_}; } auto begin() noexcept -> iterator { return {data(), stride()}; } auto end() noexcept -> iterator { return {data() + stride() * size(), stride()}; } auto begin() const noexcept -> const_iterator { return cbegin(); } auto end() const noexcept -> const_iterator { return cend(); } auto cbegin() const noexcept -> const_iterator { return {data(), stride()}; } auto cend() const noexcept -> const_iterator { return {data() + stride() * size(), stride()}; } auto size() const noexcept { return size_; } protected: auto data() -> value_type* { return data_; } auto data() const -> const value_type* { return data_; } auto stride() const -> std::size_t { return stride_; } strided_ref_vector(const strided_ref_vector& source) = default; strided_ref_vector(strided_ref_vector&& source) noexcept = default; value_type* data_; std::size_t size_; std::size_t stride_; }; } // namespace vlite #endif // VLITE_STRIDED_REF_VECTOR_HPP_INCLUDED
27.764706
88
0.658128
verri
2cba665570bb385075abcde32c257eaa4c100300
29,839
cpp
C++
camera/ndk/impl/ACameraManager.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
null
null
null
camera/ndk/impl/ACameraManager.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
null
null
null
camera/ndk/impl/ACameraManager.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "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 "ACameraManager" #include <memory> #include "ACameraManager.h" #include "ACameraMetadata.h" #include "ACameraDevice.h" #include <utils/Vector.h> #include <cutils/properties.h> #include <stdlib.h> #include <camera/CameraUtils.h> #include <camera/VendorTagDescriptor.h> using namespace android::acam; namespace android { namespace acam { // Static member definitions const char* CameraManagerGlobal::kCameraIdKey = "CameraId"; const char* CameraManagerGlobal::kPhysicalCameraIdKey = "PhysicalCameraId"; const char* CameraManagerGlobal::kCallbackFpKey = "CallbackFp"; const char* CameraManagerGlobal::kContextKey = "CallbackContext"; const nsecs_t CameraManagerGlobal::kCallbackDrainTimeout = 5000000; // 5 ms Mutex CameraManagerGlobal::sLock; CameraManagerGlobal* CameraManagerGlobal::sInstance = nullptr; CameraManagerGlobal& CameraManagerGlobal::getInstance() { Mutex::Autolock _l(sLock); CameraManagerGlobal* instance = sInstance; if (instance == nullptr) { instance = new CameraManagerGlobal(); sInstance = instance; } return *instance; } CameraManagerGlobal::~CameraManagerGlobal() { // clear sInstance so next getInstance call knows to create a new one Mutex::Autolock _sl(sLock); sInstance = nullptr; Mutex::Autolock _l(mLock); if (mCameraService != nullptr) { IInterface::asBinder(mCameraService)->unlinkToDeath(mDeathNotifier); mCameraService->removeListener(mCameraServiceListener); } mDeathNotifier.clear(); if (mCbLooper != nullptr) { mCbLooper->unregisterHandler(mHandler->id()); mCbLooper->stop(); } mCbLooper.clear(); mHandler.clear(); mCameraServiceListener.clear(); mCameraService.clear(); } sp<hardware::ICameraService> CameraManagerGlobal::getCameraService() { Mutex::Autolock _l(mLock); return getCameraServiceLocked(); } sp<hardware::ICameraService> CameraManagerGlobal::getCameraServiceLocked() { if (mCameraService.get() == nullptr) { if (CameraUtils::isCameraServiceDisabled()) { return mCameraService; } sp<IServiceManager> sm = defaultServiceManager(); sp<IBinder> binder; do { binder = sm->getService(String16(kCameraServiceName)); if (binder != nullptr) { break; } ALOGW("CameraService not published, waiting..."); usleep(kCameraServicePollDelay); } while(true); if (mDeathNotifier == nullptr) { mDeathNotifier = new DeathNotifier(this); } binder->linkToDeath(mDeathNotifier); mCameraService = interface_cast<hardware::ICameraService>(binder); // Setup looper thread to perfrom availiability callbacks if (mCbLooper == nullptr) { mCbLooper = new ALooper; mCbLooper->setName("C2N-mgr-looper"); status_t err = mCbLooper->start( /*runOnCallingThread*/false, /*canCallJava*/ true, PRIORITY_DEFAULT); if (err != OK) { ALOGE("%s: Unable to start camera service listener looper: %s (%d)", __FUNCTION__, strerror(-err), err); mCbLooper.clear(); return nullptr; } if (mHandler == nullptr) { mHandler = new CallbackHandler(this); } mCbLooper->registerHandler(mHandler); } // register ICameraServiceListener if (mCameraServiceListener == nullptr) { mCameraServiceListener = new CameraServiceListener(this); } std::vector<hardware::CameraStatus> cameraStatuses{}; mCameraService->addListener(mCameraServiceListener, &cameraStatuses); for (auto& c : cameraStatuses) { onStatusChangedLocked(c.status, c.cameraId); for (auto& unavailablePhysicalId : c.unavailablePhysicalIds) { onStatusChangedLocked(hardware::ICameraServiceListener::STATUS_NOT_PRESENT, c.cameraId, unavailablePhysicalId); } } // setup vendor tags sp<VendorTagDescriptor> desc = new VendorTagDescriptor(); binder::Status ret = mCameraService->getCameraVendorTagDescriptor(/*out*/desc.get()); if (ret.isOk()) { if (0 < desc->getTagCount()) { status_t err = VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc); if (err != OK) { ALOGE("%s: Failed to set vendor tag descriptors, received error %s (%d)", __FUNCTION__, strerror(-err), err); } } else { sp<VendorTagDescriptorCache> cache = new VendorTagDescriptorCache(); binder::Status res = mCameraService->getCameraVendorTagCache( /*out*/cache.get()); if (res.serviceSpecificErrorCode() == hardware::ICameraService::ERROR_DISCONNECTED) { // No camera module available, not an error on devices with no cameras VendorTagDescriptorCache::clearGlobalVendorTagCache(); } else if (res.isOk()) { status_t err = VendorTagDescriptorCache::setAsGlobalVendorTagCache( cache); if (err != OK) { ALOGE("%s: Failed to set vendor tag cache," "received error %s (%d)", __FUNCTION__, strerror(-err), err); } } else { VendorTagDescriptorCache::clearGlobalVendorTagCache(); ALOGE("%s: Failed to setup vendor tag cache: %s", __FUNCTION__, res.toString8().string()); } } } else if (ret.serviceSpecificErrorCode() == hardware::ICameraService::ERROR_DEPRECATED_HAL) { ALOGW("%s: Camera HAL too old; does not support vendor tags", __FUNCTION__); VendorTagDescriptor::clearGlobalVendorTagDescriptor(); } else { ALOGE("%s: Failed to get vendor tag descriptors: %s", __FUNCTION__, ret.toString8().string()); } } ALOGE_IF(mCameraService == nullptr, "no CameraService!?"); return mCameraService; } void CameraManagerGlobal::DeathNotifier::binderDied(const wp<IBinder>&) { ALOGE("Camera service binderDied!"); sp<CameraManagerGlobal> cm = mCameraManager.promote(); if (cm != nullptr) { AutoMutex lock(cm->mLock); for (auto& pair : cm->mDeviceStatusMap) { const String8 &cameraId = pair.first; cm->onStatusChangedLocked( CameraServiceListener::STATUS_NOT_PRESENT, cameraId); } cm->mCameraService.clear(); // TODO: consider adding re-connect call here? } } void CameraManagerGlobal::registerExtendedAvailabilityCallback( const ACameraManager_ExtendedAvailabilityCallbacks *callback) { return registerAvailCallback<ACameraManager_ExtendedAvailabilityCallbacks>(callback); } void CameraManagerGlobal::unregisterExtendedAvailabilityCallback( const ACameraManager_ExtendedAvailabilityCallbacks *callback) { Mutex::Autolock _l(mLock); drainPendingCallbacksLocked(); Callback cb(callback); mCallbacks.erase(cb); } void CameraManagerGlobal::registerAvailabilityCallback( const ACameraManager_AvailabilityCallbacks *callback) { return registerAvailCallback<ACameraManager_AvailabilityCallbacks>(callback); } void CameraManagerGlobal::unregisterAvailabilityCallback( const ACameraManager_AvailabilityCallbacks *callback) { Mutex::Autolock _l(mLock); drainPendingCallbacksLocked(); Callback cb(callback); mCallbacks.erase(cb); } void CameraManagerGlobal::onCallbackCalled() { Mutex::Autolock _l(mLock); if (mPendingCallbackCnt > 0) { mPendingCallbackCnt--; } mCallbacksCond.signal(); } void CameraManagerGlobal::drainPendingCallbacksLocked() { while (mPendingCallbackCnt > 0) { auto res = mCallbacksCond.waitRelative(mLock, kCallbackDrainTimeout); if (res != NO_ERROR) { ALOGE("%s: Error waiting to drain callbacks: %s(%d)", __FUNCTION__, strerror(-res), res); break; } } } template<class T> void CameraManagerGlobal::registerAvailCallback(const T *callback) { Mutex::Autolock _l(mLock); Callback cb(callback); auto pair = mCallbacks.insert(cb); // Send initial callbacks if callback is newly registered if (pair.second) { for (auto& pair : mDeviceStatusMap) { const String8& cameraId = pair.first; int32_t status = pair.second.getStatus(); // Don't send initial callbacks for camera ids which don't support // camera2 if (!pair.second.supportsHAL3) { continue; } // Camera available/unavailable callback sp<AMessage> msg = new AMessage(kWhatSendSingleCallback, mHandler); ACameraManager_AvailabilityCallback cbFunc = isStatusAvailable(status) ? cb.mAvailable : cb.mUnavailable; msg->setPointer(kCallbackFpKey, (void *) cbFunc); msg->setPointer(kContextKey, cb.mContext); msg->setString(kCameraIdKey, AString(cameraId)); mPendingCallbackCnt++; msg->post(); // Physical camera unavailable callback std::set<String8> unavailablePhysicalCameras = pair.second.getUnavailablePhysicalIds(); for (const auto& physicalCameraId : unavailablePhysicalCameras) { sp<AMessage> msg = new AMessage(kWhatSendSinglePhysicalCameraCallback, mHandler); ACameraManager_PhysicalCameraAvailabilityCallback cbFunc = cb.mPhysicalCamUnavailable; msg->setPointer(kCallbackFpKey, (void *) cbFunc); msg->setPointer(kContextKey, cb.mContext); msg->setString(kCameraIdKey, AString(cameraId)); msg->setString(kPhysicalCameraIdKey, AString(physicalCameraId)); mPendingCallbackCnt++; msg->post(); } } } } bool CameraManagerGlobal::supportsCamera2ApiLocked(const String8 &cameraId) { bool camera2Support = false; auto cs = getCameraServiceLocked(); binder::Status serviceRet = cs->supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2, &camera2Support); if (!serviceRet.isOk()) { ALOGE("%s: supportsCameraApi2Locked() call failed for cameraId %s", __FUNCTION__, cameraId.c_str()); return false; } return camera2Support; } void CameraManagerGlobal::getCameraIdList(std::vector<String8>* cameraIds) { // Ensure that we have initialized/refreshed the list of available devices Mutex::Autolock _l(mLock); // Needed to make sure we're connected to cameraservice getCameraServiceLocked(); for(auto& deviceStatus : mDeviceStatusMap) { int32_t status = deviceStatus.second.getStatus(); if (status == hardware::ICameraServiceListener::STATUS_NOT_PRESENT || status == hardware::ICameraServiceListener::STATUS_ENUMERATING) { continue; } if (!deviceStatus.second.supportsHAL3) { continue; } cameraIds->push_back(deviceStatus.first); } } bool CameraManagerGlobal::validStatus(int32_t status) { switch (status) { case hardware::ICameraServiceListener::STATUS_NOT_PRESENT: case hardware::ICameraServiceListener::STATUS_PRESENT: case hardware::ICameraServiceListener::STATUS_ENUMERATING: case hardware::ICameraServiceListener::STATUS_NOT_AVAILABLE: return true; default: return false; } } bool CameraManagerGlobal::isStatusAvailable(int32_t status) { switch (status) { case hardware::ICameraServiceListener::STATUS_PRESENT: return true; default: return false; } } void CameraManagerGlobal::CallbackHandler::onMessageReceived( const sp<AMessage> &msg) { onMessageReceivedInternal(msg); if (msg->what() == kWhatSendSingleCallback || msg->what() == kWhatSendSingleAccessCallback || msg->what() == kWhatSendSinglePhysicalCameraCallback) { notifyParent(); } } void CameraManagerGlobal::CallbackHandler::onMessageReceivedInternal( const sp<AMessage> &msg) { switch (msg->what()) { case kWhatSendSingleCallback: { ACameraManager_AvailabilityCallback cb; void* context; AString cameraId; bool found = msg->findPointer(kCallbackFpKey, (void**) &cb); if (!found) { ALOGE("%s: Cannot find camera callback fp!", __FUNCTION__); return; } found = msg->findPointer(kContextKey, &context); if (!found) { ALOGE("%s: Cannot find callback context!", __FUNCTION__); return; } found = msg->findString(kCameraIdKey, &cameraId); if (!found) { ALOGE("%s: Cannot find camera ID!", __FUNCTION__); return; } (*cb)(context, cameraId.c_str()); break; } case kWhatSendSingleAccessCallback: { ACameraManager_AccessPrioritiesChangedCallback cb; void* context; AString cameraId; bool found = msg->findPointer(kCallbackFpKey, (void**) &cb); if (!found) { ALOGE("%s: Cannot find camera callback fp!", __FUNCTION__); return; } found = msg->findPointer(kContextKey, &context); if (!found) { ALOGE("%s: Cannot find callback context!", __FUNCTION__); return; } (*cb)(context); break; } case kWhatSendSinglePhysicalCameraCallback: { ACameraManager_PhysicalCameraAvailabilityCallback cb; void* context; AString cameraId; AString physicalCameraId; bool found = msg->findPointer(kCallbackFpKey, (void**) &cb); if (!found) { ALOGE("%s: Cannot find camera callback fp!", __FUNCTION__); return; } if (cb == nullptr) { // Physical camera callback is null return; } found = msg->findPointer(kContextKey, &context); if (!found) { ALOGE("%s: Cannot find callback context!", __FUNCTION__); return; } found = msg->findString(kCameraIdKey, &cameraId); if (!found) { ALOGE("%s: Cannot find camera ID!", __FUNCTION__); return; } found = msg->findString(kPhysicalCameraIdKey, &physicalCameraId); if (!found) { ALOGE("%s: Cannot find physical camera ID!", __FUNCTION__); return; } (*cb)(context, cameraId.c_str(), physicalCameraId.c_str()); break; } default: ALOGE("%s: unknown message type %d", __FUNCTION__, msg->what()); break; } } void CameraManagerGlobal::CallbackHandler::notifyParent() { sp<CameraManagerGlobal> parent = mParent.promote(); if (parent != nullptr) { parent->onCallbackCalled(); } } binder::Status CameraManagerGlobal::CameraServiceListener::onCameraAccessPrioritiesChanged() { sp<CameraManagerGlobal> cm = mCameraManager.promote(); if (cm != nullptr) { cm->onCameraAccessPrioritiesChanged(); } else { ALOGE("Cannot deliver camera access priority callback. Global camera manager died"); } return binder::Status::ok(); } binder::Status CameraManagerGlobal::CameraServiceListener::onStatusChanged( int32_t status, const String16& cameraId) { sp<CameraManagerGlobal> cm = mCameraManager.promote(); if (cm != nullptr) { cm->onStatusChanged(status, String8(cameraId)); } else { ALOGE("Cannot deliver status change. Global camera manager died"); } return binder::Status::ok(); } binder::Status CameraManagerGlobal::CameraServiceListener::onPhysicalCameraStatusChanged( int32_t status, const String16& cameraId, const String16& physicalCameraId) { sp<CameraManagerGlobal> cm = mCameraManager.promote(); if (cm != nullptr) { cm->onStatusChanged(status, String8(cameraId), String8(physicalCameraId)); } else { ALOGE("Cannot deliver physical camera status change. Global camera manager died"); } return binder::Status::ok(); } void CameraManagerGlobal::onCameraAccessPrioritiesChanged() { Mutex::Autolock _l(mLock); for (auto cb : mCallbacks) { sp<AMessage> msg = new AMessage(kWhatSendSingleAccessCallback, mHandler); ACameraManager_AccessPrioritiesChangedCallback cbFp = cb.mAccessPriorityChanged; if (cbFp != nullptr) { msg->setPointer(kCallbackFpKey, (void *) cbFp); msg->setPointer(kContextKey, cb.mContext); mPendingCallbackCnt++; msg->post(); } } } void CameraManagerGlobal::onStatusChanged( int32_t status, const String8& cameraId) { Mutex::Autolock _l(mLock); onStatusChangedLocked(status, cameraId); } void CameraManagerGlobal::onStatusChangedLocked( int32_t status, const String8& cameraId) { if (!validStatus(status)) { ALOGE("%s: Invalid status %d", __FUNCTION__, status); return; } bool firstStatus = (mDeviceStatusMap.count(cameraId) == 0); int32_t oldStatus = firstStatus ? status : // first status mDeviceStatusMap[cameraId].getStatus(); if (!firstStatus && isStatusAvailable(status) == isStatusAvailable(oldStatus)) { // No status update. No need to send callback return; } bool supportsHAL3 = supportsCamera2ApiLocked(cameraId); if (firstStatus) { mDeviceStatusMap.emplace(std::piecewise_construct, std::forward_as_tuple(cameraId), std::forward_as_tuple(status, supportsHAL3)); } else { mDeviceStatusMap[cameraId].updateStatus(status); } // Iterate through all registered callbacks if (supportsHAL3) { for (auto cb : mCallbacks) { sp<AMessage> msg = new AMessage(kWhatSendSingleCallback, mHandler); ACameraManager_AvailabilityCallback cbFp = isStatusAvailable(status) ? cb.mAvailable : cb.mUnavailable; msg->setPointer(kCallbackFpKey, (void *) cbFp); msg->setPointer(kContextKey, cb.mContext); msg->setString(kCameraIdKey, AString(cameraId)); mPendingCallbackCnt++; msg->post(); } } if (status == hardware::ICameraServiceListener::STATUS_NOT_PRESENT) { mDeviceStatusMap.erase(cameraId); } } void CameraManagerGlobal::onStatusChanged( int32_t status, const String8& cameraId, const String8& physicalCameraId) { Mutex::Autolock _l(mLock); onStatusChangedLocked(status, cameraId, physicalCameraId); } void CameraManagerGlobal::onStatusChangedLocked( int32_t status, const String8& cameraId, const String8& physicalCameraId) { if (!validStatus(status)) { ALOGE("%s: Invalid status %d", __FUNCTION__, status); return; } auto logicalStatus = mDeviceStatusMap.find(cameraId); if (logicalStatus == mDeviceStatusMap.end()) { ALOGE("%s: Physical camera id %s status change on a non-present id %s", __FUNCTION__, physicalCameraId.c_str(), cameraId.c_str()); return; } int32_t logicalCamStatus = mDeviceStatusMap[cameraId].getStatus(); if (logicalCamStatus != hardware::ICameraServiceListener::STATUS_PRESENT && logicalCamStatus != hardware::ICameraServiceListener::STATUS_NOT_AVAILABLE) { ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d", __FUNCTION__, physicalCameraId.string(), status, logicalCamStatus); return; } bool supportsHAL3 = supportsCamera2ApiLocked(cameraId); bool updated = false; if (status == hardware::ICameraServiceListener::STATUS_PRESENT) { updated = mDeviceStatusMap[cameraId].removeUnavailablePhysicalId(physicalCameraId); } else { updated = mDeviceStatusMap[cameraId].addUnavailablePhysicalId(physicalCameraId); } // Iterate through all registered callbacks if (supportsHAL3 && updated) { for (auto cb : mCallbacks) { sp<AMessage> msg = new AMessage(kWhatSendSinglePhysicalCameraCallback, mHandler); ACameraManager_PhysicalCameraAvailabilityCallback cbFp = isStatusAvailable(status) ? cb.mPhysicalCamAvailable : cb.mPhysicalCamUnavailable; msg->setPointer(kCallbackFpKey, (void *) cbFp); msg->setPointer(kContextKey, cb.mContext); msg->setString(kCameraIdKey, AString(cameraId)); msg->setString(kPhysicalCameraIdKey, AString(physicalCameraId)); mPendingCallbackCnt++; msg->post(); } } } int32_t CameraManagerGlobal::StatusAndHAL3Support::getStatus() { std::lock_guard<std::mutex> lock(mLock); return status; } void CameraManagerGlobal::StatusAndHAL3Support::updateStatus(int32_t newStatus) { std::lock_guard<std::mutex> lock(mLock); status = newStatus; } bool CameraManagerGlobal::StatusAndHAL3Support::addUnavailablePhysicalId( const String8& physicalCameraId) { std::lock_guard<std::mutex> lock(mLock); auto result = unavailablePhysicalIds.insert(physicalCameraId); return result.second; } bool CameraManagerGlobal::StatusAndHAL3Support::removeUnavailablePhysicalId( const String8& physicalCameraId) { std::lock_guard<std::mutex> lock(mLock); auto count = unavailablePhysicalIds.erase(physicalCameraId); return count > 0; } std::set<String8> CameraManagerGlobal::StatusAndHAL3Support::getUnavailablePhysicalIds() { std::lock_guard<std::mutex> lock(mLock); return unavailablePhysicalIds; } } // namespace acam } // namespace android /** * ACameraManger Implementation */ camera_status_t ACameraManager::getCameraIdList(ACameraIdList** cameraIdList) { Mutex::Autolock _l(mLock); std::vector<String8> idList; CameraManagerGlobal::getInstance().getCameraIdList(&idList); int numCameras = idList.size(); ACameraIdList *out = new ACameraIdList; if (!out) { ALOGE("Allocate memory for ACameraIdList failed!"); return ACAMERA_ERROR_NOT_ENOUGH_MEMORY; } out->numCameras = numCameras; out->cameraIds = new const char*[numCameras]; if (!out->cameraIds) { ALOGE("Allocate memory for ACameraIdList failed!"); deleteCameraIdList(out); return ACAMERA_ERROR_NOT_ENOUGH_MEMORY; } for (int i = 0; i < numCameras; i++) { const char* src = idList[i].string(); size_t dstSize = strlen(src) + 1; char* dst = new char[dstSize]; if (!dst) { ALOGE("Allocate memory for ACameraIdList failed!"); deleteCameraIdList(out); return ACAMERA_ERROR_NOT_ENOUGH_MEMORY; } strlcpy(dst, src, dstSize); out->cameraIds[i] = dst; } *cameraIdList = out; return ACAMERA_OK; } void ACameraManager::deleteCameraIdList(ACameraIdList* cameraIdList) { if (cameraIdList != nullptr) { if (cameraIdList->cameraIds != nullptr) { for (int i = 0; i < cameraIdList->numCameras; i ++) { if (cameraIdList->cameraIds[i] != nullptr) { delete[] cameraIdList->cameraIds[i]; } } delete[] cameraIdList->cameraIds; } delete cameraIdList; } } camera_status_t ACameraManager::getCameraCharacteristics( const char* cameraIdStr, sp<ACameraMetadata>* characteristics) { Mutex::Autolock _l(mLock); sp<hardware::ICameraService> cs = CameraManagerGlobal::getInstance().getCameraService(); if (cs == nullptr) { ALOGE("%s: Cannot reach camera service!", __FUNCTION__); return ACAMERA_ERROR_CAMERA_DISCONNECTED; } CameraMetadata rawMetadata; binder::Status serviceRet = cs->getCameraCharacteristics(String16(cameraIdStr), &rawMetadata); if (!serviceRet.isOk()) { switch(serviceRet.serviceSpecificErrorCode()) { case hardware::ICameraService::ERROR_DISCONNECTED: ALOGE("%s: Camera %s has been disconnected", __FUNCTION__, cameraIdStr); return ACAMERA_ERROR_CAMERA_DISCONNECTED; case hardware::ICameraService::ERROR_ILLEGAL_ARGUMENT: ALOGE("%s: Camera ID %s does not exist!", __FUNCTION__, cameraIdStr); return ACAMERA_ERROR_INVALID_PARAMETER; default: ALOGE("Get camera characteristics from camera service failed: %s", serviceRet.toString8().string()); return ACAMERA_ERROR_UNKNOWN; // should not reach here } } *characteristics = new ACameraMetadata( rawMetadata.release(), ACameraMetadata::ACM_CHARACTERISTICS); return ACAMERA_OK; } camera_status_t ACameraManager::openCamera( const char* cameraId, ACameraDevice_StateCallbacks* callback, /*out*/ACameraDevice** outDevice) { sp<ACameraMetadata> chars; camera_status_t ret = getCameraCharacteristics(cameraId, &chars); Mutex::Autolock _l(mLock); if (ret != ACAMERA_OK) { ALOGE("%s: cannot get camera characteristics for camera %s. err %d", __FUNCTION__, cameraId, ret); return ACAMERA_ERROR_INVALID_PARAMETER; } ACameraDevice* device = new ACameraDevice(cameraId, callback, chars); sp<hardware::ICameraService> cs = CameraManagerGlobal::getInstance().getCameraService(); if (cs == nullptr) { ALOGE("%s: Cannot reach camera service!", __FUNCTION__); delete device; return ACAMERA_ERROR_CAMERA_DISCONNECTED; } sp<hardware::camera2::ICameraDeviceCallbacks> callbacks = device->getServiceCallback(); sp<hardware::camera2::ICameraDeviceUser> deviceRemote; // No way to get package name from native. // Send a zero length package name and let camera service figure it out from UID binder::Status serviceRet = cs->connectDevice( callbacks, String16(cameraId), String16(""), std::unique_ptr<String16>(), hardware::ICameraService::USE_CALLING_UID, /*out*/&deviceRemote); if (!serviceRet.isOk()) { ALOGE("%s: connect camera device failed: %s", __FUNCTION__, serviceRet.toString8().string()); // Convert serviceRet to camera_status_t switch(serviceRet.serviceSpecificErrorCode()) { case hardware::ICameraService::ERROR_DISCONNECTED: ret = ACAMERA_ERROR_CAMERA_DISCONNECTED; break; case hardware::ICameraService::ERROR_CAMERA_IN_USE: ret = ACAMERA_ERROR_CAMERA_IN_USE; break; case hardware::ICameraService::ERROR_MAX_CAMERAS_IN_USE: ret = ACAMERA_ERROR_MAX_CAMERA_IN_USE; break; case hardware::ICameraService::ERROR_ILLEGAL_ARGUMENT: ret = ACAMERA_ERROR_INVALID_PARAMETER; break; case hardware::ICameraService::ERROR_DEPRECATED_HAL: // Should not reach here since we filtered legacy HALs earlier ret = ACAMERA_ERROR_INVALID_PARAMETER; break; case hardware::ICameraService::ERROR_DISABLED: ret = ACAMERA_ERROR_CAMERA_DISABLED; break; case hardware::ICameraService::ERROR_PERMISSION_DENIED: ret = ACAMERA_ERROR_PERMISSION_DENIED; break; case hardware::ICameraService::ERROR_INVALID_OPERATION: default: ret = ACAMERA_ERROR_UNKNOWN; break; } delete device; return ret; } if (deviceRemote == nullptr) { ALOGE("%s: connect camera device failed! remote device is null", __FUNCTION__); delete device; return ACAMERA_ERROR_CAMERA_DISCONNECTED; } device->setRemoteDevice(deviceRemote); *outDevice = device; return ACAMERA_OK; } ACameraManager::~ACameraManager() { }
37.675505
101
0.628875
Dreadwyrm
2cbb92f70ac51a6f3dd45b695bd796bdc8525db9
5,547
cpp
C++
CodeGenere/photogram/cRegD2.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
451
2016-11-25T09:40:28.000Z
2022-03-30T04:20:42.000Z
CodeGenere/photogram/cRegD2.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
143
2016-11-25T20:35:57.000Z
2022-03-01T11:58:02.000Z
CodeGenere/photogram/cRegD2.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
139
2016-12-02T10:26:21.000Z
2022-03-10T19:40:29.000Z
/*Header-MicMac-eLiSe-25/06/2007 MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation eLiSe : ELements of an Image Software Environnement www.micmac.ign.fr Copyright : Institut Geographique National Author : Marc Pierrot Deseilligny Contributors : Gregoire Maillet, Didier Boldo. [1] M. Pierrot-Deseilligny, N. Paparoditis. "A multiresolution and optimization-based image matching approach: An application to surface reconstruction from SPOT5-HRS stereo imagery." In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space (With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006. [2] M. Pierrot-Deseilligny, "MicMac, un lociel de mise en correspondance d'images, adapte au contexte geograhique" to appears in Bulletin d'information de l'Institut Geographique National, 2007. Francais : MicMac est un logiciel de mise en correspondance d'image adapte au contexte de recherche en information geographique. Il s'appuie sur la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la licences Cecill-B. Voir en bas de fichier et http://www.cecill.info. English : MicMac is an open source software specialized in image matching for research in geographic information. MicMac is built on the eLiSe image library. MicMac is governed by the "Cecill-B licence". See below and http://www.cecill.info. Header-MicMac-eLiSe-25/06/2007*/ // File Automatically generated by eLiSe #include "general/all.h" #include "private/all.h" #include "cRegD2.h" cRegD2::cRegD2(): cElCompiledFonc(4) { AddIntRef (cIncIntervale("toto0",0,1)); AddIntRef (cIncIntervale("toto1",1,2)); AddIntRef (cIncIntervale("toto2",2,3)); AddIntRef (cIncIntervale("toto3",3,4)); AddIntRef (cIncIntervale("toto4",4,5)); AddIntRef (cIncIntervale("toto5",5,6)); AddIntRef (cIncIntervale("toto6",6,7)); AddIntRef (cIncIntervale("toto7",7,8)); AddIntRef (cIncIntervale("toto8",8,9)); Close(false); } void cRegD2::ComputeVal() { double tmp0_ = mCompCoord[4]; double tmp1_ = 2*tmp0_; mVal[0] = (mCompCoord[3]+mCompCoord[5])-tmp1_; mVal[1] = (mCompCoord[1]+mCompCoord[7])-tmp1_; mVal[2] = (mCompCoord[6]+mCompCoord[2])-tmp1_; mVal[3] = (mCompCoord[0]+mCompCoord[8])-tmp1_; } void cRegD2::ComputeValDeriv() { double tmp0_ = mCompCoord[4]; double tmp1_ = 2*tmp0_; double tmp2_ = -(2); mVal[0] = (mCompCoord[3]+mCompCoord[5])-tmp1_; mCompDer[0][0] = 0; mCompDer[0][1] = 0; mCompDer[0][2] = 0; mCompDer[0][3] = 1; mCompDer[0][4] = tmp2_; mCompDer[0][5] = 1; mCompDer[0][6] = 0; mCompDer[0][7] = 0; mCompDer[0][8] = 0; mVal[1] = (mCompCoord[1]+mCompCoord[7])-tmp1_; mCompDer[1][0] = 0; mCompDer[1][1] = 1; mCompDer[1][2] = 0; mCompDer[1][3] = 0; mCompDer[1][4] = tmp2_; mCompDer[1][5] = 0; mCompDer[1][6] = 0; mCompDer[1][7] = 1; mCompDer[1][8] = 0; mVal[2] = (mCompCoord[6]+mCompCoord[2])-tmp1_; mCompDer[2][0] = 0; mCompDer[2][1] = 0; mCompDer[2][2] = 1; mCompDer[2][3] = 0; mCompDer[2][4] = tmp2_; mCompDer[2][5] = 0; mCompDer[2][6] = 1; mCompDer[2][7] = 0; mCompDer[2][8] = 0; mVal[3] = (mCompCoord[0]+mCompCoord[8])-tmp1_; mCompDer[3][0] = 1; mCompDer[3][1] = 0; mCompDer[3][2] = 0; mCompDer[3][3] = 0; mCompDer[3][4] = tmp2_; mCompDer[3][5] = 0; mCompDer[3][6] = 0; mCompDer[3][7] = 0; mCompDer[3][8] = 1; } void cRegD2::ComputeValDerivHessian() { ELISE_ASSERT(false,"Foncteur cRegD2 Has no Der Sec"); } double * cRegD2::AdrVarLocFromString(const std::string & aName) { return 0; } cElCompiledFonc::cAutoAddEntry cRegD2::mTheAuto("cRegD2",cRegD2::Alloc); cElCompiledFonc * cRegD2::Alloc() { return new cRegD2(); } /*Footer-MicMac-eLiSe-25/06/2007 Ce logiciel est un programme informatique servant à la mise en correspondances d'images pour la reconstruction du relief. Ce logiciel est régi par la licence CeCILL-B soumise au droit français et respectant les principes de diffusion des logiciels libres. Vous pouvez utiliser, modifier et/ou redistribuer ce programme sous les conditions de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA sur le site "http://www.cecill.info". En contrepartie de l'accessibilité au code source et des droits de copie, de modification et de redistribution accordés par cette licence, il n'est offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons, seule une responsabilité restreinte pèse sur l'auteur du programme, le titulaire des droits patrimoniaux et les concédants successifs. A cet égard l'attention de l'utilisateur est attirée sur les risques associés au chargement, à l'utilisation, à la modification et/ou au développement et à la reproduction du logiciel par l'utilisateur étant donné sa spécificité de logiciel libre, qui peut le rendre complexe à manipuler et qui le réserve donc à des développeurs et des professionnels avertis possédant des connaissances informatiques approfondies. Les utilisateurs sont donc invités à charger et tester l'adéquation du logiciel à leurs besoins dans des conditions permettant d'assurer la sécurité de leurs systèmes et ou de leurs données et, plus généralement, à l'utiliser et l'exploiter dans les mêmes conditions de sécurité. Le fait que vous puissiez accéder à cet en-tête signifie que vous avez pris connaissance de la licence CeCILL-B, et que vous en avez accepté les termes. Footer-MicMac-eLiSe-25/06/2007*/
29.663102
81
0.711556
kikislater
2cc0184b760471df88cb0c90a9e9d89b3dff60db
16,874
hpp
C++
LinaGraphics/include/Core/Backend/OpenGL/OpenGLRenderEngine.hpp
moonantonio/LinaEngine
fe5a91a85c64dd0719656eb38e2fb37037bacfc1
[ "MIT" ]
10
2018-09-30T22:29:27.000Z
2018-10-08T14:04:42.000Z
LinaGraphics/include/Core/Backend/OpenGL/OpenGLRenderEngine.hpp
moonantonio/LinaEngine
fe5a91a85c64dd0719656eb38e2fb37037bacfc1
[ "MIT" ]
15
2018-10-02T22:14:17.000Z
2018-10-12T08:01:36.000Z
LinaGraphics/include/Core/Backend/OpenGL/OpenGLRenderEngine.hpp
moonantonio/LinaEngine
fe5a91a85c64dd0719656eb38e2fb37037bacfc1
[ "MIT" ]
1
2018-09-30T16:37:10.000Z
2018-09-30T16:37:10.000Z
/* This file is a part of: Lina Engine https://github.com/inanevin/LinaEngine Author: Inan Evin http://www.inanevin.com Copyright (c) [2018-2020] [Inan Evin] 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. */ /* Class: OpenGLRenderEngine Responsible for managing the whole rendering pipeline, creating frame buffers, textures, materials, meshes etc. Also handles most of the memory management for the rendering pipeline. Timestamp: 4/15/2019 12:26:31 PM */ #pragma once #ifndef RenderEngine_HPP #define RenderEngine_HPP #include "ECS/SystemList.hpp" #include "ECS/Systems/AnimationSystem.hpp" #include "ECS/Systems/CameraSystem.hpp" #include "ECS/Systems/FrustumSystem.hpp" #include "ECS/Systems/LightingSystem.hpp" #include "ECS/Systems/ModelNodeSystem.hpp" #include "ECS/Systems/ReflectionSystem.hpp" #include "ECS/Systems/SpriteRendererSystem.hpp" #include "OpenGLRenderDevice.hpp" #include "OpenGLWindow.hpp" #include "Rendering/Mesh.hpp" #include "Rendering/Model.hpp" #include "Rendering/PostProcessEffect.hpp" #include "Rendering/RenderBuffer.hpp" #include "Rendering/RenderSettings.hpp" #include "Rendering/RenderingCommon.hpp" #include "Rendering/UniformBuffer.hpp" #include "Rendering/VertexArray.hpp" #include <functional> #include <queue> #include <set> namespace Lina { class Engine; namespace Resources { class ResourceStorage; } namespace Event { class EventSystem; struct EAllResourcesOfTypeLoaded; struct EDrawLine; struct EDrawBox; struct EDrawCircle; struct EDrawSphere; struct EDrawHemiSphere; struct EDrawCapsule; struct EWindowResized; } // namespace Event } // namespace Lina namespace Lina::Graphics { class Shader; struct BufferValueRecord { float zNear; float zFar; }; class OpenGLRenderEngine { public: static OpenGLRenderEngine* Get() { return s_renderEngine; } /// <summary> /// Any system added to the rendering pipeline will be updated within the render loop. /// </summary> void AddToRenderingPipeline(ECS::System& system); /// <summary> /// Any system added to the animation pipeline will be updated within the animation loop. /// </summary> void AddToAnimationPipeline(ECS::System& system); /// <summary> /// Sets the screen position and size, resizes the framebuffers accordingly. /// </summary> void SetScreenDisplay(Vector2i offset, Vector2i size); /// <summary> /// Use this to change current draw parameters. Will be replaced with in-engine parameters every frame. /// </summary> /// <param name="params"></param> void SetDrawParameters(const DrawParams& params); /// <summary> /// Sets uniform render settings from the current Render Settings struct. /// </summary> void UpdateRenderSettings(); /// <summary> /// Sets the current skybox material used to draw the scene. /// </summary> inline void SetSkyboxMaterial(Material* skyboxMaterial) { m_skyboxMaterial = skyboxMaterial; } /// <summary> /// Returns a texture pointer to the final drawed image, which is usually drawn to the screen as a full-screen quad. /// </summary> uint32 GetFinalImage(); /// <summary> /// Returns a texture pointer to the current shadow map. /// </summary> uint32 GetShadowMapImage(); /// <summary> /// Given a texture & a location, captures 6-faced cubemap & writes into the given texture. /// </summary> void CaptureReflections(Texture& writeTexture, const Vector3& areaLocation, const Vector2i& resolution); /// <summary> /// Draws the current skybox into an irradiance cubemap. /// </summary> void CaptureSkybox(); /// <summary> /// Given an HDRI loaded texture, captures & calculates HDRI cube probes & writes it into global HRDI buffer. /// This buffer will be sent to the materials whose HDRI support is enabled. /// </summary> void CaptureCalculateHDRI(Texture& hdriTexture); /// <summary> /// Add the texture with the given StringID to the debug icon buffer. /// </summary> void DrawIcon(Vector3 p, StringIDType textureID, float size = 1.0f); /// <summary> /// Adds a line to the debug buffer with given parameters. /// </summary> void DrawLine(Vector3 p1, Vector3 p2, Color col, float width = 1.0f); /// <summary> /// Pass in any run-time constructed shader. The shader will be drawn to a full-screen quad & added as a /// post-process effect. /// </summary> PostProcessEffect& AddPostProcessEffect(Shader* shader); /// <summary> /// Renders the given model in a preview scene and returns the resulting image. /// </summary> uint32 RenderModelPreview(Model* model, Matrix& modelMatrix, RenderTarget* overrideTarget = nullptr, Material* materialOverride = nullptr); void UpdateShaderData(Material* mat, bool lightPass = false); inline UniformBuffer& GetViewBuffer() { return m_globalViewBuffer; } inline DrawParams GetMainDrawParams() { return m_defaultDrawParams; } inline OpenGLRenderDevice* GetRenderDevice() { return &m_renderDevice; } inline Texture& GetHDRICubemap() { return m_hdriCubemap; } inline uint32 GetScreenQuadVAO() { return m_screenQuadVAO; } inline Vector2i GetScreenSize() { return m_screenSize; } inline Vector2i GetScreenPos() { return m_screenPos; } inline ECS::CameraSystem* GetCameraSystem() { return &m_cameraSystem; } inline ECS::LightingSystem* GetLightingSystem() { return &m_lightingSystem; } inline ECS::ModelNodeSystem* GetModelNodeSystem() { return &m_modelNodeSystem; } inline ECS::ReflectionSystem* GetReflectionSystem() { return &m_reflectionSystem; } inline ECS::FrustumSystem* GetFrustumSystem() { return &m_frustumSystem; } inline Texture* GetDefaultTexture() { return &m_defaultTexture; } inline Material* GetDefaultUnlitMaterial() { return m_defaultUnlit; } inline Material* GetDefaultLitMaterial() { return m_defaultLit; } inline Material* GetDefaultSkyboxMaterial() { return m_defaultSkybox; } inline Material* GetDefaultSkyboxHDRIMaterial() { return m_defaultSkyboxHDRI; } inline Material* GetDefaultSpriteMaterial() { return m_defaultSprite; } inline Shader* GetDefaultUnlitShader() { return m_standardUnlitShader; } inline Shader* GetDefaultLitShader() { return m_standardLitShader; } inline void SetCurrentPLightCount(int count) { m_currentPointLightCount = count; } inline void SetCurrentSLightCount(int count) { m_currentSpotLightCount = count; } inline const ECS::SystemList& GetRenderingPipeline() { return m_renderingPipeline; } inline const ECS::SystemList& GetAnimationPipeline() { return m_animationPipeline; } inline SamplerParameters GetPrimaryRTParams() { return m_primaryRTParams; } inline void SetAppData(float delta, float elapsed, const Vector2& mousePos) { m_deltaTime = delta; m_elapsedTime = elapsed; m_mousePosition = mousePos; } inline Material* GetSkyboxMaterial() { return m_skyboxMaterial; } private: friend class Engine; OpenGLRenderEngine() = default; ~OpenGLRenderEngine() = default; void ConnectEvents(); void Initialize(ApplicationMode appMode, RenderSettings* renderSettings); void Shutdown(); void Render(float interpolation); void Tick(float delta); void UpdateSystems(float interpolation); void DrawSceneObjects(DrawParams& drawpParams, Material* overrideMaterial = nullptr, bool completeFlush = true); void DrawSkybox(); void SetHDRIData(Material* mat); void RemoveHDRIData(Material* mat); void ProcessDebugQueue(); private: void OnDrawLine(const Event::EDrawLine& event); void OnDrawBox(const Event::EDrawBox& event); void OnDrawCircle(const Event::EDrawCircle& event); void OnDrawSphere(const Event::EDrawSphere& event); void OnDrawHemiSphere(const Event::EDrawHemiSphere& event); void OnDrawCapsule(const Event::EDrawCapsule& event); void OnWindowResized(const Event::EWindowResized& event); void OnAllResourcesOfTypeLoaded(const Event::EAllResourcesOfTypeLoaded& ev); void OnResourceReloaded(const Event::EResourceReloaded& ev); bool ValidateEngineShaders(); void SetupEngineShaders(); void ConstructEngineMaterials(); void ConstructRenderTargets(); void DumpMemory(); void Draw(); void DrawFinalize(RenderTarget* overrideTarget = nullptr); void UpdateUniformBuffers(); void CalculateHDRICubemap(Texture& hdriTexture, glm::mat4& captureProjection, glm::mat4 views[6]); void CalculateHDRIIrradiance(Matrix& captureProjection, Matrix views[6]); void CalculateHDRIPrefilter(Matrix& captureProjection, Matrix views[6]); void CalculateHDRIBRDF(Matrix& captureProjection, Matrix views[6]); private: static OpenGLRenderEngine* s_renderEngine; ApplicationMode m_appMode = ApplicationMode::Editor; OpenGLWindow* m_appWindow = nullptr; OpenGLRenderDevice m_renderDevice; Event::EventSystem* m_eventSystem = nullptr; RenderTarget m_primaryRenderTarget; RenderTarget m_secondaryRenderTarget; RenderTarget m_previewRenderTarget; RenderTarget m_primaryMSAATarget; RenderTarget m_pingPongRenderTarget1; RenderTarget m_pingPongRenderTarget2; RenderTarget m_hdriCaptureRenderTarget; RenderTarget m_reflectionCaptureRenderTarget; RenderTarget m_skyboxIrradianceCaptureRenderTarget; RenderTarget m_shadowMapTarget; RenderTarget m_pLightShadowTargets[MAX_POINT_LIGHTS]; RenderTarget m_gBuffer; RenderBuffer m_primaryBuffer; RenderBuffer m_primaryMSAABuffer; RenderBuffer m_secondaryRenderBuffer; RenderBuffer m_previewRenderBuffer; RenderBuffer m_hdriCaptureRenderBuffer; RenderBuffer m_reflectionCaptureRenderBuffer; RenderBuffer m_skyboxIrradianceCaptureRenderBuffer; RenderBuffer m_gBufferRenderBuffer; Texture m_gBufferPosition; Texture m_gBufferNormal; Texture m_gBufferAlbedo; Texture m_gBufferEmission; Texture m_gBufferMetallicRoughnessAOWorkflow; Texture m_primaryMSAARTTexture0; Texture m_primaryMSAARTTexture1; Texture m_primaryRTTexture0; Texture m_primaryRTTexture1; Texture m_secondaryRTTexture; Texture m_previewRTTexture; Texture m_pingPongRTTexture1; Texture m_pingPongRTTexture2; Texture m_hdriCubemap; Texture m_hdriIrradianceMap; Texture m_hdriPrefilterMap; Texture m_hdriLutMap; Texture m_shadowMapRTTexture; Texture m_defaultCubemapTexture; Texture m_pLightShadowTextures[MAX_POINT_LIGHTS]; Texture m_defaultTexture; Texture m_skyboxIrradianceCubemap; Texture m_reflectionCubemap; Texture* m_lastCapturedHDR = nullptr; // Frame buffer texture parameters SamplerParameters m_primaryRTParams; SamplerParameters m_pingPongRTParams; SamplerParameters m_shadowsRTParams; Mesh m_quadMesh; Material m_gBufferLightPassMaterial; Material m_screenQuadFinalMaterial; Material m_screenQuadBlurMaterial; Material m_screenQuadOutlineMaterial; Material* m_skyboxMaterial = nullptr; Material m_debugLineMaterial; Material m_debugIconMaterial; Material m_hdriMaterial; Material m_shadowMapMaterial; Material m_defaultSkyboxMaterial; Material m_pLightShadowDepthMaterial; Material* m_defaultSkyboxHDRI = nullptr; Material* m_defaultUnlit = nullptr; Material* m_defaultLit = nullptr; Material* m_defaultSkybox = nullptr; Material* m_defaultSprite = nullptr; Shader* m_hdriBRDFShader = nullptr; Shader* m_hdriPrefilterShader = nullptr; Shader* m_hdriEquirectangularShader = nullptr; Shader* m_hdriIrradianceShader = nullptr; Shader* m_standardUnlitShader = nullptr; Shader* m_standardLitShader = nullptr; DrawParams m_defaultDrawParams; DrawParams m_skyboxDrawParams; DrawParams m_fullscreenQuadDP; DrawParams m_shadowMapDrawParams; UniformBuffer m_globalViewBuffer; UniformBuffer m_globalLightBuffer; UniformBuffer m_globalDebugBuffer; UniformBuffer m_globalAppDataBuffer; RenderingDebugData m_debugData; RenderSettings* m_renderSettings; // Structure that keeps track of current buffer values BufferValueRecord m_bufferValueRecord; ECS::AnimationSystem m_animationSystem; ECS::CameraSystem m_cameraSystem; ECS::ModelNodeSystem m_modelNodeSystem; ECS::ReflectionSystem m_reflectionSystem; ECS::SpriteRendererSystem m_spriteRendererSystem; ECS::LightingSystem m_lightingSystem; ECS::FrustumSystem m_frustumSystem; ECS::SystemList m_renderingPipeline; ECS::SystemList m_animationPipeline; Resources::ResourceStorage* m_storage = nullptr; private: uint32 m_skyboxVAO = 0; uint32 m_screenQuadVAO = 0; uint32 m_hdriCubeVAO = 0; uint32 m_lineVAO = 0; int m_currentSpotLightCount = 0; int m_currentPointLightCount = 0; Vector2i m_hdriResolution = Vector2i(512, 512); Vector2i m_shadowMapResolution = Vector2i(2048, 2048); Vector2i m_screenPos = Vector2i(0, 0); Vector2i m_screenSize = Vector2i(0, 0); Vector2i m_pLightShadowResolution = Vector2i(1024, 1024); Vector2i m_skyboxIrradianceResolution = Vector2i(1024, 1024); bool m_firstFrameDrawn = false; float m_deltaTime = 0.0f; float m_elapsedTime = 0.0f; Vector2 m_mousePosition = Vector2::Zero; std::queue<DebugLine> m_debugLineQueue; std::queue<DebugIcon> m_debugIconQueue; std::map<Shader*, PostProcessEffect> m_postProcessMap; }; } // namespace Lina::Graphics #endif
35.081081
147
0.648987
moonantonio
2cc40324de4e9508a348c23e4b8157b91237050a
6,558
cpp
C++
eagleye_core/navigation/src/smoothing.cpp
shjzhang/eagleye
e4e105d3a5438cf5ee36f1cc525ff87313923fc5
[ "BSD-3-Clause" ]
1
2020-07-16T15:31:59.000Z
2020-07-16T15:31:59.000Z
eagleye_core/navigation/src/smoothing.cpp
shjzhang/eagleye
e4e105d3a5438cf5ee36f1cc525ff87313923fc5
[ "BSD-3-Clause" ]
null
null
null
eagleye_core/navigation/src/smoothing.cpp
shjzhang/eagleye
e4e105d3a5438cf5ee36f1cc525ff87313923fc5
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019, Map IV, Inc. // 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 Map IV, Inc. 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 COPYRIGHT HOLDER 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. /* * smoothing.cpp * Author MapIV Takanose */ #include "coordinate.hpp" #include "navigation.hpp" void smoothing_estimate(rtklib_msgs::RtklibNav rtklib_nav, eagleye_msgs::VelocityScaleFactor velocity_scale_factor,SmoothingParameter smoothing_parameter, SmoothingStatus* smoothing_status,eagleye_msgs::Position* gnss_smooth_pos_enu) { double ecef_pos[3]; double ecef_base_pos[3]; double enu_pos[3]; std::size_t index_length; std::size_t time_buffer_length; std::size_t velocity_index_length; if(gnss_smooth_pos_enu->ecef_base_pos.x == 0 && gnss_smooth_pos_enu->ecef_base_pos.y == 0 && gnss_smooth_pos_enu->ecef_base_pos.z == 0) { gnss_smooth_pos_enu->ecef_base_pos.x = rtklib_nav.ecef_pos.x; gnss_smooth_pos_enu->ecef_base_pos.y = rtklib_nav.ecef_pos.y; gnss_smooth_pos_enu->ecef_base_pos.z = rtklib_nav.ecef_pos.z; if(smoothing_parameter.ecef_base_pos_x != 0 && smoothing_parameter.ecef_base_pos_y != 0 && smoothing_parameter.ecef_base_pos_z != 0){ gnss_smooth_pos_enu->ecef_base_pos.x = smoothing_parameter.ecef_base_pos_x; gnss_smooth_pos_enu->ecef_base_pos.y = smoothing_parameter.ecef_base_pos_y; gnss_smooth_pos_enu->ecef_base_pos.z = smoothing_parameter.ecef_base_pos_z; } } ecef_pos[0] = rtklib_nav.ecef_pos.x; ecef_pos[1] = rtklib_nav.ecef_pos.y; ecef_pos[2] = rtklib_nav.ecef_pos.z; ecef_base_pos[0] = gnss_smooth_pos_enu->ecef_base_pos.x; ecef_base_pos[1] = gnss_smooth_pos_enu->ecef_base_pos.y; ecef_base_pos[2] = gnss_smooth_pos_enu->ecef_base_pos.z; xyz2enu(ecef_pos, ecef_base_pos, enu_pos); smoothing_status->time_buffer.push_back(rtklib_nav.header.stamp.toSec()); smoothing_status->enu_pos_x_buffer.push_back(enu_pos[0]); smoothing_status->enu_pos_y_buffer.push_back(enu_pos[1]); smoothing_status->enu_pos_z_buffer.push_back(enu_pos[2]); smoothing_status->correction_velocity_buffer.push_back(velocity_scale_factor.correction_velocity.linear.x); time_buffer_length = std::distance(smoothing_status->time_buffer.begin(), smoothing_status->time_buffer.end()); if (time_buffer_length > smoothing_parameter.estimated_number_max) { smoothing_status->time_buffer.erase(smoothing_status->time_buffer.begin()); smoothing_status->enu_pos_x_buffer.erase(smoothing_status->enu_pos_x_buffer.begin()); smoothing_status->enu_pos_y_buffer.erase(smoothing_status->enu_pos_y_buffer.begin()); smoothing_status->enu_pos_z_buffer.erase(smoothing_status->enu_pos_z_buffer.begin()); smoothing_status->correction_velocity_buffer.erase(smoothing_status->correction_velocity_buffer.begin()); } if (smoothing_status->estimated_number < smoothing_parameter.estimated_number_max) { ++smoothing_status->estimated_number; gnss_smooth_pos_enu->status.enabled_status = false; } else { smoothing_status->estimated_number = smoothing_parameter.estimated_number_max; gnss_smooth_pos_enu->status.enabled_status = true; } std::vector<int> velocity_index; std::vector<int> index; int i; double gnss_smooth_pos[3] = {0}; double sum_gnss_pos[3] = {0}; if (smoothing_status->estimated_number == smoothing_parameter.estimated_number_max) { for (i = 0; i < smoothing_status->estimated_number; i++) { index.push_back(i); if (smoothing_status->correction_velocity_buffer[i] > smoothing_parameter.estimated_velocity_threshold) { velocity_index.push_back(i); } } index_length = std::distance(index.begin(), index.end()); velocity_index_length = std::distance(velocity_index.begin(), velocity_index.end()); for (i = 0; i < velocity_index_length; i++) { sum_gnss_pos[0] = sum_gnss_pos[0] + smoothing_status->enu_pos_x_buffer[velocity_index[i]]; sum_gnss_pos[1] = sum_gnss_pos[1] + smoothing_status->enu_pos_y_buffer[velocity_index[i]]; sum_gnss_pos[2] = sum_gnss_pos[2] + smoothing_status->enu_pos_z_buffer[velocity_index[i]]; } if (velocity_index_length > index_length * smoothing_parameter.estimated_threshold) { gnss_smooth_pos[0] = sum_gnss_pos[0]/velocity_index_length; gnss_smooth_pos[1] = sum_gnss_pos[1]/velocity_index_length; gnss_smooth_pos[2] = sum_gnss_pos[2]/velocity_index_length; gnss_smooth_pos_enu->status.estimate_status = true; } else { gnss_smooth_pos[0] = smoothing_status->last_pos[0]; gnss_smooth_pos[1] = smoothing_status->last_pos[1]; gnss_smooth_pos[2] = smoothing_status->last_pos[2]; gnss_smooth_pos_enu->status.estimate_status = false; } smoothing_status->last_pos[0] = gnss_smooth_pos[0]; smoothing_status->last_pos[1] = gnss_smooth_pos[1]; smoothing_status->last_pos[2] = gnss_smooth_pos[2]; } gnss_smooth_pos_enu->enu_pos.x = gnss_smooth_pos[0]; gnss_smooth_pos_enu->enu_pos.y = gnss_smooth_pos[1]; gnss_smooth_pos_enu->enu_pos.z = gnss_smooth_pos[2]; // gnss_smooth_pos_enu->ecef_base_pos = enu_absolute_pos.ecef_base_pos; gnss_smooth_pos_enu->header = rtklib_nav.header; }
44.310811
233
0.76319
shjzhang
2cc564d474ea0a6388fb3bc8a018f3293f77c791
291
cpp
C++
src/Client/MainClient.cpp
Marukyu/NecroEdit
4b2380cc3417c6578476a213e05f4cbc846e5a77
[ "MIT", "Unlicense" ]
13
2016-04-02T14:21:49.000Z
2021-01-10T17:32:43.000Z
src/Client/MainClient.cpp
Marukyu/NecroEdit
4b2380cc3417c6578476a213e05f4cbc846e5a77
[ "MIT", "Unlicense" ]
24
2016-04-02T12:08:39.000Z
2021-01-27T01:21:58.000Z
src/Client/MainClient.cpp
Marukyu/NecroEdit
4b2380cc3417c6578476a213e05f4cbc846e5a77
[ "MIT", "Unlicense" ]
6
2016-04-02T12:05:28.000Z
2017-05-10T14:13:39.000Z
/** * NecroEdit v1.0 */ #include <Client/System/NEApplication.hpp> #include <string> #include <vector> int main(int argc, char *argv[]) { // put arguments into vector. std::vector<std::string> args(argv, argv+argc); // run client. NEApplication client; return client.run(args); }
16.166667
48
0.680412
Marukyu
2cc69a0e44e5b8df7888fbfdda346c3c700cf26a
253
cc
C++
src/AST/ASTRequire.cc
dburkart/check-sieve
667f0e9670e8820e37a8162ec09e794e6e4f1cb4
[ "MIT" ]
20
2015-09-06T04:16:04.000Z
2022-03-24T16:34:56.000Z
src/AST/ASTRequire.cc
dburkart/mail-sieve-verifier
cb51fda06c933dd1e1d0ded05ccba9bedbe67e7f
[ "MIT" ]
24
2015-06-14T01:44:30.000Z
2015-09-05T17:25:11.000Z
src/AST/ASTRequire.cc
dburkart/mail-sieve-verifier
cb51fda06c933dd1e1d0ded05ccba9bedbe67e7f
[ "MIT" ]
3
2015-09-08T05:24:08.000Z
2019-04-01T00:15:29.000Z
#include "ASTRequire.hh" #include "ASTVisitor.hh" namespace sieve { ASTRequire::ASTRequire( yy::location location ) : ASTCommand( location ) { } void ASTRequire::accept( ASTVisitor &visitor ) { visitor.visit(this); } } // namespace sieve
14.882353
48
0.6917
dburkart
2cc7e361669722d95a91ef3d1479964f30499718
190,413
cpp
C++
com/netfx/src/clr/vm/excep.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/netfx/src/clr/vm/excep.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/netfx/src/clr/vm/excep.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /* EXCEP.CPP: * */ #include "common.h" #include "tls.h" #include "frames.h" #include "threads.h" #include "excep.h" #include "object.h" #include "COMString.h" #include "field.h" #include "DbgInterface.h" #include "cgensys.h" #include "gcscan.h" #include "comutilnative.h" #include "comsystem.h" #include "commember.h" #include "SigFormat.h" #include "siginfo.hpp" #include "gc.h" #include "EEDbgInterfaceImpl.h" //so we can clearexception in RealCOMPlusThrow #include "PerfCounters.h" #include "NExport.h" #include "stackwalk.h" //for CrawlFrame, in SetIPFromSrcToDst #include "ShimLoad.h" #include "EEConfig.h" #include "zapmonitor.h" #define FORMAT_MESSAGE_BUFFER_LENGTH 1024 #define SZ_UNHANDLED_EXCEPTION L"Unhandled Exception:" LPCWSTR GetHResultSymbolicName(HRESULT hr); typedef struct { OBJECTREF pThrowable; STRINGREF s1; OBJECTREF pTmpThrowable; } ProtectArgsStruct; static VOID RealCOMPlusThrowPreallocated(); LPVOID GetCurrentSEHRecord(); BOOL ComPlusStubSEH(EXCEPTION_REGISTRATION_RECORD*); BOOL ComPlusFrameSEH(EXCEPTION_REGISTRATION_RECORD*); BOOL ComPlusCoopFrameSEH(EXCEPTION_REGISTRATION_RECORD*); BOOL ComPlusCannotThrowSEH(EXCEPTION_REGISTRATION_RECORD*); VOID RealCOMPlusThrow(OBJECTREF throwable, BOOL rethrow); VOID RealCOMPlusThrow(OBJECTREF throwable); VOID RealCOMPlusThrow(RuntimeExceptionKind reKind); void ThrowUsingMessage(MethodTable * pMT, const WCHAR *pszMsg); void ThrowUsingWin32Message(MethodTable * pMT); void ThrowUsingResource(MethodTable * pMT, DWORD dwMsgResID); void ThrowUsingResourceAndWin32(MethodTable * pMT, DWORD dwMsgResID); void CreateMessageFromRes (MethodTable * pMT, DWORD dwMsgResID, BOOL win32error, WCHAR * wszMessage); extern "C" void JIT_WriteBarrierStart(); extern "C" void JIT_WriteBarrierEnd(); // Max # of inserts allowed in a error message. enum { kNumInserts = 3 }; // Stores the IP of the EE's RaiseException call to detect forgeries. // This variable gets set the first time a COM+ exception is thrown. LPVOID gpRaiseExceptionIP = 0; void COMPlusThrowBoot(HRESULT hr) { _ASSERTE(g_fEEShutDown >= ShutDown_Finalize2 || !"Exception during startup"); ULONG_PTR arg = hr; RaiseException(BOOTUP_EXCEPTION_COMPLUS, EXCEPTION_NONCONTINUABLE, 1, &arg); } //=========================================================================== // Loads a message from the resource DLL and fills in the inserts. // Cannot return NULL: always throws a COM+ exception instead. // NOTE: The returned message is LocalAlloc'd and therefore must be // LocalFree'd. //=========================================================================== LPWSTR CreateExceptionMessage(BOOL fHasResourceID, UINT iResourceID, LPCWSTR wszArg1, LPCWSTR wszArg2, LPCWSTR wszArg3) { THROWSCOMPLUSEXCEPTION(); LPCWSTR wszArgs[kNumInserts] = {wszArg1, wszArg2, wszArg3}; WCHAR wszTemplate[500]; HRESULT hr; if (!fHasResourceID) { wcscpy(wszTemplate, L"%1"); } else { hr = LoadStringRC(iResourceID, wszTemplate, sizeof(wszTemplate)/sizeof(wszTemplate[0]), FALSE); if (FAILED(hr)) { wszTemplate[0] = L'?'; wszTemplate[1] = L'\0'; } } LPWSTR wszFinal = NULL; DWORD res = WszFormatMessage(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ARGUMENT_ARRAY|FORMAT_MESSAGE_ALLOCATE_BUFFER, wszTemplate, 0, 0, (LPWSTR) &wszFinal, 0, (va_list*)wszArgs); if (res == 0) { _ASSERTE(wszFinal == NULL); RealCOMPlusThrowPreallocated(); } return wszFinal; } //=========================================================================== // Gets the message text from an exception //=========================================================================== ULONG GetExceptionMessage(OBJECTREF throwable, LPWSTR buffer, ULONG bufferLength) { if (throwable == NULL) return 0; BinderMethodID sigID=METHOD__EXCEPTION__INTERNAL_TO_STRING; if (!IsException(throwable->GetClass())) sigID=METHOD__OBJECT__TO_STRING; MethodDesc *pMD = g_Mscorlib.GetMethod(sigID); STRINGREF pString = NULL; INT64 arg[1] = {ObjToInt64(throwable)}; pString = Int64ToString(pMD->Call(arg, sigID)); if (pString == NULL) return 0; ULONG length = pString->GetStringLength(); LPWSTR chars = pString->GetBuffer(); if (length < bufferLength) { wcsncpy(buffer, chars, length); buffer[length] = 0; } else { wcsncpy(buffer, chars, bufferLength); buffer[bufferLength-1] = 0; } return length; } void GetExceptionMessage(OBJECTREF throwable, CQuickWSTRNoDtor *pBuffer) { if (throwable == NULL) return; BinderMethodID sigID=METHOD__EXCEPTION__INTERNAL_TO_STRING; if (!IsException(throwable->GetClass())) sigID=METHOD__OBJECT__TO_STRING; MethodDesc *pMD = g_Mscorlib.GetMethod(sigID); STRINGREF pString = NULL; INT64 arg[1] = {ObjToInt64(throwable)}; pString = Int64ToString(pMD->Call(arg, sigID)); if (pString == NULL) return; ULONG length = pString->GetStringLength(); LPWSTR chars = pString->GetBuffer(); if (SUCCEEDED(pBuffer->ReSize(length+1))) wcsncpy(pBuffer->Ptr(), chars, length); else { pBuffer->Maximize(); _ASSERTE(pBuffer->Size() < length); wcsncpy(pBuffer->Ptr(), chars, pBuffer->Size()); } (*pBuffer)[pBuffer->Size()-1] = 0; return; } //------------------------------------------------------------------------ // Array that is used to retrieve the right exception for a given HRESULT. //------------------------------------------------------------------------ struct ExceptionHRInfo { int cHRs; HRESULT *aHRs; }; #define EXCEPTION_BEGIN_DEFINE(ns, reKind, hr) static HRESULT s_##reKind##HRs[] = {hr, #define EXCEPTION_ADD_HR(hr) hr, #define EXCEPTION_END_DEFINE() }; #include "rexcep.h" #undef EXCEPTION_BEGIN_DEFINE #undef EXCEPTION_ADD_HR #undef EXCEPTION_END_DEFINE static ExceptionHRInfo gExceptionHRInfos[] = { #define EXCEPTION_BEGIN_DEFINE(ns, reKind, hr) {sizeof(s_##reKind##HRs) / sizeof(HRESULT), s_##reKind##HRs}, #define EXCEPTION_ADD_HR(hr) #define EXCEPTION_END_DEFINE() #include "rexcep.h" #undef EXCEPTION_BEGIN_DEFINE #undef EXCEPTION_ADD_HR #undef EXCEPTION_END_DEFINE }; void CreateExceptionObject(RuntimeExceptionKind reKind, UINT iResourceID, LPCWSTR wszArg1, LPCWSTR wszArg2, LPCWSTR wszArg3, OBJECTREF *pThrowable) { LPWSTR wszMessage = NULL; EE_TRY_FOR_FINALLY { wszMessage = CreateExceptionMessage(TRUE, iResourceID, wszArg1, wszArg2, wszArg3); CreateExceptionObject(reKind, wszMessage, pThrowable); } EE_FINALLY { if (wszMessage) LocalFree(wszMessage); } EE_END_FINALLY; } void CreateExceptionObject(RuntimeExceptionKind reKind, LPCWSTR pMessage, OBJECTREF *pThrowable) { _ASSERTE(GetThread()); BEGIN_ENSURE_COOPERATIVE_GC(); struct _gc { OBJECTREF throwable; STRINGREF message; } gc; gc.throwable = NULL; gc.message = NULL; GCPROTECT_BEGIN(gc); CreateExceptionObject(reKind, &gc.throwable); gc.message = COMString::NewString(pMessage); INT64 args1[] = { ObjToInt64(gc.throwable), ObjToInt64(gc.message)}; CallConstructor(&gsig_IM_Str_RetVoid, args1); *pThrowable = gc.throwable; GCPROTECT_END(); //Prot END_ENSURE_COOPERATIVE_GC(); } void CreateExceptionObjectWithResource(RuntimeExceptionKind reKind, LPCWSTR resourceName, OBJECTREF *pThrowable) { THROWSCOMPLUSEXCEPTION(); _ASSERTE(resourceName); // You should add a resource. _ASSERTE(GetThread()); BEGIN_ENSURE_COOPERATIVE_GC(); LPWSTR wszValue = NULL; struct _gc { OBJECTREF throwable; STRINGREF str; } gc; gc.throwable = NULL; gc.str = NULL; GCPROTECT_BEGIN(gc); ResMgrGetString(resourceName, &gc.str); CreateExceptionObject(reKind, &gc.throwable); INT64 args1[] = { ObjToInt64(gc.throwable), ObjToInt64(gc.str)}; CallConstructor(&gsig_IM_Str_RetVoid, args1); *pThrowable = gc.throwable; GCPROTECT_END(); //Prot END_ENSURE_COOPERATIVE_GC(); } void CreateTypeInitializationExceptionObject(LPCWSTR pTypeThatFailed, OBJECTREF *pException, OBJECTREF *pThrowable) { _ASSERTE(IsProtectedByGCFrame(pThrowable)); _ASSERTE(IsProtectedByGCFrame(pException)); Thread * pThread = GetThread(); _ASSERTE(pThread); BOOL fGCDisabled = pThread->PreemptiveGCDisabled(); if (!fGCDisabled) pThread->DisablePreemptiveGC(); CreateExceptionObject(kTypeInitializationException, pThrowable); BOOL fDerivesFromException = TRUE; if ( (*pException) != NULL ) { fDerivesFromException = FALSE; MethodTable *pSystemExceptionMT = g_Mscorlib.GetClass(CLASS__EXCEPTION); MethodTable *pInnerMT = (*pException)->GetMethodTable(); while (pInnerMT != NULL) { if (pInnerMT == pSystemExceptionMT) { fDerivesFromException = TRUE; break; } pInnerMT = pInnerMT->GetParentMethodTable(); } } STRINGREF sType = COMString::NewString(pTypeThatFailed); if (fDerivesFromException) { INT64 args1[] = { ObjToInt64(*pThrowable), ObjToInt64(*pException), ObjToInt64(sType)}; CallConstructor(&gsig_IM_Str_Exception_RetVoid, args1); } else { INT64 args1[] = { ObjToInt64(*pThrowable), ObjToInt64(NULL), ObjToInt64(sType)}; CallConstructor(&gsig_IM_Str_Exception_RetVoid, args1); } if (!fGCDisabled) pThread->EnablePreemptiveGC(); } // Creates derivatives of ArgumentException that need two String parameters // in their constructor. void CreateArgumentExceptionObject(RuntimeExceptionKind reKind, LPCWSTR pArgName, STRINGREF pMessage, OBJECTREF *pThrowable) { Thread * pThread = GetThread(); _ASSERTE(pThread); BOOL fGCDisabled = pThread->PreemptiveGCDisabled(); if (!fGCDisabled) pThread->DisablePreemptiveGC(); ProtectArgsStruct prot; memset(&prot, 0, sizeof(ProtectArgsStruct)); prot.s1 = pMessage; GCPROTECT_BEGIN(prot); CreateExceptionObject(reKind, pThrowable); prot.pThrowable = *pThrowable; STRINGREF argName = COMString::NewString(pArgName); // @BUG 59415. It's goofy that ArgumentException and its subclasses // take arguments to their constructors in reverse order. // Likely, this won't ever get fixed. if (reKind == kArgumentException) { INT64 args1[] = { ObjToInt64(prot.pThrowable), ObjToInt64(argName), ObjToInt64(prot.s1) }; CallConstructor(&gsig_IM_Str_Str_RetVoid, args1); } else { INT64 args1[] = { ObjToInt64(prot.pThrowable), ObjToInt64(prot.s1), ObjToInt64(argName) }; CallConstructor(&gsig_IM_Str_Str_RetVoid, args1); } GCPROTECT_END(); //Prot if (!fGCDisabled) pThread->EnablePreemptiveGC(); } void CreateFieldExceptionObject(RuntimeExceptionKind reKind, FieldDesc *pField, OBJECTREF *pThrowable) { LPUTF8 szFullName; LPCUTF8 szClassName, szMember; szMember = pField->GetName(); DefineFullyQualifiedNameForClass(); szClassName = GetFullyQualifiedNameForClass(pField->GetEnclosingClass()); MAKE_FULLY_QUALIFIED_MEMBER_NAME(szFullName, NULL, szClassName, szMember, NULL); MAKE_WIDEPTR_FROMUTF8(szwFullName, szFullName); CreateExceptionObject(reKind, szwFullName, pThrowable); } void CreateMethodExceptionObject(RuntimeExceptionKind reKind, MethodDesc *pMethod, OBJECTREF *pThrowable) { LPUTF8 szFullName; LPCUTF8 szClassName, szMember; szMember = pMethod->GetName(); DefineFullyQualifiedNameForClass(); szClassName = GetFullyQualifiedNameForClass(pMethod->GetClass()); MetaSig tmp(pMethod->GetSig(), pMethod->GetModule()); SigFormat sigFormatter(tmp, szMember); const char * sigStr = sigFormatter.GetCStringParmsOnly(); MAKE_FULLY_QUALIFIED_MEMBER_NAME(szFullName, NULL, szClassName, szMember, sigStr); MAKE_WIDEPTR_FROMUTF8(szwFullName, szFullName); CreateExceptionObject(reKind, szwFullName, pThrowable); } BOOL CreateExceptionObject(RuntimeExceptionKind reKind, OBJECTREF *pThrowable) { _ASSERTE(g_pPreallocatedOutOfMemoryException != NULL); BOOL success = FALSE; if (pThrowable == RETURN_ON_ERROR) return success; Thread * pThread = GetThread(); BOOL fGCDisabled = pThread->PreemptiveGCDisabled(); if (!fGCDisabled) pThread->DisablePreemptiveGC(); MethodTable *pMT = g_Mscorlib.GetException(reKind); OBJECTREF throwable = AllocateObject(pMT); if (pThrowable == THROW_ON_ERROR) { DEBUG_SAFE_TO_THROW_IN_THIS_BLOCK; COMPlusThrow(throwable); } _ASSERTE(pThrowableAvailable(pThrowable)); *pThrowable = throwable; if (!fGCDisabled) pThread->EnablePreemptiveGC(); return success; } BOOL IsException(EEClass *pClass) { while (pClass != NULL) { if (pClass == g_pExceptionClass->GetClass()) return TRUE; pClass = pClass->GetParentClass(); } return FALSE; } #ifdef _IA64_ VOID RealCOMPlusThrowWorker(RuntimeExceptionKind reKind, BOOL fMessage, BOOL fHasResourceID, UINT resID, HRESULT hr, LPCWSTR wszArg1, LPCWSTR wszArg2, LPCWSTR wszArg3, ExceptionData* pED) { _ASSERTE(!"RealCOMPlusThrowWorker -- NOT IMPLEMENTED"); } #else // !_IA64_ static VOID RealCOMPlusThrowWorker(RuntimeExceptionKind reKind, BOOL fMessage, BOOL fHasResourceID, UINT resID, HRESULT hr, LPCWSTR wszArg1, LPCWSTR wszArg2, LPCWSTR wszArg3, ExceptionData* pED) { THROWSCOMPLUSEXCEPTION(); Thread *pThread = GetThread(); _ASSERTE(pThread); // Switch to preemptive GC before we manipulate objectref's. if (!pThread->PreemptiveGCDisabled()) pThread->DisablePreemptiveGC(); if (!g_fExceptionsOK) COMPlusThrowBoot(hr); if (reKind == kOutOfMemoryException && hr == S_OK) RealCOMPlusThrow(ObjectFromHandle(g_pPreallocatedOutOfMemoryException)); if (reKind == kExecutionEngineException && hr == S_OK && (!fMessage)) RealCOMPlusThrow(ObjectFromHandle(g_pPreallocatedExecutionEngineException)); ProtectArgsStruct prot; memset(&prot, 0, sizeof(ProtectArgsStruct)); Frame * __pFrame = pThread->GetFrame(); EE_TRY_FOR_FINALLY { FieldDesc *pFD; MethodTable *pMT; GCPROTECT_BEGIN(prot); LPWSTR wszExceptionMessage = NULL; GCPROTECT_BEGININTERIOR(wszArg1); pMT = g_Mscorlib.GetException(reKind); // Will throw if we fail to load the type. // If there is a message, copy that in the event that a caller passed in // a pointer into the middle of an un-GC-protected String object if (fMessage) { wszExceptionMessage = CreateExceptionMessage(fHasResourceID, resID, wszArg1, wszArg2, wszArg3); } GCPROTECT_END(); prot.pThrowable = AllocateObject(pMT); CallDefaultConstructor(prot.pThrowable); // If we have exception data then retrieve information from there. if (pED) { // The HR in the exception data better be the same as the one thrown. _ASSERTE(hr == pED->hr); // Retrieve the description from the exception data. if (pED->bstrDescription != NULL) { // If this truly is a BSTR, we can't guarantee that it is null terminated! // call NewString constructor with SysStringLen(bstr) as second param. prot.s1 = COMString::NewString(pED->bstrDescription, SysStringLen(pED->bstrDescription)); } // Set the _helpURL field in the exception. if (pED->bstrHelpFile) { // @MANAGED: Set Exception's _helpURL field pFD = g_Mscorlib.GetField(FIELD__EXCEPTION__HELP_URL); // Create the helt link from the help file and the help context. STRINGREF helpStr = NULL; if (pED->dwHelpContext != 0) { // We have a non 0 help context so use it to form the help link. WCHAR strHelpContext[32]; _ltow(pED->dwHelpContext, strHelpContext, 10); helpStr = COMString::NewString((INT32)(SysStringLen(pED->bstrHelpFile) + wcslen(strHelpContext) + 1)); swprintf(helpStr->GetBuffer(), L"%s#%s", pED->bstrHelpFile, strHelpContext); } else { // The help context is 0 so we simply use the help file to from the help link. helpStr = COMString::NewString(pED->bstrHelpFile, SysStringLen(pED->bstrHelpFile)); } // Set the value of the help link field. pFD->SetRefValue(prot.pThrowable, (OBJECTREF)helpStr); } // Set the Source field in the exception. if (pED->bstrSource) { pFD = g_Mscorlib.GetField(FIELD__EXCEPTION__SOURCE); STRINGREF sourceStr = COMString::NewString(pED->bstrSource, SysStringLen(pED->bstrSource)); pFD->SetRefValue(prot.pThrowable, (OBJECTREF)sourceStr); } else { // for now set a null source pFD = g_Mscorlib.GetField(FIELD__EXCEPTION__SOURCE); pFD->SetRefValue(prot.pThrowable, (OBJECTREF)COMString::GetEmptyString()); } } else if (fMessage) { EE_TRY_FOR_FINALLY { prot.s1 = COMString::NewString(wszExceptionMessage); } EE_FINALLY { LocalFree(wszExceptionMessage); } EE_END_FINALLY; } if (FAILED(hr)) { // If we haven't managed to get a message so far then try and get one from the // the OS using format message. if (prot.s1 == NULL) { WCHAR *strMessageBuf; if (WszFormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, hr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (WCHAR *)&strMessageBuf, 0, 0)) { // System messages contain a trailing \r\n, which we don't want normally. int iLen = lstrlenW(strMessageBuf); if (iLen > 3 && strMessageBuf[iLen - 2] == '\r' && strMessageBuf[iLen - 1] == '\n') strMessageBuf[iLen - 2] = '\0'; // Use the formated error message. prot.s1 = COMString::NewString(strMessageBuf); // Free the buffer allocated by FormatMessage. LocalFree((HLOCAL)strMessageBuf); } } // If we haven't found the message yet and if hr is one of those we know has an // entry in mscorrc.rc that doesn't take arguments, print that out. if (prot.s1 == NULL && HRESULT_FACILITY(hr) == FACILITY_URT) { switch(hr) { case SN_CRYPTOAPI_CALL_FAILED: case SN_NO_SUITABLE_CSP: wszExceptionMessage = CreateExceptionMessage(TRUE, HRESULT_CODE(hr), 0, 0, 0); prot.s1 = COMString::NewString(wszExceptionMessage); LocalFree(wszExceptionMessage); break; } } // If we still haven't managed to get an error message, use the default error message. if (prot.s1 == NULL) { LPCWSTR wszSymbolicName = GetHResultSymbolicName(hr); WCHAR numBuff[140]; Wszultow(hr, numBuff, 16 /*hex*/); if (wszSymbolicName) { wcscat(numBuff, L" ("); wcscat(numBuff, wszSymbolicName); wcscat(numBuff, L")"); } wszExceptionMessage = CreateExceptionMessage(TRUE, IDS_EE_THROW_HRESULT, numBuff, wszArg2, wszArg3); prot.s1 = COMString::NewString(wszExceptionMessage); LocalFree(wszExceptionMessage); } } // Set the message field. It is not safe doing this through the constructor // since the string constructor for some exceptions add a prefix to the message // which we don't want. // // We only want to replace whatever the default constructor put there, if we // have something meaningful to add. if (prot.s1 != NULL) { pFD = g_Mscorlib.GetField(FIELD__EXCEPTION__MESSAGE); pFD->SetRefValue((OBJECTREF) prot.pThrowable, (OBJECTREF) prot.s1); } // If the HRESULT is not S_OK then set it by setting the field value directly. if (hr != S_OK) { pFD = g_Mscorlib.GetField(FIELD__EXCEPTION__HRESULT); pFD->SetValue32(prot.pThrowable, hr); } RealCOMPlusThrow(prot.pThrowable); GCPROTECT_END(); //Prot } EE_FINALLY { // make sure we pop out the frames. If we don't do this, we will leave some // frames on the thread when ThreadAbortException happens. UnwindFrameChain( pThread, __pFrame); } EE_END_FINALLY } #endif // !_IA64_ static VOID RealCOMPlusThrowWorker(RuntimeExceptionKind reKind, BOOL fMessage, BOOL fHasResourceID, UINT resID, HRESULT hr, LPCWSTR wszArg1, LPCWSTR wszArg2, LPCWSTR wszArg3) { THROWSCOMPLUSEXCEPTION(); RealCOMPlusThrowWorker(reKind, fMessage, fHasResourceID, resID, hr, wszArg1, wszArg2, wszArg3, NULL); } //========================================================================== // Throw the preallocated OutOfMemory object. //========================================================================== static VOID RealCOMPlusThrowPreallocated() { THROWSCOMPLUSEXCEPTION(); LOG((LF_EH, LL_INFO100, "In RealCOMPlusThrowPreallocated\n")); if (g_pPreallocatedOutOfMemoryException != NULL) { RealCOMPlusThrow(ObjectFromHandle(g_pPreallocatedOutOfMemoryException)); } else { // Big trouble. _ASSERTE(!"Unrecoverable out of memory situation."); RaiseException(EXCEPTION_ACCESS_VIOLATION,EXCEPTION_NONCONTINUABLE, 0,0); _ASSERTE(!"Cannot continue after COM+ exception"); // Debugger can bring you here. SafeExitProcess(0); // We can't continue. } } // ========================================================================== // COMPlusComputeNestingLevel // // This is code factored out of COMPlusThrowCallback to figure out // what the number of nested exception handlers is. // ========================================================================== DWORD COMPlusComputeNestingLevel( IJitManager *pIJM, METHODTOKEN mdTok, SIZE_T offsNat, bool fGte) { // Determine the nesting level of EHClause. Just walk the table // again, and find out how many handlers enclose it DWORD nestingLevel = 0; EH_CLAUSE_ENUMERATOR pEnumState2; EE_ILEXCEPTION_CLAUSE EHClause2, *EHClausePtr; unsigned EHCount2 = pIJM->InitializeEHEnumeration(mdTok, &pEnumState2); if (EHCount2 > 1) for (unsigned j=0; j<EHCount2; j++) { EHClausePtr = pIJM->GetNextEHClause(mdTok,&pEnumState2,&EHClause2); _ASSERTE(EHClausePtr->HandlerEndPC != -1); // TODO remove, only protects against a deprecated convention if (fGte ) { if (offsNat >= EHClausePtr->HandlerStartPC && offsNat < EHClausePtr->HandlerEndPC) nestingLevel++; } else { if (offsNat > EHClausePtr->HandlerStartPC && offsNat < EHClausePtr->HandlerEndPC) nestingLevel++; } } return nestingLevel; } // ******************************* EHRangeTreeNode ************************** // EHRangeTreeNode::EHRangeTreeNode(void) { CommonCtor(0, 0); } EHRangeTreeNode::EHRangeTreeNode(DWORD start, DWORD end) { CommonCtor(start, end); } void EHRangeTreeNode::CommonCtor(DWORD start, DWORD end) { m_depth = 0; m_pTree = NULL; m_pContainedBy = NULL; m_clause = NULL; m_offStart = start; m_offEnd = end; } bool EHRangeTreeNode::Contains(DWORD addrStart, DWORD addrEnd) { return ( addrStart >= m_offStart && addrEnd < m_offEnd ); } bool EHRangeTreeNode::TryContains(DWORD addrStart, DWORD addrEnd) { if (m_clause != NULL && addrStart >= m_clause->TryStartPC && addrEnd < m_clause->TryEndPC) return true; return false; } bool EHRangeTreeNode::HandlerContains(DWORD addrStart, DWORD addrEnd) { if (m_clause != NULL && addrStart >= m_clause->HandlerStartPC && addrEnd < m_clause->HandlerEndPC ) return true; return false; } HRESULT EHRangeTreeNode::AddContainedRange(EHRangeTreeNode *pContained) { _ASSERTE(pContained != NULL); EHRangeTreeNode **ppEH = m_containees.Append(); if (ppEH == NULL) return E_OUTOFMEMORY; (*ppEH) = pContained; return S_OK; } // ******************************* EHRangeTree ************************** // EHRangeTree::EHRangeTree(COR_ILMETHOD_DECODER *pMethodDecoder) { LOG((LF_CORDB, LL_INFO10000, "EHRT::ERHT: on disk!\n")); _ASSERTE(pMethodDecoder!=NULL); m_EHCount = 0xFFFFFFFF; m_isNative = FALSE; // !!! THIS ISN"T ON THE HEAP - it's only a covienient packaging for // the core constructor method, so don't save pointers to it !!! EHRT_InternalIterator ii; ii.which = EHRT_InternalIterator::EHRTT_ON_DISK; if(pMethodDecoder->EH == NULL) { m_EHCount = 0; } else { const COR_ILMETHOD_SECT_EH *sectEH = pMethodDecoder->EH; m_EHCount = sectEH->EHCount(); ii.tf.OnDisk.sectEH = sectEH; } DWORD methodSize = pMethodDecoder->GetCodeSize(); CommonCtor(&ii, methodSize); } EHRangeTree::EHRangeTree(IJitManager* pIJM, METHODTOKEN methodToken, DWORD methodSize) { LOG((LF_CORDB, LL_INFO10000, "EHRT::ERHT: already loaded!\n")); m_EHCount = 0xFFFFFFFF; m_isNative = TRUE; // !!! THIS ISN"T ON THE HEAP - it's only a covienient packaging for // the core constructor method, so don't save pointers to it !!! EHRT_InternalIterator ii; ii.which = EHRT_InternalIterator::EHRTT_JIT_MANAGER; ii.tf.JitManager.pIJM = pIJM; ii.tf.JitManager.methodToken = methodToken; m_EHCount = pIJM->InitializeEHEnumeration(methodToken, (EH_CLAUSE_ENUMERATOR*)&ii.tf.JitManager.pEnumState); CommonCtor(&ii, methodSize); } EHRangeTree::~EHRangeTree() { if (m_rgNodes != NULL) delete [] m_rgNodes; if (m_rgClauses != NULL) delete [] m_rgClauses; } //Dtor // Before calling this, m_EHCount must be filled in. void EHRangeTree::CommonCtor(EHRT_InternalIterator *pii, DWORD methodSize) { _ASSERTE(m_EHCount != 0xFFFFFFFF); ULONG i = 0; m_maxDepth = EHRT_INVALID_DEPTH; m_rgClauses = NULL; m_rgNodes = NULL; m_root = NULL; m_hrInit = S_OK; if (m_EHCount > 0) { m_rgClauses = new EE_ILEXCEPTION_CLAUSE[m_EHCount]; if (m_rgClauses == NULL) { m_hrInit = E_OUTOFMEMORY; goto LError; } } LOG((LF_CORDB, LL_INFO10000, "EHRT::CC: m_ehcount:0x%x, m_rgClauses:0%x\n", m_EHCount, m_rgClauses)); m_rgNodes = new EHRangeTreeNode[m_EHCount+1]; if (m_rgNodes == NULL) { m_hrInit = E_OUTOFMEMORY; goto LError; } //this contains everything, even stuff on the last IP m_root = &(m_rgNodes[m_EHCount]); m_root->m_offEnd = methodSize+1; LOG((LF_CORDB, LL_INFO10000, "EHRT::CC: rgNodes:0x%x\n", m_rgNodes)); if (m_EHCount ==0) { LOG((LF_CORDB, LL_INFO10000, "EHRT::CC: About to leave!\n")); m_maxDepth = 0; // we don't actually have any EH clauses return; } LOG((LF_CORDB, LL_INFO10000, "EHRT::CC: Sticking around!\n")); EE_ILEXCEPTION_CLAUSE *pEHClause = NULL; EHRangeTreeNode *pNodeCur; // First, load all the EH clauses into the object. for(i=0; i < m_EHCount; i++) { LOG((LF_CORDB, LL_INFO10000, "EHRT::CC: i:0x%x!\n", i)); switch(pii->which) { case EHRT_InternalIterator::EHRTT_JIT_MANAGER: { LOG((LF_CORDB, LL_INFO10000, "EHRT::CC: EHRTT_JIT_MANAGER\n", i)); pEHClause = pii->tf.JitManager.pIJM->GetNextEHClause( pii->tf.JitManager.methodToken, (EH_CLAUSE_ENUMERATOR*)&(pii->tf.JitManager.pEnumState), &(m_rgClauses[i]) ); LOG((LF_CORDB, LL_INFO10000, "EHRT::CC: EHRTT_JIT_MANAGER got clause\n", i)); // What's actually // happening is that the JIT ignores m_rgClauses[i], and simply // hands us back a pointer to their internal data structure. // So copy it over, THEN muck with it. m_rgClauses[i] = (*pEHClause); //bitwise copy pEHClause = &(m_rgClauses[i]); LOG((LF_CORDB, LL_INFO10000, "EHRT::CC: clause 0x%x," "addrof:0x%x\n", i, &(m_rgClauses[i]) )); break; } case EHRT_InternalIterator::EHRTT_ON_DISK: { LOG((LF_CORDB, LL_INFO10000, "EHRT::CC: EHRTT_ON_DISK\n")); IMAGE_COR_ILMETHOD_SECT_EH_CLAUSE_FAT clause; const IMAGE_COR_ILMETHOD_SECT_EH_CLAUSE_FAT *pClause; pClause = pii->tf.OnDisk.sectEH->EHClause(i, &clause); LOG((LF_CORDB, LL_INFO10000, "EHRT::CC: EHRTT_ON_DISK got clause\n")); // Convert between data structures. pEHClause = &(m_rgClauses[i]); // DON'T DELETE THIS!!!!!!!!!!!!!!!!!!!!!!!!!!!!! pEHClause->Flags = pClause->Flags; pEHClause->TryStartPC = pClause->TryOffset; pEHClause->TryEndPC = pClause->TryOffset+pClause->TryLength; pEHClause->HandlerStartPC = pClause->HandlerOffset; pEHClause->HandlerEndPC = pClause->HandlerOffset+pClause->HandlerLength; LOG((LF_CORDB, LL_INFO10000, "EHRT::CC: post disk get\n")); break; } #ifdef _DEBUG default: { _ASSERTE( !"Debugger is trying to analyze an unknown " "EH format!"); } #endif //_DEBUG } LOG((LF_CORDB, LL_INFO10000, "EHRT::CC: got da clause!\n")); _ASSERTE(pEHClause->HandlerEndPC != -1); // TODO remove, only protects against a deprecated convention pNodeCur = &(m_rgNodes[i]); pNodeCur->m_pTree = this; pNodeCur->m_clause = pEHClause; // Since the filter doesn't have a start/end FilterPC, the only // way we can know the size of the filter is if it's located // immediately prior to it's handler. We assume that this is, // and if it isn't, we're so amazingly hosed that we can't // continue if (pEHClause->Flags == COR_ILEXCEPTION_CLAUSE_FILTER && (pEHClause->FilterOffset >= pEHClause->HandlerStartPC || pEHClause->FilterOffset < pEHClause->TryEndPC)) { m_hrInit = CORDBG_E_SET_IP_IMPOSSIBLE; goto LError; } pNodeCur->m_offStart = pEHClause->TryStartPC; pNodeCur->m_offEnd = pEHClause->HandlerEndPC; } LOG((LF_CORDB, LL_INFO10000, "EHRT::CC: about to do the second pass\n")); // Second, for each EH, find it's most limited, containing clause for(i=0; i < m_EHCount; i++) { LOG((LF_CORDB, LL_INFO10000, "EHRT::CC: SP:0x%x\n", i)); pNodeCur = &(m_rgNodes[i]); EHRangeTreeNode *pNodeCandidate = NULL; pNodeCandidate = FindContainer(pNodeCur); _ASSERTE(pNodeCandidate != NULL); pNodeCur->m_pContainedBy = pNodeCandidate; LOG((LF_CORDB, LL_INFO10000, "EHRT::CC: SP: about to add to tree\n")); HRESULT hr = pNodeCandidate->AddContainedRange(pNodeCur); if (FAILED(hr)) { m_hrInit = hr; goto LError; } } return; LError: LOG((LF_CORDB, LL_INFO10000, "EHRT::CC: LError - something went wrong!\n")); if (m_rgClauses != NULL) { delete [] m_rgClauses; m_rgClauses = NULL; } if (m_rgNodes != NULL) { delete [] m_rgNodes; m_rgNodes = NULL; } LOG((LF_CORDB, LL_INFO10000, "EHRT::CC: Falling off of LError!\n")); } // Ctor Core EHRangeTreeNode *EHRangeTree::FindContainer(EHRangeTreeNode *pNodeCur) { EHRangeTreeNode *pNodeCandidate = NULL; // Examine the root, too. for(ULONG iInner=0; iInner < m_EHCount+1; iInner++) { EHRangeTreeNode *pNodeSearch = &(m_rgNodes[iInner]); if (pNodeSearch->Contains(pNodeCur->m_offStart, pNodeCur->m_offEnd) && pNodeCur != pNodeSearch) { if (pNodeCandidate == NULL) { pNodeCandidate = pNodeSearch; } else if (pNodeSearch->m_offStart > pNodeCandidate->m_offStart && pNodeSearch->m_offEnd < pNodeCandidate->m_offEnd) { pNodeCandidate = pNodeSearch; } } } return pNodeCandidate; } EHRangeTreeNode *EHRangeTree::FindMostSpecificContainer(DWORD addr) { EHRangeTreeNode node(addr, addr); return FindContainer(&node); } EHRangeTreeNode *EHRangeTree::FindNextMostSpecificContainer( EHRangeTreeNode *pNodeCur, DWORD addr) { EHRangeTreeNode **rgpNodes = pNodeCur->m_containees.Table(); if (NULL == rgpNodes) return pNodeCur; // It's possible that no subrange contains the desired address, so // keep a reasonable default around. EHRangeTreeNode *pNodeCandidate = pNodeCur; USHORT cSubRanges = pNodeCur->m_containees.Count(); EHRangeTreeNode **ppNodeSearch = pNodeCur->m_containees.Table(); for (int i = 0; i < cSubRanges; i++, ppNodeSearch++) { if ((*ppNodeSearch)->Contains(addr, addr) && (*ppNodeSearch)->m_offStart >= pNodeCandidate->m_offStart && (*ppNodeSearch)->m_offEnd < pNodeCandidate->m_offEnd) { pNodeCandidate = (*ppNodeSearch); } } return pNodeCandidate; } BOOL EHRangeTree::isNative() { return m_isNative; } ULONG32 EHRangeTree::MaxDepth() { // If we haven't asked for the depth before, then we'll // have to compute it now. if (m_maxDepth == EHRT_INVALID_DEPTH) { INT32 i; INT32 iMax; EHRangeTreeNode *pNodeCur = NULL; // Create a queue that will eventually hold all the nodes EHRangeTreeNode **rgNodes = new EHRangeTreeNode*[m_EHCount+1]; if (rgNodes == NULL) { return EHRT_INVALID_DEPTH; } // Prime the queue by adding the root node. rgNodes[0] = m_root; m_root->m_depth = 0; m_maxDepth = 0; // iMax = count of elements in the rgNodes queue. This will // increase as we put more in. for(i = 0, iMax = 1; i < iMax;i++) { // For all the children of the current element that we're processing. EHRangeTreeNode **rgChildNodes = rgNodes[i]->m_containees.Table(); if (NULL != rgChildNodes) { USHORT cKids = rgNodes[i]->m_containees.Count(); pNodeCur = rgChildNodes[0]; // Loop over the children - iKid just keeps track of // how many we've done. for (int iKid = 0; iKid < cKids; iKid++, pNodeCur++) { // The depth of children of node i is // the depth of node i + 1, since they're one deeper. pNodeCur->m_depth = rgNodes[i]->m_depth+1; // Put the children into the queue, so we can get // their children, as well. rgNodes[iMax++] = pNodeCur; } } } i--; //back up to the last element m_maxDepth = rgNodes[i]->m_depth; // Clean up the queue. delete [] rgNodes; rgNodes = NULL; } return m_maxDepth; } // @BUG 59560: BOOL EHRangeTree::isAtStartOfCatch(DWORD offset) { if (NULL != m_rgNodes && m_EHCount != 0) { for(unsigned i = 0; i < m_EHCount;i++) { if (m_rgNodes[i].m_clause->HandlerStartPC == offset && (m_rgNodes[i].m_clause->Flags != COR_ILEXCEPTION_CLAUSE_FILTER && m_rgNodes[i].m_clause->Flags != COR_ILEXCEPTION_CLAUSE_FINALLY && m_rgNodes[i].m_clause->Flags != COR_ILEXCEPTION_CLAUSE_FAULT)) return TRUE; } } return FALSE; } enum TRY_CATCH_FINALLY { TCF_NONE= 0, TCF_TRY, TCF_FILTER, TCF_CATCH, TCF_FINALLY, TCF_COUNT, //count of all elements, not an element itself }; #ifdef LOGGING char *TCFStringFromConst(TRY_CATCH_FINALLY tcf) { switch( tcf ) { case TCF_NONE: return "TCFS_NONE"; break; case TCF_TRY: return "TCFS_TRY"; break; case TCF_FILTER: return "TCF_FILTER"; break; case TCF_CATCH: return "TCFS_CATCH"; break; case TCF_FINALLY: return "TCFS_FINALLY"; break; case TCF_COUNT: return "TCFS_COUNT"; break; default: return "INVALID TCFS VALUE"; break; } } #endif //LOGGING // We're unwinding if we'll return to the EE's code. Otherwise // we'll return to someplace in the current code. Anywhere outside // this function is "EE code". bool FinallyIsUnwinding(EHRangeTreeNode *pNode, ICodeManager* pEECM, PREGDISPLAY pReg, SLOT addrStart) { const BYTE *pbRetAddr = pEECM->GetFinallyReturnAddr(pReg); if (pbRetAddr < (const BYTE *)addrStart) return true; DWORD offset = (DWORD)(size_t)(pbRetAddr - addrStart); EHRangeTreeNode *pRoot = pNode->m_pTree->m_root; if(!pRoot->Contains((DWORD)offset, (DWORD)offset)) return true; else return false; } BOOL LeaveCatch(ICodeManager* pEECM, Thread *pThread, CONTEXT *pCtx, void *firstException, void *methodInfoPtr, unsigned offset) { // We can assert these things here, and skip a call // to COMPlusCheckForAbort later. // If no abort has been requested, _ASSERTE((pThread->GetThrowable() != NULL) || // or if there is a pending exception. (!pThread->IsAbortRequested()) ); DWORD esp = ::COMPlusEndCatch(pThread, pCtx, firstException); // Do JIT-specific work pEECM->LeaveCatch(methodInfoPtr, offset, pCtx); #ifdef _X86_ pCtx->Esp = esp; #elif defined(CHECK_PLATFORM_BUILD) #error "Platform NYI" #else _ASSERTE(!"Platform NYI"); #endif return TRUE; } TRY_CATCH_FINALLY GetTcf(EHRangeTreeNode *pNode, ICodeManager* pEECM, void *methodInfoPtr, unsigned offset, PCONTEXT pCtx, DWORD nl) { _ASSERTE(pNode != NULL); TRY_CATCH_FINALLY tcf; if (!pNode->Contains(offset,offset)) { tcf = TCF_NONE; } else if (pNode->TryContains(offset, offset)) { tcf = TCF_TRY; } else { _ASSERTE(pNode->m_clause); if (IsFilterHandler(pNode->m_clause) && offset >= pNode->m_clause->FilterOffset && offset < pNode->m_clause->HandlerStartPC) tcf = TCF_FILTER; else if (IsFaultOrFinally(pNode->m_clause)) tcf = TCF_FINALLY; else tcf = TCF_CATCH; } return tcf; } const DWORD bEnter = 0x01; const DWORD bLeave = 0x02; HRESULT IsLegalTransition(Thread *pThread, bool fCanSetIPOnly, DWORD fEnter, EHRangeTreeNode *pNode, DWORD offFrom, DWORD offTo, ICodeManager* pEECM, PREGDISPLAY pReg, SLOT addrStart, void *firstException, void *methodInfoPtr, PCONTEXT pCtx, DWORD nlFrom, DWORD nlTo) { #ifdef _DEBUG if (fEnter & bEnter) { _ASSERTE(pNode->Contains(offTo, offTo)); } if (fEnter & bLeave) { _ASSERTE(pNode->Contains(offFrom, offFrom)); } #endif //_DEBUG // First, figure out where we're coming from/going to TRY_CATCH_FINALLY tcfFrom = GetTcf(pNode, pEECM, methodInfoPtr, offFrom, pCtx, nlFrom); TRY_CATCH_FINALLY tcfTo = GetTcf(pNode, pEECM, methodInfoPtr, offTo, pCtx, nlTo); LOG((LF_CORDB, LL_INFO10000, "ILT: from %s to %s\n", TCFStringFromConst(tcfFrom), TCFStringFromConst(tcfTo))); // Now we'll consider, case-by-case, the various permutations that // can arise switch(tcfFrom) { case TCF_NONE: case TCF_TRY: { switch(tcfTo) { case TCF_NONE: case TCF_TRY: { return S_OK; break; } case TCF_FILTER: { return CORDBG_E_CANT_SETIP_INTO_OR_OUT_OF_FILTER; break; } case TCF_CATCH: { return CORDBG_E_CANT_SET_IP_INTO_CATCH; break; } case TCF_FINALLY: { return CORDBG_E_CANT_SET_IP_INTO_FINALLY; break; } } break; } case TCF_FILTER: { switch(tcfTo) { case TCF_NONE: case TCF_TRY: case TCF_CATCH: case TCF_FINALLY: { return CORDBG_E_CANT_SETIP_INTO_OR_OUT_OF_FILTER; break; } case TCF_FILTER: { return S_OK; break; } } break; } case TCF_CATCH: { switch(tcfTo) { case TCF_NONE: case TCF_TRY: { CONTEXT *pCtx = pThread->GetFilterContext(); if (pCtx == NULL) return CORDBG_E_SET_IP_IMPOSSIBLE; if (!fCanSetIPOnly) { if (!LeaveCatch(pEECM, pThread, pCtx, firstException, methodInfoPtr, offFrom)) return E_FAIL; } return S_OK; break; } case TCF_FILTER: { return CORDBG_E_CANT_SETIP_INTO_OR_OUT_OF_FILTER; break; } case TCF_CATCH: { return S_OK; break; } case TCF_FINALLY: { return CORDBG_E_CANT_SET_IP_INTO_FINALLY; break; } } break; } case TCF_FINALLY: { switch(tcfTo) { case TCF_NONE: case TCF_TRY: { if (!FinallyIsUnwinding(pNode, pEECM, pReg, addrStart)) { CONTEXT *pCtx = pThread->GetFilterContext(); if (pCtx == NULL) return CORDBG_E_SET_IP_IMPOSSIBLE; if (!fCanSetIPOnly) { if (!pEECM->LeaveFinally(methodInfoPtr, offFrom, pCtx, nlFrom)) return E_FAIL; } return S_OK; } else { return CORDBG_E_CANT_SET_IP_OUT_OF_FINALLY; } break; } case TCF_FILTER: { return CORDBG_E_CANT_SETIP_INTO_OR_OUT_OF_FILTER; break; } case TCF_CATCH: { return CORDBG_E_CANT_SET_IP_INTO_CATCH; break; } case TCF_FINALLY: { return S_OK; break; } } break; } break; } _ASSERTE( !"IsLegalTransition: We should never reach this point!" ); return CORDBG_E_SET_IP_IMPOSSIBLE; } // @BUG 59560: We need this to determine what // to do based on whether the stack in general is empty, not // this kludgey hack that's just a hotfix. HRESULT DestinationIsValid(void *pDjiToken, DWORD offTo, EHRangeTree *pERHT) { // We'll add a call to the DebugInterface that takes this // & tells us if the destination is a stack empty point. // DebuggerJitInfo *pDji = (DebuggerJitInfo *)pDjiToken; if (pERHT->isAtStartOfCatch(offTo)) return CORDBG_S_BAD_START_SEQUENCE_POINT; else return S_OK; } // We want to keep the 'worst' HRESULT - if one has failed (..._E_...) & the // other hasn't, take the failing one. If they've both/neither failed, then // it doesn't matter which we take. // Note that this macro favors retaining the first argument #define WORST_HR(hr1,hr2) (FAILED(hr1)?hr1:hr2) HRESULT SetIPFromSrcToDst(Thread *pThread, IJitManager* pIJM, METHODTOKEN MethodToken, SLOT addrStart, // base address of method DWORD offFrom, // native offset DWORD offTo, // native offset bool fCanSetIPOnly, // if true, don't do any real work PREGDISPLAY pReg, PCONTEXT pCtx, DWORD methodSize, void *firstExceptionHandler, void *pDji) { LPVOID methodInfoPtr; HRESULT hr = S_OK; HRESULT hrReturn = S_OK; BYTE *EipReal = *(pReg->pPC); EHRangeTree *pERHT = NULL; DWORD nlFrom; DWORD nlTo; bool fCheckOnly = true; nlFrom = COMPlusComputeNestingLevel(pIJM, MethodToken, offFrom, true); nlTo = COMPlusComputeNestingLevel(pIJM, MethodToken, offTo, true); // Make sure that the start point is GC safe *(pReg->pPC) = (BYTE *)(addrStart+offFrom); // This seems redundant? For now, I'm just putting the assert, MikePa should remove // this after reviewing IJitManager* pEEJM = ExecutionManager::FindJitMan(*(pReg->pPC)); _ASSERTE(pEEJM); _ASSERTE(pEEJM == pIJM); methodInfoPtr = pEEJM->GetGCInfo(MethodToken); ICodeManager * pEECM = pEEJM->GetCodeManager(); EECodeInfo codeInfo(MethodToken, pEEJM); // Make sure that the end point is GC safe *(pReg->pPC) = (BYTE *)(addrStart + offTo); IJitManager* pEEJMDup; pEEJMDup = ExecutionManager::FindJitMan(*(pReg->pPC)); _ASSERTE(pEEJMDup == pEEJM); // Undo this here so stack traces, etc, don't look weird *(pReg->pPC) = EipReal; methodInfoPtr = pEEJM->GetGCInfo(MethodToken); ICodeManager * pEECMDup; pEECMDup = pEEJM->GetCodeManager(); _ASSERTE(pEECMDup == pEECM); EECodeInfo codeInfoDup(MethodToken, pEEJM); // Do both checks here so compiler doesn't complain about skipping // initialization b/c of goto. if (!pEECM->IsGcSafe(pReg, methodInfoPtr, &codeInfo,0) && fCanSetIPOnly) { hrReturn = WORST_HR(hrReturn, CORDBG_E_SET_IP_IMPOSSIBLE); } if (!pEECM->IsGcSafe(pReg, methodInfoPtr, &codeInfoDup,0) && fCanSetIPOnly) { hrReturn = WORST_HR(hrReturn, CORDBG_E_SET_IP_IMPOSSIBLE); } // Create our structure for analyzing this. // @PERF: optimize - hold on to this so we don't rebuild it for both // CanSetIP & SetIP. pERHT = new EHRangeTree(pEEJM, MethodToken, methodSize); if (FAILED(pERHT->m_hrInit)) { hrReturn = WORST_HR(hrReturn, pERHT->m_hrInit); delete pERHT; goto LExit; } if ((hr = DestinationIsValid(pDji, offTo, pERHT)) != S_OK && fCanSetIPOnly) { hrReturn = WORST_HR(hrReturn,hr); } // The basic approach is this: We'll start with the most specific (smallest) // EHClause that contains the starting address. We'll 'back out', to larger // and larger ranges, until we either find an EHClause that contains both // the from and to addresses, or until we reach the root EHRangeTreeNode, // which contains all addresses within it. At each step, we check/do work // that the various transitions (from inside to outside a catch, etc). // At that point, we do the reverse process - we go from the EHClause that // encompasses both from and to, and narrow down to the smallest EHClause that // encompasses the to point. We use our nifty data structure to manage // the tree structure inherent in this process. // // NOTE: We do this process twice, once to check that we're not doing an // overall illegal transition, such as ultimately set the IP into // a catch, which is never allowed. We're doing this because VS // calls SetIP without calling CanSetIP first, and so we should be able // to return an error code and have the stack in the same condition // as the start of the call, and so we shouldn't back out of clauses // or move into them until we're sure that can be done. retryForCommit: EHRangeTreeNode *node; EHRangeTreeNode *nodeNext; node = pERHT->FindMostSpecificContainer(offFrom); while (!node->Contains(offTo, offTo)) { hr = IsLegalTransition(pThread, fCheckOnly, bLeave, node, offFrom, offTo, pEECM, pReg, addrStart, firstExceptionHandler, methodInfoPtr, pCtx, nlFrom, nlTo); if (FAILED(hr)) { hrReturn = WORST_HR(hrReturn,hr); } node = node->m_pContainedBy; // m_root prevents node from ever being NULL. } if (node != pERHT->m_root) { hr = IsLegalTransition(pThread, fCheckOnly, bEnter|bLeave, node, offFrom, offTo, pEECM, pReg, addrStart, firstExceptionHandler, methodInfoPtr, pCtx, nlFrom, nlTo); if (FAILED(hr)) { hrReturn = WORST_HR(hrReturn,hr); } } nodeNext = pERHT->FindNextMostSpecificContainer(node, offTo); while(nodeNext != node) { hr = IsLegalTransition(pThread, fCheckOnly, bEnter, nodeNext, offFrom, offTo, pEECM, pReg, addrStart, firstExceptionHandler, methodInfoPtr, pCtx, nlFrom, nlTo); if (FAILED(hr)) { hrReturn = WORST_HR(hrReturn, hr); } node = nodeNext; nodeNext = pERHT->FindNextMostSpecificContainer(node, offTo); } // If it was the intention to actually set the IP and the above transition checks succeeded, // then go back and do it all again but this time widen and narrow the thread's actual scope if (!fCanSetIPOnly && fCheckOnly) { fCheckOnly = false; goto retryForCommit; } LExit: if (pERHT != NULL) delete pERHT; return hrReturn; } // This function should only be called if the thread is suspended and sitting in jitted code BOOL IsInFirstFrameOfHandler(Thread *pThread, IJitManager *pJitManager, METHODTOKEN MethodToken, DWORD offset) { // if don't have a throwable the aren't processing an exception if (IsHandleNullUnchecked(pThread->GetThrowableAsHandle())) return FALSE; EH_CLAUSE_ENUMERATOR pEnumState; unsigned EHCount = pJitManager->InitializeEHEnumeration(MethodToken, &pEnumState); if (EHCount == 0) return FALSE; EE_ILEXCEPTION_CLAUSE EHClause, *EHClausePtr; for(ULONG i=0; i < EHCount; i++) { EHClausePtr = pJitManager->GetNextEHClause(MethodToken, &pEnumState, &EHClause); _ASSERTE(IsValidClause(EHClausePtr)); if ( offset >= EHClausePtr->HandlerStartPC && offset < EHClausePtr->HandlerEndPC) return TRUE; // check if it's in the filter itself if we're not in the handler if (IsFilterHandler(EHClausePtr) && offset >= EHClausePtr->FilterOffset && offset < EHClausePtr->HandlerStartPC) return TRUE; } return FALSE; } LFH LookForHandler(const EXCEPTION_POINTERS *pExceptionPointers, Thread *pThread, ThrowCallbackType *tct) { if (pExceptionPointers->ExceptionRecord->ExceptionCode == EXCEPTION_COMPLUS && GetIP(pExceptionPointers->ContextRecord) != gpRaiseExceptionIP) { // normally we would return LFH_NOT_FOUND, however, there is one case where we // throw a COMPlusException (from ThrowControlForThread), we need to check for that case // The check relies on the fact that when we do throw control for thread, we record the // ip of managed code into m_OSContext. So just check to see that the IP in the context record // matches it. if ((pThread->m_OSContext == NULL) || (GetIP(pThread->m_OSContext) != GetIP(pExceptionPointers->ContextRecord))) return LFH_NOT_FOUND; //will cause continue_search } // Make sure that the stack depth counter is set ro zero. COUNTER_ONLY(GetPrivatePerfCounters().m_Excep.cThrowToCatchStackDepth=0); COUNTER_ONLY(GetGlobalPerfCounters().m_Excep.cThrowToCatchStackDepth=0); // go through to find if anyone handles the exception // @PERF: maybe can skip stackwalk code here and go directly to StackWalkEx. StackWalkAction action = pThread->StackWalkFrames((PSTACKWALKFRAMESCALLBACK)COMPlusThrowCallback, tct, 0, //can't use FUNCTIONSONLY because the callback uses non-function frames to stop the walk tct->pBottomFrame ); // if someone handles it, the action will be SWA_ABORT with pFunc and dHandler indicating the // function and handler that is handling the exception. Debugger can put a hook in here. if (action == SWA_ABORT && tct->pFunc != NULL) return LFH_FOUND; // nobody is handling it return LFH_NOT_FOUND; } StackWalkAction COMPlusUnwindCallback (CrawlFrame *pCf, ThrowCallbackType *pData); void UnwindFrames(Thread *pThread, ThrowCallbackType *tct) { // Make sure that the stack depth counter is set ro zero. COUNTER_ONLY(GetPrivatePerfCounters().m_Excep.cThrowToCatchStackDepth=0); COUNTER_ONLY(GetGlobalPerfCounters().m_Excep.cThrowToCatchStackDepth=0); pThread->StackWalkFrames((PSTACKWALKFRAMESCALLBACK)COMPlusUnwindCallback, tct, POPFRAMES | (tct->pFunc ? FUNCTIONSONLY : 0), // can only use FUNCTIONSONLY here if know will stop tct->pBottomFrame); } void SaveStackTraceInfo(ThrowCallbackType *pData, ExInfo *pExInfo, OBJECTHANDLE *hThrowable, BOOL bReplaceStack, BOOL bSkipLastElement) { // if have bSkipLastElement, must also keep the stack _ASSERTE(! bSkipLastElement || ! bReplaceStack); EEClass *pClass = ObjectFromHandle(*hThrowable)->GetTrueClass(); if (! pData->bAllowAllocMem || pExInfo->m_dFrameCount == 0) { pExInfo->ClearStackTrace(); if (bReplaceStack && IsException(pClass)) { FieldDesc *pStackTraceFD = g_Mscorlib.GetField(FIELD__EXCEPTION__STACK_TRACE); FieldDesc *pStackTraceStringFD = g_Mscorlib.GetField(FIELD__EXCEPTION__STACK_TRACE_STRING); pStackTraceFD->SetRefValue(ObjectFromHandle(*hThrowable), (OBJECTREF)(size_t)NULL); pStackTraceStringFD->SetRefValue(ObjectFromHandle(*hThrowable), (OBJECTREF)(size_t)NULL); } return; } // the stack trace info is now filled in so copy it to the exception object I1ARRAYREF arr = NULL; I1 *pI1 = NULL; // Only save stack trace info on exceptions if (!IsException(pClass)) return; FieldDesc *pStackTraceFD = g_Mscorlib.GetField(FIELD__EXCEPTION__STACK_TRACE); int cNewTrace = pExInfo->m_dFrameCount*sizeof(SystemNative::StackTraceElement); _ASSERTE(pStackTraceFD != NULL); if (bReplaceStack) { // nuke previous info arr = (I1ARRAYREF)AllocatePrimitiveArray(ELEMENT_TYPE_I1, cNewTrace); if (! arr) RealCOMPlusThrowOM(); pI1 = (I1 *)arr->GetDirectPointerToNonObjectElements(); } else { // append to previous info unsigned cOrigTrace = 0; // this is total size of array since each elem is 1 byte I1ARRAYREF pOrigTrace = NULL; GCPROTECT_BEGIN(pOrigTrace); pOrigTrace = (I1ARRAYREF)((size_t)pStackTraceFD->GetValue32(ObjectFromHandle(*hThrowable))); if (pOrigTrace != NULL) { cOrigTrace = pOrigTrace->GetNumComponents(); } if (bSkipLastElement && cOrigTrace!=0) { cOrigTrace -= sizeof(SystemNative::StackTraceElement); } arr = (I1ARRAYREF)AllocatePrimitiveArray(ELEMENT_TYPE_I1, cOrigTrace + cNewTrace); _ASSERTE(arr->GetNumComponents() % sizeof(SystemNative::StackTraceElement) == 0); if (! arr) RealCOMPlusThrowOM(); pI1 = (I1 *)arr->GetDirectPointerToNonObjectElements(); if (cOrigTrace && pOrigTrace!=NULL) { I1* pI1Orig = (I1 *)pOrigTrace->GetDirectPointerToNonObjectElements(); memcpyNoGCRefs(pI1, pI1Orig, cOrigTrace); pI1 += cOrigTrace; } GCPROTECT_END(); } memcpyNoGCRefs(pI1, pExInfo->m_pStackTrace, cNewTrace); pExInfo->ClearStackTrace(); pStackTraceFD->SetRefValue(ObjectFromHandle(*hThrowable), (OBJECTREF)arr); FieldDesc *pStackTraceStringFD = g_Mscorlib.GetField(FIELD__EXCEPTION__STACK_TRACE_STRING); pStackTraceStringFD->SetRefValue(ObjectFromHandle(*hThrowable), (OBJECTREF)(size_t)NULL); } // Copy a context record, being careful about whether or not the target // is large enough to support CONTEXT_EXTENDED_REGISTERS. // High 2 bytes are machine type. Low 2 bytes are register subset. #define CONTEXT_EXTENDED_BIT (CONTEXT_EXTENDED_REGISTERS & 0xffff) VOID ReplaceExceptionContextRecord(CONTEXT *pTarget, CONTEXT *pSource) { _ASSERTE(pTarget); _ASSERTE(pSource); // Source must be a full register set except, perhaps, the extended registers. _ASSERTE( (pSource->ContextFlags & (CONTEXT_FULL | CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS)) == (CONTEXT_FULL | CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS)); #ifdef CONTEXT_EXTENDED_REGISTERS if (pSource->ContextFlags & CONTEXT_EXTENDED_BIT) { if (pTarget->ContextFlags & CONTEXT_EXTENDED_BIT) { *pTarget = *pSource; } else { memcpy(pTarget, pSource, offsetof(CONTEXT, ExtendedRegisters)); pTarget->ContextFlags &= ~CONTEXT_EXTENDED_BIT; // Target was short. Reset the extended bit. } } else { memcpy(pTarget, pSource, offsetof(CONTEXT, ExtendedRegisters)); } #else // !CONTEXT_EXTENDED_REGISTERS *pTarget = *pSource; #endif // !CONTEXT_EXTENDED_REGISTERS } VOID FixupOnRethrow(Thread *pCurThread, EXCEPTION_POINTERS *pExceptionPointers) { ExInfo *pExInfo = pCurThread->GetHandlerInfo(); // Don't allow rethrow of a STATUS_STACK_OVERFLOW -- it's a new throw of the COM+ exception. if (pExInfo->m_ExceptionCode == STATUS_STACK_OVERFLOW) { gpRaiseExceptionIP = GetIP(pExceptionPointers->ContextRecord); return; } // For COMPLUS exceptions, we don't need the original context for our rethrow. if (pExInfo->m_ExceptionCode != EXCEPTION_COMPLUS) { _ASSERTE(pExInfo->m_pExceptionRecord); _ASSERTE(pExInfo->m_pContext); // don't copy parm args as have already supplied them on the throw memcpy((void *)pExceptionPointers->ExceptionRecord, (void *)pExInfo->m_pExceptionRecord, offsetof(EXCEPTION_RECORD, ExceptionInformation)); // Restore original context if available. if (pExInfo->m_pContext) { ReplaceExceptionContextRecord(pExceptionPointers->ContextRecord, pExInfo->m_pContext); } } pExInfo->SetIsRethrown(); } //========================================================================== // Throw an object. //========================================================================== #ifdef _IA64_ VOID RealCOMPlusThrow(OBJECTREF throwable, BOOL rethrow) { _ASSERTE(!"RealCOMPlusThrow - NOT IMPLEMENTED"); } #else // !_IA64_ VOID RaiseTheException(OBJECTREF throwable, BOOL rethrow) { THROWSCOMPLUSEXCEPTION(); LOG((LF_EH, LL_INFO100, "RealCOMPlusThrow throwing %s\n", throwable->GetTrueClass()->m_szDebugClassName)); if (throwable == NULL) { _ASSERTE(!"RealCOMPlusThrow(OBJECTREF) called with NULL argument. Somebody forgot to post an exception!"); FATAL_EE_ERROR(); } Thread *pThread = GetThread(); _ASSERTE(pThread); ExInfo *pExInfo = pThread->GetHandlerInfo(); _ASSERTE(pExInfo); // raise __try { //_ASSERTE(! rethrow || pExInfo->m_pExceptionRecord); ULONG_PTR *args; ULONG argCount; ULONG flags; ULONG code; // always save the current object in the handle so on rethrow we can reuse it. This // is important as it contains stack trace info. pThread->SetLastThrownObject(throwable); if (!rethrow || pExInfo->m_ExceptionCode == EXCEPTION_COMPLUS || pExInfo->m_ExceptionCode == STATUS_STACK_OVERFLOW) { args = NULL; argCount = 0; flags = EXCEPTION_NONCONTINUABLE; code = EXCEPTION_COMPLUS; } else { // Exception code should be consistent. _ASSERTE(pExInfo->m_pExceptionRecord->ExceptionCode == pExInfo->m_ExceptionCode); args = pExInfo->m_pExceptionRecord->ExceptionInformation; argCount = pExInfo->m_pExceptionRecord->NumberParameters; flags = pExInfo->m_pExceptionRecord->ExceptionFlags; code = pExInfo->m_pExceptionRecord->ExceptionCode; } // enable preemptive mode before call into OS pThread->EnablePreemptiveGC(); RaiseException(code, flags, argCount, args); } __except( // need to reset the EH info back to the original thrown exception rethrow ? FixupOnRethrow(pThread, GetExceptionInformation()) : // We want to use the IP of the exception context to distinguish // true COM+ throws (exceptions raised from this function) from // forgeries (exceptions thrown by other code using our exception // code.) To do, so we need to save away the eip of this call site - // the easiest way to do this is to intercept our own exception // and suck the ip out of the exception context. gpRaiseExceptionIP = GetIP((GetExceptionInformation())->ContextRecord), EXCEPTION_CONTINUE_SEARCH ) { } _ASSERTE(!"Cannot continue after COM+ exception"); // Debugger can bring you here. SafeExitProcess(0); // We can't continue. } VOID RealCOMPlusThrow(OBJECTREF throwable, BOOL rethrow) { INSTALL_COMPLUS_EXCEPTION_HANDLER(); RaiseTheException(throwable, rethrow); UNINSTALL_COMPLUS_EXCEPTION_HANDLER(); } #endif // !_IA64_ VOID RealCOMPlusThrow(OBJECTREF throwable) { RealCOMPlusThrow(throwable, FALSE); } //========================================================================== // Throw an undecorated runtime exception. //========================================================================== VOID RealCOMPlusThrow(RuntimeExceptionKind reKind) { if (reKind == kExecutionEngineException) FATAL_EE_ERROR(); THROWSCOMPLUSEXCEPTION(); RealCOMPlusThrowWorker(reKind, FALSE, FALSE, 0,0,0,0,0); } //========================================================================== // Throw a decorated runtime exception. // Try using RealCOMPlusThrow(reKind, wszResourceName) instead. //========================================================================== VOID RealCOMPlusThrowNonLocalized(RuntimeExceptionKind reKind, LPCWSTR wszTag) { THROWSCOMPLUSEXCEPTION(); RealCOMPlusThrowWorker(reKind, TRUE, FALSE, 0,0,wszTag,0,0); } //========================================================================== // Throw a decorated runtime exception with a localized message. // Queries the ResourceManager for a corresponding resource value. //========================================================================== VOID RealCOMPlusThrow(RuntimeExceptionKind reKind, LPCWSTR wszResourceName) { THROWSCOMPLUSEXCEPTION(); _ASSERTE(wszResourceName); // You should add a resource. LPWSTR wszValue = NULL; STRINGREF str = NULL; ResMgrGetString(wszResourceName, &str); if (str != NULL) { int len; RefInterpretGetStringValuesDangerousForGC(str, (LPWSTR*)&wszValue, &len); } RealCOMPlusThrowWorker(reKind, TRUE, FALSE, 0,0, wszValue,0,0); } // This function does poentially a LOT of work (loading possibly 50 classes). // The return value is an un-GC-protected string ref, or possibly NULL. void ResMgrGetString(LPCWSTR wszResourceName, STRINGREF * ppMessage) { _ASSERTE(ppMessage != NULL); OBJECTREF ResMgr = NULL; STRINGREF name = NULL; MethodDesc* pInitResMgrMeth = g_Mscorlib.GetMethod(METHOD__ENVIRONMENT__INIT_RESOURCE_MANAGER); ResMgr = Int64ToObj(pInitResMgrMeth->Call((INT64*)NULL, METHOD__ENVIRONMENT__INIT_RESOURCE_MANAGER)); GCPROTECT_BEGIN(ResMgr); // Call ResourceManager::GetString(String name). Returns String value (or maybe null) MethodDesc* pMeth = g_Mscorlib.GetMethod(METHOD__RESOURCE_MANAGER__GET_STRING); // No GC-causing actions occur after this line. name = COMString::NewString(wszResourceName); LPCWSTR wszValue = wszResourceName; if (ResMgr == NULL || wszResourceName == NULL) goto exit; { // Don't need to GCPROTECT pArgs, since it's not used after the function call. INT64 pArgs[2] = { ObjToInt64(ResMgr), ObjToInt64(name) }; STRINGREF value = (STRINGREF) Int64ToObj(pMeth->Call(pArgs, METHOD__RESOURCE_MANAGER__GET_STRING)); _ASSERTE(value!=NULL || !"Resource string lookup failed - possible misspelling or .resources missing or out of date?"); *ppMessage = value; } exit: GCPROTECT_END(); } //========================================================================== // Throw a decorated runtime exception. //========================================================================== VOID __cdecl RealCOMPlusThrow(RuntimeExceptionKind reKind, UINT resID) { THROWSCOMPLUSEXCEPTION(); RealCOMPlusThrow(reKind, resID, NULL, NULL, NULL); } //========================================================================== // Throw a decorated runtime exception. //========================================================================== VOID __cdecl RealCOMPlusThrow(RuntimeExceptionKind reKind, UINT resID, LPCWSTR wszArg1) { THROWSCOMPLUSEXCEPTION(); RealCOMPlusThrow(reKind, resID, wszArg1, NULL, NULL); } //========================================================================== // Throw a decorated runtime exception. //========================================================================== VOID __cdecl RealCOMPlusThrow(RuntimeExceptionKind reKind, UINT resID, LPCWSTR wszArg1, LPCWSTR wszArg2) { THROWSCOMPLUSEXCEPTION(); RealCOMPlusThrow(reKind, resID, wszArg1, wszArg2, NULL); } //========================================================================== // Throw a decorated runtime exception. //========================================================================== VOID __cdecl RealCOMPlusThrow(RuntimeExceptionKind reKind, UINT resID, LPCWSTR wszArg1, LPCWSTR wszArg2, LPCWSTR wszArg3) { THROWSCOMPLUSEXCEPTION(); RealCOMPlusThrowWorker(reKind, TRUE, TRUE, resID, 0, wszArg1, wszArg2, wszArg3); } void FreeExceptionData(ExceptionData *pedata) { _ASSERTE(pedata != NULL); // @NICE: At one point, we had the comment: // (DM) Remove this when shutdown works better. // This test may no longer be necessary. Remove at own peril. Thread *pThread = GetThread(); if (!pThread) return; if (pedata->bstrSource) SysFreeString(pedata->bstrSource); if (pedata->bstrDescription) SysFreeString(pedata->bstrDescription); if (pedata->bstrHelpFile) SysFreeString(pedata->bstrHelpFile); } VOID RealCOMPlusThrowHRWorker(HRESULT hr, ExceptionData *pData, UINT resourceID, LPCWSTR wszArg1, LPCWSTR wszArg2) { THROWSCOMPLUSEXCEPTION(); if (!g_fExceptionsOK) COMPlusThrowBoot(hr); _ASSERTE(pData == NULL || hr == pData->hr); RuntimeExceptionKind reKind = kException; BOOL bMatch = FALSE; int i; for (i = 0; i < kLastException; i++) { for (int j = 0; j < gExceptionHRInfos[i].cHRs; j++) { if (gExceptionHRInfos[i].aHRs[j] == hr) { bMatch = TRUE; break; } } if (bMatch) break; } reKind = (i != kLastException) ? (RuntimeExceptionKind)i : kCOMException; if (pData != NULL) { RealCOMPlusThrowWorker(reKind, FALSE, FALSE, 0, hr, NULL, NULL, NULL, pData); } else { WCHAR numBuff[40]; Wszultow(hr, numBuff, 16 /*hex*/); if(resourceID == 0) { bool fMessage; fMessage = wszArg1 ? TRUE : FALSE; // It doesn't make sense to have a second string without a ResourceID. _ASSERTE (!wszArg2); RealCOMPlusThrowWorker(reKind, fMessage, FALSE, 0, hr, wszArg1, NULL, NULL); } else { RealCOMPlusThrowWorker(reKind, TRUE, TRUE, resourceID, hr, numBuff, wszArg1, wszArg2); } } } VOID RealCOMPlusThrowHRWorker(HRESULT hr, ExceptionData *pData, LPCWSTR wszArg1 = NULL) { RealCOMPlusThrowHRWorker(hr, pData, 0, wszArg1, NULL); } //========================================================================== // Throw a runtime exception based on an HResult //========================================================================== VOID RealCOMPlusThrowHR(HRESULT hr, IErrorInfo* pErrInfo ) { THROWSCOMPLUSEXCEPTION(); if (!g_fExceptionsOK) COMPlusThrowBoot(hr); // check for complus created IErrorInfo pointers if (pErrInfo != NULL && IsComPlusTearOff(pErrInfo)) { OBJECTREF oref = GetObjectRefFromComIP(pErrInfo); _ASSERTE(oref != NULL); GCPROTECT_BEGIN (oref); ULONG cbRef= SafeRelease(pErrInfo); LogInteropRelease(pErrInfo, cbRef, "IErrorInfo release"); RealCOMPlusThrow(oref); GCPROTECT_END (); } if (pErrInfo != NULL) { ExceptionData edata; edata.hr = hr; edata.bstrDescription = NULL; edata.bstrSource = NULL; edata.bstrHelpFile = NULL; edata.dwHelpContext = NULL; edata.guid = GUID_NULL; FillExceptionData(&edata, pErrInfo); EE_TRY_FOR_FINALLY { RealCOMPlusThrowHRWorker(hr, &edata); } EE_FINALLY { FreeExceptionData(&edata); // free the BStrs } EE_END_FINALLY; } else { RealCOMPlusThrowHRWorker(hr, NULL); } } VOID RealCOMPlusThrowHR(HRESULT hr) { THROWSCOMPLUSEXCEPTION(); IErrorInfo *pErrInfo = NULL; if (GetErrorInfo(0, &pErrInfo) != S_OK) pErrInfo = NULL; RealCOMPlusThrowHR(hr, pErrInfo); } VOID RealCOMPlusThrowHR(HRESULT hr, LPCWSTR wszArg1) { THROWSCOMPLUSEXCEPTION(); RealCOMPlusThrowHRWorker(hr, NULL, wszArg1); } VOID RealCOMPlusThrowHR(HRESULT hr, UINT resourceID, LPCWSTR wszArg1, LPCWSTR wszArg2) { THROWSCOMPLUSEXCEPTION(); RealCOMPlusThrowHRWorker(hr, NULL, resourceID, wszArg1, wszArg2); } //========================================================================== // Throw a runtime exception based on an HResult, check for error info //========================================================================== VOID RealCOMPlusThrowHR(HRESULT hr, IUnknown *iface, REFIID riid) { THROWSCOMPLUSEXCEPTION(); IErrorInfo *info = NULL; GetSupportedErrorInfo(iface, riid, &info); RealCOMPlusThrowHR(hr, info); } //========================================================================== // Throw a runtime exception based on an EXCEPINFO. This function will free // the strings in the EXCEPINFO that is passed in. //========================================================================== VOID RealCOMPlusThrowHR(EXCEPINFO *pExcepInfo) { THROWSCOMPLUSEXCEPTION(); // If there is a fill in function then call it to retrieve the filled in EXCEPINFO. EXCEPINFO FilledInExcepInfo; if (pExcepInfo->pfnDeferredFillIn) { HRESULT hr = pExcepInfo->pfnDeferredFillIn(&FilledInExcepInfo); if (SUCCEEDED(hr)) { // Free the strings in the original EXCEPINFO. if (pExcepInfo->bstrDescription) { SysFreeString(pExcepInfo->bstrDescription); pExcepInfo->bstrDescription = NULL; } if (pExcepInfo->bstrSource) { SysFreeString(pExcepInfo->bstrSource); pExcepInfo->bstrSource = NULL; } if (pExcepInfo->bstrHelpFile) { SysFreeString(pExcepInfo->bstrHelpFile); pExcepInfo->bstrHelpFile = NULL; } // Set the ExcepInfo pointer to the filled in one. pExcepInfo = &FilledInExcepInfo; } } // Extract the required information from the EXCEPINFO. ExceptionData edata; edata.hr = pExcepInfo->scode; edata.bstrDescription = pExcepInfo->bstrDescription; edata.bstrSource = pExcepInfo->bstrSource; edata.bstrHelpFile = pExcepInfo->bstrHelpFile; edata.dwHelpContext = pExcepInfo->dwHelpContext; edata.guid = GUID_NULL; // Zero the EXCEPINFO. memset(pExcepInfo, NULL, sizeof(EXCEPINFO)); // Call the RealCOMPlusThrowHRWorker to do the actual work of throwing the exception. EE_TRY_FOR_FINALLY { RealCOMPlusThrowHRWorker(edata.hr, &edata); } EE_FINALLY { FreeExceptionData(&edata); // free the BStrs } EE_END_FINALLY; } //========================================================================== // Throw a runtime exception based on the last Win32 error (GetLastError()) //========================================================================== VOID RealCOMPlusThrowWin32() { THROWSCOMPLUSEXCEPTION(); // before we do anything else... DWORD err = ::GetLastError(); WCHAR wszBuff[FORMAT_MESSAGE_BUFFER_LENGTH]; WCHAR *wszFinal = wszBuff; DWORD res = WszFormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL /*ignored msg source*/, err, 0 /*pick appropriate languageId*/, wszFinal, FORMAT_MESSAGE_BUFFER_LENGTH-1, 0 /*arguments*/); if (res == 0) RealCOMPlusThrowPreallocated(); // Either way, we now have the formatted string from the system. RealCOMPlusThrowNonLocalized(kApplicationException, wszFinal); } //========================================================================== // Throw a runtime exception based on the last Win32 error (GetLastError()) // with one string argument. Note that the number & kind & interpretation // of each error message is specific to each HResult. // This is a nasty hack done wrong, but it doesn't matter since this should // be used extremely infrequently. // As of 8/98, in winerror.h, there are 24 HResult messages with %1's in them, // and only 2 with %2's. There is only one with a %3 in it. This is out of // 1472 error messages. //========================================================================== VOID RealCOMPlusThrowWin32(DWORD hr, WCHAR* arg) { THROWSCOMPLUSEXCEPTION(); // before we do anything else... WCHAR wszBuff[FORMAT_MESSAGE_BUFFER_LENGTH]; DWORD res = WszFormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY, NULL /*ignored msg source*/, hr, 0 /*pick appropriate languageId*/, wszBuff, FORMAT_MESSAGE_BUFFER_LENGTH-1, (va_list*)(char**) &arg /*arguments*/); if (res == 0) { RealCOMPlusThrowPreallocated(); } // Either way, we now have the formatted string from the system. RealCOMPlusThrowNonLocalized(kApplicationException, wszBuff); } //========================================================================== // Throw an OutOfMemoryError //========================================================================== VOID RealCOMPlusThrowOM() { THROWSCOMPLUSEXCEPTION(); RealCOMPlusThrow(ObjectFromHandle(g_pPreallocatedOutOfMemoryException)); } //========================================================================== // Throw an ArithmeticException //========================================================================== VOID RealCOMPlusThrowArithmetic() { THROWSCOMPLUSEXCEPTION(); RealCOMPlusThrow(kArithmeticException); } //========================================================================== // Throw an ArgumentNullException //========================================================================== VOID RealCOMPlusThrowArgumentNull(LPCWSTR argName, LPCWSTR wszResourceName) { THROWSCOMPLUSEXCEPTION(); _ASSERTE(wszResourceName); ProtectArgsStruct prot; memset(&prot, 0, sizeof(ProtectArgsStruct)); GCPROTECT_BEGIN(prot); ResMgrGetString(wszResourceName, &prot.s1); CreateArgumentExceptionObject(kArgumentNullException, argName, prot.s1, &prot.pThrowable); RealCOMPlusThrow(prot.pThrowable); GCPROTECT_END(); } VOID RealCOMPlusThrowArgumentNull(LPCWSTR argName) { THROWSCOMPLUSEXCEPTION(); OBJECTREF throwable = NULL; GCPROTECT_BEGIN(throwable); // This will work - the ArgumentNullException constructor that takes one string takes an // argument name, not a message. While this next method expects a message, we'll live just fine. CreateExceptionObject(kArgumentNullException, argName, &throwable); RealCOMPlusThrow(throwable); GCPROTECT_END(); } //========================================================================== // Throw an ArgumentOutOfRangeException //========================================================================== VOID RealCOMPlusThrowArgumentOutOfRange(LPCWSTR argName, LPCWSTR wszResourceName) { THROWSCOMPLUSEXCEPTION(); ProtectArgsStruct prot; memset(&prot, 0, sizeof(ProtectArgsStruct)); GCPROTECT_BEGIN(prot); ResMgrGetString(wszResourceName, &prot.s1); CreateArgumentExceptionObject(kArgumentOutOfRangeException, argName, prot.s1, &prot.pThrowable); RealCOMPlusThrow(prot.pThrowable); GCPROTECT_END(); } //========================================================================== // Throw an ArgumentException //========================================================================== VOID RealCOMPlusThrowArgumentException(LPCWSTR argName, LPCWSTR wszResourceName) { THROWSCOMPLUSEXCEPTION(); ProtectArgsStruct prot; memset(&prot, 0, sizeof(ProtectArgsStruct)); GCPROTECT_BEGIN(prot); ResMgrGetString(wszResourceName, &prot.s1); CreateArgumentExceptionObject(kArgumentException, argName, prot.s1, &prot.pThrowable); RealCOMPlusThrow(prot.pThrowable); GCPROTECT_END(); } //========================================================================== // Re-Throw the last error. Don't call this - use EE_FINALLY instead //========================================================================== VOID RealCOMPlusRareRethrow() { THROWSCOMPLUSEXCEPTION(); LOG((LF_EH, LL_INFO100, "RealCOMPlusRareRethrow\n")); OBJECTREF throwable = GETTHROWABLE(); if (throwable != NULL) RealCOMPlusThrow(throwable, TRUE); else // This can only be the result of bad IL (or some internal EE failure). RealCOMPlusThrow(kInvalidProgramException, (UINT)IDS_EE_RETHROW_NOT_ALLOWED); } // // Maps a Win32 fault to a COM+ Exception enumeration code // // Returns 0xFFFFFFFF if it cannot be mapped. // DWORD MapWin32FaultToCOMPlusException(DWORD Code) { switch (Code) { case STATUS_FLOAT_INEXACT_RESULT: case STATUS_FLOAT_INVALID_OPERATION: case STATUS_FLOAT_STACK_CHECK: case STATUS_FLOAT_UNDERFLOW: return (DWORD) kArithmeticException; case STATUS_FLOAT_OVERFLOW: case STATUS_INTEGER_OVERFLOW: return (DWORD) kOverflowException; case STATUS_FLOAT_DIVIDE_BY_ZERO: case STATUS_INTEGER_DIVIDE_BY_ZERO: return (DWORD) kDivideByZeroException; case STATUS_FLOAT_DENORMAL_OPERAND: return (DWORD) kFormatException; case STATUS_ACCESS_VIOLATION: return (DWORD) kNullReferenceException; case STATUS_ARRAY_BOUNDS_EXCEEDED: return (DWORD) kIndexOutOfRangeException; case STATUS_NO_MEMORY: return (DWORD) kOutOfMemoryException; case STATUS_STACK_OVERFLOW: return (DWORD) kStackOverflowException; default: return kSEHException; } } TRtlUnwind GetRtlUnwind() { static TRtlUnwind pRtlUnwind = NULL; if (! pRtlUnwind) { // We will load the Kernel32.DLL and look for RtlUnwind. // If this is avaialble we can proceed with the excption handling scenario, // in the other case we will fail HINSTANCE hiKernel32; // the handle to Kernel32 hiKernel32 = WszGetModuleHandle(L"Kernel32.DLL"); if (hiKernel32) { // we got the handle now let's get the address pRtlUnwind = (TRtlUnwind) GetProcAddress(hiKernel32, "RtlUnwind"); // everything is supposed to be fine if we got a pointer to the function... if (! pRtlUnwind) { _ASSERTE(0); // RtlUnwind was not found return NULL; } } } return pRtlUnwind; } // on x86 at least, RtlUnwind always returns, but provide this so can catch // otherwise void RtlUnwindCallback() { _ASSERTE(!"Should not get here"); } #ifdef _DEBUG // check if anyone has written to the stack above the handler which would wipe out the EH registration void CheckStackBarrier(EXCEPTION_REGISTRATION_RECORD *exRecord) { if (exRecord->Handler != COMPlusFrameHandler) return; DWORD *stackOverwriteBarrier = (DWORD *)(((char *)exRecord) - STACK_OVERWRITE_BARRIER_SIZE * sizeof(DWORD)); for (int i =0; i < STACK_OVERWRITE_BARRIER_SIZE; i++) { if (*(stackOverwriteBarrier+i) != STACK_OVERWRITE_BARRIER_VALUE) { // to debug this error, you must determine who erroneously overwrote the stack _ASSERTE(!"Fatal error: the stack has been overwritten"); } } } #endif // //------------------------------------------------------------------------- // This is installed to indicate a function that cannot allow a COMPlus exception // to be thrown past it. //------------------------------------------------------------------------- #ifdef _DEBUG EXCEPTION_DISPOSITION __cdecl COMPlusCannotThrowExceptionHandler(EXCEPTION_RECORD *pExceptionRecord, EXCEPTION_REGISTRATION_RECORD *pEstablisherFrame, CONTEXT *pContext, void *DispatcherContext) { if (pExceptionRecord->ExceptionCode != STATUS_BREAKPOINT && pExceptionRecord->ExceptionCode != STATUS_ACCESS_VIOLATION) _ASSERTE(!"Exception thrown past CANNOTTHROWCOMPLUSEXCEPTION boundary"); return ExceptionContinueSearch; } EXCEPTION_DISPOSITION __cdecl COMPlusCannotThrowExceptionMarker(EXCEPTION_RECORD *pExceptionRecord, EXCEPTION_REGISTRATION_RECORD *pEstablisherFrame, CONTEXT *pContext, void *DispatcherContext) { return ExceptionContinueSearch; } #endif //------------------------------------------------------------------------- // A marker for unmanaged -> EE transition when we know we're in cooperative // gc mode. As we leave the EE, we fix a few things: // // - the gc state must be set back to co-operative // - the COM+ frame chain must be rewound to what it was on entry // - ExInfo()->m_pSearchBoundary must be adjusted // if we popped the frame that is identified as begnning the next // crawl. //------------------------------------------------------------------------- EXCEPTION_DISPOSITION __cdecl COMPlusCooperativeTransitionHandler( EXCEPTION_RECORD *pExceptionRecord, EXCEPTION_REGISTRATION_RECORD *pEstablisherFrame, CONTEXT *pContext, void *pDispatcherContext) { if (IS_UNWINDING(pExceptionRecord->ExceptionFlags)) { LOG((LF_EH, LL_INFO1000, "COMPlusCooprativeTransitionHandler unwinding\n")); // Fetch a few things we need. Thread* pThread = GetThread(); _ASSERTE(pThread); // Restore us to cooperative gc mode. if (!pThread->PreemptiveGCDisabled()) pThread->DisablePreemptiveGC(); // 3rd dword is the frame to which we must unwind. Frame *pFrame = (Frame*)((size_t*)pEstablisherFrame)[2]; // Pop the frame chain. UnwindFrameChain(pThread, pFrame); _ASSERTE(pFrame == pThread->GetFrame()); // An exception is being thrown through here. The COM+ exception // info keeps a pointer to a frame that is used by the next // COM+ Exception Handler as the starting point of its crawl. // We may have popped this marker -- in which case, we need to // update it to the current frame. // ExInfo *pExInfo = pThread->GetHandlerInfo(); if ( pExInfo && pExInfo->m_pSearchBoundary && pExInfo->m_pSearchBoundary < pFrame) { LOG((LF_EH, LL_INFO1000, "\tpExInfo->m_pSearchBoundary = %08x\n", (void*)pFrame)); pExInfo->m_pSearchBoundary = pFrame; } } return ExceptionContinueSearch; // Same for both DISPATCH and UNWIND } // //------------------------------------------------------------------------- // This is installed when we call COMPlusFrameHandler to provide a bound to // determine when are within a nested exception //------------------------------------------------------------------------- EXCEPTION_DISPOSITION __cdecl COMPlusNestedExceptionHandler(EXCEPTION_RECORD *pExceptionRecord, EXCEPTION_REGISTRATION_RECORD *pEstablisherFrame, CONTEXT *pContext, void *pDispatcherContext) { if (pExceptionRecord->ExceptionFlags & (EXCEPTION_UNWINDING | EXCEPTION_EXIT_UNWIND)) { LOG((LF_EH, LL_INFO100, " COMPlusNestedHandler(unwind) with %x at %x\n", pExceptionRecord->ExceptionCode, GetIP(pContext))); // We're unwinding past a nested exception record, which means that we've thrown // a new excecption out of a region in which we're handling a previous one. The // previous exception is overridden -- and needs to be unwound. // The preceding is ALMOST true. There is one more case, where we use setjmp/longjmp // from withing a nested handler. We won't have a nested exception in that case -- just // the unwind. Thread *pThread = GetThread(); _ASSERTE(pThread); ExInfo *pExInfo = pThread->GetHandlerInfo(); ExInfo *pPrevNestedInfo = pExInfo->m_pPrevNestedInfo; if (pPrevNestedInfo == &((NestedHandlerExRecord*)pEstablisherFrame)->m_handlerInfo) { _ASSERTE(pPrevNestedInfo); if (pPrevNestedInfo->m_pThrowable != NULL) { DestroyHandle(pPrevNestedInfo->m_pThrowable); } pPrevNestedInfo->FreeStackTrace(); pExInfo->m_pPrevNestedInfo = pPrevNestedInfo->m_pPrevNestedInfo; } else { // The whacky setjmp/longjmp case. Nothing to do. } } else { LOG((LF_EH, LL_INFO100, " InCOMPlusNestedHandler with %x at %x\n", pExceptionRecord->ExceptionCode, GetIP(pContext))); } // There is a nasty "gotcha" in the way exception unwinding, finally's, and nested exceptions // interact. Here's the scenario ... it involves two exceptions, one normal one, and one // raised in a finally. // // The first exception occurs, and is caught by some handler way up the stack. That handler // calls RtlUnwind -- and handlers that didn't catch this first exception are called again, with // the UNWIND flag set. If, one of the handlers throws an exception during // unwind (like, a throw from a finally) -- then that same handler is not called during // the unwind pass of the second exception. [ASIDE: It is called on first-pass.] // // What that means is -- the COMPlusExceptionHandler, can't count on unwinding itself correctly // if an exception is thrown from a finally. Instead, it relies on the NestedExceptionHandler // that it pushes for this. // EXCEPTION_DISPOSITION retval = COMPlusFrameHandler(pExceptionRecord, pEstablisherFrame, pContext, pDispatcherContext); LOG((LF_EH, LL_INFO100, "Leaving COMPlusNestedExceptionHandler with %d\n", retval)); return retval; } EXCEPTION_REGISTRATION_RECORD *FindNestedEstablisherFrame(EXCEPTION_REGISTRATION_RECORD *pEstablisherFrame) { while (pEstablisherFrame->Handler != COMPlusNestedExceptionHandler) { pEstablisherFrame = pEstablisherFrame->Next; _ASSERTE((SSIZE_T)pEstablisherFrame != -1); // should always find one } return pEstablisherFrame; } ExInfo *FindNestedExInfo(EXCEPTION_REGISTRATION_RECORD *pEstablisherFrame) { while (pEstablisherFrame->Handler != COMPlusNestedExceptionHandler) { pEstablisherFrame = pEstablisherFrame->Next; _ASSERTE((SSIZE_T)pEstablisherFrame != -1); // should always find one } return &((NestedHandlerExRecord*)pEstablisherFrame)->m_handlerInfo; } ExInfo& ExInfo::operator=(const ExInfo &from) { LOG((LF_EH, LL_INFO100, "In ExInfo::operator=()\n")); // The throwable, and the stack address are handled differently. Save the original // values. OBJECTHANDLE pThrowable = m_pThrowable; void *stackAddress = this->m_StackAddress; // Blast the entire record. memcpy(this, &from, sizeof(ExInfo)); // Preserve the stack address. It should never change. m_StackAddress = stackAddress; // memcpy doesnt work for handles ... copy the handle the right way. if (pThrowable != NULL) DestroyHandle(pThrowable); if (from.m_pThrowable != NULL) { HHANDLETABLE table = HndGetHandleTable(from.m_pThrowable); m_pThrowable = CreateHandle(table, ObjectFromHandle(from.m_pThrowable)); } return *this; } void ExInfo::Init() { m_pSearchBoundary = NULL; m_pBottomMostHandler = NULL; m_pPrevNestedInfo = NULL; m_pStackTrace = NULL; m_cStackTrace = 0; m_dFrameCount = 0; m_ExceptionCode = 0xcccccccc; m_pExceptionRecord = NULL; m_pContext = NULL; m_pShadowSP = NULL; m_flags = 0; m_StackAddress = this; if (m_pThrowable != NULL) DestroyHandle(m_pThrowable); m_pThrowable = NULL; } ExInfo::ExInfo() { m_pThrowable = NULL; Init(); } void ExInfo::FreeStackTrace() { if (m_pStackTrace) { delete [] m_pStackTrace; m_pStackTrace = NULL; m_cStackTrace = 0; m_dFrameCount = 0; } } void ExInfo::ClearStackTrace() { m_dFrameCount = 0; } // When hit an endcatch or an unwind and have nested handler info, either 1) have contained a nested exception // and will continue handling the original or 2) the nested exception was not contained and was // thrown beyond the original bounds where the first exception occurred. The way we can tell this // is from the stack pointer. The topmost nested handler is installed at the point where the exception // occurred. For a nested exception to be contained, it must be caught within the scope of any code that // is called after the nested handler is installed. If it is caught by anything earlier on the stack, it was // not contained. So we unwind the nested handlers until we get to one that is higher on the stack than // esp we will unwind to. If we still have a nested handler, then we have successfully handled a nested // exception and should restore the exception settings that we saved so that processing of the // original exception can continue. Otherwise the nested exception has gone beyond where the original // exception was thrown and therefore replaces the original exception. Will always remove the current // exception info from the chain. void UnwindExInfo(ExInfo *pExInfo, VOID* limit) { // We must be in cooperative mode to do the chaining below Thread * pThread = GetThread(); // The debugger thread will be using this, even though it has no // Thread object associated with it. _ASSERT((pThread != NULL && pThread->PreemptiveGCDisabled()) || g_pDebugInterface->GetRCThreadId() == GetCurrentThreadId()); ExInfo *pPrevNestedInfo = pExInfo->m_pPrevNestedInfo; // At first glance, you would think that each nested exception has // been unwound by it's corresponding NestedExceptionHandler. But that's // not necessarily the case. The following assertion cannot be made here, // and the loop is necessary. // //_ASSERTE(pPrevNestedInfo == 0 || (DWORD)pPrevNestedInfo >= limit); // // Make sure we've unwound any nested exceptions that we're going to skip over. // while (pPrevNestedInfo && pPrevNestedInfo->m_StackAddress < limit) { if (pPrevNestedInfo->m_pThrowable != NULL) { DestroyHandle(pPrevNestedInfo->m_pThrowable); } pPrevNestedInfo->FreeStackTrace(); ExInfo *pPrev = pPrevNestedInfo->m_pPrevNestedInfo; if (pPrevNestedInfo->IsHeapAllocated()) delete pPrevNestedInfo; pPrevNestedInfo = pPrev; } // either clear the one we're about to copy over or the topmost one pExInfo->FreeStackTrace(); if (pPrevNestedInfo) { // found nested handler info that is above the esp restore point so succesfully caught nested LOG((LF_EH, LL_INFO100, "UnwindExInfo: resetting nested info to 0x%08x\n", pPrevNestedInfo)); *pExInfo = *pPrevNestedInfo; pPrevNestedInfo->Init(); // Clear out the record, freeing handles. if (pPrevNestedInfo->IsHeapAllocated()) delete pPrevNestedInfo; } else { LOG((LF_EH, LL_INFO100, "UnwindExInfo: m_pBottomMostHandler gets NULL\n")); pExInfo->Init(); } } void UnwindFrameChain(Thread* pThread, Frame* limit) { BEGIN_ENSURE_COOPERATIVE_GC(); Frame* pFrame = pThread->m_pFrame; while (pFrame != limit) { _ASSERTE(pFrame != 0); pFrame->ExceptionUnwind(); pFrame->Pop(pThread); pFrame = pThread->GetFrame(); } END_ENSURE_COOPERATIVE_GC(); } BOOL ComPlusFrameSEH(EXCEPTION_REGISTRATION_RECORD* pEHR) { return (pEHR->Handler == COMPlusFrameHandler || pEHR->Handler == COMPlusNestedExceptionHandler); } BOOL ComPlusCoopFrameSEH(EXCEPTION_REGISTRATION_RECORD* pEHR) { return (pEHR->Handler == COMPlusCooperativeTransitionHandler); } #ifdef _DEBUG BOOL ComPlusCannotThrowSEH(EXCEPTION_REGISTRATION_RECORD* pEHR) { return ( pEHR->Handler == COMPlusCannotThrowExceptionHandler || pEHR->Handler == COMPlusCannotThrowExceptionMarker); } #endif #ifdef _DEBUG //------------------------------------------------------------------------- // Decide if we are in the scope of a COMPLUS_TRY block. // // WARNING: This routine is only used for debug assertions and // it will fail to detect some cases where COM+ exceptions are // not actually allowed. In particular, if you execute native code // from a COMPLUS_TRY block without inserting some kind of frame // that can signal the transition, ComPlusExceptionsAllowed() // will return TRUE even within the native code. // // The COMPlusFilter() is designed to be precise so that // it won't be fooled by COM+-looking exceptions thrown from outside // code (although they shouldn't be doing this anyway because // COM+ exception code has the "reserved by Microsoft" bit on.) //------------------------------------------------------------------------- VOID ThrowsCOMPlusExceptionWorker() { if (!g_fExceptionsOK) { // We're at bootup time: diagnostic services suspended. return; } else { Thread *pThread = GetThread(); EXCEPTION_REGISTRATION_RECORD* pEHR = (EXCEPTION_REGISTRATION_RECORD*) GetCurrentSEHRecord(); void* pCatchLocation = pThread->m_ComPlusCatchDepth; while (pEHR != (void *)-1) { _ASSERTE(pEHR != 0); if (ComPlusStubSEH(pEHR) || ComPlusFrameSEH(pEHR) || ComPlusCoopFrameSEH(pEHR) || NExportSEH(pEHR) || FastNExportSEH(pEHR)) return; if ((void*) pEHR > pCatchLocation) return; if (ComPlusCannotThrowSEH(pEHR)) _ASSERTE(!"Throwing an exception here will go through a function with CANNOTTHROWCOMPLUSEXCEPTION"); pEHR = pEHR->Next; } // No handlers on the stack. Might be ok if there are no frames on the stack. _ASSERTE( pThread->m_pFrame == FRAME_TOP || !"Potential COM+ Exception not guarded by a COMPLUS_TRY." ); } } BOOL IsCOMPlusExceptionHandlerInstalled() { EXCEPTION_REGISTRATION_RECORD* pEHR = (EXCEPTION_REGISTRATION_RECORD*) GetCurrentSEHRecord(); while (pEHR != (void *)-1) { _ASSERTE(pEHR != 0); if ( ComPlusStubSEH(pEHR) || ComPlusFrameSEH(pEHR) || ComPlusCoopFrameSEH(pEHR) || NExportSEH(pEHR) || FastNExportSEH(pEHR) || ComPlusCannotThrowSEH(pEHR) ) return TRUE; pEHR = pEHR->Next; } // no handlers on the stack return FALSE; } #endif //_DEBUG //========================================================================== // Generate a managed string representation of a method or field. //========================================================================== STRINGREF CreatePersistableMemberName(IMDInternalImport *pInternalImport, mdToken token) { THROWSCOMPLUSEXCEPTION(); LPCUTF8 pName = "<unknownmember>"; LPCUTF8 tmp; PCCOR_SIGNATURE psig; DWORD csig; switch (TypeFromToken(token)) { case mdtMemberRef: if ((tmp = pInternalImport->GetNameAndSigOfMemberRef(token, &psig, &csig)) != NULL) pName = tmp; break; case mdtMethodDef: if ((tmp = pInternalImport->GetNameOfMethodDef(token)) != NULL) pName = tmp; break; default: ; } return COMString::NewString(pName); } //========================================================================== // Generate a managed string representation of a full classname. //========================================================================== STRINGREF CreatePersistableClassName(IMDInternalImport *pInternalImport, mdToken token) { THROWSCOMPLUSEXCEPTION(); LPCUTF8 szFullName; CQuickBytes qb; LPCUTF8 szClassName = "<unknownclass>"; LPCUTF8 szNameSpace = NULL; switch (TypeFromToken(token)) { case mdtTypeRef: pInternalImport->GetNameOfTypeRef(token, &szNameSpace, &szClassName); break; case mdtTypeDef: pInternalImport->GetNameOfTypeDef(token, &szClassName, &szNameSpace); default: ; // leave it as "<unknown>" }; if (szNameSpace && *szNameSpace) { if (!ns::MakePath(qb, szNameSpace, szClassName)) RealCOMPlusThrowOM(); szFullName = (LPCUTF8) qb.Ptr(); } else { szFullName = szClassName; } return COMString::NewString(szFullName); } //========================================================================== // Used by the classloader to record a managed exception object to explain // why a classload got botched. // // - Can be called with gc enabled or disabled. // - pThrowable must point to a buffer protected by a GCFrame. // - If pThrowable is NULL, this function does nothing. // - If (*pThrowable) is non-NULL, this function does nothing. // This allows a catch-all error path to post a generic catchall error // message w/out bonking more specific error messages posted by inner functions. // - If pThrowable != NULL, this function is guaranteed to leave // a valid managed exception in it on exit. //========================================================================== VOID PostTypeLoadException(LPCUTF8 pszNameSpace, LPCUTF8 pTypeName, LPCWSTR pAssemblyName, LPCUTF8 pMessageArg, UINT resIDWhy, OBJECTREF *pThrowable) { _ASSERTE(IsProtectedByGCFrame(pThrowable)); if (pThrowable == RETURN_ON_ERROR) return; // we already have a pThrowable filled in. if (pThrowableAvailable(pThrowable) && *((Object**) pThrowable) != NULL) return; Thread *pThread = GetThread(); BOOL toggleGC = !(pThread->PreemptiveGCDisabled()); if (toggleGC) pThread->DisablePreemptiveGC(); LPUTF8 pszFullName; if(pszNameSpace) { MAKE_FULL_PATH_ON_STACK_UTF8(pszFullName, pszNameSpace, pTypeName); } else pszFullName = (LPUTF8) pTypeName; COUNTER_ONLY(GetPrivatePerfCounters().m_Loading.cLoadFailures++); COUNTER_ONLY(GetGlobalPerfCounters().m_Loading.cLoadFailures++); COMPLUS_TRY { MethodTable *pMT = g_Mscorlib.GetException(kTypeLoadException); struct _gc { OBJECTREF pNewException; STRINGREF pNewAssemblyString; STRINGREF pNewClassString; STRINGREF pNewMessageArgString; } gc; ZeroMemory(&gc, sizeof(gc)); GCPROTECT_BEGIN(gc); gc.pNewClassString = COMString::NewString(pszFullName); if (pMessageArg) gc.pNewMessageArgString = COMString::NewString(pMessageArg); if (pAssemblyName) gc.pNewAssemblyString = COMString::NewString(pAssemblyName); gc.pNewException = AllocateObject(pMT); __int64 args[] = { ObjToInt64(gc.pNewException), (__int64)resIDWhy, ObjToInt64(gc.pNewMessageArgString), ObjToInt64(gc.pNewAssemblyString), ObjToInt64(gc.pNewClassString), }; CallConstructor(&gsig_IM_Str_Str_Str_Int_RetVoid, args); if (pThrowable == THROW_ON_ERROR) { DEBUG_SAFE_TO_THROW_IN_THIS_BLOCK; COMPlusThrow(gc.pNewException); } *pThrowable = gc.pNewException; GCPROTECT_END(); } COMPLUS_CATCH { UpdateThrowable(pThrowable); } COMPLUS_END_CATCH; if (toggleGC) pThread->EnablePreemptiveGC(); } //@TODO: security: It would be nice for debugging purposes if the // user could have the full path, if the user has the right permission. VOID PostFileLoadException(LPCSTR pFileName, BOOL fRemovePath, LPCWSTR pFusionLog, HRESULT hr, OBJECTREF *pThrowable) { _ASSERTE(IsProtectedByGCFrame(pThrowable)); if (pThrowable == RETURN_ON_ERROR) return; // we already have a pThrowable filled in. if (pThrowableAvailable(pThrowable) && *((Object**) pThrowable) != NULL) return; if (fRemovePath) { // Strip path for security reasons LPCSTR pTemp = strrchr(pFileName, '\\'); if (pTemp) pFileName = pTemp+1; pTemp = strrchr(pFileName, '/'); if (pTemp) pFileName = pTemp+1; } Thread *pThread = GetThread(); BOOL toggleGC = !(pThread->PreemptiveGCDisabled()); if (toggleGC) pThread->DisablePreemptiveGC(); COUNTER_ONLY(GetPrivatePerfCounters().m_Loading.cLoadFailures++); COUNTER_ONLY(GetGlobalPerfCounters().m_Loading.cLoadFailures++); COMPLUS_TRY { RuntimeExceptionKind type; if (Assembly::ModuleFound(hr)) { //@BUG: this can be removed when the fileload/badimage stress bugs have been fixed STRESS_ASSERT(0); if ((hr == COR_E_BADIMAGEFORMAT) || (hr == CLDB_E_FILE_OLDVER) || (hr == CLDB_E_FILE_CORRUPT) || (hr == HRESULT_FROM_WIN32(ERROR_BAD_EXE_FORMAT)) || (hr == HRESULT_FROM_WIN32(ERROR_EXE_MARKED_INVALID)) || (hr == CORSEC_E_INVALID_IMAGE_FORMAT)) type = kBadImageFormatException; else { if ((hr == E_OUTOFMEMORY) || (hr == NTE_NO_MEMORY)) RealCOMPlusThrowOM(); type = kFileLoadException; } } else type = kFileNotFoundException; struct _gc { OBJECTREF pNewException; STRINGREF pNewFileString; STRINGREF pFusLogString; } gc; ZeroMemory(&gc, sizeof(gc)); GCPROTECT_BEGIN(gc); gc.pNewFileString = COMString::NewString(pFileName); gc.pFusLogString = COMString::NewString(pFusionLog); gc.pNewException = AllocateObject(g_Mscorlib.GetException(type)); __int64 args[] = { ObjToInt64(gc.pNewException), (__int64) hr, ObjToInt64(gc.pFusLogString), ObjToInt64(gc.pNewFileString), }; CallConstructor(&gsig_IM_Str_Str_Int_RetVoid, args); if (pThrowable == THROW_ON_ERROR) { DEBUG_SAFE_TO_THROW_IN_THIS_BLOCK; COMPlusThrow(gc.pNewException); } *pThrowable = gc.pNewException; GCPROTECT_END(); } COMPLUS_CATCH { UpdateThrowable(pThrowable); } COMPLUS_END_CATCH if (toggleGC) pThread->EnablePreemptiveGC(); } //========================================================================== // Used by the classloader to post illegal layout //========================================================================== HRESULT PostFieldLayoutError(mdTypeDef cl, // cl of the NStruct being loaded Module* pModule, // Module that defines the scope, loader and heap (for allocate FieldMarshalers) DWORD dwOffset, // Offset of field DWORD dwID, // Message id OBJECTREF *pThrowable) { IMDInternalImport *pInternalImport = pModule->GetMDImport(); // Internal interface for the NStruct being loaded. LPCUTF8 pszName, pszNamespace; pInternalImport->GetNameOfTypeDef(cl, &pszName, &pszNamespace); LPUTF8 offsetBuf = (LPUTF8)alloca(100); sprintf(offsetBuf, "%d", dwOffset); pModule->GetAssembly()->PostTypeLoadException(pszNamespace, pszName, offsetBuf, dwID, pThrowable); return COR_E_TYPELOAD; } //========================================================================== // Used by the classloader to post an out of memory. //========================================================================== VOID PostOutOfMemoryException(OBJECTREF *pThrowable) { _ASSERTE(IsProtectedByGCFrame(pThrowable)); if (pThrowable == RETURN_ON_ERROR) return; // we already have a pThrowable filled in. if (pThrowableAvailable(pThrowable) && *((Object**) pThrowable) != NULL) return; Thread *pThread = GetThread(); BOOL toggleGC = !(pThread->PreemptiveGCDisabled()); if (toggleGC) { pThread->DisablePreemptiveGC(); } COMPLUS_TRY { RealCOMPlusThrowOM(); } COMPLUS_CATCH { UpdateThrowable(pThrowable); } COMPLUS_END_CATCH; if (toggleGC) { pThread->EnablePreemptiveGC(); } } //========================================================================== // Private helper for TypeLoadException. //========================================================================== struct _FormatTypeLoadExceptionMessageArgs { UINT32 resId; STRINGREF messageArg; STRINGREF assemblyName; STRINGREF typeName; }; LPVOID __stdcall FormatTypeLoadExceptionMessage(struct _FormatTypeLoadExceptionMessageArgs *args) { LPVOID rv = NULL; DWORD ncType = args->typeName->GetStringLength(); CQuickBytes qb; CQuickBytes qb2; CQuickBytes qb3; LPWSTR wszType = (LPWSTR) qb.Alloc( (ncType+1)*2 ); CopyMemory(wszType, args->typeName->GetBuffer(), ncType*2); wszType[ncType] = L'\0'; LPWSTR wszAssembly; if (args->assemblyName == NULL) wszAssembly = NULL; else { DWORD ncAsm = args->assemblyName->GetStringLength(); wszAssembly = (LPWSTR) qb2.Alloc( (ncAsm+1)*2 ); CopyMemory(wszAssembly, args->assemblyName->GetBuffer(), ncAsm*2); wszAssembly[ncAsm] = L'\0'; } LPWSTR wszMessageArg; if (args->messageArg == NULL) wszMessageArg = NULL; else { DWORD ncMessageArg = args->messageArg->GetStringLength(); wszMessageArg = (LPWSTR) qb3.Alloc( (ncMessageArg+1)*2 ); CopyMemory(wszMessageArg, args->messageArg->GetBuffer(), ncMessageArg*2); wszMessageArg[ncMessageArg] = L'\0'; } LPWSTR wszMessage = CreateExceptionMessage(TRUE, args->resId ? args->resId : IDS_CLASSLOAD_GENERIC, wszType, wszAssembly, wszMessageArg); *((OBJECTREF*)(&rv)) = (OBJECTREF) COMString::NewString(wszMessage); if (wszMessage) LocalFree(wszMessage); return rv; } //========================================================================== // Private helper for FileLoadException and FileNotFoundException. //========================================================================== struct _FormatFileLoadExceptionMessageArgs { UINT32 hresult; STRINGREF fileName; }; LPVOID __stdcall FormatFileLoadExceptionMessage(struct _FormatFileLoadExceptionMessageArgs *args) { LPVOID rv = NULL; LPWSTR wszFile; CQuickBytes qb; if (args->fileName == NULL) wszFile = NULL; else { DWORD ncFile = args->fileName->GetStringLength(); wszFile = (LPWSTR) qb.Alloc( (ncFile+1)*2 ); CopyMemory(wszFile, args->fileName->GetBuffer(), ncFile*2); wszFile[ncFile] = L'\0'; } switch (args->hresult) { case COR_E_FILENOTFOUND: case HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND): case HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND): case HRESULT_FROM_WIN32(ERROR_INVALID_NAME): case CTL_E_FILENOTFOUND: case HRESULT_FROM_WIN32(ERROR_BAD_NET_NAME): case HRESULT_FROM_WIN32(ERROR_BAD_NETPATH): case HRESULT_FROM_WIN32(ERROR_NOT_READY): case HRESULT_FROM_WIN32(ERROR_WRONG_TARGET_NAME): args->hresult = IDS_EE_FILE_NOT_FOUND; case FUSION_E_REF_DEF_MISMATCH: case FUSION_E_INVALID_PRIVATE_ASM_LOCATION: case FUSION_E_PRIVATE_ASM_DISALLOWED: case FUSION_E_SIGNATURE_CHECK_FAILED: case FUSION_E_ASM_MODULE_MISSING: case FUSION_E_INVALID_NAME: case FUSION_E_CODE_DOWNLOAD_DISABLED: case COR_E_MODULE_HASH_CHECK_FAILED: case COR_E_FILELOAD: case SECURITY_E_INCOMPATIBLE_SHARE: case SECURITY_E_INCOMPATIBLE_EVIDENCE: case SECURITY_E_UNVERIFIABLE: case CORSEC_E_INVALID_STRONGNAME: case CORSEC_E_NO_EXEC_PERM: case E_ACCESSDENIED: case COR_E_BADIMAGEFORMAT: case COR_E_ASSEMBLYEXPECTED: case COR_E_FIXUPSINEXE: case HRESULT_FROM_WIN32(ERROR_TOO_MANY_OPEN_FILES): case HRESULT_FROM_WIN32(ERROR_SHARING_VIOLATION): case HRESULT_FROM_WIN32(ERROR_LOCK_VIOLATION): case HRESULT_FROM_WIN32(ERROR_OPEN_FAILED): case HRESULT_FROM_WIN32(ERROR_UNRECOGNIZED_VOLUME): case HRESULT_FROM_WIN32(ERROR_FILE_INVALID): case HRESULT_FROM_WIN32(ERROR_DLL_INIT_FAILED): case HRESULT_FROM_WIN32(ERROR_DISK_CORRUPT): case HRESULT_FROM_WIN32(ERROR_FILE_CORRUPT): case IDS_EE_PROC_NOT_FOUND: case IDS_EE_PATH_TOO_LONG: case IDS_EE_INTERNET_D: //TODO: find name break; case CLDB_E_FILE_OLDVER: case CLDB_E_FILE_CORRUPT: case HRESULT_FROM_WIN32(ERROR_BAD_EXE_FORMAT): case HRESULT_FROM_WIN32(ERROR_EXE_MARKED_INVALID): case CORSEC_E_INVALID_IMAGE_FORMAT: args->hresult = COR_E_BADIMAGEFORMAT; break; case COR_E_DEVICESNOTSUPPORTED: case HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE): case HRESULT_FROM_WIN32(ERROR_UNSUPPORTED_TYPE): case MK_E_SYNTAX: args->hresult = FUSION_E_INVALID_NAME; break; case 0x800c000b: //TODO: find name args->hresult = IDS_EE_INTERNET_B; break; case NTE_BAD_HASH: case NTE_BAD_LEN: case NTE_BAD_KEY: case NTE_BAD_DATA: case NTE_BAD_ALGID: case NTE_BAD_FLAGS: case NTE_BAD_HASH_STATE: case NTE_BAD_UID: case NTE_FAIL: case NTE_BAD_TYPE: case NTE_BAD_VER: case NTE_BAD_SIGNATURE: case NTE_SIGNATURE_FILE_BAD: case CRYPT_E_HASH_VALUE: args->hresult = IDS_EE_HASH_VAL_FAILED; break; case CORSEC_E_NO_SUITABLE_CSP: args->hresult = SN_NO_SUITABLE_CSP_NAME; break; default: _ASSERTE(!"Unknown hresult"); args->hresult = COR_E_FILELOAD; } LPWSTR wszMessage = CreateExceptionMessage(TRUE, args->hresult, wszFile, NULL, NULL); *((OBJECTREF*)(&rv)) = (OBJECTREF) COMString::NewString(wszMessage); if (wszMessage) LocalFree(wszMessage); return rv; } //========================================================================== // Persists a data type member of sig. //========================================================================== VOID PersistDataType(SigPointer *psp, IMDInternalImport *pInternalImport, StubLinker *psl) { THROWSCOMPLUSEXCEPTION(); CorElementType typ = (CorElementType)(psp->GetElemType()); psl->Emit8((INT8)typ); if (!CorIsPrimitiveType(typ)) { switch (typ) { case ELEMENT_TYPE_FNPTR: default: _ASSERTE(!"Illegal or unimplement type in COM+ sig."); break; case ELEMENT_TYPE_TYPEDBYREF: break; case ELEMENT_TYPE_BYREF: case ELEMENT_TYPE_PTR: PersistDataType(psp, pInternalImport, psl); break; case ELEMENT_TYPE_STRING: { psl->EmitUtf8(g_StringClassName); psl->Emit8('\0'); break; } case ELEMENT_TYPE_VAR: case ELEMENT_TYPE_OBJECT: { psl->EmitUtf8(g_ObjectClassName); psl->Emit8('\0'); break; } case ELEMENT_TYPE_VALUETYPE: //fallthru case ELEMENT_TYPE_CLASS: { LPCUTF8 szNameSpace; LPCUTF8 szClassName; mdToken token = psp->GetToken(); if (TypeFromToken(token) == mdtTypeRef) pInternalImport->GetNameOfTypeRef(token, &szNameSpace, &szClassName); else pInternalImport->GetNameOfTypeDef(token, &szNameSpace, &szClassName); if (*szNameSpace) { psl->EmitUtf8(szNameSpace); psl->Emit8(NAMESPACE_SEPARATOR_CHAR); } psl->EmitUtf8(szClassName); psl->Emit8('\0'); } break; case ELEMENT_TYPE_SZARRAY: PersistDataType(psp, pInternalImport, psl); // persist element type psl->Emit32(psp->GetData()); // persist array size break; case ELEMENT_TYPE_ARRAY: //fallthru { PersistDataType(psp, pInternalImport, psl); // persist element type UINT32 rank = psp->GetData(); // Get rank psl->Emit32(rank); if (rank) { UINT32 nsizes = psp->GetData(); // Get # of sizes psl->Emit32(nsizes); while (nsizes--) { psl->Emit32(psp->GetData()); // Persist size } UINT32 nlbounds = psp->GetData(); // Get # of lower bounds psl->Emit32(nlbounds); while (nlbounds--) { psl->Emit32(psp->GetData()); // Persist lower bounds } } } break; } } } StubLinker *NewStubLinker() { return new StubLinker(); } //========================================================================== // Convert a signature into a persistable byte array format. // // This format mirrors that of the metadata signature format with // two exceptions: // // 1. Any metadata token is replaced with a utf8 string describing // the actual class. // 2. No compression is done on 32-bit ints. //========================================================================== I1ARRAYREF CreatePersistableSignature(const VOID *pSig, IMDInternalImport *pInternalImport) { THROWSCOMPLUSEXCEPTION(); StubLinker *psl = NULL; Stub *pstub = NULL; I1ARRAYREF pArray = NULL; if (pSig != NULL) { COMPLUS_TRY { psl = NewStubLinker(); if (!psl) { RealCOMPlusThrowOM(); } SigPointer sp((PCCOR_SIGNATURE)pSig); DWORD nargs; UINT32 cc = sp.GetData(); psl->Emit32(cc); if (cc == IMAGE_CEE_CS_CALLCONV_FIELD) { PersistDataType(&sp, pInternalImport, psl); } else { psl->Emit32(nargs = sp.GetData()); //Persist arg count PersistDataType(&sp, pInternalImport, psl); //Persist return type for (DWORD i = 0; i < nargs; i++) { PersistDataType(&sp, pInternalImport, psl); } } UINT cbSize; pstub = psl->Link(&cbSize); *((OBJECTREF*)&pArray) = AllocatePrimitiveArray(ELEMENT_TYPE_I1, cbSize); memcpyNoGCRefs(pArray->GetDirectPointerToNonObjectElements(), pstub->GetEntryPoint(), cbSize); } COMPLUS_CATCH { delete psl; if (pstub) { pstub->DecRef(); } RealCOMPlusThrow(GETTHROWABLE()); } COMPLUS_END_CATCH delete psl; if (pstub) { pstub->DecRef(); } _ASSERTE(pArray != NULL); } return pArray; } //========================================================================== // Unparses an individual type. //========================================================================== const BYTE *UnparseType(const BYTE *pType, StubLinker *psl) { THROWSCOMPLUSEXCEPTION(); switch ( (CorElementType) *(pType++) ) { case ELEMENT_TYPE_VOID: psl->EmitUtf8("void"); break; case ELEMENT_TYPE_BOOLEAN: psl->EmitUtf8("boolean"); break; case ELEMENT_TYPE_CHAR: psl->EmitUtf8("char"); break; case ELEMENT_TYPE_U1: psl->EmitUtf8("unsigned "); //fallthru case ELEMENT_TYPE_I1: psl->EmitUtf8("byte"); break; case ELEMENT_TYPE_U2: psl->EmitUtf8("unsigned "); //fallthru case ELEMENT_TYPE_I2: psl->EmitUtf8("short"); break; case ELEMENT_TYPE_U4: psl->EmitUtf8("unsigned "); //fallthru case ELEMENT_TYPE_I4: psl->EmitUtf8("int"); break; case ELEMENT_TYPE_I: psl->EmitUtf8("native int"); break; case ELEMENT_TYPE_U: psl->EmitUtf8("native unsigned"); break; case ELEMENT_TYPE_U8: psl->EmitUtf8("unsigned "); //fallthru case ELEMENT_TYPE_I8: psl->EmitUtf8("long"); break; case ELEMENT_TYPE_R4: psl->EmitUtf8("float"); break; case ELEMENT_TYPE_R8: psl->EmitUtf8("double"); break; case ELEMENT_TYPE_STRING: psl->EmitUtf8(g_StringName); break; case ELEMENT_TYPE_VAR: case ELEMENT_TYPE_OBJECT: psl->EmitUtf8(g_ObjectName); break; case ELEMENT_TYPE_PTR: pType = UnparseType(pType, psl); psl->EmitUtf8("*"); break; case ELEMENT_TYPE_BYREF: pType = UnparseType(pType, psl); psl->EmitUtf8("&"); break; case ELEMENT_TYPE_VALUETYPE: case ELEMENT_TYPE_CLASS: psl->EmitUtf8((LPCUTF8)pType); while (*(pType++)) { //nothing } break; case ELEMENT_TYPE_SZARRAY: { pType = UnparseType(pType, psl); psl->EmitUtf8("[]"); } break; case ELEMENT_TYPE_ARRAY: { pType = UnparseType(pType, psl); DWORD rank = *((DWORD*)pType); pType += sizeof(DWORD); if (rank) { UINT32 nsizes = *((UINT32*)pType); // Get # of sizes pType += 4 + nsizes*4; UINT32 nlbounds = *((UINT32*)pType); // Get # of lower bounds pType += 4 + nlbounds*4; while (rank--) { psl->EmitUtf8("[]"); } } } break; case ELEMENT_TYPE_TYPEDBYREF: psl->EmitUtf8("&"); break; case ELEMENT_TYPE_FNPTR: psl->EmitUtf8("ftnptr"); break; default: psl->EmitUtf8("?"); break; } return pType; } //========================================================================== // Helper for MissingMethodException. //========================================================================== struct MissingMethodException_FormatSignature_Args { I1ARRAYREF pPersistedSig; }; LPVOID __stdcall MissingMethodException_FormatSignature(struct MissingMethodException_FormatSignature_Args *args) { THROWSCOMPLUSEXCEPTION(); STRINGREF pString = NULL; DWORD csig = 0; if (args->pPersistedSig != NULL) csig = args->pPersistedSig->GetNumComponents(); if (csig == 0) { pString = COMString::NewString("Unknown signature"); return *((LPVOID*)&pString); } const BYTE *psig = (const BYTE*)_alloca(csig); CopyMemory((BYTE*)psig, args->pPersistedSig->GetDirectPointerToNonObjectElements(), csig); StubLinker *psl = NewStubLinker(); Stub *pstub = NULL; if (!psl) { RealCOMPlusThrowOM(); } COMPLUS_TRY { UINT32 cconv = *((UINT32*)psig); psig += 4; if (cconv == IMAGE_CEE_CS_CALLCONV_FIELD) { psig = UnparseType(psig, psl); } else { UINT32 nargs = *((UINT32*)psig); psig += 4; // Unparse return type psig = UnparseType(psig, psl); psl->EmitUtf8("("); while (nargs--) { psig = UnparseType(psig, psl); if (nargs) { psl->EmitUtf8(", "); } } psl->EmitUtf8(")"); } psl->Emit8('\0'); pstub = psl->Link(); pString = COMString::NewString( (LPCUTF8)(pstub->GetEntryPoint()) ); } COMPLUS_CATCH { delete psl; if (pstub) { pstub->DecRef(); } RealCOMPlusThrow(GETTHROWABLE()); } COMPLUS_END_CATCH delete psl; if (pstub) { pstub->DecRef(); } return *((LPVOID*)&pString); } //========================================================================== // Throw a MissingMethodException //========================================================================== VOID RealCOMPlusThrowMissingMethod(IMDInternalImport *pInternalImport, mdToken mdtoken) { THROWSCOMPLUSEXCEPTION(); RealCOMPlusThrowMember(kMissingMethodException, pInternalImport, mdtoken); } //========================================================================== // Throw an exception pertaining to member access. //========================================================================== VOID RealCOMPlusThrowMember(RuntimeExceptionKind reKind, IMDInternalImport *pInternalImport, mdToken mdtoken) { THROWSCOMPLUSEXCEPTION(); mdToken tk = TypeFromToken(mdtoken); mdToken tkclass = mdTypeDefNil; const void *psig = NULL; MethodTable *pMT = g_Mscorlib.GetException(reKind); mdToken tmp; PCCOR_SIGNATURE tmpsig; DWORD tmpcsig; LPCUTF8 tmpname; switch (tk) { case mdtMethodDef: if (SUCCEEDED(pInternalImport->GetParentToken(mdtoken, &tmp))) { tkclass = tmp; } psig = pInternalImport->GetSigOfMethodDef(mdtoken, &tmpcsig); break; case mdtMemberRef: tkclass = pInternalImport->GetParentOfMemberRef(mdtoken); tmpname = pInternalImport->GetNameAndSigOfMemberRef(mdtoken,&tmpsig,&tmpcsig); break; default: ; // leave tkclass as mdTypeDefNil; } struct _gc { OBJECTREF pException; STRINGREF pFullClassName; STRINGREF pMethodName; I1ARRAYREF pSig; } gc; FillMemory(&gc, sizeof(gc), 0); GCPROTECT_BEGIN(gc); gc.pException = AllocateObject(pMT); gc.pFullClassName = CreatePersistableClassName(pInternalImport, tkclass); gc.pMethodName = CreatePersistableMemberName(pInternalImport, mdtoken); gc.pSig = CreatePersistableSignature(psig ,pInternalImport); __int64 args[] = { ObjToInt64(gc.pException), ObjToInt64(gc.pSig), ObjToInt64(gc.pMethodName), ObjToInt64(gc.pFullClassName), }; CallConstructor(&gsig_IM_Str_Str_ArrByte_RetVoid, args); RealCOMPlusThrow(gc.pException); GCPROTECT_END(); } //========================================================================== // Throw an exception pertaining to member access. //========================================================================== VOID RealCOMPlusThrowMember(RuntimeExceptionKind reKind, IMDInternalImport *pInternalImport, MethodTable *pClassMT, LPCWSTR name, PCCOR_SIGNATURE pSig) { THROWSCOMPLUSEXCEPTION(); MethodTable *pMT = g_Mscorlib.GetException(reKind); struct _gc { OBJECTREF pException; STRINGREF pFullClassName; STRINGREF pMethodName; I1ARRAYREF pSig; } gc; FillMemory(&gc, sizeof(gc), 0); GCPROTECT_BEGIN(gc); gc.pException = AllocateObject(pMT); gc.pFullClassName = CreatePersistableClassName(pInternalImport, pClassMT->GetClass()->GetCl()); gc.pMethodName = COMString::NewString(name); gc.pSig = CreatePersistableSignature(pSig, pInternalImport); __int64 args[] = { ObjToInt64(gc.pException), ObjToInt64(gc.pSig), ObjToInt64(gc.pMethodName), ObjToInt64(gc.pFullClassName), }; CallConstructor(&gsig_IM_Str_Str_ArrByte_RetVoid, args); RealCOMPlusThrow(gc.pException); GCPROTECT_END(); } BOOL IsExceptionOfType(RuntimeExceptionKind reKind, OBJECTREF *pThrowable) { _ASSERTE(pThrowableAvailable(pThrowable)); if (*pThrowable == NULL) return FALSE; MethodTable *pThrowableMT = (*pThrowable)->GetTrueMethodTable(); return g_Mscorlib.IsException(pThrowableMT, reKind); } BOOL IsAsyncThreadException(OBJECTREF *pThrowable) { if ( IsExceptionOfType(kThreadStopException, pThrowable) ||IsExceptionOfType(kThreadAbortException, pThrowable) ||IsExceptionOfType(kThreadInterruptedException, pThrowable)) { return TRUE; } else { return FALSE; } } BOOL IsUncatchable(OBJECTREF *pThrowable) { if (IsAsyncThreadException(pThrowable) || IsExceptionOfType(kExecutionEngineException, pThrowable)) { return TRUE; } else { return FALSE; } } #ifdef _DEBUG BOOL IsValidClause(EE_ILEXCEPTION_CLAUSE *EHClause) { DWORD valid = COR_ILEXCEPTION_CLAUSE_FILTER | COR_ILEXCEPTION_CLAUSE_FINALLY | COR_ILEXCEPTION_CLAUSE_FAULT | COR_ILEXCEPTION_CLAUSE_CACHED_CLASS; #if 0 // @NICE: enable this when VC stops generatng a bogus 0x8000. if (EHClause->Flags & ~valid) return FALSE; #endif if (EHClause->TryStartPC > EHClause->TryEndPC) return FALSE; return TRUE; } #endif //=========================================================================================== // // UNHANDLED EXCEPTION HANDLING // //===================== // FailFast is called to take down the process when we discover some kind of unrecoverable // error. It can be called from an exception handler, or from any other place we discover // a fatal error. If called from a handler, and pExceptionRecord and pContext are not null, // we'll first give the debugger a chance to handle the exception. // the exception first. #pragma warning(disable:4702) void FailFast(Thread* pThread, UnhandledExceptionLocation reason, EXCEPTION_RECORD *pExceptionRecord, CONTEXT *pContext) { HRESULT hr; if ( g_pConfig && g_pConfig->ContinueAfterFatalError() && reason != FatalExecutionEngineException) return; LOG((LF_EH, LL_INFO100, "FailFast() called.\n")); g_fFatalError = 1; #ifdef _DEBUG // If this exception interupted a ForbidGC, we need to restore it so that the // recovery code is in a semi stable state. if (pThread != NULL) { while(pThread->GCForbidden()) { pThread->EndForbidGC(); } } #endif // We sometimes get some other fatal error as a result of a stack overflow. For example, // inside the OS heap allocation routines ... they return a NULL if they get a stack // overflow. If we call it out-of-memory it's misleading, as the machine may have lots of // memory remaining // if (pThread && !pThread->GuardPageOK()) reason = FatalStackOverflow; if (pThread && pContext && pExceptionRecord) { BEGIN_ENSURE_COOPERATIVE_GC(); // Managed debugger gets a chance if we passed in a context and exception record. switch(reason) { case FatalStackOverflow: pThread->SetThrowable(ObjectFromHandle(g_pPreallocatedStackOverflowException)); break; case FatalOutOfMemory: pThread->SetThrowable(ObjectFromHandle(g_pPreallocatedOutOfMemoryException)); break; default: pThread->SetThrowable(ObjectFromHandle(g_pPreallocatedExecutionEngineException)); break; } if (g_pDebugInterface && g_pDebugInterface-> LastChanceManagedException( pExceptionRecord, pContext, pThread, ProcessWideHandler) == ExceptionContinueExecution) { LOG((LF_EH, LL_INFO100, "FailFast: debugger ==> EXCEPTION_CONTINUE_EXECUTION\n")); _ASSERTE(!"Debugger should not have returned ContinueExecution"); } END_ENSURE_COOPERATIVE_GC(); } // Debugger didn't stop us. We're out of here. // Would use the resource file, but we can't do that without running managed code. switch (reason) { case FatalStackOverflow: // LoadStringRC(IDS_EE_FATAL_STACK_OVERFLOW, buf, buf_size); PrintToStdErrA("\nFatal stack overflow error.\n"); hr = COR_E_STACKOVERFLOW; break; case FatalOutOfMemory: //LoadStringRC(IDS_EE_FATAL_OUT_OF_MEMORY, buf, buf_size); PrintToStdErrA("\nFatal out of memory error.\n"); hr = COR_E_OUTOFMEMORY; break; default: //LoadStringRC(IDS_EE_FATAL_ERROR, buf, buf_size); PrintToStdErrA("\nFatal execution engine error.\n"); hr = COR_E_EXECUTIONENGINE; _ASSERTE(0); // These we want to look at. break; } g_fForbidEnterEE = 1; //DebugBreak(); // Give the guy a chance to attack a debugger before we die. Note ... // func-evals are probably not going to work well any more. ::ExitProcess(hr); _ASSERTE(!"::ExitProcess(hr) should not return"); ::TerminateProcess(GetCurrentProcess(), hr); } #pragma warning(default:4702) // // Used to get the current instruction pointer value // #pragma inline_depth ( 0 ) DWORD __declspec(naked) GetEIP() { __asm { mov eax, [esp] ret } } #pragma inline_depth() // // Log an error to the event log if possible, then throw up a dialog box. // #define FatalErrorStringLength 50 #define FatalErrorAddressLength 20 WCHAR lpWID[FatalErrorAddressLength]; WCHAR lpMsg[FatalErrorStringLength]; void LogFatalError(DWORD id) { // Id is currently an 8 char memory address // Error string is 31 characters // Create the error message Wszwsprintf(lpWID, L"0x%x", id); Wszlstrcpy (lpMsg, L"Fatal Execution Engine Error ("); Wszlstrcat (lpMsg, lpWID); Wszlstrcat(lpMsg, L")"); // Write to the event log and/or display WszMessageBoxInternal(NULL, lpMsg, NULL, MB_OK | MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST); if (IsDebuggerPresent()) { DebugBreak(); } } static void FatalErrorFilter(Thread *pThread, UnhandledExceptionLocation reason, EXCEPTION_POINTERS *pExceptionPointers) { CONTEXT *pContext = pExceptionPointers->ContextRecord; EXCEPTION_RECORD *pExceptionRecord = pExceptionPointers->ExceptionRecord; FailFast(pThread, reason, pExceptionRecord, pContext); } static void FatalError(UnhandledExceptionLocation reason, OBJECTHANDLE hException) { Thread *pThread = GetThread(); if (!pThread || !g_fExceptionsOK) { FailFast(NULL, reason, NULL, NULL); } else { __try { pThread->SetLastThrownObjectHandleAndLeak(hException); RaiseException(EXCEPTION_COMPLUS, EXCEPTION_NONCONTINUABLE, 0, NULL); } __except((FatalErrorFilter(pThread, reason, GetExceptionInformation()), COMPLUS_EXCEPTION_EXECUTE_HANDLER)) { /* do nothing */; } } } void FatalOutOfMemoryError() { if (g_pConfig && g_pConfig->ContinueAfterFatalError()) return; FatalError(FatalOutOfMemory, g_pPreallocatedOutOfMemoryException); } void FatalInternalError() { FatalError(FatalExecutionEngineException, g_pPreallocatedExecutionEngineException); } int UserBreakpointFilter(EXCEPTION_POINTERS* pEP) { int result = UnhandledExceptionFilter(pEP); if (result == EXCEPTION_CONTINUE_SEARCH) { // A debugger got attached. Instead of allowing the exception to continue // up, and hope for the second-chance, we cause it to happen again. The // debugger snags all int3's on first-chance. return EXCEPTION_CONTINUE_EXECUTION; } else { TerminateProcess(GetCurrentProcess(), STATUS_BREAKPOINT); // Shouldn't get here ... return EXCEPTION_CONTINUE_EXECUTION; } } // We keep a pointer to the previous unhandled exception filter. After we install, we use // this to call the previous guy. When we un-install, we put them back. Putting them back // is a bug -- we have no guarantee that the DLL unload order matches the DLL load order -- we // may in fact be putting back a pointer to a DLL that has been unloaded. // // initialize to -1 because NULL won't detect difference between us not having installed our handler // yet and having installed it but the original handler was NULL. static LPTOP_LEVEL_EXCEPTION_FILTER g_pOriginalUnhandledExceptionFilter = (LPTOP_LEVEL_EXCEPTION_FILTER)-1; #define FILTER_NOT_INSTALLED (LPTOP_LEVEL_EXCEPTION_FILTER) -1 void InstallUnhandledExceptionFilter() { if (g_pOriginalUnhandledExceptionFilter == FILTER_NOT_INSTALLED) { g_pOriginalUnhandledExceptionFilter = SetUnhandledExceptionFilter(COMUnhandledExceptionFilter); // make sure is set (ie. is not our special value to indicate unset) } _ASSERTE(g_pOriginalUnhandledExceptionFilter != FILTER_NOT_INSTALLED); } void UninstallUnhandledExceptionFilter() { if (g_pOriginalUnhandledExceptionFilter != FILTER_NOT_INSTALLED) { SetUnhandledExceptionFilter(g_pOriginalUnhandledExceptionFilter); g_pOriginalUnhandledExceptionFilter = FILTER_NOT_INSTALLED; } } // // COMUnhandledExceptionFilter is used to catch all unhandled exceptions. // The debugger will either handle the exception, attach a debugger, or // notify an existing attached debugger. // BOOL LaunchJITDebugger(); LONG InternalUnhandledExceptionFilter(struct _EXCEPTION_POINTERS *pExceptionInfo, BOOL isTerminating) { if (g_fFatalError) return EXCEPTION_CONTINUE_SEARCH; LOG((LF_EH, LL_INFO100, "InternalUnhandledExceptionFilter: Called\n")); Thread *pThread = GetThread(); if (!pThread) { return g_pOriginalUnhandledExceptionFilter ? g_pOriginalUnhandledExceptionFilter(pExceptionInfo) : EXCEPTION_CONTINUE_SEARCH; } #ifdef _DEBUG static bool bBreakOnUncaught = false; static int fBreakOnUncaught = 0; if (!bBreakOnUncaught) { fBreakOnUncaught = g_pConfig->GetConfigDWORD(L"BreakOnUncaughtException", 0); bBreakOnUncaught = true; } // static fBreakOnUncaught mad file global due to VC7 bug if (fBreakOnUncaught) { //fprintf(stderr, "Attach debugger now. Sleeping for 1 minute.\n"); //Sleep(60 * 1000); _ASSERTE(!"BreakOnUnCaughtException"); } #endif #ifdef _DEBUG_ADUNLOAD printf("%x InternalUnhandledExceptionFilter: Called for %x\n", GetThread()->GetThreadId(), pExceptionInfo->ExceptionRecord->ExceptionCode); fflush(stdout); #endif if (!pThread->GuardPageOK()) g_fFatalError = TRUE; if (g_fNoExceptions) // This shouldn't be possible, but MSVC re-installs us ... return EXCEPTION_CONTINUE_SEARCH; // ... for now, just bail if this happens. LOG((LF_EH, LL_INFO100, "InternalUnhandledExceptionFilter: Handling\n")); _ASSERTE(g_pOriginalUnhandledExceptionFilter != FILTER_NOT_INSTALLED); SLOT ExceptionEIP = 0; __try { // Debugger does func-evals inside this call, which may take nested exceptions. We // need a nested exception handler to allow this. #ifdef DEBUGGING_SUPPORTED LOG((LF_EH, LL_INFO100, "InternalUnhandledExceptionFilter: Notifying Debugger...\n")); INSTALL_NESTED_EXCEPTION_HANDLER(pThread->GetFrame()); if (g_pDebugInterface && g_pDebugInterface-> LastChanceManagedException(pExceptionInfo->ExceptionRecord, pExceptionInfo->ContextRecord, pThread, ProcessWideHandler) == ExceptionContinueExecution) { LOG((LF_EH, LL_INFO100, "InternalUnhandledExceptionFilter: debugger ==> EXCEPTION_CONTINUE_EXECUTION\n")); return EXCEPTION_CONTINUE_EXECUTION; } LOG((LF_EH, LL_INFO100, "InternalUnhandledExceptionFilter: ... returned.\n")); UNINSTALL_NESTED_EXCEPTION_HANDLER(); #endif // DEBUGGING_SUPPORTED // Except for notifying debugger, ignore exception if thread is NULL, or if it's // a debugger-generated exception. if ( pExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_BREAKPOINT || pExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP) { LOG((LF_EH, LL_INFO100, "InternalUnhandledExceptionFilter, ignoring the exception\n")); return g_pOriginalUnhandledExceptionFilter ? g_pOriginalUnhandledExceptionFilter(pExceptionInfo) : EXCEPTION_CONTINUE_SEARCH; } LOG((LF_EH, LL_INFO100, "InternalUnhandledExceptionFilter: Calling DefaultCatchHandler\n")); BOOL toggleGC = ! pThread->PreemptiveGCDisabled(); if (toggleGC) pThread->DisablePreemptiveGC(); DefaultCatchHandler(NULL, TRUE); if (toggleGC) pThread->EnablePreemptiveGC(); } __except( (ExceptionEIP = (SLOT)GetIP((GetExceptionInformation())->ContextRecord)), COMPLUS_EXCEPTION_EXECUTE_HANDLER) { // Should never get here. #ifdef _DEBUG char buffer[200]; g_fFatalError = 1; sprintf(buffer, "\nInternal error: Uncaught exception was thrown from IP = 0x%08x in UnhandledExceptionFilter on thread %x\n", ExceptionEIP, GetThread()->GetThreadId()); PrintToStdErrA(buffer); _ASSERTE(!"Unexpected exception in UnhandledExceptionFilter"); #endif FreeBuildDebugBreak(); } LOG((LF_EH, LL_INFO100, "InternalUnhandledExceptionFilter: call next handler\n")); return g_pOriginalUnhandledExceptionFilter ? g_pOriginalUnhandledExceptionFilter(pExceptionInfo) : EXCEPTION_CONTINUE_SEARCH; } LONG COMUnhandledExceptionFilter(struct _EXCEPTION_POINTERS *pExceptionInfo) { return InternalUnhandledExceptionFilter(pExceptionInfo, TRUE); } void PrintStackTraceToStdout(); void STDMETHODCALLTYPE DefaultCatchHandler(OBJECTREF *pThrowableIn, BOOL isTerminating) { // TODO: The strings in here should be translatable. LOG((LF_ALL, LL_INFO10, "In DefaultCatchHandler\n")); const int buf_size = 128; WCHAR buf[buf_size]; #ifdef _DEBUG static bool bBreakOnUncaught = false; static int fBreakOnUncaught = 0; if (!bBreakOnUncaught) { fBreakOnUncaught = g_pConfig->GetConfigDWORD(L"BreakOnUncaughtException", 0); bBreakOnUncaught = true; } // static fBreakOnUncaught mad file global due to VC7 bug if (fBreakOnUncaught) { _ASSERTE(!"BreakOnUnCaughtException"); //fprintf(stderr, "Attach debugger now. Sleeping for 1 minute.\n"); //Sleep(60 * 1000); } #endif Thread *pThread = GetThread(); // @NICE: At one point, we had the comment: // The following hack reduces a window for a race during shutdown. IT DOES NOT FIX // THE PROBLEM. ONLY MAKES IT LESS LIKELY. UGH... // It may no longer be necessary ... but remove at own peril. if (!pThread) { _ASSERTE(g_fEEShutDown); return; } _ASSERTE(pThread); ExInfo* pExInfo = pThread->GetHandlerInfo(); BOOL ExInUnmanagedHandler = pExInfo->IsInUnmanagedHandler(); pExInfo->ResetIsInUnmanagedHandler(); BOOL fWasGCEnabled = !pThread->PreemptiveGCDisabled(); if (fWasGCEnabled) pThread->DisablePreemptiveGC(); OBJECTREF throwable; // If we can't run managed code, can't deliver the event, nor can we print a string. Just silently let // the exception go. if (!CanRunManagedCode()) goto exit; if (pThrowableAvailable(pThrowableIn)) throwable = *pThrowableIn; else throwable = GETTHROWABLE(); if (throwable == NULL) { LOG((LF_ALL, LL_INFO10, "Unhangled exception, throwable == NULL\n")); goto exit; } GCPROTECT_BEGIN(throwable); BOOL IsStackOverflow = (throwable->GetTrueMethodTable() == g_pStackOverflowExceptionClass); BOOL IsOutOfMemory = (throwable->GetTrueMethodTable() == g_pOutOfMemoryExceptionClass); // Notify the AppDomain that we have taken an unhandled exception. Can't notify // of stack overflow -- guard page is not yet reset. BOOL SentEvent = FALSE; if (!IsStackOverflow && !IsOutOfMemory && pThread->GuardPageOK()) { INSTALL_NESTED_EXCEPTION_HANDLER(pThread->GetFrame()); // This guy will never throw, but it will need a spot to store // any nested exceptions it might find. SentEvent = pThread->GetDomain()->OnUnhandledException(&throwable, isTerminating); UNINSTALL_NESTED_EXCEPTION_HANDLER(); } #ifndef _IA64_ COMPLUS_TRY { #endif // if this isn't ThreadStopException, we want to print a stack trace to // indicate why this thread abruptly terminated. Exceptions kill threads // rarely enough that an uncached name check is reasonable. BOOL dump = TRUE; if (IsStackOverflow || !pThread->GuardPageOK() || IsOutOfMemory) { // We have to be very careful. If we walk off the end of the stack, the process // will just die. e.g. IsAsyncThreadException() and Exception.ToString both consume // too much stack -- and can't be called here. // // @BUG 26505: See if we can't find a way to print a partial stack trace. dump = FALSE; PrintToStdErrA("\n"); if (FAILED(LoadStringRC(IDS_EE_UNHANDLED_EXCEPTION, buf, buf_size))) wcscpy(buf, SZ_UNHANDLED_EXCEPTION); PrintToStdErrW(buf); if (IsOutOfMemory) { PrintToStdErrA(" OutOfMemoryException.\n"); } else { PrintToStdErrA(" StackOverflowException.\n"); } } else if (SentEvent || IsAsyncThreadException(&throwable)) { dump = FALSE; } if (dump) { CQuickWSTRNoDtor message; if (throwable != NULL) { PrintToStdErrA("\n"); if (FAILED(LoadStringRC(IDS_EE_UNHANDLED_EXCEPTION, buf, buf_size))) wcscpy(buf, SZ_UNHANDLED_EXCEPTION); PrintToStdErrW(buf); PrintToStdErrA(" "); INSTALL_NESTED_EXCEPTION_HANDLER(pThread->GetFrame()); GetExceptionMessage(throwable, &message); UNINSTALL_NESTED_EXCEPTION_HANDLER(); if (message.Size() > 0) { NPrintToStdErrW(message.Ptr(), message.Size()); } PrintToStdErrA("\n"); } message.Destroy(); } #ifndef _IA64_ } COMPLUS_CATCH { LOG((LF_ALL, LL_INFO10, "Exception occured while processing uncaught exception\n")); if (FAILED(LoadStringRC(IDS_EE_EXCEPTION_TOSTRING_FAILED, buf, buf_size))) wcscpy(buf, L"Exception.ToString() failed."); PrintToStdErrA("\n "); PrintToStdErrW(buf); PrintToStdErrA("\n"); } COMPLUS_END_CATCH #endif FlushLogging(); // Flush any logging output GCPROTECT_END(); exit: if (fWasGCEnabled) pThread->EnablePreemptiveGC(); if (ExInUnmanagedHandler) pExInfo->SetIsInUnmanagedHandler(); } BOOL COMPlusIsMonitorException(struct _EXCEPTION_POINTERS *pExceptionInfo) { return COMPlusIsMonitorException(pExceptionInfo->ExceptionRecord, pExceptionInfo->ContextRecord); } BOOL COMPlusIsMonitorException(EXCEPTION_RECORD *pExceptionRecord, CONTEXT *pContext) { #if ZAPMONITOR_ENABLED //get the fault address and hand it to monitor. if (pExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) { void* f_address = (void*)pExceptionRecord->ExceptionInformation [1]; if (ZapMonitor::HandleAccessViolation ((BYTE*)f_address, pContext)) return true; } #endif return false; } LONG ThreadBaseExceptionFilter(struct _EXCEPTION_POINTERS *pExceptionInfo, Thread* pThread, UnhandledExceptionLocation location) { LOG((LF_EH, LL_INFO100, "ThreadBaseExceptionFilter: Enter\n")); if (COMPlusIsMonitorException(pExceptionInfo)) return EXCEPTION_CONTINUE_EXECUTION; #ifdef _DEBUG if (g_pConfig->GetConfigDWORD(L"BreakOnUncaughtException", 0)) _ASSERTE(!"BreakOnUnCaughtException"); #endif _ASSERTE(!g_fNoExceptions); _ASSERTE(pThread); // Debugger does func-evals inside this call, which may take nested exceptions. We // need a nested exception handler to allow this. if (!pThread->IsAbortRequested()) { LONG result = EXCEPTION_CONTINUE_SEARCH; // A thread-abort is "expected". No debugger popup required. INSTALL_NESTED_EXCEPTION_HANDLER(pThread->GetFrame()); if (g_pDebugInterface && g_pDebugInterface-> LastChanceManagedException(pExceptionInfo->ExceptionRecord, pExceptionInfo->ContextRecord, GetThread(), location) == ExceptionContinueExecution) { LOG((LF_EH, LL_INFO100, "COMUnhandledExceptionFilter: EXCEPTION_CONTINUE_EXECUTION\n")); result = EXCEPTION_CONTINUE_EXECUTION; } UNINSTALL_NESTED_EXCEPTION_HANDLER(); if (result == EXCEPTION_CONTINUE_EXECUTION) return result; } // ignore breakpoint exceptions if ( location != ClassInitUnhandledException && pExceptionInfo->ExceptionRecord->ExceptionCode != STATUS_BREAKPOINT && pExceptionInfo->ExceptionRecord->ExceptionCode != STATUS_SINGLE_STEP) { LOG((LF_EH, LL_INFO100, "ThreadBaseExceptionFilter: Calling DefaultCatchHandler\n")); DefaultCatchHandler(NULL, FALSE); } return EXCEPTION_CONTINUE_SEARCH; } #ifndef _X86_ BOOL InitializeExceptionHandling() { return TRUE; } #ifdef SHOULD_WE_CLEANUP VOID TerminateExceptionHandling() { } #endif /* SHOULD_WE_CLEANUP */ #endif //========================================================================== // Handy helper functions //========================================================================== #define FORMAT_MESSAGE_BUFFER_LENGTH 1024 #define RES_BUFF_LEN 128 #define EXCEP_BUFF_LEN FORMAT_MESSAGE_BUFFER_LENGTH + RES_BUFF_LEN + 3 static void GetWin32Error(DWORD err, WCHAR *wszBuff, int len) { THROWSCOMPLUSEXCEPTION(); DWORD res = WszFormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL /*ignored msg source*/, err, 0 /*pick appropriate languageId*/, wszBuff, len-1, 0 /*arguments*/); if (res == 0) COMPlusThrowOM(); } static void ThrowException(OBJECTREF *pThrowable, STRINGREF message) { THROWSCOMPLUSEXCEPTION(); _ASSERTE(pThrowableAvailable(pThrowable)); _ASSERTE(*pThrowable); if (message != NULL) { INT64 args[] = { ObjToInt64(*pThrowable), ObjToInt64(message) }; CallConstructor(&gsig_IM_Str_RetVoid, args); } else { INT64 args[] = { ObjToInt64(*pThrowable) }; CallConstructor(&gsig_IM_RetVoid, args); } COMPlusThrow(*pThrowable); _ASSERTE(!"Should never reach here !"); } /* * Given a class name and a "message string", an object of the throwable class * is created and the constructor is called using the "message string". * Use this method if the constructor takes a string as parameter. * If the string is NULL, the constructor is called without any * parameters. * * After successfully creating an object of the class, it is thrown. * * If the message is not null and the object constructor does not take a * string input, a method not found exception is thrown. */ void ThrowUsingMessage(MethodTable * pMT, const WCHAR *pszMsg) { THROWSCOMPLUSEXCEPTION(); struct _gc { OBJECTREF throwable; STRINGREF message; _gc() : throwable(OBJECTREF((size_t)NULL)), message(STRINGREF((size_t)NULL)) {} } gc; GCPROTECT_BEGIN(gc); gc.throwable = AllocateObject(pMT); if (pszMsg) { gc.message = COMString::NewString(pszMsg); if (gc.message == NULL) COMPlusThrowOM(); } ThrowException(&gc.throwable, gc.message); _ASSERTE(!"Should never reach here !"); GCPROTECT_END(); } /* * Given a class name, an object of the throwable class is created and the * constructor is called using a string created using Win32 error message. * This function uses GetLastError() to obtain the Win32 error code. * Use this method if the constructor takes a string as parameter. * After successfully creating an object of the class, it is thrown. * * If the object constructor does not take a string input, a method * not found exception is thrown. */ void ThrowUsingWin32Message(MethodTable * pMT) { THROWSCOMPLUSEXCEPTION(); WCHAR wszBuff[FORMAT_MESSAGE_BUFFER_LENGTH]; GetWin32Error(GetLastError(), wszBuff, FORMAT_MESSAGE_BUFFER_LENGTH); wszBuff[FORMAT_MESSAGE_BUFFER_LENGTH - 1] = 0; struct _gc { OBJECTREF throwable; STRINGREF message; _gc() : throwable(OBJECTREF((size_t)NULL)), message(STRINGREF((size_t)NULL)) {} } gc; GCPROTECT_BEGIN(gc); gc.message = COMString::NewString(wszBuff); gc.throwable = AllocateObject(pMT); ThrowException(&gc.throwable, gc.message); _ASSERTE(!"Should never reach here !"); GCPROTECT_END(); } /* * An attempt is made to get the Win32 Error message. * If the Win32 message is available, it is appended to the given message. * The ResourceID is used to lookup a string to get the message */ void ThrowUsingResourceAndWin32(MethodTable * pMT, DWORD dwMsgResID) { THROWSCOMPLUSEXCEPTION(); WCHAR wszMessage[EXCEP_BUFF_LEN]; CreateMessageFromRes (pMT, dwMsgResID, TRUE, wszMessage); struct _gc { OBJECTREF throwable; STRINGREF message; _gc() : throwable(OBJECTREF((size_t)NULL)), message(STRINGREF((size_t)NULL)) {} } gc; GCPROTECT_BEGIN(gc); gc.message = COMString::NewString(wszMessage); gc.throwable = AllocateObject(pMT); ThrowException(&gc.throwable, gc.message); _ASSERTE(!"Should never reach here !"); GCPROTECT_END(); } void ThrowUsingResource(MethodTable * pMT, DWORD dwMsgResID) { THROWSCOMPLUSEXCEPTION(); CreateMessageFromRes (pMT, dwMsgResID, FALSE, NULL); } // wszMessage is, when affected, RCString[WIN32_Error] void CreateMessageFromRes (MethodTable * pMT, DWORD dwMsgResID, BOOL win32error, WCHAR * wszMessage) { // First get the Win32 error code DWORD err = GetLastError(); // Create the exception message by looking up the resource WCHAR wszBuff[EXCEP_BUFF_LEN]; wszBuff[0] = 0; if (FAILED(LoadStringRC(dwMsgResID, wszBuff, RES_BUFF_LEN))) { wcsncpy(wszBuff, L"[EEInternal : LoadResource Failed]", EXCEP_BUFF_LEN); ThrowUsingMessage(pMT, wszBuff); } wszBuff[RES_BUFF_LEN] = 0; // get the Win32 error code err = (win32error ? err : 0); if (err == 0) { ThrowUsingMessage(pMT, wszBuff); _ASSERTE(!"Should never reach here !"); } wcscat(wszBuff, L"["); // FORMAT_MESSAGE_BUFFER_LENGTH is guaranteed to work because we used // wcslen(wszBuff) <= RES_BUFF_LEN + 1 _ASSERTE(wcslen(wszBuff) <= (RES_BUFF_LEN + 1)); GetWin32Error(err, &wszBuff[wcslen(wszBuff)], FORMAT_MESSAGE_BUFFER_LENGTH); wszBuff[EXCEP_BUFF_LEN - 1] = 0; wcscat(wszBuff, L"]"); _ASSERTE(wcslen(wszBuff) < EXCEP_BUFF_LEN); wcscpy(wszMessage, wszBuff); } LPCWSTR GetHResultSymbolicName(HRESULT hr) { #define CASE_HRESULT(hrname) case hrname: return L#hrname; switch (hr) { CASE_HRESULT(E_UNEXPECTED)// 0x8000FFFFL CASE_HRESULT(E_NOTIMPL)// 0x80004001L CASE_HRESULT(E_OUTOFMEMORY)// 0x8007000EL CASE_HRESULT(E_INVALIDARG)// 0x80070057L CASE_HRESULT(E_NOINTERFACE)// 0x80004002L CASE_HRESULT(E_POINTER)// 0x80004003L CASE_HRESULT(E_HANDLE)// 0x80070006L CASE_HRESULT(E_ABORT)// 0x80004004L CASE_HRESULT(E_FAIL)// 0x80004005L CASE_HRESULT(E_ACCESSDENIED)// 0x80070005L CASE_HRESULT(CO_E_INIT_TLS)// 0x80004006L CASE_HRESULT(CO_E_INIT_SHARED_ALLOCATOR)// 0x80004007L CASE_HRESULT(CO_E_INIT_MEMORY_ALLOCATOR)// 0x80004008L CASE_HRESULT(CO_E_INIT_CLASS_CACHE)// 0x80004009L CASE_HRESULT(CO_E_INIT_RPC_CHANNEL)// 0x8000400AL CASE_HRESULT(CO_E_INIT_TLS_SET_CHANNEL_CONTROL)// 0x8000400BL CASE_HRESULT(CO_E_INIT_TLS_CHANNEL_CONTROL)// 0x8000400CL CASE_HRESULT(CO_E_INIT_UNACCEPTED_USER_ALLOCATOR)// 0x8000400DL CASE_HRESULT(CO_E_INIT_SCM_MUTEX_EXISTS)// 0x8000400EL CASE_HRESULT(CO_E_INIT_SCM_FILE_MAPPING_EXISTS)// 0x8000400FL CASE_HRESULT(CO_E_INIT_SCM_MAP_VIEW_OF_FILE)// 0x80004010L CASE_HRESULT(CO_E_INIT_SCM_EXEC_FAILURE)// 0x80004011L CASE_HRESULT(CO_E_INIT_ONLY_SINGLE_THREADED)// 0x80004012L // ****************** // FACILITY_ITF // ****************** CASE_HRESULT(S_OK)// 0x00000000L CASE_HRESULT(S_FALSE)// 0x00000001L CASE_HRESULT(OLE_E_OLEVERB)// 0x80040000L CASE_HRESULT(OLE_E_ADVF)// 0x80040001L CASE_HRESULT(OLE_E_ENUM_NOMORE)// 0x80040002L CASE_HRESULT(OLE_E_ADVISENOTSUPPORTED)// 0x80040003L CASE_HRESULT(OLE_E_NOCONNECTION)// 0x80040004L CASE_HRESULT(OLE_E_NOTRUNNING)// 0x80040005L CASE_HRESULT(OLE_E_NOCACHE)// 0x80040006L CASE_HRESULT(OLE_E_BLANK)// 0x80040007L CASE_HRESULT(OLE_E_CLASSDIFF)// 0x80040008L CASE_HRESULT(OLE_E_CANT_GETMONIKER)// 0x80040009L CASE_HRESULT(OLE_E_CANT_BINDTOSOURCE)// 0x8004000AL CASE_HRESULT(OLE_E_STATIC)// 0x8004000BL CASE_HRESULT(OLE_E_PROMPTSAVECANCELLED)// 0x8004000CL CASE_HRESULT(OLE_E_INVALIDRECT)// 0x8004000DL CASE_HRESULT(OLE_E_WRONGCOMPOBJ)// 0x8004000EL CASE_HRESULT(OLE_E_INVALIDHWND)// 0x8004000FL CASE_HRESULT(OLE_E_NOT_INPLACEACTIVE)// 0x80040010L CASE_HRESULT(OLE_E_CANTCONVERT)// 0x80040011L CASE_HRESULT(OLE_E_NOSTORAGE)// 0x80040012L CASE_HRESULT(DV_E_FORMATETC)// 0x80040064L CASE_HRESULT(DV_E_DVTARGETDEVICE)// 0x80040065L CASE_HRESULT(DV_E_STGMEDIUM)// 0x80040066L CASE_HRESULT(DV_E_STATDATA)// 0x80040067L CASE_HRESULT(DV_E_LINDEX)// 0x80040068L CASE_HRESULT(DV_E_TYMED)// 0x80040069L CASE_HRESULT(DV_E_CLIPFORMAT)// 0x8004006AL CASE_HRESULT(DV_E_DVASPECT)// 0x8004006BL CASE_HRESULT(DV_E_DVTARGETDEVICE_SIZE)// 0x8004006CL CASE_HRESULT(DV_E_NOIVIEWOBJECT)// 0x8004006DL CASE_HRESULT(DRAGDROP_E_NOTREGISTERED)// 0x80040100L CASE_HRESULT(DRAGDROP_E_ALREADYREGISTERED)// 0x80040101L CASE_HRESULT(DRAGDROP_E_INVALIDHWND)// 0x80040102L CASE_HRESULT(CLASS_E_NOAGGREGATION)// 0x80040110L CASE_HRESULT(CLASS_E_CLASSNOTAVAILABLE)// 0x80040111L CASE_HRESULT(VIEW_E_DRAW)// 0x80040140L CASE_HRESULT(REGDB_E_READREGDB)// 0x80040150L CASE_HRESULT(REGDB_E_WRITEREGDB)// 0x80040151L CASE_HRESULT(REGDB_E_KEYMISSING)// 0x80040152L CASE_HRESULT(REGDB_E_INVALIDVALUE)// 0x80040153L CASE_HRESULT(REGDB_E_CLASSNOTREG)// 0x80040154L CASE_HRESULT(CACHE_E_NOCACHE_UPDATED)// 0x80040170L CASE_HRESULT(OLEOBJ_E_NOVERBS)// 0x80040180L CASE_HRESULT(INPLACE_E_NOTUNDOABLE)// 0x800401A0L CASE_HRESULT(INPLACE_E_NOTOOLSPACE)// 0x800401A1L CASE_HRESULT(CONVERT10_E_OLESTREAM_GET)// 0x800401C0L CASE_HRESULT(CONVERT10_E_OLESTREAM_PUT)// 0x800401C1L CASE_HRESULT(CONVERT10_E_OLESTREAM_FMT)// 0x800401C2L CASE_HRESULT(CONVERT10_E_OLESTREAM_BITMAP_TO_DIB)// 0x800401C3L CASE_HRESULT(CONVERT10_E_STG_FMT)// 0x800401C4L CASE_HRESULT(CONVERT10_E_STG_NO_STD_STREAM)// 0x800401C5L CASE_HRESULT(CONVERT10_E_STG_DIB_TO_BITMAP)// 0x800401C6L CASE_HRESULT(CLIPBRD_E_CANT_OPEN)// 0x800401D0L CASE_HRESULT(CLIPBRD_E_CANT_EMPTY)// 0x800401D1L CASE_HRESULT(CLIPBRD_E_CANT_SET)// 0x800401D2L CASE_HRESULT(CLIPBRD_E_BAD_DATA)// 0x800401D3L CASE_HRESULT(CLIPBRD_E_CANT_CLOSE)// 0x800401D4L CASE_HRESULT(MK_E_CONNECTMANUALLY)// 0x800401E0L CASE_HRESULT(MK_E_EXCEEDEDDEADLINE)// 0x800401E1L CASE_HRESULT(MK_E_NEEDGENERIC)// 0x800401E2L CASE_HRESULT(MK_E_UNAVAILABLE)// 0x800401E3L CASE_HRESULT(MK_E_SYNTAX)// 0x800401E4L CASE_HRESULT(MK_E_NOOBJECT)// 0x800401E5L CASE_HRESULT(MK_E_INVALIDEXTENSION)// 0x800401E6L CASE_HRESULT(MK_E_INTERMEDIATEINTERFACENOTSUPPORTED)// 0x800401E7L CASE_HRESULT(MK_E_NOTBINDABLE)// 0x800401E8L CASE_HRESULT(MK_E_NOTBOUND)// 0x800401E9L CASE_HRESULT(MK_E_CANTOPENFILE)// 0x800401EAL CASE_HRESULT(MK_E_MUSTBOTHERUSER)// 0x800401EBL CASE_HRESULT(MK_E_NOINVERSE)// 0x800401ECL CASE_HRESULT(MK_E_NOSTORAGE)// 0x800401EDL CASE_HRESULT(MK_E_NOPREFIX)// 0x800401EEL CASE_HRESULT(MK_E_ENUMERATION_FAILED)// 0x800401EFL CASE_HRESULT(CO_E_NOTINITIALIZED)// 0x800401F0L CASE_HRESULT(CO_E_ALREADYINITIALIZED)// 0x800401F1L CASE_HRESULT(CO_E_CANTDETERMINECLASS)// 0x800401F2L CASE_HRESULT(CO_E_CLASSSTRING)// 0x800401F3L CASE_HRESULT(CO_E_IIDSTRING)// 0x800401F4L CASE_HRESULT(CO_E_APPNOTFOUND)// 0x800401F5L CASE_HRESULT(CO_E_APPSINGLEUSE)// 0x800401F6L CASE_HRESULT(CO_E_ERRORINAPP)// 0x800401F7L CASE_HRESULT(CO_E_DLLNOTFOUND)// 0x800401F8L CASE_HRESULT(CO_E_ERRORINDLL)// 0x800401F9L CASE_HRESULT(CO_E_WRONGOSFORAPP)// 0x800401FAL CASE_HRESULT(CO_E_OBJNOTREG)// 0x800401FBL CASE_HRESULT(CO_E_OBJISREG)// 0x800401FCL CASE_HRESULT(CO_E_OBJNOTCONNECTED)// 0x800401FDL CASE_HRESULT(CO_E_APPDIDNTREG)// 0x800401FEL CASE_HRESULT(CO_E_RELEASED)// 0x800401FFL CASE_HRESULT(OLE_S_USEREG)// 0x00040000L CASE_HRESULT(OLE_S_STATIC)// 0x00040001L CASE_HRESULT(OLE_S_MAC_CLIPFORMAT)// 0x00040002L CASE_HRESULT(DRAGDROP_S_DROP)// 0x00040100L CASE_HRESULT(DRAGDROP_S_CANCEL)// 0x00040101L CASE_HRESULT(DRAGDROP_S_USEDEFAULTCURSORS)// 0x00040102L CASE_HRESULT(DATA_S_SAMEFORMATETC)// 0x00040130L CASE_HRESULT(VIEW_S_ALREADY_FROZEN)// 0x00040140L CASE_HRESULT(CACHE_S_FORMATETC_NOTSUPPORTED)// 0x00040170L CASE_HRESULT(CACHE_S_SAMECACHE)// 0x00040171L CASE_HRESULT(CACHE_S_SOMECACHES_NOTUPDATED)// 0x00040172L CASE_HRESULT(OLEOBJ_S_INVALIDVERB)// 0x00040180L CASE_HRESULT(OLEOBJ_S_CANNOT_DOVERB_NOW)// 0x00040181L CASE_HRESULT(OLEOBJ_S_INVALIDHWND)// 0x00040182L CASE_HRESULT(INPLACE_S_TRUNCATED)// 0x000401A0L CASE_HRESULT(CONVERT10_S_NO_PRESENTATION)// 0x000401C0L CASE_HRESULT(MK_S_REDUCED_TO_SELF)// 0x000401E2L CASE_HRESULT(MK_S_ME)// 0x000401E4L CASE_HRESULT(MK_S_HIM)// 0x000401E5L CASE_HRESULT(MK_S_US)// 0x000401E6L CASE_HRESULT(MK_S_MONIKERALREADYREGISTERED)// 0x000401E7L // ****************** // FACILITY_WINDOWS // ****************** CASE_HRESULT(CO_E_CLASS_CREATE_FAILED)// 0x80080001L CASE_HRESULT(CO_E_SCM_ERROR)// 0x80080002L CASE_HRESULT(CO_E_SCM_RPC_FAILURE)// 0x80080003L CASE_HRESULT(CO_E_BAD_PATH)// 0x80080004L CASE_HRESULT(CO_E_SERVER_EXEC_FAILURE)// 0x80080005L CASE_HRESULT(CO_E_OBJSRV_RPC_FAILURE)// 0x80080006L CASE_HRESULT(MK_E_NO_NORMALIZED)// 0x80080007L CASE_HRESULT(CO_E_SERVER_STOPPING)// 0x80080008L CASE_HRESULT(MEM_E_INVALID_ROOT)// 0x80080009L CASE_HRESULT(MEM_E_INVALID_LINK)// 0x80080010L CASE_HRESULT(MEM_E_INVALID_SIZE)// 0x80080011L // ****************** // FACILITY_DISPATCH // ****************** CASE_HRESULT(DISP_E_UNKNOWNINTERFACE)// 0x80020001L CASE_HRESULT(DISP_E_MEMBERNOTFOUND)// 0x80020003L CASE_HRESULT(DISP_E_PARAMNOTFOUND)// 0x80020004L CASE_HRESULT(DISP_E_TYPEMISMATCH)// 0x80020005L CASE_HRESULT(DISP_E_UNKNOWNNAME)// 0x80020006L CASE_HRESULT(DISP_E_NONAMEDARGS)// 0x80020007L CASE_HRESULT(DISP_E_BADVARTYPE)// 0x80020008L CASE_HRESULT(DISP_E_EXCEPTION)// 0x80020009L CASE_HRESULT(DISP_E_OVERFLOW)// 0x8002000AL CASE_HRESULT(DISP_E_BADINDEX)// 0x8002000BL CASE_HRESULT(DISP_E_UNKNOWNLCID)// 0x8002000CL CASE_HRESULT(DISP_E_ARRAYISLOCKED)// 0x8002000DL CASE_HRESULT(DISP_E_BADPARAMCOUNT)// 0x8002000EL CASE_HRESULT(DISP_E_PARAMNOTOPTIONAL)// 0x8002000FL CASE_HRESULT(DISP_E_BADCALLEE)// 0x80020010L CASE_HRESULT(DISP_E_NOTACOLLECTION)// 0x80020011L CASE_HRESULT(TYPE_E_BUFFERTOOSMALL)// 0x80028016L CASE_HRESULT(TYPE_E_INVDATAREAD)// 0x80028018L CASE_HRESULT(TYPE_E_UNSUPFORMAT)// 0x80028019L CASE_HRESULT(TYPE_E_REGISTRYACCESS)// 0x8002801CL CASE_HRESULT(TYPE_E_LIBNOTREGISTERED)// 0x8002801DL CASE_HRESULT(TYPE_E_UNDEFINEDTYPE)// 0x80028027L CASE_HRESULT(TYPE_E_QUALIFIEDNAMEDISALLOWED)// 0x80028028L CASE_HRESULT(TYPE_E_INVALIDSTATE)// 0x80028029L CASE_HRESULT(TYPE_E_WRONGTYPEKIND)// 0x8002802AL CASE_HRESULT(TYPE_E_ELEMENTNOTFOUND)// 0x8002802BL CASE_HRESULT(TYPE_E_AMBIGUOUSNAME)// 0x8002802CL CASE_HRESULT(TYPE_E_NAMECONFLICT)// 0x8002802DL CASE_HRESULT(TYPE_E_UNKNOWNLCID)// 0x8002802EL CASE_HRESULT(TYPE_E_DLLFUNCTIONNOTFOUND)// 0x8002802FL CASE_HRESULT(TYPE_E_BADMODULEKIND)// 0x800288BDL CASE_HRESULT(TYPE_E_SIZETOOBIG)// 0x800288C5L CASE_HRESULT(TYPE_E_DUPLICATEID)// 0x800288C6L CASE_HRESULT(TYPE_E_INVALIDID)// 0x800288CFL CASE_HRESULT(TYPE_E_TYPEMISMATCH)// 0x80028CA0L CASE_HRESULT(TYPE_E_OUTOFBOUNDS)// 0x80028CA1L CASE_HRESULT(TYPE_E_IOERROR)// 0x80028CA2L CASE_HRESULT(TYPE_E_CANTCREATETMPFILE)// 0x80028CA3L CASE_HRESULT(TYPE_E_CANTLOADLIBRARY)// 0x80029C4AL CASE_HRESULT(TYPE_E_INCONSISTENTPROPFUNCS)// 0x80029C83L CASE_HRESULT(TYPE_E_CIRCULARTYPE)// 0x80029C84L // ****************** // FACILITY_STORAGE // ****************** CASE_HRESULT(STG_E_INVALIDFUNCTION)// 0x80030001L CASE_HRESULT(STG_E_FILENOTFOUND)// 0x80030002L CASE_HRESULT(STG_E_PATHNOTFOUND)// 0x80030003L CASE_HRESULT(STG_E_TOOMANYOPENFILES)// 0x80030004L CASE_HRESULT(STG_E_ACCESSDENIED)// 0x80030005L CASE_HRESULT(STG_E_INVALIDHANDLE)// 0x80030006L CASE_HRESULT(STG_E_INSUFFICIENTMEMORY)// 0x80030008L CASE_HRESULT(STG_E_INVALIDPOINTER)// 0x80030009L CASE_HRESULT(STG_E_NOMOREFILES)// 0x80030012L CASE_HRESULT(STG_E_DISKISWRITEPROTECTED)// 0x80030013L CASE_HRESULT(STG_E_SEEKERROR)// 0x80030019L CASE_HRESULT(STG_E_WRITEFAULT)// 0x8003001DL CASE_HRESULT(STG_E_READFAULT)// 0x8003001EL CASE_HRESULT(STG_E_SHAREVIOLATION)// 0x80030020L CASE_HRESULT(STG_E_LOCKVIOLATION)// 0x80030021L CASE_HRESULT(STG_E_FILEALREADYEXISTS)// 0x80030050L CASE_HRESULT(STG_E_INVALIDPARAMETER)// 0x80030057L CASE_HRESULT(STG_E_MEDIUMFULL)// 0x80030070L CASE_HRESULT(STG_E_ABNORMALAPIEXIT)// 0x800300FAL CASE_HRESULT(STG_E_INVALIDHEADER)// 0x800300FBL CASE_HRESULT(STG_E_INVALIDNAME)// 0x800300FCL CASE_HRESULT(STG_E_UNKNOWN)// 0x800300FDL CASE_HRESULT(STG_E_UNIMPLEMENTEDFUNCTION)// 0x800300FEL CASE_HRESULT(STG_E_INVALIDFLAG)// 0x800300FFL CASE_HRESULT(STG_E_INUSE)// 0x80030100L CASE_HRESULT(STG_E_NOTCURRENT)// 0x80030101L CASE_HRESULT(STG_E_REVERTED)// 0x80030102L CASE_HRESULT(STG_E_CANTSAVE)// 0x80030103L CASE_HRESULT(STG_E_OLDFORMAT)// 0x80030104L CASE_HRESULT(STG_E_OLDDLL)// 0x80030105L CASE_HRESULT(STG_E_SHAREREQUIRED)// 0x80030106L CASE_HRESULT(STG_E_NOTFILEBASEDSTORAGE)// 0x80030107L CASE_HRESULT(STG_S_CONVERTED)// 0x00030200L // ****************** // FACILITY_RPC // ****************** CASE_HRESULT(RPC_E_CALL_REJECTED)// 0x80010001L CASE_HRESULT(RPC_E_CALL_CANCELED)// 0x80010002L CASE_HRESULT(RPC_E_CANTPOST_INSENDCALL)// 0x80010003L CASE_HRESULT(RPC_E_CANTCALLOUT_INASYNCCALL)// 0x80010004L CASE_HRESULT(RPC_E_CANTCALLOUT_INEXTERNALCALL)// 0x80010005L CASE_HRESULT(RPC_E_CONNECTION_TERMINATED)// 0x80010006L CASE_HRESULT(RPC_E_SERVER_DIED)// 0x80010007L CASE_HRESULT(RPC_E_CLIENT_DIED)// 0x80010008L CASE_HRESULT(RPC_E_INVALID_DATAPACKET)// 0x80010009L CASE_HRESULT(RPC_E_CANTTRANSMIT_CALL)// 0x8001000AL CASE_HRESULT(RPC_E_CLIENT_CANTMARSHAL_DATA)// 0x8001000BL CASE_HRESULT(RPC_E_CLIENT_CANTUNMARSHAL_DATA)// 0x8001000CL CASE_HRESULT(RPC_E_SERVER_CANTMARSHAL_DATA)// 0x8001000DL CASE_HRESULT(RPC_E_SERVER_CANTUNMARSHAL_DATA)// 0x8001000EL CASE_HRESULT(RPC_E_INVALID_DATA)// 0x8001000FL CASE_HRESULT(RPC_E_INVALID_PARAMETER)// 0x80010010L CASE_HRESULT(RPC_E_CANTCALLOUT_AGAIN)// 0x80010011L CASE_HRESULT(RPC_E_SERVER_DIED_DNE)// 0x80010012L CASE_HRESULT(RPC_E_SYS_CALL_FAILED)// 0x80010100L CASE_HRESULT(RPC_E_OUT_OF_RESOURCES)// 0x80010101L CASE_HRESULT(RPC_E_ATTEMPTED_MULTITHREAD)// 0x80010102L CASE_HRESULT(RPC_E_NOT_REGISTERED)// 0x80010103L CASE_HRESULT(RPC_E_FAULT)// 0x80010104L CASE_HRESULT(RPC_E_SERVERFAULT)// 0x80010105L CASE_HRESULT(RPC_E_CHANGED_MODE)// 0x80010106L CASE_HRESULT(RPC_E_INVALIDMETHOD)// 0x80010107L CASE_HRESULT(RPC_E_DISCONNECTED)// 0x80010108L CASE_HRESULT(RPC_E_RETRY)// 0x80010109L CASE_HRESULT(RPC_E_SERVERCALL_RETRYLATER)// 0x8001010AL CASE_HRESULT(RPC_E_SERVERCALL_REJECTED)// 0x8001010BL CASE_HRESULT(RPC_E_INVALID_CALLDATA)// 0x8001010CL CASE_HRESULT(RPC_E_CANTCALLOUT_ININPUTSYNCCALL)// 0x8001010DL CASE_HRESULT(RPC_E_WRONG_THREAD)// 0x8001010EL CASE_HRESULT(RPC_E_THREAD_NOT_INIT)// 0x8001010FL CASE_HRESULT(RPC_E_UNEXPECTED)// 0x8001FFFFL // ****************** // FACILITY_CTL // ****************** CASE_HRESULT(CTL_E_ILLEGALFUNCTIONCALL) CASE_HRESULT(CTL_E_OVERFLOW) CASE_HRESULT(CTL_E_OUTOFMEMORY) CASE_HRESULT(CTL_E_DIVISIONBYZERO) CASE_HRESULT(CTL_E_OUTOFSTRINGSPACE) CASE_HRESULT(CTL_E_OUTOFSTACKSPACE) CASE_HRESULT(CTL_E_BADFILENAMEORNUMBER) CASE_HRESULT(CTL_E_FILENOTFOUND) CASE_HRESULT(CTL_E_BADFILEMODE) CASE_HRESULT(CTL_E_FILEALREADYOPEN) CASE_HRESULT(CTL_E_DEVICEIOERROR) CASE_HRESULT(CTL_E_FILEALREADYEXISTS) CASE_HRESULT(CTL_E_BADRECORDLENGTH) CASE_HRESULT(CTL_E_DISKFULL) CASE_HRESULT(CTL_E_BADRECORDNUMBER) CASE_HRESULT(CTL_E_BADFILENAME) CASE_HRESULT(CTL_E_TOOMANYFILES) CASE_HRESULT(CTL_E_DEVICEUNAVAILABLE) CASE_HRESULT(CTL_E_PERMISSIONDENIED) CASE_HRESULT(CTL_E_DISKNOTREADY) CASE_HRESULT(CTL_E_PATHFILEACCESSERROR) CASE_HRESULT(CTL_E_PATHNOTFOUND) CASE_HRESULT(CTL_E_INVALIDPATTERNSTRING) CASE_HRESULT(CTL_E_INVALIDUSEOFNULL) CASE_HRESULT(CTL_E_INVALIDFILEFORMAT) CASE_HRESULT(CTL_E_INVALIDPROPERTYVALUE) CASE_HRESULT(CTL_E_INVALIDPROPERTYARRAYINDEX) CASE_HRESULT(CTL_E_SETNOTSUPPORTEDATRUNTIME) CASE_HRESULT(CTL_E_SETNOTSUPPORTED) CASE_HRESULT(CTL_E_NEEDPROPERTYARRAYINDEX) CASE_HRESULT(CTL_E_SETNOTPERMITTED) CASE_HRESULT(CTL_E_GETNOTSUPPORTEDATRUNTIME) CASE_HRESULT(CTL_E_GETNOTSUPPORTED) CASE_HRESULT(CTL_E_PROPERTYNOTFOUND) CASE_HRESULT(CTL_E_INVALIDCLIPBOARDFORMAT) CASE_HRESULT(CTL_E_INVALIDPICTURE) CASE_HRESULT(CTL_E_PRINTERERROR) CASE_HRESULT(CTL_E_CANTSAVEFILETOTEMP) CASE_HRESULT(CTL_E_SEARCHTEXTNOTFOUND) CASE_HRESULT(CTL_E_REPLACEMENTSTOOLONG) default: return NULL; } }
35.812112
178
0.569814
npocmaka
2cc93bc2deb10ffdd179cc6269c4f4830d1cffe3
88
hpp
C++
noncopyable.hpp
yuriks/libyuriks
e80c599cdfe6294df8ce58ad5570af20e50b1072
[ "Apache-2.0" ]
6
2015-02-13T20:58:28.000Z
2020-10-02T02:38:13.000Z
libyuriks/noncopyable.hpp
yuriks/super-match-5-dx
47d53b99cc8f93f7cd63a7b11b380ba935739662
[ "Apache-2.0" ]
null
null
null
libyuriks/noncopyable.hpp
yuriks/super-match-5-dx
47d53b99cc8f93f7cd63a7b11b380ba935739662
[ "Apache-2.0" ]
2
2016-10-03T18:50:27.000Z
2018-12-12T22:14:58.000Z
#pragma once #define NONCOPYABLE(cls) cls(const cls&); const cls& operator=(const cls&)
29.333333
74
0.738636
yuriks
2ccc90d150fe55648df73ba053f9b4f7ffe5772c
1,988
hpp
C++
src/endian/boost/io/detail/bin_manip.hpp
veprbl/libepecur
83167ac6220e69887c03b556f1a7ffc518cbb227
[ "Unlicense" ]
1
2021-06-25T13:41:19.000Z
2021-06-25T13:41:19.000Z
src/endian/boost/io/detail/bin_manip.hpp
veprbl/libepecur
83167ac6220e69887c03b556f1a7ffc518cbb227
[ "Unlicense" ]
null
null
null
src/endian/boost/io/detail/bin_manip.hpp
veprbl/libepecur
83167ac6220e69887c03b556f1a7ffc518cbb227
[ "Unlicense" ]
null
null
null
// boost/io/detail/bin_manip.hpp -----------------------------------------------------// // Copyright Beman Dawes 2009, 2011 // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt #ifndef BOOST_BIN_MANIP_HPP #define BOOST_BIN_MANIP_HPP #include <boost/config.hpp> #include <ostream> #include <istream> #include <string> #include <cstring> // for strlen #ifndef BOOST_NO_CWCHAR # include <cwchar> // for wcslen #endif // unformatted binary (as opposed to formatted character) input and output manipulator // Caution: Use only on streams opened with filemode std::ios_base::binary. Thus // unformatted binary I/O should not be with the standard streams (cout, cin, etc.) // since they are opened in text mode. Use on text streams may produce incorrect // results, such as insertion of unwanted characters or premature end-of-file. // For example, on Windows 0x0D would become 0x0D, 0x0A. namespace boost { namespace detail { template <class T> struct const_binary_data { const char* ptr; explicit const_binary_data(const T& x) : ptr(reinterpret_cast<const char*>(&x)) {} }; template <class T> struct binary_data { char* ptr; explicit binary_data(T& x) : ptr(reinterpret_cast<char*>(&x)) {} }; } template <class T> inline detail::const_binary_data<T> bin(const T& x) { return detail::const_binary_data<T>(x); } template <class T> inline detail::binary_data<T> bin(T& x) { return detail::binary_data<T>(x); } template <class T> inline std::ostream& operator<<(std::ostream& os, detail::const_binary_data<T> x) { return os.write(x.ptr, sizeof(T)); } template <class T> inline std::ostream& operator<<(std::ostream& os, detail::binary_data<T> x) { return os.write(x.ptr, sizeof(T)); } template <class T> inline std::istream& operator>>(std::istream& is, detail::binary_data<T> x) { return is.read(x.ptr, sizeof(T)); } } // namespace boost #endif // BOOST_BIN_MANIP_HPP
24.54321
90
0.691147
veprbl
2ccd42cb5391a7f47e2769fe6befd68a23307375
2,348
cpp
C++
src/saveload/animated_tile_sl.cpp
trademarks/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
8
2016-10-21T09:01:43.000Z
2021-05-31T06:32:14.000Z
src/saveload/animated_tile_sl.cpp
blackberry/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
null
null
null
src/saveload/animated_tile_sl.cpp
blackberry/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
4
2017-05-16T00:15:58.000Z
2020-08-06T01:46:31.000Z
/* $Id$ */ /* * This file is part of OpenTTD. * OpenTTD 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, version 2. * OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file animated_tile_sl.cpp Code handling saving and loading of animated tiles */ #include "../stdafx.h" #include "../tile_type.h" #include "../core/alloc_func.hpp" #include "saveload.h" extern TileIndex *_animated_tile_list; extern uint _animated_tile_count; extern uint _animated_tile_allocated; /** * Save the ANIT chunk. */ static void Save_ANIT() { SlSetLength(_animated_tile_count * sizeof(*_animated_tile_list)); SlArray(_animated_tile_list, _animated_tile_count, SLE_UINT32); } /** * Load the ANIT chunk; the chunk containing the animated tiles. */ static void Load_ANIT() { /* Before version 80 we did NOT have a variable length animated tile table */ if (IsSavegameVersionBefore(80)) { /* In pre version 6, we has 16bit per tile, now we have 32bit per tile, convert it ;) */ SlArray(_animated_tile_list, 256, IsSavegameVersionBefore(6) ? (SLE_FILE_U16 | SLE_VAR_U32) : SLE_UINT32); for (_animated_tile_count = 0; _animated_tile_count < 256; _animated_tile_count++) { if (_animated_tile_list[_animated_tile_count] == 0) break; } return; } _animated_tile_count = (uint)SlGetFieldLength() / sizeof(*_animated_tile_list); /* Determine a nice rounded size for the amount of allocated tiles */ _animated_tile_allocated = 256; while (_animated_tile_allocated < _animated_tile_count) _animated_tile_allocated *= 2; _animated_tile_list = ReallocT<TileIndex>(_animated_tile_list, _animated_tile_allocated); SlArray(_animated_tile_list, _animated_tile_count, SLE_UINT32); } /** * "Definition" imported by the saveload code to be able to load and save * the animated tile table. */ extern const ChunkHandler _animated_tile_chunk_handlers[] = { { 'ANIT', Save_ANIT, Load_ANIT, NULL, NULL, CH_RIFF | CH_LAST}, };
36.6875
185
0.758518
trademarks
2ccd709ed3d6150e8440478c862626b8257c7a06
2,128
cpp
C++
src/kalman_filter.cpp
kunlin596/CarND-Extended-Kalman-Filter-Project
130a8e3555b94edb494dcbcef20d3620176cf21a
[ "MIT" ]
null
null
null
src/kalman_filter.cpp
kunlin596/CarND-Extended-Kalman-Filter-Project
130a8e3555b94edb494dcbcef20d3620176cf21a
[ "MIT" ]
null
null
null
src/kalman_filter.cpp
kunlin596/CarND-Extended-Kalman-Filter-Project
130a8e3555b94edb494dcbcef20d3620176cf21a
[ "MIT" ]
null
null
null
#include "kalman_filter.h" #include "tools.h" #include "logger.h" using Eigen::MatrixXd; using Eigen::VectorXd; /* * Please note that the Eigen library does not initialize * VectorXd or MatrixXd objects with zeros upon creation. */ void KalmanFilter::Predict(double dt) { // Update F F_(0, 2) = F_(1, 3) = dt; // Using linear motion model for all measurements // Update Q static constexpr double noise_ax = 9.0, noise_ay = 9.0; const double dt4 = std::pow(dt, 4) / 4.0, dt3 = std::pow(dt, 3) / 2.0, dt2 = std::pow(dt, 2); Q_ << dt4 * noise_ax , 0.0 , dt3 * noise_ax , 0.0 , 0.0 , dt4 * noise_ay , 0.0 , dt3 * noise_ay , dt3 * noise_ax , 0.0 , dt2 * noise_ax , 0.0 , 0.0 , dt3 * noise_ay , 0.0 , dt2 * noise_ay ; // Predict next state and covariance x_ = F_ * x_; P_ = F_ * P_ * F_.transpose() + Q_; BOOST_LOG_TRIVIAL(debug) << "Predict: x=" << x_.transpose().format(HeavyFmt); // BOOST_LOG_TRIVIAL(debug) << " P=\n" << P_.format(HeavyFmt); } void KalmanFilter::Update(const Eigen::Vector2d &z) { const Eigen::Vector2d y = z - H_ * x_; const Eigen::Matrix2d S = H_ * P_ * H_.transpose() + R_; const Eigen::Matrix<double, 4, 2> K = P_ * H_.transpose() * S.inverse(); x_ = x_ + K * y; P_ = P_ - K * H_ * P_; } void KalmanFilter::UpdateEKF(const Eigen::Vector3d &z) { Eigen::Matrix<double, 3, 4> Hj = Tools::CalculateJacobian(x_); Eigen::Vector3d z_pred = Tools::ConvertCartesianToPolar(x_); // NOTE: Handle a case where the measured angle changes from M_PI to -M_PI. // FIXME: Is there better way to flip the angle? if (z_pred[1] < -M_PI * 0.9 and z[1] > M_PI * 0.9) { z_pred[1] = 2 * M_PI - std::abs(z_pred[1]); } Eigen::Vector3d y = z - z_pred; Eigen::Matrix3d S = Hj * P_ * Hj.transpose() + R_; Eigen::Matrix<double, 4, 3> K = P_ * Hj.transpose() * S.inverse(); x_ = x_ + K * y; P_ = P_ - K * Hj * P_; }
33.25
81
0.549342
kunlin596
2ccf346bceb3ae6911c239b47004f6e90a1b497d
5,926
hpp
C++
third_party/concurrentqueue/tests/relacy/relacy/relacy/memory.hpp
tufeigunchu/orbit
407354cf7c9159ff7e3177c603a6850b95509e3a
[ "BSD-2-Clause" ]
1,847
2020-03-24T19:01:42.000Z
2022-03-31T13:18:57.000Z
third_party/concurrentqueue/tests/relacy/relacy/relacy/memory.hpp
tufeigunchu/orbit
407354cf7c9159ff7e3177c603a6850b95509e3a
[ "BSD-2-Clause" ]
1,100
2020-03-24T19:41:13.000Z
2022-03-31T14:27:09.000Z
third_party/concurrentqueue/tests/relacy/relacy/relacy/memory.hpp
tufeigunchu/orbit
407354cf7c9159ff7e3177c603a6850b95509e3a
[ "BSD-2-Clause" ]
228
2020-03-25T05:32:08.000Z
2022-03-31T11:27:39.000Z
/* Relacy Race Detector * Copyright (c) 2008-2013, Dmitry S. Vyukov * All rights reserved. * This software is provided AS-IS with no warranty, either express or implied. * This software is distributed under a license and may not be copied, * modified or distributed except as expressly authorized under the * terms of the license contained in the file LICENSE in this distribution. */ #ifndef RL_MEMORY_HPP #define RL_MEMORY_HPP #ifdef _MSC_VER # pragma once #endif #include "base.hpp" namespace rl { class memory_mgr : nocopy<> { public: memory_mgr() { memset(deferred_free_, 0, sizeof(deferred_free_)); memset(deferred_free_size_, 0, sizeof(deferred_free_size_)); deferred_index_ = 0; } ~memory_mgr() { /* while (allocs_.size()) { size_t* p = (size_t*)(allocs_.begin()->first); free(p - 1, false); allocs_.erase(allocs_.begin()); } */ } #ifndef RL_GC void* alloc(size_t size) #else void* alloc(size_t size, void (*dtor)(void*)) #endif { void* pp = 0; for (size_t i = 0; i != alloc_cache_.size(); ++i) { if (alloc_cache_[i].first == size) { if (alloc_cache_[i].second.size()) { pp = alloc_cache_[i].second.top(); alloc_cache_[i].second.pop(); } break; } } if (0 == pp) pp = (::malloc)(size + alignment); if (pp) { RL_VERIFY(alignment >= sizeof(void*)); *(size_t*)pp = size; void* p = (char*)pp + alignment; #ifndef RL_GC allocs_.insert(std::make_pair(p, size)); #else alloc_desc_t desc = {p, size, dtor}; gc_allocs_.push_back(desc); #endif return p; } else { throw std::bad_alloc(); } } bool free(void* pp, bool defer) { if (0 == pp) return true; #ifndef RL_GC map<void*, size_t>::type::iterator iter = allocs_.find(pp); if (allocs_.end() == iter) return false; allocs_.erase(iter); void* p = (char*)pp - alignment; size_t size = *(size_t*)p; if (defer) { deferred_free_[deferred_index_ % deferred_count] = p; deferred_free_size_[deferred_index_ % deferred_count] = size; deferred_index_ += 1; p = deferred_free_[deferred_index_ % deferred_count]; size = deferred_free_size_[deferred_index_ % deferred_count]; if (p) rl_free_impl(p, size); } else { rl_free_impl(p, size); } return true; #else (void)defer; for (size_t i = 0; i != gc_allocs_.size(); ++i) { alloc_desc_t const& desc = gc_allocs_[i]; if (desc.addr == pp) { void* p = (char*)desc.addr - alignment; rl_free_impl(p, desc.size); gc_allocs_.erase(gc_allocs_.begin() + i); return true; } } return false; #endif } bool iteration_end() { #ifndef RL_GC return allocs_.empty(); #else for (size_t i = 0; i != gc_allocs_.size(); ++i) { alloc_desc_t const& desc = gc_allocs_[i]; if (desc.dtor) desc.dtor(desc.addr); void* p = (char*)desc.addr - alignment; rl_free_impl(p, desc.size); } gc_allocs_.clear(); return true; #endif } #ifndef RL_GC void output_allocs(std::ostream& stream) { stream << "memory allocations:" << std::endl; map<void*, size_t>::type::iterator iter = allocs_.begin(); map<void*, size_t>::type::iterator end = allocs_.end(); for (; iter != end; ++iter) { stream << iter->first << " [" << (unsigned)iter->second << "]" << std::endl; } stream << std::endl; } #endif private: typedef stack<void*>::type freelist_t; typedef std::pair<size_t, freelist_t> alloc_entry_t; typedef vector<alloc_entry_t>::type alloc_t; static size_t const deferred_count = 64; alloc_t alloc_cache_; size_t deferred_index_; void* deferred_free_ [deferred_count]; size_t deferred_free_size_ [deferred_count]; #ifndef RL_GC map<void*, size_t>::type allocs_; #else struct alloc_desc_t { void* addr; size_t size; void (*dtor)(void*); }; vector<alloc_desc_t>::type gc_allocs_; #endif void rl_free_impl(void* p, size_t size) { bool found = false; for (size_t i = 0; i != alloc_cache_.size(); ++i) { if (alloc_cache_[i].first == size) { found = true; alloc_cache_[i].second.push(p); break; } } if (!found) { alloc_cache_.push_back(std::make_pair(size, freelist_t())); alloc_cache_.back().second.push(p); } } }; struct memory_alloc_event { void* addr_; size_t size_; bool is_array_; void output(std::ostream& s) const { s << "memory allocation: addr=" << std::hex << (void*)((char*)addr_ + (is_array_ ? alignment : 0)) << std::dec << ", size=" << (unsigned)size_; } }; struct memory_free_event { void* addr_; bool is_array_; void output(std::ostream& s) const { s << "memory deallocation: addr=" << std::hex << (void*)((char*)addr_ + (is_array_ ? alignment : 0)) << std::dec; } }; } #endif
24.487603
121
0.509619
tufeigunchu
2ccfac126bcae4aaea53017a8daef5a4d577a548
1,429
cpp
C++
moci/moci_system/system/windows/info.cpp
tobanteAudio/moci
a0a764e8a5270f9344ff57366fea36f72e7e3aa4
[ "BSD-2-Clause" ]
null
null
null
moci/moci_system/system/windows/info.cpp
tobanteAudio/moci
a0a764e8a5270f9344ff57366fea36f72e7e3aa4
[ "BSD-2-Clause" ]
16
2020-03-19T22:08:47.000Z
2020-06-18T18:55:00.000Z
moci/moci_system/system/windows/info.cpp
tobanteAudio/moci
a0a764e8a5270f9344ff57366fea36f72e7e3aa4
[ "BSD-2-Clause" ]
null
null
null
#include "moci_system/system/windows/info.hpp" #if defined(MOCI_WINDOWS) #include <windows.h> namespace moci { std::string SystemInfo::Pimpl::GetOSName() { return "Windows"; } std::string SystemInfo::Pimpl::GetVendor() { // auto const procInfo = SystemInfoLinuxReadProcInfo(); // auto const vendorID = procInfo.find(std::string("vendor_id")); // if (vendorID != std::end(procInfo)) // { // return vendorID->second; // } return ""; } std::string SystemInfo::Pimpl::GetCPUModel() { // auto const procInfo = SystemInfoLinuxReadProcInfo(); // auto const vendorID = procInfo.find(std::string("model name")); // if (vendorID != std::end(procInfo)) // { // return vendorID->second; // } return ""; } int SystemInfo::Pimpl::GetCPUCoreCount() { SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); auto const numCPU = sysinfo.dwNumberOfProcessors; return numCPU; } int SystemInfo::Pimpl::GetCPUThreadCount() { SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); auto const numCPU = sysinfo.dwNumberOfProcessors; return numCPU; } std::string SystemInfo::Pimpl::GetCPUFeatures() { // auto const procInfo = SystemInfoLinuxReadProcInfo(); // auto const vendorID = procInfo.find(std::string("flags")); // if (vendorID != std::end(procInfo)) // { // return vendorID->second; // } return ""; } } // namespace moci #endif
23.42623
70
0.649405
tobanteAudio