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
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 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
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
593bd5cbebba25d703bd851dfffeb578320ea1f3
8e4c9ebefc0f7db0615377376f142e4a866f7700
/MiracleEngine/Src/Engine/Tools/MathLib/Vector2.h
74c9cd1167eec4bd69606ff79c63398a1aba47b9
[]
no_license
Yuxuannnnnnnn/Gam200---Miracle-Studios
2edaaf5902e9dd79bfb74c7204773e81093f0673
897d294df6876852a3dfaefa940c628d27e9bf66
refs/heads/master
2021-09-28T19:46:09.740223
2021-09-08T13:19:53
2021-09-08T13:19:53
205,817,968
0
0
null
null
null
null
UTF-8
C++
false
false
3,453
h
/////////////////////////////////////////////////////////////////////////////////////// // // Vector2.h // // Authors: yinshuyu // Copyright 2019, Digipen Institute of Technology // /////////////////////////////////////////////////////////////////////////////////////// #ifndef _SHUYU_VECTOR2_H #define _SHUYU_VECTOR2_H #include <cmath> #include <fstream> /* 1 byte -> bool, char, unsigned char, signed char, __int8 2 bytes -> __int16, short, unsigned short, wchar_t, __wchar_t 4 bytes -> float, __int32, int, unsigned int, long, unsigned long 8 bytes -> double, __int64, long double, long long */ namespace mathLib { typedef union Vector2 { public: struct { float _x; float _y; }; float m[2]; static const Vector2 Vec2Zero; static const Vector2 Vec2EX; static const Vector2 Vec2EY; public: // Default Constructor Vector2(); // Conversion Constructor Vector2(const float& x, const float& y = 0.f); // Copy constructor Vector2(const Vector2& rhs); // Default destructor ~Vector2() {} Vector2& operator=(const Vector2& rhs); float operator[](size_t index) const; float& GetX(); float& GetY(); void SetX(const float& x); void SetY(const float& y); void Set(float x = 0.f, float y = 0.f); public: // other function float Sum() const; float Distance(const Vector2& pt) const; float Distance(float x, float y) const; float Length() const; float SquaredLength() const; Vector2& Normalize(); Vector2 Normalized() const; Vector2& Round(); Vector2 Rounded() const; Vector2 Cross(const Vector2& v) const; float Dot(const Vector2& v) const; float AbsDot(const Vector2& v) const; Vector2 Abs() const; bool IsFinite() const; // problems : not fix //static float DistToLine(const Vector2& lineEdge1, const Vector2& lineEdge2, const Vector2& pt); //static Vector2 Normal(const Vector2& v1, const Vector2& v2, const Vector2& v3); friend std::ostream& operator<<(std::ostream& out, const Vector2& v); friend std::istream& operator>>(std::istream& in, Vector2& v); } Vector2, Vec2; Vector2 operator+(const Vector2& lhs); Vector2 operator-(const Vector2& lhs); Vector2 operator+(const Vector2& lhs, const Vector2& rhs); Vector2 operator-(const Vector2& lhs, const Vector2& rhs); Vector2 operator*(const Vector2& lhs, const Vector2& rhs); Vector2 operator/(const Vector2& lhs, const Vector2& rhs); Vector2& operator+=(Vector2& lhs, const Vector2& rhs); Vector2& operator-=(Vector2& lhs, const Vector2& rhs); Vector2& operator*=(Vector2& lhs, const Vector2& rhs); Vector2& operator/=(Vector2& lhs, const Vector2& rhs); Vector2 operator*(const Vector2& lhs, const float& rhs); Vector2 operator*(const float& lhs, const Vector2& rhs); Vector2 operator/(const Vector2& lhs, const float& rhs); //Vector2 operator/(const float& lhs, const Vector2& rhs); Vector2& operator*=(Vector2& lhs, const float& rhs); Vector2& operator*=(const float& lhs, Vector2& rhs); Vector2& operator/=(Vector2& lhs, const float& rhs); //Vector2& operator/=(const float& lhs, Vector2& rhs); bool operator==(const Vector2& lhs, const Vector2& rhs); bool operator!=(const Vector2& lhs, const Vector2& rhs); //bool operator<(const Vector2& lhs, const Vector2& rhs); //bool operator>(const Vector2& lhs, const Vector2& rhs); //bool operator<=(const Vector2& lhs, const Vector2& rhs); //bool operator>=(const Vector2& lhs, const Vector2& rhs); } #endif
[ "love0love.ys@gmail.com" ]
love0love.ys@gmail.com
d56cb90186b645e2706cd46902f5c4b0a1aa3aef
975d4b8384122694b2a75d4737a25f06d672c208
/src/dispatcher.h
374a7297323d040e9155bf9d3190b9c18d5e0690
[]
no_license
dxfburns/distribution_adapter
d9e165278d8c3b3dafdf31be2cea6321816c1f2f
fe38ab47063471d245e913a5139c3756838a9a76
refs/heads/master
2016-09-11T02:11:59.311722
2014-05-04T02:53:02
2014-05-04T02:53:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
937
h
/* * dispatcher.h * * Created on: Apr 28, 2014 * Author: root */ #ifndef DISPATCHER_H_ #define DISPATCHER_H_ #include <websocketpp/config/asio_no_tls_client.hpp> #include <websocketpp/client.hpp> #include <map> #include <vector> #include "model.h" typedef websocketpp::client<websocketpp::config::asio_client> client; // pull out the type of messages sent by our config typedef websocketpp::config::asio_client::message_type::ptr message_ptr; using namespace std; class dispatcher { private: int machine_id; client sip_client; void on_open(websocketpp::connection_hdl); void on_message(websocketpp::connection_hdl, message_ptr); void set_dispatch_package_from_message(const string&, dispatch_package&); void set_message_from_dispatch_package(dispatch_package&, string&); void set_waiters_map(vector<string>&, map<int, string>&); public: dispatcher() {} void run(int, string); }; #endif /* DISPATCHER_H_ */
[ "xfdu.ld@gmail.com" ]
xfdu.ld@gmail.com
87789b31da44bf563cc4aaf3c7a89795d24de25d
30c0974df70d24e485dfed1afab9f8db135ff019
/projects/libhttp/src/httpformfield_file.cpp
2b1ebd55f30122d793cb6c6d8b7193901657fa45
[ "Apache-2.0" ]
permissive
leckel2014/CoreLooper
48cc7ae970fe9c46400b1eb9747dfc0d90c62219
5afd067488bd81105297eb84016949d539b67ea9
refs/heads/master
2020-05-25T19:04:26.976075
2019-03-05T12:25:29
2019-03-05T12:25:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,577
cpp
#include "stdafx.h" #include "httpformfield_file.h" using namespace Bear::Core; namespace Bear { namespace Core { using namespace FileSystem; namespace Net { namespace Http { HttpFormField_File::HttpFormField_File() { mFile = nullptr; } HttpFormField_File::~HttpFormField_File() { Close(); } void HttpFormField_File::Close() { if (mFile) { fclose(mFile); mFile = nullptr; if (mDataReady) { if (File::FileExists(mFilePath.c_str())) { File::DeleteFile(mFilePath.c_str()); } File::rename(mFilePathTmp.c_str(), mFilePath.c_str()); } else { //自动删除无效的数据 } } } int HttpFormField_File::Input(LPBYTE data, int dataLen) { if (!mFile) { //mFieldName中可能也带有子目录 string fullFilePath = mFolder + "/" + mFieldName; File::CreateFolderForFile(fullFilePath.c_str()); mFilePath = fullFilePath; mFilePathTmp = fullFilePath + ".tmp"; if (mRangeStart == 0) { mFile = fopen(mFilePathTmp.c_str(), "wb"); } else { mFile = fopen(mFilePathTmp.c_str(), "a+b"); } } if (mFile) { static int idx = -1; ++idx; int ret = dataLen; //if (idx == 0) { ret = (int)fwrite(data, 1, dataLen, mFile); } if (ret == dataLen) { return 0; } else { DW("fail fwrite,dataLen=%d,ret=%d,error=%d", dataLen, ret, errno); } } else { int x = 0; } return -1; } void HttpFormField_File::SetDataReady(bool ready) { __super::SetDataReady(ready); if (ready) { Close(); } } void HttpFormField_File::OnPostFail() { //不要删除,可支持断点继传 } } } } }
[ "xwpcom@163.com" ]
xwpcom@163.com
df6d6985cc679c5e2b9067ca35dde8a835754a14
8d5016fa9db9eba2a014b2c78f6b09c40a56f98e
/exceptions.h
7cbbd18f79edcd809d33051ac981b199e5d18cb1
[]
no_license
mathewkramsch/pa01_cs130a
8bd31aa5fc74be05050247adbb776903a58f5012
f5f01808c4eb9e35ac01d6038515125f0e7ed784
refs/heads/master
2022-04-06T05:04:41.481906
2020-02-08T00:18:57
2020-02-08T00:18:57
238,636,238
0
0
null
null
null
null
UTF-8
C++
false
false
300
h
// exceptions.h #ifndef EXCEPTIONS_H #define EXCEPTIONS_H class noInput { public: void mssg(); }; class invalidOperator { public: void mssg(); }; class invalidPolynomial { public: void mssg(); }; class invalidOperation {public: void mssg(); }; class outOfOrderPoly {public: void mssg(); }; #endif
[ "mathewkramsch@ucsb.edu" ]
mathewkramsch@ucsb.edu
b8e7929300e8d7c6e50ac825269c8e0eb0864226
a06515f4697a3dbcbae4e3c05de2f8632f8d5f46
/corpus/taken_from_cppcheck_tests/stolen_146.cpp
1739cd6f90f45dec231082adbed99d1297e20219
[]
no_license
pauldreik/fuzzcppcheck
12d9c11bcc182cc1f1bb4893e0925dc05fcaf711
794ba352af45971ff1f76d665b52adeb42dcab5f
refs/heads/master
2020-05-01T01:55:04.280076
2019-03-22T21:05:28
2019-03-22T21:05:28
177,206,313
0
0
null
null
null
null
UTF-8
C++
false
false
50
cpp
int main() { int i; free(&i); return 0; }
[ "github@pauldreik.se" ]
github@pauldreik.se
cd14d0c7a5733cdf80dc012f0613c0b82d48d953
17d8812540d360aaa3066c385e23284c1991ece2
/tests/regressions/insieme-src-a2667acd.cpp
cc627368cad6e758f3c3cf86396139ceee2d8292
[]
no_license
allscale/allscale_runtime
0fde3cc0fe6e9dde0687291f9f2d02b2e869ab0c
27736d33cc8dd06836f13cab1448bc5acb4d9c2c
refs/heads/master
2021-01-13T15:50:26.903497
2018-11-15T17:15:43
2018-11-15T17:15:43
76,855,426
6
3
null
2018-11-26T16:44:28
2016-12-19T11:13:54
C++
UTF-8
C++
false
false
2,506
cpp
/** * ------------------------ Auto-generated Code ------------------------ * This code was generated by the Insieme Compiler * --------------------------------------------------------------------- */ #include <allscale/runtime.hpp> #include <stdint.h> #ifdef __cplusplus #define INS_INIT(...) __VA_ARGS__ #else #define INS_INIT(...) (__VA_ARGS__) #endif #ifdef __cplusplus #include <new> #define INS_INPLACE_INIT(Loc,Type) new(Loc) Type #else #define INS_INPLACE_INIT(Loc,Type) *(Loc) = (Type) #endif #ifdef __cplusplus /** Workaround for libstdc++/libc bug. * There's an inconsistency between libstdc++ and libc regarding whether * ::gets is declared or not, which is only evident when using certain * compilers and language settings * (tested positively with clang 3.9 --std=c++14 and libc 2.17). */ #include <initializer_list> // force libstdc++ to include its config #undef _GLIBCXX_HAVE_GETS // correct broken config #endif /* ------- Program Code --------- */ struct __wi_main_name { static const char* name() { return "__wi_main"; } }; struct __wi_main_variant_0; typedef struct __wi_main_variant_0 __wi_main_variant_0; struct __wi_main_variant_1; typedef struct __wi_main_variant_1 __wi_main_variant_1; using __wi_main_work = allscale::work_item_description<int32_t, __wi_main_name, allscale::no_serialization, __wi_main_variant_0, __wi_main_variant_1 >; /* ------- Function Definitions --------- */ int32_t main() { return allscale::runtime::main_wrapper<__wi_main_work >(); } /* ------- Function Definitions --------- */ int32_t allscale_fun_3() { return 0; } ALLSCALE_REGISTER_TREETURE_TYPE(int32_t) /* ------- Function Definitions --------- */ allscale::treeture<int32_t > allscale_fun_1(hpx::util::tuple<int, char** > const& var_0) { return allscale::treeture<int32_t >(allscale_fun_3()); } struct __wi_main_variant_0 { static allscale::treeture<int32_t > execute(hpx::util::tuple<int, char** > const& var_0); static constexpr bool valid = true; }; allscale::treeture<int32_t > __wi_main_variant_0::execute(hpx::util::tuple<int, char** > const& var_0) { return allscale_fun_1(var_0); } struct __wi_main_variant_1 { static allscale::treeture<int32_t > execute(hpx::util::tuple<int, char** > const& var_0); static constexpr bool valid = true; }; allscale::treeture<int32_t > __wi_main_variant_1::execute(hpx::util::tuple<int, char** > const& var_0) { return allscale_fun_1(var_0); }
[ "thomas.heller@cs.fau.de" ]
thomas.heller@cs.fau.de
bd87ef94841b92b1f3f7f4ef999b80ee153dd84b
d0fb46aecc3b69983e7f6244331a81dff42d9595
/paifeaturestore/include/alibabacloud/paifeaturestore/model/WriteFeatureViewTableResult.h
b8b0b47e025068358f6eddc435fbb5cef54d3aba
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
1,437
h
/* * Copyright 2009-2017 Alibaba Cloud 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. */ #ifndef ALIBABACLOUD_PAIFEATURESTORE_MODEL_WRITEFEATUREVIEWTABLERESULT_H_ #define ALIBABACLOUD_PAIFEATURESTORE_MODEL_WRITEFEATUREVIEWTABLERESULT_H_ #include <string> #include <vector> #include <utility> #include <alibabacloud/core/ServiceResult.h> #include <alibabacloud/paifeaturestore/PaiFeatureStoreExport.h> namespace AlibabaCloud { namespace PaiFeatureStore { namespace Model { class ALIBABACLOUD_PAIFEATURESTORE_EXPORT WriteFeatureViewTableResult : public ServiceResult { public: WriteFeatureViewTableResult(); explicit WriteFeatureViewTableResult(const std::string &payload); ~WriteFeatureViewTableResult(); protected: void parse(const std::string &payload); private: }; } } } #endif // !ALIBABACLOUD_PAIFEATURESTORE_MODEL_WRITEFEATUREVIEWTABLERESULT_H_
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
2aa2a3a50371725531cae2211764396e1a94a4cd
33035c05aad9bca0b0cefd67529bdd70399a9e04
/src/boost_process_start_dir.hpp
67fbaf3aa2eeb24d8e613a308e322b3546593d14
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
elvisbugs/BoostForArduino
7e2427ded5fd030231918524f6a91554085a8e64
b8c912bf671868e2182aa703ed34076c59acf474
refs/heads/master
2023-03-25T13:11:58.527671
2021-03-27T02:37:29
2021-03-27T02:37:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
39
hpp
#include <boost/process/start_dir.hpp>
[ "k@kekyo.net" ]
k@kekyo.net
681f20bc8e78d5192381d814db7d26eceb4f448b
9f89b08007ab7df86f44481d1a06a122ac55d924
/Maximum Sum Increasing Subsequence.cpp
8097e58f933022302d65f10bdae994da1eb2f91d
[]
no_license
raviguru123/prog-amazon
af22ecb62954a588f7c26930e7f58485384b09f1
30aeb83539dfa394ba58a171fb55b9284500aa17
refs/heads/master
2021-01-19T04:47:53.867859
2017-04-06T09:13:22
2017-04-06T09:13:22
87,396,593
0
1
null
null
null
null
UTF-8
C++
false
false
565
cpp
#include <iostream> #include <vector> #include <limits.h> using namespace std; int maxsum(vector<int> &v){ vector<int> sum(v.size(),0); sum[0]=v[0]; int max; for(int i=1;i<v.size();++i){ int j=i-1; max=INT_MIN; while(j>=0){ max=(max<sum[j]&&v[i]>=v[j])?sum[j]:max; j--; } sum[i]=max+v[i]; } max=INT_MIN; for(int i=0;i<sum.size();++i){ cout<<sum[i]<<" "; max=max<sum[i]?sum[i]:max; } cout<<endl; return max; } int main(){ int a[]={3, 4, 5, 10}; vector<int> v(a,a+(sizeof a)/sizeof(int)); cout<<maxsum(v)<<endl; return 0; }
[ "raviguruiitr@gmail.com" ]
raviguruiitr@gmail.com
cca03d9caa8262fb904349673b90b3987cc52694
e312d48f11ea4f60dd185a12b54b5d66860a6e49
/RaylibStarterCPP1/inc/SeekBehaviour.h
5b318cfaaa19b7b816a22c513056906dcd23be25
[]
no_license
SuperiorJacob/AIGame
1df393408b7fbd81acf58874150db6319abb701f
e2a2344b7689ea1dbc50bd068e26c19f0f109dd1
refs/heads/master
2022-11-28T14:46:16.950132
2020-07-31T06:39:53
2020-07-31T06:39:53
283,411,859
1
0
null
null
null
null
UTF-8
C++
false
false
602
h
#pragma once #include "Behaviour.h" #include "raymath.h" #include <functional> class SeekBehaviour : public Behaviour { public: SeekBehaviour(); virtual ~SeekBehaviour(); virtual void Update(GameObject* obj, float deltaTime); virtual void Draw(GameObject* obj); const Vector2& GetTarget() const; void SetTarget(const Vector2& target); const float& GetTargetRadius() const; void SetTargetRadius(const float& radius); void OnArrive(std::function<void()> callback); protected: Vector2 m_target = { 0,0 }; float m_targetRadius = 1.0f; std::function<void()> m_onArriveFn; private: };
[ "s200503@students.aie.edu.au" ]
s200503@students.aie.edu.au
ece3878c4688dc9dece209b0df42efd6caf4f3ca
4ba79c40692ae5ff3711674418bf0771fe18db7c
/src/s01-hello-name.cpp
c2949dd700cff84d978c168b593ff927c8e2ae7b
[]
no_license
s23578-pj/pjatk-prg1
0c3dd8424216a1aeee090d29df058c810a88a9ac
6d4120ce1b4c907c788396cb11c67e5cd0dcc681
refs/heads/master
2023-03-01T11:25:58.599517
2021-02-14T20:41:05
2021-02-14T20:41:05
304,903,383
0
0
null
null
null
null
UTF-8
C++
false
false
178
cpp
#include <iostream> #include <string> auto main() -> int { auto name = std::string{}; std::getline(std::cin, name); std::cout << " Hello, " << name << "!\n"; return 0; }
[ "s23578@pjwstk.edu.edu.pl" ]
s23578@pjwstk.edu.edu.pl
e2d0eae20f177cb4aa38129f77059edfe9237665
d61aed92e58ad2e6ae22c70539ae28e091551448
/BinarySearchFindIt-spyhton200p.cpp
7bb2c30c48136a9821e3fdf18b08e5eb720ae732
[]
no_license
jungsungyoon/test2
b568ea2daafbacaa6a599e9315d45fd2b35bde11
678d486d8827d149caae88c76efb928efb8986a5
refs/heads/master
2021-12-23T06:07:37.926984
2021-08-07T14:07:13
2021-08-07T14:07:13
161,124,525
0
0
null
null
null
null
UTF-8
C++
false
false
735
cpp
#include <bits/stdc++.h> using namespace std; int n, m; // 가게게 있는 전체 부품 번호를 담을 집합(set) 컨테이너 set<int> s; vector<int> targets; int main(void) { cin >> n; for (int i = 0; i < n; i++) { int x; cin >> x; s.insert(x); } cin >> m; for (int i = 0; i < m; i++) { int target; cin >> target; targets.push_back(target); } // 손님이 확인 요청한 부품 번호를 하나씩 확인 for (int i = 0; i < m; i++) { // 해당 부품이 존재하는지 확인 if (s.find(targets[i]) != s.end()) { cout << "yes" << ' '; } else { cout << "no" << ' '; } } }
[ "dkffprtm0404@naver.com" ]
dkffprtm0404@naver.com
1037356e1e8029709e0d18f5fdd4ab90ad5ad38e
091afb7001e86146209397ea362da70ffd63a916
/inst/include/nt2/include/functions/scalar/fast_tan.hpp
825d8bcc8f5232af253dfff2216f9ce5a4823e8a
[]
no_license
RcppCore/RcppNT2
f156b58c08863243f259d1e609c9a7a8cf669990
cd7e548daa2d679b6ccebe19744b9a36f1e9139c
refs/heads/master
2021-01-10T16:15:16.861239
2016-02-02T22:18:25
2016-02-02T22:18:25
50,460,545
15
1
null
2019-11-15T22:08:50
2016-01-26T21:29:34
C++
UTF-8
C++
false
false
194
hpp
#ifndef NT2_INCLUDE_FUNCTIONS_SCALAR_FAST_TAN_HPP_INCLUDED #define NT2_INCLUDE_FUNCTIONS_SCALAR_FAST_TAN_HPP_INCLUDED #include <nt2/trigonometric/include/functions/scalar/fast_tan.hpp> #endif
[ "kevinushey@gmail.com" ]
kevinushey@gmail.com
64284224566a505c9afa35bd575e4b9ebdd186b0
48739132eb3f8c43fb632af8e111110125ec43a6
/pad-drop-simulator/calculate_test.cpp
415afc9c633653cbaa121f2dd02d3e3f297c6d0c
[]
no_license
dkwingsmt/pad-drop-simulator
2bd5eae5157211786c0bb5e064ccde7adc22499a
402444ae78ae32b2312bf75d98087850bf9e1b2f
refs/heads/master
2021-01-21T12:50:17.238667
2017-09-01T10:18:18
2017-09-01T10:18:18
102,101,447
0
0
null
null
null
null
UTF-8
C++
false
false
3,644
cpp
#include "stdafx.h" #include "types.h" #include "calculate.h" #include "utils.h" #include "calculate_test.h" void flagHollows(tCell *table); size_t countHollowGroups(const tCell *table, tCell *filter); void simulateDrop(tCell *table); void translateTable(const char *src, tCell *dst) { for (size_t iRow = 0; iRow < TABLE_HEIGHT; iRow++) { for (size_t iCol = 0; iCol < TABLE_WIDTH; iCol++) { dst[versTablePos<false>(iRow, iCol)] = (tCell)*src - (tCell)'0'; src++; } } } struct ValuePosList { tCell value; std::vector<size_t> pos; }; void tableShouldBe(const tCell *table, tCell defaultVal, const std::vector<ValuePosList> exceptions) { for (size_t iRow = 0; iRow < TABLE_HEIGHT; iRow++) { for (size_t iCol = 0; iCol < TABLE_WIDTH; iCol++) { size_t pos = versTablePos<false>(iRow, iCol); bool isException = false; for (auto exc : exceptions) { for (auto excPos : exc.pos) { if (TABLE_WIDTH * iRow + iCol == excPos) { assert(table[pos] == exc.value); isException = true; } } } if (!isException) { assert(table[pos] == defaultVal); } } } } void test_flagHollows() { tCell table[TABLE_CELL_NUM_MEM]; // All 0 translateTable( "000000" "000000" "000000" "000000" "000000", table ); flagHollows(table); tableShouldBe(table, 0x10, {}); // Isolated translateTable( "110011" "100001" "000000" "100001" "110011", table ); flagHollows(table); tableShouldBe(table, 0x10, { {0x01, {0, 1, 4, 5, 6, 11, 18, 23, 24, 25, 28, 29}} }); // Isolated translateTable( "100001" "000010" "110010" "000000" "100001", table ); flagHollows(table); tableShouldBe(table, 0x10, { { 0x01, { 0, 5, 10, 12, 13, 16, 24, 29 } } }); } void test_countHollowGroups() { tCell table[TABLE_CELL_NUM_MEM]; tCell library[TABLE_CELL_NUM_MEM]; // All 0 translateTable( "000000" "000000" "000000" "000000" "000000", table ); flagHollows(table); assert(countHollowGroups(table, library) == 1); // U shape and O shape translateTable( "000010" "000000" "000000" "100110" "100000", table ); flagHollows(table); assert(countHollowGroups(table, library) == 1); // Snake (late connection) translateTable( "011111" "010001" "011101" "000001" "111111", table ); flagHollows(table); assert(countHollowGroups(table, library) == 2); // Special (non-hollow connects separate hollows) translateTable( "011100" "110000" "100000" "100000" "000000", table ); flagHollows(table); assert(countHollowGroups(table, library) == 3); } void test_simulateDrop() { tCell table[TABLE_CELL_NUM_MEM]; // All 0 translateTable( "000000" "000000" "000000" "000000" "000000", table ); flagHollows(table); simulateDrop(table); tableShouldBe(table, 0x20, {}); // Stairs translateTable( "110022" "111002" "111100" "111112" "000000", table ); flagHollows(table); simulateDrop(table); tableShouldBe(table, 0x20, { { 0x00, { 26, 27, 28, 21, 22, 23 } }, { 0x02, { 11, 16, 17, 29 } } }); } void test_calculateCombo() { tCell table[TABLE_CELL_NUM_MEM]; // All 0 translateTable( "000000" "000000" "000000" "000000" "000000", table ); assert(calculateCombo(table, nullptr) == 1); // 0 combo translateTable( "010101" "101010" "010101" "101010" "010101", table ); assert(calculateCombo(table, nullptr) == 0); translateTable( "010100" "000100" "101010" "110001" "100100", table ); assert(calculateCombo(table, nullptr) == 9); } void runAllTests() { test_flagHollows(); test_countHollowGroups(); test_simulateDrop(); test_calculateCombo(); }
[ "dkwingsmt@gmail.com" ]
dkwingsmt@gmail.com
3c2f7aad617fbe1634adb78a434e542244043d81
b4020318967ccac1a0e08a087184b62751285829
/Source/UT_FrameworkEditor/Private/Npc/Graph/Node/NpcBehaviorGraphNode_RandomBranch.cpp
8f8a34f4360e1fda7668d6c26fd1cfe8b41908ee
[]
no_license
richmondx/UT_Framework
a30dd8a3fc8a88c6955e5df9bb458dd320e74598
2cd70429ce9800c5f179fb10c29deed2c0b47a3e
refs/heads/master
2020-03-25T07:58:51.384554
2018-05-27T15:28:33
2018-05-27T15:28:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,491
cpp
/************************************************************************/ /* UMBRA TOOLS */ /* Maxwell - Axel Clerget */ /************************************************************************/ #include "NpcBehaviorGraphNode_RandomBranch.h" #include "NpcBehaviorTask_RandomBranch.h" #include "NpcBehaviorTask_Default.h" #include "EdGraph/EdGraphPin.h" #include "FrameworkGenerics.h" UNpcBehaviorGraphNode_RandomBranch::UNpcBehaviorGraphNode_RandomBranch(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } void UNpcBehaviorGraphNode_RandomBranch::ReconstructNode() { this->InputPin = this->Pins[0]; this->RefreshAllOutputPins(); FGenericNodeData NodeData = this->Task->NodeData; this->NodePosX = NodeData.NodePosX; this->NodePosY = NodeData.NodePosY; } FText UNpcBehaviorGraphNode_RandomBranch::GetNodeTitle(ENodeTitleType::Type TitleType) const { return FText::FromString("RandomBranch"); } void UNpcBehaviorGraphNode_RandomBranch::AllocateDefaultPins() { check(Pins.Num() == 0); InputPin = CreatePin(EGPD_Input, TEXT("RandomBranch"), FName(), nullptr, TEXT("")); } FLinearColor UNpcBehaviorGraphNode_RandomBranch::GetNodeTitleColor() const { return FLinearColor(0.254706f, 0.187059f, 0.44902f); } void UNpcBehaviorGraphNode_RandomBranch::RefreshAllOutputPins() { this->CleanAllOutputsPin(); if (UNpcBehaviorTask_RandomBranch* RandomBranchTask = Cast<UNpcBehaviorTask_RandomBranch>(this->Task)) { for (int32 Index = 0; Index < RandomBranchTask->Number; ++Index) { if (RandomBranchTask->MultipleTargets.IsValidIndex(Index) == false) { UEdGraphPin* NewPin = CreatePin(EGPD_Output, TEXT("RandomBranch"), FName(), nullptr, TEXT("")); this->MultipleOutputPins.AddUnique(NewPin); FNpcBehaviorTask_MultipleTarget Target; RandomBranchTask->MultipleTargets.Add(Target); } } } } void UNpcBehaviorGraphNode_RandomBranch::OnPropertyUpdated(const FPropertyChangedEvent& PropertyChangedEvent, UProperty* PropertyThatChanged) { if (UNpcBehaviorTask_RandomBranch* RandomBranchTask = Cast<UNpcBehaviorTask_RandomBranch>(this->Task)) { // --- } } TArray<UNpcBehaviorTask_Default*> UNpcBehaviorGraphNode_RandomBranch::GetAllNextTasks() { TArray<UNpcBehaviorTask_Default*> Tasks; for (FNpcBehaviorTask_MultipleTarget Target : Cast<UNpcBehaviorTask_RandomBranch>(this->Task)->MultipleTargets) { Tasks.Add(Target.NextTask); } return Tasks; }
[ "clerget.a@gmail.com" ]
clerget.a@gmail.com
412f183ca989199d0ec33f86fa4f038517802099
32db093028132c1e85b82ee801dc8f494c3b0b90
/Codechef/MayChallenge(NoobQuota)/ValidPaths.cpp
150b39f3e31936cd029a56b7e8d1b5530a172ee4
[]
no_license
gautam-bits/CompetitiveCoding
b0aa13400655505fec48e4909d48b119b5fa895a
d9fb47c8f6bc94b6587cbdec3271ebd2bdf75b41
refs/heads/master
2023-08-16T18:02:07.278849
2021-09-24T09:08:13
2021-09-24T09:08:13
296,126,985
0
0
null
null
null
null
UTF-8
C++
false
false
2,190
cpp
#include <bits/stdc++.h> using namespace std; #define pb push_back #define ll long long #define cnl(x) cout << x << endl #define csp(x) cout << x << " " #define read(x) cin >> x #define fo(i,a,b) for(int i=a;i<b;i++) #define test(t) ll t; cin >> t; fo(tno,1,t+1) #define endl "\n" typedef vector<ll> vi; typedef pair<ll,ll> pi; typedef vector<pi> vpi; typedef vector<vi> vvi; const ll MOD = 1000000007 ; vvi adjList; vector<bool> visited; vi longSum; vi allSum; ll dfs1(ll node){ visited[node] = 1; ll sum = 0; for(ll child : adjList[node]) if(!visited[child]){ ll te = dfs1(child); sum = (sum + te)%MOD; } longSum[node] = (longSum[node] + sum)%MOD; sum = (sum + longSum[node])%MOD; return sum; } void dfs2(ll node) { visited[node] = 1; for(ll child : adjList[node]) if(!visited[child]){ dfs2(child); longSum[node] = (longSum[node] + longSum[child])%MOD; } } void dfs3(ll node) { visited[node] = 1; ll sum = 0; ll temp = 0; for(ll child : adjList[node])if(!visited[child]) { sum = (sum + longSum[child])%MOD; allSum[node] = (allSum[node] - longSum[child]*longSum[child] + MOD*MOD)%MOD; dfs3(child); } allSum[node] = (allSum[node] + sum*sum)%MOD; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); test(t){ // tno[1..t] ll n; read(n); adjList.assign(n,vi()); visited.assign(n,0); longSum.assign(n,1); allSum.assign(n,0); auto addEdge = [](ll u,ll v) { adjList[u].pb(v); adjList[v].pb(u); return; fo(i,0,n-1){ ll u,v; read(u);read(v); u--;v--; addEdge(u,v); } ll ans = 0; dfs1(0); fo(i,0,n) ans =(ans + longSum[i])%MOD; visited.assign(n,0); dfs2(0); visited.assign(n,0); dfs3(0); fo(i,0,n) ans =(ans + allSum[i])%MOD; cnl(ans); } return 0; }
[ "gautammps123456789@gmail.com" ]
gautammps123456789@gmail.com
9a9879ec10042e0e535a5d4f9eeaa93e42ab8688
94c647a218b1111785dca500b95cabfe98ee26d9
/ssdb/src/ssdb/binlog.h
413796c30c3c1a12afa6e4e20e867af8190da39c
[ "BSD-3-Clause", "Apache-2.0", "BSD-4-Clause-UC", "MIT", "BSD-2-Clause" ]
permissive
taihedeveloper/SSDB_Cluster
a417f497e3228a6251574c26c6ad1481624c9d02
b8279dc42af24f8a244842f4d5191b3d1894ce88
refs/heads/master
2021-06-23T16:15:17.326140
2017-08-21T10:22:02
2017-08-21T10:22:02
94,286,919
2
1
null
null
null
null
UTF-8
C++
false
false
2,677
h
/* Copyright (c) 2012-2014 The SSDB Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #ifndef SSDB_BINLOG_H_ #define SSDB_BINLOG_H_ #include <string> #include "leveldb/db.h" #include "leveldb/options.h" #include "leveldb/slice.h" #include "leveldb/status.h" #include "leveldb/write_batch.h" #include "../util/thread.h" #include "../util/bytes.h" class Binlog{ private: std::string buf; static const unsigned int HEADER_LEN = sizeof(uint64_t) + 2; public: Binlog(){} Binlog(uint64_t seq, char type, char cmd, const leveldb::Slice &key, int64_t ttl = 0); int load(const Bytes &s); int load(const leveldb::Slice &s); int load(const std::string &s); uint64_t seq() const; char type() const; char cmd() const; const Bytes key() const; int64_t ttl() const; const char* data() const{ return buf.data(); } int size() const{ return (int)buf.size(); } const std::string repr() const{ return this->buf; } std::string dumps() const; }; // circular queue class BinlogQueue{ private: //#ifdef NDEBUG static const int LOG_QUEUE_SIZE = 20 * 1000 * 1000; //#else // static const int LOG_QUEUE_SIZE = 10000; //#endif leveldb::DB *db; uint64_t min_seq; volatile uint64_t last_seq; uint64_t tran_seq; int capacity; leveldb::WriteBatch batch; volatile bool thread_quit; static void* log_clean_thread_func(void *arg); int del(uint64_t seq); // [start, end] includesive int del_range(uint64_t start, uint64_t end); void merge(); bool enabled; public: Mutex mutex; BinlogQueue(leveldb::DB *db, bool enabled=true); ~BinlogQueue(); void begin(); void rollback(); leveldb::Status commit(); // leveldb put void Put(const leveldb::Slice& key, const leveldb::Slice& value); // leveldb delete void Delete(const leveldb::Slice& key); void add_log(char type, char cmd, const leveldb::Slice &key); void add_log(char type, char cmd, const std::string &key); int get(uint64_t seq, Binlog *log) const; int update(uint64_t seq, char type, char cmd, const std::string &key); void flush(); uint64_t get_last_seq() { return this->last_seq; } /** @returns 1 : log.seq greater than or equal to seq 0 : not found -1: error */ int find_next(uint64_t seq, Binlog *log) const; int find_last(Binlog *log, const leveldb::Snapshot *snapshot = NULL) const; std::string stats() const; }; class Transaction{ private: BinlogQueue *logs; public: Transaction(BinlogQueue *logs){ this->logs = logs; logs->mutex.lock(); logs->begin(); } ~Transaction(){ // it is safe to call rollback after commit logs->rollback(); logs->mutex.unlock(); } }; #endif
[ "wangchangqing@taihe.com" ]
wangchangqing@taihe.com
a3ea90c771508d25a4e3410317d0398b004094c2
4bd4609fe5e592a57a730a3fe9e0f7de6ce7526b
/Release/moc_licensecheck.cpp
11144b16420530cdd45852cb06585158a5c5263b
[]
no_license
HuangGlory/ftrcartctl_u200
38d7f81c5285ff559bf7f7518d87896089b00ad2
2feda0c37844d8bbec212900c2125eae5f9119e3
refs/heads/master
2023-07-07T20:25:27.495393
2021-06-17T06:18:50
2021-06-17T06:18:50
394,573,712
0
0
null
null
null
null
UTF-8
C++
false
false
2,726
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'licensecheck.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.14.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include <memory> #include "../licensecheck.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'licensecheck.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.14.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_LicenseCheck_t { QByteArrayData data[1]; char stringdata0[13]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_LicenseCheck_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_LicenseCheck_t qt_meta_stringdata_LicenseCheck = { { QT_MOC_LITERAL(0, 0, 12) // "LicenseCheck" }, "LicenseCheck" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_LicenseCheck[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; void LicenseCheck::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { Q_UNUSED(_o); Q_UNUSED(_id); Q_UNUSED(_c); Q_UNUSED(_a); } QT_INIT_METAOBJECT const QMetaObject LicenseCheck::staticMetaObject = { { QMetaObject::SuperData::link<QObject::staticMetaObject>(), qt_meta_stringdata_LicenseCheck.data, qt_meta_data_LicenseCheck, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *LicenseCheck::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *LicenseCheck::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_LicenseCheck.stringdata0)) return static_cast<void*>(this); return QObject::qt_metacast(_clname); } int LicenseCheck::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "h_yinwei@foxmail.com" ]
h_yinwei@foxmail.com
5100b3fe15ac09dfe016a42aa470c25c07b548ad
303cb679fdcd8a436dbd373f98da679eefefae01
/LVSerial/Serialization/Style.h
9f1e607fd68472bec0f4f1fb967213020c1a5107
[ "MIT" ]
permissive
rohmer/LVGL_UI_Creator
d812a66ca8e3f8a736b02f074d6fbb324560b881
8ff044064819be0ab52eee89642956a3cc81564b
refs/heads/Dev
2023-02-16T01:25:33.247640
2023-02-09T16:58:50
2023-02-09T16:58:50
209,129,978
37
17
MIT
2023-02-09T16:58:51
2019-09-17T18:35:36
C
UTF-8
C++
false
false
518
h
#pragma once #include <cstdlib> #include <sstream> #include <string> #include <time.h> #include "../../3rdParty/JSON/json.hpp" #include "../../3rdParty/LVGL/lvgl/lvgl.h" #include "LVFont.h" using json = nlohmann::json; namespace Serialization { class Style { public: static json ToJSON(lv_style_t& style); static json ToJSON(lv_style_t& style, std::string name); static const lv_style_t &FromJSON(json j); static bool StyleComp(lv_style_t st1, lv_style_t st2); }; }
[ "rohmer@yahoo.com" ]
rohmer@yahoo.com
87903a7a924ecec06e4ddcf79ba48328817534e7
8ebeffcd7730dda77c72ae92cd4c09b5451dfc73
/CS350_Spring2020/CS350Framework/CS350Framework/Assignment2Tests.cpp
562778212fb02771b1d71f226b6e84523e8f7019
[]
no_license
Javonlxw/personal
0a0f7ac044fc630d49e15b5a93350a938e595f4c
cd29bf7212ba39ed0c88410c19258a2c889750e5
refs/heads/master
2021-05-01T18:23:29.970731
2020-03-30T12:19:01
2020-03-30T12:19:01
121,006,477
0
0
null
null
null
null
UTF-8
C++
false
false
384
cpp
#include "Precompiled.hpp" #include "Application.hpp" #include "Shapes.hpp" #include "Geometry.hpp" #include "Math/Utilities.hpp" #include "DebugDraw.hpp" #include "Components.hpp" #include "SimpleNSquared.hpp" #include "UnitTests.hpp" void InitializeAssignment2Tests() { mTestFns.push_back(AssignmentUnitTestList()); AssignmentUnitTestList& list = mTestFns[1]; }
[ "javonleexw@gmail.com" ]
javonleexw@gmail.com
e5ae30c9afc51e37d2053fb4484d4e071da9eb51
9a9677246703f24121e5472bec1850fa7d998740
/6Shots-V2/CRandom.cpp
e19552aadf4b6a864b5f0f091bb785c8ce94f921
[ "CC0-1.0" ]
permissive
chrisdepas/6Shots-Game
ec02f21d5cb48da612ed25037d3b292b3255c061
2b339b1a367e3421d502e7815548d0b13ea3e32c
refs/heads/master
2021-04-03T10:22:47.210072
2018-08-22T23:27:07
2018-08-22T23:27:07
124,375,434
2
0
null
null
null
null
UTF-8
C++
false
false
541
cpp
#include "stdafx.h" #include "CRandom.h" int CRandom::RandomInt() { return m_RandEngine(); } float CRandom::RandomFloat(float fMin, float fMax) { // Overhead of std::uniform_real_distribution is minimal return std::uniform_real_distribution<float> {fMin, fMax}(m_RandEngine); } int CRandom::RandomInt(int iMin, int iMax) { // Overhead of std::uniform_int_distribution is minimal return std::uniform_int_distribution<int> {iMin, iMax}(m_RandEngine); } int CRandom::RandomInt(int iMax) { return RandomInt(0, iMax); }
[ "cdep@squale.me" ]
cdep@squale.me
2dbfd5dac579818b24fd5495f6ca256b2cff1464
e949d578989d2c6fac3de825a6aff7cc599152d5
/成绩.cpp
6742fa38afb685443eb74848c54e29c0e47cc259
[]
no_license
20180309/C-
822b4d1517a1440c65350fd3b5ac3f3d23d87dc9
267223d41b84ee72da4227d23875514c019fdc35
refs/heads/master
2020-03-10T13:34:49.072083
2018-06-19T13:46:54
2018-06-19T13:46:54
129,403,301
0
0
null
null
null
null
GB18030
C++
false
false
435
cpp
#include<stdio.h> #include<math.h> int main() { float grade; printf("请输入成绩小于100的分数grade:"); scanf("%f",&grade); if(grade>100) {printf("输入错误,请输入小于100的成绩grade:\n"); } else if(grade>=90) { printf("A\n"); } else if(grade>=80) { printf("B\n"); } else if(grade>=70) { printf("C\n"); } else if(grade>=60) { printf("D\n"); } else { printf("E\n"); } return 0; }
[ "2457099326@qq.com" ]
2457099326@qq.com
5ea5861d42ce1e7bd9ae14dbd761a29308c51834
0b5f5a38bb3f43ded62b9c1e4f710f882b1155c5
/owRender/R_Shader.h
26ed7b03a52f6fda4efb4add66e09a48079e2510
[ "Apache-2.0" ]
permissive
xuebai5/OpenWow
a3c41d984cebe4dc34e9e3d0530363da4106bb61
97b2738862ce0244fd5b708f4dc3f05db7491f8b
refs/heads/master
2020-04-26T23:16:26.733576
2019-03-03T12:41:04
2019-03-03T12:41:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,161
h
#pragma once // FORWARD BEGIN class RenderDevice; // FORWARD END class R_Shader { public: R_Shader(RenderDevice* _RenderDevice, cstring _name); ~R_Shader(); void createShader(const char *vertexShaderSrc, const char *fragmentShaderSrc, const char *geometryShaderSrc, const char *tessControlShaderSrc, const char *tessEvaluationShaderSrc, const char *computeShaderSrc); void bindShader(); void unbindShader(); int getShaderConstLoc(const char* name); int getShaderSamplerLoc(const char* name); int getShaderBufferLoc(const char* name); void setShaderConst(int loc, R_ShaderConstType type, const void *values, uint32 count = 1); void setShaderSampler(int loc, uint32 texUnit); void runComputeShader(uint32 xDim, uint32 yDim, uint32 zDim); private: uint32 createShaderProgram(const char *vertexShaderSrc, const char *fragmentShaderSrc, const char *geometryShaderSrc, const char *tessControlShaderSrc, const char *tessEvalShaderSrc, const char *computeShaderSrc); bool linkShaderProgram(); public: std::string m_Name; uint32 m_ProgramGLObj; R_InputLayout m_InputLayouts[MaxNumVertexLayouts]; private: RenderDevice* m_RenderDevice; };
[ "alexstenfard@gmail.com" ]
alexstenfard@gmail.com
0e0d60e402a6231a299128b187acb421f2baea0b
afdcb4ae6ab7ea2f7d9ed2cde544c5da3e08e7c6
/Classes/Slash.h
8c5a80258be8f86ae4f59d8b1a30897181c5eb66
[]
no_license
a3845021/thecondorheroesCC2D
cc1dc65aa8107d998f67711e64d36915569bcb01
892700981ccaff72b0c52bd1a8bd8afcf46084aa
refs/heads/master
2020-04-26T02:56:16.415172
2017-05-30T09:51:13
2017-05-30T09:51:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
478
h
#ifndef __SLASH_H__ #define __SLASH_H__ #include "B2Skeleton.h" class Slash : public B2Skeleton { private: CC_SYNTHESIZE(bool, isDie, IsDie); public: Slash(string jsonFile, string atlasFile, float scale); static Slash* create(string jsonFile, string atlasFile, float scale); void initCirclePhysic(b2World *world, Point pos); void updateMe(BaseHero* hero); void setAngle(float radian, float scale); //void runAnimation(); //void die(); }; #endif // __B2_SPRITE_H__
[ "vanthinh061189@gmail.com" ]
vanthinh061189@gmail.com
dbae989f57276915a9a78344548ce95f18970b20
be1ba277fc8d33195498ba14a450a3dcaaf28d25
/My practice12—inheritance and derive.cpp
2eb44153fb266eeed896b2b8254cd1a94ccfbb59
[]
no_license
programAA/DataStructure
869dbeb03f9353099fa5e48450fc5dbe3c96f707
e3f40f2e4d23b1b07e1d706eedc8fa9c9230dfee
refs/heads/master
2021-10-24T06:31:38.164493
2021-10-16T04:32:02
2021-10-16T04:32:02
151,939,720
0
0
null
null
null
null
GB18030
C++
false
false
2,987
cpp
// 分别声明Teacher(教师)类和Cadre(干部)类,采用多重继承方式由这两个类派生出新类Teacher_Cadre(教师兼干部),要求: //(1)在两个基类中都包含有姓名、年龄、性别、地址、电话等数据成员; //(2)在Teacher类中还包含数据成员title(职称),在Cadre类中还包含数据成员post(职务), // 在Teacher_Cadre类中还包含数据成员wages(工资); //(3)对两个基类中的姓名、年龄、性别、地址、电话等数据成员用相同的名字,在引用这些数据成员时,指定作用域; //(4)在类体中声明成员函数,在类外定义成员函数; //(5)在派生类Teacher_Cadre的成员函数show中调用Teacher类中的display函数, // 输出姓名、年龄、性别、地址、电话,然后再用cout语句输出职务和工资。 //派生类的构造函数只能初始化自己的成员函数,而不能初始化基类的成员。 //有时派生类从基类继承了成员,他也可以初始化从基类继承的成员。 #include <iostream> #include <string> using namespace std; class Teacher { private: string name;//姓名 int age;//年龄 string sex;//性别 string address;//地址 string phone;//电话 public: string title;//职称 Teacher(string n, int a, string s, string ad, string p, string t);//构造函数 void display(); }; Teacher::Teacher(string n, int a, string s, string ad, string p, string t) :name(n), age(a), sex(s), address(ad), phone(p), title(t) {} void Teacher::display() { cout << "姓名:" << name << endl; cout << "年龄:" << age << endl; cout << "性别:" << sex << endl; cout << "地址:" << address << endl; cout << "电话:" << phone << endl; cout << "职称:" << title << endl; } class Cadre { private: string name; int age; string sex; string address; string phone; public: string post;//职务 Cadre(string n, int a, string s, string ad, string p, string po); void display(); }; Cadre::Cadre(string n, int a, string s, string ad, string p, string po) :name(n), age(a), sex(s), address(ad), phone(p), post(po) {} void Cadre::display() { cout << "姓名:" << name << endl; cout << "年龄:" << age << endl; cout << "性别:" << sex << endl; cout << "地址:" << address << endl; cout << "电话:" << phone << endl; cout << "职务:" << post << endl; } class Teacher_Cadre :public Teacher, public Cadre { private: int wages;//工资 public: Teacher_Cadre(string n, int a, string s, string ad, string p, string t, string po, int w) :Teacher(n, a, s, ad, p, t), Cadre(n, a, s, ad, p, po) { wages = w; } void display(); }; void Teacher_Cadre::display() { Teacher::display(); cout << "职务:" << post << endl; cout << "工资:" << wages << endl; } int main() { Teacher_Cadre x("lihua", 40, "male", "zhoukoushi", "18465895421", "professor", "dean", 8000); x.display(); x.Teacher::display();//防止二义性,指明继承自哪个基类 x.Cadre::display(); return 0; }
[ "784562470@qq.com" ]
784562470@qq.com
64cd12fbe4c60f19914aa3fc4a3cfeb27f190194
a33b66a7148aaf8ef2e483937c74b5edef12440d
/sketches/lockbud.ino
183c5f913fd5d2aaeffe10751c05d78e575e534b
[]
no_license
Zaidos/lockbud
5b18746fc35529c60c7d1f7d9a2cae56c6dd81e7
7cb2e4c1ca2c20ac2cf60b2787fd986e1ac014e4
refs/heads/master
2016-09-08T05:10:16.656778
2014-10-20T19:22:05
2014-10-20T19:22:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
857
ino
#define LOCK_PIN 6 long openTime = 0.0f; long openDuration = 4000; char incomingByte = 0; char password = 'o'; void setup() { Serial.begin(9600); Serial.println(F("Arduino: Starting Lockbud Server")); pinMode(LOCK_PIN, OUTPUT); resetLock(); } void loop() { if (Serial.available() > 0) { incomingByte = Serial.read(); Serial.println(incomingByte); if (incomingByte == password) { openLock(); } } if (openTime && (millis() - openTime > openDuration)) { resetLock(); } } void openLock() { if (openTime > 0.0f) { Serial.println(F("Arduino: Lock is already open.")); return; } Serial.println(F("Arduino: Opening lock")); openTime = millis(); digitalWrite(LOCK_PIN, HIGH); } void resetLock() { Serial.println(F("Arduino: Resetting lock")); digitalWrite(LOCK_PIN, LOW); openTime = 0.0f; }
[ "nevlad@gmail.com" ]
nevlad@gmail.com
d2035e69f46470c7d2cd7ff0fda85899d16d123f
a5e00504919bb338910de4cc5c3c3c4afb71e8c6
/CodeForces/contest/1321/f.cpp
b3b26dc0c960de9940664abf32544012da0a0889
[]
no_license
samuel21119/Cpp
f55333a6e012e020dd45b54d8fff59a339d0f808
056a6570bd28dd795f66f31c82537c79eb57cc72
refs/heads/master
2023-01-05T15:14:55.357393
2020-10-20T23:32:20
2020-10-20T23:32:20
168,485,083
0
0
null
null
null
null
UTF-8
C++
false
false
2,312
cpp
/************************************************************************* > File Name: f.cpp > Author: Samuel > Mail: enminghuang21119@gmail.com > Created Time: Tue Mar 3 15:24:39 2020 *************************************************************************/ #include <bits/stdc++.h> using namespace std; typedef long long ll; const ll mod = 99999989; const ll mul = 9487; int n; bool in[200010]; int sum[200010]; vector<int> v; ll ha[2][200010]; ll dp[200010]; ll calc(int times) { if (times <= 0) return dp[0] = 1; if (dp[times]) return dp[times]; return dp[times] = calc(times - 1) * mul % mod; } int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> n; v.emplace_back(0); for (int i = 1; i <= n; i++) { char a; cin >> a; a -= '0'; in[i] = a; sum[i] = !a + sum[i - 1]; if (!a) v.emplace_back(i); } int len = v.size(); ha[0][0] = 0; ha[1][0] = 0; ll m = mul; for (int i = 1; i < len; i++) { ha[0][i] = (ha[0][i - 1] * m + (v[i] & 1)) % mod; ha[1][i] = (ha[1][i - 1] * m + !(v[i] & 1)) % mod; } ha[0][len] = ha[0][len - 1]; int t; cin >> t; while (t--) { int l1, l2, m; cin >> l1 >> l2 >> m; if (l2 < l1) swap(l1, l2); if (sum[l1 + m - 1] - sum[l1 - 1] != sum[l2 + m - 1] - sum[l2 - 1]) { cout << "No" << '\n'; continue; } ll ptrx1 = lower_bound(v.begin(), v.end(), l1) - v.begin(); ll ptrx2 = ptrx1 + sum[l1 + m - 1] - sum[l1 - 1] - 1; ll ptry1 = lower_bound(v.begin(), v.end(), l2) - v.begin(); ll ptry2 = ptry1 + sum[l1 + m - 1] - sum[l1 - 1] - 1; int t1 = (l1 & 1); int t2 = (l2 & 1); ll hash1 = ha[t1][ptrx2] - ha[t1][ptrx1 - 1] * calc(ptrx2 - ptrx1 + 1) % mod; ll hash2 = ha[t2][ptry2] - ha[t2][ptry1 - 1] * calc(ptry2 - ptry1 + 1) % mod; if (hash1 < 0) hash1 += mod; if (hash2 < 0) hash2 += mod; //cout << hash1 << ' ' << hash2 << ' ' << ptrx1 << ' ' << ptry1 << ' ' << ptrx2 << ' ' << ptry2 << ' ' << t1 << ' ' << t2 <<'\n'; if (hash1 == hash2) cout << "Yes"; else cout << "No"; cout << '\n'; } return 0; }
[ "enminghuang21119@gmail.com" ]
enminghuang21119@gmail.com
92867f91334b4b73d7ff5e29646807380f718e79
bbeb7e4c334f9f33ea1106810a7113b58f281b27
/AtCoder/Beginner/Beginner Contest 055/A.cpp
d6f17a7c260143619be1926891531f70741472fb
[]
no_license
Drone-Banks/ACM
18638af3f3307ecb26dc5e79d0a06d58c87dedaf
937224c32f8a00ce4885f12ffd83e35b9c99718c
refs/heads/master
2021-04-15T13:41:20.077221
2018-04-16T13:17:33
2018-04-16T13:17:33
126,587,158
0
0
null
null
null
null
UTF-8
C++
false
false
823
cpp
/************************************************************************* > File Name: test.cpp > Author: Akira > Mail: qaq.febr2.qaq@gmail.com ************************************************************************/ #include<bits/stdc++.h> typedef long long LL; typedef unsigned long long ULL; typedef long double LD; #define MST(a,b) memset(a,b,sizeof(a)) #define CLR(a) MST(a,0) #define Sqr(a) ((a)*(a)) using namespace std; #define MaxN 100001 #define MaxM MaxN*10 #define INF 0x3f3f3f3f #define PI 3.1415926535897932384626 const int mod = 1E9+7; const double eps = 1e-6; #define bug cout<<88888888<<endl; #define debug(x) cout << #x" = " << x << endl; int N; int main() { //std::ios::sync_with_stdio(false); scanf("%d\n", &N); printf("%d\n", N*800-(N/15)*200); //system("pause"); }
[ "qaq.febr2.qaq@gmail.com" ]
qaq.febr2.qaq@gmail.com
1afd518bd203a8b41945bdc28b696d567e0e9b61
a926089ebc425d33d3f1a8fd2fd1d99437104784
/ErrorChecking.h
8f4b310d0ec9583d64b4fa1fb729f6423e92f005
[]
no_license
Eliminater30013/Book-Management-System
81ca23cc937943f6ea9b0caa90ce8ca06f4b5a4a
d1e6b3e60bf962b4231b7f0dabaa0f1c999376f7
refs/heads/master
2022-12-08T06:38:06.187404
2020-09-01T13:32:09
2020-09-01T13:32:09
264,035,060
2
0
null
null
null
null
UTF-8
C++
false
false
297
h
#pragma once #include <iostream> #include <string> using namespace std; /*Function Declarations*/ int CheckUsername(string username, string password, char option); // ensure that this has error checking to ensure that username > 20; istream& getline(istream& ins, int& n); string getDate_Time();
[ "ahmedosman30013@gmail.com" ]
ahmedosman30013@gmail.com
da709b79d76118a095e197098a12fe4ca392fbb0
988413076cd53832ed9b0041770b64346f162201
/src/misaxx-core/include/misaxx/core/misa_default_description_accessors.h
a5853212b5bffb6346d209e33a8cf089fdd34d3a
[ "BSD-2-Clause" ]
permissive
applied-systems-biology/misa-framework
1a1edb7208009e92d8e34e6e749f1efe6a758840
e7a303ccfd79e41f45df5fa79e52e24bdf4123d9
refs/heads/master
2023-08-20T12:46:10.905828
2023-08-12T12:19:06
2023-08-12T12:19:06
181,515,264
2
2
null
2023-09-06T18:43:36
2019-04-15T15:27:13
HTML
UTF-8
C++
false
false
1,464
h
/** * Copyright by Ruman Gerst * Research Group Applied Systems Biology - Head: Prof. Dr. Marc Thilo Figge * https://www.leibniz-hki.de/en/applied-systems-biology.html * HKI-Center for Systems Biology of Infection * Leibniz Institute for Natural Product Research and Infection Biology - Hans Knöll Insitute (HKI) * Adolf-Reichwein-Straße 23, 07745 Jena, Germany * * This code is licensed under BSD 2-Clause * See the LICENSE file provided with this code for the full license. */ #pragma once namespace misaxx { /** * Convenience type for creating accessors. * @tparam Pattern The pattern that is associated to the underlying cache * @tparam Description The description that is associated to the underlying cache */ template<class Pattern, class Description, class Derived> struct misa_default_description_accessors { const Pattern &get_data_pattern() const { return static_cast<const Derived*>(this)->describe()->template get<Pattern>(); } const Description &get_data_description() const { return static_cast<const Derived*>(this)->describe()->template get<Description>(); } }; /** * Derives misa_default_description_accessors from a cache type */ template<class Cache, class Derived> using misa_description_accessors_from_cache = misa_default_description_accessors<typename Cache::pattern_type, typename Cache::description_type, Derived>; }
[ "ruman.gerst@leibniz-hki.de" ]
ruman.gerst@leibniz-hki.de
1d54407392e152630cd302bfb45eb65f42d49ab7
58a0ba5ee99ec7a0bba36748ba96a557eb798023
/Olympiad Solutions/DMOJ/dmpg18g3.cpp
bc004e72840f4d29ac49a01d35d38e0257edd996
[ "MIT" ]
permissive
adityanjr/code-DS-ALGO
5bdd503fb5f70d459c8e9b8e58690f9da159dd53
1c104c33d2f56fe671d586b702528a559925f875
refs/heads/master
2022-10-22T21:22:09.640237
2022-10-18T15:38:46
2022-10-18T15:38:46
217,567,198
40
54
MIT
2022-10-18T15:38:47
2019-10-25T15:50:28
C++
UTF-8
C++
false
false
3,932
cpp
// Ivan Carvalho // Solution to https://dmoj.ca/problem/dmpg18g3 #include <bits/stdc++.h> #define LSOne(S) (S & (-S)) using namespace std; typedef tuple<int,int,int> tupla; const int MAXN = 2*1e5 + 10; int BUCKET; long long respostas[MAXN],frequencias[MAXN],quadrados[MAXN],total[MAXN]; int sz[MAXN],nivel[MAXN],N,Q,ini[MAXN],fim[MAXN],vetor[MAXN],dfsPtr,pai[MAXN],pesado[MAXN],range_update[MAXN]; int bit[MAXN],MAXIMO; vector<int> grafo[MAXN]; vector<tupla> perguntas[MAXN]; void dfs_precalculo(int v,int p){ pai[v] = p; ini[v] = ++dfsPtr; vetor[dfsPtr] = v; sz[v] = 1; for(int u : grafo[v]){ if(u == p) continue; nivel[u] = nivel[v] + 1; dfs_precalculo(u,v); sz[v] += sz[u]; } fim[v] = dfsPtr; } void processa_pesado(int v){ for(int i = 0;i<=MAXIMO;i++){ range_update[i] = quadrados[i] = total[i] = 0; } for(int u : grafo[v]){ if(u == pai[v]) continue; int min_h = nivel[v] + 1, max_h = nivel[v] + 1; for(int i = ini[u];i<=fim[u];i++){ int w = vetor[i]; max_h = max(max_h,nivel[w]); frequencias[nivel[w]]++; total[nivel[w]]++; } for(int i = min_h;i<=max_h;i++){ frequencias[i] += frequencias[i-1]; quadrados[i] += frequencias[i]*frequencias[i]; } range_update[max_h + 1] += frequencias[max_h]*frequencias[max_h]; for(int i = min_h;i<=max_h;i++){ frequencias[i] = 0; } } total[nivel[v]]++; for(int i = 1;i<=MAXIMO;i++) total[i] += total[i-1]; for(int i = 1;i<=MAXIMO;i++){ range_update[i] += range_update[i-1]; quadrados[i] += range_update[i]; } for(tupla davez : perguntas[v]){ int id = get<0>(davez),hi = get<1>(davez); respostas[id] = (total[hi])*(total[hi]) - (quadrados[hi]); respostas[id]++; respostas[id] /= 2; } } void update(int idx,int val){ while(idx <= MAXIMO){ bit[idx] += val; idx += LSOne(idx); } } int read(int idx){ int ans = 0; while(idx > 0){ ans += bit[idx]; idx -= LSOne(idx); } return ans; } void dfs_sack(int v,int p,int keep){ int mx = -1,big = -1; for(int u : grafo[v]){ if(u == p) continue; if(sz[u] > mx){ mx = sz[u]; big = u; } } for(int u : grafo[v]){ if(u == p || u == big) continue; dfs_sack(u,v,0); } if(big != -1) dfs_sack(big,v,1); update(nivel[v],1); if(pesado[v]){ for(int u : grafo[v]){ if(u == p || u == big) continue; for(int i = ini[u];i<=fim[u];i++){ int w = vetor[i]; update(nivel[w],1); } } } else{ for(int i = 0;i<perguntas[v].size();i++){ int id = get<0>(perguntas[v][i]), h = get<1>(perguntas[v][i]), tot = 0; tot = read(h); respostas[id] += tot; get<2>(perguntas[v][i]) = tot; } for(int u : grafo[v]){ if(u == p || u == big) continue; for(int i = ini[u];i<=fim[u];i++){ int w = vetor[i]; update(nivel[w],1); for(int j = 0;j<perguntas[v].size();j++){ int id = get<0>(perguntas[v][j]), h = get<1>(perguntas[v][j]), tot = get<2>(perguntas[v][j]); if(nivel[w] <= h) respostas[id] += tot; } } for(int i = ini[u];i<=fim[u];i++){ int w = vetor[i]; for(int j = 0;j<perguntas[v].size();j++){ int id = get<0>(perguntas[v][j]), h = get<1>(perguntas[v][j]); if(nivel[w] <= h) get<2>(perguntas[v][j])++; } } } } if(keep) return; for(int i = ini[v];i<=fim[v];i++){ int u = vetor[i]; update(nivel[u],-1); } } int main(){ scanf("%d",&N); for(int i = 1;i<N;i++){ int u,v; scanf("%d %d",&u,&v); grafo[u].push_back(v); grafo[v].push_back(u); } nivel[1] = 1; dfs_precalculo(1,-1); for(int i = 1;i<=N;i++){ MAXIMO = max(MAXIMO,nivel[i]); } scanf("%d",&Q); for(int i = 1;i<=Q;i++){ int v,d; scanf("%d %d",&v,&d); perguntas[v].push_back(make_tuple(i,min(nivel[v]+d,MAXIMO),0)); } BUCKET = int(sqrt(Q)/(log(MAXIMO)/log(2))); for(int i = 1;i<=N;i++) pesado[i] = (perguntas[i].size() >= BUCKET); dfs_sack(1,-1,1); for(int i = 1;i<=N;i++) if(pesado[i]) processa_pesado(i); for(int i = 1;i<=Q;i++) printf("%lld\n",respostas[i]); return 0; }
[ "samant04aditya@gmail.com" ]
samant04aditya@gmail.com
d49c74b7694d4f8190d9e79b20de9da9ad21a75c
fa0c642ba67143982d3381f66c029690b6d2bd17
/Source/Engine/Platform/TJoystick.h
fc40ea35f5736ed07be9dd745105e1b04eea0542
[ "MIT" ]
permissive
blockspacer/EasyGameEngine
3f605fb2d5747ab250ef8929b0b60e5a41cf6966
da0b0667138573948cbd2e90e56ece5c42cb0392
refs/heads/master
2023-05-05T20:01:31.532452
2021-06-01T13:35:54
2021-06-01T13:35:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,869
h
//! @file TJoystick.h //! @author LiCode //! @version 1.1.0.621 //! @date 2011/01/17 //! Copyright 2009-2010 LiCode's Union. #pragma once namespace EGE { //---------------------------------------------------------------------------- // TJoystick //---------------------------------------------------------------------------- template< typename Type > class TJoystick : public INTERFACE_OBSERVER_IMPL( Type ) { protected: //! The joystick ID _dword mID; //! The ranges DwordRange mXRange; DwordRange mYRange; //! The notifier IJoystickNotifierRef mNotifier; protected: //! When dispatch key event. virtual _ubool OnDispatchKeyEvent( _handle key_event ) PURE; //! When dispatch generic motion event. virtual _ubool OnDispatchGenericMotionEvent( _handle key_event ) PURE; //! When move. virtual _void OnMove( const PointI& pos ) PURE; //! When z-move. virtual _void OnZMove( _int z_pos ) PURE; //! When button up. virtual _void OnButtonUp( _dword flags ) PURE; //! When button down. virtual _void OnButtonDown( _dword flags ) PURE; protected: TJoystick( _dword id, const DwordRange& x_range, const DwordRange& y_range ); virtual ~TJoystick( ); // IObserver Interface public: virtual _void Notify( const EventBase& event, const IObject* object, const IObservable* generator ) override; // IJoystick Interface public: virtual _dword GetID( ) const override; virtual _void SetNotifier( IJoystickNotifier* notifier ) override; virtual IJoystickNotifierRef GetNotifier( ) override; }; //---------------------------------------------------------------------------- // TJoystick Implementation //---------------------------------------------------------------------------- template< typename Type > TJoystick< Type >::TJoystick( _dword id, const DwordRange& x_range, const DwordRange& y_range ) { mID = id; mXRange = x_range; mYRange = y_range; mNotifier = &NullEngine::GetInstance( ).GetJoystickNotifier( ); } template< typename Type > TJoystick< Type >::~TJoystick( ) { } template< typename Type > _void TJoystick< Type >::Notify( const EventBase& event, const IObject* object, const IObservable* generator ) { switch ( event.mEventID ) { case _EVENT_DISPATCHED_KEY: { const EventDispatchedKey& msg = (const EventDispatchedKey&) event; // Force to modify it ((EventDispatchedKey&) msg).mHandled = OnDispatchKeyEvent( msg.mEvent ); } break; case _EVENT_DISPATCHED_GENERIC_MOTION: { const EventDispatchedGenericMotion& msg = (const EventDispatchedGenericMotion&) event; // Force to modify it ((EventDispatchedGenericMotion&) msg).mHandled = OnDispatchGenericMotionEvent( msg.mEvent ); } break; case _EVENT_JOYSTICK_MOVE: { const EventJoystickMove& msg = (const EventJoystickMove&) event; if ( msg.mID == mID ) OnMove( msg.mPosition ); } break; case _EVENT_JOYSTICK_ZMOVE: { const EventJoystickZMove& msg = (const EventJoystickZMove&) event; if ( msg.mID == mID ) OnZMove( msg.mZPosition ); } break; case _EVENT_JOYSTICK_BUTTON_UP: { const EventJoystickButtonUp& msg = (const EventJoystickButtonUp&) event; if ( msg.mID == mID ) OnButtonUp( msg.mFlags ); } break; case _EVENT_JOYSTICK_BUTTON_DOWN: { const EventJoystickButtonDown& msg = (const EventJoystickButtonDown&) event; if ( msg.mID == mID ) OnButtonDown( msg.mFlags ); } break; default: break; } } template< typename Type > _dword TJoystick< Type >::GetID( ) const { return mID; } template< typename Type > _void TJoystick< Type >::SetNotifier( IJoystickNotifier* notifier ) { if ( notifier == _null ) mNotifier = &NullEngine::GetInstance( ).GetJoystickNotifier( ); else mNotifier = notifier; } template< typename Type > IJoystickNotifierRef TJoystick< Type >::GetNotifier( ) { return mNotifier; } }
[ "zopenge@126.com" ]
zopenge@126.com
60ea6c20f204d996e8cce3948d49b8dde18f7775
c602c1b4a2fd92ac70dfab173ec1d35c989a0e36
/src/Events/HoldEvent.h
04cb9192d635ffae3992fbabccda164385f4954b
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
alfredtorch/SimpleButton
7f3146830250feae2b6dc1012cfbe20b7132b268
0ed5af22be4e8a8d911efdc551a344e217fa363f
refs/heads/master
2020-11-30T16:15:17.293840
2020-04-09T14:22:21
2020-04-09T14:22:21
230,439,153
0
0
MIT
2019-12-27T12:21:24
2019-12-27T12:21:23
null
UTF-8
C++
false
false
425
h
#ifndef SimpleButton_HoldEvent_h #define SimpleButton_HoldEvent_h #include "Event.h" namespace simplebutton { class HoldEvent : public Event { public: HoldEvent(ButtonEventFunction, uint32_t interval); ~HoldEvent(); uint8_t getMode(); uint32_t getInterval(); private: uint32_t interval = 0; }; } #endif // ifndef SimpleButton_HoldEvent_h
[ "stef.1497@gmail.com" ]
stef.1497@gmail.com
f8f3bac50c874898d73f23d9bbf170b1907d3b25
ed5669151a0ebe6bcc8c4b08fc6cde6481803d15
/test/magma-1.6.0/src/cheevr_gpu.cpp
315d9ba6bcb294a3da25db22bec55b1168cfdd84
[]
no_license
JieyangChen7/DVFS-MAGMA
1c36344bff29eeb0ce32736cadc921ff030225d4
e7b83fe3a51ddf2cad0bed1d88a63f683b006f54
refs/heads/master
2021-09-26T09:11:28.772048
2018-05-27T01:45:43
2018-05-27T01:45:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,063
cpp
/* -- MAGMA (version 1.6.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date November 2014 @author Raffaele Solca @author Azzam Haidar @generated from zheevr_gpu.cpp normal z -> c, Sat Nov 15 19:54:09 2014 */ #include "common_magma.h" /** Purpose ------- CHEEVR computes selected eigenvalues and, optionally, eigenvectors of a complex Hermitian matrix T. Eigenvalues and eigenvectors can be selected by specifying either a range of values or a range of indices for the desired eigenvalues. Whenever possible, CHEEVR calls CSTEGR to compute the eigenspectrum using Relatively Robust Representations. CSTEGR computes eigenvalues by the dqds algorithm, while orthogonal eigenvectors are computed from various "good" L D L^T representations (also known as Relatively Robust Representations). Gram-Schmidt orthogonalization is avoided as far as possible. More specifically, the various steps of the algorithm are as follows. For the i-th unreduced block of T, 1. Compute T - sigma_i = L_i D_i L_i^T, such that L_i D_i L_i^T is a relatively robust representation, 2. Compute the eigenvalues, lambda_j, of L_i D_i L_i^T to high relative accuracy by the dqds algorithm, 3. If there is a cluster of close eigenvalues, "choose" sigma_i close to the cluster, and go to step (a), 4. Given the approximate eigenvalue lambda_j of L_i D_i L_i^T, compute the corresponding eigenvector by forming a rank-revealing twisted factorization. The desired accuracy of the output can be specified by the input parameter ABSTOL. For more details, see "A new O(n^2) algorithm for the symmetric tridiagonal eigenvalue/eigenvector problem", by Inderjit Dhillon, Computer Science Division Technical Report No. UCB//CSD-97-971, UC Berkeley, May 1997. Note 1 : CHEEVR calls CSTEGR when the full spectrum is requested on machines which conform to the ieee-754 floating point standard. CHEEVR calls SSTEBZ and CSTEIN on non-ieee machines and when partial spectrum requests are made. Normal execution of CSTEGR may create NaNs and infinities and hence may abort due to a floating point exception in environments which do not handle NaNs and infinities in the ieee standard default manner. Arguments --------- @param[in] jobz magma_vec_t - = MagmaNoVec: Compute eigenvalues only; - = MagmaVec: Compute eigenvalues and eigenvectors. @param[in] range magma_range_t - = MagmaRangeAll: all eigenvalues will be found. - = MagmaRangeV: all eigenvalues in the half-open interval (VL,VU] will be found. - = MagmaRangeI: the IL-th through IU-th eigenvalues will be found. @param[in] uplo magma_uplo_t - = MagmaUpper: Upper triangle of A is stored; - = MagmaLower: Lower triangle of A is stored. @param[in] n INTEGER The order of the matrix A. N >= 0. @param[in,out] dA COMPLEX array, dimension (LDDA, N) On entry, the Hermitian matrix A. If UPLO = MagmaUpper, the leading N-by-N upper triangular part of A contains the upper triangular part of the matrix A. If UPLO = MagmaLower, the leading N-by-N lower triangular part of A contains the lower triangular part of the matrix A. On exit, DA is destroyed. @param[in] ldda INTEGER The leading dimension of the array A. LDDA >= max(1,N). @param[in] vl REAL @param[in] vu REAL If RANGE=MagmaRangeV, the lower and upper bounds of the interval to be searched for eigenvalues. VL < VU. Not referenced if RANGE = MagmaRangeAll or MagmaRangeI. @param[in] il INTEGER @param[in] iu INTEGER If RANGE=MagmaRangeI, the indices (in ascending order) of the smallest and largest eigenvalues to be returned. 1 <= IL <= IU <= N, if N > 0; IL = 1 and IU = 0 if N = 0. Not referenced if RANGE = MagmaRangeAll or MagmaRangeV. @param[in] abstol REAL The absolute error tolerance for the eigenvalues. An approximate eigenvalue is accepted as converged when it is determined to lie in an interval [a,b] of width less than or equal to ABSTOL + EPS * max( |a|,|b| ), \n where EPS is the machine precision. If ABSTOL is less than or equal to zero, then EPS*|T| will be used in its place, where |T| is the 1-norm of the tridiagonal matrix obtained by reducing A to tridiagonal form. \n See "Computing Small Singular Values of Bidiagonal Matrices with Guaranteed High Relative Accuracy," by Demmel and Kahan, LAPACK Working Note #3. \n If high relative accuracy is important, set ABSTOL to SLAMCH( 'Safe minimum' ). Doing so will guarantee that eigenvalues are computed to high relative accuracy when possible in future releases. The current code does not make any guarantees about high relative accuracy, but furutre releases will. See J. Barlow and J. Demmel, "Computing Accurate Eigensystems of Scaled Diagonally Dominant Matrices", LAPACK Working Note #7, for a discussion of which matrices define their eigenvalues to high relative accuracy. @param[out] m INTEGER The total number of eigenvalues found. 0 <= M <= N. If RANGE = MagmaRangeAll, M = N, and if RANGE = MagmaRangeI, M = IU-IL+1. @param[out] w REAL array, dimension (N) The first M elements contain the selected eigenvalues in ascending order. @param[out] dZ COMPLEX array, dimension (LDDZ, max(1,M)) If JOBZ = MagmaVec, then if INFO = 0, the first M columns of Z contain the orthonormal eigenvectors of the matrix A corresponding to the selected eigenvalues, with the i-th column of Z holding the eigenvector associated with W(i). If JOBZ = MagmaNoVec, then Z is not referenced. Note: the user must ensure that at least max(1,M) columns are supplied in the array Z; if RANGE = MagmaRangeV, the exact value of M is not known in advance and an upper bound must be used. ******* (workspace) If FAST_HEMV is defined DZ should be (LDDZ, max(1,N)) in both cases. @param[in] lddz INTEGER The leading dimension of the array Z. LDZ >= 1, and if JOBZ = MagmaVec, LDZ >= max(1,N). @param[out] isuppz INTEGER ARRAY, dimension ( 2*max(1,M) ) The support of the eigenvectors in Z, i.e., the indices indicating the nonzero elements in Z. The i-th eigenvector is nonzero only in elements ISUPPZ( 2*i-1 ) through ISUPPZ( 2*i ). __Implemented only for__ RANGE = MagmaRangeAll or MagmaRangeI and IU - IL = N - 1 @param wA (workspace) COMPLEX array, dimension (LDWA, N) @param[in] ldwa INTEGER The leading dimension of the array wA. LDWA >= max(1,N). @param wZ (workspace) COMPLEX array, dimension (LDWZ, max(1,M)) @param[in] ldwz INTEGER The leading dimension of the array wZ. LDWZ >= 1, and if JOBZ = MagmaVec, LDWZ >= max(1,N). @param[out] work (workspace) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK[0] returns the optimal LWORK. @param[in] lwork INTEGER The length of the array WORK. LWORK >= (NB+1)*N, where NB is the max of the blocksize for CHETRD \n If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. @param[out] rwork (workspace) REAL array, dimension (LRWORK) On exit, if INFO = 0, RWORK[0] returns the optimal (and minimal) LRWORK. @param[in] lrwork INTEGER The length of the array RWORK. LRWORK >= max(1,24*N). \n If LRWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the RWORK array, returns this value as the first entry of the RWORK array, and no error message related to LRWORK is issued by XERBLA. @param[out] iwork (workspace) INTEGER array, dimension (LIWORK) On exit, if INFO = 0, IWORK[0] returns the optimal (and minimal) LIWORK. @param[in] liwork INTEGER The dimension of the array IWORK. LIWORK >= max(1,10*N). \n If LIWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the IWORK array, returns this value as the first entry of the IWORK array, and no error message related to LIWORK is issued by XERBLA. @param[out] info INTEGER - = 0: successful exit - < 0: if INFO = -i, the i-th argument had an illegal value - > 0: Internal error Further Details --------------- Based on contributions by Inderjit Dhillon, IBM Almaden, USA Osni Marques, LBNL/NERSC, USA Ken Stanley, Computer Science Division, University of California at Berkeley, USA @ingroup magma_cheev_driver ********************************************************************/ extern "C" magma_int_t magma_cheevr_gpu( magma_vec_t jobz, magma_range_t range, magma_uplo_t uplo, magma_int_t n, magmaFloatComplex_ptr dA, magma_int_t ldda, float vl, float vu, magma_int_t il, magma_int_t iu, float abstol, magma_int_t *m, float *w, magmaFloatComplex_ptr dZ, magma_int_t lddz, magma_int_t *isuppz, magmaFloatComplex *wA, magma_int_t ldwa, magmaFloatComplex *wZ, magma_int_t ldwz, magmaFloatComplex *work, magma_int_t lwork, float *rwork, magma_int_t lrwork, magma_int_t *iwork, magma_int_t liwork, magma_int_t *info) { const char* uplo_ = lapack_uplo_const( uplo ); const char* jobz_ = lapack_vec_const( jobz ); const char* range_ = lapack_range_const( range ); magma_int_t ione = 1; float szero = 0.; float sone = 1.; magma_int_t indrd, indre; magma_int_t imax; magma_int_t lopt, itmp1, indree, indrdd; magma_int_t lower, wantz, tryrac; magma_int_t i, j, jj, i__1; magma_int_t alleig, valeig, indeig; magma_int_t iscale, indibl, indifl; magma_int_t indiwo, indisp, indtau; magma_int_t indrwk, indwk; magma_int_t llwork, llrwork, nsplit; magma_int_t lquery, ieeeok; magma_int_t iinfo; magma_int_t lwmin, lrwmin, liwmin; float safmin; float bignum; float smlnum; float eps, tmp1; float anrm; float sigma, d__1; float rmin, rmax; magmaFloat_ptr dwork; lower = (uplo == MagmaLower); wantz = (jobz == MagmaVec); alleig = (range == MagmaRangeAll); valeig = (range == MagmaRangeV); indeig = (range == MagmaRangeI); lquery = (lwork == -1 || lrwork == -1 || liwork == -1); *info = 0; if (! (wantz || (jobz == MagmaNoVec))) { *info = -1; } else if (! (alleig || valeig || indeig)) { *info = -2; } else if (! (lower || (uplo == MagmaUpper))) { *info = -3; } else if (n < 0) { *info = -4; } else if (ldda < max(1,n)) { *info = -6; } else if (lddz < 1 || (wantz && lddz < n)) { *info = -15; } else if (ldwa < max(1,n)) { *info = -18; } else if (ldwz < 1 || (wantz && ldwz < n)) { *info = -20; } else { if (valeig) { if (n > 0 && vu <= vl) { *info = -8; } } else if (indeig) { if (il < 1 || il > max(1,n)) { *info = -9; } else if (iu < min(n,il) || iu > n) { *info = -10; } } } magma_int_t nb = magma_get_chetrd_nb(n); lwmin = n * (nb + 1); lrwmin = 24 * n; liwmin = 10 * n; work[0] = MAGMA_C_MAKE( lwmin, 0 ); rwork[0] = lrwmin; iwork[0] = liwmin; if (lwork < lwmin && ! lquery) { *info = -22; } else if ((lrwork < lrwmin) && ! lquery) { *info = -24; } else if ((liwork < liwmin) && ! lquery) { *info = -26; } if (*info != 0) { magma_xerbla( __func__, -(*info)); return *info; } else if (lquery) { return *info; } *m = 0; /* Check if matrix is very small then just call LAPACK on CPU, no need for GPU */ if (n <= 128) { #ifdef ENABLE_DEBUG printf("--------------------------------------------------------------\n"); printf(" warning matrix too small N=%d NB=%d, calling lapack on CPU \n", (int) n, (int) nb); printf("--------------------------------------------------------------\n"); #endif magmaFloatComplex *a; magma_cmalloc_cpu( &a, n*n ); magma_cgetmatrix(n, n, dA, ldda, a, n); lapackf77_cheevr(jobz_, range_, uplo_, &n, a, &n, &vl, &vu, &il, &iu, &abstol, m, w, wZ, &ldwz, isuppz, work, &lwork, rwork, &lrwork, iwork, &liwork, info); magma_csetmatrix( n, n, a, n, dA, ldda); magma_csetmatrix( n, *m, wZ, ldwz, dZ, lddz); magma_free_cpu(a); return *info; } if (MAGMA_SUCCESS != magma_smalloc( &dwork, n )) { fprintf (stderr, "!!!! device memory allocation error (magma_cheevr_gpu)\n"); *info = MAGMA_ERR_DEVICE_ALLOC; return *info; } --w; --work; --rwork; --iwork; --isuppz; /* Get machine constants. */ safmin = lapackf77_slamch("Safe minimum"); eps = lapackf77_slamch("Precision"); smlnum = safmin / eps; bignum = 1. / smlnum; rmin = magma_ssqrt(smlnum); rmax = magma_ssqrt(bignum); /* Scale matrix to allowable range, if necessary. */ anrm = magmablas_clanhe(MagmaMaxNorm, uplo, n, dA, ldda, dwork); iscale = 0; sigma = 1; if (anrm > 0. && anrm < rmin) { iscale = 1; sigma = rmin / anrm; } else if (anrm > rmax) { iscale = 1; sigma = rmax / anrm; } if (iscale == 1) { d__1 = 1.; magmablas_clascl(uplo, 0, 0, 1., sigma, n, n, dA, ldda, info); if (abstol > 0.) { abstol *= sigma; } if (valeig) { vl *= sigma; vu *= sigma; } } /* Call CHETRD to reduce Hermitian matrix to tridiagonal form. */ indtau = 1; indwk = indtau + n; indre = 1; indrd = indre + n; indree = indrd + n; indrdd = indree + n; indrwk = indrdd + n; llwork = lwork - indwk + 1; llrwork = lrwork - indrwk + 1; indifl = 1; indibl = indifl + n; indisp = indibl + n; indiwo = indisp + n; #ifdef FAST_HEMV magma_chetrd2_gpu(uplo, n, dA, ldda, &rwork[indrd], &rwork[indre], &work[indtau], wA, ldwa, &work[indwk], llwork, dZ, lddz*n, &iinfo); #else magma_chetrd_gpu (uplo, n, dA, ldda, &rwork[indrd], &rwork[indre], &work[indtau], wA, ldwa, &work[indwk], llwork, &iinfo); #endif lopt = n + (magma_int_t)MAGMA_C_REAL(work[indwk]); /* If all eigenvalues are desired and ABSTOL is less than or equal to zero, then call SSTERF or CUNGTR and CSTEQR. If this fails for some eigenvalue, then try SSTEBZ. */ ieeeok = lapackf77_ieeeck( &ione, &szero, &sone); /* If only the eigenvalues are required call SSTERF for all or SSTEBZ for a part */ if (! wantz) { blasf77_scopy(&n, &rwork[indrd], &ione, &w[1], &ione); i__1 = n - 1; if (alleig || (indeig && il == 1 && iu == n)) { lapackf77_ssterf(&n, &w[1], &rwork[indre], info); *m = n; } else { lapackf77_sstebz(range_, "E", &n, &vl, &vu, &il, &iu, &abstol, &rwork[indrd], &rwork[indre], m, &nsplit, &w[1], &iwork[indibl], &iwork[indisp], &rwork[indrwk], &iwork[indiwo], info); } /* Otherwise call CSTEMR if infinite and NaN arithmetic is supported */ } else if (ieeeok == 1) { //printf("MRRR\n"); i__1 = n - 1; blasf77_scopy(&i__1, &rwork[indre], &ione, &rwork[indree], &ione); blasf77_scopy(&n, &rwork[indrd], &ione, &rwork[indrdd], &ione); if (abstol < 2*n*eps) tryrac=1; else tryrac=0; lapackf77_cstemr(jobz_, range_, &n, &rwork[indrdd], &rwork[indree], &vl, &vu, &il, &iu, m, &w[1], wZ, &ldwz, &n, &isuppz[1], &tryrac, &rwork[indrwk], &llrwork, &iwork[1], &liwork, info); if (*info == 0 && wantz) { magma_csetmatrix( n, *m, wZ, ldwz, dZ, lddz ); magma_cunmtr_gpu(MagmaLeft, uplo, MagmaNoTrans, n, *m, dA, ldda, &work[indtau], dZ, lddz, wA, ldwa, &iinfo); } } /* Call SSTEBZ and CSTEIN if infinite and NaN arithmetic is not supported or CSTEMR didn't converge. */ if (wantz && (ieeeok == 0 || *info != 0)) { printf("B/I\n"); *info = 0; lapackf77_sstebz(range_, "B", &n, &vl, &vu, &il, &iu, &abstol, &rwork[indrd], &rwork[indre], m, &nsplit, &w[1], &iwork[indibl], &iwork[indisp], &rwork[indrwk], &iwork[indiwo], info); lapackf77_cstein(&n, &rwork[indrd], &rwork[indre], m, &w[1], &iwork[indibl], &iwork[indisp], wZ, &ldwz, &rwork[indrwk], &iwork[indiwo], &iwork[indifl], info); /* Apply unitary matrix used in reduction to tridiagonal form to eigenvectors returned by CSTEIN. */ magma_csetmatrix( n, *m, wZ, ldwz, dZ, lddz ); magma_cunmtr_gpu(MagmaLeft, uplo, MagmaNoTrans, n, *m, dA, ldda, &work[indtau], dZ, lddz, wA, ldwa, &iinfo); } /* If matrix was scaled, then rescale eigenvalues appropriately. */ if (iscale == 1) { if (*info == 0) { imax = *m; } else { imax = *info - 1; } d__1 = 1. / sigma; blasf77_sscal(&imax, &d__1, &w[1], &ione); } /* If eigenvalues are not in order, then sort them, along with eigenvectors. */ if (wantz) { for (j = 1; j <= *m-1; ++j) { i = 0; tmp1 = w[j]; for (jj = j + 1; jj <= *m; ++jj) { if (w[jj] < tmp1) { i = jj; tmp1 = w[jj]; } } if (i != 0) { itmp1 = iwork[indibl + i - 1]; w[i] = w[j]; iwork[indibl + i - 1] = iwork[indibl + j - 1]; w[j] = tmp1; iwork[indibl + j - 1] = itmp1; magma_cswap(n, dZ + (i-1)*lddz, ione, dZ + (j-1)*lddz, ione); } } } /* Set WORK[0] to optimal complex workspace size. */ work[1] = MAGMA_C_MAKE( lopt, 0 ); rwork[1] = (float) lrwmin; iwork[1] = liwmin; return *info; } /* magma_cheevr_gpu */
[ "cjy7117@gmail.com" ]
cjy7117@gmail.com
7e5575e464ae2529260e384aa7de008400bc3f15
032a44c3e0a7dc77271bb2213467154212a4e5d3
/src/mprmpr/rpc/connection.cc
e2c16f77a57daef948d5feb0cf326befe34811ba
[]
no_license
wqx081/mpr_mpr
94f557e4d1ec696e880f93ce68ce57594da5a11c
cd0546e38f92576df73714088bc59e7f59b645d2
refs/heads/master
2021-01-12T10:25:03.208531
2016-12-21T14:53:15
2016-12-21T14:53:15
76,452,236
1
1
null
null
null
null
UTF-8
C++
false
false
25,343
cc
#include "mprmpr/rpc/connection.h" #include <algorithm> #include <boost/intrusive/list.hpp> #include <gflags/gflags.h> #include <glog/logging.h> #include <iostream> #include <set> #include <stdint.h> #include <string> #include <vector> #include "mprmpr/base/map-util.h" #include "mprmpr/base/strings/human_readable.h" #include "mprmpr/base/strings/substitute.h" #include "mprmpr/rpc/rpc_introspection.pb.h" #include "mprmpr/rpc/constants.h" #include "mprmpr/rpc/messenger.h" #include "mprmpr/rpc/reactor.h" #include "mprmpr/rpc/rpc_controller.h" #include "mprmpr/rpc/rpc_header.pb.h" #include "mprmpr/rpc/sasl_client.h" #include "mprmpr/rpc/sasl_server.h" #include "mprmpr/rpc/transfer.h" //#include "mprmpr/util/debug-util.h" //#include "mprmpr/util/flag_tags.h" //#include "mprmpr/util/logging.h" #include "mprmpr/util/net/sockaddr.h" #include "mprmpr/util/net/ssl_factory.h" #include "mprmpr/util/net/ssl_socket.h" #include "mprmpr/util/status.h" #include "mprmpr/util/trace.h" using std::function; using std::includes; using std::set; using std::shared_ptr; using std::vector; using strings::Substitute; DECLARE_bool(server_require_kerberos); namespace mprmpr { namespace rpc { /// /// Connection /// Connection::Connection(ReactorThread *reactor_thread, Sockaddr remote, Socket* socket, Direction direction) : reactor_thread_(reactor_thread), remote_(std::move(remote)), socket_(socket), direction_(direction), last_activity_time_(MonoTime::Now()), is_epoll_registered_(false), next_call_id_(1), sasl_client_(kSaslAppName, socket), sasl_server_(kSaslAppName, socket), negotiation_complete_(false) { } Status Connection::SetNonBlocking(bool enabled) { return socket_->SetNonBlocking(enabled); } void Connection::EpollRegister(ev::loop_ref& loop) { DCHECK(reactor_thread_->IsCurrentThread()); DVLOG(4) << "Registering connection for epoll: " << ToString(); write_io_.set(loop); write_io_.set(socket_->GetFd(), ev::WRITE); write_io_.set<Connection, &Connection::WriteHandler>(this); if (direction_ == CLIENT && negotiation_complete_) { write_io_.start(); } read_io_.set(loop); read_io_.set(socket_->GetFd(), ev::READ); read_io_.set<Connection, &Connection::ReadHandler>(this); read_io_.start(); is_epoll_registered_ = true; } Connection::~Connection() { // Must clear the outbound_transfers_ list before deleting. CHECK(outbound_transfers_.begin() == outbound_transfers_.end()); // It's crucial that the connection is Shutdown first -- otherwise // our destructor will end up calling read_io_.stop() and write_io_.stop() // from a possibly non-reactor thread context. This can then make all // hell break loose with libev. CHECK(!is_epoll_registered_); } bool Connection::Idle() const { DCHECK(reactor_thread_->IsCurrentThread()); // check if we're in the middle of receiving something InboundTransfer *transfer = inbound_.get(); if (transfer && (transfer->TransferStarted())) { return false; } // check if we still need to send something if (!outbound_transfers_.empty()) { return false; } // can't kill a connection if calls are waiting response if (!awaiting_response_.empty()) { return false; } if (!calls_being_handled_.empty()) { return false; } // We are not idle if we are in the middle of connection negotiation. if (!negotiation_complete_) { return false; } return true; } void Connection::Shutdown(const Status &status) { DCHECK(reactor_thread_->IsCurrentThread()); shutdown_status_ = status.CloneAndPrepend("RPC connection failed"); if (inbound_ && inbound_->TransferStarted()) { double secs_since_active = (reactor_thread_->cur_time() - last_activity_time_).ToSeconds(); LOG(WARNING) << "Shutting down connection " << ToString() << " with pending inbound data (" << inbound_->StatusAsString() << ", last active " << HumanReadableElapsedTime::ToShortString(secs_since_active) << " ago, status=" << status.ToString() << ")"; } // Clear any calls which have been sent and were awaiting a response. for (const car_map_t::value_type &v : awaiting_response_) { CallAwaitingResponse *c = v.second; if (c->call) { c->call->SetFailed(status); } // And we must return the CallAwaitingResponse to the pool car_pool_.Destroy(c); } awaiting_response_.clear(); // Clear any outbound transfers. while (!outbound_transfers_.empty()) { OutboundTransfer *t = &outbound_transfers_.front(); outbound_transfers_.pop_front(); delete t; } read_io_.stop(); write_io_.stop(); is_epoll_registered_ = false; WARN_NOT_OK(socket_->Close(), "Error closing socket"); } void Connection::QueueOutbound(gscoped_ptr<OutboundTransfer> transfer) { DCHECK(reactor_thread_->IsCurrentThread()); if (!shutdown_status_.ok()) { // If we've already shut down, then we just need to abort the // transfer rather than bothering to queue it. transfer->Abort(shutdown_status_); return; } DVLOG(3) << "Queueing transfer: " << transfer->HexDump(); outbound_transfers_.push_back(*transfer.release()); if (negotiation_complete_ && !write_io_.is_active()) { // If we weren't currently in the middle of sending anything, // then our write_io_ interest is stopped. Need to re-start it. // Only do this after connection negotiation is done doing its work. write_io_.start(); } } Connection::CallAwaitingResponse::~CallAwaitingResponse() { DCHECK(conn->reactor_thread_->IsCurrentThread()); } void Connection::CallAwaitingResponse::HandleTimeout(ev::timer &watcher, int revents) { if (remaining_timeout > 0) { if (watcher.remaining() < -1.0) { LOG(WARNING) << "RPC call timeout handler was delayed by " << -watcher.remaining() << "s! This may be due to a process-wide " << "pause such as swapping, logging-related delays, or allocator lock " << "contention. Will allow an additional " << remaining_timeout << "s for a response."; } watcher.set(remaining_timeout, 0); watcher.start(); remaining_timeout = 0; return; } conn->HandleOutboundCallTimeout(this); } void Connection::HandleOutboundCallTimeout(CallAwaitingResponse *car) { DCHECK(reactor_thread_->IsCurrentThread()); DCHECK(car->call); // The timeout timer is stopped by the car destructor exiting Connection::HandleCallResponse() DCHECK(!car->call->IsFinished()); // Mark the call object as failed. car->call->SetTimedOut(); // Drop the reference to the call. If the original caller has moved on after // seeing the timeout, we no longer need to hold onto the allocated memory // from the request. car->call.reset(); // We still leave the CallAwaitingResponse in the map -- this is because we may still // receive a response from the server, and we don't want a spurious log message // when we do finally receive the response. The fact that CallAwaitingResponse::call // is a NULL pointer indicates to the response processing code that the call // already timed out. } // Callbacks after sending a call on the wire. // This notifies the OutboundCall object to change its state to SENT once it // has been fully transmitted. struct CallTransferCallbacks : public TransferCallbacks { public: explicit CallTransferCallbacks(shared_ptr<OutboundCall> call) : call_(std::move(call)) {} virtual void NotifyTransferFinished() OVERRIDE { // TODO: would be better to cancel the transfer while it is still on the queue if we // timed out before the transfer started, but there is still a race in the case of // a partial send that we have to handle here if (call_->IsFinished()) { DCHECK(call_->IsTimedOut()); } else { call_->SetSent(); } delete this; } virtual void NotifyTransferAborted(const Status &status) OVERRIDE { VLOG(1) << "Transfer of RPC call " << call_->ToString() << " aborted: " << status.ToString(); delete this; } private: shared_ptr<OutboundCall> call_; }; void Connection::QueueOutboundCall(const shared_ptr<OutboundCall> &call) { DCHECK(call); DCHECK_EQ(direction_, CLIENT); DCHECK(reactor_thread_->IsCurrentThread()); if (PREDICT_FALSE(!shutdown_status_.ok())) { // Already shutdown call->SetFailed(shutdown_status_); return; } // At this point the call has a serialized request, but no call header, since we haven't // yet assigned a call ID. DCHECK(!call->call_id_assigned()); // Assign the call ID. int32_t call_id = GetNextCallId(); call->set_call_id(call_id); // Serialize the actual bytes to be put on the wire. slices_tmp_.clear(); Status s = call->SerializeTo(&slices_tmp_); if (PREDICT_FALSE(!s.ok())) { call->SetFailed(s); return; } call->SetQueued(); scoped_car car(car_pool_.make_scoped_ptr(car_pool_.Construct())); car->conn = this; car->call = call; // Set up the timeout timer. const MonoDelta &timeout = call->controller()->timeout(); if (timeout.Initialized()) { reactor_thread_->RegisterTimeout(&car->timeout_timer); car->timeout_timer.set<CallAwaitingResponse, // NOLINT(*) &CallAwaitingResponse::HandleTimeout>(car.get()); // For calls with a timeout of at least 500ms, we actually run the timeout // handler in two stages. The first timeout fires with a timeout 10% less // than the user-specified one. It then schedules a second timeout for the // remaining amount of time. // // The purpose of this two-stage timeout is to be more robust when the client // has some process-wide pause, such as lock contention in tcmalloc, or a // reactor callback that blocks in glog. Consider the following case: // // T = 0s user issues an RPC with 5 second timeout // T = 0.5s - 6s process is blocked // T = 6s process unblocks, and the timeout fires (1s late) // // Without the two-stage timeout, we would determine that the call had timed out, // even though it's likely that the response is waiting on our TCP socket. // With the two-stage timeout, we'll end up with: // // T = 0s user issues an RPC with 5 second timeout // T = 0.5s - 6s process is blocked // T = 6s process unblocks, and the first-stage timeout fires (1.5s late) // T = 6s - 6.200s time for the client to read the response which is waiting // T = 6.200s if the response was not actually available, we'll time out here // // We don't bother with this logic for calls with very short timeouts - assumedly // a user setting such a short RPC timeout is well equipped to handle one. double time = timeout.ToSeconds(); if (time >= 0.5) { car->remaining_timeout = time * 0.1; time -= car->remaining_timeout; } else { car->remaining_timeout = 0; } car->timeout_timer.set(time, 0); car->timeout_timer.start(); } TransferCallbacks *cb = new CallTransferCallbacks(call); awaiting_response_[call_id] = car.release(); QueueOutbound(gscoped_ptr<OutboundTransfer>( OutboundTransfer::CreateForCallRequest(call_id, slices_tmp_, cb))); } // Callbacks for sending an RPC call response from the server. // This takes ownership of the InboundCall object so that, once it has // been responded to, we can free up all of the associated memory. struct ResponseTransferCallbacks : public TransferCallbacks { public: ResponseTransferCallbacks(gscoped_ptr<InboundCall> call, Connection *conn) : call_(std::move(call)), conn_(conn) {} ~ResponseTransferCallbacks() { // Remove the call from the map. InboundCall *call_from_map = EraseKeyReturnValuePtr( &conn_->calls_being_handled_, call_->call_id()); DCHECK_EQ(call_from_map, call_.get()); } virtual void NotifyTransferFinished() OVERRIDE { delete this; } virtual void NotifyTransferAborted(const Status &status) OVERRIDE { LOG(WARNING) << "Connection torn down before " << call_->ToString() << " could send its response"; delete this; } private: gscoped_ptr<InboundCall> call_; Connection *conn_; }; // Reactor task which puts a transfer on the outbound transfer queue. class QueueTransferTask : public ReactorTask { public: QueueTransferTask(gscoped_ptr<OutboundTransfer> transfer, Connection *conn) : transfer_(std::move(transfer)), conn_(conn) {} virtual void Run(ReactorThread *thr) OVERRIDE { conn_->QueueOutbound(std::move(transfer_)); delete this; } virtual void Abort(const Status &status) OVERRIDE { transfer_->Abort(status); delete this; } private: gscoped_ptr<OutboundTransfer> transfer_; Connection *conn_; }; void Connection::QueueResponseForCall(gscoped_ptr<InboundCall> call) { // This is usually called by the IPC worker thread when the response // is set, but in some circumstances may also be called by the // reactor thread (e.g. if the service has shut down) DCHECK_EQ(direction_, SERVER); // If the connection is torn down, then the QueueOutbound() call that // eventually runs in the reactor thread will take care of calling // ResponseTransferCallbacks::NotifyTransferAborted. std::vector<Slice> slices; call->SerializeResponseTo(&slices); TransferCallbacks *cb = new ResponseTransferCallbacks(std::move(call), this); // After the response is sent, can delete the InboundCall object. // We set a dummy call ID and required feature set, since these are not needed // when sending responses. gscoped_ptr<OutboundTransfer> t(OutboundTransfer::CreateForCallResponse(slices, cb)); QueueTransferTask *task = new QueueTransferTask(std::move(t), this); reactor_thread_->reactor()->ScheduleReactorTask(task); } void Connection::set_user_credentials(const UserCredentials &user_credentials) { user_credentials_.CopyFrom(user_credentials); } RpczStore* Connection::rpcz_store() { return reactor_thread_->reactor()->messenger()->rpcz_store(); } void Connection::ReadHandler(ev::io &watcher, int revents) { DCHECK(reactor_thread_->IsCurrentThread()); DVLOG(3) << ToString() << " ReadHandler(revents=" << revents << ")"; if (revents & EV_ERROR) { reactor_thread_->DestroyConnection(this, Status::NetworkError(ToString() + ": ReadHandler encountered an error")); return; } last_activity_time_ = reactor_thread_->cur_time(); while (true) { if (!inbound_) { inbound_.reset(new InboundTransfer()); } Status status = inbound_->ReceiveBuffer(*socket_); if (PREDICT_FALSE(!status.ok())) { if (status.posix_code() == ESHUTDOWN) { VLOG(1) << ToString() << " shut down by remote end."; } else { LOG(WARNING) << ToString() << " recv error: " << status.ToString(); } reactor_thread_->DestroyConnection(this, status); return; } if (!inbound_->TransferFinished()) { DVLOG(3) << ToString() << ": read is not yet finished yet."; return; } DVLOG(3) << ToString() << ": finished reading " << inbound_->data().size() << " bytes"; if (direction_ == CLIENT) { HandleCallResponse(std::move(inbound_)); } else if (direction_ == SERVER) { HandleIncomingCall(std::move(inbound_)); } else { LOG(FATAL) << "Invalid direction: " << direction_; } // TODO: it would seem that it would be good to loop around and see if // there is more data on the socket by trying another recv(), but it turns // out that it really hurts throughput to do so. A better approach // might be for each InboundTransfer to actually try to read an extra byte, // and if it succeeds, then we'd copy that byte into a new InboundTransfer // and loop around, since it's likely the next call also arrived at the // same time. break; } } void Connection::HandleIncomingCall(gscoped_ptr<InboundTransfer> transfer) { DCHECK(reactor_thread_->IsCurrentThread()); gscoped_ptr<InboundCall> call(new InboundCall(this)); Status s = call->ParseFrom(std::move(transfer)); if (!s.ok()) { LOG(WARNING) << ToString() << ": received bad data: " << s.ToString(); // TODO: shutdown? probably, since any future stuff on this socket will be // "unsynchronized" return; } if (!InsertIfNotPresent(&calls_being_handled_, call->call_id(), call.get())) { LOG(WARNING) << ToString() << ": received call ID " << call->call_id() << " but was already processing this ID! Ignoring"; reactor_thread_->DestroyConnection( this, Status::RuntimeError("Received duplicate call id", Substitute("$0", call->call_id()))); return; } reactor_thread_->reactor()->messenger()->QueueInboundCall(std::move(call)); } void Connection::HandleCallResponse(gscoped_ptr<InboundTransfer> transfer) { DCHECK(reactor_thread_->IsCurrentThread()); gscoped_ptr<CallResponse> resp(new CallResponse); CHECK_OK(resp->ParseFrom(std::move(transfer))); CallAwaitingResponse *car_ptr = EraseKeyReturnValuePtr(&awaiting_response_, resp->call_id()); if (PREDICT_FALSE(car_ptr == nullptr)) { LOG(WARNING) << ToString() << ": Got a response for call id " << resp->call_id() << " which " << "was not pending! Ignoring."; return; } // The car->timeout_timer ev::timer will be stopped automatically by its destructor. scoped_car car(car_pool_.make_scoped_ptr(car_ptr)); if (PREDICT_FALSE(car->call.get() == nullptr)) { // The call already failed due to a timeout. VLOG(1) << "Got response to call id " << resp->call_id() << " after client already timed out"; return; } car->call->SetResponse(std::move(resp)); } void Connection::WriteHandler(ev::io &watcher, int revents) { DCHECK(reactor_thread_->IsCurrentThread()); if (revents & EV_ERROR) { reactor_thread_->DestroyConnection(this, Status::NetworkError(ToString() + ": writeHandler encountered an error")); return; } DVLOG(3) << ToString() << ": writeHandler: revents = " << revents; OutboundTransfer *transfer; if (outbound_transfers_.empty()) { LOG(WARNING) << ToString() << " got a ready-to-write callback, but there is " "nothing to write."; write_io_.stop(); return; } while (!outbound_transfers_.empty()) { transfer = &(outbound_transfers_.front()); if (!transfer->TransferStarted()) { if (transfer->is_for_outbound_call()) { CallAwaitingResponse* car = FindOrDie(awaiting_response_, transfer->call_id()); if (!car->call) { // If the call has already timed out, then the 'call' field will have been nulled. // In that case, we don't need to bother sending it. outbound_transfers_.pop_front(); transfer->Abort(Status::Aborted("already timed out")); delete transfer; continue; } // If this is the start of the transfer, then check if the server has the // required RPC flags. We have to wait until just before the transfer in // order to ensure that the negotiation has taken place, so that the flags // are available. const set<RpcFeatureFlag>& required_features = car->call->required_rpc_features(); const set<RpcFeatureFlag>& server_features = sasl_client_.server_features(); if (!includes(server_features.begin(), server_features.end(), required_features.begin(), required_features.end())) { outbound_transfers_.pop_front(); Status s = Status::NotSupported("server does not support the required RPC features"); transfer->Abort(s); car->call->SetFailed(s); car->call.reset(); delete transfer; continue; } } } last_activity_time_ = reactor_thread_->cur_time(); Status status = transfer->SendBuffer(*socket_); if (PREDICT_FALSE(!status.ok())) { LOG(WARNING) << ToString() << " send error: " << status.ToString(); reactor_thread_->DestroyConnection(this, status); return; } if (!transfer->TransferFinished()) { DVLOG(3) << ToString() << ": writeHandler: xfer not finished."; return; } outbound_transfers_.pop_front(); delete transfer; } // If we were able to write all of our outbound transfers, // we don't have any more to write. write_io_.stop(); } std::string Connection::ToString() const { // This may be called from other threads, so we cannot // include anything in the output about the current state, // which might concurrently change from another thread. return strings::Substitute( "$0 $1", direction_ == SERVER ? "server connection from" : "client connection to", remote_.ToString()); } Status Connection::InitSSLIfNecessary() { if (!reactor_thread_->reactor()->messenger()->ssl_enabled()) return Status::OK(); SSLSocket* ssl_socket = down_cast<SSLSocket*>(socket_.get()); RETURN_NOT_OK(ssl_socket->DoHandshake()); return Status::OK(); } Status Connection::InitSaslClient() { // Note that remote_.host() is an IP address here: we've already lost // whatever DNS name the client was attempting to use. Unless krb5 // is configured with 'rdns = false', it will automatically take care // of reversing this address to its canonical hostname to determine // the expected server principal. sasl_client().set_server_fqdn(remote_.host()); Status gssapi_status = sasl_client().EnableGSSAPI(); if (!gssapi_status.ok()) { // If we can't enable GSSAPI, it's likely the client is just missing the // appropriate SASL plugin. We don't want to require it to be installed // if the user doesn't care about connecting to servers using Kerberos // authentication. So, we'll just VLOG this here. If we try to connect // to a server which requires Kerberos, we'll get a negotiation error // at that point. if (VLOG_IS_ON(1)) { //TODO(wqx): // KLOG_FIRST_N(INFO, 1) << "Couldn't enable GSSAPI (Kerberos) SASL plugin: " // << gssapi_status.message().ToString() // << ". This process will be unable to connect to " // << "servers requiring Kerberos authentication."; } } // TODO(todd): we dont seem to ever use ANONYMOUS. Should we remove it? RETURN_NOT_OK(sasl_client().EnableAnonymous()); RETURN_NOT_OK(sasl_client().EnablePlain(user_credentials().real_user(), "")); RETURN_NOT_OK(sasl_client().Init(kSaslProtoName)); return Status::OK(); } Status Connection::InitSaslServer() { if (FLAGS_server_require_kerberos) { RETURN_NOT_OK(sasl_server().EnableGSSAPI()); } else { RETURN_NOT_OK(sasl_server().EnablePlain()); } RETURN_NOT_OK(sasl_server().Init(kSaslProtoName)); return Status::OK(); } // Reactor task that transitions this Connection from connection negotiation to // regular RPC handling. Destroys Connection on negotiation error. class NegotiationCompletedTask : public ReactorTask { public: NegotiationCompletedTask(Connection* conn, const Status& negotiation_status) : conn_(conn), negotiation_status_(negotiation_status) { } virtual void Run(ReactorThread *rthread) OVERRIDE { rthread->CompleteConnectionNegotiation(conn_, negotiation_status_); delete this; } virtual void Abort(const Status &status) OVERRIDE { DCHECK(conn_->reactor_thread()->reactor()->closing()); VLOG(1) << "Failed connection negotiation due to shut down reactor thread: " << status.ToString(); delete this; } private: scoped_refptr<Connection> conn_; Status negotiation_status_; }; void Connection::CompleteNegotiation(const Status& negotiation_status) { auto task = new NegotiationCompletedTask(this, negotiation_status); reactor_thread_->reactor()->ScheduleReactorTask(task); } void Connection::MarkNegotiationComplete() { DCHECK(reactor_thread_->IsCurrentThread()); negotiation_complete_ = true; } Status Connection::DumpPB(const DumpRunningRpcsRequestPB& req, RpcConnectionPB* resp) { DCHECK(reactor_thread_->IsCurrentThread()); resp->set_remote_ip(remote_.ToString()); if (negotiation_complete_) { resp->set_state(RpcConnectionPB::OPEN); resp->set_remote_user_credentials(user_credentials_.ToString()); } else { // It's racy to dump credentials while negotiating, since the Connection // object is owned by the negotiation thread at that point. resp->set_state(RpcConnectionPB::NEGOTIATING); } if (direction_ == CLIENT) { for (const car_map_t::value_type& entry : awaiting_response_) { CallAwaitingResponse *c = entry.second; if (c->call) { c->call->DumpPB(req, resp->add_calls_in_flight()); } } } else if (direction_ == SERVER) { for (const inbound_call_map_t::value_type& entry : calls_being_handled_) { InboundCall* c = entry.second; c->DumpPB(req, resp->add_calls_in_flight()); } } else { LOG(FATAL); } return Status::OK(); } } // namespace rpc } // namespace kudu
[ "you@example.com" ]
you@example.com
41060893b0c97ead5587fc5f96b6965f39c32c83
fa35b79ce696cc78c46d6473d9fbb278a1ea0bf1
/lz/LZRecorderMgr.cpp
ae1683683ca02119a97c493c72a7c0536d510a8d
[]
no_license
hitner/beginner_items
87669225d4f1c6ed96703dcb8e8b9de70e6726d7
e0e00d16d7a8e77e64c255b42c85ee57df4482a0
refs/heads/master
2023-01-07T05:20:04.960105
2020-11-05T02:43:58
2020-11-05T02:43:58
261,348,363
0
0
null
null
null
null
UTF-8
C++
false
false
1,637
cpp
#include "LZRecorderMgr.h" #include "LZRecorder.h" #include "lzconfig.h" LZRecorderMgr::LZRecorderMgr() { } LZRecorderMgr::~LZRecorderMgr(){ stopRecordAll(); } void LZRecorderMgr::startRecord(const std::string & channel){ if (channel.length() > 0) { for (auto it = recorderList_.cbegin(); it != recorderList_.cend(); ++ it) { if (channel.compare((*it)->getChannel()) == 0) { LzLogWarn("warn: start record same channel, %s",channel.c_str()); return; } } LZRecorder * recorder = new LZRecorder(); recorder->joinChannel(channel); recorderList_.push_back(recorder); } } void LZRecorderMgr::stopRecord(const std::string & channel){ if (channel.length() > 0) { for (auto it = recorderList_.cbegin(); it != recorderList_.cend(); ++ it) { if (channel.compare((*it)->getChannel()) == 0) { LZRecorder * tmp = *it; tmp->leaveChannel(); delete tmp; recorderList_.erase(it); return; } } LzLogWarn("warn: no such channel:%s", channel.c_str()); } } void LZRecorderMgr::stopRecordAll(){ for (auto it = recorderList_.cbegin(); it != recorderList_.cend(); ++ it) { (*it)->leaveChannel(); delete (*it); } recorderList_.clear(); } void LZRecorderMgr::stopRecordLast(){ if (!recorderList_.empty()) { LZRecorder * tmp = recorderList_.back(); recorderList_.pop_back(); tmp->leaveChannel(); delete tmp; } else { printf("no record anymore"); } } void LZRecorderMgr::getAllRecordChannel(std::list<std::string> & retList) const { for (auto it = recorderList_.cbegin(); it != recorderList_.cend(); ++ it) { retList.push_back(std::string((*it)->getChannel())); } }
[ "hitner@qq.com" ]
hitner@qq.com
4dbd462c7924657265fcbf8025012083d7752f16
867ee0c866e481939964ad35a8e54d2e2b07fe2a
/d01/ex05_test/Brain.hpp
316db233f2a441f24d2cb5b516b6646fd9ab2b9e
[]
no_license
rjwhobbs/cpp_bootcamp
0db7ceaeeb0b19d898965ceb26b5b84635b36a5d
8edc3bd419ee3587966a14bb3bebcf94c6efa8d4
refs/heads/master
2021-05-18T20:11:31.886529
2020-08-26T08:46:24
2020-08-26T08:46:24
251,397,756
0
0
null
null
null
null
UTF-8
C++
false
false
216
hpp
#ifndef BRAIN_HPP #define BRAIN_HPP #include <string> #include <sstream> class Brain { public: Brain(void); ~Brain(void); std::string identify(void) const; private: std::string _humanAddress; }; #endif
[ "rhobbs@student.wethinkcode.co.za" ]
rhobbs@student.wethinkcode.co.za
93745c4bf50daf27ef29c16b4680888e10f7026c
f37016b7ff0ac795e85b22f4d03168d7e4f2b0e6
/BaseFramework_2/Rasteriser/DirectionalLight.h
cb780dd933d53d81d0daff20c98c37b960ee4b32
[]
no_license
Regilio-Henry/Software-Rendering-Engine
52a481776a6426dc7eec1489c780263011596721
cce564a6cabe9364b8c14587c9fda64c2b2d698f
refs/heads/master
2020-04-20T03:14:32.244756
2019-01-31T20:43:00
2019-01-31T20:43:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
583
h
#include <algorithm> #include "Vector.h" #include <vector> class DirectionaLighting { public: DirectionaLighting(); DirectionaLighting(Vector _lightDirection, float r, float g, float b); ~DirectionaLighting(); void setRed(float redIntensity); float getRed() const; void setBlue(float blueIntensity); float getBlue() const; void setGreen(float greenIntensity); float getGreen() const; Vector getLightDirection() const; void setLightDirection(Vector lightDirection) ; private: float _redIntensity; float _greenIntensity; float _blueIntensity; Vector lightDirection; };
[ "regilio.henry@hotmail.com" ]
regilio.henry@hotmail.com
b62f5f811732aeae38839a0cd0a23ab0656297af
2907470d7ef28a8b83773228228ae2ffaeedc969
/Flocking_Demo/Flocking_Demo/AvoidanceForce.cpp
fd2ffdf733bd366540dcc36ae11b07c7c31127c5
[]
no_license
sparkplug377/AI-for-Games
c39ff5e6119fc0a46ccf621686b9ab722455e6ff
7709e01d2cde74211101b16a91879eea8c0a5a83
refs/heads/master
2020-03-21T01:45:42.715388
2019-05-18T12:00:42
2019-05-18T12:00:42
137,960,753
0
0
null
null
null
null
UTF-8
C++
false
false
647
cpp
#include "AvoidanceForce.h" AvoidanceForce::AvoidanceForce() { } AvoidanceForce::~AvoidanceForce() { } Vector3 AvoidanceForce::getForce(Agent * agent) { Vector3 force = Vector3(0, 0, 0); // get agent's current velocity Vector3 ahead = agent->GetLocalTransform()[2] + agent->GetVelocity(); float distance = ahead.magnitude(); // if the agent is moving if (distance > 0) { // iterate through all the obstacles for (auto o : m_circles) { // check if velocity of the agent intersects with obstacle if (o.IntersectsLine(ahead)) { force = force + (ahead - o.GetPosition()); } } } return force * agent->GetSpeed(); }
[ "rk.amumar@gmail.com" ]
rk.amumar@gmail.com
77d4beec57662294b24d65f76c52f8f49846daa2
119e3839dc83d2f8fca8b8a78a687982cfe25104
/prebuild/VTK-8.1.0.rc1/ThirdParty/vtkm/vtk-m/vtkm/worklet/testing/UnitTestWorkletMapTopologyExplicit.cxx
2fe43836cd8529128f219083a18eaa8342720c50
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
liulihuogyh/osgall
30cdb5c8ca7d3f2c0863ef2da6ff6c1bafb357f1
310530672b69be6afac16f0b9b2f5bd9b3ec60d4
refs/heads/master
2023-04-14T13:01:04.085705
2021-04-24T19:53:50
2021-04-24T19:53:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,695
cxx
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. // // Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS). // Copyright 2014 UT-Battelle, LLC. // Copyright 2014 Los Alamos National Security. // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National // Laboratory (LANL), the U.S. Government retains certain rights in // this software. //============================================================================ #include <vtkm/worklet/DispatcherMapTopology.h> #include <vtkm/worklet/WorkletMapTopology.h> #include <vtkm/worklet/CellAverage.h> #include <vtkm/worklet/PointAverage.h> #include <vtkm/Math.h> #include <vtkm/cont/DataSet.h> #include <vtkm/cont/testing/MakeTestDataSet.h> #include <vtkm/cont/testing/Testing.h> namespace test_explicit { class MaxPointOrCellValue : public vtkm::worklet::WorkletMapPointToCell { public: typedef void ControlSignature(FieldInCell<Scalar> inCells, FieldInPoint<Scalar> inPoints, CellSetIn topology, FieldOutCell<Scalar> outCells); typedef void ExecutionSignature(_1, _4, _2, PointCount, CellShape, PointIndices); typedef _3 InputDomain; VTKM_CONT MaxPointOrCellValue() {} template <typename InCellType, typename OutCellType, typename InPointVecType, typename CellShapeTag, typename PointIndexType> VTKM_EXEC void operator()(const InCellType& cellValue, OutCellType& maxValue, const InPointVecType& pointValues, const vtkm::IdComponent& numPoints, const CellShapeTag& vtkmNotUsed(type), const PointIndexType& vtkmNotUsed(pointIDs)) const { //simple functor that returns the max of cellValue and pointValue maxValue = static_cast<OutCellType>(cellValue); for (vtkm::IdComponent pointIndex = 0; pointIndex < numPoints; ++pointIndex) { maxValue = vtkm::Max(maxValue, static_cast<OutCellType>(pointValues[pointIndex])); } } }; } namespace { static void TestMaxPointOrCell(); static void TestAvgPointToCell(); static void TestAvgCellToPoint(); void TestWorkletMapTopologyExplicit() { typedef vtkm::cont::DeviceAdapterTraits<VTKM_DEFAULT_DEVICE_ADAPTER_TAG> DeviceAdapterTraits; std::cout << "Testing Topology Worklet ( Explicit ) on device adapter: " << DeviceAdapterTraits::GetName() << std::endl; TestMaxPointOrCell(); TestAvgPointToCell(); TestAvgCellToPoint(); } static void TestMaxPointOrCell() { std::cout << "Testing MaxPointOfCell worklet" << std::endl; vtkm::cont::testing::MakeTestDataSet testDataSet; vtkm::cont::DataSet dataSet = testDataSet.Make3DExplicitDataSet0(); vtkm::cont::ArrayHandle<vtkm::Float32> result; vtkm::worklet::DispatcherMapTopology<::test_explicit::MaxPointOrCellValue> dispatcher; dispatcher.Invoke( dataSet.GetField("cellvar"), dataSet.GetField("pointvar"), dataSet.GetCellSet(0), result); std::cout << "Make sure we got the right answer." << std::endl; VTKM_TEST_ASSERT(test_equal(result.GetPortalConstControl().Get(0), 100.1f), "Wrong result for PointToCellMax worklet"); VTKM_TEST_ASSERT(test_equal(result.GetPortalConstControl().Get(1), 100.2f), "Wrong result for PointToCellMax worklet"); } static void TestAvgPointToCell() { std::cout << "Testing AvgPointToCell worklet" << std::endl; vtkm::cont::testing::MakeTestDataSet testDataSet; vtkm::cont::DataSet dataSet = testDataSet.Make3DExplicitDataSet0(); vtkm::cont::ArrayHandle<vtkm::Float32> result; vtkm::worklet::DispatcherMapTopology<vtkm::worklet::CellAverage> dispatcher; dispatcher.Invoke(dataSet.GetCellSet(), dataSet.GetField("pointvar"), result); std::cout << "Make sure we got the right answer." << std::endl; VTKM_TEST_ASSERT(test_equal(result.GetPortalConstControl().Get(0), 20.1333f), "Wrong result for PointToCellAverage worklet"); VTKM_TEST_ASSERT(test_equal(result.GetPortalConstControl().Get(1), 35.2f), "Wrong result for PointToCellAverage worklet"); std::cout << "Try to invoke with an input array of the wrong size." << std::endl; bool exceptionThrown = false; try { dispatcher.Invoke(dataSet.GetCellSet(), dataSet.GetField("cellvar"), // should be pointvar result); } catch (vtkm::cont::ErrorBadValue& error) { std::cout << " Caught expected error: " << error.GetMessage() << std::endl; exceptionThrown = true; } VTKM_TEST_ASSERT(exceptionThrown, "Dispatcher did not throw expected exception."); } static void TestAvgCellToPoint() { std::cout << "Testing AvgCellToPoint worklet" << std::endl; vtkm::cont::testing::MakeTestDataSet testDataSet; vtkm::cont::DataSet dataSet = testDataSet.Make3DExplicitDataSet1(); vtkm::cont::ArrayHandle<vtkm::Float32> result; vtkm::worklet::DispatcherMapTopology<vtkm::worklet::PointAverage> dispatcher; dispatcher.Invoke(dataSet.GetCellSet(), dataSet.GetField("cellvar"), result); std::cout << "Make sure we got the right answer." << std::endl; VTKM_TEST_ASSERT(test_equal(result.GetPortalConstControl().Get(0), 100.1f), "Wrong result for CellToPointAverage worklet"); VTKM_TEST_ASSERT(test_equal(result.GetPortalConstControl().Get(1), 100.15f), "Wrong result for CellToPointAverage worklet"); std::cout << "Try to invoke with an input array of the wrong size." << std::endl; bool exceptionThrown = false; try { dispatcher.Invoke(dataSet.GetCellSet(), dataSet.GetField("pointvar"), // should be cellvar result); } catch (vtkm::cont::ErrorBadValue& error) { std::cout << " Caught expected error: " << error.GetMessage() << std::endl; exceptionThrown = true; } VTKM_TEST_ASSERT(exceptionThrown, "Dispatcher did not throw expected exception."); } } // anonymous namespace int UnitTestWorkletMapTopologyExplicit(int, char* []) { return vtkm::cont::testing::Testing::Run(TestWorkletMapTopologyExplicit); }
[ "shell_tdf@126.com" ]
shell_tdf@126.com
cd855350f0789f8d94bf6fd995034a6cb5d73580
1bd56891d75b9e386453bf54a41caa9f08fe80b7
/frf/429142_AC_0.08SEC.cpp
a969d7c4b9cc22074fc52ed952850cde5586a9da
[]
no_license
ItzKaserine/Dovelet
9f7dda5435bcb5704fdedfbfce0a7100659ba240
ba24d6dfe8d69d00d0e22e5e644f5609016c4695
refs/heads/master
2023-05-26T13:08:41.772253
2017-10-09T07:04:13
2017-10-09T07:04:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
695
cpp
#include<stdio.h> int dp[100][100][100]; int main() { int a,b,c; scanf("%d%d%d",&a,&b,&c); if(a<0||b<0||c<0) { printf("w(%d, %d, %d) = 1",a,b,c); return 0; } int i,j,k; for(i=0;i<=20;i++) for(j=0;j<=20;j++) for(k=0;k<=20;k++) if(i==0||j==0||k==0) dp[i][j][k]=1; for(i=1;i<=20;i++) { for(j=1;j<=20;j++) { for(k=1;k<=20;k++) { if(i < j && j < k) dp[i][j][k] = dp[i][j][k-1]+dp[i][j-1][k-1]-dp[i][j-1][k]; else dp[i][j][k] = dp[i-1][j][k]+dp[i-1][j-1][k]+dp[i-1][j][k-1]-dp[i-1][j-1][k-1]; } } } if(a>20||b>20||c>20) { printf("w(%d, %d, %d) = %d",a,b,c,dp[20][20][20]); return 0; } else printf("w(%d, %d, %d) = %d",a,b,c,dp[a][b][c]); }
[ "conankun@gatech.edu" ]
conankun@gatech.edu
4a40c3741be28f82ead3ecec345bf967435d5ef7
30871a624da21421ee839ad49a0b6f65f74b80bf
/Lectures Codes/Code (16)/Code/OurStack.cpp
f09cc7ee6c2d0266dc451245391e740b2b94e574
[]
no_license
bakurits/Programming-Abstractions
7b15dbe543951e74d543389cb0c37efd4ef07cb2
680a87b3f029fe004355512be70ba822d1cd5ca9
refs/heads/master
2021-01-19T19:14:26.673149
2017-07-19T18:21:16
2017-07-19T18:21:16
88,407,754
0
1
null
null
null
null
UTF-8
C++
false
false
1,165
cpp
#include "OurStack.h" #include "error.h" /* Constant controlling the default size of our stack. */ const int kDefaultSize = 4; /* Constructor initializes the fields of the stack to * appropriate defaults. */ OurStack::OurStack() { logicalLength = 0; allocatedLength = kDefaultSize; elems = new int[allocatedLength]; } /* Destructor cleans up memory allocated by the stack. */ OurStack::~OurStack() { delete[] elems; } int OurStack::size() { return logicalLength; } bool OurStack::isEmpty() { return size() == 0; } void OurStack::grow() { allocatedLength *= 2; int* newArray = new int[allocatedLength]; for (int i = 0; i < logicalLength; i++) { newArray[i] = elems[i]; } delete[] elems; elems = newArray; } void OurStack::push(int value) { if (allocatedLength == logicalLength) { grow(); } elems[logicalLength] = value; logicalLength++; } int OurStack::peek() { if (isEmpty()) { error("What is the sound of one hand clapping?"); } return elems[logicalLength - 1]; } int OurStack::pop() { /* This line both does bounds checking and obtains the * return value. */ int result = peek(); logicalLength--; return result; }
[ "bakuricucxashvili@gmail.com" ]
bakuricucxashvili@gmail.com
ba31af052a8c6ee1102e1f26bf0d70f911413550
d07a162fae98a9092f5eaa9588898436bb6c29f9
/cosesdelpen/ConsoleApplication2/Map.h
945261bc2c1cfb47352cf5d4b873d27838056b61
[]
no_license
Setsilvestre/codipen
8b6ae74d2610777f22f9760b0fca9e45beb628b1
3e2659e9f25ab67fd460c3163a0ca206c7e000ec
refs/heads/master
2016-08-04T17:02:52.299401
2015-02-23T09:30:01
2015-02-23T09:30:01
31,201,147
0
0
null
null
null
null
UTF-8
C++
false
false
2,071
h
#pragma once using namespace std; #include <exception> //Management of exceptions #include <iostream> //Management of cin and cout #include <stdlib.h> //Management of random numbers: srand, rand #include <time.h> //Management of time features #include <cstdlib> //Management of system functions such as pause #include <fstream> //Managment of the save/load game //create the class map class Map{ //attributes for the class map protected: //Data of each cell int ** data; //Variables for the data to save/load int temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9, temp10, temp11; public: int rows; int cols; //constructor Map(); //destructor ~Map(); //Overload Constructor Map(int x, int y); //Create the map, the first parameter is the number of columns, and the second parameter is the number of rows void CreateMap(int x, int y); //Use the function create map and assign to each field a number for the surface void LoadMap(); //Use the function create map and assign to each field a number for the surface for a transition beetwen surfaces void LoadSecondLayer(); //return the number of the surface stored on the position x,y int getSurface(int x, int y); //Return the number of columns int getColumns(); //return the number of rows int getRows(); //Set the surface void Set(int x, int y, int _data); //Save the map void SaveMap( int x, int y, int sword, int fireball, int xenemy, int yenemy, int xenemy2, int yenemy2,int xboss, int yboss, int health, int map); //Load the map void LoadMap( int map); //Return the X hero position int HeroPosX(); //Return the Y hero position int HeroPosY(); //Return the health int HeroHealth(); //Return the sword variable int Sword(); //Return the fireball variable int Fireball(); //Return the X enemy position int EnemyX(); //Return the Y enemy position int EnemyY(); //Return the X enemy2 position int EnemyX2(); //Return the Y enemy2 position int EnemyY2(); //Get the X boss position int getXBoss(); //Get the Y boss position int getYBoss(); };
[ "xavier_figuerola@hotmail.com" ]
xavier_figuerola@hotmail.com
f033795d2c5259ece6a158fce5861df38757170e
11227b9a3344c050366e801e0179f6bb6d05e725
/Engine/Graphics/Font.h
d8af16a1c97c63ec0b68d1226a3cbbbaa6617201
[]
no_license
MagnusRunesson/Pidventure
46fefb63b95cecd78a1d159dcd4551651ac3d2d6
4bec99e46263c44c7ad69085cc0db81469bdae33
refs/heads/master
2020-09-22T15:12:20.369444
2018-01-02T19:37:15
2018-01-02T19:37:15
67,161,478
2
0
null
null
null
null
UTF-8
C++
false
false
469
h
// // Font.h // Razware Mega Collection 1 // // Created by Magnus Runesson on 2017-06-05. // Copyright © 2017 Magnus Runesson. All rights reserved. // #ifndef Font_h #define Font_h class Image; class FontGlyph { public: unsigned char ID; int rectLeft, rectTop; int rectWidth, rectHeight; int baseline; }; class Font { public: int numGlyphs; FontGlyph* glyphs; Image* pImage; FontGlyph* GetGlyph( unsigned char _glyphID ) const; }; #endif /* Font_h */
[ "magnus@pokewhat.com" ]
magnus@pokewhat.com
c3f752e3941585b132fa8c368d0ea5aba780015e
f466e399822d25211abf450bbd0e5d4d35be7f42
/Settings.cpp
4aa5895d4d541cb46412dcfc55f40476f5ea9f77
[]
no_license
jhpark2798/JSLib
d899cf737c52bd10130fc2a8079b9ce4aa62a2d8
101f1800f77d84be6049c5145aac7e5109847ad4
refs/heads/master
2020-09-12T12:56:05.744953
2020-03-05T21:41:01
2020-03-05T21:41:01
222,432,023
0
0
null
null
null
null
UTF-8
C++
false
false
240
cpp
#include "Settings.h" namespace JSLib { Settings::DateProxy& Settings::DateProxy::operator=(const Date& d) { ObservableValue<Date>::operator=(d); return *this; } Settings::DateProxy::operator Date() const { return value(); } }
[ "jhpark2798@gmail.com" ]
jhpark2798@gmail.com
9c152c971b755a91f716964210df954c0d0ba3cb
6e203dbe435bbfe167e637b42f9b80cce673e574
/libs/Vehicle.hpp
73b5d47e225e61a183ad6c92ae35d5f3f7baaad8
[]
no_license
Carlovan/vehicles
3c83beef211d4c0fcb1cf6f8faa57d34cd76f409
c383b3d2367b48baf240d7d0d4c7aa31a1244b9e
refs/heads/main
2023-06-06T08:29:17.010780
2021-06-30T19:02:19
2021-06-30T19:02:19
380,838,114
0
0
null
null
null
null
UTF-8
C++
false
false
501
hpp
#ifndef VEHICLES_VEHICLE_H #define VEHICLES_VEHICLE_H #include <Object.hpp> #include <VectorMath.hpp> /* * This vehicle model is heavily inspired by http://www.red3d.com/cwr/steer/gdc99/ */ class Vehicle : public Object { const float maxSpeed = 5; const float maxForce = 1; public: Vehicle(const float x, const float y); /* void update() override; */ void applyForce(vecmath::Vec2); std::unique_ptr<sf::Shape> getShape() const override; public: vecmath::Vec2 velocity{0,0}; }; #endif
[ "giulio.carlassare@gmail.com" ]
giulio.carlassare@gmail.com
a8bfc1830713095bd3ab97fb120ba42d04d0820b
c51febc209233a9160f41913d895415704d2391f
/YorozuyaGSLib/source/_qry_sheet_reged.cpp
f1f2b6406d704574535b3c22d0a47c26d741ad82
[ "MIT" ]
permissive
roussukke/Yorozuya
81f81e5e759ecae02c793e65d6c3acc504091bc3
d9a44592b0714da1aebf492b64fdcb3fa072afe5
refs/heads/master
2023-07-08T03:23:00.584855
2023-06-29T08:20:25
2023-06-29T08:20:25
463,330,454
0
0
MIT
2022-02-24T23:15:01
2022-02-24T23:15:00
null
UTF-8
C++
false
false
560
cpp
#include <_qry_sheet_reged.hpp> START_ATF_NAMESPACE _qry_sheet_reged::_qry_sheet_reged() { using org_ptr = void (WINAPIV*)(struct _qry_sheet_reged*); (org_ptr(0x14011f550L))(this); }; void _qry_sheet_reged::ctor__qry_sheet_reged() { using org_ptr = void (WINAPIV*)(struct _qry_sheet_reged*); (org_ptr(0x14011f550L))(this); }; int _qry_sheet_reged::size() { using org_ptr = int (WINAPIV*)(struct _qry_sheet_reged*); return (org_ptr(0x14011f540L))(this); }; END_ATF_NAMESPACE
[ "b1ll.cipher@yandex.ru" ]
b1ll.cipher@yandex.ru
76f89febb42277945d265dc7fa33f486a04d3f01
3004d76f5f48ed932377c2e40a816e102216d237
/344 Reverse String.cpp
01e2d71c9f82820845a6599ebec0dc5299a022d7
[]
no_license
gro-mit/LeetCode
4e1c26380f90c4a036ba6a63a8ee32c267464afe
9e11805b8dbea748e56b33b49cb75fde89caa1b6
refs/heads/master
2021-01-21T06:59:07.382179
2017-04-04T11:34:45
2017-04-04T11:34:45
82,875,042
1
0
null
null
null
null
UTF-8
C++
false
false
215
cpp
class Solution { public: string reverseString(string s) { int i=0,j=s.length()-1; while(i<=j){ swap(s[i],s[j]); i++; j--; } return s; } };
[ "spatriotc@sina.com" ]
spatriotc@sina.com
b1b5d3dcf75e02ef0719a0f485109f77768a7b5b
6cd7fe3c469db20990f49def35e72b4dddeb495e
/fuse-bindings.cc
14bc0f6b7eeb521c3d92915eee95530632fccb51
[ "MIT" ]
permissive
dweinstein/fuse-bindings
00bcdd94b8cf230207e2e33ec91d5aeaff015f8a
de412a6aaf566cc8d55d405e1407b9c5a07df465
refs/heads/master
2021-01-18T05:47:04.631961
2015-03-22T12:07:36
2015-03-22T12:07:36
32,242,617
0
0
null
2015-03-15T03:03:27
2015-03-15T03:03:27
null
UTF-8
C++
false
false
38,379
cc
#include <nan.h> #define FUSE_USE_VERSION 29 #include <fuse.h> #include <fuse_opt.h> #include <fuse_lowlevel.h> #include <semaphore.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <sys/mount.h> #include <sys/types.h> #include <sys/wait.h> #ifdef __APPLE__ #include <dispatch/dispatch.h> #endif using namespace v8; enum bindings_ops_t { OP_INIT = 0, OP_ERROR, OP_ACCESS, OP_STATFS, OP_FGETATTR, OP_GETATTR, OP_FLUSH, OP_FSYNC, OP_FSYNCDIR, OP_READDIR, OP_TRUNCATE, OP_FTRUNCATE, OP_UTIMENS, OP_READLINK, OP_CHOWN, OP_CHMOD, OP_SETXATTR, OP_GETXATTR, OP_OPEN, OP_OPENDIR, OP_READ, OP_WRITE, OP_RELEASE, OP_RELEASEDIR, OP_CREATE, OP_UNLINK, OP_RENAME, OP_LINK, OP_SYMLINK, OP_MKDIR, OP_RMDIR, OP_DESTROY }; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static Persistent<Function> buffer_constructor; static NanCallback *callback_constructor; static struct stat empty_stat; struct bindings_t { int index; int gc; // fuse data char mnt[1024]; char mntopts[1024]; pthread_t thread; #ifdef __APPLE__ dispatch_semaphore_t semaphore; #else sem_t semaphore; #endif uv_async_t async; // methods NanCallback *ops_init; NanCallback *ops_error; NanCallback *ops_access; NanCallback *ops_statfs; NanCallback *ops_getattr; NanCallback *ops_fgetattr; NanCallback *ops_flush; NanCallback *ops_fsync; NanCallback *ops_fsyncdir; NanCallback *ops_readdir; NanCallback *ops_truncate; NanCallback *ops_ftruncate; NanCallback *ops_readlink; NanCallback *ops_chown; NanCallback *ops_chmod; NanCallback *ops_setxattr; NanCallback *ops_getxattr; NanCallback *ops_open; NanCallback *ops_opendir; NanCallback *ops_read; NanCallback *ops_write; NanCallback *ops_release; NanCallback *ops_releasedir; NanCallback *ops_create; NanCallback *ops_utimens; NanCallback *ops_unlink; NanCallback *ops_rename; NanCallback *ops_link; NanCallback *ops_symlink; NanCallback *ops_mkdir; NanCallback *ops_rmdir; NanCallback *ops_destroy; NanCallback *callback; // method data bindings_ops_t op; fuse_fill_dir_t filler; // used in readdir struct fuse_file_info *info; char *path; char *name; off_t offset; off_t length; void *data; // various structs int mode; int uid; int gid; int result; }; static bindings_t *bindings_mounted[1024]; static int bindings_mounted_count = 0; #ifdef __APPLE__ NAN_INLINE static int semaphore_init (dispatch_semaphore_t *sem) { *sem = dispatch_semaphore_create(0); return *sem == NULL ? -1 : 0; } NAN_INLINE static void semaphore_wait (dispatch_semaphore_t *sem) { dispatch_semaphore_wait(*sem, DISPATCH_TIME_FOREVER); } NAN_INLINE static void semaphore_signal (dispatch_semaphore_t *sem) { dispatch_semaphore_signal(*sem); } #else NAN_INLINE static int semaphore_init (sem_t *sem) { return sem_init(sem, 0, 0); } NAN_INLINE static void semaphore_wait (sem_t *sem) { sem_wait(sem); } NAN_INLINE static void semaphore_signal (sem_t *sem) { sem_post(sem); } #endif static bindings_t *bindings_find_mounted (char *path) { for (int i = 0; i < bindings_mounted_count; i++) { bindings_t *b = bindings_mounted[i]; if (b != NULL && !b->gc && !strcmp(b->mnt, path)) { return b; } } return NULL; } static void bindings_fusermount (char *path) { #ifdef __APPLE__ char *argv[] = {(char *) "umount", path, NULL}; #else char *argv[] = {(char *) "fusermount", (char *) "-q", (char *) "-u", path, NULL}; #endif pid_t cpid = vfork(); if (cpid > 0) waitpid(cpid, NULL, 0); else execvp(argv[0], argv); } static void bindings_unmount (char *path) { pthread_mutex_lock(&mutex); bindings_t *b = bindings_find_mounted(path); if (b != NULL) b->gc = 1; bindings_fusermount(path); if (b != NULL) pthread_join(b->thread, NULL); pthread_mutex_unlock(&mutex); } #if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) NAN_INLINE v8::Local<v8::Object> bindings_buffer (char *data, size_t length) { Local<Object> buf = NanNew(buffer_constructor)->NewInstance(0, NULL); buf->Set(NanNew<String>("length"), NanNew<Number>(length)); buf->SetIndexedPropertiesToExternalArrayData((char *) data, kExternalUnsignedByteArray, length); return buf; } #else void noop (char *data, void *hint) {} NAN_INLINE v8::Local<v8::Object> bindings_buffer (char *data, size_t length) { return NanNewBufferHandle(data, length, noop, NULL); } #endif NAN_INLINE static int bindings_call (bindings_t *b) { uv_async_send(&(b->async)); semaphore_wait(&(b->semaphore)); return b->result; } static int bindings_truncate (const char *path, off_t size) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_TRUNCATE; b->path = (char *) path; b->length = size; return bindings_call(b); } static int bindings_ftruncate (const char *path, off_t size, struct fuse_file_info *info) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_FTRUNCATE; b->path = (char *) path; b->length = size; b->info = info; return bindings_call(b); } static int bindings_getattr (const char *path, struct stat *stat) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_GETATTR; b->path = (char *) path; b->data = stat; return bindings_call(b); } static int bindings_fgetattr (const char *path, struct stat *stat, struct fuse_file_info *info) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_FGETATTR; b->path = (char *) path; b->data = stat; b->info = info; return bindings_call(b); } static int bindings_flush (const char *path, struct fuse_file_info *info) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_FLUSH; b->path = (char *) path; b->info = info; return bindings_call(b); } static int bindings_fsync (const char *path, int datasync, struct fuse_file_info *info) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_FSYNC; b->path = (char *) path; b->mode = datasync; b->info = info; return bindings_call(b); } static int bindings_fsyncdir (const char *path, int datasync, struct fuse_file_info *info) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_FSYNCDIR; b->path = (char *) path; b->mode = datasync; b->info = info; return bindings_call(b); } static int bindings_readdir (const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *info) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_READDIR; b->path = (char *) path; b->data = buf; b->filler = filler; return bindings_call(b); } static int bindings_readlink (const char *path, char *buf, size_t len) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_READLINK; b->path = (char *) path; b->data = (void *) buf; b->length = len; return bindings_call(b); } static int bindings_chown (const char *path, uid_t uid, gid_t gid) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_CHOWN; b->path = (char *) path; b->uid = uid; b->gid = gid; return bindings_call(b); } static int bindings_chmod (const char *path, mode_t mode) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_CHMOD; b->path = (char *) path; b->mode = mode; return bindings_call(b); } #ifdef __APPLE__ static int bindings_setxattr (const char *path, const char *name, const char *value, size_t size, int flags, uint32_t position) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_SETXATTR; b->path = (char *) path; b->name = (char *) name; b->data = (void *) value; b->length = size; b->offset = position; b->mode = flags; return bindings_call(b); } static int bindings_getxattr (const char *path, const char *name, char *value, size_t size, uint32_t position) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_GETXATTR; b->path = (char *) path; b->name = (char *) name; b->data = (void *) value; b->length = size; b->offset = position; return bindings_call(b); } #else static int bindings_setxattr (const char *path, const char *name, const char *value, size_t size, int flags) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_SETXATTR; b->path = (char *) path; b->name = (char *) name; b->data = (void *) value; b->length = size; b->offset = 0; b->mode = flags; return bindings_call(b); } static int bindings_getxattr (const char *path, const char *name, char *value, size_t size) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_GETXATTR; b->path = (char *) path; b->name = (char *) name; b->data = (void *) value; b->length = size; b->offset = 0; return bindings_call(b); } #endif static int bindings_statfs (const char *path, struct statvfs *statfs) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_STATFS; b->path = (char *) path; b->data = statfs; return bindings_call(b); } static int bindings_open (const char *path, struct fuse_file_info *info) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_OPEN; b->path = (char *) path; b->mode = info->flags; b->info = info; return bindings_call(b); } static int bindings_opendir (const char *path, struct fuse_file_info *info) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_OPENDIR; b->path = (char *) path; b->mode = info->flags; b->info = info; return bindings_call(b); } static int bindings_read (const char *path, char *buf, size_t len, off_t offset, struct fuse_file_info *info) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_READ; b->path = (char *) path; b->data = (void *) buf; b->offset = offset; b->length = len; b->info = info; return bindings_call(b); } static int bindings_write (const char *path, const char *buf, size_t len, off_t offset, struct fuse_file_info * info) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_WRITE; b->path = (char *) path; b->data = (void *) buf; b->offset = offset; b->length = len; b->info = info; return bindings_call(b); } static int bindings_release (const char *path, struct fuse_file_info *info) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_RELEASE; b->path = (char *) path; b->info = info; return bindings_call(b); } static int bindings_releasedir (const char *path, struct fuse_file_info *info) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_RELEASEDIR; b->path = (char *) path; b->info = info; return bindings_call(b); } static int bindings_access (const char *path, int mode) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_ACCESS; b->path = (char *) path; b->mode = mode; return bindings_call(b); } static int bindings_create (const char *path, mode_t mode, struct fuse_file_info *info) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_CREATE; b->path = (char *) path; b->mode = mode; b->info = info; return bindings_call(b); } static int bindings_utimens (const char *path, const struct timespec tv[2]) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_UTIMENS; b->path = (char *) path; b->data = (void *) tv; return bindings_call(b); } static int bindings_unlink (const char *path) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_UNLINK; b->path = (char *) path; return bindings_call(b); } static int bindings_rename (const char *src, const char *dest) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_RENAME; b->path = (char *) src; b->data = (void *) dest; return bindings_call(b); } static int bindings_link (const char *path, const char *dest) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_LINK; b->path = (char *) path; b->data = (void *) dest; return bindings_call(b); } static int bindings_symlink (const char *path, const char *dest) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_SYMLINK; b->path = (char *) path; b->data = (void *) dest; return bindings_call(b); } static int bindings_mkdir (const char *path, mode_t mode) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_MKDIR; b->path = (char *) path; b->mode = mode; return bindings_call(b); } static int bindings_rmdir (const char *path) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_RMDIR; b->path = (char *) path; return bindings_call(b); } static void* bindings_init (struct fuse_conn_info *conn) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_INIT; bindings_call(b); return b; } static void bindings_destroy (void *data) { bindings_t *b = (bindings_t *) fuse_get_context()->private_data; b->op = OP_DESTROY; bindings_call(b); } static void bindings_free (bindings_t *b) { if (b->ops_access != NULL) delete b->ops_access; if (b->ops_truncate != NULL) delete b->ops_truncate; if (b->ops_ftruncate != NULL) delete b->ops_ftruncate; if (b->ops_getattr != NULL) delete b->ops_getattr; if (b->ops_fgetattr != NULL) delete b->ops_fgetattr; if (b->ops_flush != NULL) delete b->ops_flush; if (b->ops_fsync != NULL) delete b->ops_fsync; if (b->ops_fsyncdir != NULL) delete b->ops_fsyncdir; if (b->ops_readdir != NULL) delete b->ops_readdir; if (b->ops_readlink != NULL) delete b->ops_readlink; if (b->ops_chown != NULL) delete b->ops_chown; if (b->ops_chmod != NULL) delete b->ops_chmod; if (b->ops_setxattr != NULL) delete b->ops_setxattr; if (b->ops_getxattr != NULL) delete b->ops_getxattr; if (b->ops_statfs != NULL) delete b->ops_statfs; if (b->ops_open != NULL) delete b->ops_open; if (b->ops_opendir != NULL) delete b->ops_opendir; if (b->ops_read != NULL) delete b->ops_read; if (b->ops_write != NULL) delete b->ops_write; if (b->ops_release != NULL) delete b->ops_release; if (b->ops_releasedir != NULL) delete b->ops_releasedir; if (b->ops_create != NULL) delete b->ops_create; if (b->ops_utimens != NULL) delete b->ops_utimens; if (b->ops_unlink != NULL) delete b->ops_unlink; if (b->ops_rename != NULL) delete b->ops_rename; if (b->ops_link != NULL) delete b->ops_link; if (b->ops_symlink != NULL) delete b->ops_symlink; if (b->ops_mkdir != NULL) delete b->ops_mkdir; if (b->ops_rmdir != NULL) delete b->ops_rmdir; if (b->ops_init != NULL) delete b->ops_init; if (b->ops_destroy != NULL) delete b->ops_destroy; if (b->callback != NULL) delete b->callback; bindings_mounted[b->index] = NULL; while (bindings_mounted_count > 0 && bindings_mounted[bindings_mounted_count - 1] == NULL) { bindings_mounted_count--; } free(b); } static void bindings_on_close (uv_handle_t *handle) { pthread_mutex_lock(&mutex); bindings_free((bindings_t *) handle->data); pthread_mutex_unlock(&mutex); } static void *bindings_thread (void *data) { bindings_t *b = (bindings_t *) data; struct fuse_operations ops = { }; if (b->ops_access != NULL) ops.access = bindings_access; if (b->ops_truncate != NULL) ops.truncate = bindings_truncate; if (b->ops_ftruncate != NULL) ops.ftruncate = bindings_ftruncate; if (b->ops_getattr != NULL) ops.getattr = bindings_getattr; if (b->ops_fgetattr != NULL) ops.fgetattr = bindings_fgetattr; if (b->ops_flush != NULL) ops.flush = bindings_flush; if (b->ops_fsync != NULL) ops.fsync = bindings_fsync; if (b->ops_fsyncdir != NULL) ops.fsyncdir = bindings_fsyncdir; if (b->ops_readdir != NULL) ops.readdir = bindings_readdir; if (b->ops_readlink != NULL) ops.readlink = bindings_readlink; if (b->ops_chown != NULL) ops.chown = bindings_chown; if (b->ops_chmod != NULL) ops.chmod = bindings_chmod; if (b->ops_setxattr != NULL) ops.setxattr = bindings_setxattr; if (b->ops_getxattr != NULL) ops.getxattr = bindings_getxattr; if (b->ops_statfs != NULL) ops.statfs = bindings_statfs; if (b->ops_open != NULL) ops.open = bindings_open; if (b->ops_opendir != NULL) ops.opendir = bindings_opendir; if (b->ops_read != NULL) ops.read = bindings_read; if (b->ops_write != NULL) ops.write = bindings_write; if (b->ops_release != NULL) ops.release = bindings_release; if (b->ops_releasedir != NULL) ops.releasedir = bindings_releasedir; if (b->ops_create != NULL) ops.create = bindings_create; if (b->ops_utimens != NULL) ops.utimens = bindings_utimens; if (b->ops_unlink != NULL) ops.unlink = bindings_unlink; if (b->ops_rename != NULL) ops.rename = bindings_rename; if (b->ops_link != NULL) ops.link = bindings_link; if (b->ops_symlink != NULL) ops.symlink = bindings_symlink; if (b->ops_mkdir != NULL) ops.mkdir = bindings_mkdir; if (b->ops_rmdir != NULL) ops.rmdir = bindings_rmdir; if (b->ops_init != NULL) ops.init = bindings_init; if (b->ops_destroy != NULL) ops.destroy = bindings_destroy; int argc = !strcmp(b->mntopts, "-o") ? 1 : 2; char *argv[] = { (char *) "fuse_bindings_dummy", (char *) b->mntopts }; struct fuse_args args = FUSE_ARGS_INIT(argc, argv); struct fuse_chan *ch = fuse_mount(b->mnt, &args); if (ch == NULL) { b->op = OP_ERROR; bindings_call(b); uv_close((uv_handle_t*) &(b->async), &bindings_on_close); return NULL; } struct fuse *fuse = fuse_new(ch, &args, &ops, sizeof(struct fuse_operations), b); if (fuse == NULL) { b->op = OP_ERROR; bindings_call(b); uv_close((uv_handle_t*) &(b->async), &bindings_on_close); return NULL; } fuse_loop(fuse); fuse_unmount(b->mnt, ch); fuse_session_remove_chan(ch); fuse_destroy(fuse); uv_close((uv_handle_t*) &(b->async), &bindings_on_close); return NULL; } NAN_INLINE static void bindings_set_date (struct timespec *out, Local<Date> date) { double ms = date->NumberValue(); time_t secs = (time_t)(ms / 1000.0); time_t rem = ms - (1000.0 * secs); time_t ns = rem * 1000000.0; out->tv_sec = secs; out->tv_nsec = ns; } NAN_INLINE static void bindings_set_stat (struct stat *stat, Local<Object> obj) { if (obj->Has(NanNew<String>("dev"))) stat->st_dev = obj->Get(NanNew<String>("dev"))->NumberValue(); if (obj->Has(NanNew<String>("ino"))) stat->st_ino = obj->Get(NanNew<String>("ino"))->NumberValue(); if (obj->Has(NanNew<String>("mode"))) stat->st_mode = obj->Get(NanNew<String>("mode"))->Uint32Value(); if (obj->Has(NanNew<String>("nlink"))) stat->st_nlink = obj->Get(NanNew<String>("nlink"))->NumberValue(); if (obj->Has(NanNew<String>("uid"))) stat->st_uid = obj->Get(NanNew<String>("uid"))->NumberValue(); if (obj->Has(NanNew<String>("gid"))) stat->st_gid = obj->Get(NanNew<String>("gid"))->NumberValue(); if (obj->Has(NanNew<String>("rdev"))) stat->st_rdev = obj->Get(NanNew<String>("rdev"))->NumberValue(); if (obj->Has(NanNew<String>("size"))) stat->st_size = obj->Get(NanNew<String>("size"))->NumberValue(); if (obj->Has(NanNew<String>("blksize"))) stat->st_blksize = obj->Get(NanNew<String>("blksize"))->NumberValue(); if (obj->Has(NanNew<String>("blocks"))) stat->st_blocks = obj->Get(NanNew<String>("blocks"))->NumberValue(); #ifdef __APPLE__ if (obj->Has(NanNew<String>("mtime"))) bindings_set_date(&stat->st_mtimespec, obj->Get(NanNew("mtime")).As<Date>()); if (obj->Has(NanNew<String>("ctime"))) bindings_set_date(&stat->st_ctimespec, obj->Get(NanNew("ctime")).As<Date>()); if (obj->Has(NanNew<String>("atime"))) bindings_set_date(&stat->st_atimespec, obj->Get(NanNew("atime")).As<Date>()); #else if (obj->Has(NanNew<String>("mtime"))) bindings_set_date(&stat->st_mtim, obj->Get(NanNew("mtime")).As<Date>()); if (obj->Has(NanNew<String>("ctime"))) bindings_set_date(&stat->st_ctim, obj->Get(NanNew("ctime")).As<Date>()); if (obj->Has(NanNew<String>("atime"))) bindings_set_date(&stat->st_atim, obj->Get(NanNew("atime")).As<Date>()); #endif } NAN_INLINE static void bindings_set_utimens (struct timespec tv[2], Local<Object> obj) { if (obj->Has(NanNew<String>("atime"))) bindings_set_date(&tv[0], obj->Get(NanNew("atime")).As<Date>()); if (obj->Has(NanNew<String>("mtime"))) bindings_set_date(&tv[1], obj->Get(NanNew("mtime")).As<Date>()); } NAN_INLINE static void bindings_set_statfs (struct statvfs *statfs, Local<Object> obj) { // from http://linux.die.net/man/2/stat if (obj->Has(NanNew<String>("bsize"))) statfs->f_bsize = obj->Get(NanNew<String>("bsize"))->Uint32Value(); if (obj->Has(NanNew<String>("frsize"))) statfs->f_frsize = obj->Get(NanNew<String>("frsize"))->Uint32Value(); if (obj->Has(NanNew<String>("blocks"))) statfs->f_blocks = obj->Get(NanNew<String>("blocks"))->Uint32Value(); if (obj->Has(NanNew<String>("bfree"))) statfs->f_bfree = obj->Get(NanNew<String>("bfree"))->Uint32Value(); if (obj->Has(NanNew<String>("bavail"))) statfs->f_bavail = obj->Get(NanNew<String>("bavail"))->Uint32Value(); if (obj->Has(NanNew<String>("files"))) statfs->f_files = obj->Get(NanNew<String>("files"))->Uint32Value(); if (obj->Has(NanNew<String>("ffree"))) statfs->f_ffree = obj->Get(NanNew<String>("ffree"))->Uint32Value(); if (obj->Has(NanNew<String>("favail"))) statfs->f_favail = obj->Get(NanNew<String>("favail"))->Uint32Value(); if (obj->Has(NanNew<String>("fsid"))) statfs->f_fsid = obj->Get(NanNew<String>("fsid"))->Uint32Value(); if (obj->Has(NanNew<String>("flag"))) statfs->f_flag = obj->Get(NanNew<String>("flag"))->Uint32Value(); if (obj->Has(NanNew<String>("namemax"))) statfs->f_namemax = obj->Get(NanNew<String>("namemax"))->Uint32Value(); } NAN_INLINE static void bindings_set_dirs (bindings_t *b, Local<Array> dirs) { for (uint32_t i = 0; i < dirs->Length(); i++) { NanUtf8String dir(dirs->Get(i)); if (b->filler(b->data, *dir, &empty_stat, 0)) break; } } NAN_INLINE static void bindings_set_fd (bindings_t *b, Local<Number> fd) { b->info->fh = fd->Uint32Value(); } NAN_METHOD(OpCallback) { NanScope(); bindings_t *b = bindings_mounted[args[0]->Uint32Value()]; b->result = args[1]->Uint32Value(); if (!b->result) { switch (b->op) { case OP_STATFS: { if (args.Length() > 2 && args[2]->IsObject()) bindings_set_statfs((struct statvfs *) b->data, args[2].As<Object>()); } break; case OP_GETATTR: case OP_FGETATTR: { if (args.Length() > 2 && args[2]->IsObject()) bindings_set_stat((struct stat *) b->data, args[2].As<Object>()); } break; case OP_READDIR: { if (args.Length() > 2 && args[2]->IsArray()) bindings_set_dirs(b, args[2].As<Array>()); } break; case OP_CREATE: case OP_OPEN: case OP_OPENDIR: { if (args.Length() > 2 && args[2]->IsNumber()) bindings_set_fd(b, args[2].As<Number>()); } break; case OP_UTIMENS: { if (args.Length() > 2 && args[2]->IsObject()) bindings_set_utimens((struct timespec *) b->data, args[2].As<Object>()); } break; case OP_INIT: case OP_ERROR: case OP_ACCESS: case OP_FLUSH: case OP_FSYNC: case OP_FSYNCDIR: case OP_TRUNCATE: case OP_FTRUNCATE: case OP_READLINK: case OP_CHOWN: case OP_CHMOD: case OP_SETXATTR: case OP_GETXATTR: case OP_READ: case OP_WRITE: case OP_RELEASE: case OP_RELEASEDIR: case OP_UNLINK: case OP_RENAME: case OP_LINK: case OP_SYMLINK: case OP_MKDIR: case OP_RMDIR: case OP_DESTROY: break; } } semaphore_signal(&(b->semaphore)); NanReturnUndefined(); } NAN_INLINE static void bindings_call_op (bindings_t *b, NanCallback *fn, int argc, Local<Value> *argv) { if (fn == NULL) semaphore_signal(&(b->semaphore)); else fn->Call(argc, argv); } static void bindings_dispatch (uv_async_t* handle, int status) { bindings_t *b = (bindings_t *) handle->data; Local<Function> callback = b->callback->GetFunction(); b->result = -1; switch (b->op) { case OP_INIT: { Local<Value> tmp[] = {callback}; bindings_call_op(b, b->ops_init, 1, tmp); } return; case OP_ERROR: { Local<Value> tmp[] = {callback}; bindings_call_op(b, b->ops_error, 1, tmp); } return; case OP_STATFS: { Local<Value> tmp[] = {NanNew<String>(b->path), callback}; bindings_call_op(b, b->ops_statfs, 2, tmp); } return; case OP_FGETATTR: { Local<Value> tmp[] = {NanNew<String>(b->path), NanNew<Number>(b->info->fh), callback}; bindings_call_op(b, b->ops_fgetattr, 3, tmp); } return; case OP_GETATTR: { Local<Value> tmp[] = {NanNew<String>(b->path), callback}; bindings_call_op(b, b->ops_getattr, 2, tmp); } return; case OP_READDIR: { Local<Value> tmp[] = {NanNew<String>(b->path), callback}; bindings_call_op(b, b->ops_readdir, 2, tmp); } return; case OP_CREATE: { Local<Value> tmp[] = {NanNew<String>(b->path), NanNew<Number>(b->mode), callback}; bindings_call_op(b, b->ops_create, 3, tmp); } return; case OP_TRUNCATE: { Local<Value> tmp[] = {NanNew<String>(b->path), NanNew<Number>(b->offset), callback}; bindings_call_op(b, b->ops_truncate, 3, tmp); } return; case OP_FTRUNCATE: { Local<Value> tmp[] = {NanNew<String>(b->path), NanNew<Number>(b->info->fh), NanNew<Number>(b->offset), callback}; bindings_call_op(b, b->ops_ftruncate, 4, tmp); } return; case OP_ACCESS: { Local<Value> tmp[] = {NanNew<String>(b->path), NanNew<Number>(b->mode), callback}; bindings_call_op(b, b->ops_access, 3, tmp); } return; case OP_OPEN: { Local<Value> tmp[] = {NanNew<String>(b->path), NanNew<Number>(b->mode), callback}; bindings_call_op(b, b->ops_open, 3, tmp); } return; case OP_OPENDIR: { Local<Value> tmp[] = {NanNew<String>(b->path), NanNew<Number>(b->mode), callback}; bindings_call_op(b, b->ops_opendir, 3, tmp); } return; case OP_WRITE: { Local<Value> tmp[] = { NanNew<String>(b->path), NanNew<Number>(b->info->fh), bindings_buffer((char *) b->data, b->length), NanNew<Number>(b->length), NanNew<Number>(b->offset), callback }; bindings_call_op(b, b->ops_write, 6, tmp); } return; case OP_READ: { Local<Value> tmp[] = { NanNew<String>(b->path), NanNew<Number>(b->info->fh), bindings_buffer((char *) b->data, b->length), NanNew<Number>(b->length), NanNew<Number>(b->offset), callback }; bindings_call_op(b, b->ops_read, 6, tmp); } return; case OP_RELEASE: { Local<Value> tmp[] = {NanNew<String>(b->path), NanNew<Number>(b->info->fh), callback}; bindings_call_op(b, b->ops_release, 3, tmp); } return; case OP_RELEASEDIR: { Local<Value> tmp[] = {NanNew<String>(b->path), NanNew<Number>(b->info->fh), callback}; bindings_call_op(b, b->ops_releasedir, 3, tmp); } return; case OP_UNLINK: { Local<Value> tmp[] = {NanNew<String>(b->path), callback}; bindings_call_op(b, b->ops_unlink, 2, tmp); } return; case OP_RENAME: { Local<Value> tmp[] = {NanNew<String>(b->path), NanNew<String>((char *) b->data), callback}; bindings_call_op(b, b->ops_rename, 3, tmp); } return; case OP_LINK: { Local<Value> tmp[] = {NanNew<String>(b->path), NanNew<String>((char *) b->data), callback}; bindings_call_op(b, b->ops_link, 3, tmp); } return; case OP_SYMLINK: { Local<Value> tmp[] = {NanNew<String>(b->path), NanNew<String>((char *) b->data), callback}; bindings_call_op(b, b->ops_symlink, 3, tmp); } return; case OP_CHMOD: { Local<Value> tmp[] = {NanNew<String>(b->path), NanNew<Number>(b->mode), callback}; bindings_call_op(b, b->ops_chmod, 3, tmp); } return; case OP_CHOWN: { Local<Value> tmp[] = {NanNew<String>(b->path), NanNew<Number>(b->uid), NanNew<Number>(b->gid), callback}; bindings_call_op(b, b->ops_chown, 4, tmp); } return; case OP_READLINK: { Local<Value> tmp[] = { NanNew<String>(b->path), bindings_buffer((char *) b->data, b->length), NanNew<Number>(b->length), callback }; bindings_call_op(b, b->ops_readlink, 4, tmp); } return; case OP_SETXATTR: { Local<Value> tmp[] = { NanNew<String>(b->path), NanNew<String>(b->name), bindings_buffer((char *) b->data, b->length), NanNew<Number>(b->length), NanNew<Number>(b->offset), NanNew<Number>(b->mode), callback }; bindings_call_op(b, b->ops_setxattr, 7, tmp); } return; case OP_GETXATTR: { Local<Value> tmp[] = { NanNew<String>(b->path), NanNew<String>(b->name), bindings_buffer((char *) b->data, b->length), NanNew<Number>(b->length), NanNew<Number>(b->offset), callback }; bindings_call_op(b, b->ops_getxattr, 6, tmp); } return; case OP_MKDIR: { Local<Value> tmp[] = {NanNew<String>(b->path), NanNew<Number>(b->mode), callback}; bindings_call_op(b, b->ops_mkdir, 3, tmp); } return; case OP_RMDIR: { Local<Value> tmp[] = {NanNew<String>(b->path), callback}; bindings_call_op(b, b->ops_rmdir, 2, tmp); } return; case OP_DESTROY: { Local<Value> tmp[] = {callback}; bindings_call_op(b, b->ops_destroy, 1, tmp); } return; case OP_UTIMENS: { Local<Value> tmp[] = {NanNew<String>(b->path), callback}; bindings_call_op(b, b->ops_utimens, 2, tmp); } return; case OP_FLUSH: { Local<Value> tmp[] = {NanNew<String>(b->path), NanNew<Number>(b->info->fh), callback}; bindings_call_op(b, b->ops_flush, 3, tmp); } return; case OP_FSYNC: { Local<Value> tmp[] = {NanNew<String>(b->path), NanNew<Number>(b->info->fh), NanNew<Number>(b->mode), callback}; bindings_call_op(b, b->ops_fsync, 4, tmp); } return; case OP_FSYNCDIR: { Local<Value> tmp[] = {NanNew<String>(b->path), NanNew<Number>(b->info->fh), NanNew<Number>(b->mode), callback}; bindings_call_op(b, b->ops_fsyncdir, 4, tmp); } return; } semaphore_signal(&(b->semaphore)); } static int bindings_alloc () { int free_index = -1; size_t size = sizeof(bindings_t); for (int i = 0; i < bindings_mounted_count; i++) { if (bindings_mounted[i] == NULL) { free_index = i; break; } } if (free_index == -1 && bindings_mounted_count < 1024) free_index = bindings_mounted_count++; if (free_index != -1) { bindings_t *b = bindings_mounted[free_index] = (bindings_t *) malloc(size); memset(b, 0, size); b->index = free_index; } return free_index; } NAN_METHOD(Mount) { NanScope(); if (!args[0]->IsString()) return NanThrowError("mnt must be a string"); pthread_mutex_lock(&mutex); int index = bindings_alloc(); pthread_mutex_unlock(&mutex); if (index == -1) return NanThrowError("You cannot mount more than 1024 filesystem in one process"); pthread_mutex_lock(&mutex); bindings_t *b = bindings_mounted[index]; pthread_mutex_unlock(&mutex); memset(&empty_stat, 0, sizeof(empty_stat)); memset(b, 0, sizeof(bindings_t)); NanUtf8String path(args[0]); Local<Object> ops = args[1].As<Object>(); b->ops_init = ops->Has(NanNew<String>("init")) ? new NanCallback(ops->Get(NanNew<String>("init")).As<Function>()) : NULL; b->ops_error = ops->Has(NanNew<String>("error")) ? new NanCallback(ops->Get(NanNew<String>("error")).As<Function>()) : NULL; b->ops_access = ops->Has(NanNew<String>("access")) ? new NanCallback(ops->Get(NanNew<String>("access")).As<Function>()) : NULL; b->ops_statfs = ops->Has(NanNew<String>("statfs")) ? new NanCallback(ops->Get(NanNew<String>("statfs")).As<Function>()) : NULL; b->ops_getattr = ops->Has(NanNew<String>("getattr")) ? new NanCallback(ops->Get(NanNew<String>("getattr")).As<Function>()) : NULL; b->ops_fgetattr = ops->Has(NanNew<String>("fgetattr")) ? new NanCallback(ops->Get(NanNew<String>("fgetattr")).As<Function>()) : NULL; b->ops_flush = ops->Has(NanNew<String>("flush")) ? new NanCallback(ops->Get(NanNew<String>("flush")).As<Function>()) : NULL; b->ops_fsync = ops->Has(NanNew<String>("fsync")) ? new NanCallback(ops->Get(NanNew<String>("fsync")).As<Function>()) : NULL; b->ops_fsyncdir = ops->Has(NanNew<String>("fsyncdir")) ? new NanCallback(ops->Get(NanNew<String>("fsyncdir")).As<Function>()) : NULL; b->ops_readdir = ops->Has(NanNew<String>("readdir")) ? new NanCallback(ops->Get(NanNew<String>("readdir")).As<Function>()) : NULL; b->ops_truncate = ops->Has(NanNew<String>("truncate")) ? new NanCallback(ops->Get(NanNew<String>("truncate")).As<Function>()) : NULL; b->ops_ftruncate = ops->Has(NanNew<String>("ftruncate")) ? new NanCallback(ops->Get(NanNew<String>("ftruncate")).As<Function>()) : NULL; b->ops_readlink = ops->Has(NanNew<String>("readlink")) ? new NanCallback(ops->Get(NanNew<String>("readlink")).As<Function>()) : NULL; b->ops_chown = ops->Has(NanNew<String>("chown")) ? new NanCallback(ops->Get(NanNew<String>("chown")).As<Function>()) : NULL; b->ops_chmod = ops->Has(NanNew<String>("chmod")) ? new NanCallback(ops->Get(NanNew<String>("chmod")).As<Function>()) : NULL; b->ops_setxattr = ops->Has(NanNew<String>("setxattr")) ? new NanCallback(ops->Get(NanNew<String>("setxattr")).As<Function>()) : NULL; b->ops_getxattr = ops->Has(NanNew<String>("getxattr")) ? new NanCallback(ops->Get(NanNew<String>("getxattr")).As<Function>()) : NULL; b->ops_open = ops->Has(NanNew<String>("open")) ? new NanCallback(ops->Get(NanNew<String>("open")).As<Function>()) : NULL; b->ops_opendir = ops->Has(NanNew<String>("opendir")) ? new NanCallback(ops->Get(NanNew<String>("opendir")).As<Function>()) : NULL; b->ops_read = ops->Has(NanNew<String>("read")) ? new NanCallback(ops->Get(NanNew<String>("read")).As<Function>()) : NULL; b->ops_write = ops->Has(NanNew<String>("write")) ? new NanCallback(ops->Get(NanNew<String>("write")).As<Function>()) : NULL; b->ops_release = ops->Has(NanNew<String>("release")) ? new NanCallback(ops->Get(NanNew<String>("release")).As<Function>()) : NULL; b->ops_releasedir = ops->Has(NanNew<String>("releasedir")) ? new NanCallback(ops->Get(NanNew<String>("releasedir")).As<Function>()) : NULL; b->ops_create = ops->Has(NanNew<String>("create")) ? new NanCallback(ops->Get(NanNew<String>("create")).As<Function>()) : NULL; b->ops_utimens = ops->Has(NanNew<String>("utimens")) ? new NanCallback(ops->Get(NanNew<String>("utimens")).As<Function>()) : NULL; b->ops_unlink = ops->Has(NanNew<String>("unlink")) ? new NanCallback(ops->Get(NanNew<String>("unlink")).As<Function>()) : NULL; b->ops_rename = ops->Has(NanNew<String>("rename")) ? new NanCallback(ops->Get(NanNew<String>("rename")).As<Function>()) : NULL; b->ops_link = ops->Has(NanNew<String>("link")) ? new NanCallback(ops->Get(NanNew<String>("link")).As<Function>()) : NULL; b->ops_symlink = ops->Has(NanNew<String>("symlink")) ? new NanCallback(ops->Get(NanNew<String>("symlink")).As<Function>()) : NULL; b->ops_mkdir = ops->Has(NanNew<String>("mkdir")) ? new NanCallback(ops->Get(NanNew<String>("mkdir")).As<Function>()) : NULL; b->ops_rmdir = ops->Has(NanNew<String>("rmdir")) ? new NanCallback(ops->Get(NanNew<String>("rmdir")).As<Function>()) : NULL; b->ops_destroy = ops->Has(NanNew<String>("destroy")) ? new NanCallback(ops->Get(NanNew<String>("destroy")).As<Function>()) : NULL; Local<Value> tmp[] = {NanNew<Number>(index), NanNew<FunctionTemplate>(OpCallback)->GetFunction()}; b->callback = new NanCallback(callback_constructor->Call(2, tmp).As<Function>()); stpcpy(b->mnt, *path); stpcpy(b->mntopts, "-o"); Local<Array> options = ops->Get(NanNew<String>("options")).As<Array>(); if (options->IsArray()) { for (uint32_t i = 0; i < options->Length(); i++) { NanUtf8String option(options->Get(i)); if (strcmp(b->mntopts, "-o")) strcat(b->mntopts, ","); strcat(b->mntopts, *option); } } semaphore_init(&(b->semaphore)); uv_async_init(uv_default_loop(), &(b->async), (uv_async_cb) bindings_dispatch); b->async.data = b; pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&(b->thread), &attr, bindings_thread, b); NanReturnUndefined(); } class UnmountWorker : public NanAsyncWorker { public: UnmountWorker(NanCallback *callback, char *path) : NanAsyncWorker(callback), path(path) {} ~UnmountWorker() {} void Execute () { bindings_unmount(path); free(path); } void HandleOKCallback () { NanScope(); callback->Call(0, NULL); } private: char *path; }; NAN_METHOD(SetCallback) { NanScope(); callback_constructor = new NanCallback(args[0].As<Function>()); NanReturnUndefined(); } NAN_METHOD(SetBuffer) { NanScope(); NanAssignPersistent(buffer_constructor, args[0].As<Function>()); NanReturnUndefined(); } NAN_METHOD(Unmount) { NanScope(); if (!args[0]->IsString()) return NanThrowError("mnt must be a string"); NanUtf8String path(args[0]); Local<Function> callback = args[1].As<Function>(); char *path_alloc = (char *) malloc(1024); stpcpy(path_alloc, *path); NanAsyncQueueWorker(new UnmountWorker(new NanCallback(callback), path_alloc)); NanReturnUndefined(); } void Init(Handle<Object> exports) { exports->Set(NanNew("setCallback"), NanNew<FunctionTemplate>(SetCallback)->GetFunction()); exports->Set(NanNew("setBuffer"), NanNew<FunctionTemplate>(SetBuffer)->GetFunction()); exports->Set(NanNew("mount"), NanNew<FunctionTemplate>(Mount)->GetFunction()); exports->Set(NanNew("unmount"), NanNew<FunctionTemplate>(Unmount)->GetFunction()); } NODE_MODULE(fuse_bindings, Init)
[ "mathiasbuus@gmail.com" ]
mathiasbuus@gmail.com
a9e83c24d730ae191dbadf4c47ed43fe6d72c152
1589539e075e6c3a5cee4d62541ea274bb1c02b2
/SnookerVideoEventDetector/SnookerVideoEventDetector.h
027a1e40d01466945ee0da25f149cd46f37af94e
[]
no_license
147xin/SnookerVideoEventDetector
2619e3167a644ea5acbbc5cc8ad8035e2da914dc
accbf4becd8c7cca8351f3257eceae3cda20eb4a
refs/heads/master
2021-01-01T05:41:57.211743
2015-03-25T13:09:10
2015-03-25T13:09:10
28,905,011
1
0
null
null
null
null
UTF-8
C++
false
false
8,023
h
// // SnookerVideoEventDetector.h // SnookerVideoEventDetector // // Created by Yixin Huang on 14/12/22. // Copyright (c) 2014年 Yixin Huang. All rights reserved. // #ifndef SnookerVideoEventDetector_h #define SnookerVideoEventDetector_h #include <string> #include <vector> #include <iostream> #include <fstream> #include <unordered_set> #include <unordered_map> #include <algorithm> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <ctime> #include <cmath> #include <cstring> #include <boost/algorithm/string.hpp> // 使用了trim_copy函数 #include <tesseract/baseapi.h> // Google Tesseract OCR Engine #include "ShotCut.h" #include "ReplayDetector.h" extern bool frameFeaturesDetectionStarted; struct FrameFeature { int frameId = -1; //帧编号,初始值为-1 bool hasTable = false; //是否包含桌面 bool isFullTable = false; //是否是全台面 bool hasScoreBar = false; //是否包含比分条 cv::Rect scorebarRegion; //比分条在原帧中的位置, 这个字段用于获取候选的比分条区域 //各字段在比分条中的位置 int maxFrameNumPos[2] = {-1, -1}; int frameNum1Pos[2] = {-1, -1}; int frameNum2Pos[2] = {-1, -1}; int score1Pos[2] = {-1, -1}; int score2Pos[2] = {-1, -1}; int name1Pos[2] = {-1, -1}; int name2Pos[2] = {-1, -1}; int name1PosPlanB[2] = {-1, -1}; int name2PosPlanB[2] = {-1, -1}; //比分条文本特征 int turn = -1; //击球方 0/1,-1表示不确定 std::string name1, name2; //球员名字,获取候选球员名 int score1 = -1, score2 = -1; //当局比分 int frameScore1 = -1, frameScore2 = -1; //大比分(局比分) int bestFrames; //总局数 }; enum AudioType { APPLAUSE, CHEER, LAUGHTER, NOISE, REPLAY_SHOT, SHOT, SIGH, SILENCE, SPEECH, SPEECH_WITH_APPLAUSE, SPEECH_WITH_CHEER }; enum EventType { SCORE, FOUL, MISS, SAFETY, MISS_OR_SAFETY, UNKNOWN, NOEVENT }; struct AudioEvent { int startFrame; int length; AudioType audioType; }; // 一局比赛的起始及终局标志 struct Frame { int start = -1; int end = -1; int num = -1; int score1, score2; //该局结束时的该局比分 int frameScore1, frameScore2; // 该局结束时的局比分 int gamePoint = -1; // 是否某一方的赛点,0表示球员1的赛点,1表示球员2的赛点,2表示双赛点 bool isFinal = false; }; // 高分 struct HighScore { int start = -1; int end = -1; int score = -1; int player = -1; // 打出该高分的球员,0/1 }; // 防守大战 struct Defence { int start = -1; int end = -1; }; // 犯规 struct Foul { int start = -1; int end = -1; int player = -1; // 指示谁犯规了,0/1 }; // 回放 struct Replay { int start = -1; int end = -1; int player = -1; int eventType = -1; // 0进球,1失误,2犯规 }; struct SnookerVideoInfo { std::string videoFilePath; //视频文件路径 std::string framesFolder; //存放视频帧的文件夹 std::string cutPath, gtPath, replayPath, replayFeatPath, allCutPath, cutUpdatePath, gtUpdatePath; //回放检测器需要用到的一些路径 double fps; //帧率 int framesNum; //总帧数 int width, height; //视频尺寸 std::string playerName1, playerName2; //球员名字 int bestFrames; //最大局数 int bestFramesCharColor = -1; //最大局数二值化后的字符(前景)颜色,0是黑色,255是白色,-1表示未确定 cv::Rect scorebarRegion; //比分条在原帧中的位置 int currentPlayerFlagPos[2][2]; //当前击球球员指示符在比分条中的位置 std::vector<FrameFeature> frameFeatures; //取样帧的特征 std::vector<ReplayInfo> rawReplays; //回放镜头 std::unordered_set<int> replayCheckHashTab; std::vector<AudioType> audioEvents; //音频事件 // 根据比分序列检测到的事件 std::vector<Frame> frames; // 各局比赛信息 std::vector<HighScore> highScores; // 高分 std::vector<Defence> defences; // 防守 std::vector<Foul> fouls; // 犯规 // 根据比分序列和回放镜头检测到的事件 std::vector<Replay> replays; }; class SnookerVideoEventDetector { public: SnookerVideoInfo videoInfo; std::vector<cv::Rect> candidateScorebarRegions; cv::Mat lastScorebar, currentScorebar; std::string extendedPlayerListPath; void SetExtendedPlayerListPath(const std::string &path) { extendedPlayerListPath = path; } SnookerVideoEventDetector(); //构造函数 void SetVideoFilePath(const std::string &videoPath); void GetVideoFrames(const std::string &framesPath); void SetReplayDetectorOutputPath(const std::string &outputPath); void GetReplayInfo(); void ReadReplayInfo(); void GetFrameFeature(int const currentFrameNum, FrameFeature &frameFeature); void GetScorebarRegion(); bool GetCurrentPlayerFlagPos(); void GetVideoFramesFeature(); // 对比分序列进行处理,去除无效记录与重复记录 void RefineScoreSequence(); // 根据比分序列进行事件判定 void EventDetection(); // 以上函数包含下列几个事件的检测 void FrameDetection(); // 对局检测 void HighScoreDetection(); // 高分检测 void FoulDetection(); // 犯规检测 void DefenceDetection(); // 防守检测 // 结合回放镜头与比分序列判断回放镜头中的事件类型 void DetectReplayEventType(); // 进行音频分类,获取音频事件 void GetAudioEvents(); private: void DrawDetectedLines(cv::Mat &image, const std::vector<cv::Vec2f> &lines, const cv::Scalar &color, const int width = 1); void DrawDetectedLinesP(cv::Mat &image, const std::vector<cv::Vec4i> &lines, cv::Scalar &color); void DrawCircles(cv::Mat &image, const std::vector<cv::Point> &points, const cv::Scalar &color); void IntersectionPoint(const cv::Vec2f line1, const cv::Vec2f line2, std::vector<cv::Point> &points, int imgRows, int imgCols); void SelectPoint(const std::vector<cv::Point> &points, cv::Size imageSize, cv::Point &selectedPoint, bool &leftSide); int TableRegionHeight(const std::vector<cv::Point> &points, const int imageHeight); bool IsFullTableView(const std::vector<cv::Vec2f> &lines, const cv::Size imageSize); void RemoveNearbyPoints(std::vector<cv::Point> &points, const cv::Size imageSize); void RemoveNearbyLines(std::vector<cv::Vec2f> &lines, const cv::Size imageSize); void RemoveSmallObjects(cv::Mat &image, const cv::Size &imageSize); void GetGrayScorebarFromFrameId(int const frameId, cv::Mat &scorebar); bool DetectTurnIndicator(cv::Mat &scorebarDiff); void GetCorrectNames(const std::string &name1, const std::string &name2); int EditDistance(const std::string &str1, const std::string &str2); // -------------------------------- 以下三个函数是事件判定的辅助函数 -------------------------------- // 根据前后比分变化判断是否是进球 int IsScore(FrameFeature const &ff1, FrameFeature const &ff2); // 根据前后比分变化判断是否是失误或安全球 int IsMissOrSafety(FrameFeature const &ff1, FrameFeature const &ff2); // 根据前后比分变化判断是否是犯规 int IsFoul(FrameFeature const &ff1, FrameFeature const &ff2); // 根据前后比分变化判断是否存在事件 EventType CheckEventType(FrameFeature const &ff1, FrameFeature const &ff2, int &playerId); }; #endif
[ "yef147@gmail.com" ]
yef147@gmail.com
c0f7f7131ff0c7828f799165a1edddf027078dbb
a568d13304fad8f44b1a869837b99ca29687b7d8
/Code_16/night/lesson_7_test_RT/RT_Converse.cpp
51b08ed5fa6559e805dc040a0e35b8f659cd0f2f
[]
no_license
MasterIceZ/Code_CPP
ded570ace902c57e2f5fc84e4b1055d191fc4e3d
bc2561484e58b3a326a5f79282f1e6e359ba63ba
refs/heads/master
2023-02-20T14:13:47.722180
2021-01-21T06:15:03
2021-01-21T06:15:03
331,527,248
0
0
null
2021-01-21T05:51:49
2021-01-21T05:43:59
null
UTF-8
C++
false
false
891
cpp
/* TASK: LANG: CPP AUTHOR: Wichada SCHOOL: RYW */ #include<bits/stdc++.h> using namespace std; map< int,int > a,b; int main() { int q,n,now,ansa=0,ansb=0,ans; scanf("%d",&q); while(q--){ ansa=ansb=0; ans=0; scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d",&now); a[now]++; } for(int i=1;i<=n;i++){ scanf("%d",&now); b[now]++; } for(int i=1;i<=5;i++){ if(b[i]>a[i]){ // printf("%d %d\n",a[i],b[i]); ansa+=((b[i]-a[i])/2); }else ansb+=((a[i]-b[i])/2); if((b[i]+a[i])%2){ ans=-1; break; } } if(ans==-1 || ansa!=ansb)printf("-1\n"); else printf("%d\n",ansa); a.clear(); b.clear(); } return 0; }
[ "w.wichada26@gmail.com" ]
w.wichada26@gmail.com
d350f72fdfa1e1f0b9844ebec17c28eaa34e65c0
1afc8cdbd3a6d627415b346293416ede54bf31e2
/codeforces/1265/C.cpp
52f783381c78e1bb4b6dcd034cf7fd0de02e4313
[]
no_license
umangja/CompetitiveProgrammingSolution
bf6944b81373061124179db5ba2ce2612032e1fe
d622398e40dadadde191c0d9b34a9fcd4735c69c
refs/heads/master
2023-03-25T23:05:09.596577
2021-02-23T09:07:00
2021-03-14T15:22:40
341,297,361
0
0
null
null
null
null
UTF-8
C++
false
false
2,236
cpp
/*input */ //assic value of ('0'-'9') is(48 - 57) and (a-z) is (97-122) and (A-Z) is(65-90) and 32 for space #include<bits/stdc++.h> using namespace std; #define ll long long #define pb push_back #define pii pair<ll int,ll int> #define vpii vector< pii > #define vi vector<ll int> #define vs vector< string > #define vvi vector< vector< ll > > #define inf (ll)1e18 #define all(it,a) for(auto it=(a).begin();it!=(a).end();it++) #define F first #define S second #define sz(x) (ll int)x.size() #define rep(i,a,b) for(ll int i=a;i<b;i++) #define repr(i,a,b) for(ll int i=a;i>b;i--) #define lbnd lower_bound #define ubnd upper_bound #define mp make_pair #define whatis(x) cout << #x << " is " << x << "\n"; #define graph(n) adj(n,vector< ll > () ) //mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int solve() { ll n;cin>>n; vi p(n); ll gf=0,sf=0,bf=0; rep(i,0,n) cin>>p[i]; map<ll,ll> hash; ll num=1; for(ll i=n-1;i>=0;i--) { if(hash.find(p[i])==hash.end()) hash[p[i]]=num++; p[i]=hash[p[i]]; } num--; vi freq(num+1,0); rep(i,0,n) freq[p[i]]++; reverse(freq.begin(), freq.end()); for(ll i=1;i<num+1;i++) freq[i] += freq[i-1]; ll b=0; ll tot=0; rep(i,0,num+1) if(freq[i]<=n/2) b=i; rep(g,0,num+1) { if((freq[b]-freq[g])>=2*(freq[g]+1)) { ll id = lower_bound(freq.begin(), freq.end(),2*freq[g]+1)-freq.begin(); if(id==num+1) break; ll gc = freq[g]; ll sc = freq[id]-gc; ll bc = freq[b]-sc-gc; if(gc>0 && sc>0 && bc>0 && gc<sc && gc<bc && (gc+bc+sc) <=n/2 && (gc+bc+sc)>tot) tot = (gc+bc+sc),gf=gc,bf=bc,sf=sc; } } cout<<gf<<" "<<sf<<" "<<bf<<"\n"; return 0; } int main() { auto start = chrono::high_resolution_clock::now(); ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); ll test_cases=1; cin>>test_cases; while(test_cases--) solve(); auto stop = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::milliseconds>(stop-start); // cout<<"\nduration: "<<(double)duration.count()<<" milliseconds"; }
[ "umang.jain.cse17@itbhu.ac.in" ]
umang.jain.cse17@itbhu.ac.in
8ee4158f4fb825995eff28099618ee09c0641235
b53c09f2264c9ed94c1e9ed88feece12633a15f3
/ihup-fix/HeadTable.cc
2b6ba59f2367c5d125eac70083c9c015be752ff5
[]
no_license
wsgan001/iCHUM-utility-mining
87ce1ccc6f28fc553b824f5242b843e002eb0d6e
d655fd595fd2b5ac524747bab0f43e27642fff09
refs/heads/master
2020-03-25T19:29:35.847415
2015-08-10T06:16:11
2015-08-10T06:16:11
null
0
0
null
null
null
null
GB18030
C++
false
false
1,004
cc
#include<iostream> using namespace std; #include "HeadTable.h" #include "pardhp.h" HeadTable::HeadTable(const double *d){ int i; HeadNode = new item_2[maxitem]; for (i = 0; i<maxitem; i++) { HeadNode[i].item2 = i;//设置其物品编号 HeadNode[i].t_utility = d[i];//设置其物品的TWU值 HeadNode[i].tf =0;//设置初始的tf次数 HeadNode[i].linknode = NULL;//设置指向IHUP节点的link } } HeadTable::~HeadTable(){ clear(); } int compare(const void *a, const void*b){//从大到小排列 item_2 arg1 = *reinterpret_cast<const item_2*>(a); item_2 arg2 = *reinterpret_cast<const item_2*>(b); if (arg1.t_utility < arg2.t_utility) { return 1; } if (arg1.t_utility == arg2.t_utility) { return 0; } if (arg1.t_utility > arg2.t_utility) { return -1; } } void HeadTable::TWU_sort(){ qsort(HeadNode, maxitem, sizeof(item_2), compare); } void HeadTable::clear(){ delete[] HeadNode; //size = 0; }
[ "xiaojue1990@gmail.com" ]
xiaojue1990@gmail.com
82ee69d5eef61c1e7e27496d337d71ef7845e5b8
6717142162a4f06640291cd9b5651af86043d103
/chrome/browser/shell_integration_win.h
294ae248fe29024c8cada0b26489451f2c22a5e1
[ "BSD-3-Clause" ]
permissive
Sharp-Rock/chromium
ad82f1be0ba36563dfab380071b8520c7c39d89a
239aaf3cc8a338de2c668e5b9170d37b0848a238
refs/heads/master
2023-02-25T08:29:01.592526
2019-09-11T12:31:58
2019-09-11T12:31:58
207,808,804
0
0
BSD-3-Clause
2019-09-11T12:37:41
2019-09-11T12:37:41
null
UTF-8
C++
false
false
4,300
h
// Copyright 2016 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. #ifndef CHROME_BROWSER_SHELL_INTEGRATION_WIN_H_ #define CHROME_BROWSER_SHELL_INTEGRATION_WIN_H_ #include <memory> #include <string> #include "base/callback_forward.h" #include "base/files/file_path.h" #include "base/strings/string16.h" namespace shell_integration { namespace win { // Initiates an OS shell flow which (if followed by the user) should set // Chrome as the default browser. Returns false if the flow cannot be // initialized, if it is not supported (introduced for Windows 8) or if the // user cancels the operation. This is a blocking call and requires a FILE // thread. If Chrome is already default browser, no interactive dialog will be // shown and this method returns true. bool SetAsDefaultBrowserUsingIntentPicker(); // Initiates the interaction with the system settings for the default browser. // The function takes care of making sure |on_finished_callback| will get called // exactly once when the interaction is finished. void SetAsDefaultBrowserUsingSystemSettings( const base::Closure& on_finished_callback); // Initiates an OS shell flow which (if followed by the user) should set // Chrome as the default handler for |protocol|. Returns false if the flow // cannot be initialized, if it is not supported (introduced for Windows 8) // or if the user cancels the operation. This is a blocking call and requires // a FILE thread. If Chrome is already default for |protocol|, no interactive // dialog will be shown and this method returns true. bool SetAsDefaultProtocolClientUsingIntentPicker(const std::string& protocol); // Initiates the interaction with the system settings for the default handler of // |protocol|. The function takes care of making sure |on_finished_callback| // will get called exactly once when the interaction is finished. void SetAsDefaultProtocolClientUsingSystemSettings( const std::string& protocol, const base::Closure& on_finished_callback); // Generates an application user model ID (AppUserModelId) for a given app // name and profile path. The returned app id is in the format of // "|app_name|[.<profile_id>]". "profile_id" is appended when user override // the default value. // Note: If the app has an installation specific suffix (e.g. on user-level // Chrome installs), |app_name| should already be suffixed, this method will // then further suffix it with the profile id as described above. base::string16 GetAppModelIdForProfile(const base::string16& app_name, const base::FilePath& profile_path); // Generates an application user model ID (AppUserModelId) for Chromium by // calling GetAppModelIdForProfile() with ShellUtil::GetAppId() as app_name. base::string16 GetChromiumModelIdForProfile(const base::FilePath& profile_path); // Returns the taskbar pin state of Chrome via the IsPinnedToTaskbarCallback. // The first bool is true if the state could be calculated, and the second bool // is true if Chrome is pinned to the taskbar. // The ConnectionErrorCallback is called instead if something wrong happened // with the connection to the remote process. using ConnectionErrorCallback = base::Closure; using IsPinnedToTaskbarCallback = base::Callback<void(bool, bool)>; void GetIsPinnedToTaskbarState( const ConnectionErrorCallback& on_error_callback, const IsPinnedToTaskbarCallback& result_callback); // Migrates existing chrome taskbar pins by tagging them with correct app id. // see http://crbug.com/28104 void MigrateTaskbarPins(); // Migrates all shortcuts in |path| which point to |chrome_exe| such that they // have the appropriate AppUserModelId. Also clears the legacy dual_mode // property from shortcuts with the default chrome app id. // Returns the number of shortcuts migrated. // This method should not be called prior to Windows 7. // This method is only public for the sake of tests and shouldn't be called // externally otherwise. int MigrateShortcutsInPathInternal(const base::FilePath& chrome_exe, const base::FilePath& path); } // namespace win } // namespace shell_integration #endif // CHROME_BROWSER_SHELL_INTEGRATION_WIN_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
859058e39cce779eba438e092e77a19a76fcb81d
e4583509d9f01bc0fa6e7e8516b5466f158c2ff5
/Prototyping/Misthaven - Aaron/Misthaven/Prototyping/Game.cpp
eec83d18211982fa45eb8b691176316b6fab084a
[]
no_license
Acularius/Pixel-Brother
425a5871a43803b504b0aada474a7a9c168ef315
672b639a1d7418902bdf90b91676e68ed7d6a04b
refs/heads/master
2021-01-19T11:03:29.960263
2014-04-13T22:04:26
2014-04-13T22:04:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,559
cpp
#include "Game.h" #include "DrawPrimitives.h" /* this is called by std::sort to sort the list based on layerID * for drawing in the proper order */ bool spriteSortingFunction(Sprite *s1, Sprite *s2) { // return true if s1's layerID is less than s2's layerID return (s1->layerID < s2->layerID); } /* constructor */ Game::Game(void) { /* green background */ stateInfo.bgClearColor.red = 0; stateInfo.bgClearColor.green = 0; stateInfo.bgClearColor.blue = 0; /* init state */ stateInfo.gameState = STATE_GAMEPLAY; renderingTimer = new Timer("RENDER"); updateTimer = new Timer("UPDATE"); // iScore = 0; } /* destructor */ Game::~Game(void) { /* deallocate memory and clean up here. if needed */ } /* * initializeGame() * - this function is called in the constructor to initialize everything related * to the game, i..e loading sprites etc. * - MUST be called prior to any drawing/updating (you should add in checks to ensure this occurs in the right order) */ void Game::initializeGame() { std::cout<<"\n\n BOOT UP: LOADING SPRITES: "; //Loading Text MainMenu* MenuState = new MainMenu(); MenuState->Init(this); states.push_back(MenuState); LevelHome* StateHome = new LevelHome(); StateHome->Init(this); states.push_back(StateHome); LevelOne* StateOne = new LevelOne(); StateOne->Init(this); states.push_back(StateOne); LevelTwo* StateTwo = new LevelTwo(); StateTwo->Init(this); states.push_back(StateTwo); LevelThree* StateThree = new LevelThree(); StateThree->Init(this); states.push_back(StateThree); MessageState* Msg = new MessageState(); Msg->Init(this); states.push_back(Msg); } //=========================================================================================== //=========================================================================================== /* draw() * - this gets called automatically about 30 times per second * - this function just draws the sprites */ void Game::draw() { /* pre-draw - setup the rendering */ PreDraw(); /* draw - actually render to the screen */ DrawGame(); /* post-draw - after rendering, setup the next frame */ PostDraw(); } /* * Pre-Draw() is for setting up things that need to happen in order to draw * the game, i.e. sorting, splitting things into appropriate lists etc. */ void Game::PreDraw() { /* clear the screen */ glViewport(0,0,stateInfo.windowWidth,stateInfo.windowHeight); glClearColor(stateInfo.bgClearColor.red, stateInfo.bgClearColor.green, stateInfo.bgClearColor.blue, 0); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glLoadIdentity(); // clear out the transformation matrix glEnable(GL_TEXTURE_2D); // turn on texturing // if we update our timer it will tell us the elapsed time since the previous // frame that we rendered renderingTimer->tick(); /* sort the sprites by layerID so we draw them in the right order */ std::sort(spriteListToDraw.begin(), spriteListToDraw.end(), spriteSortingFunction); } /* * DrawGame() * - this is the actual drawing of the current frame of the game. */ void Game::DrawGame() { /* here is where your drawing stuff goes */ drawSprites(); glDisable(GL_TEXTURE_2D); //drawTestPrimitives(); // Test draw the primitives /* this makes it actually show up on the screen */ glutSwapBuffers(); } /* * PostDraw() * - in here you should clean up and set up things for the next frame * - i.e. once I've used my assets, I can change them to set up things for * the next frame, usually just memory management or setting up game state * boolean values etc. */ void Game::PostDraw() { // nothing here at the moment } /* drawSprites() * - this function is what actually draws the sprites * onto the screen at their appropriate location * - it actually loops through a list of active sprites * and then sorts them by their layerID and then draws them * - the sorting has to happen so that you draw from back to front * just like a painter and a canvas. */ void Game::drawSprites() { /* we could just do the following to draw the three sprites but that would be silly since we have a list of sprites to draw stored, so all we need to do is go through the list and draw eaach sprite in the list */ /* // silly way testSprite->draw(); animatedSprite->draw(); animatedSprite2->draw(); */ /* better way */ /* this is better because it doesn't matter how many sprites we have, they will always be drawn */ // std::vector<Sprite*>::iterator it; // for(it=spriteListToDraw.begin(); it != spriteListToDraw.end(); it++) // { // Sprite *s = (*it); // s->draw(); // } // //=========================================================================================== // SPRITE ITERATOR //=========================================================================================== std::vector<GameState*>::iterator it; for (it = states.begin(); it != states.end(); it++) { if (*it) { GameState* s = (*it); if(s->active==true) s->Draw(); } } } /* For testing purposes for drawing primitives for GDWII * milestone */ void Game::drawTestPrimitives() { /* Score */ // setColor(1,1,1); // drawText("SCORE: ",350,290); // drawNum(iScore,430,290); } /* update() - this function is essentially the game loop it gets called often and as such you don't actually need a "loop" to define the game it happens behind the scenes - think of this function as one iteration of the game loop - if you need to update physics calculations, sprite animation info, or sound etc, it goes in here */ void Game::update() { // Time updateTimer->tick(); //=========================================================================================== // UPDATE ITERATOR //=========================================================================================== std::vector<GameState*>::iterator it; for (it = states.begin(); it != states.end(); it++) { if (*it) { GameState* s = (*it); if(s->active==true) s->Update(); } } } /* * addSpriteToDrawList() * - this function simply pushes the sprite to the end of the list */ void Game::addSpriteToDrawList(Sprite *s) { if(s) { /* push the sprite to the back of the list */ this->spriteListToDraw.push_back(s); } } /*************************************************/ /* INPUT - keyboard/mouse functions below */ /*************************************************/ /* keyboardDown() - this gets called when you press a key down - you are given the key that was pressed and where the (x,y) location of the mouse is when pressed */ void Game::keyboardDown(unsigned char key, int mouseX, int mouseY) { switch(key) { case 32: // the space bar break; //case 27: // the escape key case 'q': // the 'q' key exit(1); break; } //=========================================================================================== // KEYDOWN ITERATOR //=========================================================================================== std::vector<GameState*>::iterator it; for (it = states.begin(); it != states.end(); it++) { if (*it) { GameState* s = (*it); if(s->active==true) s->KeyDown(key); } } //=========================================================================================== // TESTING KEYS (StateChanges) //=========================================================================================== switch(key) { case '1': { SwitchStateTo (StateHome, 1); break; } case '2': { SwitchStateTo (StateHome, 2); // playEnvironment(); //StateControl(UI,true,6); MessageControl(Msg, 3, 7); break; } case '3': { SwitchStateTo (StateHome, 3); //StateControl(UI,true,6); MessageControl(Msg, 2, 7); break; } case '4': { SwitchStateTo (StateHome, 4); //StateControl(UI,true,6); MessageControl(Msg, 1, 7); break; } case '5': { SwitchStateTo (StateHome, 5); //StateControl(UI,true,6); MessageControl(Msg, 0, 7); break; } case 't': { std::cout<<"YOLO\n"; break; } case 'm': { // playBeepSound(); break; } case 27: { StateToggle (MenuState, 1); StateToggle (StateOne, 2); //StateToggle (UI,6); break; } } } } //=========================================================================================== //=========================================================================================== /* keyboardUp() - this gets called when you lift a key up - you are given the key that was pressed and where the (x,y) location of the mouse is when pressed */ void Game::keyboardUp(unsigned char key, int mouseX, int mouseY) { switch(key) { case 32: // the space bar break; //case 27: // the escape key case 'q': // the 'q' key exit(1); break; } std::vector<GameState*>::iterator it; for (it = states.begin(); it != states.end(); it++) { if (*it) { GameState* s = (*it); if(s->active==true) s->KeyUp(key); } } } ////=========================================================================================== //// FMOD SOUND FUNCTION ////=========================================================================================== // ////Audio.lib seems much easier to use. Consider reimplementing sounds later. // // int Game::playSound(bool Sound) // { // // bool soundDone= false; // //declare variable for FMOD system object // FMOD::System* system; // //allocate memory for the FMOD system object // FMOD_RESULT result = FMOD::System_Create(&system); // //initialize the FMOD system object // system->init(32, FMOD_INIT_NORMAL, NULL); // //declare variable for the sound object // FMOD::Sound* sound; // //created sound object and specify the sound // // result = system->createSound("Cathedral_of_Light.mp3",FMOD_LOOP_NORMAL,NULL, &sound); // // play sound - 1st parameter can be combined flags (| separator) // FMOD::Channel* channel = 0; // // //start sound // // bool pauseSound=false; // // channel->isPlaying(&pauseSound); // // result = system->playSound(FMOD_CHANNEL_FREE, sound, Sound, &channel); // soundDone=true; // // // while (soundDone!=true) // { // channel->setPaused(false); // system->update(); // // //} // // release resources // result = sound->release(); // result = system->close(); // result = system->release(); // } // return 0; // // } // // //int Game::playBeepSound() // { // // bool soundDone=false; // //declare variable for FMOD system object // FMOD::System* system; // //allocate memory for the FMOD system object // FMOD_RESULT result = FMOD::System_Create(&system); // //initialize the FMOD system object // system->init(32, FMOD_INIT_NORMAL, NULL); // //declare variable for the sound object // FMOD::Sound* sound; // //created sound object and specify the sound // // result = system->createSound("Futuristic Fly.mp3",FMOD_DEFAULT,NULL, &sound); // // play sound - 1st parameter can be combined flags (| separator) // FMOD::Channel* channel = 0; // bool pauseSound = false; // // //start sound // // channel->isPlaying(&pauseSound); // // result = system->playSound(FMOD_CHANNEL_FREE, sound,false, &channel); // soundDone=true; // // // while (soundDone!=true) // { // channel->setPaused(false); // system->update(); // // //} // // release resources // result = sound->release(); // result = system->close(); // result = system->release(); // } // return 0; // // } // // // int Game::playEnvironment() // { // bool soundDone=false; // FMOD::System* system; // FMOD_RESULT result = FMOD::System_Create(&system); // system->init(32, FMOD_INIT_NORMAL, NULL); // FMOD::Sound* sound; // // result = system->createSound("Ocean.WAV",FMOD_LOOP_NORMAL,NULL, &sound); // FMOD::Channel* channel = 0; // bool pauseSound = false; // // // channel->isPlaying(&pauseSound); // // result = system->playSound(FMOD_CHANNEL_FREE, sound,false, &channel); // soundDone=true; // // // while (soundDone!=true) // { // channel->setPaused(false); // system->update(); // // result = sound->release(); // result = system->close(); // result = system->release(); // } // return 0; // } // ////=========================================================================================== //===========================================================================================
[ "aaron-metallion@hotmail.com" ]
aaron-metallion@hotmail.com
e9c6e754630fa0b20dd53e5f307a166f65026ee3
f7a6fd59ded5c9259649ddb2258391715cd16baa
/src/GameInput.cpp
41f427b535eeea877555b60d511880025541e538
[]
no_license
sillybear/StepMania-3.9-r2017
1b25cc9cd06f53c9fddea7ea98aa939146c66873
ae40fb35f9d6c439bb1c9820dc2daf249a675b93
refs/heads/master
2021-01-19T09:57:03.481713
2018-02-09T21:39:03
2018-02-09T21:39:03
82,153,677
1
0
null
null
null
null
UTF-8
C++
false
false
1,727
cpp
#include "global.h" #include "GameInput.h" #include "RageLog.h" #include "RageUtil.h" CString GameInput::toString() { return ssprintf("%d-%d", controller, button ); } bool GameInput::fromString( CString s ) { CStringArray a; split( s, "-", a); if( a.size() != 2 ) { MakeInvalid(); return false; } controller = (GameController)atoi( a[0] ); button = (GameButton)atoi( a[1] ); return true; }; /* * (c) 2001-2004 Chris Danford * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * 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 OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */
[ "jindev2k7@yahoo.com" ]
jindev2k7@yahoo.com
4629d83f1129001d753402d50b41b479cbe2427e
c776476e9d06b3779d744641e758ac3a2c15cddc
/examples/litmus/c/run-scripts/tmp_1/Z6.2+dmb.sy+ctrlisb+addr.c.cbmc_out.cpp
775976233ef36198dd545182ab74320205970f3f
[]
no_license
ashutosh0gupta/llvm_bmc
aaac7961c723ba6f7ffd77a39559e0e52432eade
0287c4fb180244e6b3c599a9902507f05c8a7234
refs/heads/master
2023-08-02T17:14:06.178723
2023-07-31T10:46:53
2023-07-31T10:46:53
143,100,825
3
4
null
2023-05-25T05:50:55
2018-08-01T03:47:00
C++
UTF-8
C++
false
false
41,367
cpp
// 0:vars:3 // 3:atom_1_X0_1:1 // 4:atom_2_X0_1:1 // 5:thr0:1 // 6:thr1:1 // 7:thr2:1 #define ADDRSIZE 8 #define NPROC 4 #define NCONTEXT 1 #define ASSUME(stmt) __CPROVER_assume(stmt) #define ASSERT(stmt) __CPROVER_assert(stmt, "error") #define max(a,b) (a>b?a:b) char __get_rng(); char get_rng( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } char get_rng_th( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } int main(int argc, char **argv) { // declare arrays for intial value version in contexts int meminit_[ADDRSIZE*NCONTEXT]; #define meminit(x,k) meminit_[(x)*NCONTEXT+k] int coinit_[ADDRSIZE*NCONTEXT]; #define coinit(x,k) coinit_[(x)*NCONTEXT+k] int deltainit_[ADDRSIZE*NCONTEXT]; #define deltainit(x,k) deltainit_[(x)*NCONTEXT+k] // declare arrays for running value version in contexts int mem_[ADDRSIZE*NCONTEXT]; #define mem(x,k) mem_[(x)*NCONTEXT+k] int co_[ADDRSIZE*NCONTEXT]; #define co(x,k) co_[(x)*NCONTEXT+k] int delta_[ADDRSIZE*NCONTEXT]; #define delta(x,k) delta_[(x)*NCONTEXT+k] // declare arrays for local buffer and observed writes int buff_[NPROC*ADDRSIZE]; #define buff(x,k) buff_[(x)*ADDRSIZE+k] int pw_[NPROC*ADDRSIZE]; #define pw(x,k) pw_[(x)*ADDRSIZE+k] // declare arrays for context stamps char cr_[NPROC*ADDRSIZE]; #define cr(x,k) cr_[(x)*ADDRSIZE+k] char iw_[NPROC*ADDRSIZE]; #define iw(x,k) iw_[(x)*ADDRSIZE+k] char cw_[NPROC*ADDRSIZE]; #define cw(x,k) cw_[(x)*ADDRSIZE+k] char cx_[NPROC*ADDRSIZE]; #define cx(x,k) cx_[(x)*ADDRSIZE+k] char is_[NPROC*ADDRSIZE]; #define is(x,k) is_[(x)*ADDRSIZE+k] char cs_[NPROC*ADDRSIZE]; #define cs(x,k) cs_[(x)*ADDRSIZE+k] char crmax_[NPROC*ADDRSIZE]; #define crmax(x,k) crmax_[(x)*ADDRSIZE+k] char sforbid_[ADDRSIZE*NCONTEXT]; #define sforbid(x,k) sforbid_[(x)*NCONTEXT+k] // declare arrays for synchronizations int cl[NPROC]; int cdy[NPROC]; int cds[NPROC]; int cdl[NPROC]; int cisb[NPROC]; int caddr[NPROC]; int cctrl[NPROC]; int cstart[NPROC]; int creturn[NPROC]; // declare arrays for contexts activity int active[NCONTEXT]; int ctx_used[NCONTEXT]; int r0= 0; char creg_r0; int r1= 0; char creg_r1; int r2= 0; char creg_r2; int r3= 0; char creg_r3; int r4= 0; char creg_r4; int r5= 0; char creg_r5; int r6= 0; char creg_r6; int r7= 0; char creg_r7; int r8= 0; char creg_r8; int r9= 0; char creg_r9; int r10= 0; char creg_r10; int r11= 0; char creg_r11; int r12= 0; char creg_r12; int r13= 0; char creg_r13; int r14= 0; char creg_r14; char old_cctrl= 0; char old_cr= 0; char old_cdy= 0; char old_cw= 0; char new_creg= 0; buff(0,0) = 0; pw(0,0) = 0; cr(0,0) = 0; iw(0,0) = 0; cw(0,0) = 0; cx(0,0) = 0; is(0,0) = 0; cs(0,0) = 0; crmax(0,0) = 0; buff(0,1) = 0; pw(0,1) = 0; cr(0,1) = 0; iw(0,1) = 0; cw(0,1) = 0; cx(0,1) = 0; is(0,1) = 0; cs(0,1) = 0; crmax(0,1) = 0; buff(0,2) = 0; pw(0,2) = 0; cr(0,2) = 0; iw(0,2) = 0; cw(0,2) = 0; cx(0,2) = 0; is(0,2) = 0; cs(0,2) = 0; crmax(0,2) = 0; buff(0,3) = 0; pw(0,3) = 0; cr(0,3) = 0; iw(0,3) = 0; cw(0,3) = 0; cx(0,3) = 0; is(0,3) = 0; cs(0,3) = 0; crmax(0,3) = 0; buff(0,4) = 0; pw(0,4) = 0; cr(0,4) = 0; iw(0,4) = 0; cw(0,4) = 0; cx(0,4) = 0; is(0,4) = 0; cs(0,4) = 0; crmax(0,4) = 0; buff(0,5) = 0; pw(0,5) = 0; cr(0,5) = 0; iw(0,5) = 0; cw(0,5) = 0; cx(0,5) = 0; is(0,5) = 0; cs(0,5) = 0; crmax(0,5) = 0; buff(0,6) = 0; pw(0,6) = 0; cr(0,6) = 0; iw(0,6) = 0; cw(0,6) = 0; cx(0,6) = 0; is(0,6) = 0; cs(0,6) = 0; crmax(0,6) = 0; buff(0,7) = 0; pw(0,7) = 0; cr(0,7) = 0; iw(0,7) = 0; cw(0,7) = 0; cx(0,7) = 0; is(0,7) = 0; cs(0,7) = 0; crmax(0,7) = 0; cl[0] = 0; cdy[0] = 0; cds[0] = 0; cdl[0] = 0; cisb[0] = 0; caddr[0] = 0; cctrl[0] = 0; cstart[0] = get_rng(0,NCONTEXT-1); creturn[0] = get_rng(0,NCONTEXT-1); buff(1,0) = 0; pw(1,0) = 0; cr(1,0) = 0; iw(1,0) = 0; cw(1,0) = 0; cx(1,0) = 0; is(1,0) = 0; cs(1,0) = 0; crmax(1,0) = 0; buff(1,1) = 0; pw(1,1) = 0; cr(1,1) = 0; iw(1,1) = 0; cw(1,1) = 0; cx(1,1) = 0; is(1,1) = 0; cs(1,1) = 0; crmax(1,1) = 0; buff(1,2) = 0; pw(1,2) = 0; cr(1,2) = 0; iw(1,2) = 0; cw(1,2) = 0; cx(1,2) = 0; is(1,2) = 0; cs(1,2) = 0; crmax(1,2) = 0; buff(1,3) = 0; pw(1,3) = 0; cr(1,3) = 0; iw(1,3) = 0; cw(1,3) = 0; cx(1,3) = 0; is(1,3) = 0; cs(1,3) = 0; crmax(1,3) = 0; buff(1,4) = 0; pw(1,4) = 0; cr(1,4) = 0; iw(1,4) = 0; cw(1,4) = 0; cx(1,4) = 0; is(1,4) = 0; cs(1,4) = 0; crmax(1,4) = 0; buff(1,5) = 0; pw(1,5) = 0; cr(1,5) = 0; iw(1,5) = 0; cw(1,5) = 0; cx(1,5) = 0; is(1,5) = 0; cs(1,5) = 0; crmax(1,5) = 0; buff(1,6) = 0; pw(1,6) = 0; cr(1,6) = 0; iw(1,6) = 0; cw(1,6) = 0; cx(1,6) = 0; is(1,6) = 0; cs(1,6) = 0; crmax(1,6) = 0; buff(1,7) = 0; pw(1,7) = 0; cr(1,7) = 0; iw(1,7) = 0; cw(1,7) = 0; cx(1,7) = 0; is(1,7) = 0; cs(1,7) = 0; crmax(1,7) = 0; cl[1] = 0; cdy[1] = 0; cds[1] = 0; cdl[1] = 0; cisb[1] = 0; caddr[1] = 0; cctrl[1] = 0; cstart[1] = get_rng(0,NCONTEXT-1); creturn[1] = get_rng(0,NCONTEXT-1); buff(2,0) = 0; pw(2,0) = 0; cr(2,0) = 0; iw(2,0) = 0; cw(2,0) = 0; cx(2,0) = 0; is(2,0) = 0; cs(2,0) = 0; crmax(2,0) = 0; buff(2,1) = 0; pw(2,1) = 0; cr(2,1) = 0; iw(2,1) = 0; cw(2,1) = 0; cx(2,1) = 0; is(2,1) = 0; cs(2,1) = 0; crmax(2,1) = 0; buff(2,2) = 0; pw(2,2) = 0; cr(2,2) = 0; iw(2,2) = 0; cw(2,2) = 0; cx(2,2) = 0; is(2,2) = 0; cs(2,2) = 0; crmax(2,2) = 0; buff(2,3) = 0; pw(2,3) = 0; cr(2,3) = 0; iw(2,3) = 0; cw(2,3) = 0; cx(2,3) = 0; is(2,3) = 0; cs(2,3) = 0; crmax(2,3) = 0; buff(2,4) = 0; pw(2,4) = 0; cr(2,4) = 0; iw(2,4) = 0; cw(2,4) = 0; cx(2,4) = 0; is(2,4) = 0; cs(2,4) = 0; crmax(2,4) = 0; buff(2,5) = 0; pw(2,5) = 0; cr(2,5) = 0; iw(2,5) = 0; cw(2,5) = 0; cx(2,5) = 0; is(2,5) = 0; cs(2,5) = 0; crmax(2,5) = 0; buff(2,6) = 0; pw(2,6) = 0; cr(2,6) = 0; iw(2,6) = 0; cw(2,6) = 0; cx(2,6) = 0; is(2,6) = 0; cs(2,6) = 0; crmax(2,6) = 0; buff(2,7) = 0; pw(2,7) = 0; cr(2,7) = 0; iw(2,7) = 0; cw(2,7) = 0; cx(2,7) = 0; is(2,7) = 0; cs(2,7) = 0; crmax(2,7) = 0; cl[2] = 0; cdy[2] = 0; cds[2] = 0; cdl[2] = 0; cisb[2] = 0; caddr[2] = 0; cctrl[2] = 0; cstart[2] = get_rng(0,NCONTEXT-1); creturn[2] = get_rng(0,NCONTEXT-1); buff(3,0) = 0; pw(3,0) = 0; cr(3,0) = 0; iw(3,0) = 0; cw(3,0) = 0; cx(3,0) = 0; is(3,0) = 0; cs(3,0) = 0; crmax(3,0) = 0; buff(3,1) = 0; pw(3,1) = 0; cr(3,1) = 0; iw(3,1) = 0; cw(3,1) = 0; cx(3,1) = 0; is(3,1) = 0; cs(3,1) = 0; crmax(3,1) = 0; buff(3,2) = 0; pw(3,2) = 0; cr(3,2) = 0; iw(3,2) = 0; cw(3,2) = 0; cx(3,2) = 0; is(3,2) = 0; cs(3,2) = 0; crmax(3,2) = 0; buff(3,3) = 0; pw(3,3) = 0; cr(3,3) = 0; iw(3,3) = 0; cw(3,3) = 0; cx(3,3) = 0; is(3,3) = 0; cs(3,3) = 0; crmax(3,3) = 0; buff(3,4) = 0; pw(3,4) = 0; cr(3,4) = 0; iw(3,4) = 0; cw(3,4) = 0; cx(3,4) = 0; is(3,4) = 0; cs(3,4) = 0; crmax(3,4) = 0; buff(3,5) = 0; pw(3,5) = 0; cr(3,5) = 0; iw(3,5) = 0; cw(3,5) = 0; cx(3,5) = 0; is(3,5) = 0; cs(3,5) = 0; crmax(3,5) = 0; buff(3,6) = 0; pw(3,6) = 0; cr(3,6) = 0; iw(3,6) = 0; cw(3,6) = 0; cx(3,6) = 0; is(3,6) = 0; cs(3,6) = 0; crmax(3,6) = 0; buff(3,7) = 0; pw(3,7) = 0; cr(3,7) = 0; iw(3,7) = 0; cw(3,7) = 0; cx(3,7) = 0; is(3,7) = 0; cs(3,7) = 0; crmax(3,7) = 0; cl[3] = 0; cdy[3] = 0; cds[3] = 0; cdl[3] = 0; cisb[3] = 0; caddr[3] = 0; cctrl[3] = 0; cstart[3] = get_rng(0,NCONTEXT-1); creturn[3] = get_rng(0,NCONTEXT-1); // Dumping initializations mem(0+0,0) = 0; mem(0+1,0) = 0; mem(0+2,0) = 0; mem(3+0,0) = 0; mem(4+0,0) = 0; mem(5+0,0) = 0; mem(6+0,0) = 0; mem(7+0,0) = 0; // Dumping context matching equalities co(0,0) = 0; delta(0,0) = -1; co(1,0) = 0; delta(1,0) = -1; co(2,0) = 0; delta(2,0) = -1; co(3,0) = 0; delta(3,0) = -1; co(4,0) = 0; delta(4,0) = -1; co(5,0) = 0; delta(5,0) = -1; co(6,0) = 0; delta(6,0) = -1; co(7,0) = 0; delta(7,0) = -1; // Dumping thread 1 int ret_thread_1 = 0; cdy[1] = get_rng(0,NCONTEXT-1); ASSUME(cdy[1] >= cstart[1]); T1BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !35, metadata !DIExpression()), !dbg !44 // br label %label_1, !dbg !45 goto T1BLOCK1; T1BLOCK1: // call void @llvm.dbg.label(metadata !43), !dbg !46 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !36, metadata !DIExpression()), !dbg !47 // call void @llvm.dbg.value(metadata i64 2, metadata !39, metadata !DIExpression()), !dbg !47 // store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !48 // ST: Guess iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW old_cw = cw(1,0); cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM // Check ASSUME(active[iw(1,0)] == 1); ASSUME(active[cw(1,0)] == 1); ASSUME(sforbid(0,cw(1,0))== 0); ASSUME(iw(1,0) >= 0); ASSUME(iw(1,0) >= 0); ASSUME(cw(1,0) >= iw(1,0)); ASSUME(cw(1,0) >= old_cw); ASSUME(cw(1,0) >= cr(1,0)); ASSUME(cw(1,0) >= cl[1]); ASSUME(cw(1,0) >= cisb[1]); ASSUME(cw(1,0) >= cdy[1]); ASSUME(cw(1,0) >= cdl[1]); ASSUME(cw(1,0) >= cds[1]); ASSUME(cw(1,0) >= cctrl[1]); ASSUME(cw(1,0) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0) = 2; mem(0,cw(1,0)) = 2; co(0,cw(1,0))+=1; delta(0,cw(1,0)) = -1; ASSUME(creturn[1] >= cw(1,0)); // call void (...) @dmbsy(), !dbg !49 // dumbsy: Guess old_cdy = cdy[1]; cdy[1] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[1] >= old_cdy); ASSUME(cdy[1] >= cisb[1]); ASSUME(cdy[1] >= cdl[1]); ASSUME(cdy[1] >= cds[1]); ASSUME(cdy[1] >= cctrl[1]); ASSUME(cdy[1] >= cw(1,0+0)); ASSUME(cdy[1] >= cw(1,0+1)); ASSUME(cdy[1] >= cw(1,0+2)); ASSUME(cdy[1] >= cw(1,3+0)); ASSUME(cdy[1] >= cw(1,4+0)); ASSUME(cdy[1] >= cw(1,5+0)); ASSUME(cdy[1] >= cw(1,6+0)); ASSUME(cdy[1] >= cw(1,7+0)); ASSUME(cdy[1] >= cr(1,0+0)); ASSUME(cdy[1] >= cr(1,0+1)); ASSUME(cdy[1] >= cr(1,0+2)); ASSUME(cdy[1] >= cr(1,3+0)); ASSUME(cdy[1] >= cr(1,4+0)); ASSUME(cdy[1] >= cr(1,5+0)); ASSUME(cdy[1] >= cr(1,6+0)); ASSUME(cdy[1] >= cr(1,7+0)); ASSUME(creturn[1] >= cdy[1]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !40, metadata !DIExpression()), !dbg !50 // call void @llvm.dbg.value(metadata i64 1, metadata !42, metadata !DIExpression()), !dbg !50 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !51 // ST: Guess iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW old_cw = cw(1,0+1*1); cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM // Check ASSUME(active[iw(1,0+1*1)] == 1); ASSUME(active[cw(1,0+1*1)] == 1); ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(cw(1,0+1*1) >= iw(1,0+1*1)); ASSUME(cw(1,0+1*1) >= old_cw); ASSUME(cw(1,0+1*1) >= cr(1,0+1*1)); ASSUME(cw(1,0+1*1) >= cl[1]); ASSUME(cw(1,0+1*1) >= cisb[1]); ASSUME(cw(1,0+1*1) >= cdy[1]); ASSUME(cw(1,0+1*1) >= cdl[1]); ASSUME(cw(1,0+1*1) >= cds[1]); ASSUME(cw(1,0+1*1) >= cctrl[1]); ASSUME(cw(1,0+1*1) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0+1*1) = 1; mem(0+1*1,cw(1,0+1*1)) = 1; co(0+1*1,cw(1,0+1*1))+=1; delta(0+1*1,cw(1,0+1*1)) = -1; ASSUME(creturn[1] >= cw(1,0+1*1)); // ret i8* null, !dbg !52 ret_thread_1 = (- 1); // Dumping thread 2 int ret_thread_2 = 0; cdy[2] = get_rng(0,NCONTEXT-1); ASSUME(cdy[2] >= cstart[2]); T2BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !55, metadata !DIExpression()), !dbg !70 // br label %label_2, !dbg !52 goto T2BLOCK1; T2BLOCK1: // call void @llvm.dbg.label(metadata !68), !dbg !72 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !58, metadata !DIExpression()), !dbg !73 // %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !55 // LD: Guess old_cr = cr(2,0+1*1); cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,0+1*1)] == 2); ASSUME(cr(2,0+1*1) >= iw(2,0+1*1)); ASSUME(cr(2,0+1*1) >= 0); ASSUME(cr(2,0+1*1) >= cdy[2]); ASSUME(cr(2,0+1*1) >= cisb[2]); ASSUME(cr(2,0+1*1) >= cdl[2]); ASSUME(cr(2,0+1*1) >= cl[2]); // Update creg_r0 = cr(2,0+1*1); crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1)); caddr[2] = max(caddr[2],0); if(cr(2,0+1*1) < cw(2,0+1*1)) { r0 = buff(2,0+1*1); } else { if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) { ASSUME(cr(2,0+1*1) >= old_cr); } pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1)); r0 = mem(0+1*1,cr(2,0+1*1)); } ASSUME(creturn[2] >= cr(2,0+1*1)); // call void @llvm.dbg.value(metadata i64 %0, metadata !60, metadata !DIExpression()), !dbg !73 // %conv = trunc i64 %0 to i32, !dbg !56 // call void @llvm.dbg.value(metadata i32 %conv, metadata !56, metadata !DIExpression()), !dbg !70 // %tobool = icmp ne i32 %conv, 0, !dbg !57 // br i1 %tobool, label %if.then, label %if.else, !dbg !59 old_cctrl = cctrl[2]; cctrl[2] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[2] >= old_cctrl); ASSUME(cctrl[2] >= creg_r0); ASSUME(cctrl[2] >= 0); if((r0!=0)) { goto T2BLOCK2; } else { goto T2BLOCK3; } T2BLOCK2: // br label %lbl_LC00, !dbg !60 goto T2BLOCK4; T2BLOCK3: // br label %lbl_LC00, !dbg !61 goto T2BLOCK4; T2BLOCK4: // call void @llvm.dbg.label(metadata !69), !dbg !81 // call void (...) @isb(), !dbg !63 // isb: Guess cisb[2] = get_rng(0,NCONTEXT-1); // Check ASSUME(cisb[2] >= cdy[2]); ASSUME(cisb[2] >= cctrl[2]); ASSUME(cisb[2] >= caddr[2]); ASSUME(creturn[2] >= cisb[2]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !61, metadata !DIExpression()), !dbg !83 // call void @llvm.dbg.value(metadata i64 1, metadata !63, metadata !DIExpression()), !dbg !83 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !65 // ST: Guess iw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,0+2*1); cw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,0+2*1)] == 2); ASSUME(active[cw(2,0+2*1)] == 2); ASSUME(sforbid(0+2*1,cw(2,0+2*1))== 0); ASSUME(iw(2,0+2*1) >= 0); ASSUME(iw(2,0+2*1) >= 0); ASSUME(cw(2,0+2*1) >= iw(2,0+2*1)); ASSUME(cw(2,0+2*1) >= old_cw); ASSUME(cw(2,0+2*1) >= cr(2,0+2*1)); ASSUME(cw(2,0+2*1) >= cl[2]); ASSUME(cw(2,0+2*1) >= cisb[2]); ASSUME(cw(2,0+2*1) >= cdy[2]); ASSUME(cw(2,0+2*1) >= cdl[2]); ASSUME(cw(2,0+2*1) >= cds[2]); ASSUME(cw(2,0+2*1) >= cctrl[2]); ASSUME(cw(2,0+2*1) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,0+2*1) = 1; mem(0+2*1,cw(2,0+2*1)) = 1; co(0+2*1,cw(2,0+2*1))+=1; delta(0+2*1,cw(2,0+2*1)) = -1; ASSUME(creturn[2] >= cw(2,0+2*1)); // %cmp = icmp eq i32 %conv, 1, !dbg !66 // %conv1 = zext i1 %cmp to i32, !dbg !66 // call void @llvm.dbg.value(metadata i32 %conv1, metadata !64, metadata !DIExpression()), !dbg !70 // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !65, metadata !DIExpression()), !dbg !86 // %1 = zext i32 %conv1 to i64 // call void @llvm.dbg.value(metadata i64 %1, metadata !67, metadata !DIExpression()), !dbg !86 // store atomic i64 %1, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !68 // ST: Guess iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,3); cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,3)] == 2); ASSUME(active[cw(2,3)] == 2); ASSUME(sforbid(3,cw(2,3))== 0); ASSUME(iw(2,3) >= max(creg_r0,0)); ASSUME(iw(2,3) >= 0); ASSUME(cw(2,3) >= iw(2,3)); ASSUME(cw(2,3) >= old_cw); ASSUME(cw(2,3) >= cr(2,3)); ASSUME(cw(2,3) >= cl[2]); ASSUME(cw(2,3) >= cisb[2]); ASSUME(cw(2,3) >= cdy[2]); ASSUME(cw(2,3) >= cdl[2]); ASSUME(cw(2,3) >= cds[2]); ASSUME(cw(2,3) >= cctrl[2]); ASSUME(cw(2,3) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,3) = (r0==1); mem(3,cw(2,3)) = (r0==1); co(3,cw(2,3))+=1; delta(3,cw(2,3)) = -1; ASSUME(creturn[2] >= cw(2,3)); // ret i8* null, !dbg !69 ret_thread_2 = (- 1); // Dumping thread 3 int ret_thread_3 = 0; cdy[3] = get_rng(0,NCONTEXT-1); ASSUME(cdy[3] >= cstart[3]); T3BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !91, metadata !DIExpression()), !dbg !105 // br label %label_3, !dbg !52 goto T3BLOCK1; T3BLOCK1: // call void @llvm.dbg.label(metadata !104), !dbg !107 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !93, metadata !DIExpression()), !dbg !108 // %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !55 // LD: Guess old_cr = cr(3,0+2*1); cr(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM // Check ASSUME(active[cr(3,0+2*1)] == 3); ASSUME(cr(3,0+2*1) >= iw(3,0+2*1)); ASSUME(cr(3,0+2*1) >= 0); ASSUME(cr(3,0+2*1) >= cdy[3]); ASSUME(cr(3,0+2*1) >= cisb[3]); ASSUME(cr(3,0+2*1) >= cdl[3]); ASSUME(cr(3,0+2*1) >= cl[3]); // Update creg_r1 = cr(3,0+2*1); crmax(3,0+2*1) = max(crmax(3,0+2*1),cr(3,0+2*1)); caddr[3] = max(caddr[3],0); if(cr(3,0+2*1) < cw(3,0+2*1)) { r1 = buff(3,0+2*1); } else { if(pw(3,0+2*1) != co(0+2*1,cr(3,0+2*1))) { ASSUME(cr(3,0+2*1) >= old_cr); } pw(3,0+2*1) = co(0+2*1,cr(3,0+2*1)); r1 = mem(0+2*1,cr(3,0+2*1)); } ASSUME(creturn[3] >= cr(3,0+2*1)); // call void @llvm.dbg.value(metadata i64 %0, metadata !95, metadata !DIExpression()), !dbg !108 // %conv = trunc i64 %0 to i32, !dbg !56 // call void @llvm.dbg.value(metadata i32 %conv, metadata !92, metadata !DIExpression()), !dbg !105 // %xor = xor i32 %conv, %conv, !dbg !57 creg_r2 = max(creg_r1,creg_r1); ASSUME(active[creg_r2] == 3); r2 = r1 ^ r1; // call void @llvm.dbg.value(metadata i32 %xor, metadata !96, metadata !DIExpression()), !dbg !105 // %add = add nsw i32 0, %xor, !dbg !58 creg_r3 = max(0,creg_r2); ASSUME(active[creg_r3] == 3); r3 = 0 + r2; // %idxprom = sext i32 %add to i64, !dbg !58 // %arrayidx = getelementptr inbounds [3 x i64], [3 x i64]* @vars, i64 0, i64 %idxprom, !dbg !58 r4 = 0+r3*1; ASSUME(creg_r4 >= 0); ASSUME(creg_r4 >= creg_r3); ASSUME(active[creg_r4] == 3); // call void @llvm.dbg.value(metadata i64* %arrayidx, metadata !97, metadata !DIExpression()), !dbg !113 // call void @llvm.dbg.value(metadata i64 1, metadata !99, metadata !DIExpression()), !dbg !113 // store atomic i64 1, i64* %arrayidx monotonic, align 8, !dbg !58 // ST: Guess iw(3,r4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW old_cw = cw(3,r4); cw(3,r4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM // Check ASSUME(active[iw(3,r4)] == 3); ASSUME(active[cw(3,r4)] == 3); ASSUME(sforbid(r4,cw(3,r4))== 0); ASSUME(iw(3,r4) >= 0); ASSUME(iw(3,r4) >= creg_r4); ASSUME(cw(3,r4) >= iw(3,r4)); ASSUME(cw(3,r4) >= old_cw); ASSUME(cw(3,r4) >= cr(3,r4)); ASSUME(cw(3,r4) >= cl[3]); ASSUME(cw(3,r4) >= cisb[3]); ASSUME(cw(3,r4) >= cdy[3]); ASSUME(cw(3,r4) >= cdl[3]); ASSUME(cw(3,r4) >= cds[3]); ASSUME(cw(3,r4) >= cctrl[3]); ASSUME(cw(3,r4) >= caddr[3]); // Update caddr[3] = max(caddr[3],creg_r4); buff(3,r4) = 1; mem(r4,cw(3,r4)) = 1; co(r4,cw(3,r4))+=1; delta(r4,cw(3,r4)) = -1; ASSUME(creturn[3] >= cw(3,r4)); // %cmp = icmp eq i32 %conv, 1, !dbg !60 // %conv1 = zext i1 %cmp to i32, !dbg !60 // call void @llvm.dbg.value(metadata i32 %conv1, metadata !100, metadata !DIExpression()), !dbg !105 // call void @llvm.dbg.value(metadata i64* @atom_2_X0_1, metadata !101, metadata !DIExpression()), !dbg !115 // %1 = zext i32 %conv1 to i64 // call void @llvm.dbg.value(metadata i64 %1, metadata !103, metadata !DIExpression()), !dbg !115 // store atomic i64 %1, i64* @atom_2_X0_1 seq_cst, align 8, !dbg !62 // ST: Guess iw(3,4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW old_cw = cw(3,4); cw(3,4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM // Check ASSUME(active[iw(3,4)] == 3); ASSUME(active[cw(3,4)] == 3); ASSUME(sforbid(4,cw(3,4))== 0); ASSUME(iw(3,4) >= max(creg_r1,0)); ASSUME(iw(3,4) >= 0); ASSUME(cw(3,4) >= iw(3,4)); ASSUME(cw(3,4) >= old_cw); ASSUME(cw(3,4) >= cr(3,4)); ASSUME(cw(3,4) >= cl[3]); ASSUME(cw(3,4) >= cisb[3]); ASSUME(cw(3,4) >= cdy[3]); ASSUME(cw(3,4) >= cdl[3]); ASSUME(cw(3,4) >= cds[3]); ASSUME(cw(3,4) >= cctrl[3]); ASSUME(cw(3,4) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,4) = (r1==1); mem(4,cw(3,4)) = (r1==1); co(4,cw(3,4))+=1; delta(4,cw(3,4)) = -1; ASSUME(creturn[3] >= cw(3,4)); // ret i8* null, !dbg !63 ret_thread_3 = (- 1); // Dumping thread 0 int ret_thread_0 = 0; cdy[0] = get_rng(0,NCONTEXT-1); ASSUME(cdy[0] >= cstart[0]); T0BLOCK0: // %thr0 = alloca i64, align 8 // %thr1 = alloca i64, align 8 // %thr2 = alloca i64, align 8 // call void @llvm.dbg.value(metadata i32 %argc, metadata !125, metadata !DIExpression()), !dbg !163 // call void @llvm.dbg.value(metadata i8** %argv, metadata !126, metadata !DIExpression()), !dbg !163 // %0 = bitcast i64* %thr0 to i8*, !dbg !79 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !79 // call void @llvm.dbg.declare(metadata i64* %thr0, metadata !127, metadata !DIExpression()), !dbg !165 // %1 = bitcast i64* %thr1 to i8*, !dbg !81 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !81 // call void @llvm.dbg.declare(metadata i64* %thr1, metadata !131, metadata !DIExpression()), !dbg !167 // %2 = bitcast i64* %thr2 to i8*, !dbg !83 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !83 // call void @llvm.dbg.declare(metadata i64* %thr2, metadata !132, metadata !DIExpression()), !dbg !169 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !133, metadata !DIExpression()), !dbg !170 // call void @llvm.dbg.value(metadata i64 0, metadata !135, metadata !DIExpression()), !dbg !170 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !86 // ST: Guess iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0+2*1); cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0+2*1)] == 0); ASSUME(active[cw(0,0+2*1)] == 0); ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(cw(0,0+2*1) >= iw(0,0+2*1)); ASSUME(cw(0,0+2*1) >= old_cw); ASSUME(cw(0,0+2*1) >= cr(0,0+2*1)); ASSUME(cw(0,0+2*1) >= cl[0]); ASSUME(cw(0,0+2*1) >= cisb[0]); ASSUME(cw(0,0+2*1) >= cdy[0]); ASSUME(cw(0,0+2*1) >= cdl[0]); ASSUME(cw(0,0+2*1) >= cds[0]); ASSUME(cw(0,0+2*1) >= cctrl[0]); ASSUME(cw(0,0+2*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+2*1) = 0; mem(0+2*1,cw(0,0+2*1)) = 0; co(0+2*1,cw(0,0+2*1))+=1; delta(0+2*1,cw(0,0+2*1)) = -1; ASSUME(creturn[0] >= cw(0,0+2*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !136, metadata !DIExpression()), !dbg !172 // call void @llvm.dbg.value(metadata i64 0, metadata !138, metadata !DIExpression()), !dbg !172 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !88 // ST: Guess iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0+1*1); cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0+1*1)] == 0); ASSUME(active[cw(0,0+1*1)] == 0); ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(cw(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cw(0,0+1*1) >= old_cw); ASSUME(cw(0,0+1*1) >= cr(0,0+1*1)); ASSUME(cw(0,0+1*1) >= cl[0]); ASSUME(cw(0,0+1*1) >= cisb[0]); ASSUME(cw(0,0+1*1) >= cdy[0]); ASSUME(cw(0,0+1*1) >= cdl[0]); ASSUME(cw(0,0+1*1) >= cds[0]); ASSUME(cw(0,0+1*1) >= cctrl[0]); ASSUME(cw(0,0+1*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+1*1) = 0; mem(0+1*1,cw(0,0+1*1)) = 0; co(0+1*1,cw(0,0+1*1))+=1; delta(0+1*1,cw(0,0+1*1)) = -1; ASSUME(creturn[0] >= cw(0,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !139, metadata !DIExpression()), !dbg !174 // call void @llvm.dbg.value(metadata i64 0, metadata !141, metadata !DIExpression()), !dbg !174 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !90 // ST: Guess iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0); cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0)] == 0); ASSUME(active[cw(0,0)] == 0); ASSUME(sforbid(0,cw(0,0))== 0); ASSUME(iw(0,0) >= 0); ASSUME(iw(0,0) >= 0); ASSUME(cw(0,0) >= iw(0,0)); ASSUME(cw(0,0) >= old_cw); ASSUME(cw(0,0) >= cr(0,0)); ASSUME(cw(0,0) >= cl[0]); ASSUME(cw(0,0) >= cisb[0]); ASSUME(cw(0,0) >= cdy[0]); ASSUME(cw(0,0) >= cdl[0]); ASSUME(cw(0,0) >= cds[0]); ASSUME(cw(0,0) >= cctrl[0]); ASSUME(cw(0,0) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0) = 0; mem(0,cw(0,0)) = 0; co(0,cw(0,0))+=1; delta(0,cw(0,0)) = -1; ASSUME(creturn[0] >= cw(0,0)); // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !142, metadata !DIExpression()), !dbg !176 // call void @llvm.dbg.value(metadata i64 0, metadata !144, metadata !DIExpression()), !dbg !176 // store atomic i64 0, i64* @atom_1_X0_1 monotonic, align 8, !dbg !92 // ST: Guess iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,3); cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,3)] == 0); ASSUME(active[cw(0,3)] == 0); ASSUME(sforbid(3,cw(0,3))== 0); ASSUME(iw(0,3) >= 0); ASSUME(iw(0,3) >= 0); ASSUME(cw(0,3) >= iw(0,3)); ASSUME(cw(0,3) >= old_cw); ASSUME(cw(0,3) >= cr(0,3)); ASSUME(cw(0,3) >= cl[0]); ASSUME(cw(0,3) >= cisb[0]); ASSUME(cw(0,3) >= cdy[0]); ASSUME(cw(0,3) >= cdl[0]); ASSUME(cw(0,3) >= cds[0]); ASSUME(cw(0,3) >= cctrl[0]); ASSUME(cw(0,3) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,3) = 0; mem(3,cw(0,3)) = 0; co(3,cw(0,3))+=1; delta(3,cw(0,3)) = -1; ASSUME(creturn[0] >= cw(0,3)); // call void @llvm.dbg.value(metadata i64* @atom_2_X0_1, metadata !145, metadata !DIExpression()), !dbg !178 // call void @llvm.dbg.value(metadata i64 0, metadata !147, metadata !DIExpression()), !dbg !178 // store atomic i64 0, i64* @atom_2_X0_1 monotonic, align 8, !dbg !94 // ST: Guess iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,4); cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,4)] == 0); ASSUME(active[cw(0,4)] == 0); ASSUME(sforbid(4,cw(0,4))== 0); ASSUME(iw(0,4) >= 0); ASSUME(iw(0,4) >= 0); ASSUME(cw(0,4) >= iw(0,4)); ASSUME(cw(0,4) >= old_cw); ASSUME(cw(0,4) >= cr(0,4)); ASSUME(cw(0,4) >= cl[0]); ASSUME(cw(0,4) >= cisb[0]); ASSUME(cw(0,4) >= cdy[0]); ASSUME(cw(0,4) >= cdl[0]); ASSUME(cw(0,4) >= cds[0]); ASSUME(cw(0,4) >= cctrl[0]); ASSUME(cw(0,4) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,4) = 0; mem(4,cw(0,4)) = 0; co(4,cw(0,4))+=1; delta(4,cw(0,4)) = -1; ASSUME(creturn[0] >= cw(0,4)); // %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !95 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[1] >= cdy[0]); // %call9 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !96 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[2] >= cdy[0]); // %call10 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !97 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[3] >= cdy[0]); // %3 = load i64, i64* %thr0, align 8, !dbg !98, !tbaa !99 // LD: Guess old_cr = cr(0,5); cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,5)] == 0); ASSUME(cr(0,5) >= iw(0,5)); ASSUME(cr(0,5) >= 0); ASSUME(cr(0,5) >= cdy[0]); ASSUME(cr(0,5) >= cisb[0]); ASSUME(cr(0,5) >= cdl[0]); ASSUME(cr(0,5) >= cl[0]); // Update creg_r6 = cr(0,5); crmax(0,5) = max(crmax(0,5),cr(0,5)); caddr[0] = max(caddr[0],0); if(cr(0,5) < cw(0,5)) { r6 = buff(0,5); } else { if(pw(0,5) != co(5,cr(0,5))) { ASSUME(cr(0,5) >= old_cr); } pw(0,5) = co(5,cr(0,5)); r6 = mem(5,cr(0,5)); } ASSUME(creturn[0] >= cr(0,5)); // %call11 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !103 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[1]); // %4 = load i64, i64* %thr1, align 8, !dbg !104, !tbaa !99 // LD: Guess old_cr = cr(0,6); cr(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,6)] == 0); ASSUME(cr(0,6) >= iw(0,6)); ASSUME(cr(0,6) >= 0); ASSUME(cr(0,6) >= cdy[0]); ASSUME(cr(0,6) >= cisb[0]); ASSUME(cr(0,6) >= cdl[0]); ASSUME(cr(0,6) >= cl[0]); // Update creg_r7 = cr(0,6); crmax(0,6) = max(crmax(0,6),cr(0,6)); caddr[0] = max(caddr[0],0); if(cr(0,6) < cw(0,6)) { r7 = buff(0,6); } else { if(pw(0,6) != co(6,cr(0,6))) { ASSUME(cr(0,6) >= old_cr); } pw(0,6) = co(6,cr(0,6)); r7 = mem(6,cr(0,6)); } ASSUME(creturn[0] >= cr(0,6)); // %call12 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !105 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[2]); // %5 = load i64, i64* %thr2, align 8, !dbg !106, !tbaa !99 // LD: Guess old_cr = cr(0,7); cr(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,7)] == 0); ASSUME(cr(0,7) >= iw(0,7)); ASSUME(cr(0,7) >= 0); ASSUME(cr(0,7) >= cdy[0]); ASSUME(cr(0,7) >= cisb[0]); ASSUME(cr(0,7) >= cdl[0]); ASSUME(cr(0,7) >= cl[0]); // Update creg_r8 = cr(0,7); crmax(0,7) = max(crmax(0,7),cr(0,7)); caddr[0] = max(caddr[0],0); if(cr(0,7) < cw(0,7)) { r8 = buff(0,7); } else { if(pw(0,7) != co(7,cr(0,7))) { ASSUME(cr(0,7) >= old_cr); } pw(0,7) = co(7,cr(0,7)); r8 = mem(7,cr(0,7)); } ASSUME(creturn[0] >= cr(0,7)); // %call13 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !107 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[3]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !149, metadata !DIExpression()), !dbg !193 // %6 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) seq_cst, align 8, !dbg !109 // LD: Guess old_cr = cr(0,0); cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,0)] == 0); ASSUME(cr(0,0) >= iw(0,0)); ASSUME(cr(0,0) >= 0); ASSUME(cr(0,0) >= cdy[0]); ASSUME(cr(0,0) >= cisb[0]); ASSUME(cr(0,0) >= cdl[0]); ASSUME(cr(0,0) >= cl[0]); // Update creg_r9 = cr(0,0); crmax(0,0) = max(crmax(0,0),cr(0,0)); caddr[0] = max(caddr[0],0); if(cr(0,0) < cw(0,0)) { r9 = buff(0,0); } else { if(pw(0,0) != co(0,cr(0,0))) { ASSUME(cr(0,0) >= old_cr); } pw(0,0) = co(0,cr(0,0)); r9 = mem(0,cr(0,0)); } ASSUME(creturn[0] >= cr(0,0)); // call void @llvm.dbg.value(metadata i64 %6, metadata !151, metadata !DIExpression()), !dbg !193 // %conv = trunc i64 %6 to i32, !dbg !110 // call void @llvm.dbg.value(metadata i32 %conv, metadata !148, metadata !DIExpression()), !dbg !163 // %cmp = icmp eq i32 %conv, 2, !dbg !111 // %conv14 = zext i1 %cmp to i32, !dbg !111 // call void @llvm.dbg.value(metadata i32 %conv14, metadata !152, metadata !DIExpression()), !dbg !163 // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !154, metadata !DIExpression()), !dbg !197 // %7 = load atomic i64, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !113 // LD: Guess old_cr = cr(0,3); cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,3)] == 0); ASSUME(cr(0,3) >= iw(0,3)); ASSUME(cr(0,3) >= 0); ASSUME(cr(0,3) >= cdy[0]); ASSUME(cr(0,3) >= cisb[0]); ASSUME(cr(0,3) >= cdl[0]); ASSUME(cr(0,3) >= cl[0]); // Update creg_r10 = cr(0,3); crmax(0,3) = max(crmax(0,3),cr(0,3)); caddr[0] = max(caddr[0],0); if(cr(0,3) < cw(0,3)) { r10 = buff(0,3); } else { if(pw(0,3) != co(3,cr(0,3))) { ASSUME(cr(0,3) >= old_cr); } pw(0,3) = co(3,cr(0,3)); r10 = mem(3,cr(0,3)); } ASSUME(creturn[0] >= cr(0,3)); // call void @llvm.dbg.value(metadata i64 %7, metadata !156, metadata !DIExpression()), !dbg !197 // %conv18 = trunc i64 %7 to i32, !dbg !114 // call void @llvm.dbg.value(metadata i32 %conv18, metadata !153, metadata !DIExpression()), !dbg !163 // call void @llvm.dbg.value(metadata i64* @atom_2_X0_1, metadata !158, metadata !DIExpression()), !dbg !200 // %8 = load atomic i64, i64* @atom_2_X0_1 seq_cst, align 8, !dbg !116 // LD: Guess old_cr = cr(0,4); cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,4)] == 0); ASSUME(cr(0,4) >= iw(0,4)); ASSUME(cr(0,4) >= 0); ASSUME(cr(0,4) >= cdy[0]); ASSUME(cr(0,4) >= cisb[0]); ASSUME(cr(0,4) >= cdl[0]); ASSUME(cr(0,4) >= cl[0]); // Update creg_r11 = cr(0,4); crmax(0,4) = max(crmax(0,4),cr(0,4)); caddr[0] = max(caddr[0],0); if(cr(0,4) < cw(0,4)) { r11 = buff(0,4); } else { if(pw(0,4) != co(4,cr(0,4))) { ASSUME(cr(0,4) >= old_cr); } pw(0,4) = co(4,cr(0,4)); r11 = mem(4,cr(0,4)); } ASSUME(creturn[0] >= cr(0,4)); // call void @llvm.dbg.value(metadata i64 %8, metadata !160, metadata !DIExpression()), !dbg !200 // %conv22 = trunc i64 %8 to i32, !dbg !117 // call void @llvm.dbg.value(metadata i32 %conv22, metadata !157, metadata !DIExpression()), !dbg !163 // %and = and i32 %conv18, %conv22, !dbg !118 creg_r12 = max(creg_r10,creg_r11); ASSUME(active[creg_r12] == 0); r12 = r10 & r11; // call void @llvm.dbg.value(metadata i32 %and, metadata !161, metadata !DIExpression()), !dbg !163 // %and23 = and i32 %conv14, %and, !dbg !119 creg_r13 = max(max(creg_r9,0),creg_r12); ASSUME(active[creg_r13] == 0); r13 = (r9==2) & r12; // call void @llvm.dbg.value(metadata i32 %and23, metadata !162, metadata !DIExpression()), !dbg !163 // %cmp24 = icmp eq i32 %and23, 1, !dbg !120 // br i1 %cmp24, label %if.then, label %if.end, !dbg !122 old_cctrl = cctrl[0]; cctrl[0] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[0] >= old_cctrl); ASSUME(cctrl[0] >= creg_r13); ASSUME(cctrl[0] >= 0); if((r13==1)) { goto T0BLOCK1; } else { goto T0BLOCK2; } T0BLOCK1: // call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([109 x i8], [109 x i8]* @.str.1, i64 0, i64 0), i32 noundef 73, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !123 // unreachable, !dbg !123 r14 = 1; T0BLOCK2: // %9 = bitcast i64* %thr2 to i8*, !dbg !126 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %9) #7, !dbg !126 // %10 = bitcast i64* %thr1 to i8*, !dbg !126 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !126 // %11 = bitcast i64* %thr0 to i8*, !dbg !126 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !126 // ret i32 0, !dbg !127 ret_thread_0 = 0; ASSERT(r14== 0); }
[ "tuan-phong.ngo@it.uu.se" ]
tuan-phong.ngo@it.uu.se
7488240056099a3660f0cd26abfb030500844414
4c23be1a0ca76f68e7146f7d098e26c2bbfb2650
/ic8h18/0.0025/TC3H6OCHO
934e3a956d91b4aad710d0a6bbd4ce2a23e4bd97
[]
no_license
labsandy/OpenFOAM_workspace
a74b473903ddbd34b31dc93917e3719bc051e379
6e0193ad9dabd613acf40d6b3ec4c0536c90aed4
refs/heads/master
2022-02-25T02:36:04.164324
2019-08-23T02:27:16
2019-08-23T02:27:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
842
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.0025"; object TC3H6OCHO; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 0 0 0 0]; internalField uniform 5.73636e-12; boundaryField { boundary { type empty; } } // ************************************************************************* //
[ "jfeatherstone123@gmail.com" ]
jfeatherstone123@gmail.com
49dbe701a8bb4be0c877aa478181c4f9e4456649
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_1480487_1/C++/RosyIsh/A1.cpp
c3c9789bf8d07a4632b9fcb65d8af734070b4314
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,108
cpp
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<vector> #include<map> #include<set> #include<queue> #include<algorithm> #define SI(x) scanf("%d ",&x) #define SL(x) scanf("%lld",&x) typedef long long LL; using namespace std; int S[500]; int K[500]; double p[500]; double x = 0.0; double eps = 1.0e-9; int main() { freopen("A-large.in","r",stdin); freopen("A-large-output.txt","w",stdout); int T,tnum=1; SI(T); while(T-- >0) { int n; x = 0.0; SI(n); for(int i=0;i<n;i++) { SI(S[i]); x+=S[i];} printf("Case #%d: ",tnum); double INF = 1000.0; for(int i=0;i<n;i++) { double lo = 0, hi = 1.0; for(int it=1;it<=1000;it++) { double mid = (lo+hi)/2.0; double needed = 0.0; for(int j=0;j<n;j++) { if(j==i) continue; double k = ((S[i]-S[j])*1.0/x + mid); if(k<0.0) needed+=0; else needed+=k; } double what = 1.0-mid; if(needed<=what || (needed>what && needed-what<=eps)) lo = mid; else hi = mid; } printf("%.10lf ",lo*100); } printf("\n"); tnum++; } fclose(stdout); return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
537463592fd471642c79ccaa742961b34854f191
73a8f3c9c640af08acbefe657bff62e3d1751fc2
/Dependencies/Qt-5.4.1/include/QtLocation/5.4.1/QtLocation/private/qgeocodereply_p.h
b75379e39fc9fd00903c9060e46a9a9332be6472
[]
no_license
knight666/pitstop
8d5ad076a71055803df1601e1df1640430ad56ca
4e541d90507f38f36274e50b0d702a284d648e27
refs/heads/master
2020-07-10T00:51:28.141786
2019-08-24T20:08:02
2019-08-24T20:08:02
204,123,196
0
0
null
null
null
null
UTF-8
C++
false
false
2,516
h
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtLocation module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and 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 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** 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. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QGEOCODEREPLY_P_H #define QGEOCODEREPLY_P_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. // #include "qgeocodereply.h" #include "qgeoshape.h" #include <QList> QT_BEGIN_NAMESPACE class QGeoLocation; class QGeoCodeReplyPrivate { public: QGeoCodeReplyPrivate(); QGeoCodeReplyPrivate(QGeoCodeReply::Error error, const QString &errorString); ~QGeoCodeReplyPrivate(); QGeoCodeReply::Error error; QString errorString; bool isFinished; QGeoShape viewport; QList<QGeoLocation> locations; int limit; int offset; private: Q_DISABLE_COPY(QGeoCodeReplyPrivate) }; QT_END_NAMESPACE #endif
[ "knight666+github@gmail.com" ]
knight666+github@gmail.com
6059adb59011f809a1241d481aa3b19d885a77bd
3e21b0cc1b0c0089cb7259c8ae77c64ffccf8ade
/max-subarray-sum.cpp
82083f494f0a2e32fa3ab824a9841746e5eec396
[]
no_license
mehrankamal/competitive-100
ee6c0946cc0c1f290e8a8dd989913d05859a8794
4b46d6c5940c2ba3942ba3164bebc52574f46649
refs/heads/main
2023-07-31T11:19:40.608156
2021-09-09T20:48:32
2021-09-09T20:48:32
396,076,441
1
0
null
null
null
null
UTF-8
C++
false
false
1,058
cpp
/* * author: mkbaloch * datetime: 2021-08-18 05:37:37 */ #include<bits/stdc++.h> #define all(x) x.begin(), x.end() #define deb(x) cerr << "[" << #x << ": " << x << "]" << endl; using namespace std; typedef long long ll; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); #ifdef LOCAL auto start = chrono::high_resolution_clock::now(); freopen("inputf.txt", "r", stdin); freopen("outputf.txt", "w", stdout); #endif //-------Start-------// int n; cin >> n; ll max_sum=INT_MIN, current_sum=INT_MIN; for(int i=0; i<n; i++){ ll num; cin >> num; current_sum = max(num, current_sum + num); max_sum = max(max_sum, current_sum); } cout << max_sum; //-------End---------// #ifdef LOCAL auto end = chrono::high_resolution_clock::now(); auto dur = chrono::duration_cast<chrono::microseconds>(end - start); fprintf(stderr, "Execution time: %.6Lf seconds.\n", ((long double)dur.count() / 1e6)); #endif return 0; }
[ "mehran_kamal@outlook.com" ]
mehran_kamal@outlook.com
63718c4fbf4b0eb0eaa7ed54352d5fa588033647
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/skia/src/gpu/ganesh/GrDrawingManager.cpp
13e3fd1ab6956b01a143f417ae009d5110394cd5
[ "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
41,923
cpp
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/gpu/ganesh/GrDrawingManager.h" #include <algorithm> #include <memory> #include "include/core/SkDeferredDisplayList.h" #include "include/gpu/GrBackendSemaphore.h" #include "include/gpu/GrDirectContext.h" #include "include/gpu/GrRecordingContext.h" #include "src/base/SkTInternalLList.h" #include "src/core/SkDeferredDisplayListPriv.h" #include "src/gpu/ganesh/GrBufferTransferRenderTask.h" #include "src/gpu/ganesh/GrBufferUpdateRenderTask.h" #include "src/gpu/ganesh/GrClientMappedBufferManager.h" #include "src/gpu/ganesh/GrCopyRenderTask.h" #include "src/gpu/ganesh/GrDDLTask.h" #include "src/gpu/ganesh/GrDirectContextPriv.h" #include "src/gpu/ganesh/GrGpu.h" #include "src/gpu/ganesh/GrMemoryPool.h" #include "src/gpu/ganesh/GrNativeRect.h" #include "src/gpu/ganesh/GrOnFlushResourceProvider.h" #include "src/gpu/ganesh/GrOpFlushState.h" #include "src/gpu/ganesh/GrRecordingContextPriv.h" #include "src/gpu/ganesh/GrRenderTargetProxy.h" #include "src/gpu/ganesh/GrRenderTask.h" #include "src/gpu/ganesh/GrRenderTaskCluster.h" #include "src/gpu/ganesh/GrResourceAllocator.h" #include "src/gpu/ganesh/GrResourceProvider.h" #include "src/gpu/ganesh/GrSurfaceProxyPriv.h" #include "src/gpu/ganesh/GrTTopoSort.h" #include "src/gpu/ganesh/GrTexture.h" #include "src/gpu/ganesh/GrTextureProxy.h" #include "src/gpu/ganesh/GrTextureProxyPriv.h" #include "src/gpu/ganesh/GrTextureResolveRenderTask.h" #include "src/gpu/ganesh/GrTracing.h" #include "src/gpu/ganesh/GrTransferFromRenderTask.h" #include "src/gpu/ganesh/GrWaitRenderTask.h" #include "src/gpu/ganesh/GrWritePixelsRenderTask.h" #include "src/gpu/ganesh/ops/OpsTask.h" #include "src/gpu/ganesh/ops/SoftwarePathRenderer.h" #include "src/gpu/ganesh/surface/SkSurface_Ganesh.h" #include "src/text/gpu/SDFTControl.h" using namespace skia_private; /////////////////////////////////////////////////////////////////////////////////////////////////// GrDrawingManager::GrDrawingManager(GrRecordingContext* rContext, const PathRendererChain::Options& optionsForPathRendererChain, bool reduceOpsTaskSplitting) : fContext(rContext) , fOptionsForPathRendererChain(optionsForPathRendererChain) , fPathRendererChain(nullptr) , fSoftwarePathRenderer(nullptr) , fReduceOpsTaskSplitting(reduceOpsTaskSplitting) { } GrDrawingManager::~GrDrawingManager() { this->closeAllTasks(); this->removeRenderTasks(); } bool GrDrawingManager::wasAbandoned() const { return fContext->abandoned(); } void GrDrawingManager::freeGpuResources() { for (int i = fOnFlushCBObjects.size() - 1; i >= 0; --i) { if (!fOnFlushCBObjects[i]->retainOnFreeGpuResources()) { // it's safe to just do this because we're iterating in reverse fOnFlushCBObjects.removeShuffle(i); } } // a path renderer may be holding onto resources fPathRendererChain = nullptr; fSoftwarePathRenderer = nullptr; } // MDB TODO: make use of the 'proxies' parameter. bool GrDrawingManager::flush( SkSpan<GrSurfaceProxy*> proxies, SkSurface::BackendSurfaceAccess access, const GrFlushInfo& info, const skgpu::MutableTextureState* newState) { GR_CREATE_TRACE_MARKER_CONTEXT("GrDrawingManager", "flush", fContext); if (fFlushing || this->wasAbandoned()) { if (info.fSubmittedProc) { info.fSubmittedProc(info.fSubmittedContext, false); } if (info.fFinishedProc) { info.fFinishedProc(info.fFinishedContext); } return false; } SkDEBUGCODE(this->validate()); // As of now we only short-circuit if we got an explicit list of surfaces to flush. if (!proxies.empty() && !info.fNumSemaphores && !info.fFinishedProc && access == SkSurface::BackendSurfaceAccess::kNoAccess && !newState) { bool allUnused = std::all_of(proxies.begin(), proxies.end(), [&](GrSurfaceProxy* proxy) { bool used = std::any_of(fDAG.begin(), fDAG.end(), [&](auto& task) { return task && task->isUsed(proxy); }); return !used; }); if (allUnused) { if (info.fSubmittedProc) { info.fSubmittedProc(info.fSubmittedContext, true); } return false; } } auto dContext = fContext->asDirectContext(); SkASSERT(dContext); dContext->priv().clientMappedBufferManager()->process(); GrGpu* gpu = dContext->priv().getGpu(); // We have a non abandoned and direct GrContext. It must have a GrGpu. SkASSERT(gpu); fFlushing = true; auto resourceProvider = dContext->priv().resourceProvider(); auto resourceCache = dContext->priv().getResourceCache(); // Semi-usually the GrRenderTasks are already closed at this point, but sometimes Ganesh needs // to flush mid-draw. In that case, the SkGpuDevice's opsTasks won't be closed but need to be // flushed anyway. Closing such opsTasks here will mean new ones will be created to replace them // if the SkGpuDevice(s) write to them again. this->closeAllTasks(); fActiveOpsTask = nullptr; this->sortTasks(); if (!fCpuBufferCache) { // We cache more buffers when the backend is using client side arrays. Otherwise, we // expect each pool will use a CPU buffer as a staging buffer before uploading to a GPU // buffer object. Each pool only requires one staging buffer at a time. int maxCachedBuffers = fContext->priv().caps()->preferClientSideDynamicBuffers() ? 2 : 6; fCpuBufferCache = GrBufferAllocPool::CpuBufferCache::Make(maxCachedBuffers); } GrOpFlushState flushState(gpu, resourceProvider, &fTokenTracker, fCpuBufferCache); GrOnFlushResourceProvider onFlushProvider(this); // Prepare any onFlush op lists (e.g. atlases). bool preFlushSuccessful = true; for (GrOnFlushCallbackObject* onFlushCBObject : fOnFlushCBObjects) { preFlushSuccessful &= onFlushCBObject->preFlush(&onFlushProvider); } bool cachePurgeNeeded = false; if (preFlushSuccessful) { bool usingReorderedDAG = false; GrResourceAllocator resourceAllocator(dContext); if (fReduceOpsTaskSplitting) { usingReorderedDAG = this->reorderTasks(&resourceAllocator); if (!usingReorderedDAG) { resourceAllocator.reset(); } } #if 0 // Enable this to print out verbose GrOp information SkDEBUGCODE(SkDebugf("RenderTasks (%d):\n", fDAG.count())); for (const auto& task : fDAG) { SkDEBUGCODE(task->dump(/* printDependencies */ true);) } #endif if (!resourceAllocator.failedInstantiation()) { if (!usingReorderedDAG) { for (const auto& task : fDAG) { SkASSERT(task); task->gatherProxyIntervals(&resourceAllocator); } resourceAllocator.planAssignment(); } resourceAllocator.assign(); } cachePurgeNeeded = !resourceAllocator.failedInstantiation() && this->executeRenderTasks(&flushState); } this->removeRenderTasks(); gpu->executeFlushInfo(proxies, access, info, newState); // Give the cache a chance to purge resources that become purgeable due to flushing. if (cachePurgeNeeded) { resourceCache->purgeAsNeeded(); cachePurgeNeeded = false; } for (GrOnFlushCallbackObject* onFlushCBObject : fOnFlushCBObjects) { onFlushCBObject->postFlush(fTokenTracker.nextFlushToken()); cachePurgeNeeded = true; } if (cachePurgeNeeded) { resourceCache->purgeAsNeeded(); } fFlushing = false; return true; } bool GrDrawingManager::submitToGpu(bool syncToCpu) { if (fFlushing || this->wasAbandoned()) { return false; } auto direct = fContext->asDirectContext(); if (!direct) { return false; // Can't submit while DDL recording } GrGpu* gpu = direct->priv().getGpu(); return gpu->submitToGpu(syncToCpu); } bool GrDrawingManager::executeRenderTasks(GrOpFlushState* flushState) { #if GR_FLUSH_TIME_OP_SPEW SkDebugf("Flushing %d opsTasks\n", fDAG.size()); for (int i = 0; i < fDAG.size(); ++i) { if (fDAG[i]) { SkString label; label.printf("task %d/%d", i, fDAG.size()); fDAG[i]->dump(label, {}, true, true); } } #endif bool anyRenderTasksExecuted = false; for (const auto& renderTask : fDAG) { if (!renderTask || !renderTask->isInstantiated()) { continue; } SkASSERT(renderTask->deferredProxiesAreInstantiated()); renderTask->prepare(flushState); } // Upload all data to the GPU flushState->preExecuteDraws(); // For Vulkan, if we have too many oplists to be flushed we end up allocating a lot of resources // for each command buffer associated with the oplists. If this gets too large we can cause the // devices to go OOM. In practice we usually only hit this case in our tests, but to be safe we // put a cap on the number of oplists we will execute before flushing to the GPU to relieve some // memory pressure. static constexpr int kMaxRenderTasksBeforeFlush = 100; int numRenderTasksExecuted = 0; // Execute the normal op lists. for (const auto& renderTask : fDAG) { SkASSERT(renderTask); if (!renderTask->isInstantiated()) { continue; } if (renderTask->execute(flushState)) { anyRenderTasksExecuted = true; } if (++numRenderTasksExecuted >= kMaxRenderTasksBeforeFlush) { flushState->gpu()->submitToGpu(false); numRenderTasksExecuted = 0; } } SkASSERT(!flushState->opsRenderPass()); SkASSERT(fTokenTracker.nextDrawToken() == fTokenTracker.nextFlushToken()); // We reset the flush state before the RenderTasks so that the last resources to be freed are // those that are written to in the RenderTasks. This helps to make sure the most recently used // resources are the last to be purged by the resource cache. flushState->reset(); return anyRenderTasksExecuted; } void GrDrawingManager::removeRenderTasks() { for (const auto& task : fDAG) { SkASSERT(task); if (!task->unique() || task->requiresExplicitCleanup()) { // TODO: Eventually uniqueness should be guaranteed: http://skbug.com/7111. // DDLs, however, will always require an explicit notification for when they // can clean up resources. task->endFlush(this); } task->disown(this); } fDAG.clear(); fReorderBlockerTaskIndices.clear(); fLastRenderTasks.reset(); } void GrDrawingManager::sortTasks() { // We separately sort the ranges around non-reorderable tasks. for (size_t i = 0, start = 0, end; start < SkToSizeT(fDAG.size()); ++i, start = end + 1) { end = i == fReorderBlockerTaskIndices.size() ? fDAG.size() : fReorderBlockerTaskIndices[i]; SkSpan span(fDAG.begin() + start, end - start); SkASSERT(std::none_of(span.begin(), span.end(), [](const auto& t) { return t->blocksReordering(); })); SkASSERT(span.end() == fDAG.end() || fDAG[end]->blocksReordering()); #if defined(SK_GANESH) && defined(SK_DEBUG) // In order to partition the dag array like this it must be the case that each partition // only depends on nodes in the partition or earlier partitions. auto check = [&](const GrRenderTask* task, auto&& check) -> void { SkASSERT(GrRenderTask::TopoSortTraits::WasOutput(task) || std::find_if(span.begin(), span.end(), [task](const auto& n) { return n.get() == task; })); for (int i = 0; i < task->fDependencies.size(); ++i) { check(task->fDependencies[i], check); } }; for (const auto& node : span) { check(node.get(), check); } #endif bool sorted = GrTTopoSort<GrRenderTask, GrRenderTask::TopoSortTraits>(span, start); if (!sorted) { SkDEBUGFAIL("Render task topo sort failed."); } #ifdef SK_DEBUG if (sorted && !span.empty()) { // This block checks for any unnecessary splits in the opsTasks. If two sequential // opsTasks could have merged it means the opsTask was artificially split. auto prevOpsTask = span[0]->asOpsTask(); for (size_t j = 1; j < span.size(); ++j) { auto curOpsTask = span[j]->asOpsTask(); if (prevOpsTask && curOpsTask) { SkASSERT(!prevOpsTask->canMerge(curOpsTask)); } prevOpsTask = curOpsTask; } } #endif } } // Reorder the array to match the llist without reffing & unreffing sk_sp's. // Both args must contain the same objects. // This is basically a shim because clustering uses LList but the rest of drawmgr uses array. template <typename T> static void reorder_array_by_llist(const SkTInternalLList<T>& llist, TArray<sk_sp<T>>* array) { int i = 0; for (T* t : llist) { // Release the pointer that used to live here so it doesn't get unreffed. [[maybe_unused]] T* old = array->at(i).release(); array->at(i++).reset(t); } SkASSERT(i == array->size()); } bool GrDrawingManager::reorderTasks(GrResourceAllocator* resourceAllocator) { SkASSERT(fReduceOpsTaskSplitting); // We separately sort the ranges around non-reorderable tasks. bool clustered = false; SkTInternalLList<GrRenderTask> llist; for (size_t i = 0, start = 0, end; start < SkToSizeT(fDAG.size()); ++i, start = end + 1) { end = i == fReorderBlockerTaskIndices.size() ? fDAG.size() : fReorderBlockerTaskIndices[i]; SkSpan span(fDAG.begin() + start, end - start); SkASSERT(std::none_of(span.begin(), span.end(), [](const auto& t) { return t->blocksReordering(); })); SkTInternalLList<GrRenderTask> subllist; if (GrClusterRenderTasks(span, &subllist)) { clustered = true; } if (i < fReorderBlockerTaskIndices.size()) { SkASSERT(fDAG[fReorderBlockerTaskIndices[i]]->blocksReordering()); subllist.addToTail(fDAG[fReorderBlockerTaskIndices[i]].get()); } llist.concat(std::move(subllist)); } if (!clustered) { return false; } for (GrRenderTask* task : llist) { task->gatherProxyIntervals(resourceAllocator); } if (!resourceAllocator->planAssignment()) { return false; } if (!resourceAllocator->makeBudgetHeadroom()) { auto dContext = fContext->asDirectContext(); SkASSERT(dContext); dContext->priv().getGpu()->stats()->incNumReorderedDAGsOverBudget(); return false; } reorder_array_by_llist(llist, &fDAG); int newCount = 0; for (int i = 0; i < fDAG.size(); i++) { sk_sp<GrRenderTask>& task = fDAG[i]; if (auto opsTask = task->asOpsTask()) { size_t remaining = fDAG.size() - i - 1; SkSpan<sk_sp<GrRenderTask>> nextTasks{fDAG.end() - remaining, remaining}; int removeCount = opsTask->mergeFrom(nextTasks); for (const auto& removed : nextTasks.first(removeCount)) { removed->disown(this); } i += removeCount; } fDAG[newCount++] = std::move(task); } fDAG.resize_back(newCount); return true; } void GrDrawingManager::closeAllTasks() { for (auto& task : fDAG) { if (task) { task->makeClosed(fContext); } } } GrRenderTask* GrDrawingManager::insertTaskBeforeLast(sk_sp<GrRenderTask> task) { if (!task) { return nullptr; } if (fDAG.empty()) { return fDAG.push_back(std::move(task)).get(); } if (!fReorderBlockerTaskIndices.empty() && fReorderBlockerTaskIndices.back() == fDAG.size()) { fReorderBlockerTaskIndices.back()++; } fDAG.push_back(std::move(task)); auto& penultimate = fDAG.fromBack(1); fDAG.back().swap(penultimate); return penultimate.get(); } GrRenderTask* GrDrawingManager::appendTask(sk_sp<GrRenderTask> task) { if (!task) { return nullptr; } if (task->blocksReordering()) { fReorderBlockerTaskIndices.push_back(fDAG.size()); } return fDAG.push_back(std::move(task)).get(); } static void resolve_and_mipmap(GrGpu* gpu, GrSurfaceProxy* proxy) { if (!proxy->isInstantiated()) { return; } // In the flushSurfaces case, we need to resolve MSAA immediately after flush. This is // because clients expect the flushed surface's backing texture to be fully resolved // upon return. if (proxy->requiresManualMSAAResolve()) { auto* rtProxy = proxy->asRenderTargetProxy(); SkASSERT(rtProxy); if (rtProxy->isMSAADirty()) { SkASSERT(rtProxy->peekRenderTarget()); gpu->resolveRenderTarget(rtProxy->peekRenderTarget(), rtProxy->msaaDirtyRect()); gpu->submitToGpu(false); rtProxy->markMSAAResolved(); } } // If, after a flush, any of the proxies of interest have dirty mipmaps, regenerate them in // case their backend textures are being stolen. // (This special case is exercised by the ReimportImageTextureWithMipLevels test.) // FIXME: It may be more ideal to plumb down a "we're going to steal the backends" flag. if (auto* textureProxy = proxy->asTextureProxy()) { if (textureProxy->mipmapsAreDirty()) { SkASSERT(textureProxy->peekTexture()); gpu->regenerateMipMapLevels(textureProxy->peekTexture()); textureProxy->markMipmapsClean(); } } } GrSemaphoresSubmitted GrDrawingManager::flushSurfaces( SkSpan<GrSurfaceProxy*> proxies, SkSurface::BackendSurfaceAccess access, const GrFlushInfo& info, const skgpu::MutableTextureState* newState) { if (this->wasAbandoned()) { if (info.fSubmittedProc) { info.fSubmittedProc(info.fSubmittedContext, false); } if (info.fFinishedProc) { info.fFinishedProc(info.fFinishedContext); } return GrSemaphoresSubmitted::kNo; } SkDEBUGCODE(this->validate()); auto direct = fContext->asDirectContext(); SkASSERT(direct); GrGpu* gpu = direct->priv().getGpu(); // We have a non abandoned and direct GrContext. It must have a GrGpu. SkASSERT(gpu); // TODO: It is important to upgrade the drawingmanager to just flushing the // portion of the DAG required by 'proxies' in order to restore some of the // semantics of this method. bool didFlush = this->flush(proxies, access, info, newState); for (GrSurfaceProxy* proxy : proxies) { resolve_and_mipmap(gpu, proxy); } SkDEBUGCODE(this->validate()); if (!didFlush || (!direct->priv().caps()->semaphoreSupport() && info.fNumSemaphores)) { return GrSemaphoresSubmitted::kNo; } return GrSemaphoresSubmitted::kYes; } void GrDrawingManager::addOnFlushCallbackObject(GrOnFlushCallbackObject* onFlushCBObject) { fOnFlushCBObjects.push_back(onFlushCBObject); } #if GR_TEST_UTILS void GrDrawingManager::testingOnly_removeOnFlushCallbackObject(GrOnFlushCallbackObject* cb) { int n = std::find(fOnFlushCBObjects.begin(), fOnFlushCBObjects.end(), cb) - fOnFlushCBObjects.begin(); SkASSERT(n < fOnFlushCBObjects.size()); fOnFlushCBObjects.removeShuffle(n); } #endif void GrDrawingManager::setLastRenderTask(const GrSurfaceProxy* proxy, GrRenderTask* task) { #ifdef SK_DEBUG if (auto prior = this->getLastRenderTask(proxy)) { SkASSERT(prior->isClosed() || prior == task); } #endif uint32_t key = proxy->uniqueID().asUInt(); if (task) { fLastRenderTasks.set(key, task); } else if (fLastRenderTasks.find(key)) { fLastRenderTasks.remove(key); } } GrRenderTask* GrDrawingManager::getLastRenderTask(const GrSurfaceProxy* proxy) const { auto entry = fLastRenderTasks.find(proxy->uniqueID().asUInt()); return entry ? *entry : nullptr; } skgpu::ganesh::OpsTask* GrDrawingManager::getLastOpsTask(const GrSurfaceProxy* proxy) const { GrRenderTask* task = this->getLastRenderTask(proxy); return task ? task->asOpsTask() : nullptr; } void GrDrawingManager::moveRenderTasksToDDL(SkDeferredDisplayList* ddl) { SkDEBUGCODE(this->validate()); // no renderTask should receive a new command after this this->closeAllTasks(); fActiveOpsTask = nullptr; this->sortTasks(); fDAG.swap(ddl->fRenderTasks); SkASSERT(fDAG.empty()); fReorderBlockerTaskIndices.clear(); for (auto& renderTask : ddl->fRenderTasks) { renderTask->disown(this); renderTask->prePrepare(fContext); } ddl->fArenas = std::move(fContext->priv().detachArenas()); fContext->priv().detachProgramData(&ddl->fProgramData); SkDEBUGCODE(this->validate()); } void GrDrawingManager::createDDLTask(sk_sp<const SkDeferredDisplayList> ddl, sk_sp<GrRenderTargetProxy> newDest, SkIPoint offset) { SkDEBUGCODE(this->validate()); if (fActiveOpsTask) { // This is a temporary fix for the partial-MDB world. In that world we're not // reordering so ops that (in the single opsTask world) would've just glommed onto the // end of the single opsTask but referred to a far earlier RT need to appear in their // own opsTask. fActiveOpsTask->makeClosed(fContext); fActiveOpsTask = nullptr; } // Propagate the DDL proxy's state information to the replay target. if (ddl->priv().targetProxy()->isMSAADirty()) { auto nativeRect = GrNativeRect::MakeIRectRelativeTo( ddl->characterization().origin(), ddl->priv().targetProxy()->backingStoreDimensions().height(), ddl->priv().targetProxy()->msaaDirtyRect()); newDest->markMSAADirty(nativeRect); } GrTextureProxy* newTextureProxy = newDest->asTextureProxy(); if (newTextureProxy && GrMipmapped::kYes == newTextureProxy->mipmapped()) { newTextureProxy->markMipmapsDirty(); } // Here we jam the proxy that backs the current replay SkSurface into the LazyProxyData. // The lazy proxy that references it (in the DDL opsTasks) will then steal its GrTexture. ddl->fLazyProxyData->fReplayDest = newDest.get(); // Add a task to handle drawing and lifetime management of the DDL. SkDEBUGCODE(auto ddlTask =) this->appendTask(sk_make_sp<GrDDLTask>(this, std::move(newDest), std::move(ddl), offset)); SkASSERT(ddlTask->isClosed()); SkDEBUGCODE(this->validate()); } #ifdef SK_DEBUG void GrDrawingManager::validate() const { if (fActiveOpsTask) { SkASSERT(!fDAG.empty()); SkASSERT(!fActiveOpsTask->isClosed()); SkASSERT(fActiveOpsTask == fDAG.back().get()); } for (int i = 0; i < fDAG.size(); ++i) { if (fActiveOpsTask != fDAG[i].get()) { // The resolveTask associated with the activeTask remains open for as long as the // activeTask does. bool isActiveResolveTask = fActiveOpsTask && fActiveOpsTask->fTextureResolveTask == fDAG[i].get(); bool isAtlas = fDAG[i]->isSetFlag(GrRenderTask::kAtlas_Flag); SkASSERT(isActiveResolveTask || isAtlas || fDAG[i]->isClosed()); } } // The active opsTask, if any, should always be at the back of the DAG. if (!fDAG.empty()) { if (fDAG.back()->isSetFlag(GrRenderTask::kAtlas_Flag)) { SkASSERT(fActiveOpsTask == nullptr); SkASSERT(!fDAG.back()->isClosed()); } else if (fDAG.back()->isClosed()) { SkASSERT(fActiveOpsTask == nullptr); } else { SkASSERT(fActiveOpsTask == fDAG.back().get()); } } else { SkASSERT(fActiveOpsTask == nullptr); } } #endif // SK_DEBUG void GrDrawingManager::closeActiveOpsTask() { if (fActiveOpsTask) { // This is a temporary fix for the partial-MDB world. In that world we're not // reordering so ops that (in the single opsTask world) would've just glommed onto the // end of the single opsTask but referred to a far earlier RT need to appear in their // own opsTask. fActiveOpsTask->makeClosed(fContext); fActiveOpsTask = nullptr; } } sk_sp<skgpu::ganesh::OpsTask> GrDrawingManager::newOpsTask(GrSurfaceProxyView surfaceView, sk_sp<GrArenas> arenas) { SkDEBUGCODE(this->validate()); SkASSERT(fContext); this->closeActiveOpsTask(); sk_sp<skgpu::ganesh::OpsTask> opsTask(new skgpu::ganesh::OpsTask( this, std::move(surfaceView), fContext->priv().auditTrail(), std::move(arenas))); SkASSERT(this->getLastRenderTask(opsTask->target(0)) == opsTask.get()); this->appendTask(opsTask); fActiveOpsTask = opsTask.get(); SkDEBUGCODE(this->validate()); return opsTask; } void GrDrawingManager::addAtlasTask(sk_sp<GrRenderTask> atlasTask, GrRenderTask* previousAtlasTask) { SkDEBUGCODE(this->validate()); SkASSERT(fContext); if (previousAtlasTask) { previousAtlasTask->makeClosed(fContext); for (GrRenderTask* previousAtlasUser : previousAtlasTask->dependents()) { // Make the new atlas depend on everybody who used the old atlas, and close their tasks. // This guarantees that the previous atlas is totally out of service before we render // the next one, meaning there is only ever one atlas active at a time and that they can // all share the same texture. atlasTask->addDependency(previousAtlasUser); previousAtlasUser->makeClosed(fContext); if (previousAtlasUser == fActiveOpsTask) { fActiveOpsTask = nullptr; } } } atlasTask->setFlag(GrRenderTask::kAtlas_Flag); this->insertTaskBeforeLast(std::move(atlasTask)); SkDEBUGCODE(this->validate()); } GrTextureResolveRenderTask* GrDrawingManager::newTextureResolveRenderTaskBefore( const GrCaps& caps) { // Unlike in the "new opsTask" case, we do not want to close the active opsTask, nor (if we are // in sorting and opsTask reduction mode) the render tasks that depend on any proxy's current // state. This is because those opsTasks can still receive new ops and because if they refer to // the mipmapped version of 'proxy', they will then come to depend on the render task being // created here. // // Add the new textureResolveTask before the fActiveOpsTask (if not in // sorting/opsTask-splitting-reduction mode) because it will depend upon this resolve task. // NOTE: Putting it here will also reduce the amount of work required by the topological sort. GrRenderTask* task = this->insertTaskBeforeLast(sk_make_sp<GrTextureResolveRenderTask>()); return static_cast<GrTextureResolveRenderTask*>(task); } void GrDrawingManager::newTextureResolveRenderTask(sk_sp<GrSurfaceProxy> proxy, GrSurfaceProxy::ResolveFlags flags, const GrCaps& caps) { SkDEBUGCODE(this->validate()); SkASSERT(fContext); if (!proxy->requiresManualMSAAResolve()) { SkDEBUGCODE(this->validate()); return; } GrRenderTask* lastTask = this->getLastRenderTask(proxy.get()); if (!proxy->asRenderTargetProxy()->isMSAADirty() && (!lastTask || lastTask->isClosed())) { SkDEBUGCODE(this->validate()); return; } this->closeActiveOpsTask(); auto resolveTask = sk_make_sp<GrTextureResolveRenderTask>(); // Add proxy also adds all the needed dependencies we need resolveTask->addProxy(this, std::move(proxy), flags, caps); auto task = this->appendTask(std::move(resolveTask)); task->makeClosed(fContext); // We have closed the previous active oplist but since a new oplist isn't being added there // shouldn't be an active one. SkASSERT(!fActiveOpsTask); SkDEBUGCODE(this->validate()); } void GrDrawingManager::newWaitRenderTask(sk_sp<GrSurfaceProxy> proxy, std::unique_ptr<std::unique_ptr<GrSemaphore>[]> semaphores, int numSemaphores) { SkDEBUGCODE(this->validate()); SkASSERT(fContext); sk_sp<GrWaitRenderTask> waitTask = sk_make_sp<GrWaitRenderTask>(GrSurfaceProxyView(proxy), std::move(semaphores), numSemaphores); if (fActiveOpsTask && (fActiveOpsTask->target(0) == proxy.get())) { SkASSERT(this->getLastRenderTask(proxy.get()) == fActiveOpsTask); this->insertTaskBeforeLast(waitTask); // In this case we keep the current renderTask open but just insert the new waitTask // before it in the list. The waitTask will never need to trigger any resolves or mip // map generation which is the main advantage of going through the proxy version. // Additionally we would've had to temporarily set the wait task as the lastRenderTask // on the proxy, add the dependency, and then reset the lastRenderTask to // fActiveOpsTask. Additionally we make the waitTask depend on all of fActiveOpsTask // dependencies so that we don't unnecessarily reorder the waitTask before them. // Note: Any previous Ops already in fActiveOpsTask will get blocked by the wait // semaphore even though they don't need to be for correctness. // Make sure we add the dependencies of fActiveOpsTask to waitTask first or else we'll // get a circular self dependency of waitTask on waitTask. waitTask->addDependenciesFromOtherTask(fActiveOpsTask); fActiveOpsTask->addDependency(waitTask.get()); } else { // In this case we just close the previous RenderTask and start and append the waitTask // to the DAG. Since it is the last task now we call setLastRenderTask on the proxy. If // there is a lastTask on the proxy we make waitTask depend on that task. This // dependency isn't strictly needed but it does keep the DAG from reordering the // waitTask earlier and blocking more tasks. if (GrRenderTask* lastTask = this->getLastRenderTask(proxy.get())) { waitTask->addDependency(lastTask); } this->setLastRenderTask(proxy.get(), waitTask.get()); this->closeActiveOpsTask(); this->appendTask(waitTask); } waitTask->makeClosed(fContext); SkDEBUGCODE(this->validate()); } void GrDrawingManager::newTransferFromRenderTask(sk_sp<GrSurfaceProxy> srcProxy, const SkIRect& srcRect, GrColorType surfaceColorType, GrColorType dstColorType, sk_sp<GrGpuBuffer> dstBuffer, size_t dstOffset) { SkDEBUGCODE(this->validate()); SkASSERT(fContext); this->closeActiveOpsTask(); GrRenderTask* task = this->appendTask(sk_make_sp<GrTransferFromRenderTask>( srcProxy, srcRect, surfaceColorType, dstColorType, std::move(dstBuffer), dstOffset)); const GrCaps& caps = *fContext->priv().caps(); // We always say GrMipmapped::kNo here since we are always just copying from the base layer. We // don't need to make sure the whole mip map chain is valid. task->addDependency(this, srcProxy.get(), GrMipmapped::kNo, GrTextureResolveManager(this), caps); task->makeClosed(fContext); // We have closed the previous active oplist but since a new oplist isn't being added there // shouldn't be an active one. SkASSERT(!fActiveOpsTask); SkDEBUGCODE(this->validate()); } void GrDrawingManager::newBufferTransferTask(sk_sp<GrGpuBuffer> src, size_t srcOffset, sk_sp<GrGpuBuffer> dst, size_t dstOffset, size_t size) { SkASSERT(src); SkASSERT(dst); SkASSERT(srcOffset + size <= src->size()); SkASSERT(dstOffset + size <= dst->size()); SkASSERT(src->intendedType() == GrGpuBufferType::kXferCpuToGpu); SkASSERT(dst->intendedType() != GrGpuBufferType::kXferCpuToGpu); SkDEBUGCODE(this->validate()); SkASSERT(fContext); this->closeActiveOpsTask(); sk_sp<GrRenderTask> task = GrBufferTransferRenderTask::Make(std::move(src), srcOffset, std::move(dst), dstOffset, size); SkASSERT(task); this->appendTask(task); task->makeClosed(fContext); // We have closed the previous active oplist but since a new oplist isn't being added there // shouldn't be an active one. SkASSERT(!fActiveOpsTask); SkDEBUGCODE(this->validate()); } void GrDrawingManager::newBufferUpdateTask(sk_sp<SkData> src, sk_sp<GrGpuBuffer> dst, size_t dstOffset) { SkASSERT(src); SkASSERT(dst); SkASSERT(dstOffset + src->size() <= dst->size()); SkASSERT(dst->intendedType() != GrGpuBufferType::kXferCpuToGpu); SkASSERT(!dst->isMapped()); SkDEBUGCODE(this->validate()); SkASSERT(fContext); this->closeActiveOpsTask(); sk_sp<GrRenderTask> task = GrBufferUpdateRenderTask::Make(std::move(src), std::move(dst), dstOffset); SkASSERT(task); this->appendTask(task); task->makeClosed(fContext); // We have closed the previous active oplist but since a new oplist isn't being added there // shouldn't be an active one. SkASSERT(!fActiveOpsTask); SkDEBUGCODE(this->validate()); } sk_sp<GrRenderTask> GrDrawingManager::newCopyRenderTask(sk_sp<GrSurfaceProxy> dst, SkIRect dstRect, sk_sp<GrSurfaceProxy> src, SkIRect srcRect, GrSamplerState::Filter filter, GrSurfaceOrigin origin) { SkDEBUGCODE(this->validate()); SkASSERT(fContext); // It'd be nicer to check this in GrCopyRenderTask::Make. This gets complicated because of // "active ops task" tracking. dst will be the target of our copy task but it might also be the // target of the active ops task. We currently require the active ops task to be closed before // making a new task that targets the same proxy. However, if we first close the active ops // task, then fail to make a copy task, the next active ops task may target the same proxy. This // will trip an assert related to unnecessary ops task splitting. if (src->framebufferOnly()) { return nullptr; } this->closeActiveOpsTask(); sk_sp<GrRenderTask> task = GrCopyRenderTask::Make(this, std::move(dst), dstRect, src, srcRect, filter, origin); if (!task) { return nullptr; } this->appendTask(task); const GrCaps& caps = *fContext->priv().caps(); // We always say GrMipmapped::kNo here since we are always just copying from the base layer to // another base layer. We don't need to make sure the whole mip map chain is valid. task->addDependency(this, src.get(), GrMipmapped::kNo, GrTextureResolveManager(this), caps); task->makeClosed(fContext); // We have closed the previous active oplist but since a new oplist isn't being added there // shouldn't be an active one. SkASSERT(!fActiveOpsTask); SkDEBUGCODE(this->validate()); return task; } bool GrDrawingManager::newWritePixelsTask(sk_sp<GrSurfaceProxy> dst, SkIRect rect, GrColorType srcColorType, GrColorType dstColorType, const GrMipLevel levels[], int levelCount) { SkDEBUGCODE(this->validate()); SkASSERT(fContext); this->closeActiveOpsTask(); const GrCaps& caps = *fContext->priv().caps(); // On platforms that prefer flushes over VRAM use (i.e., ANGLE) we're better off forcing a // complete flush here. if (!caps.preferVRAMUseOverFlushes()) { this->flushSurfaces(SkSpan<GrSurfaceProxy*>{}, SkSurface::BackendSurfaceAccess::kNoAccess, GrFlushInfo{}, nullptr); } GrRenderTask* task = this->appendTask(GrWritePixelsTask::Make(this, std::move(dst), rect, srcColorType, dstColorType, levels, levelCount)); if (!task) { return false; } task->makeClosed(fContext); // We have closed the previous active oplist but since a new oplist isn't being added there // shouldn't be an active one. SkASSERT(!fActiveOpsTask); SkDEBUGCODE(this->validate()); return true; } /* * This method finds a path renderer that can draw the specified path on * the provided target. * Due to its expense, the software path renderer has split out so it can * can be individually allowed/disallowed via the "allowSW" boolean. */ skgpu::ganesh::PathRenderer* GrDrawingManager::getPathRenderer( const PathRenderer::CanDrawPathArgs& args, bool allowSW, PathRendererChain::DrawType drawType, PathRenderer::StencilSupport* stencilSupport) { if (!fPathRendererChain) { fPathRendererChain = std::make_unique<PathRendererChain>(fContext, fOptionsForPathRendererChain); } auto pr = fPathRendererChain->getPathRenderer(args, drawType, stencilSupport); if (!pr && allowSW) { auto swPR = this->getSoftwarePathRenderer(); if (PathRenderer::CanDrawPath::kNo != swPR->canDrawPath(args)) { pr = swPR; } } #if GR_PATH_RENDERER_SPEW if (pr) { SkDebugf("getPathRenderer: %s\n", pr->name()); } #endif return pr; } skgpu::ganesh::PathRenderer* GrDrawingManager::getSoftwarePathRenderer() { if (!fSoftwarePathRenderer) { fSoftwarePathRenderer.reset(new skgpu::ganesh::SoftwarePathRenderer( fContext->priv().proxyProvider(), fOptionsForPathRendererChain.fAllowPathMaskCaching)); } return fSoftwarePathRenderer.get(); } skgpu::ganesh::AtlasPathRenderer* GrDrawingManager::getAtlasPathRenderer() { if (!fPathRendererChain) { fPathRendererChain = std::make_unique<PathRendererChain>(fContext, fOptionsForPathRendererChain); } return fPathRendererChain->getAtlasPathRenderer(); } skgpu::ganesh::PathRenderer* GrDrawingManager::getTessellationPathRenderer() { if (!fPathRendererChain) { fPathRendererChain = std::make_unique<PathRendererChain>(fContext, fOptionsForPathRendererChain); } return fPathRendererChain->getTessellationPathRenderer(); } void GrDrawingManager::flushIfNecessary() { auto direct = fContext->asDirectContext(); if (!direct) { return; } auto resourceCache = direct->priv().getResourceCache(); if (resourceCache && resourceCache->requestsFlush()) { if (this->flush({}, SkSurface::BackendSurfaceAccess::kNoAccess, GrFlushInfo(), nullptr)) { this->submitToGpu(false); } resourceCache->purgeAsNeeded(); } }
[ "jengelh@inai.de" ]
jengelh@inai.de
d8e3eabc911276a0cec7835d9b3d394b7f803fdb
df680738e90d9d7c0022b0d109f45b3a03ab1359
/entities/fire_streak.h
3b26477e8d567e5f74767096b2c8df4c3c90770d
[]
no_license
graysonpike/cs378-sdlgl-tank-game
fc303f8ab1d51eebef0ecf0b61c97f7d9de36033
742fb9b6df9f5a6bae86afe3de743e1f382ad916
refs/heads/main
2023-01-27T11:52:07.251327
2020-12-13T17:17:37
2020-12-13T17:17:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
369
h
#ifndef FIRESTREAK_H #define FIRESTREAK_H #include <utility> #include <sdlgl/game/physical_entity.h> #include <sdlgl/game/timer.h> class FireStreak : public PhysicalEntity { int end_x; int end_y; Timer timer; public: FireStreak(Scene *scene, std::pair<int, int> start, std::pair<int, int> end, float duration=1.0f); void update(); void render(); }; #endif
[ "graysonpike@gmail.com" ]
graysonpike@gmail.com
94e1f778978afa42c294dcb1a9ca0796f7e388bc
3d67864b29ce4b5438037af53d9cc18990661833
/MyTestApp/Camera.cpp
15f7b68c80869ac88e0990bbcd51abdaa0685708
[]
no_license
TheCapleGuy/NSFWGL_Personal
fcd4e807a45cf747f928ac7d2bc790bc55f5c789
7cbafbf93b7f7c2a9d183e45e9949596f02d9037
refs/heads/master
2021-01-10T15:15:57.060299
2015-12-11T00:48:15
2015-12-11T00:48:15
43,984,460
0
0
null
null
null
null
UTF-8
C++
false
false
568
cpp
#include "Camera.h" #include "Window.h" void Camera::update() { { auto &w = nsfw::Window::instance(); auto const &time = w.getTime(); //move camera right if (w.getKey('D')) m_transform[3] += m_transform[0] * (camSpeed * time); //move camera left if (w.getKey('A')) m_transform[3] -= m_transform[0] * (camSpeed * time); //move camera up if (w.getKey('W')) m_transform[3] -= m_transform[2] * (camSpeed * time); //move camera down if (w.getKey('S')) m_transform[3] += m_transform[2] * (camSpeed * time); } //lookAt(pos, target, up); }
[ "adrianocaple@gmail.com" ]
adrianocaple@gmail.com
211ff5dba81185772af16d6d050a622fe6592a98
f35bf9ff7405c179289f049fad4396198b4a0ef8
/Algorithms/BS_Rotated_SrchPivot.cpp
9a529677924e4fd3ef8d4b2a9cb822796fbad208
[]
no_license
proRamLOGO/Competitive_Programming
d19fc542e9f10faba9a23f4ef3335f367ccc125a
06e59ba95c3804cae10120ac7eda6482c3d72088
refs/heads/master
2023-01-03T07:27:25.960619
2020-10-29T19:15:53
2020-10-29T19:15:53
151,049,005
0
7
null
2020-10-29T19:15:54
2018-10-01T07:05:55
C++
UTF-8
C++
false
false
1,257
cpp
#include <iostream> #include <vector> using namespace std ; int main() { int n, x ; cin >> n ; vector< int > v(n) ; for ( auto i = 0 ; i < n ; ++i ) cin >> v[i] ; cin >> x ; int lo = 0, hi = n-1, mid, ans=-1 ; //Binary Search while ( hi >= lo ) { mid = (hi+lo) / 2 ; if ( v[mid]==x ) { ans = mid ; break ; } if ( v[mid] >= v[0]) { if ( v[0] <= x <= v[mid] ) hi = mid-1 ; else lo = mid+1 ; } else { if ( v[mid] <= x <= v[n-1] ) lo = mid+1 ; else hi = mid-1 ; } } cout << "Found " << x << " at " << ans << " index\n\n." ; //Find Pivot /* while ( hi >= lo ) { mid = (hi+lo) / 2 ; if ( v[mid] > v[mid+1] && mid < hi ) { break ; } else if ( v[mid-1] > v[mid] && mid > lo ) { --mid ; break ; } else if ( v[mid] <= v[lo] ) { hi = mid-1 ; } else if ( v[mid] >= v[hi] ) { lo = mid+1 ; } } cout << "Pivot at " << mid << " index\n\n" ;*/ }
[ "kapilgupta547@outlook.com" ]
kapilgupta547@outlook.com
b40c39526f1a278ce8d46e072f73db57b4b1516f
97477c1b51de48e76bd823e66c3197c1bc258afc
/Sources/Transition.cpp
01676a0eb46c9eed99307236a3417a74efe9644c
[]
no_license
anasteyshakoshman/Automaton
5085ee9ae2562dd6ac479f7eadf7829b9c8e4d54
02dde12f1c517625d76bcf947d223319c1eca3b8
refs/heads/master
2020-04-13T04:52:48.208402
2018-12-26T21:50:27
2018-12-26T21:50:27
161,214,591
0
0
null
null
null
null
UTF-8
C++
false
false
1,328
cpp
// // Created by Анастасия on 23/12/2018. // #include "../Headers/Transition.h" Transition::Transition() { Out = NONE; In = NONE; }; Transition::Transition(const state out, const char letter, const state in) { Out = out; In = in; Letter = letter; }; Transition & Transition::operator =(const Transition & obj) { Out = obj.Out; Letter = obj.Letter; In = obj.In; return *this; }; Transition & Transition::setIn(const int in) { In = in; return *this; }; Transition & Transition::setOut(const int out) { Out = out; return *this; }; Transition & Transition::setLetter(const char letter) { Letter = letter; return *this; }; state Transition::getOut() const { return Out; }; state Transition::getIn() const { return In; }; char Transition::getLetter() const { return Letter; }; bool Transition::operator ==(const Transition & obj) const { return obj.In == In && obj.Out == Out && obj.Letter == Letter; }; bool Transition::operator >(const Transition & obj) const { if(Out == obj.Out) return In > obj.In; else return Out > obj.Out; }; Transition::~Transition() { Out = NONE; In = NONE; }; bool operator <(const Transition & lhs, const Transition & rhs) { if(lhs == rhs) return false; else return !(lhs > rhs); };
[ "anastasiay.andreevnaa@gmail.com" ]
anastasiay.andreevnaa@gmail.com
5ed1d6af490aa7d4eb2f459372eac1cd680272c4
09545709c219b7532cd2623708265965588318d3
/Cgadius 0.5/CMP105App/Level.h
269ba78be0d1a253f2be8bd5844bde896e376cb0
[]
no_license
dardarus86/Cgadius
a6bcc85abf0a788bea0188cba8cef5e4d18e752d
83bea7f94cc4aa90bfd0e1816b4a5ca6589c3099
refs/heads/master
2021-11-03T20:42:06.436457
2019-04-27T01:44:48
2019-04-27T01:44:48
177,153,459
0
0
null
null
null
null
UTF-8
C++
false
false
1,144
h
#pragma once #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include "Framework/Input.h" #include "Framework/Collision.h" #include "AsteroidManager.h" #include "WallManager.h" #include "EnemyManager.h" #include "Asteroid.h" #include "Enemy.h" #include "Wall.h" #include "Player.h" #include <string.h> #include <string> #include <iostream> class Level{ public: Level(sf::RenderWindow* hwnd, Input* in); ~Level(); void handleInput(float dt); void update(float dt); void render(); private: // Default functions for rendering to the screen. void beginDraw(); void endDraw(); // Default variables for level class. sf::RenderWindow* window; Input* input; //bullet //View sf::View view1; sf::View scoreview; //Sound+Music sf::SoundBuffer boss; sf::Sound sound; sf::Music music; //background GameObject background; sf::Texture backgroundtexture; //player Player player; sf::Texture playertexture; //wall(white collidable wall objects in level) AsteroidManager asteroidManager; WallManager wallManager; EnemyManager enemyManager; //text sf::Font font; sf::Text score; sf::Text time; sf::Text lives; };
[ "jamiehaddow@hotmail.com" ]
jamiehaddow@hotmail.com
2d9baf02f1a529a7cc7447b8169263a2392c99c4
d4ad9c07d8fac9e800170b1af05954ddf297e394
/ventana.cpp
a09e5318ad898d8608f1518198284f89649d7fae
[]
no_license
etanol/vigger
04c3d4011e47498fa95747181963f6aef9a84dd0
dfa955f1601cda7bb2335790cdabaf867525a292
refs/heads/master
2020-04-29T07:52:11.731284
2012-11-09T14:08:09
2012-11-09T14:08:09
175,967,188
0
0
null
null
null
null
UTF-8
C++
false
false
13,799
cpp
// // ventana.cpp - Implementación de la clase Ventana // // Este fichero reemplaza el antiguo ventana.ui.h siguiendo los cambios // determinados por la migración de Qt3 a Qt4. // #include <QFileInfo> #include <QFileDialog> #include <QMessageBox> #include <QColorDialog> #include <QColor> #include "ventana.h" #include "ayuda.h" Ventana::Ventana () : QWidget(0) { setupUi(this); // Conexiones de signals y slots. Para verlo mejor, ampliar la anchura de // la ventana del editor hasta 110 columnas. // // Las conexiones se programan aquí ya que en el QtDesigner de Qt4 no // permite utilizar signals y slots definidos por el usuario. connect(btnAyuda, SIGNAL(clicked()), this, SLOT(cargaAyuda())); connect(btnAmbiente, SIGNAL(clicked()), this, SLOT(setColorAmbiente())); connect(btnCargaEs, SIGNAL(clicked()), this, SLOT(cargaEscenario())); connect(btnCargaRo, SIGNAL(clicked()), this, SLOT(cargaRobot())); connect(btnColorFondo, SIGNAL(clicked()), this, SLOT(colorFondo())); connect(btnDifusa, SIGNAL(clicked()), this, SLOT(setColorDifusa())); connect(btnEspecular, SIGNAL(clicked()), this, SLOT(setColorEspecular())); connect(btnFrustum, SIGNAL(clicked()), this, SLOT(colorFrustum())); connect(btnResetCam, SIGNAL(clicked()), glVista, SLOT(reseteaCam())); connect(btnSeleccionado, SIGNAL(clicked()), this, SLOT(setColorSeleccionado())); connect(btnSalir, SIGNAL(clicked()), this, SLOT(close())); connect(btnVisibles, SIGNAL(clicked()), this, SLOT(setColorVisibles())); connect(chkCamPrimera, SIGNAL(toggled(bool)), glVista, SLOT(setCamPrimera(bool))); connect(chkAlambre, SIGNAL(toggled(bool)), glVista, SLOT(pintaAlambre(bool))); connect(chkLActiva, SIGNAL(toggled(bool)), this, SLOT(cambiaEstadoLuz(bool))); connect(chkMarcVisibles, SIGNAL(toggled(bool)), glVista, SLOT(setMarcaVis(bool))); connect(chkMovimiento, SIGNAL(toggled(bool)), glVista, SLOT(animaRobots(bool))); connect(chkVisFrustum, SIGNAL(toggled(bool)), glVista, SLOT(setPintaFrus(bool))); connect(cmbLuz, SIGNAL(activated(int)), this, SLOT(cambiaLuz(int))); connect(cmbReferencia, SIGNAL(activated(int)), this, SLOT(coordenadasLuz())); connect(cmbRotaRobots, SIGNAL(activated(int)), glVista, SLOT(setRotacionRob(int))); connect(glVista, SIGNAL(nuevoAR(double)), dspAR, SLOT(display(double))); connect(glVista, SIGNAL(nuevoPanX(double)), dspPanX, SLOT(display(double))); connect(glVista, SIGNAL(nuevoPanY(double)), dspPanY, SLOT(display(double))); connect(glVista, SIGNAL(nuevoZNear(double)), dspzNear, SLOT(display(double))); connect(glVista, SIGNAL(nuevoZFar(double)), dspzFar, SLOT(display(double))); connect(glVista, SIGNAL(nuevoAnguloA(int)), dspApertura, SLOT(display(int))); connect(glVista, SIGNAL(nuevoAnguloX(int)), sldAnguloX, SLOT(setValue(int))); connect(glVista, SIGNAL(nuevoAnguloY(int)), sldAnguloY, SLOT(setValue(int))); connect(glVista, SIGNAL(nuevoAnguloZ(int)), sldAnguloZ, SLOT(setValue(int))); connect(glVista, SIGNAL(nuevoAnguloA(int)), sldApertura, SLOT(setValue(int))); connect(glVista, SIGNAL(nuevaDist(int)), sldDistancia, SLOT(setValue(int))); connect(glVista, SIGNAL(nuevaSel(int)), dspSeleccionado, SLOT(display(int))); connect(glVista, SIGNAL(nuevoRadio(double)), dspRadio, SLOT(display(double))); connect(glVista, SIGNAL(nuevoRadioXZ(double)), dspRadioXZ, SLOT(display(double))); connect(glVista, SIGNAL(nuevoRadio(double)), this, SLOT(actualizaRadio(double))); connect(glVista, SIGNAL(alturas(int,int)), this, SLOT(actualizaAlturas(int,int))); connect(sldAltura, SIGNAL(sliderMoved(int)), glVista, SLOT(setAltura(int))); connect(sldAltura, SIGNAL(valueChanged(int)), dspAltura, SLOT(displayFloat(int))); connect(sldAnguloX, SIGNAL(valueChanged(int)), dspAnguloX, SLOT(display(int))); connect(sldAnguloX, SIGNAL(sliderMoved(int)), glVista, SLOT(setAnguloX(int))); connect(sldAnguloY, SIGNAL(valueChanged(int)), dspAnguloY, SLOT(display(int))); connect(sldAnguloY, SIGNAL(sliderMoved(int)), glVista, SLOT(setAnguloY(int))); connect(sldAnguloZ, SIGNAL(valueChanged(int)), dspAnguloZ, SLOT(display(int))); connect(sldAnguloZ, SIGNAL(sliderMoved(int)), glVista, SLOT(setAnguloZ(int))); connect(sldDistancia, SIGNAL(valueChanged(int)), dspDistancia, SLOT(displayFloat(int))); connect(sldDistancia, SIGNAL(sliderMoved(int)), glVista, SLOT(setDistancia(int))); connect(sldApertura, SIGNAL(sliderMoved(int)), glVista, SLOT(setApertura(int))); connect(sldTransparencia, SIGNAL(valueChanged(int)), glVista, SLOT(setTrFrust(int))); connect(sldZFarPrimera, SIGNAL(valueChanged(int)), glVista, SLOT(setZFarCamPri(int))); connect(spbFPS, SIGNAL(valueChanged(int)), glVista, SLOT(setFPS(int))); connect(spbNumRobots, SIGNAL(valueChanged(int)), glVista, SLOT(setNumRobots(int))); connect(spbVangular, SIGNAL(valueChanged(int)), glVista, SLOT(setVAngular(int))); connect(spbVlineal, SIGNAL(valueChanged(int)), glVista, SLOT(setVLineal(int))); connect(txtlCoordX, SIGNAL(returnPressed()), this, SLOT(coordenadasLuz())); connect(txtlCoordY, SIGNAL(returnPressed()), this, SLOT(coordenadasLuz())); connect(txtlCoordZ, SIGNAL(returnPressed()), this, SLOT(coordenadasLuz())); // Configuramos la ventana de selección de modelos seleccionModelo = new QFileDialog(this, Qt::Dialog); ventanaAyuda = new Ayuda(this); seleccionModelo->setFilter("Models 3DS (*.3ds)"); // Estos valores son 'hardcoded', así que cuidado al cambiarlos; consultar // glfuncs.cpp btnFrustum ->setRGB( 0, 0, 200); btnSeleccionado->setRGB(240, 240, 0); btnVisibles ->setRGB( 0, 240, 0); btnColorFondo ->setRGB(102, 102, 102); cambiaLuz(0); } // // cargaAyuda - Muestra la ventana de ayuda. // void Ventana::cargaAyuda () { ventanaAyuda->show(); } // // cargaEscenario - Muestra un diálogo para seleccionar un fichero que se carga // como escenario. // void Ventana::cargaEscenario () { if (seleccionModelo->exec() == QDialog::Accepted) { if (glVista->cargaEscenario(seleccionModelo->selectedFiles()[0])) btnCargaRo->setEnabled(true); // Ya podemos cargar robots else { // Imprime error QFileInfo fi(seleccionModelo->selectedFiles()[0]); QMessageBox::critical(this, "Error", "No se ha podido abrir el fichero " + fi.fileName(), QMessageBox::Ok, QMessageBox::NoButton); } } } // // cargaRobot - Muestra un diálogo para seleccionar un fichero que se cargará // como robot. // void Ventana::cargaRobot () { if (seleccionModelo->exec() == QDialog::Accepted) { if (!glVista->cargaRobots(seleccionModelo->selectedFiles()[0])) { // Error QFileInfo fi(seleccionModelo->selectedFiles()[0]); QMessageBox::critical(this, "Error", "No se ha podido abrir el fichero " + fi.fileName(), QMessageBox::Ok, QMessageBox::NoButton); } } } // // actualizaRadio - Ajusta los sliders necesarios según el valor de "radio". // void Ventana::actualizaRadio (double radio) { sldDistancia->setMaximum(static_cast<int>(100.0*radio)); sldDistancia->setMinimum(0); sldZFarPrimera->setMaximum(static_cast<int>(20.0*radio)); sldZFarPrimera->setValue(static_cast<int>(20.0*radio)); } // // actualizaAlguras - Ajusta el slider de altura de los robots teniendo en // cuenta "maxescenaY" y "maxrobotY". // void Ventana::actualizaAlturas (int maxescenaY, int maxrobotY) { sldAltura->setMinimum(maxrobotY - maxescenaY); sldAltura->setMaximum(maxescenaY - maxrobotY); sldAltura->setValue(maxrobotY); } // // setColorLuz - Cambia alguna componente de la luz actual seleccionada en la // ventana. // void Ventana::setColorLuz (VPushButton *b, int componente) { QColor c; c = QColorDialog::getColor(QColor(b->getR(), b->getG(), b->getB()), this); b->setRGB(c.red(), c.green(), c.blue()); glVista->setColLuz(cmbLuz->currentIndex(), componente, c.red(), c.green(), c.blue()); glVista->updateGL(); } // Ahora enlazamos con los clicks de los botones void Ventana::setColorAmbiente () { setColorLuz(btnAmbiente, 0); } void Ventana::setColorDifusa () { setColorLuz(btnDifusa, 1); } void Ventana::setColorEspecular () { setColorLuz(btnEspecular, 2); } // // coordenadasLuz - Cambia las coordenadas y la referencia de la luz actual // seleccionada en la ventana. // void Ventana::coordenadasLuz () { bool okx, oky, okz; float valx, valy, valz; valx = txtlCoordX->text().toFloat(&okx); valy = txtlCoordY->text().toFloat(&oky); valz = txtlCoordZ->text().toFloat(&okz); if (okx && oky && okz) { glVista->setPosLuz(cmbLuz->currentIndex(), valx, valy, valz, cmbReferencia->currentIndex() == 0); glVista->updateGL(); } else QMessageBox::critical(this, "Error", "Coordenadas incorrectas", QMessageBox::Ok, QMessageBox::NoButton); } // // colorSeleccionados - Selecciona el color de los seleccionados (valga la // redundancia) según el botón que se haya pulsado. // void Ventana::colorSeleccionados (VPushButton *b, int indice) { QColor c; c = QColorDialog::getColor(QColor(b->getR(), b->getG(), b->getB()), this); b->setRGB(c.red(), c.green(), c.blue()); glVista->setColSelec(indice, c.red(), c.green(), c.blue()); glVista->updateGL(); } // Ahora enlazamos con los clicks de los botones void Ventana::setColorSeleccionado () { colorSeleccionados(btnSeleccionado,0); } void Ventana::setColorVisibles () { colorSeleccionados(btnVisibles, 1); } // // colorFrustum - Cambia el color del frustum y ya está. // void Ventana::colorFrustum () { QColor c; c = QColorDialog::getColor(QColor(btnFrustum->getR(), btnFrustum->getG(), btnFrustum->getB()), this); btnFrustum->setRGB(c.red(), c.green(), c.blue()); glVista->setColFrust(c.red(), c.green(), c.blue()); glVista->updateGL(); } // // colorFondo - Cambia el color de fondo de la escena. // void Ventana::colorFondo () { QColor c; c = QColorDialog::getColor(QColor(btnColorFondo->getR(), btnColorFondo->getG(), btnColorFondo->getB()), this); btnColorFondo->setRGB(c.red(), c.green(), c.blue()); glVista->setColorFondo(c.red(), c.green(), c.blue()); glVista->updateGL(); } // // cambiaLuz - Cambia la luz seleccionada y actualiza la parte de luz en la // interfaz. Uff, qué palo. // void Ventana::cambiaLuz (int luz) { int rgb[3]; float *pos; bool enable = glVista->luzActivada(luz); // Replicamos el código de la función "cambioEstadoLuz()" porque aquí // necesitamos modificar el estado de "chkLActiva" sin que se emita ninguna // señal chkLActiva->blockSignals(true); chkLActiva->setChecked(enable); btnAmbiente->setEnabled(enable); btnDifusa->setEnabled(enable); btnEspecular->setEnabled(enable); txtlCoordX->setEnabled(enable); txtlCoordY->setEnabled(enable); txtlCoordZ->setEnabled(enable); cmbReferencia->setEnabled(enable); chkLActiva->blockSignals(false); // Consultamos los colores glVista->getColLuz(luz, 0, rgb); btnAmbiente->setRGB(rgb[0], rgb[1], rgb[2]); glVista->getColLuz(luz, 1, rgb); btnDifusa->setRGB(rgb[0], rgb[1], rgb[2]); glVista->getColLuz(luz, 2, rgb); btnEspecular->setRGB(rgb[0], rgb[1], rgb[2]); // I les coordenades cmbReferencia->setCurrentIndex(glVista->getRefLuz(luz) ? 0 : 1); pos = glVista->getPosLuz(luz); txtlCoordX->setText(QString::number(pos[0], 'f', 3)); txtlCoordY->setText(QString::number(pos[1], 'f', 3)); txtlCoordZ->setText(QString::number(pos[2], 'f', 3)); } // // cambiaEstadoLuz - Activa o desactiva la luz actual. // void Ventana::cambiaEstadoLuz (bool estado) { glVista->activaLuz(cmbLuz->currentIndex(), estado); // Activamos y desactivamos según el booleano btnAmbiente->setEnabled(estado); btnDifusa->setEnabled(estado); btnEspecular->setEnabled(estado); txtlCoordX->setEnabled(estado); txtlCoordY->setEnabled(estado); txtlCoordZ->setEnabled(estado); cmbReferencia->setEnabled(estado); // Actualizamos la posició por si acaso coordenadasLuz(); }
[ "diptongo@gmail.com" ]
diptongo@gmail.com
6e72bfece938ebd76d0a0e2a998d607ae2fc2029
ce4228a3005f297cd2eddf14dfee37eeeaae9d64
/9_2.cpp
df5ca52ff417aa3de591e9b68faf5511cb66c3ab
[]
no_license
ShushGalstyan/Exercises-Chapter-9
a7e57932c465ca7c44c857677a0a64efb4310e41
891ac2eead1ed99e4fc2a3122c7933c4a75cf78a
refs/heads/master
2020-03-23T10:27:51.689754
2018-07-21T19:04:28
2018-07-21T19:04:28
141,444,543
0
0
null
null
null
null
UTF-8
C++
false
false
639
cpp
//9_2.cpp // Demonstrating the class member access operators . and -> #include <iostream> using namespace std; class Count { public: int setX(int value) { x = value; } void print() { cout<< x<<endl; } private: int x; }; int main() { Count Counter; Count *CounterPtr = &Counter; Count &CounterRef = Counter; cout << "Set x to 1 and print using the object's name: "; Counter.setX(1); Counter.print(); cout << "Set x to 3 and print using a pointer to an object: "; CounterPtr->setX(2); CounterPtr->print(); cout << "Set x to 2 and print using a reference to an object: "; CounterRef.setX(3); CounterRef.print(); }
[ "shush.galstyan.10@mail.ru" ]
shush.galstyan.10@mail.ru
e5c04ba609c08881268b7b48beecd6be608d0f28
7e85999425d16039207c2e86f450452088d1ad1a
/cc/ModelSubroutines.h
73ef347ac62e2ba270e4e9b999be4c1d3f12e9e5
[]
no_license
proger/inquiry
914f8402c69811d86d3505dc108f43c3d7acbd71
07774dd86a367bb0f4f2e17141f72dab9c225dd0
refs/heads/master
2021-01-20T06:26:11.939703
2011-11-16T13:45:55
2011-11-16T13:45:55
2,813,340
1
0
null
null
null
null
UTF-8
C++
false
false
1,594
h
/* $SYSREVERSE: ModelSubroutines.h,v 1.7 2011/05/05 19:48:18 proger Exp $ */ #ifndef _SYSREV_INQUIRY_AST_MODELSUBR_H_ #define _SYSREV_INQUIRY_AST_MODELSUBR_H_ #include <clang/AST/Decl.h> #include <clang/AST/DeclGroup.h> #include <clang/AST/Stmt.h> #include <clang/AST/Expr.h> #include <clang/AST/Type.h> #include <clang/Sema/DeclSpec.h> namespace inquiry { namespace AST { using namespace clang; using std::string; static inline Model::Location Location(clang::PresumedLoc &ploc) { Model::Location o(string(ploc.getFilename()), ploc.getLine(), ploc.getColumn()); return o; } static inline Model::Location Location(clang::SourceManager &sm, clang::SourceLocation loc) { clang::PresumedLoc ploc = sm.getPresumedLoc(loc); return Location(ploc); } static inline unsigned short TagTypeKindToModelType(clang::TagTypeKind ttk) { switch (ttk) { case clang::TTK_Struct: return (TYPE_STRUCT); case clang::TTK_Union: return (TYPE_UNION); case clang::TTK_Enum: return (TYPE_ENUM); default: /* class is not supported atm */ return (0); }; } #define TYPESPEC_UNCLOAK_STRUCTURE(type, vspec, vdecl) do { \ if (const TagType *rt = (type)->getAs<TagType>()) { \ vspec = TagTypeKindToModelType( \ rt->getDecl()->getTagKind()); \ vdecl = rt->getDecl(); \ } else if (const TypedefType *tt = (type)->getAs<TypedefType>()) {\ vspec = TYPE_TYPEDEF; \ vdecl = tt->getDecl(); \ } else { \ vdecl = NULL; \ break; \ } \ } while (0); } /* namespace AST */ } /* namespace inquiry */ #endif /* _SYSREV_INQUIRY_AST_MODELSUBR_H_ */
[ "proger@wilab.org.ua" ]
proger@wilab.org.ua
1d2b68877936ee53c37560572753e19299396fa0
38e9780cb2d2f9069428302b1ba4b4bb4ca04ed6
/Huiswerk/Eindopdracht/Game Engine V2/stdafx.cpp
dc4fa79c9f41aa8ed495c54e8ecdd074a92e842a
[]
no_license
MaurodeLyon/Computer-Vision
6184fc13eb7812979a984fafb6bb6a8dba5df9ac
d0271ec47ac50d8daedfa25247b12f155456b042
refs/heads/master
2021-01-17T13:27:09.885862
2016-06-07T19:30:14
2016-06-07T19:30:14
56,507,877
0
0
null
null
null
null
UTF-8
C++
false
false
293
cpp
// stdafx.cpp : source file that includes just the standard includes // Game Engine V2.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "maurodelyon@gmail.com" ]
maurodelyon@gmail.com
caab951c611645cad2d32945f7c807a2c5285f6d
799d9503ac8bbabae206e0f12cd6f29121e3734f
/utils/particle_filter/landmarks_transformation.cpp
e012412dec8bf756e557bdea3be7acc346dff51e
[ "MIT" ]
permissive
andrea-ortalda/CarND-Kidnapped-Vehicle-Project
71344c82b2861db7bd7b1a2194dc7eb094b5ccaa
63a7446b24d049bc1e4d5a0575f63fb5cb351fb4
refs/heads/master
2020-12-26T19:58:54.781013
2020-02-01T17:59:55
2020-02-01T17:59:55
237,624,574
0
0
null
null
null
null
UTF-8
C++
false
false
1,788
cpp
#include <cmath> #include <iostream> int main() { // define coordinates and theta double x_part, y_part, x_obs, y_obs, theta; x_part = 4; y_part = 5; x_obs = 2; y_obs = 2; theta = -M_PI / 2; // -90 degrees // transform to map x coordinate double x_map; x_map = x_part + (cos(theta) * x_obs) - (sin(theta) * y_obs); // transform to map y coordinate double y_map; y_map = y_part + (sin(theta) * x_obs) + (cos(theta) * y_obs); // (6,3) std::cout << int(round(x_map)) << ", " << int(round((y_map)) << std::endl; return 0; } //#include <cmath> //#include <iostream> // //int main() { // // define coordinates and theta // double x_part, y_part, x_obs, y_obs, theta; // x_part = 4; // y_part = 5; // x_obs = 3; // y_obs = -2; // theta = -M_PI/2; // -90 degrees // // // transform to map x coordinate // double x_map; // x_map = x_part + (cos(theta) * x_obs) - (sin(theta) * y_obs); // // // transform to map y coordinate // double y_map; // y_map = y_part + (sin(theta) * x_obs) + (cos(theta) * y_obs); // // // (2,2) // std::cout << int(round(x_map)) << ", " << int(round(y_map)) << std::endl; // // return 0; //} // #include <cmath> // #include <iostream> // // int main() { // // define coordinates and theta // double x_part, y_part, x_obs, y_obs, theta; // x_part = 4; // y_part = 5; // x_obs = 0; // y_obs = -4; // theta = -M_PI/2; // -90 degrees // // // transform to map x coordinate // double x_map; // x_map = x_part + (cos(theta) * x_obs) - (sin(theta) * y_obs); // // // transform to map y coordinate // double y_map; // y_map = y_part + (sin(theta) * x_obs) + (cos(theta) * y_obs); // // // (0,5) // std::cout << int(round(x_map)) << ", " << int(round(y_map)) << std::endl; // // return 0; // }
[ "andrea.ortalda@fcagroup.com" ]
andrea.ortalda@fcagroup.com
4decdf0ee459b4ad4834de54415479e5bd8d5726
f5f750efbde0ccd95856820c975ec88ee6ace0f8
/aws-cpp-sdk-sqs/include/aws/sqs/model/SetQueueAttributesRequest.h
f22d8ab8cb2c5ea9dae69cacd029630cfb33d9da
[ "JSON", "MIT", "Apache-2.0" ]
permissive
csimmons0/aws-sdk-cpp
578a4ae6e7899944f8850dc37accba5568b919eb
1d0e1ddb51022a02700a9d1d3658abf628bb41c8
refs/heads/develop
2020-06-17T14:58:41.406919
2017-04-12T03:45:33
2017-04-12T03:45:33
74,995,798
0
0
null
2017-03-02T05:35:49
2016-11-28T17:12:34
C++
UTF-8
C++
false
false
64,036
h
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/sqs/SQS_EXPORTS.h> #include <aws/sqs/SQSRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSMap.h> #include <aws/sqs/model/QueueAttributeName.h> namespace Aws { namespace SQS { namespace Model { /** * <p/><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/SetQueueAttributesRequest">AWS * API Reference</a></p> */ class AWS_SQS_API SetQueueAttributesRequest : public SQSRequest { public: SetQueueAttributesRequest(); Aws::String SerializePayload() const override; protected: void DumpBodyToUrl(Aws::Http::URI& uri ) const override; public: /** * <p>The URL of the Amazon SQS queue whose attributes are set.</p> <p>Queue URLs * are case-sensitive.</p> */ inline const Aws::String& GetQueueUrl() const{ return m_queueUrl; } /** * <p>The URL of the Amazon SQS queue whose attributes are set.</p> <p>Queue URLs * are case-sensitive.</p> */ inline void SetQueueUrl(const Aws::String& value) { m_queueUrlHasBeenSet = true; m_queueUrl = value; } /** * <p>The URL of the Amazon SQS queue whose attributes are set.</p> <p>Queue URLs * are case-sensitive.</p> */ inline void SetQueueUrl(Aws::String&& value) { m_queueUrlHasBeenSet = true; m_queueUrl = value; } /** * <p>The URL of the Amazon SQS queue whose attributes are set.</p> <p>Queue URLs * are case-sensitive.</p> */ inline void SetQueueUrl(const char* value) { m_queueUrlHasBeenSet = true; m_queueUrl.assign(value); } /** * <p>The URL of the Amazon SQS queue whose attributes are set.</p> <p>Queue URLs * are case-sensitive.</p> */ inline SetQueueAttributesRequest& WithQueueUrl(const Aws::String& value) { SetQueueUrl(value); return *this;} /** * <p>The URL of the Amazon SQS queue whose attributes are set.</p> <p>Queue URLs * are case-sensitive.</p> */ inline SetQueueAttributesRequest& WithQueueUrl(Aws::String&& value) { SetQueueUrl(value); return *this;} /** * <p>The URL of the Amazon SQS queue whose attributes are set.</p> <p>Queue URLs * are case-sensitive.</p> */ inline SetQueueAttributesRequest& WithQueueUrl(const char* value) { SetQueueUrl(value); return *this;} /** * <p>A map of attributes to set.</p> <p>The following lists the names, * descriptions, and values of the special request parameters that the * <code>SetQueueAttributes</code> action uses:</p> <ul> <li> <p> * <code>DelaySeconds</code> - The number of seconds for which the delivery of all * messages in the queue is delayed. Valid values: An integer from 0 to 900 (15 * minutes). The default is 0 (zero). </p> </li> <li> <p> * <code>MaximumMessageSize</code> - The limit of how many bytes a message can * contain before Amazon SQS rejects it. Valid values: An integer from 1,024 bytes * (1 KiB) up to 262,144 bytes (256 KiB). The default is 262,144 (256 KiB). </p> * </li> <li> <p> <code>MessageRetentionPeriod</code> - The number of seconds for * which Amazon SQS retains a message. Valid values: An integer representing * seconds, from 60 (1 minute) to 1,209,600 (14 days). The default is 345,600 (4 * days). </p> </li> <li> <p> <code>Policy</code> - The queue's policy. A valid AWS * policy. For more information about policy structure, see <a * href="http://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html">Overview * of AWS IAM Policies</a> in the <i>Amazon IAM User Guide</i>. </p> </li> <li> <p> * <code>ReceiveMessageWaitTimeSeconds</code> - The number of seconds for which a * <code> <a>ReceiveMessage</a> </code> action waits for a message to arrive. Valid * values: an integer from 0 to 20 (seconds). The default is 0. </p> </li> <li> <p> * <code>RedrivePolicy</code> - The parameters for the dead letter queue * functionality of the source queue. For more information about the redrive policy * and dead letter queues, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html">Using * Amazon SQS Dead Letter Queues</a> in the <i>Amazon SQS Developer Guide</i>. </p> * <note> <p>The dead letter queue of a FIFO queue must also be a FIFO queue. * Similarly, the dead letter queue of a standard queue must also be a standard * queue.</p> </note> </li> <li> <p> <code>VisibilityTimeout</code> - The * visibility timeout for the queue. Valid values: an integer from 0 to 43,200 (12 * hours). The default is 30. For more information about the visibility timeout, * see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html">Visibility * Timeout</a> in the <i>Amazon SQS Developer Guide</i>.</p> </li> </ul> <p>The * following attribute applies only to <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html">FIFO * (first-in-first-out) queues</a>:</p> <ul> <li> <p> * <code>ContentBasedDeduplication</code> - Enables content-based deduplication. * For more information, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing">Exactly-Once * Processing</a> in the <i>Amazon SQS Developer Guide</i>. </p> <ul> <li> <p>Every * message must have a unique <code>MessageDeduplicationId</code>,</p> <ul> <li> * <p>You may provide a <code>MessageDeduplicationId</code> explicitly.</p> </li> * <li> <p>If you aren't able to provide a <code>MessageDeduplicationId</code> and * you enable <code>ContentBasedDeduplication</code> for your queue, Amazon SQS * uses a SHA-256 hash to generate the <code>MessageDeduplicationId</code> using * the body of the message (but not the attributes of the message). </p> </li> <li> * <p>If you don't provide a <code>MessageDeduplicationId</code> and the queue * doesn't have <code>ContentBasedDeduplication</code> set, the action fails with * an error.</p> </li> <li> <p>If the queue has * <code>ContentBasedDeduplication</code> set, your * <code>MessageDeduplicationId</code> overrides the generated one.</p> </li> </ul> * </li> <li> <p>When <code>ContentBasedDeduplication</code> is in effect, messages * with identical content sent within the deduplication interval are treated as * duplicates and only one copy of the message is delivered.</p> </li> <li> <p>You * can also use <code>ContentBasedDeduplication</code> for messages with identical * content to be treated as duplicates.</p> </li> <li> <p>If you send one message * with <code>ContentBasedDeduplication</code> enabled and then another message * with a <code>MessageDeduplicationId</code> that is the same as the one generated * for the first <code>MessageDeduplicationId</code>, the two messages are treated * as duplicates and only one copy of the message is delivered. </p> </li> </ul> * </li> </ul> <p>Any other valid special request parameters (such as the * following) are ignored:</p> <ul> <li> <p> * <code>ApproximateNumberOfMessages</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesDelayed</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesNotVisible</code> </p> </li> <li> <p> * <code>CreatedTimestamp</code> </p> </li> <li> <p> * <code>LastModifiedTimestamp</code> </p> </li> <li> <p> <code>QueueArn</code> * </p> </li> </ul> */ inline const Aws::Map<QueueAttributeName, Aws::String>& GetAttributes() const{ return m_attributes; } /** * <p>A map of attributes to set.</p> <p>The following lists the names, * descriptions, and values of the special request parameters that the * <code>SetQueueAttributes</code> action uses:</p> <ul> <li> <p> * <code>DelaySeconds</code> - The number of seconds for which the delivery of all * messages in the queue is delayed. Valid values: An integer from 0 to 900 (15 * minutes). The default is 0 (zero). </p> </li> <li> <p> * <code>MaximumMessageSize</code> - The limit of how many bytes a message can * contain before Amazon SQS rejects it. Valid values: An integer from 1,024 bytes * (1 KiB) up to 262,144 bytes (256 KiB). The default is 262,144 (256 KiB). </p> * </li> <li> <p> <code>MessageRetentionPeriod</code> - The number of seconds for * which Amazon SQS retains a message. Valid values: An integer representing * seconds, from 60 (1 minute) to 1,209,600 (14 days). The default is 345,600 (4 * days). </p> </li> <li> <p> <code>Policy</code> - The queue's policy. A valid AWS * policy. For more information about policy structure, see <a * href="http://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html">Overview * of AWS IAM Policies</a> in the <i>Amazon IAM User Guide</i>. </p> </li> <li> <p> * <code>ReceiveMessageWaitTimeSeconds</code> - The number of seconds for which a * <code> <a>ReceiveMessage</a> </code> action waits for a message to arrive. Valid * values: an integer from 0 to 20 (seconds). The default is 0. </p> </li> <li> <p> * <code>RedrivePolicy</code> - The parameters for the dead letter queue * functionality of the source queue. For more information about the redrive policy * and dead letter queues, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html">Using * Amazon SQS Dead Letter Queues</a> in the <i>Amazon SQS Developer Guide</i>. </p> * <note> <p>The dead letter queue of a FIFO queue must also be a FIFO queue. * Similarly, the dead letter queue of a standard queue must also be a standard * queue.</p> </note> </li> <li> <p> <code>VisibilityTimeout</code> - The * visibility timeout for the queue. Valid values: an integer from 0 to 43,200 (12 * hours). The default is 30. For more information about the visibility timeout, * see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html">Visibility * Timeout</a> in the <i>Amazon SQS Developer Guide</i>.</p> </li> </ul> <p>The * following attribute applies only to <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html">FIFO * (first-in-first-out) queues</a>:</p> <ul> <li> <p> * <code>ContentBasedDeduplication</code> - Enables content-based deduplication. * For more information, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing">Exactly-Once * Processing</a> in the <i>Amazon SQS Developer Guide</i>. </p> <ul> <li> <p>Every * message must have a unique <code>MessageDeduplicationId</code>,</p> <ul> <li> * <p>You may provide a <code>MessageDeduplicationId</code> explicitly.</p> </li> * <li> <p>If you aren't able to provide a <code>MessageDeduplicationId</code> and * you enable <code>ContentBasedDeduplication</code> for your queue, Amazon SQS * uses a SHA-256 hash to generate the <code>MessageDeduplicationId</code> using * the body of the message (but not the attributes of the message). </p> </li> <li> * <p>If you don't provide a <code>MessageDeduplicationId</code> and the queue * doesn't have <code>ContentBasedDeduplication</code> set, the action fails with * an error.</p> </li> <li> <p>If the queue has * <code>ContentBasedDeduplication</code> set, your * <code>MessageDeduplicationId</code> overrides the generated one.</p> </li> </ul> * </li> <li> <p>When <code>ContentBasedDeduplication</code> is in effect, messages * with identical content sent within the deduplication interval are treated as * duplicates and only one copy of the message is delivered.</p> </li> <li> <p>You * can also use <code>ContentBasedDeduplication</code> for messages with identical * content to be treated as duplicates.</p> </li> <li> <p>If you send one message * with <code>ContentBasedDeduplication</code> enabled and then another message * with a <code>MessageDeduplicationId</code> that is the same as the one generated * for the first <code>MessageDeduplicationId</code>, the two messages are treated * as duplicates and only one copy of the message is delivered. </p> </li> </ul> * </li> </ul> <p>Any other valid special request parameters (such as the * following) are ignored:</p> <ul> <li> <p> * <code>ApproximateNumberOfMessages</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesDelayed</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesNotVisible</code> </p> </li> <li> <p> * <code>CreatedTimestamp</code> </p> </li> <li> <p> * <code>LastModifiedTimestamp</code> </p> </li> <li> <p> <code>QueueArn</code> * </p> </li> </ul> */ inline void SetAttributes(const Aws::Map<QueueAttributeName, Aws::String>& value) { m_attributesHasBeenSet = true; m_attributes = value; } /** * <p>A map of attributes to set.</p> <p>The following lists the names, * descriptions, and values of the special request parameters that the * <code>SetQueueAttributes</code> action uses:</p> <ul> <li> <p> * <code>DelaySeconds</code> - The number of seconds for which the delivery of all * messages in the queue is delayed. Valid values: An integer from 0 to 900 (15 * minutes). The default is 0 (zero). </p> </li> <li> <p> * <code>MaximumMessageSize</code> - The limit of how many bytes a message can * contain before Amazon SQS rejects it. Valid values: An integer from 1,024 bytes * (1 KiB) up to 262,144 bytes (256 KiB). The default is 262,144 (256 KiB). </p> * </li> <li> <p> <code>MessageRetentionPeriod</code> - The number of seconds for * which Amazon SQS retains a message. Valid values: An integer representing * seconds, from 60 (1 minute) to 1,209,600 (14 days). The default is 345,600 (4 * days). </p> </li> <li> <p> <code>Policy</code> - The queue's policy. A valid AWS * policy. For more information about policy structure, see <a * href="http://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html">Overview * of AWS IAM Policies</a> in the <i>Amazon IAM User Guide</i>. </p> </li> <li> <p> * <code>ReceiveMessageWaitTimeSeconds</code> - The number of seconds for which a * <code> <a>ReceiveMessage</a> </code> action waits for a message to arrive. Valid * values: an integer from 0 to 20 (seconds). The default is 0. </p> </li> <li> <p> * <code>RedrivePolicy</code> - The parameters for the dead letter queue * functionality of the source queue. For more information about the redrive policy * and dead letter queues, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html">Using * Amazon SQS Dead Letter Queues</a> in the <i>Amazon SQS Developer Guide</i>. </p> * <note> <p>The dead letter queue of a FIFO queue must also be a FIFO queue. * Similarly, the dead letter queue of a standard queue must also be a standard * queue.</p> </note> </li> <li> <p> <code>VisibilityTimeout</code> - The * visibility timeout for the queue. Valid values: an integer from 0 to 43,200 (12 * hours). The default is 30. For more information about the visibility timeout, * see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html">Visibility * Timeout</a> in the <i>Amazon SQS Developer Guide</i>.</p> </li> </ul> <p>The * following attribute applies only to <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html">FIFO * (first-in-first-out) queues</a>:</p> <ul> <li> <p> * <code>ContentBasedDeduplication</code> - Enables content-based deduplication. * For more information, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing">Exactly-Once * Processing</a> in the <i>Amazon SQS Developer Guide</i>. </p> <ul> <li> <p>Every * message must have a unique <code>MessageDeduplicationId</code>,</p> <ul> <li> * <p>You may provide a <code>MessageDeduplicationId</code> explicitly.</p> </li> * <li> <p>If you aren't able to provide a <code>MessageDeduplicationId</code> and * you enable <code>ContentBasedDeduplication</code> for your queue, Amazon SQS * uses a SHA-256 hash to generate the <code>MessageDeduplicationId</code> using * the body of the message (but not the attributes of the message). </p> </li> <li> * <p>If you don't provide a <code>MessageDeduplicationId</code> and the queue * doesn't have <code>ContentBasedDeduplication</code> set, the action fails with * an error.</p> </li> <li> <p>If the queue has * <code>ContentBasedDeduplication</code> set, your * <code>MessageDeduplicationId</code> overrides the generated one.</p> </li> </ul> * </li> <li> <p>When <code>ContentBasedDeduplication</code> is in effect, messages * with identical content sent within the deduplication interval are treated as * duplicates and only one copy of the message is delivered.</p> </li> <li> <p>You * can also use <code>ContentBasedDeduplication</code> for messages with identical * content to be treated as duplicates.</p> </li> <li> <p>If you send one message * with <code>ContentBasedDeduplication</code> enabled and then another message * with a <code>MessageDeduplicationId</code> that is the same as the one generated * for the first <code>MessageDeduplicationId</code>, the two messages are treated * as duplicates and only one copy of the message is delivered. </p> </li> </ul> * </li> </ul> <p>Any other valid special request parameters (such as the * following) are ignored:</p> <ul> <li> <p> * <code>ApproximateNumberOfMessages</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesDelayed</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesNotVisible</code> </p> </li> <li> <p> * <code>CreatedTimestamp</code> </p> </li> <li> <p> * <code>LastModifiedTimestamp</code> </p> </li> <li> <p> <code>QueueArn</code> * </p> </li> </ul> */ inline void SetAttributes(Aws::Map<QueueAttributeName, Aws::String>&& value) { m_attributesHasBeenSet = true; m_attributes = value; } /** * <p>A map of attributes to set.</p> <p>The following lists the names, * descriptions, and values of the special request parameters that the * <code>SetQueueAttributes</code> action uses:</p> <ul> <li> <p> * <code>DelaySeconds</code> - The number of seconds for which the delivery of all * messages in the queue is delayed. Valid values: An integer from 0 to 900 (15 * minutes). The default is 0 (zero). </p> </li> <li> <p> * <code>MaximumMessageSize</code> - The limit of how many bytes a message can * contain before Amazon SQS rejects it. Valid values: An integer from 1,024 bytes * (1 KiB) up to 262,144 bytes (256 KiB). The default is 262,144 (256 KiB). </p> * </li> <li> <p> <code>MessageRetentionPeriod</code> - The number of seconds for * which Amazon SQS retains a message. Valid values: An integer representing * seconds, from 60 (1 minute) to 1,209,600 (14 days). The default is 345,600 (4 * days). </p> </li> <li> <p> <code>Policy</code> - The queue's policy. A valid AWS * policy. For more information about policy structure, see <a * href="http://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html">Overview * of AWS IAM Policies</a> in the <i>Amazon IAM User Guide</i>. </p> </li> <li> <p> * <code>ReceiveMessageWaitTimeSeconds</code> - The number of seconds for which a * <code> <a>ReceiveMessage</a> </code> action waits for a message to arrive. Valid * values: an integer from 0 to 20 (seconds). The default is 0. </p> </li> <li> <p> * <code>RedrivePolicy</code> - The parameters for the dead letter queue * functionality of the source queue. For more information about the redrive policy * and dead letter queues, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html">Using * Amazon SQS Dead Letter Queues</a> in the <i>Amazon SQS Developer Guide</i>. </p> * <note> <p>The dead letter queue of a FIFO queue must also be a FIFO queue. * Similarly, the dead letter queue of a standard queue must also be a standard * queue.</p> </note> </li> <li> <p> <code>VisibilityTimeout</code> - The * visibility timeout for the queue. Valid values: an integer from 0 to 43,200 (12 * hours). The default is 30. For more information about the visibility timeout, * see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html">Visibility * Timeout</a> in the <i>Amazon SQS Developer Guide</i>.</p> </li> </ul> <p>The * following attribute applies only to <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html">FIFO * (first-in-first-out) queues</a>:</p> <ul> <li> <p> * <code>ContentBasedDeduplication</code> - Enables content-based deduplication. * For more information, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing">Exactly-Once * Processing</a> in the <i>Amazon SQS Developer Guide</i>. </p> <ul> <li> <p>Every * message must have a unique <code>MessageDeduplicationId</code>,</p> <ul> <li> * <p>You may provide a <code>MessageDeduplicationId</code> explicitly.</p> </li> * <li> <p>If you aren't able to provide a <code>MessageDeduplicationId</code> and * you enable <code>ContentBasedDeduplication</code> for your queue, Amazon SQS * uses a SHA-256 hash to generate the <code>MessageDeduplicationId</code> using * the body of the message (but not the attributes of the message). </p> </li> <li> * <p>If you don't provide a <code>MessageDeduplicationId</code> and the queue * doesn't have <code>ContentBasedDeduplication</code> set, the action fails with * an error.</p> </li> <li> <p>If the queue has * <code>ContentBasedDeduplication</code> set, your * <code>MessageDeduplicationId</code> overrides the generated one.</p> </li> </ul> * </li> <li> <p>When <code>ContentBasedDeduplication</code> is in effect, messages * with identical content sent within the deduplication interval are treated as * duplicates and only one copy of the message is delivered.</p> </li> <li> <p>You * can also use <code>ContentBasedDeduplication</code> for messages with identical * content to be treated as duplicates.</p> </li> <li> <p>If you send one message * with <code>ContentBasedDeduplication</code> enabled and then another message * with a <code>MessageDeduplicationId</code> that is the same as the one generated * for the first <code>MessageDeduplicationId</code>, the two messages are treated * as duplicates and only one copy of the message is delivered. </p> </li> </ul> * </li> </ul> <p>Any other valid special request parameters (such as the * following) are ignored:</p> <ul> <li> <p> * <code>ApproximateNumberOfMessages</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesDelayed</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesNotVisible</code> </p> </li> <li> <p> * <code>CreatedTimestamp</code> </p> </li> <li> <p> * <code>LastModifiedTimestamp</code> </p> </li> <li> <p> <code>QueueArn</code> * </p> </li> </ul> */ inline SetQueueAttributesRequest& WithAttributes(const Aws::Map<QueueAttributeName, Aws::String>& value) { SetAttributes(value); return *this;} /** * <p>A map of attributes to set.</p> <p>The following lists the names, * descriptions, and values of the special request parameters that the * <code>SetQueueAttributes</code> action uses:</p> <ul> <li> <p> * <code>DelaySeconds</code> - The number of seconds for which the delivery of all * messages in the queue is delayed. Valid values: An integer from 0 to 900 (15 * minutes). The default is 0 (zero). </p> </li> <li> <p> * <code>MaximumMessageSize</code> - The limit of how many bytes a message can * contain before Amazon SQS rejects it. Valid values: An integer from 1,024 bytes * (1 KiB) up to 262,144 bytes (256 KiB). The default is 262,144 (256 KiB). </p> * </li> <li> <p> <code>MessageRetentionPeriod</code> - The number of seconds for * which Amazon SQS retains a message. Valid values: An integer representing * seconds, from 60 (1 minute) to 1,209,600 (14 days). The default is 345,600 (4 * days). </p> </li> <li> <p> <code>Policy</code> - The queue's policy. A valid AWS * policy. For more information about policy structure, see <a * href="http://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html">Overview * of AWS IAM Policies</a> in the <i>Amazon IAM User Guide</i>. </p> </li> <li> <p> * <code>ReceiveMessageWaitTimeSeconds</code> - The number of seconds for which a * <code> <a>ReceiveMessage</a> </code> action waits for a message to arrive. Valid * values: an integer from 0 to 20 (seconds). The default is 0. </p> </li> <li> <p> * <code>RedrivePolicy</code> - The parameters for the dead letter queue * functionality of the source queue. For more information about the redrive policy * and dead letter queues, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html">Using * Amazon SQS Dead Letter Queues</a> in the <i>Amazon SQS Developer Guide</i>. </p> * <note> <p>The dead letter queue of a FIFO queue must also be a FIFO queue. * Similarly, the dead letter queue of a standard queue must also be a standard * queue.</p> </note> </li> <li> <p> <code>VisibilityTimeout</code> - The * visibility timeout for the queue. Valid values: an integer from 0 to 43,200 (12 * hours). The default is 30. For more information about the visibility timeout, * see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html">Visibility * Timeout</a> in the <i>Amazon SQS Developer Guide</i>.</p> </li> </ul> <p>The * following attribute applies only to <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html">FIFO * (first-in-first-out) queues</a>:</p> <ul> <li> <p> * <code>ContentBasedDeduplication</code> - Enables content-based deduplication. * For more information, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing">Exactly-Once * Processing</a> in the <i>Amazon SQS Developer Guide</i>. </p> <ul> <li> <p>Every * message must have a unique <code>MessageDeduplicationId</code>,</p> <ul> <li> * <p>You may provide a <code>MessageDeduplicationId</code> explicitly.</p> </li> * <li> <p>If you aren't able to provide a <code>MessageDeduplicationId</code> and * you enable <code>ContentBasedDeduplication</code> for your queue, Amazon SQS * uses a SHA-256 hash to generate the <code>MessageDeduplicationId</code> using * the body of the message (but not the attributes of the message). </p> </li> <li> * <p>If you don't provide a <code>MessageDeduplicationId</code> and the queue * doesn't have <code>ContentBasedDeduplication</code> set, the action fails with * an error.</p> </li> <li> <p>If the queue has * <code>ContentBasedDeduplication</code> set, your * <code>MessageDeduplicationId</code> overrides the generated one.</p> </li> </ul> * </li> <li> <p>When <code>ContentBasedDeduplication</code> is in effect, messages * with identical content sent within the deduplication interval are treated as * duplicates and only one copy of the message is delivered.</p> </li> <li> <p>You * can also use <code>ContentBasedDeduplication</code> for messages with identical * content to be treated as duplicates.</p> </li> <li> <p>If you send one message * with <code>ContentBasedDeduplication</code> enabled and then another message * with a <code>MessageDeduplicationId</code> that is the same as the one generated * for the first <code>MessageDeduplicationId</code>, the two messages are treated * as duplicates and only one copy of the message is delivered. </p> </li> </ul> * </li> </ul> <p>Any other valid special request parameters (such as the * following) are ignored:</p> <ul> <li> <p> * <code>ApproximateNumberOfMessages</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesDelayed</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesNotVisible</code> </p> </li> <li> <p> * <code>CreatedTimestamp</code> </p> </li> <li> <p> * <code>LastModifiedTimestamp</code> </p> </li> <li> <p> <code>QueueArn</code> * </p> </li> </ul> */ inline SetQueueAttributesRequest& WithAttributes(Aws::Map<QueueAttributeName, Aws::String>&& value) { SetAttributes(value); return *this;} /** * <p>A map of attributes to set.</p> <p>The following lists the names, * descriptions, and values of the special request parameters that the * <code>SetQueueAttributes</code> action uses:</p> <ul> <li> <p> * <code>DelaySeconds</code> - The number of seconds for which the delivery of all * messages in the queue is delayed. Valid values: An integer from 0 to 900 (15 * minutes). The default is 0 (zero). </p> </li> <li> <p> * <code>MaximumMessageSize</code> - The limit of how many bytes a message can * contain before Amazon SQS rejects it. Valid values: An integer from 1,024 bytes * (1 KiB) up to 262,144 bytes (256 KiB). The default is 262,144 (256 KiB). </p> * </li> <li> <p> <code>MessageRetentionPeriod</code> - The number of seconds for * which Amazon SQS retains a message. Valid values: An integer representing * seconds, from 60 (1 minute) to 1,209,600 (14 days). The default is 345,600 (4 * days). </p> </li> <li> <p> <code>Policy</code> - The queue's policy. A valid AWS * policy. For more information about policy structure, see <a * href="http://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html">Overview * of AWS IAM Policies</a> in the <i>Amazon IAM User Guide</i>. </p> </li> <li> <p> * <code>ReceiveMessageWaitTimeSeconds</code> - The number of seconds for which a * <code> <a>ReceiveMessage</a> </code> action waits for a message to arrive. Valid * values: an integer from 0 to 20 (seconds). The default is 0. </p> </li> <li> <p> * <code>RedrivePolicy</code> - The parameters for the dead letter queue * functionality of the source queue. For more information about the redrive policy * and dead letter queues, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html">Using * Amazon SQS Dead Letter Queues</a> in the <i>Amazon SQS Developer Guide</i>. </p> * <note> <p>The dead letter queue of a FIFO queue must also be a FIFO queue. * Similarly, the dead letter queue of a standard queue must also be a standard * queue.</p> </note> </li> <li> <p> <code>VisibilityTimeout</code> - The * visibility timeout for the queue. Valid values: an integer from 0 to 43,200 (12 * hours). The default is 30. For more information about the visibility timeout, * see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html">Visibility * Timeout</a> in the <i>Amazon SQS Developer Guide</i>.</p> </li> </ul> <p>The * following attribute applies only to <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html">FIFO * (first-in-first-out) queues</a>:</p> <ul> <li> <p> * <code>ContentBasedDeduplication</code> - Enables content-based deduplication. * For more information, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing">Exactly-Once * Processing</a> in the <i>Amazon SQS Developer Guide</i>. </p> <ul> <li> <p>Every * message must have a unique <code>MessageDeduplicationId</code>,</p> <ul> <li> * <p>You may provide a <code>MessageDeduplicationId</code> explicitly.</p> </li> * <li> <p>If you aren't able to provide a <code>MessageDeduplicationId</code> and * you enable <code>ContentBasedDeduplication</code> for your queue, Amazon SQS * uses a SHA-256 hash to generate the <code>MessageDeduplicationId</code> using * the body of the message (but not the attributes of the message). </p> </li> <li> * <p>If you don't provide a <code>MessageDeduplicationId</code> and the queue * doesn't have <code>ContentBasedDeduplication</code> set, the action fails with * an error.</p> </li> <li> <p>If the queue has * <code>ContentBasedDeduplication</code> set, your * <code>MessageDeduplicationId</code> overrides the generated one.</p> </li> </ul> * </li> <li> <p>When <code>ContentBasedDeduplication</code> is in effect, messages * with identical content sent within the deduplication interval are treated as * duplicates and only one copy of the message is delivered.</p> </li> <li> <p>You * can also use <code>ContentBasedDeduplication</code> for messages with identical * content to be treated as duplicates.</p> </li> <li> <p>If you send one message * with <code>ContentBasedDeduplication</code> enabled and then another message * with a <code>MessageDeduplicationId</code> that is the same as the one generated * for the first <code>MessageDeduplicationId</code>, the two messages are treated * as duplicates and only one copy of the message is delivered. </p> </li> </ul> * </li> </ul> <p>Any other valid special request parameters (such as the * following) are ignored:</p> <ul> <li> <p> * <code>ApproximateNumberOfMessages</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesDelayed</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesNotVisible</code> </p> </li> <li> <p> * <code>CreatedTimestamp</code> </p> </li> <li> <p> * <code>LastModifiedTimestamp</code> </p> </li> <li> <p> <code>QueueArn</code> * </p> </li> </ul> */ inline SetQueueAttributesRequest& AddAttributes(const QueueAttributeName& key, const Aws::String& value) { m_attributesHasBeenSet = true; m_attributes[key] = value; return *this; } /** * <p>A map of attributes to set.</p> <p>The following lists the names, * descriptions, and values of the special request parameters that the * <code>SetQueueAttributes</code> action uses:</p> <ul> <li> <p> * <code>DelaySeconds</code> - The number of seconds for which the delivery of all * messages in the queue is delayed. Valid values: An integer from 0 to 900 (15 * minutes). The default is 0 (zero). </p> </li> <li> <p> * <code>MaximumMessageSize</code> - The limit of how many bytes a message can * contain before Amazon SQS rejects it. Valid values: An integer from 1,024 bytes * (1 KiB) up to 262,144 bytes (256 KiB). The default is 262,144 (256 KiB). </p> * </li> <li> <p> <code>MessageRetentionPeriod</code> - The number of seconds for * which Amazon SQS retains a message. Valid values: An integer representing * seconds, from 60 (1 minute) to 1,209,600 (14 days). The default is 345,600 (4 * days). </p> </li> <li> <p> <code>Policy</code> - The queue's policy. A valid AWS * policy. For more information about policy structure, see <a * href="http://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html">Overview * of AWS IAM Policies</a> in the <i>Amazon IAM User Guide</i>. </p> </li> <li> <p> * <code>ReceiveMessageWaitTimeSeconds</code> - The number of seconds for which a * <code> <a>ReceiveMessage</a> </code> action waits for a message to arrive. Valid * values: an integer from 0 to 20 (seconds). The default is 0. </p> </li> <li> <p> * <code>RedrivePolicy</code> - The parameters for the dead letter queue * functionality of the source queue. For more information about the redrive policy * and dead letter queues, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html">Using * Amazon SQS Dead Letter Queues</a> in the <i>Amazon SQS Developer Guide</i>. </p> * <note> <p>The dead letter queue of a FIFO queue must also be a FIFO queue. * Similarly, the dead letter queue of a standard queue must also be a standard * queue.</p> </note> </li> <li> <p> <code>VisibilityTimeout</code> - The * visibility timeout for the queue. Valid values: an integer from 0 to 43,200 (12 * hours). The default is 30. For more information about the visibility timeout, * see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html">Visibility * Timeout</a> in the <i>Amazon SQS Developer Guide</i>.</p> </li> </ul> <p>The * following attribute applies only to <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html">FIFO * (first-in-first-out) queues</a>:</p> <ul> <li> <p> * <code>ContentBasedDeduplication</code> - Enables content-based deduplication. * For more information, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing">Exactly-Once * Processing</a> in the <i>Amazon SQS Developer Guide</i>. </p> <ul> <li> <p>Every * message must have a unique <code>MessageDeduplicationId</code>,</p> <ul> <li> * <p>You may provide a <code>MessageDeduplicationId</code> explicitly.</p> </li> * <li> <p>If you aren't able to provide a <code>MessageDeduplicationId</code> and * you enable <code>ContentBasedDeduplication</code> for your queue, Amazon SQS * uses a SHA-256 hash to generate the <code>MessageDeduplicationId</code> using * the body of the message (but not the attributes of the message). </p> </li> <li> * <p>If you don't provide a <code>MessageDeduplicationId</code> and the queue * doesn't have <code>ContentBasedDeduplication</code> set, the action fails with * an error.</p> </li> <li> <p>If the queue has * <code>ContentBasedDeduplication</code> set, your * <code>MessageDeduplicationId</code> overrides the generated one.</p> </li> </ul> * </li> <li> <p>When <code>ContentBasedDeduplication</code> is in effect, messages * with identical content sent within the deduplication interval are treated as * duplicates and only one copy of the message is delivered.</p> </li> <li> <p>You * can also use <code>ContentBasedDeduplication</code> for messages with identical * content to be treated as duplicates.</p> </li> <li> <p>If you send one message * with <code>ContentBasedDeduplication</code> enabled and then another message * with a <code>MessageDeduplicationId</code> that is the same as the one generated * for the first <code>MessageDeduplicationId</code>, the two messages are treated * as duplicates and only one copy of the message is delivered. </p> </li> </ul> * </li> </ul> <p>Any other valid special request parameters (such as the * following) are ignored:</p> <ul> <li> <p> * <code>ApproximateNumberOfMessages</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesDelayed</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesNotVisible</code> </p> </li> <li> <p> * <code>CreatedTimestamp</code> </p> </li> <li> <p> * <code>LastModifiedTimestamp</code> </p> </li> <li> <p> <code>QueueArn</code> * </p> </li> </ul> */ inline SetQueueAttributesRequest& AddAttributes(QueueAttributeName&& key, const Aws::String& value) { m_attributesHasBeenSet = true; m_attributes[key] = value; return *this; } /** * <p>A map of attributes to set.</p> <p>The following lists the names, * descriptions, and values of the special request parameters that the * <code>SetQueueAttributes</code> action uses:</p> <ul> <li> <p> * <code>DelaySeconds</code> - The number of seconds for which the delivery of all * messages in the queue is delayed. Valid values: An integer from 0 to 900 (15 * minutes). The default is 0 (zero). </p> </li> <li> <p> * <code>MaximumMessageSize</code> - The limit of how many bytes a message can * contain before Amazon SQS rejects it. Valid values: An integer from 1,024 bytes * (1 KiB) up to 262,144 bytes (256 KiB). The default is 262,144 (256 KiB). </p> * </li> <li> <p> <code>MessageRetentionPeriod</code> - The number of seconds for * which Amazon SQS retains a message. Valid values: An integer representing * seconds, from 60 (1 minute) to 1,209,600 (14 days). The default is 345,600 (4 * days). </p> </li> <li> <p> <code>Policy</code> - The queue's policy. A valid AWS * policy. For more information about policy structure, see <a * href="http://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html">Overview * of AWS IAM Policies</a> in the <i>Amazon IAM User Guide</i>. </p> </li> <li> <p> * <code>ReceiveMessageWaitTimeSeconds</code> - The number of seconds for which a * <code> <a>ReceiveMessage</a> </code> action waits for a message to arrive. Valid * values: an integer from 0 to 20 (seconds). The default is 0. </p> </li> <li> <p> * <code>RedrivePolicy</code> - The parameters for the dead letter queue * functionality of the source queue. For more information about the redrive policy * and dead letter queues, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html">Using * Amazon SQS Dead Letter Queues</a> in the <i>Amazon SQS Developer Guide</i>. </p> * <note> <p>The dead letter queue of a FIFO queue must also be a FIFO queue. * Similarly, the dead letter queue of a standard queue must also be a standard * queue.</p> </note> </li> <li> <p> <code>VisibilityTimeout</code> - The * visibility timeout for the queue. Valid values: an integer from 0 to 43,200 (12 * hours). The default is 30. For more information about the visibility timeout, * see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html">Visibility * Timeout</a> in the <i>Amazon SQS Developer Guide</i>.</p> </li> </ul> <p>The * following attribute applies only to <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html">FIFO * (first-in-first-out) queues</a>:</p> <ul> <li> <p> * <code>ContentBasedDeduplication</code> - Enables content-based deduplication. * For more information, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing">Exactly-Once * Processing</a> in the <i>Amazon SQS Developer Guide</i>. </p> <ul> <li> <p>Every * message must have a unique <code>MessageDeduplicationId</code>,</p> <ul> <li> * <p>You may provide a <code>MessageDeduplicationId</code> explicitly.</p> </li> * <li> <p>If you aren't able to provide a <code>MessageDeduplicationId</code> and * you enable <code>ContentBasedDeduplication</code> for your queue, Amazon SQS * uses a SHA-256 hash to generate the <code>MessageDeduplicationId</code> using * the body of the message (but not the attributes of the message). </p> </li> <li> * <p>If you don't provide a <code>MessageDeduplicationId</code> and the queue * doesn't have <code>ContentBasedDeduplication</code> set, the action fails with * an error.</p> </li> <li> <p>If the queue has * <code>ContentBasedDeduplication</code> set, your * <code>MessageDeduplicationId</code> overrides the generated one.</p> </li> </ul> * </li> <li> <p>When <code>ContentBasedDeduplication</code> is in effect, messages * with identical content sent within the deduplication interval are treated as * duplicates and only one copy of the message is delivered.</p> </li> <li> <p>You * can also use <code>ContentBasedDeduplication</code> for messages with identical * content to be treated as duplicates.</p> </li> <li> <p>If you send one message * with <code>ContentBasedDeduplication</code> enabled and then another message * with a <code>MessageDeduplicationId</code> that is the same as the one generated * for the first <code>MessageDeduplicationId</code>, the two messages are treated * as duplicates and only one copy of the message is delivered. </p> </li> </ul> * </li> </ul> <p>Any other valid special request parameters (such as the * following) are ignored:</p> <ul> <li> <p> * <code>ApproximateNumberOfMessages</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesDelayed</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesNotVisible</code> </p> </li> <li> <p> * <code>CreatedTimestamp</code> </p> </li> <li> <p> * <code>LastModifiedTimestamp</code> </p> </li> <li> <p> <code>QueueArn</code> * </p> </li> </ul> */ inline SetQueueAttributesRequest& AddAttributes(const QueueAttributeName& key, Aws::String&& value) { m_attributesHasBeenSet = true; m_attributes[key] = value; return *this; } /** * <p>A map of attributes to set.</p> <p>The following lists the names, * descriptions, and values of the special request parameters that the * <code>SetQueueAttributes</code> action uses:</p> <ul> <li> <p> * <code>DelaySeconds</code> - The number of seconds for which the delivery of all * messages in the queue is delayed. Valid values: An integer from 0 to 900 (15 * minutes). The default is 0 (zero). </p> </li> <li> <p> * <code>MaximumMessageSize</code> - The limit of how many bytes a message can * contain before Amazon SQS rejects it. Valid values: An integer from 1,024 bytes * (1 KiB) up to 262,144 bytes (256 KiB). The default is 262,144 (256 KiB). </p> * </li> <li> <p> <code>MessageRetentionPeriod</code> - The number of seconds for * which Amazon SQS retains a message. Valid values: An integer representing * seconds, from 60 (1 minute) to 1,209,600 (14 days). The default is 345,600 (4 * days). </p> </li> <li> <p> <code>Policy</code> - The queue's policy. A valid AWS * policy. For more information about policy structure, see <a * href="http://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html">Overview * of AWS IAM Policies</a> in the <i>Amazon IAM User Guide</i>. </p> </li> <li> <p> * <code>ReceiveMessageWaitTimeSeconds</code> - The number of seconds for which a * <code> <a>ReceiveMessage</a> </code> action waits for a message to arrive. Valid * values: an integer from 0 to 20 (seconds). The default is 0. </p> </li> <li> <p> * <code>RedrivePolicy</code> - The parameters for the dead letter queue * functionality of the source queue. For more information about the redrive policy * and dead letter queues, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html">Using * Amazon SQS Dead Letter Queues</a> in the <i>Amazon SQS Developer Guide</i>. </p> * <note> <p>The dead letter queue of a FIFO queue must also be a FIFO queue. * Similarly, the dead letter queue of a standard queue must also be a standard * queue.</p> </note> </li> <li> <p> <code>VisibilityTimeout</code> - The * visibility timeout for the queue. Valid values: an integer from 0 to 43,200 (12 * hours). The default is 30. For more information about the visibility timeout, * see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html">Visibility * Timeout</a> in the <i>Amazon SQS Developer Guide</i>.</p> </li> </ul> <p>The * following attribute applies only to <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html">FIFO * (first-in-first-out) queues</a>:</p> <ul> <li> <p> * <code>ContentBasedDeduplication</code> - Enables content-based deduplication. * For more information, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing">Exactly-Once * Processing</a> in the <i>Amazon SQS Developer Guide</i>. </p> <ul> <li> <p>Every * message must have a unique <code>MessageDeduplicationId</code>,</p> <ul> <li> * <p>You may provide a <code>MessageDeduplicationId</code> explicitly.</p> </li> * <li> <p>If you aren't able to provide a <code>MessageDeduplicationId</code> and * you enable <code>ContentBasedDeduplication</code> for your queue, Amazon SQS * uses a SHA-256 hash to generate the <code>MessageDeduplicationId</code> using * the body of the message (but not the attributes of the message). </p> </li> <li> * <p>If you don't provide a <code>MessageDeduplicationId</code> and the queue * doesn't have <code>ContentBasedDeduplication</code> set, the action fails with * an error.</p> </li> <li> <p>If the queue has * <code>ContentBasedDeduplication</code> set, your * <code>MessageDeduplicationId</code> overrides the generated one.</p> </li> </ul> * </li> <li> <p>When <code>ContentBasedDeduplication</code> is in effect, messages * with identical content sent within the deduplication interval are treated as * duplicates and only one copy of the message is delivered.</p> </li> <li> <p>You * can also use <code>ContentBasedDeduplication</code> for messages with identical * content to be treated as duplicates.</p> </li> <li> <p>If you send one message * with <code>ContentBasedDeduplication</code> enabled and then another message * with a <code>MessageDeduplicationId</code> that is the same as the one generated * for the first <code>MessageDeduplicationId</code>, the two messages are treated * as duplicates and only one copy of the message is delivered. </p> </li> </ul> * </li> </ul> <p>Any other valid special request parameters (such as the * following) are ignored:</p> <ul> <li> <p> * <code>ApproximateNumberOfMessages</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesDelayed</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesNotVisible</code> </p> </li> <li> <p> * <code>CreatedTimestamp</code> </p> </li> <li> <p> * <code>LastModifiedTimestamp</code> </p> </li> <li> <p> <code>QueueArn</code> * </p> </li> </ul> */ inline SetQueueAttributesRequest& AddAttributes(QueueAttributeName&& key, Aws::String&& value) { m_attributesHasBeenSet = true; m_attributes[key] = value; return *this; } /** * <p>A map of attributes to set.</p> <p>The following lists the names, * descriptions, and values of the special request parameters that the * <code>SetQueueAttributes</code> action uses:</p> <ul> <li> <p> * <code>DelaySeconds</code> - The number of seconds for which the delivery of all * messages in the queue is delayed. Valid values: An integer from 0 to 900 (15 * minutes). The default is 0 (zero). </p> </li> <li> <p> * <code>MaximumMessageSize</code> - The limit of how many bytes a message can * contain before Amazon SQS rejects it. Valid values: An integer from 1,024 bytes * (1 KiB) up to 262,144 bytes (256 KiB). The default is 262,144 (256 KiB). </p> * </li> <li> <p> <code>MessageRetentionPeriod</code> - The number of seconds for * which Amazon SQS retains a message. Valid values: An integer representing * seconds, from 60 (1 minute) to 1,209,600 (14 days). The default is 345,600 (4 * days). </p> </li> <li> <p> <code>Policy</code> - The queue's policy. A valid AWS * policy. For more information about policy structure, see <a * href="http://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html">Overview * of AWS IAM Policies</a> in the <i>Amazon IAM User Guide</i>. </p> </li> <li> <p> * <code>ReceiveMessageWaitTimeSeconds</code> - The number of seconds for which a * <code> <a>ReceiveMessage</a> </code> action waits for a message to arrive. Valid * values: an integer from 0 to 20 (seconds). The default is 0. </p> </li> <li> <p> * <code>RedrivePolicy</code> - The parameters for the dead letter queue * functionality of the source queue. For more information about the redrive policy * and dead letter queues, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html">Using * Amazon SQS Dead Letter Queues</a> in the <i>Amazon SQS Developer Guide</i>. </p> * <note> <p>The dead letter queue of a FIFO queue must also be a FIFO queue. * Similarly, the dead letter queue of a standard queue must also be a standard * queue.</p> </note> </li> <li> <p> <code>VisibilityTimeout</code> - The * visibility timeout for the queue. Valid values: an integer from 0 to 43,200 (12 * hours). The default is 30. For more information about the visibility timeout, * see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html">Visibility * Timeout</a> in the <i>Amazon SQS Developer Guide</i>.</p> </li> </ul> <p>The * following attribute applies only to <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html">FIFO * (first-in-first-out) queues</a>:</p> <ul> <li> <p> * <code>ContentBasedDeduplication</code> - Enables content-based deduplication. * For more information, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing">Exactly-Once * Processing</a> in the <i>Amazon SQS Developer Guide</i>. </p> <ul> <li> <p>Every * message must have a unique <code>MessageDeduplicationId</code>,</p> <ul> <li> * <p>You may provide a <code>MessageDeduplicationId</code> explicitly.</p> </li> * <li> <p>If you aren't able to provide a <code>MessageDeduplicationId</code> and * you enable <code>ContentBasedDeduplication</code> for your queue, Amazon SQS * uses a SHA-256 hash to generate the <code>MessageDeduplicationId</code> using * the body of the message (but not the attributes of the message). </p> </li> <li> * <p>If you don't provide a <code>MessageDeduplicationId</code> and the queue * doesn't have <code>ContentBasedDeduplication</code> set, the action fails with * an error.</p> </li> <li> <p>If the queue has * <code>ContentBasedDeduplication</code> set, your * <code>MessageDeduplicationId</code> overrides the generated one.</p> </li> </ul> * </li> <li> <p>When <code>ContentBasedDeduplication</code> is in effect, messages * with identical content sent within the deduplication interval are treated as * duplicates and only one copy of the message is delivered.</p> </li> <li> <p>You * can also use <code>ContentBasedDeduplication</code> for messages with identical * content to be treated as duplicates.</p> </li> <li> <p>If you send one message * with <code>ContentBasedDeduplication</code> enabled and then another message * with a <code>MessageDeduplicationId</code> that is the same as the one generated * for the first <code>MessageDeduplicationId</code>, the two messages are treated * as duplicates and only one copy of the message is delivered. </p> </li> </ul> * </li> </ul> <p>Any other valid special request parameters (such as the * following) are ignored:</p> <ul> <li> <p> * <code>ApproximateNumberOfMessages</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesDelayed</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesNotVisible</code> </p> </li> <li> <p> * <code>CreatedTimestamp</code> </p> </li> <li> <p> * <code>LastModifiedTimestamp</code> </p> </li> <li> <p> <code>QueueArn</code> * </p> </li> </ul> */ inline SetQueueAttributesRequest& AddAttributes(QueueAttributeName&& key, const char* value) { m_attributesHasBeenSet = true; m_attributes[key] = value; return *this; } /** * <p>A map of attributes to set.</p> <p>The following lists the names, * descriptions, and values of the special request parameters that the * <code>SetQueueAttributes</code> action uses:</p> <ul> <li> <p> * <code>DelaySeconds</code> - The number of seconds for which the delivery of all * messages in the queue is delayed. Valid values: An integer from 0 to 900 (15 * minutes). The default is 0 (zero). </p> </li> <li> <p> * <code>MaximumMessageSize</code> - The limit of how many bytes a message can * contain before Amazon SQS rejects it. Valid values: An integer from 1,024 bytes * (1 KiB) up to 262,144 bytes (256 KiB). The default is 262,144 (256 KiB). </p> * </li> <li> <p> <code>MessageRetentionPeriod</code> - The number of seconds for * which Amazon SQS retains a message. Valid values: An integer representing * seconds, from 60 (1 minute) to 1,209,600 (14 days). The default is 345,600 (4 * days). </p> </li> <li> <p> <code>Policy</code> - The queue's policy. A valid AWS * policy. For more information about policy structure, see <a * href="http://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html">Overview * of AWS IAM Policies</a> in the <i>Amazon IAM User Guide</i>. </p> </li> <li> <p> * <code>ReceiveMessageWaitTimeSeconds</code> - The number of seconds for which a * <code> <a>ReceiveMessage</a> </code> action waits for a message to arrive. Valid * values: an integer from 0 to 20 (seconds). The default is 0. </p> </li> <li> <p> * <code>RedrivePolicy</code> - The parameters for the dead letter queue * functionality of the source queue. For more information about the redrive policy * and dead letter queues, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html">Using * Amazon SQS Dead Letter Queues</a> in the <i>Amazon SQS Developer Guide</i>. </p> * <note> <p>The dead letter queue of a FIFO queue must also be a FIFO queue. * Similarly, the dead letter queue of a standard queue must also be a standard * queue.</p> </note> </li> <li> <p> <code>VisibilityTimeout</code> - The * visibility timeout for the queue. Valid values: an integer from 0 to 43,200 (12 * hours). The default is 30. For more information about the visibility timeout, * see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html">Visibility * Timeout</a> in the <i>Amazon SQS Developer Guide</i>.</p> </li> </ul> <p>The * following attribute applies only to <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html">FIFO * (first-in-first-out) queues</a>:</p> <ul> <li> <p> * <code>ContentBasedDeduplication</code> - Enables content-based deduplication. * For more information, see <a * href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing">Exactly-Once * Processing</a> in the <i>Amazon SQS Developer Guide</i>. </p> <ul> <li> <p>Every * message must have a unique <code>MessageDeduplicationId</code>,</p> <ul> <li> * <p>You may provide a <code>MessageDeduplicationId</code> explicitly.</p> </li> * <li> <p>If you aren't able to provide a <code>MessageDeduplicationId</code> and * you enable <code>ContentBasedDeduplication</code> for your queue, Amazon SQS * uses a SHA-256 hash to generate the <code>MessageDeduplicationId</code> using * the body of the message (but not the attributes of the message). </p> </li> <li> * <p>If you don't provide a <code>MessageDeduplicationId</code> and the queue * doesn't have <code>ContentBasedDeduplication</code> set, the action fails with * an error.</p> </li> <li> <p>If the queue has * <code>ContentBasedDeduplication</code> set, your * <code>MessageDeduplicationId</code> overrides the generated one.</p> </li> </ul> * </li> <li> <p>When <code>ContentBasedDeduplication</code> is in effect, messages * with identical content sent within the deduplication interval are treated as * duplicates and only one copy of the message is delivered.</p> </li> <li> <p>You * can also use <code>ContentBasedDeduplication</code> for messages with identical * content to be treated as duplicates.</p> </li> <li> <p>If you send one message * with <code>ContentBasedDeduplication</code> enabled and then another message * with a <code>MessageDeduplicationId</code> that is the same as the one generated * for the first <code>MessageDeduplicationId</code>, the two messages are treated * as duplicates and only one copy of the message is delivered. </p> </li> </ul> * </li> </ul> <p>Any other valid special request parameters (such as the * following) are ignored:</p> <ul> <li> <p> * <code>ApproximateNumberOfMessages</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesDelayed</code> </p> </li> <li> <p> * <code>ApproximateNumberOfMessagesNotVisible</code> </p> </li> <li> <p> * <code>CreatedTimestamp</code> </p> </li> <li> <p> * <code>LastModifiedTimestamp</code> </p> </li> <li> <p> <code>QueueArn</code> * </p> </li> </ul> */ inline SetQueueAttributesRequest& AddAttributes(const QueueAttributeName& key, const char* value) { m_attributesHasBeenSet = true; m_attributes[key] = value; return *this; } private: Aws::String m_queueUrl; bool m_queueUrlHasBeenSet; Aws::Map<QueueAttributeName, Aws::String> m_attributes; bool m_attributesHasBeenSet; }; } // namespace Model } // namespace SQS } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
8b9a8315c9d95d59b292c405818babcc853b8efb
ca3c87e77a1a13d66c28a7ddfd651fdefa225c4f
/Classes/Building_Sprite.cpp
d168ab288eb1e1a9b43d88f495ae0f33d479da14
[]
no_license
Anatoliuz/SpaceWarsX
255dbd14389e9e1d393892bdb8a122b77315a6d9
375b5ba5c0168c740d2aac4676310e4628d65725
refs/heads/master
2021-01-17T07:08:09.494800
2016-06-25T15:17:49
2016-06-25T15:17:49
53,348,512
1
1
null
null
null
null
UTF-8
C++
false
false
1,097
cpp
// // Building_Sprite.cpp // space // // Created by fix on 18/05/16. // // #include "Building_Sprite.hpp" using namespace cocos2d; Building_Sprite* Building_Sprite::create(){ Building_Sprite * sprite = new Building_Sprite(); if (sprite->initWithFile("building.png")) { sprite->autorelease(); sprite->initOptions(sprite); // sprite->addEvents(sprite); return sprite; } CC_SAFE_DELETE(sprite); return NULL; } void Building_Sprite::initOptions(Building_Sprite* building_sprite){ coordinate_X_Y coord; coord.x = 0; coord.y = 0; building *temp = new building(coord, 0, 0, 0);//!!! building_sprite->setScaleX(1.2*temp->get_width()/building_sprite->getContentSize().width); building_sprite->setScaleY(1.2*temp->get_height()/building_sprite->getContentSize().height); // building_sprite->setAnchorPoint(ccp(20,0)); delete temp; } void Building_Sprite::set_building_sprite(building* cur_unit){ building_in_sprite = cur_unit; } building* Building_Sprite::get_building_in_sprite(){ return building_in_sprite; }
[ "afilinovs@gmail.com" ]
afilinovs@gmail.com
3c8d01699bae7943eec6af58066fe614424a8fa1
30812e2d83952e5c96d3c24609944399d46f8b35
/作业6.27.0.cpp
558d88cf898d47d71ede8aed18ae22a41197536b
[]
no_license
xutong66/xu_tong
516cbf204757527370884fc391268d2b3845d38d
04afbc2bac04a31534b3f623ab05bec4cba83fd8
refs/heads/master
2020-04-28T03:19:02.831748
2019-08-09T06:07:50
2019-08-09T06:07:50
174,932,174
0
0
null
null
null
null
UTF-8
C++
false
false
504
cpp
#include<iostream> using namespace std; double smallest ( double,double,double ); int main () { double n1 = 0; double n2 = 0; double n3 = 0; cout << "Enter three numbers: "; cin >> n1 >> n2 >> n3; cout << "The smallest is: " << smallest ( n1, n2, n3 )<< endl; } double smallest ( double n1,double n2, double n3 ) { if ( n1 < n2 && n1 < n3) return n1; else if ( n2 < n1 && n2 < n3 ) return n2; else if ( n3 < n1 && n3 < n2 ) return n3; }
[ "2482780136@qq.com" ]
2482780136@qq.com
9b54891bdb6df3d895fbb7e8c51cfc2f55f89574
a167971a2957008a35028412b8557c11872b5e06
/MathLibrary/VecMatrix.h
a535783841a7d5153cde2927265a3f42e05c5ba3
[]
no_license
MaxGuidry/Intro_To_Programming
a4f26f975cf20c7f67b84cf892257d661b1b6bad
861de072aed82da692f5f6cffa2d24829044f617
refs/heads/master
2020-12-01T18:26:46.488601
2017-02-21T19:47:41
2017-02-21T19:47:41
66,005,250
0
0
null
null
null
null
UTF-8
C++
false
false
9,399
h
#pragma once #include<iostream> #include<time.h> #include<Windows.h> #include<fstream> class Vector2 { public: Vector2(); Vector2(float xx, float yy); //NAME: operator== //ARGUMENTS: one argument of a const 2d vector //DESCRIPTION: checks each value in the vector and returns true if they are equal and false if they are not bool operator == (const Vector2 &A); friend std::ostream& operator<<(std::ostream& os, const Vector2 vec); //NAME:operator + //ARGUMENTS: one argument of type const 2d vector //DESCRIPTION: adds the current vector to the one passed in and returns the result Vector2 operator +(const Vector2 &A); //NAME: operator - //ARGUMENTS: one argument of a const 3d vector //DESCRIPTION: subtracts each of the values in the vector and returns the result Vector2 operator -(const Vector2 &A); //NAME: operator * //ARGUMENTS: one argument of a float //DESCRIPTION: multiplies each value in the vector by a scalar value and returns the resultant vector Vector2 operator *(float Mult); //NAME: Magnitude //ARGUMENTS: no arguments //DESCRIPTION: returns the value that is the length of the vector float Magnitude(); //NAME: Normalize //ARGUMENTS: no arguments //DESCRIPTION: creates a temporary 3d vector and sets its values to the normalized values of the current vector by dividing each value by the magnitude Vector2 Normalize(); //NAME: DotProduct //ARGUMENTS: one arguments of const 3d vector //DESCRIPTION: returns the result of the dot product of the current vector and the vector passed in and returns the result float DotProduct(const Vector2 &A); float x, y; }; class Vector3 { public: //NAME: operator== //ARGUMENTS: one argument of a const 3d vector //DESCRIPTION: checks each value in the vector and returns true if they are equal and false if they are not bool operator==(const Vector3 &B); friend std::ostream& operator<<(std::ostream& os, const Vector3 vec); //NAME:operator + //ARGUMENTS: one argument of type const 3d vector //DESCRIPTION: adds the current vector to the one passed in and returns the result Vector3 operator +(const Vector3 &B); //NAME: operator - //ARGUMENTS: one argument of a const 3d vector //DESCRIPTION: subtracts each of the values in the vector and returns the result Vector3 operator -(const Vector3 &B); Vector3(); //constructor that takes in 3 float values for each part in the vector Vector3(float xpos, float ypos, float zpos); //NAME: operator * //ARGUMENTS: one argument of a float //DESCRIPTION: multiplies each value in the vector by a scalar value and returns the resultant vector Vector3 operator *(float Scalar); //NAME: Magnitude //ARGUMENTS: no arguments //DESCRIPTION: returns the value that is the length of the vector float Magnitude(); //NAME: Normalize //ARGUMENTS: no arguments //DESCRIPTION: creates a temporary 3d vector and sets its values to the normalized values of the current vector by dividing each value by the magnitude Vector3 Normalize(); //NAME: DotProduct //ARGUMENTS: one arguments of const 3d vector //DESCRIPTION: returns the result of the dot product of the current vector and the vector passed in and returns the result float DotProduct(const Vector3 &B); //NAME: CrossProduct //ARGUMENTS: one argument of type const 3d vector //DESCRIPTION: creates a new 3d vector whos values are given by the cross product of the current vector and the one passed in using the cross product formula Vector3 CrossProduct(const Vector3 &B); float VecArray[3]; float x, y, z; }; class Vector4 { public: Vector4(); //constructor that takes in 4 float values for each part in the vector Vector4(float xpos, float ypos, float zpos, float wpos); friend std::ostream& operator<<(std::ostream& os, const Vector4 vec); //NAME: operator * //ARGUMENTS: one argument of a float //DESCRIPTION: multiplies each value in the vector by a scalar value and returns the resultant vector Vector4 operator*(float scalar); //NAME: Magnitude //ARGUMENTS: no arguments //DESCRIPTION: returns the value that is the length of the vector float Magnitude(); //NAME: Normalize //ARGUMENTS: no arguments //DESCRIPTION: creates a temporary 4d vector and sets its values to the normalized values of the current vector by dividing each value by the magnitude Vector4 Normalize(); //NAME: DotProduct //ARGUMENTS: one arguments of const 4d vector //DESCRIPTION: returns the result of the dot product of the current vector and the vector passed in and returns the result float DotProduct(const Vector4 &B); //NAME:operator + //ARGUMENTS: one argument of type const 4d vector //DESCRIPTION: adds the current vector to the one passed in and returns the result Vector4 operator +(const Vector4 &B); //NAME: operator - //ARGUMENTS: one argument of a const 4d vector //DESCRIPTION: subtracts each of the values in the vector and returns the result Vector4 operator -(const Vector4 &B); //NAME: operator== //ARGUMENTS: one argument of a const 4d vector //DESCRIPTION: checks each value in the vector and returns true if they are equal and false if they are not bool operator==(const Vector4 &B); float VecArray[4]; float x, y, z, w; }; class Mat2 { public: Mat2(float a[2][2]); // Mat2(float a, float b, float c, float d); friend std::ostream& operator<<(std::ostream& os, const Mat2 mat); //NAME: print //ARGUMENTS: no arguments //DESCRIPTION: void print(); //NAME: operator * //ARGUMENTS: one argument of a const 2d vector //DESCRIPTION: multiplies the current matrix by the vector that is passed in and returns the result Vector2 operator *(const Vector2 &vec)const; //NAME: operator * //ARGUMENTS: one argument of a const 2x2 matrix //DESCRIPTION: multiplies current matrix by the passed in matrix and returns the result Mat2 operator *(const Mat2 &mat)const; private: float matrix[2][2]; }; class Mat3 { public: Mat3(); //constructor taking in an array and initializing the matrix Mat3(float a[3][3]); //constructor for 9 float values to initialize the matrix Mat3(float a, float b, float c, float d, float e, float f, float g, float h, float i); friend std::ostream& operator<<(std::ostream& os, const Mat3 mat); //NAME: print //ARGUMENTS: none //DESCRIPTION: loops through the matrix and prints the number at each index void print(); //NAME: operator * //ARGUMENTS: one argument of a 3x3 matrix //DESCRIPTION: creates matrix temp of all zeros then sets this temp equal to the two matrices multiplied together Vector3 operator *(const Vector3 &vec); //NAME: operator * //ARGUMENTS: one argument of a 3d vector //DESCRIPTION: creates a vector temp of all zeros then loops through the multiplication of the vector and matrix //setting the temp equal to the product and returns the temp vector Mat3 operator *(const Mat3 &mat); //NAME: setRotateX //ARGUMENTS: one argument of type float //DESCRIPTION: function for rotation around the X axis using the overloaded multiplication operators and returns //the current instance of the matrix Mat3 setRotateX(float angle); //NAME: setRotateY //ARGUMENTS: one argument of type float //DESCRIPTION: function for rotation around the Y axis using the overloaded multiplication operators and returns //the current instance of the matrix Mat3 setRotateY(float angle); //NAME: setRotateZ //ARGUMENTS: one argument of type float //DESCRIPTION: function for rotation around the Z axis using the overloaded multiplication operators and returns //the current instance of the matrix Mat3 setRotateZ(float angle); private: float matrix[3][3]; }; class Mat4 { public: //Two constructors //Constructor that takes in a 2x2 array to initialize the matrix Mat4(float a[4][4]); //Constructor that takes in 16 float values to initialize the matrix Mat4(float a, float b, float c, float d, float e, float f, float g, float h, float i, float j, float k, float l, float m, float n, float o, float p); friend std::ostream& operator<<(std::ostream& os, const Mat4 mat); void print(); //NAME: operator * //ARGUMENTS: one argument of a 4x4 matrix //DESCRIPTION: creates matrix temp of all zeros then sets this temp equal to the two matrices multiplied together Mat4 operator *(const Mat4 &mat) const; //NAME: operator * //ARGUMENTS: one argument of a 4d vector //DESCRIPTION: creates a vector temp of all zeros then loops through the multiplication of the vector and matrix //setting the temp equal to the product and returns the temp vector Vector4 operator *(const Vector4 &vec)const; //NAME: setRotateX //ARGUMENTS: one argument of type float //DESCRIPTION: function for rotation around the x axis using the overloaded multiplication operators and returns //the current instance of the matrix Mat4 setRotateX(float angle); //NAME: setRotateY //ARGUMENTS: one argument of type float //DESCRIPTION: function for rotation around the y axis using the overloaded multiplication operators and returns //the current instance of the matrix Mat4 setRotateY(float angle); //NAME: setRotateZ //ARGUMENTS: one arguments of type float //DESCRIPTION: function for rotation around the z axis using the overloaded multipication operators and returns //the current instance of the matrix Mat4 setRotateZ(float angle); private: float matrix[4][4]; };
[ "mguidry7@outlook.com" ]
mguidry7@outlook.com
909914258962a7d72434f06445102c75cced88bb
18c5ed1057dd6b4528adde132bb268af707e5083
/src/ATen/templates/TensorDerived.cpp
5977a834fe298eac7c025ab83ae594beaffa819d
[]
no_license
jgehring/ATen
9356d284d1353d3870dc0ba269e5664989cab541
574352a7e3e0c3d7e8babadbb11ff49f10ec4acd
refs/heads/master
2020-12-02T16:38:32.008369
2017-07-07T17:54:17
2017-07-07T17:54:17
96,564,049
0
0
null
2017-07-07T18:10:08
2017-07-07T18:10:08
null
UTF-8
C++
false
false
796
cpp
#include "ATen/${Tensor}.h" #include "ATen/Scalar.h" #include "ATen/Half.h" namespace at { ${Tensor}::${Tensor}(Context* context) : ${Tensor}(context,${THTensor}_new(${state})) {} ${Tensor}::${Tensor}(Context* context, ${THTensor} * tensor) : TensorImpl(&context->getType(Backend::${Backend},ScalarType::${ScalarName})), tensor(tensor), context(context) {} ${Tensor}::~${Tensor}() { ${THTensor}_free(${state,} tensor); } const char * ${Tensor}::toString() const { return "${Tensor}"; } IntList ${Tensor}::sizes() { return IntList(reinterpret_cast<int64_t*>(tensor->size),dim()); } int64_t ${Tensor}::dim() { if(isScalar()) return 0; return ${THTensor}_nDimension(${state,}tensor); } const char * ${Tensor}::typeString() { return "${Type}"; } ${TensorDenseOrSparse} }
[ "zdevito@fb.com" ]
zdevito@fb.com
76308fa66e6834bd66144671ba8e591b6fdc3643
0c7be72ca167c64ac7b46fa13932e384aaf3f21a
/ch1.LinearList/Reference_Linked_list.cpp
69709757b28c9edd255929ec2aa8a85c8ea08ada
[]
no_license
SilenceHS/algo_ds
cfdddeb20816b9550975c22c94199d99f2211311
79116cb56a5bb77e765d716ad52369cd6c6ccf4b
refs/heads/master
2020-07-07T15:22:44.639706
2019-08-28T14:58:30
2019-08-28T14:58:30
203,388,161
0
0
null
null
null
null
UTF-8
C++
false
false
815
cpp
#include <iostream> using namespace std; struct LinkList{ int data; LinkList * next; }; void show(LinkList* L); void delete2thNode(LinkList* &L); int main(){ LinkList* L= (LinkList*)malloc(sizeof(LinkList)); LinkList* pre=L; for(int i=0;i<4;i++) { LinkList* node= (LinkList*)malloc(sizeof(LinkList)); node->next=NULL; node->data=i*2; pre->next=node; pre=pre->next; } cout<<L<<endl; cout<<L->next<<endl; show(L); delete2thNode(L->next); show(L); } void show(LinkList* L) { LinkList * node=L->next; while(node) { cout<<node->data<<endl; node=node->next; } cout<<"......"<<endl; } void delete2thNode(LinkList* &L) { cout<<"**"<<L<<endl; cout<<L->data<<endl<<endl; L=L->next; }
[ "5724924@qq.com" ]
5724924@qq.com
cb7e931a8bfb18b4201c117a8091da458f07aab2
d3d5636ae069c3d31c6e1dfae964f4b9797d1f87
/C++_CN_Day16/C++_NC_Day16/完美数.cpp
59694f2601f42884d53c84bc1e30886670323bdf
[]
no_license
adong001/C-C-_NC_Day
1f83b1c609f2c9496ff787a0a98880a6cdad4c1d
3351588293823c2507a4cef128967a07b80969ed
refs/heads/master
2021-07-11T00:56:07.846956
2020-09-13T05:14:56
2020-09-13T05:14:56
191,345,716
1
0
null
null
null
null
UTF-8
C++
false
false
542
cpp
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> #include<cmath> using namespace std; int PerfectNum(int num) { int count = 0; int i, j; for (i = 1; i <= num; i++) { int sum = 0; for (j = 1; j <= sqrt(i); j++) { if (i%j == 0) { sum += j; if (j != i / j) { sum += i / j; } } } sum -= i; if (sum == i) { count++; } } if (count > 0) { return count; } return -1; } int main1() { int num; while (cin >> num) { cout << PerfectNum(num) << endl; } system("pause"); return 0; }
[ "1792095378@qq.com" ]
1792095378@qq.com
a25ca22d31a504574a11b798159c32c641832e36
897ef84932251c57a790b75b1410a147b9b64792
/midieffecteditor.cpp
32e542f6b175b5ff37b6f58ef9b16dbbcf57b083
[]
no_license
erophames/CamX
a92b789d758e514d43e6fd676dbb9eed1b7b3468
56b08ed02d976621f538feca10e1aaa58926aa5a
refs/heads/master
2021-06-21T21:14:27.776691
2017-07-22T11:46:09
2017-07-22T11:46:09
98,467,657
1
2
null
null
null
null
UTF-8
C++
false
false
48
cpp
#include "songmain.h" #include "MIDIeffects.h"
[ "matthieu.brucher@gmail.com" ]
matthieu.brucher@gmail.com
fbbea912d6b38967f66d3c3b01240532fa81cf86
a283103cbcdca66bd251a4ef03381e85fcf9611e
/Algorithms/Project2/11631.cpp
ec3f0881a2ffdb6840dde809f1bb1a9bfd0655c7
[]
no_license
Alybaev/MathTasks
98691a0fed5c6c1ef94d6722fe5f8a4087bc70e5
c0eeaa377d38ef75f13a05045c9aed5f700c89e0
refs/heads/master
2020-05-02T04:21:41.563993
2019-05-14T08:12:59
2019-05-14T08:12:59
177,747,431
0
0
null
null
null
null
UTF-8
C++
false
false
1,169
cpp
#include <bits/stdc++.h> using namespace std; struct Edge { int u; int w; Edge(int aU,int aW) :u(aU),w(aW) { } }; int main() { iostream::sync_with_stdio(false); int n,m; while(cin >> n >> m and (n != 0 or m != 0)) { int total = 0; std::vector<std::vector<Edge>> g(n); for(int k = 0; k < m;k++) { int v,u,w;cin >> v >> u >> w; total += w; g[v].emplace_back(u,w); g[u].emplace_back(v,w); } std::vector<int> d(n,-1); std::vector<int> vis(n, false); int minSum = 0; std::vector<pair<int,int>> pq; vis[0] = true; d[0] = 0; auto cmp = greater<pair<int,int>>(); for (auto& e: g[0]) { d[e.u] = e.w; pq.emplace_back(d[e.u], e.u); push_heap(begin(pq),end(pq), cmp); } while(!pq.empty()) { int v = pq.front().second; pq.pop_back(); pop_heap(begin(pq),end(pq), cmp); if(vis[v])continue; vis[v] = true; minSum += d[v]; for(auto& e: g[v]) { if(!vis[e.u] and (d[e.u] == -1 or e.w < d[e.u])) { d[e.u] = e.w; pq.emplace_back(d[e.u], e.u); push_heap(begin(pq),end(pq), cmp); } } } cout << total - minSum << "\n"; } }
[ "alybaev_d@auca.kg" ]
alybaev_d@auca.kg
b1625138ccbef71bd3c5c55d228f3f22a7c0760a
42b69b6ee94412955bff05072f521cbfaf64686e
/src/gui/MessagesFrame.h
ea075b4f6f89809ee4b15918a20f0f77fc1c35ed
[ "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
Aluisyo/conceal-wallet
66cb1c9d5234cd6620951fed69797216e35d6782
8019ca9d630e0e16052d20d24a73001eca471296
refs/heads/master
2020-04-29T11:31:46.948957
2019-03-12T10:32:13
2019-03-12T10:32:13
176,101,941
0
0
MIT
2019-03-17T13:03:02
2019-03-17T13:03:02
null
UTF-8
C++
false
false
992
h
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2018 The Circle Foundation // // Copyright (c) 2018 The Circle Foundation // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include <QFrame> namespace Ui { class MessagesFrame; } namespace WalletGui { class VisibleMessagesModel; class MessagesFrame : public QFrame { Q_OBJECT public: MessagesFrame(QWidget* _parent); ~MessagesFrame(); int test; private: QScopedPointer<Ui::MessagesFrame> m_ui; QScopedPointer<VisibleMessagesModel> m_visibleMessagesModel; void currentMessageChanged(const QModelIndex& _currentIndex); Q_SLOT void messageDoubleClicked(const QModelIndex& _index); Q_SLOT void replyClicked(); Q_SLOT void backClicked(); Q_SLOT void newMessageClicked(); Q_SIGNALS: void backSignal(); void newMessageSignal(); void replyToSignal(const QModelIndex& _index); }; }
[ "kahthan@gmail.com" ]
kahthan@gmail.com
305692b0bc873702e19ca442ab258d85b9e8a6a4
f9ebe7a39f065eb9f2b23dfb5fabab5dfc385580
/libs-carto/vt/src/vt/BitmapManager.h
9bf7a2e4ac206f225c6302ded7eb75de5e92090b
[ "BSD-3-Clause" ]
permissive
giserfly/mobile-sdk
b94f771a3723eb594c4469fffa54a47ee02a4337
7997616230901ccc0864f47e1079e86cd212ce39
refs/heads/master
2021-01-01T15:37:53.424250
2017-07-05T13:30:13
2017-07-05T13:30:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,844
h
/* * Copyright (c) 2016 CartoDB. All rights reserved. * Copying and using this code is allowed only according * to license terms, as given in https://cartodb.com/terms/ */ #ifndef _CARTO_VT_BITMAPMANAGER_H_ #define _CARTO_VT_BITMAPMANAGER_H_ #include "Bitmap.h" #include <memory> #include <string> #include <map> #include <mutex> namespace carto { namespace vt { class BitmapManager { public: class BitmapLoader { public: virtual ~BitmapLoader() = default; virtual std::shared_ptr<Bitmap> load(const std::string& fileName) const = 0; }; explicit BitmapManager(const std::shared_ptr<BitmapLoader>& loader); virtual ~BitmapManager() = default; std::shared_ptr<const Bitmap> getBitmap(const std::string& fileName) const; std::shared_ptr<const Bitmap> loadBitmap(const std::string& fileName); void storeBitmap(const std::string& fileName, const std::shared_ptr<const Bitmap>& bitmap); std::shared_ptr<const BitmapPattern> getBitmapPattern(const std::string& fileName) const; std::shared_ptr<const BitmapPattern> loadBitmapPattern(const std::string& fileName, float widthScale, float heightScale); void storeBitmapPattern(const std::string& fileName, const std::shared_ptr<const BitmapPattern>& bitmapPattern); static std::shared_ptr<const Bitmap> scale(const std::shared_ptr<const Bitmap>& bitmap, int width, int height); static std::shared_ptr<const Bitmap> scaleToPOT(const std::shared_ptr<const Bitmap>& bitmap); protected: std::shared_ptr<BitmapLoader> _bitmapLoader; std::map<std::string, std::shared_ptr<const Bitmap>> _bitmapMap; std::map<std::string, std::shared_ptr<const BitmapPattern>> _bitmapPatternMap; mutable std::mutex _mutex; }; } } #endif
[ "mark@nutiteq.ee" ]
mark@nutiteq.ee
e736ee3304ef1315f8893c67a69acc868661cb1d
ef13f111f5988ebdcad3b569ff805bb9e8146025
/5796_Tai_Game/map.cpp
a487023edbe372acaca91debefa284b2196b1e36
[]
no_license
Tai1412/Basic_Game_Engine
2e653d2a32264d5b098e86eb28bd7a22e0a38482
f7ac0bdbab39d41e9529748da378bf4c6e727a4a
refs/heads/master
2020-05-18T22:26:14.304551
2019-06-20T21:59:12
2019-06-20T21:59:12
184,690,029
0
0
null
null
null
null
UTF-8
C++
false
false
1,817
cpp
#include "map.h" void Map::loadMyMap(char* mapName) { gameMap.maxX = 0;//start count from cell 0 gameMap.maxY = 0; FILE* file = NULL; //read file fopen_s(&file, mapName, "rb");//read mode rb if (file == NULL)//check file { return; } for (int i = 0; i < maxMapY; i++)//<10 rows { for (int j = 0; j < maxMapX; j++) { fscanf_s(file, "%d", &gameMap.tile[i][j]); if (gameMap.tile[i][j] > 0)//take until last elements { if (j > gameMap.maxX) { gameMap.maxX = j; } if (i > gameMap.maxY) { gameMap.maxY = i; } } } } gameMap.maxX = (gameMap.maxX + 1)*tileSize; // 25600=>400x64 gameMap.maxY = (gameMap.maxY + 1)*tileSize;//10*64=640 gameMap.startX = gameMap.startY = 0; gameMap.fileName = mapName;//save in case reload fclose(file); } void Map::loadMyMapTiles(SDL_Renderer* screen) { char fileImage[40]; FILE *file = NULL; for (int i = 0; i < maxTiles; i++) { sprintf_s(fileImage, "assets/myMap/%d.png", i); fopen_s(&file, fileImage, "rb");//check if (file == NULL) { continue;//iff image null jut skip } fclose(file); tileMat[i].loadImage(fileImage, screen); } } void Map::drawMyMap(SDL_Renderer* des) { int mapX = 0; int x1 = 0; int x2 = 0; int mapY = 0; int y1 = 0; int y2 = 0; mapX = gameMap.startX / tileSize; x1 = (gameMap.startX %tileSize)*-1; x2 = x1 + screenWidth + (x1 == 0 ? 0 : tileSize); mapY = gameMap.startY / tileSize; y1 = (gameMap.startY%tileSize)*-1; y2 = y1 + screenHeight + (y1 == 0 ? 0 : tileSize); for (int i = y1; i < y2; i += tileSize) { mapX = gameMap.startX / tileSize; for (int j = x1; j < x2; j += tileSize) { int value = gameMap.tile[mapY][mapX]; if (value != 0) { tileMat[value].setRect(j, i); tileMat[value].render(des); } mapX++; } mapY++; } }
[ "5796@ait.nsw.edu.au" ]
5796@ait.nsw.edu.au
ffda4d8a58cc5365a2c34ed697b156f123821a25
9832a7e0b2047b55bb236d8289e4d90b7add309e
/opmlimport.cpp
4246c48741e298609dfeedaabe909991f9a498a8
[]
no_license
zhorro/zizulja
f02a24a8c2e196864a32ec5722badce0c281fd7b
e9661d8a15d25d9843cc6069764d860861b3de48
refs/heads/master
2021-01-22T22:39:20.155002
2011-11-27T15:53:52
2011-11-27T15:53:52
2,542,154
0
1
null
null
null
null
UTF-8
C++
false
false
1,612
cpp
#include <QFile> #include <QXmlSimpleReader> #include <QXmlInputSource> #include <QXmlDefaultHandler> #include <QUrl> #include "opmlimport.h" #include "podcastsdb.h" class OPMLHandler : public QXmlDefaultHandler { private: int m_newElements; public: OPMLHandler(void) : QXmlDefaultHandler() { resetCounter(); } void resetCounter() { m_newElements = 0; } int newElements () { return m_newElements; } virtual bool startElement ( const QString & namespaceURI, const QString & localName, const QString & qName, const QXmlAttributes & atts) { Q_UNUSED (qName); Q_UNUSED (namespaceURI); int idx = atts.index("xmlUrl"); if (localName == "outline" && idx>0) { QUrl url (atts.value(idx)); qDebug() << "Нашли описание, url = " << url.toString(); // Проверить есть ли в базе с таким урлом подкаст if (pdb.exists(url)) // Уже такой есть return true; // Ловить нечего pdb.append (url); m_newElements++; } return true; } }; int OPMLImport ( QString src ) { QFile file (src); QXmlSimpleReader xmlReader; QXmlInputSource *source = new QXmlInputSource(&file); OPMLHandler *handler = new OPMLHandler; xmlReader.setContentHandler(handler); xmlReader.setErrorHandler(handler); bool ok = xmlReader.parse(source); if (!ok) qDebug() << "Parsing failed." << endl; return handler->newElements(); }
[ "smaksim@gmail.com" ]
smaksim@gmail.com
4ffa0837ef97fd8ae4cb796551c3e1c726cffba1
424f0ff71d6cf8d8780f1e311600a80025bd6a56
/TestGame/TestGame.cpp
b81d2b76b82e681f9e2d2913c198bf870d5a445a
[]
no_license
GAR-for-GATC/GameEngine
384fd5d5db77901909f37a9ee9a7792dc5e6c558
27bb290bdb8ecfccaaf8221f315b67754eeb20ad
refs/heads/master
2021-01-18T21:10:23.868477
2016-10-29T04:18:59
2016-10-29T04:18:59
72,263,012
0
0
null
null
null
null
UTF-8
C++
false
false
623
cpp
#include <QtWidgets\qapplication.h> #include <QtWidgets\qwidget.h> #include "MyGlWindow.h" int main(int argc, char* argv[]){ //This here just opens up a command line when run using // return application.exec(); QApplication application(argc, argv); //This opens a GUI window. //QWidget myWidget; //myWidget.show(); MyGlWindow myGlWindow; myGlWindow.show(); //First thing is to draw a triangle. // coordinates are going to be: //(0,0), (1,0), (0.5, 1) //openGL has a right handed coordinate system. //Next video discusses the game loop, the main loop to update info. return application.exec(); }
[ "eweaver15@comcast.net" ]
eweaver15@comcast.net
ec370f12178664293397162ddb60d7f47cd00dab
cdd00d4d303e0829bb0c00530a165e1bd20cc7e6
/gcpCbass/antenna/control/cbass/MountOffset.cc
3ca2ace4a6a963f28c1c1f51cd145dac181511c8
[]
no_license
chopley/controlCode
fa538a20719989c7d13946d7e273bae153aa91d7
0b40d14797bc6db63ca9ea55115be5217d87dc88
refs/heads/master
2021-01-19T01:34:05.388485
2016-07-20T11:20:29
2016-07-20T11:20:29
11,604,863
0
0
null
null
null
null
UTF-8
C++
false
false
2,980
cc
#define __FILEPATH__ "antenna/control/specific/MountOffset.cc" #include <iostream> #include "gcp/util/common/Debug.h" #include "gcp/util/common/Exception.h" #include "gcp/antenna/control/specific/MountOffset.h" using namespace std; using namespace gcp::antenna::control; using namespace gcp::util; /**....................................................................... * Constructor just intializes the offsets to zero */ MountOffset::MountOffset() { reset(); } /**....................................................................... * Initialize the offsets */ void MountOffset::reset() { az_ = 0; el_ = 0; pa_ = 0; } /**....................................................................... * Increment the offsets, in radians */ void MountOffset::increment(double daz, double del) { az_ = wrapPi(az_ + daz); el_ = wrapPi(el_ + del); //pa_ = wrapPi(pa_ + dpa); } /**....................................................................... * Set the offsets */ void MountOffset::set(OffsetMsg msg) { switch(msg.mode) { case OffsetMsg::ADD: if(msg.axes & OffsetMsg::AZ) az_ = wrapPi(az_ + msg.body.mount.az); if(msg.axes & OffsetMsg::EL) el_ = wrapPi(el_ + msg.body.mount.el); //if(msg.axes & OffsetMsg::PA) //pa_ = wrapPi(el_ + msg.body.mount.pa); break; // Replace the existing offsets. case OffsetMsg::SET: if(msg.axes & OffsetMsg::AZ) az_ = wrapPi(msg.body.mount.az); if(msg.axes & OffsetMsg::EL) el_ = wrapPi(msg.body.mount.el); //if(msg.axes & OffsetMsg::PA) //pa_ = wrapPi(msg.body.mount.pa); break; default: ErrorDef(err, "SkyOffset::setOffset: Unrecognized mode.\n"); break; }; DBPRINT(true, Debug::DEBUG3, "Mount offsets are (new): " << az_ << ", " << el_); } /**....................................................................... * Return the az offset */ double MountOffset::getAz() { return az_; } /**....................................................................... * Return the elevation offset */ double MountOffset::getEl() { return el_; } /**....................................................................... * Return the parallactic angle offset */ //double MountOffset::getPa() //{ //return pa_; //} /**....................................................................... * Method to pack the mount offsets for archival in the register * database. */ void MountOffset::pack(signed* s_elements) { DBPRINT(true, Debug::DEBUG3, "Mount offsets are: " << az_ << ", " << el_); s_elements[0] = static_cast<signed>(az_ * rtomas); s_elements[1] = static_cast<signed>(el_ * rtomas); s_elements[2] = static_cast<signed>(pa_ * rtomas); } /**....................................................................... * Method to pack the mount offsets for archival in the register * database. */ void MountOffset::pack(double* array) { array[0] = az_; array[1] = el_; array[2] = pa_; }
[ "cbassuser@c-bass.(none)" ]
cbassuser@c-bass.(none)
20ad06d7caaaf427df8ab6bd838679fb1f26e304
d21c44d6d0131a902ba8b55bd6c995191430fbda
/HEW4-2/sprite.cpp
6bbfae12423da7fc3f3bada80ea10a596cc847ec
[]
no_license
shirokuma1114/Hew
f76399b446d0bf9607a3344343694cf0b0285e09
42ccad26a6028911f24237ee5ac941729075df6b
refs/heads/master
2020-09-20T06:05:26.422354
2019-11-28T09:57:49
2019-11-28T09:57:49
223,906,974
0
5
null
2019-11-26T09:22:22
2019-11-25T09:12:50
RPC
UTF-8
C++
false
false
5,655
cpp
#include <d3dx9.h> #include <math.h> #include "mydirect3d.h" #include "texture.h" typedef struct Vertex2D_tag { D3DXVECTOR4 position; D3DCOLOR color; D3DXVECTOR2 texcoord; } Vertex2D; #define FVF_VERTEX2D (D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1) static D3DCOLOR g_Color = 0xffffffff; // static D3DCOLOR g_Color = D3DCOLOR_RGBA(255, 255, 255, 255); void Sprite_SetColor(D3DCOLOR color) { g_Color = color; } void Sprite_Draw(TextureIndex texture_index, float dx, float dy) { LPDIRECT3DDEVICE9 pDevice = GetD3DDevice(); if (!pDevice) return; float w = (float)Texture_GetWidth(texture_index); float h = (float)Texture_GetHeight(texture_index); Vertex2D vertexes[] = { { D3DXVECTOR4(dx - 0.5f, dy - 0.5f, 0.0f, 1.0f), g_Color, D3DXVECTOR2(0.0f, 0.0f) }, { D3DXVECTOR4(dx + w - 0.5f, dy - 0.5f, 0.0f, 1.0f), g_Color, D3DXVECTOR2(1.0f, 0.0f) }, { D3DXVECTOR4(dx - 0.5f, dy + h - 0.5f, 0.0f, 1.0f), g_Color, D3DXVECTOR2(0.0f, 1.0f) }, { D3DXVECTOR4(dx + w - 0.5f, dy + h - 0.5f, 0.0f, 1.0f), g_Color, D3DXVECTOR2(1.0f, 1.0f) }, }; pDevice->SetFVF(FVF_VERTEX2D); pDevice->SetTexture(0, Texture_GetTexture(texture_index)); pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, vertexes, sizeof(Vertex2D)); } void Sprite_Draw(TextureIndex texture_index, float dx, float dy, int tx, int ty, int tw, int th) { LPDIRECT3DDEVICE9 pDevice = GetD3DDevice(); if (!pDevice) return; float w = (float)Texture_GetWidth(texture_index); float h = (float)Texture_GetHeight(texture_index); float u[2], v[2]; u[0] = (float)tx / w; v[0] = (float)ty / h; u[1] = (float)(tx + tw) / w; v[1] = (float)(ty + th) / h; Vertex2D vertexes[] = { { D3DXVECTOR4(dx - 0.5f, dy - 0.5f, 0.0f, 1.0f), g_Color, D3DXVECTOR2(u[0], v[0]) }, { D3DXVECTOR4(dx + tw - 0.5f, dy - 0.5f, 0.0f, 1.0f), g_Color, D3DXVECTOR2(u[1], v[0]) }, { D3DXVECTOR4(dx - 0.5f, dy + th - 0.5f, 0.0f, 1.0f), g_Color, D3DXVECTOR2(u[0], v[1]) }, { D3DXVECTOR4(dx + tw - 0.5f, dy + th - 0.5f, 0.0f, 1.0f), g_Color, D3DXVECTOR2(u[1], v[1]) }, }; pDevice->SetFVF(FVF_VERTEX2D); pDevice->SetTexture(0, Texture_GetTexture(texture_index)); pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, vertexes, sizeof(Vertex2D)); } /* void Sprite_Draw(TextureIndex texture_index, float dx, float dy, int tx, int ty,int tw, int th, float cx, float cy, float sx, float sy, float rotation) { LPDIRECT3DDEVICE9 pDevice = GetD3DDevice(); if( !pDevice ) return; float w = (float)Texture_GetWidth(texture_index); float h = (float)Texture_GetHeight(texture_index); float u[2], v[2]; u[0] = (float)tx / w; v[0] = (float)ty / h; u[1] = (float)(tx + tw) / w; v[1] = (float)(ty + th) / h; float px[4], py[4]; px[0] = -cx * sx * cos(rotation) - -cy * sy * sin(rotation); py[0] = -cx * sx * sin(rotation) + -cy * sy * cos(rotation); px[1] = (-cx + tw) * sx * cos(rotation) - -cy * sy * sin(rotation); py[1] = (-cx + tw) * sx * sin(rotation) + -cy * sy * cos(rotation); px[2] = -cx * sx * cos(rotation) - (-cy + th) * sy * sin(rotation); py[2] = -cx * sx * sin(rotation) + (-cy + th) * sy * cos(rotation); px[3] = (-cx + tw) * sx * cos(rotation) - (-cy + th) * sy * sin(rotation); py[3] = (-cx + tw) * sx * sin(rotation) + (-cy + th) * sy * cos(rotation); Vertex2D vertexes[] = { { D3DXVECTOR4(px[0] + dx + cx - 0.5f, py[0] + dy + cy - 0.5f, 0.0f, 1.0f), g_Color, D3DXVECTOR2(u[0], v[0]) }, { D3DXVECTOR4(px[1] + dx + cx - 0.5f, py[1] + dy + cy - 0.5f, 0.0f, 1.0f), g_Color, D3DXVECTOR2(u[1], v[0]) }, { D3DXVECTOR4(px[2] + dx + cx - 0.5f, py[2] + dy + cy - 0.5f, 0.0f, 1.0f), g_Color, D3DXVECTOR2(u[0], v[1]) }, { D3DXVECTOR4(px[3] + dx + cx - 0.5f, py[3] + dy + cy - 0.5f, 0.0f, 1.0f), g_Color, D3DXVECTOR2(u[1], v[1]) }, }; pDevice->SetFVF(FVF_VERTEX2D); pDevice->SetTexture(0, Texture_GetTexture(texture_index)); pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, vertexes, sizeof(Vertex2D)); } */ void Sprite_Draw(TextureIndex texture_index, float dx, float dy, int tx, int ty, int tw, int th, float cx, float cy, float sx, float sy, float rotation) { LPDIRECT3DDEVICE9 pDevice = GetD3DDevice(); if (!pDevice) return; float w = (float)Texture_GetWidth(texture_index); float h = (float)Texture_GetHeight(texture_index); float u[2], v[2]; u[0] = (float)tx / w; v[0] = (float)ty / h; u[1] = (float)(tx + tw) / w; v[1] = (float)(ty + th) / h; D3DXMATRIX matBase[4]; D3DXMatrixTranslation(&matBase[0], -(tw - (tw - cx)), -(th - (th - cy)), 0.0f); D3DXMatrixTranslation(&matBase[1], tw - cx, -(th - (th - cy)), 0.0f); D3DXMatrixTranslation(&matBase[2], -(tw - (tw - cx)), th - cy, 0.0f); D3DXMatrixTranslation(&matBase[3], tw - cx, th - cy, 0.0f); D3DXMATRIX matTrans; D3DXMATRIX matRot; D3DXMATRIX matScale; D3DXMATRIX matAll; float px[4], py[4]; D3DXMatrixTranslation(&matTrans, dx, dy, 0.0f); D3DXMatrixRotationZ(&matRot, rotation); D3DXMatrixScaling(&matScale, sx, sy, 1.0f); for (int i = 0; i < 4; i++) { matAll = matBase[i] * matScale * matRot * matTrans; px[i] = matAll._41; py[i] = matAll._42; } Vertex2D vertexes[] = { { D3DXVECTOR4(px[0] - 0.5f, py[0] - 0.5f, 0.0f, 1.0f), g_Color, D3DXVECTOR2(u[0], v[0]) }, { D3DXVECTOR4(px[1] - 0.5f, py[1] - 0.5f, 0.0f, 1.0f), g_Color, D3DXVECTOR2(u[1], v[0]) }, { D3DXVECTOR4(px[2] - 0.5f, py[2] - 0.5f, 0.0f, 1.0f), g_Color, D3DXVECTOR2(u[0], v[1]) }, { D3DXVECTOR4(px[3] - 0.5f, py[3] - 0.5f, 0.0f, 1.0f), g_Color, D3DXVECTOR2(u[1], v[1]) }, }; pDevice->SetFVF(FVF_VERTEX2D); pDevice->SetTexture(0, Texture_GetTexture(texture_index)); pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, vertexes, sizeof(Vertex2D)); }
[ "hiromu.zai@gmail.com" ]
hiromu.zai@gmail.com
11750489a14dfa2032603eb788a6ea80a42e1882
096961ee99272213aae979902aad0fed8b86a957
/CodeForces/training/158B.cpp
4a2e94efde83bcf1d98e2c5737e7bbcfff41d1fb
[]
no_license
yassin64b/competitive-programming
2d92ee9878e33b5f40da4f0440e994beb595a21b
180a309da3e12d00c9e4dc384a9aa95ec3e80938
refs/heads/master
2021-03-27T15:58:27.450505
2020-01-11T16:40:17
2020-01-11T16:40:17
53,347,417
0
0
null
null
null
null
UTF-8
C++
false
false
855
cpp
#include <iostream> #include <vector> #include <cstdlib> using namespace std; int main() { int n, num = 0; cin >> n; int cnt[4] = {0}; for(int i = 0; i < n; ++i) { int s; cin >> s; cnt[s-1]++; } num += cnt[3]; //cout << num << endl; num += cnt[1]/2, cnt[1] -= (cnt[1]/2)*2; //cout << num << endl; int tmp = min(cnt[0],cnt[2]); num += tmp, cnt[0] -= tmp, cnt[2] -= tmp; //cout << num << endl; if(cnt[2] > 0) { num += cnt[2]; } //cout << num << endl; if(cnt[0] > 0) { num += cnt[0]/4, cnt[0] = cnt[0]%4; if((cnt[0] || cnt[1]) && cnt[0] + cnt[1]*2 <= 4) ++num, cnt[1] = 0; else if(cnt[0] || cnt[1]) num += 2, cnt[1] = 0; } //cout << num << endl; num += cnt[1]; cout << num << endl; }
[ "yassin.bahloul@gmx.de" ]
yassin.bahloul@gmx.de
40a2c82f6aa5a7d1a2eb5c43c914e9dcf799eef4
8caae43ec3015fda9e1a8782980a21d7158452c3
/src/nest_recursive/nest.cpp
7764ae7a939620f46af29bd8da8544afa33d41b5
[]
no_license
morning-color/data-structure
5fafbff86bcded66bbd75b112a803fcff4c208e9
e1df53f2b5c7f480f189c36a801022161e05775f
refs/heads/master
2016-09-06T13:51:40.285820
2015-05-14T13:06:52
2015-05-14T13:06:52
34,613,861
0
0
null
null
null
null
GB18030
C++
false
false
1,918
cpp
/****************************************************************************************** * Data Structures in C++ * ISBN: 7-302-33064-6 & 7-302-33065-3 & 7-302-29652-2 & 7-302-26883-3 * Junhui DENG, deng@tsinghua.edu.cn * Computer Science & Technology, Tsinghua University * Copyright (c) 2006-2013. All rights reserved. ******************************************************************************************/ /*DSA*/#include "../nest_stack/nest.h" void trim(const char exp[], int& lo, int& hi) { //删除表达式exp[lo, hi]不含括号的最长前缀、后缀 while ((lo <= hi) && (exp[lo] != '(') && (exp[lo] != ')')) lo++; //查找第一个和 while ((lo <= hi) && (exp[hi] != '(') && (exp[hi] != ')')) hi--; //最后一个括号 } int divide(const char exp[], int lo, int hi) { //切分表达式exp[lo, hi],使exp匹配仅当它们匹配 int mi = lo; int crc = 1; //crc为[lo, mi]范围内左、右括号数目之差 while ((0 < crc) && (++mi < hi)) //逐个检查各字符,直到左、右括号数目相等,或者越界 { if (exp[mi] == ')') crc--; if (exp[mi] == '(') crc++; } //左、右括号分别计数 return mi; //若mi <= hi,则为合法切分点;否则,意味着局部不可能匹配 } bool paren(const char exp[], int lo, int hi) { //检查表达式exp[lo, hi]是否括号匹配(递归版) /*DSA*/displaySubstring(exp, lo, hi); trim(exp, lo, hi); if (lo > hi) return true; //清除不含括号的前缀、后缀 if (exp[lo] != '(') return false; //首字符非左括号,则必不匹配 if (exp[hi] != ')') return false; //末字符非右括号,则必不匹配 int mi = divide(exp, lo, hi); //确定适当的切分点 if (mi > hi) return false; //切分点不合法,意味着局部以至整体不匹配 return paren(exp, lo+1, mi-1) && paren(exp, mi+1, hi); //分别检查左、右子表达式 }
[ "moring_color@163.com" ]
moring_color@163.com
8f37ff0527f5d3c51f945fd5d8b6672b2d0ac686
4352b5c9e6719d762e6a80e7a7799630d819bca3
/tutorials/oldd/old/pimpleDyM_Piston/1.18/p
13dfae39a56dba353fcd38c451d2ab7576ae743a
[]
no_license
dashqua/epicProject
d6214b57c545110d08ad053e68bc095f1d4dc725
54afca50a61c20c541ef43e3d96408ef72f0bcbc
refs/heads/master
2022-02-28T17:20:20.291864
2019-10-28T13:33:16
2019-10-28T13:33:16
184,294,390
1
0
null
null
null
null
UTF-8
C++
false
false
8,141
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "1.18"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField nonuniform List<scalar> 800 ( -23.5012 -88.0388 -119.932 -109.787 -103.84 -115.715 -126.654 -101.094 -99.2806 -105.153 -106.218 -123.632 -127.724 -142.837 -183.146 -247.777 -202.302 -162.397 -140.488 59.8516 -42.0419 -87.7207 -121.736 -108.029 -105.217 -116.631 -127.885 -101.238 -99.6894 -105.245 -106.773 -123.174 -130.648 -138.456 -187.956 -244.535 -203.646 -162.479 -144.348 60.245 -44.515 -87.4545 -122.174 -108.49 -104.266 -114.609 -128.608 -101.821 -99.4165 -105.058 -107.668 -123.539 -128.532 -141.7 -188.251 -241.539 -202.957 -164.736 -145.893 61.1225 -39.0849 -87.6339 -120.698 -109.562 -108.035 -112.706 -129.094 -102.431 -100.211 -103.373 -107.495 -123.269 -125.281 -140.021 -201.685 -242.594 -200.996 -169.673 -147.823 61.0226 -39.8224 -87.94 -119.712 -112.432 -108.789 -109.912 -129.667 -102.47 -101.189 -104.925 -108.258 -123.754 -122.765 -141.442 -198.091 -246.283 -202.852 -171.362 -148.302 60.584 -40.1741 -88.2091 -118.656 -116.178 -111.106 -108.249 -130.841 -103.169 -100.462 -103.15 -110.3 -123.678 -122.509 -139.46 -200.226 -249.903 -204.111 -173.405 -147.231 60.0086 -43.2994 -88.4857 -117.599 -119.308 -112.567 -108.495 -135.24 -103.151 -99.9117 -103.221 -110.61 -124.588 -123.422 -136.229 -198.01 -255.389 -206.638 -168.497 -146.897 59.2182 -42.3136 -88.8044 -116.9 -122.426 -112.502 -104.974 -133.856 -106.247 -99.9803 -104.926 -110.149 -123.561 -127.09 -137.423 -192.658 -261.034 -209.591 -165.478 -143.403 58.3687 -43.9092 -88.6448 -116.318 -125.666 -116.315 -102.499 -136.244 -109.108 -100.473 -105.98 -109.557 -122.543 -130.456 -140.196 -184.458 -267.348 -211.912 -157.832 -142.935 56.9026 -42.8408 -89.0912 -115.616 -127.345 -117.014 -100.443 -135.073 -109.476 -100.479 -108.791 -108.98 -124.285 -132.36 -141.253 -183.637 -276.252 -214.362 -154.131 -140.947 55.3206 -46.345 -90.1907 -114.118 -127.185 -119.762 -100.03 -133.491 -108.297 -96.7008 -108.212 -109.364 -124.186 -132.462 -146.245 -185.259 -280.861 -218.834 -148.336 -141.455 53.0998 -46.618 -91.0785 -112.721 -125.473 -121.431 -100.246 -133.256 -105.541 -98.5344 -109.909 -111.479 -123.425 -130.128 -148.419 -187.843 -284.222 -223.099 -145.104 -143.705 50.8976 -47.4864 -92.11 -112.205 -124.241 -123.948 -104.917 -129.929 -106.027 -97.3904 -110.556 -110.311 -122.917 -128.694 -155.853 -191.372 -284.2 -228.502 -143.734 -144.619 46.8921 -47.5717 -93.0217 -111.444 -124.285 -125.425 -109.274 -131.385 -107.643 -95.979 -108.297 -111.762 -124.205 -126.579 -157.716 -195.498 -277.608 -233.864 -144.638 -145.132 42.9953 -49.0874 -93.8252 -111.237 -123.785 -126.172 -115.735 -130.05 -110.184 -95.1641 -107.821 -112.774 -122.278 -125.742 -165.288 -199.687 -267.674 -239.06 -151.423 -143.032 38.4949 -49.5264 -94.4619 -110.888 -124.707 -126.809 -120.02 -130.501 -111.987 -95.8444 -104.823 -112.595 -123.413 -125.018 -165.212 -203.597 -253.936 -240.819 -156.927 -144.56 34.2951 -51.378 -94.6837 -110.846 -124.71 -127.135 -125.717 -131.81 -110.458 -96.7645 -104.763 -113.503 -121.213 -124.77 -170.784 -206.88 -239.506 -243.141 -163.895 -144.452 31.158 -51.7547 -94.3611 -110.457 -126.645 -127.406 -132.415 -133.346 -110.313 -98.6572 -104.736 -112.791 -120.388 -124.993 -168.676 -208.496 -228.29 -245.255 -170.471 -145.563 27.2792 -52.6919 -93.2194 -110.794 -126.327 -127.209 -137.839 -134.792 -110.239 -99.1293 -105.412 -113.042 -118.004 -125.03 -171.188 -212.575 -220.489 -248.312 -171.862 -146.276 25.7265 -52.3738 -91.1836 -110.017 -129.204 -127.225 -145.726 -135.572 -109.821 -101.707 -106.412 -112.835 -117.32 -125.022 -170.851 -211.453 -216.78 -251.095 -171.703 -145.252 21.9115 -52.1311 -88.7907 -109.947 -127.703 -127.002 -149.614 -134.995 -110.834 -102.335 -106.754 -112.228 -116.595 -125.731 -174.448 -210.841 -216.375 -251.591 -171.077 -143.317 21.3255 -51.153 -86.7945 -108.896 -129.715 -127.854 -158.166 -134.856 -109.944 -104.68 -106.838 -112.537 -114.154 -126.233 -174.461 -209.015 -219.005 -253.494 -169.252 -135.805 17.0926 -49.2482 -85.9388 -108.037 -127.532 -126.683 -156.548 -131.956 -111.52 -105.552 -106.97 -116.258 -111.562 -125.269 -177.451 -205.032 -218.305 -253.199 -171.478 -133.199 16.012 -47.4718 -85.6196 -108.081 -128.429 -127.205 -161.611 -131.212 -110.52 -106.983 -107.445 -116.262 -109.086 -125.209 -176.479 -202.165 -218.157 -255.18 -174.656 -122.21 12.2349 -45.2808 -85.6907 -108.123 -125.856 -123.054 -155.377 -126.511 -112.419 -107.969 -107.729 -116.464 -107.883 -125.008 -177.909 -196.389 -215.626 -257.079 -175.414 -124.514 10.3257 -43.1501 -86.0873 -108.138 -127.226 -121.344 -156.106 -125.638 -111.574 -108.605 -108.427 -116.266 -106.7 -124.998 -176.723 -191.495 -209.601 -258.167 -181.45 -120.092 8.41901 -41.669 -85.3333 -108.588 -124.127 -117.48 -149.04 -120.46 -112.941 -109.169 -109.148 -116.104 -105.212 -125.063 -177.368 -182.185 -205.36 -256.676 -175.398 -122.127 5.04769 -39.6489 -84.9675 -108.215 -124.716 -116.326 -147.404 -119.76 -112.638 -109.622 -109.779 -116.454 -104.103 -124.003 -177.048 -175.592 -196.143 -243.634 -176.604 -120.972 5.47089 -39.5576 -83.2533 -107.321 -122.699 -115.662 -140.388 -115.384 -113.402 -109.597 -110.203 -116.609 -103.023 -124.243 -176.936 -164.805 -198.202 -240.04 -173.602 -120.198 0.449716 -38.7112 -82.2169 -105.792 -121.369 -116.233 -137.221 -114.573 -113.059 -109.557 -110.624 -116.922 -101.846 -121.959 -179.064 -160.918 -201.288 -234.917 -173.876 -122.318 6.36234 -40.0052 -80.9639 -103.055 -120.724 -117.109 -130.487 -111.378 -113.464 -109.064 -110.912 -117.226 -101.253 -121.499 -179.725 -160.227 -210.946 -225.034 -173.945 -122.782 4.97887 -40.0441 -79.9964 -101.328 -119 -118.055 -126.016 -110.443 -112.861 -108.504 -111.385 -117.274 -100.599 -120.522 -181.555 -169.905 -215.029 -223.215 -174.138 -126.691 6.72246 -40.5106 -78.6815 -98.9476 -118.91 -118.043 -120.066 -108.954 -112.868 -107.856 -111.956 -117.287 -100.441 -120.033 -183.55 -164.105 -216.837 -223.795 -174.798 -126.087 11.5029 -40.6127 -77.2518 -97.73 -116.887 -119.472 -115.834 -108.381 -112.151 -107.04 -112.707 -116.799 -100.823 -119.172 -185.786 -160.611 -218.48 -223.512 -176.93 -125.291 11.9934 -40.2353 -77.5307 -96.32 -115.907 -119.239 -113.175 -108.926 -111.579 -106.433 -113.386 -116.785 -100.779 -119.578 -188.393 -154.331 -217.102 -223.935 -178.065 -129.283 15.0917 -39.7646 -77.061 -95.5147 -113.174 -120.31 -110.608 -108.2 -111.123 -105.523 -113.852 -116.458 -102.091 -117.73 -189.081 -148.904 -215.501 -223.656 -181.758 -129.852 23.2514 -39.0393 -77.2236 -94.8632 -110.988 -121.44 -109.818 -108.659 -110.355 -105.002 -114.741 -116.608 -100.675 -117.889 -188.532 -144.513 -213.44 -226.727 -182.977 -132.435 28.5793 -38.6014 -76.4611 -94.3898 -107.999 -123.423 -106.799 -106.36 -110.071 -104.037 -116.82 -116.096 -101.421 -116.541 -186.77 -141.87 -213.155 -224.313 -182.635 -138.21 33.2488 -38.3794 -76.4081 -94.2137 -105.178 -126.32 -108.67 -103.731 -110.054 -103.19 -115.925 -117.481 -99.202 -118.27 -185.81 -139.074 -213.286 -225.495 -184.71 -137.282 37.3751 -38.1898 -76.4112 -93.7863 -104.84 -122.317 -107.445 -103.034 -110.071 -102.943 -115.83 -118.616 -98.6518 -119.853 -184.415 -134.703 -207.28 -230.018 -186.418 -136.811 36.4454 ) ; boundaryField { piston { type zeroGradient; } outlet { type zeroGradient; } walls { type zeroGradient; } front { type empty; } back { type empty; } } // ************************************************************************* //
[ "tdg@debian" ]
tdg@debian
f16168a8452bc7471958c0876c90d937caad9f0d
87955ec8a20c3d3ee98ebce458956d57c972ed31
/src/governance-validators.cpp
3a9ec4f04ebe8408827c1fbf89efd9e409410904
[ "MIT" ]
permissive
FullStackDeveloper2020/Hashshare
e7d8cdcff778ee127e01d092231c5080515ae4c2
e4e5893183994382c1490356d158ee3dfc9f200e
refs/heads/master
2020-12-26T12:06:11.529510
2020-01-31T19:48:36
2020-01-31T19:48:36
237,503,888
0
0
null
null
null
null
UTF-8
C++
false
false
8,845
cpp
// Copyright (c) 2014-2018 The Dash Core developers // Copyright (c) 2018-2019 The PACGlobal developers // Copyright (c) 2019 The HashShare Coin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "governance-validators.h" #include "base58.h" #include "timedata.h" #include "tinyformat.h" #include "utilstrencodings.h" #include <algorithm> const size_t MAX_DATA_SIZE = 512; const size_t MAX_NAME_SIZE = 40; CProposalValidator::CProposalValidator(const std::string& strHexData, bool fAllowLegacyFormat) : objJSON(UniValue::VOBJ), fJSONValid(false), fAllowLegacyFormat(fAllowLegacyFormat), strErrorMessages() { if (!strHexData.empty()) { ParseStrHexData(strHexData); } } void CProposalValidator::ParseStrHexData(const std::string& strHexData) { std::vector<unsigned char> v = ParseHex(strHexData); if (v.size() > MAX_DATA_SIZE) { strErrorMessages = strprintf("data exceeds %lu characters;", MAX_DATA_SIZE); return; } ParseJSONData(std::string(v.begin(), v.end())); } bool CProposalValidator::Validate(bool fCheckExpiration) { if (!fJSONValid) { strErrorMessages += "JSON parsing error;"; return false; } if (!ValidateName()) { strErrorMessages += "Invalid name;"; return false; } if (!ValidateStartEndEpoch(fCheckExpiration)) { strErrorMessages += "Invalid start:end range;"; return false; } if (!ValidatePaymentAmount()) { strErrorMessages += "Invalid payment amount;"; return false; } if (!ValidatePaymentAddress()) { strErrorMessages += "Invalid payment address;"; return false; } if (!ValidateURL()) { strErrorMessages += "Invalid URL;"; return false; } return true; } bool CProposalValidator::ValidateName() { std::string strName; if (!GetDataValue("name", strName)) { strErrorMessages += "name field not found;"; return false; } if (strName.size() > MAX_NAME_SIZE) { strErrorMessages += strprintf("name exceeds %lu characters;", MAX_NAME_SIZE); return false; } static const std::string strAllowedChars = "-_abcdefghijklmnopqrstuvwxyz0123456789"; std::transform(strName.begin(), strName.end(), strName.begin(), ::tolower); if (strName.find_first_not_of(strAllowedChars) != std::string::npos) { strErrorMessages += "name contains invalid characters;"; return false; } return true; } bool CProposalValidator::ValidateStartEndEpoch(bool fCheckExpiration) { int64_t nStartEpoch = 0; int64_t nEndEpoch = 0; if (!GetDataValue("start_epoch", nStartEpoch)) { strErrorMessages += "start_epoch field not found;"; return false; } if (!GetDataValue("end_epoch", nEndEpoch)) { strErrorMessages += "end_epoch field not found;"; return false; } if (nEndEpoch <= nStartEpoch) { strErrorMessages += "end_epoch <= start_epoch;"; return false; } if (fCheckExpiration && nEndEpoch <= GetAdjustedTime()) { strErrorMessages += "expired;"; return false; } return true; } bool CProposalValidator::ValidatePaymentAmount() { double dValue = 0.0; if (!GetDataValue("payment_amount", dValue)) { strErrorMessages += "payment_amount field not found;"; return false; } if (dValue <= 0.0) { strErrorMessages += "payment_amount is negative;"; return false; } // TODO: Should check for an amount which exceeds the budget but this is // currently difficult because start and end epochs are defined in terms of // clock time instead of block height. return true; } bool CProposalValidator::ValidatePaymentAddress() { std::string strPaymentAddress; if (!GetDataValue("payment_address", strPaymentAddress)) { strErrorMessages += "payment_address field not found;"; return false; } if (std::find_if(strPaymentAddress.begin(), strPaymentAddress.end(), ::isspace) != strPaymentAddress.end()) { strErrorMessages += "payment_address can't have whitespaces;"; return false; } CBitcoinAddress address(strPaymentAddress); if (!address.IsValid()) { strErrorMessages += "payment_address is invalid;"; return false; } if (address.IsScript()) { strErrorMessages += "script addresses are not supported;"; return false; } return true; } bool CProposalValidator::ValidateURL() { std::string strURL; if (!GetDataValue("url", strURL)) { strErrorMessages += "url field not found;"; return false; } if (std::find_if(strURL.begin(), strURL.end(), ::isspace) != strURL.end()) { strErrorMessages += "url can't have whitespaces;"; return false; } if (strURL.size() < 4U) { strErrorMessages += "url too short;"; return false; } if (!CheckURL(strURL)) { strErrorMessages += "url invalid;"; return false; } return true; } void CProposalValidator::ParseJSONData(const std::string& strJSONData) { fJSONValid = false; if (strJSONData.empty()) { return; } try { UniValue obj(UniValue::VOBJ); obj.read(strJSONData); if (obj.isObject()) { objJSON = obj; } else { if (fAllowLegacyFormat) { std::vector<UniValue> arr1 = obj.getValues(); std::vector<UniValue> arr2 = arr1.at(0).getValues(); objJSON = arr2.at(1); } else { throw std::runtime_error("Legacy proposal serialization format not allowed"); } } fJSONValid = true; } catch (std::exception& e) { strErrorMessages += std::string(e.what()) + std::string(";"); } catch (...) { strErrorMessages += "Unknown exception;"; } } bool CProposalValidator::GetDataValue(const std::string& strKey, std::string& strValueRet) { bool fOK = false; try { strValueRet = objJSON[strKey].get_str(); fOK = true; } catch (std::exception& e) { strErrorMessages += std::string(e.what()) + std::string(";"); } catch (...) { strErrorMessages += "Unknown exception;"; } return fOK; } bool CProposalValidator::GetDataValue(const std::string& strKey, int64_t& nValueRet) { bool fOK = false; try { const UniValue uValue = objJSON[strKey]; switch (uValue.getType()) { case UniValue::VNUM: nValueRet = uValue.get_int64(); fOK = true; break; default: break; } } catch (std::exception& e) { strErrorMessages += std::string(e.what()) + std::string(";"); } catch (...) { strErrorMessages += "Unknown exception;"; } return fOK; } bool CProposalValidator::GetDataValue(const std::string& strKey, double& dValueRet) { bool fOK = false; try { const UniValue uValue = objJSON[strKey]; switch (uValue.getType()) { case UniValue::VNUM: dValueRet = uValue.get_real(); fOK = true; break; default: break; } } catch (std::exception& e) { strErrorMessages += std::string(e.what()) + std::string(";"); } catch (...) { strErrorMessages += "Unknown exception;"; } return fOK; } /* The purpose of this function is to replicate the behavior of the Python urlparse function used by sentinel (urlparse.py). This function should return false whenever urlparse raises an exception and true otherwise. */ bool CProposalValidator::CheckURL(const std::string& strURLIn) { std::string strRest(strURLIn); std::string::size_type nPos = strRest.find(':'); if (nPos != std::string::npos) { //std::string strSchema = strRest.substr(0,nPos); if (nPos < strRest.size()) { strRest = strRest.substr(nPos + 1); } else { strRest = ""; } } // Process netloc if ((strRest.size() > 2) && (strRest.substr(0, 2) == "//")) { static const std::string strNetlocDelimiters = "/?#"; strRest = strRest.substr(2); std::string::size_type nPos2 = strRest.find_first_of(strNetlocDelimiters); std::string strNetloc = strRest.substr(0, nPos2); if ((strNetloc.find('[') != std::string::npos) && (strNetloc.find(']') == std::string::npos)) { return false; } if ((strNetloc.find(']') != std::string::npos) && (strNetloc.find('[') == std::string::npos)) { return false; } } return true; }
[ "59161578+hashshare@users.noreply.github.com" ]
59161578+hashshare@users.noreply.github.com
ee6b08b0d34dcf5e0f1a2aadc5ea98c3cd686971
50932dc8cec6f1ca48aff7a0a134885c0dead46c
/huffman_last.cpp
ed3d8d0fc5687c2ed04b0e2d55ae13bc060ce4ed
[]
no_license
ea-evdokimov/1-semestr
8986fb1c05478b7f20bb6d85e5bbe6285e7b8c2c
996ede52b77a4f752454c7a01ee0e15c3ac23947
refs/heads/master
2022-01-04T17:50:23.948791
2020-03-01T11:47:10
2020-03-01T11:47:10
223,782,760
0
0
null
null
null
null
UTF-8
C++
false
false
7,059
cpp
#include <iostream> #include <string> #include <queue> //#include "Huffman.h" using namespace std; typedef unsigned char byte; class node { private: int frequency; byte symbol; bool help;//флаг, является ли узел вспомогательным string code;//строка для кода символа node* left = nullptr; node* right = nullptr; public: node(int freq, byte symb, int h) : frequency(freq), symbol(symb), help(h) {} ~node() { delete left; delete right; } void SetChildren(node* r, node* l) { right = r; left = l; } bool IsHelp() { return help; } int GetFreq() { return frequency; } int GetSymbol() { return (int)symbol; } node* GetLeftChild() { return left; } node* GetRightChild() { return right; } void SetCode(string res) { code = res; } void print(int level) const { if (this == nullptr) return; right->print(level + 1); for (int i = 0; i < level; i++) cout << "_ "; cout << "(" << symbol << "-" << frequency << "-" << code << ")" << endl; left->print(level + 1); } }; struct Tree { node* root; Tree(node* root_) { root = root_; } ~Tree() { delete root; } bool empty() const { return root == nullptr; } void SetCodes(node* node, int bit, string res, string* codes) { if (node == root) { if (node->GetRightChild()) SetCodes(node->GetRightChild(), 1, res, codes); if (node->GetLeftChild()) SetCodes(node->GetLeftChild(), 0, res, codes); } else if (node->IsHelp()) {//если node вспомогательный if (node->GetLeftChild()) { if (bit) SetCodes(node->GetLeftChild(), 0, res + "1", codes); else SetCodes(node->GetLeftChild(), 0, res + "0", codes); } if (node->GetRightChild()) { if (bit) SetCodes(node->GetRightChild(), 1, res + "1", codes); else SetCodes(node->GetRightChild(), 1, res + "0", codes); } } else {//node с нашим символом if (bit) { node->SetCode(res + "1"); codes[node->GetSymbol()] = res + "1"; } else { node->SetCode(res + "0"); codes[node->GetSymbol()] = res + "0"; } } } void print() const { cout << "\n"; root->print(0); } }; class comp {//компаратор для построение кучи с поддержанием минимума public: bool operator()(node* x, node* y) { return x->GetFreq() > y->GetFreq(); } }; struct bytein {//симуляция IInputStream public: bool Read(byte& value) { value = getchar(); if (value == 255 || value == '\n') return 0; } }; string GetString(bytein& input) {//функция получение строки из входящего потока byte value; string s; while (input.Read(value)) { s += value; } return s; } byte ToChars(string s, int start) {//перерводит строки из кодов символов в другие байты int res = 0; int p = 1; for (int i = 0; i < 8; i++) { res += (s[start + 7 - i] == '1') * p; p = p << 1; } return (byte)res; } string ToBites(int n) {//перевод каждого int в строку из 4 byte int mask = 255; string res = " "; for (int i = 0; i < 4; i++) { res[3 - i] = (byte)n & mask; n = n >> 8; } return res; } int GetBit(byte c, int n) {//получение бита под номером n int mask = 1 << (7 - n); return ((c & mask) != 0); } void Decode(string arch) { string result; int *freq = new int[256](); for (int i = 0; i < 256; i++) {//обратный перевод первых 256 char в чатсоты int result = 0; for (int j = 0; j < 4; j++) { result <<= 8; result |= (byte)arch[i * 4 + j]; } freq[i] = result; }//готовый массив с частотами int length = 0; for (int i = 0; i < 256; i++) { length += freq[i]; }//длина исходной строки как сумма всех частот //аналогичное построение дерева на частотах встречаемости элементов priority_queue<node*, vector<node*>, comp> q; for (int i = 0; i < 256; i++) { if (freq[i] > 0) { node* a = new node(freq[i], (byte)i, 0); q.push(a); } } while (q.size() > 1) { node* r = q.top(); q.pop(); node* l = q.top(); q.pop(); node* parent = new node(r->GetFreq() + l->GetFreq(), '!', 1); parent->SetChildren(r, l); q.push(parent); } node* root_ = q.top(); Tree* tree = new Tree(root_); auto curr = root_; int len_of_bytes = arch.size() - 1024;//длина символов, которые кодируют строку int k = 0;//количество считанных символов for (int i = 0; i < len_of_bytes && k < length; i++) { for (int t = 0; t < 8 && k < length; t++) { if (curr->IsHelp() == 0) { result += (byte)curr->GetSymbol();//если дошли до листа, получаем k++; if (GetBit(arch[i + 1024], t) == 1) curr = root_->GetRightChild(); else curr = root_->GetLeftChild(); } else { if (GetBit(arch[i + 1024], t) == 1) curr = curr->GetRightChild(); else curr = curr->GetLeftChild(); } } } cout << "result:" << result; delete[] freq; } void Encode(bytein& original) { string orig = GetString(original);//оригинальная строка int* freq = new int[256](); string *codes = new string[256]; for (int i = 0; i < orig.length(); i++) { freq[(byte)orig[i]]++; }//массив с частотами встречающихся символов priority_queue<node*, vector<node*>, comp> q; for (int i = 0; i < 256; i++) { if (freq[i] > 0) { node* a = new node(freq[i], (byte)i, 0); q.push(a); } }//создана очередь из узлов дерева с символами и их частотами while (q.size() > 1) { node* r = q.top(); q.pop(); node* l = q.top(); q.pop(); node* parent = new node(r->GetFreq() + l->GetFreq(), '!', 1); parent->SetChildren(r, l); q.push(parent); } node* root_ = q.top();//указатель на корень дерева, постороенного на частотах q.pop(); Tree* tree = new Tree(root_); string e_s = ""; if (!tree->empty()) { tree->SetCodes(root_, 0, e_s, codes); //tree->print(); } //////////////////////////////////////////////////////////////////////// string raw; for (int i = 0; i < orig.length(); i++) raw += codes[(byte)orig[i]]; bool flag = 0; if (raw.length() % 8 == 0) flag = 1; while (raw.size() % 8 != 0) raw += "0"; string decode; for (int i = 0; i < 256; i++) { decode += ToBites(freq[i]); }//в строку занесены частоты встречаемостей символов, переведенный в char for (int i = 0; i < raw.length() / 8; i++) { decode += ToChars(raw, i * 8); }//после частот идут коды символов if (flag) decode += "0"; Decode(decode); delete[] freq; delete[] codes; } int main() { bytein in; Encode(in); return 0; }
[ "e.evdokimov.gor@gmail.com" ]
e.evdokimov.gor@gmail.com
968e8f94c6e5040a36577c88d4ef96309104ff9d
45c6e5e140019ea417b06fe5c082ad309eaab0ce
/Imaging/include/Grabber.h
fb3db5d6543b836b71ee3922e69673125fcefbf3
[]
no_license
isliulin/fadvs
532220b54d17eab90717a8cd92b280417e65eeeb
5729519bcd0651eb85b34fcbda61c50f1d70ddc4
refs/heads/master
2022-10-16T04:32:17.502976
2020-06-15T09:55:21
2020-06-15T09:55:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
44,294
h
// Grabber.h: interface for the Grabber class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_GRABBER_H__F72DCE0B_3C5C_44EA_BFAB_ADDE04304CA6__INCLUDED_) #define AFX_GRABBER_H__F72DCE0B_3C5C_44EA_BFAB_ADDE04304CA6__INCLUDED_ #pragma once #include <string> #include <vector> #include "udshl_defs.h" #include "smart_ptr.h" #include "simplectypes.h" #include "AnalogChannelItem.h" #include "VideoNormItem.h" #include "VideoFormatItem.h" #include "VideoFormatDesc.h" #include "VideoCaptureDeviceItem.h" #include "Error.h" #include "IVCDProperty.h" #include "DeBayerTransform.h" #include "FrameFilterBase.h" namespace _DSHOWLIB_NAMESPACE { class Grabber; class MemBufferCollection; class MemBuffer; class GrabberListener; class GrabberSinkType; class FilterInfoObject; class OverlayBitmap; class IDispEventDispatcher; /** This function must be used to initialize the library. * The implicit parameter is coinitmode = COINIT_MULTITHREADED. When you want to use another COM apartment model * you have to use InitLibrary( 0, <other_model> ); * @return true on success, false otherwise. */ _UDSHL_EXP_API bool InitLibrary(); /** This function must be used to initialize the library. * @param pSerialNumber the serial number you want to set * @param coinitmode mode passed to CoInitializeEx. * Pass -1 when you already called OleInitialize or CoInitialize/Ex or you bind * statically to common dialogs like the file open dialog. * Pass COINIT_APARTMENTTHREADED if you want to load a common dialog dynamically or when * some OLE object fails after InitLibrary. * @return true on success, false otherwise. */ _UDSHL_EXP_API bool InitLibrary( const char* pSerialNumber, DWORD coinitmode = COINIT_MULTITHREADED ); /** This function must be used to initialize the library. * @param ppSerialNumber the serial numbers you want to set. * @param count the number of serial numbers in ppSerialNumber * @param coinitmode mode passed to CoInitializeEx. * Pass -1 when you already called OleInitialize or CoInitialize/Ex or you bind * statically to common dialogs like the file open dialog. * Pass COINIT_APARTMENTTHREADED if you want to load a common dialog dynamically or when * some OLE object fails after InitLibrary. * @return true on success, false otherwise. */ _UDSHL_EXP_API bool InitLibrary( const char** ppSerialNumber, unsigned int count, DWORD coinitmode = COINIT_MULTITHREADED ); /** This method returns true when all objects returned by the * the library were destroyed, otherwise false. * You can use this to determine the best time to unload the library (e.g. for COM objects). */ _UDSHL_EXP_API bool CanUnloadLibrary(); /** This method should be called by the client app, when the library should shut down. * If you don't do this, then the library may seem to leak several objects and bytes, because the dump running * objects call may happen before the library has been told to unload itself. * * After calling ExitLibrary no operation on the library is valid and so its effect is undefined. */ _UDSHL_EXP_API void ExitLibrary(); /// struct that defines a frame end callback struct _UDSHL_EXP_API tsFrameEndCallback { typedef smart_ptr<MemBuffer> tMemBufferPtr; /** Callback function for user defined EndOfFrame Callback * @param ptr pointer set by setCallback() * @param buffer pointer to actual frame buffer * @param frameCount number of current frame (continuous until UINT_MAX) **/ typedef void (*tFrameEndCallbackFuncPtr)( void* ptr, tMemBufferPtr pBuffer, DWORD frameCount ); /// default constructor initializes pointers with 0 tsFrameEndCallback(); /// constructor to give initial values tsFrameEndCallback( tFrameEndCallbackFuncPtr func, void* data ); tFrameEndCallbackFuncPtr pFunc; ///< callback function pointer void* pData; ///< pointer to data for callback function }; /// a range type for all the properties in Grabber struct tsPropertyRange { long min; long max; }; class GrabberPImpl; /** This class provides the interface to the device. * * Most of the methods return a boolean value. If false or 0 is returned by a method an Error * may have occurred. You can check this with getLastError(), which returns the last occurred error. * * @see Error **/ class _UDSHL_EXP_API Grabber { public: Grabber(); virtual ~Grabber(); /// Video properties. typedef VideoProcAmpProperty tVideoPropertyEnum; /// Camera properties. typedef CameraControlProperty tCameraPropertyEnum; /// VideoCaptureDevice (i. e. device) typedef VideoCaptureDeviceItem tVideoCaptureDeviceItem; typedef std::vector<tVideoCaptureDeviceItem> tVidCapDevList; /// VideoCaptureDeviceList typedef smart_ptr<tVidCapDevList> tVidCapDevListPtr; /// input channel for device typedef AnalogChannelItem tInputChannelItem; typedef std::vector<tInputChannelItem> tInChnList; /// list of input channels typedef smart_ptr<tInChnList> tInChnListPtr; /// VideoNorm for device typedef VideoNormItem tVideoNormItem; typedef std::vector<tVideoNormItem> tVidNrmList; /// VideoNormList typedef smart_ptr<tVidNrmList> tVidNrmListPtr; /// VideoFormat for device typedef VideoFormatItem tVideoFormatItem; typedef std::vector<tVideoFormatItem> tVidFmtList; /// VideoFormatList typedef smart_ptr<tVidFmtList> tVidFmtListPtr; // VideoFormatDescList typedef smart_ptr<VideoFormatDesc> tVidFmtDescPtr; typedef std::vector<tVidFmtDescPtr> tVidFmtDescList; typedef smart_ptr<tVidFmtDescList> tVidFmtDescListPtr; /// Memory buffer smart pointer typedef smart_ptr<MemBufferCollection> tMemBufferCollectionPtr; /// Memory buffer smart pointer typedef smart_ptr<MemBuffer> tMemBufferPtr; /// compressor item typedef FilterInfoObject tCompressorItems; typedef std::vector<FilterInfoObject> tCompressorList; /// list of all available compressors typedef smart_ptr<tCompressorList> tCompressorListPtr; /// list of frame rates typedef std::vector<long> tFrameRateList; typedef smart_ptr<tFrameRateList> tFrameRateListPtr; typedef std::vector<double> tFPSList; typedef smart_ptr<tFPSList> tFPSListPtr; /** returns the last error. * when the last call into the library failed, returns the according error structure, else return eNOERROR. * @return the last occurred error */ Error getLastError() const; /** get all available video capture devices in a vector. * @return all available video capture devices in a vector. This may be empty. * On an error 0 is returned. **/ tVidCapDevListPtr getAvailableVideoCaptureDevices() const; /** get all available compressors * @return all available video compressors in a vector. This may be empty. * On an error 0 is returned. */ tCompressorListPtr getAvailableVideoCompressors() const; /** get all available video formats for the current device and current VideoNorm. * @return all available video formats in a vector for the current VideoNorm. This may be empty. * On an error 0 is returned. **/ tVidFmtListPtr getAvailableVideoFormats() const; /** get all available video formats for the current device and a given VideoNorm. * @return all available VideoFormats for the given VideoNorm in a vector. This may be empty. * On an error 0 is returned. * @param videonorm videonorm for which the VideoFormats are returned **/ tVidFmtListPtr getAvailableVideoFormats( const VideoNormItem& videonorm ) const; /** test if the device supports video norms * @return true if the device supports video norms **/ bool isVideoNormAvailableWithCurDev() const; /** get all supported VideoNorms supported by the device * @return all available VideoNorms in a vector. This may be empty. * On an error 0 is returned. **/ tVidNrmListPtr getAvailableVideoNorms() const; /** test if the device supports multiple input channels * @return true if the device supports multiple input channels **/ bool isInputChannelAvailableWithCurDev() const; /** get all supported input channels * @return all available input channels in a vector. This may be empty. * On an error 0 is returned. **/ tInChnListPtr getAvailableInputChannels() const; /** get current input channel * @param channel input channel to set * @return true on success, else false **/ tInputChannelItem getInputChannel() const; /** set new input channel * @param channel new input channel * @return true on success, else false **/ bool setInputChannel( const tInputChannelItem& ); /** set new input channel * @param channel new input channel * @return true on success, else false **/ bool setInputChannel( DWORD channel ); /** Opens a video capture device. * @return true on success **/ bool openDev( const VideoCaptureDeviceItem& dev ); /** Opens a video capture device. * @return true on success **/ bool openDev( const char* dev ); /** gets an item for the currently opened video device * @return the current VideoCaptureDeviceItem, on error an invalid item is returned **/ tVideoCaptureDeviceItem getDev() const; /** Closes the current opened video capture device. * @return true on success **/ bool closeDev(); /** Test if a device is open * @return true, if dev is opened **/ bool isDevOpen() const; /** Test if the device is valid (not unplugged) * @return true, if dev is valid, else false if no device is opened or current device is invalid **/ bool isDevValid() const; /** get maximum image size * @return maximum image size (width) **/ long getAcqSizeMaxX() const; /** get maximum image size * @return maximum image size (height) **/ long getAcqSizeMaxY() const; /** set the format of the sink. * this function invalidates the active MemBufferCollection, when you pass a FrameGrabberSink * with another colorformat than the colorformat of the MemBufferCollection into it. * if you want to hold a reference to the sink you should call setSinkType( const smart_ptr<GrabberSinkType>& pNewSink ) * @param newSinkType the new sink type * @return true on success * removed */ // bool setSinkType( const GrabberSinkType& newSinkType ); /** returns the current sink type. * will never fail * @return the current sink type */ const GrabberSinkType& getSinkType() const; /** returns the current sink type. * will never fail * @return the current sink type */ GrabberSinkType& getSinkType(); /** get range of certain property (e. g. hue, saturation, gamma, focus, ... ). * @param type property to query * @return range of setting (min,max) **/ tsPropertyRange getPropertyRange( tCameraPropertyEnum type ) const; /** get range of certain property (e. g. hue, saturation, gamma, focus, ... ). * @param type property to query * @return range of setting (min,max) **/ tsPropertyRange getPropertyRange( tVideoPropertyEnum type ) const; /** get the default value of a certain property * @param type property to query * @return default value for property **/ long getPropertyDefault( tCameraPropertyEnum type ) const; /** get the default value of a certain property * @param type property to query * @return default value for property **/ long getPropertyDefault( tVideoPropertyEnum type ) const; /** set properties automation state (e. g. hue, saturation, gamma, focus, ... ). * @param type property to set * @param autom true to set, false to unset automation * @return true on success **/ bool setProperty( tCameraPropertyEnum type, bool autom ); /** set properties automation state (e. g. hue, saturation, gamma, focus, ... ). * @param type property to set * @param autom true to set, false to unset automation * @return true on success **/ bool setProperty( tVideoPropertyEnum type, bool autom ); /** set properties (e. g. hue, saturation, gamma, focus, ... ). * @param type property to set * @return true on success **/ bool setProperty( tCameraPropertyEnum type, long val ); /** set properties (e. g. hue, saturation, gamma, focus, ... ). * @param type property to set * @param val value to set * @return true on success **/ bool setProperty( tVideoPropertyEnum type, long val ); /** get properties (e. g. hue, saturation, gamma, focus, ... ). * @param type property to return * @param val value to set * @return value of given property **/ long getProperty( tCameraPropertyEnum type ) const; /** get properties (e. g. hue, saturation, gamma, focus, ... ). * @param type property to return * @return value of given property **/ long getProperty( tVideoPropertyEnum type ) const; /** query automation state of properties (e. g. hue, saturation, gamma, focus, ... ). * @param type property to query * @return true, if automation is enabled for given property, else false **/ bool isPropertyAutomationEnabled( tCameraPropertyEnum type ) const; /** query automation state of properties (e. g. hue, saturation, gamma, focus, ... ). * @param type property to query * @return true, if automation is enabled for given property, else false **/ bool isPropertyAutomationEnabled( tVideoPropertyEnum type ) const; /** query availability of certain property * @param type property to query * @return true on availability of type, else false **/ bool isPropertyAvailableWithCurDev( tCameraPropertyEnum type ) const; /** query availability of certain property * @param type property to query * @return true on availability of type, else false **/ bool isPropertyAvailableWithCurDev( tVideoPropertyEnum type ) const; /** query availability of automation for certain property * @param type property to query * @return true on availability of automation for type, else false **/ bool isPropertyAutomationAvailableWithCurDev( tCameraPropertyEnum type ) const; /** query availability of automation for certain property * @param type property to query * @return true on availability of automation for type, else false **/ bool isPropertyAutomationAvailableWithCurDev( tVideoPropertyEnum type ) const; /** creates a new MemBufferCollection * @param size size of the frames * @param colorformat colorformat to use for the frames * @param count the buffer count in the collection * @return true on success **/ tMemBufferCollectionPtr newMemBufferCollection( SIZE size, tColorformatEnum colorformat, DWORD count = 1 ) const; /** creates a new MemBufferCollection. The parameters are taken from * the current Grabber (an error occurs if current Grabber is * invalid). * @param grabber a Grabber reference to get the size and colorformat * @param count the buffer count in the collection * @return true on success **/ tMemBufferCollectionPtr newMemBufferCollection( DWORD count = 1 ) const; /** creates a new MemBufferCollection * @param size size of the frames * @param colorformat colorformat to use for the frames * @param buffersize size of one buffer * @param buffers Array with buffer pointers to user allocated memory of size <code>buffersize</code> * @param count dimension of <code>buffers</code>, i. e. the length of the collection **/ tMemBufferCollectionPtr newMemBufferCollection( SIZE size, tColorformatEnum colorformat, DWORD buffersize, BYTE* buffers[], DWORD count ) const; /** creates a new MemBufferCollection. The parameters are taken from * the current Grabber (an error occurs if current Grabber is * invalid). * @param buffersize size of one buffer * @param buffers Array with buffer pointers to user allocated memory * of size <code>buffersize</code> * @param count dimension of <code>buffers</code>, i. e. the length of * the collection **/ tMemBufferCollectionPtr newMemBufferCollection( DWORD buffersize, BYTE* buffers[], DWORD count ) const ; /** set active memory buffer for grabbing. * This method invalidates all the buffers set with pushBackUserMemBuffer(). * @param pBuffer buffer to use for grabbing or 0 to reset internal setting * @return true on success **/ bool setActiveMemBufferCollection( tMemBufferCollectionPtr pBuffer ); /** get active memory buffer for grabbing * @return Buffer used for grabbing **/ tMemBufferCollectionPtr getActiveMemBufferCollection() const; /** get active MemBuffer. A pointer to a buffer containing the last acquired image is returned * @return pointer to actual buffer or 0 if no buffer is active **/ tMemBufferPtr getActiveMemBuffer() const; /** get currently necessary size of a UserMemBuffer * @return the size of a frame in bytes according to the current colorformat and region of interest **/ DWORD getUserMemBufferSize() const; // in bytes /** Start live mode. * This operation may take relatively long and can fail due to many different reasons. So check the error * value after the call of this method. * @param show_videowindow true to enable the live video window, false to grab only. * @return true on success **/ bool startLive( bool show_videowindow = true ); /** stop live mode * @return true on success **/ bool stopLive(); /** test of live mode * @return true if live mode is on **/ bool isLive() const; /** snaps some images in the currently active buffer at the currently active position. * This function will only work, if live mode is active. * @param count the number of frames to acquire (default: 1) * @param timeout if 0xFFFFFFFF then the function may block indefinitely, otherwise the function waits for timeout * milliseconds. When the timeout is reached, the system may snap the remaining frames if the system does commence. * this parameter is only intended to reduce hangups when no samples are delivered by the device * @return true on success otherwise false **/ bool snapImages( DWORD count = 1, DWORD timeout = 0xFFFFFFFF ); /** get current videonorm * @return current videonorm **/ VideoNormItem getVideoNorm() const; /** set current video norm * @param videonorm videonorm to set as current * @return true on success, else false **/ bool setVideoNorm( const VideoNormItem& videonorm ); /** get current videoformat (for acquisition) * @return current videoformat **/ VideoFormatItem getVideoFormat() const; /** set current videoformat (for acquisition) * @param videoformat videoformat to set * @return true on success, else false **/ bool setVideoFormat( const VideoFormatItem& videoformat ); /** set Window for live grabbing * @param hwnd window handle for the window to use * @return true on success **/ bool setHWND( HWND hwnd ); /** get current HWND for live grabbing * @return null if no handle is set, else the handle **/ HWND getHWND() const; /** set callback function pointer * @param callback structure with callback information (default is reset) * @return true on success, else false **/ bool setCallback( const tsFrameEndCallback& callback = tsFrameEndCallback() ); /** get callback function pointer * @return callback function pointer or 0 on error **/ tsFrameEndCallback getCallback() const; /** get current frame count * @return content of internal frame counter **/ DWORD getFrameCount() const; /** flip image horizontal. * @param flip true flip, false do not flip * @return true on success **/ bool setFlipH( bool flip = true ); /** get current horizontal flip state * @return current flip state or false if any error occurs * @see setFlip() **/ bool getFlipH() const; /** returns if flip horizontal is available. * @return current flip state or false if any error occurs * @see setFlip() **/ bool isFlipHAvailable() const; /** returns true if the current video capture device has an external transport control */ bool hasExternalTransport() const; /** this function sets the Mode of the ExternalTranport Module if present * for an overview of all available modes see IAMExtTransport::put_Mode */ bool setExternalTransportMode( long ); /** retrieve the current mode of the External Transport Device */ long getExternalTransportMode() const; /** returns the frame rates available for this videoformat. * the rates describe the time from the start of one frame to the next in milliseconds */ tFrameRateListPtr getAvailableFrameRates( const VideoFormatItem& op ) const; /** returns the frame rates available for the current videoformat. * the rates describe the time from the start of one frame to the next in milliseconds */ tFrameRateListPtr getAvailableFrameRates() const; /** retrieve the actual frame rate achieved by the device. * the rates describe the time from the start of one frame to the next in milliseconds<br> * only available in live mode */ long getCurrentActualFrameRate() const; /** sets the frame rate to achieve by the device. * the rates describe the time from the start of one frame to the next in milliseconds<br> * only available outside live mode */ bool setFrameRate( long rate ); /** gets the frame rate which is currently set. * the rates describe the time from the start of one frame to the next in milliseconds<br> */ long getFrameRate() const; /** returns if the current device has and may use an external trigger. * <strong>this may return false information for devices, that implement internal trigger support</strong> */ bool hasExternalTrigger() const; /** sets the External Trigger on/off. * only available outside live mode * @param m when true the external trigger is enabled, else disabled. */ bool setExternalTrigger( bool m ); /** returns the current setting for the External Trigger. * @return true if it is enabled, else false */ bool getExternalTrigger() const; // new in 1.4 /////// /** flip image vertical. * @param flip true flip, false do not flip * @return true on success **/ bool setFlipV( bool flip = true ); /** get current vertical flip state * @return current flip state or false if any error occurs * @see setFlip() **/ bool getFlipV() const; /** returns if flip vertical is available. * @return current flip state or false if any error occurs * @see setFlip() **/ bool isFlipVAvailable() const; /** sets the position of the video in the live window. * the settings are invalidated by a call to setVideoFormat when getDefaultWindowPosition() == true, otherwise * the settings will not be invalidated by any call to the grabber object. * calling this when the graph is running directly influences the live display. * @param x0 the offset left from the window origin * @param y0 the offset down from the window origin * @return true on success otherwise getLastError() returns the error value. */ bool setWindowPosition( long x0, long y0 ); /** sets the size of the video in the live window. * the settings are invalidated by a call to setVideoFormat when getDefaultWindowPosition() == true, otherwise * the settings will not be invalidated by any call to the grabber object. * calling this when the graph is running directly influences the live display. * @param width the width of the video display in the window. Must be >= 0, otherwise an error is returned. * @param height the height of the video display in the window. Must be >= 0, otherwise an error is returned. * @return true on success otherwise getLastError() returns the error value. */ bool setWindowSize( long width, long height ); /** resets the live window position and size to the defaults (x0 = 0, y0 = 0, w = getAcqSizeMaxX(), h = getAcqSizeMaxY() ) */ bool setWindowPosition(); /** fills the parameters with the current values. */ bool getWindowPosition( long& x0, long& y0, long& w, long& h ) const; /** sets if the window position is reset by a call to VideoFormat. * @param b if b == true then a change of the VideoFormat will change the dimensions */ bool setDefaultWindowPosition( bool b ); /** returns if DefaultWindowPosition is set. */ bool getDefaultWindowPosition() const; /** attaches a new listener object. * @param pListener pointer to the object derived from GrabberListener used as message sink. * the object pointed to by pListener must live at least as long as the object is registered. * @param reg the callbacks for which the object will be registered. This can be any combination of the flags * defined by GrabberListener::tListenerType. * -1 is interpreted as GrabberListener::eALL. * @return true on success, otherwise false */ bool addListener( GrabberListener* pListener, DWORD reg = -1 ); /** removes a listener object for all of the registration values you passed in. * When an entry (pListener,reg) does not exist, the method does nothing for that entry. * When a CB is currently running for one entry removeListener returns false and removing for that entry * is postponed until the CB returns. * (You can check if the listener was removed by calling isListenerRegistered). * If no CB is running on the listener object, the entry is removed and the method returns true. * @param pListener pointer to the object derived from GrabberListener which was previously registered. * @param reg the methods may be called by the Grabber object. The flags are defined by GrabberListener::tListenerType. * -1 is interpreted as GrabberListener::eALL. * @return True when all entries were immediately removed from the list. * False when one or more entries could not be immediately removed */ bool removeListener( GrabberListener* pListener, DWORD reg = -1 ); /** returns if the listener object is registered for any of the passed registration values. * @param pListener the listener to check * @param reg the type for the listener is tested to be registered. * @return true if the listener is registered under any of the types passed in by reg, else false */ bool isListenerRegistered( GrabberListener* pListener, DWORD reg = -1 ); /** returns an overlay surfaces which is rendered into the stream */ smart_ptr<OverlayBitmap> getOverlay() const; /** set the format of the sink. * this function invalidates the active MemBufferCollection, when you pass a FrameGrabberSink * with another colorformat than the colorformat of the MemBufferCollection into it. * @param pNewSink the new sink type * @return true on success */ bool setSinkType( const smart_ptr<GrabberSinkType>& pNewSink ); /** returns the current reference time in 100 nanoseconds (or 1/10000 milliseconds). * the value depends on the ReferenceClock used in the graph (but is mostly equivalent to QueryPerformanceCounter). * the method fails when no reference clock is available. * @param Current gets the value of the current reference time. * @return true on success, otherwise false and an error value is set. */ bool getCurReferenceTime( REFERENCE_TIME& Current ) const; /** returns the reference time used when the graph was started in 100 nanoseconds (or 1/10000 milliseconds). * the value depends on the ReferenceClock used in the graph (but is mostly equivalent to QueryPerformanceCounter). * the method fails when no reference clock is available. * @param GraphStart gets the value of the reference start time of the graph. * @return true on success, otherwise false and an error value is set. */ bool getGraphStartReferenceTime( REFERENCE_TIME& GraphStart ) const; /////////////////////////////////////////////// // new in version 2.0 /////////////////////////// smart_com<IVCDPropertyItems> getAvailableVCDProperties() const; /** Returns if a device supports querying it, if an video stream is available for the device. * @return */ bool isSignalDetectedAvailable() const; /** returns if a signal was detected by the device. This flag is only thought for devices * which get a signal from an external device, e.g. a converter which gets its video * from a analog camera. * @return true the driver of the device said that a signal was detected. false when * either the driver said no signal was detected or when an error occurred * (e.g. option not available). */ bool getSignalDetected() const; /** Returns if the device supports a list of frame rates, which the user can set. * @return true/false */ bool isFrameRateListAvailable() const; bool isFrameRateListAvailable( const VideoFormatItem& op ) const; /** Returns the frame rates available for this videoformat. * the rates describe the time from the start of one frame to the next in milliseconds */ tFPSListPtr getAvailableFPS( const VideoFormatItem& op ) const; /** Returns the frame rates available for the current videoformat. * the rates describe the time from the start of one frame to the next in milliseconds */ tFPSListPtr getAvailableFPS() const; /** Retrieve the actual frame rate achieved by the device. * the rates describe the time from the start of one frame to the next in milliseconds<br> * only available in live mode */ double getCurrentActualFPS() const; /** Returns the current maximal fps the device can achieve on the bus. * This may be different from the maximal fps in the fps list, due to several devices which run * on the same bus and have to share the bandwidth. * If you set a higher frame rate than the one returned by this function, the call to startLive may * fail because the device cannot be started at the rate. This leads to the error "Failed to connect * the pins." * @return The FPS. This may be 0 when the device does not support this property or cannot supply it * in the current mode of operation. * (some devices need to be started to retrieve this setting (this is a bit odd in some drivers ;-) ) */ double getCurrentMaxAvailableFPS() const; /** sets the frame rate to achieve by the device. * only available outside live mode */ bool setFPS( double fps ); /** gets the frame rate which is currently set. */ double getFPS() const; /** Returns if the device supports retrieving the current dropped frames counter. * @return true/false */ bool isCountOfFramesDroppedAvailable() const; /** Returns the number of frames dropped by the VideoCaptureDevice. * @return The number of frames dropped by the VideoCaptureDevice. * May be == 0 when the device does not export this property. */ long getCountOfFramesDropped() const; /** Returns the number of frames the VideoCaptureDevice send, which were not dropped by the device. * This doesn't mean these frames were delivered, because some frames can be dropped along the way. * @return The number of frames not dropped by the VideoCaptureDevice. * May be == 0 when the device does not export this property. */ long getCountOfFramesNotDropped() const; /** Sets the pause mode. * In live mode the video is immediately paused. Outside live mode the mode is saved and will be set * when a startLive is called. * @return true on success, otherwise false. */ bool setPauseLive( bool on ); /** Returns if the pause mode is enabled. * @return true when the pause mode is enabled. */ bool getPauseLive() const; /** Shows the property page for this device. * \param title The title to show. * \param hParent The parent window of this property page. If this is 0, then the active window is used * because the page needs to be modal!! * \return true on success, otherwise false. */ bool showVCDPropertyPage( HWND hParent = 0, const std::string& title = "" ); bool showVCDPropertyPage( HWND hParent, const std::wstring& title ); /** Shows a device settings page to choose a device and several other options for this device. * \param hParent The parent of this modal page. If this is 0, then the active window is used * because the page needs to be modal!! * \param excludeDevices A vector containing names of the devices that are not displayed in the * device selection combo box. This is useful to hide devices that are already opened by * the calling application. * \return true when the user clicked OK to exit the page, false if he clicked CANCEL or an error occurred. */ bool showDevicePage( HWND hParent = 0 ); bool showDevicePage( HWND hParent, const std::vector<std::string>& excludeDevices ); bool showDevicePage( HWND hParent, const std::vector<std::wstring>& excludeDevices ); bool openDev( const std::string& devstring ); bool openDev( const std::wstring& devstring ); bool openDev( const __int64& serial ); bool setVideoFormat( const std::string& videoformatstring ); bool setVideoFormat( const std::wstring& videoformatstring ); bool setVideoNorm( const std::string& videonormstring ); bool setVideoNorm( const std::wstring& videonormstring ); bool setInputChannel( const std::string& inputchannel ); bool setInputChannel( const std::wstring& inputchannel ); bool openDevByUniqueName( const std::string& unique_name ); bool openDevByUniqueName( const std::wstring& unique_name ); bool openDevByDisplayName( const std::string& display_name ); bool openDevByDisplayName( const std::wstring& display_name ); /** Saves the grabber settings to a xml string. Following settings are saved : * - Opened device (and serial) * - Video norm * - Video Format * - Input Channel * - FPS * - FlipH * - FlipV * - VCR compatibility * - VCD Properties */ std::string saveDeviceState() const; std::wstring saveDeviceStateW() const; /** Restores a saved grabber state */ bool loadDeviceState( const std::string& xmlStr, bool bOpenDev = true ); bool loadDeviceState( const std::wstring& xmlStr, bool bOpenDev = true ); /** Saves the grabber state to a file */ bool saveDeviceStateToFile( const std::string& filename ) const; bool saveDeviceStateToFile( const std::wstring& filename ) const; /** Loads the grabber state from a file */ bool loadDeviceStateFromFile( const std::string& filename, bool bOpenDev = true ); bool loadDeviceStateFromFile( const std::wstring& filename, bool bOpenDev = true ); /////////////////////////////////////////////// // new in version 3.0 /////////////////////////// /** sets the position of the OverlayBitmap in the graph. * You can set the position before calling startLive, when the graph is running you cannot change the position. * The Graph position is saved as long as the grabber object instance lives and is not invalidated by closing * the current device. * @see tPathPosition for the available positions the overlay bitmap can take in the graph. * @param OVBPathPositions An or'ed value which contains all path positions which should be enabled. * @return true on success, otherwise false and getLastError returns an error description. */ bool setOverlayBitmapPathPosition( DWORD OVBPathPositions ); /** returns the current position of the OverlayBitmap in the graph. * @see tPathPosition for the available positions the overlay bitmap can take in the graph. * @return true on success, otherwise false and getLastError returns an error description. */ DWORD getOverlayBitmapPathPosition() const; /** Returns a pointer to the current sink. * @return 0 when no sink is set. */ smart_ptr<GrabberSinkType> getSinkTypePtr() const; /** This methods allow fine grained control over what is saved to the string/file. * @param bDevice If the device should be saved * @param bGrabberDeviceSetup If the following device settings should be saved: * <ul> * <li>Video norm</li> * <li>Video format</li> * <li>Input Channel</li> * <li>FPS</li> * <li>FlipH/V</li> * <li>VCRCompatibility</li> * </ul> * @param bVCDProperties If the VCDProperties should be saved * @return the string. */ std::string saveDeviceState( bool bDevice, bool bGrabberDeviceSetup = true, bool bVCDProperties = true ) const; std::wstring saveDeviceStateW( bool bDevice, bool bGrabberDeviceSetup = true, bool bVCDProperties = true ) const; bool saveDeviceStateToFile( const std::string& filename, bool bDevice, bool bGrabberDeviceSetup = true, bool bVCDProperties = true ) const; bool saveDeviceStateToFile( const std::wstring& filename,bool bDevice, bool bGrabberDeviceSetup = true, bool bVCDProperties = true ) const; /** Sets one device frame filter for the grabber. You can only set filters when the graph is stopped. * These new frame filters will be placed right behind the VideoCaptureDevice. * * Any previous installed frame filters are removed. * If you pass in 0, no new frame filter will be installed. * @param pFrameFilter The new frame filter you want to use. This must not be deleted * while it is set in the grabber. * @return true on success, false otherwise. */ bool setDeviceFrameFilters( IFrameFilter* pFrameFilter ); /** Sets one or more device frame filters for the grabber. You can only set filters when the graph is stopped. * These new frame filters will be placed right behind the VideoCaptureDevice. * * Any previous installed frame filters are removed. * If you pass an empty list, no new frame filter will be installed. * @param lst The new frame filters you want to use. These must not be deleted * while they are set in the grabber. * @return true on success, false otherwise. */ bool setDeviceFrameFilters( const tFrameFilterList& lst ); /** Returns a list of frame filters set by setDeviceFrameFilters. * @return Either the list of currently set frame filters, or an empty list when no frame filters are set. */ const tFrameFilterList getDeviceFrameFilters() const; /** Returns the actual dimension of the data which is passed to the video window. * This may be different from the VideoFormat, when you use DeviceFrameFilters/DisplayFrameFilters and * it may be different from the FrameHandlerSink dimensions. * * You can only retrieve this information, when the graph is already built. * @param dim Will be filled with the dimension of the video data stream, which arrives at the VideoRenderer. * @return true when dim could be filled with the actual dimensions, otherwise false. */ bool getVideoDataDimension( SIZE& dim ) const; /** Tries to create the graph and then disconnects the VideoCaptureDevice. * You can use this to save time when building the graph. * * No operation which may change the graph layout is permitted after prepareLive is called. * * So following operations are not permitted : * <ul> * <li>setVideoFormat</li> * <li>setFrameRate/setFPS</li> * <li>setVideoNorm</li> * <li>setSinkType</li> * <li>setOverlayBitmapPathPosition</li> * <li>setTrigger</li> * <li>setFlipH/V</li> * <li>...</li> * </ul> * * The methods stopLive and closeDev end this mode. * * @param bUseVideoRenderer If a VideoRenderer should be used. @see Grabber::startLive. * @return true on success, otherwise false. */ bool prepareLive( bool bUseVideoRenderer ); /** Returns if the graph is prepared, but not yet started. * @return true/false. */ bool isLivePrepared() const; /** Suspends a running graph. * A running graph so gets prepared. * * When the operation fails, the graph is set to the stopped state. * @return true on success, otherwise false. */ bool suspendLive(); /** Sets one display frame filter for the grabber. You can only set filters when the graph is stopped. * These new frame filters will be placed right in front of the VideoRenderer. * * Any previous installed frame filters are removed. * If you pass in 0, no new frame filter will be installed. * @param pFrameFilter The new frame filter you want to use. This must not be deleted * while it is set in the grabber. * @return true on success, false otherwise. */ bool setDisplayFrameFilters( IFrameFilter* pCB ); /** Sets one or more device frame filters for the grabber. You can only set filters when the graph is stopped. * These new frame filters will be placed right in front of the VideoRenderer. * * Any previous installed frame filters are removed. * If you pass an empty list, no new frame filter will be installed. * @param lst The new frame filters you want to use. These must not be deleted * while they are set in the grabber. * @return true on success, false otherwise. */ bool setDisplayFrameFilters( const tFrameFilterList& lst ); /** Returns a list of frame filters set by setDeviceFrameFilters. * @return Either the list of currently set frame filters, or an empty list when no frame filters are set. */ const tFrameFilterList getDisplayFrameFilters() const; /** Returns the control interface for the DeBayerTransform filter, which may be used in * the grabber to implicitly debayer a stream. * @return should never be 0, */ smart_ptr<DeBayerTransform> getDeBayerTransform() const; /** This method fetches the according OVB from the internal list of usable OVB objects. * @param PathPositionToFetch The position of the OVB to fetch. * @return 0 if an invalid index was passed, otherwise the according object. */ smart_ptr<OverlayBitmap> getOverlay( tPathPosition PathPositionToFetch ) const; /** Alters the behavior of the setProperty/setPropertyAutomation/... etc. functions. * Do not use when you create a new Application. */ void setOldPropertyBehavior( bool bBehavior ); bool getOldPropertyBehavior() const; /** Retrieves the list of interfaces, retrieved from the graph. * This should be used with caution, as not to hold things, you shouldn't keep open. * * Beware, that this method does not set the last error var. * \param itf_guid The IID of the interfaces to retrieve. * \param vec List, where the interfaces will be added to. * \return false, when no graph is build, etc. */ typedef std::vector<smart_com<IUnknown> > tGraphItfList; bool getGraphInterfaceList( const GUID& itf_guid, tGraphItfList& vec ); /** Internal interface. Do not use. */ //IDispEventDispatcher& getEventDispatcher(); tVidFmtDescListPtr getAvailableVideoFormatDescs() const; tVidFmtDescListPtr getAvailableVideoFormatDescs( const VideoNormItem& videoNorm ) const; private: GrabberPImpl* m_pP; }; } #endif // !defined(AFX_GRABBER_H__F72DCE0B_3C5C_44EA_BFAB_ADDE04304CA6__INCLUDED_)
[ "qdh8087@gmail.com" ]
qdh8087@gmail.com
1867b3a849976bfe07c15fd76fbcded58af6f75c
6cb9d8be6814d03099ad0d2d7367501bc45d5419
/Singularity/Code/World.cpp
d9cc05f749ca717039b054c792e82d39adbb908d
[]
no_license
y2kiah/singularity
ae7f5cdc627bf3cf79cc85a1b2db5cdd4a37980b
a489e6e1997bd220322466073b3dfcad8045ec6f
refs/heads/master
2020-09-27T01:24:51.329042
2019-12-06T18:55:52
2019-12-06T18:55:52
226,389,561
0
0
null
null
null
null
UTF-8
C++
false
false
7,188
cpp
/* ----==== WORLD.CPP ====---- */ #include <GL\glew.h> #include <cmath> #include <fstream> #include "world.h" #include "world_console.h" #include "engine.h" #include "options.h" #include "player.h" #include "frustum.h" #include "console.h" #include "texturemanager.h" #include "meshmanager.h" #include "shadermanager.h" #include "objectmanager.h" /*------------------ ---- STRUCTURES ---- ------------------*/ ////////// class Level ////////// bool Level::loadLevel(const std::string &filename) { bool nameDone = false, heightDone = false, groundDone = false, groundMapDone = false; bool detailDone = false, skyDone = false, shaderDone = false; std::string inStr; levelLoaded = false; loadError = true; console.addLine(Color3f(1,1,1),"loading level \"%s\"",filename.c_str()); std::ifstream inFile(filename.c_str()); if (!inFile) { console.addLineErr(" file \"%s\" not found",filename.c_str()); inFile.close(); return false; } while (!inFile.eof()) { inStr.clear(); std::getline(inFile,inStr); if (inStr == "[LEVEL NAME]") { nameDone = true; std::getline(inFile,levelName); } else if (inStr == "[HEIGHTMAP]") { heightDone = true; float hSpacing, vSpacing, texStretch, detTexStretch, detDist; std::getline(inFile,inStr); inFile >> hSpacing; inFile >> vSpacing; inFile >> texStretch; inFile >> detTexStretch; inFile >> detDist; terrain = new Terrain(gOptions.CHUNKSIZE, hSpacing, vSpacing, texStretch, detTexStretch, detDist); if (!terrain->loadRAW(std::string("data/level/")+inStr)) { console.addLineErr(" file \"%s\" not found", inStr.c_str()); inFile.close(); return false; } } else if (inStr == "[GROUND TEXTURES]") { if (!terrain) { console.addLineErr(" section [GROUND TEXTURES] must be after section [HEIGHTMAP]"); inFile.close(); return false; } groundDone = true; int texCount = 0; inFile >> texCount; std::getline(inFile,inStr); terrain->groundTexID = new unsigned int[texCount]; int texID; for (int t = 0; t < texCount; t++) { std::getline(inFile,inStr); texID = texture.loadFromFile(std::string("data/textures/")+inStr, GL_REPEAT, GL_MODULATE, true, true, true, false); if (texID == -1) { inFile.close(); return false; } else { terrain->groundTexID[t] = texID; // Store the global ID after loading the texture so } } // find number of lookups to use int numLookups = texCount / 4; if (texCount % 4 > 0) numLookups++; terrain->lookupTexID = new unsigned int[numLookups]; for (int l = 0; l < numLookups; l++) { std::getline(inFile,inStr); texID = texture.loadFromFile(std::string("data/textures/")+inStr, GL_CLAMP_TO_EDGE, GL_DECAL, false, true, false, false); if (texID == -1) { inFile.close(); return false; } else { terrain->lookupTexID[l] = texID; } } } else if (inStr == "[GROUND MAP TEXTURES]") { if (!terrain) { console.addLineErr(" section [GROUND MAP TEXTURES] must be after section [HEIGHTMAP]"); inFile.close(); return false; } groundMapDone = true; int texCount = 0; inFile >> texCount; std::getline(inFile,inStr); terrain->layerTexID = new unsigned int[texCount]; int texID; for (int t = 0; t < texCount; t++) { std::getline(inFile,inStr); texID = texture.loadFromFile(std::string("data/textures/")+inStr, GL_REPEAT, GL_MODULATE, true, true, true, false); if (texID == -1) { inFile.close(); return false; } else { terrain->layerTexID[t] = texID; // Store the global ID after loading the texture so } } // find number of lookups to use int numLookups = texCount / 4; if (texCount % 4 > 0) numLookups++; terrain->layerMapTexID = new unsigned int[numLookups]; for (int l = 0; l < numLookups; l++) { std::getline(inFile,inStr); texID = texture.loadFromFile(std::string("data/textures/")+inStr, GL_CLAMP_TO_EDGE, GL_DECAL, false, true, false, false); if (texID == -1) { inFile.close(); return false; } else { terrain->layerMapTexID[l] = texID; } } }/* else if (inStr == "[DETAIL OBJECT TEXTURES]") { if (!terrain) { console.addLineErr(" section [DETAIL OBJECT TEXTURES] must be after section [HEIGHTMAP]"); inFile.close(); return false; } detailDone = true; int texcount = 0; inFile >> texcount; std::getline(inFile,inStr); detailTexture = new unsigned int[texcount]; for (int c = 0; c < texcount; c++) { std::getline(inFile,inStr); int texID = texture.loadFromFile("data/texture/"+inStr, GL_CLAMP_TO_EDGE, GL_MODULATE, true, true, true); if (texID == -1) { inFile.close(); return false; } else { detailTexture[c] = texID; } } }*/ else if (inStr == "[SKYBOX]") { skyDone = true; std::getline(inFile,inStr); skyBox = new Skybox; if (!skyBox->loadSkybox(std::string("data/level/")+inStr)) { console.addLineErr(" error loading skybox"); inFile.close(); return false; } } else if (inStr == "[SHADERS]") { if (!terrain) { console.addLineErr(" section [SHADERS] must be after section [HEIGHTMAP]"); inFile.close(); return false; } shaderDone = true; std::getline(inFile,inStr); int shaderID = shader.loadFromFile(std::string("data/shaders/"+inStr+".vert"), std::string("data/shaders/"+inStr+".frag")); if (shaderID == -1) { inFile.close(); return false; } else { terrain->terShaderID = shaderID; // store the terrain shader ID } } } inFile.close(); // Check if all sections loaded if (!nameDone) console.addLineErr(" [LEVEL NAME] section not found in \"%s\"",filename); if (!heightDone) console.addLineErr(" [HEIGHTMAP] section not found in \"%s\"",filename); if (!groundDone) console.addLineErr(" [GROUND TEXTURES] section not found in \"%s\"",filename); if (!groundMapDone) console.addLineErr(" [GROUND MAP TEXTURES] section not found in \"%s\"",filename); // if (!detailDone) console.addLineErr(" [DETAIL OBJECT TEXTURES] section not found in \"%s\"",filename); if (!skyDone) console.addLineErr(" [SKYBOX] section not found in \"%s\"",filename); if (!shaderDone) console.addLineErr(" [SHADERS] section not found in \"%s\"",filename); levelLoaded = nameDone && heightDone && groundDone && groundMapDone && /*detailDone &&*/ skyDone && shaderDone; loadError = !levelLoaded; return levelLoaded; } bool Level::unloadLevel(void) { if (levelLoaded || loadError) { console.addLine(" level \"%s\" unloaded",levelName.c_str()); delete terrain; delete skyBox; objectMgr.clearInstances(); objectMgr.clearTypes(); mesh.clear(); texture.clear(); terrain = 0; skyBox = 0; levelName.clear(); levelLoaded = false; loadError = false; return true; } return false; } Level::Level() : Singleton<Level>(*this) { levelLoaded = false; loadError = false; terrain = 0; skyBox = 0; levelName.clear(); cHandler = new Level_CAccess; } Level::~Level() { unloadLevel(); delete cHandler; }
[ "y2kiah@hotmail.com" ]
y2kiah@hotmail.com
11030a3d01c2d0dd08bcbebfce90e2f95f94ab31
20560888f97b922dc4cba544027b19acdd6ee4d6
/libraries/SinricPro_Generic/examples/Generic/Switch/Generic_WiFiNINA/Generic_WiFiNINA_MultiSwitch_beginner/Generic_WiFiNINA_MultiSwitch_beginner.ino
d937f1077c1a41cfad8fbc723c8f50cb4e1f97d0
[ "MIT" ]
permissive
WellingtonSouzaAbreu/Arduino-code
6b8c419f2876d47966f8738e461d3a280e36ba71
0b6c18b3849717fbb8dff8ed2d210965055adcec
refs/heads/master
2023-07-09T22:37:40.610906
2021-08-10T01:36:15
2021-08-10T01:36:15
314,090,841
0
0
null
null
null
null
UTF-8
C++
false
false
3,122
ino
/**************************************************************************************************************************** Generic_WiFiNINA_MultiSwitch_beginner.ino For Generic boards, running WiFiNINA Based on and modified from SinricPro libarary (https://github.com/sinricpro/) to support other boards such as SAMD21, SAMD51, Adafruit's nRF52 boards, etc. Built by Khoi Hoang https://github.com/khoih-prog/SinricPro_Generic Licensed under MIT license Copyright (c) 2019 Sinric. All rights reserved. Licensed under Creative Commons Attribution-Share Alike (CC BY-SA) This file is part of the Sinric Pro (https://github.com/sinricpro/) **********************************************************************************************************************************/ // STM32 Boards supported: Nucleo-144, Nucleo-64, Nucleo-32, Discovery, STM32F1, STM32F3, STM32F4, STM32H7, STM32L0, etc. // SAM DUE // Teensy 4.1, 4.0, 3.6, 3.5, 3.2/3.1, 3.0 #include "defines.h" #include "SinricPro_Generic.h" #include "SinricProSwitch.h" bool onPowerState1(const String &deviceId, bool &state) { Serial.println("Device 1 turned " + String(state ? "on" : "off")); return true; // request handled properly } bool onPowerState2(const String &deviceId, bool &state) { Serial.println("Device 2 turned " + String(state ? "on" : "off")); return true; // request handled properly } bool onPowerState3(const String &deviceId, bool &state) { Serial.println("Device 3 turned " + String(state ? "on" : "off")); return true; // request handled properly } bool onPowerState4(const String &deviceId, bool &state) { Serial.println("Device 4 turned " + String(state ? "on" : "off")); return true; // request handled properly } // setup function for WiFi connection void setupWiFi() { Serial.println("\n[Wifi]: Connecting"); WiFi.begin(WIFI_SSID, WIFI_PASS); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(250); } Serial.print("\n[WiFi]: IP-Address is "); Serial.println(WiFi.localIP()); } // setup function for SinricPro void setupSinricPro() { // add devices and callbacks to SinricPro SinricProSwitch& mySwitch1 = SinricPro[SWITCH_ID_1]; mySwitch1.onPowerState(onPowerState1); SinricProSwitch& mySwitch2 = SinricPro[SWITCH_ID_2]; mySwitch2.onPowerState(onPowerState2); SinricProSwitch& mySwitch3 = SinricPro[SWITCH_ID_3]; mySwitch3.onPowerState(onPowerState3); SinricProSwitch& mySwitch4 = SinricPro[SWITCH_ID_4]; mySwitch4.onPowerState(onPowerState4); // setup SinricPro SinricPro.onConnected([]() { Serial.println("Connected to SinricPro"); }); SinricPro.onDisconnected([]() { Serial.println("Disconnected from SinricPro"); }); SinricPro.begin(APP_KEY, APP_SECRET); } // main setup function void setup() { Serial.begin(BAUD_RATE); while (!Serial); Serial.println("\nStarting Generic_WiFiNINA_MultiSwitch_beginner on " + String(BOARD_NAME)); Serial.println("Version : " + String(SINRICPRO_VERSION_STR)); setupWiFi(); setupSinricPro(); } void loop() { SinricPro.handle(); }
[ "wellingtonsouza.wsa100@gmail.com" ]
wellingtonsouza.wsa100@gmail.com
c8387fd11c0959c10aa3691c28e4076e1b949350
8dc84558f0058d90dfc4955e905dab1b22d12c08
/third_party/blink/renderer/core/loader/modulescript/module_script_loader_registry.h
c3dd895bb6586a9ebafc3902a02a5d85d4133a99
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "LGPL-2.0-only", "BSD-2-Clause", "LGPL-2.1-only" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
1,502
h
// Copyright 2017 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. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_MODULESCRIPT_MODULE_SCRIPT_LOADER_REGISTRY_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_MODULESCRIPT_MODULE_SCRIPT_LOADER_REGISTRY_H_ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/wtf/hash_set.h" namespace blink { class Modulator; class ModuleScriptFetchRequest; class ModuleScriptLoader; class ModuleScriptLoaderClient; enum class ModuleGraphLevel; // ModuleScriptLoaderRegistry keeps active ModuleLoaders alive. class CORE_EXPORT ModuleScriptLoaderRegistry final : public GarbageCollected<ModuleScriptLoaderRegistry> { public: static ModuleScriptLoaderRegistry* Create() { return new ModuleScriptLoaderRegistry; } void Trace(blink::Visitor*); ModuleScriptLoader* Fetch(const ModuleScriptFetchRequest&, ModuleGraphLevel, Modulator*, ModuleScriptLoaderClient*); private: ModuleScriptLoaderRegistry() = default; friend class ModuleScriptLoader; void ReleaseFinishedLoader(ModuleScriptLoader*); HeapHashSet<Member<ModuleScriptLoader>> active_loaders_; }; } // namespace blink #endif
[ "arnaud@geometry.ee" ]
arnaud@geometry.ee
644b49fdfbd5cd782b29bf390c543004f99e0504
59a53ffbfe19eb84ba310e66889462ce67451318
/443.compress.cpp
a85c59228171c8a67b2659ed255cf2d0d30e9faa
[]
no_license
wfnuser/leetcode
0877e03fed6617836a8c4dd695f62868d00c0f05
3202104983b4b68272766a3285ffe8683e9b1712
refs/heads/master
2022-06-29T04:16:12.874513
2022-05-25T05:52:03
2022-05-25T05:52:03
142,956,247
42
14
null
null
null
null
UTF-8
C++
false
false
755
cpp
class Solution { public: int compress(vector<char>& chars) { int slow = 0; int fast = 0; chars.push_back(' '); int cnt = 1; for (int fast = 1; fast < chars.size(); fast++) { if (chars[fast] == chars[fast-1]) { cnt++; } else { chars[slow] = chars[fast-1]; if (cnt == 1) { slow++; } else { slow++; string cs = to_string(cnt); for (auto c: cs) { chars[slow] = c; slow++; } } cnt=1; } } return slow; } };
[ "wfnuser@126.com" ]
wfnuser@126.com
c8d6c5a09e9ed41d6d33498fca1d633a8dbf8ba3
5247709841cccca956cd25c22521750227d3ef86
/src/Packages.cc
17dcc4a09f04c696351aaf06cfbf6ded45c59630
[]
no_license
caliston/packman
5b69b6f312fa75b2ef710d1c172448f21032a084
f2b47945ef25d2f7a018dab01c4f5107838605aa
refs/heads/master
2021-01-20T05:31:46.220278
2012-09-27T23:03:27
2012-09-27T23:03:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,580
cc
/********************************************************************* * Copyright 2009 Alan Buckley * * This file is part of PackMan. * * PackMan is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PackMan 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 PackMan. If not, see <http://www.gnu.org/licenses/>. * *****************************************************************************/ /* * Packages.cc * * Created on: 23-Mar-2009 * Author: alanb */ #include "Packages.h" #include "ErrorWindow.h" #include "libpkg/pkgbase.h" #include "libpkg/filesystem.h" #include <string> #include <set> #include <cstdlib> #include "swis.h" #include "tbx/swixcheck.h" #include "tbx/stringutils.h" using namespace std; Packages *Packages::_instance = 0; Packages g_packages; // Single instance of the packages Packages::Packages() : _package_base(0), _upgrades_available(DONT_KNOW) { _instance = this; } Packages::~Packages() { _instance = 0; } /** * Ensure packages have been loaded */ bool Packages::ensure_package_base() { if (!_package_base) { try { // Do not use distribution master of package database. std::string apath=pkg::canonicalise("<Packages$Dir>"); std::string dpath= pkg::canonicalise("<PackMan$Dir>.Resources.!Packages"); if ((apath!=dpath)&&(pkg::object_type(apath)!=0)) { // If the package database exists, but does not contain a // Paths file, and a Paths file does exist in the choices // directory (as used by previous versions of RiscPkg) // then copy it across. string pb_ppath=apath+string(".Paths"); string ch_ppath("Choices:RiscPkg.Paths"); if ((pkg::object_type(pb_ppath)==0)&& (pkg::object_type(ch_ppath)!=0)) { pkg::copy_object(ch_ppath,pb_ppath); } // Attempt to access package database. _package_base=new pkg::pkgbase("<Packages$Dir>","<PackMan$Dir>.Resources", "Choices:PackMan"); // Ensure that default paths are present, unless they // have been explicitly disabled by the user. bool paths_changed=_package_base->paths().ensure_defaults(); if (paths_changed) _package_base->paths().commit(); } } catch(...) { // Just delete as we will be shown the create package dialog delete _package_base; _package_base=0; } } return (_package_base != 0); } /** * Return a sorted, comma separated list of all the sections * in the given packages */ std::string Packages::sections() { if (_sections.empty()) { const pkg::binary_control_table& ctrltab = _package_base->control(); std::set<std::string> section_set; pkg::control::key_type section_key("Section"); for (pkg::binary_control_table::const_iterator i=ctrltab.begin(); i !=ctrltab.end(); ++i) { const pkg::binary_control &ctrl = i->second; pkg::control::const_iterator s = ctrl.find(section_key); if (s != ctrl.end()) section_set.insert((*s).second); } for (std::set<std::string>::iterator entry = section_set.begin(); entry != section_set.end(); ++entry) { _sections += (*entry); _sections += ","; } // Remove extra comma if (!_sections.empty()) _sections.erase(_sections.length()-1); } return _sections; } /** * Clear selection state. * * This resets the selection state to match the base state so nothing * is waiting for a commit. */ void Packages::clear_selection() { pkg::status_table & seltable = _package_base->selstat (); pkg::status_table::const_iterator i; std::set < std::string > selected; // Get list of packages with there stateClear any old selection for (i = seltable.begin(); i != seltable.end(); ++i) { pkg::status curstat = _package_base->curstat ()[i->first]; if (curstat != i->second) { selected.insert(i->first); } } for (std::set<std::string>::const_iterator reseti = selected.begin(); reseti != selected.end(); ++reseti) { pkg::status curstat = _package_base->curstat ()[*reseti]; seltable.insert(*reseti, curstat); } _package_base->fix_dependencies(selected); _package_base->remove_auto(); } /** * Unset upgrades available so they will be recalculated */ void Packages::unset_upgrades_available() { _upgrades_available = DONT_KNOW; } /** * Check if there are any upgrades available for installed packages */ bool Packages::upgrades_available() { if (_upgrades_available == DONT_KNOW) { _upgrades_available = NO; const pkg::binary_control_table& ctrltab = _package_base->control(); std::string prev_pkgname; for (pkg::binary_control_table::const_iterator i=ctrltab.begin(); i !=ctrltab.end(); ++i) { std::string pkgname=i->first.pkgname; if (pkgname!=prev_pkgname) { // Don't use i->second for ctrl as it may not be the latest version // instead look it up. prev_pkgname=pkgname; pkg::status curstat=_package_base->curstat()[pkgname]; if (curstat.state()>=pkg::status::state_installed) { const pkg::control& ctrl=_package_base->control()[pkgname]; pkg::version inst_version(curstat.version()); pkg::version cur_version(ctrl.version()); if (inst_version < cur_version) { _upgrades_available = YES; break; // Don't need to check any more } } } } } return (_upgrades_available != NO); } /** * Convert paths to path relative to Boot$Dir if possible * * @param full_path path to convert * @returns path definition relative to boot if possible * or original path if not. */ std::string Packages::make_path_definition(const std::string &full_path) { std::string result(full_path); if (tbx::find_ignore_case(full_path, ".!BOOT.") == std::string::npos) { const char *boot_path = getenv("Boot$Dir"); if (boot_path != 0 && strlen(boot_path) < result.size()) { const char *parent_end = strrchr(boot_path, '.'); if (parent_end != 0) { int match = 0; while (boot_path < parent_end && tolower(*boot_path) == tolower(result[match])) { boot_path++; match++; } if (boot_path == parent_end && result[match] == '.') { result.replace(0, match, "<Boot$Dir>.^"); } } } } return result; }
[ "alanb@RISCID.ORG@78777953-6a5e-4945-a5f6-d951f3f33b3d" ]
alanb@RISCID.ORG@78777953-6a5e-4945-a5f6-d951f3f33b3d
75a19a2983ed87ee84fb1c0dbfa688b3e9209c31
1dbf007249acad6038d2aaa1751cbde7e7842c53
/eip/include/huaweicloud/eip/v2/model/NeutronShowFloatingIpRequest.h
1d1a2f7fb3511e782cdcf261805518cd9ffc51ca
[]
permissive
huaweicloud/huaweicloud-sdk-cpp-v3
24fc8d93c922598376bdb7d009e12378dff5dd20
71674f4afbb0cd5950f880ec516cfabcde71afe4
refs/heads/master
2023-08-04T19:37:47.187698
2023-08-03T08:25:43
2023-08-03T08:25:43
324,328,641
11
10
Apache-2.0
2021-06-24T07:25:26
2020-12-25T09:11:43
C++
UTF-8
C++
false
false
1,590
h
#ifndef HUAWEICLOUD_SDK_EIP_V2_MODEL_NeutronShowFloatingIpRequest_H_ #define HUAWEICLOUD_SDK_EIP_V2_MODEL_NeutronShowFloatingIpRequest_H_ #include <huaweicloud/eip/v2/EipExport.h> #include <huaweicloud/core/utils/ModelBase.h> #include <huaweicloud/core/http/HttpResponse.h> #include <string> namespace HuaweiCloud { namespace Sdk { namespace Eip { namespace V2 { namespace Model { using namespace HuaweiCloud::Sdk::Core::Utils; using namespace HuaweiCloud::Sdk::Core::Http; /// <summary> /// Request Object /// </summary> class HUAWEICLOUD_EIP_V2_EXPORT NeutronShowFloatingIpRequest : public ModelBase { public: NeutronShowFloatingIpRequest(); virtual ~NeutronShowFloatingIpRequest(); ///////////////////////////////////////////// /// ModelBase overrides void validate() override; web::json::value toJson() const override; bool fromJson(const web::json::value& json) override; ///////////////////////////////////////////// /// NeutronShowFloatingIpRequest members /// <summary> /// floatingip的ID /// </summary> std::string getFloatingipId() const; bool floatingipIdIsSet() const; void unsetfloatingipId(); void setFloatingipId(const std::string& value); protected: std::string floatingipId_; bool floatingipIdIsSet_; #ifdef RTTR_FLAG RTTR_ENABLE() public: NeutronShowFloatingIpRequest& dereference_from_shared_ptr(std::shared_ptr<NeutronShowFloatingIpRequest> ptr) { return *ptr; } #endif }; } } } } } #endif // HUAWEICLOUD_SDK_EIP_V2_MODEL_NeutronShowFloatingIpRequest_H_
[ "hwcloudsdk@huawei.com" ]
hwcloudsdk@huawei.com