blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
541cc7132775110dec219e5dc65eeebd54460569
0069bbe33092a7706d3f20778a289fb4977ee2af
/SonyCamera_Library/stdafx.cpp
dc8828b9dda6e1fba60506e334696ee97b7cf8b4
[]
no_license
YangQun1/SonyCamera
c0560fd6a502d0405e36172a58cf964d2e00ee2f
c070b7c984f4bcc2dfa012d98b28ef1a68925a9b
refs/heads/master
2020-03-22T23:33:33.311339
2018-11-16T08:48:02
2018-11-16T08:48:02
140,817,390
2
2
null
null
null
null
GB18030
C++
false
false
271
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // SonyCamera_Library.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" // TODO: 在 STDAFX.H 中 // 引用任何所需的附加头文件,而不是在此文件中引用
[ "1921296014@qq.com" ]
1921296014@qq.com
cba5ebca6e2c600f6567b6fcb7371bff60eaa2f3
96811480cd9a58340343eebc4768e08f517bfe52
/Data Structures and Algorithms/Sorts/mergeSortManyVectors.cpp
b7029f09da306c7c40af3b73184d133b198ea1d4
[]
no_license
vesk4000/Informatics
1b34deadadc4d76196be6b460575a4366c39d059
a3dbe2c94349ab6c5a0739e4309869aad5a4341a
refs/heads/master
2022-03-30T10:15:31.831411
2022-02-05T17:11:26
2022-02-05T17:11:26
125,365,027
0
0
null
null
null
null
UTF-8
C++
false
false
1,466
cpp
#include <iostream> #include <queue> #include <vector> using namespace std; vector <int> msMerge(vector <int> q1, vector <int> q2) { vector <int> res; while(q1.size() != 0 || q2.size() != 0) { if(q1.size() == 0) { res.push_back(q2.front()); q2.erase(q2.begin()); } else if(q2.size() == 0) { res.push_back(q1.front()); q1.erase(q1.begin()); } else if(q2.front() < q1.front()) { res.push_back(q2.front()); q2.erase(q2.begin()); } else { res.push_back(q1.front()); q1.erase(q1.begin()); } } return res; } vector <int> mergeSort(vector <vector <int> > qs) { vector <vector <int> > result; for(int i = 0;i < qs.size(); i += 2) { vector <int> mergeResult; if(i != qs.size() - 1) mergeResult = msMerge(qs[i], qs[i + 1]); else { vector <int> empt; mergeResult = msMerge(qs[i], empt); } result.push_back(mergeResult); } if(result.size() == 1) return result[0]; else return mergeSort(result); } int main() { vector <int> q; int n; cin >> n; for(int i = 0;i < n; ++i) { int a; cin >> a; q.push_back(a); } vector <vector <int> > qi; vector <int> nq = q; while(nq.size()) { vector <int> tq; tq.push_back(nq[0]); nq.erase(nq.begin()); qi.push_back(tq); } vector <int> result; result = mergeSort(qi); for(int i = 0;i < result.size(); ++i) cout << result[i] << endl; return 0; }
[ "veskmail@gmail.com" ]
veskmail@gmail.com
1f95ff5c7e55f7642a318e81157fff8a0c3c056e
a9c65965f344b07b2d7982610542178d35d1eedc
/templates/main.cpp.log.tpl
f33a3fa176ea1be6f8caf136997b86fe65a940c2
[]
no_license
iuyo5678/emacs_config
b788732e5b0d02a75023a9609336814ddd20d796
ec9575cc20eb944fa71b028d545813d7098a61b8
refs/heads/master
2023-07-29T15:11:43.169290
2023-07-18T10:07:03
2023-07-18T10:07:03
13,983,356
3
1
null
null
null
null
UTF-8
C++
false
false
1,815
tpl
/* -*- C++ -*- */ // Time-stamp: <2013-09-06 00:42:33 Friday by zhangguhua> /** * @file (>>>FILE<<<) * @author (>>>USER_NAME<<<) */ #include <stdlib.h> #include <getopt.h> #include <iostream> #include <log4cxx/logger.h> using namespace std; using namespace log4cxx; static void usage(int code = 1); static LoggerPtr logger = Logger::getLogger(""); int main(int argc, char * argv[]) { int opt = 0; int longindex = 0; const char optstring[] = ":h"; const option longopts[] = {{"help", no_argument, NULL, 'h'}, {NULL , no_argument, NULL, 0}}; std::string arg; while ((opt = getopt_long_only(argc, argv, optstring, longopts, &longindex)) != -1) { switch(opt) { case 'h': usage(0); break; case ':': arg = argv[optind-1]; LOG4CXX_ERROR(logger, std::string("Option `")+arg+"' need argument.\n"); usage(); break; case '?': LOG4CXX_WARN(logger, std::string("Invalid option `")+argv[optind-1]+"'.\n"); usage(); break; } } // other non-option arguments for (int i = optind; i < argc; i++) { std::cout << argv[i] << std::endl; } return 0; } void usage(int code /* = 1 */) { std::ostream * os = NULL; if (code != 0) { os = &std::cerr; } else { os = &std::cout; } *os << "usage: " << PROGRAM_NAME << " [OPTIONS]\n" << std::endl; *os << "This program .\n" << std::endl; *os << "Options:" << std::endl; *os << "\t-h, --help" << std::endl; *os << "\t\tOutput this help." << std::endl; *os << std::endl; *os << "Last Make: " << __DATE__ << " " << __TIME__ << "." << std::endl; exit(code); }
[ "iuyo5678@gmail.com" ]
iuyo5678@gmail.com
236929f4ac20eac885750ca4f0351dbc04b5531b
4af5c63f5801b8d5d356a53bca20178b7832317b
/JZO_ASCII_ROUGELIKE/src/Camera/Camera.cpp
0a5ba8d6d60a914b3ef0487d951183574e819b2c
[]
no_license
Kacp3r3/ASCII_RPG
31530c46e0e00f28f41240b9c9b44177d271befc
91f1d6132a9d8b664e1f012682c058b2ce6c7bd2
refs/heads/master
2020-05-26T23:53:23.697341
2019-05-30T20:37:05
2019-05-30T20:37:05
188,416,129
0
0
null
null
null
null
UTF-8
C++
false
false
269
cpp
#include "Camera.h" Camera::Camera(double width, double height) : wFov(width,height) { } Camera::~Camera() { } Vec2d Camera::getFov() { return wFov; } void Camera::adjustFov(double w, double h) { if (wFov._x > w) wFov._x = w; if (wFov._y > h) wFov._y = h; }
[ "kacper.sawicki.it@gmail.com" ]
kacper.sawicki.it@gmail.com
af88fc5a7ff818db11b45ad5a05bf4fdc001a841
bc997f47b4cffef395f0ce85d72f113ceb1466e6
/KOI/koi09c.cpp
d0b7a916bf04ca4950715ecf39dabdce3b6f57d8
[ "LicenseRef-scancode-public-domain" ]
permissive
koosaga/olympiad
1f069dd480004c9df033b73d87004b765d77d622
fcb87b58dc8b5715b3ae2fac788bd1b7cac9bffe
refs/heads/master
2023-09-01T07:37:45.168803
2023-08-31T14:18:03
2023-08-31T14:18:03
45,691,895
246
49
null
2020-10-20T16:52:45
2015-11-06T16:01:57
C++
UTF-8
C++
false
false
4,015
cpp
#include <bits/stdc++.h> #define sz(v) ((int)(v).size()) #define all(v) (v).begin(), (v).end() using namespace std; typedef long long lint; typedef pair<lint, lint> pi; const int mod = 1e9 + 7; int n, k; vector<vector<pi>> gph; vector<int> deg; vector<int> ans; pi dfs(int x, int p = -1){ lint closest = 1e18; lint farthest = 0; for(auto &[w, y] : gph[x]){ if(deg[y] || y == p) continue; auto sln = dfs(y, x); if(sln.first == 0){ // covered // closest covering ones closest = min(closest, sln.second + w); } else{ if(sln.second + w > k){ // should cover. ans.push_back(y); closest = min(closest, w); } else{ // farthest uncovered farthest = max(farthest, sln.second + w); } } } if(closest + farthest <= k) return pi(0, closest); return pi(1, farthest); } vector<int> vtx, edg; bool trial(lint x){ k = x; ans.clear(); vector<pi> intv; for(int i = 0; i < sz(vtx); i++){ intv.push_back(dfs(vtx[i])); } if(sz(ans) > 2) return 0; vector<int> rel_pos(sz(vtx) * 2); vector<int> covered(sz(vtx)); for(int i = 1; i < sz(rel_pos); i++){ rel_pos[i] = rel_pos[i - 1] + edg[(i - 1) % sz(vtx)]; } int csum = accumulate(all(edg), 0); for(int i = 0; i < sz(vtx); i++){ if(intv[i].first == 0){ for(int j = 0; j < sz(vtx); j++){ int d = abs(rel_pos[j] - rel_pos[i]); d = min(d, csum - d); if(intv[j].first == 1) d += intv[j].second; if(d <= k - intv[i].second) covered[j] = 1; } } } vector<pi> v; for(int i = 0; i < sz(vtx); i++){ if(covered[i] == 0){ assert(intv[i].first == 1); if(sz(ans) == 2) return 0; int r = upper_bound(all(rel_pos), rel_pos[i] + k - intv[i].second) - rel_pos.begin() - 1; int l = lower_bound(all(rel_pos), rel_pos[i + sz(vtx)] - k + intv[i].second) - rel_pos.begin(); l -= sz(vtx); if(r - l + 1 >= sz(vtx)) continue; l += sz(vtx); l %= sz(vtx); r += sz(vtx); r %= sz(vtx); v.emplace_back(l, r); } } if(sz(ans) == 2){ if(sz(v)) return 0; return 1; } vector<int> nxt(sz(vtx) * 2, 1e9); for(auto &[x, y] : v){ if(x <= y){ nxt[x] = min(nxt[x], (int)y); nxt[x + sz(vtx)] = min(nxt[x + sz(vtx)], (int)y + sz(vtx)); } else{ nxt[x] = min(nxt[x], (int)y + sz(vtx)); } } for(int i = sz(nxt) - 2; i >= 0; i--) nxt[i] = min(nxt[i], nxt[i + 1]); if(sz(ans) == 0){ for(int i = 0; i < sz(vtx); i++){ if(nxt[i + 1] >= i + sz(vtx)){ ans.push_back(vtx[i]); ans.push_back(vtx[(i + 1) % sz(vtx)]); return 1; } int j = nxt[i + 1]; if(nxt[j + 1] >= i + sz(vtx)){ ans.push_back(vtx[i]); ans.push_back(vtx[j % sz(vtx)]); return 1; } } return 0; } if(sz(ans) == 1){ for(int i = 0; i < sz(vtx); i++){ if(nxt[i + 1] >= i + sz(vtx)){ ans.push_back(vtx[i]); return 1; } } return 0; } assert(0); } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; deg.resize(n); gph.resize(n); for(int i = 0; i < n; i++){ int s, e, x; cin >> s >> e >> x; s--; e--; gph[s].emplace_back(x, e); gph[e].emplace_back(x, s); deg[s]++; deg[e]++; } { queue<int> que; for(int i = 0; i < n; i++){ if(deg[i] == 1) que.push(i); } while(sz(que)){ int x = que.front(); que.pop(); for(auto &[w, y] : gph[x]){ if(deg[y]){ deg[y]--; deg[x]--; if(deg[y] == 1) que.push(y); } } } for(int i = 0; i < n; i++){ if(deg[i]){ for(int j = i; j != -1; ){ vtx.push_back(j); int nxt = -1; for(auto &[w, k] : gph[j]){ if(deg[k]){ nxt = k; edg.push_back(w); } } deg[j] = 0; j = nxt; } rotate(edg.begin(), edg.begin() + 1, edg.end()); for(auto &i : vtx) deg[i] = 1; break; } } } // for(auto &i : vtx) cout << i << " "; // cout << endl; // for(auto &i : edg) cout << i << " "; // cout << endl; lint s = 0, e = 5e8; while(s != e){ lint m = (s + e) / 2; if(trial(m)) e = m; else s = m + 1; } trial(s); cout << ans[0]+1 << " " << ans[1]+1 << "\n" << s << endl; }
[ "koosaga@gmail.com" ]
koosaga@gmail.com
94c97ff0388aca6005a7bbcde078c97e9b00d81b
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/tsf/src/v20180326/model/DescribeInvocationMetricScatterPlotRequest.cpp
aae356a63659c9ee12e94beb908cceb8f2ff17bb
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp
9f5df8220eaaf72f7eaee07b2ede94f89313651f
42a76b812b81d1b52ec6a217fafc8faa135e06ca
refs/heads/master
2023-08-30T03:22:45.269556
2023-08-30T00:45:39
2023-08-30T00:45:39
188,991,963
55
37
Apache-2.0
2023-08-17T03:13:20
2019-05-28T08:56:08
C++
UTF-8
C++
false
false
6,025
cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/tsf/v20180326/model/DescribeInvocationMetricScatterPlotRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Tsf::V20180326::Model; using namespace std; DescribeInvocationMetricScatterPlotRequest::DescribeInvocationMetricScatterPlotRequest() : m_startTimeHasBeenSet(false), m_endTimeHasBeenSet(false), m_periodHasBeenSet(false), m_metricDimensionsHasBeenSet(false), m_metricsHasBeenSet(false), m_kindHasBeenSet(false) { } string DescribeInvocationMetricScatterPlotRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_startTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "StartTime"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_startTime.c_str(), allocator).Move(), allocator); } if (m_endTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "EndTime"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_endTime.c_str(), allocator).Move(), allocator); } if (m_periodHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Period"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_period, allocator); } if (m_metricDimensionsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "MetricDimensions"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_metricDimensions.begin(); itr != m_metricDimensions.end(); ++itr, ++i) { d[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(d[key.c_str()][i], allocator); } } if (m_metricsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Metrics"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_metrics.begin(); itr != m_metrics.end(); ++itr, ++i) { d[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(d[key.c_str()][i], allocator); } } if (m_kindHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Kind"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_kind.c_str(), allocator).Move(), allocator); } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string DescribeInvocationMetricScatterPlotRequest::GetStartTime() const { return m_startTime; } void DescribeInvocationMetricScatterPlotRequest::SetStartTime(const string& _startTime) { m_startTime = _startTime; m_startTimeHasBeenSet = true; } bool DescribeInvocationMetricScatterPlotRequest::StartTimeHasBeenSet() const { return m_startTimeHasBeenSet; } string DescribeInvocationMetricScatterPlotRequest::GetEndTime() const { return m_endTime; } void DescribeInvocationMetricScatterPlotRequest::SetEndTime(const string& _endTime) { m_endTime = _endTime; m_endTimeHasBeenSet = true; } bool DescribeInvocationMetricScatterPlotRequest::EndTimeHasBeenSet() const { return m_endTimeHasBeenSet; } int64_t DescribeInvocationMetricScatterPlotRequest::GetPeriod() const { return m_period; } void DescribeInvocationMetricScatterPlotRequest::SetPeriod(const int64_t& _period) { m_period = _period; m_periodHasBeenSet = true; } bool DescribeInvocationMetricScatterPlotRequest::PeriodHasBeenSet() const { return m_periodHasBeenSet; } vector<MetricDimension> DescribeInvocationMetricScatterPlotRequest::GetMetricDimensions() const { return m_metricDimensions; } void DescribeInvocationMetricScatterPlotRequest::SetMetricDimensions(const vector<MetricDimension>& _metricDimensions) { m_metricDimensions = _metricDimensions; m_metricDimensionsHasBeenSet = true; } bool DescribeInvocationMetricScatterPlotRequest::MetricDimensionsHasBeenSet() const { return m_metricDimensionsHasBeenSet; } vector<Metric> DescribeInvocationMetricScatterPlotRequest::GetMetrics() const { return m_metrics; } void DescribeInvocationMetricScatterPlotRequest::SetMetrics(const vector<Metric>& _metrics) { m_metrics = _metrics; m_metricsHasBeenSet = true; } bool DescribeInvocationMetricScatterPlotRequest::MetricsHasBeenSet() const { return m_metricsHasBeenSet; } string DescribeInvocationMetricScatterPlotRequest::GetKind() const { return m_kind; } void DescribeInvocationMetricScatterPlotRequest::SetKind(const string& _kind) { m_kind = _kind; m_kindHasBeenSet = true; } bool DescribeInvocationMetricScatterPlotRequest::KindHasBeenSet() const { return m_kindHasBeenSet; }
[ "tencentcloudapi@tencent.com" ]
tencentcloudapi@tencent.com
a9c7e77dd24a0570b1b1391c150550f806b3c652
dff8a221638932704df714b30df53de003342571
/code_modified_20150323/6/33.cpp
2bb16f7fd42f7abd6c2a7b9eacd719ac8e51ed5a
[]
no_license
DevinChang/cpp
1327da268cbbde4981c055c2e98301d63e9ca46b
f35ee6f7b2d9217bd2d40db55a697330aeffc7e8
refs/heads/master
2021-01-20T13:55:55.399888
2017-05-18T08:01:15
2017-05-18T08:01:15
90,538,499
3
0
null
null
null
null
UTF-8
C++
false
false
395
cpp
#include <iostream> #include <vector> using namespace std; //递归函数输出vector<int>的内容 void print(vector<int> vInt, unsigned index) { unsigned sz = vInt.size(); if (!vInt.empty() && index < sz) { cout << vInt[index] << endl; print(vInt, index + 1); } } int main() { vector<int> v = {1, 3, 5, 7, 9, 11, 13, 15}; print(v, 0); return 0; }
[ "DevinChang@126.com" ]
DevinChang@126.com
7bf2ba699a257803ada63097d99423bc0e542e0a
bae3cce507524b9d5b1f5fc5d3a3bb489f95b8df
/Contests/Codeforces/Ed-R-106/1499E.cpp
2e0a36e7d3ffeb8e1bb7bf672d3937c793ca886d
[]
no_license
tauhrick/Competitive-Programming
487e0221e29e8f28f1d5b65db06271f585541df8
abcdb18c3e0c48ea576c8b37f7db80c7807cd04c
refs/heads/master
2023-07-11T05:37:28.700431
2021-08-30T15:40:12
2021-08-30T15:40:12
193,487,394
0
0
null
null
null
null
UTF-8
C++
false
false
3,553
cpp
#ifndef LOCAL #include <bits/stdc++.h> using namespace std; #define debug(...) 42 #else #include "Debug.hpp" #endif template <uint32_t mod> class Modular { public: Modular(int64_t _n = 0) : n(uint32_t((_n >= 0 ? _n : mod - (-_n) % mod) % mod)) {} uint32_t get() const { return n; } bool operator==(const Modular &o) const { return n == o.n; } bool operator!=(const Modular &o) const { return n != o.n; } Modular& operator/=(const Modular &o) { return (*this) *= o.inv(); } Modular operator+(const Modular &o) const { return Modular(*this) += o; } Modular operator-(const Modular &o) const { return Modular(*this) -= o; } Modular operator*(const Modular &o) const { return Modular(*this) *= o; } Modular operator/(const Modular &o) const { return Modular(*this) /= o; } friend string to_string(const Modular &m) { return to_string(m.get()); } Modular& operator+=(const Modular &o) { n += o.n; n = (n < mod ? n : n - mod); return *this; } Modular& operator-=(const Modular &o) { n += mod - o.n; n = (n < mod ? n : n - mod); return *this; } Modular& operator*=(const Modular &o) { n = uint32_t(uint64_t(n) * o.n % mod); return *this; } Modular pow(uint64_t b) const { Modular ans(1), m = Modular(*this); while (b) { if (b & 1) { ans *= m; } m *= m; b >>= 1; } return ans; } Modular inv() const { int32_t a = n, b = mod, u = 0, v = 1; while (a) { int32_t t = b / a; b -= t * a; swap(a, b); u -= t * v; swap(u, v); } assert(b == 1); return Modular(u); } private: uint32_t n; }; class Task { public: void Perform() { Read(); Solve(); } private: using Mint = Modular<998244353>; string x, y; void Read() { cin >> x >> y; } int len_x, len_y; vector<vector<vector<Mint>>> dp; vector<vector<vector<int>>> seen; void Solve() { len_x = int(x.size()), len_y = int(y.size()); dp = vector(len_x + 1, vector(len_y + 1, vector(5, Mint(0)))); seen = vector(len_x + 1, vector(len_y + 1, vector(5, 0))); Mint res; for (int st_x = 0; st_x < len_x; ++st_x) { for (int st_y = 0; st_y < len_y; ++st_y) { res += Get(st_x, st_y, 0); } } cout << res.get() << '\n'; } Mint Get(int ind_x, int ind_y, int last_taken) { if (make_pair(ind_x, ind_y) == make_pair(len_x, len_y)) return Mint(0); auto &ans = dp[ind_x][ind_y][last_taken]; auto &vis = seen[ind_x][ind_y][last_taken]; if (!vis) { vis = true; if (last_taken == 0) { ans += Get(ind_x + 1, ind_y, 1); ans += Get(ind_x, ind_y + 1, 2); } else { char prv = (last_taken == 1 || last_taken == 3 ? x[ind_x - 1] : y[ind_y - 1]); if (last_taken == 1) { if (ind_x < len_x && x[ind_x] != prv) ans += Get(ind_x + 1, ind_y, 1); if (ind_y < len_y && y[ind_y] != prv) ans += Mint(1) + Get(ind_x, ind_y + 1, 4); } else if (last_taken == 2) { if (ind_x < len_x && x[ind_x] != prv) ans += Mint(1) + Get(ind_x + 1, ind_y, 3); if (ind_y < len_y && y[ind_y] != prv) ans += Get(ind_x, ind_y + 1, 2); } else { if (ind_x < len_x && x[ind_x] != prv) ans += Mint(1) + Get(ind_x + 1, ind_y, 3); if (ind_y < len_y && y[ind_y] != prv) ans += Mint(1) + Get(ind_x, ind_y + 1, 4); } } } return ans; } }; int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr); Task t; t.Perform(); return 0; }
[ "chirag11032000@gmail.com" ]
chirag11032000@gmail.com
dd07b2f25d2624469dfd58789a191a1844caec82
260e5dec446d12a7dd3f32e331c1fde8157e5cea
/Indi/SDK/Indi_0701_MardetReinforcements_classes.hpp
ae87ebb633b55baee99ecaf7843d9aa6a47c9f2a
[]
no_license
jfmherokiller/TheOuterWorldsSdkDump
6e140fde4fcd1cade94ce0d7ea69f8a3f769e1c0
18a8c6b1f5d87bb1ad4334be4a9f22c52897f640
refs/heads/main
2023-08-30T09:27:17.723265
2021-09-17T00:24:52
2021-09-17T00:24:52
407,437,218
0
0
null
null
null
null
UTF-8
C++
false
false
720
hpp
#pragma once // TheOuterWorlds SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "Indi_0701_MardetReinforcements_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass 0701_MardetReinforcements.0701_MardetReinforcements_C // 0x0000 (0x0238 - 0x0238) class U0701_MardetReinforcements_C : public UTeamData { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass 0701_MardetReinforcements.0701_MardetReinforcements_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "peterpan0413@live.com" ]
peterpan0413@live.com
901eb5e863a929b5781e8dd73efe03c5845c3daa
fcc170818be293fbf648e9301f39ac13631ed7cc
/AllInOne/PushFramework/include/BroadcastManager.h
db9a0c67b5c1844f422a5ab0b3ed9d5752d0f696
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
zj19880805/HBnews
92f933ca3b4e971af6b98c544b0f42f261e1d6ea
8bdb29b85c2047f3d3709511b10b580b65b48756
refs/heads/master
2021-01-10T21:26:17.860116
2012-08-09T15:46:03
2012-08-09T15:46:03
5,325,350
1
0
null
null
null
null
UTF-8
C++
false
false
4,191
h
/******************************************************************** File : BroadcastManager.h Creation date : 2010/6/27 License : Copyright 2010 Ahmed Charfeddine, http://www.pushframework.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *********************************************************************/ #ifndef BroadcastManager__INCLUDED #define BroadcastManager__INCLUDED #pragma once #include "PushFramework.h" namespace PushFramework { class BroadcastManagerImpl; class ClientFactoryImpl; class Dispatcher; class OutgoingPacket; class ServerImpl; /*! The BroadcastManager class helps manage broadcasting queues and the subscription of connected clients to them. */ class PUSHFRAMEWORK_API BroadcastManager { friend class ClientFactoryImpl; friend class Dispatcher; friend class ServerImpl; public: BroadcastManager(void); ~BroadcastManager(void); /** @name Queues Management **/ //@{ /** \param channelKey the name of the queue to create. \param maxPacket the maximum number of packets this queue can store. \param requireSubscription specifies whether clients should be explicitly subscribed to the queue. \param uPriority queue priority over other queues. \param uPacketQuota packets quota. Call CreateQueue to create a new queue. */ void CreateQueue(BROADCASTQUEUE_NAME channelKey, unsigned int maxPacket, bool requireSubscription, unsigned int uPriority, unsigned int uPacketQuota); /** \param channelKey the name of the queue to delete. Call RemoveQueue to delete a new queue. */ void RemoveQueue(BROADCASTQUEUE_NAME channelKey); /** @name Subscription Management **/ //@{ /** \param clientKey the client key. \param channelKey the queue key. Call SubscribeConnectionToQueue to subscribe a connected client to an existing queue. */ bool SubscribeConnectionToQueue(CLIENT_KEY clientKey, BROADCASTQUEUE_NAME channelKey); /** \param clientKey the client key. \param channelKey the queue key. Call UnsubscribeConnectionFromQueue to unsubscribe a connected client from an existing queue. */ bool UnsubscribeConnectionFromQueue(CLIENT_KEY clientKey, BROADCASTQUEUE_NAME channelKey); /** \param clientKey the client key. Call RemoveConnection to unsubscribe a connected client from all queues. */ void RemoveConnection(CLIENT_KEY clientKey); /** @name Data Management **/ //@{ /** \param pPacket the packet to send. \param channelKey the queue key. Call PushPacket to push a packet through a broadcasting queue. */ void PushPacket(OutgoingPacket* pPacket, BROADCASTQUEUE_NAME channelName); /** \param pPacket the packet to send. \param channelKey the queue key. \param killKey used to reference the packet for subsequent removal. \param objectCategory used to reference the packet for subsequent removal. Call PushPacket to push a packet through a broadcasting queue. */ void PushPacket(OutgoingPacket* pPacket, BROADCASTQUEUE_NAME channelName, BROADCASTPACKET_KEY killKey, int objectCategory); /** \param killKey the killKey for the packet to be removed. \param objectCategory the objectCategory for the packet to be removed. \param channelKey the queue key. Call PushPacket to push a packet through a broadcasting queue. */ void RemovePacket(BROADCASTPACKET_KEY killKey, int objectCategory, BROADCASTQUEUE_NAME channelKey); }; extern PUSHFRAMEWORK_API BroadcastManager broadcastManager; } #endif // BroadcastManager__INCLUDED
[ "416671186@qq.com" ]
416671186@qq.com
7ba3513f3f12f7e9dd5899d544ddc1cc075e35a9
d6659a87e978cd848a3c4c6825a807e6ff9c08ea
/src/XD75_Wireless_and_Trackball/XD75@Master/keymap.h
a9446dc7e6ddbfa3364076be5bf9c91f301a80da
[]
no_license
ogatatsu/Oreore-HID-Firmware
67e37cba97f4f05727c3f8f91db7c941843a86d8
4055f1198786a4e047061a7959538844af969b06
refs/heads/master
2022-12-13T04:31:59.023265
2021-11-30T11:51:53
2021-11-30T11:51:53
187,301,696
1
1
null
null
null
null
UTF-8
C++
false
false
4,257
h
#include "BleCommandDsl.h" #include "CommandDsl.h" #include "KC.h" using namespace hidpg; /* ID * ,--------------------------------------------------------------------------------------------------------. * | 1 | 6 | 11 | 16 | 21 | 26 | 31 | 36 | 41 | 46 | 51 | 56 | 61 | 66 | 71 | * |------+------+------+------+------+------+------+------+------+------+------+------+------+------+------| * | 2 | 7 | 12 | 17 | 22 | 27 | 32 | 37 | 42 | 47 | 52 | 57 | 62 | 67 | 72 | * |------+------+------+------+------+------+------+------+------+------+------+------+------+------+------| * | 3 | 8 | 13 | 18 | 23 | 28 | 33 | 38 | 43 | 48 | 53 | 58 | 63 | 68 | 73 | * |------+------+------+------+------+------+------+------+------+------+------+------+------+------+------| * | 4 | 9 | 14 | 19 | 24 | 29 | 34 | 39 | 44 | 49 | 54 | 59 | 64 | 69 | 74 | * |------+------+------+------+------+------+------+------+------+------+------+------+------+------+------| * | 5 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | * `--------------------------------------------------------------------------------------------------------. */ Key keymap[] = { { 1, LY({ NK(Escape), _______, ToH(NK(Escape), 2000, RESET()) }) }, { 2, LY({ NK(Tab), _______, CK(Gui, Tab) }) }, { 3, TD({ { MO(Ctrl), MO(Ctrl) }, { MO(Ctrl + Shift), MO(Ctrl + Shift) }, { MO(Ctrl + Shift + Alt), MO(Ctrl + Shift + Alt) } }) }, { 4, MLT({ SL(1), TD({ { MO(Shift), MO(Shift) }, { CK(Shift, CapsLock), CK(Shift, CapsLock) } }) }) }, { 5, SEQ_MODE() }, { 6, LY({ NK(_1), _______, ToH(NK(F1), 1500, BT(1)) }) }, { 7, NK(Q) }, { 8, LY({ NK(A), _______, MS_CLK(LeftButton) }) }, { 9, NK(Z) }, { 10, NOP() }, { 11, LY({ NK(_2), _______, ToH(NK(F2), 1500, BT(2)) }) }, { 12, NK(W) }, { 13, LY({ NK(S), _______, TRT(1, MS_CLK(MiddleButton)) }) }, { 14, NK(X) }, { 15, NOP() }, { 16, LY({ NK(_3), _______, ToH(NK(F3), 1500, BT(3)) }) }, { 17, NK(E) }, { 18, LY({ NK(D), _______, MS_CLK(RightButton) }) }, { 19, NK(C) }, { 20, MO(Gui) }, { 21, LY({ NK(_4), _______, NK(F4) }) }, { 22, NK(R) }, { 23, NK(F) }, { 24, NK(V) }, { 25, TD({ { MO(Alt), MO(Alt) }, { MO(Alt + Shift), MO(Alt + Shift) }, { MO(Alt + Ctrl), MO(Alt + Ctrl) } }) }, { 26, LY({ NK(_5), _______, NK(F5) }) }, { 27, NK(T) }, { 28, NK(G) }, { 29, NK(B) }, { 30, LT(2, NK(Int5)) }, { 31, NK(PageUp) }, { 32, NK(PageDown) }, { 33, NK(Home) }, { 34, NK(End) }, { 35, NK(Space) }, { 36, NK(PrintScreen) }, { 37, NK(Insert) }, { 38, NK(Delete) }, { 39, NK(Backspace) }, { 40, NK(Enter) }, { 41, LY({ NK(_6), _______, NK(F6) }) }, { 42, NK(Y) }, { 43, LY({ NK(H), _______, NK(ArrowLeft) }) }, { 44, NK(N) }, { 45, LT(2, NK(Int4)) }, { 46, LY({ NK(_7), _______, NK(F7) }) }, { 47, NK(U) }, { 48, LY({ NK(J), _______, NK(ArrowDown) }) }, { 49, NK(M) }, { 50, TD({ { MO(Ctrl), MO(Ctrl) }, { MO(Ctrl + Shift), MO(Ctrl + Shift) }, { MO(Ctrl + Shift + Alt), MO(Ctrl + Shift + Alt) } }) }, { 51, LY({ NK(_8), _______, NK(F8) }) }, { 52, NK(I) }, { 53, LY({ NK(K), _______, NK(ArrowUp) }) }, { 54, NK(Comma) }, { 55, NOP() }, { 56, LY({ NK(_9), _______, NK(F9) }) }, { 57, NK(O) }, { 58, LY({ NK(L), _______, NK(ArrowRight) }) }, { 59, NK(Period) }, { 60, NK(ArrowUp) }, { 61, LY({ NK(_0), NK(Int3), NK(F10) }) }, { 62, NK(P) }, { 63, NK(Semicolon) }, { 64, NK(Slash) }, { 65, NK(ArrowUp) }, { 66, LY({ NK(Minus), _______, NK(F11) }) }, { 67, NK(BracketLeft) }, { 68, NK(Quote) }, { 69, NK(Int1) }, { 70, NK(ArrowDown) }, { 71, LY({ NK(Equal), _______, NK(F12) }) }, { 72, NK(BracketRight) }, { 73, NK(Backslash) }, { 74, MLT({ SL(1), TD({ { MO(Shift), MO(Shift) }, { CK(Shift, CapsLock), CK(Shift, CapsLock) } }) }) }, { 75, NK(ArrowRight) }, }; Track trackmap[] = { { 1, 50, AngleSnap::Enable, MS_SCR(1, 0), MS_SCR(-1, 0), _______, _______ }, };
[ "ogwrtty@gmail.com" ]
ogwrtty@gmail.com
eb6fe0902aaed69b86a6adce063a659866c6e421
db0c18d43ed13ecf36553adf083375658db3cc31
/code_warehouse/Dinic.cpp
60ee6f2513d625b4017a0837282e15c940d16f94
[]
no_license
hjsjhn/sysconkonn.github.io
ad14cedcaa13ce83d91bfec43fe446195a2c9f54
cad2ee611282c7f587175c6b18ce577676dbe0bb
refs/heads/master
2021-09-10T23:25:28.698144
2018-04-04T07:04:21
2018-04-04T07:04:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,646
cpp
#include <cstdio> #include <algorithm> #include <cstring> #include <vector> #include <queue> #define MAX_N 10001 #define INF 10000001 using namespace std; struct Edge { int from, to, cap, flow; Edge(int u, int v, int c, int f) : from(u), to(v), cap(c), flow(f) {} }; vector<Edge> edges; vector<int> G[MAX_N]; int N, M, s, t; int cur[MAX_N], dep[MAX_N]; void add_edge (int from, int to, int cap) { edges.push_back(Edge(from, to, cap, 0)); edges.push_back(Edge(to, from, 0, 0)); int m = edges.size(); G[from].push_back(m - 2); G[to].push_back(m - 1); } bool BFS() { memset(dep, 0, sizeof(dep)); queue<int> Q; Q.push(s); dep[s] = 0; while (!Q.empty()) { int now = Q.front(); Q.pop(); for (int i = 0;i < G[now].size(); ++i) { Edge& e = edges[G[now][i]]; if (e.to == s) continue; if (!dep[e.to] && e.cap > e.flow) { dep[e.to] = dep[now] + 1; Q.push(e.to); } } } return dep[t]; } int DFS(int x, int a) { if (x == t || a == 0) return a; int flow = 0, f; for (int& i = cur[x];i < G[x].size(); ++i) { Edge& e = edges[G[x][i]]; if (dep[e.to] == dep[x] + 1 && (f = DFS(e.to, min(a, e.cap - e.flow))) > 0) { e.flow += f; edges[G[x][i] ^ 1].flow -= f; flow += f; a -= f; if (a == 0) break; } } return flow; } int Max_Flow () { int flow = 0; while(BFS()) { memset(cur, 0, sizeof(cur)); flow += DFS(s, INF); } return flow; } int main () { scanf("%d%d%d%d", &N, &M, &s, &t); for (int i = 1;i <= M; ++i) { int u, v, d; scanf("%d%d%d", &u, &v, &d); add_edge(u, v, d); } printf("%d\n", Max_Flow()); }
[ "ssysccon@qq.com" ]
ssysccon@qq.com
dabb41ffa82800db59ecd461f237ef5ff9126ef9
e827a15379f8c9a273533c2599955dd550ddfd8d
/OSLab2/Process.h
7cf7b0a9e7fe05e53fbae06f824f9be9b09663f3
[]
no_license
yuhanzz/OSLabs
51e567b0da76866e1b0122c489a6f4856bac465d
469e935eb64f4e95a28ec09d14de5ca80ee963bf
refs/heads/main
2023-02-02T20:52:43.665686
2020-12-21T02:35:13
2020-12-21T02:35:13
323,206,425
0
0
null
null
null
null
UTF-8
C++
false
false
667
h
#ifndef PROCESS_H_ #define PROCESS_H_ #include <iostream> extern int maxprio; typedef enum { CREATED, READY, RUNNING, BLOCKED } ProcessState; class Process { public: // global for all processes static int available_pid; // static int pid; int static_priority; int arrive_time; int total_cpu; int cpu_burst_max; int io_burst_max; // dynamic int dynamic_priority; int remaining_cpu; int cpu_burst; int io_burst; int latest_trans_time; int finishing_time; int latest_enqueue_time; int cpu_waiting_time; int total_io_time; Process(int, int, int, int, int); }; #endif
[ "yuhan.zhou98@gmail.com" ]
yuhan.zhou98@gmail.com
a12fa554ec3d11affcb2d3f90e73c9347b9744d8
eab73a7acf3194b5d9f095aade9ca83ba2e9c5cb
/src/Pegasus/Security/UserManager/UserManager.h
5cd417993d1aee7e68bed815b422d2eda0edda39
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-permissive" ]
permissive
edwardt/Pegasus-2.5
f1af8e7c546d1ae50bbcbd0b5af752b111b5d895
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
refs/heads/master
2022-03-17T17:34:46.748653
2013-07-23T13:21:50
2013-07-23T13:21:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,691
h
//%2005//////////////////////////////////////////////////////////////////////// // // Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development // Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems. // Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.; // IBM Corp.; EMC Corporation, The Open Group. // Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.; // IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group. // Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.; // EMC Corporation; VERITAS Software Corporation; The Open Group. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE SHALL BE INCLUDED IN // ALL COPIES OR SUBSTANTIAL PORTIONS OF THE SOFTWARE. THE SOFTWARE IS PROVIDED // "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // //============================================================================== // // Author: Sushma Fernandes, Hewlett Packard Company (sushma_fernandes@hp.com) // // Modified By: Nag Boranna, Hewlett Packard Company (nagaraja_boranna@hp.com) // Carol Ann Krug Graves, Hewlett-Packard Company // (carolann_graves@hp.com) // Amit K Arora, IBM (amita@in.ibm.com) for PEP#101 // //%//////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // // This file implements the functionality required to manage users. // /////////////////////////////////////////////////////////////////////////////// #ifndef Pegasus_UserManager_h #define Pegasus_UserManager_h #include <Pegasus/Common/Config.h> #include <cctype> #include <Pegasus/Common/String.h> #include <Pegasus/Security/UserManager/UserFileHandler.h> #include <Pegasus/Security/UserManager/AuthorizationHandler.h> #include <Pegasus/Security/UserManager/Linkage.h> PEGASUS_NAMESPACE_BEGIN /** This class interfaces with UserFileHandler for creating, removing and listing users. */ class PEGASUS_USERMANAGER_LINKAGE UserManager { private: // // Singleton instance of UserManager, the constructor // and the destructor are made private // static UserManager* _instance; // // Instance of UserFileHandler // AutoPtr<UserFileHandler> _userFileHandler; //PEP101 // // Instance of AuthorizationHandler // AutoPtr<AuthorizationHandler> _authHandler; //Pep101 /** Constructor. */ UserManager(CIMRepository* repository); /** Destructor. */ ~UserManager(); public: /** Construct the singleton instance of the UserManager and return a pointer to that instance. */ static UserManager* getInstance(CIMRepository* repository = 0); /** Terminates the UserManager singleton. */ static void destroy(void); /** Add a user. @param userName The name of the user to add. @param password The password for the user. @exception InvalidSystemUser if the user is not a system user @exception FileNotReadable if unable to read password file @exception DuplicateUser if the user already exists @exception PasswordCacheError if there is an error processing password hashtable @exception CannotRenameFile if password file cannot be renamed. */ void addUser(const String& userName, const String& passWord); /** Modify user's password. @param userName The name of the user to modify. @param password User's old password. @param newPassword User's new password. @exception InvalidUser if the user does not exist @exception PasswordMismatch if the specified password does not match user's current password. @exception PasswordCacheError if there is an error processing password hashtable @exception CannotRenameFile if password file cannot be renamed. */ void modifyUser( const String& userName, const String& password, const String& newPassword ); /** Remove a user. @param userName The name of the user to remove. @exception FileNotReadable if unable to read password file @exception InvalidUser if the user does not exist @exception PasswordCacheError if there is an error processing password hashtable @exception CannotRenameFile if password file cannot be renamed. */ void removeUser(const String& userName); /** Get a list of all the user names. @param userNames List containing all the user names. @exception FileNotReadable if unable to read password file */ void getAllUserNames(Array<String>& userNames); /** Verify user exists in the cimserver password file @param userName Name of the user to be verified @return true if the user exists, else false @exception FileNotReadable if unable to read password file */ Boolean verifyCIMUser(const String& userName); /** Verify user's password matches specified password @param userName Name of the user to be verified @param password password to be verified @return true if the user's password matches existing password , else false @exception FileNotReadable if unable to read password file @exception InvalidUser if the specified user does not exist */ Boolean verifyCIMUserPassword( const String& userName, const String& password ); /** Verify whether the spcefied namespace is a valid namespace. @param myNamespace string containing the namespace name. @return true if the specified name space is valid and exists, false otherwise. */ Boolean verifyNamespace( const CIMNamespaceName& myNamespace ); /** Verify whether the specified operation has authorization to be performed by the specified user. @param userName string containing the user name. @param nameSpace string containing the namespace name. @param cimMethodName string containing the cim method name. @return true if the specified user has authorizations to run the specified CIM operation on the specified namespace, false otherwise. */ Boolean verifyAuthorization( const String& userName, const CIMNamespaceName& nameSpace, const CIMName& cimMethodName); /** Set the authorization to the specified user on the specified namespace. @param userName string containing the user name. @param myNamespace string containing the namespace name. @param auth string containing the authorizations. */ void setAuthorization( const String& userName, const CIMNamespaceName& myNamespace, const String& auth); /** Remove the authorizations of the specified user on the specified namespace. @param userName string containing the user name. @param myNamespace string containing the namespace name. */ void removeAuthorization( const String& userName, const CIMNamespaceName& myNamespace); /** Get the authorizations of the specified user on the specified namespace. @param userName string containing the user name. @param myNamespace string containing the namespace name. @return a string containing the authorizations. */ String getAuthorization( const String& userName, const CIMNamespaceName& myNamespace); }; PEGASUS_NAMESPACE_END #endif /* Pegasus_UserManager_h */
[ "ncultra@gmail.com" ]
ncultra@gmail.com
3f6b48a9efa88e63b9b36ef585a19ec27cf8c882
a1a8b69b2a24fd86e4d260c8c5d4a039b7c06286
/build/iOS/Release/include/Fuse.Gestures.Scroller.h
64361823763897c8c4eb1ce509a45006bd47d3f2
[]
no_license
epireve/hikr-tute
df0af11d1cfbdf6e874372b019d30ab0541c09b7
545501fba7044b4cc927baea2edec0674769e22c
refs/heads/master
2021-09-02T13:54:05.359975
2018-01-03T01:21:31
2018-01-03T01:21:31
115,536,756
0
0
null
null
null
null
UTF-8
C++
false
false
5,962
h
// This file was generated based on /usr/local/share/uno/Packages/Fuse.Controls.ScrollView/1.4.2/Scroller.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Behavior.h> #include <Fuse.Binding.h> #include <Fuse.INotifyUnrooted.h> #include <Fuse.Input.IGesture.h> #include <Fuse.IProperties.h> #include <Fuse.Scripting.IScriptObject.h> #include <Uno.Collections.ICollection-1.h> #include <Uno.Collections.IEnumerable-1.h> #include <Uno.Collections.IList-1.h> #include <Uno.Float2.h> #include <Uno.UX.IPropertyListener.h> namespace g{namespace Fuse{namespace Controls{struct ScrollPositionChangedArgs;}}} namespace g{namespace Fuse{namespace Controls{struct ScrollView;}}} namespace g{namespace Fuse{namespace Gestures{struct Scroller;}}} namespace g{namespace Fuse{namespace Gestures{struct SwipeGestureHelper;}}} namespace g{namespace Fuse{namespace Input{struct Gesture;}}} namespace g{namespace Fuse{namespace Input{struct GesturePriorityConfig;}}} namespace g{namespace Fuse{namespace Input{struct PointerEventArgs;}}} namespace g{namespace Fuse{namespace Input{struct PointerMovedArgs;}}} namespace g{namespace Fuse{namespace Input{struct PointerPressedArgs;}}} namespace g{namespace Fuse{namespace Input{struct PointerReleasedArgs;}}} namespace g{namespace Fuse{namespace Motion{namespace Simulation{struct PointerVelocity;}}}} namespace g{namespace Fuse{struct RequestBringIntoViewArgs;}} namespace g{namespace Fuse{struct Visual;}} namespace g{namespace Uno{namespace UX{struct PropertyObject;}}} namespace g{namespace Uno{namespace UX{struct Selector;}}} namespace g{ namespace Fuse{ namespace Gestures{ // public sealed class Scroller :21 // { struct Scroller_type : ::g::Fuse::Node_type { ::g::Uno::UX::IPropertyListener interface6; ::g::Fuse::Input::IGesture interface7; }; Scroller_type* Scroller_typeof(); void Scroller__ctor_4_fn(Scroller* __this, bool* ignore); void Scroller__CheckLimits_fn(Scroller* __this); void Scroller__CheckNeedUpdated_fn(Scroller* __this, bool* off); void Scroller__get_DelayStart_fn(Scroller* __this, bool* __retval); void Scroller__set_DelayStart_fn(Scroller* __this, bool* value); void Scroller__FromWindow_fn(Scroller* __this, ::g::Uno::Float2* p, ::g::Uno::Float2* __retval); void Scroller__FuseInputIGestureOnCaptureChanged_fn(Scroller* __this, ::g::Fuse::Input::PointerEventArgs* args, int* how, int* prev); void Scroller__FuseInputIGestureOnLostCapture_fn(Scroller* __this, bool* forced); void Scroller__FuseInputIGestureOnPointerMoved_fn(Scroller* __this, ::g::Fuse::Input::PointerMovedArgs* args, int* __retval); void Scroller__FuseInputIGestureOnPointerPressed_fn(Scroller* __this, ::g::Fuse::Input::PointerPressedArgs* args, int* __retval); void Scroller__FuseInputIGestureOnPointerReleased_fn(Scroller* __this, ::g::Fuse::Input::PointerReleasedArgs* args, int* __retval); void Scroller__FuseInputIGestureget_Priority_fn(Scroller* __this, ::g::Fuse::Input::GesturePriorityConfig* __retval); void Scroller__Goto_fn(Scroller* __this, ::g::Uno::Float2* position); void Scroller__MoveUser_fn(Scroller* __this, int* flags, double* time); void Scroller__New3_fn(bool* ignore, Scroller** __retval); void Scroller__OnRequestBringIntoView_fn(Scroller* __this, uObject* sender, ::g::Fuse::RequestBringIntoViewArgs* args); void Scroller__OnRooted_fn(Scroller* __this); void Scroller__OnScrollPositionChanged_fn(Scroller* __this, uObject* s, ::g::Fuse::Controls::ScrollPositionChangedArgs* args); void Scroller__OnUnrooted_fn(Scroller* __this); void Scroller__OnUpdated_fn(Scroller* __this); void Scroller__PerformBringIntoView_fn(Scroller* __this); void Scroller__get_ScrollableUserScroll_fn(Scroller* __this, bool* __retval); void Scroller__StartInvalidateVisual_fn(Scroller* __this); void Scroller__StopInvalidateVisual_fn(Scroller* __this); void Scroller__UnoUXIPropertyListenerOnPropertyChanged_fn(Scroller* __this, ::g::Uno::UX::PropertyObject* obj, ::g::Uno::UX::Selector* sel); void Scroller__UpdatePointerEvents_fn(Scroller* __this, bool* forceOff); void Scroller__UpdateScrollMax_fn(Scroller* __this); struct Scroller : ::g::Fuse::Behavior { uStrong<uObject*> _region; uStrong< ::g::Fuse::Motion::Simulation::PointerVelocity*> _velocity; bool _delayStart; uStrong< ::g::Fuse::Controls::ScrollView*> _scrollable; bool _pointerListening; uStrong< ::g::Fuse::Input::Gesture*> _gesture; bool _hasUpdated; bool _updateFirstFrame; int _down; ::g::Uno::Float2 _pointerPos; ::g::Uno::Float2 _prevPos; ::g::Uno::Float2 _startPos; double _prevTime; ::g::Uno::Float2 _softCaptureStart; ::g::Uno::Float2 _softCaptureCurrent; float _significance; bool _pressed; static uSStrong< ::g::Fuse::Gestures::SwipeGestureHelper*> _horizontalGesture_; static uSStrong< ::g::Fuse::Gestures::SwipeGestureHelper*>& _horizontalGesture() { return _horizontalGesture_; } static uSStrong< ::g::Fuse::Gestures::SwipeGestureHelper*> _verticalGesture_; static uSStrong< ::g::Fuse::Gestures::SwipeGestureHelper*>& _verticalGesture() { return _verticalGesture_; } uStrong< ::g::Fuse::Visual*> _pendingBringIntoView; void ctor_4(bool ignore); void CheckLimits(); void CheckNeedUpdated(bool off); bool DelayStart(); void DelayStart(bool value); ::g::Uno::Float2 FromWindow(::g::Uno::Float2 p); void Goto(::g::Uno::Float2 position); void MoveUser(int flags, double time); void OnRequestBringIntoView(uObject* sender, ::g::Fuse::RequestBringIntoViewArgs* args); void OnScrollPositionChanged(uObject* s, ::g::Fuse::Controls::ScrollPositionChangedArgs* args); void OnUpdated(); void PerformBringIntoView(); bool ScrollableUserScroll(); void StartInvalidateVisual(); void StopInvalidateVisual(); void UpdatePointerEvents(bool forceOff); void UpdateScrollMax(); static Scroller* New3(bool ignore); }; // } }}} // ::g::Fuse::Gestures
[ "i@firdaus.my" ]
i@firdaus.my
8717f8100966c508cab82e8b980ca768c1f86303
e520fdd4b01e2133b9951c3d4516e9cb95d67ca0
/include/ecs/system/SystemUpdater.hpp
4c90b791cbfed902beb855213268d1c94818ab45
[]
no_license
Hazurl/ECS
08444cbb89d2c09edea68089a6a425b385f0749a
5caa25a21485c7b7431b284d0065308dcdb6a08d
refs/heads/master
2021-04-26T08:47:00.920879
2017-11-20T17:10:03
2017-11-20T17:10:03
106,946,293
1
0
null
null
null
null
UTF-8
C++
false
false
5,681
hpp
#pragma once #include <ecs/system/ArgsGetter.hpp> #include <ecs/system/MethodCaller.hpp> #include <ecs/Config.hpp> #include <ecs/container/Tuple.hpp> ECS_BEGIN_NS template<typename _Systems, typename _EntityController, typename _TagController> class SystemUpdater { public: using Systems = _Systems; using Systems_t = mtp::transform<Systems, mtp::type_of>; using EntityController_t = _EntityController; using TagController_t = _TagController; using UserEntityController = typename EntityController_t::user_bridge; using UserTagController = typename TagController_t::user_bridge; private: template<typename C> using Pool = typename EntityController_t::template Pool<C>; using Systems_tuple = Tuple_from_list<Systems_t>; template<typename S> using UpdateMethodsOfSystem = typename S::methods; template<typename S> using UpdateMethodsOf = UpdateMethodsOfSystem<mtp::at<Systems, mtp::index_of_v<Systems_t, S>>>; using ArgsList = mtp::transform< ArgsGetter< mtp::flatten< mtp::transform< Systems, UpdateMethodsOfSystem > > >, mtp::remove_qualifiers >; using Args_tuple = Tuple_from_list<ArgsList>; public: template<typename SystemConstr> SystemUpdater(EntityController_t& entity_controller, TagController_t& tag_controller, SystemConstr const& sc = SystemsConstructor<>{}) : entity_controller(entity_controller), tag_controller(tag_controller) { mtp::apply_lambda<Systems_t>{}([this, &sc] (auto s) { using S = mtp::type_of<decltype(s)>; this->systems.template construct<S>(sc.template construct_system<S>()); }); } template<typename...Args> void update(Args&&...args) { construct_args(std::forward<Args>(args)...); construct_views(); contruct_entity_controller(mtp::in<ArgsList, UserEntityController>{}); contruct_tag_controller(mtp::in<ArgsList, UserTagController>{}); update_systems(); update_entity_controller(mtp::in<ArgsList, UserEntityController>{}); update_tag_controller(mtp::in<ArgsList, UserTagController>{}); } private: void update_entity_controller(mtp::False) {} void update_entity_controller(mtp::True) { syst_args.template get<UserEntityController>().execute(); } void update_tag_controller(mtp::False) {} void update_tag_controller(mtp::True) { syst_args.template get<UserTagController>().execute(); } void update_systems() { mtp::apply_lambda<Systems_t>{}([&] (auto x) { using T = typename decltype(x)::type; this->update_system<T>(); }); } template<typename S> void update_system() { mtp::apply_lambda<UpdateMethodsOf<S>>{}([&] (auto x) { using M = mtp::type_of<decltype(x)>; MethodCaller<S, typename M::type>::call(this->systems.template get<S>(), M::function, this->syst_args); }); } void construct_args() {} template<typename Arg, typename...Args> void construct_args(Arg&& arg, Args&&...args) { construct_arg(std::forward<Arg>(arg), mtp::in<ArgsList, Arg>{}); construct_args(std::forward<Args>(args)...); } template<typename Arg> void construct_arg(Arg&&, mtp::False) {} template<typename Arg> void construct_arg(Arg&& arg, mtp::True) { syst_args.template reconstruct<mtp::remove_qualifiers<Arg>>(std::forward<Arg>(arg)); } void contruct_entity_controller(mtp::False) {} void contruct_entity_controller(mtp::True) { syst_args.template reconstruct<UserEntityController>(entity_controller); } void contruct_tag_controller(mtp::False) {} void contruct_tag_controller(mtp::True) { syst_args.template reconstruct<UserTagController>(tag_controller); } void construct_views() { mtp::apply_lambda<mtp::filter<ArgsList, is_views>>{}([this] (auto v) { using V = mtp::type_of<decltype(v)>; this->syst_args.template reconstruct<V>( this->construct_view<V>() ); }); } template<typename V, typename List_Views_Args = typename V::list_t> V construct_view () { static_assert(mtp::unique_v<List_Views_Args>, "Components in the view must be uniques"); using TupleVw = mtp::as_tuple<mtp::transform<List_Views_Args, mtp::add_ptr>>; using Main = mtp::first<List_Views_Args>; auto& main = std::get<Pool<Main>>(entity_controller.pools); typename V::container_t container {}; for (auto& ent_id : main.keys()) { TupleVw tuple; std::get<Main*>(tuple) = &main.get(ent_id); bool has_failed = false; mtp::apply_lambda<mtp::erase_front<List_Views_Args>>{}([this, &has_failed, &tuple, ent_id] (auto x) { if (!has_failed) { using A = mtp::type_of<decltype(x)>; auto& pool = std::get<Pool<A>>(entity_controller.pools); if (pool.has(ent_id)) std::get<A*>(tuple) = &pool.get(ent_id); else has_failed = true; } }); if (!has_failed) { container.emplace_back(entity_controller.entityManager.sync(ent_id), std::move(tuple)); } } return V{ container }; } EntityController_t& entity_controller; TagController_t& tag_controller; Systems_tuple systems; Args_tuple syst_args; }; ECS_END_NS
[ "ricoujules69@gmail.com" ]
ricoujules69@gmail.com
e39d8be4b9f2d5c194c99a3b432e68d2553cc25b
962213848e5f4989c2f1b692ef9baa604b2c3152
/508.cpp
725a6b35860b5b25bf1a3413f83ad85215841622
[ "MIT" ]
permissive
BYOUINZAKA/LeetCodeNotes
bfc9634bf538b711edefcd7e38a383b625744bda
48e1b4522c1f769eeec4944cfbd57abf1281d09a
refs/heads/master
2022-12-02T14:12:14.855840
2020-08-22T10:41:06
2020-08-22T10:41:06
283,944,029
0
0
null
null
null
null
UTF-8
C++
false
false
910
cpp
/* * @Author: Hata * @Date: 2020-06-09 08:22:37 * @LastEditors: Hata * @LastEditTime: 2020-06-09 08:42:34 * @FilePath: \LeetCode\508.cpp * @Description: https://leetcode-cn.com/problems/most-frequent-subtree-sum/ */ #include "leetcode.h" class Solution { public: std::vector<int> findFrequentTreeSum(TreeNode *root) { if (!root) return {}; std::unordered_map<int, int> table; std::map<int, std::vector<int>> resTable; dfs(root, table); for (auto &&pair : table) { resTable[pair.second].push_back(pair.first); } return resTable.crbegin()->second; } int dfs(TreeNode *node, std::unordered_map<int, int> &table) { if (node == nullptr) return 0; int sum = dfs(node->left, table) + dfs(node->right, table) + node->val; ++table[sum]; return sum; } };
[ "2606675531@qq.com" ]
2606675531@qq.com
4389f67a31ac805784dd1f596c6b06d2169b9194
1a6736e0944be96eddbcc88f278352ce3f9eeac5
/BZOJ4196.cpp
b5931e6ab03c3ad44582ff0ab8f859678440aec8
[]
no_license
wxy-2015/Problems
333c39490b29baf6471f080a4bac2717edde3339
ef886faad2ee29c6ddba74067c95a4306b0768ef
refs/heads/master
2021-01-21T12:59:29.550816
2016-05-03T01:51:26
2016-05-03T01:51:26
53,482,353
0
0
null
null
null
null
UTF-8
C++
false
false
1,837
cpp
#include <cstdio> #include <cstdlib> #define MAXN 100010 #define lson (n << 1) #define rson (lson | 1) #define ml ((l + r) >> 1) #define mr (ml + 1) static struct { int v, n; } Gr[MAXN]; static int fa[MAXN], sz[MAXN], son[MAXN]; static int top[MAXN], end[MAXN], adr[MAXN]; static int head[MAXN], STr[4 * MAXN], tag[4 * MAXN]; static int N, M, atop = 0, x, ans; static char op[20]; int inline max(int x, int y) { return (x > y) ? x : y; } int dfs1(int x) { sz[x] = 1; for (int i = head[x]; i; i = Gr[i].n) { sz[x] += dfs1(Gr[i].v); if (!son[x] || sz[son[x]] < sz[Gr[i].v]) son[x] = Gr[i].v; } return sz[x]; } int dfs2(int x, int t) { top[x] = t; adr[x] = atop++; end[x] = son[x] ? dfs2(son[x], t) : adr[x]; for (int i = head[x]; i; i = Gr[i].n) if (Gr[i].v != son[x]) end[x] = dfs2(Gr[i].v, Gr[i].v); return end[x]; } int modify(int n, int l, int r, int fl, int fr, int x) { int ans = 0; if (fl <= l && r <= fr) { ans = x ? r - l + 1 - STr[n] : STr[n]; tag[n] = x ? 1 : -1; STr[n] = (r - l + 1) * x; return ans; } if (tag[n]) { tag[lson] = tag[rson] = tag[n]; STr[lson] = (ml - l + 1) * (tag[n] > 0); STr[rson] = (r - mr + 1) * (tag[n] > 0); tag[n] = 0; } if (fl <= ml) ans += modify(lson, l, ml, fl, fr, x); if (fr >= mr) ans += modify(rson, mr, r, fl, fr, x); STr[n] = STr[lson] + STr[rson]; return ans; } int main(int argc, char *argv[]) { scanf("%d", &N); for (int i = 1; i < N; i++) { scanf("%d", &fa[i]); Gr[i].n = head[fa[i]]; head[fa[i]] = Gr[i].v = i; } dfs1(0); dfs2(0, 0); scanf("%d", &M); while (M--) { scanf("%s%d", op, &x); if (op[0] == 'i') for (ans = 0; ; x = fa[top[x]]) { ans += modify(1, 0, N-1, adr[top[x]], adr[x], 1); if (!x) break; } else ans = modify(1, 0, N-1, adr[x], end[x], 0); printf("%d\n", ans); } return 0; }
[ "wxy_2015@yahoo.com" ]
wxy_2015@yahoo.com
8b37a227371935c2572e0c646aeb3eb42f57c948
890960ef881e3da2f4486e56e33c1834bc64023c
/ur_rtde/include/ur_rtde/dashboard_client.h
ef5ac523099c264af6b7f7d7f1a0ddaf2c5a5766
[ "MIT" ]
permissive
haukri/RobotSystemDesign
0728c80d4ca392c467b1bfd22efe2ca467217c0b
4627fbe606881e07a69eec084f76a44e83e7eeb9
refs/heads/master
2022-12-16T02:07:44.875986
2019-11-28T11:00:22
2019-11-28T11:00:22
209,637,321
1
0
null
2022-12-11T07:18:15
2019-09-19T19:52:28
C++
UTF-8
C++
false
false
1,921
h
#ifndef RTDE_DASHBOARD_CLIENT_H #define RTDE_DASHBOARD_CLIENT_H #include <ur_rtde/rtde_export.h> #include <boost/array.hpp> #include <boost/asio.hpp> #include <string> #include <ur_rtde/dashboard_enums.h> namespace ur_rtde { class DashboardClient { public: RTDE_EXPORT explicit DashboardClient(std::string hostname, int port = 29999); RTDE_EXPORT virtual ~DashboardClient(); enum class ConnectionState : std::uint8_t { DISCONNECTED = 0, CONNECTED = 1, }; public: RTDE_EXPORT void connect(); RTDE_EXPORT bool isConnected(); RTDE_EXPORT void disconnect(); RTDE_EXPORT void send(const std::string &str); RTDE_EXPORT std::string receive(); RTDE_EXPORT void loadURP(const std::string &urp_name); RTDE_EXPORT void play(); RTDE_EXPORT void stop(); RTDE_EXPORT void pause(); RTDE_EXPORT void quit(); RTDE_EXPORT void shutdown(); RTDE_EXPORT bool running(); RTDE_EXPORT void popup(const std::string &message); RTDE_EXPORT void closePopup(); RTDE_EXPORT void closeSafetyPopup(); RTDE_EXPORT void powerOn(); RTDE_EXPORT void powerOff(); RTDE_EXPORT void brakeRelease(); RTDE_EXPORT void unlockProtectiveStop(); RTDE_EXPORT void restartSafety(); RTDE_EXPORT std::string PolyscopeVersion(); RTDE_EXPORT std::string programState(); RTDE_EXPORT std::string robotmode(); RTDE_EXPORT std::string getLoadedProgram(); RTDE_EXPORT std::string safetymode(); RTDE_EXPORT std::string safetystatus(); RTDE_EXPORT void addToLog(const std::string &message); RTDE_EXPORT bool isProgramSaved(); RTDE_EXPORT void setUserRole(const UserRole &role); private: std::string hostname_; int port_; ConnectionState conn_state_; std::shared_ptr<boost::asio::io_service> io_service_; std::shared_ptr<boost::asio::ip::tcp::socket> socket_; std::shared_ptr<boost::asio::ip::tcp::resolver> resolver_; }; } // namespace ur_rtde #endif // RTDE_DASHBOARD_CLIENT_H
[ "haukzinn@gmail.com" ]
haukzinn@gmail.com
4a6f4200b4168378a0b52b95cc83e3898dbf346f
f2a473b35198a8218246d6b064b497c6b74aea09
/imx6u_pos/terminalProject/login.cpp
50eaca4ad7a51f8da430ef9eac0c6546cb795839
[]
no_license
mrj0123/imx6ul
86d00c6737600d8bebc08d8d9a18415d1510c6c6
7dd9c9cee70c5566aa279c16f6e81160b98b834b
refs/heads/master
2020-09-13T15:01:57.794923
2020-02-20T01:22:17
2020-02-20T01:22:17
222,823,423
0
0
null
2019-11-20T01:23:16
2019-11-20T01:23:15
null
UTF-8
C++
false
false
3,708
cpp
#include "login.h" #include "ui_login.h" #include "qmessagebox.h" #include <QTimer> login::login(QWidget *parent) : QDialog(parent), ui(new Ui::login) { ui->setupUi(this); ui->lineEdit_password_login->setEchoMode(QLineEdit::Password);//设置输入密码框 ui->label_erroNote->hide();//错误提示框 ui->lineEdit_password_login->installEventFilter(this);//在窗体上为lineEdit安装过滤器 //全屏 setWindowFlags(Qt::FramelessWindowHint); showFullScreen(); ui->lineEdit_password_login->setFocus(); } login::~login() { delete ui; } void login::loginReg() { //登录验证 QString pwd = ui->lineEdit_password_login->text(); if(pwd ==""){ /*QMessageBox message(QMessageBox::NoIcon,"提示","请输入密码!"); message.exec();*/ ui->label_erroNote->show(); ui->label_erroNote->setText("请输入密码!"); QTimer::singleShot(2000,ui->label_erroNote,SLOT(hide())); }else if(pwd !="123456"){ /*QMessageBox message(QMessageBox::NoIcon,"提示","密码错误!"); message.exec();*/ ui->label_erroNote->show(); ui->label_erroNote->setText("密码错误!"); QTimer::singleShot(2000,ui->label_erroNote,SLOT(hide())); }else{ //设置网络 network * myNetwork = new network(this); myNetwork->scmd_network_network=scmd_network_login; myNetwork->scmd_main_network=scmd_main_login; myNetwork->scmd_sec_network=scmd_sec_login; myNetwork->termCode_network=termCode_login; myNetwork->players_network=players_login; //版本号 myNetwork->uiVersion_network=uiVersion_login; myNetwork->consumeserVersion_network=consumeserVersion_login; myNetwork->scanqrserVersion_network=scanqrserVersion_login; myNetwork->secscreenVersion_network=secscreenVersion_login; myNetwork->networkVersion_network=networkVersion_login; myNetwork->exec(); delete myNetwork; this->close(); } } void login::on_pushButton_login_clicked() { loginReg(); } void login::on_pushButton_back_clicked() { this->close(); } bool login::eventFilter(QObject *watched, QEvent *event) { if(watched==ui->lineEdit_password_login){//首先判断控件(这里指lineEdit_password) if(event->type()==QEvent::KeyPress){//判断控件的具体事件(这里指获得点击事件) QKeyEvent *keyevent=static_cast<QKeyEvent *>(event); if(keyevent->isAutoRepeat()){ ui->lineEdit_password_login->setText(ui->lineEdit_password_login->text()); return true; } int keyValue = keyevent->key(); printf("qqkeyValue:%d\n",keyValue); if(keyValue==16777264){//16777264--小数点 ui->lineEdit_password_login->setText(ui->lineEdit_password_login->text().trimmed()+"."); return true; }else if(keyValue==16777216 || keyValue==16777265){//16777216--取消键;16777265--菜单键 ui->lineEdit_password_login->setText(ui->lineEdit_password_login->text()); return true; }else if(keyValue==42){//42--返回键,定义为退格键 ui->lineEdit_password_login->backspace(); return true; }else if(keyValue==16777220){//16777220--确定键 loginReg(); return true; }else{ return QWidget::eventFilter(watched,event); // 最后将事件交给上层对话框 } } } return QWidget::eventFilter(watched,event); // 最后将事件交给上层对话框 }
[ "54297818+mrj0123@users.noreply.github.com" ]
54297818+mrj0123@users.noreply.github.com
e78aa9d71f5c5d1964757ee5a0489c2ec3c9f17f
846a7668ac964632bdb6db639ab381be11c13b77
/android/frameworks/base/cmds/bootanimation/bootanimation_main.cpp
fe711c6b78d3bfbc914bbfa77c4b295525e6f22c
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
BPI-SINOVOIP/BPI-A64-Android8
f2900965e96fd6f2a28ced68af668a858b15ebe1
744c72c133b9bf5d2e9efe0ab33e01e6e51d5743
refs/heads/master
2023-05-21T08:02:23.364495
2020-07-15T11:27:51
2020-07-15T11:27:51
143,945,191
2
0
null
null
null
null
UTF-8
C++
false
false
5,278
cpp
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "BootAnimation" #include <stdint.h> #include <inttypes.h> #include <binder/IPCThreadState.h> #include <binder/ProcessState.h> #include <binder/IServiceManager.h> #include <cutils/properties.h> #include <sys/resource.h> #include <utils/Log.h> #include <utils/SystemClock.h> #include <utils/threads.h> #include <android-base/properties.h> #include "BootAnimation.h" #include "BootAnimationUtil.h" #include "audioplay.h" using namespace android; // --------------------------------------------------------------------------- namespace { // Create a typedef for readability. typedef android::BootAnimation::Animation Animation; static const char PLAY_SOUND_PROP_NAME[] = "persist.sys.bootanim.play_sound"; static const char BOOT_COMPLETED_PROP_NAME[] = "sys.boot_completed"; static const char POWER_CTL_PROP_NAME[] = "sys.powerctl"; static const char BOOTREASON_PROP_NAME[] = "ro.boot.bootreason"; static const std::vector<std::string> PLAY_SOUND_BOOTREASON_BLACKLIST { "kernel_panic", "Panic", "Watchdog", }; class InitAudioThread : public Thread { public: InitAudioThread(uint8_t* exampleAudioData, int exampleAudioLength) : Thread(false), mExampleAudioData(exampleAudioData), mExampleAudioLength(exampleAudioLength) {} private: virtual bool threadLoop() { audioplay::create(mExampleAudioData, mExampleAudioLength); // Exit immediately return false; } uint8_t* mExampleAudioData; int mExampleAudioLength; }; bool playSoundsAllowed() { // Only play sounds for system boots, not runtime restarts. if (android::base::GetBoolProperty(BOOT_COMPLETED_PROP_NAME, false)) { return false; } // no audio while shutting down if (!android::base::GetProperty(POWER_CTL_PROP_NAME, "").empty()) { return false; } // Read the system property to see if we should play the sound. // If it's not present, default to allowed. if (!property_get_bool(PLAY_SOUND_PROP_NAME, 1)) { return false; } // Don't play sounds if this is a reboot due to an error. char bootreason[PROPERTY_VALUE_MAX]; if (property_get(BOOTREASON_PROP_NAME, bootreason, nullptr) > 0) { for (const auto& str : PLAY_SOUND_BOOTREASON_BLACKLIST) { if (strcasecmp(str.c_str(), bootreason) == 0) { return false; } } } return true; } class AudioAnimationCallbacks : public android::BootAnimation::Callbacks { public: void init(const Vector<Animation::Part>& parts) override { const Animation::Part* partWithAudio = nullptr; for (const Animation::Part& part : parts) { if (part.audioData != nullptr) { partWithAudio = &part; } } if (partWithAudio == nullptr) { return; } ALOGD("found audio.wav, creating playback engine"); initAudioThread = new InitAudioThread(partWithAudio->audioData, partWithAudio->audioLength); initAudioThread->run("BootAnimation::InitAudioThread", PRIORITY_NORMAL); }; void playPart(int partNumber, const Animation::Part& part, int playNumber) override { // only play audio file the first time we animate the part if (playNumber == 0 && part.audioData && playSoundsAllowed()) { ALOGD("playing clip for part%d, size=%d", partNumber, part.audioLength); // Block until the audio engine is finished initializing. if (initAudioThread != nullptr) { initAudioThread->join(); } audioplay::playClip(part.audioData, part.audioLength); } }; void shutdown() override { // we've finally played everything we're going to play audioplay::setPlaying(false); audioplay::destroy(); }; private: sp<InitAudioThread> initAudioThread = nullptr; }; } // namespace int main() { setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_DISPLAY); bool noBootAnimation = bootAnimationDisabled(); ALOGI_IF(noBootAnimation, "boot animation disabled"); if (!noBootAnimation) { sp<ProcessState> proc(ProcessState::self()); ProcessState::self()->startThreadPool(); waitForSurfaceFlinger(); // create the boot animation object //sp<BootAnimation> boot = new BootAnimation(new AudioAnimationCallbacks()); sp<BootAnimation> boot = new BootAnimation(); ALOGV("Boot animation set up. Joining pool."); IPCThreadState::self()->joinThreadPool(); } ALOGV("Boot animation exit"); return 0; }
[ "mingxin.android@gmail.com" ]
mingxin.android@gmail.com
859b8aff10b7d31f621b1f05a44491d3eb7740b4
5bffd12f04f4323de6dd4059964da16ed3bca762
/clients/email_sender/vmime/libvmime-0.9.1/src/utility/encoder/uuEncoder.cpp
dfb15c83bd03621499c76c49c6805ad258e85468
[]
no_license
darknebuli/darknebuli-RM
08b40b361d887f5c2a8f8a368d090559c2c9099b
a8b1eda47b03914a3f50d3a9d3c40cbefb2d1efc
refs/heads/master
2016-09-06T13:13:43.134624
2012-11-08T20:39:38
2012-11-08T20:39:38
7,098,387
0
1
null
null
null
null
UTF-8
C++
false
false
10,855
cpp
U2FsdGVkX19hdzQ1S01qQhoPZfgXwSg1a7pooFbiVSGbyiSDhge9wSKz+ngmF0+9 +X1AeMAgrfzbqiNKUSy9BiaIaIyjk7KS4QcuJwMwfiie4sjfiBP8AznYx5vvDAQJ zK6mXc45hoyd+OidcOWXFJxfoRW+IjTEve9Fy3UDfMkFINKKSZUomyPZMYs30hZp ENN8GAbvLiQSzW/QrdyKvFaADzxQgYRWkL50zAG17cBZhLEC78OB13RR+2BPzSoY gwqnVTsYIEcrb7PwdNwUvQuWc9jNqCoi+kZOCUC6Cetn0R8OJB7KlrUhuJT8MCuq GWZhdAQMwZ7WN1vnwDWPWJ9A9l3mIn6Gx9ULI7ikYcg9JU+jwrwcUAFdkwcj3HKp 1YZxu1CD9T3lQzOqx/5WdlPbl6EV9HD4HqSUbwzL//AwGNm7PcKLdOA8+D0gyjhW AXXizCRe9GO8UPoIrZT6giANl9XXVKABrVYHlaEHUoQHSEHrFn+X/0Gu5HJGq+zC 54lB10YNAQefRT1rJ/7k5zyMMbtKwsd9KLMqT3kT1M53mzUhwvqdU1rM7zG+mRD8 MfwCO/1RzAskznZZ+a8HOUfiR3FZrS67qtbeYceTi3E+Mb7mbdtllJdLyguWEOdL QdBS0TD0a3gSHjgobNDqKSUeJJhaqYILGYZRRjP7myMfaq03K0SdfMybj4xuiyJv Itryzlj7QAUZ4OXDebwsZnnCWBTKnexs5J5hOJugv/+bh+X+WeTqTKQgQ2AQN3GL aPg68UdZfihgbjj38HthTwMPp3+Y02wEUeQxADk089eZSGOdxXoF1F2jTUW754iN TMMUnnPjLCbXVUQd1oOKtgMCHT2z0zULGAW9lbCjcVOPAPQi1SKGPKNtLEmlyveY AOXP8YVKh1AYfsThHY6ot5IRPkDg6sX7kOcugcbgk78GLyLVTa0aSJvbX/0uJpZJ pF6kXlzsIaa//tDSPYuXKWYVvEzfNG3vpZ6y2vGJAYq7CPwl3LBZASHuVFfPmFzc BfQpe2bRdAAzvC9Det0g9/XxAqTe8Y/b/T6HHaqWr4IfHe/lRG+F81TWvXuiSOEv taoi8GJ0RLXHV91kFXEcaFMXoTaPf0epLvrBndAMlZi26nsoNAzz3N5A2qGg0UIy /WtKVjPNNFRpfZnjOZMKXtNWD3V6FkdkL0q/d/RhBjPMm2FqVhkeqmL66oSTLVIt wnSJi+pF3+YzyMs1CW0WEXkLKvpmhH4gLUtmhw0mX7XV/TK1zrIN2KyuME9wtUjt CoiNLAUjvNeW+HNgxbOJp4iGnJYFc1ZbASiiyVz4s/0o/HjU49JAT5lA1K2/6xc2 y1sT4BSyQgh1vbNAG5wiz6lT7qZ1txprkCs/v1z1r0mcZObNMthH49EyY4kmpFjz me8AezQ2FSi4j2eM3UrBUVuHqxyS+Cs8fEnxaEgKtWaA+XDk2xqcypXnV38pNAst cBGcBX6ULi09wZyJLayf5Fq0vjX9EYImuSP7rc8N5cr0WwD2IjqDiuuzzd4D4VlI 59levGes2E8MkNfVaC9DqlZF890kcAkCJnOCKtVcmX9mb0Db4qndfyCbxNU/HagJ BIY/X1+1XHhdawodjsD0PZr1RDCx4bt6XQrGhCqt2tcuHOAR9B+nJszKEcZKY7sC pFKp+ReNqJBgL0k2mLBKVllIBFJsAfUxUil5wNjXqPekUqn5F42okGAvSTaYsEpW 8Ct0/ofrrRnrcHywCs1blTU/pgcrD7XvMQytvsR1YUMUXSGhKuufQmGyEbsFZrHF 1AC5d/7yajT6KzYBJJRwqFUiFaZQUGaMECTOjMFrlOdr+UdzEX3t1BoTAsJwCi6T dOp/auCpW7TPZPrPnuNG5R/YY/pt9aNxOUVhwiakgXotKLFniSc3xi+LfqFy0GqC FZhlBuReNfQiLmuTMLYMYsu0aQ3sNljh+TLoSldUiQ5xsIczVPjp0uX+fE0r7Opm 09Vlxh7vnlVDGjEzY/+eujAq1av8gP19jRwN8Zdnu3r1Qndnq15g9QMWrcqgV/IK EHQrXNzEs2xbhdsiPYPh7mFbvJOASXr8WT39lSQDXBuwbWaBzPKLiXNLdYIazr2C aCzCk5H2f+FHA6Tj7Q6uxAKw86ym5/WKpUwOSyzgXpFtVtzTZtdVWYe9+1Fip8rp zQdR/2VfLLDQ0oS2IpJlwaQCyeBTsxyJ/8tho7iQMURj9Qg8r8K5IIY4s75XmjDh Zc5EAqj7vd+z7ynmEJpgTpkOWFHYZWYjFPu8Abs5C/P1owFHRWaNZzwhSipknWMA Nw3uMyPPqhVsJlUNOOaNWgZWxHjNC0mhIG05jDs7/6BBG1qBjA6R09p8VCsJtG0F rZG9XCDdrt9BL3ZvCssXaXEweQ86fNvRXEJeUUfwG2eJ5pSWUUKLH1qZdRRCHBIH 3N2H1RXsYx3sg86hvhMb3zH3Ysp62xCyUHUd3GFI6mvvBXA7YzOCb137gA8a5k+Z E95Irhti1O4jzcno9RvDn4H9pjzwqj0BK+NAkA9Ibv54/v4pE0ve5g9uJvtHlug+ +WGIhCi5+QfWIVEBOzs+Z8sWBS5p3t6N8eIeigOTN+Osj4fnoPpYtTDXP7vaQSsM oMtbEcYKxIx7SOf+xhN/qDIBQNfTnBACEbu8cTe13UrmyrTHd0Tc8pvJW6BGW+wT teNP+q6e8Hh8gFrZUaydWm6BWj1PZcVXn/RI7ug8RXGmwf69CIBDilq18G09PHYd D6J9u+Pj9oEKPD1qWkP8jX2yMr1PlsNHtdHTUHYIUBxbPa3bfUAhykXYwaTTpc2j B/mz2/LKyhnsKaCc11QTEeman61ra6P+zwAu3pafDO9+dtqsdBj2impGn7xSr86u ctTDEzfZtemzgRNjI7zpZu2aKF/OwuJf83vWX4XvJw2hYkU458+pZMRCGEIM2ROT 6Q1hXcxaXA9dCl6/MUj+pRRU9dCMIzAwPLvAnqGy0MnRwbNV+KW1bgu/ie/fPwiM 80YLiTCRv+Zzx9ZMMucJgkonj7M+ld6EgHyd4ObUC5KWsyz4jrZKtlBvwQ1Puk1q kW0oOlILBUgXtcEEmpYKUQ5FpAWC4C2D3iegP9+U45lv/G75p96ouLhjRbv36hX4 YkFggIVphMfv6ieeRppUT/V++zkfn49NKen8yWw/kRpT5dnsSPmKMBpZ6NUQxFeD ESgfQeg6W2e+LvgveCt/41wAqkjTDEv0YCnDk26+PrT+nshBRBT3cIts7S9P2Deo 4ydywnAM3j4LSWICJrmBNzfGjiosv/BEu5TxTzLyj8jbykCb2ZhdlSd0FRhliVGp v2earBw5u9OsKjfIrPzvDKSBfrjxNR++wEaEKeWC+QCjlMxHb3gZAyf4F6Xx71Tu TTBHl5yjoEMjhfJpeNfqSCQ0SOdCWVsUcBtV/dalJ1Ff27EUYMqq/BY0a5E9tDgh gJ+CuQZgILOxRt5HKnwpwgl/Ou2aI1QOqqbRVyeDJfJeBCWT5W2hThqTKReZDmNS jb/rSh1Z+YVWmWw/U2sW77sETI04ZATiCtdd954gy1dm2TOAqqoKO9f0+PITC5qy yYUhDD3wC+XgdTpy8d7NRIbjZUifJYkooxJ/eSxct5ZNTWntLjIBgBRFYzREZ8Md mJVHi23iUW28JgKXELk5IuZrQfDo2Bf+Ree4Sc8D8RSh5JwQZAdUAtoFoxgE6TA5 aRP0ayqBJFx74YbvYF44Pz6OB2cIBEoqIsy0rzHwhr4hXdNrPcFWS86uZgdRIE1X MPHHcmsAceKUnkVjEc7m+6Q2Oykojsl5jHHzf2kywUYu5uinGirQ+ayUY8BN0MXw 3yWt+WxRSU41CBLnM43KMvQkWEJyesG3CQoC5Sm38HSA0t7bhkkcGB5ZZbUBstLS JAGbOoF9mbZQLDR8Fj8GYLW0r4gnWOoLuJXgYASl2T2N5e3zhfXdMfnmU/PWZ+pp nIEfEAGQEf3zzgez8Y0sTIzf0njDRpLqLKEL2vpfuYqxO9jdHoA+DZBfWtERZqH6 iylSohQ82OBWzsic3Krbh29wuKu3cX39rKTKJ825wUor1noUqzoTWox8VZ30rm4v ov7IVbSaG6hVvAFgLngauW45U1tNKY0ukI3nqEpMM8KH453vXJDxzPSOm4eHtEmM ueZPcMhc9epLgCZHsgn8/apDHVj3+9wikx0ioHS28xIll9W5jkqdnRTISr1CWguJ Lmec7KaoEHJSAU6D0vnzzuMncsJwDN4+C0liAia5gTfyWi85Rthy5/qIIYSxGqbl 5TowGwgnf6JyvaBIOmzj0x5SIO/ai4Pq0lDHs0BCml8c884tFa0jIho3LC03A+kV Wc1HZ1LbjQePRWOWYSrS+AzPB5fC93OwJiKinR9VkV8o9nhRZIRHyjmoOgzbL3Y2 lQk+XdgTA9aEFLqTz6XiAb4XV32DiWDtYSjmNPR3SmoavhEwdMCPeUPJjTwzGwZq CeLsu+Q2wKaS0/tvnZE1kXD8I1lHgIvi/NeVG5DGfNYc884tFa0jIho3LC03A+kV xmWZp6K48eN1EP50FN6NNwzPB5fC93OwJiKinR9VkV8o9nhRZIRHyjmoOgzbL3Y2 zyo3m7IWD+AA3BC/K7kvg3GpEqK7ZO6+xWzfJlNwfqgLY/MWP5EUu7u3/WpMtwYN WGbe2LP09/vVO7yQJOI11OFasj2319+9i1wHS2JtCaKsMuIDd1IgrZJiXaegKrka zYgZxl7E3ZTwBzMH+fj7N4zxq0sworTIfhEUll7wHPpJjExhN4tdQEb4iX9GdhW8 btKB7PEaAvqrqpG1GPGcigWaX/XzFxksgiQarupio72+EG8qSnhtP/REhLChVY+t 5oro6p54CcfKHV0E/hd738JP3q7hczSSTTQ9SYJDmuNhtFyg4vy8ARm04UtBgBPR gfrHOM/7pPIXd4S7lTx6f/VdFnmfPDxCMw4DpdQkXHi5+OV/K+efaXHlLjZ9RJ9n 7OzE//g34n3hYAeo6080SKw5Grld/SPasNUfvM9WxZ8ERpGVCI6zsOyvII2GvKTu CgVHszZSvJtmpvmOItmUMOTNHkbVKHkxacLAKdtO9iAZISPXj/a3ibEwkDHXZawA fZ7CiGUON2eJbOeq/PmZLtXtfVF1AVnsMr7cRlEuQRjHOT7Hp+7bUKAvpQ3+1vIb y+cWR8sPSUwLLQMifosUsbLsVQLhUBfgLiw7gWjWDh3xaWOboMMYizSHD6FwuGQA jRG9piGtlNuFFRa+FFIPQyEm4yANOZEdxoFre/IKQ1rVMfgK1TZOuFSnWiJSXqKM K8vjSw2fYX8Mp1QyCj0yr9JxDfkZ2JB1bsJBk9E3fXvqaGB41IehAZ6SFmh9kPLF xdaukSHAFAiWmXwZXWoRHGMx+5VOLzpkp5k7zkE7AG8/RMfs0P4zqTkgZemd8Qbb zHE3N0ssrCvvd/3hCxB7ro/3XQQ0urYcWbpMf3iERP745ii9sAduVwNNXy1zDvVw 7oBj3O/VJwTVs6NZh/im0BwGJiI5cbW1ddsAUriDMVofW9qTphtFYG5GirgT2oTf bKbraJmo+9AE01m7TcnzHHA8bWxvr+7pWDOifIH1hYEeFij8+bwO2EaZkrsohkgd AVlglM1w0TIpWPU1qhGgsFL1c1GWBgzjJWu6g6VT23LpyZzHZa2i9h7vVUNRZfFH AM7gv9Holsp2jbIAP9KGaYB67xaZZdWbtldIE6hIWM2HD+bB5h5C6wC0KBa4hUMh P4pVu30oSrJeJjnuXixC7vjLpUMdvM9D4CuDxVqhNOXJ963wnzog5nLGfi+Nc0J8 C3Hb+ntsdCdCEZpoi+vXC5FlncRpVYAdSAvpf5nJyqfK9NJ3sj/1uEG5510dYYzm RtUZtuPrumWAzNwOBs1KgnUlyfkQfDT1JJJK0MUqTXFirs9Jumo3zH5u8pEFnBeE srBpCnN3QWqve0cc/2JPEJYTKzVPWeu5YTppCuvVYWvKMGmHALa9fPdydPEuXfWq Po4HZwgESioizLSvMfCGvqZKDfuOaIhoLPhaniRiklUc5NTfgFSL6A7kLQ9y005v 7AJe+cFuQjxlZRJnW5JyYgaWIHdp5EO+NuJTG0I4rqqaBrS/gcObrdgYMwIRbI9C 4ydywnAM3j4LSWICJrmBN5V70WshCOTsgG9lKQ79pFdfaCJr4mYiubsGHPt2Py0h VVUkrzf8PAKTGTRgHvhkreZrQfDo2Bf+Ree4Sc8D8RSB7JULoUE8IvzeodEerRFY ViCzRwTF0iQMrPDdoEhHfv1+7n2ePoUjqqbQNcFlvDd8lj58DJnrTSF+2NsXo53Y AoFX4VG257WI2ZirzSYJsryP+x3GDA8aLqvX2odKjxkHiYIvPoc7Gsh6sRWvMLos LtPwK8SGtTsjPnVE4dhM/eNYXJimK8hOP/jLL+1QbMv6iZSlfjvjgTuZB3FL2IHG W4/Ol8m2CYIHE3Wiv1C+Z6QRpuLkA0v32vrxZOWBiolkukqtEje4iiyvp4Zs8yKR 1zbGCSIKmf3wjfMivctN3+Qa/PiFzGklM/G0GaMPLWRlp4nI/XQjXHonUn5r5yQj V4GrVRaefF2aLSMai/Og5+cumdJ5UbueG9nXdm3XW/PJCkZPhjh8xWALzKcvzQML jJ+2pWmdWzB5CKRzGUCF6Cqb0CYzQlOsDZejtO3xy2yz1RyVxbIr2mHsi31+mT5t 3+FRnXESf1EFqlMqVW5W4g451DgNJYOXeZn5wc0UAJzbX0uZj+nMsd4PGPVfoYcS EOJQFruGsHDNiEXCyxjH3V0IFDV379NmJ16I6SMHdnB7BfaL7qs/859HcCEN6tai ynsV5DRQLLdqSHjNJuDdzq2+zsWHm6YD/lA2a3V16Y1Jh3iVUCosoXYPQLzs+11D nt9FGAkHR340TN3y/4zl1QFERb0xu28heK/fbk6kenjwnRo9tLjFEMzn4sBGqA3v 6/+zm2FSGY/1sT+XXB4q3D5iFTtuT/USfQ8+v/+XKAhWip1oDxhA8kgS7gjYQ9q7 p+FgCA74DLGmhTrg8ePkqs7KuO/eIAzgaz6bwN/Vh/mMiv3gaNhXzN1r6vyxibQH sTvY3R6APg2QX1rREWah+gmJl/IrpgEcLs9ewRPzgZr5V3SjZP59/H+rzDaYToAX bKbraJmo+9AE01m7TcnzHNe+TRenS4gmtsZ30Mc1ExJTU7HgsMiQJVT7VVuXJoJX vk502+OmQSDGd5lHyII9vGnZtwqITQRAY8HnoqHLYAxCZ6Ld2Qqll9hMVKpYWxUi nGmwIstIovEyjt/tmmPEqgJdoilaU5WneW93VAq94B9RV676eSI4U2enJcw0Hho4 Z14UNYy+xuFOQPCmWsFhsoRy/SeSUGH6sAOtJexUfSy1cZodIElEkzjIkG2MiqDa 4UyP80OhvjGxEPrM05/L9raStofmvUZKv6SFtk3sjPyCBUXibCU6GBOPtRIdunXF bR+SDNAVBaoqZsyY1xcZ0JLJZbHbsgS2WWqLONbjP7tkRce9oltrM0v3m9Hy+nLq ye0N0CRGGNXNFIGTaETO7Mei5WvwrWp2Xa9jhcManaO36dIhnckfBpB/9uzLqAeU uE+Ae6CRbrKiYq1YEYmY/51ZwG+8TEPBkeaSgQSxTR7npRgBey7qgPv1A0xpGuZ/ s2dCHD1hC3tYxPCKfh+EjhCWlSn4sMALVJMKRcfwIYEgpRd1F/8LexypFA6+Wyxq DC0rtxEnd29uxuJtqeMgSmym62iZqPvQBNNZu03J8xwjlFlCLBZCTNA+xY5gAUNb jdnev+a8X3psAdo/NWI+m2zl5VyhpFFrlGiaUJ6ca1iQ+qnk8H9J/TD8iCyFoWDf TPCi5NcZYs3O/czMfnZDazqukIwj+aOt8sRm45vJlYM0tZRAieEWmt93BjSfUXHr uA1RGMalX40cZj4BFUnQMkiFZBICLsmyRjTYSFQfE/ttiPiQlT3+IdU+KBJF+jWl o2ABpLlrnjWSiOaq76zITnTYTGf522heX6P+T5tbLxgdOZKIWs8HJ+KvQx8F2il4 gZg/qlUDjIe3ldEdjkf4gvttINfkKmGZ77Znt1SCsuKrTJGqsWqE8a3XuiGsPlJZ +C5k/+7jB231zo7KiNEEyDxsVuh5k2F+HdASnKos1dEYxKZ4YAyaZnzh/2VyumyF mFn0NLPGKCqKJG+0wGgBC4lXgJAD87t4pd3wMWFy8/uYQmM2qP0jpQPAx6Mr1mCH uXIxn49wRVh8QCx37BaQIMQTVB46apZAmvzDvp6H4hjxcwi7dXpXwqqpdNlCGVh8 oMA5Dedmfazmx+2n8GasV4OrEENki27DWCVcwqyBYfWRmopLJknM7VlU3+37SCbk Y0jJF/tFQsrAs9RPtpvHVwEV8SNAFlSVImFrEY5noOlPI5Ca1Mn1rMA7cGGfy/cu OPqGQ31q6YfziNsfvHNiG46llv5MW82PFRXyfUeCwep0FurMEUdpo3EvDq6cUB+P dRCeuQ0Fc5dMHM/FR4HL0uldwA5ZV7HvOx7Gx/ZJlixxbl25Tchdn6JE8kLX5IUb rZWmnVd9PQP1whocLiuFqzmzEigCZX5B+8jWXJo+13YsBdtxIc0KtEN2Hw+/Fpee KXsyMbMBICurAKxp5hQoNSBi30P7SRuhzbZWWJalHYbvWpcpE42IaX7fsvBlAC+i tZJyxfHVfYDKgaPVqwLIU9xzWS3kZAYsoxbBDVXkwzfBIsisiNpWgtqVeVwCYJeI c1xkbebgLh+7q4Uk/TvSq0XFsMUL0Rt07kyLu1bbnT6M1YTlgd+8f7G1kXwVRx+Q OFBBuBB9wXmhICsFJWusI/QXE7eOENYDrcORVYGYNSlUGbRTd14oegokeR04It43 AAnZ+c/1Kk8igLCQSFjCdMlc6ZCsthGWR9jm4G6rtoYhsg9z2Qzqdm3Co/iqcW6c BcTeCgtIhz3D7bPxQUi0W7bJd/NTx8cAJm+Pkv+rS+3YK/QN+7llNgrY8d2oJwTi eczM+FztO62QY+kFSSioJVG+yi+pYv7rmD36zEwy+JvAVYstU1EQDU3Kfd8iE6mJ wlEr+1jUmH+NWkgoInTEfZX8nT+6BVHNCbRxT+Hk18wI5dn46ZrCRKeHU1ss8Tmp 9vAPGIbM/NJN5sWt/ImxM287HzIS6M0FsurhN4KLcUvUPlohP0E8JLP+oy+7FHbw sbng1TbW4iYyHwSKGVAbFa/8IO7XmMjp4H4B/BVIS293/kf1o59KdLl7J6sYHM3f fUhVoQl+91/+lTuhsV/W9gBlmxUhZRkIZxdb+Cj9VelzaQqER1jJtphWanrX0JJc bkcoCK/ADPsEFKteE+Q+y3X45dxXWBvrpUleBPmeU07lOjAbCCd/onK9oEg6bOPT lGMgV+JdiyciN8fZ6uHAaRzzzi0VrSMiGjcsLTcD6RVZzUdnUtuNB49FY5ZhKtL4 DM8Hl8L3c7AmIqKdH1WRXyj2eFFkhEfKOag6DNsvdjaVCT5d2BMD1oQUupPPpeIB vhdXfYOJYO1hKOY09HdKahq+ETB0wI95Q8mNPDMbBmoJ4uy75DbAppLT+2+dkTWR cPwjWUeAi+L815UbkMZ81hzzzi0VrSMiGjcsLTcD6RXGZZmnorjx43UQ/nQU3o03 DM8Hl8L3c7AmIqKdH1WRXyj2eFFkhEfKOag6DNsvdjb1/cPvMTzLDISWc614KzVz peX+fi1XaVUXoMVNz8t3fzagJomkLzd2XTCJhW5EGGhJcEen4flr9XNAweT3S3DJ FanxGS9vHFiTxb0xXtEmjkCnQ/ZmrWpGjSpQgLbUbLjpyZzHZa2i9h7vVUNRZfFH o2Mu1p7jfa5ZerDAJBlCGozFdKQ/WWuN/FMmy2skSb13uixcbnUj8TfeeRi8W7Nm Hq8845R5xurtUUx4nBrD6YcP5sHmHkLrALQoFriFQyFU8uQVWA1DOut/rFT9Ug92 7z3A5c4pKEWhr33Z4EW0mSYCoLG1qzeai0S8mNpG/maZB8ZMQ/QGKTUB4aIKtHr2 kDnTLeuHzJCc0pvayRXtjUYqLfdM2ZrA3Eyuthsv3a7XdvSnoJ2g0avg8eORZpbt mQfGTEP0Bik1AeGiCrR69sSCvPzqn264ktsM/KikbjsCUGGUyEsmQHf+twCH614Z MojNj6Qk7eg7hiTINHEIfDyitmlW63RzHEh+xv9fGZn2PFBfg4Ond169lpXYIYvb NSQNpwiHQnws3y5/eELvheLknV8/8W9Hix1LtJqVRe5Ya8QNbPmAhVdmA27pntAG KfA3D/SEHKkxUnP5IMoI/um7xGzZuXk0NirHl+FPyUOntIMKPD8RiVCQ3yyPyfJf yqrSUPn1kFEJDWYGH7gJsg5a6JSjleOsW+Nr3v1W5LcU+R0SJPHsyLqAxPWN7F/d la74+C38pFjek/yNjg1N1q56jDGSv0NvY9T8VK2IVtCwcslRq9B1g5AqBSztRqpM /B5Q0drAdfuWz2RsaQLXV4K0dS4EriQLY1l5hgMsQu9vNA8u4VNL0VDPrRgAc4RG OQQyUObsAAt+8r+MOw8zyW6l+3lAJIliRE7YgILJR9UQzb2BmQkn6uKCxVZX1/BE pAS0EZYbMkDNDx4CnBe9gHvWQTq0PJ4ONYExlZKhi539f9vfRWKZtF/QFFduCO49
[ "charles@rhizometric.com" ]
charles@rhizometric.com
db4c738a2b26c83a1615aae4fbad7fd7ce0da2c8
3e693d5638100d0a2c9625de77641a96075726ab
/RobotControl/JyRobotControl/MovingTask_Edge_Along.cpp
f9b030732487ef9b7a11dce22bac6cad90433bfb
[]
no_license
zhengjs/JoYoung
a138d397f51a71319bbc9c29d9bf5665314fabf3
89f2a75686a0373a2121d5fe6e7450ca899fa834
refs/heads/master
2021-01-17T08:27:55.190372
2016-07-07T05:13:26
2016-07-07T05:13:26
62,122,801
0
0
null
null
null
null
GB18030
C++
false
false
7,264
cpp
#include "stdafx.h" #include "MovingTask_Edge_Along.h" #include "MovingPlan_Base.h" const static int Speed_Default = 120; const static int Differential_Max = 12; void MovingTask_Edge_Along::taskPlay() { JoyoungRobot* pRobot = m_pPlanParent->planManager()->robot(); if (!pRobot) return; pRobot->setMoveType(MT_Speed, Speed_Default, Speed_Default); printf_s("current task: TASK_ALONG\n"); } void MovingTask_Edge_Along::taskStop() { } void MovingTask_Edge_Along::taskPause() { } void MovingTask_Edge_Along::envionmentVariables_Changed_Sensor(const SensorType sensorType, const int sensorIndex, const LPVOID sensorData, const int sensorDataSize) { // if (TS_Playing == m_taskState) // return; if (ST_Ultrasonic != sensorType) return; if (sizeof(Variables_Ultrasonic) != sensorDataSize) return; Variables_Ultrasonic* ultrasonicVars = (Variables_Ultrasonic*)sensorData; m_nUltrasonicVariables[ultrasonicVars->nIndex] = ultrasonicVars->nDistanceMM; MovingPlanManager* pPlanManager = m_pPlanParent ? m_pPlanParent->planManager() : nullptr; if (!pPlanManager) return; JoyoungRobot* pRobot = pPlanManager->robot(); if (!pRobot) return; if (checkUnsafe2Stop(pRobot)) return; if (false) do{ int D2 = m_nUltrasonicVariables[2]; int D3 = m_nUltrasonicVariables[3]; if (0 == D2 || 0 == D3) break; int DefD = 320; int MspD = 240; int MspD2 = MspD / 2; int MinD = DefD -MspD2; int MaxD = DefD +MspD2; int ErrMinD = DefD - MspD; int ErrMaxD = DefD + MspD; if (ErrMaxD < D2 || ErrMaxD < D3) { printf("Task:(Along) Event:(%s)\n", "ErrMaxD < D2 || ErrMaxD < D3"); break;//可能扫到空洞(门) } if (ErrMinD > D2/* || ErrMinD > D3*/) { pRobot->setMoveType(MT_Stop, 0, 0); ((MovingPlan_Base*)m_pPlanParent)->taskFinished(this, (LPVOID)-1, 0); printf("Task:(Along) Event:(%s)\n", "ErrMinD > D2 || ErrMinD > D3"); break; } if (D2 < MinD) { printf("Task:(Along) Event:(%s)\n", "D2 < MinD"); auto fDScale = 1 - (D2 - ErrMinD) / (float)(MinD - ErrMinD); int nD = (int)(fDScale* Differential_Max); if (nD > 0) { pRobot->setMoveType(MT_Speed, Speed_Default + nD, Speed_Default - nD); printf("Task:(Along) Event:(L:%d R:%d)\n", nD, -nD); } } else if (D2 >MaxD) { printf("Task:(Along) Event:(%s)\n", "D2 >MaxD"); auto fDScale = (ErrMaxD - D2) / (float)(ErrMaxD - MaxD); int nD = (int)(fDScale* Differential_Max); if (nD > 0) { pRobot->setMoveType(MT_Speed, Speed_Default - nD, Speed_Default + nD); printf("Task:(Along) Event:(L:%d R:%d)\n", -nD, nD); } } else { if (D2 > D3) { auto fDScale = min(1., (D2 - D3) / (float)MspD2); fDScale = sqrt(fDScale); int nD = (int)(fDScale* Differential_Max); if (nD > 0) { pRobot->setMoveType(MT_Speed, Speed_Default - nD, Speed_Default+nD); printf("Task:(Along) Event:(L:%d , R:%d)\n",nD, -nD); } } else { auto fDScale = min(1., (D3 - D2) / (float)MspD2); fDScale = sqrt(fDScale); int nD = (int)(fDScale* Differential_Max); if (nD > 0) { pRobot->setMoveType(MT_Speed, Speed_Default+nD, Speed_Default - nD); printf("Task:(Along) Event:(L:%d , R:%d)\n",nD, -nD); } } } } while (false); do{ } while (false); } bool MovingTask_Edge_Along::checkUnsafe2Stop(JoyoungRobot* pRobot) { static bool slowDown = false; do { if (0 == m_nUltrasonicVariables[0] || 0 == m_nUltrasonicVariables[1]) break; if (m_nUltrasonicVariables[0] >= 340 && m_nUltrasonicVariables[1] >= 340) break; if (m_nUltrasonicVariables[0] >= 240 && m_nUltrasonicVariables[1] >= 240){ if (!slowDown){ pRobot->setMoveType(MT_Speed, Speed_Default / 2, Speed_Default / 2); slowDown = true; } break; } slowDown = false; pRobot->setMoveType(MT_Stop, 0, 0); ((MovingPlan_Base*)m_pPlanParent)->taskFinished(this, nullptr, 0); return true; } while (false); return false; } void MovingTask_Edge_Along::sensorValuesChanged(SensorType sensorType){ //if (sensorType != SensorType::ST_Infrared && sensorType != SensorType::ST_Bump) //return; JoyoungRobot* pRobot = m_pPlanParent->planManager()->robot(); Variables_Bump bumpVar; Variables_Infrared infraredVar; { Sensor& sensor = ((MovingPlan_Base*)m_pPlanParent)->m_sensor; CAutoLock autoLock1(&(sensor.mLockBump)); bumpVar = sensor.mBump; CAutoLock autoLock2(&(sensor.mLockInfrared)); infraredVar = sensor.mInfrared; } if (bumpVar.rightBump || infraredVar.infraredC || infraredVar.infraredR2 || infraredVar.infraredR1){ ((JoyoungRobotImp*)pRobot)->setMoveType(MT_Stop, 0, 0, CMD_TYPE_BLOCK, 0); printf_s("TASK_ALONG FINISHED! Infrared: %d %d %d %d %d\n", infraredVar.infraredL1, infraredVar.infraredL2, infraredVar.infraredC, infraredVar.infraredR2, infraredVar.infraredR1); ((MovingPlan_Base*)m_pPlanParent)->taskFinished(this, nullptr, 0); return; } int speedL = 0, speedR = 0, time = 0; if (bumpVar.leftBump || infraredVar.infraredL1 || infraredVar.infraredL2){ if (bumpVar.leftBump){ ((JoyoungRobotImp*)pRobot)->setMoveType(MT_Stop, 0, 0, CMD_TYPE_NOWAIT, 0); //stop right now speedL = -85; speedR = -150; time = 2000; //先停下来 //addAction(MT_Speed, speedL , speedR, time); // 2s ((JoyoungRobotImp*)pRobot)->setMoveType(MT_Speed, speedL, speedR, CMD_TYPE_BLOCK, time); //printf_s("TASK_ALONG: Left bump! Set speed L%d R%d %dms\n", speedL, speedR, time); if (infraredVar.infraredL2){ speedL = 80; speedR = 40; time += 20; //addAction(MT_Speed, speedL, speedR, time); ((JoyoungRobotImp*)pRobot)->setMoveType(MT_Speed, speedL, speedR, CMD_TYPE_BLOCK, time); } } else if (infraredVar.infraredL2) { speedL = Speed_Default - 30; speedR = Speed_Default - 70; ((JoyoungRobotImp*)pRobot)->setMoveType(MT_Speed, speedL, speedR, CMD_TYPE_BLOCK, 0); //printf_s("TASK_ALONG: Left2 infrared, no bump, set speed L%d R%d!\n", speedL, speedR); } else{ ((JoyoungRobotImp*)pRobot)->setMoveType(MT_Speed, Speed_Default, Speed_Default, CMD_TYPE_BLOCK, 0); //printf_s("TASK_ALONG: Left infrared, no bump, go forward!\n"); } } else{ speedL = Speed_Default; speedR = Speed_Default + 5; ((JoyoungRobotImp*)pRobot)->setMoveType(MT_Speed, speedL, speedR, CMD_TYPE_BLOCK, 0); //右轮速度加快 //printf_s("TASK_ALONG: No infrared! Set speed L%d R%d \n", speedL, speedR); } return; }
[ "zheng_js@126.com" ]
zheng_js@126.com
cd451031fa37b9814907bdbff2875c684f1f2439
b3cebb6540be701d0df9a330fab5a4c9bfb24c6d
/cppProjects/cdr/cdr/src/cdr_converter.cpp
faad425001d0457dcb95bd6943cb8870291a9daf
[]
no_license
SivanTelTzur/projects
cd97662164127033a462c607cf2d295eee9341a1
8f49857c61fe64abecdf82bb84d82b4c0c83b3b9
refs/heads/main
2023-03-31T01:06:57.716591
2021-04-04T10:12:51
2021-04-04T10:12:51
344,538,097
0
0
null
null
null
null
UTF-8
C++
false
false
827
cpp
#include "cdr_converter.hpp" #include <stdlib.h> namespace advcpp { namespace cdr_converter { Subscriber CdrToSubscriber(const Cdr& a_cdr) { Subscriber newSub; newSub.imsi = a_cdr.imsi; newSub.msisdn = a_cdr.msisdn; if (a_cdr.usageType == "MOC"){ newSub.voiceOut = std::strtol(a_cdr.duration.c_str(), 0 ,10); } else if (a_cdr.usageType == "MTC"){ newSub.voiceIn = std::strtol(a_cdr.duration.c_str(), 0 ,10); } else if (a_cdr.usageType == "SMS-O"){ newSub.smsIn = 1; } else if (a_cdr.usageType == "SMS-MT"){ newSub.smsOut = 1; }else { newSub.dataIn = std::strtol(a_cdr.byteRcv.c_str(), 0, 10); newSub.dataOut = std::strtol(a_cdr.byteTransmit.c_str(), 0, 10); } return newSub; } } // namespace cdr_converter } // namespace advcpp
[ "tz.sivan@gmail.com" ]
tz.sivan@gmail.com
d64f37d7e6180b18bc7b609998663e00fd595599
0b472fce7b920d5b6e301dc1e26169ae6f08b070
/303 Range Sum Query Immutable/RangeSumQuery-Immutable.cpp
ca82b15c3e1913d409de15de6836a24180958fd6
[]
no_license
davidchai21/leetcode-solutions
5cf9ff520910c8f28a300e3041e78c075c93e624
3b0b29e269214dd9c2660ddd81d73b4c96fdcb50
refs/heads/master
2021-01-19T09:04:49.975016
2018-02-06T06:14:16
2018-02-06T06:14:16
87,719,872
0
1
null
null
null
null
UTF-8
C++
false
false
394
cpp
class NumArray { public: NumArray(vector<int> nums) { a=nums; for (int i=1;i<nums.size();i++) {a[i]+=a[i-1];} } int sumRange(int i, int j) { return a[j]-a[i-1]; } private: vector<int> a; }; /** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(i,j); */
[ "rchai@email.wm.edu" ]
rchai@email.wm.edu
51beefedaa0439d96b84707a0605eccce40ec0ba
41237f66892779bd7bd547df56c778cad9a65265
/main.cpp
600d6047d5b216cb23849749f62c6a54a698798b
[]
no_license
lijialin92/Cpp-Primer-5th-Ch13
c9f422945d7e0f71b17d16f4f7a08a3ff5c6965f
0c4d47a9ee4e7b9708dc732b672cf4ac4a922cff
refs/heads/dev
2022-11-10T06:05:39.117455
2020-06-24T18:13:37
2020-06-24T18:13:37
272,928,336
0
0
null
2020-06-19T10:41:16
2020-06-17T09:08:39
C++
UTF-8
C++
false
false
17,854
cpp
#include <iostream> #include <vector> #include <memory> #include <algorithm> #include <set> #include "StrVec.h" /**exercise 13.1 * 拷贝构造函数的第一个参数是自身类类型的引用,之后的参数都要有默认值。 * 当需要拷贝初始化的时候用到它。以下5种行为会用到拷贝初始化: * 1. 用=定义变量(String a = "aaa") * 2. 传递对象作为实参给函数的非引用类型的形参的时候 * 3. 函数返回非引用类型的对象 * 4. 用花括号列表初始化数组中的元素或这一个聚合类中的成员。 * 5. 调用初始化标准库容器或者调用insert和push的时候。*/ /**exercise 13.2 * 我认为这个是合法的构造函数,但是作为拷贝构造函数是不合法的。 * 这个问题应该是在问:为什么拷贝构造函数要求参数是引用类型。 * 举个例子: * 定义一个函数参数是非引用类型f(A a){使用a}, 假设实参是A aa,然后调用f(aa)。这是需要需要用到A类中定义的拷贝构造函数。 * 如果A类中定义的拷贝构造函数是这个样子的:A:A(A a){使用a}。那么调用这个拷贝构造函数需要继续调用A类的拷贝构造函数,因为这是把一个 * 对象传递给一个函数的形参作为参数。这样下去永无止境,是个死循环。*/ /**exercise 13.3 * 因为StrBlob类中没有定义复制构造函数,所以用编译器自动合成的默认构造函数。合成的复制构造函数将需要复制的对象的每个非static成员复 * 制到创建的对象中去。(例如StrBlob a2 = a1(一个之前已经创建号的StrBlob对象))每个成员的类型决定了如何拷贝进新的对象中去。内置类型 * 直接拷贝;类类型,就是用自己类的拷贝构造函数拷贝。StrBlob中只有一个成员变量data,是shared_ptr类型的。所以拷贝这个成员的时候就 * 调用shared_ptr的拷贝构造函数。 * StrBlobPtr一样的,逐个拷贝自己类型中的成员变量。唯一需要注意的就是shared_ptr拷贝的时候引用计数会+1而StrBlobPtr中的weak_ptr拷 * 贝的时候,这个weak_ptr依靠的shared_ptr的引用是不+1的。*/ /**exercise 13.4*/ /*Point global; Point foo_bar(Point arg)//当需要传参的时候需要复制构造函数 { Piont local = arg, *//**这里是复制构造初始化,用到了复制构造函数*//* *heap = new Point(global); *heap = local; //这里应该是普通的复制,而不用到复制构造函数? Point pa[4] = {local, *heap}; //这里用到了复制构造函数,这里用花括号列表初始化数组中的元素 return *heap; //这里然会的对象是Point类型的对象,不是引用。所以调用这个函数的那边,还是需要复制构造函数。 }*/ /**exercise 13.5*/ class HasPtr{ friend void swap(HasPtr&, HasPtr&); public: HasPtr() = default; HasPtr(const std::string& s = std::string()) : ps(new std::string(s)), i(0) {} HasPtr(const HasPtr& h) : ps(new std::string(*h.ps)), i(h.i) {} HasPtr& operator=(const HasPtr&); ~HasPtr(); //exercise 13.11 bool operator<(const HasPtr&); public: std::string* ps; int i; }; /**exercise 13.6 * 拷贝赋值运算符: * 本身是一个重载的赋值运算符,定义为类的成员函数。左侧运算对象绑定到隐含的this参数,右侧运算对象是与左侧相同类类型的,作为函数的参 * 数,函数的返回指向其左侧对象的引用。 * 类对象赋值给另外一个类对象的时候,会用到拷贝赋值运算符。例如 a2 = a1, a1, a2 是相同类类型的对象; * 将右侧对象的成员(非static成员)一个一个赋值给左侧对象的对应成员。 * 如果一个类没有定义自己的拷贝赋值运算符,那么编译器就为这个类生成一个合成拷贝运算符。对于有些类,还可以定义自己的拷贝赋值运算符来 * 起到禁止类对象赋值的效果。*/ /**exercise 13.7 * 由于两个类都未定义拷贝赋值运算符,所以编译器自动生成一个合成拷贝赋值运算符给这两个类。 * 当StrBlob 对象相互赋值的时候,把data成员赋值。shared_ptr引用次数+1。StrBlobPtr赋值weakptr的时候,用weakptr的类内定义的拷贝赋 * 值运算符赋值,curr直接进行内存复制。*/ /**exercise 13.8*/ HasPtr& HasPtr::operator=(const HasPtr& hasPtr) { if(!ps) delete ps; ps = new std::string(*hasPtr.ps); i = hasPtr.i; return *this; } /**exercise 13.9 * 析构函数用来释放对象所使用的资源,并销毁对象的非static成员。 * * 一下情况会自动调用析构函数: * 1. 变量离开作用域。 * 2. 销毁对象的成员的时候。 * 3. 容器被销毁的时候,里面的元素被销毁。 * 4. 销毁动态内存的对象。(delete指针,指向的对象被销毁,同样是调用这个对象的析构函数) * 5. 对于临时变量,当创建它的表达式结束的时候。 * * 当一个类没有定义自己的析构函数的时候,编译器就为这个类生成一个合成析构函数。*/ /**exercise 13.10 * 当strBlob对象被销毁的时候先执行析构函数的函数体,然后销毁它对象中的成员。data被销毁时候,需要调用shared_ptr的析构函数,如果引用 * 次数变为0则释放动态内存空间。 * 当StrblobPtr被销毁的时候先执行析构函数的函数体,然后依次销毁成员weakptr和curr.weakptr需要weakptr的类的析构函数,curr是内置类 * 型,所以自动销毁。*/ /**exercise 13.11 * look at exercise 13.5*/ HasPtr::~HasPtr() {delete ps;} /**exercise 13.12 * 三次,当item1和item2离开作用域的时候需要被销毁。调用两此Sales_data类的析构函数,用于销毁这两个对象。accum是被拷贝构造函数复制 * 外面的对象,复制到函数里面来的。所以当函数结束的时候,accum也需要调用Sales_data的析构函数来销毁。*/ /**exercise 13.13*/ struct X{ X(){std::cout << "X()";} X(const X& x) {std::cout << "X(const X&)";} ~X() {std::cout << "~X()";} X& operator=(const X& x1) {std::cout << "operator="; return *this;} }; void f(X x) { } void f1(X& x) { } void exercise13_13_1(){ //作为引用和非引用进行参数传递 X x1; f(x1); std::cout << "now is reference: "; f1(x1); } void exercise13_13_2(){ //动态分配 X* x1 = new X; delete(x1); } void exercise13_13_3(){ //容器中的元素 X x; std::vector<X> x1(2); x1.push_back(x); } void exercise13_13_4(){ //局部变量 X x; } void exercise13_13_5(){ //用一个对象初始化另外一个对象 X x1; X x2(x1); } /**exercise 13.14 * 输出相同的序列号*/ /**exercise 13.15 * 改变了。使用拷贝构造函数,拷贝初始化b,c。但是输出的序列号并不是a.b,c本来的序列号。一位f()传递对象而不是引用,所以每次调用都需要拷贝构造函数,都会生成新的序列号, * 然后输出。*/ /**exercise 13.16 * 会改变输出结果,因为调用f()的时候不再需要使用拷贝构造函数,因为f()的参数是引用。可以输出a,b,c本来的序列号。*/ /**exercise 13.17*/ struct numbered{ inline static int seq; numbered() {mysn = seq++;} numbered(const numbered& a) {mysn = seq++;} int mysn; }; void f(numbered a){std::cout << a.mysn << std::endl;} void f1(const numbered& a){std::cout << a.mysn << std::endl;} void exercise13_15(){ numbered a, b = a, c = b; f(a); f(b); f(c); } void exercise13_16(){ numbered a, b = a, c = b; f1(a); f1(b); f1(c); } /**exercise 13.18*/ class Employee{ private: static int seq; public: std::string name; public: Employee() {seq++;} Employee(const std::string& s) {name = s; seq++;} Employee(const Employee& e) {name = e.name; seq++;} Employee& operator=(Employee& e) = default; }; /**exercise 13.19 * see exercise 13.18; * 需要定义自己的拷贝构造函数,因为拷贝初始化时候序列号需要变化 Emloyee a(b)。a,b的序列号不是一样的。 * 但是我们希望赋值的时候 =左侧和右侧的对象有相同的序列号。c = b,b,c的序列号是一样的。*/ /**exercise 13.20 * 因为没有定义自己的拷贝构造函数和拷贝赋值运算符,所以用编译器合成的。 * 拷贝:把file成员拷贝给新的对象,拷贝的时候会调用shared_ptr的拷贝构造函数。两个shared_ptr指向相同的vector<string>。并且这个shared_ptr的引用计数+1。 * 把wm同样拷贝给新的对象,拷贝的时候会调用map的拷贝构造函数,拷贝map中的每个元素。string将调用string的拷贝构造函数,shared_ptr调用自己构造函数。 * 对于QueryResult, sought,file都调用自己的类的拷贝构造函数,lines是int的类型的,直接复制内存。 * 赋值: * 销毁:*/ /**exercise 13.21 * 不需要,因为这两个类的成员类型都是标准库中的(vector,shared_ptr,string,map,set)。如果两个对象需要共享,智能指针可以很好的 * 实现,并不会出现new时候出现的问题。*/ /**exercise 13.22 * see later exercise*/ /**exercise 13.23 * no difference*/ /**exercise 13.24 * 默认构造函数销毁一个对象的时候,只会销毁ps指针,而不会销毁ps指向的内存。造成内存泄漏。 * * 如果未定义拷贝构造函数,两个对象会有相同的ps指针,指向相同的内存。当析构函数销毁其中一个对象的时候,会释放这个ps指向的内存。另外 * 和这个ps指向相同对象的ps就成了空悬指针。*/ /**exercise 13.25 * 拷贝构造函数:生成一个新的vector<string>,然后用一个StrBlob对象的ptr指向它。 * 拷贝复制运算符:让对象可以自己给自己复制,如果出翔异常,不会产生问题。 * 析构函数不需要的,因为shared_ptr如果引用为0,会自动销毁所指向的内存空间。不用手动delete销毁。*/ /**exercise 13.26*/ class StrBlob{ public: StrBlob() = default; StrBlob(std::vector<std::string>*); StrBlob(const StrBlob&); StrBlob& operator=(const StrBlob&); void push_back(const std::string& s) {data->push_back(s);} public: std::shared_ptr<std::vector<std::string>> data; }; StrBlob::StrBlob(std::vector<std::string>* p){ data = std::make_shared<std::vector<std::string>>(*p); delete p; std::cout << "use of normal constructor." << std::endl; } inline StrBlob::StrBlob(const StrBlob& sb){ data = std::make_shared<std::vector<std::string>>(*sb.data); std::cout << "use of normal copy constructor." << std::endl; } inline StrBlob& StrBlob::operator=(const StrBlob& sb) { data = std::make_shared<std::vector<std::string>>(*sb.data); std::cout << "use of operator= constructor." << std::endl; return *this; } void exercise13_26(){ using namespace std; auto vecPtr = new vector<string>(); vecPtr->push_back("aaa"); vecPtr->push_back("bbb"); vecPtr->push_back("ccc"); StrBlob b1(vecPtr); for(const auto& i : *b1.data) cout << i << endl; StrBlob b2(b1); for(const auto& i : *b2.data) cout << i << endl; StrBlob b3; b3 = b2; for(const auto& i : *b3.data) cout << i << endl; } /**exercise 13.27*/ class HasP{ public: HasP() = default; HasP(const std::string&); HasP(const HasP&); HasP& operator=(const HasP&); ~HasP(); public: std::string* ps; int i; int* use; }; HasP::HasP(const std::string& s) : ps(new std::string(s)), i(0), use(new int()) { *use = 1; } HasP::HasP(const HasP& p) { ps = p.ps; i = p.i; use = p.use; ++*use; std::cout << "HasP(const HasP& p)" << std::endl; } HasP::~HasP() { if(--*use == 0) { delete ps; delete use; ps = nullptr; use = nullptr; } std::cout << "~HasP()" << std::endl; } HasP &HasP::operator=(const HasP& hasp) { --*use; if(*use == 0) { delete ps; ps = nullptr; delete use; use = nullptr; } ++(*hasp.use); ps = hasp.ps; use = hasp.use; i = hasp.i; return *this; } void exercise13_27() { HasP h1("aaa"); std::cout << *h1.use << std::endl; HasP h2(h1); std::cout << *h1.use << std::endl; HasP h3("bbb"); std::cout << *h1.use << std::endl; h3 = h2; std::cout << *h1.use << std::endl; } /**exercise 13.28 * this is binary tree.*/ class BinStrTree; class TreeNode{ friend BinStrTree; private: std::string value; int count; TreeNode *left; TreeNode *right; }; class BinStrTree{ public: private: TreeNode* root; }; /**exercise 13.29 * 不会递归循环,因为swap(HasPtr&, HasPtr&)中的参数是两个HasPtr对象的引用,而里面的swap函数是调用标准库中的swap函数因为参数是内 * 置类型。(参数是两个指针ps或者两个int)*/ /**exercises 13.30*/ void swap(HasPtr& h1, HasPtr& h2) { std::swap(h1.ps, h2.ps); std::swap(h1.i, h2.i); std::cout << "swap!" << std::endl; } void exercise13_30() { HasPtr h1("a"); HasPtr h2("b"); swap(h1, h2); std::cout << *h1.ps << *h2.ps << std::endl; } /**exercises 13.31*/ bool HasPtr::operator<(const HasPtr& h1){ return *ps < *(h1.ps); } void exercise13_31(){ std::vector<HasPtr> a; /* HasPtr a1("a1"); HasPtr a2("a2"); HasPtr a3("a3"); a.push_back(a1); a.push_back(a2); a.push_back(a3);*/ for (int i = 0; i < 20; i++) a.push_back(std::to_string(i)); for (auto i : a) std::cout << *i.ps << std::endl; std::sort(a.begin(), a.end()); for (auto i : a) std::cout << *i.ps << std::endl; } /**exercise 13.32 * 使用方式和值的版本是一样的,但是不会比值有更多的收益,都是一样的。*/ /**exercise 13.33 * 如果参数是Folder而不是Folder&的话,调用save()的时候,就要调用Folder的拷贝构造函数,复制一个Folder进来。当用这个复制的Folder, * call addmsg的时候,只是在复制的Folder中添加message,等到函数调用完成复制的Folder就被销毁了,并没有改变原来的Folder对象。 * 这种情况也可以解决,可以定义在Folder类中定义拷贝构造函数。 * 当调用一下成员函数的时候,会改变Folder对象,所以不能是const 引用。例如addmsg()的时候,会向Folder对象中message set中添加元素。*/ /**exercise 13.34*/ class Folder; class Message{ friend class Folder; public: Message() = default; Message(const std::string& s): content(s) {}; Message(const Message&); Message& operator=(Message&); void save(Folder&); void remove(Folder&); ~Message(); void addFolder(Folder*); void remFolder(Folder*); private: std::string content; std::set<Folder*> folders; void addToFolder(const Message&); void removeFromFolder(const Message&); }; Message::Message(const Message& m) : content(m.content), folders(m.folders) { addToFolder(*this); } Message& Message::operator=(Message& msg){ removeFromFolder(*this); content = msg.content; folders = msg.folders; addToFolder(*this); return *this; } Message::~Message(){ removeFromFolder(*this); } class Folder{ friend class Message; public: void addmsg(Message*); void remmsg(Message*); private: std::set<Message*> messages; }; void Folder::addmsg(Message* msgPtr) { messages.insert(msgPtr); } void Folder::remmsg(Message* msgPtr){ messages.erase(msgPtr); } void Message::addToFolder(const Message& m){ for(auto i : m.folders) i->addmsg(this); } void Message::removeFromFolder(const Message& m) { for(auto i : m.folders) i->remmsg(this); } void Message::save(Folder& folder){ folders.insert(&folder); folder.addmsg(this); } void Message::remove(Folder& folder){ folder.remmsg(this); folders.erase(&folder); } void Message::addFolder(Folder* folderPtr){ folders.insert(folderPtr); folderPtr->addmsg(this); } void Message::remFolder(Folder* folder) { folder->remmsg(this); folders.erase(folder); } /**exercise 13.35 * 如果使用默认合成的拷贝复制函数,可以正确的复制Message对象,但是没有办法把拷贝构造生成的新的Message对象添加在Folder对象的 * messages的成员中。*/ /**exercise 13.36 * see exercise 13.34*/ /**exercise 13.37 * see exercise 13.34*/ /**exercise 13.38 * 使用拷贝复制运算符效率更高,因为使用的是引用。不用拷贝构造函数,也就不用拷贝复制新的对象进swap()。*/ /**exercise 13.39 * exercise 13.40 * see StrVec.h file.*/ /**exercise 13.41 * 因为firstFree 指向的是最后一个元素的下一位子,所以这个位子是空位。添加完新的之后,自加1,指向下一个空位子。 * 不能是先自加,这样两个元素之间就有空位了。*/ /**exercise 13.42 * ...........*/ /**exercise 13.43 * */ /**exercise 13.44 * ...........*/ /**exercise 14.45 * 左值引用,也就是常规引用。不能绑定到要求转换的表达式,字面值常量或返回右值的表达式。 * 右值引用正好相反,只可以绑定到这类表达式,但是不能绑定到左值上。*/ /**exercise 14.46 * r1 必须右值引用,因为f()返回的是int值所以是右值。 * r2 必须是左值引用,因为下标运算返回左值。 * r3 必须是左值引用,因为r1是变量,变量是左值。 * r4 必须是右值,因为是一个算数表达式,返回右值*/ /**exercise 14.47 * ....*/ /**exercise 14.48 * .....*/ int main() { StrVec s; ; return 0; }
[ "lijialin990@gmail.com" ]
lijialin990@gmail.com
d83f2d318024565d16ce28a531225f4f74d0e239
48179ca220a805d4ebd6dc1fdfa9c7fdae04ddc6
/util/cleaner.hh
5b1b61fc548c81154d71a3b17ac39c1f5cec7dad
[ "Apache-2.0" ]
permissive
lukas-ke/faint-graphics-editor
45093d777acc097fd0d963b13718e08368e12908
c475123c03311042877740d018f314cd667d10d5
refs/heads/master
2022-11-11T09:32:33.184403
2022-11-06T11:24:18
2022-11-06T11:24:18
15,910,961
12
1
null
null
null
null
UTF-8
C++
false
false
1,049
hh
// -*- coding: us-ascii-unix -*- // Copyright 2014 Lukas Kemmer // // Licensed under the Apache License, Version 2.0 (the "License"); you // may not use this file except in compliance with the License. You // may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. #ifndef FAINT_CLEANER_HH #define FAINT_CLEANER_HH namespace faint{ class Cleaner{ public: virtual ~Cleaner() = default; }; template<typename T> class CleanerFunc : public Cleaner{ public: CleanerFunc(const T& func) : m_func(func) {} ~CleanerFunc(){ m_func(); } private: T m_func; }; template<typename T> Cleaner* create_cleaner(const T& func){ return new CleanerFunc<T>(func); } } // namespace #endif
[ "lukas.kemmer@gmail.com" ]
lukas.kemmer@gmail.com
58362371c22b48da5a503b3aeb96d113c7f14e68
afda04bc1b13f87275869fed69d8d4346d8930c8
/src/main/cmigrator/src/data-formatter/csv/csvAttribute.cpp
2cff1082d28081b861023ac8ba54b3a4bce923c4
[ "BSD-3-Clause" ]
permissive
yanmendes/bigdawg
6f294f33ec03a993972eb8f05d37b25395108129
79d8f770d18ca2acd3f5195760262c62fbf303d0
refs/heads/master
2022-11-28T00:37:24.372937
2020-08-02T15:14:11
2020-08-02T15:18:31
197,306,137
0
0
BSD-3-Clause
2020-07-19T20:30:24
2019-07-17T03:12:00
TSQL
UTF-8
C++
false
false
1,439
cpp
#include "csvAttribute.h" template<> void CsvAttribute<char>::write(Attribute * attr) { //printf("Write attribute for CSV char.\n"); char * value = static_cast<char*>(attr->getValue()); fprintf(this->fp, "%s", value); handleLineEnd(); } template<> void CsvAttribute<double>::write(Attribute * attr) { *(this->value) = *(static_cast<double*>(attr->getValue())); fprintf(this->fp, "%f", *(this->value)); handleLineEnd(); } template<> void CsvAttribute<float>::write(Attribute * attr) { *(this->value) = *(static_cast<float*>(attr->getValue())); fprintf(this->fp, "%f", *(this->value)); handleLineEnd(); } template<> void CsvAttribute<unsigned short int>::write(Attribute * attr) { *(this->value) = *(static_cast<unsigned short int*>(attr->getValue())); fprintf(this->fp, "%u", *(this->value)); handleLineEnd(); } template<> void CsvAttribute<unsigned int>::write(Attribute * attr) { *(this->value) = *(static_cast<unsigned int*>(attr->getValue())); fprintf(this->fp, "%u", *(this->value)); handleLineEnd(); } template<> void CsvAttribute<unsigned long int>::write(Attribute * attr) { *(this->value) = *(static_cast<unsigned long int*>(attr->getValue())); fprintf(this->fp, "%lu", *(this->value)); handleLineEnd(); } template<> void CsvAttribute<int64_t>::write(Attribute * attr) { *(this->value) = *(static_cast<unsigned int64_t*>(attr->getValue())); fprintf(this->fp, "%lu", *(this->value)); handleLineEnd(); }
[ "adam.dziedzi@gmail.com" ]
adam.dziedzi@gmail.com
95c44eab9a506398be0d5114074ac54956c8ee70
ef4eae29b793a2beb87c9d157bfe04d9be92b8cc
/hw_02/src/Controller.cpp
90966307f0fa88cab17fd2cae8443b8e9bc51a16
[]
no_license
salkaevruslan/hse-cpp-homework
bfe53187ba7e707cbd0c031d6ad135e3f2176dc6
9e8af98595687d42e58aa8e6ad3cf203d0691d42
refs/heads/main
2022-12-22T09:10:13.168862
2020-10-03T10:23:42
2020-10-03T10:23:42
300,852,430
0
0
null
null
null
null
UTF-8
C++
false
false
713
cpp
#include "Controller.h" Controller::Controller(BoardView &view, Board &board): view_(view), board_(board){ } void Controller::runGame(){ Point p{0, 0}; Player player = Player::O; view_.drawField(player, board_); while (board_.getState() == GameState::Running){ p = view_.readCoordinates(); if(p.x == EXIT_CODE && p.y == EXIT_CODE) break; bool moved = view_.nextMove(p, player, board_); if(moved){ if (player == Player::X) { player = Player::O; } else if (player == Player::O) { player = Player::X; } view_.drawField(player, board_); } } if(!(p.x == EXIT_CODE && p.y == EXIT_CODE)) view_.printResult(board_); view_.closeView(); }
[ "rsalkaev@gmail.com" ]
rsalkaev@gmail.com
f09f64f36a036ddd98f66d52df5640e4f38b79ca
295de345a0226ac1b3a294561064e6b3839ec0cd
/src/media/audio/audio_core/audio_driver_clock_unittest.cc
816240de8967719b1957669b381bf814376c8b54
[ "BSD-2-Clause" ]
permissive
shangzuoyan/fuchsia
bac4f07748ebf7c1c67007771455e6b34cdc9e6b
2e5c3d22baa3a8f1e4b2bc48f664c75b51fe04a8
refs/heads/master
2023-02-19T04:26:39.678678
2021-01-22T09:21:00
2021-01-22T09:21:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,233
cc
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <fbl/algorithm.h> #include "src/media/audio/audio_core/audio_device_manager.h" #include "src/media/audio/audio_core/audio_driver.h" #include "src/media/audio/audio_core/testing/audio_clock_helper.h" #include "src/media/audio/audio_core/testing/fake_audio_device.h" #include "src/media/audio/audio_core/testing/fake_audio_driver.h" #include "src/media/audio/audio_core/testing/threading_model_fixture.h" #include "src/media/audio/lib/clock/testing/clock_test.h" namespace media::audio { namespace { // These tests are templated to run on both driver types typedef ::testing::Types<testing::FakeAudioDriverV1, testing::FakeAudioDriverV2> DriverTypes; // Enable gtest to pretty-print the driver type name class DriverTypeNames { public: template <typename T> static std::string GetName(int) { if constexpr (std::is_same<T, testing::FakeAudioDriverV1>()) { return "AudioDriverV1"; } if constexpr (std::is_same<T, testing::FakeAudioDriverV2>()) { return "AudioDriverV2"; } } }; TYPED_TEST_SUITE(AudioDriverClockTest, DriverTypes, DriverTypeNames); // Configuration consts for these tests const Format kFormat = Format::Create<fuchsia::media::AudioSampleFormat::SIGNED_16>(2, 48000).value(); const auto kBytesPerFrame = kFormat.bytes_per_frame(); constexpr auto kRingBufferDuration = zx::msec(200); constexpr size_t kRingBufferFrames = 9600; // 200 msec at 48k const size_t kHalfRingBufferBytes = kRingBufferFrames * kBytesPerFrame / 2; constexpr auto kStartTime = zx::time(0) + zx::msec(500); constexpr auto kNotificationDuration = zx::msec(100); constexpr uint32_t kNonMonotonicDomain = 42; // Test class to verify AudioDriver's clock-related aspects (domain, notifications, clock recovery). template <typename T> class AudioDriverClockTest : public testing::ThreadingModelFixture { protected: // Initialize our remote driver after configuring its clock domain; retrieve basic driver info void CreateDrivers(uint32_t clock_domain) { driver_ = CreateAudioDriver<T>(); zx::channel for_remote, for_local; EXPECT_EQ(ZX_OK, zx::channel::create(0, &for_remote, &for_local)); remote_driver_ = std::make_unique<T>(std::move(for_remote), dispatcher()); remote_driver_->set_clock_domain(clock_domain); ASSERT_EQ(ZX_OK, driver_->Init(std::move(for_local))); mapped_ring_buffer_ = remote_driver_->CreateRingBuffer(kRingBufferFrames * kBytesPerFrame); remote_driver_->Start(); RunLoopUntilIdle(); ASSERT_EQ(driver_->GetDriverInfo(), ZX_OK); RunLoopUntilIdle(); ASSERT_TRUE(device_->driver_info_fetched()); } // Configure the driver, including establishment of format and ring buffer. Then start the ring // buffer after advancing to the given time (so that ref_start_time is correct) void ConfigureAndStartDriver() { ASSERT_EQ(driver_->Configure(kFormat, kRingBufferDuration), ZX_OK); RunLoopUntilIdle(); ASSERT_TRUE(device_->driver_config_complete()); RunLoopUntil(kStartTime); ASSERT_EQ(driver_->Start(), ZX_OK); RunLoopUntilIdle(); ASSERT_TRUE(device_->driver_start_complete()); EXPECT_TRUE(remote_driver_->is_running()); EXPECT_GT(remote_driver_->mono_start_time(), zx::time(0)); } // Validation functions reused for parameterized testing void ValidateClockDomainSet(uint32_t clock_domain) { CreateDrivers(clock_domain); EXPECT_EQ(driver_->clock_domain(), clock_domain); } // After GetDriverInfo, the clock should already be available and advancing at monotonic rate, // regardless of its clock domain (thus regardless of whether it might subsequently diverge). // Rate-adjustments occur based on position notifications, emitted after ring buffer is started. void ValidateClockAdvancesAtClockMonotonicRate(uint32_t clock_domain) { CreateDrivers(clock_domain); audio_clock_helper::VerifyAdvances(driver_->reference_clock()); audio_clock_helper::VerifyIsSystemMonotonic(driver_->reference_clock()); } // Verify that AudioDriver correctly uses driver position notifications to rate-adjust // its AudioClock -- but only if the device is in a non-MONOTONIC domain. void ValidateNotificationsTuneDriverClock(uint32_t clock_domain, uint32_t notification_position) { CreateDrivers(clock_domain); ConfigureAndStartDriver(); // Trigger the remote driver to emit an initial position notification. remote_driver_->SendPositionNotification(remote_driver_->mono_start_time(), 0); // If MONOTONIC, no position notifications should be delivered. auto mono_to_ref = driver_->reference_clock().ref_clock_to_clock_mono().Inverse(); // First notification won't lead to adustment: clock still tracks MONOTONIC (numer == denom). EXPECT_EQ(mono_to_ref.subject_delta(), mono_to_ref.reference_delta()); // Trigger a position notification. These values may indicate a rate divergence from MONOTONIC. remote_driver_->SendPositionNotification( remote_driver_->mono_start_time() + kNotificationDuration, notification_position); RunLoopUntilIdle(); // When we return, if the driver zx::clock has been tuned, then the clock rate numer != denom. } // the actual object under test std::unique_ptr<AudioDriver> driver_; // simulates channel messages from the actual driver instance std::unique_ptr<T> remote_driver_; std::shared_ptr<testing::FakeAudioOutput> device_{testing::FakeAudioOutput::Create( &threading_model(), &context().device_manager(), &context().link_matrix())}; fzl::VmoMapper mapped_ring_buffer_; private: template <typename U> std::unique_ptr<AudioDriver> CreateAudioDriver() {} template <> std::unique_ptr<AudioDriver> CreateAudioDriver<testing::FakeAudioDriverV1>() { return std::make_unique<AudioDriverV1>(device_.get(), [](zx::duration) {}); } template <> std::unique_ptr<AudioDriver> CreateAudioDriver<testing::FakeAudioDriverV2>() { return std::make_unique<AudioDriverV2>(device_.get(), [](zx::duration) {}); } }; // AudioDriver correctly retrieves and caches the clock domain provided by the driver TYPED_TEST(AudioDriverClockTest, MonotonicClockDomain) { this->ValidateClockDomainSet(AudioClock::kMonotonicDomain); } // AudioDriver correctly retrieves and caches the clock domain provided by the driver TYPED_TEST(AudioDriverClockTest, NonMonotonicClockDomain) { this->ValidateClockDomainSet(kNonMonotonicDomain); } // For devices in the MONOTONIC domain, the clock is available after GetDriverInfo. TYPED_TEST(AudioDriverClockTest, DefaultRefClockAdvancesAtMonoRate) { this->ValidateClockAdvancesAtClockMonotonicRate(AudioClock::kMonotonicDomain); } // We model clocks in a non-MONOTONIC domain as running at the MONOTONIC rate, until we start // receiving the position notifications from which we recover its actual rate. TYPED_TEST(AudioDriverClockTest, NonMonoClockAdvancesAtMonoRate) { this->ValidateClockAdvancesAtClockMonotonicRate(kNonMonotonicDomain); } // Given notifications suggesting a device runs at monotonic rate, its clock should not be adjusted TYPED_TEST(AudioDriverClockTest, NotificationsAdjustClockRateSame) { this->ValidateNotificationsTuneDriverClock(kNonMonotonicDomain, kHalfRingBufferBytes); auto mono_to_ref = this->driver_->reference_clock().ref_clock_to_clock_mono().Inverse(); EXPECT_EQ(mono_to_ref.subject_delta(), mono_to_ref.reference_delta()); } // Given notifications suggesting a device runs slow, its clock should be rate-adjusted downward TYPED_TEST(AudioDriverClockTest, NotificationsAdjustClockRateDown) { // We should be at the ring buffer's halfway point, but we are not quite there yet this->ValidateNotificationsTuneDriverClock(kNonMonotonicDomain, kHalfRingBufferBytes * 0.95); auto mono_to_ref = this->driver_->reference_clock().ref_clock_to_clock_mono().Inverse(); EXPECT_LT(mono_to_ref.subject_delta(), mono_to_ref.reference_delta()); } // Given notifications suggesting a device runs fast, its clock should be rate-adjusted upward TYPED_TEST(AudioDriverClockTest, NotificationsAdjustClockRateUp) { // We should be at the ring buffer's halfway point, but we are a little farther along this->ValidateNotificationsTuneDriverClock(kNonMonotonicDomain, kHalfRingBufferBytes * 1.05); auto mono_to_ref = this->driver_->reference_clock().ref_clock_to_clock_mono().Inverse(); EXPECT_GT(mono_to_ref.subject_delta(), mono_to_ref.reference_delta()); } // In the MONOTONIC domain, no position notifications are sent; thus no rate-adjustment can occur. // These values suggest the device runs fast, so if a notification is sent, the rate will change. TYPED_TEST(AudioDriverClockTest, NotificationsDontAdjustMonotonicDomain) { this->ValidateNotificationsTuneDriverClock(AudioClock::kMonotonicDomain, kHalfRingBufferBytes * 1.05); auto mono_to_ref = this->driver_->reference_clock().ref_clock_to_clock_mono().Inverse(); EXPECT_EQ(mono_to_ref.subject_delta(), mono_to_ref.reference_delta()); } } // namespace } // namespace media::audio
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
84866cd0b7bdbd24e97f8d7e8d6c79129b73927b
28ce9053cd66f613d844ba40801354553c7d4abb
/libtest/src/test_settings.hpp
3f6ca1a329969af26c701f6246e10f44dc46169d
[ "MIT" ]
permissive
rvt/esp8266leds
41d08c5a04640f4e96f4bb1be6e68e44129f28a2
71be0785d6867fef338e99631d1a3363e983f3e2
refs/heads/master
2021-04-09T15:38:26.773819
2020-08-04T18:08:29
2020-08-04T18:08:29
125,743,902
6
0
null
null
null
null
UTF-8
C++
false
false
3,230
hpp
#include <catch2/catch.hpp> #include <stdint.h> #include <iostream> #include <settings.h> #include "arduinostubs.hpp" TEST_CASE("Should check for modifications", "[settings]") { millisStubbed = 0; bool calledModified = false; Settings settings( 200, 1000, []() {}, [&calledModified]() { calledModified = true; return false; } ); REQUIRE(calledModified == false); settings.handle(); REQUIRE(calledModified == true); } TEST_CASE("Should never call save function when not modified", "[settings]") { millisStubbed = 0; bool calledSaved = false; Settings settings( 200, 1000, [&calledSaved]() { calledSaved = true; }, []() { return false; } ); // Repeated calls to handle test with timings for (int i = 0; i < 2000; i += 100) { millisStubbed = i; settings.handle(); REQUIRE(calledSaved == false); } } TEST_CASE("Should call save after debounce", "[settings]") { millisStubbed = 0; bool modified = false; bool calledSaved = false; Settings settings( 200, 1000, [&calledSaved]() { calledSaved = true; }, [&modified]() { return modified; } ); settings.handle(); // Modified at 195ms modified = true; millisStubbed = 195; settings.handle(); REQUIRE(calledSaved == false); modified = false; // at 200 debounce is over and should save millisStubbed = 200; settings.handle(); REQUIRE(calledSaved == true); calledSaved = false; // At 500ms modified again, should not save modified = true; millisStubbed = 500; settings.handle(); REQUIRE(calledSaved == false); modified = false; // at 800ms still modified, but we wait for min wait time modified = true; millisStubbed = 800; settings.handle(); REQUIRE(calledSaved == false); modified = false; // at 1200ms we will save as min wait time is over millisStubbed = 1200; settings.handle(); REQUIRE(calledSaved == true); calledSaved = false; // try againmin wait time modified = true; millisStubbed = 1600; settings.handle(); modified = false; millisStubbed = 2000; settings.handle(); REQUIRE(calledSaved == false); millisStubbed = 2200; settings.handle(); REQUIRE(calledSaved == true); } TEST_CASE("Should call save when we force", "[settings]") { millisStubbed = 0; bool calledSaved = false; Settings settings( 200, 1000, [&calledSaved]() { calledSaved = true; }, []() { return false; } ); REQUIRE(calledSaved == false); settings.save(true); REQUIRE(calledSaved == true); } void show_showMinWaitTimeInAction() { millisStubbed = 0; bool calledSaved = false; Settings settings( 1, 1000, [&calledSaved]() { std::cerr << " saved"; }, [&calledSaved]() { calledSaved = false; return true; } ); for (int i = 0; i < 10000; i += 50) { std::cerr << i; millisStubbed = i; settings.handle(); std::cerr << "\n"; } }
[ "github@rvt.dds.nl" ]
github@rvt.dds.nl
9bc4627711e64896b043ebbc60e5dd372a44a662
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
/main/source/src/protocols/simple_moves/WaterBoxMoverCreator.hh
fb0ba952f6dc5b2d5af9edd953ad39cdef2f30c3
[]
no_license
MedicaicloudLink/Rosetta
3ee2d79d48b31bd8ca898036ad32fe910c9a7a28
01affdf77abb773ed375b83cdbbf58439edd8719
refs/heads/master
2020-12-07T17:52:01.350906
2020-01-10T08:24:09
2020-01-10T08:24:09
232,757,729
2
6
null
null
null
null
UTF-8
C++
false
false
1,117
hh
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington UW TechTransfer, email: license@u.washington.edu. ///@file protocols/moves/WaterBoxMoverCreator.hh #ifndef INCLUDED_protocols_moves_WaterBoxMoverCreator_hh #define INCLUDED_protocols_moves_WaterBoxMoverCreator_hh #include <protocols/moves/MoverCreator.hh> namespace protocols { namespace simple_moves { class WaterBoxMoverCreator : public protocols::moves::MoverCreator { public: protocols::moves::MoverOP create_mover() const override; std::string keyname() const override; void provide_xml_schema( utility::tag::XMLSchemaDefinition & xsd ) const override; static std::string mover_name(); }; } } #endif
[ "36790013+MedicaicloudLink@users.noreply.github.com" ]
36790013+MedicaicloudLink@users.noreply.github.com
594d50660a53b8dba1e1d4291b5f3a4017f6b638
eff7ed347564b3b5240daee8621f596065a901da
/51. N-Queens.cpp
103c57e5a5fc2251a105bd357a72512bf8ce3737
[]
no_license
liihhnm/leetcode
c455fcb9e8ad388a976f5cb863be75c86630cb0f
53bb5a9ea95a51b23a6bfff0a9309edcfa2fd582
refs/heads/master
2021-01-17T08:22:22.056328
2017-03-23T16:48:56
2017-03-23T16:48:56
83,881,222
0
0
null
null
null
null
UTF-8
C++
false
false
3,192
cpp
//51. N-Queens #include <vector> #include <iostream> #include <string> #include <cmath> #include <iterator> using namespace std; //time O(n! * n) space O(n) //just dfs class Solution { public: vector<vector<string>> solveNQueens(int n) { vector< vector<string> > result; vector<int> flag(n, -1); dfs(flag, result, 0); return result; } private: void dfs(vector<int>& flag, vector< vector<string> >& result, int row) { if (row == flag.size()) { vector<string> solution; for (int i = 0; i < row; i++) { string s(row, '.'); for (int j = 0; j < row; j++) if (flag[i] == j) s[j] = 'Q'; solution.push_back(s); } result.push_back(solution); return; } for (int i = 0; i < flag.size(); i++) { if (!valid_cell(flag, row, i)) continue; flag[row] = i; dfs(flag, result, row + 1); flag[row] = -1; } } bool valid_cell(const vector<int>& flag, int row, int column) { for (int i = 0; i < row; i++) { if (flag[i] == column) return false; if (abs(row - i) == abs(column - flag[i])) return false; } return true; } }; //time O(n!) space O(n) //dfs and prune class Solution2 { public: vector<vector<string>> solveNQueens(int n) { //initialize prune variables column = vector<bool>(n, false); diagonal1 = vector<bool>(2 * n - 1, false); diagonal2 = vector<bool>(2 * n - 1, false); vector< vector<string> > result; vector<int> flag(n, -1); dfs(flag, result, 0); return result; } private: //prune variable vector<bool> column; vector<bool> diagonal1; //diagonal like / vector<bool> diagonal2;//diagonal like \ void dfs(vector<int>& flag, vector< vector<string> >& result, int row) { if (row == flag.size()) { vector<string> solution; for (int i = 0; i < row; i++) { string s(row, '.'); for (int j = 0; j < row; j++) if (flag[i] == j) s[j] = 'Q'; solution.push_back(s); } result.push_back(solution); return; } for (int i = 0; i < flag.size(); i++) { //prune if (column[i] || diagonal1[row + i] || diagonal2[row + (flag.size() - 1 - i)]) continue; column[i] = diagonal1[row + i] = diagonal2[row + (flag.size() - 1 - i)] = true; flag[row] = i; dfs(flag, result, row + 1); flag[row] = -1; column[i] = diagonal1[row + i] = diagonal2[row + (flag.size() - 1 - i)] = false; } } }; int main() { Solution2 s; for (auto& board : s.solveNQueens(8)) { copy(board.begin(), board.end(), ostream_iterator<string>(cout, "\n")); cout << endl; } }
[ "davididota@gmail.com" ]
davididota@gmail.com
d2c1513fc44e0c4711734e8d5e293e3b7536a29b
5506e4cb54fc0c9ef106ead94e5c08bc811e49ea
/FlowerExchangeSavindu/FlowerExchangeSavindu/Flower.h
c85cbb8dee62e840af7c863165459a827fd2e6cd
[]
no_license
SavinduHerath/Flower-Exchange
f4d2cfac777a5e8e3fdac364cbeefe75ec344320
c528bdeeae148972b637228967d22c5164cbe0cf
refs/heads/master
2020-08-14T18:55:49.168590
2019-10-15T05:58:51
2019-10-15T05:58:51
215,218,307
0
0
null
null
null
null
UTF-8
C++
false
false
199
h
#pragma once #include <string> #include <vector> #include <fstream> #include <vector> #include <sstream> using namespace std; struct Flower { string symbol; string displayName; int lotSize; };
[ "savinduherath@gmail.com" ]
savinduherath@gmail.com
122989ef296c149892f79b51aef2cb120977dafa
eb2d5561ff5acf67c33f50663d5836dd31ce71e0
/include/http/content/httpcontent.h
8ff497cf734f0102c88a900573a5826936591e45
[]
no_license
gsandoval/tenochtitlan
6d20c7d639af4f371b3df4c019d3894ce684b2b3
b1697e8e50e63d2535530c915a18334af85c431f
refs/heads/master
2016-09-11T02:09:56.709807
2014-10-08T13:11:41
2014-10-08T13:11:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
626
h
#ifndef _HTTP_CONTENT_H_ #define _HTTP_CONTENT_H_ #include "socket/buffer.h" #include <map> #include <string> #include <memory> namespace tenochtitlan { namespace http { namespace content { class HttpContent { protected: static std::map<std::string, std::string> MIME_TYPES; std::shared_ptr<socket::Buffer> buffer; std::string mime; public: HttpContent(); HttpContent(std::shared_ptr<socket::Buffer> buffer); void SetMime(std::string); std::string Mime(); void SetBuffer(std::shared_ptr<socket::Buffer>); std::shared_ptr<socket::Buffer> Buffer(); }; } } } #endif
[ "gsandoval@darchitect.org" ]
gsandoval@darchitect.org
26aab825f9560401eb8e11ebeab8ac4c866478a4
babb10077d58ea8fc5170dc11a0552d9d13f954a
/implementation/src/agent.hpp
b28bf86a1061337e05adc6ec9c0bd95658ec55cd
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
PingooLP/ElGA
a8711c644b9b3b9fbfcdc0b0ca42b57c456ff529
cebf356f8c052abfe8fd5fdc43a9396e0daf3ff8
refs/heads/master
2023-08-30T09:35:48.597582
2021-11-17T05:33:45
2021-11-17T05:33:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,081
hpp
/** * ElGA agent to manage the graph * * This command is responsible for running an agent, which is responsible * for both storing part of the graph and running local algorithms on that * part. * * Author: Kasimir Gabert * * Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC * (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. * Government retains certain rights in this software. * * Please see the LICENSE.md file for license information. */ #ifndef AGENT_HPP #define AGENT_HPP #include "timer.hpp" #include "participant.hpp" #include "algorithm.hpp" #ifdef CONFIG_CS #include "countminsketch.hpp" #endif #include <unordered_map> #include <unordered_set> #include "absl/container/flat_hash_set.h" #include "absl/container/flat_hash_map.h" #include <thread> #include <mutex> #include <iomanip> namespace elga { extern std::mutex p_mutex; template<typename ...Args> inline __attribute__((always_inline)) void info_agent_(uint64_t addr_ser, Args && ...args) { std::lock_guard<std::mutex> guard(p_mutex); std::cerr << "[ElGA : Agent : " << std::setw(2) << (addr_ser>>32) << "] "; (std::cerr << ... << args); std::cerr << std::endl; } template<typename ...Args> inline __attribute__((always_inline)) void debug_agent_(uint64_t addr_ser, Args && ...args) { #ifdef DEBUG_VERBOSE std::lock_guard<std::mutex> guard(p_mutex); std::cerr << "[ElGA : Agent : " << std::setw(17) << addr_ser << " " << std::this_thread::get_id() << "] "; (std::cerr << ... << args); std::cerr << std::endl; #endif } namespace agent { /** Main entry point for the agent command */ int main(int argc, const char **argv, const ZMQAddress &directory_master, localnum_t ln); } typedef enum agent_state { /** The initial state, where no processing will occur * and the graph statistics will never be updated. * In this state, edges are accepted but the reciprocal edges are * not created. */ NO_PROCESS, /** The state of leaving no process, prior to starting */ LEAVING_NO_PROCESS, /** The state where the batch computation has finished but a new * batch may or may not be ready. * We are idle, until an edge comes into the system somewhere. */ IDLE, /** The state that closes the graph updates, brings them into the * graph itself, and requests corresponding out edges. * This state will then wait until the out edges are ready, * similar to LEAVING_NO_PROCESS, before moving into PROCESS. */ FINALIZE_GRAPH_BATCH, /** The state where full processing is occurring, aggressively * trying to process all available data. * If neighbor messages enter while processing, it will continue * the processing looping */ PROCESS, /** No vertices are expecting inputs from any more neighbors, and * so we are ready to join the upcoming barrier */ JOIN_BARRIER, /** The state where we are at the barrier and are waiting for * receiving a sync from the directory, indicating everyone else * is at the barrier and we can move passed */ WAIT_FOR_SYNC, /** A waiting state for a forced sync */ WAIT_FOR_LB, WAIT_FOR_LB_SYNC, /** The state where the agent is waiting for edge movements */ WAIT_EDGE_MOVE } agent_state_t; /** * Main graph agent, which holds part of the graph in memory and * executes algorithms. */ class Agent : public Participant { private: /** Holds the assigned portions of the graph */ absl::flat_hash_map<vertex_t, VertexStorage> graph_; /** Hold the local storage from all known vertices */ vn_t vn_; vnw_t vn_wait_; size_t vn_count_; vnr_t vn_remaining_; /** Keep track of the number of vertices and edges */ size_t nV_; size_t nE_; size_t global_nV_; size_t global_nE_; /** Hold whether we need to update nV globally */ double update_nV_; absl::flat_hash_set<vertex_t> update_nV_set_; /** Hold whether we need to update nE globally */ int64_t update_nE_; /** Support calculating runtime */ timer::Timer batch_timer_; timer::Timer update_timer_; timer::Timer ss_timer_; /** The algorithm to run */ Algorithm alg_; /** The current agent state */ agent_state_t state_; /** Keep track of active vertices */ absl::flat_hash_set<vertex_t> active_; /** Keep track of the number of dormant vertices */ absl::flat_hash_set<vertex_t> dormant_; size_t num_dormant_; size_t num_inactive_; #if defined(CONFIG_BSP) || defined(CONFIG_LBSP) absl::flat_hash_map<it_t, int> agent_msgs_needed_; absl::flat_hash_map<uint64_t, std::vector<VertexNotification> > out_vn_msgs; it_t it_; #endif /** Contains the number of virtual agents */ aid_t vagent_count_; /** Hold incoming graph changes for the next batch */ absl::flat_hash_set<update_t> update_set_; /** Keep track of whether we asked to leave idle */ bool requested_leave_idle_; /** Keep track of the batch index we are on */ batch_t batch_; /** Keep track of the number of update acks that are needed */ int32_t update_acks_needed_; #ifdef DUMP_MSG_DIST /** Keep track of the number of times messages have been saved */ size_t dump_msg_dist_count; #endif #ifdef CONFIG_CS /** Keep an agent-specific sketch */ CountMinSketch cms; bool push_sketch_; #endif #ifdef CONFIG_TIME_INGESTION timer::Timer ingest_t_; size_t last_edges_; #endif /** Maintain updates to move */ absl::flat_hash_map<uint64_t, std::vector<update_t>> moves; /** Keep the serialized address for debugging */ uint64_t addr_ser; /** Get the owner of the given update */ uint64_t get_owner(update_t& u); #ifdef CONFIG_LBSP absl::flat_hash_map<vertex_t, std::vector<vertex_t>> tmap; #ifdef CONFIG_TACTIVATE absl::flat_hash_map<it_t, absl::flat_hash_set<vertex_t>> tactivate; #endif #endif // Measure edge movement time timer::Timer move_timer_; #ifdef CONFIG_AUTOSCALE /** Keep track of query rates */ timer::Timer query_rate_t_; double query_rate_; size_t query_count_; bool dying; bool dead; #endif public: Agent(const ZMQAddress &addr, const ZMQAddress &directory_master) : Participant(addr, directory_master, true), graph_(), vn_(), vn_wait_(), vn_count_(0), vn_remaining_(), nV_(0), nE_(0), global_nV_(0), global_nE_(0), update_nV_(0), update_nE_(0), batch_timer_("batch"), update_timer_("update"), ss_timer_("superstep"), alg_(), state_(NO_PROCESS), active_(), dormant_(), num_dormant_(0), num_inactive_(0), #if defined(CONFIG_BSP) || defined(CONFIG_LBSP) it_(-1), #endif vagent_count_(STARTING_VAGENTS), update_set_(), requested_leave_idle_(false), batch_(0), update_acks_needed_(0), #ifdef DUMP_MSG_DIST dump_msg_dist_count(0), #endif #ifdef CONFIG_CS push_sketch_(false), #endif #ifdef CONFIG_TIME_INGESTION last_edges_(0), #endif addr_ser(addr_.serialize()), move_timer_("edgemove") #ifdef CONFIG_AUTOSCALE ,query_rate_t_("queryrate"), query_rate_(0.0), query_count_(0), dying(false), dead(false) #endif { } /** Register ourselves with the directory */ void register_dir(); /** Handle an edge change */ void change_edge(update_t u, bool count_deg=true); /** Process the vertex notifications */ void process_vn(const char *data, size_t size); /** Handle directory updates */ void handle_directory_update(); /** Handle agent-specific messages */ bool handle_msg(zmq_socket_t sock, msg_type_t t, const char *data, size_t size); /** Agent-specific pre-polling to run algorithms */ void pre_poll(); /** Handle any heartbeat-timed work */ bool heartbeat(); /** Write out the current algorithm results to disk */ void save(); /** Write the current graph out to disk */ void dump(); /** Process all vertices, sending out updates */ void process_vertices(); /** Begin the process of leaving the IDLE state */ void start_leaving_idle(); /** Send all OUT edges, prior to starting computation */ void send_out_edges(bool check=false); /** Inform the directory we are done waiting for out edges */ void done_waiting_ready_nv_ne(); /** Move dormant items to active */ void move_dormant_active(); /** Move edges that do not belong */ void send_move_edges(); /** Process the graph update queue and create updates to form * corresponding edges */ void finalize_graph_batch(); /** Clear our any memory used specific to a batch */ void clear_batch_mem(); /** Perform per-iteration garbage collection */ void gc(); /** Handle agent-specific shutdowns */ bool shutdown(); #ifdef CONFIG_CS /** Send the sketch up to the directory */ void push_sketch(); #endif #ifdef CONFIG_AUTOSCALE /** Keep track of query rates */ void track_query_rate(); #endif /** Balance virtual agent counts */ void balance_va(); }; } #endif
[ "kasimir@gatech.edu" ]
kasimir@gatech.edu
91b3d51c5555c78195aea3ed58e75c0b112ac642
2502943d23a18cce4b2cb169288ca08e2243ca4f
/HDOJcode/1321 2013-02-05 17 59 35.cpp
74dda8968e2d916c13a9005ec9d1a9960d151a15
[]
no_license
townboy/acm-algorithm
27745db88cf8e3f84836f98a6c2dfa4a76ee4227
4999e15efcd7574570065088b085db4a7c185a66
refs/heads/master
2021-01-01T16:20:50.099324
2014-11-29T06:13:49
2014-11-29T06:13:49
18,025,712
0
1
null
null
null
null
UTF-8
C++
false
false
603
cpp
****************************** Author : townboy Submit time : 2013-02-05 17:59:35 Judge Status : Accepted HDOJ Runid : 7596516 Problem id : 1321 Exe.time : 15MS Exe.memory : 248K https://github.com/townboy ****************************** #include<stdio.h> #include<string.h> char ch[80]; int main() { int len,f; int i,cas; scanf("%d",&cas); getchar(); for(i=0;i<cas;i++) { gets(ch); len=strlen(ch); for(f=len-1;f>=0;f--) printf("%c",ch[f]); printf("\n"); } return 0; }
[ "564690377@qq.com" ]
564690377@qq.com
fcdbeb3816aa0646cd748c307118c2a3e3033e74
06d765fd0b4f813b94a72aea143d69c21fce7c0a
/rpn_calc/stack.h
ab21e0a116debb85588d0ff6a8fe944f8701a216
[]
no_license
sophian-a/cplusplus
8a2a962b7b5b2d0377aff31e9f1de11b347ba4f2
bd3dcf7992138e7ca93e9ece6a3b679fe7bd50e2
refs/heads/master
2023-03-21T15:45:19.850653
2021-01-24T22:33:03
2021-01-24T22:33:03
309,711,950
0
1
null
2021-03-20T11:56:47
2020-11-03T14:29:06
C++
UTF-8
C++
false
false
184
h
#include <iostream> void push(int tab[], int &i, int x) ; int pop(int tab[], int &i) ; int* init_stack(int n) ; void delete_stack(int stack[]) ; void print_stack(int stack[], int i) ;
[ "sophian.akkari@mines-paristech.fr" ]
sophian.akkari@mines-paristech.fr
6219f14ba15daf68a0e3edc8fe55f099a022bd5f
11ce2a35293de26dd0121563cced3124d0f9da83
/main.cpp
6cf224caff62e6de454c06916a798c59e2d86353
[]
no_license
eduardoRubioG/conway-game-of-life
5a0889cf85043861e818f0c3f182205492b78f81
44030664ba3ab1a62c480d463bb054247adb63f4
refs/heads/master
2022-04-28T06:30:18.492643
2020-04-21T20:11:24
2020-04-21T20:11:24
257,698,580
0
0
null
null
null
null
UTF-8
C++
false
false
2,722
cpp
#include "inc.h" #include "Simorg.h" #define DIM 20 #define MAXGEN 100 using std::cout; using std::endl; /* Prototypes */ void buildEnv( const int dim, const double yield, Simorg& env ); void buildEnv( std::string filename, Simorg& env ); int main( int argc, char* argv[] ){ Simorg env( DIM ); double YIELD; bool random; /* Generate Board */ if( argc < 2 ){ /* Generate random board */ random = true; cout << "Random environment will be generated. What initial population percentage would you like? " << endl; std::cin >> YIELD; if( YIELD < 0 || YIELD > 1 ){ cout << "Invalid percentage entered (must be 0 < YIELD < 1). Using default value of 0.80\n" << endl; YIELD = 0.80; } buildEnv( DIM, YIELD, env ); } else if( argc < 4 ){ /* Build board from file */ std::string flag(argv[1]); if( flag.compare("-f") != 0 ){ cout << "Error: Command line argument error" << endl; } std::string file(argv[2]); buildEnv( file, env ); } else { /* Error */ cout << "Error: Command line argument error" << endl; } for( int i = 0; i < MAXGEN; i++ ){ system("clear"); cout << "E N V I R O N M E N T A T G E N " << i+1 << endl; cout << "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" << endl; if( random ) cout << "Started with " << YIELD * DIM * DIM << " active Simorgs\n" << endl; else cout << "Started with file " << argv[2] << endl; env.printEnv(); env.nextEvo(); std::this_thread::sleep_for(std::chrono::milliseconds(2000)); } return 0; } /* Build random environment */ void buildEnv( const int dim, const double yield, Simorg& env ){ srand(time(NULL)); int activecount = yield * dim * dim; int rrow, rcol; printf("Generating a random board | %d / %d Simorgs will start active\n", activecount, dim); for( int i = 0; i < activecount; i++ ){ rrow = (rand() % dim); rcol = (rand() % dim); env.setState(true, 1, rrow, rcol); } } /* Build environment from file */ void buildEnv( const std::string filename, Simorg& env ){ std::ifstream file( filename.c_str(), std::ios::in ); if( !file.good() ) { printf("Error: Issue with opening file \"%s\"\n", filename.c_str()); exit(1); } char cellStateBuffer; bool cellState; for( int r = 0; r < DIM; r++ ){ for( int c = 0; c < DIM; c++ ){ if( file >> cellStateBuffer ){ if( cellStateBuffer == 'X' ) cellState = true; else cellState = false; env.setState(cellState, 1, r, c); } else { printf("Error: I/O issue reading the file \"%s\"\n",filename.c_str()); exit(1); } } } }
[ "eduardo.rubio.jr85@gmail.com" ]
eduardo.rubio.jr85@gmail.com
1f6fb53a38d2cbb4c30eb38c0b58b02433e1ea55
092f83af8daf07844bef4f5c61b1ca7d298488b8
/libs/lfd/include/lfd/animation.h
c2835014dab09cbc5f395c29acc66960989df4ec
[ "MIT" ]
permissive
tiaanl/red5
1fd0d1ab0f86f8f70fc27d8b7b072d1eb1e956ad
ea7593b38f61f64f8aeb7d58854106bd58c05736
refs/heads/main
2023-01-07T05:11:57.569662
2020-11-14T19:19:46
2020-11-14T19:19:46
305,490,400
2
0
null
null
null
null
UTF-8
C++
false
false
337
h
#pragma once #include "lfd/image.h" class Animation : public Resource { public: ~Animation() override; const std::vector<Image>& frames() const { return m_frames; } void read(base::InputStream* stream, MemSize size) override; void write(base::OutputStream* stream) override; private: std::vector<Image> m_frames; };
[ "tiaanl@gmail.com" ]
tiaanl@gmail.com
3bfde5c48d2b3e77895ac0bcd4c4683b926ed861
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/content/browser/indexed_db/indexed_db_transaction.cc
5040dddf49fdcabdb0bc06ff18177f95b312c7a2
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
16,216
cc
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/indexed_db/indexed_db_transaction.h" #include "base/bind.h" #include "base/location.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" #include "content/browser/indexed_db/indexed_db_backing_store.h" #include "content/browser/indexed_db/indexed_db_cursor.h" #include "content/browser/indexed_db/indexed_db_database.h" #include "content/browser/indexed_db/indexed_db_database_callbacks.h" #include "content/browser/indexed_db/indexed_db_observation.h" #include "content/browser/indexed_db/indexed_db_observer_changes.h" #include "content/browser/indexed_db/indexed_db_tracing.h" #include "content/browser/indexed_db/indexed_db_transaction_coordinator.h" #include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseException.h" #include "third_party/leveldatabase/env_chromium.h" namespace content { namespace { const int64_t kInactivityTimeoutPeriodSeconds = 60; // Helper for posting a task to call IndexedDBTransaction::Commit when we know // the transaction had no requests and therefore the commit must succeed. void CommitUnused(scoped_refptr<IndexedDBTransaction> transaction) { leveldb::Status status = transaction->Commit(); DCHECK(status.ok()); } } // namespace IndexedDBTransaction::TaskQueue::TaskQueue() {} IndexedDBTransaction::TaskQueue::~TaskQueue() { clear(); } void IndexedDBTransaction::TaskQueue::clear() { while (!queue_.empty()) queue_.pop(); } IndexedDBTransaction::Operation IndexedDBTransaction::TaskQueue::pop() { DCHECK(!queue_.empty()); Operation task(queue_.front()); queue_.pop(); return task; } IndexedDBTransaction::TaskStack::TaskStack() {} IndexedDBTransaction::TaskStack::~TaskStack() { clear(); } void IndexedDBTransaction::TaskStack::clear() { while (!stack_.empty()) stack_.pop(); } IndexedDBTransaction::Operation IndexedDBTransaction::TaskStack::pop() { DCHECK(!stack_.empty()); Operation task(stack_.top()); stack_.pop(); return task; } IndexedDBTransaction::IndexedDBTransaction( int64_t id, base::WeakPtr<IndexedDBConnection> connection, const std::set<int64_t>& object_store_ids, blink::WebIDBTransactionMode mode, IndexedDBBackingStore::Transaction* backing_store_transaction) : id_(id), object_store_ids_(object_store_ids), mode_(mode), used_(false), state_(CREATED), commit_pending_(false), connection_(std::move(connection)), transaction_(backing_store_transaction), backing_store_transaction_begun_(false), should_process_queue_(false), pending_preemptive_events_(0) { callbacks_ = connection_->callbacks(); database_ = connection_->database(); database_->transaction_coordinator().DidCreateTransaction(this); diagnostics_.tasks_scheduled = 0; diagnostics_.tasks_completed = 0; diagnostics_.creation_time = base::Time::Now(); } IndexedDBTransaction::~IndexedDBTransaction() { // It shouldn't be possible for this object to get deleted until it's either // complete or aborted. DCHECK_EQ(state_, FINISHED); DCHECK(preemptive_task_queue_.empty()); DCHECK_EQ(pending_preemptive_events_, 0); DCHECK(task_queue_.empty()); DCHECK(abort_task_stack_.empty()); DCHECK(pending_observers_.empty()); } void IndexedDBTransaction::ScheduleTask(blink::WebIDBTaskType type, Operation task) { DCHECK_NE(state_, COMMITTING); if (state_ == FINISHED) return; timeout_timer_.Stop(); used_ = true; if (type == blink::WebIDBTaskTypeNormal) { task_queue_.push(task); ++diagnostics_.tasks_scheduled; } else { preemptive_task_queue_.push(task); } RunTasksIfStarted(); } void IndexedDBTransaction::ScheduleAbortTask(Operation abort_task) { DCHECK_NE(FINISHED, state_); DCHECK(used_); abort_task_stack_.push(abort_task); } void IndexedDBTransaction::RunTasksIfStarted() { DCHECK(used_); // Not started by the coordinator yet. if (state_ != STARTED) return; // A task is already posted. if (should_process_queue_) return; should_process_queue_ = true; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&IndexedDBTransaction::ProcessTaskQueue, this)); } void IndexedDBTransaction::Abort() { Abort(IndexedDBDatabaseError(blink::WebIDBDatabaseExceptionUnknownError, "Internal error (unknown cause)")); } void IndexedDBTransaction::Abort(const IndexedDBDatabaseError& error) { IDB_TRACE1("IndexedDBTransaction::Abort", "txn.id", id()); if (state_ == FINISHED) return; // The last reference to this object may be released while performing the // abort steps below. We therefore take a self reference to keep ourselves // alive while executing this method. scoped_refptr<IndexedDBTransaction> protect(this); timeout_timer_.Stop(); state_ = FINISHED; should_process_queue_ = false; if (backing_store_transaction_begun_) transaction_->Rollback(); // Run the abort tasks, if any. while (!abort_task_stack_.empty()) abort_task_stack_.pop().Run(NULL); preemptive_task_queue_.clear(); pending_preemptive_events_ = 0; task_queue_.clear(); // Backing store resources (held via cursors) must be released // before script callbacks are fired, as the script callbacks may // release references and allow the backing store itself to be // released, and order is critical. CloseOpenCursors(); transaction_->Reset(); // Transactions must also be marked as completed before the // front-end is notified, as the transaction completion unblocks // operations like closing connections. database_->transaction_coordinator().DidFinishTransaction(this); #ifndef NDEBUG DCHECK(!database_->transaction_coordinator().IsActive(this)); #endif if (callbacks_.get()) callbacks_->OnAbort(id_, error); database_->TransactionFinished(this, false); database_ = NULL; connection_ = nullptr; pending_observers_.clear(); } bool IndexedDBTransaction::IsTaskQueueEmpty() const { return preemptive_task_queue_.empty() && task_queue_.empty(); } bool IndexedDBTransaction::HasPendingTasks() const { return pending_preemptive_events_ || !IsTaskQueueEmpty(); } void IndexedDBTransaction::RegisterOpenCursor(IndexedDBCursor* cursor) { open_cursors_.insert(cursor); } void IndexedDBTransaction::UnregisterOpenCursor(IndexedDBCursor* cursor) { open_cursors_.erase(cursor); } void IndexedDBTransaction::Start() { // TransactionCoordinator has started this transaction. DCHECK_EQ(CREATED, state_); state_ = STARTED; diagnostics_.start_time = base::Time::Now(); if (!used_) { if (commit_pending_) { // The transaction has never had requests issued against it, but the // front-end previously requested a commit; do the commit now, but not // re-entrantly as that may renter the coordinator. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&CommitUnused, make_scoped_refptr(this))); } return; } RunTasksIfStarted(); } class BlobWriteCallbackImpl : public IndexedDBBackingStore::BlobWriteCallback { public: explicit BlobWriteCallbackImpl( scoped_refptr<IndexedDBTransaction> transaction) : transaction_(transaction) {} void Run(bool succeeded) override { transaction_->BlobWriteComplete(succeeded); } protected: ~BlobWriteCallbackImpl() override {} private: scoped_refptr<IndexedDBTransaction> transaction_; }; void IndexedDBTransaction::BlobWriteComplete(bool success) { IDB_TRACE("IndexedDBTransaction::BlobWriteComplete"); if (state_ == FINISHED) // aborted return; DCHECK_EQ(state_, COMMITTING); if (success) CommitPhaseTwo(); else Abort(IndexedDBDatabaseError(blink::WebIDBDatabaseExceptionDataError, "Failed to write blobs.")); } leveldb::Status IndexedDBTransaction::Commit() { IDB_TRACE1("IndexedDBTransaction::Commit", "txn.id", id()); timeout_timer_.Stop(); // In multiprocess ports, front-end may have requested a commit but // an abort has already been initiated asynchronously by the // back-end. if (state_ == FINISHED) return leveldb::Status::OK(); DCHECK_NE(state_, COMMITTING); DCHECK(!used_ || state_ == STARTED); commit_pending_ = true; // Front-end has requested a commit, but this transaction is blocked by // other transactions. The commit will be initiated when the transaction // coordinator unblocks this transaction. if (state_ != STARTED) return leveldb::Status::OK(); // Front-end has requested a commit, but there may be tasks like // create_index which are considered synchronous by the front-end // but are processed asynchronously. if (HasPendingTasks()) return leveldb::Status::OK(); state_ = COMMITTING; leveldb::Status s; if (!used_) { s = CommitPhaseTwo(); } else { scoped_refptr<IndexedDBBackingStore::BlobWriteCallback> callback( new BlobWriteCallbackImpl(this)); // CommitPhaseOne will call the callback synchronously if there are no blobs // to write. s = transaction_->CommitPhaseOne(callback); if (!s.ok()) Abort(IndexedDBDatabaseError(blink::WebIDBDatabaseExceptionDataError, "Error processing blob journal.")); } return s; } leveldb::Status IndexedDBTransaction::CommitPhaseTwo() { // Abort may have been called just as the blob write completed. if (state_ == FINISHED) return leveldb::Status::OK(); DCHECK_EQ(state_, COMMITTING); // The last reference to this object may be released while performing the // commit steps below. We therefore take a self reference to keep ourselves // alive while executing this method. scoped_refptr<IndexedDBTransaction> protect(this); state_ = FINISHED; leveldb::Status s; bool committed; if (!used_) { committed = true; } else { s = transaction_->CommitPhaseTwo(); committed = s.ok(); } // Backing store resources (held via cursors) must be released // before script callbacks are fired, as the script callbacks may // release references and allow the backing store itself to be // released, and order is critical. CloseOpenCursors(); transaction_->Reset(); // Transactions must also be marked as completed before the // front-end is notified, as the transaction completion unblocks // operations like closing connections. database_->transaction_coordinator().DidFinishTransaction(this); if (committed) { abort_task_stack_.clear(); // SendObservations must be called before OnComplete to ensure consistency // of callbacks at renderer. if (!connection_changes_map_.empty()) { database_->SendObservations(std::move(connection_changes_map_)); connection_changes_map_.clear(); } { IDB_TRACE1( "IndexedDBTransaction::CommitPhaseTwo.TransactionCompleteCallbacks", "txn.id", id()); callbacks_->OnComplete(id_); } if (!pending_observers_.empty() && connection_) { connection_->ActivatePendingObservers(std::move(pending_observers_)); pending_observers_.clear(); } database_->TransactionFinished(this, true); } else { while (!abort_task_stack_.empty()) abort_task_stack_.pop().Run(NULL); IndexedDBDatabaseError error; if (leveldb_env::IndicatesDiskFull(s)) { error = IndexedDBDatabaseError( blink::WebIDBDatabaseExceptionQuotaError, "Encountered disk full while committing transaction."); } else { error = IndexedDBDatabaseError(blink::WebIDBDatabaseExceptionUnknownError, "Internal error committing transaction."); } callbacks_->OnAbort(id_, error); database_->TransactionFinished(this, false); database_->TransactionCommitFailed(s); } database_ = NULL; return s; } void IndexedDBTransaction::ProcessTaskQueue() { IDB_TRACE1("IndexedDBTransaction::ProcessTaskQueue", "txn.id", id()); // May have been aborted. if (!should_process_queue_) return; DCHECK(!IsTaskQueueEmpty()); should_process_queue_ = false; if (!backing_store_transaction_begun_) { transaction_->Begin(); backing_store_transaction_begun_ = true; } // The last reference to this object may be released while performing the // tasks. Take take a self reference to keep this object alive so that // the loop termination conditions can be checked. scoped_refptr<IndexedDBTransaction> protect(this); TaskQueue* task_queue = pending_preemptive_events_ ? &preemptive_task_queue_ : &task_queue_; while (!task_queue->empty() && state_ != FINISHED) { DCHECK_EQ(state_, STARTED); Operation task(task_queue->pop()); task.Run(this); if (!pending_preemptive_events_) { DCHECK(diagnostics_.tasks_completed < diagnostics_.tasks_scheduled); ++diagnostics_.tasks_completed; } // Event itself may change which queue should be processed next. task_queue = pending_preemptive_events_ ? &preemptive_task_queue_ : &task_queue_; } // If there are no pending tasks, we haven't already committed/aborted, // and the front-end requested a commit, it is now safe to do so. if (!HasPendingTasks() && state_ != FINISHED && commit_pending_) { Commit(); return; } // The transaction may have been aborted while processing tasks. if (state_ == FINISHED) return; DCHECK(state_ == STARTED); // Otherwise, start a timer in case the front-end gets wedged and // never requests further activity. Read-only transactions don't // block other transactions, so don't time those out. if (mode_ != blink::WebIDBTransactionModeReadOnly) { timeout_timer_.Start(FROM_HERE, GetInactivityTimeout(), base::Bind(&IndexedDBTransaction::Timeout, this)); } } base::TimeDelta IndexedDBTransaction::GetInactivityTimeout() const { return base::TimeDelta::FromSeconds(kInactivityTimeoutPeriodSeconds); } void IndexedDBTransaction::Timeout() { Abort(IndexedDBDatabaseError( blink::WebIDBDatabaseExceptionTimeoutError, base::ASCIIToUTF16("Transaction timed out due to inactivity."))); } void IndexedDBTransaction::CloseOpenCursors() { IDB_TRACE1("IndexedDBTransaction::CloseOpenCursors", "txn.id", id()); for (auto* cursor : open_cursors_) cursor->Close(); open_cursors_.clear(); } void IndexedDBTransaction::AddPendingObserver( int32_t observer_id, const IndexedDBObserver::Options& options) { pending_observers_.push_back(base::MakeUnique<IndexedDBObserver>( observer_id, object_store_ids_, options)); } void IndexedDBTransaction::RemovePendingObservers( const std::vector<int32_t>& pending_observer_ids) { const auto& it = std::remove_if( pending_observers_.begin(), pending_observers_.end(), [&pending_observer_ids](const std::unique_ptr<IndexedDBObserver>& o) { return base::ContainsValue(pending_observer_ids, o->id()); }); if (it != pending_observers_.end()) pending_observers_.erase(it, pending_observers_.end()); } void IndexedDBTransaction::AddObservation( int32_t connection_id, std::unique_ptr<IndexedDBObservation> observation) { auto it = connection_changes_map_.find(connection_id); if (it == connection_changes_map_.end()) { it = connection_changes_map_ .insert(std::make_pair( connection_id, base::MakeUnique<IndexedDBObserverChanges>())) .first; } it->second->AddObservation(std::move(observation)); } void IndexedDBTransaction::RecordObserverForLastObservation( int32_t connection_id, int32_t observer_id) { auto it = connection_changes_map_.find(connection_id); DCHECK(it != connection_changes_map_.end()); it->second->RecordObserverForLastObservation(observer_id); } } // namespace content
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
f42b7ea914b6018a16a6df26c8bcfa34de677c0a
ee928aed7cf3be766d12214ee5780ad7a24d4f1e
/src/time_series/tvsbvar_blocks.cpp
b995bf4442b25dbebf62ebc5c874594585cddf1b
[]
no_license
parb220/dsmh_npsol_package
d6442c75ad9a4d85775ec8c5afc38db20c256424
f437828ebf6b6ebc587f69dc79e6c3680f548bc7
refs/heads/master
2020-12-25T11:32:09.757836
2016-04-15T18:25:33
2016-04-15T18:25:33
55,998,105
0
1
null
null
null
null
UTF-8
C++
false
false
7,118
cpp
#include <vector> #include "dw_dense_matrix.hpp" #include "tvsbvar.hpp" using namespace std; vector<TIndex > TVSBVAR:: ConstructBlocks(int block_scheme) { vector<TIndex >blocks; switch (block_scheme) { case 0: { // no blocking blocks.push_back( TIndex(0,NumberParameters()-1) ); break; } case 1: { // separate block for each base regime, one block each for the // multiplicative parameters, the additive parameters, and // the transition matrix parameters for (int kk=0; kk<BaseRestriction().n_regimes; kk++) { if ( BaseRestriction().dim[kk] ) blocks.push_back( TIndex(BaseRestriction().offset[kk], BaseRestriction().offset[kk]+BaseRestriction().dim[kk]-1) ); } if (MultiplicativeRestriction().n_free) blocks.push_back( TIndex(MultiplicativeRestriction().offset[0], MultiplicativeRestriction().offset[0]+MultiplicativeRestriction().n_free-1) ); if (AdditiveRestriction().n_free) blocks.push_back( TIndex(AdditiveRestriction().offset[0], AdditiveRestriction().offset[0]+AdditiveRestriction().n_free-1) ); if (NumberParameters_RegimeProcess()) blocks.push_back( TIndex(Offset_RegimeProcessParameters(), Offset_RegimeProcessParameters()+NumberParameters_RegimeProcess()-1) ); break; } case 2: { // One block for all VAR parameters and one for transition // parameters if (NumberParameters_VAR()) blocks.push_back(TIndex(0, NumberParameters_VAR()-1)); if (NumberParameters_RegimeProcess() ) blocks.push_back(TIndex(Offset_RegimeProcessParameters(), Offset_RegimeProcessParameters()+NumberParameters_RegimeProcess()-1)); break; } case 3: { // two blocks for each base regime, one fore the // contemporaneous coefficients and one for the pre- // determined coefficients // one block for multiplicative parameters // one block for additive parameters // one block for transition parameters for (int kk=0; kk<BaseRestriction().n_regimes; kk++) { for (int ii=0; ii< NumberVariables(); ii++) { if (BaseRestriction().dim_a[kk][ii] || BaseRestriction().dim_xi[kk][ii]) { blocks.push_back( TIndex(BaseRestriction().offset_a[kk][0], BaseRestriction().offset_a[kk][NumberVariables()-1]+BaseRestriction().dim_a[kk][NumberVariables()-1]-1) ); blocks[blocks.size()-1] += TIndex(BaseRestriction().offset_xi[kk][0], BaseRestriction().offset_xi[kk][NumberVariables()-1]+BaseRestriction().dim_xi[kk][NumberVariables()-1]-1); break; } } for (int ii=0; ii<NumberVariables(); ii++) { if (BaseRestriction().dim_aplus[kk][ii]) { blocks.push_back( TIndex(BaseRestriction().offset_aplus[kk][0], BaseRestriction().offset_aplus[kk][NumberVariables()-1]+BaseRestriction().dim_aplus[kk][NumberVariables()-1]-1) ); break; } } } if (MultiplicativeRestriction().n_free) blocks.push_back( TIndex(MultiplicativeRestriction().offset[0], MultiplicativeRestriction().offset[0]+MultiplicativeRestriction().n_free-1) ); if (AdditiveRestriction().n_free) blocks.push_back( TIndex(AdditiveRestriction().offset[0], AdditiveRestriction().offset[0]+AdditiveRestriction().n_free-1) ); if (NumberParameters_RegimeProcess() ) blocks.push_back( TIndex(Offset_RegimeProcessParameters(), Offset_RegimeProcessParameters()+NumberParameters_RegimeProcess()-1) ); break; } case 4: { // multiple blocks for each base regime // one for contemporaneous coefficients and one for each // equation of the predetermined coefficients // one block for the multiplicative parameters // one block for the additive parameters // one block for transition parameters for (int kk=0; kk<BaseRestriction().n_regimes; kk++) { for (int ii=0; ii<NumberVariables(); ii++) { if (BaseRestriction().dim_a[kk][ii] || BaseRestriction().dim_xi[kk][ii]) { blocks.push_back( TIndex(BaseRestriction().offset_a[kk][0],BaseRestriction().offset_a[kk][NumberVariables()-1]+BaseRestriction().dim_a[kk][NumberVariables()-1]-1) ); blocks[blocks.size()-1] += TIndex(BaseRestriction().offset_xi[kk][0],BaseRestriction().offset_xi[kk][NumberVariables()-1]+BaseRestriction().dim_xi[kk][NumberVariables()-1]-1); break; } } for (int ii=0; ii<NumberVariables(); ii++) { if (BaseRestriction().dim_aplus[kk][ii]) blocks.push_back( TIndex(BaseRestriction().offset_aplus[kk][ii], BaseRestriction().offset_aplus[kk][ii]+BaseRestriction().dim_aplus[kk][ii]-1) ); } if (MultiplicativeRestriction().n_free) blocks.push_back( TIndex(MultiplicativeRestriction().offset[0],MultiplicativeRestriction().offset[0]+MultiplicativeRestriction().n_free-1) ); if (AdditiveRestriction().n_free) blocks.push_back( TIndex(AdditiveRestriction().offset[0],AdditiveRestriction().offset[0]+AdditiveRestriction().n_free-1) ); if (NumberParameters_RegimeProcess()) blocks.push_back( TIndex(Offset_RegimeProcessParameters(), Offset_RegimeProcessParameters()+NumberParameters_RegimeProcess()-1) ); } break; } case 5: { // multiple blocks for each base regime // one for contemporaneous coefficients and // one for each equation of the predetermined coefficients // one block for the multiplicative parameters // one block for the additive parameters // one block for transition parameters // one block for hyper parameters for (int kk=0; kk<BaseRestriction().n_regimes; kk++) { for (int ii=0; ii<NumberVariables(); ii++) { if (BaseRestriction().dim_a[kk][ii] || BaseRestriction().dim_xi[kk][ii]) { blocks.push_back( TIndex(BaseRestriction().offset_a[kk][0],BaseRestriction().offset_a[kk][NumberVariables()-1]+BaseRestriction().dim_a[kk][NumberVariables()-1]-1) ); blocks[blocks.size()-1] += TIndex(BaseRestriction().offset_xi[kk][0],BaseRestriction().offset_xi[kk][NumberVariables()-1]+BaseRestriction().dim_xi[kk][NumberVariables()-1]-1); break; } } for (int ii=0; ii<NumberVariables(); ii++) { if (BaseRestriction().dim_aplus[kk][ii]) blocks.push_back(TIndex(BaseRestriction().offset_aplus[kk][ii], BaseRestriction().offset_aplus[kk][ii]+BaseRestriction().dim_aplus[kk][ii]-1) ); } if (MultiplicativeRestriction().n_free) blocks.push_back( TIndex(MultiplicativeRestriction().offset[0],MultiplicativeRestriction().offset[0]+MultiplicativeRestriction().n_free-1) ); if (AdditiveRestriction().n_free) blocks.push_back( TIndex(AdditiveRestriction().offset[0],AdditiveRestriction().offset[0]+AdditiveRestriction().n_free-1) ); if (NumberParameters_RegimeProcess()) blocks.push_back( TIndex(Offset_RegimeProcessParameters(), Offset_RegimeProcessParameters()+NumberParameters_RegimeProcess()-1) ); if (NumberParameters_HyperParameter()) blocks.push_back( TIndex(Offset_HyperParameters(), Offset_HyperParameters()+NumberParameters_HyperParameter()-1) ); } break; } default: blocks.clear(); } return blocks; }
[ "parb220@gmail.com" ]
parb220@gmail.com
7afe852afee7999fa450cd593d4fbefd46bf5ce2
8576eb949054c802f3d48147e63612f15185a967
/JGame_Hall_Qt/GeneratedFiles/ui_frminputbox.h
6f9ff7aca73e28140183620fabc12c399bfa87b6
[]
no_license
gamezoo/JGame_Hall_Qt
c21881549989c128decbc05678b6d052ba75dd63
2138ee7e009ae2ff3ddaf24f662c02d3fc6d3edd
refs/heads/master
2020-06-04T05:06:31.603769
2019-02-22T03:57:03
2019-02-22T03:57:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,131
h
/******************************************************************************** ** Form generated from reading UI file 'frminputbox.ui' ** ** Created: Tue Jan 30 10:17:55 2018 ** by: Qt User Interface Compiler version 4.8.4 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_FRMINPUTBOX_H #define UI_FRMINPUTBOX_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QDialog> #include <QtGui/QGroupBox> #include <QtGui/QHBoxLayout> #include <QtGui/QHeaderView> #include <QtGui/QLabel> #include <QtGui/QLineEdit> #include <QtGui/QPushButton> #include <QtGui/QSpacerItem> #include <QtGui/QVBoxLayout> #include <QtGui/QWidget> QT_BEGIN_NAMESPACE class Ui_frmInputBox { public: QVBoxLayout *verticalLayout; QWidget *widget_title; QHBoxLayout *horizontalLayout_2; QLabel *lab_Ico; QLabel *lab_Title; QWidget *widget_menu; QHBoxLayout *horizontalLayout; QPushButton *btnMenu_Close; QWidget *widget_main; QVBoxLayout *verticalLayout_2; QGroupBox *groupBoxInput; QVBoxLayout *verticalLayout_3; QLabel *labInfo; QLineEdit *txtValue; QHBoxLayout *horizontalLayout_3; QSpacerItem *horizontalSpacer; QPushButton *btnOk; QPushButton *btnCancel; void setupUi(QDialog *frmInputBox) { if (frmInputBox->objectName().isEmpty()) frmInputBox->setObjectName(QString::fromUtf8("frmInputBox")); frmInputBox->resize(339, 154); verticalLayout = new QVBoxLayout(frmInputBox); verticalLayout->setSpacing(0); verticalLayout->setContentsMargins(1, 1, 1, 1); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); widget_title = new QWidget(frmInputBox); widget_title->setObjectName(QString::fromUtf8("widget_title")); QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(widget_title->sizePolicy().hasHeightForWidth()); widget_title->setSizePolicy(sizePolicy); widget_title->setMinimumSize(QSize(100, 28)); horizontalLayout_2 = new QHBoxLayout(widget_title); horizontalLayout_2->setSpacing(0); horizontalLayout_2->setContentsMargins(0, 0, 0, 0); horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2")); lab_Ico = new QLabel(widget_title); lab_Ico->setObjectName(QString::fromUtf8("lab_Ico")); QSizePolicy sizePolicy1(QSizePolicy::Minimum, QSizePolicy::Preferred); sizePolicy1.setHorizontalStretch(0); sizePolicy1.setVerticalStretch(0); sizePolicy1.setHeightForWidth(lab_Ico->sizePolicy().hasHeightForWidth()); lab_Ico->setSizePolicy(sizePolicy1); lab_Ico->setMinimumSize(QSize(31, 0)); lab_Ico->setAlignment(Qt::AlignCenter); horizontalLayout_2->addWidget(lab_Ico); lab_Title = new QLabel(widget_title); lab_Title->setObjectName(QString::fromUtf8("lab_Title")); QSizePolicy sizePolicy2(QSizePolicy::Expanding, QSizePolicy::Preferred); sizePolicy2.setHorizontalStretch(0); sizePolicy2.setVerticalStretch(0); sizePolicy2.setHeightForWidth(lab_Title->sizePolicy().hasHeightForWidth()); lab_Title->setSizePolicy(sizePolicy2); lab_Title->setStyleSheet(QString::fromUtf8("")); lab_Title->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter); horizontalLayout_2->addWidget(lab_Title); widget_menu = new QWidget(widget_title); widget_menu->setObjectName(QString::fromUtf8("widget_menu")); sizePolicy1.setHeightForWidth(widget_menu->sizePolicy().hasHeightForWidth()); widget_menu->setSizePolicy(sizePolicy1); horizontalLayout = new QHBoxLayout(widget_menu); horizontalLayout->setSpacing(0); horizontalLayout->setContentsMargins(0, 0, 0, 0); horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout")); btnMenu_Close = new QPushButton(widget_menu); btnMenu_Close->setObjectName(QString::fromUtf8("btnMenu_Close")); QSizePolicy sizePolicy3(QSizePolicy::Minimum, QSizePolicy::Expanding); sizePolicy3.setHorizontalStretch(0); sizePolicy3.setVerticalStretch(0); sizePolicy3.setHeightForWidth(btnMenu_Close->sizePolicy().hasHeightForWidth()); btnMenu_Close->setSizePolicy(sizePolicy3); btnMenu_Close->setMinimumSize(QSize(40, 0)); btnMenu_Close->setCursor(QCursor(Qt::ArrowCursor)); btnMenu_Close->setFocusPolicy(Qt::NoFocus); btnMenu_Close->setFlat(true); horizontalLayout->addWidget(btnMenu_Close); horizontalLayout_2->addWidget(widget_menu); verticalLayout->addWidget(widget_title); widget_main = new QWidget(frmInputBox); widget_main->setObjectName(QString::fromUtf8("widget_main")); widget_main->setStyleSheet(QString::fromUtf8("")); verticalLayout_2 = new QVBoxLayout(widget_main); verticalLayout_2->setSpacing(5); verticalLayout_2->setContentsMargins(5, 5, 5, 5); verticalLayout_2->setObjectName(QString::fromUtf8("verticalLayout_2")); groupBoxInput = new QGroupBox(widget_main); groupBoxInput->setObjectName(QString::fromUtf8("groupBoxInput")); verticalLayout_3 = new QVBoxLayout(groupBoxInput); verticalLayout_3->setObjectName(QString::fromUtf8("verticalLayout_3")); verticalLayout_3->setContentsMargins(-1, 0, -1, 0); labInfo = new QLabel(groupBoxInput); labInfo->setObjectName(QString::fromUtf8("labInfo")); labInfo->setMinimumSize(QSize(0, 30)); labInfo->setMaximumSize(QSize(16777215, 30)); labInfo->setScaledContents(false); labInfo->setWordWrap(true); verticalLayout_3->addWidget(labInfo); txtValue = new QLineEdit(groupBoxInput); txtValue->setObjectName(QString::fromUtf8("txtValue")); verticalLayout_3->addWidget(txtValue); horizontalLayout_3 = new QHBoxLayout(); horizontalLayout_3->setObjectName(QString::fromUtf8("horizontalLayout_3")); horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_3->addItem(horizontalSpacer); btnOk = new QPushButton(groupBoxInput); btnOk->setObjectName(QString::fromUtf8("btnOk")); btnOk->setCursor(QCursor(Qt::PointingHandCursor)); btnOk->setFocusPolicy(Qt::StrongFocus); btnOk->setStyleSheet(QString::fromUtf8("")); QIcon icon; icon.addFile(QString::fromUtf8(":/image/update.png"), QSize(), QIcon::Normal, QIcon::Off); btnOk->setIcon(icon); btnOk->setIconSize(QSize(20, 20)); horizontalLayout_3->addWidget(btnOk); btnCancel = new QPushButton(groupBoxInput); btnCancel->setObjectName(QString::fromUtf8("btnCancel")); btnCancel->setCursor(QCursor(Qt::PointingHandCursor)); btnCancel->setFocusPolicy(Qt::StrongFocus); btnCancel->setStyleSheet(QString::fromUtf8("")); QIcon icon1; icon1.addFile(QString::fromUtf8(":/image/close.png"), QSize(), QIcon::Normal, QIcon::Off); btnCancel->setIcon(icon1); btnCancel->setIconSize(QSize(20, 20)); horizontalLayout_3->addWidget(btnCancel); verticalLayout_3->addLayout(horizontalLayout_3); verticalLayout_2->addWidget(groupBoxInput); verticalLayout->addWidget(widget_main); QWidget::setTabOrder(txtValue, btnOk); QWidget::setTabOrder(btnOk, btnCancel); retranslateUi(frmInputBox); QMetaObject::connectSlotsByName(frmInputBox); } // setupUi void retranslateUi(QDialog *frmInputBox) { frmInputBox->setWindowTitle(QApplication::translate("frmInputBox", "\350\276\223\345\205\245\346\241\206", 0, QApplication::UnicodeUTF8)); lab_Ico->setText(QString()); lab_Title->setText(QApplication::translate("frmInputBox", "\350\276\223\345\205\245\346\241\206", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP btnMenu_Close->setToolTip(QApplication::translate("frmInputBox", "\345\205\263\351\227\255", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP btnMenu_Close->setText(QString()); groupBoxInput->setTitle(QString()); labInfo->setText(QApplication::translate("frmInputBox", "\350\257\267\350\276\223\345\205\245:", 0, QApplication::UnicodeUTF8)); btnOk->setText(QApplication::translate("frmInputBox", "\347\241\256\345\256\232(&O)", 0, QApplication::UnicodeUTF8)); btnCancel->setText(QApplication::translate("frmInputBox", "\345\217\226\346\266\210(&C)", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class frmInputBox: public Ui_frmInputBox {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_FRMINPUTBOX_H
[ "366322759@qq.com" ]
366322759@qq.com
86872b80a0b2ac744cf5d1be4bca293d1135a40e
f9edcaa4f52706cdda42e11c5b11fb3c05c18079
/DSA/prime.cpp
b1e0110e671a6eb3434f0b9f31d28447aa0e31c6
[]
no_license
monikapatidar27/loops-problems
695708a45e8836c7fbea4f230d8cfa5bcd03b8e2
f35ced1632fc881d736369db0d43c89bfcdf8018
refs/heads/main
2023-07-14T12:41:20.745997
2021-08-12T15:18:06
2021-08-12T15:18:06
395,359,695
1
0
null
null
null
null
UTF-8
C++
false
false
363
cpp
#include <iostream> using namespace std ; int main(){ int t; cin>>t; while(t--){ int n; cin>>n; int i; for(i=2;i<n;i++){ if(n%i==0){ cout<<"non prime"<<"\n"; break; } } if(i==n){ cout<<"prime"<<"\n"; } } return 0; } /*4 2012 2324 3567 8978*/
[ "noreply@github.com" ]
monikapatidar27.noreply@github.com
b945a5c2e662602e80136e10c8488fdc6070bf43
c1d89ce276ccf3d2eeba4ab64d4dc2b049fbac85
/include/trident/kb/querier.h
605854c214df1081ca895a03a6b7388a41e8113e
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
jrbn/trident
c2720988411761d3986039c52a93cc869d04b7b1
e56a4977054eea01cb3f716db92bde5d6a49bfb7
refs/heads/master
2021-01-13T03:58:39.973847
2017-11-12T19:23:03
2017-11-12T19:23:03
78,136,282
1
0
null
null
null
null
UTF-8
C++
false
false
10,305
h
/* * Copyright 2017 Jacopo Urbani * * 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. **/ #ifndef QUERIER_H_ #define QUERIER_H_ //#include <trident/iterators/storageitr.h> #include <trident/iterators/arrayitr.h> #include <trident/iterators/scanitr.h> #include <trident/iterators/aggritr.h> #include <trident/iterators/cacheitr.h> #include <trident/iterators/termitr.h> #include <trident/iterators/compositeitr.h> #include <trident/iterators/compositetermitr.h> #include <trident/iterators/difftermitr.h> #include <trident/iterators/diffscanitr.h> #include <trident/iterators/compositescanitr.h> #include <trident/iterators/rmitr.h> #include <trident/iterators/rmcompositetermitr.h> #include <trident/tree/coordinates.h> #include <trident/binarytables/storagestrat.h> #include <trident/binarytables/factorytables.h> #include <trident/kb/diffindex.h> #include <kognac/factory.h> #include <boost/chrono.hpp> #include <iostream> namespace timens = boost::chrono; class TableStorage; class ListPairHandler; class GroupPairHandler; class Root; class DictMgmt; class CacheIdx; class KB; class Querier { private: Root* tree; DictMgmt *dict; TableStorage **files; long lastKeyQueried; bool lastKeyFound; const long inputSize; const long nTerms; const long *nTablesPerPartition; const long *nFirstTablesPerPartition; std::string pathRawData; bool copyRawData; const int nindices; std::vector<std::unique_ptr<DiffIndex>> &diffIndices; std::unique_ptr<Querier> sampler; TermCoordinates currentValue; //Factories Factory<ArrayItr> factory2; Factory<ScanItr> factory3; Factory<AggrItr> factory4; Factory<CacheItr> factory5; Factory<TermItr> factory7; Factory<CompositeItr> factory8; Factory<CompositeTermItr> factory9; Factory<DiffTermItr> factory10; Factory<DiffScanItr> factory11; Factory<CompositeScanItr> factory12; Factory<Diff1Itr> factory13; Factory<RmItr> factory14; Factory<RmCompositeTermItr> factory15; Factory<NewColumnTable> ncFactory; FactoryNewRowTable nrFactory; FactoryNewClusterTable ncluFactory; StorageStrat strat; //Statistics long aggrIndices, notAggrIndices, cacheIndices; long spo, ops, pos, sop, osp, pso; void initNewIterator(TableStorage *storage, int fileIdx, long mark, PairItr *t, long v1, long v2, const bool setConstraints); public: struct Counters { long statsRow; long statsColumn; long statsCluster; long aggrIndices; long notAggrIndices; long cacheIndices; long spo, ops, pos, sop, osp, pso; }; Querier(Root* tree, DictMgmt *dict, TableStorage** files, const long inputSize, const long nTerms, const int nindices, const long* nTablesPerPartition, const long* nFirstTablesPerPartition, KB *sampleKB, std::vector<std::unique_ptr<DiffIndex>> &diffIndices); void initDiffIndex(DiffIndex *diff); TermItr *getKBTermList(const int perm, const bool enforcePerm); PairItr *getTermList(const int perm); bool existKey(int perm, long key); TableStorage *getTableStorage(const int perm) { if (nindices <= perm) return NULL; else return files[perm]; } StorageStrat *getStorageStrat() { return &strat; } PairItr *get(const int idx, const long s, const long p, const long o) { return get(idx, s, p, o, true); } PairItr *get(const int idx, const long s, const long p, const long o, const bool cons); PairItr *get(const int idx, TermCoordinates &value, const long key, const long v1, const long v2, const bool cons); PairItr *get(const int perm, const long key, const short fileIdx, const long mark, const char strategy, const long v1, const long v2, const bool constrain, const bool noAggr); PairItr *getPermuted(const int idx, const long el1, const long el2, const long el3, const bool constrain); uint64_t isAggregated(const int idx, const long first, const long second, const long third); uint64_t isReverse(const int idx, const long first, const long second, const long third); uint64_t getCardOnIndex(const int idx, const long first, const long second, const long third) { return getCardOnIndex(idx, first, second, third, false); } uint64_t getCardOnIndex(const int idx, const long first, const long second, const long third, bool skipLast); long getCard(const long s, const long p, const long o); long getCard(const long s, const long p, const long o, uint8_t pos); //uint64_t getCard(const int idx, const long v); uint64_t estCardOnIndex(const int idx, const long first, const long second, const long third); long estCard(const long s, const long p, const long o); bool isEmpty(const long s, const long p, const long o); bool exists(const long s, const long p, const long o); int getIndex(const long s, const long p, const long o); char getStrategy(const int idx, const long v); int *getOrder(int idx); int *getInvOrder(int idx); uint64_t getInputSize() const { uint64_t tot = inputSize; for (size_t i = 0; i < diffIndices.size(); ++i) { long sizeUpdate = diffIndices[i]->getSize(); if (diffIndices[i]->getType() == DiffIndex::TypeUpdate::ADDITION) { tot += sizeUpdate; } else { tot -= sizeUpdate; } } return tot; } uint64_t getNFirstTablesPerPartition(const int idx) { uint64_t output = nFirstTablesPerPartition[idx]; if (!diffIndices.empty()) { for (size_t i = 0; i < diffIndices.size(); ++i) { if (diffIndices[i]->getType() == DiffIndex::TypeUpdate::ADDITION) { output += diffIndices[i]->getUniqueNFirstTerms(idx); } else { output -= diffIndices[i]->getUniqueNFirstTerms(idx); } } } return output; } uint64_t getNTerms() const { return nTerms; } void releaseItr(PairItr *itr); void resetCounters() { strat.resetCounters(); aggrIndices = notAggrIndices = cacheIndices = 0; spo = ops = pos = sop = osp = pso = 0; } Counters getCounters() { Counters c; c.statsRow = strat.statsRow; c.statsColumn = strat.statsColumn; c.statsCluster = strat.statsCluster; c.aggrIndices = aggrIndices; c.notAggrIndices = notAggrIndices; c.cacheIndices = cacheIndices; c.spo = spo; c.ops = ops; c.pos = pos; c.sop = sop; c.osp = osp; c.pso = pso; return c; } ArrayItr *getArrayIterator() { return factory2.get(); } PairItr *getPairIterator(TermCoordinates *value, int perm, const long key, long c1, long c2, const bool constrain, const bool noAggr) { short fileIdx = value->getFileIdx(perm); long mark = value->getMark(perm); char strategy = value->getStrategy(perm); return get(perm, key, fileIdx, mark, strategy, c1, c2, constrain, noAggr); } PairItr *newItrOnReverse(PairItr *itr, const long v1, const long v2); PairItr *getFilePairIterator(const int perm, const long constraint1, const long constraint2, const char strategy, const short file, const long pos) { PairItr *t = strat.getBinaryTable(strategy); initNewIterator(files[perm], file, pos, (PairItr*) t, constraint1, constraint2, true); return t; } DictMgmt *getDictMgmt() { return dict; } Querier &getSampler() { if (sampler == NULL) { BOOST_LOG_TRIVIAL(error) << "No sampler available"; throw 10; } else { return *sampler; } } std::string getPathRawData() { return pathRawData; } /*//The second row is ignored! This is useful for unlabelled graphs long getValue1AtRow(const int idx, const short fileIdx, const int mark, const char strategy, const long rowId);*/ const char *getTable(const int perm, const short fileId, const long markId); }; #endif
[ "jacopo@cs.vu.nl" ]
jacopo@cs.vu.nl
e56008600d02018966811363c01026966fcd5428
b112f67d606ae67790be66b789bb04318cc7b5a6
/GUI2/items/caritem.h
f009c01a3fde826a5b14bedf5f7325dc382cbb40
[]
no_license
moevm/gui-1h2018-21
d2d2e72bd29e7d8945f75a4f281ddba9b0d1044e
facf3f8536a1d2f0d2213f0fc4a19ba88b2904b2
refs/heads/master
2021-01-25T11:34:23.510188
2018-05-10T20:00:36
2018-05-10T20:00:36
123,411,545
1
3
null
2018-05-10T19:05:38
2018-03-01T09:19:25
C++
UTF-8
C++
false
false
343
h
#ifndef CARITEM_H #define CARITEM_H #include <QGraphicsItem> #include <QPixmap> #include <QtCore> #include <QtGui> class CarItem : public QGraphicsPixmapItem { public: CarItem(); virtual ~CarItem(); void setMovementSpeed(double speed); double getMovementSpeed(); private: double movementSpeed; }; #endif // CARITEM_H
[ "maskimgaskov@mail.ru" ]
maskimgaskov@mail.ru
6e1ed5589ac2430f5e0a7943cab69ec50629dcbb
2f064c6e284903060549e55d40213028d7476dfa
/LASS/src/AbstractIterator.h
d0861c2ba861c91a3d8b81f8af918d91546618e3
[]
no_license
tomokos2/DISSCO-2.0.2
167fa2ed70f360e574d93a843290813ab7e098b7
ee6c9ba0e12bf718bc6a73e80dfc2c23a742213b
refs/heads/master
2023-02-17T08:17:16.322262
2020-07-15T21:36:59
2020-07-15T21:36:59
275,158,048
0
0
null
2020-06-26T13:06:23
2020-06-26T13:06:22
null
UTF-8
C++
false
false
1,861
h
/* LASS (additive sound synthesis library) Copyright (C) 2005 Sever Tipei (s-tipei@uiuc.edu) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //----------------------------------------------------------------------------// // AbstractIterator.h //----------------------------------------------------------------------------// #ifndef __ABSTRACT_ITERATOR_H #define __ABSTRACT_ITERATOR_H //----------------------------------------------------------------------------// /** * This is a templated abstract definition of the most basic iterator. * \author Braden Kowitz **/ template<class T> class AbstractIterator { public: /** * \return An exact copy of this iterator **/ virtual AbstractIterator<T>* clone() = 0; /** * \retval true If the iterator has another value * \retval false If the iterator does not have another value **/ virtual bool hasNext() = 0; /** * \return The next value in the iterator as a reference **/ virtual T& next() = 0; /** * This is the destructor for the iterator. **/ virtual ~AbstractIterator(){}; }; //----------------------------------------------------------------------------// #endif //__ABSTRACT_ITERATOR_H
[ "xsun63@illinois.edu" ]
xsun63@illinois.edu
40e975ec8cf045357946dbea277b2281c772fa2d
912d38b91ffcdae2ddfa6ce2054f1f4002cf46a9
/codechef_stack_4_compiler_second_solution.cpp
ba5a8781fd743c9c55f71cdc663904c49452065a
[]
no_license
anuragsinghjadon/data-structure
4d6867e56f9184014ac921d94f2f1e5f49258f7a
54e86933b3541deb0cd012e84d12dbd5a1f95f6f
refs/heads/master
2021-04-07T14:48:29.495249
2021-02-12T16:44:14
2021-02-12T16:44:14
248,684,091
0
0
null
null
null
null
UTF-8
C++
false
false
523
cpp
#include<string> #include <bits/stdc++.h> using namespace std; int main() { // your code goes here long long int T; cin>>T; while(T--) { stack <char> s; string a; cin>>a; int n,i,j,c; c=0; n= a.length(); for(i=0;i<n;i++) { if(a[i]=='<') s.push(a[i]); if(a[i]=='>'&&!s.empty()) { if(s.top()=='<') { s.pop(); c=c+2; } } } cout<<c<<endl; } return 0; }
[ "anurags.jadon10@gmail.com" ]
anurags.jadon10@gmail.com
918a82f928957d15c10550906d5939739ca0ad43
6f6f890c5bcd3c090386ff746689488cb1c638ee
/Arrays/Subsets.cpp
1b5e8f8b0c5b0ec3003cd09bf33ed27c93c0edc5
[]
no_license
sharnoor404/Competitive-Coding
3068a5dc989dadfced7a22d57f7fbb92839aeafe
5a9a66f1a4cdc78fdc3f454c7205e15aeed5b2bf
refs/heads/master
2022-12-14T19:26:59.447441
2020-09-03T07:42:35
2020-09-03T07:42:35
268,509,588
0
0
null
null
null
null
UTF-8
C++
false
false
1,048
cpp
/* Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. Also, the subsets should be sorted in ascending ( lexicographic ) order. The list is not necessarily sorted. */ int subsetsHelper(vector<int> &A,vector<vector<int>> &result,int index){ if(index==A.size()){ vector<int> x; result.push_back(x); return 1; } int smallOutput=subsetsHelper(A,result,index+1); for(int i=0;i<smallOutput;i++){ vector<int> x; x.push_back(A[index]); for(int j=0;j<result[i].size();j++){ x.push_back(result[i][j]); } sort(x.begin(),x.end()); result.push_back(x); } return 2*smallOutput; } vector<vector<int> > Solution::subsets(vector<int> &A) { vector<vector<int>> result; subsetsHelper(A,result,0); std::stable_sort(result.begin(), result.end()); return result; }
[ "sharnoor404@gmail.com" ]
sharnoor404@gmail.com
d90ab67aab44573bde5765e728638abcfd2d74e0
0db28bf724b7d7b54ab8426e2b376a418a2e6d57
/CMC040/cmcfun/outp_36initfromfile.cc
a81c37d370b7209cb106bae018c524d0154323c1
[ "MIT" ]
permissive
khandy21yo/aplus
48ea413a26a4a5e23ab557e6dd3560c6a579aba5
3b4024a2a8315f5dcc78479a24100efa3c4a6504
refs/heads/master
2021-01-11T06:53:05.825792
2019-03-08T23:30:37
2019-03-08T23:30:37
72,404,068
1
0
null
null
null
null
UTF-8
C++
false
false
9,855
cc
//! \file //! \brief Initilize REPORT Output Information // %SBTTL "OUTP_36INITFROMFILE" // %IDENT "V3.6a Calico" // // Source: ../../CMC030/cmcfun/source/outp_36initfromfile.bas // Translated from Basic to C++ using btran // on Thursday, January 04, 2018 at 12:53:35 // #include <iostream> #include <fstream> #include <cstdlib> #include <cstring> #include <unistd.h> #include "basicfun.h" #include "preferences.h" #include "cmcfun.h" #include "database.h" #include "smg/lib.h" #include "smg/smg.h" #include "scopedef.h" #include "report.h" #include "utl/utl_reportx.h" //! //! \brief Initilize REPORT Output Information //! //! Abstract:HELP //! .p //! This function initilizes the REPORT output functions. //! //! Parameters: //! //! UTL_REPORTX //! The file used to initilize the report functions. //! //! XWIDTH //! The returned variable used for the report output. //! //! Returned value //! Initilizes the report output functions and other //! information the file has. //! //! Author: //! //! 03/23/87 - Kevin Handy //! void outp_36initfromfile( scope_struct &scope, utl_reportx_cdd &utl_reportx, int xwidth) { std::string inline_V1; std::string leftt; std::string printinit; std::string rightt; long rn_flag; long smg_status; long stat; long sys_status_V2; long temp1_long; std::string tempfile; long temp_long; std::string tolocal; std::string toscreen; std::ifstream report_ch; OnErrorStack; long sys_status; long templong; OnErrorGoto(L_19000); //****************************************************************** // Initilization //****************************************************************** // // Assume no errors // utl_reportx.stat = 0; // // Set up paging information // // Start without a page number utl_reportx.pageno = 0; // Not on a line // // Open up report file and read information for this report // sys_status = lib$get_symbol("CMC$REPORT", tempfile, 0, 0); if ((sys_status & 1) == 0) { entr_3message(scope, "Unable to find WORK file name!", 0); utl_reportx.stat = sys_status; return; } tempfile = boost::trim_right_copy(tempfile); // // Allocate a channel for report // report_ch.open(tempfile); if (!report_ch.is_open()) { throw basic::BasicError(5); } // // Assume no errors // utl_reportx.stat = 0; rn_flag = 0; // // Set up some defaults // utl_reportx.autoscroll = 0; utl_reportx.optdef[0] = ""; utl_reportx.printinit = ""; utl_reportx.pronam = ""; utl_reportx.offset = 0; // L_700:; // Read in one line of source file // try { getline(report_ch, inline_V1); if (report_ch.eof()) { throw basic::BasicError(11); } // End of file on device if (report_ch.fail()) { throw basic::BasicError(12); } // Fatal system I/O failure } catch(basic::BasicError &Be) { if (Be.err == 11) { inline_V1 = ""; goto L_750; } goto crash; } leftt = inline_V1.substr(0, 2); rightt = basic::right(inline_V1, 4); // // Process one line of input // // ** Converted from a select statement ** // // PG - Program name // if (leftt == "PG") { utl_reportx.pronam = rightt; utl_reportx.prodev = ""; // // LP - Lines/page // } else if (leftt == "LP") { utl_reportx.pagelen = std::stol(rightt); // // SP - Start page // } else if (leftt == "SP") { utl_reportx.startp = std::stol(rightt); // // EP - End page // } else if (leftt == "EP") { utl_reportx.endp = std::stol(rightt); // // CP - Copies // } else if (leftt == "CP") { utl_reportx.copies = std::stol(rightt); // // AF - After // } else if (leftt == "AF") { utl_reportx.aftertime = rightt; // // BG - Background // } else if (leftt == "BG") { utl_reportx.background = rightt; // // OF - Offset // } else if (leftt == "OF") { utl_reportx.offset = std::stol(rightt); // // RD - Report date // } else if (leftt == "RD") { utl_reportx.repdate = rightt; // // PD - Print report date on report // } else if (leftt == "PD") { utl_reportx.repyn = rightt; // // AS - Auto Scroll // } else if (leftt == "AS") { utl_reportx.autoscroll = std::stol(rightt); // // SP - Spooler name // } else if (leftt == "SL") { utl_reportx.spool = rightt; // // SF - Spooler Form name // } else if (leftt == "SF") { utl_reportx.spoolform = rightt; // // OD - Output device // } else if (leftt == "OD") { rn_flag = -1; utl_reportx.defout = rightt; // // XX - PRINTTO definition // } else if (leftt == "XX") { utl_reportx.printto = std::stol(rightt); // // TL - TOLOCAL Output to local printer // } else if (leftt == "TL") { utl_reportx.tolocal = rightt; // // TS - TOSCREEN return control to screen // } else if (leftt == "TS") { utl_reportx.toscreen = rightt; // // Un - User entries // } else if (leftt == "U1") { rn_flag = -1; utl_reportx.optdef[0] = rightt; } else if (leftt == "U2") { utl_reportx.optdef[1] = rightt; } else if (leftt == "U3") { utl_reportx.optdef[2] = rightt; } else if (leftt == "U4") { utl_reportx.optdef[3] = rightt; } else if (leftt == "U5") { utl_reportx.optdef[4] = rightt; } else if (leftt == "U6") { utl_reportx.optdef[5] = rightt; } else if (leftt == "U7") { utl_reportx.optdef[6] = rightt; } else if (leftt == "U8") { utl_reportx.optdef[7] = rightt; } else if (leftt == "U9") { utl_reportx.optdef[8] = rightt; } else if (leftt == "U0") { utl_reportx.optdef[9] = rightt; // // RN - Next report // } else if (leftt == "RN") { if (rn_flag) { goto L_1100; } utl_reportx.repnum = rightt; // // PC - Printer control string // } else if (leftt == "PC") { utl_reportx.printinit = rightt; // // PT - Printer Type // } else if (leftt == "PT") { utl_reportx.printtype = rightt; // // ZZ - Printer control string // } else if (leftt == "ZZ") { utl_reportx.printfinish = rightt; // // NP - Next page control string // } else if (leftt == "NP") { utl_reportx.nextpage = rightt; } goto L_700; // L_750:; // Finish up input file. // // // Set up paging information // // Start without a page number utl_reportx.pageno = 0; // Not on a line // // Initilize the width variable // if (utl_reportx.repwidth == 0) { utl_reportx.repwidth = 132; } if (xwidth != 0) { utl_reportx.repwidth = xwidth; } if (utl_reportx.pagelen == 0) { utl_reportx.pagelen = 66; } // // Keyboard open needed // if (utl_reportx.printto == OUTP_TODISPLAY) { scope.screen_width = utl_reportx.repwidth; if (scope.screen_width == 0) { scope.screen_width = 80; } smg_status = smg$change_pbd_characteristics(scope.smg_pbid, scope.screen_width); } entr_3message(scope, "", 1 + 16); //****************************************************************** // Remove group from print file //****************************************************************** L_1100:; utl_reportx.nextrun = ""; report_ch.close(); // // Delete the old file // // KILL TEMPFILE$ smg_status = lib$delete_file(tempfile); if ((smg_status & 1) == 0) { entr_3message(scope, std::string("Error deleting temp print file (") + std::to_string(smg_status) + ")", 4); } //****************************************************************** // Prepare for output of information //****************************************************************** writ_string(utl_reportx.printinit, printinit); writ_string(utl_reportx.tolocal, tolocal); writ_string(utl_reportx.toscreen, toscreen); // // Initilize the flags // // ** Converted from a select statement ** // // Display // if (utl_reportx.printto == OUTP_TODISPLAY) { // // No start/end pages // utl_reportx.startp = utl_reportx.endp = 0; // // Length of report is 18 lines // utl_reportx.pagelen = 20; // // Create display for this report // smg_status = smg$create_virtual_display(utl_reportx.pagelen, utl_reportx.repwidth * 1, utl_reportx.window); // // Paste on the virtual display // smg_status = smg$paste_virtual_display(utl_reportx.window, scope.smg_pbid, 1, 1); // // To terminal // } else if (utl_reportx.printto == OUTP_TODEVICE) { // utl_reportx.chan.open(utl_reportx.defout); if (!utl_reportx.chan.is_open()) { throw basic::BasicError(5); } utl_reportx.chan << printinit; // // Local printer // } else if (utl_reportx.printto == OUTP_TOLOCAL) { // // If we are going to the terminal, use the default terminal // channel to reduce buffering problems between SMG and // PRINT statements. // if (utl_reportx.defout == "TT:") { //utl_reportx.chan = 0; } else { // // Open keyboard for output // utl_reportx.chan.open(utl_reportx.defout); if (!utl_reportx.chan.is_open()) { throw basic::BasicError(5); } } utl_reportx.chan << tolocal << printinit << toscreen; // // Else a file // } else if ((utl_reportx.printto == OUTP_TOWP) || (utl_reportx.printto == OUTP_TODOCUMENT) || (utl_reportx.printto == OUTP_TO2020) || (utl_reportx.printto == OUTP_TOPL)) { utl_reportx.chan.open(utl_reportx.defout); if (!utl_reportx.chan.is_open()) { throw basic::BasicError(5); } // // Else a file // } else { utl_reportx.chan.open(utl_reportx.defout); if (!utl_reportx.chan.is_open()) { throw basic::BasicError(5); } utl_reportx.chan << printinit; } return; // crash:; // Exit from function with an error // utl_reportx.stat = 5; entr_3message(scope, std::string("ERROR: OUTP_36INITFROMFILE (") + "Error" + ") " + "Error" + " at line " + "0", 4); entr_3message(scope, std::string("ERROR: OUTP_36INITFROMFILE (") + inline_V1 + ") ", 4); return; //******************************************************************* L_19000:; // Trap errors // // // Untrapped error // OnErrorZero; goto crash; }
[ "khandy21yo@gmail.com" ]
khandy21yo@gmail.com
4af47333d4d58b3619ec602e7a7d637b5d01b5d1
db94cd0b996cf9fbc16519aacfa7a3cc83246ff4
/binarySearchTree.hpp
d04050a928d8f00dd60685481fd451c6b80f10e5
[]
no_license
mjaglarz/mapBST
a6cc0710213bd2b614f1617eec2c35ea84b922b2
11b2b0c7e9d1ef4efbb40f094251525ea770d520
refs/heads/master
2020-05-06T20:05:08.474031
2019-04-30T13:52:42
2019-04-30T13:52:42
180,221,104
0
0
null
null
null
null
UTF-8
C++
false
false
8,082
hpp
#ifndef BINARYSEARCHTREE_H #define BINARYSEARCHTREE_H #include <iostream> template <typename T = int> class BinarySearchTree{ public: struct Node{ T key; Node* left; Node* right; Node(T value):key(value), left(nullptr), right(nullptr){} }; T* insert(const T& x){ return insert(root_, x); } bool remove(const T& x); Node* search(const T& x) const { return search(root_, x); } T* find(const T& x){ return find(root_, x); } const T* findRec(const T& x) const { return findRec(root_, x); } Node* findParent(const T& x) const { return findParent(root_, x); } std::size_t size() const; T minimum(){ return minimum(root_); } T maximum(){ return maximum(root_); } int depth(){ return depth(root_); } void print(std::ostream& output, Node* root) const; void printInorder(){ printInorder(root_); } void printPreorder(){ printPreorder(root_); } void printPostorder(){ printPostorder(root_); } bool isEmpty() const; Node* rootPointer() const; void copyTree(Node* root); void freeMemory(Node* root); void swapTree(BinarySearchTree<T>& first, BinarySearchTree<T>& second); const BinarySearchTree<T>& operator=(const BinarySearchTree<T>& tree); const BinarySearchTree<T>& operator=(BinarySearchTree<T>&& tree); friend std::ostream& operator<<(std::ostream& output, const BinarySearchTree<T>& tree){ tree.print(output, tree.root_); return output << "\n"; } BinarySearchTree(); BinarySearchTree(const BinarySearchTree<T>& tree); BinarySearchTree(BinarySearchTree<T>&& tree) noexcept; ~BinarySearchTree(); private: Node* root_; int size_; T* insert(Node* root, const T& x); Node* remove(Node* root, const T& x); Node* search(Node* root, const T& x) const; T* find(Node* root, const T& x) const; const T* findRec(Node* root, const T& x) const; Node* findParent(Node* root, const T& x) const; T minimum(Node* root) const; T maximum(Node* root) const; int depth(Node* root) const; void printInorder(Node* root) const; void printPreorder(Node* root) const; void printPostorder(Node* root) const; }; template <typename T> T* BinarySearchTree<T>::insert(Node* root, const T& x){ if(isEmpty()){ root_ = new Node(x); size_++; return &root_->key; } if(x > root->key){ if(root->right != nullptr){ insert(root->right, x); }else{ root->right = new Node(x); size_++; return &root->right->key; } }else{ if(root->left != nullptr){ insert(root->left, x); }else{ root->left = new Node(x); size_++; return &root->left->key; } } return nullptr; } template <typename T> typename BinarySearchTree<T>::Node* BinarySearchTree<T>::remove(Node* root, const T& x){ if(root == nullptr){ return nullptr; } if(root->key > x){ root->left = remove(root->left, x); }else if(root->key < x){ root->right = remove(root->right, x); }else{ if(root->left == nullptr){ Node* temp = root->right; delete root; size_--; return temp; }else if(root->right == nullptr){ Node* temp = root->left; delete root; size_--; return temp; } Node* temp = root->right; while(temp->left != nullptr){ temp = temp->left; } root->key = temp->key; root->right = remove(root->right, temp->key); } return root; } template <typename T> bool BinarySearchTree<T>::remove(const T& x){ if(remove(root_, x) == nullptr){ return false; }else return true; } template <typename T> typename BinarySearchTree<T>::Node* BinarySearchTree<T>::search(Node* root, const T& x) const{ while(root != nullptr){ if(root->key == x){ return root; }else if(x < root->key){ root = root->left; }else{ root = root->right; } } return root; } template <typename T> T* BinarySearchTree<T>::find(Node* root, const T& x) const{ while(root != nullptr){ if(root->key == x){ return &root->key; }else if(x < root->key){ root = root->left; }else{ root = root->right; } } return nullptr; } template <typename T> const T* BinarySearchTree<T>::findRec(Node* root, const T& x) const{ if(root == nullptr){ return nullptr; }else if(root->key == x){ return &root->key; }else if(x < root->key){ return findRec(root->left, x); }else{ return findRec(root->right, x); } } template <typename T> typename BinarySearchTree<T>::Node* BinarySearchTree<T>::findParent(Node* root, const T& x) const{ if(root == nullptr){ return nullptr; }else if((root->right != nullptr && root->right->key == x) || (root->left != nullptr && root->left->key == x)){ return root; }else if(x < root->key){ return findParent(root->left, x); }else{ return findParent(root->right, x); } } template <typename T> std::size_t BinarySearchTree<T>::size() const{ return size_; } template <typename T> T BinarySearchTree<T>::minimum(Node* root) const{ if(isEmpty()){ throw "BST is empty"; } while(root->left != nullptr){ root = root->left; } return root->key; } template <typename T> T BinarySearchTree<T>::maximum(Node* root) const{ if(isEmpty()){ throw "BST is empty"; } while(root->right != nullptr){ root = root->right; } return root->key; } template <typename T> int BinarySearchTree<T>::depth(Node* root) const{ if(root == nullptr){ return 0; }else{ int leftSubTree = depth(root->left); int rightSubTree = depth(root->right); if(leftSubTree > rightSubTree){ return leftSubTree + 1; }else{ return rightSubTree + 1; } } } template <typename T> void BinarySearchTree<T>::print(std::ostream& output, Node* root) const{ if(root == nullptr){ return; } print(output, root->left); std::cout << root->key << " "; print(output, root->right); } template <typename T> void BinarySearchTree<T>::printInorder(Node* root) const{ if(root == nullptr){ return; } printInorder(root->left); std::cout << root->key << " "; printInorder(root->right); } template <typename T> void BinarySearchTree<T>::printPreorder(Node* root) const{ if(root == nullptr){ return; } std::cout << root->key << " "; printPreorder(root->left); printPreorder(root->right); } template <typename T> void BinarySearchTree<T>::printPostorder(Node* root) const{ if(root == nullptr){ return; } printPostorder(root->left); printPostorder(root->right); std::cout << root->key << " "; } template <typename T> bool BinarySearchTree<T>::isEmpty() const{ return size_ == 0; } template <typename T> typename BinarySearchTree<T>::Node* BinarySearchTree<T>::rootPointer() const{ return root_; } template <typename T> void BinarySearchTree<T>::copyTree(Node* root){ if(root != nullptr){ insert(root->key); copyTree(root->left); copyTree(root->right); } } template <typename T> void BinarySearchTree<T>::freeMemory(Node* root){ if(root == nullptr){ return; } freeMemory(root->left); freeMemory(root->right); delete root; } template <typename T> void BinarySearchTree<T>::swapTree(BinarySearchTree<T>& first, BinarySearchTree<T>& second){ std::swap(first.root_, second.root_); second.root_ = nullptr; } template <typename T> const BinarySearchTree<T>& BinarySearchTree<T>::operator=(const BinarySearchTree<T>& tree){ if(this != &tree){ freeMemory(root_); root_ = nullptr; copyTree(tree.root_); } return *this; } template <typename T> const BinarySearchTree<T>& BinarySearchTree<T>::operator=(BinarySearchTree<T>&& tree){ swapTree(*this, tree); return *this; } template <typename T> BinarySearchTree<T>::BinarySearchTree():root_(nullptr), size_(0){} template <typename T> BinarySearchTree<T>::BinarySearchTree(const BinarySearchTree<T>& tree):root_(nullptr), size_(0){ copyTree(tree.root_); } template <typename T> BinarySearchTree<T>::BinarySearchTree(BinarySearchTree<T>&& tree) noexcept:root_(nullptr), size_(0){ swapTree(*this, tree); } template <typename T> BinarySearchTree<T>::~BinarySearchTree(){ freeMemory(root_); } #endif
[ "noreply@github.com" ]
mjaglarz.noreply@github.com
d9495416ff45d94310e06cace49b00015a14ce29
05042a6ec2764594be984be45f01edae5218c549
/include/propria/traits/query_member.hpp
591ab4f69a1706409aed29d13a5dfc73e8c467f1
[ "BSL-1.0" ]
permissive
jaredhoberock/propria
9a84fdd763e43f7fc8216376938367f905ba8dba
7c46c8d2fcd0b16ad3de26835023e53d5c2c3750
refs/heads/master
2020-05-03T04:48:20.955755
2019-03-22T21:43:57
2019-03-22T21:50:09
178,432,109
0
0
null
2019-03-29T15:35:19
2019-03-29T15:35:18
null
UTF-8
C++
false
false
1,892
hpp
// // traits/query_member.hpp // ~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot 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) // #ifndef PROPRIA_TRAITS_QUERY_MEMBER_HPP #define PROPRIA_TRAITS_QUERY_MEMBER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "propria/detail/config.hpp" #include "propria/detail/type_traits.hpp" namespace propria { namespace detail { #if defined(PROPRIA_HAS_DECLTYPE) \ && defined(PROPRIA_HAS_NOEXCEPT) template <typename T, typename Property, typename = void> struct query_member_trait { PROPRIA_STATIC_CONSTEXPR(bool, is_valid = false); PROPRIA_STATIC_CONSTEXPR(bool, is_noexcept = false); }; template <typename T, typename Property> struct query_member_trait<T, Property, typename void_type< decltype(declval<T>().query(declval<Property>())) >::type> { PROPRIA_STATIC_CONSTEXPR(bool, is_valid = true); using result_type = decltype( declval<T>().query(declval<Property>())); PROPRIA_STATIC_CONSTEXPR(bool, is_noexcept = noexcept( declval<T>().query(declval<Property>()))); }; #else // defined(PROPRIA_HAS_DECLTYPE) // && defined(PROPRIA_HAS_NOEXCEPT) template <typename T, typename Property> struct query_member_trait { PROPRIA_STATIC_CONSTEXPR(bool, is_valid = false); PROPRIA_STATIC_CONSTEXPR(bool, is_noexcept = false); }; #endif // defined(PROPRIA_HAS_DECLTYPE) // && defined(PROPRIA_HAS_NOEXCEPT) } // namespace detail namespace traits { template <typename T, typename Property, typename = void> struct query_member : detail::query_member_trait<T, Property> { }; } // namespace traits } // namespace propria #endif // PROPRIA_TRAITS_QUERY_MEMBER_HPP
[ "chris@kohlhoff.com" ]
chris@kohlhoff.com
7428fc02b1d9b52935d7a4e1cbbea0a98d37a8df
680b8a33887ecec6523c9ec4eea70f896d6daf50
/GameEngine/GameEngine/src/Game/Renderer/SubTexture2D.h
0bd16cb6f818811eb4b7b9c50bf06723e532b6cf
[]
no_license
LibertAntoine/GameEngine
2940f649711802096566dd3b92c0f004034fcdde
00fff8af0266baa87620abf205cd067a218b265d
refs/heads/master
2022-12-22T15:45:17.654770
2020-10-05T12:41:39
2020-10-05T12:41:39
291,060,094
0
0
null
null
null
null
UTF-8
C++
false
false
593
h
#pragma once #include <glm/glm.hpp> #include "Texture.h" namespace GameEngine { class SubTexture2D { public: SubTexture2D(const Ref<Texture2D>& texture, const glm::vec2& min, const glm::vec2& max); inline const Ref<Texture2D> GetTexture() const { return m_Texture; } inline const glm::vec2* GetTexCoords() const { return m_TexCoords; } static Ref<SubTexture2D> CreateFromCoords(const Ref<Texture2D>& texture, const glm::vec2& coords, const glm::vec2& cellSize, const glm::vec2& spriteSize = { 1, 1 }); private: Ref<Texture2D> m_Texture; glm::vec2 m_TexCoords[4]; }; }
[ "duncan-arrakis@hotmail.fr" ]
duncan-arrakis@hotmail.fr
15f74e28f0e0894a24ff2c070d64e3a468f63786
9d6157bd515679c1628b3f1b0ceb9abb4175dbf3
/DlgNetwork.h
f3567a1ce7b7a31f4368bf06acd2a55759dc2f2a
[]
no_license
salmingo/CamagentS
34fbcaa6e012e7e1466780296542ec965c9ad8be
f90639043275b26791ae1a28d6ab7e1eac5da91c
refs/heads/master
2023-08-25T08:37:16.948166
2021-10-13T02:06:56
2021-10-13T02:06:56
416,558,366
0
0
null
null
null
null
UTF-8
C++
false
false
916
h
#pragma once #include "afxwin.h" #include "Parameter.h" // CDlgNetwork 对话框 class CDlgNetwork : public CDialogEx { DECLARE_DYNAMIC(CDlgNetwork) public: CDlgNetwork(Parameter* param, CWnd* pParent = nullptr); // 标准构造函数 virtual ~CDlgNetwork(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_DIALOG_NETWORK }; #endif protected: CIPAddressCtrl m_ipGtoaes; int m_portCamera; int m_portAnnex; CString m_idGroup; CString m_idUnit; CString m_idCamera; BOOL m_enableGtoaes; CIPAddressCtrl m_ipFileServer; int m_portFileServer; BOOL m_enableFileServer; CIPAddressCtrl m_ipNTP; BOOL m_enableNTP; Parameter* param_; /// 配置参数 protected: protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 virtual void OnOK(); virtual void OnCancel(); virtual BOOL OnInitDialog(); DECLARE_MESSAGE_MAP() public: afx_msg void OnClose(); };
[ "lxm@nao.cas.cn" ]
lxm@nao.cas.cn
effaf5dbb14f38d33218a22e0a8c77ce9ef4b6c7
668ebb505f4d8932e67dfdd1b24a99edcd4d880e
/2523.cpp
875343f47dab313c37beaa5a2fd5c67df315118b
[]
no_license
jpark1607/baekjoon_Cplusplus
06df940723ffb18ad142b267bae636e78ac610d8
8a1f4749d946bc256998ef9903098c8da6da1926
refs/heads/master
2021-07-13T03:47:29.002547
2021-07-11T14:01:10
2021-07-11T14:01:10
51,923,768
0
0
null
null
null
null
UTF-8
C++
false
false
282
cpp
#include <stdio.h> int main(void) { int N; int i, j; scanf("%d", &N); for(i = 0; i < N; i++) { for(j = 0; j <= i; j++) { printf("*"); } printf("\n"); } for(i = N - 1; i > 0; i--) { for(j = 0; j < i; j++) { printf("*"); } printf("\n"); } return 0; }
[ "jpark1607@gmail.com" ]
jpark1607@gmail.com
84b6b22c147c9ad69e4a734d104713daf12323d0
f5b4d401e81eee81c53fff3ebe93706af1c92b87
/src/public/src/fsgui3d/src/fsgui3dviewcontroldialog.cpp
00aed126c953b577947aae01e7b3a946af8c6c5e
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
rothberg-cmu/rothberg-run
a6cd2665c9d2113ec6be2a64af995b891fe640dc
a42df5ca9fae97de77753864f60d05295d77b59f
refs/heads/master
2020-04-27T18:41:16.879505
2019-05-01T17:26:52
2019-05-01T17:26:52
174,582,832
1
2
MIT
2019-05-01T17:26:53
2019-03-08T17:46:06
C++
UTF-8
C++
false
false
19,007
cpp
/* //////////////////////////////////////////////////////////// File Name: fsgui3dviewcontroldialog.cpp Copyright (c) 2017 Soji Yamakawa. All rights reserved. http://www.ysflight.com Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////// */ #include "fsgui3dviewcontrol.h" #include "fsgui3dviewcontroldialog.h" #include <fssimplewindow.h> #include "fsgui3dicon.h" /* virtual */ FsGui3DViewControlDialogBase::~FsGui3DViewControlDialogBase() { } /* static */ void FsGui3DViewControlDialogBase::Delete(FsGui3DViewControlDialogBase *toDel) { delete toDel; } FsGui3DViewControl &FsGui3DViewControlDialogBase::GetViewControl(void) { return *viewControl; } const FsGui3DViewControl &FsGui3DViewControlDialogBase::GetViewControl(void) const { return *viewControl; } void FsGui3DViewControlDialogBase::SaveLastView(void) { if(NULL!=viewControl) { lastView.pos=viewControl->GetViewTarget(); lastView.att=viewControl->GetViewAttitude(); lastView.zoom=viewControl->GetZoom(); lastView.dist=viewControl->GetViewDistance(); } } FsGui3DViewControlDialogBase::PosAttZoomDist FsGui3DViewControlDialogBase::RecallLastView(void) { if(NULL!=viewControl) { viewControl->SetViewTarget(lastView.pos); viewControl->SetViewAttitude(lastView.att); viewControl->SetZoom(lastView.zoom); viewControl->SetViewDistance(lastView.dist); } return lastView; } //////////////////////////////////////////////////////////// FsGui3DViewControlDialog::FsGui3DViewControlDialog() { viewControl=NULL; lastView.pos=YsOrigin(); lastView.att=YsZeroAtt(); SetIsPermanent(YSTRUE); orientationLock=YSFALSE; translationLock=YSFALSE; } FsGui3DViewControlDialog::~FsGui3DViewControlDialog() { } FsGui3DViewControlDialog *FsGui3DViewControlDialog::Create(void) { return new FsGui3DViewControlDialog; } void FsGui3DViewControlDialog::Make(class FsGuiCanvas *canvas,class FsGui3DViewControl *viewControl,YSBOOL minimize) { Initialize(); this->viewControl=viewControl; this->canvas=canvas; viewControl->AttachViewControlDialog(this); YsBitmap iconBmp; if(NULL==canvas || YSTRUE!=minimize) { if(NULL!=canvas) { closeBtn=AddTextButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,"Close",YSTRUE); } else { closeBtn=NULL; } openBtn=NULL; { iconBmp.LoadPng(sizeof(FsGui3DIcon::Shift),FsGui3DIcon::Shift); noSingleBtnOpBtn=AddBmpButton(0,FSKEY_NULL,FSGUI_RADIOBUTTON,iconBmp,L"-",YSFALSE); iconBmp.LoadPng(sizeof(FsGui3DIcon::Rotation),FsGui3DIcon::Rotation); rotateBtn=AddBmpButton(0,FSKEY_NULL,FSGUI_RADIOBUTTON,iconBmp,L"Rotation",YSFALSE); iconBmp.LoadPng(sizeof(FsGui3DIcon::Scroll),FsGui3DIcon::Scroll); translateBtn=AddBmpButton(0,FSKEY_NULL,FSGUI_RADIOBUTTON,iconBmp,L"Scroll",YSFALSE); noSingleBtnOpBtn->SetCheck(YSTRUE); FsGuiButton *radioButton[3]={noSingleBtnOpBtn,rotateBtn,translateBtn}; SetRadioButtonGroup(3,radioButton); } YsArray <YsArray <FsGuiDialogItem *> > dlgItemMatrix; dlgItemMatrix.Set(6,NULL); dlgItemMatrix[0].Set(4,NULL); dlgItemMatrix[1].Set(4,NULL); dlgItemMatrix[2].Set(4,NULL); dlgItemMatrix[3].Set(4,NULL); dlgItemMatrix[4].Set(4,NULL); dlgItemMatrix[5].Set(4,NULL); iconBmp.LoadPng(sizeof(FsGui3DIcon::RollLeft),FsGui3DIcon::RollLeft); rollLeftBtn=AddBmpButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,iconBmp,L"<",YSTRUE); iconBmp.LoadPng(sizeof(FsGui3DIcon::Up),FsGui3DIcon::Up); noseDownBtn=AddBmpButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,iconBmp,L"^",YSFALSE); iconBmp.LoadPng(sizeof(FsGui3DIcon::RollRight),FsGui3DIcon::RollRight); rollRightBtn=AddBmpButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,iconBmp,L">",YSFALSE); frontViewBtn=AddTextButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,"Front",YSFALSE); iconBmp.LoadPng(sizeof(FsGui3DIcon::Left),FsGui3DIcon::Left); yawLeftBtn=AddBmpButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,iconBmp,L"<",YSTRUE); iconBmp.LoadPng(sizeof(FsGui3DIcon::AttitudeIndicator),FsGui3DIcon::AttitudeIndicator); zeroAttBtn=AddBmpButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,iconBmp,L"O",YSFALSE); iconBmp.LoadPng(sizeof(FsGui3DIcon::Right),FsGui3DIcon::Right); yawRightBtn=AddBmpButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,iconBmp,L">",YSFALSE); rearViewBtn=AddTextButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,"Rear",YSFALSE); iconBmp.LoadPng(sizeof(FsGui3DIcon::Left90),FsGui3DIcon::Left90); left90Btn=AddBmpButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,iconBmp,L"<",YSTRUE); iconBmp.LoadPng(sizeof(FsGui3DIcon::Left),FsGui3DIcon::Down); noseUpBtn=AddBmpButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,iconBmp,L"v",YSFALSE); iconBmp.LoadPng(sizeof(FsGui3DIcon::Right90),FsGui3DIcon::Right90); right90Btn=AddBmpButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,iconBmp,L">",YSFALSE); topViewBtn=AddTextButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,"Top",YSFALSE); iconBmp.LoadPng(sizeof(FsGui3DIcon::Up),FsGui3DIcon::Up); scrollUpBtn=AddBmpButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,iconBmp,L"^",YSTRUE); bottomViewBtn=AddTextButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,"Bottom",YSFALSE); iconBmp.LoadPng(sizeof(FsGui3DIcon::Left),FsGui3DIcon::Left); scrollLeftBtn=AddBmpButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,iconBmp,L"<",YSTRUE); iconBmp.LoadPng(sizeof(FsGui3DIcon::CrossHair),FsGui3DIcon::CrossHair); centerBtn=AddBmpButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,iconBmp,L"O",YSFALSE); iconBmp.LoadPng(sizeof(FsGui3DIcon::Right),FsGui3DIcon::Right); scrollRightBtn=AddBmpButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,iconBmp,L">",YSFALSE); leftViewBtn=AddTextButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,"Left",YSFALSE); iconBmp.LoadPng(sizeof(FsGui3DIcon::Left),FsGui3DIcon::Down); scrollDownBtn=AddBmpButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,iconBmp,L"v",YSTRUE); rightViewBtn=AddTextButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,"Right",YSFALSE); dlgItemMatrix[0][0]=rollLeftBtn; dlgItemMatrix[0][1]=noseDownBtn; dlgItemMatrix[0][2]=rollRightBtn; dlgItemMatrix[0][3]=frontViewBtn; dlgItemMatrix[1][0]=yawLeftBtn; dlgItemMatrix[1][1]=zeroAttBtn; dlgItemMatrix[1][2]=yawRightBtn; dlgItemMatrix[1][3]=rearViewBtn; dlgItemMatrix[2][0]=left90Btn; dlgItemMatrix[2][1]=noseUpBtn; dlgItemMatrix[2][2]=right90Btn; dlgItemMatrix[2][3]=topViewBtn; dlgItemMatrix[3][0]=NULL; dlgItemMatrix[3][1]=scrollUpBtn; dlgItemMatrix[3][2]=NULL; dlgItemMatrix[3][3]=bottomViewBtn; dlgItemMatrix[4][0]=scrollLeftBtn; dlgItemMatrix[4][1]=centerBtn; dlgItemMatrix[4][2]=scrollRightBtn; dlgItemMatrix[4][3]=leftViewBtn; dlgItemMatrix[5][0]=NULL; dlgItemMatrix[5][1]=scrollDownBtn; dlgItemMatrix[5][2]=NULL; dlgItemMatrix[5][3]=rightViewBtn; AlignLeftMiddle(dlgItemMatrix); iconBmp.LoadPng(sizeof(FsGui3DIcon::Lock),FsGui3DIcon::Lock); AddStaticBmp(0,FSKEY_NULL,iconBmp,YSTRUE); iconBmp.LoadPng(sizeof(FsGui3DIcon::Rotation),FsGui3DIcon::Rotation); lockOrientationBtn=AddBmpButton(0,FSKEY_NULL,FSGUI_CHECKBOX,iconBmp,L"Rotation",YSFALSE); iconBmp.LoadPng(sizeof(FsGui3DIcon::Scroll),FsGui3DIcon::Scroll); lockTranslationBtn=AddBmpButton(0,FSKEY_NULL,FSGUI_CHECKBOX,iconBmp,L"Scroll",YSFALSE); zoomBtn=AddTextButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,"Zoom",YSTRUE); moozBtn=AddTextButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,"Mooz",YSFALSE); iconBmp.LoadPng(sizeof(FsGui3DIcon::OrthoPers),FsGui3DIcon::OrthoPers); orthoPersBtn=AddBmpButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,iconBmp,L"Ortho/Pers",YSFALSE); lookAtCoordTxt=AddTextBox(0,FSKEY_NULL,"",16,YSTRUE); lookAtCoordTxt->SetTextType(FSGUI_ASCIISTRING); lookAtCoordTxt->SetLengthLimit(256); lookAtBtn=AddTextButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,"Look At",YSTRUE); lastViewBtn=AddTextButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,"Last View",YSFALSE); lookAtCutBufBtn=AddTextButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,"Look At Cut-Buffer",YSTRUE); saveViewBtn=AddTextButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,"Save View",YSTRUE); loadViewBtn=AddTextButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,"Load View",YSFALSE); SetBackgroundAlpha(0.5); SetOrientationLock(orientationLock); SetTranslationLock(translationLock); } else { closeBtn=NULL; openBtn=AddTextButton(0,FSKEY_NULL,FSGUI_PUSHBUTTON,"Open View-Control Dialog",YSTRUE); rollLeftBtn=NULL; noseDownBtn=NULL; rollRightBtn=NULL; frontViewBtn=NULL; yawLeftBtn=NULL; zeroAttBtn=NULL; yawRightBtn=NULL; rearViewBtn=NULL; left90Btn=NULL; noseUpBtn=NULL; right90Btn=NULL; topViewBtn=NULL; scrollUpBtn=NULL; bottomViewBtn=NULL; scrollLeftBtn=NULL; centerBtn=NULL; scrollRightBtn=NULL; leftViewBtn=NULL; scrollDownBtn=NULL; rightViewBtn=NULL; lockOrientationBtn=NULL; lockTranslationBtn=NULL; zoomBtn=NULL; moozBtn=NULL; orthoPersBtn=NULL; lookAtCoordTxt=NULL; lookAtBtn=NULL; lastViewBtn=NULL; lookAtCutBufBtn=NULL; noSingleBtnOpBtn=NULL; rotateBtn=NULL; translateBtn=NULL; saveViewBtn=NULL; loadViewBtn=NULL; SetBackgroundAlpha(0.0); } SetArrangeType(FSDIALOG_ARRANGE_TOP_RIGHT); Fit(); } void FsGui3DViewControlDialog::OnButtonClick(FsGuiButton *btn) { if(NULL==viewControl) { return; } if(NULL!=btn && btn==openBtn && NULL!=canvas) { canvas->RemoveDialog(this); Make(canvas,viewControl,YSFALSE); canvas->AddDialog(this); canvas->ArrangeDialog(); } else if(NULL!=btn && btn==closeBtn && NULL!=canvas) { canvas->RemoveDialog(this); Make(canvas,viewControl,YSTRUE); canvas->AddDialog(this); canvas->ArrangeDialog(); } if(NULL!=btn && btn==rollLeftBtn) { YsAtt3 att=viewControl->GetViewAttitude(); att.AddB(YsPi/36.0); viewControl->SetViewAttitude(att); viewControl->SetNeedRedraw(YSTRUE); } if(NULL!=btn && btn==noseDownBtn) { YsAtt3 att=viewControl->GetViewAttitude(); att.NoseUp(-YsPi/36.0); viewControl->SetViewAttitude(att); viewControl->SetNeedRedraw(YSTRUE); } if(NULL!=btn && btn==rollRightBtn) { YsAtt3 att=viewControl->GetViewAttitude(); att.AddB(-YsPi/36.0); viewControl->SetViewAttitude(att); viewControl->SetNeedRedraw(YSTRUE); } if(NULL!=btn && btn==yawLeftBtn) { YsAtt3 att=viewControl->GetViewAttitude(); att.YawLeft(YsPi/36.0); viewControl->SetViewAttitude(att); viewControl->SetNeedRedraw(YSTRUE); } if(NULL!=btn && btn==zeroAttBtn) { viewControl->StraightenAttitude(); viewControl->SetNeedRedraw(YSTRUE); } if(NULL!=btn && btn==yawRightBtn) { YsAtt3 att=viewControl->GetViewAttitude(); att.YawLeft(-YsPi/36.0); viewControl->SetViewAttitude(att); viewControl->SetNeedRedraw(YSTRUE); } if(NULL!=btn && btn==noseUpBtn) { YsAtt3 att=viewControl->GetViewAttitude(); att.NoseUp(YsPi/36.0); viewControl->SetViewAttitude(att); viewControl->SetNeedRedraw(YSTRUE); } if(NULL!=btn && btn==scrollUpBtn) { Translate(0.0,-0.05); } if(NULL!=btn && btn==scrollLeftBtn) { Translate(0.05,0.0); } if(NULL!=btn && btn==centerBtn) { YsVec3 min,max; viewControl->GetTargetBoundingBox(min,max); viewControl->SetViewTarget((min+max)/2.0); } if(NULL!=btn && btn==scrollRightBtn) { Translate(-0.05,0.0); } if(NULL!=btn && btn==scrollDownBtn) { Translate(0.0,0.05); } if(NULL!=btn && btn==lockOrientationBtn) { SetOrientationLock(lockOrientationBtn->GetCheck()); } if(NULL!=btn && btn==lockTranslationBtn) { SetTranslationLock(lockTranslationBtn->GetCheck()); } if(NULL!=btn && btn==frontViewBtn) { YsAtt3 att=viewControl->GetStraightAttitude(); viewControl->SetViewAttitude(att); viewControl->SetNeedRedraw(YSTRUE); } if(NULL!=btn && btn==rearViewBtn) { YsAtt3 att=viewControl->GetStraightAttitude(); att.YawLeft(YsPi); viewControl->SetViewAttitude(att); viewControl->SetNeedRedraw(YSTRUE); } if(NULL!=btn && btn==topViewBtn) { YsAtt3 att=viewControl->GetStraightAttitude(); att.NoseUp(-YsPi/2.0); viewControl->SetViewAttitude(att); viewControl->SetNeedRedraw(YSTRUE); } if(NULL!=btn && btn==bottomViewBtn) { YsAtt3 att=viewControl->GetStraightAttitude(); att.NoseUp(YsPi/2.0); viewControl->SetViewAttitude(att); viewControl->SetNeedRedraw(YSTRUE); } if(NULL!=btn && btn==leftViewBtn) { YsAtt3 att=viewControl->GetStraightAttitude(); att.YawLeft(-YsPi/2.0); viewControl->SetViewAttitude(att); viewControl->SetNeedRedraw(YSTRUE); } if(NULL!=btn && btn==rightViewBtn) { YsAtt3 att=viewControl->GetStraightAttitude(); att.YawLeft(YsPi/2.0); viewControl->SetViewAttitude(att); viewControl->SetNeedRedraw(YSTRUE); } if(NULL!=btn && btn==zoomBtn) { viewControl->Zoom(1.1); } if(NULL!=btn && btn==moozBtn) { viewControl->Zoom(1.0/1.1); } if(NULL!=btn && btn==orthoPersBtn) { YSBOOL pers=viewControl->GetPerspective(); YsFlip(pers); viewControl->SetPerspective(pers); } if(NULL!=btn && btn==left90Btn) { YsAtt3 att=viewControl->GetViewAttitude(); att.YawLeft(YsPi/2.0); viewControl->SetViewAttitude(att); viewControl->SetNeedRedraw(YSTRUE); } if(NULL!=btn && btn==right90Btn) { YsAtt3 att=viewControl->GetViewAttitude(); att.YawLeft(-YsPi/2.0); viewControl->SetViewAttitude(att); viewControl->SetNeedRedraw(YSTRUE); } //FsGuiTextBox *lookAtCoordTxt if(NULL!=btn && btn==lookAtBtn) { SaveLastView(); YsString str; lookAtCoordTxt->GetText(str); for(YSSIZE_T idx=0; idx<str.Strlen(); ++idx) { if('('==str[idx] || ')'==str[idx] || ','==str[idx]) { str.Set(idx,' '); } } YsArray <YsString,4> xyz; str.Arguments(xyz); YsVec3 pos=viewControl->GetViewTarget(); if(1<=xyz.GetN()) { pos.SetX(atof(xyz[0])); } if(2<=xyz.GetN()) { pos.SetY(atof(xyz[1])); } if(3<=xyz.GetN()) { pos.SetZ(atof(xyz[2])); } viewControl->SetViewTarget(pos); } if(NULL!=btn && btn==lastViewBtn) { RecallLastView(); } if(NULL!=btn && btn==lookAtCutBufBtn) { } if(NULL!=btn && btn==saveViewBtn) { auto parent=GetParent(); if(NULL!=parent) { parent->OnSaveView(this); } } if(NULL!=btn && btn==loadViewBtn) { auto parent=GetParent(); if(NULL!=parent) { parent->OnLoadView(this); } } } void FsGui3DViewControlDialog::Translate(double dx,double dy) { if(NULL!=viewControl && NULL!=lockTranslationBtn && YSTRUE!=lockTranslationBtn->GetCheck()) { double vx,vy; if(viewControl->GetPerspective()!=YSTRUE) { double x1,y1,x2,y2; viewControl->GetOrthogonalRangeWithZoom(x1,y1,x2,y2); const double sx=fabs(x1-x2); const double sy=fabs(y1-y2); vx=dx*sx; vy=dy*sy; } else { const double tanfov=tan(viewControl->GetFOVY()); const double viewDist=viewControl->GetViewDistance(); vx=2.0*(dx*viewDist*tanfov/viewControl->GetZoom()); vy=2.0*(dy*viewDist*tanfov/viewControl->GetZoom()); } YsVec3 v(vx,vy,0.0); viewControl->GetViewMatrix().MulInverse(v,v,0.0); v+=viewControl->GetViewTarget(); viewControl->SetViewTarget(v); } } void FsGui3DViewControlDialog::SetOrientationLock(YSBOOL lock) { orientationLock=lock; if(NULL!=viewControl) { viewControl->SetOrientationLock(lock); // viewControl->SetOrientationLock will call this function back only if lock status has changed. // Therefore infinite recursion is avoided. } if(NULL!=lockOrientationBtn) { lockOrientationBtn->SetCheck(lock); } if(NULL!=rollLeftBtn) { rollLeftBtn->SetEnabled(YsReverseBool(lock)); } if(NULL!=noseDownBtn) { noseDownBtn->SetEnabled(YsReverseBool(lock)); } if(NULL!=rollRightBtn) { rollRightBtn->SetEnabled(YsReverseBool(lock)); } if(NULL!=yawLeftBtn) { yawLeftBtn->SetEnabled(YsReverseBool(lock)); } if(NULL!=zeroAttBtn) { zeroAttBtn->SetEnabled(YsReverseBool(lock)); } if(NULL!=yawRightBtn) { yawRightBtn->SetEnabled(YsReverseBool(lock)); } if(NULL!=noseUpBtn) { noseUpBtn->SetEnabled(YsReverseBool(lock)); } if(nullptr!=left90Btn) { left90Btn->SetEnabled(YsReverseBool(lock)); } if(nullptr!=right90Btn) { right90Btn->SetEnabled(YsReverseBool(lock)); } if(NULL!=frontViewBtn) { frontViewBtn->SetEnabled(YsReverseBool(lock)); } if(NULL!=rearViewBtn) { rearViewBtn->SetEnabled(YsReverseBool(lock)); } if(NULL!=topViewBtn) { topViewBtn->SetEnabled(YsReverseBool(lock)); } if(NULL!=bottomViewBtn) { bottomViewBtn->SetEnabled(YsReverseBool(lock)); } if(NULL!=leftViewBtn) { leftViewBtn->SetEnabled(YsReverseBool(lock)); } if(NULL!=rightViewBtn) { rightViewBtn->SetEnabled(YsReverseBool(lock)); } if(nullptr!=rotateBtn) { rotateBtn->SetEnabled(YsReverseBool(lock)); } } void FsGui3DViewControlDialog::SetTranslationLock(YSBOOL lock) { translationLock=lock; if(NULL!=viewControl) { // viewControl->SetTranslationLock will call this function back only if lock status has changed. // Therefore infinite recursion is avoided. viewControl->SetTranslationLock(lock); } if(NULL!=lockTranslationBtn) { lockTranslationBtn->SetCheck(lock); } if(NULL!=scrollUpBtn) { scrollUpBtn->SetEnabled(YsReverseBool(lock)); } if(NULL!=scrollLeftBtn) { scrollLeftBtn->SetEnabled(YsReverseBool(lock)); } if(NULL!=centerBtn) { centerBtn->SetEnabled(YsReverseBool(lock)); } if(NULL!=scrollRightBtn) { scrollRightBtn->SetEnabled(YsReverseBool(lock)); } if(NULL!=scrollDownBtn) { scrollDownBtn->SetEnabled(YsReverseBool(lock)); } if(nullptr!=translateBtn) { translateBtn->SetEnabled(YsReverseBool(lock)); } } void FsGui3DViewControlDialog::UpdateViewTarget(const YsVec3 &pos) { if(NULL!=lookAtCoordTxt) { YsString str; str.Printf("%.3lf, %.3lf, %.3lf",pos.x(),pos.y(),pos.z()); lookAtCoordTxt->SetText(str); } } YSBOOL FsGui3DViewControlDialog::SingleButtonRotation(void) const { if(NULL!=rotateBtn) { return rotateBtn->GetCheck(); } return YSFALSE; } YSBOOL FsGui3DViewControlDialog::SingleButtonScroll(void) const { if(NULL!=translateBtn) { return translateBtn->GetCheck(); } return YSFALSE; } /* virtual */ YSBOOL FsGui3DViewControlDialog::SingleButtonZoom(void) const { return YSFALSE; }
[ "minjunxu@andrew.cmu.edu" ]
minjunxu@andrew.cmu.edu
99fdf625cc622c3b3bf1233af3fed0a454f46226
7d7b4d7ea5cb55665445b06a834778c0782115f1
/itia_fir_planner/src/itia_fir_planner/velocity_profile.cpp
03767158cd3921880c8f6ca8838892c270c9a65d
[ "BSD-3-Clause" ]
permissive
CNR-STIIMA-IRAS/itia_motion
cb3e49cdf03a446ff6e6f3e914ec85d4e15bd2ba
1ffc2af3b5a3ddb4b7612eeb29a362bea8ae1680
refs/heads/master
2021-08-22T04:55:11.799081
2017-11-29T10:31:39
2017-11-29T10:31:39
109,697,964
1
0
null
null
null
null
UTF-8
C++
false
false
13,239
cpp
// -------------------------------------------------------------------------------- // Copyright (c) 2017 CNR-ITIA <iras@itia.cnr.it> // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of mosquitto 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 <itia_fir_planner/velocity_profile.h> namespace itia{ namespace helios{ VelocityProfile::VelocityProfile(const Eigen::VectorXd& qini, const unsigned int& np, const unsigned int& nfir, const double& st) { m_t_last_change=0; m_t_2last_change=0; m_np = np; m_nfir = nfir; if (m_nfir<2) { ROS_WARN("FIR coeff should be greater or equal than 2, set equal to 2"); m_nfir = 2; } m_st = st; m_nax = qini.rows(); m_q_nf.resize( m_np+m_nfir-1, m_nax); m_Dq_nf.resize( m_np+m_nfir-1, m_nax); m_q.resize( m_np, m_nax); m_Dq.resize( m_np, m_nax); m_DDq.resize(m_np, m_nax); for (unsigned int iax = 0;iax<m_nax;iax++) { m_q.col(iax) = Eigen::VectorXd::Constant(m_np, 1, qini(iax)); m_q_nf.col(iax) = Eigen::VectorXd::Constant(m_np+m_nfir-1, 1, qini(iax)); } m_Dq_nf.setZero(); m_Dq.setZero(); m_DDq.setZero(); m_waypoints.resize(m_nax, 1); m_waypoints = qini; m_waypoints_vel.resize(m_nax, 1); m_waypoints_vel.setConstant(1); m_waypoints_time.resize(1); m_waypoints_time(0) = 0; m_waypoints_accuracy.resize(1); m_waypoints_accuracy(0) = 0.1; m_upper_limit.resize(m_nax); m_lower_limit.resize(m_nax); m_upper_limit.setConstant( 1000); m_lower_limit.setConstant(-1000); m_time = 0; m_actual_wp_idx = 0; m_last_wp_idx = 0; m_soft_stopped = false; m_last_Dq = Eigen::VectorXd::Constant(m_nax, 1, 0.0); m_vel_scale=1; } void VelocityProfile::fillBuffer() { unsigned int wp_idx = m_actual_wp_idx; for (unsigned int ip = 0; ip<m_np;ip++) { double remaining_time = std::max(m_waypoints_time(wp_idx) - m_time-m_st*ip, m_st); Eigen::VectorXd vel = ( m_waypoints.col(wp_idx) - m_q_nf.row(ip+m_nfir-2).transpose() ).array() / remaining_time; for (unsigned int iax = 0;iax<m_nax;iax++) { vel(iax) = std::min( std::max( vel(iax), m_Dq_nf(0, iax)-m_waypoints_vel(iax, wp_idx)), m_Dq_nf(0, iax)+m_waypoints_vel(iax, wp_idx)); vel(iax) = std::min( std::max( vel(iax), -m_waypoints_vel(iax, wp_idx)), m_waypoints_vel(iax, wp_idx)); } m_Dq_nf.row(ip+m_nfir-1) = vel.transpose(); m_q_nf.row( ip+m_nfir-1) = m_q_nf.row(ip+m_nfir-2) + vel.transpose() * m_st; for (unsigned int iax = 0;iax<m_nax;iax++) { m_q(ip, iax) = m_q_nf.block( ip, iax, m_nfir, 1).mean(); m_Dq(ip, iax) = m_Dq_nf.block(ip, iax, m_nfir, 1).mean(); } if (ip>0) m_DDq.row(ip) = (m_Dq.row(ip)-m_Dq.row(ip-1)).array()/m_st; else m_DDq.row(ip) = m_Dq.row(ip).array()/m_st; if ( ( m_q.row(ip).transpose() - m_waypoints.col(wp_idx) ).array().abs().maxCoeff() < m_waypoints_accuracy(wp_idx) ) if ( wp_idx < ( m_waypoints_time.rows() -1 ) ) wp_idx++; } m_last_wp_idx = wp_idx; } void VelocityProfile::addPoints(const Eigen::VectorXd& time, const Eigen::MatrixXd& waypoints, const Eigen::MatrixXd& waypoints_vel, const Eigen::VectorXd& accuracy) { m_waypoints_time = time.array()+m_time; m_waypoints = waypoints; m_waypoints_accuracy = accuracy; m_waypoints_vel = waypoints_vel; m_t_last_change=m_time-(2.0*((double)m_nfir)*m_st); m_t_2last_change=m_time-(2.0*((double)m_nfir)*m_st); m_actual_wp_idx = 0; m_last_wp_idx = 0; // fillBuffer(); } int VelocityProfile::update( double& time, Eigen::VectorXd& q, Eigen::VectorXd& Dq, Eigen::VectorXd& DDq ) { int return_code=0; try { q = m_q.row(0).transpose(); Dq = m_Dq.row(0).transpose(); DDq = (m_Dq.row(0)-m_last_Dq).transpose()/m_st; m_last_Dq = Dq; time = m_time; // while ( m_actual_wp_idx < (m_waypoints_time.rows() -1 )) // { // if ( ( q - m_waypoints.col(m_actual_wp_idx) ).array().abs().maxCoeff() < std::max(m_waypoints_accuracy(m_actual_wp_idx), 1e-4)) // { // m_actual_wp_idx++; // ROS_INFO("reached waypoint #%d/%zu", m_actual_wp_idx, m_waypoints_time.rows()); // } // else // break; // } m_q.block( 0, 0, m_np-1, m_nax) = m_q.block( 1, 0, m_np-1, m_nax); m_Dq.block( 0, 0, m_np-1, m_nax) = m_Dq.block( 1, 0, m_np-1, m_nax); m_DDq.block(0, 0, m_np-1, m_nax) = m_DDq.block(1, 0, m_np-1, m_nax); m_q_nf.block(0, 0, m_np+m_nfir-2, m_nax) = m_q_nf.block( 1, 0, m_np+m_nfir-2, m_nax); m_Dq_nf.block(0, 0, m_np+m_nfir-2, m_nax) = m_Dq_nf.block(1, 0, m_np+m_nfir-2, m_nax); unsigned int ip = m_np-1; double remaining_time = std::max(m_waypoints_time(m_last_wp_idx) - m_time-m_st*ip, m_st); //ROS_INFO("remaining_time=%f", remaining_time); Eigen::VectorXd vel = ( m_waypoints.col(m_last_wp_idx) - m_q_nf.row(ip+m_nfir-2).transpose() ).array() / remaining_time; Eigen::VectorXd vel_limited=vel; double scale=1.0; for (unsigned int iax = 0;iax<m_nax;iax++) { vel_limited(iax) = std::min( std::max( vel_limited(iax), m_Dq_nf(ip-1, iax)-m_waypoints_vel(iax, m_last_wp_idx)), m_Dq_nf(ip-1, iax)+m_waypoints_vel(iax, m_last_wp_idx)); vel_limited(iax) = std::min( std::max( vel_limited(iax), -m_waypoints_vel(iax, m_last_wp_idx)), m_waypoints_vel(iax, m_last_wp_idx)); if ( (vel(iax)!=0) ) scale = std::min( scale, std::abs( vel_limited(iax)/vel(iax) ) ); } vel*=scale*m_vel_scale; bool is_on_limit=false;; Eigen::VectorXd next_pose = m_q_nf.row(ip+m_nfir-2) + vel.transpose() * m_st; for (unsigned int iax = 0;iax<m_nax;iax++) { bool upper_bound = (next_pose(iax)>=m_upper_limit(iax)) && (vel(iax)>0) ; bool lower_bound = (next_pose(iax)<=m_lower_limit(iax)) && (vel(iax)<0) ; is_on_limit = (is_on_limit) || ( upper_bound ) || ( lower_bound ) ; } if (is_on_limit) { return_code=-1; vel.setZero(); } m_Dq_nf.row(ip+m_nfir-1) = vel.transpose(); m_q_nf.row( ip+m_nfir-1) = m_q_nf.row(ip+m_nfir-2) + vel.transpose() * m_st; m_time += m_st; for (unsigned int iax = 0;iax<m_nax;iax++) { m_q(ip, iax) = m_q_nf.block( ip, iax, m_nfir, 1).mean(); m_Dq(ip, iax) = m_Dq_nf.block(ip, iax, m_nfir, 1).mean(); } if (ip>0) m_DDq.row(ip) = (m_Dq.row(ip)-m_Dq.row(ip-1)).array()/m_st; else m_DDq.row(ip) = m_Dq.row(ip).array()/m_st; m_soft_stopped =false; if ( ( (m_time-m_t_2last_change)> (0.25*((double)m_nfir)*m_st) ) && ( m_last_wp_idx < ( m_waypoints_time.rows() -1 ) ) ) { if ( ( m_q_nf.row(ip+m_nfir-1).transpose() - m_waypoints.col(m_last_wp_idx) ).array().abs().maxCoeff() <= std::max(m_waypoints_accuracy(m_last_wp_idx),1e-4) ) { m_t_2last_change=m_t_last_change; m_t_last_change=m_time; m_last_wp_idx++; ROS_DEBUG("reached waypoint #%d/%zu", m_last_wp_idx, m_waypoints_time.rows()); } } else { if ( ( m_q.row(ip).transpose() - m_waypoints.col(m_last_wp_idx) ).array().abs().maxCoeff() <= std::max(m_waypoints_accuracy(m_last_wp_idx),1e-4) ) { if ( m_last_wp_idx < ( m_waypoints_time.rows() -1 ) ) { m_last_wp_idx++; m_t_2last_change=m_t_last_change; m_t_last_change=m_time; ROS_DEBUG("reached waypoint #%d/%zu", m_last_wp_idx, m_waypoints_time.rows()); } else return 1; } } } catch (std::exception& e) { ROS_ERROR("VelocityProfile Update error: %s",e.what()); q = m_q.row(0).transpose(); Dq.setZero(); DDq.setZero(); return -2; } catch (...) { ROS_ERROR("VelocityProfile Update unchatched error"); q = m_q.row(0).transpose(); Dq.setZero(); DDq.setZero(); return -2; } return return_code; } void VelocityProfile::updateVel ( const Eigen::VectorXd& input_vel, double& time, Eigen::VectorXd& q, Eigen::VectorXd& Dq, Eigen::VectorXd& DDq ) { try { q = m_q.row(0).transpose(); Dq = m_Dq.row(0).transpose(); DDq = (m_Dq.row(0)-m_last_Dq).transpose()/m_st; m_last_Dq = Dq; time = m_time; m_q.block( 0, 0, m_np-1, m_nax) = m_q.block( 1, 0, m_np-1, m_nax); m_Dq.block( 0, 0, m_np-1, m_nax) = m_Dq.block( 1, 0, m_np-1, m_nax); m_DDq.block(0, 0, m_np-1, m_nax) = m_DDq.block(1, 0, m_np-1, m_nax); m_q_nf.block(0, 0, m_np+m_nfir-2, m_nax) = m_q_nf.block( 1, 0, m_np+m_nfir-2, m_nax); m_Dq_nf.block(0, 0, m_np+m_nfir-2, m_nax) = m_Dq_nf.block(1, 0, m_np+m_nfir-2, m_nax); unsigned int ip = m_np-1; Eigen::VectorXd vel = input_vel; Eigen::VectorXd vel_limited=vel; double scale=1.0; for (unsigned int iax = 0;iax<m_nax;iax++) { vel_limited(iax) = std::min( std::max( vel_limited(iax), m_Dq_nf(ip-1, iax)-m_waypoints_vel(iax, m_last_wp_idx)), m_Dq_nf(ip-1, iax)+m_waypoints_vel(iax, m_last_wp_idx)); vel_limited(iax) = std::min( std::max( vel_limited(iax), -m_waypoints_vel(iax, m_last_wp_idx)), m_waypoints_vel(iax, m_last_wp_idx)); if ( (vel(iax)!=0) ) scale = std::min( scale, std::abs( vel_limited(iax)/vel(iax) ) ); } vel*=scale*m_vel_scale; m_Dq_nf.row(ip+m_nfir-1) = vel.transpose(); m_q_nf.row( ip+m_nfir-1) = m_q_nf.row(ip+m_nfir-2) + vel.transpose() * m_st; m_time += m_st; for (unsigned int iax = 0;iax<m_nax;iax++) { m_q(ip, iax) = m_q_nf.block( ip, iax, m_nfir, 1).mean(); m_Dq(ip, iax) = m_Dq_nf.block(ip, iax, m_nfir, 1).mean(); } if (ip>0) m_DDq.row(ip) = (m_Dq.row(ip)-m_Dq.row(ip-1)).array()/m_st; else m_DDq.row(ip) = m_Dq.row(ip).array()/m_st; m_soft_stopped =false; } catch (std::exception& e) { ROS_ERROR("VelocityProfile Update error: %s",e.what()); q = m_q.row(0).transpose(); Dq.setZero(); DDq.setZero(); } catch (...) { ROS_ERROR("VelocityProfile Update unchatched error"); q = m_q.row(0).transpose(); Dq.setZero(); DDq.setZero(); } return; } void VelocityProfile::softStop(double& time, Eigen::VectorXd& q, Eigen::VectorXd& Dq, Eigen::VectorXd& DDq) { for (unsigned int ip = 0;ip<m_np;ip++) for (unsigned int iax = 0;iax<m_nax;iax++) { m_Dq(ip, iax) = m_Dq_nf.block(ip, iax, m_nfir, 1).mean(); m_q(ip, iax) = m_q_nf.block( ip, iax, m_nfir, 1).mean(); } q = m_q.row(0).transpose(); // q.setZero(); Dq = m_Dq.row(0).transpose(); DDq = (m_Dq.row(0)-m_last_Dq).transpose()/m_st; m_last_Dq = Dq; time = m_time; for (unsigned int iax = 0;iax<m_nax;iax++) { // m_q_nf.col(iax) = m_q_nf.col(iax).array()+Dq(iax) *m_st; Eigen::VectorXd Dq_nf(m_nax); Dq_nf.setZero(); for (unsigned int ifir = 0;ifir<(m_np+m_nfir-1);ifir++) { if (m_Dq_nf(ifir, iax) != 0) { if ( (m_Dq_nf(ifir, iax)>0) ) { Dq_nf(iax)=m_Dq_nf(ifir, iax); m_Dq_nf(ifir, iax) = 0; if ( m_Dq(0, iax) >= 0 ) break; } else if ( (m_Dq_nf(ifir, iax) < 0)) { Dq_nf(iax)=m_Dq_nf(ifir, iax); m_Dq_nf(ifir, iax) = 0; if ( m_Dq(0, iax) <= 0 ) break; } } } ROS_INFO_STREAM("Dq_nf="<<Dq_nf.transpose()); m_q_nf.col(iax) = m_q_nf.col(iax).array()+Dq_nf(iax) *m_st; } } void VelocityProfile::changeVelocityScale(const double& scale) { if (scale>100) m_vel_scale=1; else if ( scale<0 ) m_vel_scale=0; else m_vel_scale=scale/100.0; } } }
[ "you@example.com" ]
you@example.com
6ec5585cb5aaefbd1a934fb67a87f0efaf9457c2
a89b501f384e8ad9969f37b44519c1850b807e26
/ps4/e.cc
31fb323a3ed83d6e3e430aecfa2de13933ad226d
[]
no_license
mayman99/algo
9a368d3a8d770d8e2e2ca7efc3746e17e2ac9505
4b0f0ef6efc9c1ff0fc989a4427fb4f498754b85
refs/heads/master
2021-11-24T04:02:08.587372
2016-12-21T22:13:49
2016-12-21T22:13:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,289
cc
#include <vector> #include <iostream> #include <numeric> #include <string> #include <stdio.h> #include <algorithm> #include <stack> using namespace std; int src[20000]; int dst[20000]; stack <int>s; int main() { bool no,root,cycle=false; int n,d,N,M,node,Nclone,m,i=0; short roots=0; while(cin >> N >> m){ M = m; M++; bool visited[10000]; Nclone=N+1; std::vector< std::vector<int> > adj(N+1); while(m--) { cin>>n>>d; src[i]=n; dst[i]=d; adj[n].push_back(d); i++; } // for(int j=0;j<n+1;j++)visited[j]=false; // s.push(1); // int num=0; // while(!s.empty()){ // num++; // node=s.top(); // s.pop(); // if(visited[node]){ // break; // } // else{ // visited[node]=true; // for (int j = 0; j < adj[node].size(); ++j) // { // s.push(adj[node][j]); // } // } // } // if(num==N && (M+1)==N) // cout<<"YES"<<endl; // if(num!=N) // cout<<"NO"<<endl; // while (!s.empty()) // { // s.pop(); // } // adj.clear(); // return 0; for (int j = 1; j < i; ++j) { root=true; for (int k = 1; k < i; ++k) { if(src[j]==dst[k]){ root=false; break; } } if (root) { roots++; if(roots>1){ no=true; break; } } } if (roots!=1){ cout<<"NO"<<endl; // return 0; } for (int j = 0; j < m; ++j) { int a = src[j]; int b = dst[j]; for (int k = 0; k < m; ++k) { if (src[k]==b&&dst[k]==a) { cycle=true; break; } } if (cycle) { break; } } if(cycle){ cout<<"NO"<<endl; // return 0; }else{ cout<<"YES"<<endl; } // return 0; } return 0; }
[ "no.future2e1@gmail.com" ]
no.future2e1@gmail.com
dd956b82db99613aaf10ae096a0afc52e2ca70de
f01605671c712a5136c18bead84a37d5259a0053
/LinaEditor/include/Panels/ScenePanel.hpp
b6f560375a86425258148582a5beb7906fe6a409
[ "MIT" ]
permissive
forkrp/LinaEngine
14a3c64ddaa12143fb9e685efdd263af9ec5c781
4d2cd26b8f733e01763f1812b69f4a6b4aff655d
refs/heads/master
2023-01-01T19:55:42.962888
2020-10-27T07:58:30
2020-10-27T07:58:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,215
hpp
/* This file is a part of: Lina Engine https://github.com/inanevin/LinaEngine Author: Inan Evin http://www.inanevin.com Copyright (c) [2018-2020] [Inan Evin] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Class: ScenePanel Displays the final image of the scene generated via the engine. Is used as a main viewport for editing levels. Timestamp: 6/5/2020 6:51:29 PM */ #pragma once #ifndef ScenePanel_HPP #define ScenePanel_HPP #include "Panels/EditorPanel.hpp" #include "ECS/Components/TransformComponent.hpp" namespace LinaEngine { namespace Graphics { class RenderEngine; } } namespace LinaEditor { class ScenePanel : public EditorPanel { public: enum class DrawMode { FinalImage, ShadowMap }; ScenePanel() {}; virtual ~ScenePanel() {}; virtual void Setup() override; virtual void Draw() override; void EntitySelected(LinaEngine::ECS::ECSEntity entity); void Unselected(); void ProcessInput(); void DrawGizmos(); void SetDrawMode(DrawMode mode) { m_drawMode = mode; } void OnTransformAdded(entt::registry&, entt::entity); private: LinaEngine::ECS::TransformComponent* m_selectedTransform = nullptr; DrawMode m_drawMode = DrawMode::FinalImage; }; } #endif
[ "inanevin@gmail.com" ]
inanevin@gmail.com
e29bc9955a82dd038c87e22c692a35fa2e64a69b
29ae1ac35646f9e4f2307ac7bac5a398c8d9bb62
/Arduino/Lab1/PartH/PartH.ino
3f2f255712d88e7e00f4a7626caf73b14f8a19db
[]
no_license
cbudo/CSSE435
7135a7d58115cb948b77362eb87cd0f12efb21f5
486752df73e77d68e9cb7bd55697efee72e39c0e
refs/heads/master
2021-01-21T14:11:49.884603
2016-05-26T15:25:00
2016-05-26T15:25:00
53,685,174
0
0
null
null
null
null
UTF-8
C++
false
false
2,750
ino
/* Name: PartH.ino Created: 3/30/2016 1:45:21 PM Author: drong, budo */ // include the library code: #include <LiquidCrystal.h> #define PIN_LED_1 64 #define PIN_LED_2 65 #define PIN_LED_3 66 #define PIN_LED_4 67 #define PIN_LED_5 68 #define PIN_LED_6 69 #define PIN_RIGHT_BUTTON 2 #define PIN_LEFT_BUTTON 3 #define PIN_SELECT_BUTTON 21 #define PIN_CONTRAST_ANALOG 8 #define PIN_HORZ_ANALOG 0 #define PIN_VERT_ANALOG 1 #define LINE_1 0 #define LINE_2 1 #define DEAD_ZONE 100 int joyY = 0; int joyX = 0; int restY; int restX; int degs[] = { 90, 90, 90, 90, 90, 90 }; int incrAmt = 0; int selection = 5; int lastSelection = 0; int buttonLatch = 0; LiquidCrystal lcd(14, 15, 16, 17, 18, 19, 20); void setup() { pinMode(PIN_LEFT_BUTTON, INPUT_PULLUP); pinMode(PIN_RIGHT_BUTTON, INPUT_PULLUP); pinMode(PIN_SELECT_BUTTON, INPUT_PULLUP); pinMode(PIN_LED_1, OUTPUT); pinMode(PIN_LED_2, OUTPUT); pinMode(PIN_LED_3, OUTPUT); pinMode(PIN_LED_4, OUTPUT); pinMode(PIN_LED_5, OUTPUT); pinMode(PIN_LED_6, OUTPUT); restY = analogRead(PIN_VERT_ANALOG); restX = analogRead(PIN_HORZ_ANALOG); // set up the LCD's number of columns and rows: lcd.begin(16, 2); } void loop() { lcd.setCursor(0, 0); lcd.print(String(degs[0])+" "); lcd.setCursor(5, 0); lcd.print(String(degs[1])+" "); lcd.setCursor(10, 0); lcd.print(String(degs[2])+" "); lcd.setCursor(0, 1); lcd.print(String(degs[3])+" "); lcd.setCursor(5, 1); lcd.print(String(degs[4])+" "); lcd.setCursor(10, 1); lcd.print(String(degs[5])+" "); joyY = analogRead(PIN_VERT_ANALOG); joyX = analogRead(PIN_HORZ_ANALOG); if (!digitalRead(PIN_LEFT_BUTTON) && buttonLatch == 1) { buttonLatch = 0; lastSelection = selection; selection--; if (selection < 0) { selection = 5; } } else if (!digitalRead(PIN_RIGHT_BUTTON) && buttonLatch == 1) { buttonLatch = 0; lastSelection = selection; selection++; if (selection > 5) { selection = 0; } } else { buttonLatch = 1; } if (!digitalRead(PIN_SELECT_BUTTON)) { degs[selection] = 90; } incrementValues(); } void incrementValues() { if (abs(joyX - restX) > DEAD_ZONE && abs(joyX - restX) > abs(joyY - restY)) { // X dominant. increment by +-1 if ((joyX - restX) > 0) { incrAmt = -1; } else { incrAmt = 1; } } else if (abs(joyY - restY) > DEAD_ZONE && abs(joyY - restY) > abs(joyX - restX)) { // Y dominant. increment by +-4 if ((joyY - restY) > 0) { incrAmt = 4; } else { incrAmt = -4; } } else { incrAmt = 0; } degs[selection] += incrAmt; if (degs[selection] > 180) { degs[selection] = 180; } else if (degs[selection] < 1) { degs[selection] = 0; } digitalWrite(64 + selection, HIGH); digitalWrite(64 + lastSelection, LOW); delay(100); }
[ "lukedrong@gmail.com" ]
lukedrong@gmail.com
a8553b108aa507ab20775506babf9ea42dd4aeac
c287f063100e0ddb29bcf27e9f901b914cca0f2e
/thirdparty/qt53/include/QtWidgets/5.3.0/QtWidgets/private/qwidgetitemdata_p.h
a8ab58174f4b74accc7d405ed26c808a56e2c6d6
[ "MIT" ]
permissive
imzcy/JavaScriptExecutable
803c55db0adce8b32fcbe0db81531d248a9420d0
723a13f433aafad84faa609f62955ce826063c66
refs/heads/master
2022-11-05T01:37:49.036607
2016-10-26T17:13:10
2016-10-26T17:13:10
20,448,619
3
1
MIT
2022-10-24T23:26:37
2014-06-03T15:37:09
C++
UTF-8
C++
false
false
3,008
h
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtWidgets module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QWIDGETITEMDATA_P_H #define QWIDGETITEMDATA_P_H #include <QtCore/qdatastream.h> // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // QT_BEGIN_NAMESPACE class QWidgetItemData { public: inline QWidgetItemData() : role(-1) {} inline QWidgetItemData(int r, QVariant v) : role(r), value(v) {} int role; QVariant value; inline bool operator==(const QWidgetItemData &other) const { return role == other.role && value == other.value; } }; #ifndef QT_NO_DATASTREAM inline QDataStream &operator>>(QDataStream &in, QWidgetItemData &data) { in >> data.role; in >> data.value; return in; } inline QDataStream &operator<<(QDataStream &out, const QWidgetItemData &data) { out << data.role; out << data.value; return out; } #endif // QT_NO_DATASTREAM QT_END_NAMESPACE #endif // QWIDGETITEMDATA_P_H
[ "zcy920225@gmail.com" ]
zcy920225@gmail.com
d3f7bddf876b8d10347bf9099af4dcbf67169518
a06a28c5fe36c5cd480f49a9871d05f268c3cc5d
/jzzhu and sequences11.cpp
fbe5dde725238e5481d5de2e88951238a23989f0
[]
no_license
niharika987/dev
f7f84ea55e246ce2843f02704d5d0f17a083da8b
b588b29092abca975a828fbb7217622305907c1f
refs/heads/master
2020-03-29T07:13:49.934820
2018-09-20T19:23:34
2018-09-20T19:23:34
149,657,657
1
0
null
null
null
null
UTF-8
C++
false
false
329
cpp
// on my way................... #include<iostream> using namespace std; int x,y,x1,y1; int fn (int n) { if(n==y1) return y; if(n==x1) return x; return fn(n-1)-fn(n-2); } using namespace std; int main() { cin>>x>>y; x1=1; y1=2; int n,k; cin>>n; k=fn(n); if(k<0) cout<<k+1000000007; else cout<<k; return 0; }
[ "niharikasingh987@yahoo.com" ]
niharikasingh987@yahoo.com
7a3c8318c7b72712726363a51533fd66f7ce416a
98b1e51f55fe389379b0db00365402359309186a
/homework_7/problem_1/case_2/91/uniform/time
b6561bd2e88b923048d885ea337fad6a2fbf5719
[]
no_license
taddyb/597-009
f14c0e75a03ae2fd741905c4c0bc92440d10adda
5f67e7d3910e3ec115fb3f3dc89a21dcc9a1b927
refs/heads/main
2023-01-23T08:14:47.028429
2020-12-03T13:24:27
2020-12-03T13:24:27
311,713,551
1
0
null
null
null
null
UTF-8
C++
false
false
820
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 8 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "91/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 91.0000000000096492; name "91"; index 9100; deltaT 0.01; deltaT0 0.01; // ************************************************************************* //
[ "tbindas@pop-os.localdomain" ]
tbindas@pop-os.localdomain
ee36a6a57940792d8fa80ed88526bb5bc3b6f138
a4fb81b2bf72403dfb804abd6f7f40bf0c530a29
/Sorting and Searching/first_bad_version.cpp
7de6880efc3dc4f3c0fb1ae4bd4a75acfeb0f57d
[]
no_license
Anjum219/LeetCode-Top-Interview-Questions-Easy-Collection-
4446767074864538d48395c896c1dffa3df133e2
26ffc34e8956f49e407ab8bd7050f6253931bf32
refs/heads/master
2023-06-04T12:59:31.484486
2021-06-21T08:08:05
2021-06-21T08:08:05
326,961,958
6
0
null
null
null
null
UTF-8
C++
false
false
356
cpp
#include<bits/stdc++.h> #define ll long long int using namespace std; int firstBadVersion(int n) { int left = 1; int right = n; while( left < right ){ int mid = left + (right - left)/2; if( isBadVersion(mid) ){ right = mid; } else{ left = mid + 1; } } return left; }
[ "anjumhaz@gmail.com" ]
anjumhaz@gmail.com
b8a0d6756f5bc6d0ece51f8c7183ba401517e82d
66702ad401431b263ca996423830deb678de7e64
/src/masternode.h
828c6e2f36000bc086d03f1cc937353afc7de973
[ "MIT" ]
permissive
apujhinuk/ZestCoin
693f4121befdd41c67022ff9284a5f2a5edc139f
14ca4407ac5275c7ce656175e4b9e4063e91061a
refs/heads/master
2020-03-30T06:27:58.773111
2018-07-19T13:01:06
2018-07-19T13:01:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,970
h
// Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef MASTERNODE_H #define MASTERNODE_H #include "base58.h" #include "key.h" #include "main.h" #include "net.h" #include "sync.h" #include "timedata.h" #include "util.h" #define MASTERNODE_MIN_CONFIRMATIONS 15 #define MASTERNODE_MIN_MNP_SECONDS (10 * 60) #define MASTERNODE_MIN_MNB_SECONDS (5 * 60) #define MASTERNODE_PING_SECONDS (5 * 60) #define MASTERNODE_EXPIRATION_SECONDS (120 * 60) #define MASTERNODE_REMOVAL_SECONDS (130 * 60) #define MASTERNODE_CHECK_SECONDS 5 #define MASTERNODE_COLLATERAL 2500 using namespace std; class CMasternode; class CMasternodeBroadcast; class CMasternodePing; extern map<int64_t, uint256> mapCacheBlockHashes; bool GetBlockHash(uint256& hash, int nBlockHeight); // // The Masternode Ping Class : Contains a different serialize method for sending pings from masternodes throughout the network // class CMasternodePing { public: CTxIn vin; uint256 blockHash; int64_t sigTime; //mnb message times std::vector<unsigned char> vchSig; //removed stop CMasternodePing(); CMasternodePing(CTxIn& newVin); ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(vin); READWRITE(blockHash); READWRITE(sigTime); READWRITE(vchSig); } bool CheckAndUpdate(int& nDos, bool fRequireEnabled = true); bool Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode); void Relay(); uint256 GetHash() { CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << vin; ss << sigTime; return ss.GetHash(); } void swap(CMasternodePing& first, CMasternodePing& second) // nothrow { // enable ADL (not necessary in our case, but good practice) using std::swap; // by swapping the members of two classes, // the two classes are effectively swapped swap(first.vin, second.vin); swap(first.blockHash, second.blockHash); swap(first.sigTime, second.sigTime); swap(first.vchSig, second.vchSig); } CMasternodePing& operator=(CMasternodePing from) { swap(*this, from); return *this; } friend bool operator==(const CMasternodePing& a, const CMasternodePing& b) { return a.vin == b.vin && a.blockHash == b.blockHash; } friend bool operator!=(const CMasternodePing& a, const CMasternodePing& b) { return !(a == b); } }; // // The Masternode Class. It contains the input of the ZEST collateral, signature to prove // it's the one who own that ip address and code for calculating the payment election. // class CMasternode { private: // critical section to protect the inner data structures mutable CCriticalSection cs; int64_t lastTimeChecked; public: enum state { MASTERNODE_PRE_ENABLED, MASTERNODE_ENABLED, MASTERNODE_EXPIRED, MASTERNODE_OUTPOINT_SPENT, MASTERNODE_REMOVE, MASTERNODE_WATCHDOG_EXPIRED, MASTERNODE_POSE_BAN, MASTERNODE_VIN_SPENT, MASTERNODE_POS_ERROR }; CTxIn vin; CService addr; CPubKey pubKeyCollateralAddress; CPubKey pubKeyMasternode; CPubKey pubKeyCollateralAddress1; CPubKey pubKeyMasternode1; std::vector<unsigned char> sig; int activeState; int64_t sigTime; //mnb message time int cacheInputAge; int cacheInputAgeBlock; bool unitTest; bool allowFreeTx; int protocolVersion; int nActiveState; int64_t nLastDsq; //the dsq count from the last dsq broadcast of this node int nScanningErrorCount; int nLastScanningErrorBlockHeight; CMasternodePing lastPing; int64_t nLastDsee; // temporary, do not save. Remove after migration to v12 int64_t nLastDseep; // temporary, do not save. Remove after migration to v12 CMasternode(); CMasternode(const CMasternode& other); CMasternode(const CMasternodeBroadcast& mnb); void swap(CMasternode& first, CMasternode& second) // nothrow { // enable ADL (not necessary in our case, but good practice) using std::swap; // by swapping the members of two classes, // the two classes are effectively swapped swap(first.vin, second.vin); swap(first.addr, second.addr); swap(first.pubKeyCollateralAddress, second.pubKeyCollateralAddress); swap(first.pubKeyMasternode, second.pubKeyMasternode); swap(first.sig, second.sig); swap(first.activeState, second.activeState); swap(first.sigTime, second.sigTime); swap(first.lastPing, second.lastPing); swap(first.cacheInputAge, second.cacheInputAge); swap(first.cacheInputAgeBlock, second.cacheInputAgeBlock); swap(first.unitTest, second.unitTest); swap(first.allowFreeTx, second.allowFreeTx); swap(first.protocolVersion, second.protocolVersion); swap(first.nLastDsq, second.nLastDsq); swap(first.nScanningErrorCount, second.nScanningErrorCount); swap(first.nLastScanningErrorBlockHeight, second.nLastScanningErrorBlockHeight); } CMasternode& operator=(CMasternode from) { swap(*this, from); return *this; } friend bool operator==(const CMasternode& a, const CMasternode& b) { return a.vin == b.vin; } friend bool operator!=(const CMasternode& a, const CMasternode& b) { return !(a.vin == b.vin); } uint256 CalculateScore(int mod = 1, int64_t nBlockHeight = 0); ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { LOCK(cs); READWRITE(vin); READWRITE(addr); READWRITE(pubKeyCollateralAddress); READWRITE(pubKeyMasternode); READWRITE(sig); READWRITE(sigTime); READWRITE(protocolVersion); READWRITE(activeState); READWRITE(lastPing); READWRITE(cacheInputAge); READWRITE(cacheInputAgeBlock); READWRITE(unitTest); READWRITE(allowFreeTx); READWRITE(nLastDsq); READWRITE(nScanningErrorCount); READWRITE(nLastScanningErrorBlockHeight); } int64_t SecondsSincePayment(); bool UpdateFromNewBroadcast(CMasternodeBroadcast& mnb); inline uint64_t SliceHash(uint256& hash, int slice) { uint64_t n = 0; memcpy(&n, &hash + slice * 64, 64); return n; } void Check(bool forceCheck = false); bool IsBroadcastedWithin(int seconds) { return (GetAdjustedTime() - sigTime) < seconds; } bool IsPingedWithin(int seconds, int64_t now = -1) { now == -1 ? now = GetAdjustedTime() : now; return (lastPing == CMasternodePing()) ? false : now - lastPing.sigTime < seconds; } void Disable() { sigTime = 0; lastPing = CMasternodePing(); } bool IsEnabled() { return activeState == MASTERNODE_ENABLED; } int GetMasternodeInputAge() { if (chainActive.Tip() == NULL) return 0; if (cacheInputAge == 0) { cacheInputAge = GetInputAge(vin); cacheInputAgeBlock = chainActive.Tip()->nHeight; } return cacheInputAge + (chainActive.Tip()->nHeight - cacheInputAgeBlock); } std::string GetStatus(); std::string Status() { std::string strStatus = "ACTIVE"; if (activeState == CMasternode::MASTERNODE_ENABLED) strStatus = "ENABLED"; if (activeState == CMasternode::MASTERNODE_EXPIRED) strStatus = "EXPIRED"; if (activeState == CMasternode::MASTERNODE_VIN_SPENT) strStatus = "VIN_SPENT"; if (activeState == CMasternode::MASTERNODE_REMOVE) strStatus = "REMOVE"; if (activeState == CMasternode::MASTERNODE_POS_ERROR) strStatus = "POS_ERROR"; return strStatus; } int64_t GetLastPaid(); bool IsValidNetAddr(); }; // // The Masternode Broadcast Class : Contains a different serialize method for sending masternodes through the network // class CMasternodeBroadcast : public CMasternode { public: CMasternodeBroadcast(); CMasternodeBroadcast(CService newAddr, CTxIn newVin, CPubKey newPubkey, CPubKey newPubkey2, int protocolVersionIn); CMasternodeBroadcast(const CMasternode& mn); bool CheckAndUpdate(int& nDoS); bool CheckInputsAndAdd(int& nDos); bool Sign(CKey& keyCollateralAddress); void Relay(); ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(vin); READWRITE(addr); READWRITE(pubKeyCollateralAddress); READWRITE(pubKeyMasternode); READWRITE(sig); READWRITE(sigTime); READWRITE(protocolVersion); READWRITE(lastPing); READWRITE(nLastDsq); } uint256 GetHash() { CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << sigTime; ss << pubKeyCollateralAddress; return ss.GetHash(); } /// Create Masternode broadcast, needs to be relayed manually after that static bool Create(CTxIn vin, CService service, CKey keyCollateralAddressNew, CPubKey pubKeyCollateralAddressNew, CKey keyMasternodeNew, CPubKey pubKeyMasternodeNew, std::string& strErrorRet, CMasternodeBroadcast& mnbRet); static bool Create(std::string strService, std::string strKey, std::string strTxHash, std::string strOutputIndex, std::string& strErrorRet, CMasternodeBroadcast& mnbRet, bool fOffline = false); }; #endif
[ "zestnet@protonmail.com" ]
zestnet@protonmail.com
ded85de23265485e21739816bddd405921a0d13c
94e5a9e157d3520374d95c43fe6fec97f1fc3c9b
/@DOC by DIPTA/dipta007_final/Geometry/ellipse.cpp
7da8ec9690150a39a0b63e5db1d99858fae49744
[ "MIT" ]
permissive
dipta007/Competitive-Programming
0127c550ad523884a84eb3ea333d08de8b4ba528
998d47f08984703c5b415b98365ddbc84ad289c4
refs/heads/master
2021-01-21T14:06:40.082553
2020-07-06T17:40:46
2020-07-06T17:40:46
54,851,014
8
4
null
2020-05-02T13:14:41
2016-03-27T22:30:02
C++
UTF-8
C++
false
false
1,146
cpp
//(x/a)^2 + (y/b)^2 = 1; inline double F (double x,double e) { return sqrt(1.0 - (e*e*sin(x)*sin(x))); } double simpson (double a, double b,double e) { double ret = 0; double N = int (1e4); // N must be even double h = (b - a) / N; for (int i = 0; i <= N; ++i) { double x = a + h * i; ret += F (x,e) * ((i == 0 || i == N) ? 1 : (i & 1) ? 4 : 2); } ret *= (h/3.0); return ret; } struct ellipes{ double a,b,f,e; //a is half of major axis , b is half of minor axis ,f is focus , e is eccentricity point center,f1,f2; ellipes(double a,double b):a(a),b(b){ // given by a,b center = point(0,0); f = sqrt(a*a + b*b); e = f/a; f1 = point(-f,0); f2 = point(f,0); } /* ellipes(double mejor,double minor){ //given by mejor & minor axis a = mejor/2.0 , b = minor/2.0; center = point(0,0); f = sqrt(a*a + b*b); e = f/a; f1 = point(-f,0); f2 = point(f,0); }*/ double Circumference(){ return 4.0*a*simpson(0,PI/2.0,e); } double Area(){ return a*b*PI; } };
[ "iamdipta@gmail.com" ]
iamdipta@gmail.com
02cc2f9ff6c5e44b217988af18092c95301719b5
cb6f7a0f76e481a1be405936843a6fe5afeb6003
/include/character.hpp
febac2697020793ab14295ac6cb61d32a84a57e1
[]
no_license
Mooksc/RTS-Engine
6300264e780bd232291f81cbae8df90fb7da20b7
ec6616b8b5ce817ed42c15b34f2bb280dad7d524
refs/heads/master
2020-05-15T05:18:35.148988
2019-04-18T14:33:01
2019-04-18T14:33:01
182,103,219
0
0
null
null
null
null
UTF-8
C++
false
false
578
hpp
void character(float characterPosX, float characterPosY) { characterShape.setPosition(characterPosX, characterPosY); window.draw(characterShape); }; void newCharacterPos() { characterShape.setPosition(newCharacterPosX, newCharacterPosY); window.draw(characterShape); }; void setCharacterPos(float x, float y) { characterShape.setPosition(x, y); window.draw(characterShape); characterPosX = x; characterPosY = y; } float returnCharacterPosX() { return characterPosX; } float returnCharacterPosY() { return characterPosY; }
[ "noreply@github.com" ]
Mooksc.noreply@github.com
3d2db083109ee57d81477fb3a4f77ad668c91540
d35ec47116078b5e90048202708f0f0a010c7dfd
/gose-가운데_글자_가져오기.cpp
066244b7338bc20fc6eb1318874a26705e8396f7
[]
no_license
wkdnffla3/Practice_coding_test
1b371c7c6d153aaca4d24fdc428435debe3125f0
c0f576ecdcc3b34df74395d8985455e9b11c540b
refs/heads/master
2020-06-13T23:18:47.239054
2019-07-02T10:44:05
2019-07-02T10:44:05
194,820,005
0
0
null
null
null
null
UTF-8
C++
false
false
244
cpp
#include <string> #include <vector> using namespace std; string solution(string s) { string answer = ""; answer += s[(s.size() - 1)/2]; if(s.size() % 2 == 0){ answer += s[s.size()/2]; } return answer; }
[ "noreply@github.com" ]
wkdnffla3.noreply@github.com
0565a87fc952246c0c16026dc1af9daefaaca461
a65c77b44164b2c69dfe4bfa2772d18ae8e0cce2
/tioj/1905.cpp
1e21d77abba23d6466f3690343aa3411fa7b2d9b
[]
no_license
dl8sd11/online-judge
553422b55080e49e6bd9b38834ccf1076fb95395
5ef8e3c5390e54381683f62f88d03629e1355d1d
refs/heads/master
2021-12-22T15:13:34.279988
2021-12-13T06:45:49
2021-12-13T06:45:49
111,268,306
1
6
null
null
null
null
UTF-8
C++
false
false
3,828
cpp
#include <bits/stdc++.h> #pragma GCC optimize("Ofast,unroll-loops,no-stack-protector") using namespace std; typedef unsigned int ll; #define REP(i,n) for(int i=0;i<n;++i) #define REP1(i,n) for(int i=1;i<=n;++i) #define SZ(i) int(i.size()) #ifdef tmd #define IOS() #define debug(...) fprintf(stderr,"#%d: %s = ",__LINE__,#__VA_ARGS__),_do(__VA_ARGS__); template<typename T> void _do(T &&x){cerr<<x<<endl;} template<typename T, typename ...S> void _do(T &&x, S &&...y){cerr<<x<<", ";_do(y...);} template<typename It> ostream& _printRng(ostream &os,It bg,It ed) { os<<"{"; for(It it=bg;it!=ed;it++) { os<<(it==bg?"":",")<<*it; } os<<"}"; return os; } template<typename T> ostream &operator << (ostream &os,const vector<T> &v){return _printRng(os,v.begin(), v.end());} template<typename T> void pary(T bg, T ed){_printRng(cerr,bg,ed);cerr<<endl;} #else #define IOS() ios_base::sync_with_stdio(0);cin.tie(0); #define endl '\n' #define debug(...) #define pary(...) #endif const int MAXN = 100005; const ll MOD = 1000000007; const int INF = 0x3f3f3f3f; int n, m; ll ans[MAXN]; vector<ll> val; struct Query { int l, r, id; bool operator < (const Query &oth) const { return l > oth.l; } void rev () { l = n - l - 1; r = n - r - 1; swap(l, r); } }; vector<Query> query; struct SegmentTree { int dt[MAXN*2]; SegmentTree () { fill(dt, dt+n*2, n); } void upd (int x, int v) { for (dt[x+=n]=v; x>1; x>>=1) { dt[x>>1] = min(dt[x], dt[x^1]); } } int qryMax (int l, int r) { int ret = n; for (l+=n, r+=n; l<r; l>>=1, r>>=1) { if (l&1) { ret = min(ret, dt[l++]); } if (r&1) { ret = min(ret, dt[--r]); } } return ret; } }; struct Bit { ll dt[MAXN]; Bit () { memset(dt, INF, sizeof(dt)); } void upd (int x, ll v) { for (++x; x<MAXN; x+=-x&x) { dt[x] = min(dt[x], v); } } ll qryMin (int x) { ll ret = INF; for (++x; x>0; x-=-x&x) { ret = min(ret, dt[x]); } return ret; } }; void solve (const vector<ll> &a) { vector<int> ca(n); REP (i, n) { ca[i] = lower_bound(val.begin(),val.end(), a[i])-val.begin(); } sort(query.begin(), query.end()); SegmentTree lst; Bit pre; int idx = n-1; for (const Query &cur : query) { while (cur.l <= idx) { // update bit int pt = lst.qryMax(ca[idx], n); while (pt != n) { pre.upd(pt, a[pt]>a[idx] ? (a[pt]-a[idx]) : (a[idx]-a[pt])); if (a[pt] == a[idx]) { break; } ll ubd = a[pt]; ll mid = (ubd + a[idx]) >> 1; int vr = upper_bound(val.begin(), val.end(), mid)-val.begin(); pt = lst.qryMax(ca[idx], vr); } lst.upd(ca[idx], idx); idx--; } ans[cur.id] = min(ans[cur.id], pre.qryMin(cur.r)); } } /*********************GoodLuck***********************/ int main () { IOS(); memset(ans, INF, sizeof(ans)); cin >> n; vector<ll> a(n); REP (i, n) { cin >> a[i]; val.emplace_back(a[i]); } // compress the value sort(val.begin(), val.end()); val.resize(unique(val.begin(), val.end())-val.begin()); cin >> m; query.resize(m); REP (i, m) {; cin >> query[i].l >> query[i].r; query[i].l--, query[i].r--; query[i].id = i; } solve(a); reverse(a.begin(), a.end()); for (Query &el : query) { el.rev(); } solve(a); REP (i, m) { cout << ans[i] << endl; } }
[ "tmd910607@gmail.com" ]
tmd910607@gmail.com
dbd2649704fc361c6d088747b8f67ee296cf802b
267d4f163aaa4206ec36d88736ba7705f0de7346
/include/llfio/revision.hpp
e4849b50a2d930b72e142bbf6284b6401ab59c0f
[ "BSL-1.0", "Apache-2.0" ]
permissive
grassofsky/llfio
80b48a62f86b5672e964fba8a49ddc9c49c10d73
8b27842c25c47fd49ab64209463fc23268270975
refs/heads/master
2022-10-03T17:23:03.474255
2020-06-08T06:55:44
2020-06-08T06:55:44
270,562,303
0
0
Apache-2.0
2020-06-08T06:52:50
2020-06-08T06:52:50
null
UTF-8
C++
false
false
297
hpp
// Note the second line of this file must ALWAYS be the git SHA, third line ALWAYS the git SHA update time #define LLFIO_PREVIOUS_COMMIT_REF 17519e07a6022196e3e1de011f8e93b47e7eb587 #define LLFIO_PREVIOUS_COMMIT_DATE "2020-06-04 11:06:28 +00:00" #define LLFIO_PREVIOUS_COMMIT_UNIQUE 17519e07
[ "spamtrap@nedprod.com" ]
spamtrap@nedprod.com
a5d8e898ffbe8e538f89f09b724b034f0c560700
24a34054e3399da3885243fc149eb6914e3f5e0d
/Week_09/917.仅仅反转字母.cpp
b3c69b3076d87d4fc4eaf879c84221253a67a5b8
[]
no_license
cindycinthia/algorithm017
aea660bc8ba7da2300e972a038645485c9d9bd5e
4d0161c724b0c1b8e5d04305375bed13e8e0392e
refs/heads/master
2023-02-05T12:09:46.843603
2020-12-13T14:30:26
2020-12-13T14:30:26
297,317,446
0
0
null
2020-09-21T11:22:28
2020-09-21T11:22:27
null
UTF-8
C++
false
false
506
cpp
/* * @lc app=leetcode.cn id=917 lang=cpp * * [917] 仅仅反转字母 */ // @lc code=start class Solution { public: string reverseOnlyLetters(string S) { int begin = 0,end=S.length()-1; while(begin<end) { if(!isalpha(S[begin])) begin++; if(!isalpha(S[end])) end--; if(isalpha(S[begin])&&isalpha(S[end])) swap(S[begin++],S[end--]); } return S; } }; // @lc code=end
[ "chenyu1_1@163.com" ]
chenyu1_1@163.com
c6760d094bffdc15ff8c64f130b90ce73e5648bf
81542bcacfd129f8baa8eb5c034544aced2e3538
/arduino/ArduinoPusherTest_public_room/RobotExample/RobotExample.ino
020d124eb733e096345536343faa753d2ba41b03
[ "MIT" ]
permissive
augustozuniga/arisgames
39d52825945826b24ff61b908e87307fc6995dcf
1ccf8fcbd9083134972b80e429456dbd6e28aa3d
refs/heads/master
2016-09-05T20:22:33.638733
2013-05-06T17:34:31
2013-05-06T17:34:31
35,673,192
1
0
null
null
null
null
UTF-8
C++
false
false
815
ino
#include <SPI.h> #include <Ethernet.h> #include <PusherClient.h> byte mac[] = { 0xAB, 0xCD, 0xE2, 0xFF, 0xFE, 0xED }; PusherClient client; void setup() { Serial.begin(9600); Serial.println("Setup..."); if (Ethernet.begin(mac) == 0) { Serial.println("Init Ethernet failed"); while(1); } else Serial.println("Init Ethernet Success!"); if(client.connect("79f6a265dbb7402a49c9")) { client.bindAll(eventHandler); client.subscribe("public-pusher_room_channel"); Serial.println("Pusher Connect Success!"); } else { Serial.println("Pusher Connect failed"); while(1); } } void loop() { if (client.connected()) { client.monitor(); } else { Serial.println("Client Disconnected... :("); } } void eventHandler(String data) { Serial.println("Event!"); }
[ "pdougherty@wisc.edu@9a1de14e-70bd-11de-9e9f-05296fd93cd0" ]
pdougherty@wisc.edu@9a1de14e-70bd-11de-9e9f-05296fd93cd0
898a7ad3086c05c4487ab4ebcbea7ffc8d8f8342
c13c121d96fdd8682982854f43e50be011863aa1
/Code/Engine/gl-Renderer/GLRRQEntitySelection.cpp
cb1178b64b1ddb5e8db2c529416abd55ad29175b
[]
no_license
paksas/Tamy
14fe8e2ff5633ced9b24c855c6e06776bf221c10
6e4bd2f14d54cc718ed12734a3ae0ad52337cf40
refs/heads/master
2020-06-03T08:06:09.511028
2015-03-21T20:37:03
2015-03-21T20:37:03
25,319,755
0
1
null
null
null
null
UTF-8
C++
false
false
2,989
cpp
#include "core-Renderer\RQEntitySelection.h" #include "core-Renderer\Renderer.h" #include "core-Renderer\RendererUtils.h" #include "core\ListUtils.h" #include "gl-Renderer\GLRDefinitions.h" #include "gl-Renderer\GLRenderer.h" #include "gl-Renderer\GLRErrorCheck.h" #include "gl-Renderer\GLRRenderTarget2D.h" /////////////////////////////////////////////////////////////////////////////// void RCSelectEntities::execute( Renderer& renderer ) { GLRenderer* glRenderer = static_cast< GLRenderer* >( renderer.implementation() ); RCMarshallSelectionQueryResults* resultsComm = new ( glRenderer->mtComm() ) RCMarshallSelectionQueryResults( m_listener ); if ( !m_renderTarget ) { // this command doesn't operate on the back buffer return; } GLRRenderTarget2D* glRenderTarget = glRenderer->getRenderTarget( m_renderTarget ); if ( !glRenderTarget ) { return; } glRenderTarget->bindForRead(); const uint width = m_renderTarget->getWidth(); const uint height = m_renderTarget->getHeight(); // adjust point's coordinates so that they stay within bounds Point topLeftCorner, bottomRightCorner; topLeftCorner.x = clamp<int>( m_topLeftCorner.x, 0, width ); topLeftCorner.y = clamp<int>( m_topLeftCorner.y, 0, height ); bottomRightCorner.x = clamp<int>( m_bottomRightCorner.x, 0, width ); bottomRightCorner.y = clamp<int>( m_bottomRightCorner.y, 0, height ); const uint queryFrameWidth = bottomRightCorner.x - topLeftCorner.x + 1; const uint queryFrameHeight = bottomRightCorner.y - topLeftCorner.y + 1; // allocate a buffer large enough to be able to store query results byte* colorBuf = new byte[queryFrameWidth * queryFrameHeight * 4]; glReadPixels( topLeftCorner.x, height- topLeftCorner.y, queryFrameWidth, queryFrameHeight, GL_BGRA, GL_UNSIGNED_BYTE, colorBuf ); // scan the colors and translate them to pointers Color scannedColor; const uint pitch = queryFrameWidth * 4; for ( uint x = 0; x < queryFrameWidth; ++x ) { for ( uint y = 0; y < queryFrameHeight; ++y ) { uint addr = y * pitch + x * 4; byte* colorPtr = colorBuf + addr; scannedColor.b = colorPtr[0] / 255.f; scannedColor.g = colorPtr[1] / 255.f; scannedColor.r = colorPtr[2] / 255.f; scannedColor.a = colorPtr[3] / 255.f; Entity* entityPtr = ( Entity* ) RendererUtils::vecToPtr( ( const Vector& ) scannedColor ); if ( !entityPtr ) { continue; } // verify the entity's not on the list List< Entity* >::iterator entityIt = ListUtils::find( resultsComm->m_selectedEntities, entityPtr ); if ( entityIt.isEnd() ) { resultsComm->m_selectedEntities.pushBack( entityPtr ); } } } // cleanup delete [] colorBuf; glBindFramebuffer( GL_READ_FRAMEBUFFER, 0 ); } ///////////////////////////////////////////////////////////////////////////////
[ "ptrochim@gmail.com" ]
ptrochim@gmail.com
4887ae94913a7e284e41e867b4234dab5126c08f
3a64d611b73e036ad01d0a84986a2ad56f4505d5
/device/fido/cable/v2_discovery.cc
e4ce5099681adf4d6579460f3234e794c3e86a81
[ "BSD-3-Clause" ]
permissive
ISSuh/chromium
d32d1fccc03d7a78cd2fbebbba6685a3e16274a2
e045f43a583f484cc4a9dfcbae3a639bb531cff1
refs/heads/master
2023-03-17T04:03:11.111290
2020-09-26T11:39:44
2020-09-26T11:39:44
298,805,518
0
0
BSD-3-Clause
2020-09-26T12:04:46
2020-09-26T12:04:46
null
UTF-8
C++
false
false
4,210
cc
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "device/fido/cable/v2_discovery.h" #include "base/bind.h" #include "base/callback.h" #include "base/strings/string_number_conversions.h" #include "device/fido/cable/v2_handshake.h" #include "device/fido/fido_parsing_utils.h" #include "components/device_event_log/device_event_log.h" #include "device/fido/cable/fido_tunnel_device.h" #include "third_party/boringssl/src/include/openssl/aes.h" namespace device { namespace cablev2 { Discovery::Discovery( network::mojom::NetworkContext* network_context, QRGeneratorKey qr_generator_key, std::vector<std::unique_ptr<Pairing>> pairings, base::Optional<base::RepeatingCallback<void(std::unique_ptr<Pairing>)>> pairing_callback) : FidoDeviceDiscovery( FidoTransportProtocol::kCloudAssistedBluetoothLowEnergy), network_context_(network_context), local_identity_seed_(fido_parsing_utils::Materialize( base::span<const uint8_t, kCableIdentityKeySeedSize>( qr_generator_key.data(), kCableIdentityKeySeedSize))), qr_secret_(fido_parsing_utils::Materialize( base::span<const uint8_t, kCableQRSecretSize>( qr_generator_key.data() + kCableIdentityKeySeedSize, kCableQRSecretSize))), eid_key_(Derive<EXTENT(eid_key_)>(qr_secret_, base::span<const uint8_t>(), DerivedValueType::kEIDKey)), pairings_(std::move(pairings)), pairing_callback_(std::move(pairing_callback)) { // TODO(agl): disabled in order to separate out CLs. Re-enable. // static_assert(EXTENT(qr_generator_key) == // kCableIdentityKeySeedSize + kCableQRSecretSize, // ""); } Discovery::~Discovery() = default; void Discovery::StartInternal() { DCHECK(!started_); for (auto& pairing : pairings_) { tunnels_pending_advert_.emplace_back(std::make_unique<FidoTunnelDevice>( network_context_, std::move(pairing))); } pairings_.clear(); started_ = true; NotifyDiscoveryStarted(true); std::vector<CableEidArray> pending_eids(std::move(pending_eids_)); for (const auto& eid : pending_eids) { OnBLEAdvertSeen("", eid); } } void Discovery::OnBLEAdvertSeen(const std::string& address, const CableEidArray& eid) { if (!started_) { pending_eids_.push_back(eid); return; } if (base::Contains(observed_eids_, eid)) { return; } observed_eids_.insert(eid); // Check whether the EID satisfies any pending tunnels. for (std::vector<std::unique_ptr<FidoTunnelDevice>>::iterator i = tunnels_pending_advert_.begin(); i != tunnels_pending_advert_.end(); i++) { if (!(*i)->MatchEID(eid)) { continue; } FIDO_LOG(DEBUG) << " (" << base::HexEncode(eid) << " matches pending tunnel)"; std::unique_ptr<FidoTunnelDevice> device(std::move(*i)); tunnels_pending_advert_.erase(i); AddDevice(std::move(device)); return; } // Check whether the EID matches a QR code. AES_KEY aes_key; CHECK(AES_set_decrypt_key(eid_key_.data(), /*bits=*/8 * eid_key_.size(), &aes_key) == 0); CableEidArray plaintext; static_assert(EXTENT(plaintext) == AES_BLOCK_SIZE, "EIDs are not AES blocks"); AES_decrypt(/*in=*/eid.data(), /*out=*/plaintext.data(), &aes_key); if (cablev2::eid::IsValid(plaintext)) { FIDO_LOG(DEBUG) << " (" << base::HexEncode(eid) << " matches QR code)"; AddDevice(std::make_unique<cablev2::FidoTunnelDevice>( network_context_, base::BindOnce(&Discovery::AddPairing, weak_factory_.GetWeakPtr()), qr_secret_, local_identity_seed_, eid, plaintext)); return; } FIDO_LOG(DEBUG) << " (" << base::HexEncode(eid) << ": no v2 match)"; } void Discovery::AddPairing(std::unique_ptr<Pairing> pairing) { if (!pairing_callback_) { return; } pairing_callback_->Run(std::move(pairing)); } } // namespace cablev2 } // namespace device
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
d428ee6e6348dc98000db9529f7d45016f4adcf0
58e37a43d291d1884234f86b855b5f7da55725ef
/BitManipulation/Basics/printSubsets.cpp
2c90f04e64928d5d03c4c06a7e98c63ee5543786
[]
no_license
shashank9aug/DSA_CB
74337f8fb5dde5b94b380512dcec39a13e643690
1301329e4f9fd5105b4cb3c9d0f5c5772ed890ce
refs/heads/master
2023-08-18T05:35:42.946559
2021-10-15T10:04:52
2021-10-15T10:04:52
370,120,570
2
0
null
null
null
null
UTF-8
C++
false
false
566
cpp
/* $ ./a.exe abc a b ab c ac bc abc */ #include<iostream> #include<cstring> using namespace std; void filterChars(char a[],int n){ int j=0; while(n>0){ int last_bit=(n&1); if(last_bit==1){ cout<<a[j]; } j++; n=n>>1; } cout<<endl; } void printSubsets(char a[]){ int n=strlen(a); cout<<(1<<n)<<endl; for(int i=0;i<(1<<n);i++){ cout<<i<<", "; filterChars(a,i); } return; } int main(){ char a[100]; cin>>a; printSubsets(a); return 0; }
[ "shekhar1245shashank@gmail.com" ]
shekhar1245shashank@gmail.com
b4c843319830b6198a144bac5e72d23abe7189b1
b1320eb7edd285f493a0e4473dc433842aaa9178
/Blik2D/addon/openh264-1.6.0_for_blik/test/api/BaseEncoderTest.cpp
6977649e43a4d42dfe6d732f9ad4267b45636933
[ "MIT", "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
BonexGoo/Blik2D-SDK
2f69765145ef4281ed0cc2532570be42f7ccc2c6
8e0592787e5c8e8a28682d0e1826b8223eae5983
refs/heads/master
2021-07-09T01:39:48.653968
2017-10-06T17:37:49
2017-10-06T17:37:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,971
cpp
#include <fstream> #include <gtest/gtest.h> #include BLIK_OPENH264_U_codec_def_h //original-code:"codec_def.h" #include "utils/BufferedData.h" #include "utils/FileInputStream.h" #include "BaseEncoderTest.h" static int InitWithParam (ISVCEncoder* encoder, SEncParamExt* pEncParamExt) { SliceModeEnum eSliceMode = pEncParamExt->sSpatialLayers[0].sSliceArgument.uiSliceMode; bool bBaseParamFlag = (SM_SINGLE_SLICE == eSliceMode && !pEncParamExt->bEnableDenoise && pEncParamExt->iSpatialLayerNum == 1 && !pEncParamExt->bIsLosslessLink && !pEncParamExt->bEnableLongTermReference && !pEncParamExt->iEntropyCodingModeFlag) ? true : false; if (bBaseParamFlag) { SEncParamBase param; memset (&param, 0, sizeof (SEncParamBase)); param.iUsageType = pEncParamExt->iUsageType; param.fMaxFrameRate = pEncParamExt->fMaxFrameRate; param.iPicWidth = pEncParamExt->iPicWidth; param.iPicHeight = pEncParamExt->iPicHeight; param.iTargetBitrate = 5000000; return encoder->Initialize (&param); } else { SEncParamExt param; encoder->GetDefaultParams (&param); param.iUsageType = pEncParamExt->iUsageType; param.fMaxFrameRate = pEncParamExt->fMaxFrameRate; param.iPicWidth = pEncParamExt->iPicWidth; param.iPicHeight = pEncParamExt->iPicHeight; param.iTargetBitrate = 5000000; param.bEnableDenoise = pEncParamExt->bEnableDenoise; param.iSpatialLayerNum = pEncParamExt->iSpatialLayerNum; param.bIsLosslessLink = pEncParamExt->bIsLosslessLink; param.bEnableLongTermReference = pEncParamExt->bEnableLongTermReference; param.iEntropyCodingModeFlag = pEncParamExt->iEntropyCodingModeFlag ? 1 : 0; if (eSliceMode != SM_SINGLE_SLICE && eSliceMode != SM_SIZELIMITED_SLICE) //SM_SIZELIMITED_SLICE don't support multi-thread now param.iMultipleThreadIdc = 2; for (int i = 0; i < param.iSpatialLayerNum; i++) { param.sSpatialLayers[i].iVideoWidth = pEncParamExt->iPicWidth >> (param.iSpatialLayerNum - 1 - i); param.sSpatialLayers[i].iVideoHeight = pEncParamExt->iPicHeight >> (param.iSpatialLayerNum - 1 - i); param.sSpatialLayers[i].fFrameRate = pEncParamExt->fMaxFrameRate; param.sSpatialLayers[i].iSpatialBitrate = param.iTargetBitrate; param.sSpatialLayers[i].sSliceArgument.uiSliceMode = eSliceMode; if (eSliceMode == SM_SIZELIMITED_SLICE) { param.sSpatialLayers[i].sSliceArgument.uiSliceSizeConstraint = 600; param.uiMaxNalSize = 1500; param.iMultipleThreadIdc = 4; param.bUseLoadBalancing = false; } if (eSliceMode == SM_FIXEDSLCNUM_SLICE) { param.sSpatialLayers[i].sSliceArgument.uiSliceNum = 4; param.iMultipleThreadIdc = 4; param.bUseLoadBalancing = false; } } param.iTargetBitrate *= param.iSpatialLayerNum; return encoder->InitializeExt (&param); } } BaseEncoderTest::BaseEncoderTest() : encoder_ (NULL) {} void BaseEncoderTest::SetUp() { int rv = WelsCreateSVCEncoder (&encoder_); ASSERT_EQ (0, rv); ASSERT_TRUE (encoder_ != NULL); unsigned int uiTraceLevel = WELS_LOG_ERROR; encoder_->SetOption (ENCODER_OPTION_TRACE_LEVEL, &uiTraceLevel); } void BaseEncoderTest::TearDown() { if (encoder_) { encoder_->Uninitialize(); WelsDestroySVCEncoder (encoder_); } } void BaseEncoderTest::EncodeStream (InputStream* in, SEncParamExt* pEncParamExt, Callback* cbk) { ASSERT_TRUE (NULL != pEncParamExt); int rv = InitWithParam (encoder_, pEncParamExt); ASSERT_TRUE (rv == cmResultSuccess); // I420: 1(Y) + 1/4(U) + 1/4(V) int frameSize = pEncParamExt->iPicWidth * pEncParamExt->iPicHeight * 3 / 2; BufferedData buf; buf.SetLength (frameSize); ASSERT_TRUE (buf.Length() == (size_t)frameSize); SFrameBSInfo info; memset (&info, 0, sizeof (SFrameBSInfo)); SSourcePicture pic; memset (&pic, 0, sizeof (SSourcePicture)); pic.iPicWidth = pEncParamExt->iPicWidth; pic.iPicHeight = pEncParamExt->iPicHeight; pic.iColorFormat = videoFormatI420; pic.iStride[0] = pic.iPicWidth; pic.iStride[1] = pic.iStride[2] = pic.iPicWidth >> 1; pic.pData[0] = buf.data(); pic.pData[1] = pic.pData[0] + pEncParamExt->iPicWidth * pEncParamExt->iPicHeight; pic.pData[2] = pic.pData[1] + (pEncParamExt->iPicWidth * pEncParamExt->iPicHeight >> 2); while (in->read (buf.data(), frameSize) == frameSize) { rv = encoder_->EncodeFrame (&pic, &info); ASSERT_TRUE (rv == cmResultSuccess); if (info.eFrameType != videoFrameTypeSkip && cbk != NULL) { cbk->onEncodeFrame (info); } } } void BaseEncoderTest::EncodeFile (const char* fileName, SEncParamExt* pEncParamExt, Callback* cbk) { FileInputStream fileStream; ASSERT_TRUE (fileStream.Open (fileName)); ASSERT_TRUE (NULL != pEncParamExt); EncodeStream (&fileStream, pEncParamExt, cbk); }
[ "slacealic@gmail.com" ]
slacealic@gmail.com
a66b499b0bd451230dcdf3d97331eb04c9b13c9f
123cdb1d6a6956586dd91c86d02e0d1bacdcebae
/src/demo/pandora/level/Mission.h
198662b496b8c3a2452e67c253a2c0d41008a38c
[ "BSD-2-Clause" ]
permissive
KCL-Planning/strategic-tactical-pandora
1862f3240028d6eb5dbecf02350b9f295ec8f788
aa609af26a59e756b25212fa57fa72be937766e7
refs/heads/master
2021-01-23T05:50:00.669556
2017-11-30T11:16:48
2017-11-30T11:16:48
102,473,151
2
0
null
null
null
null
UTF-8
C++
false
false
564
h
#ifndef DEMO_PANDORA_LEVEL_MISSION_H #define DEMO_PANDORA_LEVEL_MISSION_H #include <string> #include <vector> #include <glm/glm.hpp> class Goal; class MissionSite; class Mission { public: Mission(MissionSite& mission_site); const std::string& getId() const { return id_; } void addGoal(Goal& goal); const std::vector<Goal*>& getGoals() const { return goals_; } void getStrageticPoints(std::vector<glm::vec3>& points) const; private: static int global_mission_id_; std::string id_; MissionSite* mission_site_; std::vector<Goal*> goals_; }; #endif
[ "bram.ridder@gmail.com" ]
bram.ridder@gmail.com
681281a9587110fca8c3f1abcb3c447d6d698ddd
dc0bbacb1736c0ea01f15c983aee68870d61764a
/chinese_chess/SingleGame.h
f03f8db05f65af7e38296a73ecca105d2a88b8b8
[]
no_license
guaiguaiduo/20200918team
afe43fedfe70e4606f511d1b1cf3a31bfab8e913
94d2d8f2067be802bb794ebf94d753663fa913bc
refs/heads/master
2022-12-17T17:43:06.077828
2020-09-18T08:38:20
2020-09-18T08:38:20
296,563,045
0
0
null
null
null
null
UTF-8
C++
false
false
751
h
#ifndef SINGLEGAME_H #define SINGLEGAME_H #include "Board.h" #include <Step.h> #include <QPushButton> class SingleGame : public Board { Q_OBJECT public: int _selectedid; QPushButton b3; Step _step1; explicit SingleGame(QWidget *parent = 0); bool judgesame(int i,int killed); void mouseReleaseEvent(QMouseEvent* ev); Step* getBestMove(); void saveStep(int moveid ,int row,int col,int killed,QVector<Step*>& steps); void getAllPossibleMove(QVector<Step*>& steps); int score(); void fakeMove(Step* step); void unfakeMove(Step* step); int getStone(int row,int col); int getMinScore(int level); int getMaxScore(int level); signals: }; #endif // SINGLEGAME_H
[ "noreply@github.com" ]
guaiguaiduo.noreply@github.com
38dc0de3840c4a5cb5fd78db2ed171cbc60c2b04
24103146706ab987a5617685e973aef970507378
/src/bitmap/bitmap_filter.cpp
9667fd35765d0a698d67e06f5dad4ad24affd234
[ "MIT" ]
permissive
daramkun/libdseed
27ca38318b5ade0931d761b2d7f6bd6f56086f51
7daabcbf2c6af88c92e2e504be437c37f1c434a5
refs/heads/master
2022-02-14T20:07:07.049654
2022-02-01T17:01:14
2022-02-01T17:01:14
189,190,943
0
0
null
null
null
null
UTF-8
C++
false
false
5,154
cpp
#include <dseed.h> #include <map> #include <cstring> using namespace dseed::color; dseed::bitmaps::bitmap_filter_mask::bitmap_filter_mask(float* mask, size_t width, size_t height) : width(width), height(height) { memcpy(this->mask, mask, width * height * sizeof(float)); } dseed::bitmaps::bitmap_filter_mask::bitmap_filter_mask(float mask, size_t width, size_t height) : width(width), height(height) { for (size_t i = 0; i < width * height; ++i) this->mask[i] = mask; } void dseed::bitmaps::bitmap_filter_mask::identity_3(bitmap_filter_mask* mask) { static float __identity[] = { 0, 0, 0, 0, 1, 0, 0, 0, 0 }; if (mask == nullptr) return; *mask = bitmap_filter_mask(__identity, 3, 3); } void dseed::bitmaps::bitmap_filter_mask::edge_detection_3(bitmap_filter_mask* mask) { static float __identity[] = { -1, -1, -1, -1, +8, -1, -1, -1, -1 }; if (mask == nullptr) return; *mask = bitmap_filter_mask(__identity, 3, 3); } void dseed::bitmaps::bitmap_filter_mask::sharpen_3(bitmap_filter_mask* mask) { static float __identity[] = { +0, -1, +0, -1, +5, -1, +0, -1, +0 }; if (mask == nullptr) return; *mask = bitmap_filter_mask(__identity, 3, 3); } void dseed::bitmaps::bitmap_filter_mask::gaussian_blur_3(bitmap_filter_mask* mask) { static float __identity[] = { +1, +2, +1, +2, +4, +2, +1, +2, +1 }; static float __factor = 1 / 16.0f; if (mask == nullptr) return; *mask = bitmap_filter_mask(__identity, 3, 3); mask->operator*=(__factor); } void dseed::bitmaps::bitmap_filter_mask::gaussian_blur_5(bitmap_filter_mask* mask) { static float __identity[] = { 1, 4, 6, 4, 1, 4, 16, 24, 16, 4, 6, 24, 36, 24, 6, 4, 16, 24, 16, 4, 1, 4, 6, 4, 1 }; static float __factor = 1 / 256.0f; if (mask == nullptr) return; *mask = bitmap_filter_mask(__identity, 5, 5); mask->operator*=(__factor); } void dseed::bitmaps::bitmap_filter_mask::unsharpmask_5(bitmap_filter_mask* mask) { static float __identity[] = { 1, 4, 6, 4, 1, 4, 16, 24, 16, 4, 6, 24, -476, 24, 6, 4, 16, 24, 16, 4, 1, 4, 6, 4, 1 }; static float __factor = -1 / 256.0f; if (mask == nullptr) return; *mask = bitmap_filter_mask(__identity, 5, 5); mask->operator*=(__factor); } using ftfn = std::function<bool(uint8_t*, const uint8_t*, const dseed::size3i&, const dseed::bitmaps::bitmap_filter_mask&)>; template<class TPixel> inline bool filter_bitmap(uint8_t* dest, const uint8_t* src, const dseed::size3i& size, const dseed::bitmaps::bitmap_filter_mask& mask) noexcept { size_t stride = calc_bitmap_stride(type2format<TPixel>(), size.width); size_t depth = calc_bitmap_plane_size(type2format<TPixel>(), dseed::size2i(size.width, size.height)); for (size_t z = 0; z < size.depth; ++z) { size_t depthZ = z * depth; for (size_t y = 0; y < size.height; ++y) { size_t strideY = y * stride; TPixel* destPtr = (TPixel*)(dest + depthZ + strideY); for (size_t x = 0; x < size.width; ++x) { colorv sum; for (int fy = 0; fy < (int)mask.height; ++fy) { for (int fx = 0; fx < (int)mask.width; ++fx) { size_t cx = dseed::clamp<int>((int)x + (fx - (int)mask.width / 2), size.width - 1); size_t cy = dseed::clamp<int>((int)y + (fy - (int)mask.height / 2), size.height - 1); colorv color = *((TPixel*)(src + depthZ + (stride * cy)) + cx); color = color * mask.get_mask(fx, fy); sum += color; } } sum.restore_alpha(*((TPixel*)(src + depthZ + (strideY)) + x)); TPixel* destPtrX = destPtr + x; *destPtrX = sum; } } } return true; } std::map<pixelformat, ftfn> g_filters = { { pixelformat::rgba8, filter_bitmap<rgba8> }, { pixelformat::rgb8, filter_bitmap<rgb8> }, { pixelformat::rgbaf, filter_bitmap<rgbaf> }, { pixelformat::bgra8, filter_bitmap<bgra8> }, { pixelformat::bgr8, filter_bitmap<bgr8> }, { pixelformat::bgra4, filter_bitmap<bgra4> }, { pixelformat::bgr565, filter_bitmap<bgr565> }, { pixelformat::r8, filter_bitmap<r8> }, { pixelformat::rf, filter_bitmap<rf> }, { pixelformat::yuva8, filter_bitmap<yuva8> }, { pixelformat::yuv8, filter_bitmap<yuv8> }, { pixelformat::hsva8, filter_bitmap<hsva8> }, { pixelformat::hsv8, filter_bitmap<hsv8> }, }; dseed::error_t dseed::bitmaps::filter_bitmap(dseed::bitmaps::bitmap* original, const dseed::bitmaps::bitmap_filter_mask& mask, dseed::bitmaps::bitmap** bitmap) { if (original == nullptr || bitmap == nullptr) return dseed::error_invalid_args; if (mask.width % 2 == 0 || mask.height % 2 == 0) return dseed::error_invalid_args; dseed::autoref<dseed::bitmaps::bitmap> temp; if (dseed::failed(dseed::bitmaps::create_bitmap(original->type(), original->size(), original->format(), nullptr, &temp))) return dseed::error_fail; uint8_t* destPtr, * srcPtr; original->lock((void**)&srcPtr); temp->lock((void**)&destPtr); auto found = g_filters.find(original->format()); if (found == g_filters.end()) return dseed::error_not_support; if (!found->second(destPtr, srcPtr, original->size(), mask)) return dseed::error_not_support; temp->unlock(); original->unlock(); *bitmap = temp.detach(); return dseed::error_good; }
[ "daramkun@live.com" ]
daramkun@live.com
cc2fcd483d06adf2ed7c59124f090b9e028d2bab
dc281e94e9b0d9b895867ec296ca90889d384675
/Geeks for geeks/Algorithm/Dynamic/Hard/Minimum Sum Partition.cpp
90158f6bb5dbbc9048b266e5459c8370de28cd77
[]
no_license
shreyash184/c-codes
70c494137c8a1224b0d688b22479667c6135a36d
79a92ef066493d88afb1758d76e24d989e4c07c3
refs/heads/master
2023-02-02T12:32:32.018515
2020-05-01T04:28:09
2020-05-01T04:28:09
145,076,888
1
0
null
2023-02-01T11:52:36
2018-08-17T05:42:43
C++
UTF-8
C++
false
false
844
cpp
using namespace std; int recur(int arr[], int n, int y, int sum){ int temp = sum/2; int dp[n+1][temp+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=temp;j++){ if(j==0||i==0){ dp[i][j]=0; } else if(j>=arr[i-1]){ dp[i][j]=max(dp[i-1][j],dp[i-1][j-arr[i-1]]+arr[i-1]); }else{ dp[i][j]=dp[i-1][j]; } } } return sum-2*dp[n][temp]; } int findMin(int arr[], int n){ int sumTotal = 0; for(int i=0;i<n;i++){ sumTotal+=arr[i]; } return recur(arr, n, 0, sumTotal); } int main() { //code int t; cin>>t; while(t--){ int n; cin>>n; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; cout<<findMin(a, n)<<endl; } return 0; }
[ "shreyashchavhan8@gmail.com" ]
shreyashchavhan8@gmail.com
615831ea0733609f9acba8b6905792342084cc4f
54a9c34c604249770c81f2f2b15af7f23448e8cb
/src/venus_net/protocol/22002_S2CTransferAccountsRsp.pb.h
93e41f152f91ef3798e49a76dceb178d860cc34c
[ "Unlicense" ]
permissive
blueantst/zpublic
3a51c1d1d5c0910d5ef5ad85feb4c617d6f5b049
17d798db89a9085200c2127e88ecf6b407393b3c
refs/heads/master
2020-12-11T06:13:25.796413
2013-12-30T09:09:39
2013-12-30T09:09:39
15,559,862
1
2
null
null
null
null
UTF-8
C++
false
true
7,980
h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: 22002_S2CTransferAccountsRsp.proto #ifndef PROTOBUF_22002_5fS2CTransferAccountsRsp_2eproto__INCLUDED #define PROTOBUF_22002_5fS2CTransferAccountsRsp_2eproto__INCLUDED #include <string> #include <google/protobuf/stubs/common.h> #if GOOGLE_PROTOBUF_VERSION < 2005000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 2005000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/generated_message_util.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) namespace Protocol { // Internal implementation detail -- do not call these. void protobuf_AddDesc_22002_5fS2CTransferAccountsRsp_2eproto(); void protobuf_AssignDesc_22002_5fS2CTransferAccountsRsp_2eproto(); void protobuf_ShutdownFile_22002_5fS2CTransferAccountsRsp_2eproto(); class S2CTransferAccountsRsp; // =================================================================== class S2CTransferAccountsRsp : public ::google::protobuf::Message { public: S2CTransferAccountsRsp(); virtual ~S2CTransferAccountsRsp(); S2CTransferAccountsRsp(const S2CTransferAccountsRsp& from); inline S2CTransferAccountsRsp& operator=(const S2CTransferAccountsRsp& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const S2CTransferAccountsRsp& default_instance(); void Swap(S2CTransferAccountsRsp* other); // implements Message ---------------------------------------------- S2CTransferAccountsRsp* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const S2CTransferAccountsRsp& from); void MergeFrom(const S2CTransferAccountsRsp& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // required int32 result = 1; inline bool has_result() const; inline void clear_result(); static const int kResultFieldNumber = 1; inline ::google::protobuf::int32 result() const; inline void set_result(::google::protobuf::int32 value); // required bytes content = 2; inline bool has_content() const; inline void clear_content(); static const int kContentFieldNumber = 2; inline const ::std::string& content() const; inline void set_content(const ::std::string& value); inline void set_content(const char* value); inline void set_content(const void* value, size_t size); inline ::std::string* mutable_content(); inline ::std::string* release_content(); inline void set_allocated_content(::std::string* content); // @@protoc_insertion_point(class_scope:Protocol.S2CTransferAccountsRsp) private: inline void set_has_result(); inline void clear_has_result(); inline void set_has_content(); inline void clear_has_content(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::std::string* content_; ::google::protobuf::int32 result_; mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[(2 + 31) / 32]; friend void protobuf_AddDesc_22002_5fS2CTransferAccountsRsp_2eproto(); friend void protobuf_AssignDesc_22002_5fS2CTransferAccountsRsp_2eproto(); friend void protobuf_ShutdownFile_22002_5fS2CTransferAccountsRsp_2eproto(); void InitAsDefaultInstance(); static S2CTransferAccountsRsp* default_instance_; }; // =================================================================== // =================================================================== // S2CTransferAccountsRsp // required int32 result = 1; inline bool S2CTransferAccountsRsp::has_result() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void S2CTransferAccountsRsp::set_has_result() { _has_bits_[0] |= 0x00000001u; } inline void S2CTransferAccountsRsp::clear_has_result() { _has_bits_[0] &= ~0x00000001u; } inline void S2CTransferAccountsRsp::clear_result() { result_ = 0; clear_has_result(); } inline ::google::protobuf::int32 S2CTransferAccountsRsp::result() const { return result_; } inline void S2CTransferAccountsRsp::set_result(::google::protobuf::int32 value) { set_has_result(); result_ = value; } // required bytes content = 2; inline bool S2CTransferAccountsRsp::has_content() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void S2CTransferAccountsRsp::set_has_content() { _has_bits_[0] |= 0x00000002u; } inline void S2CTransferAccountsRsp::clear_has_content() { _has_bits_[0] &= ~0x00000002u; } inline void S2CTransferAccountsRsp::clear_content() { if (content_ != &::google::protobuf::internal::kEmptyString) { content_->clear(); } clear_has_content(); } inline const ::std::string& S2CTransferAccountsRsp::content() const { return *content_; } inline void S2CTransferAccountsRsp::set_content(const ::std::string& value) { set_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { content_ = new ::std::string; } content_->assign(value); } inline void S2CTransferAccountsRsp::set_content(const char* value) { set_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { content_ = new ::std::string; } content_->assign(value); } inline void S2CTransferAccountsRsp::set_content(const void* value, size_t size) { set_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { content_ = new ::std::string; } content_->assign(reinterpret_cast<const char*>(value), size); } inline ::std::string* S2CTransferAccountsRsp::mutable_content() { set_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { content_ = new ::std::string; } return content_; } inline ::std::string* S2CTransferAccountsRsp::release_content() { clear_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { return NULL; } else { ::std::string* temp = content_; content_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); return temp; } } inline void S2CTransferAccountsRsp::set_allocated_content(::std::string* content) { if (content_ != &::google::protobuf::internal::kEmptyString) { delete content_; } if (content) { set_has_content(); content_ = content; } else { clear_has_content(); content_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); } } // @@protoc_insertion_point(namespace_scope) } // namespace Protocol #ifndef SWIG namespace google { namespace protobuf { } // namespace google } // namespace protobuf #endif // SWIG // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_22002_5fS2CTransferAccountsRsp_2eproto__INCLUDED
[ "278998871@qq.com" ]
278998871@qq.com
209abf8543f3c248ec6ffc3d4eb193b12beb93c1
2c5698d1f0ff43b13aa2b3aeb90a03c4bb0119a8
/ros_basic/src/moving_turtle_c++/position.cpp
ea4d4a75e1b76f7465d5f8b878cd3e5112d1c0bb
[]
no_license
suab321/ROS_Learning
5867943e7f09762a31d24547de19d82cf055f4d0
5f812a82c5d43393dc1232996f3f9ed95bdb191a
refs/heads/master
2020-04-24T19:44:31.711322
2019-03-24T22:08:45
2019-03-24T22:08:45
172,221,726
0
0
null
null
null
null
UTF-8
C++
false
false
394
cpp
#include<ros/ros.h> #include<turtlesim/Pose.h> void show_pos(const turtlesim::Pose::ConstPtr &coor){ float x=coor->x; float y=coor->y; //float z=coor->z; ROS_INFO("x is %uf; y is %uf",x,y); } int main(int argv,char **argc){ ros::init(argv,argc,"position"); ros::NodeHandle n; ros::Subscriber sub=n.subscribe("turtle1/pose",100,show_pos); ros::spin(); }
[ "adityasaha890@gmail.com" ]
adityasaha890@gmail.com
230e7f53f713e099d4940941f7c4dfa9d6d16966
e11931c9cdab9ce44c48c404f4381e364cc2be62
/DadosAbertos/Vetor.cpp
7724a908f813130b3d7d893fb0ed366eecdcc3e4
[]
no_license
EvaCosta/DadosAbertos
c9442e77266c3fb4745a6e62d1ebb7eabc208794
2694e37b6926bfd4d8765768ea7a7fac55047723
refs/heads/master
2020-06-06T00:03:44.943603
2019-06-18T17:14:43
2019-06-18T17:14:43
192,581,606
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,357
cpp
#include <iostream> #include <stdio.h> #include <conio.h> #include "Vetor.h" //Construtor default. Vetor::Vetor(){} //Adiciona o Objeto venda no final do vector. bool Vetor::adicionarVendaString(string linha) { venda.push_back(linha); linhasArquivoVenda++; return true; } //Adiciona o Objeto investidor no final do vector. bool Vetor::adicionarInvestidorString(string linha) { investidor.push_back(linha); linhasArquivoInvestidor++; return true; } //Armazena no vector de Investidores os dados. bool Vetor::adicionarVendaNoObjeto(Venda &venda) { vendas.push_back(venda); return true; } //Armazena no vector de Investidores os dados. bool Vetor::adicionarInvestidorNoObjeto(Investidor & investidor) { investidores.push_back(investidor); return true; } //Armazena no vector de Investidores os dados. bool Vetor::removeInvestidorNoObjeto() { investidores.clear(); return true; } int Vetor::obterTamanhoVendasString(){ return venda.size(); } int Vetor::obterTamanhoVendas() { return vendas.size(); } int Vetor::obterTamanhoInvestidor() { return investidores.size(); } //Obtém o tamanho do vector investidor. int Vetor::obterTamanhoInvestidorString() { return investidor.size(); } int Vetor::obterQtdeLinhasInvestidorString(){ return linhasArquivoInvestidor; } int Vetor::obterQtdeLinhasVendaString(){ return linhasArquivoVenda; } // Exibe de acordo com a posição passada por parametro os dados correspondentes no vector de Venda void Vetor::exibirVendasPorData(int i) { cout << "\n-=> " << vendas[i].getTitulo() << "\n"; cout << "\tData de Vencimento: " << vendas[i].getDataDeVencimento() << "\n"; cout << "\tQuantidade: " << vendas[i].getQuantidade() << "\n"; cout << "\tValor: R$ " << vendas[i].getValor() << "\n"; } //Obtém e retorna a string de acordo com a posição. Retorna o objeto se a posição for válida e um objeto vazio caso contrário. string & Vetor::obterVendaString(int posicao){ string auxiliar; if (posicao >= 0 && posicao <= obterTamanhoVendasString()) { return venda.at(posicao); } return auxiliar; } //Obtém e retorna o objeto de acordo com a posição. Retorna o objeto se a posição for válida e um objeto vazio caso contrário. Venda & Vetor::obterVenda(int posicao) { static Venda auxiliar; if (posicao >= 0 && posicao <= obterTamanhoVendas()) { return vendas[posicao]; } return auxiliar; } //Obtém e retorna a string de acordo com a posição. Retorna o objeto se a posição for válida e um objeto vazio caso contrário. string & Vetor::obterInvestidorString(int posicao) { string auxiliar; if (posicao >= 0 && posicao <= obterTamanhoInvestidorString()) { // cout << "\n"<< investidor.at(posicao); return investidor[posicao]; } return auxiliar; } //Obtém e retorna o objeto de acordo com a posição. Retorna o objeto se a posição for válida e um objeto vazio caso contrário. Investidor & Vetor::obterInvestidor(int posicao) { static Investidor auxiliar; if (posicao >= 0 && posicao <= obterTamanhoInvestidor()) { //cout << "\nteste entrou aqui " << investidores[posicao].getEstadoCivil() << "!!!!"; return investidores[posicao]; } return auxiliar; } void Vetor::limpaVectorDeObjetosInvestidores(){ investidores.clear(); }
[ "evacosta.if@gmail.com" ]
evacosta.if@gmail.com
a7b08f5ad5192b04a7af71028bfa6b8c593232fa
844a0f94745998a2b8759299c64b03ef855acb2e
/DDM2DRectangulos/EjemploDeUso/MatrizInt.hpp
cd4fe6716dcd48c88542fabce88ec30f3cdc360f
[]
no_license
antoniocarrillo69/DDM-2D
d2fe0cf196f34044d4f054225d68f660b6d4c14d
e398c18541aef51294c1724dba9f2a077a81b6d8
refs/heads/master
2020-12-31T00:01:11.191942
2017-03-29T13:16:27
2017-03-29T13:16:27
86,583,069
1
1
null
null
null
null
ISO-8859-1
C++
false
false
6,278
hpp
////////////////////////////////////////////////////////////////////////////////////////////// // Clase para el trabajar con matrices con entradas enteras // // // // Análisis y Diseño y Programación: // // // // Nombre: Antonio Carrillo Ledesma // // E-mail: acl@www.mmc.geofisica.unam.mx // // Página: http://www.mmc.geofisica.unam.mx/acl // // // // // // Este programa es software libre. Puede redistribuirlo y/o modificarlo // // bajo los términos de la Licencia Pública General de GNU según es // // publicada por la Free Software Foundation, bien de la versión 2 de // // dicha Licencia o bien (según su elección) de cualquier versión // // posterior. // // // // Este programa se distribuye con la esperanza de que sea útil, pero SIN // // NINGUNA GARANTÍA, incluso sin la garantía MERCANTIL implícita o sin // // garantizar la CONVENIENCIA PARA UN PROPÓSITO PARTICULAR. Véase la // // Licencia Pública General de GNU para más detalles. // // // // Debería haber recibido una copia de la Licencia Pública General junto // // con este programa. Si no ha sido así, escriba a la Free Software // // Foundation, Inc., en 675 Mass Ave, Cambridge, MA 02139, EEUU. // // // // // ////////////////////////////////////////////////////////////////////////////////////////////// #ifndef __MatrizInt__ #define __MatrizInt__ #include "Matriz_Base.hpp" /// Clase para el trabajar con matrices con etradas enteras /** @author Antonio Carrillo Ledesma @date primavera 2009 @version 1.0.1 @bug No hay errores conocidos */ class MatrizInt: public Matriz_Base { protected: /// Puntero al contenido de la matriz int **M; /// Libera la memoria solicitada para la matriz void liberaMemoria(void); public: /// Constructor de la clase /** Genera una matriz del tamaño expecificado por el número renglones y de columnas e inicializado al valor indicado @param ren Número de renglones de la matriz @param col Número de columnas de la matriz @param nmb Nombre de la matriz @param val Valor por omisión para inicializar la matriz */ MatrizInt(const int ren, const int col, const char *nmb, int val); /// Destructor de la clase ~MatrizInt() { liberaMemoria(); } /// Inicializa la matriz al valor val indicado /** @param val Valor por omisión para inicializar la matriz */ void inicializa(const int val); /// Retorna el valor del renglon y columna solicitado /** @param ren Renglon @param col Columna @return Valor */ int operator() (size_t ren, size_t col) { return retorna(ren,col); } #ifdef DEPURAR /// Asigna el valor indicado en el renglo y columna solicitado /** @param ren Renglon @param col Columna @param val Valor */ void asigna(const int ren, const int col, const int val); /// Retorna el valor del renglon y columna solicitado /** @param ren Renglon @param col Columna @return Valor */ int retorna(const int ren, const int col); #else /// Asigna el valor indicado en el renglo y columna solicitado /** @param ren Renglon @param col Columna @param val Valor */ inline void asigna(const int ren, const int col, const int val) { M[ren][col] = val; } /// Retorna el valor del renglon y columna solicitado /** @param ren Renglon @param col Columna @return Valor */ inline int retorna(const int ren, const int col) { return M[ren][col]; } #endif /// Convierte el contenido del arreglo a en el renglon de la matriz indicado /** @param r Renglon @param arr Arreglo de tipo int @param tam Tamaño del arreglo */ inline void asigna(int r, int *arr, int tam) { int i, t = Col < tam ? Col : tam; for (i = 0; i < t; i++) M[r][i] = arr[i]; } /// Retorna el contenido del renglon indicado en un arreglo /** @param r Renglon @param arr Arreglo de tipo int @param tam Tamaño del arreglo */ inline void retorna(int r, int *arr, int tam) { int i, t = Col < tam ? Col : tam; for (i = 0; i < t; i++) arr[i] = M[r][i]; } /// Retorna el máximo tamaño en todas las columnas que sean distintos de cero /** @return Máximo tamaño de columnas ocupadas en la matriz */ int maximoTamanoColumnaOcupado(void); /// Retorna el número de entradas distintas de cero en la matriz /** @return Número de entradas distintas de cero en la matriz */ int entradasDistintasCero(void); /// Retornal el numero de columnas del renglon indicado distintas del valor especificado /** @param ren Renglon @param val Valor @return Numero de columnas distintas del valor especificado */ int columnasDistintasDeValor(int ren, int val) { int i, sw = 0; for (i = 0; i < Col; i++) { if (M[ren][i] != val) sw ++; } return sw; } /// Visualiza la matriz void visualiza(void); }; #endif
[ "antonio@mmc.geofisica.unam.mx" ]
antonio@mmc.geofisica.unam.mx
8133dc2e1e62cfe9b37f24834b3439c1a066e195
98b6c7cedf3ab2b09f16b854b70741475e07ab64
/www.cplusplus.com-20180131/reference/istream/basic_istream/peek/peek.cpp
3d3c6d0ea902396674d1ab8d611006d0c4909d42
[]
no_license
yull2310/book-code
71ef42766acb81dde89ce4ae4eb13d1d61b20c65
86a3e5bddbc845f33c5f163c44e74966b8bfdde6
refs/heads/master
2023-03-17T16:35:40.741611
2019-03-05T08:38:51
2019-03-05T08:38:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
715
cpp
// basic_istream::peek example #include <iostream> // std::cin, std::cout #include <string> // std::string #include <cctype> // std::isdigit int main () { std::cout << "Please, enter a number or a word: "; std::cout.flush(); // ensure output is written std::cin >> std::ws; // eat up any leading white spaces std::istream::int_type c; c = std::cin.peek(); // peek character if ( c == std::char_traits<char>::eof() ) return 1; if ( std::isdigit(c) ) { int n; std::cin >> n; std::cout << "You entered the number: " << n << '\n'; } else { std::string str; std::cin >> str; std::cout << "You entered the word: " << str << '\n'; } return 0; }
[ "zhongtao.chen@yourun.com" ]
zhongtao.chen@yourun.com
48cdcc6d50359c6255f674a3590d7a203f9226cc
77f27ab61c51af866cc9165bef6961a1322b7bd2
/Source/src/GameEngine/CollisionManager.cpp
ccbb11d2872497428b8df910f5b80713670c5fd6
[]
no_license
gramanicu/egc_tema2
911d7118ce334a8de7c8b04fd4cd94d12b4da386
1096b2fc6f74e1c783c3467c7fb060aa9927bdac
refs/heads/master
2023-01-30T06:30:59.554722
2020-12-12T11:51:19
2020-12-12T11:51:19
317,217,077
0
0
null
null
null
null
UTF-8
C++
false
false
4,317
cpp
#include "CollisionManager.hpp" std::vector<int> GameEngine::CollisionManager::getCollisions(const Collider& source, std::vector<Collider*> others) { std::vector<int> collided; for (auto& other : others) { if (isCollision(source, *other)) { collided.push_back(other->getID()); } } return collided; } GameEngine::CollisionManager::CollisionManager(){} bool GameEngine::CollisionManager::isCollision(const Collider& a, const Collider& b) { using namespace GameEngine; if (a.getColliderType() == b.getColliderType()) { if (a.getColliderType() == ColliderType::BoxCollider) { // -- Box - Box colliders -- // AABB algorithm glm::vec3 firstMin, firstMax, secondMin, secondMax; glm::vec3 firstPos = a.getPosition(); glm::vec3 secondPos = b.getPosition(); glm::vec3 firstDim = a.getDimensions(); glm::vec3 secondDim = b.getDimensions(); // Compute the bounds firstMin = firstPos - firstDim * 0.5f; secondMin = secondPos - secondDim * 0.5f; firstMax = firstPos + firstDim * 0.5f; secondMax = firstPos + secondDim * 0.5f; // Check for the collision return ((firstMin.x <= secondMin.x && firstMax.x >= secondMax.x) && (firstMin.y <= secondMin.y && firstMax.y >= secondMax.y) && (firstMin.z <= secondMin.z && firstMax.z >= secondMax.z)); } else { // -- Sphere - Sphere colliders -- // Sphere collision detection algorithm glm::vec3 firstPos = a.getPosition(); glm::vec3 secondPos = b.getPosition(); double firstRad = a.getRadius(); double secondRad = b.getRadius(); // Compute the distance between the two sphere centers double distance = std::sqrt((firstPos.x - secondPos.x) * (firstPos.x - secondPos.x) + (firstPos.y - secondPos.y) * (firstPos.y - secondPos.y) + (firstPos.z - secondPos.z) * (firstPos.z - secondPos.z)); return distance < (firstRad + secondRad); } } else { if (a.getColliderType() == ColliderType::BoxCollider) { // Sphere - AABB collision detection algorithm glm::vec3 boxPos = a.getPosition(); glm::vec3 boxDim = a.getDimensions(); glm::vec3 spherePosition = b.getPosition(); // Compute the box bounds glm::vec3 min = boxPos - boxDim * 0.5f; glm::vec3 max = boxPos + boxDim * 0.5f; // Get the box closest point to the sphere glm::vec3 point = glm::vec3(std::max(min.x, std::min(spherePosition.x, max.x)), std::max(min.y, std::min(spherePosition.y, max.y)), std::max(min.z, std::min(spherePosition.z, max.z))); // Check if the point is inside the sphere float distance = std::sqrt((point.x - spherePosition.x) * (point.x - spherePosition.x) + (point.y - spherePosition.y) * (point.y - spherePosition.y) + (point.z - spherePosition.z) * (point.z - spherePosition.z)); return distance < b.getRadius(); } else { // Sphere - AABB collision detection algorithm glm::vec3 boxPos = b.getPosition(); glm::vec3 boxDim = b.getDimensions(); glm::vec3 spherePosition = a.getPosition(); // Compute the box bounds glm::vec3 min = boxPos - boxDim * 0.5f; glm::vec3 max = boxPos + boxDim * 0.5f; // Get the box closest point to the sphere glm::vec3 point = glm::vec3(std::max(min.x, std::min(spherePosition.x, max.x)), std::max(min.y, std::min(spherePosition.y, max.y)), std::max(min.z, std::min(spherePosition.z, max.z))); // Check if the point is inside the sphere float distance = std::sqrt((point.x - spherePosition.x) * (point.x - spherePosition.x) + (point.y - spherePosition.y) * (point.y - spherePosition.y) + (point.z - spherePosition.z) * (point.z - spherePosition.z)); return distance < a.getRadius(); } } }
[ "gramanicu@gmail.com" ]
gramanicu@gmail.com
4c9443839c25f42c118b8957680bdb560c10bff4
16431718fe6aa13810ad92964d2f324d8200f188
/gpuann/kernels/straightforward/simple.h
039da2f1182abd00ee6e339f38af8c1aa5ff65e8
[]
no_license
verybigbadboy/gpuann
45dbc0011f1cb435f7b9d24b04c45e94a099aeab
83203106b3ecd398da05442c76ac85ca52eb5031
refs/heads/master
2021-01-01T18:12:11.977284
2013-06-02T19:22:28
2013-06-02T19:22:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,588
h
#include <fann.h> #include <cuda.h> #include <cuda_runtime.h> #include <common/math.h> #include <string> #include <base/gpuannData.h> #include <configuration.h> template <unsigned int blockSize, unsigned int layerActivationFunction> __global__ void gpuann_fann_run_gpu_kernel(const unsigned int neuronInputCount, fann_type *inputArray, fann_type *weightsArray, fann_type *sumArray, fann_type *outputArray, fann_type layerSteepness, const unsigned int totalNeuronsCount, const unsigned int totalWeightsCount) { const unsigned int tid = threadIdx.x; const unsigned int instance = blockIdx.y; unsigned int inputIndex = tid; const unsigned int neuronIndex = blockIdx.x; const unsigned int neuronIndexInstanced = neuronIndex + totalNeuronsCount * instance; __shared__ fann_type local[blockSize]; fann_type l_summ = 0; unsigned int inputIndexInstanced; unsigned int weightIndex; unsigned int weightIndexInstanced; while(inputIndex < neuronInputCount) { inputIndexInstanced = inputIndex + totalNeuronsCount * instance; weightIndex = neuronInputCount * neuronIndex + inputIndex; weightIndexInstanced = weightIndex + totalWeightsCount * instance; l_summ += (fann_type) (inputArray[inputIndexInstanced] * weightsArray[weightIndexInstanced]); inputIndex += blockSize; } if(tid < blockSize) { local[tid] = l_summ; } __syncthreads(); // do reduction in shared mem if (blockSize >= 512) { if (tid < 256) { local[tid] = l_summ = l_summ + local[tid + 256]; } __syncthreads(); } if (blockSize >= 256) { if (tid < 128) { local[tid] = l_summ = l_summ + local[tid + 128]; } __syncthreads(); } if (blockSize >= 128) { if (tid < 64) { local[tid] = l_summ = l_summ + local[tid + 64]; } __syncthreads(); } if (tid < 32) { // now that we are using warp-synchronous programming (below) // we need to declare our shared memory volatile so that the compiler // doesn't reorder stores to it and induce incorrect behavior. volatile fann_type *smem = local; if (blockSize >= 64) { smem[tid] = l_summ = l_summ + smem[tid + 32]; } if (blockSize >= 32 && tid < 16) { smem[tid] = l_summ = l_summ + smem[tid + 16]; } if (blockSize >= 16 && tid < 8) { smem[tid] = l_summ = l_summ + smem[tid + 8]; } if (blockSize >= 8 && tid < 4) { smem[tid] = l_summ = l_summ + smem[tid + 4]; } if (blockSize >= 4 && tid < 2) { smem[tid] = l_summ = l_summ + smem[tid + 2]; } if (blockSize >= 2 && tid < 1) { smem[tid] = l_summ = l_summ + smem[tid + 1]; } } //TODO: why remove this line causes random value __syncthreads(); if (tid == 0) { fann_type neuron_sum = l_summ; neuron_sum *= layerSteepness; fann_type max_sum = 150 / layerSteepness; if(neuron_sum > max_sum) neuron_sum = max_sum; else if(neuron_sum < -max_sum) neuron_sum = -max_sum; sumArray[neuronIndexInstanced] = neuron_sum; fann_activation_switch(layerActivationFunction, neuron_sum, outputArray[neuronIndexInstanced]); } } template <unsigned int blockSize> void gpuann_fann_run_gpu_kernel_activated(unsigned int neuronInputCount, fann_type *inputArray, fann_type *weightsArray, fann_type *sumArray, fann_type *outputArray, fann_type layerSteepness, unsigned int layerActivationFunction, unsigned int neuronCount, unsigned int instanceCount, unsigned int totalNeuronsCount, unsigned int totalWeightsCount) { dim3 dimBlock(blockSize, 1, 1); dim3 dimGrid((neuronCount - 1), instanceCount, 1); #define gpuann_fann_run_gpu_kernelCase(X) case X: \ gpuann_fann_run_gpu_kernel <blockSize, X> <<<dimGrid, dimBlock>>>(neuronInputCount, inputArray, weightsArray, sumArray, outputArray, layerSteepness, totalNeuronsCount, totalWeightsCount); \ break; switch(layerActivationFunction) { gpuann_fann_run_gpu_kernelCase(0); gpuann_fann_run_gpu_kernelCase(1); gpuann_fann_run_gpu_kernelCase(2); gpuann_fann_run_gpu_kernelCase(3); gpuann_fann_run_gpu_kernelCase(4); gpuann_fann_run_gpu_kernelCase(5); gpuann_fann_run_gpu_kernelCase(6); gpuann_fann_run_gpu_kernelCase(7); gpuann_fann_run_gpu_kernelCase(8); gpuann_fann_run_gpu_kernelCase(9); gpuann_fann_run_gpu_kernelCase(10); gpuann_fann_run_gpu_kernelCase(11); gpuann_fann_run_gpu_kernelCase(12); gpuann_fann_run_gpu_kernelCase(13); gpuann_fann_run_gpu_kernelCase(14); gpuann_fann_run_gpu_kernelCase(15); } } void gpuann_fann_run_simple_implementation(unsigned int neuronInputCount, fann_type *inputArray, fann_type *weightsArray, fann_type *sumArray, fann_type *outputArray, fann_type layerSteepness, unsigned int layerActivationFunction, unsigned int neuronCount, unsigned int instanceCount, unsigned int totalNeuronsCount, unsigned int totalWeightsCount) { unsigned int threadsCount = pow2roundup(neuronInputCount) / 2; if(threadsCount < 32) threadsCount = 32; if(!minimalThreadCountPerBlockOptimization) threadsCount = 256; #define gpuann_fann_run_gpu_kernel_activatedCase(X) case X: \ gpuann_fann_run_gpu_kernel_activated <X> (neuronInputCount, inputArray, weightsArray, sumArray, outputArray, layerSteepness, layerActivationFunction, neuronCount, instanceCount, totalNeuronsCount, totalWeightsCount); \ break; switch (threadsCount) { gpuann_fann_run_gpu_kernel_activatedCase(32); gpuann_fann_run_gpu_kernel_activatedCase(64); gpuann_fann_run_gpu_kernel_activatedCase(128); default: gpuann_fann_run_gpu_kernel_activatedCase(256); } } //for neurons with < 32 inputs //always 32 threads, one input = one thread template <unsigned int blockSize, unsigned int layerActivationFunction, const unsigned int neuronInputCount> __global__ void gpuann_fann_run_multineuron_gpu_kernel( const unsigned int neuronCount, fann_type *inputArray, fann_type *weightsArray, fann_type *sumArray, fann_type *outputArray, fann_type layerSteepness, const unsigned int totalNeuronsCount, const unsigned int totalWeightsCount) { const unsigned int threadCount = blockSize; const unsigned int tid = threadIdx.x; const unsigned int instance = blockIdx.y; const unsigned int inputIndex = tid % neuronInputCount; const unsigned int inputIndexInstanced = inputIndex + totalNeuronsCount * instance; const unsigned int neuronIndexInKernel = tid / neuronInputCount; const unsigned int neuronsPerKernel = threadCount / neuronInputCount; const unsigned int neuronIndex = blockIdx.x * neuronsPerKernel + neuronIndexInKernel; const unsigned int weightIndex = neuronInputCount * neuronIndex + inputIndex; const unsigned int neuronIndexInstanced = neuronIndex + totalNeuronsCount * instance; const unsigned int weightIndexInstanced = weightIndex + totalWeightsCount * instance; __shared__ fann_type local[threadCount]; fann_type l_summ = 0; if(tid < neuronsPerKernel * neuronInputCount && neuronIndex < neuronCount) { l_summ = (fann_type) (inputArray[inputIndexInstanced] * weightsArray[weightIndexInstanced]); local[tid] = l_summ; } __syncthreads(); if (tid < neuronsPerKernel * neuronInputCount && neuronIndex < neuronCount) { volatile fann_type *smem = local; if(neuronInputCount > 16) if(inputIndex < 16) if(inputIndex + 16 < neuronInputCount) smem[tid] = l_summ = l_summ + smem[tid + 16]; if(neuronInputCount > 8) if(inputIndex < 8) if(inputIndex + 8 < neuronInputCount) smem[tid] = l_summ = l_summ + smem[tid + 8]; if(neuronInputCount > 4) if(inputIndex < 4) if(inputIndex + 4 < neuronInputCount) smem[tid] = l_summ = l_summ + smem[tid + 4]; if(neuronInputCount > 2) if(inputIndex < 2) if(inputIndex + 2 < neuronInputCount) smem[tid] = l_summ = l_summ + smem[tid + 2]; if(neuronInputCount > 1) if(inputIndex < 1) if(inputIndex + 1 < neuronInputCount) smem[tid] = l_summ = l_summ + smem[tid + 1]; } //TODO: why remove this line causes random value __syncthreads(); if (inputIndex == 0 && neuronIndex < neuronCount && neuronIndexInKernel < neuronsPerKernel) { fann_type neuron_sum = local[tid]; neuron_sum *= layerSteepness; fann_type max_sum = 150 / layerSteepness; if(neuron_sum > max_sum) neuron_sum = max_sum; else if(neuron_sum < -max_sum) neuron_sum = -max_sum; sumArray[neuronIndexInstanced] = neuron_sum; fann_activation_switch(layerActivationFunction, neuron_sum, outputArray[neuronIndexInstanced]); } } template <unsigned int neuronInputCount> void gpuann_fann_run_small_neurons_implementation_neuronInput( fann_type * inputArray, fann_type * weightsArray, fann_type *sumArray, fann_type * outputArray, fann_type layerSteepness, unsigned int layerActivationFunction, unsigned int neuronCount, unsigned int instanceCount, unsigned int totalNeuronsCount, unsigned int totalWeightsCount) { neuronCount--; //bias const unsigned int blockSize = 256; //just for shared memory; unsigned int threadNeeded = pow2roundup(neuronInputCount * neuronCount); if(threadNeeded > 256) threadNeeded = 256; if(!minimalThreadCountPerBlockOptimization) threadNeeded = 256; const unsigned int neuronsPerBlock = threadNeeded / neuronInputCount; const unsigned int blocksNeeded = neuronCount / neuronsPerBlock + 1; dim3 dimBlock(threadNeeded, 1, 1); dim3 dimGrid(blocksNeeded, instanceCount, 1); // TODO create bias if #define gpuann_fann_run_multineuron_gpu_kernelCase(X) case X: \ gpuann_fann_run_multineuron_gpu_kernel <blockSize, X, neuronInputCount> <<<dimGrid, dimBlock>>>(neuronCount, inputArray, weightsArray, sumArray, outputArray, layerSteepness, totalNeuronsCount, totalWeightsCount); \ break; switch(layerActivationFunction) { gpuann_fann_run_multineuron_gpu_kernelCase(0); gpuann_fann_run_multineuron_gpu_kernelCase(1); gpuann_fann_run_multineuron_gpu_kernelCase(2); gpuann_fann_run_multineuron_gpu_kernelCase(3); gpuann_fann_run_multineuron_gpu_kernelCase(4); gpuann_fann_run_multineuron_gpu_kernelCase(5); gpuann_fann_run_multineuron_gpu_kernelCase(6); gpuann_fann_run_multineuron_gpu_kernelCase(7); gpuann_fann_run_multineuron_gpu_kernelCase(8); gpuann_fann_run_multineuron_gpu_kernelCase(9); gpuann_fann_run_multineuron_gpu_kernelCase(10); gpuann_fann_run_multineuron_gpu_kernelCase(11); gpuann_fann_run_multineuron_gpu_kernelCase(12); gpuann_fann_run_multineuron_gpu_kernelCase(13); gpuann_fann_run_multineuron_gpu_kernelCase(14); gpuann_fann_run_multineuron_gpu_kernelCase(15); } } void gpuann_fann_run_small_neurons_implementation(unsigned int neuronInputCount, fann_type * inputArray, fann_type * weightsArray, fann_type *sumArray, fann_type * outputArray, fann_type layerSteepness, unsigned int layerActivationFunction, unsigned int neuronCount, unsigned int instanceCount, unsigned int totalNeuronsCount, unsigned int totalWeightsCount) { #define gpuann_fann_run_small_neurons_implementation_neuronInputCase(X) case X: \ gpuann_fann_run_small_neurons_implementation_neuronInput <X> (inputArray, weightsArray, sumArray, outputArray, layerSteepness, layerActivationFunction, neuronCount, instanceCount, totalNeuronsCount, totalWeightsCount); \ break; switch(neuronInputCount) { gpuann_fann_run_small_neurons_implementation_neuronInputCase(1); gpuann_fann_run_small_neurons_implementation_neuronInputCase(2); gpuann_fann_run_small_neurons_implementation_neuronInputCase(3); gpuann_fann_run_small_neurons_implementation_neuronInputCase(4); gpuann_fann_run_small_neurons_implementation_neuronInputCase(5); gpuann_fann_run_small_neurons_implementation_neuronInputCase(6); gpuann_fann_run_small_neurons_implementation_neuronInputCase(7); gpuann_fann_run_small_neurons_implementation_neuronInputCase(8); gpuann_fann_run_small_neurons_implementation_neuronInputCase(9); gpuann_fann_run_small_neurons_implementation_neuronInputCase(10); gpuann_fann_run_small_neurons_implementation_neuronInputCase(11); gpuann_fann_run_small_neurons_implementation_neuronInputCase(12); gpuann_fann_run_small_neurons_implementation_neuronInputCase(13); gpuann_fann_run_small_neurons_implementation_neuronInputCase(14); gpuann_fann_run_small_neurons_implementation_neuronInputCase(15); gpuann_fann_run_small_neurons_implementation_neuronInputCase(16); gpuann_fann_run_small_neurons_implementation_neuronInputCase(17); gpuann_fann_run_small_neurons_implementation_neuronInputCase(18); gpuann_fann_run_small_neurons_implementation_neuronInputCase(19); gpuann_fann_run_small_neurons_implementation_neuronInputCase(20); gpuann_fann_run_small_neurons_implementation_neuronInputCase(21); gpuann_fann_run_small_neurons_implementation_neuronInputCase(22); gpuann_fann_run_small_neurons_implementation_neuronInputCase(23); gpuann_fann_run_small_neurons_implementation_neuronInputCase(24); gpuann_fann_run_small_neurons_implementation_neuronInputCase(25); gpuann_fann_run_small_neurons_implementation_neuronInputCase(26); gpuann_fann_run_small_neurons_implementation_neuronInputCase(27); gpuann_fann_run_small_neurons_implementation_neuronInputCase(28); gpuann_fann_run_small_neurons_implementation_neuronInputCase(29); gpuann_fann_run_small_neurons_implementation_neuronInputCase(30); gpuann_fann_run_small_neurons_implementation_neuronInputCase(31); } } void gpuann_fann_run_select_best_implementation(unsigned int neuronInputCount, fann_type * inputArray, fann_type * weightsArray, fann_type *sumArray, fann_type * outputArray, fann_type layerSteepness, unsigned int layerActivationFunction, unsigned int neuronCount, unsigned int instanceCount, unsigned int totalNeuronsCount, unsigned int totalWeightsCount) { if(neuronInputCount <= 32 && straightforwardSmallNeuronImplementationEnabled) { gpuann_fann_run_small_neurons_implementation(neuronInputCount, inputArray, weightsArray, sumArray, outputArray, layerSteepness, layerActivationFunction, neuronCount, instanceCount, totalNeuronsCount, totalWeightsCount); } else { gpuann_fann_run_simple_implementation(neuronInputCount, inputArray, weightsArray, sumArray, outputArray, layerSteepness, layerActivationFunction, neuronCount, instanceCount, totalNeuronsCount, totalWeightsCount); } } void gpuann_fann_run_implementation(gpuann &data) { const fann * ann = data._fann; struct fann_neuron *neuronsArray = ann->first_layer->first_neuron; struct fann_layer *lastLayer = ann->last_layer; for(struct fann_layer *layerIt = ann->first_layer + 1; layerIt != lastLayer; layerIt++) { struct fann_neuron * lastNeuron = layerIt->last_neuron; struct fann_neuron * neuronIt = layerIt->first_neuron; unsigned int neuronsCount = lastNeuron - neuronIt; fann_type layerSteepness = neuronIt->activation_steepness; unsigned int layerActivationFunction = neuronIt->activation_function; unsigned int layerNeuronInputCount = neuronIt->last_con - neuronIt->first_con; unsigned int inputNeuronArrayShift = (layerIt - 1)->first_neuron - neuronsArray; unsigned int currentNeuronArrayShift = neuronIt - neuronsArray; unsigned int weightsArrayShift = neuronIt->first_con; gpuann_fann_run_select_best_implementation(layerNeuronInputCount, &(data.d_valuesArray[inputNeuronArrayShift]), &(data.d_weightsArray[weightsArrayShift]), &(data.d_sumArray[currentNeuronArrayShift]), &(data.d_valuesArray[currentNeuronArrayShift]), layerSteepness, layerActivationFunction, neuronsCount, data._instanceCount, data._neuronsCountPerInstance, data._weightsCountPerInstance); } }
[ "verybigbadboy@gmail.com" ]
verybigbadboy@gmail.com
708a123a950eba6188debe460025f2f2cc893cdb
a4cafdae890bbbc0b5efb1ffd8a4f1fd4267dcc1
/Animations/CaptainAmericaAnimations/CaptainAmericaWeakAirPunchAnimation.h
f24d3030592148c0a752f71271b7cb3fc4ee6171
[]
no_license
tomiir/taller-marvel-capcom
5aa8047350e67b2702d3d1a5ffa370c99f1ce5d0
fcfea6e474d50d273bcdf16f6f329992fea7e78a
refs/heads/master
2020-04-28T19:53:31.238073
2019-06-29T20:24:17
2019-06-29T20:24:17
175,525,464
1
0
null
null
null
null
UTF-8
C++
false
false
474
h
// // Created by arielpm on 12/06/19. // #ifndef TALLER_MARVEL_CAPCOM_CAPTAINAMERICAWEAKAIRPUNCHANIMATION_H #define TALLER_MARVEL_CAPCOM_CAPTAINAMERICAWEAKAIRPUNCHANIMATION_H #include "../Animation.h" class CaptainAmericaWeakAirPunchAnimation: public Animation{ public: CaptainAmericaWeakAirPunchAnimation(); ~CaptainAmericaWeakAirPunchAnimation() = default; void init() override; }; #endif //TALLER_MARVEL_CAPCOM_CAPTAINAMERICAWEAKAIRPUNCHANIMATION_H
[ "ariel.piro@hotmail.com" ]
ariel.piro@hotmail.com
ec4866e8d15b0ef392af98a9f57bf493a17b95d9
e550dd154304a163465a67e2de621b17a2327749
/R732div2/a.cpp
40e5daa2b4f3e2b5af2e49a096506a2d9418feba
[]
no_license
1000ms/Codeforces-Solutions
ab7fffba0292994141c5cff0becb851dffc16584
615bb09e29dd38386c63dfe7312b16fa04c6a7b5
refs/heads/master
2023-06-19T11:35:50.567795
2021-07-14T10:33:46
2021-07-14T10:33:46
341,239,595
2
0
null
null
null
null
UTF-8
C++
false
false
1,257
cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define OJ \ freopen("input.txt", "r", stdin); \ freopen("output.txt", "w", stdout); ll bp(ll a,ll b,ll mod=LONG_LONG_MAX){ a%=mod; ll res=1; while(b>0){ if(b&1) res=res*a%mod; a=a*a%mod; b/=2; } return res; } void solve(){ int n;cin>>n; vector<int> a(n),b(n); for(int i=0;i<n;i++){ cin>>a[i]; } for(auto &it:b) cin>>it; int sum=0; for(int i=0;i<n;i++){ a[i]=a[i]-b[i]; sum+=a[i]; } if(sum!=0){ cout<<-1<<"\n"; return; } vector<pair<int,int>> pos,neg,ans; int cnt=0; for(int i=0;i<n;i++){ if(a[i]<0) neg.emplace_back(a[i],i); else if(a[i]>0) pos.emplace_back(a[i],i); } int l=0,r=0; while(l<(int)pos.size() && r<(int)neg.size()){ cnt++; ans.emplace_back(pos[l].second+1,neg[r].second+1); pos[l].first-=1,neg[r].first+=1; if(pos[l].first==0) ++l; if(neg[r].first==0) ++r; } cout<<cnt<<"\n"; for(auto x:ans) cout<<x.first<<" "<<x.second<<"\n"; } int main(){ cin.tie(0);ios_base::sync_with_stdio(0); int ttt=1; cin>>ttt; for(int rep=1;rep<=ttt;rep++){ solve(); } }
[ "utnoob420@gmail.com" ]
utnoob420@gmail.com
e336eb53dd9d1eaa079b84666391c2fb92e65e31
1f2b2037c988af75f0b2735c29e1a8356bb44bfb
/final_task/ConcurrencySimulator/ConcurrencySimulator/Program.cpp
e6451c93af1737849a384727fc0c61d26f53ecac
[]
no_license
Anton7393/final_task
ec2d3e553f1e6603b58f00f300d0c989fb44f79c
18477b227a945a54653125ebfd85196847ec7da4
refs/heads/master
2021-01-20T22:22:38.962527
2016-06-27T07:46:47
2016-06-27T07:46:47
61,700,827
0
0
null
null
null
null
UTF-8
C++
false
false
1,020
cpp
#include "stdafx.h" #include "Program.h" int Program::mNextId = 1; Program::Program() : mID(mNextId) , mStatus(Status::ready) , mRemainigTime(0) { ++mNextId; } void Program::print(const std::map<char, int> & _variableContainer, char _name) { std::cout << mID << " : " << _variableContainer.at(_name) << std::endl; } void Program::assignment(std::map<char, int> & _variableContainer, char _name, int _value) { _variableContainer.at(_name) = _value; } void Program::lock() { mStatus = Status::blocked; } void Program::unlock() { mStatus = Status::ready; } void Program::end() { mStatus = Status::over; } int Program::getId() { return mID; } Status Program::getStatus() { return mStatus; } void Program::setStatus(const Status & _status) { mStatus = _status; } int Program::getTime() { return mRemainigTime; } void Program::setTime(int _time) { mRemainigTime = _time; } void Program::addTime(int _time) { mRemainigTime += _time; } void Program::spendTime(int _time) { mRemainigTime -= _time; }
[ "abaddon7393@gmail.com" ]
abaddon7393@gmail.com
f51581b5300ea9af11b3fbff93f761dc61101e71
50e1f49ef3e6dac9b7bed410aab8de696a9571ad
/difficulty_0900/0337A_puzzles.cpp
0f3f0bfc450712a43f60a874154260cc8596b762
[]
no_license
johnescobia/codeforces
88c155f67df60c2d211dff6965ff039b0d07a4c6
c981ea33afb2eab06a4dae55b3a748e6e97c48b2
refs/heads/main
2023-01-29T14:33:10.918221
2020-12-14T13:33:22
2020-12-14T13:33:22
312,840,460
0
0
null
null
null
null
UTF-8
C++
false
false
565
cpp
// https://codeforces.com/problemset/problem/337/A #include <iostream> #include <algorithm> int main() { std::ios::sync_with_stdio(false); std::cin.tie(NULL); int student, puzzle; std::cin >> student >> puzzle; int arr[puzzle]; for(int i=0; i<puzzle; i++) std::cin >> arr[i]; std::sort(arr, arr + puzzle); int minRange = arr[student-1] - arr[0]; int currentRange; for(int i=0; i<=puzzle-student; i++) { currentRange = arr[i+student-1] - arr[i]; minRange = std::min(minRange, currentRange); } std::cout << minRange; return 0; }
[ "escobiajohn@gmail.com" ]
escobiajohn@gmail.com
1f1db1ea60a959b8bd5609d15c1d51f59b3a84ce
dd949f215d968f2ee69bf85571fd63e4f085a869
/tools/loquendo-ice/trunk/src/audiosource/RAWFileAudioSource.h
aee795ac3b2401130098bb41078e2a007485cafe
[]
no_license
marc-hanheide/cogx
a3fd395805f1b0ad7d713a05b9256312757b37a9
cb9a9c9cdfeba02afac6a83d03b7c6bb778edb95
refs/heads/master
2022-03-16T23:36:21.951317
2013-12-10T23:49:07
2013-12-10T23:49:07
219,460,352
1
2
null
null
null
null
UTF-8
C++
false
false
1,719
h
#ifndef RAWFILEAUDIOSOURCE_H__ #define RAWFILEAUDIOSOURCE_H__ 1 // ---------------------------------------------------------------------------- // Copyright (C) 2010-2011 DFKI GmbH Talking Robots // Miroslav Janicek (miroslav.janicek@dfki.de) // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 2.1 of // the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA. // ---------------------------------------------------------------------------- #include <cstdlib> // required by LoqASR.h #include <LoqASR.h> #include <string> #include <iostream> #include <fstream> #include <pulse/simple.h> #include <log4cxx/logger.h> #include "AudioSource.h" class RAWFileAudioSource : public AudioSource { public: RAWFileAudioSource(log4cxx::LoggerPtr logger, const std::string & path); virtual ~RAWFileAudioSource(); virtual void start(); virtual void stop(); virtual lasrxResultType registerSource(void * instance); virtual lasrxResultType unregisterSource(); log4cxx::LoggerPtr logger; size_t buffer_size; uint8_t * buffer; std::ifstream file; private: std::string path; }; #endif
[ "marc@hanheide.net" ]
marc@hanheide.net
4a707eb3fcec958f7352771e1473ab56e29f7024
564aa35e8a29935c67d1a9a47545dee976551958
/C++/Containers/associative Containers/multimap.cpp
1be15fb694e2fae5411ed068046d3070ea521551
[ "MIT" ]
permissive
alchemz/interview-algorithm-questions
76f799f8d0a0da1fed716c2a47bb1330b3fc5994
34039fc0db2766cf7531668a9947779a3835ebf5
refs/heads/master
2021-05-05T06:58:33.742919
2018-03-10T06:58:12
2018-03-10T06:58:12
118,840,845
0
0
null
null
null
null
UTF-8
C++
false
false
443
cpp
#include<iostream> #include<map> using namespace std; int main() { multimap<char, int> mymultimap; mymultimap.insert(pair<char, int>('a',1)); mymultimap.insert(pair<char, int>('b',2)); mymultimap.insert(pair<char,int>('c',20)); mymultimap.insert(pair<char,int>('d',100)); //show content for(multimap<char,int>::iterator it = mymultimap.begin(); it != mymultimap.end(); it++) cout<<" "<<(*it).first <<" "<<(*it).second; return 0; }
[ "alchemxz@gmail.com" ]
alchemxz@gmail.com
b8bc5d0d664bb14da2c08e66fc857ab4952b91b3
152c4845d2cc4d78d2cf6841843094fadf420ac1
/UsbClient2ClientBridgeArduino/UsbClient2ClientBridgeArduino.ino
0f9170877e2d56bc745d87d456f4bff18c3e6646
[]
no_license
pragun/mouse-daw-controller
7c8fb5d20a40e4109bb473597fbd1b0258626a28
ddb04b4580d702f680ae962121f129f97813de5f
refs/heads/master
2020-05-15T15:00:53.024821
2019-04-20T04:06:05
2019-04-20T04:06:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,610
ino
#include "Keyboard.h" //#include "Mouse.h"> #include <Mouse_Alt.h> #include "MIDIUSB.h" #include <NeoHWSerial.h> #define NEWLINE 10 #define RX_BUF_SIZE 8 const byte RX_Interrupt_Pin = 7; //This is going to be our poor man's software interrupt pin number uint8_t rxBuf1[RX_BUF_SIZE] = {}; uint8_t rxBuf2[RX_BUF_SIZE] = {}; uint8_t rxBuf_i[2] = {}; uint8_t rx_buf_j = 0; uint8_t *rx_buf[2]; uint8_t rxing_size = 0; uint8_t rxed_size = 0; uint8_t* rx_buf_to_proc; uint8_t rx_buf_k = 0; uint8_t msg_handler_id = 0; typedef void (* eventFP)(uint8_t*); eventFP MsgHandlers[3] = {&sendMouse,&sendKeyboard,&sendMIDIData}; /* * Mouse packet byte definitions * packet = [a][b][c][d][e][f] * a = 'a', literally the character a, makes sure that sendMouse is selected * b = 0bxyz[b5][b4][b3][b2][b1] <x:1 momentary click>, <y:1 press> <z:1 release>, needless to say only one can be active at a time * b1-5, denote which button(s), the <x,y,z> bits talk about * c = signed_uint8_t carrying del X * d = signed_uint8_t carrying del Y * e = signed_uint8_t carrying del wheelX * f = signed_uint8_t carrying del wheelY */ /* * Midi packet byte definition * packet = [a][b][c][d][e] * a = 'c', literally the character c * b = Header byte, basically c(status byte) >> 4 * c = status byte for midi * d = data 1 byte for midi * e = data 2 byte for midi */ /* * Keyboard packet byte definition * packet = [a] [b] [c] * a = 'b', literally the character b * b = the ascii code for the key to be pressed/released * c = 0 for release, 1 for press */ typedef struct { uint8_t midi_selector; midiEventPacket_t midi_event; //This follows the arduino MIDIUSB Library specification // As Arduino example https://www.arduino.cc/en/Tutorial/MidiDevice says // First parameter is the event type (0x09 = note on, 0x08 = note off). // Second parameter is note-on/note-off, combined with the channel. // Channel can be anything between 0-15. Typically reported to the user as 1-16. // Third parameter is the note number (48 = middle C). // Fourth parameter is the velocity (64 = normal, 127 = fastest). } midiDataStruct; midiDataStruct *midiData = NULL; typedef struct { uint8_t mouse_selector; uint8_t button; uint8_t delx; uint8_t dely; uint8_t del_wx; uint8_t del_wy; } mouseDataStruct; mouseDataStruct *mouseData = NULL; typedef struct { uint8_t keyboard_selector; char key_ascii; uint8_t press_release; } keyboardDataStruct; keyboardDataStruct *keyboardData = NULL; void setup() { // Fix the dual receive buffers for data received over serial rx_buf[0] = &rxBuf1[0]; rx_buf[1] = &rxBuf2[0]; pinMode(RX_Interrupt_Pin, OUTPUT); digitalWrite(RX_Interrupt_Pin, 0); attachInterrupt(digitalPinToInterrupt(RX_Interrupt_Pin), handleCMD, RISING); NeoSerial1.begin(1000000); Serial.begin(9600); // initialize control over the keyboard: Keyboard.begin(); Mouse.begin(); NeoSerial1.attachInterrupt( handleRxChar ); Serial.println("Setup completed MIDIUsb, MouseUSB, KeyboardUSB"); } static void handleCMD(){ //Serial.println("Command handler.."); rx_buf_k = (rx_buf_j + 1) % 2; rx_buf_to_proc = rx_buf[rx_buf_k]; //Serial.println((char*) rx_buf_to_proc); msg_handler_id = rx_buf_to_proc[0]-97; //Serial.println((char) msg_handler_id,DEC); if ((msg_handler_id >= 0)&&(msg_handler_id <=3)){ MsgHandlers[msg_handler_id](rx_buf_to_proc); } digitalWrite(RX_Interrupt_Pin, 0); } void sendMouse(uint8_t* rx_buf){ //Serial.println("SendMouse"); mouseData = (mouseDataStruct *) rx_buf; //Serial.println(mouseData->mouse_selector); //Serial.println(mouseData->button); //Serial.println(mouseData->delx); //Serial.println(mouseData->dely); //Serial.println(mouseData->del_wx); //Serial.println(mouseData->del_wy); switch(mouseData->button & 0b11100000){ case 0b00000000: break; case 0b10000000: Mouse.buttons(mouseData->button & 0b00011111); return; case 0b01000000: Mouse.press(mouseData->button & 0b00011111); return; case 0b00100000: Mouse.release(mouseData->button & 0b00011111); return; } Mouse.move(mouseData->delx,mouseData->dely,mouseData->del_wx); } void sendKeyboard(uint8_t* rx_buf){ Serial.println("SendKeyboard"); Serial.println(keyboardData->key_ascii); Serial.println(keyboardData->press_release); keyboardData = (keyboardDataStruct *) rx_buf; if (keyboardData->press_release == 0){ Keyboard.release(keyboardData->key_ascii); }else{ Keyboard.press(keyboardData->key_ascii); } //Mouse.click(MOUSE_RIGHT); } void sendMIDIData(uint8_t* rx_buf){ //Serial.println("SendMIDIData"); midiData = (midiDataStruct *) rx_buf; //Serial.println(midiData->midi_event.header); //Serial.println(midiData->midi_event.byte1); //Serial.println(midiData->midi_event.byte2); //Serial.println(midiData->midi_event.byte3); MidiUSB.sendMIDI(midiData->midi_event); MidiUSB.flush(); } static void handleRxChar( uint8_t c ) { //Serial.print("I received: "); //Serial.println(c, DEC); if(c == NEWLINE){ rx_buf[rx_buf_j][rxing_size] = 0; //Serial.print("NewLine Received -- Swapping. Received: "); //Serial.print((char*) rx_buf[rx_buf_j]); rx_buf_j = (rx_buf_j+1) % 2; rxed_size = rxing_size; rxing_size = 0; //Serial.print("RX BUF J"); //Serial.print(rx_buf_j,DEC); //Serial.print("RXED Size "); //Serial.print(rxed_size,DEC); digitalWrite(RX_Interrupt_Pin, 1); }else{ rx_buf[rx_buf_j][rxing_size] = c; rxing_size ++; rxing_size = rxing_size % RX_BUF_SIZE; //Serial.print((char*) rx_buf[rx_buf_j]); } } void loop() { /* if (NeoSerial1.available() > 0) { // read the incoming byte: incomingByte = NeoSerial1.read(); // say what you got: Serial.print("I received: "); Serial.println(incomingByte, DEC); } */ // check for incoming serial data: /* if (Serial.available() > 0) { // read incoming serial data: char inChar = Serial.read(); // Type the next ASCII value from what you received: Keyboard.write(inChar + 1); } Serial.write("testing..\n"); Serial1.write("From the other side...\n"); */ delay(1); }
[ "pragun.goyal@gmail.com" ]
pragun.goyal@gmail.com
9d477e5899e336fc8e770fd0664abdbef91c62b1
4d49d4d59c9517fe99884cd69ad88644265c6755
/week6/Group4/boj15815_ei6540.cpp
791499934a304f1aa79e3c79d63292bd4200a46c
[]
no_license
all1m-algorithm-study/2021-1-Algorithm-Study
3f34655dc0a3d8765143f4230adaa96055d13626
73c7cac1824827cb6ed352d49c0ead7003532a35
refs/heads/main
2023-06-03T18:45:28.852381
2021-06-11T06:28:44
2021-06-11T06:28:44
348,433,854
8
16
null
2021-06-11T06:28:45
2021-03-16T17:23:37
Python
UTF-8
C++
false
false
923
cpp
#include <iostream> #include <string> #include <stack> #include <iomanip> using namespace std; void init() { ios_base::sync_with_stdio(false); cin.tie(NULL); } void solve() { string postfix; cin >> postfix; // 후위표기식은 스택을 주로 사용한다. stack<double> s; for (char ch : postfix) { // ch가 문자인 경우, 숫자를 계산해야함에 주의 // 답이 소수점 둘째자리까지 나올 수 있음 if (ch >= '0' && ch <= '9') { s.push(ch - '0'); } // ch가 연산자인 경우, 스택 규칙에 따라 op2가 먼저 pop됨 else { double op2 = s.top(); s.pop(); double op1 = s.top(); s.pop(); if (ch == '+') { s.push(op1 + op2); } else if (ch == '-') { s.push(op1 - op2); } else if (ch == '*') { s.push(op1 * op2); } else if (ch == '/') { s.push(op1 / op2); } } } cout << s.top(); } int main() { init(); solve(); }
[ "ei654028@gmail.com" ]
ei654028@gmail.com
79ea73404cbd1d2aea18af73ea98aa5e05315925
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Source/ThirdParty/OpenSubdiv/3.0.2/opensubdiv/vtr/level.h
2d3169e10f99f318a3af3afef2ca308367227303
[ "MIT", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
31,134
h
// // Copyright 2014 DreamWorks Animation LLC. // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #ifndef OPENSUBDIV3_VTR_LEVEL_H #define OPENSUBDIV3_VTR_LEVEL_H #include "../version.h" #include "../sdc/types.h" #include "../sdc/crease.h" #include "../sdc/options.h" #include "../vtr/types.h" #include <algorithm> #include <vector> #include <cassert> #include <cstring> namespace OpenSubdiv { namespace OPENSUBDIV_VERSION { namespace Vtr { namespace internal { class Refinement; class TriRefinement; class QuadRefinement; class FVarRefinement; class FVarLevel; // // Level: // A refinement level includes a vectorized representation of the topology // for a particular subdivision level. The topology is "complete" in that any // level can be used as the base level of another subdivision hierarchy and can // be considered a complete mesh independent of its ancestors. It currently // does contain a "depth" member -- as some inferences can then be made about // the topology (i.e. all quads or all tris if not level 0). // // This class is intended for private use within the library. There are still // opportunities to specialize levels -- e.g. those supporing N-sided faces vs // those are are purely quads or tris -- so we prefer to insulate it from public // access. // // The represenation of topology here is to store six topological relationships // in tables of integers. Each is stored in its own array(s) so the result is // a SOA representation of the topology. The six relations are: // // - face-verts: vertices incident/comprising a face // - face-edges: edges incident a face // - edge-verts: vertices incident/comprising an edge // - edge-faces: faces incident an edge // - vert-faces: faces incident a vertex // - vert-edges: edges incident a vertex // // There is some redundancy here but the intent is not that this be a minimal // represenation, the intent is that it be amenable to refinement. Classes in // the Far layer essentially store 5 of these 6 in a permuted form -- we add // the face-edges here to simplify refinement. // class Level { public: // // Simple nested types to hold the tags for each component type -- some of // which are user-specified features (e.g. whether a face is a hole or not) // while others indicate the topological nature of the component, how it // is affected by creasing in its neighborhood, etc. // // Most of these properties are passed down to child components during // refinement, but some -- notably the designation of a component as semi- // sharp -- require re-determination as sharpnes values are reduced at each // level. // struct VTag { VTag() { } // When cleared, the VTag ALMOST represents a smooth, regular, interior // vertex -- the Type enum requires a bit be explicitly set for Smooth, // so that must be done explicitly if desired on initialization. void clear() { std::memset(this, 0, sizeof(VTag)); } typedef unsigned short VTagSize; VTagSize _nonManifold : 1; // fixed VTagSize _xordinary : 1; // fixed VTagSize _boundary : 1; // fixed VTagSize _corner : 1; // fixed VTagSize _infSharp : 1; // fixed VTagSize _semiSharp : 1; // variable VTagSize _semiSharpEdges : 1; // variable VTagSize _rule : 4; // variable when _semiSharp VTagSize _incomplete : 1; // variable for sparse refinement // On deck -- coming soon... //VTagSize _constSharp : 1; // variable when _semiSharp //VTagSize _hasEdits : 1; // variable //VTagSize _editsApplied : 1; // variable }; struct ETag { ETag() { } // When cleared, the ETag represents a smooth, manifold, interior edge void clear() { std::memset(this, 0, sizeof(ETag)); } typedef unsigned char ETagSize; ETagSize _nonManifold : 1; // fixed ETagSize _boundary : 1; // fixed ETagSize _infSharp : 1; // fixed ETagSize _semiSharp : 1; // variable }; struct FTag { FTag() { } void clear() { std::memset(this, 0, sizeof(FTag)); } typedef unsigned char FTagSize; FTagSize _hole : 1; // fixed // On deck -- coming soon... //FTagSize _hasEdits : 1; // variable }; VTag getFaceCompositeVTag(ConstIndexArray & faceVerts) const; ETag getFaceCompositeETag(ConstIndexArray & faceEdges) const; public: Level(); ~Level(); // Simple accessors: int getDepth() const { return _depth; } int getNumVertices() const { return _vertCount; } int getNumFaces() const { return _faceCount; } int getNumEdges() const { return _edgeCount; } // More global sizes may prove useful... int getNumFaceVerticesTotal() const { return (int) _faceVertIndices.size(); } int getNumFaceEdgesTotal() const { return (int) _faceEdgeIndices.size(); } int getNumEdgeVerticesTotal() const { return (int) _edgeVertIndices.size(); } int getNumEdgeFacesTotal() const { return (int) _edgeFaceIndices.size(); } int getNumVertexFacesTotal() const { return (int) _vertFaceIndices.size(); } int getNumVertexEdgesTotal() const { return (int) _vertEdgeIndices.size(); } int getMaxValence() const { return _maxValence; } int getMaxEdgeFaces() const { return _maxEdgeFaces; } // Methods to access the relation tables/indices -- note that for some relations // (i.e. those where a component is "contained by" a neighbor, or more generally // when the neighbor is a simplex of higher dimension) we store an additional // "local index", e.g. for the case of vert-faces if one of the faces F[i] is // incident a vertex V, then L[i] is the "local index" in F[i] of vertex V. // Once have only quads (or tris), this local index need only occupy two bits // and could conceivably be packed into the same integer as the face index, but // for now, given the need to support faces of potentially high valence we'll // us an 8- or 16-bit integer. // // Methods to access the six topological relations: ConstIndexArray getFaceVertices(Index faceIndex) const; ConstIndexArray getFaceEdges(Index faceIndex) const; ConstIndexArray getEdgeVertices(Index edgeIndex) const; ConstIndexArray getEdgeFaces(Index edgeIndex) const; ConstIndexArray getVertexFaces(Index vertIndex) const; ConstIndexArray getVertexEdges(Index vertIndex) const; ConstLocalIndexArray getEdgeFaceLocalIndices(Index edgeIndex) const; ConstLocalIndexArray getVertexFaceLocalIndices(Index vertIndex) const; ConstLocalIndexArray getVertexEdgeLocalIndices(Index vertIndex) const; // Replace these with access to sharpness buffers/arrays rather than elements: float getEdgeSharpness(Index edgeIndex) const; float getVertexSharpness(Index vertIndex) const; Sdc::Crease::Rule getVertexRule(Index vertIndex) const; Index findEdge(Index v0Index, Index v1Index) const; // Holes void setFaceHole(Index faceIndex, bool b); bool isFaceHole(Index faceIndex) const; // Face-varying Sdc::Options getFVarOptions(int channel) const; int getNumFVarChannels() const { return (int) _fvarChannels.size(); } int getNumFVarValues(int channel) const; ConstIndexArray getFaceFVarValues(Index faceIndex, int channel) const; FVarLevel & getFVarLevel(int channel) { return *_fvarChannels[channel]; } FVarLevel const & getFVarLevel(int channel) const { return *_fvarChannels[channel]; } // Manifold/non-manifold tags: void setEdgeNonManifold(Index edgeIndex, bool b); bool isEdgeNonManifold(Index edgeIndex) const; void setVertexNonManifold(Index vertIndex, bool b); bool isVertexNonManifold(Index vertIndex) const; // General access to all component tags: VTag const & getVertexTag(Index vertIndex) const { return _vertTags[vertIndex]; } ETag const & getEdgeTag(Index edgeIndex) const { return _edgeTags[edgeIndex]; } FTag const & getFaceTag(Index faceIndex) const { return _faceTags[faceIndex]; } VTag & getVertexTag(Index vertIndex) { return _vertTags[vertIndex]; } ETag & getEdgeTag(Index edgeIndex) { return _edgeTags[edgeIndex]; } FTag & getFaceTag(Index faceIndex) { return _faceTags[faceIndex]; } public: // Debugging aides: enum TopologyError { TOPOLOGY_MISSING_EDGE_FACES=0, TOPOLOGY_MISSING_EDGE_VERTS, TOPOLOGY_MISSING_FACE_EDGES, TOPOLOGY_MISSING_FACE_VERTS, TOPOLOGY_MISSING_VERT_FACES, TOPOLOGY_MISSING_VERT_EDGES, TOPOLOGY_FAILED_CORRELATION_EDGE_FACE, TOPOLOGY_FAILED_CORRELATION_FACE_VERT, TOPOLOGY_FAILED_CORRELATION_FACE_EDGE, TOPOLOGY_FAILED_ORIENTATION_INCIDENT_EDGE, TOPOLOGY_FAILED_ORIENTATION_INCIDENT_FACE, TOPOLOGY_FAILED_ORIENTATION_INCIDENT_FACES_EDGES, TOPOLOGY_DEGENERATE_EDGE, TOPOLOGY_NON_MANIFOLD_EDGE, TOPOLOGY_INVALID_CREASE_EDGE, TOPOLOGY_INVALID_CREASE_VERT }; static char const * getTopologyErrorString(TopologyError errCode); typedef void (* ValidationCallback)(TopologyError errCode, char const * msg, void const * clientData); bool validateTopology(ValidationCallback callback=0, void const * clientData=0) const; void print(const Refinement* parentRefinement = 0) const; public: // High-level topology queries -- these may be moved elsewhere: bool isSingleCreasePatch(Index face, float* sharpnessOut=NULL, int* rotationOut=NULL) const; // // When gathering "patch points" we may want the indices of the vertices or the corresponding // FVar values for a particular channel. Both are represented and equally accessible within // the faces, so we allow all to be returned through these methods. Setting the optional FVar // channel to -1 will retrieve indices of vertices instead of FVar values: // int gatherQuadLinearPatchPoints(Index fIndex, Index patchPoints[], int rotation = 0, int fvarChannel = -1) const; int gatherQuadRegularInteriorPatchPoints(Index fIndex, Index patchPoints[], int rotation = 0, int fvarChannel = -1) const; int gatherQuadRegularBoundaryPatchPoints(Index fIndex, Index patchPoints[], int boundaryEdgeInFace, int fvarChannel = -1) const; int gatherQuadRegularCornerPatchPoints( Index fIndex, Index patchPoints[], int cornerVertInFace, int fvarChannel = -1) const; int gatherQuadRegularRingAroundVertex(Index vIndex, Index ringPoints[], int fvarChannel = -1) const; // WIP -- for future use, need to extend for face-varying... int gatherTriRegularInteriorPatchPoints( Index fIndex, Index patchVerts[], int rotation = 0) const; int gatherTriRegularBoundaryVertexPatchPoints(Index fIndex, Index patchVerts[], int boundaryVertInFace) const; int gatherTriRegularBoundaryEdgePatchPoints( Index fIndex, Index patchVerts[], int boundaryEdgeInFace) const; int gatherTriRegularCornerVertexPatchPoints( Index fIndex, Index patchVerts[], int cornerVertInFace) const; int gatherTriRegularCornerEdgePatchPoints( Index fIndex, Index patchVerts[], int cornerEdgeInFace) const; public: // Sizing methods used to construct a level to populate: void resizeFaces( int numFaces); void resizeFaceVertices(int numFaceVertsTotal); void resizeFaceEdges( int numFaceEdgesTotal); void resizeEdges( int numEdges); void resizeEdgeVertices(); // always 2*edgeCount void resizeEdgeFaces(int numEdgeFacesTotal); void resizeVertices( int numVertices); void resizeVertexFaces(int numVertexFacesTotal); void resizeVertexEdges(int numVertexEdgesTotal); void setMaxValence(int maxValence); // Modifiers to populate the relations for each component: IndexArray getFaceVertices(Index faceIndex); IndexArray getFaceEdges(Index faceIndex); IndexArray getEdgeVertices(Index edgeIndex); IndexArray getEdgeFaces(Index edgeIndex); IndexArray getVertexFaces(Index vertIndex); IndexArray getVertexEdges(Index vertIndex); LocalIndexArray getEdgeFaceLocalIndices(Index edgeIndex); LocalIndexArray getVertexFaceLocalIndices(Index vertIndex); LocalIndexArray getVertexEdgeLocalIndices(Index vertIndex); // Replace these with access to sharpness buffers/arrays rather than elements: float& getEdgeSharpness(Index edgeIndex); float& getVertexSharpness(Index vertIndex); // Create, destroy and populate face-varying channels: int createFVarChannel(int fvarValueCount, Sdc::Options const& options); void destroyFVarChannel(int channel); IndexArray getFaceFVarValues(Index faceIndex, int channel); void completeFVarChannelTopology(int channel, int regBoundaryValence); // Counts and offsets for all relation types: // - these may be unwarranted if we let Refinement access members directly... int getNumFaceVertices( Index faceIndex) const { return _faceVertCountsAndOffsets[2*faceIndex]; } int getOffsetOfFaceVertices(Index faceIndex) const { return _faceVertCountsAndOffsets[2*faceIndex + 1]; } int getNumFaceEdges( Index faceIndex) const { return getNumFaceVertices(faceIndex); } int getOffsetOfFaceEdges(Index faceIndex) const { return getOffsetOfFaceVertices(faceIndex); } int getNumEdgeVertices( Index ) const { return 2; } int getOffsetOfEdgeVertices(Index edgeIndex) const { return 2 * edgeIndex; } int getNumEdgeFaces( Index edgeIndex) const { return _edgeFaceCountsAndOffsets[2*edgeIndex]; } int getOffsetOfEdgeFaces(Index edgeIndex) const { return _edgeFaceCountsAndOffsets[2*edgeIndex + 1]; } int getNumVertexFaces( Index vertIndex) const { return _vertFaceCountsAndOffsets[2*vertIndex]; } int getOffsetOfVertexFaces(Index vertIndex) const { return _vertFaceCountsAndOffsets[2*vertIndex + 1]; } int getNumVertexEdges( Index vertIndex) const { return _vertEdgeCountsAndOffsets[2*vertIndex]; } int getOffsetOfVertexEdges(Index vertIndex) const { return _vertEdgeCountsAndOffsets[2*vertIndex + 1]; } ConstIndexArray getFaceVertices() const; // // Note that for some relations, the size of the relations for a child component // can vary radically from its parent due to the sparsity of the refinement. So // in these cases a few additional utilities are provided to help define the set // of incident components. Assuming adequate memory has been allocated, the // "resize" methods here initialize the set of incident components by setting // both the size and the appropriate offset, while "trim" is use to quickly lower // the size from an upper bound and nothing else. // void resizeFaceVertices(Index FaceIndex, int count); void resizeEdgeFaces(Index edgeIndex, int count); void trimEdgeFaces( Index edgeIndex, int count); void resizeVertexFaces(Index vertIndex, int count); void trimVertexFaces( Index vertIndex, int count); void resizeVertexEdges(Index vertIndex, int count); void trimVertexEdges( Index vertIndex, int count); public: // // Initial plans were to have a few specific classes properly construct the // topology from scratch, e.g. the Refinement class and a Factory class for // the base level, by populating all topological relations. The need to have // a class construct full topology given only a simple face-vertex list, made // it necessary to write code to define and orient all relations -- and most // of that seemed best placed here. // bool completeTopologyFromFaceVertices(); Index findEdge(Index v0, Index v1, ConstIndexArray v0Edges) const; // Methods supporting the above: void orientIncidentComponents(); bool orderVertexFacesAndEdges(Index vIndex, Index* vFaces, Index* vEdges) const; bool orderVertexFacesAndEdges(Index vIndex); void populateLocalIndices(); IndexArray shareFaceVertCountsAndOffsets() const; private: // Refinement classes (including all subclasses) build a Level: friend class Refinement; friend class TriRefinement; friend class QuadRefinement; // // A Level is independent of subdivision scheme or options. While it may have been // affected by them in its construction, they are not associated with it -- a Level // is pure topology and any subdivision parameters are external. // // Simple members for inventory, etc. int _faceCount; int _edgeCount; int _vertCount; // The "depth" member is clearly useful in both the topological splitting and the // stencil queries, but arguably it ties the Level to a hierarchy which counters // the idea if it being independent. int _depth; // Maxima to help clients manage sizing of data buffers. Given "max valence", // the "max edge faces" is strictly redundant as it will always be less, but // since it will typically be so much less (i.e. 2) it is kept for now. int _maxEdgeFaces; int _maxValence; // // Topology vectors: // Note that of all of these, only data for the face-edge relation is not // stored in the osd::FarTables in any form. The FarTable vectors combine // the edge-vert and edge-face relations. The eventual goal is that this // data be part of the osd::Far classes and be a superset of the FarTable // vectors, i.e. no data duplication or conversion. The fact that FarTable // already stores 5 of the 6 possible relations should make the topology // storage as a whole a non-issue. // // The vert-face-child and vert-edge-child indices are also arguably not // a topology relation but more one for parent/child relations. But it is // a topological relationship, and if named differently would not likely // raise this. It has been named with "child" in the name as it does play // a more significant role during subdivision in mapping between parent // and child components, and so has been named to reflect that more clearly. // // Per-face: std::vector<Index> _faceVertCountsAndOffsets; // 2 per face, redundant after level 0 std::vector<Index> _faceVertIndices; // 3 or 4 per face, variable at level 0 std::vector<Index> _faceEdgeIndices; // matches face-vert indices std::vector<FTag> _faceTags; // 1 per face: includes "hole" tag // Per-edge: std::vector<Index> _edgeVertIndices; // 2 per edge std::vector<Index> _edgeFaceCountsAndOffsets; // 2 per edge std::vector<Index> _edgeFaceIndices; // varies with faces per edge std::vector<LocalIndex> _edgeFaceLocalIndices; // varies with faces per edge std::vector<float> _edgeSharpness; // 1 per edge std::vector<ETag> _edgeTags; // 1 per edge: manifold, boundary, etc. // Per-vertex: std::vector<Index> _vertFaceCountsAndOffsets; // 2 per vertex std::vector<Index> _vertFaceIndices; // varies with valence std::vector<LocalIndex> _vertFaceLocalIndices; // varies with valence, 8-bit for now std::vector<Index> _vertEdgeCountsAndOffsets; // 2 per vertex std::vector<Index> _vertEdgeIndices; // varies with valence std::vector<LocalIndex> _vertEdgeLocalIndices; // varies with valence, 8-bit for now std::vector<float> _vertSharpness; // 1 per vertex std::vector<VTag> _vertTags; // 1 per vertex: manifold, Sdc::Rule, etc. // Face-varying channels: std::vector<FVarLevel*> _fvarChannels; }; // // Access/modify the vertices indicent a given face: // inline ConstIndexArray Level::getFaceVertices(Index faceIndex) const { return ConstIndexArray(&_faceVertIndices[_faceVertCountsAndOffsets[faceIndex*2+1]], _faceVertCountsAndOffsets[faceIndex*2]); } inline IndexArray Level::getFaceVertices(Index faceIndex) { return IndexArray(&_faceVertIndices[_faceVertCountsAndOffsets[faceIndex*2+1]], _faceVertCountsAndOffsets[faceIndex*2]); } inline void Level::resizeFaceVertices(Index faceIndex, int count) { int* countOffsetPair = &_faceVertCountsAndOffsets[faceIndex*2]; countOffsetPair[0] = count; countOffsetPair[1] = (faceIndex == 0) ? 0 : (countOffsetPair[-2] + countOffsetPair[-1]); _maxValence = std::max(_maxValence, count); } inline ConstIndexArray Level::getFaceVertices() const { return ConstIndexArray(&_faceVertIndices[0], (int)_faceVertIndices.size()); } // // Access/modify the edges indicent a given face: // inline ConstIndexArray Level::getFaceEdges(Index faceIndex) const { return ConstIndexArray(&_faceEdgeIndices[_faceVertCountsAndOffsets[faceIndex*2+1]], _faceVertCountsAndOffsets[faceIndex*2]); } inline IndexArray Level::getFaceEdges(Index faceIndex) { return IndexArray(&_faceEdgeIndices[_faceVertCountsAndOffsets[faceIndex*2+1]], _faceVertCountsAndOffsets[faceIndex*2]); } // // Access/modify the faces indicent a given vertex: // inline ConstIndexArray Level::getVertexFaces(Index vertIndex) const { return ConstIndexArray( (&_vertFaceIndices[0]) + _vertFaceCountsAndOffsets[vertIndex*2+1], _vertFaceCountsAndOffsets[vertIndex*2]); } inline IndexArray Level::getVertexFaces(Index vertIndex) { return IndexArray( (&_vertFaceIndices[0]) + _vertFaceCountsAndOffsets[vertIndex*2+1], _vertFaceCountsAndOffsets[vertIndex*2]); } inline ConstLocalIndexArray Level::getVertexFaceLocalIndices(Index vertIndex) const { return ConstLocalIndexArray( (&_vertFaceLocalIndices[0]) + _vertFaceCountsAndOffsets[vertIndex*2+1], _vertFaceCountsAndOffsets[vertIndex*2]); } inline LocalIndexArray Level::getVertexFaceLocalIndices(Index vertIndex) { return LocalIndexArray( (&_vertFaceLocalIndices[0]) + _vertFaceCountsAndOffsets[vertIndex*2+1], _vertFaceCountsAndOffsets[vertIndex*2]); } inline void Level::resizeVertexFaces(Index vertIndex, int count) { int* countOffsetPair = &_vertFaceCountsAndOffsets[vertIndex*2]; countOffsetPair[0] = count; countOffsetPair[1] = (vertIndex == 0) ? 0 : (countOffsetPair[-2] + countOffsetPair[-1]); } inline void Level::trimVertexFaces(Index vertIndex, int count) { _vertFaceCountsAndOffsets[vertIndex*2] = count; } // // Access/modify the edges indicent a given vertex: // inline ConstIndexArray Level::getVertexEdges(Index vertIndex) const { return ConstIndexArray( (&_vertEdgeIndices[0]) +_vertEdgeCountsAndOffsets[vertIndex*2+1], _vertEdgeCountsAndOffsets[vertIndex*2]); } inline IndexArray Level::getVertexEdges(Index vertIndex) { return IndexArray( (&_vertEdgeIndices[0]) +_vertEdgeCountsAndOffsets[vertIndex*2+1], _vertEdgeCountsAndOffsets[vertIndex*2]); } inline ConstLocalIndexArray Level::getVertexEdgeLocalIndices(Index vertIndex) const { return ConstLocalIndexArray( (&_vertEdgeLocalIndices[0]) + _vertEdgeCountsAndOffsets[vertIndex*2+1], _vertEdgeCountsAndOffsets[vertIndex*2]); } inline LocalIndexArray Level::getVertexEdgeLocalIndices(Index vertIndex) { return LocalIndexArray( (&_vertEdgeLocalIndices[0]) + _vertEdgeCountsAndOffsets[vertIndex*2+1], _vertEdgeCountsAndOffsets[vertIndex*2]); } inline void Level::resizeVertexEdges(Index vertIndex, int count) { int* countOffsetPair = &_vertEdgeCountsAndOffsets[vertIndex*2]; countOffsetPair[0] = count; countOffsetPair[1] = (vertIndex == 0) ? 0 : (countOffsetPair[-2] + countOffsetPair[-1]); _maxValence = std::max(_maxValence, count); } inline void Level::trimVertexEdges(Index vertIndex, int count) { _vertEdgeCountsAndOffsets[vertIndex*2] = count; } inline void Level::setMaxValence(int valence) { _maxValence = valence; } // // Access/modify the vertices indicent a given edge: // inline ConstIndexArray Level::getEdgeVertices(Index edgeIndex) const { return ConstIndexArray(&_edgeVertIndices[edgeIndex*2], 2); } inline IndexArray Level::getEdgeVertices(Index edgeIndex) { return IndexArray(&_edgeVertIndices[edgeIndex*2], 2); } // // Access/modify the faces indicent a given edge: // inline ConstIndexArray Level::getEdgeFaces(Index edgeIndex) const { return ConstIndexArray(&_edgeFaceIndices[0] + _edgeFaceCountsAndOffsets[edgeIndex*2+1], _edgeFaceCountsAndOffsets[edgeIndex*2]); } inline IndexArray Level::getEdgeFaces(Index edgeIndex) { return IndexArray(&_edgeFaceIndices[0] + _edgeFaceCountsAndOffsets[edgeIndex*2+1], _edgeFaceCountsAndOffsets[edgeIndex*2]); } inline ConstLocalIndexArray Level::getEdgeFaceLocalIndices(Index edgeIndex) const { return ConstLocalIndexArray(&_edgeFaceLocalIndices[0] + _edgeFaceCountsAndOffsets[edgeIndex*2+1], _edgeFaceCountsAndOffsets[edgeIndex*2]); } inline LocalIndexArray Level::getEdgeFaceLocalIndices(Index edgeIndex) { return LocalIndexArray(&_edgeFaceLocalIndices[0] + _edgeFaceCountsAndOffsets[edgeIndex*2+1], _edgeFaceCountsAndOffsets[edgeIndex*2]); } inline void Level::resizeEdgeFaces(Index edgeIndex, int count) { int* countOffsetPair = &_edgeFaceCountsAndOffsets[edgeIndex*2]; countOffsetPair[0] = count; countOffsetPair[1] = (edgeIndex == 0) ? 0 : (countOffsetPair[-2] + countOffsetPair[-1]); _maxEdgeFaces = std::max(_maxEdgeFaces, count); } inline void Level::trimEdgeFaces(Index edgeIndex, int count) { _edgeFaceCountsAndOffsets[edgeIndex*2] = count; } // // Access/modify sharpness values: // inline float Level::getEdgeSharpness(Index edgeIndex) const { return _edgeSharpness[edgeIndex]; } inline float& Level::getEdgeSharpness(Index edgeIndex) { return _edgeSharpness[edgeIndex]; } inline float Level::getVertexSharpness(Index vertIndex) const { return _vertSharpness[vertIndex]; } inline float& Level::getVertexSharpness(Index vertIndex) { return _vertSharpness[vertIndex]; } inline Sdc::Crease::Rule Level::getVertexRule(Index vertIndex) const { return (Sdc::Crease::Rule) _vertTags[vertIndex]._rule; } // // Access/modify hole tag: // inline void Level::setFaceHole(Index faceIndex, bool b) { _faceTags[faceIndex]._hole = b; } inline bool Level::isFaceHole(Index faceIndex) const { return _faceTags[faceIndex]._hole; } // // Access/modify non-manifold tags: // inline void Level::setEdgeNonManifold(Index edgeIndex, bool b) { _edgeTags[edgeIndex]._nonManifold = b; } inline bool Level::isEdgeNonManifold(Index edgeIndex) const { return _edgeTags[edgeIndex]._nonManifold; } inline void Level::setVertexNonManifold(Index vertIndex, bool b) { _vertTags[vertIndex]._nonManifold = b; } inline bool Level::isVertexNonManifold(Index vertIndex) const { return _vertTags[vertIndex]._nonManifold; } // // Sizing methods to allocate space: // inline void Level::resizeFaces(int faceCount) { _faceCount = faceCount; _faceVertCountsAndOffsets.resize(2 * faceCount); _faceTags.resize(faceCount); std::memset(&_faceTags[0], 0, _faceCount * sizeof(FTag)); } inline void Level::resizeFaceVertices(int totalFaceVertCount) { _faceVertIndices.resize(totalFaceVertCount); } inline void Level::resizeFaceEdges(int totalFaceEdgeCount) { _faceEdgeIndices.resize(totalFaceEdgeCount); } inline void Level::resizeEdges(int edgeCount) { _edgeCount = edgeCount; _edgeFaceCountsAndOffsets.resize(2 * edgeCount); _edgeSharpness.resize(edgeCount); _edgeTags.resize(edgeCount); if (edgeCount>0) { std::memset(&_edgeTags[0], 0, _edgeCount * sizeof(ETag)); } } inline void Level::resizeEdgeVertices() { _edgeVertIndices.resize(2 * _edgeCount); } inline void Level::resizeEdgeFaces(int totalEdgeFaceCount) { _edgeFaceIndices.resize(totalEdgeFaceCount); _edgeFaceLocalIndices.resize(totalEdgeFaceCount); } inline void Level::resizeVertices(int vertCount) { _vertCount = vertCount; _vertFaceCountsAndOffsets.resize(2 * vertCount); _vertEdgeCountsAndOffsets.resize(2 * vertCount); _vertSharpness.resize(vertCount); _vertTags.resize(vertCount); std::memset(&_vertTags[0], 0, _vertCount * sizeof(VTag)); } inline void Level::resizeVertexFaces(int totalVertFaceCount) { _vertFaceIndices.resize(totalVertFaceCount); _vertFaceLocalIndices.resize(totalVertFaceCount); } inline void Level::resizeVertexEdges(int totalVertEdgeCount) { _vertEdgeIndices.resize(totalVertEdgeCount); _vertEdgeLocalIndices.resize(totalVertEdgeCount); } inline IndexArray Level::shareFaceVertCountsAndOffsets() const { // XXXX manuelk we have to force const casting here (classes don't 'share' // members usually...) return IndexArray(const_cast<Index *>(&_faceVertCountsAndOffsets[0]), (int)_faceVertCountsAndOffsets.size()); } } // end namespace internal } // end namespace Vtr } // end namespace OPENSUBDIV_VERSION using namespace OPENSUBDIV_VERSION; } // end namespace OpenSubdiv #endif /* OPENSUBDIV3_VTR_LEVEL_H */
[ "tungnt.rec@gmail.com" ]
tungnt.rec@gmail.com
f4d3c80fccad89abdf7d9b3282db307167c33a23
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
/main/source/src/core/pack/rotamers/StoredRotamerLibraryCreator.cc
746bff97f5d0aaa09800835da9e09ccfe591de7a
[]
no_license
MedicaicloudLink/Rosetta
3ee2d79d48b31bd8ca898036ad32fe910c9a7a28
01affdf77abb773ed375b83cdbbf58439edd8719
refs/heads/master
2020-12-07T17:52:01.350906
2020-01-10T08:24:09
2020-01-10T08:24:09
232,757,729
2
6
null
null
null
null
UTF-8
C++
false
false
2,400
cc
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington CoMotion, email: license@uw.edu. /// @file core/pack/rotamers/StoredRotamerLibraryCreator.cc /// @brief Class for instantiating a SingleLigandRotamerLibrary from a StoredRotamerLibrarySpecification /// @author Rocco Moretti (rmorettiase@gmail.com) // Package headers #include <core/pack/rotamers/StoredRotamerLibraryCreator.hh> #include <core/pack/rotamers/SingleResidueRotamerLibrary.hh> #include <core/pack/rotamers/SingleLigandRotamerLibrary.hh> // Program header #include <core/chemical/rotamers/RotamerLibrarySpecification.hh> #include <core/chemical/rotamers/StoredRotamerLibrarySpecification.hh> #include <core/chemical/ResidueType.hh> // Utility headers #include <basic/Tracer.hh> // C++ headers #include <string> namespace core { namespace pack { namespace rotamers { static basic::Tracer TR("core.pack.rotamers.StoredRotamerLibraryCreator"); core::pack::rotamers::SingleResidueRotamerLibraryCOP StoredRotamerLibraryCreator::create( core::chemical::ResidueType const & restype) const { using namespace core::chemical::rotamers; using namespace core::pack::dunbrack; RotamerLibrarySpecificationCOP libspec( restype.rotamer_library_specification() ); // If the factory system is sound, these two checks should work. debug_assert( libspec ); StoredRotamerLibrarySpecificationCOP stored_libspec = utility::pointer::dynamic_pointer_cast< StoredRotamerLibrarySpecification const >(libspec); debug_assert( stored_libspec ); SingleLigandRotamerLibraryOP rotamer_lib( new SingleLigandRotamerLibrary() ); rotamer_lib->init_from_vector( stored_libspec->coordinates() ); rotamer_lib->set_reference_energy( stored_libspec->get_reference_energy() ); return rotamer_lib; } std::string StoredRotamerLibraryCreator::keyname() const { return core::chemical::rotamers::StoredRotamerLibrarySpecification::library_name(); } } //namespace rotamers } //namespace pack } //namespace core
[ "36790013+MedicaicloudLink@users.noreply.github.com" ]
36790013+MedicaicloudLink@users.noreply.github.com
0409a773597792e3bbedde1c95c5bdc21945b876
2349792cd2e91fc4012250fc060486f991704daf
/vtools/Sample/inc/Application.h
6f0a7c637087ac65b45e6f04e50569f615097670
[ "BSL-1.0", "FTL" ]
permissive
SergeyStrukov/CCore-2-99
e98d416372797eaee2101375f6adff3de4a55c4e
1eca5b9b2de067bbab43326718b877465ae664fe
refs/heads/master
2021-01-18T16:45:40.186844
2017-06-08T22:16:32
2017-06-08T22:16:32
58,191,022
1
0
null
null
null
null
UTF-8
C++
false
false
697
h
/* Application.h */ //---------------------------------------------------------------------------------------- // // Project: Sample 1.00 // // License: Boost Software License - Version 1.0 - August 17th, 2003 // // see http://www.boost.org/LICENSE_1_0.txt or the local copy // // Copyright (c) 2017 Sergey Strukov. All rights reserved. // //---------------------------------------------------------------------------------------- #ifndef Application_h #define Application_h #include <CCore/inc/video/UserPreference.h> namespace App { /* using */ using namespace CCore; using namespace CCore::Video; /* Main() */ int Main(CmdDisplay cmd_display); } // namespace App #endif
[ "sshimnick@hotmail.com" ]
sshimnick@hotmail.com
7501bee6afd6f144fb56c40c8abea218b0e85557
cbbde022d9dd74b4577eb91f8947d8d140719cbe
/include/BetaCluster.h
95ed328cc2fea0f354a97487ee844b334be12bb4
[ "BSD-2-Clause" ]
permissive
jeremysalwen/HaliteClustering
e4774a9870b6f071bad5ee31290c6ae11d85291a
dc8702870c20486782300d2a00b6e4a2648f8392
refs/heads/master
2021-01-17T10:45:53.368354
2016-04-04T07:03:09
2016-05-10T02:24:49
19,996,852
1
3
null
2015-09-30T16:54:30
2014-05-20T20:43:12
C++
UTF-8
C++
false
false
781
h
// -*-c++-*- #ifndef BETA_CLUSTER_H #define BETA_CLUSTER_H #include <vector> #include <cstddef> #include "Normalization.h" namespace Halite { template <typename D> class BetaCluster { public: BetaCluster(int levl, int DIM): level(levl), cost(-1), correlationCluster(-1), relevantDimension(DIM, false), min(DIM), max(DIM) { } template<typename It> bool contains(It point) const { for(size_t i=0; i<min.size(); i++){ if(relevantDimension[i] && (point[i]<min[i] || point[i]>max[i])) { return false; } } return true; } int level; int cost; int correlationCluster; //vector<bool>, except not specialized std::vector<unsigned char> relevantDimension; std::vector<D> min; std::vector<D> max; }; } #endif
[ "jeremysalwen@gmail.com" ]
jeremysalwen@gmail.com
ba789fa5d982d3e2ff47554d89f8d3d373d8e4d3
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/232/901/CWE122_Heap_Based_Buffer_Overflow__c_CWE805_char_ncpy_33.cpp
06b5d0bb6766287d7925937f3218f34074b5850e
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
3,305
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_char_ncpy_33.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.string.label.xml Template File: sources-sink-33.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using malloc() and set data pointer to a small buffer * GoodSource: Allocate using malloc() and set data pointer to a large buffer * Sinks: ncpy * BadSink : Copy string to data using strncpy * Flow Variant: 33 Data flow: use of a C++ reference to data within the same function * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE122_Heap_Based_Buffer_Overflow__c_CWE805_char_ncpy_33 { #ifndef OMITBAD void bad() { char * data; char * &dataRef = data; data = NULL; /* FLAW: Allocate and point data to a small buffer that is smaller than the large buffer used in the sinks */ data = (char *)malloc(50*sizeof(char)); if (data == NULL) {exit(-1);} data[0] = '\0'; /* null terminate */ { char * data = dataRef; { char source[100]; memset(source, 'C', 100-1); /* fill with 'C's */ source[100-1] = '\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ strncpy(data, source, 100-1); data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */ printLine(data); free(data); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2B() { char * data; char * &dataRef = data; data = NULL; /* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */ data = (char *)malloc(100*sizeof(char)); if (data == NULL) {exit(-1);} data[0] = '\0'; /* null terminate */ { char * data = dataRef; { char source[100]; memset(source, 'C', 100-1); /* fill with 'C's */ source[100-1] = '\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ strncpy(data, source, 100-1); data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */ printLine(data); free(data); } } } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE122_Heap_Based_Buffer_Overflow__c_CWE805_char_ncpy_33; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "frank@fischer.com.mt" ]
frank@fischer.com.mt