hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
e3437f9c2d621ce8c1b96dc6bdf4cb40898ae75e
3,570
tcc
C++
pcre2++/private/format.tcc
sjinks/pcre2pp
f9d842075704e5383ad2d4ce3e3748e40bc0b070
[ "MIT" ]
5
2018-03-02T19:14:32.000Z
2021-08-13T19:24:57.000Z
pcre2++/private/format.tcc
sjinks/pcre2pp
f9d842075704e5383ad2d4ce3e3748e40bc0b070
[ "MIT" ]
12
2017-08-08T07:18:25.000Z
2021-08-14T08:33:49.000Z
pcre2++/private/format.tcc
sjinks/pcre2pp
f9d842075704e5383ad2d4ce3e3748e40bc0b070
[ "MIT" ]
1
2018-07-10T09:50:28.000Z
2018-07-10T09:50:28.000Z
#ifndef PCRE2XX_MATCH_RESULTS_H #error "Please include pcre2++/match_results.h instead" #endif #include <algorithm> template<typename BiIter, typename Alloc> template<typename OutIter> OutIter pcre2::match_results<BiIter, Alloc>::format(OutIter out, const char_type* fmt_first, const char_type* fmt_last, match_flag_type f) const { if (f & pcre2::regex_constants::format_sed) { return this->format_sed(out, fmt_first, fmt_last); } return this->format_default(out, fmt_first, fmt_last); } template<typename BiIter, typename Alloc> template<typename OutIter> OutIter pcre2::match_results<BiIter, Alloc>::format_sed(OutIter out, const char_type* fmt_first, const char_type* fmt_last) const { auto output = [this, &out](std::size_t idx) { auto& s = (*this)[idx]; if (s.matched) { out = std::copy(s.first, s.second, out); } }; while (fmt_first != fmt_last) { char_type c = *fmt_first; if ('&' == c) { output(0); ++fmt_first; } else if ('\\' == c) { ++fmt_first; if (fmt_first != fmt_last) { c = *fmt_first; if (c >= '0' && c <= '9') { output(c - '0'); ++fmt_first; } else if ('&' == c || '\\' == c) { *out = c; ++out; ++fmt_first; } else { *out = '\\'; } } else { *out = '\\'; } } else { *out = *fmt_first; ++out; ++fmt_first; } } return out; } template<typename BiIter, typename Alloc> template<typename OutIter> OutIter pcre2::match_results<BiIter, Alloc>::format_default(OutIter out, const char_type* fmt_first, const char_type* fmt_last) const { auto output = [this, &out](std::size_t idx) { auto& s = (*this)[idx]; if (s.matched) { out = std::copy(s.first, s.second, out); } }; while (true) { auto next = std::find(fmt_first, fmt_last, '$'); if (next == fmt_last) { break; } out = std::copy(fmt_first, next, out); ++next; if (next == fmt_last) { *out = '$'; ++out; } else if (*next == '$') { *out = '$'; ++out; ++next; } else if (*next == '&') { ++next; output(0); } else if (*next == '`') { ++next; auto& pfx = this->get_prefix(); if (pfx.matched) { out = std::copy(pfx.first, pfx.second, out); } } else if (*next == '\'') { ++next; auto& sfx = this->get_suffix(); if (sfx.matched) { out = std::copy(sfx.first, sfx.second, out); } } else if (*next >= '0' && *next <= '9') { std::size_t idx = *next - '0'; ++next; if (next != fmt_last && *next >= '0' && *next <= '9') { idx = idx * 10 + (*next - '0'); ++next; } if (idx < this->size()) { output(idx); } } else { *out = '$'; ++out; } fmt_first = next; } out = std::copy(fmt_first, fmt_last, out); return out; }
25.683453
144
0.432213
sjinks
e356791ff030ab80a56f80c2b3608477f2854080
783
hpp
C++
test/control.hpp
cynodelic/mulinum
fc7b9e750aadaede2cee8d840e65fa3832787764
[ "BSL-1.0" ]
null
null
null
test/control.hpp
cynodelic/mulinum
fc7b9e750aadaede2cee8d840e65fa3832787764
[ "BSL-1.0" ]
null
null
null
test/control.hpp
cynodelic/mulinum
fc7b9e750aadaede2cee8d840e65fa3832787764
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2019 Álvaro Ceballos // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt #ifndef CYNODELIC_MULINUM_TEST_CONTROL_HPP #define CYNODELIC_MULINUM_TEST_CONTROL_HPP CYNODELIC_TESTER_TEST_CASE_SINGLE_SECTION(control) { CYNODELIC_TESTER_CHECK_TRUE((mln::equals<int,int>::value)); CYNODELIC_TESTER_CHECK_FALSE((mln::equals<char[3][3],int[1]>::value)); CYNODELIC_TESTER_CHECK_FALSE((mln::not_equals<int,int>::value)); CYNODELIC_TESTER_CHECK_TRUE((mln::not_equals<char[3][3],int[1]>::value)); CYNODELIC_TESTER_CHECK_TRUE((mln::equals<mln::if_<true,double,bool>,double>::value)); CYNODELIC_TESTER_CHECK_TRUE((mln::equals<mln::if_<false,double,bool>,bool>::value)); } #endif
34.043478
86
0.780332
cynodelic
e35e9ea0fe934ea8f34c5ba38a8afebf7938a98c
1,529
cpp
C++
2020day18/test.cpp
AntonJoha/AdventOfCode
3349f789adf3dc1d8062d56ba3efb20fbb0ee335
[ "MIT" ]
null
null
null
2020day18/test.cpp
AntonJoha/AdventOfCode
3349f789adf3dc1d8062d56ba3efb20fbb0ee335
[ "MIT" ]
null
null
null
2020day18/test.cpp
AntonJoha/AdventOfCode
3349f789adf3dc1d8062d56ba3efb20fbb0ee335
[ "MIT" ]
null
null
null
#include <fstream> #include <iostream> #include <list> #include "run.h" typedef bool (*test)(); std::list<test> testcases; void testRun(){ int i = 1; for (test t : testcases){ if (t()) { std::cout << "Passed test: " << i << "\n"; } else { std::cout << "Didn't pass test: " << i << "\n"; } ++i; } } bool testMain(const char* filename, std::string expected){ std::ifstream fs; fs.open(filename); if (!fs.is_open()) return false; std::string result = run::solve(&fs); fs.close(); return expected == result; } #ifdef FIRST bool test1(){ return testMain("test1.1", "26"); } bool test2(){ return testMain("test2.1", "437"); } bool test3(){ return testMain("test3.1", "12240"); } bool test4(){ return testMain("test4.1", "13632"); } bool test5(){ return testMain("test5.1", "26335"); } void addTest(){ testcases.push_front(test5); testcases.push_front(test4); testcases.push_front(test3); testcases.push_front(test2); testcases.push_front(test1); } #endif #ifdef SECOND bool test1(){ return testMain("test1.2", "51"); } bool test2(){ return testMain("test2.2", "46"); } bool test3(){ return testMain("test3.2", "1445"); } bool test4(){ return testMain("test4.2", "669060"); } bool test5(){ return testMain("test5.2", "23340"); } void addTest(){ testcases.push_front(test5); testcases.push_front(test4); testcases.push_front(test3); testcases.push_front(test2); testcases.push_front(test1); } #endif int main(){ addTest(); testRun(); }
12.532787
58
0.626553
AntonJoha
e3620eabfc5755933fc365f62e5355c3d1d97366
4,012
hpp
C++
include/slim/types/Regexp.hpp
wnewbery/cpp-slim
c7087294b55db5d7ca846438ebddfaec395d1a12
[ "MIT" ]
3
2017-12-24T23:35:04.000Z
2019-03-16T09:35:46.000Z
include/slim/types/Regexp.hpp
wnewbery/cpp-slim
c7087294b55db5d7ca846438ebddfaec395d1a12
[ "MIT" ]
98
2016-07-01T14:55:03.000Z
2020-03-13T14:12:49.000Z
include/slim/types/Regexp.hpp
wnewbery/cpp-slim
c7087294b55db5d7ca846438ebddfaec395d1a12
[ "MIT" ]
2
2019-04-03T12:16:14.000Z
2020-03-13T14:13:25.000Z
#pragma once #include "Object.hpp" #include "Type.hpp" #include <regex> #include <unordered_map> #include <vector> #include <cassert> namespace slim { class Array; class Number; class String; class Regexp; /**MatchData for Regexp.*/ class MatchData : public Object { public: static const std::string &name() { static const std::string TYPE_NAME = "MatchData"; return TYPE_NAME; } virtual const std::string& type_name()const override { return name(); } virtual std::string to_string()const override; virtual bool eq(const Object *rhs)const override; virtual size_t hash()const override; virtual ObjectPtr el_ref(const FunctionArgs &args)override; Ptr<Object> begin(Number *n); Ptr<Array> captures(); Ptr<Object> end(Number *n); //names: Not supported because do not support named captures Ptr<Object> offset(Number *n); Ptr<String> post_match(); Ptr<String> pre_match(); Ptr<Regexp> regexp() { return regex; } Ptr<Number> size(); Ptr<String> string(); Ptr<Array> to_a(); Ptr<Array> values_at(const FunctionArgs &args); protected: virtual const MethodTable &method_table()const; private: friend class Regexp; Ptr<Regexp> regex; std::string str; std::smatch match; MatchData(Ptr<Regexp> regex, const std::string &str) : regex(regex), str(str), match() {} std::ssub_match get_sub(Number *n)const; Ptr<Object> sub_str(int n)const; }; /**Script Regexp using std::regex.*/ class Regexp : public Object { public: static const int IGNORECASE = 1; static const int EXTENDED = 2; static const int MULTILINE = 4; static Ptr<String> escape(String *str); //static Ptr<Object> last_match(const FunctionArgs &args); static Ptr<Regexp> new_instance(const FunctionArgs &args); //static Ptr<Regexp> try_convert(Ptr<Object> obj); //static Ptr<Regexp> union(const FunctionArgs &args); static const std::string &name() { static const std::string TYPE_NAME = "Regexp"; return TYPE_NAME; } virtual const std::string& type_name()const override { return name(); } Regexp(const Regexp &cp) = default; Regexp(const std::string &str, int opts = 0); virtual std::string to_string()const override; virtual std::string inspect()const override; virtual bool eq(const Object *rhs)const override; virtual size_t hash()const override; //unary ~ const std::regex& get()const { return regex; } /**Returns nullptr rather than NIL_VALUE*/ Ptr<MatchData> do_match(const std::string &str, int pos); /**Search from the end of str. * Note that this creates a temp regex. * Also note that all capture groups are +1. As such this does not conform with MatchData * so the plain std::smatch is returned instead. */ std::smatch do_rmatch(const std::string &str, int pos); std::smatch do_rmatch(const std::string &str) { return do_rmatch(str, (int)str.size()); } virtual Ptr<Object> match(const FunctionArgs &args); Ptr<Boolean> casefold_q(); //encoding //fixed_encoding? //named_capatures //names Ptr<Number> options(); Ptr<String> source(); protected: virtual const MethodTable &method_table()const; private: static std::regex_constants::syntax_option_type syntax_options(int opts); std::string src; int opts; std::regex regex; }; class RegexpType : public SimpleClass<Regexp> { public: RegexpType(); protected: virtual const slim::MethodTable &method_table()const override; }; }
31.590551
97
0.603938
wnewbery
e3629d4551983d66ecac534029cc457243546b04
17,491
cpp
C++
src/cryptopp/test/cryptor/tst_cryptortest.cpp
karagog/gutil
43936af9bc4be1945e4f1a3656e91dfbf42cc35b
[ "Apache-2.0" ]
null
null
null
src/cryptopp/test/cryptor/tst_cryptortest.cpp
karagog/gutil
43936af9bc4be1945e4f1a3656e91dfbf42cc35b
[ "Apache-2.0" ]
2
2015-01-30T21:47:55.000Z
2015-02-10T00:22:27.000Z
src/cryptopp/test/cryptor/tst_cryptortest.cpp
karagog/gutil
43936af9bc4be1945e4f1a3656e91dfbf42cc35b
[ "Apache-2.0" ]
null
null
null
/*Copyright 2014 George Karagoulis 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 "gutil_cryptopp_cryptor.h" #include "gutil_sourcesandsinks.h" #include "gutil_strings.h" #include <QtTest> USING_NAMESPACE_GUTIL; USING_NAMESPACE_GUTIL1(CryptoPP); // Keyfiles 1 and 2 differ only in one byte #define KEYFILE1 "keyfile1.txt" #define KEYFILE2 "keyfile2.txt" class CryptorTest : public QObject { Q_OBJECT private Q_SLOTS: void test_basic_encryption(); void test_encryption_with_authentication(); void test_salt(); void test_encryption_with_keyfiles(); void test_nonce(); void test_encryption_with_all_features(); void test_copy(); }; void CryptorTest::test_basic_encryption() { Cryptor crypt("password"); // Test encrypting a small string String pData = "Hello world!!!"; Vector<char> cData; { ByteArrayInput i(pData.ConstData(), pData.Length()); VectorByteArrayOutput o(cData); crypt.EncryptData(&o, &i); } QVERIFY(0 != memcmp(pData.ConstData(), cData.ConstData(), pData.Length())); QVERIFY(cData.Length() == pData.Length() + crypt.GetNonceSize() + crypt.TagLength); Vector<char> recovered; try{ ByteArrayInput i(cData.ConstData(), cData.Length()); VectorByteArrayOutput o(recovered); crypt.DecryptData(&o, &i); } catch(...){ QVERIFY(false); } QVERIFY(0 == memcmp(pData.ConstData(), recovered.ConstData(), pData.Length())); QVERIFY(pData == recovered); // Encrypting the same thing twice gives you completely different crypttexts Vector<char> cData2; { ByteArrayInput i(pData.ConstData(), pData.Length()); VectorByteArrayOutput o(cData2); crypt.EncryptData(&o, &i); } QVERIFY(cData.Length() == cData2.Length()); QVERIFY(0 != memcmp(cData.ConstData(), cData2.ConstData(), cData.Length())); // Test encrypting a long string cData.Empty(); pData = "This is a really long string, to see if it makes a difference" " between a long string and a short string. It might actually, because" " you know, if the message is longer than a single block of the" " block cipher then this tests the cryptor's ability to chain the" " data blocks and the cipher correctly."; { ByteArrayInput i(pData.ConstData(), pData.Length()); VectorByteArrayOutput o(cData); crypt.EncryptData(&o, &i); } QVERIFY(0 != memcmp(pData.ConstData(), cData.ConstData(), pData.Length())); recovered.Empty(); try{ ByteArrayInput i(cData.ConstData(), cData.Length()); VectorByteArrayOutput o(recovered); crypt.DecryptData(&o, &i); } catch(...){ QVERIFY(false); } QVERIFY(pData == recovered); // Try decrypting with a bad password Cryptor crypt2("badpassword"); bool exception_hit = false; try{ ByteArrayInput i(cData.ConstData(), cData.Length()); crypt2.DecryptData(NULL, &i); } catch(const AuthenticationException<> &){ exception_hit = true; } catch(...){ QVERIFY(false); } QVERIFY(exception_hit); // Try corrupting the message by incrementing a byte somewhere cData[0] = cData[0] + 1; exception_hit = false; try{ ByteArrayInput i(cData.ConstData(), cData.Length()); crypt.DecryptData(NULL, &i); } catch(const AuthenticationException<> &){ exception_hit = true; } catch(...){ QVERIFY(false); } QVERIFY(exception_hit); } void CryptorTest::test_encryption_with_authentication() { Cryptor crypt("password"); String pData = "Hello world!!!"; String aData = "This message will be authenticated"; Vector<char> cData; // First authenticate a message without pData { ByteArrayInput i(aData.ConstData(), aData.Length()); VectorByteArrayOutput o(cData); crypt.EncryptData(&o, NULL, &i); } // The crypttext has only the IV and MAC QVERIFY(cData.Length() == crypt.GetNonceSize() + crypt.TagLength); // Verify the authenticity correctly try{ ByteArrayInput i(cData.ConstData(), cData.Length()); ByteArrayInput ia(aData.ConstData(), aData.Length()); crypt.DecryptData(NULL, &i, &ia); } catch(...){ QVERIFY(false); } // Corrupt the message by truncating the auth data, authenticity check fails bool exception_hit = false; try{ ByteArrayInput i(cData.ConstData(), cData.Length()); ByteArrayInput ia(aData.ConstData(), aData.Length() - 1); crypt.DecryptData(NULL, &i, &ia); } catch(const AuthenticationException<> &){ exception_hit = true; } catch(...){ QVERIFY(false); } QVERIFY(exception_hit); // Now try encrypting with both pData and aData cData.Empty(); { ByteArrayInput i(pData.ConstData(), pData.Length()); ByteArrayInput ia(aData.ConstData(), aData.Length()); VectorByteArrayOutput o(cData); crypt.EncryptData(&o, &i, &ia); } // The crypttext has the plaintext plus IV and MAC QVERIFY(cData.Length() == pData.Length() + crypt.GetNonceSize() + crypt.TagLength); // Recover the pData and verify the authenticity Vector<char> recovered; try{ ByteArrayInput i(cData.ConstData(), cData.Length()); ByteArrayInput ia(aData.ConstData(), aData.Length()); VectorByteArrayOutput o(recovered); crypt.DecryptData(&o, &i, &ia); } catch(...){ QVERIFY(false); } QVERIFY(pData.Length() == recovered.Length()); QVERIFY(0 == memcmp(pData.ConstData(), recovered.ConstData(), pData.Length())); // Authenticity check fails if auth data is different exception_hit = false; recovered.Empty(); try{ ByteArrayInput i(cData.ConstData(), cData.Length()); ByteArrayInput ia(aData.ConstData(), aData.Length() - 1); crypt.DecryptData(NULL, &i, &ia); } catch(const AuthenticationException<> &){ exception_hit = true; } catch(...){ QVERIFY(false); } QVERIFY(exception_hit); } static void __test_encryption_with_keyfiles(const byte *salt, GUINT32 salt_len) { // First let's make one successfully so we feel good about ourselves try{ Cryptor(NULL, KEYFILE1); } catch(...){ QVERIFY(false); } // Now let's try to break it by giving it bad inputs // The keyfile must exist bool exception_hit = false; try{ Cryptor(NULL, "this_file_doesnt_exist"); } catch(...){ exception_hit = true; } QVERIFY(exception_hit); // can't give it a directory exception_hit = false; try{ Cryptor(NULL, "."); } catch(...){ exception_hit = true; } QVERIFY(exception_hit); // Ok now let's encrypt and decrypt and see if it works using keyfiles Cryptor crypt(NULL, KEYFILE1, Cryptor::DefaultNonceSize, new Cryptor::DefaultKeyDerivation(salt, salt_len)); String pData = "Hello world!!!"; Vector<char> cData; { ByteArrayInput i(pData.ConstData(), pData.Length()); VectorByteArrayOutput o(cData); crypt.EncryptData(&o, &i); } QVERIFY(cData.Length() == pData.Length() + crypt.GetNonceSize() + crypt.TagLength); QVERIFY(0 != memcmp(pData.ConstData(), cData.ConstData(), pData.Length())); Vector<char> recovered; try{ ByteArrayInput i(cData.ConstData(), cData.Length()); VectorByteArrayOutput o(recovered); crypt.DecryptData(&o, &i); } catch(...){ QVERIFY(false); } QVERIFY(0 == memcmp(pData.ConstData(), recovered.ConstData(), pData.Length())); QVERIFY(pData == recovered); // What if we decrypt with the wrong keyfile? Cryptor crypt2(NULL, KEYFILE2, Cryptor::DefaultNonceSize, new Cryptor::DefaultKeyDerivation(salt, salt_len)); exception_hit = false; try{ ByteArrayInput i(cData.ConstData(), cData.Length()); crypt2.DecryptData(NULL, &i); } catch(const AuthenticationException<> &){ exception_hit = true; } catch(...){ QVERIFY(false); } QVERIFY(exception_hit); // What if we decrypt with the right keyfile but also give a password? crypt2.ChangePassword("password", KEYFILE1); exception_hit = false; try{ ByteArrayInput i(cData.ConstData(), cData.Length()); crypt2.DecryptData(NULL, &i); } catch(const AuthenticationException<> &){ exception_hit = true; } catch(...){ QVERIFY(false); } QVERIFY(exception_hit); // But after everything we can still decrypt it with the right keyfile crypt2.ChangePassword("", KEYFILE1); recovered.Empty(); try{ ByteArrayInput i(cData.ConstData(), cData.Length()); VectorByteArrayOutput o(recovered); crypt2.DecryptData(&o, &i); } catch(...){ QVERIFY(false); } QVERIFY(0 == memcmp(pData.ConstData(), recovered.ConstData(), pData.Length())); QVERIFY(pData == recovered); } void CryptorTest::test_salt() { const char *salt = "Hello I am salt"; __test_encryption_with_keyfiles((byte const *)salt, sizeof(salt)); Cryptor crypt("password", NULL, Cryptor::DefaultNonceSize, new Cryptor::DefaultKeyDerivation((const byte *)salt, sizeof(salt))); String pData = "Hello world!!!"; String aData = "This data will be authenticated!"; Vector<char> cData; { ByteArrayInput i(pData.ConstData(), pData.Length()); ByteArrayInput ia(aData.ConstData(), aData.Length()); VectorByteArrayOutput o(cData); crypt.EncryptData(&o, &i, &ia); } QVERIFY(cData.Length() == pData.Length() + crypt.GetNonceSize() + crypt.TagLength); // Try to decrypt with a bad salt bool exception_hit = false; try{ const char *bad_salt = "This salt is different"; Cryptor crypt2("password", NULL, Cryptor::DefaultNonceSize, new Cryptor::DefaultKeyDerivation((const byte *)bad_salt, sizeof(bad_salt))); ByteArrayInput i(cData.ConstData(), cData.Length()); ByteArrayInput ia(aData.ConstData(), aData.Length()); crypt2.DecryptData(NULL, &i, &ia); } catch(const AuthenticationException<> &){ exception_hit = true; } catch(...){ QVERIFY(false); } QVERIFY(exception_hit); } static void __test_cryptor_nonce_length(int nonce_len) { Cryptor crypt("password", NULL, nonce_len); QVERIFY(crypt.GetNonceSize() == nonce_len); String pData = "Hello world!!!"; String aData = "This data will be authenticated!"; Vector<char> cData; { ByteArrayInput i(pData.ConstData(), pData.Length()); ByteArrayInput ia(aData.ConstData(), aData.Length()); VectorByteArrayOutput o(cData); crypt.EncryptData(&o, &i, &ia); } QVERIFY(cData.Length() == pData.Length() + crypt.GetNonceSize() + crypt.TagLength); QVERIFY(0 != memcmp(pData.ConstData(), cData.ConstData(), pData.Length())); Vector<char> recovered; try{ ByteArrayInput i(cData.ConstData(), cData.Length()); ByteArrayInput ia(aData.ConstData(), aData.Length()); VectorByteArrayOutput o(recovered); crypt.DecryptData(&o, &i, &ia); } catch(...){ QVERIFY(false); } QVERIFY(0 == memcmp(pData.ConstData(), recovered.ConstData(), pData.Length())); QVERIFY(pData == recovered); } void CryptorTest::test_nonce() { bool exception_hit = false; try{ Cryptor(NULL, NULL, 6); } catch(...){ exception_hit = true; } QVERIFY(exception_hit); exception_hit = false; try{ Cryptor(NULL, NULL, 14); } catch(...){ exception_hit = true; } QVERIFY(exception_hit); for(int i = 7; i <= 13; ++i) __test_cryptor_nonce_length(i); // Try encrypting a payload that is too large class too_large_input : public GUtil::IInput{ GUINT64 m_value; public: too_large_input(GUINT64 value) :m_value(value){ } GUINT64 BytesAvailable() const{ return m_value; } GUINT32 ReadBytes(GBYTE *, GUINT32, GUINT32){ return 0; } }; for(int i = 8; i <= 13; ++i) { Cryptor crypt(NULL, NULL, i); exception_hit = false; try{ too_large_input input(((GUINT64)0x10000) << 8*(13-i)); crypt.EncryptData(NULL, &input, NULL); } catch(...){ exception_hit = true; } QVERIFY(exception_hit); } // Test specifying my own nonce Cryptor crypt(NULL, NULL, 8); QVERIFY(crypt.GetNonceSize() == 8); GUINT64 n = 0; String pData = "Hello world!!!"; Vector<char> cData; { ByteArrayInput i(pData.ConstData(), pData.Length()); VectorByteArrayOutput o(cData); crypt.EncryptData(&o, &i, NULL, (byte const *)&n); } QVERIFY(cData.Length() == pData.Length() + crypt.GetNonceSize() + crypt.TagLength); // Check if the nonce is on the end of the message exactly as we gave it QVERIFY(0 == memcmp(cData.Data() + pData.Length() + Cryptor::TagLength, &n, sizeof(n))); } void CryptorTest::test_encryption_with_keyfiles() { __test_encryption_with_keyfiles(NULL, 0); } void CryptorTest::test_encryption_with_all_features() { Cryptor crypt("password", KEYFILE1); // Test basic encryption with auth data String pData = "Hello world!!!"; String aData = "This data will be authenticated!"; Vector<char> cData; { ByteArrayInput i(pData.ConstData(), pData.Length()); ByteArrayInput ia(aData.ConstData(), aData.Length()); VectorByteArrayOutput o(cData); crypt.EncryptData(&o, &i, &ia); } QVERIFY(cData.Length() == pData.Length() + crypt.GetNonceSize() + crypt.TagLength); QVERIFY(0 != memcmp(pData.ConstData(), cData.ConstData(), pData.Length())); Vector<char> recovered; try{ ByteArrayInput i(cData.ConstData(), cData.Length()); ByteArrayInput ia(aData.ConstData(), aData.Length()); VectorByteArrayOutput o(recovered); crypt.DecryptData(&o, &i, &ia); } catch(...){ QVERIFY(false); } QVERIFY(0 == memcmp(pData.ConstData(), recovered.ConstData(), pData.Length())); QVERIFY(pData == recovered); // Try decrypting with a bad password but bood keyfile crypt.ChangePassword("pasSword", KEYFILE1); bool exception_hit = false; try{ ByteArrayInput i(cData.ConstData(), cData.Length()); ByteArrayInput ia(aData.ConstData(), aData.Length()); crypt.DecryptData(NULL, &i, &ia); } catch(const AuthenticationException<> &){ exception_hit = true; } catch(...){ QVERIFY(false); } QVERIFY(exception_hit); // Try decrypting with a good password but bad keyfile crypt.ChangePassword("password", KEYFILE2); exception_hit = false; try{ ByteArrayInput i(cData.ConstData(), cData.Length()); ByteArrayInput ia(aData.ConstData(), aData.Length()); crypt.DecryptData(NULL, &i, &ia); } catch(const AuthenticationException<> &){ exception_hit = true; } catch(...){ QVERIFY(false); } QVERIFY(exception_hit); // Now with the right password and keyfile it should work again crypt.ChangePassword("password", KEYFILE1); recovered.Empty(); try{ ByteArrayInput i(cData.ConstData(), cData.Length()); ByteArrayInput ia(aData.ConstData(), aData.Length()); VectorByteArrayOutput o(recovered); crypt.DecryptData(&o, &i, &ia); } catch(...){ QVERIFY(false); } QVERIFY(0 == memcmp(pData.ConstData(), recovered.ConstData(), pData.Length())); QVERIFY(pData == recovered); // If the auth data was corrupted it should also fail exception_hit = false; try{ ByteArrayInput i(cData.ConstData(), cData.Length()); ByteArrayInput ia(aData.ConstData(), aData.Length() - 1); crypt.DecryptData(NULL, &i, &ia); } catch(const AuthenticationException<> &){ exception_hit = true; } catch(...){ QVERIFY(false); } QVERIFY(exception_hit); // If the crypttext was corrupted it should also fail cData[15] = ~cData[15]; exception_hit = false; try{ ByteArrayInput i(cData.ConstData(), cData.Length()); ByteArrayInput ia(aData.ConstData(), aData.Length()); crypt.DecryptData(NULL, &i, &ia); } catch(const AuthenticationException<> &){ exception_hit = true; } catch(...){ QVERIFY(false); } QVERIFY(exception_hit); } void CryptorTest::test_copy() { Cryptor c1("password", KEYFILE1); Cryptor c2(c1); QVERIFY(c2.CheckPassword("password", KEYFILE1)); } QTEST_APPLESS_MAIN(CryptorTest) #include "tst_cryptortest.moc"
30.525305
132
0.629238
karagog
e36316248b6eaf033e042bd80ed91df5fa0634b4
11,674
cpp
C++
utils/createGrid/main.cpp
basselin7u/GPU-Restricted-Power-Diagrams
196e7d79125fb7edc75ed7b8f13990a7877c48f3
[ "MIT" ]
2
2021-04-06T20:29:42.000Z
2021-04-08T12:37:13.000Z
utils/createGrid/main.cpp
basselin7u/GPU-Restricted-Power-Diagrams
196e7d79125fb7edc75ed7b8f13990a7877c48f3
[ "MIT" ]
null
null
null
utils/createGrid/main.cpp
basselin7u/GPU-Restricted-Power-Diagrams
196e7d79125fb7edc75ed7b8f13990a7877c48f3
[ "MIT" ]
1
2022-01-24T12:42:52.000Z
2022-01-24T12:42:52.000Z
/* -*- Mode: C++; c-default-style: "k&r"; indent-tabs-mode: nil; tab-width: 2; c-basic-offset: 2 -*- */ /* * GEOGRAM example program: * compute Restricted Voronoi diagrams, i.e. * intersection between a Voronoi diagram and a * tetrahedral mesh (or a triangulated mesh). */ /* * Copyright (c) 2012-2014, Bruno Levy * 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 ALICE Project-Team nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * If you modify this software, you should include a notice giving the * name of the person performing the modification, the date of modification, * and the reason for such modification. * * Contact: Bruno Levy * * Bruno.Levy@inria.fr * http://www.loria.fr/~levy * * ALICE Project * LORIA, INRIA Lorraine, * Campus Scientifique, BP 239 * 54506 VANDOEUVRE LES NANCY CEDEX * FRANCE * */ #include <cmath> #include <iomanip> #include <fstream> #include <vector> #include <geogram/basic/common.h> #include <geogram/basic/logger.h> #include <geogram/basic/command_line.h> #include <geogram/basic/command_line_args.h> #include <geogram/basic/stopwatch.h> #include <geogram/basic/file_system.h> #include <geogram/basic/process.h> #include <geogram/mesh/mesh.h> #include <geogram/mesh/mesh_geometry.h> #include <geogram/mesh/mesh_topology.h> #include <geogram/mesh/mesh_io.h> #include <geogram/mesh/mesh_repair.h> #include <geogram/mesh/mesh_fill_holes.h> #include <geogram/mesh/mesh_preprocessing.h> #include <geogram/mesh/mesh_degree3_vertices.h> #include <geogram/mesh/mesh_tetrahedralize.h> #include <geogram/delaunay/delaunay.h> #include <geogram/voronoi/RVD.h> #include <geogram/voronoi/RVD_callback.h> #include <geogram/voronoi/RVD_mesh_builder.h> #include <geogram/numerics/predicates.h> #include "geometry.h" struct VoxelGrid { VoxelGrid(GEO::index_t nb_voxels_per_dimension) { size = nb_voxels_per_dimension; voxel_size = float(1000. / double(size)); in_domain.resize(nb_voxels()); } GEO::vec3 voxel_corner_pos(GEO::index_t id) { return voxel_size*GEO::vec3(id%size, (id / size) % size, id / (size*size)); } GEO::vec3 voxel_center_pos(GEO::index_t id) { return voxel_size*GEO::vec3(0.5 + double(id%size), 0.5 + double((id / size) % size), 0.5 + double(id / (size*size))); } GEO::index_t id(GEO::index_t i, GEO::index_t j, GEO::index_t k) { return k*size*size + j*size + i;} GEO::index_t nb_voxels() { return size*size*size; } void save(std::string const &filename) { std::ofstream f; f.open(filename); f.precision(20); f << size << "\n"; for (GEO::index_t i=0; i<nb_voxels(); ++i) f << in_domain[i] << " "; f << "\n"; f << T_pts.size() << "\n"; for (GEO::index_t i=0; i<T_pts.size(); ++i) f << T_pts[i] << " "; f << "\n"; f << T_triplets.size() << "\n"; for (GEO::index_t i=0; i<T_triplets.size(); ++i) f << T_triplets[i] << " "; f << "\n"; f << T_indir.size() << "\n"; for (GEO::index_t i=0; i<T_indir.size(); ++i) f << T_indir[i] << " "; f << "\n"; f << T_offset.size() << "\n"; for (GEO::index_t i=0; i<T_offset.size(); ++i) f << T_offset[i] << " "; f << "\n"; f.close(); } // data GEO::index_t size ; GEO::vector<char> in_domain; GEO::vector<GEO::vec3> T_pts; GEO::vector<GEO::index_t> T_triplets; GEO::vector<GEO::index_t> T_indir; GEO::vector<GEO::index_t> T_offset; // precomputed float voxel_size; }; int main(int argc, char** argv) { using namespace GEO; GEO::initialize(); try { Stopwatch Wtot("Total time"); std::vector<std::string> filenames; CmdLine::import_arg_group("standard"); CmdLine::import_arg_group("algo"); CmdLine::declare_arg("division", 75, "numbers of division by axis"); CmdLine::declare_arg("grid", "", "volume grid(output)"); CmdLine::declare_arg("output", "", "modified volume"); if(!CmdLine::parse(argc, argv, filenames, "meshfile") ) { return 1; } if(filenames.size() != 1) { std::cout << "Error:" << argv[0] << "meshfile\n"; return 1; } index_t num_divide=75; if(CmdLine::get_arg_int("division") > 0) num_divide=index_t(CmdLine::get_arg_int("division")); std::string mesh_filename = filenames[0]; std::string grid_filename = CmdLine::get_arg("grid"); std::string modif_filename = CmdLine::get_arg("output"); if (!grid_filename.empty()) Logger::out("I/O") << "Grid = " << grid_filename << std::endl; if (!modif_filename.empty()) Logger::out("I/O") << "Modif = " << modif_filename << std::endl; Logger::div("Loading data"); Mesh M_in, grid_in; Mesh M_out; // load mesh { MeshIOFlags flags; flags.set_element(MESH_CELLS); if(!mesh_load(mesh_filename, M_in, flags)) return 1; } // code to reproject point on a sub grid ( retrieved from OGF::MeshGrobGlobalParamCommands::export_notet_domain_definition ) M_in.cells.clear(); M_in.vertices.remove_isolated(); M_in.facets.triangulate(); if (1) { double min[3], max[3]; get_bbox(M_in, min, max); double maxdim = 0; for (int i=0; i<3; ++i) maxdim = std::max(maxdim, max[i]-min[i]); for (index_t v=0; v<M_in.vertices.nb(); ++v) M_in.vertices.point(v)=(990.222/ maxdim) *(M_in.vertices.point(v) - vec3(min[0],min[1],min[2])) + vec3(4.998, 4.998, 4.998); } if (!modif_filename.empty()) { Logger::div("Saving modified data"); mesh_save(M_in, modif_filename); } if (!grid_filename.empty()) { Logger::div("Creating grid"); VoxelGrid grid(num_divide); for (index_t v=0; v<M_in.vertices.nb(); ++v) grid.T_pts.push_back(M_in.vertices.point(v)); for (index_t f=0; f<M_in.facets.nb(); ++f) { for (index_t lv=0; lv<3; ++lv) grid.T_triplets.push_back(M_in.facets.vertex(f,lv)); } std::cerr << "generate list of triangles per voxel\n"; vector<vector<index_t> > voxel_to_tri_id(grid.nb_voxels()); for (index_t f=0; f<M_in.facets.nb(); ++f) { GEO::vec3 boxMin, boxMax; for(index_t c = 0; c < 3; c++) { boxMin[c] = Numeric::max_float64(); boxMax[c] = Numeric::min_float64(); } for(index_t lv=0; lv<3; ++lv) { const double* p = M_in.vertices.point_ptr(M_in.facets.vertex(f,lv)); for(index_t c = 0; c < 3; c++) { boxMin[c] = std::min(boxMin[c], p[c]); boxMax[c] = std::max(boxMax[c], p[c]); } } boxMin = double(grid.size)* boxMin / 1000.; boxMax = double(grid.size)* boxMax / 1000.; for (index_t i = index_t(std::floor(boxMin[0])); i <= index_t(std::ceil(boxMax[0])); i++) { if (i>=grid.size) continue; for (index_t j = index_t(std::floor(boxMin[1])); j <= index_t(std::ceil(boxMax[1])); j++) { if (j>=grid.size) continue; for (index_t k = index_t(std::floor(boxMin[2])); k <= index_t(std::ceil(boxMax[2])); k++) { if (k>=grid.size) continue; index_t id = grid.id(i, j, k); float center[3]; for (index_t d=0; d<3; ++d) center[d] = float(grid.voxel_center_pos(id)[d]); float halfbox_size[3] = { 0.5f*grid.voxel_size , 0.5f*grid.voxel_size , 0.5f*grid.voxel_size }; vec3 trivert[3]; for (index_t lv=0; lv<3; ++lv) trivert[lv] = M_in.vertices.point(M_in.facets.vertex(f, lv)); if (triBoxOverlap(center, halfbox_size, trivert)) voxel_to_tri_id[id].push_back(f); } } } } grid.T_offset.push_back(0); for (index_t i=0; i<grid.nb_voxels(); ++i) { for(index_t lf=0; lf<voxel_to_tri_id[i].size(); ++lf) grid.T_indir.push_back(voxel_to_tri_id[i][lf]); grid.T_offset.push_back(grid.T_indir.size()); } std::cerr << "Compute points step\n"; // compute points for (index_t i=0; i<grid.nb_voxels(); ++i) grid.in_domain[i] = 0; mesh_tetrahedralize(M_in, false, true, 1.); for(index_t c=0; c<M_in.cells.nb(); ++c) { vec3 boxMin, boxMax; for(index_t ce = 0; ce < 3; ce++) { boxMin[ce] = Numeric::max_float64(); boxMax[ce] = Numeric::min_float64(); } for(index_t lv=0; lv<4; ++lv) { const double* p = M_in.vertices.point_ptr(M_in.cells.vertex(c,lv)); for(index_t ce = 0; ce < 3; ce++) { boxMin[ce] = std::min(boxMin[ce], p[ce]); boxMax[ce] = std::max(boxMax[ce], p[ce]); } } boxMin = double(grid.size)* boxMin / 1000.; boxMax = double(grid.size)* boxMax / 1000.; for (index_t i = index_t(floor(boxMin[0])); i <= index_t(ceil(boxMax[0])); i++) { if (i>=grid.size) continue; for (index_t j = index_t(floor(boxMin[1])); j <= index_t(ceil(boxMax[1])); j++) { if (j>=grid.size) continue; for (index_t k = index_t(floor(boxMin[2])); k <= index_t(ceil(boxMax[2])); k++) { if (k>=grid.size) continue; index_t id = grid.id(i, j, k); bool all_inside = true; bool one_outside = false; for(index_t f=0; f<4; ++f) { vec3 P[3]; for(index_t lv=0; lv<3; ++lv) P[lv] = M_in.vertices.point(M_in.cells.facet_vertex(c, f, lv)); vec3 n = cross(P[2] - P[0], P[1] - P[0]); n = normalize(n); double eps = .001; double signed_dist = dot(grid.voxel_corner_pos(id) - P[0], n); all_inside = all_inside && (signed_dist < -eps); one_outside = one_outside || (signed_dist > eps); } if (all_inside) grid.in_domain[id] = 2; else if (!one_outside && grid.in_domain[id] != 2) grid.in_domain[id] = 1; } } } } grid.save(grid_filename); } } catch(const std::exception& e) { std::cerr << "Received an exception: " << e.what() << std::endl; return 1; } Logger::out("") << "Everything OK, Returning status 0" << std::endl; return 0; }
38.150327
167
0.602279
basselin7u
e364e14e47809e5eef2dee638ffc418c30657ff9
1,119
cpp
C++
src/osgEarthBuildings/ElevationsLodNode.cpp
VTMAK/osgearth-buildings
84e3f2cfb352bfeae27944ef62b68ffd8fd98a28
[ "MIT" ]
3
2017-12-05T06:38:28.000Z
2021-12-07T06:19:39.000Z
src/osgEarthBuildings/ElevationsLodNode.cpp
VTMAK/osgearth-buildings
84e3f2cfb352bfeae27944ef62b68ffd8fd98a28
[ "MIT" ]
null
null
null
src/osgEarthBuildings/ElevationsLodNode.cpp
VTMAK/osgearth-buildings
84e3f2cfb352bfeae27944ef62b68ffd8fd98a28
[ "MIT" ]
3
2017-12-03T09:48:04.000Z
2021-12-07T06:19:41.000Z
#include "ElevationsLodNode" #include <osgDB/ObjectWrapper> namespace osgEarth { namespace Buildings { ElevationsLodNode::ElevationsLodNode() { ; } ElevationsLodNode::ElevationsLodNode(const ElevationsLodNode& rhs, const osg::CopyOp& copyop) { elevationsLOD = rhs.elevationsLOD; xform = rhs.xform; } ElevationsLodNode& ElevationsLodNode::operator=(const ElevationsLodNode& rhs) { elevationsLOD = rhs.elevationsLOD; xform = rhs.xform; return *this; } const osg::LOD * ElevationsLodNode::getelevationsLOD() const { return elevationsLOD.get(); } void ElevationsLodNode::setelevationsLOD(osg::LOD * lod) { elevationsLOD = lod; } REGISTER_OBJECT_WRAPPER(ElevationsLodNode, new ElevationsLodNode, osgEarth::Buildings::ElevationsLodNode, "osg::Object osgEarth::Buildings::ElevationsLodNode") { ADD_OBJECT_SERIALIZER(elevationsLOD, osg::LOD, NULL); ADD_MATRIX_SERIALIZER(xform, osg::Matrix()); } } }
26.642857
99
0.631814
VTMAK
e36925a74858e06658647e2c3d7e61995f2af31a
5,818
cpp
C++
src/common/portmgr.cpp
kingtaurus/vogl
a7317fa38e9d909ada4e941ca7dc2df1e4415b37
[ "MIT" ]
497
2015-01-02T19:45:01.000Z
2022-03-04T19:22:07.000Z
src/common/portmgr.cpp
kingtaurus/vogl
a7317fa38e9d909ada4e941ca7dc2df1e4415b37
[ "MIT" ]
40
2015-01-05T21:04:20.000Z
2020-03-25T07:01:59.000Z
src/common/portmgr.cpp
kingtaurus/vogl
a7317fa38e9d909ada4e941ca7dc2df1e4415b37
[ "MIT" ]
85
2015-01-02T22:29:00.000Z
2021-11-28T02:42:48.000Z
/************************************************************************** * * Copyright 2013-2014 RAD Game Tools and Valve Software * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <pthread.h> #include "../common/radlogging.h" #include "portmgr.h" using namespace ports; PortManager::PortManager(int portStart, int portIncrement, int portEnd) { m_fInitialized = false; m_portStart = portStart; m_portIncrement = portIncrement; m_portEnd = portEnd; m_numPorts = (m_portEnd - m_portStart) / m_portIncrement; m_rgPortUsage = NULL; } PortManager::~PortManager() { if (false == m_fInitialized) return; if (m_rgPortUsage) free(m_rgPortUsage); (void)pthread_mutex_destroy(&m_portList_mutex); // Nothing to look at } bool PortManager::FInitialize(int portReserved) { bool fReturn = false; if ((portReserved < m_portStart) || (portReserved > m_portEnd)) { syslog(RAD_CRITICAL, "PortMgr::Finitialize(%d) - portReserved out of range (%d - %d).\n", portReserved, m_portStart, m_portEnd); goto out; } fReturn = FInitialize(); if (false == fReturn) goto out; // // Now reserve this particular port in the list // m_rgPortUsage[portReserved - m_portStart] = true; out: return fReturn; } bool PortManager::FInitialize() { pthread_mutexattr_t mAttr; int rc = 0; if (m_fInitialized) goto out; // already initialized // // Need to allocate the array of ports // if (m_rgPortUsage) free(m_rgPortUsage); m_rgPortUsage = (bool *)malloc(1 + m_numPorts); if (NULL == m_rgPortUsage) { syslog(RAD_CRITICAL, "Unable to allocate memory for PortMgr array.\n"); goto out; } // Initialize to unused (false) for (int iPort = 0; iPort < m_numPorts; iPort++) m_rgPortUsage[iPort] = false; // Initialize mutex for assigning new ports // setup recursive mutex for mutex attribute - this is most like, in behavior, to Windows critical sections // // PTHREAD_MUTEX_RECURSIVE_NP means that the mutex can be used recursively. /* The pthread_mutexattr_settype() function shall fail if: EINVAL The value type is invalid. */ rc = pthread_mutexattr_init(&mAttr); if (0 != rc) { syslog(RAD_CRITICAL, "Error on pthread_mutexattr_init(return code = %x)\nTerminating...\n", rc); goto out; } rc = pthread_mutexattr_settype(&mAttr, PTHREAD_MUTEX_RECURSIVE_NP); if (0 != rc) { syslog(RAD_CRITICAL, "Error on pthread_mutexattr_settype(return code = %x)\nTerminating...\n", rc); goto out; } // Use the mutex attribute to create the mutex /* The pthread_mutex_init() function shall fail if: EAGAIN The system lacked the necessary resources (other than memory) to initialize another mutex. ENOMEM Insufficient memory exists to initialize the mutex. EPERM The caller does not have the privilege to perform the operation. The pthread_mutex_init() function may fail if: EBUSY The implementation has detected an attempt to reinitialize the object referenced by mutex, a previously initialized, but not yet destroyed, mutex. EINVAL The value specified by attr is invalid. */ rc = pthread_mutex_init(&m_portList_mutex, &mAttr); if (0 != rc) { syslog(RAD_CRITICAL, "Error on port manager pthread_mutex_init(return code = %x)\nTerminating...\n", rc); goto out; } m_fInitialized = true; out: return m_fInitialized; } int PortManager::GetNextAvailablePort() { int freePort = -1; int ec = 0; (void)ec; if (false == m_fInitialized) return -1; ec = pthread_mutex_lock(&m_portList_mutex); for (int i = 0; i < m_numPorts; i++) { if (false == m_rgPortUsage[i]) { // This port is free freePort = (i * m_portIncrement) + m_portStart; m_rgPortUsage[i] = true; break; } } pthread_mutex_unlock(&m_portList_mutex); return freePort; } int PortManager::ReleasePort(int port) { int portIndex = (port - m_portStart) / m_portIncrement; int ec = 0; (void)ec; if (false == m_fInitialized) return -1; if (portIndex < 0 || portIndex >= m_numPorts) { syslog(RAD_WARN, "Attempting to release port number out of range(%d)\n", port); return -1; } ec = pthread_mutex_lock(&m_portList_mutex); m_rgPortUsage[portIndex] = false; pthread_mutex_unlock(&m_portList_mutex); return port; }
28.380488
156
0.654692
kingtaurus
e36d993591fe76fbd15ab11ec8228d828faee3fd
11,288
cpp
C++
mathlib/planefit.cpp
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
252
2020-12-16T15:34:43.000Z
2022-03-31T23:21:37.000Z
cstrike15_src/mathlib/planefit.cpp
bahadiraraz/Counter-Strike-Global-Offensive
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
[ "MIT" ]
23
2020-12-20T18:02:54.000Z
2022-03-28T16:58:32.000Z
cstrike15_src/mathlib/planefit.cpp
bahadiraraz/Counter-Strike-Global-Offensive
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
[ "MIT" ]
42
2020-12-19T04:32:33.000Z
2022-03-30T06:00:28.000Z
//============ Copyright (c) Valve Corporation, All rights reserved. ============ // // Code to compute the equation of a plane with a least-squares residual fit. // //=============================================================================== #include "vplane.h" #include "mathlib.h" #include <algorithm> using namespace std; ////////////////////////////////////////////////////////////////////////// // Forward Declarations ////////////////////////////////////////////////////////////////////////// static const float DETERMINANT_EPSILON = 1e-6f; template< int PRIMARY_AXIS > bool ComputeLeastSquaresPlaneFit( const Vector *pPoints, int nNumPoints, VPlane *pFitPlane ); ////////////////////////////////////////////////////////////////////////// // Public Implementation ////////////////////////////////////////////////////////////////////////// bool ComputeLeastSquaresPlaneFitX( const Vector *pPoints, int nNumPoints, VPlane *pFitPlane ) { return ComputeLeastSquaresPlaneFit<0>( pPoints, nNumPoints, pFitPlane ); } bool ComputeLeastSquaresPlaneFitY( const Vector *pPoints, int nNumPoints, VPlane *pFitPlane ) { return ComputeLeastSquaresPlaneFit<1>( pPoints, nNumPoints, pFitPlane ); } bool ComputeLeastSquaresPlaneFitZ( const Vector *pPoints, int nNumPoints, VPlane *pFitPlane ) { return ComputeLeastSquaresPlaneFit<2>( pPoints, nNumPoints, pFitPlane ); } float ComputeSquaredError( const Vector *pPoints, int nNumPoints, const VPlane *pFitPlane ) { float flSqrError = 0.0f; float flError = 0.0f; for ( int i = 0; i < nNumPoints; ++ i ) { float flDist = pFitPlane->DistTo( pPoints[i] ); flError += flDist; flSqrError += flDist * flDist; } return flSqrError; } ////////////////////////////////////////////////////////////////////////// // Private Implementation ////////////////////////////////////////////////////////////////////////// // Because this is not a least-squares orthogonal distance fit, an axis must be specified along which residuals are computed. // A traditional least-squares linear regression computes residuals along the y-axis and fits to a function of x, meaning that vertical lines cannot be properly fit. // Similarly, this algorithm cannot properly fit planes which lie along a plane parallel to the primary axis // // PRIMARY_AXIS // X = 0 // Y = 1 // Z = 2 template< int PRIMARY_AXIS > bool ComputeLeastSquaresPlaneFit( const Vector *pPoints, int nNumPoints, VPlane *pFitPlane ) { memset( pFitPlane, 0, sizeof( VPlane ) ); if ( nNumPoints < 3 ) { // We must have at least 3 points to fit a plane return false; } Vector vCentroid( 0, 0, 0 ); // averages: x-bar, y-bar, z-bar Vector vSquaredSums( 0, 0, 0 ); // x => x*x, y => y*y, z => z*z Vector vCrossSums( 0, 0, 0 ); // x => y*z, y => x*z, z >= x*y float flNumPoints = ( float )nNumPoints; for ( int i = 0; i < nNumPoints; ++ i ) { vCentroid += pPoints[i]; vSquaredSums += pPoints[i] * pPoints[i]; vCrossSums.x += pPoints[i].y * pPoints[i].z; vCrossSums.y += pPoints[i].x * pPoints[i].z; vCrossSums.z += pPoints[i].x * pPoints[i].y; } vCentroid /= ( float ) nNumPoints; if ( PRIMARY_AXIS == 0 ) { // swap X and Z swap( vCentroid.x, vCentroid.z ); swap( vSquaredSums.x, vSquaredSums.z ); swap( vCrossSums.x, vCrossSums.z ); } else if ( PRIMARY_AXIS == 1 ) { // Swap Y and Z swap( vCentroid.y, vCentroid.z ); swap( vSquaredSums.y, vSquaredSums.z ); swap( vCrossSums.y, vCrossSums.z ); } // Solve system of equations: // (example assumes primary axis is Z) // // A * ( sum( xi * xi ) - n * vCentroid.x^2 ) + B * ( sum( xi * yi ) - n * vCentroid.x * vCentroid.y ) - sum( xi * zi ) + n * vCentroid.x * vCentroid.z = 0 // A * ( sum( xi * yi ) - n * vCentroid.x * vCentroid.y ) + B * ( sum( yi * yi ) - n * vCentroid.y ^ 2 ) - sum( yi * zi ) + n * vCentroid.y * vCentroid.z = 0 // C = vCentroid.z - A * vCentroid.x - B * vCentroid.y // // where z = Ax + By + C // // Transform to: // [ m11 m12 ] [ A ] = [ c1 ] // [ m21 m22 ] [ B ] = [ c2 ] // // M * x = C // Take the inverse of M, post-multiply by C: // x = M_inverse * C float flM11 = vSquaredSums.x - flNumPoints * vCentroid.x * vCentroid.x; float flM12 = vCrossSums.z - flNumPoints * vCentroid.x * vCentroid.y; float flC1 = vCrossSums.y - flNumPoints * vCentroid.x * vCentroid.z; float flM21 = vCrossSums.z - flNumPoints * vCentroid.x * vCentroid.y; float flM22 = vSquaredSums.y - flNumPoints * vCentroid.y * vCentroid.y; float flC2 = vCrossSums.x - flNumPoints * vCentroid.y * vCentroid.z; float flDeterminant = flM11 * flM22 - flM12 * flM21; if ( fabsf( flDeterminant ) > DETERMINANT_EPSILON ) { float flInvDeterminant = 1.0f / flDeterminant; float flA = flInvDeterminant * ( flM22 * flC1 - flM12 * flC2 ); float flB = flInvDeterminant * ( -flM21 * flC1 + flM11 * flC2 ); float flC = vCentroid.z - flA * vCentroid.x - flB * vCentroid.y; pFitPlane->m_Normal = Vector( -flA, -flB, 1.0f ); float flScale = pFitPlane->m_Normal.NormalizeInPlace(); pFitPlane->m_Dist = flC * 1.0f / flScale; if ( PRIMARY_AXIS == 0 ) { // swap X and Z swap( pFitPlane->m_Normal.x, pFitPlane->m_Normal.z ); } else if ( PRIMARY_AXIS == 1 ) { // Swap Y and Z swap( pFitPlane->m_Normal.y, pFitPlane->m_Normal.z ); } return true; } // Bad determinant return false; } struct Complex_t { float r; float i; Complex_t() { } Complex_t( float flR, float flI ) : r( flR ), i( flI ) { } static Complex_t FromPolar( float flRadius, float flTheta ) { return Complex_t( flRadius * cosf( flTheta ), flRadius * sinf( flTheta ) ); } static Complex_t SquareRoot( float flValue ) { if ( flValue < 0.0f ) { return Complex_t( 0.0f, sqrtf( -flValue ) ); } else { return Complex_t( sqrtf( flValue ), 0.0f ); } } Complex_t operator+( const Complex_t &rhs ) const { return Complex_t( r + rhs.r, i + rhs.i ); } Complex_t operator-( const Complex_t &rhs ) const { return Complex_t( r - rhs.r, i - rhs.i ); } Complex_t operator*( const Complex_t &rhs ) const { return Complex_t( r * rhs.r - i * rhs.i, r * rhs.i + i * rhs.r ); } Complex_t operator*( float rhs ) const { return Complex_t( r * rhs, i * rhs ); } Complex_t operator/( float rhs ) const { return Complex_t( r / rhs, i / rhs ); } Complex_t CubeRoot() const { float flRadius = sqrtf( r * r + i * i ); float flTheta = atan2f( i, r ); //if ( flTheta < 0.0f ) flTheta += 2.0f * 3.14159f; // Demoivre's theorem for principal root return FromPolar( powf( flRadius, 1.0f / 3.0f ), flTheta / 3.0f ); } }; // [kutta] // This code is a work-in-progress; need to write code to robustly find an eigenvector given its eigenvalue. #if USE_ORTHOGONAL_LEAST_SQUARES template< int PRIMARY_AXIS = 0 > bool TryFindEigenvector( float flEigenvalue, const Vector *pMatrix, Vector *pEigenvector ) { const float flCoefficientEpsilon = 1e-3; const int nOtherRow1 = ( PRIMARY_AXIS + 1 ) % 3; const int nOtherRow2 = ( PRIMARY_AXIS + 2 ) % 3; bool bUseRow1 = fabsf( pMatrix[0][nOtherRow1] / flEigenvalue ) > flCoefficientEpsilon && fabsf( pMatrix[0][nOtherRow2] / flEigenvalue ) > flCoefficientEpsilon ); bool bUseRow2 = fabsf( pMatrix[1][nOtherRow1] / flEigenvalue ) > flCoefficientEpsilon && fabsf( pMatrix[1][nOtherRow2] / flEigenvalue ) > flCoefficientEpsilon ); bool bUseRow3 = fabsf( pMatrix[2][nOtherRow1] / flEigenvalue ) > flCoefficientEpsilon && fabsf( pMatrix[2][nOtherRow2] / flEigenvalue ) > flCoefficientEpsilon ); // ... } bool ComputeLeastSquaresOrthogonalPlaneFit( const Vector *pPoints, int nNumPoints, VPlane *pFitPlane ) { memset( pFitPlane, 0, sizeof( VPlane ) ); if ( nNumPoints < 3 ) { // We must have at least 3 points to fit a plane return false; } Vector vCentroid( 0, 0, 0 ); // averages: x-bar, y-bar, z-bar Vector vSquaredSums( 0, 0, 0 ); // x => x*x, y => y*y, z => z*z Vector vCrossSums( 0, 0, 0 ); // x => y*z, y => x*z, z >= x*y float flNumPoints = ( float )nNumPoints; for ( int i = 0; i < nNumPoints; ++ i ) { vCentroid += pPoints[i]; vSquaredSums += pPoints[i] * pPoints[i]; vCrossSums.x += pPoints[i].y * pPoints[i].z; vCrossSums.y += pPoints[i].x * pPoints[i].z; vCrossSums.z += pPoints[i].x * pPoints[i].y; } vCentroid /= ( float ) nNumPoints; // Re-center the squared and cross sums vSquaredSums.x -= flNumPoints * vCentroid.x * vCentroid.x; vSquaredSums.y -= flNumPoints * vCentroid.y * vCentroid.y; vSquaredSums.z -= flNumPoints * vCentroid.z * vCentroid.z; vCrossSums.x -= flNumPoints * vCentroid.y * vCentroid.z; vCrossSums.y -= flNumPoints * vCentroid.x * vCentroid.z; vCrossSums.z -= flNumPoints * vCentroid.x * vCentroid.y; // Best fit normal occurs at the minimum of the Rayleigh quotient: // // n' * M * n // ---------- // n' * n // // Where M is the covariance matrix. // M is computed from ( A' * A ) where A is a 3xN matrix of x/y/z residuals for each point in the data set. // Solve for eigenvalues & eigenvectors of 3x3 real symmetric covariance matrix. // The resulting characteristic polynormial equation is a cubic of the form: // x^3 + Ax^2 + Bx + C = 0 // // All roots of the equation and eigenvalues are positive real values; the lowest one corresponds to the eigenvalue which is the normal to the best fit plane. float flA = -( vSquaredSums.x + vSquaredSums.y + vSquaredSums.z ); float flB = vSquaredSums.x * vSquaredSums.z + vSquaredSums.x * vSquaredSums.y + vSquaredSums.y * vSquaredSums.z - vCrossSums.x * vCrossSums.x - vCrossSums.y * vCrossSums.y - vCrossSums.z * vCrossSums.z; float flC = -( vSquaredSums.x * vSquaredSums.y * vSquaredSums.z + 2.0f * vCrossSums.x * vCrossSums.y * vCrossSums.z ) + ( vSquaredSums.x * vCrossSums.x * vCrossSums.x + vSquaredSums.y * vCrossSums.y * vCrossSums.y + vSquaredSums.z * vCrossSums.z * vCrossSums.z ); // Using formula for roots of cubic polynomial, see http://en.wikipedia.org/wiki/Cubic_function float flM = 2.0f * flA * flA * flA - 9.0f * flA * flB + 27.0f * flC; float flK = flA * flA - 3.0f * flB; float flN = flM * flM - 4.0f * flK * flK * flK; Complex_t flSolutions[3]; const Complex_t omega1( -0.5f, 0.5f * sqrtf( 3.0f ) ); const Complex_t omega2( -0.5f, -0.5f * sqrtf( 3.0f ) ); Complex_t complexA = Complex_t( flA, 0.0f ); Complex_t complexM = Complex_t( flM, 0.0f ); Complex_t intermediateA = ( ( complexM + Complex_t::SquareRoot( flN ) ) / 2.0f ); Complex_t intermediateB = ( ( complexM - Complex_t::SquareRoot( flN ) ) / 2.0f ); Complex_t cubeA = intermediateA.CubeRoot(); Complex_t cubeB = intermediateB.CubeRoot(); Complex_t tempA = cubeA * cubeA * cubeA; Complex_t tempB = cubeB * cubeB * cubeB; flSolutions[0] = ( complexA + cubeA + cubeB ) * -1.0f / 3.0f; flSolutions[1] = ( complexA + ( omega2 * cubeA ) + ( omega1 * cubeB ) ) * -1.0f / 3.0f; flSolutions[2] = ( complexA + ( omega1 * cubeA ) + ( omega2 * cubeB ) ) * -1.0f / 3.0f; float flMinEigenvalue = MIN( flSolutions[0].r, flSolutions[1].r ); flMinEigenvalue = MIN( flMinEigenvalue, flSolutions[2].r ); // Subtract eigenvalue from the diagonal of the matrix to get a 3x3, real-symmetric, non-invertible matrix. // Pick 2 non-zero rows from this matrix and construct a system of 2 equations. return true; } #endif // USE_ORTHOGONAL_LEAST_SQUARES
34.414634
264
0.634833
DannyParker0001
e36ef2d2b03bbe5ec22bdb7bee6076697fd0f1b1
966
cpp
C++
widestring.cpp
jesse6548/peparser
7c304b332739a7cd874c57d5cbede9252b44987a
[ "MIT" ]
86
2016-04-15T21:50:39.000Z
2022-03-09T05:48:02.000Z
widestring.cpp
jesse6548/peparser
7c304b332739a7cd874c57d5cbede9252b44987a
[ "MIT" ]
2
2017-07-17T23:27:34.000Z
2019-05-31T22:28:03.000Z
widestring.cpp
jesse6548/peparser
7c304b332739a7cd874c57d5cbede9252b44987a
[ "MIT" ]
24
2016-04-15T22:00:07.000Z
2021-02-13T03:32:29.000Z
// Copyright (c) 2016 SMART Technologies. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "widestring.h" namespace peparser { template<> const char Literals<char>::colon = ':'; template<> const wchar_t Literals<wchar_t>::colon = L':'; template<> const char Literals<char>::null = '\0'; template<> const wchar_t Literals<wchar_t>::null = L'\0'; template<> const char* Literals<char>::month[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; template<> const wchar_t* Literals<wchar_t>::month[] = { L"Jan", L"Feb", L"Mar", L"Apr", L"May", L"Jun", L"Jul", L"Aug", L"Sep", L"Oct", L"Nov", L"Dec" }; template<> const char Literals<char>::slash = '/'; template<> const wchar_t Literals<wchar_t>::slash = L'/'; template<> const char Literals<char>::backslash = '\\'; template<> const wchar_t Literals<wchar_t>::backslash = L'\\'; }
42
155
0.652174
jesse6548
e37dbef058ac81324252e8686c4165d6c40d1b3c
800
hpp
C++
tui/window.hpp
sk2sat/libtui
9c338201de2dee59cef2bd8f8788e10659b9b4ee
[ "MIT" ]
2
2020-08-28T20:55:35.000Z
2021-03-06T21:17:42.000Z
tui/window.hpp
sk2sat/libtui
9c338201de2dee59cef2bd8f8788e10659b9b4ee
[ "MIT" ]
null
null
null
tui/window.hpp
sk2sat/libtui
9c338201de2dee59cef2bd8f8788e10659b9b4ee
[ "MIT" ]
1
2018-07-21T12:18:47.000Z
2018-07-21T12:18:47.000Z
#ifndef TUI_WINDOW_HPP_ #define TUI_WINDOW_HPP_ #include "screen.hpp" #include "color.hpp" namespace tui { class window { public: window() : col_bk(color::Black) { // とりあえずスクリーンと同じサイズ auto i = screen::get_info(); width = i.width; height= i.height; } window(size_t w, size_t h) : width(w), height(h), col_bk(color::Black) {} window(size_t w, size_t h, color::color4_t c) : width(w), height(h), col_bk(c) {} size_t get_width() const { return width; } size_t get_height()const { return height;} void set_width(size_t w){ width = w; } void set_height(size_t h){height= h; } void set_colback(const color::color4_t &c){ col_bk = c; } void draw(){ col_bk.set_back(); screen::clear(); } private: size_t width, height; color::color4_t col_bk; }; } #endif
21.621622
83
0.6575
sk2sat
e3803317d9816d4d9a606a15755a38b833e5b08f
2,470
hpp
C++
src/lib/spline/SplineGenerator.hpp
roboFiddle/7405M_TowerTakeover_Code
e16ffab17964ff61a25eac2074da78d0d7577caa
[ "MIT" ]
null
null
null
src/lib/spline/SplineGenerator.hpp
roboFiddle/7405M_TowerTakeover_Code
e16ffab17964ff61a25eac2074da78d0d7577caa
[ "MIT" ]
null
null
null
src/lib/spline/SplineGenerator.hpp
roboFiddle/7405M_TowerTakeover_Code
e16ffab17964ff61a25eac2074da78d0d7577caa
[ "MIT" ]
null
null
null
// // Created by alexweiss on 7/4/19. // #ifndef INC_7405M_CODE_SPLINEGENERATOR_HPP #define INC_7405M_CODE_SPLINEGENERATOR_HPP #include "Spline.hpp" #include "CubicHermiteSpline.hpp" #include "QuinticHermiteSpline.hpp" #include "../geometry/Pose2dWithCurvature.hpp" #include <vector> namespace spline { class SplineGenerator { private: static constexpr units::QLength kMaxDX = 2.0; static constexpr units::QLength kMaxDY = .05; static constexpr units::Angle kMaxDTheta = 0.1; // RADIANS!! static constexpr int kMinSampleSize = 1; template <class T> static std::vector<geometry::Pose2dWithCurvature> parameterizeSplinesTemplated(std::vector<T> *splines, units::QLength maxDx, units::QLength maxDy, units::Angle maxDTheta); public: static std::vector<geometry::Pose2dWithCurvature> parameterizeSpline(Spline *s, units::QLength maxDx, units::QLength maxDy, units::Angle maxDTheta, units::QTime t0, units::QTime t1); static std::vector<geometry::Pose2dWithCurvature> parameterizeSpline(Spline *s); static std::vector<geometry::Pose2dWithCurvature> parameterizeSpline(Spline *s, units::QLength maxDx, units::QLength maxDy, units::Angle maxDTheta); static std::vector<geometry::Pose2dWithCurvature> parameterizeSplines(std::vector<CubicHermiteSpline> *splines); static std::vector<geometry::Pose2dWithCurvature> parameterizeSplines(std::vector<CubicHermiteSpline> *splines, units::QLength maxDx, units::QLength maxDy, units::Angle maxDTheta); static std::vector<geometry::Pose2dWithCurvature> parameterizeSplines(std::vector<QuinticHermiteSpline> *splines); static std::vector<geometry::Pose2dWithCurvature> parameterizeSplines(std::vector<QuinticHermiteSpline> *splines, units::QLength maxDx, units::QLength maxDy, units::Angle maxDTheta); static void getSegmentArc(Spline *s, std::vector<geometry::Pose2dWithCurvature> *rv, units::QTime t0, units::QTime t1, units::QLength maxDx, units::QLength maxDy, units::Angle maxDTheta); }; } #endif //INC_7405M_CODE_SPLINEGENERATOR_HPP
49.4
148
0.640486
roboFiddle
be66ff22032f1aaecb9072748929b4ef5973a7df
588
cpp
C++
src/app.cpp
Neckrome/vectorFieldSurface
91afebadf9815e6a2dc658cdce82691fddd603ee
[ "MIT" ]
null
null
null
src/app.cpp
Neckrome/vectorFieldSurface
91afebadf9815e6a2dc658cdce82691fddd603ee
[ "MIT" ]
null
null
null
src/app.cpp
Neckrome/vectorFieldSurface
91afebadf9815e6a2dc658cdce82691fddd603ee
[ "MIT" ]
null
null
null
#include "app.hpp" #include "geometry/utils.hpp" #include "geometry/plane.hpp" #include "test.hpp" #include "optim/deformingMesh.hpp" #include <functional> #include "geometrycentral/surface/manifold_surface_mesh.h" #include "geometrycentral/surface/meshio.h" #include "geometrycentral/surface/vertex_position_geometry.h" #include "polyscope/polyscope.h" #include "polyscope/surface_mesh.h" #include "polyscope/point_cloud.h" App::App() { } void App::run() { std::cout << "Running..." << std::endl; Test test = Test(); test.test1(); }
20.275862
62
0.680272
Neckrome
be6bd61fac3d8645d0fefd06bef1360b2e31d4be
650
hpp
C++
tests/helper.hpp
marwage/alzheimer
b58688ea91f9b2ca4ae5457858b0fcc2a6e3e041
[ "CC0-1.0" ]
null
null
null
tests/helper.hpp
marwage/alzheimer
b58688ea91f9b2ca4ae5457858b0fcc2a6e3e041
[ "CC0-1.0" ]
null
null
null
tests/helper.hpp
marwage/alzheimer
b58688ea91f9b2ca4ae5457858b0fcc2a6e3e041
[ "CC0-1.0" ]
null
null
null
// Copyright 2020 Marcel Wagenländer #ifndef HELPER_HPP #define HELPER_HPP #include "sage_linear.hpp" #include "tensors.hpp" void save_params(std::vector<Matrix<float> *> parameters); void save_grads(SageLinearGradients *gradients, std::vector<Matrix<float> *> weight_gradients); void save_grads(SageLinearGradientsChunked *gradients, std::vector<Matrix<float> *> weight_gradients, long num_nodes); int read_return_value(std::string path); void write_value(int value, std::string path); int num_equal_rows(Matrix<float> A, Matrix<float> B); int compare_mat(Matrix<float> *mat_a, Matrix<float> *mat_b, std::string name); #endif//HELPER_HPP
26
118
0.776923
marwage
be6e7b4a381fde523f96db80dcaa8714550ad249
6,166
cpp
C++
z80emu/fuzix-arm/src/main.cpp
Paolo-Maffei/retro
bf30cec3d82672eb2805392e77f3b21705129fc0
[ "Unlicense" ]
1
2022-02-12T19:35:39.000Z
2022-02-12T19:35:39.000Z
z80emu/fuzix-arm/src/main.cpp
Paolo-Maffei/retro
bf30cec3d82672eb2805392e77f3b21705129fc0
[ "Unlicense" ]
null
null
null
z80emu/fuzix-arm/src/main.cpp
Paolo-Maffei/retro
bf30cec3d82672eb2805392e77f3b21705129fc0
[ "Unlicense" ]
null
null
null
#include <jee.h> #include <jee/spi-sdcard.h> #include <string.h> #include "cpmdate.h" extern "C" { #include "context.h" #include "z80emu.h" #include "macros.h" } UartBufDev< PinA<9>, PinA<10> > console; int printf(const char* fmt, ...) { va_list ap; va_start(ap, fmt); veprintf(console.putc, fmt, ap); va_end(ap); return 0; } PinB<9> led; RTC rtc; SpiGpio< PinD<2>, PinC<8>, PinC<12>, PinC<11> > spi; SdCard< decltype(spi) > sd; Context context; // max: 3x60K+4K, 3x48K+16K, 4x32K+32K, 8x16K+48K, 16x8K+56K static uint8_t bankMem [120*1024]; // additional memory banks on F407 static void setBankSplit (uint8_t page) { context.split = mainMem + (page << 8); memset(context.offset, 0, sizeof context.offset); #if NBANKS > 1 uint8_t* base = bankMem; for (int i = 1; i < NBANKS; ++i) { uint8_t* limit = base + (page << 8); if (limit > bankMem + sizeof bankMem) break; // no more complete banks left context.offset[i] = base - mainMem; base = limit; } #endif } void systemCall (Context* z, int req, int pc) { Z80_STATE* state = &(z->state); #if 0 if (req > 3) printf("\treq %d AF %04x BC %04x DE %04x HL %04x SP %04x @ %d:%04x\n", req, AF, BC, DE, HL, SP, context.bank, pc); #endif switch (req) { case 0: // coninst A = console.readable() ? 0xFF : 0x00; break; case 1: // conin A = console.getc(); break; case 2: // conout console.putc(C); break; case 3: // constr for (uint16_t i = DE; *mapMem(&context, i) != 0; i++) console.putc(*mapMem(&context, i)); break; case 4: // read/write // ld a,(sekdrv) // ld b,1 ; +128 for write // ld de,(seksat) // ld hl,(dmaadr) // in a,(4) // ret //printf("AF %04X BC %04X DE %04X HL %04X\n", AF, BC, DE, HL); { bool out = (B & 0x80) != 0; #if 0 uint8_t sec = DE, trk = DE >> 8, dsk = A, cnt = B & 0x7F; uint32_t pos = 2048*dsk + 26*trk + sec; // no skewing for (int i = 0; i < cnt; ++i) { void* mem = mapMem(&context, HL + 128*i); if (out) disk_write(pos + i, mem, 128); else disk_read(pos + i, mem, 128); } #else uint8_t cnt = B & 0x7F; uint32_t pos = 16384*A + DE + 2048; // no skewing for (int i = 0; i < cnt; ++i) { void* mem = mapMem(&context, HL + 512*i); #if 0 printf("HD%d wr %d mem %d:0x%x pos %d\n", A, out, context.bank, HL + 512*i, pos + i); #endif if (out) sd.write512(pos + i, mem); else sd.read512(pos + i, mem); } #endif } A = 0; break; case 5: { // time get/set if (C == 0) { #if 0 RTC::DateTime dt = rtc.get(); //printf("mdy %02d/%02d/20%02d %02d:%02d:%02d (%d ms)\n", // dt.mo, dt.dy, dt.yr, dt.hh, dt.mm, dt.ss, ticks); uint8_t* ptr = mapMem(&context, HL); int t = date2dr(dt.yr, dt.mo, dt.dy); ptr[0] = t; ptr[1] = t>>8; ptr[2] = dt.hh + 6*(dt.hh/10); // hours, to BCD ptr[3] = dt.mm + 6*(dt.mm/10); // minutes, to BCD ptr[4] = dt.ss + 6*(dt.ss/10); // seconcds, to BCD } else { RTC::DateTime dt; uint8_t* ptr = mapMem(&context, HL); // TODO set clock date & time dr2date(*(uint16_t*) ptr, &dt); dt.hh = ptr[2] - 6*(ptr[2]>>4); // hours, from BCD dt.mm = ptr[3] - 6*(ptr[3]>>4); // minutes, from BCD dt.ss = ptr[4] - 6*(ptr[4]>>4); // seconds, from BCD rtc.set(dt); #endif } break; } case 6: // set banked memory limit setBankSplit(A); break; case 7: { // select bank and return previous setting uint8_t prevBank = context.bank; context.bank = A; A = prevBank; break; } case 8: { // for use in xmove, inter-bank copying uint8_t *src = mainMem + DE, *dst = mainMem + HL; // never map above the split, i.e. in the common area if (dst < context.split) dst += context.offset[(A>>4) % NBANKS]; if (src < context.split) src += context.offset[A % NBANKS]; // TODO careful, this won't work across the split! memcpy(dst, src, BC); DE += BC; HL += BC; break; } default: printf("syscall %d @ %04x ?\n", req, pc); while (1) {} } } int main() { console.init(); enableSysTick(); led.mode(Pinmode::out); rtc.init(); printf("\nsd init: "); spi.init(); if (sd.init()) printf("detected, sdhc=%d\n", sd.sdhc); // switch to full speed, now that the SD card has been inited wait_ms(10); // let serial output drain console.baud(115200, fullSpeedClock()/2); const uint16_t origin = 0x0100; #if 0 // emulated rom bootstrap, loads first disk sector to 0x0000 disk.readSector(0, mapMem(&context, 0x0000)); #else printf("booting: "); for (int i = 0; i < 127; ++i) { // read 63.5K into RAM console.putc('.'); sd.read512(1 + i, mapMem(&context, origin + 512*i)); } printf("\n"); #endif // start emulating Z80Reset(&context.state); context.state.pc = origin; context.done = 0; do { Z80Emulate(&context.state, 2000000, &context); led.toggle(); } while (!context.done); led = 1; // turn LED off (inverted logic) while (true) {} }
30.676617
79
0.46432
Paolo-Maffei
be6f02055f535eaadbe98993a1ac00def5164452
3,285
hpp
C++
include/CobraModelParser/MatlabV5/ArrayFlags.hpp
qacwnfq/CobraModelParser
9e03ff6e9f05e4a971b39a85360494925c72dbeb
[ "MIT" ]
null
null
null
include/CobraModelParser/MatlabV5/ArrayFlags.hpp
qacwnfq/CobraModelParser
9e03ff6e9f05e4a971b39a85360494925c72dbeb
[ "MIT" ]
null
null
null
include/CobraModelParser/MatlabV5/ArrayFlags.hpp
qacwnfq/CobraModelParser
9e03ff6e9f05e4a971b39a85360494925c72dbeb
[ "MIT" ]
null
null
null
#include <utility> #ifndef COBRAMODELPARSER_MATLABV5_ARRAYFLAGS_HPP #define COBRAMODELPARSER_MATLABV5_ARRAYFLAGS_HPP #include <ostream> #include <CobraModelParser/ByteParser.hpp> #include "CobraModelParser/ByteQueue.hpp" #include "CobraModelParser/MatlabV5/ArrayType.hpp" #include "CobraModelParser/MatlabV5/ArrayTypeTable.hpp" #include "CobraModelParser/MatlabV5/TagParser.hpp" namespace CobraModelParser { namespace MatlabV5 { class ArrayFlags { public: static ArrayFlags fromByteQueue(ByteQueue &byteQueue, const ByteParser &byteParser, const TagParser &tagParser) { Tag tag = tagParser.parseTag(byteQueue); if (tag.getType() != DataTypeTable::lookUp(6)) { throw UnexpectedDataTypeException(DataTypeTable::lookUp(6).getSymbol(), tag.getType().getSymbol()); } if (tag.getNumberOfBytes() != 8) { throw UnexpectedSizeException(8, tag.getNumberOfBytes()); } std::vector<Byte> byteBlock = byteQueue.popByteBlock(); if(byteParser.getEndianIndicator() == "MI") { std::reverse(byteBlock.begin(), byteBlock.end()); } Byte flags = byteBlock[1]; bool complex = byteParser.getBitFromByte(flags, 4); bool global = byteParser.getBitFromByte(flags, 5); bool logical = byteParser.getBitFromByte(flags, 6); const auto arrayTypeLookUp = byteParser.parseIntegerType<size_t>( std::vector<Byte>(byteBlock.begin(), byteBlock.begin() + 1)); const ArrayType &arrayType = ArrayTypeTable::lookUp(arrayTypeLookUp); return ArrayFlags(tag, arrayType, complex, global, logical); } ArrayFlags() = default; ArrayFlags( Tag tag, ArrayType arrayType, bool complex, bool global, bool logical) : tag(std::move(tag)), arrayType(std::move(arrayType)), complex(complex), global(global), logical(logical) {} const Tag &getTag() const { return tag; } friend std::ostream &operator<<(std::ostream &os, const ArrayFlags &flags) { os << "arrayType: " << flags.arrayType << " complex: " << flags.complex << " global: " << flags.global << " logical: " << flags.logical; return os; } const ArrayType &getArrayType() const { return arrayType; } bool isComplex() const { return complex; } bool isGlobal() const { return global; } bool isLogical() const { return logical; } private: Tag tag; ArrayType arrayType; bool complex; bool global; bool logical; }; } } #endif //COBRAMODELPARSER_MATLABV5_ARRAYFLAGS_HPP
34.578947
119
0.526941
qacwnfq
be75a963db59fccca4dfef00231f29ab04f88b18
8,695
cpp
C++
Source/UI/Components/VirtualKeyboard/KeyboardViewport.cpp
vsicurella/SuperVirtualKeyboard
b59549281ea16b70f94b3136fe0b9a1f9fc355e2
[ "Unlicense" ]
22
2019-06-26T12:41:49.000Z
2022-02-11T14:48:18.000Z
Source/UI/Components/VirtualKeyboard/KeyboardViewport.cpp
vsicurella/SuperVirtualKeyboard
b59549281ea16b70f94b3136fe0b9a1f9fc355e2
[ "Unlicense" ]
18
2019-06-22T21:49:21.000Z
2021-05-15T01:33:57.000Z
Source/UI/Components/VirtualKeyboard/KeyboardViewport.cpp
vsicurella/SuperVirtualKeyboard
b59549281ea16b70f94b3136fe0b9a1f9fc355e2
[ "Unlicense" ]
null
null
null
/* ============================================================================== KeyboardViewPort.cpp Created: 31 Oct 2019 2:41:37pm Author: Vincenzo Sicurella ============================================================================== */ #include "KeyboardViewport.h" KeyboardViewport::KeyboardViewport(VirtualKeyboard::Keyboard* keyboardIn, const String& nameIn, int scrollingModeIn, int scrollingStyleIn) : Viewport(nameIn) { stepRightLarge.reset(new ImageButton()); stepRightLarge->addListener(this); addChildComponent(stepRightLarge.get()); stepRightSmall.reset(new ImageButton()); stepRightSmall->addListener(this); addChildComponent(stepRightSmall.get()); stepLeftLarge.reset(new ImageButton()); stepLeftLarge->addListener(this); addChildComponent(stepLeftLarge.get()); stepLeftSmall.reset(new ImageButton()); stepLeftSmall->addListener(this); addChildComponent(stepLeftSmall.get()); setScrollingMode(scrollingModeIn); setScrollingStyle(scrollingStyleIn); keyboard = keyboardIn; setViewedComponent(keyboard); } void KeyboardViewport::viewedComponentChanged(Component* newComponent) { keyboard = dynamic_cast<Keyboard*>(newComponent); resizeKeyboard(); } void KeyboardViewport::visibleAreaChanged(const Rectangle<int>&) { if (keyboard->getHeight() > getMaximumVisibleHeight()) { resizeKeyboard(); } } int KeyboardViewport::getStepSmall() { return stepSmall; } int KeyboardViewport::getStepLarge() { return stepLarge; } int KeyboardViewport::getButtonWidth() { if (isShowingButtons()) return buttonWidth; return 0; } bool KeyboardViewport::isShowingButtons() { return scrollingModeSelected > 1; } float KeyboardViewport::getCenterKeyProportion() const { int center = getViewPositionX() + getMaximumVisibleWidth() / 2; Key* key = keyboard->getKeyFromPosition({ center, 0 }); if (key) return key->keyNumber + (center % key->getWidth()) / (float)key->getWidth(); return -1; } void KeyboardViewport::setButtonWidth(int widthIn) { buttonWidth = widthIn; } void KeyboardViewport::setScrollingMode(int modeIdIn) { scrollingModeSelected = modeIdIn; if (scrollingModeSelected > 1) { stepRightLarge->setVisible(true); stepRightSmall->setVisible(true); stepLeftLarge->setVisible(true); stepLeftSmall->setVisible(true); } else { stepRightLarge->setVisible(false); stepRightSmall->setVisible(false); stepLeftLarge->setVisible(false); stepLeftSmall->setVisible(false); } } void KeyboardViewport::setScrollingStyle(int styleIdIn) { scrollingStyleSelected = styleIdIn; // do stuff } void KeyboardViewport::stepSmallForward() { Viewport::setViewPosition(getViewPositionX() + stepSmall, getViewPositionY()); } void KeyboardViewport::stepSmallBackward() { Viewport::setViewPosition(getViewPositionX() - stepSmall, getViewPositionY()); } void KeyboardViewport::stepLargeForward() { Viewport::setViewPosition(getViewPositionX() + stepLarge, getViewPositionY()); } void KeyboardViewport::stepLargeBackward() { Viewport::setViewPosition(getViewPositionX() - stepLarge, getViewPositionY()); } void KeyboardViewport::centerOnKey(int keyNumberIn) { Key* key = keyboard->getKey(keyNumberIn); if (key) { int position = key->getBoundsInParent().getX() - getMaximumVisibleWidth() / 2; Viewport::setViewPosition(position, getViewPositionY()); } } void KeyboardViewport::centerOnKey(float keyNumberProportionIn) { Key* key = keyboard->getKey((int)keyNumberProportionIn); if (key) { int proportion = (keyNumberProportionIn - (int)keyNumberProportionIn) * key->getWidth(); int position = key->getBoundsInParent().getX() + proportion - getMaximumVisibleWidth() / 2; Viewport::setViewPosition(position, getViewPositionY()); } } int KeyboardViewport::drawAngleBracket(Graphics& g, bool isRightPointing, int sideLength, int xCenter, int yCenter, float thickness) { float halfSide = sideLength / 2.0f; float altitude = sqrtf(powf(sideLength, 2.0f) - powf(halfSide, 2.0f)); float halfAltitude = altitude / 2.0f; int x1 = xCenter - halfAltitude; int x2 = xCenter + halfAltitude; int y1 = yCenter + halfSide; int y2 = yCenter - halfSide; if (isRightPointing) { g.drawLine(Line<float>(x1, y1, x2, yCenter), thickness); g.drawLine(Line<float>(x1, y2, x2, yCenter), thickness); } else { g.drawLine(Line<float>(x2, y1, x1, yCenter), thickness); g.drawLine(Line<float>(x2, y2, x1, yCenter), thickness); } return altitude; } void KeyboardViewport::redrawButtons(int heightIn) { Image singleBracketImage = Image(Image::PixelFormat::ARGB, buttonWidth, heightIn, false); Image doubleBracketImage = singleBracketImage.createCopy(); Image singleBracketFlipped = singleBracketImage.createCopy(); Image doubleBracketFlipped = singleBracketImage.createCopy(); Colour buttonColour = Colours::steelblue.darker().withSaturation(0.33f); Colour bracketColour = Colours::black; Colour mouseOverColor = Colours::lightgrey.withAlpha(0.33f); Colour mouseClickColor = Colours::darkgrey.withAlpha(0.75f); int sideLength = round(buttonWidth * 0.33f); int altitude; int xCenter = buttonWidth / 2; int yCenter = getHeight() / 4; int doubleSeparation = 3; Graphics g1(singleBracketImage); g1.setColour(buttonColour); g1.fillAll(); g1.setColour(bracketColour); altitude = drawAngleBracket(g1, true, sideLength, xCenter, yCenter, 1); Graphics g2(doubleBracketImage); g2.setColour(buttonColour); g2.fillAll(); g2.setColour(bracketColour); drawAngleBracket(g2, true, sideLength, xCenter - doubleSeparation, yCenter, 1); drawAngleBracket(g2, true, sideLength, xCenter + doubleSeparation, yCenter, 1); Graphics g3(singleBracketFlipped); g3.setColour(buttonColour); g3.fillAll(); g3.setColour(bracketColour); altitude = drawAngleBracket(g3, false, sideLength, xCenter, yCenter, 1); Graphics g4(doubleBracketFlipped); g4.setColour(buttonColour); g4.fillAll(); g4.setColour(bracketColour); drawAngleBracket(g4, false, sideLength, xCenter - doubleSeparation, yCenter, 1); drawAngleBracket(g4, false, sideLength, xCenter + doubleSeparation, yCenter, 1); stepLeftSmall->setImages(false, false, false, singleBracketImage, 1.0f, Colours::transparentBlack, singleBracketImage, 1.0f, mouseOverColor, singleBracketImage, 1.0f, mouseClickColor); stepLeftLarge->setImages(false, false, false, doubleBracketImage, 1.0f, Colours::transparentBlack, doubleBracketImage, 1.0f, mouseOverColor, doubleBracketImage, 1.0f, mouseClickColor); stepRightSmall->setImages(false, false, false, singleBracketFlipped, 1.0f, Colours::transparentBlack, singleBracketFlipped, 1.0f, mouseOverColor, singleBracketFlipped, 1.0f, mouseClickColor); stepRightLarge->setImages(false, false, false, doubleBracketFlipped, 1.0f, Colours::transparentBlack, doubleBracketFlipped, 1.0f, mouseOverColor, doubleBracketFlipped, 1.0f, mouseClickColor); } void KeyboardViewport::resizeKeyboard() { int heightWithScrollbar = getHeight() - getScrollBarThickness(); keyboard->setBounds(0, 0, keyboard->getPianoWidth(heightWithScrollbar), heightWithScrollbar); } void KeyboardViewport::resized() { Viewport::resized(); stepSmall = keyboard->getWidth() / keyboard->getKeysByOrder(0).size(); stepLarge = stepSmall * keyboard->getModeSize(); // draw step buttons if (scrollingModeSelected > 1) { int halfHeight = round(getMaximumVisibleHeight() / 2.0f); redrawButtons(halfHeight); stepRightLarge->setBounds(0, 0, buttonWidth, halfHeight); stepRightSmall->setBounds(0, halfHeight, buttonWidth, halfHeight); stepLeftLarge->setBounds(getWidth() - buttonWidth, 0, buttonWidth, halfHeight); stepLeftSmall->setBounds(getWidth() - buttonWidth, halfHeight, buttonWidth, halfHeight); } } void KeyboardViewport::buttonClicked(Button* button) { if (button == stepRightLarge.get()) { stepLargeBackward(); } else if (button == stepRightSmall.get()) { stepSmallBackward(); } else if (button == stepLeftLarge.get()) { stepLargeForward(); } else if (button == stepLeftSmall.get()) { stepSmallForward(); } }
29.276094
138
0.686371
vsicurella
be7adbbff25a909c45d8b427fa5efe11574dc57f
352
hpp
C++
example/openglGame.hpp
Withbini/game-engine
40c28e994c00e4acd2ed41720eb24f6754031382
[ "BSD-2-Clause" ]
null
null
null
example/openglGame.hpp
Withbini/game-engine
40c28e994c00e4acd2ed41720eb24f6754031382
[ "BSD-2-Clause" ]
null
null
null
example/openglGame.hpp
Withbini/game-engine
40c28e994c00e4acd2ed41720eb24f6754031382
[ "BSD-2-Clause" ]
null
null
null
#pragma once #include "Game.hpp" #include "Shader.hpp" #include "VertexArray.hpp" #include "Renderer.hpp" class openglGame : public Game { public: openglGame(); ~openglGame() override; bool Initialize() override; void LoadData() override; private: class Ship2* mShip; VertexArray* mSpriteVerts; int mSpriteFrags; Shader* mSpriteShader; };
14.666667
28
0.735795
Withbini
be816982618a5ba2577c6c5bfe30589cfb890641
951
cc
C++
benchmark/supermalloc/src/footprint.cc
jneuhauser/rpmalloc-benchmark
f492744530a349b9b6c831305b25aec0ec5a6a5b
[ "Unlicense" ]
287
2015-05-13T22:37:29.000Z
2022-03-31T01:56:53.000Z
benchmark/supermalloc/src/footprint.cc
jneuhauser/rpmalloc-benchmark
f492744530a349b9b6c831305b25aec0ec5a6a5b
[ "Unlicense" ]
50
2015-06-08T02:13:25.000Z
2019-07-17T22:41:02.000Z
benchmark/supermalloc/src/footprint.cc
jneuhauser/rpmalloc-benchmark
f492744530a349b9b6c831305b25aec0ec5a6a5b
[ "Unlicense" ]
31
2015-07-24T10:20:49.000Z
2022-01-17T18:30:51.000Z
/* Maintain a count of the footprint. */ #include <sched.h> #include "malloc_internal.h" #include "atomically.h" static const int processor_number_limit = 128; // should be enough for now. static uint64_t partitioned_footprint[processor_number_limit]; struct processor_id { int cpuid; int count; } __attribute__((aligned(64))); static const int prid_cache_time = 128; static __thread processor_id prid; static inline void check_cpuid(void) { if (prid.count++ % prid_cache_time == 0) { prid.cpuid = sched_getcpu() % processor_number_limit; } } void add_to_footprint(int64_t delta) { check_cpuid(); __sync_fetch_and_add(&partitioned_footprint[prid.cpuid], delta); } int64_t get_footprint(void) { int64_t sum = 0; for (int i = 0; i < processor_number_limit; i++) { sum += partitioned_footprint[i]; //sum += atomic_load(&partitioned_footprint[i]); // don't really care if we slightly stale answers. } return sum; }
25.026316
103
0.725552
jneuhauser
be92326c9c6b7a7a87ad2680ad57ae4d2c334cb7
571
cpp
C++
slsv_cnc/tests-cpp/Tests.cpp
command-paul/slsv-master
a703bfaa8031e18e3fb74d3f1f2f4544c75a73ef
[ "BSD-3-Clause" ]
null
null
null
slsv_cnc/tests-cpp/Tests.cpp
command-paul/slsv-master
a703bfaa8031e18e3fb74d3f1f2f4544c75a73ef
[ "BSD-3-Clause" ]
null
null
null
slsv_cnc/tests-cpp/Tests.cpp
command-paul/slsv-master
a703bfaa8031e18e3fb74d3f1f2f4544c75a73ef
[ "BSD-3-Clause" ]
1
2021-01-29T14:29:52.000Z
2021-01-29T14:29:52.000Z
#include "../src/TestInstance.hpp" #include <iostream> // Append all of these to a Vector of test functions. bool test_spike_interface(){ return true; } bool test_state(){ riscv* a = new riscv; (*a).addHART(); (*a).addMemory(); (*a).addNHSV(); std::cout << (*a).HART_Vec[0].GPR[0] << std::endl; delete a; return true; } bool test_Hart(){ return true; } bool test_memory(){ return true; } bool test_NHSV(){ return true; } bool test_Device(){ return true; } int main(){ bool test_result = false; test_result = test_Device(); return (int)test_result; }
14.641026
53
0.661996
command-paul
be9497a88db7a28553fb2fac51b78aa15d4e7fd6
5,348
hpp
C++
third_party/boost/simd/arch/x86/xop/simd/function/is_equal.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
6
2018-02-25T22:23:33.000Z
2021-01-15T15:13:12.000Z
third_party/boost/simd/arch/x86/xop/simd/function/is_equal.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
third_party/boost/simd/arch/x86/xop/simd/function/is_equal.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
7
2017-12-12T12:36:31.000Z
2020-02-10T14:27:07.000Z
//================================================================================================== /** Copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) **/ //================================================================================================== #ifndef BOOST_SIMD_ARCH_X86_XOP_SIMD_FUNCTION_IS_EQUAL_HPP_INCLUDED #define BOOST_SIMD_ARCH_X86_XOP_SIMD_FUNCTION_IS_EQUAL_HPP_INCLUDED #include <boost/simd/detail/overload.hpp> #include <boost/simd/meta/as_logical.hpp> #if !defined(_MM_PCOMCTRL_EQ) #define _MM_PCOMCTRL_EQ 4 #define BOOST_SIMD_MISSING_MM_PCOMCTRL_EQ #endif #if BOOST_HW_SIMD_X86_AMD_XOP namespace boost { namespace simd { namespace ext { namespace bd = boost::dispatch; namespace bs = boost::simd; BOOST_DISPATCH_OVERLOAD ( is_equal_ , (typename A0) , bs::avx_ , bs::pack_<bd::int8_<A0>, bs::sse_> , bs::pack_<bd::int8_<A0>, bs::sse_> ) { BOOST_FORCEINLINE bs::as_logical_t<A0> operator()(const A0& a0, const A0& a1) const BOOST_NOEXCEPT { #if defined(__clang__) return _mm_com_epi8(a0,a1,_MM_PCOMCTRL_EQ); #else return _mm_comeq_epi8(a0,a1); #endif } }; BOOST_DISPATCH_OVERLOAD ( is_equal_ , (typename A0) , bs::avx_ , bs::pack_<bd::int16_<A0>, bs::sse_> , bs::pack_<bd::int16_<A0>, bs::sse_> ) { BOOST_FORCEINLINE bs::as_logical_t<A0> operator()(const A0& a0, const A0& a1) const BOOST_NOEXCEPT { #if defined(__clang__) return _mm_com_epi16(a0,a1,_MM_PCOMCTRL_EQ); #else return _mm_comeq_epi16(a0,a1); #endif } }; BOOST_DISPATCH_OVERLOAD ( is_equal_ , (typename A0) , bs::avx_ , bs::pack_<bd::int32_<A0>, bs::sse_> , bs::pack_<bd::int32_<A0>, bs::sse_> ) { BOOST_FORCEINLINE bs::as_logical_t<A0> operator()(const A0& a0, const A0& a1) const BOOST_NOEXCEPT { #if defined(__clang__) return _mm_com_epi32(a0,a1,_MM_PCOMCTRL_EQ); #else return _mm_comeq_epi32(a0,a1); #endif } }; BOOST_DISPATCH_OVERLOAD ( is_equal_ , (typename A0) , bs::avx_ , bs::pack_<bd::int64_<A0>, bs::sse_> , bs::pack_<bd::int64_<A0>, bs::sse_> ) { BOOST_FORCEINLINE bs::as_logical_t<A0> operator()(const A0& a0, const A0& a1) const BOOST_NOEXCEPT { #if defined(__clang__) return _mm_com_epi64(a0,a1,_MM_PCOMCTRL_EQ); #else return _mm_comeq_epi64(a0,a1); #endif } }; BOOST_DISPATCH_OVERLOAD ( is_equal_ , (typename A0) , bs::avx_ , bs::pack_<bd::uint8_<A0>, bs::sse_> , bs::pack_<bd::uint8_<A0>, bs::sse_> ) { BOOST_FORCEINLINE bs::as_logical_t<A0> operator()(const A0& a0, const A0& a1) const BOOST_NOEXCEPT { #if defined(__clang__) return _mm_com_epu8(a0,a1,_MM_PCOMCTRL_EQ); #else return _mm_comeq_epu8(a0,a1); #endif } }; BOOST_DISPATCH_OVERLOAD ( is_equal_ , (typename A0) , bs::avx_ , bs::pack_<bd::uint16_<A0>, bs::sse_> , bs::pack_<bd::uint16_<A0>, bs::sse_> ) { BOOST_FORCEINLINE bs::as_logical_t<A0> operator()(const A0& a0, const A0& a1) const BOOST_NOEXCEPT { #if defined(__clang__) return _mm_com_epu16(a0,a1,_MM_PCOMCTRL_EQ); #else return _mm_comeq_epu16(a0,a1); #endif } }; BOOST_DISPATCH_OVERLOAD ( is_equal_ , (typename A0) , bs::avx_ , bs::pack_<bd::uint32_<A0>, bs::sse_> , bs::pack_<bd::uint32_<A0>, bs::sse_> ) { BOOST_FORCEINLINE bs::as_logical_t<A0> operator()(const A0& a0, const A0& a1) const BOOST_NOEXCEPT { #if defined(__clang__) return _mm_com_epu32(a0,a1,_MM_PCOMCTRL_EQ); #else return _mm_comeq_epu32(a0,a1); #endif } }; BOOST_DISPATCH_OVERLOAD ( is_equal_ , (typename A0) , bs::avx_ , bs::pack_<bd::uint64_<A0>, bs::sse_> , bs::pack_<bd::uint64_<A0>, bs::sse_> ) { BOOST_FORCEINLINE bs::as_logical_t<A0> operator()(const A0& a0, const A0& a1) const BOOST_NOEXCEPT { #if defined(__clang__) return _mm_com_epu64(a0,a1,_MM_PCOMCTRL_EQ); #else return _mm_comeq_epu64(a0,a1); #endif } }; } } } #endif #if defined(BOOST_SIMD_MISSING_MM_PCOMCTRL_EQ) #undef _MM_PCOMCTRL_EQ #undef BOOST_SIMD_MISSING_MM_PCOMCTRL_EQ #endif #endif
30.044944
100
0.512528
SylvainCorlay
be99a543c56d95b3d0608df21a72cccb5f6e57c2
2,353
cpp
C++
gwen/UnitTest/ListBox.cpp
Oipo/GWork
3dd70c090bf8708dd3e7b9cfbcb67163bb7166db
[ "MIT" ]
null
null
null
gwen/UnitTest/ListBox.cpp
Oipo/GWork
3dd70c090bf8708dd3e7b9cfbcb67163bb7166db
[ "MIT" ]
null
null
null
gwen/UnitTest/ListBox.cpp
Oipo/GWork
3dd70c090bf8708dd3e7b9cfbcb67163bb7166db
[ "MIT" ]
null
null
null
#include "Gwen/UnitTest/UnitTest.h" #include "Gwen/Controls/ListBox.h" using namespace Gwen; class ListBox : public GUnit { public: GWEN_CONTROL_INLINE(ListBox, GUnit) { { Gwen::Controls::ListBox* ctrl = new Gwen::Controls::ListBox(this); ctrl->SetBounds(10, 10, 100, 200); ctrl->AddItem("First"); ctrl->AddItem("Blue"); ctrl->AddItem("Yellow"); ctrl->AddItem("Orange"); ctrl->AddItem("Brown"); ctrl->AddItem("Black"); ctrl->AddItem("Green"); ctrl->AddItem("Dog"); ctrl->AddItem("Cat Blue"); ctrl->AddItem("Shoes"); ctrl->AddItem("Shirts"); ctrl->AddItem("Chair"); ctrl->AddItem("Last"); ctrl->SelectByString("Bl*", true); ctrl->SetAllowMultiSelect(true); ctrl->SetKeyboardInputEnabled(true); ctrl->onRowSelected.Add(this, &ThisClass::RowSelected); } { Gwen::Controls::ListBox* ctrl = new Gwen::Controls::ListBox(this); ctrl->SetBounds(120, 10, 200, 200); ctrl->SetColumnCount(3); ctrl->SetAllowMultiSelect(true); ctrl->onRowSelected.Add(this, &ThisClass::RowSelected); { Gwen::Controls::Layout::TableRow* pRow = ctrl->AddItem("Baked Beans"); pRow->SetCellText(1, "Heinz"); pRow->SetCellText(2, "£3.50"); } { Gwen::Controls::Layout::TableRow* pRow = ctrl->AddItem("Bananas"); pRow->SetCellText(1, "Trees"); pRow->SetCellText(2, "$1.27"); } { Gwen::Controls::Layout::TableRow* pRow = ctrl->AddItem("Chicken"); pRow->SetCellText(1, Gwen::Utility::Narrow(L"\u5355\u5143\u6D4B\u8BD5")); pRow->SetCellText(2, Gwen::Utility::Narrow(L"\u20AC8.95")); } } } void RowSelected(Gwen::Controls::Base* pControl) { Gwen::Controls::ListBox* ctrl = (Gwen::Controls::ListBox*)pControl; UnitPrint(Utility::Format("Listbox Item Selected: %s", ctrl->GetSelectedRow()->GetText(0).c_str())); } Gwen::Font m_Font; }; DEFINE_UNIT_TEST(ListBox, "ListBox");
33.614286
89
0.523587
Oipo
bea227ef94b26917242359f7f9e5a286d85e6bb0
250
cpp
C++
Crossy_Roads/Camera/obscamera.cpp
Daryan7/Crossy_Roads
af816aa73ba29241fb1db4722940e42be8a76102
[ "MIT" ]
1
2018-04-18T12:54:33.000Z
2018-04-18T12:54:33.000Z
Crossy_Roads/Camera/obscamera.cpp
Daryan7/Crossy_Roads
af816aa73ba29241fb1db4722940e42be8a76102
[ "MIT" ]
null
null
null
Crossy_Roads/Camera/obscamera.cpp
Daryan7/Crossy_Roads
af816aa73ba29241fb1db4722940e42be8a76102
[ "MIT" ]
null
null
null
#include "obscamera.h" using namespace glm; OBSCamera::OBSCamera() { } OBSCamera::OBSCamera(vec3 OBS, vec3 UP) { this->OBS = OBS; this->UP = UP; } OBSCamera::~OBSCamera() { } void OBSCamera::updateVM() { VM = lookAt(OBS, VRP, UP); }
12.5
41
0.624
Daryan7
bea2390778d527b02f1d8a7ff84ece78d39fa6e7
7,325
cpp
C++
sysc/dev.cpp
dcblack/technology_demonstrator
c8f3d2fc9a51fba0db3ed9a44c540f1249b59b10
[ "Apache-2.0" ]
4
2018-10-12T01:06:32.000Z
2022-01-11T19:14:20.000Z
sysc/dev.cpp
dcblack/technology_demonstrator
c8f3d2fc9a51fba0db3ed9a44c540f1249b59b10
[ "Apache-2.0" ]
1
2017-06-13T05:08:35.000Z
2019-01-03T14:14:34.000Z
sysc/dev.cpp
dcblack/technology_demonstrator
c8f3d2fc9a51fba0db3ed9a44c540f1249b59b10
[ "Apache-2.0" ]
1
2015-04-29T08:42:17.000Z
2015-04-29T08:42:17.000Z
//BEGIN dev.cpp (systemc) /////////////////////////////////////////////////////////////////////////////// // $Info: Simple device implementation $ /////////////////////////////////////////////////////////////////////////////// // $License: Apache 2.0 $ // // This file is 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 "dev.h" #include "report.h" #include "sc_literals.h" using namespace sc_core; namespace { // Declare string used as message identifier in SC_REPORT_* calls static char const* const MSGID = "/Doulos/example/dev"; // Embed file version information into object to help forensics static char const* const RCSID = "(@)$Id: dev.cpp,v 1.0 2013/02/04 18:13:33 dcblack Exp $"; // FILENAME VER DATE TIME USERNAME } /////////////////////////////////////////////////////////////////////////////// // Constructor << SC_HAS_PROCESS(dev_module); dev_module::dev_module ( sc_module_name instance_name ) : sc_module(instance_name) , target_socket("target_socket") , m_register_count(8) , m_latency(10_ns) { // Misc. initialization m_byte_width = target_socket.get_bus_width()/8; m_register = new int[m_register_count]; // Register methods target_socket.register_b_transport ( this, &dev_module::b_transport ); target_socket.register_transport_dbg( this, &dev_module::transport_dbg ); // Register processes - NONE REPORT_INFO("Constructed " << " " << name()); }//endconstructor /////////////////////////////////////////////////////////////////////////////// // Destructor << dev_module::~dev_module(void) { delete [] m_register; REPORT_INFO("Destroyed " << name()); } /////////////////////////////////////////////////////////////////////////////// // TLM-2 forward methods /////////////////////////////////////////////////////////////////////////////// // // ##### ####### #### # # # #### ##### #### #### ####### // # # # # # # # ## # # # # # # # # # # // # # # # # # # # # # # # # # # # # # // ##### # #### # # # # # #### ##### # # #### # // # # # # # ####### # # # # # # # # # # // # # # # # # # # ## # # # # # # # # // ##### ##### # # # # # # # #### # #### # # # // /////////////////////////////////////////////////////////////////////////////// void dev_module::b_transport(tlm::tlm_generic_payload& trans, sc_time& delay) { tlm::tlm_command command = trans.get_command(); sc_dt::uint64 address = trans.get_address(); unsigned char* data_ptr = trans.get_data_ptr(); unsigned int data_length = trans.get_data_length(); unsigned char* byte_enables = trans.get_byte_enable_ptr(); unsigned int streaming_width = trans.get_streaming_width(); // Obliged to check address range and check for unsupported features, // i.e. byte enables, streaming, and bursts // Can ignore DMI hint and extensions // Using the SystemC report handler is an acceptable way of signalling an error if (address >= sc_dt::uint64(m_register_count) * m_byte_width) { trans.set_response_status( tlm::TLM_ADDRESS_ERROR_RESPONSE ); return; } else if (address % m_byte_width) { // Only allow aligned bit width transfers SC_REPORT_WARNING(MSGID,"Misaligned address"); trans.set_response_status( tlm::TLM_ADDRESS_ERROR_RESPONSE ); return; } else if (byte_enables != 0) { // No support for byte enables trans.set_response_status( tlm::TLM_BYTE_ENABLE_ERROR_RESPONSE ); return; } else if ((data_length % m_byte_width) != 0 || streaming_width < data_length || data_length == 0 || (address+data_length)/m_byte_width >= m_register_count) { // Only allow word-multiple transfers within memory size trans.set_response_status( tlm::TLM_BURST_ERROR_RESPONSE ); return; }//endif // Obliged to implement read and write commands if ( command == tlm::TLM_READ_COMMAND ) { memcpy(data_ptr, &m_register[address/m_byte_width], data_length); } else if ( command == tlm::TLM_WRITE_COMMAND ) { memcpy(&m_register[address/m_byte_width], data_ptr, data_length); }//endif // Memory access time per bus value delay += (m_latency * data_length/m_byte_width); // Obliged to set response status to indicate successful completion trans.set_response_status( tlm::TLM_OK_RESPONSE ); }//end dev_module::b_transport //////////////////////////////////////////////////////////////////////////////// // // ####### #### # # # ### ### ## #### ####### ### #### ### // # # # # # ## # # # # # # # # # # # # # # # # // # # # # # # # # # # # # # # # # # # # # # // # #### # # # # # ### ### # # #### # # # #### # ### // # # # ##### # # # # # # # # # # # # # # # # // # # # # # # ## # # # # # # # # # # # # # # // # # # # # # # ### # ## # # # ##### ### #### ### // //////////////////////////////////////////////////////////////////////////////// unsigned int dev_module::transport_dbg(tlm::tlm_generic_payload& trans) { int transferred = 0; tlm::tlm_command command = trans.get_command(); sc_dt::uint64 address = trans.get_address(); unsigned char* data_ptr = trans.get_data_ptr(); unsigned int data_length = trans.get_data_length(); unsigned char* byte_enables = trans.get_byte_enable_ptr(); unsigned int streaming_width = trans.get_streaming_width(); // Obliged to check address range and check for unsupported features, // i.e. byte enables, streaming, and bursts // Can ignore DMI hint and extensions // Using the SystemC report handler is an acceptable way of signalling an error if (address >= sc_dt::uint64(m_register_count) * m_byte_width) { trans.set_response_status( tlm::TLM_ADDRESS_ERROR_RESPONSE ); return 0; } else if (address % m_byte_width) { // Only allow aligned bit width transfers trans.set_response_status( tlm::TLM_ADDRESS_ERROR_RESPONSE ); return 0; }//endif // Obliged to implement read and write commands if ( command == tlm::TLM_READ_COMMAND ) { memcpy(data_ptr, &m_register[address/m_byte_width], data_length); transferred = data_length; } else if ( command == tlm::TLM_WRITE_COMMAND ) { memcpy(&m_register[address/m_byte_width], data_ptr, data_length); transferred = data_length; }//endif // Obliged to set response status to indicate successful completion trans.set_response_status( tlm::TLM_OK_RESPONSE ); return transferred; }//end dev_module::transport_dbg //EOF
42.34104
99
0.539113
dcblack
bea67ba9bf710f926e27096b87b670a45f3670c3
1,493
cpp
C++
ZSpire-Framework/src/zs-forward-render.cpp
Pershades/zspire
9b08cfd4cf25348680dc0c3f139b079a2f7434ef
[ "MIT" ]
4
2018-03-15T20:02:17.000Z
2018-03-31T19:19:53.000Z
ZSpire-Framework/src/zs-forward-render.cpp
Cvosttv/zspire
9b08cfd4cf25348680dc0c3f139b079a2f7434ef
[ "MIT" ]
null
null
null
ZSpire-Framework/src/zs-forward-render.cpp
Cvosttv/zspire
9b08cfd4cf25348680dc0c3f139b079a2f7434ef
[ "MIT" ]
3
2018-03-25T15:43:51.000Z
2018-03-27T22:43:05.000Z
#include <vector> #include "../includes/zs-base-structs.h" #include "../includes/zs-camera.h" #include "../includes/zs-light.h" #include "../includes/zs-shader.h" #include "../includes/zs-game-object.h" #include "../includes/zs-scene.h" #include "../includes/zs-forward-render.h" #ifdef _WIN32 #include <glew.h> #endif #ifdef __linux__ #include <GL/glew.h> #endif ZSpire::Shader* object_shader; ZSpire::ZSRENDERRULE renderRules; GLbitfield clearMode = GL_COLOR_BUFFER_BIT; void ZSpire::ForwardRender::setForwardObjectShader(Shader* shader) { object_shader = shader; } void ZSpire::ForwardRender::RenderScene(Scene* scene) { glClear(clearMode); if (renderRules.cullFaces == true) { glEnable(GL_CULL_FACE); } if (renderRules.depthTest == true) { glEnable(GL_DEPTH_TEST); } object_shader->Use(); object_shader->setUniformInt("lights_amount", scene->getLightsCount()); Camera::setCameraMode(CAMERA_MODE_SCENE); object_shader->updateCamera(); for (unsigned int light = 0; light < scene->getLightsCount(); light ++) { object_shader->setLight(light, scene->getLightAt(light)); } for (unsigned int obj = 0; obj < scene->getObjectsCount(); obj ++) { Transform * tr = scene->getObjectAt(obj)->getTransform(); object_shader->setTransform(tr); scene->getObjectAt(obj)->Draw(); } } void ZSpire::ForwardRender::setRenderRule(ZSRENDERRULE rule) { renderRules = rule; if (rule.depthTest == true) { clearMode = clearMode | GL_DEPTH_BUFFER_BIT; } }
20.452055
74
0.713999
Pershades
bea9a92742289ee55258270749877935498b490c
44,181
cpp
C++
src/JSystem/JAS/JASAramStream.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
33
2021-12-08T11:10:59.000Z
2022-03-26T19:59:37.000Z
src/JSystem/JAS/JASAramStream.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
6
2021-12-22T17:54:31.000Z
2022-01-07T21:43:18.000Z
src/JSystem/JAS/JASAramStream.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
2
2022-01-04T06:00:49.000Z
2022-01-26T07:27:28.000Z
#include "types.h" /* Generated from dpostproc .section .rodata # 0x804732E0 - 0x8049E220 .global OSC_RELEASE_TABLE OSC_RELEASE_TABLE: .4byte 0x00000002 .4byte 0x0000000F .4byte 0x00000000 .global OSC_ENV OSC_ENV: .4byte 0x00000000 .float 1.0 .4byte 0x00000000 .4byte OSC_RELEASE_TABLE .float 1.0 .4byte 0x00000000 .4byte 0x00000000 .section .data, "wa" # 0x8049E220 - 0x804EFC20 .global lbl_804A44A0 lbl_804A44A0: .4byte lbl_800A9AF8 .4byte lbl_800A9AEC .4byte lbl_800A9B00 .4byte lbl_800A9AF8 .4byte lbl_800A9AF8 .4byte lbl_800A9AF8 .4byte lbl_800A9AF8 .4byte lbl_800A9AF8 .4byte lbl_800A9AF8 .4byte lbl_800A9AF8 .4byte lbl_800A9AF8 .4byte lbl_800A9AF8 .4byte lbl_800A9AF8 .4byte 0x00000000 .4byte 0x00000000 .4byte 0x00000000 .section .sbss # 0x80514D80 - 0x80516360 .global sLoadThread__13JASAramStream sLoadThread__13JASAramStream: .skip 0x4 .global sReadBuffer__13JASAramStream sReadBuffer__13JASAramStream: .skip 0x4 .global sBlockSize__13JASAramStream sBlockSize__13JASAramStream: .skip 0x4 .global sChannelMax__13JASAramStream sChannelMax__13JASAramStream: .skip 0x4 .global sSystemPauseFlag__13JASAramStream sSystemPauseFlag__13JASAramStream: .skip 0x1 .global sFatalErrorFlag__13JASAramStream sFatalErrorFlag__13JASAramStream: .skip 0x7 .section .sdata2, "a" # 0x80516360 - 0x80520E40 .global lbl_80516EB0 lbl_80516EB0: .4byte 0x00000000 .global lbl_80516EB4 lbl_80516EB4: .float 1.0 .global lbl_80516EB8 lbl_80516EB8: .float 0.5 .global lbl_80516EBC lbl_80516EBC: .4byte 0x42FE0000 .global lbl_80516EC0 lbl_80516EC0: .4byte 0x43300000 .4byte 0x00000000 .global one$870 one$870: .4byte 0x00000001 .4byte 0x00000000 */ /* * --INFO-- * Address: 800A8FA4 * Size: 000090 */ void JASAramStream::initSystem(unsigned long, unsigned long) { /* stwu r1, -0x10(r1) mflr r0 lis r5, dvdErrorCheck__13JASAramStreamFPv@ha stw r0, 0x14(r1) addi r0, r5, dvdErrorCheck__13JASAramStreamFPv@l stw r31, 0xc(r1) mr r31, r4 li r4, 0 stw r30, 8(r1) mr r30, r3 mr r3, r0 bl registerSubFrameCallback__9JASDriverFPFPv_lPv clrlwi. r0, r3, 0x18 beq lbl_800A901C lwz r0, sLoadThread__13JASAramStream@sda21(r13) cmplwi r0, 0 bne lbl_800A8FF0 bl getThreadPointer__6JASDvdFv stw r3, sLoadThread__13JASAramStream@sda21(r13) lbl_800A8FF0: addi r0, r30, 0x20 lwz r4, JASDram@sda21(r13) mullw r3, r0, r31 li r5, 0x20 bl __nwa__FUlP7JKRHeapi li r0, 0 stw r3, sReadBuffer__13JASAramStream@sda21(r13) stw r30, sBlockSize__13JASAramStream@sda21(r13) stw r31, sChannelMax__13JASAramStream@sda21(r13) stb r0, sSystemPauseFlag__13JASAramStream@sda21(r13) stb r0, sFatalErrorFlag__13JASAramStream@sda21(r13) lbl_800A901C: lwz r0, 0x14(r1) lwz r31, 0xc(r1) lwz r30, 8(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: ........ * Size: 000008 */ void JASAramStream::setLoadThread(JASTaskThread*) { // UNUSED FUNCTION } /* * --INFO-- * Address: 800A9034 * Size: 000158 */ JASAramStream::JASAramStream() { /* li r0, 0 lfs f3, lbl_80516EB0@sda21(r2) stw r0, 0x198(r3) lfs f2, lbl_80516EB4@sda21(r2) stb r0, 0x19c(r3) lfs f1, lbl_80516EB8@sda21(r2) stb r0, 0x19d(r3) lfs f0, lbl_80516EB0@sda21(r2) stb r0, 0x19e(r3) stw r0, 0x1a0(r3) stw r0, 0x1a4(r3) stw r0, 0x1a8(r3) stw r0, 0x1ac(r3) stb r0, 0x1b0(r3) stw r0, 0x1b4(r3) stfs f3, 0x1b8(r3) stw r0, 0x1f8(r3) stw r0, 0x1fc(r3) stw r0, 0x200(r3) stb r0, 0x204(r3) stw r0, 0x208(r3) stw r0, 0x21c(r3) stw r0, 0x238(r3) stw r0, 0x23c(r3) stw r0, 0x240(r3) stw r0, 0x244(r3) sth r0, 0x248(r3) sth r0, 0x24a(r3) stw r0, 0x24c(r3) stw r0, 0x250(r3) stw r0, 0x254(r3) stb r0, 0x258(r3) stw r0, 0x25c(r3) stw r0, 0x260(r3) stfs f2, 0x264(r3) stfs f2, 0x268(r3) stb r0, 0x2d8(r3) stw r0, 0x180(r3) sth r0, 0x220(r3) sth r0, 0x22c(r3) stfs f2, 0x26c(r3) stfs f1, 0x284(r3) stfs f0, 0x29c(r3) stfs f0, 0x2b4(r3) stw r0, 0x184(r3) sth r0, 0x222(r3) sth r0, 0x22e(r3) stfs f2, 0x270(r3) stfs f1, 0x288(r3) stfs f0, 0x2a0(r3) stfs f0, 0x2b8(r3) stw r0, 0x188(r3) sth r0, 0x224(r3) sth r0, 0x230(r3) stfs f2, 0x274(r3) stfs f1, 0x28c(r3) stfs f0, 0x2a4(r3) stfs f0, 0x2bc(r3) stw r0, 0x18c(r3) sth r0, 0x226(r3) sth r0, 0x232(r3) stfs f2, 0x278(r3) stfs f1, 0x290(r3) stfs f0, 0x2a8(r3) stfs f0, 0x2c0(r3) stw r0, 0x190(r3) sth r0, 0x228(r3) sth r0, 0x234(r3) stfs f2, 0x27c(r3) stfs f1, 0x294(r3) stfs f0, 0x2ac(r3) stfs f0, 0x2c4(r3) stw r0, 0x194(r3) sth r0, 0x22a(r3) sth r0, 0x236(r3) stfs f2, 0x280(r3) stfs f1, 0x298(r3) stfs f0, 0x2b0(r3) stfs f0, 0x2c8(r3) sth r0, 0x2cc(r3) sth r0, 0x2ce(r3) sth r0, 0x2d0(r3) sth r0, 0x2d2(r3) sth r0, 0x2d4(r3) sth r0, 0x2d6(r3) blr */ } /* * --INFO-- * Address: 800A918C * Size: 0000F8 */ void JASAramStream::init(unsigned long, unsigned long, void (*)(unsigned long, JASAramStream*, void*), void*) { /* .loc_0x0: stwu r1, -0x10(r1) mflr r0 lfs f0, -0x74B0(r2) li r9, 0 stw r0, 0x14(r1) lis r8, 0x1 lfs f2, -0x74AC(r2) subi r0, r8, 0x1 stw r31, 0xC(r1) mr r31, r3 lfs f1, -0x74A8(r2) stw r4, 0x238(r3) addi r4, r31, 0x40 stw r5, 0x23C(r3) li r5, 0x10 stfs f0, 0x1B8(r3) lfs f0, -0x74B0(r2) stb r9, 0x19E(r3) stb r9, 0x19C(r3) stb r9, 0x19D(r3) stb r9, 0x204(r3) sth r9, 0x24A(r3) stfs f2, 0x26C(r3) stfs f1, 0x284(r3) stfs f0, 0x29C(r3) stfs f0, 0x2B4(r3) stfs f2, 0x270(r3) stfs f1, 0x288(r3) stfs f0, 0x2A0(r3) stfs f0, 0x2B8(r3) stfs f2, 0x274(r3) stfs f1, 0x28C(r3) stfs f0, 0x2A4(r3) stfs f0, 0x2BC(r3) stfs f2, 0x278(r3) stfs f1, 0x290(r3) stfs f0, 0x2A8(r3) stfs f0, 0x2C0(r3) stfs f2, 0x27C(r3) stfs f1, 0x294(r3) stfs f0, 0x2AC(r3) stfs f0, 0x2C4(r3) stfs f2, 0x280(r3) stfs f1, 0x298(r3) stfs f0, 0x2B0(r3) stfs f0, 0x2C8(r3) stfs f2, 0x264(r3) stfs f2, 0x268(r3) stb r9, 0x2D8(r3) sth r0, 0x2CC(r3) stw r6, 0x240(r3) stw r7, 0x244(r3) bl 0x46260 addi r3, r31, 0x20 addi r4, r31, 0x80 li r5, 0x4 bl 0x46250 lwz r0, 0x14(r1) lwz r31, 0xC(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: ........ * Size: 000010 */ void JASAramStream::setBusSetting(unsigned long, unsigned short) { // UNUSED FUNCTION } /* * --INFO-- * Address: ........ * Size: 000058 */ void JASAramStream::prepare(const char*, int) { // UNUSED FUNCTION } /* * --INFO-- * Address: 800A9284 * Size: 0000B8 */ void JASAramStream::prepare(long, int) { /* stwu r1, -0x20(r1) mflr r0 stw r0, 0x24(r1) stw r31, 0x1c(r1) mr r31, r5 stw r30, 0x18(r1) mr r30, r3 mr r3, r4 addi r4, r30, 0x1bc bl DVDFastOpen cmpwi r3, 0 bne lbl_800A92BC li r3, 0 b lbl_800A9324 lbl_800A92BC: lis r3, channelProcCallback__13JASAramStreamFPv@ha mr r4, r30 addi r3, r3, channelProcCallback__13JASAramStreamFPv@l bl registerSubFrameCallback__9JASDriverFPFPv_lPv clrlwi. r0, r3, 0x18 bne lbl_800A92DC li r3, 0 b lbl_800A9324 lbl_800A92DC: lbz r0, 0x204(r30) cmplwi r0, 0 beq lbl_800A92F0 li r3, 0 b lbl_800A9324 lbl_800A92F0: stw r30, 8(r1) lis r3, headerLoadTask__13JASAramStreamFPv@ha addi r4, r3, headerLoadTask__13JASAramStreamFPv@l lwz r3, sLoadThread__13JASAramStream@sda21(r13) lwz r0, 0x23c(r30) addi r5, r1, 8 li r6, 0xc stw r0, 0xc(r1) stw r31, 0x10(r1) bl sendCmdMsg__13JASTaskThreadFPFPv_vPCvUl neg r0, r3 or r0, r0, r3 srwi r3, r0, 0x1f lbl_800A9324: lwz r0, 0x24(r1) lwz r31, 0x1c(r1) lwz r30, 0x18(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /* * --INFO-- * Address: 800A933C * Size: 000034 */ void JASAramStream::start() { /* stwu r1, -0x10(r1) mflr r0 li r4, 0 li r5, 0 stw r0, 0x14(r1) bl OSSendMessage neg r0, r3 or r0, r0, r3 srwi r3, r0, 0x1f lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 800A9370 * Size: 000038 */ void JASAramStream::stop(unsigned short) { /* stwu r1, -0x10(r1) mflr r0 li r5, 0 stw r0, 0x14(r1) slwi r0, r4, 0x10 ori r4, r0, 1 bl OSSendMessage neg r0, r3 or r0, r0, r3 srwi r3, r0, 0x1f lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 800A93A8 * Size: 000048 */ void JASAramStream::pause(bool) { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) clrlwi. r0, r4, 0x18 li r4, 3 beq lbl_800A93C4 li r4, 2 lbl_800A93C4: li r5, 0 bl OSSendMessage cmpwi r3, 0 bne lbl_800A93DC li r3, 0 b lbl_800A93E0 lbl_800A93DC: li r3, 1 lbl_800A93E0: lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 800A93F0 * Size: 000044 */ void JASAramStream::cancel() { /* stwu r1, -0x10(r1) mflr r0 lis r4, finishTask__13JASAramStreamFPv@ha mr r5, r3 stw r0, 0x14(r1) li r0, 1 addi r4, r4, finishTask__13JASAramStreamFPv@l stb r0, 0x204(r3) lwz r3, sLoadThread__13JASAramStream@sda21(r13) bl sendCmdMsg__13JASTaskThreadFPFPv_vPv neg r0, r3 or r0, r0, r3 srwi r3, r0, 0x1f lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: ........ * Size: 000034 */ void JASAramStream::getBlockSamples() const { // UNUSED FUNCTION } /* * --INFO-- * Address: 800A9434 * Size: 000030 */ void JASAramStream::headerLoadTask(void*) { /* stwu r1, -0x10(r1) mflr r0 mr r5, r3 stw r0, 0x14(r1) lwz r4, 4(r5) lwz r3, 0(r3) lwz r5, 8(r5) bl headerLoad__13JASAramStreamFUli lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 800A9464 * Size: 0000DC */ void JASAramStream::firstLoadTask(void*) { /* stwu r1, -0x20(r1) mflr r0 stw r0, 0x24(r1) stw r31, 0x1c(r1) mr r31, r3 stw r30, 0x18(r1) lwz r30, 0(r3) mr r3, r30 bl load__13JASAramStreamFv clrlwi. r0, r3, 0x18 beq lbl_800A9528 lwz r3, 8(r31) cmpwi r3, 0 ble lbl_800A94D4 addi r0, r3, -1 stw r0, 8(r31) lwz r0, 8(r31) cmpwi r0, 0 bne lbl_800A94D4 lis r4, prepareFinishTask__13JASAramStreamFPv@ha lwz r3, sLoadThread__13JASAramStream@sda21(r13) addi r4, r4, prepareFinishTask__13JASAramStreamFPv@l mr r5, r30 bl sendCmdMsg__13JASTaskThreadFPFPv_vPv cmpwi r3, 0 bne lbl_800A94D4 li r0, 1 stb r0, sFatalErrorFlag__13JASAramStream@sda21(r13) lbl_800A94D4: lwz r3, 4(r31) cmplwi r3, 0 beq lbl_800A9528 addi r0, r3, -1 lis r3, firstLoadTask__13JASAramStreamFPv@ha stw r0, 4(r31) addi r4, r3, firstLoadTask__13JASAramStreamFPv@l mr r5, r31 li r6, 0xc lwz r3, sLoadThread__13JASAramStream@sda21(r13) bl sendCmdMsg__13JASTaskThreadFPFPv_vPCvUl cmpwi r3, 0 bne lbl_800A9510 li r0, 1 stb r0, sFatalErrorFlag__13JASAramStream@sda21(r13) lbl_800A9510: bl OSDisableInterrupts lwz r4, 0x208(r30) stw r3, 8(r1) addi r0, r4, 1 stw r0, 0x208(r30) bl OSRestoreInterrupts lbl_800A9528: lwz r0, 0x24(r1) lwz r31, 0x1c(r1) lwz r30, 0x18(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /* * --INFO-- * Address: 800A9540 * Size: 000020 */ void JASAramStream::loadToAramTask(void*) { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) bl load__13JASAramStreamFv lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 800A9560 * Size: 000060 */ void JASAramStream::finishTask(void*) { /* stwu r1, -0x10(r1) mflr r0 lis r4, channelProcCallback__13JASAramStreamFPv@ha stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r3 addi r3, r4, channelProcCallback__13JASAramStreamFPv@l mr r4, r31 bl rejectCallback__9JASDriverFPFPv_lPv lwz r12, 0x240(r31) cmplwi r12, 0 beq lbl_800A95AC mr r4, r31 lwz r5, 0x244(r31) li r3, 0 mtctr r12 bctrl li r0, 0 stw r0, 0x240(r31) lbl_800A95AC: lwz r0, 0x14(r1) lwz r31, 0xc(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 800A95C0 * Size: 000058 */ void JASAramStream::prepareFinishTask(void*) { /* stwu r1, -0x10(r1) mflr r0 li r4, 4 li r5, 1 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r3 addi r3, r31, 0x20 bl OSSendMessage lwz r12, 0x240(r31) cmplwi r12, 0 beq lbl_800A9604 mr r4, r31 lwz r5, 0x244(r31) li r3, 1 mtctr r12 bctrl lbl_800A9604: lwz r0, 0x14(r1) lwz r31, 0xc(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 800A9618 * Size: 0001CC */ void JASAramStream::headerLoad(unsigned long, int) { /* stwu r1, -0x30(r1) mflr r0 stw r0, 0x34(r1) stw r31, 0x2c(r1) mr r31, r5 stw r30, 0x28(r1) mr r30, r4 stw r29, 0x24(r1) mr r29, r3 lbz r0, sFatalErrorFlag__13JASAramStream@sda21(r13) cmplwi r0, 0 beq lbl_800A9650 li r3, 0 b lbl_800A97C8 lbl_800A9650: lbz r0, 0x204(r29) cmplwi r0, 0 beq lbl_800A9664 li r3, 0 b lbl_800A97C8 lbl_800A9664: lwz r4, sReadBuffer__13JASAramStream@sda21(r13) addi r3, r29, 0x1bc li r5, 0x40 li r6, 0 li r7, 1 bl DVDReadPrio cmpwi r3, 0 bge lbl_800A9694 li r0, 1 li r3, 0 stb r0, sFatalErrorFlag__13JASAramStream@sda21(r13) b lbl_800A97C8 lbl_800A9694: lwz r5, sReadBuffer__13JASAramStream@sda21(r13) lis r0, 0x4330 stw r0, 0x18(r1) li r0, 0 lbz r3, 9(r5) cmpwi r31, 0 lfd f2, lbl_80516EC0@sda21(r2) sth r3, 0x248(r29) lfs f0, lbl_80516EBC@sda21(r2) lhz r3, 0xc(r5) sth r3, 0x24a(r29) lwz r3, 0x10(r5) stw r3, 0x254(r29) lhz r4, 0xe(r5) neg r3, r4 or r3, r3, r4 srwi r3, r3, 0x1f stb r3, 0x258(r29) lwz r3, 0x18(r5) stw r3, 0x25c(r29) lwz r3, 0x1c(r5) stw r3, 0x260(r29) lbz r3, 0x28(r5) stw r3, 0x1c(r1) lfd f1, 0x18(r1) fsubs f1, f1, f2 fdivs f0, f1, f0 stfs f0, 0x264(r29) stw r0, 0x208(r29) stw r0, 0x200(r29) stw r0, 0x1fc(r29) lwz r3, sBlockSize__13JASAramStream@sda21(r13) lhz r0, 0xc(r5) divwu r3, r30, r3 divwu r0, r3, r0 stw r0, 0x250(r29) lwz r0, 0x250(r29) stw r0, 0x24c(r29) lwz r3, 0x24c(r29) addi r0, r3, -1 stw r0, 0x24c(r29) lwz r0, 0x24c(r29) stw r0, 0x1f8(r29) blt lbl_800A9750 lwz r0, 0x1f8(r29) cmplw r31, r0 ble lbl_800A9754 lbl_800A9750: lwz r31, 0x1f8(r29) lbl_800A9754: lbz r0, 0x204(r29) cmplwi r0, 0 beq lbl_800A9768 li r3, 0 b lbl_800A97C8 lbl_800A9768: stw r29, 0xc(r1) lis r3, firstLoadTask__13JASAramStreamFPv@ha addi r4, r3, firstLoadTask__13JASAramStreamFPv@l lwz r3, sLoadThread__13JASAramStream@sda21(r13) lwz r7, 0x1f8(r29) addi r5, r1, 0xc li r6, 0xc addi r0, r7, -1 stw r31, 0x14(r1) stw r0, 0x10(r1) bl sendCmdMsg__13JASTaskThreadFPFPv_vPCvUl cmpwi r3, 0 bne lbl_800A97AC li r0, 1 li r3, 0 stb r0, sFatalErrorFlag__13JASAramStream@sda21(r13) b lbl_800A97C8 lbl_800A97AC: bl OSDisableInterrupts lwz r4, 0x208(r29) stw r3, 8(r1) addi r0, r4, 1 stw r0, 0x208(r29) bl OSRestoreInterrupts li r3, 1 lbl_800A97C8: lwz r0, 0x34(r1) lwz r31, 0x2c(r1) lwz r30, 0x28(r1) lwz r29, 0x24(r1) mtlr r0 addi r1, r1, 0x30 blr */ } /* * --INFO-- * Address: 800A97E4 * Size: 0002B4 */ void JASAramStream::load() { /* stwu r1, -0x30(r1) mflr r0 stw r0, 0x34(r1) stmw r26, 0x18(r1) mr r27, r3 bl OSDisableInterrupts lwz r4, 0x208(r27) stw r3, 8(r1) addi r0, r4, -1 stw r0, 0x208(r27) bl OSRestoreInterrupts lbz r0, sFatalErrorFlag__13JASAramStream@sda21(r13) cmplwi r0, 0 beq lbl_800A9824 li r3, 0 b lbl_800A9A84 lbl_800A9824: lbz r0, 0x204(r27) cmplwi r0, 0 beq lbl_800A9838 li r3, 0 b lbl_800A9A84 lbl_800A9838: lhz r4, 0x248(r27) cmplwi r4, 0 bne lbl_800A9860 lwz r0, sBlockSize__13JASAramStream@sda21(r13) lis r3, 0x38E38E39@ha addi r3, r3, 0x38E38E39@l slwi r0, r0, 4 mulhwu r0, r3, r0 srwi r5, r0, 1 b lbl_800A9868 lbl_800A9860: lwz r0, sBlockSize__13JASAramStream@sda21(r13) srwi r5, r0, 1 lbl_800A9868: lwz r3, 0x260(r27) cmplwi r4, 0 lwz r4, 0x25c(r27) addi r0, r3, -1 divwu r31, r0, r5 bne lbl_800A989C lwz r0, sBlockSize__13JASAramStream@sda21(r13) lis r3, 0x38E38E39@ha addi r3, r3, 0x38E38E39@l slwi r0, r0, 4 mulhwu r0, r3, r0 srwi r0, r0, 1 b lbl_800A98A4 lbl_800A989C: lwz r0, sBlockSize__13JASAramStream@sda21(r13) srwi r0, r0, 1 lbl_800A98A4: divwu r30, r4, r0 lwz r4, 0x200(r27) cmplw r4, r31 ble lbl_800A98BC li r3, 0 b lbl_800A9A84 lbl_800A98BC: lwz r3, sBlockSize__13JASAramStream@sda21(r13) lhz r0, 0x24a(r27) mullw r3, r3, r0 addi r0, r3, 0x20 mullw r3, r4, r0 mr r5, r0 addi r6, r3, 0x40 bne lbl_800A98E4 lwz r0, 0x1f0(r27) subf r5, r6, r0 lbl_800A98E4: lwz r4, sReadBuffer__13JASAramStream@sda21(r13) addi r3, r27, 0x1bc li r7, 1 bl DVDReadPrio cmpwi r3, 0 bge lbl_800A990C li r0, 1 li r3, 0 stb r0, sFatalErrorFlag__13JASAramStream@sda21(r13) b lbl_800A9A84 lbl_800A990C: lwz r3, 0x1fc(r27) li r28, 0 lwz r0, sBlockSize__13JASAramStream@sda21(r13) lwz r4, 0x238(r27) mullw r0, r3, r0 lwz r29, sReadBuffer__13JASAramStream@sda21(r13) add r26, r4, r0 b lbl_800A9988 lbl_800A992C: lwz r3, sBlockSize__13JASAramStream@sda21(r13) li r6, 0 lwz r0, 0x250(r27) li r7, 0 lwz r5, 4(r29) li r8, 0 mullw r0, r3, r0 lwz r4, sReadBuffer__13JASAramStream@sda21(r13) li r9, -1 li r10, 0 mullw r3, r5, r28 addi r3, r3, 0x20 mullw r0, r28, r0 add r3, r4, r3 add r4, r26, r0 bl mainRamToAram__7JKRAramFPUcUlUl15JKRExpandSwitchUlP7JKRHeapiPUl cmplwi r3, 0 bne lbl_800A9984 li r0, 1 li r3, 0 stb r0, sFatalErrorFlag__13JASAramStream@sda21(r13) b lbl_800A9A84 lbl_800A9984: addi r28, r28, 1 lbl_800A9988: lhz r0, 0x24a(r27) cmpw r28, r0 blt lbl_800A992C lwz r3, 0x1fc(r27) addi r0, r3, 1 stw r0, 0x1fc(r27) lwz r0, 0x1fc(r27) lwz r3, 0x1f8(r27) cmplw r0, r3 blt lbl_800A9A58 lbz r0, 0x258(r27) lwz r4, 0x200(r27) cmplwi r0, 0 add r4, r3, r4 addi r4, r4, -1 beq lbl_800A99DC b lbl_800A99D4 lbl_800A99CC: subf r4, r31, r4 add r4, r4, r30 lbl_800A99D4: cmplw r4, r31 bgt lbl_800A99CC lbl_800A99DC: cmplw r4, r31 beq lbl_800A99F0 addi r0, r4, 2 cmplw r0, r31 bne lbl_800A9A0C lbl_800A99F0: lwz r0, 0x250(r27) addi r3, r27, 0x20 li r4, 5 li r5, 1 stw r0, 0x1f8(r27) bl OSSendMessage b lbl_800A9A18 lbl_800A9A0C: lwz r3, 0x250(r27) addi r0, r3, -1 stw r0, 0x1f8(r27) lbl_800A9A18: mr r3, r29 mr r4, r27 li r5, 0 b lbl_800A9A44 lbl_800A9A28: lha r0, 8(r3) addi r5, r5, 1 sth r0, 0x220(r4) lha r0, 0xa(r3) addi r3, r3, 4 sth r0, 0x22c(r4) addi r4, r4, 2 lbl_800A9A44: lhz r0, 0x24a(r27) cmpw r5, r0 blt lbl_800A9A28 li r0, 0 stw r0, 0x1fc(r27) lbl_800A9A58: lwz r3, 0x200(r27) addi r0, r3, 1 stw r0, 0x200(r27) lwz r0, 0x200(r27) cmplw r0, r31 ble lbl_800A9A80 lbz r0, 0x258(r27) cmplwi r0, 0 beq lbl_800A9A80 stw r30, 0x200(r27) lbl_800A9A80: li r3, 1 lbl_800A9A84: lmw r26, 0x18(r1) lwz r0, 0x34(r1) mtlr r0 addi r1, r1, 0x30 blr */ } /* * --INFO-- * Address: 800A9A98 * Size: 000020 */ void JASAramStream::channelProcCallback(void*) { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) bl channelProc__13JASAramStreamFv lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 800A9AB8 * Size: 00005C */ void JASAramStream::dvdErrorCheck(void*) { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) bl DVDGetDriveStatus addi r0, r3, 1 cmplwi r0, 0xc bgt lbl_800A9AF8 lis r3, lbl_804A44A0@ha slwi r0, r0, 2 addi r3, r3, lbl_804A44A0@l lwzx r0, r3, r0 mtctr r0 bctr .global lbl_800A9AEC lbl_800A9AEC: li r0, 0 stb r0, sSystemPauseFlag__13JASAramStream@sda21(r13) b lbl_800A9B00 .global lbl_800A9AF8 lbl_800A9AF8: li r0, 1 stb r0, sSystemPauseFlag__13JASAramStream@sda21(r13) .global lbl_800A9B00 lbl_800A9B00: lwz r0, 0x14(r1) li r3, 0 mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 800A9B14 * Size: 00003C */ void JASAramStream::channelCallback(unsigned long, JASChannel*, JASDsp::TChannel*, void*) { /* .loc_0x0: stwu r1, -0x10(r1) mflr r0 mr r8, r3 mr r7, r4 stw r0, 0x14(r1) mr r0, r5 mr r3, r6 mr r4, r8 mr r5, r7 mr r6, r0 bl .loc_0x3C lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr .loc_0x3C: */ } /* * --INFO-- * Address: 800A9B50 * Size: 000758 */ void JASAramStream::updateChannel(unsigned long, JASChannel*, JASDsp::TChannel*) { /* stwu r1, -0x50(r1) mflr r0 stw r0, 0x54(r1) stmw r24, 0x30(r1) mr r27, r3 mr r28, r5 mr r29, r6 lhz r0, 0x248(r3) cmplwi r0, 0 bne lbl_800A9B94 lwz r0, sBlockSize__13JASAramStream@sda21(r13) lis r3, 0x38E38E39@ha addi r3, r3, 0x38E38E39@l slwi r0, r0, 4 mulhwu r0, r3, r0 srwi r31, r0, 1 b lbl_800A9B9C lbl_800A9B94: lwz r0, sBlockSize__13JASAramStream@sda21(r13) srwi r31, r0, 1 lbl_800A9B9C: cmpwi r4, 1 beq lbl_800A9BC0 bge lbl_800A9BB4 cmpwi r4, 0 bge lbl_800A9C08 b lbl_800AA27C lbl_800A9BB4: cmpwi r4, 3 bge lbl_800AA27C b lbl_800AA17C lbl_800A9BC0: lwz r0, 0x198(r27) cmplwi r0, 0 bne lbl_800AA27C stw r28, 0x198(r27) li r4, 0 lwz r0, 0x24c(r27) mullw r0, r31, r0 stw r0, 0x1a4(r27) stw r4, 0x1a8(r27) stw r4, 0x1a0(r27) lwz r3, 0x260(r27) addi r0, r3, -1 divwu r0, r0, r31 stw r0, 0x1ac(r27) stb r4, 0x1b0(r27) stw r4, 0x1b4(r27) stw r4, 0x21c(r27) b lbl_800AA27C lbl_800A9C08: lhz r0, 8(r29) cmplwi r0, 0 bne lbl_800AA27C lwz r0, 0x198(r27) cmplw r28, r0 bne lbl_800AA0AC li r6, 0 stw r6, 0x21c(r27) lwz r3, 0x74(r29) lhz r0, 0x64(r29) lwz r4, 0x1a4(r27) add r7, r3, r0 cmplw r7, r4 bgt lbl_800A9C54 lwz r3, 0x1a8(r27) subf r0, r7, r4 add r0, r3, r0 stw r0, 0x1a8(r27) b lbl_800A9D08 lbl_800A9C54: lbz r0, 0x1b0(r27) cmplwi r0, 0 bne lbl_800A9C88 lwz r0, 0x1a8(r27) add r0, r0, r4 stw r0, 0x1a8(r27) lwz r0, 0x24c(r27) lwz r3, 0x1a8(r27) mullw r0, r31, r0 subf r0, r7, r0 add r0, r3, r0 stw r0, 0x1a8(r27) b lbl_800A9D08 lbl_800A9C88: lwz r3, 0x1a8(r27) li r0, -1 add r3, r3, r4 stw r3, 0x1a8(r27) lwz r3, 0x24c(r27) lwz r4, 0x110(r29) mullw r3, r31, r3 lwz r5, 0x1a8(r27) subf r3, r7, r3 subf r3, r4, r3 add r3, r5, r3 stw r3, 0x1a8(r27) lwz r4, 0x260(r27) lwz r3, 0x1a8(r27) subf r3, r4, r3 stw r3, 0x1a8(r27) lwz r4, 0x1a8(r27) lwz r3, 0x25c(r27) add r3, r4, r3 stw r3, 0x1a8(r27) stw r6, 0x110(r29) stw r6, 0x210(r27) lwz r3, 0x21c(r27) ori r3, r3, 2 stw r3, 0x21c(r27) lwz r3, 0x1b4(r27) cmplw r3, r0 bge lbl_800A9D00 addi r0, r3, 1 stw r0, 0x1b4(r27) lbl_800A9D00: li r0, 0 stb r0, 0x1b0(r27) lbl_800A9D08: lwz r3, 0x1a8(r27) lwz r0, 0x260(r27) cmplw r3, r0 ble lbl_800A9D20 li r0, 1 stb r0, sFatalErrorFlag__13JASAramStream@sda21(r13) lbl_800A9D20: lwz r4, 0x25c(r27) lis r5, 0x4330 lwz r3, 0x260(r27) li r0, -1 lwz r6, 0x1b4(r27) subf r3, r4, r3 stw r5, 0x10(r1) lfd f1, lbl_80516EC0@sda21(r2) cmplw r6, r0 stw r6, 0x14(r1) lfd f0, 0x10(r1) stw r3, 0x1c(r1) fsubs f2, f0, f1 stw r5, 0x18(r1) lfd f0, 0x18(r1) fsubs f0, f0, f1 fmuls f2, f2, f0 bge lbl_800A9D80 lwz r0, 0x1a8(r27) stw r5, 0x20(r1) stw r0, 0x24(r1) lfd f0, 0x20(r1) fsubs f0, f0, f1 fadds f2, f2, f0 lbl_800A9D80: lwz r3, 0x254(r27) lis r0, 0x4330 stw r0, 0x28(r1) lfd f1, lbl_80516EC0@sda21(r2) stw r3, 0x2c(r1) lfd f0, 0x28(r1) fsubs f0, f0, f1 fdivs f2, f2, f0 stfs f2, 0x1b8(r27) lwz r3, 0x1a8(r27) lwz r0, 0x260(r27) addi r3, r3, 0x190 cmplw r3, r0 blt lbl_800A9EAC lbz r0, 0x1b0(r27) cmplwi r0, 0 bne lbl_800A9EAC lbz r0, 0x258(r27) cmplwi r0, 0 beq lbl_800A9E1C lwz r3, 0x1ac(r27) lwz r0, 0x24c(r27) addi r3, r3, 1 cmplw r3, r0 blt lbl_800A9DE8 li r3, 0 lbl_800A9DE8: lwz r4, 0x25c(r27) mullw r0, r3, r31 divwu r3, r4, r31 mullw r3, r3, r31 subf r3, r3, r4 add r0, r3, r0 stw r0, 0x110(r29) lwz r0, 0x110(r29) stw r0, 0x210(r27) lwz r0, 0x21c(r27) ori r0, r0, 2 stw r0, 0x21c(r27) b lbl_800A9E34 lbl_800A9E1C: li r0, 0 sth r0, 0x102(r29) sth r0, 0x218(r27) lwz r0, 0x21c(r27) ori r0, r0, 8 stw r0, 0x21c(r27) lbl_800A9E34: lwz r7, 0x260(r27) li r0, 1 lwz r5, 0x1ac(r27) divwu r6, r7, r31 lwz r4, 0x24c(r27) lwz r3, 0x74(r29) mullw r6, r6, r31 mullw r5, r5, r31 subf r6, r6, r7 mullw r4, r31, r4 add r5, r6, r5 subf r4, r5, r4 subf r3, r4, r3 stw r3, 0x74(r29) lwz r3, 0x74(r29) stw r3, 0x20c(r27) lwz r3, 0x21c(r27) ori r3, r3, 1 stw r3, 0x21c(r27) lwz r3, 0x260(r27) lwz r4, 0x25c(r27) addi r3, r3, -1 lwz r5, 0x1ac(r27) divwu r4, r4, r31 divwu r3, r3, r31 subf r3, r4, r3 add r3, r3, r5 addi r3, r3, 1 stw r3, 0x1ac(r27) stb r0, 0x1b0(r27) lbl_800A9EAC: lwz r3, 0xec(r28) lwz r0, 0x70(r29) subf. r3, r3, r0 beq lbl_800A9EC0 addi r3, r3, -1 lbl_800A9EC0: lwz r0, sBlockSize__13JASAramStream@sda21(r13) lwz r4, 0x1a0(r27) divwu r30, r3, r0 cmplw r30, r4 beq lbl_800AA048 xor r0, r4, r30 lis r3, loadToAramTask__13JASAramStreamFPv@ha cntlzw r0, r0 li r26, 0 slw r0, r4, r0 addi r25, r3, loadToAramTask__13JASAramStreamFPv@l srwi r24, r0, 0x1f b lbl_800A9F50 lbl_800A9EF4: lwz r3, sLoadThread__13JASAramStream@sda21(r13) mr r4, r25 mr r5, r27 bl sendCmdMsg__13JASTaskThreadFPFPv_vPv cmpwi r3, 0 bne lbl_800A9F18 li r0, 1 stb r0, sFatalErrorFlag__13JASAramStream@sda21(r13) b lbl_800A9F5C lbl_800A9F18: bl OSDisableInterrupts lwz r4, 0x208(r27) stw r3, 8(r1) addi r0, r4, 1 stw r0, 0x208(r27) bl OSRestoreInterrupts lwz r3, 0x1a0(r27) addi r0, r3, 1 stw r0, 0x1a0(r27) lwz r3, 0x1a0(r27) lwz r0, 0x24c(r27) cmplw r3, r0 blt lbl_800A9F50 stw r26, 0x1a0(r27) lbl_800A9F50: lwz r0, 0x1a0(r27) cmplw r30, r0 bne lbl_800A9EF4 lbl_800A9F5C: cmplwi r24, 0 beq lbl_800AA078 lwz r3, 0x24c(r27) lwz r0, 0x1ac(r27) subf r0, r3, r0 stw r0, 0x1ac(r27) lbz r0, 0x19d(r27) cmplwi r0, 0 beq lbl_800A9FE0 lbz r0, 0x1b0(r27) cmplwi r0, 0 bne lbl_800A9FAC lwz r0, 0x74(r29) add r0, r0, r31 stw r0, 0x74(r29) lwz r0, 0x74(r29) stw r0, 0x20c(r27) lwz r0, 0x21c(r27) ori r0, r0, 1 stw r0, 0x21c(r27) lbl_800A9FAC: lwz r3, 0x114(r29) li r0, 0 add r3, r3, r31 stw r3, 0x114(r29) lwz r3, 0x114(r29) stw r3, 0x214(r27) lwz r3, 0x21c(r27) ori r3, r3, 4 stw r3, 0x21c(r27) lwz r3, 0x250(r27) stw r3, 0x24c(r27) stb r0, 0x19d(r27) b lbl_800AA078 lbl_800A9FE0: lwz r3, 0x250(r27) lwz r0, 0x24c(r27) addi r3, r3, -1 cmplw r0, r3 beq lbl_800AA078 stw r3, 0x24c(r27) lwz r0, 0x114(r29) subf r0, r31, r0 stw r0, 0x114(r29) lwz r0, 0x114(r29) stw r0, 0x214(r27) lwz r0, 0x21c(r27) ori r0, r0, 4 stw r0, 0x21c(r27) lbz r0, 0x1b0(r27) cmplwi r0, 0 bne lbl_800AA078 lwz r0, 0x74(r29) subf r0, r31, r0 stw r0, 0x74(r29) lwz r0, 0x74(r29) stw r0, 0x20c(r27) lwz r0, 0x21c(r27) ori r0, r0, 1 stw r0, 0x21c(r27) b lbl_800AA078 lbl_800AA048: lwz r0, 0x208(r27) cmplwi r0, 0 bne lbl_800AA078 lbz r0, sSystemPauseFlag__13JASAramStream@sda21(r13) cmplwi r0, 0 bne lbl_800AA078 lbz r0, 0x19e(r27) rlwinm r0, r0, 0, 0x1f, 0x1d stb r0, 0x19e(r27) lbz r0, 0x19e(r27) rlwinm r0, r0, 0, 0x1e, 0x1c stb r0, 0x19e(r27) lbl_800AA078: lwz r3, 0x74(r29) lhz r0, 0x64(r29) add r0, r3, r0 stw r0, 0x1a4(r27) lwz r3, 0x250(r27) lwz r4, 0x208(r27) addi r0, r3, -2 cmplw r4, r0 blt lbl_800AA0FC lbz r0, 0x19e(r27) ori r0, r0, 4 stb r0, 0x19e(r27) b lbl_800AA0FC lbl_800AA0AC: lwz r0, 0x21c(r27) clrlwi. r0, r0, 0x1f beq lbl_800AA0C0 lwz r0, 0x20c(r27) stw r0, 0x74(r29) lbl_800AA0C0: lwz r0, 0x21c(r27) rlwinm. r0, r0, 0, 0x1e, 0x1e beq lbl_800AA0D4 lwz r0, 0x210(r27) stw r0, 0x110(r29) lbl_800AA0D4: lwz r0, 0x21c(r27) rlwinm. r0, r0, 0, 0x1d, 0x1d beq lbl_800AA0E8 lwz r0, 0x214(r27) stw r0, 0x114(r29) lbl_800AA0E8: lwz r0, 0x21c(r27) rlwinm. r0, r0, 0, 0x1c, 0x1c beq lbl_800AA0FC lhz r0, 0x218(r27) sth r0, 0x102(r29) lbl_800AA0FC: lwz r0, 0x180(r27) li r3, 0 cmplw r28, r0 beq lbl_800AA160 lwz r0, 0x184(r27) li r3, 1 cmplw r28, r0 beq lbl_800AA160 lwz r0, 0x188(r27) li r3, 2 cmplw r28, r0 beq lbl_800AA160 lwz r0, 0x18c(r27) li r3, 3 cmplw r28, r0 beq lbl_800AA160 lwz r0, 0x190(r27) li r3, 4 cmplw r28, r0 beq lbl_800AA160 lwz r0, 0x194(r27) li r3, 5 cmplw r28, r0 beq lbl_800AA160 li r3, 6 lbl_800AA160: slwi r0, r3, 1 add r3, r27, r0 lha r0, 0x220(r3) sth r0, 0x104(r29) lha r0, 0x22c(r3) sth r0, 0x106(r29) b lbl_800AA27C lbl_800AA17C: lwz r3, 0x180(r27) li r4, 0 li r0, 0 cmplw r28, r3 bne lbl_800AA198 stw r0, 0x180(r27) b lbl_800AA1A4 lbl_800AA198: cmplwi r3, 0 beq lbl_800AA1A4 li r4, 1 lbl_800AA1A4: lwz r3, 0x184(r27) cmplw r28, r3 bne lbl_800AA1B8 stw r0, 0x184(r27) b lbl_800AA1C4 lbl_800AA1B8: cmplwi r3, 0 beq lbl_800AA1C4 li r4, 1 lbl_800AA1C4: lwz r3, 0x188(r27) cmplw r28, r3 bne lbl_800AA1D8 stw r0, 0x188(r27) b lbl_800AA1E4 lbl_800AA1D8: cmplwi r3, 0 beq lbl_800AA1E4 li r4, 1 lbl_800AA1E4: lwz r3, 0x18c(r27) cmplw r28, r3 bne lbl_800AA1F8 stw r0, 0x18c(r27) b lbl_800AA204 lbl_800AA1F8: cmplwi r3, 0 beq lbl_800AA204 li r4, 1 lbl_800AA204: lwz r3, 0x190(r27) cmplw r28, r3 bne lbl_800AA218 stw r0, 0x190(r27) b lbl_800AA224 lbl_800AA218: cmplwi r3, 0 beq lbl_800AA224 li r4, 1 lbl_800AA224: lwz r3, 0x194(r27) cmplw r28, r3 bne lbl_800AA238 stw r0, 0x194(r27) b lbl_800AA244 lbl_800AA238: cmplwi r3, 0 beq lbl_800AA244 li r4, 1 lbl_800AA244: clrlwi. r0, r4, 0x18 bne lbl_800AA27C li r0, 1 lis r3, finishTask__13JASAramStreamFPv@ha stb r0, 0x204(r27) addi r4, r3, finishTask__13JASAramStreamFPv@l mr r5, r27 lwz r3, sLoadThread__13JASAramStream@sda21(r13) bl sendCmdMsg__13JASTaskThreadFPFPv_vPv cmpwi r3, 0 bne lbl_800AA27C li r0, 1 stb r0, sFatalErrorFlag__13JASAramStream@sda21(r13) b lbl_800AA294 lbl_800AA27C: lbz r4, 0x19e(r27) mr r3, r28 neg r0, r4 or r0, r0, r4 srwi r4, r0, 0x1f bl setPauseFlag__10JASChannelFb lbl_800AA294: lmw r24, 0x30(r1) lwz r0, 0x54(r1) mtlr r0 addi r1, r1, 0x50 blr */ } /* * --INFO-- * Address: 800AA2A8 * Size: 0001E4 */ void JASAramStream::channelProc() { /* stwu r1, -0x20(r1) mflr r0 stw r0, 0x24(r1) stw r31, 0x1c(r1) mr r31, r3 stw r30, 0x18(r1) li r30, 1 b lbl_800AA2F0 lbl_800AA2C8: lwz r0, 8(r1) cmpwi r0, 5 beq lbl_800AA2EC bge lbl_800AA2F0 cmpwi r0, 4 bge lbl_800AA2E4 b lbl_800AA2F0 lbl_800AA2E4: stb r30, 0x19c(r31) b lbl_800AA2F0 lbl_800AA2EC: stb r30, 0x19d(r31) lbl_800AA2F0: addi r3, r31, 0x20 addi r4, r1, 8 li r5, 0 bl OSReceiveMessage cmpwi r3, 0 bne lbl_800AA2C8 lbz r0, 0x19c(r31) cmplwi r0, 0 bne lbl_800AA388 li r3, 0 b lbl_800AA474 b lbl_800AA388 lbl_800AA320: lwz r3, 8(r1) clrlwi r0, r3, 0x18 cmpwi r0, 2 beq lbl_800AA36C bge lbl_800AA344 cmpwi r0, 0 beq lbl_800AA350 bge lbl_800AA35C b lbl_800AA388 lbl_800AA344: cmpwi r0, 4 bge lbl_800AA388 b lbl_800AA37C lbl_800AA350: mr r3, r31 bl channelStart__13JASAramStreamFv b lbl_800AA388 lbl_800AA35C: srwi r4, r3, 0x10 mr r3, r31 bl channelStop__13JASAramStreamFUs b lbl_800AA388 lbl_800AA36C: lbz r0, 0x19e(r31) ori r0, r0, 1 stb r0, 0x19e(r31) b lbl_800AA388 lbl_800AA37C: lbz r0, 0x19e(r31) rlwinm r0, r0, 0, 0x18, 0x1e stb r0, 0x19e(r31) lbl_800AA388: mr r3, r31 addi r4, r1, 8 li r5, 0 bl OSReceiveMessage cmpwi r3, 0 bne lbl_800AA320 lwz r0, 0x180(r31) cmplwi r0, 0 bne lbl_800AA3B4 li r3, 0 b lbl_800AA474 lbl_800AA3B4: lbz r0, sFatalErrorFlag__13JASAramStream@sda21(r13) cmplwi r0, 0 beq lbl_800AA3CC lbz r0, 0x19e(r31) ori r0, r0, 8 stb r0, 0x19e(r31) lbl_800AA3CC: lbz r0, sSystemPauseFlag__13JASAramStream@sda21(r13) cmplwi r0, 0 beq lbl_800AA3E4 lbz r0, 0x19e(r31) ori r0, r0, 2 stb r0, 0x19e(r31) lbl_800AA3E4: mr r3, r31 li r5, 0 b lbl_800AA438 lbl_800AA3F0: lfs f1, 0x264(r31) lfs f0, 0x26c(r3) lwz r4, 0x180(r3) fmuls f0, f1, f0 stfs f0, 0x100(r4) lfs f0, 0x268(r31) stfs f0, 0x104(r4) lbz r0, 0x2d8(r31) cmplwi r0, 0 beq lbl_800AA420 lfs f0, 0x284(r3) stfs f0, 0xd0(r4) lbl_800AA420: lfs f0, 0x29c(r3) addi r5, r5, 1 stfs f0, 0xd8(r4) lfs f0, 0x2b4(r3) addi r3, r3, 4 stfs f0, 0xe0(r4) lbl_800AA438: lhz r4, 0x24a(r31) cmpw r5, r4 blt lbl_800AA3F0 lbz r0, 0x2d8(r31) cmplwi r0, 0 bne lbl_800AA470 cmplwi r4, 2 bne lbl_800AA470 lfs f1, lbl_80516EB0@sda21(r2) lwz r3, 0x180(r31) lfs f0, lbl_80516EB4@sda21(r2) stfs f1, 0xd0(r3) lwz r3, 0x184(r31) stfs f0, 0xd0(r3) lbl_800AA470: li r3, 0 lbl_800AA474: lwz r0, 0x24(r1) lwz r31, 0x1c(r1) lwz r30, 0x18(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /* * --INFO-- * Address: 800AA48C * Size: 000240 */ void JASAramStream::channelStart() { /* stwu r1, -0x60(r1) mflr r0 stw r0, 0x64(r1) stfd f31, 0x50(r1) psq_st f31, 88(r1), 0, qr0 stmw r21, 0x24(r1) mr r23, r3 lhz r0, 0x248(r3) cmpwi r0, 1 beq lbl_800AA4CC bge lbl_800AA4D0 cmpwi r0, 0 bge lbl_800AA4C4 b lbl_800AA4D0 lbl_800AA4C4: li r26, 0 b lbl_800AA4D0 lbl_800AA4CC: li r26, 3 lbl_800AA4D0: lis r3, OSC_ENV@ha lfd f31, lbl_80516EC0@sda21(r2) mr r28, r23 mr r27, r23 addi r31, r3, OSC_ENV@l li r25, 0 lis r30, 0x4330 b lbl_800AA69C lbl_800AA4F0: addi r24, r28, 0x90 li r3, -1 stb r26, 0x90(r28) li r0, 0 stw r3, 0xa0(r28) stw r0, 0xa4(r28) lhz r0, 0x248(r23) lwz r4, 0x24c(r23) cmplwi r0, 0 bne lbl_800AA534 lwz r0, sBlockSize__13JASAramStream@sda21(r13) lis r3, 0x38E38E39@ha addi r3, r3, 0x38E38E39@l slwi r0, r0, 4 mulhwu r0, r3, r0 srwi r0, r0, 1 b lbl_800AA53C lbl_800AA534: lwz r0, sBlockSize__13JASAramStream@sda21(r13) srwi r0, r0, 1 lbl_800AA53C: mullw r4, r4, r0 li r3, 0 addi r0, r2, one$870@sda21 stw r4, 0x18(r24) lwz r4, 0x18(r24) stw r4, 0x1c(r24) sth r3, 0x20(r24) sth r3, 0x22(r24) stw r0, 0x24(r24) lwz r0, "sInstance__123JASSingletonHolder<62JASMemPool<10JASChannel,Q217JASThreadingModel14SingleThreaded>,Q217JASCreationPolicy15NewFromRootHeap>"@sda21(r13) cmplwi r0, 0 bne lbl_800AA5A8 bl OSDisableInterrupts lwz r0, "sInstance__123JASSingletonHolder<62JASMemPool<10JASChannel,Q217JASThreadingModel14SingleThreaded>,Q217JASCreationPolicy15NewFromRootHeap>"@sda21(r13) stw r3, 8(r1) cmplwi r0, 0 bne lbl_800AA5A0 lwz r4, JASDram@sda21(r13) li r3, 0xc li r5, 0 bl __nw__FUlP7JKRHeapi or. r29, r3, r3 beq lbl_800AA59C bl __ct__17JASGenericMemPoolFv lbl_800AA59C: stw r29, "sInstance__123JASSingletonHolder<62JASMemPool<10JASChannel,Q217JASThreadingModel14SingleThreaded>,Q217JASCreationPolicy15NewFromRootHeap>"@sda21(r13) lbl_800AA5A0: lwz r3, 8(r1) bl OSRestoreInterrupts lbl_800AA5A8: lwz r3, "sInstance__123JASSingletonHolder<62JASMemPool<10JASChannel,Q217JASThreadingModel14SingleThreaded>,Q217JASCreationPolicy15NewFromRootHeap>"@sda21(r13) li r4, 0x118 bl alloc__17JASGenericMemPoolFUl or. r29, r3, r3 beq lbl_800AA5D0 lis r4, channelCallback__13JASAramStreamFUlP10JASChannelPQ26JASDsp8TChannelPv@ha mr r5, r23 addi r4, r4, channelCallback__13JASAramStreamFUlP10JASChannelPQ26JASDsp8TChannelPv@l bl __ct__10JASChannelFPFUlP10JASChannelPQ26JASDsp8TChannelPv_vPv mr r29, r3 lbl_800AA5D0: lfs f1, lbl_80516EB0@sda21(r2) li r0, 0x7f sth r0, 0xbc(r29) mr r3, r29 fmr f2, f1 lfs f3, lbl_80516EB4@sda21(r2) bl setPanPower__10JASChannelFfff li r0, 1 mr r22, r23 stb r0, 0x108(r29) li r21, 0 stb r0, 0x109(r29) stb r0, 0x10a(r29) lbl_800AA604: lhz r5, 0x2cc(r22) mr r3, r29 mr r4, r21 bl setMixConfig__10JASChannelFiUs addi r21, r21, 1 addi r22, r22, 2 cmpwi r21, 6 blt lbl_800AA604 bl getDacRate__9JASDriverFv lwz r0, 0x254(r23) mr r3, r29 stw r30, 0x10(r1) mr r5, r31 li r4, 0 stw r0, 0x14(r1) lfd f0, 0x10(r1) fsubs f0, f0, f31 fdivs f0, f0, f1 stfs f0, 0xf0(r29) lfs f0, 0xf0(r29) stfs f0, 0xf8(r29) bl setOscInit__10JASChannelFiPCQ213JASOscillator4Data stw r24, 0xe8(r29) li r0, 0 mr r3, r29 lwz r5, sBlockSize__13JASAramStream@sda21(r13) lwz r4, 0x250(r23) lwz r6, 0x238(r23) mullw r4, r5, r4 mullw r4, r25, r4 add r4, r6, r4 stw r4, 0xec(r29) stb r0, 0xe4(r29) bl playForce__10JASChannelFv stw r29, 0x180(r27) addi r28, r28, 0x28 addi r27, r27, 4 addi r25, r25, 1 lbl_800AA69C: lhz r0, 0x24a(r23) cmpw r25, r0 blt lbl_800AA4F0 li r0, 0 stw r0, 0x198(r23) psq_l f31, 88(r1), 0, qr0 lfd f31, 0x50(r1) lmw r21, 0x24(r1) lwz r0, 0x64(r1) mtlr r0 addi r1, r1, 0x60 blr */ } /* * --INFO-- * Address: 800AA6CC * Size: 000078 */ void JASAramStream::channelStop(unsigned short) { /* stwu r1, -0x20(r1) mflr r0 stw r0, 0x24(r1) stw r31, 0x1c(r1) stw r30, 0x18(r1) li r30, 0 stw r29, 0x14(r1) mr r29, r4 stw r28, 0x10(r1) mr r28, r3 mr r31, r28 b lbl_800AA718 lbl_800AA6FC: lwz r3, 0x180(r31) cmplwi r3, 0 beq lbl_800AA710 mr r4, r29 bl release__10JASChannelFUs lbl_800AA710: addi r31, r31, 4 addi r30, r30, 1 lbl_800AA718: lhz r0, 0x24a(r28) cmpw r30, r0 blt lbl_800AA6FC lwz r0, 0x24(r1) lwz r31, 0x1c(r1) lwz r30, 0x18(r1) lwz r29, 0x14(r1) lwz r28, 0x10(r1) mtlr r0 addi r1, r1, 0x20 blr .4byte 0x00000000 /* unknown instruction */ .4byte 0x00000000 /* unknown instruction */ .4byte 0x00000000 /* unknown instruction */ .4byte 0x00000000 /* unknown instruction */ .4byte 0x00000000 /* unknown instruction */ .4byte 0x00000000 /* unknown instruction */ .4byte 0x00000000 /* unknown instruction */ * / }
20.549302
150
0.574319
projectPiki
beabcdf481ed6eff8a8ca9c18d7bdc6bf003558c
1,754
cpp
C++
KFPlugin/KFHttpClient/KFHttpThread.cpp
282951387/KFrame
5d6e953f7cc312321c36632715259394ca67144c
[ "Apache-2.0" ]
1
2021-04-26T09:31:32.000Z
2021-04-26T09:31:32.000Z
KFPlugin/KFHttpClient/KFHttpThread.cpp
282951387/KFrame
5d6e953f7cc312321c36632715259394ca67144c
[ "Apache-2.0" ]
null
null
null
KFPlugin/KFHttpClient/KFHttpThread.cpp
282951387/KFrame
5d6e953f7cc312321c36632715259394ca67144c
[ "Apache-2.0" ]
null
null
null
#include "KFHttpThread.hpp" #include "KFHttp/KFHttp.h" namespace KFrame { KFHttpThread::KFHttpThread() { _thread_run = true; _http_response_list.InitQueue( 20000u ); KFThread::CreateThread( this, &KFHttpThread::RunHttpRequest, __FUNC_LINE__ ); } KFHttpThread::~KFHttpThread() { _thread_run = false; { KFLocker locker( _kf_req_mutex ); for ( auto httpdata : _http_request_list ) { __KF_DELETE__( KFHttpData, httpdata ); } _http_request_list.clear(); } } void KFHttpThread::ShutDown() { _thread_run = false; } void KFHttpThread::AddHttpRequest( KFHttpData* httpdata ) { KFLocker locker( _kf_req_mutex ); _http_request_list.push_back( httpdata ); } void KFHttpThread::RunHttpRequest() { while ( _thread_run ) { std::list< KFHttpData* > templist; { KFLocker locker( _kf_req_mutex ); templist.swap( _http_request_list ); } for ( auto httpdata : templist ) { httpdata->Request(); _http_response_list.PushObject( httpdata ); } KFThread::Sleep( 1 ); } } void KFHttpThread::RunHttpResponse() { auto responsecount = 0u; do { auto httpdata = _http_response_list.PopObject(); if ( httpdata == nullptr ) { break; } ++responsecount; httpdata->Response(); __KF_DELETE__( KFHttpData, httpdata ); } while ( responsecount <= 200u ); } }
23.386667
85
0.518814
282951387
beb54bfd3c776f6efddc4bdc818813d8bc85a1d1
345
cpp
C++
src/DupLogger.cpp
DIYEmbeddedSystems/Logger
b3ac778786253bdcd298e4d8c04b161d2092c07b
[ "MIT" ]
null
null
null
src/DupLogger.cpp
DIYEmbeddedSystems/Logger
b3ac778786253bdcd298e4d8c04b161d2092c07b
[ "MIT" ]
null
null
null
src/DupLogger.cpp
DIYEmbeddedSystems/Logger
b3ac778786253bdcd298e4d8c04b161d2092c07b
[ "MIT" ]
null
null
null
#include <Arduino.h> #include <ArduinoLogger.h> #include <DupLogger.h> DupLogger::DupLogger(Logger &logger1, Logger &logger2) : _logger1(logger1), _logger2(logger2) { info("DupLogger constructed"); } void DupLogger::output(const char *log_buffer, size_t len) { _logger1.output(log_buffer, len); _logger2.output(log_buffer, len); }
20.294118
58
0.730435
DIYEmbeddedSystems
beb8147403f3f64a7e1617135d0cc76b78921430
835
cpp
C++
706B.cpp
JiangWeibeta/Answers-to-Codeforces-Problems
f258ed0d441f587551ae0fc55215dca189a9dcef
[ "Apache-2.0" ]
1
2021-10-30T02:17:29.000Z
2021-10-30T02:17:29.000Z
706B.cpp
JiangWeibeta/Answers-to-codeforces-problemset
f258ed0d441f587551ae0fc55215dca189a9dcef
[ "Apache-2.0" ]
null
null
null
706B.cpp
JiangWeibeta/Answers-to-codeforces-problemset
f258ed0d441f587551ae0fc55215dca189a9dcef
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <iostream> #include <stdlib.h> #include <vector> using namespace std; int main() { int len = 0; cin >> len; vector<int> vc(len); for (int i = 0; i < len; i++) { cin >> vc[i]; } sort(vc.begin(), vc.end()); int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { int tmp = 0; cin >> tmp; int left = 0, right = len; int ans = 0; while (left < right) { int mid = (left + right) / 2; if (vc[mid] <= tmp) { left = mid + 1; } else { right = mid; } } ans = left; cout << ans << endl; } system("pause"); return 0; }
18.977273
42
0.361677
JiangWeibeta
bebc043e1bd065c318d08aafc83b2e1ae34188a6
813
hpp
C++
Library/Source/EnergyManager/Utility/Units/SIUnit.hpp
NB4444/BachelorProjectEnergyManager
d1fd93dcc83af6d6acd36b7efda364ac2aab90eb
[ "MIT" ]
null
null
null
Library/Source/EnergyManager/Utility/Units/SIUnit.hpp
NB4444/BachelorProjectEnergyManager
d1fd93dcc83af6d6acd36b7efda364ac2aab90eb
[ "MIT" ]
null
null
null
Library/Source/EnergyManager/Utility/Units/SIUnit.hpp
NB4444/BachelorProjectEnergyManager
d1fd93dcc83af6d6acd36b7efda364ac2aab90eb
[ "MIT" ]
null
null
null
#pragma once #include "EnergyManager/Utility/Units/Unit.hpp" namespace EnergyManager { namespace Utility { namespace Units { /** * SI prefix types. */ enum class SIPrefix { YOCTO = -24, ZEPTO = -21, ATTO = -18, FEMTO = -15, PICO = -12, NANO = -9, MICRO = -6, MILLI = -3, CENTI = -2, DECI = -1, NONE = 0, DEKA = 1, HECTO = 2, KILO = 3, MEGA = 6, GIGA = 9, TERA = 12, PETA = 15, EXA = 18, ZETTA = 21, YOTTA = 24 }; /** * Represents an SI value. * @tparam Self The type of the class. * @tparam Type The type of the value. */ template<typename Self, typename Type> class SIUnit : public Unit<Self, Type, SIPrefix> { public: using Unit<Self, Type, SIPrefix>::Unit; }; } } }
17.297872
53
0.530135
NB4444
bebdf80ff5a9cc18f8b7289fd0fbc26537c76609
13,298
cpp
C++
parsers/arg_parser/generated/ArgumentListLexer.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
307
2015-04-10T13:27:32.000Z
2022-03-21T03:30:38.000Z
parsers/arg_parser/generated/ArgumentListLexer.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
2,231
2015-04-27T10:47:35.000Z
2022-03-31T19:22:37.000Z
parsers/arg_parser/generated/ArgumentListLexer.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
282
2015-01-05T12:16:57.000Z
2022-03-28T04:45:11.000Z
// Generated from /media/cache/code/asarium/fs2open.github.com/parsers/arg_parser/ArgumentList.g4 by ANTLR 4.8 #include "ArgumentListLexer.h" using namespace antlr4; ArgumentListLexer::ArgumentListLexer(CharStream *input) : Lexer(input) { _interpreter = new atn::LexerATNSimulator(this, _atn, _decisionToDFA, _sharedContextCache); } ArgumentListLexer::~ArgumentListLexer() { delete _interpreter; } std::string ArgumentListLexer::getGrammarFileName() const { return "ArgumentList.g4"; } const std::vector<std::string>& ArgumentListLexer::getRuleNames() const { return _ruleNames; } const std::vector<std::string>& ArgumentListLexer::getChannelNames() const { return _channelNames; } const std::vector<std::string>& ArgumentListLexer::getModeNames() const { return _modeNames; } const std::vector<std::string>& ArgumentListLexer::getTokenNames() const { return _tokenNames; } dfa::Vocabulary& ArgumentListLexer::getVocabulary() const { return _vocabulary; } const std::vector<uint16_t> ArgumentListLexer::getSerializedATN() const { return _serializedATN; } const atn::ATN& ArgumentListLexer::getATN() const { return _atn; } // Static vars and initialization. std::vector<dfa::DFA> ArgumentListLexer::_decisionToDFA; atn::PredictionContextCache ArgumentListLexer::_sharedContextCache; // We own the ATN which in turn owns the ATN states. atn::ATN ArgumentListLexer::_atn; std::vector<uint16_t> ArgumentListLexer::_serializedATN; std::vector<std::string> ArgumentListLexer::_ruleNames = { u8"COMMA", u8"EQUALS", u8"STRING", u8"NIL", u8"TRUE", u8"FALSE", u8"FUNCTION", u8"VARARGS_SPECIFIER", u8"NUMBER", u8"TYPE_ALT", u8"L_BRACKET", u8"R_BRACKET", u8"L_PAREN", u8"R_PAREN", u8"L_CURLY", u8"R_CURLY", u8"ARROW", u8"ITERATOR", u8"L_ANGLE_BRACKET", u8"R_ANGLE_BRACKET", u8"ARG_COMMENT", u8"ID", u8"SPACE", u8"OTHER" }; std::vector<std::string> ArgumentListLexer::_channelNames = { "DEFAULT_TOKEN_CHANNEL", "HIDDEN" }; std::vector<std::string> ArgumentListLexer::_modeNames = { u8"DEFAULT_MODE" }; std::vector<std::string> ArgumentListLexer::_literalNames = { "", u8"','", u8"'='", "", u8"'nil'", u8"'true'", u8"'false'", u8"'function'", u8"'...'", "", "", u8"'['", u8"']'", u8"'('", u8"')'", u8"'{'", u8"'}'", u8"'=>'", u8"'iterator'", u8"'<'", u8"'>'" }; std::vector<std::string> ArgumentListLexer::_symbolicNames = { "", u8"COMMA", u8"EQUALS", u8"STRING", u8"NIL", u8"TRUE", u8"FALSE", u8"FUNCTION", u8"VARARGS_SPECIFIER", u8"NUMBER", u8"TYPE_ALT", u8"L_BRACKET", u8"R_BRACKET", u8"L_PAREN", u8"R_PAREN", u8"L_CURLY", u8"R_CURLY", u8"ARROW", u8"ITERATOR", u8"L_ANGLE_BRACKET", u8"R_ANGLE_BRACKET", u8"ARG_COMMENT", u8"ID", u8"SPACE", u8"OTHER" }; dfa::Vocabulary ArgumentListLexer::_vocabulary(_literalNames, _symbolicNames); std::vector<std::string> ArgumentListLexer::_tokenNames; ArgumentListLexer::Initializer::Initializer() { // This code could be in a static initializer lambda, but VS doesn't allow access to private class members from there. for (size_t i = 0; i < _symbolicNames.size(); ++i) { std::string name = _vocabulary.getLiteralName(i); if (name.empty()) { name = _vocabulary.getSymbolicName(i); } if (name.empty()) { _tokenNames.push_back("<INVALID>"); } else { _tokenNames.push_back(name); } } _serializedATN = { 0x3, 0x608b, 0xa72a, 0x8133, 0xb9ed, 0x417c, 0x3be7, 0x7786, 0x5964, 0x2, 0x1a, 0xb8, 0x8, 0x1, 0x4, 0x2, 0x9, 0x2, 0x4, 0x3, 0x9, 0x3, 0x4, 0x4, 0x9, 0x4, 0x4, 0x5, 0x9, 0x5, 0x4, 0x6, 0x9, 0x6, 0x4, 0x7, 0x9, 0x7, 0x4, 0x8, 0x9, 0x8, 0x4, 0x9, 0x9, 0x9, 0x4, 0xa, 0x9, 0xa, 0x4, 0xb, 0x9, 0xb, 0x4, 0xc, 0x9, 0xc, 0x4, 0xd, 0x9, 0xd, 0x4, 0xe, 0x9, 0xe, 0x4, 0xf, 0x9, 0xf, 0x4, 0x10, 0x9, 0x10, 0x4, 0x11, 0x9, 0x11, 0x4, 0x12, 0x9, 0x12, 0x4, 0x13, 0x9, 0x13, 0x4, 0x14, 0x9, 0x14, 0x4, 0x15, 0x9, 0x15, 0x4, 0x16, 0x9, 0x16, 0x4, 0x17, 0x9, 0x17, 0x4, 0x18, 0x9, 0x18, 0x4, 0x19, 0x9, 0x19, 0x3, 0x2, 0x3, 0x2, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x4, 0x7, 0x4, 0x3a, 0xa, 0x4, 0xc, 0x4, 0xe, 0x4, 0x3d, 0xb, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x7, 0x4, 0x42, 0xa, 0x4, 0xc, 0x4, 0xe, 0x4, 0x45, 0xb, 0x4, 0x3, 0x4, 0x5, 0x4, 0x48, 0xa, 0x4, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x9, 0x3, 0x9, 0x3, 0x9, 0x3, 0x9, 0x3, 0xa, 0x5, 0xa, 0x67, 0xa, 0xa, 0x3, 0xa, 0x6, 0xa, 0x6a, 0xa, 0xa, 0xd, 0xa, 0xe, 0xa, 0x6b, 0x3, 0xa, 0x6, 0xa, 0x6f, 0xa, 0xa, 0xd, 0xa, 0xe, 0xa, 0x70, 0x3, 0xa, 0x3, 0xa, 0x7, 0xa, 0x75, 0xa, 0xa, 0xc, 0xa, 0xe, 0xa, 0x78, 0xb, 0xa, 0x3, 0xa, 0x3, 0xa, 0x6, 0xa, 0x7c, 0xa, 0xa, 0xd, 0xa, 0xe, 0xa, 0x7d, 0x5, 0xa, 0x80, 0xa, 0xa, 0x3, 0xb, 0x3, 0xb, 0x3, 0xc, 0x3, 0xc, 0x3, 0xd, 0x3, 0xd, 0x3, 0xe, 0x3, 0xe, 0x3, 0xf, 0x3, 0xf, 0x3, 0x10, 0x3, 0x10, 0x3, 0x11, 0x3, 0x11, 0x3, 0x12, 0x3, 0x12, 0x3, 0x12, 0x3, 0x13, 0x3, 0x13, 0x3, 0x13, 0x3, 0x13, 0x3, 0x13, 0x3, 0x13, 0x3, 0x13, 0x3, 0x13, 0x3, 0x13, 0x3, 0x14, 0x3, 0x14, 0x3, 0x15, 0x3, 0x15, 0x3, 0x16, 0x3, 0x16, 0x3, 0x16, 0x3, 0x16, 0x7, 0x16, 0xa4, 0xa, 0x16, 0xc, 0x16, 0xe, 0x16, 0xa7, 0xb, 0x16, 0x3, 0x16, 0x3, 0x16, 0x3, 0x16, 0x3, 0x17, 0x3, 0x17, 0x7, 0x17, 0xae, 0xa, 0x17, 0xc, 0x17, 0xe, 0x17, 0xb1, 0xb, 0x17, 0x3, 0x18, 0x3, 0x18, 0x3, 0x18, 0x3, 0x18, 0x3, 0x19, 0x3, 0x19, 0x3, 0xa5, 0x2, 0x1a, 0x3, 0x3, 0x5, 0x4, 0x7, 0x5, 0x9, 0x6, 0xb, 0x7, 0xd, 0x8, 0xf, 0x9, 0x11, 0xa, 0x13, 0xb, 0x15, 0xc, 0x17, 0xd, 0x19, 0xe, 0x1b, 0xf, 0x1d, 0x10, 0x1f, 0x11, 0x21, 0x12, 0x23, 0x13, 0x25, 0x14, 0x27, 0x15, 0x29, 0x16, 0x2b, 0x17, 0x2d, 0x18, 0x2f, 0x19, 0x31, 0x1a, 0x3, 0x2, 0x9, 0x5, 0x2, 0xc, 0xc, 0xf, 0xf, 0x24, 0x24, 0x5, 0x2, 0xc, 0xc, 0xf, 0xf, 0x29, 0x29, 0x3, 0x2, 0x32, 0x3b, 0x4, 0x2, 0x31, 0x31, 0x7e, 0x7e, 0x5, 0x2, 0x43, 0x5c, 0x61, 0x61, 0x63, 0x7c, 0x6, 0x2, 0x32, 0x3c, 0x43, 0x5c, 0x61, 0x61, 0x63, 0x7c, 0x5, 0x2, 0xb, 0xc, 0xf, 0xf, 0x22, 0x22, 0x2, 0xc3, 0x2, 0x3, 0x3, 0x2, 0x2, 0x2, 0x2, 0x5, 0x3, 0x2, 0x2, 0x2, 0x2, 0x7, 0x3, 0x2, 0x2, 0x2, 0x2, 0x9, 0x3, 0x2, 0x2, 0x2, 0x2, 0xb, 0x3, 0x2, 0x2, 0x2, 0x2, 0xd, 0x3, 0x2, 0x2, 0x2, 0x2, 0xf, 0x3, 0x2, 0x2, 0x2, 0x2, 0x11, 0x3, 0x2, 0x2, 0x2, 0x2, 0x13, 0x3, 0x2, 0x2, 0x2, 0x2, 0x15, 0x3, 0x2, 0x2, 0x2, 0x2, 0x17, 0x3, 0x2, 0x2, 0x2, 0x2, 0x19, 0x3, 0x2, 0x2, 0x2, 0x2, 0x1b, 0x3, 0x2, 0x2, 0x2, 0x2, 0x1d, 0x3, 0x2, 0x2, 0x2, 0x2, 0x1f, 0x3, 0x2, 0x2, 0x2, 0x2, 0x21, 0x3, 0x2, 0x2, 0x2, 0x2, 0x23, 0x3, 0x2, 0x2, 0x2, 0x2, 0x25, 0x3, 0x2, 0x2, 0x2, 0x2, 0x27, 0x3, 0x2, 0x2, 0x2, 0x2, 0x29, 0x3, 0x2, 0x2, 0x2, 0x2, 0x2b, 0x3, 0x2, 0x2, 0x2, 0x2, 0x2d, 0x3, 0x2, 0x2, 0x2, 0x2, 0x2f, 0x3, 0x2, 0x2, 0x2, 0x2, 0x31, 0x3, 0x2, 0x2, 0x2, 0x3, 0x33, 0x3, 0x2, 0x2, 0x2, 0x5, 0x35, 0x3, 0x2, 0x2, 0x2, 0x7, 0x47, 0x3, 0x2, 0x2, 0x2, 0x9, 0x49, 0x3, 0x2, 0x2, 0x2, 0xb, 0x4d, 0x3, 0x2, 0x2, 0x2, 0xd, 0x52, 0x3, 0x2, 0x2, 0x2, 0xf, 0x58, 0x3, 0x2, 0x2, 0x2, 0x11, 0x61, 0x3, 0x2, 0x2, 0x2, 0x13, 0x66, 0x3, 0x2, 0x2, 0x2, 0x15, 0x81, 0x3, 0x2, 0x2, 0x2, 0x17, 0x83, 0x3, 0x2, 0x2, 0x2, 0x19, 0x85, 0x3, 0x2, 0x2, 0x2, 0x1b, 0x87, 0x3, 0x2, 0x2, 0x2, 0x1d, 0x89, 0x3, 0x2, 0x2, 0x2, 0x1f, 0x8b, 0x3, 0x2, 0x2, 0x2, 0x21, 0x8d, 0x3, 0x2, 0x2, 0x2, 0x23, 0x8f, 0x3, 0x2, 0x2, 0x2, 0x25, 0x92, 0x3, 0x2, 0x2, 0x2, 0x27, 0x9b, 0x3, 0x2, 0x2, 0x2, 0x29, 0x9d, 0x3, 0x2, 0x2, 0x2, 0x2b, 0x9f, 0x3, 0x2, 0x2, 0x2, 0x2d, 0xab, 0x3, 0x2, 0x2, 0x2, 0x2f, 0xb2, 0x3, 0x2, 0x2, 0x2, 0x31, 0xb6, 0x3, 0x2, 0x2, 0x2, 0x33, 0x34, 0x7, 0x2e, 0x2, 0x2, 0x34, 0x4, 0x3, 0x2, 0x2, 0x2, 0x35, 0x36, 0x7, 0x3f, 0x2, 0x2, 0x36, 0x6, 0x3, 0x2, 0x2, 0x2, 0x37, 0x3b, 0x7, 0x24, 0x2, 0x2, 0x38, 0x3a, 0xa, 0x2, 0x2, 0x2, 0x39, 0x38, 0x3, 0x2, 0x2, 0x2, 0x3a, 0x3d, 0x3, 0x2, 0x2, 0x2, 0x3b, 0x39, 0x3, 0x2, 0x2, 0x2, 0x3b, 0x3c, 0x3, 0x2, 0x2, 0x2, 0x3c, 0x3e, 0x3, 0x2, 0x2, 0x2, 0x3d, 0x3b, 0x3, 0x2, 0x2, 0x2, 0x3e, 0x48, 0x7, 0x24, 0x2, 0x2, 0x3f, 0x43, 0x7, 0x29, 0x2, 0x2, 0x40, 0x42, 0xa, 0x3, 0x2, 0x2, 0x41, 0x40, 0x3, 0x2, 0x2, 0x2, 0x42, 0x45, 0x3, 0x2, 0x2, 0x2, 0x43, 0x41, 0x3, 0x2, 0x2, 0x2, 0x43, 0x44, 0x3, 0x2, 0x2, 0x2, 0x44, 0x46, 0x3, 0x2, 0x2, 0x2, 0x45, 0x43, 0x3, 0x2, 0x2, 0x2, 0x46, 0x48, 0x7, 0x29, 0x2, 0x2, 0x47, 0x37, 0x3, 0x2, 0x2, 0x2, 0x47, 0x3f, 0x3, 0x2, 0x2, 0x2, 0x48, 0x8, 0x3, 0x2, 0x2, 0x2, 0x49, 0x4a, 0x7, 0x70, 0x2, 0x2, 0x4a, 0x4b, 0x7, 0x6b, 0x2, 0x2, 0x4b, 0x4c, 0x7, 0x6e, 0x2, 0x2, 0x4c, 0xa, 0x3, 0x2, 0x2, 0x2, 0x4d, 0x4e, 0x7, 0x76, 0x2, 0x2, 0x4e, 0x4f, 0x7, 0x74, 0x2, 0x2, 0x4f, 0x50, 0x7, 0x77, 0x2, 0x2, 0x50, 0x51, 0x7, 0x67, 0x2, 0x2, 0x51, 0xc, 0x3, 0x2, 0x2, 0x2, 0x52, 0x53, 0x7, 0x68, 0x2, 0x2, 0x53, 0x54, 0x7, 0x63, 0x2, 0x2, 0x54, 0x55, 0x7, 0x6e, 0x2, 0x2, 0x55, 0x56, 0x7, 0x75, 0x2, 0x2, 0x56, 0x57, 0x7, 0x67, 0x2, 0x2, 0x57, 0xe, 0x3, 0x2, 0x2, 0x2, 0x58, 0x59, 0x7, 0x68, 0x2, 0x2, 0x59, 0x5a, 0x7, 0x77, 0x2, 0x2, 0x5a, 0x5b, 0x7, 0x70, 0x2, 0x2, 0x5b, 0x5c, 0x7, 0x65, 0x2, 0x2, 0x5c, 0x5d, 0x7, 0x76, 0x2, 0x2, 0x5d, 0x5e, 0x7, 0x6b, 0x2, 0x2, 0x5e, 0x5f, 0x7, 0x71, 0x2, 0x2, 0x5f, 0x60, 0x7, 0x70, 0x2, 0x2, 0x60, 0x10, 0x3, 0x2, 0x2, 0x2, 0x61, 0x62, 0x7, 0x30, 0x2, 0x2, 0x62, 0x63, 0x7, 0x30, 0x2, 0x2, 0x63, 0x64, 0x7, 0x30, 0x2, 0x2, 0x64, 0x12, 0x3, 0x2, 0x2, 0x2, 0x65, 0x67, 0x7, 0x2f, 0x2, 0x2, 0x66, 0x65, 0x3, 0x2, 0x2, 0x2, 0x66, 0x67, 0x3, 0x2, 0x2, 0x2, 0x67, 0x7f, 0x3, 0x2, 0x2, 0x2, 0x68, 0x6a, 0x9, 0x4, 0x2, 0x2, 0x69, 0x68, 0x3, 0x2, 0x2, 0x2, 0x6a, 0x6b, 0x3, 0x2, 0x2, 0x2, 0x6b, 0x69, 0x3, 0x2, 0x2, 0x2, 0x6b, 0x6c, 0x3, 0x2, 0x2, 0x2, 0x6c, 0x80, 0x3, 0x2, 0x2, 0x2, 0x6d, 0x6f, 0x9, 0x4, 0x2, 0x2, 0x6e, 0x6d, 0x3, 0x2, 0x2, 0x2, 0x6f, 0x70, 0x3, 0x2, 0x2, 0x2, 0x70, 0x6e, 0x3, 0x2, 0x2, 0x2, 0x70, 0x71, 0x3, 0x2, 0x2, 0x2, 0x71, 0x72, 0x3, 0x2, 0x2, 0x2, 0x72, 0x76, 0x7, 0x30, 0x2, 0x2, 0x73, 0x75, 0x9, 0x4, 0x2, 0x2, 0x74, 0x73, 0x3, 0x2, 0x2, 0x2, 0x75, 0x78, 0x3, 0x2, 0x2, 0x2, 0x76, 0x74, 0x3, 0x2, 0x2, 0x2, 0x76, 0x77, 0x3, 0x2, 0x2, 0x2, 0x77, 0x80, 0x3, 0x2, 0x2, 0x2, 0x78, 0x76, 0x3, 0x2, 0x2, 0x2, 0x79, 0x7b, 0x7, 0x30, 0x2, 0x2, 0x7a, 0x7c, 0x9, 0x4, 0x2, 0x2, 0x7b, 0x7a, 0x3, 0x2, 0x2, 0x2, 0x7c, 0x7d, 0x3, 0x2, 0x2, 0x2, 0x7d, 0x7b, 0x3, 0x2, 0x2, 0x2, 0x7d, 0x7e, 0x3, 0x2, 0x2, 0x2, 0x7e, 0x80, 0x3, 0x2, 0x2, 0x2, 0x7f, 0x69, 0x3, 0x2, 0x2, 0x2, 0x7f, 0x6e, 0x3, 0x2, 0x2, 0x2, 0x7f, 0x79, 0x3, 0x2, 0x2, 0x2, 0x80, 0x14, 0x3, 0x2, 0x2, 0x2, 0x81, 0x82, 0x9, 0x5, 0x2, 0x2, 0x82, 0x16, 0x3, 0x2, 0x2, 0x2, 0x83, 0x84, 0x7, 0x5d, 0x2, 0x2, 0x84, 0x18, 0x3, 0x2, 0x2, 0x2, 0x85, 0x86, 0x7, 0x5f, 0x2, 0x2, 0x86, 0x1a, 0x3, 0x2, 0x2, 0x2, 0x87, 0x88, 0x7, 0x2a, 0x2, 0x2, 0x88, 0x1c, 0x3, 0x2, 0x2, 0x2, 0x89, 0x8a, 0x7, 0x2b, 0x2, 0x2, 0x8a, 0x1e, 0x3, 0x2, 0x2, 0x2, 0x8b, 0x8c, 0x7, 0x7d, 0x2, 0x2, 0x8c, 0x20, 0x3, 0x2, 0x2, 0x2, 0x8d, 0x8e, 0x7, 0x7f, 0x2, 0x2, 0x8e, 0x22, 0x3, 0x2, 0x2, 0x2, 0x8f, 0x90, 0x7, 0x3f, 0x2, 0x2, 0x90, 0x91, 0x7, 0x40, 0x2, 0x2, 0x91, 0x24, 0x3, 0x2, 0x2, 0x2, 0x92, 0x93, 0x7, 0x6b, 0x2, 0x2, 0x93, 0x94, 0x7, 0x76, 0x2, 0x2, 0x94, 0x95, 0x7, 0x67, 0x2, 0x2, 0x95, 0x96, 0x7, 0x74, 0x2, 0x2, 0x96, 0x97, 0x7, 0x63, 0x2, 0x2, 0x97, 0x98, 0x7, 0x76, 0x2, 0x2, 0x98, 0x99, 0x7, 0x71, 0x2, 0x2, 0x99, 0x9a, 0x7, 0x74, 0x2, 0x2, 0x9a, 0x26, 0x3, 0x2, 0x2, 0x2, 0x9b, 0x9c, 0x7, 0x3e, 0x2, 0x2, 0x9c, 0x28, 0x3, 0x2, 0x2, 0x2, 0x9d, 0x9e, 0x7, 0x40, 0x2, 0x2, 0x9e, 0x2a, 0x3, 0x2, 0x2, 0x2, 0x9f, 0xa0, 0x7, 0x31, 0x2, 0x2, 0xa0, 0xa1, 0x7, 0x2c, 0x2, 0x2, 0xa1, 0xa5, 0x3, 0x2, 0x2, 0x2, 0xa2, 0xa4, 0xb, 0x2, 0x2, 0x2, 0xa3, 0xa2, 0x3, 0x2, 0x2, 0x2, 0xa4, 0xa7, 0x3, 0x2, 0x2, 0x2, 0xa5, 0xa6, 0x3, 0x2, 0x2, 0x2, 0xa5, 0xa3, 0x3, 0x2, 0x2, 0x2, 0xa6, 0xa8, 0x3, 0x2, 0x2, 0x2, 0xa7, 0xa5, 0x3, 0x2, 0x2, 0x2, 0xa8, 0xa9, 0x7, 0x2c, 0x2, 0x2, 0xa9, 0xaa, 0x7, 0x31, 0x2, 0x2, 0xaa, 0x2c, 0x3, 0x2, 0x2, 0x2, 0xab, 0xaf, 0x9, 0x6, 0x2, 0x2, 0xac, 0xae, 0x9, 0x7, 0x2, 0x2, 0xad, 0xac, 0x3, 0x2, 0x2, 0x2, 0xae, 0xb1, 0x3, 0x2, 0x2, 0x2, 0xaf, 0xad, 0x3, 0x2, 0x2, 0x2, 0xaf, 0xb0, 0x3, 0x2, 0x2, 0x2, 0xb0, 0x2e, 0x3, 0x2, 0x2, 0x2, 0xb1, 0xaf, 0x3, 0x2, 0x2, 0x2, 0xb2, 0xb3, 0x9, 0x8, 0x2, 0x2, 0xb3, 0xb4, 0x3, 0x2, 0x2, 0x2, 0xb4, 0xb5, 0x8, 0x18, 0x2, 0x2, 0xb5, 0x30, 0x3, 0x2, 0x2, 0x2, 0xb6, 0xb7, 0xb, 0x2, 0x2, 0x2, 0xb7, 0x32, 0x3, 0x2, 0x2, 0x2, 0xe, 0x2, 0x3b, 0x43, 0x47, 0x66, 0x6b, 0x70, 0x76, 0x7d, 0x7f, 0xa5, 0xaf, 0x3, 0x8, 0x2, 0x2, }; atn::ATNDeserializer deserializer; _atn = deserializer.deserialize(_serializedATN); size_t count = _atn.getNumberOfDecisions(); _decisionToDFA.reserve(count); for (size_t i = 0; i < count; i++) { _decisionToDFA.emplace_back(_atn.getDecisionState(i), i); } } ArgumentListLexer::Initializer ArgumentListLexer::_init;
52.561265
120
0.618439
trgswe
bebe23bb7cf418e86220e5eb91e98ebfec244c5c
4,237
cpp
C++
3dc/sphere.cpp
Melanikus/AvP
9d61eb974a23538e32bf2ef1b738643a018935a0
[ "BSD-3-Clause" ]
null
null
null
3dc/sphere.cpp
Melanikus/AvP
9d61eb974a23538e32bf2ef1b738643a018935a0
[ "BSD-3-Clause" ]
null
null
null
3dc/sphere.cpp
Melanikus/AvP
9d61eb974a23538e32bf2ef1b738643a018935a0
[ "BSD-3-Clause" ]
null
null
null
#include "3dc.h" #include "module.h" #include "inline.h" #include "tables.h" #include "sphere.h" #define UseLocalAssert TRUE #include "ourasert.h" #define MakeVertex(o,x,y,z) \ { \ o->vx=(x); \ o->vy=(y); \ o->vz=(z); \ o++; \ } #define MakeFace(f,a,b,c) \ { \ f->v[0] = (a); \ f->v[1] = (b); \ f->v[2] = (c); \ f++; \ } VECTORCH OctantVertex[(SPHERE_ORDER+1)*(SPHERE_ORDER+2)/2]; VECTORCH SphereVertex[SPHERE_VERTICES]; VECTORCH SphereRotatedVertex[SPHERE_VERTICES]; VECTORCH SphereAtmosRotatedVertex[SPHERE_VERTICES]; int SphereAtmosU[SPHERE_VERTICES]; int SphereAtmosV[SPHERE_VERTICES]; TRI_FACE SphereFace[SPHERE_FACES]; int SphereVertexHeight[SPHERE_VERTICES]; static void Generate_SphereOctant(void) { int i,j; VECTORCH *o = OctantVertex; /* i=0, j=0 */ MakeVertex(o,0,0,SPHERE_RADIUS); for (i=1; i<SPHERE_ORDER; i++) { int cosPhi, sinPhi; { int phi = 1024*i/SPHERE_ORDER; cosPhi = GetCos(phi); sinPhi = GetSin(phi); } /* 0<i<n, j=0 */ /* => cosTheta = 1, sinTheta = 0 */ MakeVertex(o,sinPhi,0,cosPhi); for (j=1; j<i; j++) { int cosTheta, sinTheta; { int theta = 1024*j/i; cosTheta = GetCos(theta); sinTheta = GetSin(theta); } /* 0<i<n, 0<j<i */ MakeVertex(o,MUL_FIXED(cosTheta,sinPhi),MUL_FIXED(sinTheta,sinPhi),cosPhi); } /* 0<i<n, j=i */ MakeVertex(o,0,sinPhi,cosPhi); } /* i=n, j=0 */ MakeVertex(o,SPHERE_RADIUS,0,0); for (j=1; j<SPHERE_ORDER; j++) { int cosTheta, sinTheta; { int theta = 1024*j/SPHERE_ORDER; cosTheta = GetCos(theta); sinTheta = GetSin(theta); } /* i=n, 0<j<i */ MakeVertex(o,cosTheta,sinTheta,0); } /* i=n, j=i */ MakeVertex(o,0,SPHERE_RADIUS,0); } void Generate_Sphere(void) { /* first generate vertices */ { int i,j; VECTORCH *v = SphereVertex; VECTORCH *o = OctantVertex; Generate_SphereOctant(); /* north pole */ *v++ = *o; for (i=0; ++i<=SPHERE_ORDER;) { o += i; /* 1st Quadrant */ for (j=i; --j>=0; o++, v++) { *v = *o; } /* 2nd Quadrant */ for (j=i; --j>=0; o--, v++) { v->vx = -o->vx; v->vy = o->vy; v->vz = o->vz; } /* 3rd Quadrant */ for (j=i; --j>=0; o++, v++) { v->vx = -o->vx; v->vy = -o->vy; v->vz = o->vz; } /* 4th Quadrant */ for (j=i; --j>=0; o--, v++) { v->vx = o->vx; v->vy = -o->vy; v->vz = o->vz; } } for (; --i>1;) { o -= i; /* 5th Quadrant */ for (j=i; --j>0; o++, v++) { v->vx = o->vx; v->vy = o->vy; v->vz = -o->vz; } /* 6th Quadrant */ for (j=i; --j>0; o--, v++) { v->vx = -o->vx; v->vy = o->vy; v->vz = -o->vz; } /* 7th Quadrant */ for (j=i; --j>0; o++, v++) { v->vx = -o->vx; v->vy = -o->vy; v->vz = -o->vz; } /* 8th Quadrant */ for (j=i; --j>0; o--, v++) { v->vx = o->vx; v->vy = -o->vy; v->vz = -o->vz; } } o--; /* south pole */ v->vx = -o->vx; v->vy = -o->vy; v->vz = -o->vz; } /* now generate face data */ { TRI_FACE *f = SphereFace; int kv,kw,ko,kv0,kw0,i,j; kv = 0, kw = 1; for(i=0; i<SPHERE_ORDER; i++) { kv0 = kv, kw0 = kw; for (ko=1; ko<=3; ko++) { for (j=i;; j--) { MakeFace(f,kv,kw,++kw); if (j==0) break; MakeFace(f,kv,kw,++kv); } } for (j=i;;j--) { if (j==0) { MakeFace(f,kv0,kw,kw0); kv++; kw++; break; } MakeFace(f,kv,kw,++kw); if (j==1) { MakeFace(f,kv,kw,kv0); } else MakeFace(f,kv,kw,++kv); } } for(; --i>=0;) { kv0=kv,kw0=kw; for(ko=5;ko<=7;ko++) { for (j=i;; j--) { MakeFace(f,kv,kw,++kv); if (j==0) break; MakeFace(f,kv,kw,++kw); } } for (j=i;;j--) { if (j==0) { MakeFace(f,kv,kw0,kv0); kv++; kw++; break; } MakeFace(f,kv,kw,++kv); if (j==1) { MakeFace(f,kv,kw,kw0); } else MakeFace(f,kv,kw,++kw); } } } { int i; VECTORCH *vSphere = SphereVertex; for (i = 0; i < SPHERE_VERTICES; i++, vSphere++) { SphereAtmosV[i] = ArcCos(vSphere->vy)*32*128*SPHERE_TEXTURE_WRAP; SphereAtmosU[i] = ArcTan(vSphere->vz, vSphere->vx)*16*128*SPHERE_TEXTURE_WRAP; } } }
16.681102
81
0.495634
Melanikus
bec2481709501c3146718d513f3ffa5176f05b20
1,560
cpp
C++
Code.v05-00/src/Util/MC_Rand.cpp
MIT-LAE/APCEMM
2954bca64ec1c13552830d467d404dbe627ef71a
[ "MIT" ]
2
2022-03-21T20:49:37.000Z
2022-03-22T17:25:31.000Z
Code.v05-00/src/Util/MC_Rand.cpp
MIT-LAE/APCEMM
2954bca64ec1c13552830d467d404dbe627ef71a
[ "MIT" ]
null
null
null
Code.v05-00/src/Util/MC_Rand.cpp
MIT-LAE/APCEMM
2954bca64ec1c13552830d467d404dbe627ef71a
[ "MIT" ]
1
2022-03-21T20:50:50.000Z
2022-03-21T20:50:50.000Z
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* */ /* Aircraft Plume Chemistry, Emission and Microphysics Model */ /* (APCEMM) */ /* */ /* MC_Rand Program File */ /* */ /* Author : Thibaud M. Fritz */ /* Time : 1/25/2019 */ /* File : MC_Rand.cpp */ /* */ /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include "Util/MC_Rand.hpp" void setSeed() { /* Sets seed for pseudo-random generator. * For that use the current unix timestamp as our random seed. */ srand(time(0)); } /* End of setSeed */ template <typename T> T fRand(const T fMin, const T fMax) { /* Returns a random number between fMin and fMax */ double f = (double) rand()/RAND_MAX; return (T) fMin + f * (fMax - fMin); } /* End of fRand */ template double fRand(const double fMin, const double fMax); template float fRand(const float fMin, const float fMax); template int fRand(const int fMin, const int fMax); template unsigned int fRand(const unsigned int fMin, const unsigned int fMax); /* End of MC_Rand.cpp */
39
78
0.385897
MIT-LAE
becb4dee1d0fc3f6f31881b3bb75ad8bcba117fd
12,227
cpp
C++
tests/das_tests/wire_out_with_fee_tests.cpp
powerchain-ltd/greenpower-blockchain
ff04c37f2de11677c3a34889fdede1256a3e5e02
[ "MIT" ]
1
2021-07-26T02:42:01.000Z
2021-07-26T02:42:01.000Z
tests/das_tests/wire_out_with_fee_tests.cpp
green-powerchain-ltd/greenpower-blockchain
ff04c37f2de11677c3a34889fdede1256a3e5e02
[ "MIT" ]
null
null
null
tests/das_tests/wire_out_with_fee_tests.cpp
green-powerchain-ltd/greenpower-blockchain
ff04c37f2de11677c3a34889fdede1256a3e5e02
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2018 Tech Solutions Malta LTD * * 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 <boost/test/unit_test.hpp> #include <graphene/chain/database.hpp> #include <graphene/chain/wire_out_with_fee_object.hpp> #include <graphene/chain/withdrawal_limit_object.hpp> #include "../common/database_fixture.hpp" using namespace graphene::chain; using namespace graphene::chain::test; BOOST_FIXTURE_TEST_SUITE( dascoin_tests, database_fixture ) BOOST_FIXTURE_TEST_SUITE( wire_out_with_fee_unit_tests, database_fixture ) BOOST_AUTO_TEST_CASE( wire_out_with_fee_web_asset_test ) { try { ACTOR(wallet); generate_block(); VAULT_ACTOR(vault); tether_accounts(wallet_id, vault_id); issue_dascoin(vault_id, 100); disable_vault_to_wallet_limit(vault_id); transfer_dascoin_vault_to_wallet(vault_id, wallet_id, 100 * DASCOIN_DEFAULT_ASSET_PRECISION); const auto check_balances = [this](const account_object& account, share_type expected_cash, share_type expected_reserved) { share_type cash, reserved; std::tie(cash, reserved) = get_web_asset_amounts(account.id); BOOST_CHECK_EQUAL( cash.value, expected_cash.value ); BOOST_CHECK_EQUAL( reserved.value, expected_reserved.value ); }; // Reject, insufficient balance: GRAPHENE_REQUIRE_THROW( wire_out_with_fee(wallet_id, web_asset(10000), "BTC", "SOME_BTC_ADDRESS"), fc::exception ); // Reject, cannot wire out cycles: GRAPHENE_REQUIRE_THROW( wire_out_with_fee(wallet_id, asset{1, get_cycle_asset_id()}, "BTC", "SOME_BTC_ADDRESS"), fc::exception ); // Reject, cannot wire out dascoin: GRAPHENE_REQUIRE_THROW( wire_out_with_fee(wallet_id, asset{1, get_dascoin_asset_id()}, "BTC", "SOME_BTC_ADDRESS"), fc::exception ); issue_webasset("1", wallet_id, 15000, 15000); generate_blocks(db.head_block_time() + fc::hours(24) + fc::seconds(1)); // Update the limits: // update_pi_limits(wallet_id, 99, {20000,20000,20000}); // Wire out 10K: wire_out_with_fee(wallet_id, web_asset(10000), "BTC", "SOME_BTC_ADDRESS", "debit"); // Check if the balance has been reduced: check_balances(wallet, 5000, 15000); // Check if the holder object exists: auto holders = get_wire_out_with_fee_holders(wallet_id, {get_web_asset_id()}); BOOST_CHECK_EQUAL( holders.size(), 1 ); BOOST_CHECK_EQUAL( holders[0].currency_of_choice, "BTC" ); BOOST_CHECK_EQUAL( holders[0].to_address, "SOME_BTC_ADDRESS" ); BOOST_CHECK_EQUAL( holders[0].memo, "debit" ); // Wire out 5K: wire_out_with_fee(wallet_id, web_asset(5000), "BTC", "SOME_BTC_ADDRESS"); // Check the balances are zero: check_balances(wallet, 0, 15000); // There should be two holders now: holders = get_wire_out_with_fee_holders(wallet_id, {get_web_asset_id()}); BOOST_CHECK_EQUAL(holders.size(), 2); // Deny the first request: wire_out_with_fee_reject(holders[0].id); // Check if the wire out holder was deleted: BOOST_CHECK_EQUAL( get_wire_out_with_fee_holders(wallet_id, {get_web_asset_id()}).size(), 1 ); // 10K should return to the wallet: check_balances(wallet, 10000, 15000); // Complete a wire out transaction: wire_out_with_fee_complete(holders[1].id); // Check if the wire out holder object was deleted: BOOST_CHECK_EQUAL( get_wire_out_with_fee_holders(wallet_id, {get_web_asset_id()}).size(), 0 ); issue_btcasset("1", wallet_id, 15000, 15000); wire_out_with_fee(wallet_id, asset{5000, get_btc_asset_id()}, "BTC", "SOME_BTC_ADDRESS"); // After HARDFORK_BLC_340_DEPRECATE_MINTING_TIME wire out for web euros is deprecated: generate_blocks(HARDFORK_BLC_340_DEPRECATE_MINTING_TIME + fc::seconds(10)); GRAPHENE_REQUIRE_THROW( wire_out_with_fee(wallet_id, asset{1, get_web_asset_id()}, "BTC", "SOME_BTC_ADDRESS"), fc::exception ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( wire_out_with_fee_web_asset_history_test ) { try { ACTOR(wallet); generate_block(); issue_webasset("1", wallet_id, 15000, 15000); generate_blocks(db.head_block_time() + fc::hours(24) + fc::seconds(1)); // Wire out 10K: wire_out_with_fee(wallet_id, web_asset(10000), "BTC", "SOME_BTC_ADDRESS", "debit"); generate_blocks(db.head_block_time() + fc::hours(24) + fc::seconds(1)); auto holders = get_wire_out_with_fee_holders(wallet_id, {get_web_asset_id()}); wire_out_with_fee_reject(holders[0].id); generate_blocks(db.head_block_time() + fc::hours(24) + fc::seconds(1)); auto history = get_operation_history( wallet_id ); BOOST_CHECK( !history.empty() ); // Wire out result should be on top: wire_out_with_fee_result_operation op = history[0].op.get<wire_out_with_fee_result_operation>(); BOOST_CHECK ( !op.completed ); // Wire out 10K again: wire_out_with_fee(wallet_id, web_asset(10000), "BTC", "SOME_BTC_ADDRESS", "debit"); generate_blocks(db.head_block_time() + fc::hours(24) + fc::seconds(1)); holders = get_wire_out_with_fee_holders(wallet_id, {get_web_asset_id()}); wire_out_with_fee_complete(holders[0].id); generate_blocks(db.head_block_time() + fc::hours(24) + fc::seconds(1)); history = get_operation_history( wallet_id ); // Wire out result should be on top: op = history[0].op.get<wire_out_with_fee_result_operation>(); BOOST_CHECK ( op.completed ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( wire_out_with_fee_limit_test ) { try { ACTOR(wallet); issue_webasset("1", wallet_id, 3000 * DASCOIN_FIAT_ASSET_PRECISION, 15000); auto root_id = db.get_global_properties().authorities.root_administrator; // Set withdrawal limit to 500 eur, 100 sec revolving auto new_params = db.get_global_properties().parameters; new_params.extensions.insert(withdrawal_limit_type{asset{500 * DASCOIN_FIAT_ASSET_PRECISION, asset_id_type{DASCOIN_WEB_ASSET_INDEX}}, 100, {asset_id_type{DASCOIN_WEB_ASSET_INDEX}}}); do_op(update_global_parameters_operation(root_id, new_params)); generate_blocks(HARDFORK_BLC_342_TIME + fc::hours(1)); // Ought to fail, exceeds the absolute limit: GRAPHENE_REQUIRE_THROW( wire_out_with_fee(wallet_id, web_asset(600 * DASCOIN_FIAT_ASSET_PRECISION), "BTC", "SOME_BTC_ADDRESS", "debit"), fc::exception ); wire_out_with_fee(wallet_id, web_asset(200 * DASCOIN_FIAT_ASSET_PRECISION), "BTC", "SOME_BTC_ADDRESS", "debit"); // Fails since limit has been exceeded: GRAPHENE_REQUIRE_THROW( wire_out_with_fee(wallet_id, web_asset(400 * DASCOIN_FIAT_ASSET_PRECISION), "BTC", "SOME_BTC_ADDRESS", "debit"), fc::exception ); generate_blocks(200); wire_out_with_fee(wallet_id, web_asset(400 * DASCOIN_FIAT_ASSET_PRECISION), "BTC", "SOME_BTC_ADDRESS", "debit"); // Fails since time limit has been exceeded: GRAPHENE_REQUIRE_THROW( wire_out_with_fee(wallet_id, web_asset(200 * DASCOIN_FIAT_ASSET_PRECISION), "BTC", "SOME_BTC_ADDRESS", "debit"), fc::exception ); generate_blocks(200); // Works since the limit has been reset: wire_out_with_fee(wallet_id, web_asset(500 * DASCOIN_FIAT_ASSET_PRECISION), "BTC", "SOME_BTC_ADDRESS", "debit"); new_params.extensions.clear(); new_params.extensions.insert(withdrawal_limit_type{asset{500 * DASCOIN_FIAT_ASSET_PRECISION, asset_id_type{DASCOIN_WEB_ASSET_INDEX}}, 100, {asset_id_type{DASCOIN_DASCOIN_INDEX}}}); do_op(update_global_parameters_operation(root_id, new_params)); // Works since eur is no longer limited: wire_out_with_fee(wallet_id, web_asset(600 * DASCOIN_FIAT_ASSET_PRECISION), "BTC", "SOME_BTC_ADDRESS", "debit"); new_params.extensions.clear(); new_params.extensions.insert(withdrawal_limit_type{asset{-1 * DASCOIN_FIAT_ASSET_PRECISION, asset_id_type{DASCOIN_WEB_ASSET_INDEX}}, 100, {asset_id_type{DASCOIN_WEB_ASSET_INDEX}}}); do_op(update_global_parameters_operation(root_id, new_params)); // Works since limit is now set to infinity: wire_out_with_fee(wallet_id, web_asset(700 * DASCOIN_FIAT_ASSET_PRECISION), "BTC", "SOME_BTC_ADDRESS", "debit"); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( wire_out_with_fee_limit_and_reject_test ) { try { ACTOR(wallet); issue_webasset("1", wallet_id, 3000 * DASCOIN_FIAT_ASSET_PRECISION, 15000); auto root_id = db.get_global_properties().authorities.root_administrator; // Set withdrawal limit to 500 eur, 100 sec revolving auto new_params = db.get_global_properties().parameters; new_params.extensions.insert(withdrawal_limit_type{asset{500 * DASCOIN_FIAT_ASSET_PRECISION, asset_id_type{DASCOIN_WEB_ASSET_INDEX}}, 100, {asset_id_type{DASCOIN_WEB_ASSET_INDEX}}}); do_op(update_global_parameters_operation(root_id, new_params)); generate_blocks(HARDFORK_BLC_328_TIME + fc::hours(1)); // Works since amount is less than the limit: wire_out_with_fee(wallet_id, web_asset(400 * DASCOIN_FIAT_ASSET_PRECISION), "BTC", "SOME_BTC_ADDRESS", "debit"); const auto& idx = db.get_index_type<withdrawal_limit_index>().indices().get<by_account_id>(); auto itr = idx.find(wallet_id); BOOST_CHECK( itr != idx.end() ); BOOST_CHECK_EQUAL( itr->spent.amount.value, 400 * DASCOIN_FIAT_ASSET_PRECISION ); // Fails because of the limit: GRAPHENE_REQUIRE_THROW( wire_out_with_fee(wallet_id, web_asset(200 * DASCOIN_FIAT_ASSET_PRECISION), "BTC", "SOME_BTC_ADDRESS", "debit"), fc::exception ); // Reject wire out now: auto holders = get_wire_out_with_fee_holders(wallet_id, {get_web_asset_id()}); wire_out_with_fee_reject(holders[0].id); wire_out_with_fee(wallet_id, web_asset(200 * DASCOIN_FIAT_ASSET_PRECISION), "BTC", "SOME_BTC_ADDRESS", "debit"); itr = idx.find(wallet_id); BOOST_CHECK( itr != idx.end() ); // Spent has been reset to 0 and is 200 now: BOOST_CHECK_EQUAL( itr->spent.amount.value, 200 * DASCOIN_FIAT_ASSET_PRECISION ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( wire_out_with_fee_342_test ) { try { ACTOR(wallet); issue_webasset("1", wallet_id, 3000 * DASCOIN_FIAT_ASSET_PRECISION, 15000); auto root_id = db.get_global_properties().authorities.root_administrator; // Set withdrawal limit to 500 eur, 100 sec revolving auto new_params = db.get_global_properties().parameters; new_params.extensions.insert(withdrawal_limit_type{asset{500 * DASCOIN_FIAT_ASSET_PRECISION, asset_id_type{DASCOIN_WEB_ASSET_INDEX}}, 2592000, {asset_id_type{DASCOIN_WEB_ASSET_INDEX}}}); do_op(update_global_parameters_operation(root_id, new_params)); generate_blocks(HARDFORK_BLC_328_TIME + fc::hours(1)); // Works since amount is less than the limit: wire_out_with_fee(wallet_id, web_asset(500 * DASCOIN_FIAT_ASSET_PRECISION), "BTC", "SOME_BTC_ADDRESS", "debit"); generate_blocks(HARDFORK_BLC_328_TIME + fc::hours(2)); // Should work due to BLC-342 issue: wire_out_with_fee(wallet_id, web_asset(500 * DASCOIN_FIAT_ASSET_PRECISION), "BTC", "SOME_BTC_ADDRESS", "debit"); generate_blocks(HARDFORK_BLC_342_TIME + fc::hours(1)); wire_out_with_fee(wallet_id, web_asset(500 * DASCOIN_FIAT_ASSET_PRECISION), "BTC", "SOME_BTC_ADDRESS", "debit"); generate_blocks(HARDFORK_BLC_342_TIME + fc::minutes(110)); GRAPHENE_REQUIRE_THROW( wire_out_with_fee(wallet_id, web_asset(500 * DASCOIN_FIAT_ASSET_PRECISION), "BTC", "SOME_BTC_ADDRESS", "debit"), fc::exception ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
44.461818
188
0.765192
powerchain-ltd
becfa603a2fe2ed4d77b68fbeb677efa956018bf
922
hpp
C++
notebook/mutsim/src/mut.hpp
johnsmith2077/kevlar
3ed06dae62479e89ccd200391728c416d4df8052
[ "MIT" ]
24
2016-12-07T07:59:09.000Z
2019-03-11T02:05:36.000Z
notebook/mutsim/src/mut.hpp
johnsmith2077/kevlar
3ed06dae62479e89ccd200391728c416d4df8052
[ "MIT" ]
325
2016-12-07T07:37:17.000Z
2019-03-12T19:01:40.000Z
notebook/mutsim/src/mut.hpp
standage/kevlar
622d1869266550422e91a60119ddc7261eea434a
[ "MIT" ]
8
2017-08-17T01:37:39.000Z
2019-03-01T16:17:44.000Z
#ifndef KEVLAR_CPP_MUT #define KEVLAR_CPP_MUT #include <random> #include <string> #include "hist.hpp" #include "log.hpp" #include "hashtable.hh" using namespace oxli; class Mutator { protected: uint k; ulong limit; Histogram abund_hist; Histogram unique_hist; Logger& logger; double sampling_rate; std::uniform_real_distribution<double> dist; std::random_device rand; std::mt19937 prng; public: Mutator(uint ksize, Logger& l, uint maxabund = 16, ulong lim = 0); virtual unsigned long process(std::string& sequence, Counttable& counttable) = 0; std::ostream& print(std::ostream& stream) const; bool skip_nucl(); void set_sampling_rate(double rate, int seed); virtual ulong get_mut_count() = 0; }; std::ostream& operator<<(std::ostream& stream, const Mutator& m); #endif // KEVLAR_CPP_MUT
24.263158
89
0.652928
johnsmith2077
bede9b5653bc0edea47bed131b930eb881df611a
7,393
inl
C++
marstd2/inline/CMatrix4.inl
marcel303/marstd2004
8494eae253bea7c740f68458b0084c82c7ce2e0e
[ "MIT" ]
1
2020-05-20T12:31:35.000Z
2020-05-20T12:31:35.000Z
marstd2/inline/CMatrix4.inl
marcel303/marstd2004
8494eae253bea7c740f68458b0084c82c7ce2e0e
[ "MIT" ]
null
null
null
marstd2/inline/CMatrix4.inl
marcel303/marstd2004
8494eae253bea7c740f68458b0084c82c7ce2e0e
[ "MIT" ]
1
2020-05-20T12:31:40.000Z
2020-05-20T12:31:40.000Z
////////////////////////////////////////////////////////////////////// // CMatrix4 implementation. ////////////////////////////////////////////////////////////////////// #include <vector> // std::swap() #define INDEX3(x, y) ((x) + (y) * 3) #define INDEX4(x, y) ((x) + (y) * 4) inline CMatrix4::CMatrix4() { } inline CMatrix4::~CMatrix4() { } inline void CMatrix4::mul(float x, float y, float z, float w, float* xout, float* yout, float* zout, float* wout) { *xout = v[INDEX4(0, 0)] * x + v[INDEX4(1, 0)] * y + v[INDEX4(2, 0)] * z + v[INDEX4(3, 0)] * w; *yout = v[INDEX4(0, 1)] * x + v[INDEX4(1, 1)] * y + v[INDEX4(2, 1)] * z + v[INDEX4(3, 1)] * w; *zout = v[INDEX4(0, 2)] * x + v[INDEX4(1, 2)] * y + v[INDEX4(2, 2)] * z + v[INDEX4(3, 2)] * w; *wout = v[INDEX4(0, 3)] * x + v[INDEX4(1, 3)] * y + v[INDEX4(2, 3)] * z + v[INDEX4(3, 3)] * w; } inline void CMatrix4::mul4x3(float x, float y, float z, float* xout, float* yout, float* zout) { // Assume w = 1.0. *xout = v[INDEX4(0, 0)] * x + v[INDEX4(1, 0)] * y + v[INDEX4(2, 0)] * z + v[INDEX4(3, 0)]; *yout = v[INDEX4(0, 1)] * x + v[INDEX4(1, 1)] * y + v[INDEX4(2, 1)] * z + v[INDEX4(3, 1)]; *zout = v[INDEX4(0, 2)] * x + v[INDEX4(1, 2)] * y + v[INDEX4(2, 2)] * z + v[INDEX4(3, 2)]; } inline void CMatrix4::mul3x3(float x, float y, float z, float* xout, float* yout, float* zout) { // Assume w = 0.0. *xout = v[INDEX4(0, 0)] * x + v[INDEX4(1, 0)] * y + v[INDEX4(2, 0)] * z; *yout = v[INDEX4(0, 1)] * x + v[INDEX4(1, 1)] * y + v[INDEX4(2, 1)] * z; *zout = v[INDEX4(0, 2)] * x + v[INDEX4(1, 2)] * y + v[INDEX4(2, 2)] * z; } inline void CMatrix4::mul(CVector& vector, CVector& out) { mul(vector[0], vector[1], vector[2], vector[3], &out[0], &out[1], &out[2], &out[3]); } inline void CMatrix4::mul4x3(CVector& vector, CVector& out) { mul4x3(vector[0], vector[1], vector[2], &out[0], &out[1], &out[2]); } inline void CMatrix4::mul3x3(CVector& vector, CVector& out) { mul3x3(vector[0], vector[1], vector[2], &out[0], &out[1], &out[2]); } inline void CMatrix4::mul(CMatrix4& matrix) { float tmp[16]; for (int x = 0; x < 4; ++x) { for (int y = 0; y < 4; ++y) { tmp[INDEX4(x, y)] = v[INDEX4(0, y)] * matrix.v[INDEX4(x, 0)] + v[INDEX4(1, y)] * matrix.v[INDEX4(x, 1)] + v[INDEX4(2, y)] * matrix.v[INDEX4(x, 2)] + v[INDEX4(3, y)] * matrix.v[INDEX4(x, 3)]; } } for (int i = 0; i < 16; ++i) v[i] = tmp[i]; } inline void CMatrix4::mul3x3(CMatrix3& matrix) { float tmp[9]; for (int x = 0; x < 3; ++x) { for (int y = 0; y < 3; ++y) { tmp[INDEX3(x, y)] = v[INDEX4(0, y)] * matrix.v[INDEX3(x, 0)] + v[INDEX4(1, y)] * matrix.v[INDEX3(x, 1)] + v[INDEX4(2, y)] * matrix.v[INDEX3(x, 2)]; } } for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) v[INDEX4(i, j)] = tmp[INDEX3(i, j)]; } inline void CMatrix4::mul4x3(CMatrix3& matrix) { float tmp[16]; for (int x = 0; x < 4; ++x) { for (int y = 0; y < 4; ++y) { if (x == 3) { tmp[INDEX4(x, y)] = v[INDEX4(0, y)] * matrix.v[INDEX3(x, 0)] + v[INDEX4(1, y)] * matrix.v[INDEX3(x, 1)] + v[INDEX4(2, y)] * matrix.v[INDEX3(x, 2)]; } else { tmp[INDEX4(x, y)] = v[INDEX4(0, y)] + v[INDEX4(1, y)] + v[INDEX4(2, y)]; } } } for (int i = 0; i < 16; ++i) v[i] = tmp[i]; } inline void CMatrix4::mul(CMatrix4& matrix, CMatrix4& out) { for (int x = 0; x < 4; ++x) { for (int y = 0; y < 4; ++y) { out.v[INDEX4(x, y)] = v[INDEX4(0, y)] * matrix.v[INDEX4(x, 0)] + v[INDEX4(1, y)] * matrix.v[INDEX4(x, 1)] + v[INDEX4(2, y)] * matrix.v[INDEX4(x, 2)] + v[INDEX4(3, y)] * matrix.v[INDEX4(x, 3)]; } } } inline void CMatrix4::mul3x3(CMatrix3& matrix, CMatrix4& out) { for (int x = 0; x < 3; ++x) { for (int y = 0; y < 3; ++y) { out.v[INDEX4(x, y)] = v[INDEX4(0, y)] * matrix.v[INDEX3(x, 0)] + v[INDEX4(1, y)] * matrix.v[INDEX3(x, 1)] + v[INDEX4(2, y)] * matrix.v[INDEX3(x, 2)]; } } // Copy right column. out.v[INDEX4(3, 0)] = v[INDEX4(3, 0)]; out.v[INDEX4(3, 1)] = v[INDEX4(3, 1)]; out.v[INDEX4(3, 2)] = v[INDEX4(3, 2)]; // Copy bottom row. out.v[INDEX4(0, 3)] = v[INDEX4(0, 3)]; out.v[INDEX4(1, 3)] = v[INDEX4(1, 3)]; out.v[INDEX4(2, 3)] = v[INDEX4(2, 3)]; out.v[INDEX4(3, 3)] = v[INDEX4(3, 3)]; } inline void CMatrix4::mul4x3(CMatrix3& matrix, CMatrix4& out) { for (int x = 0; x < 3; ++x) { for (int y = 0; y < 3; ++y) { if (x == 3) { out.v[INDEX4(x, y)] = v[INDEX4(0, y)] * matrix.v[INDEX3(x, 0)] + v[INDEX4(1, y)] * matrix.v[INDEX3(x, 1)] + v[INDEX4(2, y)] * matrix.v[INDEX3(x, 2)]; } else { out.v[INDEX4(x, y)] = v[INDEX4(0, y)] + v[INDEX4(1, y)] + v[INDEX4(2, y)]; } } } // Copy right column. out.v[INDEX4(3, 0)] = v[INDEX4(3, 0)]; out.v[INDEX4(3, 1)] = v[INDEX4(3, 1)]; out.v[INDEX4(3, 2)] = v[INDEX4(3, 2)]; // Copy bottom row. out.v[INDEX4(0, 3)] = v[INDEX4(0, 3)]; out.v[INDEX4(1, 3)] = v[INDEX4(1, 3)]; out.v[INDEX4(2, 3)] = v[INDEX4(2, 3)]; out.v[INDEX4(3, 3)] = v[INDEX4(3, 3)]; } inline float CMatrix4::operator()(int x, int y) { return v[INDEX4(x, y)]; } inline CVector CMatrix4::operator*(CVector vector) { CVector tmp; tmp[0] = v[INDEX4(0, 0)] * vector[0] + v[INDEX4(1, 0)] * vector[1] + v[INDEX4(2, 0)] * vector[2] + v[INDEX4(3, 0)]; // * 1.0 tmp[1] = v[INDEX4(0, 1)] * vector[0] + v[INDEX4(1, 1)] * vector[1] + v[INDEX4(2, 1)] * vector[2] + v[INDEX4(3, 1)]; // * 1.0 tmp[2] = v[INDEX4(0, 2)] * vector[0] + v[INDEX4(1, 2)] * vector[1] + v[INDEX4(2, 2)] * vector[2] + v[INDEX4(3, 2)]; // * 1.0 // tmp[3] = 1.0; return tmp; } inline CMatrix4 CMatrix4::operator*(CMatrix4& matrix) { CMatrix4 tmp = *this; tmp *= matrix; return tmp; } inline CMatrix4 CMatrix4::operator*(CMatrix3& matrix) { CMatrix4 tmp = *this; tmp *= matrix; return tmp; } inline CMatrix4& CMatrix4::operator*=(CMatrix4& matrix) { mul(matrix); return *this; } inline CMatrix4& CMatrix4::operator*=(CMatrix3& matrix) { mul4x3(matrix); return *this; } #undef INDEX3 #undef INDEX4
20.31044
114
0.422562
marcel303
bedf79f3e26c44efe53726d95ddae33576a0e457
364
cpp
C++
URI Online Judge/Beginners/1101 - Sequence of Numbers and Sum.cpp
wgarcia1309/competitive-programming
a1788c8a7cbddaa753c2f468859581c1bac9e322
[ "MIT" ]
null
null
null
URI Online Judge/Beginners/1101 - Sequence of Numbers and Sum.cpp
wgarcia1309/competitive-programming
a1788c8a7cbddaa753c2f468859581c1bac9e322
[ "MIT" ]
null
null
null
URI Online Judge/Beginners/1101 - Sequence of Numbers and Sum.cpp
wgarcia1309/competitive-programming
a1788c8a7cbddaa753c2f468859581c1bac9e322
[ "MIT" ]
null
null
null
//1101 - Sequence of Numbers and Sum #include<iostream> using namespace std; int main(){ int m,n,t; cin>>n; cin>>m; while (m>0 && n>0) { if (n>m) { t=n; n=m; m=t; } t=0; for (int j =n ; j <=m; j++) { cout<<j<<" "; t+=j; } cout<<"Sum="<<t<<endl; cin>>m; cin>>n; } return 0; }
14
36
0.401099
wgarcia1309
bee7428de9930bdcf6c481fc4eded1ca31d47eab
4,778
cpp
C++
src/devel/csjp_logger.cpp
csjpeter/libcsjp
a26a574b09e1814337f887d653e2ced6d1d66334
[ "BSD-3-Clause" ]
null
null
null
src/devel/csjp_logger.cpp
csjpeter/libcsjp
a26a574b09e1814337f887d653e2ced6d1d66334
[ "BSD-3-Clause" ]
1
2016-03-06T12:45:01.000Z
2016-03-26T20:10:59.000Z
src/devel/csjp_logger.cpp
csjpeter/libcsjp
a26a574b09e1814337f887d653e2ced6d1d66334
[ "BSD-3-Clause" ]
null
null
null
/* * Author: Csaszar, Peter <csjpeter@gmail.com> * Copyright (C) 2009-2012 Csaszar, Peter */ #include <sys/time.h> #include <sys/stat.h> #include <unistd.h> #include <errno.h> #include <time.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #ifdef FCLOG #include <fclog.h> #endif #include "csjp_logger.h" namespace csjp { static void dateStamp(char res[16]) { time_t t = time(NULL); strftime(res, 16, "%Y-%m-%d-%a", localtime(&t)); } static void timeStamp(char res[16]) { char timeStr[16] = {0}; timeval unixTime; gettimeofday(&unixTime, NULL); time_t t = unixTime.tv_sec; int unixMillisecs = unixTime.tv_usec/1000; struct tm _tm; localtime_r(&t, &_tm); strftime(timeStr, sizeof(timeStr), "%H:%M:%S", &_tm); snprintf(res, 16, "%s:%03d", timeStr, unixMillisecs); } static char g_LogDir[256] = {0}; static char g_LogFileName[512] = {0}; static char g_LogFileNameSpecializer[128] = {0}; static char g_BinaryName[128] = "unknown"; bool verboseMode = false; bool haveLogDir = true; void resetLogFileName() { g_LogFileName[0] = 0; } void setLogDir(const char * dir) { if(dir) strncpy(g_LogDir, dir, sizeof(g_LogDir)); else strncpy(g_LogDir, "./", sizeof(g_LogDir)); haveLogDir = true; resetLogFileName(); } void setBinaryName(const char * name) { if(!name) return; const char *baseName = strrchr(name, '/'); baseName = baseName ? baseName + 1 : name; strncpy(g_BinaryName, baseName, sizeof(g_BinaryName)); resetLogFileName(); } const char * getBinaryName() { return g_BinaryName; } const char * logFileName() { #ifdef FCLOG return FCLOG_FILE; #else if(g_LogFileName[0] == 0 && haveLogDir){ struct stat fileStat; if(0 <= stat(g_LogDir, &fileStat)) if(S_ISDIR(fileStat.st_mode)){ snprintf(g_LogFileName, sizeof(g_LogFileName), "%s/%s%s.log", g_LogDir, g_BinaryName, g_LogFileNameSpecializer); return g_LogFileName; } haveLogDir = false; } return g_LogFileName; #endif } void setLogFileNameSpecializer(const char * str) { if(str != NULL){ g_LogFileNameSpecializer[0] = '.'; strncpy(g_LogFileNameSpecializer + 1, str, sizeof(g_LogFileNameSpecializer) - 1); } else g_LogFileNameSpecializer[0] = 0; resetLogFileName(); } static unsigned loggerMutex = 0; /* Initialized before main() */ void msgLogger(FILE * stdfile, const char * string, size_t length) { if(!length) length = strlen(string); char header[64]; { char time_stamp[16]; timeStamp(time_stamp); char date_stamp[16]; dateStamp(date_stamp); double c = (double)(clock())/(double)(CLOCKS_PER_SEC); snprintf(header, sizeof(header), "%14s %12s %7.3f %5d", date_stamp, time_stamp, c, getpid()); } const char * fmt = "%s %s "; #if ! _ISOC99_SOURCE #error We need to use C99 for calculating printed number of characters with vsnprintf(). #endif /* Now lets calculate the amount of memory needed by the full log message. */ int size = 0; size += strlen(fmt); size += sizeof(header); size += length; /* Allocate memory */ char * msg = (char*)malloc(size); if(!msg){ if(stderr) fprintf(stderr, VT_RED VT_TA_BOLD "ERROR" VT_NORMAL "No enoguh memory for log message!"); return; } /* Compose the log message */ int len = snprintf(msg, size, fmt, header, string); if(len < 0){ if(stderr) fprintf(stderr, VT_RED VT_TA_BOLD "ERROR" VT_NORMAL "Failed to snprintf the log message and its header!\n"); free(msg); return; } msg[len++] = '\n'; msg[len] = 0; /* We need to have logging thread safe. * We should not use posix mutex since that might fail, and * on posix failure we should report the issue, thus call * this logger. This would be a circular dependency and a * possible place to have infinite recursion. * * So we are going to use gcc special low level atomic operations. * http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Atomic-Builtins.html#Atomic-Builtins * type __sync_fetch_and_add (type *ptr, type value, ...) * type __sync_fetch_and_sub (type *ptr, type value, ...) */ #if not __GNUC__ >= 4 #error "We need gcc 4 or later for __sync_fetch_and_add() and __sync_fetch_and_sub()" #endif unsigned loggerMutexLast = 1; while(loggerMutexLast){ loggerMutexLast = __sync_fetch_and_add(&loggerMutex, 1); if(loggerMutexLast){ __sync_fetch_and_sub(&loggerMutex, 1); usleep(100); } } if(haveLogDir && logFileName()[0]){ FILE *log = fopen(logFileName(), "a"); if(log){ fputs(msg, log); fflush(log); TEMP_FAILURE_RETRY( fclose(log) ); } else if(stderr) { fprintf(stderr, VT_RED VT_TA_BOLD "ERROR" VT_NORMAL " Could not open logfile: %s\n", logFileName()); haveLogDir = false; } } basicLogger(msg, stdfile, g_BinaryName); __sync_fetch_and_sub(&loggerMutex, 1); free(msg); } }
22.327103
88
0.685224
csjpeter
beea03b4623f3c024fecefab9615f3f84a674f40
6,907
cpp
C++
gui/qt-gui/gui/calibrationdialog.cpp
yleniaBattistini/ObjectTracker
9f408d2c8e55209e80592ab17e6cddfddb38f5c4
[ "MIT" ]
null
null
null
gui/qt-gui/gui/calibrationdialog.cpp
yleniaBattistini/ObjectTracker
9f408d2c8e55209e80592ab17e6cddfddb38f5c4
[ "MIT" ]
null
null
null
gui/qt-gui/gui/calibrationdialog.cpp
yleniaBattistini/ObjectTracker
9f408d2c8e55209e80592ab17e6cddfddb38f5c4
[ "MIT" ]
null
null
null
#include "calibrationdialog.h" #include "ui_calibrationdialog.h" #include "displayutils.h" #include "pixmaputils.h" #include <opencv2/core.hpp> #include <opencv2/calib3d.hpp> #include <opencv2/imgproc.hpp> #include <iostream> #include <QFileDialog> #include <QDir> #include <opencv2/imgcodecs.hpp> #include <QMessageBox> #define INITIAL_SQUARE_SIZE 50.0 CalibrationDialog::CalibrationDialog(Camera *camera, PoseController *poseController, QWidget *parent) : QDialog(parent), ui(new Ui::CalibrationDialog), camera(camera), calibrationProcess(CalibrationProcess(INITIAL_SQUARE_SIZE)), poseController(poseController) { ui->setupUi(this); timer.start(50); display = setupAsDisplay(ui->grpCameraView); calibrationViewsModel = new QStandardItemModel(); ui->lstCalibrationViews->setModel(calibrationViewsModel); ui->spnSquareSize->setValue(INITIAL_SQUARE_SIZE); connect(&timer, SIGNAL(timeout()), this, SLOT(onNewFrame())); connect(ui->btnAddView, SIGNAL(clicked()), this, SLOT(onAddViewClicked())); connect(ui->btnRemoveView, SIGNAL(clicked()), this, SLOT(onRemoveViewClicked())); connect(ui->btnRunCalibration, SIGNAL(clicked()), this, SLOT(onRunCalibrationClicked())); connect(ui->spnSquareSize, SIGNAL(valueChanged(double)), this, SLOT(onSquareSizeChanged(double))); connect(ui->btnSave, SIGNAL(clicked()), this, SLOT(onSaveClicked())); connect(ui->btnSaveAs, SIGNAL(clicked()), this, SLOT(onSaveAsClicked())); connect(ui->btnOpen, SIGNAL(clicked()), this, SLOT(onOpenClicked())); } CalibrationDialog::~CalibrationDialog() { delete ui; delete display; } void CalibrationDialog::recomputeCalibration() { calibrationProcess.recomputeCalibration(); int rows = calibrationViewsModel->rowCount(); for (int i = 0; i < rows; i++) { QString reprojectionErrorText = QString("Reprojection Error: %1").arg(calibrationProcess.getReprojectionError(i)); QStandardItem *item = calibrationViewsModel->item(i); item->setText(reprojectionErrorText); } } QString CalibrationDialog::selectNewFolder() { QString oldPath = ui->lblFolderPath->text(); QString selectedPath = QFileDialog::getExistingDirectory(this, "Select a folder", oldPath); if (!selectedPath.isNull()) { setCurrentFolderPath(selectedPath); } return selectedPath; } void CalibrationDialog::setCurrentFolderPath(QString path) { ui->lblFolderPath->setText(path); ui->btnSave->setEnabled(!path.isEmpty()); } void CalibrationDialog::addView(Mat &view, vector<Point2f> &corners) { calibrationProcess.addView(view, corners); views.push_back(view); QPixmap pixmap; pixmapFromOpencvImage(view, pixmap); QIcon icon(pixmap); calibrationViewsModel->appendRow(new QStandardItem(icon, "")); } void CalibrationDialog::removeView(int index) { calibrationProcess.removeView(index); views.erase(views.begin() + index); calibrationViewsModel->removeRow(index); } void CalibrationDialog::saveInFolder(QString folderName) { QDir dir = QDir(folderName); QString calibrationFile = dir.filePath(DATA_FILE_NAME); FileStorage fs(calibrationFile.toStdString(), FileStorage::WRITE); fs << "SquareSize" << (double) calibrationProcess.getSquareSize(); fs << "NumberOfViews" << (int) views.size(); if (dir.exists(VIEWS_FOLDER_NAME)) { dir.cd(VIEWS_FOLDER_NAME); dir.removeRecursively(); dir.cdUp(); } dir.mkdir(VIEWS_FOLDER_NAME); dir.cd(VIEWS_FOLDER_NAME); for (int i = 0; i < views.size(); i++) { QString viewFile = QString("%1.%2").arg(i).arg(IMAGE_FILES_EXTENSION); QString filePath = dir.filePath(viewFile); imwrite(filePath.toStdString(), views[i]); } } void CalibrationDialog::openFolder(QString folderName) { QDir dir = QDir(folderName); QString calibrationFile = dir.filePath(DATA_FILE_NAME); FileStorage fs(calibrationFile.toStdString(), FileStorage::READ); int numberOfViews; double squareSize; fs["SquareSize"] >> squareSize; fs["NumberOfViews"] >> numberOfViews; calibrationProcess.clearViews(); calibrationViewsModel->clear(); views.clear(); calibrationProcess.setSquareSize(squareSize); ui->spnSquareSize->setValue(squareSize); dir.cd(VIEWS_FOLDER_NAME); for (int i = 0; i < numberOfViews; i++) { QString viewFile = QString("%1.%2").arg(i).arg(IMAGE_FILES_EXTENSION); QString filePath = dir.filePath(viewFile); Mat view = imread(filePath.toStdString()); vector<Point2f> corners; calibrationProcess.detectPattern(view, corners); addView(view, corners); } recomputeCalibration(); } void CalibrationDialog::onNewFrame() { camera->acquireNextFrame(currentFrame); currentCorners.clear(); patternFoundOnCurrentFrame = calibrationProcess.detectPattern(currentFrame, currentCorners); if (patternFoundOnCurrentFrame) { Mat frameWithPattern = currentFrame.clone(); calibrationProcess.drawPattern(frameWithPattern, currentCorners); display->setOpencvImage(frameWithPattern); } else { display->setOpencvImage(currentFrame); } } void CalibrationDialog::onSaveClicked() { saveInFolder(ui->lblFolderPath->text()); } void CalibrationDialog::onSaveAsClicked() { QString selectedPath = selectNewFolder(); if (selectedPath.isNull()) { return; } saveInFolder(selectedPath); } void CalibrationDialog::onOpenClicked() { QString selectedPath = selectNewFolder(); if (selectedPath.isNull()) { return; } openFolder(selectedPath); } void CalibrationDialog::onAddViewClicked() { if (!patternFoundOnCurrentFrame) { return; } Mat frameClone = currentFrame.clone(); addView(frameClone, currentCorners); recomputeCalibration(); } void CalibrationDialog::onRemoveViewClicked() { if (!ui->lstCalibrationViews->selectionModel()->hasSelection()) { return; } int selectedIndex = ui->lstCalibrationViews->selectionModel()->currentIndex().row(); removeView(selectedIndex); recomputeCalibration(); } void CalibrationDialog::onRunCalibrationClicked() { if (views.empty()) { QMessageBox::information(this, "Error", "At least one view is necessary", QMessageBox::Ok); return; } Mat cameraMatrix; Mat distortionCoefficients; calibrationProcess.getCalibrationResult(cameraMatrix, distortionCoefficients); camera->calibrate(cameraMatrix, distortionCoefficients); poseController->setCalibration(cameraMatrix, distortionCoefficients); accept(); } void CalibrationDialog::onSquareSizeChanged(double newValue) { calibrationProcess.setSquareSize(newValue); calibrationProcess.recomputeCalibration(); recomputeCalibration(); }
29.266949
122
0.70624
yleniaBattistini
bef0763f95dfc01933495791d303250b2b7e9c7c
3,072
cpp
C++
Source/TracerLib/TracerDebug.cpp
yalcinerbora/meturay
cff17b537fd8723af090802dfd17a0a740b404f5
[ "MIT" ]
null
null
null
Source/TracerLib/TracerDebug.cpp
yalcinerbora/meturay
cff17b537fd8723af090802dfd17a0a740b404f5
[ "MIT" ]
null
null
null
Source/TracerLib/TracerDebug.cpp
yalcinerbora/meturay
cff17b537fd8723af090802dfd17a0a740b404f5
[ "MIT" ]
null
null
null
#include "TracerDebug.h" #include "ImageMemory.h" #include "DefaultLeaf.h" #include "RayLib/ImageIO.h" namespace Debug { namespace Detail { void OutputHitPairs(std::ostream& s, const RayId* ids, const HitKey* keys, size_t count); } } void Debug::Detail::OutputHitPairs(std::ostream& s, const RayId* ids, const HitKey* keys, size_t count) { // Do Sync this makes memory to be accessible from Host for(size_t i = 0; i < count; i++) { s << "{" << std::hex << std::setw(8) << std::setfill('0') << keys[i] << ", " << std::dec << std::setw(0) << std::setfill(' ') << ids[i] << "}" << " "; } } void Debug::DumpImage(const std::string& fName, const ImageMemory& iMem) { ImageIO io; Vector2ui size(iMem.SegmentSize()[0], iMem.SegmentSize()[1]); auto image = iMem.GMem<Vector4f>(); io.WriteAsPNG(image.gPixels, size, fName); } void Debug::PrintHitPairs(const RayId* ids, const HitKey* keys, size_t count) { std::stringstream s; Detail::OutputHitPairs(s, ids, keys, count); METU_LOG("%s", s.str().c_str()); } void Debug::WriteHitPairs(const RayId* ids, const HitKey* keys, size_t count, const std::string& file) { std::ofstream f(file); Detail::OutputHitPairs(f, ids, keys, count); } std::ostream& operator<<(std::ostream& stream, const Vector2ul& v) { stream << std::setw(0) << v[0] << ", " << v[1]; return stream; } std::ostream& operator<<(std::ostream& stream, const Vector2f& v) { stream << std::setw(0) << v[0] << ", " << v[1]; return stream; } std::ostream& operator<<(std::ostream& stream, const Vector3f& v) { stream << std::setw(0) << v[0] << ", " << v[1] << ", " << v[2]; return stream; } std::ostream& operator<<(std::ostream& stream, const Vector4f& v) { stream << std::setw(0) << v[0] << ", " << v[1] << ", " << v[2] << ", " << v[3]; return stream; } std::ostream& operator<<(std::ostream& stream, const AABB3f& aabb) { stream << std::setw(0) << "{(" << aabb.Min() << "), (" << aabb.Max() << ")}"; return stream; } std::ostream& operator<<(std::ostream& stream, const RayGMem& r) { stream << std::setw(0) << "{" << r.pos[0] << ", " << r.pos[1] << ", " << r.pos[2] << "} " << "{" << r.dir[0] << ", " << r.dir[1] << ", " << r.dir[2] << "} " << "{" << r.tMin << ", " << r.tMax << "}"; return stream; } std::ostream& operator<<(std::ostream& stream, const HitKey& key) { stream << std::hex << std::setfill('0') << std::setw(HitKey::BatchBits / 4) << HitKey::FetchBatchPortion(key) << ":" << std::setw(HitKey::IdBits / 4) << HitKey::FetchIdPortion(key); stream << std::dec; return stream; } std::ostream& operator<<(std::ostream& stream, const DefaultLeaf& l) { stream << std::setw(0) << "{ mat: " << l.matId << ", primId: " << l.primitiveId << "} "; return stream; }
26.25641
103
0.524414
yalcinerbora
bef247fcf133245b8c13c61b58803ae0b9209993
5,489
hpp
C++
parallel_bandits/source/algorithms.hpp
piojanu/Parallel-Bandits
57a91dd5aa0b31aab79ea09a6b6ed9bb5a9ad266
[ "Apache-2.0" ]
null
null
null
parallel_bandits/source/algorithms.hpp
piojanu/Parallel-Bandits
57a91dd5aa0b31aab79ea09a6b6ed9bb5a9ad266
[ "Apache-2.0" ]
null
null
null
parallel_bandits/source/algorithms.hpp
piojanu/Parallel-Bandits
57a91dd5aa0b31aab79ea09a6b6ed9bb5a9ad266
[ "Apache-2.0" ]
null
null
null
#pragma once #include <memory> #include <vector> #include "bandits.hpp" using namespace std; namespace bandits { class IAlgorithm { public: /** * Solve the Multi-Armed Bandit problem. * * @param bandit Vector of bandit arms to pull. * @return The (ε-)optimal arm index. */ virtual size_t solve(const vector<shared_ptr<IBanditArm>> &bandit) const = 0; /** * Solve the Multi-Armed Bandit problem. * * @param[in] bandit Vector of bandit arms to pull. * @param[in, out] total_pulls Total number of arm pulls to the present * moment. * @return The (ε-)optimal arm index. */ virtual size_t solve(const vector<shared_ptr<IBanditArm>> &bandit, size_t &total_pulls) const = 0; virtual ~IAlgorithm() = default; }; class PACAlgorithm : public IAlgorithm { public: /** * Initialize the (ε, δ)-PAC solver. * * @param epsilon Find an arm that is at most ε worse than the optimal * arm in terms of the expected value (bounded between [0, 1]). * @param delta With probability of at least 1-δ find an ε-optimal arm. * @param limit_pulls Don't pull all arms more then this amount. * If the limit is exceeded, then `solve` returns an arbitrary arm! */ PACAlgorithm(double epsilon, double delta, size_t limit_pulls) : _epsilon(epsilon), _delta(delta), _limit_pulls(limit_pulls) { } PACAlgorithm() = delete; // Note: It is required because `solve` in this class hides the other // `solve` in the IAlgorithm interface. // Source: https://stackoverflow.com/a/1896864/7983111 using IAlgorithm::solve; size_t solve(const vector<shared_ptr<IBanditArm>> &bandit) const override { size_t total_pulls = 0; return this->solve(bandit, total_pulls); } protected: const double _epsilon, _delta; const size_t _limit_pulls; }; class MedianElimination : public PACAlgorithm { public: MedianElimination(double epsilon, double delta, size_t limit_pulls) : PACAlgorithm(epsilon, delta, limit_pulls) { } using PACAlgorithm::solve; // Use the base class implementation; size_t solve(const vector<shared_ptr<IBanditArm>> &bandit, size_t &total_pulls) const override; }; class ExpGapElimination : public PACAlgorithm { public: ExpGapElimination(double epsilon, double delta, size_t limit_pulls) : PACAlgorithm(epsilon, delta, limit_pulls) { } using PACAlgorithm::solve; // Use the base class implementation; size_t solve(const vector<shared_ptr<IBanditArm>> &bandit, size_t &total_pulls) const override; }; class OneRoundBestArm : public IAlgorithm { public: /** * Initialize the distributed one-round best-arm solver. * * It identifies the best arm with probability at least 2/3 using * no more than arm pulls per player: * $$O( 1/\sqrt(k) * \sum_{i=2}^{n} 1/\Delta_i^2 \log(1/\Delta_i) )$$ * * See: Hillel, E., Karnin, Z., Koren, T., Lempel, R., and Somekh, O., * “Distributed Exploration in Multi-Armed Bandits”, 2013. * * @param num_players Number of OpenMP threads. * @param time_horizon Limit of arm pulls per player. */ OneRoundBestArm(int num_players, size_t time_horizon) : _num_players(num_players), _time_horizon(time_horizon) { } OneRoundBestArm() = delete; size_t solve(const vector<shared_ptr<IBanditArm>> &bandit) const override { size_t total_pulls = 0; return this->solve(bandit, total_pulls); } size_t solve(const vector<shared_ptr<IBanditArm>> &bandit, size_t &total_pulls) const override; private: const int _num_players; const size_t _time_horizon; }; class MultiRoundEpsilonArm : public PACAlgorithm { public: /** * Initialize the distributed multi-round ε-arm solver. * * See: Hillel, E., Karnin, Z., Koren, T., Lempel, R., and Somekh, O., * “Distributed Exploration in Multi-Armed Bandits”, 2013. * * @param num_players Number of OpenMP threads. * @param epsilon Find an arm that is at most ε worse than the optimal * arm in terms of the expected value (bounded between [0, 1]). * @param delta With probability of at least 1-δ find an ε-optimal arm. * @param limit_pulls Don't pull all arms more then this amount. * If the limit is exceeded, then `solve` returns an arbitrary arm! */ MultiRoundEpsilonArm(int num_players, double epsilon, double delta, size_t limit_pulls) : PACAlgorithm(epsilon, delta, limit_pulls), _num_players(num_players) { } using PACAlgorithm::solve; // Use the base class implementation; size_t solve(const vector<shared_ptr<IBanditArm>> &bandit, size_t &total_pulls) const override; private: const int _num_players; }; }
33.066265
79
0.594644
piojanu
bef957555d1bd2533bf48080a56162a275b21ea8
43,911
cpp
C++
src/ReBarBands.cpp
TimoKunze/ToolBarControls
409625a0e8541d7cea7a108951699970953af757
[ "MIT" ]
1
2019-12-12T08:12:14.000Z
2019-12-12T08:12:14.000Z
src/ReBarBands.cpp
TimoKunze/ToolBarControls
409625a0e8541d7cea7a108951699970953af757
[ "MIT" ]
null
null
null
src/ReBarBands.cpp
TimoKunze/ToolBarControls
409625a0e8541d7cea7a108951699970953af757
[ "MIT" ]
2
2018-05-05T02:30:05.000Z
2021-12-09T18:20:38.000Z
// ReBarBands.cpp: Manages a collection of ReBarBand objects #include "stdafx.h" #include "ReBarBands.h" #include "ClassFactory.h" ////////////////////////////////////////////////////////////////////// // implementation of ISupportErrorInfo STDMETHODIMP ReBarBands::InterfaceSupportsErrorInfo(REFIID interfaceToCheck) { if(InlineIsEqualGUID(IID_IReBarBands, interfaceToCheck)) { return S_OK; } return S_FALSE; } // implementation of ISupportErrorInfo ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // implementation of IEnumVARIANT STDMETHODIMP ReBarBands::Clone(IEnumVARIANT** ppEnumerator) { ATLASSERT_POINTER(ppEnumerator, LPENUMVARIANT); if(!ppEnumerator) { return E_POINTER; } *ppEnumerator = NULL; CComObject<ReBarBands>* pRBarBandsObj = NULL; CComObject<ReBarBands>::CreateInstance(&pRBarBandsObj); pRBarBandsObj->AddRef(); // clone all settings properties.CopyTo(&pRBarBandsObj->properties); pRBarBandsObj->QueryInterface(IID_IEnumVARIANT, reinterpret_cast<LPVOID*>(ppEnumerator)); pRBarBandsObj->Release(); return S_OK; } STDMETHODIMP ReBarBands::Next(ULONG numberOfMaxBands, VARIANT* pBands, ULONG* pNumberOfBandsReturned) { ATLASSERT_POINTER(pBands, VARIANT); if(!pBands) { return E_POINTER; } HWND hWndRBar = properties.GetRBarHWnd(); ATLASSERT(IsWindow(hWndRBar)); // check each band in the rebar int numberOfBands = static_cast<int>(SendMessage(hWndRBar, RB_GETBANDCOUNT, 0, 0)); ULONG i = 0; for(i = 0; i < numberOfMaxBands; ++i) { VariantInit(&pBands[i]); do { if(properties.lastEnumeratedBand >= 0) { if(properties.lastEnumeratedBand < numberOfBands) { properties.lastEnumeratedBand = GetNextBandToProcess(properties.lastEnumeratedBand, numberOfBands); } } else { properties.lastEnumeratedBand = GetFirstBandToProcess(numberOfBands); } if(properties.lastEnumeratedBand >= numberOfBands) { properties.lastEnumeratedBand = -1; } } while((properties.lastEnumeratedBand != -1) && (!IsPartOfCollection(properties.lastEnumeratedBand, hWndRBar))); if(properties.lastEnumeratedBand != -1) { ClassFactory::InitReBarBand(properties.lastEnumeratedBand, properties.pOwnerRBar, IID_IDispatch, reinterpret_cast<LPUNKNOWN*>(&pBands[i].pdispVal)); pBands[i].vt = VT_DISPATCH; } else { // there's nothing more to iterate break; } } if(pNumberOfBandsReturned) { *pNumberOfBandsReturned = i; } return (i == numberOfMaxBands ? S_OK : S_FALSE); } STDMETHODIMP ReBarBands::Reset(void) { properties.lastEnumeratedBand = -1; return S_OK; } STDMETHODIMP ReBarBands::Skip(ULONG numberOfBandsToSkip) { VARIANT dummy; ULONG numBandsReturned = 0; // we could skip all bands at once, but it's easier to skip them one after the other for(ULONG i = 1; i <= numberOfBandsToSkip; ++i) { HRESULT hr = Next(1, &dummy, &numBandsReturned); VariantClear(&dummy); if(hr != S_OK || numBandsReturned == 0) { // there're no more bands to skip, so don't try it anymore break; } } return S_OK; } // implementation of IEnumVARIANT ////////////////////////////////////////////////////////////////////// BOOL ReBarBands::IsValidBooleanFilter(VARIANT& filter) { BOOL isValid = TRUE; if((filter.vt == (VT_ARRAY | VT_VARIANT)) && filter.parray) { LONG lBound = 0; LONG uBound = 0; if((SafeArrayGetLBound(filter.parray, 1, &lBound) == S_OK) && (SafeArrayGetUBound(filter.parray, 1, &uBound) == S_OK)) { // now that we have the bounds, iterate the array VARIANT element; if(lBound > uBound) { isValid = FALSE; } for(LONG i = lBound; i <= uBound && isValid; ++i) { if(SafeArrayGetElement(filter.parray, &i, &element) == S_OK) { isValid = (element.vt == VT_BOOL); VariantClear(&element); } else { isValid = FALSE; } } } else { isValid = FALSE; } } else { isValid = FALSE; } return isValid; } BOOL ReBarBands::IsValidIntegerFilter(VARIANT& filter, int minValue, int maxValue) { BOOL isValid = TRUE; if((filter.vt == (VT_ARRAY | VT_VARIANT)) && filter.parray) { LONG lBound = 0; LONG uBound = 0; if((SafeArrayGetLBound(filter.parray, 1, &lBound) == S_OK) && (SafeArrayGetUBound(filter.parray, 1, &uBound) == S_OK)) { // now that we have the bounds, iterate the array VARIANT element; if(lBound > uBound) { isValid = FALSE; } for(LONG i = lBound; i <= uBound && isValid; ++i) { if(SafeArrayGetElement(filter.parray, &i, &element) == S_OK) { isValid = SUCCEEDED(VariantChangeType(&element, &element, 0, VT_INT)) && element.intVal >= minValue && element.intVal <= maxValue; VariantClear(&element); } else { isValid = FALSE; } } } else { isValid = FALSE; } } else { isValid = FALSE; } return isValid; } BOOL ReBarBands::IsValidIntegerFilter(VARIANT& filter, int minValue) { BOOL isValid = TRUE; if((filter.vt == (VT_ARRAY | VT_VARIANT)) && filter.parray) { LONG lBound = 0; LONG uBound = 0; if((SafeArrayGetLBound(filter.parray, 1, &lBound) == S_OK) && (SafeArrayGetUBound(filter.parray, 1, &uBound) == S_OK)) { // now that we have the bounds, iterate the array VARIANT element; if(lBound > uBound) { isValid = FALSE; } for(LONG i = lBound; i <= uBound && isValid; ++i) { if(SafeArrayGetElement(filter.parray, &i, &element) == S_OK) { isValid = SUCCEEDED(VariantChangeType(&element, &element, 0, VT_INT)) && element.intVal >= minValue; VariantClear(&element); } else { isValid = FALSE; } } } else { isValid = FALSE; } } else { isValid = FALSE; } return isValid; } BOOL ReBarBands::IsValidIntegerFilter(VARIANT& filter) { BOOL isValid = TRUE; if((filter.vt == (VT_ARRAY | VT_VARIANT)) && filter.parray) { LONG lBound = 0; LONG uBound = 0; if((SafeArrayGetLBound(filter.parray, 1, &lBound) == S_OK) && (SafeArrayGetUBound(filter.parray, 1, &uBound) == S_OK)) { // now that we have the bounds, iterate the array VARIANT element; if(lBound > uBound) { isValid = FALSE; } for(LONG i = lBound; i <= uBound && isValid; ++i) { if(SafeArrayGetElement(filter.parray, &i, &element) == S_OK) { isValid = SUCCEEDED(VariantChangeType(&element, &element, 0, VT_UI4)); VariantClear(&element); } else { isValid = FALSE; } } } else { isValid = FALSE; } } else { isValid = FALSE; } return isValid; } BOOL ReBarBands::IsValidStringFilter(VARIANT& filter) { BOOL isValid = TRUE; if((filter.vt == (VT_ARRAY | VT_VARIANT)) && filter.parray) { LONG lBound = 0; LONG uBound = 0; if((SafeArrayGetLBound(filter.parray, 1, &lBound) == S_OK) && (SafeArrayGetUBound(filter.parray, 1, &uBound) == S_OK)) { // now that we have the bounds, iterate the array VARIANT element; if(lBound > uBound) { isValid = FALSE; } for(LONG i = lBound; i <= uBound && isValid; ++i) { if(SafeArrayGetElement(filter.parray, &i, &element) == S_OK) { isValid = (element.vt == VT_BSTR); VariantClear(&element); } else { isValid = FALSE; } } } else { isValid = FALSE; } } else { isValid = FALSE; } return isValid; } int ReBarBands::GetFirstBandToProcess(int numberOfBands) { if(numberOfBands == 0) { return -1; } return 0; } int ReBarBands::GetNextBandToProcess(int previousBand, int numberOfBands) { if(previousBand < numberOfBands - 1) { return previousBand + 1; } return -1; } BOOL ReBarBands::IsBooleanInSafeArray(LPSAFEARRAY pSafeArray, VARIANT_BOOL value, LPVOID pComparisonFunction) { LONG lBound = 0; LONG uBound = 0; SafeArrayGetLBound(pSafeArray, 1, &lBound); SafeArrayGetUBound(pSafeArray, 1, &uBound); VARIANT element; BOOL foundMatch = FALSE; for(LONG i = lBound; i <= uBound && !foundMatch; ++i) { SafeArrayGetElement(pSafeArray, &i, &element); if(pComparisonFunction) { typedef BOOL WINAPI ComparisonFn(VARIANT_BOOL, VARIANT_BOOL); ComparisonFn* pComparisonFn = reinterpret_cast<ComparisonFn*>(pComparisonFunction); if(pComparisonFn(value, element.boolVal)) { foundMatch = TRUE; } } else { if(element.boolVal == value) { foundMatch = TRUE; } } VariantClear(&element); } return foundMatch; } BOOL ReBarBands::IsIntegerInSafeArray(LPSAFEARRAY pSafeArray, int value, LPVOID pComparisonFunction) { LONG lBound = 0; LONG uBound = 0; SafeArrayGetLBound(pSafeArray, 1, &lBound); SafeArrayGetUBound(pSafeArray, 1, &uBound); VARIANT element; BOOL foundMatch = FALSE; for(LONG i = lBound; i <= uBound && !foundMatch; ++i) { SafeArrayGetElement(pSafeArray, &i, &element); int v = 0; if(SUCCEEDED(VariantChangeType(&element, &element, 0, VT_INT))) { v = element.intVal; } if(pComparisonFunction) { typedef BOOL WINAPI ComparisonFn(LONG, LONG); ComparisonFn* pComparisonFn = reinterpret_cast<ComparisonFn*>(pComparisonFunction); if(pComparisonFn(value, v)) { foundMatch = TRUE; } } else { if(v == value) { foundMatch = TRUE; } } VariantClear(&element); } return foundMatch; } BOOL ReBarBands::IsStringInSafeArray(LPSAFEARRAY pSafeArray, BSTR value, LPVOID pComparisonFunction) { LONG lBound = 0; LONG uBound = 0; SafeArrayGetLBound(pSafeArray, 1, &lBound); SafeArrayGetUBound(pSafeArray, 1, &uBound); VARIANT element; BOOL foundMatch = FALSE; for(LONG i = lBound; i <= uBound && !foundMatch; ++i) { SafeArrayGetElement(pSafeArray, &i, &element); if(pComparisonFunction) { typedef BOOL WINAPI ComparisonFn(BSTR, BSTR); ComparisonFn* pComparisonFn = reinterpret_cast<ComparisonFn*>(pComparisonFunction); if(pComparisonFn(value, element.bstrVal)) { foundMatch = TRUE; } } else { if(properties.caseSensitiveFilters) { if(lstrcmpW(OLE2W(element.bstrVal), OLE2W(value)) == 0) { foundMatch = TRUE; } } else { if(lstrcmpiW(OLE2W(element.bstrVal), OLE2W(value)) == 0) { foundMatch = TRUE; } } } VariantClear(&element); } return foundMatch; } BOOL ReBarBands::IsPartOfCollection(int bandIndex, HWND hWndRBar/* = NULL*/) { if(!hWndRBar) { hWndRBar = properties.GetRBarHWnd(); } ATLASSERT(IsWindow(hWndRBar)); if(!IsValidBandIndex(bandIndex, hWndRBar)) { return FALSE; } BOOL isPart = FALSE; // we declare this one here to avoid compiler warnings REBARBANDINFO band = {0}; band.cbSize = RunTimeHelper::SizeOf_REBARBANDINFO(); if(properties.filterType[fpIndex] != ftDeactivated) { if(IsIntegerInSafeArray(properties.filter[fpIndex].parray, bandIndex, properties.comparisonFunction[fpIndex])) { if(properties.filterType[fpIndex] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpIndex] == ftIncluding) { goto Exit; } } } BOOL mustRetrieveBandData = FALSE; if(properties.filterType[fpIconIndex] != ftDeactivated) { band.fMask |= RBBIM_IMAGE; mustRetrieveBandData = TRUE; } if(properties.filterType[fpBandData] != ftDeactivated) { band.fMask |= RBBIM_LPARAM; mustRetrieveBandData = TRUE; } if(properties.filterType[fpText] != ftDeactivated) { band.fMask |= RBBIM_TEXT; band.cch = MAX_BANDTEXTLENGTH; band.lpText = reinterpret_cast<LPTSTR>(malloc((band.cch + 1) * sizeof(TCHAR))); mustRetrieveBandData = TRUE; } if(properties.filterType[fpAddMarginsAroundChild] != ftDeactivated || properties.filterType[fpFixedBackgroundBitmapOrigin] != ftDeactivated || properties.filterType[fpHideIfVertical] != ftDeactivated || properties.filterType[fpKeepInFirstRow] != ftDeactivated || properties.filterType[fpNewLine] != ftDeactivated || properties.filterType[fpResizable] != ftDeactivated || properties.filterType[fpShowTitle] != ftDeactivated || properties.filterType[fpSizingGripVisibility] != ftDeactivated || properties.filterType[fpUseChevron] != ftDeactivated || properties.filterType[fpVariableHeight] != ftDeactivated || properties.filterType[fpVisible] != ftDeactivated) { band.fMask |= RBBIM_STYLE; mustRetrieveBandData = TRUE; } if(properties.filterType[fpBackColor] != ftDeactivated || properties.filterType[fpForeColor] != ftDeactivated) { band.fMask |= RBBIM_COLORS; mustRetrieveBandData = TRUE; } if(properties.filterType[fpCurrentHeight] != ftDeactivated || properties.filterType[fpHeightChangeStepSize] != ftDeactivated || properties.filterType[fpMaximumHeight] != ftDeactivated || properties.filterType[fpMinimumHeight] != ftDeactivated || properties.filterType[fpMinimumWidth] != ftDeactivated) { band.fMask |= RBBIM_CHILDSIZE; mustRetrieveBandData = TRUE; } if(properties.filterType[fpCurrentWidth] != ftDeactivated) { band.fMask |= RBBIM_SIZE; mustRetrieveBandData = TRUE; } if(properties.filterType[fpHBackgroundBitmap] != ftDeactivated) { band.fMask |= RBBIM_BACKGROUND; mustRetrieveBandData = TRUE; } if(properties.filterType[fpHContainedWindow] != ftDeactivated) { band.fMask |= RBBIM_CHILD; mustRetrieveBandData = TRUE; } if(properties.filterType[fpID] != ftDeactivated) { band.fMask |= RBBIM_ID; mustRetrieveBandData = TRUE; } if(properties.filterType[fpIdealWidth] != ftDeactivated) { band.fMask |= RBBIM_IDEALSIZE; mustRetrieveBandData = TRUE; } if(properties.filterType[fpTitleWidth] != ftDeactivated) { band.fMask |= RBBIM_HEADERSIZE; mustRetrieveBandData = TRUE; } if(mustRetrieveBandData) { if(!SendMessage(hWndRBar, RB_GETBANDINFO, bandIndex, reinterpret_cast<LPARAM>(&band))) { goto Exit; } // apply the filters if(properties.filterType[fpID] != ftDeactivated) { if(IsIntegerInSafeArray(properties.filter[fpID].parray, static_cast<int>(band.wID), properties.comparisonFunction[fpID])) { if(properties.filterType[fpID] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpID] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpBandData] != ftDeactivated) { if(IsIntegerInSafeArray(properties.filter[fpBandData].parray, static_cast<int>(band.lParam), properties.comparisonFunction[fpBandData])) { if(properties.filterType[fpBandData] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpBandData] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpIdealWidth] != ftDeactivated) { if(IsIntegerInSafeArray(properties.filter[fpIdealWidth].parray, static_cast<int>(band.cxIdeal), properties.comparisonFunction[fpIdealWidth])) { if(properties.filterType[fpIdealWidth] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpIdealWidth] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpText] != ftDeactivated) { if(IsStringInSafeArray(properties.filter[fpText].parray, CComBSTR(band.lpText), properties.comparisonFunction[fpText])) { if(properties.filterType[fpText] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpText] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpIconIndex] != ftDeactivated) { if(IsIntegerInSafeArray(properties.filter[fpIconIndex].parray, (band.iImage == -1 ? -2 : band.iImage), properties.comparisonFunction[fpIconIndex])) { if(properties.filterType[fpIconIndex] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpIconIndex] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpVisible] != ftDeactivated) { if(IsBooleanInSafeArray(properties.filter[fpVisible].parray, BOOL2VARIANTBOOL(!(band.fStyle & RBBS_HIDDEN)), properties.comparisonFunction[fpVisible])) { if(properties.filterType[fpVisible] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpVisible] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpHideIfVertical] != ftDeactivated) { if(IsBooleanInSafeArray(properties.filter[fpHideIfVertical].parray, BOOL2VARIANTBOOL((band.fStyle & RBBS_NOVERT) == RBBS_NOVERT), properties.comparisonFunction[fpHideIfVertical])) { if(properties.filterType[fpHideIfVertical] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpHideIfVertical] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpShowTitle] != ftDeactivated) { if(IsBooleanInSafeArray(properties.filter[fpShowTitle].parray, BOOL2VARIANTBOOL(!(band.fStyle & RBBS_HIDETITLE)), properties.comparisonFunction[fpShowTitle])) { if(properties.filterType[fpShowTitle] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpShowTitle] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpUseChevron] != ftDeactivated) { if(IsBooleanInSafeArray(properties.filter[fpUseChevron].parray, BOOL2VARIANTBOOL((band.fStyle & RBBS_USECHEVRON) == RBBS_USECHEVRON), properties.comparisonFunction[fpUseChevron])) { if(properties.filterType[fpUseChevron] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpUseChevron] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpNewLine] != ftDeactivated) { if(IsBooleanInSafeArray(properties.filter[fpNewLine].parray, BOOL2VARIANTBOOL((band.fStyle & RBBS_BREAK) == RBBS_BREAK), properties.comparisonFunction[fpNewLine])) { if(properties.filterType[fpNewLine] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpNewLine] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpSizingGripVisibility] != ftDeactivated) { SizingGripVisibilityConstants sgv = sgvAutomatic; if(band.fStyle & RBBS_NOGRIPPER) { sgv = sgvNever; } else if(band.fStyle & RBBS_GRIPPERALWAYS) { sgv = sgvAlways; } if(IsIntegerInSafeArray(properties.filter[fpSizingGripVisibility].parray, sgv, properties.comparisonFunction[fpSizingGripVisibility])) { if(properties.filterType[fpSizingGripVisibility] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpSizingGripVisibility] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpHContainedWindow] != ftDeactivated) { if(IsIntegerInSafeArray(properties.filter[fpHContainedWindow].parray, HandleToLong(band.hwndChild), properties.comparisonFunction[fpHContainedWindow])) { if(properties.filterType[fpHContainedWindow] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpHContainedWindow] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpCurrentHeight] != ftDeactivated) { if(IsIntegerInSafeArray(properties.filter[fpCurrentHeight].parray, band.cyChild, properties.comparisonFunction[fpCurrentHeight])) { if(properties.filterType[fpCurrentHeight] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpCurrentHeight] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpCurrentWidth] != ftDeactivated) { if(IsIntegerInSafeArray(properties.filter[fpCurrentWidth].parray, band.cx, properties.comparisonFunction[fpCurrentWidth])) { if(properties.filterType[fpCurrentWidth] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpCurrentWidth] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpMaximumHeight] != ftDeactivated) { if(IsIntegerInSafeArray(properties.filter[fpMaximumHeight].parray, band.cyMaxChild, properties.comparisonFunction[fpMaximumHeight])) { if(properties.filterType[fpMaximumHeight] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpMaximumHeight] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpMinimumHeight] != ftDeactivated) { if(IsIntegerInSafeArray(properties.filter[fpMinimumHeight].parray, band.cyMinChild, properties.comparisonFunction[fpMinimumHeight])) { if(properties.filterType[fpMinimumHeight] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpMinimumHeight] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpMinimumWidth] != ftDeactivated) { if(IsIntegerInSafeArray(properties.filter[fpMinimumWidth].parray, band.cxMinChild, properties.comparisonFunction[fpMinimumWidth])) { if(properties.filterType[fpMinimumWidth] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpMinimumWidth] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpTitleWidth] != ftDeactivated) { if(IsIntegerInSafeArray(properties.filter[fpTitleWidth].parray, band.cxHeader, properties.comparisonFunction[fpTitleWidth])) { if(properties.filterType[fpTitleWidth] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpTitleWidth] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpHBackgroundBitmap] != ftDeactivated) { if(IsIntegerInSafeArray(properties.filter[fpHBackgroundBitmap].parray, HandleToLong(band.hbmBack), properties.comparisonFunction[fpHBackgroundBitmap])) { if(properties.filterType[fpHBackgroundBitmap] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpHBackgroundBitmap] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpHeightChangeStepSize] != ftDeactivated) { if(IsIntegerInSafeArray(properties.filter[fpHeightChangeStepSize].parray, band.cyIntegral, properties.comparisonFunction[fpHeightChangeStepSize])) { if(properties.filterType[fpHeightChangeStepSize] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpHeightChangeStepSize] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpKeepInFirstRow] != ftDeactivated) { if(IsBooleanInSafeArray(properties.filter[fpKeepInFirstRow].parray, BOOL2VARIANTBOOL((band.fStyle & RBBS_TOPALIGN) == RBBS_TOPALIGN), properties.comparisonFunction[fpKeepInFirstRow])) { if(properties.filterType[fpKeepInFirstRow] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpKeepInFirstRow] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpResizable] != ftDeactivated) { if(IsBooleanInSafeArray(properties.filter[fpResizable].parray, BOOL2VARIANTBOOL(!(band.fStyle & RBBS_FIXEDSIZE)), properties.comparisonFunction[fpResizable])) { if(properties.filterType[fpResizable] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpResizable] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpVariableHeight] != ftDeactivated) { if(IsBooleanInSafeArray(properties.filter[fpVariableHeight].parray, BOOL2VARIANTBOOL((band.fStyle & RBBS_VARIABLEHEIGHT) == RBBS_VARIABLEHEIGHT), properties.comparisonFunction[fpVariableHeight])) { if(properties.filterType[fpVariableHeight] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpVariableHeight] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpFixedBackgroundBitmapOrigin] != ftDeactivated) { if(IsBooleanInSafeArray(properties.filter[fpFixedBackgroundBitmapOrigin].parray, BOOL2VARIANTBOOL((band.fStyle & RBBS_FIXEDBMP) == RBBS_FIXEDBMP), properties.comparisonFunction[fpFixedBackgroundBitmapOrigin])) { if(properties.filterType[fpFixedBackgroundBitmapOrigin] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpFixedBackgroundBitmapOrigin] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpAddMarginsAroundChild] != ftDeactivated) { if(IsBooleanInSafeArray(properties.filter[fpAddMarginsAroundChild].parray, BOOL2VARIANTBOOL((band.fStyle & RBBS_CHILDEDGE) == RBBS_CHILDEDGE), properties.comparisonFunction[fpAddMarginsAroundChild])) { if(properties.filterType[fpAddMarginsAroundChild] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpAddMarginsAroundChild] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpBackColor] != ftDeactivated) { if(IsIntegerInSafeArray(properties.filter[fpBackColor].parray, (band.clrBack == CLR_DEFAULT ? static_cast<COLORREF>(SendMessage(hWndRBar, RB_GETBKCOLOR, 0, 0)) : band.clrBack), properties.comparisonFunction[fpBackColor])) { if(properties.filterType[fpBackColor] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpBackColor] == ftIncluding) { goto Exit; } } } if(properties.filterType[fpForeColor] != ftDeactivated) { if(IsIntegerInSafeArray(properties.filter[fpForeColor].parray, (band.clrFore == CLR_DEFAULT ? static_cast<COLORREF>(SendMessage(hWndRBar, RB_GETTEXTCOLOR, 0, 0)) : band.clrFore), properties.comparisonFunction[fpForeColor])) { if(properties.filterType[fpForeColor] == ftExcluding) { goto Exit; } } else { if(properties.filterType[fpForeColor] == ftIncluding) { goto Exit; } } } } isPart = TRUE; Exit: if(band.lpText) { SECUREFREE(band.lpText); } return isPart; } void ReBarBands::OptimizeFilter(FilteredPropertyConstants filteredProperty) { if(filteredProperty != fpAddMarginsAroundChild && filteredProperty != fpFixedBackgroundBitmapOrigin && filteredProperty != fpHideIfVertical && filteredProperty != fpKeepInFirstRow && filteredProperty != fpNewLine && filteredProperty != fpResizable && filteredProperty != fpShowTitle && filteredProperty != fpUseChevron && filteredProperty != fpVariableHeight && filteredProperty != fpVisible) { // currently we optimize boolean filters only return; } LONG lBound = 0; LONG uBound = 0; SafeArrayGetLBound(properties.filter[filteredProperty].parray, 1, &lBound); SafeArrayGetUBound(properties.filter[filteredProperty].parray, 1, &uBound); // now that we have the bounds, iterate the array VARIANT element; UINT numberOfTrues = 0; UINT numberOfFalses = 0; for(LONG i = lBound; i <= uBound; ++i) { SafeArrayGetElement(properties.filter[filteredProperty].parray, &i, &element); if(element.boolVal == VARIANT_FALSE) { ++numberOfFalses; } else { ++numberOfTrues; } VariantClear(&element); } if(numberOfTrues > 0 && numberOfFalses > 0) { // we've something like True Or False Or True - we can deactivate this filter properties.filterType[filteredProperty] = ftDeactivated; VariantClear(&properties.filter[filteredProperty]); } else if(numberOfTrues == 0 && numberOfFalses > 1) { // False Or False Or False... is still False, so we need just one False VariantClear(&properties.filter[filteredProperty]); properties.filter[filteredProperty].vt = VT_ARRAY | VT_VARIANT; properties.filter[filteredProperty].parray = SafeArrayCreateVectorEx(VT_VARIANT, 1, 1, NULL); VARIANT newElement; VariantInit(&newElement); newElement.vt = VT_BOOL; newElement.boolVal = VARIANT_FALSE; LONG index = 1; SafeArrayPutElement(properties.filter[filteredProperty].parray, &index, &newElement); VariantClear(&newElement); } else if(numberOfFalses == 0 && numberOfTrues > 1) { // True Or True Or True... is still True, so we need just one True VariantClear(&properties.filter[filteredProperty]); properties.filter[filteredProperty].vt = VT_ARRAY | VT_VARIANT; properties.filter[filteredProperty].parray = SafeArrayCreateVectorEx(VT_VARIANT, 1, 1, NULL); VARIANT newElement; VariantInit(&newElement); newElement.vt = VT_BOOL; newElement.boolVal = VARIANT_TRUE; LONG index = 1; SafeArrayPutElement(properties.filter[filteredProperty].parray, &index, &newElement); VariantClear(&newElement); } } #ifdef USE_STL HRESULT ReBarBands::RemoveBands(std::list<int>& bandsToRemove, HWND hWndRBar) #else HRESULT ReBarBands::RemoveBands(CAtlList<int>& bandsToRemove, HWND hWndRBar) #endif { ATLASSERT(IsWindow(hWndRBar)); CWindowEx2(hWndRBar).InternalSetRedraw(FALSE); // sort in reverse order #ifdef USE_STL bandsToRemove.sort(std::greater<int>()); for(std::list<int>::const_iterator iter = bandsToRemove.begin(); iter != bandsToRemove.end(); ++iter) { SendMessage(hWndRBar, RB_DELETEBAND, *iter, 0); } #else // perform a crude bubble sort for(size_t j = 0; j < bandsToRemove.GetCount(); ++j) { for(size_t i = 0; i < bandsToRemove.GetCount() - 1; ++i) { if(bandsToRemove.GetAt(bandsToRemove.FindIndex(i)) < bandsToRemove.GetAt(bandsToRemove.FindIndex(i + 1))) { bandsToRemove.SwapElements(bandsToRemove.FindIndex(i), bandsToRemove.FindIndex(i + 1)); } } } for(size_t i = 0; i < bandsToRemove.GetCount(); ++i) { SendMessage(hWndRBar, RB_DELETEBAND, bandsToRemove.GetAt(bandsToRemove.FindIndex(i)), 0); } #endif CWindowEx2(hWndRBar).InternalSetRedraw(TRUE); return S_OK; } ReBarBands::Properties::~Properties() { for(int i = 0; i < NUMBEROFFILTERS_RB; ++i) { VariantClear(&filter[i]); } if(pOwnerRBar) { pOwnerRBar->Release(); } } void ReBarBands::Properties::CopyTo(ReBarBands::Properties* pTarget) { ATLASSERT_POINTER(pTarget, Properties); if(pTarget) { pTarget->pOwnerRBar = this->pOwnerRBar; if(pTarget->pOwnerRBar) { pTarget->pOwnerRBar->AddRef(); } pTarget->lastEnumeratedBand = this->lastEnumeratedBand; pTarget->caseSensitiveFilters = this->caseSensitiveFilters; for(int i = 0; i < NUMBEROFFILTERS_RB; ++i) { VariantCopy(&pTarget->filter[i], &this->filter[i]); pTarget->filterType[i] = this->filterType[i]; pTarget->comparisonFunction[i] = this->comparisonFunction[i]; } pTarget->usingFilters = this->usingFilters; } } HWND ReBarBands::Properties::GetRBarHWnd(void) { ATLASSUME(pOwnerRBar); OLE_HANDLE handle = NULL; pOwnerRBar->get_hWnd(&handle); return static_cast<HWND>(LongToHandle(handle)); } void ReBarBands::SetOwner(ReBar* pOwner) { if(properties.pOwnerRBar) { properties.pOwnerRBar->Release(); } properties.pOwnerRBar = pOwner; if(properties.pOwnerRBar) { properties.pOwnerRBar->AddRef(); } } STDMETHODIMP ReBarBands::get_CaseSensitiveFilters(VARIANT_BOOL* pValue) { ATLASSERT_POINTER(pValue, VARIANT_BOOL); if(!pValue) { return E_POINTER; } *pValue = BOOL2VARIANTBOOL(properties.caseSensitiveFilters); return S_OK; } STDMETHODIMP ReBarBands::put_CaseSensitiveFilters(VARIANT_BOOL newValue) { properties.caseSensitiveFilters = VARIANTBOOL2BOOL(newValue); return S_OK; } STDMETHODIMP ReBarBands::get_ComparisonFunction(FilteredPropertyConstants filteredProperty, LONG* pValue) { ATLASSERT_POINTER(pValue, LONG); if(!pValue) { return E_POINTER; } switch(filteredProperty) { case fpIconIndex: case fpIndex: case fpBandData: case fpText: *pValue = static_cast<LONG>(reinterpret_cast<LONG_PTR>(properties.comparisonFunction[filteredProperty])); return S_OK; break; default: if(filteredProperty >= fpAddMarginsAroundChild && filteredProperty <= fpVisible) { *pValue = static_cast<LONG>(reinterpret_cast<LONG_PTR>(properties.comparisonFunction[filteredProperty])); return S_OK; } break; } return E_INVALIDARG; } STDMETHODIMP ReBarBands::put_ComparisonFunction(FilteredPropertyConstants filteredProperty, LONG newValue) { switch(filteredProperty) { case fpIconIndex: case fpIndex: case fpBandData: case fpText: properties.comparisonFunction[filteredProperty] = reinterpret_cast<LPVOID>(static_cast<LONG_PTR>(newValue)); return S_OK; break; default: if(filteredProperty >= fpAddMarginsAroundChild && filteredProperty <= fpVisible) { properties.comparisonFunction[filteredProperty] = reinterpret_cast<LPVOID>(static_cast<LONG_PTR>(newValue)); return S_OK; } break; } return E_INVALIDARG; } STDMETHODIMP ReBarBands::get_Filter(FilteredPropertyConstants filteredProperty, VARIANT* pValue) { ATLASSERT_POINTER(pValue, VARIANT); if(!pValue) { return E_POINTER; } switch(filteredProperty) { case fpIconIndex: case fpIndex: case fpBandData: case fpText: VariantClear(pValue); VariantCopy(pValue, &properties.filter[filteredProperty]); return S_OK; break; default: if(filteredProperty >= fpAddMarginsAroundChild && filteredProperty <= fpVisible) { VariantClear(pValue); VariantCopy(pValue, &properties.filter[filteredProperty]); return S_OK; } break; } return E_INVALIDARG; } STDMETHODIMP ReBarBands::put_Filter(FilteredPropertyConstants filteredProperty, VARIANT newValue) { // check 'newValue' switch(filteredProperty) { case fpIconIndex: if(!IsValidIntegerFilter(newValue, -2)) { // invalid value - raise VB runtime error 380 return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 380); } break; case fpIndex: case fpCurrentHeight: case fpCurrentWidth: case fpHeightChangeStepSize: case fpIdealWidth: case fpMaximumHeight: case fpMinimumHeight: case fpMinimumWidth: case fpTitleWidth: if(!IsValidIntegerFilter(newValue, 0)) { // invalid value - raise VB runtime error 380 return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 380); } break; case fpSizingGripVisibility: if(!IsValidIntegerFilter(newValue, 0, 2)) { // invalid value - raise VB runtime error 380 return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 380); } break; case fpBandData: case fpBackColor: case fpForeColor: case fpHBackgroundBitmap: case fpHContainedWindow: case fpID: if(!IsValidIntegerFilter(newValue)) { // invalid value - raise VB runtime error 380 return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 380); } break; case fpText: if(!IsValidStringFilter(newValue)) { // invalid value - raise VB runtime error 380 return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 380); } break; case fpAddMarginsAroundChild: case fpFixedBackgroundBitmapOrigin: case fpHideIfVertical: case fpKeepInFirstRow: case fpNewLine: case fpResizable: case fpShowTitle: case fpUseChevron: case fpVariableHeight: case fpVisible: if(!IsValidBooleanFilter(newValue)) { // invalid value - raise VB runtime error 380 return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 380); } break; default: return E_INVALIDARG; break; } VariantClear(&properties.filter[filteredProperty]); VariantCopy(&properties.filter[filteredProperty], &newValue); OptimizeFilter(filteredProperty); return S_OK; } STDMETHODIMP ReBarBands::get_FilterType(FilteredPropertyConstants filteredProperty, FilterTypeConstants* pValue) { ATLASSERT_POINTER(pValue, FilterTypeConstants); if(!pValue) { return E_POINTER; } switch(filteredProperty) { case fpIconIndex: case fpIndex: case fpBandData: case fpText: *pValue = properties.filterType[filteredProperty]; return S_OK; break; default: if(filteredProperty >= fpAddMarginsAroundChild && filteredProperty <= fpVisible) { *pValue = properties.filterType[filteredProperty]; return S_OK; } break; } return E_INVALIDARG; } STDMETHODIMP ReBarBands::put_FilterType(FilteredPropertyConstants filteredProperty, FilterTypeConstants newValue) { if(newValue < 0 || newValue > 2) { // invalid value - raise VB runtime error 380 return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 380); } BOOL isOkay = FALSE; switch(filteredProperty) { case fpIconIndex: case fpIndex: case fpBandData: case fpText: isOkay = TRUE; break; default: isOkay = (filteredProperty >= fpAddMarginsAroundChild && filteredProperty <= fpVisible); break; } if(isOkay) { properties.filterType[filteredProperty] = newValue; if(newValue != ftDeactivated) { properties.usingFilters = TRUE; } else { properties.usingFilters = FALSE; for(int i = 0; i < NUMBEROFFILTERS_RB; ++i) { if(properties.filterType[i] != ftDeactivated) { properties.usingFilters = TRUE; break; } } } return S_OK; } return E_INVALIDARG; } STDMETHODIMP ReBarBands::get_Item(LONG bandIdentifier, BandIdentifierTypeConstants bandIdentifierType/* = bitIndex*/, IReBarBand** ppBand/* = NULL*/) { ATLASSERT_POINTER(ppBand, IReBarBand*); if(!ppBand) { return E_POINTER; } // retrieve the band's index int bandIndex = -1; switch(bandIdentifierType) { case bitID: if(properties.pOwnerRBar) { bandIndex = properties.pOwnerRBar->IDToBandIndex(bandIdentifier); } break; case bitIndex: bandIndex = bandIdentifier; break; } if(bandIndex != -1) { if(IsPartOfCollection(bandIndex)) { ClassFactory::InitReBarBand(bandIndex, properties.pOwnerRBar, IID_IReBarBand, reinterpret_cast<LPUNKNOWN*>(ppBand)); if(*ppBand) { return S_OK; } } } // band not found if(bandIdentifierType == bitIndex) { return DISP_E_BADINDEX; } else { return E_INVALIDARG; } } STDMETHODIMP ReBarBands::get__NewEnum(IUnknown** ppEnumerator) { ATLASSERT_POINTER(ppEnumerator, LPUNKNOWN); if(!ppEnumerator) { return E_POINTER; } Reset(); return QueryInterface(IID_IUnknown, reinterpret_cast<LPVOID*>(ppEnumerator)); } STDMETHODIMP ReBarBands::Add(LONG insertAt/* = -1*/, OLE_HANDLE hContainedWindow/* = NULL*/, VARIANT_BOOL newLine/* = VARIANT_FALSE*/, SizingGripVisibilityConstants sizingGripVisibility/* = sgvAutomatic*/, VARIANT_BOOL resizable/* = VARIANT_TRUE*/, VARIANT_BOOL keepInFirstRow/* = VARIANT_FALSE*/, VARIANT_BOOL visible/* = VARIANT_TRUE*/, OLE_XSIZE_PIXELS idealWidth/* = 0*/, OLE_XSIZE_PIXELS minimumWidth/* = -1*/, OLE_YSIZE_PIXELS minimumHeight/* = -1*/, OLE_YSIZE_PIXELS maximumHeight/* = -1*/, OLE_YSIZE_PIXELS heightChangeStepSize/* = -1*/, VARIANT_BOOL variableHeight/* = VARIANT_FALSE*/, VARIANT_BOOL showTitle/* = VARIANT_TRUE*/, BSTR text/* = L""*/, LONG iconIndex/* = -2*/, LONG bandData/* = 0*/, OLE_XSIZE_PIXELS titleWidth/* = -1*/, VARIANT_BOOL hideIfVertical/* = VARIANT_FALSE*/, VARIANT_BOOL addMarginsAroundChild/* = VARIANT_FALSE*/, IReBarBand** ppAddedBand/* = NULL*/) { ATLASSERT_POINTER(ppAddedBand, IReBarBand*); if(!ppAddedBand) { return E_POINTER; } if(insertAt < -1 || idealWidth < 0 || minimumWidth < -1 || minimumHeight < -1 || maximumHeight < -1 || heightChangeStepSize < -1 || titleWidth < -1) { // invalid value - raise VB runtime error 380 return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 380); } HWND hWndRBar = properties.GetRBarHWnd(); ATLASSERT(IsWindow(hWndRBar)); HRESULT hr = E_FAIL; REBARBANDINFO insertionData = {0}; insertionData.cbSize = RunTimeHelper::SizeOf_REBARBANDINFO(); insertionData.cxMinChild = static_cast<UINT>(-1); insertionData.cyChild = static_cast<UINT>(-1); insertionData.cyIntegral = static_cast<UINT>(-1); insertionData.cyMaxChild = static_cast<UINT>(-1); insertionData.cyMinChild = static_cast<UINT>(-1); insertionData.fMask = RBBIM_IDEALSIZE | RBBIM_LPARAM | RBBIM_STYLE | RBBIM_TEXT | RBBIM_SETID; insertionData.cxIdeal = idealWidth; insertionData.lParam = bandData; #ifdef UNICODE insertionData.lpText = OLE2W(text); #else COLE2T converter(text); insertionData.lpText = converter; #endif if(newLine != VARIANT_FALSE) { insertionData.fStyle |= RBBS_BREAK; } switch(sizingGripVisibility) { case sgvNever: insertionData.fStyle |= RBBS_NOGRIPPER; break; case sgvAlways: insertionData.fStyle |= RBBS_GRIPPERALWAYS; break; } if(resizable == VARIANT_FALSE) { insertionData.fStyle |= RBBS_FIXEDSIZE; } if(keepInFirstRow != VARIANT_FALSE) { insertionData.fStyle |= RBBS_TOPALIGN; } if(visible == VARIANT_FALSE) { insertionData.fStyle |= RBBS_HIDDEN; } if(variableHeight != VARIANT_FALSE) { insertionData.fStyle |= RBBS_VARIABLEHEIGHT; } if(showTitle == VARIANT_FALSE) { insertionData.fStyle |= RBBS_HIDETITLE; } if(hideIfVertical != VARIANT_FALSE) { insertionData.fStyle |= RBBS_NOVERT; } if(addMarginsAroundChild != VARIANT_FALSE) { insertionData.fStyle |= RBBS_CHILDEDGE; } if(hContainedWindow) { insertionData.fMask |= RBBIM_CHILD; insertionData.hwndChild = static_cast<HWND>(LongToHandle(hContainedWindow)); } if(minimumWidth > -1) { insertionData.fMask |= RBBIM_CHILDSIZE; insertionData.cxMinChild = minimumWidth; } if(minimumHeight > -1) { insertionData.fMask |= RBBIM_CHILDSIZE; insertionData.cyMinChild = minimumHeight; insertionData.cyChild = minimumHeight; } if(maximumHeight > -1) { insertionData.fMask |= RBBIM_CHILDSIZE; insertionData.cyMaxChild = maximumHeight; } if(heightChangeStepSize > -1) { insertionData.fMask |= RBBIM_CHILDSIZE; insertionData.cyIntegral = heightChangeStepSize; } if(iconIndex > -1) { insertionData.fMask |= RBBIM_IMAGE; insertionData.iImage = iconIndex; } if(titleWidth > -1) { insertionData.fMask |= RBBIM_HEADERSIZE; insertionData.cxHeader = titleWidth; } int insertedBand = -1; if(SendMessage(hWndRBar, RB_INSERTBAND, insertAt, reinterpret_cast<LPARAM>(&insertionData))) { ATLASSERT(insertionData.fMask & RBBIM_ID); insertedBand = properties.pOwnerRBar->IDToBandIndex(insertionData.wID); ClassFactory::InitReBarBand(insertedBand, properties.pOwnerRBar, IID_IReBarBand, reinterpret_cast<LPUNKNOWN*>(ppAddedBand)); hr = S_OK; } return hr; } STDMETHODIMP ReBarBands::Contains(LONG bandIdentifier, BandIdentifierTypeConstants bandIdentifierType/* = bitIndex*/, VARIANT_BOOL* pValue/* = NULL*/) { ATLASSERT_POINTER(pValue, VARIANT_BOOL); if(!pValue) { return E_POINTER; } // retrieve the band's index int bandIndex = -1; switch(bandIdentifierType) { case bitID: if(properties.pOwnerRBar) { bandIndex = properties.pOwnerRBar->IDToBandIndex(bandIdentifier); } break; case bitIndex: bandIndex = bandIdentifier; break; } *pValue = BOOL2VARIANTBOOL(IsPartOfCollection(bandIndex)); return S_OK; } STDMETHODIMP ReBarBands::Count(LONG* pValue) { ATLASSERT_POINTER(pValue, LONG); if(!pValue) { return E_POINTER; } HWND hWndRBar = properties.GetRBarHWnd(); ATLASSERT(IsWindow(hWndRBar)); if(!properties.usingFilters) { *pValue = SendMessage(hWndRBar, RB_GETBANDCOUNT, 0, 0); return S_OK; } // count the bands manually *pValue = 0; int numberOfBands = SendMessage(hWndRBar, RB_GETBANDCOUNT, 0, 0); int bandIndex = GetFirstBandToProcess(numberOfBands); while(bandIndex != -1) { if(IsPartOfCollection(bandIndex, hWndRBar)) { ++(*pValue); } bandIndex = GetNextBandToProcess(bandIndex, numberOfBands); } return S_OK; } STDMETHODIMP ReBarBands::Remove(LONG bandIdentifier, BandIdentifierTypeConstants bandIdentifierType/* = bitIndex*/) { HWND hWndRBar = properties.GetRBarHWnd(); ATLASSERT(IsWindow(hWndRBar)); // retrieve the band's index int bandIndex = -1; switch(bandIdentifierType) { case bitID: if(properties.pOwnerRBar) { bandIndex = properties.pOwnerRBar->IDToBandIndex(bandIdentifier); } break; case bitIndex: bandIndex = bandIdentifier; break; } if(bandIndex != -1) { if(IsPartOfCollection(bandIndex)) { if(SendMessage(hWndRBar, RB_DELETEBAND, bandIndex, 0)) { return S_OK; } } } else { // band not found if(bandIdentifierType == bitIndex) { return DISP_E_BADINDEX; } else { return E_INVALIDARG; } } return E_FAIL; } STDMETHODIMP ReBarBands::RemoveAll(void) { HWND hWndRBar = properties.GetRBarHWnd(); ATLASSERT(IsWindow(hWndRBar)); int numberOfBands = static_cast<int>(SendMessage(hWndRBar, RB_GETBANDCOUNT, 0, 0)); if(numberOfBands == -1) { return E_FAIL; } if(!properties.usingFilters) { for(int i = numberOfBands - 1; i >= 0; --i) { if(!SendMessage(hWndRBar, RB_DELETEBAND, i, 0)) { return E_FAIL; } } } // find the bands to remove manually #ifdef USE_STL std::list<int> bandsToRemove; #else CAtlList<int> bandsToRemove; #endif int bandIndex = GetFirstBandToProcess(numberOfBands); while(bandIndex != -1) { if(IsPartOfCollection(bandIndex, hWndRBar)) { #ifdef USE_STL bandsToRemove.push_back(bandIndex); #else bandsToRemove.AddTail(bandIndex); #endif } bandIndex = GetNextBandToProcess(bandIndex, numberOfBands); } return RemoveBands(bandsToRemove, hWndRBar); }
30.137955
886
0.713899
TimoKunze
befb2292d6e8c3cf870fe5b05c97003fab9bfbb6
22,288
cpp
C++
src/scripting/jb_luaapi_gui_textrsrc.cpp
JadeMatrix/jadebase
c4575cc9f0b73c18ea82b671f6b347211507b71b
[ "Zlib" ]
null
null
null
src/scripting/jb_luaapi_gui_textrsrc.cpp
JadeMatrix/jadebase
c4575cc9f0b73c18ea82b671f6b347211507b71b
[ "Zlib" ]
8
2015-02-24T19:38:35.000Z
2016-05-25T02:33:48.000Z
src/scripting/jb_luaapi_gui_textrsrc.cpp
JadeMatrix/jadebase
c4575cc9f0b73c18ea82b671f6b347211507b71b
[ "Zlib" ]
null
null
null
/* * jb_luaapi_gui_textrsrc.cpp * * Implements GUI text resource API fron jb_luaapi.hpp * */ /* INCLUDES *******************************************************************//******************************************************************************/ #include "jb_luaapi.hpp" #include "../jadebase.hpp" // Include everything /******************************************************************************//******************************************************************************/ namespace jade { namespace lua { int jade_gui_newTextRsrc( lua_State* state ) { LUA_API_SAFETY_BLOCK_BEGIN {/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int argc = lua_gettop( state ); if( argc >= 1 && !lua_isnumber( state, 1 ) ) { luaL_error( state, err_argtype( "new_text_rsrc", "", "pointsize", 1, "number" ).c_str() ); return 0; } if( argc >= 2 && !lua_isstring( state, 2 ) ) { luaL_error( state, err_argtype( "new_text_rsrc", "", "font", 2, "string" ).c_str() ); return 0; } if( argc >= 3 && !lua_isstring( state, 3 ) ) { luaL_error( state, err_argtype( "new_text_rsrc", "", "string", 3, "string" ).c_str() ); return 0; } if( argc > 3 ) { luaL_error( state, err_argcount( "new_text_rsrc", "", 2, 0, -3 ).c_str() ); return 0; } std::shared_ptr< text_rsrc >* rsrc_sp = ( std::shared_ptr< text_rsrc >* )lua_newuserdata( state, sizeof( std::shared_ptr< text_rsrc > ) ); switch( argc ) // This is set up to use default values for constructor { case 0: new( rsrc_sp ) std::shared_ptr< text_rsrc >( new text_rsrc() ); break; case 1: new( rsrc_sp ) std::shared_ptr< text_rsrc >( new text_rsrc( lua_tonumber( state, 1 ) ) ); break; case 2: new( rsrc_sp ) std::shared_ptr< text_rsrc >( new text_rsrc( lua_tonumber( state, 1 ), lua_tostring( state, 2 ) ) ); break; case 3: new( rsrc_sp ) std::shared_ptr< text_rsrc >( new text_rsrc( lua_tonumber( state, 1 ), lua_tostring( state, 2 ), lua_tostring( state, 3 ) ) ); break; default: break; } lua_newtable( state ); { lua_pushcfunction( state, jade_gui_textrsrc_dimensions ); lua_setfield( state, -2, "dimensions" ); lua_pushcfunction( state, jade_gui_textrsrc_pointSize ); lua_setfield( state, -2, "point_size" ); lua_pushcfunction( state, jade_gui_textrsrc_string ); lua_setfield( state, -2, "string" ); lua_pushcfunction( state, jade_gui_textrsrc_font ); lua_setfield( state, -2, "font" ); lua_pushcfunction( state, jade_gui_textrsrc_color ); lua_setfield( state, -2, "color" ); lua_pushcfunction( state, jade_gui_textrsrc_maxDimensions ); lua_setfield( state, -2, "max_dimensions" ); lua_pushcfunction( state, jade_gui_textrsrc_baseline ); lua_setfield( state, -2, "baseline" ); lua_pushcfunction( state, jade_gui_textrsrc_gc ); lua_setfield( state, -2, "__gc" ); lua_pushcfunction( state, jade_gui_textrsrc_tostring ); lua_setfield( state, -2, "__tostring" ); lua_pushnumber( state, JADE_TEXT_RSRC ); lua_setfield( state, -2, "__type_key" ); lua_pushstring( state, warn_metatable( __FILE__, "text_rsrc" ).c_str() ); lua_setfield( state, -2, "__metatable" ); // Protect metatable lua_pushstring( state, "__index" ); // Create object index lua_pushvalue( state, -2 ); lua_settable( state, -3 ); } lua_setmetatable( state, -2 ); return 1; }/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// LUA_API_SAFETY_BLOCK_END } int jade_gui_textrsrc_dimensions( lua_State* state ) { LUA_API_SAFETY_BLOCK_BEGIN {/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int argc = lua_gettop( state ); if( argc < 1 || getUDataType( state, 1 ) != JADE_TEXT_RSRC ) { luaL_error( state, err_objtype( "dimensions", "text_rsrc" ).c_str() ); return 0; } if( argc > 1 ) { luaL_error( state, err_argcount( "dimensions", "text_rsrc", 0 ).c_str() ); return 0; } std::shared_ptr< text_rsrc >* rsrc_sp = ( std::shared_ptr< text_rsrc >* )lua_touserdata( state, 1 ); std::pair< unsigned int, unsigned int > dims( ( *rsrc_sp ) -> getDimensions() ); lua_pushnumber( state, dims.first ); lua_pushnumber( state, dims.second ); return 2; }/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// LUA_API_SAFETY_BLOCK_END } int jade_gui_textrsrc_pointSize( lua_State* state ) { LUA_API_SAFETY_BLOCK_BEGIN {/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int argc = lua_gettop( state ); if( argc < 1 || getUDataType( state, 1 ) != JADE_TEXT_RSRC ) { luaL_error( state, err_objtype( "point_size", "text_rsrc" ).c_str() ); return 0; } std::shared_ptr< text_rsrc >* rsrc_sp = ( std::shared_ptr< text_rsrc >* )lua_touserdata( state, 1 ); switch( argc ) { case 2: if( !lua_isnumber( state, 2 ) ) { luaL_error( state, err_argtype( "point_size", "text_rsrc", "size", 1, "number" ).c_str() ); return 0; } ( *rsrc_sp ) -> setPointSize( lua_tonumber( state, 2 ) ); case 1: lua_pushnumber( state, ( *rsrc_sp ) -> getPointSize() ); break; default: luaL_error( state, err_argcount( "point_size", "text_rsrc", 2, 0, 1 ).c_str() ); return 0; } return 1; }/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// LUA_API_SAFETY_BLOCK_END } int jade_gui_textrsrc_string( lua_State* state ) { LUA_API_SAFETY_BLOCK_BEGIN {/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int argc = lua_gettop( state ); if( argc < 1 || getUDataType( state, 1 ) != JADE_TEXT_RSRC ) { luaL_error( state, err_objtype( "string", "text_rsrc" ).c_str() ); return 0; } std::shared_ptr< text_rsrc >* rsrc_sp = ( std::shared_ptr< text_rsrc >* )lua_touserdata( state, 1 ); switch( argc ) { case 2: if( !lua_isstring( state, 2 ) ) { luaL_error( state, err_argtype( "string", "text_rsrc", "string", 1, "string" ).c_str() ); return 0; } ( *rsrc_sp ) -> setString( lua_tostring( state, 2 ) ); case 1: lua_pushstring( state, ( *rsrc_sp ) -> getString().c_str() ); break; default: luaL_error( state, err_argcount( "string", "text_rsrc", 2, 0, 1 ).c_str() ); return 0; } return 1; }/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// LUA_API_SAFETY_BLOCK_END } int jade_gui_textrsrc_font( lua_State* state ) { LUA_API_SAFETY_BLOCK_BEGIN {/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int argc = lua_gettop( state ); if( argc < 1 || getUDataType( state, 1 ) != JADE_TEXT_RSRC ) { luaL_error( state, err_objtype( "font", "text_rsrc" ).c_str() ); return 0; } std::shared_ptr< text_rsrc >* rsrc_sp = ( std::shared_ptr< text_rsrc >* )lua_touserdata( state, 1 ); switch( argc ) { case 2: if( !lua_isstring( state, 2 ) ) { luaL_error( state, err_argtype( "font", "text_rsrc", "font", 1, "string" ).c_str() ); return 0; } ( *rsrc_sp ) -> setFont( lua_tostring( state, 2 ) ); case 1: lua_pushstring( state, ( *rsrc_sp ) -> getFont().c_str() ); break; default: luaL_error( state, err_argcount( "font", "text_rsrc", 2, 0, 1 ).c_str() ); return 0; } return 1; }/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// LUA_API_SAFETY_BLOCK_END } int jade_gui_textrsrc_color( lua_State* state ) { LUA_API_SAFETY_BLOCK_BEGIN {/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int argc = lua_gettop( state ); if( argc < 1 || getUDataType( state, 1 ) != JADE_TEXT_RSRC ) { luaL_error( state, err_objtype( "color", "text_rsrc" ).c_str() ); return 0; } if( argc != 5 ) { luaL_error( state, err_argcount( "color", "text_rsrc", 1, 4 ).c_str() ); return 0; } if( !lua_isnumber( state, 2 ) ) { luaL_error( state, err_argtype( "color", "text_rsrc", "red", 1, "number" ).c_str() ); return 0; } if( !lua_isnumber( state, 3 ) ) { luaL_error( state, err_argtype( "color", "text_rsrc", "green", 2, "number" ).c_str() ); return 0; } if( !lua_isnumber( state, 4 ) ) { luaL_error( state, err_argtype( "color", "text_rsrc", "blue", 3, "number" ).c_str() ); return 0; } if( !lua_isnumber( state, 5 ) ) { luaL_error( state, err_argtype( "color", "text_rsrc", "alpha", 4, "number" ).c_str() ); return 0; } std::shared_ptr< text_rsrc >* rsrc_sp = ( std::shared_ptr< text_rsrc >* )lua_touserdata( state, 1 ); ( *rsrc_sp ) -> setColor( lua_tonumber( state, 2 ), lua_tonumber( state, 3 ), lua_tonumber( state, 4 ), lua_tonumber( state, 5 ) ); return 0; }/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// LUA_API_SAFETY_BLOCK_END } int jade_gui_textrsrc_maxDimensions( lua_State* state ) { LUA_API_SAFETY_BLOCK_BEGIN {/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int argc = lua_gettop( state ); if( argc < 1 || getUDataType( state, 1 ) != JADE_TEXT_RSRC ) { luaL_error( state, err_objtype( "max_dimensions", "text_rsrc" ).c_str() ); return 0; } if( argc == 3 || argc == 4 ) { if( !lua_isnumber( state, 2 ) ) { luaL_error( state, err_argtype( "max_dimensions", "text_rsrc", "width", 1, "number" ).c_str() ); return 0; } if( !lua_isnumber( state, 3 ) ) { luaL_error( state, err_argtype( "max_dimensions", "text_rsrc", "heigth", 2, "number" ).c_str() ); return 0; } if( argc == 4 && !lua_isnumber( state, 4 ) ) { luaL_error( state, err_argtype( "max_dimensions", "text_rsrc", "ellipsis_mode", 3, "number" ).c_str() ); return 0; } } std::shared_ptr< text_rsrc >* rsrc_sp = ( std::shared_ptr< text_rsrc >* )lua_touserdata( state, 1 ); switch( argc ) { case 4: ( *rsrc_sp ) -> setMaxDimensions( lua_tonumber( state, 2 ), lua_tonumber( state, 3 ), ( text_rsrc::ellipsis_mode )lua_tonumber( state, 4 ) ); break; case 3: ( *rsrc_sp ) -> setMaxDimensions( lua_tonumber( state, 2 ), lua_tonumber( state, 3 ) ); break; case 1: break; default: luaL_error( state, err_argcount( "max_dimensions", "text_rsrc", 3, 0, 2, 3 ).c_str() ); return 0; } std::pair< int, int > max_d = ( *rsrc_sp ) -> getMaxDimensions(); lua_pushnumber( state, max_d.first ); lua_pushnumber( state, max_d.second ); return 2; }/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// LUA_API_SAFETY_BLOCK_END } int jade_gui_textrsrc_baseline( lua_State* state ) { LUA_API_SAFETY_BLOCK_BEGIN {/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int argc = lua_gettop( state ); if( argc < 1 || getUDataType( state, 1 ) != JADE_TEXT_RSRC ) { luaL_error( state, err_objtype( "baseline", "text_rsrc" ).c_str() ); return 0; } std::shared_ptr< text_rsrc >* rsrc_sp = ( std::shared_ptr< text_rsrc >* )lua_touserdata( state, 1 ); switch( argc ) { case 2: if( !lua_isboolean( state, 2 ) ) { luaL_error( state, err_argtype( "baseline", "text_rsrc", "enabled", 1, "boolean" ).c_str() ); return 0; } ( *rsrc_sp ) -> setEnableBaseline( lua_toboolean( state, 2 ) ); case 1: lua_pushboolean( state, ( *rsrc_sp ) -> getEnableBaseline() ); break; default: luaL_error( state, err_argcount( "baseline", "text_rsrc", 2, 0, 1 ).c_str() ); return 0; } return 1; }/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// LUA_API_SAFETY_BLOCK_END } int jade_gui_textrsrc_gc( lua_State* state ) { LUA_API_SAFETY_BLOCK_BEGIN {/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int argc = lua_gettop( state ); if( argc < 1 || getUDataType( state, 1 ) != JADE_TEXT_RSRC ) { luaL_error( state, err_objtype( "__gc", "text_rsrc" ).c_str() ); return 0; } if( argc > 1 ) { luaL_error( state, err_argcount( "__gc", "text_rsrc", 0 ).c_str() ); return 0; } std::shared_ptr< text_rsrc >* rsrc_sp = ( std::shared_ptr< text_rsrc >* )lua_touserdata( state, 1 ); rsrc_sp -> ~shared_ptr< text_rsrc >(); return 0; }/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// LUA_API_SAFETY_BLOCK_END } int jade_gui_textrsrc_tostring( lua_State* state ) { LUA_API_SAFETY_BLOCK_BEGIN {/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int argc = lua_gettop( state ); if( argc < 1 || getUDataType( state, 1 ) != JADE_TEXT_RSRC ) { luaL_error( state, err_objtype( "__tostring", "text_rsrc" ).c_str() ); return 0; } if( argc > 1 ) { luaL_error( state, err_argcount( "__tostring", "text_rsrc", 0 ).c_str() ); return 0; } std::shared_ptr< text_rsrc >* rsrc_sp = ( std::shared_ptr< text_rsrc >* )lua_touserdata( state, 1 ); std::string str; std::pair< unsigned int, unsigned int > dims( ( *rsrc_sp ) -> getDimensions() ); ff::write( str, "jade::text_rsrc at 0x", ff::to_x( ( unsigned long )( &**rsrc_sp ), PTR_HEX_WIDTH, PTR_HEX_WIDTH ), " (", dims.first, ",", dims.second, ")" ); lua_pushstring( state, str.c_str() ); return 1; }/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// LUA_API_SAFETY_BLOCK_END } } }
47.220339
160
0.327127
JadeMatrix
beff941d1021004cdcef7e99ba6977c1816fa6de
1,005
cpp
C++
hdu-winter-2020/problems/字符串/1005.cpp
songhn233/Algorithm-Packages
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
[ "CC0-1.0" ]
1
2020-08-10T21:40:21.000Z
2020-08-10T21:40:21.000Z
hdu-winter-2020/problems/字符串/1005.cpp
songhn233/Algorithm-Packages
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
[ "CC0-1.0" ]
null
null
null
hdu-winter-2020/problems/字符串/1005.cpp
songhn233/Algorithm-Packages
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
[ "CC0-1.0" ]
null
null
null
#include<cstdio> #include<algorithm> #include<cstring> #include<iostream> #include<vector> #include<queue> #include<cmath> #include<map> #include<set> #define ll long long #define F(i,a,b) for(int i=(a);i<=(b);i++) #define mst(a,b) memset((a),(b),sizeof(a)) #define PII pair<int,int> using namespace std; template<class T>inline void read(T &x) { x=0; int ch=getchar(),f=0; while(ch<'0'||ch>'9'){if (ch=='-') f=1;ch=getchar();} while (ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();} if(f)x=-x; } const int inf=0x3f3f3f3f; const int maxn=1000050; int n,tire[maxn][30],num; string s; void insert(string s) { int p=0; for(int i=0;i<s.size();i++) { if(tire[p][s[i]-'a']) p=tire[p][s[i]-'a']; else { tire[p][s[i]-'a']=++num; p=num; } } } int main() { while(~scanf("%d",&n)) { num=0; int maxx=0; memset(tire,0,sizeof(tire)); for(int i=1;i<=n;i++) { cin>>s; insert(s); maxx=max(maxx,(int)s.size()); } cout<<2*num+n-maxx<<endl; } return 0; }
17.946429
67
0.573134
songhn233
8301b8c81bf5259d7fc3f689b17aade9077f4e89
113
hpp
C++
Motionless/include/State.hpp
rcurtis/Motionless
e64d13be03ddbf22f849aed4232455f89bf78005
[ "MIT" ]
1
2017-02-15T04:05:11.000Z
2017-02-15T04:05:11.000Z
Motionless/include/State.hpp
rcurtis/Motionless
e64d13be03ddbf22f849aed4232455f89bf78005
[ "MIT" ]
null
null
null
Motionless/include/State.hpp
rcurtis/Motionless
e64d13be03ddbf22f849aed4232455f89bf78005
[ "MIT" ]
null
null
null
#pragma once namespace mt { enum class State { Stopped, Playing, Paused }; }
10.272727
20
0.486726
rcurtis
8307c8e09b0b7dce2308a84bb171ed7e1847663e
616
cpp
C++
test/reverse/core/var_unittest.cpp
kilasuelika/FastAD
dd070c608c18f5391f2ac68dca4f9db223a33eca
[ "MIT" ]
50
2019-11-28T22:25:01.000Z
2022-02-20T03:55:19.000Z
test/reverse/core/var_unittest.cpp
kilasuelika/FastAD
dd070c608c18f5391f2ac68dca4f9db223a33eca
[ "MIT" ]
25
2019-11-28T20:44:12.000Z
2021-10-30T00:14:39.000Z
test/reverse/core/var_unittest.cpp
kilasuelika/FastAD
dd070c608c18f5391f2ac68dca4f9db223a33eca
[ "MIT" ]
2
2021-02-26T11:14:56.000Z
2021-07-07T06:40:18.000Z
#include <gtest/gtest.h> #include <fastad_bits/reverse/core/var.hpp> namespace ad { namespace core { struct var_fixture : ::testing::Test { protected: using value_t = double; using scl_v_t = Var<value_t, scl>; using vec_v_t = Var<value_t, vec>; using mat_v_t = Var<value_t, mat>; template <class T> void test_ctor(T&& tmp) { T x(std::forward<T>(tmp)); T y = x; y = x; x = std::move(y); } }; TEST_F(var_fixture, var_ctors) { test_ctor(scl_v_t()); test_ctor(vec_v_t(1)); test_ctor(mat_v_t(1,2)); } } // namespace core } // namespace ad
18.117647
43
0.599026
kilasuelika
8309ed90755f198e0cf680ed488a977f00f4eb65
2,286
cpp
C++
UE4.26/IGLMeshProcessingProject/Plugins/MeshProcessingPlugin/Source/MeshProcessingPlugin/Private/MeshProcessingPluginStyle.cpp
VonHirsch/UnrealMeshProcessingTools
5380cfda12d2370c3744884280ecb10cd4967e35
[ "MIT" ]
153
2020-01-06T05:59:28.000Z
2022-03-23T03:43:15.000Z
UE4.26/IGLMeshProcessingProject/Plugins/MeshProcessingPlugin/Source/MeshProcessingPlugin/Private/MeshProcessingPluginStyle.cpp
VonHirsch/UnrealMeshProcessingTools
5380cfda12d2370c3744884280ecb10cd4967e35
[ "MIT" ]
6
2020-04-17T05:11:59.000Z
2022-03-14T00:15:25.000Z
UE4.26/IGLMeshProcessingProject/Plugins/MeshProcessingPlugin/Source/MeshProcessingPlugin/Private/MeshProcessingPluginStyle.cpp
VonHirsch/UnrealMeshProcessingTools
5380cfda12d2370c3744884280ecb10cd4967e35
[ "MIT" ]
48
2020-05-23T16:43:59.000Z
2022-03-22T06:05:31.000Z
#include "MeshProcessingPluginStyle.h" #include "Styling/SlateStyleRegistry.h" #include "Styling/SlateTypes.h" #include "Styling/CoreStyle.h" #include "EditorStyleSet.h" #include "Interfaces/IPluginManager.h" #include "SlateOptMacros.h" //======================================= // EVERYTHING BELOW HERE IS BOILERPLATE! //======================================= #define IMAGE_PLUGIN_BRUSH( RelativePath, ... ) FSlateImageBrush( FMeshProcessingPluginStyle::InContent( RelativePath, ".png" ), __VA_ARGS__ ) #define IMAGE_BRUSH(RelativePath, ...) FSlateImageBrush(StyleSet->RootToContentDir(RelativePath, TEXT(".png")), __VA_ARGS__) #define BOX_BRUSH(RelativePath, ...) FSlateBoxBrush(StyleSet->RootToContentDir(RelativePath, TEXT(".png")), __VA_ARGS__) #define DEFAULT_FONT(...) FCoreStyle::GetDefaultFontStyle(__VA_ARGS__) FString FMeshProcessingPluginStyle::InContent(const FString& RelativePath, const ANSICHAR* Extension) { static FString ContentDir = IPluginManager::Get().FindPlugin(TEXT("MeshToolPlugin"))->GetContentDir(); return (ContentDir / RelativePath) + Extension; } TSharedPtr<FSlateStyleSet> FMeshProcessingPluginStyle::StyleSet = nullptr; FName FMeshProcessingPluginStyle::GetStyleSetName() { static FName StyleName(TEXT("MeshProcessingPluginStyle")); return StyleName; } BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION void FMeshProcessingPluginStyle::Initialize() { // Const icon sizes const FVector2D Icon8x8(8.0f, 8.0f); const FVector2D Icon16x16(16.0f, 16.0f); const FVector2D Icon20x20(20.0f, 20.0f); const FVector2D Icon28x28(28.0f, 28.0f); const FVector2D Icon40x40(40.0f, 40.0f); // Only register once if (StyleSet.IsValid()) { return; } StyleSet = MakeShareable(new FSlateStyleSet(GetStyleSetName())); StyleSet->SetContentRoot(FPaths::EnginePluginsDir() / TEXT("MeshToolPlugin/Content")); StyleSet->SetCoreContentRoot(FPaths::EngineContentDir() / TEXT("Slate")); FSlateStyleRegistry::RegisterSlateStyle(*StyleSet.Get()); }; END_SLATE_FUNCTION_BUILD_OPTIMIZATION #undef IMAGE_PLUGIN_BRUSH #undef IMAGE_BRUSH #undef BOX_BRUSH #undef DEFAULT_FONT void FMeshProcessingPluginStyle::Shutdown() { if (StyleSet.IsValid()) { FSlateStyleRegistry::UnRegisterSlateStyle(*StyleSet.Get()); ensure(StyleSet.IsUnique()); StyleSet.Reset(); } }
31.75
142
0.755031
VonHirsch
830acf9ea1ed3894eacfb8df720b563a4654dc90
134
cpp
C++
src/sa-bsn/system_manager/enactor/apps/controller.cpp
gabrielevi10/bsn
2d42aa006933caf75365bb327fd7d79ae30c88b7
[ "MIT" ]
8
2020-01-26T15:26:27.000Z
2022-01-05T15:38:07.000Z
src/sa-bsn/system_manager/enactor/apps/controller.cpp
gabrielevi10/bsn
2d42aa006933caf75365bb327fd7d79ae30c88b7
[ "MIT" ]
50
2019-08-29T23:52:43.000Z
2021-01-24T19:09:54.000Z
src/sa-bsn/system_manager/enactor/apps/controller.cpp
gabrielevi10/bsn
2d42aa006933caf75365bb327fd7d79ae30c88b7
[ "MIT" ]
4
2019-06-15T17:23:57.000Z
2020-10-16T20:09:41.000Z
#include "controller/Controller.hpp" int main(int argc, char **argv) { Controller c(argc, argv, "enactor"); return c.run(); }
22.333333
40
0.656716
gabrielevi10
9b0042645b3fa15cf56977c4ed688c05f5b23b2c
516
cpp
C++
src/ResourceEntry.cpp
skaarj1989/FrameGraph
326e6762dcec39e6dbe529fb1be88910f7e33377
[ "MIT" ]
3
2022-03-17T06:55:17.000Z
2022-03-25T06:08:11.000Z
src/ResourceEntry.cpp
skaarj1989/FrameGraph
326e6762dcec39e6dbe529fb1be88910f7e33377
[ "MIT" ]
null
null
null
src/ResourceEntry.cpp
skaarj1989/FrameGraph
326e6762dcec39e6dbe529fb1be88910f7e33377
[ "MIT" ]
2
2022-03-17T06:55:05.000Z
2022-03-25T05:06:50.000Z
#include "fg/ResourceEntry.hpp" std::string ResourceEntry::toString() const { return m_concept->toString(); } void ResourceEntry::create(void *allocator) { assert(isTransient()); m_concept->create(allocator); } void ResourceEntry::destroy(void *allocator) { assert(isTransient()); m_concept->destroy(allocator); } uint32_t ResourceEntry::getVersion() const { return m_version; } bool ResourceEntry::isImported() const { return m_imported; } bool ResourceEntry::isTransient() const { return !m_imported; }
30.352941
77
0.75
skaarj1989
9b0b13b949ba93854a196b97a4bb3a981ed96444
554
hpp
C++
trview.common/Json.hpp
chreden/trview
e2a5e3539036f27adfa54fc7fcf4c3537b99a221
[ "MIT" ]
20
2018-10-17T02:00:03.000Z
2022-03-24T09:37:20.000Z
trview.common/Json.hpp
chreden/trview
e2a5e3539036f27adfa54fc7fcf4c3537b99a221
[ "MIT" ]
396
2018-07-22T16:11:47.000Z
2022-03-29T11:57:03.000Z
trview.common/Json.hpp
chreden/trview
e2a5e3539036f27adfa54fc7fcf4c3537b99a221
[ "MIT" ]
8
2018-07-25T21:31:06.000Z
2021-11-01T14:36:26.000Z
#pragma once namespace trview { template <typename T> T read_attribute(const nlohmann::json& json, const std::string& attribute_name) { if (json.count(attribute_name) != 0) { return json[attribute_name].get<T>(); } return {}; } template <typename T> void read_attribute(const nlohmann::json& json, T& destination, const std::string& attribute_name) { if (json.count(attribute_name) != 0) { destination = json[attribute_name].get<T>(); } } }
24.086957
102
0.579422
chreden
9b153db6366c8a38ec0f67d10e3754c52cec7071
1,522
hpp
C++
SDK/ARKSurvivalEvolved_MissionModule_zSubmodule_CompanionReaction_Base_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_MissionModule_zSubmodule_CompanionReaction_Base_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_MissionModule_zSubmodule_CompanionReaction_Base_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_MissionModule_zSubmodule_CompanionReaction_Base_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function MissionModule_zSubmodule_CompanionReaction_Base.MissionModule_zSubmodule_CompanionReaction_Base_C.HandleMissionModuleBegin struct UMissionModule_zSubmodule_CompanionReaction_Base_C_HandleMissionModuleBegin_Params { int ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function MissionModule_zSubmodule_CompanionReaction_Base.MissionModule_zSubmodule_CompanionReaction_Base_C.TriggerMissionModuleBegin struct UMissionModule_zSubmodule_CompanionReaction_Base_C_TriggerMissionModuleBegin_Params { }; // Function MissionModule_zSubmodule_CompanionReaction_Base.MissionModule_zSubmodule_CompanionReaction_Base_C.ExecuteUbergraph_MissionModule_zSubmodule_CompanionReaction_Base struct UMissionModule_zSubmodule_CompanionReaction_Base_C_ExecuteUbergraph_MissionModule_zSubmodule_CompanionReaction_Base_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
39.025641
174
0.687911
2bite
9b18fc07e0897f6f97b2d7ac8685843fd95a7e69
9,835
cc
C++
core/mm/slab.cc
TheCool1Kevin/LiquiDOS
721f26bb915599e9b001d8331d993da83078323f
[ "MIT" ]
12
2017-09-02T01:36:32.000Z
2019-09-17T12:49:49.000Z
core/mm/slab.cc
TheOneKevin/LiquiDOS
721f26bb915599e9b001d8331d993da83078323f
[ "MIT" ]
4
2017-08-16T07:58:13.000Z
2019-12-28T06:06:03.000Z
core/mm/slab.cc
TheOneKevin/LiquiDOS
721f26bb915599e9b001d8331d993da83078323f
[ "MIT" ]
2
2019-03-15T21:59:40.000Z
2019-12-08T16:11:18.000Z
/** * Copyright (c) 2019 The cxkernel Authors. All rights reserved. * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT * * @file slab.cc * @author Kevin Dai \<kevindai02@outlook.com\> * @date Created on June 06 2019, 5:50 PM */ #define __MODULE__ "[SLAB]" #include <math.h> #include <string.h> #include <assert.h> #include <linked_list.h> #include "arch/interface.h" #include "core/memory.h" #define SLAB_MAX_SIZE 256 #define IS_OBJECT_IN_SLAB(c, s, o) ((virt_t)(s)->objects >= (virt_t)(o) && (virt_t)(o) <= (virt_t)(s)->objects + ((c)->slab_size * (c)->slab_objects)) namespace kmem { static slabcache_t root_cache; static void init_cache(slabcache_t* cache, size_t size) { INIT_LLIST(&cache -> list_free); INIT_LLIST(&cache -> list_full); INIT_LLIST(&cache -> list_partial); INIT_LLIST(&cache -> node); cache -> order = 0; cache -> slab_size = size; cache -> slab_objects = 0; // Calculate the number of objects that can fit inside one slab // TODO: Improve algorithm for calculation cache order int free = ARCH_PAGE_SIZE; // Minimum number of pages to fit object (object might be > 1 page) while(free - (int)(size + sizeof(kmem_objctl_t) + sizeof(slab_t)) < 0) free *= 2, cache -> order++; free -= sizeof(slab_t); while(free - (int)(size + sizeof(kmem_objctl_t)) >= 0) free -= size + sizeof(kmem_objctl_t), cache -> slab_objects++; // Note that in Linux: // "The offset is in units of BYTES_PER_WORD unless SLAB_HWCACHE_ALIGN is set, in which case // it is aligned to blocks of L1_CACHE_BYTES for alignment to the L1 hardware cache." // and // "Coloring leads to moving some of the free area of the slab from the end to the beginning." // Therefore we may wish to partition the remaining space into chunks the size of the L1 cache. cache -> colour_next = 0; cache -> colour_num = free / 64; // TODO: Change... } static slabcache_t* get_cache(size_t size) { // Find best fit slab slabcache_t* cache = &root_cache; slabcache_t* best = NULL; size_t delta = SLAB_MAX_SIZE; while(cache -> node.next != NULL) { if(cache -> slab_size >= size && cache -> slab_size - size <= delta) delta = cache -> slab_size - size, best = cache; cache = LIST_ENTRY(cache -> node.next, slabcache_t, node); } if(cache -> slab_size >= size && cache -> slab_size - size <= delta) delta = cache -> slab_size - size, best = cache; return best; } static slabcache_t* find_cache_kmalloc(const void* buf) { list_head_t* cur = &root_cache.node; slab_t* ptr = NULL; while(cur != NULL) { slabcache_t* cache = LIST_ENTRY(cur, slabcache_t, node); if(strstr(cache -> name, "ubxela") != NULL) { foreach_llist_entry(ptr, node, cache -> list_full.next) { if(IS_OBJECT_IN_SLAB(cache, ptr, buf)) return cache; } foreach_llist_entry(ptr, node, cache -> list_partial.next) { if(IS_OBJECT_IN_SLAB(cache, ptr, buf)) return cache; } } cur = cache -> node.next; } return NULL; } void init() { init_cache(&root_cache, sizeof(slabcache_t)); } slabcache_t* new_cache(size_t size) { slabcache_t* cache = (slabcache_t*) cache_alloc(sizeof(slabcache_t)); if(cache == NULL) return NULL; init_cache(cache, size); list_append(&root_cache.node, &cache -> node); return cache; } void* cache_alloc(size_t size) { if(pmm::get_allocator().get_type() != PMM_TYPE_LIST) return NULL; slabcache_t* cache = get_cache(size); if(cache == NULL) return NULL; slab_t* slab = NULL; // Do we need more slabs? if(list_count(&cache -> list_free) == 0 && list_count(&cache -> list_partial) == 0) { /** * Layout of a single slab: * +--------+-----------------+---------------+ * | slab_t | kmem_objctl_t[] | color padding | objects... * +--------+-----------------+---------------+ * ^ void* page * Note: bufctl[i] = i+1 * bufctl [i] [i+1] [i+2] ... * +---^ +---^ etc... * Which means that when we free, we can consult bufctl to give us the next * free object. See https://www.kernel.org/doc/gorman/html/understand/understand011.html */ list_node_t* page = NULL; pmm::get_allocator().allocate_contiguous(1 << (cache -> order), (uintptr_t) &page); // TODO: Make more portable slab = (slab_t*) (pmm::get_phys(LIST_ENTRY(page, page_t, node)) + ARCH_KMALLOC_BASE); INIT_LLIST(&slab -> node); // Fill in structure slab -> parent = cache; slab -> colour_offset = cache -> colour_next * 64; // TODO: Change slab -> free = 0; slab -> inuse = 0; slab -> objects = (void*)((virt_t) slab + sizeof(slab_t) + cache -> slab_objects * sizeof(kmem_objctl_t) + slab -> colour_offset); cache -> colour_next = (cache -> colour_next + 1) % (cache -> colour_num + 1); // Fill in bufctl kmem_objctl_t* bufctl = (kmem_objctl_t*)((virt_t) slab + sizeof(slab_t)); void* obj = slab -> objects; memset((void*) bufctl, 0, sizeof(kmem_objctl_t) * cache -> slab_objects); for (unsigned int i = 0; i < cache -> slab_objects; i++) { // TODO: CTOR obj = (void*)((virt_t) obj + cache -> slab_size); bufctl[i] = i+1; } } // Partial first, then free else if(list_count(&cache -> list_partial)) { slab = LIST_ENTRY(cache -> list_partial.next, slab_t, node); list_remove(&slab -> node); } else if(list_count(&cache -> list_free)) { slab = LIST_ENTRY(cache -> list_free.next, slab_t, node); list_remove(&slab -> node); } ASSERT_HARD(slab != NULL, "Fatal error! Slab cannot be empty."); void* ret = (void*)((virt_t) slab -> objects + slab -> free * cache -> slab_size); kmem_objctl_t* bufctl = (kmem_objctl_t*)((virt_t) slab + sizeof(slab_t)); slab -> free = bufctl[slab -> free]; slab -> inuse++; // Adjust state if(slab -> inuse == cache -> slab_objects) list_append(&cache -> list_full, &slab -> node); else if(slab -> inuse == 0) list_append(&cache -> list_free, &slab -> node); else list_append(&cache -> list_partial, &slab -> node); return ret; } void cache_free(slabcache_t* cache, const void* obj) { if(cache == NULL) return; // TODO: Error slab_t* slab = NULL; bool isObjInFull = true; // Search full list { slab_t* ptr = NULL; foreach_llist_entry(ptr, node, cache -> list_full.next) { if(IS_OBJECT_IN_SLAB(cache, ptr, obj)) { slab = ptr; break; } } } // Search partial list if(slab == NULL) { slab_t* ptr = NULL; isObjInFull = false; foreach_llist_entry(ptr, node, cache -> list_partial.next) { if(IS_OBJECT_IN_SLAB(cache, ptr, obj)) { slab = ptr; break; } } } if(slab == NULL) return; // TODO: Error // Adjust slabs unsigned int id = ((unsigned int) obj - (unsigned int) slab -> objects) / cache -> slab_size; kmem_objctl_t* bufctl = (kmem_objctl_t*)((virt_t) slab + sizeof(slab_t)); bufctl[id] = slab -> free; slab -> free = id; slab -> inuse--; // We should guarantee at least 2 objects per slab if(isObjInFull) { // Full slabs must become partial list_remove(&slab -> node); list_append(&cache -> list_partial, &slab -> node); } else { // Partial slabs can only be partial or free if(slab -> inuse == 0) { list_remove(&slab -> node); list_append(&cache -> list_free, &slab -> node); } } } void *kmalloc(size_t size) { size_t j = (size_t) next_pow2l((uint64_t) size); slabcache_t* best = get_cache(j); if(best == NULL || best -> slab_size != j) { best = new_cache(j); strcpy(best -> name, "ubxela\0"); } void* alloc = cache_alloc(j); return alloc; } void kfree(void* obj) { slabcache_t* cache = find_cache_kmalloc(obj); if(cache == NULL) return; cache_free(cache, obj); // TODO: Shrink cache if needed } }
34.875887
151
0.506151
TheCool1Kevin
9b1d7b807be9ac9a2903aa818f0b1df381a9d77c
1,104
cpp
C++
leetcode-problems/medium/139-word-break.cpp
formatkaka/dsalgo
a7c7386c5c161e23bc94456f93cadd0f91f102fa
[ "Unlicense" ]
null
null
null
leetcode-problems/medium/139-word-break.cpp
formatkaka/dsalgo
a7c7386c5c161e23bc94456f93cadd0f91f102fa
[ "Unlicense" ]
null
null
null
leetcode-problems/medium/139-word-break.cpp
formatkaka/dsalgo
a7c7386c5c161e23bc94456f93cadd0f91f102fa
[ "Unlicense" ]
null
null
null
// // Created by Siddhant on 2019-11-11. // #include "iostream" #include "vector" #include "string" #include "unordered_map" using namespace std; unordered_map<string, bool> map; bool wordBreak(string s, vector<string> &wordDict) { if (s.empty()) { return true; } if(map.find(s) != map.end()){ cout << "using cache : " << s << endl; return map[s]; } bool got = false; for (int i = 0; i < wordDict.size(); i++) { int find = s.find(wordDict[i]); if ( find != string::npos) { string sub1 = s.substr(0, find); string sub2 = s.substr(find+wordDict[i].length()); // cout << "s : " << s << " dict : " << wordDict[i] << " sub1 : " << sub1 << " sub2 : " << sub2 << endl; got = got || (wordBreak(sub1, wordDict) && wordBreak(sub2, wordDict)); } } map.insert(make_pair(s, got)); return got; } int main() { string s = "catsandog"; vector<string> dict = {"cats", "dog", "sand", "and", "cat"}; cout << "break : " << endl << wordBreak(s, dict); return 0; }
21.230769
115
0.51721
formatkaka
9b1dc1e5061574115bce16b4127c33e666569b5b
6,023
cpp
C++
source/quantum-script-extension-random.cpp
g-stefan/quantum-script-extension-random
26746cad95d3104a933a3add824a5f499c47e9a7
[ "MIT", "Unlicense" ]
null
null
null
source/quantum-script-extension-random.cpp
g-stefan/quantum-script-extension-random
26746cad95d3104a933a3add824a5f499c47e9a7
[ "MIT", "Unlicense" ]
null
null
null
source/quantum-script-extension-random.cpp
g-stefan/quantum-script-extension-random
26746cad95d3104a933a3add824a5f499c47e9a7
[ "MIT", "Unlicense" ]
null
null
null
// // Quantum Script Extension Random // // Copyright (c) 2020-2021 Grigore Stefan <g_stefan@yahoo.com> // Created by Grigore Stefan <g_stefan@yahoo.com> // // MIT License (MIT) <http://opensource.org/licenses/MIT> // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "quantum-script-extension-random-license.hpp" #include "quantum-script-extension-random.hpp" #include "quantum-script-extension-random-variablerandom.hpp" #ifndef QUANTUM_SCRIPT_EXTENSION_RANDOM_NO_VERSION #include "quantum-script-extension-random-version.hpp" #endif #include "quantum-script-variableboolean.hpp" #include "quantum-script-variablenumber.hpp" #include "quantum-script-variablestring.hpp" //#define QUANTUM_SCRIPT_VM_DEBUG_RUNTIME namespace Quantum { namespace Script { namespace Extension { namespace Random { using namespace XYO; using namespace Quantum::Script; RandomContext::RandomContext() { symbolFunctionRandom = 0; prototypeRandom.pointerLink(this); }; RandomContext *getContext() { return TSingleton<RandomContext>::getValue(); }; static TPointer<Variable> functionRandom(VariableFunction *function, Variable *this_, VariableArray *arguments) { return VariableRandom::newVariable(); }; static void deleteContext() { RandomContext *randomContext = getContext(); randomContext->prototypeRandom.deleteMemory(); randomContext->symbolFunctionRandom = 0; }; static void newContext(Executive *executive, void *extensionId) { VariableFunction *defaultPrototypeFunction; RandomContext *randomContext = getContext(); executive->setExtensionDeleteContext(extensionId, deleteContext); randomContext->symbolFunctionRandom = Context::getSymbol("Random"); randomContext->prototypeRandom.newMemory(); defaultPrototypeFunction = (VariableFunction *)VariableFunction::newVariable(nullptr, nullptr, nullptr, functionRandom, nullptr, nullptr); (Context::getGlobalObject())->setPropertyBySymbol(randomContext->symbolFunctionRandom, defaultPrototypeFunction); randomContext->prototypeRandom = defaultPrototypeFunction->prototype; }; static Number toNumber_(Variable *value) { return ((Number)((static_cast<VariableRandom *>(value))->value.getValue())) / (double)4294967296.0; }; static Number toInteger_(Variable *value) { return ((Number)((static_cast<VariableRandom *>(value))->value.getValue())); }; static TPointer<Variable> nextRandom(VariableFunction *function, Variable *this_, VariableArray *arguments) { #ifdef QUANTUM_SCRIPT_DEBUG_RUNTIME printf("- random-next-random\n"); #endif if(!TIsType<VariableRandom>(this_)) { throw(Error("invalid parameter")); }; ((VariableRandom *)( this_ ))->value.nextRandom(); return VariableNumber::newVariable(toNumber_(this_)); }; static TPointer<Variable> toInteger(VariableFunction *function, Variable *this_, VariableArray *arguments) { #ifdef QUANTUM_SCRIPT_DEBUG_RUNTIME printf("- random-to-integer\n"); #endif if(!TIsType<VariableRandom>(this_)) { throw(Error("invalid parameter")); }; return VariableNumber::newVariable(toInteger_(this_)); }; static TPointer<Variable> toNumber(VariableFunction *function, Variable *this_, VariableArray *arguments) { #ifdef QUANTUM_SCRIPT_DEBUG_RUNTIME printf("- random-to-number\n"); #endif if(!TIsType<VariableRandom>(this_)) { throw(Error("invalid parameter")); }; return VariableNumber::newVariable(toNumber_(this_)); }; static TPointer<Variable> toString(VariableFunction *function, Variable *this_, VariableArray *arguments) { #ifdef QUANTUM_SCRIPT_DEBUG_RUNTIME printf("- random-to-string\n"); #endif if(!TIsType<VariableRandom>(this_)) { throw(Error("invalid parameter")); }; return VariableString::newVariable(VariableNumber::toStringX(toNumber_(this_))); }; static TPointer<Variable> seed(VariableFunction *function, Variable *this_, VariableArray *arguments) { #ifdef QUANTUM_SCRIPT_DEBUG_RUNTIME printf("- random-seed\n"); #endif if(!TIsType<VariableRandom>(this_)) { throw(Error("invalid parameter")); }; Number value = (arguments->index(0))->toNumber(); if(isnan(value) || isinf(value) || signbit(value)) { return VariableBoolean::newVariable(false); }; ((VariableRandom *)( this_ ))->value.seed((Integer)value); return VariableBoolean::newVariable(true); }; void registerInternalExtension(Executive *executive) { executive->registerInternalExtension("Random", initExecutive); }; void initExecutive(Executive *executive, void *extensionId) { String info = "Random\r\n"; info << License::shortContent(); executive->setExtensionName(extensionId, "Random"); executive->setExtensionInfo(extensionId, info); #ifndef QUANTUM_SCRIPT_EXTENSION_RANDOM_NO_VERSION executive->setExtensionVersion(extensionId, Extension::Random::Version::versionWithBuild()); #endif executive->setExtensionPublic(extensionId, true); newContext(executive, extensionId); executive->setFunction2("Random.prototype.next()", nextRandom); executive->setFunction2("Random.prototype.toInteger()", toInteger); executive->setFunction2("Random.prototype.toNumber()", toNumber); executive->setFunction2("Random.prototype.toString()", toString); executive->setFunction2("Random.prototype.seed(x)", seed); }; }; }; }; }; #ifdef XYO_COMPILE_DYNAMIC_LIBRARY extern "C" QUANTUM_SCRIPT_EXTENSION_RANDOM_EXPORT void quantumScriptExtension(Quantum::Script::Executive *executive, void *extensionId) { Quantum::Script::Extension::Random::initExecutive(executive, extensionId); }; #endif
32.38172
144
0.699485
g-stefan
9b1ddbe9922eed1a4d5202f886a990f049dbac93
886
cpp
C++
firmware/src/hsvtorgb.cpp
atomic14/moon_lamp_public
058e9b4040d49137f4738efea58d9c398b457110
[ "CC0-1.0" ]
null
null
null
firmware/src/hsvtorgb.cpp
atomic14/moon_lamp_public
058e9b4040d49137f4738efea58d9c398b457110
[ "CC0-1.0" ]
5
2021-03-10T22:49:15.000Z
2022-02-27T06:58:42.000Z
firmware/src/hsvtorgb.cpp
atomic14/moon_lamp_public
058e9b4040d49137f4738efea58d9c398b457110
[ "CC0-1.0" ]
null
null
null
#include <Arduino.h> #include <cmath> #include "hsvtorgb.h" rgb_t HSVtoRGB(int h, double s, double v) { double c = s * v; double x = c * (1 - std::abs(fmod(h / 60.0, 2) - 1)); double m = v - c; double r, g, b; if (h >= 0 && h < 60) { r = c; g = x; b = 0; } else if (h >= 60 && h < 120) { r = x; g = c; b = 0; } else if (h >= 120 && h < 180) { r = 0; g = c; b = x; } else if (h >= 180 && h < 240) { r = 0; g = x; b = c; } else if (h >= 240 && h < 300) { r = x; g = 0; b = c; } else { r = c; g = 0; b = x; } rgb_t result = { uint8_t((r + m) * 255.0), uint8_t((g + m) * 255.0), uint8_t((b + m) * 255.0)}; return result; }
16.109091
57
0.327314
atomic14
9b207c257fcc28b254f94cd2fc6dfb70a91f3e2a
81,018
cpp
C++
Blizzlike/Trinity/Scripts/Zones/borean_tundra.cpp
499453466/Lua-Other
43fd2b72405faf3f2074fd2a2706ef115d16faa6
[ "Unlicense" ]
2
2015-06-23T16:26:32.000Z
2019-06-27T07:45:59.000Z
Blizzlike/Trinity/Scripts/Zones/borean_tundra.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
null
null
null
Blizzlike/Trinity/Scripts/Zones/borean_tundra.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
3
2015-01-10T18:22:59.000Z
2021-04-27T21:28:28.000Z
/* * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Borean_Tundra SD%Complete: 100 SDComment: Quest support: 11708. Taxi vendors. SDCategory: Borean Tundra EndScriptData */ /* ContentData npc_iruk npc_corastrasza npc_jenny npc_sinkhole_kill_credit npc_khunok_the_behemoth npc_scourge_prisoner mob_nerubar_victim npc_keristrasza npc_nesingwary_trapper npc_lurgglbr npc_nexus_drake_hatchling EndContentData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "ScriptedEscortAI.h" #include "ScriptedFollowerAI.h" /*###### ## npc_sinkhole_kill_credit ######*/ enum eSinkhole { SPELL_SET_CART = 46797, SPELL_EXPLODE_CART = 46799, SPELL_SUMMON_CART = 46798, SPELL_SUMMON_WORM = 46800, }; class npc_sinkhole_kill_credit : public CreatureScript { public: npc_sinkhole_kill_credit() : CreatureScript("npc_sinkhole_kill_credit") { } struct npc_sinkhole_kill_creditAI : public ScriptedAI { npc_sinkhole_kill_creditAI(Creature* creature) : ScriptedAI(creature){} uint32 uiPhaseTimer; uint8 Phase; uint64 casterGuid; void Reset() { uiPhaseTimer = 500; Phase = 0; casterGuid = 0; } void SpellHit(Unit* caster, const SpellInfo* spell) { if (Phase) return; if (spell->Id == SPELL_SET_CART && caster->GetTypeId() == TYPEID_PLAYER && CAST_PLR(caster)->GetQuestStatus(11897) == QUEST_STATUS_INCOMPLETE) { Phase = 1; casterGuid = caster->GetGUID(); } } void EnterCombat(Unit* /*who*/){} void UpdateAI(const uint32 diff) { if (!Phase) return; if (uiPhaseTimer <= diff) { switch (Phase) { case 1: DoCast(me, SPELL_EXPLODE_CART, true); DoCast(me, SPELL_SUMMON_CART, true); if (GameObject* cart = me->FindNearestGameObject(188160, 3)) cart->SetUInt32Value(GAMEOBJECT_FACTION, 14); uiPhaseTimer = 3000; Phase = 2; break; case 2: if (GameObject* cart = me->FindNearestGameObject(188160, 3)) cart->UseDoorOrButton(); DoCast(me, SPELL_EXPLODE_CART, true); uiPhaseTimer = 3000; Phase = 3; break; case 3: DoCast(me, SPELL_EXPLODE_CART, true); uiPhaseTimer = 2000; Phase = 4; case 5: DoCast(me, SPELL_SUMMON_WORM, true); if (Unit* worm = me->FindNearestCreature(26250, 3)) { worm->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); worm->HandleEmoteCommand(EMOTE_ONESHOT_EMERGE); } uiPhaseTimer = 1000; Phase = 6; break; case 6: DoCast(me, SPELL_EXPLODE_CART, true); if (Unit* worm = me->FindNearestCreature(26250, 3)) { me->Kill(worm); worm->RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); } uiPhaseTimer = 2000; Phase = 7; break; case 7: DoCast(me, SPELL_EXPLODE_CART, true); if (Player* caster = Unit::GetPlayer(*me, casterGuid)) caster->KilledMonster(me->GetCreatureTemplate(), me->GetGUID()); uiPhaseTimer = 5000; Phase = 8; break; case 8: EnterEvadeMode(); break; } } else uiPhaseTimer -= diff; } }; CreatureAI* GetAI(Creature* creature) const { return new npc_sinkhole_kill_creditAI(creature); } }; /*###### ## npc_khunok_the_behemoth ######*/ class npc_khunok_the_behemoth : public CreatureScript { public: npc_khunok_the_behemoth() : CreatureScript("npc_khunok_the_behemoth") { } struct npc_khunok_the_behemothAI : public ScriptedAI { npc_khunok_the_behemothAI(Creature* creature) : ScriptedAI(creature) {} void MoveInLineOfSight(Unit* who) { ScriptedAI::MoveInLineOfSight(who); if (who->GetTypeId() != TYPEID_UNIT) return; if (who->GetEntry() == 25861 && me->IsWithinDistInMap(who, 10.0f)) { if (Unit* owner = who->GetOwner()) { if (owner->GetTypeId() == TYPEID_PLAYER) { owner->CastSpell(owner, 46231, true); CAST_CRE(who)->DespawnOrUnsummon(); } } } } }; CreatureAI* GetAI(Creature* creature) const { return new npc_khunok_the_behemothAI(creature); } }; /*###### ## npc_keristrasza ######*/ enum eKeristrasza { SPELL_TELEPORT_TO_SARAGOSA = 46772 }; #define GOSSIP_HELLO_KERI "I am prepared to face Saragosa!" class npc_keristrasza : public CreatureScript { public: npc_keristrasza() : CreatureScript("npc_keristrasza") { } bool OnGossipHello(Player* player, Creature* creature) { if (creature->isQuestGiver()) player->PrepareQuestMenu(creature->GetGUID()); if (player->GetQuestStatus(11957) == QUEST_STATUS_INCOMPLETE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HELLO_KERI, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); return true; } bool OnGossipSelect(Player* player, Creature* /*creature*/, uint32 /*sender*/, uint32 action) { player->PlayerTalkClass->ClearMenus(); if (action == GOSSIP_ACTION_INFO_DEF + 1) { player->CLOSE_GOSSIP_MENU(); player->CastSpell(player, SPELL_TELEPORT_TO_SARAGOSA, true); } return true; } }; /*###### ## npc_corastrasza ######*/ #define GOSSIP_ITEM_C_1 "I... I think so..." enum eCorastrasza { SPELL_SUMMON_WYRMREST_SKYTALON = 61240, SPELL_WYRMREST_SKYTALON_RIDE_PERIODIC = 61244, QUEST_ACES_HIGH_DAILY = 13414, QUEST_ACES_HIGH = 13413 }; class npc_corastrasza : public CreatureScript { public: npc_corastrasza() : CreatureScript("npc_corastrasza") { } bool OnGossipHello(Player* player, Creature* creature) { if (creature->isQuestGiver()) player->PrepareQuestMenu(creature->GetGUID()); if (player->GetQuestStatus(QUEST_ACES_HIGH) == QUEST_STATUS_INCOMPLETE || player->GetQuestStatus(QUEST_ACES_HIGH_DAILY) == QUEST_STATUS_INCOMPLETE) //It's the same dragon for both quests. player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_C_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); return true; } bool OnGossipSelect(Player* player, Creature* /*creature*/, uint32 /*sender*/, uint32 action) { player->PlayerTalkClass->ClearMenus(); if (action == GOSSIP_ACTION_INFO_DEF+1) { player->CLOSE_GOSSIP_MENU(); player->CastSpell(player, SPELL_SUMMON_WYRMREST_SKYTALON, true); player->CastSpell(player, SPELL_WYRMREST_SKYTALON_RIDE_PERIODIC, true); } return true; } }; /*###### ## npc_iruk ######*/ #define GOSSIP_ITEM_I "<Search corpse for Issliruk's Totem.>" enum eIruk { QUEST_SPIRITS_WATCH_OVER_US = 11961, SPELL_CREATURE_TOTEM_OF_ISSLIRUK = 46816, GOSSIP_TEXT_I = 12585 }; class npc_iruk : public CreatureScript { public: npc_iruk() : CreatureScript("npc_iruk") { } bool OnGossipHello(Player* player, Creature* creature) { if (player->GetQuestStatus(QUEST_SPIRITS_WATCH_OVER_US) == QUEST_STATUS_INCOMPLETE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_I, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); player->PlayerTalkClass->SendGossipMenu(GOSSIP_TEXT_I, creature->GetGUID()); return true; } bool OnGossipSelect(Player* player, Creature* /*creature*/, uint32 /*sender*/, uint32 action) { player->PlayerTalkClass->ClearMenus(); switch (action) { case GOSSIP_ACTION_INFO_DEF+1: player->CastSpell(player, SPELL_CREATURE_TOTEM_OF_ISSLIRUK, true); player->CLOSE_GOSSIP_MENU(); break; } return true; } }; /*###### ## mob_nerubar_victim ######*/ #define WARSONG_PEON 25270 const uint32 nerubarVictims[3] = { 45526, 45527, 45514 }; class mob_nerubar_victim : public CreatureScript { public: mob_nerubar_victim() : CreatureScript("mob_nerubar_victim") { } struct mob_nerubar_victimAI : public ScriptedAI { mob_nerubar_victimAI(Creature* creature) : ScriptedAI(creature) {} void Reset() {} void EnterCombat(Unit* /*who*/) {} void MoveInLineOfSight(Unit* /*who*/) {} void JustDied(Unit* killer) { Player* player = killer->ToPlayer(); if (!player) return; if (player->GetQuestStatus(11611) == QUEST_STATUS_INCOMPLETE) { uint8 uiRand = urand(0, 99); if (uiRand < 25) { player->CastSpell(me, 45532, true); player->KilledMonsterCredit(WARSONG_PEON, 0); } else if (uiRand < 75) player->CastSpell(me, nerubarVictims[urand(0, 2)], true); } } }; CreatureAI* GetAI(Creature* creature) const { return new mob_nerubar_victimAI(creature); } }; /*###### ## npc_scourge_prisoner ######*/ enum eScourgePrisoner { GO_SCOURGE_CAGE = 187867 }; class npc_scourge_prisoner : public CreatureScript { public: npc_scourge_prisoner() : CreatureScript("npc_scourge_prisoner") { } struct npc_scourge_prisonerAI : public ScriptedAI { npc_scourge_prisonerAI(Creature* creature) : ScriptedAI (creature){} void Reset() { me->SetReactState(REACT_PASSIVE); if (GameObject* go = me->FindNearestGameObject(GO_SCOURGE_CAGE, 5.0f)) if (go->GetGoState() == GO_STATE_ACTIVE) go->SetGoState(GO_STATE_READY); } }; CreatureAI* GetAI(Creature* creature) const { return new npc_scourge_prisonerAI(creature); } }; /*###### ## npc_jenny ######*/ enum eJenny { QUEST_LOADER_UP = 11881, NPC_FEZZIX_GEARTWIST = 25849, NPC_JENNY = 25969, SPELL_GIVE_JENNY_CREDIT = 46358, SPELL_CRATES_CARRIED = 46340, SPELL_DROP_CRATE = 46342 }; class npc_jenny : public CreatureScript { public: npc_jenny() : CreatureScript("npc_jenny") { } struct npc_jennyAI : public ScriptedAI { npc_jennyAI(Creature* creature) : ScriptedAI(creature) {} bool setCrateNumber; void Reset() { if (!setCrateNumber) setCrateNumber = true; me->SetReactState(REACT_PASSIVE); switch (CAST_PLR(me->GetOwner())->GetTeamId()) { case TEAM_ALLIANCE: me->setFaction(FACTION_ESCORT_A_NEUTRAL_ACTIVE); break; default: case TEAM_HORDE: me->setFaction(FACTION_ESCORT_H_NEUTRAL_ACTIVE); break; } } void DamageTaken(Unit* /*pDone_by*/, uint32& /*uiDamage*/) { DoCast(me, SPELL_DROP_CRATE, true); } void UpdateAI(const uint32 /*diff*/) { if (setCrateNumber) { me->AddAura(SPELL_CRATES_CARRIED, me); setCrateNumber = false; } if (!setCrateNumber && !me->HasAura(SPELL_CRATES_CARRIED)) me->DisappearAndDie(); if (!UpdateVictim()) return; } }; CreatureAI* GetAI(Creature* creature) const { return new npc_jennyAI (creature); } }; /*###### ## npc_fezzix_geartwist ######*/ class npc_fezzix_geartwist : public CreatureScript { public: npc_fezzix_geartwist() : CreatureScript("npc_fezzix_geartwist") { } struct npc_fezzix_geartwistAI : public ScriptedAI { npc_fezzix_geartwistAI(Creature* creature) : ScriptedAI(creature) {} void MoveInLineOfSight(Unit* who) { ScriptedAI::MoveInLineOfSight(who); if (who->GetTypeId() != TYPEID_UNIT) return; if (who->GetEntry() == NPC_JENNY && me->IsWithinDistInMap(who, 10.0f)) { if (Unit* owner = who->GetOwner()) { if (owner->GetTypeId() == TYPEID_PLAYER) { if (who->HasAura(SPELL_CRATES_CARRIED)) { owner->CastSpell(owner, SPELL_GIVE_JENNY_CREDIT, true); // Maybe is not working. CAST_PLR(owner)->CompleteQuest(QUEST_LOADER_UP); CAST_CRE(who)->DisappearAndDie(); } } } } } }; CreatureAI* GetAI(Creature* creature) const { return new npc_fezzix_geartwistAI(creature); } }; /*###### ## npc_nesingwary_trapper ######*/ enum eNesingwaryTrapper { GO_HIGH_QUALITY_FUR = 187983, GO_CARIBOU_TRAP_1 = 187982, GO_CARIBOU_TRAP_2 = 187995, GO_CARIBOU_TRAP_3 = 187996, GO_CARIBOU_TRAP_4 = 187997, GO_CARIBOU_TRAP_5 = 187998, GO_CARIBOU_TRAP_6 = 187999, GO_CARIBOU_TRAP_7 = 188000, GO_CARIBOU_TRAP_8 = 188001, GO_CARIBOU_TRAP_9 = 188002, GO_CARIBOU_TRAP_10 = 188003, GO_CARIBOU_TRAP_11 = 188004, GO_CARIBOU_TRAP_12 = 188005, GO_CARIBOU_TRAP_13 = 188006, GO_CARIBOU_TRAP_14 = 188007, GO_CARIBOU_TRAP_15 = 188008, SPELL_TRAPPED = 46104, }; #define CaribouTrapsNum 15 const uint32 CaribouTraps[CaribouTrapsNum] = { GO_CARIBOU_TRAP_1, GO_CARIBOU_TRAP_2, GO_CARIBOU_TRAP_3, GO_CARIBOU_TRAP_4, GO_CARIBOU_TRAP_5, GO_CARIBOU_TRAP_6, GO_CARIBOU_TRAP_7, GO_CARIBOU_TRAP_8, GO_CARIBOU_TRAP_9, GO_CARIBOU_TRAP_10, GO_CARIBOU_TRAP_11, GO_CARIBOU_TRAP_12, GO_CARIBOU_TRAP_13, GO_CARIBOU_TRAP_14, GO_CARIBOU_TRAP_15, }; class npc_nesingwary_trapper : public CreatureScript { public: npc_nesingwary_trapper() : CreatureScript("npc_nesingwary_trapper") { } struct npc_nesingwary_trapperAI : public ScriptedAI { npc_nesingwary_trapperAI(Creature* creature) : ScriptedAI(creature) { creature->SetVisible(false); } uint64 go_caribouGUID; uint8 Phase; uint32 uiPhaseTimer; void Reset() { me->SetVisible(false); uiPhaseTimer = 2500; Phase = 1; go_caribouGUID = 0; } void EnterCombat(Unit* /*who*/) {} void MoveInLineOfSight(Unit* /*who*/) {} void JustDied(Unit* /*killer*/) { if (GameObject* go_caribou = me->GetMap()->GetGameObject(go_caribouGUID)) go_caribou->SetLootState(GO_JUST_DEACTIVATED); if (TempSummon* summon = me->ToTempSummon()) if (summon->isSummon()) if (Unit* temp = summon->GetSummoner()) if (temp->GetTypeId() == TYPEID_PLAYER) CAST_PLR(temp)->KilledMonsterCredit(me->GetEntry(), 0); if (GameObject* go_caribou = me->GetMap()->GetGameObject(go_caribouGUID)) go_caribou->SetGoState(GO_STATE_READY); } void UpdateAI(const uint32 diff) { if (uiPhaseTimer <= diff) { switch (Phase) { case 1: me->SetVisible(true); uiPhaseTimer = 2000; Phase = 2; break; case 2: if (GameObject* go_fur = me->FindNearestGameObject(GO_HIGH_QUALITY_FUR, 11.0f)) me->GetMotionMaster()->MovePoint(0, go_fur->GetPositionX(), go_fur->GetPositionY(), go_fur->GetPositionZ()); uiPhaseTimer = 1500; Phase = 3; break; case 3: //DoScriptText(SAY_NESINGWARY_1, me); uiPhaseTimer = 2000; Phase = 4; break; case 4: me->HandleEmoteCommand(EMOTE_ONESHOT_LOOT); uiPhaseTimer = 1000; Phase = 5; break; case 5: me->HandleEmoteCommand(EMOTE_ONESHOT_NONE); uiPhaseTimer = 500; Phase = 6; break; case 6: if (GameObject* go_fur = me->FindNearestGameObject(GO_HIGH_QUALITY_FUR, 11.0f)) go_fur->Delete(); uiPhaseTimer = 500; Phase = 7; break; case 7: { GameObject* go_caribou = NULL; for (uint8 i = 0; i < CaribouTrapsNum; ++i) { go_caribou = me->FindNearestGameObject(CaribouTraps[i], 5.0f); if (go_caribou) { go_caribou->SetGoState(GO_STATE_ACTIVE); go_caribouGUID = go_caribou->GetGUID(); break; } } Phase = 8; uiPhaseTimer = 1000; } break; case 8: DoCast(me, SPELL_TRAPPED, true); Phase = 0; break; } } else uiPhaseTimer -= diff; } }; CreatureAI* GetAI(Creature* creature) const { return new npc_nesingwary_trapperAI(creature); } }; /*###### ## npc_lurgglbr ######*/ enum eLurgglbr { QUEST_ESCAPE_WINTERFIN_CAVERNS = 11570, GO_CAGE = 187369, FACTION_ESCORTEE_A = 774, FACTION_ESCORTEE_H = 775, }; /*#define SAY_WP_1_LUR_START -1571004 #define SAY_WP_1_LUR_END -1571005 #define SAY_WP_41_LUR_START -1571006 #define SAY_WP_41_LUR_END -1571007*/ class npc_lurgglbr : public CreatureScript { public: npc_lurgglbr() : CreatureScript("npc_lurgglbr") { } struct npc_lurgglbrAI : public npc_escortAI { npc_lurgglbrAI(Creature* creature) : npc_escortAI(creature){} uint32 IntroTimer; uint32 IntroPhase; void Reset() { if (!HasEscortState(STATE_ESCORT_ESCORTING)) { IntroTimer = 0; IntroPhase = 0; } } void WaypointReached(uint32 waypointId) { switch (waypointId) { case 0: IntroPhase = 1; IntroTimer = 2000; break; case 41: IntroPhase = 4; IntroTimer = 2000; break; } } void UpdateAI(const uint32 diff) { if (IntroPhase) { if (IntroTimer <= diff) { switch (IntroPhase) { case 1: //DoScriptText(SAY_WP_1_LUR_START, me); IntroPhase = 2; IntroTimer = 7500; break; case 2: //DoScriptText(SAY_WP_1_LUR_END, me); IntroPhase = 3; IntroTimer = 7500; break; case 3: me->SetReactState(REACT_AGGRESSIVE); IntroPhase = 0; IntroTimer = 0; break; case 4: //DoScriptText(SAY_WP_41_LUR_START, me); IntroPhase = 5; IntroTimer = 8000; break; case 5: //DoScriptText(SAY_WP_41_LUR_END, me); IntroPhase = 6; IntroTimer = 2500; break; case 6: if (Player* player = GetPlayerForEscort()) player->AreaExploredOrEventHappens(QUEST_ESCAPE_WINTERFIN_CAVERNS); IntroPhase = 7; IntroTimer = 2500; break; case 7: me->DespawnOrUnsummon(); IntroPhase = 0; IntroTimer = 0; break; } } else IntroTimer -= diff; } npc_escortAI::UpdateAI(diff); if (!UpdateVictim()) return; } }; CreatureAI* GetAI(Creature* creature) const { return new npc_lurgglbrAI(creature); } bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest) { if (quest->GetQuestId() == QUEST_ESCAPE_WINTERFIN_CAVERNS) { if (GameObject* go = creature->FindNearestGameObject(GO_CAGE, 5.0f)) { go->SetRespawnTime(0); go->SetGoType(GAMEOBJECT_TYPE_BUTTON); go->UseDoorOrButton(20); } if (npc_escortAI* pEscortAI = CAST_AI(npc_lurgglbr::npc_lurgglbrAI, creature->AI())) pEscortAI->Start(true, false, player->GetGUID()); switch (player->GetTeam()) { case ALLIANCE: creature->setFaction(FACTION_ESCORTEE_A); break; default: case HORDE: creature->setFaction(FACTION_ESCORTEE_H); break; } return true; } return false; } }; /*###### ## npc_nexus_drake_hatchling ######*/ enum eNexusDrakeHatchling { SPELL_DRAKE_HARPOON = 46607, SPELL_RED_DRAGONBLOOD = 46620, SPELL_DRAKE_HATCHLING_SUBDUED = 46691, SPELL_SUBDUED = 46675, NPC_RAELORASZ = 26117, QUEST_DRAKE_HUNT = 11919, QUEST_DRAKE_HUNT_D = 11940 }; class npc_nexus_drake_hatchling : public CreatureScript { public: npc_nexus_drake_hatchling() : CreatureScript("npc_nexus_drake_hatchling") { } struct npc_nexus_drake_hatchlingAI : public FollowerAI //The spell who makes the npc follow the player is missing, also we can use FollowerAI! { npc_nexus_drake_hatchlingAI(Creature* creature) : FollowerAI(creature) {} uint64 HarpoonerGUID; bool WithRedDragonBlood; void Reset() { WithRedDragonBlood = false; HarpoonerGUID = 0; } void EnterCombat(Unit* who) { if (me->IsValidAttackTarget(who)) AttackStart(who); } void SpellHit(Unit* caster, const SpellInfo* spell) { if (spell->Id == SPELL_DRAKE_HARPOON && caster->GetTypeId() == TYPEID_PLAYER) { HarpoonerGUID = caster->GetGUID(); DoCast(me, SPELL_RED_DRAGONBLOOD, true); } WithRedDragonBlood = true; } void MoveInLineOfSight(Unit* who) { FollowerAI::MoveInLineOfSight(who); if (!HarpoonerGUID) return; if (me->HasAura(SPELL_SUBDUED) && who->GetEntry() == NPC_RAELORASZ) { if (me->IsWithinDistInMap(who, INTERACTION_DISTANCE)) { if (Player* pHarpooner = Unit::GetPlayer(*me, HarpoonerGUID)) { pHarpooner->KilledMonsterCredit(26175, 0); pHarpooner->RemoveAura(SPELL_DRAKE_HATCHLING_SUBDUED); SetFollowComplete(); HarpoonerGUID = 0; me->DisappearAndDie(); } } } } void UpdateAI(const uint32 /*diff*/) { if (WithRedDragonBlood && HarpoonerGUID && !me->HasAura(SPELL_RED_DRAGONBLOOD)) { if (Player* pHarpooner = Unit::GetPlayer(*me, HarpoonerGUID)) { EnterEvadeMode(); StartFollow(pHarpooner, 35, NULL); DoCast(me, SPELL_SUBDUED, true); pHarpooner->CastSpell(pHarpooner, SPELL_DRAKE_HATCHLING_SUBDUED, true); me->AttackStop(); WithRedDragonBlood = false; } } if (!UpdateVictim()) return; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const { return new npc_nexus_drake_hatchlingAI(creature); } }; /*###### ## npc_thassarian ######*/ enum eThassarian { QUEST_LAST_RITES = 12019, SPELL_TRANSFORM_VALANAR = 46753, SPELL_STUN = 46957, SPELL_SHADOW_BOLT = 15537, NPC_IMAGE_LICH_KING = 26203, NPC_COUNSELOR_TALBOT = 25301, NPC_PRINCE_VALANAR = 28189, NPC_GENERAL_ARLOS = 25250, NPC_LERYSSA = 25251, SAY_TALBOT_1 = -1571004, SAY_LICH_1 = -1571005, SAY_TALBOT_2 = -1571006, SAY_THASSARIAN_1 = -1571007, SAY_THASSARIAN_2 = -1571008, SAY_LICH_2 = -1571009, SAY_THASSARIAN_3 = -1571010, SAY_TALBOT_3 = -1571011, SAY_LICH_3 = -1571012, SAY_TALBOT_4 = -1571013, SAY_ARLOS_1 = -1571014, SAY_ARLOS_2 = -1571015, SAY_LERYSSA_1 = -1571016, SAY_THASSARIAN_4 = -1571017, SAY_LERYSSA_2 = -1571018, SAY_THASSARIAN_5 = -1571019, SAY_LERYSSA_3 = -1571020, SAY_THASSARIAN_6 = -1571021, SAY_LERYSSA_4 = -1571022, SAY_THASSARIAN_7 = -1571023, }; #define GOSSIP_ITEM_T "Let's do this, Thassarian. It's now or never." class npc_thassarian : public CreatureScript { public: npc_thassarian() : CreatureScript("npc_thassarian") { } struct npc_thassarianAI : public npc_escortAI { npc_thassarianAI(Creature* creature) : npc_escortAI(creature) { } uint64 uiArthas; uint64 uiTalbot; uint64 uiLeryssa; uint64 uiArlos; bool bArthasInPosition; bool bArlosInPosition; bool bLeryssaInPosition; bool bTalbotInPosition; uint32 uiPhase; uint32 uiPhaseTimer; void Reset() { me->RestoreFaction(); me->RemoveStandFlags(UNIT_STAND_STATE_SIT); uiArthas = 0; uiTalbot = 0; uiLeryssa = 0; uiArlos = 0; bArthasInPosition = false; bArlosInPosition = false; bLeryssaInPosition = false; bTalbotInPosition = false; uiPhase = 0; uiPhaseTimer = 0; } void WaypointReached(uint32 waypointId) { Player* player = GetPlayerForEscort(); if (!player) return; switch (waypointId) { case 3: SetEscortPaused(true); if (Creature* pArthas = me->SummonCreature(NPC_IMAGE_LICH_KING, 3730.313f, 3518.689f, 473.324f, 1.562f, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 120000)) { uiArthas = pArthas->GetGUID(); pArthas->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); pArthas->SetReactState(REACT_PASSIVE); pArthas->SetWalk(true); pArthas->GetMotionMaster()->MovePoint(0, 3737.374756f, 3564.841309f, 477.433014f); } if (Creature* pTalbot = me->SummonCreature(NPC_COUNSELOR_TALBOT, 3747.23f, 3614.936f, 473.321f, 4.462012f, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 120000)) { uiTalbot = pTalbot->GetGUID(); pTalbot->SetWalk(true); pTalbot->GetMotionMaster()->MovePoint(0, 3738.000977f, 3568.882080f, 477.433014f); } me->SetWalk(false); break; case 4: SetEscortPaused(true); uiPhase = 7; break; } } void UpdateAI(const uint32 uiDiff) { npc_escortAI::UpdateAI(uiDiff); if (bArthasInPosition && bTalbotInPosition) { uiPhase = 1; bArthasInPosition = false; bTalbotInPosition = false; } if (bArlosInPosition && bLeryssaInPosition) { bArlosInPosition = false; bLeryssaInPosition = false; DoScriptText(SAY_THASSARIAN_1, me); SetEscortPaused(false); } if (uiPhaseTimer <= uiDiff) { Creature* pTalbot = me->GetCreature(*me, uiTalbot); Creature* pArthas = me->GetCreature(*me, uiArthas); switch (uiPhase) { case 1: if (pTalbot) pTalbot->SetStandState(UNIT_STAND_STATE_KNEEL); uiPhaseTimer = 3000; ++uiPhase; break; case 2: if (pTalbot) { pTalbot->UpdateEntry(NPC_PRINCE_VALANAR, ALLIANCE); pTalbot->setFaction(14); pTalbot->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); pTalbot->SetReactState(REACT_PASSIVE); } uiPhaseTimer = 5000; ++uiPhase; break; case 3: if (pTalbot) DoScriptText(SAY_TALBOT_1, pTalbot); uiPhaseTimer = 5000; ++uiPhase; break; case 4: if (pArthas) DoScriptText(SAY_LICH_1, pArthas); uiPhaseTimer = 5000; ++uiPhase; break; case 5: if (pTalbot) DoScriptText(SAY_TALBOT_2, pTalbot); uiPhaseTimer = 5000; ++uiPhase; break; case 6: if (Creature* pArlos = me->SummonCreature(NPC_GENERAL_ARLOS, 3745.527100f, 3615.655029f, 473.321533f, 4.447805f, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 120000)) { uiArlos = pArlos->GetGUID(); pArlos->SetWalk(true); pArlos->GetMotionMaster()->MovePoint(0, 3735.570068f, 3572.419922f, 477.441010f); } if (Creature* pLeryssa = me->SummonCreature(NPC_LERYSSA, 3749.654541f, 3614.959717f, 473.323486f, 4.524959f, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 120000)) { uiLeryssa = pLeryssa->GetGUID(); pLeryssa->SetWalk(false); pLeryssa->SetReactState(REACT_PASSIVE); pLeryssa->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); pLeryssa->GetMotionMaster()->MovePoint(0, 3741.969971f, 3571.439941f, 477.441010f); } uiPhaseTimer = 2000; uiPhase = 0; break; case 7: DoScriptText(SAY_THASSARIAN_2, me); uiPhaseTimer = 5000; ++uiPhase; break; case 8: if (pArthas && pTalbot) { pArthas->SetInFront(me); //The client doesen't update with the new orientation :l pTalbot->SetStandState(UNIT_STAND_STATE_STAND); DoScriptText(SAY_LICH_2, pArthas); } uiPhaseTimer = 5000; uiPhase = 9; break; case 9: DoScriptText(SAY_THASSARIAN_3, me); uiPhaseTimer = 5000; uiPhase = 10; break; case 10: if (pTalbot) DoScriptText(SAY_TALBOT_3, pTalbot); uiPhaseTimer = 5000; uiPhase = 11; break; case 11: if (pArthas) DoScriptText(SAY_LICH_3, pArthas); uiPhaseTimer = 5000; uiPhase = 12; break; case 12: if (pTalbot) DoScriptText(SAY_TALBOT_4, pTalbot); uiPhaseTimer = 2000; uiPhase = 13; break; case 13: if (pArthas) pArthas->RemoveFromWorld(); ++uiPhase; break; case 14: me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); if (pTalbot) { pTalbot->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); pTalbot->SetReactState(REACT_AGGRESSIVE); pTalbot->CastSpell(me, SPELL_SHADOW_BOLT, false); } uiPhaseTimer = 1500; ++uiPhase; break; case 15: me->SetReactState(REACT_AGGRESSIVE); AttackStart(pTalbot); uiPhase = 0; break; case 16: me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_QUESTGIVER); uiPhaseTimer = 20000; ++uiPhase; break; case 17: if (Creature* pLeryssa = me->GetCreature(*me, uiLeryssa)) pLeryssa->RemoveFromWorld(); if (Creature* pArlos= me->GetCreature(*me, uiArlos)) pArlos->RemoveFromWorld(); if (pTalbot) pTalbot->RemoveFromWorld(); me->RemoveStandFlags(UNIT_STAND_STATE_SIT); SetEscortPaused(false); uiPhaseTimer = 0; uiPhase = 0; } } else uiPhaseTimer -= uiDiff; if (!UpdateVictim()) return; DoMeleeAttackIfReady(); } void JustDied(Unit* /*killer*/) { if (Creature* pTalbot = me->GetCreature(*me, uiTalbot)) pTalbot->RemoveFromWorld(); if (Creature* pLeryssa = me->GetCreature(*me, uiLeryssa)) pLeryssa->RemoveFromWorld(); if (Creature* pArlos = me->GetCreature(*me, uiArlos)) pArlos->RemoveFromWorld(); if (Creature* pArthas = me->GetCreature(*me, uiArthas)) pArthas->RemoveFromWorld(); } }; bool OnGossipHello(Player* player, Creature* creature) { if (creature->isQuestGiver()) player->PrepareQuestMenu(creature->GetGUID()); if (player->GetQuestStatus(QUEST_LAST_RITES) == QUEST_STATUS_INCOMPLETE && creature->GetAreaId() == 4128) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_T, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); return true; } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) { player->PlayerTalkClass->ClearMenus(); switch (action) { case GOSSIP_ACTION_INFO_DEF+1: CAST_AI(npc_escortAI, (creature->AI()))->Start(true, false, player->GetGUID()); CAST_AI(npc_escortAI, (creature->AI()))->SetMaxPlayerDistance(200.0f); break; } return true; } CreatureAI* GetAI(Creature* creature) const { return new npc_thassarianAI(creature); } }; /*###### ## npc_image_lich_king ######*/ class npc_image_lich_king : public CreatureScript { public: npc_image_lich_king() : CreatureScript("npc_image_lich_king") { } struct npc_image_lich_kingAI : public ScriptedAI { npc_image_lich_kingAI(Creature* creature) : ScriptedAI(creature) {} void Reset() { me->RestoreFaction(); } void MovementInform(uint32 uiType, uint32 /*uiId*/) { if (uiType != POINT_MOTION_TYPE) return; if (me->isSummon()) if (Unit* summoner = me->ToTempSummon()->GetSummoner()) CAST_AI(npc_thassarian::npc_thassarianAI, CAST_CRE(summoner)->AI())->bArthasInPosition = true; } }; CreatureAI* GetAI(Creature* creature) const { return new npc_image_lich_kingAI(creature); } }; /*###### ## npc_general_arlos ######*/ class npc_general_arlos : public CreatureScript { public: npc_general_arlos() : CreatureScript("npc_general_arlos") { } struct npc_general_arlosAI : public ScriptedAI { npc_general_arlosAI(Creature* creature) : ScriptedAI(creature) {} void MovementInform(uint32 uiType, uint32 /*uiId*/) { if (uiType != POINT_MOTION_TYPE) return; me->AddUnitState(UNIT_STATE_STUNNED); me->CastSpell(me, SPELL_STUN, true); if (me->isSummon()) if (Unit* summoner = me->ToTempSummon()->GetSummoner()) CAST_AI(npc_thassarian::npc_thassarianAI, CAST_CRE(summoner)->AI())->bArlosInPosition = true; } }; CreatureAI* GetAI(Creature* creature) const { return new npc_general_arlosAI(creature); } }; /*###### ## npc_counselor_talbot ######*/ enum eCounselorTalbot { SPELL_DEFLECTION = 51009, SPELL_SOUL_BLAST = 50992, }; class npc_counselor_talbot : public CreatureScript { public: npc_counselor_talbot() : CreatureScript("npc_counselor_talbot") { } struct npc_counselor_talbotAI : public ScriptedAI { npc_counselor_talbotAI(Creature* creature) : ScriptedAI(creature) { creature->RestoreFaction(); } uint64 LeryssaGUID; uint64 ArlosGUID; bool bCheck; uint32 uiShadowBoltTimer; uint32 uiDeflectionTimer; uint32 uiSoulBlastTimer; void Reset() { LeryssaGUID = 0; ArlosGUID = 0; bCheck = false; uiShadowBoltTimer = urand(5000, 12000); uiDeflectionTimer = urand(20000, 25000); uiSoulBlastTimer = urand (12000, 18000); } void MovementInform(uint32 uiType, uint32 /*uiId*/) { if (uiType != POINT_MOTION_TYPE) return; if (me->isSummon()) if (Unit* summoner = me->ToTempSummon()->GetSummoner()) CAST_AI(npc_thassarian::npc_thassarianAI, CAST_CRE(summoner)->AI())->bTalbotInPosition = true; } void UpdateAI(const uint32 uiDiff) { if (bCheck) { if (Creature* pLeryssa = me->FindNearestCreature(NPC_LERYSSA, 50.0f, true)) LeryssaGUID = pLeryssa->GetGUID(); if (Creature* pArlos = me->FindNearestCreature(NPC_GENERAL_ARLOS, 50.0f, true)) ArlosGUID = pArlos->GetGUID(); bCheck = false; } if (!UpdateVictim()) return; if (me->GetAreaId() == 4125) { if (uiShadowBoltTimer <= uiDiff) { DoCast(me->getVictim(), SPELL_SHADOW_BOLT); uiShadowBoltTimer = urand(5000, 12000); } else uiShadowBoltTimer -= uiDiff; if (uiDeflectionTimer <= uiDiff) { DoCast(me->getVictim(), SPELL_DEFLECTION); uiDeflectionTimer = urand(20000, 25000); } else uiDeflectionTimer -= uiDiff; if (uiSoulBlastTimer <= uiDiff) { DoCast(me->getVictim(), SPELL_SOUL_BLAST); uiSoulBlastTimer = urand (12000, 18000); } else uiSoulBlastTimer -= uiDiff; } DoMeleeAttackIfReady(); } void JustDied(Unit* killer) { if (!LeryssaGUID || !ArlosGUID) return; Creature* pLeryssa = Unit::GetCreature(*me, LeryssaGUID); Creature* pArlos = Unit::GetCreature(*me, ArlosGUID); if (!pLeryssa || !pArlos) return; DoScriptText(SAY_ARLOS_1, pArlos); DoScriptText(SAY_ARLOS_2, pArlos); DoScriptText(SAY_LERYSSA_1, pLeryssa); pArlos->Kill(pArlos, false); pLeryssa->RemoveAura(SPELL_STUN); pLeryssa->ClearUnitState(UNIT_STATE_STUNNED); pLeryssa->SetWalk(false); pLeryssa->GetMotionMaster()->MovePoint(0, 3722.114502f, 3564.201660f, 477.441437f); if (Player* player = killer->ToPlayer()) player->RewardPlayerAndGroupAtEvent(NPC_PRINCE_VALANAR, 0); } }; CreatureAI* GetAI(Creature* creature) const { return new npc_counselor_talbotAI(creature); } }; /*###### ## npc_leryssa ######*/ class npc_leryssa : public CreatureScript { public: npc_leryssa() : CreatureScript("npc_leryssa") { } struct npc_leryssaAI : public ScriptedAI { npc_leryssaAI(Creature* creature) : ScriptedAI(creature) { bDone = false; Phase = 0; uiPhaseTimer = 0; creature->RemoveStandFlags(UNIT_STAND_STATE_SIT); } bool bDone; uint32 Phase; uint32 uiPhaseTimer; void MovementInform(uint32 uiType, uint32 /*uiId*/) { if (uiType != POINT_MOTION_TYPE) return; if (!bDone) { if (Creature* pTalbot = me->FindNearestCreature(NPC_PRINCE_VALANAR, 50.0f, true)) CAST_AI(npc_counselor_talbot::npc_counselor_talbotAI, pTalbot->GetAI())->bCheck = true; me->AddUnitState(UNIT_STATE_STUNNED); me->CastSpell(me, SPELL_STUN, true); if (me->isSummon()) if (Unit* summoner = me->ToTempSummon()->GetSummoner()) CAST_AI(npc_thassarian::npc_thassarianAI, summoner->GetAI())->bLeryssaInPosition = true; bDone = true; } else { me->SetStandState(UNIT_STAND_STATE_SIT); if (me->isSummon()) if (Unit* summoner = me->ToTempSummon()->GetSummoner()) summoner->SetStandState(UNIT_STAND_STATE_SIT); uiPhaseTimer = 1500; Phase = 1; } } void UpdateAI(const uint32 uiDiff) { ScriptedAI::UpdateAI(uiDiff); if (uiPhaseTimer <= uiDiff) { switch (Phase) { case 1: if (me->isSummon()) if (Unit* pThassarian = me->ToTempSummon()->GetSummoner()) DoScriptText(SAY_THASSARIAN_4, pThassarian); uiPhaseTimer = 5000; ++Phase; break; case 2: DoScriptText(SAY_LERYSSA_2, me); uiPhaseTimer = 5000; ++Phase; break; case 3: if (me->isSummon()) if (Unit* pThassarian = me->ToTempSummon()->GetSummoner()) DoScriptText(SAY_THASSARIAN_5, pThassarian); uiPhaseTimer = 5000; ++Phase; break; case 4: DoScriptText(SAY_LERYSSA_3, me); uiPhaseTimer = 5000; ++Phase; break; case 5: if (me->isSummon()) if (Unit* pThassarian = me->ToTempSummon()->GetSummoner()) DoScriptText(SAY_THASSARIAN_6, pThassarian); uiPhaseTimer = 5000; ++Phase; break; case 6: DoScriptText(SAY_LERYSSA_4, me); uiPhaseTimer = 5000; ++Phase; break; case 7: if (me->isSummon()) if (Unit* pThassarian = me->ToTempSummon()->GetSummoner()) { DoScriptText(SAY_THASSARIAN_7, pThassarian); CAST_AI(npc_thassarian::npc_thassarianAI, pThassarian->GetAI())->uiPhase = 16; } uiPhaseTimer = 5000; Phase = 0; break; } } else uiPhaseTimer -= uiDiff; if (!UpdateVictim()) return; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const { return new npc_leryssaAI(creature); } }; /*###### ## npc_beryl_sorcerer ######*/ enum eBerylSorcerer { NPC_CAPTURED_BERLY_SORCERER = 25474, NPC_LIBRARIAN_DONATHAN = 25262, SPELL_ARCANE_CHAINS = 45611, SPELL_COSMETIC_CHAINS = 54324, SPELL_COSMETIC_ENSLAVE_CHAINS_SELF = 45631 }; class npc_beryl_sorcerer : public CreatureScript { public: npc_beryl_sorcerer() : CreatureScript("npc_beryl_sorcerer") { } struct npc_beryl_sorcererAI : public FollowerAI { npc_beryl_sorcererAI(Creature* creature) : FollowerAI(creature) {} bool bEnslaved; void Reset() { me->SetReactState(REACT_AGGRESSIVE); bEnslaved = false; } void EnterCombat(Unit* who) { if (me->IsValidAttackTarget(who)) AttackStart(who); } void SpellHit(Unit* pCaster, const SpellInfo* pSpell) { if (pSpell->Id == SPELL_ARCANE_CHAINS && pCaster->GetTypeId() == TYPEID_PLAYER && !HealthAbovePct(50) && !bEnslaved) { EnterEvadeMode(); //We make sure that the npc is not attacking the player! me->SetReactState(REACT_PASSIVE); StartFollow(pCaster->ToPlayer(), 0, NULL); me->UpdateEntry(NPC_CAPTURED_BERLY_SORCERER, TEAM_NEUTRAL); DoCast(me, SPELL_COSMETIC_ENSLAVE_CHAINS_SELF, true); if (Player* player = pCaster->ToPlayer()) player->KilledMonsterCredit(NPC_CAPTURED_BERLY_SORCERER, 0); bEnslaved = true; } } void MoveInLineOfSight(Unit* who) { FollowerAI::MoveInLineOfSight(who); if (who->GetEntry() == NPC_LIBRARIAN_DONATHAN && me->IsWithinDistInMap(who, INTERACTION_DISTANCE)) { SetFollowComplete(); me->DisappearAndDie(); } } void UpdateAI(const uint32 /*uiDiff*/) { if (!UpdateVictim()) return; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const { return new npc_beryl_sorcererAI(creature); } }; /*###### ## npc_imprisoned_beryl_sorcerer ######*/ enum eImprisionedBerylSorcerer { SPELL_NEURAL_NEEDLE = 45634, NPC_IMPRISONED_BERYL_SORCERER = 25478, SAY_IMPRISIONED_BERYL_1 = -1571024, SAY_IMPRISIONED_BERYL_2 = -1571025, SAY_IMPRISIONED_BERYL_3 = -1571026, SAY_IMPRISIONED_BERYL_4 = -1571027, SAY_IMPRISIONED_BERYL_5 = -1571028, SAY_IMPRISIONED_BERYL_6 = -1571029, SAY_IMPRISIONED_BERYL_7 = -1571030, }; class npc_imprisoned_beryl_sorcerer : public CreatureScript { public: npc_imprisoned_beryl_sorcerer() : CreatureScript("npc_imprisoned_beryl_sorcerer") { } struct npc_imprisoned_beryl_sorcererAI : public ScriptedAI { npc_imprisoned_beryl_sorcererAI(Creature* creature) : ScriptedAI(creature) {} uint64 CasterGUID; uint32 uiStep; uint32 uiPhase; void Reset() { uiStep = 1; uiPhase = 0; CasterGUID = 0; } void EnterCombat(Unit* /*who*/) { } void SpellHit(Unit* unit, const SpellInfo* pSpell) { if (pSpell->Id == SPELL_NEURAL_NEEDLE && unit->GetTypeId() == TYPEID_PLAYER) { ++uiPhase; CasterGUID = unit->GetGUID(); } } void UpdateAI(const uint32 uiDiff) { ScriptedAI::UpdateAI(uiDiff); if (!me->HasAura(SPELL_COSMETIC_ENSLAVE_CHAINS_SELF)) DoCast(me, SPELL_COSMETIC_ENSLAVE_CHAINS_SELF); if (me->GetReactState() != REACT_PASSIVE) me->SetReactState(REACT_PASSIVE); switch (uiPhase) { case 1: if (uiStep == 1) { DoScriptText(SAY_IMPRISIONED_BERYL_1, me); uiStep = 2; } break; case 2: if (uiStep == 2) { DoScriptText(SAY_IMPRISIONED_BERYL_2, me); uiStep = 3; } break; case 3: if (uiStep == 3) { DoScriptText(SAY_IMPRISIONED_BERYL_3, me); uiStep = 4; } break; case 4: if (uiStep == 4) { DoScriptText(SAY_IMPRISIONED_BERYL_4, me); uiStep = 5; } break; case 5: if (uiStep == 5) { if (Player* pCaster = Unit::GetPlayer(*me, CasterGUID)) { DoScriptText(SAY_IMPRISIONED_BERYL_5, me); pCaster->KilledMonsterCredit(25478, 0); uiStep = 6; } } break; case 6: if (uiStep == 6) { DoScriptText(SAY_IMPRISIONED_BERYL_6, me); uiStep = 7; } break; case 7: if (uiStep == 7) { DoScriptText(SAY_IMPRISIONED_BERYL_7, me); uiStep = 1; uiPhase = 0; } break; } } }; CreatureAI* GetAI(Creature* creature) const { return new npc_imprisoned_beryl_sorcererAI(creature); } }; /*###### ## npc_mootoo_the_younger ######*/ enum Script_Texts_Mootoo_the_Younger { SAY_1 =-1750040, SAY_2 =-1750041, SAY_3 =-1750042, SAY_4 =-1750043, SAY_5 =-1750044 }; enum Mootoo_the_Younger_Entries { NPC_MOOTOO_THE_YOUNGER =25504, QUEST_ESCAPING_THE_MIST =11664 }; class npc_mootoo_the_younger : public CreatureScript { public: npc_mootoo_the_younger() : CreatureScript("npc_mootoo_the_younger") { } bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest) { if (quest->GetQuestId() == QUEST_ESCAPING_THE_MIST) { switch (player->GetTeam()) { case ALLIANCE: creature->setFaction(FACTION_ESCORTEE_A); break; case HORDE: creature->setFaction(FACTION_ESCORTEE_H); break; } creature->SetStandState(UNIT_STAND_STATE_STAND); DoScriptText(SAY_1, creature); CAST_AI(npc_escortAI, (creature->AI()))->Start(true, false, player->GetGUID()); } return true; } struct npc_mootoo_the_youngerAI : public npc_escortAI { npc_mootoo_the_youngerAI(Creature* creature) : npc_escortAI(creature) {} void Reset() { SetDespawnAtFar(false); } void JustDied(Unit* /*killer*/) { if (Player* player=GetPlayerForEscort()) player->FailQuest(QUEST_ESCAPING_THE_MIST); } void WaypointReached(uint32 waypointId) { Player* player = GetPlayerForEscort(); if (!player) return; switch (waypointId) { case 10: me->HandleEmoteCommand(EMOTE_ONESHOT_EXCLAMATION); DoScriptText(SAY_2, me); break; case 12: DoScriptText(SAY_3, me); me->HandleEmoteCommand(EMOTE_ONESHOT_LOOT); break; case 16: DoScriptText(SAY_4, me); me->HandleEmoteCommand(EMOTE_ONESHOT_EXCLAMATION); break; case 20: me->SetPhaseMask(1, true); DoScriptText(SAY_5, me); me->HandleEmoteCommand(EMOTE_ONESHOT_EXCLAMATION); player->GroupEventHappens(QUEST_ESCAPING_THE_MIST, me); SetRun(true); break; } } }; CreatureAI* GetAI(Creature* creature) const { return new npc_mootoo_the_youngerAI(creature); } }; /*###### ## npc_bonker_togglevolt ######*/ enum Bonker_Togglevolt_Entries { NPC_BONKER_TOGGLEVOLT = 25589, QUEST_GET_ME_OUTA_HERE = 11673 }; enum Script_Texts_Bonker_Togglevolt { SAY_bonker_1 = -1700002, SAY_bonker_2 = -1700003 }; class npc_bonker_togglevolt : public CreatureScript { public: npc_bonker_togglevolt() : CreatureScript("npc_bonker_togglevolt") { } bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest) { if (quest->GetQuestId() == QUEST_GET_ME_OUTA_HERE) { creature->SetStandState(UNIT_STAND_STATE_STAND); DoScriptText(SAY_bonker_2, creature, player); CAST_AI(npc_escortAI, (creature->AI()))->Start(true, true, player->GetGUID()); } return true; } struct npc_bonker_togglevoltAI : public npc_escortAI { npc_bonker_togglevoltAI(Creature* creature) : npc_escortAI(creature) {} uint32 Bonker_agro; void Reset() { Bonker_agro=0; SetDespawnAtFar(false); } void JustDied(Unit* /*killer*/) { if (Player* player = GetPlayerForEscort()) player->FailQuest(QUEST_GET_ME_OUTA_HERE); } void UpdateEscortAI(const uint32 /*diff*/) { if (GetAttack() && UpdateVictim()) { if (Bonker_agro == 0) { DoScriptText(SAY_bonker_1, me); Bonker_agro++; } DoMeleeAttackIfReady(); } else Bonker_agro=0; } void WaypointReached(uint32 waypointId) { Player* player = GetPlayerForEscort(); if (!player) return; switch (waypointId) { case 29: player->GroupEventHappens(QUEST_GET_ME_OUTA_HERE, me); break; } } }; CreatureAI* GetAI(Creature* creature) const { return new npc_bonker_togglevoltAI(creature); } }; /*###### ## Help Those That Cannot Help Themselves, Quest 11876 ######*/ enum eHelpThemselves { QUEST_CANNOT_HELP_THEMSELVES = 11876, GO_MAMMOTH_TRAP_1 = 188022, GO_MAMMOTH_TRAP_2 = 188024, GO_MAMMOTH_TRAP_3 = 188025, GO_MAMMOTH_TRAP_4 = 188026, GO_MAMMOTH_TRAP_5 = 188027, GO_MAMMOTH_TRAP_6 = 188028, GO_MAMMOTH_TRAP_7 = 188029, GO_MAMMOTH_TRAP_8 = 188030, GO_MAMMOTH_TRAP_9 = 188031, GO_MAMMOTH_TRAP_10 = 188032, GO_MAMMOTH_TRAP_11 = 188033, GO_MAMMOTH_TRAP_12 = 188034, GO_MAMMOTH_TRAP_13 = 188035, GO_MAMMOTH_TRAP_14 = 188036, GO_MAMMOTH_TRAP_15 = 188037, GO_MAMMOTH_TRAP_16 = 188038, GO_MAMMOTH_TRAP_17 = 188039, GO_MAMMOTH_TRAP_18 = 188040, GO_MAMMOTH_TRAP_19 = 188041, GO_MAMMOTH_TRAP_20 = 188042, GO_MAMMOTH_TRAP_21 = 188043, GO_MAMMOTH_TRAP_22 = 188044, }; #define MammothTrapsNum 22 const uint32 MammothTraps[MammothTrapsNum] = { GO_MAMMOTH_TRAP_1, GO_MAMMOTH_TRAP_2, GO_MAMMOTH_TRAP_3, GO_MAMMOTH_TRAP_4, GO_MAMMOTH_TRAP_5, GO_MAMMOTH_TRAP_6, GO_MAMMOTH_TRAP_7, GO_MAMMOTH_TRAP_8, GO_MAMMOTH_TRAP_9, GO_MAMMOTH_TRAP_10, GO_MAMMOTH_TRAP_11, GO_MAMMOTH_TRAP_12, GO_MAMMOTH_TRAP_13, GO_MAMMOTH_TRAP_14, GO_MAMMOTH_TRAP_15, GO_MAMMOTH_TRAP_16, GO_MAMMOTH_TRAP_17, GO_MAMMOTH_TRAP_18, GO_MAMMOTH_TRAP_19, GO_MAMMOTH_TRAP_20, GO_MAMMOTH_TRAP_21, GO_MAMMOTH_TRAP_22 }; class npc_trapped_mammoth_calf : public CreatureScript { public: npc_trapped_mammoth_calf() : CreatureScript("npc_trapped_mammoth_calf") { } struct npc_trapped_mammoth_calfAI : public ScriptedAI { npc_trapped_mammoth_calfAI(Creature* creature) : ScriptedAI(creature) {} uint32 uiTimer; bool bStarted; void Reset() { uiTimer = 1500; bStarted = false; GameObject* pTrap = NULL; for (uint8 i = 0; i < MammothTrapsNum; ++i) { pTrap = me->FindNearestGameObject(MammothTraps[i], 11.0f); if (pTrap) { pTrap->SetGoState(GO_STATE_ACTIVE); return; } } } void UpdateAI(const uint32 diff) { if (bStarted) { if (uiTimer <= diff) { Position pos; me->GetRandomNearPosition(pos, 10.0f); me->GetMotionMaster()->MovePoint(0, pos); bStarted = false; } else uiTimer -= diff; } } void DoAction(const int32 param) { if (param == 1) bStarted = true; } void MovementInform(uint32 uiType, uint32 /*uiId*/) { if (uiType != POINT_MOTION_TYPE) return; me->DisappearAndDie(); GameObject* pTrap = NULL; for (uint8 i = 0; i < MammothTrapsNum; ++i) { pTrap = me->FindNearestGameObject(MammothTraps[i], 11.0f); if (pTrap) { pTrap->SetLootState(GO_JUST_DEACTIVATED); return; } } } }; CreatureAI* GetAI(Creature* creature) const { return new npc_trapped_mammoth_calfAI(creature); } }; /*###### ## Quest 11653: Hah... You're Not So Big Now! ######*/ enum eNotSoBig { QUEST_YOU_RE_NOT_SO_BIG_NOW = 11653, SPELL_AURA_NOTSOBIG_1 = 45672, SPELL_AURA_NOTSOBIG_2 = 45673, SPELL_AURA_NOTSOBIG_3 = 45677, SPELL_AURA_NOTSOBIG_4 = 45681 }; class npc_magmoth_crusher : public CreatureScript { public: npc_magmoth_crusher() : CreatureScript("npc_magmoth_crusher") { } struct npc_magmoth_crusherAI : public ScriptedAI { npc_magmoth_crusherAI(Creature* creature) : ScriptedAI(creature) {} void JustDied(Unit* killer) { Player* player = killer->ToPlayer(); if (!player) return; if (player->GetQuestStatus(QUEST_YOU_RE_NOT_SO_BIG_NOW) == QUEST_STATUS_INCOMPLETE && (me->HasAura(SPELL_AURA_NOTSOBIG_1) || me->HasAura(SPELL_AURA_NOTSOBIG_2) || me->HasAura(SPELL_AURA_NOTSOBIG_3) || me->HasAura(SPELL_AURA_NOTSOBIG_4))) { Quest const* qInfo = sObjectMgr->GetQuestTemplate(QUEST_YOU_RE_NOT_SO_BIG_NOW); if (qInfo) player->KilledMonsterCredit(qInfo->RequiredNpcOrGo[0], 0); } } }; CreatureAI* GetAI(Creature* creature) const { return new npc_magmoth_crusherAI(creature); } }; /*###### ## Quest 11608: Bury Those Cockroaches! ######*/ #define QUEST_BURY_THOSE_COCKROACHES 11608 #define SPELL_SEAFORIUM_DEPTH_CHARGE_EXPLOSION 45502 class npc_seaforium_depth_charge : public CreatureScript { public: npc_seaforium_depth_charge() : CreatureScript("npc_seaforium_depth_charge") { } struct npc_seaforium_depth_chargeAI : public ScriptedAI { npc_seaforium_depth_chargeAI(Creature* creature) : ScriptedAI(creature) { } uint32 uiExplosionTimer; void Reset() { uiExplosionTimer = urand(5000, 10000); } void UpdateAI(const uint32 diff) { if (uiExplosionTimer < diff) { DoCast(SPELL_SEAFORIUM_DEPTH_CHARGE_EXPLOSION); for (uint8 i = 0; i < 4; ++i) { if (Creature* cCredit = me->FindNearestCreature(25402 + i, 10.0f))//25402-25405 credit markers { if (Unit* uOwner = me->GetOwner()) { Player* owner = uOwner->ToPlayer(); if (owner && owner->GetQuestStatus(QUEST_BURY_THOSE_COCKROACHES) == QUEST_STATUS_INCOMPLETE) owner->KilledMonsterCredit(cCredit->GetEntry(), cCredit->GetGUID()); } } } me->Kill(me); return; } else uiExplosionTimer -= diff; } }; CreatureAI* GetAI(Creature* creature) const { return new npc_seaforium_depth_chargeAI(creature); } }; /*###### ## Help Those That Cannot Help Themselves, Quest 11876 ######*/ enum eValiancekeepcannons { GO_VALIANCE_KEEP_CANNON_1 = 187560, GO_VALIANCE_KEEP_CANNON_2 = 188692 }; class npc_valiance_keep_cannoneer : public CreatureScript { public: npc_valiance_keep_cannoneer() : CreatureScript("npc_valiance_keep_cannoneer") { } struct npc_valiance_keep_cannoneerAI : public ScriptedAI { npc_valiance_keep_cannoneerAI(Creature* creature) : ScriptedAI(creature) {} uint32 uiTimer; void Reset() { uiTimer = urand(13000, 18000); } void UpdateAI(const uint32 diff) { if (uiTimer <= diff) { me->HandleEmoteCommand(EMOTE_ONESHOT_KNEEL); GameObject* pCannon = me->FindNearestGameObject(GO_VALIANCE_KEEP_CANNON_1, 10); if (!pCannon) pCannon = me->FindNearestGameObject(GO_VALIANCE_KEEP_CANNON_2, 10); if (pCannon) pCannon->Use(me); uiTimer = urand(13000, 18000); } else uiTimer -= diff; if (!UpdateVictim()) return; } }; CreatureAI* GetAI(Creature* creature) const { return new npc_valiance_keep_cannoneerAI(creature); } }; /******************************************************* * npc_warmage_coldarra *******************************************************/ enum Spells { SPELL_TRANSITUS_SHIELD_BEAM = 48310 }; enum NPCs { NPC_TRANSITUS_SHIELD_DUMMY = 27306, NPC_WARMAGE_HOLLISTER = 27906, NPC_WARMAGE_CALANDRA = 27173, NPC_WARMAGE_WATKINS = 27904 }; class npc_warmage_coldarra : public CreatureScript { public: npc_warmage_coldarra() : CreatureScript("npc_warmage_coldarra") { } struct npc_warmage_coldarraAI : public Scripted_NoMovementAI { npc_warmage_coldarraAI(Creature* creature) : Scripted_NoMovementAI(creature){} uint32 m_uiTimer; //Timer until recast void Reset() { m_uiTimer = 0; } void EnterCombat(Unit* /*who*/) {} void AttackStart(Unit* /*who*/) {} void UpdateAI(const uint32 uiDiff) { if (m_uiTimer <= uiDiff) { std::list<Creature*> orbList; GetCreatureListWithEntryInGrid(orbList, me, NPC_TRANSITUS_SHIELD_DUMMY, 32.0f); switch (me->GetEntry()) { case NPC_WARMAGE_HOLLISTER: { if (!orbList.empty()) { for (std::list<Creature*>::const_iterator itr = orbList.begin(); itr != orbList.end(); ++itr) { if (Creature* pOrb = *itr) if (pOrb->GetPositionY() > 6680) DoCast(pOrb, SPELL_TRANSITUS_SHIELD_BEAM); } } m_uiTimer = urand(90000, 120000); } break; case NPC_WARMAGE_CALANDRA: { if (!orbList.empty()) { for (std::list<Creature*>::const_iterator itr = orbList.begin(); itr != orbList.end(); ++itr) { if (Creature* pOrb = *itr) if ((pOrb->GetPositionY() < 6680) && (pOrb->GetPositionY() > 6630)) DoCast(pOrb, SPELL_TRANSITUS_SHIELD_BEAM); } } m_uiTimer = urand(90000, 120000); } break; case NPC_WARMAGE_WATKINS: { if (!orbList.empty()) { for (std::list<Creature*>::const_iterator itr = orbList.begin(); itr != orbList.end(); ++itr) { if (Creature* pOrb = *itr) if (pOrb->GetPositionY() < 6630) DoCast(pOrb, SPELL_TRANSITUS_SHIELD_BEAM); } } m_uiTimer = urand(90000, 120000); } break; } } else m_uiTimer -= uiDiff; ScriptedAI::UpdateAI(uiDiff); if (!UpdateVictim()) return; } }; CreatureAI* GetAI(Creature* creature) const { return new npc_warmage_coldarraAI(creature); } }; /*###### ## npc_hidden_cultist ######*/ enum eHiddenCultist { SPELL_SHROUD_OF_THE_DEATH_CULTIST = 46077, //not working SPELL_RIGHTEOUS_VISION = 46078, //player aura QUEST_THE_HUNT_IS_ON = 11794, GOSSIP_TEXT_SALTY_JOHN_THORPE = 12529, GOSSIP_TEXT_GUARD_MITCHELSS = 12530, GOSSIP_TEXT_TOM_HEGGER = 12528, NPC_TOM_HEGGER = 25827, NPC_SALTY_JOHN_THORPE = 25248, NPC_GUARD_MITCHELLS = 25828, SAY_HIDDEN_CULTIST_1 = -1571044, SAY_HIDDEN_CULTIST_2 = -1571045, SAY_HIDDEN_CULTIST_3 = -1571046, SAY_HIDDEN_CULTIST_4 = -1571047 }; const char* GOSSIP_ITEM_TOM_HEGGER = "What do you know about the Cult of the Damned?"; const char* GOSSIP_ITEM_GUARD_MITCHELLS = "How long have you worked for the Cult of the Damned?"; const char* GOSSIP_ITEM_SALTY_JOHN_THORPE = "I have a reason to believe you're involved in the cultist activity"; class npc_hidden_cultist : public CreatureScript { public: npc_hidden_cultist() : CreatureScript("npc_hidden_cultist") { } struct npc_hidden_cultistAI : public ScriptedAI { npc_hidden_cultistAI(Creature* creature) : ScriptedAI(creature) { uiEmoteState = creature->GetUInt32Value(UNIT_NPC_EMOTESTATE); uiNpcFlags = creature->GetUInt32Value(UNIT_NPC_FLAGS); } uint32 uiEmoteState; uint32 uiNpcFlags; uint32 uiEventTimer; uint8 uiEventPhase; uint64 uiPlayerGUID; void Reset() { if (uiEmoteState) me->SetUInt32Value(UNIT_NPC_EMOTESTATE, uiEmoteState); if (uiNpcFlags) me->SetUInt32Value(UNIT_NPC_FLAGS, uiNpcFlags); uiEventTimer = 0; uiEventPhase = 0; uiPlayerGUID = 0; DoCast(SPELL_SHROUD_OF_THE_DEATH_CULTIST); me->RestoreFaction(); } void DoAction(const int32 /*iParam*/) { me->StopMoving(); me->SetUInt32Value(UNIT_NPC_FLAGS, 0); if (Player* player = me->GetPlayer(*me, uiPlayerGUID)) { me->SetInFront(player); me->SendMovementFlagUpdate(); } uiEventTimer = 3000; uiEventPhase = 1; } void SetGUID(uint64 uiGuid, int32 /*iId*/) { uiPlayerGUID = uiGuid; } void AttackPlayer() { me->setFaction(14); if (Player* player = me->GetPlayer(*me, uiPlayerGUID)) me->AI()->AttackStart(player); } void UpdateAI(const uint32 uiDiff) { if (uiEventTimer && uiEventTimer <= uiDiff) { switch (uiEventPhase) { case 1: switch (me->GetEntry()) { case NPC_SALTY_JOHN_THORPE: me->SetUInt32Value(UNIT_NPC_EMOTESTATE, 0); DoScriptText(SAY_HIDDEN_CULTIST_1, me); uiEventTimer = 5000; uiEventPhase = 2; break; case NPC_GUARD_MITCHELLS: DoScriptText(SAY_HIDDEN_CULTIST_2, me); uiEventTimer = 5000; uiEventPhase = 2; break; case NPC_TOM_HEGGER: DoScriptText(SAY_HIDDEN_CULTIST_3, me); uiEventTimer = 5000; uiEventPhase = 2; break; } break; case 2: switch (me->GetEntry()) { case NPC_SALTY_JOHN_THORPE: DoScriptText(SAY_HIDDEN_CULTIST_4, me); if (Player* player = me->GetPlayer(*me, uiPlayerGUID)) { me->SetInFront(player); me->SendMovementFlagUpdate(); } uiEventTimer = 3000; uiEventPhase = 3; break; case NPC_GUARD_MITCHELLS: case NPC_TOM_HEGGER: AttackPlayer(); uiEventPhase = 0; break; } break; case 3: if (me->GetEntry() == NPC_SALTY_JOHN_THORPE) { AttackPlayer(); uiEventPhase = 0; } break; } }else uiEventTimer -= uiDiff; if (!UpdateVictim()) return; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const { return new npc_hidden_cultistAI(creature); } bool OnGossipHello(Player* player, Creature* creature) { uint32 uiGossipText = 0; const char* charGossipItem; switch (creature->GetEntry()) { case NPC_TOM_HEGGER: uiGossipText = GOSSIP_TEXT_TOM_HEGGER; charGossipItem = GOSSIP_ITEM_TOM_HEGGER; break; case NPC_SALTY_JOHN_THORPE: uiGossipText = GOSSIP_TEXT_SALTY_JOHN_THORPE; charGossipItem = GOSSIP_ITEM_SALTY_JOHN_THORPE; break; case NPC_GUARD_MITCHELLS: uiGossipText = GOSSIP_TEXT_GUARD_MITCHELSS; charGossipItem = GOSSIP_ITEM_GUARD_MITCHELLS; break; default: charGossipItem = ""; return false; } if (player->HasAura(SPELL_RIGHTEOUS_VISION) && player->GetQuestStatus(QUEST_THE_HUNT_IS_ON) == QUEST_STATUS_INCOMPLETE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, charGossipItem, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); if (creature->isVendor()) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_VENDOR, GOSSIP_TEXT_BROWSE_GOODS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_TRADE); player->SEND_GOSSIP_MENU(uiGossipText, creature->GetGUID()); return true; } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) { player->PlayerTalkClass->ClearMenus(); if (action == GOSSIP_ACTION_INFO_DEF+1) { player->CLOSE_GOSSIP_MENU(); creature->AI()->SetGUID(player->GetGUID()); creature->AI()->DoAction(1); } if (action == GOSSIP_ACTION_TRADE) player->GetSession()->SendListInventory(creature->GetGUID()); return true; } }; void AddSC_borean_tundra() { new npc_sinkhole_kill_credit(); new npc_khunok_the_behemoth(); new npc_keristrasza(); new npc_corastrasza(); new npc_iruk(); new mob_nerubar_victim(); new npc_scourge_prisoner(); new npc_jenny(); new npc_fezzix_geartwist(); new npc_nesingwary_trapper(); new npc_lurgglbr(); new npc_nexus_drake_hatchling(); new npc_thassarian(); new npc_image_lich_king(); new npc_counselor_talbot(); new npc_leryssa(); new npc_general_arlos(); new npc_beryl_sorcerer(); new npc_imprisoned_beryl_sorcerer(); new npc_mootoo_the_younger(); new npc_bonker_togglevolt(); new npc_trapped_mammoth_calf(); new npc_magmoth_crusher(); new npc_seaforium_depth_charge(); new npc_valiance_keep_cannoneer(); new npc_warmage_coldarra(); new npc_hidden_cultist(); }
31.220809
195
0.497248
499453466
9b2a6680a07c2b73eb0f077ba3bf4e8587e0488b
641
cpp
C++
CS Academy/Round #62/find-binary-array.cpp
itsmevanessi/Competitive-Programming
e14208c0e0943d0dec90757368f5158bb9c4bc17
[ "MIT" ]
null
null
null
CS Academy/Round #62/find-binary-array.cpp
itsmevanessi/Competitive-Programming
e14208c0e0943d0dec90757368f5158bb9c4bc17
[ "MIT" ]
null
null
null
CS Academy/Round #62/find-binary-array.cpp
itsmevanessi/Competitive-Programming
e14208c0e0943d0dec90757368f5158bb9c4bc17
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; pair<int, int> arr[200001]; int final [200001]; int main(void) { memset(final, 1, sizeof final); int n; cin >> n; for(int i = 0; i < n; ++i){ cin >> arr[i].first; } for(int i = 0; i < n; ++i){ cin >> arr[i].second; } for(int i = 1; i < n; ++i){ if(arr[i].first != arr[i - 1].first) final[i - 1] = 0; } for(int i = 0; i < n - 1; ++i){ if(arr[i].second != arr[i + 1].second) final[i + 1] = 0; } for(int i = 0; i < n; ++i){ if(final[i])cout << "1"; else cout << "0"; } }
20.677419
46
0.422777
itsmevanessi
9b2a9b3283325d59eae7dfb12d77da47c6b8a3e5
1,578
cpp
C++
Views/FooterComponent.cpp
InTheMerde/photon-room-node
f82fa20f06d75686c69316e01e408e3a0e47c828
[ "MIT" ]
3
2015-12-23T16:02:36.000Z
2016-02-10T09:21:58.000Z
Views/FooterComponent.cpp
imarmorat/photon-room-node
f82fa20f06d75686c69316e01e408e3a0e47c828
[ "MIT" ]
null
null
null
Views/FooterComponent.cpp
imarmorat/photon-room-node
f82fa20f06d75686c69316e01e408e3a0e47c828
[ "MIT" ]
null
null
null
#include "Adafruit_ILI9341\Adafruit_ILI9341.h" #include "../general.h" #include "FooterComponent.h" #include "application.h" // http://www.barth-dev.de/online/rgb565-color-picker/ #define VIEW_NORMAL_COLOR 0xEF5D #define VIEW_CURRENT_COLOR 0x041F FooterComponent::FooterComponent() { } void FooterComponent::display() { _display->fillRect(x, y, width, height, ILI9341_BLACK); drawViewBar(); } Action FooterComponent::handleEvent(Action action) { //if (action != Action_SwitchToNextView) // return Action_None; drawViewBar(); return Action_None; } void FooterComponent::drawViewBar() { // TODO: these calculations should be done in constructor int horizontalPadding = 10; int verticalPadding = 2; int indicatorSize = 10; // this->height - (verticalPadding * 2); int containerWidth = parentContainer->viewCount * indicatorSize + horizontalPadding * (parentContainer->viewCount - 1); int startX = x + (width - containerWidth) / 2; int startY = y + height / 2; for (int i = 0; i < parentContainer->viewCount; i++) { bool isCurrentView = (i == parentContainer->currentViewIdx); int ih = indicatorSize * (isCurrentView ? 1 : 0.5) / 2; int ix = startX + indicatorSize / 2 + i * (indicatorSize + horizontalPadding); if (!isCurrentView) // because the indicator for non current view is smaller, we clear the area _display->fillRect(ix - indicatorSize/2, startY - indicatorSize/2, indicatorSize, indicatorSize, ILI9341_BLACK); _display->fillRect(ix - ih, startY - ih, ih * 2, ih * 2, isCurrentView ? VIEW_CURRENT_COLOR : VIEW_NORMAL_COLOR); } }
29.222222
120
0.727503
InTheMerde
9b2f7bdcf1b990df294395a55edfbba1a97514da
774
cpp
C++
C++/Object-Oriented Programming in C++/Chapter 3_Loops and Decisions/4.cpp
OjeshManandhar/Code-Backup
67a395fe2439725f42ce0a18b4d2e2e65f00695d
[ "MIT" ]
2
2019-01-03T14:12:52.000Z
2019-03-22T16:13:16.000Z
C++/Object-Oriented Programming in C++/Chapter 3_Loops and Decisions/4.cpp
OjeshManandhar/Code-Backup
67a395fe2439725f42ce0a18b4d2e2e65f00695d
[ "MIT" ]
null
null
null
C++/Object-Oriented Programming in C++/Chapter 3_Loops and Decisions/4.cpp
OjeshManandhar/Code-Backup
67a395fe2439725f42ce0a18b4d2e2e65f00695d
[ "MIT" ]
1
2019-01-13T17:54:01.000Z
2019-01-13T17:54:01.000Z
#include <iostream> using namespace std; int main() { float a,b; char op,choice; do { cout << "Enter first number, operator, second number: "; cin >> a >> op >> b; switch (op) { case '+': cout << "Answer: " << a+b << endl; break; case '-': cout << "Answer: " << a-b << endl; break; case '*': cout << "Answer: " << a*b << endl; break; case '/': cout << "Answer: " << a/b << endl; break; default: cout << "Wrong Input." << endl; } cout << endl << "Do another (y/n): "; cin >> choice; cout << endl; }while (choice == 'y'); return 0; }
19.35
64
0.381137
OjeshManandhar
9b3155e795f2c03c44a0bb406fe61ae84567ab70
601
cpp
C++
IRadiance/src/IRadiance/Raytracer/Samplers/JitteredSampler.cpp
Nickelium/IRadiance
7e7040460852a6f9f977cf466e6dcecf44618ae7
[ "MIT" ]
null
null
null
IRadiance/src/IRadiance/Raytracer/Samplers/JitteredSampler.cpp
Nickelium/IRadiance
7e7040460852a6f9f977cf466e6dcecf44618ae7
[ "MIT" ]
null
null
null
IRadiance/src/IRadiance/Raytracer/Samplers/JitteredSampler.cpp
Nickelium/IRadiance
7e7040460852a6f9f977cf466e6dcecf44618ae7
[ "MIT" ]
null
null
null
#include "pch.h" #include "JitteredSampler.h" #include "IRadiance/Raytracer/Maths/Utilities.h" namespace IRadiance { JitteredSampler::JitteredSampler(int _nbSamples) : Sampler(_nbSamples) { Init(); } void JitteredSampler::GenerateSamples2D() { float n = (float)(int)sqrt(m_NumSamples); for (int s = 0; s < m_NumSets; ++s) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { m_Samples2D.push_back ( Point2 { (j + RandUNorm()) / n, (i + RandUNorm()) / n } ); } } } } }
16.694444
50
0.517471
Nickelium
9b3d3948d6f9955e5ae01810467f6dc31d5c2a08
3,966
cpp
C++
2003 - Task3 {16 of 19} [g]/src/Main.cpp
retgone/cmc-cg
7e5a76992e524958353ee799092f810681a13107
[ "MIT" ]
null
null
null
2003 - Task3 {16 of 19} [g]/src/Main.cpp
retgone/cmc-cg
7e5a76992e524958353ee799092f810681a13107
[ "MIT" ]
null
null
null
2003 - Task3 {16 of 19} [g]/src/Main.cpp
retgone/cmc-cg
7e5a76992e524958353ee799092f810681a13107
[ "MIT" ]
null
null
null
#include <vcl.h> #pragma hdrstop #include "Filters.h" #include "Main.h" #include "dlg.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm1::Open1Click(TObject *Sender) { if(OpenDialog1->Execute()) { Image1->Picture->LoadFromFile(OpenDialog1->FileName); Image1->Width = Image1->Picture->Width; Image1->Height = Image1->Picture->Height; } } //--------------------------------------------------------------------------- void __fastcall TForm1::Binarize1Click(TObject *Sender) { Binar(Image1->Picture->Bitmap); Image1->Refresh(); } //--------------------------------------------------------------------------- void __fastcall TForm1::N2Click(TObject *Sender) { Rasshirenie(Image1->Picture->Bitmap, GetR()); Image1->Refresh(); } //--------------------------------------------------------------------------- void __fastcall TForm1::N3Click(TObject *Sender) { Szhatie(Image1->Picture->Bitmap, GetR()); Image1->Refresh(); } //--------------------------------------------------------------------------- void __fastcall TForm1::N4Click(TObject *Sender) { Otkritie(Image1->Picture->Bitmap, GetR()); Image1->Refresh(); } //--------------------------------------------------------------------------- void __fastcall TForm1::N5Click(TObject *Sender) { Zakritie(Image1->Picture->Bitmap, GetR()); Image1->Refresh(); } //--------------------------------------------------------------------------- void __fastcall TForm1::N6Click(TObject *Sender) { Median(Image1->Picture->Bitmap, GetR()); Image1->Refresh(); } //--------------------------------------------------------------------------- void __fastcall TForm1::N8Click(TObject *Sender) { FindClock(Image1->Picture->Bitmap, Image1->Picture->Bitmap); Image1->Refresh(); } //--------------------------------------------------------------------------- void __fastcall TForm1::Simple1Click(TObject *Sender) { Graphics::TBitmap *bin = new Graphics::TBitmap; bin->Assign(Image1->Picture->Bitmap); Binar(bin); FindClock(Image1->Picture->Bitmap, bin); delete bin; Image1->Refresh(); } //--------------------------------------------------------------------------- void __fastcall TForm1::Noisy21311Click(TObject *Sender) { Graphics::TBitmap *bin = new Graphics::TBitmap; bin->Assign(Image1->Picture->Bitmap); Median(bin, 1); Binar(bin); Median(bin, 1); Zakritie(bin, 3); Median(bin, 1); FindClock(Image1->Picture->Bitmap, bin); delete bin; Image1->Refresh(); } //--------------------------------------------------------------------------- void __fastcall TForm1::SimpleNoisy11Click(TObject *Sender) { Graphics::TBitmap *bin = new Graphics::TBitmap; bin->Assign(Image1->Picture->Bitmap); Median(bin, 2); Binar(bin); Median(bin, 1); Median(bin, 1); Median(bin, 1); Median(bin, 1); Median(bin, 2); Median(bin, 2); Median(bin, 2); Zakritie(bin, 3); FindClock(Image1->Picture->Bitmap, bin); delete bin; Image1->Refresh(); } //--------------------------------------------------------------------------- void __fastcall TForm1::Noisy1Click(TObject *Sender) { Graphics::TBitmap *bin = new Graphics::TBitmap; bin->Assign(Image1->Picture->Bitmap); Binar(bin); Szhatie(bin, 1); Zakritie(bin, 3); Rasshirenie(bin, 2); Median(bin, 3); Median(bin, 3); Median(bin, 3); FindClock(Image1->Picture->Bitmap, bin); delete bin; Image1->Refresh(); } //---------------------------------------------------------------------------
27.541667
78
0.459153
retgone
9b4085c028a2a9d273bbb5cf4be0fe4abdea303a
3,998
cpp
C++
player.cpp
williamsonlogan/fauxcaster
815fa250b49efb5a36fa2c56db65c9ff6b141e41
[ "MIT" ]
null
null
null
player.cpp
williamsonlogan/fauxcaster
815fa250b49efb5a36fa2c56db65c9ff6b141e41
[ "MIT" ]
null
null
null
player.cpp
williamsonlogan/fauxcaster
815fa250b49efb5a36fa2c56db65c9ff6b141e41
[ "MIT" ]
null
null
null
#include "player.h" Player::Player(float posx, float posy, Map * map) : Entity::Entity("player", posx, posy, "\0") { if (agk::GetObjectExists(getID())) agk::DeleteObject(getID()); _map = map; agk::SetCameraPosition(1, posx, 0, posy); agk::SetCameraRotation(1, 0, 0, 0); agk::SetCameraFOV(1, fieldOfView); agk::SetCameraRange(1, 0.0001f, 500.0f); agk::SetRawMouseVisible(0); } Player::~Player() { agk::SetRawMouseVisible(1); } void Player::Update() { rotation += GetMouseX() * mouseSensitivity * agk::GetFrameTime(); if (pitch <= 60.0f && pitch >= -60.0f) pitch += GetMouseY() * mouseSensitivity * agk::GetFrameTime(); if (pitch > 60.0f) pitch = 60.0f; else if (pitch < -60.0f) pitch = -60.0f; agk::SetCameraRotation(1, pitch, rotation, 0); float velx = 0, vely = 0; bool collides = false; float dirX = sinf(rotation * RADS), dirY = cosf(rotation * RADS); float perpDirX = dirY, perpDirY = -dirX; if (GetVerticalAxis() != 0) { velx += dirX * GetVerticalAxis(); vely += dirY * GetVerticalAxis(); /*if (_map->GetTile((int)getPosX(), (int)getPosY()) != '.') { //TODO: ResolveCollision() setPosition(getPosX() - sinf(rotation * RADS) * movementSpeed * agk::GetFrameTime() * GetVerticalAxis(), getPosY() - cosf(rotation * RADS) * movementSpeed * agk::GetFrameTime() * GetVerticalAxis()); } */ } if (GetHorizontalAxis() != 0) { velx += perpDirX * GetHorizontalAxis(); vely += perpDirY * GetHorizontalAxis(); /* if (_map->GetTile((int)getPosX(), (int)getPosY()) != '.') { //TODO: ResolveCollision() setPosition(getPosX() - cosf(rotation * RADS) * movementSpeed * agk::GetFrameTime() * GetHorizontalAxis(), getPosY() + sinf(rotation * RADS) * movementSpeed * agk::GetFrameTime() * GetHorizontalAxis()); } */ } if (velx != 0 || vely != 0) { //normalize velocity to scale by speed float velMag = std::sqrt(velx * velx + vely * vely); velx /= velMag; vely /= velMag; velMag = 1; velx *= movementSpeed; vely *= movementSpeed; float newx = getPosX() + velx; float newy = getPosY() + vely; for (int i = -1; i <= 1 && !collides; ++i) { for (int j = -1; j <= 1 && !collides; ++j) { float checkMag = std::sqrt(i * i + j * j); float xOff = (float)i / checkMag; float yOff = (float)j / checkMag; if (newx + xOff * 0.075f < _map->getWidth() && newx + xOff * 0.075f >= 0 && newy + yOff * 0.075f < _map->getHeight() && newy + yOff * 0.075f >= 0 && _map->IsWall(int(newx + xOff * 0.075f), int(newy + yOff * 0.075f))) collides = true; } } if (!collides) { setPosition(newx, newy); } else { //normalize velocity velMag = std::sqrt(velx * velx + vely * vely); velx /= velMag; vely /= velMag; velMag = 1; float oldvelx = velx; if (!_map->IsWall(int(getPosX()), int(getPosY() + vely))) velx = 0; if (!_map->IsWall(int(getPosX() + oldvelx), int(getPosY()))) vely = 0; if (!_map->IsWall(int(getPosX() + velx), int(getPosY() + vely))) setPosition(getPosX() + 0.1 * velx, getPosY() + 0.1 * vely); } } agk::SetCameraPosition(1, getPosX(), 0, getPosY()); agk::SetRawMousePosition(agk::GetVirtualWidth() / 2, agk::GetVirtualHeight() / 2); } float Player::GetMouseX() { float mx = agk::GetRawMouseX() - (agk::GetVirtualWidth() / 2); float xmove = 0; xmove += mx; xmove /= 10; return xmove; } float Player::GetMouseY() { float my = agk::GetRawMouseY() - (agk::GetVirtualHeight() / 2); float ymove = 0; ymove += my; ymove /= 10; return ymove; } float Player::GetHorizontalAxis() { float val; if (agk::GetRawKeyState(68) && !agk::GetRawKeyState(65)) val = 1.0f; else if (!agk::GetRawKeyState(68) && agk::GetRawKeyState(65)) val = -1.0f; else val = 0.0f; return val; } float Player::GetVerticalAxis() { float val; if (agk::GetRawKeyState(87) && !agk::GetRawKeyState(83)) val = 1.0f; else if (!agk::GetRawKeyState(87) && agk::GetRawKeyState(83)) val = -1.0f; else val = 0.0f; return val; }
23.94012
108
0.611306
williamsonlogan
9b4323148a73bc90d8bd3a69f15320f96e902aa6
986
hpp
C++
include/communication/mapping/SerialTransferMapping.hpp
Tyulis/ToyGB
841507fa19c320caa98b16eae2a6df0bc996ba51
[ "MIT" ]
null
null
null
include/communication/mapping/SerialTransferMapping.hpp
Tyulis/ToyGB
841507fa19c320caa98b16eae2a6df0bc996ba51
[ "MIT" ]
null
null
null
include/communication/mapping/SerialTransferMapping.hpp
Tyulis/ToyGB
841507fa19c320caa98b16eae2a6df0bc996ba51
[ "MIT" ]
null
null
null
#ifndef _COMMUNICATION_MAPPING_SERIALTRANSFERMAPPING_HPP #define _COMMUNICATION_MAPPING_SERIALTRANSFERMAPPING_HPP #include "core/hardware.hpp" #include "memory/Constants.hpp" #include "memory/MemoryMapping.hpp" #include "util/error.hpp" namespace toygb { /** Serial port communication IO registers mapping */ class SerialTransferMapping : public MemoryMapping { public: SerialTransferMapping(HardwareStatus* m_hardware); uint8_t get(uint16_t address); void set(uint16_t address, uint8_t value); uint8_t transferData; // Data to be transferred / that has been received through the serial port (register SB) bool transferStartFlag; // Set whether a transfer is requested / in progress (register SC, bit 7) bool clockSpeed; // Set whether to use the fast clock speed (CGB only) (register SC, bit 1) bool shiftClock; // Clock to use (0 = external, 1 = internal) (register SC, bit 0) private: HardwareStatus* m_hardware; }; } #endif
32.866667
116
0.744422
Tyulis
9b4cdd879a3a1360c32ccc5ebeff837efe382c21
120
cpp
C++
FightingGameProject/FightersHitStopMessage.cpp
RoundBearChoi/CPP_FightingGame
21d07caab82dd5ee0ad233886a36ef1fe93e25b6
[ "Unlicense" ]
8
2021-03-08T06:21:13.000Z
2022-03-04T21:53:37.000Z
FightingGameProject/FightersHitStopMessage.cpp
RoundBearChoi/CPP_FightingGame
21d07caab82dd5ee0ad233886a36ef1fe93e25b6
[ "Unlicense" ]
null
null
null
FightingGameProject/FightersHitStopMessage.cpp
RoundBearChoi/CPP_FightingGame
21d07caab82dd5ee0ad233886a36ef1fe93e25b6
[ "Unlicense" ]
null
null
null
#include "FightersHitStopMessage.h" namespace RB { Updater* FightersHitStopMessage::_fightersFixedUpdater = nullptr; }
20
66
0.816667
RoundBearChoi
9b4dde4486692724c84b39148eb1e3b9bc7319cb
30
cc
C++
Token/samples/sample1.cc
lijinpei/libclang-sample
8594028f0025769acd27ccbe64a1b35375279c99
[ "MIT" ]
31
2015-02-16T10:05:45.000Z
2021-12-22T16:09:08.000Z
Token/samples/sample1.cc
lijinpei/libclang-sample
8594028f0025769acd27ccbe64a1b35375279c99
[ "MIT" ]
1
2015-12-31T21:56:03.000Z
2016-01-08T10:36:44.000Z
Token/samples/sample1.cc
lijinpei/libclang-sample
8594028f0025769acd27ccbe64a1b35375279c99
[ "MIT" ]
12
2015-11-03T03:22:49.000Z
2020-05-05T15:16:48.000Z
int main("aa", /* "bb"= */1 )
15
29
0.4
lijinpei
9b536374a077c4498cc6f0d33e814e102cbc0dcb
527
cpp
C++
wizards/qtcreator/projects/xpcf application/main.cpp
b-com-software-basis/xpcf
26ce21929ff6209ef69117270cf49844348c988f
[ "Apache-2.0" ]
null
null
null
wizards/qtcreator/projects/xpcf application/main.cpp
b-com-software-basis/xpcf
26ce21929ff6209ef69117270cf49844348c988f
[ "Apache-2.0" ]
7
2020-02-13T20:35:16.000Z
2021-11-19T17:46:15.000Z
wizards/qtcreator/projects/xpcf application/main.cpp
b-com-software-basis/xpcf
26ce21929ff6209ef69117270cf49844348c988f
[ "Apache-2.0" ]
1
2018-02-26T14:10:43.000Z
2018-02-26T14:10:43.000Z
%{Cpp:LicenseTemplate}\ #include <xpcf/xpcf.h> #include <iostream> namespace xpcf=org::bcom::xpcf; /** * Declare module. */ int main(int argc, char ** argv) { SRef<xpcf::IComponentManager> xpcfComponentManager = xpcf::getComponentManagerInstance(); XPCFErrorCode xpcfComponentManager->loadModuleMetadata(%{moduleName},"./"); SRef<%{interfaceName}> component = xpcfComponentManager->create<>(%{componentName})->bindTo<%{interfaceName}>(); // call %{interfaceName} methods below //... return 0; }
25.095238
116
0.6926
b-com-software-basis
9b5cdaf94bbc021f9036f4087b03fd370ce4b2d6
4,916
cpp
C++
OOP/Second partial exam/ex 7/main.cpp
LjupcheD14/FINKI1408
be2454864d8aa0c33621141295f958424c7b0f16
[ "Apache-2.0" ]
null
null
null
OOP/Second partial exam/ex 7/main.cpp
LjupcheD14/FINKI1408
be2454864d8aa0c33621141295f958424c7b0f16
[ "Apache-2.0" ]
null
null
null
OOP/Second partial exam/ex 7/main.cpp
LjupcheD14/FINKI1408
be2454864d8aa0c33621141295f958424c7b0f16
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cstring> using namespace std; class OutOfBoundsException { public: void message() { cout<<"Brojot na pin kodovi ne moze da go nadmine dozvolenoto"<<endl; } }; class Karticka { protected: char smetka[16]; int pin; bool povekjePin; public: Karticka(char* smetka,int pin) { strcpy(this->smetka,smetka); this->pin=pin; this->povekjePin=false; } // дополниете ја класата bool getDopolnitelenPin() { return povekjePin; } char *getSmetka() { return smetka; } virtual int presmetajTezina() { int digits=0; int k=pin; while(k!=0) { k/=10; digits++; } return digits; } int tezinaProbivanje() { int digits=0; int k=pin; while(k!=0) { k/=10; digits++; } return digits; } friend ostream &operator<<(ostream &out, Karticka &k) { out<<k.smetka<<": "<<k.tezinaProbivanje()<<endl; return out; } }; //вметнете го кодот за SpecijalnaKarticka class SpecijalnaKarticka : public Karticka { private: int *dopolnitelni; int n; static int maxn; public: SpecijalnaKarticka(char* smetka,int pin, int *dopolnitelni, int n) : Karticka(smetka,pin) { this->dopolnitelni=new int[n]; for(int i=0; i<n; i++) { this->dopolnitelni[i]=dopolnitelni[i]; } this->n=n; } SpecijalnaKarticka(char smetka[15], int pin) : Karticka(smetka,pin) { this->dopolnitelni=new int[0]; this->n=0; } int tezinaProbivanje() { return Karticka::presmetajTezina()+n; } SpecijalnaKarticka &operator+=(int k) { if(n+1>maxn) throw OutOfBoundsException(); int *tmp = new int[n+1]; for(int i=0; i<n; i++) { tmp[i]=dopolnitelni[i]; } delete[] dopolnitelni; tmp[n]=k; dopolnitelni=tmp; return *this; } int broj() { return n; } int maks() { return maxn; } }; int SpecijalnaKarticka::maxn=4; class Banka { private: char naziv[30]; Karticka *karticki[20]; int broj; static int LIMIT; public: Banka(char *naziv, Karticka** karticki,int broj ) { strcpy(this->naziv,naziv); for (int i=0; i<broj; i++) { //ako kartickata ima dopolnitelni pin kodovi if (karticki[i]->getDopolnitelenPin()) { this->karticki[i]=new SpecijalnaKarticka(*dynamic_cast<SpecijalnaKarticka*>(karticki[i])); } else this->karticki[i]=new Karticka(*karticki[i]); } this->broj=broj; } ~Banka() { for (int i=0; i<broj; i++) delete karticki[i]; } //да се дополни класата static void setLIMIT(int lim) { LIMIT=lim; } void pecatiKarticki() { cout<<"Vo bankata "<<naziv<<" moze da se probijat kartickite:"<<endl; for(int i=0; i<broj; i++) { if(karticki[i]->presmetajTezina()<=LIMIT) { cout<<*karticki[i]; } } } void dodadiDopolnitelenPin(char *smetka, int novPin) { for(int i=0; i<broj; i++) { bool flag=false; int index; if(strcmp(karticki[i]->getSmetka(),smetka)==0) { flag=true; index=i; } if(flag) { SpecijalnaKarticka *sk=dynamic_cast<SpecijalnaKarticka*>(karticki[index]); if(sk!=0) { try { *sk+=novPin; } catch (OutOfBoundsException e) { throw e; } } } } } }; int Banka::LIMIT=7; int main() { Karticka **niza; int n,m,pin; char smetka[16]; bool daliDopolnitelniPin; cin>>n; niza=new Karticka*[n]; for (int i=0; i<n; i++) { cin>>smetka; cin>>pin; cin>>daliDopolnitelniPin; if (!daliDopolnitelniPin) niza[i]=new Karticka(smetka,pin); else niza[i]=new SpecijalnaKarticka(smetka,pin); } Banka komercijalna("Komercijalna",niza,n); for (int i=0; i<n; i++) delete niza[i]; delete [] niza; cin>>m; for (int i=0; i<m; i++) { cin>>smetka>>pin; try { komercijalna.dodadiDopolnitelenPin(smetka,pin); } catch(OutOfBoundsException e) { e.message(); } } Banka::setLIMIT(5); komercijalna.pecatiKarticki(); }
20.39834
106
0.486981
LjupcheD14
9b635c0e1d4b75aa6a618c02984155d021eb27ac
414
hpp
C++
sprout/random.hpp
osyo-manga/Sprout
8885b115f739ef255530f772067475d3bc0dcef7
[ "BSL-1.0" ]
1
2020-02-04T05:16:01.000Z
2020-02-04T05:16:01.000Z
sprout/random.hpp
osyo-manga/Sprout
8885b115f739ef255530f772067475d3bc0dcef7
[ "BSL-1.0" ]
null
null
null
sprout/random.hpp
osyo-manga/Sprout
8885b115f739ef255530f772067475d3bc0dcef7
[ "BSL-1.0" ]
null
null
null
#ifndef SPROUT_RANDOM_HPP #define SPROUT_RANDOM_HPP #include <sprout/config.hpp> #include <sprout/random/engine.hpp> #include <sprout/random/distribution.hpp> #include <sprout/random/variate_generator.hpp> #include <sprout/random/random_result.hpp> #include <sprout/random/iterator.hpp> #include <sprout/random/range.hpp> #include <sprout/random/unique_seed.hpp> #endif // #ifndef SPROUT_RANDOM_HPP
29.571429
47
0.777778
osyo-manga
9b6a2db45e653e07c7df5e840f9529727c1f07c3
377
cpp
C++
Array/Leaders in an Array problem using Efficient Method.cpp
themlstudent/MasteringDataStructure
06ee83706a3844d21249f1d192b0619f30f12eef
[ "MIT" ]
null
null
null
Array/Leaders in an Array problem using Efficient Method.cpp
themlstudent/MasteringDataStructure
06ee83706a3844d21249f1d192b0619f30f12eef
[ "MIT" ]
null
null
null
Array/Leaders in an Array problem using Efficient Method.cpp
themlstudent/MasteringDataStructure
06ee83706a3844d21249f1d192b0619f30f12eef
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; void leaders(int arr[], int n) { int curr_ldr = arr[n - 1]; cout<<curr_ldr<<" "; for(int i = n - 2; i >= 0; i--) { if(curr_ldr < arr[i]) { curr_ldr = arr[i]; cout<<curr_ldr<<" "; } } } int main() { int arr[] = {7, 10, 4, 10, 6, 5, 2}, n = 7; leaders(arr, n); }
12.16129
50
0.440318
themlstudent
9b6b15db0b9706e037b025b648352576fec4982e
279
cpp
C++
Windows/LV50A/Source/UI-Methods/UI-Paint.cpp
landonviator/LV50A
4b9dce09b7bb15cc80393b21d5cea3dcfc981e6f
[ "MIT" ]
null
null
null
Windows/LV50A/Source/UI-Methods/UI-Paint.cpp
landonviator/LV50A
4b9dce09b7bb15cc80393b21d5cea3dcfc981e6f
[ "MIT" ]
null
null
null
Windows/LV50A/Source/UI-Methods/UI-Paint.cpp
landonviator/LV50A
4b9dce09b7bb15cc80393b21d5cea3dcfc981e6f
[ "MIT" ]
null
null
null
/* ============================================================================== UI-Paint.cpp Created: 24 Oct 2021 1:41:00am Author: Landon Viator ============================================================================== */ #include "../PluginEditor.h"
23.25
80
0.25448
landonviator
9b7b06d64125b187fef1fe5d38f9ce54d460bf0d
217
cpp
C++
lab5/exercise2.cpp
tz01x/Cse207_lab
f355e5dfa2b68a632d104e554975cd2c6e6f1162
[ "MIT" ]
null
null
null
lab5/exercise2.cpp
tz01x/Cse207_lab
f355e5dfa2b68a632d104e554975cd2c6e6f1162
[ "MIT" ]
null
null
null
lab5/exercise2.cpp
tz01x/Cse207_lab
f355e5dfa2b68a632d104e554975cd2c6e6f1162
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int GCD(int f,int s){ if(f<=0){return s;} else if(s<=0){return f;} return GCD(s,f%s); } int main(){ int FIRST=10,SECOND=15; int n=GCD(FIRST,SECOND); cout<<n<<endl; }
12.055556
24
0.631336
tz01x
9b7b2beab27a0ed0e381833fd07e3c2c7aeb0acc
21,849
cpp
C++
tests/ReloadTests.cpp
theOtherMichael/HotConsts
0184075ce5cf09d4752682b2c75c883abd8a02f0
[ "MIT" ]
1
2021-05-09T21:36:16.000Z
2021-05-09T21:36:16.000Z
tests/ReloadTests.cpp
theOtherMichael/HotConsts
0184075ce5cf09d4752682b2c75c883abd8a02f0
[ "MIT" ]
null
null
null
tests/ReloadTests.cpp
theOtherMichael/HotConsts
0184075ce5cf09d4752682b2c75c883abd8a02f0
[ "MIT" ]
null
null
null
#include <HotConsts/HotConsts.h> #include "_tests.h" // NOTE: For these tests to succeed, the working directory of the test application // must be the folder containing the HotConsts_Test project. // In Xcode, this requires manual modification. // Use backslashes in paths on Windows becaus'a fuckin' Microsoft #ifdef _WIN32 #define TESTFILEDIR "ReloadTests\\" #else #define TESTFILEDIR "ReloadTests/" #endif // RELOAD TESTS // Source code comment parsing bool handleSingleLineComments() { bool startsInMultiline = false; std::string beforeLine, afterLine; std::ifstream beforeFile(TESTFILEDIR "handleSingleLineComments_before.txt"); std::ifstream afterFile(TESTFILEDIR "handleSingleLineComments_after.txt"); if (beforeFile.is_open() && afterFile.is_open()) { while (std::getline(beforeFile, beforeLine)) { if (std::getline(afterFile, afterLine)) { beforeLine = HotConsts::_stripComments(beforeLine, startsInMultiline); if (beforeLine != afterLine) { beforeFile.close(); afterFile.close(); return false; } } else { std::cout << "Number of lines in \"ReloadTests/handleSingleLineComments_before.txt\" and " "\"ReloadTests/handleSingleLineComments_after.txt\" differ." << std::endl; beforeFile.close(); afterFile.close(); return false; } } } else { std::cout << "Issue opening \"ReloadTests/handleSingleLineComments_before.txt\" or " "\"ReloadTests/handleSingleLineComments_after.txt\"" << std::endl; if (beforeFile.is_open()) beforeFile.close(); if (afterFile.is_open()) afterFile.close(); return false; } return true; } bool handleSingleLineCommentsInStrings() { bool startsInMultiline = false; std::string beforeLine, afterLine; std::ifstream srcFile(TESTFILEDIR "handleSingleLineCommentsInStrings.txt"); if (srcFile.is_open()) { while (std::getline(srcFile, beforeLine)) { afterLine = HotConsts::_stripComments(beforeLine, startsInMultiline); if (beforeLine != afterLine) { srcFile.close(); return false; } } } else { std::cout << "Issue opening \"ReloadTests/handleSingleLineCommentsInStrings.txt\"." << std::endl; return false; } return true; } bool handleMultiLineComments() { bool startsInMultiline = false; std::string beforeLine, afterLine; std::ifstream beforeFile(TESTFILEDIR "handleMultiLineComments_before.txt"); std::ifstream afterFile(TESTFILEDIR "handleMultiLineComments_after.txt"); if (beforeFile.is_open() && afterFile.is_open()) { while (std::getline(beforeFile, beforeLine)) { if (std::getline(afterFile, afterLine)) { beforeLine = HotConsts::_stripComments(beforeLine, startsInMultiline); if (beforeLine != afterLine) { beforeFile.close(); afterFile.close(); return false; } } else { std::cout << "Number of lines in \"ReloadTests/handleMultiLineComments_before.txt\" and " "\"ReloadTests/handleMultiLineComments_after.txt\" differ." << std::endl; beforeFile.close(); afterFile.close(); return false; } } } else { std::cout << "Issue opening \"ReloadTests/handleMultiLineComments_before.txt\" or " "\"ReloadTests/handleMultiLineComments_after.txt\"" << std::endl; if (beforeFile.is_open()) beforeFile.close(); if (afterFile.is_open()) afterFile.close(); return false; } return true; } bool handleMultiLineCommentsInStrings() { bool startsInMultiline = false; std::string beforeLine, afterLine; std::ifstream srcFile(TESTFILEDIR "handleMultiLineCommentsInStrings.txt"); if (srcFile.is_open()) { while (std::getline(srcFile, beforeLine)) { afterLine = HotConsts::_stripComments(beforeLine, startsInMultiline); if (beforeLine != afterLine) { srcFile.close(); return false; } } } else { std::cout << "Issue opening \"ReloadTests/handleMultiLineCommentsInStrings.txt\"." << std::endl; return false; } return true; } // Source code reload bool reloadSimpleHC() { const HotConsts::HC_Atomic<int>& reloadSimpleHC_testVal = HotConsts::_registerHotConst<int>( TESTFILEDIR "reloadSimpleHC.txt", "reloadSimpleHC_testVal", "int") = 1; HotConsts::_reloadSrcFile(TESTFILEDIR "reloadSimpleHC.txt"); if (reloadSimpleHC_testVal == 100) return true; else return false; } bool reloadSingleHCWithTypeModifier() { const HotConsts::HC_Atomic<unsigned int>& reloadSingleHCWithTypeModifier_testVal = HotConsts::_registerHotConst<unsigned int>( TESTFILEDIR "reloadSingleHCWithTypeModifier.txt", "reloadSingleHCWithTypeModifier_testVal", "unsigned int") = 1; HotConsts::_reloadSrcFile(TESTFILEDIR "reloadSingleHCWithTypeModifier.txt"); if (reloadSingleHCWithTypeModifier_testVal == 100) return true; else return false; } bool reloadSingleHCWithLineBreaks() { const HotConsts::HC_Atomic<int>& reloadSingleHCWithLineBreaks_testVal = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadSingleHCWithLineBreaks.txt", "reloadSingleHCWithLineBreaks_testVal", "int") = 1; HotConsts::_reloadSrcFile(TESTFILEDIR "reloadSingleHCWithLineBreaks.txt"); if (reloadSingleHCWithLineBreaks_testVal == 100) return true; else return false; } bool reloadSingleHCWithTypeModifierAndLineBreaks() { const HotConsts::HC_Atomic<int>& reloadSingleHCWithTypeModifierAndLineBreaks_testVal = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadSingleHCWithTypeModifierAndLineBreaks.txt", "reloadSingleHCWithTypeModifierAndLineBreaks_testVal", "unsigned int") = 1; HotConsts::_reloadSrcFile(TESTFILEDIR "reloadSingleHCWithTypeModifierAndLineBreaks.txt"); if (reloadSingleHCWithTypeModifierAndLineBreaks_testVal == 100) return true; else return false; } bool reloadMultipleHCs() { const HotConsts::HC_Atomic<int>& reloadMultipleHCs_testVal1 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadMultipleHCs.txt", "reloadMultipleHCs_testVal1", "int") = 1; const HotConsts::HC_Atomic<int>& reloadMultipleHCs_testVal2 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadMultipleHCs.txt", "reloadMultipleHCs_testVal2", "int") = 2; const HotConsts::HC_Atomic<int>& reloadMultipleHCs_testVal3 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadMultipleHCs.txt", "reloadMultipleHCs_testVal3", "int") = 3; HotConsts::_reloadSrcFile(TESTFILEDIR "reloadMultipleHCs.txt"); if (reloadMultipleHCs_testVal1 == 100 && reloadMultipleHCs_testVal2 == 200 && reloadMultipleHCs_testVal3 == 300) return true; else return false; } bool reloadMutipleHCsSingleLine() { const HotConsts::HC_Atomic<int>& reloadMultipleHCsSingleLine_testVal1 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadMutipleHCsSingleLine.txt", "reloadMultipleHCsSingleLine_testVal1", "int") = 1; const HotConsts::HC_Atomic<int>& reloadMultipleHCsSingleLine_testVal2 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadMutipleHCsSingleLine.txt", "reloadMultipleHCsSingleLine_testVal2", "int") = 2; const HotConsts::HC_Atomic<int>& reloadMultipleHCsSingleLine_testVal3 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadMutipleHCsSingleLine.txt", "reloadMultipleHCsSingleLine_testVal3", "int") = 3; HotConsts::_reloadSrcFile(TESTFILEDIR "reloadMutipleHCsSingleLine.txt"); if (reloadMultipleHCsSingleLine_testVal1 == 100 && reloadMultipleHCsSingleLine_testVal2 == 200 && reloadMultipleHCsSingleLine_testVal3 == 300) return true; else return false; } bool reloadIgnoresMacroInStrings() { const HotConsts::HC_Atomic<int>& reloadIgnoresMacroInStrings_testVal1 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadIgnoresMacroInStrings.txt", "reloadIgnoresMacroInStrings_testVal1", "int") = 100; HotConsts::_reloadSrcFile(TESTFILEDIR "reloadIgnoresMacroInStrings.txt"); if (reloadIgnoresMacroInStrings_testVal1 == 100) return true; else return false; } bool reloadSkipsSymbolsContainingHC() { const HotConsts::HC_Atomic<int>& reloadSkipsSymbolsContainingHC_testVal1 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadSkipsSymbolsContainingHC.txt", "reloadSkipsSymbolsContainingHC_testVal1", "int") = 1; const HotConsts::HC_Atomic<int>& reloadSkipsSymbolsContainingHC_testVal2 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadSkipsSymbolsContainingHC.txt", "reloadSkipsSymbolsContainingHC_testVal2", "int") = 2; const HotConsts::HC_Atomic<int>& reloadSkipsSymbolsContainingHC_testVal3 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadSkipsSymbolsContainingHC.txt", "reloadSkipsSymbolsContainingHC_testVal3", "int") = 3; const HotConsts::HC_Atomic<int>& reloadSkipsSymbolsContainingHC_testVal4 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadSkipsSymbolsContainingHC.txt", "reloadSkipsSymbolsContainingHC_testVal4", "int") = 4; const HotConsts::HC_Atomic<int>& reloadSkipsSymbolsContainingHC_testVal5 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadSkipsSymbolsContainingHC.txt", "reloadSkipsSymbolsContainingHC_testVal5", "int") = 5; const HotConsts::HC_Atomic<int>& reloadSkipsSymbolsContainingHC_testVal6 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadSkipsSymbolsContainingHC.txt", "reloadSkipsSymbolsContainingHC_testVal6", "int") = 6; const HotConsts::HC_Atomic<int>& reloadSkipsSymbolsContainingHC_testVal7 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadSkipsSymbolsContainingHC.txt", "reloadSkipsSymbolsContainingHC_testVal7", "int") = 7; const HotConsts::HC_Atomic<int>& reloadSkipsSymbolsContainingHC_testVal8 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadSkipsSymbolsContainingHC.txt", "reloadSkipsSymbolsContainingHC_testVal8", "int") = 8; const HotConsts::HC_Atomic<int>& reloadSkipsSymbolsContainingHC_testVal9 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadSkipsSymbolsContainingHC.txt", "reloadSkipsSymbolsContainingHC_testVal9", "int") = 9; const HotConsts::HC_Atomic<int>& reloadSkipsSymbolsContainingHC_testVal10 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadSkipsSymbolsContainingHC.txt", "reloadSkipsSymbolsContainingHC_testVal10", "int") = 10; HotConsts::_reloadSrcFile(TESTFILEDIR "reloadSkipsSymbolsContainingHC.txt"); if (reloadSkipsSymbolsContainingHC_testVal1 == 1 && reloadSkipsSymbolsContainingHC_testVal2 == 2 && reloadSkipsSymbolsContainingHC_testVal3 == 3 && reloadSkipsSymbolsContainingHC_testVal4 == 4 && reloadSkipsSymbolsContainingHC_testVal5 == 5 && reloadSkipsSymbolsContainingHC_testVal6 == 6 && reloadSkipsSymbolsContainingHC_testVal7 == 7 && reloadSkipsSymbolsContainingHC_testVal8 == 8 && reloadSkipsSymbolsContainingHC_testVal9 == 9 && reloadSkipsSymbolsContainingHC_testVal10 == 10) return true; else return false; } // Bad source code reload bool reloadCatchesFileOpenFailure() { HotConsts::_reloadSrcFile("NonexistentFolder/Nonexistentfile.bad"); return true; } bool reloadHandlesBadParams() { const HotConsts::HC_Atomic<int>& testConst = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadHandlesBadParams.txt", "testConst", "int") = 1; HotConsts::_reloadSrcFile(TESTFILEDIR "reloadHandlesBadParams.txt"); if (testConst == 1) return true; else return false; } bool reloadHandlesBadAssignment() { const HotConsts::HC_Atomic<int>& reloadHandlesBadAssignment_testVal1 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadHandlesBadAssignment.txt", "reloadHandlesBadAssignment_testVal1", "int") = 1; // const HotConsts::HC_Atomic<int>& reloadHandlesBadAssignment_testVal2 = // HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadHandlesBadAssignment.txt", // "reloadHandlesBadAssignment_testVal2", "int") = 2; const HotConsts::HC_Atomic<int>& reloadHandlesBadAssignment_testVal3 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadHandlesBadAssignment.txt", "reloadHandlesBadAssignment_testVal3", "int") = 3; const HotConsts::HC_Atomic<int>& reloadHandlesBadAssignment_testVal4 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadHandlesBadAssignment.txt", "reloadHandlesBadAssignment_testVal4", "int") = 4; const HotConsts::HC_Atomic<int>& reloadHandlesBadAssignment_testVal5 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadHandlesBadAssignment.txt", "reloadHandlesBadAssignment_testVal5", "int") = 5; const HotConsts::HC_Atomic<int>& reloadHandlesBadAssignment_testVal6 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadHandlesBadAssignment.txt", "reloadHandlesBadAssignment_testVal6", "int") = 6; HotConsts::_reloadSrcFile(TESTFILEDIR "reloadHandlesBadAssignment.txt"); if (reloadHandlesBadAssignment_testVal1 == 1 && // TODO: Avoid discarding line after a macro invocation that's missing a semicolon // reloadHandlesBadAssignment_testVal2 == 200 && reloadHandlesBadAssignment_testVal3 == 3 && reloadHandlesBadAssignment_testVal4 == 4 && reloadHandlesBadAssignment_testVal5 == 5 && reloadHandlesBadAssignment_testVal6 == 6) return true; else return false; } bool reloadHandlesNewParams() { const HotConsts::HC_Atomic<int>& reloadHandlesNewParams_testVal1 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadHandlesNewParams.txt", "reloadHandlesNewParams_testVal1", "int") = 1; const HotConsts::HC_Atomic<int>& reloadHandlesNewParams_testVal2 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadHandlesNewParams.txt", "reloadHandlesNewParams_testVal2", "int") = 1; HotConsts::_reloadSrcFile(TESTFILEDIR "reloadHandlesNewParams.txt"); if (reloadHandlesNewParams_testVal1 == 1 && reloadHandlesNewParams_testVal2 == 200) return true; else return false; } bool reloadHandlesRedefinitions() { const HotConsts::HC_Atomic<int>& reloadHandlesRedefinitions_testVal1 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadHandlesRedefinitions.txt", "reloadHandlesRedefinitions_testVal1", "int") = 1; HotConsts::_reloadSrcFile(TESTFILEDIR "reloadHandlesRedefinitions.txt"); if (reloadHandlesRedefinitions_testVal1 == 100) return true; else return false; } bool reloadHandlesEOF_awaitingLParentheses() { const HotConsts::HC_Atomic<int>& reloadHandlesEOF_awaitingLParentheses_testVal1 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadHandlesEOF_awaitingLParentheses.txt", "reloadHandlesEOF_awaitingLParentheses_testVal1", "int") = 1; HotConsts::_reloadSrcFile(TESTFILEDIR "reloadHandlesEOF_awaitingLParentheses.txt"); if (reloadHandlesEOF_awaitingLParentheses_testVal1 == 1) return true; else return false; } bool reloadHandlesEOF_awaitingParam1() { const HotConsts::HC_Atomic<int>& reloadHandlesEOF_awaitingParam1_testVal1 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadHandlesEOF_awaitingParam1.txt", "reloadHandlesEOF_awaitingParam1_testVal1", "int") = 1; HotConsts::_reloadSrcFile(TESTFILEDIR "reloadHandlesEOF_awaitingParam1.txt"); if (reloadHandlesEOF_awaitingParam1_testVal1 == 1) return true; else return false; } bool reloadHandlesEOF_awaitingComma() { const HotConsts::HC_Atomic<int>& reloadHandlesEOF_awaitingComma_testVal1 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadHandlesEOF_awaitingComma.txt", "reloadHandlesEOF_awaitingComma_testVal1", "int") = 1; HotConsts::_reloadSrcFile(TESTFILEDIR "reloadHandlesEOF_awaitingComma.txt"); if (reloadHandlesEOF_awaitingComma_testVal1 == 1) return true; else return false; } bool reloadHandlesEOF_awaitingParam2() { const HotConsts::HC_Atomic<int>& reloadHandlesEOF_awaitingParam2_testVal1 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadHandlesEOF_awaitingParam2.txt", "reloadHandlesEOF_awaitingParam2_testVal1", "int") = 1; HotConsts::_reloadSrcFile(TESTFILEDIR "reloadHandlesEOF_awaitingParam2.txt"); if (reloadHandlesEOF_awaitingParam2_testVal1 == 1) return true; else return false; } bool reloadHandlesEOF_awaitingRParentheses() { const HotConsts::HC_Atomic<int>& reloadHandlesEOF_awaitingRParentheses_testVal1 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadHandlesEOF_awaitingRParentheses.txt", "reloadHandlesEOF_awaitingRParentheses_testVal1", "int") = 1; HotConsts::_reloadSrcFile(TESTFILEDIR "reloadHandlesEOF_awaitingRParentheses.txt"); if (reloadHandlesEOF_awaitingRParentheses_testVal1 == 1) return true; else return false; } bool reloadHandlesEOF_awaitingAssignmentOperator() { const HotConsts::HC_Atomic<int>& reloadHandlesEOF_awaitingAssignmentOperator_testVal1 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadHandlesEOF_awaitingAssignmentOperator.txt", "reloadHandlesEOF_awaitingAssignmentOperator_testVal1", "int") = 1; HotConsts::_reloadSrcFile(TESTFILEDIR "reloadHandlesEOF_awaitingAssignmentOperator.txt"); if (reloadHandlesEOF_awaitingAssignmentOperator_testVal1 == 1) return true; else return false; } bool reloadHandlesEOF_awaitingSemicolon() { const HotConsts::HC_Atomic<int>& reloadHandlesEOF_awaitingSemicolon_testVal1 = HotConsts::_registerHotConst<int>(TESTFILEDIR "reloadHandlesEOF_awaitingSemicolon.txt", "reloadHandlesEOF_awaitingSemicolon_testVal1", "int") = 1; HotConsts::_reloadSrcFile(TESTFILEDIR "reloadHandlesEOF_awaitingSemicolon.txt"); if (reloadHandlesEOF_awaitingSemicolon_testVal1 == 1) return true; else return false; } bool fileChangeTriggersReload() { std::ofstream srcFile(TESTFILEDIR "fileChangeTriggersReload.txt", std::ios_base::trunc); if (srcFile.is_open()) { // First, set the source file to a "previous" state. srcFile << "#include <HotConsts/HotConsts.h>\n\nHC(int, fileChangeTriggersReload_testVal1) = 1;\n"; srcFile.close(); // Simulate a macro invocation from the test file. // Hack: The path to the file in this test must be a full path to work correctly on macOS. std::string thisDirectory; #ifdef _WIN32 thisDirectory = "ReloadTests\\fileChangeTriggersReload.txt"; #else std::string thisfile(__FILE__); auto postSlashPos = thisfile.rfind("ReloadTests.cpp"); thisDirectory = thisfile.substr(0, postSlashPos) + "ReloadTests/fileChangeTriggersReload.txt"; #endif const HotConsts::HC_Atomic<int>& fileChangeTriggersReload_testVal1 = HotConsts::_registerHotConst<int>(thisDirectory.c_str(), "fileChangeTriggersReload_testVal1", "int") = 1; // After being registered, change the file to have a new value. srcFile.open(TESTFILEDIR "fileChangeTriggersReload.txt", std::ios_base::trunc); if (srcFile.is_open()) { srcFile << "#include <HotConsts/HotConsts.h>\n\nHC(int, fileChangeTriggersReload_testVal1) = 100;\n"; srcFile.close(); std::this_thread::sleep_for(std::chrono::milliseconds(200)); //macOS reload latency is set to 100ms // See if new value has been loaded. // Sleep is to ensure asynchronous calls have time to complete. if (fileChangeTriggersReload_testVal1 == 100) return true; else return false; } else { std::cout << "Error reopening ReloadTests/fileChangeTriggersReload.txt." << std::endl; return false; } } else { std::cout << "Error opening ReloadTests/fileChangeTriggersReload.txt." << std::endl; return false; } }
42.673828
130
0.67669
theOtherMichael
f92f2fbb8686648e600e9a5008d0e575efcd7079
1,387
hpp
C++
inc/main.hpp
davemoore22/libtcod-sdl-callback
de932121070e068a7161f8d0056b0b482d64ab27
[ "MIT" ]
1
2019-05-18T07:01:29.000Z
2019-05-18T07:01:29.000Z
inc/main.hpp
davemoore22/libtcod-sdl-callback
de932121070e068a7161f8d0056b0b482d64ab27
[ "MIT" ]
null
null
null
inc/main.hpp
davemoore22/libtcod-sdl-callback
de932121070e068a7161f8d0056b0b482d64ab27
[ "MIT" ]
null
null
null
// Copyright 2019 Dave Moore // // 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. #pragma once #include <cmath> #include <string> #include <iostream> #include <filesystem> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_ttf.h> #include "libtcod.h" auto CSTR(const std::string& string_to_convert) -> const char*; auto main(int argc, char* args[]) -> int;
44.741935
120
0.763518
davemoore22
f9311f1525714076d3cec73b1e488aa1f5c27363
183
hpp
C++
src/utz.hpp
zatarain/utz
fd7fd6b8ebc7076c8c380c1521cd317b5f49d571
[ "MIT" ]
1
2020-11-20T06:03:10.000Z
2020-11-20T06:03:10.000Z
src/utz.hpp
zatarain/utz
fd7fd6b8ebc7076c8c380c1521cd317b5f49d571
[ "MIT" ]
2
2020-04-11T16:49:15.000Z
2020-04-19T20:21:46.000Z
src/utz.hpp
zatarain/utz
fd7fd6b8ebc7076c8c380c1521cd317b5f49d571
[ "MIT" ]
null
null
null
#ifndef UTZ_HEADER #define UTZ_HEADER #include "utz/assertion.hpp" #include "utz/test.hpp" namespace is = utz::is; #ifndef expect using utz::expect; #endif using utz::skip; #endif
13.071429
28
0.737705
zatarain
f93bdbbf2da7b9879a95e24792af390ac5791178
2,879
cpp
C++
BigBaseV2/src/main.cpp
skript023/Jan-Stat-Editor
3ffb20454873e405b16b8df456379e0bb8973ec7
[ "MIT" ]
null
null
null
BigBaseV2/src/main.cpp
skript023/Jan-Stat-Editor
3ffb20454873e405b16b8df456379e0bb8973ec7
[ "MIT" ]
null
null
null
BigBaseV2/src/main.cpp
skript023/Jan-Stat-Editor
3ffb20454873e405b16b8df456379e0bb8973ec7
[ "MIT" ]
null
null
null
#include "common.hpp" #include "features.hpp" #include "fiber_pool.hpp" #include "gui.hpp" #include "logger.hpp" #include "hooking.hpp" #include "pointers.hpp" #include "renderer.hpp" #include "script_mgr.hpp" BOOL APIENTRY DllMain(HMODULE hmod, DWORD reason, PVOID) { using namespace big; if (reason == DLL_PROCESS_ATTACH) { DisableThreadLibraryCalls(hmod); g_hmodule = hmod; g_main_thread = CreateThread(nullptr, 0, [](PVOID) -> DWORD { while (!FindWindow(L"grcWindow", L"Grand Theft Auto V")) std::this_thread::sleep_for(1s); auto logger_instance = std::make_unique<logger>(); try { LOG(RAW_GREEN_TO_CONSOLE) << u8R"kek( _ _ _____ _ _ ______ _ _ _ | | | | / ____| | | | | ____| | (_) | | | __ _ _ __ ___ ___ ___ | | __ | (___ | |_ __ _| |_ | |__ __| |_| |_ ___ _ __ _ | |/ _` | '_ \ / __/ _ \ / _ \| |/ / \___ \| __/ _` | __| | __| / _` | | __/ _ \| '__| | |__| | (_| | | | | (_| (_) | (_) | < ____) | || (_| | |_ | |___| (_| | | || (_) | | \____/ \__,_|_| |_|\___\___/ \___/|_|\_\ |_____/ \__\__,_|\__| |______\__,_|_|\__\___/|_| )kek"; auto pointers_instance = std::make_unique<pointers>(); LOG(INFO) << "Pointers initialized."; auto renderer_instance = std::make_unique<renderer>(); LOG(INFO) << "Renderer initialized."; auto fiber_pool_instance = std::make_unique<fiber_pool>(10); LOG(INFO) << "Fiber pool initialized."; auto hooking_instance = std::make_unique<hooking>(); LOG(INFO) << "Hooking initialized."; g_settings.load(); LOG(INFO) << "Settings Loaded."; g_script_mgr.add_script(std::make_unique<script>(&features::script_func)); g_script_mgr.add_script(std::make_unique<script>(&gui::script_func)); LOG(INFO) << "Scripts registered."; g_hooking->enable(); LOG(INFO) << "Hooking enabled."; while (g_running) { std::this_thread::sleep_for(500ms); } g_hooking->disable(); LOG(INFO) << "Hooking disabled."; std::this_thread::sleep_for(1000ms); g_script_mgr.remove_all_scripts(); LOG(INFO) << "Scripts unregistered."; hooking_instance.reset(); LOG(INFO) << "Hooking uninitialized."; fiber_pool_instance.reset(); LOG(INFO) << "Fiber pool uninitialized."; renderer_instance.reset(); LOG(INFO) << "Renderer uninitialized."; pointers_instance.reset(); LOG(INFO) << "Pointers uninitialized."; } catch (std::exception const &ex) { LOG(WARNING) << ex.what(); MessageBoxA(nullptr, ex.what(), nullptr, MB_OK | MB_ICONEXCLAMATION); } LOG(INFO) << "Farewell!"; logger_instance.reset(); CloseHandle(g_main_thread); FreeLibraryAndExitThread(g_hmodule, 0); }, nullptr, 0, &g_main_thread_id); } return true; }
29.080808
93
0.59083
skript023
f93efcbfd89f765ff9275f22345d5e2e1c5be3ad
1,472
cpp
C++
src/util/Util.cpp
Estebanan/glSolarSystem
fd57ca572a039d57f7944cc03bced96159918dfa
[ "MIT" ]
3
2019-07-31T06:13:41.000Z
2021-04-04T15:32:40.000Z
src/util/Util.cpp
MarcelIwanicki/glSolarSystem
fd57ca572a039d57f7944cc03bced96159918dfa
[ "MIT" ]
null
null
null
src/util/Util.cpp
MarcelIwanicki/glSolarSystem
fd57ca572a039d57f7944cc03bced96159918dfa
[ "MIT" ]
null
null
null
#include "Util.h" #include <iostream> #include <fstream> std::string Util::readFile(const std::string &path) { std::fstream file; file.open(path); std::string result; std::string line; if(file.is_open()) while(file.good()) { getline(file, line); result.append(line + "\n"); } else std::cerr << "ERROR: Couldn't read file: " << path << std::endl; return result; } void Util::checkShaderError(GLuint shader, GLuint status, bool isProgram, const std::string &errorMessage) { GLint success; GLchar info[512]; if(isProgram) glGetProgramiv(shader, status, &success); else glGetShaderiv(shader, status, &success); if(!success) { if(isProgram) { glGetProgramInfoLog(shader, sizeof(info) / sizeof(*info), nullptr, info); std::cerr << errorMessage << " | " << info << std::endl; } else { glGetShaderInfoLog(shader, sizeof(info) / sizeof(*info), nullptr, info); std::cerr << errorMessage << " | " << info << std::endl; } } } const std::vector<std::string> Util::split(const std::string& s, const char& c) { std::string buff{""}; std::vector<std::string> v; for(auto n:s) { if(n != c) buff+=n; else if(n == c && buff != "") { v.push_back(buff); buff = ""; } } if(buff != "") v.push_back(buff); return v; }
23.365079
106
0.54144
Estebanan
f9406b19457f332f350757b0f27f91b15e5d08df
2,592
hpp
C++
include/effortless/statistic.hpp
foehnx/effortless
a90962782731e10827597c5102b2d24ba8183074
[ "MIT" ]
null
null
null
include/effortless/statistic.hpp
foehnx/effortless
a90962782731e10827597c5102b2d24ba8183074
[ "MIT" ]
1
2021-10-14T20:50:28.000Z
2021-11-09T18:37:32.000Z
include/effortless/statistic.hpp
foehnx/effortless
a90962782731e10827597c5102b2d24ba8183074
[ "MIT" ]
null
null
null
#pragma once #include <cmath> #include <iomanip> #include <iostream> #include <limits> #include <string> namespace effortless { using Scalar = double; class Statistic { public: Statistic(const std::string &name = "Statistic") : name_(name) {} Statistic(const Statistic &rhs) = default; Statistic &operator=(const Statistic &rhs) { n_ = rhs.n_; last_ = rhs.last_; min_ = rhs.min_; max_ = rhs.max_; sum_ = rhs.sum_; ssum_ = rhs.ssum_; return *this; } Scalar operator<<(const Scalar in) { if (!std::isfinite(in)) return std::numeric_limits<Scalar>::quiet_NaN(); ++n_; sum_ += in; ssum_ += in * in; last_ = in; min_ = std::min(in, min_); max_ = std::max(in, max_); return mean(); } Scalar add(const Scalar in) { return operator<<(in); } [[nodiscard]] Scalar operator()() const { return mean(); } [[nodiscard]] operator double() const { return (double)mean(); } [[nodiscard]] operator float() const { return (float)mean(); } [[nodiscard]] operator int() const { return n_; } [[nodiscard]] int count() const { return n_; } [[nodiscard]] Scalar last() const { return last_; } [[nodiscard]] Scalar mean() const { return sum_ / ((Scalar)n_); } [[nodiscard]] Scalar std() const { if (!n_) return 0.0; const Scalar m = mean(); return std::sqrt(ssum_ / n_ - m * m); } [[nodiscard]] Scalar min() const { return min_; } [[nodiscard]] Scalar max() const { return max_; } [[nodiscard]] Scalar sum() const { return sum_; } [[nodiscard]] const std::string &name() const { return name_; } void reset() { n_ = 0; sum_ = 0.0; ssum_ = 0.0; last_ = 0.0; min_ = std::numeric_limits<Scalar>::max(); max_ = std::numeric_limits<Scalar>::min(); } friend std::ostream &operator<<(std::ostream &os, const Statistic &s) { if (s.n_ < 1) os << s.name_ << "has no sample yet!" << std::endl; const std::streamsize prec = os.precision(); os.precision(3); os << std::left << std::setw(16) << s.name_ << "mean|std "; os << std::left << std::setw(5) << s.mean() << "|"; os << std::left << std::setw(5) << s.std() << " [min|max: "; os << std::left << std::setw(5) << s.min() << "|"; os << std::left << std::setw(5) << s.max() << "]" << std::endl; os.precision(prec); return os; } protected: const std::string name_; int n_{0}; Scalar sum_{0.0}; Scalar ssum_{0.0}; Scalar last_{0.0}; Scalar min_{std::numeric_limits<Scalar>::max()}; Scalar max_{std::numeric_limits<Scalar>::min()}; }; } // namespace effortless
26.721649
76
0.587191
foehnx
f940b99ca1da797cc4b39a8a4bb684fa59c7b119
21,967
cc
C++
GenFit/GBL/src/GblFitter.cc
ggfdsa10/KEBI_AT-TPC
40e00fcd10d3306b93fff93be5fb0988f87715a7
[ "MIT" ]
null
null
null
GenFit/GBL/src/GblFitter.cc
ggfdsa10/KEBI_AT-TPC
40e00fcd10d3306b93fff93be5fb0988f87715a7
[ "MIT" ]
null
null
null
GenFit/GBL/src/GblFitter.cc
ggfdsa10/KEBI_AT-TPC
40e00fcd10d3306b93fff93be5fb0988f87715a7
[ "MIT" ]
null
null
null
//-*-mode: C++; c-basic-offset: 2; -*- /* Copyright 2013-2014 * Authors: Sergey Yashchenko and Tadeas Bilka * * This is an interface to General Broken Lines * * Version: 6 -------------------------------------------------------------- * - complete rewrite to GblFitter using GblFitterInfo and GblFitStatus * - mathematics should be the same except for additional iterations * (not possible before) * - track is populated with scatterers + additional points with * scatterers and no measurement (optional) * - final track contains GblFitStatus and fitted states from GBL prediction * - 1D/2D hits supported (pixel, single strip, combined strips(2D), wire) * - At point: Only the very first raw measurement is used and from * that, constructed MeasurementOnPlane with heighest weight * Version: 5 -------------------------------------------------------------- * - several bug-fixes: * - Scatterers at bad points * - Jacobians at a point before they should be (code reorganized) * - Change of sign of residuals * Version: 4 -------------------------------------------------------------- * Fixed calculation of equvivalent scatterers (solution by C. Kleinwort) * Now a scatterer is inserted at each measurement (except last) and * between each two measurements. * TrueHits/Clusters. Ghost (1D) hits ignored. With or * without magnetic field. * Version: 3 -------------------------------------------------------------- * This version now supports both TrueHits and Clusters for VXD. * It can be used for arbitrary material distribution between * measurements. Moments of scattering distribution are computed * and translated into two equivalent thin GBL scatterers placed * at computed positions between measurement points. * Version: 2 ... never published ----------------------------------------- * Scatterer at each boundary (tooo many scatterers). TrueHits/Clusters. * Without global der.&MP2 output. * Version: 1 -------------------------------------------------------------- * Scatterers at measurement planes. TrueHits * Version: 0 -------------------------------------------------------------- * Without scatterers. Genfit 1. * ------------------------------------------------------------------------- * * This file is part of GENFIT. * * GENFIT 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 3 of the License, or * (at your option) any later version. * * GENFIT 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 GENFIT. If not, see <http://www.gnu.org/licenses/>. */ #include "GblFitter.h" #include "../include/GblFitStatus.h" #include "GblFitterInfo.h" #include "GblTrajectory.h" #include "GblPoint.h" #include "ICalibrationParametersDerivatives.h" #include "Track.h" #include <TFile.h> #include <TH1F.h> #include <TTree.h> #include <string> #include <list> #include <FieldManager.h> #include <HMatrixU.h> #include <HMatrixV.h> #include <Math/SMatrix.h> #include <TMatrixD.h> #include <TVectorDfwd.h> #include <TMatrixT.h> #include <TVector3.h> //#define DEBUG using namespace gbl; using namespace std; using namespace genfit; /** * Destructor */ GblFitter::~GblFitter() { if (m_segmentController) { delete m_segmentController; m_segmentController = nullptr; } } void GblFitter::setTrackSegmentController(GblTrackSegmentController* controler) { if (m_segmentController) { delete m_segmentController; m_segmentController = nullptr; } m_segmentController = controler; } void GblFitter::processTrackWithRep(Track* trk, const AbsTrackRep* rep, bool resortHits) { cleanGblInfo(trk, rep); if (resortHits) sortHits(trk, rep); // This flag enables/disables fitting of q/p parameter in GBL // It is switched off automatically if no B-field at (0,0,0) is detected. bool fitQoverP = true; //TODO: Use clever way to determine zero B-field double Bfield = genfit::FieldManager::getInstance()->getFieldVal(TVector3(0., 0., 0.)).Mag(); if (!(Bfield > 1.e-16)) fitQoverP = false; // degrees of freedom after fit int Ndf = 0; // Chi2 after fit double Chi2 = 0.; //FIXME: d-w's not used so far... double lostWeight = 0.; // Preparation of points (+add reference states) for GBL fit // ----------------------------------------------------------------- genfit::GblFitStatus* gblfs = new genfit::GblFitStatus(); trk->setFitStatus(gblfs, rep); gblfs->setCurvature(fitQoverP); // // Propagate reference seed, create scattering points, calc Jacobians // and store everything in fitter infos. (ready to collect points and fit) // // gblfs->setTrackLen( // constructGblInfo(trk, rep) // ); // // gblfs->setIsFittedWithReferenceTrack(true); gblfs->setNumIterations(0); //default value, still valid, No GBL iteration if (m_externalIterations < 1) return; // ----------------------------------------------------------------- // cppcheck-suppress unreadVariable unsigned int nFailed = 0; // cppcheck-suppress unreadVariable int fitRes = 0; std::vector<std::string> gblIterations; gblIterations.push_back(m_gblInternalIterations); // Iterations and updates of fitter infos and fit status // ------------------------------------------------------------------- for (unsigned int iIter = 0; iIter < m_externalIterations; iIter++) { // GBL refit (1st of reference, then refit of GBL trajectory itself) int nscat = 0, nmeas = 0, ndummy = 0; std::vector<gbl::GblPoint> points = collectGblPoints(trk, rep); for(unsigned int ip = 0;ip<points.size(); ip++) { GblPoint & p = points.at(ip); if (p.hasScatterer()) nscat++; if (p.hasMeasurement()) nmeas++; if(!p.hasMeasurement()&&!p.hasScatterer()) ndummy++; } gbl::GblTrajectory traj(points, gblfs->hasCurvature()); fitRes = traj.fit(Chi2, Ndf, lostWeight, (iIter == m_externalIterations - 1) ? m_gblInternalIterations : ""); // Update fit results in fitterinfos updateGblInfo(traj, trk, rep); // This repropagates to get new Jacobians, // if planes changed, predictions are extrapolated to new planes if (m_recalcJacobians > iIter) { GblFitterInfo* prevFitterInfo = 0; GblFitterInfo* currFitterInfo = 0; for (unsigned int ip = 0; ip < trk->getNumPoints(); ip++) { if (trk->getPoint(ip)->hasFitterInfo(rep) && (currFitterInfo = dynamic_cast<GblFitterInfo*>(trk->getPoint(ip)->getFitterInfo(rep)))) { currFitterInfo->recalculateJacobian(prevFitterInfo); prevFitterInfo = currFitterInfo; } } } gblfs->setIsFitted(true); gblfs->setIsFitConvergedPartially(fitRes == 0); nFailed = trk->getNumPointsWithMeasurement() - nmeas; gblfs->setNFailedPoints(nFailed); gblfs->setIsFitConvergedFully(fitRes == 0 && nFailed == 0); gblfs->setNumIterations(iIter + 1); gblfs->setChi2(Chi2); gblfs->setNdf(Ndf); gblfs->setCharge(trk->getFittedState().getCharge()); #ifdef DEBUG int npoints_meas = trk->getNumPointsWithMeasurement(); int npoints_all = trk->getNumPoints(); cout << "-------------------------------------------------------" << endl; cout << " GBL processed genfit::Track " << endl; cout << "-------------------------------------------------------" << endl; cout << " # Track Points : " << npoints_all << endl; cout << " # Meas. Points : " << npoints_meas << endl; cout << " # GBL points all : " << traj.getNumPoints(); if (ndummy) cout << " (" << ndummy << " dummy) "; cout << endl; cout << " # GBL points meas : " << nmeas << endl; cout << " # GBL points scat : " << nscat << endl; cout << "-------------- GBL Fit Results ----------- Iteration " << iIter+1 << " " << ((iIter < gblIterations.size()) ? gblIterations[iIter] : "") << endl; cout << " Fit q/p parameter : " << (gblfs->hasCurvature() ? ("True") : ("False")) << endl; cout << " Valid trajectory : " << ((traj.isValid()) ? ("True") : ("False")) << endl; cout << " Fit result : " << fitRes << " (0 for success)" << endl; cout << " GBL track NDF : " << Ndf << " (-1 for failure)" << endl; cout << " GBL track Chi2 : " << Chi2 << endl; cout << " GBL track P-value : " << TMath::Prob(Chi2, Ndf) << endl; cout << "-------------------------------------------------------" << endl; #endif } // ------------------------------------------------------------------- } void GblFitter::cleanGblInfo(Track* trk, const AbsTrackRep* rep) const { for (int ip = trk->getNumPoints() - 1; ip >=0; ip--) { trk->getPoint(ip)->setScatterer(nullptr); trk->getPoint(ip)->deleteFitterInfo(rep); //TODO if (!trk->getPoint(ip)->hasRawMeasurements()) trk->deletePoint(ip); } } void GblFitter::sortHits(Track* trk, const AbsTrackRep* rep) const { // All measurement points in ref. track int npoints_meas = trk->getNumPointsWithMeasurement(); // Prepare state for extrapolation of track seed StateOnPlane reference(rep); rep->setTime(reference, trk->getTimeSeed()); rep->setPosMom(reference, trk->getStateSeed()); // Take the state to first plane SharedPlanePtr firstPlane(trk->getPointWithMeasurement(0)->getRawMeasurement(0)->constructPlane(reference)); reference.extrapolateToPlane(firstPlane); //1st point is at arc-len=0 double arcLenPos = 0; // Loop only between meas. points for (int ipoint_meas = 0; ipoint_meas < npoints_meas - 1; ipoint_meas++) { // current measurement point TrackPoint* point_meas = trk->getPointWithMeasurement(ipoint_meas); // Current detector plane SharedPlanePtr plane = point_meas->getRawMeasurement(0)->constructPlane(reference); // Get the next plane SharedPlanePtr nextPlane(trk->getPointWithMeasurement(ipoint_meas + 1)->getRawMeasurement(0)->constructPlane(reference)); point_meas->setSortingParameter(arcLenPos); arcLenPos += reference.extrapolateToPlane(nextPlane); } // end of loop over track points with measurement trk->getPointWithMeasurement(npoints_meas - 1)->setSortingParameter(arcLenPos); trk->sort(); } std::vector<gbl::GblPoint> GblFitter::collectGblPoints(genfit::Track* trk, const genfit::AbsTrackRep* rep) { //TODO store collected points in in fit status? need streamer for GblPoint (or something like that) std::vector<gbl::GblPoint> thePoints; thePoints.clear(); // Collect points from track and fitterInfo(rep) for (unsigned int ip = 0; ip < trk->getNumPoints(); ip++) { GblFitterInfo * gblfi = dynamic_cast<GblFitterInfo*>(trk->getPoint(ip)->getFitterInfo(rep)); if (!gblfi) continue; thePoints.push_back(gblfi->constructGblPoint()); } return thePoints; } void GblFitter::updateGblInfo(gbl::GblTrajectory& traj, genfit::Track* trk, const genfit::AbsTrackRep* rep) { //FIXME if (!traj.isValid()) return; // Update points in track and fitterInfo(rep) int igblfi = -1; for (unsigned int ip = 0; ip < trk->getNumPoints(); ip++) { GblFitterInfo * gblfi = dynamic_cast<GblFitterInfo*>(trk->getPoint(ip)->getFitterInfo(rep)); if (!gblfi) continue; igblfi++; // The point will calculate its position on the track // (counting fitter infos) which hopefully gblfi->updateFitResults(traj); // This is agains logic. User can do this if he wants and it is recommended usually // so that following fit could reuse the updated seed //if (igblfi == 0) { // trk->setStateSeed( gblfi->getFittedState(true).getPos(), gblfi->getFittedState(true).getMom() ); // trk->setCovSeed( gblfi->getFittedState(true).get6DCov() ); //} } } void GblFitter::getScattererFromMatList(double& length, double& theta, double& s, double& ds, const double p, const double mass, const double charge, const std::vector<genfit::MatStep>& steps) const { theta = 0.; s = 0.; ds = 0.; length = 0; if (steps.empty()) return; // sum of step lengths double len = 0.; // normalization double sumxx = 0.; // first moment (non-normalized) double sumx2x2 = 0.; // (part of) second moment / variance (non-normalized) double sumx3x3 = 0.; // cppcheck-suppress unreadVariable double xmin = 0.; double xmax = 0.; for (unsigned int i = 0; i < steps.size(); i++) { const MatStep step = steps.at(i); // inverse of material radiation length ... (in 1/cm) ... "density of scattering" double rho = 1. / step.material_.radiationLength; len += fabs(step.stepSize_); xmin = xmax; xmax = xmin + fabs(step.stepSize_); // Compute integrals // integral of rho(x) sumxx += rho * (xmax - xmin); // integral of x*rho(x) sumx2x2 += rho * (xmax * xmax - xmin * xmin) / 2.; // integral of x*x*rho(x) sumx3x3 += rho * (xmax * xmax * xmax - xmin * xmin * xmin) / 3.; } // This ensures PDG formula still gives positive results (but sumxx should be > 1e-4 for it to hold) if (sumxx < 1.0e-10) return; // Calculate theta from total sum of radiation length // instead of summimg squares of individual deflection angle variances // PDG formula: double beta = p / sqrt(p * p + mass * mass); theta = (0.0136 / p / beta) * fabs(charge) * sqrt(sumxx) * (1. + 0.038 * log(sumxx)); //theta = (0.015 / p / beta) * fabs(charge) * sqrt(sumxx); // track length length = len; // Normalization factor double N = 1. / sumxx; // First moment s = N * sumx2x2; // Square of second moment (variance) // integral of (x - s)*(x - s)*rho(x) double ds_2 = N * (sumx3x3 - 2. * sumx2x2 * s + sumxx * s * s); ds = sqrt(ds_2); #ifdef DEBUG ////std::cout << "Thick scatterer parameters (dtheta, <s>, ds): " << "(" << theta << ", " << s << ", " << ds << ")" << endl; #endif } double GblFitter::constructGblInfo(Track* trk, const AbsTrackRep* rep) { // All measurement points in ref. track int npoints_meas = trk->getNumPointsWithMeasurement(); // Dimesion of representation/state int dim = rep->getDim(); // Jacobian for point with measurement = how to propagate from previous point (scat/meas) TMatrixD jacPointToPoint(dim, dim); jacPointToPoint.UnitMatrix(); // Prepare state for extrapolation of track seed // Take the state to first plane StateOnPlane reference(rep); rep->setTime(reference, trk->getTimeSeed()); rep->setPosMom(reference, trk->getStateSeed()); SharedPlanePtr firstPlane(trk->getPointWithMeasurement(0)->getRawMeasurement(0)->constructPlane(reference)); reference.extrapolateToPlane(firstPlane); double sumTrackLen = 0; // NOT used but useful TMatrixDSym noise; TVectorD deltaState; // Loop only between meas. points for (int ipoint_meas = 0; ipoint_meas < npoints_meas; ipoint_meas++) { // current measurement point TrackPoint* point_meas = trk->getPointWithMeasurement(ipoint_meas); // Current detector plane SharedPlanePtr plane = point_meas->getRawMeasurement(0)->constructPlane(reference); // track direction at plane (in global coords) TVector3 trackDir = rep->getDir(reference); // track momentum direction vector at plane (in global coords) double trackMomMag = rep->getMomMag(reference); // charge of particle double particleCharge = rep->getCharge(reference); // mass of particle double particleMass = rep->getMass(reference); // Parameters of a thick scatterer between measurements double trackLen = 0., scatTheta = 0., scatSMean = 0., scatDeltaS = 0.; // Parameters of two equivalent thin scatterers double theta1 = 0., theta2 = 0., s1 = 0., s2 = 0.; // jacobian from s1=0 to s2 TMatrixD jacMeas2Scat(dim, dim); jacMeas2Scat.UnitMatrix(); // Stop here if we are at last point (do not add scatterers to last point), // just the fitter info if (ipoint_meas >= npoints_meas - 1) { // Construction last measurement (no scatterer) // -------------------------------------------- // Just add the fitter info of last plane GblFitterInfo* gblfimeas(new GblFitterInfo(point_meas, rep, reference)); gblfimeas->setJacobian(jacPointToPoint); point_meas->setFitterInfo(gblfimeas); // -------------------------------------------- break; } // Extrapolate to next measurement to get material distribution // Use a temp copy of the StateOnPlane to propage between measurements StateOnPlane refCopy(reference); // Get the next plane SharedPlanePtr nextPlane(trk->getPointWithMeasurement(ipoint_meas + 1)->getRawMeasurement(0)->constructPlane(reference)); // Extrapolation for multiple scattering calculation // Extrap to point + 1, do NOT stop at boundary TVector3 segmentEntry = refCopy.getPos(); rep->extrapolateToPlane(refCopy, nextPlane, false, false); TVector3 segmentExit = refCopy.getPos(); getScattererFromMatList(trackLen, scatTheta, scatSMean, scatDeltaS, trackMomMag, particleMass, particleCharge, rep->getSteps()); // Now calculate positions and scattering variance for equivalent scatterers // (Solution from Claus Kleinwort (DESY)) s1 = 0.; s2 = scatSMean + scatDeltaS * scatDeltaS / (scatSMean - s1); theta1 = sqrt(scatTheta * scatTheta * scatDeltaS * scatDeltaS / (scatDeltaS * scatDeltaS + (scatSMean - s1) * (scatSMean - s1))); theta2 = sqrt(scatTheta * scatTheta * (scatSMean - s1) * (scatSMean - s1) / (scatDeltaS * scatDeltaS + (scatSMean - s1) * (scatSMean - s1))); // Call segment controller to set MS options: if (m_segmentController) m_segmentController->controlTrackSegment(segmentEntry, segmentExit, scatTheta, this); // Scattering options: OFF / THIN / THICK if (m_enableScatterers && !m_enableIntermediateScatterer) { theta1 = scatTheta; theta2 = 0; } else if (!m_enableScatterers) { theta1 = 0.; theta2 = 0.; } // Construction of measurement (with scatterer) // -------------------------------------------- if (theta1 > scatEpsilon) point_meas->setScatterer(new ThinScatterer(plane, Material(theta1, 0., 0., 0., 0.))); GblFitterInfo* gblfimeas(new GblFitterInfo(point_meas, rep, reference)); gblfimeas->setJacobian(jacPointToPoint); point_meas->setFitterInfo(gblfimeas); // -------------------------------------------- // If not last measurement, extrapolate and get jacobians for scattering points between this and next measurement if (theta2 > scatEpsilon) { // First scatterer has been placed at current measurement point (see above) // theta2 > 0 ... we want second scatterer: // Extrapolate to s2 (we have s1 = 0) rep->extrapolateBy(reference, s2, false, true); rep->getForwardJacobianAndNoise(jacMeas2Scat, noise, deltaState); // Construction of intermediate scatterer // -------------------------------------- TrackPoint* scattp = new TrackPoint(trk); scattp->setSortingParameter(point_meas->getSortingParameter() + s2); scattp->setScatterer(new ThinScatterer(reference.getPlane(), Material(theta2, 0., 0., 0., 0.))); // Add point to track before next point int pointIndex = 0; //TODO Deduce this rather than looping over all points for (unsigned int itp = 0; itp < trk->getNumPoints(); itp++) { if (trk->getPoint(itp) == point_meas) { pointIndex = itp; break; } } trk->insertPoint(scattp, pointIndex + 1); // Create and store fitter info GblFitterInfo * gblfiscat(new GblFitterInfo(scattp, rep, reference)); gblfiscat->setJacobian(jacMeas2Scat); scattp->setFitterInfo(gblfiscat); // --------------------------------------- // Finish extrapolation to next measurement double nextStep = rep->extrapolateToPlane(reference, nextPlane, false, true); rep->getForwardJacobianAndNoise(jacPointToPoint, noise, deltaState); if (0. > nextStep) { cout << " ERROR: The extrapolation to measurement point " << (ipoint_meas + 2) << " stepped back by " << nextStep << "cm !!! Track will be cut before this point." << endl; // stop trajectory construction here break; } } else { // No scattering: extrapolate whole distance between measurements double nextStep = rep->extrapolateToPlane(reference, nextPlane, false, true); rep->getForwardJacobianAndNoise(jacPointToPoint, noise, deltaState); if (0. > nextStep) { cout << " ERROR: The extrapolation to measurement point " << (ipoint_meas + 2) << " stepped back by " << nextStep << "cm !!! Track will be cut before this point." << endl; // stop trajectory construction here break; } } // Track length up to next point sumTrackLen += trackLen; } // end of loop over track points with measurement return sumTrackLen; }
40.52952
179
0.615196
ggfdsa10
f946caad09e2b632c9e4fec7e7a2f293b609661b
2,845
cpp
C++
zimlib/test/header.cpp
zjzdy/Offline-small-search
8bc7382b3f55184c8d179a2bf6e1e90730d6a09c
[ "ICU" ]
10
2016-05-10T14:48:44.000Z
2021-06-16T11:49:55.000Z
zimlib/test/header.cpp
zjzdy/Offline-small-search
8bc7382b3f55184c8d179a2bf6e1e90730d6a09c
[ "ICU" ]
null
null
null
zimlib/test/header.cpp
zjzdy/Offline-small-search
8bc7382b3f55184c8d179a2bf6e1e90730d6a09c
[ "ICU" ]
2
2016-11-09T06:56:29.000Z
2019-11-22T14:34:27.000Z
/* * Copyright (C) 2009 Tommi Maekitalo * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * is provided AS IS, WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and * NON-INFRINGEMENT. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <iostream> #include <sstream> #include <zim/fileheader.h> #include <cxxtools/unit/testsuite.h> #include <cxxtools/unit/registertest.h> class FileheaderTest : public cxxtools::unit::TestSuite { public: FileheaderTest() : cxxtools::unit::TestSuite("zim::FileheaderTest") { registerMethod("ReadWriteHeader", *this, &FileheaderTest::ReadWriteHeader); } void ReadWriteHeader() { zim::Fileheader header; header.setUuid("1234567890abcdef"); header.setArticleCount(4711); header.setUrlPtrPos(12345); header.setTitleIdxPos(23456); header.setClusterCount(14); header.setClusterPtrPos(45678); header.setMainPage(11); header.setLayoutPage(13); CXXTOOLS_UNIT_ASSERT_EQUALS(header.getUuid(), "1234567890abcdef"); CXXTOOLS_UNIT_ASSERT_EQUALS(header.getArticleCount(), 4711); CXXTOOLS_UNIT_ASSERT_EQUALS(header.getUrlPtrPos(), 12345); CXXTOOLS_UNIT_ASSERT_EQUALS(header.getTitleIdxPos(), 23456); CXXTOOLS_UNIT_ASSERT_EQUALS(header.getClusterCount(), 14); CXXTOOLS_UNIT_ASSERT_EQUALS(header.getClusterPtrPos(), 45678); CXXTOOLS_UNIT_ASSERT_EQUALS(header.getMainPage(), 11); CXXTOOLS_UNIT_ASSERT_EQUALS(header.getLayoutPage(), 13); std::stringstream s; s << header; zim::Fileheader header2; s >> header2; CXXTOOLS_UNIT_ASSERT_EQUALS(s.tellg(), s.tellp()); CXXTOOLS_UNIT_ASSERT_EQUALS(header2.getUuid(), "1234567890abcdef"); CXXTOOLS_UNIT_ASSERT_EQUALS(header2.getArticleCount(), 4711); CXXTOOLS_UNIT_ASSERT_EQUALS(header2.getUrlPtrPos(), 12345); CXXTOOLS_UNIT_ASSERT_EQUALS(header2.getTitleIdxPos(), 23456); CXXTOOLS_UNIT_ASSERT_EQUALS(header2.getClusterCount(), 14); CXXTOOLS_UNIT_ASSERT_EQUALS(header2.getClusterPtrPos(), 45678); CXXTOOLS_UNIT_ASSERT_EQUALS(header2.getMainPage(), 11); CXXTOOLS_UNIT_ASSERT_EQUALS(header2.getLayoutPage(), 13); } }; cxxtools::unit::RegisterTest<FileheaderTest> register_FileheaderTest;
36.012658
81
0.730756
zjzdy
f9538e809f3293b4f3d239787bb9b6e1a7206b99
5,462
ipp
C++
src/spacetime/basis.ipp
rvanvenetie/spacetime
b516419be2a59115d9b2d853aeea9fcd4f125c94
[ "MIT" ]
null
null
null
src/spacetime/basis.ipp
rvanvenetie/spacetime
b516419be2a59115d9b2d853aeea9fcd4f125c94
[ "MIT" ]
null
null
null
src/spacetime/basis.ipp
rvanvenetie/spacetime
b516419be2a59115d9b2d853aeea9fcd4f125c94
[ "MIT" ]
null
null
null
#pragma once #include <boost/core/demangle.hpp> #include <iomanip> #include <vector> #include "basis.hpp" namespace spacetime { template <class DblTreeIn, class DblTreeOut> auto GenerateSigma(const DblTreeIn &Lambda_in, const DblTreeOut &Lambda_out) { using OutNodeVector = std::vector<typename DblTreeOut::T0 *>; for (const auto &psi_out : Lambda_out.Project_0()->Bfs()) for (auto elem : psi_out->node()->support()) { if (!elem->has_data()) elem->set_data(new OutNodeVector()); elem->template data<OutNodeVector>()->push_back(psi_out->node()); } auto Sigma = std::make_shared<datastructures::DoubleTreeVector< typename DblTreeIn::T0, typename DblTreeOut::T1>>( std::get<0>(Lambda_in.root()->nodes()), std::get<1>(Lambda_out.root()->nodes())); Sigma->Project_0()->Union(Lambda_in.Project_0()); Sigma->Project_1()->Union(Lambda_out.Project_1()); OutNodeVector PI; for (const auto &psi_in_labda_0 : Sigma->Project_0()->Bfs()) { // NOTE: The code below is sigma as described in followup3.pdf. We chose // to enlarge sigma in order to create a `cheap` transpose of a spacetime // bilinear form. To do this, we must add the `diagonal` to Sigma. // std::vector<Time::Element1D *> children; // children.reserve(psi_in_labda_0->node()->support().size() * // DblTreeIn::T0::N_children); // for (auto elem : psi_in_labda_0->node()->support()) // for (auto child : elem->children()) children.push_back(child); // std::sort(children.begin(), children.end()); // auto last = std::unique(children.begin(), children.end()); // children.erase(last, children.end()); PI.clear(); for (auto child : psi_in_labda_0->node()->support()) { if (!child->has_data()) continue; PI.insert(PI.end(), child->template data<OutNodeVector>()->begin(), child->template data<OutNodeVector>()->end()); } // Remove duplicates from PI. std::sort(PI.begin(), PI.end()); PI.erase(std::unique(PI.begin(), PI.end()), PI.end()); for (auto mu : PI) psi_in_labda_0->FrozenOtherAxis()->Union(Lambda_out.Fiber_1(mu)); } for (const auto &psi_out : Lambda_out.Project_0()->Bfs()) for (auto elem : psi_out->node()->support()) { if (!elem->has_data()) continue; auto data = elem->template data<OutNodeVector>(); elem->reset_data(); delete data; } Sigma->ComputeFibers(); #ifdef VERBOSE std::cerr << std::left; std::cerr << "GenerateSigma(" << boost::core::demangle(typeid(DblTreeIn).name()) << ", " << boost::core::demangle(typeid(DblTreeIn).name()) << std::endl; std::cerr << " Lambda_in: #bfs = " << std::setw(10) << Lambda_in.Bfs().size() << "#container = " << Lambda_in.container().size() << std::endl; std::cerr << " Lambda_out: #bfs = " << std::setw(10) << Lambda_out.Bfs().size() << "#container = " << Lambda_out.container().size() << std::endl; std::cerr << " Sigma: #bfs = " << std::setw(10) << Sigma->Bfs().size() << "#container = " << Sigma->container().size() << std::endl; std::cerr << std::right; #endif return Sigma; } template <class DblTreeIn, class DblTreeOut> auto GenerateTheta(const DblTreeIn &Lambda_in, const DblTreeOut &Lambda_out) { return GenerateSigma(Lambda_out, Lambda_in); // auto Theta = std::make_shared<datastructures::DoubleTreeVector< // typename DblTreeOut::T0, typename DblTreeIn::T1>>( // std::get<0>(Lambda_out.root()->nodes()), // std::get<1>(Lambda_in.root()->nodes())); // Theta->Project_0()->Union(Lambda_out.Project_0()); // Theta->Project_1()->Union(Lambda_in.Project_1()); // // for (const auto &psi_in_labda_1 : Theta->Project_1()->Bfs()) { // auto fiber_labda_0 = Lambda_in.Fiber_0(psi_in_labda_1->node()); // auto fiber_labda_0_nodes = fiber_labda_0->Bfs(); // for (const auto &psi_in_labda_0 : fiber_labda_0_nodes) // for (auto elem : psi_in_labda_0->node()->support()) // elem->set_marked(true); // // psi_in_labda_1->FrozenOtherAxis()->Union( // Lambda_out.Project_0(), [](const auto &psi_out_labda_0) { // for (auto elem : psi_out_labda_0->node()->support()) // if (elem->marked()) return true; // return false; // }); // // for (const auto &psi_in_labda_0 : fiber_labda_0_nodes) // for (auto elem : psi_in_labda_0->node()->support()) // elem->set_marked(false); // } // Theta->ComputeFibers(); // //#ifdef VERBOSE // std::cerr << std::left; // std::cerr << "GenerateTheta(" // << boost::core::demangle(typeid(DblTreeIn).name()) << ", " // << boost::core::demangle(typeid(DblTreeIn).name()) << std::endl; // std::cerr << " Lambda_in: #bfs = " << std::setw(10) // << Lambda_in.Bfs().size() // << "#container = " << Lambda_in.container().size() << std::endl; // std::cerr << " Lambda_out: #bfs = " << std::setw(10) // << Lambda_out.Bfs().size() // << "#container = " << Lambda_out.container().size() << // std::endl; // std::cerr << " Theta: #bfs = " << std::setw(10) << Theta->Bfs().size() // << "#container = " << Theta->container().size() << std::endl; // std::cerr << std::right; //#endif // return Theta; } } // namespace spacetime
41.067669
80
0.592091
rvanvenetie
f95b0c54c790692aee64c65d7174c926a6bdea08
15,245
cpp
C++
network/libserver/ioclient.cpp
dariadb/dariadb
1edf637122752ba21c582675e2a9183fff91fa50
[ "Apache-2.0" ]
null
null
null
network/libserver/ioclient.cpp
dariadb/dariadb
1edf637122752ba21c582675e2a9183fff91fa50
[ "Apache-2.0" ]
null
null
null
network/libserver/ioclient.cpp
dariadb/dariadb
1edf637122752ba21c582675e2a9183fff91fa50
[ "Apache-2.0" ]
null
null
null
#include <libdariadb/meas.h> #include <libdariadb/timeutil.h> #include <libdariadb/utils/exception.h> #include <libserver/ioclient.h> #include <cassert> using namespace std::placeholders; using namespace boost::asio; using namespace dariadb; using namespace dariadb::net; struct SubscribeCallback : public storage::IReaderClb { utils::async::Locker _locker; IOClient *_parent; QueryNumber _query_num; SubscribeCallback(IOClient *parent, QueryNumber query_num) { _parent = parent; _query_num = query_num; } ~SubscribeCallback() {} void call(const Meas &m) override { send_buffer(m); } void is_end() override {} void send_buffer(const Meas &m) { auto nd = _parent->env->nd_pool->construct(DATA_KINDS::APPEND); nd->size = sizeof(QueryAppend_header); auto hdr = reinterpret_cast<QueryAppend_header *>(&nd->data); hdr->id = _query_num; size_t space_left = 0; QueryAppend_header::make_query(hdr, &m, size_t(1), 0, &space_left); auto size_to_write = NetData::MAX_MESSAGE_SIZE - MARKER_SIZE - space_left; nd->size = static_cast<NetData::MessageSize>(size_to_write); _parent->_async_connection->send(nd); } }; IOClient::ClientDataReader::ClientDataReader(IOClient *parent, QueryNumber query_num) { _parent = parent; pos = 0; _query_num = query_num; assert(_query_num != 0); } void IOClient::ClientDataReader::call(const Meas &m) { std::lock_guard<utils::async::Locker> lg(_locker); if (pos == BUFFER_LENGTH) { send_buffer(); pos = 0; } _buffer[pos++] = m; } void IOClient::ClientDataReader::is_end() { IReaderClb::is_end(); send_buffer(); auto nd = _parent->env->nd_pool->construct(DATA_KINDS::APPEND); nd->size = sizeof(QueryAppend_header); auto hdr = reinterpret_cast<QueryAppend_header *>(&nd->data); hdr->id = _query_num; hdr->count = 0; logger("server: #", _parent->_async_connection->id(), " end of #", hdr->id); _parent->_async_connection->send(nd); this->_parent->readerRemove(this->_query_num); } void IOClient::ClientDataReader::send_buffer() { if (pos == 0) { return; } size_t writed = 0; while (writed != pos) { auto nd = _parent->env->nd_pool->construct(DATA_KINDS::APPEND); nd->size = sizeof(QueryAppend_header); auto hdr = reinterpret_cast<QueryAppend_header *>(&nd->data); hdr->id = _query_num; size_t space_left = 0; QueryAppend_header::make_query(hdr, _buffer.data(), pos, writed, &space_left); logger_info("server: pack count: ", hdr->count); auto size_to_write = NetData::MAX_MESSAGE_SIZE - MARKER_SIZE - space_left; nd->size = static_cast<NetData::MessageSize>(size_to_write); writed += hdr->count; logger("server: #", _parent->_async_connection->id(), " send to client result of #", hdr->id, " count ", hdr->count); _parent->_async_connection->send(nd); } } IOClient::ClientDataReader::~ClientDataReader() {} IOClient::IOClient(int _id, socket_ptr &_sock, IOClient::Environment *_env) { subscribe_reader = nullptr; pings_missed = 0; state = CLIENT_STATE::CONNECT; sock = _sock; env = _env; _last_query_time = dariadb::timeutil::current_time(); AsyncConnection::onDataRecvHandler on_d = [this](const NetData_ptr &d, bool &cancel, bool &dont_free_memory) { onDataRecv(d, cancel, dont_free_memory); }; AsyncConnection::onNetworkErrorHandler on_n = [this](const boost::system::error_code &err) { onNetworkError(err); }; _async_connection = std::shared_ptr<AsyncConnection>{new AsyncConnection(_env->nd_pool, on_d, on_n)}; _async_connection->set_id(_id); } IOClient::~IOClient() { if (_async_connection != nullptr) { _async_connection->full_stop(); } for (auto kv : _readers) { logger_info("server: stop reader #", kv.first); kv.second.first->cancel(); kv.second.first->wait(); this->readerRemove(kv.first); } } void IOClient::end_session() { if (this->state == CLIENT_STATE::DISCONNETION_START) { return; } logger_info("server: #", _async_connection->id(), " send disconnect signal."); this->state = CLIENT_STATE::DISCONNETION_START; if (sock->is_open()) { auto nd = this->_async_connection->get_pool()->construct(DATA_KINDS::DISCONNECT); this->_async_connection->send(nd); } } void IOClient::close() { if (state != CLIENT_STATE::DISCONNECTED) { state = CLIENT_STATE::DISCONNECTED; _async_connection->mark_stoped(); if (this->sock->is_open()) { _async_connection->full_stop(); this->sock->close(); } logger_info("server: client #", this->_async_connection->id(), " stoped."); _async_connection = nullptr; } } void IOClient::ping() { auto delta_time = (dariadb::timeutil::current_time() - _last_query_time); if (delta_time < PING_TIMER_INTERVAL) { return; } pings_missed++; auto nd = this->_async_connection->get_pool()->construct(DATA_KINDS::PING); this->_async_connection->send(nd); } void IOClient::onNetworkError(const boost::system::error_code &err) { if ((state != CLIENT_STATE::DISCONNECTED) && (state != CLIENT_STATE::DISCONNETION_START)) { logger_info("server: client #", this->_async_connection->id(), " network error - ", err.message()); logger_info("server: client #", this->_async_connection->id(), " stoping..."); this->close(); } } void IOClient::onDataRecv(const NetData_ptr &d, bool &cancel, bool &dont_free_memory) { _last_query_time = dariadb::timeutil::current_time(); // logger("server: #", this->id(), " dataRecv ", d->size, " bytes."); auto qh = reinterpret_cast<Query_header *>(d->data); DATA_KINDS kind = (DATA_KINDS)qh->kind; switch (kind) { case DATA_KINDS::APPEND: { if (this->env->srv->server_begin_stopping()) { logger_info("server: #", this->_async_connection->id(), " refuse append query. server in stop."); return; } auto hdr = reinterpret_cast<QueryAppend_header *>(&d->data); auto count = hdr->count; logger_info("server: #", this->_async_connection->id(), " recv #", hdr->id, " write ", count); this->env->srv->write_begin(); this->append(d); break; } case DATA_KINDS::PONG: { pings_missed--; logger_info("server: #", this->_async_connection->id(), " pings_missed: ", pings_missed.load()); break; } case DATA_KINDS::DISCONNECT: { logger_info("server: #", this->_async_connection->id(), " disconnection request."); cancel = true; this->end_session(); env->srv->client_disconnect(this->_async_connection->id()); break; } case DATA_KINDS::READ_INTERVAL: { if (this->env->srv->server_begin_stopping()) { logger_info("server: #", this->_async_connection->id(), " refuse read_interval query. server in stop."); return; } auto query_hdr = reinterpret_cast<QueryInterval_header *>(&d->data); sendOk(query_hdr->id); this->readInterval(d); break; } case DATA_KINDS::READ_TIMEPOINT: { if (this->env->srv->server_begin_stopping()) { logger_info("server: #", this->_async_connection->id(), " refuse read_timepoint query. server in stop."); return; } auto query_hdr = reinterpret_cast<QueryTimePoint_header *>(&d->data); sendOk(query_hdr->id); this->readTimePoint(d); break; } case DATA_KINDS::CURRENT_VALUE: { if (this->env->srv->server_begin_stopping()) { logger_info("server: #", this->_async_connection->id(), " refuse current_value query. server in stop."); return; } auto query_hdr = reinterpret_cast<QueryCurrentValue_header *>(&d->data); sendOk(query_hdr->id); this->currentValue(d); break; } case DATA_KINDS::SUBSCRIBE: { if (this->env->srv->server_begin_stopping()) { logger_info("server: #", this->_async_connection->id(), " refuse subscribe query. server in stop."); return; } auto query_hdr = reinterpret_cast<QuerSubscribe_header *>(&d->data); sendOk(query_hdr->id); subscribe(d); break; } case DATA_KINDS::HELLO: { if (this->env->srv->server_begin_stopping()) { logger_info("server: #", this->_async_connection->id(), " refuse connection query. server in stop."); return; } QueryHello_header *qhh = reinterpret_cast<QueryHello_header *>(d->data); if (qhh->version != PROTOCOL_VERSION) { logger("server: #", _async_connection->id(), " wrong protocol version: exp=", PROTOCOL_VERSION, ", rec=", qhh->version); sendError(0, ERRORS::WRONG_PROTOCOL_VERSION); this->state = CLIENT_STATE::DISCONNECTED; return; } auto host_ptr = ((char *)(&qhh->host_size) + sizeof(qhh->host_size)); std::string msg(host_ptr, host_ptr + qhh->host_size); host = msg; env->srv->client_connect(this->_async_connection->id()); auto nd = _async_connection->get_pool()->construct(DATA_KINDS::HELLO); nd->size += sizeof(uint32_t); auto idptr = (uint32_t *)(&nd->data[1]); *idptr = _async_connection->id(); this->_async_connection->send(nd); break; } case DATA_KINDS::COMPACT: { if (this->env->srv->server_begin_stopping()) { logger_info("server: #", this->_async_connection->id(), " refuse compact query. server in stop."); return; } logger_info("server: #", this->_async_connection->id(), " query to storage compaction."); if (this->env->storage->strategy() == storage::STRATEGY::WAL) { auto wals = this->env->storage->description().wal_count; logger_info("server: #", this->_async_connection->id(), " drop ", wals, " wals to pages."); this->env->storage->drop_part_wals(wals); this->env->storage->flush(); } auto query_hdr = reinterpret_cast<QuerCompact_header *>(&d->data); if (query_hdr->pageCount != 0) { this->env->storage->compactTo(query_hdr->pageCount); } else { this->env->storage->compactbyTime(query_hdr->from, query_hdr->to); } break; } default: logger_fatal("server: unknow query kind - ", (uint8_t)kind); break; } } void IOClient::sendOk(QueryNumber query_num) { auto ok_nd = env->nd_pool->construct(DATA_KINDS::OK); auto qh = reinterpret_cast<QueryOk_header *>(ok_nd->data); qh->id = query_num; assert(qh->id != 0); ok_nd->size = sizeof(QueryOk_header); _async_connection->send(ok_nd); } void IOClient::sendError(QueryNumber query_num, const ERRORS &err) { auto err_nd = env->nd_pool->construct(DATA_KINDS::OK); auto qh = reinterpret_cast<QueryError_header *>(err_nd->data); qh->id = query_num; qh->error_code = (uint16_t)err; err_nd->size = sizeof(QueryError_header); _async_connection->send(err_nd); } void IOClient::append(const NetData_ptr &d) { auto hdr = reinterpret_cast<QueryAppend_header *>(d->data); auto count = hdr->count; logger_info("server: #", this->_async_connection->id(), " begin writing ", count); MeasArray ma = hdr->read_measarray(); auto ar = env->storage->append(ma.begin(), ma.end()); this->env->srv->write_end(); if (ar.ignored != size_t(0)) { logger_info("server: write error - ", ar.error_message); sendError(hdr->id, ERRORS::APPEND_ERROR); } else { sendOk(hdr->id); } logger_info("server: #", this->_async_connection->id(), " writed ", ar.writed, " ignored ", ar.ignored); } void IOClient::readInterval(const NetData_ptr &d) { auto query_hdr = reinterpret_cast<QueryInterval_header *>(d->data); auto from_str = timeutil::to_string(query_hdr->from); auto to_str = timeutil::to_string(query_hdr->from); logger_info("server: #", this->_async_connection->id(), " read interval point #", query_hdr->id, " id(", query_hdr->ids_count, ") [", from_str, ',', to_str, "]"); auto ids_ptr = (Id *)((char *)(&query_hdr->ids_count) + sizeof(query_hdr->ids_count)); IdArray all_ids{ids_ptr, ids_ptr + query_hdr->ids_count}; auto query_num = query_hdr->id; auto qi = new storage::QueryInterval{all_ids, query_hdr->flag, query_hdr->from, query_hdr->to}; if (query_hdr->from >= query_hdr->to) { sendError(query_num, ERRORS::WRONG_QUERY_PARAM_FROM_GE_TO); } else { auto cdr = new ClientDataReader(this, query_num); this->readerAdd(cdr, qi); env->storage->foreach (*qi, cdr); } } void IOClient::readTimePoint(const NetData_ptr &d) { auto query_hdr = reinterpret_cast<QueryTimePoint_header *>(d->data); auto tp_str = timeutil::to_string(query_hdr->tp); logger_info("server: #", this->_async_connection->id(), " read time point #", query_hdr->id, " id(", query_hdr->ids_count, ") [", tp_str, "]"); auto ids_ptr = (Id *)((char *)(&query_hdr->ids_count) + sizeof(query_hdr->ids_count)); IdArray all_ids{ids_ptr, ids_ptr + query_hdr->ids_count}; auto query_num = query_hdr->id; auto qi = new storage::QueryTimePoint{all_ids, query_hdr->flag, query_hdr->tp}; auto cdr = new ClientDataReader(this, query_num); readerAdd(cdr, qi); env->storage->foreach (*qi, cdr); } void IOClient::currentValue(const NetData_ptr &d) { auto query_hdr = reinterpret_cast<QueryCurrentValue_header *>(d->data); logger_info("server: #", this->_async_connection->id(), " current values #", query_hdr->id, " id(", query_hdr->ids_count, ")"); auto ids_ptr = (Id *)((char *)(&query_hdr->ids_count) + sizeof(query_hdr->ids_count)); IdArray all_ids{ids_ptr, ids_ptr + query_hdr->ids_count}; auto flag = query_hdr->flag; auto query_num = query_hdr->id; auto result = env->storage->currentValue(all_ids, flag); auto cdr = new ClientDataReader(this, query_num); readerAdd(cdr, nullptr); for (auto &v : result) { cdr->call(v.second); } cdr->is_end(); } void IOClient::subscribe(const NetData_ptr &d) { auto query_hdr = reinterpret_cast<QuerSubscribe_header *>(d->data); logger_info("server: #", this->_async_connection->id(), " subscribe to values #", query_hdr->id, " id(", query_hdr->ids_count, ")"); auto ids_ptr = (Id *)((char *)(&query_hdr->ids_count) + sizeof(query_hdr->ids_count)); IdArray all_ids{ids_ptr, ids_ptr + query_hdr->ids_count}; auto flag = query_hdr->flag; auto query_num = query_hdr->id; if (subscribe_reader == nullptr) { subscribe_reader = std::shared_ptr<storage::IReaderClb>(new SubscribeCallback(this, query_num)); } env->storage->subscribe(all_ids, flag, subscribe_reader); } void IOClient::readerAdd(ClientDataReader *cdr, void *data) { std::lock_guard<std::mutex> lg(_readers_lock); this->_readers.insert(std::make_pair(cdr->_query_num, std::make_pair(cdr, data))); } void IOClient::readerRemove(QueryNumber number) { std::lock_guard<std::mutex> lg(_readers_lock); auto fres = this->_readers.find(number); if (fres == this->_readers.end()) { THROW_EXCEPTION("engien: readerRemove logic error"); } else { auto ptr = fres->second; this->_readers.erase(fres); delete ptr.first; if (ptr.second != nullptr) { delete ptr.second; } } }
33.505495
90
0.65615
dariadb
f95bd0f0589793a9fce74da8ccbe11a2b0a4da4a
3,922
cpp
C++
src/FSDefineFont.cpp
pperehozhih/transform-cxx
f630079779e9e3cf6d06dcfc04b3ad0bd99d7e48
[ "BSD-3-Clause" ]
4
2018-09-16T09:55:22.000Z
2020-12-19T02:02:40.000Z
src/FSDefineFont.cpp
pperehozhih/transform-cxx
f630079779e9e3cf6d06dcfc04b3ad0bd99d7e48
[ "BSD-3-Clause" ]
null
null
null
src/FSDefineFont.cpp
pperehozhih/transform-cxx
f630079779e9e3cf6d06dcfc04b3ad0bd99d7e48
[ "BSD-3-Clause" ]
2
2015-11-24T20:27:35.000Z
2019-06-04T15:23:30.000Z
/* * FSDefineFont.cpp * Transform SWF * * Created by smackay on Thu Mar 20 2003. * Copyright (c) 2001-2003 Flagstone Software Ltd. All rights reserved. * * This file contains Original Code and/or Modifications of Original Code as defined in * and that are subject to the Flagstone Software Source License Version 1.0 (the * 'License'). You may not use this file except in compliance with the License. Please * obtain a copy of the License at http://www.flagstonesoftware.com/licenses/source.html * and read it before using this file. * * The Original Code and all software distributed under the License are distributed on an * 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, AND Flagstone * HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT OF THIRD PARTY * RIGHTS. Please see the License for the specific language governing rights and limitations * under the License. */ #include "FSDefineFont.h" #include <string.h> #include "FSMovie.h" #include "FSInputStream.h" #include "FSOutputStream.h" using namespace transform; namespace transform { FSDefineFont::FSDefineFont(FSInputStream* aStream) : FSDefineObject(DefineFont, 0), shapes() { decodeFromStream(aStream); } const char* FSDefineFont::className() const { const static char _name[] = "FSDefineFont"; return _name; } void FSDefineFont::add(const FSVector<FSShape>& anArray) { for (FSVector<FSShape>::const_iterator i = anArray.begin(); i != anArray.end(); ++i) shapes.push_back(*i); } int FSDefineFont::lengthInStream(FSOutputStream* aStream) { FSDefineObject::lengthInStream(aStream); aStream->setContext(FSStream::FillBits, 1); aStream->setContext(FSStream::LineBits, 0); length += (int)(shapes.size())*2; for (FSVector<FSShape>::iterator i = shapes.begin(); i != shapes.end(); ++i) length += (*i).lengthInStream(aStream); aStream->setContext(FSStream::FillBits, 0); aStream->setContext(FSStream::LineBits, 0); return length; } void FSDefineFont::encodeToStream(FSOutputStream* aStream) { aStream->startEncoding(className()); FSDefineObject::encodeToStream(aStream); aStream->setContext(FSStream::FillBits, 1); aStream->setContext(FSStream::LineBits, 0); aStream->setContext(FSStream::FillStyles, 1); aStream->setContext(FSStream::LineStyles, 0); FSMovie::encodeToStream(shapes, 16, false, aStream); aStream->setContext(FSStream::FillBits, 0); aStream->setContext(FSStream::LineBits, 0); aStream->setContext(FSStream::FillStyles, 0); aStream->setContext(FSStream::LineStyles, 0); aStream->endEncoding(className()); } void FSDefineFont::decodeFromStream(FSInputStream* aStream) { int glyphCount = 0; aStream->startDecoding(className()); FSDefineObject::decodeFromStream(aStream); glyphCount = aStream->scan(FSStream::UnsignedWord, 16) / 2; aStream->setCursor(aStream->getCursor()-16); #ifdef _DEBUG aStream->startDecoding("array"); #endif for (int i=0; i<glyphCount; i++) aStream->read(FSStream::UnsignedWord, 16); #ifdef _DEBUG aStream->endDecoding("array"); aStream->startDecoding("array"); #endif for (int i=0; i<glyphCount; i++) shapes.push_back(FSShape(aStream)); #ifdef _DEBUG aStream->endDecoding("array"); #endif aStream->endDecoding(className()); } }
31.886179
95
0.635135
pperehozhih
f95d939d6508bdc72cbcd5064e445a1015c45e4a
2,002
cpp
C++
241#different-ways-to-add-parentheses/solution.cpp
llwwns/leetcode_solutions
e352c9bf6399ab3ee0f23889e70361c9f2a3bd33
[ "MIT" ]
null
null
null
241#different-ways-to-add-parentheses/solution.cpp
llwwns/leetcode_solutions
e352c9bf6399ab3ee0f23889e70361c9f2a3bd33
[ "MIT" ]
null
null
null
241#different-ways-to-add-parentheses/solution.cpp
llwwns/leetcode_solutions
e352c9bf6399ab3ee0f23889e70361c9f2a3bd33
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class UniqueBST { public: vector<TreeNode*> make(int l, int r) { if (l > r) return vector<TreeNode*>{NULL}; if (l == r) return vector<TreeNode*>{new TreeNode(l)}; vector<TreeNode*> ans; for (int i = l; i <= r; i++) { auto a = make(l, i-1); auto b = make(i + 1, r); ans.reserve(a.size() * b.size()); for (auto pl : a) { for (auto pr : b) { TreeNode *p = new TreeNode(i); p->left = pl; p->right = pr; ans.push_back(p); } } } return ans; } }; class Solution { public: vector<int> nums; vector<char> opts; int calc(TreeNode *p) { int l = p->left == NULL ? nums[p->val - 1] : calc(p->left); int r = p->right == NULL ? nums[p->val] : calc(p->right); switch (opts[p->val - 1]) { case '+': return l + r; case '-': return l - r; case '*': return l * r; } } vector<int> diffWaysToCompute(string input) { int n = 0; nums.clear(); opts.clear(); for (char s : input) { if (s <= '9' && s >= '0') { n = n * 10 + (s - '0'); } else { nums.push_back(n); n = 0; opts.push_back(s); } } if (opts.empty()) return vector<int>{n}; nums.push_back(n); auto lst = UniqueBST().make(1, opts.size()); vector<int> ret; ret.reserve(lst.size()); for (auto p : lst) { ret.push_back(calc(p)); } return ret; } };
28.197183
68
0.398102
llwwns
f962b58c588835cd39b86121b810bf77ce2a3039
5,875
hpp
C++
gearoenix/glc3/shader/gx-glc3-shd-shader.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
35
2018-01-07T02:34:38.000Z
2022-02-09T05:19:03.000Z
gearoenix/glc3/shader/gx-glc3-shd-shader.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
111
2017-09-20T09:12:36.000Z
2020-12-27T12:52:03.000Z
gearoenix/glc3/shader/gx-glc3-shd-shader.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
5
2020-02-11T11:17:37.000Z
2021-01-08T17:55:43.000Z
#ifndef GEAROENIX_GLC3_SHADER_SHADER_HPP #define GEAROENIX_GLC3_SHADER_SHADER_HPP #include "../../core/gx-cr-build-configuration.hpp" #ifdef GX_USE_OPENGL_CLASS_3 #include "../../core/gx-cr-static.hpp" #include "../../core/gx-cr-types.hpp" #include "../../core/sync/gx-cr-sync-end-caller.hpp" #include "../../gl/gx-gl-constants.hpp" #include "../../gl/gx-gl-loader.hpp" #include "../../gl/gx-gl-types.hpp" #include "../gx-glc3.hpp" #include <string> #define GX_GLC3_UNIFORM_FAILED -1 #define GX_GLC3_TEXTURE_INDEX_FAILED -1 #ifdef GX_DEBUG_GL_CLASS_3 #define GX_DEBUG_GL_CLASS_3_GLSL #endif #define GX_GLC3_UNIFORM_TEXTURE_ARRAY(name, count) \ GX_GET_VAL_PRV(gl::sint, name, GX_GLC3_UNIFORM_FAILED) \ GX_GET_ARR_PRV(gl::sint, name##_indices, count) #define GX_GLC3_UNIFORM_TEXTURE(name) \ GX_GET_VAL_PRV(gl::sint, name, GX_GLC3_UNIFORM_FAILED) \ GX_GET_VAL_PRV(gl::sint, name##_index, GX_GLC3_TEXTURE_INDEX_FAILED) #define GX_GLC3_UNIFORM(name, function) \ GX_GET_VAL_PRV(gl::sint, name, GX_GLC3_UNIFORM_FAILED) \ void set_##name##_data(const float* data) const noexcept \ { \ gl::Loader::uniform##function; \ } #define GX_GLC3_UNIFORM_VECTOR(name, element_count, count) \ GX_GLC3_UNIFORM(name, element_count##fv(name, count, data)) #define GX_GLC3_UNIFORM_FLOAT(name, count) \ GX_GLC3_UNIFORM(name, 1fv(name, count, data)) #define GX_GLC3_UNIFORM_MATRIX(name, element_count, count) \ GX_GLC3_UNIFORM(name, _matrix##element_count##fv(name, count, GL_FALSE, data)) #define GX_GLC3_GET_UNIFORM(shd, uniform) \ uniform = shd->get_uniform_location(#uniform); \ if (GX_GLC3_UNIFORM_FAILED == uniform) { \ GXLOGF("Failed to locate the uniform " << #uniform); \ } #define GX_GLC3_THIS_GET_UNIFORM(uniform) GX_GLC3_GET_UNIFORM(this, uniform) #define GX_GLC3_SHADER_SET_TEXTURE_INDEX(x) \ x##_index = texture_index; \ ++texture_index; #define GX_GLC3_SHADER_SET_TEXTURE_INDEX_ARRAY(x) \ for (auto& i : x##_indices) { \ i = texture_index; \ ++texture_index; \ } #define GX_GLC3_THIS_GET_UNIFORM_TEXTURE(uniform) \ GX_GLC3_THIS_GET_UNIFORM(uniform) \ GX_GLC3_SHADER_SET_TEXTURE_INDEX(uniform) #define GX_GLC3_THIS_GET_UNIFORM_TEXTURE_ARRAY(uniform) \ GX_GLC3_GET_UNIFORM(this, uniform) \ GX_GLC3_SHADER_SET_TEXTURE_INDEX_ARRAY(uniform) #define GX_GLC3_SHADER_SET_TEXTURE_INDEX_STARTING gl::sint texture_index = 0; #define GX_GLC3_SHADER_SET_TEXTURE_INDEX_UNIFORM(x) gl::Loader::uniform1i(x, x##_index); #define GX_GLC3_SHADER_SET_TEXTURE_INDEX_ARRAY_UNIFORM(x) gl::Loader::uniform1iv(x, GX_COUNT_OF(x##_indices), x##_indices); #define GX_GLC3_SHADER_SRC_DEFAULT_VERSION \ "#version " << ((e->get_engine_type() == render::engine::Type::OpenGLES3) ? "300 es" : ((e->get_engine_type() == render::engine::Type::OpenGL33) ? "330" : "430")) \ << "\n" \ << "#define GX_PI 3.141592653589793238\n" \ "precision highp float;\n" \ "precision highp int;\n" \ << ((e->get_engine_type() == render::engine::Type::OpenGLES3) ? "precision highp sampler2D;\nprecision highp samplerCube;\n" : "") #define GX_GLC3_SHADER_SRC_DEFAULT_ATTRIBUTES \ "layout(location = 0) in vec3 position;\n" \ "layout(location = 1) in vec3 normal;\n" \ "layout(location = 2) in vec4 tangent;\n" \ "layout(location = 3) in vec2 uv;\n" #define GX_GLC3_SHADER_SRC_DEFAULT_VERTEX_STARTING \ std::stringstream vertex_shader_code; \ vertex_shader_code << GX_GLC3_SHADER_SRC_DEFAULT_VERSION << GX_GLC3_SHADER_SRC_DEFAULT_ATTRIBUTES #define GX_GLC3_SHADER_SRC_DEFAULT_FRAGMENT_STARTING \ std::stringstream fragment_shader_code; \ fragment_shader_code << GX_GLC3_SHADER_SRC_DEFAULT_VERSION namespace gearoenix::glc3::engine { class Engine; } namespace gearoenix::glc3::shader { class Shader { protected: engine::Engine* const e; gl::uint shader_program = 0; gl::uint vertex_object = 0; gl::uint fragment_object = 0; void create_program() noexcept; void run() noexcept; void link() const noexcept; void validate() const noexcept; [[nodiscard]] gl::uint add_shader_to_program(const std::string& shd, gl::enumerated shader_type) const noexcept; void set_vertex_shader(const std::string& shd) noexcept; void set_fragment_shader(const std::string& shd) noexcept; static void end_program(gl::uint shader_program) noexcept; static void end_object(gl::uint shader_object) noexcept; public: Shader(engine::Engine* e, const core::sync::EndCaller<core::sync::EndCallerIgnore>& c) noexcept; virtual ~Shader() noexcept; /// On not found returns GX_SHADER_UNIFORM_FAILED [[nodiscard]] gl::sint get_uniform_location(const std::string& name) const noexcept; [[nodiscard]] gl::uint get_shader_program() const noexcept; virtual void bind() const noexcept; }; } #endif #endif
42.883212
168
0.607149
Hossein-Noroozpour
f963dd3efeedb483f95ed7f4a52bcc3e7d3f5171
2,680
cpp
C++
tests/source/extractor_test.cpp
TheMarlboroMan/japavocards
df1d9922e2a087c6212c4c600796ec35f41432ca
[ "Beerware" ]
null
null
null
tests/source/extractor_test.cpp
TheMarlboroMan/japavocards
df1d9922e2a087c6212c4c600796ec35f41432ca
[ "Beerware" ]
null
null
null
tests/source/extractor_test.cpp
TheMarlboroMan/japavocards
df1d9922e2a087c6212c4c600796ec35f41432ca
[ "Beerware" ]
null
null
null
#include <iostream> #include <string> #include "../class/app/extractor.cpp" #include "../class/app/lector.cpp" #include "../class/app/datos_bruto.cpp" #include "../class/app/palabra.cpp" #include "../class/app/etiqueta.cpp" #include <class/dnot_parser.h> #include <herramientas/log_base/log_base.h> using namespace App; int main(int argc, char ** argv) { std::string str("idiomas:[\ {acronimo:\"ES\", nombre:\"Español\"},\ {acronimo:\"EN\", nombre:\"Inglés\"}\ ],\ etiquetas:[\ {clave:\"bilingue\",nombres:[\ {acronimo:\"ES\", nombre:\"Bilingue\"},\ {acronimo:\"EN\", nombre:\"Bilingual\"}]\ },\ {clave:\"english\",nombres:[\ {acronimo:\"EN\", nombre:\"English only\"}]\ },\ {clave:\"espanol\",nombres:[\ {acronimo:\"ES\", nombre:\"Sólo español\"}]\ },\ {clave:\"espanol2\",nombres:[\ {acronimo:\"ES\", nombre:\"Sólo español 2 que no se asigna\"}]\ },\ {clave:\"sin_usar\",nombres:[\ {acronimo:\"ES\", nombre:\"Sin usar\"},\ {acronimo:\"EN\", nombre:\"Unused\"}]\ }\ ],\ palabras:[\ {\ japones:\"completa\", romaji:\"completa\",\ etiquetas:[\"bilingue\", \"english\", \"espanol\"],\ traducciones:[\ {acronimo:\"ES\", traduccion:\"Completa\"},\ {acronimo:\"EN\", traduccion:\"Complete\"}]\ },\ {\ japones:\"soloespanol\", romaji:\"soloespanol\",\ etiquetas:[\"espanol\"],\ traducciones:[\ {acronimo:\"ES\", traduccion:\"Sólo español\"}]\ },\ {\ japones:\"enlishonly\", romaji:\"enlishonly\",\ etiquetas:[\"english\"],\ traducciones:[\ {acronimo:\"EN\", traduccion:\"English only\"}]\ },\ {\ japones:\"unlabeled\", romaji:\"unlabeled\",\ etiquetas:[],\ traducciones:[\ {acronimo:\"ES\", traduccion:\"Sin etiquetar\"},\ {acronimo:\"EN\", traduccion:\"Unlabeled\"}]\ }\ ]"); std::cout<<"Cargando lector..."<<std::endl; try { DLibH::Log_base log("log/log_extractor_test.log"); Lector L; L.cargar_desde_string(str); const auto& v=L.acc_idiomas(); for(const auto& i : v) { std::cout<<"- Iniciando extractor para "<<i->nombre<<"..."<<std::endl; Extractor e(L, *i, log); Almacenaje almacenaje=std::move(e.extraer_almacenaje()); const auto vet=almacenaje.etiquetas; std::cout<<"Se extraen "<<vet.size()<<" etiquetas."<<std::endl; for(const auto& e : vet) std::cout<<"\t"<<e.acc_nombre()<<std::endl; const auto vpa=almacenaje.palabras; std::cout<<"Se extraen "<<vpa.size()<<" palabras."<<std::endl; for(const auto& p : vpa) std::cout<<"\t"<<p.acc_japones()<<" "<<p.acc_romaji()<<" "<<p.acc_traduccion()<<" ["<<p.obtener_string_etiquetas()<<"]"<<std::endl; } } catch(std::runtime_error& e) { std::cout<<"ERROR: "<<e.what()<<std::endl; } return 0; }
27.070707
135
0.604851
TheMarlboroMan
f96bd30fe5d1f772b7d9c13bbb4f7e10550a021a
1,195
hpp
C++
basic_datastructure/AVLtree/AVLTree.hpp
weekieACpper/DataStructre-weekie
9f15d95dd57c02d7d385b151940bbee4f3c2d99b
[ "MIT" ]
null
null
null
basic_datastructure/AVLtree/AVLTree.hpp
weekieACpper/DataStructre-weekie
9f15d95dd57c02d7d385b151940bbee4f3c2d99b
[ "MIT" ]
null
null
null
basic_datastructure/AVLtree/AVLTree.hpp
weekieACpper/DataStructre-weekie
9f15d95dd57c02d7d385b151940bbee4f3c2d99b
[ "MIT" ]
null
null
null
/* * @Author: weekie * @Date: 2022-02-11 23:24:25 * @LastEditTime: 2022-02-28 18:18:06 * @LastEditors: weekie * @Description: AVL树的ADT描述 * @FilePath: /datastructure/AVLtree/AVLTree.hpp */ #ifndef __AVLTREE_HPP__ #define __AVLTREE_HPP__ struct TreeNode { TreeNode():leftChild(nullptr),rightChild(nullptr),height(1){} TreeNode(const int & x):leftChild(nullptr),rightChild(nullptr),value(x),height(1){} TreeNode* leftChild; TreeNode* rightChild; int value; int height; }; class AVLTree { public: AVLTree(); ~AVLTree(); public: int size(); bool empty(); TreeNode* find(const int & value);//查找操作 void insert(const int & value);//插入操作 void erase(const int & value);//删除操作 void print();//打印操作 private: void auxPrint(TreeNode* node);//辅助打印函数 TreeNode* auxErase(TreeNode* node,const int & value, TreeNode* storedNode);//删除函数的辅助函数 TreeNode* leftRotation(TreeNode* node);//左旋转 TreeNode* rightRotation(TreeNode* node);//右旋转 int getNodeHeight(TreeNode* node);//获得结点的高度 void auxDestructor(TreeNode * node);//辅助析构函数 private: TreeNode* _sentinelNode;//哨兵结点 TreeNode* _root;//根结点 int _treeSize;//树中结点的数量 }; #endif
27.159091
90
0.684519
weekieACpper
f97538bc7b51b9944cbf37fb0034d6fe4f6330f8
6,834
cpp
C++
Signal Flow Simulation/truetime-2.0/examples/advanced_demos/RUNES_demo/robot/tmote.cpp
raulest50/MicroGrid_GITCoD
885001242c8e581a6998afb4be2ae1c0b923e9c4
[ "MIT" ]
1
2019-08-31T08:06:48.000Z
2019-08-31T08:06:48.000Z
Signal Flow Simulation/truetime-2.0/examples/advanced_demos/RUNES_demo/robot/tmote.cpp
raulest50/MicroGrid_GITCoD
885001242c8e581a6998afb4be2ae1c0b923e9c4
[ "MIT" ]
null
null
null
Signal Flow Simulation/truetime-2.0/examples/advanced_demos/RUNES_demo/robot/tmote.cpp
raulest50/MicroGrid_GITCoD
885001242c8e581a6998afb4be2ae1c0b923e9c4
[ "MIT" ]
1
2020-01-07T10:46:23.000Z
2020-01-07T10:46:23.000Z
/** Task for requesting wheel velocities from wheel avr */ double request_wheel_pos_code(int segment, void* t_d) { AODVrcv_Data *d = (AODVrcv_Data *) t_d; MailboxMsg *mailboxmsgin; switch (segment){ case 1: { generic* m; m = new generic; m->t = REQUEST_WHEEL_VEL; REQUEST_WHEEL_VEL_MSG* msg = new REQUEST_WHEEL_VEL_MSG; m->msg = msg; msg->hdr.sender = TMOTE; msg->hdr.receiver = LEFT_WHEEL; ttSendMsg(I2C_NETWORK + d->bot_nbr - 1, LEFT_WHEEL, m, 8); return 0.0001; } case 2: { ttFetch("WheelRequestBox"); return 0.0; } case 3: { mailboxmsgin = (MailboxMsg*) ttRetrieve("WheelRequestBox"); d->leftVel = ((DataMsg*)mailboxmsgin->datamsg)->data; delete mailboxmsgin; return 0.0; } case 4: { generic* m2; m2 = new generic; m2->t = REQUEST_WHEEL_VEL; REQUEST_WHEEL_VEL_MSG* msg = new REQUEST_WHEEL_VEL_MSG; m2->msg = msg; msg->hdr.sender = TMOTE; msg->hdr.receiver = RIGHT_WHEEL; ttSendMsg(I2C_NETWORK + d->bot_nbr - 1, RIGHT_WHEEL, m2, 8); return 0.0001; } case 5: { ttFetch("WheelRequestBox"); return 0.0; } default: { mailboxmsgin = (MailboxMsg*) ttRetrieve("WheelRequestBox"); // d->leftVel = ((DATAMSG*)mailboxmsgin->datamsg)->vel; // datamsgin = (DataMsg*) ttRetrieve("WheelRequestBox"); // msgin = (SEND_WHEEL_VEL_MSG*) datamsgin->datamsg; generic* m1; m1 = new generic; m1->t = SEND_WHEEL_VELS; SEND_WHEEL_VELS_MSG* msg1 = new SEND_WHEEL_VELS_MSG; m1->msg = msg1; msg1->hdr.sender = TMOTE; msg1->hdr.receiver = LEFT_WHEEL; msg1->leftVel = d->leftVel; msg1->rightVel = ((DataMsg*)mailboxmsgin->datamsg)->data; ttSendMsg(I2C_NETWORK + d->bot_nbr - 1, MEGA_128, m1, 8+2*32); delete mailboxmsgin; return FINISHED; } } return FINISHED; } /** Task for sending range requests to nodes * This is not a periodic task but a task in an * infinite loop. * #1 Check if blocked, if so add 50 ms delay * #2 Send radio message * #3 Request ultra sound transmission from Mega_Ultra */ double send_range_request(int segment, void* t_d) { AODVrcv_Data *d = (AODVrcv_Data *)t_d; switch (segment){ case 1: { if (ttCurrentTime() < d->snd_block) { // Request sending blocked, delay next send with 50 ms mexPrintf("Bot#%d dalying 50 ms\n", d->bot_nbr); ttSleep(0.050); ttSetNextSegment(4); } else if (d->rcv_timeout == 0.0) { // First time wait before sending first to avoid synced send d->rcv_timeout = ttCurrentTime(); ttSleep(d->bot_nbr * 0.2); ttSetNextSegment(1); } return 0.0001; } case 2: { // Broadcast message GenericNwkMsg *msg = new GenericNwkMsg; msg->type = RANGE_REQUEST; msg->intermed = 0; // Intermedian sending node? // Send the network message ttSendMsg(ZIGBEENETW, 0, msg, 8*sizeof(*msg)); // mexPrintf("Robot sends range request from x %f y %f at %f\n",ttAnalogIn(1),ttAnalogIn(2),ttCurrentTime()); return 0.0001; } case 3: { // Tell ultra_mega to send ultra sound generic* m; m = new generic; m->t = SEND_ULTRA; m->msg = new SEND_ULTRA_MSG; d->rcv_timeout = ttCurrentTime() + 0.150; ttSendMsg(I2C_NETWORK + d->bot_nbr - 1, MEGA_ULTRA, m, 8); ttAnalogOut(1,d->responseCounter); d->responseCounter = 0; return 0.0001; } case 4: { // Loop back to #1 ttSleep(1.2); ttSetNextSegment(1); return 0.0001; } } return FINISHED; } /** Task for sending node data to Mega_128 * A job of this task i created in the * message receive handler when a node * answers a range request. */ double send_data_to_kalman(int segment, void* t_d) { AODVrcv_Data *d = (AODVrcv_Data *)t_d; switch (segment){ case 1: { // Tell mega128 to make a kalman_update generic* m = new generic; m->t = SEND_ULTRA_POS; SEND_ULTRA_POS_MSG* msg = new SEND_ULTRA_POS_MSG; msg->hdr.sender = TMOTE; msg->hdr.receiver = MEGA_128; msg->x = d->node_x; msg->y = d->node_y; msg->dist = d->node_dist; msg->nodeID = d->node_nodeID; m->msg = msg; ttSendMsg(I2C_NETWORK + d->bot_nbr - 1, MEGA_128, m, 8+3*32+16); return 0.0001; } default: return FINISHED; } } /** Periodc task that requests the Mega_128 to send * reference velocities to the wheel avr:s. */ double request_wheel_vel_code(int segment, void* t_d) { AODVrcv_Data *d = (AODVrcv_Data *) t_d; switch (segment){ case 1:{ generic* m; m = new generic; m->t = REQUEST_WHEEL_VEL; REQUEST_WHEEL_VEL_MSG* msg = new REQUEST_WHEEL_VEL_MSG; m->msg = msg; msg->hdr.sender = TMOTE; msg->hdr.receiver = MEGA_128; ttSendMsg(I2C_NETWORK + d->bot_nbr - 1, MEGA_128, m, 8); return 0.0001; } default: return FINISHED; } } /** Periodic task that tells the Mega_Ultra to * send obstacle avoidance information collected * from the IR-sensor. */ double request_ir_code(int segment, void* t_d) { AODVrcv_Data *d = (AODVrcv_Data *) t_d; switch (segment){ case 1:{ generic* m; m = new generic; m->t = REQUEST_IR; REQUEST_IR_MSG* msg = new REQUEST_IR_MSG; m->msg = msg; msg->hdr.sender = TMOTE; msg->hdr.receiver = MEGA_ULTRA; ttSendMsg(I2C_NETWORK + d->bot_nbr - 1, MEGA_ULTRA, m, 8); return 0.0001; } default: return FINISHED; } } /** Task, executed upon receiving a network message * on the I2C-bus. */ double msg_rcv_handler(int seg, void* t_d) { AODVrcv_Data *d = (AODVrcv_Data *) t_d; MailboxMsg *mailboxmsg; DataMsg *dataMsg; generic *m; m = (generic *) ttGetMsg(I2C_NETWORK + d->bot_nbr - 1); switch (seg) { case 1: switch (m->t){ // Forwarding velocity references from Mega_128 to wheel avr:s // or forwarding velocities from wheel avr:s to Mega_128. case SEND_WHEEL_VEL: { if (((SEND_WHEEL_VEL_MSG*) m->msg)->hdr.sender == MEGA_128) { if (((SEND_WHEEL_VEL_MSG*) m->msg)->hdr.receiver == LEFT_WHEEL) ttSendMsg(I2C_NETWORK + d->bot_nbr - 1, LEFT_WHEEL, m, 8+32); else ttSendMsg(I2C_NETWORK + d->bot_nbr - 1, RIGHT_WHEEL, m, 8+32); } else { // This else needs to be modified mailboxmsg = new MailboxMsg; dataMsg = new DataMsg; dataMsg->data = ((SEND_WHEEL_VEL_MSG*) m->msg)->vel; mailboxmsg->datamsg = dataMsg; ttPost("WheelRequestBox",mailboxmsg); // ttSendMsg(I2C_NETWORK + d->bot_nbr - 1, MEGA_128, m, 10); delete m; } return 0.0001; } // Forwarding obstacle avoidance information from Mega_Ultra to // to Mega_128. case SEND_IR: { ttSendMsg(I2C_NETWORK + d->bot_nbr - 1, MEGA_128, m, 8+32); return 0.0001; } default: {} } return 0.0001; default: return FINISHED; } }
24.234043
115
0.635353
raulest50
f978c1a5a4f580e0011d2bb642d95289e18d66e8
4,243
cpp
C++
test/source/io/tsequenceset.cpp
adonmo/meos
123d138f1fda8a65a4e09b5e74d51cfd4e69287e
[ "MIT" ]
13
2020-09-14T07:02:50.000Z
2022-03-31T08:07:33.000Z
test/source/io/tsequenceset.cpp
adonmo/meos
123d138f1fda8a65a4e09b5e74d51cfd4e69287e
[ "MIT" ]
25
2020-07-11T21:10:18.000Z
2020-11-10T20:32:56.000Z
test/source/io/tsequenceset.cpp
adonmo/meos
123d138f1fda8a65a4e09b5e74d51cfd4e69287e
[ "MIT" ]
1
2020-09-17T14:31:05.000Z
2020-09-17T14:31:05.000Z
#include <catch2/catch.hpp> #include <meos/io/Deserializer.hpp> #include <meos/io/Serializer.hpp> #include <meos/types/temporal/TSequenceSet.hpp> #include <string> #include "../common/matchers.hpp" #include "../common/time_utils.hpp" #include "../common/utils.hpp" using namespace meos; using namespace std; TEMPLATE_TEST_CASE("TSequenceSet are serialized", "[serializer][tsequenceset]", int, float) { Serializer<TestType> w; SECTION("only one value present") { auto i = GENERATE(0, 1, -1, 2012, 756772544, take(30, random(numeric_limits<int>::min(), numeric_limits<int>::max()))); auto instant = TInstant<TestType>(i, unix_time_point(2012, 11, 1)); set<TInstant<TestType>> instants; instants.insert(instant); auto sequences = set<TSequence<TestType>>{ TSequence<TestType>(instants, true, true), }; TSequenceSet<TestType> sequence_set(sequences); REQUIRE(w.write(&sequence_set) == "{[" + w.write(i) + "@2012-11-01T00:00:00+0000]}"); } SECTION("multiple values present") { auto i = GENERATE(0, 1, -1, 2012, 756772544, take(6, random(numeric_limits<int>::min(), numeric_limits<int>::max()))); auto j = GENERATE(0, 1, -1, 2012, 756772544, take(6, random(numeric_limits<int>::min(), numeric_limits<int>::max()))); auto instant1 = TInstant<TestType>(i, unix_time_point(2012, 11, 1)); auto instant2 = TInstant<TestType>(j, unix_time_point(2012, 11, 2)); set<TInstant<TestType>> instants; instants.insert(instant1); instants.insert(instant2); auto sequences = set<TSequence<TestType>>{ TSequence<TestType>(instants), }; TSequenceSet<TestType> sequence_set(sequences); string serialized = w.write(&sequence_set); REQUIRE(serialized.size() > 2); REQUIRE(serialized[0] == '{'); REQUIRE(serialized[1] == '['); REQUIRE(serialized[serialized.size() - 2] == ')'); REQUIRE(serialized[serialized.size() - 1] == '}'); set<string> actual = split_into_set(serialized.substr(2, serialized.size() - 4), ", "); set<string> expected = { w.write(i) + "@2012-11-01T00:00:00+0000", w.write(j) + "@2012-11-02T00:00:00+0000", }; REQUIRE_THAT(actual, UnorderedEquals(expected)); } } TEMPLATE_TEST_CASE("TSequenceSet are deserialized", "[deserializer][tsequenceset]", int, float) { SECTION("only one TSequenceSet present") { SECTION("only one inst present") { Deserializer<TestType> r("{[10@2012-11-01]}"); unique_ptr<TSequenceSet<TestType>> sequence_set = r.nextTSequenceSet(); set<TInstant<TestType>> actual = sequence_set->instants(); set<TInstant<TestType>> expected = {TInstant<TestType>(10, unix_time_point(2012, 11, 1))}; auto x = UnorderedEquals(expected); REQUIRE_THAT(actual, x); CHECK_THROWS(r.nextTSequenceSet()); } SECTION("multiple inst present") { Deserializer<TestType> r("{[10@2012-01-01 00:00:00+00], [12@2012-04-01 00:00:00+00]}"); unique_ptr<TSequenceSet<TestType>> sequence_set = r.nextTSequenceSet(); set<TInstant<TestType>> actual = sequence_set->instants(); set<TInstant<TestType>> expected = {TInstant<TestType>(10, unix_time_point(2012, 1, 1)), TInstant<TestType>(12, unix_time_point(2012, 4, 1))}; auto x = UnorderedEquals(expected); REQUIRE_THAT(actual, x); CHECK_THROWS(r.nextTSequenceSet()); } } SECTION("multiple TSequenceSets present") { Deserializer<TestType> r("{[10@2012-01-01 00:00:00+00]} {[12@2012-04-01 00:00:00+00]}"); unique_ptr<TSequenceSet<TestType>> sequence_set = r.nextTSequenceSet(); set<TInstant<TestType>> actual = sequence_set->instants(); set<TInstant<TestType>> expected = {TInstant<TestType>(10, unix_time_point(2012, 1, 1))}; auto x1 = UnorderedEquals(expected); REQUIRE_THAT(actual, x1); unique_ptr<TSequenceSet<TestType>> instantSet2 = r.nextTSequenceSet(); set<TInstant<TestType>> actual2 = instantSet2->instants(); expected = {TInstant<TestType>(12, unix_time_point(2012, 4, 1))}; auto x2 = UnorderedEquals(expected); REQUIRE_THAT(actual2, x2); CHECK_THROWS(r.nextTSequenceSet()); } }
41.598039
97
0.658968
adonmo
f97f36bb8a05dd893e0cfb14141e602710686dae
2,811
cpp
C++
cpp/libs/src/asiopal/TCPServer.cpp
Aditya23456/Something
a6e1937228fba865c0bbc9205b998c92bd700ed7
[ "Apache-2.0" ]
1
2022-03-29T03:58:06.000Z
2022-03-29T03:58:06.000Z
cpp/libs/src/asiopal/TCPServer.cpp
Aditya23456/Dnp3-with-group0
a6e1937228fba865c0bbc9205b998c92bd700ed7
[ "Apache-2.0" ]
null
null
null
cpp/libs/src/asiopal/TCPServer.cpp
Aditya23456/Dnp3-with-group0
a6e1937228fba865c0bbc9205b998c92bd700ed7
[ "Apache-2.0" ]
null
null
null
/* * Licensed to Green Energy Corp (www.greenenergycorp.com) under one or * more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Green Energy Corp licenses this file to you 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 project was forked on 01/01/2013 by Automatak, LLC and modifications * may have been made to this file. Automatak, LLC licenses these modifications * to you under the terms of the License. */ #include "asiopal/TCPServer.h" #include <openpal/logging/LogMacros.h> #include <opendnp3/LogLevels.h> #include <sstream> using namespace asio; using namespace asio::ip; using namespace opendnp3; namespace asiopal { TCPServer::TCPServer(std::shared_ptr<ThreadPool> pool, openpal::LogRoot root, IPEndpoint endpoint, std::error_code& ec) : m_pool(pool), m_root(std::move(root)), m_endpoint(ip::tcp::v4(), endpoint.port), m_acceptor(pool->GetIOService()), m_socket(pool->GetIOService()), m_session_id(0) { this->Configure(endpoint.address, ec); } void TCPServer::BeginShutdown() { m_acceptor.close(); } void TCPServer::Configure(const std::string& adapter, std::error_code& ec) { auto address = asio::ip::address::from_string(adapter, ec); if (ec) { return; } m_endpoint.address(address); m_acceptor.open(m_endpoint.protocol(), ec); if (ec) { return; } m_acceptor.set_option(ip::tcp::acceptor::reuse_address(true), ec); if (ec) { return; } m_acceptor.bind(m_endpoint, ec); if (ec) { return; } m_acceptor.listen(socket_base::max_connections, ec); if (!ec) { std::ostringstream oss; oss << m_endpoint; FORMAT_LOG_BLOCK(m_root.logger, flags::INFO, "Listening on: %s", oss.str().c_str()); } } void TCPServer::StartAccept() { // this ensures that the TCPListener is never deleted during an active callback auto self(shared_from_this()); auto callback = [self](std::error_code ec) { if (ec) { SIMPLE_LOG_BLOCK(self->m_root.logger, flags::INFO, ec.message().c_str()); self->OnShutdown(); } else { const auto ID = self->m_session_id; ++self->m_session_id; // method responsible for closing self->AcceptConnection(ID, std::move(self->m_socket)); self->StartAccept(); } }; m_acceptor.async_accept(m_socket, callback); } }
23.040984
121
0.723586
Aditya23456
f98206a74d7c77865d891e7a7ecbdcb1d970a534
1,335
hpp
C++
src/gsw.hpp
adomasven/gsw13
488459270e54113f791bf3c6a0e2134a3f5e9a88
[ "MIT" ]
9
2016-11-22T13:55:40.000Z
2022-03-17T14:24:18.000Z
src/gsw.hpp
adomasven/gsw13
488459270e54113f791bf3c6a0e2134a3f5e9a88
[ "MIT" ]
1
2019-12-05T07:23:25.000Z
2020-03-16T08:39:44.000Z
src/gsw.hpp
adomasven/gsw13
488459270e54113f791bf3c6a0e2134a3f5e9a88
[ "MIT" ]
4
2018-06-12T04:41:07.000Z
2021-11-03T12:11:35.000Z
#pragma once #include "utils.hpp" #include "gaussSampler.hpp" #define sigma 3.8 #define sigma6 (int)(sigma*6) class GSW { public: BigInt quotient; // q/sigma6 > 8(N + 1)^L unsigned int n, n_1; // n >= log(q/sigma)(k+110)/7.2 unsigned int m; // m = O(n log q) unsigned int l; // l = floor(log q) + 1 unsigned int N; // N = (n + 1) * l GaussSampler *gaussSampler; GSW(); GSW(const int, const int); ~GSW(); BIVector secret_key_gen() const; //sk = Z(n+1)_q BIMatrix public_key_gen(const BIVector& secret_key) const; //pk = Z(m, n+1)_q // C = flatten(message * identity + BitDecomp(R * A)) BitMatrix encrypt(const BIMatrix& public_key, const BigInt& message) const; BigInt decrypt(const BIVector& private_key, const BitMatrix& cyphertext) const; bool decrypt_bit(const BIVector& private_key, const BitMatrix& cyphertext) const; // Homomorphic operations BitMatrix nand(const BitMatrix&, const BitMatrix&) const; // utility functions BIVector powers_of_2(const BIVector&) const ; BitVector bit_decomp(const BIVector&) const ; BIVector inverse_bit_decomp(const BitVector&) const ; BIVector inverse_bit_decomp(const BIVector&) const ; BitVector flatten(const BitVector&) const ; BitVector flatten(const BIVector&) const ; };
26.7
85
0.670412
adomasven
f9898e3d60ae75a4aa64f6b64ac43d83a67f481a
2,779
cpp
C++
warsztaty-finalowe-2019/rejected/wiezowce-dzakarty.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
2
2019-05-04T09:37:09.000Z
2019-05-22T18:07:28.000Z
warsztaty-finalowe-2019/rejected/wiezowce-dzakarty.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
null
null
null
warsztaty-finalowe-2019/rejected/wiezowce-dzakarty.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef intmax_t I; const I inf = 1e18; typedef pair<I, I> II; typedef double F; template <typename T> ostream &operator<<(ostream &o, const vector<T> &v) { o << "["; for (auto i = v.begin(); i != v.end(); ++i) { o << *i; if (i != prev(v.end())) o << ", "; } o << "]"; return o; } struct Hund { I x, p; }; struct Kante { I v, w; }; ostream &operator<<(ostream &o, Hund i) { o << "(" << i.x << ", " << i.p << ")"; return o; } ostream &operator<<(ostream &o, Kante i) { o << "(" << i.v << ", " << i.w << ")"; return o; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr), cout.tie(nullptr); I n, m; cin >> n >> m; vector<Hund> hunde(m); for (I i = 0; i < m; ++i) cin >> hunde[i].x >> hunde[i].p; vector<vector<I>> jumps(n); for (Hund h : hunde) { jumps[h.x].push_back(h.p); } for (I i = 0; i < n; ++i) { sort(jumps[i].begin(), jumps[i].end()); jumps[i].erase(unique(jumps[i].begin(), jumps[i].end()), jumps[i].end()); } vector<vector<Kante>> graph(n); // for (I i = 0; i < m; ++i) { // // for (I j = 0; j < m; ++j) { // // if (i == j) continue; // // // if (hunde[i].x == hunde[j].x) { // // // graph[i].push_back({j, 0}); // // // } // // if (hunde[i].x % hunde[i].p == hunde[j].x % hunde[i].p) { // // graph[hunde[i].x].push_back( // // {hunde[j].x, abs(hunde[j].x - hunde[i].x) / hunde[i].p}); // // } // // } // } // cout << jumps << endl; for (I i = 0; i < n; ++i) { for (I c : jumps[i]) { for (I j = i - c; j >= 0; j -= c) { if (!jumps[j].empty()) { graph[i].push_back({j, (i - j) / c}); if (binary_search(jumps[j].begin(), jumps[j].end(), c)) break; } } for (I j = i + c; j < n; j += c) { if (!jumps[j].empty()) { graph[i].push_back({j, (j - i) / c}); if (binary_search(jumps[j].begin(), jumps[j].end(), c)) break; } } } } // for (auto i : graph) { // cout << i << endl; // } vector<I> abstand(n, inf); set<II, greater<II>> q; q.insert({0, hunde[0].x}); abstand[hunde[0].x] = 0; while (!q.empty()) { I d, i; tie(d, i) = *q.begin(), q.erase(q.begin()); abstand[i] = d; // cout << d << ' ' << i << '\n'; for (Kante k : graph[i]) { if (d + k.w < abstand[k.v]) { auto it = q.find({abstand[k.v], k.v}); if (it != q.end()) q.erase(it); abstand[k.v] = d + k.w; q.insert({d + k.w, k.v}); } } } // cout << abstand << '\n'; cout << (abstand[hunde[1].x] < inf ? abstand[hunde[1].x] : -1) << '\n'; #ifdef UNITEST cout.flush(); system("pause"); #endif return 0; }
22.41129
77
0.441526
Aleshkev
f98e0a3128c306d55a6d97920ada4995a182df1b
10,403
cpp
C++
src/protocols/NbIoTClient.cpp
tsi5/dt-arduino-iot-agent
91b6c63b9f2de9f9cd8ac6408d65613769455d8e
[ "MIT" ]
null
null
null
src/protocols/NbIoTClient.cpp
tsi5/dt-arduino-iot-agent
91b6c63b9f2de9f9cd8ac6408d65613769455d8e
[ "MIT" ]
null
null
null
src/protocols/NbIoTClient.cpp
tsi5/dt-arduino-iot-agent
91b6c63b9f2de9f9cd8ac6408d65613769455d8e
[ "MIT" ]
null
null
null
/** * @file NbiotClient.cpp * @description Abstracted Network interface of an NB-IoT Modem. * @author mm1 Technology GmbH * @copyright (C) 2017-2018 Deutsche Telekom AG- all rights reserved. * @licence MIT licence * * Code pieces based on Arduino WiFiClient and GIMASI TUINO example project(s): * Company: http://www.tuino.io/ * GitHub: https://github.com/gimasi */ #include "DTCoTSetup.h" #if CONN_TYPE == NB_IOT //#include "DbgSerialInit.h" extern "C" { // #include "utility/wl_definitions.h" // #include "utility/wl_types.h" #include "string.h" // #include "utility/debug.h" } // #include "WiFi.h" // #include "WiFiClient.h" // #include "WiFiServer.h" // #include "utility/server_drv.h" #include "utility/Regexp.h" #include "gmx_nbiot.h" #include "protocols/NbIoTClient.h" #include "DTCoTSetup.h" #include "utility/DTCoTDebugOutput.h" #define MAX_SOCK_NUM 0xFF uint16_t NbiotClient::_srcport = 1883; NbiotClient::NbiotClient( const String& ipAddress, Stream& dbgOutputStream /* default = Serial */) : _sock( MAX_SOCK_NUM) , _dbgOutputStream( dbgOutputStream) , _modemInitialized( false) , _serverIP( ipAddress) , _serial(Serial) , _resetPin(10) { //_dbgOutputStream.println("NbiotClient::NbiotClient():"); } /** * @brief Initialise / start modem here. */ NbiotClient::NbiotClient(uint8_t sock, Stream& dbgOutputStream /* default = Serial */) : _sock(sock) , _serial(Serial) , _resetPin(10) ,_dbgOutputStream( dbgOutputStream) { } NbiotClient::NbiotClient(const String& serverIP, const unsigned short& serverPort, const String& imsi , const String& password, Stream& serial , int resetPin, Stream& dbgOutputStream) : _serverIP(serverIP) , _serverPort(serverPort) , _imsi(imsi) , _password(password) , _serial(serial) , _resetPin(resetPin) , _dbgOutputStream( dbgOutputStream) { //_dbgOutputStream.println("NbiotClient::NbiotClient():"); //Serial.println("NbiotClient::NbiotClient():"); //delay(1000); } NbiotClient::NbiotClient(Stream& dbgOutputStream /* default = Serial */) : _dbgOutputStream( dbgOutputStream) , _serial(Serial) , _resetPin(10) { //Serial.println("NbiotClient::NbiotClient():"); } /** * @brief Dummy method which has to be there. Does nothing but return an error if called. * @note This function always returns an error, since NBIOT does not support host name resolution. Use IP addresses, instead. * @param host Host name * @param port Destination port. * @returns Returns always error code 0, since NBIOT cannot resolve host names. Use IP addresses, instead. */ int NbiotClient::connect(const char* host, uint16_t port) { // _dbgOutputStream.println("NbiotClient::connect(const char* host, uint16_t port)"); /*NOTE Do some stupid stuff to make the compiler happy. :-| */ host = host; port = port; /*Error: no host name resolution with NB-IoT*/ if( !_modemInitialized ) { _modemInitialized = initNBIoTModem(); if( !_modemInitialized ) { return 0; } } gmxNB_connect(_serverIP, _serverPort); _socket = gmxNB_SocketOpen(); return 0; } /** * @brief All UDP packets will be delivered to the remote host which is configured here. * @param ip Host IP address. * @param port Destination port. * @returns 1 if connected successfully, 0 on failure. */ int NbiotClient::connect(IPAddress ip, uint16_t port) { _dbgOutputStream.println( "NbiotClient::connect( ip=" + String( _serverIP) + ", port=" + String( _serverPort) + ")" ); if( !_modemInitialized ) { _modemInitialized = initNBIoTModem(); if( !_modemInitialized ) { return 0; } } gmxNB_connect(_serverIP, _serverPort); _socket = gmxNB_SocketOpen(); return 1; } /** * @brief Bytewise data transmission. * @note Will not be implemented (yet?). * @param b Byte to be transmitted. * @returns Always 0, because no data transmission is executed. */ size_t NbiotClient::write(uint8_t b) { _dbgOutputStream.println("NbiotClient::write(uint8_t b)"); if( !_modemInitialized ) { _modemInitialized = initNBIoTModem(); if( !_modemInitialized ) { return 0; } } /* TODO: Implement byte sending */ return 0; } /** * @brief Packet-wise data transmission. * @param buf Payload buffer to be sent. * @param size Number of bytes to be sent. * @returns Number of bytes that were sent. */ size_t NbiotClient::write(const uint8_t *buf, size_t size) { if( !_modemInitialized ) { _modemInitialized = initNBIoTModem(); if( !_modemInitialized ) { _dbgOutputStream.println( "NbiotClient::write(const uint8_t *buf, size_t size): ERROR: Failed to initialize the modem"); return 0; } } byte retval; /*TODO test if socket is already open!*/ retval = gmxNB_TXData((const char*)buf, size); if(retval == GMXNB_OK) { return size; } return 0; } /** * @brief Returns a value > 0 for a received / pending packet. * @fixme This implementation only counts characters received from the modem. It should * return the number of bytes pending to be read. * @returns 0 for no pending packet, >0 otherwise. */ int NbiotClient::available() { _dbgOutputStream.println("NbiotClient::available()"); return gmxNB_Available(); } /** * @brief Byte-wise read. * @note Will not be implemented (yet?). * @brief Always returns an error. */ int NbiotClient::read() { _dbgOutputStream.println("NbiotClient::read()"); /*TODO Implement byte-wise read operation. (not recommended though!)*/ return -1; } int NbiotClient::read(uint8_t* buf, size_t size) { _dbgOutputStream.println("NbiotClient::read(uint8_t* buf, size_t size)"); byte status; int _size = size; String remoteIp; int myUdpPort; /*TODO check if socket is active*/ status = gmxNB_RXData(_serverIP, _serverPort, (byte*)buf, _size); if( status != GMXNB_OK ) { _dbgOutputStream.println("NbiotClient::read(): Err CoT connection failed."); return -1; } else { return _size; } #if 0 // sizeof(size_t) is architecture dependent // but we need a 16 bit data type here uint16_t _size = size; gmxNB_RXData(); if (!ServerDrv::getDataBuf(_sock, buf, &_size)) return -1; return 0; #endif /*0*/ } int NbiotClient::peek() { _dbgOutputStream.println("NbiotClient::peek()"); return -1; #if 0 uint8_t b; if (!available()) return -1; NbiotClient::getData(_sock, &b, 1); return b; #endif /*0*/ } void NbiotClient::flush() { _dbgOutputStream.println("NbiotClient::flush()"); // TODO: a real check to ensure transmission has been completed } /** * @brief Stops the device. * @note Not yet implemented. Restart the system, instead. */ void NbiotClient::stop() { _dbgOutputStream.println("NbiotClient::stop()"); if (_sock == MAX_SOCK_NUM) return; _sock = MAX_SOCK_NUM; } uint8_t NbiotClient::connected() { _dbgOutputStream.println("NbiotClient::connected()"); if( !_modemInitialized) { return 0; } /* if (_sock == MAX_SOCK_NUM) { return 0; } */ return 1; #if 0 /*TODO encode connection state like this*/ uint8_t s = status(); return !(s == LISTEN || s == CLOSED || s == FIN_WAIT_1 || s == FIN_WAIT_2 || s == TIME_WAIT || s == SYN_SENT || s== SYN_RCVD || (s == CLOSE_WAIT)); } #endif /*0*/ } uint8_t NbiotClient::status() { _dbgOutputStream.println("NbiotClient::status()"); if (_sock == MAX_SOCK_NUM) { return 0; } else { return 1; } } NbiotClient::operator bool() { _dbgOutputStream.println("NbiotClient::operator bool()"); return _sock != MAX_SOCK_NUM; } // Private Methods uint8_t NbiotClient::getFirstSocket() { _dbgOutputStream.println("NbiotClient::getFirstSocket()"); return 0; } bool NbiotClient::initNBIoTModem() { // Init NB IoT board _dbgOutputStream.println("NbiotClient::initNBIoTModem(): Initializing modem ... "); byte initStatus = gmxNB_init( /*forceReset:*/ false, _serverIP, _serverPort, _serial, _resetPin, NULL ); if( ( initStatus != NB_NETWORK_JOINED) && ( initStatus != GMXNB_OK) ) { _dbgOutputStream.println(""); _dbgOutputStream.println("NbiotClient::initNBIoTModem(): ERROR: Failed to initialize modem"); return false; } _dbgOutputStream.println("NbiotClient::initNBIoTModem(): Modem initialized"); // _dbgOutputStream.println("NbiotClient::initNBIoTModem(): Collecting modem IMEI ... " ); String imeiInfo; if( gmxNB_getIMEI( imeiInfo) != GMXNB_OK ) { _dbgOutputStream.println(""); _dbgOutputStream.println("NbiotClient::initNBIoTModem(): ERROR: Failed to aquire modem IMEI"); return false; } _dbgOutputStream.println("NbiotClient::initNBIoTModem(): IMEI:" + imeiInfo); if (initStatus != NB_NETWORK_JOINED) { /* TODO: check for return code after it is implemented in the driver! */ _dbgOutputStream.println("NbiotClient::initNBIoTModem(): Configuring for DT network ... " ); gmxNB_startDT(); _dbgOutputStream.println("NbiotClient::initNBIoTModem(): Configured for DT network" ); } // _dbgOutputStream.println("NbiotClient::initNBIoTModem(): Aquiring IMSI ..." ); String testImsi; gmxNB_getIMSI(testImsi); /* TODO: * 1) check for return code after it is implemented in the driver! * 2) IMSI should also be used for athentication. */ _dbgOutputStream.println("NbiotClient::initNBIoTModem(): IMSI: " + testImsi); _dbgOutputStream.println("NbiotClient::initNBIoTModem(): Attempting to join the network ..." ); unsigned long netJoinRetryCounter = 0; for( ; netJoinRetryCounter < MAX_NETWORK_JOIN_RETRIES; netJoinRetryCounter++ ) { if( gmxNB_isNetworkJoined() == NB_NETWORK_JOINED) { break; } DTCoTNBIoTHardware_led(GMXNB_LED_ON, 2); delay(500); DTCoTNBIoTHardware_led(GMXNB_LED_OFF, 2); _dbgOutputStream.print("."); delay(2500); } _dbgOutputStream.println(""); if( netJoinRetryCounter >= MAX_NETWORK_JOIN_RETRIES) { _dbgOutputStream.println("NbiotClient::initNBIoTModem(): Failed to join network"); return false; } DTCoTNBIoTHardware_led(GMXNB_LED_ON, 2); _dbgOutputStream.println("NbiotClient::initNBIoTModem(): Successfuly joined the network"); _modemInitialized = true; return true; } int NbiotClient::init() { /* if( !_modemInitialized ) { _modemInitialized = initNBIoTModem(); if( !_modemInitialized ) { _dbgOutputStream.println( "NbiotClient::init(): ERROR: Failed to initialize the modem"); return 0; } } */ } #endif
22.468683
125
0.693165
tsi5
f993dab3d081da54019c85b7586d050757c2aeed
3,606
cpp
C++
Engine/Graphics/GL/GLFramebuffer.cpp
guimeixen/Engine
fcea39d2099b613b32b20462586e1c932bbb24fc
[ "MIT" ]
null
null
null
Engine/Graphics/GL/GLFramebuffer.cpp
guimeixen/Engine
fcea39d2099b613b32b20462586e1c932bbb24fc
[ "MIT" ]
17
2021-03-12T18:19:07.000Z
2021-08-06T21:25:35.000Z
Engine/Graphics/GL/GLFramebuffer.cpp
guimeixen/Engine
fcea39d2099b613b32b20462586e1c932bbb24fc
[ "MIT" ]
null
null
null
#include "GLFramebuffer.h" #include "GLTexture2D.h" #include <iostream> namespace Engine { GLFramebuffer::GLFramebuffer(const FramebufferDesc &desc) { width = desc.width; height = desc.height; useColor = desc.colorTextures.size() > 0; useDepth = desc.useDepth; colorOnly = useColor && !useDepth; writesDisabled = desc.writesDisabled; if (!desc.writesDisabled) Create(desc); } GLFramebuffer::~GLFramebuffer() { Dispose(); } void GLFramebuffer::Resize(const FramebufferDesc &desc) { if (desc.width == width && desc.height == height) return; if (writesDisabled) return; if (id > 0) Dispose(); width = desc.width; height = desc.height; Create(desc); } void GLFramebuffer::Clear() const { glClear(clearMask); } void GLFramebuffer::Bind() const { glBindFramebuffer(GL_FRAMEBUFFER, id); } void GLFramebuffer::SetDefault(int width, int height, int x, int y) { glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void GLFramebuffer::Create(const FramebufferDesc &desc) { colorAttachments.resize(desc.colorTextures.size()); for (size_t i = 0; i < desc.colorTextures.size(); i++) { FramebufferAttachment attachment = {}; attachment.params = desc.colorTextures[i]; colorAttachments[i] = attachment; } depthAttachment = {}; depthAttachment.params = desc.depthTexture; depthAttachment.texture = nullptr; glGenFramebuffers(1, &id); glBindFramebuffer(GL_FRAMEBUFFER, id); if (useColor) { std::vector<GLuint> attachments(colorAttachments.size()); for (size_t i = 0; i < colorAttachments.size(); i++) { colorAttachments[i].texture = new GLTexture2D(width, height, colorAttachments[i].params); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, colorAttachments[i].texture->GetID(), 0); attachments[i] = GL_COLOR_ATTACHMENT0 + i; } glDrawBuffers(attachments.size(), attachments.data()); } else { glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); } // Only create the depth attachment if we're not color only framebuffer if (desc.sampleDepth) { depthAttachment.texture = new GLTexture2D(width, height, depthAttachment.params); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthAttachment.texture->GetID(), 0); } else if (useDepth) { glGenRenderbuffers(1, &rboID); glBindRenderbuffer(GL_RENDERBUFFER, rboID); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height); glBindRenderbuffer(GL_RENDERBUFFER, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rboID); } GLenum fboStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (fboStatus != GL_FRAMEBUFFER_COMPLETE) { std::cout << "Framebuffer not complete: " << fboStatus << "\n"; } else { if (colorOnly) { clearMask = GL_COLOR_BUFFER_BIT; } else if (useColor && useDepth) { clearMask = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT; } else if (useDepth) { clearMask = GL_DEPTH_BUFFER_BIT; } } glBindFramebuffer(GL_FRAMEBUFFER, 0); } void GLFramebuffer::Dispose() { if (id > 0) glDeleteFramebuffers(1, &id); for (size_t i = 0; i < colorAttachments.size(); i++) { colorAttachments[i].texture->RemoveReference(); } colorAttachments.clear(); if (useDepth) { if (depthAttachment.texture) { depthAttachment.texture->RemoveReference(); } } else if (rboID > 0) glDeleteRenderbuffers(1, &rboID); } }
22.122699
125
0.698835
guimeixen
f9949649440e24b8481b68d528970f8e90286460
2,674
cpp
C++
car/src/main.cpp
ian7/automation
3fa4bc456c58d5c1c4d24050ff9f58a41fb6143c
[ "MIT" ]
1
2019-06-30T04:21:08.000Z
2019-06-30T04:21:08.000Z
car/src/main.cpp
ian7/automation
3fa4bc456c58d5c1c4d24050ff9f58a41fb6143c
[ "MIT" ]
null
null
null
car/src/main.cpp
ian7/automation
3fa4bc456c58d5c1c4d24050ff9f58a41fb6143c
[ "MIT" ]
null
null
null
#include <Servo.h> //#include <MQTTClient.h> #include <ESP8266WiFi.h> #include <wifi-password.h> #include <PubSubClient.h> WiFiClient net; PubSubClient client(net); //MQTTClient client; Servo servo; void publish( const String &topic, const String &payload){ unsigned char topicChars[100]; unsigned char payloadChars[100]; topic.getBytes(topicChars,100); payload.getBytes(payloadChars,100); client.publish((char *) topicChars, (char *) payloadChars);//,false,1); } void messageReceived(const String topic, const String payload) { if (topic == String("/car/steering")) { int steering = payload.toInt(); servo.write(steering); //publish("/car/ack", "steering: " + String(steering)); } if (topic == String("/car/horn")) { if( payload == String("on") ){ digitalWrite(10,HIGH); } if( payload == String("off") ){ digitalWrite(10,LOW); } // publish("/car/ack", "horn: " + payload); } if (topic == String("/car/drive")) { int speed = payload.toInt(); //publish("/car/ack", "drive: " + String(speed)); if (speed > 0) { digitalWrite(0, LOW); analogWrite(5, speed); } else { digitalWrite(0, HIGH); analogWrite(5, -speed); } } } void connect() { while (WiFi.status() != WL_CONNECTED) { delay(200); } while (!client.connect("car")) { delay(200); } client.subscribe("/car/drive", 1); client.subscribe("/car/steering", 1); client.subscribe("/car/horn", 1); } void pubSubCallback(char* topic, byte* payload, unsigned int length){ String payloadString = String((char*)payload).substring(0,length); String topicString = String(topic); messageReceived(topicString, payloadString); } void setup() { WiFi.mode(WIFI_STA); WiFi.begin(ssid, pass); pinMode(0, OUTPUT); pinMode(10, OUTPUT); //client.begin("10.10.4.1", net); //client.onMessage(messageReceived); client.setServer("10.10.4.1",1883); client.setCallback(pubSubCallback); connect(); servo.attach(2); } void loop() { while (true) { delay(50); client.loop(); if (!client.connected()) { connect(); } } /* delay(1000); analogWrite(5, 1020); delay(1000); analogWrite(5, 700); delay(1000); analogWrite(5, 0); digitalWrite(0, 0); delay(1000); servo.write(0); delay(1000); delay(1000); analogWrite(5, 700); delay(1000); analogWrite(5, 1020); delay(1000); analogWrite(5, 700); delay(1000); analogWrite(5, 0); digitalWrite(0, 1); */ }
20.412214
76
0.586387
ian7
f999923cdcb904572d274db7830e5d07966fec65
1,461
cpp
C++
uiSamusEditorClass.cpp
interdpth/DoubleHelix-2
d494cc7957b7470b12779d2cde14b13285fa6396
[ "MIT" ]
1
2021-11-23T13:57:03.000Z
2021-11-23T13:57:03.000Z
uiSamusEditorClass.cpp
interdpth/DoubleHelix-2
d494cc7957b7470b12779d2cde14b13285fa6396
[ "MIT" ]
null
null
null
uiSamusEditorClass.cpp
interdpth/DoubleHelix-2
d494cc7957b7470b12779d2cde14b13285fa6396
[ "MIT" ]
1
2021-11-12T22:47:58.000Z
2021-11-12T22:47:58.000Z
#include "uiSamusEditorClass.h" SamusEditorClass::SamusEditorClass() { SamusEditorClass::hwndSamusEditor = NULL; hwndSamusSpritePreview = NULL; SpritePreview = new SpriteObject(); } SamusEditorClass::~SamusEditorClass() { delete SpritePreview; } HWND SamusEditorClass::hwndSamusEditor; int SamusEditorClass::SetupSamusPreview(SamusBase* base) { long PalPnt = 0; long palsize = 0; long addybuf = 0; long size = 0; int i = 0; int ii = 0; //unsigned char* compBuffer = new unsigned char[64691]; //GBAMethods* GBA = new GBAMethods(); //unsigned char* decompbuf = new unsigned char[32687]; //unsigned short transferpal[256] = { 0 }; int X = 0; long off = 0; int x = 0; SpritePreview = base->theSprite; // // GBA->DecodePal((short*)base->Suit_color, SpritePreview->PreviewPal, 16, 0); // // memcpy(SpritePreview->PreRAM, base->Sprite_tiles, 0x8000); // // SpritePreview->OAM.clear(); // //SpritePreview->maxparts = 0; //// SpritePreview->OAM.clear(); // i = 0; // for (i = 0; i < base->theSprite->maxparts; i++) SpritePreview->OAM.push_back(base->theSprite->OAM[i]); // SpritePreview->maxparts = i; // // SpritePreview->id = 0xFF; // // //RD1Engine::theGame->mgrOAM->DecodeOAM(GBA->ROM, true, SpritePreview,(unsigned long) base->SamusOAMPointer - 0x8000000); // SpritePreview->PreviewSprite.GetFullImage()->Clear(); // RD1Engine::theGame->mgrOAM->DrawPSprite(SpritePreview); // // delete[] compBuffer; // delete[] decompbuf; return 0; }
24.35
124
0.698152
interdpth
f99bac824a04f3f81c082047b29090259e4ff352
1,255
hpp
C++
multimodalmaze/domains/mazeDomain/simulator/libfastsim/src/light_sensor.hpp
alexander-hagg/phdexperiments
6506c8f2a438c67ca7c808df8715711fde73dfce
[ "MIT" ]
null
null
null
multimodalmaze/domains/mazeDomain/simulator/libfastsim/src/light_sensor.hpp
alexander-hagg/phdexperiments
6506c8f2a438c67ca7c808df8715711fde73dfce
[ "MIT" ]
null
null
null
multimodalmaze/domains/mazeDomain/simulator/libfastsim/src/light_sensor.hpp
alexander-hagg/phdexperiments
6506c8f2a438c67ca7c808df8715711fde73dfce
[ "MIT" ]
null
null
null
#ifndef FASTSIM_LIGHT_SENSOR_HPP_ #define FASTSIM_LIGHT_SENSOR_HPP_ #include <boost/shared_ptr.hpp> #include "posture.hpp" #include "map.hpp" namespace fastsim { /// detect an colored illuminated switch in the given direction /// (angle) and within the angular range. There is no range limit. /// light sensors DONT'T SEE TROUGH OBSTACLES class LightSensor { public: LightSensor(int color, float angle, float range) : _color(color), _angle(angle), _range(range), _activated(false), _num(0), _distance(-1) { // std::cout<<"angle="<<angle<<" range="<<range<<std::endl; } int update(const Posture& pos, const boost::shared_ptr<Map>& map); int get_color() const { return _color; } float get_angle() const { return _angle; } float get_range() const { return _range; } bool get_activated() const { return _activated; } unsigned int get_num() const {return _num;} float get_distance() const { return _distance; } protected: // the "color" (i.e. light identifier) detected int _color; // float _angle; // float _range; // bool _activated; // sensor number (for display only) unsigned int _num; // float _distance; }; } #endif
27.282609
70
0.654183
alexander-hagg
390003e0d62e9bcd1b06bc2c06a1e689e01e9083
7,732
cpp
C++
games/2048/2048.cpp
Lenzebo/mcts_solver
c434a3024fb7b37ef9e7a4fb12985fb89110a350
[ "MIT" ]
null
null
null
games/2048/2048.cpp
Lenzebo/mcts_solver
c434a3024fb7b37ef9e7a4fb12985fb89110a350
[ "MIT" ]
null
null
null
games/2048/2048.cpp
Lenzebo/mcts_solver
c434a3024fb7b37ef9e7a4fb12985fb89110a350
[ "MIT" ]
null
null
null
#include "2048.h" namespace g2048 { std::ostream& G2048State::writeToStream(std::ostream& stream) const // NOLINT(readability-identifier-naming) { stream << board(); return mcts::State<G2048State>::writeToStream(stream); } bool G2048State::empty(size_t x, size_t y) const { auto value = 1 << board(x, y); return value == 1; } bool G2048State::operator==(const G2048State& rhs) const { return board_ == rhs.board_ && nextIsChance_ == rhs.nextIsChance_; } bool G2048State::operator!=(const G2048State& rhs) const { return !(rhs == *this); } std::string G2048Problem::actionToString(const StateType& state, const ActionType& action) const // NOLINT { switch (action) { case UP: return "UP"; case LEFT: return "LEFT"; case RIGHT: return "RIGHT"; case DOWN: return "DOWN"; } return Problem::actionToString(state, action); } mcts::StageType G2048Problem::getNextStageType(const G2048State& state) { if (state.isChanceNext()) { return mcts::StageType::CHANCE; } else { return mcts::StageType::DECISION; } } /** * Should return a list of all possible actions for this player */ [[nodiscard]] zbo::MaxSizeVector<Actions, 4> G2048Problem::getAvailableActions(const G2048State& state) const { if (state.isChanceNext()) { return {}; } zbo::MaxSizeVector<Actions, 4> retval{}; auto can = canMove(state); if (can.up) { retval.push_back(UP); } if (can.left) { retval.push_back(LEFT); } if (can.right) { retval.push_back(RIGHT); } if (can.down) { retval.push_back(DOWN); } return retval; }; /** * Should return a list of all possible chance events with probability */ [[nodiscard]] zbo::MaxSizeVector<std::pair<float, ChanceEvent>, NUM_CELLS * 2> G2048Problem::getAvailableChanceEvents( const G2048State& state) const { zbo::MaxSizeVector<std::pair<float, ChanceEvent>, NUM_CELLS * 2> retval; if (!state.isChanceNext()) { return retval; } size_t numEmpty = countEmptyCells(state); const float probabilityPerCell = 1 / float(numEmpty); for (uint8_t x = 0; x < BOARD_DIMS; ++x) { for (uint8_t y = 0; y < BOARD_DIMS; ++y) { if (state.board(x, y) == 0) { retval.push_back(std::make_pair(probabilityPerCell * PROBABILITY_SPAWN_2, ChanceEvent{x, y, 1})); retval.push_back(std::make_pair(probabilityPerCell * PROBABILITY_SPAWN_4, ChanceEvent{x, y, 2})); } } } return retval; }; /** * Apply the action to the gamestate. Gamestate will be changed with this */ ProblemDefinition::ValueVector G2048Problem::performChanceEvent(const ChanceEventType event, G2048State& state) const { assert(state.isChanceNext()); state.setNextChance(false); assert(state.board(event.x, event.y) == 0); state.setBoard(event.x, event.y, event.value); return {}; } /** * Apply the action to the gamestate. Gamestate will be changed with this */ ProblemDefinition::ValueVector G2048Problem::performAction(const ActionType action, G2048State& state) const { assert(!state.isChanceNext()); ValueVector retval{0}; int start = 0; int end = 0; int increment = 1; bool upDown = (action == UP || action == DOWN); switch (action) { case UP: start = 0; end = BOARD_DIMS; break; case LEFT: start = 0; end = BOARD_DIMS; break; case RIGHT: start = BOARD_DIMS - 1; increment = -1; end = -1; break; case DOWN: start = BOARD_DIMS - 1; increment = -1; end = -1; break; } size_t numUpdatedCells = 0; for (size_t otherdim = 0; otherdim < BOARD_DIMS; otherdim++) { for (int xy = start; xy != end; xy += increment) { const size_t x = upDown ? otherdim : xy; const size_t y = upDown ? xy : otherdim; bool changed = false; for (int xyd = xy + increment; xyd != end; xyd += increment) { const size_t xd = upDown ? otherdim : xyd; const size_t yd = upDown ? xyd : otherdim; if (state.board(xd, yd) == 0) { continue; } if (state.board(x, y) == 0) { state.setBoard(x, y, state.board(xd, yd)); numUpdatedCells++; state.setBoard(xd, yd, 0); numUpdatedCells++; changed = true; break; } else if (state.board(x, y) == state.board(xd, yd)) { state.setBoard(x, y, state.board(x, y) + 1); numUpdatedCells++; retval += 1U << state.board(xd, yd); state.setBoard(xd, yd, 0); numUpdatedCells++; break; } else { break; } } if (changed) { xy -= increment; } } } const bool didChangeAnyCell = numUpdatedCells > 0; state.setNextChance(didChangeAnyCell); return retval; } ProblemDefinition::ValueVector G2048Problem::performRandomChanceEvent(G2048State& state) const { addRandomElement(state); return {}; } ProblemDefinition::ValueVector G2048Problem::performRandomAction(G2048State& state) const { auto actions = getAvailableActions(state); auto ac = actions[engine_() % actions.size()]; return performAction(ac, state); } [[nodiscard]] bool G2048Problem::isTerminal(const G2048State& state) const { auto can = canMove(state); return !state.isChanceNext() && !can.any(); } G2048Problem::CanMove G2048Problem::canMove(const G2048State& state) const { G2048Problem::CanMove retval{}; for (size_t x = 0; x < BOARD_DIMS; ++x) { for (size_t y = 0; y < BOARD_DIMS; ++y) { auto c = state.board(x, y); if (x < BOARD_DIMS - 1) { auto cright = state.board(x + 1, y); if (cright > 0 && (c == 0 || c == cright)) { retval.left = true; } if (c > 0 && (cright == 0 || c == cright)) { retval.right = true; } } if (y < BOARD_DIMS - 1) { auto cbelow = state.board(x, y + 1); if (cbelow > 0 && (c == 0 || c == cbelow)) { retval.up = true; } if (c > 0 && (cbelow == 0 || c == cbelow)) { retval.down = true; } } if (retval.all()) { return retval; } } } return retval; } [[nodiscard]] size_t G2048Problem::countEmptyCells(const G2048State& state) const { return state.board().numEmpty(); } void G2048Problem::addRandomElement(G2048State& state) const { assert(state.isChanceNext()); state.setNextChance(false); size_t numEmpty = countEmptyCells(state); assert(numEmpty > 0); std::uniform_int_distribution<size_t> dist(0, numEmpty - 1); size_t randNum = dist(engine_); for (uint8_t x = 0; x < BOARD_DIMS; ++x) { for (uint8_t y = 0; y < BOARD_DIMS; ++y) { if (state.board(x, y) != 0) { continue; } if (randNum == 0) { if (bernoulli_(engine_)) { state.setBoard(x, y, 1); } else { state.setBoard(x, y, 2); } return; } randNum--; } } assert(false); } } // namespace g2048
28.958801
118
0.547206
Lenzebo
39013fa1535bcf51ce6f841f810e6c9881b13c04
707
hpp
C++
library/ATF/__helper_attributes__v1_alttypeAttribute.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/__helper_attributes__v1_alttypeAttribute.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/__helper_attributes__v1_alttypeAttribute.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> START_ATF_NAMESPACE namespace vc_attributes { namespace helper_attributes { template<> struct v1_alttypeAttribute { template<> enum type_e { eBoolean = 0x0, eInteger = 0x1, eFloat = 0x2, eDouble = 0x3, }; type_e type; }; }; // end namespace helper_attributes }; // end namespace vc_attributes END_ATF_NAMESPACE
25.25
108
0.502122
lemkova
390e17505f5f68e50831c9b3588e874e958a0b2f
449
cpp
C++
Hackerrank/Hourrank 25/A.cpp
itsmevanessi/Competitive-Programming
e14208c0e0943d0dec90757368f5158bb9c4bc17
[ "MIT" ]
null
null
null
Hackerrank/Hourrank 25/A.cpp
itsmevanessi/Competitive-Programming
e14208c0e0943d0dec90757368f5158bb9c4bc17
[ "MIT" ]
null
null
null
Hackerrank/Hourrank 25/A.cpp
itsmevanessi/Competitive-Programming
e14208c0e0943d0dec90757368f5158bb9c4bc17
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int sumOfDigitsOfN(int n){ int sum = 0; while(n){ sum += (n % 10); n /= 10; } return sum; } int main(void){ int testcases, n, x, sumOfDigits; scanf("%d", &testcases); while(testcases--){ sumOfDigits = 0; scanf("%d", &n); while(n --){ scanf("%d", &x); sumOfDigits += sumOfDigitsOfN(x); } if(sumOfDigits % 3)puts("No"); else puts("Yes"); } }
16.035714
39
0.532294
itsmevanessi
390f9496f72b5fd4c8acbf4fa85134a035ae5136
1,399
hpp
C++
unittests/general/Several/bin/firebird/include/firebird/impl/boost/preprocessor/control/iif.hpp
jiemurat/delphimvcframework
6bfa63b85a2e4ce3ba03fc4df11d2ed654021e54
[ "Apache-2.0" ]
1,009
2015-05-28T12:34:39.000Z
2022-03-30T14:10:18.000Z
unittests/general/Several/bin/firebird/include/firebird/impl/boost/preprocessor/control/iif.hpp
jiemurat/delphimvcframework
6bfa63b85a2e4ce3ba03fc4df11d2ed654021e54
[ "Apache-2.0" ]
574
2016-03-23T15:35:56.000Z
2022-03-31T07:11:03.000Z
unittests/general/Several/bin/firebird/include/firebird/impl/boost/preprocessor/control/iif.hpp
jiemurat/delphimvcframework
6bfa63b85a2e4ce3ba03fc4df11d2ed654021e54
[ "Apache-2.0" ]
377
2015-05-28T16:29:21.000Z
2022-03-21T18:36:12.000Z
# /* ************************************************************************** # * * # * (C) Copyright Paul Mensonides 2002. # * 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) # * * # ************************************************************************** */ # # /* See http://www.boost.org for most recent version. */ # # ifndef FB_BOOST_PREPROCESSOR_CONTROL_IIF_HPP # define FB_BOOST_PREPROCESSOR_CONTROL_IIF_HPP # # include <firebird/impl/boost/preprocessor/config/config.hpp> # # if ~FB_BOOST_PP_CONFIG_FLAGS() & FB_BOOST_PP_CONFIG_MWCC() # define FB_BOOST_PP_IIF(bit, t, f) FB_BOOST_PP_IIF_I(bit, t, f) # else # define FB_BOOST_PP_IIF(bit, t, f) FB_BOOST_PP_IIF_OO((bit, t, f)) # define FB_BOOST_PP_IIF_OO(par) FB_BOOST_PP_IIF_I ## par # endif # # if ~FB_BOOST_PP_CONFIG_FLAGS() & FB_BOOST_PP_CONFIG_MSVC() # define FB_BOOST_PP_IIF_I(bit, t, f) FB_BOOST_PP_IIF_ ## bit(t, f) # else # define FB_BOOST_PP_IIF_I(bit, t, f) FB_BOOST_PP_IIF_II(FB_BOOST_PP_IIF_ ## bit(t, f)) # define FB_BOOST_PP_IIF_II(id) id # endif # # define FB_BOOST_PP_IIF_0(t, f) f # define FB_BOOST_PP_IIF_1(t, f) t # # endif
39.971429
90
0.558971
jiemurat