blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
75fc2947a93d4cd336abfd762b68035e0983291c
bf7cf4c0f777dc3648be7831bb4f05793cd2cf8d
/DS_Week09_Assignment/ShootingGame/util.cpp
2aaef806fcf82df18cae5d79046b478e1ab8c632
[]
no_license
aCordion/CK_2018-01-02
c846ca48ea2599f343046cedb454f60709d02b9d
7bb2c8448b10e1fccd4a06ae4489f523b0b25821
refs/heads/master
2021-08-22T15:31:39.403543
2018-12-19T11:12:32
2018-12-19T11:12:32
148,662,280
1
0
null
null
null
null
UHC
C++
false
false
1,710
cpp
#include "util.h" #include <Windows.h> static int g_nScreenIndex; static HANDLE g_hScreen[2]; void gotoxy(int x, int y) { COORD CursorPosition = {x, y}; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), CursorPosition); } void ScreenInit() { CONSOLE_CURSOR_INFO cci; // 화면 버퍼 2개를 만든다. g_hScreen[0] = CreateConsoleScreenBuffer( GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL ); g_hScreen[1] = CreateConsoleScreenBuffer( GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL ); system("title Shooting Game"); // 커서 숨기기 cci.dwSize = 1; cci.bVisible = FALSE; SetConsoleCursorInfo( g_hScreen[0], &cci ); SetConsoleCursorInfo( g_hScreen[1], &cci ); } void ScreenFlipping() { SetConsoleActiveScreenBuffer( g_hScreen[g_nScreenIndex] ); g_nScreenIndex = !g_nScreenIndex; } void ScreenClear() { COORD Coor = { 0, 0 }; DWORD dw; FillConsoleOutputCharacter( g_hScreen[g_nScreenIndex], ' ', 80*25, Coor, &dw ); } void ScreenRelease() { CloseHandle( g_hScreen[0] ); CloseHandle( g_hScreen[1] ); } void ScreenPrint( int x, int y, char *string ) { DWORD dw; COORD CursorPosition = { x, y }; SetConsoleCursorPosition( g_hScreen[g_nScreenIndex], CursorPosition ); WriteFile( g_hScreen[g_nScreenIndex], string, strlen( string ), &dw, NULL ); } // 1 ~ 15 까지 색상 설정 가능 void SetColor( unsigned short color ) { SetConsoleTextAttribute( g_hScreen[g_nScreenIndex], color ); }
[ "39215817+aCordion@users.noreply.github.com" ]
39215817+aCordion@users.noreply.github.com
f8996b741c6dae7f2769291329ea26aa8cebfbc1
e04e2a4b73f273d46a2361fef303bc829b0a00f0
/NotePadDlg.cpp
13a384b019a06222418860d8ae6bbb75ee5124b6
[]
no_license
StarLuck/University-Staff-Management
571bcd876475fd1308d75dbb2395cda780429488
0b64c8729c1d0534d62f15071a1f137fcce28a68
refs/heads/master
2020-04-11T18:06:43.248085
2018-12-16T09:35:23
2018-12-16T09:35:23
161,986,371
0
0
null
null
null
null
GB18030
C++
false
false
6,829
cpp
// NotePadDlg.cpp : implementation file // #include "stdafx.h" #include "manager.h" #include "NotePadDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CNotePadDlg dialog CNotePadDlg::CNotePadDlg(CWnd* pParent /*=NULL*/) : CDialog(CNotePadDlg::IDD, pParent) { //{{AFX_DATA_INIT(CNotePadDlg) m_strContent = _T(""); m_strSort = _T(""); m_strTitle = _T(""); m_strComments = _T(""); m_nCondition = -1; //}}AFX_DATA_INIT m_strID = "-1"; } void CNotePadDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CNotePadDlg) DDX_Control(pDX, IDC_BUTTON_NEW, m_bntNew); DDX_Control(pDX, IDC_BUTTON_MODIFY, m_bntModify); DDX_Control(pDX, IDC_BUTTON_DELETE, m_bntDelete); DDX_Control(pDX, IDOK, m_bntOK); DDX_Control(pDX, IDC_LIST1, m_ctrList); DDX_Control(pDX, IDC_COMBO_CONDITION, m_ctrCondition); DDX_Control(pDX, IDC_BUTTON_CANCEL, m_bntCancel); DDX_DateTimeCtrl(pDX, IDC_DATETIMEPICKER_DATE, m_tmDate); DDX_Text(pDX, IDC_EDIT_CONTENT, m_strContent); DDX_Text(pDX, IDC_EDIT_SORT, m_strSort); DDX_Text(pDX, IDC_EDIT_TITLE, m_strTitle); DDX_Text(pDX, IDC_RICHEDIT1, m_strComments); DDX_CBIndex(pDX, IDC_COMBO_CONDITION, m_nCondition); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CNotePadDlg, CDialog) //{{AFX_MSG_MAP(CNotePadDlg) ON_BN_CLICKED(IDC_BUTTON_NEW, OnButtonNew) ON_BN_CLICKED(IDC_BUTTON_DELETE, OnButtonDelete) ON_BN_CLICKED(IDC_BUTTON_MODIFY, OnButtonModify) ON_NOTIFY(NM_CLICK, IDC_LIST1, OnClickList1) ON_BN_CLICKED(IDC_BUTTON_CANCEL, OnButtonCancel) ON_BN_CLICKED(IDC_BUTTON_SEARCH, OnButtonSearch) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CNotePadDlg message handlers BOOL CNotePadDlg::OnInitDialog() { CDialog::OnInitDialog(); m_ctrList.InsertColumn(0,"序号"); m_ctrList.SetColumnWidth(0,40); m_ctrList.InsertColumn(1,"日期"); m_ctrList.SetColumnWidth(1,60); m_ctrList.InsertColumn(2,"类别"); m_ctrList.SetColumnWidth(2,60); m_ctrList.InsertColumn(3,"标题"); m_ctrList.SetColumnWidth(3,100); m_ctrList.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES); CString strSQL; strSQL="select * from notepad"; RefreshData(strSQL); m_bntOK.EnableWindow(FALSE); m_bntCancel.EnableWindow(FALSE); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CNotePadDlg::RefreshData(CString strSQL) { m_ctrList.SetFocus(); m_ctrList.DeleteAllItems(); m_ctrList.SetRedraw(FALSE); CString strTime; char buffer[20]; UpdateData(TRUE); if(!m_recordset.Open(AFX_DB_USE_DEFAULT_TYPE,strSQL)) { MessageBox("打开数据库失败!","数据库错误",MB_OK); return ; } int i=0; while(!m_recordset.IsEOF()) { strTime.Format("%d-%d-%d",m_recordset.m_date.GetYear(),m_recordset.m_date.GetMonth(),m_recordset.m_date.GetDay()); ltoa(m_recordset.m_ID,buffer,10); m_ctrList.InsertItem(i,buffer); m_ctrList.SetItemText(i,1,strTime); m_ctrList.SetItemText(i,2,m_recordset.m_sort); m_ctrList.SetItemText(i,3,m_recordset.m_caption); i++; m_recordset.MoveNext(); } m_recordset.Close(); m_ctrList.SetRedraw(TRUE); } void CNotePadDlg::OnButtonNew() { // TODO: Add your control notification handler code here m_strSort = ""; m_strTitle = ""; m_strComments = ""; m_strID = "-1"; m_tmDate = CTime::GetCurrentTime(); m_bntOK.EnableWindow(); m_bntCancel.EnableWindow(); UpdateData(FALSE); } void CNotePadDlg::OnButtonDelete() { // TODO: Add your control notification handler code here int i = m_ctrList.GetSelectionMark(); if(0>i) { MessageBox("请选择一条记录进行删除!"); return; } CString strSQL; strSQL.Format("select * from notepad where ID= %s ",m_ctrList.GetItemText(i,0)); if(!m_recordset.Open(AFX_DB_USE_DEFAULT_TYPE,strSQL)) { MessageBox("打开数据库失败!","数据库错误",MB_OK); return ; } //删除该用户 m_recordset.Delete(); m_recordset.Close(); //更新用户列表 strSQL="select * from notepad"; RefreshData(strSQL); m_strSort = ""; m_strTitle = ""; m_strComments = ""; UpdateData(FALSE); m_bntOK.EnableWindow(FALSE); m_bntCancel.EnableWindow(FALSE); } void CNotePadDlg::OnButtonModify() { // TODO: Add your control notification handler code here m_bntOK.EnableWindow(); m_bntCancel.EnableWindow(); } void CNotePadDlg::OnClickList1(NMHDR* pNMHDR, LRESULT* pResult) { // TODO: Add your control notification handler code here m_bntOK.EnableWindow(FALSE); m_bntCancel.EnableWindow(FALSE); CString strSQL; UpdateData(TRUE); int i = m_ctrList.GetSelectionMark(); m_strID = m_ctrList.GetItemText(i,0); strSQL.Format("select * from notepad where ID=%s",m_strID); if(!m_recordset.Open(AFX_DB_USE_DEFAULT_TYPE,strSQL)) { MessageBox("打开数据库失败!","数据库错误",MB_OK); return ; } m_strSort = m_recordset.m_sort; m_strTitle = m_recordset.m_caption; m_tmDate = m_recordset.m_date; m_strComments = m_recordset.m_comments; m_recordset.Close(); UpdateData(FALSE); *pResult = 0; } void CNotePadDlg::OnOK() { UpdateData(); if(m_strSort=="") { MessageBox("请输入类别!"); return; } CString strSQL; strSQL.Format("select * from notepad where ID= %s",m_strID); if(!m_recordset.Open(AFX_DB_USE_DEFAULT_TYPE,strSQL)) { MessageBox("打开数据库失败!","数据库错误",MB_OK); return ; } if(m_recordset.GetRecordCount()==0) {//判断用户是否存在 m_recordset.AddNew(); m_recordset.m_sort = m_strSort ; m_recordset.m_caption = m_strTitle ; m_recordset.m_date = m_tmDate ; m_recordset.m_comments = m_strComments ; m_recordset.Update(); } else {//修改用户信息 m_recordset.Edit(); m_recordset.m_sort = m_strSort ; m_recordset.m_caption = m_strTitle ; m_recordset.m_date = m_tmDate ; m_recordset.m_comments = m_strComments ; m_recordset.Update(); } m_recordset.Close(); strSQL="select * from notepad"; RefreshData(strSQL); m_bntOK.EnableWindow(FALSE); m_bntCancel.EnableWindow(FALSE); } void CNotePadDlg::OnButtonCancel() { // TODO: Add your control notification handler code here m_bntOK.EnableWindow(FALSE); m_bntCancel.EnableWindow(FALSE); } void CNotePadDlg::OnButtonSearch() { // TODO: Add your control notification handler code here UpdateData(); CString strSQL; if(0==m_nCondition) strSQL.Format("select * from notepad where sort='%s'",m_strContent); else strSQL.Format("select * from notepad where caption='%s'",m_strContent); //显示全部信息 if(m_strContent=="") strSQL = "select * from notepad"; RefreshData(strSQL); m_bntOK.EnableWindow(FALSE); m_bntCancel.EnableWindow(FALSE); }
[ "wjq776688@163.com" ]
wjq776688@163.com
d5313111c90889c225e88b89cb1a7c01e368a02f
f61b2ab296ae3aa472901af3eed218e7c7364fae
/HotLineEngineDemo/StateManager.cpp
c7c80b0504accd0fee63cf8500b95d2c32ee30f9
[]
no_license
yuragri/HLengine
491789b80b59af060906f903d7feab352da918fb
455725da55a4afe5f80cccff271b97504395e88f
refs/heads/master
2020-05-18T11:23:56.874839
2015-04-05T13:49:34
2015-04-05T13:49:34
31,547,609
0
0
null
null
null
null
UTF-8
C++
false
false
52
cpp
#include "StateManager.h" using namespace HotLine;
[ "dartem@meta.ua" ]
dartem@meta.ua
924f3058c245261e7c13408f19ffbac2b087b5e8
4de80db5134bd37099917ffe7a19befb54580970
/Arduino/Sketches/Simon_Monk/Programming Arduino-Next Steps/ArduinoNextSteps-master/ArduinoNextSteps/sketch_07_01_I2C_TEA5767/sketch_07_01_I2C_TEA5767.ino
c0e974764a2080396bb1cf237c0f4f21e020eaaf
[ "MIT" ]
permissive
ElectricRCAircraftGuy/Arduino-STEM-Presentation
519015eb8773e9ad6fe406d8188464369f6b71d8
061f4b7f1280df0442ad3f38b7f21a9eb49675b4
refs/heads/master
2022-11-02T11:51:36.288988
2020-06-15T05:13:52
2020-06-15T05:13:52
272,290,790
0
0
null
null
null
null
UTF-8
C++
false
false
506
ino
// sketch_07_01_I2C_TEA5767 #include <Wire.h> void setup() { Wire.begin(); setFrequency(93.0); // MHz } void loop() { } void setFrequency(float frequency) { unsigned int frequencyB = 4 * (frequency * 1000000 + 225000) / 32768; byte frequencyH = frequencyB >> 8; byte frequencyL = frequencyB & 0XFF; Wire.beginTransmission(0x60); Wire.write(frequencyH); Wire.write(frequencyL); Wire.write(0xB0); Wire.write(0x10); Wire.write(0x00); Wire.endTransmission(); delay(100); }
[ "ercaguy@gmail.com" ]
ercaguy@gmail.com
2f2a21c983dcb3250be737298ff30937f1fcea66
2c03fd50b31eaf9122bc2364fc566760fb9d4f46
/caffe2/modules/detectron/select_smooth_l1_loss_op.h
aa18424684e8c20499717eeffe3c124bec0336cc
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSD-2-Clause", "Apache-2.0", "MIT" ]
permissive
Ming-er/Semi-supervised-Adaptive-Distillation
c25d3a7114c65289268daa0d45af3a83c33e6576
3244dfa1a4d03e7311244687c1287b5ec26bd9ca
refs/heads/master
2022-05-04T22:17:29.123835
2019-10-09T00:40:08
2019-10-09T00:40:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,669
h
/** * Copyright (c) 2016-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SELECT_SMOOTH_L1_LOSS_OP_H_ #define SELECT_SMOOTH_L1_LOSS_OP_H_ #include "caffe2/core/context.h" #include "caffe2/core/logging.h" #include "caffe2/core/operator.h" #include "caffe2/utils/math.h" namespace caffe2 { template <typename T, class Context> class SelectSmoothL1LossOp final : public Operator<Context> { public: SelectSmoothL1LossOp(const OperatorDef& operator_def, Workspace* ws) : Operator<Context>(operator_def, ws), beta_(OperatorBase::GetSingleArgument<float>("beta", 1.)), scale_(OperatorBase::GetSingleArgument<float>("scale", 1.)), use_gt_flag(OperatorBase::GetSingleArgument<int>("use_gt_flag", 0)) { CAFFE_ENFORCE(beta_ > 0); CAFFE_ENFORCE(scale_ >= 0); } USE_OPERATOR_CONTEXT_FUNCTIONS; bool RunOnDevice() override { // No CPU implementation for now CAFFE_NOT_IMPLEMENTED; } protected: float beta_; // Transition point from L1 to L2 loss float scale_; // Scale the loss by scale_ int dim_; // dimension for 1 anchor prediction int use_gt_flag; Tensor<Context> buff_; // Buffer for element-wise differences }; template <typename T, class Context> class SelectSmoothL1LossGradientOp final : public Operator<Context> { public: SelectSmoothL1LossGradientOp(const OperatorDef& def, Workspace* ws) : Operator<Context>(def, ws), beta_(OperatorBase::GetSingleArgument<float>("beta", 1.)), scale_(OperatorBase::GetSingleArgument<float>("scale", 1.)), use_gt_flag(OperatorBase::GetSingleArgument<int>("use_gt_flag", 0)) { CAFFE_ENFORCE(beta_ > 0); CAFFE_ENFORCE(scale_ >= 0); } USE_OPERATOR_CONTEXT_FUNCTIONS; bool RunOnDevice() override { // No CPU implementation for now CAFFE_NOT_IMPLEMENTED; } protected: float beta_; // Transition point from L1 to L2 loss float scale_; // Scale the loss by scale_ int dim_; // dimension for 1 anchor prediction int use_gt_flag; Tensor<Context> buff_; // Buffer for element-wise differences }; } // namespace caffe2 #endif // SELECT_SMOOTH_L1_LOSS_OP_H_
[ "tangshitao@DESKTOP-DDJHNED.localdomain" ]
tangshitao@DESKTOP-DDJHNED.localdomain
fd5ec0f5cedeed9fd2e1a67edd4a1ba08de7863e
4e7f736969804451a12bf2a1124b964f15cc15e8
/AtCoder/other_contest/JapaneseStudentChampionship2021/D.cpp
5d595dde4a9741e0de3de64c9d43d91e56385633
[]
no_license
hayaten0415/Competitive-programming
bb753303f9d8d1864991eb06fa823a9f74e42a4c
ea8bf51c1570566e631699aa7739cda973133f82
refs/heads/master
2022-11-26T07:11:46.953867
2022-11-01T16:18:04
2022-11-01T16:18:04
171,068,479
0
0
null
null
null
null
UTF-8
C++
false
false
4,915
cpp
#pragma region Macros // #pragma GCC target("avx2") #pragma GCC optimize("O3") #include <bits/stdc++.h> #include <atcoder/all> #define rep(i, n) for (int i = 0; i < (n); i++) #define rrep(i, n) for (int i = (n - 1); i >= 0; i--) #define ALL(v) v.begin(), v.end() #define pb push_back #define eb emplace_back using namespace std; using namespace atcoder; using P = pair<int, int>; typedef long long ll; template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; const int fx[8] = {0, 1, 1, 1, 0, -1, -1, -1}; const int fy[8] = {1, 1, 0, -1, -1, -1, 0, 1}; // modint: mod 計算を int を扱うように扱える構造体 template<int MOD> struct Fp { long long val; constexpr Fp(long long v = 0) noexcept : val(v % MOD) { if (val < 0) val += MOD; } constexpr int getmod() const { return MOD; } constexpr Fp operator - () const noexcept { return val ? MOD - val : 0; } constexpr Fp operator + (const Fp& r) const noexcept { return Fp(*this) += r; } constexpr Fp operator - (const Fp& r) const noexcept { return Fp(*this) -= r; } constexpr Fp operator * (const Fp& r) const noexcept { return Fp(*this) *= r; } constexpr Fp operator / (const Fp& r) const noexcept { return Fp(*this) /= r; } constexpr Fp& operator += (const Fp& r) noexcept { val += r.val; if (val >= MOD) val -= MOD; return *this; } constexpr Fp& operator -= (const Fp& r) noexcept { val -= r.val; if (val < 0) val += MOD; return *this; } constexpr Fp& operator *= (const Fp& r) noexcept { val = val * r.val % MOD; return *this; } constexpr Fp& operator /= (const Fp& r) noexcept { long long a = r.val, b = MOD, u = 1, v = 0; while (b) { long long t = a / b; a -= t * b, swap(a, b); u -= t * v, swap(u, v); } val = val * u % MOD; if (val < 0) val += MOD; return *this; } constexpr bool operator == (const Fp& r) const noexcept { return this->val == r.val; } constexpr bool operator != (const Fp& r) const noexcept { return this->val != r.val; } friend constexpr istream& operator >> (istream& is, Fp<MOD>& x) noexcept { is >> x.val; x.val %= MOD; if (x.val < 0) x.val += MOD; return is; } friend constexpr ostream& operator << (ostream& os, const Fp<MOD>& x) noexcept { return os << x.val; } friend constexpr Fp<MOD> modpow(const Fp<MOD>& r, long long n) noexcept { if (n == 0) return 1; if (n < 0) return modpow(modinv(r), -n); auto t = modpow(r, n / 2); t = t * t; if (n & 1) t = t * r; return t; } friend constexpr Fp<MOD> modinv(const Fp<MOD>& r) noexcept { long long a = r.val, b = MOD, u = 1, v = 0; while (b) { long long t = a / b; a -= t * b, swap(a, b); u -= t * v, swap(u, v); } return Fp<MOD>(u); } }; // Binomial Coefficient template<class T> struct BiCoef { vector<T> fact_, inv_, finv_; constexpr BiCoef() {} constexpr BiCoef(int n) noexcept : fact_(n, 1), inv_(n, 1), finv_(n, 1) { init(n); } constexpr void init(int n) noexcept { fact_.assign(n, 1), inv_.assign(n, 1), finv_.assign(n, 1); int MOD = fact_[0].getmod(); for(int i = 2; i < n; i++){ fact_[i] = fact_[i-1] * i; inv_[i] = -inv_[MOD%i] * (MOD/i); finv_[i] = finv_[i-1] * inv_[i]; } } constexpr T com(int n, int k) const noexcept { if (n < k || n < 0 || k < 0) return 0; return fact_[n] * finv_[k] * finv_[n-k]; } constexpr T fact(int n) const noexcept { if (n < 0) return 0; return fact_[n]; } constexpr T inv(int n) const noexcept { if (n < 0) return 0; return inv_[n]; } constexpr T finv(int n) const noexcept { if (n < 0) return 0; return finv_[n]; } }; using mint = Fp<1000000007>; mint choose(int n, int a) { mint x = 1, y = 1; rep(i,a) { x *= n-i; y *= i+1; } return x / y; } long long modpow(long long a, long long n, long long mod) { long long res = 1; while (n > 0) { if (n & 1) res = res * a % mod; a = a * a % mod; n >>= 1; } return res; } int main() { ll n, p; cin >> n >> p; if(p == 2){ if(n != 1){ cout << 0 << endl; return 0; }else{ cout << 1 << endl; return 0; } } if(p == 3){ cout << 2 << endl; return 0; } mint res = modpow(p - 2, n-1, 1000000007); res *= (p - 1); cout << res << endl; }
[ "hayaten415@gmail.com" ]
hayaten415@gmail.com
145d485380a2c8ab08afb00549ece6b5295332c3
47267247675fb109e262a8497ad8cdb880628eb3
/hihocoder/背包问题总结.cpp
cbd12946f41447d370ce290aba963d9d326ecc0a
[]
no_license
bkyileo/algorithm-practice
2aa461f6142fe92b2619f31643ee470f901e320a
616e4db3f4f0004288441805572c186ef64541d8
refs/heads/master
2021-01-21T21:00:44.011317
2017-11-02T02:20:12
2017-11-02T02:20:12
92,297,914
1
0
null
null
null
null
GB18030
C++
false
false
2,736
cpp
// 背包问题 #include<bits/stdc++.h> #define maxw 5 #define F 15 using namespace std; int w[11]; int v[11]; int nativeDp[20][20]; int reduceDp[100]; // 0-1背包 native版本 void knapsackN(int nums) { memset(nativeDp,0,sizeof(nativeDp)); for(int i=1;i<=nums;++i) { for(int j=1;j<=maxw;++j) { if(w[i]<=j) nativeDp[i][j]=max(nativeDp[i-1][j-w[i]]+v[i],nativeDp[i-1][j]); else nativeDp[i][j]=nativeDp[i-1][j]; } } for(int i=1;i<=nums;++i) { for(int j=1;j<=maxw;++j) { cout<<nativeDp[i][j]<<" "; } cout<<endl; } } // 0-1背包 存储压缩版本 逆序 void knapsackR(int nums) { memset(reduceDp,0,sizeof(reduceDp)); for(int i=1;i<=nums;++i) { for(int j=maxw;j>0;j--) { //w[i]<=j 可以为零 就是把所有的东西拿出来 if(w[i]<=j) reduceDp[j]=max(reduceDp[j],reduceDp[j-w[i]]+v[i]); } } for(int j=1;j<=maxw;++j) { cout<<reduceDp[j]<<" "; } cout<<endl; } // 完全背包 随便放物品 void knapsackA(int nums) { memset(reduceDp,0,sizeof(reduceDp)); for(int i=1;i<=nums;++i) { for(int j=1;j<=maxw;++j) { if(w[i]<=j) reduceDp[j]=max(reduceDp[j],reduceDp[j-w[i]]+v[i]); } } for(int j=1;j<=maxw;++j) { cout<<reduceDp[j]<<" "; } cout<<endl; } //完全 反转 void knapsackRe1(int nums) { reduceDp[0]=0; for(int i=1;i<=15;++i) { reduceDp[i]=100; } for(int i=1;i<=nums;++i) { for(int j=0;j<=15;++j) if(v[i]+j>=15) reduceDp[15]=min(reduceDp[15],w[i]+reduceDp[j]); else reduceDp[ v[i]+j ]=min(reduceDp[ v[i]+j ],w[i]+reduceDp[j]); } for(int j=1;j<=15;++j) { cout<<reduceDp[j]<<" "; } cout<<endl; } //0-1 反转 void knapsackRe2(int nums) { for(int i=0;i<=15;++i) { reduceDp[i]=100; } reduceDp[0]=0; for(int i=1;i<=nums;++i) { for(int j=F;j>=0;--j) if(v[i]+j>=F) reduceDp[F]=min(reduceDp[F],w[i]+reduceDp[j]); else reduceDp[v[i]+j]=min(reduceDp[v[i]+j],w[i]+reduceDp[j]); } for(int i=1;i<=15;++i) { cout<<reduceDp[i]<<" "; } cout<<endl; } //给出 给出应有价值F 考虑背包达到F时候放入物品的最小重量的问题 /* 0-1 背包 和完全被曝两种情况 完全背包: for(int i=1;i<=nums;++i) { for(int j=0;j<=15;++j) if(v[i]+j>=15) reduceDp[15]=min(reduceDp[15],w[i]+reduceDp[j]); else reduceDp[ v[i]+j ]=min(reduceDp[ v[i]+j ],w[i]+reduceDp[j]); } 0-1 背包 ps自己实现可能有问题 用二维dp图 for(int i=1;i<=nums;++i) { for(int j=F;j>=0;--j) if(v[i]+j>=F) reduceDp[F]=min(reduceDp[F],w[i]+reduceDp[j]); else reduceDp[v[i]+j]=min(reduceDp[v[i]+j],w[i]+reduceDp[j]); } */ int main() { w[1]=2;w[2]=3;w[3]=4; v[1]=6;v[2]=10;v[3]=13; knapsackRe1(3); knapsackRe2(3); return 0; }
[ "bkyifanleo@gmail.com" ]
bkyifanleo@gmail.com
3507b3b886cdec9d4d958b20bea7a31c6fd7d07d
12154201c2c4dc8968b690fa8237ebfe1932f60a
/BOJ/5656.cpp
6c63eb3862347ae0b592d0609e039a52375bf19c
[]
no_license
heon24500/PS
9cc028de3d9b1a26543b5bd498cfd5134d3d6de4
df901f6fc71f8c9d659b4c5397d44de9a2031a9d
refs/heads/master
2023-02-20T17:06:30.065944
2021-01-25T12:43:48
2021-01-25T12:43:48
268,433,390
2
0
null
null
null
null
UTF-8
C++
false
false
559
cpp
#include <iostream> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int cnt = 0; while (true) { cnt++; int a, b; string op; cin >> a >> op >> b; if (op == "E") break; bool result = false; if (op == ">") result = a > b; if (op == ">=") result = a >= b; if (op == "<") result = a < b; if (op == "<=") result = a <= b; if (op == "==") result = a == b; if (op == "!=") result = a != b; cout << "Case " << cnt << ": "; if (result) cout << "true\n"; else cout << "false\n"; } return 0; }
[ "heon24500@naver.com" ]
heon24500@naver.com
71970c1eed9f0d609d15a83b300f24b3a10382d3
7c12262a4b464dd7ef5a06794d73c7b087a8251e
/Dtracker2WithOpenCV/src/DTracker.cpp
7a133e2cec1ad7ebf5c451fcbfa8740e3e227c64
[]
no_license
Sarthakg91/SuperVision
8691df14c08390095e7a2518a93f93dcb811658b
46f8c92bd5aa0c751ab4be72999549d2a7f2c60a
refs/heads/master
2020-05-31T21:39:16.226037
2019-06-06T02:50:39
2019-06-06T02:50:39
190,496,660
0
0
null
null
null
null
UTF-8
C++
false
false
8,946
cpp
/* * This class serves to connect the ART tracker and process data in a Qt GUI. * (c) * Derived from "example_with_simple_remote_control" from A.R.T. GmbH. * * DTrackSDK: C++ example, A.R.T. GmbH 16.12.05-17.6.13 * C++ example using DTrackSDK with simple DTrack/DTrack2 remote control * Copyright (C) 2005-2013, Advanced Realtime Tracking GmbH * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Purpose: * - example with DTrack/DTrack2 remote commands: * starts measurement, collects frames and stops measurement again * - using DTrackSDK v2.4.0 * - tested under Linux (gcc) and MS Windows 2000/XP (MS Visual C++) * */ #include "DTracker.h" #include "MainWindow.h" #include "DTrackSDK.hpp" #include <iostream> #include <sstream> #include <QObject> #include <QBasicTimer> #include <QTextStream> using namespace std; void DTracker::processTrackingData() { ostringstream ss; ss.precision(3); ss.setf(ios::fixed, ios::floatfield); // ss << endl << "frame " << dt->getFrameCounter() << " ts " << dt->getTimeStamp() // << " nbod " << dt->getNumBody() << " nfly " << dt->getNumFlyStick() // << " nmea " << dt->getNumMeaTool() << " nmearef " << dt->getNumMeaRef() // << " nhand " << dt->getNumHand() << " nmar " << dt->getNumMarker() // << " nhuman " << dt->getNumHuman() // << endl; // bodies: DTrack_Body_Type_d body; for (int i=0; i<dt->getNumBody(); i++){ body = *dt->getBody(i); if (body.quality < 0) { ss << "bod " << body.id << " not tracked" << endl; } else { ss << "bod " << body.id << " qu " << body.quality << " loc " << body.loc[0] << " " << body.loc[1] << " " << body.loc[2] << " rot " << body.rot[0] << " " << body.rot[1] << " " << body.rot[2] << " " << body.rot[3] << " " << body.rot[4] << " " << body.rot[5] << " " << body.rot[6] << " " << body.rot[7] << " " << body.rot[8] << endl; } trans= QMatrix4x4( float(body.rot[0]),float(body.rot[3]),float(body.rot[6]),float (0.0), float (body.rot[1]) , float(body.rot[4]) ,float(body.rot[7]),float (0.0), float (body.rot[2]) , float(body.rot[5]),float(body.rot[8]),float (0.0), float (0.0),float (0.0),float (0.0),float (1.0)); // location.setX(float(flystick.loc[0])); // location.setY(float(flystick.loc[1])); // location.setZ(float(flystick.loc[2])); // transformedLocation=trans*location; transformedLocation=QVector3D(body.rot[6],body.rot[7],body.rot[8]); ModulusOfPosition=transformedLocation.length(); ss<<"The modulus of pointting vector is :"<<ModulusOfPosition; directionCosineX=transformedLocation.x()/ModulusOfPosition; directionCosineY=transformedLocation.y()/ModulusOfPosition; directionCosineZ=transformedLocation.z()/ModulusOfPosition; /* //for intersection with Z plane zLine=(ZPlaneForWall-flystick.loc[2])/directionCosineZ; intersectionPoint.setX( qreal((directionCosineX*zLine)+flystick.loc[0])); intersectionPoint.setY( qreal((directionCosineY*zLine)+flystick.loc[1])); ss<<" the pointing vector is : "<<transformedLocation.x()<<", "<<transformedLocation.y()<<", "<<transformedLocation.z(); ss<<" The intersection Point for Z='-1500' is "<<intersectionPoint.x()<<", "<<intersectionPoint.y(); */ // for intersection with left wall. xLine=(xPlaneForLeftWall-body.loc[0])/directionCosineX; intersectionPoint.setX( qreal((directionCosineZ*xLine)+body.loc[2])); intersectionPoint.setY( qreal((directionCosineY*xLine)+body.loc[1])); ss<<" the pointing vector is : "<<transformedLocation.x()<<", "<<transformedLocation.y()<<", "<<transformedLocation.z(); ss<<" The intersection Point for X='-2000' is "<<intersectionPoint.x()<<", "<<intersectionPoint.y(); //--------------------------------------------------------------- //------------------------------------------------------------------------------------------------ //if(flystick.quality>0&&buttonPress==1) //{ qDebug()<<"flystick button pressed signal emitted"; // emit(flyStickButtonPressed(intersectionPoint)); // prevButtonState=1; //} // the image is always updated in widget.cpp // emit signal if the body is tracked. the intersection point is always emitted if(body.quality>0) emit(bodyTracked(intersectionPoint));// handled by updateCenter in widget.cpp // emit signal if a flystick is tracked and if button is released // this means element is to be selected. //if(flystick.quality>0&&prevButtonState==1&&buttonPress==0) //{ // qDebug()<<"buttonRelease signal emitted"; // emit(flyStickButtonReleased(intersectionPoint));// Slot : selectElement in widget.cpp // prevButtonState=0;buttonPress=0; //} ss << endl; } sendMessage(ss.str()); } bool DTracker::processErrors() { if (dt->getLastDataError() == DTrackSDK::ERR_TIMEOUT) { sendMessage("! Timeout while waiting for tracking data"); return false; } if (dt->getLastDataError() == DTrackSDK::ERR_NET) { sendMessage("! Error while receiving tracking data"); return false; } if (dt->getLastDataError() == DTrackSDK::ERR_PARSE){ sendMessage("! Error while parsing tracking data"); return false; } return true; } void DTracker::processMessages() { while (dt->getMessage()) { string msg = "ATC message: '"; msg += dt->getMessageStatus() + "' '" + dt->getMessageMsg() + "'"; sendMessage(msg); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DTracker::sendMessage(const string& txt) { //cout << "Msg: " << txt <<endl; emit onMessage(QString(txt.c_str())); } void DTracker::sendState(int state) { //cout << "State: " << state <<endl; emit onStateChange(state); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - DTracker::DTracker(const string& hostname, int port, int rport) : dt(NULL), hostname(hostname), port(port), rport(rport), state(Disconnected) { qDebug()<<"Inside DTracker constructor"; location= QVector3D(0.0,0.0,1.0); trans= QMatrix4x4(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); qDebug()<<trans*location; directionCosineX=1.0; directionCosineY=1.0;directionCosineZ=1.0; ZPlaneForWall=-1500; xPlaneForLeftWall=-2000; xLine=0.0; zLine=0.0; //------------------------------------------------------- } DTracker::~DTracker() { stop(); wait(100); } void DTracker::setHost(const string& _hostname, int _port, int _rport) { hostname = _hostname; port = _port; rport = _rport; } void DTracker::stop() { //if (state == Connecting) terminate(); // run is blocked state = Disconnecting; } void DTracker::run() { sendState(state = Connecting); stringstream ss; ss << "\n*** Starting connection with "<< hostname << " on ports " << port << " " << rport; sendMessage(ss.str()); sendMessage("Please wait..."); dt = new DTrackSDK(hostname, rport, port); if (!dt->isLocalDataPortValid()) { sendMessage("! Could not connect\n"); delete dt; dt = NULL; sendState(state = Disconnected); return; } if (!dt->startMeasurement()) { sendMessage("! Start measurement failed\n"); processMessages(); delete dt; dt = NULL; sendState(state = Disconnected); return; } sendMessage("Running..."); sendState(state = Running); while (state == Running) { if (dt->receive()) processTrackingData(); else processErrors(); processMessages(); } sendMessage("Disconnecting\n"); sendState(state = Disconnecting); // stop measurement & clean up: dt->stopMeasurement(); processMessages(); delete dt; dt = NULL; sendState(state = Disconnected); }
[ "sarthakg91@gmail.com" ]
sarthakg91@gmail.com
fedbfedec0537c97a2eed410126f24292f179d61
73dc34c1887ce865452d63d961619cdc700987b5
/day3/src/main.cpp
68395af952f8fada33f35b5480ccab2148507020
[]
no_license
antonholmberg/advent-of-code-cpp
f6cf60fd002a7d0c97d6238b3874e6335baf308a
8dd34a4349532fd1c1eea37c4ab9677ba457a300
refs/heads/master
2020-04-12T10:52:24.664173
2019-02-10T16:01:29
2019-02-10T16:01:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
926
cpp
#include <fstream> #include <iostream> #include <string> #include <vector> #include "claim.hpp" #include "fabric.hpp" std::vector<std::string> get_input_data(char const *const file_name); int main(int argc, char *argv[]) { Fabric fabric{}; auto input_strings = get_input_data(argv[1]); std::vector<Claim> claims; for (auto &input_string : input_strings) { claims.push_back(Claim::from_string(input_string)); } for (auto &claim : claims) { fabric.add_claim(claim); } std::cout << "Colliding size is: " << fabric.colliding_claims_size() << '\n'; std::cout << "Unique iterator: " << *fabric.get_unique_claims() << '\n'; return 0; } std::vector<std::string> get_input_data(char const *const file_name) { std::ifstream ifs{file_name}; std::string tmp_str; std::vector<std::string> result; while (std::getline(ifs, tmp_str, '\n')) { result.push_back(tmp_str); } return result; }
[ "anton.holmberg@greenely.se" ]
anton.holmberg@greenely.se
e9062e3af6eedd6314a0dcbf5652491920aa5261
9e3cbbc38bdd7769f4f737fe0c5245783ed47168
/ping.h
849d5a772aa85c6f8309d174b59484e7d38ac87c
[]
no_license
lanxiaziyi/ZNetCallClient
76d3eb57a995d0f841c5b02ea341a72f83bbd828
368490552219992f15fa49fedfa9e2d1e4763574
refs/heads/master
2020-04-18T07:59:29.527646
2019-07-31T08:46:24
2019-07-31T08:46:24
167,380,069
1
0
null
null
null
null
GB18030
C++
false
false
1,468
h
#pragma once #include <WinSock2.h> #include <windows.h> //这里需要导入库 Ws2_32.lib,在不同的IDE下可能不太一样 //#pragma comment(lib, "Ws2_32.lib") #define DEF_PACKET_SIZE 32 #define ECHO_REQUEST 8 #define ECHO_REPLY 0 struct IPHeader { BYTE m_byVerHLen; //4位版本+4位首部长度 BYTE m_byTOS; //服务类型 USHORT m_usTotalLen; //总长度 USHORT m_usID; //标识 USHORT m_usFlagFragOffset; //3位标志+13位片偏移 BYTE m_byTTL; //TTL BYTE m_byProtocol; //协议 USHORT m_usHChecksum; //首部检验和 ULONG m_ulSrcIP; //源IP地址 ULONG m_ulDestIP; //目的IP地址 }; struct ICMPHeader { BYTE m_byType; //类型 BYTE m_byCode; //代码 USHORT m_usChecksum; //检验和 USHORT m_usID; //标识符 USHORT m_usSeq; //序号 ULONG m_ulTimeStamp; //时间戳(非标准ICMP头部) }; struct PingReply { USHORT m_usSeq; DWORD m_dwRoundTripTime; DWORD m_dwBytes; DWORD m_dwTTL; }; class CPing { public: CPing(); ~CPing(); BOOL Ping(DWORD dwDestIP, PingReply *pPingReply = NULL, DWORD dwTimeout = 2000); BOOL Ping(char *szDestIP, PingReply *pPingReply = NULL, DWORD dwTimeout = 2000); private: BOOL PingCore(DWORD dwDestIP, PingReply *pPingReply, DWORD dwTimeout); USHORT CalCheckSum(USHORT *pBuffer, int nSize); ULONG GetTickCountCalibrate(); private: SOCKET m_sockRaw; WSAEVENT m_event; USHORT m_usCurrentProcID; char *m_szICMPData; BOOL m_bIsInitSucc; private: static USHORT s_usPacketSeq; };
[ "wangcheng@zhonghu.cn" ]
wangcheng@zhonghu.cn
294dddca33b400c8e0a080a4e0d89434bac2f653
f739df1f252d7c961ed881be3b8babaf62ff4170
/softs/SCADAsoft/5.3.2/ACE_Wrappers/TAO/orbsvcs/orbsvcs/FtRtecEventCommC.h
f115ac4f8643de7cca0bf8f0ef85e18066aad45c
[]
no_license
billpwchan/SCADA-nsl
739484691c95181b262041daa90669d108c54234
1287edcd38b2685a675f1261884f1035f7f288db
refs/heads/master
2023-04-30T09:15:49.104944
2021-01-10T21:53:10
2021-01-10T21:53:10
328,486,982
0
0
null
2023-04-22T07:10:56
2021-01-10T21:53:19
C++
UTF-8
C++
false
false
20,605
h
// -*- C++ -*- // // $Id$ // **** Code generated by the The ACE ORB (TAO) IDL Compiler v1.6a_p10 **** // TAO and the TAO IDL Compiler have been developed by: // Center for Distributed Object Computing // Washington University // St. Louis, MO // USA // http://www.cs.wustl.edu/~schmidt/doc-center.html // and // Distributed Object Computing Laboratory // University of California at Irvine // Irvine, CA // USA // http://doc.ece.uci.edu/ // and // Institute for Software Integrated Systems // Vanderbilt University // Nashville, TN // USA // http://www.isis.vanderbilt.edu/ // // Information about TAO is available at: // http://www.cs.wustl.edu/~schmidt/TAO.html // TAO_IDL - Generated from // be\be_codegen.cpp:135 #ifndef _TAO_IDL_FTRTECEVENTCOMMC_H_ #define _TAO_IDL_FTRTECEVENTCOMMC_H_ #include /**/ "ace/pre.h" #include /**/ "ace/config-all.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ #include /**/ "orbsvcs/FtRtEvent/Utils/ftrtevent_export.h" #include "tao/AnyTypeCode/AnyTypeCode_methods.h" #include "tao/Valuetype/ValueBase.h" #include "tao/Valuetype/Valuetype_Adapter_Factory_Impl.h" #include "tao/ORB.h" #include "tao/SystemException.h" #include "tao/UserException.h" #include "tao/Basic_Types.h" #include "tao/ORB_Constants.h" #include "tao/Object.h" #include "tao/Messaging/Messaging.h" #include "tao/Sequence_T.h" #include "tao/Valuetype/Value_VarOut_T.h" #include "tao/Objref_VarOut_T.h" #include "tao/Seq_Var_T.h" #include "tao/Seq_Out_T.h" #include "tao/VarOut_T.h" #include /**/ "tao/Versioned_Namespace.h" #include "orbsvcs/RtecEventCommC.h" #if defined (TAO_EXPORT_MACRO) #undef TAO_EXPORT_MACRO #endif #define TAO_EXPORT_MACRO TAO_FtRtEvent_Export TAO_BEGIN_VERSIONED_NAMESPACE_DECL // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_root/root_ch.cpp:62 TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL namespace TAO { class Collocation_Proxy_Broker; template<typename T> class Narrow_Utils; } TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_typedef/typedef_ch.cpp:472 typedef CORBA::OctetSeq EventPayload; typedef CORBA::OctetSeq_var EventPayload_var; typedef CORBA::OctetSeq_out EventPayload_out; // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_module/module_ch.cpp:49 namespace FtRtecEventComm { // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_sequence/sequence_ch.cpp:107 #if !defined (_FTRTECEVENTCOMM_OBJECTID_CH_) #define _FTRTECEVENTCOMM_OBJECTID_CH_ class ObjectId; typedef TAO_FixedSeq_Var_T< ObjectId > ObjectId_var; typedef TAO_Seq_Out_T< ObjectId > ObjectId_out; class TAO_FtRtEvent_Export ObjectId : public TAO::unbounded_value_sequence< ::CORBA::Octet > { public: ObjectId (void); ObjectId ( ::CORBA::ULong max); ObjectId ( ::CORBA::ULong max, ::CORBA::ULong length, ::CORBA::Octet* buffer, ::CORBA::Boolean release = false ); ObjectId (const ObjectId &); virtual ~ObjectId (void); static void _tao_any_destructor (void *); typedef ObjectId_var _var_type; typedef ObjectId_out _out_type; #if (TAO_NO_COPY_OCTET_SEQUENCES == 1) ObjectId ( ::CORBA::ULong length, const ACE_Message_Block* mb ) : TAO::unbounded_value_sequence< ::CORBA::Octet> (length, mb) {} #endif /* TAO_NO_COPY_OCTET_SEQUENCE == 1 */ }; #endif /* end #if !defined */ // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_typecode/typecode_decl.cpp:49 extern TAO_FtRtEvent_Export ::CORBA::TypeCode_ptr const _tc_ObjectId; // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_exception/exception_ch.cpp:53 #if !defined (_FTRTECEVENTCOMM_INVALIDOBJECTID_CH_) #define _FTRTECEVENTCOMM_INVALIDOBJECTID_CH_ class TAO_FtRtEvent_Export InvalidObjectID : public ::CORBA::UserException { public: InvalidObjectID (void); InvalidObjectID (const InvalidObjectID &); ~InvalidObjectID (void); InvalidObjectID &operator= (const InvalidObjectID &); static void _tao_any_destructor (void *); static InvalidObjectID *_downcast ( ::CORBA::Exception *); static const InvalidObjectID *_downcast ( ::CORBA::Exception const *); static ::CORBA::Exception *_alloc (void); virtual ::CORBA::Exception *_tao_duplicate (void) const; virtual void _raise (void) const; virtual void _tao_encode (TAO_OutputCDR &cdr) const; virtual void _tao_decode (TAO_InputCDR &cdr); virtual ::CORBA::TypeCode_ptr _tao_type (void) const; }; // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_typecode/typecode_decl.cpp:49 extern TAO_FtRtEvent_Export ::CORBA::TypeCode_ptr const _tc_InvalidObjectID; #endif /* end #if !defined */ #if !defined (_FTRTECEVENTCOMM_AMI_PUSHCONSUMERHANDLER___PTR_CH_) #define _FTRTECEVENTCOMM_AMI_PUSHCONSUMERHANDLER___PTR_CH_ class AMI_PushConsumerHandler; typedef AMI_PushConsumerHandler *AMI_PushConsumerHandler_ptr; #endif /* end #if !defined */ // TAO_IDL - Generated from // be\be_interface.cpp:644 #if !defined (_FTRTECEVENTCOMM_PUSHCONSUMER__VAR_OUT_CH_) #define _FTRTECEVENTCOMM_PUSHCONSUMER__VAR_OUT_CH_ class PushConsumer; typedef PushConsumer *PushConsumer_ptr; typedef TAO_Objref_Var_T< PushConsumer > PushConsumer_var; typedef TAO_Objref_Out_T< PushConsumer > PushConsumer_out; #endif /* end #if !defined */ // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_interface/interface_ch.cpp:54 #if !defined (_FTRTECEVENTCOMM_PUSHCONSUMER_CH_) #define _FTRTECEVENTCOMM_PUSHCONSUMER_CH_ class TAO_FtRtEvent_Export PushConsumer : public virtual ::CORBA::Object { public: friend class TAO::Narrow_Utils<PushConsumer>; typedef PushConsumer_ptr _ptr_type; typedef PushConsumer_var _var_type; typedef PushConsumer_out _out_type; // The static operations. static PushConsumer_ptr _duplicate (PushConsumer_ptr obj); static void _tao_release (PushConsumer_ptr obj); static PushConsumer_ptr _narrow (::CORBA::Object_ptr obj); static PushConsumer_ptr _unchecked_narrow (::CORBA::Object_ptr obj); static PushConsumer_ptr _nil (void) { return static_cast<PushConsumer_ptr> (0); } static void _tao_any_destructor (void *); // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_operation/operation_ch.cpp:46 virtual void push ( const ::FtRtecEventComm::ObjectId & oid, const ::RtecEventComm::EventSet & data); // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_operation/ami_ch.cpp:55 virtual void sendc_push ( ::FtRtecEventComm::AMI_PushConsumerHandler_ptr ami_handler, const ::FtRtecEventComm::ObjectId & oid, const ::RtecEventComm::EventSet & data); // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_interface/interface_ch.cpp:216 virtual ::CORBA::Boolean _is_a (const char *type_id); virtual const char* _interface_repository_id (void) const; virtual ::CORBA::Boolean marshal (TAO_OutputCDR &cdr); private: TAO::Collocation_Proxy_Broker *the_TAO_PushConsumer_Proxy_Broker_; protected: // Concrete interface only. PushConsumer (void); // These methods travese the inheritance tree and set the // parents piece of the given class in the right mode. virtual void FtRtecEventComm_PushConsumer_setup_collocation (void); // Concrete non-local interface only. PushConsumer ( ::IOP::IOR *ior, TAO_ORB_Core *orb_core); // Non-local interface only. PushConsumer ( TAO_Stub *objref, ::CORBA::Boolean _tao_collocated = false, TAO_Abstract_ServantBase *servant = 0, TAO_ORB_Core *orb_core = 0); virtual ~PushConsumer (void); private: // Private and unimplemented for concrete interfaces. PushConsumer (const PushConsumer &); void operator= (const PushConsumer &); }; #endif /* end #if !defined */ // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_typecode/typecode_decl.cpp:49 extern TAO_FtRtEvent_Export ::CORBA::TypeCode_ptr const _tc_PushConsumer; // TAO_IDL - Generated from // be\be_interface.cpp:644 #if !defined (_FTRTECEVENTCOMM_AMI_PUSHCONSUMERHANDLER__VAR_OUT_CH_) #define _FTRTECEVENTCOMM_AMI_PUSHCONSUMERHANDLER__VAR_OUT_CH_ class AMI_PushConsumerHandler; typedef AMI_PushConsumerHandler *AMI_PushConsumerHandler_ptr; typedef TAO_Objref_Var_T< AMI_PushConsumerHandler > AMI_PushConsumerHandler_var; typedef TAO_Objref_Out_T< AMI_PushConsumerHandler > AMI_PushConsumerHandler_out; #endif /* end #if !defined */ // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_interface/interface_ch.cpp:54 #if !defined (_FTRTECEVENTCOMM_AMI_PUSHCONSUMERHANDLER_CH_) #define _FTRTECEVENTCOMM_AMI_PUSHCONSUMERHANDLER_CH_ class TAO_FtRtEvent_Export AMI_PushConsumerHandler : public virtual ::Messaging::ReplyHandler { public: friend class TAO::Narrow_Utils<AMI_PushConsumerHandler>; typedef AMI_PushConsumerHandler_ptr _ptr_type; typedef AMI_PushConsumerHandler_var _var_type; typedef AMI_PushConsumerHandler_out _out_type; // The static operations. static AMI_PushConsumerHandler_ptr _duplicate (AMI_PushConsumerHandler_ptr obj); static void _tao_release (AMI_PushConsumerHandler_ptr obj); static AMI_PushConsumerHandler_ptr _narrow (::CORBA::Object_ptr obj); static AMI_PushConsumerHandler_ptr _unchecked_narrow (::CORBA::Object_ptr obj); static AMI_PushConsumerHandler_ptr _nil (void) { return static_cast<AMI_PushConsumerHandler_ptr> (0); } static void _tao_any_destructor (void *); // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_operation/operation_ch.cpp:46 virtual void push ( void); static void push_reply_stub ( TAO_InputCDR &_tao_reply_cdr, ::Messaging::ReplyHandler_ptr _tao_reply_handler, ::CORBA::ULong reply_status); // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_operation/operation_ch.cpp:46 virtual void push_excep ( ::Messaging::ExceptionHolder * excep_holder); // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_interface/interface_ch.cpp:216 virtual ::CORBA::Boolean _is_a (const char *type_id); virtual const char* _interface_repository_id (void) const; virtual ::CORBA::Boolean marshal (TAO_OutputCDR &cdr); private: TAO::Collocation_Proxy_Broker *the_TAO_AMI_PushConsumerHandler_Proxy_Broker_; protected: // Concrete interface only. AMI_PushConsumerHandler (void); // These methods travese the inheritance tree and set the // parents piece of the given class in the right mode. virtual void FtRtecEventComm_AMI_PushConsumerHandler_setup_collocation (void); // Concrete non-local interface only. AMI_PushConsumerHandler ( ::IOP::IOR *ior, TAO_ORB_Core *orb_core); // Non-local interface only. AMI_PushConsumerHandler ( TAO_Stub *objref, ::CORBA::Boolean _tao_collocated = false, TAO_Abstract_ServantBase *servant = 0, TAO_ORB_Core *orb_core = 0); virtual ~AMI_PushConsumerHandler (void); private: // Private and unimplemented for concrete interfaces. AMI_PushConsumerHandler (const AMI_PushConsumerHandler &); void operator= (const AMI_PushConsumerHandler &); }; #endif /* end #if !defined */ // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_typecode/typecode_decl.cpp:49 extern TAO_FtRtEvent_Export ::CORBA::TypeCode_ptr const _tc_AMI_PushConsumerHandler; // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_module/module_ch.cpp:78 } // module FtRtecEventComm // Proxy Broker Factory function pointer declarations. // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_root/root.cpp:139 extern TAO_FtRtEvent_Export TAO::Collocation_Proxy_Broker * (*FtRtecEventComm__TAO_PushConsumer_Proxy_Broker_Factory_function_pointer) ( ::CORBA::Object_ptr obj ); extern TAO_FtRtEvent_Export TAO::Collocation_Proxy_Broker * (*FtRtecEventComm__TAO_AMI_PushConsumerHandler_Proxy_Broker_Factory_function_pointer) ( ::CORBA::Object_ptr obj ); // TAO_IDL - Generated from // be\be_visitor_traits.cpp:64 TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL // Traits specializations. namespace TAO { #if !defined (_FTRTECEVENTCOMM_PUSHCONSUMER__TRAITS_) #define _FTRTECEVENTCOMM_PUSHCONSUMER__TRAITS_ template<> struct TAO_FtRtEvent_Export Objref_Traits< ::FtRtecEventComm::PushConsumer> { static ::FtRtecEventComm::PushConsumer_ptr duplicate ( ::FtRtecEventComm::PushConsumer_ptr p ); static void release ( ::FtRtecEventComm::PushConsumer_ptr p ); static ::FtRtecEventComm::PushConsumer_ptr nil (void); static ::CORBA::Boolean marshal ( const ::FtRtecEventComm::PushConsumer_ptr p, TAO_OutputCDR & cdr ); }; #endif /* end #if !defined */ #if !defined (_FTRTECEVENTCOMM_AMI_PUSHCONSUMERHANDLER__TRAITS_) #define _FTRTECEVENTCOMM_AMI_PUSHCONSUMERHANDLER__TRAITS_ template<> struct TAO_FtRtEvent_Export Objref_Traits< ::FtRtecEventComm::AMI_PushConsumerHandler> { static ::FtRtecEventComm::AMI_PushConsumerHandler_ptr duplicate ( ::FtRtecEventComm::AMI_PushConsumerHandler_ptr p ); static void release ( ::FtRtecEventComm::AMI_PushConsumerHandler_ptr p ); static ::FtRtecEventComm::AMI_PushConsumerHandler_ptr nil (void); static ::CORBA::Boolean marshal ( const ::FtRtecEventComm::AMI_PushConsumerHandler_ptr p, TAO_OutputCDR & cdr ); }; #endif /* end #if !defined */ } TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_sequence/any_op_ch.cpp:53 TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO_FtRtEvent_Export void operator<<= ( ::CORBA::Any &, const FtRtecEventComm::ObjectId &); // copying version TAO_FtRtEvent_Export void operator<<= ( ::CORBA::Any &, FtRtecEventComm::ObjectId*); // noncopying version TAO_FtRtEvent_Export ::CORBA::Boolean operator>>= (const ::CORBA::Any &, FtRtecEventComm::ObjectId *&); // deprecated TAO_FtRtEvent_Export ::CORBA::Boolean operator>>= (const ::CORBA::Any &, const FtRtecEventComm::ObjectId *&); TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_exception/any_op_ch.cpp:53 TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO_FtRtEvent_Export void operator<<= (::CORBA::Any &, const FtRtecEventComm::InvalidObjectID &); // copying version TAO_FtRtEvent_Export void operator<<= (::CORBA::Any &, FtRtecEventComm::InvalidObjectID*); // noncopying version TAO_FtRtEvent_Export ::CORBA::Boolean operator>>= (const ::CORBA::Any &, FtRtecEventComm::InvalidObjectID *&); // deprecated TAO_FtRtEvent_Export ::CORBA::Boolean operator>>= (const ::CORBA::Any &, const FtRtecEventComm::InvalidObjectID *&); TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_interface/any_op_ch.cpp:54 #if defined (ACE_ANY_OPS_USE_NAMESPACE) namespace FtRtecEventComm { TAO_FtRtEvent_Export void operator<<= ( ::CORBA::Any &, PushConsumer_ptr); // copying TAO_FtRtEvent_Export void operator<<= ( ::CORBA::Any &, PushConsumer_ptr *); // non-copying TAO_FtRtEvent_Export ::CORBA::Boolean operator>>= (const ::CORBA::Any &, PushConsumer_ptr &); } #else TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO_FtRtEvent_Export void operator<<= (::CORBA::Any &, FtRtecEventComm::PushConsumer_ptr); // copying TAO_FtRtEvent_Export void operator<<= (::CORBA::Any &, FtRtecEventComm::PushConsumer_ptr *); // non-copying TAO_FtRtEvent_Export ::CORBA::Boolean operator>>= (const ::CORBA::Any &, FtRtecEventComm::PushConsumer_ptr &); TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL #endif // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_interface/any_op_ch.cpp:54 #if defined (ACE_ANY_OPS_USE_NAMESPACE) namespace FtRtecEventComm { TAO_FtRtEvent_Export void operator<<= ( ::CORBA::Any &, AMI_PushConsumerHandler_ptr); // copying TAO_FtRtEvent_Export void operator<<= ( ::CORBA::Any &, AMI_PushConsumerHandler_ptr *); // non-copying TAO_FtRtEvent_Export ::CORBA::Boolean operator>>= (const ::CORBA::Any &, AMI_PushConsumerHandler_ptr &); } #else TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO_FtRtEvent_Export void operator<<= (::CORBA::Any &, FtRtecEventComm::AMI_PushConsumerHandler_ptr); // copying TAO_FtRtEvent_Export void operator<<= (::CORBA::Any &, FtRtecEventComm::AMI_PushConsumerHandler_ptr *); // non-copying TAO_FtRtEvent_Export ::CORBA::Boolean operator>>= (const ::CORBA::Any &, FtRtecEventComm::AMI_PushConsumerHandler_ptr &); TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL #endif // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_sequence/cdr_op_ch.cpp:71 #if !defined _TAO_CDR_OP_FtRtecEventComm_ObjectId_H_ #define _TAO_CDR_OP_FtRtecEventComm_ObjectId_H_ TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO_FtRtEvent_Export ::CORBA::Boolean operator<< ( TAO_OutputCDR &strm, const FtRtecEventComm::ObjectId &_tao_sequence ); TAO_FtRtEvent_Export ::CORBA::Boolean operator>> ( TAO_InputCDR &strm, FtRtecEventComm::ObjectId &_tao_sequence ); TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL #endif /* _TAO_CDR_OP_FtRtecEventComm_ObjectId_H_ */ // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_exception/cdr_op_ch.cpp:52 TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO_FtRtEvent_Export ::CORBA::Boolean operator<< (TAO_OutputCDR &, const FtRtecEventComm::InvalidObjectID &); TAO_FtRtEvent_Export ::CORBA::Boolean operator>> (TAO_InputCDR &, FtRtecEventComm::InvalidObjectID &); TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_interface/cdr_op_ch.cpp:55 TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO_FtRtEvent_Export ::CORBA::Boolean operator<< (TAO_OutputCDR &, const FtRtecEventComm::PushConsumer_ptr ); TAO_FtRtEvent_Export ::CORBA::Boolean operator>> (TAO_InputCDR &, FtRtecEventComm::PushConsumer_ptr &); TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL // TAO_IDL - Generated from // d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_interface/cdr_op_ch.cpp:55 TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO_FtRtEvent_Export ::CORBA::Boolean operator<< (TAO_OutputCDR &, const FtRtecEventComm::AMI_PushConsumerHandler_ptr ); TAO_FtRtEvent_Export ::CORBA::Boolean operator>> (TAO_InputCDR &, FtRtecEventComm::AMI_PushConsumerHandler_ptr &); TAO_END_VERSIONED_NAMESPACE_DECL TAO_BEGIN_VERSIONED_NAMESPACE_DECL // TAO_IDL - Generated from // be\be_codegen.cpp:1228 TAO_END_VERSIONED_NAMESPACE_DECL #if defined (__ACE_INLINE__) #include "FtRtecEventCommC.inl" #endif /* defined INLINE */ #include /**/ "ace/post.h" #endif /* ifndef */
[ "billpwchan@hotmail.com" ]
billpwchan@hotmail.com
67f1b363aad2a060183e47fa67ae582620612a58
bafdadd9d7164e43ee0ade27780975f36e806b5c
/2018-2019/valera_and_elections.cpp
8f463dde6dbcd4d86c208342bfd5fbd2fecffbe1
[]
no_license
ddeka0/CP
580d5c7970c9fae42c76f571ec4a3519af88c0f7
877c50401ad9047e3ccba041bdad4c0ed3315289
refs/heads/master
2023-06-19T00:58:15.400741
2021-07-16T23:18:14
2021-07-16T23:18:14
142,334,713
0
0
null
null
null
null
UTF-8
C++
false
false
1,586
cpp
#include <bits/stdc++.h> using namespace std; template<typename T> void LOG(T const& t) {std::cout <<t<<endl;} template<typename First, typename ... Rest> void LOG(First const& first, Rest const& ... rest) { std::cout << first<<" "; LOG(rest ...);} template<class T> T gcd(T a, T b) { return b ? gcd(b, a % b) : a; } long long modpow(long long a,long long x,long long M) { long long res = 1; while(x) {if(x&1) res = (res*a)%M; a = (a*a)%M; x/=2;} return res; } #define show(a) std::cout << #a << ": " << (a) << std::endl long long f[100009]; long long rf[100009]; void inv_factorials(long long M) { f[0] = 1; long long m = 100000; for(int i = 1;i<=m;i++) {f[i] = (f[i - 1]*i)%M;} rf[m] = modpow(f[m],M-2,M); for(int i = m - 1;i>=0;i--) {rf[i] = (rf[i+1]*(i+1))%M;} } long long C(int _n,int _r,long long M) {return (_r <0 || _r > _n)?0 : f[_n]*rf[_r]%M*rf[_n - _r]%M; } void solve(); int main() { ios_base::sync_with_stdio(NULL); cin.tie(NULL); solve(); return 0; } vector<pair<int,int>> g[100009]; bool visited[100009]; std::vector<int> vertices; int dfs(int u,int p,int state) { visited[u] = true; int ans = 0; for(auto e:g[u]) { int v = e.first; int f = e.second; if(!visited[v]) { ans += dfs(v,u,f); } } if(ans == 0 && state == 2) { ans = 1; vertices.push_back(u); } return ans; } void solve() { int n,u,v,f; cin >> n; for(int i = 1;i<n;i++) { cin >> u >> v >> f; g[u].push_back(make_pair(v,f)); g[v].push_back(make_pair(u,f)); } int ans = dfs(1,-1,1); cout << ans << endl; for(int u:vertices) { cout << u << " "; } cout << endl; }
[ "dekadebashish3@gmail.com" ]
dekadebashish3@gmail.com
5ae02e55eba4d7bcc6338c99ee6eca174d1c8192
6a2686efe30bd1b25c8c5dcea7aafa9535570783
/src/warnings.h
19a36401c3de5225ff2277ed49176a34e6f31d05
[ "MIT" ]
permissive
bumbacoin/cream
493b9203c7d5cf73f67f2357dbecc25a1ae3088c
f3e72b58a3b5ae108e2e9c1675f95aacb2599711
refs/heads/master
2020-04-17T17:29:34.657525
2019-01-22T05:28:22
2019-01-22T05:28:22
166,779,886
0
0
MIT
2019-01-21T08:52:49
2019-01-21T08:52:46
null
UTF-8
C++
false
false
957
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Copyright (c) 2018 The Cream developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_WARNINGS_H #define BITCOIN_WARNINGS_H #include <stdlib.h> #include <string> void SetMiscWarning(const std::string& strWarning); void SetfLargeWorkForkFound(bool flag); bool GetfLargeWorkForkFound(); void SetfLargeWorkInvalidChainFound(bool flag); /** Format a string that describes several potential problems detected by the core. * @param[in] strFor can have the following values: * - "statusbar": get the most important warning * - "gui": get all warnings, translated (where possible) for GUI, separated by <hr /> * @returns the warning string selected by strFor */ std::string GetWarnings(const std::string& strFor); #endif // BITCOIN_WARNINGS_H
[ "creamcoin@gmail.com" ]
creamcoin@gmail.com
35a11f176993966fc79b34fc54e0d6be81399b38
d61d05748a59a1a73bbf3c39dd2c1a52d649d6e3
/chromium/third_party/blink/renderer/core/paint/table_section_painter.h
eabff481f90858a16e263246af455fbbff6c8cfc
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0" ]
permissive
Csineneo/Vivaldi
4eaad20fc0ff306ca60b400cd5fad930a9082087
d92465f71fb8e4345e27bd889532339204b26f1e
refs/heads/master
2022-11-23T17:11:50.714160
2019-05-25T11:45:11
2019-05-25T11:45:11
144,489,531
5
4
BSD-3-Clause
2022-11-04T05:55:33
2018-08-12T18:04:37
null
UTF-8
C++
false
false
1,794
h
// Copyright 2014 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_PAINT_TABLE_SECTION_PAINTER_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_TABLE_SECTION_PAINTER_H_ #include "third_party/blink/renderer/core/paint/paint_phase.h" #include "third_party/blink/renderer/core/style/shadow_data.h" #include "third_party/blink/renderer/platform/geometry/layout_rect.h" #include "third_party/blink/renderer/platform/wtf/allocator.h" namespace blink { class CellSpan; class LayoutPoint; class LayoutTableCell; class LayoutTableSection; struct PaintInfo; class TableSectionPainter { STACK_ALLOCATED(); public: TableSectionPainter(const LayoutTableSection& layout_table_section) : layout_table_section_(layout_table_section) {} void Paint(const PaintInfo&); void PaintCollapsedBorders(const PaintInfo&); private: void PaintObject(const PaintInfo&, const LayoutPoint& paint_offset); void PaintBoxDecorationBackground(const PaintInfo&, const LayoutPoint&, const CellSpan& dirtied_rows, const CellSpan& dirtied_columns); void PaintBackgroundsBehindCell(const LayoutTableCell&, const PaintInfo&); void PaintCell(const LayoutTableCell&, const PaintInfo&); void PaintSection(const PaintInfo&); void PaintCollapsedSectionBorders(const PaintInfo&); LayoutRect TableAlignedRect(const PaintInfo& paint_info, const LayoutPoint& paint_offset); const LayoutTableSection& layout_table_section_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_TABLE_SECTION_PAINTER_H_
[ "tofu@rMBP.local" ]
tofu@rMBP.local
b868001bdb4fb6dcf038b7f716419d238747e75e
ab270b50335ae1e65ae487dbc513669917d2988f
/test/stadfa/stadfa_09.i--tags--stadfa.re
b2f40a21d5a9cbefada5aa580a5dbee3822e93aa
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain" ]
permissive
ryandesign/re2c
a2bab466e901d5214f16fd357d103d73873fadfd
e2f29c1691759aabac3398e363c7d455bd0fef6e
refs/heads/master
2022-11-15T06:56:20.443998
2020-07-04T09:34:16
2020-07-04T09:39:45
277,114,415
1
0
NOASSERTION
2020-07-04T13:24:19
2020-07-04T13:24:19
null
UTF-8
C++
false
false
38
re
/*!re2c ([c] | @t) [c][c] {} "" {} */
[ "skvadrik@gmail.com" ]
skvadrik@gmail.com
15f4c46ad5c6e5783b278896e2f1f00393149f2a
267091f176d8458bc340a0e104cc31c3249c4f3f
/Common/tests/HtmlResultsWriter_test.cpp
70d1067ec2b86d7e44bb2734acb32e23ab11908c
[ "MIT" ]
permissive
afperezm/binary-location-recognition
cf4405f140e83dcb68e08a9c359c2a1fb90b64e3
db0ab392c2586b03518ec84455cec91b6011be4e
refs/heads/master
2021-05-29T07:55:16.058844
2015-07-03T22:12:10
2015-07-03T22:12:10
12,215,930
2
0
null
null
null
null
UTF-8
C++
false
false
128
cpp
/* * HtmlResultsWriter_test.cpp * * Created on: Nov 10, 2013 * Author: andresf */ #include <HtmlResultsWriter.hpp>
[ "gantzer89@gmail.com" ]
gantzer89@gmail.com
a2180617d5dabe81a65b401b81d8b25895b2232a
00ef8d964caf4abef549bbeff81a744c282c8c16
/net/quic/chromium/quic_chromium_client_session.cc
261387f46dd65e17d595ccbeb8b7344b99b0473b
[ "BSD-3-Clause" ]
permissive
czhang03/browser-android-tabs
8295f466465e89d89109659cff74d6bb9adb8633
0277ceb50f9a90a2195c02e0d96da7b157f3b192
refs/heads/master
2023-02-16T23:55:29.149602
2018-09-14T07:46:16
2018-09-14T07:46:16
149,174,398
1
0
null
null
null
null
UTF-8
C++
false
false
106,669
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/quic/chromium/quic_chromium_client_session.h" #include <utility> #include "base/callback_helpers.h" #include "base/location.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/sparse_histogram.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/memory_usage_estimator.h" #include "base/values.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/base/network_activity_monitor.h" #include "net/http/transport_security_state.h" #include "net/log/net_log_event_type.h" #include "net/log/net_log_source_type.h" #include "net/quic/chromium/crypto/proof_verifier_chromium.h" #include "net/quic/chromium/quic_chromium_connection_helper.h" #include "net/quic/chromium/quic_chromium_packet_writer.h" #include "net/quic/chromium/quic_connectivity_probing_manager.h" #include "net/quic/chromium/quic_crypto_client_stream_factory.h" #include "net/quic/chromium/quic_server_info.h" #include "net/quic/chromium/quic_stream_factory.h" #include "net/socket/datagram_client_socket.h" #include "net/spdy/spdy_http_utils.h" #include "net/spdy/spdy_log_util.h" #include "net/spdy/spdy_session.h" #include "net/ssl/channel_id_service.h" #include "net/ssl/ssl_connection_status_flags.h" #include "net/ssl/ssl_info.h" #include "net/ssl/token_binding.h" #include "net/third_party/quic/core/quic_client_promised_info.h" #include "net/third_party/quic/core/spdy_utils.h" #include "net/third_party/quic/platform/api/quic_ptr_util.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "third_party/boringssl/src/include/openssl/ssl.h" namespace net { namespace { // IPv6 packets have an additional 20 bytes of overhead than IPv4 packets. const size_t kAdditionalOverheadForIPv6 = 20; // Maximum number of Readers that are created for any session due to // connection migration. A new Reader is created every time this endpoint's // IP address changes. const size_t kMaxReadersPerQuicSession = 5; // Size of the MRU cache of Token Binding signatures. Since the material being // signed is constant and there aren't many keys being used to sign, a fairly // small number was chosen, somewhat arbitrarily, and to match // SSLClientSocketImpl. const size_t kTokenBindingSignatureMapSize = 10; // Time to wait (in seconds) when no networks are available and // migrating sessions need to wait for a new network to connect. const size_t kWaitTimeForNewNetworkSecs = 10; const size_t kMinRetryTimeForDefaultNetworkSecs = 1; // Maximum RTT time for this session when set initial timeout for probing // network. const int kDefaultRTTMilliSecs = 300; // The maximum size of uncompressed QUIC headers that will be allowed. const size_t kMaxUncompressedHeaderSize = 256 * 1024; // The maximum time allowed to have no retransmittable packets on the wire // (after sending the first retransmittable packet) if // |migrate_session_early_v2_| is true. PING frames will be sent as needed to // enforce this. const size_t kDefaultRetransmittableOnWireTimeoutMillisecs = 100; // Histograms for tracking down the crashes from http://crbug.com/354669 // Note: these values must be kept in sync with the corresponding values in: // tools/metrics/histograms/histograms.xml enum Location { DESTRUCTOR = 0, ADD_OBSERVER = 1, TRY_CREATE_STREAM = 2, CREATE_OUTGOING_RELIABLE_STREAM = 3, NOTIFY_FACTORY_OF_SESSION_CLOSED_LATER = 4, NOTIFY_FACTORY_OF_SESSION_CLOSED = 5, NUM_LOCATIONS = 6, }; void RecordUnexpectedOpenStreams(Location location) { UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.UnexpectedOpenStreams", location, NUM_LOCATIONS); } void RecordUnexpectedObservers(Location location) { UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.UnexpectedObservers", location, NUM_LOCATIONS); } void RecordUnexpectedNotGoingAway(Location location) { UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.UnexpectedNotGoingAway", location, NUM_LOCATIONS); } std::unique_ptr<base::Value> NetLogQuicConnectionMigrationTriggerCallback( std::string trigger, NetLogCaptureMode capture_mode) { std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetString("trigger", trigger); return std::move(dict); } std::unique_ptr<base::Value> NetLogQuicConnectionMigrationFailureCallback( QuicConnectionId connection_id, std::string reason, NetLogCaptureMode capture_mode) { std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetString("connection_id", base::NumberToString(connection_id)); dict->SetString("reason", reason); return std::move(dict); } std::unique_ptr<base::Value> NetLogQuicConnectionMigrationSuccessCallback( QuicConnectionId connection_id, NetLogCaptureMode capture_mode) { std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetString("connection_id", base::NumberToString(connection_id)); return std::move(dict); } // Histogram for recording the different reasons that a QUIC session is unable // to complete the handshake. enum HandshakeFailureReason { HANDSHAKE_FAILURE_UNKNOWN = 0, HANDSHAKE_FAILURE_BLACK_HOLE = 1, HANDSHAKE_FAILURE_PUBLIC_RESET = 2, NUM_HANDSHAKE_FAILURE_REASONS = 3, }; void RecordHandshakeFailureReason(HandshakeFailureReason reason) { UMA_HISTOGRAM_ENUMERATION( "Net.QuicSession.ConnectionClose.HandshakeNotConfirmed.Reason", reason, NUM_HANDSHAKE_FAILURE_REASONS); } // Note: these values must be kept in sync with the corresponding values in: // tools/metrics/histograms/histograms.xml enum HandshakeState { STATE_STARTED = 0, STATE_ENCRYPTION_ESTABLISHED = 1, STATE_HANDSHAKE_CONFIRMED = 2, STATE_FAILED = 3, NUM_HANDSHAKE_STATES = 4 }; void RecordHandshakeState(HandshakeState state) { UMA_HISTOGRAM_ENUMERATION("Net.QuicHandshakeState", state, NUM_HANDSHAKE_STATES); } std::string ConnectionMigrationCauseToString(ConnectionMigrationCause cause) { switch (cause) { case UNKNOWN: return "Unknown"; case ON_NETWORK_CONNECTED: return "OnNetworkConnected"; case ON_NETWORK_DISCONNECTED: return "OnNetworkDisconnected"; case ON_WRITE_ERROR: return "OnWriteError"; case ON_NETWORK_MADE_DEFAULT: return "OnNetworkMadeDefault"; case ON_MIGRATE_BACK_TO_DEFAULT_NETWORK: return "OnMigrateBackToDefaultNetwork"; case ON_PATH_DEGRADING: return "OnPathDegrading"; default: QUIC_NOTREACHED(); break; } return "InvalidCause"; } std::unique_ptr<base::Value> NetLogQuicClientSessionCallback( const QuicServerId* server_id, int cert_verify_flags, bool require_confirmation, NetLogCaptureMode /* capture_mode */) { std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetString("host", server_id->host()); dict->SetInteger("port", server_id->port()); dict->SetBoolean("privacy_mode", server_id->privacy_mode() == PRIVACY_MODE_ENABLED); dict->SetBoolean("require_confirmation", require_confirmation); dict->SetInteger("cert_verify_flags", cert_verify_flags); return std::move(dict); } std::unique_ptr<base::Value> NetLogQuicPushPromiseReceivedCallback( const spdy::SpdyHeaderBlock* headers, spdy::SpdyStreamId stream_id, spdy::SpdyStreamId promised_stream_id, NetLogCaptureMode capture_mode) { std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->Set("headers", ElideSpdyHeaderBlockForNetLog(*headers, capture_mode)); dict->SetInteger("id", stream_id); dict->SetInteger("promised_stream_id", promised_stream_id); return std::move(dict); } // TODO(fayang): Remove this when necessary data is collected. void LogProbeResultToHistogram(ConnectionMigrationCause cause, bool success) { UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.ConnectionMigrationProbeSuccess", success); const std::string histogram_name = "Net.QuicSession.ConnectionMigrationProbeSuccess." + ConnectionMigrationCauseToString(cause); STATIC_HISTOGRAM_POINTER_GROUP( histogram_name, cause, MIGRATION_CAUSE_MAX, AddBoolean(success), base::BooleanHistogram::FactoryGet( histogram_name, base::HistogramBase::kUmaTargetedHistogramFlag)); } class HpackEncoderDebugVisitor : public QuicHpackDebugVisitor { void OnUseEntry(QuicTime::Delta elapsed) override { UMA_HISTOGRAM_TIMES( "Net.QuicHpackEncoder.IndexedEntryAge", base::TimeDelta::FromMicroseconds(elapsed.ToMicroseconds())); } }; class HpackDecoderDebugVisitor : public QuicHpackDebugVisitor { void OnUseEntry(QuicTime::Delta elapsed) override { UMA_HISTOGRAM_TIMES( "Net.QuicHpackDecoder.IndexedEntryAge", base::TimeDelta::FromMicroseconds(elapsed.ToMicroseconds())); } }; class QuicServerPushHelper : public ServerPushDelegate::ServerPushHelper { public: explicit QuicServerPushHelper( base::WeakPtr<QuicChromiumClientSession> session, const GURL& url) : session_(session), request_url_(url) {} void Cancel() override { if (session_) { session_->CancelPush(request_url_); } } const GURL& GetURL() const override { return request_url_; } private: base::WeakPtr<QuicChromiumClientSession> session_; const GURL request_url_; }; } // namespace QuicChromiumClientSession::Handle::Handle( const base::WeakPtr<QuicChromiumClientSession>& session, const HostPortPair& destination) : MultiplexedSessionHandle(session), session_(session), destination_(destination), net_log_(session_->net_log()), was_handshake_confirmed_(session->IsCryptoHandshakeConfirmed()), net_error_(OK), quic_error_(QUIC_NO_ERROR), port_migration_detected_(false), server_id_(session_->server_id()), quic_version_(session->connection()->transport_version()), push_handle_(nullptr), was_ever_used_(false) { DCHECK(session_); session_->AddHandle(this); } QuicChromiumClientSession::Handle::~Handle() { if (push_handle_) { auto* push_handle = push_handle_; push_handle_ = nullptr; push_handle->Cancel(); } if (session_) session_->RemoveHandle(this); } void QuicChromiumClientSession::Handle::OnCryptoHandshakeConfirmed() { was_handshake_confirmed_ = true; } void QuicChromiumClientSession::Handle::OnSessionClosed( QuicTransportVersion quic_version, int net_error, QuicErrorCode quic_error, bool port_migration_detected, LoadTimingInfo::ConnectTiming connect_timing, bool was_ever_used) { session_ = nullptr; port_migration_detected_ = port_migration_detected; net_error_ = net_error; quic_error_ = quic_error; quic_version_ = quic_version; connect_timing_ = connect_timing; push_handle_ = nullptr; was_ever_used_ = was_ever_used; } bool QuicChromiumClientSession::Handle::IsConnected() const { return session_ != nullptr; } bool QuicChromiumClientSession::Handle::IsCryptoHandshakeConfirmed() const { return was_handshake_confirmed_; } const LoadTimingInfo::ConnectTiming& QuicChromiumClientSession::Handle::GetConnectTiming() { if (!session_) return connect_timing_; return session_->GetConnectTiming(); } Error QuicChromiumClientSession::Handle::GetTokenBindingSignature( crypto::ECPrivateKey* key, TokenBindingType tb_type, std::vector<uint8_t>* out) { if (!session_) return ERR_CONNECTION_CLOSED; return session_->GetTokenBindingSignature(key, tb_type, out); } void QuicChromiumClientSession::Handle::PopulateNetErrorDetails( NetErrorDetails* details) const { if (session_) { session_->PopulateNetErrorDetails(details); } else { details->quic_port_migration_detected = port_migration_detected_; details->quic_connection_error = quic_error_; } } QuicTransportVersion QuicChromiumClientSession::Handle::GetQuicVersion() const { if (!session_) return quic_version_; return session_->connection()->transport_version(); } void QuicChromiumClientSession::Handle::ResetPromised( QuicStreamId id, QuicRstStreamErrorCode error_code) { if (session_) session_->ResetPromised(id, error_code); } std::unique_ptr<QuicConnection::ScopedPacketFlusher> QuicChromiumClientSession::Handle::CreatePacketBundler( QuicConnection::AckBundling bundling_mode) { if (!session_) return nullptr; return std::make_unique<QuicConnection::ScopedPacketFlusher>( session_->connection(), bundling_mode); } bool QuicChromiumClientSession::Handle::SharesSameSession( const Handle& other) const { return session_.get() == other.session_.get(); } int QuicChromiumClientSession::Handle::RendezvousWithPromised( const spdy::SpdyHeaderBlock& headers, const CompletionCallback& callback) { if (!session_) return ERR_CONNECTION_CLOSED; QuicAsyncStatus push_status = session_->push_promise_index()->Try(headers, this, &push_handle_); switch (push_status) { case QUIC_FAILURE: return ERR_FAILED; case QUIC_SUCCESS: return OK; case QUIC_PENDING: push_callback_ = callback; return ERR_IO_PENDING; } NOTREACHED(); return ERR_UNEXPECTED; } int QuicChromiumClientSession::Handle::RequestStream( bool requires_confirmation, const CompletionCallback& callback, const NetworkTrafficAnnotationTag& traffic_annotation) { DCHECK(!stream_request_); if (!session_) return ERR_CONNECTION_CLOSED; // std::make_unique does not work because the StreamRequest constructor // is private. stream_request_ = std::unique_ptr<StreamRequest>( new StreamRequest(this, requires_confirmation, traffic_annotation)); return stream_request_->StartRequest(callback); } std::unique_ptr<QuicChromiumClientStream::Handle> QuicChromiumClientSession::Handle::ReleaseStream() { DCHECK(stream_request_); auto handle = stream_request_->ReleaseStream(); stream_request_.reset(); return handle; } std::unique_ptr<QuicChromiumClientStream::Handle> QuicChromiumClientSession::Handle::ReleasePromisedStream() { DCHECK(push_stream_); return std::move(push_stream_); } int QuicChromiumClientSession::Handle::WaitForHandshakeConfirmation( const CompletionCallback& callback) { if (!session_) return ERR_CONNECTION_CLOSED; return session_->WaitForHandshakeConfirmation(callback); } void QuicChromiumClientSession::Handle::CancelRequest(StreamRequest* request) { if (session_) session_->CancelRequest(request); } int QuicChromiumClientSession::Handle::TryCreateStream(StreamRequest* request) { if (!session_) return ERR_CONNECTION_CLOSED; return session_->TryCreateStream(request); } QuicClientPushPromiseIndex* QuicChromiumClientSession::Handle::GetPushPromiseIndex() { if (!session_) return push_promise_index_; return session_->push_promise_index(); } int QuicChromiumClientSession::Handle::GetPeerAddress( IPEndPoint* address) const { if (!session_) return ERR_CONNECTION_CLOSED; *address = session_->peer_address().impl().socket_address(); return OK; } int QuicChromiumClientSession::Handle::GetSelfAddress( IPEndPoint* address) const { if (!session_) return ERR_CONNECTION_CLOSED; *address = session_->self_address().impl().socket_address(); return OK; } bool QuicChromiumClientSession::Handle::WasEverUsed() const { if (!session_) return was_ever_used_; return session_->WasConnectionEverUsed(); } bool QuicChromiumClientSession::Handle::CheckVary( const spdy::SpdyHeaderBlock& client_request, const spdy::SpdyHeaderBlock& promise_request, const spdy::SpdyHeaderBlock& promise_response) { HttpRequestInfo promise_request_info; ConvertHeaderBlockToHttpRequestHeaders(promise_request, &promise_request_info.extra_headers); HttpRequestInfo client_request_info; ConvertHeaderBlockToHttpRequestHeaders(client_request, &client_request_info.extra_headers); HttpResponseInfo promise_response_info; if (!SpdyHeadersToHttpResponse(promise_response, &promise_response_info)) { DLOG(WARNING) << "Invalid headers"; return false; } HttpVaryData vary_data; if (!vary_data.Init(promise_request_info, *promise_response_info.headers.get())) { // Promise didn't contain valid vary info, so URL match was sufficient. return true; } // Now compare the client request for matching. return vary_data.MatchesRequest(client_request_info, *promise_response_info.headers.get()); } void QuicChromiumClientSession::Handle::OnRendezvousResult( QuicSpdyStream* stream) { DCHECK(!push_stream_); int rv = ERR_FAILED; if (stream) { rv = OK; push_stream_ = static_cast<QuicChromiumClientStream*>(stream)->CreateHandle(); } if (push_callback_) { DCHECK(push_handle_); push_handle_ = nullptr; base::ResetAndReturn(&push_callback_).Run(rv); } } QuicChromiumClientSession::StreamRequest::StreamRequest( QuicChromiumClientSession::Handle* session, bool requires_confirmation, const NetworkTrafficAnnotationTag& traffic_annotation) : session_(session), requires_confirmation_(requires_confirmation), stream_(nullptr), traffic_annotation_(traffic_annotation), weak_factory_(this) {} QuicChromiumClientSession::StreamRequest::~StreamRequest() { if (stream_) stream_->Reset(QUIC_STREAM_CANCELLED); if (session_) session_->CancelRequest(this); } int QuicChromiumClientSession::StreamRequest::StartRequest( const CompletionCallback& callback) { if (!session_->IsConnected()) return ERR_CONNECTION_CLOSED; next_state_ = STATE_WAIT_FOR_CONFIRMATION; int rv = DoLoop(OK); if (rv == ERR_IO_PENDING) callback_ = callback; return rv; } std::unique_ptr<QuicChromiumClientStream::Handle> QuicChromiumClientSession::StreamRequest::ReleaseStream() { DCHECK(stream_); return std::move(stream_); } void QuicChromiumClientSession::StreamRequest::OnRequestCompleteSuccess( std::unique_ptr<QuicChromiumClientStream::Handle> stream) { DCHECK_EQ(STATE_REQUEST_STREAM_COMPLETE, next_state_); stream_ = std::move(stream); // This method is called even when the request completes synchronously. if (callback_) DoCallback(OK); } void QuicChromiumClientSession::StreamRequest::OnRequestCompleteFailure( int rv) { DCHECK_EQ(STATE_REQUEST_STREAM_COMPLETE, next_state_); // This method is called even when the request completes synchronously. if (callback_) { // Avoid re-entrancy if the callback calls into the session. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&QuicChromiumClientSession::StreamRequest::DoCallback, weak_factory_.GetWeakPtr(), rv)); } } void QuicChromiumClientSession::StreamRequest::OnIOComplete(int rv) { rv = DoLoop(rv); if (rv != ERR_IO_PENDING && !callback_.is_null()) { DoCallback(rv); } } void QuicChromiumClientSession::StreamRequest::DoCallback(int rv) { CHECK_NE(rv, ERR_IO_PENDING); CHECK(!callback_.is_null()); // The client callback can do anything, including destroying this class, // so any pending callback must be issued after everything else is done. base::ResetAndReturn(&callback_).Run(rv); } int QuicChromiumClientSession::StreamRequest::DoLoop(int rv) { do { State state = next_state_; next_state_ = STATE_NONE; switch (state) { case STATE_WAIT_FOR_CONFIRMATION: CHECK_EQ(OK, rv); rv = DoWaitForConfirmation(); break; case STATE_WAIT_FOR_CONFIRMATION_COMPLETE: rv = DoWaitForConfirmationComplete(rv); break; case STATE_REQUEST_STREAM: CHECK_EQ(OK, rv); rv = DoRequestStream(); break; case STATE_REQUEST_STREAM_COMPLETE: rv = DoRequestStreamComplete(rv); break; default: NOTREACHED() << "next_state_: " << next_state_; break; } } while (next_state_ != STATE_NONE && next_state_ && rv != ERR_IO_PENDING); return rv; } int QuicChromiumClientSession::StreamRequest::DoWaitForConfirmation() { next_state_ = STATE_WAIT_FOR_CONFIRMATION_COMPLETE; if (requires_confirmation_) { return session_->WaitForHandshakeConfirmation( base::Bind(&QuicChromiumClientSession::StreamRequest::OnIOComplete, weak_factory_.GetWeakPtr())); } return OK; } int QuicChromiumClientSession::StreamRequest::DoWaitForConfirmationComplete( int rv) { DCHECK_NE(ERR_IO_PENDING, rv); if (rv < 0) return rv; next_state_ = STATE_REQUEST_STREAM; return OK; } int QuicChromiumClientSession::StreamRequest::DoRequestStream() { next_state_ = STATE_REQUEST_STREAM_COMPLETE; return session_->TryCreateStream(this); } int QuicChromiumClientSession::StreamRequest::DoRequestStreamComplete(int rv) { DCHECK(rv == OK || !stream_); return rv; } QuicChromiumClientSession::QuicChromiumClientSession( QuicConnection* connection, std::unique_ptr<DatagramClientSocket> socket, QuicStreamFactory* stream_factory, QuicCryptoClientStreamFactory* crypto_client_stream_factory, QuicClock* clock, TransportSecurityState* transport_security_state, std::unique_ptr<QuicServerInfo> server_info, const QuicSessionKey& session_key, bool require_confirmation, bool migrate_session_early, bool migrate_sessions_on_network_change, bool migrate_session_early_v2, bool migrate_sessions_on_network_change_v2, base::TimeDelta max_time_on_non_default_network, int max_migrations_to_non_default_network_on_path_degrading, int yield_after_packets, QuicTime::Delta yield_after_duration, bool headers_include_h2_stream_dependency, int cert_verify_flags, const QuicConfig& config, QuicCryptoClientConfig* crypto_config, const char* const connection_description, base::TimeTicks dns_resolution_start_time, base::TimeTicks dns_resolution_end_time, QuicClientPushPromiseIndex* push_promise_index, ServerPushDelegate* push_delegate, base::SequencedTaskRunner* task_runner, std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher, NetLog* net_log) : QuicSpdyClientSessionBase(connection, push_promise_index, config), session_key_(session_key), require_confirmation_(require_confirmation), migrate_session_early_(migrate_session_early), migrate_session_on_network_change_(migrate_sessions_on_network_change), migrate_session_early_v2_(migrate_session_early_v2), migrate_session_on_network_change_v2_( migrate_sessions_on_network_change_v2), max_time_on_non_default_network_(max_time_on_non_default_network), max_migrations_to_non_default_network_on_path_degrading_( max_migrations_to_non_default_network_on_path_degrading), current_migrations_to_non_default_network_on_path_degrading_(0), clock_(clock), yield_after_packets_(yield_after_packets), yield_after_duration_(yield_after_duration), most_recent_path_degrading_timestamp_(base::TimeTicks()), most_recent_network_disconnected_timestamp_(base::TimeTicks()), most_recent_write_error_(0), most_recent_write_error_timestamp_(base::TimeTicks()), stream_factory_(stream_factory), transport_security_state_(transport_security_state), server_info_(std::move(server_info)), pkp_bypassed_(false), is_fatal_cert_error_(false), num_total_streams_(0), task_runner_(task_runner), net_log_(NetLogWithSource::Make(net_log, NetLogSourceType::QUIC_SESSION)), logger_(new QuicConnectionLogger(this, connection_description, std::move(socket_performance_watcher), net_log_)), going_away_(false), port_migration_detected_(false), token_binding_signatures_(kTokenBindingSignatureMapSize), push_delegate_(push_delegate), streams_pushed_count_(0), streams_pushed_and_claimed_count_(0), bytes_pushed_count_(0), bytes_pushed_and_unclaimed_count_(0), probing_manager_(this, task_runner_), retry_migrate_back_count_(0), current_connection_migration_cause_(UNKNOWN), migration_pending_(false), headers_include_h2_stream_dependency_( headers_include_h2_stream_dependency && this->connection()->transport_version() > QUIC_VERSION_42), weak_factory_(this) { default_network_ = socket->GetBoundNetwork(); sockets_.push_back(std::move(socket)); packet_readers_.push_back(std::make_unique<QuicChromiumPacketReader>( sockets_.back().get(), clock, this, yield_after_packets, yield_after_duration, net_log_)); crypto_stream_.reset( crypto_client_stream_factory->CreateQuicCryptoClientStream( session_key.server_id(), this, std::make_unique<ProofVerifyContextChromium>(cert_verify_flags, net_log_), crypto_config)); connection->set_debug_visitor(logger_.get()); connection->set_creator_debug_delegate(logger_.get()); migrate_back_to_default_timer_.SetTaskRunner(task_runner_); net_log_.BeginEvent( NetLogEventType::QUIC_SESSION, base::Bind(NetLogQuicClientSessionCallback, &session_key.server_id(), cert_verify_flags, require_confirmation_)); IPEndPoint address; if (socket && socket->GetLocalAddress(&address) == OK && address.GetFamily() == ADDRESS_FAMILY_IPV6) { connection->SetMaxPacketLength(connection->max_packet_length() - kAdditionalOverheadForIPv6); } connect_timing_.dns_start = dns_resolution_start_time; connect_timing_.dns_end = dns_resolution_end_time; if (migrate_session_early_v2_) { connection->set_retransmittable_on_wire_timeout( QuicTime::Delta::FromMilliseconds( kDefaultRetransmittableOnWireTimeoutMillisecs)); } } QuicChromiumClientSession::~QuicChromiumClientSession() { DCHECK(callback_.is_null()); net_log_.EndEvent(NetLogEventType::QUIC_SESSION); DCHECK(waiting_for_confirmation_callbacks_.empty()); if (!dynamic_streams().empty()) RecordUnexpectedOpenStreams(DESTRUCTOR); if (!handles_.empty()) RecordUnexpectedObservers(DESTRUCTOR); if (!going_away_) RecordUnexpectedNotGoingAway(DESTRUCTOR); while (!dynamic_streams().empty() || !handles_.empty() || !stream_requests_.empty()) { // The session must be closed before it is destroyed. DCHECK(dynamic_streams().empty()); CloseAllStreams(ERR_UNEXPECTED); DCHECK(handles_.empty()); CloseAllHandles(ERR_UNEXPECTED); CancelAllRequests(ERR_UNEXPECTED); connection()->set_debug_visitor(nullptr); } if (connection()->connected()) { // Ensure that the connection is closed by the time the session is // destroyed. RecordInternalErrorLocation(QUIC_CHROMIUM_CLIENT_SESSION_DESTRUCTOR); connection()->CloseConnection(QUIC_INTERNAL_ERROR, "session torn down", ConnectionCloseBehavior::SILENT_CLOSE); } if (IsEncryptionEstablished()) RecordHandshakeState(STATE_ENCRYPTION_ESTABLISHED); if (IsCryptoHandshakeConfirmed()) RecordHandshakeState(STATE_HANDSHAKE_CONFIRMED); else RecordHandshakeState(STATE_FAILED); UMA_HISTOGRAM_COUNTS_1M("Net.QuicSession.NumTotalStreams", num_total_streams_); UMA_HISTOGRAM_COUNTS_1M("Net.QuicNumSentClientHellos", crypto_stream_->num_sent_client_hellos()); UMA_HISTOGRAM_COUNTS_1M("Net.QuicSession.Pushed", streams_pushed_count_); UMA_HISTOGRAM_COUNTS_1M("Net.QuicSession.PushedAndClaimed", streams_pushed_and_claimed_count_); UMA_HISTOGRAM_COUNTS_1M("Net.QuicSession.PushedBytes", bytes_pushed_count_); DCHECK_LE(bytes_pushed_and_unclaimed_count_, bytes_pushed_count_); UMA_HISTOGRAM_COUNTS_1M("Net.QuicSession.PushedAndUnclaimedBytes", bytes_pushed_and_unclaimed_count_); if (!IsCryptoHandshakeConfirmed()) return; // Sending one client_hello means we had zero handshake-round-trips. int round_trip_handshakes = crypto_stream_->num_sent_client_hellos() - 1; // Don't bother with these histogram during tests, which mock out // num_sent_client_hellos(). if (round_trip_handshakes < 0 || !stream_factory_) return; SSLInfo ssl_info; // QUIC supports only secure urls. if (GetSSLInfo(&ssl_info) && ssl_info.cert.get()) { UMA_HISTOGRAM_CUSTOM_COUNTS("Net.QuicSession.ConnectRandomPortForHTTPS", round_trip_handshakes, 1, 3, 4); if (require_confirmation_) { UMA_HISTOGRAM_CUSTOM_COUNTS( "Net.QuicSession.ConnectRandomPortRequiringConfirmationForHTTPS", round_trip_handshakes, 1, 3, 4); } } const QuicConnectionStats stats = connection()->GetStats(); // The MTU used by QUIC is limited to a fairly small set of predefined values // (initial values and MTU discovery values), but does not fare well when // bucketed. Because of that, a sparse histogram is used here. base::UmaHistogramSparse("Net.QuicSession.ClientSideMtu", connection()->max_packet_length()); base::UmaHistogramSparse("Net.QuicSession.ServerSideMtu", stats.max_received_packet_size); UMA_HISTOGRAM_COUNTS_1M("Net.QuicSession.MtuProbesSent", connection()->mtu_probe_count()); if (stats.packets_sent >= 100) { // Used to monitor for regressions that effect large uploads. UMA_HISTOGRAM_COUNTS_1000( "Net.QuicSession.PacketRetransmitsPerMille", 1000 * stats.packets_retransmitted / stats.packets_sent); } if (stats.max_sequence_reordering == 0) return; const base::HistogramBase::Sample kMaxReordering = 100; base::HistogramBase::Sample reordering = kMaxReordering; if (stats.min_rtt_us > 0) { reordering = static_cast<base::HistogramBase::Sample>( 100 * stats.max_time_reordering_us / stats.min_rtt_us); } UMA_HISTOGRAM_CUSTOM_COUNTS("Net.QuicSession.MaxReorderingTime", reordering, 1, kMaxReordering, 50); if (stats.min_rtt_us > 100 * 1000) { UMA_HISTOGRAM_CUSTOM_COUNTS("Net.QuicSession.MaxReorderingTimeLongRtt", reordering, 1, kMaxReordering, 50); } UMA_HISTOGRAM_COUNTS_1M( "Net.QuicSession.MaxReordering", static_cast<base::HistogramBase::Sample>(stats.max_sequence_reordering)); } void QuicChromiumClientSession::Initialize() { QuicSpdyClientSessionBase::Initialize(); SetHpackEncoderDebugVisitor(std::make_unique<HpackEncoderDebugVisitor>()); SetHpackDecoderDebugVisitor(std::make_unique<HpackDecoderDebugVisitor>()); set_max_uncompressed_header_bytes(kMaxUncompressedHeaderSize); } size_t QuicChromiumClientSession::WriteHeaders( QuicStreamId id, spdy::SpdyHeaderBlock headers, bool fin, spdy::SpdyPriority priority, QuicReferenceCountedPointer<QuicAckListenerInterface> ack_notifier_delegate) { spdy::SpdyStreamId parent_stream_id = 0; int weight = 0; bool exclusive = false; if (headers_include_h2_stream_dependency_) { priority_dependency_state_.OnStreamCreation(id, priority, &parent_stream_id, &weight, &exclusive); } else { weight = spdy::Spdy3PriorityToHttp2Weight(priority); } return WriteHeadersImpl(id, std::move(headers), fin, weight, parent_stream_id, exclusive, std::move(ack_notifier_delegate)); } void QuicChromiumClientSession::UnregisterStreamPriority(QuicStreamId id, bool is_static) { if (headers_include_h2_stream_dependency_ && !is_static) { priority_dependency_state_.OnStreamDestruction(id); } QuicSpdySession::UnregisterStreamPriority(id, is_static); } void QuicChromiumClientSession::UpdateStreamPriority( QuicStreamId id, spdy::SpdyPriority new_priority) { if (headers_include_h2_stream_dependency_) { auto updates = priority_dependency_state_.OnStreamUpdate(id, new_priority); for (auto update : updates) { WritePriority(update.id, update.parent_stream_id, update.weight, update.exclusive); } } QuicSpdySession::UpdateStreamPriority(id, new_priority); } void QuicChromiumClientSession::OnStreamFrame(const QuicStreamFrame& frame) { // Record total number of stream frames. UMA_HISTOGRAM_COUNTS_1M("Net.QuicNumStreamFramesInPacket", 1); // Record number of frames per stream in packet. UMA_HISTOGRAM_COUNTS_1M("Net.QuicNumStreamFramesPerStreamInPacket", 1); return QuicSpdySession::OnStreamFrame(frame); } void QuicChromiumClientSession::AddHandle(Handle* handle) { if (going_away_) { RecordUnexpectedObservers(ADD_OBSERVER); handle->OnSessionClosed(connection()->transport_version(), ERR_UNEXPECTED, error(), port_migration_detected_, GetConnectTiming(), WasConnectionEverUsed()); return; } DCHECK(!base::ContainsKey(handles_, handle)); handles_.insert(handle); } void QuicChromiumClientSession::RemoveHandle(Handle* handle) { DCHECK(base::ContainsKey(handles_, handle)); handles_.erase(handle); } // TODO(zhongyi): replace migration_session_* booleans with // ConnectionMigrationMode. ConnectionMigrationMode QuicChromiumClientSession::connection_migration_mode() const { if (migrate_session_early_v2_) return ConnectionMigrationMode::FULL_MIGRATION_V2; if (migrate_session_on_network_change_v2_) return ConnectionMigrationMode::NO_MIGRATION_ON_PATH_DEGRADING_V2; if (migrate_session_early_) return ConnectionMigrationMode::FULL_MIGRATION_V1; if (migrate_session_on_network_change_) return ConnectionMigrationMode::NO_MIGRATION_ON_PATH_DEGRADING_V1; return ConnectionMigrationMode::NO_MIGRATION; } int QuicChromiumClientSession::WaitForHandshakeConfirmation( const CompletionCallback& callback) { if (!connection()->connected()) return ERR_CONNECTION_CLOSED; if (IsCryptoHandshakeConfirmed()) return OK; waiting_for_confirmation_callbacks_.push_back(callback); return ERR_IO_PENDING; } int QuicChromiumClientSession::TryCreateStream(StreamRequest* request) { if (goaway_received()) { DVLOG(1) << "Going away."; return ERR_CONNECTION_CLOSED; } if (!connection()->connected()) { DVLOG(1) << "Already closed."; return ERR_CONNECTION_CLOSED; } if (going_away_) { RecordUnexpectedOpenStreams(TRY_CREATE_STREAM); return ERR_CONNECTION_CLOSED; } if (GetNumOpenOutgoingStreams() < max_open_outgoing_streams()) { request->stream_ = CreateOutgoingReliableStreamImpl(request->traffic_annotation()) ->CreateHandle(); return OK; } request->pending_start_time_ = base::TimeTicks::Now(); stream_requests_.push_back(request); UMA_HISTOGRAM_COUNTS_1000("Net.QuicSession.NumPendingStreamRequests", stream_requests_.size()); return ERR_IO_PENDING; } void QuicChromiumClientSession::CancelRequest(StreamRequest* request) { // Remove |request| from the queue while preserving the order of the // other elements. StreamRequestQueue::iterator it = std::find(stream_requests_.begin(), stream_requests_.end(), request); if (it != stream_requests_.end()) { it = stream_requests_.erase(it); } } bool QuicChromiumClientSession::ShouldCreateOutgoingDynamicStream() { if (!crypto_stream_->encryption_established()) { DVLOG(1) << "Encryption not active so no outgoing stream created."; return false; } if (GetNumOpenOutgoingStreams() >= max_open_outgoing_streams()) { DVLOG(1) << "Failed to create a new outgoing stream. " << "Already " << GetNumOpenOutgoingStreams() << " open."; return false; } if (goaway_received()) { DVLOG(1) << "Failed to create a new outgoing stream. " << "Already received goaway."; return false; } if (going_away_) { RecordUnexpectedOpenStreams(CREATE_OUTGOING_RELIABLE_STREAM); return false; } return true; } bool QuicChromiumClientSession::WasConnectionEverUsed() { const QuicConnectionStats& stats = connection()->GetStats(); return stats.bytes_sent > 0 || stats.bytes_received > 0; } QuicChromiumClientStream* QuicChromiumClientSession::CreateOutgoingDynamicStream() { NOTREACHED() << "CreateOutgoingReliableStreamImpl should be called directly"; return nullptr; } QuicChromiumClientStream* QuicChromiumClientSession::CreateOutgoingReliableStreamImpl( const NetworkTrafficAnnotationTag& traffic_annotation) { DCHECK(connection()->connected()); QuicChromiumClientStream* stream = new QuicChromiumClientStream( GetNextOutgoingStreamId(), this, net_log_, traffic_annotation); ActivateStream(base::WrapUnique(stream)); ++num_total_streams_; UMA_HISTOGRAM_COUNTS_1M("Net.QuicSession.NumOpenStreams", GetNumOpenOutgoingStreams()); // The previous histogram puts 100 in a bucket betweeen 86-113 which does // not shed light on if chrome ever things it has more than 100 streams open. UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.TooManyOpenStreams", GetNumOpenOutgoingStreams() > 100); return stream; } QuicCryptoClientStream* QuicChromiumClientSession::GetMutableCryptoStream() { return crypto_stream_.get(); } const QuicCryptoClientStream* QuicChromiumClientSession::GetCryptoStream() const { return crypto_stream_.get(); } bool QuicChromiumClientSession::GetRemoteEndpoint(IPEndPoint* endpoint) { *endpoint = peer_address().impl().socket_address(); return true; } // TODO(rtenneti): Add unittests for GetSSLInfo which exercise the various ways // we learn about SSL info (sync vs async vs cached). bool QuicChromiumClientSession::GetSSLInfo(SSLInfo* ssl_info) const { ssl_info->Reset(); if (!cert_verify_result_) { return false; } ssl_info->cert_status = cert_verify_result_->cert_status; ssl_info->cert = cert_verify_result_->verified_cert; // Map QUIC AEADs to the corresponding TLS 1.3 cipher. OpenSSL's cipher suite // numbers begin with a stray 0x03, so mask them off. QuicTag aead = crypto_stream_->crypto_negotiated_params().aead; uint16_t cipher_suite; int security_bits; switch (aead) { case kAESG: cipher_suite = TLS1_CK_AES_128_GCM_SHA256 & 0xffff; security_bits = 128; break; case kCC20: cipher_suite = TLS1_CK_CHACHA20_POLY1305_SHA256 & 0xffff; security_bits = 256; break; default: NOTREACHED(); return false; } int ssl_connection_status = 0; SSLConnectionStatusSetCipherSuite(cipher_suite, &ssl_connection_status); SSLConnectionStatusSetVersion(SSL_CONNECTION_VERSION_QUIC, &ssl_connection_status); // Report the QUIC key exchange as the corresponding TLS curve. switch (crypto_stream_->crypto_negotiated_params().key_exchange) { case kP256: ssl_info->key_exchange_group = SSL_CURVE_SECP256R1; break; case kC255: ssl_info->key_exchange_group = SSL_CURVE_X25519; break; default: NOTREACHED(); return false; } ssl_info->public_key_hashes = cert_verify_result_->public_key_hashes; ssl_info->is_issued_by_known_root = cert_verify_result_->is_issued_by_known_root; ssl_info->pkp_bypassed = pkp_bypassed_; ssl_info->connection_status = ssl_connection_status; ssl_info->client_cert_sent = false; ssl_info->channel_id_sent = crypto_stream_->WasChannelIDSent(); ssl_info->security_bits = security_bits; ssl_info->handshake_type = SSLInfo::HANDSHAKE_FULL; ssl_info->pinning_failure_log = pinning_failure_log_; ssl_info->is_fatal_cert_error = is_fatal_cert_error_; ssl_info->UpdateCertificateTransparencyInfo(*ct_verify_result_); if (crypto_stream_->crypto_negotiated_params().token_binding_key_param == kTB10) { ssl_info->token_binding_negotiated = true; ssl_info->token_binding_key_param = TB_PARAM_ECDSAP256; } return true; } Error QuicChromiumClientSession::GetTokenBindingSignature( crypto::ECPrivateKey* key, TokenBindingType tb_type, std::vector<uint8_t>* out) { // The same key will be used across multiple requests to sign the same value, // so the signature is cached. std::string raw_public_key; if (!key->ExportRawPublicKey(&raw_public_key)) return ERR_FAILED; TokenBindingSignatureMap::iterator it = token_binding_signatures_.Get(std::make_pair(tb_type, raw_public_key)); if (it != token_binding_signatures_.end()) { *out = it->second; return OK; } std::string key_material; if (!crypto_stream_->ExportTokenBindingKeyingMaterial(&key_material)) return ERR_FAILED; if (!CreateTokenBindingSignature(key_material, tb_type, key, out)) return ERR_FAILED; token_binding_signatures_.Put(std::make_pair(tb_type, raw_public_key), *out); return OK; } int QuicChromiumClientSession::CryptoConnect( const CompletionCallback& callback) { connect_timing_.connect_start = base::TimeTicks::Now(); RecordHandshakeState(STATE_STARTED); DCHECK(flow_controller()); if (!crypto_stream_->CryptoConnect()) return ERR_QUIC_HANDSHAKE_FAILED; if (IsCryptoHandshakeConfirmed()) { connect_timing_.connect_end = base::TimeTicks::Now(); return OK; } // Unless we require handshake confirmation, activate the session if // we have established initial encryption. if (!require_confirmation_ && IsEncryptionEstablished()) return OK; callback_ = callback; return ERR_IO_PENDING; } int QuicChromiumClientSession::GetNumSentClientHellos() const { return crypto_stream_->num_sent_client_hellos(); } bool QuicChromiumClientSession::CanPool(const std::string& hostname, PrivacyMode privacy_mode, const SocketTag& socket_tag) const { DCHECK(connection()->connected()); if (privacy_mode != session_key_.privacy_mode() || socket_tag != session_key_.socket_tag()) { // Privacy mode and socket tag must always match. return false; } SSLInfo ssl_info; if (!GetSSLInfo(&ssl_info) || !ssl_info.cert.get()) { NOTREACHED() << "QUIC should always have certificates."; return false; } return SpdySession::CanPool(transport_security_state_, ssl_info, session_key_.host(), hostname); } bool QuicChromiumClientSession::ShouldCreateIncomingDynamicStream( QuicStreamId id) { if (!connection()->connected()) { LOG(DFATAL) << "ShouldCreateIncomingDynamicStream called when disconnected"; return false; } if (goaway_received()) { DVLOG(1) << "Cannot create a new outgoing stream. " << "Already received goaway."; return false; } if (going_away_) { return false; } if (id % 2 != 0) { LOG(WARNING) << "Received invalid push stream id " << id; connection()->CloseConnection( QUIC_INVALID_STREAM_ID, "Server created odd numbered stream", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } return true; } QuicChromiumClientStream* QuicChromiumClientSession::CreateIncomingDynamicStream(QuicStreamId id) { if (!ShouldCreateIncomingDynamicStream(id)) { return nullptr; } net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("quic_chromium_incoming_session", R"( semantics { sender: "Quic Chromium Client Session" description: "When a web server needs to push a response to a client, an incoming " "stream is created to reply the client with pushed message instead " "of a message from the network." trigger: "A request by a server to push a response to the client." data: "None." destination: OTHER destination_other: "This stream is not used for sending data." } policy { cookies_allowed: NO setting: "This feature cannot be disabled in settings." policy_exception_justification: "Essential for network access." } )"); return CreateIncomingReliableStreamImpl(id, traffic_annotation); } QuicChromiumClientStream* QuicChromiumClientSession::CreateIncomingReliableStreamImpl( QuicStreamId id, const NetworkTrafficAnnotationTag& traffic_annotation) { DCHECK(connection()->connected()); QuicChromiumClientStream* stream = new QuicChromiumClientStream(id, this, net_log_, traffic_annotation); stream->CloseWriteSide(); ActivateStream(base::WrapUnique(stream)); ++num_total_streams_; return stream; } void QuicChromiumClientSession::CloseStream(QuicStreamId stream_id) { QuicStream* stream = GetOrCreateStream(stream_id); if (stream) { logger_->UpdateReceivedFrameCounts(stream_id, stream->num_frames_received(), stream->num_duplicate_frames_received()); if (stream_id % 2 == 0) { // Stream with even stream is initiated by server for PUSH. bytes_pushed_count_ += stream->stream_bytes_read(); } } QuicSpdySession::CloseStream(stream_id); OnClosedStream(); } void QuicChromiumClientSession::SendRstStream(QuicStreamId id, QuicRstStreamErrorCode error, QuicStreamOffset bytes_written) { QuicStream* stream = GetOrCreateStream(id); if (stream) { if (id % 2 == 0) { // Stream with even stream is initiated by server for PUSH. bytes_pushed_count_ += stream->stream_bytes_read(); } } QuicSpdySession::SendRstStream(id, error, bytes_written); OnClosedStream(); } void QuicChromiumClientSession::OnClosedStream() { if (GetNumOpenOutgoingStreams() < max_open_outgoing_streams() && !stream_requests_.empty() && crypto_stream_->encryption_established() && !goaway_received() && !going_away_ && connection()->connected()) { StreamRequest* request = stream_requests_.front(); // TODO(ckrasic) - analyze data and then add logic to mark QUIC // broken if wait times are excessive. UMA_HISTOGRAM_TIMES("Net.QuicSession.PendingStreamsWaitTime", base::TimeTicks::Now() - request->pending_start_time_); stream_requests_.pop_front(); request->OnRequestCompleteSuccess( CreateOutgoingReliableStreamImpl(request->traffic_annotation()) ->CreateHandle()); } if (GetNumOpenOutgoingStreams() == 0 && stream_factory_) { stream_factory_->OnIdleSession(this); } } void QuicChromiumClientSession::OnConfigNegotiated() { QuicSpdyClientSessionBase::OnConfigNegotiated(); if (!stream_factory_ || !config()->HasReceivedAlternateServerAddress()) return; // Server has sent an alternate address to connect to. IPEndPoint new_address = config()->ReceivedAlternateServerAddress().impl().socket_address(); IPEndPoint old_address; GetDefaultSocket()->GetPeerAddress(&old_address); // Migrate only if address families match, or if new address family is v6, // since a v4 address should be reachable over a v6 network (using a // v4-mapped v6 address). if (old_address.GetFamily() != new_address.GetFamily() && old_address.GetFamily() == ADDRESS_FAMILY_IPV4) { return; } if (old_address.GetFamily() != new_address.GetFamily()) { DCHECK_EQ(old_address.GetFamily(), ADDRESS_FAMILY_IPV6); DCHECK_EQ(new_address.GetFamily(), ADDRESS_FAMILY_IPV4); // Use a v4-mapped v6 address. new_address = IPEndPoint(ConvertIPv4ToIPv4MappedIPv6(new_address.address()), new_address.port()); } if (!stream_factory_->allow_server_migration()) return; // Specifying kInvalidNetworkHandle for the |network| parameter // causes the session to use the default network for the new socket. Migrate(NetworkChangeNotifier::kInvalidNetworkHandle, new_address, /*close_session_on_error*/ true, net_log_); } void QuicChromiumClientSession::OnCryptoHandshakeEvent( CryptoHandshakeEvent event) { if (!callback_.is_null() && (!require_confirmation_ || event == HANDSHAKE_CONFIRMED || event == ENCRYPTION_REESTABLISHED)) { // TODO(rtenneti): Currently for all CryptoHandshakeEvent events, callback_ // could be called because there are no error events in CryptoHandshakeEvent // enum. If error events are added to CryptoHandshakeEvent, then the // following code needs to changed. base::ResetAndReturn(&callback_).Run(OK); } if (event == HANDSHAKE_CONFIRMED) { if (stream_factory_) stream_factory_->set_require_confirmation(false); // Update |connect_end| only when handshake is confirmed. This should also // take care of any failed 0-RTT request. connect_timing_.connect_end = base::TimeTicks::Now(); DCHECK_LE(connect_timing_.connect_start, connect_timing_.connect_end); UMA_HISTOGRAM_TIMES( "Net.QuicSession.HandshakeConfirmedTime", connect_timing_.connect_end - connect_timing_.connect_start); // Track how long it has taken to finish handshake after we have finished // DNS host resolution. if (!connect_timing_.dns_end.is_null()) { UMA_HISTOGRAM_TIMES( "Net.QuicSession.HostResolution.HandshakeConfirmedTime", base::TimeTicks::Now() - connect_timing_.dns_end); } HandleSet::iterator it = handles_.begin(); while (it != handles_.end()) { Handle* handle = *it; ++it; handle->OnCryptoHandshakeConfirmed(); } NotifyRequestsOfConfirmation(OK); } QuicSpdySession::OnCryptoHandshakeEvent(event); } void QuicChromiumClientSession::OnCryptoHandshakeMessageSent( const CryptoHandshakeMessage& message) { logger_->OnCryptoHandshakeMessageSent(message); } void QuicChromiumClientSession::OnCryptoHandshakeMessageReceived( const CryptoHandshakeMessage& message) { logger_->OnCryptoHandshakeMessageReceived(message); if (message.tag() == kREJ || message.tag() == kSREJ) { UMA_HISTOGRAM_CUSTOM_COUNTS( "Net.QuicSession.RejectLength", message.GetSerialized(Perspective::IS_CLIENT).length(), 1000, 10000, 50); QuicStringPiece proof; UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.RejectHasProof", message.GetStringPiece(kPROF, &proof)); } } void QuicChromiumClientSession::OnGoAway(const QuicGoAwayFrame& frame) { QuicSession::OnGoAway(frame); NotifyFactoryOfSessionGoingAway(); port_migration_detected_ = frame.error_code == QUIC_ERROR_MIGRATING_PORT; } void QuicChromiumClientSession::OnRstStream(const QuicRstStreamFrame& frame) { QuicSession::OnRstStream(frame); OnClosedStream(); } void QuicChromiumClientSession::OnConnectionClosed( QuicErrorCode error, const std::string& error_details, ConnectionCloseSource source) { DCHECK(!connection()->connected()); logger_->OnConnectionClosed(error, error_details, source); if (source == ConnectionCloseSource::FROM_PEER) { if (IsCryptoHandshakeConfirmed()) { base::UmaHistogramSparse( "Net.QuicSession.ConnectionCloseErrorCodeServer.HandshakeConfirmed", error); base::HistogramBase* histogram = base::SparseHistogram::FactoryGet( "Net.QuicSession.StreamCloseErrorCodeServer.HandshakeConfirmed", base::HistogramBase::kUmaTargetedHistogramFlag); size_t num_streams = GetNumActiveStreams(); if (num_streams > 0) histogram->AddCount(error, num_streams); } base::UmaHistogramSparse("Net.QuicSession.ConnectionCloseErrorCodeServer", error); } else { if (IsCryptoHandshakeConfirmed()) { base::UmaHistogramSparse( "Net.QuicSession.ConnectionCloseErrorCodeClient.HandshakeConfirmed", error); base::HistogramBase* histogram = base::SparseHistogram::FactoryGet( "Net.QuicSession.StreamCloseErrorCodeClient.HandshakeConfirmed", base::HistogramBase::kUmaTargetedHistogramFlag); size_t num_streams = GetNumActiveStreams(); if (num_streams > 0) histogram->AddCount(error, num_streams); } base::UmaHistogramSparse("Net.QuicSession.ConnectionCloseErrorCodeClient", error); } if (error == QUIC_NETWORK_IDLE_TIMEOUT) { UMA_HISTOGRAM_COUNTS_1M( "Net.QuicSession.ConnectionClose.NumOpenStreams.TimedOut", GetNumOpenOutgoingStreams()); if (IsCryptoHandshakeConfirmed()) { if (GetNumOpenOutgoingStreams() > 0) { UMA_HISTOGRAM_BOOLEAN( "Net.QuicSession.TimedOutWithOpenStreams.HasUnackedPackets", connection()->sent_packet_manager().HasUnackedPackets()); UMA_HISTOGRAM_COUNTS_1M( "Net.QuicSession.TimedOutWithOpenStreams.ConsecutiveRTOCount", connection()->sent_packet_manager().GetConsecutiveRtoCount()); UMA_HISTOGRAM_COUNTS_1M( "Net.QuicSession.TimedOutWithOpenStreams.ConsecutiveTLPCount", connection()->sent_packet_manager().GetConsecutiveTlpCount()); base::UmaHistogramSparse( "Net.QuicSession.TimedOutWithOpenStreams.LocalPort", connection()->self_address().port()); } } else { UMA_HISTOGRAM_COUNTS_1M( "Net.QuicSession.ConnectionClose.NumOpenStreams.HandshakeTimedOut", GetNumOpenOutgoingStreams()); UMA_HISTOGRAM_COUNTS_1M( "Net.QuicSession.ConnectionClose.NumTotalStreams.HandshakeTimedOut", num_total_streams_); } } if (IsCryptoHandshakeConfirmed()) { // QUIC connections should not timeout while there are open streams, // since PING frames are sent to prevent timeouts. If, however, the // connection timed out with open streams then QUIC traffic has become // blackholed. Alternatively, if too many retransmission timeouts occur // then QUIC traffic has become blackholed. if (stream_factory_ && (error == QUIC_TOO_MANY_RTOS || (error == QUIC_NETWORK_IDLE_TIMEOUT && GetNumOpenOutgoingStreams() > 0))) { stream_factory_->OnBlackholeAfterHandshakeConfirmed(this); } } else { if (error == QUIC_PUBLIC_RESET) { RecordHandshakeFailureReason(HANDSHAKE_FAILURE_PUBLIC_RESET); } else if (connection()->GetStats().packets_received == 0) { RecordHandshakeFailureReason(HANDSHAKE_FAILURE_BLACK_HOLE); base::UmaHistogramSparse( "Net.QuicSession.ConnectionClose.HandshakeFailureBlackHole.QuicError", error); } else { RecordHandshakeFailureReason(HANDSHAKE_FAILURE_UNKNOWN); base::UmaHistogramSparse( "Net.QuicSession.ConnectionClose.HandshakeFailureUnknown.QuicError", error); } } base::UmaHistogramSparse("Net.QuicSession.QuicVersion", connection()->transport_version()); NotifyFactoryOfSessionGoingAway(); QuicSession::OnConnectionClosed(error, error_details, source); if (!callback_.is_null()) { base::ResetAndReturn(&callback_).Run(ERR_QUIC_PROTOCOL_ERROR); } for (auto& socket : sockets_) { socket->Close(); } DCHECK(dynamic_streams().empty()); CloseAllStreams(ERR_UNEXPECTED); CloseAllHandles(ERR_UNEXPECTED); CancelAllRequests(ERR_CONNECTION_CLOSED); NotifyRequestsOfConfirmation(ERR_CONNECTION_CLOSED); NotifyFactoryOfSessionClosedLater(); } void QuicChromiumClientSession::OnSuccessfulVersionNegotiation( const ParsedQuicVersion& version) { logger_->OnSuccessfulVersionNegotiation(version); QuicSpdySession::OnSuccessfulVersionNegotiation(version); } void QuicChromiumClientSession::OnConnectivityProbeReceived( const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address) { DVLOG(1) << "Probing response from ip:port: " << peer_address.ToString() << " to ip:port: " << self_address.ToString() << " is received"; // Notify the probing manager that a connectivity probing packet is received. probing_manager_.OnConnectivityProbingReceived(self_address, peer_address); } int QuicChromiumClientSession::HandleWriteError( int error_code, scoped_refptr<QuicChromiumPacketWriter::ReusableIOBuffer> packet) { base::UmaHistogramSparse("Net.QuicSession.WriteError", -error_code); if (IsCryptoHandshakeConfirmed()) { base::UmaHistogramSparse("Net.QuicSession.WriteError.HandshakeConfirmed", -error_code); } if (error_code == ERR_MSG_TOO_BIG || stream_factory_ == nullptr || !stream_factory_->migrate_sessions_on_network_change()) { return error_code; } NetworkChangeNotifier::NetworkHandle current_network = GetDefaultSocket()->GetBoundNetwork(); net_log_.AddEvent(NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_WRITE_ERROR, NetLog::Int64Callback("network", current_network)); DCHECK(packet != nullptr); DCHECK_NE(ERR_IO_PENDING, error_code); DCHECK_GT(0, error_code); DCHECK(!migration_pending_); DCHECK(packet_ == nullptr); // Post a task to migrate the session onto a new network. task_runner_->PostTask( FROM_HERE, base::Bind(&QuicChromiumClientSession::MigrateSessionOnWriteError, weak_factory_.GetWeakPtr(), error_code)); // Store packet in the session since the actual migration and packet rewrite // can happen via this posted task or via an async network notification. packet_ = std::move(packet); migration_pending_ = true; // Cause the packet writer to return ERR_IO_PENDING and block so // that the actual migration happens from the message loop instead // of under the call stack of QuicConnection::WritePacket. return ERR_IO_PENDING; } void QuicChromiumClientSession::MigrateSessionOnWriteError(int error_code) { most_recent_write_error_timestamp_ = base::TimeTicks::Now(); most_recent_write_error_ = error_code; // If migration_pending_ is false, an earlier task completed migration. if (!migration_pending_) return; current_connection_migration_cause_ = ON_WRITE_ERROR; MigrationResult result = MigrationResult::FAILURE; if (stream_factory_ != nullptr) { LogHandshakeStatusOnConnectionMigrationSignal(); const NetLogWithSource migration_net_log = NetLogWithSource::Make( net_log_.net_log(), NetLogSourceType::QUIC_CONNECTION_MIGRATION); migration_net_log.BeginEvent( NetLogEventType::QUIC_CONNECTION_MIGRATION_TRIGGERED, base::Bind(&NetLogQuicConnectionMigrationTriggerCallback, "WriteError")); result = MigrateToAlternateNetwork(/*close_session_on_error*/ false, migration_net_log); migration_net_log.EndEvent( NetLogEventType::QUIC_CONNECTION_MIGRATION_TRIGGERED); } if (result == MigrationResult::SUCCESS) return; if (result == MigrationResult::NO_NEW_NETWORK) { OnNoNewNetwork(); return; } // Close the connection if migration failed. Do not cause a // connection close packet to be sent since socket may be borked. connection()->CloseConnection(QUIC_PACKET_WRITE_ERROR, "Write and subsequent migration failed", ConnectionCloseBehavior::SILENT_CLOSE); } void QuicChromiumClientSession::OnNoNewNetwork() { migration_pending_ = true; // Block the packet writer to avoid any writes while migration is in progress. static_cast<QuicChromiumPacketWriter*>(connection()->writer()) ->set_write_blocked(true); // Post a task to maybe close the session if the alarm fires. task_runner_->PostDelayedTask( FROM_HERE, base::Bind(&QuicChromiumClientSession::OnMigrationTimeout, weak_factory_.GetWeakPtr(), sockets_.size()), base::TimeDelta::FromSeconds(kWaitTimeForNewNetworkSecs)); } void QuicChromiumClientSession::WriteToNewSocket() { // Prevent any pending migration from executing. migration_pending_ = false; static_cast<QuicChromiumPacketWriter*>(connection()->writer()) ->set_write_blocked(false); if (packet_ == nullptr) { // Unblock the connection before sending a PING packet, since it // may have been blocked before the migration started. connection()->OnCanWrite(); SendPing(); return; } // The connection is waiting for the original write to complete // asynchronously. The new writer will notify the connection if the // write below completes asynchronously, but a synchronous competion // must be propagated back to the connection here. WriteResult result = static_cast<QuicChromiumPacketWriter*>(connection()->writer()) ->WritePacketToSocket(std::move(packet_)); if (result.error_code == ERR_IO_PENDING) return; // All write errors should be mapped into ERR_IO_PENDING by // HandleWriteError. DCHECK_LT(0, result.error_code); connection()->OnCanWrite(); } void QuicChromiumClientSession::OnMigrationTimeout(size_t num_sockets) { // If number of sockets has changed, this migration task is stale. if (num_sockets != sockets_.size()) return; LogConnectionMigrationResultToHistogram(MIGRATION_STATUS_TIMEOUT); CloseSessionOnError(ERR_NETWORK_CHANGED, QUIC_CONNECTION_MIGRATION_NO_NEW_NETWORK); } void QuicChromiumClientSession::OnProbeNetworkSucceeded( NetworkChangeNotifier::NetworkHandle network, const QuicSocketAddress& self_address, std::unique_ptr<DatagramClientSocket> socket, std::unique_ptr<QuicChromiumPacketWriter> writer, std::unique_ptr<QuicChromiumPacketReader> reader) { DCHECK(socket); DCHECK(writer); DCHECK(reader); net_log_.AddEvent( NetLogEventType::QUIC_CONNECTION_CONNECTIVITY_PROBING_SUCCEEDED, NetLog::Int64Callback("network", network)); LogProbeResultToHistogram(current_connection_migration_cause_, true); // Set |this| to listen on socket write events on the packet writer // that was used for probing. writer->set_delegate(this); connection()->SetSelfAddress(self_address); // Migrate to the probed socket immediately: socket, writer and reader will // be acquired by connection and used as default on success. if (!MigrateToSocket(std::move(socket), std::move(reader), std::move(writer))) { net_log_.AddEvent( NetLogEventType::QUIC_CONNECTION_MIGRATION_FAILURE_AFTER_PROBING); return; } net_log_.AddEvent( NetLogEventType::QUIC_CONNECTION_MIGRATION_SUCCESS_AFTER_PROBING, NetLog::Int64Callback("migrate_to_network", network)); if (network == default_network_) { DVLOG(1) << "Client successfully migrated to default network."; CancelMigrateBackToDefaultNetworkTimer(); } else { DVLOG(1) << "Client successfully got off default network after " << "successful probing network: " << network << "."; current_migrations_to_non_default_network_on_path_degrading_++; if (!migrate_back_to_default_timer_.IsRunning()) { current_connection_migration_cause_ = ON_MIGRATE_BACK_TO_DEFAULT_NETWORK; // Session gets off the |default_network|, stay on |network| for now but // try to migrate back to default network after 1 second. StartMigrateBackToDefaultNetworkTimer( base::TimeDelta::FromSeconds(kMinRetryTimeForDefaultNetworkSecs)); } } } void QuicChromiumClientSession::OnProbeNetworkFailed( NetworkChangeNotifier::NetworkHandle network) { net_log_.AddEvent( NetLogEventType::QUIC_CONNECTION_CONNECTIVITY_PROBING_FAILED, NetLog::Int64Callback("network", network)); LogProbeResultToHistogram(current_connection_migration_cause_, false); // Probing failure for default network can be ignored. DVLOG(1) << "Connectivity probing failed on NetworkHandle " << network; DVLOG_IF(1, network == default_network_ && GetDefaultSocket()->GetBoundNetwork() != default_network_) << "Client probing failed on the default network, QUIC still " "using non-default network."; } bool QuicChromiumClientSession::OnSendConnectivityProbingPacket( QuicChromiumPacketWriter* writer, const QuicSocketAddress& peer_address) { return connection()->SendConnectivityProbingPacket(writer, peer_address); } void QuicChromiumClientSession::OnNetworkConnected( NetworkChangeNotifier::NetworkHandle network, const NetLogWithSource& net_log) { net_log_.AddEvent( NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_NETWORK_CONNECTED, NetLog::Int64Callback("connected_network", network)); // If there was no migration pending and the path is not degrading, ignore // this signal. if (!migration_pending_ && !connection()->IsPathDegrading()) return; current_connection_migration_cause_ = ON_NETWORK_CONNECTED; if (migrate_session_on_network_change_v2_) { LogHandshakeStatusOnConnectionMigrationSignal(); if (migration_pending_) { // |migration_pending_| is true, there was no working network previously. // |network| is now the only possible candidate, migrate immediately. MigrateImmediately(network); } else { // The connection is path degrading. DCHECK(connection()->IsPathDegrading()); OnPathDegrading(); } return; } // TODO(jri): Ensure that OnSessionGoingAway is called consistently, // and that it's always called at the same time in the whole // migration process. Allows tests to be more uniform. stream_factory_->OnSessionGoingAway(this); Migrate(network, connection()->peer_address().impl().socket_address(), /*close_session_on_error=*/true, net_log); } void QuicChromiumClientSession::OnNetworkDisconnected( NetworkChangeNotifier::NetworkHandle alternate_network, const NetLogWithSource& migration_net_log) { LogMetricsOnNetworkDisconnected(); if (!migrate_session_on_network_change_) return; current_connection_migration_cause_ = ON_NETWORK_DISCONNECTED; MaybeMigrateOrCloseSession( alternate_network, /*close_if_cannot_migrate*/ true, migration_net_log); } void QuicChromiumClientSession::OnNetworkDisconnectedV2( NetworkChangeNotifier::NetworkHandle disconnected_network, const NetLogWithSource& migration_net_log) { net_log_.AddEvent( NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_NETWORK_DISCONNECTED, NetLog::Int64Callback("disconnected_network", disconnected_network)); LogMetricsOnNetworkDisconnected(); if (!migrate_session_on_network_change_v2_) return; // Stop probing the disconnected network if there is one. probing_manager_.CancelProbing(disconnected_network); // Ignore the signal if the current active network is not affected. if (GetDefaultSocket()->GetBoundNetwork() != disconnected_network) { DVLOG(1) << "Client's current default network is not affected by the " << "disconnected one."; return; } current_connection_migration_cause_ = ON_NETWORK_DISCONNECTED; // Attempt to find alternative network. NetworkChangeNotifier::NetworkHandle new_network = stream_factory_->FindAlternateNetwork(disconnected_network); if (new_network == NetworkChangeNotifier::kInvalidNetworkHandle) { OnNoNewNetwork(); return; } LogHandshakeStatusOnConnectionMigrationSignal(); // Current network is being disconnected, migrate immediately to the // alternative network. MigrateImmediately(new_network); } void QuicChromiumClientSession::OnNetworkMadeDefault( NetworkChangeNotifier::NetworkHandle new_network, const NetLogWithSource& migration_net_log) { net_log_.AddEvent( NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_NETWORK_MADE_DEFAULT, NetLog::Int64Callback("new_default_network", new_network)); LogMetricsOnNetworkMadeDefault(); if (!migrate_session_on_network_change_ && !migrate_session_on_network_change_v2_) return; DCHECK_NE(NetworkChangeNotifier::kInvalidNetworkHandle, new_network); default_network_ = new_network; current_connection_migration_cause_ = ON_NETWORK_MADE_DEFAULT; if (!migrate_session_on_network_change_v2_) { MaybeMigrateOrCloseSession(new_network, /*close_if_cannot_migrate*/ false, migration_net_log); return; } current_migrations_to_non_default_network_on_path_degrading_ = 0; // Connection migration v2. // If we are already on the new network, simply cancel the timer to migrate // back to the default network. if (GetDefaultSocket()->GetBoundNetwork() == new_network) { CancelMigrateBackToDefaultNetworkTimer(); HistogramAndLogMigrationFailure( migration_net_log, MIGRATION_STATUS_ALREADY_MIGRATED, connection_id(), "Already migrated on the new network"); return; } LogHandshakeStatusOnConnectionMigrationSignal(); // Stay on the current network. Try to migrate back to default network // without any delay, which will start probing the new default network and // migrate to the new network immediately on success. StartMigrateBackToDefaultNetworkTimer(base::TimeDelta()); } void QuicChromiumClientSession::MigrateImmediately( NetworkChangeNotifier::NetworkHandle network) { // We have no choice but to migrate to |network|. If any error encoutered, // close the session. When migration succeeds: if we are no longer on the // default interface, start timer to migrate back to the default network; // otherwise, we are now on default networ, cancel timer to migrate back // to the defautlt network if it is running. if (!ShouldMigrateSession(/*close_if_cannot_migrate*/ true, network, net_log_)) { return; } if (network == GetDefaultSocket()->GetBoundNetwork()) return; // Cancel probing on |network| if there is any. probing_manager_.CancelProbing(network); MigrationResult result = Migrate(network, connection()->peer_address().impl().socket_address(), /*close_session_on_error=*/true, net_log_); if (result == MigrationResult::FAILURE) return; if (network != default_network_) { // TODO(zhongyi): reconsider this, maybe we just want to hear back // We are forced to migrate to |network|, probably |default_network_| is // not working, start to migrate back to default network after 1 secs. StartMigrateBackToDefaultNetworkTimer( base::TimeDelta::FromSeconds(kMinRetryTimeForDefaultNetworkSecs)); } else { CancelMigrateBackToDefaultNetworkTimer(); } } void QuicChromiumClientSession::OnWriteError(int error_code) { DCHECK_NE(ERR_IO_PENDING, error_code); DCHECK_GT(0, error_code); connection()->OnWriteError(error_code); } void QuicChromiumClientSession::OnWriteUnblocked() { connection()->OnCanWrite(); } void QuicChromiumClientSession::OnPathDegrading() { net_log_.AddEvent( NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_PATH_DEGRADING); if (most_recent_path_degrading_timestamp_ == base::TimeTicks()) most_recent_path_degrading_timestamp_ = base::TimeTicks::Now(); if (stream_factory_) { const NetLogWithSource migration_net_log = NetLogWithSource::Make( net_log_.net_log(), NetLogSourceType::QUIC_CONNECTION_MIGRATION); migration_net_log.BeginEvent( NetLogEventType::QUIC_CONNECTION_MIGRATION_TRIGGERED, base::Bind(&NetLogQuicConnectionMigrationTriggerCallback, "PathDegrading")); if (migrate_session_early_v2_) { NetworkChangeNotifier::NetworkHandle alternate_network = stream_factory_->FindAlternateNetwork( GetDefaultSocket()->GetBoundNetwork()); current_connection_migration_cause_ = ON_PATH_DEGRADING; if (alternate_network != NetworkChangeNotifier::kInvalidNetworkHandle) { if (GetDefaultSocket()->GetBoundNetwork() == default_network_ && current_migrations_to_non_default_network_on_path_degrading_ >= max_migrations_to_non_default_network_on_path_degrading_) { HistogramAndLogMigrationFailure( migration_net_log, MIGRATION_STATUS_ON_PATH_DEGRADING_DISABLED, connection_id(), "Exceeds maximum number of migrations on path degrading"); } else { LogHandshakeStatusOnConnectionMigrationSignal(); // Probe alternative network, session will migrate to the probed // network and decide whether it wants to migrate back to the default // network on success. StartProbeNetwork( alternate_network, connection()->peer_address().impl().socket_address(), migration_net_log); } } else { HistogramAndLogMigrationFailure( migration_net_log, MIGRATION_STATUS_NO_ALTERNATE_NETWORK, connection_id(), "No alternative network on path degrading"); } } else if (migrate_session_early_) { MigrateToAlternateNetwork(/*close_session_on_error*/ true, migration_net_log); } else { HistogramAndLogMigrationFailure( migration_net_log, MIGRATION_STATUS_PATH_DEGRADING_NOT_ENABLED, connection_id(), "Migration on path degrading not enabled"); } migration_net_log.EndEvent( NetLogEventType::QUIC_CONNECTION_MIGRATION_TRIGGERED); } } bool QuicChromiumClientSession::HasOpenDynamicStreams() const { return QuicSession::HasOpenDynamicStreams() || GetNumDrainingOutgoingStreams() > 0; } void QuicChromiumClientSession::OnProofValid( const QuicCryptoClientConfig::CachedState& cached) { DCHECK(cached.proof_valid()); if (!server_info_) { return; } QuicServerInfo::State* state = server_info_->mutable_state(); state->server_config = cached.server_config(); state->source_address_token = cached.source_address_token(); state->cert_sct = cached.cert_sct(); state->chlo_hash = cached.chlo_hash(); state->server_config_sig = cached.signature(); state->certs = cached.certs(); server_info_->Persist(); } void QuicChromiumClientSession::OnProofVerifyDetailsAvailable( const ProofVerifyDetails& verify_details) { const ProofVerifyDetailsChromium* verify_details_chromium = reinterpret_cast<const ProofVerifyDetailsChromium*>(&verify_details); cert_verify_result_.reset( new CertVerifyResult(verify_details_chromium->cert_verify_result)); pinning_failure_log_ = verify_details_chromium->pinning_failure_log; std::unique_ptr<ct::CTVerifyResult> ct_verify_result_copy( new ct::CTVerifyResult(verify_details_chromium->ct_verify_result)); ct_verify_result_ = std::move(ct_verify_result_copy); logger_->OnCertificateVerified(*cert_verify_result_); pkp_bypassed_ = verify_details_chromium->pkp_bypassed; is_fatal_cert_error_ = verify_details_chromium->is_fatal_cert_error; } void QuicChromiumClientSession::StartReading() { for (auto& packet_reader : packet_readers_) { packet_reader->StartReading(); } } void QuicChromiumClientSession::CloseSessionOnError(int net_error, QuicErrorCode quic_error) { base::UmaHistogramSparse("Net.QuicSession.CloseSessionOnError", -net_error); if (quic_error == QUIC_INTERNAL_ERROR) { RecordInternalErrorLocation( QUIC_CHROMIUM_CLIENT_SESSION_CLOSE_SESSION_ON_ERROR); } if (!callback_.is_null()) { base::ResetAndReturn(&callback_).Run(net_error); } CloseAllStreams(net_error); CloseAllHandles(net_error); net_log_.AddEvent(NetLogEventType::QUIC_SESSION_CLOSE_ON_ERROR, NetLog::IntCallback("net_error", net_error)); if (connection()->connected()) connection()->CloseConnection(quic_error, "net error", ConnectionCloseBehavior::SILENT_CLOSE); DCHECK(!connection()->connected()); NotifyFactoryOfSessionClosed(); } void QuicChromiumClientSession::CloseSessionOnErrorLater( int net_error, QuicErrorCode quic_error) { base::UmaHistogramSparse("Net.QuicSession.CloseSessionOnError", -net_error); if (!callback_.is_null()) { base::ResetAndReturn(&callback_).Run(net_error); } CloseAllStreams(net_error); CloseAllHandles(net_error); net_log_.AddEvent(NetLogEventType::QUIC_SESSION_CLOSE_ON_ERROR, NetLog::IntCallback("net_error", net_error)); if (connection()->connected()) connection()->CloseConnection(quic_error, "net error", ConnectionCloseBehavior::SILENT_CLOSE); DCHECK(!connection()->connected()); NotifyFactoryOfSessionClosedLater(); } void QuicChromiumClientSession::CloseAllStreams(int net_error) { while (!dynamic_streams().empty()) { QuicStream* stream = dynamic_streams().begin()->second.get(); QuicStreamId id = stream->id(); static_cast<QuicChromiumClientStream*>(stream)->OnError(net_error); CloseStream(id); } } void QuicChromiumClientSession::CloseAllHandles(int net_error) { while (!handles_.empty()) { Handle* handle = *handles_.begin(); handles_.erase(handle); handle->OnSessionClosed(connection()->transport_version(), net_error, error(), port_migration_detected_, GetConnectTiming(), WasConnectionEverUsed()); } } void QuicChromiumClientSession::CancelAllRequests(int net_error) { UMA_HISTOGRAM_COUNTS_1000("Net.QuicSession.AbortedPendingStreamRequests", stream_requests_.size()); while (!stream_requests_.empty()) { StreamRequest* request = stream_requests_.front(); stream_requests_.pop_front(); request->OnRequestCompleteFailure(net_error); } } void QuicChromiumClientSession::NotifyRequestsOfConfirmation(int net_error) { // Post tasks to avoid reentrancy. for (auto callback : waiting_for_confirmation_callbacks_) task_runner_->PostTask(FROM_HERE, base::Bind(callback, net_error)); waiting_for_confirmation_callbacks_.clear(); } ProbingResult QuicChromiumClientSession::StartProbeNetwork( NetworkChangeNotifier::NetworkHandle network, IPEndPoint peer_address, const NetLogWithSource& migration_net_log) { if (!stream_factory_) return ProbingResult::FAILURE; CHECK_NE(NetworkChangeNotifier::kInvalidNetworkHandle, network); if (GetNumActiveStreams() == 0) { HistogramAndLogMigrationFailure(migration_net_log, MIGRATION_STATUS_NO_MIGRATABLE_STREAMS, connection_id(), "No active streams"); CloseSessionOnErrorLater(ERR_NETWORK_CHANGED, QUIC_CONNECTION_MIGRATION_NO_MIGRATABLE_STREAMS); return ProbingResult::DISABLED_WITH_IDLE_SESSION; } // Abort probing if connection migration is disabled by config. if (config()->DisableConnectionMigration()) { DVLOG(1) << "Client disables probing network with connection migration " << "disabled by config"; HistogramAndLogMigrationFailure( migration_net_log, MIGRATION_STATUS_DISABLED_BY_CONFIG, connection_id(), "Migration disabled by config"); // TODO(zhongyi): do we want to close the session? return ProbingResult::DISABLED_BY_CONFIG; } // TODO(zhongyi): migrate the session still, but reset non-migratable stream. // TODO(zhongyi): migrate non-migrtable stream if moving from Cellular to // wifi. // Abort probing if there is stream marked as non-migratable. if (HasNonMigratableStreams()) { DVLOG(1) << "Clients disables probing network with non-migratable streams"; HistogramAndLogMigrationFailure(migration_net_log, MIGRATION_STATUS_NON_MIGRATABLE_STREAM, connection_id(), "Non-migratable stream"); return ProbingResult::DISABLED_BY_NON_MIGRABLE_STREAM; } // Check if probing manager is probing the same path. if (probing_manager_.IsUnderProbing( network, QuicSocketAddress(QuicSocketAddressImpl(peer_address)))) { return ProbingResult::PENDING; } // Create and configure socket on |network|. std::unique_ptr<DatagramClientSocket> probing_socket = stream_factory_->CreateSocket(net_log_.net_log(), net_log_.source()); if (stream_factory_->ConfigureSocket(probing_socket.get(), peer_address, network, session_key_.socket_tag()) != OK) { HistogramAndLogMigrationFailure( migration_net_log, MIGRATION_STATUS_INTERNAL_ERROR, connection_id(), "Socket configuration failed"); return ProbingResult::INTERNAL_ERROR; } // Create new packet writer and reader on the probing socket. std::unique_ptr<QuicChromiumPacketWriter> probing_writer( new QuicChromiumPacketWriter(probing_socket.get(), task_runner_)); std::unique_ptr<QuicChromiumPacketReader> probing_reader( new QuicChromiumPacketReader(probing_socket.get(), clock_, this, yield_after_packets_, yield_after_duration_, net_log_)); int rtt_ms = connection() ->sent_packet_manager() .GetRttStats() ->smoothed_rtt() .ToMilliseconds(); if (rtt_ms == 0 || rtt_ms > kDefaultRTTMilliSecs) rtt_ms = kDefaultRTTMilliSecs; int timeout_ms = rtt_ms * 2; probing_manager_.StartProbing( network, QuicSocketAddress(QuicSocketAddressImpl(peer_address)), std::move(probing_socket), std::move(probing_writer), std::move(probing_reader), base::TimeDelta::FromMilliseconds(timeout_ms), net_log_); return ProbingResult::PENDING; } void QuicChromiumClientSession::StartMigrateBackToDefaultNetworkTimer( base::TimeDelta delay) { if (current_connection_migration_cause_ != ON_NETWORK_MADE_DEFAULT) current_connection_migration_cause_ = ON_MIGRATE_BACK_TO_DEFAULT_NETWORK; CancelMigrateBackToDefaultNetworkTimer(); // Post a task to try migrate back to default network after |delay|. migrate_back_to_default_timer_.Start( FROM_HERE, delay, base::Bind( &QuicChromiumClientSession::MaybeRetryMigrateBackToDefaultNetwork, weak_factory_.GetWeakPtr())); } void QuicChromiumClientSession::CancelMigrateBackToDefaultNetworkTimer() { retry_migrate_back_count_ = 0; migrate_back_to_default_timer_.Stop(); } void QuicChromiumClientSession::TryMigrateBackToDefaultNetwork( base::TimeDelta timeout) { net_log_.AddEvent(NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_MIGRATE_BACK, base::Bind(NetLog::Int64Callback( "retry_count", retry_migrate_back_count_))); // Start probe default network immediately, if manager is probing // the same network, this will be a no-op. Otherwise, previous probe // will be cancelled and manager starts to probe |default_network_| // immediately. ProbingResult result = StartProbeNetwork( default_network_, connection()->peer_address().impl().socket_address(), net_log_); if (result == ProbingResult::DISABLED_WITH_IDLE_SESSION) { // |this| session has been closed due to idle session. return; } if (result != ProbingResult::PENDING) { // Session is not allowed to migrate, mark session as going away, cancel // migrate back to default timer. if (stream_factory_) stream_factory_->OnSessionGoingAway(this); CancelMigrateBackToDefaultNetworkTimer(); return; } retry_migrate_back_count_++; migrate_back_to_default_timer_.Start( FROM_HERE, timeout, base::Bind( &QuicChromiumClientSession::MaybeRetryMigrateBackToDefaultNetwork, weak_factory_.GetWeakPtr())); } void QuicChromiumClientSession::MaybeRetryMigrateBackToDefaultNetwork() { base::TimeDelta retry_migrate_back_timeout = base::TimeDelta::FromSeconds(UINT64_C(1) << retry_migrate_back_count_); if (retry_migrate_back_timeout > max_time_on_non_default_network_) { // Mark session as going away to accept no more streams. stream_factory_->OnSessionGoingAway(this); return; } TryMigrateBackToDefaultNetwork(retry_migrate_back_timeout); } bool QuicChromiumClientSession::ShouldMigrateSession( bool close_if_cannot_migrate, NetworkChangeNotifier::NetworkHandle network, const NetLogWithSource& migration_net_log) { // Close idle sessions. if (GetNumActiveStreams() == 0) { HistogramAndLogMigrationFailure(migration_net_log, MIGRATION_STATUS_NO_MIGRATABLE_STREAMS, connection_id(), "No active streams"); CloseSessionOnErrorLater(ERR_NETWORK_CHANGED, QUIC_CONNECTION_MIGRATION_NO_MIGRATABLE_STREAMS); return false; } if (migrate_session_on_network_change_) { // Always mark session going away for connection migrate v1 if session // has any active streams. DCHECK(stream_factory_); stream_factory_->OnSessionGoingAway(this); } // Do not migrate sessions where connection migration is disabled. if (config()->DisableConnectionMigration()) { HistogramAndLogMigrationFailure( migration_net_log, MIGRATION_STATUS_DISABLED_BY_CONFIG, connection_id(), "Migration disabled by config"); if (close_if_cannot_migrate) { CloseSessionOnErrorLater(ERR_NETWORK_CHANGED, QUIC_CONNECTION_MIGRATION_DISABLED_BY_CONFIG); } else if (migrate_session_on_network_change_v2_) { // Session cannot migrate, mark it as going away for v2. stream_factory_->OnSessionGoingAway(this); } return false; } // Do not migrate sessions with non-migratable streams. if (HasNonMigratableStreams()) { HistogramAndLogMigrationFailure(migration_net_log, MIGRATION_STATUS_NON_MIGRATABLE_STREAM, connection_id(), "Non-migratable stream"); if (close_if_cannot_migrate) { CloseSessionOnErrorLater(ERR_NETWORK_CHANGED, QUIC_CONNECTION_MIGRATION_NON_MIGRATABLE_STREAM); } else if (migrate_session_on_network_change_v2_) { // Session cannot migrate, mark it as going away for v2. stream_factory_->OnSessionGoingAway(this); } return false; } if (GetDefaultSocket()->GetBoundNetwork() == network) { HistogramAndLogMigrationFailure( migration_net_log, MIGRATION_STATUS_ALREADY_MIGRATED, connection_id(), "Already bound to new network"); return false; } return true; } void QuicChromiumClientSession::LogMetricsOnNetworkDisconnected() { if (most_recent_path_degrading_timestamp_ != base::TimeTicks()) { most_recent_network_disconnected_timestamp_ = base::TimeTicks::Now(); base::TimeDelta degrading_duration = most_recent_network_disconnected_timestamp_ - most_recent_path_degrading_timestamp_; UMA_HISTOGRAM_CUSTOM_TIMES( "Net.QuicNetworkDegradingDurationTillDisconnected", degrading_duration, base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10), 100); } if (most_recent_write_error_timestamp_ != base::TimeTicks()) { base::TimeDelta write_error_to_disconnection_gap = most_recent_network_disconnected_timestamp_ - most_recent_write_error_timestamp_; UMA_HISTOGRAM_CUSTOM_TIMES( "Net.QuicNetworkGapBetweenWriteErrorAndDisconnection", write_error_to_disconnection_gap, base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10), 100); base::UmaHistogramSparse("Net.QuicSession.WriteError.NetworkDisconnected", -most_recent_write_error_); most_recent_write_error_ = 0; most_recent_write_error_timestamp_ = base::TimeTicks(); } } void QuicChromiumClientSession::LogMetricsOnNetworkMadeDefault() { if (most_recent_path_degrading_timestamp_ != base::TimeTicks()) { if (most_recent_network_disconnected_timestamp_ != base::TimeTicks()) { // NetworkDiscconected happens before NetworkMadeDefault, the platform // is dropping WiFi. base::TimeTicks now = base::TimeTicks::Now(); base::TimeDelta disconnection_duration = now - most_recent_network_disconnected_timestamp_; base::TimeDelta degrading_duration = now - most_recent_path_degrading_timestamp_; UMA_HISTOGRAM_CUSTOM_TIMES("Net.QuicNetworkDisconnectionDuration", disconnection_duration, base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10), 100); UMA_HISTOGRAM_CUSTOM_TIMES( "Net.QuicNetworkDegradingDurationTillNewNetworkMadeDefault", degrading_duration, base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10), 100); most_recent_network_disconnected_timestamp_ = base::TimeTicks(); } most_recent_path_degrading_timestamp_ = base::TimeTicks(); } } void QuicChromiumClientSession::LogConnectionMigrationResultToHistogram( QuicConnectionMigrationStatus status) { UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.ConnectionMigration", status, MIGRATION_STATUS_MAX); // Log the connection migraiton result to different histograms based on the // cause of the connection migration. std::string histogram_name = "Net.QuicSession.ConnectionMigration." + ConnectionMigrationCauseToString(current_connection_migration_cause_); base::UmaHistogramEnumeration(histogram_name, status, MIGRATION_STATUS_MAX); current_connection_migration_cause_ = UNKNOWN; } void QuicChromiumClientSession::LogHandshakeStatusOnConnectionMigrationSignal() const { UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.HandshakeStatusOnConnectionMigration", IsCryptoHandshakeConfirmed()); } void QuicChromiumClientSession::HistogramAndLogMigrationFailure( const NetLogWithSource& net_log, QuicConnectionMigrationStatus status, QuicConnectionId connection_id, const std::string& reason) { LogConnectionMigrationResultToHistogram(status); net_log.AddEvent(NetLogEventType::QUIC_CONNECTION_MIGRATION_FAILURE, base::Bind(&NetLogQuicConnectionMigrationFailureCallback, connection_id, reason)); } void QuicChromiumClientSession::HistogramAndLogMigrationSuccess( const NetLogWithSource& net_log, QuicConnectionId connection_id) { LogConnectionMigrationResultToHistogram(MIGRATION_STATUS_SUCCESS); net_log.AddEvent( NetLogEventType::QUIC_CONNECTION_MIGRATION_SUCCESS, base::Bind(&NetLogQuicConnectionMigrationSuccessCallback, connection_id)); } std::unique_ptr<base::Value> QuicChromiumClientSession::GetInfoAsValue( const std::set<HostPortPair>& aliases) { std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetString("version", QuicVersionToString(connection()->transport_version())); dict->SetInteger("open_streams", GetNumOpenOutgoingStreams()); std::unique_ptr<base::ListValue> stream_list(new base::ListValue()); for (DynamicStreamMap::const_iterator it = dynamic_streams().begin(); it != dynamic_streams().end(); ++it) { stream_list->AppendString(base::UintToString(it->second->id())); } dict->Set("active_streams", std::move(stream_list)); dict->SetInteger("total_streams", num_total_streams_); dict->SetString("peer_address", peer_address().ToString()); dict->SetString("connection_id", base::NumberToString(connection_id())); dict->SetBoolean("connected", connection()->connected()); const QuicConnectionStats& stats = connection()->GetStats(); dict->SetInteger("packets_sent", stats.packets_sent); dict->SetInteger("packets_received", stats.packets_received); dict->SetInteger("packets_lost", stats.packets_lost); SSLInfo ssl_info; std::unique_ptr<base::ListValue> alias_list(new base::ListValue()); for (std::set<HostPortPair>::const_iterator it = aliases.begin(); it != aliases.end(); it++) { alias_list->AppendString(it->ToString()); } dict->Set("aliases", std::move(alias_list)); return std::move(dict); } std::unique_ptr<QuicChromiumClientSession::Handle> QuicChromiumClientSession::CreateHandle(const HostPortPair& destination) { return std::make_unique<QuicChromiumClientSession::Handle>( weak_factory_.GetWeakPtr(), destination); } void QuicChromiumClientSession::OnReadError( int result, const DatagramClientSocket* socket) { DCHECK(socket != nullptr); base::UmaHistogramSparse("Net.QuicSession.ReadError.AnyNetwork", -result); if (socket != GetDefaultSocket()) { base::UmaHistogramSparse("Net.QuicSession.ReadError.OtherNetworks", -result); // Ignore read errors from sockets that are not affecting the current // network, i.e., sockets that are no longer active and probing socket. // TODO(jri): Maybe clean up old sockets on error. return; } base::UmaHistogramSparse("Net.QuicSession.ReadError.CurrentNetwork", -result); if (IsCryptoHandshakeConfirmed()) { base::UmaHistogramSparse( "Net.QuicSession.ReadError.CurrentNetwork.HandshakeConfirmed", -result); } if (migration_pending_) { // Ignore read errors during pending migration. Connection will be closed if // pending migration failed or timed out. base::UmaHistogramSparse("Net.QuicSession.ReadError.PendingMigration", -result); return; } DVLOG(1) << "Closing session on read error: " << result; connection()->CloseConnection(QUIC_PACKET_READ_ERROR, ErrorToString(result), ConnectionCloseBehavior::SILENT_CLOSE); } bool QuicChromiumClientSession::OnPacket( const QuicReceivedPacket& packet, const QuicSocketAddress& local_address, const QuicSocketAddress& peer_address) { ProcessUdpPacket(local_address, peer_address, packet); if (!connection()->connected()) { NotifyFactoryOfSessionClosedLater(); return false; } return true; } void QuicChromiumClientSession::NotifyFactoryOfSessionGoingAway() { going_away_ = true; if (stream_factory_) stream_factory_->OnSessionGoingAway(this); } void QuicChromiumClientSession::NotifyFactoryOfSessionClosedLater() { if (!dynamic_streams().empty()) RecordUnexpectedOpenStreams(NOTIFY_FACTORY_OF_SESSION_CLOSED_LATER); if (!going_away_) RecordUnexpectedNotGoingAway(NOTIFY_FACTORY_OF_SESSION_CLOSED_LATER); going_away_ = true; DCHECK_EQ(0u, GetNumActiveStreams()); DCHECK(!connection()->connected()); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&QuicChromiumClientSession::NotifyFactoryOfSessionClosed, weak_factory_.GetWeakPtr())); } void QuicChromiumClientSession::NotifyFactoryOfSessionClosed() { if (!dynamic_streams().empty()) RecordUnexpectedOpenStreams(NOTIFY_FACTORY_OF_SESSION_CLOSED); if (!going_away_) RecordUnexpectedNotGoingAway(NOTIFY_FACTORY_OF_SESSION_CLOSED); going_away_ = true; DCHECK_EQ(0u, GetNumActiveStreams()); // Will delete |this|. if (stream_factory_) stream_factory_->OnSessionClosed(this); } void QuicChromiumClientSession::MaybeMigrateOrCloseSession( NetworkChangeNotifier::NetworkHandle new_network, bool close_if_cannot_migrate, const NetLogWithSource& migration_net_log) { if (!ShouldMigrateSession(close_if_cannot_migrate, new_network, migration_net_log)) { return; } // No new network was found. Notify session, so it can wait for a new // network. if (new_network == NetworkChangeNotifier::kInvalidNetworkHandle) { OnNoNewNetwork(); return; } Migrate(new_network, connection()->peer_address().impl().socket_address(), /*close_session_on_error*/ true, migration_net_log); } MigrationResult QuicChromiumClientSession::MigrateToAlternateNetwork( bool close_session_on_error, const NetLogWithSource& migration_net_log) { if (!migrate_session_on_network_change_ && !migrate_session_on_network_change_v2_) { HistogramAndLogMigrationFailure(migration_net_log, MIGRATION_STATUS_NOT_ENABLED, connection_id(), "Migration not enabled"); return MigrationResult::FAILURE; } if (HasNonMigratableStreams()) { HistogramAndLogMigrationFailure(migration_net_log, MIGRATION_STATUS_NON_MIGRATABLE_STREAM, connection_id(), "Non-migratable stream"); return MigrationResult::FAILURE; } if (config()->DisableConnectionMigration()) { HistogramAndLogMigrationFailure( migration_net_log, MIGRATION_STATUS_DISABLED_BY_CONFIG, connection_id(), "Migration disabled by config"); return MigrationResult::FAILURE; } DCHECK(stream_factory_); NetworkChangeNotifier::NetworkHandle new_network = stream_factory_->FindAlternateNetwork( GetDefaultSocket()->GetBoundNetwork()); if (new_network == NetworkChangeNotifier::kInvalidNetworkHandle) { // No alternate network found. HistogramAndLogMigrationFailure( migration_net_log, MIGRATION_STATUS_NO_ALTERNATE_NETWORK, connection_id(), "No alternate network found"); return MigrationResult::NO_NEW_NETWORK; } stream_factory_->OnSessionGoingAway(this); return Migrate(new_network, connection()->peer_address().impl().socket_address(), close_session_on_error, migration_net_log); } MigrationResult QuicChromiumClientSession::Migrate( NetworkChangeNotifier::NetworkHandle network, IPEndPoint peer_address, bool close_session_on_error, const NetLogWithSource& migration_net_log) { if (!stream_factory_) return MigrationResult::FAILURE; // Create and configure socket on |network|. std::unique_ptr<DatagramClientSocket> socket( stream_factory_->CreateSocket(net_log_.net_log(), net_log_.source())); if (stream_factory_->ConfigureSocket(socket.get(), peer_address, network, session_key_.socket_tag()) != OK) { HistogramAndLogMigrationFailure( migration_net_log, MIGRATION_STATUS_INTERNAL_ERROR, connection_id(), "Socket configuration failed"); if (close_session_on_error) { if (migrate_session_on_network_change_v2_) { CloseSessionOnErrorLater(ERR_NETWORK_CHANGED, QUIC_CONNECTION_MIGRATION_INTERNAL_ERROR); } else { CloseSessionOnError(ERR_NETWORK_CHANGED, QUIC_CONNECTION_MIGRATION_INTERNAL_ERROR); } } return MigrationResult::FAILURE; } // Create new packet reader and writer on the new socket. std::unique_ptr<QuicChromiumPacketReader> new_reader( new QuicChromiumPacketReader(socket.get(), clock_, this, yield_after_packets_, yield_after_duration_, net_log_)); std::unique_ptr<QuicChromiumPacketWriter> new_writer( new QuicChromiumPacketWriter(socket.get(), task_runner_)); new_writer->set_delegate(this); // Migrate to the new socket. if (!MigrateToSocket(std::move(socket), std::move(new_reader), std::move(new_writer))) { HistogramAndLogMigrationFailure(migration_net_log, MIGRATION_STATUS_TOO_MANY_CHANGES, connection_id(), "Too many changes"); if (close_session_on_error) { if (migrate_session_on_network_change_v2_) { CloseSessionOnErrorLater(ERR_NETWORK_CHANGED, QUIC_CONNECTION_MIGRATION_TOO_MANY_CHANGES); } else { CloseSessionOnError(ERR_NETWORK_CHANGED, QUIC_CONNECTION_MIGRATION_TOO_MANY_CHANGES); } } return MigrationResult::FAILURE; } HistogramAndLogMigrationSuccess(migration_net_log, connection_id()); return MigrationResult::SUCCESS; } bool QuicChromiumClientSession::MigrateToSocket( std::unique_ptr<DatagramClientSocket> socket, std::unique_ptr<QuicChromiumPacketReader> reader, std::unique_ptr<QuicChromiumPacketWriter> writer) { DCHECK_EQ(sockets_.size(), packet_readers_.size()); // TODO(zhongyi): figure out whether we want to limit the number of // connection migrations for v2, which includes migration on platform signals, // write error events, and path degrading on original network. if (!migrate_session_on_network_change_v2_ && sockets_.size() >= kMaxReadersPerQuicSession) { return false; } // TODO(jri): Make SetQuicPacketWriter take a scoped_ptr. packet_readers_.push_back(std::move(reader)); sockets_.push_back(std::move(socket)); StartReading(); // Block the writer to prevent it being used until WriteToNewSocket // completes. writer->set_write_blocked(true); connection()->SetQuicPacketWriter(writer.release(), /*owns_writer=*/true); // Post task to write the pending packet or a PING packet to the new // socket. This avoids reentrancy issues if there is a write error // on the write to the new socket. task_runner_->PostTask( FROM_HERE, base::Bind(&QuicChromiumClientSession::WriteToNewSocket, weak_factory_.GetWeakPtr())); // Migration completed. migration_pending_ = false; return true; } void QuicChromiumClientSession::PopulateNetErrorDetails( NetErrorDetails* details) const { details->quic_port_migration_detected = port_migration_detected_; details->quic_connection_error = error(); } const DatagramClientSocket* QuicChromiumClientSession::GetDefaultSocket() const { DCHECK(sockets_.back().get() != nullptr); // The most recently added socket is the currently active one. return sockets_.back().get(); } bool QuicChromiumClientSession::IsAuthorized(const std::string& hostname) { bool result = CanPool(hostname, session_key_.privacy_mode(), session_key_.socket_tag()); if (result) streams_pushed_count_++; return result; } bool QuicChromiumClientSession::HasNonMigratableStreams() const { for (const auto& stream : dynamic_streams()) { if (!static_cast<QuicChromiumClientStream*>(stream.second.get()) ->can_migrate()) { return true; } } return false; } bool QuicChromiumClientSession::HandlePromised( QuicStreamId id, QuicStreamId promised_id, const spdy::SpdyHeaderBlock& headers) { bool result = QuicSpdyClientSessionBase::HandlePromised(id, promised_id, headers); if (result) { // The push promise is accepted, notify the push_delegate that a push // promise has been received. if (push_delegate_) { std::string pushed_url = SpdyUtils::GetPromisedUrlFromHeaders(headers); push_delegate_->OnPush(std::make_unique<QuicServerPushHelper>( weak_factory_.GetWeakPtr(), GURL(pushed_url)), net_log_); } if (headers_include_h2_stream_dependency_) { // Even though the promised stream will not be created until after the // push promise headers are received, send a PRIORITY frame for the // promised stream ID. Send |kDefaultPriority| since that will be the // initial spdy::SpdyPriority of the push promise stream when created. const spdy::SpdyPriority priority = QuicStream::kDefaultPriority; spdy::SpdyStreamId parent_stream_id = 0; int weight = 0; bool exclusive = false; priority_dependency_state_.OnStreamCreation( promised_id, priority, &parent_stream_id, &weight, &exclusive); WritePriority(promised_id, parent_stream_id, weight, exclusive); } } net_log_.AddEvent(NetLogEventType::QUIC_SESSION_PUSH_PROMISE_RECEIVED, base::Bind(&NetLogQuicPushPromiseReceivedCallback, &headers, id, promised_id)); return result; } void QuicChromiumClientSession::DeletePromised( QuicClientPromisedInfo* promised) { if (IsOpenStream(promised->id())) streams_pushed_and_claimed_count_++; QuicSpdyClientSessionBase::DeletePromised(promised); } void QuicChromiumClientSession::OnPushStreamTimedOut(QuicStreamId stream_id) { QuicSpdyStream* stream = GetPromisedStream(stream_id); if (stream != nullptr) bytes_pushed_and_unclaimed_count_ += stream->stream_bytes_read(); } void QuicChromiumClientSession::CancelPush(const GURL& url) { QuicClientPromisedInfo* promised_info = QuicSpdyClientSessionBase::GetPromisedByUrl(url.spec()); if (!promised_info || promised_info->is_validating()) { // Push stream has already been claimed or is pending matched to a request. return; } QuicStreamId stream_id = promised_info->id(); // Collect data on the cancelled push stream. QuicSpdyStream* stream = GetPromisedStream(stream_id); if (stream != nullptr) bytes_pushed_and_unclaimed_count_ += stream->stream_bytes_read(); // Send the reset and remove the promised info from the promise index. QuicSpdyClientSessionBase::ResetPromised(stream_id, QUIC_STREAM_CANCELLED); DeletePromised(promised_info); } const LoadTimingInfo::ConnectTiming& QuicChromiumClientSession::GetConnectTiming() { connect_timing_.ssl_start = connect_timing_.connect_start; connect_timing_.ssl_end = connect_timing_.connect_end; return connect_timing_; } QuicTransportVersion QuicChromiumClientSession::GetQuicVersion() const { return connection()->transport_version(); } size_t QuicChromiumClientSession::EstimateMemoryUsage() const { // TODO(xunjieli): Estimate |crypto_stream_|, QuicSpdySession's // QuicHeaderList, QuicSession's QuiCWriteBlockedList, open streams and // unacked packet map. return base::trace_event::EstimateMemoryUsage(packet_readers_); } } // namespace net
[ "artem@brave.com" ]
artem@brave.com
286eecfa66fd151a4e6d012e88444eec2e3399e0
d0773b7e3b5b13a4a4f210cc9f226039d947d54f
/2@prgm 5.cpp
3c6af7dfc3d90a48b69a25a815b495d10a3f6988
[]
no_license
sarandevs/c-assignment2
569b5b1963c37b93d056b46e7a94a3299ae71707
4a1c827ea4f36b5758fa4cce6cdbd70705eb2219
refs/heads/master
2021-01-21T12:58:08.256289
2017-09-01T12:09:21
2017-09-01T12:09:21
102,109,006
0
0
null
null
null
null
UTF-8
C++
false
false
202
cpp
#include <iostream> #include <cmath> using namespace std; int main() { int a,b,c; cout<<"number ="<<endl; cin>>a; cout<<"raise to ="<<endl; cin>>b; c=pow(a,b); cout<<"power ="<<c; return 0; }
[ "noreply@github.com" ]
noreply@github.com
f2af0e6ed18f4c95f5943c55bb7a6b145f2e621d
18bf6db630d1cbb60261b1bafe5c820c2ac9c470
/FireDog/json/json-schema/json-patch.hpp
d4c9d058bae3bc390be2c61c42a2bc13d2cdda14
[ "MIT" ]
permissive
fengjixuchui/FireDog
5fc9c1c812e10d0c2b2790d1f6829120f9ac3406
90494f1dd1aa093feb1d6756949c352f6fa9c257
refs/heads/master
2023-07-19T03:01:32.282377
2021-09-27T04:35:39
2021-09-27T04:35:39
409,472,259
0
0
MIT
2021-09-27T04:35:39
2021-09-23T06:20:15
null
UTF-8
C++
false
false
759
hpp
#pragma once #include "json/json.hpp" #include <string> namespace nlohmann { class JsonPatchFormatException : public std::exception { public: explicit JsonPatchFormatException(std::string msg) : ex_{std::move(msg)} {} inline const char *what() const noexcept override final { return ex_.c_str(); } private: std::string ex_; }; class json_patch { public: json_patch() = default; json_patch(json &&patch); json_patch(const json &patch); json_patch &add(const json::json_pointer &, json value); json_patch &replace(const json::json_pointer &, json value); json_patch &remove(const json::json_pointer &); operator json() const { return j_; } private: json j_; static void validateJsonPatch(json const &patch); }; } // namespace nlohmann
[ "zhanghaishan@360.cn" ]
zhanghaishan@360.cn
7546792af5a82b741b73705cad5ee4976364c622
25cbcdccb5ae8a30bb3571959aa59d73af2d35dc
/GenericFilter.cpp
61411687ec56c46b28f8574f12cffa3d4ff2698e
[]
no_license
19and99/ImagenomicProject1
7c8c9064b6e65ba55fd32ed2acb8fb457e7c3d0f
bcbfd17d6d8b3d3900186cb5bbfc664f5ce37dc1
refs/heads/master
2020-05-02T16:32:24.064483
2019-04-18T21:22:12
2019-04-18T21:22:12
178,071,687
0
0
null
null
null
null
UTF-8
C++
false
false
214
cpp
#include "stdafx.h" #include "GenericFilter.h" GenericFilter::GenericFilter() { } GenericFilter::GenericFilter(GenericImage* image_) { image = image_; } GenericFilter::~GenericFilter() { }
[ "noreply@github.com" ]
noreply@github.com
dc1e4fa79d68451a66fe0fe8edf9108a72366b98
b2810745e7d746140b87367f9fa55374cc82b2f2
/Source/BansheeUtility/Source/BsDynLibManager.cpp
93c38841dff8bdc1932fe202f2f849c8d329a2f8
[]
no_license
nemerle/BansheeEngine
7aabb7d2c1af073b1069f313a2192e0152b56e99
10436324afc9327865251169918177a6eabc8506
refs/heads/preview
2020-04-05T18:29:09.657686
2016-05-11T08:19:09
2016-05-11T08:19:09
58,526,181
2
0
null
2016-05-11T08:10:44
2016-05-11T08:10:44
null
UTF-8
C++
false
false
1,838
cpp
//********************************** Banshee Engine (www.banshee3d.com) **************************************************// //**************** Copyright (c) 2016 Marko Pintera (marko.pintera@gmail.com). All rights reserved. **********************// #include "BsDynLibManager.h" #include "BsDynLib.h" namespace BansheeEngine { DynLibManager::DynLibManager() { } DynLib* DynLibManager::load(const String& name) { String filename = name; #if BS_PLATFORM == BS_PLATFORM_LINUX if (name.substr(name.length() - 3, 3) != ".so") name += ".so"; #elif BS_PLATFORM == BS_PLATFORM_OSX if (name.substr(name.length() - 6, 6) != ".dylib") name += ".dylib"; #elif BS_PLATFORM == BS_PLATFORM_WIN32 // Although LoadLibraryEx will add .dll itself when you only specify the library name, // if you include a relative path then it does not. So, add it to be sure. if (filename.substr(filename.length() - 4, 4) != ".dll") filename += ".dll"; #endif auto iterFind = mLoadedLibraries.find(filename); if (iterFind != mLoadedLibraries.end()) { return iterFind->second; } else { DynLib* newLib = new (bs_alloc<DynLib>()) DynLib(filename); mLoadedLibraries[filename] = newLib; return newLib; } } void DynLibManager::unload(DynLib* lib) { auto iterFind = mLoadedLibraries.find(lib->getName()); if (iterFind != mLoadedLibraries.end()) { mLoadedLibraries.erase(iterFind); } lib->unload(); bs_delete(lib); } DynLibManager::~DynLibManager() { // Unload & delete resources in turn for(auto& entry : mLoadedLibraries) { entry.second->unload(); bs_delete(entry.second); } // Empty the list mLoadedLibraries.clear(); } DynLibManager& gDynLibManager() { return DynLibManager::instance(); } }
[ "bearishsun@gmail.com" ]
bearishsun@gmail.com
cc713638e62b9b70b6c15b93cf7c1c4666f30c39
bb3941d7497fb1bbb68890fc9a4197632fae706b
/Task_9/src/project/Task_3/Fanctions.h
0bbd1f67ab7b8383dd658c654049abd520d38b7f
[]
no_license
Romamart/system-programming
fd878f68078b85754b2c520ba64b63303d0016ca
a3200d28f2e7966969cbd6cc0aabbbbf6fc18665
refs/heads/master
2020-08-23T15:48:39.819487
2020-01-24T01:01:29
2020-01-24T01:01:29
216,654,753
0
0
null
null
null
null
UTF-8
C++
false
false
2,222
h
#include <array> #include <vector> #include <string> #include <sstream> #pragma once template <class T, int N, int M> struct Tie { private: std::array<T*,M> data; public: Tie(std::array<T*,M> other); void operator=(const std::array<T,N*M>& rhs); }; //#include <Fanctions.h> template <class T, size_t N> std::array<T,N> cat(std::array<T,N> arr){ return arr; } template <class T, size_t N, class ... Other> auto cat(std::array<T,N> arr, Other ... other) -> std::array<T,N*(sizeof...(Other)+1)>{ std::array<T,N*sizeof...(Other)> tmp = cat(other ...); std::array<T, N*(sizeof...(Other)+1)> new_arr; for (int i = 0; i<arr.size(); i++){ new_arr[i] = arr[i]; } for (int j = 0; j<tmp.size(); j++){ new_arr[arr.size()+j] = tmp[j]; } return new_arr; } template <class Head> void message(std::ostream& Flow, const char* str1 , Head head){ std::string str = str1; if (str.find('%')<=(str.size()-1)){ std::stringstream s; std::string str2; s << head; s >> str2; str = str.replace(str.find('%'),1,str2); Flow << str; }else{ Flow << str; } } template <class Head, class ... Other> void message(std::ostream& Flow,const char* str1, Head head, Other ... other){ std::string str = str1; if (str.find('%')<=(str.size()-1)){ // const char str2 = std::to_string(head); std::stringstream s; std::string str2; s << head; s >> str2; str = str.replace(str.find('%'),1,str2); message(Flow, str.c_str(), other ...); }else{ Flow << str; } } template <class T, int N, int M> Tie<T,N,M>::Tie(std::array<T*,M> other) : data(other){} template <class T, int N, int M> void Tie<T,N,M>::operator= (const std::array<T,N*M>& rhs){ size_t num = 0; for (auto& el : data){ for (int j = 0; j < N; j++){ *(el + j) = rhs.at(j + num * N); } } } template <class T, size_t N, class... Args> auto tie(std::array<T,N>& arr, Args& ... args)->Tie<T,N,sizeof...(args) + 1>{ const auto M = sizeof...(args) + 1; std::array<T*,M> v{arr.data(),args.data()...}; return Tie<T,N,M>(v); }
[ "martinyuk.r@yandex.ru" ]
martinyuk.r@yandex.ru
72a1d105c05a09260aa8685ef726d6bda6f2d895
eeeee72af501e5f2e159499723686a154e0d2b24
/chapter_02/_72.cpp
b130a6895ed585d4d2be387c1023f5a92b445117
[]
no_license
CoAAColA/CSAPP_homework
543c9f71c6a4b2f27259dd2857f0f19408ba8941
f895917eda602c88865477ad8541428141c052ca
refs/heads/master
2022-11-14T10:21:17.176239
2020-07-11T13:57:11
2020-07-11T13:57:11
275,547,696
0
0
null
null
null
null
UTF-8
C++
false
false
287
cpp
//A: unsigned 与 int 的 运算结果为unsigned, 总是大于等于0 //B: #include <stdio.h> #include <memory.h> void copy_int(int val, void* buf, int maxbytes) { if (maxbytes >= sizeof(val)) { memcpy(buf, (void*)&val, sizeof(val)); } } int main() { return 0; }
[ "noreply@github.com" ]
noreply@github.com
9d41f14f520104a24889141fb09ea3571db1accc
5d1a033cf72f630688da2b8de788d1cebf6339e6
/Source/WebKit2/UIProcess/ios/SmartMagnificationController.h
60ca5d4212213dd45143ca8aee56bbef4001b7a2
[]
no_license
jaokim/odyssey
e2115123f75df185fcda87452f455f25907b0c79
5ee0f826dd3502f04e077b3df59e3d855c7afd0c
refs/heads/kas1e_branch
2022-11-07T17:48:02.860664
2017-04-05T20:43:43
2017-04-05T20:43:43
55,713,581
2
1
null
2022-10-28T23:56:32
2016-04-07T17:17:09
C++
UTF-8
C++
false
false
2,735
h
/* * Copyright (C) 2013, 2014 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SmartMagnificationController_h #define SmartMagnificationController_h #if PLATFORM(IOS) #include "MessageReceiver.h" #include <WebCore/FloatRect.h> #include <wtf/Noncopyable.h> #include <wtf/RetainPtr.h> OBJC_CLASS WKContentView; OBJC_CLASS UIScrollView; namespace WebKit { class WebPageProxy; class SmartMagnificationController : private IPC::MessageReceiver { WTF_MAKE_NONCOPYABLE(SmartMagnificationController); public: SmartMagnificationController(WKContentView *); ~SmartMagnificationController(); void handleSmartMagnificationGesture(WebCore::FloatPoint origin); void handleResetMagnificationGesture(WebCore::FloatPoint origin); private: // IPC::MessageReceiver. virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; void didCollectGeometryForSmartMagnificationGesture(WebCore::FloatPoint origin, WebCore::FloatRect renderRect, WebCore::FloatRect visibleContentBounds, bool isReplacedElement, double viewportMinimumScale, double viewportMaximumScale); void magnify(WebCore::FloatPoint origin, WebCore::FloatRect targetRect, WebCore::FloatRect visibleContentRect, double viewportMinimumScale, double viewportMaximumScale); WebPageProxy& m_webPageProxy; WKContentView *m_contentView; }; } // namespace WebKit #endif // PLATFORM(IOS) #endif // SmartMagnificationController_h
[ "deadwood@wp.pl" ]
deadwood@wp.pl
1afd27caf9b68d2913e59245bbca30abc9f54a48
20b6016e84f5ee61fafe76cbd61037e491ba261a
/craafting_oop/Craftable.h
8003f48cc74068439c0640a18e5a5ca280b8c220
[]
no_license
tmedi005/oop
37100fbe5d23cf52c8bc7be8b9bab51e63567d94
6211a47a8c7c4ffe1df971240c5366ac5385e043
refs/heads/master
2021-01-01T06:53:53.192635
2017-07-18T14:10:15
2017-07-18T14:10:15
97,546,059
0
0
null
null
null
null
UTF-8
C++
false
false
1,495
h
#ifndef CRAFTABLE_H_INCLUDED #define CRAFTABLE_H_INCLUDED #include "Item.h" /** * This class represents one Craftable Item. This is an Item that can only * be created by the result of crafting * * Craftable Items may be created from Ingredients, other Craftable Items, * or a combination of both. */ class Craftable : public Item { private: /** * Array of Item Pointers These represent the * Ingredients used to create this Craftable Item */ Item **ingredients; /** * Number of ingredients used--i.e., size of the * ingredients array */ int ingredient_count; public: /** * Default to a Comsumable Item with an empty name */ Craftable(); /** * Copy Constructor */ Craftable( const Craftable &src ); /** * Destructor */ ~Craftable(); /** * Print the Craftable Item */ virtual void display( std::ostream &outs ) const ; /** * Read Craftable Item attributes from an input stream */ virtual void read( std::istream& ins ); /** * Clone--i.e., copy--this Craftable Item */ virtual Item* clone() const ; /** * Assignment Operator */ Craftable& operator=( const Craftable &rhs ); }; #endif
[ "noreply@github.com" ]
noreply@github.com
21aa55f49e4f6318d7f044bd97afc777428aa177
bfe6c95fa8a2aae3c3998bd59555583fed72900a
/isToeplitzMatrix.cpp
8b4002e5fced016070ee00fec717ad4d150d9d80
[]
no_license
zzz136454872/leetcode
f9534016388a1ba010599f4771c08a55748694b2
b5ea6c21bff317884bdb3d7e873aa159b8c30215
refs/heads/master
2023-09-01T17:26:57.624117
2023-08-29T03:18:56
2023-08-29T03:18:56
240,464,565
0
0
null
null
null
null
UTF-8
C++
false
false
927
cpp
/** * @author f4prime * @email zzz136454872@163.com * @aim a plain model for leetcode */ #include"cpptools.h" #include<iostream> #include<string> #include<vector> #include<algorithm> #include<map> #include<stack> #include<queue> #include<set> using namespace std; //#define testMod #ifdef testMod void test() { } #endif #ifndef testMod class Solution { public: bool isToeplitzMatrix(vector<vector<int>>& matrix) { for(int i=1;i<(int)matrix.size();i++) { for(int j=1;j<(int)matrix[0].size();j++) { if(matrix[i][j]!=matrix[i-1][j-1]) return false; } } return true; } private: }; #endif int main() { #ifdef testMod test(); #endif #ifndef testMod Solution sl; vector<vector<int>> matrix = {{1,2,3,4},{5,1,2,3},{9,5,1,2}}; cout<<sl.isToeplitzMatrix(matrix)<<endl; #endif return 0; }
[ "zzz136454872@163.com" ]
zzz136454872@163.com
31ae6054e4e5ce5e3dc83ee22c5b9269f4062231
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/git/old_hunk_2870.cpp
3a7357ca8f30b17f1adff4e9a964bb8ee186a9b1
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
334
cpp
} ref_transaction_free(transaction); unlink(git_path("CHERRY_PICK_HEAD")); unlink(git_path("REVERT_HEAD")); unlink(git_path("MERGE_HEAD")); unlink(git_path("MERGE_MSG")); unlink(git_path("MERGE_MODE")); unlink(git_path("SQUASH_MSG")); if (commit_index_files()) die (_("Repository has been updated, but unable to write\n"
[ "993273596@qq.com" ]
993273596@qq.com
bdfcc0478c98d2a0660b830934270f5890bc06fb
e9e8064dd3848b85b65e871877c55f025628fb49
/code/MapEngine/MapCtrol/MapWnd - 副本.h
fc5e6afd8c2a3e12318ac395580412fda367f24c
[]
no_license
xxh0078/gmapx
eb5ae8eefc2308b8ca3a07f575ee3a27b3e90d95
e265ad90b302db7da05345e2467ec2587e501e90
refs/heads/master
2021-06-02T14:42:30.372998
2019-08-29T02:45:10
2019-08-29T02:45:10
12,397,909
0
0
null
null
null
null
GB18030
C++
false
false
944
h
#pragma once #include "MapButton.h" class CMapWnd { public: CMapWnd(void); ~CMapWnd(void); //创建窗口 void Create( HWND hWnd ); //绘制 void OnDraw( HDC hdc ); //鼠标消息 bool OnLButtonDown( VOSPoint point ); bool OnLButtonUp( VOSPoint point); bool OnMouseMove( VOSPoint point); bool OnLButtonDblClk( VOSPoint point ); bool OnMouseWheel( short zDelta, VOSPoint point); //void OnMoveOut(); //添加控件 void AddChild( CMapCtrol* pCtrol ); //得到控件 CMapCtrol* GetCtrol( int nID ); //刷新屏幕 void Invalidate(); //发送消息 bool PostMessage( int nMessage,long lParam1, long lParam2 ); //命令 virtual void OnCommand( int id, int param1,int param2 ); private: //设置CtrlButton基准位置 void SetBasePos( long left, long top ); private: vector<CMapCtrol*> m_arrMapCtrol; CMapCtrol* m_pLastCtrol;//当前按钮 CMapCtrol* m_pCtrolMouseIn;//鼠标移入的按钮 HWND m_hWnd; };
[ "you@example.com" ]
you@example.com
8ea3233a56c30f6536da5c4d8b9c1103b0977572
3514a67cd2e2975fe0c4c30919b0db442676b7c9
/branch/MSP432/SaltyOS/User/BoardIO.cpp
4f1a643943b5b3cf6c2e995c62a91289a244970d
[ "MIT" ]
permissive
wtywtykk/STM32Framework_SaltyProject
8fd699fb76645d50eb067f88a8327025e0f53d2f
ba52576006a9c4bdb3c0e6b0dbef2d261359da50
refs/heads/master
2020-05-01T00:43:32.538567
2019-03-22T17:07:12
2019-03-22T17:07:12
177,175,463
1
1
null
null
null
null
UTF-8
C++
false
false
4,230
cpp
#include "Kernel\Common\KCommon.h" #include "HAL\UniGPIO.h" #include "MultiInstDriver/PGA11x.h" #include "MultiInstDriver/DAC8311.h" UniGPIO_Handle TRIG_AC1; UniGPIO_Handle TRIG_SEL; UniGPIO_Handle TG_DIN; UniGPIO_Handle AC2; UniGPIO_Handle SCLK2; UniGPIO_Handle SDIO2; UniGPIO_Handle CS2; UniGPIO_Handle TRIG_AC2; UniGPIO_Handle DAC_DIN1; UniGPIO_Handle DAC_SCLK; UniGPIO_Handle DAC_SYNC; UniGPIO_Handle DAC_DIN2; UniGPIO_Handle AC1; UniGPIO_Handle SCLK1; UniGPIO_Handle SDIO1; UniGPIO_Handle CS1; PGA11x_Handle PGA1; PGA11x_Handle PGA2; DAC8311_Handle DAC1; DAC8311_Handle DAC2; u16 DACs[3]; void BoardIO_UpdateDAC(void); void BoardIO_InitPins(void) { GPIO_InitTypeDef GPIOInit; GPIOInit.FuncSel = 0; GPIOInit.HighDrive = false; GPIOInit.InterruptEnable = false; GPIOInit.InterruptLowToHigh = false; GPIOInit.Output = true; GPIOInit.Pull = false; GPIOInit.Pin = GPIO_PIN0; GPIO_32_InitPin(1, &GPIOInit, &TRIG_AC1); UniGPIO_SetHigh(&TRIG_AC1); GPIOInit.Pin = GPIO_PIN1; GPIO_32_InitPin(1, &GPIOInit, &TRIG_SEL); UniGPIO_SetHigh(&TRIG_SEL); GPIOInit.Pin = GPIO_PIN2; GPIO_32_InitPin(1, &GPIOInit, &TG_DIN); UniGPIO_SetHigh(&TG_DIN); GPIOInit.Pin = GPIO_PIN2; GPIO_32_InitPin(4, &GPIOInit, &AC2); UniGPIO_SetHigh(&AC2); GPIOInit.Pin = GPIO_PIN3; GPIO_32_InitPin(4, &GPIOInit, &SCLK2); UniGPIO_SetHigh(&SCLK2); GPIOInit.Pin = GPIO_PIN4; GPIO_32_InitPin(4, &GPIOInit, &SDIO2); UniGPIO_SetHigh(&SDIO2); GPIOInit.Pin = GPIO_PIN5; GPIO_32_InitPin(4, &GPIOInit, &CS2); UniGPIO_SetHigh(&CS2); GPIOInit.Pin = GPIO_PIN6; GPIO_32_InitPin(4, &GPIOInit, &TRIG_AC2); UniGPIO_SetHigh(&TRIG_AC2); GPIOInit.Pin = GPIO_PIN0; GPIO_32_InitPin(5, &GPIOInit, &DAC_DIN1); UniGPIO_SetHigh(&DAC_DIN1); GPIOInit.Pin = GPIO_PIN1; GPIO_32_InitPin(5, &GPIOInit, &DAC_SCLK); UniGPIO_SetHigh(&DAC_SCLK); GPIOInit.Pin = GPIO_PIN2; GPIO_32_InitPin(5, &GPIOInit, &DAC_SYNC); UniGPIO_SetHigh(&DAC_SYNC); GPIOInit.Pin = GPIO_PIN3; GPIO_32_InitPin(5, &GPIOInit, &DAC_DIN2); UniGPIO_SetHigh(&DAC_DIN2); GPIOInit.Pin = GPIO_PIN0; GPIO_32_InitPin(7, &GPIOInit, &AC1); UniGPIO_SetHigh(&AC1); GPIOInit.Pin = GPIO_PIN1; GPIO_32_InitPin(7, &GPIOInit, &SCLK1); UniGPIO_SetHigh(&SCLK1); GPIOInit.Pin = GPIO_PIN2; GPIO_32_InitPin(7, &GPIOInit, &SDIO1); UniGPIO_SetHigh(&SDIO1); GPIOInit.Pin = GPIO_PIN3; GPIO_32_InitPin(7, &GPIOInit, &CS1); UniGPIO_SetHigh(&CS1); } void BoardIO_InitDrivers(void) { PGA11x_Init(&PGA1, &SDIO1, &SCLK1, &CS1); PGA11x_Init(&PGA2, &SDIO2, &SCLK2, &CS2); PGA11x_SetChannel(&PGA1, CH1); PGA11x_SetChannel(&PGA2, CH1); PGA11x_SetGain(&PGA1, 1); PGA11x_SetGain(&PGA2, 1); DACs[0] = 0x3FFF; DACs[1] = 0x3FFF; DACs[2] = 0x3FFF; BoardIO_UpdateDAC(); } void BoardIO_Init(void) { BoardIO_InitPins(); BoardIO_InitDrivers(); } void BoardIO_SetChannelAC(u8 Ch, bool AC) { if (Ch == 0) { if (AC) { UniGPIO_SetLow(&AC1); } else { UniGPIO_SetHigh(&AC1); } } else { if (AC) { UniGPIO_SetLow(&AC2); } else { UniGPIO_SetHigh(&AC2); } } } void BoardIO_SetChannelTrigAC(u8 Ch, bool AC) { if (Ch == 0) { if (AC) { UniGPIO_SetHigh(&TRIG_AC1); } else { UniGPIO_SetLow(&TRIG_AC1); } } else { if (AC) { UniGPIO_SetHigh(&TRIG_AC2); } else { UniGPIO_SetLow(&TRIG_AC2); } } } void BoardIO_SetDAC(u8 Ch, u16 Val) { DACs[Ch] = Val; BoardIO_UpdateDAC(); } void BoardIO_UpdateDAC(void) { u8 i; u16 SBuf[3]; for (i = 0; i < 3; i++) { SBuf[i] = DACs[i]; } UniGPIO_SetHigh(&DAC_SCLK); UniGPIO_SetLow(&DAC_SYNC); for (i = 0; i < 16; i++) { UniGPIO_SetVal(&DAC_DIN1, (SBuf[0] & 0x8000) ? 1 : 0); SBuf[0] <<= 1; UniGPIO_SetVal(&DAC_DIN2, (SBuf[1] & 0x8000) ? 1 : 0); SBuf[1] <<= 1; UniGPIO_SetVal(&TG_DIN, (SBuf[2] & 0x8000) ? 1 : 0); SBuf[2] <<= 1; UniGPIO_SetLow(&DAC_SCLK); UniGPIO_SetHigh(&DAC_SCLK); } UniGPIO_SetHigh(&DAC_SYNC); } void BoardIO_SetPGA(u8 Ch, u8 Gain) { u8 Reg = 0; u8 RegGain = 1; while (RegGain != Gain) { if (RegGain == 0) { return; } RegGain <<= 1; Reg++; } if (Ch == 0) { PGA11x_SetGain(&PGA1, Reg); } else { PGA11x_SetGain(&PGA2, Reg); } } void BoardIO_SetFilter(bool HighBW) { UniGPIO_SetVal(&TRIG_AC1, HighBW); }
[ "163.wty@163.com" ]
163.wty@163.com
2d688c28c8bb5c1d4819858716fd85ed44406847
42bb012c72990cd720d9f694fa98bad40ddf5d7b
/GetSysInfo/GetSysInfo.cpp
1b0a43214da32e28c0f8853c6456304510022a32
[]
no_license
yazici/NetAndSysMonitor
d636638c841350f6e7b7884d79db5fbf3912af02
f1c6fa64b2372ae5b3387bc791245ae59d46a7fa
refs/heads/master
2021-01-05T10:30:12.335251
2013-07-05T06:17:50
2013-07-05T06:17:50
null
0
0
null
null
null
null
GB18030
C++
false
false
1,303
cpp
// GetSysInfo.cpp : 定义控制台应用程序的入口点。 // //#include "stdafx.h" #include "sysinfo.h" #include <stdio.h> #include <afxmt.h> #include <winioctl.h> //#include <Windows.h> int _tmain(int argc, _TCHAR* argv[]) { //printf("操作系统\n"); //printf("==============================\n"); //GetOSVersion(); // //printf("\n\n处理器\n"); //printf("==============================\n"); //GetCPUInfo(); //printf("\n\n内存\n"); //printf("==============================\n"); //GetMemoryInfo(); printf("\n\n电源\n"); printf("==============================\n"); PowerMng(); //printf("\n\nUSB Root Hub\n"); //printf("==============================\n"); //GetUSBHub(); //printf("\n\n网卡\n"); //printf("==============================\n"); //GetNetInfo(); // //printf("\n\n监听端口\n"); //printf("==============================\n"); //GetListeningPorts(); //printf("\n\n硬盘\n"); //printf("==============================\n"); //GetDiskInfo(); //printf("\n\n传感器\n"); //printf("==============================\n"); //GetSensorsInfo(); //printf("\n\n用户登录日志\n"); //printf("==============================\n"); //GetLoginInfo(); //printf("Press Enter to exit\n"); //getc(stdin); printf("\n"); system("pause"); return 0; }
[ "519916178@qq.com" ]
519916178@qq.com
1c2759a5b6e09be55fca1b3261f86deb9aa15d37
195a84eff9fbc23b1d9ec3e89b14c19d012cdbf4
/The 81/cinema_line1.cpp
c6acbe56b015c4356e57ede30de49c9cd8125d95
[]
no_license
Touhidul121/All_code
419baba7b37fa831e017f977063820b431308506
fb32f84a8d61eb30f48aae93e39388abe1388ab8
refs/heads/main
2023-01-02T17:16:18.433873
2020-10-26T18:47:07
2020-10-26T18:47:07
307,454,724
0
0
null
null
null
null
UTF-8
C++
false
false
1,002
cpp
#include<bits/stdc++.h> using namespace std; int main() { int n,a,c25=0,c50=0,x,flag=0; cin>>n; vector<int>v; for(int i=0;i<n;i++) { cin>>a; v.push_back(a); } for(int i=0;i<n;i++) { x=v[i]; if(x==25) { c25++; continue; } else if(x==50) { c50++; if(c25<1) { flag++; } else c25--; } else if(x==100) { if(c50>0) { if(c25<1) { flag++; } else { c25--; c50--; } } else if(c25<3) { flag++; } else c25-=3; } } if(flag) cout<<"NO"<<endl; else cout<<"YES"<<endl; }
[ "60749211+Touhidul121@users.noreply.github.com" ]
60749211+Touhidul121@users.noreply.github.com
1daa171587bcdd64b9255d358f26934510625476
c726edae823b73706ca3816aadbb995475576ef0
/qt_data/firstqt-build-desktop-Qt_4_8_1___PATH________/moc_main.cpp
047026a149c4477a7e90b33f3e289d46175612e1
[]
no_license
yunyitianqing/mycode_store
08fef09061707d3ada0f1f6435b24a92db7843a0
032220d69ecfcdc012c59a55c3d04aa2772ea85d
refs/heads/master
2020-04-06T06:41:08.207092
2015-05-20T08:58:19
2015-05-20T08:58:19
34,198,050
0
0
null
null
null
null
UTF-8
C++
false
false
2,340
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'main.h' ** ** Created: Mon Nov 4 09:30:06 2013 ** by: The Qt Meta Object Compiler version 63 (Qt 4.8.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../firstqt/main.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'main.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.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 static const uint qt_meta_data_MainWindow[] = { // content: 6, // 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 }; static const char qt_meta_stringdata_MainWindow[] = { "MainWindow\0" }; void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { Q_UNUSED(_o); Q_UNUSED(_id); Q_UNUSED(_c); Q_UNUSED(_a); } const QMetaObjectExtraData MainWindow::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject MainWindow::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_MainWindow, qt_meta_data_MainWindow, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &MainWindow::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *MainWindow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *MainWindow::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_MainWindow)) return static_cast<void*>(const_cast< MainWindow*>(this)); return QObject::qt_metacast(_clname); } int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE
[ "yunyi@yunyi-Lenovo-V370.(none)" ]
yunyi@yunyi-Lenovo-V370.(none)
60ca7ca7fe813c2c2c3c5fab937de3c26d678b8e
606cd394e75fed96db174f7fa7b217b8de4e9ee6
/third-party/thrift/gen/thrift/lib/thrift/gen-cpp2/reflection_types.cpp
989e076b1e2928a8794e615af30befe1a94d27eb
[ "MIT", "Zend-2.0", "PHP-3.01" ]
permissive
senfore/hhvm
3845e6b18914477445d9c910277f77900531719c
ba4f7b6bbcc87b64c9d57f5c8ba2692b895a046a
refs/heads/master
2020-12-04T16:12:31.345081
2020-01-04T17:28:27
2020-01-04T17:39:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,433
cpp
/** * Autogenerated by Thrift * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #include "thrift/lib/thrift/gen-cpp2/reflection_types.h" #include "thrift/lib/thrift/gen-cpp2/reflection_types.tcc" #include <thrift/lib/cpp2/gen/module_types_cpp.h> #include "thrift/lib/thrift/gen-cpp2/reflection_data.h" namespace apache { namespace thrift { constexpr std::size_t const TEnumTraits<::apache::thrift::reflection::Type>::size; folly::Range<::apache::thrift::reflection::Type const*> const TEnumTraits<::apache::thrift::reflection::Type>::values = folly::range(::apache::thrift::reflection::_TypeEnumDataStorage::values); folly::Range<folly::StringPiece const*> const TEnumTraits<::apache::thrift::reflection::Type>::names = folly::range(::apache::thrift::reflection::_TypeEnumDataStorage::names); char const* TEnumTraits<::apache::thrift::reflection::Type>::findName(type value) { using factory = ::apache::thrift::reflection::_Type_EnumMapFactory; static folly::Indestructible<factory::ValuesToNamesMapType> const map{ factory::makeValuesToNamesMap()}; auto found = map->find(value); return found == map->end() ? nullptr : found->second; } bool TEnumTraits<::apache::thrift::reflection::Type>::findValue(char const* name, type* out) { using factory = ::apache::thrift::reflection::_Type_EnumMapFactory; static folly::Indestructible<factory::NamesToValuesMapType> const map{ factory::makeNamesToValuesMap()}; auto found = map->find(name); return found == map->end() ? false : (*out = found->second, true); } }} // apache::thrift namespace apache { namespace thrift { namespace reflection { const _Type_EnumMapFactory::ValuesToNamesMapType _Type_VALUES_TO_NAMES = _Type_EnumMapFactory::makeValuesToNamesMap(); const _Type_EnumMapFactory::NamesToValuesMapType _Type_NAMES_TO_VALUES = _Type_EnumMapFactory::makeNamesToValuesMap(); }}} // apache::thrift::reflection namespace apache { namespace thrift { namespace detail { void TccStructTraits<::apache::thrift::reflection::StructField>::translateFieldName( FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "isRequired") { fid = 1; _ftype = apache::thrift::protocol::T_BOOL; } else if (_fname == "type") { fid = 2; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "name") { fid = 3; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "annotations") { fid = 4; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "order") { fid = 5; _ftype = apache::thrift::protocol::T_I16; } } void TccStructTraits<::apache::thrift::reflection::DataType>::translateFieldName( FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "name") { fid = 1; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "fields") { fid = 2; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "mapKeyType") { fid = 3; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "valueType") { fid = 4; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "enumValues") { fid = 5; _ftype = apache::thrift::protocol::T_MAP; } } void TccStructTraits<::apache::thrift::reflection::Schema>::translateFieldName( FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "dataTypes") { fid = 1; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "names") { fid = 2; _ftype = apache::thrift::protocol::T_MAP; } } } // namespace detail } // namespace thrift } // namespace apache namespace apache { namespace thrift { namespace reflection { StructField::StructField() : isRequired(0), type(0), order(0) {} StructField::~StructField() {} StructField::StructField(apache::thrift::FragileConstructor, bool isRequired__arg, int64_t type__arg, ::std::string name__arg, std::unordered_map<::std::string, ::std::string> annotations__arg, int16_t order__arg) : isRequired(std::move(isRequired__arg)), type(std::move(type__arg)), name(std::move(name__arg)), annotations(std::move(annotations__arg)), order(std::move(order__arg)) { __isset.isRequired = true; __isset.type = true; __isset.name = true; __isset.annotations = true; __isset.order = true; } void StructField::__clear() { // clear all fields isRequired = 0; type = 0; name = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); annotations.clear(); order = 0; __isset = {}; } bool StructField::operator==(const StructField& rhs) const { (void)rhs; auto& lhs = *this; (void)lhs; if (!(lhs.isRequired == rhs.isRequired)) { return false; } if (!(lhs.type == rhs.type)) { return false; } if (!(lhs.name == rhs.name)) { return false; } if (lhs.__isset.annotations != rhs.__isset.annotations) { return false; } if (lhs.__isset.annotations) { if (!(lhs.annotations == rhs.annotations)) { return false; } } if (!(lhs.order == rhs.order)) { return false; } return true; } const std::unordered_map<::std::string, ::std::string>* StructField::get_annotations() const& { return __isset.annotations ? std::addressof(annotations) : nullptr; } std::unordered_map<::std::string, ::std::string>* StructField::get_annotations() & { return __isset.annotations ? std::addressof(annotations) : nullptr; } void swap(StructField& a, StructField& b) { using ::std::swap; swap(a.isRequired, b.isRequired); swap(a.type, b.type); swap(a.name, b.name); swap(a.annotations, b.annotations); swap(a.order, b.order); swap(a.__isset, b.__isset); } template void StructField::readNoXfer<>(apache::thrift::BinaryProtocolReader*); template uint32_t StructField::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t StructField::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t StructField::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template void StructField::readNoXfer<>(apache::thrift::CompactProtocolReader*); template uint32_t StructField::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t StructField::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t StructField::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }}} // apache::thrift::reflection namespace apache { namespace thrift { namespace reflection { DataType::DataType() : mapKeyType(0), valueType(0) {} DataType::~DataType() {} DataType::DataType(apache::thrift::FragileConstructor, ::std::string name__arg, std::unordered_map<int16_t, ::apache::thrift::reflection::StructField> fields__arg, int64_t mapKeyType__arg, int64_t valueType__arg, std::unordered_map<::std::string, int32_t> enumValues__arg) : name(std::move(name__arg)), fields(std::move(fields__arg)), mapKeyType(std::move(mapKeyType__arg)), valueType(std::move(valueType__arg)), enumValues(std::move(enumValues__arg)) { __isset.name = true; __isset.fields = true; __isset.mapKeyType = true; __isset.valueType = true; __isset.enumValues = true; } void DataType::__clear() { // clear all fields name = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); fields.clear(); mapKeyType = 0; valueType = 0; enumValues.clear(); __isset = {}; } bool DataType::operator==(const DataType& rhs) const { (void)rhs; auto& lhs = *this; (void)lhs; if (!(lhs.name == rhs.name)) { return false; } if (lhs.__isset.fields != rhs.__isset.fields) { return false; } if (lhs.__isset.fields) { if (!(lhs.fields == rhs.fields)) { return false; } } if (lhs.__isset.mapKeyType != rhs.__isset.mapKeyType) { return false; } if (lhs.__isset.mapKeyType) { if (!(lhs.mapKeyType == rhs.mapKeyType)) { return false; } } if (lhs.__isset.valueType != rhs.__isset.valueType) { return false; } if (lhs.__isset.valueType) { if (!(lhs.valueType == rhs.valueType)) { return false; } } if (lhs.__isset.enumValues != rhs.__isset.enumValues) { return false; } if (lhs.__isset.enumValues) { if (!(lhs.enumValues == rhs.enumValues)) { return false; } } return true; } const std::unordered_map<int16_t, ::apache::thrift::reflection::StructField>* DataType::get_fields() const& { return __isset.fields ? std::addressof(fields) : nullptr; } std::unordered_map<int16_t, ::apache::thrift::reflection::StructField>* DataType::get_fields() & { return __isset.fields ? std::addressof(fields) : nullptr; } const std::unordered_map<::std::string, int32_t>* DataType::get_enumValues() const& { return __isset.enumValues ? std::addressof(enumValues) : nullptr; } std::unordered_map<::std::string, int32_t>* DataType::get_enumValues() & { return __isset.enumValues ? std::addressof(enumValues) : nullptr; } void swap(DataType& a, DataType& b) { using ::std::swap; swap(a.name, b.name); swap(a.fields, b.fields); swap(a.mapKeyType, b.mapKeyType); swap(a.valueType, b.valueType); swap(a.enumValues, b.enumValues); swap(a.__isset, b.__isset); } template void DataType::readNoXfer<>(apache::thrift::BinaryProtocolReader*); template uint32_t DataType::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t DataType::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t DataType::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template void DataType::readNoXfer<>(apache::thrift::CompactProtocolReader*); template uint32_t DataType::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t DataType::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t DataType::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }}} // apache::thrift::reflection namespace apache { namespace thrift { namespace reflection { Schema::Schema(apache::thrift::FragileConstructor, std::unordered_map<int64_t, ::apache::thrift::reflection::DataType> dataTypes__arg, std::unordered_map<::std::string, int64_t> names__arg) : dataTypes(std::move(dataTypes__arg)), names(std::move(names__arg)) { __isset.dataTypes = true; __isset.names = true; } void Schema::__clear() { // clear all fields dataTypes.clear(); names.clear(); __isset = {}; } bool Schema::operator==(const Schema& rhs) const { (void)rhs; auto& lhs = *this; (void)lhs; if (!(lhs.dataTypes == rhs.dataTypes)) { return false; } if (!(lhs.names == rhs.names)) { return false; } return true; } const std::unordered_map<int64_t, ::apache::thrift::reflection::DataType>& Schema::get_dataTypes() const& { return dataTypes; } std::unordered_map<int64_t, ::apache::thrift::reflection::DataType> Schema::get_dataTypes() && { return std::move(dataTypes); } const std::unordered_map<::std::string, int64_t>& Schema::get_names() const& { return names; } std::unordered_map<::std::string, int64_t> Schema::get_names() && { return std::move(names); } void swap(Schema& a, Schema& b) { using ::std::swap; swap(a.dataTypes, b.dataTypes); swap(a.names, b.names); swap(a.__isset, b.__isset); } template void Schema::readNoXfer<>(apache::thrift::BinaryProtocolReader*); template uint32_t Schema::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t Schema::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Schema::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template void Schema::readNoXfer<>(apache::thrift::CompactProtocolReader*); template uint32_t Schema::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t Schema::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t Schema::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }}} // apache::thrift::reflection
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
78a109342cad67989ed7f0e58751d69609735ce1
8d7c1318b069a8d54f9142015663f27ef93a8c6c
/wpilibc/src/main/native/include/frc/simulation/SolenoidSim.h
5b803665c3dedf439cbf42e869a232f40170deac
[ "BSD-3-Clause" ]
permissive
Glenffiiddich/allwpilib
149677f261597742c339ecf74ba9b69e2053cc89
a1c87e1e155e793fbdb621cba809d053abadf128
refs/heads/main
2023-03-31T22:26:12.767317
2021-04-06T20:19:49
2021-04-06T20:19:49
355,379,537
1
0
NOASSERTION
2021-04-07T01:43:27
2021-04-07T01:43:26
null
UTF-8
C++
false
false
2,629
h
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #pragma once #include <memory> #include "frc/Solenoid.h" #include "frc/simulation/CallbackStore.h" #include "frc/simulation/PCMSim.h" namespace frc::sim { /** * Class to control a simulated Pneumatic Control Module (PCM). */ class SolenoidSim { public: /** * Constructs for a solenoid on the default PCM. * * @param channel the solenoid channel. */ explicit SolenoidSim(int channel); /** * Constructs for the given solenoid. * * @param doubleSolenoid the solenoid to simulate. */ explicit SolenoidSim(Solenoid& solenoid); /** * Constructs for a solenoid. * * @param module the CAN ID of the PCM the solenoid is connected to. * @param channel the solenoid channel. * * @see PCMSim#PCMSim(int) */ SolenoidSim(int module, int channel); /** * Constructs for a solenoid on the given PCM. * * @param pcm the PCM the solenoid is connected to. * @param channel the solenoid channel. */ SolenoidSim(PCMSim& pcm, int channel); /** * Register a callback to be run when this solenoid is initialized. * * @param callback the callback * @param initialNotify should the callback be run with the initial state * @return the {@link CallbackStore} object associated with this callback. */ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterInitializedCallback( NotifyCallback callback, bool initialNotify); /** * Check if this solenoid has been initialized. * * @return true if initialized */ bool GetInitialized() const; /** * Define whether this solenoid has been initialized. * * @param initialized whether the solenoid is intiialized. */ void SetInitialized(bool initialized); /** * Register a callback to be run when the output of this solenoid has changed. * * @param callback the callback * @param initialNotify should the callback be run with the initial value * @return the {@link CallbackStore} object associated with this callback. */ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterOutputCallback( NotifyCallback callback, bool initialNotify); /** * Check the solenoid output. * * @return the solenoid output */ bool GetOutput() const; /** * Change the solenoid output. * * @param output the new solenoid output */ void SetOutput(bool output); private: PCMSim m_pcm; int m_channel; }; } // namespace frc::sim
[ "noreply@github.com" ]
noreply@github.com
cbb8cae47b851be67835aaa851b36ad8a397630f
0904d6c152b0cef9f8a6014ca8ebb6793ef71fd3
/block.h
63d0aba2d146d9dc96bfcb65a237b85e9f3c77e1
[]
no_license
kseckinc/rummikub
6dc80df43cc315cf94d6e89ff6a1125a998da4bf
ae80453369d9aa7c0206b5f294c7727a1afbd67b
refs/heads/master
2022-01-26T05:43:05.969088
2009-03-06T19:46:51
2009-03-06T19:46:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
127
h
#ifndef BLOCK_H #define BLOCK_H #include <QObject> class Block : public QObject { public: Block(); }; #endif // BLOCK_H
[ "bartekpiech@gmail.com" ]
bartekpiech@gmail.com
3bac29286f7f65a6af9752350e816189f7d3d2ad
b383d126d06088c370f8c92310bc5cc9e94e1b0c
/include/Stick.h
b4e9158c45a12a209cee6727b4b41c0cea62f7bf
[]
no_license
tamtamxtamtam/StickHero
064b7793fe11b122d117aabeb74c294a0e44a159
52385efe7f355359d9e59e123bc5f0a5dde5aa41
refs/heads/master
2021-05-20T10:36:05.660574
2020-04-01T18:22:02
2020-04-01T18:42:13
252,252,756
1
0
null
null
null
null
UTF-8
C++
false
false
471
h
#ifndef STICK_H #define STICK_H #include <SFML/Graphics.hpp> using namespace sf; class Stick { public: const int stick_width = 5; float stick_length=0; int d; // stt: 0 trạng thái đứng im, 1: trạng thái thay đổi độ cao; int stt=1; float angle=0; //Stick(); Stick(float stick_length); void DrawStick(RenderWindow& window); void RotationStick(); }; #endif // STICK_H
[ "tamnoa48@gmail.com" ]
tamnoa48@gmail.com
10b26ea7c376d7205ed94f498958cbe53c884d20
8403738e873da6add2b5d32beb8105fe8d2e66cb
/C++ Primer_5/13/13.27.h
a2686dd0d6a3ec84b9871bcf74ebcb379b8655c2
[]
no_license
autyinjing/Cpp-learning
415a9e9130c1d864b28b749e8a27935936a08234
fea63fed9c124c6a4218c61ce455554a8d6f29e4
refs/heads/master
2021-01-19T01:52:59.513207
2017-04-21T10:18:22
2017-04-21T10:18:22
38,310,895
0
0
null
null
null
null
UTF-8
C++
false
false
1,418
h
// ===================================================================================== // // Filename: 13.27.cpp // // Description: // // Version: 1.0 // Created: 10/18/2014 09:46:09 PM // Revision: none // Compiler: g++ // // Author: aut (yinjing), linuxeryinjing@gmail.com // Company: Information and Computing Science 1201 // // ===================================================================================== #ifndef HASPTR_H #define HASPTR_H #include <string> class HasPtr { public: HasPtr(const std::string &s = std::string()) : ps(new std::string(s)), i(0), use(new std::size_t(1)) { } HasPtr(const HasPtr &p) : ps(p.ps), i(p.i), use(p.use) { ++*use; } HasPtr& operator=(const HasPtr&); ~HasPtr(); private: std::string *ps; int i; std::size_t *use; }; HasPtr::~HasPtr() { if (--*use == 0) { delete ps; delete use; } } HasPtr& HasPtr::operator=(const HasPtr &rhs) { ++*rhs.use; if (--*use == 0) { delete ps; delete use; } ps = rhs.ps; i = rhs.i; use = rhs.use; return *this; } #endif
[ "autyinjing@126.com" ]
autyinjing@126.com
31e92504c2dadfef29079a312fc708d9b423f9da
b8b364536f1064e5d123023375ce944e3d69be35
/src/LAVAflow/devel/trunk/drivers/devel/AveragingDriver/Averaging.h
fa0cd4d16e3bda2cc4ec537e4700fdc47010dacf
[]
no_license
csu-anzai/Hydro
c891ee71a25f19e5326ecbe9d69031899afcbcba
9b15767875550ebb6da72797d263d9c1aa8a74c1
refs/heads/master
2020-07-19T00:25:44.453761
2019-09-03T11:20:38
2019-09-03T11:20:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
375
h
#include<vector> #include "FlashAmrMesh.h" struct averageData { char dir; int nbins; double binsize; vector<double> binAverages; }; class ShellAverage { public: ShellAverage(); void calcShellAverage(int, int); void calcShellAverage(int, double); void calcShellAverage(int, vector<double>&); ~ShellAverage(); private: };
[ "git@github.com" ]
git@github.com
1018579e73dea16b89fddc31c0358724a4242ed9
cd84920281226d0b9bde1d6c1e9a7de9ce0f9210
/lab5.cpp
02e98502c4e6f447a041a5de23c1283fffbc5efd
[]
no_license
mansha28/data-structure-and-algorith
5455274ad1770497d625fe3bae241c35b44dd289
f2e104c032ae78c15ca467a89086fc6a5733ca14
refs/heads/master
2020-06-28T20:38:05.507033
2019-11-11T07:19:31
2019-11-11T07:19:31
200,335,712
0
0
null
null
null
null
UTF-8
C++
false
false
3,743
cpp
#include<bits/stdc++.h> #include<string> using namespace std; struct et { string value; et* left, *right; }; int toInt(string s) { int num = 0; for (int i=0; i<s.length(); i++) num = num*10 + (int(s[i])-48); return num; } int eval(et* root) { if (!root) return 0; if (!root->left && !root->right) return toInt(root->value); int l_val = eval(root->left); int r_val = eval(root->right); string w=root->value; if (w[0]=='+') return l_val+r_val; if (w[0]=='-') return l_val-r_val; if (w[0]=='/') return l_val*r_val; if (w[0]=='*') return l_val*r_val; if(w[0]=='^') return pow(l_val,r_val); return l_val/r_val; } int isOperator(string s) {if(s[0]=='+'||s[0]=='*'||s[0]=='-'||s[0]=='/'||s[0]=='^') return(1); else return(0);} et* newNode(string v) { et *temp = new et; temp->left = temp->right = NULL; temp->value = v; return temp; }; et* constructTree(vector<string> j) { stack<et *> st; et *t, *t1, *t2; for (int i=0; i<j.size(); i++) { if (!isOperator(j[i])) { t = newNode(j[i]); st.push(t); } else { t = newNode(j[i]); t1 = st.top(); st.pop(); t2 = st.top(); st.pop(); t->right = t1; t->left = t2; st.push(t); } } t = st.top(); st.pop(); return t; } int prec(char c) { if(c == '^') return 3; else if(c == '*' || c == '/') return 2; else if(c == '+' || c == '-') return 1; else return -1; } vector <string> intopo(string s) { stack<string> st; string x; st.push(x); vector<string> ns; for(int i = 0; i < s.length(); i++) { string q=""; string r; while(s[i] >= '0' && s[i] <= '9') { q.push_back(s[i]); i++; } ns.push_back(q); q.clear(); if(((s[0] >= 'a' && s[0] <= 'z')||(s[0] >= 'A' && s[0] <= 'Z'))&&(s[1]=='=')) {string r=""; for(int d=0;d<s.length();d++){ r.push_back(s[i]); ns.push_back(r);}} r.clear(); if(s[i] == '(') {string r=""; r.push_back(s[i]); st.push(r);} r.clear(); string d="("; if(s[i] == ')') { while(st.top() != x && st.top() !=d) { string c = st.top(); st.pop(); ns.push_back(c); } if(st.top() == d) { string c = st.top(); st.pop(); } } if(s[i]=='+'||s[i]=='/'||s[i]=='*'||s[i]=='-'||s[i]=='^'){ string f=st.top(); char c=f[0]; while(st.top() != x && prec(s[i]) <= prec(c)) { string h = st.top(); st.pop(); char c=h[0]; ns.push_back(h); } string r=""; r.push_back(s[i]); st.push(r); } } while(st.top() != x) { string c = st.top(); st.pop(); ns.push_back(c); } return ns; } int main() { int k,l,a,num; cin>>k>>a; string o; for(l=0;l<k;l++) { for(int v=0;v<a;v++) { cin>>o; vector<string> j = intopo(o); int i; et* a = constructTree(j) ; num = eval(a); cout<<num<<endl;} } }
[ "noreply@github.com" ]
noreply@github.com
e12dc8b664d3a3b2c10342c5d61d468e7e07a9fb
642e54aa613e0ff40832520689340b104a6b8e49
/Project/huffman_tree_by_binary_heap.h
baced90ec58b4287ca7ab7260cccb2bb45c21ec1
[]
no_license
song-zc/COP5536-ADS
3d49a0cae5cdcc480aac181465b56e12d3af3e9e
231e2fc4b7f1a0ce63bbb263deb89613f6357821
refs/heads/main
2023-02-24T23:30:12.349456
2021-01-29T23:03:40
2021-01-29T23:03:40
334,248,783
0
0
null
null
null
null
UTF-8
C++
false
false
130
h
#include <unordered_map> void build_tree_using_binary_heap(std::unordered_map<int,int>& ,std::unordered_map<int, std::string>&);
[ "54408520+song-zc@users.noreply.github.com" ]
54408520+song-zc@users.noreply.github.com
e127fdb2c0ab4c335277410e8ddd421d413f1d20
030422bd97b8df840fc68ab38974855c677391f3
/src/move_robot/include/sendrev.h
75c22f33aed42a1672877568453e4e2d95ab32ae
[]
no_license
yoyoyin0902/outdoorAGV
c06474b44bfa45dcff3692b41bb8235d0e0530fd
b8ddab634b4946176e4d98c298e3e10a86b42712
refs/heads/main
2023-06-21T04:02:24.971344
2021-07-08T12:41:53
2021-07-08T12:41:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,350
h
#include <vector> #include <math.h> #include <stdio.h> #include <iostream> #include <Eigen/Core> #include <Eigen/Dense> #include <move_robot/Battery.h> #define ChinaMotor 0 #define IVAM_Car_vlvr 0 #define IVAM_Car_vw 1 #define Boling_smallgray 2 #define public_wheel 0 class sendrev { public: sendrev(); void Setmode(int input); void Package_AllDir_encoder(int FL, int FLA,int BL,int BLA,int FR ,int FRA,int BR,int BRA,std::vector<unsigned char> &return_cmd); void Package_Diff_encoder(double cmd_vl, double cmd_vr,std::vector<unsigned char> &return_cmd); void Package_publicWheel_encoder(double cmd_vx, double cmd_vy, double cmd_w, int type, std::vector<unsigned char> &return_cmd);//測試公板 void Package_Boling_smallgray(double &cmd_vl, double &cmd_vr,std::vector<unsigned char> &return_cmd); void Package_Boling_yellow(double v, double th,unsigned char &return_cmd,int &nByte); void Package_allWheel_encoder(double cmd_vx, double cmd_vy, double cmd_w, int type, std::vector<unsigned char> &return_cmd);//測試公版 void RevProcess_AllDir_encoder(std::vector<unsigned char> &rev_buf,float &Rev_FR_rpm,float &Rev_FL_rpm,float &Rev_RR_rpm,float &Rev_RL_rpm,float &Rev_FR_deg,float &Rev_FL_deg,float &Rev_RR_deg,float &Rev_RL_deg); void RevProcess_two_wheel_encoder(std::vector<unsigned char> &rev_buf,float &Rev_V, float &Rev_W); void RevProcess_publicWheel_encoder(std::vector<unsigned char> &rev_buf,float &Rev_V, float &Rev_th, float &Rev_W, int &type);//測試公版 void RevProcess_allWheel(std::vector<unsigned char> &rev_buf,float &Rev_V, float &Rev_W);//測試公版 private: void Package_ChinaMotor(int &FL, int &FLA,int &BL,int &BLA,int &FR ,int &FRA,int &BR,int &BRA,std::vector<unsigned char> &return_cmd ); void Package_IVAM_Car_vlvr(double &cmd_vl, double &cmd_vr,std::vector<unsigned char> &return_cmd); void Package_IVAM_Car_vw(double &cmd_vl, double &cmd_vr,std::vector<unsigned char> &return_cmd); void RevProcess_ChinaMotor(std::vector<unsigned char> &rev_buf,float &Rev_FR_rpm,float &Rev_FL_rpm,float &Rev_RR_rpm,float &Rev_RL_rpm,float &Rev_FR_deg,float &Rev_FL_deg,float &Rev_RR_deg,float &Rev_RL_deg); void RevProcess_IVAM_Car_vw(std::vector<unsigned char> &rev_buf,float &Rev_V, float &Rev_W); private: int mode; ros::NodeHandle nodeHandle_; ros::Publisher Battery_Publisher_; }; sendrev::sendrev() { mode = -1 ; Battery_Publisher_ = nodeHandle_.advertise<move_robot::Battery>("Battery",10); } void sendrev::Setmode(int input) { mode = input; } void sendrev::Package_AllDir_encoder(int FL, int FLA,int BL,int BLA,int FR ,int FRA,int BR,int BRA,std::vector<unsigned char> &return_cmd) { switch(mode){ case ChinaMotor: Package_ChinaMotor( FL, FLA, BL, BLA, FR , FRA, BR, BRA, return_cmd ); break; default: break; } } void sendrev::Package_publicWheel_encoder(double cmd_vx, double cmd_vy, double cmd_w, int type, std::vector<unsigned char> &return_cmd)//測試公版 { switch(mode){ case public_wheel: Package_allWheel_encoder(cmd_vx, cmd_vy, cmd_w, type, return_cmd); break; default: break; } } void sendrev::Package_Diff_encoder(double cmd_vl, double cmd_vr,std::vector<unsigned char> &return_cmd) { switch(mode){ case IVAM_Car_vlvr: Package_IVAM_Car_vlvr(cmd_vl, cmd_vr, return_cmd); break; case IVAM_Car_vw: Package_IVAM_Car_vw(cmd_vl, cmd_vr, return_cmd); break; case Boling_smallgray: Package_Boling_smallgray(cmd_vl, cmd_vr, return_cmd); break; default: break; } } void sendrev::Package_ChinaMotor(int &FL, int &FLA,int &BL,int &BLA,int &FR ,int &FRA,int &BR,int &BRA,std::vector<unsigned char> &return_cmd ) { static unsigned char counter = 0; //int nByte = 0; //unsigned char command[30]; std::vector<unsigned char> command; unsigned char FLHrpm,FLLrpm, FLHdegree,FLLdegree,FRHrpm,FRFLLrpm, FRHdegree,FRLdegree ,BLHrpm,BLLrpm, BLHdegree,BLLdegree,BRHrpm,BRFLLrpm, BRHdegree,BRLdegree; if(FL < 0) { FLHrpm=(unsigned char)((FL&0xFF00)>>8); FLLrpm=(unsigned char)(FL&0x00FF); } else { FLHrpm=(unsigned char)(FL/256); FLLrpm=(unsigned char)(FL%256); } if(FLA < 0) { FLHdegree=(unsigned char)((FLA&0xFF00)>>8); FLLdegree=(unsigned char)(FLA&0x00FF); } else { FLHdegree=(unsigned char)(FLA/256); FLLdegree=(unsigned char)(FLA%256); } if(BL < 0) { BLHrpm=(unsigned char)((BL&0xFF00)>>8); BLLrpm=(unsigned char)(BL&0x00FF); }else { BLHrpm=(unsigned char)(BL/256); BLLrpm=(unsigned char)(BL%256); } if(BLA < 0) { BLHdegree=(unsigned char)((BLA&0xFF00)>>8); BLLdegree=(unsigned char)(BLA&0x00FF); } else { BLHdegree=(unsigned char)(BLA/256); BLLdegree=(unsigned char)(BLA%256); } if(FR < 0) { FRHrpm=(unsigned char)((FR&0xFF00)>>8); FRFLLrpm=(unsigned char)(FR&0x00FF); } else { FRHrpm=(unsigned char)(FR/256); FRFLLrpm=(unsigned char)(FR%256); } if(FRA < 0) { FRHdegree=(unsigned char)((FRA&0xFF00)>>8); FRLdegree=(unsigned char)(FRA&0x00FF); } else { FRHdegree=(unsigned char)(FRA/256); FRLdegree=(unsigned char)(FRA%256); } if(BR < 0) { BRHrpm=(unsigned char)((BR&0xFF00)>>8); BRFLLrpm=(unsigned char)(BR&0x00FF); }else { BRHrpm=(unsigned char)(BR/256); BRFLLrpm=(unsigned char)(BR%256); } if(BRA < 0) { BRHdegree=(unsigned char)((BRA&0xFF00)>>8); BRLdegree=(unsigned char)(BRA&0x00FF); } else { BRHdegree=(unsigned char)(BRA/256); BRLdegree=(unsigned char)(BRA%256); } //std::cout<<"FL "<< FL<<std::endl; command.push_back(0x0a); command.push_back(FRFLLrpm); command.push_back(FRHrpm); command.push_back(FRLdegree); command.push_back(FRHdegree); command.push_back(FLLrpm); command.push_back(FLHrpm); command.push_back(FLLdegree); command.push_back(FLHdegree); command.push_back(BLLrpm); command.push_back(BLHrpm); command.push_back(BLLdegree); command.push_back(BLHdegree); command.push_back(BRFLLrpm); command.push_back(BRHrpm); command.push_back(BRLdegree); command.push_back(BRHdegree); command.push_back(0x00); command.push_back(0x00); command.push_back(0x00); command.push_back(0x00); command.push_back(0x00); command.push_back(0x00); command.push_back(0x00); command.push_back(0x00); command.push_back(0x00); command.push_back(0x00); command.push_back(counter); command.push_back(0x00); command.push_back(0x0d); for(int i=1; i<=27; i++) command[28] += command[i]; counter += 1; if(counter > 255) counter = 0; return_cmd = command; } void sendrev::Package_allWheel_encoder(double cmd_vx, double cmd_vy, double cmd_w, int type, std::vector<unsigned char> &return_cmd)//測試公版沒有vy就是0 { //std::cout<<"cmd_vx: "<<cmd_vx<<std::endl; std::cout<<"cmd_vx: "<<cmd_vx<<" cmd_w: "<<cmd_w<<" type: "<<type<<std::endl; double send_vx = cmd_vx + 100.0; double send_vy = cmd_vy + 100.0; double send_w = cmd_w + 100.0; static unsigned char count = 0; std::vector<unsigned char> command; int integer_vx = (int(send_vx)); int float_vx = ( int((send_vx - double(integer_vx))*1000 )); int integer_vy = (int(send_vy)); int float_vy = ( int((send_vy - double(integer_vy))*1000 )); int integer_w = (int(send_w)); int float_w = ( int((send_w - double(integer_w))*1000 )); int HighByte_integer_vx = integer_vx/256; int LowByte_integer_vx = integer_vx%256; int HighByte_float_vx = float_vx/256; int LowByte_float_vx = float_vx%256; int HighByte_integer_vy = integer_vy/256; int LowByte_integer_vy = integer_vy%256; int HighByte_float_vy = float_vy/256; int LowByte_float_vy = float_vy%256; int HighByte_integer_w = integer_w/256; int LowByte_integer_w = integer_w%256; int HighByte_float_w = float_w/256; int LowByte_float_w = float_w%256; int checksum = HighByte_integer_vx + LowByte_integer_vx + HighByte_float_vx + LowByte_float_vx + HighByte_integer_vy + LowByte_integer_vy + HighByte_float_vy + LowByte_float_vy + HighByte_integer_w + LowByte_integer_w + HighByte_float_w + LowByte_float_w; if(type == 1) { HighByte_float_vx = 0; LowByte_float_vx = 0; HighByte_float_vy = 0; LowByte_float_vy = 0; HighByte_float_w = 0; LowByte_float_w = 0; } command.push_back('S'); command.push_back('T'); command.push_back(HighByte_integer_vx); command.push_back(LowByte_integer_vx); command.push_back(HighByte_float_vx); command.push_back(LowByte_float_vx); command.push_back(HighByte_integer_vy); command.push_back(LowByte_integer_vy); command.push_back(HighByte_float_vy); command.push_back(LowByte_float_vy); command.push_back(HighByte_integer_w); command.push_back(LowByte_integer_w); command.push_back(HighByte_float_w); command.push_back(LowByte_float_w); command.push_back(checksum); command.push_back(count);//判斷有沒有斷訊 command.push_back(type);//開口 command.push_back('E'); command.push_back('N'); command.push_back('D'); return_cmd = command; count++; if(count == 256) { count = 0; } } void sendrev::RevProcess_IVAM_Car_vw(std::vector<unsigned char> &rev_buf,float &Rev_V, float &Rev_W) { if(rev_buf[0] == 'E' && rev_buf[1] == 'C' && rev_buf[10] == 'E') { int HighByte_integer_v = rev_buf[2]; int LowByte_integer_v = rev_buf[3]; int HighByte_float_v = rev_buf[4]; int LowByte_float_v = rev_buf[5]; int HighByte_integer_w = rev_buf[6]; int LowByte_integer_w = rev_buf[7]; int HighByte_float_w = rev_buf[8]; int LowByte_float_w = rev_buf[9]; int integer_v = HighByte_integer_v * 256 + LowByte_integer_v; int float_v = HighByte_float_v * 256 + LowByte_float_v; int integer_w = HighByte_integer_w * 256 + LowByte_integer_w; int float_w = HighByte_float_w * 256 + LowByte_float_w; float V = integer_v + float_v * 0.001; float W = integer_w + float_w * 0.001; Rev_V = V - 20; Rev_W = W - 20; } //std::cout<<"Rev_V = "<<Rev_V<<" "<<" Rev_W = "<<Rev_W<<std::endl; } void sendrev::Package_Boling_yellow(double v, double th,unsigned char &return_cmd,int &nByte) { double send_v = v + 20.0; double send_th = th + 100.0; unsigned char command[13]; //std::cout<<"send_vl: "<<send_vl<<std::endl; //std::cout<<"send_vr: "<<send_vr<<std::endl; int integer_v = (int(send_v)); int float_v = ( int((send_v - double(integer_v))*1000 )); int integer_th = (int(send_th)); int float_th = ( int((send_th - double(integer_th))*1000 )); int HighByte_integer_v = integer_v/128; int LowByte_integer_v = integer_v%128; int HighByte_float_v = float_v/128; int LowByte_float_v = float_v%128; int HighByte_integer_th = integer_th/128; int LowByte_integer_th = integer_th%128; int HighByte_float_th = float_th/128; int LowByte_float_th = float_th%128; command[ 0] = 'S'; command[ 1] = 'A'; command[ 2] = HighByte_integer_v; command[ 3] = LowByte_integer_v; command[ 4] = HighByte_float_v; command[ 5] = LowByte_float_v; command[ 6] = HighByte_integer_th; command[ 7] = LowByte_integer_th; command[ 8] = HighByte_float_th; command[ 9] = LowByte_float_th; command[10] = 'E'; command[11] = 'N'; command[12] = 'D'; nByte = 13; return_cmd = *command; // int nByte = 0; // if(mySerial.serial_ok){ // nByte = write(mySerial.fd,command,13); // ROS_INFO("AAA %d", nByte); // std::cout<<"command "<<command[0]<<std::endl; // } } void sendrev::RevProcess_two_wheel_encoder(std::vector<unsigned char> &rev_buf,float &Rev_V, float &Rev_W) { switch(mode) { case IVAM_Car_vw: RevProcess_IVAM_Car_vw(rev_buf, Rev_V, Rev_W); break; default: break; } } void sendrev::RevProcess_AllDir_encoder(std::vector<unsigned char> &rev_buf,float &Rev_FR_rpm,float &Rev_FL_rpm,float &Rev_RR_rpm,float &Rev_RL_rpm,float &Rev_FR_deg,float &Rev_FL_deg,float &Rev_RR_deg,float &Rev_RL_deg) { switch(mode){ case ChinaMotor: RevProcess_ChinaMotor(rev_buf, Rev_FR_rpm, Rev_FL_rpm, Rev_RR_rpm, Rev_RL_rpm, Rev_FR_deg, Rev_FL_deg, Rev_RR_deg, Rev_RL_deg); break; default: break; } } void sendrev::RevProcess_publicWheel_encoder(std::vector<unsigned char> &rev_buf,float &Rev_V, float &Rev_th, float &Rev_W, int &type) { switch(mode) { case public_wheel: RevProcess_allWheel(rev_buf, Rev_V, Rev_W); break; default: break; } } void sendrev::RevProcess_allWheel(std::vector<unsigned char> &rev_buf,float &Rev_V, float &Rev_W) { //static int count = 0; if(rev_buf[0] == 'E' && rev_buf[1] == 'C' && rev_buf[10] == 'E') { int HighByte_integer_v = rev_buf[2]; int LowByte_integer_v = rev_buf[3]; int HighByte_float_v = rev_buf[4]; int LowByte_float_v = rev_buf[5]; int HighByte_integer_w = rev_buf[6]; int LowByte_integer_w = rev_buf[7]; int HighByte_float_w = rev_buf[8]; int LowByte_float_w = rev_buf[9]; int integer_v = HighByte_integer_v * 256 + LowByte_integer_v; int float_v = HighByte_float_v * 256 + LowByte_float_v; int integer_w = HighByte_integer_w * 256 + LowByte_integer_w; int float_w = HighByte_float_w * 256 + LowByte_float_w; float V = integer_v + float_v * 0.001; float W = integer_w + float_w * 0.001; Rev_V = V - 100; Rev_W = W - 100; } //std::cout<<"Rev_V = "<<Rev_V<<" "<<" Rev_W = "<<Rev_W<<std::endl; } void sendrev::RevProcess_ChinaMotor(std::vector<unsigned char> &rev_buf,float &Rev_FR_rpm,float &Rev_FL_rpm,float &Rev_RR_rpm,float &Rev_RL_rpm,float &Rev_FR_deg,float &Rev_FL_deg,float &Rev_RR_deg,float &Rev_RL_deg) { // for(int i =0;i<rev_buf.size();i++) // { // printf("%x \n",rev_buf[i]); // } if(rev_buf[0] == 0x0A && rev_buf[26] ==0x00 && rev_buf[29] == 0x0D){ unsigned char FR_RPM_L = rev_buf[1] + 0x00; unsigned char FR_RPM_H = rev_buf[2] + 0x00; unsigned char FR_DEG_L = rev_buf[3] + 0x00; unsigned char FR_DEG_H = rev_buf[4] + 0x00; unsigned char FL_RPM_L = rev_buf[5] + 0x00; unsigned char FL_RPM_H = rev_buf[6] + 0x00; unsigned char FL_DEG_L = rev_buf[7] + 0x00; unsigned char FL_DEG_H = rev_buf[8] + 0x00; unsigned char RL_RPM_L = rev_buf[9] + 0x00; unsigned char RL_RPM_H = rev_buf[10] + 0x00; unsigned char RL_DEG_L = rev_buf[11] + 0x00; unsigned char RL_DEG_H = rev_buf[12] + 0x00; unsigned char RR_RPM_L = rev_buf[13] + 0x00; unsigned char RR_RPM_H = rev_buf[14] + 0x00; unsigned char RR_DEG_L = rev_buf[15] + 0x00; unsigned char RR_DEG_H = rev_buf[16] + 0x00; unsigned char check_byte = rev_buf[28] + 0x00; unsigned char sum_of_byte = 0; for(int j=1; j <= 27; j++){ unsigned char byte_buf = rev_buf[j] + 0x00; sum_of_byte += byte_buf; } sum_of_byte = sum_of_byte%256; float FR_RPM = float(int(FR_RPM_H)*256 + int(FR_RPM_L)); float FL_RPM = float(int(FL_RPM_H)*256 + int(FL_RPM_L)); float RR_RPM = float(int(RR_RPM_H)*256 + int(RR_RPM_L)); float RL_RPM = float(int(RL_RPM_H)*256 + int(RL_RPM_L)); float FR_DEG = float(int(FR_DEG_H)*256 + int(FR_DEG_L)); float FL_DEG = float(int(FL_DEG_H)*256 + int(FL_DEG_L)); float RR_DEG = float(int(RR_DEG_H)*256 + int(RR_DEG_L)); float RL_DEG = float(int(RL_DEG_H)*256 + int(RL_DEG_L)); if(FR_RPM >= 32768.0) FR_RPM = FR_RPM - 65536; if(FL_RPM >= 32768.0) FL_RPM = FL_RPM - 65536; if(RR_RPM >= 32768.0) RR_RPM = RR_RPM - 65536; if(RL_RPM >= 32768.0) RL_RPM = RL_RPM - 65536; if(FR_DEG >= 32768.0) FR_DEG = FR_DEG - 65536.0; if(FL_DEG >= 32768.0) FL_DEG = FL_DEG - 65536.0; if(RR_DEG >= 32768.0) RR_DEG = RR_DEG - 65536.0; if(RL_DEG >= 32768.0) RL_DEG = RL_DEG - 65536.0; FR_RPM = FR_RPM/10; FL_RPM = FL_RPM/10; RR_RPM = RR_RPM/10; RL_RPM = RL_RPM/10; FR_DEG = FR_DEG/10; FL_DEG = FL_DEG/10; RR_DEG = RR_DEG/10; RL_DEG = RL_DEG/10; //std::cout<<"FR_DEG: "<<FR_DEG<<std::endl; if(sum_of_byte == check_byte){ Rev_FR_rpm = FR_RPM; Rev_FL_rpm = FL_RPM; Rev_RR_rpm = RR_RPM; Rev_RL_rpm = RL_RPM; Rev_FR_deg = FR_DEG; Rev_FL_deg = FL_DEG; Rev_RR_deg = RR_DEG; Rev_RL_deg = RL_DEG; // std::cout<<"========================================="<<std::endl; // std::cout<<"FR_RPM: "<<FR_RPM<<std::endl; // std::cout<<"FL_RPM: "<<FL_RPM<<std::endl; // std::cout<<"RR_RPM: "<<RR_RPM<<std::endl; // std::cout<<"RL_RPM: "<<RL_RPM<<std::endl; // std::cout<<"-----------------------------------------"<<std::endl; //std::cout<<"FR_DEG: "<<FR_DEG * M_PI /180.0<<std::endl; // std::cout<<"FL_DEG: "<<FL_DEG * M_PI /180.0<<std::endl; // std::cout<<"RR_DEG: "<<RR_DEG<<std::endl; // std::cout<<"RL_DEG: "<<RL_DEG<<std::endl; // std::cout<<"-----------------------------------------"<<std::endl; // std::cout<<"check_byte: "<<check_byte<<std::endl; // std::cout<<"sum_of_byte: "<<sum_of_byte<<std::endl; } rev_buf.clear(); //std::cout<<"========rev_buf.size()======== "<<rev_buf.size()<<std::endl; } else if(rev_buf[0] == 0x0A && rev_buf[26] == 0x01 && rev_buf[29] == 0x0D){ unsigned char Voltage1_buf = rev_buf[1] + 0x00; unsigned char Voltage2_buf = rev_buf[2] + 0x00; unsigned char Voltage3_buf = rev_buf[3] + 0x00; unsigned char Voltage4_buf = rev_buf[4] + 0x00; unsigned char Current1_buf = rev_buf[5] + 0x00; unsigned char Current2_buf = rev_buf[6] + 0x00; unsigned char Current3_buf = rev_buf[7] + 0x00; unsigned char Current4_buf = rev_buf[8] + 0x00; unsigned char RelativeSOC1_buf = rev_buf[9] + 0x00; unsigned char RelativeSOC2_buf = rev_buf[10] + 0x00; unsigned char RelativeSOC3_buf = rev_buf[11] + 0x00; unsigned char RelativeSOC4_buf = rev_buf[12] + 0x00; unsigned char AbsoluteSOC1_buf = rev_buf[13] + 0x00; unsigned char AbsoluteSOC2_buf = rev_buf[14] + 0x00; unsigned char AbsoluteSOC3_buf = rev_buf[15] + 0x00; unsigned char AbsoluteSOC4_buf = rev_buf[16] + 0x00; unsigned char Temp1_buf = rev_buf[17] + 0x00; unsigned char Temp2_buf = rev_buf[18] + 0x00; unsigned char Temp3_buf = rev_buf[19] + 0x00; unsigned char Temp4_buf = rev_buf[20] + 0x00; unsigned char check_byte = rev_buf[28] + 0x00; unsigned char sum_of_byte = 0; for(int j=1; j <= 27; j++){ unsigned char byte_buf = rev_buf[j] + 0x00; sum_of_byte += byte_buf; } sum_of_byte = sum_of_byte%256; if(sum_of_byte == check_byte){ float Voltage1 = float(Voltage1_buf % 256); float Voltage2 = float(Voltage2_buf % 256); float Voltage3 = float(Voltage3_buf % 256); float Voltage4 = float(Voltage4_buf % 256); float Current1 = float(Current1_buf % 256 ); float Current2 = float(Current2_buf % 256 ); float Current3 = float(Current3_buf % 256 ); float Current4 = float(Current4_buf % 256 ); float RelativeSOC1 = float(RelativeSOC1_buf % 256); float RelativeSOC2 = float(RelativeSOC2_buf % 256); float RelativeSOC3 = float(RelativeSOC3_buf % 256); float RelativeSOC4 = float(RelativeSOC4_buf % 256); float AbsoluteSOC1 = float(AbsoluteSOC1_buf % 256); float AbsoluteSOC2 = float(AbsoluteSOC2_buf % 256); float AbsoluteSOC3 = float(AbsoluteSOC3_buf % 256); float AbsoluteSOC4 = float(AbsoluteSOC4_buf % 256); float Temp1 = float(Temp1_buf % 256); float Temp2 = float(Temp2_buf % 256); float Temp3 = float(Temp3_buf % 256); float Temp4 = float(Temp4_buf % 256); //有負的話 if(Current1 >128){Current1 = Current1 - 256;} if(Current2 >128){Current2 = Current2 - 256;} if(Current3 >128){Current3 = Current3 - 256;} if(Current4 >128){Current4 = Current4 - 256;} if(Temp1 >128){Temp1 = Temp1 - 256;} if(Temp2 >128){Temp2 = Temp2 - 256;} if(Temp3 >128){Temp3 = Temp3 - 256;} if(Temp4 >128){Temp4 = Temp4 - 256;} float Voltage = (Voltage1 + Voltage2 + Voltage3 + Voltage4)/10.0; float Current = (Current1 + Current2 + Current3 + Current4)/4.0; move_robot::Battery msg; msg.Voltage = Voltage; msg.Current = Current; msg.RelativeSOC1 = RelativeSOC1; msg.RelativeSOC2 = RelativeSOC2; msg.RelativeSOC3 = RelativeSOC3; msg.RelativeSOC4 = RelativeSOC4; msg.AbsoluteSOC1 = AbsoluteSOC1; msg.AbsoluteSOC2 = AbsoluteSOC2; msg.AbsoluteSOC3 = AbsoluteSOC3; msg.AbsoluteSOC4 = AbsoluteSOC4; msg.Temp1 = Temp1; msg.Temp2 = Temp2; msg.Temp3 = Temp3; msg.Temp4 = Temp4; Battery_Publisher_.publish(msg); //電壓 除10倍才是原值 // std::cout<<"========================================="<<std::endl; // std::cout<<"Voltage1: "<<Voltage1 /10.0<<std::endl; // std::cout<<"Voltage2: "<<Voltage2 /10.0<<std::endl; // std::cout<<"Voltage3: "<<Voltage3 /10.0<<std::endl; // std::cout<<"Voltage4: "<<Voltage4 /10.0<<std::endl; // std::cout<<"Current1: "<< Current1<<std::endl; // std::cout<<"Current2: "<< Current2<<std::endl; // std::cout<<"Current3: "<< Current3<<std::endl; // std::cout<<"Current4: "<< Current4<<std::endl; // std::cout<<"RelativeSOC1: "<<RelativeSOC1<<std::endl; // std::cout<<"RelativeSOC2: "<<RelativeSOC2<<std::endl; // std::cout<<"RelativeSOC3: "<<RelativeSOC3<<std::endl; // std::cout<<"RelativeSOC4: "<<RelativeSOC4<<std::endl; // std::cout<<"AbsoluteSOC1: "<<AbsoluteSOC1<<std::endl; // std::cout<<"AbsoluteSOC2: "<<AbsoluteSOC2<<std::endl; // std::cout<<"AbsoluteSOC3: "<<AbsoluteSOC3<<std::endl; // std::cout<<"AbsoluteSOC4: "<<AbsoluteSOC4<<std::endl; // std::cout<<"Temp1: "<<Temp1<<std::endl; // std::cout<<"Temp2: "<<Temp2<<std::endl; // std::cout<<"Temp3: "<<Temp3<<std::endl; // std::cout<<"Temp4: "<<Temp4<<std::endl; } rev_buf.clear(); } } void sendrev::Package_IVAM_Car_vlvr(double &cmd_vl, double &cmd_vr,std::vector<unsigned char> &return_cmd) { double send_vl = cmd_vl + 20.0; double send_vr = cmd_vr + 20.0; std::vector<unsigned char> command; //std::cout<<"send_vl: "<<send_vl<<std::endl; //std::cout<<"send_vr: "<<send_vr<<std::endl; int integer_vl = (int(send_vl)); int float_vl = ( int((send_vl - double(integer_vl))*1000 )); int integer_vr = (int(send_vr)); int float_vr = ( int((send_vr - double(integer_vr))*1000 )); int HighByte_integer_vl = integer_vl/256; int LowByte_integer_vl = integer_vl%256; int HighByte_float_vl = float_vl/256; int LowByte_float_vl = float_vl%256; int HighByte_integer_vr = integer_vr/256; int LowByte_integer_vr = integer_vr%256; int HighByte_float_vr = float_vr/256; int LowByte_float_vr = float_vr%256; command.push_back('S'); command.push_back('T'); command.push_back(HighByte_integer_vl); command.push_back(LowByte_integer_vl); command.push_back(HighByte_float_vl); command.push_back(LowByte_float_vl); command.push_back(HighByte_integer_vr); command.push_back(LowByte_integer_vr); command.push_back(HighByte_float_vr); command.push_back(LowByte_float_vr); command.push_back('E'); command.push_back('N'); command.push_back('D'); return_cmd = command; } void sendrev::Package_IVAM_Car_vw(double &cmd_v, double &cmd_w,std::vector<unsigned char> &return_cmd) { // std::cout<<"cmd_v: "<<cmd_v<<std::endl; // std::cout<<"cmd_w: "<<cmd_w<<std::endl; double send_v = cmd_v + 20.0; double send_w = cmd_w + 20.0; std::vector<unsigned char> command; // std::cout<<"send_v: "<<send_v<<std::endl; // std::cout<<"send_w: "<<send_w<<std::endl; int integer_v = (int(send_v)); int float_v = ( int((send_v - double(integer_v))*1000 )); int integer_w = (int(send_w)); int float_w = ( int((send_w - double(integer_w))*1000 )); int HighByte_integer_v = integer_v/256; int LowByte_integer_v = integer_v%256; int HighByte_float_v = float_v/256; int LowByte_float_v = float_v%256; int HighByte_integer_w = integer_w/256; int LowByte_integer_w = integer_w%256; int HighByte_float_w = float_w/256; int LowByte_float_w = float_w%256; command.push_back('S'); command.push_back('T'); command.push_back(HighByte_integer_v); command.push_back(LowByte_integer_v); command.push_back(HighByte_float_v); command.push_back(LowByte_float_v); command.push_back(HighByte_integer_w); command.push_back(LowByte_integer_w); command.push_back(HighByte_float_w); command.push_back(LowByte_float_w); command.push_back('E'); command.push_back('N'); command.push_back('D'); return_cmd = command; } void sendrev::Package_Boling_smallgray(double &cmd_vl, double &cmd_vr,std::vector<unsigned char> &return_cmd) { double send_vl = -1*cmd_vl + 20.0; double send_vr = -1*cmd_vr + 20.0; std::vector<unsigned char> command; std::cout<<"send_vl: "<<send_vl<<std::endl; std::cout<<"send_vr: "<<send_vr<<std::endl; int integer_vl = (int(send_vl)); int float_vl = ( int((send_vl - double(integer_vl))*1000 )); int integer_vr = (int(send_vr)); int float_vr = ( int((send_vr - double(integer_vr))*1000 )); int HighByte_integer_vl = integer_vl/128; int LowByte_integer_vl = integer_vl%128; int HighByte_float_vl = float_vl/128; int LowByte_float_vl = float_vl%128; int HighByte_integer_vr = integer_vr/128; int LowByte_integer_vr = integer_vr%128; int HighByte_float_vr = float_vr/128; int LowByte_float_vr = float_vr%128; command.push_back('S'); command.push_back('A'); command.push_back(HighByte_integer_vr); command.push_back(LowByte_integer_vr); command.push_back(HighByte_float_vr); command.push_back(LowByte_float_vr); command.push_back(HighByte_integer_vl); command.push_back(LowByte_integer_vl); command.push_back(HighByte_float_vl); command.push_back(LowByte_float_vl); command.push_back('E'); command.push_back('N'); command.push_back('D'); return_cmd = command; }
[ "amy0937968@gmail.com" ]
amy0937968@gmail.com
7f330376632d714af8f4914dc412e5559e85f241
50d559c1c3d1d50960ff3cddbdc7745de69dfa83
/Prata_S/Prata_S/MyList.cpp
e2a39eb175094c7fe2b6b164760e3f5c7032ec44
[]
no_license
phoenix76/teach_projects
467a562d223ab3e8815581f003a911dbab707a09
fface4b34b00e477d70ec0e3a296aa6e9fbca221
refs/heads/master
2021-01-10T06:18:14.683697
2016-03-27T14:39:54
2016-03-27T14:39:54
53,208,350
0
0
null
null
null
null
UTF-8
C++
false
false
527
cpp
#include "MyList.h" #include <iostream> void CMyList::operator+(Item *p) { if(top < 9) { stack[top] = p; top++; } else std::cout << "List is full.\n"; } void CMyList::operator-() { if(top != 0) { stack[top] = nullptr; top--; } else std::cout << "List is empty.\n"; } Item *CMyList::GetItem(unsigned short n) { if(top >= n - 1) return stack[n - 1]; else std::cout << "This element is not found.\n"; } bool CMyList::IsEmpty() const { return top == 0; } bool CMyList::IsFull() const { return top == 9; }
[ "djokerxx2013@mail.ru" ]
djokerxx2013@mail.ru
0a86cbb2d56b2266b722d922f03a7bd411701aa4
41d6b7e3b34b10cc02adb30c6dcf6078c82326a3
/src/plugins/liznoo/platform/upower/upowerconnector.h
7e56426fe696e33c55efae513fbe7746128cef7d
[ "BSL-1.0" ]
permissive
ForNeVeR/leechcraft
1c84da3690303e539e70c1323e39d9f24268cb0b
384d041d23b1cdb7cc3c758612ac8d68d3d3d88c
refs/heads/master
2020-04-04T19:08:48.065750
2016-11-27T02:08:30
2016-11-27T02:08:30
2,294,915
1
0
null
null
null
null
UTF-8
C++
false
false
2,177
h
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #pragma once #include <memory> #include "../../batteryinfo.h" #include "../common/connectorbase.h" namespace LeechCraft { namespace Liznoo { namespace UPower { class UPowerConnector : public ConnectorBase { Q_OBJECT public: UPowerConnector (QObject* = nullptr); private slots: void handleGonnaSleep (); void enumerateDevices (); void requeryDevice (const QString&); signals: void batteryInfoUpdated (Liznoo::BatteryInfo); }; using UPowerConnector_ptr = std::shared_ptr<UPowerConnector>; } } }
[ "0xd34df00d@gmail.com" ]
0xd34df00d@gmail.com
7598bbefe60cc9a111dc6718c9093299d4bcd10c
db035b36bb9c99ea66bda5fe5ff3a2b48843ff69
/Express1.cpp
21f6376cd4640c2837bf924810237550ee79c17c
[]
no_license
lockon57/No.4_24-point
abb4b078cee9295b6f05ac17dcda6a8619f602df
f2c9b688da3d53c6d34e9cb7431db89865cda27d
refs/heads/master
2021-01-19T10:29:06.823677
2017-02-16T13:21:03
2017-02-16T13:21:03
82,182,999
0
0
null
null
null
null
GB18030
C++
false
false
7,645
cpp
// Function.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "math.h" #include "express.h" #include <ctype.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif IMPLEMENT_SERIAL(CExpression, CObject, 0) void CExpression::elibmem ( arbore a) { if (a==NULL) return; if (a->left!=NULL) elibmem(a->left); if (a->right!=NULL) elibmem(a->right); if (a->operatie == '`') delete a->valoarestr; delete a; } CExpression::CExpression() { m_Arbore = NULL; m_definitie = ""; pozitie = 0; m_pvariabile = NULL; } CExpression::CExpression(CMapVariabile * vars) { m_Arbore = NULL; m_definitie = ""; pozitie = 0; m_pvariabile = vars; } CExpression::~CExpression() { elibmem (m_Arbore); } void CExpression::Serialize(CArchive & ar) { if (ar.IsStoring()) { // TODO: add storing code here ar << m_definitie; } else { // TODO: add loading code here ar >> m_definitie; m_Arbore = NULL; pozitie = 0; UpdateArbore(); } } int CExpression::UpdateArbore() { if (m_definitie.IsEmpty()) return 0; elibmem(m_Arbore); m_Arbore = NULL; pozitie = 0; m_Arbore = expresie(); if (m_definitie[pozitie]!='\0') { elibmem(m_Arbore); m_Arbore = NULL; } if (m_Arbore == NULL) return pozitie; else return -1; } CExpression::arbore CExpression::expresie() { arbore nod; arbore arb1 = termen(); arbore arb2; if (arb1 == NULL) return NULL; while ((m_definitie[pozitie]=='-') || (m_definitie[pozitie]=='+')) { nod=new NOD; nod->left=arb1; nod->operatie=m_definitie[pozitie]; pozitie++; arb2 = termen(); nod->right=arb2; if (arb2 == NULL) { elibmem(nod); return NULL; } arb1 = nod; } return arb1; } CExpression::arbore CExpression::termen() { arbore nod; arbore arb1 = putere(); arbore arb2; if (arb1 == NULL) return NULL; while ((m_definitie[pozitie]=='*') || (m_definitie[pozitie]=='/')) { nod=new NOD; nod->left=arb1; nod->operatie=m_definitie[pozitie]; pozitie++; arb2 = putere(); nod->right=arb2; if (arb2 == NULL) { elibmem(nod); return NULL; } arb1 = nod; } return arb1; } CExpression::arbore CExpression::putere() { arbore nod = NULL; arbore arb1 = logicalOp(); arbore arb2; if (arb1 == NULL) return NULL; while (m_definitie[pozitie]=='^') { nod=new NOD; nod->left=arb1; nod->operatie=m_definitie[pozitie]; pozitie++; arb2 = logicalOp(); nod->right=arb2; if (arb2 == NULL) { elibmem(nod); return NULL; } arb1 = nod; } return arb1; } CExpression::arbore CExpression::factor() { arbore nod = NULL,nod2 = NULL,left = NULL; while(m_definitie[pozitie] == ' ' && m_definitie[pozitie] != '\0') pozitie++; if (m_definitie[pozitie]=='-') { nod = new NOD; left = new NOD; left->right=NULL; left->left=NULL; left->operatie='@'; left->valoare=-1; nod->left=left; nod->operatie='*'; pozitie++; nod->right = expresie(); if (nod->right == NULL) return NULL; return nod; } if (m_definitie[pozitie]=='(') { pozitie++; nod = expresie(); if (nod == NULL) return NULL; if (m_definitie[pozitie]!=')') { elibmem(nod); return NULL; } pozitie++; return nod; } else if (m_definitie[pozitie]=='|') { pozitie++; nod2 = expresie(); if (nod2 == NULL) return NULL; if (m_definitie[pozitie]!='|') { elibmem(nod); return NULL; } nod = new NOD; nod->left=nod2; nod->right=NULL; nod->operatie='|'; pozitie++; return nod; } else return identificator(); return nod; } CExpression::arbore CExpression::identificator() { int poz; arbore nod = NULL,nod2 = NULL; arbore result = NULL; poz=pozitie; SkipSpaces(); if (m_definitie[pozitie]=='\0') result = NULL; if (isdigit(m_definitie[pozitie])) { while ((isdigit(m_definitie[pozitie]) || (m_definitie[pozitie]=='.'))) pozitie++; nod = new NOD; nod->left = NULL; nod->right = NULL; nod->operatie = '@'; nod->valoare = atof(m_definitie.Mid(poz,pozitie-poz)); result = nod; } if (isalpha(m_definitie[pozitie])) {/*此处可添加代码以处理函数*/} SkipSpaces(); return result; } int CExpression::ChangeExpression(CString & expresie) { m_definitie = expresie + '\0' + '\0'; return UpdateArbore(); } int code; int CExpression::Value(double& valoare) { code=0; if (m_Arbore == NULL) return -1; valoare=vexp(m_Arbore); return (code); } double CExpression::vexp ( arbore a ) { double v; if (a->operatie==NULL) {code=10;return 0;} switch(a->operatie) { case '+' : return( vexp(a->left)+vexp(a->right) ); case '-' : return( vexp(a->left)-vexp(a->right) ); case '*' : return( vexp(a->left)*vexp(a->right) ); case '/' : v=vexp(a->right) ; if (v==0) {code=DIVISION_BY_0;return -vexp(a->left)/0.001;} else return(vexp(a->left)/v); case 153 : v=vexp(a->left) ; if (v<0) {code=INVALID_DOMAIN;return 0;} else return(sqrt(v)); case 154 : v=vexp(a->left) ; if (v<=0) {code=INVALID_DOMAIN;return 0;} else return(log(v)); case '|' : return(fabs(vexp(a->left))); case '@' : return (a->valoare); //logical operations evaluation case '<' : return( vexp(a->left)<vexp(a->right) ); case '>' : return( vexp(a->left)>vexp(a->right) ); case '!' : return(!vexp(a->right)) ; default : { if (m_pvariabile==NULL) { code=UNDEFINED_VARIABLE; return 0; } CValue *valoare; if (!m_pvariabile->Lookup(*a->valoarestr,valoare)) { code=UNDEFINED_VARIABLE; return 0; } else return valoare->GetValue(); } } } CExpression::arbore CExpression::GetArbore() { return m_Arbore; } CExpression::CExpression(CExpression & expresie) { *this = expresie; } CExpression::arbore CExpression::CloneTree() { return clone(m_Arbore); } void CExpression::AtachVariables(CMapVariabile * vars) { m_pvariabile = vars; } CExpression::arbore CExpression::clone(arbore arb) { if (arb == NULL) return NULL; arbore clonArb = new NOD; *clonArb = *arb; clonArb->left = clone(arb->left); clonArb->right = clone(arb->right); return clonArb; } CExpression& CExpression::operator=(CExpression &expr) { m_definitie = expr.m_definitie; m_pvariabile = expr.m_pvariabile; pozitie = 0; m_Arbore = expr.CloneTree(); return *this; } void CExpression::SkipSpaces() { while (m_definitie[pozitie]==' ' && m_definitie[pozitie]!='\0') pozitie ++; } CExpression::arbore CExpression::logicalOp() { arbore nod; arbore arb1 = sgOp(); arbore arb2; if (arb1 == NULL) return NULL; while ((m_definitie[pozitie]=='<') || (m_definitie[pozitie]=='>')) { nod=new NOD; nod->left=arb1; nod->operatie=m_definitie[pozitie]; pozitie++; arb2 = sgOp(); nod->right=arb2; if (arb2 == NULL) { elibmem(nod); return NULL; } arb1 = nod; } return arb1; } CExpression::arbore CExpression::sgOp() { arbore nod = NULL; arbore arb2; if ((m_definitie[pozitie]=='!')) { nod=new NOD; nod->left=NULL; nod->operatie=m_definitie[pozitie]; pozitie++; arb2 = sgOp(); nod->right=arb2; if (arb2 == NULL) { elibmem(nod); return NULL; } } else nod = factor(); return nod; }
[ "wushiqi@wushiqitekiMacBook-Pro.local" ]
wushiqi@wushiqitekiMacBook-Pro.local
b003cd545565416ea20b3ef559c53d30f262aa64
7cdbac97437657022daa0b97b27b9fa3dea2a889
/engine/source/memory/dataChunker.cc
d311c9693eb0a604836565304e390908bbb998b5
[]
no_license
lineCode/3SS
36617d2b6e35b913e342d26fd2be238dbb4b4f3f
51c702bbaee8239c02db58f6c974b2c6cd2271d1
refs/heads/master
2020-09-30T18:43:27.358305
2015-03-04T00:14:23
2015-03-04T00:14:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,270
cc
//----------------------------------------------------------------------------- // Torque // Copyright GarageGames, LLC 2011 //----------------------------------------------------------------------------- #include "platform/platform.h" #include "dataChunker.h" //---------------------------------------------------------------------------- DataChunker::DataChunker(S32 size) { chunkSize = size; curBlock = new DataBlock(size); curBlock->next = NULL; curBlock->curIndex = 0; } DataChunker::~DataChunker() { freeBlocks(); } void *DataChunker::alloc(S32 size) { AssertFatal(size <= chunkSize, "Data chunk too large."); if(!curBlock || size + curBlock->curIndex > chunkSize) { DataBlock *temp = new DataBlock(chunkSize); temp->next = curBlock; temp->curIndex = 0; curBlock = temp; } void *ret = curBlock->data + curBlock->curIndex; curBlock->curIndex += (size + 3) & ~3; // dword align return ret; } DataChunker::DataBlock::DataBlock(S32 size) { data = new U8[size]; } DataChunker::DataBlock::~DataBlock() { delete[] data; } void DataChunker::freeBlocks() { while(curBlock) { DataBlock *temp = curBlock->next; delete curBlock; curBlock = temp; } }
[ "kylem@garagegames.com" ]
kylem@garagegames.com
409c8964b306b25cdfc2a968615646c2b9121cd4
ca0ce7156735133821d241fb2215f2a2f319af4e
/lib/Core/MemoryManager.cpp
efbfb9134d1675c5453b096ecfd1c8089c256acb
[ "NCSA" ]
permissive
Jokerzyq/klee-zyq
45a10be089a51849a9e9da1b65aa07d119ac4a9c
73fafb25c27a8c2be75f877bb2ebfcfab0cf1bdc
refs/heads/master
2021-04-09T15:32:36.961996
2016-10-25T09:03:11
2016-10-25T09:03:11
61,523,208
0
0
null
null
null
null
UTF-8
C++
false
false
2,403
cpp
//===-- MemoryManager.cpp -------------------------------------------------===// // // The KLEE Symbolic Virtual Machine // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Common.h" #include "CoreStats.h" #include "Memory.h" #include "MemoryManager.h" #include "klee/ExecutionState.h" #include "klee/Expr.h" #include "klee/Solver.h" #include "llvm/Support/CommandLine.h" using namespace klee; /***/ MemoryManager::~MemoryManager() { while (!objects.empty()) { MemoryObject *mo = *objects.begin(); if (!mo->isFixed) free((void *)mo->address); objects.erase(mo); delete mo; } } //cyj: 分配一块size大小的memory, 地址为address; 新建一个MemoryObject, 对其address/size赋值 MemoryObject *MemoryManager::allocate(uint64_t size, bool isLocal, bool isGlobal, const llvm::Value *allocSite) { if (size>10*1024*1024) klee_warning_once(0, "Large alloc: %u bytes. KLEE may run out of memory.", (unsigned) size); uint64_t address = (uint64_t) (unsigned long) malloc((unsigned) size); if (!address) return 0; ++stats::allocations; MemoryObject *res = new MemoryObject(address, size, isLocal, isGlobal, false, allocSite, this); objects.insert(res); return res; } MemoryObject *MemoryManager::allocateFixed(uint64_t address, uint64_t size, const llvm::Value *allocSite) { #ifndef NDEBUG for (objects_ty::iterator it = objects.begin(), ie = objects.end(); it != ie; ++it) { MemoryObject *mo = *it; if (address+size > mo->address && address < mo->address+mo->size) klee_error("Trying to allocate an overlapping object"); } #endif ++stats::allocations; MemoryObject *res = new MemoryObject(address, size, false, true, true, allocSite, this); objects.insert(res); return res; } void MemoryManager::deallocate(const MemoryObject *mo) { assert(0); } void MemoryManager::markFreed(MemoryObject *mo) { if (objects.find(mo) != objects.end()) { if (!mo->isFixed) free((void *)mo->address); objects.erase(mo); } }
[ "Jokerzyq@github.com" ]
Jokerzyq@github.com
de9e034a4812c25c52526c7eaaaeb636abdc40fb
327befeb9bbb8aee75c24c5ef78d859f35428ebd
/test/cpp/interop/reconnect_interop_server.cc
92b5bf4dfaa2e5115598b4d450f5595ffcc50473
[ "BSD-3-Clause" ]
permissive
CharaD7/grpc
33b64f8eabf09014b1bc739b77809aed7a058633
062ad488881839d2637b7a191ade5b87346b4597
refs/heads/master
2023-07-08T19:36:00.065815
2016-01-04T17:28:15
2016-01-04T17:28:15
49,012,756
1
0
BSD-3-Clause
2023-07-06T01:32:59
2016-01-04T17:39:11
C
UTF-8
C++
false
false
6,257
cc
/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <signal.h> #include <unistd.h> #include <condition_variable> #include <memory> #include <mutex> #include <sstream> #include <gflags/gflags.h> #include <grpc/grpc.h> #include <grpc/support/log.h> #include <grpc++/server.h> #include <grpc++/server_builder.h> #include <grpc++/server_context.h> #include "test/core/util/reconnect_server.h" #include "test/cpp/util/test_config.h" #include "test/proto/test.grpc.pb.h" #include "test/proto/empty.grpc.pb.h" #include "test/proto/messages.grpc.pb.h" DEFINE_int32(control_port, 0, "Server port for controlling the server."); DEFINE_int32(retry_port, 0, "Server port for raw tcp connections. All incoming " "connections will be closed immediately."); using grpc::Server; using grpc::ServerBuilder; using grpc::ServerContext; using grpc::ServerCredentials; using grpc::ServerReader; using grpc::ServerReaderWriter; using grpc::ServerWriter; using grpc::SslServerCredentialsOptions; using grpc::Status; using grpc::testing::Empty; using grpc::testing::ReconnectService; using grpc::testing::ReconnectInfo; static bool got_sigint = false; class ReconnectServiceImpl : public ReconnectService::Service { public: explicit ReconnectServiceImpl(int retry_port) : retry_port_(retry_port), serving_(false), server_started_(false), shutdown_(false) { reconnect_server_init(&tcp_server_); } ~ReconnectServiceImpl() { if (server_started_) { reconnect_server_destroy(&tcp_server_); } } void Poll(int seconds) { reconnect_server_poll(&tcp_server_, seconds); } Status Start(ServerContext* context, const Empty* request, Empty* response) { bool start_server = true; std::unique_lock<std::mutex> lock(mu_); while (serving_ && !shutdown_) { cv_.wait(lock); } if (shutdown_) { return Status(grpc::StatusCode::UNAVAILABLE, "shutting down"); } serving_ = true; if (server_started_) { start_server = false; } else { server_started_ = true; } lock.unlock(); if (start_server) { reconnect_server_start(&tcp_server_, retry_port_); } else { reconnect_server_clear_timestamps(&tcp_server_); } return Status::OK; } Status Stop(ServerContext* context, const Empty* request, ReconnectInfo* response) { // extract timestamps and set response Verify(response); reconnect_server_clear_timestamps(&tcp_server_); std::lock_guard<std::mutex> lock(mu_); serving_ = false; cv_.notify_one(); return Status::OK; } void Verify(ReconnectInfo* response) { double expected_backoff = 1000.0; const double kTransmissionDelay = 100.0; const double kBackoffMultiplier = 1.6; const double kJitterFactor = 0.2; const int kMaxBackoffMs = 120 * 1000; bool passed = true; for (timestamp_list* cur = tcp_server_.head; cur && cur->next; cur = cur->next) { double backoff = gpr_time_to_millis( gpr_time_sub(cur->next->timestamp, cur->timestamp)); double min_backoff = expected_backoff * (1 - kJitterFactor); double max_backoff = expected_backoff * (1 + kJitterFactor); if (backoff < min_backoff - kTransmissionDelay || backoff > max_backoff + kTransmissionDelay) { passed = false; } response->add_backoff_ms(static_cast<gpr_int32>(backoff)); expected_backoff *= kBackoffMultiplier; expected_backoff = expected_backoff > kMaxBackoffMs ? kMaxBackoffMs : expected_backoff; } response->set_passed(passed); } void Shutdown() { std::lock_guard<std::mutex> lock(mu_); shutdown_ = true; cv_.notify_all(); } private: int retry_port_; reconnect_server tcp_server_; bool serving_; bool server_started_; bool shutdown_; std::mutex mu_; std::condition_variable cv_; }; void RunServer() { std::ostringstream server_address; server_address << "0.0.0.0:" << FLAGS_control_port; ReconnectServiceImpl service(FLAGS_retry_port); ServerBuilder builder; builder.RegisterService(&service); builder.AddListeningPort(server_address.str(), grpc::InsecureServerCredentials()); std::unique_ptr<Server> server(builder.BuildAndStart()); gpr_log(GPR_INFO, "Server listening on %s", server_address.str().c_str()); while (!got_sigint) { service.Poll(5); } service.Shutdown(); } static void sigint_handler(int x) { got_sigint = true; } int main(int argc, char** argv) { grpc::testing::InitTest(&argc, &argv, true); signal(SIGINT, sigint_handler); GPR_ASSERT(FLAGS_control_port != 0); GPR_ASSERT(FLAGS_retry_port != 0); RunServer(); return 0; }
[ "yangg@google.com" ]
yangg@google.com
9097742f1d9078adb110ec2da83fc214d58c5d40
209eaef38213edae38c0cf05a89416437e916657
/vt/src/vt/TileLabel.h
9516184d78f01afb3cf150b4ff19f9aa0151e2b6
[ "BSD-3-Clause" ]
permissive
farfromrefug/mobile-carto-libs
0d0ae81b0742f026726974fce53f6f979fc79dc5
c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df
refs/heads/master
2023-07-29T01:44:54.131553
2021-06-05T13:23:38
2021-06-05T13:23:38
214,130,740
0
0
BSD-3-Clause
2019-10-10T08:38:51
2019-10-10T08:38:50
null
UTF-8
C++
false
false
3,770
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_TILELABEL_H_ #define _CARTO_VT_TILELABEL_H_ #include "TileId.h" #include "Color.h" #include "Transform.h" #include "Bitmap.h" #include "Font.h" #include "ViewState.h" #include "VertexArray.h" #include "Styles.h" #include <memory> #include <optional> #include <array> #include <list> #include <vector> #include <limits> #include <algorithm> namespace carto { namespace vt { class TileLabel final { public: struct Style { LabelOrientation orientation; ColorFunction colorFunc; FloatFunction sizeFunc; ColorFunction haloColorFunc; FloatFunction haloRadiusFunc; bool autoflip; float scale; float ascent; float descent; std::optional<Transform> transform; std::shared_ptr<const GlyphMap> glyphMap; explicit Style(LabelOrientation orientation, ColorFunction colorFunc, FloatFunction sizeFunc, ColorFunction haloColorFunc, FloatFunction haloRadiusFunc, bool autoflip, float scale, float ascent, float descent, const std::optional<Transform>& transform, std::shared_ptr<const GlyphMap> glyphMap) : orientation(orientation), colorFunc(std::move(colorFunc)), sizeFunc(std::move(sizeFunc)), haloColorFunc(std::move(haloColorFunc)), haloRadiusFunc(std::move(haloRadiusFunc)), autoflip(autoflip), scale(scale), ascent(ascent), descent(descent), transform(transform), glyphMap(std::move(glyphMap)) { } }; struct PlacementInfo { int priority; float minimumGroupDistance; explicit PlacementInfo(int priority, float minimumGroupDistance) : priority(priority), minimumGroupDistance(minimumGroupDistance) { } }; explicit TileLabel(const TileId& tileId, int layerIndex, long long localId, long long globalId, long long groupId, std::vector<Font::Glyph> glyphs, std::optional<cglib::vec2<float>> position, std::vector<cglib::vec2<float>> vertices, std::shared_ptr<const Style> style, const PlacementInfo& placementInfo) : _tileId(tileId), _layerIndex(layerIndex), _localId(localId), _globalId(globalId), _groupId(groupId), _glyphs(std::move(glyphs)), _position(std::move(position)), _vertices(std::move(vertices)), _style(std::move(style)), _placementInfo(placementInfo) { } const TileId& getTileId() const { return _tileId; } int getLayerIndex() const { return _layerIndex; } long long getLocalId() const { return _localId; } long long getGlobalId() const { return _globalId; } long long getGroupId() const { return _groupId; } const std::vector<Font::Glyph>& getGlyphs() const { return _glyphs; } const std::optional<cglib::vec2<float>>& getPosition() const { return _position; } const std::vector<cglib::vec2<float>>& getVertices() const { return _vertices; } const std::shared_ptr<const Style>& getStyle() const { return _style; } const PlacementInfo& getPlacementInfo() const { return _placementInfo; } std::size_t getResidentSize() const { return 16 + sizeof(TileLabel); } private: const TileId _tileId; const int _layerIndex; const long long _localId; const long long _globalId; const long long _groupId; const std::vector<Font::Glyph> _glyphs; const std::optional<cglib::vec2<float>> _position; const std::vector<cglib::vec2<float>> _vertices; const std::shared_ptr<const Style> _style; const PlacementInfo _placementInfo; }; } } #endif
[ "mark.tehver@gmail.com" ]
mark.tehver@gmail.com
6c6360f6b7577b4eeab79642be751784cfcf2793
ac227cc22d5f5364e5d029a2cef83816a6954590
/applications/physbam/physbam-lib/Public_Library/PhysBAM_Dynamics/Motion/ATTACHMENT_FRAME_CONTROL_SET.h
07454dcfca278f4084e3b49a016de4b3334c1161
[ "BSD-3-Clause" ]
permissive
schinmayee/nimbus
597185bc8bac91a2480466cebc8b337f5d96bd2e
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
refs/heads/master
2020-03-11T11:42:39.262834
2018-04-18T01:28:23
2018-04-18T01:28:23
129,976,755
0
0
BSD-3-Clause
2018-04-17T23:33:23
2018-04-17T23:33:23
null
UTF-8
C++
false
false
4,748
h
//##################################################################### // Copyright 2004-2007, Andrew Selle, Eftychios Sifakis. // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### // Class ATTACHMENT_FRAME_CONTROL_SET //##################################################################### #ifndef __ATTACHMENT_FRAME_CONTROL_SET__ #define __ATTACHMENT_FRAME_CONTROL_SET__ #include <PhysBAM_Tools/Arrays/ARRAY.h> #include <PhysBAM_Tools/Read_Write/Utilities/FILE_UTILITIES.h> #include <PhysBAM_Tools/Vectors/TWIST.h> #include <PhysBAM_Solids/PhysBAM_Solids/Forces_And_Torques/SOLIDS_FORCES.h> #include <PhysBAM_Dynamics/Motion/FACE_CONTROL_SET.h> #include <PhysBAM_Dynamics/Motion/QUASI_RIGID_TRANSFORM_3D.h> namespace PhysBAM{ template<class T> class ATTACHMENT_FRAME_CONTROL_SET:public FACE_CONTROL_SET<T> { typedef VECTOR<T,3> TV; public: typedef typename FACE_CONTROL_SET<T>::TYPE T_TYPE; using FACE_CONTROL_SET<T>::ATTACHMENT_FRAME; QUASI_RIGID_TRANSFORM_3D<T> cranium_transform,jaw_transform,cranium_transform_save,jaw_transform_save; ARRAY<bool> coefficient_active; ARRAY<TV>& X; ARRAY<TV> X_save; SOLIDS_FORCES<TV>* muscle_force; ARRAY<ARRAY<int> >& attached_nodes; int jaw_attachment_index; T rigidity_penalty_coefficient,jaw_constraint_penalty_coefficient; TV jaw_midpoint,jaw_normal,jaw_axis,jaw_front; T jaw_axis_length,jaw_sliding_length,max_opening_angle; FRAME<TV> cranium_frame_save,jaw_frame_save; ATTACHMENT_FRAME_CONTROL_SET(ARRAY<TV>& X_input,ARRAY<ARRAY<int> >& attached_nodes_input,const int jaw_attachment_index_input); ~ATTACHMENT_FRAME_CONTROL_SET(); FRAME<TV> Cranium_Frame() {return cranium_transform.Frame()*cranium_frame_save;} FRAME<TV> Jaw_Frame() {return QUASI_RIGID_TRANSFORM_3D<T>::Composite_Transform(cranium_transform,jaw_transform).Frame()*jaw_frame_save;} //##################################################################### int Size() const PHYSBAM_OVERRIDE; T_TYPE Type() const PHYSBAM_OVERRIDE; T operator()(const int control_id) const PHYSBAM_OVERRIDE; T& operator()(const int control_id) PHYSBAM_OVERRIDE; T Identity(const int control_id) const PHYSBAM_OVERRIDE; void Maximal_Controls() PHYSBAM_OVERRIDE; bool Control_Active(const int control_id) const PHYSBAM_OVERRIDE; bool& Control_Active(const int control_id) PHYSBAM_OVERRIDE; bool Positions_Determined_Kinematically(const int control_id) const PHYSBAM_OVERRIDE; void Force_Derivative(ARRAY<TV>& dFdl,ARRAY<TWIST<TV> >& dFrdl,const int control_id) const PHYSBAM_OVERRIDE; void Position_Derivative(ARRAY<TV>& dXdl,const int control_id) const PHYSBAM_OVERRIDE; void Set_Attachment_Positions(ARRAY<TV>&X) const PHYSBAM_OVERRIDE; void Save_Controls() PHYSBAM_OVERRIDE; void Kinematically_Update_Positions(ARRAY<TV>&X) const PHYSBAM_OVERRIDE; void Kinematically_Update_Jacobian(ARRAY<TV>&dX) const PHYSBAM_OVERRIDE; T Penalty() const PHYSBAM_OVERRIDE; T Penalty_Gradient(const int control_id) const PHYSBAM_OVERRIDE; T Penalty_Hessian(const int control_id1,const int control_id2) const PHYSBAM_OVERRIDE; T Jaw_Constraint_Penalty() const; T Jaw_Constraint_Penalty_Gradient(const int control_id) const; T Jaw_Constraint_Penalty_Hessian(const int control_id1,const int control_id2) const; void Read_Jaw_Joint_From_File(const STREAM_TYPE& stream_type,const std::string& filename); void Write_Jaw_Joint_To_File(const STREAM_TYPE& stream_type,const std::string& filename) const; void Read_Configuration(const STREAM_TYPE& stream_type,std::istream& input_stream); void Write_Configuration(const STREAM_TYPE& stream_type,std::ostream& output_stream) const; void Set_Original_Attachment_Configuration(const FRAME<TV>& cranium_frame_input,const FRAME<TV>& jaw_frame_input); void Project_Parameters_To_Allowable_Range(const bool active_controls_only) PHYSBAM_OVERRIDE; void Set_From_Generalized_Coordinates(const T left_sliding_parameter,const T right_sliding_parameter,const T opening_angle); T Opening_Angle() const; void Increment_Opening_Angle(const T angle); T Left_Condyle_Sliding_Parameter() const; T Right_Condyle_Sliding_Parameter() const; void Interpolate(const T interpolation_fraction) PHYSBAM_OVERRIDE; void Scale(const T scale) PHYSBAM_OVERRIDE; T Distance(const ARRAY<T>& weights,int base) PHYSBAM_OVERRIDE; void Print_Diagnostics(std::ostream& output) const PHYSBAM_OVERRIDE; //##################################################################### }; } #endif
[ "quhang@stanford.edu" ]
quhang@stanford.edu
0cf8845bc2bcaa7679e26ee126c5a09d21ba5a59
aa9d5a1191a44d0703e72a446d049be2dab45d0c
/cpp/test/rpc/client_ssl_test.cpp
b2ee3cc0283bb600d056c86e4280884f3271eb15
[ "BSD-3-Clause" ]
permissive
lkairies/xtreemfs
f3762be5039b24d48a99209167308da38c76f879
37b02b2aa4ea746828462fd98b8343548753ba27
refs/heads/master
2021-01-18T00:29:11.564556
2014-12-11T13:27:17
2014-12-11T13:27:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
34,735
cpp
/* * Copyright (c) 2014 by Robert Schmidtke, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ #ifdef HAS_OPENSSL #include <gtest/gtest.h> #include <boost/algorithm/string/predicate.hpp> #include <boost/scoped_ptr.hpp> #include <boost/thread.hpp> #include <cerrno> #include <fcntl.h> #include <fstream> #include <stdio.h> #include <stdexcept> #include <string> #include <openssl/opensslv.h> #include "libxtreemfs/client.h" #include "libxtreemfs/client_implementation.h" #include "libxtreemfs/options.h" #include "libxtreemfs/xtreemfs_exception.h" #include "pbrpc/RPC.pb.h" #include "util/logging.h" /** * The working directory is assumed to be cpp/build. */ using namespace xtreemfs::pbrpc; using namespace xtreemfs::util; namespace xtreemfs { namespace rpc { /** * Represents a DIR, MRC or OSD started via command line. Not the stripped * down test environment services. */ class ExternalService { public: ExternalService( std::string service_class, std::string config_file_name, std::string log_file_name, std::string startup_phrase) : service_class_(service_class), config_file_name_(config_file_name), log_file_name_(log_file_name), startup_phrase_(startup_phrase), java_home_(""), classpath_(""), argv_(NULL), service_pid_(-1) { char *java_home = getenv("JAVA_HOME"); if (java_home == NULL || (java_home_ = java_home).empty()) { if (Logging::log->loggingActive(LEVEL_WARN)) { Logging::log->getLog(LEVEL_WARN) << "JAVA_HOME is empty." << std::endl; } } if (!boost::algorithm::ends_with(java_home_, "/")) { java_home_ += "/"; } classpath_ = "../../java/servers/dist/XtreemFS.jar"; classpath_ += ":../../java/foundation/dist/Foundation.jar"; classpath_ += ":../../java/flease/dist/Flease.jar"; classpath_ += ":../../java/lib/*"; } int JavaMajorVersion() { // java -version prints to stderr FILE *pipe = popen((java_home_ + "bin/java -version 2>&1").c_str(), "r"); char buf[256]; std::string output(""); while (!feof(pipe)) { if (fgets(buf, 256, pipe) != NULL) { output += buf; } } pclose(pipe); // Output starts with: java version "1.X.Y_Z" size_t a = output.find('.', 0); size_t b = output.find('.', a + 1); return atoi(output.substr(a + 1, b - a - 1).c_str()); } void Start() { argv_ = new char*[7]; argv_[0] = strdup((java_home_ + "bin/java").c_str()); argv_[1] = strdup("-ea"); argv_[2] = strdup("-cp"); argv_[3] = strdup(classpath_.c_str()); argv_[4] = strdup(service_class_.c_str()); argv_[5] = strdup(config_file_name_.c_str()); argv_[6] = NULL; char *envp[] = { NULL }; service_pid_ = fork(); if (service_pid_ == 0) { /* This block is executed by the child and is blocking. */ // Redirect stdout and stderr to file int log_fd = open(log_file_name_.c_str(), O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); dup2(log_fd, 1); dup2(log_fd, 2); close(log_fd); // execve does not return control upon successful completion. execve((java_home_ + "bin/java").c_str(), argv_, envp); exit(errno); } else { /* This block is executed by the parent. */ // Wait until the child has created the log file. int log_fd = -1; while ((log_fd = open(log_file_name_.c_str(), O_RDONLY)) == -1) ; // Listen to the log file until the startup phrase has occurred. std::string output(""); while (output.find(startup_phrase_) == std::string::npos) { char buffer[1024]; ssize_t n = read(log_fd, buffer, sizeof(buffer)); if (n > 0) { output.append(buffer, n); } else if (n == -1) { throw std::runtime_error( "Could not read log file '" + log_file_name_ + "'."); } } close(log_fd); } } void Shutdown() { if (service_pid_ > 0) { // This block is executed by the parent. Interrupt the child and wait // for completion. kill(service_pid_, 2); waitpid(service_pid_, NULL, 0); service_pid_ = -1; for (size_t i = 0; i < 6; ++i) { free(argv_[i]); } delete[] argv_; } } private: std::string service_class_; std::string config_file_name_; std::string log_file_name_; std::string startup_phrase_; std::string java_home_; std::string classpath_; char **argv_; pid_t service_pid_; }; class ExternalDIR : public ExternalService { public: ExternalDIR(std::string config_file_name, std::string log_file_name) : ExternalService("org.xtreemfs.dir.DIR", config_file_name, log_file_name, "PBRPC Srv 48638 ready") {} }; class ExternalMRC : public ExternalService { public: ExternalMRC(std::string config_file_name, std::string log_file_name) : ExternalService("org.xtreemfs.mrc.MRC", config_file_name, log_file_name, "PBRPC Srv 48636 ready") {} }; class ExternalOSD : public ExternalService { public: ExternalOSD(std::string config_file_name, std::string log_file_name) : ExternalService("org.xtreemfs.osd.OSD", config_file_name, log_file_name, "PBRPC Srv 48640 ready") {} }; enum TestCertificateType { None, kPKCS12, kPEM }; char g_ssl_tls_version_sslv3[] = "sslv3"; char g_ssl_tls_version_ssltls[] = "ssltls"; char g_ssl_tls_version_tlsv1[] = "tlsv1"; #if (BOOST_VERSION > 105300) char g_ssl_tls_version_tlsv11[] = "tlsv11"; char g_ssl_tls_version_tlsv12[] = "tlsv12"; #endif // BOOST_VERSION > 105300 class ClientTest : public ::testing::Test { protected: virtual void SetUp() { initialize_logger(options_.log_level_string, options_.log_file_path, LEVEL_WARN); dir_log_file_name_ = options_.log_file_path + "_dir"; mrc_log_file_name_ = options_.log_file_path + "_mrc"; osd_log_file_name_ = options_.log_file_path + "_osd"; external_dir_.reset(new ExternalDIR(dir_config_file_, dir_log_file_name_)); external_dir_->Start(); external_mrc_.reset(new ExternalMRC(mrc_config_file_, mrc_log_file_name_)); external_mrc_->Start(); external_osd_.reset(new ExternalOSD(osd_config_file_, osd_log_file_name_)); external_osd_->Start(); auth_.set_auth_type(AUTH_NONE); user_credentials_.set_username("client_ssl_test"); user_credentials_.add_groups("client_ssl_test"); options_.retry_delay_s = 5; mrc_url_.ParseURL(kMRC); dir_url_.ParseURL(kDIR); client_.reset(xtreemfs::Client::CreateClient(dir_url_.service_addresses, user_credentials_, options_.GenerateSSLOptions(), options_)); client_->Start(); } virtual void TearDown() { client_->Shutdown(); external_osd_->Shutdown(); external_mrc_->Shutdown(); external_dir_->Shutdown(); } void CreateOpenDeleteVolume(std::string volume_name) { client_->CreateVolume(mrc_url_.service_addresses, auth_, user_credentials_, volume_name); client_->OpenVolume(volume_name, options_.GenerateSSLOptions(), options_); client_->DeleteVolume(mrc_url_.service_addresses, auth_, user_credentials_, volume_name); } size_t count_occurrences_in_file(std::string file_path, std::string s) { std::ifstream in(file_path.c_str(), std::ios_base::in); size_t occurences = 0; while (!in.eof()) { std::string line; std::getline(in, line); occurences += line.find(s) == std::string::npos ? 0 : 1; } in.close(); return occurences; } std::string cert_path(std::string cert) { return "../../tests/certs/client_ssl_test/" + cert; } std::string config_path(std::string config) { return "../../tests/configs/" + config; } boost::scoped_ptr<ExternalDIR> external_dir_; boost::scoped_ptr<ExternalMRC> external_mrc_; boost::scoped_ptr<ExternalOSD> external_osd_; boost::scoped_ptr<xtreemfs::Client> client_; xtreemfs::Options options_; std::string dir_log_file_name_; std::string mrc_log_file_name_; std::string osd_log_file_name_; xtreemfs::Options dir_url_; xtreemfs::Options mrc_url_; std::string dir_config_file_; std::string mrc_config_file_; std::string osd_config_file_; xtreemfs::pbrpc::Auth auth_; xtreemfs::pbrpc::UserCredentials user_credentials_; }; class ClientNoSSLTest : public ClientTest { protected: virtual void SetUp() { dir_config_file_ = config_path("dirconfig_no_ssl.test"); mrc_config_file_ = config_path("mrcconfig_no_ssl.test"); osd_config_file_ = config_path("osdconfig_no_ssl.test"); dir_url_.xtreemfs_url = "pbrpc://localhost:48638/"; mrc_url_.xtreemfs_url = "pbrpc://localhost:48636/"; options_.log_level_string = "DEBUG"; options_.log_file_path = "/tmp/xtreemfs_client_ssl_test_no_ssl"; ClientTest::SetUp(); } virtual void TearDown() { ClientTest::TearDown(); unlink(options_.log_file_path.c_str()); unlink(dir_log_file_name_.c_str()); unlink(mrc_log_file_name_.c_str()); unlink(osd_log_file_name_.c_str()); } }; template<TestCertificateType t> class ClientSSLTestShortChain : public ClientTest { protected: virtual void SetUp() { // Root signed, root trusted dir_config_file_ = config_path("dirconfig_ssl_short_chain.test"); mrc_config_file_ = config_path("mrcconfig_ssl_short_chain.test"); osd_config_file_ = config_path("osdconfig_ssl_short_chain.test"); dir_url_.xtreemfs_url = "pbrpcs://localhost:48638/"; mrc_url_.xtreemfs_url = "pbrpcs://localhost:48636/"; options_.log_level_string = "DEBUG"; // Root signed, only root as additional certificate. switch (t) { case kPKCS12: options_.log_file_path = "/tmp/xtreemfs_client_ssl_test_short_chain_pkcs12"; options_.ssl_pkcs12_path = cert_path("Client_Root_Root.p12"); break; case kPEM: options_.log_file_path = "/tmp/xtreemfs_client_ssl_test_short_chain_pem"; options_.ssl_pem_cert_path = cert_path("Client_Root.pem"); options_.ssl_pem_key_path = cert_path("Client_Root.key"); options_.ssl_pem_trusted_certs_path = cert_path("CA_Root.pem"); break; case None: break; } options_.ssl_verify_certificates = true; ClientTest::SetUp(); } virtual void TearDown() { ClientTest::TearDown(); unlink(options_.log_file_path.c_str()); unlink(dir_log_file_name_.c_str()); unlink(mrc_log_file_name_.c_str()); unlink(osd_log_file_name_.c_str()); } void DoTest() { CreateOpenDeleteVolume("test_ssl_short_chain"); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "SSL support activated")); switch (t) { case kPKCS12: ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "SSL support using PKCS#12 file " "../../tests/certs/client_ssl_test/Client_Root_Root.p12")); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Writing 1 verification certificates to /tmp/ca")); break; case kPEM: ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "SSL support using PEM private key file " "../../tests/certs/client_ssl_test/Client_Root.key")); break; case None: break; } ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Verification of subject 'CN=Root CA,O=ZIB,L=Berlin,ST=Berlin,C=DE' " "was successful.")); ASSERT_EQ(0, count_occurrences_in_file( options_.log_file_path, "CN=Intermediate CA,O=ZIB,L=Berlin,ST=Berlin,C=DE")); ASSERT_EQ(0, count_occurrences_in_file( options_.log_file_path, "CN=Leaf CA,O=ZIB,L=Berlin,ST=Berlin,C=DE")); ASSERT_EQ(1, count_occurrences_in_file( options_.log_file_path, "Verification of subject 'CN=MRC (Root),O=ZIB,L=Berlin,ST=Berlin,C=DE' " "was successful")); ASSERT_EQ(1, count_occurrences_in_file( options_.log_file_path, "Verification of subject 'CN=DIR (Root),O=ZIB,L=Berlin,ST=Berlin,C=DE' " "was successful.")); } }; class ClientSSLTestShortChainPKCS12 : public ClientSSLTestShortChain<kPKCS12> {}; class ClientSSLTestShortChainPEM : public ClientSSLTestShortChain<kPEM> {}; template<TestCertificateType t> class ClientSSLTestLongChain : public ClientTest { protected: virtual void SetUp() { // All service certificates are signed with Leaf CA, which is signed with // Intermediate CA, which is signed with Root CA. The keystore contains // only the Leaf CA. dir_config_file_ = config_path("dirconfig_ssl_long_chain.test"); mrc_config_file_ = config_path("mrcconfig_ssl_long_chain.test"); osd_config_file_ = config_path("osdconfig_ssl_long_chain.test"); dir_url_.xtreemfs_url = "pbrpcs://localhost:48638/"; mrc_url_.xtreemfs_url = "pbrpcs://localhost:48636/"; options_.log_level_string = "DEBUG"; // Client certificate is signed with Leaf CA. Contains the entire chain // as additional certificates. switch (t) { case kPKCS12: options_.log_file_path = "/tmp/xtreemfs_client_ssl_test_long_chain_pkcs12"; options_.ssl_pkcs12_path = cert_path("Client_Leaf_Chain.p12"); break; case kPEM: options_.log_file_path = "/tmp/xtreemfs_client_ssl_test_long_chain_pem"; options_.ssl_pem_cert_path = cert_path("Client_Leaf.pem"); options_.ssl_pem_key_path = cert_path("Client_Leaf.key"); options_.ssl_pem_trusted_certs_path = cert_path("CA_Chain.pem"); break; case None: break; } options_.ssl_verify_certificates = true; ClientTest::SetUp(); } virtual void TearDown() { ClientTest::TearDown(); unlink(options_.log_file_path.c_str()); unlink(dir_log_file_name_.c_str()); unlink(mrc_log_file_name_.c_str()); unlink(osd_log_file_name_.c_str()); } void DoTest() { CreateOpenDeleteVolume("test_ssl_long_chain"); // Once for MRC and once for DIR. ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "SSL support activated")); switch (t) { case kPKCS12: ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "SSL support using PKCS#12 file " "../../tests/certs/client_ssl_test/Client_Leaf_Chain.p12")); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Writing 3 verification certificates to /tmp/ca")); break; case kPEM: ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "SSL support using PEM private key file " "../../tests/certs/client_ssl_test/Client_Leaf.key")); break; case None: break; } ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Verification of subject 'CN=Root CA,O=ZIB,L=Berlin,ST=Berlin,C=DE' " "was successful.")); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Verification of subject 'CN=Intermediate CA,O=ZIB,L=Berlin,ST=Berlin,C=DE' " "was successful.")); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Verification of subject 'CN=Leaf CA,O=ZIB,L=Berlin,ST=Berlin,C=DE' was " "successful.")); ASSERT_EQ(1, count_occurrences_in_file( options_.log_file_path, "Verification of subject 'CN=MRC (Leaf),O=ZIB,L=Berlin,ST=Berlin,C=DE' " "was successful")); ASSERT_EQ(1, count_occurrences_in_file( options_.log_file_path, "Verification of subject 'CN=DIR (Leaf),O=ZIB,L=Berlin,ST=Berlin,C=DE' " "was successful.")); } }; class ClientSSLTestLongChainPKCS12 : public ClientSSLTestLongChain<kPKCS12> {}; class ClientSSLTestLongChainPEM : public ClientSSLTestLongChain<kPEM> {}; template<TestCertificateType t> class ClientSSLTestShortChainVerification : public ClientTest { protected: virtual void SetUp() { dir_config_file_ = config_path("dirconfig_ssl_short_chain.test"); mrc_config_file_ = config_path("mrcconfig_ssl_short_chain.test"); osd_config_file_ = config_path("osdconfig_ssl_short_chain.test"); dir_url_.xtreemfs_url = "pbrpcs://localhost:48638/"; mrc_url_.xtreemfs_url = "pbrpcs://localhost:48636/"; options_.log_level_string = "DEBUG"; // Server does not know client's certificate, client does not know server's // certificate. switch (t) { case kPKCS12: options_.log_file_path = "/tmp/xtreemfs_client_ssl_test_verification_pkcs12"; options_.ssl_pkcs12_path = cert_path("Client_Leaf.p12"); break; case kPEM: options_.log_file_path = "/tmp/xtreemfs_client_ssl_test_verification_pem"; options_.ssl_pem_cert_path = cert_path("Client_Leaf.pem"); options_.ssl_pem_key_path = cert_path("Client_Leaf.key"); break; case None: break; } options_.ssl_verify_certificates = true; // Need this to avoid too many reconnects upon SSL errors. options_.max_tries = 3; ClientTest::SetUp(); } virtual void TearDown() { ClientTest::TearDown(); unlink(options_.log_file_path.c_str()); unlink(dir_log_file_name_.c_str()); unlink(mrc_log_file_name_.c_str()); unlink(osd_log_file_name_.c_str()); } void DoTest() { // Server does not accept our certificate. std::string exception_text; try { CreateOpenDeleteVolume("test_ssl_verification"); } catch (xtreemfs::IOException& e) { exception_text = e.what(); } // Depending on whether the error occurs on initial connect or reconnect, // the error message varies. This depends on how quick the services start // up, such that the first connect might happen before the services are // operational. ASSERT_TRUE( exception_text.find("could not connect to host") != std::string::npos || exception_text.find("cannot connect to server") != std::string::npos); // We do not accept the server's certificate. ASSERT_TRUE(count_occurrences_in_file( options_.log_file_path, "OpenSSL verify error: 20") > 0); // Issuer certificate of untrusted // certificate cannot be found. ASSERT_TRUE(count_occurrences_in_file( options_.log_file_path, "Verification of subject 'CN=MRC (Root),O=ZIB,L=Berlin,ST=Berlin,C=DE' " "was unsuccessful.") > 0); } }; class ClientSSLTestShortChainVerificationPKCS12 : public ClientSSLTestShortChainVerification<kPKCS12> {}; class ClientSSLTestShortChainVerificationPEM : public ClientSSLTestShortChainVerification<kPEM> {}; template<TestCertificateType t> class ClientSSLTestLongChainVerificationIgnoreErrors : public ClientTest { protected: virtual void SetUp() { dir_config_file_ = config_path("dirconfig_ssl_ignore_errors.test"); mrc_config_file_ = config_path("mrcconfig_ssl_ignore_errors.test"); osd_config_file_ = config_path("osdconfig_ssl_ignore_errors.test"); dir_url_.xtreemfs_url = "pbrpcs://localhost:48638/"; mrc_url_.xtreemfs_url = "pbrpcs://localhost:48636/"; options_.log_level_string = "DEBUG"; // Server knows client's certificate, client does not know server's // certificate. switch (t) { case kPKCS12: options_.log_file_path = "/tmp/xtreemfs_client_ssl_test_verification_ignore_errors_pkcs12"; options_.ssl_pkcs12_path = cert_path("Client_Leaf_Root.p12"); break; case kPEM: options_.log_file_path = "/tmp/xtreemfs_client_ssl_test_verification_ignore_errors_pem"; options_.ssl_pem_cert_path = cert_path("Client_Leaf.pem"); options_.ssl_pem_key_path = cert_path("Client_Leaf.key"); options_.ssl_pem_trusted_certs_path = cert_path("CA_Root.pem"); break; case None: break; } options_.ssl_verify_certificates = true; // The issuer certificate could not be found: this occurs if the issuer // certificate of an untrusted certificate cannot be found. options_.ssl_ignore_verify_errors.push_back(20); // The root CA is not marked as trusted for the specified purpose. options_.ssl_ignore_verify_errors.push_back(27); // No signatures could be verified because the chain contains only one // certificate and it is not self signed. options_.ssl_ignore_verify_errors.push_back(21); ClientTest::SetUp(); } virtual void TearDown() { ClientTest::TearDown(); unlink(options_.log_file_path.c_str()); unlink(dir_log_file_name_.c_str()); unlink(mrc_log_file_name_.c_str()); unlink(osd_log_file_name_.c_str()); } void DoTest() { CreateOpenDeleteVolume("test_ssl_verification_ignore_errors"); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Ignoring OpenSSL verify error: 20 because of user settings.")); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Ignoring OpenSSL verify error: 27 because of user settings.")); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Ignoring OpenSSL verify error: 21 because of user settings.")); ASSERT_EQ(3, count_occurrences_in_file( options_.log_file_path, "Verification of subject 'CN=MRC (Leaf),O=ZIB,L=Berlin,ST=Berlin,C=DE' " "was unsuccessful. Overriding because of user settings.")); ASSERT_EQ(3, count_occurrences_in_file( options_.log_file_path, "Verification of subject 'CN=DIR (Leaf),O=ZIB,L=Berlin,ST=Berlin,C=DE' " "was unsuccessful. Overriding because of user settings.")); } }; class ClientSSLTestLongChainVerificationIgnoreErrorsPKCS12 : public ClientSSLTestLongChainVerificationIgnoreErrors<kPKCS12> {}; class ClientSSLTestLongChainVerificationIgnoreErrorsPEM : public ClientSSLTestLongChainVerificationIgnoreErrors<kPEM> {}; template<TestCertificateType t> class ClientSSLTestLongChainNoVerification : public ClientTest { protected: virtual void SetUp() { dir_config_file_ = config_path("dirconfig_ssl_no_verification.test"); mrc_config_file_ = config_path("mrcconfig_ssl_no_verification.test"); osd_config_file_ = config_path("osdconfig_ssl_no_verification.test"); dir_url_.xtreemfs_url = "pbrpcs://localhost:48638/"; mrc_url_.xtreemfs_url = "pbrpcs://localhost:48636/"; options_.log_level_string = "DEBUG"; // Server knows client's certificate, client does not know all of server's // certificate. switch (t) { case kPKCS12: options_.log_file_path = "/tmp/xtreemfs_client_ssl_test_no_verification_pkcs12"; options_.ssl_pkcs12_path = cert_path("Client_Leaf_Leaf.p12"); break; case kPEM: options_.log_file_path = "/tmp/xtreemfs_client_ssl_test_no_verification_pem"; options_.ssl_pem_cert_path = cert_path("Client_Leaf.pem"); options_.ssl_pem_key_path = cert_path("Client_Leaf.key"); options_.ssl_pem_trusted_certs_path = cert_path("CA_Leaf.pem"); break; case None: break; } ClientTest::SetUp(); } virtual void TearDown() { ClientTest::TearDown(); unlink(options_.log_file_path.c_str()); unlink(dir_log_file_name_.c_str()); unlink(mrc_log_file_name_.c_str()); unlink(osd_log_file_name_.c_str()); } void DoTest() { CreateOpenDeleteVolume("test_ssl_no_verification"); // The issuer certificate of a looked up certificate could not be found. // This normally means the list of trusted certificates is not complete. ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Ignoring OpenSSL verify error: 2 because of user settings.")); // Twice for MRC, twice for DIR. ASSERT_EQ(4, count_occurrences_in_file( options_.log_file_path, "Ignoring OpenSSL verify error: 27 because of user settings.")); // Succeed because the client can verify the leaf certificates, but not their // issuer certificates. ASSERT_EQ(1, count_occurrences_in_file( options_.log_file_path, "Verification of subject 'CN=DIR (Leaf),O=ZIB,L=Berlin,ST=Berlin,C=DE' " "was successful.")); ASSERT_EQ(1, count_occurrences_in_file( options_.log_file_path, "Verification of subject 'CN=DIR (Leaf),O=ZIB,L=Berlin,ST=Berlin,C=DE' " "was successful.")); } }; class ClientSSLTestLongChainNoVerificationPKCS12 : public ClientSSLTestLongChainNoVerification<kPKCS12> {}; class ClientSSLTestLongChainNoVerificationPEM : public ClientSSLTestLongChainNoVerification<kPEM> {}; template<TestCertificateType t, char const *ssl_method_string> class ClientSSLTestSSLVersion : public ClientTest { public: ClientSSLTestSSLVersion() { // Grab the Java version that all services run on so we know what TLS // capabilities to expect. java_major_version_ = ExternalService("", "", "", "").JavaMajorVersion(); } protected: virtual void SetUp() { ASSERT_GE(java_major_version_, 6); dir_config_file_ = config_path("dirconfig_ssl_version.test"); mrc_config_file_ = config_path("mrcconfig_ssl_version.test"); osd_config_file_ = config_path("osdconfig_ssl_version.test"); dir_url_.xtreemfs_url = "pbrpcs://localhost:48638/"; mrc_url_.xtreemfs_url = "pbrpcs://localhost:48636/"; options_.log_level_string = "DEBUG"; switch (t) { case kPKCS12: options_.log_file_path = "/tmp/xtreemfs_client_ssl_test_version_pkcs12_"; options_.ssl_pkcs12_path = cert_path("Client_Root_Root.p12"); break; case kPEM: options_.log_file_path = "/tmp/xtreemfs_client_ssl_test_version_pem_"; options_.ssl_pem_cert_path = cert_path("Client_Root.pem"); options_.ssl_pem_key_path = cert_path("Client_Root.key"); options_.ssl_pem_trusted_certs_path = cert_path("CA_Root.pem"); break; case None: break; } options_.log_file_path.append(ssl_method_string); options_.ssl_method_string = ssl_method_string; options_.ssl_verify_certificates = true; options_.max_tries = 3; ClientTest::SetUp(); } virtual void TearDown() { ClientTest::TearDown(); unlink(options_.log_file_path.c_str()); unlink(dir_log_file_name_.c_str()); unlink(mrc_log_file_name_.c_str()); unlink(osd_log_file_name_.c_str()); } void DoTest() { CreateOpenDeleteVolume("test_ssl_version"); if (strcmp(ssl_method_string, "sslv3") == 0) { ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Using SSL/TLS version 'SSLv3'.")); } #if (BOOST_VERSION < 104800) // Boost < 1.48 supports SSLv3 and TLSv1 if (strcmp(ssl_method_string, "ssltls") == 0 || strcmp(ssl_method_string, "tlsv1") == 0) { ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Using SSL/TLS version 'TLSv1'.")); } else if (strcmp(ssl_method_string, "tlsv11") == 0 || strcmp(ssl_method_string, "tlsv12") == 0){ // Connection must fail for TLSv1.1 and TLSv1.2 ASSERT_EQ(0, count_occurrences_in_file( options_.log_file_path, "Using SSL/TLS")); } #else // BOOST_VERSION < 104800 // Boost >= 1.48 supports whatever OpenSSL supports #if (OPENSSL_VERSION_NUMBER < 0x1000100fL) // OpenSSL < 1.0.1 supports SSLv3 and TLSv1 if (strcmp(ssl_method_string, "ssltls") == 0 || strcmp(ssl_method_string, "tlsv1") == 0) { ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Using SSL/TLS version 'TLSv1'.")); } else if (strcmp(ssl_method_string, "tlsv11") == 0 || strcmp(ssl_method_string, "tlsv12") == 0){ // Connection must fail for TLSv1.1 and TLSv1.2 ASSERT_EQ(0, count_occurrences_in_file( options_.log_file_path, "Using SSL/TLS")); } #endif // OPENSSL_VERSION_NUMBER < 0x1000100fL #endif // BOOST_VERSION < 104800 if (java_major_version_ == 6) { // Java 6 supports SSLv3, TLSv1 and possibly TLSv1.1 #if (BOOST_VERSION >= 104800 && OPENSSL_VERSION_NUMBER >= 0x1000100fL) // OpenSSL >= 1.0.1 supports SSLv3, TLSv1, TLSv1.1 and TLSv1.2 if (strcmp(ssl_method_string, "ssltls") == 0) { // Boost and OpenSSL are capable of 1.2, Java at most 1.1 int tlsv1 = count_occurrences_in_file( options_.log_file_path, "Using SSL/TLS version 'TLSv1'."); int tlsv11 = count_occurrences_in_file( options_.log_file_path, "Using SSL/TLS version 'TLSv1.1'."); ASSERT_EQ(2, tlsv1 + tlsv11); } else if (strcmp(ssl_method_string, "tlsv1") == 0) { ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Using SSL/TLS version 'TLSv1'.")); } else if (strcmp(ssl_method_string, "tlsv11") == 0) { // Don't fail if Java 6 does not support TLSv1.1 EXPECT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Using SSL/TLS version 'TLSv1.1'.")); } else if (strcmp(ssl_method_string, "tlsv12") == 0) { // Java 6 is incapable of TLSv1.2, connection must fail. ASSERT_EQ(0, count_occurrences_in_file( options_.log_file_path, "Using SSL/TLS version")); } #endif // BOOST_VERSION >= 104800 && OPENSSL_VERSION_NUMBER >= 0x1000100fL } else if (java_major_version_ >= 7) { // Java 7+ supports SSLv3, TLSv1, TLSv1.1 and TLSv1.2 #if (BOOST_VERSION >= 104800 && OPENSSL_VERSION_NUMBER >= 0x1000100fL) // OpenSSL >= 1.0.1 supports SSLv3, TLSv1, TLSv1.1 and TLSv1.2 if (strcmp(ssl_method_string, "ssltls") == 0) { ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Using SSL/TLS version 'TLSv1.2'.")); } else if (strcmp(ssl_method_string, "tlsv1") == 0) { ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Using SSL/TLS version 'TLSv1'.")); } else if (strcmp(ssl_method_string, "tlsv11") == 0) { ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Using SSL/TLS version 'TLSv1.1'.")); } else if (strcmp(ssl_method_string, "tlsv12") == 0) { ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Using SSL/TLS version 'TLSv1.2'.")); } #endif // BOOST_VERSION >= 104800 && OPENSSL_VERSION_NUMBER >= 0x1000100fL } } private: int java_major_version_; }; class ClientSSLTestSSLVersionPKCS12SSLv3 : public ClientSSLTestSSLVersion<kPKCS12, g_ssl_tls_version_sslv3> {}; class ClientSSLTestSSLVersionPKCS12SSLTLS : public ClientSSLTestSSLVersion<kPKCS12, g_ssl_tls_version_ssltls> {}; class ClientSSLTestSSLVersionPKCS12TLSv1 : public ClientSSLTestSSLVersion<kPKCS12, g_ssl_tls_version_tlsv1> {}; #if (BOOST_VERSION > 105300) class ClientSSLTestSSLVersionPKCS12TLSv11 : public ClientSSLTestSSLVersion<kPKCS12, g_ssl_tls_version_tlsv11> {}; class ClientSSLTestSSLVersionPKCS12TLSv12 : public ClientSSLTestSSLVersion<kPKCS12, g_ssl_tls_version_tlsv12> {}; #endif // BOOST_VERSION > 105300 class ClientSSLTestSSLVersionPEMSSLv3 : public ClientSSLTestSSLVersion<kPEM, g_ssl_tls_version_sslv3> {}; class ClientSSLTestSSLVersionPEMSSLTLS : public ClientSSLTestSSLVersion<kPEM, g_ssl_tls_version_ssltls> {}; class ClientSSLTestSSLVersionPEMTLSv1 : public ClientSSLTestSSLVersion<kPEM, g_ssl_tls_version_tlsv1> {}; #if (BOOST_VERSION > 105300) class ClientSSLTestSSLVersionPEMTLSv11 : public ClientSSLTestSSLVersion<kPEM, g_ssl_tls_version_tlsv11> {}; class ClientSSLTestSSLVersionPEMTLSv12 : public ClientSSLTestSSLVersion<kPEM, g_ssl_tls_version_tlsv12> {}; #endif // BOOST_VERSION > 105300 TEST_F(ClientNoSSLTest, TestNoSSL) { CreateOpenDeleteVolume("test_no_ssl"); ASSERT_EQ(0, count_occurrences_in_file(options_.log_file_path, "SSL")); } TEST_F(ClientSSLTestShortChainPKCS12, TestVerifyShortChain) { DoTest(); } TEST_F(ClientSSLTestShortChainPEM, TestVerifyShortChain) { DoTest(); } TEST_F(ClientSSLTestLongChainPKCS12, TestVerifyLongChain) { DoTest(); } TEST_F(ClientSSLTestLongChainPEM, TestVerifyLongChain) { DoTest(); } TEST_F(ClientSSLTestShortChainVerificationPKCS12, TestVerificationFail) { DoTest(); } TEST_F(ClientSSLTestShortChainVerificationPEM, TestVerificationFail) { DoTest(); } TEST_F(ClientSSLTestLongChainVerificationIgnoreErrorsPKCS12, TestVerificationIgnoreErrors) { DoTest(); } TEST_F(ClientSSLTestLongChainVerificationIgnoreErrorsPEM, TestVerificationIgnoreErrors) { DoTest(); } TEST_F(ClientSSLTestLongChainNoVerificationPKCS12, TestNoVerification) { DoTest(); } TEST_F(ClientSSLTestLongChainNoVerificationPEM, TestNoVerification) { DoTest(); } TEST_F(ClientSSLTestSSLVersionPKCS12SSLv3, TestSSLVersion) { DoTest(); } TEST_F(ClientSSLTestSSLVersionPKCS12SSLTLS, TestSSLVersion) { DoTest(); } TEST_F(ClientSSLTestSSLVersionPKCS12TLSv1, TestSSLVersion) { DoTest(); } #if (BOOST_VERSION > 105300) TEST_F(ClientSSLTestSSLVersionPKCS12TLSv11, TestSSLVersion) { DoTest(); } TEST_F(ClientSSLTestSSLVersionPKCS12TLSv12, TestSSLVersion) { DoTest(); } #endif // BOOST_VERSION > 105300 TEST_F(ClientSSLTestSSLVersionPEMSSLv3, TestSSLVersion) { DoTest(); } TEST_F(ClientSSLTestSSLVersionPEMSSLTLS, TestSSLVersion) { DoTest(); } TEST_F(ClientSSLTestSSLVersionPEMTLSv1, TestSSLVersion) { DoTest(); } #if (BOOST_VERSION > 105300) TEST_F(ClientSSLTestSSLVersionPEMTLSv11, TestSSLVersion) { DoTest(); } TEST_F(ClientSSLTestSSLVersionPEMTLSv12, TestSSLVersion) { DoTest(); } #endif // BOOST_VERSION > 105300 } // namespace rpc } // namespace xtreemfs #endif // HAS_OPENSSL
[ "ro.schmidtke@gmail.com" ]
ro.schmidtke@gmail.com
a76b267474a0f5b8aefc2c55141082166adf6db7
7534f0e65d2d45c7cf27f9eb896b83aa294bfc11
/01-professional-cplusplus/07-08-classes-and-objects/test/EvenSequenceTest.cpp
e61d821aafa9b537d9793fd72cc997f6367b0848
[]
no_license
knpwrs/Learning-CPlusPlus
2b688c9d18fa173d3e69a695318e774ce30ca251
2445f0c683373f4c4036ad5d74568b95d5da1afc
refs/heads/master
2021-01-10T08:28:17.092105
2016-04-01T03:15:28
2016-04-01T03:15:28
52,158,351
0
0
null
null
null
null
UTF-8
C++
false
false
601
cpp
#include "gtest/gtest.h" #include "EvenSequence.h" using namespace std; using namespace PcppC02E07; TEST(EvenSequence, InitializerListConstructor) { EvenSequence p1 {1.0, 2.0, 3.0, 4.0, 5.5, 7.7}; EXPECT_EQ(p1.size(), 6); } TEST(EvenSequence, InvalidArgument) { try { EvenSequence p1 {1.0, 2.0, 3.0}; FAIL() << "Expected std::invalid_argument"; } catch(invalid_argument const & err) { EXPECT_EQ(err.what(), string("initializer_list should contain even number of elements")); } catch(...) { FAIL() << "Expected std::invalid_argument"; } }
[ "ken@kenpowers.net" ]
ken@kenpowers.net
b6290bc227e0f7b44ddd6cca5cbea989719f64ca
421962a8c2d781562bb6b5a316b57288b9a6fbda
/constructor overloading.cpp
bd3bfbfd0df9741acbc2d15fbb20d0973ee9dc31
[]
no_license
Agarwal-Saurabh/cpp-program
8b559be1c1831af29878505b63e0394519b27514
5cb239dce93ce70375e31de74203055b8a169118
refs/heads/master
2020-03-23T05:38:31.990175
2018-07-16T15:25:38
2018-07-16T15:25:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
615
cpp
#include<iostream> #include<conio.h> using namespace std; class salary { int basic,ta ,da; int total; public: salary() { basic=9000,ta=0,da=0; total=basic+ta+da; } salary(int t) { basic=9000,ta=t,da=0; total=basic+ta+da; } salary(int t,int d) { basic=9000,ta=t,da=d; total=basic+ta+da; } void show() { cout<<"basic salary="<<basic<<endl; cout<<"ta ="<<ta<<"da="<<da<<endl; cout<<"total salary"<<total<<endl; } }; int main() { salary ob1; salary ob2(1000); salary ob3(1000,2000); ob1.show(); ob2.show(); ob3.show(); getch(); return 0; }
[ "saurabhagarwal97jpr@gmail.com" ]
saurabhagarwal97jpr@gmail.com
431ed38642cbbfd09ee6425785b79b8d72c6add2
31ac07ecd9225639bee0d08d00f037bd511e9552
/externals/OCCTLib/inc/Handle_PColPGeom_HArray2OfBSplineSurface.hxx
20b2a1e04f2a04986c09664cfdd72a69ed386092
[]
no_license
litao1009/SimpleRoom
4520e0034e4f90b81b922657b27f201842e68e8e
287de738c10b86ff8f61b15e3b8afdfedbcb2211
refs/heads/master
2021-01-20T19:56:39.507899
2016-07-29T08:01:57
2016-07-29T08:01:57
64,462,604
1
0
null
null
null
null
UTF-8
C++
false
false
927
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _Handle_PColPGeom_HArray2OfBSplineSurface_HeaderFile #define _Handle_PColPGeom_HArray2OfBSplineSurface_HeaderFile #ifndef _Standard_Macro_HeaderFile #include <Standard_Macro.hxx> #endif #ifndef _Standard_DefineHandle_HeaderFile #include <Standard_DefineHandle.hxx> #endif #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Handle_Standard_Persistent_HeaderFile #include <Handle_Standard_Persistent.hxx> #endif class Standard_Persistent; class Handle(Standard_Type); class Handle(Standard_Persistent); class PColPGeom_HArray2OfBSplineSurface; DEFINE_STANDARD_PHANDLE(PColPGeom_HArray2OfBSplineSurface,Standard_Persistent) #endif
[ "litao1009@gmail.com" ]
litao1009@gmail.com
cfff55f5ad4e4e2c727456beab92244c4ec6046d
30d65bd092e4750655cb5af2a7945ebb5082cc7c
/Test10_1/Test11_1.cpp
b4fbc85674b223b53c5af02ffee72fe53aa5d797
[]
no_license
Gao-zhenfeng/Object-Oriented
ad2b4077165bee1c21aa20dce412f979747183fe
a19fa99d5714e44dfe7294c3dcb11817c0a2ffe5
refs/heads/master
2023-03-10T22:36:24.202926
2021-02-28T15:07:31
2021-02-28T15:07:31
319,052,636
0
0
null
2020-12-07T08:28:15
2020-12-06T14:28:46
null
UTF-8
C++
false
false
383
cpp
// Test10_1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> vi; int ti; while (cin >> ti) { vi.push_back(ti); } sort(vi.begin(), vi.end()); for (unsigned int i = 0; i < vi.size(); i++) { cout << vi[i] << endl; } return 0; }
[ "gaozhenfeng1999@gmail.com" ]
gaozhenfeng1999@gmail.com
2fbcee10b4da46a553bc62137f171f708a54bbfc
6792c7ab428e9287656d2c627df5fa6f6450b263
/dht/dht.cpp
e645dfcbbf664d91ba6e3ed33bfe59359ac9e9a2
[]
no_license
Mirax-MRX/Mirax-DHT
8b4806522cad5b08592bfe6bfdd018610e8a91a5
55b6e0623fe6ad3ee9ca06ef1112b05a9afa84d8
refs/heads/master
2023-05-02T23:05:59.468661
2021-06-01T18:21:29
2021-06-01T18:21:29
372,918,385
0
0
null
null
null
null
UTF-8
C++
false
false
20,008
cpp
#include "dht.hpp" #include /utils/tl_storers.h" #include /utils/crypto.h" #include /utils/tl_parsers.h" #include /utils/Random.h" #include /utils/base64.h" #include /utils/format.h" #include /db/RocksDb.h" #include "keys/encryptor.h" #include "adnl/utils.hpp" #include "auto/tl/ton_api.hpp" #include "dht.h" #include "dht-bucket.hpp" #include "dht-query.hpp" #include "dht-in.hpp" namespace ton { namespace dht { td::actor::ActorOwn<DhtMember> DhtMember::create(adnl::AdnlNodeIdShort id, std::string db_root, td::actor::ActorId<keyring::Keyring> keyring, td::actor::ActorId<adnl::Adnl> adnl, td::uint32 k, td::uint32 a, bool client_only) { return td::actor::ActorOwn<DhtMember>( td::actor::create_actor<DhtMemberImpl>("dht", id, db_root, keyring, adnl, k, a, client_only)); } td::Result<td::actor::ActorOwn<Dht>> Dht::create(adnl::AdnlNodeIdShort id, std::string db_root, std::shared_ptr<DhtGlobalConfig> conf, td::actor::ActorId<keyring::Keyring> keyring, td::actor::ActorId<adnl::Adnl> adnl) { CHECK(conf->get_k() > 0); CHECK(conf->get_a() > 0); auto D = DhtMember::create(id, db_root, keyring, adnl, conf->get_k(), conf->get_a()); auto &nodes = conf->nodes(); for (auto &node : nodes.list()) { auto key = node.get_key(); td::actor::send_closure(D, &DhtMember::add_full_node, key, node.clone()); } return std::move(D); } td::Result<td::actor::ActorOwn<Dht>> Dht::create_client(adnl::AdnlNodeIdShort id, std::string db_root, std::shared_ptr<DhtGlobalConfig> conf, td::actor::ActorId<keyring::Keyring> keyring, td::actor::ActorId<adnl::Adnl> adnl) { CHECK(conf->get_k() > 0); CHECK(conf->get_a() > 0); auto D = DhtMember::create(id, db_root, keyring, adnl, conf->get_k(), conf->get_a(), true); auto &nodes = conf->nodes(); for (auto &node : nodes.list()) { auto key = node.get_key(); td::actor::send_closure(D, &DhtMember::add_full_node, key, node.clone()); } return std::move(D); } void DhtMemberImpl::start_up() { std::vector<td::int32> methods = {ton_api::dht_getSignedAddressList::ID, ton_api::dht_findNode::ID, ton_api::dht_findValue::ID, ton_api::dht_store::ID, ton_api::dht_ping::ID, ton_api::dht_query::ID, ton_api::dht_message::ID}; for (auto it : methods) { td::actor::send_closure(adnl_, &adnl::Adnl::subscribe, id_, adnl::Adnl::int_to_bytestring(it), std::make_unique<Callback>(actor_id(this), id_)); } alarm_timestamp() = td::Timestamp::in(1.0); if (!db_root_.empty()) { std::shared_ptr<td::KeyValue> kv = std::make_shared<td::RocksDb>( td::RocksDb::open(PSTRING() << db_root_ << "/dht-" << td::base64url_encode(id_.as_slice())).move_as_ok()); for (td::uint32 bit = 0; bit < 256; bit++) { auto key = create_hash_tl_object<ton_api::dht_db_key_bucket>(bit); std::string value; auto R = kv->get(key.as_slice(), value); R.ensure(); if (R.move_as_ok() == td::KeyValue::GetStatus::Ok) { auto V = fetch_tl_object<ton_api::dht_db_bucket>(td::BufferSlice{value}, true); V.ensure(); auto nodes = std::move(V.move_as_ok()->nodes_); auto s = nodes->nodes_.size(); DhtNodesList list{std::move(nodes)}; CHECK(list.size() == s); auto &B = buckets_[bit]; for (auto &node : list.list()) { auto key = node.get_key(); B.add_full_node(key, std::move(node), adnl_, id_); } } } db_ = DbType{std::move(kv)}; } } void DhtMemberImpl::tear_down() { std::vector<td::int32> methods = {ton_api::dht_getSignedAddressList::ID, ton_api::dht_findNode::ID, ton_api::dht_findValue::ID, ton_api::dht_store::ID, ton_api::dht_ping::ID, ton_api::dht_query::ID, ton_api::dht_message::ID}; for (auto it : methods) { td::actor::send_closure(adnl_, &adnl::Adnl::unsubscribe, id_, adnl::Adnl::int_to_bytestring(it)); } } void DhtMemberImpl::save_to_db() { if (db_root_.empty()) { return; } next_save_to_db_at_ = td::Timestamp::in(10.0); alarm_timestamp().relax(next_save_to_db_at_); td::uint32 bit = td::Random::fast(0, 255); auto &B = buckets_[bit]; auto list = B.export_nodes(); if (list.size() > 0) { auto key = create_hash_tl_object<ton_api::dht_db_key_bucket>(bit); auto value = create_serialize_tl_object<ton_api::dht_db_bucket>(list.tl()); db_.set(key, std::move(value)); } } DhtNodesList DhtMemberImpl::get_nearest_nodes(DhtKeyId id, td::uint32 k) { DhtNodesList vec; auto id_xor = id ^ key_; for (td::uint32 bit = 0; bit < 256; bit++) { if (id_xor.get_bit(bit)) { buckets_[bit].get_nearest_nodes(id, bit, vec, k); if (vec.size() >= k) { break; } } } for (auto &el : vec.list()) { CHECK((el.get_key() ^ id) < id_xor); } if (vec.size() < k) { for (td::uint32 bit = 255; bit != 256; bit = bit ? (bit - 1) : 256) { if (!id_xor.get_bit(bit)) { buckets_[bit].get_nearest_nodes(id, bit, vec, k); if (vec.size() >= k) { break; } } } } CHECK(vec.size() <= k); return vec; } td::uint32 DhtMemberImpl::distance(DhtKeyId key_id, td::uint32 max_value) { if (!max_value) { max_value = 2 * k_; } td::uint32 res = 0; auto id_xor = key_id ^ key_; for (td::uint32 bit = 0; bit < 256; bit++) { if (id_xor.get_bit(bit)) { res += buckets_[bit].active_cnt(); if (res >= max_value) { return max_value; } } } return res; } void DhtMemberImpl::process_query(adnl::AdnlNodeIdShort src, ton_api::dht_ping &query, td::Promise<td::BufferSlice> promise) { ping_queries_++; promise.set_value(create_serialize_tl_object<ton_api::dht_pong>(query.random_id_)); } void DhtMemberImpl::process_query(adnl::AdnlNodeIdShort src, ton_api::dht_findNode &query, td::Promise<td::BufferSlice> promise) { find_node_queries_++; auto k = static_cast<td::uint32>(query.k_); if (k > max_k()) { k = max_k(); } auto R = get_nearest_nodes(DhtKeyId{query.key_}, k); promise.set_value(serialize_tl_object(R.tl(), true)); } void DhtMemberImpl::process_query(adnl::AdnlNodeIdShort src, ton_api::dht_findValue &query, td::Promise<td::BufferSlice> promise) { find_value_queries_++; auto it = values_.find(DhtKeyId{query.key_}); if (it != values_.end() && it->second.expired()) { values_.erase(it); it = values_.end(); } if (it != values_.end()) { promise.set_value(create_serialize_tl_object<ton_api::dht_valueFound>(it->second.tl())); return; } auto k = static_cast<td::uint32>(query.k_); if (k > max_k()) { k = max_k(); } auto R = get_nearest_nodes(DhtKeyId{query.key_}, k); promise.set_value(create_serialize_tl_object<ton_api::dht_valueNotFound>(R.tl())); } td::Status DhtMemberImpl::store_in(DhtValue value) { if (value.expired()) { VLOG(DHT_INFO) << this << ": dropping expired value: " << value.key_id() << " expire_at = " << value.ttl(); return td::Status::OK(); } TRY_STATUS(value.check()); auto key_id = value.key_id(); auto dist = distance(key_id, k_ + 10); if (dist < k_ + 10) { auto it = values_.find(key_id); if (it != values_.end()) { it->second.update(std::move(value)); } else { values_.emplace(key_id, std::move(value)); } } else { VLOG(DHT_INFO) << this << ": dropping too remote value: " << value.key_id() << " distance = " << dist; } return td::Status::OK(); } void DhtMemberImpl::process_query(adnl::AdnlNodeIdShort src, ton_api::dht_store &query, td::Promise<td::BufferSlice> promise) { store_queries_++; auto V = DhtValue::create(std::move(query.value_), true); if (V.is_error()) { promise.set_error(td::Status::Error(ErrorCode::protoviolation, PSTRING() << "dropping invalid dht_store() value: " << V.error().to_string())); VLOG(DHT_INFO) << this << ": dropping invalid value: " << V.move_as_error(); return; } auto b = store_in(V.move_as_ok()); if (b.is_ok()) { promise.set_value(create_serialize_tl_object<ton_api::dht_stored>()); } else { VLOG(DHT_INFO) << this << ": dropping store() query from " << src << ": " << b.move_as_error(); promise.set_error(td::Status::Error(ErrorCode::protoviolation, "dropping dht_store() query")); } } void DhtMemberImpl::process_query(adnl::AdnlNodeIdShort src, ton_api::dht_getSignedAddressList &query, td::Promise<td::BufferSlice> promise) { get_addr_list_queries_++; auto P = td::PromiseCreator::lambda([promise = std::move(promise)](td::Result<DhtNode> R) mutable { R.ensure(); promise.set_value(serialize_tl_object(R.move_as_ok().tl(), true)); }); get_self_node(std::move(P)); } void DhtMemberImpl::receive_query(adnl::AdnlNodeIdShort src, td::BufferSlice data, td::Promise<td::BufferSlice> promise) { if (client_only_) { return; } { auto R = fetch_tl_prefix<ton_api::dht_query>(data, true); if (R.is_ok()) { auto N = DhtNode::create(std::move(R.move_as_ok()->node_)); if (N.is_ok()) { auto node = N.move_as_ok(); auto key = node.get_key(); add_full_node(key, std::move(node)); } else { VLOG(DHT_WARNING) << this << ": dropping bad node " << N.move_as_error(); } } } auto R = fetch_tl_object<ton_api::Function>(std::move(data), true); if (R.is_error()) { VLOG(DHT_WARNING) << this << ": dropping unknown query to DHT node: " << R.move_as_error(); promise.set_error(td::Status::Error(ErrorCode::protoviolation, "failed to parse dht query")); return; } auto Q = R.move_as_ok(); if (td::Random::fast(0, 127) == 0) { VLOG(DHT_DEBUG) << this << ": ping=" << ping_queries_ << " fnode=" << find_node_queries_ << " fvalue=" << find_value_queries_ << " store=" << store_queries_ << " addrlist=" << get_addr_list_queries_; VLOG(DHT_DEBUG) << this << ": query to DHT from " << src << ": " << ton_api::to_string(Q); } VLOG(DHT_EXTRA_DEBUG) << this << ": query to DHT from " << src << ": " << ton_api::to_string(Q); ton_api::downcast_call(*Q.get(), [&](auto &object) { this->process_query(src, object, std::move(promise)); }); } void DhtMemberImpl::add_full_node(DhtKeyId key, DhtNode node) { VLOG(DHT_EXTRA_DEBUG) << this << ": adding full node " << key; auto eid = key ^ key_; auto bit = eid.count_leading_zeroes(); #ifndef NDEBUG for (td::uint32 i = 0; i < bit; i++) { CHECK(key.get_bit(i) == key_.get_bit(i)); } #endif if (bit < 256) { CHECK(key.get_bit(bit) != key_.get_bit(bit)); buckets_[bit].add_full_node(key, std::move(node), adnl_, id_); } else { CHECK(key == key_); } } void DhtMemberImpl::receive_ping(DhtKeyId key, DhtNode result) { VLOG(DHT_EXTRA_DEBUG) << this << ": received ping from " << key; auto eid = key ^ key_; auto bit = eid.count_leading_zeroes(); if (bit < 256) { buckets_[bit].receive_ping(key, std::move(result), adnl_, id_); } else { CHECK(key == key_); } } void DhtMemberImpl::receive_message(adnl::AdnlNodeIdShort src, td::BufferSlice data) { } void DhtMemberImpl::set_value(DhtValue value, td::Promise<td::Unit> promise) { auto S = value.check(); if (S.is_error()) { promise.set_error(std::move(S)); return; } auto h = value.key_id(); our_values_.emplace(h, value.clone()); send_store(std::move(value), std::move(promise)); } void DhtMemberImpl::get_value_in(DhtKeyId key, td::Promise<DhtValue> result) { auto P = td::PromiseCreator::lambda([key, promise = std::move(result), SelfId = actor_id(this), print_id = print_id(), adnl = adnl_, list = get_nearest_nodes(key, k_), k = k_, a = a_, id = id_, client_only = client_only_](td::Result<DhtNode> R) mutable { R.ensure(); td::actor::create_actor<DhtQueryFindValue>("FindValueQuery", key, print_id, id, std::move(list), k, a, R.move_as_ok(), client_only, SelfId, adnl, std::move(promise)) .release(); }); get_self_node(std::move(P)); } void DhtMemberImpl::check() { VLOG(DHT_INFO) << this << ": ping=" << ping_queries_ << " fnode=" << find_node_queries_ << " fvalue=" << find_value_queries_ << " store=" << store_queries_ << " addrlist=" << get_addr_list_queries_; for (auto &bucket : buckets_) { bucket.check(client_only_, adnl_, actor_id(this), id_); } if (next_save_to_db_at_.is_in_past()) { save_to_db(); } if (values_.size() > 0) { auto it = values_.lower_bound(last_check_key_); if (it != values_.end() && it->first == last_check_key_) { it++; } if (it == values_.end()) { it = values_.begin(); } td::uint32 cnt = 0; auto s = last_check_key_; while (values_.size() > 0 && cnt < 1 && it->first != s) { last_check_key_ = it->first; cnt++; if (it->second.expired()) { it = values_.erase(it); // do not republish soon-to-be-expired values } else if (it->second.ttl() > td::Clocks::system() + 60) { auto dist = distance(it->first, k_ + 10); if (dist == 0) { if (it->second.key().update_rule()->need_republish()) { auto P = td::PromiseCreator::lambda([print_id = print_id()](td::Result<td::Unit> R) { if (R.is_error()) { VLOG(DHT_INFO) << print_id << ": failed to store: " << R.move_as_error(); } }); send_store(it->second.clone(), std::move(P)); } it++; } else if (dist >= k_ + 10) { it = values_.erase(it); } else { it++; } } else { it++; } if (values_.size() == 0) { break; } if (it == values_.end()) { it = values_.begin(); } } } if (republish_att_.is_in_past()) { auto it = our_values_.lower_bound(last_republish_key_); if (it != our_values_.end() && it->first == last_republish_key_) { it++; } if (it == our_values_.end()) { it = our_values_.begin(); } if (it != our_values_.end()) { if (it->second.ttl() > td::Clocks::system() + 60) { auto P = td::PromiseCreator::lambda([print_id = print_id()](td::Result<td::Unit> R) { if (R.is_error()) { VLOG(DHT_INFO) << print_id << ": failed to store: " << R.move_as_error(); } }); send_store(it->second.clone(), std::move(P)); } last_republish_key_ = it->first; } republish_att_ = td::Timestamp::in(10.0 + td::Random::fast(0, 1000) * 0.001); } if (fill_att_.is_in_past()) { auto promise = td::PromiseCreator::lambda([](td::Result<DhtNodesList> R) { if (R.is_error()) { VLOG(DHT_WARNING) << "failed find self query: " << R.move_as_error(); } }); td::Bits256 x; td::uint32 t = td::Random::fast(0, 6); td::uint32 b = 64 - td::Random::fast(0, 1 << t); td::Random::secure_bytes(x.as_slice()); for (td::uint32 i = 0; i < b; i++) { x.bits()[i] = key_.get_bit(i); } DhtKeyId key{x}; auto P = td::PromiseCreator::lambda([key, promise = std::move(promise), SelfId = actor_id(this), print_id = print_id(), adnl = adnl_, list = get_nearest_nodes(key, k_), k = k_, a = a_, id = id_, client_only = client_only_](td::Result<DhtNode> R) mutable { R.ensure(); td::actor::create_actor<DhtQueryFindNodes>("FindNodesQuery", key, print_id, id, std::move(list), k, a, R.move_as_ok(), client_only, SelfId, adnl, std::move(promise)) .release(); }); get_self_node(std::move(P)); fill_att_ = td::Timestamp::in(10.0 + td::Random::fast(0, 100) * 0.1); } } void DhtMemberImpl::dump(td::StringBuilder &sb) const { for (auto &B : buckets_) { B.dump(sb); } } void DhtMemberImpl::send_store(DhtValue value, td::Promise<td::Unit> promise) { value.check().ensure(); auto key_id = value.key_id(); auto P = td::PromiseCreator::lambda([value = std::move(value), print_id = print_id(), id = id_, client_only = client_only_, list = get_nearest_nodes(key_id, k_), k = k_, a = a_, SelfId = actor_id(this), adnl = adnl_, promise = std::move(promise)](td::Result<DhtNode> R) mutable { R.ensure(); td::actor::create_actor<DhtQueryStore>("StoreQuery", std::move(value), print_id, id, std::move(list), k, a, R.move_as_ok(), client_only, SelfId, adnl, std::move(promise)) .release(); }); get_self_node(std::move(P)); } void DhtMemberImpl::get_self_node(td::Promise<DhtNode> promise) { auto P = td::PromiseCreator::lambda([promise = std::move(promise), print_id = print_id(), id = id_, keyring = keyring_, client_only = client_only_](td::Result<adnl::AdnlNode> R) mutable { R.ensure(); auto node = R.move_as_ok(); auto version = static_cast<td::int32>(td::Clocks::system()); auto B = create_serialize_tl_object<ton_api::dht_node>(node.pub_id().tl(), node.addr_list().tl(), version, td::BufferSlice()); if (!client_only) { CHECK(node.addr_list().size() > 0); } auto P = td::PromiseCreator::lambda( [promise = std::move(promise), node = std::move(node), version](td::Result<td::BufferSlice> R) mutable { R.ensure(); DhtNode n{node.pub_id(), node.addr_list(), version, R.move_as_ok()}; promise.set_result(std::move(n)); }); td::actor::send_closure(keyring, &keyring::Keyring::sign_message, id.pubkey_hash(), std::move(B), std::move(P)); }); td::actor::send_closure(adnl_, &adnl::Adnl::get_self_node, id_, std::move(P)); } td::Result<std::shared_ptr<DhtGlobalConfig>> Dht::create_global_config(tl_object_ptr<ton_api::dht_config_global> conf) { td::uint32 k; if (conf->k_ == 0) { k = DhtMember::default_k(); } else if (conf->k_ > 0 && static_cast<td::uint32>(conf->k_) <= DhtMember::max_k()) { k = conf->k_; } else { return td::Status::Error(ErrorCode::protoviolation, PSTRING() << "bad value k=" << conf->k_); } td::uint32 a; if (conf->a_ == 0) { a = DhtMember::default_a(); } else if (conf->a_ > 0 && static_cast<td::uint32>(conf->a_) <= DhtMember::max_a()) { a = conf->a_; } else { return td::Status::Error(ErrorCode::protoviolation, PSTRING() << "bad value a=" << conf->a_); } DhtNodesList l{std::move(conf->static_nodes_)}; return std::make_shared<DhtGlobalConfig>(k, a, std::move(l)); } } // namespace dht } // namespace ton
[ "khadjik000@gmail.com" ]
khadjik000@gmail.com
f8ce7eb738a0c960d65eb3ab2c5448a028385695
5ec06dab1409d790496ce082dacb321392b32fe9
/clients/cpp-restbed-server/generated/model/ComDayCqAnalyticsTestandtargetImplTestandtargetHttpClientImplInfo.cpp
5fd0583b09fd1bb45b6705710d324129b5eb4daf
[ "Apache-2.0" ]
permissive
shinesolutions/swagger-aem-osgi
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
c2f6e076971d2592c1cbd3f70695c679e807396b
refs/heads/master
2022-10-29T13:07:40.422092
2021-04-09T07:46:03
2021-04-09T07:46:03
190,217,155
3
3
Apache-2.0
2022-10-05T03:26:20
2019-06-04T14:23:28
null
UTF-8
C++
false
false
2,881
cpp
/** * Adobe Experience Manager OSGI config (AEM) API * Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API * * OpenAPI spec version: 1.0.0-pre.0 * Contact: opensource@shinesolutions.com * * NOTE: This class is auto generated by OpenAPI-Generator 3.2.1-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ #include "ComDayCqAnalyticsTestandtargetImplTestandtargetHttpClientImplInfo.h" #include <string> #include <sstream> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> using boost::property_tree::ptree; using boost::property_tree::read_json; using boost::property_tree::write_json; namespace org { namespace openapitools { namespace server { namespace model { ComDayCqAnalyticsTestandtargetImplTestandtargetHttpClientImplInfo::ComDayCqAnalyticsTestandtargetImplTestandtargetHttpClientImplInfo() { m_Pid = ""; m_Title = ""; m_Description = ""; } ComDayCqAnalyticsTestandtargetImplTestandtargetHttpClientImplInfo::~ComDayCqAnalyticsTestandtargetImplTestandtargetHttpClientImplInfo() { } std::string ComDayCqAnalyticsTestandtargetImplTestandtargetHttpClientImplInfo::toJsonString() { std::stringstream ss; ptree pt; pt.put("Pid", m_Pid); pt.put("Title", m_Title); pt.put("Description", m_Description); write_json(ss, pt, false); return ss.str(); } void ComDayCqAnalyticsTestandtargetImplTestandtargetHttpClientImplInfo::fromJsonString(std::string const& jsonString) { std::stringstream ss(jsonString); ptree pt; read_json(ss,pt); m_Pid = pt.get("Pid", ""); m_Title = pt.get("Title", ""); m_Description = pt.get("Description", ""); } std::string ComDayCqAnalyticsTestandtargetImplTestandtargetHttpClientImplInfo::getPid() const { return m_Pid; } void ComDayCqAnalyticsTestandtargetImplTestandtargetHttpClientImplInfo::setPid(std::string value) { m_Pid = value; } std::string ComDayCqAnalyticsTestandtargetImplTestandtargetHttpClientImplInfo::getTitle() const { return m_Title; } void ComDayCqAnalyticsTestandtargetImplTestandtargetHttpClientImplInfo::setTitle(std::string value) { m_Title = value; } std::string ComDayCqAnalyticsTestandtargetImplTestandtargetHttpClientImplInfo::getDescription() const { return m_Description; } void ComDayCqAnalyticsTestandtargetImplTestandtargetHttpClientImplInfo::setDescription(std::string value) { m_Description = value; } std::shared_ptr<ComDayCqAnalyticsTestandtargetImplTestandtargetHttpClientImplProperties> ComDayCqAnalyticsTestandtargetImplTestandtargetHttpClientImplInfo::getProperties() const { return m_Properties; } void ComDayCqAnalyticsTestandtargetImplTestandtargetHttpClientImplInfo::setProperties(std::shared_ptr<ComDayCqAnalyticsTestandtargetImplTestandtargetHttpClientImplProperties> value) { m_Properties = value; } } } } }
[ "cliffano@gmail.com" ]
cliffano@gmail.com
c3e0ea4c5863235b635d5001f01b8fe6699dd9b1
3ca7664834675f20acc1915cb2aa9ad62bc89fac
/extras/log4cplus/src/socketbuffer.cxx
08e5aa88cd0ff8595d5784f2b32eb0dab07c168c
[ "Apache-1.1", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "MIT" ]
permissive
tianpi/thekla
aaf4694bc8a460c570089681ec572bdfeb0fee8b
3cee9fc26752f712f003745785abd67236ba8102
refs/heads/master
2022-12-08T03:28:24.844489
2006-11-29T11:00:00
2006-11-29T11:00:00
293,784,563
0
0
null
null
null
null
UTF-8
C++
false
false
8,464
cxx
// Module: Log4CPLUS // File: socketbuffer.cxx // Created: 5/2003 // Author: Tad E. Smith // // // Copyright (C) Tad E. Smith All rights reserved. // // This software is published under the terms of the Apache Software // License version 1.1, a copy of which has been included with this // distribution in the LICENSE.APL file. // // $Log: socketbuffer.cxx,v $ // Revision 1.1 2006-08-04 11:07:37 chris // Restructure towards ICG SVN REPO part 1 :: // o added extras // - log4cplus // . added vc.2005 directory w/ solution and project (for dll): TODO: tested on win32 // - cxxtest // o tests // - moved xml -> lib // - moved adapter -> lib // - removed adapter, xml // - moved tests/common/TestInit.h -> tests/ // - removed common // o root // - updated Makefile (see tests) // o misc // - removed // // Revision 1.5 2003/11/21 21:23:29 tcsmith // Fixed memory alignment errors on Solaris. // // Revision 1.4 2003/09/28 04:26:02 tcsmith // Added include for <winsock.h> on WIN32. // // Revision 1.3 2003/08/08 05:36:51 tcsmith // Changed the #if checks to look for _WIN32 and not WIN32. // // Revision 1.2 2003/05/21 22:11:00 tcsmith // Added appendSize_t() method. // // Revision 1.1 2003/05/04 07:25:16 tcsmith // Initial version. // #include <log4cplus/helpers/socketbuffer.h> #include <log4cplus/helpers/loglog.h> #if !defined(_WIN32) # include <netdb.h> #else #include <winsock.h> #endif using namespace log4cplus; using namespace log4cplus::helpers; ////////////////////////////////////////////////////////////////////////////// // SocketBuffer ctors and dtor ////////////////////////////////////////////////////////////////////////////// log4cplus::helpers::SocketBuffer::SocketBuffer(size_t maxsize) : maxsize(maxsize), size(0), pos(0), buffer(new char[maxsize]) { } log4cplus::helpers::SocketBuffer::SocketBuffer(const SocketBuffer& rhs) { copy(rhs); } log4cplus::helpers::SocketBuffer::~SocketBuffer() { delete buffer; } SocketBuffer& log4cplus::helpers::SocketBuffer::operator=(const SocketBuffer& rhs) { if(&rhs != this) { delete buffer; copy(rhs); } return *this; } void log4cplus::helpers::SocketBuffer::copy(const SocketBuffer& r) { SocketBuffer& rhs = const_cast<SocketBuffer&>(r); maxsize = rhs.maxsize; size = rhs.size; pos = rhs.pos; buffer = rhs.buffer; rhs.maxsize = 0; rhs.size = 0; rhs.pos = 0; rhs.buffer = 0; } ////////////////////////////////////////////////////////////////////////////// // SocketBuffer methods ////////////////////////////////////////////////////////////////////////////// unsigned char log4cplus::helpers::SocketBuffer::readByte() { if(pos >= maxsize) { getLogLog().error(LOG4CPLUS_TEXT("SocketBuffer::readByte()- end of buffer reached")); return 0; } else if((pos + sizeof(unsigned char)) > maxsize) { getLogLog().error(LOG4CPLUS_TEXT("SocketBuffer::readByte()- Attempt to read beyond end of buffer")); return 0; } unsigned char ret = *((unsigned char*)&buffer[pos]); pos += sizeof(unsigned char); return ret; } unsigned short log4cplus::helpers::SocketBuffer::readShort() { if(pos >= maxsize) { getLogLog().error(LOG4CPLUS_TEXT("SocketBuffer::readShort()- end of buffer reached")); return 0; } else if((pos + sizeof(unsigned short)) > maxsize) { getLogLog().error(LOG4CPLUS_TEXT("SocketBuffer::readShort()- Attempt to read beyond end of buffer")); return 0; } unsigned short ret; memcpy(&ret, buffer + pos, sizeof(ret)); ret = ntohs(ret); pos += sizeof(unsigned short); return ret; } unsigned int log4cplus::helpers::SocketBuffer::readInt() { if(pos >= maxsize) { getLogLog().error(LOG4CPLUS_TEXT("SocketBuffer::readInt()- end of buffer reached")); return 0; } else if((pos + sizeof(unsigned int)) > maxsize) { getLogLog().error(LOG4CPLUS_TEXT("SocketBuffer::readInt()- Attempt to read beyond end of buffer")); return 0; } unsigned int ret; memcpy (&ret, buffer + pos, sizeof(ret)); ret = ntohl(ret); pos += sizeof(unsigned int); return ret; } tstring log4cplus::helpers::SocketBuffer::readString(unsigned char sizeOfChar) { size_t strlen = readInt(); size_t bufferLen = strlen * sizeOfChar; if(strlen == 0) { return tstring(); } if(pos > maxsize) { getLogLog().error(LOG4CPLUS_TEXT("SocketBuffer::readString()- end of buffer reached")); return tstring(); } if((pos + bufferLen) > maxsize) { getLogLog().error(LOG4CPLUS_TEXT("SocketBuffer::readString()- Attempt to read beyond end of buffer")); bufferLen = (maxsize - 1) - pos; strlen = bufferLen / sizeOfChar; } #ifndef UNICODE if(sizeOfChar == 1) { tstring ret(&buffer[pos], strlen); pos += strlen; return ret; } else if(sizeOfChar == 2) { tstring ret; for(tstring::size_type i=0; i<strlen; ++i) { unsigned short tmp = readShort(); ret += static_cast<char>(tmp < 256 ? tmp : ' '); } return ret; } else { getLogLog().error(LOG4CPLUS_TEXT("SocketBuffer::readString()- Invalid sizeOfChar!!!!")); } #else /* UNICODE */ if(sizeOfChar == 1) { std::string ret(&buffer[pos], strlen); pos += strlen; return towstring(ret); } else if(sizeOfChar == 2) { tstring ret; for(tstring::size_type i=0; i<strlen; ++i) { ret += static_cast<tchar>(readShort()); } return ret; } else { getLogLog().error(LOG4CPLUS_TEXT("SocketBuffer::readString()- Invalid sizeOfChar!!!!")); } #endif return tstring(); } void log4cplus::helpers::SocketBuffer::appendByte(unsigned char val) { if((pos + sizeof(unsigned char)) > maxsize) { getLogLog().error(LOG4CPLUS_TEXT("SocketBuffer::appendByte()- Attempt to write beyond end of buffer")); return; } *((unsigned char*)&buffer[pos]) = val; pos += sizeof(unsigned char); size = pos; } void log4cplus::helpers::SocketBuffer::appendShort(unsigned short val) { if((pos + sizeof(unsigned short)) > maxsize) { getLogLog().error(LOG4CPLUS_TEXT("SocketBuffer::appendShort()- Attempt to write beyond end of buffer")); return; } *((unsigned short*)&buffer[pos]) = htons(val); pos += sizeof(unsigned short); size = pos; } void log4cplus::helpers::SocketBuffer::appendInt(unsigned int val) { if((pos + sizeof(unsigned int)) > maxsize) { getLogLog().error(LOG4CPLUS_TEXT("SocketBuffer::appendInt()- Attempt to write beyond end of buffer")); return; } int i = htonl(val); memcpy(buffer + pos, &i, sizeof (i)); pos += sizeof(unsigned int); size = pos; } void log4cplus::helpers::SocketBuffer::appendSize_t(size_t val) { if((pos + sizeof(size_t)) > maxsize) { getLogLog().error(LOG4CPLUS_TEXT("SocketBuffer::appendInt(size_t)- Attempt to write beyond end of buffer")); return; } size_t st = htonl(val); memcpy(buffer + pos, &st, sizeof(st)); pos += sizeof(size_t); size = pos; } void log4cplus::helpers::SocketBuffer::appendString(const tstring& str) { #ifndef UNICODE size_t strlen = str.length(); if((pos + sizeof(unsigned int) + strlen) > maxsize) { getLogLog().error(LOG4CPLUS_TEXT("SocketBuffer::appendString()- Attempt to write beyond end of buffer")); return; } appendSize_t(strlen); memcpy(&buffer[pos], str.data(), strlen); pos += strlen; size = pos; #else size_t strlen = str.length(); if((pos + sizeof(unsigned int) + (strlen * 2)) > maxsize) { getLogLog().error(LOG4CPLUS_TEXT("SocketBuffer::appendString()- Attempt to write beyond end of buffer")); return; } appendInt(strlen); for(tstring::size_type i=0; i<str.length(); ++i) { appendShort(static_cast<unsigned short>(str[i])); } #endif } void log4cplus::helpers::SocketBuffer::appendBuffer(const SocketBuffer& buf) { if((pos + buf.getSize()) > maxsize) { getLogLog().error(LOG4CPLUS_TEXT("SocketBuffer::appendBuffer()- Attempt to write beyond end of buffer")); return; } memcpy(&buffer[pos], buf.buffer, buf.getSize()); pos += buf.getSize(); size = pos; }
[ "5852961+tianpi@users.noreply.github.com" ]
5852961+tianpi@users.noreply.github.com
b149f5080ad04bbd84f51f1ef8fbb6c73c20565b
9178022b8d1dc9f510a950fd6d4c97c5639edf71
/c++11/11special/autoType/autoType.cpp
2511124e68cbfdf81ce67ea384007b65d47b06a6
[]
no_license
hanhiver/mycpp11
f71ea9fbcb021763630dd05861c3226eb9457558
deaebbde07bd153d2cd287af8c1b474f51f5d8a5
refs/heads/master
2021-06-21T16:33:29.668467
2021-03-23T07:00:09
2021-03-23T07:00:09
204,598,282
1
1
null
null
null
null
UTF-8
C++
false
false
164
cpp
#include <iostream> int main() { auto i = 42; float s[] = {1.0, 3.4, 5.9}; auto j = &s; std::cout<<i<<std::endl; std::cout<<s[1]<<std::endl; return 0; }
[ "handongfr@163.com" ]
handongfr@163.com
ac026c5470154a2dd939c9cd28dbc76233a89b49
62869fe5152bbe07fbe9f0b61166be32e4f5016c
/3rdparty/CGAL/include/CGAL/Envelope_2/Env_divide_and_conquer_2_impl.h
2a93f79573761ae32b887d05d498742bd54c5116
[ "LicenseRef-scancode-warranty-disclaimer", "LGPL-3.0-or-later", "LGPL-2.0-or-later", "GPL-1.0-or-later", "LicenseRef-scancode-commercial-license", "MIT" ]
permissive
daergoth/SubdivisionSandbox
aef65eab0e1ab3dfecb2f9254c36d26c71ecd4fd
d67386980eb978a552e5a98ba1c4b25cf5a9a328
refs/heads/master
2020-03-30T09:19:07.121847
2019-01-08T16:42:53
2019-01-08T16:42:53
151,070,972
0
0
MIT
2018-12-03T11:10:03
2018-10-01T10:26:28
C++
UTF-8
C++
false
false
42,536
h
// Copyright (c) 2006 Tel-Aviv University (Israel). // All rights reserved. // // This file is part of CGAL (www.cgal.org). // 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. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL$ // $Id$ // // Author(s) : Ron Wein <wein@post.tau.ac.il> #ifndef CGAL_ENVELOPE_DIVIDE_AND_CONQUER_2_IMPL_H #define CGAL_ENVELOPE_DIVIDE_AND_CONQUER_2_IMPL_H #include <CGAL/license/Envelope_2.h> /*! \file * Definitions of the functions of the Envelope_divide_and_conquer_2 class. */ #include <boost/optional.hpp> namespace CGAL { // --------------------------------------------------------------------------- // Construct the lower/upper envelope of the given list of non-vertical curves. // template <class Traits, class Diagram> void Envelope_divide_and_conquer_2<Traits,Diagram>:: _construct_envelope_non_vertical(Curve_pointer_iterator begin, Curve_pointer_iterator end, Envelope_diagram_1& out_d) { out_d.clear(); if (begin == end) return; // Check if the range contains just a single curve. Curve_pointer_iterator iter = begin; ++iter; if (iter == end) { // Construct a singleton diagram, which matches a single curve. _construct_singleton_diagram(*(*begin), out_d); } else { // Divide the given range of curves into two. std::size_t size = std::distance(begin, end); Curve_pointer_iterator div_it = begin; std::advance(div_it, size / 2); // Construct the diagrams (envelopes) for the two sub-ranges recursively // and then merge the two diagrams to obtain the result. Envelope_diagram_1 d1; Envelope_diagram_1 d2; _construct_envelope_non_vertical(begin, div_it, d1); _construct_envelope_non_vertical(div_it, end, d2); _merge_envelopes(d1, d2, out_d); // Print the minimization diagram. /* RWRW: Edge_const_handle e = out_d.leftmost(); Vertex_const_handle v; std::cout << "The diagram: "; while (e != out_d.rightmost()) { if (! e->is_empty()) std::cout << e->curve() << " "; else std::cout << "[empty]" << " "; v = e->right(); std::cout << "(" << v->point() << ") "; e = v->right(); } std::cout << "[empty]" << std::endl; */ } return; } // --------------------------------------------------------------------------- // Construct a singleton diagram, which matches a single curve. // template <class Traits, class Diagram> void Envelope_divide_and_conquer_2<Traits,Diagram>:: _construct_singleton_diagram(const X_monotone_curve_2& cv, Envelope_diagram_1& out_d) { CGAL_assertion(out_d.leftmost() == out_d.rightmost()); CGAL_assertion(out_d.leftmost()->is_empty()); // Check if the given curve is bounded from the left and from the right. if (traits->parameter_space_in_x_2_object()(cv, ARR_MIN_END) != ARR_INTERIOR) { if (traits->parameter_space_in_x_2_object()(cv, ARR_MAX_END) != ARR_INTERIOR) { // The curve is defined over (-oo, oo), so its diagram contains // only a single edge. out_d.leftmost()->add_curve(cv); return; } // The curve is defined over (-oo, x], where x is finite. // Create a vertex and associate it with the right endpoint of cv. CGAL_precondition (traits->parameter_space_in_y_2_object()(cv, ARR_MAX_END) == ARR_INTERIOR); Vertex_handle v = out_d.new_vertex(traits->construct_max_vertex_2_object()(cv)); Edge_handle e_right = out_d.new_edge(); v->add_curve(cv); v->set_left(out_d.leftmost()); v->set_right(e_right); // The leftmost edge is associated with cv, and the rightmost is empty. out_d.leftmost()->add_curve(cv); out_d.leftmost()->set_right(v); e_right->set_left(v); out_d.set_rightmost(e_right); return; } if (traits->parameter_space_in_x_2_object()(cv, ARR_MAX_END) != ARR_INTERIOR) { // The curve is defined over [x, +oo), where x is finite. // Create a vertex and associate it with the left endpoint of cv. CGAL_precondition (traits->parameter_space_in_y_2_object()(cv, ARR_MIN_END) == ARR_INTERIOR); Vertex_handle v = out_d.new_vertex(traits->construct_min_vertex_2_object()(cv)); Edge_handle e_left = out_d.new_edge(); v->add_curve(cv); v->set_left(e_left); v->set_right(out_d.rightmost()); // The rightmost edge is associated with cv, and the leftmost is empty. out_d.rightmost()->add_curve(cv); out_d.rightmost()->set_left(v); e_left->set_right(v); out_d.set_leftmost(e_left); return; } // If we reached here, the curve is defined over a bounded x-range. // We therefore create the following diagram: // // (empty) v1 e v2 (empty) // -oo -------------(+)============(+)------------ +oo // CGAL_precondition (traits->parameter_space_in_y_2_object()(cv, ARR_MIN_END) == ARR_INTERIOR); CGAL_precondition (traits->parameter_space_in_y_2_object()(cv, ARR_MAX_END) == ARR_INTERIOR); Vertex_handle v1 = out_d.new_vertex(traits->construct_min_vertex_2_object()(cv)); Vertex_handle v2 = out_d.new_vertex(traits->construct_max_vertex_2_object()(cv)); Edge_handle e_left = out_d.new_edge(); Edge_handle e_right = out_d.new_edge(); Edge_handle e = out_d.leftmost(); v1->add_curve(cv); v1->set_left(e_left); v1->set_right(e); v2->add_curve(cv); v2->set_left(e); v2->set_right(e_right); e->add_curve(cv); e->set_left(v1); e->set_right(v2); e_left->set_right(v1); e_right->set_left(v2); out_d.set_leftmost(e_left); out_d.set_rightmost(e_right); return; } // --------------------------------------------------------------------------- // Merge two minimization (or maximization) diagrams. // template <class Traits, class Diagram> void Envelope_divide_and_conquer_2<Traits,Diagram>:: _merge_envelopes(const Envelope_diagram_1& d1, const Envelope_diagram_1& d2, Envelope_diagram_1& out_d) { Edge_const_handle e1 = d1.leftmost(); bool is_leftmost1 = true; Vertex_const_handle v1 = Vertex_const_handle(); Edge_const_handle e2 = d2.leftmost(); bool is_leftmost2 = true; Vertex_const_handle v2 = Vertex_const_handle(); Vertex_const_handle next_v = Vertex_const_handle(); bool next_exists = true; Comparison_result res_v = EQUAL; bool same_x = false; do { // Locate the vertex that has smaller x-coordinate between v1 and v2. // If both have the same x-ccordinate, find the one that should be in // the envelope. same_x = false; if (e1 == d1.rightmost()) { if (e2 == d2.rightmost()) { // Both current edges do not have a vertex to their right. next_exists = false; } else { // e1 is not bounded from the right while e2 is. v2 = e2->right(); next_v = v2; res_v = LARGER; } } else if (e2 == d2.rightmost()) { // e2 is not bounded from the right while e1 is. v1 = e1->right(); next_v = v1; res_v = SMALLER; } else { v1 = e1->right(); v2 = e2->right(); res_v = _compare_vertices(v1, v2, same_x); next_v = (res_v == SMALLER) ? v1 : v2; } // Check if the current edges represent empty intervals or not. if (! e1->is_empty() && ! e2->is_empty()) { // Both edges are not empty, and there are curves defined on them. _merge_two_intervals(e1, is_leftmost1, e2, is_leftmost2, next_v, next_exists, res_v, out_d); } else if (! e1->is_empty() && e2->is_empty()) { // e1 is not empty but e2 is empty: _merge_single_interval(e1, e2, next_v, next_exists, res_v, out_d); } else if (e1->is_empty() && ! e2->is_empty()) { // e1 is empty and e2 is not empty: _merge_single_interval(e2, e1, next_v, next_exists, CGAL::opposite(res_v), out_d); } else { // Both edges are empty: append an empty edge to out_d: if (next_exists) { Vertex_handle new_v = _append_vertex(out_d, next_v->point(), e1); switch(res_v) { case SMALLER: new_v->add_curves(v1->curves_begin(), v1->curves_end()); break; case LARGER: new_v->add_curves(v2->curves_begin(), v2->curves_end()); break; case EQUAL: new_v->add_curves(v1->curves_begin(), v1->curves_end()); new_v->add_curves(v2->curves_begin(), v2->curves_end()); break; } } } // Proceed to the next diagram edge(s), if possible. if (next_exists) { // Check if we should proceed on d1 or on d2. // \todo: we do not need 3 cases, only two. if (res_v == SMALLER) { e1 = v1->right(); is_leftmost1 = false; if (same_x) { e2 = v2->right(); is_leftmost2 = false; } } else if (res_v == LARGER) { e2 = v2->right(); is_leftmost2 = false; if (same_x) { e1 = v1->right(); is_leftmost1 = false; } } else { e1 = v1->right(); is_leftmost1 = false; e2 = v2->right(); is_leftmost2 = false; } } } while (next_exists); return; } // --------------------------------------------------------------------------- // Compare two diagram vertices. // template <class Traits, class Diagram> Comparison_result Envelope_divide_and_conquer_2<Traits,Diagram>:: _compare_vertices(Vertex_const_handle v1, Vertex_const_handle v2, bool& same_x) const { Comparison_result res = traits->compare_x_2_object()(v1->point(), v2->point()); if (res != EQUAL) { same_x = false; return (res); } else { same_x = true; } // In case the x-coordinates of the two vertices are equal: res = traits->compare_xy_2_object()(v1->point(), v2->point()); // In case of upper envlope we take the opposite result if (env_type == UPPER) return CGAL::opposite(res); return res; } // --------------------------------------------------------------------------- // Deal with an interval which is non-empty in one of the merged diagrams and // empty in the other. // template <class Traits, class Diagram> void Envelope_divide_and_conquer_2<Traits,Diagram>:: _merge_single_interval(Edge_const_handle e, Edge_const_handle other_edge, Vertex_const_handle v, bool v_exists, Comparison_result origin_of_v, Envelope_diagram_1& out_d) { if (! v_exists) { // The non-empty edge e is unbounded from the right, so we simply have // to update the rightmost edge in out_d. out_d.rightmost()->add_curves(e->curves_begin(), e->curves_end()); return; } Vertex_handle new_v; if (origin_of_v == SMALLER) { // The non-empty edge ends at v, so we simply insert it to out_d. new_v = _append_vertex(out_d, v->point(), e); new_v->add_curves(v->curves_begin(), v->curves_end()); return; } if (origin_of_v == EQUAL) // the edges have vertices at the same place. { new_v = _append_vertex(out_d, v->point(), e); new_v->add_curves(e->right()->curves_begin(), e->right()->curves_end()); new_v->add_curves(other_edge->right()->curves_begin(), other_edge->right()->curves_end()); return; } // If v is not on e, we should insert it to the merged diagram only if it // is below (or above, in case of an upper envelope) the curves of e. Comparison_result res = traits->compare_y_at_x_2_object()(v->point(), e->curve()); if ((res == EQUAL) || (env_type == LOWER && res == SMALLER) || (env_type == UPPER && res == LARGER)) { new_v = _append_vertex(out_d, v->point(), e); new_v->add_curves(v->curves_begin(), v->curves_end()); if (res == EQUAL) { // In case of equality, append e's curves to those of the new vertex. new_v->add_curves(e->curves_begin(), e->curves_end()); } } } //! \brief Functions that should be on Arr_traits_adaptor. /*@{*/ //! Compare the $y$-coordinates of two curves at their endpoints /*! The function compares the $y$ values of two curves with a joint range of $x$ values, at the end of the joint range. \param xcv1 The first curve \param xcv2 The second curve \param curve_end ARR_MIN_END - compare the $y$ value of the smaller endpoint, ARR_MAX_END - compare the $y$ value of the larger endpoint. \pre The two $x$-monotone curves need to have a partially overlapping $x$-ranges. \return \todo Move it to Arr_traits_adaptor ? */ template <class Traits, class Diagram> Comparison_result Envelope_divide_and_conquer_2<Traits,Diagram>:: compare_y_at_end(const X_monotone_curve_2& xcv1, const X_monotone_curve_2& xcv2, Arr_curve_end curve_end) const { CGAL_precondition(traits->is_in_x_range_2_object()(xcv1, xcv2)); typedef typename Traits::Compare_xy_2 Compare_xy_2; typedef typename Traits::Compare_y_at_x_2 Compare_y_at_x_2; typedef typename Traits::Construct_min_vertex_2 Construct_min_vertex_2; typedef typename Traits::Construct_max_vertex_2 Construct_max_vertex_2; Compare_y_at_x_2 compare_y_at_x = traits->compare_y_at_x_2_object(); Construct_min_vertex_2 min_vertex = traits->construct_min_vertex_2_object(); Construct_max_vertex_2 max_vertex = traits->construct_max_vertex_2_object(); // First check whether any of the curves is defined at x boundary. const Arr_parameter_space ps_x1 = traits->parameter_space_in_x_2_object()(xcv1, curve_end); const Arr_parameter_space ps_x2 = traits->parameter_space_in_x_2_object()(xcv2, curve_end); Comparison_result res; if (ps_x1 != ARR_INTERIOR) { if (ps_x2 != ARR_INTERIOR) { // Compare the relative position of the curves at x boundary. return (traits->compare_y_near_boundary_2_object()(xcv1, xcv2, curve_end)); } // Check if the left end of xcv2 lies at y boundary. const Arr_parameter_space ps_y2 = traits->parameter_space_in_y_2_object()(xcv2, curve_end); if (ps_y2 == ARR_BOTTOM_BOUNDARY) return (LARGER); // xcv2 is obviously below xcv1. else if (ps_y2 == ARR_TOP_BOUNDARY) return (SMALLER); // xcv2 is obviously above xcv1. // Compare the position of the left end of xcv2 (which is a normal // point) to xcv1. res = (curve_end == ARR_MIN_END) ? compare_y_at_x(min_vertex(xcv2), xcv1) : compare_y_at_x(max_vertex(xcv2), xcv1); // Swap the result. return CGAL::opposite(res); } else if (ps_x2 != ARR_INTERIOR) { // Check if the left end of xcv1 lies at y boundary. const Arr_parameter_space ps_y1 = traits->parameter_space_in_y_2_object() (xcv1, curve_end); if (ps_y1 == ARR_BOTTOM_BOUNDARY) return (SMALLER); // xcv1 is obviously below xcv2. else if (ps_y1 == ARR_TOP_BOUNDARY) return (LARGER); // xcv1 is obviously above xcv2. // Compare the position of the left end of xcv1 (which is a normal // point) to xcv2. res = (curve_end == ARR_MIN_END) ? compare_y_at_x(min_vertex(xcv1), xcv2) : compare_y_at_x(max_vertex(xcv1), xcv2); return (res); } // Check if the left curve end lies at y = +/- oo. const Arr_parameter_space ps_y1 = traits->parameter_space_in_y_2_object()(xcv1, curve_end); const Arr_parameter_space ps_y2 = traits->parameter_space_in_y_2_object()(xcv2, curve_end); Comparison_result l_res; if (ps_y1 != ARR_INTERIOR) { if (ps_y2 != ARR_INTERIOR) { // The curve ends have boundary conditions with oposite signs in y, // we readily know their relative position (recall that they do not // instersect). if ((ps_y1 == ARR_BOTTOM_BOUNDARY) && (ps_y2 == ARR_TOP_BOUNDARY)) return (SMALLER); else if ((ps_y1 == ARR_TOP_BOUNDARY) && (ps_y2 == ARR_BOTTOM_BOUNDARY)) return (LARGER); // Both curves have vertical asymptotes with the same sign in y. // Check which asymptote is the rightmost. Note that in this case // the vertical asymptotes cannot be equal. l_res = traits->compare_x_curve_ends_2_object()(xcv1, curve_end, xcv2, curve_end); CGAL_assertion(l_res != EQUAL); if (ps_y1 == ARR_TOP_BOUNDARY) return (l_res); else return CGAL::opposite(l_res); } // xcv1 has a vertical asymptote and xcv2 has a normal left endpoint. // Compare the x-positions of this endpoint and the asymptote. const Point_2& left2 = (curve_end == ARR_MIN_END) ? min_vertex(xcv2) : max_vertex(xcv2); l_res = traits->compare_x_point_curve_end_2_object()(left2, xcv1, curve_end); if (l_res == LARGER) { // left2 lies in the x-range of xcv1, so it is safe to compare: res = compare_y_at_x(left2, xcv1); return CGAL::opposite(res); } else // xcv1 is below or above xcv2. return ((ps_y1 == ARR_BOTTOM_BOUNDARY) ? SMALLER : LARGER); } else if (ps_y2 != ARR_INTERIOR) { // xcv2 has a vertical asymptote and xcv1 has a normal left endpoint. // Compare the x-positions of this endpoint and the asymptote. const Point_2& left1 = (curve_end == ARR_MIN_END) ? min_vertex(xcv1) : max_vertex(xcv1); l_res = traits->compare_x_point_curve_end_2_object()(left1, xcv2, curve_end); return ((l_res == LARGER) ? // left1 lies in the x-range of xcv2, so it is safe to compare: (compare_y_at_x(left1, xcv2)) : ((ps_y2 == ARR_BOTTOM_BOUNDARY) ? LARGER : SMALLER)); } // In this case we compare two normal points. Compare_xy_2 compare_xy = traits->compare_xy_2_object(); // Get the left endpoints of xcv1 and xcv2. const Point_2& left1 = (curve_end == ARR_MIN_END) ? min_vertex(xcv1) : max_vertex(xcv1); const Point_2& left2 = (curve_end == ARR_MIN_END) ? min_vertex(xcv2) : max_vertex(xcv2); // Locate the rightmost point of left1 and left2 and compare its position // to the other curve. l_res = compare_xy(left1, left2); return ((l_res != SMALLER) ? // left1 is in the x-range of xcv2: compare_y_at_x(left1, xcv2) : // left2 is in the x-range of xcv1: CGAL::opposite(compare_y_at_x(left2, xcv1))); } /*@}*/ // --------------------------------------------------------------------------- // Merge two non-empty intervals into the merged diagram. // template <class Traits, class Diagram> void Envelope_divide_and_conquer_2<Traits,Diagram>:: _merge_two_intervals(Edge_const_handle e1, bool is_leftmost1, Edge_const_handle e2, bool is_leftmost2, Vertex_const_handle v, bool v_exists, Comparison_result origin_of_v, Envelope_diagram_1& out_d) { typedef std::pair<Point_2, typename Traits::Multiplicity> Intersection_point; Comparison_result current_res; bool equal_at_v = false; // Get the relative position of two curves associated with e1 and e2 // at the rightmost of the left endpoints of e1 and e2. current_res = compare_y_at_end(e1->curve(), e2->curve(), ARR_MIN_END); // Flip the result in case of an upper envelope. if (env_type == UPPER) current_res = CGAL::opposite(current_res); // Use the current rightmost of the two left vertices as a reference point. // This is the rightmost vertex in the current minimization diagram (out_d). // The intersection points/curves that interest us are the ones in // [v_leftmost, v]. // Without using make_optional we get a "maybe uninitialized" warning with gcc -Wall boost::optional<Vertex_const_handle> v_leftmost = boost::make_optional(false, Vertex_const_handle()); if (is_leftmost1 == true) { if (is_leftmost2 == false) v_leftmost = e2->left(); } else { if (is_leftmost2 == true) v_leftmost = e1->left(); else { if ((traits->compare_xy_2_object()(e1->left()->point(), e2->left()->point()) == LARGER)) v_leftmost = e1->left(); else v_leftmost = e2->left(); } } // Find the next intersection of the envelopes to the right of the current // rightmost point in the merged diagram. // \todo Use the faster object_cast. std::list<CGAL::Object> objects; CGAL::Object obj; const X_monotone_curve_2* intersection_curve; const Intersection_point* intersection_point; traits->intersect_2_object()(e1->curve(), e2->curve(), std::back_inserter(objects)); while (! objects.empty()) { // Pop the xy-lexicographically smallest intersection object. obj = objects.front(); objects.pop_front(); if ((intersection_point = CGAL::object_cast<Intersection_point>(&obj)) != NULL) { // We have a simple intersection point. bool is_in_x_range = true; // true if the intersection point is to the // right of v_leftmost. // check if we are before the leftmost point. if (v_leftmost && traits->compare_xy_2_object() (intersection_point->first, (*v_leftmost)->point()) != LARGER) { // The point is to the left of the current rightmost vertex in out_d, // so we skip it and continue examining the next intersections. // However, we update the last intersection point observed. is_in_x_range = false; } // check if we arrived at the rightmost point (stop if indeed we are // there). if (is_in_x_range && v_exists) { Comparison_result res = traits->compare_xy_2_object() (intersection_point->first, v->point()); // v is an intersection points, so both curves are equal there: if (res == EQUAL) equal_at_v = true; // We passed the next vertex, so we can stop here. if (res == LARGER) break; } // Create a new vertex in the output diagram that corrsponds to the // current intersection point. if (is_in_x_range) { CGAL_assertion(current_res != EQUAL); Vertex_handle new_v = (current_res == SMALLER) ? _append_vertex(out_d, intersection_point->first, e1) : _append_vertex(out_d, intersection_point->first, e2); // if we are at v, then this is a special case that is handled after // the loop. We need to add the curves from the original vertices. if (equal_at_v == false) { // Note that the new vertex is incident to all curves in e1 and in e2. new_v->add_curves(e1->curves_begin(), e1->curves_end()); new_v->add_curves(e2->curves_begin(), e2->curves_end()); } // Update the handle to the rightmost vertex in the output diagram. v_leftmost = new_v; } // Update the relative position of the two curves, which is their // order immediately to the right of their last observed intersection // point. // Get the curve order immediately to the right of the intersection // point. Note that in case of even (non-zero) multiplicity the order // remains the same. if ((current_res != EQUAL) && (intersection_point->second % 2 == 1)) { // Odd multiplicity: flip the current comparison result. current_res = CGAL::opposite(current_res); } // if we are at v, then we may not be able to call compare_y_at_x_right_2. else if (((intersection_point->second == 0) || (current_res == EQUAL)) && (equal_at_v == false)) { // The multiplicity is unknown, so we have to compare the curves to // the right of their intersection point. current_res = traits->compare_y_at_x_right_2_object()(e1->curve(), e2->curve(), intersection_point->first); // Flip the result in case of an upper envelope. if (env_type == UPPER) current_res = CGAL::opposite (current_res); } } else { // We have an x-monotone curve representing an overlap of the two // curves. intersection_curve = CGAL::object_cast<X_monotone_curve_2>(&obj); if (intersection_curve == NULL) CGAL_error_msg("unrecognized intersection object."); // Get the endpoints of the overlapping curves. const bool has_left = (traits->parameter_space_in_x_2_object() (*intersection_curve, ARR_MIN_END) == ARR_INTERIOR); const bool has_right = (traits->parameter_space_in_x_2_object() (*intersection_curve, ARR_MAX_END) == ARR_INTERIOR); Point_2 p_left, p_right; if (has_left) p_left = traits->construct_min_vertex_2_object()(*intersection_curve); if (has_right) p_right = traits->construct_max_vertex_2_object()(*intersection_curve); bool is_in_x_range = true; // Check if the overlapping curve is not relevant to our range. if (v_leftmost && has_right && (traits->compare_xy_2_object()(p_right, (*v_leftmost)->point()) != LARGER)) { // The right point of the overlappinf curve is to the left of the // current rightmost vertex in out_d, so we skip it and continue // examining the next intersections. // However, we update the last intersection point observed. is_in_x_range = false; } if (is_in_x_range && v_exists && has_left) { Comparison_result res = traits->compare_xy_2_object()(p_left, v->point()); // v is an intersection points, so both curves are equal there: if (res == EQUAL) equal_at_v = true; // We passed the next vertex, so we can stop here. if (res == LARGER) break; } // There is an overlap between the range [u, v] and intersection_curve. if (is_in_x_range && has_left && (! v_leftmost || (traits->compare_xy_2_object()(p_left, (*v_leftmost)->point()) == LARGER))) { // Create an output edge that represent the portion of [u, v] to the // left of the overlapping curve. CGAL_assertion(current_res != EQUAL); Vertex_handle new_v = (current_res == SMALLER) ? _append_vertex(out_d, p_left, e1) : _append_vertex(out_d, p_left, e2); // if we are at v, then this is a special case that is handled after // the loop. We need to add the curves from the original vertices. if (equal_at_v == false) { // Note that the new vertex is incident to all curves in e1 and // in e2. new_v->add_curves(e1->curves_begin(), e1->curves_end()); new_v->add_curves(e2->curves_begin(), e2->curves_end()); } // Update the handle to the rightmost vertex in the output diagram. v_leftmost = new_v; } if (is_in_x_range && has_right && (! v_exists || (traits->compare_xy_2_object()(p_right, v->point()) == SMALLER))) { // Create an edge that represents the overlapping curve. Vertex_handle new_v = _append_vertex(out_d, p_right, e1); new_v->left()->add_curves(e2->curves_begin(), e2->curves_end()); // We are not at v becuase p_right is smaller than v. // The special case that we are at v is handled in the next // condition. // If we were at v, then this was a special case that is handled // later. CGAL_assertion(equal_at_v == false); new_v->add_curves(e1->curves_begin(), e1->curves_end()); new_v->add_curves(e2->curves_begin(), e2->curves_end()); // Update the handle to the rightmost vertex in the output diagram. v_leftmost = new_v; } if (has_right == false || (v_exists && traits->compare_xy_2_object()(p_right, v->point()) != SMALLER)) { // The overlapping curves reaches v. if (v_exists) { Vertex_handle new_v = _append_vertex(out_d, v->point(), e1); new_v->left()->add_curves(e2->curves_begin(), e2->curves_end()); } equal_at_v = true; current_res = EQUAL; break; } // We arrive here only if we are not at v and the overlap has a right // endpoint. // Compare the curves to the right of p_right. current_res = traits->compare_y_at_x_right_2_object()(e1->curve(), e2->curve(), p_right); // Flip the result in case of an upper envelope. if (env_type == UPPER) current_res = CGAL::opposite (current_res); } } // End of the traversal over the intersection objects. // Handle the portion after the intersection objects. if (equal_at_v) { CGAL_assertion (v_exists); // v_leftmost should be our vertex at v. // In this case the two curves intersect (or overlap) at v. // We need to add the correct curves to v_leftmost. Vertex_handle v_to_be_updated = out_d.rightmost()->left(); if (origin_of_v == EQUAL) { // If the vertices of the edge are the same, we have to get the // curves from there: v_to_be_updated->add_curves(e1->right()->curves_begin(), e1->right()->curves_end()); v_to_be_updated->add_curves(e2->right()->curves_begin(), e2->right()->curves_end()); } else { // We add the curves from the original vertex and from the edge of the // other diagram. Edge_const_handle e = (origin_of_v == SMALLER) ? e2 : e1; v_to_be_updated->add_curves (v->curves_begin(), v->curves_end()); v_to_be_updated->add_curves (e->curves_begin(), e->curves_end()); } return; } if (! v_exists) { // Both edges are unbounded from the right, so we simply have // to update the rightmost edge in out_d. switch (current_res) { case SMALLER: out_d.rightmost()->add_curves(e1->curves_begin(), e1->curves_end()); return; case LARGER: out_d.rightmost()->add_curves(e2->curves_begin(), e2->curves_end()); return; case EQUAL: out_d.rightmost()->add_curves(e1->curves_begin(), e1->curves_end()); out_d.rightmost()->add_curves(e2->curves_begin(), e2->curves_end()); return; default: CGAL_error_msg("should not reach here."); return; } } // origin_of_v could be EQUAL but the curves do not intersect. // This is because of the fact that v could be the endpoint of the NEXT // curve (which is lower than the currrent curve. The second diagram, however, // has a curve that ends at v. // For example: // First diagram is the segment: [(0, -1), (1, 0)] // Second diagram of the two segments: [(0, 0), (1, 1)], [(1, 0), (2, 1)] // Check if we need to insert v into the diagram. if (current_res == SMALLER) { // The final part of the interval is taken from e1. Vertex_handle new_v; if (origin_of_v == SMALLER) { // In case v is also from e1, append it to the merged diagram. new_v = _append_vertex(out_d, v->point(), e1); new_v->add_curves(v->curves_begin(), v->curves_end()); } else { // if origin_of_v is EQUAL then the two diagram have a vertex at // exact same place. if (origin_of_v == EQUAL) { new_v = _append_vertex(out_d, v->point(), e1); new_v->add_curves(v->curves_begin(), v->curves_end()); // adding the curves of the vertex of the first diagram (vertices are // equal...) new_v->add_curves(e1->right()->curves_begin(), e1->right()->curves_end()); } else { // If v is from e2, check if it below (or above, in case of an upper // envelope) cv1 to insert it. const Comparison_result res = traits->compare_y_at_x_2_object()(v->point(), e1->curve()); if (res == EQUAL || ((env_type == LOWER) && (res == SMALLER)) || ((env_type == UPPER) && (res == LARGER))) { new_v = _append_vertex(out_d, v->point(), e1); new_v->add_curves(v->curves_begin(), v->curves_end()); if (res == EQUAL) new_v->add_curves(e1->curves_begin(), e1->curves_end()); } } } } else { // The final part of the interval is taken from e2. Vertex_handle new_v; if (origin_of_v != SMALLER) { // In case v is also from e2, append it to the merged diagram. new_v = _append_vertex(out_d, v->point(), e2); new_v->add_curves(v->curves_begin(), v->curves_end()); // if origin_of_v is EQUAL then the two diagram have a vertex at // exact same place. if (origin_of_v == EQUAL) { // adding the curves of the vertex of the first diagram (vertices are // equal...) new_v->add_curves(e1->right()->curves_begin(), e1->right()->curves_end()); } } else { // If v is from e1, check if it below (or above, in case of an upper // envelope) cv2 to insert it. const Comparison_result res = traits->compare_y_at_x_2_object()(v->point(), e2->curve()); if (res == EQUAL || ((env_type == LOWER) && (res == SMALLER)) || ((env_type == UPPER) && (res == LARGER))) { new_v = _append_vertex(out_d, v->point(), e2); new_v->add_curves(v->curves_begin(), v->curves_end()); if (res == EQUAL) new_v->add_curves(e2->curves_begin(), e2->curves_end()); } } } return; } // --------------------------------------------------------------------------- // Append a vertex to the given diagram. // template <class Traits, class Diagram> typename Envelope_divide_and_conquer_2<Traits,Diagram>::Vertex_handle Envelope_divide_and_conquer_2<Traits,Diagram>:: _append_vertex(Envelope_diagram_1& diag, const Point_2& p, Edge_const_handle e) { // Create the new vertex and the new edge. Vertex_handle new_v = diag.new_vertex(p); Edge_handle new_e = diag.new_edge(); if (! e->is_empty()) new_e->add_curves(e->curves_begin(), e->curves_end()); // Connect the new vertex. new_v->set_left(new_e); new_v->set_right(diag.rightmost()); if (diag.leftmost() != diag.rightmost()) { // The diagram is not empty. Connect the new edge to the left of the // rightmost edge of the diagram. new_e->set_right(new_v); new_e->set_left(diag.rightmost()->left()); diag.rightmost()->left()->set_right(new_e); diag.rightmost()->set_left(new_v); } else { // The diagram is empty: Make the new edge the leftmost. new_e->set_right(new_v); diag.set_leftmost(new_e); diag.rightmost()->set_left(new_v); } return (new_v); } // --------------------------------------------------------------------------- // Merge the vertical segments into the envelope given as a minimization // (or maximization) diagram. // template <class Traits, class Diagram> void Envelope_divide_and_conquer_2<Traits,Diagram>:: _merge_vertical_segments(Curve_pointer_vector& vert_vec, Envelope_diagram_1& out_d) { // Sort the vertical segments by their increasing x-coordinate. Less_vertical_segment les_vert(traits); std::sort(vert_vec.begin(), vert_vec.end(), les_vert); // Proceed on the diagram and on the sorted sequence of vertical segments // and merge them into the diagram. typename Traits_adaptor_2::Compare_x_2 comp_x = traits->compare_x_2_object(); typename Traits_adaptor_2::Compare_xy_2 comp_xy = traits->compare_xy_2_object(); typename Traits_adaptor_2::Compare_y_at_x_2 comp_y_at_x = traits->compare_y_at_x_2_object(); typename Traits_adaptor_2::Construct_min_vertex_2 min_vertex = traits->construct_min_vertex_2_object(); typename Traits_adaptor_2::Construct_max_vertex_2 max_vertex = traits->construct_max_vertex_2_object(); Edge_handle e = out_d.leftmost(); Vertex_handle v = Vertex_handle(); Curve_pointer_iterator iter = vert_vec.begin(); Curve_pointer_iterator next; Comparison_result res; bool in_e_range; bool on_v; Point_2 p; while (iter != vert_vec.end()) { // Check if the current vertical segment is on the x-range of the current // edge. if (e != out_d.rightmost()) { // The current edge is not the rightmost one: we compare the x-coordinate // of the vertical segment to its right vertex. v = e->right(); res = comp_x(min_vertex(**iter), v->point()); in_e_range = (res != LARGER); on_v = (res == EQUAL); } else { // This is the rightmost edge, so the vertical segment must lie on its // x-range. in_e_range = true; on_v = false; } // If the current vertical segment is not in the x-range of the current // edge, we proceed to the next edge. if (! in_e_range) { e = v->right(); continue; } // Go over all vertical segments that share the same x-coordinate and // find the one(s) with the smallest endpoint (or largest endpoint, if // we construct an upper envelope). std::list<X_monotone_curve_2> env_cvs; env_cvs.push_back(**iter); next = iter; ++next; while ((next != vert_vec.end()) && (comp_x(min_vertex(**iter), min_vertex(**next)) == EQUAL)) { if (env_type == LOWER) { // Compare the lower endpoints of both curves. res = comp_xy(min_vertex(env_cvs.front()), min_vertex(**next)); // Update the list of vertical segments with minimal endpoints as // necessary. if (res == EQUAL) { env_cvs.push_back(**next); } if (res == LARGER) { env_cvs.clear(); env_cvs.push_back(**next); } } else { // Compare the upper endpoints of both curves. res = comp_xy(max_vertex(env_cvs.front()), max_vertex(**next)); // Update the list of vertical segments with maximal endpoints as // necessary. if (res == EQUAL) { env_cvs.push_back(**next); } if (res == SMALLER) { env_cvs.clear(); env_cvs.push_back(**next); } } ++next; } // Compare the endpoint to the diagram feature. p = (env_type == LOWER) ? min_vertex(env_cvs.front()) : max_vertex(env_cvs.front()); if (on_v) { // Compare p to the current vertex. res = comp_xy(p, v->point()); if (res == EQUAL) { // Add curves to the current vertex. v->add_curves(env_cvs.begin(), env_cvs.end()); } else if ((env_type == LOWER && res == SMALLER) || (env_type == UPPER && res == LARGER)) { // Replace the list of curves associated with the vertex. v->clear_curves(); v->add_curves(env_cvs.begin(), env_cvs.end()); } } else { // p lies in the interior of the current edge. Vertex_handle new_v; if (e->is_empty()) { // Split the empty edge and associate the new vertex with the // vertical segments. new_v = _split_edge(out_d, p, e); new_v->add_curves(env_cvs.begin(), env_cvs.end()); } else { // Compare p with the current curve. res = comp_y_at_x(p, e->curve()); if (((env_type == LOWER) && (res != LARGER)) || ((env_type == UPPER) && (res != SMALLER))) { new_v = _split_edge(out_d, p, e); new_v->add_curves(env_cvs.begin(), env_cvs.end()); if (res == EQUAL) new_v->add_curve(e->curve()); } } } // Proceed to the next vertical segment with larger x-coordinate. iter = next; } return; } // --------------------------------------------------------------------------- // Split a given diagram edge by inserting a vertex in its interior. // template <class Traits, class Diagram> typename Envelope_divide_and_conquer_2<Traits,Diagram>::Vertex_handle Envelope_divide_and_conquer_2<Traits,Diagram>:: _split_edge(Envelope_diagram_1& diag, const Point_2& p, Edge_handle e) { // Create the new vertex and the new edge. Vertex_handle new_v = diag.new_vertex(p); Edge_handle new_e = diag.new_edge(); // Duplicate the curves container associated with e. if (! e->is_empty()) new_e->add_curves(e->curves_begin(), e->curves_end()); // Connect the new vertex between e and new_e. new_v->set_left(e); new_v->set_right(new_e); new_e->set_left(new_v); if (e != diag.rightmost()) new_e->set_right(e->right()); else diag.set_rightmost(new_e); e->set_right(new_v); // Return the new vertex. return (new_v); } } //namespace CGAL #endif
[ "bodonyiandi94@gmail.com" ]
bodonyiandi94@gmail.com
e4fd19effe81cad3b0a33a42512d69cca1998d6c
9b8591c5f2a54cc74c73a30472f97909e35f2ecf
/source/QtMultimedia/QSoundEffectSlots.h
48e95dcc2fc88aef4e1e2f64c86fab140119f429
[ "MIT" ]
permissive
tnsr1/Qt5xHb
d3a9396a6ad5047010acd5d8459688e6e07e49c2
04b6bd5d8fb08903621003fa5e9b61b831c36fb3
refs/heads/master
2021-05-17T11:15:52.567808
2020-03-26T06:52:17
2020-03-26T06:52:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
967
h
/* Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5 Copyright (C) 2020 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com> */ /* DO NOT EDIT THIS FILE - the content was created using a source code generator */ #ifndef QSOUNDEFFECTSLOTS_H #define QSOUNDEFFECTSLOTS_H #include <QtCore/QObject> #include <QtCore/QCoreApplication> #include <QtCore/QString> #include <QtMultimedia/QSoundEffect> #include "qt5xhb_common.h" #include "qt5xhb_macros.h" #include "qt5xhb_signals.h" class QSoundEffectSlots: public QObject { Q_OBJECT public: QSoundEffectSlots(QObject *parent = 0); ~QSoundEffectSlots(); public slots: void sourceChanged(); void loopCountChanged(); void loopsRemainingChanged(); void volumeChanged(); void mutedChanged(); void loadedChanged(); void playingChanged(); void statusChanged(); void categoryChanged(); }; #endif /* QSOUNDEFFECTSLOTS_H */
[ "5998677+marcosgambeta@users.noreply.github.com" ]
5998677+marcosgambeta@users.noreply.github.com
cc977a92eb98d9fbb552305dd7b7ab0823fe8aa7
c3d30f0dc78b6de32daada4d58dc2f9c1b400ddf
/Anime4KCore/src/CudaACNet.cpp
bcb8cfdaeebe6991e496f6e5c5a56054c5278eb1
[ "MIT" ]
permissive
long007/Anime4KCPP
6e51a570879c7e7760cae4976033c5915e4b24ba
1fab311b3ff6e502b73179e0b99f51062b6ccf00
refs/heads/master
2023-03-13T15:14:38.825555
2021-03-05T15:25:21
2021-03-05T15:25:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,566
cpp
#ifdef ENABLE_CUDA #define DLL #include "CudaACNet.hpp" Anime4KCPP::Cuda::ACNet::ACNet(const Parameters& parameters) : AC(parameters) {} std::string Anime4KCPP::Cuda::ACNet::getInfo() { std::ostringstream oss; oss << AC::getInfo() << "----------------------------------------------" << std::endl << "CUDA Device ID:" << cuGetDeviceID() << std::endl << "Zoom Factor: " << param.zoomFactor << std::endl << "HDN Mode: " << std::boolalpha << param.HDN << std::endl << "HDN Level: " << (param.HDN ? param.HDNLevel : 0) << std::endl << "----------------------------------------------" << std::endl; return oss.str(); } std::string Anime4KCPP::Cuda::ACNet::getFiltersInfo() { std::ostringstream oss; oss << AC::getFiltersInfo() << "----------------------------------------------" << std::endl << "Filter not supported" << std::endl << "----------------------------------------------" << std::endl; return oss.str(); } inline void Anime4KCPP::Cuda::ACNet::runKernelB(const cv::Mat& orgImg, cv::Mat& dstImg) { ACCudaParamACNet cuParam{ orgImg.cols, orgImg.rows,(param.HDN ? param.HDNLevel : 0) }; cuRunKernelACNetB(orgImg.data, dstImg.data, &cuParam); } inline void Anime4KCPP::Cuda::ACNet::runKernelW(const cv::Mat& orgImg, cv::Mat& dstImg) { ACCudaParamACNet cuParam{ orgImg.cols, orgImg.rows,(param.HDN ? param.HDNLevel : 0) }; cuRunKernelACNetW(reinterpret_cast<const unsigned short int*>(orgImg.data), reinterpret_cast<unsigned short int*>(dstImg.data), &cuParam); } inline void Anime4KCPP::Cuda::ACNet::runKernelF(const cv::Mat& orgImg, cv::Mat& dstImg) { ACCudaParamACNet cuParam{ orgImg.cols, orgImg.rows,(param.HDN ? param.HDNLevel : 0) }; cuRunKernelACNetF(reinterpret_cast<const float *>(orgImg.data), reinterpret_cast<float*>(dstImg.data), &cuParam); } void Anime4KCPP::Cuda::ACNet::processYUVImageB() { if (!param.fastMode) { double tmpZf = std::log2(param.zoomFactor); if (tmpZf < 0.0001) tmpZf = 1.0 - 0.0002; int tmpZfUp = std::ceil(tmpZf); cv::Mat tmpY = orgY; dstU = orgU; dstV = orgV; for (int i = 0; i < tmpZfUp; i++) { dstY.create(tmpY.rows * 2, tmpY.cols * 2, CV_8UC1); runKernelB(tmpY, dstY); cv::resize(dstU, dstU, cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); cv::resize(dstV, dstV, cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); tmpY = dstY; } if (tmpZfUp - tmpZf > 0.00001) { double currZf = param.zoomFactor / exp2(tmpZfUp); cv::resize(dstY, dstY, cv::Size(0, 0), currZf, currZf, cv::INTER_AREA); cv::resize(dstU, dstU, cv::Size(0, 0), currZf, currZf, cv::INTER_AREA); cv::resize(dstV, dstV, cv::Size(0, 0), currZf, currZf, cv::INTER_AREA); } } else { if (param.zoomFactor > 2.0) cv::resize(orgY, orgY, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_CUBIC); else if (param.zoomFactor < 2.0) cv::resize(orgY, orgY, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_AREA); dstY.create(orgY.rows * 2, orgY.cols * 2, CV_8UC1); runKernelB(orgY, dstY); cv::resize(orgU, dstU, cv::Size(0, 0), param.zoomFactor, param.zoomFactor, cv::INTER_CUBIC); cv::resize(orgV, dstV, cv::Size(0, 0), param.zoomFactor, param.zoomFactor, cv::INTER_CUBIC); } } void Anime4KCPP::Cuda::ACNet::processRGBImageB() { if (!param.fastMode) { double tmpZf = std::log2(param.zoomFactor); if (tmpZf < 0.0001) tmpZf = 1.0 - 0.0002; int tmpZfUp = std::ceil(tmpZf); cv::Mat tmpImg = orgImg; cv::cvtColor(tmpImg, tmpImg, cv::COLOR_BGR2YUV); std::vector<cv::Mat> yuv(3); cv::split(tmpImg, yuv); tmpImg = yuv[Y]; for (int i = 0; i < tmpZfUp; i++) { dstImg.create(tmpImg.rows * 2, tmpImg.cols * 2, CV_8UC1); runKernelB(tmpImg, dstImg); cv::resize(yuv[U], yuv[U], cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); cv::resize(yuv[V], yuv[V], cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); tmpImg = dstImg; } cv::merge(std::vector<cv::Mat>{ dstImg, yuv[U], yuv[V] }, dstImg); cv::cvtColor(dstImg, dstImg, cv::COLOR_YUV2BGR); if (tmpZfUp - tmpZf > 0.00001) { cv::resize(dstImg, dstImg, cv::Size(W, H), 0, 0, cv::INTER_AREA); } } else { if (param.zoomFactor > 2.0) cv::resize(orgImg, orgImg, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_CUBIC); else if (param.zoomFactor < 2.0) cv::resize(orgImg, orgImg, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_AREA); cv::cvtColor(orgImg, orgImg, cv::COLOR_BGR2YUV); std::vector<cv::Mat> yuv(3); cv::split(orgImg, yuv); orgImg = yuv[Y]; dstImg.create(orgImg.rows * 2, orgImg.cols * 2, CV_8UC1); runKernelB(orgImg, dstImg); cv::resize(yuv[U], yuv[U], cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); cv::resize(yuv[V], yuv[V], cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); cv::merge(std::vector<cv::Mat>{ dstImg, yuv[U], yuv[V] }, dstImg); cv::cvtColor(dstImg, dstImg, cv::COLOR_YUV2BGR); } } void Anime4KCPP::Cuda::ACNet::processGrayscaleB() { if (!param.fastMode) { double tmpZf = std::log2(param.zoomFactor); if (tmpZf < 0.0001) tmpZf = 1.0 - 0.0002; int tmpZfUp = std::ceil(tmpZf); cv::Mat tmpImg = orgImg; for (int i = 0; i < tmpZfUp; i++) { dstImg.create(tmpImg.rows * 2, tmpImg.cols * 2, CV_8UC1); runKernelB(tmpImg, dstImg); tmpImg = dstImg; } if (tmpZfUp - tmpZf > 0.00001) { double currZf = param.zoomFactor / exp2(tmpZfUp); cv::resize(dstImg, dstImg, cv::Size(0, 0), currZf, currZf, cv::INTER_AREA); } } else { if (param.zoomFactor > 2.0) cv::resize(orgImg, orgImg, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_CUBIC); else if (param.zoomFactor < 2.0) cv::resize(orgImg, orgImg, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_AREA); dstImg.create(orgImg.rows * 2, orgImg.cols * 2, CV_8UC1); runKernelB(orgImg, dstImg); } } void Anime4KCPP::Cuda::ACNet::processRGBVideoB() { if (!param.fastMode) { double tmpZf = std::log2(param.zoomFactor); if (tmpZf < 0.0001) tmpZf = 1.0 - 0.0002; int tmpZfUp = std::ceil(tmpZf); videoIO->init( [this, tmpZfUp, tmpZf]() { Utils::Frame frame = videoIO->read(); cv::Mat orgFrame = frame.first; cv::Mat dstFrame; cv::Mat tmpFrame = orgFrame; cv::cvtColor(tmpFrame, tmpFrame, cv::COLOR_BGR2YUV); std::vector<cv::Mat> yuv(3); cv::split(tmpFrame, yuv); tmpFrame = yuv[Y]; for (int i = 0; i < tmpZfUp; i++) { dstFrame.create(tmpFrame.rows * 2, tmpFrame.cols * 2, CV_8UC1); runKernelB(tmpFrame, dstFrame); cv::resize(yuv[U], yuv[U], cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); cv::resize(yuv[V], yuv[V], cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); tmpFrame = dstFrame; } cv::merge(std::vector<cv::Mat>{ dstFrame, yuv[U], yuv[V] }, dstFrame); cv::cvtColor(dstFrame, dstFrame, cv::COLOR_YUV2BGR); if (tmpZfUp - tmpZf > 0.00001) { cv::resize(dstFrame, dstFrame, cv::Size(W, H), 0, 0, cv::INTER_AREA); } frame.first = dstFrame; videoIO->write(frame); } , param.maxThreads ).process(); } else { videoIO->init( [this]() { Utils::Frame frame = videoIO->read(); cv::Mat orgFrame = frame.first; cv::Mat dstFrame; if (param.zoomFactor > 2.0) cv::resize(orgFrame, orgFrame, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_CUBIC); else if (param.zoomFactor < 2.0) cv::resize(orgFrame, orgFrame, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_AREA); cv::cvtColor(orgFrame, orgFrame, cv::COLOR_BGR2YUV); std::vector<cv::Mat> yuv(3); cv::split(orgFrame, yuv); orgFrame = yuv[Y]; dstFrame.create(orgFrame.rows * 2, orgFrame.cols * 2, CV_8UC1); runKernelB(orgFrame, dstFrame); cv::resize(yuv[U], yuv[U], cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); cv::resize(yuv[V], yuv[V], cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); cv::merge(std::vector<cv::Mat>{ dstFrame, yuv[U], yuv[V] }, dstFrame); cv::cvtColor(dstFrame, dstFrame, cv::COLOR_YUV2BGR); frame.first = dstFrame; videoIO->write(frame); } , param.maxThreads ).process(); } } void Anime4KCPP::Cuda::ACNet::processYUVImageW() { if (!param.fastMode) { double tmpZf = std::log2(param.zoomFactor); if (tmpZf < 0.0001) tmpZf = 1.0 - 0.0002; int tmpZfUp = std::ceil(tmpZf); cv::Mat tmpY = orgY; dstU = orgU; dstV = orgV; for (int i = 0; i < tmpZfUp; i++) { dstY.create(tmpY.rows * 2, tmpY.cols * 2, CV_16UC1); runKernelW(tmpY, dstY); cv::resize(dstU, dstU, cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); cv::resize(dstV, dstV, cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); tmpY = dstY; } if (tmpZfUp - tmpZf > 0.00001) { double currZf = param.zoomFactor / exp2(tmpZfUp); cv::resize(dstY, dstY, cv::Size(0, 0), currZf, currZf, cv::INTER_AREA); cv::resize(dstU, dstU, cv::Size(0, 0), currZf, currZf, cv::INTER_AREA); cv::resize(dstV, dstV, cv::Size(0, 0), currZf, currZf, cv::INTER_AREA); } } else { if (param.zoomFactor > 2.0) cv::resize(orgY, orgY, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_CUBIC); else if (param.zoomFactor < 2.0) cv::resize(orgY, orgY, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_AREA); dstY.create(orgY.rows * 2, orgY.cols * 2, CV_16UC1); runKernelW(orgY, dstY); cv::resize(orgU, dstU, cv::Size(0, 0), param.zoomFactor, param.zoomFactor, cv::INTER_CUBIC); cv::resize(orgV, dstV, cv::Size(0, 0), param.zoomFactor, param.zoomFactor, cv::INTER_CUBIC); } } void Anime4KCPP::Cuda::ACNet::processRGBImageW() { if (!param.fastMode) { double tmpZf = std::log2(param.zoomFactor); if (tmpZf < 0.0001) tmpZf = 1.0 - 0.0002; int tmpZfUp = std::ceil(tmpZf); cv::Mat tmpImg = orgImg; cv::cvtColor(tmpImg, tmpImg, cv::COLOR_BGR2YUV); std::vector<cv::Mat> yuv(3); cv::split(tmpImg, yuv); tmpImg = yuv[Y]; for (int i = 0; i < tmpZfUp; i++) { dstImg.create(tmpImg.rows * 2, tmpImg.cols * 2, CV_16UC1); runKernelW(tmpImg, dstImg); cv::resize(yuv[U], yuv[U], cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); cv::resize(yuv[V], yuv[V], cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); tmpImg = dstImg; } cv::merge(std::vector<cv::Mat>{ dstImg, yuv[U], yuv[V] }, dstImg); cv::cvtColor(dstImg, dstImg, cv::COLOR_YUV2BGR); if (tmpZfUp - tmpZf > 0.00001) { cv::resize(dstImg, dstImg, cv::Size(W, H), 0, 0, cv::INTER_AREA); } } else { if (param.zoomFactor > 2.0) cv::resize(orgImg, orgImg, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_CUBIC); else if (param.zoomFactor < 2.0) cv::resize(orgImg, orgImg, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_AREA); cv::cvtColor(orgImg, orgImg, cv::COLOR_BGR2YUV); std::vector<cv::Mat> yuv(3); cv::split(orgImg, yuv); orgImg = yuv[Y]; dstImg.create(orgImg.rows * 2, orgImg.cols * 2, CV_16UC1); runKernelW(orgImg, dstImg); cv::resize(yuv[U], yuv[U], cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); cv::resize(yuv[V], yuv[V], cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); cv::merge(std::vector<cv::Mat>{ dstImg, yuv[U], yuv[V] }, dstImg); cv::cvtColor(dstImg, dstImg, cv::COLOR_YUV2BGR); } } void Anime4KCPP::Cuda::ACNet::processGrayscaleW() { if (!param.fastMode) { double tmpZf = std::log2(param.zoomFactor); if (tmpZf < 0.0001) tmpZf = 1.0 - 0.0002; int tmpZfUp = std::ceil(tmpZf); cv::Mat tmpImg = orgImg; for (int i = 0; i < tmpZfUp; i++) { dstImg.create(tmpImg.rows * 2, tmpImg.cols * 2, CV_16UC1); runKernelW(tmpImg, dstImg); tmpImg = dstImg; } if (tmpZfUp - tmpZf > 0.00001) { double currZf = param.zoomFactor / exp2(tmpZfUp); cv::resize(dstImg, dstImg, cv::Size(0, 0), currZf, currZf, cv::INTER_AREA); } } else { if (param.zoomFactor > 2.0) cv::resize(orgImg, orgImg, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_CUBIC); else if (param.zoomFactor < 2.0) cv::resize(orgImg, orgImg, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_AREA); dstImg.create(orgImg.rows * 2, orgImg.cols * 2, CV_16UC1); runKernelW(orgImg, dstImg); } } void Anime4KCPP::Cuda::ACNet::processYUVImageF() { if (!param.fastMode) { double tmpZf = std::log2(param.zoomFactor); if (tmpZf < 0.0001) tmpZf = 1.0 - 0.0002; int tmpZfUp = std::ceil(tmpZf); cv::Mat tmpY = orgY; dstU = orgU; dstV = orgV; for (int i = 0; i < tmpZfUp; i++) { dstY.create(tmpY.rows * 2, tmpY.cols * 2, CV_32FC1); runKernelF(tmpY, dstY); cv::resize(dstU, dstU, cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); cv::resize(dstV, dstV, cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); tmpY = dstY; } if (tmpZfUp - tmpZf > 0.00001) { double currZf = param.zoomFactor / exp2(tmpZfUp); cv::resize(dstY, dstY, cv::Size(0, 0), currZf, currZf, cv::INTER_AREA); cv::resize(dstU, dstU, cv::Size(0, 0), currZf, currZf, cv::INTER_AREA); cv::resize(dstV, dstV, cv::Size(0, 0), currZf, currZf, cv::INTER_AREA); } } else { if (param.zoomFactor > 2.0) cv::resize(orgY, orgY, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_CUBIC); else if (param.zoomFactor < 2.0) cv::resize(orgY, orgY, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_AREA); dstY.create(orgY.rows * 2, orgY.cols * 2, CV_32FC1); runKernelF(orgY, dstY); cv::resize(orgU, dstU, cv::Size(0, 0), param.zoomFactor, param.zoomFactor, cv::INTER_CUBIC); cv::resize(orgV, dstV, cv::Size(0, 0), param.zoomFactor, param.zoomFactor, cv::INTER_CUBIC); } } void Anime4KCPP::Cuda::ACNet::processRGBImageF() { if (!param.fastMode) { double tmpZf = std::log2(param.zoomFactor); if (tmpZf < 0.0001) tmpZf = 1.0 - 0.0002; int tmpZfUp = std::ceil(tmpZf); cv::Mat tmpImg = orgImg; cv::cvtColor(tmpImg, tmpImg, cv::COLOR_BGR2YUV); std::vector<cv::Mat> yuv(3); cv::split(tmpImg, yuv); tmpImg = yuv[Y]; for (int i = 0; i < tmpZfUp; i++) { dstImg.create(tmpImg.rows * 2, tmpImg.cols * 2, CV_32FC1); runKernelF(tmpImg, dstImg); cv::resize(yuv[U], yuv[U], cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); cv::resize(yuv[V], yuv[V], cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); tmpImg = dstImg; } cv::merge(std::vector<cv::Mat>{ dstImg, yuv[U], yuv[V] }, dstImg); cv::cvtColor(dstImg, dstImg, cv::COLOR_YUV2BGR); if (tmpZfUp - tmpZf > 0.00001) { cv::resize(dstImg, dstImg, cv::Size(W, H), 0, 0, cv::INTER_AREA); } } else { if (param.zoomFactor > 2.0) cv::resize(orgImg, orgImg, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_CUBIC); else if (param.zoomFactor < 2.0) cv::resize(orgImg, orgImg, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_AREA); cv::cvtColor(orgImg, orgImg, cv::COLOR_BGR2YUV); std::vector<cv::Mat> yuv(3); cv::split(orgImg, yuv); orgImg = yuv[Y]; dstImg.create(orgImg.rows * 2, orgImg.cols * 2, CV_32FC1); runKernelF(orgImg, dstImg); cv::resize(yuv[U], yuv[U], cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); cv::resize(yuv[V], yuv[V], cv::Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC); cv::merge(std::vector<cv::Mat>{ dstImg, yuv[U], yuv[V] }, dstImg); cv::cvtColor(dstImg, dstImg, cv::COLOR_YUV2BGR); } } void Anime4KCPP::Cuda::ACNet::processGrayscaleF() { if (!param.fastMode) { double tmpZf = std::log2(param.zoomFactor); if (tmpZf < 0.0001) tmpZf = 1.0 - 0.0002; int tmpZfUp = std::ceil(tmpZf); cv::Mat tmpImg = orgImg; for (int i = 0; i < tmpZfUp; i++) { dstImg.create(tmpImg.rows * 2, tmpImg.cols * 2, CV_32FC1); runKernelF(tmpImg, dstImg); tmpImg = dstImg; } if (tmpZfUp - tmpZf > 0.00001) { double currZf = param.zoomFactor / exp2(tmpZfUp); cv::resize(dstImg, dstImg, cv::Size(0, 0), currZf, currZf, cv::INTER_AREA); } } else { if (param.zoomFactor > 2.0) cv::resize(orgImg, orgImg, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_CUBIC); else if (param.zoomFactor < 2.0) cv::resize(orgImg, orgImg, cv::Size(0, 0), param.zoomFactor / 2.0, param.zoomFactor / 2.0, cv::INTER_AREA); dstImg.create(orgImg.rows * 2, orgImg.cols * 2, CV_32FC1); runKernelF(orgImg, dstImg); } } Anime4KCPP::Processor::Type Anime4KCPP::Cuda::ACNet::getProcessorType() noexcept { return Processor::Type::Cuda_ACNet; } std::string Anime4KCPP::Cuda::ACNet::getProcessorInfo() { std::ostringstream oss; oss << "Processor type: " << getProcessorType() << std::endl << "Current CUDA devices:" << std::endl << cuGetDeviceInfo(cuGetDeviceID()); return oss.str(); } #endif
[ "TianLin2112@outlook.com" ]
TianLin2112@outlook.com
be91138ee7954dea2129ae4c820d87c2f53e69a1
5664ab66deeecea95313faeea037fa832cca34ce
/modules/perception/fusion/lib/gatekeeper/pbf_gatekeeper/proto/pbf_gatekeeper_config.pb.h
25545e1c7ee3f44f66f74c0c2e0cb99e76fbeeb0
[ "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
Forrest-Z/t1
5d1f8c17dc475394ab4d071a577953289238c9f4
bdacd5398e7f0613e2463b0c2197ba9354f1d3e3
refs/heads/master
2023-08-02T03:58:50.032599
2021-10-08T05:38:10
2021-10-08T05:38:10
null
0
0
null
null
null
null
UTF-8
C++
false
true
31,695
h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: modules/perception/fusion/lib/gatekeeper/pbf_gatekeeper/proto/pbf_gatekeeper_config.proto #ifndef GOOGLE_PROTOBUF_INCLUDED_modules_2fperception_2ffusion_2flib_2fgatekeeper_2fpbf_5fgatekeeper_2fproto_2fpbf_5fgatekeeper_5fconfig_2eproto #define GOOGLE_PROTOBUF_INCLUDED_modules_2fperception_2ffusion_2flib_2fgatekeeper_2fpbf_5fgatekeeper_2fproto_2fpbf_5fgatekeeper_5fconfig_2eproto #include <limits> #include <string> #include <google/protobuf/port_def.inc> #if PROTOBUF_VERSION < 3018000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3018000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/port_undef.inc> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/metadata_lite.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> #define PROTOBUF_INTERNAL_EXPORT_modules_2fperception_2ffusion_2flib_2fgatekeeper_2fpbf_5fgatekeeper_2fproto_2fpbf_5fgatekeeper_5fconfig_2eproto PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; } // namespace internal PROTOBUF_NAMESPACE_CLOSE // Internal implementation detail -- do not use these members. struct TableStruct_modules_2fperception_2ffusion_2flib_2fgatekeeper_2fpbf_5fgatekeeper_2fproto_2fpbf_5fgatekeeper_5fconfig_2eproto { static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_modules_2fperception_2ffusion_2flib_2fgatekeeper_2fpbf_5fgatekeeper_2fproto_2fpbf_5fgatekeeper_5fconfig_2eproto; namespace apollo { namespace perception { namespace fusion { class PbfGatekeeperConfig; struct PbfGatekeeperConfigDefaultTypeInternal; extern PbfGatekeeperConfigDefaultTypeInternal _PbfGatekeeperConfig_default_instance_; } // namespace fusion } // namespace perception } // namespace apollo PROTOBUF_NAMESPACE_OPEN template<> ::apollo::perception::fusion::PbfGatekeeperConfig* Arena::CreateMaybeMessage<::apollo::perception::fusion::PbfGatekeeperConfig>(Arena*); PROTOBUF_NAMESPACE_CLOSE namespace apollo { namespace perception { namespace fusion { // =================================================================== class PbfGatekeeperConfig final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:apollo.perception.fusion.PbfGatekeeperConfig) */ { public: inline PbfGatekeeperConfig() : PbfGatekeeperConfig(nullptr) {} ~PbfGatekeeperConfig() override; explicit constexpr PbfGatekeeperConfig(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); PbfGatekeeperConfig(const PbfGatekeeperConfig& from); PbfGatekeeperConfig(PbfGatekeeperConfig&& from) noexcept : PbfGatekeeperConfig() { *this = ::std::move(from); } inline PbfGatekeeperConfig& operator=(const PbfGatekeeperConfig& from) { CopyFrom(from); return *this; } inline PbfGatekeeperConfig& operator=(PbfGatekeeperConfig&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const PbfGatekeeperConfig& default_instance() { return *internal_default_instance(); } static inline const PbfGatekeeperConfig* internal_default_instance() { return reinterpret_cast<const PbfGatekeeperConfig*>( &_PbfGatekeeperConfig_default_instance_); } static constexpr int kIndexInFileMessages = 0; friend void swap(PbfGatekeeperConfig& a, PbfGatekeeperConfig& b) { a.Swap(&b); } inline void Swap(PbfGatekeeperConfig* other) { if (other == this) return; if (GetOwningArena() == other->GetOwningArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(PbfGatekeeperConfig* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline PbfGatekeeperConfig* New() const final { return new PbfGatekeeperConfig(); } PbfGatekeeperConfig* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<PbfGatekeeperConfig>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const PbfGatekeeperConfig& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom(const PbfGatekeeperConfig& from); private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(PbfGatekeeperConfig* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "apollo.perception.fusion.PbfGatekeeperConfig"; } protected: explicit PbfGatekeeperConfig(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kMinRadarConfidentDistanceFieldNumber = 5, kMaxRadarConfidentAngleFieldNumber = 6, kMinCameraPublishDistanceFieldNumber = 7, kInvisiblePeriodThresholdFieldNumber = 8, kToicThresholdFieldNumber = 9, kUseTrackTimePubStrategyFieldNumber = 10, kPubTrackTimeThreshFieldNumber = 11, kExistenceThresholdFieldNumber = 12, kRadarExistenceThresholdFieldNumber = 13, kPublishIfHasLidarFieldNumber = 1, kPublishIfHasRadarFieldNumber = 2, kPublishIfHasCameraFieldNumber = 3, kUseCamera3DFieldNumber = 4, }; // optional double min_radar_confident_distance = 5; bool has_min_radar_confident_distance() const; private: bool _internal_has_min_radar_confident_distance() const; public: void clear_min_radar_confident_distance(); double min_radar_confident_distance() const; void set_min_radar_confident_distance(double value); private: double _internal_min_radar_confident_distance() const; void _internal_set_min_radar_confident_distance(double value); public: // optional double max_radar_confident_angle = 6; bool has_max_radar_confident_angle() const; private: bool _internal_has_max_radar_confident_angle() const; public: void clear_max_radar_confident_angle(); double max_radar_confident_angle() const; void set_max_radar_confident_angle(double value); private: double _internal_max_radar_confident_angle() const; void _internal_set_max_radar_confident_angle(double value); public: // optional double min_camera_publish_distance = 7; bool has_min_camera_publish_distance() const; private: bool _internal_has_min_camera_publish_distance() const; public: void clear_min_camera_publish_distance(); double min_camera_publish_distance() const; void set_min_camera_publish_distance(double value); private: double _internal_min_camera_publish_distance() const; void _internal_set_min_camera_publish_distance(double value); public: // optional double invisible_period_threshold = 8; bool has_invisible_period_threshold() const; private: bool _internal_has_invisible_period_threshold() const; public: void clear_invisible_period_threshold(); double invisible_period_threshold() const; void set_invisible_period_threshold(double value); private: double _internal_invisible_period_threshold() const; void _internal_set_invisible_period_threshold(double value); public: // optional double toic_threshold = 9; bool has_toic_threshold() const; private: bool _internal_has_toic_threshold() const; public: void clear_toic_threshold(); double toic_threshold() const; void set_toic_threshold(double value); private: double _internal_toic_threshold() const; void _internal_set_toic_threshold(double value); public: // optional bool use_track_time_pub_strategy = 10; bool has_use_track_time_pub_strategy() const; private: bool _internal_has_use_track_time_pub_strategy() const; public: void clear_use_track_time_pub_strategy(); bool use_track_time_pub_strategy() const; void set_use_track_time_pub_strategy(bool value); private: bool _internal_use_track_time_pub_strategy() const; void _internal_set_use_track_time_pub_strategy(bool value); public: // optional int32 pub_track_time_thresh = 11; bool has_pub_track_time_thresh() const; private: bool _internal_has_pub_track_time_thresh() const; public: void clear_pub_track_time_thresh(); ::PROTOBUF_NAMESPACE_ID::int32 pub_track_time_thresh() const; void set_pub_track_time_thresh(::PROTOBUF_NAMESPACE_ID::int32 value); private: ::PROTOBUF_NAMESPACE_ID::int32 _internal_pub_track_time_thresh() const; void _internal_set_pub_track_time_thresh(::PROTOBUF_NAMESPACE_ID::int32 value); public: // optional double existence_threshold = 12; bool has_existence_threshold() const; private: bool _internal_has_existence_threshold() const; public: void clear_existence_threshold(); double existence_threshold() const; void set_existence_threshold(double value); private: double _internal_existence_threshold() const; void _internal_set_existence_threshold(double value); public: // optional double radar_existence_threshold = 13; bool has_radar_existence_threshold() const; private: bool _internal_has_radar_existence_threshold() const; public: void clear_radar_existence_threshold(); double radar_existence_threshold() const; void set_radar_existence_threshold(double value); private: double _internal_radar_existence_threshold() const; void _internal_set_radar_existence_threshold(double value); public: // optional bool publish_if_has_lidar = 1 [default = true]; bool has_publish_if_has_lidar() const; private: bool _internal_has_publish_if_has_lidar() const; public: void clear_publish_if_has_lidar(); bool publish_if_has_lidar() const; void set_publish_if_has_lidar(bool value); private: bool _internal_publish_if_has_lidar() const; void _internal_set_publish_if_has_lidar(bool value); public: // optional bool publish_if_has_radar = 2 [default = true]; bool has_publish_if_has_radar() const; private: bool _internal_has_publish_if_has_radar() const; public: void clear_publish_if_has_radar(); bool publish_if_has_radar() const; void set_publish_if_has_radar(bool value); private: bool _internal_publish_if_has_radar() const; void _internal_set_publish_if_has_radar(bool value); public: // optional bool publish_if_has_camera = 3 [default = true]; bool has_publish_if_has_camera() const; private: bool _internal_has_publish_if_has_camera() const; public: void clear_publish_if_has_camera(); bool publish_if_has_camera() const; void set_publish_if_has_camera(bool value); private: bool _internal_publish_if_has_camera() const; void _internal_set_publish_if_has_camera(bool value); public: // optional bool use_camera_3d = 4 [default = true]; bool has_use_camera_3d() const; private: bool _internal_has_use_camera_3d() const; public: void clear_use_camera_3d(); bool use_camera_3d() const; void set_use_camera_3d(bool value); private: bool _internal_use_camera_3d() const; void _internal_set_use_camera_3d(bool value); public: // @@protoc_insertion_point(class_scope:apollo.perception.fusion.PbfGatekeeperConfig) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; double min_radar_confident_distance_; double max_radar_confident_angle_; double min_camera_publish_distance_; double invisible_period_threshold_; double toic_threshold_; bool use_track_time_pub_strategy_; ::PROTOBUF_NAMESPACE_ID::int32 pub_track_time_thresh_; double existence_threshold_; double radar_existence_threshold_; bool publish_if_has_lidar_; bool publish_if_has_radar_; bool publish_if_has_camera_; bool use_camera_3d_; friend struct ::TableStruct_modules_2fperception_2ffusion_2flib_2fgatekeeper_2fpbf_5fgatekeeper_2fproto_2fpbf_5fgatekeeper_5fconfig_2eproto; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // PbfGatekeeperConfig // optional bool publish_if_has_lidar = 1 [default = true]; inline bool PbfGatekeeperConfig::_internal_has_publish_if_has_lidar() const { bool value = (_has_bits_[0] & 0x00000200u) != 0; return value; } inline bool PbfGatekeeperConfig::has_publish_if_has_lidar() const { return _internal_has_publish_if_has_lidar(); } inline void PbfGatekeeperConfig::clear_publish_if_has_lidar() { publish_if_has_lidar_ = true; _has_bits_[0] &= ~0x00000200u; } inline bool PbfGatekeeperConfig::_internal_publish_if_has_lidar() const { return publish_if_has_lidar_; } inline bool PbfGatekeeperConfig::publish_if_has_lidar() const { // @@protoc_insertion_point(field_get:apollo.perception.fusion.PbfGatekeeperConfig.publish_if_has_lidar) return _internal_publish_if_has_lidar(); } inline void PbfGatekeeperConfig::_internal_set_publish_if_has_lidar(bool value) { _has_bits_[0] |= 0x00000200u; publish_if_has_lidar_ = value; } inline void PbfGatekeeperConfig::set_publish_if_has_lidar(bool value) { _internal_set_publish_if_has_lidar(value); // @@protoc_insertion_point(field_set:apollo.perception.fusion.PbfGatekeeperConfig.publish_if_has_lidar) } // optional bool publish_if_has_radar = 2 [default = true]; inline bool PbfGatekeeperConfig::_internal_has_publish_if_has_radar() const { bool value = (_has_bits_[0] & 0x00000400u) != 0; return value; } inline bool PbfGatekeeperConfig::has_publish_if_has_radar() const { return _internal_has_publish_if_has_radar(); } inline void PbfGatekeeperConfig::clear_publish_if_has_radar() { publish_if_has_radar_ = true; _has_bits_[0] &= ~0x00000400u; } inline bool PbfGatekeeperConfig::_internal_publish_if_has_radar() const { return publish_if_has_radar_; } inline bool PbfGatekeeperConfig::publish_if_has_radar() const { // @@protoc_insertion_point(field_get:apollo.perception.fusion.PbfGatekeeperConfig.publish_if_has_radar) return _internal_publish_if_has_radar(); } inline void PbfGatekeeperConfig::_internal_set_publish_if_has_radar(bool value) { _has_bits_[0] |= 0x00000400u; publish_if_has_radar_ = value; } inline void PbfGatekeeperConfig::set_publish_if_has_radar(bool value) { _internal_set_publish_if_has_radar(value); // @@protoc_insertion_point(field_set:apollo.perception.fusion.PbfGatekeeperConfig.publish_if_has_radar) } // optional bool publish_if_has_camera = 3 [default = true]; inline bool PbfGatekeeperConfig::_internal_has_publish_if_has_camera() const { bool value = (_has_bits_[0] & 0x00000800u) != 0; return value; } inline bool PbfGatekeeperConfig::has_publish_if_has_camera() const { return _internal_has_publish_if_has_camera(); } inline void PbfGatekeeperConfig::clear_publish_if_has_camera() { publish_if_has_camera_ = true; _has_bits_[0] &= ~0x00000800u; } inline bool PbfGatekeeperConfig::_internal_publish_if_has_camera() const { return publish_if_has_camera_; } inline bool PbfGatekeeperConfig::publish_if_has_camera() const { // @@protoc_insertion_point(field_get:apollo.perception.fusion.PbfGatekeeperConfig.publish_if_has_camera) return _internal_publish_if_has_camera(); } inline void PbfGatekeeperConfig::_internal_set_publish_if_has_camera(bool value) { _has_bits_[0] |= 0x00000800u; publish_if_has_camera_ = value; } inline void PbfGatekeeperConfig::set_publish_if_has_camera(bool value) { _internal_set_publish_if_has_camera(value); // @@protoc_insertion_point(field_set:apollo.perception.fusion.PbfGatekeeperConfig.publish_if_has_camera) } // optional bool use_camera_3d = 4 [default = true]; inline bool PbfGatekeeperConfig::_internal_has_use_camera_3d() const { bool value = (_has_bits_[0] & 0x00001000u) != 0; return value; } inline bool PbfGatekeeperConfig::has_use_camera_3d() const { return _internal_has_use_camera_3d(); } inline void PbfGatekeeperConfig::clear_use_camera_3d() { use_camera_3d_ = true; _has_bits_[0] &= ~0x00001000u; } inline bool PbfGatekeeperConfig::_internal_use_camera_3d() const { return use_camera_3d_; } inline bool PbfGatekeeperConfig::use_camera_3d() const { // @@protoc_insertion_point(field_get:apollo.perception.fusion.PbfGatekeeperConfig.use_camera_3d) return _internal_use_camera_3d(); } inline void PbfGatekeeperConfig::_internal_set_use_camera_3d(bool value) { _has_bits_[0] |= 0x00001000u; use_camera_3d_ = value; } inline void PbfGatekeeperConfig::set_use_camera_3d(bool value) { _internal_set_use_camera_3d(value); // @@protoc_insertion_point(field_set:apollo.perception.fusion.PbfGatekeeperConfig.use_camera_3d) } // optional double min_radar_confident_distance = 5; inline bool PbfGatekeeperConfig::_internal_has_min_radar_confident_distance() const { bool value = (_has_bits_[0] & 0x00000001u) != 0; return value; } inline bool PbfGatekeeperConfig::has_min_radar_confident_distance() const { return _internal_has_min_radar_confident_distance(); } inline void PbfGatekeeperConfig::clear_min_radar_confident_distance() { min_radar_confident_distance_ = 0; _has_bits_[0] &= ~0x00000001u; } inline double PbfGatekeeperConfig::_internal_min_radar_confident_distance() const { return min_radar_confident_distance_; } inline double PbfGatekeeperConfig::min_radar_confident_distance() const { // @@protoc_insertion_point(field_get:apollo.perception.fusion.PbfGatekeeperConfig.min_radar_confident_distance) return _internal_min_radar_confident_distance(); } inline void PbfGatekeeperConfig::_internal_set_min_radar_confident_distance(double value) { _has_bits_[0] |= 0x00000001u; min_radar_confident_distance_ = value; } inline void PbfGatekeeperConfig::set_min_radar_confident_distance(double value) { _internal_set_min_radar_confident_distance(value); // @@protoc_insertion_point(field_set:apollo.perception.fusion.PbfGatekeeperConfig.min_radar_confident_distance) } // optional double max_radar_confident_angle = 6; inline bool PbfGatekeeperConfig::_internal_has_max_radar_confident_angle() const { bool value = (_has_bits_[0] & 0x00000002u) != 0; return value; } inline bool PbfGatekeeperConfig::has_max_radar_confident_angle() const { return _internal_has_max_radar_confident_angle(); } inline void PbfGatekeeperConfig::clear_max_radar_confident_angle() { max_radar_confident_angle_ = 0; _has_bits_[0] &= ~0x00000002u; } inline double PbfGatekeeperConfig::_internal_max_radar_confident_angle() const { return max_radar_confident_angle_; } inline double PbfGatekeeperConfig::max_radar_confident_angle() const { // @@protoc_insertion_point(field_get:apollo.perception.fusion.PbfGatekeeperConfig.max_radar_confident_angle) return _internal_max_radar_confident_angle(); } inline void PbfGatekeeperConfig::_internal_set_max_radar_confident_angle(double value) { _has_bits_[0] |= 0x00000002u; max_radar_confident_angle_ = value; } inline void PbfGatekeeperConfig::set_max_radar_confident_angle(double value) { _internal_set_max_radar_confident_angle(value); // @@protoc_insertion_point(field_set:apollo.perception.fusion.PbfGatekeeperConfig.max_radar_confident_angle) } // optional double min_camera_publish_distance = 7; inline bool PbfGatekeeperConfig::_internal_has_min_camera_publish_distance() const { bool value = (_has_bits_[0] & 0x00000004u) != 0; return value; } inline bool PbfGatekeeperConfig::has_min_camera_publish_distance() const { return _internal_has_min_camera_publish_distance(); } inline void PbfGatekeeperConfig::clear_min_camera_publish_distance() { min_camera_publish_distance_ = 0; _has_bits_[0] &= ~0x00000004u; } inline double PbfGatekeeperConfig::_internal_min_camera_publish_distance() const { return min_camera_publish_distance_; } inline double PbfGatekeeperConfig::min_camera_publish_distance() const { // @@protoc_insertion_point(field_get:apollo.perception.fusion.PbfGatekeeperConfig.min_camera_publish_distance) return _internal_min_camera_publish_distance(); } inline void PbfGatekeeperConfig::_internal_set_min_camera_publish_distance(double value) { _has_bits_[0] |= 0x00000004u; min_camera_publish_distance_ = value; } inline void PbfGatekeeperConfig::set_min_camera_publish_distance(double value) { _internal_set_min_camera_publish_distance(value); // @@protoc_insertion_point(field_set:apollo.perception.fusion.PbfGatekeeperConfig.min_camera_publish_distance) } // optional double invisible_period_threshold = 8; inline bool PbfGatekeeperConfig::_internal_has_invisible_period_threshold() const { bool value = (_has_bits_[0] & 0x00000008u) != 0; return value; } inline bool PbfGatekeeperConfig::has_invisible_period_threshold() const { return _internal_has_invisible_period_threshold(); } inline void PbfGatekeeperConfig::clear_invisible_period_threshold() { invisible_period_threshold_ = 0; _has_bits_[0] &= ~0x00000008u; } inline double PbfGatekeeperConfig::_internal_invisible_period_threshold() const { return invisible_period_threshold_; } inline double PbfGatekeeperConfig::invisible_period_threshold() const { // @@protoc_insertion_point(field_get:apollo.perception.fusion.PbfGatekeeperConfig.invisible_period_threshold) return _internal_invisible_period_threshold(); } inline void PbfGatekeeperConfig::_internal_set_invisible_period_threshold(double value) { _has_bits_[0] |= 0x00000008u; invisible_period_threshold_ = value; } inline void PbfGatekeeperConfig::set_invisible_period_threshold(double value) { _internal_set_invisible_period_threshold(value); // @@protoc_insertion_point(field_set:apollo.perception.fusion.PbfGatekeeperConfig.invisible_period_threshold) } // optional double toic_threshold = 9; inline bool PbfGatekeeperConfig::_internal_has_toic_threshold() const { bool value = (_has_bits_[0] & 0x00000010u) != 0; return value; } inline bool PbfGatekeeperConfig::has_toic_threshold() const { return _internal_has_toic_threshold(); } inline void PbfGatekeeperConfig::clear_toic_threshold() { toic_threshold_ = 0; _has_bits_[0] &= ~0x00000010u; } inline double PbfGatekeeperConfig::_internal_toic_threshold() const { return toic_threshold_; } inline double PbfGatekeeperConfig::toic_threshold() const { // @@protoc_insertion_point(field_get:apollo.perception.fusion.PbfGatekeeperConfig.toic_threshold) return _internal_toic_threshold(); } inline void PbfGatekeeperConfig::_internal_set_toic_threshold(double value) { _has_bits_[0] |= 0x00000010u; toic_threshold_ = value; } inline void PbfGatekeeperConfig::set_toic_threshold(double value) { _internal_set_toic_threshold(value); // @@protoc_insertion_point(field_set:apollo.perception.fusion.PbfGatekeeperConfig.toic_threshold) } // optional bool use_track_time_pub_strategy = 10; inline bool PbfGatekeeperConfig::_internal_has_use_track_time_pub_strategy() const { bool value = (_has_bits_[0] & 0x00000020u) != 0; return value; } inline bool PbfGatekeeperConfig::has_use_track_time_pub_strategy() const { return _internal_has_use_track_time_pub_strategy(); } inline void PbfGatekeeperConfig::clear_use_track_time_pub_strategy() { use_track_time_pub_strategy_ = false; _has_bits_[0] &= ~0x00000020u; } inline bool PbfGatekeeperConfig::_internal_use_track_time_pub_strategy() const { return use_track_time_pub_strategy_; } inline bool PbfGatekeeperConfig::use_track_time_pub_strategy() const { // @@protoc_insertion_point(field_get:apollo.perception.fusion.PbfGatekeeperConfig.use_track_time_pub_strategy) return _internal_use_track_time_pub_strategy(); } inline void PbfGatekeeperConfig::_internal_set_use_track_time_pub_strategy(bool value) { _has_bits_[0] |= 0x00000020u; use_track_time_pub_strategy_ = value; } inline void PbfGatekeeperConfig::set_use_track_time_pub_strategy(bool value) { _internal_set_use_track_time_pub_strategy(value); // @@protoc_insertion_point(field_set:apollo.perception.fusion.PbfGatekeeperConfig.use_track_time_pub_strategy) } // optional int32 pub_track_time_thresh = 11; inline bool PbfGatekeeperConfig::_internal_has_pub_track_time_thresh() const { bool value = (_has_bits_[0] & 0x00000040u) != 0; return value; } inline bool PbfGatekeeperConfig::has_pub_track_time_thresh() const { return _internal_has_pub_track_time_thresh(); } inline void PbfGatekeeperConfig::clear_pub_track_time_thresh() { pub_track_time_thresh_ = 0; _has_bits_[0] &= ~0x00000040u; } inline ::PROTOBUF_NAMESPACE_ID::int32 PbfGatekeeperConfig::_internal_pub_track_time_thresh() const { return pub_track_time_thresh_; } inline ::PROTOBUF_NAMESPACE_ID::int32 PbfGatekeeperConfig::pub_track_time_thresh() const { // @@protoc_insertion_point(field_get:apollo.perception.fusion.PbfGatekeeperConfig.pub_track_time_thresh) return _internal_pub_track_time_thresh(); } inline void PbfGatekeeperConfig::_internal_set_pub_track_time_thresh(::PROTOBUF_NAMESPACE_ID::int32 value) { _has_bits_[0] |= 0x00000040u; pub_track_time_thresh_ = value; } inline void PbfGatekeeperConfig::set_pub_track_time_thresh(::PROTOBUF_NAMESPACE_ID::int32 value) { _internal_set_pub_track_time_thresh(value); // @@protoc_insertion_point(field_set:apollo.perception.fusion.PbfGatekeeperConfig.pub_track_time_thresh) } // optional double existence_threshold = 12; inline bool PbfGatekeeperConfig::_internal_has_existence_threshold() const { bool value = (_has_bits_[0] & 0x00000080u) != 0; return value; } inline bool PbfGatekeeperConfig::has_existence_threshold() const { return _internal_has_existence_threshold(); } inline void PbfGatekeeperConfig::clear_existence_threshold() { existence_threshold_ = 0; _has_bits_[0] &= ~0x00000080u; } inline double PbfGatekeeperConfig::_internal_existence_threshold() const { return existence_threshold_; } inline double PbfGatekeeperConfig::existence_threshold() const { // @@protoc_insertion_point(field_get:apollo.perception.fusion.PbfGatekeeperConfig.existence_threshold) return _internal_existence_threshold(); } inline void PbfGatekeeperConfig::_internal_set_existence_threshold(double value) { _has_bits_[0] |= 0x00000080u; existence_threshold_ = value; } inline void PbfGatekeeperConfig::set_existence_threshold(double value) { _internal_set_existence_threshold(value); // @@protoc_insertion_point(field_set:apollo.perception.fusion.PbfGatekeeperConfig.existence_threshold) } // optional double radar_existence_threshold = 13; inline bool PbfGatekeeperConfig::_internal_has_radar_existence_threshold() const { bool value = (_has_bits_[0] & 0x00000100u) != 0; return value; } inline bool PbfGatekeeperConfig::has_radar_existence_threshold() const { return _internal_has_radar_existence_threshold(); } inline void PbfGatekeeperConfig::clear_radar_existence_threshold() { radar_existence_threshold_ = 0; _has_bits_[0] &= ~0x00000100u; } inline double PbfGatekeeperConfig::_internal_radar_existence_threshold() const { return radar_existence_threshold_; } inline double PbfGatekeeperConfig::radar_existence_threshold() const { // @@protoc_insertion_point(field_get:apollo.perception.fusion.PbfGatekeeperConfig.radar_existence_threshold) return _internal_radar_existence_threshold(); } inline void PbfGatekeeperConfig::_internal_set_radar_existence_threshold(double value) { _has_bits_[0] |= 0x00000100u; radar_existence_threshold_ = value; } inline void PbfGatekeeperConfig::set_radar_existence_threshold(double value) { _internal_set_radar_existence_threshold(value); // @@protoc_insertion_point(field_set:apollo.perception.fusion.PbfGatekeeperConfig.radar_existence_threshold) } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // @@protoc_insertion_point(namespace_scope) } // namespace fusion } // namespace perception } // namespace apollo // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_modules_2fperception_2ffusion_2flib_2fgatekeeper_2fpbf_5fgatekeeper_2fproto_2fpbf_5fgatekeeper_5fconfig_2eproto
[ "530872883@qq.com" ]
530872883@qq.com
55c170a57f862b326bd2ce852f6aa9d1e33641ab
7d33112cc076560bebccaa6c580fee9157fd1004
/parsian_ws/src/parsian_util/src/math/matrix.cpp
5549f149a6aed34e62f286c6c0f2d6b3c0646f96
[]
no_license
kianbehzad/ParsianStack
6a9ff4a103487dc3da2e3e0318f18be79f718682
dc9f81badbedf00eb4af6b3c51403e806c42200f
refs/heads/develop
2021-04-11T09:39:20.841446
2020-04-13T17:59:22
2020-04-13T17:59:22
249,008,527
3
1
null
2020-04-13T17:59:24
2020-03-21T15:50:07
C++
UTF-8
C++
false
false
16,876
cpp
/********************************************************************** * * Kwun Han <kwunh@cs.cmu.edu> * March 1997 * * Michael Bowling <mhb@cs.cmu.edu> * 1998-2002 * * Determinant and inverse code is copied from mtrxmath under the GPL. * **********************************************************************/ /* LICENSE: */ #include <cstring> #include <cassert> #include <cstdio> #include <cstdlib> #include <cmath> #include "parsian_util/math/matrix.h" Matrix::Matrix(char* const init_string) : r_(), c_(), mat() { str_init(init_string); } Matrix::Matrix(int rows, int columns) { r_ = rows; c_ = columns; mat = (double*)malloc(r_ * c_ * sizeof(double)); for (int i = 0 ; i < rows ; i++) { for (int j = 0 ; j < columns ; j++) { this->e(i, j) = 0; } } } Matrix::Matrix(int rows, int columns, const float *m) { r_ = rows; c_ = columns; mat = (double*)malloc(r_ * c_ * sizeof(double)); for (int i = 0; i < rows * columns; i++) { mat[i] = m[i]; } } Matrix::Matrix(int identity_size) { r_ = identity_size; c_ = identity_size; mat = (double*)malloc(r_ * c_ * sizeof(double)); for (int i = 0; i < identity_size; i++) { for (int j = 0; j < identity_size; j++) { this->e(i, j) = i == j; } } } Matrix::Matrix() { // printf("Matrix::Matrix()\n"); r_ = 0; c_ = 0; mat = 0; } Matrix::Matrix(const Matrix& other) { // fprintf(stderr, "Matrix::Matrix(const Matrix& other)\n"); // fprintf(stderr, "mat: 0x%x\n", mat); // if(mat) free(mat); r_ = other.r_; c_ = other.c_; mat = (double*)malloc(r_ * c_ * sizeof(double)); // fprintf(stderr, "mat: 0x%x\n", mat); for (int i = 0; i < r_ * c_; i++) { mat[i] = other.mat[i]; } // fprintf(stderr, "Matrix::Matrix(const Matrix& other) done\n"); } Matrix::~Matrix() { if (mat) { free(mat); } } void Matrix::CopyData(float *data) { for (double *ptr = mat; ptr < mat + r_ * c_; ptr++) { *data++ = (float)(*ptr++); } } void Matrix::CopyData(double *data) { memcpy(data, mat, r_ * c_ * sizeof(double)); } const Matrix& Matrix::operator= (const Matrix& other) { if (this == &other) { return *this; } // fprintf(stderr, "\nop=\n"); int i; // fprintf(stderr, "mat: 0x%x\n", mat); if (mat) { free(mat); } r_ = other.r_; c_ = other.c_; mat = (double*)malloc(r_ * c_ * sizeof(double)); // other.print(); // fprintf(stderr, "mat: 0x%x r: %d c: %d\n", // mat, other.r_, other.c_); for (i = 0; i < (r_ * c_); i++) { mat[i] = other.mat[i]; } // fprintf(stderr, "op= done\n"); return *this; } const Matrix& Matrix::operator= (char* const init_string) { if (mat) { free(mat); } str_init(init_string); return *this; } void Matrix::str_init(char* const init_string) { char* str1 = (char*)malloc(strlen(init_string) + 1); int tcount; char* delim = const_cast<char *>(" ;[]"); strcpy(str1, init_string); tcount = 0; if (strtok(str1, delim) != nullptr) { tcount++; } while (strtok(nullptr, delim)) { tcount ++; } if (!tcount) { mat = 0; free(str1); return; } mat = (double*)malloc(tcount * sizeof(double)); strcpy(str1, init_string); r_ = 0; if (strtok(str1, ";")) { r_++; } while (strtok(NULL, ";")) { r_ ++; } c_ = tcount / r_; strcpy(str1, init_string); mat[0] = atof(strtok(str1, delim)); for (int i = 1; i < tcount; i++) { mat[i] = atof(strtok(NULL, delim)); } free(str1); } const Matrix operator+ (const Matrix& a, const Matrix& b) { Matrix out; m_add(out, a, b); return out; } const Matrix operator- (const Matrix& a, const Matrix& b) { Matrix out; m_subtract(out, a, b); return out; } const Matrix operator* (const Matrix& a, const Matrix& b) { // fprintf(stderr, "\nop*\n"); // a.print(); // b.print(); Matrix out; m_multiply(out, a, b); // out.print(); // fprintf(stderr, "op* done\n"); return out; } const Matrix operator* (const double a , const Matrix& m) { // fprintf(stderr, "\nop*\n"); // a.print(); // b.print(); Matrix out(m); out.scale(a); // out.print(); // fprintf(stderr, "op* done\n"); return out; } Matrix kron(const Matrix &a , const Matrix &b) { Matrix out; out.resize(a.r_ * b.r_ , a.c_ * b.c_); for (int i = 0; i < out.r_ * out.c_; i++) { out.mat[i] = 0.0; } for (int i = 0 ; i < a.r_ ; i++) { for (int j = 0 ; j < a.c_ ; j++) { for (int ii = 0 ; ii < b.r_ ; ii++) { for (int jj = 0 ; jj < b.c_ ; jj++) { out.e(i * b.r_ + ii , j * b.c_ + jj) = a.e(i , j) * b.e(ii, jj); } } } } return out; } const Matrix inverse(const Matrix& a) { Matrix out; out = a; out.inverse(); return out; } const Matrix transpose(const Matrix& a) { Matrix out; out = a; out.transpose(); return out; } const Matrix pseudoinverse(const Matrix& a) { Matrix out; out = a; out.pseudoinverse(); return out; } const Matrix& m_multiply(Matrix& out, const Matrix& a, const Matrix& b) { int i, j, k; assert(a.c_ == b.r_); out.resize(a.r_, b.c_); // fprintf(stderr, "%dx%d * %dx%d --> %dx%d\n", // a.r_, a.c_, b.r_, b.c_, // out.r_, out.c_); for (i = 0; i < out.r_ * out.c_; i++) { out.mat[i] = 0.0; } for (i = 0; i < a.r_; i++) { for (j = 0; j < b.c_; j++) { for (k = 0; k < a.c_; k++) { out.e(i, j) += a.e(i, k) * b.e(k, j); } } } // fprintf(stderr, "done\n"); return out; } const Matrix& m_inverse(Matrix& out, const Matrix& in) { out = in; out.inverse(); return out; } const Matrix& m_add(Matrix& out, const Matrix& a, const Matrix& b) { assert(a.r_ == b.r_ && a.c_ == b.c_); out.resize(a.r_, a.c_); for (int i = 0; i < a.r_ * a.c_ ; i++) { out.mat[i] = a.mat[i] + b.mat[i]; } return out; } const Matrix& m_subtract(Matrix& out, const Matrix& a, const Matrix& b) { assert(a.r_ == b.r_ && a.c_ == b.c_); out.resize(a.r_, a.c_); for (int i = 0; i < a.r_ * a.c_ ; i++) { out.mat[i] = a.mat[i] - b.mat[i]; } return out; } const Matrix& m_transpose(Matrix& out, const Matrix& in) { out.resize(in.c_, in.r_); for (int i = 0; i < in.r_; i++) { for (int j = 0; j < in.c_; j++) { out.e(j, i) = in.e(i, j); } } return out; } const Matrix& m_pseudoinverse(Matrix& out, const Matrix& in) { out = in; out.inverse(); return out; } const Matrix& Matrix::transpose() { if (!mat) { return *this; } double* newmat = (double*)malloc(r_ * c_ * sizeof(double)); for (int i = 0; i < r_; i++) { for (int j = 0; j < c_; j++) { newmat[j * r_ + i] = e(i, j); } } int t; t = c_; c_ = r_; r_ = t; free(mat); mat = newmat; return *this; } const Matrix& Matrix::identity(int size) { if (mat) { free(mat); } r_ = size; c_ = size; mat = (double*)malloc(r_ * c_ * sizeof(double)); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { this->e(i, j) = i == j; } } return *this; } const Matrix& Matrix::resize(int rows, int columns) { if (rows == r_ && columns == c_) { return *this; } if (mat) { free(mat); } r_ = rows; c_ = columns; mat = (double*)malloc(r_ * c_ * sizeof(double)); return *this; } const Matrix& Matrix::resizeS(int rows, int columns) { if (rows == r_ && columns == c_) { return *this; } assert(rows * columns == r_ * c_); r_ = rows; c_ = columns; return *this; } const Matrix& Matrix::scale(double factor) { if (!mat) { return *this; } for (int i = 0; i < r_ * c_; i++) { mat[i] *= factor; } return *this; } void Matrix::print() const { int i, j; //printf("\n%dx%d\n", r_, c_); for (i = 0; i < r_; i++) { for (j = 0; j < c_; j++) { fprintf(stderr, "%f ", e(i, j)); } fprintf(stderr, "\n"); } } Matrix *Matrix::reduce_matrix(int cut_row, int cut_column) const { Matrix *reduced; int y, x, rc, rr; rc = rr = 0; reduced = new Matrix(r_ - 1, r_ - 1); /* This function performs a fairly simple function. It reduces a matrix in size by one element on each dimesion around the coordinates sent in the cut_row and cut_column values. For example: 3x3 Matrix: 1 2 3 4 5 6 7 8 9 is sent to this function with the cut_row == 2 and cut_column == 1, the function returns the 2x2 Matrix: 2 3 8 9 */ for (x = 0 ; x < r_ ; x++) { for (y = 0 ; y < c_; y++) { if (x == cut_row || y == cut_column) { } else { reduced->e(rr, rc) = e(x, y); rc++; } } if (rr != cut_row || x > cut_row) { rr++; rc = 0; } } return reduced; } /* * Determinant * Solve the determinant of a matrix * * Yes, I know this uses the Cramer's Method of finding a * determinate, and that Gaussian would be better. I'm * looking into implementing a Gaussian function, but for * now this works. */ double Matrix::determinant() { double det = 0; Matrix *tmp; int i, sign = 1; /* Do I need to explain this? */ assert(r_ == c_); /* This may never be used, but it's necessary for error checking */ if (r_ == 1) { return e(0, 0); } return determinant(this, r_); } double Matrix::determinant(Matrix *mx, int n) { if (n == 2) { return mx->e(0, 0) * mx->e(1, 1) - mx->e(0, 1) * mx->e(1, 0); } else { bool b = true; int i , j; for (i = 0 ; i < n && b ; i++) for (j = 0 ; j < n && b ; j++) if (mx->e(i, j) != 0) { b = false; } i--; j--; Matrix *m = new Matrix(n - 1, n - 1); double scale = 1.0; int logarithm = (int)(log10(fabs(mx->e(i, j)))); if (logarithm < -3) { scale = pow(10.0, -3 - logarithm); } else if (logarithm > 3) { scale = pow(10.0, 3 - logarithm); } for (int k = 0 ; k < n ; k++) { for (int p = 0 ; p < n ; p++) { if (k < i && p < j) { m->e(k, p) = (mx->e(k, p) * mx->e(i, j) - mx->e(k, j) * mx->e(i, p)) * scale; } else if (k < i && p > j) { m->e(k, p - 1) = (mx->e(k, j) * mx->e(i, p) - mx->e(k, p) * mx->e(i, j)) * scale; } else if (k > i && p < j) { m->e(k - 1, p) = (mx->e(k, j) * mx->e(i, p) - mx->e(k, p) * mx->e(i, j)) * scale; } else if (k > i && p > j) { m->e(k - 1, p - 1) = (mx->e(k, p) * mx->e(i, j) - mx->e(k, j) * mx->e(i, p)) * scale; } } } double temp = ((1.0 / pow(mx->e(i, j), n - 2)) * determinant(m, n - 1)) / pow(scale, n - 1); delete m; return temp; } } /* * inverse * * Function to find the inverse of a matrix */ const Matrix &Matrix::inverse() { Matrix *inverse; Matrix *tmp; double det = 0; int row, col, sign = 1; assert(r_ == c_); inverse = new Matrix(r_, c_); det = determinant(); assert(det != 0); for (row = 0; row < r_; row++) { for (col = 0; col < c_; col++) { /* This looks kind of confusing. All it does is take the inverse and multiply each square by the determinant that is reduced around the spot the matrix is being reduced by For Instance: In a 3x3 Matrix: A B C D E F G H I When computing with Element B, Element B is multiplied by the determinant of the 2x2 matrix: D F G I */ tmp = reduce_matrix(row, col); if ((row + col) % 2 == 0) { sign = 1; } else { sign = -1; } inverse->e(col, row) = sign * tmp->determinant(); delete tmp; } } inverse->scale(1 / det); *this = *inverse; delete inverse; return *this; } const Matrix &Matrix::pseudoinverse() { //h -> r //w -> c int r, c; int k = 1; Matrix *dk, *ck, *bk; Matrix *R_plus; Matrix *ak = new Matrix(r_, 1); Matrix *akT, *ckT, *dkT; for (r = 0; r < r_; r++) for (c = 0; c < 1; c++) { ak->e(r, c) = 0.0; } for (r = 0; r < r_; r++) { ak->e(r, 0) = this->e(r, 0); } // ak->print(); if (!ak->equals(0.0)) { // fprintf(stderr,"!"); akT = new Matrix(*ak); akT->transpose(); R_plus = new Matrix((1.0 / (ak->dot(*ak))) * (*akT)); // fprintf(stderr,"!"); } else { R_plus = new Matrix(1, r_); for (r = 0; r < 1; r++) for (c = 0; c < r_; c++) { R_plus->e(r, c) = 0.0; } } // fprintf(stderr,"@"); while (k < c_) { // fprintf(stderr,"#%d",k); for (r = 0; r < r_; r++) { ak->e(r, 0) = this->e(r, k); } // fprintf(stderr,"\r\nRPlus\r\n"); // R_plus->print(); // fprintf(stderr,"\r\nak\r\n"); // ak->print(); dk = new Matrix((*R_plus) * (*ak)); ////// // fprintf(stderr,"\r\ndk\r\n"); // dk->print(); // fprintf(stderr,"!"); Matrix *T = new Matrix(r_, k); for (r = 0; r < r_; r++) for (c = 0; c < k; c++) { T->e(r, c) = this->e(r, c); } // fprintf(stderr,"\r\nT\r\n"); // T->print(); Matrix *tmp = new Matrix((*T) * (*dk)); /// // fprintf(stderr,"\r\ntmp\r\n"); // tmp->print(); ck = new Matrix((*ak) - * (tmp)); //// // fprintf(stderr,"\r\nck\r\n"); // ck->print(); if (!ck->equals(0.0)) { ckT = new Matrix(*ck); ckT->transpose(); bk = new Matrix((1.0 / (ck->dot(*ck))) * (*ckT)); // fprintf(stderr,"\r\nbk1\r\n"); // bk->print(); } else { dkT = new Matrix(*dk); dkT->transpose(); bk = new Matrix((1.0 / (1.0 + (dk->dot(*dk)))) * (*dkT) * (*R_plus)); //// // fprintf(stderr,"\r\nbk2\r\n"); // bk->print(); } tmp = new Matrix((*dk) * (*bk)); // fprintf(stderr,"\r\ntmp\r\n"); // tmp->print(); auto *N = new Matrix(*R_plus); m_subtract(*N, *R_plus, *tmp); // fprintf(stderr,"\r\N\r\n"); // N->print(); delete tmp; delete R_plus; R_plus = new Matrix(N->nrows() + 1, N->ncols()); for (r = 0; r < N->nrows(); r++) for (c = 0; c < N->ncols(); c++) { R_plus->e(r, c) = N->e(r, c); } for (c = 0; c < N->ncols(); c++) { R_plus->e(R_plus->nrows() - 1, c) = bk->e(0, c); } // fprintf(stderr,"\r\nR_plus\r\n"); // R_plus->print(); delete dk; delete T; delete ck; delete bk; delete N; k++; } delete ak; this->r_ = R_plus->r_; this->c_ = R_plus->c_; this->mat = (double*)malloc(r_ * c_ * sizeof(double)); R_plus->CopyData(this->mat); delete R_plus; return *this; } bool Matrix::equals(double val) { for (int r = 0; r < this->r_; r++) for (int c = 0; c < this->c_; c++) if (fabs(this->e(r, c) - val) > .0001) { return false; } return true; } double Matrix::dot(Matrix &m) { assert((r_ == m.nrows()) && (c_ == m.ncols())); double sum = 0; for (int r = 0; r < this->r_; r++) for (int c = 0; c < this->c_; c++) { sum += this->e(r, c) * m.e(r, c); } return sum; } Matrix& Matrix::dotP(Matrix &m) { assert((r_ == m.nrows()) && (c_ == m.ncols())); auto * res = new Matrix(r_, c_); for (int r = 0; r < this->r_; r++) for (int c = 0; c < this->c_; c++) { res->e(r, c) = this->e(r, c) * m.e(r, c); } return *res; }
[ "kian.behzad@gmail.com" ]
kian.behzad@gmail.com
fa6c2fbc3589c2f29e9b8d898557feff991832e0
ff78a0b4de684f13280cb3711e418c5b6b063ab7
/mainwindow-qt.h
346ed5c3f2cec6ddb81d51626292213b0e7f55ac
[]
no_license
njaard/meow
8eb2e4126c4ab0a118afe80d368937ce649b2744
031763ef2949c75c13a00e713022546805627218
refs/heads/master
2021-01-10T05:44:00.554059
2014-01-15T03:21:44
2014-01-15T03:21:44
43,370,165
0
0
null
null
null
null
UTF-8
C++
false
false
2,118
h
#ifndef MEOW_MAINWINDOW_H #define MEOW_MAINWINDOW_H #include <qmainwindow.h> #include <qdialog.h> #include <qsystemtrayicon.h> #include <db/file.h> #include <map> class QSlider; class QSignalMapper; class QUrl; namespace Meow { class TreeView; class Player; class Collection; class DirectoryAdder; class File; class MainWindow : public QMainWindow { Q_OBJECT struct MainWindowPrivate; MainWindowPrivate *d; public: MainWindow(bool dontPlayLastPlayed); ~MainWindow(); private slots: void reloadCollections(); public slots: void addFiles(); void addDirs(); void addFile(const QUrl &url); void addAndPlayFile(const QUrl &url); void toggleVisible(); protected: virtual void closeEvent(QCloseEvent *event); virtual void wheelEvent(QWheelEvent *event); virtual void dropEvent(QDropEvent *event); virtual void dragEnterEvent(QDragEnterEvent *event); virtual bool eventFilter(QObject *object, QEvent *event); private slots: void adderDone(); void showItemContext(const QPoint &at); void changeCaption(const File &f); void systemTrayClicked(QSystemTrayIcon::ActivationReason reason); void itemProperties(); void selectorActivated(QAction*); void fileDialogAccepted(); void fileDialogClosed(); void showSettings(); void showShortcutSettings(); void showAbout(); void toggleToolBar(); void toggleMenuBar(); void quitting(); void showVolume(); void isPlaying(bool pl); void newCollection(); void copyCollection(); void renameCollection(); void deleteCollection(); void loadCollection(const QString &collection, FileId first); void loadCollection(const QString &collection) { loadCollection(collection, 0); } private: void beginDirectoryAdd(const QString &url); static bool globalEventFilter(void *_m); QIcon renderIcon(const QIcon& baseIcon, const QIcon &overlayIcon) const; void registerShortcuts(); }; class ShortcutInput; class Shortcut; class ShortcutDialog : public QDialog { Q_OBJECT public: ShortcutDialog(std::map<QString, Shortcut*>& s, QWidget *w); std::map<QString, ShortcutInput*> inputs; }; } #endif // kate: space-indent off; replace-tabs off;
[ "charles" ]
charles
29868f215e9cb116854a9b39d83c3e80bf329f2b
126519713b91125b75cfa1c3a6c159c5cf9b00db
/Classes/AppDelegate.cpp
8f6616f82de8d916cb53806bd2e71bbcb49d56fd
[]
no_license
Showjy/wingame-by-cocos2dx
65bd6f2f20e49e7c56468893fce1e63dce2a5a39
246b31f8584fd27e5a0c60020869d56a49035e39
refs/heads/master
2021-07-21T23:45:06.773948
2017-10-31T13:25:24
2017-10-31T13:25:24
108,997,919
0
0
null
null
null
null
UTF-8
C++
false
false
1,974
cpp
#include "AppDelegate.h" #include "HelloWorldScene.h" USING_NS_CC; AppDelegate::AppDelegate() { } AppDelegate::~AppDelegate() { } //if you want a different context,just modify the value of glContextAttrs //it will takes effect on all platforms void AppDelegate::initGLContextAttrs() { //set OpenGL context attributions,now can only set six attributions: //red,green,blue,alpha,depth,stencil GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8}; GLView::setGLContextAttrs(glContextAttrs); } // If you want to use packages manager to install more packages, // don't modify or remove this function static int register_all_packages() { return 0; //flag for packages manager } bool AppDelegate::applicationDidFinishLaunching() { // initialize director auto director = Director::getInstance(); auto glview = director->getOpenGLView(); if(!glview) { glview = GLViewImpl::create("Bird's Adventure"); director->setOpenGLView(glview); } // turn on display FPS director->setDisplayStats(true); // set FPS. the default value is 1.0/60 if you don't call this director->setAnimationInterval(1.0 / 60); register_all_packages(); // create a scene. it's an autorelease object auto scene = HelloWorld::createScene(); // run director->runWithScene(scene); return true; } // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void AppDelegate::applicationDidEnterBackground() { Director::getInstance()->stopAnimation(); // if you use SimpleAudioEngine, it must be pause // SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); } // this function will be called when the app is active again void AppDelegate::applicationWillEnterForeground() { Director::getInstance()->startAnimation(); // if you use SimpleAudioEngine, it must resume here // SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); }
[ "noreply@github.com" ]
noreply@github.com
8a87d47f4b0c5add8e3ae48c192b2d2a8e388d7d
18ba0310c7287c7b5b9ec1ec66eab44766cb1dec
/psd2cocos/bindLua/libfairygui/Classes/UIPackage.h
791d49c982a6eae19a063f6ffc8c0908f3d684fe
[]
no_license
decwang/Other
fc0919fbf5c69e9ce45f7e67261477274adbb455
d7f6118c155f549f4fb8d6d0ea76310521aad04d
refs/heads/master
2020-05-14T00:05:43.869289
2019-04-15T11:57:04
2019-04-15T11:57:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,831
h
#ifndef __UIPACKAGE_H__ #define __UIPACKAGE_H__ #include "cocos2d.h" #include "FairyGUIMacros.h" #include "PackageItem.h" #include "GObject.h" NS_FGUI_BEGIN USING_NS_CC; struct AtlasSprite; class PixelHitTestData; class UIPackage { public: UIPackage(); ~UIPackage(); static UIPackage* getById(const std::string& id); static UIPackage* getByName(const std::string& name); static UIPackage* addPackage(const std::string& descFilePath); static void removePackage(const std::string& packageIdOrName); static void removeAllPackages(); static GObject* createObject(const std::string& pkgName, const std::string& resName); static GObject* createObjectFromURL(const std::string& url); static std::string getItemURL(const std::string& pkgName, const std::string& resName); static PackageItem* getItemByURL(const std::string& url); static std::string normalizeURL(const std::string& url); static Texture2D* getEmptyTexture() { return _emptyTexture; } const std::string& getId() const { return _id; } const std::string& getName() const { return _name; } PackageItem* getItem(const std::string& itemId); PackageItem* getItemByName(const std::string& itemName); void loadItem(const std::string& resName); void loadItem(PackageItem* item); PixelHitTestData* getPixelHitTestData(const std::string& itemId); static int _constructing; static const std::string URL_PREFIX; private: void create(const std::string& assetPath); void decodeDesc(cocos2d::Data& data); void loadPackage(); cocos2d::SpriteFrame* createSpriteTexture(AtlasSprite* sprite); void loadAtlas(PackageItem* item); void loadMovieClip(PackageItem* item); void loadFont(PackageItem* item); void loadComponent(PackageItem* item); void loadComponentChildren(PackageItem* item); void translateComponent(PackageItem* item); GObject* createObject(const std::string& resName); GObject* createObject(PackageItem* item); private: std::string _id; std::string _name; std::string _assetPath; std::vector<PackageItem*> _items; std::unordered_map<std::string, PackageItem*> _itemsById; std::unordered_map<std::string, PackageItem*> _itemsByName; std::unordered_map<std::string, AtlasSprite*> _sprites; std::unordered_map<std::string, cocos2d::Data*> _descPack; std::unordered_map<std::string, PixelHitTestData*> _hitTestDatas; std::string _assetNamePrefix; std::string _customId; bool _loadingPackage; static std::unordered_map<std::string, UIPackage*> _packageInstById; static std::unordered_map<std::string, UIPackage*> _packageInstByName; static std::vector<UIPackage*> _packageList; static ValueMap _stringsSource; static Texture2D* _emptyTexture; }; NS_FGUI_END #endif
[ "275702919@qq.com" ]
275702919@qq.com
886f9743cf5adbbb630672a3f65b01c6ebacda8b
ea401c3e792a50364fe11f7cea0f35f99e8f4bde
/hackathon/2010/li_yun/ITK-V3D-Plugins/Source/Registration/RegistrationBSpline_3D.cxx
eca509890d6015fa2f531a125c926e356695a2da
[ "MIT", "Apache-2.0" ]
permissive
Vaa3D/vaa3d_tools
edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9
e6974d5223ae70474efaa85e1253f5df1814fae8
refs/heads/master
2023-08-03T06:12:01.013752
2023-08-02T07:26:01
2023-08-02T07:26:01
50,527,925
107
86
MIT
2023-05-22T23:43:48
2016-01-27T18:19:17
C++
UTF-8
C++
false
false
12,567
cxx
/* RegistrationBSpline_3D.cpp * 2010-06-04: create this program by Lei Qu */ #include <QtGui> #include <math.h> #include <stdlib.h> #include "V3DITKFilterDualImage.h" #include "RegistrationBSpline_3D.h" // ITK Header Files #include "itkImportImageFilter.h" #include "itkRescaleIntensityImageFilter.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" #include "itkCastImageFilter.h" #include "itkSubtractImageFilter.h" #include "itkSquaredDifferenceImageFilter.h" #include "itkCenteredTransformInitializer.h" #include "itkImageRegistrationMethod.h" #include "itkMeanSquaresImageToImageMetric.h" #include "itkLinearInterpolateImageFunction.h" #include "itkBSplineDeformableTransform.h" #include "itkLBFGSBOptimizer.h"//for 3D #include "itkImage.h" // Q_EXPORT_PLUGIN2 ( PluginName, ClassName ) // The value of PluginName should correspond to the TARGET specified in the // plugin's project file. Q_EXPORT_PLUGIN2(RegistrationBSpline, ITKRegistrationBSplinePlugin) QStringList ITKRegistrationBSplinePlugin::menulist() const { return QStringList() << QObject::tr("ITK BSpline Registration") << QObject::tr("about this plugin"); } //for 3D #include "itkCommand.h" class CommandIterationUpdate : public itk::Command { public: typedef CommandIterationUpdate Self; typedef itk::Command Superclass; typedef itk::SmartPointer<Self> Pointer; itkNewMacro( Self ); protected: CommandIterationUpdate() {}; public: typedef itk::LBFGSBOptimizer OptimizerType; typedef const OptimizerType * OptimizerPointer; void Execute(itk::Object *caller, const itk::EventObject & event) { Execute( (const itk::Object *)caller, event); } void Execute(const itk::Object * object, const itk::EventObject & event) { OptimizerPointer optimizer = dynamic_cast< OptimizerPointer >( object ); if( !(itk::IterationEvent().CheckEvent( &event )) ) { return; } std::cout << optimizer->GetCurrentIteration() << " "; std::cout << optimizer->GetValue() << " "; std::cout << optimizer->GetInfinityNormOfProjectedGradient() << std::endl; } }; template<typename TPixelType> class ITKRegistrationBSplineSpecializaed : public V3DITKFilterDualImage< TPixelType, TPixelType > { public: typedef V3DITKFilterDualImage< TPixelType, TPixelType > Superclass; typedef TPixelType PixelType; typedef typename Superclass::Input3DImageType Input3DImageType; typedef itk::ImportImageFilter<PixelType, 3> ImportFilterType; typedef itk::Image< PixelType, 3 > ImageType_mid; typedef itk::Image< PixelType, 3 > ImageType_input; typedef itk::RescaleIntensityImageFilter< ImageType_input, ImageType_mid > RescaleFilterType_input; // cast datatype to float typedef itk::ImageRegistrationMethod< ImageType_mid, ImageType_mid > RegistrationType; typedef itk::CastImageFilter<ImageType_mid,ImageType_input > CastFilterType; typedef itk::ImageFileWriter< ImageType_input > WriterType; public: ITKRegistrationBSplineSpecializaed( V3DPluginCallback * callback ): Superclass(callback) { this->rescaler_to_32f_fix = RescaleFilterType_input::New(); this->rescaler_to_32f_mov = RescaleFilterType_input::New(); this->registration = RegistrationType::New(); this->caster = CastFilterType::New(); this->writer = WriterType::New(); this->RegisterInternalFilter( this->rescaler_to_32f_fix, 0.1 ); this->RegisterInternalFilter( this->rescaler_to_32f_mov, 0.1 ); this->RegisterInternalFilter( this->registration, 0.7 ); this->RegisterInternalFilter( this->caster, 0.1 ); } virtual ~ITKRegistrationBSplineSpecializaed() {}; void Execute(const QString &menu_name, V3DPluginCallback &callback, QWidget *parent) { v3dhandleList wndlist = callback.getImageWindowList(); Image4DSimple* p4DImage=callback.getImage(wndlist[0]); //set image Origin origin.Fill(0.0); //set spacing spacing.Fill(1.0); //set ROI region typename ImportFilterType::IndexType start; start.Fill(0); typename ImportFilterType::SizeType size; size[0] = p4DImage->getXDim(); size[1] = p4DImage->getYDim(); size[2] = p4DImage->getZDim(); region.SetIndex(start); region.SetSize(size); this->SetImageSelectionDialogTitle("Input Images"); this->AddImageSelectionLabel("Image 1"); this->AddImageSelectionLabel("Image 2"); this->m_ImageSelectionDialog.SetCallback(this->m_V3DPluginCallback); this->Compute(); } virtual void ComputeOneRegion() { const unsigned int Dimension = 3; //------------------------------------------------------------------ //setup filter: cast datatype to float rescaler_to_32f_fix->SetOutputMinimum( 0 ); rescaler_to_32f_fix->SetOutputMaximum( 255 ); rescaler_to_32f_mov->SetOutputMinimum( 0 ); rescaler_to_32f_mov->SetOutputMaximum( 255 ); rescaler_to_32f_fix->SetInput( this->GetInput3DImage1() ); rescaler_to_32f_mov->SetInput( this->GetInput3DImage2() ); rescaler_to_32f_fix->Update(); rescaler_to_32f_mov->Update(); //------------------------------------------------------------------ //set method type used in each module const unsigned int SpaceDimension = Dimension; const unsigned int SplineOrder = 3; typedef double CoordinateRepType; typedef itk::BSplineDeformableTransform< CoordinateRepType, SpaceDimension, SplineOrder > TransformType; typedef itk::LBFGSBOptimizer OptimizerType; typedef itk::MeanSquaresImageToImageMetric< ImageType_mid, ImageType_mid > MetricType; typedef itk::LinearInterpolateImageFunction< ImageType_mid, double > InterpolatorType; typename TransformType::Pointer transform = TransformType::New(); typename OptimizerType::Pointer optimizer = OptimizerType::New(); typename MetricType::Pointer metric = MetricType::New(); typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); registration->SetTransform( transform ); registration->SetMetric( metric ); registration->SetOptimizer( optimizer ); registration->SetInterpolator( interpolator ); registration->SetFixedImage( rescaler_to_32f_fix->GetOutput() ); registration->SetMovingImage( rescaler_to_32f_mov->GetOutput() ); registration->SetFixedImageRegion(rescaler_to_32f_fix->GetOutput()->GetBufferedRegion() ); //------------------------------------------------------------------ //Here we define the parameters of the BSplineDeformableTransform grid typedef TransformType::RegionType RegionType; RegionType bsplineRegion; RegionType::SizeType gridSizeOnImage; RegionType::SizeType gridBorderSize; RegionType::SizeType totalGridSize; gridSizeOnImage.Fill( 10 ); gridBorderSize.Fill( 3 ); // Border for spline order = 3 ( 1 lower, 2 upper ) totalGridSize = gridSizeOnImage + gridBorderSize; bsplineRegion.SetSize( totalGridSize ); typedef TransformType::SpacingType SpacingType; typedef TransformType::OriginType OriginType; typename ImageType_mid::SizeType fixedImageSize = region.GetSize(); for(unsigned int r=0; r<Dimension; r++) { spacing[r] *= static_cast<double>(fixedImageSize[r] - 1) / static_cast<double>(gridSizeOnImage[r] - 1); } typename ImageType_mid::DirectionType gridDirection = rescaler_to_32f_fix->GetOutput()->GetDirection(); SpacingType gridOriginOffset = gridDirection * spacing; OriginType gridOrigin = origin - gridOriginOffset; transform->SetGridSpacing( spacing ); transform->SetGridOrigin( gridOrigin ); transform->SetGridRegion( bsplineRegion ); transform->SetGridDirection( gridDirection ); typedef TransformType::ParametersType ParametersType; const unsigned int numberOfParameters = transform->GetNumberOfParameters(); ParametersType parameters( numberOfParameters ); parameters.Fill( 0.0 ); transform->SetParameters( parameters ); //------------------------------------------------------------------ //use the offset of the mass center of two image to initialize the transform of registration registration->SetInitialTransformParameters(transform->GetParameters() ); //for 3D OptimizerType::BoundSelectionType boundSelect( transform->GetNumberOfParameters() ); OptimizerType::BoundValueType upperBound( transform->GetNumberOfParameters() ); OptimizerType::BoundValueType lowerBound( transform->GetNumberOfParameters() ); boundSelect.Fill( 0 ); upperBound.Fill( 0.0 ); lowerBound.Fill( 0.0 ); optimizer->SetBoundSelection( boundSelect ); optimizer->SetUpperBound( upperBound ); optimizer->SetLowerBound( lowerBound ); optimizer->SetCostFunctionConvergenceFactor( 1e+12 ); optimizer->SetProjectedGradientTolerance( 1.0 ); optimizer->SetMaximumNumberOfIterations( 500 ); optimizer->SetMaximumNumberOfEvaluations( 500 ); optimizer->SetMaximumNumberOfCorrections( 5 ); // Create the Command observer and register it with the optimizer. CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New(); optimizer->AddObserver( itk::IterationEvent(), observer ); try { registration->StartRegistration(); std::cout << "Optimizer stop condition: " << registration->GetOptimizer()->GetStopConditionDescription() << std::endl; } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return; } OptimizerType::ParametersType finalParameters = registration->GetLastTransformParameters(); std::cout << "Last Transform Parameters" << std::endl; std::cout << finalParameters << std::endl; //------------------------------------------------------------------ // resample the moving image and write out the difference image // before and after registration. We will also rescale the intensities of the // difference images, so that they look better! typedef itk::ResampleImageFilter<ImageType_mid,ImageType_mid> ResampleFilterType; typename ResampleFilterType::Pointer resampler = ResampleFilterType::New(); resampler->SetTransform( transform ); resampler->SetInput( rescaler_to_32f_mov->GetOutput() ); typename ImageType_mid::Pointer fixedImage = rescaler_to_32f_fix->GetOutput(); resampler->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() ); resampler->SetOutputOrigin( fixedImage->GetOrigin() ); resampler->SetOutputSpacing( fixedImage->GetSpacing() ); resampler->SetOutputDirection( fixedImage->GetDirection() ); resampler->SetDefaultPixelValue( 0 ); // write the warped moving image to disk writer->SetFileName("output.tif"); printf("save output.tif complete\n"); // cast datatype to original one for write/display caster->SetInput( resampler->GetOutput() ); writer->SetInput( caster->GetOutput() ); caster->Update(); //writer->Update(); this->SetOutputImage( caster->GetOutput() ); } private: typename RescaleFilterType_input::Pointer rescaler_to_32f_fix ; typename RescaleFilterType_input::Pointer rescaler_to_32f_mov ; typename RegistrationType::Pointer registration ; typename CastFilterType::Pointer caster ;// cast datatype to original one for write/display typename WriterType::Pointer writer ; typename ImageType_input::PointType origin; typename ImportFilterType::SpacingType spacing; typename ImportFilterType::RegionType region; }; #define EXECUTE_PLUGIN_FOR_ONE_IMAGE_TYPE( v3d_pixel_type, c_pixel_type ) \ case v3d_pixel_type: \ { \ ITKRegistrationBSplineSpecializaed< c_pixel_type > runner( &callback ); \ runner.Execute( menu_name, callback, parent ); \ break; \ } void ITKRegistrationBSplinePlugin::domenu(const QString & menu_name, V3DPluginCallback & callback, QWidget * parent) { if (menu_name == QObject::tr("about this plugin")) { QMessageBox::information(parent, "Version info", "This is about ITKRegistrationPlugin"); return; } v3dhandle curwin = callback.currentImageWindow(); if (!curwin) { v3d_msg(tr("You don't have any image open in the main window.")); return; } Image4DSimple *p4DImage = callback.getImage(curwin); if (! p4DImage) { v3d_msg(tr("The input image is null.")); return; } EXECUTE_PLUGIN_FOR_ALL_PIXEL_TYPES; }
[ "hanchuan.peng@gmail.com" ]
hanchuan.peng@gmail.com
0e0cdfff31c7ec2452efd2c76854f64493f3c43f
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/media/gpu/android/avda_shared_state.cc
dbb035370b317b3ea4f3d4e5ccaec4d4370aca05
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
2,485
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/gpu/android/avda_shared_state.h" #include "base/metrics/histogram_macros.h" #include "base/time/time.h" #include "media/gpu/android/avda_codec_image.h" #include "ui/gl/android/surface_texture.h" #include "ui/gl/gl_bindings.h" #include "ui/gl/scoped_make_current.h" namespace media { AVDASharedState::AVDASharedState( scoped_refptr<AVDASurfaceBundle> surface_bundle) : gl_matrix_{ 1, 0, 0, 0, // Default to a sane guess just in case we can't get the 0, 1, 0, 0, // matrix on the first call. Will be Y-flipped later. 0, 0, 1, 0, // 0, 0, 0, 1, // Comment preserves 4x4 formatting. }, surface_bundle_(surface_bundle), weak_this_factory_(this) { // If we're holding a reference to an overlay, then register to drop it if the // overlay's surface is destroyed. if (overlay()) { overlay()->AddSurfaceDestroyedCallback(base::Bind( &AVDASharedState::ClearOverlay, weak_this_factory_.GetWeakPtr())); } } AVDASharedState::~AVDASharedState() = default; void AVDASharedState::RenderCodecBufferToSurfaceTexture( MediaCodecBridge* codec, int codec_buffer_index) { if (surface_texture()->IsExpectingFrameAvailable()) surface_texture()->WaitForFrameAvailable(); codec->ReleaseOutputBuffer(codec_buffer_index, true); surface_texture()->SetReleaseTimeToNow(); } void AVDASharedState::WaitForFrameAvailable() { surface_texture()->WaitForFrameAvailable(); } void AVDASharedState::UpdateTexImage() { surface_texture()->UpdateTexImage(); // Helpfully, this is already column major. surface_texture()->GetTransformMatrix(gl_matrix_); } void AVDASharedState::GetTransformMatrix(float matrix[16]) const { memcpy(matrix, gl_matrix_, sizeof(gl_matrix_)); } void AVDASharedState::ClearReleaseTime() { if (surface_texture()) surface_texture()->IgnorePendingRelease(); } void AVDASharedState::ClearOverlay(AndroidOverlay* overlay_raw) { if (surface_bundle_ && overlay() == overlay_raw) surface_bundle_ = nullptr; } void AVDASharedState::SetPromotionHintCB( PromotionHintAggregator::NotifyPromotionHintCB cb) { promotion_hint_cb_ = cb; } const PromotionHintAggregator::NotifyPromotionHintCB& AVDASharedState::GetPromotionHintCB() { return promotion_hint_cb_; } } // namespace media
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com
921f13b73ffc744c565541dd57aea8e37eeaf903
b292168a299483841e5eab63b8c2a153dcf5c6de
/Classes/TitleLayer.cpp
069a7efa17812575c35e85993a165275f8532237
[]
no_license
francis1122/RogueDeck
81622d512ff6ebbbc1856f2133d80fed8a2403d4
f7e1853cd01bfff0ff50cd1033486889cbe8db37
refs/heads/master
2020-06-03T17:04:03.540198
2014-04-16T00:31:40
2014-04-16T00:31:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,221
cpp
// // TitleLayer.cpp // RogueDeck // // Created by Hunter Francis on 11/17/13. // // #include "TitleLayer.h" #include "GameLayer.h" #include "GameManager.h" #include "BetweenRoundLayer.h" #include "Constants.h" USING_NS_CC; CCScene* TitleLayer::scene() { // 'scene' is an autorelease object CCScene *scene = CCScene::create(); // 'layer' is an autorelease object TitleLayer *layer = TitleLayer::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool TitleLayer::init() { ////////////////////////////// // 1. super init first if ( !CCLayer::init() ) { return false; } CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize(); CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object CCMenuItemSprite *pCloseItem = CCMenuItemSprite::create(CCSprite::createWithSpriteFrameName("StartButton_Normal"), CCSprite::createWithSpriteFrameName("StartButton_Pressed"), this, menu_selector(TitleLayer::startGame)); pCloseItem->setPosition(ccp(visibleSize.width/2, 150)); // create menu, it's an autorelease object CCMenu* pMenu = CCMenu::create(pCloseItem, NULL); pMenu->setPosition(CCPointZero); this->addChild(pMenu, 1); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label // CCLabelTTF* pLabel = CCLabelTTF::create("Rogue Deck", Main_Font, 24); CCSprite* title = CCSprite::createWithSpriteFrameName("Title"); // position the label on the center of the screen title->setPosition(ccp(origin.x + visibleSize.width/2, origin.y + visibleSize.height - title->getContentSize().height + 60)); // add the label as a child to this layer this->addChild(title, 1); // add "HelloWorld" splash screen" CCSprite* pSprite = CCSprite::createWithSpriteFrameName("MenuBG"); pSprite->setPosition(ccp(pSprite->getContentSize().width/2, pSprite->getContentSize().height/2)); // position the sprite on the center of the screen // pSprite->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); // add the sprite as a child to this layer this->addChild(pSprite, 0); return true; } void TitleLayer::startGame(CCObject* pSender) { //load game scene // create a scene. it's an autorelease object GM->startNewGame(); // CCDirector* pDirector = CCDirector::sharedDirector(); // CCScene *pScene = BetweenRoundLayer::scene(); // run // pDirector->replaceScene(pScene); }
[ "francis1122@gmail.com" ]
francis1122@gmail.com
bcf0159e4d6743b0298c40f9e01ac27039b1c989
c95e16517c0c886f0b386a5048f9b47673aeda5f
/Educational Codeforces Round 111 (Rated for Div. 2)/B. Maximum Cost Deletion.cpp
ed8ac13465e7edd89756624f0368368238cf1397
[]
no_license
Hasanul-Bari/contests
7c9f659e2b2d0090a3d71bc8a54455447ef760ea
e98b025360a30da5c8ac91348f6e633932ebe2ee
refs/heads/master
2022-11-23T04:18:44.541827
2022-11-02T17:49:22
2022-11-02T17:49:22
250,586,853
1
0
null
null
null
null
UTF-8
C++
false
false
784
cpp
#include<bits/stdc++.h> #define faster ios :: sync_with_stdio(0); cin.tie(0); cout.tie(0); #define ll long long #define ull unsigned long long #define pb push_back const double PI = acos(-1.0); using namespace std; void solve(int tc) { int n,a,b; string s; cin>>n>>a>>b>>s; ll x=a*n; if(b>=0) { x=x+(n*b); } else { char curr='*'; int c=0; for(int i=0; i<n; i++) { if(curr!=s[i]) { c++; curr=s[i]; } } c=c/2; c++; x=x+(c*b); //cout<<c<<endl; } cout<<x<<endl; } int main() { faster int t; cin>>t; for(int tc=1; tc<=t; tc++)solve(tc); //solve(1); return 0; }
[ "hasanul.bari.hasan96@gmail.com" ]
hasanul.bari.hasan96@gmail.com
71ecffcffe1e5b6d1fa892bb235b99deeaa18b7c
5877ab778e62d8aa9fa14fefe0b9ceeaadafc1e0
/src/analysis.h
48593e0a624f13e24e254dd538133a7aaf232784
[]
no_license
mmirmomeni/sunspot
500617fd34f11f4004e90805d1d20664236ac968
acfe232f4831307fe2026aec0650b7ff4357b567
refs/heads/master
2020-05-19T08:40:59.299727
2013-09-07T11:56:31
2013-09-07T11:56:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,153
h
#ifndef _ANALYSIS_H_ #define _ANALYSIS_H_ template <typename EA> struct sunspot_data : public ealib::analysis::unary_function<EA> { static const char* name() { return "sunspot_data";} virtual void operator()(EA& ea) { using namespace ealib; using namespace ealib::analysis; typename EA::fitness_function_type::matrix_type& M=ea.fitness_function()._train_input; typename EA::fitness_function_type::vector_type& T=ea.fitness_function()._train_t; typename EA::fitness_function_type::vector_type& Tp1=ea.fitness_function()._train_tplus1; datafile df("sunspot_data.dat"); df.comment("WARNING: bits are reversed (i0=LSB) and multiple numbers may be encoded per line"); df.add_field("t"); for(std::size_t i=0; i<M.size2(); ++i) { df.add_field("i" + boost::lexical_cast<std::string>(i)); } df.add_field("tplus1"); for(std::size_t i=0; i<M.size1(); ++i) { typename EA::fitness_function_type::row_type r(M,i); df.write(T(i)) .write_all(r.begin(), r.end()) .write(Tp1(i)) .endl(); } } }; template <typename EA> struct sunspot_train_predictions : public ealib::analysis::unary_function<EA> { static const char* name() { return "sunspot_train_predictions";} virtual void operator()(EA& ea) { using namespace ealib; using namespace ealib::analysis; namespace bnu=boost::numeric::ublas; typename EA::individual_type& ind = analysis::find_dominant(ea); datafile df("sunspot_train_predictions.dat"); df.add_field("sample").add_field("t").add_field("observed").add_field("predicted"); sunspot_fitness::matrix_type output; ea.fitness_function().train(ind, output, ea.rng(), ea); sunspot_fitness::vector_type& observed = ea.fitness_function()._test_tplus1; double factor = static_cast<double>(1 << get<SUNSPOT_FRACTIONAL_BITS>(ea)); for(std::size_t i=0; i<get<SUNSPOT_PREDICTION_HORIZON>(ea); ++i) { sunspot_fitness::column_type c(output,i); assert(c.size() == observed.size()); sunspot_fitness::dvector_type obs = bnu::vector_range<sunspot_fitness::vector_type>(observed, bnu::range(i,observed.size())) / factor; sunspot_fitness::dvector_type pre = bnu::vector_range<sunspot_fitness::column_type>(c, bnu::range(0,c.size()-i)) / factor; assert(obs.size() == pre.size()); for(std::size_t j=0; j<obs.size(); ++j) { df.write(j).write(i+1).write(obs(j)).write(pre(j)).endl(); } } } }; template <typename EA> struct sunspot_test_predictions : public ealib::analysis::unary_function<EA> { static const char* name() { return "sunspot_test_predictions";} virtual void operator()(EA& ea) { using namespace ealib; using namespace ealib::analysis; namespace bnu=boost::numeric::ublas; typename EA::individual_type& ind = analysis::find_dominant(ea); datafile df("sunspot_test_predictions.dat"); df.add_field("sample").add_field("t").add_field("observed").add_field("predicted"); sunspot_fitness::matrix_type output; ea.fitness_function().test(ind, output, ea.rng(), ea); sunspot_fitness::vector_type& observed = ea.fitness_function()._test_tplus1; double factor = static_cast<double>(1 << get<SUNSPOT_FRACTIONAL_BITS>(ea)); for(std::size_t i=0; i<get<SUNSPOT_PREDICTION_HORIZON>(ea); ++i) { sunspot_fitness::column_type c(output,i); assert(c.size() == observed.size()); sunspot_fitness::dvector_type obs = bnu::vector_range<sunspot_fitness::vector_type>(observed, bnu::range(i,observed.size())) / factor; sunspot_fitness::dvector_type pre = bnu::vector_range<sunspot_fitness::column_type>(c, bnu::range(0,c.size()-i)) / factor; assert(obs.size() == pre.size()); for(std::size_t j=0; j<obs.size(); ++j) { df.write(j).write(i+1).write(obs(j)).write(pre(j)).endl(); } } } }; template <typename EA> struct sunspot_train_detail : public ealib::analysis::unary_function<EA> { static const char* name() { return "sunspot_train_detail";} virtual void operator()(EA& ea) { using namespace ealib; using namespace ealib::analysis; typename EA::individual_type& ind = analysis::find_dominant(ea); datafile df("sunspot_train_detail.dat"); df.add_field("observed"); for(std::size_t i=0; i<get<SUNSPOT_PREDICTION_HORIZON>(ea); ++i) { df.add_field("tplus" + boost::lexical_cast<std::string>(i+1)); } sunspot_fitness::matrix_type output; ea.fitness_function().train(ind, output, ea.rng(), ea); for(std::size_t i=0; i<output.size1(); ++i) { df.write(ea.fitness_function()._train_tplus1(i)); for(std::size_t j=0; j<output.size2(); ++j) { df.write(output(i,j)); } df.endl(); } } }; template <typename EA> struct sunspot_test_detail : public ealib::analysis::unary_function<EA> { static const char* name() { return "sunspot_test_detail";} virtual void operator()(EA& ea) { using namespace ealib; using namespace ealib::analysis; typename EA::individual_type& ind = analysis::find_dominant(ea); datafile df("sunspot_test_detail.dat"); df.add_field("observed"); for(std::size_t i=0; i<get<SUNSPOT_PREDICTION_HORIZON>(ea); ++i) { df.add_field("tplus" + boost::lexical_cast<std::string>(i+1)); } sunspot_fitness::matrix_type output; ea.fitness_function().test(ind, output, ea.rng(), ea); for(std::size_t i=0; i<output.size1(); ++i) { df.write(ea.fitness_function()._test_tplus1(i)); for(std::size_t j=0; j<output.size2(); ++j) { df.write(output(i,j)); } df.endl(); } } }; template <typename EA> struct sunspot_train_rmse : public ealib::analysis::unary_function<EA> { static const char* name() { return "sunspot_train_rmse";} virtual void operator()(EA& ea) { using namespace ealib; using namespace ealib::analysis; typename EA::individual_type& ind = analysis::find_dominant(ea); datafile df("sunspot_train_rmse.dat"); df.add_field("total_rmse"); for(std::size_t i=0; i<get<SUNSPOT_PREDICTION_HORIZON>(ea); ++i) { df.add_field("tplus" + boost::lexical_cast<std::string>(i+1)); } sunspot_fitness::matrix_type output; sunspot_fitness::dvector_type rmse = ea.fitness_function().train(ind, output, ea.rng(), ea); df.write(std::accumulate(rmse.begin(),rmse.end(),0.0)).write_all(rmse.begin(), rmse.end()).endl(); } }; template <typename EA> struct sunspot_test_rmse : public ealib::analysis::unary_function<EA> { static const char* name() { return "sunspot_test_rmse";} virtual void operator()(EA& ea) { using namespace ealib; using namespace ealib::analysis; typename EA::individual_type& ind = analysis::find_dominant(ea); datafile df("sunspot_test_rmse.dat"); df.add_field("total_rmse"); for(std::size_t i=0; i<get<SUNSPOT_PREDICTION_HORIZON>(ea); ++i) { df.add_field("tplus" + boost::lexical_cast<std::string>(i+1)); } sunspot_fitness::matrix_type output; sunspot_fitness::dvector_type rmse = ea.fitness_function().test(ind, output, ea.rng(), ea); df.write(std::accumulate(rmse.begin(),rmse.end(),0.0)).write_all(rmse.begin(), rmse.end()).endl(); } }; #endif
[ "dave.knoester@gmail.com" ]
dave.knoester@gmail.com
382480e6b503506eab059d94a05eda008620e571
9ead5fcc5efaf7a73c4c585d813c1cddcb89666d
/m5/src/dev/i8254xGBe.hh
738b1cf439cd37c018f1ec2f4cfe091aa6576f2d
[ "BSD-3-Clause" ]
permissive
x10an14/tdt4260Group
b539b6271c8f01f80a9f75249779fb277fa521a4
1c4dc24acac3fe6df749e0f41f4d7ab69f443514
refs/heads/master
2016-09-06T02:48:04.929661
2014-04-08T10:40:22
2014-04-08T10:40:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,631
hh
/* * Copyright (c) 2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Ali Saidi */ /* @file * Device model for Intel's 8254x line of gigabit ethernet controllers. */ #ifndef __DEV_I8254XGBE_HH__ #define __DEV_I8254XGBE_HH__ #include <deque> #include <string> #include "base/cp_annotate.hh" #include "base/inet.hh" #include "dev/etherdevice.hh" #include "dev/etherint.hh" #include "dev/etherpkt.hh" #include "dev/i8254xGBe_defs.hh" #include "dev/pcidev.hh" #include "dev/pktfifo.hh" #include "params/IGbE.hh" #include "sim/eventq.hh" class IGbEInt; class IGbE : public EtherDevice { private: IGbEInt *etherInt; CPA *cpa; // device registers iGbReg::Regs regs; // eeprom data, status and control bits int eeOpBits, eeAddrBits, eeDataBits; uint8_t eeOpcode, eeAddr; uint16_t flash[iGbReg::EEPROM_SIZE]; // The drain event if we have one Event *drainEvent; // cached parameters from params struct bool useFlowControl; // packet fifos PacketFifo rxFifo; PacketFifo txFifo; // Packet that we are currently putting into the txFifo EthPacketPtr txPacket; // Should to Rx/Tx State machine tick? bool rxTick; bool txTick; bool txFifoTick; bool rxDmaPacket; // Number of bytes copied from current RX packet unsigned pktOffset; // Delays in managaging descriptors Tick fetchDelay, wbDelay; Tick fetchCompDelay, wbCompDelay; Tick rxWriteDelay, txReadDelay; // Event and function to deal with RDTR timer expiring void rdtrProcess() { rxDescCache.writeback(0); DPRINTF(EthernetIntr, "Posting RXT interrupt because RDTR timer expired\n"); postInterrupt(iGbReg::IT_RXT); } //friend class EventWrapper<IGbE, &IGbE::rdtrProcess>; EventWrapper<IGbE, &IGbE::rdtrProcess> rdtrEvent; // Event and function to deal with RADV timer expiring void radvProcess() { rxDescCache.writeback(0); DPRINTF(EthernetIntr, "Posting RXT interrupt because RADV timer expired\n"); postInterrupt(iGbReg::IT_RXT); } //friend class EventWrapper<IGbE, &IGbE::radvProcess>; EventWrapper<IGbE, &IGbE::radvProcess> radvEvent; // Event and function to deal with TADV timer expiring void tadvProcess() { txDescCache.writeback(0); DPRINTF(EthernetIntr, "Posting TXDW interrupt because TADV timer expired\n"); postInterrupt(iGbReg::IT_TXDW); } //friend class EventWrapper<IGbE, &IGbE::tadvProcess>; EventWrapper<IGbE, &IGbE::tadvProcess> tadvEvent; // Event and function to deal with TIDV timer expiring void tidvProcess() { txDescCache.writeback(0); DPRINTF(EthernetIntr, "Posting TXDW interrupt because TIDV timer expired\n"); postInterrupt(iGbReg::IT_TXDW); } //friend class EventWrapper<IGbE, &IGbE::tidvProcess>; EventWrapper<IGbE, &IGbE::tidvProcess> tidvEvent; // Main event to tick the device void tick(); //friend class EventWrapper<IGbE, &IGbE::tick>; EventWrapper<IGbE, &IGbE::tick> tickEvent; uint64_t macAddr; void rxStateMachine(); void txStateMachine(); void txWire(); /** Write an interrupt into the interrupt pending register and check mask * and interrupt limit timer before sending interrupt to CPU * @param t the type of interrupt we are posting * @param now should we ignore the interrupt limiting timer */ void postInterrupt(iGbReg::IntTypes t, bool now = false); /** Check and see if changes to the mask register have caused an interrupt * to need to be sent or perhaps removed an interrupt cause. */ void chkInterrupt(); /** Send an interrupt to the cpu */ void delayIntEvent(); void cpuPostInt(); // Event to moderate interrupts EventWrapper<IGbE, &IGbE::delayIntEvent> interEvent; /** Clear the interupt line to the cpu */ void cpuClearInt(); Tick intClock() { return SimClock::Int::ns * 1024; } /** This function is used to restart the clock so it can handle things like * draining and resume in one place. */ void restartClock(); /** Check if all the draining things that need to occur have occured and * handle the drain event if so. */ void checkDrain(); void anBegin(std::string sm, std::string st, int flags = CPA::FL_NONE) { cpa->hwBegin((CPA::flags)flags, sys, macAddr, sm, st); } void anQ(std::string sm, std::string q) { cpa->hwQ(CPA::FL_NONE, sys, macAddr, sm, q, macAddr); } void anDq(std::string sm, std::string q) { cpa->hwDq(CPA::FL_NONE, sys, macAddr, sm, q, macAddr); } void anPq(std::string sm, std::string q, int num = 1) { cpa->hwPq(CPA::FL_NONE, sys, macAddr, sm, q, macAddr, NULL, num); } void anRq(std::string sm, std::string q, int num = 1) { cpa->hwRq(CPA::FL_NONE, sys, macAddr, sm, q, macAddr, NULL, num); } void anWe(std::string sm, std::string q) { cpa->hwWe(CPA::FL_NONE, sys, macAddr, sm, q, macAddr); } void anWf(std::string sm, std::string q) { cpa->hwWf(CPA::FL_NONE, sys, macAddr, sm, q, macAddr); } template<class T> class DescCache { protected: virtual Addr descBase() const = 0; virtual long descHead() const = 0; virtual long descTail() const = 0; virtual long descLen() const = 0; virtual void updateHead(long h) = 0; virtual void enableSm() = 0; virtual void actionAfterWb() {} virtual void fetchAfterWb() = 0; typedef std::deque<T *> CacheType; CacheType usedCache; CacheType unusedCache; T *fetchBuf; T *wbBuf; // Pointer to the device we cache for IGbE *igbe; // Name of this descriptor cache std::string _name; // How far we've cached int cachePnt; // The size of the descriptor cache int size; // How many descriptors we are currently fetching int curFetching; // How many descriptors we are currently writing back int wbOut; // if the we wrote back to the end of the descriptor ring and are going // to have to wrap and write more bool moreToWb; // What the alignment is of the next descriptor writeback Addr wbAlignment; /** The packet that is currently being dmad to memory if any */ EthPacketPtr pktPtr; /** Shortcut for DMA address translation */ Addr pciToDma(Addr a) { return igbe->platform->pciToDma(a); } public: /** Annotate sm*/ std::string annSmFetch, annSmWb, annUnusedDescQ, annUsedCacheQ, annUsedDescQ, annUnusedCacheQ, annDescQ; DescCache(IGbE *i, const std::string n, int s); virtual ~DescCache(); std::string name() { return _name; } /** If the address/len/head change when we've got descriptors that are * dirty that is very bad. This function checks that we don't and if we * do panics. */ void areaChanged(); void writeback(Addr aMask); void writeback1(); EventWrapper<DescCache, &DescCache::writeback1> wbDelayEvent; /** Fetch a chunk of descriptors into the descriptor cache. * Calls fetchComplete when the memory system returns the data */ void fetchDescriptors(); void fetchDescriptors1(); EventWrapper<DescCache, &DescCache::fetchDescriptors1> fetchDelayEvent; /** Called by event when dma to read descriptors is completed */ void fetchComplete(); EventWrapper<DescCache, &DescCache::fetchComplete> fetchEvent; /** Called by event when dma to writeback descriptors is completed */ void wbComplete(); EventWrapper<DescCache, &DescCache::wbComplete> wbEvent; /* Return the number of descriptors left in the ring, so the device has * a way to figure out if it needs to interrupt. */ unsigned descLeft() const { unsigned left = unusedCache.size(); if (cachePnt > descTail()) left += (descLen() - cachePnt + descTail()); else left += (descTail() - cachePnt); return left; } /* Return the number of descriptors used and not written back. */ unsigned descUsed() const { return usedCache.size(); } /* Return the number of cache unused descriptors we have. */ unsigned descUnused() const { return unusedCache.size(); } /* Get into a state where the descriptor address/head/etc colud be * changed */ void reset(); virtual void serialize(std::ostream &os); virtual void unserialize(Checkpoint *cp, const std::string &section); virtual bool hasOutstandingEvents() { return wbEvent.scheduled() || fetchEvent.scheduled(); } }; class RxDescCache : public DescCache<iGbReg::RxDesc> { protected: virtual Addr descBase() const { return igbe->regs.rdba(); } virtual long descHead() const { return igbe->regs.rdh(); } virtual long descLen() const { return igbe->regs.rdlen() >> 4; } virtual long descTail() const { return igbe->regs.rdt(); } virtual void updateHead(long h) { igbe->regs.rdh(h); } virtual void enableSm(); virtual void fetchAfterWb() { if (!igbe->rxTick && igbe->getState() == SimObject::Running) fetchDescriptors(); } bool pktDone; /** Variable to head with header/data completion events */ int splitCount; /** Bytes of packet that have been copied, so we know when to set EOP */ unsigned bytesCopied; public: RxDescCache(IGbE *i, std::string n, int s); /** Write the given packet into the buffer(s) pointed to by the * descriptor and update the book keeping. Should only be called when * there are no dma's pending. * @param packet ethernet packet to write * @param pkt_offset bytes already copied from the packet to memory * @return pkt_offset + number of bytes copied during this call */ int writePacket(EthPacketPtr packet, int pkt_offset); /** Called by event when dma to write packet is completed */ void pktComplete(); /** Check if the dma on the packet has completed and RX state machine * can continue */ bool packetDone(); EventWrapper<RxDescCache, &RxDescCache::pktComplete> pktEvent; // Event to handle issuing header and data write at the same time // and only callking pktComplete() when both are completed void pktSplitDone(); EventWrapper<RxDescCache, &RxDescCache::pktSplitDone> pktHdrEvent; EventWrapper<RxDescCache, &RxDescCache::pktSplitDone> pktDataEvent; virtual bool hasOutstandingEvents(); virtual void serialize(std::ostream &os); virtual void unserialize(Checkpoint *cp, const std::string &section); }; friend class RxDescCache; RxDescCache rxDescCache; class TxDescCache : public DescCache<iGbReg::TxDesc> { protected: virtual Addr descBase() const { return igbe->regs.tdba(); } virtual long descHead() const { return igbe->regs.tdh(); } virtual long descTail() const { return igbe->regs.tdt(); } virtual long descLen() const { return igbe->regs.tdlen() >> 4; } virtual void updateHead(long h) { igbe->regs.tdh(h); } virtual void enableSm(); virtual void actionAfterWb(); virtual void fetchAfterWb() { if (!igbe->txTick && igbe->getState() == SimObject::Running) fetchDescriptors(); } bool pktDone; bool isTcp; bool pktWaiting; bool pktMultiDesc; Addr completionAddress; bool completionEnabled; uint32_t descEnd; // tso variables bool useTso; Addr tsoHeaderLen; Addr tsoMss; Addr tsoTotalLen; Addr tsoUsedLen; Addr tsoPrevSeq;; Addr tsoPktPayloadBytes; bool tsoLoadedHeader; bool tsoPktHasHeader; uint8_t tsoHeader[256]; Addr tsoDescBytesUsed; Addr tsoCopyBytes; int tsoPkts; public: TxDescCache(IGbE *i, std::string n, int s); /** Tell the cache to DMA a packet from main memory into its buffer and * return the size the of the packet to reserve space in tx fifo. * @return size of the packet */ unsigned getPacketSize(EthPacketPtr p); void getPacketData(EthPacketPtr p); void processContextDesc(); /** Return the number of dsecriptors in a cache block for threshold * operations. */ unsigned descInBlock(unsigned num_desc) { return num_desc / igbe->cacheBlockSize() / sizeof(iGbReg::TxDesc); } /** Ask if the packet has been transfered so the state machine can give * it to the fifo. * @return packet available in descriptor cache */ bool packetAvailable(); /** Ask if we are still waiting for the packet to be transfered. * @return packet still in transit. */ bool packetWaiting() { return pktWaiting; } /** Ask if this packet is composed of multiple descriptors * so even if we've got data, we need to wait for more before * we can send it out. * @return packet can't be sent out because it's a multi-descriptor * packet */ bool packetMultiDesc() { return pktMultiDesc;} /** Called by event when dma to write packet is completed */ void pktComplete(); EventWrapper<TxDescCache, &TxDescCache::pktComplete> pktEvent; void headerComplete(); EventWrapper<TxDescCache, &TxDescCache::headerComplete> headerEvent; void completionWriteback(Addr a, bool enabled) { DPRINTF(EthernetDesc, "Completion writeback Addr: %#x enabled: %d\n", a, enabled); completionAddress = a; completionEnabled = enabled; } virtual bool hasOutstandingEvents(); void nullCallback() { DPRINTF(EthernetDesc, "Completion writeback complete\n"); } EventWrapper<TxDescCache, &TxDescCache::nullCallback> nullEvent; virtual void serialize(std::ostream &os); virtual void unserialize(Checkpoint *cp, const std::string &section); }; friend class TxDescCache; TxDescCache txDescCache; public: typedef IGbEParams Params; const Params * params() const { return dynamic_cast<const Params *>(_params); } IGbE(const Params *params); ~IGbE() {} virtual void init(); virtual EtherInt *getEthPort(const std::string &if_name, int idx); Tick clock; Tick lastInterrupt; inline Tick ticks(int numCycles) const { return numCycles * clock; } virtual Tick read(PacketPtr pkt); virtual Tick write(PacketPtr pkt); virtual Tick writeConfig(PacketPtr pkt); bool ethRxPkt(EthPacketPtr packet); void ethTxDone(); virtual void serialize(std::ostream &os); virtual void unserialize(Checkpoint *cp, const std::string &section); virtual unsigned int drain(Event *de); virtual void resume(); }; class IGbEInt : public EtherInt { private: IGbE *dev; public: IGbEInt(const std::string &name, IGbE *d) : EtherInt(name), dev(d) { } virtual bool recvPacket(EthPacketPtr pkt) { return dev->ethRxPkt(pkt); } virtual void sendDone() { dev->ethTxDone(); } }; #endif //__DEV_I8254XGBE_HH__
[ "chrischa@stud.ntnu.no" ]
chrischa@stud.ntnu.no
a6a9b8ec7bbed650261a9493663678c75760530c
ac3a1f31c535496ec0d6504e5ee5a185c384bd58
/test/People.h
78a2377a6c5e32084a30d09b1c4de53dba45c6aa
[]
no_license
dark1412myj/GDI-Game
c6d1e93bd0ec6caffbbc0a58d8c1673b34cdee28
49886332b0026909148ccd7783381300ca630d93
refs/heads/master
2021-04-05T23:43:58.806124
2018-03-13T10:19:03
2018-03-13T10:19:03
124,888,706
4
0
null
null
null
null
UTF-8
C++
false
false
333
h
#pragma once //#include "stdafx.h" #include "thing.h" class CPeople : public CThing { int m_targetX,m_targetY; public: CPeople(void); CPeople(int x,int y):CThing(x,y){} void setPicBase(int p){this->m_pic_base=p;} void setTarget(int x,int y); virtual int run(); int mesure(); ~CPeople(void); bool drawHeself(HDC hdc); };
[ "504112619@qq.com" ]
504112619@qq.com
ce00ef179a32ff5de5b3182cedf153683b116b35
5dca2df244f64ab5c3b7288e9525b0194d1ee922
/tutoriais/test.cpp
f9dd37ec2bd8f5a8360dd031e6e39e76a441a0c1
[]
no_license
Frankson18/processamento-digital-imagens
096446bb9eab6683ef733bd29650a93e5400cdb0
60f7d3394f0c5609c9dfabb768f71913159f9c13
refs/heads/main
2023-07-15T09:10:10.831482
2021-08-27T04:52:13
2021-08-27T04:52:13
388,305,068
0
0
null
null
null
null
UTF-8
C++
false
false
2,947
cpp
#include <iostream> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; void printmask(Mat &m){ for(int i=0; i<m.size().height; i++){ for(int j=0; j<m.size().width; j++){ cout << m.at<float>(i,j) << ","; } cout << endl; } } void menu(){ cout << "\npressione a tecla para ativar o filtro: \n" "a - calcular modulo\n" "m - media\n" "g - gauss\n" "v - vertical\n" "h - horizontal\n" "l - laplaciano\n" "x - laplaciano do gaussiano\n" "esc - sair\n"; } int main(int argvc, char** argv){ VideoCapture video; float media[] = {1,1,1, 1,1,1, 1,1,1}; float gauss[] = {1,2,1, 2,4,2, 1,2,1}; float horizontal[]={-1,0,1, -2,0,2, -1,0,1}; float vertical[]={-1,-2,-1, 0,0,0, 1,2,1}; float laplacian[]={0,-1,0, -1,4,-1, 0,-1,0}; //laplaciano do gaussiano float LoG[]={0,0,-1,0,0,0,-1,-2,-1,0,-1,-2,16,-2,-1, 0,-1,-2,-1,0,0,0,-1,0,0}; Mat cap, frame, frame32f, frameFiltered; Mat mask(3,3,CV_32F), mask1; Mat result, result1; double width, height, min, max; int absolut; char key; video.open(0); if(!video.isOpened()) return -1; width=video.get(CV_CAP_PROP_FRAME_WIDTH); height=video.get(CV_CAP_PROP_FRAME_HEIGHT); std::cout << "largura=" << width << "\n";; std::cout << "altura =" << height<< "\n";; namedWindow("filtroespacial",1); mask = Mat(3, 3, CV_32F, media); scaleAdd(mask, 1/9.0, Mat::zeros(3,3,CV_32F), mask1); swap(mask, mask1); absolut=1; // calcs abs of the image menu(); for(;;){ video >> cap; cvtColor(cap, frame, CV_BGR2GRAY); //lip(frame, frame, 1); imshow("original", frame); frame.convertTo(frame32f, CV_32F); filter2D(frame32f, frameFiltered, frame32f.depth(), mask, Point(1,1), 0); if(absolut){ frameFiltered=abs(frameFiltered); } frameFiltered.convertTo(result, CV_8U); imshow("filtroespacial", result); key = (char) waitKey(10); if( key == 27 ) break; // esc pressed! switch(key){ case 'a': menu(); absolut=!absolut; break; case 'm': menu(); mask = Mat(3, 3, CV_32F, media); scaleAdd(mask, 1/9.0, Mat::zeros(3,3,CV_32F), mask1); mask = mask1; printmask(mask); break; case 'g': menu(); mask = Mat(3, 3, CV_32F, gauss); scaleAdd(mask, 1/16.0, Mat::zeros(3,3,CV_32F), mask1); mask = mask1; printmask(mask); break; case 'h': menu(); mask = Mat(3, 3, CV_32F, horizontal); printmask(mask); break; case 'v': menu(); mask = Mat(3, 3, CV_32F, vertical); printmask(mask); break; case 'l': menu(); mask = Mat(3, 3, CV_32F, laplacian); printmask(mask); break; case 'x': menu(); mask = Mat(5, 5, CV_32F, LoG); printmask(mask); break; default: break; } } return 0; }
[ "noreply@github.com" ]
noreply@github.com
ba3ce18445cd805fa43cb7eab8262724a79f2d82
0d462c69a464edc7e95e65d13ebce62834164bb6
/codegen/codegen.cpp
6fe7dac3d6b1157ce9a1f16ddfd88630afd1e593
[]
no_license
Kazanovitz/compiler
2b72320247f77e2ccee7096ee835ebebc6a17245
51647ecc12244660f480368311f9f8a0a763f2bc
refs/heads/master
2020-06-09T01:30:32.937300
2014-03-16T07:22:18
2014-03-16T07:22:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,054
cpp
#include "ast.hpp" #include "symtab.hpp" #include "classhierarchy.hpp" #include "primitive.hpp" #include "assert.h" #include <typeinfo> #include <stdio.h> class Codegen : public Visitor { private: FILE * m_outputfile; SymTab *m_symboltable; ClassTable *m_classtable; const char * heapStart="_heap_start"; const char * heapTop="_heap_top"; const char * printFormat=".LC0"; const char * printFun="Print"; OffsetTable*currClassOffset; OffsetTable*currMethodOffset; // basic size of a word (integers and booleans) in bytes static const int wordsize = 4; int label_count; //access with new_label // ********** Helper functions ******************************** // this is used to get new unique labels (cleverly named label1, label2, ...) int new_label() { return label_count++; } // PART 1: // 1) get arithmetic expressions on integers working: // you wont really be able to run your code, // but you can visually inspect it to see that the correct // chains of opcodes are being generated. // 2) get function calls working: // if you want to see at least a very simple program compile // and link successfully against gcc-produced code, you // need to get at least this far // 3) get boolean operation working // before we can implement any of the conditional control flow // stuff, we need to have booleans worked out. // 4) control flow: // we need a way to have if-elses and for loops in our language. // // Hint: Symbols have an associated member variable called m_offset // That offset can be used to figure out where in the activation // record you should look for a particuar variable /////////////////////////////////////////////////////////////////////////////// // // function_prologue // function_epilogue // // Together these two functions implement the callee-side of the calling // convention. A stack frame has the following layout: // // <- SP (before pre-call / after epilogue) // high ----------------- // | actual arg 1 | // | ... | // | actual arg n | // ----------------- // | Return Addr | // ================= // | temporary 1 | <- SP (when starting prologue) // | ... | // | temporary n | // low ----------------- <- SP (when done prologue) // // // || // || // \ / // \/ // // // The caller is responsible for placing the actual arguments // and the return address on the stack. Actually, the return address // is put automatically on the stack as part of the x86 call instruction. // // On function entry, the callee // // (1) allocates space for the callee's temporaries on the stack // // (2) saves callee-saved registers (see below) - including the previous activation record pointer (%ebp) // // (3) makes the activation record pointer (frame pointer - %ebp) point to the start of the temporary region // // (4) possibly copies the actual arguments into the temporary variables to allow easier access // // On function exit, the callee: // // (1) pops the callee's activation record (temporay area) off the stack // // (2) restores the callee-saved registers, including the activation record of the caller (%ebp) // // (3) jumps to the return address (using the x86 "ret" instruction, this automatically pops the // return address off the stack // ////////////////////////////////////////////////////////////////////////////// // // Since we are interfacing with code produced by GCC, we have to respect the // calling convention that GCC demands: // // Contract between caller and callee on x86: // * after call instruction: // o %eip points at first instruction of function // o %esp+4 points at first argument // o %esp points at return address // * after ret instruction: // o %eip contains return address // o %esp points at arguments pushed by caller // o called function may have trashed arguments // o %eax contains return value (or trash if function is void) // o %ecx, %edx may be trashed // o %ebp, %ebx, %esi, %edi must contain contents from time of call // * Terminology: // o %eax, %ecx, %edx are "caller save" registers // o %ebp, %ebx, %esi, %edi are "callee save" registers //////////////////////////////////////////////////////////////////////////////// void init() { fprintf( m_outputfile, ".text\n\n"); fprintf( m_outputfile, ".comm %s,4,4\n", heapStart); fprintf( m_outputfile, ".comm %s,4,4\n\n", heapTop); fprintf( m_outputfile, "%s:\n", printFormat); fprintf( m_outputfile, " .string \"%%d\\n\"\n"); fprintf( m_outputfile, " .text\n"); fprintf( m_outputfile, " .globl %s\n",printFun); fprintf( m_outputfile, " .type %s, @function\n\n",printFun); fprintf( m_outputfile, ".global %s\n",printFun); fprintf( m_outputfile, "%s:\n",printFun); fprintf( m_outputfile, " pushl %%ebp\n"); fprintf( m_outputfile, " movl %%esp, %%ebp\n"); fprintf( m_outputfile, " movl 8(%%ebp), %%eax\n"); fprintf( m_outputfile, " pushl %%eax\n"); fprintf( m_outputfile, " pushl $.LC0\n"); fprintf( m_outputfile, " call printf\n"); fprintf( m_outputfile, " addl $8, %%esp\n"); fprintf( m_outputfile, " leave\n"); fprintf( m_outputfile, " ret\n\n"); } void start(int programSize) { fprintf( m_outputfile, "# Start Function\n"); fprintf( m_outputfile, ".global Start\n"); fprintf( m_outputfile, "Start:\n"); fprintf( m_outputfile, " pushl %%ebp\n"); fprintf( m_outputfile, " movl %%esp, %%ebp\n"); fprintf( m_outputfile, " movl 8(%%ebp), %%ecx\n"); fprintf( m_outputfile, " movl %%ecx, %s\n",heapStart); fprintf( m_outputfile, " movl %%ecx, %s\n",heapTop); fprintf( m_outputfile, " addl $%d, %s\n",programSize,heapTop); fprintf( m_outputfile, " pushl %s \n",heapStart); fprintf( m_outputfile, " call Program_start \n"); fprintf( m_outputfile, " leave\n"); fprintf( m_outputfile, " ret\n"); } void allocSpace(int size) { // Optional WRITE ME } //////////////////////////////////////////////////////////////////////////////// public: Codegen(FILE * outputfile, SymTab * st, ClassTable* ct) { m_outputfile = outputfile; m_symboltable = st; m_classtable = ct; label_count = 0; currMethodOffset=currClassOffset=NULL; } void printSymTab(){ FILE * pFile; pFile = fopen ("myfile.txt" , "w"); m_symboltable->dump(pFile); fclose (pFile); } void visitProgramImpl(ProgramImpl *p) { init(); p->visit_children(this); // WRITEME } void visitClassImpl(ClassImpl *p) { ClassIDImpl * ClassIdP = dynamic_cast<ClassIDImpl*>(p->m_classid_1); char * key1 = strdup(ClassIdP->m_classname->spelling()); Symbol * symPtr = new Symbol; symPtr->classType.classID = ClassIdP->m_classname->spelling(); m_symboltable->insert((char *)"xxx", symPtr); p->visit_children(this); // WRITEME } void visitDeclarationImpl(DeclarationImpl *p) { // cout<<"can i subtract here?"<<endl; p->visit_children(this); // cout<<"whaddabout here?"<<endl; // WRITEME } void visitMethodImpl(MethodImpl *p) { fprintf( m_outputfile, "#### METHOD IMPLEMENTATION\n"); int localSpace, args, mem; int j=0; int methMem = 0; CompoundType info; currMethodOffset = new OffsetTable(); // cout<<"before my childen"<<endl; //this is to make the label name Symbol * symbP; SymScope * sync; MethodIDImpl * MethIdP = dynamic_cast<MethodIDImpl*>(p->m_methodid); char * funcName = strdup(MethIdP->m_symname->spelling()); sync = m_symboltable->get_current_scope(); symbP = sync->lookup((const char *)"xxx"); char * classMethName = strdup(symbP->classType.classID); strcat(classMethName,"_"); strcat(classMethName,funcName); fprintf( m_outputfile, "_%s:\n",classMethName); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ fprintf( m_outputfile, " pushl %%ebp\n"); fprintf( m_outputfile, " movl %%esp , %%ebp\n"); MethodBodyImpl * MethBodP = dynamic_cast<MethodBodyImpl*>(p->m_methodbody); localSpace = (p->m_parameter_list->size() + MethBodP->m_declaration_list->size()); localSpace = localSpace * wordsize; // currMethodOffset->insert(classMethName, localSpace, 4,symbP->classType); currMethodOffset->setTotalSize(localSpace); currMethodOffset->setParamSize(p->m_parameter_list->size() * wordsize); //### inserting paramaters into the offset table ########### for (std::list<Parameter_ptr>::iterator it = p->m_parameter_list->begin() ; it != p->m_parameter_list->end(); ++it){ ParameterImpl * param = dynamic_cast<ParameterImpl*>(*it); VariableIDImpl * VarId = dynamic_cast<VariableIDImpl*>(param->m_variableid); info.baseType = param->m_type->m_attribute.m_type.baseType; if(info.baseType == 8){ info.classID = param->m_type->m_attribute.m_type.classType.classID; } else{ info.classID = "NO CLASS"; } methMem -= 4; // cout<<"Offset-> symname: "<<VarId->m_symname->spelling()<<" offset: "<<methMem<<" class type: " <<info.baseType<<endl; currMethodOffset->insert(VarId->m_symname->spelling(), methMem, 4,info); } //################################ //<><>Diving into Declaration <><><><>><><><><><><><><><><><>><><><><><>< typename std::list<Declaration_ptr>::iterator it = MethBodP->m_declaration_list->begin(); for( ; it != MethBodP->m_declaration_list->end(); ++it) { DeclarationImpl * DeclaP = dynamic_cast<DeclarationImpl *> (*it); typename std::list<VariableID_ptr>::iterator it = DeclaP->m_variableid_list->begin(); for( ; it != DeclaP->m_variableid_list->end(); ++it) { methMem -= 4; // need to move to the next offset VariableIDImpl * VarIdP = dynamic_cast<VariableIDImpl*>(*it); char * var = strdup(VarIdP->m_symname->spelling()); // cout<<"Offset-> symname: "<<var<<" Offset: "<<methMem<<" Class type: " <<endl; info.baseType = DeclaP->m_type->m_attribute.m_type.baseType; if(info.baseType == 8){ info.classID = DeclaP->m_type->m_attribute.m_type.classType.classID; } else{ info.classID = "NO CLASS"; } currMethodOffset->insert(var, methMem, 4,info); } } //<><><><><><><><><><><><><><><><><>><><><><><>< //~~~~ allocating space on the stack and moves parameters into local ~~~~~~ // cout<<"param size: "<<currMethodOffset->getParamSize()<<endl; // cout<<" LocalSpace: "<< -(methMem)<<endl; fprintf( m_outputfile, " subl $%d, %%esp\n",-(methMem)); mem = -4; for(int i = currMethodOffset->getParamSize() + 4; i>= 8; i = i-4){ fprintf( m_outputfile, " movl %d(%%ebp) , %%eax\n",i); fprintf( m_outputfile, " movl %%eax , %d(%%ebp)\n",mem); mem -= 4; // symbP->methodType.argsType[j].baseType; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ p->visit_children(this); // cout<<"after the children"<<endl; fprintf( m_outputfile, " leave\n"); fprintf( m_outputfile, " ret\n"); // WRITEME } void visitMethodBodyImpl(MethodBodyImpl *p) { p->visit_children(this); // WRITEME } void visitParameterImpl(ParameterImpl *p) { p->visit_children(this); // WRITEME } void visitAssignment(Assignment *p) { fprintf( m_outputfile, "#### ASSIGNMENT\n"); // cout<<"Before assignment@@@@@@@@@@@@@@@@@@@@@@ "<<endl; p->visit_children(this); // cout<<"AFTER assignment$$$$$$$$$$$$$$$$$$$$$$$$ "<<endl; VariableIDImpl * VarId = dynamic_cast<VariableIDImpl*>(p->m_variableid); char * varName = strdup(VarId->m_symname->spelling()); // fprintf( m_outputfile, " popl %%eax\n"); fprintf( m_outputfile, " movl %%eax , %d(%%ebp)\n",currMethodOffset->get_offset(varName)); // WRITEME } void visitIf(If *p) { fprintf( m_outputfile, "#### IF Statemet\n"); // cout<<"before IF Express"<<endl; if (p->m_expression != NULL) { p->m_expression->accept( this ); } else { this->visitNullPointer(); } fprintf( m_outputfile, " popl %%eax\n"); fprintf( m_outputfile, " movl $0 , %%ebx\n"); fprintf( m_outputfile, " cmp %%eax, %%ebx\n"); fprintf( m_outputfile, " je skip_%d\n", new_label()); // cout<<"the label count is: "<<label_count<<endl; // cout<<"Before IF state after express"<<endl; if (p->m_statement != NULL) { p->m_statement->accept( this ); } else { this->visitNullPointer(); } // cout<<"After IF Statemetn"<<endl; fprintf( m_outputfile, " skip_%d: \n",label_count-1); // WRITEME } void visitPrint(Print *p) { fprintf( m_outputfile, "#### PRINT\n"); p->visit_children(this); // WRITEME } void visitReturnImpl(ReturnImpl *p) { p->visit_children(this); // WRITEME } void visitTInteger(TInteger *p) { p->visit_children(this); // WRITEME } void visitTBoolean(TBoolean *p) { p->visit_children(this); // WRITEME } void visitTNothing(TNothing *p) { p->visit_children(this); // WRITEME } void visitTObject(TObject *p) { p->visit_children(this); // WRITEME } void visitClassIDImpl(ClassIDImpl *p) { p->visit_children(this); // WRITEME } void visitVariableIDImpl(VariableIDImpl *p) { p->visit_children(this); // WRITEME } void visitMethodIDImpl(MethodIDImpl *p) { p->visit_children(this); // WRITEME } void visitPlus(Plus *p) { fprintf( m_outputfile, "#### ADD\n"); p -> visit_children(this); fprintf( m_outputfile, " popl %%ebx\n"); fprintf( m_outputfile, " popl %%eax\n"); fprintf( m_outputfile, " addl %%ebx, %%eax\n"); fprintf( m_outputfile, " pushl %%eax\n"); // WRITEME } void visitMinus(Minus *p) { fprintf( m_outputfile, "#### MINUS\n"); p -> visit_children(this); fprintf( m_outputfile, " popl %%ebx\n"); fprintf( m_outputfile, " popl %%eax\n"); fprintf( m_outputfile, " subl %%ebx, %%eax\n"); fprintf( m_outputfile, " pushl %%eax\n"); // WRITEME } void visitTimes(Times *p) { fprintf( m_outputfile, "#### TIMES\n"); p -> visit_children(this); fprintf( m_outputfile, " popl %%ebx\n"); fprintf( m_outputfile, " popl %%eax\n"); fprintf( m_outputfile, " imull %%ebx, %%eax\n"); fprintf( m_outputfile, " pushl %%eax\n"); // WRITEME } void visitDivide(Divide *p) { fprintf( m_outputfile, "#### DIVIDE\n"); p -> visit_children(this); fprintf( m_outputfile, " popl %%ebx\n"); fprintf( m_outputfile, " popl %%eax\n"); fprintf( m_outputfile, " cdq\n"); fprintf( m_outputfile, " idivl %%ebx\n"); fprintf( m_outputfile, " pushl %%eax\n"); // WRITEME } void visitAnd(And *p) { fprintf( m_outputfile, "#### AND\n"); p -> visit_children(this); fprintf( m_outputfile, " popl %%ebx\n"); fprintf( m_outputfile, " popl %%eax\n"); fprintf( m_outputfile, " andl %%ebx, %%eax\n"); fprintf( m_outputfile, " pushl %%eax\n"); // WRITEME } void visitLessThan(LessThan *p) { fprintf( m_outputfile, "#### LESSTHAN\n"); p -> visit_children(this); new_label(); fprintf( m_outputfile, " popl %%ebx\n"); fprintf( m_outputfile, " popl %%eax\n"); fprintf( m_outputfile, " cmp %%ebx, %%eax\n"); fprintf( m_outputfile, " jl True_%d\n", label_count); fprintf( m_outputfile, " jmp False_%d\n", label_count); fprintf( m_outputfile, "True_%d: \n",label_count); fprintf( m_outputfile, " movl $1 , %%eax\n"); fprintf( m_outputfile, " pushl %%eax\n"); fprintf( m_outputfile, " jmp EndLT_%d\n", label_count); fprintf( m_outputfile, "False_%d: \n",label_count); fprintf( m_outputfile, " pushl %%eax\n"); fprintf( m_outputfile, " movl $0 , %%eax\n"); fprintf( m_outputfile, "EndLT_%d: \n",label_count); // WRITEME } void visitLessThanEqualTo(LessThanEqualTo *p) { fprintf( m_outputfile, "#### LESS THAN EQUAL TOO\n"); p -> visit_children(this); new_label(); fprintf( m_outputfile, " popl %%ebx\n"); fprintf( m_outputfile, " popl %%eax\n"); fprintf( m_outputfile, " cmp %%ebx, %%eax\n"); fprintf( m_outputfile, " jle True_%d\n", label_count); fprintf( m_outputfile, " jmp False_%d\n", label_count); fprintf( m_outputfile, "True_%d: \n",label_count); fprintf( m_outputfile, " movl $1 , %%eax\n"); fprintf( m_outputfile, " jmp EndLE_%d\n", label_count); fprintf( m_outputfile, " pushl %%eax\n"); fprintf( m_outputfile, "False_%d: \n",label_count); fprintf( m_outputfile, " pushl %%eax\n"); fprintf( m_outputfile, " movl $0 , %%eax\n"); fprintf( m_outputfile, "EndLE_%d: \n",label_count); // WRITEME } void visitNot(Not *p) { fprintf( m_outputfile, "#### NOT\n"); p -> visit_children(this); fprintf( m_outputfile, " popl %%eax\n"); fprintf( m_outputfile, " notl %%eax\n"); fprintf( m_outputfile, " pushl %%eax\n"); // WRITEME } void visitUnaryMinus(UnaryMinus *p) { fprintf( m_outputfile, "#### UNARY MINUS\n"); p -> visit_children(this); fprintf( m_outputfile, " popl %%eax\n"); fprintf( m_outputfile, " neg %%eax\n"); fprintf( m_outputfile, " pushl %%eax\n"); // WRITEME } void visitMethodCall(MethodCall *p) { fprintf( m_outputfile, "#### METHOD CALL\n"); p->visit_children(this); // WRITEME } void visitSelfCall(SelfCall *p) { fprintf( m_outputfile, "#### SELF CALL\n"); int args; Symbol * symbP; SymScope * sync; MethodIDImpl * MethIdP = dynamic_cast<MethodIDImpl*>(p->m_methodid); char * funcName = strdup(MethIdP->m_symname->spelling()); sync = m_symboltable->get_current_scope(); symbP = sync->lookup((const char *)"xxx"); p->visit_children(this); args = p->m_expression_list->size(); args = args * wordsize; // cout<<"the number of params: "<<args<<endl; char * className = strdup(symbP->classType.classID); strcat(className,"_"); strcat(className,funcName); fprintf( m_outputfile, "call %s\n",className); fprintf( m_outputfile, "addl $%d , %%esp\n",args); // WRITEME } void visitVariable(Variable *p) { //get value put in eax and push VariableIDImpl * VarId = dynamic_cast<VariableIDImpl*>(p->m_variableid); char * varName = strdup(VarId->m_symname->spelling()); fprintf( m_outputfile, " movl %d(%%ebp) , %%eax\n",currMethodOffset->get_offset(varName)); fprintf( m_outputfile, " pushl %%eax\n"); p->visit_children(this); // WRITEME } void visitIntegerLiteral(IntegerLiteral *p) { p->visit_children(this); // WRITEME } void visitBooleanLiteral(BooleanLiteral *p) { p->visit_children(this); // WRITEME } void visitNothing(Nothing *p) { p->visit_children(this); // WRITEME } void visitSymName(SymName *p) { // WRITEME } void visitPrimitive(Primitive *p) { fprintf( m_outputfile, "#### PRIMITIVE \n"); fprintf( m_outputfile, " movl $%d, %%eax\n", p->m_data); fprintf( m_outputfile, " pushl %%eax\n"); // WRITEME } void visitClassName(ClassName *p) { // WRITEME } void visitNullPointer() {} };
[ "Jono.Kassan@gmail.com" ]
Jono.Kassan@gmail.com
0af4d7a727ac5b2c4495ba851443135d6af7d42b
0169bc4f1196a2b9da7891440508f8662fd67b39
/Thelengthofthesegments.cpp
765f7635867fba2f914c9f8b34730b4a4bab8de2
[]
no_license
Woldos/My-first-works
1da1d4b91859b2d3e88d1b2b12509dcfd8adeb12
7d0cfb19b39a906fd4d77126cf453f2c0edf0c17
refs/heads/master
2020-07-09T17:51:05.621779
2019-11-18T23:35:38
2019-11-18T23:35:38
204,039,145
0
0
null
null
null
null
UTF-8
C++
false
false
364
cpp
#include <iostream> using namespace std; int main(){ int a,b,c,ab = 0, bc = 0,sum = 0; cin >> a >> b >> c; if (a > b){ ab = a - b; } else { ab = b - a; } if (b > c){ bc = b - c; } else { bc = c - b; } sum = ab + bc; cout << ab << " " << bc << " " << sum; return 0; }
[ "noreply@github.com" ]
noreply@github.com
261860dc58294fda08389198e0aa7984ecd385fc
060b94e4c1f72aabdbd470b556a939b01e30dcb0
/Buffer.cpp
fdf5122a63d4b3441ea728042fd938fba87bceb0
[]
no_license
annygakh/manuscrito
c0737ebf1fa35a1ca2f72bf0d9018ba04ff3d1b4
10a80321802ad205ce7a807d1db4cd3e59b4575c
refs/heads/master
2021-01-18T20:19:25.649359
2017-02-28T06:31:39
2017-02-28T06:31:39
82,375,067
5
1
null
null
null
null
UTF-8
C++
false
false
1,926
cpp
// // Created by Anaid Gakhokidze on 2016-11-16. // #include "Buffer.h" #include "Log.h" #include <sstream> Buffer::Buffer() : m_filename("") , m_fileOutput(NULL) , m_openForWriting(false) { m_lines.push_back(""); } std::string Buffer::generateName() { time_t t = time(0); // get time now struct tm * now = localtime( & t ); std::stringstream ss; ss << "Untitled" << (now->tm_year + 1900) << '-' << (now->tm_mon + 1) << '-' << now->tm_mday << '_' << now->tm_hour << ':' << now->tm_sec << ".txt"; return ss.str(); } Buffer::Buffer(std::string filename) : m_filename(filename) , m_fileOutput(NULL) , m_openForWriting(false) { std::ifstream file(filename, std::ifstream::out); Log::instance()->logMessage("Entered constructor\n"); // TODO move the following to initialize function if (file.is_open()) { while(!file.eof()) { std::string tmp; getline(file, tmp); m_lines.push_back(tmp); } } else { Log::instance()->logMessage("Could not open file %s\n", m_filename.c_str()); m_lines.push_back(""); m_filename = ""; } Log::instance()->logMessage("%s\n", m_filename.c_str()); file.close(); } bool Buffer::openFile(std::string filename) { if (!m_openForWriting) { m_fileOutput.open(filename, std::ios::trunc | std::ios::out); } return true; } bool Buffer::saveFile() { if (!m_openForWriting) { if (!filenameDefined()) { m_filename = generateName(); } openFile(m_filename); } for (std::string line : m_lines) { m_fileOutput << line; m_fileOutput << "\n"; } m_fileOutput.close(); return true; } Buffer::~Buffer() { if (m_openForWriting) { m_fileOutput.close(); } }
[ "annygakhokidze@gmail.com" ]
annygakhokidze@gmail.com
d86696eeefcbf5a8670935f8e1f6b2c53d057178
1845c6efb42540378628c21e884881eca9a13e4f
/Programming in C++/lab4/Interface.h
c340b42ad52266ff7e806a5a6434b659ee4abeaa
[]
no_license
nazzrrg/Programming-in-Cpp-Language-II
ed8e80459799cf190c568a594d15d1818ad3f7d7
555b4d2fe7d9e7f6310495b29d3b22815f7938ba
refs/heads/master
2021-01-07T06:32:41.539472
2020-05-31T16:57:18
2020-05-31T16:57:18
241,607,285
0
1
null
null
null
null
UTF-8
C++
false
false
2,852
h
// // Created by Егор Назаров on 25.02.2020. // #ifndef LAB4_INTERFACE_H #define LAB4_INTERFACE_H #include <string> class IGeoFig { public: [[nodiscard]] virtual double getSquare() const = 0; [[nodiscard]] virtual double getPerimeter() const = 0; }; class Vector2D { public: double x, y; Vector2D (){ x = y = 0; } Vector2D (double x_, double y_){ x = x_; y = y_; } }; class IPhysObject { public: [[nodiscard]] virtual double getMass() const = 0; [[nodiscard]] virtual Vector2D getPosition() const = 0; virtual bool operator==(const IPhysObject& ob) const = 0; virtual bool operator<(const IPhysObject& ob) const = 0; }; class IPrintable { public: virtual void draw() const = 0; }; class IDialogInitiable { public: virtual void initFromDialog() = 0; }; class IBaseObject { public: [[nodiscard]] virtual std::string getClassName() const = 0; [[nodiscard]] virtual uint64_t getSize() const = 0; }; class IFigure: public IGeoFig, public IPhysObject, public IPrintable, public IDialogInitiable, public IBaseObject {}; class Rectangle : public IFigure { private: const std::string name = "Rectangle"; double a, b; double mass; Vector2D position{}; public: bool operator==(const IPhysObject& x) const override; bool operator<(const IPhysObject& x) const override; [[nodiscard]] double getSquare() const override; [[nodiscard]] double getPerimeter() const override; [[nodiscard]] double getMass() const override; [[nodiscard]] Vector2D getPosition() const override; void draw() const override; void initFromDialog() override; [[nodiscard]] std::string getClassName() const override; [[nodiscard]] uint64_t getSize() const override; Rectangle(); Rectangle(const double& a_, const double& b_, const double& mass_, const Vector2D& position_); Rectangle(const Rectangle& x); }; class Trapeze : public IFigure { private: const std::string name = "Trapeze"; double a, b, h; double mass; Vector2D position{}; public: bool operator==(const IPhysObject& x) const override; bool operator<(const IPhysObject& x) const override; [[nodiscard]] double getSquare() const override; [[nodiscard]] double getPerimeter() const override; [[nodiscard]] double getMass() const override; [[nodiscard]] Vector2D getPosition() const override; void draw() const override; void initFromDialog() override; [[nodiscard]] std::string getClassName() const override; [[nodiscard]] uint64_t getSize() const override; Trapeze(); Trapeze(const double& a_, const double& b_, const double& h_, const double& mass_, const Vector2D& position_); Trapeze(const Trapeze& x); }; #endif //LAB4_INTERFACE_H
[ "nazarov.egor2010@yandex.ru" ]
nazarov.egor2010@yandex.ru
f47da3057a90e26c44e4b9417441713a860000e0
172a3e34144ac15dc80eaa44aeac664e77a04703
/src/lib/liquid/StringFragment.cpp
a9957446c25de8803624f640e121ec8b9b19c0bb
[ "Zlib" ]
permissive
ptf/openliquid
8ff6beb032b95f9bb733bdcd7b1055d1ea65f1f1
96ce45a84e820efbd4babf49aad6fad3b297f468
refs/heads/master
2021-01-21T03:25:25.676004
2012-05-09T12:50:36
2012-05-09T12:50:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,688
cpp
#include "Fragment.hpp" #define TARGET_TCL namespace Liquid { bool StringFragment::Compare(Fragment* other, ConditionalOperator op) { // Implicit operators need to respect boolean comparison if (op == ConditionalImplicit) { #ifdef TARGET_TCL if (this->_value == "t") return true; else if (this->_value == "f") return false; #endif return (!this->_value.empty()); } // Type dependant evaluation switch (other->GetType()) { case FragmentTypeBoolean: { #ifdef TARGET_TCL bool booleanValue = reinterpret_cast<BooleanFragment*>(other)->GetValue(); if (this->_value == "t") { if (op == ConditionalEquals) return booleanValue; if (op == ConditionalNotEquals) return !booleanValue; } else if (this->_value == "f") { if (op == ConditionalEquals) return !booleanValue; if (op == ConditionalNotEquals) return booleanValue; } #endif break; } case FragmentTypeEmpty: if (op == ConditionalEquals) return this->_value.empty(); if (op == ConditionalNotEquals) return !this->_value.empty(); return false; case FragmentTypeString: { int comparison = this->_value.compare(reinterpret_cast<StringFragment*>(other)->_value); switch (op) { case ConditionalEquals: return (comparison == 0); case ConditionalNotEquals: return (comparison != 0); case ConditionalGreaterThan: return (comparison > 0); case ConditionalLessThan: return (comparison < 0); case ConditionalGreaterThanOrEquals: return (comparison >= 0); case ConditionalLessThanOrEquals: return (comparison <= 0); default: return false; } } default: break; } return (op == ConditionalNotEquals); } }
[ "mail@nickbruun.dk" ]
mail@nickbruun.dk
c47b76889cc4d6846d740c73505f716232f17f3d
55a0a9c86b4af4fdda1ec481434252e1f6eed63f
/13days/Stack.h
1ebdc4e93609ac3b094dc004e7d7c5bad50b3bdc
[]
no_license
krud0726/C_PLUS_PLUS
6ec2df3d1427a129ba5af5a81330fba29e157ef6
966e36e86bb798a97466eb5e363edc81ad06d283
refs/heads/main
2023-06-19T07:29:44.923166
2021-07-19T14:53:21
2021-07-19T14:53:21
381,121,757
0
0
null
null
null
null
UTF-8
C++
false
false
1,046
h
// // Created by User on 2021-07-13. // #ifndef EXCEPTION_STACK_H #define EXCEPTION_STACK_H #include "StackException.h" #include <iostream> template<typename T> class Stack{ public: Stack(int sz) : size(sz) { s = new T[size]; }; // 객체 초기화 및 필요한 자원을 획득하시오 ~Stack() noexcept{ delete []s; }; // 사용한 자원을 해제하시오 // 복사 생성자와 복사 대입 연산자를 삭제하시오 Stack(Stack const&) = delete; Stack& operator=(Stack const&) = delete; void push(T c) { if(size <= top) {throw StackException("Stack is full!", "main.cpp", __LINE__);} s[top++] = c; }; T pop() { if((top == 0) || (size <= 0)) { throw StackException("Stack is empty!", "main.cpp", __LINE__);} T r = s[--top]; return r; }; void print() const{ for(int i=0; i< top; i++) { std::cout << s[i] << "\n"; } } private: int size = 0; int top = 0; T* s = nullptr; }; #endif //EXCEPTION_STACK_H
[ "49744553+krud0726@users.noreply.github.com" ]
49744553+krud0726@users.noreply.github.com
d2e5219e130d5df5c75002f7aea446269c10259d
00b7958b46df566e9d0ce80a6f968834af0af7b1
/importform.h
9577f49f37d4958d46917aa49da3ac4efcc056bf
[]
no_license
leeroyka/XMLDB
c6e8f215e9d48ec0a3d29ae4514383cafbbf2c7c
57a946e62e25b16d83e5cfc5b4607e88d22353e7
refs/heads/master
2020-04-30T19:58:59.468007
2019-03-22T17:02:47
2019-03-22T17:02:47
177,053,550
0
0
null
null
null
null
UTF-8
C++
false
false
289
h
#ifndef IMPORTFORM_H #define IMPORTFORM_H #include <QWidget> namespace Ui { class importForm; } class importForm : public QWidget { Q_OBJECT public: explicit importForm(QWidget *parent = nullptr); ~importForm(); private: Ui::importForm *ui; }; #endif // IMPORTFORM_H
[ "blokhin321@gmail.com" ]
blokhin321@gmail.com
3bca0c7ac3af53aaa1cd9a5a0e6c2ab06712e726
694c813173b7b57d76326248eb91d9af1d6dc4c9
/include/drc_shared/yarp_msgs/wall_msg.h
31ee53c79fd5c58a66956aa1870eb317135b285c
[]
no_license
ADVRHumanoids/DRC_shared
d33f951b221daedbc973f1ddd96d34f73cf4b7ee
86235f239f22c53ce0010e4c2b8557f215812713
refs/heads/master
2021-01-18T16:12:36.734694
2017-04-03T11:12:17
2017-04-03T11:12:17
86,728,779
0
0
null
null
null
null
UTF-8
C++
false
false
4,132
h
/* Software License Agreement (BSD License) * * Copyright (c) 2015-2016, Dimitrios Kanoulas * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder(s) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef WALL_MSG #define WALL_MSG #include <string> #include <yarp/os/Portable.h> #include <yarp/os/Bottle.h> #include <kdl/frames.hpp> #include "drc_shared/yarp_msgs/KDL_frame_msg.h" class wall_msg { /** \brief The wall message object represents the pose of a wall surface * (rotation, translation). * * \author Dimitrios Kanoulas */ public: /** \brief Constructor with the default values. */ wall_msg () { command = ""; frame = ""; wall_data.p.x (0.0); wall_data.p.y (0.0); wall_data.p.z (0.0); wall_data.M = KDL::Rotation::Identity(); } /** \brief YARP message exchange toBottle method. */ yarp::os::Bottle toBottle () { yarp::os::Bottle temp; yarp::os::Bottle& list= temp.addList (); list.addString (command); if (command == "walldatasent") { list.addString (frame); list.add (yarp_KDL::getBlob (wall_data)); } return temp; } /** \brief YARP message exchange fromBottle method. */ void fromBottle (yarp::os::Bottle* temp) { if (temp->get(0).isNull()) { command = ""; return; } yarp::os::Bottle* list = temp->get(0).asList(); if (list==NULL) { command = ""; return; } if (list->get(0).isNull()) { command = ""; return; } command = list->get(0).asString(); int index = 1; if (command == "walldatasent") { frame = list->get(index++).asString(); if (list->get(index).asBlobLength() != 0) { wall_data = yarp_KDL::fromBlob (list->get(index++)); } else { wall_data.p.x (list->get(index++).asDouble()); wall_data.p.y (list->get(index++).asDouble()); wall_data.p.z (list->get(index++).asDouble()); double qx,qy,qz,qw; qx = list->get(index++).asDouble(); qy = list->get(index++).asDouble(); qz = list->get(index++).asDouble(); qw = list->get(index++).asDouble(); wall_data.M = KDL::Rotation::Quaternion (qx,qy,qz,qw); } } return; } public: /** \brief The command name. */ std::string command; /** \brief The fixed frame of the data. */ std::string frame; /** \brief The Wall data frame (translation, rotation). */ KDL::Frame wall_data; }; #endif // WALL_MSG
[ "dimitrios.kanoulas@iit.it" ]
dimitrios.kanoulas@iit.it
ae9cd2891634c10cb6f9d8156f6942b0f92f529f
c389099930e650355c88f97745ff33599dcf425f
/CookOffs/COOK70_P1Z2S.cpp
ef9df90edb5138d14a8b408e3fcbd365c641d550
[]
no_license
mudit1993/Practice-Programs
51b5e4baeaf7507c5cfb246dd37a8adf2c2b24d7
3bbd6eb6d6fcd26e18cf58ea4aa22f6c02dd2f49
refs/heads/master
2021-07-16T07:24:05.739834
2020-06-27T15:25:01
2020-06-27T15:25:01
179,814,263
1
0
null
null
null
null
UTF-8
C++
false
false
360
cpp
#include <iostream> #include<cmath> #include<cstdio> using namespace std; long long a[100000]; int main() { long long n,i; long long sum=0; cin>>n; for(i=0;i<n;i++){ cin>>a[i]; sum+=a[i]; } if(sum%2==1){ sum=(sum+1)/2; } else sum/=2; if(sum<n) cout<<n<<endl; else cout<<sum<<endl; return 0; }
[ "mudit.madhogaria@sap.com" ]
mudit.madhogaria@sap.com
1c731e7839815368ba0940bd37712f07b35d1cae
646182cc74ac8b8bdc9750c5b0afbc86ff7f7601
/source/option/option.cpp
4fefe1efc24bd79ac6117aef6233dc17efbe1fa5
[ "LicenseRef-scancode-mulanpsl-2.0-en", "MulanPSL-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
qqsskk/tinyToolkit
04d42cfbedd1f8b8f4343de1c016ce6a5ecdb547
6387b8865d85cfbccac6b2acd758e497bd111a85
refs/heads/master
2022-12-20T12:05:40.856443
2020-10-21T03:18:13
2020-10-21T03:18:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,176
cpp
/** * * 作者: hm * * 说明: 解析器 * */ #include "option.h" #include <cstring> #include <iomanip> #include <sstream> #include <algorithm> namespace tinyToolkit { namespace option { /** * * 单例对象 * * @return 单例对象 * */ Option & Option::Instance() { static Option instance{ }; return instance; } /** * * 解析 * * @param argc 选项个数 * @param argv 选项数组 * */ void Option::Parse(int argc, const char * argv[]) { std::string opt{ }; std::string val{ }; std::string err{ }; for (int32_t i = 1; i < argc; ++i) { const char * value = argv[i]; const char * found = ::strstr(value, "="); std::unordered_map<std::string, DescriptionInfo *>::iterator iter{ }; if (::strncmp(value, "--", 2) == 0) { if (found) { val.assign(found + 1); opt.assign(value + 2, found); } else { opt.assign(value + 2); } err = "--" + opt; if (opt.empty()) { throw std::invalid_argument("Option is empty : " + err); } iter = _longOptions.find(opt); if (iter == _longOptions.end()) { throw std::invalid_argument("Undefined option : " + err); } } else if (::strncmp(value, "-", 1) == 0) { if (found) { val.assign(found + 1); opt.assign(value + 1, found); } else { opt.assign(value + 1); } err = "-" + opt; if (opt.empty()) { throw std::invalid_argument("Option is empty : " + err); } iter = _shortOptions.find(opt); if (iter == _shortOptions.end()) { throw std::invalid_argument("Undefined option : " + err); } } else { throw std::invalid_argument("Invalid option : " + std::string(value)); } if (iter->second->IsRequired()) { if (found == nullptr) { throw std::invalid_argument("Option require input value : " + err); } iter->second->Update(val); } else { if (found) { throw std::invalid_argument("Option do not require input value : " + err); } iter->second->Update(); } } } /** * * 添加描述组 * * @param group 描述组 * */ void Option::AddDescriptionGroup(const std::shared_ptr<DescriptionGroup> & group) { if (std::find(_groups.begin(), _groups.end(), group) != _groups.end()) { throw std::runtime_error("Multiple add description group : " + group->Caption()); } _groups.push_back(group); for (auto && iter : group->Options()) { if (!iter->LongName().empty()) { if (!_options.insert(std::make_pair(iter->LongName(), iter.get())).second || !_longOptions.insert(std::make_pair(iter->LongName(), iter.get())).second) { throw std::runtime_error("Multiple definition : " + iter->LongName()); } } if (!iter->ShortName().empty()) { if (!_options.insert(std::make_pair(iter->ShortName(), iter.get())).second || !_shortOptions.insert(std::make_pair(iter->ShortName(), iter.get())).second) { throw std::runtime_error("Multiple definition : " + iter->ShortName()); } } if (iter->IsRequired()) { if (iter->Value()->HasDefault()) { if (_modeWidth < (iter->Mode().size() + iter->Value()->Content().size() + 11)) { _modeWidth = iter->Mode().size() + iter->Value()->Content().size() + 11; } } else { if (_modeWidth < iter->Mode().size()) { _modeWidth = iter->Mode().size(); } } } if (_optionWidth < iter->OptionName().size()) { _optionWidth = iter->OptionName().size(); } } } /** * * 是否存在 * * @param option 选项 * * @return 是否存在 * */ bool Option::Exits(const std::string & option) const { auto find = _options.find(option); if (find == _options.end()) { return false; } return find->second->IsValid(); } /** * * 详细信息 * * @return 详细信息 * */ std::string Option::Verbose() { std::stringstream stream{ }; for (auto && group : _groups) { stream << std::endl << group->Caption() << ":" << std::endl; for (auto && option : group->Options()) { stream << " " << std::setw(static_cast<int32_t>(_optionWidth)) << std::right << option->OptionName() << " "; std::size_t width = _modeWidth; if (option->IsRequired()) { stream << option->Mode(); width -= option->Mode().size(); if (option->Value()->HasDefault()) { stream << " (default=" << option->Value()->Content() << ")"; width -= option->Value()->Content().size() + 11; } } if (width > 0) { stream << std::setw(static_cast<int32_t>(width)) << std::right << " "; } stream << " " << option->Info() << std::endl; } } return stream.str(); } } }
[ "huangmengmeng0526@gmail.com" ]
huangmengmeng0526@gmail.com
da49b0def3bb53403e32ca4bd2482735fabb0d1f
b5e242c6afaad1973f1ff3a86118e8e387ecd94b
/leetcode-algorithms/401. Binary Watch/401.BinaryWatch.cpp
9c76535f77b3c52e629e918af53f7265dbe8f420
[]
no_license
csyang79/algorithms-and-oj
e80c063585585ca5c447d7e657b7b5d3b06edd42
ccce7f0f6b14d02d777f09fb4a3ba1e78ecd958d
refs/heads/master
2021-04-12T08:16:11.538385
2019-10-02T12:08:48
2019-10-02T12:08:48
125,964,716
0
0
null
null
null
null
UTF-8
C++
false
false
361
cpp
class Solution { public: vector<string> readBinaryWatch(int num) { vector<string> res; for (int i = 0; i < 12; ++i) for (int j = 0; j < 60; ++j) if (bitset<10>((i << 6) | j).count() == num) res.emplace_back(to_string(i) + ":" + (j < 10 ? "0": "") + to_string(j)); return res; } };
[ "csyang79@gmail.com" ]
csyang79@gmail.com
2f8dc44806644541fd9f87f2bacda62ffade80f8
ae4d9cf742b9f6e5024bcd5bdf4b4473558da9e3
/_PSmine/PS모음/codeblock/codeup1476/main.cpp
48fb3b937b21415561c0c5223fc4329cb0cd2028
[]
no_license
son0179/ttt
b6d171141e0b7894258cfb367023de62cdc9dd19
a5153b0170c0df156c96d9be85b21d73f1f2e21e
refs/heads/master
2023-02-09T22:01:57.658467
2021-01-05T09:14:52
2021-01-05T09:14:52
200,059,589
1
0
null
null
null
null
UTF-8
C++
false
false
740
cpp
#include<stdio.h> int main(){ int a[100][100],n,m; scanf("%d %d",&n,&m); n--; m--; int x=0,y=0,i=1,s=1,l=1; while(1){ a[x][y]=i; if(x==n&&m==y){ break; } else{ if(y==m||x==0){ if(s<=n){ x=s; y=0; s++; } else{ x=n; y=l; l++; } } else{ x--; y++; } } i++; } for(int i=0;i<=n;i++){ for(int j=0;j<=m;j++){ printf("%d ",a[i][j]); } printf("\n"); } }
[ "starson2648@gmail.com" ]
starson2648@gmail.com
4f4d3dd6b37090add6ebf71ac2f35ba0e15d2f4f
181d3e8dc9cb7bef770dbdbb403c9afb4c755d0d
/naive-bayes/naive-bayes.cpp
7265086608adc8af71425fff7b7f77689998388b
[]
no_license
michaeldannunzio/ml-performance-test
d355d62afbdf30e934cb7bffaadd923c147ff39b
43da52e413f323df37c6a81898e569d7f3234027
refs/heads/master
2020-12-29T10:24:17.393050
2020-02-18T03:22:21
2020-02-18T03:22:21
238,572,850
2
0
null
2020-02-17T02:29:49
2020-02-06T00:00:09
C++
UTF-8
C++
false
false
7,419
cpp
/** * Project 4 * Part 1 - Naive Bayes * CS 4375.501 * Michael D'Annunzio & Zain Husain */ #include <cstdlib> // C standard library #include <iostream> // I/O streaming #include <vector> // better than arrays #include <map> // key value store #include <fstream> // file streaming #include <cmath> // math functions #include <string> // string utilities #include <armadillo> // matrix operations #include <ctime> // time using namespace std; using namespace arma; using namespace chrono; // preprocessor macros #define FILEPATH "./titanic_project.csv" #define TRAIN_TEST_SPLIT_INDEX 900 // type aliases typedef map<string, vector<double> > Dataframe; // function prototypes Dataframe read_csv(string); tuple<Dataframe, Dataframe> train_test_split(Dataframe, int); vector<string> split(const string&, const string&); string strip(const string&, const string&); void display(Dataframe); void display(vector<double>); // entry point // main logic int main(int argc, char *argv[]) { unsigned int tp = 0; unsigned int tn = 0; unsigned int fp = 0; unsigned int fn = 0; double acc; double sens; double spec; clock_t startTime; clock_t endTime; Dataframe df = read_csv(FILEPATH); int age = 0; int pclass = 1; int sex = 2; int survived = 3; // make single matrix from typedef Dataframe mat data = join_rows( mat(df["age"]), mat(df["pclass"]), mat(df["sex"]), mat(df["survived"]) ); // train-test split mat train = data.rows(0, 900); mat test = data.rows(901, data.n_rows - 1); startTime = clock(); vec apriori = { mat(train.rows(find(train.col(survived) == 0))).n_rows / (double) train.n_rows, mat(train.rows(find(train.col(survived) == 1))).n_rows / (double) train.n_rows }; uvec count_survived = { mat(train.rows(find(train.col(survived) == 0))).n_rows, mat(train.rows(find(train.col(survived) == 1))).n_rows }; mat lh_pclass(2, 3, fill::zeros); for (int sv = 0; sv < 2; sv++) { mat S = mat(train.rows(find(train.col(survived) == sv))); for (int pc = 0; pc < 3; pc++) { lh_pclass(sv, pc) = mat(S.rows(find(S.col(pclass) == pc + 1))).n_rows / (double) count_survived[sv]; } } mat lh_sex(2, 2, fill::zeros); for (int sv = 0; sv < 2; sv++) { mat S = mat(train.rows(find(train.col(survived) == sv))); for (int sx = 0; sx < 2; sx++) { lh_sex(sv, sx) = mat(S.rows(find(S.col(sex) == sx))).n_rows / (double) count_survived[sv]; } } vec age_mean = { 0, 0 }; vec age_var = { 0, 0 }; for (int sv = 0; sv < 2; sv++) { mat S = mat(train.rows(find(train.col(survived) == sv))); age_mean[sv] = mean(S.col(age)); age_var[sv] = var(S.col(age)); } auto calc_age_lh = [](int _age, double mean_v, double var_v) { double x = (1 / sqrt(2 * M_PI * var_v)); double y = pow((_age - mean_v), 2) / (2 * var_v); return x * y; }; auto calc_raw_prob = [lh_pclass, lh_sex, apriori, calc_age_lh, age_mean, age_var](int _pclass, int _sex, int _age) { double num_s = ( lh_pclass(1, _pclass - 1) * lh_sex(1, _sex) * apriori[1] * calc_age_lh(_age, age_mean[1], age_var[1]) ); double num_p = ( lh_pclass(0, _pclass - 1) * lh_sex(0, _sex) * apriori[0] * calc_age_lh(_age, age_mean[0], age_var[0]) ); double denominator = ( lh_pclass(1, _pclass - 1) * lh_sex(1, _sex) * calc_age_lh(_age, age_mean[1], age_var[1]) * apriori[1] + lh_pclass(0, _pclass - 1) * lh_sex(0, _sex) * calc_age_lh(_age, age_mean[0], age_var[0]) * apriori[0] ); vec prob_survived = { num_s / denominator, num_p / denominator }; return prob_survived; }; auto predict = [](double x) { return (int)round(x); }; vec raw; // testing for (int i = 0; i < 146; i++) { int _pclass = test.col(pclass)[i]; int _sex = test.col(sex)[i]; int _age = test.col(age)[i]; raw = calc_raw_prob(_pclass, _sex, _age); // col vector is size 2 int pred = predict(raw[0]); if (pred == 0) if (test.col(survived)[i] == 0) tn += 1; else fn += 1; else if (test.col(survived)[i] == 1) tp += 1; else fp += 1; } acc = (tp + tn) / (double) test.n_rows; sens = (double) tp / (tp + fn); spec = (double) tn / (tn + fp); endTime = clock(); cout << "Duration (s): " << (((float)endTime - (float)startTime) / CLOCKS_PER_SEC) << endl; cout << "True Positive: " << tp << endl; cout << "True Negative: " << tn << endl; cout << "False Positive: " << fp << endl; cout << "False Negative: " << fn << endl; cout << "Accuracy: " << acc << endl; cout << "Sensitivity: " << sens << endl; cout << "Specificity: " << spec << endl; return EXIT_SUCCESS; } tuple<Dataframe, Dataframe> train_test_split(Dataframe df, int split_index) { Dataframe train; Dataframe test; vector<string> attrs; // get column names for (Dataframe::iterator it = df.begin(); it != df.end(); it++) attrs.push_back(it->first); // iterate through dataset // split on index 900 for (int i = 0; i < df[attrs[0]].size(); i++) if (i < split_index) for (int j = 0; j < attrs.size(); j++) train[attrs[j]].push_back(df[attrs[j]][i]); else for (int j = 0; j < attrs.size(); j++) test[attrs[j]].push_back(df[attrs[j]][i]); return { train, test }; } Dataframe read_csv(string filepath) { Dataframe df; ifstream fin(filepath); char buffer[256]; vector<string> attrs; vector<string> vals; // check if file opened if (!fin) { cout << "[ERROR] Unable to open file: " << filepath << endl; exit(EXIT_FAILURE); } fin.getline(buffer, 256, '\n'); // read first line of csv file - column names attrs = split(buffer, ","); // clean strip double quotes from column names for (int i = 1; i < attrs.size(); i++) attrs[i] = strip(attrs[i], "\""); attrs[attrs.size()-1] = attrs[attrs.size()-1].substr(0, attrs[attrs.size()-1].length()-1); // read remaining data while (fin.getline(buffer, 256, '\n')) { vals = split(buffer, ","); for (int i = 1; i < attrs.size(); i++) df[attrs[i]].push_back(stof(vals[i])); // cast string value to float and save to dataframe } fin.close(); return df; } vector<string> split(const string& str, const string& delim) { vector<string> tokens; size_t prev = 0, pos = 0; do { pos = str.find(delim, prev); if (pos == string::npos) { pos = str.length(); } string token = str.substr(prev, pos-prev); if (!token.empty()) { tokens.push_back(token); } prev = pos + delim.length(); } while (pos < str.length() && prev < str.length()); return tokens; } string strip(const string& str, const string& delim) { vector<string> str_arr = split(str, delim); string final_str = ""; for (string s : str_arr) final_str += s; return final_str; } void display(Dataframe df) { vector<string> attrs; string attr; for (Dataframe::iterator it = df.begin(); it != df.end(); it++) { attr = it->first; attrs.push_back(attr); cout << attr << ","; } int len = df[attrs[0]].size(); cout << endl; for (int i = 1; i < len; i++) { for (int j = 0; j < attrs.size(); j++) { cout << df[attrs[j]][i] << ","; } cout << endl; } }
[ "michael.dannunzio3@gmail.com" ]
michael.dannunzio3@gmail.com
648db17773973269cea9c49435397f03148603d4
fd24eb59a764e916d70e65b5ba601e76cb18776a
/NeonBlasters/Source/NeonBlasters/DisparoJug2.cpp
28d51fe93e353fbdcfe855d9a6b9985963d96d34
[]
no_license
VLauren/NeonBlasters
a0eeea12e19a4100a84051d9cfa5f84a90c712a4
622e7ec8538c0d2de5253358b954ac811a718fe1
refs/heads/master
2021-05-09T17:53:52.820663
2018-01-28T13:40:13
2018-01-28T13:40:13
119,148,549
0
0
null
null
null
null
UTF-8
C++
false
false
1,290
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "DisparoJug2.h" const float VEL = 10000; // Sets default values ADisparoJug2::ADisparoJug2(const FObjectInitializer& objectInitializer) :Super(objectInitializer) { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; _collision = CreateDefaultSubobject<USphereComponent>(TEXT("RootCollision")); _collision->SetSphereRadius(200.f); _collision->SetHiddenInGame(false); RootComponent = _collision; } // Called when the game starts or when spawned void ADisparoJug2::BeginPlay() { Super::BeginPlay(); _collision->OnComponentBeginOverlap.AddDynamic(this, &ADisparoJug2::OnDisparoOverlap); } void ADisparoJug2::OnDisparoOverlap(UPrimitiveComponent * OverlappedComponent, AActor * OtherActor, UPrimitiveComponent * OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult) { // GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, "Overlap!"); UE_LOG(LogTemp, Warning, TEXT("ALGO?")); } // Called every frame void ADisparoJug2::Tick(float DeltaTime) { Super::Tick(DeltaTime); FVector Mov = FVector(VEL * DeltaTime, 0, 0); AddActorLocalOffset(Mov, true); }
[ "lau.16.9@gmail.com" ]
lau.16.9@gmail.com
890ab07144f13dbc0270a4c6420721d023a536d0
07c43092ac87907bdaeecff136b125b4f77182c2
/third_party/LLVM/include/llvm/Support/Atomic.h
1a6c606aa5f636af969ab6cd633e59d5362452eb
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "NCSA" ]
permissive
ddrmax/swiftshader-ex
9cd436f2a0e8bc9e0966de148e5a60f974c4b144
2d975b5090e778857143c09c21aa24255f41e598
refs/heads/master
2021-04-27T15:14:22.444686
2018-03-15T10:12:49
2018-03-15T10:12:49
122,465,205
7
0
Apache-2.0
2018-03-15T10:12:50
2018-02-22T10:40:03
C++
UTF-8
C++
false
false
1,185
h
//===- llvm/Support/Atomic.h - Atomic Operations -----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares the llvm::sys atomic operations. // //===----------------------------------------------------------------------===// #ifndef LLVM_SYSTEM_ATOMIC_H #define LLVM_SYSTEM_ATOMIC_H #include "llvm/Support/DataTypes.h" namespace llvm { namespace sys { void MemoryFence(); #ifdef _MSC_VER typedef long cas_flag; #else typedef uint32_t cas_flag; #endif cas_flag CompareAndSwap(volatile cas_flag* ptr, cas_flag new_value, cas_flag old_value); cas_flag AtomicIncrement(volatile cas_flag* ptr); cas_flag AtomicDecrement(volatile cas_flag* ptr); cas_flag AtomicAdd(volatile cas_flag* ptr, cas_flag val); cas_flag AtomicMul(volatile cas_flag* ptr, cas_flag val); cas_flag AtomicDiv(volatile cas_flag* ptr, cas_flag val); } } #endif
[ "capn@google.com" ]
capn@google.com
cdf6d20316e675df3292484375b11cfd5de4bffd
c40dcf880cfe595922138ac5bc915862d35e731d
/Control4_relays_with_RF_315_Receiver_bodule_and_remote.ino
fc13be9d7baf01013c726121dc844b407feb797d
[]
no_license
anokhramesh/RF315-Mhz-4-relay-control
fea27efbd968e5d137b441f97f5f9ba270155912
c384cc7820bae5b8bdeaadf7f2f71db0c3fd0f65
refs/heads/main
2023-07-15T04:21:48.165889
2021-08-10T09:05:00
2021-08-10T09:05:00
394,424,218
0
0
null
null
null
null
UTF-8
C++
false
false
6,269
ino
//In this Project We will controll 4 relays Remotely with the Help of Radio Frequency (YK04-Rf 315 or 433 Mhz Receiver Module)and its Remote control // Sketch Modified by Rameshkumar,Anokhautomation,anokhramesh@gmail.com,+971557407961,www.anokhautomation.blogspot.com //When pressed the Button-B of Remote control -Output will be High on RF Receiver module pin-D0 //When pressed the Button-D-of Remote cintrol- Output will be High on RF Receiver module pin-D1 //When pressed the Button-A of Remote control -Output will be High on RF Receiver module pin-D2 //When pressed the Button-C-of Remote control -Output will be High on RF Receiver module pin-D3 //Arduino Output Pin D09- Relay Module IN1 //Arduino Output Pin D10- Relay Module IN2 //Arduino Output Pin D11- Relay Module IN3 //Arduino Output Pin D12- Relay Module IN4 // initializing pin numbers: const int buttonPin1 = 2; // Connect D3 pin of RF Module to Arduino Pin#2 const int Relay_1 = 12; // Pin 12 will go High when pressed RF remote button-C const int buttonPin2 = 3; // Connect D2 pin of RF Module to Arduino Pin#3 const int Relay_2 = 11; // Pin 11 will go High when pressed RF remote button-A const int buttonPin3 = 4; // Connect D1 pin of RF Module to Arduino Pin#4 const int Relay_3 = 10; // Pin 10 will go High when pressed RF remote button-D const int buttonPin4 = 5; // Connect D0 pin of RF Module to Arduino Pin#5 const int Relay_4 = 9; //Pin 9 will go High when pressed RF remote button-B // Variables will change: int RelayState1 = HIGH; // the current state of the output pin-12 int buttonState1; // the current reading from the input pin-2 int lastButtonState1 = LOW; // the previous reading from the input pin-2 int RelayState2 = HIGH; // the current state of the output pin-11 int buttonState2; // the current reading from the input pin-3 int lastButtonState2 = LOW; // the previous reading from the input pin-3 int RelayState3 = HIGH; // the current state of the output pin-10 int buttonState3; // the current reading from the input pin-4 int lastButtonState3 = LOW; // the previous reading from the input pin-4 int RelayState4 = HIGH; // the current state of the output pin-9 int buttonState4; // the previous reading from the input pin-9 int lastButtonState4 = LOW; // the previous reading from the input pin-5 // the following variables are long's because the time, measured in miliseconds, // will quickly become a bigger number than can be stored in an int. long lastDebounceTime = 0; // the last time the output pin was toggled long debounceDelay = 50; // the debounce time; increase if the output flickers long lastDebounceTime2 = 0; // the last time the output pin was toggled long debounceDelay2 = 50; // the debounce time; increase if the output flickers long lastDebounceTime3 = 0; long debounceDelay3 = 50; long lastDebounceTime4 = 0; long debounceDelay4 = 50; void setup() { pinMode(buttonPin1, INPUT); pinMode(Relay_1, OUTPUT); pinMode(buttonPin2, INPUT); pinMode(Relay_2, OUTPUT); pinMode(buttonPin3, INPUT); pinMode(Relay_3, OUTPUT); pinMode(buttonPin4, INPUT); pinMode(Relay_4, OUTPUT); // set initial Relay state digitalWrite(Relay_1, RelayState1); digitalWrite(Relay_2, RelayState2); digitalWrite(Relay_3, RelayState3); digitalWrite(Relay_4, RelayState4); } void loop() { // read the state of the switch into a local variable: int reading1 = digitalRead(buttonPin1); int reading2 = digitalRead(buttonPin2); int reading3 = digitalRead(buttonPin3); int reading4 = digitalRead(buttonPin4); // check to see if you just pressed the button // (i.e. the input went from LOW to HIGH), and you've waited // long enough since the last press to ignore any noise: // If the switch changed, due to noise or pressing: if (reading1 != lastButtonState1) { // reset the debouncing timer lastDebounceTime = millis(); } if (reading2 != lastButtonState2) { // reset the debouncing timer lastDebounceTime2 = millis(); } if (reading3 != lastButtonState3) { // reset the debouncing timer lastDebounceTime3 = millis(); } if (reading4 != lastButtonState4) { // reset the debouncing timer lastDebounceTime4 = millis(); } if ((millis() - lastDebounceTime) > debounceDelay) { if ((millis() - lastDebounceTime2) > debounceDelay2) { if ((millis() - lastDebounceTime3) > debounceDelay3) { if ((millis() - lastDebounceTime4) > debounceDelay4) { // whatever the reading is at, it's been there for longer // than the debounce delay, so take it as the actual current state: // if the button state has changed: if (reading1 != buttonState1) { buttonState1 = reading1; // only toggle the Relay if the new button state is HIGH if (buttonState1 == HIGH) { RelayState1 = !RelayState1; } } } if (reading2 != buttonState2) { buttonState2 = reading2; // only toggle the Relay if the new button state is HIGH if (buttonState2 == HIGH) { RelayState2 = !RelayState2; } } } if (reading3 != buttonState3) { buttonState3 = reading3; // only toggle the Relay if the new button state is HIGH if (buttonState3 == HIGH) { RelayState3 = !RelayState3; } } } if (reading4 != buttonState4) { buttonState4 = reading4; // only toggle the Relay if the new button state is HIGH if (buttonState4 == HIGH) { RelayState4 = !RelayState4; } } } // set the Relay Status: digitalWrite(Relay_1, RelayState1); digitalWrite(Relay_2, RelayState2); digitalWrite(Relay_3, RelayState3); digitalWrite(Relay_4, RelayState4); // save the reading. Next time through the loop, // it'll be the lastButtonState: lastButtonState1 = reading1; lastButtonState2 = reading2; lastButtonState3 = reading3; lastButtonState4 = reading4; }
[ "noreply@github.com" ]
noreply@github.com
15996f9b8e55308ead7fa317c9f73f172ea11c6a
b589f62c453512d05c6272ca74e6fcb494f1a2ea
/FGJ17/src/aabb.h
388eb98870ed096a42741ae5e0e8a9bdcc12ea3c
[]
no_license
Harha/FGJ17_Attempt
8352a1f9eb4cee8a33bc0fec0268abef0bd403a5
a200a62080da6cc8e086040137d82b9325719a87
refs/heads/master
2021-01-11T16:50:04.273895
2017-01-29T20:45:43
2017-01-29T20:45:43
79,678,637
0
0
null
null
null
null
UTF-8
C++
false
false
858
h
#ifndef AABB_H #define AABB_H #include "vec2.h" class Display; class AABB { public: AABB(vec2 minP = vec2(-1, -1), vec2 maxP = vec2(1, 1)); void render(Display * const display); bool collidesXRight(const AABB & other) const; bool collidesXLeft(const AABB & other) const; bool collidesYUp(const AABB & other) const; bool collidesYDown(const AABB & other) const; bool collidesY(const AABB & other) const; bool collidesX(const AABB & other) const; bool collides(const AABB & other) const; void setMinP(const vec2 & minP); void setMaxP(const vec2 & maxP); AABB operator+(const vec2 & other) const; AABB operator-(const vec2 & other) const; AABB operator*(const float f) const; AABB operator/(const float f) const; vec2 getCenterP() const; vec2 getMinP() const; vec2 getMaxP() const; private: vec2 m_minP; vec2 m_maxP; }; #endif // AABB_H
[ "toni.s.h@netikka.fi" ]
toni.s.h@netikka.fi
30bfd068b369265c612229068bfdc9f167aee856
ea09b82be1f86700ea7367a2d23dfbea8afbefc9
/hoist/statusor.cc
3313f46da22fc810064f398380666e3147612db6
[]
no_license
explodes/mono
6a1baa6abda8ef3abcd2df987f9540d05f3da2af
281e3fd7bd07002a9fb17717f640108cd3c8270f
refs/heads/master
2020-03-15T18:47:39.105928
2019-01-26T13:01:48
2019-01-26T13:01:48
132,292,618
1
0
null
null
null
null
UTF-8
C++
false
false
289
cc
#include "hoist/statusor.h" #include <stdlib.h> #include <iostream> namespace Hoist { namespace internal { void StatusOrHelper::Crash(const Status& status) { ::std::cerr << "Status not OK: " << status.ToString(); exit(EXIT_FAILURE); } } // namespace internal } // namespace Hoist
[ "evan.explodes@gmail.com" ]
evan.explodes@gmail.com
5219fd0808f820ecd84060ba9932d115eca23c85
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/device/bluetooth/bluez/bluetooth_service_attribute_value_bluez.cc
ee6cbf611248c0dea5bb3a1306c14bdc4b70f1c2
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
1,677
cc
// 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. #include "device/bluetooth/bluez/bluetooth_service_attribute_value_bluez.h" #include <utility> #include "base/logging.h" #include "base/memory/ptr_util.h" namespace bluez { BluetoothServiceAttributeValueBlueZ::BluetoothServiceAttributeValueBlueZ() : type_(NULLTYPE), size_(0), value_(base::Value::CreateNullValue()) {} BluetoothServiceAttributeValueBlueZ::BluetoothServiceAttributeValueBlueZ( Type type, size_t size, std::unique_ptr<base::Value> value) : type_(type), size_(size), value_(std::move(value)) { CHECK_NE(type, SEQUENCE); } BluetoothServiceAttributeValueBlueZ::BluetoothServiceAttributeValueBlueZ( std::unique_ptr<Sequence> sequence) : type_(SEQUENCE), size_(sequence->size()), sequence_(std::move(sequence)) {} BluetoothServiceAttributeValueBlueZ::BluetoothServiceAttributeValueBlueZ( const BluetoothServiceAttributeValueBlueZ& attribute) { *this = attribute; } BluetoothServiceAttributeValueBlueZ& BluetoothServiceAttributeValueBlueZ:: operator=(const BluetoothServiceAttributeValueBlueZ& attribute) { if (this != &attribute) { type_ = attribute.type_; size_ = attribute.size_; if (attribute.type_ == SEQUENCE) { value_ = nullptr; sequence_ = base::MakeUnique<Sequence>(*attribute.sequence_); } else { value_ = attribute.value_->CreateDeepCopy(); sequence_ = nullptr; } } return *this; } BluetoothServiceAttributeValueBlueZ::~BluetoothServiceAttributeValueBlueZ() {} } // namespace bluez
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
ed5ca2c217a37381d0161ea874678ccb09d40740
0183f7e35056f4839907050976dc8bdf972d1c4e
/ConsoleApplication12/ConsoleApplication12.cpp
adcb280984cabccbe7c8cda235de9efc0d8d1277
[]
no_license
starosta-coder/lab4c-
77c316aa07864453d3c7767d06706c6e5b2ecf3c
dfa2a7bf1d2c7901d7811195957250bf3058cb80
refs/heads/master
2022-04-20T18:24:11.947116
2020-04-22T16:50:26
2020-04-22T16:50:26
257,962,377
0
0
null
null
null
null
UTF-8
C++
false
false
2,189
cpp
#include <iostream> #include <string> #include <Windows.h> #include <Windows.h> #include <conio.h> #include <string.h> using namespace std; void BaseTask() { cout << "Базовый уровень" << endl; cout << "Удалить первое слово заданной строки Разделителем слов считается пробел." << endl; char str[80] = "faE,1*fe A.,.3iBVf Oq. e.of 43G.FW2,jiq,e[ qe"; char token[80]; char* p = str; char* t = token; cout << str << endl; int index = 0; while (*p) { if (*p == ' ') { index = p - str; break; } ++p; } while (*p) { if (*p != index) { *t = *p; ++t; } ++p; } *t = 0; cout << token << endl; } void MediumTask() { cout << "Средний уровень:" << endl; cout << "В заданной строке поменять местами рядом стоящие символы между собой." << endl; string str; cout << "Введите строку:" << endl; getline(cin, str); for (int i = 0; i < str.size() - 1; i += 2) { swap(str[i], str[i + 1]); } cout << "Нужная строка:" << "\n"; cout << str << "\n"; cin.get(); } void HardTask() { cout << "Высокий уровень:" << endl; cout << "Заданы две строки. Построить новую строку, состоящую из символов, которые входят в первую строку, но не входят во вторую." << endl; SetConsoleCP(1251); SetConsoleOutputCP(1251); char string1[] = { "fjanafhnadfgafha" }; char string2[] = { "dfghsghfgjutyrjfbnx" }; char string3[20] = {}; for (int j = 0; j < 20; j++) { for (int i = 0; i < sizeof(string1); i++) { char temp; for (int k = 0; k < sizeof(string2); k++) { if (string1[i] != string2[k]) { temp = string1[i]; } else { temp = NULL; break; } } string3[j] = temp; if (string3[j] != NULL) { j++; } } } cout << string3; cout << endl; _getch(); } int main() { setlocale(LC_ALL, "Rus"); BaseTask(); MediumTask(); HardTask(); }
[ "noreply@github.com" ]
noreply@github.com
cf761ef3c9d5d559c4ea44ba18363429574c1010
967482ce7998d8814a13d8509db947b0df31f8e0
/src/mod/sec/shl/Kdf.cpp
8fc6244e0d539628d0e1b91472fc6e7e5428a35c
[]
no_license
loongarch64/afnix
38dc9c9808f18ff5517f7c43f641057a9583aeda
88cc629cc09086cda707e5ad6d8a1bd412491bbe
refs/heads/main
2023-05-31T17:16:56.743466
2021-06-22T05:18:32
2021-06-22T05:18:32
379,150,535
0
0
null
2021-06-25T03:05:27
2021-06-22T05:20:29
C++
UTF-8
C++
false
false
6,890
cpp
// --------------------------------------------------------------------------- // - Kdf.cpp - // - afnix:sec module - base key derivation function class implementation - // --------------------------------------------------------------------------- // - This program is free software; you can redistribute it and/or modify - // - it provided that this copyright notice is kept intact. - // - - // - This program is distributed in the hope that it will be useful, but - // - without any warranty; without even the implied warranty of - // - merchantability or fitness for a particular purpose. In no event shall - // - the copyright holder be liable for any direct, indirect, incidental or - // - special damages arising in any way out of the use of this software. - // --------------------------------------------------------------------------- // - copyright (c) 1999-2021 amaury darsch - // --------------------------------------------------------------------------- #include "Kdf.hpp" #include "Byte.hpp" #include "Ascii.hpp" #include "Vector.hpp" #include "Unicode.hpp" #include "Integer.hpp" #include "Evaluable.hpp" #include "QuarkZone.hpp" #include "Exception.hpp" namespace afnix { // ------------------------------------------------------------------------- // - class section - // ------------------------------------------------------------------------- // create a kdf object by size Kdf::Kdf (const String& name, const long kbsz) { if (kbsz <= 0) { throw Exception ("size-error", "invalid kdf buffer size"); } d_name = name; d_kbsz = kbsz; p_kbuf = new t_byte[d_kbsz]; reset (); } // destroy this kdf object Kdf::~Kdf (void) { delete [] p_kbuf; } // return the class name String Kdf::repr (void) const { return "Kdf"; } // return the kdf name String Kdf::getname (void) const { rdlock (); try { String result = d_name; unlock (); return result; } catch (...) { unlock (); throw; } } // reset this kdf object void Kdf::reset (void) { wrlock (); try { for (long i = 0; i < d_kbsz; i++) p_kbuf[i] = nilc; unlock (); } catch (...) { unlock (); throw; } } // get the key buffer size long Kdf::getkbsz (void) const { rdlock (); try { long result = d_kbsz; unlock (); return result; } catch (...) { unlock (); throw; } } // get the key buffer byte by index t_byte Kdf::getbyte (const long index) const { rdlock (); try { if (index >= d_kbsz) { throw Exception ("index-error", "key buffer index is out of bound"); } t_byte result = p_kbuf[index]; unlock (); return result; } catch (...) { unlock (); throw; } } // get the key as a buffer Buffer Kdf::getkbuf (void) const { rdlock (); try { Buffer result; result.add (reinterpret_cast<char*>(p_kbuf), d_kbsz); unlock (); return result; } catch (...) { unlock (); throw; } } // format the key buffer as a string String Kdf::format (void) const { rdlock (); try { String result = Ascii::btos (p_kbuf, d_kbsz); unlock (); return result; } catch (...) { unlock (); throw; } } // compute a key from a message String Kdf::compute (const String& msg) { char* cbuf = Unicode::encode (Encoding::EMOD_UTF8, msg); long size = Ascii::strlen (cbuf); // derive the key wrlock (); try { // process the octet string derive ((t_byte*) cbuf, size); // format result String result = format (); // clean old buffer delete [] cbuf; // unlock and return unlock (); return result; } catch (...) { delete [] cbuf; unlock (); throw; } } // compute a key from a string String Kdf::derive (const String& s) { // extract the octed string long size = 0; t_byte* sbuf = Unicode::stob (size, s); // derive the key wrlock (); try { // process the octet string derive (sbuf, size); // format result String result = format (); // clean old buffer delete [] sbuf; // unlock and return unlock (); return result; } catch (...) { delete [] sbuf; unlock (); throw; } } // ------------------------------------------------------------------------- // - object section - // ------------------------------------------------------------------------- // the quark zone static const long QUARK_ZONE_LENGTH = 7; static QuarkZone zone (QUARK_ZONE_LENGTH); // the hasher supported quarks static const long QUARK_RESET = zone.intern ("reset"); static const long QUARK_FORMAT = zone.intern ("format"); static const long QUARK_DERIVE = zone.intern ("derive"); static const long QUARK_COMPUTE = zone.intern ("compute"); static const long QUARK_GETKBSZ = zone.intern ("get-size"); static const long QUARK_GETBYTE = zone.intern ("get-byte"); static const long QUARK_GETKBUF = zone.intern ("get-key-buffer"); // return true if the given quark is defined bool Kdf::isquark (const long quark, const bool hflg) const { rdlock (); if (zone.exists (quark) == true) { unlock (); return true; } bool result = hflg ? Nameable::isquark (quark, hflg) : false; unlock (); return result; } // apply this object with a set of arguments and a quark Object* Kdf::apply (Evaluable* zobj, Nameset* nset, const long quark, Vector* argv) { // get the number of arguments long argc = (argv == nullptr) ? 0 : argv->length (); // check for 0 argument if (argc == 0) { if (quark == QUARK_FORMAT) return new String (format ()); if (quark == QUARK_GETKBSZ) return new Integer (getkbsz ()); if (quark == QUARK_GETKBUF) return new Buffer (getkbuf ()); if (quark == QUARK_RESET) { reset (); return nullptr; } } // check for 1 argument if (argc == 1) { if (quark == QUARK_DERIVE) { String s = argv->getstring (0); return new String (derive (s)); } if (quark == QUARK_COMPUTE) { String msg = argv->getstring (0); return new String (compute (msg)); } if (quark == QUARK_GETBYTE) { long index = argv->getlong (0); return new Byte (getbyte (index)); } } // call the nameable method return Nameable::apply (zobj, nset, quark, argv); } }
[ "wuxiaotian@loongson.cn" ]
wuxiaotian@loongson.cn
9318a1c75d40052dc6c7cfa0f1cd3ac9bec88a8e
5dc4ea36514927efd678638e2095a4e8e32c0386
/NPSVisor/tools/svMaker/source/pProperty/svmPropertyBtn.h
c7192069d5a72d6eb4a02c6c8b82e2ac1e86122f
[ "Unlicense" ]
permissive
NPaolini/NPS_OpenSource
732173afe958f9549af13bc39b15de79e5d6470c
0c7da066b02b57ce282a1903a3901a563d04a28f
refs/heads/main
2023-03-15T09:34:19.674662
2021-03-13T13:22:00
2021-03-13T13:22:00
342,852,203
0
0
null
null
null
null
IBM852
C++
false
false
4,454
h
//-------------------- svmPropertyBtn.h -------------------- //----------------------------------------------------------- #ifndef SVMPROPERTYBTN_H_ #define SVMPROPERTYBTN_H_ //----------------------------------------------------------- #include "precHeader.h" //----------------------------------------------------------- #include "svmDefObj.h" #include "svmObjButton.h" #include "POwnBtn.h" //----------------------------------------------------------- struct fullPrph { UINT prph; UINT addr; UINT typeVal; // UINT nDec; UINT nBits; UINT offset; int normaliz; fullPrph() : prph(0), addr(0), typeVal(0), /*nDec(0),*/ nBits(0), offset(0), normaliz(0) {} }; //----------------------------------------------------------- void saveFullPrph(P_File& pf, LPTSTR buff, int id, const fullPrph& data); void loadFullPrph(uint id, setOfString& set, fullPrph& data); //----------------------------------------------------------- class PropertyBtn : public Property { private: typedef Property baseClass; public: PropertyBtn(); virtual ~PropertyBtn(); const PropertyBtn& operator=(const PropertyBtn& other) { clone(other); return *this; } const Property& operator=(const Property& other) { clone(other); return *this; } // copia solo un set minimo di proprietÓ, usata durante la creazione di // nuovi oggetti void cloneMinusProperty(const Property& other); const PVect<LPCTSTR>& getNames() const { return nameBmp; } PVect<LPCTSTR>& getNames() { return nameBmp; } void fillNameBmp(); COLORREF fgPress; COLORREF bgPress; LPCTSTR functionLink; LPCTSTR normalText; LPCTSTR pressedText; LPCTSTR modelessName; //---- nuovi -------------- PVect<LPCTSTR> allText; // ci vengono messi anche normal e pressed come primi due valori PVect<double> textVal; PVect<COLORREF> otherFg; PVect<COLORREF> otherBg; PVect<double> colorVal; PVect<double> bmpVal; union { struct { DWORD theme : 1; DWORD flat : 1; DWORD fixedBmpDim : 1; // non pi¨ usato, lasciato per compatibilitÓ DWORD pos : 4; // i valori seguenti possono essere: 0 = non usa var, 1 = usa valore, 2 = usa indice, 3 = valore esatto (solo per i colori) DWORD colorByVar : 3; DWORD textByVar : 3; DWORD bitmapByVar : 3; DWORD noBorder : 1; DWORD styleBmpDim : 2; // 0 -> fisso, 1 -> scalato, 2 -> riempie tutto il pulsante (valido solo per testo/bmp centrato) }; DWORD flag; } Flags; // 0-> colore, 1 -> testo, 2 -> bmp fullPrph DataPrf[3]; //------------------------- protected: virtual void clone(const Property& other); private: PropertyBtn(const PropertyBtn& other); PVect<LPCTSTR> nameBmp; }; //----------------------------------------------------------- //----------------------------------------------------------- enum btnStyleShow { btnS_OnlyBmp, btnS_BmpAndText, btnS_StdAndBmp, btnS_NewStdAndBmp, }; //----------------------------------------------------------- enum btnStyleAction { btnAction, btnOnOff, btnFirstGroup, btnNextGroup, btnPressing, btnHide, btnModeless, btnOpenPageByBit, }; //----------------------------------------------------------- class svmDialogBtn : public svmBaseDialogProperty { private: typedef svmBaseDialogProperty baseClass; public: svmDialogBtn(svmObject* owner, Property* prop, PWin* parent, uint id = IDD_BTN_PROPERTY, HINSTANCE hInst = 0); ~svmDialogBtn() { destroy(); delete Bmp; } virtual bool create(); protected: virtual LRESULT windowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); virtual void CmOk(); void fillType(); void chooseBmp(); bool checkZeroAction(); void checkEditLink(); bool checkNormalAction(); bool checkhide(); void checkEnabled(bool all); void enableModeless(int enable); void findModelessName(); virtual bool useFont() const { return true; } void personalize(); void allocBmp(); // void checkHeight(); PBitmap* Bmp; bool onLink; struct colorBtn { POwnBtn* Btn; COLORREF color; colorBtn() : Btn(0), color(0) {} }; colorBtn ColorBtn[4]; void chooseColor(int ix); void invalidateColor(int ix); void chooseAction(); int lastAction; }; //----------------------------------------------------------- #endif
[ "npaolini@ennepisoft.it" ]
npaolini@ennepisoft.it
2d63c24c971af15f863a74c0d61a141f954669db
afb89ba829fd0c7f705c1a85d382cd41e1e15f83
/src/memory/unique_ptr.tcc
5d693ed8aa9cf97c4fff8479a5697d15a79e0a09
[ "MIT" ]
permissive
minijackson/IGI-3004
9e64e24dba4cfb6592752e776149cecc14e2ade6
8354f40e296cce8735b188dd3ff7406e96d5878e
refs/heads/master
2021-01-10T06:42:49.664696
2018-03-30T09:21:56
2018-03-30T09:21:56
45,906,304
1
0
null
null
null
null
UTF-8
C++
false
false
1,336
tcc
#pragma once #include "unique_ptr.hpp" #include <utility> template <typename T, typename Deleter> UniquePtr<T, Deleter>::UniquePtr(T* pointer) : pointer(pointer) {} template <typename T, typename Deleter> template <typename D> UniquePtr<T, Deleter>::UniquePtr(T* pointer, D&& deleter) : pointer(pointer) , deleter(std::forward<Deleter>(deleter)) {} template <typename T, typename Deleter> UniquePtr<T, Deleter>::UniquePtr(UniquePtr&& other) noexcept : pointer(std::move(other.pointer)), deleter(std::move(deleter)) { other.release(); } template <typename T, typename Deleter> UniquePtr<T, Deleter>& UniquePtr<T, Deleter>::operator=(UniquePtr<T, Deleter>&& other) noexcept { if(&other != this) { this->pointer = std::move(other.pointer); this->deleter = std::move(other.deleter); other.release(); } } template <typename T, typename Deleter> UniquePtr<T, Deleter>::~UniquePtr() { if(pointer != nullptr) { deleter(pointer); } } template <typename T, typename Deleter> T* UniquePtr<T, Deleter>::get() { return pointer; } template <typename T, typename Deleter> T* UniquePtr<T, Deleter>::release() { T* pointer = this->pointer; this->pointer = nullptr; return pointer; } template <typename T, typename Deleter> Deleter UniquePtr<T, Deleter>::getDeleter() const { return deleter; }
[ "minijackson@riseup.net" ]
minijackson@riseup.net
4c249517e45e8e28abaecace9f31b06ae6f0eba6
9cfb1c6a5a91bb84a1b9d9423fe1247ee1f905d9
/reverse_n.cpp
f717d8058f2abbbde6dea1122bf7816cae6eb69d
[]
no_license
dawdler/Algorithmic-Coding
2deac7b1391e93aca8e69e8e9c17e572248cfcee
5946b2039686aea49c797481de466cecf5a34875
refs/heads/master
2021-01-19T11:35:05.225326
2014-03-04T20:27:55
2014-03-04T20:27:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
244
cpp
#include<stdio.h> #include<iostream> #include<algorithm> using namespace std; string S[1025*1025];int main(){int test;cin>>test;cin>>S; string *beg=&S[0];string *last=&S[4]; while(test--) { reverse(beg,last); cout<<S;cout<<" "; } return 0; }
[ "atit.anand.cs@gmail.com" ]
atit.anand.cs@gmail.com
2772a47613aa400557029a57dd00f57edcf91aee
815a4a067c63c1aa00399e3aa14cf585a6199dec
/core/proteinstructure/md.cc
b5617567ac7d3be7a8d6f27ae57d0077b41d3102
[ "Apache-2.0" ]
permissive
tecdatalab/legacy
39ff4f4329d0dba043fef79f363a8c1fd504b5a9
9b5286d3375fff691a80ceb44172549e9a6bdee5
refs/heads/master
2020-04-18T06:00:16.559666
2019-01-24T17:27:54
2019-01-24T17:27:54
167,301,809
0
0
Apache-2.0
2019-10-18T15:27:24
2019-01-24T04:15:59
C
UTF-8
C++
false
false
3,351
cc
#include "md.h" using namespace std; #include <iostream> /* * Since we should have generated one file per chain, we assume that there are * several files named following the <complex_name>-<chain_id>.pdb pattern * This function calls the read_protein function in pdb.cc using each * of the filenames that should exist. * use_hydrogens indicates if we should load the .pdb.h files that have hydrogens added to them * It returns a vector of all the pdb instances loaded. */ vector<pdb> load_pdbs(string main_complex_name, vector<string> chain_ids, string directory, bool use_hydrogens, bool calpha_only) { // create a pdb container for each chain vector<pdb> all_proteins(chain_ids.size(), pdb()); for(size_t chain = 0; chain < chain_ids.size(); chain++) { string extension = use_hydrogens ? PDB_WITH_HYDROGEN_EXTENSION : PDB_EXTENSION; string chain_filename = directory + chain_ids[chain] + CHAIN_FILE_SEPARATOR + main_complex_name + extension; read_protein(chain_filename.c_str(), all_proteins[chain], calpha_only); } return all_proteins; } /* * Assuming that there are several <chain_id>-<chain_id>.out files, that * contain ZDock predictions, this function loads the information into zdata * instances, using read_zdock_data function in zdock.cc * The order in which chain ids are supplied is important, because it assumes * a specific sequence in which predictions have been generated. For instance, * if we have chains A, B, C and D, then we would expect files for A-B, A-C, * A-D, B-C, B-D and C-D. * It is necessary to specify if the decoys where generated with ZDOCK or LZerD */ vector< vector<transformations*> > load_predictions(vector<string> chain_ids, string directory, decoy_program_t decoy_program) { // initialize a matrix of predictions, setting the values to NULL // since we are not having predictions for all combinations // we will invoke the "invert" method to create opposite transformations // with respect to the ones that we did calculate using the decoy programs vector< vector<transformations*> > all_predictions(chain_ids.size(), vector<transformations*>(chain_ids.size(), NULL)); for(size_t receptor_index = 0; receptor_index < chain_ids.size(); receptor_index ++) { // for the current receptor, go from receptor_index + 1 up to N for(size_t ligand_index = receptor_index + 1; ligand_index < chain_ids.size(); ligand_index++) { string prediction_filename = directory + chain_ids[receptor_index] + CHAIN_FILE_SEPARATOR + chain_ids[ligand_index] + PREDICTION_EXTENSION; /* this will hold the ligand/receptor transformation, obtained by invoking the invert method */ transformations* inverted; if(decoy_program == decoy_program_zdock) // then create zdock_transformations instances { all_predictions[receptor_index][ligand_index] = new zdock_transformations(prediction_filename); inverted = new zdock_transformations(prediction_filename); } else // lzerd_transformations instance { all_predictions[receptor_index][ligand_index] = new lzerd_transformations(prediction_filename); inverted = new lzerd_transformations(prediction_filename); } /* apply the inversion and store it */ inverted->invert(); all_predictions[ligand_index][receptor_index] = inverted; } } return all_predictions; }
[ "noreply@github.com" ]
noreply@github.com