hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
46192fd5c256d3617f496bcb3fad21959dbb54f8
1,769
cpp
C++
vlc_linux/vlc-3.0.16/modules/gui/skins2/commands/cmd_playtree.cpp
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
vlc_linux/vlc-3.0.16/modules/gui/skins2/commands/cmd_playtree.cpp
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
vlc_linux/vlc-3.0.16/modules/gui/skins2/commands/cmd_playtree.cpp
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
/***************************************************************************** * cmd_playtree.cpp ***************************************************************************** * Copyright (C) 2005 the VideoLAN team * $Id: 626ba09b03156290eba9bc3bb654ec031a8f75de $ * * Authors: Antoine Cellerier <dionoea@videolan.org> * Clément Stenac <zorglub@videolan.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "cmd_playtree.hpp" #include <vlc_playlist.h> #include "../src/vlcproc.hpp" #include "../utils/var_bool.hpp" void CmdPlaytreeDel::execute() { m_rTree.delSelected(); } void CmdPlaytreeSort::execute() { /// \todo Choose sort method/order - Need more commands /// \todo Choose the correct view playlist_t *p_playlist = getPL(); PL_LOCK; playlist_RecursiveNodeSort( p_playlist, &p_playlist->root, SORT_TITLE, ORDER_NORMAL ); PL_UNLOCK; // Ask for rebuild VlcProc::instance( getIntf() )->getPlaytreeVar().onChange(); }
36.854167
79
0.616167
Brook1711
461a10273aba9fcf0e0d3aa55bec17e788550bae
271
cpp
C++
Test/run-test.cpp
As-12/Header-only-skeleton
17603f3ef8c1808000213d8f12a7f6271c15de25
[ "MIT" ]
null
null
null
Test/run-test.cpp
As-12/Header-only-skeleton
17603f3ef8c1808000213d8f12a7f6271c15de25
[ "MIT" ]
null
null
null
Test/run-test.cpp
As-12/Header-only-skeleton
17603f3ef8c1808000213d8f12a7f6271c15de25
[ "MIT" ]
null
null
null
// AllTests.cpp #include <gtest/gtest.h> #include <Library/Framework.hpp> TEST(SubtractTest1, SubtractTwoNumbers) { Library::print(); EXPECT_EQ(5, 5); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
15.055556
41
0.675277
As-12
461aa61039c0c41d53644a5192d06be4b61e2968
210
cpp
C++
266. Palindrome Permutation.cpp
rajeev-ranjan-au6/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
3
2020-12-30T00:29:59.000Z
2021-01-24T22:43:04.000Z
266. Palindrome Permutation.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
266. Palindrome Permutation.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
class Solution { public: bool canPermutePalindrome(string s) { unordered_map<char, int>m; int odd = 0; for(auto c: s) (m[c]++ % 2) ? odd-- : odd++; return odd <= 1; } };
21
52
0.504762
rajeev-ranjan-au6
462041eb825084ccf615b4abf767bd7c7a37acd1
520
cpp
C++
Engine/Source/Core/Types/Time.cpp
SparkyPotato/Ignis
40cf87c03db7c07d3a05ab2c30bbe4fe3b16156c
[ "MIT" ]
1
2021-02-27T15:42:47.000Z
2021-02-27T15:42:47.000Z
Engine/Source/Core/Types/Time.cpp
SparkyPotato/Ignis
40cf87c03db7c07d3a05ab2c30bbe4fe3b16156c
[ "MIT" ]
null
null
null
Engine/Source/Core/Types/Time.cpp
SparkyPotato/Ignis
40cf87c03db7c07d3a05ab2c30bbe4fe3b16156c
[ "MIT" ]
null
null
null
/// Copyright (c) 2021 Shaye Garg. #include "Core/Types/Time.h" #include "Core/Platform/Platform.h" #ifdef PLATFORM_WINDOWS # include <Windows.h> #endif namespace Ignis { #ifdef PLATFORM_WINDOWS Time Time::Now() { SYSTEMTIME time; GetLocalTime(&time); return Time{ .Year = time.wYear, .Month = u8(time.wMonth), .Day = u8(time.wDay), .WeekDay = u8(time.wDayOfWeek), .Hour = u8(time.wHour), .Minute = u8(time.wMinute), .Millisecond = time.wMilliseconds }; } #else Time Time::Now() { } #endif }
13.684211
38
0.667308
SparkyPotato
46222bf791ebd8f20bf205a35de1fc7d309e10da
1,485
cpp
C++
src/VKHelpers/Command/bindings.cpp
hiradyazdan/sdf-ray4d-engine
d71385e23cb630c54ff620ba1dff287ad90861b8
[ "MIT" ]
2
2021-09-28T22:15:44.000Z
2022-02-03T22:25:46.000Z
src/VKHelpers/Command/bindings.cpp
hiradyazdan/sdf-ray4d-engine
d71385e23cb630c54ff620ba1dff287ad90861b8
[ "MIT" ]
null
null
null
src/VKHelpers/Command/bindings.cpp
hiradyazdan/sdf-ray4d-engine
d71385e23cb630c54ff620ba1dff287ad90861b8
[ "MIT" ]
null
null
null
/***************************************************** * Partial Class: CommandHelper * Members: Command Buffer Bindings/Overloads (Private) *****************************************************/ #include "VKHelpers/Command.hpp" using namespace sdfRay4d::vkHelpers; /** * * @param[in] _material */ void CommandHelper::executeCmdBind( const MaterialPtr &_material ) noexcept { m_deviceFuncs->vkCmdBindPipeline( m_cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, _material->pipeline ); device::Size vbOffset = 0; m_deviceFuncs->vkCmdBindVertexBuffers( m_cmdBuffer, 0, 1, &_material->buffer, &vbOffset ); const auto &descSets = _material->descSets; const auto &descSetCount = descSets.size(); // the dynamic buffer points to the beginning of the vertex uniform data for the current frame. const uint32_t frameDynamicOffset = m_frameId * vbOffset; std::vector<uint32_t> frameDynamicOffsets = {}; // memset for(auto i = 0; i < descSetCount; i++) { for (auto j = 0; j < _material->dynamicDescCount; j++) { frameDynamicOffsets.push_back(frameDynamicOffset); } const auto &dynamicOffsetCount = frameDynamicOffsets.size(); m_deviceFuncs->vkCmdBindDescriptorSets( m_cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, _material->pipelineLayout, i, descSetCount, &descSets[i], dynamicOffsetCount, dynamicOffsetCount > 0 ? frameDynamicOffsets.data() : nullptr ); } }
25.169492
97
0.648485
hiradyazdan
4624a63178202e6ae40f52aa49966a55347aa1d5
389
cpp
C++
src/lib/output/buzzer.cpp
aescariom/In3
0e6adcca3492bc69912170bf9a39719a407873c4
[ "MIT" ]
3
2016-09-23T18:11:32.000Z
2021-05-31T20:50:47.000Z
src/lib/output/buzzer.cpp
aescariom/In3
0e6adcca3492bc69912170bf9a39719a407873c4
[ "MIT" ]
1
2016-09-23T18:14:32.000Z
2016-10-08T21:11:14.000Z
src/lib/output/buzzer.cpp
aescariom/In3
0e6adcca3492bc69912170bf9a39719a407873c4
[ "MIT" ]
1
2017-03-24T19:30:43.000Z
2017-03-24T19:30:43.000Z
#include "buzzer.h" Buzzer::Buzzer(volatile uint8_t *port, volatile uint8_t *dir, uint8_t mask){ this->port = port; this->dir = dir; this->mask = mask; } void Buzzer::init(){ *(this->dir) |= 1 << this->mask; // output pin } void Buzzer::beep(){ this->toggle(); _delay_ms(_O_BUZZER_DELAY_MS); this->toggle(); } void Buzzer::toggle(){ *(this->port) ^= (1 << this->mask); }
17.681818
76
0.619537
aescariom
4624bd768a1ee740003c4667e258e09558e94c5b
4,891
cpp
C++
Math/Generating Function of a Linear Recurrence.cpp
bazzyadb/all-code
cf3039641b5aa84b1c5b184a95d69bd4091974c9
[ "MIT" ]
1,639
2021-09-15T09:12:06.000Z
2022-03-31T22:58:57.000Z
Math/Generating Function of a Linear Recurrence.cpp
bazzyadb/all-code
cf3039641b5aa84b1c5b184a95d69bd4091974c9
[ "MIT" ]
16
2022-01-15T17:50:08.000Z
2022-01-28T12:55:21.000Z
Math/Generating Function of a Linear Recurrence.cpp
bazzyadb/all-code
cf3039641b5aa84b1c5b184a95d69bd4091974c9
[ "MIT" ]
444
2021-09-15T09:17:41.000Z
2022-03-29T18:21:46.000Z
#include<bits/stdc++.h> using namespace std; const int N = 3e3 + 9, mod = 998244353; template <int32_t MOD> struct modint { int32_t value; modint() = default; modint(int32_t value_) : value(value_) {} inline modint<MOD> operator + (modint<MOD> other) const { int32_t c = this->value + other.value; return modint<MOD>(c >= MOD ? c - MOD : c); } inline modint<MOD> operator - (modint<MOD> other) const { int32_t c = this->value - other.value; return modint<MOD>(c < 0 ? c + MOD : c); } inline modint<MOD> operator * (modint<MOD> other) const { int32_t c = (int64_t)this->value * other.value % MOD; return modint<MOD>(c < 0 ? c + MOD : c); } inline modint<MOD> & operator += (modint<MOD> other) { this->value += other.value; if (this->value >= MOD) this->value -= MOD; return *this; } inline modint<MOD> & operator -= (modint<MOD> other) { this->value -= other.value; if (this->value < 0) this->value += MOD; return *this; } inline modint<MOD> & operator *= (modint<MOD> other) { this->value = (int64_t)this->value * other.value % MOD; if (this->value < 0) this->value += MOD; return *this; } inline modint<MOD> operator - () const { return modint<MOD>(this->value ? MOD - this->value : 0); } modint<MOD> pow(uint64_t k) const { modint<MOD> x = *this, y = 1; for (; k; k >>= 1) { if (k & 1) y *= x; x *= x; } return y; } modint<MOD> inv() const { return pow(MOD - 2); } // MOD must be a prime inline modint<MOD> operator / (modint<MOD> other) const { return *this * other.inv(); } inline modint<MOD> operator /= (modint<MOD> other) { return *this *= other.inv(); } inline bool operator == (modint<MOD> other) const { return value == other.value; } inline bool operator != (modint<MOD> other) const { return value != other.value; } inline bool operator < (modint<MOD> other) const { return value < other.value; } inline bool operator > (modint<MOD> other) const { return value > other.value; } }; template <int32_t MOD> modint<MOD> operator * (int64_t value, modint<MOD> n) { return modint<MOD>(value) * n; } template <int32_t MOD> modint<MOD> operator * (int32_t value, modint<MOD> n) { return modint<MOD>(value % MOD) * n; } template <int32_t MOD> istream & operator >> (istream & in, modint<MOD> &n) { return in >> n.value; } template <int32_t MOD> ostream & operator << (ostream & out, modint<MOD> n) { return out << n.value; } using mint = modint<mod>; vector<mint> BerlekampMassey(vector<mint> S) { int n = (int)S.size(), L = 0, m = 0; vector<mint> C(n), B(n), T; C[0] = B[0] = 1; mint b = 1; for(int i = 0; i < n; i++) { ++m; mint d = S[i]; for(int j = 1; j <= L; j++) d += C[j] * S[i - j]; if (d == 0) continue; T = C; mint coef = d * b.inv(); for(int j = m; j < n; j++) C[j] -= coef * B[j - m]; if (2 * L > i) continue; L = i + 1 - L; B = T; b = d; m = 0; } C.resize(L + 1); C.erase(C.begin()); for(auto &x: C) x *= -1; return C; } // a[k] = c[0] * a[k - 1] + c[1] * a[k - 2] + ... for k >= n mint yo(vector<mint> a, vector<mint> c) { int n = a.size(); if (!n) return 0; vector<mint> p(n + 1, 0); p[0] = 1; for (int i = 0; i < n; i++) { p[i + 1] = -c[i]; } vector<mint> up(n + n, 0); for (int i = 0; i < n; i++) { for (int j = 0; j <= n; j++) { up[i + j] += a[i] * p[j]; } } up.resize(n); // generating function of the recurrence is up / p // now find its derivative and find the value at x = 1 mint v = 0; for (int i = 0; i < p.size(); i++) { v += p[i]; } mint u = 0; for (int i = 0; i < up.size(); i++) { u += up[i]; } mint du = 0; for (int i = 0; i < up.size(); i++) { du += up[i] * i; } mint dv = 0; for (int i = 0; i < p.size(); i++) { dv += p[i] * i; } return (v * du - u * dv) / (v * v); } mint dp[N * 2][N]; vector<int> g[N]; int deg[N]; mint ideg[N]; int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; cin >> n; for (int i = 1; i <= n; i++) { int x, y; cin >> x >> y; } int m; cin >> m; while (m--) { int u, v; cin >> u >> v; g[u].push_back(v); g[v].push_back(u); ++deg[u]; ++deg[v]; } for (int i = 1; i <= n; i++) { ideg[i] = mint(deg[i]).inv(); } dp[0][1] = 1; for (int k = 1; k <= n * 2; k++) { for (int u = 1; u <= n; u++) { if (u == n) continue; for (auto v: g[u]) { dp[k][v] += dp[k - 1][u] * ideg[u]; } } } vector<mint> cur; for (int i = 0; i <= 2 * n; i++) { cur.push_back(dp[i][n]); } auto tr = BerlekampMassey(cur); cur.resize(tr.size()); cout << yo(cur, tr) << '\n'; return 0; } // https://codeforces.com/gym/102268/problem/E
35.963235
172
0.512983
bazzyadb
462964858587a0c330f6bd85d4f57773591d9a22
465
cc
C++
modules/print_binary_tree.cc
xsthunder/a
3c30f31c59030d70462b71ef28c5eee19c6eddd6
[ "MIT" ]
1
2018-07-22T04:52:10.000Z
2018-07-22T04:52:10.000Z
modules/print_binary_tree.cc
xsthunder/a
3c30f31c59030d70462b71ef28c5eee19c6eddd6
[ "MIT" ]
1
2018-08-11T13:29:59.000Z
2018-08-11T13:31:28.000Z
modules/print_binary_tree.cc
xsthunder/a
3c30f31c59030d70462b71ef28c5eee19c6eddd6
[ "MIT" ]
null
null
null
#include<cstdio> #include<iostream> using namespace std; template <typename T> void pT(T *A, int d){//d for depth int sum=0; cout<<"------tree starts\n"; for(int i=0;i<d;i++){ cout<<i+1<<':'; for(int j=0;j<1<<i;j++){ cout<<*(A+sum++)<<' '; } cout<<endl; } cout<<"------tree ends\n"; } template <typename T> void pA(T *begin,int n){ for(int i=0;i<n;i++){ cout<<*(begin+i)<<' '; } printf("\n"); } int main(){ int A[10]={1,2,3,4,5,6,7,8}; pT(A,3); }
20.217391
87
0.535484
xsthunder
462cd92916a78d6d435ad71220631e0b3c63cc15
2,623
cpp
C++
plugins/goose/src/sub/QualityTemplatesConfigReader.cpp
openenergysolutions/openfmb.adapters
3c95b1c460a8967190bdd9ae16677a4e2a5d9861
[ "Apache-2.0" ]
1
2021-08-20T12:14:11.000Z
2021-08-20T12:14:11.000Z
plugins/goose/src/sub/QualityTemplatesConfigReader.cpp
openenergysolutions/openfmb.adapters
3c95b1c460a8967190bdd9ae16677a4e2a5d9861
[ "Apache-2.0" ]
3
2021-06-16T19:25:23.000Z
2021-09-02T14:39:10.000Z
plugins/goose/src/sub/QualityTemplatesConfigReader.cpp
openenergysolutions/openfmb.adapters
3c95b1c460a8967190bdd9ae16677a4e2a5d9861
[ "Apache-2.0" ]
null
null
null
// SPDX-FileCopyrightText: 2021 Open Energy Solutions Inc // // SPDX-License-Identifier: Apache-2.0 #include "sub/QualityTemplatesConfigReader.h" #include "ConfigStrings.h" #include <adapter-util/util/YAMLUtil.h> #include <adapter-util/config/YAMLGetters.h> namespace adapter { namespace goose { QualityTemplatesConfigReader::QualityTemplatesConfigReader(const YAML::Node& node) { util::yaml::foreach(node, [this](const YAML::Node& quality_node) { auto id = util::yaml::require_string(quality_node, keys::quality_id); auto quality = std::make_shared<commonmodule::Quality>(); quality->set_validity(static_cast<commonmodule::ValidityKind>(util::yaml::get::enum_value(quality_node, keys::quality_validity, *commonmodule::ValidityKind_descriptor()))); auto details = quality->mutable_detailqual(); details->set_overflow(util::yaml::require(quality_node, keys::quality_overflow).as<bool>()); details->set_outofrange(util::yaml::require(quality_node, keys::quality_outofrange).as<bool>()); details->set_badreference(util::yaml::require(quality_node, keys::quality_badreference).as<bool>()); details->set_oscillatory(util::yaml::require(quality_node, keys::quality_oscillatory).as<bool>()); details->set_failure(util::yaml::require(quality_node, keys::quality_failure).as<bool>()); details->set_olddata(util::yaml::require(quality_node, keys::quality_olddata).as<bool>()); details->set_inconsistent(util::yaml::require(quality_node, keys::quality_inconsistent).as<bool>()); details->set_inaccurate(util::yaml::require(quality_node, keys::quality_inaccurate).as<bool>()); quality->set_source(static_cast<commonmodule::SourceKind>(util::yaml::get::enum_value(quality_node, keys::quality_source, *commonmodule::SourceKind_descriptor()))); quality->set_test(util::yaml::require(quality_node, keys::quality_test).as<bool>()); quality->set_operatorblocked(util::yaml::require(quality_node, keys::quality_operatorblocked).as<bool>()); auto result = m_templates.insert({ id, quality }); if(!result.second) { throw api::Exception{"Quality template id \"" + id + "\" already used."}; } }); } const std::shared_ptr<commonmodule::Quality> QualityTemplatesConfigReader::get(const std::string& id) const { auto result = m_templates.find(id); if(result == m_templates.end()) { throw api::Exception{"Cannot find quality template with id \"" + id + "\"."}; } return result->second; } } // namespace goose } // namespace adapter
46.839286
180
0.704918
openenergysolutions
462ddf2182fe6a992adb577c17852966085f2cb9
12,751
cpp
C++
source/dynv/Xml.cpp
ericonr/gpick
ff0a3c0c797d3d06d1b8ab257cb2e9dcca389908
[ "BSD-3-Clause" ]
311
2015-03-26T18:38:51.000Z
2022-03-23T07:39:30.000Z
source/dynv/Xml.cpp
ericonr/gpick
ff0a3c0c797d3d06d1b8ab257cb2e9dcca389908
[ "BSD-3-Clause" ]
86
2015-03-27T06:05:57.000Z
2022-01-07T23:04:30.000Z
source/dynv/Xml.cpp
ericonr/gpick
ff0a3c0c797d3d06d1b8ab257cb2e9dcca389908
[ "BSD-3-Clause" ]
42
2015-03-25T16:40:26.000Z
2022-02-23T22:36:47.000Z
/* * Copyright (c) 2009-2020, Albertas Vyšniauskas * 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 software author 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 OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Xml.h" #include "Map.h" #include "Variable.h" #include "Types.h" #include "common/Scoped.h" #include <expat.h> #include <sstream> using namespace std::string_literals; namespace dynv { namespace xml { using ValueType = types::ValueType; bool writeStart(std::ostream &stream, const std::string &name) { stream << "<" << name << ">"; return stream.good(); } bool writeStart(std::ostream &stream, const std::string &name, const std::string &type) { stream << "<" << name << " type=\"" << type << "\">"; return stream.good(); } bool writeEnd(std::ostream &stream, const std::string &name) { stream << "</" << name << ">"; return stream.good(); } bool writeListStart(std::ostream &stream, const std::string &name, const std::string &type) { stream << "<" << name << " type=\"" << type << "\" list=\"true\">"; return stream.good(); } struct SerializeVisitor: public boost::static_visitor<bool> { SerializeVisitor(std::ostream &stream, const std::string &name): stream(stream), name(name) { } template<typename T> bool operator()(const T &value) const { if (!writeStart(stream, name, dynv::types::typeHandler<T>().name)) return false; if (!types::xml::write(stream, value)) return false; if (!writeEnd(stream, name)) return false; return true; } bool operator()(const common::Ref<Map> &value) const { if (!writeStart(stream, name, dynv::types::typeHandler<common::Ref<Map>>().name)) return false; if (!types::xml::write(stream, value)) return false; if (!writeEnd(stream, name)) return false; return true; } template<typename T> bool operator()(const std::vector<T> &values) const { using namespace std::string_literals; if (!writeListStart(stream, name, dynv::types::typeHandler<T>().name)) return false; for (const auto &i: values) { if (!writeStart(stream, "li"s)) return false; if (!types::xml::write(stream, i)) return false; if (!writeEnd(stream, "li"s)) return false; } return writeEnd(stream, name); } std::ostream &stream; const std::string &name; }; static bool isTrue(const char *value) { using namespace std::string_literals; if (value == nullptr) return false; return value == "true"s; } enum class EntityType { root, map, list, listItem, value, unknown, }; struct Entity { Entity(Entity &entity) = delete; Entity(Entity &&entity): m_system(entity.m_system), m_entityType(entity.m_entityType), m_valueType(entity.m_valueType), m_value(std::move(entity.m_value)) { } Entity(Map &map, EntityType entityType, ValueType valueType): m_system(map), m_entityType(entityType), m_valueType(valueType) { } Entity(Map &map, EntityType entityType, ValueType valueType, std::unique_ptr<Variable> &&value): m_system(map), m_entityType(entityType), m_valueType(valueType), m_value(std::move(value)) { } void write(const XML_Char *data, int length) { m_data.write(reinterpret_cast<const char *>(data), length); } std::string data() { return m_data.str(); } bool isList() const { return m_entityType == EntityType::list; } bool ignoreData() const { return m_entityType != EntityType::listItem && m_entityType != EntityType::value; } bool isIgnored() const { return m_entityType == EntityType::unknown; } bool hasValue() const { return static_cast<bool>(m_value); } std::unique_ptr<Variable> &value() { return m_value; } Map &map() { return m_system; } ValueType valueType() const { return m_valueType; } EntityType entityType() const { return m_entityType; } private: Map &m_system; std::stringstream m_data; EntityType m_entityType; ValueType m_valueType; std::unique_ptr<Variable> m_value; }; struct Context { Context(Map &map): m_rootFound(false), m_errors(0) { push(map, EntityType::root); } ~Context() { m_entities.clear(); } Entity &entity() { return m_entities.back(); } Entity &parentEntity() { return m_entities.at(m_entities.size() - 2); } bool rootFound() const { return m_rootFound; } void setRootFound() { m_rootFound = true; } void push(Map &map, EntityType entityType, ValueType valueType = ValueType::unknown) { m_entities.emplace_back(map, entityType, valueType); } void push(Map &map, EntityType entityType, ValueType valueType, std::unique_ptr<Variable> &&value) { m_entities.emplace_back(map, entityType, valueType, std::move(value)); } void pop() { m_entities.pop_back(); } void error() { m_errors++; } operator bool() const { return m_errors == 0; } private: bool m_rootFound; std::vector<Entity> m_entities; uint32_t m_errors; }; static const char *getAttribute(const XML_Char **attributes, const std::string &name) { for (auto i = attributes; *i; i += 2) { if (*i == name) return i[1]; } return nullptr; } static void onCharacterData(Context *context, const XML_Char *data, int length) { auto &entity = context->entity(); if (entity.ignoreData() || entity.isIgnored()) return; entity.write(data, length); } struct IsVector: public boost::static_visitor<bool> { IsVector(Entity &entity): entity(entity) { } template<typename T> bool operator()(const T &) const { return false; } template<typename T> bool operator()(const std::vector<T> &) const { return true; } Entity &entity; }; static void onStartElement(Context *context, const XML_Char *name, const XML_Char **attributes) { using namespace std::string_literals; if (!context->rootFound()) { if (name == "root"s) context->setRootFound(); return; } auto &entity = context->entity(); if (entity.isIgnored()) { context->push(entity.map(), EntityType::unknown); return; } if (entity.isList()) { if (!(name && name == "li"s)) { context->push(entity.map(), EntityType::unknown); return; } if (!boost::apply_visitor(IsVector(entity), entity.value()->data())) { context->error(); context->push(entity.map(), EntityType::unknown); return; } if (entity.valueType() == ValueType::map) { auto map = common::Ref<Map>(new Map()); auto &data = entity.value()->data(); context->push(*map, EntityType::listItem); boost::get<std::vector<common::Ref<Map>> &>(data).push_back(std::move(map)); } else { context->push(entity.map(), EntityType::listItem); } return; } auto type = types::stringToType(getAttribute(attributes, "type"s)); auto isList = isTrue(getAttribute(attributes, "list"s)); switch (type) { case ValueType::basicBool: case ValueType::basicFloat: case ValueType::basicInt32: case ValueType::color: case ValueType::string: if (isList) { std::unique_ptr<Variable> variable; switch (type) { case ValueType::basicBool: variable = std::make_unique<Variable>(name, std::vector<bool>()); break; case ValueType::basicFloat: variable = std::make_unique<Variable>(name, std::vector<float>()); break; case ValueType::basicInt32: variable = std::make_unique<Variable>(name, std::vector<int32_t>()); break; case ValueType::color: variable = std::make_unique<Variable>(name, std::vector<Color>()); break; case ValueType::string: variable = std::make_unique<Variable>(name, std::vector<std::string>()); break; case ValueType::map: case ValueType::unknown: break; } context->push(entity.map(), EntityType::list, type, std::move(variable)); } else { context->push(entity.map(), EntityType::value, type); } break; case ValueType::map: if (isList) { auto systems = std::vector<common::Ref<Map>>(); auto variable = std::make_unique<Variable>(name, systems); context->push(entity.map(), EntityType::list, type, std::move(variable)); } else { auto map = common::Ref<Map>(new Map()); entity.map().set(name, map); context->push(*map, EntityType::map, type); } break; case ValueType::unknown: context->push(entity.map(), EntityType::unknown); break; } } static void onEndElement(Context *context, const XML_Char *name) { if (!context->rootFound()) return; auto &entity = context->entity(); if (entity.isIgnored()) { context->pop(); return; } if (entity.isList()) { entity.map().set(std::move(entity.value())); context->pop(); return; } if (entity.entityType() == EntityType::listItem) { auto &listEntity = context->parentEntity(); auto &data = listEntity.value()->data(); switch (listEntity.valueType()) { case ValueType::string: boost::get<std::vector<std::string> &>(data).push_back(entity.data()); break; case ValueType::basicBool: boost::get<std::vector<bool> &>(data).push_back(entity.data() == "true"); break; case ValueType::basicInt32: boost::get<std::vector<int32_t> &>(data).push_back(std::stoi(entity.data())); break; case ValueType::basicFloat: boost::get<std::vector<float> &>(data).push_back(std::stof(entity.data())); break; case ValueType::color: { std::stringstream in(entity.data()); Color color; in >> color[0] >> color[1] >> color[2] >> color[3]; boost::get<std::vector<Color> &>(data).push_back(color); } break; case ValueType::map: break; case ValueType::unknown: break; } context->pop(); return; } if (entity.entityType() == EntityType::value) { auto &map = entity.map(); switch (entity.valueType()) { case ValueType::string: map.set(name, entity.data()); break; case ValueType::basicBool: map.set(name, entity.data() == "true"); break; case ValueType::basicInt32: map.set(name, std::stoi(entity.data())); break; case ValueType::basicFloat: map.set(name, std::stof(entity.data())); break; case ValueType::color: { std::stringstream in(entity.data()); Color color; in >> color[0] >> color[1] >> color[2] >> color[3]; map.set(name, color); } break; case ValueType::map: break; case ValueType::unknown: break; } context->pop(); return; } if (entity.entityType() == EntityType::map) { context->pop(); return; } } bool serialize(std::ostream &stream, const Map &map, bool addRootElement) { if (addRootElement) { stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root>"; if (!stream.good()) return false; } auto visitor = [&stream](const Variable &value) -> bool { if (!boost::apply_visitor(SerializeVisitor(stream, value.name()), value.data())) return false; return true; }; if (!map.visit(visitor)) return false; if (addRootElement) { stream << "</root>"; if (!stream.good()) return false; } return true; } bool deserialize(std::istream &stream, Map &map) { auto parser = XML_ParserCreate("UTF-8"); auto freeParser = common::makeScoped(XML_ParserFree, parser); XML_SetElementHandler(parser, reinterpret_cast<XML_StartElementHandler>(onStartElement), reinterpret_cast<XML_EndElementHandler>(onEndElement)); XML_SetCharacterDataHandler(parser, reinterpret_cast<XML_CharacterDataHandler>(onCharacterData)); xml::Context context(map); XML_SetUserData(parser, &context); for (;;) { auto buffer = XML_GetBuffer(parser, 4096); stream.read(reinterpret_cast<char *>(buffer), 4096); size_t length = stream.gcount(); if (!XML_ParseBuffer(parser, length, length == 0)) { std::cerr << "XML parse error\n"; return false; } if (length == 0) break; } return context; } } }
29.861827
211
0.68426
ericonr
462e31050795f341ff50315b2347c58bfbb784e9
83
cpp
C++
TP3_Prog_SpaceSim/Main.cpp
Arganancer/S3_TP3_Prog_SpaceSim
43364f6613ad690f81c94f8a027ee3708fa58d3d
[ "MIT" ]
null
null
null
TP3_Prog_SpaceSim/Main.cpp
Arganancer/S3_TP3_Prog_SpaceSim
43364f6613ad690f81c94f8a027ee3708fa58d3d
[ "MIT" ]
null
null
null
TP3_Prog_SpaceSim/Main.cpp
Arganancer/S3_TP3_Prog_SpaceSim
43364f6613ad690f81c94f8a027ee3708fa58d3d
[ "MIT" ]
null
null
null
#include "vld.h" #include "game.h" int main() { game game; return game.run(); }
9.222222
19
0.614458
Arganancer
463015586ebed441a243c541d8c89e57e01a6cc8
13,660
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/ProfileManager.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/ProfileManager.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/ProfileManager.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "elastos/droid/app/ProfileManager.h" #include "elastos/droid/app/CProfile.h" #include "elastos/droid/os/ServiceManager.h" #include "elastos/droid/os/CParcelUuid.h" #include "elastos/droid/provider/CSettingsSystem.h" #include <elastos/utility/logging/Logger.h> #include <Elastos.Droid.Utility.h> using Elastos::Droid::Content::IContentResolver; using Elastos::Droid::Os::IParcelUuid; using Elastos::Droid::Os::CParcelUuid; using Elastos::Droid::Os::IServiceManager; using Elastos::Droid::Os::ServiceManager; using Elastos::Droid::Provider::ISettingsSystem; using Elastos::Droid::Provider::CSettingsSystem; using Elastos::Utility::IUUIDHelper; using Elastos::Utility::CUUIDHelper; namespace Elastos { namespace Droid { namespace App { AutoPtr<IUUID> InitNoProfile() { AutoPtr<IUUIDHelper> helper; CUUIDHelper::AcquireSingleton((IUUIDHelper**)&helper); AutoPtr<IUUID> uuid; helper->FromString(String("00000000-0000-0000-0000-000000000000"), (IUUID**)&uuid); return uuid; } AutoPtr<IUUID> ProfileManager::NO_PROFILE = InitNoProfile(); AutoPtr<IIProfileManager> ProfileManager::sService; const String ProfileManager::TAG("ProfileManager"); const String ProfileManager::SYSTEM_PROFILES_ENABLED("system_profiles_enabled"); static AutoPtr<IProfile> InitEmptyProfile() { AutoPtr<IProfile> tmp; CProfile::New(String("EmptyProfile"), (IProfile**)&tmp); return tmp; } AutoPtr<IProfile> ProfileManager::sEmptyProfile = InitEmptyProfile(); CAR_INTERFACE_IMPL(ProfileManager, Object, IProfileManager) AutoPtr<IIProfileManager> ProfileManager::GetService() { if (sService != NULL) { return sService; } AutoPtr<IInterface> b = ServiceManager::GetService(IContext::PROFILE_SERVICE); sService = IIProfileManager::Probe(b); return sService; } ECode ProfileManager::ToString( /* [out] */ String* str) { VALIDATE_NOT_NULL(str) *str = String("ProfileManager"); return NOERROR; } ECode ProfileManager::constructor( /* [in] */ IContext* context, /* [in] */ IHandler* handler) { mContext = context; return NOERROR; } ECode ProfileManager::SetActiveProfile( /* [in] */ const String& profileName) { AutoPtr<ISettingsSystem> settingsSys; CSettingsSystem::AcquireSingleton((ISettingsSystem**)&settingsSys); AutoPtr<IContentResolver> resolver; mContext->GetContentResolver((IContentResolver**)&resolver); Int32 value; settingsSys->GetInt32(resolver, SYSTEM_PROFILES_ENABLED, 1, &value); if (value == 1) { // Profiles are enabled, return active profile // try { Boolean result; ECode ec = GetService()->SetActiveProfileByName(profileName, &result); if (ec == (ECode)E_REMOTE_EXCEPTION) { return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } return NOERROR; } ECode ProfileManager::SetActiveProfile( /* [in] */ IUUID* profileUuid) { AutoPtr<ISettingsSystem> settingsSys; CSettingsSystem::AcquireSingleton((ISettingsSystem**)&settingsSys); AutoPtr<IContentResolver> resolver; mContext->GetContentResolver((IContentResolver**)&resolver); Int32 value; settingsSys->GetInt32(resolver, SYSTEM_PROFILES_ENABLED, 1, &value); if (value == 1) { // Profiles are enabled, return active profile // try { Boolean result; AutoPtr<IParcelUuid> uuid; CParcelUuid::New(profileUuid, (IParcelUuid**)&uuid); ECode ec = GetService()->SetActiveProfile(uuid, &result); if (ec == (ECode)E_REMOTE_EXCEPTION) { return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } return NOERROR; } ECode ProfileManager::GetActiveProfile( /* [out] */ IProfile** profile) { VALIDATE_NOT_NULL(profile) AutoPtr<ISettingsSystem> settingsSys; CSettingsSystem::AcquireSingleton((ISettingsSystem**)&settingsSys); AutoPtr<IContentResolver> resolver; mContext->GetContentResolver((IContentResolver**)&resolver); Int32 value; settingsSys->GetInt32(resolver, SYSTEM_PROFILES_ENABLED, 1, &value); if (value == 1) { // Profiles are enabled, return active profile // try { ECode ec = GetService()->GetActiveProfile(profile); if (ec == (ECode)E_REMOTE_EXCEPTION) { *profile = NULL; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } else { // Profiles are not enabled, return the empty profile *profile = sEmptyProfile; REFCOUNT_ADD(*profile) } return NOERROR; } ECode ProfileManager::AddProfile( /* [in] */ IProfile* profile) { // try { Boolean result; return GetService()->AddProfile(profile, &result); // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } ECode ProfileManager::RemoveProfile( /* [in] */ IProfile* profile) { // try { Boolean result; return GetService()->RemoveProfile(profile, &result); // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } ECode ProfileManager::UpdateProfile( /* [in] */ IProfile* profile) { // try { return GetService()->UpdateProfile(profile); // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } ECode ProfileManager::GetProfile( /* [in] */ const String& profileName, /* [out] */ IProfile** profile) { VALIDATE_NOT_NULL(profile) // try { ECode ec = GetService()->GetProfileByName(profileName, profile); if (ec == (ECode)E_REMOTE_EXCEPTION) { *profile = NULL; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } return NOERROR; } ECode ProfileManager::GetProfile( /* [in] */ IUUID* profileUuid, /* [out] */ IProfile** profile) { VALIDATE_NOT_NULL(profile) // try { AutoPtr<IParcelUuid> uuid; CParcelUuid::New(profileUuid, (IParcelUuid**)&uuid); ECode ec = GetService()->GetProfile(uuid, profile); if (ec == (ECode)E_REMOTE_EXCEPTION) { *profile = NULL; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } return NOERROR; } ECode ProfileManager::GetProfileNames( /* [out, callee] */ ArrayOf<String>** names) { VALIDATE_NOT_NULL(names) // try { AutoPtr<ArrayOf<IProfile*> > profiles; ECode ec = GetService()->GetProfiles((ArrayOf<IProfile*>**)&profiles); if (ec == (ECode)E_REMOTE_EXCEPTION) { *names = NULL; return ec; } ArrayOf<String>* profileNames = ArrayOf<String>::Alloc(profiles->GetLength()); for (Int32 i = 0; i < profiles->GetLength(); i++) { (*profiles)[i]->GetName(&(*profileNames)[i]); } *names = profileNames; // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } return NOERROR; } ECode ProfileManager::GetProfiles( /* [out, callee] */ ArrayOf<IProfile*>** profiles) { VALIDATE_NOT_NULL(profiles) // try { ECode ec = GetService()->GetProfiles(profiles); if (ec == (ECode)E_REMOTE_EXCEPTION) { *profiles = NULL; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } return NOERROR; } ECode ProfileManager::ProfileExists( /* [in] */ const String& profileName, /* [out] */ Boolean* isExisted) { VALIDATE_NOT_NULL(isExisted) // try { ECode ec = GetService()->ProfileExistsByName(profileName, isExisted); if (ec == (ECode)E_REMOTE_EXCEPTION) { *isExisted = TRUE; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // // To be on the safe side, we'll return "true", to prevent duplicate profiles // // from being created. // return true; // } return NOERROR; } ECode ProfileManager::ProfileExists( /* [in] */ IUUID* profileUuid, /* [out] */ Boolean* isExisted) { VALIDATE_NOT_NULL(isExisted) // try { AutoPtr<IParcelUuid> uuid; CParcelUuid::New(profileUuid, (IParcelUuid**)&uuid); ECode ec = GetService()->ProfileExists(uuid, isExisted); if (ec == (ECode)E_REMOTE_EXCEPTION) { *isExisted = TRUE; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // // To be on the safe side, we'll return "true", to prevent duplicate profiles // // from being created. // return true; // } return NOERROR; } ECode ProfileManager::NotificationGroupExists( /* [in] */ const String& notificationGroupName, /* [out] */ Boolean* isExisted) { VALIDATE_NOT_NULL(isExisted) // try { ECode ec = GetService()->NotificationGroupExistsByName(notificationGroupName, isExisted); if (ec == (ECode)E_REMOTE_EXCEPTION) { *isExisted = TRUE; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // // To be on the safe side, we'll return "true", to prevent duplicate notification // // groups from being created. // return true; // } return NOERROR; } ECode ProfileManager::GetNotificationGroups( /* [out, callee] */ ArrayOf<INotificationGroup*>** groups) { VALIDATE_NOT_NULL(groups) // try { ECode ec = GetService()->GetNotificationGroups(groups); if (ec == (ECode)E_REMOTE_EXCEPTION) { *groups = NULL; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } return NOERROR; } ECode ProfileManager::AddNotificationGroup( /* [in] */ INotificationGroup* group) { // try { return GetService()->AddNotificationGroup(group); // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } ECode ProfileManager::RemoveNotificationGroup( /* [in] */ INotificationGroup* group) { // try { return GetService()->RemoveNotificationGroup(group); // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } ECode ProfileManager::UpdateNotificationGroup( /* [in] */ INotificationGroup* group) { // try { return GetService()->UpdateNotificationGroup(group); // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } ECode ProfileManager::GetNotificationGroupForPackage( /* [in] */ const String& pkg, /* [out] */ INotificationGroup** group) { VALIDATE_NOT_NULL(group) // try { ECode ec = GetService()->GetNotificationGroupForPackage(pkg, group); if (ec == (ECode)E_REMOTE_EXCEPTION) { *group = NULL; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } return NOERROR; } ECode ProfileManager::GetNotificationGroup( /* [in] */ IUUID* groupParcelUuid, /* [out] */ INotificationGroup** group) { VALIDATE_NOT_NULL(group) // try { AutoPtr<IParcelUuid> uuid; CParcelUuid::New(groupParcelUuid, (IParcelUuid**)&uuid); ECode ec = GetService()->GetNotificationGroup(uuid, group); if (ec == (ECode)E_REMOTE_EXCEPTION) { *group = NULL; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } return NOERROR; } ECode ProfileManager::GetActiveProfileGroup( /* [in] */ const String& packageName, /* [out] */ IProfileGroup** group) { VALIDATE_NOT_NULL(group) AutoPtr<INotificationGroup> notificationGroup; GetNotificationGroupForPackage(packageName, (INotificationGroup**)&notificationGroup); AutoPtr<IProfile> profile; GetActiveProfile((IProfile**)&profile); if (notificationGroup == NULL) { AutoPtr<IProfileGroup> defaultGroup; profile->GetDefaultGroup((IProfileGroup**)&defaultGroup); *group = defaultGroup; REFCOUNT_ADD(*group); return NOERROR; } AutoPtr<IUUID> uuid; notificationGroup->GetUuid((IUUID**)&uuid); return profile->GetProfileGroup(uuid, group); } ECode ProfileManager::ResetAll() { // try { ECode ec = GetService()->ResetAll(); if (ec == (ECode)E_REMOTE_EXCEPTION || ec == (ECode)E_SECURITY_EXCEPTION) { return ec; } return NOERROR; // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } catch (SecurityException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } } // namespace App } // namespace Droid } // namespace Elastos
29.06383
93
0.630161
jingcao80
4632501d59bf7b852fa5c135d97358d93bcdaa52
464
cpp
C++
storage/src/vespa/storage/distributor/operations/external/newest_replica.cpp
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
4,054
2017-08-11T07:58:38.000Z
2022-03-31T22:32:15.000Z
storage/src/vespa/storage/distributor/operations/external/newest_replica.cpp
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
4,854
2017-08-10T20:19:25.000Z
2022-03-31T19:04:23.000Z
storage/src/vespa/storage/distributor/operations/external/newest_replica.cpp
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
541
2017-08-10T18:51:18.000Z
2022-03-11T03:18:56.000Z
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "newest_replica.h" #include <ostream> namespace storage::distributor { std::ostream& operator<<(std::ostream& os, const NewestReplica& nr) { os << "NewestReplica(timestamp " << nr.timestamp << ", bucket_id " << nr.bucket_id << ", node " << nr.node << ", is_tombstone " << nr.is_tombstone << ')'; return os; } }
27.294118
104
0.631466
Anlon-Burke
4634737aca597d284dca13cf9574464bab7dc1ff
20
cpp
C++
src/Game/zScript.cpp
DarkRTA/bfbbdecomp
e2105e94b8da26f6e6e2dfcf1f004aaaeed9799e
[ "OLDAP-2.7" ]
null
null
null
src/Game/zScript.cpp
DarkRTA/bfbbdecomp
e2105e94b8da26f6e6e2dfcf1f004aaaeed9799e
[ "OLDAP-2.7" ]
6
2022-01-16T05:29:01.000Z
2022-01-18T01:10:29.000Z
src/Game/zScript.cpp
DarkRTA/bfbbdecomp
e2105e94b8da26f6e6e2dfcf1f004aaaeed9799e
[ "OLDAP-2.7" ]
1
2022-01-16T00:04:23.000Z
2022-01-16T00:04:23.000Z
#include "zScript.h"
20
20
0.75
DarkRTA
463b70decfcf756e76dc1f4d982ab90ff08f6feb
9,097
cpp
C++
src/daemon/process/AppProcess.cpp
FrederickHou/app-mesh
8f23a1555d3a8da1481d91e1e60464fc197bd6e5
[ "MIT" ]
null
null
null
src/daemon/process/AppProcess.cpp
FrederickHou/app-mesh
8f23a1555d3a8da1481d91e1e60464fc197bd6e5
[ "MIT" ]
null
null
null
src/daemon/process/AppProcess.cpp
FrederickHou/app-mesh
8f23a1555d3a8da1481d91e1e60464fc197bd6e5
[ "MIT" ]
1
2020-11-01T09:11:49.000Z
2020-11-01T09:11:49.000Z
#include <thread> #include <fstream> #include "AppProcess.h" #include "LinuxCgroup.h" #include "../Configuration.h" #include "../ResourceLimitation.h" #include "../../common/Utility.h" #include "../../common/DateTime.h" #include "../../common/os/pstree.hpp" #define CLOSE_ACE_HANDLER(handler) \ do \ { \ if (handler != ACE_INVALID_HANDLE) \ { \ ACE_OS::close(handler); \ handler = ACE_INVALID_HANDLE; \ } \ } while (false) AppProcess::AppProcess() : m_killTimerId(0), m_stdinHandler(ACE_INVALID_HANDLE), m_stdoutHandler(ACE_INVALID_HANDLE), m_uuid(Utility::createUUID()) { } AppProcess::~AppProcess() { if (this->running()) { killgroup(); } CLOSE_ACE_HANDLER(m_stdoutHandler); CLOSE_ACE_HANDLER(m_stdinHandler); if (m_stdinFileName.length() && Utility::isFileExist(m_stdinFileName)) { Utility::removeFile(m_stdinFileName); } if (m_stdoutReadStream && m_stdoutReadStream->is_open()) { m_stdoutReadStream->close(); } this->close_dup_handles(); this->close_passed_handles(); } void AppProcess::attach(int pid) { this->child_id_ = pid; } void AppProcess::detach() { attach(ACE_INVALID_PID); } pid_t AppProcess::getpid(void) const { return ACE_Process::getpid(); } void AppProcess::killgroup(int timerId) { const static char fname[] = "AppProcess::killgroup() "; LOG_INF << fname << "kill process <" << getpid() << ">."; if (timerId == 0) { // killed before timer event, cancel timer event this->cancelTimer(m_killTimerId); } if (m_killTimerId > 0 && m_killTimerId == timerId) { // clean timer id, trigger-ing this time. m_killTimerId = 0; } if (this->running() && this->getpid() > 1) { ACE_OS::kill(-(this->getpid()), 9); this->terminate(); if (this->wait() < 0 && errno != 10) // 10 is ECHILD:No child processes { //avoid zombie process (Interrupted system call) LOG_WAR << fname << "Wait process <" << getpid() << "> to exit failed with error : " << std::strerror(errno); std::this_thread::sleep_for(std::chrono::milliseconds(100)); if (this->wait() < 0) { LOG_ERR << fname << "Retry wait process <" << getpid() << "> failed with error : " << std::strerror(errno); } else { LOG_INF << fname << "Retry wait process <" << getpid() << "> success"; } } } } void AppProcess::setCgroup(std::shared_ptr<ResourceLimitation> &limit) { // https://blog.csdn.net/u011547375/article/details/9851455 if (limit != nullptr) { m_cgroup = std::make_unique<LinuxCgroup>(limit->m_memoryMb, limit->m_memoryVirtMb - limit->m_memoryMb, limit->m_cpuShares); m_cgroup->setCgroup(limit->m_name, getpid(), ++(limit->m_index)); } } const std::string AppProcess::getuuid() const { return m_uuid; } void AppProcess::regKillTimer(std::size_t timeout, const std::string from) { m_killTimerId = this->registerTimer(1000L * timeout, 0, std::bind(&AppProcess::killgroup, this, std::placeholders::_1), from); } // tuple: 1 cmdRoot, 2 parameters std::tuple<std::string, std::string> AppProcess::extractCommand(const std::string &cmd) { std::unique_ptr<char[]> buff(new char[cmd.length() + 1]); // find the string at the first blank not in a quote, quotes are removed std::size_t idxSrc = 0, idxDst = 0; bool isInQuote = false; while (cmd[idxSrc] != '\0') { if (cmd[idxSrc] == ' ' && !isInQuote) { break; } else if (cmd[idxSrc] == '\"') { isInQuote = isInQuote ^ true; } else { buff[idxDst++] = cmd[idxSrc]; } idxSrc++; } buff[idxDst] = '\0'; // remaining string are the parameters std::string params = cmd.substr(idxSrc); std::string cmdroot = buff.get(); return std::tuple<std::string, std::string>(params, cmdroot); } int AppProcess::spawnProcess(std::string cmd, std::string user, std::string workDir, std::map<std::string, std::string> envMap, std::shared_ptr<ResourceLimitation> limit, const std::string &stdoutFile, const std::string &stdinFileContent) { const static char fname[] = "AppProcess::spawnProcess() "; int pid = -1; // check command file existence & permission auto cmdRoot = std::get<1>(extractCommand(cmd)); bool checkCmd = true; if (cmdRoot.rfind('/') == std::string::npos && cmdRoot.rfind('\\') == std::string::npos) { checkCmd = false; } if (checkCmd && !Utility::isFileExist(cmdRoot)) { LOG_WAR << fname << "command file <" << cmdRoot << "> does not exist"; startError(Utility::stringFormat("command file <%s> does not exist", cmdRoot.c_str())); return ACE_INVALID_PID; } if (checkCmd && ACE_OS::access(cmdRoot.c_str(), X_OK) != 0) { LOG_WAR << fname << "command file <" << cmdRoot << "> does not have execution permission"; startError(Utility::stringFormat("command file <%s> does not have execution permission", cmdRoot.c_str())); return ACE_INVALID_PID; } envMap[ENV_APP_MANAGER_LAUNCH_TIME] = DateTime::formatLocalTime(std::chrono::system_clock::now(), DATE_TIME_FORMAT); std::size_t cmdLength = cmd.length() + ACE_Process_Options::DEFAULT_COMMAND_LINE_BUF_LEN; int totalEnvSize = 0; int totalEnvArgs = 0; Utility::getEnvironmentSize(envMap, totalEnvSize, totalEnvArgs); ACE_Process_Options option(1, cmdLength, totalEnvSize, totalEnvArgs); option.command_line("%s", cmd.c_str()); //option.avoid_zombies(1); if (user.empty()) user = Configuration::instance()->getDefaultExecUser(); if (user != "root") { unsigned int gid, uid; if (Utility::getUid(user, uid, gid)) { option.seteuid(uid); option.setruid(uid); option.setegid(gid); option.setrgid(gid); } else { startError(Utility::stringFormat("user <%s> does not exist", user.c_str())); return ACE_INVALID_PID; } } option.setgroup(0); // set group id with the process id, used to kill process group option.inherit_environment(true); option.handle_inheritance(0); if (workDir.length()) { option.working_directory(workDir.c_str()); } else { option.working_directory(Configuration::instance()->getDefaultWorkDir().c_str()); // set default working dir } std::for_each(envMap.begin(), envMap.end(), [&option](const std::pair<std::string, std::string> &pair) { option.setenv(pair.first.c_str(), "%s", pair.second.c_str()); LOG_DBG << "spawnProcess env: " << pair.first.c_str() << "=" << pair.second.c_str(); }); option.release_handles(); // clean if necessary CLOSE_ACE_HANDLER(m_stdoutHandler); CLOSE_ACE_HANDLER(m_stdinHandler); ACE_HANDLE dummy = ACE_INVALID_HANDLE; m_stdoutFileName = stdoutFile; if (stdoutFile.length() || stdinFileContent.length()) { dummy = ACE_OS::open("/dev/null", O_RDWR); m_stdoutHandler = m_stdinHandler = dummy; if (stdoutFile.length()) { m_stdoutHandler = ACE_OS::open(stdoutFile.c_str(), O_CREAT | O_WRONLY | O_APPEND | O_TRUNC); LOG_DBG << "std_out: " << stdoutFile; } if (stdinFileContent.length() && stdinFileContent != JSON_KEY_APP_CLOUD_APP) { m_stdinFileName = Utility::stringFormat("appmesh.%s.stdin", m_uuid.c_str()); std::ofstream inputFile(m_stdinFileName, std::ios::trunc); inputFile << stdinFileContent; inputFile.close(); assert(Utility::isFileExist(m_stdinFileName)); m_stdinHandler = ACE_OS::open(m_stdinFileName.c_str(), O_RDONLY); LOG_DBG << "std_in: " << m_stdinFileName << " : " << stdinFileContent; } option.set_handles(m_stdinHandler, m_stdoutHandler, m_stdoutHandler); } // do not inherit LD_LIBRARY_PATH to child static const std::string ldEnv = ACE_OS::getenv("LD_LIBRARY_PATH") ? ACE_OS::getenv("LD_LIBRARY_PATH") : ""; if (!ldEnv.empty()) { std::string env = ldEnv; env = Utility::stringReplace(env, "/opt/appmesh/lib64:", ""); env = Utility::stringReplace(env, ":/opt/appmesh/lib64", ""); option.setenv("LD_LIBRARY_PATH", "%s", env.c_str()); } if (this->spawn(option) >= 0) { pid = this->getpid(); LOG_INF << fname << "Process <" << cmd << "> started with pid <" << pid << ">."; this->setCgroup(limit); } else { pid = -1; LOG_ERR << fname << "Process:<" << cmd << "> start failed with error : " << std::strerror(errno); startError(Utility::stringFormat("start failed with error <%s>", std::strerror(errno))); } if (dummy != ACE_INVALID_HANDLE) ACE_OS::close(dummy); return pid; } std::string AppProcess::fetchOutputMsg() { std::lock_guard<std::recursive_mutex> guard(m_outFileMutex); if (m_stdoutReadStream == nullptr) m_stdoutReadStream = std::make_shared<std::ifstream>(m_stdoutFileName, ios::in); if (m_stdoutReadStream->is_open() && m_stdoutReadStream->good()) { std::stringstream buffer; buffer << m_stdoutReadStream->rdbuf(); return std::move(buffer.str()); } return std::string(); } std::string AppProcess::fetchLine() { char buffer[512] = {0}; std::lock_guard<std::recursive_mutex> guard(m_outFileMutex); if (m_stdoutReadStream == nullptr) m_stdoutReadStream = std::make_shared<std::ifstream>(m_stdoutFileName, ios::in); if (m_stdoutReadStream->is_open() && m_stdoutReadStream->good()) { m_stdoutReadStream->getline(buffer, sizeof(buffer)); } return buffer; }
30.62963
238
0.67165
FrederickHou
463dea99028bceb273e29e22982b837fae318681
4,507
cpp
C++
src/controller/src/SMACS.cpp
BCLab-UNM/M2M-MC
4bde093b2c43c2217fda2f4a0efd55bbfc45b9a1
[ "MIT" ]
6
2020-07-02T13:01:30.000Z
2021-05-01T06:35:10.000Z
src/controller/src/SMACS.cpp
BCLab-UNM/M2M-MC
4bde093b2c43c2217fda2f4a0efd55bbfc45b9a1
[ "MIT" ]
null
null
null
src/controller/src/SMACS.cpp
BCLab-UNM/M2M-MC
4bde093b2c43c2217fda2f4a0efd55bbfc45b9a1
[ "MIT" ]
2
2020-05-17T18:51:12.000Z
2020-11-16T16:32:44.000Z
#include "SMACS.h" // Initialize the instance SMACS* SMACS::s_instance = 0; SMACS::SMACS(){} SMACS* SMACS::instance(){ if(!s_instance) s_instance = new SMACS; return s_instance; } void SMACS::pushWithMutex(Behavior* b){ // Check if behavior is null. If it is then do not put anything on stack if(b == NULL){ cout << "STACK: " << "NULL pointer passed to stack" << endl; return; } //lock the stack from being used while we are doing something with it std::lock_guard<std::mutex> guard(stackMutex); //cout << "STACK: " << "Stack locked"<< endl; //if stack is not empty, check if behavior is stackable if(!behaviorStack.empty()){ Behavior *top = behaviorStack.top(); cout << "STACK: " << "Got top"<< endl; if(b->getType() == top->getType()){ if(!b->isStackable()){ cout << "STACK: " << "Behavior is not stackable. Was not pushed to stack"<< endl; return; } } } //stop the robot DriveController::instance()->stop(); //push new behavior behaviorStack.push(b); cout << "STACK: " << "Pushed to stack"<< endl; //cout << "STACK: " << "Stack unlocked"<< endl; } void SMACS::push(Behavior* b){ // Check if behavior is null. If it is then do not put anything on stack if(b == NULL){ cout << "STACK: " << "NULL pointer passed to stack" << endl; return; } //lock the stack from being used while we are doing something with it cout << "STACK: " << "Pushing with no mutex"<< endl; //if stack is not empty, check if behavior is stackable if(!behaviorStack.empty()){ Behavior *top = behaviorStack.top(); //cout << "STACK: " << "Got top"<< endl; if(b->getType() == top->getType()){ if(!b->isStackable()){ //cout << "STACK: " << "Behavior is not stackable. Was not pushed to stack"<< endl; return; } } } //stop the robot DriveController::instance()->stop(); //push new behavior behaviorStack.push(b); cout << "STACK: " << "Pushed to stack"<< endl; //cout << "STACK: " << "Stack unlocked"<< endl; } void SMACS::pop(){ if(behaviorStack.empty()){ cout << "STACK: " << "Behavior stack is already empty."<< endl; return; } //lock stack std::lock_guard<std::mutex> guard(stackMutex); //cout << "STACK: " << "Stack locked"<< endl; DriveController::instance()->stop(); cout << "STACK: " << "Popped from stack"<< endl; //pop element behaviorStack.pop(); //cout << "STACK: " << "Stack unlocked"<< endl; } void SMACS::pushNext(Behavior *b){ if(b == NULL){ cout << "STACK: " << "NULL pointer passed to stack"<< endl; return; } // cout << "STACK: " << "Stack not locked for push next"<< endl; // if stack is not empty, then save top element and pop it to get to the next element if(!behaviorStack.empty()){ Behavior *hold = behaviorStack.top(); behaviorStack.pop(); //if stack is not empty, check if second elements is stackable if(!behaviorStack.empty()){ Behavior *top = behaviorStack.top(); if(b->getType() == top->getType()){ if(!b->isStackable()){ cout << "STACK: " << "Behavior is not stackable. Was not pushed to stack"<< endl; behaviorStack.push(hold); return; } } } behaviorStack.push(b); behaviorStack.push(hold); } else { behaviorStack.push(b); } cout << "STACK: " << "Pushed next behavior to stack."<<endl; } bool SMACS::isEmpty(){return behaviorStack.empty();} // This is a tick method bool SMACS::tick(){ // Lock stack std::lock_guard<std::mutex> guard(stackMutex); // If stack is not empty if(!behaviorStack.empty()){ cout << "STACK: " << "Ticking behvior: "<< behaviorStack.top()->getCurrentBehavior()<< endl; if(behaviorStack.top()->tick()){ DriveController::instance()->stop(); cout << "STACK: " << "Popped from stack"<< endl; //pop element behaviorStack.pop(); //cout << "STACK: " << "Stack popped from tick"<< endl; return true; } //cout << "STACK: " << "Stack unlocked for tick"<< endl; } return false; }
25.463277
101
0.544264
BCLab-UNM
463ed1f546940c56ba4ee677e916d5a1b61dab89
7,947
cpp
C++
tests/src/percent_input_tests.cpp
DmitryDzz/calculator-comrade-lib
107930ef7df88b330b800993028b35d08d5d78f6
[ "MIT" ]
4
2021-01-18T03:11:14.000Z
2022-01-29T09:17:06.000Z
tests/src/percent_input_tests.cpp
DmitryDzz/calculator-comrade-lib
107930ef7df88b330b800993028b35d08d5d78f6
[ "MIT" ]
32
2018-10-11T22:05:14.000Z
2019-05-26T16:25:38.000Z
tests/src/percent_input_tests.cpp
DmitryDzz/calculator-comrade-lib
107930ef7df88b330b800993028b35d08d5d78f6
[ "MIT" ]
null
null
null
/** * Calculator Comrade Library * License: https://github.com/DmitryDzz/calculator-comrade-lib/blob/master/LICENSE * Author: Dmitry Dzakhov * Email: info@robot-mitya.ru */ #include <gmock/gmock.h> #include "calculator/calculator.h" #include "calculator/button.h" #include "calculator/operation.h" #include "calc_helper.h" using namespace calculatorcomrade; #define TEST_PERCENT(test_name) TEST(PercentOperations, test_name) TEST_PERCENT(NoOperation) { Calculator c(8); Register &x = c.getX(); c.input(Button::d5); c.input(Button::percent); ASSERT_EQ(5, getIntValue(x)); } TEST_PERCENT(AddPercent) { Calculator c(8); Register &x = c.getX(); c.input(Button::ca); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::plus); c.input(Button::d5); c.input(Button::percent); ASSERT_EQ(210, getIntValue(x)); c.input(Button::percent); ASSERT_EQ(210, getIntValue(x)); c.input(Button::equals); ASSERT_EQ(410, getIntValue(x)); c.input(Button::ca); c.input(Button::minus); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::plus); c.input(Button::d5); c.input(Button::percent); ASSERT_EQ(-210, getIntValue(x)); c.input(Button::percent); ASSERT_EQ(-210, getIntValue(x)); c.input(Button::equals); ASSERT_EQ(-410, getIntValue(x)); c.input(Button::ca); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::plus); c.input(Button::d5); c.input(Button::changeSign); c.input(Button::percent); ASSERT_EQ(190, getIntValue(x)); c.input(Button::percent); ASSERT_EQ(190, getIntValue(x)); c.input(Button::equals); ASSERT_EQ(-10, getIntValue(x)); c.input(Button::ca); c.input(Button::minus); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::plus); c.input(Button::d5); c.input(Button::changeSign); c.input(Button::percent); ASSERT_EQ(-190, getIntValue(x)); c.input(Button::percent); ASSERT_EQ(-190, getIntValue(x)); c.input(Button::equals); ASSERT_EQ(10, getIntValue(x)); } TEST_PERCENT(SubPercent) { Calculator c(8); Register &x = c.getX(); c.input(Button::ca); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::minus); c.input(Button::d5); c.input(Button::percent); ASSERT_EQ(190, getIntValue(x)); c.input(Button::percent); ASSERT_EQ(190, getIntValue(x)); c.input(Button::equals); ASSERT_EQ(-10, getIntValue(x)); c.input(Button::ca); c.input(Button::minus); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::minus); c.input(Button::d5); c.input(Button::percent); ASSERT_EQ(-190, getIntValue(x)); c.input(Button::percent); ASSERT_EQ(-190, getIntValue(x)); c.input(Button::equals); ASSERT_EQ(10, getIntValue(x)); c.input(Button::ca); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::minus); c.input(Button::d5); c.input(Button::changeSign); c.input(Button::percent); ASSERT_EQ(210, getIntValue(x)); c.input(Button::percent); ASSERT_EQ(210, getIntValue(x)); c.input(Button::equals); ASSERT_EQ(410, getIntValue(x)); c.input(Button::ca); c.input(Button::minus); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::minus); c.input(Button::d5); c.input(Button::changeSign); c.input(Button::percent); ASSERT_EQ(-210, getIntValue(x)); c.input(Button::percent); ASSERT_EQ(-210, getIntValue(x)); c.input(Button::equals); ASSERT_EQ(-410, getIntValue(x)); } TEST_PERCENT(MulPercent) { Calculator c(8); Register &x = c.getX(); Register &y = c.getY(); c.input(Button::ca); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::mul); c.input(Button::d5); c.input(Button::percent); ASSERT_EQ(10, getIntValue(x)); ASSERT_EQ(200, getIntValue(y)); c.input(Button::percent); ASSERT_EQ(20, getIntValue(x)); ASSERT_EQ(200, getIntValue(y)); c.input(Button::equals); ASSERT_EQ(4000, getIntValue(x)); ASSERT_EQ(200, getIntValue(y)); c.input(Button::ca); c.input(Button::minus); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::mul); c.input(Button::d5); c.input(Button::percent); ASSERT_EQ(-10, getIntValue(x)); ASSERT_EQ(-200, getIntValue(y)); c.input(Button::percent); ASSERT_EQ(20, getIntValue(x)); ASSERT_EQ(-200, getIntValue(y)); c.input(Button::equals); ASSERT_EQ(-4000, getIntValue(x)); ASSERT_EQ(-200, getIntValue(y)); c.input(Button::ca); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::mul); c.input(Button::d5); c.input(Button::changeSign); c.input(Button::percent); ASSERT_EQ(-10, getIntValue(x)); ASSERT_EQ(200, getIntValue(y)); c.input(Button::percent); ASSERT_EQ(-20, getIntValue(x)); ASSERT_EQ(200, getIntValue(y)); c.input(Button::equals); ASSERT_EQ(-4000, getIntValue(x)); ASSERT_EQ(200, getIntValue(y)); c.input(Button::ca); c.input(Button::minus); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::mul); c.input(Button::d5); c.input(Button::changeSign); c.input(Button::percent); ASSERT_EQ(10, getIntValue(x)); ASSERT_EQ(-200, getIntValue(y)); c.input(Button::percent); ASSERT_EQ(-20, getIntValue(x)); ASSERT_EQ(-200, getIntValue(y)); c.input(Button::equals); ASSERT_EQ(4000, getIntValue(x)); ASSERT_EQ(-200, getIntValue(y)); } TEST_PERCENT(DivPercent1) { Calculator c(8); Register &x = c.getX(); Register &y = c.getY(); c.input(Button::ca); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::div); c.input(Button::d5); c.input(Button::percent); ASSERT_EQ(4000, getIntValue(x)); ASSERT_EQ(5, getIntValue(y)); c.input(Button::percent); ASSERT_EQ(80000, getIntValue(x)); ASSERT_EQ(5, getIntValue(y)); c.input(Button::equals); ASSERT_EQ(16000, getIntValue(x)); ASSERT_EQ(5, getIntValue(y)); c.input(Button::ca); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::div); c.input(Button::d5); c.input(Button::changeSign); c.input(Button::percent); ASSERT_EQ(-4000, getIntValue(x)); ASSERT_EQ(-5, getIntValue(y)); c.input(Button::percent); ASSERT_EQ(80000, getIntValue(x)); ASSERT_EQ(-5, getIntValue(y)); c.input(Button::equals); ASSERT_EQ(-16000, getIntValue(x)); ASSERT_EQ(-5, getIntValue(y)); c.input(Button::ca); c.input(Button::minus); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::div); c.input(Button::d5); c.input(Button::percent); ASSERT_EQ(-4000, getIntValue(x)); ASSERT_EQ(5, getIntValue(y)); c.input(Button::percent); ASSERT_EQ(-80000, getIntValue(x)); ASSERT_EQ(5, getIntValue(y)); c.input(Button::equals); ASSERT_EQ(-16000, getIntValue(x)); ASSERT_EQ(5, getIntValue(y)); c.input(Button::ca); c.input(Button::minus); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::div); c.input(Button::d5); c.input(Button::changeSign); c.input(Button::percent); ASSERT_EQ(4000, getIntValue(x)); ASSERT_EQ(-5, getIntValue(y)); c.input(Button::percent); ASSERT_EQ(-80000, getIntValue(x)); ASSERT_EQ(-5, getIntValue(y)); c.input(Button::equals); ASSERT_EQ(16000, getIntValue(x)); ASSERT_EQ(-5, getIntValue(y)); }
26.938983
83
0.623632
DmitryDzz
463fb36ee7f82268919c4c195906ebf824f4fd3f
3,539
cpp
C++
projects/biogears/libBiogears/src/cdm/properties/SEScalarAmountPerVolume.cpp
Aaryan-kapur/core
5ebf096d18a3ddbe0259f83ca82a39607ba1f892
[ "Apache-2.0" ]
1
2020-03-13T17:43:34.000Z
2020-03-13T17:43:34.000Z
projects/biogears/libBiogears/src/cdm/properties/SEScalarAmountPerVolume.cpp
BhumikaSaini/core
baecdd736961d301fe2723858de94cef285296b0
[ "Apache-2.0" ]
5
2020-12-23T00:19:32.000Z
2020-12-29T20:53:58.000Z
projects/biogears/libBiogears/src/cdm/properties/SEScalarAmountPerVolume.cpp
BhumikaSaini/core
baecdd736961d301fe2723858de94cef285296b0
[ "Apache-2.0" ]
3
2020-02-23T06:20:08.000Z
2021-12-02T04:18:29.000Z
/************************************************************************************** Copyright 2015 Applied Research Associates, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **************************************************************************************/ #include <biogears/cdm/properties/SEScalarAmountPerVolume.h> namespace biogears { AmountPerVolumeUnit AmountPerVolumeUnit::mol_Per_L("mol/L"); AmountPerVolumeUnit AmountPerVolumeUnit::mol_Per_mL("mol/mL"); AmountPerVolumeUnit AmountPerVolumeUnit::mmol_Per_L("mmol/L"); AmountPerVolumeUnit AmountPerVolumeUnit::mmol_Per_mL("mmol/mL"); AmountPerVolumeUnit AmountPerVolumeUnit::ct_Per_L("ct/L"); AmountPerVolumeUnit AmountPerVolumeUnit::ct_Per_uL("ct/uL"); AmountPerVolumeUnit::AmountPerVolumeUnit(const char* u) : AmountPerVolumeUnit(std::string{ u }) { } //------------------------------------------------------------------------------- AmountPerVolumeUnit::AmountPerVolumeUnit(const std::string& u) : CCompoundUnit(u) { } //------------------------------------------------------------------------------- CDM::ScalarAmountPerVolumeData* SEScalarAmountPerVolume::Unload() const { if (!IsValid()) return nullptr; CDM::ScalarAmountPerVolumeData* data(new CDM::ScalarAmountPerVolumeData()); SEScalarQuantity::Unload(*data); return data; } //------------------------------------------------------------------------------- bool AmountPerVolumeUnit::IsValidUnit(const char* unit) { if (strcmp(mol_Per_L.GetString(),unit) == 0) return true; if (strcmp(mol_Per_mL.GetString(),unit) == 0) return true; if (strcmp(mmol_Per_L.GetString(),unit) == 0) return true; if (strcmp(mmol_Per_mL.GetString(),unit) == 0) return true; if (strcmp(ct_Per_L.GetString(),unit) == 0) return true; if (strcmp(ct_Per_uL.GetString(),unit) == 0) return true; return false; } //------------------------------------------------------------------------------- bool AmountPerVolumeUnit::IsValidUnit(const std::string& unit) { return IsValidUnit(unit.c_str()); } //------------------------------------------------------------------------------- const AmountPerVolumeUnit& AmountPerVolumeUnit::GetCompoundUnit(const char* unit) { if (strcmp(mol_Per_L.GetString(),unit) == 0) return mol_Per_L; if (strcmp(mol_Per_mL.GetString(),unit) == 0) return mol_Per_mL; if (strcmp(mmol_Per_L.GetString(),unit) == 0) return mmol_Per_L; if (strcmp(mmol_Per_mL.GetString(),unit) == 0) return mmol_Per_mL; if (strcmp(ct_Per_L.GetString(),unit) == 0) return ct_Per_L; if (strcmp(ct_Per_uL.GetString(),unit) == 0) return ct_Per_uL; std::stringstream err; err << unit << " is not a valid AmountPerVolume unit"; throw CommonDataModelException(err.str()); } //------------------------------------------------------------------------------- const AmountPerVolumeUnit& AmountPerVolumeUnit::GetCompoundUnit(const std::string& unit) { return GetCompoundUnit(unit.c_str()); } //------------------------------------------------------------------------------- }
40.678161
88
0.593105
Aaryan-kapur
4643ab8154366f53cffbe193c750fd0a35c954a3
578
cpp
C++
barelymusician/dsp/one_pole_filter.cpp
anokta/barelymusician
5e3485c80cc74c4bcbc0653c0eb8750ad44981d6
[ "MIT" ]
6
2021-11-25T17:40:21.000Z
2022-03-24T03:38:11.000Z
barelymusician/dsp/one_pole_filter.cpp
anokta/barelymusician
5e3485c80cc74c4bcbc0653c0eb8750ad44981d6
[ "MIT" ]
17
2021-11-27T00:10:39.000Z
2022-03-30T00:33:51.000Z
barelymusician/dsp/one_pole_filter.cpp
anokta/barelymusician
5e3485c80cc74c4bcbc0653c0eb8750ad44981d6
[ "MIT" ]
null
null
null
#include "barelymusician/dsp/one_pole_filter.h" #include <algorithm> namespace barelyapi { double OnePoleFilter::Next(double input) noexcept { output_ = coefficient_ * (output_ - input) + input; if (type_ == FilterType::kHighPass) { return input - output_; } return output_; } void OnePoleFilter::Reset() noexcept { output_ = 0.0; } void OnePoleFilter::SetCoefficient(double coefficient) noexcept { coefficient_ = std::min(std::max(coefficient, 0.0), 1.0); } void OnePoleFilter::SetType(FilterType type) noexcept { type_ = type; } } // namespace barelyapi
24.083333
71
0.719723
anokta
4647b087057511edb5817108d19eb772335602fb
10,906
cpp
C++
src/dev/steve/ScarrArm/ScarrArmModel.cpp
wvat/NTRTsim
0443cbd542e12e23c04adf79ea0d8d003c428baa
[ "Apache-2.0" ]
148
2015-01-08T22:44:00.000Z
2022-03-19T18:42:48.000Z
src/dev/steve/ScarrArm/ScarrArmModel.cpp
wvat/NTRTsim
0443cbd542e12e23c04adf79ea0d8d003c428baa
[ "Apache-2.0" ]
107
2015-01-02T16:41:42.000Z
2021-06-14T22:09:19.000Z
src/dev/steve/ScarrArm/ScarrArmModel.cpp
wvat/NTRTsim
0443cbd542e12e23c04adf79ea0d8d003c428baa
[ "Apache-2.0" ]
86
2015-01-06T07:02:36.000Z
2022-02-28T17:36:14.000Z
/* * Copyright © 2015, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform 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. */ /** * @file ScarrArmModel.cpp * @brief Contains the implementation of class ScarrArmModel. See README * $Id$ */ // This module #include "ScarrArmModel.h" // This library #include "core/tgBasicActuator.h" #include "core/tgRod.h" #include "core/abstractMarker.h" #include "tgcreator/tgBuildSpec.h" #include "tgcreator/tgBasicActuatorInfo.h" #include "tgcreator/tgKinematicContactCableInfo.h" #include "tgcreator/tgRodInfo.h" #include "tgcreator/tgStructure.h" #include "tgcreator/tgStructureInfo.h" // The Bullet Physics library #include "LinearMath/btVector3.h" // The C++ Standard Library #include <stdexcept> namespace { // see tgBaseString.h for a descripton of some of these rod parameters // (specifically, those related to the motor moving the strings.) // NOTE that any parameter that depends on units of length will scale // with the current gravity scaling. E.g., with gravity as 98.1, // the length units below are in decimeters. const struct ConfigRod { double density; double radius; double rod_length; double rod_space; double friction; double rollFriction; double restitution; } cRod = { 0.05, // density (kg / length^3) 0.8, // radius (length) 15.0, // rod_length (length) 7.5, // rod_space (length) 1.0, // friction (unitless) 0.01, // rollFriction (unitless) 0.2 // restitution (?) }; const struct ConfigCable { double elasticity; double damping; double stiffness; double pretension_olecranon; double pretension_anconeus; double pretension_brachioradialis; double pretension_support; bool history; double maxTens; double targetVelocity; double mRad; double motorFriction; double motorInertia; bool backDrivable; } cCable = { 1000.0, // elasticity 200.0, // damping (kg/s) 3000.0, // stiffness (kg / sec^2) 3000.0/1, // pretension_olecranon (force), stiffness/initial length 3000.0/15.55, // pretension_anconeus (force), stiffness/initial length 3000.0/262, // pretension_brachioradialis (force), stiffness/initial length 30000.0/1, // pretension_support (force), stiffness/initial length false, // history (boolean) 100000, // maxTens 10000, // targetVelocity 1.0, // mRad 10.0, // motorFriction 1.0, // motorInertia false // backDrivable (boolean) }; } // namespace ScarrArmModel::ScarrArmModel() : tgModel() {} ScarrArmModel::~ScarrArmModel() {} void ScarrArmModel::addNodes(tgStructure& s) { const double scale = 0.5; const double bone_scale = 0.3; const size_t nNodes = 15 + 2; //2 for massless rod // Average Adult Male Measurements with scale // Lengths are in mm const double a = 22 * scale; //ulnta distal width const double b = 334 * scale * bone_scale; //ulna length const double c = 265 * scale * bone_scale; //humerus length //NB: in model, c==b //const double d = 66 * scale; // humerus epicondylar width //const double e = 246 * scale * bone_scale; //radius length const double f = 25 * scale; // humerus head radius const double g = 17 * scale; //ulna proximal width const double x = a/2; const double z = c/2; //Format: (x, z, y) nodePositions.push_back(btVector3(g, 0, 0)); nodePositions.push_back(btVector3(0, -g, 0)); nodePositions.push_back(btVector3(-a/2, 0, 0)); nodePositions.push_back(btVector3(0, 0, g)); nodePositions.push_back(btVector3(0, 0, -g)); nodePositions.push_back(btVector3(0, g, 0)); nodePositions.push_back(btVector3(0, c, 0)); nodePositions.push_back(btVector3(x, z, 0)); nodePositions.push_back(btVector3(b+a/2, -g, 0)); nodePositions.push_back(btVector3(0, c+2, f)); nodePositions.push_back(btVector3(0, c+2, -f)); //Added 6/17/15 nodePositions.push_back(btVector3(a/2, -2*g, 0)); //ulna and radius nodePositions.push_back(btVector3(3*a/2, -g, 0)); nodePositions.push_back(btVector3(3*a/4, -g, g)); nodePositions.push_back(btVector3(3*a/4, -g, -g)); nodePositions.push_back(btVector3(f, c+2, 0)); nodePositions.push_back(btVector3(-f, c+2, 0)); for(size_t i=0;i<nNodes;i++) { s.addNode(nodePositions[i][0],nodePositions[i][1],nodePositions[i][2]); } } void ScarrArmModel::addRods(tgStructure& s) { // ulna and radius s.addPair(8, 12, "rod"); s.addPair(12, 14, "rod"); s.addPair(12, 13, "rod"); //olecranon s.addPair(0, 1, "rod"); s.addPair(1, 2, "rod"); s.addPair(1, 11, "rod"); // humerus s.addPair(3, 5, "humerus massless"); s.addPair(4, 5, "humerus massless"); s.addPair(5, 6, "humerus massless"); } void ScarrArmModel::addMuscles(tgStructure& s) { const std::vector<tgStructure*> children = s.getChildren(); s.addPair(0, 3, "olecranon muscle"); //NB actually fascial tissue s.addPair(0, 4, "olecranon muscle"); //NB actually fascial tissue s.addPair(1, 3, "olecranon muscle"); //NB actually fascial tissue s.addPair(1, 4, "olecranon muscle"); //NB actually fascial tissue s.addPair(2, 3, "olecranon muscle"); //NB actually fascial tissue s.addPair(2, 4, "olecranon muscle"); //NB actually fascial tissue s.addPair(0, 13, "olecranon muscle"); //NB actually fascial tissue s.addPair(1, 13, "olecranon muscle"); //NB actually fascial tissue s.addPair(11, 13, "olecranon muscle"); //NB actually fascial tissue s.addPair(0, 14, "olecranon muscle"); //NB actually fascial tissue s.addPair(1, 14, "olecranon muscle"); //NB actually fascial tissue s.addPair(11, 14, "olecranon muscle"); //NB actually fascial tissue s.addPair(0, 12, "olecranon muscle"); //NB actually fascial tissue s.addPair(11, 12, "olecranon muscle"); //NB actually fascial tissue s.addPair(0, 5, "brachioradialis muscle"); s.addPair(2, 5, "olecranon muscle"); //NB actually fascial tissue s.addPair(3, 13, "right anconeus muscle"); s.addPair(4, 14, "left anconeus muscle"); } /* void ScarrArmModel::addMarkers(tgStructure &s) { std::vector<tgRod *> rods=find<tgRod>("rod"); for(int i=0;i<10;i++) { const btRigidBody* bt = rods[rodNumbersPerNode[i]]->getPRigidBody(); btTransform inverseTransform = bt->getWorldTransform().inverse(); btVector3 pos = inverseTransform * (nodePositions[i]); abstractMarker tmp=abstractMarker(bt,pos,btVector3(0.08*i,1.0 - 0.08*i,.0),i); this->addMarker(tmp); } } */ void ScarrArmModel::setup(tgWorld& world) { const tgRod::Config rodConfig(cRod.radius, cRod.density, cRod.friction, cRod.rollFriction, cRod.restitution); const tgRod::Config rodConfigMassless(cRod.radius, 0.00/*c.density*/, cRod.friction, cRod.rollFriction, cRod.restitution); /// @todo acceleration constraint was removed on 12/10/14 Replace with tgKinematicActuator as appropreate tgBasicActuator::Config olecranonMuscleConfig(cCable.stiffness, cCable.damping, cCable.pretension_olecranon, cCable.history, cCable.maxTens, cCable.targetVelocity); tgBasicActuator::Config anconeusMuscleConfig(cCable.stiffness, cCable.damping, cCable.pretension_anconeus, cCable.history, cCable.maxTens, cCable.targetVelocity); tgBasicActuator::Config brachioradialisMuscleConfig(cCable.stiffness, cCable.damping, cCable.pretension_brachioradialis, cCable.history, cCable.maxTens, cCable.targetVelocity); tgBasicActuator::Config supportstringMuscleConfig(cCable.stiffness, cCable.damping, cCable.pretension_support, cCable.history, cCable.maxTens, cCable.targetVelocity); // Start creating the structure tgStructure s; addNodes(s); addRods(s); addMuscles(s); // Move the arm out of the ground btVector3 offset(0.0, 50.0, 0.0); s.move(offset); // Create the build spec that uses tags to turn the structure into a real model tgBuildSpec spec; spec.addBuilder("massless", new tgRodInfo(rodConfigMassless)); spec.addBuilder("rod", new tgRodInfo(rodConfig)); spec.addBuilder("olecranon muscle", new tgBasicActuatorInfo(olecranonMuscleConfig)); spec.addBuilder("anconeus muscle", new tgBasicActuatorInfo(anconeusMuscleConfig)); spec.addBuilder("brachioradialis muscle", new tgBasicActuatorInfo(brachioradialisMuscleConfig)); spec.addBuilder("support muscle", new tgBasicActuatorInfo(supportstringMuscleConfig)); // Create your structureInfo tgStructureInfo structureInfo(s, spec); // Use the structureInfo to build ourselves structureInfo.buildInto(*this, world); // We could now use tgCast::filter or similar to pull out the // models (e.g. muscles) that we want to control. allMuscles = tgCast::filter<tgModel, tgBasicActuator> (getDescendants()); // call the onSetup methods of all observed things e.g. controllers notifySetup(); // Actually setup the children tgModel::setup(world); //map the rods and add the markers to them //addMarkers(s); } void ScarrArmModel::step(double dt) { // Precondition if (dt <= 0.0) { throw std::invalid_argument("dt is not positive"); } else { // Notify observers (controllers) of the step so that they can take action notifyStep(dt); tgModel::step(dt); // Step any children } } void ScarrArmModel::onVisit(tgModelVisitor& r) { tgModel::onVisit(r); } const std::vector<tgBasicActuator*>& ScarrArmModel::getAllMuscles() const { return allMuscles; } void ScarrArmModel::teardown() { notifyTeardown(); tgModel::teardown(); }
37.737024
126
0.656703
wvat
46498961a608ee3f3a53e462acc2ee7f0d39f35f
415
cpp
C++
sursa.cpp
seerj30/backtracking-recursiv_permutari
8ec7d75ed50305e68527d6dd74133910d9c35256
[ "MIT" ]
null
null
null
sursa.cpp
seerj30/backtracking-recursiv_permutari
8ec7d75ed50305e68527d6dd74133910d9c35256
[ "MIT" ]
null
null
null
sursa.cpp
seerj30/backtracking-recursiv_permutari
8ec7d75ed50305e68527d6dd74133910d9c35256
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int n; void back(int st[], int k) { int i,ev,j; if(k==n+1) { for(int i = 1; i < k; i++) cout << st[i] << " "; cout << endl; } else for(int i = 1; i <= n; i++) { st[k] = i; ev=1; for(j = 1; j < k; j++) if(st[j] == st[k]) ev=0; if(ev) back(st, k+1); } } int main() { int st[50]; cout << "n="; cin >> n; back(st, 1); return 0; }
12.205882
29
0.436145
seerj30
464a3aeedf7fb4a9e26ce09eb1d2a829735d1f65
1,829
hh
C++
test/CLI/AppTest.hh
decouple/decouple.io
c841e905fbc8bd9507759a0ef6e56e1985c56c5a
[ "MIT" ]
null
null
null
test/CLI/AppTest.hh
decouple/decouple.io
c841e905fbc8bd9507759a0ef6e56e1985c56c5a
[ "MIT" ]
null
null
null
test/CLI/AppTest.hh
decouple/decouple.io
c841e905fbc8bd9507759a0ef6e56e1985c56c5a
[ "MIT" ]
null
null
null
<?hh // partial namespace Test\CLI; use Decouple\CLI\App; use Decouple\CLI\Request\Request; use Decouple\Decoupler\Decoupler; use Decouple\Registry\Paths; use Decouple\CLI\Console; class AppTest extends \Decouple\Test\TestCase { public function execute() : void { Console::output('Testing CLI bootstrap (version)'); $this->testBootstrapA(); Console::output('Testing CLI bootstrap (FooCommand)'); $this->testBootstrapB(); Console::output('Testing CLI bootstrap (BarCommand)'); $this->testBootstrapC(); } public function testBootstrapA() : void { $app = $this->__bootstrap("decouple:version"); $result = $this->capture($app); $this->assertEquals($result, "Decouple v0.1a\n"); Console::output('Passed'); } public function testBootstrapB() : void { $app = $this->__bootstrap("foo:bar"); $result = $this->capture($app); $this->assertEquals($result, "FooBar!\n"); Console::output('Passed'); } public function testBootstrapC() : void { $app = $this->__bootstrap("bar:baz --bar=wtf!"); $result = $this->capture($app); $this->assertEquals($result, "bar:wtf!\n"); Console::output('Passed'); } public function __bootstrap(string $args) : App { $args = stristr($args, ' ') ? new Vector(explode(' ', $args)) : Vector { $args }; $request = new Request($args); $services = Map {"Decouple\\CLI\\Request\Request" => $request}; $decoupler = new Decoupler($services); $app = new App($request, $decoupler, new Paths(Map { }), Vector { "Test\CLI\Fixture\FooCommand", "Test\CLI\Fixture\BarCommand" }); return $app; } public function capture(App $app) : string { ob_start(); try { $app->execute(); } catch(Exception $e) { echo $e->getMessage(); } return ob_get_clean(); } }
29.031746
85
0.631493
decouple
464b0c44e0f870c5e760b5c4e5248cfc41c05ea1
14,229
cpp
C++
modules/Math/test/Vector4Test.cpp
akb825/DeepSea
fff790d0a472cf2f9f89de653e0b4470ce605d24
[ "Apache-2.0" ]
5
2018-11-17T23:13:22.000Z
2021-09-30T13:37:04.000Z
modules/Math/test/Vector4Test.cpp
akb825/DeepSea
fff790d0a472cf2f9f89de653e0b4470ce605d24
[ "Apache-2.0" ]
null
null
null
modules/Math/test/Vector4Test.cpp
akb825/DeepSea
fff790d0a472cf2f9f89de653e0b4470ce605d24
[ "Apache-2.0" ]
2
2019-09-23T12:23:35.000Z
2020-04-07T05:31:06.000Z
/* * Copyright 2016 Aaron Barany * * 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 <DeepSea/Math/Vector4.h> #include <gtest/gtest.h> #include <cmath> // Handle older versions of gtest. #ifndef TYPED_TEST_SUITE #define TYPED_TEST_SUITE TYPED_TEST_CASE #endif template <typename T> struct Vector4TypeSelector; template <> struct Vector4TypeSelector<float> {typedef dsVector4f Type;}; template <> struct Vector4TypeSelector<double> {typedef dsVector4d Type;}; template <> struct Vector4TypeSelector<int> {typedef dsVector4i Type;}; template <typename T> class Vector4Test : public testing::Test { }; using Vector4Types = testing::Types<float, double, int>; TYPED_TEST_SUITE(Vector4Test, Vector4Types); template <typename T> class Vector4FloatTest : public Vector4Test<T> { }; using Vector4FloatTypes = testing::Types<float, double>; TYPED_TEST_SUITE(Vector4FloatTest, Vector4FloatTypes); inline float dsVector4_len(dsVector4f* a) { return dsVector4f_len(a); } inline double dsVector4_len(dsVector4d* a) { return dsVector4d_len(a); } inline double dsVector4_len(dsVector4i* a) { return dsVector4i_len(a); } inline float dsVector4_dist(dsVector4f* a, dsVector4f* b) { return dsVector4f_dist(a, b); } inline double dsVector4_dist(dsVector4d* a, dsVector4d* b) { return dsVector4d_dist(a, b); } inline double dsVector4_dist(dsVector4i* a, dsVector4i* b) { return dsVector4i_dist(a, b); } inline void dsVector4_normalize(dsVector4f* result, dsVector4f* a) { dsVector4f_normalize(result, a); } inline void dsVector4_normalize(dsVector4d* result, dsVector4d* a) { dsVector4d_normalize(result, a); } inline bool dsVector4_epsilonEqual(const dsVector4f* a, const dsVector4f* b, float epsilon) { return dsVector4f_epsilonEqual(a, b, epsilon); } inline bool dsVector4_epsilonEqual(const dsVector4d* a, const dsVector4d* b, double epsilon) { return dsVector4d_epsilonEqual(a, b, epsilon); } inline bool dsVector4_relativeEpsilonEqual(const dsVector4f* a, const dsVector4f* b, float epsilon) { return dsVector4f_relativeEpsilonEqual(a, b, epsilon); } inline bool dsVector4_relativeEpsilonEqual(const dsVector4d* a, const dsVector4d* b, double epsilon) { return dsVector4d_relativeEpsilonEqual(a, b, epsilon); } TYPED_TEST(Vector4Test, Initialize) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; EXPECT_EQ((TypeParam)-2.3, a.x); EXPECT_EQ((TypeParam)4.5, a.y); EXPECT_EQ((TypeParam)-6.7, a.z); EXPECT_EQ((TypeParam)8.9, a.w); EXPECT_EQ((TypeParam)-2.3, a.s); EXPECT_EQ((TypeParam)4.5, a.t); EXPECT_EQ((TypeParam)-6.7, a.p); EXPECT_EQ((TypeParam)8.9, a.q); EXPECT_EQ((TypeParam)-2.3, a.r); EXPECT_EQ((TypeParam)4.5, a.g); EXPECT_EQ((TypeParam)-6.7, a.b); EXPECT_EQ((TypeParam)8.9, a.w); EXPECT_EQ((TypeParam)-2.3, a.values[0]); EXPECT_EQ((TypeParam)4.5, a.values[1]); EXPECT_EQ((TypeParam)-6.7, a.values[2]); EXPECT_EQ((TypeParam)8.9, a.values[3]); } TYPED_TEST(Vector4Test, Add) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type b = {{(TypeParam)3.2, (TypeParam)-5.4, (TypeParam)7.6, (TypeParam)-9.8}}; Vector4Type result; dsVector4_add(result, a, b); EXPECT_EQ((TypeParam)-2.3 + (TypeParam)3.2, result.x); EXPECT_EQ((TypeParam)4.5 + (TypeParam)-5.4, result.y); EXPECT_EQ((TypeParam)-6.7 + (TypeParam)7.6, result.z); EXPECT_EQ((TypeParam)8.9 + (TypeParam)-9.8, result.w); } TYPED_TEST(Vector4Test, Subtract) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type b = {{(TypeParam)3.2, (TypeParam)-5.4, (TypeParam)7.6, (TypeParam)-9.8}}; Vector4Type result; dsVector4_sub(result, a, b); EXPECT_EQ((TypeParam)-2.3 - (TypeParam)3.2, result.x); EXPECT_EQ((TypeParam)4.5 - (TypeParam)-5.4, result.y); EXPECT_EQ((TypeParam)-6.7 - (TypeParam)7.6, result.z); EXPECT_EQ((TypeParam)8.9 - (TypeParam)-9.8, result.w); } TYPED_TEST(Vector4Test, Multiply) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type b = {{(TypeParam)3.2, (TypeParam)-5.4, (TypeParam)7.6, (TypeParam)-9.8}}; Vector4Type result; dsVector4_mul(result, a, b); EXPECT_EQ((TypeParam)-2.3 * (TypeParam)3.2, result.x); EXPECT_EQ((TypeParam)4.5 * (TypeParam)-5.4, result.y); EXPECT_EQ((TypeParam)-6.7 * (TypeParam)7.6, result.z); EXPECT_EQ((TypeParam)8.9 * (TypeParam)-9.8, result.w); } TYPED_TEST(Vector4Test, Divide) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type b = {{(TypeParam)3.2, (TypeParam)-5.4, (TypeParam)7.6, (TypeParam)-9.8}}; Vector4Type result; dsVector4_div(result, a, b); EXPECT_EQ((TypeParam)-2.3 / (TypeParam)3.2, result.x); EXPECT_EQ((TypeParam)4.5 / (TypeParam)-5.4, result.y); EXPECT_EQ((TypeParam)-6.7 / (TypeParam)7.6, result.z); EXPECT_EQ((TypeParam)8.9 / (TypeParam)-9.8, result.w); } TYPED_TEST(Vector4Test, Scale) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type result; dsVector4_scale(result, a, (TypeParam)3.2); EXPECT_EQ((TypeParam)-2.3 * (TypeParam)3.2, result.x); EXPECT_EQ((TypeParam)4.5 * (TypeParam)3.2, result.y); EXPECT_EQ((TypeParam)-6.7 * (TypeParam)3.2, result.z); EXPECT_EQ((TypeParam)8.9 * (TypeParam)3.2, result.w); } TYPED_TEST(Vector4Test, Neg) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type result; dsVector4_neg(result, a); EXPECT_EQ(-a.x, result.x); EXPECT_EQ(-a.y, result.y); EXPECT_EQ(-a.z, result.z); EXPECT_EQ(-a.w, result.w); } TYPED_TEST(Vector4Test, Dot) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type b = {{(TypeParam)3.2, (TypeParam)-5.4, (TypeParam)7.6, (TypeParam)-9.8}}; EXPECT_EQ((TypeParam)-2.3*(TypeParam)3.2 + (TypeParam)4.5*(TypeParam)-5.4 + (TypeParam)-6.7*(TypeParam)7.6 + (TypeParam)8.9*(TypeParam)-9.8, dsVector4_dot(a, b)); } TYPED_TEST(Vector4Test, Length) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; EXPECT_EQ(dsPow2((TypeParam)-2.3) + dsPow2((TypeParam)4.5) + dsPow2((TypeParam)-6.7) + dsPow2((TypeParam)8.9), dsVector4_len2(a)); EXPECT_EQ(std::sqrt(dsPow2((TypeParam)-2.3) + dsPow2((TypeParam)4.5) + dsPow2((TypeParam)-6.7) + dsPow2((TypeParam)8.9)), dsVector4_len(&a)); } TYPED_TEST(Vector4Test, Distance) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type b = {{(TypeParam)3.2, (TypeParam)-5.4, (TypeParam)7.6, (TypeParam)-9.8}}; EXPECT_EQ(dsPow2((TypeParam)-2.3 - (TypeParam)3.2) + dsPow2((TypeParam)4.5 - (TypeParam)-5.4) + dsPow2((TypeParam)-6.7 - (TypeParam)7.6) + dsPow2((TypeParam)8.9 - (TypeParam)-9.8), dsVector4_dist2(a, b)); EXPECT_EQ(std::sqrt(dsPow2((TypeParam)-2.3 - (TypeParam)3.2) + dsPow2((TypeParam)4.5 - (TypeParam)-5.4) + dsPow2((TypeParam)-6.7 - (TypeParam)7.6) + dsPow2((TypeParam)8.9 - (TypeParam)-9.8)), dsVector4_dist(&a, &b)); } TYPED_TEST(Vector4Test, Equal) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type b = {{(TypeParam)2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type c = {{(TypeParam)-2.3, (TypeParam)-4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type d = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)6.7, (TypeParam)8.9}}; Vector4Type e = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)-8.9}}; EXPECT_TRUE(dsVector4_equal(a, a)); EXPECT_FALSE(dsVector4_equal(a, b)); EXPECT_FALSE(dsVector4_equal(a, c)); EXPECT_FALSE(dsVector4_equal(a, d)); EXPECT_FALSE(dsVector4_equal(a, e)); } TEST(Vector4IntTest, Lerp) { dsVector4i a = {{-2, 4, -6, 8}}; dsVector4i b = {{3, -5, 7, -9}}; dsVector4i result; dsVector4i_lerp(&result, &a, &b, 0.3f); EXPECT_EQ(0, result.x); EXPECT_EQ(1, result.y); EXPECT_EQ(-2, result.z); EXPECT_EQ(2, result.w); } TYPED_TEST(Vector4FloatTest, Lerp) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type b = {{(TypeParam)3.2, (TypeParam)-5.4, (TypeParam)7.6, (TypeParam)-9.8}}; Vector4Type result; dsVector4_lerp(result, a, b, (TypeParam)0.3); EXPECT_EQ(dsLerp(a.x, b.x, (TypeParam)0.3), result.x); EXPECT_EQ(dsLerp(a.y, b.y, (TypeParam)0.3), result.y); EXPECT_EQ(dsLerp(a.z, b.z, (TypeParam)0.3), result.z); EXPECT_EQ(dsLerp(a.w, b.w, (TypeParam)0.3), result.w); } TYPED_TEST(Vector4FloatTest, Normalize) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type result; TypeParam length = dsVector4_len(&a); dsVector4_normalize(&result, &a); EXPECT_EQ((TypeParam)-2.3*(1/length), result.x); EXPECT_EQ((TypeParam)4.5*(1/length), result.y); EXPECT_EQ((TypeParam)-6.7*(1/length), result.z); EXPECT_EQ((TypeParam)8.9*(1/length), result.w); } TYPED_TEST(Vector4FloatTest, EpsilonEqual) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; TypeParam epsilon = (TypeParam)1e-3; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type b = {{(TypeParam)-2.3001, (TypeParam)4.5001, (TypeParam)-6.7001, (TypeParam)8.9001}}; Vector4Type c = {{(TypeParam)-2.31, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type d = {{(TypeParam)-2.3, (TypeParam)4.51, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type e = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.71, (TypeParam)8.9}}; Vector4Type f = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.91}}; EXPECT_TRUE(dsVector4_epsilonEqual(&a, &b, epsilon)); EXPECT_FALSE(dsVector4_epsilonEqual(&a, &c, epsilon)); EXPECT_FALSE(dsVector4_epsilonEqual(&a, &d, epsilon)); EXPECT_FALSE(dsVector4_epsilonEqual(&a, &e, epsilon)); EXPECT_FALSE(dsVector4_epsilonEqual(&a, &f, epsilon)); } TYPED_TEST(Vector4FloatTest, RelativeEpsilonEqual) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; TypeParam epsilon = (TypeParam)1e-3; Vector4Type a = {{(TypeParam)-23.0, (TypeParam)45.0, (TypeParam)-67.0, (TypeParam)89.0}}; Vector4Type b = {{(TypeParam)-23.001, (TypeParam)45.001, (TypeParam)-67.001, (TypeParam)89.001}}; Vector4Type c = {{(TypeParam)-23.1, (TypeParam)45.0, (TypeParam)-67.0, (TypeParam)89.0}}; Vector4Type d = {{(TypeParam)-23.0, (TypeParam)45.1, (TypeParam)-67.0, (TypeParam)89.0}}; Vector4Type e = {{(TypeParam)-23.0, (TypeParam)45.0, (TypeParam)-67.1, (TypeParam)89.0}}; Vector4Type f = {{(TypeParam)-23.0, (TypeParam)45.0, (TypeParam)-67.0, (TypeParam)89.1}}; EXPECT_TRUE(dsVector4_relativeEpsilonEqual(&a, &b, epsilon)); EXPECT_FALSE(dsVector4_relativeEpsilonEqual(&a, &c, epsilon)); EXPECT_FALSE(dsVector4_relativeEpsilonEqual(&a, &d, epsilon)); EXPECT_FALSE(dsVector4_relativeEpsilonEqual(&a, &e, epsilon)); EXPECT_FALSE(dsVector4_relativeEpsilonEqual(&a, &f, epsilon)); } TEST(Vector4, ConvertFloatToDouble) { dsVector4f vectorf = {{-2.3f, 4.5f, -6.7f, 8.9f}}; dsVector4d vectord; dsConvertFloatToDouble(vectord, vectorf); EXPECT_FLOAT_EQ(vectorf.x, (float)vectord.x); EXPECT_FLOAT_EQ(vectorf.y, (float)vectord.y); EXPECT_FLOAT_EQ(vectorf.z, (float)vectord.z); EXPECT_FLOAT_EQ(vectorf.w, (float)vectord.w); } TEST(Vector4, ConvertDoubleToFloat) { dsVector4d vectord = {{-2.3, 4.5, -6.7, 8.9}}; dsVector4f vectorf; dsConvertDoubleToFloat(vectorf, vectord); EXPECT_FLOAT_EQ((float)vectord.x, vectorf.x); EXPECT_FLOAT_EQ((float)vectord.y, vectorf.y); EXPECT_FLOAT_EQ((float)vectord.z, vectorf.z); EXPECT_FLOAT_EQ((float)vectord.w, vectorf.w); } TEST(Vector4, ConvertFloatToInt) { dsVector4f vectorf = {{-2, 3, -4, 5}}; dsVector4i vectori; dsConvertFloatToInt(vectori, vectorf); EXPECT_EQ(vectorf.x, (float)vectori.x); EXPECT_EQ(vectorf.y, (float)vectori.y); EXPECT_EQ(vectorf.z, (float)vectori.z); EXPECT_EQ(vectorf.w, (float)vectori.w); } TEST(Vector4, ConvertIntToFloat) { dsVector4i vectori = {{-2, 3, -4, 5}}; dsVector4f vectorf; dsConvertIntToFloat(vectorf, vectori); EXPECT_EQ(vectori.x, (int)vectorf.x); EXPECT_EQ(vectori.y, (int)vectorf.y); EXPECT_EQ(vectori.z, (int)vectorf.z); EXPECT_EQ(vectori.w, (int)vectorf.w); } TEST(Vector4, ConvertDoubleToInt) { dsVector4d vectord = {{-2, 3, -4, 5}}; dsVector4i vectori; dsConvertDoubleToInt(vectori, vectord); EXPECT_EQ(vectord.x, vectori.x); EXPECT_EQ(vectord.y, vectori.y); EXPECT_EQ(vectord.z, vectori.z); EXPECT_EQ(vectord.w, vectori.w); } TEST(Vector4, ConvertIntToDouble) { dsVector4i vectori = {{-2, 3, -4, 5}}; dsVector4d vectord; dsConvertIntToDouble(vectord, vectori); EXPECT_EQ(vectori.x, vectord.x); EXPECT_EQ(vectori.y, vectord.y); EXPECT_EQ(vectori.z, vectord.z); EXPECT_EQ(vectori.w, vectord.w); }
31.135667
100
0.710661
akb825
464b77d844ad0b1b829a3053a1afbc119a63c6ad
4,139
cpp
C++
cha1/max_subarray.cpp
byzhou/CLRS
1af11fc971b9b91a050cdb1f2b3cf9a9471c8a22
[ "MIT" ]
null
null
null
cha1/max_subarray.cpp
byzhou/CLRS
1af11fc971b9b91a050cdb1f2b3cf9a9471c8a22
[ "MIT" ]
null
null
null
cha1/max_subarray.cpp
byzhou/CLRS
1af11fc971b9b91a050cdb1f2b3cf9a9471c8a22
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdlib> #include <ctime> #include <time.h> #include <stdio.h> using namespace std; const int neg_infinity = 0xFFFFFFFF ; const int pos_infinity = 0x7FFFFFFF ; void print_array ( int* array , int num ) ; void diff_array ( int* array, int* diff_array ) ; void max_cross_subarray ( int* array , int& left , int mid , int& right ) ; struct left_right { int left ; int right ; int sum ; }; /* For a given array, this function print out the array's * elements. */ void print_array ( int* array , int num ) { printf ( "Below is the the array: \n " ) ; for ( int i = 0 ; i < num ; i ++ ) { printf ( "%d \t", array[i] ) ; } printf ( "\n " ) ; } /* This function will take the diff between two elements of an * array. */ void diff_array ( int* array , int* diff_array ) { if ( (array + 1) == NULL ) printf ( " This array has too less elements. \n " ) ; for ( int i = 0 ; (array + i + 1) != NULL ; i ++ ) diff_array[i] = array[i+1] - array[i]; } struct left_right max_cross_subarray ( int* array , int left , int mid , int right ) { int left_sum = neg_infinity ; int right_sum = neg_infinity ; int sum = 0 ; int i = 0 ; int return_left = 0 ; int return_right= 0 ; struct left_right tmp; if (left == mid || mid == right || left == right) return 0; for ( i = mid ; i > left ; i -- ) { sum += array[i] ; if ( sum > left_sum ) left_sum = sum ; return_left = i ; } tmp.left = return_left ; for ( i = mid ; i < right ; i ++ ) { sum += array[i] ; if ( sum > right_sum ) right_sum = sum ; return_right = i ; } tmp.right = return_right ; tmp.sum = left_sum + right_sum ; return tmp; } struct left_right max_subarray ( int* array , int left , int right ) { int left_sum = neg_infinity ; int right_sum = neg_infinity ; int mid_sum = neg_infinity ; int mid = (left + right) / 2 ; struct left_rigth tmp ; tmp.left = left ; tmp.right = right ; tmp.sum = array[left] ; if (left == right) return tmp ; else { left_sum = max_subarray ( array , left , mid ) . sum ; right_sum = max_subarray ( array , mid , right ) . sum ; mid_sum = max_cross_subarray ( array , left , mid , right ) . sum ; if ( ( left_sum >= right_sum ) && ( left_sum >= mid_sum ) ) return max_subarray ( array , left , mid ) ; if ( ( right_sum >= left_sum ) && ( right_sum >= mid_sum ) ) return max_subarray ( array , mid , right ) ; if ( ( mid_sum >= left_sum ) && ( mid_sum >= right_sum ) ) return max_cross_subarray ( array , left , mid , right ) ; } } int main(){ struct left_right = tmp ; //length of the array const int num = 3; //random generator seed srand(time(0)); //time generation clock_t t; int array[num*num]; int i,j; //record start time t = clock(); for ( i = 0; i < num; i++ ) { for ( j = 0; j < num; j ++ ) { array[i * num + j] = rand() / 1000000 ; printf( "array %d value is %d \n", i*num + j, array[i * num + j] ) ; } } printf( "The time spent on the array generation is: %4.2f \n", (float)( clock() - t) / CLOCKS_PER_SEC ) ; long double key; //record start time tmp = max_subarray(array , 0 , num * num - 1 ) ; print_array ( array + tmp.left, , tmp.right - tmp.left + 1 ) ; //record end time printf( "The time spent on the array sorting is: %4.2f \n", (float)( clock() - t) / CLOCKS_PER_SEC ); cout<<"The array has been sorted."<<endl; //print the sorted array /* for ( i = 0; i < num; i++ ) { for ( j = 0 ; j < num ; j++ ) { printf( "array %d value is %d \n", i * num + j , array[i * num + j] ) ; } } */ return 0; }
28.349315
113
0.512926
byzhou
464ca6a431f7f3789925b04e79a4043171b28317
785
cpp
C++
samples/test/src/main.cpp
hiroog/CCTFLibrary
9eb1d7f740ba7f6174c40dba255c12212b85d9e4
[ "MIT" ]
null
null
null
samples/test/src/main.cpp
hiroog/CCTFLibrary
9eb1d7f740ba7f6174c40dba255c12212b85d9e4
[ "MIT" ]
null
null
null
samples/test/src/main.cpp
hiroog/CCTFLibrary
9eb1d7f740ba7f6174c40dba255c12212b85d9e4
[ "MIT" ]
null
null
null
// 2019/09/01 Hiroyuki Ogasawara // vim:ts=4 sw=4 noet: #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <cctf/CCTFSystem.h> using namespace cctf; //----------------------------------------------------------------------------- class MySystemAPI : public CCSystemAPI { public: size_t AllocCount= 0; public: void* Alloc( size_t byte_size ) override { AllocCount++; return malloc( byte_size ); } void Free( void* ptr, size_t byte_size ) override { AllocCount--; free( ptr ); } }; //----------------------------------------------------------------------------- extern void cctest(); extern void ccmnist(); int main() { static MySystemAPI api; CCSystem::RegisterAPI( &api ); cctest(); ccmnist(); assert( api.AllocCount == 0 ); return 0; }
16.702128
79
0.536306
hiroog
465470dd4d63504759a42fd83d03389631e1900b
10,971
cpp
C++
solver/modules/slide/src/StraightSolver.cpp
taiheioki/procon2014_ut
8199ff0a54220f1a0c51acece377f65b64db4863
[ "MIT" ]
2
2021-04-14T06:41:18.000Z
2021-04-29T01:56:08.000Z
solver/modules/slide/src/StraightSolver.cpp
taiheioki/procon2014_ut
8199ff0a54220f1a0c51acece377f65b64db4863
[ "MIT" ]
null
null
null
solver/modules/slide/src/StraightSolver.cpp
taiheioki/procon2014_ut
8199ff0a54220f1a0c51acece377f65b64db4863
[ "MIT" ]
null
null
null
#include <algorithm> #include <functional> #include <limits> #include <boost/format.hpp> #include "StraightSolver.hpp" namespace slide { void StraightSolver::alignRow(AnswerBoard<Flexible>& board) { BOOST_ASSERT(board.height() >= 3 && board.width() >= 2); // 右端2個以外 rep(dstX, board.width()-2){ const Point dst(board.height()-1, dstX); const Point src = board.find(board.correctId(dst)); // 既に大丈夫だった if(src == dst){ continue; } if(dst.x == src.x){ if(dst.x <= board.selected.x){ moveTargetPiece(board, src, dst, 0, dst.x, board.height(), board.width()-dst.x); } else{ moveTargetPiece(board, src, dst + Point(-1, 0), 0, 0, board.height()-1, board.width()); board.moveVertically(dst.y - 2); board.moveHorizontally(dst.x); board.moveRight(); board.moveDown(); board.moveDown(); board.moveLeft(); board.moveUp(); } } else if(dst.x < src.x){ if(board.selected.x < dst.x){ board.moveHorizontally(dst.x); } moveTargetPiece(board, src, dst, 0, dst.x, board.height(), board.width()-dst.x); } else{ if(dst.x < board.selected.x){ board.moveHorizontally(dst.x); } if(board.selected.y == dst.y){ board.moveUp(); } moveTargetPiece(board, src, dst + Point(-1, 0), 0, 0, board.height(), dst.x+1); // src と dst は絶対に同じにならない if(board.selected.x == dst.x - 1){ board.moveUp(); board.moveRight(); } board.moveRight(); board.moveDown(); board.moveDown(); board.moveLeft(); board.moveUp(); } } if(board.isAligned(board.height()-1, board.width()-1)){ const uchar pieceId = board.correctId(board.height()-1, board.width()-2); if(board(board.height()-1, board.width()-2) == pieceId){ return; } else if(board(board.height()-2, board.width()-2) == pieceId && board.selected == Point(board.height()-1, board.width()-2)){ board.moveUp(); return; } } // 最後の二つ目 { const uchar pieceId = board.correctId(board.height()-1, board.width()-2); const Point src = board.find(pieceId); const Point dst(board.height()-1, board.width()-1); if(src == dst); else if(src.y == dst.y){ board.moveHorizontally(board.width() - 1); board.moveVertically(board.height() - 1); board.moveLeft(); } else if(board.selected.y == dst.y && board.width()-2 <= src.x){ moveTargetPiece(board, src, dst, 0, board.width()-2, board.height(), 2); } else{ if(board.selected.y == dst.y){ board.moveUp(); } moveTargetPiece(board, src, Point(dst.y-1, dst.x), 0, 0, board.height()-1, board.width()); board.moveHorizontally(board.width() - 2); board.moveVertically(board.height() - 1); board.moveRight(); board.moveUp(); } } // ラス1 { const uchar pieceId = board.correctId(board.height()-1, board.width()-1); if(board.selected.y == board.height()-1 && board(board.height()-2, board.width()-2) != pieceId){ board.moveUp(); } if(board.selected.y != board.height()-1 && board(board.height()-1, board.width()-2) != pieceId){ const Point src = board.find(pieceId); const Point dst(board.height()-2, board.width()-1); moveTargetPiece(board, src, dst, 0, 0, board.height()-1, board.width()); board.moveHorizontally(board.width() - 2); board.moveVertically(board.height() - 1); board.moveRight(); board.moveUp(); } else if(board.width() >= 3){ board.moveHorizontally(board.width() - 2); board.moveVertically(board.height() - 1); board.moveRight(); board.moveUp(); board.moveLeft(); board.moveLeft(); board.moveDown(); board.moveRight(); board.moveRight(); board.moveUp(); board.moveLeft(); board.moveDown(); board.moveLeft(); board.moveUp(); } else{ board.moveHorizontally(0); board.moveVertically(board.height() - 1); board.moveRight(); board.moveUp(); board.moveLeft(); board.moveUp(); board.moveRight(); board.moveDown(); board.moveDown(); board.moveLeft(); board.moveUp(); board.moveRight(); board.moveUp(); board.moveLeft(); board.moveDown(); board.moveDown(); board.moveRight(); board.moveUp(); } } } void StraightSolver::moveTargetPiece(AnswerBoard<Flexible>& board, Point src, Point dst, int y, int x, int height, int width) { BOOST_ASSERT(src.isIn(y, x, height, width)); BOOST_ASSERT(dst.isIn(y, x, height, width)); BOOST_ASSERT(board.selected.isIn(y, x, height, width)); BOOST_ASSERT(0 <= y && y+height <= board.height() && 0 <= x && x+width <= board.width()); BOOST_ASSERT(height >= 2 && width >= 2); BOOST_ASSERT(src != board.selected); // 既に大丈夫だった if(src == dst){ return; } const uchar pieceId = board(src); const Point sel = board.selected; // src に隣接する有効なセルを列挙 Direction dir = Direction::Up; Point adj = Point(-1, -1); int minDist = std::numeric_limits<int>::max(); // for each directions rep(k, 4){ const Direction nowdir = Direction(k); if(dst.y >= src.y && nowdir == Direction::Up) continue; if(dst.y <= src.y && nowdir == Direction::Down) continue; if(dst.x >= src.x && nowdir == Direction::Left) continue; if(dst.x <= src.x && nowdir == Direction::Right) continue; const Point nowadj = src + Point::delta(nowdir); if(!nowadj.isIn(y, x, height, width)){ continue; } const int dist = (nowadj - sel).l1norm(); if(dist < minDist){ dir = nowdir; adj = nowadj; minDist = dist; } } BOOST_ASSERT(adj.y >= 0); // 月蝕判定 const bool eclipseY = (sel.y <= src.y && src.y < adj.y) || (adj.y < src.y && src.y <= sel.y); const bool eclipseX = (sel.x <= src.x && src.x < adj.x) || (adj.x < src.x && src.x <= sel.x); // 月蝕の位置で一直線に並んでいるケース // the special case if(sel.x == src.x && src.x == adj.x && eclipseY){ sel.x == x ? board.moveRight() : board.moveLeft(); } else if(sel.y == src.y && src.y == adj.y && eclipseX){ sel.y == y ? board.moveDown() : board.moveUp(); } // 月蝕の位置の方向から移動 if(eclipseY){ board.moveVertically(adj.y); board.moveHorizontally(adj.x); } else{ board.moveHorizontally(adj.x); board.moveVertically(adj.y); } // move target for(;;){ board.move(dir.opposite()); if(board(dst) == pieceId){ break; } switch(dir){ case Direction::Up: if(board.selected.x == dst.x){ dst.x == x ? board.moveRight() : board.moveLeft(); board.moveUp(); board.moveUp(); dst.x == x ? board.moveLeft() : board.moveRight(); } else if(board.selected.x < dst.x){ board.moveRight(); board.moveUp(); dir = Direction::Right; } else{ board.moveLeft(); board.moveUp(); dir = Direction::Left; } break; case Direction::Right: if(board.selected.y == dst.y){ dst.y == y ? board.moveDown() : board.moveUp(); board.moveRight(); board.moveRight(); dst.y == y ? board.moveUp() : board.moveDown(); } else if(board.selected.y < dst.y){ board.moveDown(); board.moveRight(); dir = Direction::Down; } else{ board.moveUp(); board.moveRight(); dir = Direction::Up; } break; case Direction::Down: if(board.selected.x == dst.x){ dst.x == x ? board.moveRight() : board.moveLeft(); board.moveDown(); board.moveDown(); dst.x == x ? board.moveLeft() : board.moveRight(); } else if(board.selected.x > dst.x){ board.moveLeft(); board.moveDown(); dir = Direction::Left; } else{ board.moveRight(); board.moveDown(); dir = Direction::Right; } break; case Direction::Left: if(board.selected.y == dst.y){ dst.y == y ? board.moveDown() : board.moveUp(); board.moveLeft(); board.moveLeft(); dst.y == y ? board.moveUp() : board.moveDown(); } else if(board.selected.y < dst.y){ board.moveDown(); board.moveLeft(); dir = Direction::Down; } else{ board.moveUp(); board.moveLeft(); dir = Direction::Up; } break; } } } void StraightSolver::align2x2(AnswerBoard<Flexible>& board) { BOOST_ASSERT(board.selected.isIn(2, 2)); board.moveVertically(0); board.moveHorizontally(0); const uchar id = board.correctId(0, 1); if(board(1, 0) == id){ board.moveDown(); board.moveRight(); board.moveUp(); board.moveLeft(); } else if(board(1, 1) == id){ board.moveRight(); board.moveDown(); board.moveLeft(); board.moveUp(); } if(!board.isAligned(1, 0)){ board.select(1, 0); board.moveRight(); } } AnswerBoard<Flexible> StraightSolver::cropTo( const AnswerBoard<Flexible>& src, int y, int x, int height, int width, Direction topSide, bool yflip, bool xflip) { Board<Flexible> dst(topSide.isUpOrDown() ? height : width, topSide.isUpOrDown() ? width : height); rep(i, height) rep(j, width){ uchar id = src(i+y, j+x); id = Point(id).rotateFlip(topSide, yflip, xflip, height, width).toInt(); dst(Point(i, j).rotateFlip(topSide, yflip, xflip, height, width)) = id; } AnswerBoard<Flexible> answerBoard(dst); answerBoard.selected = (src.selected - Point(y, x)).rotateFlip(topSide, yflip, xflip, height, width); return answerBoard; } void StraightSolver::restore( const AnswerBoard<Flexible>& src, AnswerBoard<Flexible>& dst, int y, int x, Direction topSide, bool yflip, bool xflip) { const Direction preTopSide = topSide; topSide = topSide.isRightOrLeft() ? topSide.opposite() : topSide; rep(i, src.height()) rep(j, src.width()){ uchar id = src(i, j); id = (Point(id).rotateFlip(topSide, yflip, xflip, src.height(), src.width()) + Point(y, x)).toInt(); dst.at(Point(i, j).rotateFlip(topSide, yflip, xflip, src.height(), src.width()) + Point(y, x)) = id; } dst.selected = src.selected.rotateFlip(topSide, yflip, xflip, src.height(), src.width()) + Point(y, x); // answer の restore for(const Move& move : src.answer){ if(move.isSelection){ dst.answer.emplace_back(move.getSelected().rotateFlip(topSide, yflip, xflip, src.height(), src.width()) + Point(y, x)); } else{ Direction dir = move.getDirection(); if(yflip && dir.isUpOrDown()) dir = dir.opposite(); if(xflip && dir.isRightOrLeft()) dir = dir.opposite(); dst.answer.emplace_back(dir + preTopSide); } } } void StraightSolver::solve() { // initialize AnswerBoard AnswerBoard<Flexible> board(problem.board); board.select(board.find(board.correctId(0, 0))); // continue rearrangement until the remaining region is larger than 2x2 int remH = board.height(); int remW = board.width(); while(remH > 2 || remW > 2){ const bool isRow = remH >= remW; if(isRow){ AnswerBoard<Flexible> tmp = cropTo(board, 0, 0, remH, remW, Direction::Up, false, false); alignRow(tmp); restore(tmp, board, 0, 0, Direction::Up, false, false); --remH; } else{ AnswerBoard<Flexible> tmp = cropTo(board, 0, 0, remH, remW, Direction::Left, false, false); alignRow(tmp); restore(tmp, board, 0, 0, Direction::Left, false, false); --remW; } } align2x2(board); board.answer.optimize(); onCreatedAnswer(board.answer); std::cout << "move_count = " << board.answer.size() << std::endl; } } // end of namespace slide
25.753521
125
0.627199
taiheioki
4654c53aeb35a7c4dbdd747d4f61e5dd3ced6dd0
3,332
hpp
C++
alpaka/include/alpaka/block/shared/dyn/BlockSharedMemDynUniformCudaHipBuiltIn.hpp
alpaka-group/mallocMC
ddba224b764885f816c42a7719551b14e6f5752b
[ "MIT" ]
6
2021-02-01T09:01:39.000Z
2021-11-14T17:09:03.000Z
alpaka/include/alpaka/block/shared/dyn/BlockSharedMemDynUniformCudaHipBuiltIn.hpp
alpaka-group/mallocMC
ddba224b764885f816c42a7719551b14e6f5752b
[ "MIT" ]
17
2020-11-09T14:13:50.000Z
2021-11-03T11:54:54.000Z
alpaka/include/alpaka/block/shared/dyn/BlockSharedMemDynUniformCudaHipBuiltIn.hpp
alpaka-group/mallocMC
ddba224b764885f816c42a7719551b14e6f5752b
[ "MIT" ]
null
null
null
/* Copyright 2019 Benjamin Worpitz, René Widera * * This file is part of alpaka. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #if defined(ALPAKA_ACC_GPU_CUDA_ENABLED) || defined(ALPAKA_ACC_GPU_HIP_ENABLED) # include <alpaka/core/BoostPredef.hpp> # if defined(ALPAKA_ACC_GPU_CUDA_ENABLED) && !BOOST_LANG_CUDA # error If ALPAKA_ACC_GPU_CUDA_ENABLED is set, the compiler has to support CUDA! # endif # if defined(ALPAKA_ACC_GPU_HIP_ENABLED) && !BOOST_LANG_HIP # error If ALPAKA_ACC_GPU_HIP_ENABLED is set, the compiler has to support HIP! # endif # include <alpaka/block/shared/dyn/Traits.hpp> # include <type_traits> namespace alpaka { //############################################################################# //! The GPU CUDA/HIP block shared memory allocator. class BlockSharedMemDynUniformCudaHipBuiltIn : public concepts::Implements<ConceptBlockSharedDyn, BlockSharedMemDynUniformCudaHipBuiltIn> { public: //----------------------------------------------------------------------------- BlockSharedMemDynUniformCudaHipBuiltIn() = default; //----------------------------------------------------------------------------- __device__ BlockSharedMemDynUniformCudaHipBuiltIn(BlockSharedMemDynUniformCudaHipBuiltIn const&) = delete; //----------------------------------------------------------------------------- __device__ BlockSharedMemDynUniformCudaHipBuiltIn(BlockSharedMemDynUniformCudaHipBuiltIn&&) = delete; //----------------------------------------------------------------------------- __device__ auto operator=(BlockSharedMemDynUniformCudaHipBuiltIn const&) -> BlockSharedMemDynUniformCudaHipBuiltIn& = delete; //----------------------------------------------------------------------------- __device__ auto operator=(BlockSharedMemDynUniformCudaHipBuiltIn&&) -> BlockSharedMemDynUniformCudaHipBuiltIn& = delete; //----------------------------------------------------------------------------- /*virtual*/ ~BlockSharedMemDynUniformCudaHipBuiltIn() = default; }; namespace traits { //############################################################################# template<typename T> struct GetDynSharedMem<T, BlockSharedMemDynUniformCudaHipBuiltIn> { //----------------------------------------------------------------------------- __device__ static auto getMem(BlockSharedMemDynUniformCudaHipBuiltIn const&) -> T* { // Because unaligned access to variables is not allowed in device code, // we have to use the widest possible type to have all types aligned correctly. // See: http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#shared // http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#vector-types extern __shared__ float4 shMem[]; return reinterpret_cast<T*>(shMem); } }; } // namespace traits } // namespace alpaka #endif
45.643836
114
0.536315
alpaka-group
465af3690db8e7e38b86005371afe4aa42b6cc8b
556
cpp
C++
test/filter.cpp
ericjavier/yaml
92d9097fc58602fbc88000fd22e2debc2f90996c
[ "Apache-2.0" ]
1
2015-04-12T19:46:13.000Z
2015-04-12T19:46:13.000Z
test/filter.cpp
ericjavier/yaml
92d9097fc58602fbc88000fd22e2debc2f90996c
[ "Apache-2.0" ]
null
null
null
test/filter.cpp
ericjavier/yaml
92d9097fc58602fbc88000fd22e2debc2f90996c
[ "Apache-2.0" ]
null
null
null
#include <gtest/gtest.h> #include <yaml/config.hpp> #include <yaml/detail/placeholders.hpp> #include <yaml/arithmetic.hpp> #include <yaml/sequence/filter.hpp> #include "test_utils.hpp" using namespace YAML_NSP; using func = less::ret<_0, std::integral_constant<int, 3>>; using expected = list<std::integral_constant<int, 0>, std::integral_constant<int, 1>, std::integral_constant<int, 2 >>; TEST(filter, seq) { expect_same_seq<expected, filter::ret<func, seq3>>(); } TEST(filter, list) { expect_same_seq<expected, filter::ret<func, lst3>>(); }
25.272727
59
0.723022
ericjavier
465bb25a1f734987150e98294c974113721a02e6
991
cc
C++
src/abc011/c.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc011/c.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc011/c.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
#define _GLIBCXX_DEBUG #include <bits/stdc++.h> using namespace std; typedef long long ll; const int INF = 400; int dfs(int start, vector<int> &dp, set<int> &ng) { if(dp[start] >= 0) { return dp[start]; } if(ng.find(start) != ng.end()) { return dp[start] = INF; } int one = INF, two = INF, three = INF; if(start - 1 >= 0) { one = dfs(start - 1, dp, ng); } if(start - 2 >= 0) { two = dfs(start - 2, dp, ng); } if(start - 3 >= 0) { three = dfs(start - 3, dp, ng); } return dp[start] = min(one, min(two, three)) + 1; } string solve(int n, vector<int> ng) { vector<int> dp(301, -1); dp[0] = 0; set<int> ng_set; ng_set.insert(ng[0]); ng_set.insert(ng[1]); ng_set.insert(ng[2]); int res = dfs(n, dp, ng_set); return res <= 100 ? "YES" : "NO"; } /* int main() { int n; vector<int> ng(3); cin >> n >> ng[0] >> ng[1] >> ng[2]; cout << solve(n, ng) << endl; } */
22.022222
53
0.498486
nryotaro
465eb68fb7072790e82f6c3db5f23dbfb93e7340
4,148
cpp
C++
Linked list/LinkedListStruct.cpp
lovinh/Data-Structure
f5dab728b809507b8b15eb8f8450a6a85f95467e
[ "MIT" ]
null
null
null
Linked list/LinkedListStruct.cpp
lovinh/Data-Structure
f5dab728b809507b8b15eb8f8450a6a85f95467e
[ "MIT" ]
null
null
null
Linked list/LinkedListStruct.cpp
lovinh/Data-Structure
f5dab728b809507b8b15eb8f8450a6a85f95467e
[ "MIT" ]
null
null
null
#ifndef __LinkedListStruct_cpp #define __LinkedListStruct_cpp #include <iostream> template <class T> struct sNode // struct node { T data; sNode<T> *next; }; // Insert template <class T> void push_front(sNode<T> **head, const T &data) { sNode<T> *node = new sNode<T>; node->data = data; node->next = *head; *head = node; } template <class T> void push_back(sNode<T> **head, const T &data) { sNode<T> *nNode = new sNode<T>(); nNode->data = data; nNode->next = NULL; if (*head == NULL) { *head = nNode; } else { sNode<T> *it; // iterator it = *head; while (it->next != NULL) { it = it->next; } it->next = nNode; } } template <class T> void insert(sNode<T> **head, const T &data, size_t index) { if (index == 0) { push_front(head, data); return; } size_t size_list = size(*head); if (index > size_list) { push_back(head, data); return; } sNode<T> *nNode = new sNode<T>(); nNode->data = data; sNode<T> *it = *head; for (size_t i = 0; i < index - 1; i++) { it = it->next; } nNode->next = it->next; it->next = nNode; } // delete node template <class T> void pop_front(sNode<T> **head) { if (empty(*head)) { return; } size_t lSize = size(*head); if (lSize == 1) { sNode<T> *dNode = *head; (*head) = NULL; delete dNode; } else { sNode<T> *dNode = *head; (*head) = dNode->next; delete dNode; } } template <class T> void pop_back(sNode<T> **head) { if (empty(*head)) { return; } size_t lSize = size(*head); if (lSize == 1) { sNode<T> *dNode = *head; (*head) = NULL; delete dNode; } else { sNode<T> *dNode = *head; for (int i = 0; i < lSize - 2; i++) { dNode = dNode->next; } sNode<T> *dNode2 = dNode->next; dNode->next = NULL; delete dNode2; } } template <class T> void erase(sNode<T> **head, size_t index) { if (empty(*head)) { return; } size_t len = size(*head); if (index >= len) { return; } else { if (index == 0) pop_front(head); else if (index == len - 1) pop_back(head); else { sNode<T> *dNode = *head; for (int i = 0; i < index - 1; i++) { dNode = dNode->next; } sNode<T> *dNode2 = dNode->next; dNode->next = dNode2->next; delete dNode2; } } } // capacity template <class T> size_t size(sNode<T> *head) { size_t count = 0; while (head->next != NULL) { count++; head = head->next; } return count + 1; } template <class T> bool empty(sNode<T> *head) { return (head == NULL); } // Access template <class T> T &front(sNode<T> *head) { return head->data; } template <class T> T &back(sNode<T> *head) { sNode<T> *it = head; while (it->next != NULL) { it = it->next; } return it->data; } // Reverse a linked list template <class T> void Reverse(sNode<T> **head) { sNode<T> *previous, *current, *next; previous = NULL; current = *head; while (current != NULL) { next = current->next; current->next = previous; previous = current; current = next; } *head = previous; } // In list template <class T> void printList(sNode<T> *head) { if (empty(head)) { std::cout << "list is empty"; } else { sNode<T> *it = head; // iterator std::cout << "List is "; while (it != NULL) { std::cout << it->data << " "; it = it->next; } std::cout << "\t" << size(head); } std::cout << std::endl; } template <class T> void Print(sNode<T> *head) { if (head == NULL) return; std ::cout << head->data << " "; Print(head->next); } #endif
18.435556
57
0.478303
lovinh
465ed2ea6fea6919b888be71acce359be427cbd8
1,684
cxx
C++
main/setup_native/source/win32/customactions/quickstarter/remove_quickstart_link.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/setup_native/source/win32/customactions/quickstarter/remove_quickstart_link.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/setup_native/source/win32/customactions/quickstarter/remove_quickstart_link.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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. * *************************************************************/ #ifdef _MSC_VER #pragma warning(push, 1) /* disable warnings within system headers */ #pragma warning(disable: 4917) #endif #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <shlobj.h> #include <msiquery.h> #ifdef _MSC_VER #pragma warning(pop) #endif #include <string> #include "quickstarter.hxx" extern "C" UINT __stdcall RemoveQuickstarterLink( MSIHANDLE hMSI ) { CHAR szStartupPath[MAX_PATH]; if ( SHGetSpecialFolderPathA( NULL, szStartupPath, CSIDL_STARTUP, FALSE ) ) { std::string sQuickstartLinkPath = szStartupPath; sQuickstartLinkPath += "\\"; sQuickstartLinkPath += GetQuickstarterLinkName( hMSI ); sQuickstartLinkPath += ".lnk"; DeleteFileA( sQuickstartLinkPath.c_str() ); } return ERROR_SUCCESS; }
29.54386
76
0.690024
Grosskopf
46638a06ef05cd551a0d25bc744069d85864c7f2
2,585
cpp
C++
allocore/src/protocol/opencl/al_OpenCLProgram.cpp
donghaoren/AlloSystem
7674cc8597e470a355a5dab1dac9191c2c2e8086
[ "BSD-3-Clause" ]
null
null
null
allocore/src/protocol/opencl/al_OpenCLProgram.cpp
donghaoren/AlloSystem
7674cc8597e470a355a5dab1dac9191c2c2e8086
[ "BSD-3-Clause" ]
null
null
null
allocore/src/protocol/opencl/al_OpenCLProgram.cpp
donghaoren/AlloSystem
7674cc8597e470a355a5dab1dac9191c2c2e8086
[ "BSD-3-Clause" ]
null
null
null
#include "allocore/protocol/opencl/al_OpenCLProgram.hpp" #ifndef MIN #define MIN(a, b) (((a) < (b)) ? (a) : (b)) #endif namespace al { namespace cl { void OpenCLProgram :: create(OpenCLContext &ctx, const char *source) { destroy(); detach(); cl_int res = CL_SUCCESS; cl_program program = clCreateProgramWithSource( ctx.get_context(), 1, &source, NULL, &res ); if(opencl_error(res, "clCreateProgramWithSource error creating program")) { return; } mProgram = program; ctx.attach_resource(this); } void OpenCLProgram :: build(const OpenCLDevice &dev) { build(vector<OpenCLDevice>(1, dev)); } void OpenCLProgram :: build(const vector<OpenCLDevice> &devs) { int ndevices = devs.size(); cl_device_id devices[MAX_DEVICES]; for(int i=0; i < MIN(MAX_DEVICES, ndevices); i++) { devices[i] = devs[i].get_device(); if(!devs[i].get_available()) { char msg[256]; sprintf(msg, "OpenCL Device %s is not available", devs[i].get_name().c_str()); opencl_error(USER_OPENCL_ERROR, msg); return; } } cl_int res = clBuildProgram( mProgram, ndevices, devices, "", NULL, NULL ); if(opencl_error(res, "clBuildProgram error building program")) { /* INSTEAD OF CALLBACKS: clGetProgramBuildInfo( program, // the program object being queried device_id, // the device for which the OpenCL code was built CL_PROGRAM_BUILD_LOG, // specifies that we want the build log sizeof(buffer), // the size of the buffer buffer, // on return, holds the build log &len); // on return, the actual size in bytes of the // data returned */ return; } return; } void OpenCLProgram :: destroy() { if(mProgram) { list<OpenCLResource<OpenCLProgram> *>::iterator it = mResources.begin(); while(it != mResources.end()) { (*it)->destroy(); (*it)->detach(); it = mResources.begin(); } cl_int res = clReleaseProgram(mProgram); mProgram = 0; opencl_error(res, "clReleaseProgram error releasing program"); } } void OpenCLProgram :: attach_resource(OpenCLResource<OpenCLProgram> *resource) { resource->attach(this); mResources.push_back(resource); } void OpenCLProgram :: detach_resource(OpenCLResource<OpenCLProgram> *resource) { list<OpenCLResource<OpenCLProgram> *>::iterator it = mResources.begin(); list<OpenCLResource<OpenCLProgram> *>::iterator ite = mResources.end(); for(; it != ite; ++it) { if((*it) == resource) { mResources.erase(it); break; } } } } // cl:: } // al::
23.288288
81
0.648743
donghaoren
4663c2afa22114665144549d50fe2d00da904b5c
1,287
cpp
C++
app/src/main/cpp/Threads/FileStreamThread.cpp
PetrFlajsingr/SpeechRecognition
23c675c7389b9ad97b18a8ba3739dceb04f42856
[ "Apache-2.0" ]
1
2019-04-18T06:33:09.000Z
2019-04-18T06:33:09.000Z
app/src/main/cpp/Threads/FileStreamThread.cpp
PetrFlajsingr/SpeechRecognition
23c675c7389b9ad97b18a8ba3739dceb04f42856
[ "Apache-2.0" ]
null
null
null
app/src/main/cpp/Threads/FileStreamThread.cpp
PetrFlajsingr/SpeechRecognition
23c675c7389b9ad97b18a8ba3739dceb04f42856
[ "Apache-2.0" ]
null
null
null
// // Created by Petr Flajsingr on 18/04/2018. // #include "FileStreamThread.h" #include <constants.h> #include <android/log.h> SpeechRecognition::Threads::FileStreamThread::FileStreamThread(std::ifstream& fileStream) : thread(&FileStreamThread::threadFileStream, this) { this->fileStream = &fileStream; } void SpeechRecognition::Threads::FileStreamThread::threadFileStream() { std::unique_lock<std::mutex> lock(startMutex); conditionVariable.wait(lock); short* data = wavReader.wavToPcm(*fileStream); Q_AudioData* audioData; if(data == NULL) { audioData = new Q_AudioData{TERMINATE, NULL}; melQueue->enqueue(audioData); return; } int framesSent = 0; for(int i = 0; i < wavReader.getDataSize(); i += SUBSAMPLED_OVERLAP_LENGTH){ short* dataToSend = new short[SUBSAMPLED_OVERLAP_LENGTH]; std::copy(data + i, data + i + SUBSAMPLED_OVERLAP_LENGTH, dataToSend); audioData = new Q_AudioData{SEQUENCE_DATA, dataToSend}; melQueue->enqueue(audioData); framesSent++; } audioData = new Q_AudioData{TERMINATE, NULL}; melQueue->enqueue(audioData); } void SpeechRecognition::Threads::FileStreamThread::start() { conditionVariable.notify_all(); }
26.8125
89
0.677545
PetrFlajsingr
46642a3737950cf666a252806f317be9196ca388
1,864
cpp
C++
c++/Data Structures/RMQ.cpp
WearyJunger/notebook
8fc7bfdcacffd63b131b5ed0c92365f682ba313f
[ "MIT" ]
null
null
null
c++/Data Structures/RMQ.cpp
WearyJunger/notebook
8fc7bfdcacffd63b131b5ed0c92365f682ba313f
[ "MIT" ]
null
null
null
c++/Data Structures/RMQ.cpp
WearyJunger/notebook
8fc7bfdcacffd63b131b5ed0c92365f682ba313f
[ "MIT" ]
1
2018-10-08T21:01:59.000Z
2018-10-08T21:01:59.000Z
Range minimum query. Recibe como parametro en el constructor un array de valores. Las consultas se realizan con el método rmq(indice_inicio, indice_final) y pueden actualizarse los valores con update_point(indice, nuevo_valor) class SegmentTree { private: vector<int> st, A; int n; int left (int p) { return p << 1; } int right(int p) { return (p << 1) + 1; } void build(int p, int L, int R) { if (L == R) st[p] = L; else { build(left(p) , L, (L + R) / 2); build(right(p), (L + R) / 2 + 1, R); int p1 = st[left(p)], p2 = st[right(p)]; st[p] = (A[p1] <= A[p2]) ? p1 : p2; } } int rmq(int p, int L, int R, int i, int j) { if (i > R || j < L) return -1; if (L >= i && R <= j) return st[p]; int p1 = rmq(left(p) , L, (L+R) / 2, i, j); int p2 = rmq(right(p), (L+R) / 2 + 1, R, i, j); if (p1 == -1) return p2; if (p2 == -1) return p1; return (A[p1] <= A[p2]) ? p1 : p2; } int update_point(int p, int L, int R, int idx, int new_value) { int i = idx, j = idx; if (i > R || j < L) return st[p]; if (L == i && R == j) { A[i] = new_value; return st[p] = L; } int p1, p2; p1 = update_point(left(p) , L, (L + R) / 2, idx, new_value); p2 = update_point(right(p), (L + R) / 2 + 1, R, idx, new_value); return st[p] = (A[p1] <= A[p2]) ? p1 : p2; } public: SegmentTree(const vector<int> &_A) { A = _A; n = (int)A.size(); st.assign(4 * n, 0); build(1, 0, n - 1); } int rmq(int i, int j) { return rmq(1, 0, n - 1, i, j); } int update_point(int idx, int new_value) { return update_point(1, 0, n - 1, idx, new_value); } }; int main() { int arr[] = { 18, 17, 13, 19, 15, 11, 20 }; vector<int> A(arr, arr + 7); SegmentTree st(A); return 0; }
28.242424
226
0.495708
WearyJunger
466cc79151dff2e1c1bf8abf8acbd3a5d6c861c0
630
cpp
C++
225-Days Coding Problem/Day-002.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
225-Days Coding Problem/Day-002.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
225-Days Coding Problem/Day-002.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { const size_t n= nums.size(); vector<int>ans(n,1); int answer =1; for(size_t i=0;i<n; ++i){ if(i==0){ ans[i] = nums[i]; }else{ ans[i] = nums[i]*ans[i-1]; } } int temp; for(int i=n-1;i>=0;--i){ if(i!=0){ temp = nums[i]; nums[i] = ans[i-1]*answer; answer*=temp; }else{ nums[i] = answer; } } return nums; } };
23.333333
54
0.365079
Ashwanigupta9125
466e60dd8dd600cfbe3235959f31c170b9a87f0d
3,347
cpp
C++
SelPh/metriclearning.cpp
yuki-koyama/selph
9f3d1a868333843c6884adac41e344684efa2366
[ "MIT" ]
3
2019-09-13T07:47:39.000Z
2021-03-10T20:31:32.000Z
SelPh/metriclearning.cpp
yuki-koyama/selph
9f3d1a868333843c6884adac41e344684efa2366
[ "MIT" ]
7
2018-04-06T10:06:56.000Z
2019-08-04T05:38:12.000Z
SelPh/metriclearning.cpp
yuki-koyama/selph
9f3d1a868333843c6884adac41e344684efa2366
[ "MIT" ]
null
null
null
// #define TIME #include "metriclearning.h" #ifdef TIME #include <chrono> #endif #include <nlopt.hpp> #include "core.h" #include "eigenutility.h" using namespace Eigen; using namespace std; namespace { Core& core = Core::getInstance(); } namespace MetricLearning { struct Arg { Arg(const Core::Distance* D_images, const MatrixXd* D_params, unsigned nData) : D_images(D_images), D_params(D_params), nData(nData) {} const Core::Distance* D_images; const MatrixXd* D_params; const unsigned nData; }; /////////////////////////////////////////////////////////////////////////////////////////////// // \grad(C) = \sum_{i, j} \grad { \| D_images_{i, j}^T \alpha - D_params_{i, j} \|^2 } // = - 2 \sum_{i, j} D_images_{i, j} ( D_params_{i, j} - D_images_{i, j}^T \alpha ) /////////////////////////////////////////////////////////////////////////////////////////////// Eigen::VectorXd computeGradient(const VectorXd& alpha, const Arg* data, const double weight) { VectorXd grad = VectorXd::Zero(alpha.rows()); for (unsigned i = 0; i < data->nData; ++ i) for (unsigned j = i + 1; j < data->nData; ++ j) { const VectorXd D_ij = EigenUtility::std2eigen((*data->D_images)[i][j]); grad += D_ij * (weight * data->D_params->coeff(i, j) - D_ij.transpose() * alpha); } grad = - 2.0 * grad; return grad; } /////////////////////////////////////////////////////////////////////////////////////////////// // C = \sum_{i, j} { \| D_images_{i, j}^T \alpha - D_params_{i, j} \|^2 } /////////////////////////////////////////////////////////////////////////////////////////////// double objectiveFunction(const vector<double> &x, vector<double>& grad, void* argData) { const Arg* data = static_cast<const Arg*>(argData); const VectorXd alpha = EigenUtility::std2eigen(x); const double weight = 5.0; // Compute the function value double cost = 0.0; for (unsigned i = 0; i < data->nData; ++ i) for (unsigned j = i + 1; j < data->nData; ++ j) { const double d = Core::computeDistance(alpha, *(data->D_images), i, j) - weight * data->D_params->coeff(i, j); cost += d * d; } // Compute the gradient grad = EigenUtility::eigen2std(computeGradient(alpha, data, weight)); return cost; } VectorXd computeMetricLearning(const vector<vector<vector<double>>> &D_images, const MatrixXd &D_params, const VectorXd &seed, unsigned nData) { const unsigned dim = seed.rows(); vector<double> x = EigenUtility::eigen2std(seed); double value; const Arg argData(&D_images, &D_params, nData); // Compute local optimization nlopt::opt localOpt(nlopt::LD_LBFGS, dim); localOpt.set_min_objective(objectiveFunction, (void*) &argData); localOpt.set_lower_bounds(0.0); try { #ifdef TIME const auto t1 = chrono::system_clock::now(); #endif localOpt.optimize(x, value); #ifdef TIME const auto t2 = chrono::system_clock::now(); cout << "Metric learning: " << chrono::duration_cast<chrono::milliseconds>(t2 - t1).count() << " [ms]" << endl; #endif } catch (const nlopt::roundoff_limited e) { cerr << e.what() << endl; } catch (const std::runtime_error e) { cerr << e.what() << endl; } return EigenUtility::std2eigen(x); } }
31.575472
142
0.553929
yuki-koyama
466f649cd8398e7deb5c21a4cf7fc57bbcff1ba5
1,025
cpp
C++
Lab 4/Lab 4/Lab 4.cpp
shonwr/c-assignments-projects
fab40807ba2720cec577aa9689361746e33ef678
[ "Apache-2.0" ]
null
null
null
Lab 4/Lab 4/Lab 4.cpp
shonwr/c-assignments-projects
fab40807ba2720cec577aa9689361746e33ef678
[ "Apache-2.0" ]
null
null
null
Lab 4/Lab 4/Lab 4.cpp
shonwr/c-assignments-projects
fab40807ba2720cec577aa9689361746e33ef678
[ "Apache-2.0" ]
null
null
null
// Lab 4.cpp : main project file. #include "stdafx.h" #include <iostream> using namespace System; using namespace std; char fName[50]; char lName[50]; char space[10] = " "; int main() { system("color f0"); printf("This program: \n\t(1)Prints an entered first and last name \n\t(2)Prints the number of letters in each name on the following line.\n\n"); printf("Press enter to begin: "); scanf("%c"); printf("\n\nEnter first name: "); scanf("%s",fName); printf("\nEnter last name: "); scanf("%s",lName); //Aligned @ end printf("\n\nYou enterered: %s %s \n",fName,lName); int fLength = (strlen(fName)); int lLength = (strlen(lName)); int fSpaceEnd = (strlen(fName)-2); int lSpaceEnd = (strlen(lName)-1); printf(" %*s %d", "%*s\n\n",fSpaceEnd,space,fLength,lSpaceEnd,space,lLength); //Aligned @ beginning printf("\n\nYou enterered: %s %s \n",fName,lName); int fSpace = (strlen(fName)-2); printf(" %d %-*s %d\n\n",fLength,fSpace,space,lLength); system("pause"); return 0; }
26.973684
146
0.636098
shonwr
4671ec7a3b1a40d24223e8bfc1ef09540e1dc440
1,784
cpp
C++
DivisionEngine/DivisionTest/ClockTest.cpp
martheveldhuis/DivisionEngine
8f7ba1c355ee010c005df207e08d51673f3cdf8d
[ "MIT" ]
1
2017-11-29T19:19:43.000Z
2017-11-29T19:19:43.000Z
DivisionEngine/DivisionTest/ClockTest.cpp
martheveldhuis/DivisionEngine
8f7ba1c355ee010c005df207e08d51673f3cdf8d
[ "MIT" ]
2
2018-01-16T12:11:24.000Z
2018-01-16T15:21:46.000Z
DivisionEngine/DivisionTest/ClockTest.cpp
martheveldhuis/DivisionEngine
8f7ba1c355ee010c005df207e08d51673f3cdf8d
[ "MIT" ]
1
2018-01-28T13:10:49.000Z
2018-01-28T13:10:49.000Z
#include "CppUnitTest.h" #include "Clock.h" #include <chrono> #include <thread> #include <iostream> using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Division; namespace DivisionTest { TEST_CLASS(ClockTest) { public: TEST_METHOD(testClockStart) { Clock clock; clock.start(); Assert::IsTrue(clock.isRunning()); } TEST_METHOD(testClockPoll) { Clock clock; clock.start(); // Sleep for 1000 ms. std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // Retrieve the time that has past. int timePast = clock.poll(); // Check if the time is between a certain timespan. // Usually the past time will be 1001 ms. For cpu-threading // priority delay occasions we will allow for a 5ms delay. int isBetween = 1000 <= timePast && timePast < 1050; Assert::IsTrue(isBetween); } TEST_METHOD(testClockStop) { Clock clock; clock.start(); clock.stop(); Assert::IsFalse(clock.isRunning()); } TEST_METHOD(testClockRuntime) { Clock clock; clock.start(); // Sleep for 500 ms. std::this_thread::sleep_for(std::chrono::milliseconds(500)); clock.stop(); std::this_thread::sleep_for(std::chrono::milliseconds(500)); clock.start(); // Sleep for 500 ms. std::this_thread::sleep_for(std::chrono::milliseconds(500)); clock.stop(); int timePast = clock.getRuntime(); int isBetween = 1000 <= timePast && timePast < 1050; Assert::IsTrue(isBetween); } TEST_METHOD(testClockReset) { Clock clock; clock.start(); // Sleep for 500 ms. std::this_thread::sleep_for(std::chrono::milliseconds(500)); clock.stop(); clock.reset(); int timePast = clock.getRuntime(); Assert::AreEqual(0, timePast); } }; }
16.830189
64
0.663117
martheveldhuis
4672121dbfdbb543cd8767a085f1823f8735a986
7,810
cpp
C++
src/mame/video/namco_c169roz.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/mame/video/namco_c169roz.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/mame/video/namco_c169roz.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:David Haywood, Phil Stroffolino /****************************************************************************** Namco C169 (ROZ - Rotate and Zoom) Advanced rotate-zoom chip manages two layers. Each layer uses a designated subset of a master 256x256 tile tilemap (4096x4096 pixels). Each layer has configurable color and tile banking. ROZ attributes may be specified independently for each scanline. Used by: Namco NB2 - The Outfoxies, Mach Breakers Namco System 2 - Metal Hawk, Lucky and Wild Namco System FL - Final Lap R, Speed Racer ******************************************************************************/ #include "emu.h" #include "namco_c169roz.h" static const gfx_layout layout = { 16,16, RGN_FRAC(1,1), 8, { STEP8(0,1) }, { STEP16(0,8) }, { STEP16(0,8*16) }, 16*128 }; GFXDECODE_START( namco_c169roz_device::gfxinfo ) GFXDECODE_DEVICE( DEVICE_SELF, 0, layout, 0, 32 ) GFXDECODE_END DEFINE_DEVICE_TYPE(NAMCO_C169ROZ, namco_c169roz_device, "namco_c169roz", "Namco C169 (ROZ)") namco_c169roz_device::namco_c169roz_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock) : device_t(mconfig, NAMCO_C169ROZ, tag, owner, clock), device_gfx_interface(mconfig, *this, gfxinfo), m_color_base(0), m_is_namcofl(false), m_mask(*this, "mask") { } void namco_c169roz_device::device_start() { m_videoram.resize(m_ramsize); std::fill(std::begin(m_videoram), std::end(m_videoram), 0x0000); m_tilemap[0] = &machine().tilemap().create(*this, tilemap_get_info_delegate(*this, FUNC(namco_c169roz_device::get_info<0>)), tilemap_mapper_delegate(*this, FUNC(namco_c169roz_device::mapper)), 16, 16, 256, 256); m_tilemap[1] = &machine().tilemap().create(*this, tilemap_get_info_delegate(*this, FUNC(namco_c169roz_device::get_info<1>)), tilemap_mapper_delegate(*this, FUNC(namco_c169roz_device::mapper)), 16, 16, 256, 256); save_item(NAME(m_control)); save_item(NAME(m_videoram)); } // for bank changes void namco_c169roz_device::mark_all_dirty() { for (auto & elem : m_tilemap) elem->mark_all_dirty(); } /** * Graphics ROM addressing varies across games. * (mostly scrambling, which could be handled in the game inits, but NB1 also has banking) */ template<int Which> TILE_GET_INFO_MEMBER(namco_c169roz_device::get_info) { int tile = 0, mask = 0; m_c169_cb(m_videoram[tile_index&(m_ramsize-1)] & 0x3fff, &tile, &mask, Which); // need to mask with ramsize because the nb1/fl games have twice as much RAM, presumably the tilemaps mirror in ns2? tileinfo.mask_data = m_mask + 32 * mask; tileinfo.set(0, tile, 0/*color*/, 0/*flag*/); } TILEMAP_MAPPER_MEMBER( namco_c169roz_device::mapper ) { return ((col & 0x80) << 8) | ((row & 0xff) << 7) | (col & 0x7f); } void namco_c169roz_device::unpack_params(const uint16_t *source, roz_parameters &params) { const int xoffset = 36, yoffset = 3; /** * x-------.-------- disable layer * ----x---.-------- wrap? * ------xx.-------- size * --------.xxxx---- priority * --------.----xxxx color */ uint16_t temp = source[1]; params.wrap = BIT(~temp, 11); params.size = 512 << ((temp & 0x0300) >> 8); if (m_is_namcofl) params.color = (temp & 0x0007) * 256; else params.color = (temp & 0x000f) * 256; params.priority = (temp & 0x00f0) >> 4; temp = source[2]; params.left = (temp & 0x7000) >> 3; if (temp & 0x8000) temp |= 0xf000; else temp &= 0x0fff; // sign extend params.incxx = int16_t(temp); temp = source[3]; params.top = (temp&0x7000)>>3; if (temp & 0x8000) temp |= 0xf000; else temp &= 0x0fff; // sign extend params.incxy = int16_t(temp); temp = source[4]; if (temp & 0x8000) temp |= 0xf000; else temp &= 0x0fff; // sign extend params.incyx = int16_t(temp); temp = source[5]; if (temp & 0x8000) temp |= 0xf000; else temp &= 0x0fff; // sign extend params.incyy = int16_t(temp); params.startx = int16_t(source[6]); params.starty = int16_t(source[7]); params.startx <<= 4; params.starty <<= 4; params.startx += xoffset * params.incxx + yoffset * params.incyx; params.starty += xoffset * params.incxy + yoffset * params.incyy; // normalize params.startx <<= 8; params.starty <<= 8; params.incxx <<= 8; params.incxy <<= 8; params.incyx <<= 8; params.incyy <<= 8; } void namco_c169roz_device::draw_helper(screen_device &screen, bitmap_ind16 &bitmap, tilemap_t &tmap, const rectangle &clip, const roz_parameters &params) { if (!m_is_namcofl) // if (m_gametype != NAMCOFL_FINAL_LAP_R) // Fix speedrcr some title animations, but broke at road scene { uint32_t size_mask = params.size - 1; bitmap_ind16 &srcbitmap = tmap.pixmap(); bitmap_ind8 &flagsbitmap = tmap.flagsmap(); uint32_t startx = params.startx + clip.min_x * params.incxx + clip.min_y * params.incyx; uint32_t starty = params.starty + clip.min_x * params.incxy + clip.min_y * params.incyy; int sx = clip.min_x; int sy = clip.min_y; while (sy <= clip.max_y) { int x = sx; uint32_t cx = startx; uint32_t cy = starty; uint16_t *dest = &bitmap.pix(sy, sx); while (x <= clip.max_x) { // TODO : Wraparound disable isn't implemented uint32_t xpos = (((cx >> 16) & size_mask) + params.left) & 0xfff; uint32_t ypos = (((cy >> 16) & size_mask) + params.top) & 0xfff; if (flagsbitmap.pix(ypos, xpos) & TILEMAP_PIXEL_LAYER0) *dest = srcbitmap.pix(ypos, xpos) + params.color + m_color_base; cx += params.incxx; cy += params.incxy; x++; dest++; } startx += params.incyx; starty += params.incyy; sy++; } } else { tmap.set_palette_offset(m_color_base + params.color); tmap.draw_roz( screen, bitmap, clip, params.startx, params.starty, params.incxx, params.incxy, params.incyx, params.incyy, params.wrap,0,0); // wrap, flags, pri } } void namco_c169roz_device::draw_scanline(screen_device &screen, bitmap_ind16 &bitmap, int line, int which, int pri, const rectangle &cliprect) { if (line >= cliprect.min_y && line <= cliprect.max_y) { int row = line / 8; int offs = row * 0x100 + (line & 7) * 0x10 + 0xe080; uint16_t *source = &m_videoram[offs / 2]; // if enabled if ((source[1] & 0x8000) == 0) { roz_parameters params; unpack_params(source, params); // check priority if (pri == params.priority) { rectangle clip(0, bitmap.width() - 1, line, line); clip &= cliprect; draw_helper(screen, bitmap, *m_tilemap[which], clip, params); } } } } void namco_c169roz_device::draw(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect, int pri) { int special = (m_is_namcofl) ? 0 : 1; int mode = m_control[0]; // 0x8000 or 0x1000 for (int which = 1; which >= 0; which--) { const uint16_t *source = &m_control[which * 8]; uint16_t attrs = source[1]; // if enabled if ((attrs & 0x8000) == 0) { // second ROZ layer is configured to use per-scanline registers if (which == special && mode == 0x8000) { for (int line = cliprect.min_y; line <= cliprect.max_y; line++) draw_scanline(screen, bitmap, line, which, pri, cliprect); } else { roz_parameters params; unpack_params(source, params); if (params.priority == pri) draw_helper(screen, bitmap, *m_tilemap[which], cliprect, params); } } } } uint16_t namco_c169roz_device::control_r(offs_t offset) { return m_control[offset]; } void namco_c169roz_device::control_w(offs_t offset, uint16_t data, uint16_t mem_mask) { COMBINE_DATA(&m_control[offset]); } uint16_t namco_c169roz_device::videoram_r(offs_t offset) { return m_videoram[offset]; } void namco_c169roz_device::videoram_w(offs_t offset, uint16_t data, uint16_t mem_mask) { COMBINE_DATA(&m_videoram[offset]); for (auto & elem : m_tilemap) elem->mark_tile_dirty(offset); }
28.194946
196
0.66402
Robbbert
4674ea079e6d2cdc296410871e1316c79c9577e3
5,471
cpp
C++
triangles.cpp
bradgrantham/raycast
a103801f473d55e99fc25db28c4b0587a1271093
[ "BSD-2-Clause" ]
null
null
null
triangles.cpp
bradgrantham/raycast
a103801f473d55e99fc25db28c4b0587a1271093
[ "BSD-2-Clause" ]
null
null
null
triangles.cpp
bradgrantham/raycast
a103801f473d55e99fc25db28c4b0587a1271093
[ "BSD-2-Clause" ]
null
null
null
#include <algorithm> #include <cmath> // Okay, it's ugly, I get it. // // I didn't use classes or a vector library. I use loops to // 3 everywhere for vector operations, and I even write out dot // products. My intent was to try to build a minimal triangle // raycaster that I could convert simply to BASIC or FORTH or other // simple languages without having to downconvert C++ concepts. // // I'm already thinking function calls are problematic, as well as // the arrays with 3 dimensions. I might have to inline the functions // and use goto instead of early returns. // // So it's probably still not ugly enough. const float F = 1000000; const int W = 256; const int H = 256; const int M = 400000; float tv[M][3][3]; // vertices float tp[M][4]; // planes float te[M][3][4]; // edge half-space planes float tb[M][4]; // xmin, xmax, ymin, ymax int tc = 0; float L[3] = {.577, .577, .577}; void prepare(int k) { // Get edge vectors float e[3][3]; for(int i = 0; i < 3; i++) e[0][i] = tv[k][1][i] - tv[k][0][i]; for(int i = 0; i < 3; i++) e[1][i] = tv[k][2][i] - tv[k][1][i]; for(int i = 0; i < 3; i++) e[2][i] = tv[k][0][i] - tv[k][2][i]; // Cross product e0 and e1 to get normal tp[k][0] = e[0][1] * e[1][2] - e[0][2] * e[1][1]; tp[k][1] = e[0][2] * e[1][0] - e[0][0] * e[1][2]; tp[k][2] = e[0][0] * e[1][1] - e[0][1] * e[1][0]; // Normalize normal float d = sqrt(tp[k][0] * tp[k][0] + tp[k][1] * tp[k][1] + tp[k][2] * tp[k][2]); for(int i = 0; i < 3; i++) tp[k][i] /= d; // Use dot product of normal and v0 to get fourth plane equation element tp[k][3] = tp[k][0] * tv[k][0][0] + tp[k][1] * tv[k][0][1] + tp[k][2] * tv[k][0][2]; // Get half-spaces representing each edge by making vector // perpendicular to edge and dot that with opposite vertex to get // plane equation for(int j = 0; j < 3; j++) { te[k][j][0] = tp[k][1] * e[j][2] - tp[k][2] * e[j][1]; te[k][j][1] = tp[k][2] * e[j][0] - tp[k][0] * e[j][2]; te[k][j][2] = tp[k][0] * e[j][1] - tp[k][1] * e[j][0]; te[k][j][3] = te[k][j][0] * tv[k][j][0] + te[k][j][1] * tv[k][j][1] + te[k][j][2] * tv[k][j][2]; } tb[k][0] = 2; tb[k][1] = -2; tb[k][2] = 2; tb[k][3] = -2; for(int j = 0; j < 3; j++) { tb[k][0] = std::min(tb[k][0], tv[k][j][0] / -tv[k][j][2]); tb[k][1] = std::max(tb[k][1], tv[k][j][0] / -tv[k][j][2]); tb[k][2] = std::min(tb[k][2], tv[k][j][1] / -tv[k][j][2]); tb[k][3] = std::max(tb[k][3], tv[k][j][1] / -tv[k][j][2]); } } float intersect(int k, float r[3]) { int i; // find distance from r origin (0,0,0) to plane in units of plane normal float factor = r[0] * tp[k][0] + r[1] * tp[k][1] + r[2] * tp[k][2]; // if coincident, fail if(factor == 0.0) return F; // find distance to plane in world units float t = tp[k][3] / factor; // if intersection is behind the ray, fail if(t < 0) return F; // calculate the point in the plane float p[3]; for(int i = 0; i < 3; i++) p[i] = r[i] * t; for(i = 0; i < 3; i++) { // calculate the distance from each edge i to the point float edge = te[k][i][0] * p[0] + te[k][i][1] * p[1] + te[k][i][2] * p[2]; // if the distance is greater than the distance to the opposite vertex, fail if(edge < te[k][i][3]) return F; } // succeed by returning the distance return t; } int main() { float v[3][3]; // Read triangles. while(scanf("%f %f %f %f %f %f %f %f %f", &v[0][0], &v[0][1], &v[0][2], &v[1][0], &v[1][1], &v[1][2], &v[2][0], &v[2][1], &v[2][2]) == 9) { for(int j = 0; j < 3; j++) for(int i = 0; i < 3; i++) { tv[tc][j][i] = v[j][i]; } prepare(tc); tc++; } printf("P2 %d %d 255\n", W, H); float pdx = .5 / (W / 2.0); float pdy = .5 / (H / 2.0); for(int py = 0; py < H; py++) for(int px = 0; px < W; px++) { // Make the ray float r[3]; r[0] = -.5 + (px + .5) * pdx; r[1] = - (-.5 + (py + .5) * pdy); r[2] = -1; // find the closest triangle int tri = -1; float t = F; for(int k = 0; k < tc; k++) { if(r[0] < tb[k][0]) continue; if(r[0] > tb[k][1]) continue; if(r[1] < tb[k][2]) continue; if(r[1] > tb[k][3]) continue; float t2 = intersect(k, r); if(t2 < t) { t = t2; tri = k; } } // shade the intersection float shade; if(tri == -1) { shade = .2; } else { float facing = r[0] * tp[tri][0] + r[1] * tp[tri][1] + r[2] * tp[tri][2]; float lighting = L[0] * tp[tri][0] + L[1] * tp[tri][1] + L[2] * tp[tri][2]; if(facing > 0) lighting = -lighting; shade = std::max(0.1f, lighting); } printf("%d ", (int)(shade * 255)); } }
26.687805
91
0.425882
bradgrantham
4679a7b3404ed6d2823d710f72a2e305de31da3b
755
cpp
C++
insts/std/PVOC/PVFilterTest.cpp
jwmatthys/RTcmix
c9ba0c5bee2cd5e091c81333cf819d267008635b
[ "Apache-2.0" ]
40
2015-01-14T20:52:42.000Z
2022-03-09T00:50:45.000Z
insts/std/PVOC/PVFilterTest.cpp
jwmatthys/RTcmix
c9ba0c5bee2cd5e091c81333cf819d267008635b
[ "Apache-2.0" ]
20
2015-01-26T19:02:59.000Z
2022-01-30T18:00:39.000Z
insts/std/PVOC/PVFilterTest.cpp
jwmatthys/RTcmix
c9ba0c5bee2cd5e091c81333cf819d267008635b
[ "Apache-2.0" ]
14
2015-01-14T20:52:43.000Z
2021-09-24T02:24:32.000Z
// PVFilterTest.cpp -- test class for pvoc data filters #include "PVFilterTest.h" #include <stdio.h> #include <ugens.h> PVFilter * PVFilterTest::create() { return new PVFilterTest; } PVFilterTest::PVFilterTest() { } PVFilterTest::~PVFilterTest() { } int PVFilterTest::run(float *pvdata, int nvals) { for (int n = 0; n < nvals; ++n) { const int ampIdx = n * 2; const int frqIdx = ampIdx + 1; pvdata[frqIdx] *= val2; pvdata[frqIdx] += val1; } return 0; } int PVFilterTest::init(double *pp, int nargs) { val1 = pp[0]; val2 = pp[1]; return 1; } // This function is called by the PVOC setup() routine for each DSO extern "C" { int registerLib(int (*register_fun)(FilterCreateFunction)) { return register_fun(&PVFilterTest::create); } }
15.729167
67
0.675497
jwmatthys
467a5110cc99dab334a99239e0b6d2733962ca4c
21
cc
C++
src/main/c++/novemberizing/io/buffer.cc
iticworld/reactive-lib
9ab761376776e759390fa417d50921ec6e8a898a
[ "Apache-2.0" ]
1
2020-10-10T11:57:15.000Z
2020-10-10T11:57:15.000Z
src/main/c++/novemberizing/io/buffer.cc
iticworld/reactive-lib
9ab761376776e759390fa417d50921ec6e8a898a
[ "Apache-2.0" ]
null
null
null
src/main/c++/novemberizing/io/buffer.cc
iticworld/reactive-lib
9ab761376776e759390fa417d50921ec6e8a898a
[ "Apache-2.0" ]
null
null
null
#include "buffer.hh"
10.5
20
0.714286
iticworld
467adea4e2f3af676246adae4073c1f4877d720e
75
hxx
C++
src/drawable.hxx
luutifa/openglpractice
1158453f0b124910ad8c4101f226dd55b5ce4262
[ "MIT" ]
null
null
null
src/drawable.hxx
luutifa/openglpractice
1158453f0b124910ad8c4101f226dd55b5ce4262
[ "MIT" ]
null
null
null
src/drawable.hxx
luutifa/openglpractice
1158453f0b124910ad8c4101f226dd55b5ce4262
[ "MIT" ]
null
null
null
#pragma once class Drawable { public: virtual void draw() const; };
10.714286
30
0.653333
luutifa
46811eb70d97fa59ee2378376fe31f71a8204a9b
1,327
cc
C++
mindspore/lite/tools/converter/adapter/acl/mapper/fused_batchnorm_mapper.cc
PowerOlive/mindspore
bda20724a94113cedd12c3ed9083141012da1f15
[ "Apache-2.0" ]
3,200
2020-02-17T12:45:41.000Z
2022-03-31T20:21:16.000Z
mindspore/lite/tools/converter/adapter/acl/mapper/fused_batchnorm_mapper.cc
zimo-geek/mindspore
665ec683d4af85c71b2a1f0d6829356f2bc0e1ff
[ "Apache-2.0" ]
176
2020-02-12T02:52:11.000Z
2022-03-28T22:15:55.000Z
mindspore/lite/tools/converter/adapter/acl/mapper/fused_batchnorm_mapper.cc
zimo-geek/mindspore
665ec683d4af85c71b2a1f0d6829356f2bc0e1ff
[ "Apache-2.0" ]
621
2020-03-09T01:31:41.000Z
2022-03-30T03:43:19.000Z
/** * Copyright 2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "tools/converter/adapter/acl/mapper/fused_batchnorm_mapper.h" #include "tools/converter/adapter/acl/mapper/primitive_mapper_register.h" #include "ops/op_utils.h" namespace mindspore { namespace lite { STATUS FusedBatchNormMapper::Mapper(const CNodePtr &cnode) { ValueNodePtr value_node = nullptr; PrimitivePtr src_prim = nullptr; if (GetValueNodeAndPrimFromCnode(cnode, &value_node, &src_prim) != lite::RET_OK) { MS_LOG(ERROR) << "Get primitive from cnode failed."; return lite::RET_ERROR; } src_prim->AddAttr(ops::kIsTraining, MakeValue(false)); return lite::RET_OK; } REGISTER_PRIMITIVE_MAPPER(kNameFusedBatchNorm, FusedBatchNormMapper) } // namespace lite } // namespace mindspore
35.864865
84
0.757347
PowerOlive
46816ff6a443ba8ba63c8eefac6401da4f99b69f
2,338
cxx
C++
include/rrwindows/console/console_virtual_terminal_sequences.cxx
afoolsbag/rrCnCxx
1e673bd4edac43d8406a0c726138cba194d17f48
[ "Unlicense" ]
2
2019-03-20T01:14:10.000Z
2021-12-08T15:39:32.000Z
include/rrwindows/console/console_virtual_terminal_sequences.cxx
afoolsbag/rrCnCxx
1e673bd4edac43d8406a0c726138cba194d17f48
[ "Unlicense" ]
null
null
null
include/rrwindows/console/console_virtual_terminal_sequences.cxx
afoolsbag/rrCnCxx
1e673bd4edac43d8406a0c726138cba194d17f48
[ "Unlicense" ]
null
null
null
/// \copyright Unlicense #include "rrwindows/console/console_virtual_terminal_sequences.hxx" #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include "rrwindows/debug/error_handling.hxx" using namespace std; namespace rrwindows { RRWINDOWS_API void RRWINDOWS_CALL enable_virtual_terminal_mode() { DWORD dwMode; CONST HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); if (hStdOut == INVALID_HANDLE_VALUE) throw system_error_exception("GetStdHandle failed", GetLastError()); if (!GetConsoleMode(hStdOut, &dwMode)) throw system_error_exception("GetConsoleMode failed", GetLastError()); dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; if (!SetConsoleMode(hStdOut, dwMode)) throw system_error_exception("SetConsoleMode failed", GetLastError()); const auto hStdErr = GetStdHandle(STD_ERROR_HANDLE); if (hStdErr == INVALID_HANDLE_VALUE) throw system_error_exception("GetStdHandle failed", GetLastError()); if (!GetConsoleMode(hStdErr, &dwMode)) throw system_error_exception("GetConsoleMode failed", GetLastError()); dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; if (!SetConsoleMode(hStdErr, dwMode)) throw system_error_exception("SetConsoleMode failed", GetLastError()); } RRWINDOWS_API void RRWINDOWS_CALL disable_virtual_terminal_mode() { DWORD dwMode; const auto hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); if (hStdOut == INVALID_HANDLE_VALUE) throw system_error_exception("GetStdHandle failed", GetLastError()); if (!GetConsoleMode(hStdOut, &dwMode)) throw system_error_exception("GetConsoleMode failed", GetLastError()); dwMode &= ~static_cast<DWORD>(ENABLE_VIRTUAL_TERMINAL_PROCESSING); if (!SetConsoleMode(hStdOut, dwMode)) throw system_error_exception("SetConsoleMode failed", GetLastError()); const auto hStdErr = GetStdHandle(STD_ERROR_HANDLE); if (hStdErr == INVALID_HANDLE_VALUE) throw system_error_exception("GetStdHandle failed", GetLastError()); if (!GetConsoleMode(hStdErr, &dwMode)) throw system_error_exception("GetConsoleMode failed", GetLastError()); dwMode &= ~static_cast<DWORD>(ENABLE_VIRTUAL_TERMINAL_PROCESSING); if (!SetConsoleMode(hStdErr, dwMode)) throw system_error_exception("SetConsoleMode failed", GetLastError()); } }
38.327869
78
0.749358
afoolsbag
46823dbdade1cbfdbfe418a0c45b44216ff606cf
14,456
cpp
C++
push1st-server/core/lua/clua.cpp
navek-soft/push1st
6d0638e31031dcf55442382df0e92ac67d95801b
[ "Apache-2.0" ]
16
2021-11-02T07:29:18.000Z
2021-12-23T13:28:05.000Z
push1st-server/core/lua/clua.cpp
navek-soft/push1st
6d0638e31031dcf55442382df0e92ac67d95801b
[ "Apache-2.0" ]
null
null
null
push1st-server/core/lua/clua.cpp
navek-soft/push1st
6d0638e31031dcf55442382df0e92ac67d95801b
[ "Apache-2.0" ]
null
null
null
#include "clua.h" #include <unordered_map> #include <set> #include <deque> #include <functional> #include <ctime> #define l L.get() void* clua::engine::getModule(clua::lua_t L, const std::string_view& modName, const std::string_view& modNamespace) { if (lua_getglobal(L, modNamespace.data()); lua_istable(L, -1)) { if (lua_getfield(L, -1, modName.data()); lua_istable(L, -1)) { lua_getfield(L, -1, "__self"); if (lua_islightuserdata(L, -1)) { return (void*)lua_touserdata(L, -1); } } } return nullptr; } ssize_t clua::engine::luaRegisterModule(lua_t L, std::initializer_list<std::pair<std::string_view, lua_CFunction>>& methods, void* modClassSelf, const std::string_view& modName, const std::string_view& modNamespace) { if (!modNamespace.empty()) { lua_getglobal(L, modNamespace.data()); if (/*auto nfn = lua_gettop(L); */lua_isnil(L, -1)) { lua_newtable(L); //lua_pushstring(L, modNamespace.c_str()); //lua_setfield(L, -2, "__namespace"); lua_setglobal(L, modNamespace.data()); } if (lua_getglobal(L, modNamespace.data()); lua_istable(L, -1)) { lua_pushstring(L, modName.data()); { lua_newtable(L); lua_pushlightuserdata(L, modClassSelf); lua_setfield(L, -2, "__self"); for (auto&& [mn, mfn] : methods) { lua_pushcfunction(L, mfn); lua_setfield(L, -2, mn.data()); } lua_settable(L, -3); } } } else { lua_newtable(L); lua_pushlightuserdata(L, modClassSelf); lua_setfield(L, -2, "__self"); for (auto&& [mn, mfn] : methods) { lua_pushcfunction(L, mfn); lua_setfield(L, -2, mn.data()); } lua_setglobal(L, modName.data()); } return 0; } std::vector<std::any> clua::engine::luaExecute(const std::string& luaScript, const std::string& luaFunction, const std::vector<std::any>& luaArgs) { std::vector<std::any> multiReturn; if (auto&& L{ S() }; L) { if (!luaScript.empty()) { if (luaL_dofile(l, luaScript.c_str()) != 0) { fprintf(stderr, "clua::execute(`%s`): %s\n", luaScript.c_str(), lua_tostring(l, -1)); lua_pop(l, 1); return {}; } } if (!luaFunction.empty()) { auto multi_return_top = lua_gettop(l); try { if (lua_getglobal(l, luaFunction.c_str()); lua_isfunction(l, -1)) { for (auto&& v : luaArgs) { pushValue(l, v); } if (lua_pcall(l, (int)luaArgs.size(), LUA_MULTRET, 0) == 0) { if (int multi_return_count = lua_gettop(l) - multi_return_top; multi_return_count) { multiReturn.reserve(multi_return_count); for (; multi_return_count; --multi_return_count) { if (lua_isinteger(l, -multi_return_count)) { multiReturn.emplace_back(std::any{ ssize_t(lua_tointeger(l, -multi_return_count)) }); } else if (lua_isboolean(l, -multi_return_count)) { multiReturn.emplace_back(std::any{ bool(lua_toboolean(l, -multi_return_count)) }); } else if (lua_isnil(l, -multi_return_count)) { multiReturn.emplace_back(std::any{ nullptr }); } else if (lua_isstring(l, -multi_return_count)) { size_t ptr_len{ 0 }; if (auto ptr_str = lua_tolstring(l, -multi_return_count, &ptr_len); ptr_str && ptr_len) { multiReturn.emplace_back(std::string{ ptr_str,ptr_str + ptr_len }); } else { multiReturn.emplace_back(std::string{ }); } } else if (lua_istable(l, -multi_return_count)) { std::unordered_map<std::string, std::string> map; auto ntop = lua_gettop(l); lua_pushnil(l); while (lua_next(l, -multi_return_count - 1)) { if (lua_isnumber(l, -2)) { map.emplace(std::to_string(lua_tointeger(l, -2)), lua_tostring(l, -1)); } else if (lua_isstring(l, -2)) { map.emplace(lua_tostring(l, -2), lua_tostring(l, -1)); } lua_pop(l, 1); } multiReturn.emplace_back(map); lua_settop(l, ntop); } } } } else { fprintf(stderr, "clua::execute(error running function `%s`): %s\n", luaFunction.c_str(), lua_tostring(l, -1)); return {}; } } else { fprintf(stderr, "clua::execute(error running function `%s`): %s\n", luaFunction.c_str(), lua_tostring(l, -1)); return {}; } lua_settop(l, multi_return_top); } catch (std::exception& ex) { fprintf(stderr, "clua::exception(error running function `%s`): %s\n", luaFunction.c_str(), lua_tostring(l, -1)); } } } else { fprintf(stderr, "clua::execute(error script): %s\n", "invalid lua context (script is empty)"); } return multiReturn; } void clua::engine::luaAddRelativePackagePath(lua_t L, const std::string& path) { if (!path.empty()) { std::string pPath; if (path.front() != '/') { pPath = packageBasePath + path; } else { pPath = path; } packagePaths.emplace(pPath); if (L) { lua_getglobal(L, "package"); lua_getfield(L, -1, "path"); std::string cur_path{ lua_tostring(L, -1) }; cur_path.append(";" + pPath); lua_pop(L, 1); lua_pushstring(L, cur_path.c_str()); lua_setfield(L, -2, "path"); lua_pop(L, 1); } } } void clua::engine::luaAddPackagePath(const std::string& path) { if (!path.empty()) { if (path.back() == '/') packagePaths.emplace(path + "?.lua"); else packagePaths.emplace(path + "/?.lua"); } } void clua::engine::luaPackagePath(std::string& pathPackages) { for (auto&& path : packagePaths) { pathPackages.append(";" + path); } } clua::engine::engine() { } clua::engine::~engine() { } clua::lua_ptr_t clua::engine::S() { lua_ptr_t jitLua{ luaL_newstate(), [](lua_t L) { lua_close(L); } }; luaL_openlibs(jitLua.get()); /* adjust lua package.path */ { lua_getglobal(jitLua.get(), "package"); lua_getfield(jitLua.get(), -1, "path"); std::string cur_path{ lua_tostring(jitLua.get(), -1) }; luaPackagePath(cur_path); lua_pop(jitLua.get(), 1); lua_pushstring(jitLua.get(), cur_path.c_str()); lua_setfield(jitLua.get(), -2, "path"); lua_pop(jitLua.get(), 1); } luaLoadModules(jitLua.get()); return jitLua; } namespace typecast { static void push_value(clua::lua_t L, const std::any& val); template<typename T> void push_integer(clua::lua_t L, const std::any& val) { lua_pushinteger(L, std::any_cast<T>(val)); } template<typename T> void push_number(clua::lua_t L, const std::any& val) { lua_pushnumber(L, std::any_cast<T>(val)); } void push_bool(clua::lua_t L, const std::any& val) { lua_pushboolean(L, std::any_cast<bool>(val)); } void push_string(clua::lua_t L, const std::any& val) { lua_pushstring(L, std::any_cast<const char*>(val)); } void push_cstring(clua::lua_t L, const std::any& val) { auto&& _v = std::any_cast<std::string>(val); lua_pushlstring(L, _v.data(), _v.length()); } void push_vstring(clua::lua_t L, const std::any& val) { auto&& _v = std::any_cast<std::string_view>(val); lua_pushlstring(L, _v.data(), _v.length()); } void push_rawdata(clua::lua_t L, const std::any& val) { auto&& _v = std::any_cast<std::vector<uint8_t>>(val); lua_pushlstring(L, (const char*)_v.data(), _v.size()); } void push_nil(clua::lua_t L, const std::any& val) { lua_pushnil(L); } void push_mapsa(clua::lua_t L, const std::any& val) { lua_newtable(L); if (!std::any_cast<std::unordered_map<std::string, std::any>>(val).empty()) { for (auto&& [k, v] : std::any_cast<std::unordered_map<std::string, std::any>>(val)) { lua_pushlstring(L, k.c_str(), k.length()); push_value(L, v); lua_settable(L, -3); } } } void push_mapsva(clua::lua_t L, const std::any& val) { lua_newtable(L); if (!std::any_cast<std::unordered_map<std::string_view, std::any>>(val).empty()) { for (auto&& [k, v] : std::any_cast<std::unordered_map<std::string_view, std::any>>(val)) { lua_pushlstring(L, k.data(), k.size()); push_value(L, v); lua_settable(L, -3); } } } void push_seta(clua::lua_t L, const std::any& val) { lua_newtable(L); if (!std::any_cast<std::set<std::any>>(val).empty()) { int n = 1; for (auto&& v : std::any_cast<std::set<std::any>>(val)) { lua_pushinteger(L, n++); push_value(L, (std::any&)v); lua_settable(L, -3); } } } void push_deqa(clua::lua_t L, const std::any& val) { lua_newtable(L); if (!std::any_cast<std::deque<std::any>>(val).empty()) { int n = 1; for (auto&& v : std::any_cast<std::deque<std::any>>(val)) { lua_pushinteger(L, n++); push_value(L, (std::any&)v); lua_settable(L, -3); } } } void push_deqsw(clua::lua_t L, const std::any& val) { lua_newtable(L); if (!std::any_cast<std::deque<std::string_view>>(val).empty()) { int n = 1; for (auto&& v : std::any_cast<std::deque<std::string_view>>(val)) { lua_pushinteger(L, n++); lua_pushlstring(L, v.data(), v.length()); lua_settable(L, -3); } } } void push_class_t(clua::lua_t L, const std::any& val) { auto&& v{ std::any_cast<clua::class_t::self_t>(val) }; void** place = (void**)lua_newuserdata(L, sizeof(void*)); *place = v.selfObject; lua_newtable(L); lua_pushcfunction(L, clua::class_t::__index); lua_setfield(L, -2, "__index"); lua_pushcfunction(L, clua::class_t::__tostring); lua_setfield(L, -2, "__tostring"); lua_pushcfunction(L, clua::class_t::__gc); lua_setfield(L, -2, "__gc"); lua_setmetatable(L, -2); v.selfObject = nullptr; // now __gc can free resource } void push_veca(clua::lua_t L, const std::any& val) { lua_newtable(L); if (!std::any_cast<std::vector<std::any>>(val).empty()) { int n = 1; for (auto&& v : std::any_cast<std::vector<std::any>>(val)) { lua_pushinteger(L, n++); push_value(L, (std::any&)v); lua_settable(L, -3); } } } static const std::unordered_map<size_t, std::function<void(clua::lua_t L, const std::any& val)>> PushTypecast{ {typeid(float).hash_code(),push_number<float>}, {typeid(double).hash_code(),push_number<double>}, {typeid(int).hash_code(),push_integer<int>}, {typeid(int16_t).hash_code(),push_integer<int16_t>}, {typeid(uint16_t).hash_code(),push_integer<uint16_t>}, {typeid(int32_t).hash_code(),push_integer<int32_t>}, {typeid(uint32_t).hash_code(),push_integer<uint32_t>}, {typeid(ssize_t).hash_code(),push_integer<ssize_t>}, {typeid(std::time_t).hash_code(),push_integer<std::time_t>}, {typeid(size_t).hash_code(),push_integer<size_t>}, {typeid(int64_t).hash_code(),push_integer<int64_t>}, {typeid(uint64_t).hash_code(),push_integer<uint64_t>}, {typeid(bool).hash_code(),push_bool}, {typeid(const char*).hash_code(),push_string}, {typeid(std::string).hash_code(),push_cstring}, {typeid(std::string_view).hash_code(),push_vstring}, {typeid(std::deque<std::any>).hash_code(),push_deqa}, {typeid(std::deque<std::string_view>).hash_code(),push_deqsw}, {typeid(std::vector<std::any>).hash_code(),push_veca}, {typeid(std::set<std::any>).hash_code(),push_seta}, {typeid(std::unordered_map<std::string,std::any>).hash_code(),push_mapsa}, {typeid(std::unordered_map<std::string_view,std::any>).hash_code(), push_mapsva}, {typeid(clua::class_t::self_t).hash_code(),push_class_t}, {typeid(nullptr).hash_code(),push_nil}, }; void push_value(clua::lua_t L, const std::any& val) { if (val.has_value()) { if (auto&& it = typecast::PushTypecast.find(val.type().hash_code()); it != typecast::PushTypecast.end()) { it->second(L, val); } else { fprintf(stderr, "clua::typecast(%s) no found\n", val.type().name()); } } else { push_nil(L, { nullptr }); } } } void clua::engine::pushValue(clua::lua_t L, const std::any& val) { typecast::push_value(L, val); }
41.185185
217
0.509408
navek-soft
46835ffc0fa55038a82c3e8f90cfff09dc4cb13e
19,985
cpp
C++
src/game/server/hl1/hl1_npc_leech.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/game/server/hl1/hl1_npc_leech.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/game/server/hl1/hl1_npc_leech.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// #include "cbase.h" #include "ai_default.h" #include "ai_task.h" #include "ai_schedule.h" #include "ai_node.h" #include "ai_hull.h" #include "ai_hint.h" #include "ai_memory.h" #include "ai_route.h" #include "ai_motor.h" #include "soundent.h" #include "game.h" #include "npcevent.h" #include "entitylist.h" #include "activitylist.h" #include "animation.h" #include "basecombatweapon.h" #include "IEffects.h" #include "vstdlib/random.h" #include "engine/IEngineSound.h" #include "ammodef.h" #include "hl1_ai_basenpc.h" #include "ai_senses.h" // Animation events #define LEECH_AE_ATTACK 1 #define LEECH_AE_FLOP 2 //#define DEBUG_BEAMS 0 ConVar sk_leech_health("sk_leech_health", "2"); ConVar sk_leech_dmg_bite("sk_leech_dmg_bite", "2"); // Movement constants #define LEECH_ACCELERATE 10 #define LEECH_CHECK_DIST 45 #define LEECH_SWIM_SPEED 50 #define LEECH_SWIM_ACCEL 80 #define LEECH_SWIM_DECEL 10 #define LEECH_TURN_RATE 70 #define LEECH_SIZEX 10 #define LEECH_FRAMETIME 0.1 class CNPC_Leech : public CHL1BaseNPC { DECLARE_CLASS( CNPC_Leech, CHL1BaseNPC ); public: DECLARE_DATADESC(); void Spawn(void); void Precache(void); static const char *pAlertSounds[]; void SwimThink(void); void DeadThink(void); void SwitchLeechState(void); float ObstacleDistance(CBaseEntity *pTarget); void UpdateMotion(void); void RecalculateWaterlevel(void); void Touch(CBaseEntity *pOther); Disposition_t IRelationType(CBaseEntity *pTarget); void HandleAnimEvent(animevent_t *pEvent); void AttackSound(void); void AlertSound(void); void Activate(void); Class_T Classify(void) { return CLASS_INSECT; }; void Event_Killed(const CTakeDamageInfo &info); bool ShouldGib(const CTakeDamageInfo &info); /* // Base entity functions void Killed( entvars_t *pevAttacker, int iGib ); int TakeDamage( entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType ); */ private: // UNDONE: Remove unused boid vars, do group behavior float m_flTurning;// is this boid turning? bool m_fPathBlocked;// TRUE if there is an obstacle ahead float m_flAccelerate; float m_obstacle; float m_top; float m_bottom; float m_height; float m_waterTime; float m_sideTime; // Timer to randomly check clearance on sides float m_zTime; float m_stateTime; float m_attackSoundTime; Vector m_oldOrigin; }; LINK_ENTITY_TO_CLASS( monster_leech, CNPC_Leech ); BEGIN_DATADESC( CNPC_Leech ) DEFINE_FIELD( m_flTurning, FIELD_FLOAT ), DEFINE_FIELD( m_fPathBlocked, FIELD_BOOLEAN ), DEFINE_FIELD( m_flAccelerate, FIELD_FLOAT ), DEFINE_FIELD( m_obstacle, FIELD_FLOAT ), DEFINE_FIELD( m_top, FIELD_FLOAT ), DEFINE_FIELD( m_bottom, FIELD_FLOAT ), DEFINE_FIELD( m_height, FIELD_FLOAT ), DEFINE_FIELD( m_waterTime, FIELD_TIME ), DEFINE_FIELD( m_sideTime, FIELD_TIME ), DEFINE_FIELD( m_zTime, FIELD_TIME ), DEFINE_FIELD( m_stateTime, FIELD_TIME ), DEFINE_FIELD( m_attackSoundTime, FIELD_TIME ), DEFINE_FIELD( m_oldOrigin, FIELD_VECTOR ), DEFINE_THINKFUNC( SwimThink ), DEFINE_THINKFUNC(DeadThink), END_DATADESC() bool CNPC_Leech::ShouldGib(const CTakeDamageInfo &info) { return false; } void CNPC_Leech::Spawn(void) { Precache(); SetModel("models/leech.mdl"); SetHullType(HULL_TINY_CENTERED); SetHullSizeNormal(); UTIL_SetSize(this, Vector(-1, -1, 0), Vector(1, 1, 2)); Vector vecSurroundingMins(-8, -8, 0); Vector vecSurroundingMaxs(8, 8, 2); CollisionProp()->SetSurroundingBoundsType(USE_SPECIFIED_BOUNDS, &vecSurroundingMins, &vecSurroundingMaxs); // Don't push the minz down too much or the water check will fail because this entity is really point-sized SetSolid(SOLID_BBOX); AddSolidFlags(FSOLID_NOT_STANDABLE); SetMoveType(MOVETYPE_FLY); AddFlag(FL_SWIM); m_iHealth = sk_leech_health.GetInt(); m_flFieldOfView = -0.5; // 180 degree FOV SetDistLook(750); NPCInit(); SetThink(&CNPC_Leech::SwimThink); SetUse(NULL); SetTouch(NULL); SetViewOffset(vec3_origin); m_flTurning = 0; m_fPathBlocked = FALSE; SetActivity(ACT_SWIM); SetState(NPC_STATE_IDLE); m_stateTime = gpGlobals->curtime + random->RandomFloat(1, 5); SetRenderColor(255, 255, 255, 255); m_bloodColor = DONT_BLEED; SetCollisionGroup(COLLISION_GROUP_DEBRIS); } void CNPC_Leech::Activate(void) { RecalculateWaterlevel(); BaseClass::Activate(); } void CNPC_Leech::DeadThink(void) { if (IsSequenceFinished()) { if (GetActivity() == ACT_DIEFORWARD) { SetThink(NULL); StopAnimation(); return; } else if (GetFlags() & FL_ONGROUND) { AddSolidFlags(FSOLID_NOT_SOLID); SetActivity(ACT_DIEFORWARD); } } StudioFrameAdvance(); SetNextThink(gpGlobals->curtime + 0.1); // Apply damage velocity, but keep out of the walls if (GetAbsVelocity().x != 0 || GetAbsVelocity().y != 0) { trace_t tr; // Look 0.5 seconds ahead UTIL_TraceLine(GetLocalOrigin(), GetLocalOrigin() + GetAbsVelocity() * 0.5, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr); if (tr.fraction != 1.0) { Vector vVelocity = GetAbsVelocity(); vVelocity.x = 0; vVelocity.y = 0; SetAbsVelocity(vVelocity); } } } Disposition_t CNPC_Leech::IRelationType(CBaseEntity *pTarget) { if (pTarget->IsPlayer()) return D_HT; return BaseClass::IRelationType(pTarget); } void CNPC_Leech::Touch(CBaseEntity *pOther) { if (!pOther->IsPlayer()) return; if (pOther == GetTouchTrace().m_pEnt) { if (pOther->GetAbsVelocity() == vec3_origin) return; SetBaseVelocity(pOther->GetAbsVelocity()); AddFlag(FL_BASEVELOCITY); } } void CNPC_Leech::HandleAnimEvent(animevent_t *pEvent) { CBaseEntity *pEnemy = GetEnemy(); switch (pEvent->event) { case LEECH_AE_FLOP: // Play flop sound break; case LEECH_AE_ATTACK: AttackSound(); if (pEnemy != NULL) { Vector dir, face; AngleVectors(GetAbsAngles(), &face); face.z = 0; dir = (pEnemy->GetLocalOrigin() - GetLocalOrigin()); dir.z = 0; VectorNormalize(dir); VectorNormalize(face); if (DotProduct(dir, face) > 0.9) // Only take damage if the leech is facing the prey { CTakeDamageInfo info(this, this, sk_leech_dmg_bite.GetInt(), DMG_SLASH); CalculateMeleeDamageForce(&info, dir, pEnemy->GetAbsOrigin()); pEnemy->TakeDamage(info); } } m_stateTime -= 2; break; default: BaseClass::HandleAnimEvent(pEvent); break; } } void CNPC_Leech::Precache(void) { PrecacheModel("models/leech.mdl"); PrecacheScriptSound("Leech.Attack"); PrecacheScriptSound("Leech.Alert"); } void CNPC_Leech::AttackSound(void) { if (gpGlobals->curtime > m_attackSoundTime) { CPASAttenuationFilter filter(this); EmitSound(filter, entindex(), "Leech.Attack"); m_attackSoundTime = gpGlobals->curtime + 0.5; } } void CNPC_Leech::AlertSound(void) { CPASAttenuationFilter filter(this); EmitSound(filter, entindex(), "Leech.Alert"); } void CNPC_Leech::SwitchLeechState(void) { m_stateTime = gpGlobals->curtime + random->RandomFloat(3, 6); if (m_NPCState == NPC_STATE_COMBAT) { SetEnemy(NULL); SetState(NPC_STATE_IDLE); // We may be up against the player, so redo the side checks m_sideTime = 0; } else { GetSenses()->Look(GetSenses()->GetDistLook()); CBaseEntity *pEnemy = BestEnemy(); if (pEnemy && pEnemy->GetWaterLevel() != 0) { SetEnemy(pEnemy); SetState(NPC_STATE_COMBAT); m_stateTime = gpGlobals->curtime + random->RandomFloat(18, 25); AlertSound(); } } } void CNPC_Leech::RecalculateWaterlevel(void) { // Calculate boundaries Vector vecTest = GetLocalOrigin() - Vector(0, 0, 400); trace_t tr; UTIL_TraceLine(GetLocalOrigin(), vecTest, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr); if (tr.fraction != 1.0) m_bottom = tr.endpos.z + 1; else m_bottom = vecTest.z; m_top = UTIL_WaterLevel(GetLocalOrigin(), GetLocalOrigin().z, GetLocalOrigin().z + 400) - 1; #if DEBUG_BEAMS NDebugOverlay::Line( GetLocalOrigin(), GetLocalOrigin() + Vector( 0, 0, m_bottom ), 0, 255, 0, false, 0.1f ); NDebugOverlay::Line( GetLocalOrigin(), GetLocalOrigin() + Vector( 0, 0, m_top ), 0, 255, 255, false, 0.1f ); #endif // Chop off 20% of the outside range float newBottom = m_bottom * 0.8 + m_top * 0.2; m_top = m_bottom * 0.2 + m_top * 0.8; m_bottom = newBottom; m_height = random->RandomFloat(m_bottom, m_top); m_waterTime = gpGlobals->curtime + random->RandomFloat(5, 7); } void CNPC_Leech::SwimThink(void) { trace_t tr; float flLeftSide; float flRightSide; float targetSpeed; float targetYaw = 0; CBaseEntity *pTarget; /*if ( !UTIL_FindClientInPVS( edict() ) ) { m_flNextThink = gpGlobals->curtime + random->RandomFloat( 1.0f, 1.5f ); SetAbsVelocity( vec3_origin ); return; } else*/ SetNextThink(gpGlobals->curtime + 0.1); targetSpeed = LEECH_SWIM_SPEED; if (m_waterTime < gpGlobals->curtime) RecalculateWaterlevel(); if (m_stateTime < gpGlobals->curtime) SwitchLeechState(); ClearCondition(COND_CAN_MELEE_ATTACK1); switch (m_NPCState) { case NPC_STATE_COMBAT: pTarget = GetEnemy(); if (!pTarget) SwitchLeechState(); else { // Chase the enemy's eyes m_height = pTarget->GetLocalOrigin().z + pTarget->GetViewOffset().z - 5; // Clip to viable water area if (m_height < m_bottom) m_height = m_bottom; else if (m_height > m_top) m_height = m_top; Vector location = pTarget->GetLocalOrigin() - GetLocalOrigin(); location.z += (pTarget->GetViewOffset().z); if (location.Length() < 80) SetCondition(COND_CAN_MELEE_ATTACK1); // Turn towards target ent targetYaw = UTIL_VecToYaw(location); QAngle vTestAngle = GetAbsAngles(); targetYaw = UTIL_AngleDiff(targetYaw, UTIL_AngleMod(GetAbsAngles().y)); if (targetYaw < (-LEECH_TURN_RATE)) targetYaw = (-LEECH_TURN_RATE); else if (targetYaw > (LEECH_TURN_RATE)) targetYaw = (LEECH_TURN_RATE); else targetSpeed *= 2; } break; default: if (m_zTime < gpGlobals->curtime) { float newHeight = random->RandomFloat(m_bottom, m_top); m_height = 0.5 * m_height + 0.5 * newHeight; m_zTime = gpGlobals->curtime + random->RandomFloat(1, 4); } if (random->RandomInt(0, 100) < 10) targetYaw = random->RandomInt(-30, 30); pTarget = NULL; // oldorigin test if ((GetLocalOrigin() - m_oldOrigin).Length() < 1) { // If leech didn't move, there must be something blocking it, so try to turn m_sideTime = 0; } break; } m_obstacle = ObstacleDistance(pTarget); m_oldOrigin = GetLocalOrigin(); if (m_obstacle < 0.1) m_obstacle = 0.1; Vector vForward, vRight; AngleVectors(GetAbsAngles(), &vForward, &vRight, NULL); // is the way ahead clear? if (m_obstacle == 1.0) { // if the leech is turning, stop the trend. if (m_flTurning != 0) { m_flTurning = 0; } m_fPathBlocked = FALSE; m_flSpeed = UTIL_Approach(targetSpeed, m_flSpeed, LEECH_SWIM_ACCEL * LEECH_FRAMETIME); SetAbsVelocity(vForward * m_flSpeed); } else { m_obstacle = 1.0 / m_obstacle; // IF we get this far in the function, the leader's path is blocked! m_fPathBlocked = TRUE; if (m_flTurning == 0)// something in the way and leech is not already turning to avoid { Vector vecTest; // measure clearance on left and right to pick the best dir to turn vecTest = GetLocalOrigin() + (vRight * LEECH_SIZEX) + (vForward * LEECH_CHECK_DIST); UTIL_TraceLine(GetLocalOrigin(), vecTest, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr); flRightSide = tr.fraction; vecTest = GetLocalOrigin() + (vRight * -LEECH_SIZEX) + (vForward * LEECH_CHECK_DIST); UTIL_TraceLine(GetLocalOrigin(), vecTest, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr); flLeftSide = tr.fraction; // turn left, right or random depending on clearance ratio float delta = (flRightSide - flLeftSide); if (delta > 0.1 || (delta > -0.1 && random->RandomInt(0, 100) < 50)) m_flTurning = -LEECH_TURN_RATE; else m_flTurning = LEECH_TURN_RATE; } m_flSpeed = UTIL_Approach(-(LEECH_SWIM_SPEED * 0.5), m_flSpeed, LEECH_SWIM_DECEL * LEECH_FRAMETIME * m_obstacle); SetAbsVelocity(vForward * m_flSpeed); } GetMotor()->SetIdealYaw(m_flTurning + targetYaw); UpdateMotion(); } // // ObstacleDistance - returns normalized distance to obstacle // float CNPC_Leech::ObstacleDistance(CBaseEntity *pTarget) { trace_t tr; Vector vecTest; Vector vForward, vRight; // use VELOCITY, not angles, not all boids point the direction they are flying //Vector vecDir = UTIL_VecToAngles( pev->velocity ); QAngle tmp = GetAbsAngles(); tmp.x = -tmp.x; AngleVectors(tmp, &vForward, &vRight, NULL); // check for obstacle ahead vecTest = GetLocalOrigin() + vForward * LEECH_CHECK_DIST; UTIL_TraceLine(GetLocalOrigin(), vecTest, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr); if (tr.startsolid) { m_flSpeed = -LEECH_SWIM_SPEED * 0.5; } if (tr.fraction != 1.0) { if ((pTarget == NULL || tr.m_pEnt != pTarget)) { return tr.fraction; } else { if (fabs(m_height - GetLocalOrigin().z) > 10) return tr.fraction; } } if (m_sideTime < gpGlobals->curtime) { // extra wide checks vecTest = GetLocalOrigin() + vRight * LEECH_SIZEX * 2 + vForward * LEECH_CHECK_DIST; UTIL_TraceLine(GetLocalOrigin(), vecTest, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr); if (tr.fraction != 1.0) return tr.fraction; vecTest = GetLocalOrigin() - vRight * LEECH_SIZEX * 2 + vForward * LEECH_CHECK_DIST; UTIL_TraceLine(GetLocalOrigin(), vecTest, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr); if (tr.fraction != 1.0) return tr.fraction; // Didn't hit either side, so stop testing for another 0.5 - 1 seconds m_sideTime = gpGlobals->curtime + random->RandomFloat(0.5, 1); } return 1.0; } void CNPC_Leech::UpdateMotion(void) { float flapspeed = (m_flSpeed - m_flAccelerate) / LEECH_ACCELERATE; m_flAccelerate = m_flAccelerate * 0.8 + m_flSpeed * 0.2; if (flapspeed < 0) flapspeed = -flapspeed; flapspeed += 1.0; if (flapspeed < 0.5) flapspeed = 0.5; if (flapspeed > 1.9) flapspeed = 1.9; m_flPlaybackRate = flapspeed; QAngle vAngularVelocity = GetLocalAngularVelocity(); QAngle vAngles = GetLocalAngles(); if (!m_fPathBlocked) vAngularVelocity.y = GetMotor()->GetIdealYaw(); else vAngularVelocity.y = GetMotor()->GetIdealYaw() * m_obstacle; if (vAngularVelocity.y > 150) SetIdealActivity(ACT_TURN_LEFT); else if (vAngularVelocity.y < -150) SetIdealActivity(ACT_TURN_RIGHT); else SetIdealActivity(ACT_SWIM); // lean float targetPitch, delta; delta = m_height - GetLocalOrigin().z; /* if ( delta < -10 ) targetPitch = -30; else if ( delta > 10 ) targetPitch = 30; else*/ targetPitch = 0; vAngles.x = UTIL_Approach(targetPitch, vAngles.x, 60 * LEECH_FRAMETIME); // bank vAngularVelocity.z = -(vAngles.z + (vAngularVelocity.y * 0.25)); if (m_NPCState == NPC_STATE_COMBAT && HasCondition(COND_CAN_MELEE_ATTACK1)) SetIdealActivity(ACT_MELEE_ATTACK1); // Out of water check if (!GetWaterLevel()) { SetMoveType(MOVETYPE_FLYGRAVITY); SetIdealActivity(ACT_HOP); SetAbsVelocity(vec3_origin); // Animation will intersect the floor if either of these is non-zero vAngles.z = 0; vAngles.x = 0; m_flPlaybackRate = random->RandomFloat(0.8, 1.2); } else if (GetMoveType() == MOVETYPE_FLYGRAVITY) { SetMoveType(MOVETYPE_FLY); SetGroundEntity(NULL); // TODO RecalculateWaterlevel(); m_waterTime = gpGlobals->curtime + 2; // Recalc again soon, water may be rising } if (GetActivity() != GetIdealActivity()) { SetActivity(GetIdealActivity()); } StudioFrameAdvance(); DispatchAnimEvents(this); SetLocalAngles(vAngles); SetLocalAngularVelocity(vAngularVelocity); Vector vForward, vRight; AngleVectors(vAngles, &vForward, &vRight, NULL); #if DEBUG_BEAMS if ( m_fPathBlocked ) { float color = m_obstacle * 30; if ( m_obstacle == 1.0 ) color = 0; if ( color > 255 ) color = 255; NDebugOverlay::Line( GetLocalOrigin(), GetLocalOrigin() + vForward * LEECH_CHECK_DIST, 255, color, color, false, 0.1f ); } else NDebugOverlay::Line( GetLocalOrigin(), GetLocalOrigin() + vForward * LEECH_CHECK_DIST, 255, 255, 0, false, 0.1f ); NDebugOverlay::Line( GetLocalOrigin(), GetLocalOrigin() + vRight * (vAngularVelocity.y*0.25), 0, 0, 255, false, 0.1f ); #endif } void CNPC_Leech::Event_Killed(const CTakeDamageInfo &info) { Vector vecSplatDir; trace_t tr; //ALERT(at_aiconsole, "Leech: killed\n"); // tell owner ( if any ) that we're dead.This is mostly for MonsterMaker functionality. CBaseEntity *pOwner = GetOwnerEntity(); if (pOwner) pOwner->DeathNotice(this); // When we hit the ground, play the "death_end" activity if (GetWaterLevel()) { QAngle qAngles = GetAbsAngles(); QAngle qAngularVel = GetLocalAngularVelocity(); Vector vOrigin = GetLocalOrigin(); qAngles.z = 0; qAngles.x = 0; vOrigin.z += 1; SetAbsVelocity(vec3_origin); if (random->RandomInt(0, 99) < 70) qAngularVel.y = random->RandomInt(-720, 720); SetAbsAngles(qAngles); SetLocalAngularVelocity(qAngularVel); SetAbsOrigin(vOrigin); SetGravity(0.02); SetGroundEntity(NULL); SetActivity(ACT_DIESIMPLE); } else SetActivity(ACT_DIEFORWARD); SetMoveType(MOVETYPE_FLYGRAVITY); m_takedamage = DAMAGE_NO; SetThink(&CNPC_Leech::DeadThink); }
28.71408
129
0.615161
cstom4994
468943227aa1aababc7ce2303fe243effbaadc5e
11,202
inl
C++
Extras/RigidBodyGpuPipeline/opencl/primitives/AdlPrimitives/Sort/RadixSort32.inl
tizenorg/platform.upstream.libbullet
eb6918d59f661c0e5b469d6e007f91a82d46a302
[ "Zlib" ]
2
2015-02-28T15:50:06.000Z
2016-04-12T18:03:10.000Z
Extras/RigidBodyGpuPipeline/opencl/primitives/AdlPrimitives/Sort/RadixSort32.inl
tizenorg/platform.upstream.libbullet
eb6918d59f661c0e5b469d6e007f91a82d46a302
[ "Zlib" ]
null
null
null
Extras/RigidBodyGpuPipeline/opencl/primitives/AdlPrimitives/Sort/RadixSort32.inl
tizenorg/platform.upstream.libbullet
eb6918d59f661c0e5b469d6e007f91a82d46a302
[ "Zlib" ]
null
null
null
/* 2011 Takahiro Harada */ #define PATH "..\\..\\opencl\\primitives\\AdlPrimitives\\Sort\\RadixSort32Kernels" #define RADIXSORT32_KERNEL0 "StreamCountKernel" #define RADIXSORT32_KERNEL1 "PrefixScanKernel" #define RADIXSORT32_KERNEL2 "SortAndScatterKernel" #define RADIXSORT32_KERNEL3 "SortAndScatterKeyValueKernel" #define RADIXSORT32_KERNEL4 "SortAndScatterSortDataKernel" #define RADIXSORT32_KERNEL5 "StreamCountSortDataKernel" #include "RadixSort32KernelsCL.h" #include "RadixSort32KernelsDX11.h" // todo. Shader compiler (2010JuneSDK) doesn't allow me to place Barriers in SortAndScatterKernel... // So it only works on a GPU with 64 wide SIMD. template<DeviceType TYPE> typename RadixSort32<TYPE>::Data* RadixSort32<TYPE>::allocate( const Device* device, int maxSize ) { ADLASSERT( TYPE == device->m_type ); const char* src[] = #if defined(ADL_LOAD_KERNEL_FROM_STRING) {radixSort32KernelsCL, radixSort32KernelsDX11}; #else {0,0}; #endif Data* data = new Data; data->m_device = device; data->m_maxSize = maxSize; data->m_streamCountKernel = device->getKernel( PATH, RADIXSORT32_KERNEL0, 0, src[TYPE] ); data->m_streamCountSortDataKernel = device->getKernel( PATH, RADIXSORT32_KERNEL5, 0, src[TYPE] ); data->m_prefixScanKernel = device->getKernel( PATH, RADIXSORT32_KERNEL1, 0, src[TYPE] ); data->m_sortAndScatterKernel = device->getKernel( PATH, RADIXSORT32_KERNEL2, 0, src[TYPE] ); data->m_sortAndScatterKeyValueKernel = device->getKernel( PATH, RADIXSORT32_KERNEL3, 0, src[TYPE] ); data->m_sortAndScatterSortDataKernel = device->getKernel( PATH, RADIXSORT32_KERNEL4, 0, src[TYPE] ); int wtf = NUM_WGS*(1<<BITS_PER_PASS); data->m_workBuffer0 = new Buffer<u32>( device, maxSize ); data->m_workBuffer1 = new Buffer<u32>( device , wtf ); data->m_workBuffer2 = new Buffer<u32>( device, maxSize ); data->m_workBuffer3 = new Buffer<SortData>(device,maxSize); for(int i=0; i<32/BITS_PER_PASS; i++) data->m_constBuffer[i] = new Buffer<ConstData>( device, 1, BufferBase::BUFFER_CONST ); data->m_copyData = Copy<TYPE>::allocate( device ); return data; } template<DeviceType TYPE> void RadixSort32<TYPE>::deallocate( Data* data ) { delete data->m_workBuffer0; delete data->m_workBuffer1; delete data->m_workBuffer2; delete data->m_workBuffer3; for(int i=0; i<32/BITS_PER_PASS; i++) delete data->m_constBuffer[i]; Copy<TYPE>::deallocate( data->m_copyData ); delete data; } template<DeviceType TYPE> void RadixSort32<TYPE>::execute(Data* data, Buffer<u32>& inout, int n, int sortBits /* = 32 */ ) { ADLASSERT( n%DATA_ALIGNMENT == 0 ); ADLASSERT( n <= data->m_maxSize ); // ADLASSERT( ELEMENTS_PER_WORK_ITEM == 4 ); ADLASSERT( BITS_PER_PASS == 4 ); ADLASSERT( WG_SIZE == 64 ); ADLASSERT( (sortBits&0x3) == 0 ); Buffer<u32>* src = &inout; Buffer<u32>* dst = data->m_workBuffer0; Buffer<u32>* histogramBuffer = data->m_workBuffer1; int nWGs = NUM_WGS; ConstData cdata; { int nBlocks = (n+ELEMENTS_PER_WORK_ITEM*WG_SIZE-1)/(ELEMENTS_PER_WORK_ITEM*WG_SIZE); cdata.m_n = n; cdata.m_nWGs = NUM_WGS; cdata.m_startBit = 0; cdata.m_nBlocksPerWG = (nBlocks + cdata.m_nWGs - 1)/cdata.m_nWGs; if( nBlocks < NUM_WGS ) { cdata.m_nBlocksPerWG = 1; nWGs = nBlocks; } } for(int ib=0; ib<sortBits; ib+=4) { cdata.m_startBit = ib; { BufferInfo bInfo[] = { BufferInfo( src, true ), BufferInfo( histogramBuffer ) }; Launcher launcher( data->m_device, data->m_streamCountKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( NUM_WGS*WG_SIZE, WG_SIZE ); } {// prefix scan group histogram BufferInfo bInfo[] = { BufferInfo( histogramBuffer ) }; Launcher launcher( data->m_device, data->m_prefixScanKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( 128, 128 ); } {// local sort and distribute BufferInfo bInfo[] = { BufferInfo( src, true ), BufferInfo( histogramBuffer, true ), BufferInfo( dst ) }; Launcher launcher( data->m_device, data->m_sortAndScatterKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( nWGs*WG_SIZE, WG_SIZE ); } swap2( src, dst ); } if( src != &inout ) { Copy<TYPE>::execute( data->m_copyData, (Buffer<float>&)inout, (Buffer<float>&)*src, n ); } } template<DeviceType TYPE> void RadixSort32<TYPE>::execute(Data* data, Buffer<u32>& in, Buffer<u32>& out, int n, int sortBits /* = 32 */ ) { ADLASSERT( n%DATA_ALIGNMENT == 0 ); ADLASSERT( n <= data->m_maxSize ); // ADLASSERT( ELEMENTS_PER_WORK_ITEM == 4 ); ADLASSERT( BITS_PER_PASS == 4 ); ADLASSERT( WG_SIZE == 64 ); ADLASSERT( (sortBits&0x3) == 0 ); Buffer<u32>* src = &in; Buffer<u32>* dst = data->m_workBuffer0; Buffer<u32>* histogramBuffer = data->m_workBuffer1; int nWGs = NUM_WGS; ConstData cdata; { int nBlocks = (n+ELEMENTS_PER_WORK_ITEM*WG_SIZE-1)/(ELEMENTS_PER_WORK_ITEM*WG_SIZE); cdata.m_n = n; cdata.m_nWGs = NUM_WGS; cdata.m_startBit = 0; cdata.m_nBlocksPerWG = (nBlocks + cdata.m_nWGs - 1)/cdata.m_nWGs; if( nBlocks < NUM_WGS ) { cdata.m_nBlocksPerWG = 1; nWGs = nBlocks; } } if( sortBits == 4 ) dst = &out; for(int ib=0; ib<sortBits; ib+=4) { if( ib==4 ) { dst = &out; } cdata.m_startBit = ib; { BufferInfo bInfo[] = { BufferInfo( src, true ), BufferInfo( histogramBuffer ) }; Launcher launcher( data->m_device, data->m_streamCountKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( NUM_WGS*WG_SIZE, WG_SIZE ); } {// prefix scan group histogram BufferInfo bInfo[] = { BufferInfo( histogramBuffer ) }; Launcher launcher( data->m_device, data->m_prefixScanKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( 128, 128 ); } {// local sort and distribute BufferInfo bInfo[] = { BufferInfo( src, true ), BufferInfo( histogramBuffer, true ), BufferInfo( dst ) }; Launcher launcher( data->m_device, data->m_sortAndScatterKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( nWGs*WG_SIZE, WG_SIZE ); } swap2( src, dst ); } } template<DeviceType TYPE> void RadixSort32<TYPE>::execute(Data* data, Buffer<u32>& keysIn, Buffer<u32>& keysOut, Buffer<u32>& valuesIn, Buffer<u32>& valuesOut, int n, int sortBits /* = 32 */) { ADLASSERT( n%DATA_ALIGNMENT == 0 ); ADLASSERT( n <= data->m_maxSize ); // ADLASSERT( ELEMENTS_PER_WORK_ITEM == 4 ); ADLASSERT( BITS_PER_PASS == 4 ); ADLASSERT( WG_SIZE == 64 ); ADLASSERT( (sortBits&0x3) == 0 ); Buffer<u32>* src = &keysIn; Buffer<u32>* srcVal = &valuesIn; Buffer<u32>* dst = data->m_workBuffer0; Buffer<u32>* dstVal = data->m_workBuffer2; Buffer<u32>* histogramBuffer = data->m_workBuffer1; int nWGs = NUM_WGS; ConstData cdata; { int nBlocks = (n+ELEMENTS_PER_WORK_ITEM*WG_SIZE-1)/(ELEMENTS_PER_WORK_ITEM*WG_SIZE); cdata.m_n = n; cdata.m_nWGs = NUM_WGS; cdata.m_startBit = 0; cdata.m_nBlocksPerWG = (nBlocks + cdata.m_nWGs - 1)/cdata.m_nWGs; if( nBlocks < NUM_WGS ) { cdata.m_nBlocksPerWG = 1; nWGs = nBlocks; } } if( sortBits == 4 ) { dst = &keysOut; dstVal = &valuesOut; } for(int ib=0; ib<sortBits; ib+=4) { if( ib==4 ) { dst = &keysOut; dstVal = &valuesOut; } cdata.m_startBit = ib; { BufferInfo bInfo[] = { BufferInfo( src, true ), BufferInfo( histogramBuffer ) }; Launcher launcher( data->m_device, data->m_streamCountKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( NUM_WGS*WG_SIZE, WG_SIZE ); } {// prefix scan group histogram BufferInfo bInfo[] = { BufferInfo( histogramBuffer ) }; Launcher launcher( data->m_device, data->m_prefixScanKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( 128, 128 ); } {// local sort and distribute BufferInfo bInfo[] = { BufferInfo( src, true ), BufferInfo( srcVal, true ), BufferInfo( histogramBuffer, true ), BufferInfo( dst ), BufferInfo( dstVal ) }; Launcher launcher( data->m_device, data->m_sortAndScatterKeyValueKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( nWGs*WG_SIZE, WG_SIZE ); } swap2( src, dst ); swap2( srcVal, dstVal ); } } template<DeviceType TYPE> void RadixSort32<TYPE>::execute(Data* data, Buffer<SortData>& keyValuesInOut, int n, int sortBits /* = 32 */) { ADLASSERT( n%DATA_ALIGNMENT == 0 ); ADLASSERT( n <= data->m_maxSize ); // ADLASSERT( ELEMENTS_PER_WORK_ITEM == 4 ); ADLASSERT( BITS_PER_PASS == 4 ); ADLASSERT( WG_SIZE == 64 ); ADLASSERT( (sortBits&0x3) == 0 ); Buffer<SortData>* src = &keyValuesInOut; Buffer<SortData>* dst = data->m_workBuffer3; Buffer<u32>* histogramBuffer = data->m_workBuffer1; int nWGs = NUM_WGS; ConstData cdata; { int nBlocks = (n+ELEMENTS_PER_WORK_ITEM*WG_SIZE-1)/(ELEMENTS_PER_WORK_ITEM*WG_SIZE); cdata.m_n = n; cdata.m_nWGs = NUM_WGS; cdata.m_startBit = 0; cdata.m_nBlocksPerWG = (nBlocks + cdata.m_nWGs - 1)/cdata.m_nWGs; if( nBlocks < NUM_WGS ) { cdata.m_nBlocksPerWG = 1; nWGs = nBlocks; } } int count=0; for(int ib=0; ib<sortBits; ib+=4) { cdata.m_startBit = ib; { BufferInfo bInfo[] = { BufferInfo( src, true ), BufferInfo( histogramBuffer ) }; Launcher launcher( data->m_device, data->m_streamCountSortDataKernel); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( NUM_WGS*WG_SIZE, WG_SIZE ); } {// prefix scan group histogram BufferInfo bInfo[] = { BufferInfo( histogramBuffer ) }; Launcher launcher( data->m_device, data->m_prefixScanKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( 128, 128 ); } {// local sort and distribute BufferInfo bInfo[] = { BufferInfo( src, true ), BufferInfo( histogramBuffer, true ), BufferInfo( dst )}; Launcher launcher( data->m_device, data->m_sortAndScatterSortDataKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( nWGs*WG_SIZE, WG_SIZE ); } swap2( src, dst ); count++; } if (count&1) { ADLASSERT(0);//need to copy from workbuffer to keyValuesInOut } } #undef PATH #undef RADIXSORT32_KERNEL0 #undef RADIXSORT32_KERNEL1 #undef RADIXSORT32_KERNEL2 #undef RADIXSORT32_KERNEL3
32.282421
165
0.701303
tizenorg
468fcc6d2ed9c2da8a6a448e880c86f2aa80fc2a
310
hpp
C++
src/FileSystemUtils.hpp
antmicro/ros-tracking-nodes-tester-node
878336dca10288e017665d2b2b9d075acecbf26b
[ "Apache-2.0" ]
null
null
null
src/FileSystemUtils.hpp
antmicro/ros-tracking-nodes-tester-node
878336dca10288e017665d2b2b9d075acecbf26b
[ "Apache-2.0" ]
null
null
null
src/FileSystemUtils.hpp
antmicro/ros-tracking-nodes-tester-node
878336dca10288e017665d2b2b9d075acecbf26b
[ "Apache-2.0" ]
null
null
null
#ifndef FILE_SYSTEM_UTILS #define FILE_SYSTEM_UTILS #include <string> #include <vector> namespace FileSystemUtils { inline bool endsWith(std::string const & value, std::string const & ending); void listFiles(std::string dir_path, std::vector<std::string> &files, std::string extension=""); } #endif
22.142857
100
0.73871
antmicro
46919e1867b7bb36b75acf947a58b6309383024e
1,566
cc
C++
src/abc059/c.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc059/c.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc059/c.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; ll solve(int n, vector<ll> a) { ll sum = 0, count = 0; for(int i = 0; i < n; i++) { ll temp = sum + a[i]; if(i % 2 == 0) { if(temp > 0) { sum = temp; continue; } else { ll delta = abs(temp) + 1; count += delta; sum = temp + delta; } } else { // odd if(temp < 0) { sum = temp; continue; } else { // temp > 0 ll delta = -temp - 1; count += abs(delta); sum = temp + delta; } } } ll res = count; sum = count = 0; for(int i = 0; i < n; i++) { ll temp = sum + a[i]; if(i % 2 == 1) { // odd if(temp > 0) { sum = temp; continue; } else { ll delta = abs(temp) + 1; count += delta; sum = temp + delta; } } else { // odd if(temp < 0) { sum = temp; continue; } else { // temp > 0 ll delta = -temp - 1; count += abs(delta); sum = temp + delta; } } } res = min(res, count); return res; } /* int main() { int n; cin >> n; vector<ll> a(n); for(int i = 0; i < n; i++) { cin >> a[i]; } cout << solve(n, a) << endl; } */
23.727273
41
0.327586
nryotaro
46949531f8ddf132fb5010d55fba16a29d7c004e
7,478
cpp
C++
Simbody/tests/TestSmoothSphereHalfSpaceForce.cpp
e-schumann/simbody
4d8842270d5c400ef64cfd5723e0e0399161e51f
[ "Apache-2.0" ]
1,916
2015-01-01T09:35:21.000Z
2022-03-30T11:38:43.000Z
Simbody/tests/TestSmoothSphereHalfSpaceForce.cpp
e-schumann/simbody
4d8842270d5c400ef64cfd5723e0e0399161e51f
[ "Apache-2.0" ]
389
2015-01-01T01:13:51.000Z
2022-03-16T15:30:58.000Z
Simbody/tests/TestSmoothSphereHalfSpaceForce.cpp
e-schumann/simbody
4d8842270d5c400ef64cfd5723e0e0399161e51f
[ "Apache-2.0" ]
486
2015-01-02T10:25:49.000Z
2022-03-16T15:31:40.000Z
/* -------------------------------------------------------------------------- * * Simbody(tm) * * -------------------------------------------------------------------------- * * This is part of the SimTK biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. * * * * Portions copyright (c) 2008-19 Stanford University and the Authors. * * Authors: Antoine Falisse, Gil Serrancoli * * Contributors: Peter Eastman * * * * 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 "SimTKsimbody.h" using namespace SimTK; using namespace std; const Real TOL = 1e-10; #define ASSERT(cond) {SimTK_ASSERT_ALWAYS(cond, "Assertion failed");} template <class T> void assertEqual(T val1, T val2) { ASSERT(abs(val1-val2) < TOL); } template <int N> void assertEqual(Vec<N> val1, Vec<N> val2) { for (int i = 0; i < N; ++i) ASSERT(abs(val1[i]-val2[i]) < TOL); } void testForces() { MultibodySystem system; SimbodyMatterSubsystem matter(system); GeneralForceSubsystem forces(system); const Vec3 gravity = Vec3(0, -9.8, 0); Force::UniformGravity(forces, matter, gravity, 0); const Real radius = 0.8; const Real k = 1500.0; const Real stiffness = 0.5*std::pow(k, 2.0/3.0); const Real dissipation = 0.5; const Real us = 1.0; const Real ud = 0.5; const Real uv = 0.1; const Real vt = 0.001; const Real cf = 1e-5; const Real bd = 300; const Real bv = 50; Body::Rigid body1(MassProperties(1.0, Vec3(0), Inertia(1))); MobilizedBody::Translation sphere(matter.updGround(), Transform(), body1, Transform()); Body::Rigid body2(MassProperties(1.0, Vec3(0), Inertia(1))); MobilizedBody::Free halfSpace(matter.updGround(), Transform(), body2, Transform()); SmoothSphereHalfSpaceForce hc_smooth(forces); hc_smooth.setParameters(k,dissipation,us,ud,uv,vt,cf,bd,bv); hc_smooth.setContactSphereBody(sphere); hc_smooth.setContactSphereLocationInBody(Vec3(0)); hc_smooth.setContactSphereRadius(radius); Transform testFrame(Rotation(-0.5*Pi, ZAxis), Vec3(0)); hc_smooth.setContactHalfSpaceFrame(testFrame); hc_smooth.setContactHalfSpaceBody(halfSpace); State state = system.realizeTopology(); // Position the sphere at a variety of positions and see if the normal // force and potential energy are correct. for (Real height = radius+0.2; height > 0; height -= 0.1) { sphere.setQToFitTranslation(state, Vec3(0, height, 0)); system.realize(state, Stage::Dynamics); const Real depth = radius-height; Real f = (4./3.)*stiffness*std::pow(std::sqrt(depth*depth+cf),3./2.) *std::sqrt(radius*stiffness); Real f_smooth = f*(1./2.+(1./2.)*std::tanh(bd*depth)); assertEqual(system.getRigidBodyForces(state, Stage::Dynamics) [sphere.getMobilizedBodyIndex()][1], gravity+Vec3(0, f_smooth, 0)); assertEqual(hc_smooth.calcPotentialEnergyContribution(state), (2./5.)*f_smooth*depth); } // Now do it with a vertical velocity and see if the dissipation force is // correct. for (Real height = radius+0.2; height > 0; height -= 0.1) { sphere.setQToFitTranslation(state, Vec3(0, height, 0)); const Real depth = radius-height; Real fh = (4./3.)*stiffness*std::pow(std::sqrt(depth*depth+cf),3./2.) *std::sqrt(radius*stiffness); Real fh_smooth = fh*(1./2.+(1./2.)*std::tanh(bd*depth)); for (Real v = -1.0; v <= 1.0; v += 0.1) { sphere.setUToFitLinearVelocity(state, Vec3(0, -v, 0)); system.realize(state, Stage::Dynamics); Real f = fh_smooth*(1.+(3./2.)*dissipation*v); Real f_smooth = f*(1./2.+(1./2.) *std::tanh(bv*(v+(2./(3.*dissipation))))); assertEqual(system.getRigidBodyForces(state, Stage::Dynamics) [sphere.getMobilizedBodyIndex()][1], gravity+Vec3(0, f_smooth, 0)); } } // Now do it with a horizontal velocity and see if the friction force is // correct. Vector_<SpatialVec> expectedForce(matter.getNumBodies()); for (Real height = radius+0.2; height > 0; height -= 0.1) { sphere.setQToFitTranslation(state, Vec3(0, height, 0)); const Real depth = radius-height; Real fh = (4./3.)*stiffness*std::pow(std::sqrt(depth*depth+cf),3./2.) *std::sqrt(radius*stiffness); Real fh_smooth = fh*(1./2.+(1./2.)*std::tanh(bd*depth)); for (Real v = -1.0; v <= 1.0; v += 0.1) { sphere.setUToFitLinearVelocity(state, Vec3(v, 0, 0)); system.realize(state, Stage::Dynamics); Vec3 vec3v(v,0,0); UnitVec3 normal = (halfSpace.getBodyRotation(state)*testFrame.x()); Real vnormal = dot(vec3v, normal); Vec3 vtangent = vec3v - vnormal*normal; Real aux = vtangent.normSqr() + cf; Real vslip = pow(aux,1./2.); Real vrel = vslip / vt; Real ff_smooth_scalar = fh_smooth*(std::min(vrel,Real(1))* (ud+2*(us-ud)/(1+vrel*vrel))+uv*vslip); Vec3 ff_smooth = ff_smooth_scalar*(vtangent) / vslip; const Vec3 totalForceOnSphere = gravity - ff_smooth - fh_smooth*normal; expectedForce = SpatialVec(Vec3(0), Vec3(0)); Vec3 contactPointInSphere = sphere.findStationAtGroundPoint(state, Vec3(0, -stiffness*depth/(stiffness+stiffness), 0)); sphere.applyForceToBodyPoint(state, contactPointInSphere, totalForceOnSphere, expectedForce); SpatialVec actualForce = system.getRigidBodyForces(state, Stage::Dynamics)[sphere.getMobilizedBodyIndex()]; assertEqual(actualForce[0], expectedForce[sphere.getMobilizedBodyIndex()][0]); assertEqual(actualForce[1], expectedForce[sphere.getMobilizedBodyIndex()][1]); } } } int main() { try { testForces(); } catch(const std::exception& e) { cout << "exception: " << e.what() << endl; return 1; } cout << "Done" << endl; return 0; }
44.778443
80
0.56606
e-schumann
4696fe7ded22d7a620a092d9bfb77c12dec81854
718
cpp
C++
L04-Railroad/Student_Code/Factory.cpp
tlyon3/CS235
2bdb8eaf66c9adbfe7ec59c0535852fd1cc30eda
[ "MIT" ]
1
2018-03-04T02:58:55.000Z
2018-03-04T02:58:55.000Z
L04-Railroad/Student_Code/Factory.cpp
tlyon3/CS235
2bdb8eaf66c9adbfe7ec59c0535852fd1cc30eda
[ "MIT" ]
1
2015-02-09T21:29:12.000Z
2015-02-09T21:32:06.000Z
L04-Railroad/Student_Code/Factory.cpp
tlyon3/CS235
2bdb8eaf66c9adbfe7ec59c0535852fd1cc30eda
[ "MIT" ]
4
2019-05-20T02:57:47.000Z
2021-02-11T15:41:15.000Z
#include "Factory.h" #include "station.h" //You may add #include statments here using namespace std; /* Unlike all other documents provided, you may modify this document slightly (but do not change its name) */ //======================================================================================= /* createStation() Creates and returns an object whose class extends StationInterface. This should be an object of a class you have created. Example: If you made a class called "Station", you might say, "return new Station();". */ StationInterface* Factory::createStation() { return new Station();//Modify this line } //=======================================================================================
31.217391
104
0.558496
tlyon3
469ae2939322e272ff45c6fe1f633df93b3137a6
373
hh
C++
LAMPS-HighEnergy/detector/LHNeutronScintArray.hh
ggfdsa10/KEBI_AT-TPC
40e00fcd10d3306b93fff93be5fb0988f87715a7
[ "MIT" ]
3
2021-05-24T19:43:30.000Z
2022-01-06T21:03:23.000Z
LAMPS-HighEnergy/detector/LHNeutronScintArray.hh
ggfdsa10/KEBI_AT-TPC
40e00fcd10d3306b93fff93be5fb0988f87715a7
[ "MIT" ]
4
2020-05-04T15:52:26.000Z
2021-09-13T10:51:03.000Z
LAMPS-HighEnergy/detector/LHNeutronScintArray.hh
ggfdsa10/KEBI_AT-TPC
40e00fcd10d3306b93fff93be5fb0988f87715a7
[ "MIT" ]
3
2020-06-14T10:53:58.000Z
2022-01-06T21:03:30.000Z
#ifndef LHNEUTRONSCINTARRAY_HH #define LHNEUTRONSCINTARRAY_HH #include "KBDetector.hh" class LHNeutronScintArray : public KBDetector { public: LHNeutronScintArray(); virtual ~LHNeutronScintArray() {}; virtual bool Init(); protected: virtual bool BuildGeometry(); virtual bool BuildDetectorPlane(); ClassDef(LHNeutronScintArray, 1) }; #endif
16.954545
45
0.739946
ggfdsa10
46a09092cd0564f2523082aafc7e85aa138113b0
3,015
cpp
C++
src/drivers/Input/PS2MouseDriver.cpp
Unified-Projects/Unified-OS
89912adc1ed9ec35753fe0f4fa35f03d30ec66a2
[ "BSD-2-Clause" ]
null
null
null
src/drivers/Input/PS2MouseDriver.cpp
Unified-Projects/Unified-OS
89912adc1ed9ec35753fe0f4fa35f03d30ec66a2
[ "BSD-2-Clause" ]
null
null
null
src/drivers/Input/PS2MouseDriver.cpp
Unified-Projects/Unified-OS
89912adc1ed9ec35753fe0f4fa35f03d30ec66a2
[ "BSD-2-Clause" ]
null
null
null
#include <drivers/Input/PS2MouseDriver.h> using namespace UnifiedOS; using namespace UnifiedOS::Drivers; PS2MouseEventHandler::PS2MouseEventHandler(){ } PS2MouseEventHandler::~PS2MouseEventHandler(){ } void PS2MouseEventHandler::OnMouseDown(uint8_t button){ } void PS2MouseEventHandler::OnMouseUp(uint8_t button){ } void PS2MouseEventHandler::OnMouseMove(int x, int y){ } PS2MouseDriver::PS2MouseDriver(Interrupts::InterruptManager* manager, PS2MouseEventHandler* handler) : InterruptHandler(0x2C, manager), dataPort(0x60), commandPort(0x64) { Handler = handler; } PS2MouseDriver::~PS2MouseDriver(){ } void PS2MouseDriver::Wait(){ uint64_t timeout = 100000; while(timeout--){ if((commandPort.Read() & 0b10) == 0){ return; } } } void PS2MouseDriver::Wait_Input(){ uint64_t timeout = 100000; while(timeout--){ if(commandPort.Read() & 0b1){ return; } } } void PS2MouseDriver::Activate(){ // offset = 0; //Default Buffers // buttons = 0; // commandPort.Write(0xA8); //PIC start sending interrupts // Wait(); // commandPort.Write(0x20); //Get state // Wait_Input(); // uint8_t status = dataPort.Read() | 2; // Wait(); // commandPort.Write(0x60); //Set State // Wait(); // dataPort.Write(status); // Wait(); // commandPort.Write(0xD4); // Wait(); // dataPort.Write(0xF6); //Activate // Wait_Input(); // dataPort.Read(); // Wait(); // commandPort.Write(0xD4); // Wait(); // dataPort.Write(0xF4); //Activate // Wait_Input(); // dataPort.Read(); } bool Skip = true; void PS2MouseDriver::HandleInterrupt(uint64_t rsp){ if(Skip) {Skip = false; return;} //Skip first packet //Read status uint8_t status = commandPort.Read(); if (!(status & 0x20)) return; //If not ready return //Read Buffer at current offset buffer[offset] = dataPort.Read(); //We dont want to skip this if there is no handler if(Handler == 0) //If handler does not exist leave return; offset = (offset + 1) % 3; //Increase offset while keeping it less than three if(offset == 0) //If offset 0 (Means full buffer overwrite) { if(buffer[1] != 0 || buffer[2] != 0) //Buffer positions for cursor movement { Handler->OnMouseMove((int8_t)buffer[1], -((int8_t)buffer[2])); //We send to handler but inverse y because it is negative version } for(uint8_t i = 0; i < 3; i++) //We loop over buttons { if((buffer[0] & (0x1<<i)) != (buttons & (0x1<<i))) //Check if it is different { if(buttons & (0x1<<i)) //Shows if it is up or down Handler->OnMouseUp(i+1); //Send to handler else Handler->OnMouseDown(i+1); //Send to handler } } buttons = buffer[0]; //Load the buttons from buffer for next comparison } }
24.314516
140
0.596352
Unified-Projects
46a259730f0a41dd17d84687e7e34ffb35ebbc7c
1,677
cpp
C++
MidiChannel.cpp
Madsy/libmidi
c271e991e9d6f762e81a8d2dbf7a5cd63973629d
[ "MIT" ]
5
2018-08-14T01:04:33.000Z
2021-07-15T22:13:45.000Z
MidiChannel.cpp
Madsy/libmidi
c271e991e9d6f762e81a8d2dbf7a5cd63973629d
[ "MIT" ]
4
2017-03-21T23:10:46.000Z
2017-03-21T23:19:55.000Z
MidiChannel.cpp
Madsy/libmidi
c271e991e9d6f762e81a8d2dbf7a5cd63973629d
[ "MIT" ]
null
null
null
// // Created by madsy on 22.03.17. // #include <algorithm> #include "MidiChannel.h" MidiChannel::MidiChannel() : pChannelIndex(0), pStartTick(0), pEndTick(0) { } MidiChannel::~MidiChannel() { } std::vector<std::shared_ptr<MidiEvent>> MidiChannel::getEventsWithinInterval(unsigned int startTick, unsigned int endTick) const { std::vector<std::shared_ptr<MidiEvent>> result; for(size_t i = 0; i < pEvents.size(); i++){ unsigned int t = pEvents[i]->getTimestamp(); if(t >= startTick && t < endTick){ result.push_back(pEvents[i]); } } return pEvents; } const std::vector<std::shared_ptr<MidiEvent>> &MidiChannel::getEvents() const { return pEvents; } void MidiChannel::addEvent(const std::shared_ptr<MidiEvent> &evt) { pEvents.push_back(evt); } void MidiChannel::sort() { std::stable_sort(pEvents.begin(), pEvents.end(), [](const std::shared_ptr<MidiEvent>& a, const std::shared_ptr<MidiEvent>& b) -> bool { return a->getTimestamp() < b->getTimestamp(); } ); } unsigned int MidiChannel::getStartTick() const { return pStartTick; } unsigned int MidiChannel::getEndTick() const { return pEndTick; } void MidiChannel::update() { //refresh start and end tick after adding all events pStartTick = 0xFFFFFFFF; pEndTick = 0; for(size_t i = 0; i < pEvents.size(); i++){ if(pEvents[i] && pEvents[i]->getTimestamp() < pStartTick){ pStartTick = pEvents[i]->getTimestamp(); } if(pEvents[i] && pEvents[i]->getTimestamp() > pEndTick){ pEndTick = pEvents[i]->getTimestamp(); } } }
26.619048
130
0.621944
Madsy
46a38100725550a521f3db415b1ccaf992cbaa83
1,588
cpp
C++
Cpp/odin/odin.cpp
Deuanz/odin
da31a6bc8b9b4a0270f0807b588483840a24cf46
[ "BSL-1.0" ]
null
null
null
Cpp/odin/odin.cpp
Deuanz/odin
da31a6bc8b9b4a0270f0807b588483840a24cf46
[ "BSL-1.0" ]
null
null
null
Cpp/odin/odin.cpp
Deuanz/odin
da31a6bc8b9b4a0270f0807b588483840a24cf46
[ "BSL-1.0" ]
null
null
null
/* Copyright 2016-2017 Felspar Co Ltd. http://odin.felspar.com/ Distributed under the Boost Software License, Version 1.0. See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt */ #include <odin/odin.hpp> #include <odin/nonce.hpp> #include <fostgres/callback.hpp> const fostlib::module odin::c_odin("odin"); const fostlib::setting<fostlib::string> odin::c_jwt_secret( "odin/odin.cpp", "odin", "JWT secret", odin::nonce(), true); const fostlib::setting<bool> odin::c_jwt_trust( "odin/odin.cpp", "odin", "Trust JWT", false, true); const fostlib::setting<fostlib::string> odin::c_jwt_logout_claim( "odin/odin.cpp", "odin", "JWT logout claim", "http://odin.felspar.com/lo", true); const fostlib::setting<bool> odin::c_jwt_logout_check( "odin/odin.cpp", "odin", "Perform JWT logout check", true, true); const fostlib::setting<fostlib::string> odin::c_jwt_permissions_claim( "odin/odin.cpp", "odin", "JWT permissions claim", "http://odin.felspar.com/p", true); namespace { const fostgres::register_cnx_callback c_cb( [](fostlib::pg::connection &cnx, const fostlib::http::server::request &req) { if ( req.headers().exists("__user") ) { const auto &user = req.headers()["__user"]; cnx.set_session("odin.jwt.sub", user.value()); } if ( req.headers().exists("__jwt") ) { for ( const auto &sv : req.headers()["__jwt"] ) cnx.set_session("odin.jwt." + sv.first, sv.second); } }); }
35.288889
89
0.630982
Deuanz
46a467cd6e2de7a95f4fef7ee57741d079069e60
9,543
cpp
C++
dali/tensor/op/cost.cpp
bzcheeseman/Dali
a77c7ce60b20ce150a5927747e128688657907eb
[ "MIT" ]
null
null
null
dali/tensor/op/cost.cpp
bzcheeseman/Dali
a77c7ce60b20ce150a5927747e128688657907eb
[ "MIT" ]
null
null
null
dali/tensor/op/cost.cpp
bzcheeseman/Dali
a77c7ce60b20ce150a5927747e128688657907eb
[ "MIT" ]
null
null
null
#include "cost.h" #include "dali/array/op/binary.h" #include "dali/array/op/unary.h" #include "dali/array/op/gather_from_rows.h" #include "dali/array/op/reducers.h" #include "dali/array/op/softmax.h" #include "dali/tensor/tape.h" #include "dali/utils/make_message.h" #include "dali/tensor/tensor_macros.h" namespace tensor_ops { Tensor binary_cross_entropy(const Tensor& t, const double& target) { ASSERT2(0 <= target && target <= 1, utils::MS() << "Target value for binary_cross_entropy must be a " << "real number between 0 and 1 (got " << target << ")."); Tensor out(op::binary_cross_entropy(t.w, target)); if (graph::backprop_enabled()) { graph::emplace_back([t, target, out]() mutable { MAYBE_GRAD(t) <<= op::binary_cross_entropy_grad(t.w, target) * out.dw; }); } return out; } Tensor binary_cross_entropy(const Tensor& t, const Tensor& target) { Tensor out(op::binary_cross_entropy(t.w, target.w)); if (graph::backprop_enabled()) { graph::emplace_back([t, target, out]() mutable { MAYBE_GRAD(t) <<= op::binary_cross_entropy_grad(t.w, target.w) * out.dw; MAYBE_GRAD(target) <<= 2.0 * op::inverse_tanh(1.0 - 2.0 * t.w) * out.dw; }); } return out; } Tensor sigmoid_binary_cross_entropy(const Tensor& t, const double& target) { ASSERT2(0 <= target && target <= 1, utils::MS() << "Target value for binary_cross_entropy must be a " << "real number between 0 and 1 (got " << target << ")."); Tensor out(op::binary_cross_entropy(op::sigmoid(t.w), target)); if (graph::backprop_enabled()) { graph::emplace_back([t, target, out]() mutable { MAYBE_GRAD(t) <<= (op::sigmoid(t.w) - target) * out.dw; }); } return out; } Tensor sigmoid_binary_cross_entropy(const Tensor& t, const Tensor& target) { Tensor out(op::binary_cross_entropy(op::sigmoid(t.w), target.w)); if (graph::backprop_enabled()) { graph::emplace_back([t, target, out]() mutable { MAYBE_GRAD(t) <<= (op::sigmoid(t.w) - target.w) * out.dw; MAYBE_GRAD(target) <<= 2.0 * op::inverse_tanh(1.0 - 2.0 * op::sigmoid(t.w)) * out.dw; }); } return out; } Tensor margin_loss(const Tensor& t, const int& target, const double& margin, const int& axis) { // relevant slice: auto t_plucked = t.pluck_axis(axis, target); t_plucked = t_plucked.insert_broadcast_axis(axis); // now compare slice to rest of elements: Tensor out(op::eltmax(t_plucked.w - t.w + margin, 0.0)); out.pluck_axis(axis, target).w = 0; // gradient is wherever the if (graph::backprop_enabled()) { graph::emplace_back([t, t_plucked, margin, out, axis, target]() mutable { // TODO(szymon, jonathan): implement gradient -- previous gradient was not done explicitly // MAYBE_GRAD(t) <<= -op::F<functor::greaterthanequal>(out.w, 0.0) * out.dw; // auto t_at_target = t.pluck_axis(axis, target); // MAYBE_GRAD(t_at_target) <<= ( // op::F<functor::greaterthanequal>(out.pluck_axis(axis, target).w, 0.0) * // out.pluck_axis(axis, target).dw // ); // auto out_subslice = out.pluck_axis(axis, target); // out_subslice = out_subslice.insert_broadcast_axis(axis); // MAYBE_GRAD(t_plucked) <<= out_subslice.dw; }); } return out; } Tensor margin_loss(const Tensor&, const Tensor& target, const double& margin, const int& axis) { ASSERT2(false, "Margin loss is not yet implemented."); return Tensor(); } Tensor softmax(const Tensor& t, int axis, const double& temperature) { if (axis < 0) axis = t.ndim() + axis; Tensor out(op::softmax(t.w, axis, temperature)); if (graph::backprop_enabled() && !t.constant) graph::emplace_back([t, out, axis, temperature]() { Array softmax_times_grad_summed(op::sum(out.w * out.dw, {axis})); auto expr = (out.w * out.dw) - (out.w * softmax_times_grad_summed.insert_broadcast_axis(axis)); if (std::abs(temperature - 1.0) < 1e-6) { MAYBE_GRAD(t) <<= expr; } else { MAYBE_GRAD(t) <<= expr / temperature; } }); return out; } Tensor softmax_cross_entropy_with_idxes(const Tensor& unnormalized_probs, const Tensor& targets, const double& temperature, const int& axis) { ASSERT2(axis == unnormalized_probs.ndim() -1, utils::make_message( "softmax_cross_entropy is not yet implemented for axes other than " "-1 (got axis=", axis, ")")); Array softmax_result = op::softmax(unnormalized_probs.w, axis, temperature); Tensor out(-1.0 * op::log(op::gather_from_rows(softmax_result, targets.w))); if (graph::backprop_enabled() && !unnormalized_probs.constant) graph::emplace_back([unnormalized_probs, softmax_result, targets, temperature, axis, out]() { unnormalized_probs.dw <<= softmax_result * out.dw.insert_broadcast_axis(axis) / temperature; unnormalized_probs.dw.gather_from_rows(targets.w) -= out.dw / temperature; }); return out; } Tensor softmax_cross_entropy_with_probs(const Tensor& unnormalized_probs, const Tensor& targets, const double& temperature, const int& axis) { Array softmax_result = op::softmax(unnormalized_probs.w, axis, temperature); Tensor out(-1.0 * targets.w * op::log(softmax_result)); if (graph::backprop_enabled()) graph::emplace_back([unnormalized_probs, softmax_result, targets, temperature, axis, out]() { if (!unnormalized_probs.constant) { Array grad_times_target = op::sum(targets.w * out.dw, {axis}); grad_times_target = grad_times_target.insert_broadcast_axis(axis); unnormalized_probs.dw <<= softmax_result * grad_times_target / temperature - targets.w * out.dw / temperature; } MAYBE_GRAD(targets) <<= -op::log(softmax_result) * out.dw; }); return out; } Tensor softmax_cross_entropy(const Tensor& unnormalized_probs, const Tensor& targets, const double& temperature, int axis) { if (axis < 0) axis = unnormalized_probs.ndim() + axis; if (targets.dtype() == DTYPE_INT32) { return softmax_cross_entropy_with_idxes(unnormalized_probs, targets, temperature, axis); } else { return softmax_cross_entropy_with_probs(unnormalized_probs, targets, temperature, axis); } } Tensor cross_entropy_with_idxes(const Tensor& probs, const Tensor& target, int axis) { // 1) we ensure that cross entropy is happening in a 1D setting or // else the behavior of gather_from_rows would not broadcast in the // desired way (e.g. we assume that a single dimension contains a // multinomial distribution for which KL divergence must be computed). if (target.ndim() > 1) { return cross_entropy_with_idxes( probs.swapaxes(-1, axis).right_fit_ndim(2), target.ravel(), -1 ).reshape(target.shape()).swapaxes(-1, axis); } // 2) We now know that input probs are of the right dimensionality for // our problem (e.g. they should be 2D) and that our targets are 1D: auto permuted_probs = probs.swapaxes(-1, axis); Tensor out(-1.0 * op::log(op::gather_from_rows(permuted_probs.w, target.w))); if (graph::backprop_enabled()) graph::emplace_back([permuted_probs, target, out]() { if (!permuted_probs.constant) { permuted_probs.dw.gather_from_rows(target.w) += -out.dw / op::gather_from_rows(permuted_probs.w, target.w); } }); return out.swapaxes(axis, -1); } Tensor cross_entropy_with_probs(const Tensor& probs, const Tensor& target) { Tensor out(-1.0 * target.w * op::log(probs.w)); if (graph::backprop_enabled()) graph::emplace_back([probs, target, out]() { MAYBE_GRAD(probs) <<= -op::eltinv(probs.w) * target.w * out.dw; MAYBE_GRAD(target) <<= -op::log(probs.w) * out.dw; }); return out; } Tensor cross_entropy(const Tensor& probs, const Tensor& target, int axis) { if (target.dtype() == DTYPE_INT32) { return cross_entropy_with_idxes(probs, target, axis); } else { return cross_entropy_with_probs(probs, target); } } } // namespace tensor_ops
43.180995
111
0.562192
bzcheeseman
46a6e16f9495c024a23c36ec0d97d124ebfb46f3
593
cpp
C++
vendor/mapbox-gl-native/vendor/mapbox-base/test/io_delete.cpp
aic-develop/vietmaps-gl-native-ios-source
c73c28c4f1ea60ecd4c83c8b49f6947ee06f24f2
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
vendor/mapbox-gl-native/vendor/mapbox-base/test/io_delete.cpp
aic-develop/vietmaps-gl-native-ios-source
c73c28c4f1ea60ecd4c83c8b49f6947ee06f24f2
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
vendor/mapbox-gl-native/vendor/mapbox-base/test/io_delete.cpp
aic-develop/vietmaps-gl-native-ios-source
c73c28c4f1ea60ecd4c83c8b49f6947ee06f24f2
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
#include <mapbox/io.hpp> #include "io_delete.hpp" #include <cassert> #include <string> void deleteTests(const std::string& path, const std::string& copyPath, const std::string& invalidPath) { nonstd::expected<void, std::string> voidExpected; voidExpected = mapbox::base::io::deleteFile(path); assert(voidExpected); voidExpected = mapbox::base::io::deleteFile(copyPath); assert(voidExpected); voidExpected = mapbox::base::io::deleteFile(invalidPath); assert(!voidExpected); assert(voidExpected.error() == std::string("Failed to delete file 'invalid'")); }
28.238095
104
0.706577
aic-develop
46a7bca86ec9b994cc5976c29460d58adfaee694
550
hpp
C++
ex03/include/RobotomyRequestForm.hpp
42cursus-youkim/-Rank04-CPP-Module05
71244b25b1c9556dd4ec186e543c2a3e308d0036
[ "MIT" ]
null
null
null
ex03/include/RobotomyRequestForm.hpp
42cursus-youkim/-Rank04-CPP-Module05
71244b25b1c9556dd4ec186e543c2a3e308d0036
[ "MIT" ]
null
null
null
ex03/include/RobotomyRequestForm.hpp
42cursus-youkim/-Rank04-CPP-Module05
71244b25b1c9556dd4ec186e543c2a3e308d0036
[ "MIT" ]
null
null
null
#ifndef __ROBOTOMYREQUESTFORM_H__ #define __ROBOTOMYREQUESTFORM_H__ #include "Form.hpp" class RobotomyRequestForm : public Form { private: // Disabled Operators RobotomyRequestForm& operator=(const RobotomyRequestForm& assign); public: enum Requirement { SIGN = 72, EXEC = 45 }; // Constructors & Destructor RobotomyRequestForm(const string& target); RobotomyRequestForm(const RobotomyRequestForm& other); ~RobotomyRequestForm(); // Overrided Abstract Methods void formAction() const; }; #endif // __ROBOTOMYREQUESTFORM_H__
23.913043
68
0.767273
42cursus-youkim
9e51862fa22a4663a14bf23659084d2a25b8fc92
1,074
cpp
C++
solutions/LeetCode/C++/205.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
854
2018-11-09T08:06:16.000Z
2022-03-31T06:05:53.000Z
solutions/LeetCode/C++/205.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
29
2019-06-02T05:02:25.000Z
2021-11-15T04:09:37.000Z
solutions/LeetCode/C++/205.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
347
2018-12-23T01:57:37.000Z
2022-03-12T14:51:21.000Z
__________________________________________________________________________________________________ sample 4 ms submission static int lambda_0 = []() { std::ios::sync_with_stdio(false); cin.tie(NULL); return 0; }(); class Solution { public: bool isIsomorphic(string s, string t) { int m1[256] ={0}, m2[256] = {0}; for(int i = 0; i < s.size(); i ++) { if (m1[s[i]] != m2[t[i]]) return false; m1[s[i]] = i + 1; m2[t[i]] = i + 1; } return true; } }; __________________________________________________________________________________________________ sample 8612 kb submission class Solution { public: bool isIsomorphic(string s, string t) { int m1[256]={0}; int m2[256]={0}; for(int i=0;i<s.size();++i){ if(m1[s[i]]!=m2[t[i]])return false; m1[s[i]]=i+1; m2[t[i]]=i+1; } return true; } }; __________________________________________________________________________________________________
30.685714
98
0.597765
timxor
9e56615e2ffd44d3ff32857a39c631984255f628
8,484
cp
C++
Linux/Sources/Application/Calendar/Calendar_View/Free_Busy_View/CFreeBusyTable.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
12
2015-04-21T16:10:43.000Z
2021-11-05T13:41:46.000Z
Linux/Sources/Application/Calendar/Calendar_View/Free_Busy_View/CFreeBusyTable.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
2
2015-11-02T13:32:11.000Z
2019-07-10T21:11:21.000Z
Linux/Sources/Application/Calendar/Calendar_View/Free_Busy_View/CFreeBusyTable.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
6
2015-01-12T08:49:12.000Z
2021-03-27T09:11:10.000Z
/* Copyright (c) 2007-2009 Cyrus Daboo. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "CFreeBusyTable.h" #include "CCalendarUtils.h" #include "CCommands.h" #include "CFreeBusyTitleTable.h" #include "CMulberryCommon.h" #include "CPreferences.h" #include "CXStringResources.h" #include "CICalendarLocale.h" #include "StPenState.h" #include <UNX_LTableMultiGeometry.h> #include <JPainter.h> #include <JXColormap.h> #include <JXTextMenu.h> #include <JXScrollbar.h> #include <JXScrollbarSet.h> #include <algorithm> const uint32_t cRowHeight = 24; const uint32_t cNameColumnWidth = 128; const uint32_t cHourColumnWidth = 96; const uint32_t cNameColumn = 1; const uint32_t cFirstTimedColumn = 2; // --------------------------------------------------------------------------- // CFreeBusyTable [public] /** Default constructor */ CFreeBusyTable::CFreeBusyTable(JXScrollbarSet* scrollbarSet, JXContainer* enclosure, const HSizingOption hSizing, const VSizingOption vSizing, const JCoordinate x, const JCoordinate y, const JCoordinate w, const JCoordinate h) : CCalendarEventTableBase(scrollbarSet, enclosure, hSizing, vSizing, x, y, w, h) { mTitles = NULL; mScaleColumns = 0; mStartHour = 0; mEndHour = 24; mTableGeometry = new LTableMultiGeometry(this, 128, 24); } // --------------------------------------------------------------------------- // ~CFreeBusyTable [public] /** Destructor */ CFreeBusyTable::~CFreeBusyTable() { } #pragma mark - void CFreeBusyTable::OnCreate() { // Call inherited CCalendarEventTableBase::OnCreate(); InsertCols(1, 1, NULL); InsertRows(1, 1, NULL); SetRowHeight(cRowHeight, 1, 1); SetColWidth(cNameColumnWidth, 1, 1); itsScrollbarSet->GetHScrollbar()->SetStepSize(cHourColumnWidth); itsScrollbarSet->GetVScrollbar()->SetStepSize(cRowHeight); CreateContextMenu(CMainMenu::eContextCalendarEventTable); ApertureResized(0, 0); } void CFreeBusyTable::DrawCellRange(JPainter* pDC, const STableCell& inTopLeftCell, const STableCell& inBottomRightCell) { STableCell cell; for ( cell.row = inTopLeftCell.row; cell.row <= inBottomRightCell.row; cell.row++ ) { // Draw entire row JRect rowRect; GetLocalCellRect(STableCell(cell.row, 2), rowRect); JRect cellRect; GetLocalCellRect(STableCell(cell.row, mCols), cellRect); rowRect.right = cellRect.right; DrawRow(pDC, cell.row, rowRect); for ( cell.col = inTopLeftCell.col; cell.col <= inBottomRightCell.col; cell.col++ ) { JRect cellRect; GetLocalCellRect(cell, cellRect); DrawCell(pDC, cell, cellRect); } } } void CFreeBusyTable::DrawRow(JPainter* pDC, TableIndexT row, const JRect& inLocalRect) { StPenState save(pDC); JRect adjustedRect = inLocalRect; adjustedRect.Shrink(0, 3); float total_width = adjustedRect.width(); const SFreeBusyInfo& info = mItems.at(row - 1); JRect itemRect = adjustedRect; for(std::vector<SFreeBusyInfo::SFreeBusyPeriod>::const_iterator iter = info.mPeriods.begin(); iter != info.mPeriods.end(); iter++) { // Adjust for current width itemRect.right = itemRect.left + total_width * ((float) (*iter).second / (float)mColumnSeconds); itemRect.Shrink(1, 0); // Red for busy, green for free, blue for tentative, grey for unavailable float red = 0.0; float green = 0.0; float blue = 0.0; switch((*iter).first) { case iCal::CICalendarFreeBusy::eFree: green = 1.0; break; case iCal::CICalendarFreeBusy::eBusyTentative: blue = 1.0; break; case iCal::CICalendarFreeBusy::eBusyUnavailable: red = 0.25; green = 0.25; blue = 0.25; break; case iCal::CICalendarFreeBusy::eBusy: red = 1.0; break; } CCalendarUtils::LightenColours(red, green, blue); // Draw it JColorIndex cindex; GetColormap()->JColormap::AllocateStaticColor(CCalendarUtils::GetRGBColor(red, green, blue), &cindex); pDC->SetPenColor(cindex); pDC->SetFilling(kTrue); pDC->Rect(itemRect); pDC->SetFilling(kFalse); GetColormap()->JColormap::AllocateStaticColor(CCalendarUtils::GetRGBColor(red * 0.6, green * 0.6, blue * 0.6), &cindex); pDC->SetPenColor(cindex); pDC->Rect(itemRect); // Now adjust for next one itemRect.left += itemRect.width() + 1; itemRect.right = itemRect.left + adjustedRect.right - itemRect.left; } } void CFreeBusyTable::DrawCell(JPainter* pDC, const STableCell& inCell, const JRect& inLocalRect) { StPenState save(pDC); JRect adjustedRect = inLocalRect; JColorIndex cindex; // Left-side always { JColorIndex old_cindex = pDC->GetPenColor(); GetColormap()->JColormap::AllocateStaticColor( CCalendarUtils::GetGreyColor((inCell.col > 2) ? 0.75 : 0.5), &cindex); pDC->SetPenColor(cindex); pDC->Line(adjustedRect.left, adjustedRect.top, adjustedRect.left, adjustedRect.bottom); pDC->SetPenColor(old_cindex); } // Right-side only for last column if (inCell.col == mCols) { JColorIndex old_cindex = pDC->GetPenColor(); GetColormap()->JColormap::AllocateStaticColor(CCalendarUtils::GetGreyColor(0.5), &cindex); pDC->SetPenColor(cindex); pDC->Line(adjustedRect.right, adjustedRect.top, adjustedRect.right, adjustedRect.bottom); pDC->SetPenColor(old_cindex); } // Top-side always (lighter line above half-hour row) { JColorIndex old_cindex = pDC->GetPenColor(); GetColormap()->JColormap::AllocateStaticColor(CCalendarUtils::GetGreyColor(0.5), &cindex); pDC->SetPenColor(cindex); pDC->Line(adjustedRect.left, adjustedRect.top, adjustedRect.right, adjustedRect.top); pDC->SetPenColor(old_cindex); } // Bottom-side for last row if (inCell.row == mRows) { JColorIndex old_cindex = pDC->GetPenColor(); GetColormap()->JColormap::AllocateStaticColor(CCalendarUtils::GetGreyColor(0.5), &cindex); pDC->SetPenColor(cindex); pDC->Line(adjustedRect.left, adjustedRect.bottom, adjustedRect.right, adjustedRect.bottom); pDC->SetPenColor(old_cindex); } adjustedRect.Shrink(2, 0); if (inCell.col == 1) { cdstring name = mItems.at(inCell.row - 1).mName; pDC->SetPenColor(GetColormap()->GetBlackColor()); JRect clipRect(adjustedRect); clipRect.Shrink(0, 1); clipRect.right += 2; ::DrawClippedStringUTF8(pDC, name, JPoint(adjustedRect.left, adjustedRect.top), clipRect, eDrawString_Right); } } void CFreeBusyTable::RefreshNow() { // Redraw - double-buffering removes any flashing FRAMEWORK_REFRESH_WINDOW(this) } void CFreeBusyTable::ApertureResized(const JCoordinate dw, const JCoordinate dh) { // Allow frame adapter to adjust size CCalendarEventTableBase::ApertureResized(dw, dh); // Look for change in image size UInt32 old_width, old_height; mTableGeometry->GetTableDimensions(old_width, old_height); // If auto-fit rows, change row height RescaleWidth(); itsScrollbarSet->GetHScrollbar()->SetStepSize(GetColWidth(cFirstTimedColumn)); itsScrollbarSet->GetVScrollbar()->SetStepSize(cRowHeight); UInt32 new_width, new_height; mTableGeometry->GetTableDimensions(new_width, new_height); if (mTitles) mTitles->TableChanged(); } void CFreeBusyTable::RescaleWidth() { // If auto-fit rows, change row height if (mScaleColumns == 0) { JRect my_frame = GetFrameGlobal(); if (mCols > 1) { SInt32 col_size = std::max((SInt32) ((my_frame.width() - GetColWidth(cNameColumn)) / (mCols - 1)), 8L); SetColWidth(col_size, cFirstTimedColumn, mCols); } } } // Keep titles in sync void CFreeBusyTable::ScrollImageBy(SInt32 inLeftDelta, SInt32 inTopDelta, bool inRefresh) { // Find titles in owner chain if (mTitles) mTitles->ScrollImageBy(inLeftDelta, 0, inRefresh); CTableDrag::ScrollImageBy(inLeftDelta, inTopDelta, inRefresh); } void CFreeBusyTable::ScaleColumns(uint32_t scale) { if (scale != mScaleColumns) { mScaleColumns = scale; if (mScaleColumns > 0) SetColWidth(cHourColumnWidth / mScaleColumns, cFirstTimedColumn, mCols); else { RescaleWidth(); } } }
26.933333
131
0.709335
mulberry-mail
9e598ab89a764c1ec62524703ed3067e2692fd1f
1,497
hh
C++
src/physics/JointFeedback.hh
nherment/gazebo
fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a
[ "ECL-2.0", "Apache-2.0" ]
5
2016-01-17T20:41:39.000Z
2018-05-01T12:02:58.000Z
src/physics/JointFeedback.hh
nherment/gazebo
fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/physics/JointFeedback.hh
nherment/gazebo
fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a
[ "ECL-2.0", "Apache-2.0" ]
5
2015-09-29T02:30:16.000Z
2022-03-30T12:11:22.000Z
/* * Copyright 2011 Nate Koenig & Andrew Howard * * 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. * */ /* Desc: Specification of a contact * Author: Nate Koenig * Date: 10 Nov 2009 */ #ifndef JOINTFEEDBACK_HH #define JOINTFEEDBACK_HH #include "math/Vector3.hh" namespace gazebo { namespace physics { /// \addtogroup gazebo_physics /// \{ /// \brief Feedback information from a joint class JointFeedback { /// \brief Operator = public: JointFeedback &operator =(const JointFeedback &f) { this->body1Force = f.body1Force; this->body2Force = f.body2Force; this->body1Torque = f.body1Torque; this->body2Torque = f.body2Torque; return *this; } public: math::Vector3 body1Force; public: math::Vector3 body2Force; public: math::Vector3 body1Torque; public: math::Vector3 body2Torque; }; /// \} } } #endif
25.372881
75
0.645291
nherment
9e5a23f8dff7b1550221b4624d554fa2a046fab9
400
cpp
C++
test/unit/math/prim/prob/bernoulli_ccdf_log_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
1
2020-06-14T14:33:37.000Z
2020-06-14T14:33:37.000Z
test/unit/math/prim/prob/bernoulli_ccdf_log_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
2
2019-07-23T12:45:30.000Z
2020-05-01T20:43:03.000Z
test/unit/math/prim/prob/bernoulli_ccdf_log_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
1
2020-05-10T12:55:07.000Z
2020-05-10T12:55:07.000Z
#include <stan/math/prim.hpp> #include <gtest/gtest.h> TEST(ProbBernoulli, ccdf_log_matches_lccdf) { int n = 1; double theta = 0.3; EXPECT_FLOAT_EQ((stan::math::bernoulli_lccdf(n, theta)), (stan::math::bernoulli_ccdf_log(n, theta))); EXPECT_FLOAT_EQ((stan::math::bernoulli_lccdf<double>(n, theta)), (stan::math::bernoulli_ccdf_log<double>(n, theta))); }
30.769231
70
0.6525
LaudateCorpus1
9e5a44e311b394c612d80c73766e978ebcbf9759
5,009
hpp
C++
Linux/Ubuntu/64bit/AVAPI/Avapi/TECHNICAL_INDICATOR/AROONOSC.hpp
AvapiDotNet/AvapiCpp
2157ccbe750cac077098a6f1aa401d80fc943ff5
[ "MIT" ]
15
2018-01-31T16:58:36.000Z
2021-08-19T21:37:08.000Z
Linux/Ubuntu/64bit/AVAPI/Avapi/TECHNICAL_INDICATOR/AROONOSC.hpp
AvapiDotNet/AvapiCpp
2157ccbe750cac077098a6f1aa401d80fc943ff5
[ "MIT" ]
null
null
null
Linux/Ubuntu/64bit/AVAPI/Avapi/TECHNICAL_INDICATOR/AROONOSC.hpp
AvapiDotNet/AvapiCpp
2157ccbe750cac077098a6f1aa401d80fc943ff5
[ "MIT" ]
4
2018-01-31T17:06:26.000Z
2020-05-03T20:59:27.000Z
#ifndef AROONOSC_HPP_INCLUDED #define AROONOSC_HPP_INCLUDED #include <string> #include <map> #include <list> #include "../jsmn/jsmn.h" using namespace std; namespace Avapi { class RestClient; //forward declaration enum class Const_AROONOSC_interval{ none, n_1min, n_5min, n_15min, n_30min, n_60min, daily, weekly, monthly, }; class MAP_AROONOSC { public: static const map<Const_AROONOSC_interval, string> s_interval_translation; }; class MetaData_Type_AROONOSC { private: string Symbol; string Indicator; string LastRefreshed; string Interval; string TimePeriod; string TimeZone; public: MetaData_Type_AROONOSC(); MetaData_Type_AROONOSC(const MetaData_Type_AROONOSC& other); // copy constructor string get_Symbol() const {return Symbol;}; string get_Indicator() const {return Indicator;}; string get_LastRefreshed() const {return LastRefreshed;}; string get_Interval() const {return Interval;}; string get_TimePeriod() const {return TimePeriod;}; string get_TimeZone() const {return TimeZone;}; void set_Symbol(string Symbol){this->Symbol = Symbol;}; void set_Indicator(string Indicator){this->Indicator = Indicator;}; void set_LastRefreshed(string LastRefreshed){this->LastRefreshed = LastRefreshed;}; void set_Interval(string Interval){this->Interval = Interval;}; void set_TimePeriod(string TimePeriod){this->TimePeriod = TimePeriod;}; void set_TimeZone(string TimeZone){this->TimeZone = TimeZone;}; int ParseInternal(string& str_data, jsmntok_t* array_token ,int index, int token_size); }; class TechnicalIndicator_Type_AROONOSC { private: string AROONOSC; string DateTime; public: TechnicalIndicator_Type_AROONOSC(); TechnicalIndicator_Type_AROONOSC(const TechnicalIndicator_Type_AROONOSC& other); // copy constructor string get_AROONOSC() const {return AROONOSC;}; string get_DateTime() const {return DateTime;}; void set_AROONOSC(string AROONOSC){this->AROONOSC = AROONOSC;}; void set_DateTime(string DateTime){this->DateTime = DateTime;}; int ParseInternal(string& str_data, jsmntok_t* array_token, int index, int token_size); }; class AvapiResponse_AROONOSC_Content { private: MetaData_Type_AROONOSC MetaData; list<TechnicalIndicator_Type_AROONOSC> TechnicalIndicator; string str_prefix; bool error_status; string ErrorMessage; public: AvapiResponse_AROONOSC_Content(); ~AvapiResponse_AROONOSC_Content() {}; AvapiResponse_AROONOSC_Content(const AvapiResponse_AROONOSC_Content& other); // copy constructor MetaData_Type_AROONOSC& get_MetaData() {return MetaData;}; list<TechnicalIndicator_Type_AROONOSC>& get_TechnicalIndicator() {return TechnicalIndicator;}; void set_Error(bool error_status) {this->error_status = error_status;}; bool isError() {return error_status;}; string get_ErrorMessage() {return ErrorMessage;}; void set_ErrorMessage(string ErrorMessage) {this->ErrorMessage = str_prefix + ErrorMessage;}; }; class AvapiResponse_AROONOSC { private: string LastHttpRequest; string RawData; AvapiResponse_AROONOSC_Content* Data; public: AvapiResponse_AROONOSC(); AvapiResponse_AROONOSC(const AvapiResponse_AROONOSC& other); // copy constructor AvapiResponse_AROONOSC(AvapiResponse_AROONOSC&& other); // move constructor AvapiResponse_AROONOSC& operator=(const AvapiResponse_AROONOSC& other); //copy assignment AvapiResponse_AROONOSC& operator=(AvapiResponse_AROONOSC&& other); //move assignment ~AvapiResponse_AROONOSC(); AvapiResponse_AROONOSC_Content& get_Data() const {return *Data;}; string get_LastHttpRequest() const {return LastHttpRequest;}; string get_RawData() const {return RawData;}; void set_LastHttpRequest(string LastHttpRequest){this->LastHttpRequest = LastHttpRequest;}; void set_RawData(string RawData){this->RawData = RawData;}; }; class Impl_AROONOSC { private: string AvapiUrl; string ApiKey; RestClient *Client; static string s_function; static Impl_AROONOSC *s_instance; Impl_AROONOSC() {}; static const unsigned int START_TOKEN_SIZE = 3000; static void ParseInternal(AvapiResponse_AROONOSC& Response); public: static Impl_AROONOSC& getInstance(); static void destroyInstance(); string get_AvapiUrl() const {return AvapiUrl;}; RestClient* get_Client() const {return Client;}; string get_ApiKey() const {return ApiKey;}; void set_AvapiUrl(string AvapiUrl){this->AvapiUrl = AvapiUrl;}; void set_Client(RestClient *Client){this->Client = Client;}; void set_ApiKey(string ApiKey){this->ApiKey = ApiKey;}; AvapiResponse_AROONOSC Query(string symbol ,Const_AROONOSC_interval interval ,string time_period ); AvapiResponse_AROONOSC Query(string symbol ,string interval ,string time_period ); }; }//end namespace Avapi #endif // AROONOSC_HPP_INCLUDED
31.111801
104
0.743262
AvapiDotNet
9e5d618715c325995cc920febbce9c21e04c9062
2,489
cpp
C++
code/tests/glx/src/main.cpp
BrightComposite/RaptureStateToolkit
6eb3c831540ba6a9d29e903dd3c537aac2e7f91f
[ "MIT" ]
null
null
null
code/tests/glx/src/main.cpp
BrightComposite/RaptureStateToolkit
6eb3c831540ba6a9d29e903dd3c537aac2e7f91f
[ "MIT" ]
null
null
null
code/tests/glx/src/main.cpp
BrightComposite/RaptureStateToolkit
6eb3c831540ba6a9d29e903dd3c537aac2e7f91f
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- #include <application/starter.h> //--------------------------------------------------------------------------- #include <X11/X.h> #include <X11/Xlib.h> #include <GL/gl.h> #include <GL/glx.h> #include <GL/glu.h> #include <iostream> //--------------------------------------------------------------------------- namespace asd { void DrawAQuad() { glClearColor(1.0, 1.0, 1.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-1., 1., -1., 1., 1., 20.); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0., 0., 10., 0., 0., 0., 0., 1., 0.); glBegin(GL_QUADS); glColor3f(1.f, 0.f, 0.f); glVertex3f(-.75f, -.75f, 0.f); glColor3f(0.f, 1.f, 0.f); glVertex3f(.75f, -.75f, 0.f); glColor3f(0.f, 0.f, 1.f); glVertex3f(.75f, .75f, 0.f); glColor3f(1.f, 1.f, 0.f); glVertex3f(-.75f, .75f, 0.f); glEnd(); } static entrance open([]() { using namespace std; auto d = XOpenDisplay(NULL); if(d == nullptr) { cout << "Cannot connect to X server" << endl; return 1; } GLint att[] = {GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None}; auto vi = glXChooseVisual(d, 0, att); if(vi == NULL) { cout << "No appropriate visual found" << endl; return 1; } auto root = DefaultRootWindow(d); XSetWindowAttributes swa; swa.colormap = XCreateColormap(d, root, vi->visual, AllocNone); swa.event_mask = ExposureMask | KeyPressMask; auto w = XCreateWindow(d, root, 0, 0, 600, 600, 0, vi->depth, InputOutput, vi->visual, CWColormap | CWEventMask, &swa); XMapWindow(d, w); XStoreName(d, w, "ASD: glxtest"); auto glc = glXCreateContext(d, vi, NULL, GL_TRUE); glXMakeCurrent(d, w, glc); glEnable(GL_DEPTH_TEST); XWindowAttributes gwa; XEvent xev; cout << "Press ESC to exit" << endl; while(1) { XNextEvent(d, &xev); if(xev.type == Expose) { XGetWindowAttributes(d, w, &gwa); glViewport(0, 0, gwa.width, gwa.height); DrawAQuad(); glXSwapBuffers(d, w); } else if(xev.type == KeyPress) { if(xev.xkey.keycode == 9) { cout << "Exit..." << endl; glXMakeCurrent(d, None, NULL); glXDestroyContext(d, glc); XDestroyWindow(d, w); XCloseDisplay(d); break; } } } return 0; }); } //---------------------------------------------------------------------------
23.261682
121
0.527923
BrightComposite
9e5fed5b8db9931f8f0dca8131debee4179261a1
5,253
cpp
C++
tests/chain_tests/plugins/tags/get_posts_and_comments_tests.cpp
scorum/scorum
1da00651f2fa14bcf8292da34e1cbee06250ae78
[ "MIT" ]
53
2017-10-28T22:10:35.000Z
2022-02-18T02:20:48.000Z
tests/chain_tests/plugins/tags/get_posts_and_comments_tests.cpp
Scorum/Scorum
fb4aa0b0960119b97828865d7a5b4d0409af7876
[ "MIT" ]
38
2017-11-25T09:06:51.000Z
2018-10-31T09:17:22.000Z
tests/chain_tests/plugins/tags/get_posts_and_comments_tests.cpp
Scorum/Scorum
fb4aa0b0960119b97828865d7a5b4d0409af7876
[ "MIT" ]
27
2018-01-08T19:43:35.000Z
2022-01-14T10:50:42.000Z
#include <scorum/tags/tags_api_objects.hpp> #include <boost/test/unit_test.hpp> #include "tags_common.hpp" using namespace scorum; using namespace scorum::tags::api; using namespace scorum::app; using namespace scorum::tags; BOOST_FIXTURE_TEST_SUITE(get_posts_and_comments_tests, database_fixture::tags_fixture) SCORUM_TEST_CASE(check_get_posts_and_comments_contract_negative) { discussion_query q; q.limit = 101; BOOST_REQUIRE_THROW(_api.get_posts_and_comments(q), fc::assert_exception); q.limit = 100; q.start_author = "x"; BOOST_REQUIRE_THROW(_api.get_posts_and_comments(q), fc::assert_exception); q.start_author.reset(); q.start_permlink = "x"; BOOST_REQUIRE_THROW(_api.get_posts_and_comments(q), fc::assert_exception); } SCORUM_TEST_CASE(check_get_posts_and_comments_contract_positive) { discussion_query q; q.limit = 100; BOOST_REQUIRE_NO_THROW(_api.get_posts_and_comments(q)); q.start_author = "alice"; q.start_permlink = "p"; BOOST_REQUIRE_NO_THROW(_api.get_posts_and_comments(q)); } SCORUM_TEST_CASE(check_both_posts_and_comments_returned) { discussion_query q; q.limit = 100; BOOST_REQUIRE_EQUAL(_api.get_posts_and_comments(q).size(), 0u); auto p = create_post(alice).in_block(); p.create_comment(bob).in_block(); BOOST_REQUIRE_EQUAL(_api.get_posts_and_comments(q).size(), 2u); } SCORUM_TEST_CASE(check_truncate_body) { auto p = create_post(alice).set_body("1234567").in_block(); auto c = p.create_comment(bob).set_body("abcdefgh").in_block(); discussion_query q; q.limit = 100; q.truncate_body = 5; auto discussions = _api.get_posts_and_comments(q); BOOST_REQUIRE_EQUAL(discussions.size(), 2u); #ifdef IS_LOW_MEM BOOST_CHECK_EQUAL(discussions[0].body, ""); BOOST_CHECK_EQUAL(discussions[1].body, ""); BOOST_CHECK_EQUAL(discussions[0].body_length, 0u); BOOST_CHECK_EQUAL(discussions[1].body_length, 0u); #else BOOST_CHECK_EQUAL(discussions[0].body, "12345"); BOOST_CHECK_EQUAL(discussions[1].body, "abcde"); BOOST_CHECK_EQUAL(discussions[0].body_length, 7u); BOOST_CHECK_EQUAL(discussions[1].body_length, 8u); #endif } SCORUM_TEST_CASE(check_limit) { auto p = create_post(alice).in_block(); auto c1 = p.create_comment(bob).in_block(); auto c2 = c1.create_comment(sam).in_block(); discussion_query q; q.limit = 2; auto discussions = _api.get_posts_and_comments(q); BOOST_REQUIRE_EQUAL(discussions.size(), 2u); BOOST_CHECK_EQUAL(discussions[0].permlink, p.permlink()); BOOST_CHECK_EQUAL(discussions[1].permlink, c1.permlink()); } SCORUM_TEST_CASE(check_same_author_comments) { auto p = create_post(alice).in_block_with_delay(); auto c1 = p.create_comment(alice).in_block_with_delay(); c1.create_comment(alice).in_block_with_delay(); discussion_query q; q.limit = 100; auto discussions = _api.get_posts_and_comments(q); BOOST_REQUIRE_EQUAL(discussions.size(), 3u); } SCORUM_TEST_CASE(check_pagination) { /* * Heirarchy: * * alice/p1 * --bob/c1 * ----sam/c2 * ----alice/c3 * sam/p2 * --alice/c4 * --bob/c5 * * 'by_permlink' index will be sorted as follows: * 0. alice/c3 * 1. alice/c4 * 2. alice/p1 * 3. bob/c1 * 4. bob/c5 * 5. sam/c2 * 6. sam/p2 */ auto p1 = create_post(alice).set_permlink("p1").in_block_with_delay(); auto c1 = p1.create_comment(bob).set_permlink("c1").in_block_with_delay(); auto c2 = c1.create_comment(sam).set_permlink("c2").in_block_with_delay(); auto c3 = c1.create_comment(alice).set_permlink("c3").in_block_with_delay(); auto p2 = create_post(sam).set_permlink("p2").in_block_with_delay(); auto c4 = p2.create_comment(alice).set_permlink("c4").in_block_with_delay(); auto c5 = p2.create_comment(bob).set_permlink("c5").in_block_with_delay(); discussion_query q; q.limit = 4; { auto discussions = _api.get_posts_and_comments(q); BOOST_REQUIRE_EQUAL(discussions.size(), 4u); BOOST_CHECK_EQUAL(discussions[0].permlink, c3.permlink()); BOOST_CHECK_EQUAL(discussions[1].permlink, c4.permlink()); BOOST_CHECK_EQUAL(discussions[2].permlink, p1.permlink()); BOOST_CHECK_EQUAL(discussions[3].permlink, c1.permlink()); } { q.start_author = p1.author(); q.start_permlink = p1.permlink(); q.limit = 3u; auto discussions = _api.get_posts_and_comments(q); BOOST_REQUIRE_EQUAL(discussions.size(), 3u); BOOST_CHECK_EQUAL(discussions[0].permlink, p1.permlink()); BOOST_CHECK_EQUAL(discussions[1].permlink, c1.permlink()); BOOST_CHECK_EQUAL(discussions[2].permlink, c5.permlink()); } { q.start_author = c5.author(); q.start_permlink = c5.permlink(); q.limit = 4u; auto discussions = _api.get_posts_and_comments(q); BOOST_REQUIRE_EQUAL(discussions.size(), 3u); BOOST_CHECK_EQUAL(discussions[0].permlink, c5.permlink()); BOOST_CHECK_EQUAL(discussions[1].permlink, c2.permlink()); BOOST_CHECK_EQUAL(discussions[2].permlink, p2.permlink()); } } BOOST_AUTO_TEST_SUITE_END()
31.08284
86
0.695031
scorum
9e618b77758ee753e3d33f0beaf5ff8aa3b9b031
614
cpp
C++
esp32/examples/ttgo_demo/main/system.cpp
joachimBurket/esp32-opencv
f485b59d7b43b0a2f77a5ab547e2597929f7094a
[ "BSD-3-Clause" ]
56
2020-03-24T15:17:56.000Z
2022-03-21T13:44:08.000Z
esp32/examples/ttgo_demo/main/system.cpp
0015/esp32-opencv
f485b59d7b43b0a2f77a5ab547e2597929f7094a
[ "BSD-3-Clause" ]
6
2021-03-08T13:41:24.000Z
2022-02-19T08:10:24.000Z
esp32/examples/ttgo_demo/main/system.cpp
0015/esp32-opencv
f485b59d7b43b0a2f77a5ab547e2597929f7094a
[ "BSD-3-Clause" ]
15
2020-05-06T13:41:20.000Z
2022-03-31T19:15:47.000Z
#include <esp_log.h> #include <esp_system.h> #include <sdkconfig.h> #include <freertos/FreeRTOS.h> #include <freertos/task.h> #include <sys/param.h> #include <esp32/clk.h> #include "system.h" #define TAG "SYSTEM" void wait_msec(uint16_t v) { vTaskDelay(v / portTICK_PERIOD_MS); } void wait_sec(uint16_t v) { vTaskDelay(v * 1000 / portTICK_PERIOD_MS); } void disp_infos() { /* Print memory information */ ESP_LOGI(TAG, "task %s stack high watermark: %d Bytes", pcTaskGetTaskName(NULL), uxTaskGetStackHighWaterMark(NULL)); ESP_LOGI(TAG, "heap left: %d Bytes", esp_get_free_heap_size()); }
21.928571
120
0.708469
joachimBurket
9e622fd05f2006fc419715ae76d2647f62cbab3c
1,907
hpp
C++
include/vheis/geodesic-growth.hpp
alexbishop/Virtually-Abelian
4f19bf39e664a6ae51ef0c7f011e2fede7762d0c
[ "MIT" ]
null
null
null
include/vheis/geodesic-growth.hpp
alexbishop/Virtually-Abelian
4f19bf39e664a6ae51ef0c7f011e2fede7762d0c
[ "MIT" ]
null
null
null
include/vheis/geodesic-growth.hpp
alexbishop/Virtually-Abelian
4f19bf39e664a6ae51ef0c7f011e2fede7762d0c
[ "MIT" ]
null
null
null
#pragma once #include <map> #include <utility> #include <vector> #include "SafeInt.hpp" namespace vheis { template <class Group> class geodesic_growth { public: template <class Vector> explicit geodesic_growth(Vector g_set); template <class Iterator> explicit geodesic_growth(Iterator begin, Iterator end); std::pair<SafeInt<int>, SafeInt<unsigned long long>> next(); private: SafeInt<int> current_size; SafeInt<unsigned long long> running_total; std::vector<Group> g_set; std::map<Group, SafeInt<unsigned long long>> sphere_0; std::map<Group, SafeInt<unsigned long long>> sphere_1; std::map<Group, SafeInt<unsigned long long>> sphere_2; }; }; // namespace vheis // Implementation namespace vheis { template <class Group> template <class Vector> geodesic_growth<Group>::geodesic_growth(Vector g_set) : geodesic_growth(g_set.begin(), g_set.end()) {} template <class Group> template <class Iterator> geodesic_growth<Group>::geodesic_growth(Iterator begin, Iterator end) : g_set(begin, end), running_total(0), current_size(-1) {} template <class Group> std::pair<SafeInt<int>, SafeInt<unsigned long long>> geodesic_growth<Group>::next() { if (current_size < 0) { Group identity; sphere_0[identity] = 1ull; current_size = 0; running_total = 1ull; return std::make_pair(current_size, running_total); } sphere_2 = std::move(sphere_1); sphere_1 = std::move(sphere_0); sphere_0 = std::map<Group, SafeInt<unsigned long long>>(); for (const auto& [element, count] : sphere_1) { for (auto& g : g_set) { const auto next_element = element * g; if (sphere_1.count(next_element) == 0 && sphere_2.count(next_element) == 0) { sphere_0[next_element] += count; running_total += count; } } } ++current_size; return std::make_pair(current_size, running_total); } } // namespace vheis
23.54321
69
0.694284
alexbishop
9e6696f57287cb809f6261bae1f749e86b51c56f
484
cpp
C++
228. Summary Ranges/solution.cpp
zlsun/leetcode
438d0020a701d7aa6a82eee0e46e5b11305abfda
[ "MIT" ]
null
null
null
228. Summary Ranges/solution.cpp
zlsun/leetcode
438d0020a701d7aa6a82eee0e46e5b11305abfda
[ "MIT" ]
null
null
null
228. Summary Ranges/solution.cpp
zlsun/leetcode
438d0020a701d7aa6a82eee0e46e5b11305abfda
[ "MIT" ]
null
null
null
/** 228. Summary Ranges Given a sorted integer array without duplicates, return the summary of its ranges. For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. **/ #include <iostream> #include "../utils.h" using namespace std; class Solution { public: vector<string> summaryRanges(vector<int>& nums) { } }; int main() { Solution s; return 0; }
19.36
99
0.667355
zlsun
9e67cbfbd174db0408f4e99477194e09d737b4f8
4,357
cpp
C++
ShopListManager/ShopPackage.cpp
0x4d696e68/InGameShop
405e01defb59bd1cf22a5a5d245fdf2475b1ca36
[ "MIT" ]
5
2021-08-31T19:18:24.000Z
2021-11-11T08:58:20.000Z
ShopListManager/ShopPackage.cpp
0x4d696e68/InGameShop
405e01defb59bd1cf22a5a5d245fdf2475b1ca36
[ "MIT" ]
null
null
null
ShopListManager/ShopPackage.cpp
0x4d696e68/InGameShop
405e01defb59bd1cf22a5a5d245fdf2475b1ca36
[ "MIT" ]
2
2021-08-31T18:39:50.000Z
2021-09-16T22:37:06.000Z
//************************************************************************ // // Decompiled by @myheart, @synth3r // <https://forum.ragezone.com/members/2000236254.html> // // // FILE: ShopPackage.cpp // // #include "stdafx.h" #if(DECOMPILE_INGAMESHOP==1) #include "ShopPackage.h" #include "StringToken.h" #include "StringMethod.h" CShopPackage::CShopPackage() // OK { this->LeftCount = -1; this->ProductSeqList.clear(); this->PriceSeqList.clear(); } CShopPackage::~CShopPackage() // OK { } bool CShopPackage::SetPackage(std::string strdata) // OK { if(strdata.empty()) return 0; CStringToken token(strdata,"@"); if(token.hasMoreTokens()==0) return 0; this->ProductDisplaySeq = atoi(token.nextToken().c_str()); this->ViewOrder = atoi(token.nextToken().c_str()); this->PackageProductSeq = atoi(token.nextToken().c_str()); StringCchCopy(this->PackageProductName,sizeof(this->PackageProductName),token.nextToken().c_str()); this->PackageProductType = atoi(token.nextToken().c_str()); this->Price = atoi(token.nextToken().c_str()); StringCchCopy(this->Description,sizeof(this->Description),token.nextToken().c_str()); StringCchCopy(this->Caution,sizeof(this->Caution),token.nextToken().c_str()); this->SalesFlag = atoi(token.nextToken().c_str()); this->GiftFlag = atoi(token.nextToken().c_str()); CStringMethod::ConvertStringToDateTime(this->StartDate,token.nextToken()); CStringMethod::ConvertStringToDateTime(this->EndDate,token.nextToken()); this->CapsuleFlag = atoi(token.nextToken().c_str()); this->CapsuleCount = atoi(token.nextToken().c_str()); StringCchCopy(this->ProductCashName,sizeof(this->ProductCashName),token.nextToken().c_str()); StringCchCopy(this->PricUnitName,sizeof(this->PricUnitName),token.nextToken().c_str()); this->DeleteFlag = atoi(token.nextToken().c_str()); this->EventFlag = atoi(token.nextToken().c_str()); this->ProductAmount = atoi(token.nextToken().c_str()); this->SetProductSeqList(token.nextToken()); StringCchCopy(this->InGamePackageID,sizeof(this->InGamePackageID),token.nextToken().c_str()); this->ProductCashSeq = atoi(token.nextToken().c_str()); this->PriceCount = atoi(token.nextToken().c_str()); this->SetPriceSeqList(token.nextToken()); this->DeductMileageFlag = atoi(token.nextToken().c_str())!=0; this->CashType = atoi(token.nextToken().c_str()); this->CashTypeFlag = atoi(token.nextToken().c_str()); return 1; } void CShopPackage::SetLeftCount(int nCount) // OK { this->LeftCount = nCount; } int CShopPackage::GetProductCount() // OK { return static_cast<int>(this->ProductSeqList.size()); } void CShopPackage::SetProductSeqFirst() // OK { this->ProductSeqIter = this->ProductSeqList.begin(); } bool CShopPackage::GetProductSeqFirst(int& ProductSeq) // OK { this->ProductSeqIter = this->ProductSeqList.begin(); if(this->ProductSeqIter==this->ProductSeqList.end()) return 0; ProductSeq = (*this->ProductSeqIter); this->ProductSeqIter++; return 1; } bool CShopPackage::GetProductSeqNext(int& ProductSeq) // OK { if(this->ProductSeqIter==this->ProductSeqList.end()) return 0; ProductSeq = (*this->ProductSeqIter); this->ProductSeqIter++; return 1; } int CShopPackage::GetPriceCount() { return static_cast<int>(this->PriceSeqList.size()); } void CShopPackage::SetPriceSeqFirst() { this->PriceSeqIter = this->PriceSeqList.begin(); } bool CShopPackage::GetPriceSeqFirst(int& PriceSeq) // OK { this->PriceSeqIter = this->PriceSeqList.begin(); if(this->PriceSeqIter==this->PriceSeqList.end()) return 0; PriceSeq = (*this->PriceSeqIter); this->PriceSeqIter++; return 1; } bool CShopPackage::GetPriceSeqNext(int& PriceSeq) // OK { if(this->PriceSeqIter==this->PriceSeqList.end()) return 0; PriceSeq = (*this->PriceSeqIter); this->PriceSeqIter++; return 1; } void CShopPackage::SetProductSeqList(std::string strdata) // OK { CStringToken token(strdata,"|"); while(true) { if(token.hasMoreTokens()==0) break; std::string data = token.nextToken(); if(data.empty()) break; this->ProductSeqList.push_back(atoi(data.c_str())); } } void CShopPackage::SetPriceSeqList(std::string strdata) // OK { CStringToken token(strdata,"|"); while(true) { if(token.hasMoreTokens()==0) break; std::string data = token.nextToken(); if(data.empty()) break; this->PriceSeqList.push_back(atoi(data.c_str())); } } #endif
25.934524
100
0.706679
0x4d696e68
9e67f3cc68150c8beadda59b2c30b05adaf5e682
761
cpp
C++
Jeu/Src/ComponentsManagement/ProjectileSystem/Projectiles/Fireball.cpp
abastienIIT/Roguelike
f31935e45c968fbe608e57d0137d71251d1afc10
[ "Apache-2.0" ]
2
2021-02-07T16:07:10.000Z
2021-02-07T23:18:43.000Z
Jeu/Src/ComponentsManagement/ProjectileSystem/Projectiles/Fireball.cpp
abastienIIT/Roguelike
f31935e45c968fbe608e57d0137d71251d1afc10
[ "Apache-2.0" ]
49
2021-02-06T19:08:07.000Z
2021-09-14T16:43:27.000Z
Jeu/Src/ComponentsManagement/ProjectileSystem/Projectiles/Fireball.cpp
abastienIIT/Roguelike
f31935e45c968fbe608e57d0137d71251d1afc10
[ "Apache-2.0" ]
null
null
null
#include "Fireball.h" #include "../../Components.h" #include "../../../Common/Globalbilboulga.h" void Fireball::init(Entity* projectile, std::vector<Entity*>* targets) { ProjectileBase::init(projectile, targets); transform->velocity = velocity; sprite->setAsset("Fireball"); sprite->setCurrentTexture(0); collider->tag = "Fireball"; collider->setCollider(SDL_Rect({ 0,0,32,32 })); } void Fireball::update() { distance += velocity.x; if (distance > range || distance < range * -1 || transform->position.x < 0 || transform->position.y < 0 || transform->position.x > Globalbilboulga::getInstance()->getCurrentRoomSize().x || transform->position.y > Globalbilboulga::getInstance()->getCurrentRoomSize().y) { projectile->destroy(); } }
23.060606
83
0.683311
abastienIIT
9e69f8a3a3c40561449fcf2c1b6021ca3b2f5dca
5,954
cc
C++
src/c++/apps/echo/httpops.cc
isaac-ped/demikernel
6f372569e3599d8bf9083df6c25490c42af74c0d
[ "MIT" ]
null
null
null
src/c++/apps/echo/httpops.cc
isaac-ped/demikernel
6f372569e3599d8bf9083df6c25490c42af74c0d
[ "MIT" ]
null
null
null
src/c++/apps/echo/httpops.cc
isaac-ped/demikernel
6f372569e3599d8bf9083df6c25490c42af74c0d
[ "MIT" ]
null
null
null
#include <string.h> #include <stdio.h> #include <stdint.h> #include "httpops.hh" int regex_html(char *to_match, char *htmlDoc, size_t length) { const char *pcreErrorStr; int errOffset; pcre * reCompiled = pcre_compile(EVIL_REGEX, 0, &pcreErrorStr, &errOffset, NULL); if (reCompiled == NULL) { fprintf(stderr, "Error compiling regex"); } pcre_extra pcreExtra; pcreExtra.match_limit = -1; pcreExtra.match_limit_recursion = -1; pcreExtra.flags = PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION; int len = strlen(to_match); int x[1]; int ret = pcre_exec(reCompiled, &pcreExtra, to_match, len, 0, 0, x, 1); char resp[5]; if (ret < 0){ sprintf(resp, "%s", "NO"); } else { sprintf(resp, "%s", "YES"); } snprintf(htmlDoc, length, HTML, to_match, EVIL_REGEX, resp); pcre_free(reCompiled); return 0; } void replace_special(char *url) { for (u_int16_t i=0; i<strlen(url); i++) { if (url[i] == '%') { char hex[3]; hex[0] = url[i+1]; hex[1] = url[i+2]; hex[2] = '\0'; char sub = (char)strtol(hex, NULL, 16); url[i] = sub; for (u_int16_t j=i+1; j<strlen(url) - 1; j++) { url[j] = url[j+2]; } } } } int url_to_path(char *url, const char *dir, char *path, int capacity) { int len = 0; for (char *c=url; *c!='\0' && *c!='?'; c++, len++); int dir_len = strlen(dir); int dir_slash = (dir[dir_len - 1] == '/'); int url_slash = (url[0] == '/'); dir_len -= (dir_slash && url_slash); int both_missing_slash = (!dir_slash && !url_slash); if (dir_len + len + both_missing_slash >= capacity) { fprintf(stderr, "Path from url (%s) too large for buffer (%d)", url, capacity); return -1; } char *dest = path; strncpy(dest, dir, dir_len); if (both_missing_slash) { dest[dir_len] = '/'; } strncpy(&dest[dir_len + both_missing_slash], url, len + 1); dest[dir_len + both_missing_slash + len] = '\0'; replace_special(dest); return dir_len + len; } void path_to_mime_type(char *path, char buf[], int capacity) { char *extension = &path[strlen(path) - 1]; for (; extension != path && *extension != '.' && *extension != '/'; extension--); if (*extension != '.') strncpy(buf, DEFAULT_MIME_TYPE, capacity); extension++; // Advance past the dot // TODO: Necessary to replace this by loading /etc/mime.types into hashmap? if (strcasecmp(extension, "html") == 0 || strcasecmp(extension, "htm") == 0 || strcasecmp(extension, "txt") == 0) { strncpy(buf, "text/html", capacity); } else if (strcasecmp(extension, "png") == 0) { strncpy(buf, "image/png", capacity); } else if (strcasecmp(extension, "jpg") == 0 || strcasecmp(extension, "jpeg") == 0) { strncpy(buf, "image/jpeg", capacity); } else if (strcasecmp(extension, "gif") == 0) { strncpy(buf, "image/gif", capacity); } else { strncpy(buf, DEFAULT_MIME_TYPE, capacity); } } int generate_header(char **dest, int code, int body_len, char *mime_type) { if (code == 200) { char header_buf[MAX_HEADER_LEN]; size_t alloc_size = snprintf(header_buf, 0, BASE_HTTP_HEADER, code, mime_type, body_len) + 1; *dest = reinterpret_cast<char *>(malloc(alloc_size)); return snprintf(*dest, alloc_size, BASE_HTTP_HEADER, code, mime_type, body_len); } else if (code == 404) { size_t alloc_size = strlen(NOT_FOUND_HEADER) + 1; *dest = reinterpret_cast<char *>(malloc(alloc_size)); return snprintf(*dest, alloc_size, NOT_FOUND_HEADER); } else if (code == 501) { size_t alloc_size = strlen(INT_ERROR_HEADER) + 1; *dest = reinterpret_cast<char *>(malloc(alloc_size)); return snprintf(*dest, alloc_size, INT_ERROR_HEADER); } else { size_t alloc_size = strlen(NOT_IMPLEMENTED_HEADER) + 1; *dest = reinterpret_cast<char *>(malloc(alloc_size)); return snprintf(*dest, alloc_size, NOT_IMPLEMENTED_HEADER); } } int get_regex_value(char *url, char *regex) { char *regex_start = strstr(url, REGEX_KEY); if (regex_start == NULL) return -1; regex_start += strlen(REGEX_KEY); int start_i = (regex_start - url); for (int i=start_i; (i-start_i)<MAX_REGEX_VALUE_LEN; i++) { switch (url[i]) { case '?': case '&': case '\0': case ' ': strncpy(regex, &url[start_i], i - start_i); regex[i-start_i] = '\0'; return 0; default: continue; } } fprintf(stderr, "Requested regex value (%s) too long\n", regex_start); return -1; } enum http_req_type get_request_type(char *url) { if (strstr(url, REGEX_KEY) != NULL) { return REGEX_REQ; } return FILE_REQ; } void generate_response(char **response, char *header, char *body, int header_len, int body_len, int *response_len, uint32_t req_id) { *response = reinterpret_cast<char *>(malloc( (size_t) body_len + header_len + 2 + sizeof(uint32_t) )); memcpy(*response, (const int *) &req_id, sizeof(uint32_t)); *response_len = sizeof(uint32_t); *response_len += snprintf(*response + *response_len, header_len + 1, "%s", header); if (*response_len > (header_len + (int) sizeof(uint32_t))) { fprintf(stderr, "response_len > header_len: header was truncated!"); } if (body) { *response_len += snprintf(*response + *response_len, body_len + 1, "%s", body); free(body); } if (*response_len > (body_len + header_len + (int) sizeof(uint32_t))) { fprintf(stderr, "response_len > header_len+body_len: body was truncated!"); } free(header); }
33.638418
101
0.584649
isaac-ped
9e6b96d69508e8a7e4d2467a1b5af222443a5a6f
2,712
cpp
C++
tests/picross_shell/test_cross_command.cpp
deqyra/Picross-
0c81172faa8121c58bc2a88122d1cdbe661cc17e
[ "MIT" ]
null
null
null
tests/picross_shell/test_cross_command.cpp
deqyra/Picross-
0c81172faa8121c58bc2a88122d1cdbe661cc17e
[ "MIT" ]
1
2020-05-16T14:01:08.000Z
2020-06-11T21:12:02.000Z
tests/picross_shell/test_cross_command.cpp
deqyra/PicrossEngine
0c81172faa8121c58bc2a88122d1cdbe661cc17e
[ "MIT" ]
null
null
null
#include "../../lib/catch2/catch2.hpp" #include <sstream> #include "../../tools/cli/cli_streams.hpp" #include "../../tools/micro_shell/micro_shell_codes.hpp" #include "../../picross_shell/picross_shell_state.hpp" #include "../../picross_shell/shell_cross_command.hpp" #include "../../core/grid.hpp" #include "../../core/cell_t.hpp" #include "../../io/xml_grid_serializer.hpp" #define TAGS "[shell][shell_command]" namespace Picross { TEST_CASE("ShellCrossCommand end-to-end", TAGS) { std::stringstream ss; CLIStreams s = CLIStreams(ss, ss, ss); PicrossShellState state = PicrossShellState(); Grid g = Grid(10, 10); Grid modifiedG = g; state.mainGrid() = g; state.workingGrid() = modifiedG; ShellCrossCommand command = ShellCrossCommand(); SECTION("Bad arguments") { REQUIRE(command.processInput("cross aze", state, s) == SHELL_COMMAND_BAD_ARGUMENTS); REQUIRE(command.processInput("cross aze rty", state, s) == SHELL_COMMAND_BAD_ARGUMENTS); REQUIRE(command.processInput("cross 3 rty", state, s) == SHELL_COMMAND_BAD_ARGUMENTS); REQUIRE(state.mainGrid() == g); REQUIRE(state.workingGrid() == modifiedG); std::string expected = StringTools::readFileIntoString("resources/tests/picross_shell/cross_invalid_output.txt"); REQUIRE(ss.str() == expected); } SECTION("Cross single cell") { REQUIRE(command.processInput("cross 3 5", state, s) == SHELL_COMMAND_SUCCESS); modifiedG.crossCell(3, 5); } SECTION("Cross row or column range") { REQUIRE(command.processInput("cross 3 5:8", state, s) == SHELL_COMMAND_SUCCESS); REQUIRE(command.processInput("cross 1:4 2", state, s) == SHELL_COMMAND_SUCCESS); modifiedG.setCellRange(3, 3, 5, 8, CELL_CROSSED); modifiedG.setCellRange(1, 4, 2, 2, CELL_CROSSED); } SECTION("Cross row or column range (reversed ranges)") { REQUIRE(command.processInput("cross 3 8:5", state, s) == SHELL_COMMAND_SUCCESS); REQUIRE(command.processInput("cross 4:1 2", state, s) == SHELL_COMMAND_SUCCESS); modifiedG.setCellRange(3, 3, 5, 8, CELL_CROSSED); modifiedG.setCellRange(1, 4, 2, 2, CELL_CROSSED); } SECTION("Cross area range") { REQUIRE(command.processInput("cross 3:7 5:8", state, s) == SHELL_COMMAND_SUCCESS); modifiedG.setCellRange(3, 7, 5, 8, CELL_CROSSED); } REQUIRE(state.mainGrid() == g); REQUIRE(state.workingGrid() == modifiedG); } }
35.220779
125
0.614307
deqyra
9e6ea7609f559d3f5fa9d7c2b9f4b53b1c3d43e2
478
cpp
C++
layer2/ethernetHelper.cpp
zetwhite/SimpleEtherCATMaster
f17b04c96385d13e0cf1cdc664e4821058280273
[ "MIT" ]
2
2021-03-04T08:50:02.000Z
2021-04-05T14:59:57.000Z
layer2/ethernetHelper.cpp
zetwhite/SimpleEtherCATMaster
f17b04c96385d13e0cf1cdc664e4821058280273
[ "MIT" ]
null
null
null
layer2/ethernetHelper.cpp
zetwhite/SimpleEtherCATMaster
f17b04c96385d13e0cf1cdc664e4821058280273
[ "MIT" ]
null
null
null
#include "ethernetHelper.hpp" const int EthernetHelper::size = 14; EthernetHelper::EthernetHelper (uint8_t srcMac[6], uint8_t destMac[6], uint16_t type){ ptr = new struct ethhdr; memcpy(ptr->h_dest, destMac, 6); memcpy(ptr->h_source, srcMac, 6); ptr->h_proto = htons(type); } unsigned char* EthernetHelper::toArray(){ return reinterpret_cast<unsigned char*>(ptr); } void EthernetHelper::setType(uint16_t type){ ptr->h_proto = htons(type); }
26.555556
86
0.692469
zetwhite
9e70c3b369f80da0cad65b595b841c051f7251eb
41,980
cpp
C++
engine/navigation/navigation_manager.cpp
AugustoMoura/GritEnginePR
0f8303df7f70972036d9b555dffe08cadb473926
[ "MIT" ]
null
null
null
engine/navigation/navigation_manager.cpp
AugustoMoura/GritEnginePR
0f8303df7f70972036d9b555dffe08cadb473926
[ "MIT" ]
null
null
null
engine/navigation/navigation_manager.cpp
AugustoMoura/GritEnginePR
0f8303df7f70972036d9b555dffe08cadb473926
[ "MIT" ]
null
null
null
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // // This is a modified version of Sample_TempObstacles.cpp from Recast Demo #define _USE_MATH_DEFINES #include <math.h> #include <stdio.h> #include <string.h> #include <float.h> #include <new> #include "input_geom.h" #include "navigation_manager.h" #include "Recast.h" #include "RecastDebugDraw.h" #include "DetourAssert.h" #include "DetourNavMesh.h" #include "DetourNavMeshBuilder.h" #include "DetourDebugDraw.h" #include "DetourCommon.h" #include "DetourTileCache.h" #include "crowd_manager.h" #include "RecastAlloc.h" #include "RecastAssert.h" #include "fastlz.h" #include "DetourNavMeshQuery.h" #include "DetourCrowd.h" #ifdef WIN32 # define snprintf _snprintf #endif #include"navigation_system.h" // This value specifies how many layers (or "floors") each navmesh tile is expected to have. static const int EXPECTED_LAYERS_PER_TILE = 4; static bool isectSegAABB(const float* sp, const float* sq, const float* amin, const float* amax, float& tmin, float& tmax) { static const float EPS = 1e-6f; float d[3]; rcVsub(d, sq, sp); tmin = 0; // set to -FLT_MAX to get first hit on line tmax = FLT_MAX; // set to max distance ray can travel (for segment) // For all three slabs for (int i = 0; i < 3; i++) { if (fabsf(d[i]) < EPS) { // Ray is parallel to slab. No hit if origin not within slab if (sp[i] < amin[i] || sp[i] > amax[i]) return false; } else { // Compute intersection t value of ray with near and far plane of slab const float ood = 1.0f / d[i]; float t1 = (amin[i] - sp[i]) * ood; float t2 = (amax[i] - sp[i]) * ood; // Make t1 be intersection with near plane, t2 with far plane if (t1 > t2) rcSwap(t1, t2); // Compute the intersection of slab intersections intervals if (t1 > tmin) tmin = t1; if (t2 < tmax) tmax = t2; // Exit with no collision as soon as slab intersection becomes empty if (tmin > tmax) return false; } } return true; } static int calcLayerBufferSize(const int gridWidth, const int gridHeight) { const int headerSize = dtAlign4(sizeof(dtTileCacheLayerHeader)); const int gridSize = gridWidth * gridHeight; return headerSize + gridSize*4; } struct FastLZCompressor : public dtTileCacheCompressor { virtual int maxCompressedSize(const int bufferSize) { return (int)(bufferSize* 1.05f); } virtual dtStatus compress(const unsigned char* buffer, const int bufferSize, unsigned char* compressed, const int /*maxCompressedSize*/, int* compressedSize) { *compressedSize = fastlz_compress((const void *const)buffer, bufferSize, compressed); return DT_SUCCESS; } virtual dtStatus decompress(const unsigned char* compressed, const int compressedSize, unsigned char* buffer, const int maxBufferSize, int* bufferSize) { *bufferSize = fastlz_decompress(compressed, compressedSize, buffer, maxBufferSize); return *bufferSize < 0 ? DT_FAILURE : DT_SUCCESS; } }; struct LinearAllocator : public dtTileCacheAlloc { unsigned char* buffer; size_t capacity; size_t top; size_t high; LinearAllocator(const size_t cap) : buffer(0), capacity(0), top(0), high(0) { resize(cap); } ~LinearAllocator() { dtFree(buffer); } void resize(const size_t cap) { if (buffer) dtFree(buffer); buffer = (unsigned char*)dtAlloc(cap, DT_ALLOC_PERM); capacity = cap; } virtual void reset() { high = dtMax(high, top); top = 0; } virtual void* alloc(const size_t size) { if (!buffer) return 0; if (top+size > capacity) return 0; unsigned char* mem = &buffer[top]; top += size; return mem; } virtual void free(void* /*ptr*/) { // Empty } }; struct MeshProcess : public dtTileCacheMeshProcess { InputGeom* m_geom; inline MeshProcess() : m_geom(0) { } inline void init(InputGeom* geom) { m_geom = geom; } virtual void process(struct dtNavMeshCreateParams* params, unsigned char* polyAreas, unsigned short* polyFlags) { // Update poly flags from areas. for (int i = 0; i < params->polyCount; ++i) { if (polyAreas[i] == DT_TILECACHE_WALKABLE_AREA) polyAreas[i] = SAMPLE_POLYAREA_GROUND; if (polyAreas[i] == SAMPLE_POLYAREA_GROUND || polyAreas[i] == SAMPLE_POLYAREA_GRASS || polyAreas[i] == SAMPLE_POLYAREA_ROAD) { polyFlags[i] = SAMPLE_POLYFLAGS_WALK; } else if (polyAreas[i] == SAMPLE_POLYAREA_WATER) { polyFlags[i] = SAMPLE_POLYFLAGS_SWIM; } else if (polyAreas[i] == SAMPLE_POLYAREA_DOOR) { polyFlags[i] = SAMPLE_POLYFLAGS_WALK | SAMPLE_POLYFLAGS_DOOR; } } // Pass in off-mesh connections. if (m_geom) { params->offMeshConVerts = m_geom->getOffMeshConnectionVerts(); params->offMeshConRad = m_geom->getOffMeshConnectionRads(); params->offMeshConDir = m_geom->getOffMeshConnectionDirs(); params->offMeshConAreas = m_geom->getOffMeshConnectionAreas(); params->offMeshConFlags = m_geom->getOffMeshConnectionFlags(); params->offMeshConUserID = m_geom->getOffMeshConnectionId(); params->offMeshConCount = m_geom->getOffMeshConnectionCount(); } } }; static const int MAX_LAYERS = 32; struct TileCacheData { unsigned char* data; int dataSize; }; struct RasterizationContext { RasterizationContext() : solid(0), triareas(0), lset(0), chf(0), ntiles(0) { memset(tiles, 0, sizeof(TileCacheData)*MAX_LAYERS); } ~RasterizationContext() { rcFreeHeightField(solid); delete [] triareas; rcFreeHeightfieldLayerSet(lset); rcFreeCompactHeightfield(chf); for (int i = 0; i < MAX_LAYERS; ++i) { dtFree(tiles[i].data); tiles[i].data = 0; } } rcHeightfield* solid; unsigned char* triareas; rcHeightfieldLayerSet* lset; rcCompactHeightfield* chf; TileCacheData tiles[MAX_LAYERS]; int ntiles; }; static int rasterizeTileLayers(BuildContext* ctx, InputGeom* geom, const int tx, const int ty, const rcConfig& cfg, TileCacheData* tiles, const int maxTiles) { if (!geom || !geom->getMesh() || !geom->getChunkyMesh()) { ctx->log(RC_LOG_ERROR, "buildTile: Input mesh is not specified."); return 0; } FastLZCompressor comp; RasterizationContext rc; const float* verts = geom->getMesh()->getVerts(); const int nverts = geom->getMesh()->getVertCount(); const rcChunkyTriMesh* chunkyMesh = geom->getChunkyMesh(); // Tile bounds. const float tcs = cfg.tileSize * cfg.cs; rcConfig tcfg; memcpy(&tcfg, &cfg, sizeof(tcfg)); tcfg.bmin[0] = cfg.bmin[0] + tx*tcs; tcfg.bmin[1] = cfg.bmin[1]; tcfg.bmin[2] = cfg.bmin[2] + ty*tcs; tcfg.bmax[0] = cfg.bmin[0] + (tx+1)*tcs; tcfg.bmax[1] = cfg.bmax[1]; tcfg.bmax[2] = cfg.bmin[2] + (ty+1)*tcs; tcfg.bmin[0] -= tcfg.borderSize*tcfg.cs; tcfg.bmin[2] -= tcfg.borderSize*tcfg.cs; tcfg.bmax[0] += tcfg.borderSize*tcfg.cs; tcfg.bmax[2] += tcfg.borderSize*tcfg.cs; // Allocate voxel heightfield where we rasterize our input data to. rc.solid = rcAllocHeightfield(); if (!rc.solid) { ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'solid'."); return 0; } if (!rcCreateHeightfield(ctx, *rc.solid, tcfg.width, tcfg.height, tcfg.bmin, tcfg.bmax, tcfg.cs, tcfg.ch)) { ctx->log(RC_LOG_ERROR, "buildNavigation: Could not create solid heightfield."); return 0; } // Allocate array that can hold triangle flags. // If you have multiple meshes you need to process, allocate // and array which can hold the max number of triangles you need to process. rc.triareas = new unsigned char[chunkyMesh->maxTrisPerChunk]; if (!rc.triareas) { ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'm_triareas' (%d).", chunkyMesh->maxTrisPerChunk); return 0; } float tbmin[2], tbmax[2]; tbmin[0] = tcfg.bmin[0]; tbmin[1] = tcfg.bmin[2]; tbmax[0] = tcfg.bmax[0]; tbmax[1] = tcfg.bmax[2]; int cid[512];// TODO: Make grow when returning too many items. const int ncid = rcGetChunksOverlappingRect(chunkyMesh, tbmin, tbmax, cid, 512); if (!ncid) { return 0; // empty } for (int i = 0; i < ncid; ++i) { const rcChunkyTriMeshNode& node = chunkyMesh->nodes[cid[i]]; const int* tris = &chunkyMesh->tris[node.i*3]; const int ntris = node.n; memset(rc.triareas, 0, ntris*sizeof(unsigned char)); rcMarkWalkableTriangles(ctx, tcfg.walkableSlopeAngle, verts, nverts, tris, ntris, rc.triareas); if (!rcRasterizeTriangles(ctx, verts, nverts, tris, rc.triareas, ntris, *rc.solid, tcfg.walkableClimb)) return 0; } // Once all geometry is rasterized, we do initial pass of filtering to // remove unwanted overhangs caused by the conservative rasterization // as well as filter spans where the character cannot possibly stand. rcFilterLowHangingWalkableObstacles(ctx, tcfg.walkableClimb, *rc.solid); rcFilterLedgeSpans(ctx, tcfg.walkableHeight, tcfg.walkableClimb, *rc.solid); rcFilterWalkableLowHeightSpans(ctx, tcfg.walkableHeight, *rc.solid); rc.chf = rcAllocCompactHeightfield(); if (!rc.chf) { ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'chf'."); return 0; } if (!rcBuildCompactHeightfield(ctx, tcfg.walkableHeight, tcfg.walkableClimb, *rc.solid, *rc.chf)) { ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build compact data."); return 0; } // Erode the walkable area by agent radius. if (!rcErodeWalkableArea(ctx, tcfg.walkableRadius, *rc.chf)) { ctx->log(RC_LOG_ERROR, "buildNavigation: Could not erode."); return 0; } // (Optional) Mark areas. const ConvexVolume* vols = geom->getConvexVolumes(); for (int i = 0; i < geom->getConvexVolumeCount(); ++i) { rcMarkConvexPolyArea(ctx, vols[i].verts, vols[i].nverts, vols[i].hmin, vols[i].hmax, (unsigned char)vols[i].area, *rc.chf); } rc.lset = rcAllocHeightfieldLayerSet(); if (!rc.lset) { ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'lset'."); return 0; } if (!rcBuildHeightfieldLayers(ctx, *rc.chf, tcfg.borderSize, tcfg.walkableHeight, *rc.lset)) { ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build heighfield layers."); return 0; } rc.ntiles = 0; for (int i = 0; i < rcMin(rc.lset->nlayers, MAX_LAYERS); ++i) { TileCacheData* tile = &rc.tiles[rc.ntiles++]; const rcHeightfieldLayer* layer = &rc.lset->layers[i]; // Store header dtTileCacheLayerHeader header; header.magic = DT_TILECACHE_MAGIC; header.version = DT_TILECACHE_VERSION; // Tile layer location in the navmesh. header.tx = tx; header.ty = ty; header.tlayer = i; dtVcopy(header.bmin, layer->bmin); dtVcopy(header.bmax, layer->bmax); // Tile info. header.width = (unsigned char)layer->width; header.height = (unsigned char)layer->height; header.minx = (unsigned char)layer->minx; header.maxx = (unsigned char)layer->maxx; header.miny = (unsigned char)layer->miny; header.maxy = (unsigned char)layer->maxy; header.hmin = (unsigned short)layer->hmin; header.hmax = (unsigned short)layer->hmax; dtStatus status = dtBuildTileCacheLayer(&comp, &header, layer->heights, layer->areas, layer->cons, &tile->data, &tile->dataSize); if (dtStatusFailed(status)) { return 0; } } // Transfer ownsership of tile data from build context to the caller. int n = 0; for (int i = 0; i < rcMin(rc.ntiles, maxTiles); ++i) { tiles[n++] = rc.tiles[i]; rc.tiles[i].data = 0; rc.tiles[i].dataSize = 0; } return n; } void drawTiles(duDebugDraw* dd, dtTileCache* tc) { unsigned int fcol[6]; float bmin[3], bmax[3]; for (int i = 0; i < tc->getTileCount(); ++i) { const dtCompressedTile* tile = tc->getTile(i); if (!tile->header) continue; tc->calcTightTileBounds(tile->header, bmin, bmax); const unsigned int col = duIntToCol(i,64); duCalcBoxColors(fcol, col, col); duDebugDrawBox(dd, bmin[0],bmin[1],bmin[2], bmax[0],bmax[1],bmax[2], fcol); } for (int i = 0; i < tc->getTileCount(); ++i) { const dtCompressedTile* tile = tc->getTile(i); if (!tile->header) continue; tc->calcTightTileBounds(tile->header, bmin, bmax); const unsigned int col = duIntToCol(i,255); const float pad = tc->getParams()->cs * 0.1f; duDebugDrawBoxWire(dd, bmin[0]-pad,bmin[1]-pad,bmin[2]-pad, bmax[0]+pad,bmax[1]+pad,bmax[2]+pad, col, 2.0f); } } enum DrawDetailType { DRAWDETAIL_AREAS, DRAWDETAIL_REGIONS, DRAWDETAIL_CONTOURS, DRAWDETAIL_MESH, }; void drawDetail(duDebugDraw* dd, dtTileCache* tc, const int tx, const int ty, int type) { struct TileCacheBuildContext { inline TileCacheBuildContext(struct dtTileCacheAlloc* a) : layer(0), lcset(0), lmesh(0), alloc(a) {} inline ~TileCacheBuildContext() { purge(); } void purge() { dtFreeTileCacheLayer(alloc, layer); layer = 0; dtFreeTileCacheContourSet(alloc, lcset); lcset = 0; dtFreeTileCachePolyMesh(alloc, lmesh); lmesh = 0; } struct dtTileCacheLayer* layer; struct dtTileCacheContourSet* lcset; struct dtTileCachePolyMesh* lmesh; struct dtTileCacheAlloc* alloc; }; dtCompressedTileRef tiles[MAX_LAYERS]; const int ntiles = tc->getTilesAt(tx,ty,tiles,MAX_LAYERS); dtTileCacheAlloc* talloc = tc->getAlloc(); dtTileCacheCompressor* tcomp = tc->getCompressor(); const dtTileCacheParams* params = tc->getParams(); for (int i = 0; i < ntiles; ++i) { const dtCompressedTile* tile = tc->getTileByRef(tiles[i]); talloc->reset(); TileCacheBuildContext bc(talloc); const int walkableClimbVx = (int)(params->walkableClimb / params->ch); dtStatus status; // Decompress tile layer data. status = dtDecompressTileCacheLayer(talloc, tcomp, tile->data, tile->dataSize, &bc.layer); if (dtStatusFailed(status)) return; if (type == DRAWDETAIL_AREAS) { duDebugDrawTileCacheLayerAreas(dd, *bc.layer, params->cs, params->ch); continue; } // Build navmesh status = dtBuildTileCacheRegions(talloc, *bc.layer, walkableClimbVx); if (dtStatusFailed(status)) return; if (type == DRAWDETAIL_REGIONS) { duDebugDrawTileCacheLayerRegions(dd, *bc.layer, params->cs, params->ch); continue; } bc.lcset = dtAllocTileCacheContourSet(talloc); if (!bc.lcset) return; status = dtBuildTileCacheContours(talloc, *bc.layer, walkableClimbVx, params->maxSimplificationError, *bc.lcset); if (dtStatusFailed(status)) return; if (type == DRAWDETAIL_CONTOURS) { duDebugDrawTileCacheContours(dd, *bc.lcset, tile->header->bmin, params->cs, params->ch); continue; } bc.lmesh = dtAllocTileCachePolyMesh(talloc); if (!bc.lmesh) return; status = dtBuildTileCachePolyMesh(talloc, *bc.lcset, *bc.lmesh); if (dtStatusFailed(status)) return; if (type == DRAWDETAIL_MESH) { duDebugDrawTileCachePolyMesh(dd, *bc.lmesh, tile->header->bmin, params->cs, params->ch); continue; } } } void drawDetailOverlay(const dtTileCache* tc, const int tx, const int ty, double* proj, double* model, int* view) { dtCompressedTileRef tiles[MAX_LAYERS]; const int ntiles = tc->getTilesAt(tx,ty,tiles,MAX_LAYERS); if (!ntiles) return; (void) model; (void) view; (void) proj; //const int rawSize = calcLayerBufferSize(tc->getParams()->width, tc->getParams()->height); //char text[128]; for (int i = 0; i < ntiles; ++i) { const dtCompressedTile* tile = tc->getTileByRef(tiles[i]); float pos[3]; pos[0] = (tile->header->bmin[0]+tile->header->bmax[0])/2.0f; pos[1] = tile->header->bmin[1]; pos[2] = (tile->header->bmin[2]+tile->header->bmax[2])/2.0f; (void) pos; //-- TODO: replace this using Ogre "MoveableTextOverlay" //GLdouble x, y, z; //if (gluProject((GLdouble)pos[0], (GLdouble)pos[1], (GLdouble)pos[2], // model, proj, view, &x, &y, &z)) //{ // snprintf(text,128,"(%d,%d)/%d", tile->header->tx,tile->header->ty,tile->header->tlayer); // imguiDrawText((int)x, (int)y-25, IMGUI_ALIGN_CENTER, text, imguiRGBA(0,0,0,220)); // snprintf(text,128,"Compressed: %.1f kB", tile->dataSize/1024.0f); // imguiDrawText((int)x, (int)y-45, IMGUI_ALIGN_CENTER, text, imguiRGBA(0,0,0,128)); // snprintf(text,128,"Raw:%.1fkB", rawSize/1024.0f); // imguiDrawText((int)x, (int)y-65, IMGUI_ALIGN_CENTER, text, imguiRGBA(0,0,0,128)); //} } } dtObstacleRef hitTestObstacle(const dtTileCache* tc, const float* sp, const float* sq) { float tmin = FLT_MAX; const dtTileCacheObstacle* obmin = 0; for (int i = 0; i < tc->getObstacleCount(); ++i) { const dtTileCacheObstacle* ob = tc->getObstacle(i); if (ob->state == DT_OBSTACLE_EMPTY) continue; float bmin[3], bmax[3], t0,t1; tc->getObstacleBounds(ob, bmin,bmax); if (isectSegAABB(sp,sq, bmin,bmax, t0,t1)) { if (t0 < tmin) { tmin = t0; obmin = ob; } } } return tc->getObstacleRef(obmin); } void drawObstacles(duDebugDraw* dd, const dtTileCache* tc) { // Draw obstacles for (int i = 0; i < tc->getObstacleCount(); ++i) { const dtTileCacheObstacle* ob = tc->getObstacle(i); if (ob->state == DT_OBSTACLE_EMPTY) continue; float bmin[3], bmax[3]; tc->getObstacleBounds(ob, bmin,bmax); unsigned int col = 0; if (ob->state == DT_OBSTACLE_PROCESSING) col = duRGBA(255,255,0,128); else if (ob->state == DT_OBSTACLE_PROCESSED) col = duRGBA(255,192,0,192); else if (ob->state == DT_OBSTACLE_REMOVING) col = duRGBA(220,0,0,128); duDebugDrawCylinder(dd, bmin[0],bmin[1],bmin[2], bmax[0],bmax[1],bmax[2], col); duDebugDrawCylinderWire(dd, bmin[0],bmin[1],bmin[2], bmax[0],bmax[1],bmax[2], duDarkenCol(col), 2); } } NavigationManager::NavigationManager() : m_geom(nullptr), m_navMesh(nullptr), m_navMeshDrawFlags(DU_DRAWNAVMESH_OFFMESHCONS | DU_DRAWNAVMESH_CLOSEDLIST), m_ctx(nullptr), m_keepInterResults(false), m_tileCache(0), m_cacheBuildTimeMs(0), m_cacheCompressedSize(0), m_cacheRawSize(0), m_cacheLayerCount(0), m_cacheBuildMemUsage(0), m_drawMode(DRAWMODE_NAVMESH), m_maxTiles(0), m_maxPolysPerTile(0), m_tileSize(48) { m_navQuery = dtAllocNavMeshQuery(); m_crowd = dtAllocCrowd(); resetCommonSettings(); m_talloc = new LinearAllocator(32000); m_tcomp = new FastLZCompressor; m_tmproc = new MeshProcess; m_crowdTool = new CrowdTool(); } NavigationManager::~NavigationManager() { dtFreeNavMeshQuery(m_navQuery); dtFreeNavMesh(m_navMesh); dtFreeCrowd(m_crowd); m_navMesh = 0; dtFreeTileCache(m_tileCache); } void NavigationManager::updateMaxTiles() { if (m_geom) { const float* bmin = m_geom->getNavMeshBoundsMin(); const float* bmax = m_geom->getNavMeshBoundsMax(); // char text[64]; int gw = 0, gh = 0; rcCalcGridSize(bmin, bmax, m_cellSize, &gw, &gh); const int ts = (int)m_tileSize; const int tw = (gw + ts-1) / ts; const int th = (gh + ts-1) / ts; // Max tiles and max polys affect how the tile IDs are caculated. // There are 22 bits available for identifying a tile and a polygon. int tileBits = rcMin((int)dtIlog2(dtNextPow2(tw*th*EXPECTED_LAYERS_PER_TILE)), 14); if (tileBits > 14) tileBits = 14; int polyBits = 22 - tileBits; m_maxTiles = 1 << tileBits; m_maxPolysPerTile = 1 << polyBits; } else { m_maxTiles = 0; m_maxPolysPerTile = 0; } } // this is a modified function of Recast Debug Draw // removed tile bounds and points static void drawMeshTilex(duDebugDraw* dd, const dtNavMesh& mesh, const dtNavMeshQuery* query, const dtMeshTile* tile, unsigned char flags) { dtPolyRef base = mesh.getPolyRefBase(tile); int tileNum = mesh.decodePolyIdTile(base); dd->depthMask(false); dd->begin(DU_DRAW_TRIS); for (int i = 0; i < tile->header->polyCount; ++i) { const dtPoly* p = &tile->polys[i]; if (p->getType() == DT_POLYTYPE_OFFMESH_CONNECTION) // Skip off-mesh links. continue; const dtPolyDetail* pd = &tile->detailMeshes[i]; unsigned int col; if (query && query->isInClosedList(base | (dtPolyRef)i)) col = duRGBA(255, 196, 0, 64); else { if (flags & DU_DRAWNAVMESH_COLOR_TILES) { col = duIntToCol(tileNum, 128); } else { if (p->getArea() == 0) // Treat zero area type as default. col = duRGBA(0, 192, 255, 64); else col = duIntToCol(p->getArea(), 64); } } for (int j = 0; j < pd->triCount; ++j) { const unsigned char* t = &tile->detailTris[(pd->triBase + j) * 4]; for (int k = 0; k < 3; ++k) { if (t[k] < p->vertCount) dd->vertex(&tile->verts[p->verts[t[k]] * 3], col); else dd->vertex(&tile->detailVerts[(pd->vertBase + t[k] - p->vertCount) * 3], col); } } } dd->end(); if (flags & DU_DRAWNAVMESH_OFFMESHCONS) { dd->begin(DU_DRAW_LINES, 2.0f); for (int i = 0; i < tile->header->polyCount; ++i) { const dtPoly* p = &tile->polys[i]; if (p->getType() != DT_POLYTYPE_OFFMESH_CONNECTION) // Skip regular polys. continue; unsigned int col, col2; if (query && query->isInClosedList(base | (dtPolyRef)i)) col = duRGBA(255, 196, 0, 220); else col = duDarkenCol(duIntToCol(p->getArea(), 220)); const dtOffMeshConnection* con = &tile->offMeshCons[i - tile->header->offMeshBase]; const float* va = &tile->verts[p->verts[0] * 3]; const float* vb = &tile->verts[p->verts[1] * 3]; // Check to see if start and end end-points have links. bool startSet = false; bool endSet = false; for (unsigned int k = p->firstLink; k != DT_NULL_LINK; k = tile->links[k].next) { if (tile->links[k].edge == 0) startSet = true; if (tile->links[k].edge == 1) endSet = true; } // End points and their on-mesh locations. dd->vertex(va[0], va[1], va[2], col); dd->vertex(con->pos[0], con->pos[1], con->pos[2], col); col2 = startSet ? col : duRGBA(220, 32, 16, 196); duAppendCircle(dd, con->pos[0], con->pos[1] + 0.1f, con->pos[2], con->rad, col2); dd->vertex(vb[0], vb[1], vb[2], col); dd->vertex(con->pos[3], con->pos[4], con->pos[5], col); col2 = endSet ? col : duRGBA(220, 32, 16, 196); duAppendCircle(dd, con->pos[3], con->pos[4] + 0.1f, con->pos[5], con->rad, col2); // End point vertices. dd->vertex(con->pos[0], con->pos[1], con->pos[2], duRGBA(0, 48, 64, 196)); dd->vertex(con->pos[0], con->pos[1] + 0.2f, con->pos[2], duRGBA(0, 48, 64, 196)); dd->vertex(con->pos[3], con->pos[4], con->pos[5], duRGBA(0, 48, 64, 196)); dd->vertex(con->pos[3], con->pos[4] + 0.2f, con->pos[5], duRGBA(0, 48, 64, 196)); // Connection arc. duAppendArc(dd, con->pos[0], con->pos[1], con->pos[2], con->pos[3], con->pos[4], con->pos[5], 0.25f, (con->flags & 1) ? 0.6f : 0, 0.6f, col); } dd->end(); } dd->depthMask(true); } void duDebugDrawNavMeshx(duDebugDraw* dd, const dtNavMesh& mesh, unsigned char flags) { if (!dd) return; for (int i = 0; i < mesh.getMaxTiles(); ++i) { const dtMeshTile* tile = mesh.getTile(i); if (!tile->header) continue; drawMeshTilex(dd, mesh, 0, tile, flags); } } void NavigationManager::render() { // when loading from a navmesh file, no m_geom is loaded bool navmesh_from_disk = false; if (!m_geom || !m_geom->getMesh()) { navmesh_from_disk = true; //return; } DebugDrawGL dd; // const float texScale = 1.0f / (m_cellSize * 10.0f); if (!navmesh_from_disk) { if (m_drawMode != DRAWMODE_NAVMESH_TRANS && NavSysDebug::ShowOffmeshConnections && NavSysDebug::RedrawOffmeshConnections) { NavSysDebug::DebugObject = NavSysDebug::OffmeshConectionsObject; NavSysDebug::DebugObject->clear(); m_geom->drawOffMeshConnections(&dd); NavSysDebug::RedrawOffmeshConnections = false; } // Draw bounds const float* bmin = m_geom->getNavMeshBoundsMin(); const float* bmax = m_geom->getNavMeshBoundsMax(); if (NavSysDebug::ShowBounds && NavSysDebug::RedrawBounds) { NavSysDebug::DebugObject = NavSysDebug::BoundsObject; NavSysDebug::DebugObject->clear(); duDebugDrawBoxWire(&dd, bmin[0], bmin[1], bmin[2], bmax[0], bmax[1], bmax[2], duRGBA(255, 255, 255, 128), 1.0f); NavSysDebug::RedrawBounds = false; } if (NavSysDebug::ShowTilingGrid && NavSysDebug::RedrawTilingGrid) { // Tiling grid. int gw = 0, gh = 0; rcCalcGridSize(bmin, bmax, m_cellSize, &gw, &gh); const int tw = (gw + (int)m_tileSize - 1) / (int)m_tileSize; const int th = (gh + (int)m_tileSize - 1) / (int)m_tileSize; const float s = m_tileSize*m_cellSize; NavSysDebug::DebugObject = NavSysDebug::TilingGridObject; NavSysDebug::DebugObject->clear(); duDebugDrawGridXZ(&dd, bmin[0], bmin[1], bmin[2], tw, th, s, duRGBA(0, 0, 0, 64), 1.0f); } // TODO if (NavSysDebug::ShowConvexVolumes && NavSysDebug::RedrawConvexVolumes) { NavSysDebug::DebugObject = NavSysDebug::ConvexVolumeObjects; NavSysDebug::DebugObject->clear(); m_geom->drawConvexVolumes(&dd); // temporary convex volume drawConvexVolume(&dd); NavSysDebug::RedrawConvexVolumes = false; } m_crowdTool->render(); } //if (m_tileCache && m_drawMode == DRAWMODE_CACHE_BOUNDS) // drawTiles(&dd, m_tileCache); if (m_tileCache && NavSysDebug::ShowObstacles && NavSysDebug::RedrawObstacles) { NavSysDebug::DebugObject = NavSysDebug::ObstaclesObject; NavSysDebug::DebugObject->clear(); drawObstacles(&dd, m_tileCache); NavSysDebug::RedrawObstacles = false; } if (NavSysDebug::ShowNavmesh && NavSysDebug::RedrawNavmesh) { NavSysDebug::DebugObject = NavSysDebug::NavmeshObject; NavSysDebug::DebugObject->clear(); if (m_navMesh && m_navQuery && (m_drawMode == DRAWMODE_NAVMESH || m_drawMode == DRAWMODE_NAVMESH_TRANS || m_drawMode == DRAWMODE_NAVMESH_BVTREE || m_drawMode == DRAWMODE_NAVMESH_NODES || m_drawMode == DRAWMODE_NAVMESH_PORTALS || m_drawMode == DRAWMODE_NAVMESH_INVIS)) { if (m_drawMode != DRAWMODE_NAVMESH_INVIS) //--duDebugDrawNavMeshWithClosedList(&dd, *m_navMesh, *m_navQuery, m_navMeshDrawFlags|DU_DRAWNAVMESH_COLOR_TILES); //++ duDebugDrawNavMeshx(&dd, *m_navMesh, m_navMeshDrawFlags | DU_DRAWNAVMESH_COLOR_TILES); /* if (m_drawMode == DRAWMODE_NAVMESH_BVTREE) duDebugDrawNavMeshBVTree(&dd, *m_navMesh); if (m_drawMode == DRAWMODE_NAVMESH_PORTALS) duDebugDrawNavMeshPortals(&dd, *m_navMesh); if (m_drawMode == DRAWMODE_NAVMESH_NODES) duDebugDrawNavMeshNodes(&dd, *m_navQuery); */ //duDebugDrawNavMeshPolysWithFlags(&dd, *m_navMesh, SAMPLE_POLYFLAGS_DISABLED, duRGBA(0,0,0,128)); } NavSysDebug::RedrawNavmesh = false; } } void NavigationManager::renderCachedTile(const int tx, const int ty, const int type) { DebugDrawGL dd; if (m_tileCache) drawDetail(&dd,m_tileCache,tx,ty,type); } void NavigationManager::renderCachedTileOverlay(const int tx, const int ty, double* proj, double* model, int* view) { if (m_tileCache) drawDetailOverlay(m_tileCache, tx, ty, proj, model, view); } void NavigationManager::changeMesh(class InputGeom* geom) { m_geom = geom; dtFreeTileCache(m_tileCache); m_tileCache = 0; dtFreeNavMesh(m_navMesh); m_navMesh = 0; } void NavigationManager::addTempObstacle(const float* pos) { if (!m_tileCache) return; float p[3]; dtVcopy(p, pos); p[1] -= 0.5f; m_tileCache->addObstacle(p, 1.0f, 2.0f, 0); } void NavigationManager::removeTempObstacle(const float* sp, const float* sq) { if (!m_tileCache) return; dtObstacleRef ref = hitTestObstacle(m_tileCache, sp, sq); m_tileCache->removeObstacle(ref); } void NavigationManager::clearAllTempObstacles() { if (!m_tileCache) return; for (int i = 0; i < m_tileCache->getObstacleCount(); ++i) { const dtTileCacheObstacle* ob = m_tileCache->getObstacle(i); if (ob->state == DT_OBSTACLE_EMPTY) continue; m_tileCache->removeObstacle(m_tileCache->getObstacleRef(ob)); } } bool NavigationManager::build() { dtStatus status; if (!m_geom || !m_geom->getMesh()) { m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: No vertices and triangles."); return false; } m_tmproc->init(m_geom); // Init cache const float* bmin = m_geom->getNavMeshBoundsMin(); const float* bmax = m_geom->getNavMeshBoundsMax(); int gw = 0, gh = 0; rcCalcGridSize(bmin, bmax, m_cellSize, &gw, &gh); const int ts = (int)m_tileSize; const int tw = (gw + ts-1) / ts; const int th = (gh + ts-1) / ts; // Generation params. rcConfig cfg; memset(&cfg, 0, sizeof(cfg)); cfg.cs = m_cellSize; cfg.ch = m_cellHeight; cfg.walkableSlopeAngle = m_agentMaxSlope; cfg.walkableHeight = (int)ceilf(m_agentHeight / cfg.ch); cfg.walkableClimb = (int)floorf(m_agentMaxClimb / cfg.ch); cfg.walkableRadius = (int)ceilf(m_agentRadius / cfg.cs); cfg.maxEdgeLen = (int)(m_edgeMaxLen / m_cellSize); cfg.maxSimplificationError = m_edgeMaxError; cfg.minRegionArea = (int)rcSqr(m_regionMinSize); // Note: area = size*size cfg.mergeRegionArea = (int)rcSqr(m_regionMergeSize); // Note: area = size*size cfg.maxVertsPerPoly = (int)m_vertsPerPoly; cfg.tileSize = (int)m_tileSize; cfg.borderSize = cfg.walkableRadius + 3; // Reserve enough padding. cfg.width = cfg.tileSize + cfg.borderSize*2; cfg.height = cfg.tileSize + cfg.borderSize*2; cfg.detailSampleDist = m_detailSampleDist < 0.9f ? 0 : m_cellSize * m_detailSampleDist; cfg.detailSampleMaxError = m_cellHeight * m_detailSampleMaxError; rcVcopy(cfg.bmin, bmin); rcVcopy(cfg.bmax, bmax); // Tile cache params. dtTileCacheParams tcparams; memset(&tcparams, 0, sizeof(tcparams)); rcVcopy(tcparams.orig, bmin); tcparams.cs = m_cellSize; tcparams.ch = m_cellHeight; tcparams.width = (int)m_tileSize; tcparams.height = (int)m_tileSize; tcparams.walkableHeight = m_agentHeight; tcparams.walkableRadius = m_agentRadius; tcparams.walkableClimb = m_agentMaxClimb; tcparams.maxSimplificationError = m_edgeMaxError; tcparams.maxTiles = tw*th*EXPECTED_LAYERS_PER_TILE; tcparams.maxObstacles = 128; dtFreeTileCache(m_tileCache); m_tileCache = dtAllocTileCache(); if (!m_tileCache) { m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not allocate tile cache."); return false; } status = m_tileCache->init(&tcparams, m_talloc, m_tcomp, m_tmproc); if (dtStatusFailed(status)) { m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not init tile cache."); return false; } dtFreeNavMesh(m_navMesh); m_navMesh = dtAllocNavMesh(); if (!m_navMesh) { m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not allocate navmesh."); return false; } dtNavMeshParams params; memset(&params, 0, sizeof(params)); rcVcopy(params.orig, bmin); params.tileWidth = m_tileSize*m_cellSize; params.tileHeight = m_tileSize*m_cellSize; params.maxTiles = m_maxTiles; params.maxPolys = m_maxPolysPerTile; status = m_navMesh->init(&params); if (dtStatusFailed(status)) { m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not init navmesh."); return false; } status = m_navQuery->init(m_navMesh, 2048); if (dtStatusFailed(status)) { m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not init Detour navmesh query"); return false; } // Preprocess tiles. m_ctx->resetTimers(); m_cacheLayerCount = 0; m_cacheCompressedSize = 0; m_cacheRawSize = 0; for (int y = 0; y < th; ++y) { for (int x = 0; x < tw; ++x) { TileCacheData tiles[MAX_LAYERS]; memset(tiles, 0, sizeof(tiles)); int ntiles = rasterizeTileLayers(m_ctx, m_geom, x, y, cfg, tiles, MAX_LAYERS); for (int i = 0; i < ntiles; ++i) { TileCacheData* tile = &tiles[i]; status = m_tileCache->addTile(tile->data, tile->dataSize, DT_COMPRESSEDTILE_FREE_DATA, 0); if (dtStatusFailed(status)) { dtFree(tile->data); tile->data = 0; continue; } m_cacheLayerCount++; m_cacheCompressedSize += tile->dataSize; m_cacheRawSize += calcLayerBufferSize(tcparams.width, tcparams.height); } } } // Build initial meshes m_ctx->startTimer(RC_TIMER_TOTAL); for (int y = 0; y < th; ++y) for (int x = 0; x < tw; ++x) m_tileCache->buildNavMeshTilesAt(x,y, m_navMesh); m_ctx->stopTimer(RC_TIMER_TOTAL); m_cacheBuildTimeMs = m_ctx->getAccumulatedTime(RC_TIMER_TOTAL)/1000.0f; m_cacheBuildMemUsage = m_talloc->high; //-- /* const dtNavMesh* nav = m_navMesh; int navmeshMemUsage = 0; for (int i = 0; i < nav->getMaxTiles(); ++i) { const dtMeshTile* tile = nav->getTile(i); if (tile->header) navmeshMemUsage += tile->dataSize; } printf("navmeshMemUsage = %.1f kB", navmeshMemUsage/1024.0f); */ m_crowdTool->init(this); return true; } void NavigationManager::update(const float dt) { m_crowdTool->update(dt); if (!m_navMesh) return; if (!m_tileCache) return; m_tileCache->update(dt, m_navMesh); } void NavigationManager::getTilePos(const float* pos, int& tx, int& ty) { if (!m_geom) return; const float* bmin = m_geom->getNavMeshBoundsMin(); const float ts = m_tileSize*m_cellSize; tx = (int)((pos[0] - bmin[0]) / ts); ty = (int)((pos[2] - bmin[2]) / ts); } static const int TILECACHESET_MAGIC = 'T'<<24 | 'S'<<16 | 'E'<<8 | 'T'; //'TSET'; static const int TILECACHESET_VERSION = 1; struct TileCacheSetHeader { int magic; int version; int numTiles; dtNavMeshParams meshParams; dtTileCacheParams cacheParams; }; struct TileCacheTileHeader { dtCompressedTileRef tileRef; int dataSize; }; bool NavigationManager::saveAll(const char* path) { if (!m_tileCache) return false; FILE* fp = fopen(path, "wb"); if (!fp) return false; // Store header. TileCacheSetHeader header; header.magic = TILECACHESET_MAGIC; header.version = TILECACHESET_VERSION; header.numTiles = 0; for (int i = 0; i < m_tileCache->getTileCount(); ++i) { const dtCompressedTile* tile = m_tileCache->getTile(i); if (!tile || !tile->header || !tile->dataSize) continue; header.numTiles++; } memcpy(&header.cacheParams, m_tileCache->getParams(), sizeof(dtTileCacheParams)); memcpy(&header.meshParams, m_navMesh->getParams(), sizeof(dtNavMeshParams)); fwrite(&header, sizeof(TileCacheSetHeader), 1, fp); // Store tiles. for (int i = 0; i < m_tileCache->getTileCount(); ++i) { const dtCompressedTile* tile = m_tileCache->getTile(i); if (!tile || !tile->header || !tile->dataSize) continue; TileCacheTileHeader tileHeader; tileHeader.tileRef = m_tileCache->getTileRef(tile); tileHeader.dataSize = tile->dataSize; fwrite(&tileHeader, sizeof(tileHeader), 1, fp); fwrite(tile->data, tile->dataSize, 1, fp); } fclose(fp); return true; } bool NavigationManager::loadAll(const char* path) { FILE* fp = fopen(path, "rb"); if (!fp) return false; // Read header. TileCacheSetHeader header; size_t bytes = fread(&header, sizeof(TileCacheSetHeader), 1, fp); APP_ASSERT(bytes != sizeof(TileCacheSetHeader)); if (header.magic != TILECACHESET_MAGIC) { fclose(fp); return false; } if (header.version != TILECACHESET_VERSION) { fclose(fp); return false; } m_navMesh = dtAllocNavMesh(); if (!m_navMesh) { fclose(fp); return false; } dtStatus status = m_navMesh->init(&header.meshParams); if (dtStatusFailed(status)) { fclose(fp); return false; } m_tileCache = dtAllocTileCache(); if (!m_tileCache) { fclose(fp); return false; } status = m_tileCache->init(&header.cacheParams, m_talloc, m_tcomp, m_tmproc); if (dtStatusFailed(status)) { fclose(fp); return false; } // Read tiles. for (int i = 0; i < header.numTiles; ++i) { TileCacheTileHeader tileHeader; bytes = fread(&tileHeader, sizeof(tileHeader), 1, fp); APP_ASSERT(bytes != sizeof(tileHeader)); if (!tileHeader.tileRef || !tileHeader.dataSize) break; unsigned char* data = (unsigned char*)dtAlloc(tileHeader.dataSize, DT_ALLOC_PERM); if (!data) break; memset(data, 0, tileHeader.dataSize); bytes = fread(data, tileHeader.dataSize, 1, fp); APP_ASSERT((long long)(bytes) != tileHeader.dataSize); dtCompressedTileRef tile = 0; m_tileCache->addTile(data, tileHeader.dataSize, DT_COMPRESSEDTILE_FREE_DATA, &tile); if (tile) m_tileCache->buildNavMeshTile(tile, m_navMesh); } fclose(fp); return true; } void NavigationManager::resetCommonSettings() { m_cellSize = 0.3f; m_cellHeight = 0.2f; m_agentHeight = 2.0f; m_agentRadius = 0.6f; m_agentMaxClimb = 0.9f; m_agentMaxSlope = 45.0f; m_regionMinSize = 8; m_regionMergeSize = 20; m_edgeMaxLen = 12.0f; m_edgeMaxError = 1.3f; m_vertsPerPoly = 6.0f; m_detailSampleDist = 6.0f; m_detailSampleMaxError = 1.0f; m_partitionType = SAMPLE_PARTITION_WATERSHED; } const float* NavigationManager::getBoundsMin() { if (!m_geom) return 0; return m_geom->getNavMeshBoundsMin(); } const float* NavigationManager::getBoundsMax() { if (!m_geom) return 0; return m_geom->getNavMeshBoundsMax(); } void NavigationManager::step() { } bool NavigationManager::load(const char* path) { updateMaxTiles(); dtFreeNavMesh(m_navMesh); dtFreeTileCache(m_tileCache); bool result = loadAll(path); m_navQuery->init(m_navMesh, 2048); m_crowdTool->init(this); return result; } void NavigationManager::freeNavmesh() { dtFreeTileCache(m_tileCache); m_tileCache = 0; dtFreeNavMesh(m_navMesh); m_navMesh = 0; } // CONVEX VOLUMES: (from Convex Volume Tool) // Returns true if 'c' is left of line 'a'-'b'. inline bool left(const float* a, const float* b, const float* c) { const float u1 = b[0] - a[0]; const float v1 = b[2] - a[2]; const float u2 = c[0] - a[0]; const float v2 = c[2] - a[2]; return u1 * v2 - v1 * u2 < 0; } // Returns true if 'a' is more lower-left than 'b'. inline bool cmppt(const float* a, const float* b) { if (a[0] < b[0]) return true; if (a[0] > b[0]) return false; if (a[2] < b[2]) return true; if (a[2] > b[2]) return false; return false; } // Calculates convex hull on xz-plane of points on 'pts', // stores the indices of the resulting hull in 'out' and // returns number of points on hull. static int convexhull(const float* pts, int npts, int* out) { // Find lower-leftmost point. int hull = 0; for (int i = 1; i < npts; ++i) if (cmppt(&pts[i * 3], &pts[hull * 3])) hull = i; // Gift wrap hull. int endpt = 0; int i = 0; do { out[i++] = hull; endpt = 0; for (int j = 1; j < npts; ++j) if (hull == endpt || left(&pts[hull * 3], &pts[endpt * 3], &pts[j * 3])) endpt = j; hull = endpt; } while (endpt != out[0]); return i; } static int pointInPoly(int nvert, const float* verts, const float* p) { int i, j, c = 0; for (i = 0, j = nvert - 1; i < nvert; j = i++) { const float* vi = &verts[i * 3]; const float* vj = &verts[j * 3]; if (((vi[2] > p[2]) != (vj[2] > p[2])) && (p[0] < (vj[0] - vi[0]) * (p[2] - vi[2]) / (vj[2] - vi[2]) + vi[0])) c = !c; } return c; } void NavigationManager::removeConvexVolume(float* p) { if (!m_geom || !m_geom->getMesh()) { return; } int nearestIndex = -1; const ConvexVolume* vols = m_geom->getConvexVolumes(); for (int i = 0; i < m_geom->getConvexVolumeCount(); ++i) { if (pointInPoly(vols[i].nverts, vols[i].verts, p) && p[1] >= vols[i].hmin && p[1] <= vols[i].hmax) { nearestIndex = i; } } // If end point close enough, delete it. if (nearestIndex != -1) { m_geom->deleteConvexVolume(nearestIndex); } } void NavigationManager::createConvexVolume(float* p) { if (!m_geom || !m_geom->getMesh()) { return; } // If clicked on that last pt, create the shape. if (m_npts && rcVdistSqr(p, &m_pts[(m_npts - 1) * 3]) < rcSqr(0.2f)) { if (m_nhull > 2) { // Create shape. float verts[MAX_PTS * 3]; for (int i = 0; i < m_nhull; ++i) rcVcopy(&verts[i * 3], &m_pts[m_hull[i] * 3]); float minh = FLT_MAX, maxh = 0; for (int i = 0; i < m_nhull; ++i) minh = rcMin(minh, verts[i * 3 + 1]); minh -= m_boxDescent; maxh = minh + m_boxHeight; if (m_polyOffset > 0.01f) { float offset[MAX_PTS * 2 * 3]; int noffset = rcOffsetPoly(verts, m_nhull, m_polyOffset, offset, MAX_PTS * 2); if (noffset > 0) m_geom->addConvexVolume(offset, noffset, minh, maxh, (unsigned char)m_areaType); } else { m_geom->addConvexVolume(verts, m_nhull, minh, maxh, (unsigned char)m_areaType); } } m_npts = 0; m_nhull = 0; } else { // Add new point if (m_npts < MAX_PTS) { rcVcopy(&m_pts[m_npts * 3], p); m_npts++; // Update hull. if (m_npts > 1) m_nhull = convexhull(m_pts, m_npts, m_hull); else m_nhull = 0; } } } // Temporary convex volume void NavigationManager::drawConvexVolume(DebugDrawGL* dd) { // Find height extents of the shape. float minh = FLT_MAX, maxh = 0; for (int i = 0; i < m_npts; ++i) minh = rcMin(minh, m_pts[i * 3 + 1]); minh -= m_boxDescent; maxh = minh + m_boxHeight; dd->begin(DU_DRAW_POINTS, 4.0f); for (int i = 0; i < m_npts; ++i) { unsigned int col = duRGBA(255, 255, 255, 255); if (i == m_npts - 1) col = duRGBA(240, 32, 16, 255); dd->vertex(m_pts[i * 3 + 0], m_pts[i * 3 + 1] + 0.1f, m_pts[i * 3 + 2], col); } dd->end(); dd->begin(DU_DRAW_LINES, 2.0f); for (int i = 0, j = m_nhull - 1; i < m_nhull; j = i++) { const float* vi = &m_pts[m_hull[j] * 3]; const float* vj = &m_pts[m_hull[i] * 3]; dd->vertex(vj[0], minh, vj[2], duRGBA(255, 255, 255, 64)); dd->vertex(vi[0], minh, vi[2], duRGBA(255, 255, 255, 64)); dd->vertex(vj[0], maxh, vj[2], duRGBA(255, 255, 255, 64)); dd->vertex(vi[0], maxh, vi[2], duRGBA(255, 255, 255, 64)); dd->vertex(vj[0], minh, vj[2], duRGBA(255, 255, 255, 64)); dd->vertex(vj[0], maxh, vj[2], duRGBA(255, 255, 255, 64)); } dd->end(); }
26.910256
118
0.676941
AugustoMoura
9e716ed1b82e835dbbed3a6fa2d870d54d83a0f6
21,662
cpp
C++
src/ui/ui.cpp
EnthDev/dedicatedslave
d8c097082d9e1ae11740cd917a9e9d449be457d2
[ "MIT" ]
7
2018-03-05T02:58:13.000Z
2019-01-06T13:11:50.000Z
src/ui/ui.cpp
EnthDev/dedicatedslave
d8c097082d9e1ae11740cd917a9e9d449be457d2
[ "MIT" ]
3
2017-12-21T00:29:38.000Z
2019-04-24T01:05:12.000Z
src/ui/ui.cpp
EnthDev/dedicatedslave
d8c097082d9e1ae11740cd917a9e9d449be457d2
[ "MIT" ]
1
2019-03-07T11:41:55.000Z
2019-03-07T11:41:55.000Z
// Includes #include <QtWidgets> #include "ui.h" DedicatedSlaveUi::DedicatedSlaveUi(const QString &dir, QWidget *parent) : QWidget(parent), app_slcInstPos(new int[2]) { app_slcInstPos[0] = -1; parentWin = qobject_cast<QMainWindow*>(parent); if(parentWin != 0 ) { // After casting parent widget QMainWindow, need to check if is not null (Async) // Core qInfo() << "(CLASS)\tInitializing 'DedicatedSlaveApp' class..."; ds_app = new DedicatedSlaveApp(dir, this); qInfo() << "(CLASS)\t'DedicatedSlaveApp' initialized."; //QObject::connect(&ds_app, SIGNAL(signal_verifyComplete(int)), this); // Variables app_dir = dir; // Actions initActions(); qInfo() << "\tActions initialized."; // Main Components // Instance List ui_instanceTable = new QTableWidget; ui_instanceTable->setRowCount(0); ui_instanceTable->setColumnCount(3); QStringList header; header << "Name" << "Game" << "Status"; ui_instanceTable->setHorizontalHeaderLabels(header); connect(ui_instanceTable, SIGNAL(cellClicked(int,int)), this, SLOT(slot_instanceSelect(int, int))); // Text Edit ui_textEdit = new QTextEdit(this); ui_textEdit->setAlignment(Qt::AlignCenter); // Info Label ui_infoLabel = new QLabel(tr("<i>Welcome to DedicatedSlave, this is the information label</i>")); ui_infoLabel->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); ui_infoLabel->setAlignment(Qt::AlignCenter); // Options Dock dockOptions = new UiDockOptions("Instance Options", parentWin); // Filesystem Dock dockFileSystem = new UiDockFileSystem("Workspace File System", parentWin); qInfo() << "\tMain Components initialized."; // Toolbar QToolBar *fileToolBar = parentWin->addToolBar(tr("File Toolbar")); fileToolBar->addAction(actNewInst); fileToolBar->addAction(actRemoveInst); fileToolBar->addAction(actRunInst); fileToolBar->addAction(actVerifyInst); QToolBar *editToolBar = parentWin->addToolBar(tr("Edit Toolbar")); editToolBar->addAction(actUndo); qInfo() << "\tToolbar initialized."; // Menus initMenus(); qInfo() << "\tMenus initialized."; // Toggle View Menus menuView->addAction(dockOptions->toggleViewAction()); menuView->addAction(dockFileSystem->toggleViewAction()); menuView->addAction(fileToolBar->toggleViewAction()); menuView->addAction(editToolBar->toggleViewAction()); // Main QVBoxLayout *layout = new QVBoxLayout; QWidget *topFiller = new QWidget; topFiller->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); QWidget *bottomFiller = new QWidget; bottomFiller->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); layout->setMargin(5); layout->addWidget(topFiller); layout->addWidget(ui_textEdit); layout->addWidget(ui_instanceTable); layout->addWidget(ui_infoLabel); /* TODO: Causing segfault ** #0 0x00007ffff74c5040 in QLayout::addChildWidget(QWidget*) () from libQt5Widgets.so.5 ** #1 0x00007ffff74bcb8c in QBoxLayout::insertWidget(int, QWidget*, int, QFlags<Qt::AlignmentFlag>) () from libQt5Widgets.so.5 ** #2 0x000055555556fcf5 in DedicatedSlaveUi::DedicatedSlaveUi (this=0x555555861320, dir=..., parent=<optimized out>) at src/ui/ui.cpp:81 ** #3 0x0000555555566d82 in MainWindow::MainWindow (this=0x7fffffffd900, dir=..., parent=<optimized out>, flags=...) at src/ui/mainwindow.cpp:7 ** #4 0x000055555556639e in main (argc=<optimized out>, argv=<optimized out>) at src/ui/main.cpp:84 */ //layout->addWidget(ui_progressBar); layout->addWidget(bottomFiller); setLayout(layout); // Parent properties ui_progressBar = new QProgressBar(this); QLabel *a = new QLabel(this); parentWin->statusBar()->addPermanentWidget(ui_progressBar); parentWin->statusBar()->addPermanentWidget(a); ui_progressBar->setValue(75); parentWin->statusBar()->showMessage(tr("A context menu is available by right-clicking")); parentWin->addDockWidget(Qt::RightDockWidgetArea, dockOptions); parentWin->addDockWidget(Qt::RightDockWidgetArea, dockFileSystem); parentWin->setCentralWidget(this); qInfo() << "\tParent properties has been set."; // Populate updateModelInstTable(); updateEdit(); // ????? remove } } void DedicatedSlaveUi::contextMenuEvent(QContextMenuEvent *event){ this->getContextMenu()->exec(event->globalPos()); } QMenu* DedicatedSlaveUi::getContextMenu(){ QMenu *menu = new QMenu(this); menu->addAction(actCut); menu->addAction(actCopy); menu->addAction(actPaste); return menu; } void DedicatedSlaveUi::updateModelInstTable(){ while (ui_instanceTable->rowCount() > 0){ ui_instanceTable->removeRow(0); } QHashIterator<QString, GameInstance*> i = ds_app->listInst(); i.toFront(); while (i.hasNext()) { i.next(); if(!i.key().isEmpty()){ ui_instanceTable->insertRow(ui_instanceTable->rowCount()); QTableWidgetItem *item0 = new QTableWidgetItem(i.key()); QTableWidgetItem *item1 = new QTableWidgetItem(i.value()->getGameId()); QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(i.value()->getStatus())); ui_instanceTable->setItem(ui_instanceTable->rowCount()-1, 0, item0); ui_instanceTable->setItem(ui_instanceTable->rowCount()-1, 1, item1); ui_instanceTable->setItem(ui_instanceTable->rowCount()-1, 2, item2); } } } void DedicatedSlaveUi::updateProgressBar(int value){ ui_progressBar->setValue(value); } void DedicatedSlaveUi::resetProgressBar(){ ui_progressBar->reset(); } void DedicatedSlaveUi::updateEdit(){ ui_textEdit->clear(); QTextCursor cursor(ui_textEdit->textCursor()); cursor.movePosition(QTextCursor::Start); QTextFrame *topFrame = cursor.currentFrame(); QTextFrameFormat topFrameFormat = topFrame->frameFormat(); topFrameFormat.setPadding(16); topFrame->setFrameFormat(topFrameFormat); QTextCharFormat textFormat; QTextCharFormat boldFormat; boldFormat.setFontWeight(QFont::Bold); QTextCharFormat italicFormat; italicFormat.setFontItalic(true); QTextTableFormat tableFormat; tableFormat.setBorder(1); tableFormat.setCellPadding(16); tableFormat.setAlignment(Qt::AlignRight); cursor.insertTable(1, 1, tableFormat); cursor.insertText("The Firm", boldFormat); cursor.insertBlock(); cursor.insertText("321 City Street", textFormat); cursor.insertBlock(); cursor.insertText("Industry Park"); cursor.insertBlock(); cursor.insertText("Some Country"); cursor.setPosition(topFrame->lastPosition()); cursor.insertText(QDate::currentDate().toString("d MMMM yyyy"), textFormat); cursor.insertBlock(); cursor.insertBlock(); cursor.insertText("Dear ", textFormat); cursor.insertText("NAME", italicFormat); cursor.insertText(",", textFormat); for (int i = 0; i < 3; ++i) cursor.insertBlock(); cursor.insertText(tr("Yours sincerely,"), textFormat); for (int i = 0; i < 3; ++i) cursor.insertBlock(); cursor.insertText("The Boss", textFormat); cursor.insertBlock(); cursor.insertText("ADDRESS", italicFormat); updateEdit1("BLABLABLA 1"); updateEdit2("BLABLABLA 2"); } void DedicatedSlaveUi::updateEdit1(const QString &customer){ if (customer.isEmpty()) return; QStringList customerList = customer.split(", "); QTextDocument *document = ui_textEdit->document(); QTextCursor cursor = document->find("NAME"); if (!cursor.isNull()) { cursor.beginEditBlock(); cursor.insertText(customerList.at(0)); QTextCursor oldcursor = cursor; cursor = document->find("ADDRESS"); if (!cursor.isNull()) { for (int i = 1; i < customerList.size(); ++i) { cursor.insertBlock(); cursor.insertText(customerList.at(i)); } cursor.endEditBlock(); } else { oldcursor.endEditBlock(); } } } void DedicatedSlaveUi::updateEdit2(const QString &paragraph){ if (paragraph.isEmpty()) return; QTextDocument *document = ui_textEdit->document(); QTextCursor cursor = document->find(tr("Yours sincerely,")); if (cursor.isNull()) return; cursor.beginEditBlock(); cursor.movePosition(QTextCursor::PreviousBlock, QTextCursor::MoveAnchor, 2); cursor.insertBlock(); cursor.insertText(paragraph); cursor.insertBlock(); cursor.endEditBlock(); } void DedicatedSlaveUi::initActions(){ // https://specifications.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html // New Instance const QIcon newIcon = QIcon::fromTheme("list-add", QIcon(":/images/new.png")); actNewInst = new QAction(newIcon, tr("&New"), this); actNewInst->setShortcuts(QKeySequence::New); actNewInst->setStatusTip(tr("Add a new instance")); connect(actNewInst, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionNewInstDialog); // Remove Instance const QIcon removeIcon = QIcon::fromTheme("list-remove", QIcon(":/images/new.png")); actRemoveInst = new QAction(removeIcon, tr("&Remove"), this); actRemoveInst->setShortcuts(QKeySequence::New); actRemoveInst->setStatusTip(tr("Remove a new instance")); connect(actRemoveInst, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionRemoveInst); // Verify Instance const QIcon verifyIcon = QIcon::fromTheme("emblem-downloads", QIcon(":/images/new.png")); actVerifyInst = new QAction(verifyIcon, tr("&Verify"), this); actVerifyInst->setStatusTip(tr("Verify a instance")); connect(actVerifyInst, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionVerifyInst); // Run Instance const QIcon runIcon = QIcon::fromTheme("go-next", QIcon(":/images/new.png")); actRunInst = new QAction(runIcon, tr("&Run"), this); actRunInst->setStatusTip(tr("Run a new instance")); connect(actRunInst, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionRunInst); // Backup actBackupInst = new QAction(tr("&Backup"), this); actBackupInst->setStatusTip(tr("Backup the selected instance to disk")); connect(actBackupInst, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionBackup); // Restore actRestoreInst = new QAction(tr("&Restore"), this); actRestoreInst->setStatusTip(tr("Restore the selected instance to disk")); connect(actRestoreInst, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionRestore); // Exit/Close actExit = new QAction(tr("E&xit"), this); actExit->setShortcuts(QKeySequence::Quit); actExit->setStatusTip(tr("Exit the application")); connect(actExit, &QAction::triggered, this, &QWidget::close); // Undo const QIcon undoIcon = QIcon::fromTheme("edit-undo", QIcon(":/images/undo.png")); actUndo = new QAction(undoIcon, tr("&Undo"), this); actUndo->setShortcuts(QKeySequence::Undo); actUndo->setStatusTip(tr("Undo the last operation")); connect(actUndo, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionUndo); // Redo actRedo = new QAction(tr("&Redo"), this); actRedo->setShortcuts(QKeySequence::Redo); actRedo->setStatusTip(tr("Redo the last operation")); connect(actRedo, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionRedo); // Cut actCut = new QAction(tr("Cu&t"), this); actCut->setShortcuts(QKeySequence::Cut); actCut->setStatusTip(tr("Cut the current selection's contents to the clipboard")); connect(actCut, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionCut); // Copy actCopy = new QAction(tr("&Copy"), this); actCopy->setShortcuts(QKeySequence::Copy); actCopy->setStatusTip(tr("Copy the current selection's contents to the clipboard")); connect(actCopy, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionCopy); // Paste actPaste = new QAction(tr("&Paste"), this); actPaste->setShortcuts(QKeySequence::Paste); actPaste->setStatusTip(tr("Paste the clipboard's contents into the current selection")); connect(actPaste, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionPaste); // Options actOptions = new QAction(tr("&Options..."), this); QList<QKeySequence> optionsShortcuts; optionsShortcuts.append(QKeySequence(Qt::CTRL + Qt::Key_F)); optionsShortcuts.append(QKeySequence(Qt::CTRL + Qt::Key_P)); actOptions->setShortcuts(optionsShortcuts); actOptions->setStatusTip(tr("Open the config options dialog")); connect(actOptions, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionOptions); // Help actHelp = new QAction(tr("&Help"), this); actHelp->setStatusTip(tr("Getting started with DedicatedSlave")); connect(actHelp, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionHelp); // Check Updates actCheckUpdates = new QAction(tr("&Check Updates"), this); actCheckUpdates->setStatusTip(tr("Check if exists new updates")); connect(actCheckUpdates, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionCheckUpdates); // About actAbout = new QAction(tr("&About"), this); actAbout->setStatusTip(tr("Show the application's About box")); connect(actAbout, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionAbout); // About Qt actAboutQt = new QAction(tr("About &Qt"), this); actAboutQt->setStatusTip(tr("Show the Qt library's About box")); connect(actAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt); connect(actAboutQt, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionAboutQt); } /*! * \brief Function that initializate menus */ void DedicatedSlaveUi::initMenus(){ // File Menu // if(parentWin != 0) { //qDebug() << "\tQ_FUNC_INFO" << Q_FUNC_INFO; // qInfo() << "Q_FUNC_INFO:" << Q_FUNC_INFO; // QMenuBar *menu = parentWin->menuBar(); menuFile = parentWin->menuBar()->addMenu(tr("&File")); menuFile->addAction(actNewInst); menuFile->addAction(actRemoveInst); menuFile->addAction(actRunInst); menuFile->addAction(actVerifyInst); menuFile->addAction(actBackupInst); menuFile->addAction(actRestoreInst); menuFile->addSeparator(); menuFile->addAction(actExit); // Edit Menu menuEdit = parentWin->menuBar()->addMenu(tr("&Edit")); menuEdit->addAction(actUndo); menuEdit->addAction(actRedo); menuEdit->addSeparator(); menuEdit->addAction(actCut); menuEdit->addAction(actCopy); menuEdit->addAction(actPaste); menuEdit->addSeparator(); // View Menu menuView = parentWin->menuBar()->addMenu(tr("&View")); // Tools Menu menuTools = parentWin->menuBar()->addMenu(tr("&Tools")); menuTools->addSeparator(); menuTools->addAction(actOptions); // Help Menu menuHelp = parentWin->menuBar()->addMenu(tr("&Help")); menuHelp->addAction(actHelp); menuHelp->addAction(actCheckUpdates); menuHelp->addSeparator(); menuHelp->addAction(actAbout); menuHelp->addAction(actAboutQt); } void DedicatedSlaveUi::conn_actionHelp(){ QDesktopServices::openUrl(QUrl("https://enthdev.github.io/dedicatedslave/user-guide/gettingstarted/")); ui_infoLabel->setText(tr("Invoked <b>Help|Help</b>")); } void DedicatedSlaveUi::conn_actionCheckUpdates(){ ui_infoLabel->setText(tr("Invoked <b>Help|CheckUpdates</b>")); } void DedicatedSlaveUi::conn_actionAbout(){ ui_infoLabel->setText(tr("Invoked <b>Help|About</b>")); QMessageBox::about(this, tr("About Dedicated Slave"), tr("The <b>Dedicated Slave</b> is a cross platform desktop app " "tool to manage steam dedicated game servers with SteamCMD." "<p><a href='https://github.com/EnthDev/dedicatedslave'>Github Repository</a>" "<p><a href='https://enthdev.github.io/dedicatedslave/'>Website</a>" "<p><a href='https://enthdev.github.io/dedicatedslave/user-guide/gettingstarted/'>Website - Getting Started</a>")); } void DedicatedSlaveUi::conn_actionAboutQt(){ ui_infoLabel->setText(tr("Invoked <b>Help|About Qt</b>")); } void DedicatedSlaveUi::conn_actionVerifyInst(){ if(app_slcInstPos[0] != -1 && app_slcInstPos[1] != -1){ QString instName = ui_instanceTable->item(app_slcInstPos[0], 0)->text(); if(ds_app->hasInst(instName)){ ds_app->verifyInstProgress(ui_instanceTable->item(app_slcInstPos[0], 0)->text()); updateModelInstTable(); }else{ ui_infoLabel->setText(QString("Error: Instance '%1' does not exist").arg(instName)); } } } void DedicatedSlaveUi::conn_actionRunInst(){ if(app_slcInstPos[0] != -1 && app_slcInstPos[1] != -1){ QString instName = ui_instanceTable->item(app_slcInstPos[0], 0)->text(); if(ds_app->hasInst(instName)){ if(ds_app->hasReadyInst(instName)){ ds_app->runInst(instName); updateModelInstTable(); }else{ ui_infoLabel->setText(QString("Error: Instance '%1' is not ready to run").arg(instName)); } }else{ ui_infoLabel->setText(QString("Error: Instance '%1' does not exist").arg(instName)); } } } void DedicatedSlaveUi::conn_actionNewInstDialog(){ ui_newInstGroup = new QGroupBox; QLabel *labeltest = new QLabel(tr("Instance Game:")); // QRadioButton *radio = new QRadioButton(tr("Add Instance")); QVBoxLayout *vbox = new QVBoxLayout; QComboBox *comboGamesList = new QComboBox; connect(comboGamesList, SIGNAL(activated(int)), this, SLOT(slot_addInstanceCombo(int))); QPushButton *addButton = new QPushButton("OK"); connect(addButton, &QAbstractButton::clicked, this, &DedicatedSlaveUi::conn_actionNewInst); QLineEdit *instNameLineEdit = new QLineEdit; QLineEdit *instDirLineEdit = new QLineEdit("etcinstances"); connect(instNameLineEdit, SIGNAL(textEdited(QString)), this, SLOT(slot_addInstNameEdit(QString))); connect(instDirLineEdit, SIGNAL(textEdited(QString)), this, SLOT(slot_addInstDirEdit(QString))); // Unlike textChanged(), this signal is not emitted when the text is changed programmatically, for example, by calling setText(). comboGamesList->addItem("-"); comboGamesList->addItem("Counter-Strike: Global Offensive"); // 1 comboGamesList->addItem("Rust"); // 2 // vbox->addWidget(radio); vbox->addWidget(labeltest); vbox->addWidget(comboGamesList); vbox->addWidget(addButton); vbox->addWidget(instNameLineEdit); vbox->addWidget(instDirLineEdit); ui_newInstGroup->setLayout(vbox); ui_newInstGroup->show(); ui_infoLabel->setText(tr("Invoked <b>File|New</b>")); } void DedicatedSlaveUi::conn_actionRemoveInst(){ if(app_slcInstPos[0] != -1 && app_slcInstPos[1] != -1){ QMessageBox::StandardButton removeReply; removeReply = QMessageBox::question(this, "Remove Instace", QString("Do you really want to remove instance '%1'").arg(ui_instanceTable->item(app_slcInstPos[0], 0)->text()), QMessageBox::Yes|QMessageBox::No); if(removeReply == QMessageBox::Yes){ QMessageBox::StandardButton removeFileReply; removeFileReply = QMessageBox::question(this, "Remove Instace", "Do you want to remove all instance files?", QMessageBox::Yes|QMessageBox::No); if(removeFileReply == QMessageBox::Yes) ds_app->removeInst(ui_instanceTable->item(app_slcInstPos[0], 0)->text(), true); else ds_app->removeInst(ui_instanceTable->item(app_slcInstPos[0], 0)->text(), false); updateModelInstTable(); } } } void DedicatedSlaveUi::conn_actionNewInst(){ ui_newInstGroup->hide(); if(!app_newIntsName.isEmpty()){ if(!ds_app->hasInst(app_newIntsName)){ ds_app->addInst(app_newIntsName, app_newInstGame); updateModelInstTable(); app_newInstGame = ""; ui_infoLabel->setText(QString("Invoked New Instance <b>%1</b> (<b>%2</b>) - <b>%3</b>").arg(app_newIntsName).arg(ui_instanceTable->rowCount()-1).arg(app_newInstGame)); }else{ ui_infoLabel->setText(QString("Error: New Instance name already exist (<b>%1</b>)").arg(app_newIntsName)); } }else{ ui_infoLabel->setText("Error: New Instance name cannot be empty."); } } void DedicatedSlaveUi::conn_actionRestore(){ ui_infoLabel->setText(tr("Invoked <b>File|Restore</b>")); } void DedicatedSlaveUi::conn_actionBackup(){ ui_infoLabel->setText(tr("Invoked <b>File|Save</b>")); QMimeDatabase mimeDatabase; QString fileName = QFileDialog::getSaveFileName(this, tr("Choose a file name"), ".", mimeDatabase.mimeTypeForName("text/html").filterString()); if (fileName.isEmpty()) return; QFile file(fileName); if (!file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(this, tr("Dock Widgets"), tr("Cannot write file %1:\n%2.") .arg(QDir::toNativeSeparators(fileName), file.errorString())); return; } QTextStream out(&file); QApplication::setOverrideCursor(Qt::WaitCursor); out << ui_textEdit->toHtml(); QApplication::restoreOverrideCursor(); parentWin->statusBar()->showMessage(tr("Saved '%1'").arg(fileName), 2000); } void DedicatedSlaveUi::conn_actionUndo(){ ui_infoLabel->setText(tr("Invoked <b>Edit|Undo</b>")); ui_textEdit->document()->undo(); } void DedicatedSlaveUi::conn_actionRedo(){ ui_infoLabel->setText(tr("Invoked <b>Edit|Redo</b>")); } void DedicatedSlaveUi::conn_actionCut(){ ui_infoLabel->setText(tr("Invoked <b>Edit|Cut</b>")); } void DedicatedSlaveUi::conn_actionCopy(){ ui_infoLabel->setText(tr("Invoked <b>Edit|Copy</b>")); } void DedicatedSlaveUi::conn_actionPaste(){ ui_infoLabel->setText(tr("Invoked <b>Edit|Paste</b>")); } void DedicatedSlaveUi::conn_actionOptions(){ ui_infoLabel->setText(tr("Invoked <b>Tools|Options...</b>")); ui_dialogConfig = new ConfigDialog(ds_app); ui_dialogConfig->show(); } void DedicatedSlaveUi::slot_addInstanceCombo(int index){ switch (index) { case 1: app_newInstGame = "csgo"; break; case 2: app_newInstGame = "rust"; break; } } void DedicatedSlaveUi::slot_addInstNameEdit(QString instanceName){ app_newIntsName = instanceName; } void DedicatedSlaveUi::slot_addInstDirEdit(QString instanceDir){ app_newInstDir = instanceDir; } void DedicatedSlaveUi::slot_instanceSelect(int row, int column){ app_slcInstPos[0] = row; app_slcInstPos[1] = column; QHashIterator<QString, GameInstance*> i = ds_app->listInst(); while(i.hasNext()){ i.next(); if(i.key() == ui_instanceTable->item(app_slcInstPos[0], 0)->text()){ GameInstance *gi = i.value(); dockOptions->updateModelInst(i.key(), gi->getServerName(), gi->getNumPlayers()); } } ui_infoLabel->setText(QString("Selected Inst <b>%1</b>:<b>%2</b>").arg(row).arg(column)); }
36.591216
170
0.728188
EnthDev
9e72f674499a8b8ec62adb88341d59099f91252e
8,949
cpp
C++
SimSpark/rcssserver3d/plugin/soccer/hmdp_effector/hmdpeffector.cpp
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
SimSpark/rcssserver3d/plugin/soccer/hmdp_effector/hmdpeffector.cpp
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
SimSpark/rcssserver3d/plugin/soccer/hmdp_effector/hmdpeffector.cpp
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*- this file is part of rcssserver3D Copyright (C) 2002,2003 Koblenz University Copyright (C) 2003 RoboCup Soccer Server 3D Maintenance Group Copyright (C) 2008 N. Michael Mayer, email: nmmayer@gmail.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "hmdpeffector.h" #include "hmdpperceptor.h" #include "hmdpaction.h" #include <zeitgeist/logserver/logserver.h> #include <oxygen/gamecontrolserver/actionobject.h> #include <oxygen/agentaspect/jointeffector.h> #include <oxygen/physicsserver/hingejoint.h> using namespace boost; using namespace oxygen; using namespace salt; using namespace HMDP; //! Handler for HMDP Effector and Perceptor back and forward HMDPPerceptor *hmdpPerceptorHandle = NULL; HMDPEffector *hmdpEffectorHandle = NULL; namespace HMDP { extern "C" { using namespace HMDP; int lock; extern Hmdl *hmdl; extern Base_data *base_data; extern int readChar; void disableIRQ(); //! mimicks IRQ functionality void enableIRQ(); } } HMDPEffector::HMDPEffector(): oxygen::Effector() { ifActive = false; } HMDPEffector::~HMDPEffector() { HMDP::lock = 0; } void HMDPEffector::PrePhysicsUpdateInternal(float deltaTime) { if (iter == 0) { ReadOutJointList(); InitHMDP(); } iter++; if (!ifActive) GetLog()->Normal() << "MAIN LOOP NOT ACTIVE THOUGH!!!" << std::endl; mainLoop(); if (mAction.get() == 0 || mBody.get() == 0) { return; } boost::shared_ptr<HMDPAction> hMDPAction = dynamic_pointer_cast<HMDPAction>(mAction); mAction.reset(); if (hMDPAction.get() == 0) { GetLog()->Error() << "ERROR: (HMDPEffector) cannot realize an unknown ActionObject\n"; return; } } boost::shared_ptr<ActionObject> HMDPEffector::GetActionObject(const Predicate& predicate) { //std::cout << " GetActionObject called " << std::endl; if (predicate.name != GetPredicate()) { GetLog()->Error() << "ERROR: (HMDPEffector) invalid predicate" << predicate.name << "\n"; return boost::shared_ptr<ActionObject>(); } std::string message; if (!predicate.GetValue(predicate.begin(), message)) { GetLog()->Error() << "ERROR: (HMDPEffector) Some Problem while receiving the HMDP Message\n"; return boost::shared_ptr<ActionObject>(); }; inMessage = inMessage + message + "\r\n"; //std::cout << inMessage << std::endl; return boost::shared_ptr<ActionObject>(new HMDPAction(GetPredicate(), inMessage)); } void HMDPEffector::OnLink() { hmdpEffectorHandle = this; perceptor = hmdpPerceptorHandle; std::cout << "Perceptor points to " << perceptor << std::endl; std::cout << "in OnLink " << std::endl; ifActive = true; iter = 0; // just to do the right things on iter = 0 in pre physics routine boost::shared_ptr<Node> parent = GetParent().lock(); if (parent.get() == 0) { GetLog()->Error() << "ERROR: (HMDPEffector) parent node is not derived from BaseNode\n"; return; } // parent should be a transform, or some other node, which has a // Body-child mBody = dynamic_pointer_cast<RigidBody>(parent->GetChildOfClass("RigidBody")); if (mBody.get() == 0) { GetLog()->Error() << "ERROR: (HMDPEffector) parent node has no Body child;" "cannot apply HMDP\n"; return; } inMessage = ""; //! initialize the incoming messages stored in this string } void HMDPEffector::OnUnlink() { mBody.reset(); HMDP::lock = 0; ifActive = false; } /**************************************************************************************************** SPECIAL HMDP RELATED METHODS of the Effecotr Class ****************************************************************************************************/ float HMDPEffector::zeroPosServo(int id) //! this is to define a standard position for HMDP ( some kind of standing straight with arms diagonal down ) { return nao.zeroPosition(id); //! NAO related function inside the plugin } //! it is important for the parser to go the beginning of the new line -- no matter if the p void HMDPEffector::searchForNextLinestartInMessage() { int state = 0; while (state < 3) { char a = inMessage[0]; if ((a == 13) && (state == 0)) state = 1; if (((a != 13) || (a != 10)) && (state == 1)) state = 2; inMessage = inMessage.substr(1, inMessage.size() - 1); if (state == 2) state = 3; } } void HMDPEffector::sendMessage(std::string message) { //std::cout << "message in effector "<< message << std::endl; perceptor->sendMessage(message); // goes into perceptor part -- this is the only part where the perceptor is needed } void HMDPEffector::ReadOutJointList() { boost::shared_ptr<Node> parent = GetParent().lock(); boost::shared_ptr<Node> grandparent = parent->GetParent().lock(); grandparent->ListChildrenSupportingClass<HingeJoint>(jointList, true); // This vectors describe the state of each joint and thus there need to be an entry for each joint servo_target_pos.resize(jointList.size()); servo_gain.resize(jointList.size()); servo_angle.resize(jointList.size()); int i = 0; for (TLeafList::iterator j_it = jointList.begin(); j_it != jointList.end(); j_it++) { // set all to yzero (necessary ?) servo_target_pos[i] = 0.; servo_gain[i] = 0.05; servo_angle[i] = 0; boost::shared_ptr<Leaf> join = *j_it; boost::shared_ptr<BaseNode> jparent = dynamic_pointer_cast<BaseNode>(join->GetParent().lock()); std::cout << i << " " << jparent->GetName() << std::endl; i++; } } bool HMDPEffector::checkIfServoIDExists(int ID) //! checks if a joint with ID ID exists { if ((ID >= 0) && (ID < jointList.size())) return true; return false; } void HMDPEffector::mainLoop() // HMDP update method { prepareUsage(); int watchdog = 0; hmdpEffectorHandle = this; // just to make sure you have the right one set -- in the case of several agents while ((inMessage.size() > 0) && (watchdog < 100)) { watchdog++; inMessage = inMessage; //if (inMessage.size()>10) std::cout << "GOT LARGE MESS " << this << std::endl; HMDP::parse_one_line(); // HMDP parser reads one line in one call } HMDP::lock = 0; if (ifIRQ) HMDP::inter_routine_base(); // real time functionality (!) now in the loop controlPosServo(); // servo update loop } void HMDPEffector::controlPosServo() // for controlling servos { int i = 0; for (TLeafList::iterator j_it = jointList.begin(); j_it != jointList.end(); j_it++) { boost::shared_ptr<HingeJoint> joint = static_pointer_cast<HingeJoint> (*j_it); servo_angle[i] = joint->GetAngle() - zeroPosServo(i); double tpos = servo_target_pos[i]; float err = servo_gain[i] * (tpos - servo_angle[i]); joint->SetParameter(2 /*dParamVel*/, err); if (abs(err) > 0.00001) { boost::shared_ptr<RigidBody> body = joint->GetBody(Joint::BI_FIRST); if (body && !body->IsEnabled()) { body->Enable(); } } i++; } } void HMDPEffector::prepareUsage() { while (lock) { //std::cout <<" waiting in lock "<<std::endl; }; hmdl = &local_hmdl; base_data = &local_base; lock = 1; } void HMDPEffector::InitHMDP() //! startup of HMDP { prepareUsage(); HMDP::init_base(); //! boot the base part HMDP::init_hmdl(); //! boot the hmdp part HMDP::enableIRQ(); /* start the IRQ */ for (int i = 0; i < 64; i++) { local_base.zero_pos_inits_feed[i] = 32* 64 ; if (checkIfServoIDExists(i)) { std::cout << nao.getJointName(i) << std::endl; for (int j=0; j<6;j++) HMDP::jointnames[i][j] = nao.getJointName(i).c_str()[j]; HMDP::jointnames[i][7]=0; //! stop signal for c-string } } local_base.zero_pos_inits = &(local_base.zero_pos_inits_feed[0]); HMDP::lock=0; }
28.5
150
0.608224
IllyasvielEin
9e76384bb659a7ad64d1a252793929ad59cfc345
508
cpp
C++
Classwork/25.02.19/rectangle.cpp
5ko99/FMI-Semester-2
a7e7f2cc1ae7b3198728197c8b70d14156eb0996
[ "MIT" ]
null
null
null
Classwork/25.02.19/rectangle.cpp
5ko99/FMI-Semester-2
a7e7f2cc1ae7b3198728197c8b70d14156eb0996
[ "MIT" ]
null
null
null
Classwork/25.02.19/rectangle.cpp
5ko99/FMI-Semester-2
a7e7f2cc1ae7b3198728197c8b70d14156eb0996
[ "MIT" ]
null
null
null
#include<iostream>; using namespace std; struct Rectangle{ double width; double height; }; void printRec(Rectangle r){ cout<<"Width:"<<r.width<<endl; cout<<"Height:"<<r.height<<endl; } void initRec(Rectangle* r){ cin>>(*r).width; cin>>(*r).height; } Rectangle initRec(){ Rectangle r; cin>>r.width; cin>>r.height; return r; } int main(){ Rectangle r; initRec(&(r)); printRec(r); r=initRec(); printRec(r); return 0; }
17.517241
37
0.555118
5ko99
9e76a925bb00ef7ec3d318043a012adeaaf8e42c
5,445
hpp
C++
src/batteries/radix_queue.hpp
tonyastolfi/batteries
67349930e54785f44eab84f1e56da6c78c66a5f9
[ "Apache-2.0" ]
1
2022-01-04T20:28:17.000Z
2022-01-04T20:28:17.000Z
src/batteries/radix_queue.hpp
mihir-thakkar/batteries
67349930e54785f44eab84f1e56da6c78c66a5f9
[ "Apache-2.0" ]
2
2020-06-04T14:02:24.000Z
2020-06-04T14:03:18.000Z
src/batteries/radix_queue.hpp
mihir-thakkar/batteries
67349930e54785f44eab84f1e56da6c78c66a5f9
[ "Apache-2.0" ]
1
2022-01-03T20:24:31.000Z
2022-01-03T20:24:31.000Z
// Copyright 2021 Anthony Paul Astolfi // #pragma once #ifndef BATTERIES_RADIX_QUEUE_HPP #define BATTERIES_RADIX_QUEUE_HPP #include <batteries/assert.hpp> #include <batteries/int_types.hpp> #include <boost/functional/hash.hpp> #include <array> #include <limits> #include <type_traits> namespace batt { template <usize kCapacityInBits> class RadixQueue; template <usize N_> std::ostream& operator<<(std::ostream& out, const RadixQueue<N_>& t); // A fixed-capacity FIFO queue of integers with variable radix per integer. This is used to store sequences // of events. // template <usize kCapacityInBits> class RadixQueue { public: static constexpr usize kQueueSize = kCapacityInBits / 64; //==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - using index_type = std::conditional_t< (kCapacityInBits <= std::numeric_limits<u16>::max()), std::conditional_t<(kCapacityInBits <= std::numeric_limits<u8>::max()), u8, u16>, std::conditional_t<(kCapacityInBits <= std::numeric_limits<u32>::max()), u32, u64>>; // The queue is stored in segments of 64 bits each. // struct Segment { u64 radix = 1; u64 value = 0; friend inline std::ostream& operator<<(std::ostream& out, const Segment& t) { return out << "{.value=" << t.value << ", .radix=" << t.radix << "}"; } }; // Default hash function. // struct Hash { using value_type = usize; usize operator()(const RadixQueue& r) const { usize seed = r.queue_size(); for (usize i = 0; i < r.queue_size(); ++i) { usize j = (r.front_ + i) % kQueueSize; boost::hash_combine(seed, r.queue[j].radix); boost::hash_combine(seed, r.queue[j].value); } return seed; } }; //==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - RadixQueue() = default; // Returns true when there are no items in the queue. // bool empty() const { return this->queue_size() == 1 && this->front().radix == 1; } // Returns true when the queue has reached its maximum capacity. // bool full() const { return this->front_ == (this->back_ + 1) % kQueueSize; } // Discards the contents of the queue, resetting it to default state. // void clear() { this->front_ = 0; this->back_ = 0; this->queue_[0] = Segment{}; } // Insert the given value with the given radix at the back of the queue. // void push(u64 radix, u64 value) { BATT_CHECK_GT(radix, value) << "value must not exceed the supplied radix"; const bool would_overflow = std::numeric_limits<u64>::max() / this->back().radix < radix; if (would_overflow) { this->push_back(); } Segment& s = this->back(); s.value += value * s.radix; s.radix *= radix; } // Extract the next value out of the queue. The passed radix must match the radix used when inserting // the item originally; otherwise behavior is undefined. // u64 pop(u64 radix) { Segment& s = this->front(); BATT_CHECK_LE(radix, s.radix) << "the supplied radix is too large"; const u64 value = s.value % radix; s.radix /= radix; s.value /= radix; BATT_CHECK_LT(s.value, s.radix); if (s.radix == 1 && this->queue_size() > 1) { this->pop_front(); } return value; } template <usize N_> friend std::ostream& operator<<(std::ostream& out, const RadixQueue<N_>& t); private: static void advance_index(index_type* i) { *i = (*i + 1) % kQueueSize; } usize queue_size() const { const usize upper_bound = [&]() -> usize { if (this->front_ <= this->back_) { return this->back_ + 1; } return kQueueSize + this->back_ + 1; }(); BATT_CHECK_LT(this->front_, upper_bound); return upper_bound - this->front_; } Segment& front() { return this->queue_[this->front_]; } const Segment& front() const { return this->queue_[this->front_]; } Segment& back() { return this->queue_[this->back_]; } const Segment& back() const { return this->queue_[this->back_]; } void pop_front() { BATT_CHECK_NE(this->front_, this->back_) << "pull failed; the RadixQueue is empty"; advance_index(&this->front_); } void push_back() { BATT_CHECK(!this->full()) << "push failed; the RadixQueue is full"; advance_index(&this->back_); this->queue_[this->back_] = Segment{}; } //==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - index_type front_ = 0; index_type back_ = 0; std::array<Segment, kQueueSize> queue_; }; template <usize N_> inline std::ostream& operator<<(std::ostream& out, const RadixQueue<N_>& t) { usize end = (t.front_ <= t.back_) ? (t.back_ + 1) : (t.back_ + 1 + t.queue_.size()); out << "{"; for (usize i = t.front_; i < end; ++i) { const auto& s = t.queue_[i % t.queue_.size()]; out << s.value << "/" << s.radix << ","; } return out << "}"; } } // namespace batt #endif // BATTERIES_RADIX_QUEUE_HPP
26.052632
108
0.547658
tonyastolfi
9e7a1c6c684d37995423a925a87f05e1ff12801a
13,114
cpp
C++
groups/bdl/bdlde/bdlde_quotedprintableencoder.cpp
seanbaxter/bde-1
149176ebc2ae49c3b563895a7332fe638a760782
[ "Apache-2.0" ]
1
2021-11-10T16:53:42.000Z
2021-11-10T16:53:42.000Z
groups/bdl/bdlde/bdlde_quotedprintableencoder.cpp
seanbaxter/bde-1
149176ebc2ae49c3b563895a7332fe638a760782
[ "Apache-2.0" ]
2
2020-11-05T15:20:55.000Z
2021-01-05T19:38:43.000Z
groups/bdl/bdlde/bdlde_quotedprintableencoder.cpp
seanbaxter/bde-1
149176ebc2ae49c3b563895a7332fe638a760782
[ "Apache-2.0" ]
2
2020-01-16T17:58:12.000Z
2020-08-11T20:59:30.000Z
// bdlde_quotedprintableencoder.cpp -*-C++-*- // ---------------------------------------------------------------------------- // NOTICE // // This component is not up to date with current BDE coding standards, and // should not be used as an example for new development. // ---------------------------------------------------------------------------- #include <bdlde_quotedprintableencoder.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(bdlde_quotedprintableencoder_cpp,"$Id$ $CSID$") #include <bslma_default.h> #include <bsls_assert.h> #include <bsl_cstring.h> // 'strlen' // ====================== // FILE-SCOPE STATIC DATA // ====================== namespace { typedef BloombergLP::bdlde::QuotedPrintableEncoder QuotedPrintableEncoder; } // close unnamed namespace static const char PC = QuotedPrintableEncoder::e_PC; static const char CC = QuotedPrintableEncoder::e_CC; static const char CR = QuotedPrintableEncoder::e_CR; static const char LF = QuotedPrintableEncoder::e_LF; static const char WS = QuotedPrintableEncoder::e_WS; static const char *bdeHex = "0123456789ABCDEF"; // The following table is a map of an 8-bit index value to the corresponding // equivalence class. static const char equivalenceClassMap[] = { // 0 1 2 3 4 5 6 7 CC, CC, CC, CC, CC, CC, CC, CC, // 000 CC, WS, LF, CC, CC, CR, CC, CC, // 010 '\t', '\n', '\r' CC, CC, CC, CC, CC, CC, CC, CC, // 020 CC, CC, CC, CC, CC, CC, CC, CC, // 030 WS, PC, PC, PC, PC, PC, PC, PC, // 040 ' ', '!' is first PC PC, PC, PC, PC, PC, PC, PC, PC, // 050 PC, PC, PC, PC, PC, PC, PC, PC, // 060 PC, PC, PC, PC, PC, CC, PC, PC, // 070 '=' PC, PC, PC, PC, PC, PC, PC, PC, // 100 PC, PC, PC, PC, PC, PC, PC, PC, // 110 PC, PC, PC, PC, PC, PC, PC, PC, // 120 PC, PC, PC, PC, PC, PC, PC, PC, // 130 PC, PC, PC, PC, PC, PC, PC, PC, // 140 PC, PC, PC, PC, PC, PC, PC, PC, // 150 PC, PC, PC, PC, PC, PC, PC, PC, // 160 PC, PC, PC, PC, PC, PC, PC, CC, // 170 '~' is last PC CC, CC, CC, CC, CC, CC, CC, CC, // 200 CC, CC, CC, CC, CC, CC, CC, CC, // 210 CC, CC, CC, CC, CC, CC, CC, CC, // 220 CC, CC, CC, CC, CC, CC, CC, CC, // 230 CC, CC, CC, CC, CC, CC, CC, CC, // 240 CC, CC, CC, CC, CC, CC, CC, CC, // 250 CC, CC, CC, CC, CC, CC, CC, CC, // 260 CC, CC, CC, CC, CC, CC, CC, CC, // 270 CC, CC, CC, CC, CC, CC, CC, CC, // 300 CC, CC, CC, CC, CC, CC, CC, CC, // 310 CC, CC, CC, CC, CC, CC, CC, CC, // 320 CC, CC, CC, CC, CC, CC, CC, CC, // 330 CC, CC, CC, CC, CC, CC, CC, CC, // 340 CC, CC, CC, CC, CC, CC, CC, CC, // 350 CC, CC, CC, CC, CC, CC, CC, CC, // 360 CC, CC, CC, CC, CC, CC, CC, CC // 370 }; // The following table stores the names for the line break modes so that on // query, users can tell the mode of the encoder without having to search the // header file for the corresponding enum value. namespace BloombergLP { namespace bdlde { const char* QuotedPrintableEncoder::s_lineBreakModeName[] = { "CRLF mode", "LF mode", "Mixed mode" }; const char *QuotedPrintableEncoder::s_defaultEquivClass_p = equivalenceClassMap; // PRIVATE MANIPULATORS void QuotedPrintableEncoder::appendSoftLineBreak(char *out) { *out = '='; ++d_outputLength; d_buffer[d_bufferLength++] = '\n'; d_buffer[d_bufferLength++] = '\r'; d_lineStart = d_outputLength + 2; d_lastWasWS = false; BSLS_ASSERT(5 >= d_bufferLength); } void QuotedPrintableEncoder::appendHardLineBreak(char *out) { if (d_lastWasWS) { *out = '='; ++d_outputLength; d_buffer[d_bufferLength++] = '\n'; d_buffer[d_bufferLength++] = '\r'; d_buffer[d_bufferLength++] = '\n'; d_buffer[d_bufferLength++] = '\r'; d_lineStart = d_outputLength + 4; } else { *out = '\r'; ++d_outputLength; d_buffer[d_bufferLength++] = '\n'; d_lineStart = d_outputLength + 1; } d_lastWasWS = false; BSLS_ASSERT(5 >= d_bufferLength); } void QuotedPrintableEncoder::appendPrintable(char *out, char ch) { BSLS_ASSERT(0 == d_bufferLength); if (d_outputLength - d_lineStart >= d_maxLineLength - 1) { d_buffer[d_bufferLength++] = ch; appendSoftLineBreak(out); } else { *out = ch; ++d_outputLength; } d_lastWasWS = (WS == d_equivClass_p[static_cast<unsigned char>(ch)]); BSLS_ASSERT(5 >= d_bufferLength); } void QuotedPrintableEncoder::appendAsHex(char *out, char ch, bool isFinal) { BSLS_ASSERT(0 == d_bufferLength); d_buffer[d_bufferLength++] = bdeHex[ch & 0xf]; d_buffer[d_bufferLength++] = bdeHex[(ch >> 4) & 0xf]; if (d_outputLength - d_lineStart >= d_maxLineLength - (isFinal ? 2 : 3)) { d_buffer[d_bufferLength++] = '='; appendSoftLineBreak(out); } else { *out = '='; ++d_outputLength; } d_lastWasWS = false; BSLS_ASSERT(5 >= d_bufferLength); } // CREATORS QuotedPrintableEncoder::QuotedPrintableEncoder( QuotedPrintableEncoder::LineBreakMode lineBreakMode, int maxLineLength, bslma::Allocator *basicAllocator) : d_lineBreakMode(lineBreakMode) , d_maxLineLength(maxLineLength) , d_outputLength(0) , d_lineLength(0) , d_equivClass_p(const_cast<char *>(s_defaultEquivClass_p)) , d_state(e_INITIAL_STATE) , d_bufferLength(0) , d_lineStart(0) , d_deffered(0) , d_lastWasWS(false) , d_allocator_p(bslma::Default::allocator(basicAllocator)) { BSLS_ASSERT(4 <= d_maxLineLength); BSLS_ASSERT( d_maxLineLength <= 76); if (e_CRLF_MODE != d_lineBreakMode && e_MIXED_MODE != d_lineBreakMode) { int len = sizeof(equivalenceClassMap); d_equivClass_p = static_cast<char *>(d_allocator_p->allocate(len)); bsl::memcpy(d_equivClass_p, s_defaultEquivClass_p, len); d_equivClass_p['\r'] = CC; if (e_BINARY_MODE == d_lineBreakMode) { d_equivClass_p['\n'] = CC; } } } QuotedPrintableEncoder::QuotedPrintableEncoder( const char *extraCharsToEncode, QuotedPrintableEncoder::LineBreakMode lineBreakMode, int maxLineLength, bslma::Allocator *basicAllocator) : d_lineBreakMode(lineBreakMode) , d_maxLineLength(maxLineLength) , d_outputLength(0) , d_lineLength(0) , d_equivClass_p(const_cast<char *>(s_defaultEquivClass_p)) , d_state(e_INITIAL_STATE) , d_bufferLength(0) , d_lineStart(0) , d_deffered(0) , d_lastWasWS(false) , d_allocator_p(bslma::Default::allocator(basicAllocator)) { BSLS_ASSERT(4 <= d_maxLineLength); BSLS_ASSERT( d_maxLineLength <= 76); // First copy the default mapping table to data member. int len = sizeof(equivalenceClassMap); d_equivClass_p = static_cast<char *>(d_allocator_p->allocate(len)); bsl::memcpy(d_equivClass_p, s_defaultEquivClass_p, len); // Now change the specified individual elements. if (extraCharsToEncode) { len = static_cast<int>(bsl::strlen(extraCharsToEncode)); for (int i = 0; i < len; ++i) { int index = static_cast<unsigned char>(extraCharsToEncode[i]); if (PC == d_equivClass_p[index] || WS == d_equivClass_p[index]) { d_equivClass_p[index] = CC; } } } if (e_CRLF_MODE == d_lineBreakMode || e_MIXED_MODE == d_lineBreakMode) { d_equivClass_p['\r'] = CR; d_equivClass_p['\n'] = LF; } else if (e_LF_MODE == d_lineBreakMode) { d_equivClass_p['\r'] = CC; d_equivClass_p['\n'] = LF; } else { d_equivClass_p['\r'] = CC; d_equivClass_p['\n'] = CC; } } QuotedPrintableEncoder::~QuotedPrintableEncoder() { if (d_equivClass_p != s_defaultEquivClass_p) { d_allocator_p->deallocate(d_equivClass_p); } } // MANIPULATORS int QuotedPrintableEncoder::convert(char *out, int *numOut, int *numIn, const char *begin, const char *end, int maxNumOut) { BSLS_ASSERT(out); BSLS_ASSERT(numOut); BSLS_ASSERT(numIn); BSLS_ASSERT(begin); BSLS_ASSERT(end); if (e_ERROR_STATE == d_state || e_DONE_STATE == d_state) { d_state = e_ERROR_STATE; *numOut = 0; *numIn = 0; return -1; // RETURN } if (0 == maxNumOut) { *numOut = 0; *numIn = 0; return numOutputPending(); // RETURN } if (begin < end) { d_state = e_INPUT_STATE; } const int originalOutputLength = d_outputLength; const char *originalBegin = begin; int maxOutLen = d_outputLength + maxNumOut; while ( d_outputLength != maxOutLen && (begin < end || d_bufferLength)) { while (d_bufferLength && d_outputLength != maxOutLen) { *out++ = d_buffer[--d_bufferLength]; ++d_outputLength; } if (d_deffered && d_outputLength != maxOutLen && begin < end) { if (d_deffered == '\r') { if (LF == d_equivClass_p[static_cast<unsigned char>(*begin)]) { appendHardLineBreak(out++); ++begin; } else { appendAsHex(out++, d_deffered); } } else { if (LF == d_equivClass_p[static_cast<unsigned char>(*begin)] || CR == d_equivClass_p[static_cast<unsigned char>(*begin)]) { appendAsHex(out++, d_deffered); } else { appendPrintable(out++, d_deffered); } } d_deffered = 0; } while ( d_outputLength != maxOutLen && begin < end && 0 == d_deffered && 0 == d_bufferLength) { switch (d_equivClass_p[static_cast<unsigned char>(*begin)]) { case PC: { appendPrintable(out++, *begin++); } break; case CC: { appendAsHex(out++, *begin++); } break; case WS: { d_deffered = *begin++; } break; case CR: { d_deffered = *begin++; } break; case LF: { if ( e_LF_MODE == d_lineBreakMode || e_MIXED_MODE == d_lineBreakMode) { appendHardLineBreak(out++); ++begin; } else { appendAsHex(out++, *begin++); } } break; } } } *numOut = d_outputLength - originalOutputLength; *numIn = static_cast<int>(begin - originalBegin); return numOutputPending(); } int QuotedPrintableEncoder::endConvert(char *out, int *numOut, int maxNumOut) { enum { e_ERROR = -1 }; if (d_state == e_ERROR_STATE || isDone()) { d_state = e_ERROR_STATE; *numOut = 0; return e_ERROR; // RETURN } d_state = e_DONE_STATE; const int originalOutputLength = d_outputLength; int maxOutLen = d_outputLength + maxNumOut; if (d_deffered && d_outputLength != maxOutLen) { appendAsHex(out++, d_deffered, true); d_deffered = 0; } while (d_bufferLength && d_outputLength != maxOutLen) { *out++ = d_buffer[--d_bufferLength]; ++d_outputLength; } *numOut = d_outputLength - originalOutputLength; return numOutputPending(); } } // close package namespace } // close enterprise namespace // ---------------------------------------------------------------------------- // Copyright 2016 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
31.830097
79
0.538356
seanbaxter
9e7c6bad8dc38dc8cd43fbe739f5ef56c9044bff
200
hpp
C++
Algorithm.hpp
NagiSenbon/Algorithm
e8044820a2cdd6a26d58097fd84512f3231d8dd6
[ "Apache-2.0" ]
2
2019-10-07T01:48:53.000Z
2019-10-13T08:24:22.000Z
Algorithm.hpp
NagiSenbon/Algorithm
e8044820a2cdd6a26d58097fd84512f3231d8dd6
[ "Apache-2.0" ]
null
null
null
Algorithm.hpp
NagiSenbon/Algorithm
e8044820a2cdd6a26d58097fd84512f3231d8dd6
[ "Apache-2.0" ]
null
null
null
#pragma once #include "src/Headers.hpp" #include "src/Heap.hpp" #include "src/Math.hpp" #include "src/Meta.hpp" #include "src/Queue.hpp" #include "src/Sort.hpp" // #include "src/Tensor.hpp"
20
29
0.675
NagiSenbon
9e8113d1fca423b20b9a8299dc50a8aa10fd200d
11,716
cpp
C++
kcfi/llvm-kcfi/lib/CodeGen/CFI.cpp
IntelSTORM/Projects
b983417a5ca22c7679da5a1144b348863bea5698
[ "Intel" ]
1
2022-01-11T11:12:00.000Z
2022-01-11T11:12:00.000Z
kcfi/llvm-kcfi/lib/CodeGen/CFI.cpp
IntelSTORMteam/Jurassic-Projects
b983417a5ca22c7679da5a1144b348863bea5698
[ "Intel" ]
null
null
null
kcfi/llvm-kcfi/lib/CodeGen/CFI.cpp
IntelSTORMteam/Jurassic-Projects
b983417a5ca22c7679da5a1144b348863bea5698
[ "Intel" ]
null
null
null
//===---- CFI.cpp - kCFI LLVM IR analyzes and transformation --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // LLVM IR analyzes / transformations to enable kCFI backend instrumentation // //===----------------------------------------------------------------------===// #include <iostream> #include <sstream> #include <fstream> #include <list> #include "llvm/ADT/IndexedMap.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/CFGforCFI.h" #include "llvm/CodeGen/MachineDominators.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineLoopInfo.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/RegisterScavenging.h" #include "llvm/CodeGen/StackProtector.h" #include "llvm/CodeGen/WinEHFuncInfo.h" #include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/InlineAsm.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/ValueMap.h" #include "llvm/Transforms/IPO.h" #include "llvm/ADT/Statistic.h" #include "llvm/IR/CFG.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/Transforms/Utils/Cloning.h" #include "llvm/Transforms/Utils/CodeExtractor.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetFrameLowering.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Target/TargetSubtargetInfo.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include <climits> using namespace llvm; #define DEBUG_TYPE "cfi" extern cl::opt<bool> CFICoarse; extern CFICFG cfi; extern cl::opt<bool> CFIBuildCFG; extern cl::opt<bool> CFIv; extern cl::opt<bool> CFIvv; extern cl::opt<bool> CFICGD; extern cl::opt<bool> CFIMapDecls; static CFIUtils u; namespace { class CFI : public ModulePass { public: static char ID; CFI() : ModulePass(ID) { initializeCFIPass(*PassRegistry::getPassRegistry()); } bool runOnModule(Module &M) override; bool shouldCGD(Function *F); void dumpAliases(Module &M); void computeCalls(Module &M); void computeFunctions(Module &M); int tagCalls(Module &M); void CGD(Module &M); int tagFunctions(Module &M); void computeAndTag(Module &M); }; } char CFI::ID = 0; char &llvm::CFIID = CFI::ID; INITIALIZE_PASS_BEGIN(CFI, "CFITagger", "CFI Function Tag Placer", false, false) INITIALIZE_PASS_END(CFI, "CFITagger", "CFI Function Tag Placer", false, false) bool CFI::runOnModule(Module &M) { // Templates generated using LLVM's C++ backend. // TODO: Improve variables/types/function declarations below if(CFIBuildCFG){ GlobalVariable* CFIGlobalVar = M.getGlobalVariable("global_signature"); if(!CFIGlobalVar){ CFIGlobalVar = new GlobalVariable(M, Type::getInt32Ty(M.getContext()), false, GlobalValue::LinkOnceODRLinkage, 0, "global_signature"); CFIGlobalVar->setAlignment(1); CFIGlobalVar->setThreadLocal(false); } ConstantInt* type = ConstantInt::get(M.getContext(), APInt(32, StringRef("0"), 10)); CFIGlobalVar->setInitializer(type); } std::vector<Type*>args; args.push_back(IntegerType::get(M.getContext(), 32)); args.push_back(IntegerType::get(M.getContext(), 32)); FunctionType* func_type = FunctionType::get(Type::getVoidTy(M.getContext()), args, false); Function* cvh = M.getFunction("call_violation_handler"); if (!cvh) { cvh = Function::Create(func_type, GlobalValue::ExternalLinkage, "call_violation_handler", &M); } cvh->setCallingConv(CallingConv::PreserveMost); Function* rvh = M.getFunction("ret_violation_handler"); if (!rvh) { rvh = Function::Create(func_type, GlobalValue::ExternalLinkage, "ret_violation_handler", &M); } rvh->setCallingConv(CallingConv::PreserveMost); AttributeSet cvh_PAL; { SmallVector<AttributeSet, 4> Attrs; AttributeSet PAS; { AttrBuilder B; B.addAttribute(Attribute::NoUnwind); B.addAttribute(Attribute::UWTable); PAS = AttributeSet::get(M.getContext(), ~0U, B); } Attrs.push_back(PAS); cvh_PAL = AttributeSet::get(M.getContext(), Attrs); } cvh->setAttributes(cvh_PAL); AttributeSet rvh_PAL; { SmallVector<AttributeSet, 4> Attrs; AttributeSet PAS; { AttrBuilder B; B.addAttribute(Attribute::NoUnwind); B.addAttribute(Attribute::UWTable); PAS = AttributeSet::get(M.getContext(), ~0U, B); } Attrs.push_back(PAS); rvh_PAL = AttributeSet::get(M.getContext(), Attrs); } rvh->setAttributes(cvh_PAL); // CFI required symbols created above, now start the analysis computeAndTag(M); return true; } bool CFI::shouldCGD(Function *F){ bool v = true; StringRef handle = "_kcfi"; if(F->getName().endswith(handle)) v = false; handle = "call_violation_handler"; if(F->getName().equals_lower(handle)) v = false; handle = "ret_violation_handler"; if(F->getName().equals_lower(handle)) v = false; handle = "__brk_reservation_fn_"; if(F->getName().startswith(handle)) v = false; if(!v) return false; if(cfi.differentEdgesToStrongerNode(F)){ u.warn("Found weak linkage replacement that should be cloned\n"); return true; } if(cfi.differentEdgesToNode(F)) return true; return false; } void CFI::CGD(Module &M){ std::stringstream fname; for(Module::iterator m = M.begin(), me = M.end(); m != me; ++m){ Function *Original = m, *Clone, *HackF; if(!shouldCGD(Original)){ // if do not clone this f; check if it is an alias if it is an alias, // materialize the aliasee and then check if it should be cloned. std::string aliasee = cfi.checkWeakAlias(Original); if(aliasee.length() > 0){ fname.str(std::string()); fname.clear(); fname << aliasee; Function *a; a = M.getFunction(fname.str()); if(!a){ a = Function::Create(Original->getFunctionType(), GlobalValue::ExternalLinkage, fname.str(), &M); } a->setCallingConv(CallingConv::C); if(!shouldCGD(a)){ a->removeFromParent(); } } continue; } fname.str(std::string()); fname.clear(); fname << Original->getName().str() << "_kcfi"; if(Original->isDeclaration()){ Function* c = Function::Create(Original->getFunctionType(), GlobalValue::ExternalLinkage, fname.str(), &M); c->setCallingConv(CallingConv::C); } else { ValueToValueMapTy VMap; Clone = CloneFunction(Original, VMap, false); M.getFunctionList().push_back(Clone); CFINode n = cfi.getNode(Original, true); Clone->setCFINode(n); HackF = M.getFunction(fname.str()); if(HackF){ fprintf(stderr, "** into clone %s\n", fname.str().c_str()); HackF->replaceAllUsesWith(Clone); HackF->eraseFromParent(); } Clone->setName(fname.str()); } } } void CFI::dumpAliases(Module &M){ for(GlobalAlias &GA : M.aliases()){ if(cfi.getAlias(GA.getName()).length() > 0){ if(strcmp(cfi.getAlias(GA.getName()).c_str(), GA.getAliasee()->stripPointerCasts()->getName().str() .c_str())!=0){ fprintf(stderr, "Clashing aliases:\n Alias/value: "); GA.dump(); fprintf(stderr, "%s\n Aliasee/value:", GA.getName().str().c_str()); GA.getAliasee()->dump(); fprintf(stderr, "%s", GA.getAliasee()->stripPointerCasts()->getName() .str().c_str()); } else { continue; } } cfi.setAlias(GA.getName(), GA.getAliasee()->stripPointerCasts()->getName() .str().c_str()); } cfi.storeAliases(); } void CFI::computeAndTag(Module &M){ if(CFICoarse) return; if(CFIBuildCFG){ computeFunctions(M); computeCalls(M); cfi.storeCFG(); if(CFIMapDecls) cfi.storeDecls(); dumpAliases(M); } else { tagFunctions(M); if(CFICGD) CGD(M); tagCalls(M); } } int CFI::tagCalls(Module &M){ int n = 0; CFICluster c; for(Module::iterator m = M.begin(), me = M.end(); m != me; ++m){ Function &Fn = *m; for(Function::iterator bb = Fn.begin(), bbe = Fn.end(); bb != bbe; ++bb){ BasicBlock &b = *bb; for(BasicBlock::iterator i = b.begin(), ie = b.end(); i != ie; ++i){ CallInst *CI = dyn_cast_or_null<CallInst>(i); if(CI && u.isICall(CI)){ c = cfi.getCluster(CI->getFunctionType()); if(!c.id){ cfi_er << "Unable to get cluster " << Fn.getName().str(); u.error(true); } CI->setCFITag(c.id); n++; if(CFIvv) fprintf(stderr, "CFIMsg: tagged icall: Tag ID %x %s to %s\n", c.id, Fn.getName().str().c_str(), c.proto); } } } } return n; } void CFI::computeCalls(Module &M){ CFIEdge e; std::string t; for(Module::iterator m = M.begin(), me = M.end(); m != me; ++m){ Function &Fn = *m; for(Function::iterator bb = Fn.begin(), bbe = Fn.end(); bb != bbe; ++bb){ BasicBlock &b = *bb; for(BasicBlock::iterator i = b.begin(), ie = b.end(); i != ie; ++i){ CallInst *CI = dyn_cast_or_null<CallInst>(i); if(CI){ if(u.isICall(CI)){ CallInst *CI = dyn_cast<CallInst>(i); Type *proto = CI->getFunctionType(); e = cfi.createEdge(m, proto); if(!e.id) u.error("Unable to create edge", true); } else if(u.isDCall(CI)){ CallInst *CI = dyn_cast<CallInst>(i); Function *F = CI->getCalledFunction(); if(F){ std::stringstream s; if(F->getName().startswith("llvm.")) continue; } } } } } } } void CFI::computeFunctions(Module &M){ CFINode n; std::string t; for(Module::iterator m = M.begin(), me = M.end(); m != me; ++m){ Function &Fn = *m; if(Fn.isDeclaration()){ if(Fn.getName().startswith("llvm.")) continue; if(CFIMapDecls) cfi.createDecl(&Fn); continue; } n = cfi.createNode(&Fn); if(!n.id) u.error("Unable to create node", true); if(CFIv){ cfi_msg << "Tags created for " << Fn.getName().str() << "\n"; u.msg(); } Fn.setCFINode(n); } } int CFI::tagFunctions(Module &M){ CFINode n; CFICluster c; std::string t; int i = 0; for(Module::iterator m = M.begin(), me = M.end(); m != me; ++m){ Function &Fn = *m; if(Fn.isDeclaration()) continue; n = cfi.getNode(m, true); c = cfi.getCluster(Fn.getFunctionType()); if(!n.id){ cfi.dumpCFG(); Fn.dump(); cfi_er << "Unable to get node" << Fn.getName().str() << "\n"; u.error(true); } Fn.setCFINode(n); Fn.setCFICluster(c); i++; } return i; }
29.964194
80
0.597986
IntelSTORM
9e877c98b23dfe47cefd55199d26bc9eba31bba1
1,689
cpp
C++
cpp/leetcode/LongestStringChain.cpp
danyfang/SourceCode
8168f6058648f2a330a7354daf3a73a4d8a4e730
[ "MIT" ]
null
null
null
cpp/leetcode/LongestStringChain.cpp
danyfang/SourceCode
8168f6058648f2a330a7354daf3a73a4d8a4e730
[ "MIT" ]
null
null
null
cpp/leetcode/LongestStringChain.cpp
danyfang/SourceCode
8168f6058648f2a330a7354daf3a73a4d8a4e730
[ "MIT" ]
null
null
null
//Leetcode Problem No 1048. Longest String Chain //Solution written by Xuqiang Fang on 18 May, 2019 #include <iostream> #include <vector> #include <string> #include <algorithm> #include <unordered_map> #include <unordered_set> #include <stack> #include <queue> using namespace std; class Solution{ public: int longestStrChain(vector<string>& words) { sort(words.begin(), words.end(), [](string& a , string& b){ return a.size() < b.size(); }); const int n = words.size(); ans = 0; vector<vector<int>> graph(n, vector<int>(n, 0)); for(int i=0; i<n; ++i){ for(int j=i+1; j<n; ++j){ if(ischain(words[i], words[j])){ graph[i][j] = 1; } } } for(int i=0; i<n; ++i){ for(int j=0; j<n; ++j){ cout << graph[i][j] << " "; } cout << endl; } for(int i=0; i<n; ++i){ dfs(graph, n, i, 1); } return ans; } private: int ans; void dfs(vector<vector<int>>& graph, const int n, int i, int level){ ans = max(ans, level); for(int j=i+1; j<n; ++j){ if(graph[i][j] == 1){ dfs(graph, n, j, level+1); } } } bool ischain(string& a, string& b){ if(b.size()-a.size() != 1 ){ return false; } int num[26] = {0}; for(auto& x : a){ num[x-'a']++; } for(auto& x : b){ num[x-'a']--; } int count = 0; for(auto i : num){ if(i == 0){ count++; } } return count == 25; } }; int main(){ Solution s; vector<string> words{"a","b","ba","bca","bda","bdca"}; cout << s.longestStrChain(words) << endl; return 0; }
21.653846
72
0.487863
danyfang
9e8c11d9faa94fe11338d41a60378b8707f4955e
2,876
cpp
C++
src/window/preferences/init_chilren.cpp
LibreTextus/LibreTextus
a142c0bed2237b1b252e1ff5dcfdbe82bd4439d3
[ "CC0-1.0" ]
3
2020-08-26T06:18:42.000Z
2021-01-16T17:22:29.000Z
src/window/preferences/init_chilren.cpp
LibreTextus/LibreTextus
a142c0bed2237b1b252e1ff5dcfdbe82bd4439d3
[ "CC0-1.0" ]
null
null
null
src/window/preferences/init_chilren.cpp
LibreTextus/LibreTextus
a142c0bed2237b1b252e1ff5dcfdbe82bd4439d3
[ "CC0-1.0" ]
null
null
null
#include "preferences.hpp" void Libre::PreferencesWindow::add_themes_to_themes_combo() { std::vector<std::string> v = this->settings.get_children("themes", "name"); for (std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++) { this->ui_pane.get_theme()->get_element()->append(*i); if (*i == this->settings.get_attribute("themes", "active")) { this->ui_pane.get_theme()->get_element()->set_active_text(*i); } } } void Libre::PreferencesWindow::add_locales_to_locales_combo() { this->ui_pane.get_locale()->get_element()->append(_("System default")); for (auto & i : std::experimental::filesystem::directory_iterator(DATA("../locale"))) { this->ui_pane.get_locale()->get_element()->append(i.path().filename().string()); } this->ui_pane.get_locale()->get_element()->set_active_text( (this->settings.get_attribute("locale", "locale").empty() ? _("System default") : this->settings.get_attribute("locale", "locale")) ); } void Libre::PreferencesWindow::set_font_size_adjustment() { this->ui_pane.get_font_size()->get_element()->set_adjustment( Gtk::Adjustment::create(std::stoi(this->settings.get_attribute("font", "size")), 0, 100) ); } void Libre::PreferencesWindow::create_css_context() { Glib::RefPtr<Gdk::Screen> screen = Gdk::Screen::get_default(); this->theme_css_provider = Gtk::CssProvider::create(); this->font_size_css_provider = Gtk::CssProvider::create(); this->get_style_context()->add_provider_for_screen(screen, this->theme_css_provider, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); this->get_style_context()->add_provider_for_screen(screen, this->font_size_css_provider, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); this->theme_css_provider->load_from_path(DATA(this->settings.get_attribute("themes", "active") + ".css")); this->font_size_css_provider->load_from_data( "#text_view { font-size: " + this->settings.get_attribute("font", "size") + "px;}" ); } void Libre::PreferencesWindow::set_package_manager(Libre::PackageManager * pm) { this->package_manager = pm; std::vector<std::string> v = this->package_manager->get_sources(); for (std::vector<std::string>::const_iterator i = v.begin(); i != v.end(); i++) { this->book_manager_pane.get_book_list()->append(*i); this->book_manager_pane.get_book_list()->get_items()->back()->set_active( this->package_manager->is_enabled(*i) ); this->book_manager_pane.get_default_source()->get_element()->append(*i); this->book_manager_pane.get_book_list()->get_items()->back()->signal_clicked().connect( sigc::bind<Gtk::CheckButton *>( sigc::mem_fun(this, &Libre::PreferencesWindow::enable_changed), this->book_manager_pane.get_book_list()->get_items()->back() ) ); } this->book_manager_pane.get_default_source()->get_element()->set_active_text(this->settings.get_attribute("startupfile", "file")); }
37.350649
131
0.714882
LibreTextus
9e8dc554686bf44921293885bf7ce947bc2e370e
1,291
cpp
C++
src/thumbnailholder.cpp
digitalsurgeon/EasyWallpapers
86f62ad6453ed079f9b889d6adc910f0d89092c1
[ "MIT" ]
null
null
null
src/thumbnailholder.cpp
digitalsurgeon/EasyWallpapers
86f62ad6453ed079f9b889d6adc910f0d89092c1
[ "MIT" ]
null
null
null
src/thumbnailholder.cpp
digitalsurgeon/EasyWallpapers
86f62ad6453ed079f9b889d6adc910f0d89092c1
[ "MIT" ]
null
null
null
#include "thumbnailholder.h" #if defined(Q_OS_SYMBIAN) #include <e32std.h> #include <touchfeedback.h> #endif ThumbnailHolder::ThumbnailHolder() : iPixmap(NULL) { setFlag(QGraphicsItem::ItemClipsToShape); } ThumbnailHolder::~ThumbnailHolder() { delete iPixmap; } QRectF ThumbnailHolder::boundingRect() const { if (!iPixmap) return QRectF(0,0,420,420); return QRectF(QPointF(0,0), iPixmap->size()); } void ThumbnailHolder::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { if(iPixmap) { const QRect br = boundingRect().toRect(); painter->drawPixmap(br, *iPixmap); } } void ThumbnailHolder::mousePressEvent(QGraphicsSceneMouseEvent *) { #if defined(Q_OS_SYMBIAN) MTouchFeedback* feedBack = MTouchFeedback::Instance(); if (feedBack) { feedBack->InstantFeedback(ETouchFeedbackBasic); } #endif emit thmbnailTapped(); } void ThumbnailHolder::setPixmap(const QPixmap &pixmap) { delete iPixmap; prepareGeometryChange(); iPixmap = new QPixmap(pixmap); } void ThumbnailHolder::setImageUrl ( const QString& aUrl) { iImageUrl = aUrl; } QString ThumbnailHolder::imageUrl() const { return iImageUrl; }
18.985294
80
0.660728
digitalsurgeon
9e8ecb5a2f10b5b2c0fae200a98321ecacf7a626
3,623
cxx
C++
source/opengl/ui_renderer.cxx
bjadamson/BoomHS
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
[ "MIT" ]
2
2016-07-22T10:09:21.000Z
2017-09-16T06:50:01.000Z
source/opengl/ui_renderer.cxx
bjadamson/BoomHS
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
[ "MIT" ]
14
2016-08-13T22:45:56.000Z
2018-12-16T03:56:36.000Z
source/opengl/ui_renderer.cxx
bjadamson/BoomHS
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
[ "MIT" ]
null
null
null
#include <opengl/ui_renderer.hpp> #include <opengl/bind.hpp> #include <opengl/draw_info.hpp> #include <opengl/gpu.hpp> #include <opengl/renderer.hpp> #include <opengl/shader.hpp> #include <boomhs/camera.hpp> #include <boomhs/math.hpp> #include <boomhs/rectangle.hpp> #include <boomhs/shape.hpp> using namespace boomhs; using namespace boomhs::math; namespace opengl { UiRenderer::UiRenderer(static_shaders::BasicMvWithUniformColor&& sp2d, Viewport const& vp) : sp2d_(MOVE(sp2d)) { resize(vp); } void UiRenderer::resize(Viewport const& vp) { int constexpr NEAR_PM = -1.0; int constexpr FAR_PM = 1.0f; Frustum const fr{ vp.left(), vp.right(), vp.bottom(), vp.top(), NEAR_PM, FAR_PM }; auto constexpr ZOOM = glm::ivec2{0}; pm_ = CameraORTHO::compute_pm(fr, vp.size(), constants::ZERO, ZOOM); } void UiRenderer::draw_rect_impl(common::Logger& logger, ModelViewMatrix const& mv, DrawInfo& di, Color const& color, GLenum const dm, ShaderProgram& sp, DrawState& ds) { BIND_UNTIL_END_OF_SCOPE(logger, sp); shader::set_uniform(logger, sp, "u_mv", mv); shader::set_uniform(logger, sp, "u_color", color); BIND_UNTIL_END_OF_SCOPE(logger, di); OR::draw_2delements(logger, dm, sp, di.num_indices(), ds); } void UiRenderer::draw_rect(common::Logger& logger, DrawInfo& di, Color const& color, GLenum const dm, DrawState& ds) { auto const& mv = pm_; draw_rect_impl(logger, mv, di, color, dm, sp2d_.sp(), ds); } void UiRenderer::draw_rect(common::Logger& logger, ModelMatrix const& mmatrix, DrawInfo& di, Color const& color, GLenum const dm, DrawState& ds) { auto const mv = pm_ * mmatrix; draw_rect_impl(logger, mv, di, color, dm, sp2d_.sp(), ds); } //////////////////////////////////////////////////////////////////////////////////////////////////// // static_shaders::BasicMvWithUniformColor static_shaders::BasicMvWithUniformColor static_shaders::BasicMvWithUniformColor::create(common::Logger& logger) { constexpr auto vert_source = GLSL_SOURCE(R"GLSL( in vec3 a_position; uniform mat4 u_mv; uniform vec4 u_color; out vec4 v_color; void main() { gl_Position = u_mv * vec4(a_position, 1.0); v_color = u_color; } )GLSL"); static auto frag_source = GLSL_SOURCE(R"GLSL( in vec4 v_color; out vec4 fragment_color; void main() { fragment_color = v_color; } )GLSL"); auto api = AttributePointerInfo{0, GL_FLOAT, AttributeType::POSITION, 3}; auto sp = make_shaderprogram_expect(logger, vert_source, frag_source, MOVE(api)); return static_shaders::BasicMvWithUniformColor{MOVE(sp)}; } /////////////////////////////////////////////////////////////////////////////////////////////// // ProgramAndDrawInfo ProgramAndDrawInfo::ProgramAndDrawInfo(static_shaders::BasicMvWithUniformColor&& p, DrawInfo&& di) : program(MOVE(p)) , dinfo(MOVE(di)) { } ProgramAndDrawInfo ProgramAndDrawInfo::create_rect(common::Logger& logger, RectFloat const& rect, static_shaders::BasicMvWithUniformColor&& program, GLenum const dm) { auto builder = RectBuilder{rect}; builder.draw_mode = dm; auto const& va = program.sp().va(); auto dinfo = OG::copy_rectangle(logger, va, builder.build()); return ProgramAndDrawInfo{MOVE(program), MOVE(dinfo)}; } ProgramAndDrawInfo ProgramAndDrawInfo::create_rect(common::Logger& logger, RectFloat const& rect, GLenum const dm) { auto program = static_shaders::BasicMvWithUniformColor::create(logger); return create_rect(logger, rect, MOVE(program), dm); } } // namespace opengl
26.837037
111
0.665471
bjadamson
9e9062b2ab3c13a91fb34a48dc732c589d6af198
1,136
cpp
C++
Sid's Contests/LeetCode contests/May Challenge/Non Decreasing Array.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
14
2021-08-22T18:21:14.000Z
2022-03-08T12:04:23.000Z
Sid's Contests/LeetCode contests/May Challenge/Non Decreasing Array.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
1
2021-10-17T18:47:17.000Z
2021-10-17T18:47:17.000Z
Sid's Contests/LeetCode contests/May Challenge/Non Decreasing Array.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
5
2021-09-01T08:21:12.000Z
2022-03-09T12:13:39.000Z
class Solution { public: bool isSorted(vector<int> nums) { vector<int> res; for(int i = 0; i < nums.size(); i++) res.push_back(nums[i]); sort(res.begin(), res.end()); for(int i = 0; i < res.size(); i++) if(res[i] != nums[i]) return false; return true; } bool checkPossibility(vector<int>& nums) { //OM GAN GANAPATHAYE NAMO NAMAH //JAI SHRI RAM //JAI BAJRANGBALI //AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA vector<int> res; for(int i = 0; i < nums.size(); i++) res.push_back(nums[i]); for(int i = 0; i < nums.size()-1; i++) { if(nums[i] > nums[i+1]) { nums[i+1] = nums[i]; break; } } bool x = isSorted(nums); for(int i = 0; i < res.size()-1; i++) { if(res[i] > res[i+1]) { res[i] = res[i+1]; break; } } bool y = isSorted(res); return x|y; } };
26.418605
73
0.415493
Tiger-Team-01
9e90a644d3f786772ec655721f087a69972ab44f
59
cpp
C++
C++/Algorytmy dla zabawy/Quiz/start.cpp
Kwandes/highschool-code
ffaf7aea78236cec709ec7c70886df5427005332
[ "MIT" ]
null
null
null
C++/Algorytmy dla zabawy/Quiz/start.cpp
Kwandes/highschool-code
ffaf7aea78236cec709ec7c70886df5427005332
[ "MIT" ]
null
null
null
C++/Algorytmy dla zabawy/Quiz/start.cpp
Kwandes/highschool-code
ffaf7aea78236cec709ec7c70886df5427005332
[ "MIT" ]
null
null
null
#include <iostream> #include "quiz.h" using namespace std;
14.75
20
0.745763
Kwandes
9e91d353b7c868acdb6e2efdcbe5bcf792310ffd
96
cpp
C++
src/widgets/Library/ProgramLibraryController.cpp
javedlingasur/CompileOne
646da061ea9a8c427a533490cb612f5858de3f09
[ "MIT" ]
null
null
null
src/widgets/Library/ProgramLibraryController.cpp
javedlingasur/CompileOne
646da061ea9a8c427a533490cb612f5858de3f09
[ "MIT" ]
null
null
null
src/widgets/Library/ProgramLibraryController.cpp
javedlingasur/CompileOne
646da061ea9a8c427a533490cb612f5858de3f09
[ "MIT" ]
null
null
null
#include "ProgramLibraryController.h" ProgramLibraryController::ProgramLibraryController() { }
16
52
0.833333
javedlingasur
9e9928d6d8f93fef0c661d8e2b30a0046d429f03
4,688
cpp
C++
src/c-API/cTracer.cpp
mensinda/tracer
874d859a1ac98f296610c8d634eb557e5bc9c515
[ "BSD-3-Clause" ]
11
2017-07-04T11:23:19.000Z
2021-08-24T05:20:01.000Z
src/c-API/cTracer.cpp
mensinda/tracer
874d859a1ac98f296610c8d634eb557e5bc9c515
[ "BSD-3-Clause" ]
null
null
null
src/c-API/cTracer.cpp
mensinda/tracer
874d859a1ac98f296610c8d634eb557e5bc9c515
[ "BSD-3-Clause" ]
4
2017-07-07T19:36:16.000Z
2022-01-05T15:30:08.000Z
/* Copyright (c) 2017, Daniel Mensinger * 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 Daniel Mensinger 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 Daniel Mensinger 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. */ //! \file cTracer.cpp #include "tracer.h" #include "tracerDef.hpp" #include "tracerInternal.hpp" #include <limits> #include <stddef.h> #include <string.h> using namespace tracer; using namespace std; extern "C" { //! \brief Wrapper for tracer::Tracer::Tracer tr_Tracer_t *tr_getTracer() { tr_Tracer_t *t = new tr_Tracer_t; t->tPTR = &t->tracer; return t; } //! \brief Wrapper for tracer::Tracer::Tracer(TraceerEngines, DebuggerEngines) tr_Tracer_t *tr_getTracerWithParam(TR_TraceerEngines_t tracer, TR_DebuggerEngines_t debugInfo) { tr_Tracer_t *t = new tr_Tracer_t(static_cast<TraceerEngines>(tracer), static_cast<DebuggerEngines>(debugInfo)); t->tPTR = &t->tracer; return t; } //! \brief Creates the priavet C struct form a void pointer to the C++ Tracer object tr_Tracer_t *tr_getTracerFromVoid(void *tVoid) { tr_Tracer_t *t = new tr_Tracer_t; t->tPTR = reinterpret_cast<Tracer *>(tVoid); return t; } //! \brief Wrapper for tracer::Tracer::trace void tr_Tracer__trace(tr_Tracer_t *tracer) { if (!tracer) return; tracer->tPTR->trace(); } /*! * \brief (Indirect) Wrapper for tracer::Tracer::getFrames * \sa tr_Tracer__getFrame */ size_t tr_Tracer__getNumFrames(tr_Tracer_t *tracer) { if (!tracer) return numeric_limits<size_t>::max(); return tracer->tPTR->getFrames()->size(); } /*! * \brief (Indirect) Wrapper for tracer::Tracer::getFrames * \sa tr_Tracer__getNumFrames */ tr_Frame_t tr_Tracer__getFrame(tr_Tracer_t *tracer, size_t frameNum) { tr_Frame_t frame; memset(&frame, 0, sizeof(frame)); if (!tracer) return frame; auto *frames = tracer->tPTR->getFrames(); if (frameNum >= frames->size()) return frame; auto &f = frames->at(frameNum); frame.frameAddr = f.frameAddr; frame.funcName = f.funcName.c_str(); frame.moduleName = f.moduleName.c_str(); frame.fileName = f.fileName.c_str(); frame.line = f.line; frame.column = f.column; if ((f.flags & FrameFlags::HAS_FUNC_NAME) != FrameFlags::HAS_FUNC_NAME) frame.funcName = nullptr; if ((f.flags & FrameFlags::HAS_MODULE_INFO) != FrameFlags::HAS_MODULE_INFO) frame.moduleName = nullptr; if ((f.flags & FrameFlags::HAS_LINE_INFO) != FrameFlags::HAS_LINE_INFO) frame.fileName = nullptr; return frame; } /*! * \brief (Indirect) Wrapper for tracer::Tracer::getAvailableEngines and tracer::Tracer::getAvailableDebuggers */ tr_Tracer_AvailableEngines_t tr_Tracer__getAvailableEngines() { tr_Tracer_AvailableEngines_t result; memset(&result, 0, sizeof(result)); int c = 0; for (auto i : tracer::Tracer::getAvailableEngines()) { result.tracer[c++] = static_cast<TR_TraceerEngines_t>(i); if (c >= 8) break; } c = 0; for (auto i : tracer::Tracer::getAvailableDebuggers()) { result.debuggers[c++] = static_cast<TR_DebuggerEngines_t>(i); if (c >= 8) break; } return result; } //! \brief Destroyes the private C object and the Tracer C++ object UNLESS tr_getTracerFromVoid was used void tr_freeTracer(tr_Tracer_t *tracer) { if (tracer) delete tracer; } }
31.675676
113
0.715657
mensinda
9e9a7a21b244e330a0fe45bffa695183c9e364d8
2,281
cpp
C++
src/argparse.cpp
The-Compiler/herbstluftwm
a4f13aa299a760841ee204ddb180944bad6ceb2d
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/argparse.cpp
The-Compiler/herbstluftwm
a4f13aa299a760841ee204ddb180944bad6ceb2d
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/argparse.cpp
The-Compiler/herbstluftwm
a4f13aa299a760841ee204ddb180944bad6ceb2d
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#include "argparse.h" #include <iostream> using std::string; /** * @brief try to parse the arguments * @param input * @param output * @return return whether there has been an error (true = error, false = no error) */ bool ArgParse::parsingFails(Input& input, Output& output) { size_t mandatoryArguments = 0; size_t optionalArguments = 0; for (const auto& arg : arguments_) { if (arg.optional_) { optionalArguments++; } else { mandatoryArguments++; } } if (input.size() < mandatoryArguments) { output << input.command() << ": Expected "; if (optionalArguments) { output << "between " << mandatoryArguments << " and " << (optionalArguments + mandatoryArguments) << " arguments"; } else if (mandatoryArguments == 1) { output << "one argument"; } else { output << mandatoryArguments << " arguments"; } output << ", but got only " << input.size() << " arguments."; errorCode_ = HERBST_NEED_MORE_ARGS; return true; } // the number of optional arguments that are provided by 'input': size_t optionalArgumentsRemaining = input.size() - mandatoryArguments; for (const auto& arg : arguments_) { if (arg.optional_) { if (optionalArgumentsRemaining) { optionalArgumentsRemaining--; } else { // skip this argument if it's optional and there // are not more optional arguments in the input continue; } } string valueString; // the following can't fail because we checked input.size() before input >> valueString; try { arg.tryParse_(valueString); } catch (std::exception& e) { output << input.command() << ": Cannot parse argument \"" << valueString << "\": " << e.what() << "\n"; errorCode_ = HERBST_INVALID_ARGUMENT; return true; } } // if all arguments were parsed, then we report that there were // no errors. It's ok if there are remaining elements in 'input' that // have not been parsed. return false; }
33.544118
82
0.55765
The-Compiler
9e9a9292f67c90512d6916416204819b1fb0ae5b
2,837
cpp
C++
Source/AliveLibAO/RollingBallShaker.cpp
THEONLYDarkShadow/alive_reversing
680d87088023f2d5f2a40c42d6543809281374fb
[ "MIT" ]
1
2021-04-11T23:44:43.000Z
2021-04-11T23:44:43.000Z
Source/AliveLibAO/RollingBallShaker.cpp
THEONLYDarkShadow/alive_reversing
680d87088023f2d5f2a40c42d6543809281374fb
[ "MIT" ]
null
null
null
Source/AliveLibAO/RollingBallShaker.cpp
THEONLYDarkShadow/alive_reversing
680d87088023f2d5f2a40c42d6543809281374fb
[ "MIT" ]
null
null
null
#include "stdafx_ao.h" #include "RollingBallShaker.hpp" #include "Function.hpp" #include "Game.hpp" #include "stdlib.hpp" #include "PsxDisplay.hpp" #include "ScreenManager.hpp" #include "Primitives.hpp" void RollingBallShaker_ForceLink() {} namespace AO { const static PSX_Pos16 sRollingBallShakerScreenOffsets_4BB740[18] = { { 1, 0 }, { 0, 0 }, { -1, 1 }, { 0, 0 }, { -1, -1 }, { 0, 0 }, { 1, -1 }, { 0, 0 }, { 0, 1 }, { 0, 0 }, { 1, 0 }, { 0, 0 }, { 1, 1 }, { 0, 0 }, { -1, -1 }, { 0, 0 }, { 0, -1 }, { 0, 0 } }; RollingBallShaker* RollingBallShaker::ctor_4361A0() { ctor_487E10(1); field_6_flags.Set(Options::eDrawable_Bit4); SetVTable(this, 0x4BB788); field_4_typeId = Types::eRollingBallStopperShaker_58; field_30_shake_table_idx = 0; field_32_bKillMe = 0; // Set externally gObjList_drawables_504618->Push_Back(this); return this; } BaseGameObject* RollingBallShaker::dtor_436200() { SetVTable(this, 0x4BB788); gObjList_drawables_504618->Remove_Item(this); return dtor_487DF0(); } void RollingBallShaker::VUpdate_436260() { field_30_shake_table_idx++; if (field_30_shake_table_idx >= ALIVE_COUNTOF(sRollingBallShakerScreenOffsets_4BB740)) { field_30_shake_table_idx = 0; } } void RollingBallShaker::VRender_436280(PrimHeader** ppOt) { Prim_ScreenOffset* pPrim = &field_10_prim_screen_offset[gPsxDisplay_504C78.field_A_buffer_index + 1]; if (field_32_bKillMe != 0) { // Unshake the screen PSX_Pos16 screenOff = {}; if (gPsxDisplay_504C78.field_A_buffer_index) { screenOff.y = gPsxDisplay_504C78.field_2_height; } InitType_ScreenOffset_496000(pPrim, &screenOff); OrderingTable_Add_498A80(OtLayer(ppOt, Layer::eLayer_0), &pPrim->mBase); // Kill yourself field_6_flags.Set(Options::eDead_Bit3); } else { PSX_Pos16 screenOff = sRollingBallShakerScreenOffsets_4BB740[field_30_shake_table_idx]; if (gPsxDisplay_504C78.field_A_buffer_index) { screenOff.y += gPsxDisplay_504C78.field_2_height; } InitType_ScreenOffset_496000(pPrim, &screenOff); OrderingTable_Add_498A80(OtLayer(ppOt, Layer::eLayer_0), &pPrim->mBase); } pScreenManager_4FF7C8->InvalidateRect_406CC0(0, 0, 640, gPsxDisplay_504C78.field_2_height); } BaseGameObject* RollingBallShaker::VDestructor(signed int flags) { return Vdtor_436350(flags); } void RollingBallShaker::VUpdate() { return VUpdate_436260(); } void RollingBallShaker::VRender(PrimHeader** ppOt) { VRender_436280(ppOt); } RollingBallShaker* RollingBallShaker::Vdtor_436350(signed int flags) { dtor_436200(); if (flags & 1) { ao_delete_free_447540(this); } return this; } }
22.696
105
0.670427
THEONLYDarkShadow
9e9bb1d1c9542e659e86698919f1538459c57b57
337
cpp
C++
CodeForces/Complete/700-799/714A-MeetingOldFriends.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/700-799/714A-MeetingOldFriends.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/700-799/714A-MeetingOldFriends.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <cstdio> int main(){ long long l1, r1, l2, r2, k; scanf("%lld %lld %lld %lld %lld", &l1, &r1, &l2, &r2, &k); long long l = (l1 > l2) ? l1 : l2; long long r = (r1 < r2) ? r1 : r2; long long res = r - l + 1; if(l <= k && k <= r){--res;} if(res <= 0){res = 0;} printf("%lld\n", res); return 0; }
22.466667
91
0.454006
Ashwanigupta9125
9e9de3e0c55836644fa4ad9692f6e2948e3c5f59
5,983
cpp
C++
lib/Dialect/TPU/Interpreter/core/csc.cpp
sophgo/tpu_compiler
6299ea0a3adae1e5c206bcb9bedf225d16e636db
[ "Apache-2.0" ]
3
2022-03-14T11:47:20.000Z
2022-03-16T01:45:37.000Z
lib/Dialect/TPU/Interpreter/core/csc.cpp
sophgo/tpu_compiler
6299ea0a3adae1e5c206bcb9bedf225d16e636db
[ "Apache-2.0" ]
null
null
null
lib/Dialect/TPU/Interpreter/core/csc.cpp
sophgo/tpu_compiler
6299ea0a3adae1e5c206bcb9bedf225d16e636db
[ "Apache-2.0" ]
null
null
null
#include "tpuc/Interpreter/cpu/csc.hpp" #include "internal.hpp" #include "tpuc/Dialect/TPU/TPUDialect.h" #include "tpuc/MlirModuleInterpreter.h" static inline int align_up(int x, int n) { if (n == 0 || n == 1) { return x; } return ((x + n - 1) / n) * n; } static inline float UINT8(float data) { return static_cast<float>(F32ToUint8(data, 0)); } namespace mlir { // pixel_type 1--i420 2--nv12 3--nv21 void CscOpKernel::yuv_csc(float *input, float *output, int n, int c, int h, int w, std::vector<int> &order, int quant_type, YuvType pixel_type) { int y_w_aligned = align_up(w, y_align); int uv_w_aligned = 0; int y_offset = 0; int u_offset = 0; int v_offset = 0; if (pixel_type == YUV420_PLANAR) { uv_w_aligned = align_up(w / 2, w_align); u_offset = align_up(h * y_w_aligned, channel_align); v_offset = align_up(u_offset + h / 2 * uv_w_aligned, channel_align); } else { uv_w_aligned = align_up(w, w_align); u_offset = align_up(h * y_w_aligned, channel_align); v_offset = u_offset; } int n_stride = align_up(v_offset + h / 2 * uv_w_aligned, channel_align); for (int idx_n = 0; idx_n < n; idx_n++) { for (int idx_h = 0; idx_h < h; idx_h++) { for (int idx_w = 0; idx_w < w; idx_w++) { int y_idx = y_offset + idx_n * n_stride + idx_h * y_w_aligned + idx_w; int u_idx = 0; int v_idx = 0; if (pixel_type == YUV420_PLANAR) { // i420 u_idx = u_offset + idx_n * n_stride + idx_h / 2 * uv_w_aligned + idx_w / 2; v_idx = v_offset + idx_n * n_stride + idx_h / 2 * uv_w_aligned + idx_w / 2; } else if (pixel_type == YUV_NV12) { //nv12 u_idx = u_offset + idx_n * n_stride + idx_h / 2 * uv_w_aligned + idx_w / 2 * 2; v_idx = v_offset + idx_n * n_stride + idx_h / 2 * uv_w_aligned + idx_w / 2 * 2 + 1; } else { //nv21 u_idx = u_offset + idx_n * n_stride + idx_h / 2 * uv_w_aligned + idx_w / 2 * 2 + 1; v_idx = v_offset + idx_n * n_stride + idx_h / 2 * uv_w_aligned + idx_w / 2 * 2; } float y = input[y_idx]; float u = input[u_idx]; float v = input[v_idx]; float r, g, b; if (quant_type == 0) { y = 1.164 * (y - 16.0f); u -= 128; v -= 128; // float: r = y + 1.596 * v; g = y - 0.813 * v - 0.391 * u; b = y + 2.018 * u; } else { // u8 or bf16 y = (float)(uint8_t)y; u = (float)(uint8_t)u; v = (float)(uint8_t)v; y = BF16(BF16(1.164) * (y - 16.0f)); u -= 128.0f; v -= 128.0f; r = BF16(y + BF16(1.596f) * v); g = BF16(BF16(y + BF16(-0.813f) * v) + BF16(-0.391f) * u); b = BF16(y + BF16(2.018f) * u); } r = UINT8(r); g = UINT8(g); b = UINT8(b); float color[3] = {b, g, r}; int c0_idx = idx_n * 3 * h * w + idx_h * w + idx_w; int c1_idx = c0_idx + h * w; int c2_idx = c1_idx + h * w; output[c0_idx] = color[order[0]]; output[c1_idx] = color[order[1]]; output[c2_idx] = color[order[2]]; } } } } CscOpKernel::CscOpKernel(Operation &op, value_map_t &valueMapping, weight_map_t &weightMapping) : CPUOpKernel(op, valueMapping, weightMapping) { auto cscOp = cast<tpu::CscOp>(op); auto input_type = cscOp.input().getType().template cast<TensorType>(); this->input_shape = input_type.getShape(); this->pixel_format = cscOp.pixel_format().str(); this->aligned = cscOp.aligned(); // get tensors input_data = this->opdTensors[0]; output_data = this->resTensor; w_align = cscOp.w_align(); y_align = cscOp.y_align(); channel_align = cscOp.channel_align(); } void CscOpKernel::invoke() { if (shape.size() < 4 || input_shape.size() < 4) { dump(); llvm_unreachable("wrong shape size"); } int on = shape[0]; int oc = shape[1]; int oh = shape[2]; int ow = shape[3]; int ic = input_shape[1]; int ih = input_shape[2]; if (pixel_format == "YUV420_PLANAR") { std::vector<int> orders{0, 1, 2}; yuv_csc(input_data->data(), output_data->data(), on, oc, oh, ow, orders, datatype == DataType::FP32 ? 0 : 1, YUV420_PLANAR); } else if (pixel_format == "YUV_NV12") { std::vector<int> orders{0, 1, 2}; yuv_csc(input_data->data(), output_data->data(), on, oc, oh, ow, orders, datatype == DataType::FP32 ? 0 : 1, YUV_NV12); } else if (pixel_format == "YUV_NV21") { std::vector<int> orders{0, 1, 2}; yuv_csc(input_data->data(), output_data->data(), on, oc, oh, ow, orders, datatype == DataType::FP32 ? 0 : 1, YUV_NV21); } else if (aligned) { if (pixel_format == "RGB_PLANAR" || pixel_format == "BGR_PLANAR" || pixel_format == "RGBA_PLANAR") { // do stride copy to make data unaligned std::vector<int> indices(4, 0); int iw = align_up(shape[3], w_align); int ic_stride = align_up(iw * shape[2], channel_align); int in_stride = ic_stride * ic; std::vector<int32_t> input_stride = {in_stride, ic_stride, iw, 1}; std::vector<int32_t> output_stride = {ow * oh * oc, ow * oh, ow, 1}; stride_copy(input_data->data(), output_data->data(), shape.data(), input_stride.data(), output_stride.data(), 0, indices.data()); } else { // do crop to make data unaligned std::vector<int64_t> crop_shape(input_shape.begin(), input_shape.end()); crop_shape[3] = (int)(oc * oh * ow / (ic * ih)); std::vector<int> crop_offset{0, 0, 0, 0}; std::vector<int> indices(4, 0); crop(input_data->data(), output_data->data(), input_shape.data(), crop_shape.data(), 0, crop_offset.data(), indices.data()); } } else { output_data->assign(input_data->begin(), input_data->end()); } } } // namespace mlir
36.705521
98
0.563263
sophgo
9e9f8638d6bf5ad630ae93ca7924219572182f61
1,053
cpp
C++
comb_SWEEP_D1_main.cpp
imrehg/bloch
d4920b325b685a0e8842e305f7f9613b6a0fbf42
[ "MIT" ]
2
2016-08-08T12:33:37.000Z
2017-09-15T08:38:55.000Z
comb_SWEEP_D1_main.cpp
imrehg/bloch
d4920b325b685a0e8842e305f7f9613b6a0fbf42
[ "MIT" ]
null
null
null
comb_SWEEP_D1_main.cpp
imrehg/bloch
d4920b325b685a0e8842e305f7f9613b6a0fbf42
[ "MIT" ]
null
null
null
#include "comb.h" int main() { for(int i=0;i<11;i+=1) sweep(30,1000000,10*pow(2,i),1/pow(10,4),0,10,12,10,600,15,0); //sweep steps, total steps, power(uW/cm2),convergence condition,convergence threshold,convergency steps,ADM order,n1 interval,n2 interval,Matrix self multiplication,laser detune //fstream file; //stringstream strstream; //string filename; // //for(int j=2;j<3;j++){ // //filename.clear(); //strstream.clear(); //strstream<<"CenterSweep_"<<j*100000<<"uW.txt"; //strstream>>filename; //cout<<filename.c_str()<<endl; //file.open(filename.c_str(),ios::out | ios::trunc); // // for(int i=-200;i<201;i+=1){ // file<<setiosflags(ios::left)<<setw(30)<<0.0002*i; // file<<setiosflags(ios::left)<<setw(30)<<sweep_single(10.87827848197104833208,100000*j,1/pow(10,4),0,10,12,10,600,15,0.0002*2*pi*i)<<endl; // } // //period, power(uW/cm2),convergence condition,convergence threshold,convergency steps,ADM order,n1 interval,n2 interval,Matrix self multiplication,laser detune //file.close(); // //} return 0; }
29.25
183
0.678063
imrehg
9ea4b8ad82da2c9b3a9535d29b2e02d53215371c
2,723
cpp
C++
Github-Arduino/libraries/ideawu_RTC/base/packet.cpp
famley-richards/Documents-KTibow
b5d2be03ea2f6687cd9d854d9f43ef839a37e275
[ "MIT" ]
null
null
null
Github-Arduino/libraries/ideawu_RTC/base/packet.cpp
famley-richards/Documents-KTibow
b5d2be03ea2f6687cd9d854d9f43ef839a37e275
[ "MIT" ]
null
null
null
Github-Arduino/libraries/ideawu_RTC/base/packet.cpp
famley-richards/Documents-KTibow
b5d2be03ea2f6687cd9d854d9f43ef839a37e275
[ "MIT" ]
null
null
null
#include <stdlib.h> #include "log.h" #include "packet.h" int Packet::parse(){ parsed = true; this->params_.clear(); if(this->len < HEADER_LEN){ return -1; } int size = this->size(); char *head = (char *)this->data(); while(size > 0){ if(head[0] == ' ' || head[0] == '\r'){ head ++; size --; continue; }else if(head[0] == '\n'){ break; } char *body = (char *)memchr(head, ' ', size); if(body == NULL){ return -1; } body ++; int head_len = body - head; if(head[0] < '0' || head[0] > '9'){ log_warn("bad format"); return -1; } char head_str[20]; if(head_len > (int)sizeof(head_str) - 1){ return -1; } memcpy(head_str, head, head_len - 1); // no '\n' head_str[head_len - 1] = '\0'; int body_len = atoi(head_str); if(body_len < 0){ log_warn("bad format"); return -1; } //log_debug("size: %d, head_len: %d, body_len: %d", size, head_len, body_len); size -= head_len + body_len; if(size < 0){ return -1; } this->params_.push_back(Bytes(body, body_len)); head += head_len + body_len; //if(parsed > MAX_PACKET_SIZE){ // log_warn("fd: %d, exceed max packet size, parsed: %d", this->sock, parsed); // return -1; //} } return 1; } int Packet::append(const Bytes &b){ #define MAX_BLOCK_SIZE 10000 #define MAX_BLOCK_SIZE_STR_LEN 5 if(MAX_BLOCK_SIZE_STR_LEN + 2 + b.size() + this->len > MAX_DATA_LEN){ return -1; } char *p = this->buf() + this->len; int size_str_len = sprintf(p, " %d ", b.size()); if(size_str_len < 0){ return -1; } p += size_str_len; memcpy(p, b.data(), b.size()); p += b.size(); int ret = size_str_len + b.size(); this->len += ret; return ret; } int Packet::set_params(const Bytes &b1){ this->len = HEADER_LEN; int ret = 0; int tmp; tmp = this->append(b1); if(tmp == -1){ return -1; } ret += tmp; // add a '\n' to let the packet print-friendly this->buf()[this->len++] = '\n'; return ret; } int Packet::set_params(const Bytes &b1, const Bytes &b2){ this->len = HEADER_LEN; int ret = 0; int tmp; tmp = this->append(b1); if(tmp == -1){ return -1; } ret += tmp; tmp = this->append(b2); if(tmp == -1){ return -1; } ret += tmp; // add a '\n' to let the packet print-friendly this->buf()[this->len++] = '\n'; return ret; } int Packet::set_params(const Bytes &b1, const Bytes &b2, const Bytes &b3){ this->len = HEADER_LEN; int ret = 0; int tmp; tmp = this->append(b1); if(tmp == -1){ return -1; } ret += tmp; tmp = this->append(b2); if(tmp == -1){ return -1; } ret += tmp; tmp = this->append(b3); if(tmp == -1){ return -1; } ret += tmp; // add a '\n' to let the packet print-friendly this->buf()[this->len++] = '\n'; return ret; }
18.909722
81
0.573265
famley-richards
9ea812a3010535aa59762748ff0aa6ef36e1d939
1,554
cpp
C++
src/factory/font.cpp
equal-games/equal
acaf0d456d7b996dd2a6bc23150cd45ddf618296
[ "BSD-2-Clause", "Apache-2.0" ]
7
2019-08-07T21:27:27.000Z
2020-11-27T16:33:16.000Z
src/factory/font.cpp
equal-games/equal
acaf0d456d7b996dd2a6bc23150cd45ddf618296
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
src/factory/font.cpp
equal-games/equal
acaf0d456d7b996dd2a6bc23150cd45ddf618296
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Equal Games * 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 <equal/core/logger.hpp> #include <equal/factory/dat.hpp> #include <equal/factory/font.hpp> #include <equal/helper/error.hpp> #include <equal/helper/string.hpp> #include <equal/helper/system.hpp> #ifdef EQ_SDL #include <SDL2/SDL_ttf.h> #endif namespace eq { std::unordered_map<std::string, Font *> LoadFontFromDAT() { std::unordered_map<std::string, Font *> fonts; ResourceDAT res; ReadDAT<ResourceDAT>("resources", res); for (auto &font_dat : res.fonts) { Font *font = new Font(); font->name = fmt::format("{0}_{1}", font_dat.name, 16); #ifdef EQ_SDL TTF_Font *sdl_font = TTF_OpenFontRW(SDL_RWFromMem(font_dat.buffer.data(), font_dat.buffer.size()), 1, 16); if (!sdl_font) { TTF_CloseFont(sdl_font); EQ_THROW("Can't load font({}): {}", font->name, TTF_GetError()); } font->data = static_cast<void *>(sdl_font); #endif fonts.try_emplace(font->name, font); } return fonts; } } // namespace eq
28.254545
110
0.698198
equal-games
9ea8d3c8220c1d7b5590f4de0745222909c735b4
5,155
cpp
C++
Qt_GUI/DisplayPanelWidget.cpp
SDUBigDataCourse/RecursiveSubdivision-basedSampling
a187eabe37e64312b326461d29800f1aff25371c
[ "MIT" ]
5
2020-10-26T09:42:16.000Z
2022-02-16T10:36:24.000Z
Qt_GUI/DisplayPanelWidget.cpp
Ideas-Laboratory/RecursiveSubdivision-basedSampling
2b8cbae9cb72a05089ace5ccee4745d33121d60f
[ "MIT" ]
null
null
null
Qt_GUI/DisplayPanelWidget.cpp
Ideas-Laboratory/RecursiveSubdivision-basedSampling
2b8cbae9cb72a05089ace5ccee4745d33121d60f
[ "MIT" ]
2
2019-09-09T08:01:37.000Z
2019-12-01T03:36:47.000Z
#include "DisplayPanelWidget.h" using namespace std; DisplayPanelWidget::DisplayPanelWidget(SamplingProcessViewer *spv, unordered_map<uint, string> *c2l_mapping, QWidget * parent) : QWidget(parent), viewer(spv), class2label(c2l_mapping) { setFixedWidth(440); container = dynamic_cast<QScrollArea*>(parent); QVBoxLayout *layout = new QVBoxLayout(this); layout->setAlignment(Qt::AlignTop); setLayout(layout); addClassToColorMappingTable(); connect(spv, &SamplingProcessViewer::inputImageChanged, [this]() { clearAllChildren(); addClassToColorMappingTable(); }); connect(spv, &SamplingProcessViewer::areaCreated, [this](IndividualSampleArea* area) { addAreaInfo("r", area->getTotalInfo(), area->getSampleInfo()); }); connect(spv, &SamplingProcessViewer::areaCounted, [this](StatisticalInfo* total_info, StatisticalInfo* sample_info) { addAreaInfo("o", total_info, sample_info); }); connect(spv, &SamplingProcessViewer::adjustmentStart, [this]() { removeSpecifiedChildren([](QWidget* w) { return w->objectName() == "o"; }); }); connect(spv, &SamplingProcessViewer::sampleStart, [this]() { removeSpecifiedChildren([](QWidget* w) { return !w->objectName().isEmpty(); }); }); connect(spv, &SamplingProcessViewer::redrawStart, [this]() { removeSpecifiedChildren([](QWidget* w) { return !w->objectName().isEmpty(); }); }); //connect(spv, &SamplingProcessViewer::pointSelected, [this](uint index, uint class_) { // qDebug() << index << ',' << QString(this->class2label->at(class_).c_str()); //}); } void DisplayPanelWidget::resizeEvent(QResizeEvent * e) { QWidget::resizeEvent(e); container->verticalScrollBar()->setValue(height()); } void DisplayPanelWidget::addClassToColorMappingTable() { QGroupBox *mapping_box = new QGroupBox("Class to Color mapping:", this); QVBoxLayout *box_layout = new QVBoxLayout(mapping_box); mapping_box->setLayout(box_layout); QTableWidget *tw = new QTableWidget(this); tw->setShowGrid(false); tw->setEditTriggers(QAbstractItemView::NoEditTriggers); tw->verticalHeader()->setVisible(false); tw->setRowCount(class2label->size()); tw->setColumnCount(2); tw->setHorizontalHeaderLabels(QStringList{ "Class", "Color" }); tw->setColumnWidth(0, 300); tw->setColumnWidth(1, 70); int rows = 0; for (auto &pr : *class2label) { QTableWidgetItem *newItem = new QTableWidgetItem(tr(pr.second.c_str())); tw->setItem(rows, 0, newItem); newItem = new QTableWidgetItem(); newItem->setBackground(this->viewer->getColorBrushes()[pr.first]); tw->setItem(rows, 1, newItem); ++rows; } tw->setRowCount(rows); box_layout->addWidget(tw); mapping_box->setFixedHeight(tw->horizontalHeader()->height() + 60 + tw->rowHeight(0)*rows); this->layout()->addWidget(mapping_box); } void DisplayPanelWidget::addAreaInfo(const QString& name, StatisticalInfo * total_info, StatisticalInfo * sample_info) { if (total_info->total_num > 0) { QTableWidget *tw = new QTableWidget(this); tw->setObjectName(name); tw->setEditTriggers(QAbstractItemView::NoEditTriggers); tw->verticalHeader()->setVisible(false); tw->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); tw->setRowCount(total_info->class_point_num.size() + 1); tw->setColumnCount(4); tw->setHorizontalHeaderLabels(QStringList{ "", "Actual", "Sample", "Ratio" }); tw->setColumnWidth(0, 70); auto &map_t = total_info->class_point_num, &map_s = sample_info->class_point_num; int rows = 0; for (int i = 0, sz = selected_class_order.size(); i < sz; ++i) { int class_index = selected_class_order[i]; if (map_t.find(class_index) != map_t.end()) { QTableWidgetItem *newItem = new QTableWidgetItem(); newItem->setBackground(this->viewer->getColorBrushes()[class_index]); tw->setItem(rows, 0, newItem); newItem = new QTableWidgetItem(QString::number(map_t[class_index])); tw->setItem(rows, 1, newItem); uint sample_num = map_s.find(class_index) != map_s.end() ? map_s[class_index] : 0; newItem = new QTableWidgetItem(QString::number(sample_num)); tw->setItem(rows, 2, newItem); newItem = new QTableWidgetItem(QString::number(100.0*sample_num/map_t[class_index], 'f', 2) + "%"); tw->setItem(rows, 3, newItem); ++rows; } } tw->setItem(rows, 0, new QTableWidgetItem(tr("Sum:"))); tw->setItem(rows, 1, new QTableWidgetItem(QString::number(total_info->total_num))); tw->setItem(rows, 2, new QTableWidgetItem(QString::number(sample_info->total_num))); tw->setItem(rows, 3, new QTableWidgetItem(QString::number(100.0*sample_info->total_num/total_info->total_num, 'f', 2) + "%")); tw->setRowCount(++rows); tw->setFixedHeight(tw->horizontalHeader()->height() + 4 + tw->rowHeight(0)*rows); this->layout()->addWidget(tw); } delete total_info; delete sample_info; } void DisplayPanelWidget::removeSpecifiedChildren(std::function<bool(QWidget*)> pred) { for (int i = this->layout()->count() - 1; i > -1; --i) { QWidget *w = this->layout()->itemAt(i)->widget(); if (pred(w)) { this->layout()->removeWidget(w); w->close(); } } } void DisplayPanelWidget::clearAllChildren() { removeSpecifiedChildren([](QWidget* w) { return true; }); }
37.627737
183
0.711542
SDUBigDataCourse
9ea910c3b6479e86e3bac33e8e3cb5d3b2af02b2
2,015
cpp
C++
JayEngine/Jay_Engine/UI_Hierarchy.cpp
Josef212/JayEngine
437faf3c81eb9c13bb99a104338c7de4434323c6
[ "MIT" ]
null
null
null
JayEngine/Jay_Engine/UI_Hierarchy.cpp
Josef212/JayEngine
437faf3c81eb9c13bb99a104338c7de4434323c6
[ "MIT" ]
2
2016-09-27T09:29:06.000Z
2016-11-02T09:42:13.000Z
JayEngine/Jay_Engine/UI_Hierarchy.cpp
Josef212/JayEngine
437faf3c81eb9c13bb99a104338c7de4434323c6
[ "MIT" ]
null
null
null
#include "Application.h" #include "UI_Hierarchy.h" #include "ModuleGOManager.h" #include "GameObject.h" #include "Component.h" #include "Transform.h" #include "Mesh.h" #include "Material.h" #include "ModuleWindow.h" UI_Hierarchy::UI_Hierarchy(bool startEnalbed) : UI_Panel(startEnalbed) { } UI_Hierarchy::~UI_Hierarchy() { } void UI_Hierarchy::Draw() { int w = app->window->GetWidth(); int h = app->window->GetHeight(); //ImGui::SetNextWindowPos(ImVec2(0, 20)); //ImGui::SetNextWindowSize(ImVec2(360, 560)); ImGui::SetNextWindowPos(ImVec2(0, 20)); ImGui::SetNextWindowSize(ImVec2(w*0.2, (h -20)*0.5)); ImGui::Begin("Hierarchy", &active); { GameObject* root = app->goManager->GetSceneroot(); GameObject* selected = app->goManager->GetSelected(); ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; if (!selected) nodeFlags |= ImGuiTreeNodeFlags_Selected; if (ImGui::TreeNodeEx("Scene", nodeFlags)) { ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize() * 3); // Increase spacing to differentiate leaves from expanded contents. if (ImGui::IsItemClicked()) app->goManager->Select(nullptr); if (root) { for (uint i = 0; i < root->childs.size(); ++i) HierarchyRecursive(root->childs[i], selected); } ImGui::PopStyleVar(); ImGui::TreePop(); } ImGui::End(); } } void UI_Hierarchy::HierarchyRecursive(GameObject* node, GameObject* selected) { ImGuiTreeNodeFlags nodeFlags = 0; if (node == selected) nodeFlags |= ImGuiTreeNodeFlags_Selected; if (node->childs.size() > 0) { nodeFlags |= ImGuiTreeNodeFlags_OpenOnArrow; nodeFlags |= ImGuiTreeNodeFlags_OpenOnDoubleClick; } else nodeFlags |= ImGuiTreeNodeFlags_Leaf; if (ImGui::TreeNodeEx(node->GetName(), nodeFlags)) { if (ImGui::IsItemClicked()) app->goManager->Select(node); for (uint i = 0; i < node->childs.size(); ++i) { HierarchyRecursive(node->childs[i], selected); } ImGui::TreePop(); } }
23.430233
146
0.701241
Josef212
9ea93736a1011d8434627a70580108e9b05f012d
270
hpp
C++
include/RED4ext/Scripting/Natives/Generated/quest/QuickItemsSet.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/quest/QuickItemsSet.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/quest/QuickItemsSet.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> namespace RED4ext { namespace quest { enum class QuickItemsSet : uint32_t { Q001_Kereznikov_Heal_Phone = 0, Q003_All = 1, }; } // namespace quest } // namespace RED4ext
16.875
57
0.722222
jackhumbert