hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
c2ee0f2a77e78dfb631f1695270fa8781d8cc0c2
1,903
cpp
C++
MerdogRT/interpreter/source/word_record.cpp
HttoHu/MerdogUWP
4d823f1c95b655151f8d972018d6caed33e187ee
[ "MIT" ]
9
2018-03-05T15:07:44.000Z
2019-12-07T10:15:00.000Z
MerdogRT/interpreter/source/word_record.cpp
HttoHu/MerdogUWP
4d823f1c95b655151f8d972018d6caed33e187ee
[ "MIT" ]
null
null
null
MerdogRT/interpreter/source/word_record.cpp
HttoHu/MerdogUWP
4d823f1c95b655151f8d972018d6caed33e187ee
[ "MIT" ]
1
2019-11-14T08:09:19.000Z
2019-11-14T08:09:19.000Z
/* * MIT License * Copyright (c) 2019 Htto Hu */ #include "../include/word_record.hpp" #include "../include/function.hpp" using namespace Mer; std::map<type_code_index, std::map<std::string, type_code_index>> type_op_type_map; void Mer::SymbolTable::end_block() { for (auto& a : data.front()) _rem_vec.push_back(a.second); data.pop_front(); } WordRecorder* Mer::SymbolTable::find(std::string id) { for (size_t i = 0; i < data.size(); i++) { auto result = data[i].find(id); if (result != data[i].end()) { return result->second; } } return nullptr; } void Mer::SymbolTable::push_glo(std::string id, WordRecorder* wr) { if (data.back().find(id) != data.back().end()) throw Error("id " + id + " redefined!"); data.back().insert({ id,wr }); } void Mer::SymbolTable::push(std::string id, WordRecorder* wr) { if (data.front().find(id) != data.front().end()) throw Error("id " + id + " redefined!"); data.front().insert({ id,wr }); } void Mer::SymbolTable::print() { for (const auto& a : data) { for (const auto& b : a) { std::cout << "ID:" << b.first << " TYPE:" << b.second->get_type() << std::endl;; } std::cout << "=================================\n"; } std::cout << "#########################################\n\n\n"; } Mer::SymbolTable::~SymbolTable() { for (auto a : _rem_vec) { delete a; } for (auto& a : data) { for (auto& b : a) { delete b.second; } } } FunctionBase* Mer::FuncIdRecorder::find(const std::vector<type_code_index>& pf) { if (dnt_check) return functions[std::vector<type_code_index>()]; if (functions.find(pf) == functions.end()) return nullptr; return functions[pf]; } Mer::FuncIdRecorder::FuncIdRecorder(FunctionBase* fb) :WordRecorder(ESymbol::SFUN, fb->get_type()), functions(compare_param_feature) {} Mer::FuncIdRecorder::~FuncIdRecorder() { for (auto& a : functions) { rem_functions.insert(a.second); } }
22.127907
135
0.612191
HttoHu
c2ee2b77b990aafd5569debc5c90fa54dfd2eff2
6,569
cc
C++
cpp/shared/cpputils/cpputils/list.cc
SiliconLabs/mltk
56b19518187e9d1c8a0d275de137fc9058984a1f
[ "Zlib" ]
null
null
null
cpp/shared/cpputils/cpputils/list.cc
SiliconLabs/mltk
56b19518187e9d1c8a0d275de137fc9058984a1f
[ "Zlib" ]
1
2021-11-19T20:10:09.000Z
2021-11-19T20:10:09.000Z
cpp/shared/cpputils/cpputils/list.cc
sldriedler/mltk
d82a60359cf875f542a2257f1bc7d8eb4bdaa204
[ "Zlib" ]
null
null
null
#include <cassert> #include <cstring> #include <cstdlib> #include "cpputils/list.hpp" namespace cpputils { /*************************************************************************************************/ List::List(uint32_t entry_size, uint32_t initial_capacity) { initialize(entry_size, initial_capacity); } /*************************************************************************************************/ List::List(uint32_t entry_size, uint32_t max_capacity, void* buffer) { initialize(entry_size, max_capacity, buffer); } /*************************************************************************************************/ List::~List() { clear(); } /*************************************************************************************************/ void List::initialize(uint32_t entry_size, uint32_t initial_capacity) { is_mutable_ = true; owns_buffer_ = true; head_ = nullptr; has_malloc_error_ = false; entry_size_ = entry_size; count_ = 0; initial_capacity_ = capacity_ = initial_capacity; } /*************************************************************************************************/ void List::initialize(uint32_t entry_size, uint32_t max_capacity, void* buffer) { is_mutable_ = false; owns_buffer_ = false; has_malloc_error_ = false; head_ = static_cast<uint8_t*>(buffer); entry_size_ = entry_size; count_ = 0; initial_capacity_ = capacity_ = max_capacity; } /*************************************************************************************************/ bool List::clone(List &other) { uint8_t* buffer = nullptr; if(count_ > 0) { buffer = static_cast<uint8_t*>(malloc(count_ * entry_size_)); if(buffer == nullptr) { return false; } memcpy(buffer, head_, count_ * entry_size_); } other.is_mutable_ = is_mutable_; other.owns_buffer_ = true; other.has_malloc_error_ = false; other.head_ = buffer; other.entry_size_ = entry_size_; other.count_ = count_; other.initial_capacity_ = initial_capacity_; other.capacity_ = capacity_; return true; } /*************************************************************************************************/ bool List::append(const void* val, bool unique) { bool retval = true; if(val == nullptr) { assert(!"null ptr"); return false; } if(unique && contains(val)) { goto exit; } if(head_ == nullptr) { retval = increase_size(capacity_); if(!retval) { goto exit; } } else if((uint32_t)count_ == capacity_) { retval = increase_size(capacity_*2); if(!retval) { goto exit; } } memcpy(&head_[count_*entry_size_], val, entry_size_); count_++; exit: return retval; } /*************************************************************************************************/ bool List::prepend(const void* val, bool unique) { bool retval = true; if(val == nullptr) { assert(!"null ptr"); return false; } if(unique && contains(val)) { goto exit; } if(head_ == nullptr) { retval = increase_size(capacity_); if(!retval) { goto exit; } } else if((uint32_t)count_ == capacity_) { retval = increase_size(capacity_*2); if(!retval) { goto exit; } } memmove(&head_[1*entry_size_], &head_[0*entry_size_], count_*entry_size_); memcpy(&head_[0*entry_size_], val, entry_size_); count_++; exit: return retval; } /*************************************************************************************************/ bool List::remove(const void* val) { bool retval = false; if(val == nullptr) { return false; } for(int i = 0; i < count_; ++i) { void *other_val = get(i); if(memcmp(val, other_val, entry_size_) == 0) { retval = true; memmove(&head_[i * entry_size_], &head_[((i + 1) * entry_size_)], (count_ - i - 1) * entry_size_); count_--; break; } } return retval; } /*************************************************************************************************/ bool List::remove(int i) { if(i < 0 || i >= count_) { return false; } memmove(&head_[i * entry_size_], &head_[((i + 1) * entry_size_)], (count_ - i - 1) * entry_size_); count_--; return true; } /*************************************************************************************************/ bool List::contains(const void *val) const { bool retval = false; if(val == nullptr) { return false; } for(int i = 0; i < count_; ++i) { void *other_val = get(i); if(memcmp(val, other_val, entry_size_) == 0) { retval = true; break; } } return retval; } /*************************************************************************************************/ void* List::get(int i) const { if(i < 0 || i >= count_) { assert(!"List index overflow"); return nullptr; } return static_cast<void*>(&head_[i * entry_size_]); } /*************************************************************************************************/ bool List::increase_size(uint32_t new_size) { uint8_t *old_list = head_; if(!is_mutable_) { assert(!"Buffer overflow"); return false; } // If we're trying to malloc more than 1k, then just start incrementing rather than doubling if(new_size * entry_size_ > 1024) { new_size = capacity_ + (256 + entry_size_ - 1) / entry_size_; } uint8_t* new_head = static_cast<uint8_t*>(malloc(new_size * entry_size_)); if(new_head == nullptr) { has_malloc_error_ = true; return false; } head_ = new_head; if(old_list != nullptr) { memcpy(head_, old_list, capacity_ * entry_size_); free(old_list); } capacity_ = new_size; return true; } /*************************************************************************************************/ void List::clear(void) { if(owns_buffer_ && head_ != nullptr) { free(head_); head_ = nullptr; } count_ = 0; capacity_ = initial_capacity_; has_malloc_error_ = false; } } // namespace cpputils
21.896667
110
0.444969
SiliconLabs
c2f216b53cbfc352125ed7c8d871df234488669a
376
cpp
C++
samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlAttributeAttribute.Namespace Example/CPP/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlAttributeAttribute.Namespace Example/CPP/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlAttributeAttribute.Namespace Example/CPP/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
#using <System.Xml.dll> using namespace System; using namespace System::IO; using namespace System::Xml; using namespace System::Xml::Serialization; // <Snippet1> public ref class Car { public: [XmlAttributeAttribute(Namespace="Make")] String^ MakerName; [XmlAttributeAttribute(Namespace="Model")] String^ ModelName; }; // </Snippet1>
16.347826
46
0.680851
hamarb123
c2f55f242d2637454e327d5051b35ba012f03756
469
cpp
C++
gie/src/Node.cpp
Kerdek/gie
ebcd1aec6dc34de46145e4013afd6d5dad194a9f
[ "BSD-3-Clause-Clear" ]
57
2019-06-21T21:15:03.000Z
2022-03-30T18:17:56.000Z
gie/src/Node.cpp
Kerdek/gie
ebcd1aec6dc34de46145e4013afd6d5dad194a9f
[ "BSD-3-Clause-Clear" ]
2
2020-08-04T05:45:03.000Z
2021-02-26T10:21:16.000Z
gie/src/Node.cpp
Kerdek/gie
ebcd1aec6dc34de46145e4013afd6d5dad194a9f
[ "BSD-3-Clause-Clear" ]
8
2019-11-24T07:57:46.000Z
2021-05-05T07:58:29.000Z
// // Created by alex on 4/27/19. // #include <gie/Node.h> std::optional<Node> makeNode(const PythonContext& context, const std::string& name, Arguments arguments) { auto symbolId = context.getSymbolId(name); if(!symbolId) return std::nullopt; arguments.resize(context.getSymbol(*symbolId)->arguments.size(), NoArgument{}); return Node { {std::move(arguments)}, *symbolId }; }
22.333333
104
0.586354
Kerdek
c2f6288e1724985eb2d9ed4dc4e5350fa3115709
14,977
cpp
C++
Windows/WReformatRectifyDialog.cpp
cas-nctu/multispec
0bc840bdb073b5feaeec650c2da762cfa34ee37d
[ "Apache-2.0" ]
11
2020-03-10T02:06:00.000Z
2022-02-17T19:59:50.000Z
Windows/WReformatRectifyDialog.cpp
cas-nctu/multispec
0bc840bdb073b5feaeec650c2da762cfa34ee37d
[ "Apache-2.0" ]
null
null
null
Windows/WReformatRectifyDialog.cpp
cas-nctu/multispec
0bc840bdb073b5feaeec650c2da762cfa34ee37d
[ "Apache-2.0" ]
5
2020-05-30T00:59:22.000Z
2021-12-06T01:37:05.000Z
// MultiSpec // // Copyright 1988-2020 Purdue Research Foundation // // 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: https://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. // // MultiSpec is curated by the Laboratory for Applications of Remote Sensing at // Purdue University in West Lafayette, IN and licensed by Larry Biehl. // // File: WReformatRectifyDialog.cpp : implementation file // // Authors: Larry L. Biehl // // Revision date: 01/04/2018 // // Language: C++ // // System: Windows Operating System // // Brief description: This file contains functions that relate to the // CMReformatRectifyDlg class. // //------------------------------------------------------------------------------------ #include "SMultiSpec.h" #include "WReformatRectifyDialog.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif BEGIN_MESSAGE_MAP (CMReformatRectifyDlg, CMDialog) //{{AFX_MSG_MAP (CMReformatRectifyDlg) ON_BN_CLICKED (IDC_ReprojectToRadio, OnBnClickedReprojectToRadio) ON_BN_CLICKED (IDC_TranslateScaleRotateRadio, OnBnClickedTranslateScaleRotateRadio) ON_BN_CLICKED (IDC_UseMapOrientationAngle, OnBnClickedUsemaporientationangle) ON_BN_CLICKED (IDEntireImage, ToEntireImage) ON_BN_CLICKED (IDSelectedImage, ToSelectedImage) ON_CBN_SELENDOK (IDC_ReferenceFileList, OnCbnSelendokTargetcombo) ON_CBN_SELENDOK (IDC_ResampleMethod, &CMReformatRectifyDlg::OnCbnSelendokResamplemethod) ON_EN_CHANGE (IDC_RotationClockwise, OnEnChangeRotationclockwise) //}}AFX_MSG_MAP END_MESSAGE_MAP () CMReformatRectifyDlg::CMReformatRectifyDlg ( CWnd* pParent /*=NULL*/) : CMDialog (CMReformatRectifyDlg::IDD, pParent) { //{{AFX_DATA_INIT (CMReformatRectifyDlg) m_backgroundValue = 0; m_lineShift = 0; m_columnShift = 0; m_columnScaleFactor = 0.0; m_lineScaleFactor = 0.0; m_rotationAngle = 0.0; m_blankOutsideSelectedAreaFlag = FALSE; m_headerListSelection = -1; m_channelSelection = -1; m_useMapOrientationAngleFlag = FALSE; m_procedureCode = 0; m_fileNamesSelection = -1; m_resampleSelection = 0; //}}AFX_DATA_INIT m_referenceWindowInfoHandle = NULL; m_initializedFlag = CMDialog::m_initializedFlag; } // end "CMReformatRectifyDlg" void CMReformatRectifyDlg::DoDataExchange ( CDataExchange* pDX) { CDialog::DoDataExchange (pDX); //{{AFX_DATA_MAP (CMReformatRectifyDlg) DDX_Text (pDX, IDC_ColumnEnd, m_ColumnEnd); DDV_MinMaxLong (pDX, m_ColumnEnd, 1, m_maxNumberColumns); DDX_Text (pDX, IDC_ColumnStart, m_ColumnStart); DDV_MinMaxLong (pDX, m_ColumnStart, 1, m_maxNumberColumns); DDX_Text (pDX, IDC_LineEnd, m_LineEnd); DDV_MinMaxLong (pDX, m_LineEnd, 1, m_maxNumberLines); DDX_Text (pDX, IDC_LineStart, m_LineStart); DDV_MinMaxLong (pDX, m_LineStart, 1, m_maxNumberLines); DDX_Text2 (pDX, IDC_BackgroundValue, m_backgroundValue); DDV_MinMaxDouble (pDX, m_backgroundValue, m_minBackgroundValue, m_maxBackgroundValue); DDX_Text (pDX, IDC_LineOffset, m_lineShift); DDV_MinMaxLong (pDX, m_lineShift, -100, 100); DDX_Text (pDX, IDC_ColumnOffset, m_columnShift); DDV_MinMaxLong (pDX, m_columnShift, -100, 100); DDX_Text2 (pDX, IDC_ColumnScale, m_columnScaleFactor); DDX_Text2 (pDX, IDC_LineScale, m_lineScaleFactor); DDX_Text2 (pDX, IDC_RotationClockwise, m_rotationAngle); DDV_MinMaxDouble (pDX, m_rotationAngle, -180., 180.); DDX_Check (pDX, IDC_NonSelectedPixels, m_blankOutsideSelectedAreaFlag); DDX_CBIndex (pDX, IDC_Header, m_headerListSelection); DDX_CBIndex (pDX, IDC_OutChannels, m_channelSelection); DDX_Check (pDX, IDC_UseMapOrientationAngle, m_useMapOrientationAngleFlag); DDX_Radio (pDX, IDC_TranslateScaleRotateRadio, m_procedureCode); DDX_CBIndex (pDX, IDC_ReferenceFileList, m_fileNamesSelection); DDX_CBIndex (pDX, IDC_ResampleMethod, m_resampleSelection); //}}AFX_DATA_MAP // Verify that the line and column values make sense VerifyLineColumnStartEndValues (pDX); if (pDX->m_bSaveAndValidate) { CComboBox* comboBoxPtr; comboBoxPtr = (CComboBox*)GetDlgItem (IDC_Header); m_headerOptionsSelection = (SInt16)(comboBoxPtr->GetItemData (m_headerListSelection)); comboBoxPtr = (CComboBox*)GetDlgItem (IDC_ResampleMethod); m_resampleMethodCode = (SInt16)comboBoxPtr->GetItemData (m_resampleSelection); } // end "if (pDX->m_bSaveAndValidate)" } // end "DoDataExchange" //------------------------------------------------------------------------------------ // Copyright 1988-2020 Purdue Research Foundation // // Function name: void DoDialog // // Software purpose: The purpose of this routine is to present the reformat rectify // image specification dialog box to the user and copy the // revised information back to the reformat rectify specification // structure if the user selected OK. // // Parameters in: None // // Parameters out: None // // Value Returned: None // // Called By: // // Coded By: Larry L. Biehl Date: 04/29/2005 // Revised By: Larry L. Biehl Date: 03/26/2006 Boolean CMReformatRectifyDlg::DoDialog ( FileInfoPtr outFileInfoPtr, FileInfoPtr fileInfoPtr, WindowInfoPtr imageWindowInfoPtr, LayerInfoPtr imageLayerInfoPtr, ReformatOptionsPtr reformatOptionsPtr, double minBackgroundValue, double maxBackgroundValue) { SInt64 returnCode; Boolean continueFlag = FALSE; // Make sure intialization has been completed. if (!m_initializedFlag) return (FALSE); m_outputFileInfoPtr = outFileInfoPtr; m_fileInfoPtr = fileInfoPtr; m_imageWindowInfoPtr = imageWindowInfoPtr; m_imageLayerInfoPtr = imageLayerInfoPtr; m_reformatOptionsPtr = reformatOptionsPtr; m_minBackgroundValue = minBackgroundValue; m_maxBackgroundValue = maxBackgroundValue; // Selected area for output file. m_dialogSelectArea.lineStart = m_LineStart; m_dialogSelectArea.lineEnd = m_LineEnd; m_dialogSelectArea.lineInterval = m_LineInterval; m_dialogSelectArea.columnStart = m_ColumnStart; m_dialogSelectArea.columnEnd = m_ColumnEnd; m_dialogSelectArea.columnInterval = m_ColumnInterval; returnCode = DoModal (); if (returnCode == IDOK) { continueFlag = TRUE; m_dialogSelectArea.lineStart = m_LineStart; m_dialogSelectArea.lineEnd = m_LineEnd; m_dialogSelectArea.lineInterval = 1; m_dialogSelectArea.columnStart = m_ColumnStart; m_dialogSelectArea.columnEnd = m_ColumnEnd; m_dialogSelectArea.columnInterval = 1; RectifyImageDialogOK (this, m_outputFileInfoPtr, m_fileInfoPtr, m_imageWindowInfoPtr, m_imageLayerInfoPtr, &m_dialogSelectArea, m_reformatOptionsPtr, (SInt16)m_headerOptionsSelection, (Boolean)m_blankOutsideSelectedAreaFlag, (SInt16)m_channelSelection, m_backgroundValue, (SInt16)(m_procedureCode+1), (SInt16)m_resampleMethodCode, m_referenceWindowInfoHandle, m_lineShift, m_columnShift, m_lineScaleFactor, m_columnScaleFactor, m_rotationAngle); } // end "if (returnCode == IDOK)" return (continueFlag); } // end "DoDialog" void CMReformatRectifyDlg::OnBnClickedReprojectToRadio () { m_procedureCode = kReprojectToReferenceImage - 1; UpdateProcedureItems (IDC_LineStart, TRUE); } // end "OnBnClickedReprojectToRadio" void CMReformatRectifyDlg::OnBnClickedTranslateScaleRotateRadio () { m_procedureCode = kTranslateScaleRotate - 1; UpdateProcedureItems (IDC_LineOffset, m_blankOutsideSelectedAreaFlag); } // end "OnBnClickedTranslateScaleRotateRadio" void CMReformatRectifyDlg::OnBnClickedUsemaporientationangle () { // Add your control notification handler code here DDX_Check (m_dialogFromPtr, IDC_UseMapOrientationAngle, m_useMapOrientationAngleFlag); m_rotationAngle = 0.; if (m_useMapOrientationAngleFlag) m_rotationAngle = m_mapOrientationAngle; DDX_Text2 (m_dialogToPtr, IDC_RotationClockwise, m_rotationAngle); } // end "OnBnClickedUsemaporientationangle" void CMReformatRectifyDlg::OnCbnSelendokResamplemethod () { SInt16 savedResampleSelection; // Select resampling method popup box if (m_resampleSelection >= 0) { savedResampleSelection = m_resampleSelection; DDX_CBIndex (m_dialogFromPtr, IDC_ResampleMethod, m_resampleSelection); } // end "if (m_resampleSelection >= 0)" } // end "OnCbnSelendokResamplemethod" void CMReformatRectifyDlg::OnCbnSelendokTargetcombo () { SInt16 savedFileNamesSelection; // Reference image to register against popup box if (m_fileNamesSelection >= 0) { savedFileNamesSelection = m_fileNamesSelection; DDX_CBIndex (m_dialogFromPtr, IDC_ReferenceFileList, m_fileNamesSelection); if (savedFileNamesSelection != m_fileNamesSelection) RectifyImageDialogOnReferenceFile (this, m_procedureCode+1, m_fileNamesSelection+1, &m_referenceWindowInfoHandle, &m_dialogSelectArea); } // end "if (m_fileNamesSelection >= 0)" } // end "OnCbnSelendokTargetcombo" void CMReformatRectifyDlg::OnEnChangeRotationclockwise () { // If this is a RICHEDIT control, the control will not // send this notification unless you override the CMDialog::OnInitDialog () // function and call CRichEditCtrl ().SetEventMask () // with the ENM_CHANGE flag ORed into the mask. // Add your control notification handler code here if (m_mapOrientationAngle != 0) { DDX_Text2 (m_dialogFromPtr, IDC_RotationClockwise, m_rotationAngle); if (m_rotationAngle == m_mapOrientationAngle) m_useMapOrientationAngleFlag = TRUE; else // m_rotationAngle != m_mapOrientationAngle m_useMapOrientationAngleFlag = FALSE; DDX_Check (m_dialogToPtr, IDC_UseMapOrientationAngle, m_useMapOrientationAngleFlag); } // end "if (m_mapOrientationAngle != 0)" } // end "OnEnChangeRotationclockwise" BOOL CMReformatRectifyDlg::OnInitDialog () { CComboBox* comboBoxPtr; SInt16 channelSelection, fileNamesSelection, procedureCode, resampleMethodCode; Boolean blankOutsideSelectedAreaFlag, mapInfoExistsFlag; CDialog::OnInitDialog (); // Add extra initialization here // Make sure that we have the bitmaps for the entire image buttons. VERIFY (toEntireButton.AutoLoad (IDEntireImage, this)); VERIFY (toSelectedButton.AutoLoad (IDSelectedImage, this)); RectifyImageDialogInitialize (this, m_fileInfoPtr, &m_dialogSelectArea, m_reformatOptionsPtr, &m_headerOptionsSelection, &channelSelection, &blankOutsideSelectedAreaFlag, &m_backgroundValue, &procedureCode, &resampleMethodCode, &fileNamesSelection, &m_referenceWindowInfoHandle, &m_lineShift, &m_columnShift, &m_lineScaleFactor, &m_columnScaleFactor, &m_rotationAngle, &m_mapOrientationAngle); m_LineStart = m_reformatOptionsPtr->lineStart; m_LineEnd = m_reformatOptionsPtr->lineEnd; m_ColumnStart = m_reformatOptionsPtr->columnStart; m_ColumnEnd = m_reformatOptionsPtr->columnEnd; m_blankOutsideSelectedAreaFlag = blankOutsideSelectedAreaFlag; m_procedureCode = procedureCode - 1; m_resampleMethodCode = resampleMethodCode; // Get the resample method list selection that matches the input // resample method code. m_resampleSelection = GetComboListSelection (IDC_ResampleMethod, m_resampleMethodCode); if (m_resampleSelection == -1) m_resampleSelection = 0; m_fileNamesSelection = fileNamesSelection - 1; // Set text indicating whether the output file format could be // GeoTIFF or TIFF. mapInfoExistsFlag = FindIfMapInformationExists (gImageWindowInfoPtr); comboBoxPtr = (CComboBox*)(GetDlgItem (IDC_Header)); comboBoxPtr->DeleteString (kTIFFGeoTIFFMenuItem); if (mapInfoExistsFlag) comboBoxPtr->InsertString (kTIFFGeoTIFFMenuItem, (LPCTSTR)_T("GeoTIFF format")); else // !mapInfoExistsFlag comboBoxPtr->InsertString (kTIFFGeoTIFFMenuItem, (LPCTSTR)_T("TIFF format")); comboBoxPtr->SetItemData (0, kNoneMenuItem); comboBoxPtr->SetItemData (1, kArcViewMenuItem); comboBoxPtr->SetItemData (2, kERDAS74MenuItem); comboBoxPtr->SetItemData (3, kGAIAMenuItem); comboBoxPtr->SetItemData (4, kTIFFGeoTIFFMenuItem); comboBoxPtr->SetItemData (5, kMatlabMenuItem); // Remove Matlab and ArcView options. comboBoxPtr->DeleteString (kMatlabMenuItem); comboBoxPtr->DeleteString (kGAIAMenuItem); m_headerListSelection = GetComboListSelection (IDC_Header, m_headerOptionsSelection); m_channelSelection = channelSelection; if (UpdateData (FALSE)) PositionDialogWindow (); // Set default text selection to first edit text item SelectDialogItemText (this, IDC_LineOffset, 0, SInt16_MAX); return FALSE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } // end "OnInitDialog" void CMReformatRectifyDlg::UpdateProcedureItems ( int selectItemNumber, Boolean blankOutsideSelectedAreaFlag) { DDX_Radio (m_dialogToPtr, IDC_TranslateScaleRotateRadio, m_procedureCode); RectifyImageDialogOnRectifyCode (this, m_procedureCode+1, blankOutsideSelectedAreaFlag, m_mapOrientationAngle); RectifyImageDialogOnReferenceFile (this, m_procedureCode+1, m_fileNamesSelection+1, &m_referenceWindowInfoHandle, &m_dialogSelectArea); // Set default text selection to first edit text item SelectDialogItemText (this, selectItemNumber, 0, SInt16_MAX); } // end "OnCbnSelendokTargetcombo"
30.880412
89
0.700007
cas-nctu
c2f7051af23e47299601f57e987c6ad7ce511145
1,068
cpp
C++
libz80emu/iManager/iManager.cpp
Benji377/Z80Emu
cc0d12a267e16e1c03c7cc8ef35b70ef9b582e54
[ "Apache-2.0" ]
1
2021-05-25T08:18:14.000Z
2021-05-25T08:18:14.000Z
libz80emu/iManager/iManager.cpp
Benji377/Z80Emu
cc0d12a267e16e1c03c7cc8ef35b70ef9b582e54
[ "Apache-2.0" ]
7
2021-01-11T09:24:16.000Z
2021-05-25T16:04:19.000Z
libz80emu/iManager/iManager.cpp
Benji377/Z80Emu
cc0d12a267e16e1c03c7cc8ef35b70ef9b582e54
[ "Apache-2.0" ]
2
2021-01-19T14:53:55.000Z
2021-05-25T08:23:27.000Z
#include "iManager.h" IManager::IManager(Z80* z80){ FUN(); this->z80 = z80; this->iSet = new ISet(this->z80); } IManager::~IManager(){ FUN(); delete this->iSet; } Z80EmuInstrucion IManager::fetchIS(){ FUN(); if (this->ISLoaded){ LOGW("finalizeIS() was not called! Please call to clean up pointers!"); } //Read the opcode this->opcode = this->z80->readFromPCInc(); Z80EmuInstrucion curZ80EmuInstrucion = this->iSet->fetchZ80EmuInstrucion(this->opcode); return curZ80EmuInstrucion; } void IManager::execIS(Z80EmuInstrucion is){ FUN(); this->iSet->execIS(is); this->z80->addCycles(is.getCycles()); } void IManager::logIS(Z80EmuInstrucion is){ FUN(); uint8_t opcode = is[0]; std::string instruction = "(" + Log::toHexString(opcode) + ")"; for (size_t i = 1; i < is.size(); i++){ instruction += ";" + Log::toHexString(is[i]); } LOGD("Current instruction: " + instruction); } void IManager::finalizeIS(Z80EmuInstrucion is){ FUN(); this->ISLoaded = false; }
22.25
91
0.622659
Benji377
c2fa769dab75c7d73464dda82e4826a14d024651
1,056
hpp
C++
include/fingera/stream.hpp
fingera/fingera_header
fbda3515859eec269e6a67196276ac18251bdb49
[ "Apache-2.0" ]
1
2018-12-24T07:13:05.000Z
2018-12-24T07:13:05.000Z
include/fingera/stream.hpp
fingera/fingera_header
fbda3515859eec269e6a67196276ac18251bdb49
[ "Apache-2.0" ]
null
null
null
include/fingera/stream.hpp
fingera/fingera_header
fbda3515859eec269e6a67196276ac18251bdb49
[ "Apache-2.0" ]
null
null
null
/** * @brief 实现基础的Stream * * @file stream.hpp * @author liuyujun@fingera.cn * @date 2018-09-18 */ #pragma once #include <cstdint> #include <cstring> #include <stdexcept> #include <vector> namespace fingera { class write_stream { protected: std::vector<uint8_t> _data; public: write_stream() {} ~write_stream() {} inline void write(const void *data, size_t size) { const uint8_t *ptr = reinterpret_cast<const uint8_t *>(data); _data.insert(_data.end(), ptr, ptr + size); } inline std::vector<uint8_t> &data() { return _data; } }; class read_stream { protected: const std::vector<uint8_t> &_data; size_t _cursor; public: read_stream(const std::vector<uint8_t> &data) : _data(data), _cursor(0) {} ~read_stream() {} inline void read(void *buf, size_t size) { if (_cursor + size > _data.size()) { throw std::overflow_error("read_stream::read"); } memcpy(buf, &_data[_cursor], size); _cursor += size; } inline bool valid() { return _cursor < _data.size(); } }; } // namespace fingera
19.555556
76
0.651515
fingera
c2fc51e8440055ad9658655d6e835269a35cb5ab
45,126
cpp
C++
ExaHyPE/exahype/Parser.cpp
yungcheeze/exahype
897970ea2836132e1c221eec7bd1a717afee97ae
[ "BSD-3-Clause" ]
null
null
null
ExaHyPE/exahype/Parser.cpp
yungcheeze/exahype
897970ea2836132e1c221eec7bd1a717afee97ae
[ "BSD-3-Clause" ]
null
null
null
ExaHyPE/exahype/Parser.cpp
yungcheeze/exahype
897970ea2836132e1c221eec7bd1a717afee97ae
[ "BSD-3-Clause" ]
null
null
null
/** * This file is part of the ExaHyPE project. * Copyright (c) 2016 http://exahype.eu * All rights reserved. * * The project has received funding from the European Union's Horizon * 2020 research and innovation programme under grant agreement * No 671698. For copyrights and licensing, please consult the webpage. * * Released under the BSD 3 Open Source License. * For the full license text, see LICENSE.txt **/ #include "exahype/Parser.h" #include "tarch/Assertions.h" #include <fstream> #include <stdio.h> #include <string.h> #include <string> #include <regex> #include <cstdlib> // getenv, exit #include "tarch/la/ScalarOperations.h" tarch::logging::Log exahype::Parser::_log("exahype::Parser"); bool exahype::Parser::_interpretationErrorOccured(false); const std::string exahype::Parser::_noTokenFound("notoken"); double exahype::Parser::getValueFromPropertyString( const std::string& parameterString, const std::string& key) { std::size_t startIndex = parameterString.find(key); startIndex = parameterString.find(":", startIndex); std::size_t endIndex = parameterString.find_first_of("}, \n\r", startIndex + 1); std::string substring = parameterString.substr(startIndex + 1, endIndex - startIndex - 1); double result; std::istringstream ss(substring); ss >> result; if (ss) { return result; } else { return std::numeric_limits<double>::quiet_NaN(); } } exahype::Parser::Parser() { _identifier2Type.insert( std::pair<std::string, exahype::solvers::Solver::Type>( "ADER-DG", exahype::solvers::Solver::Type::ADERDG)); _identifier2Type.insert( std::pair<std::string, exahype::solvers::Solver::Type>( "Finite-Volumes", exahype::solvers::Solver::Type::FiniteVolumes)); _identifier2Type.insert( std::pair<std::string, exahype::solvers::Solver::Type>( "Limiting-ADER-DG", exahype::solvers::Solver::Type::LimitingADERDG)); _identifier2TimeStepping.insert( std::pair<std::string, exahype::solvers::Solver::TimeStepping>( "global", exahype::solvers::Solver::TimeStepping::Global)); _identifier2TimeStepping.insert( std::pair<std::string, exahype::solvers::Solver::TimeStepping>( "globalfixed", exahype::solvers::Solver::TimeStepping::GlobalFixed)); } void exahype::Parser::readFile(const std::string& filename) { try { const int MAX_CHARS_PER_LINE = 65536; std::regex COMMENT_BEGIN(R"((\/\*))"); // Covers all cases /*,/**,/***,... . std::regex COMMENT_END(R"((\*\/))"); // std::regex GROUP_BEGIN_OR_END(R"(^(\s|\t)*([a-zA-Z][^\=]+)+)"); std::regex CONST_PARAMETER(R"(^(\s|\t)*([A-Za-z](\w|[^a-zA-Z\d\s\t])*)(\s|\t)+const(\s|\t)*=(\s|\t)*(([^\s\t]|\,\s*)+)(\s|\t)*$)"); std::regex PARAMETER(R"(^(\s|\t)*([A-Za-z](\w|[^a-zA-Z\d\s\t])*)(\s|\t)*=(\s|\t)*(([^\s\t]|\,\s*)+)(\s|\t)*$)"); std::regex NO_SPLITTING(R"(\}|\{)"); std::regex COMMA_SEPARATED(R"((\w|[^a-zA-Z\,\s\t])+)"); std::regex WHITESPACE_SEPARATED(R"(([^\s\t]+))"); std::smatch match; _tokenStream.clear(); std::ifstream inputFile; inputFile.open(filename.c_str()); if (!inputFile.good()) { logError("readFile(String)", "cannot open file " << filename); _tokenStream.clear(); _interpretationErrorOccured = true; return; } int currentlyReadsComment = 0; int lineNumber = 0; while (!inputFile.eof() && inputFile) { char lineBuffer[MAX_CHARS_PER_LINE]; inputFile.getline(lineBuffer, MAX_CHARS_PER_LINE); std::string line(lineBuffer); // parse the line if (std::regex_search(line, match, COMMENT_BEGIN) && match.size() > 1) { currentlyReadsComment += 1; } if (std::regex_search(line, match, COMMENT_END) && match.size() > 1) { currentlyReadsComment -= 1; } // Runtime parameters if (currentlyReadsComment==0 && std::regex_search(line, match, PARAMETER) && match.size() > 1) { _tokenStream.push_back(match.str(2)); // Subgroup 2 is left-hand side (trimmed) std::string rightHandSide = match.str(6); if (!std::regex_search(rightHandSide, match, NO_SPLITTING)) { std::regex_iterator<std::string::iterator> regex_it ( rightHandSide.begin(), rightHandSide.end(), COMMA_SEPARATED ); std::regex_iterator<std::string::iterator> rend; while(regex_it!=rend) { _tokenStream.push_back(regex_it->str()); ++regex_it; } } else { _tokenStream.push_back(rightHandSide); } // Compile time parameters (Do not push the token const on the stream) } else if (currentlyReadsComment==0 && std::regex_search(line, match, CONST_PARAMETER) && match.size() > 1) { _tokenStream.push_back(match.str(2)); // Subgroup 2 is left-hand side (trimmed) std::string rightHandSide = match.str(7); if (!std::regex_search(rightHandSide, match, NO_SPLITTING)) { std::regex_iterator<std::string::iterator> regex_it ( rightHandSide.begin(), rightHandSide.end(), COMMA_SEPARATED ); std::regex_iterator<std::string::iterator> rend; while(regex_it!=rend) { _tokenStream.push_back(regex_it->str()); ++regex_it; } } else { _tokenStream.push_back(rightHandSide); } } else if (currentlyReadsComment==0 && std::regex_search(line, match, GROUP_BEGIN_OR_END) && match.size() > 1) { std::regex_iterator<std::string::iterator> regex_it ( line.begin(), line.end(), WHITESPACE_SEPARATED ); std::regex_iterator<std::string::iterator> rend; if (regex_it->str().compare("end")!=0) { // first token should not be end while(regex_it!=rend) { _tokenStream.push_back(regex_it->str()); ++regex_it; } } // else do nothing } else if (currentlyReadsComment<0) { logError("readFile(String)", "Please remove additional multi-line comment end(s) in line '" << lineNumber << "'."); _interpretationErrorOccured = true; } lineNumber++; } if (currentlyReadsComment>0) { logError("readFile(String)", "A multi-line comment was not closed after line " << lineNumber); _interpretationErrorOccured = true; } } catch (const std::regex_error& e) { logError("readFile(String)", "catched exception " << e.what() ); _interpretationErrorOccured = true; } // For debugging purposes if(std::getenv("EXAHYPE_VERBOSE_PARSER")) { // runtime debugging std::cout << "Parser _tokenStream=" << std::endl; for (std::string str : _tokenStream) { std::cout << "["<<str<<"]" << std::endl; } } checkValidity(); // std::string configuration = getMPIConfiguration(); // int ranksPerNode = static_cast<int>(exahype::Parser::getValueFromPropertyString(configuration,"ranks_per_node")); // std::cout << "ranks_per_node="<<ranksPerNode << std::endl; } void exahype::Parser::checkValidity() { // functions have side-effects: might set _interpretationErrorOccured getDomainSize(); getOffset(); getSimulationEndTime(); } bool exahype::Parser::isValid() const { return !_tokenStream.empty() && !_interpretationErrorOccured; } void exahype::Parser::invalidate() { _interpretationErrorOccured = true; } std::string exahype::Parser::getTokenAfter(std::string token, int additionalTokensToSkip) const { assertion(isValid()); int currentToken = 0; while (currentToken < static_cast<int>(_tokenStream.size()) && _tokenStream[currentToken] != token) { currentToken++; } currentToken += (additionalTokensToSkip + 1); if (currentToken < static_cast<int>(_tokenStream.size())) { return _tokenStream[currentToken]; } else return _noTokenFound; } std::string exahype::Parser::getTokenAfter(std::string token0, std::string token1, int additionalTokensToSkip) const { int currentToken = 0; while (currentToken < static_cast<int>(_tokenStream.size()) && _tokenStream[currentToken] != token0) { currentToken++; } while (currentToken < static_cast<int>(_tokenStream.size()) && _tokenStream[currentToken] != token1) { currentToken++; } currentToken += (additionalTokensToSkip + 1); if (currentToken < static_cast<int>(_tokenStream.size())) { return _tokenStream[currentToken]; } else return _noTokenFound; } std::string exahype::Parser::getTokenAfter(std::string token0, int occurance0, int additionalTokensToSkip) const { assertion(isValid()); assertion(occurance0 > 0); int currentToken = 0; while (currentToken < static_cast<int>(_tokenStream.size()) && (_tokenStream[currentToken] != token0 || occurance0 > 1)) { if (_tokenStream[currentToken] == token0) occurance0--; currentToken++; } currentToken += (additionalTokensToSkip + 1); if (currentToken < static_cast<int>(_tokenStream.size())) { return _tokenStream[currentToken]; } else return _noTokenFound; } std::string exahype::Parser::getTokenAfter(std::string token0, int occurance0, std::string token1, int occurance1, int additionalTokensToSkip) const { assertion(isValid()); assertion(occurance0 > 0); assertion(occurance1 > 0); int currentToken = 0; while (currentToken < static_cast<int>(_tokenStream.size()) && (_tokenStream[currentToken] != token0 || occurance0 > 1)) { if (_tokenStream[currentToken] == token0) occurance0--; currentToken++; } while (currentToken < static_cast<int>(_tokenStream.size()) && (_tokenStream[currentToken] != token1 || occurance1 > 1)) { if (_tokenStream[currentToken] == token1) occurance1--; currentToken++; } currentToken += (additionalTokensToSkip + 1); if (currentToken < static_cast<int>(_tokenStream.size())) { return _tokenStream[currentToken]; } else return _noTokenFound; } int exahype::Parser::getNumberOfThreads() const { assertion(isValid()); std::string token = getTokenAfter("shared-memory", "cores"); logDebug("getNumberOfThreads()", "found token " << token); int result = atoi(token.c_str()); if (result == 0) { logError("getNumberOfThreads()", "Invalid number of cores set or token shared-memory missing: " << token); result = 1; _interpretationErrorOccured = true; } return result; } tarch::la::Vector<DIMENSIONS, double> exahype::Parser::getDomainSize() const { assertion(isValid()); std::string token; tarch::la::Vector<DIMENSIONS, double> result; token = getTokenAfter("computational-domain", "dimension", 0); int dim = std::atoi(token.c_str()); if (dim < DIMENSIONS) { logError("getDomainSize()", "dimension: value "<< token << " in specification file" << " does not match -DDim"<<DIMENSIONS<<" switch in Makefile"); _interpretationErrorOccured = true; return result; } token = getTokenAfter("computational-domain", "width", 0); result(0) = atof(token.c_str()); token = getTokenAfter("computational-domain", "width", 1); result(1) = atof(token.c_str()); #if DIMENSIONS == 3 token = getTokenAfter("computational-domain", "width", 2); if (token.compare("offset")==0) { logError("getDomainSize()", "width: not enough values specified for " << DIMENSIONS<< " dimensions"); _interpretationErrorOccured = true; return result; } result(2) = atof(token.c_str()); #endif return result; } tarch::la::Vector<DIMENSIONS, double> exahype::Parser::getOffset() const { assertion(isValid()); std::string token; tarch::la::Vector<DIMENSIONS, double> result; token = getTokenAfter("computational-domain", "offset", 0); result(0) = atof(token.c_str()); token = getTokenAfter("computational-domain", "offset", 1); result(1) = atof(token.c_str()); #if DIMENSIONS == 3 token = getTokenAfter("computational-domain", "offset", 2); if (token.compare("end-time")==0) { logError("getOffset()", "offset: not enough values specified for " << DIMENSIONS<< " dimensions"); _interpretationErrorOccured = true; return result; } token = getTokenAfter("computational-domain", "offset", 2); result(2) = atof(token.c_str()); #endif logDebug("getSize()", "found offset " << result); return result; } std::string exahype::Parser::getMulticorePropertiesFile() const { std::string result = getTokenAfter("shared-memory", "properties-file"); logDebug("getMulticorePropertiesFile()", "found token " << result); return result; } exahype::Parser::MPILoadBalancingType exahype::Parser::getMPILoadBalancingType() const { std::string token = getTokenAfter("distributed-memory", "identifier"); exahype::Parser::MPILoadBalancingType result = MPILoadBalancingType::Static; if (token.compare("static_load_balancing") == 0) { result = MPILoadBalancingType::Static; } else { logError("getMPILoadBalancingType()", "Invalid distributed memory identifier " << token); _interpretationErrorOccured = true; } return result; } std::string exahype::Parser::getMPIConfiguration() const { return getTokenAfter("distributed-memory", "configure"); } int exahype::Parser::getMPIBufferSize() const { std::string token = getTokenAfter("distributed-memory", "buffer-size"); int result = atoi(token.c_str()); if (result <= 0) { logError("getMPIBufferSize()", "Invalid MPI buffer size " << token); result = 64; _interpretationErrorOccured = true; } return result; } int exahype::Parser::getMPITimeOut() const { std::string token = getTokenAfter("distributed-memory", "timeout"); int result = atoi(token.c_str()); if (result <= 0) { logError("getMPIBufferSize()", "Invalid MPI timeout value " << token); result = 0; _interpretationErrorOccured = true; } return result; } bool exahype::Parser::getMPIMasterWorkerCommunication() const { std::string token = getTokenAfter("distributed-memory", "master-worker-communication"); if (token.compare(_noTokenFound) != 0) { logInfo("getMPIMasterWorkerCommunication()", "found master-worker-communication " << token); return token.compare("on") == 0; } return true; } bool exahype::Parser::getMPINeighbourCommunication() const { std::string token = getTokenAfter("distributed-memory", "neighbour-communication"); if (token.compare(_noTokenFound) != 0) { logInfo("getMPINeighbourCommunication()", "found neighbour-communication " << token); return token.compare("on") == 0; } return true; } exahype::Parser::MulticoreOracleType exahype::Parser::getMulticoreOracleType() const { std::string token = getTokenAfter("shared-memory", "identifier"); exahype::Parser::MulticoreOracleType result = MulticoreOracleType::Dummy; if (token.compare("dummy") == 0) { result = MulticoreOracleType::Dummy; } else if (token.compare("autotuning") == 0) { result = MulticoreOracleType::AutotuningWithRestartAndLearning; } else if (token.compare("autotuning_without_learning") == 0) { result = MulticoreOracleType::AutotuningWithoutLearning; } else if (token.compare("autotuning_without_restart") == 0) { result = MulticoreOracleType::AutotuningWithLearningButWithoutRestart; } else if (token.compare("sampling") == 0) { result = MulticoreOracleType::GrainSizeSampling; } else { logError("getMulticoreOracleType()", "Invalid shared memory identifier " << token); result = MulticoreOracleType::Dummy; _interpretationErrorOccured = true; } return result; } double exahype::Parser::getSimulationEndTime() const { std::string token = getTokenAfter("computational-domain", "end-time"); logDebug("getSimulationEndTime()", "found token " << token); double result = atof(token.c_str()); if (result <= 0) { logError("getSimulationEndTime()", "Invalid simulation end-time: " << token); result = 1.0; _interpretationErrorOccured = true; } return result; } bool exahype::Parser::getFuseAlgorithmicSteps() const { std::string token = getTokenAfter("global-optimisation", "fuse-algorithmic-steps"); logDebug("getFuseAlgorithmicSteps()", "found fuse-algorithmic-steps" << token); bool result = token.compare("on") == 0; if (token.compare(_noTokenFound) == 0) { result = false; // default value } else if (token.compare("on") != 0 && token.compare("off") != 0) { logError("getFuseAlgorithmicSteps()", "fuse-algorithmic-steps is required in the " "global-optimisation segment and has to be either on or off: " << token); _interpretationErrorOccured = true; } return result; } bool exahype::Parser::getExchangeBoundaryDataInBatchedTimeSteps() const { std::string token = getTokenAfter( "global-optimisation", "disable-amr-if-grid-has-been-stationary-in-previous-iteration"); if (token.compare("on") != 0 && token.compare("off") != 0) { logError("getExchangeBoundaryDataInBatchedTimeSteps()", "disable-amr-if-grid-has-been-stationary-in-previous-iteration is " "required in the " "global-optimisation segment and has to be either on or off: " << token); _interpretationErrorOccured = true; } return token.compare("off") == 0; } double exahype::Parser::getFuseAlgorithmicStepsFactor() const { if (hasOptimisationSegment()) { std::string token = getTokenAfter("global-optimisation", "fuse-algorithmic-steps-factor"); char* pEnd; double result = std::strtod(token.c_str(), &pEnd); logDebug("getFuseAlgorithmicStepsFactor()", "found fuse-algorithmic-steps-factor " << token); if (result < 0.0 || result > 1.0 || pEnd == token.c_str()) { logError("getFuseAlgorithmicStepsFactor()", "'fuse-algorithmic-steps-factor': Value must be greater than zero " "and smaller than one: " << result); result = 0.0; _interpretationErrorOccured = true; } return result; } else return false; } double exahype::Parser::getTimestepBatchFactor() const { std::string token = getTokenAfter("global-optimisation", "timestep-batch-factor"); char* pEnd; double result = std::strtod(token.c_str(), &pEnd); logDebug("getFuseAlgorithmicStepsFactor()", "found timestep-batch-factor " << token); if (result < 0.0 || result > 1.0 || pEnd == token.c_str()) { logError("getFuseAlgorithmicStepsFactor()", "'timestep-batch-factor': Value is required in global-optimisation " "section and must be greater than zero and smaller than one: " << result); result = 0.0; _interpretationErrorOccured = true; } return result; } bool exahype::Parser::hasOptimisationSegment() const { std::string token = getTokenAfter("global-optimisation"); return token.compare(_noTokenFound)!=0; } bool exahype::Parser::getSkipReductionInBatchedTimeSteps() const { if (hasOptimisationSegment()) { std::string token = getTokenAfter("global-optimisation", "skip-reduction-in-batched-time-steps"); logDebug("getSkipReductionInBatchedTimeSteps()", "found skip-reduction-in-batched-time-steps " << token); if (token.compare("on") != 0 && token.compare("off") != 0) { logError("getSkipReductionInBatchedTimeSteps()", "skip-reduction-in-batched-time-steps is required in the " "global-optimisation segment and has to be either on or off: " << token); _interpretationErrorOccured = true; } return token.compare("on") == 0; } else return false; } double exahype::Parser::getDoubleCompressionFactor() const { std::string token = getTokenAfter("global-optimisation", "double-compression"); if (token.compare(_noTokenFound) == 0) { return 0.0; // default value } else { char* pEnd; double result = std::strtod(token.c_str(), &pEnd); logDebug("getDoubleCompressionFactor()", "found double-compression " << token); if (result < 0.0 || pEnd == token.c_str()) { logError("getDoubleCompressionFactor()", "'double-compression': Value is required in global-optimisation " "section and must be greater than or equal to zero: " << result); result = 0.0; _interpretationErrorOccured = true; } return result; } } bool exahype::Parser::getSpawnDoubleCompressionAsBackgroundTask() const { std::string token = getTokenAfter("global-optimisation", "spawn-double-compression-as-background-thread"); if (token.compare(_noTokenFound) == 0) { return false; // default value } else { logDebug("getSpawnDoubleCompressionAsBackgroundTask()", "found spawn-double-compression-as-background-thread " << token); if (token.compare("on") != 0 && token.compare("off") != 0) { logError("getSpawnDoubleCompressionAsBackgroundTask()", "spawn-double-compression-as-background-thread is required in the " "global-optimisation segment and has to be either on or off: " << token); _interpretationErrorOccured = true; } return token.compare("on") == 0; } } exahype::solvers::Solver::Type exahype::Parser::getType( int solverNumber) const { std::string token; exahype::solvers::Solver::Type result = exahype::solvers::Solver::Type::ADERDG; token = getTokenAfter("solver", solverNumber + 1, 0); if (_identifier2Type.find(token) != _identifier2Type.end()) { result = _identifier2Type.at(token); // logDebug("getType()", "found type " << result); logDebug("getType()", "found type "); } else { logError( "getType()", "'" << getIdentifier(solverNumber) << "': 'type': Value '" << token << "' is invalid. See the ExaHyPE documentation for valid values."); _interpretationErrorOccured = true; } return result; } std::string exahype::Parser::getIdentifier(int solverNumber) const { std::string token; token = getTokenAfter("solver", solverNumber + 1, 1); logDebug("getIdentifier()", "found identifier " << token); return token; } int exahype::Parser::getVariables(int solverNumber) const { std::string token; int result; std::regex COLON_SEPARATED(R"(([A-Za-z]\w*):([0-9]+))"); std::smatch match; // first check if we read in a number token = getTokenAfter("solver", solverNumber + 1, "variables", 1); result = atoi(token.c_str()); if (result < 1) { // token is not a number result = 0; int i = 1; std::regex_search(token, match, COLON_SEPARATED); while (match.size() > 1) { int multiplicity = atoi(match.str(2).c_str()); result +=multiplicity; // std::string name = match.str(1); // logInfo("getVariables(...)","token="<<token<<",name="<<match.str(1)<<",n="<<match.str(2)); token = getTokenAfter("solver", solverNumber + 1, "variables", 1, i++); std::regex_search(token, match, COLON_SEPARATED); } if (result < 1) { // token is still 0 logError("getVariables()", "'" << getIdentifier(solverNumber) << "': 'variables': Value must be greater than zero."); _interpretationErrorOccured = true; } } logDebug("getVariables()", "found variables " << result); return result; } int exahype::Parser::getParameters(int solverNumber) const { std::string token; int result; std::regex COLON_SEPARATED(R"(([A-Za-z]\w*):([0-9]+))"); std::smatch match; // first check if we read in a number token = getTokenAfter("solver", solverNumber + 1, "parameters", 1); result = atoi(token.c_str()); if (result < 1) { // token is not a number result = 0; int i = 1; std::regex_search(token, match, COLON_SEPARATED); while (match.size() > 1) { int multiplicity = atoi(match.str(2).c_str()); result +=multiplicity; // std::string name = match.str(1); // logInfo("getVariables(...)","token="<<token<<",name="<<match.str(1)<<",n="<<match.str(2)); token = getTokenAfter("solver", solverNumber + 1, "parameters", 1, i++); std::regex_search(token, match, COLON_SEPARATED); } if (result < 0) { // token is still 0 logError("getParameters()", "'" << getIdentifier(solverNumber) << "': 'parameters': Value must be non-negative."); _interpretationErrorOccured = true; } } logDebug("getVariables()", "found variables " << result); return result; } int exahype::Parser::getOrder(int solverNumber) const { std::string token; int result; token = getTokenAfter("solver", solverNumber + 1, "order", 1); result = atoi(token.c_str()); if (result < 0) { logError("getOrder()", "'" << getIdentifier(solverNumber) << "': 'order': Value must not be negative."); _interpretationErrorOccured = true; } logDebug("getOrder()", "found order " << result); return result; } double exahype::Parser::getMaximumMeshSize(int solverNumber) const { std::string token; double result; token = getTokenAfter("solver", solverNumber + 1, "maximum-mesh-size", 1, 0); result = atof(token.c_str()); if (tarch::la::smallerEquals(result, 0.0)) { logError("getMaximumMeshSize(int)", "'" << getIdentifier(solverNumber) << "': 'maximum-mesh-size': Value must be greater than zero."); _interpretationErrorOccured = true; } logDebug("getMaximumMeshSize()", "found maximum mesh size " << result); return result; } double exahype::Parser::getMaximumMeshDepth(int solverNumber) const { std::string token; int result; token = getTokenAfter("solver", solverNumber + 1, "maximum-mesh-depth", 1, 0); if (token==_noTokenFound) { return 0; } result = std::atoi(token.c_str()); if (tarch::la::smaller(result, 0)) { logError("getMaximumMeshDepth(int)", "'" << getIdentifier(solverNumber) << "': 'maximum-mesh-depth': Value must be greater than or equal to zero."); _interpretationErrorOccured = true; } logDebug("getMaximumMeshDepth()", "found maximum mesh size " << result); return result; } exahype::solvers::Solver::TimeStepping exahype::Parser::getTimeStepping( int solverNumber) const { std::string token; exahype::solvers::Solver::TimeStepping result; token = getTokenAfter("solver", solverNumber + 1, "time-stepping", 1); if (_identifier2TimeStepping.find(token) != _identifier2TimeStepping.end()) { result = _identifier2TimeStepping.at(token); // logDebug("getTimeStepping()", "found TimeStepping " << result); logDebug("getTimeStepping()", "found TimeStepping "<< token); return result; } else { logError( "getTimeStepping()", "'" << getIdentifier(solverNumber) << "': 'time-stepping': Value '" << token << "' is invalid. See the ExaHyPE documentation for valid values."); _interpretationErrorOccured = true; } return exahype::solvers::Solver::TimeStepping::Global; } double exahype::Parser::getDMPRelaxationParameter(int solverNumber) const { std::string token; double result; token = getTokenAfter("solver", solverNumber + 1, "dmp-relaxation-parameter", 1); result = atof(token.c_str()); if (result < 0) { logError("getDMPRelaxationParameter()", "'" << getIdentifier(solverNumber) << "': 'dmp-relaxation-parameter': Value must not be negative."); _interpretationErrorOccured = true; } logInfo("getParameters()", "found dmp-relaxation-parameter " << result); return result; } double exahype::Parser::getDMPDifferenceScaling(int solverNumber) const { std::string token; double result; token = getTokenAfter("solver", solverNumber + 1, "dmp-difference-scaling", 1); result = atof(token.c_str()); if (result < 0) { logError("getDMPDifferenceScaling()", "'" << getIdentifier(solverNumber) << "': 'dmp-difference-scaling': Value must not be negative."); _interpretationErrorOccured = true; } logInfo("getDMPDifferenceScaling()", "found dmp-difference-scaling " << result); return result; } int exahype::Parser::getDMPObservables(int solverNumber) const { std::string token; int result; token = getTokenAfter("solver", solverNumber + 1, "dmp-observables", 1); result = std::atoi(token.c_str()); if (result < 0) { logError("getDMPObservables()", "'" << getIdentifier(solverNumber) << "': 'dmp-observables': Value must not be negative."); _interpretationErrorOccured = true; } logInfo("getDMPObservables()", "found dmp-observables " << result); return result; } int exahype::Parser::getStepsTillCured(int solverNumber) const { std::string token; int result = 0; token = getTokenAfter("solver", solverNumber + 1, "steps-till-cured", 1); if (token.compare(_noTokenFound)!=0) { result = std::atoi(token.c_str()); if (result < 0) { logError("getStepsTillCured()", "'" << getIdentifier(solverNumber) << "': 'steps-till-cured': Value must not be negative."); _interpretationErrorOccured = true; } logInfo("getStepsTillCured()", "found steps-till-cured " << result); } return result; } int exahype::Parser::getLimiterHelperLayers(int solverNumber) const { std::string token; int result = 1; // default token = getTokenAfter("solver", solverNumber + 1, "helper-layers", 1); if (token.compare(_noTokenFound)!=0) { result = std::atoi(token.c_str()); if (result < 1) { logError("getLimiterHelperLayers()", "'" << getIdentifier(solverNumber) << "': 'helper-layers': Value must not be greater or equal to 1."); _interpretationErrorOccured = true; } logInfo("getLimiterHelperLayers()", "found helper-layers " << result); } return result; } std::string exahype::Parser::getIdentifierForPlotter(int solverNumber, int plotterNumber) const { // We have to multiply with two as the token solver occurs twice (to open and // close the section) std::string token = getTokenAfter("solver", solverNumber + 1, "plot", plotterNumber + 1); logDebug("getIdentifierForPlotter()", "found token " << token); assertion3(token.compare(_noTokenFound) != 0, token, solverNumber, plotterNumber); return token; } std::string exahype::Parser::getNameForPlotter(int solverNumber, int plotterNumber) const { // We have to multiply with two as the token solver occurs twice (to open and // close the section) std::string token = getTokenAfter("solver", solverNumber + 1, "plot", plotterNumber + 1, 1); logDebug("getIdentifierForPlotter()", "found token " << token); assertion3(token.compare(_noTokenFound) != 0, token, solverNumber, plotterNumber); return token; } int exahype::Parser::getUnknownsForPlotter(int solverNumber, int plotterNumber) const { // We have to multiply with two as the token solver occurs twice (to open and // close the section) std::string token = getTokenAfter("solver", solverNumber + 1, "plot", plotterNumber + 1, 3); logDebug("getUnknownsForPlotter()", "found token " << token); assertion3(token.compare(_noTokenFound) != 0, token, solverNumber, plotterNumber); return atoi(token.c_str()); } double exahype::Parser::getFirstSnapshotTimeForPlotter( int solverNumber, int plotterNumber) const { // We have to multiply with two as the token solver occurs twice (to open and // close the section) std::string token = getTokenAfter("solver", solverNumber + 1, "plot", plotterNumber + 1, 5); logDebug("getFirstSnapshotTimeForPlotter()", "found token " << token); assertion3(token.compare(_noTokenFound) != 0, token, solverNumber, plotterNumber); return atof(token.c_str()); } double exahype::Parser::getRepeatTimeForPlotter(int solverNumber, int plotterNumber) const { // We have to multiply with two as the token solver occurs twice (to open and // close the section) std::string token = getTokenAfter("solver", solverNumber + 1, "plot", plotterNumber + 1, 7); logDebug("getRepeatTimeForPlotter()", "found token " << token); assertion3(token.compare(_noTokenFound) != 0, token, solverNumber, plotterNumber); return atof(token.c_str()); } std::string exahype::Parser::getFilenameForPlotter(int solverNumber, int plotterNumber) const { // We have to multiply with two as the token solver occurs twice (to open and // close the section) std::string token = getTokenAfter("solver", solverNumber + 1, "plot", plotterNumber + 1, 9); logDebug("getFilenameForPlotter()", "found token " << token); assertion3(token.compare(_noTokenFound) != 0, token, solverNumber, plotterNumber); return token; } std::string exahype::Parser::getSelectorForPlotter(int solverNumber, int plotterNumber) const { // We have to multiply with two as the token solver occurs twice (to open and // close the section) std::string token = getTokenAfter("solver", solverNumber + 1, "plot", plotterNumber + 1, 11); token += "," + getTokenAfter("solver", solverNumber + 1, "plot", plotterNumber + 1, 12); #if DIMENSIONS==3 token += "," + getTokenAfter("solver",solverNumber + 1, "plot", plotterNumber + 1, 13); #endif logDebug("getSelectorForPlotter()", "found token " << token); return (token != _noTokenFound) ? token : ""; } std::string exahype::Parser::getLogFileName() const { std::string token = getTokenAfter("log-file"); logDebug("getLogFileName()", "found token " << token); return (token != _noTokenFound) ? token : ""; } std::string exahype::Parser::getProfilerIdentifier() const { std::string token = getTokenAfter("profiling", "profiler"); logDebug("getProfilerIdentifier()", "found token " << token); return (token != _noTokenFound) ? token : "NoOpProfiler"; } std::string exahype::Parser::getMetricsIdentifierList() const { std::string token = getTokenAfter("profiling", "metrics"); logDebug("getMetricsIdentifierList()", "found token " << token); return (token != _noTokenFound) ? token : "{}"; } std::string exahype::Parser::getProfilingOutputFilename() const { std::string token = getTokenAfter("profiling", "profiling-output"); logDebug("getProfilingOutputFilename()", "found token " << token); return (token != _noTokenFound) ? token : ""; } void exahype::Parser::logSolverDetails(int solverNumber) const { logInfo("logSolverDetails()", "Solver " << getTokenAfter("solver", solverNumber + 1, 0) << " " << getIdentifier(solverNumber) << ":"); logInfo("logSolverDetails()", "variables:\t\t" << getVariables(solverNumber)); logInfo("logSolverDetails()", "parameters:\t" << getParameters(solverNumber)); logInfo("logSolverDetails()", "order:\t\t" << getOrder(solverNumber)); logInfo("logSolverDetails()", "maximum-mesh-size:\t" << getMaximumMeshSize(solverNumber)); logInfo("logSolverDetails()", "time-stepping:\t" << getTokenAfter("solver", solverNumber + 1, "time-stepping", 1)); } void exahype::Parser::checkSolverConsistency(int solverNumber) const { assertion1(solverNumber < static_cast<int>(exahype::solvers::RegisteredSolvers.size()), solverNumber); exahype::solvers::Solver* solver = exahype::solvers::RegisteredSolvers[solverNumber]; bool recompile = false; bool runToolkitAgain = false; if (solver->getType() != getType(solverNumber)) { logError("checkSolverConsistency", "'" << getIdentifier(solverNumber) << "': Solver type in specification file " << "('" << exahype::solvers::Solver::toString(getType(solverNumber)) << "') " << "differs from solver type used in implementation " << "('" << exahype::solvers::Solver::toString(solver->getType()) << "')."); recompile = true; _interpretationErrorOccured = true; } if (solver->getIdentifier().compare(getIdentifier(solverNumber))) { logError("checkSolverConsistency", "'" << getIdentifier(solverNumber) << "': Identifier in specification file " << "('" << getIdentifier(solverNumber) << "') differs from identifier used in implementation ('" << solver->getIdentifier() << "')."); recompile = true; _interpretationErrorOccured = true; } if (solver->getNumberOfVariables() != getVariables(solverNumber)) { logError("checkSolverConsistency", "'" << getIdentifier(solverNumber) << "': Value for 'variables' in specification file" << "('" << getVariables(solverNumber) << "') differs from number of variables used in " "implementation file ('" << solver->getNumberOfVariables() << "')."); recompile = true; _interpretationErrorOccured = true; } if (solver->getNumberOfParameters() != getParameters(solverNumber)) { logError("checkSolverConsistency", "'" << getIdentifier(solverNumber) << "': Value for field 'parameters' in specification file" << "('" << getParameters(solverNumber) << "') differs from number of parameters used in " "implementation file ('" << solver->getNumberOfParameters() << "')."); recompile = true; _interpretationErrorOccured = true; } if (solver->getType() == exahype::solvers::Solver::Type::ADERDG && solver->getNodesPerCoordinateAxis() != getOrder(solverNumber) + 1) { logError("checkSolverConsistency", "'" << getIdentifier(solverNumber) << "': Value for field 'order' in specification file " << "('" << getOrder(solverNumber) << "') differs from value used in implementation file ('" << solver->getNodesPerCoordinateAxis() - 1 << "'). "); runToolkitAgain = true; _interpretationErrorOccured = true; } // @todo We should add checks for FV as well // (Sven:) somehow for me the following lines are never printed. I don't // know why. if (runToolkitAgain) { logError("checkSolverConsistency", "Please (1) run the Toolkit again, and (2) recompile!"); _interpretationErrorOccured = true; } if (recompile) { logError( "checkSolverConsistency", "Please (1) adjust the specification file (*.exahype) or the file '" << solver->getIdentifier() << ".cpp' accordingly, and (2) recompile!"); _interpretationErrorOccured = true; } } exahype::Parser::ParserView exahype::Parser::getParserView(int solverNumber) { return ParserView(*this, solverNumber); } exahype::Parser::ParserView::ParserView(Parser& parser, int solverNumberInSpecificationFile) : _parser(parser), _solverNumberInSpecificationFile(solverNumberInSpecificationFile) {} std::string exahype::Parser::ParserView::getValue(const std::string& key) const { assertion(_parser.isValid()); std::string token; std::regex COLON_SEPARATED(R"((.+):(.+))"); std::smatch match; token = _parser.getTokenAfter("solver", _solverNumberInSpecificationFile + 1, "constants", 1, 0); std::regex_search(token, match, COLON_SEPARATED); int i = 1; while (match.size() > 1) { if (match.str(1).compare(key)==0) { logDebug("getValue()", "solver " << _solverNumberInSpecificationFile + 1 << ": found constant '" << key << "' with value '" << match.str(2) << "'."); return match.str(2); } token = _parser.getTokenAfter("solver", _solverNumberInSpecificationFile + 1, "constants", 1, i++); std::regex_search(token, match, COLON_SEPARATED); } logDebug("hasKey()", "solver " << _solverNumberInSpecificationFile + 1 << ": cannot find constant '" << key << "'."); return ""; } bool exahype::Parser::ParserView::hasKey(const std::string& key) const { assertion(_parser.isValid()); std::string token; std::regex COLON_SEPARATED(R"(.+):(.+))"); std::smatch match; token = _parser.getTokenAfter("solver", _solverNumberInSpecificationFile + 1, "constants", 1, 0); std::regex_search(token, match, COLON_SEPARATED); int i = 1; while (match.size() > 1) { if (match.str(1).compare(key)) { logDebug("hasKey()", "solver " << _solverNumberInSpecificationFile + 1 << ": found constant '" << key << "' with value '" << match.str(2) << "'."); return true; } token = _parser.getTokenAfter("solver", _solverNumberInSpecificationFile + 1, "constants", 1, i++); std::regex_search(token, match, COLON_SEPARATED); } logDebug("hasKey()", "solver " << _solverNumberInSpecificationFile + 1 << ": cannot find constant '" << key << "'."); return false; } int exahype::Parser::ParserView::getValueAsInt(const std::string& key) const { std::string value = getValue(key); int result; std::istringstream ss(value); ss >> result; if (ss) { return result; } else { assertion(!isValueValidInt(key)); assertionMsg(false, "shall not happen. Please call isValueValidXXX before"); return -1; } } bool exahype::Parser::ParserView::getValueAsBool(const std::string& key) const { std::string value = getValue(key); // We use 'on' and 'off' for multiple switches in the specification file // which would lead the java parser to object if (value.compare("true") == 0 || value.compare("1") == 0) { return true; } else if (value.compare("false") == 0 || value.compare("0") == 0) { return false; } else { assertion(!isValueValidBool(key)); assertionMsg(false, "shall not happen. Please call isValueValidXXX before"); return false; } } double exahype::Parser::ParserView::getValueAsDouble( const std::string& key) const { std::string value = getValue(key); double result; std::istringstream ss(value); // TODO(Dominic) ss >> result; if (ss) { return result; } else { assertion(!isValueValidDouble(key)); assertionMsg(false, "shall not happen. Please call isValueValidXXX before"); return -1.0; } } std::string exahype::Parser::ParserView::getValueAsString( const std::string& key) const { return getValue(key); } bool exahype::Parser::ParserView::isValueValidInt( const std::string& key) const { const std::string inputString = _parser.getTokenAfter( "solver", _solverNumberInSpecificationFile + 1, "constants", 1); std::string value = getValue(key); int result; std::istringstream ss(value); ss >> result; if (ss) { return true; } else { return false; } } bool exahype::Parser::ParserView::isValueValidDouble( const std::string& key) const { const std::string inputString = _parser.getTokenAfter( "solver", _solverNumberInSpecificationFile + 1, "constants", 1); std::string value = getValue(key); double result; std::istringstream ss(value); ss >> result; if (ss) { return true; } else { return false; } } bool exahype::Parser::ParserView::isValueValidBool( const std::string& key) const { const std::string inputString = _parser.getTokenAfter( "solver", _solverNumberInSpecificationFile + 1, "constants", 1); std::string value = getValue(key); // We use 'on' and 'off' for multiple switches in the specification file if (value.compare("true") == 0 || value.compare("false") == 0 || value.compare("1") == 0 || value.compare("0") == 0) { return true; } else { return false; } } bool exahype::Parser::ParserView::isValueValidString( const std::string& key) const { const std::string inputString = _parser.getTokenAfter( "solver", _solverNumberInSpecificationFile + 1, "constants", 1); return getValue(key) != ""; }
36.014366
155
0.636152
yungcheeze
c2fdb03ea09747b4f3e5041388a71db3e156c7b7
1,537
hpp
C++
SDK/ARKSurvivalEvolved_PrimalItemArmor_TekPants_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_PrimalItemArmor_TekPants_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_PrimalItemArmor_TekPants_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalItemArmor_TekPants_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function PrimalItemArmor_TekPants.PrimalItemArmor_TekPants_C.OverrideCrouchingSound struct UPrimalItemArmor_TekPants_C_OverrideCrouchingSound_Params { class USoundBase** InSound; // (Parm, ZeroConstructor, IsPlainOldData) bool* bIsProne; // (Parm, ZeroConstructor, IsPlainOldData) int* soundState; // (Parm, ZeroConstructor, IsPlainOldData) class USoundBase* ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function PrimalItemArmor_TekPants.PrimalItemArmor_TekPants_C.ExecuteUbergraph_PrimalItemArmor_TekPants struct UPrimalItemArmor_TekPants_C_ExecuteUbergraph_PrimalItemArmor_TekPants_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
41.540541
173
0.50488
2bite
c2feb4e8a5fec1bde3f5acbb3603162c91e14111
4,285
cpp
C++
IvyProjects/IvyEngine/dx/DxBuffer.cpp
endy/Ivy
23d5a61d34793c74527ef803bf3693df79291539
[ "MIT" ]
null
null
null
IvyProjects/IvyEngine/dx/DxBuffer.cpp
endy/Ivy
23d5a61d34793c74527ef803bf3693df79291539
[ "MIT" ]
null
null
null
IvyProjects/IvyEngine/dx/DxBuffer.cpp
endy/Ivy
23d5a61d34793c74527ef803bf3693df79291539
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////////////////////////// /// /// Ivy Engine /// /// Copyright 2010-2011, Brandon Light /// All rights reserved. /// /////////////////////////////////////////////////////////////////////////////////////////////////// #include "DxBuffer.h" #include <d3d11.h> /////////////////////////////////////////////////////////////////////////////////////////////////// /// DxBuffer::DxBuffer /////////////////////////////////////////////////////////////////////////////////////////////////// DxBuffer::DxBuffer() { } /////////////////////////////////////////////////////////////////////////////////////////////////// /// DxBuffer::~DxBuffer /////////////////////////////////////////////////////////////////////////////////////////////////// DxBuffer::~DxBuffer() { } /////////////////////////////////////////////////////////////////////////////////////////////////// /// DxBuffer::Create /////////////////////////////////////////////////////////////////////////////////////////////////// DxBuffer* DxBuffer::Create( ID3D11Device* pDevice, DxBufferCreateInfo* pCreateInfo) { DxBuffer* pNewBuffer = new DxBuffer(); if (pNewBuffer->Init(pDevice, pCreateInfo) == FALSE) { pNewBuffer->Destroy(); pNewBuffer = NULL; } return pNewBuffer; } /////////////////////////////////////////////////////////////////////////////////////////////////// /// DxBuffer::Destroy /////////////////////////////////////////////////////////////////////////////////////////////////// VOID DxBuffer::Destroy() { if (m_pDxBuffer) { m_pDxBuffer->Release(); } delete this; } /////////////////////////////////////////////////////////////////////////////////////////////////// /// DxBuffer::Init /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL DxBuffer::Init( ID3D11Device* pDevice, DxBufferCreateInfo* pCreateInfo) { D3D11_BUFFER_DESC bufferDesc; memset(&bufferDesc, 0, sizeof(D3D11_BUFFER_DESC)); bufferDesc.Usage = D3D11_USAGE_DYNAMIC; bufferDesc.ByteWidth = pCreateInfo->elemSizeBytes; bufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bufferDesc.MiscFlags = 0; if (pCreateInfo->flags.cpuWriteable) { bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; } D3D11_SUBRESOURCE_DATA bufferInitData; memset(&bufferInitData, 0, sizeof(D3D11_SUBRESOURCE_DATA)); bufferInitData.pSysMem = pCreateInfo->pInitialData; bufferInitData.SysMemPitch = pCreateInfo->initialDataPitch; bufferInitData.SysMemSlicePitch = pCreateInfo->initialDataSlicePitch; pDevice->CreateBuffer(&bufferDesc, &bufferInitData, &m_pDxBuffer); return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// /// DxBuffer::Map /////////////////////////////////////////////////////////////////////////////////////////////////// VOID* DxBuffer::Map( ID3D11DeviceContext* pContext) { D3D11_MAPPED_SUBRESOURCE mappedBuffer; pContext->Map(m_pDxBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedBuffer); return mappedBuffer.pData; } /////////////////////////////////////////////////////////////////////////////////////////////////// /// DxBuffer::Unmap /////////////////////////////////////////////////////////////////////////////////////////////////// VOID DxBuffer::Unmap( ID3D11DeviceContext* pContext) { pContext->Unmap(m_pDxBuffer, 0); } /////////////////////////////////////////////////////////////////////////////////////////////////// /// DxBuffer::BindVS /////////////////////////////////////////////////////////////////////////////////////////////////// VOID DxBuffer::BindVS( ID3D11DeviceContext* pContext, UINT slot) { pContext->VSSetConstantBuffers(slot, 1, &m_pDxBuffer); } /////////////////////////////////////////////////////////////////////////////////////////////////// /// DxBuffer::BindPS /////////////////////////////////////////////////////////////////////////////////////////////////// VOID DxBuffer::BindPS( ID3D11DeviceContext* pContext, UINT slot) { pContext->PSSetConstantBuffers(slot, 1, &m_pDxBuffer); }
32.462121
99
0.365228
endy
6c0244634110a1519c681b39070a184245cf2763
860
cpp
C++
src/GameOverState.cpp
Natman64/BearAttack
77292fd38b45f3f21fdf4833ae653818f9e1cf00
[ "CC0-1.0" ]
null
null
null
src/GameOverState.cpp
Natman64/BearAttack
77292fd38b45f3f21fdf4833ae653818f9e1cf00
[ "CC0-1.0" ]
null
null
null
src/GameOverState.cpp
Natman64/BearAttack
77292fd38b45f3f21fdf4833ae653818f9e1cf00
[ "CC0-1.0" ]
null
null
null
#include "GameOverState.h" #include "GameState.h" namespace bears { GameOverState::GameOverState(Game* game, bool win) : loaded(false), game(game), win(win) { if (win) { text = "Congratulations! You killed all of the children in the name of the LORD."; } else { text = "Game over!"; } } void GameOverState::Update(const unsigned int deltaMS, Input& input) { if (input.IsAnyKeyPressed()) { if (win) game->Quit(); else game->SetState(new GameState(game)); } } void GameOverState::Draw(Graphics& graphics) { if (!loaded) { loaded = true; graphics.RenderText(text); } graphics.DrawText(text, 40, 500); } }
20
94
0.495349
Natman64
6c02f4c6744bd49d0af1eca3640f0de7566766e8
6,513
cpp
C++
Final/TinyDatabase/main.cpp
breeswish/C_homework
c3eb54f9d9103ac71e9aedfe6bf387d6e6d699cc
[ "MIT" ]
null
null
null
Final/TinyDatabase/main.cpp
breeswish/C_homework
c3eb54f9d9103ac71e9aedfe6bf387d6e6d699cc
[ "MIT" ]
null
null
null
Final/TinyDatabase/main.cpp
breeswish/C_homework
c3eb54f9d9103ac71e9aedfe6bf387d6e6d699cc
[ "MIT" ]
null
null
null
// // main.cpp // 1352978 // // Created by Breezewish on 13-12-5. // Copyright (c) 2013年 Breezewish. All rights reserved. // #include "main.h" MyConsole console; SQL sql; /* entry */ int main(int argc, const char * argv[]) { // Attach handlers console.bind(database_handler_create_table, MyConsole::FLAG_CREATE_TABLE, "file", "Create table from file"); console.bind(database_handler_import, MyConsole::FLAG_IMPORT, "table file", "Import data to table"); console.bind(database_handler_select, MyConsole::FLAG_SELECT, "file", "Select data by file"); console.bind(database_handler_update, MyConsole::FLAG_UPDATE, "file", "Update data by file"); console.bind(database_handler_delete, MyConsole::FLAG_DELETE, "file", "Delete data by file"); console.bind(database_handler_interactive_mode, MyConsole::FLAG_INTERACTIVE, "", "Enter interactive mode"); console.bind(database_handler_quit, MyConsole::FLAG_QUIT, "", "Quit"); console.bind(database_handler_help, MyConsole::FLAG_HELP, "", "Show this screen"); // loop console.hello(APP_VERSION); while (console.read() != MyConsole::STATUS_EXIT); return 0; } /* -it */ int database_handler_interactive_mode(const std::vector<MyString>& params) { MyString line; char input[1024]; do { std::cout << "interactive> "; std::cin.getline(input, 1024); line = MyString(input); if (line != "exit") { try { auto result = sql.execute(line); std::cout << "Completed without errors in " << result.execute_time << "ms." << std::endl; std::cout << "Involved " << result.n << " rows (scanned " << result.scanned << " rows)." << std::endl; if (result.table != nullptr && result.table->rows.size() > 0) { result.print(std::cout); } } catch (MyString err) { std::cerr << "Error: " << err << std::endl; } } } while (line != "exit"); return MyConsole::STATUS_OK; } /* -c file */ int database_handler_create_table(const std::vector<MyString>& params) { try { if (params.size() != 1) { throw MyString("Expecting 1 parameter"); } auto result = sql.execute(read(params[0])); std::cout << "Completed without errors in " << result.execute_time << "ms." << std::endl; return MyConsole::STATUS_OK; } catch (MyString err) { std::cerr << "Error: " << err << std::endl; return MyConsole::STATUS_FAIL; } } /* -i table file */ int database_handler_import(const std::vector<MyString>& params) { try { if (params.size() != 2) { throw MyString("Expecting 2 parameters"); } char *fp = params[1].toCString(); auto result = sql.import(params[0], fp); delete[] fp; //TODO: resource not released here std::cout << "Completed without errors in " << result.execute_time << "ms." << std::endl; std::cout << "Imported " << result.n << " rows." << std::endl; return MyConsole::STATUS_OK; } catch (MyString err) { std::cerr << "Error: " << err << std::endl; return MyConsole::STATUS_FAIL; } } /* -s file */ int database_handler_select(const std::vector<MyString>& params) { try { if (params.size() != 1) { throw MyString("Expecting 1 parameter"); } static int execute_n; auto result = sql.execute(read(params[0])); MyString output = MyString(OUTPUT_PREFIX).concat("select_").concat(MyString(execute_n++)).concat(".txt"); std::cout << "Completed without errors in " << result.execute_time << "ms." << std::endl; std::cout << "Selected " << result.n << " rows (scanned " << result.scanned << " rows)." << std::endl; std::cout << "Data outputed to: " << output << std::endl; result.xport(output); return MyConsole::STATUS_OK; } catch (MyString err) { std::cerr << "Error: " << err << std::endl; return MyConsole::STATUS_FAIL; } } /* -u file */ int database_handler_update(const std::vector<MyString>& params) { try { if (params.size() != 1) { throw MyString("Expecting 1 parameter"); } static int execute_n; auto result = sql.execute(read(params[0])); MyString output = MyString(OUTPUT_PREFIX).concat("update_").concat(MyString(execute_n++)).concat(".txt"); std::cout << "Completed without errors in " << result.execute_time << "ms." << std::endl; std::cout << "Updated " << result.n << " rows (scanned " << result.scanned << " rows)." << std::endl; std::cout << "Data outputed to: " << output << std::endl; result.xport(output); return MyConsole::STATUS_OK; } catch (MyString err) { std::cerr << "Error: " << err << std::endl; return MyConsole::STATUS_FAIL; } } /* -d file */ int database_handler_delete(const std::vector<MyString>& params) { try { if (params.size() != 1) { throw MyString("Expecting 1 parameter"); } static int execute_n; auto result = sql.execute(read(params[0])); MyString output = MyString(OUTPUT_PREFIX).concat("delete_").concat(MyString(execute_n++)).concat(".txt"); std::cout << "Completed without errors in " << result.execute_time << "ms." << std::endl; std::cout << "Deleted " << result.n << " rows (scanned " << result.scanned << " rows)." << std::endl; std::cout << "Table data outputed to: " << output << std::endl; sql.xport(result.table->name, output); return MyConsole::STATUS_OK; } catch (MyString err) { std::cerr << "Error: " << err << std::endl; return MyConsole::STATUS_FAIL; } } /* -q */ int database_handler_quit(const std::vector<MyString>& params) { console << "bye" << std::endl; return MyConsole::STATUS_EXIT; } /* -h */ int database_handler_help(const std::vector<MyString>& params) { return console.help(); }
28.565789
118
0.550131
breeswish
6c05ae229383a9afdd34ddfa588d7993b795a4a6
60,615
cpp
C++
NE/HyperNEAT/cake_fixeddepth/cakepp.cpp
jal278/HyperNEAT
738277091ef21b2a635abf2cb7ab838e7a10b210
[ "BSD-3-Clause" ]
3
2019-12-06T19:02:27.000Z
2021-04-08T12:47:50.000Z
NE/HyperNEAT/cake_fixeddepth/cakepp.cpp
jal278/HyperNEAT
738277091ef21b2a635abf2cb7ab838e7a10b210
[ "BSD-3-Clause" ]
null
null
null
NE/HyperNEAT/cake_fixeddepth/cakepp.cpp
jal278/HyperNEAT
738277091ef21b2a635abf2cb7ab838e7a10b210
[ "BSD-3-Clause" ]
1
2019-02-28T13:48:01.000Z
2019-02-28T13:48:01.000Z
/* * cake - a checkers engine * * Copyright (C) 2000...2007 by Martin Fierz * * contact: checkers@fierz.ch */ #include "switches.h" #include <stdio.h> #include <stdlib.h> // malloc() #include <string.h> // memset() #include <time.h> #include <assert.h> #include <algorithm> using namespace std; //#include <conio.h> //#include <windows.h> // cake-specific includes - structs defines structures, consts defines constants, // xxx.h defines function prototypes for xxx.c #include "structs.h" #include "consts.h" #include "cakepp.h" #include "move_gen.h" #include "dblookup.h" #include "initcake.h" #include "cake_misc.h" #include "cake_eval.h" #ifndef _MSC_VER int max(int a,int b) { if(a>b) return a; else return b; } #endif //-------------------------------------------------------------------------------// // globals below here are shared - even with these, cake *should* be thread-safe // //-------------------------------------------------------------------------------// static int iscapture[MAXDEPTH]; // tells whether move at realdepth was a capture int hashmegabytes = 64; // default hashtable size in MB if no value in registry is found int dbmegabytes = 128; // default db cache size in MB if no value in registry is found int usethebook = BOOKALLKINDS; // default: use best moves if no value in the registry is found static HASHENTRY *hashtable; // pointer to the hashtable, is allocated at startup static HASHENTRY *book; // pointer to the book hashtable, is allocated at startup int hashsize = HASHSIZE; #ifdef SPA static SPA_ENTRY *spatable; #endif int maxNdb=0; // the largest number of stones which is still in the database static int cakeisinit = 0; // is set to 1 after cake is initialized, i.e. initcake has been called // history table array #ifdef MOHISTORY int32 history[32][32]; #endif // hashxors array. int32 hashxors[2][4][32]; // this is initialized to constant hashxors stored in the code. // bit tables for number of set bits in word static unsigned char bitsinword[65536]; static unsigned char bitsinbyte[256]; static unsigned char LSBarray[256]; static int norefresh; int bookentries = 0; // number of entries in book hashtable int bookmovenum = 0; // number of used entries in book #ifdef HEURISTICDBSAVE FILE *fp_9pc_black, *fp_9pc_white; FILE *fp_10pc_black, *fp_10pc_white; FILE *fp_11pc_black, *fp_11pc_white; FILE *fp_12pc_black, *fp_12pc_white; FILE *fp_9pc_blackK, *fp_9pc_whiteK; FILE *fp_10pc_blackK, *fp_10pc_whiteK; FILE *fp_11pc_blackK, *fp_11pc_whiteK; FILE *fp_12pc_blackK, *fp_12pc_whiteK; #endif #ifdef THREADSAFEHT CRITICAL_SECTION hash_access; // is locked if a thread is accessing the hashtable #endif #ifdef THREADSAFEDB CRITICAL_SECTION db_access; // is locked if a thread is accessing the database #endif /*----------------------------------------------------------------------------*/ /* */ /* initialization */ /* */ /*----------------------------------------------------------------------------*/ int initcake(char str[1024]) // initcake must be called before any calls to cake_getmove can be made. // it initializes the database and some constants, like the arrays for lastone // and bitsinword, plus some evaluation tables // str is the buffer it writes output to { char dirname[256]; FILE *fp; // create a new logfile / delete old logfile sprintf(str,"creating logfile"); // delete old logfile fp = fopen("cakelog.txt","w"); fclose(fp); strcpy(dirname,"./"); //GetCurrentDirectory(256, dirname); logtofile(dirname); // do some loads. first, the endgame database. #ifdef USEDB sprintf(str, "initializing database"); maxNdb = db_init(dbmegabytes,str); #endif // USEDB #ifdef BOOK // next, load the book sprintf(str,"loading book..."); book = loadbook(&bookentries, &bookmovenum); #endif // allocate hashtable sprintf(str,"allocating hashtable..."); printf("Allocating hashtable..."); hashtable = inithashtable(hashsize); printf("Done!\n"); // initialize xors initxors((int*)hashxors); // initialize bit-lookup-table initbitoperations(bitsinword, LSBarray); initeval(); #ifdef SPA // allocate memory for SPA initspa(); #endif #ifdef BOOKHT initbookht(); #endif #ifdef THREADSAFEHT InitializeCriticalSection(&hash_access); #endif #ifdef THREADSAFEDB InitializeCriticalSection(&db_access); #endif cakeisinit=1; return 1; } void resetsearchinfo(SEARCHINFO *s) { // resets the search info structure nearly completely, with the exception of // the pointer si.repcheck, to which we allocated memory during initialization - // we don't want to create a memory leak here. s->aborttime = 0; s->allscores = 0; s->bk = 0; s->bm = 0; s->cutoffs = 0; s->cutoffsatfirst = 0; s->dblookup = 0; s->dblookupfail = 0; s->dblookupsuccess = 0; s->Gbestindex = 0; s->hash.key = 0; s->hash.lock = 0; s->hashlookup = 0; s->hashlookupsuccess = 0; s->hashstores = 0; s->iidnegamax = 0; s->leaf = 0; s->leafdepth = 0; s->matcount.bk = 0; s->matcount.bm = 0; s->matcount.wk = 0; s->matcount.wm = 0; s->maxdepth = 0; s->maxtime = 0; s->negamax = 0; s->out = NULL; s->play = NULL; s->qsearch = 0; s->qsearchfail = 0; s->qsearchsuccess = 0; s->realdepth = 0; s->searchmode = 0; s->spalookups = 0; s->spasuccess = 0; s->start = 0; s->wk = 0; s->wm = 0; } int hashreallocate(int x) { // TODO: move to little-used functions file // reallocates the hashtable to x MB static int currenthashsize; HASHENTRY *pointer; int newsize; hashmegabytes = x; newsize = (hashmegabytes)*1024*1024/sizeof(HASHENTRY); // TODO: this must be coerced to a power of 2. luckily this is true // with sizeof(HASHENTRY) == 8 bytes, but if i ever change that it will // fail #ifdef WINMEM VirtualFree(hashtable, 0, MEM_RELEASE); pointer = VirtualAlloc(0, (newsize+HASHITER)*sizeof(HASHENTRY), MEM_COMMIT, PAGE_READWRITE); #else pointer = (HASHENTRY*)realloc(hashtable,(newsize+HASHITER)*sizeof(HASHENTRY)); #endif if(pointer != NULL) { hashsize = newsize; hashtable = pointer; } // TODO: do something if pointer == NULLbut what do we do when pointer == 0 here?? return 1; } int exitcake() { // deallocate memory //free(hashtable); db_exit(); //free(book); return 1; } #ifdef BOOKGEN int bookgen(OLDPOSITION *q, int color, int *numberofmoves, int values[MAXMOVES], int how, int depth, double searchtime) { // this function analyzes a position, and returns the number of possible moves (*numberofmoves) and // an array with the evaluation of each move. to speed up things, it only looks at "sensible" values, // i.e. if a move is 120 points worse than the best move, it stops there and doesn't determine exactly // how bad it is. // bookgen is only used by the book generator, not in testcake or checkerboard. int playnow=0; int d; int value=0,lastvalue=0,n,i,j, guess; CAKE_MOVE best,last, movelist[MAXMOVES]; CAKE_MOVE mlarray[MAXMOVES][MAXMOVES]; REPETITION dummy; char Lstr[1024],str[1024]; int bookfound=1,bookbestvalue=-MATE; int bookequals=0; int bookdepth=0; int bookindex=-1; int reset=1; int forcedmove = 0; // indicates if a move is forced, then cake++ will play at depth 1. char pvstring[1024]; char valuestring[256]; char beststring[1024]; int issearched[MAXMOVES]; int bestvalue; int index; int bestnewvalue; double t; int zeroevals = 0; // since this is an alternate entry point to cake.dll, we need to have a searchinfo structure ready here SEARCHINFO si; POSITION p; // initialize module if necessary if(!cakeisinit) initcake(str); // reset all counters, nodes, database lookups etc resetsearchinfo(&si); // allocate memory for repcheck array si.repcheck = (REPETITION*)malloc((MAXDEPTH+HISTORYOFFSET) * sizeof(REPETITION)); si.play = &playnow; si.out = str; si.aborttime = 40000*searchtime; si.maxtime = searchtime; si.searchmode = how; // change from old position struct to new one, because oplib is using the old one. p.bk = q->bk; p.bm = q->bm; p.wk = q->wk; p.wm = q->wm; p.color = color; // initialize material countmaterial(&p, &(si.matcount)); // initialize hash key absolutehashkey(&p, &(si.hash)); #ifdef MOHISTORY // reset history table memset(history,0,32*32*sizeof(int)); #endif printboard(&p); // clear the hashtable memset(hashtable,0,(hashsize+HASHITER)*sizeof(HASHENTRY)); norefresh=0; n = makecapturelist(&p, movelist, values, 0); if(!n) n = makemovelist(&si, &p, movelist, values, 0, 0); #ifdef REPCHECK // initialize history list: holds the last few positions of the current game si.repcheck[HISTORYOFFSET].hash = si.hash.key; si.repcheck[HISTORYOFFSET].irreversible = 1; dummy.hash = 0; dummy.irreversible = 1; for(i=0; i<HISTORYOFFSET; i++) // was i<historyoffset + 8 - doesn't make much sense to me now si.repcheck[i] = dummy; #endif si.start = clock(); guess = 0; // initialize mlarray: for(i = 0; i<n; i++) { togglemove((&p), movelist[i]); getorderedmovelist(&p, &mlarray[i][0]); togglemove((&p), movelist[i]); } for(d=1; d<MAXDEPTH; d+=2) { si.leaf = 0; si.leafdepth = 0; value = -MATE; printf("\n"); for(i=0;i<n;i++) issearched[i] = 0; bestnewvalue = -MATE; for(i=0;i<n;i++) { // get move with next best value to search, search moves from best to worst bestvalue = -MATE; for(j=0;j<n;j++) { if(issearched[j]) continue; if(values[j]>bestvalue) { index = j; bestvalue=values[j]; } } issearched[index]=1; togglemove((&p),movelist[index]); absolutehashkey((&p), &(si.hash)); countmaterial((&p), &(si.matcount)); #ifndef MTD values[index]=-windowsearch(p,FRAC*(d-1), 0 /*guess*/, &best); // set value for next search //guess=value[i]; #endif #ifdef MTD // MTD(F) search values[index] = -bookmtdf(&si, &p, &mlarray[index][0], -values[index],FRAC*(d-1),&best,-bestnewvalue); bestnewvalue = max(bestnewvalue,values[index]); #endif value = max(value, values[index]); togglemove((&p),movelist[index]); movetonotation(&p,&movelist[index],Lstr); printf("[%s %i] ",Lstr,values[index]); if(value == values[index]) sprintf(beststring,"%s",Lstr); } // zeroevals: count how many times we have seen 0, and stop the analysis early if we see too many. if(bestnewvalue == 0) zeroevals++; else zeroevals = 0; // generate output sprintf(Lstr,"%s",beststring); getpv(&si, &p, pvstring); // check for clock tick overflow // this should not happen - reset the start time t = clock(); if(t-si.start < 0) si.start = clock(); sprintf(valuestring, "value=%i", value); //searchinfotostring(str, d*FRAC, (t-si.start)/CLK_TCK, valuestring, pvstring, &si); //printf("\n%s",str); // iterative deepening loop break conditions: depend on search mode, 'how': // how=0: time mode if(d>1) { //if( si.searchmode == TIME_BASED && ((clock() - si.start)/CLK_TCK>(si.maxtime/2)) ) //break; // early break in case of many zeros and enough search depth //if( si.searchmode == TIME_BASED && ((clock()- si.start)/CLK_TCK>(si.maxtime/8)) && (zeroevals>4) && (d>22)) //{ //printf("\n* early break"); //break; //} if( si.searchmode == DEPTH_BASED && d>=depth) break; if(abs(value)>MATE-100) break; } lastvalue=value; // save the value for this iteration last=best; // save the best move on this iteration norefresh=1; } free(si.repcheck); return value; } int bookmtdf(SEARCHINFO *si, POSITION *p, CAKE_MOVE movelist[MAXMOVES], int firstguess,int depth, CAKE_MOVE *best, int bestvalue) { int g,lowerbound, upperbound,beta; double time; char Lstr1[1024],Lstr2[1024]; #define CUTOFF 120 upperbound=MATE; lowerbound=-MATE; g=firstguess; g=0; // a bit weird, firstguess should be better, but 0 seems to help while(lowerbound<upperbound) { if(g==lowerbound) beta=g+1; else beta=g; g = firstnegamax(si, p, movelist, depth, beta-1, beta, best); if(g<beta) { upperbound=g; sprintf(Lstr1,"value<%i",beta); } else { lowerbound=g; sprintf(Lstr1,"value>%i",beta-1); // termination if this node is much worse than the best so far: if(g - CUTOFF > bestvalue) return g; } time = 1;//( (clock()- si->start)/CLK_TCK); getpv(si, p, Lstr2); sprintf(si->out,"depth %i/%i/%.1f time %.2fs %s nodes %i %ikN/s %s", (depth/FRAC),si->maxdepth,(float)si->leafdepth/((float)si->leaf+0.001) , time, Lstr1, si->negamax, (int)((float)si->negamax/time/1000),Lstr2); #ifdef FULLLOG logtofile(si.out); #endif } logtofile(si->out); return g; } #endif //bookgen int analyze(POSITION *p, int color, int how, int depth, double searchtime, int *stat_eval) { // is a direct-access function for external analysis int playnow=0; int d; int value=0,lastvalue=0, guess; int dummy; CAKE_MOVE best,last; char Lstr[1024],str[1024]; int staticeval; // si for the analyze function so that it can reset HT after X runs static int analyzedpositions; double t; // analyze is an entry point to cake, so we need a searchinfo here SEARCHINFO si; CAKE_MOVE movelist[MAXMOVES]; d = getorderedmovelist(p, movelist); resetsearchinfo(&si); // allocate memory for repcheck array si.repcheck = (REPETITION*)malloc((MAXDEPTH+HISTORYOFFSET) * sizeof(REPETITION)); si.play = &playnow; si.out = str; analyzedpositions++; // set time limits si.aborttime = 40000*searchtime; si.maxtime = searchtime; si.searchmode = how; // initialize module if necessary if(!cakeisinit) initcake(str); #ifdef MOHISTORY // reset history table memset(history,0,32*32*sizeof(int)); #endif // clear the hashtable // no - not in this mode // or more precisely, nearly never. reason: after a long time, the hashtable is // filled with positions which have a ispvnode attribute. //if((analyzedpositions % 100000) == 0) // { printf("\nresetting hashtable"); memset(hashtable,0,(hashsize+HASHITER)*sizeof(HASHENTRY)); // } norefresh=0; // initialize hash key absolutehashkey(p, &(si.hash)); countmaterial(p, &(si.matcount)); si.start = clock(); guess=0; staticeval = evaluation(p,&(si.matcount),0,&dummy,0,maxNdb); // set return value of static eval. *stat_eval = staticeval; //printf("\nstatic eval %i",staticeval); for(d=1;d<MAXDEPTH;d+=2) { si.leaf = 0; si.leafdepth = 0; // choose which search algorithm to use: // non - windowed search // value = firstnegamax(FRAC*d, -MATE, MATE, &best); #ifndef MTD // windowed search value = windowsearch(&si, p, movelist, FRAC*d, guess, &best); // set value for next search guess=value; #endif #ifdef MTD // MTD(F) search value = mtdf(&si, p, movelist, guess, FRAC*d, &best); guess = value; #endif // generate output movetonotation(p,&best,Lstr); t = clock(); // iterative deepening loop break conditions: depend on search mode, 'how': // how=0: time mode; if(d>1) { //if( si.searchmode == TIME_BASED && ((clock()- si.start)/CLK_TCK>(si.maxtime/2)) ) //break; if( si.searchmode == DEPTH_BASED && d>=depth) break; if(abs(value)>MATE-100) break; } #ifdef PLAYNOW if( *(si.play)) { // the search has been aborted, either by the user or by cake++ because // abort time limit was exceeded // stop the search. don't use the best move & value because they might be rubbish best=last; movetonotation(p,&best,Lstr); value=lastvalue; sprintf(str,"interrupt: best %s value %i",Lstr,value); break; } #endif lastvalue=value; // save the value for this iteration last=best; // save the best move on this iteration norefresh=1; } free(si.repcheck); return value; } int cake_getmove(SEARCHINFO *si, POSITION *p, int how,double maximaltime, int depthtosearch, int32 maxnodes, char str[1024], int *playnow, int log, int info) { /*----------------------------------------------------------------------------*/ /* /* cake_getmove is the entry point to cake++ /* give a pointer to a position and you get the new position in /* this structure after cake++ has calculated. /* color is BLACK or WHITE and is the side to move. /* how is TIME_BASED for time-based search and DEPTH_BASED for depth-based search and /* NODE_BASED for node-based search /* maximaltime and depthtosearch and maxnodes are used for these three search modes. /* cake++ prints information in str /* if playnow is set to a value != 0 cake++ aborts the search. /* if (log&1) cake will write information into "log.txt" /* if(log&2) cake will also print the information to stdout. /* if reset!=0 cake++ will reset hashtables and repetition checklist /* reset==0 generally means that the normal course of the game was disturbed // info currently has uses for it's first 4 bits: // info&1 means reset // info&2 means exact time level // info&4 means increment time level // info&8 means allscore search /* /*----------------------------------------------------------------------------*/ int d; int value=0,lastvalue=0,n,i, guess; CAKE_MOVE best,last; REPETITION dummy; char Lstr[1024]; int bookfound=1,bookbestvalue=-MATE; CAKE_MOVE bookmove; int bookequals=0; unsigned int bookdepth=0; int bookindex=-1,booklookupvalue; int values[MAXMOVES]; int reset=(info&1); int forcedmove = 0; // indicates if a move is forced, then cake++ will play at depth 1. int zeroes = 0; // number of zero evals returned int winslosses = 0; double t; char pvstring[1024]; CAKE_MOVE movelist[MAXMOVES]; // we make a movelist here which we pass on, so that it can be ordered // and remain so during iterative deeping. // int dolearn; // initialize module if necessary if(!cakeisinit) initcake(str); resetsearchinfo(si); for(i=0;i<MAXDEPTH;i++) iscapture[i] = 0; *playnow = 0; si->play = playnow; si->out = str; si->searchmode = how; // set time limits si->maxtime = maximaltime; si->aborttime = 4*maximaltime; // if exact: if(info&2) si->aborttime = maximaltime; // allscores: if(info&8) si->allscores = 1; //printboardtofile(p,NULL); // print current directory to see whether CB is getting confused at some point. strcpy(pvstring,"./"); //GetCurrentDirectory(256, pvstring); // initialize material countmaterial(p, &(si->matcount)); #ifdef MOHISTORY // reset history table fflush(stdout); memset(history,0,32*32*sizeof(int)); #endif // clear the hashtable fflush(stdout); memset(hashtable,0,(hashsize+HASHITER)*sizeof(HASHENTRY)); // initialize hash key absolutehashkey(p, &(si->hash)); // if LEARNUSE is defined, we stuff learned positions in the hashtable #ifdef LEARNUSE stufflearnpositions(); #endif // what is this doing at all? norefresh=0; // what is this doing here? n = makecapturelist(p, movelist, values, 0); #ifdef REPCHECK // initialize history list: holds the last few positions of the current game si->repcheck[HISTORYOFFSET].hash = si->hash.key; si->repcheck[HISTORYOFFSET].irreversible = 1; dummy.hash = 0; dummy.irreversible = 1; if(reset==0) { for(i=0;i<HISTORYOFFSET-2;i++) si->repcheck[i] = si->repcheck[i+2]; } else { for(i=0;i<HISTORYOFFSET;i++) si->repcheck[i] = dummy; } //repetitiondraw = 0; #endif #ifdef TESTPERF for(i=0;i<MAXMOVES;i++) cutoffsat[i]=0; #endif // do a book lookup TODO: put this all in a small function if(usethebook) { bookfound=0; bookindex=0; if(booklookup(p,&booklookupvalue,0,&bookdepth,&bookindex,str)) { // booklookup was successful, it sets bookindex to the index of the move in movelist that it wants to play bookfound = 1; n = makecapturelist(p, movelist, values, 0); if(!n) n = makemovelist(si, p,movelist,values,0,0); // set best value bookmove = movelist[bookindex]; } // if the remaining depth is too small, we dont use the book move if(bookdepth < BOOKMINDEPTH) bookfound = 0; if(bookfound) { movetonotation(p,&bookmove,Lstr); //sprintf(str,"found position in book, value=%i, move is %s (depth %i)\n",booklookupvalue,Lstr,bookdepth); best=bookmove; value=0; } else { sprintf(str,"%X %X not found in book\n",si->hash.key,si->hash.lock); value=0; } logtofile(str); } else bookfound=0; absolutehashkey(p, &(si->hash)); countmaterial(p, &(si->matcount)); // check if the move on the board is forced - if yes, we don't waste time on it. forcedmove = isforced(p); #ifdef SOLVE solve(p, color); return 0; #endif // get a movelist which we pass around to mtdf() and firstnegamax() - do this here // because we want to keep it ordered during iterative deepening. n = getorderedmovelist(p, movelist); si->start = clock(); guess=0; if(!bookfound) { // check if this version is set to search to a fixed depth for(d=1; d<MAXDEPTH; d++) { si->leaf=0; si->leafdepth=0; #ifndef MTD // windowed search value = windowsearch(si, p, movelist, FRAC*d, guess, &best); // set value for next search guess=value; #endif #ifdef MTD // MTD(F) search if(si->allscores == 0) { value = mtdf(si, p, movelist, guess, FRAC*d, &best); guess = value; } else value = allscoresearch(si, p, movelist, FRAC*d, &best); #endif // count zero evals if(value == 0) zeroes++; else zeroes = 0; // count winning evals // do not count evals > 400 (db wins) as this would confuse cake when it's in a db win! if(abs(value)>=100 && abs(value)<400) winslosses++; else winslosses=0; // generate output movetonotation(p,&best,Lstr); getpv(si, p, pvstring); t = clock(); // iterative deepening loop break conditions: depend on search mode if(d>1) { //if( si->searchmode == TIME_BASED && ((clock()- si->start)/CLK_TCK>(si->maxtime/2)) ) //break; if( si->searchmode == DEPTH_BASED && d>=depthtosearch) break; if(si->searchmode == NODE_BASED && si->negamax>maxnodes) break; #ifdef IMMEDIATERETURNONFORCED // do not search if only one move is possible if(forcedmove) // this move was forced! { // set return value to 0 so no win/loss claims hamper engine matches*/ value=0; break; } #endif if(abs(value)>MATE-100) break; } #ifdef PLAYNOW if(*(si->play)) { // the search has been aborted, either by the user or by cake++ because // abort time limit was exceeded // stop the search. don't use the best move & value because they might be rubbish best=last; movetonotation(p,&best,Lstr); value=lastvalue; sprintf(str,"interrupt: best %s value %i",Lstr,value); break; } #endif lastvalue=value; // save the value for this iteration last=best; // save the best move on this iteration norefresh=1; } } #ifdef REPCHECK si->repcheck[HISTORYOFFSET-2].hash = si->hash.key; si->repcheck[HISTORYOFFSET-2].irreversible = 0; #endif if(*(si->play)) best = last; togglemove(p,best); absolutehashkey(p, &(si->hash)); #ifdef REPCHECK si->repcheck[HISTORYOFFSET-1].hash = si->hash.key; si->repcheck[HISTORYOFFSET-1].irreversible = (best.bm | best.wm); #endif // return value: WIN / LOSS / DRAW / UNKNOWN if(value > WINLEVEL) return WIN; if(value < -WINLEVEL) return LOSS; #ifdef USEDB if(isdbpos(p, &(si->matcount))) { value = dblookup(p, 0); if(value == DB_DRAW) return DRAW; } #endif // TODO: find repetition draws and return DRAW too. return UNKNOWN; } #ifdef USEDB int isdbpos(POSITION *p, MATERIALCOUNT *m) { if(m->bm + m->bk + m->wm + m->wk <= maxNdb && max(m->bm + m->bk, m->wm + m->wk) <= MAXPIECE) { if(testcapture(p)) return 0; p->color ^= CC; if(testcapture(p)) { p->color^=CC; return 0; } p->color ^= CC; return 1; } return 0; } #endif /*-------------------------------------------------------------------------- | | | driver routines for search: MTD(f) and windowsearch | | | --------------------------------------------------------------------------*/ int mtdf(SEARCHINFO *si, POSITION *p, CAKE_MOVE movelist[MAXMOVES], int firstguess,int depth, CAKE_MOVE *best) { // todo: test "correct return values", // also look if the best move is always the same as the last fail-high - // perhaps that's what mtdf should return: the fail-high move with the highest // value?! int g, lowerbound, upperbound, beta; double time; char Lstr1[1024]="",Lstr2[1024]=""; g = firstguess; /*g=0; */ /* strange - this seems to help?! */ upperbound = MATE; lowerbound = -MATE; while(lowerbound<upperbound) { if(g==lowerbound) beta=g+1; else beta=g; g = firstnegamax(si, p, movelist, depth, beta-1, beta, best); if(g<beta) { upperbound=g; //upperbound = beta-1; sprintf(Lstr1,"value<%i",beta); } else { lowerbound=g; //lowerbound = beta; sprintf(Lstr1,"value>%i",beta-1); } time = 1;//( (clock() - si->start)/CLK_TCK); getpv(si, p, Lstr2); searchinfotostring(si->out, depth, time, Lstr1, Lstr2, si); #ifdef FULLLOG sprintf(Lstr,"\n -> %s",si.out); logtofile(Lstr); #endif } // for testing: //g = lowerbound; sprintf(Lstr1,"value=%i",g); searchinfotostring(si->out, depth, time, Lstr1, Lstr2, si); logtofile(si->out); return g; } int windowsearch(SEARCHINFO *si, POSITION *p, CAKE_MOVE movelist[MAXMOVES], int depth, int guess, CAKE_MOVE *best) { int value; double time; char Lstr1[1024],Lstr2[1024]; //do a search with aspiration window value = firstnegamax(si, p, movelist, depth, guess-ASPIRATIONWINDOW, guess+ASPIRATIONWINDOW, best); if(value >= guess+ASPIRATIONWINDOW) { // print info in status bar and cakelog.txt sprintf(Lstr1,"value>%i",value-1); time = 1;//( (clock()- si->start)/CLK_TCK); getpv(si, p, Lstr2); searchinfotostring(si->out, depth, time, Lstr1, Lstr2, si); logtofile(si->out); value = firstnegamax(si, p, movelist, depth, guess, MATE, best); if(value <= guess) { // print info in status bar and cakelog.txt sprintf(Lstr1,"value<%i",value+1); time = 1;//( (clock()- si->start)/CLK_TCK); getpv(si, p, Lstr2); searchinfotostring(si->out, depth, time, Lstr1, Lstr2, si); logtofile(si->out); value = firstnegamax(si, p, movelist, depth, -MATE, MATE, best); } } if(value <= guess-ASPIRATIONWINDOW) { // print info in status bar and cakelog.txt sprintf(Lstr1,"value<%i",value+1); time = 1;//( (clock()- si->start)/CLK_TCK); getpv(si, p, Lstr2); searchinfotostring(si->out, depth, time, Lstr1, Lstr2, si); logtofile(si->out); value = firstnegamax(si, p, movelist, depth, -MATE, guess, best); if(value >= guess) { // print info in status bar and cakelog.txt sprintf(Lstr1,"value>%i",value-1); time = 1;//( (clock()- si->start)/CLK_TCK); getpv(si, p, Lstr2); searchinfotostring(si->out, depth, time, Lstr1, Lstr2, si); logtofile(si->out); value = firstnegamax(si, p, movelist, depth, -MATE, MATE, best); } } sprintf(Lstr1,"value=%i",value); time = 1;//( (clock()- si->start)/CLK_TCK); getpv(si, p, Lstr2); searchinfotostring(si->out, depth, time, Lstr1, Lstr2, si); logtofile(si->out); return value; } int allscoresearch(SEARCHINFO *si, POSITION *p, CAKE_MOVE movelist[MAXMOVES], int d, CAKE_MOVE *best) { int i, j, n; static int values[MAXMOVES]; int bestindex = 0; char str[256], tmpstr[256], movestr[256]; int Lkiller; int tmpvalue; CAKE_MOVE tmpmove; MATERIALCOUNT Lmatcount; HASH localhash; #ifdef PLAYNOW if(*(si->play)) return 0; #endif // get number of moves in movelist n = numberofmoves(movelist); // save old hashkey localhash = si->hash; // save old material balance Lmatcount = si->matcount; *best = movelist[0]; for(i=0;i<n;i++) { // domove togglemove(p,movelist[i]); countmaterial(p, &(si->matcount)); si->realdepth++; updatehashkey(&movelist[i], &(si->hash)); #ifdef REPCHECK si->repcheck[si->realdepth + HISTORYOFFSET].hash = si->hash.key; si->repcheck[si->realdepth + HISTORYOFFSET].irreversible = movelist[i].bm|movelist[i].wm; #endif /********************recursion********************/ values[i] = -negamax(si,p,d-FRAC,0, &Lkiller, &Lkiller, 0,0,0); /******************* end recursion ***************/ // undomove si->realdepth--; togglemove(p,movelist[i]); si->hash = localhash; si->matcount = Lmatcount; // create output string sprintf(str,"d%i ",d/FRAC); for(j=0;j<n;j++) { if(j<=i) { movetonotation(p, &movelist[j], movestr); sprintf(tmpstr, "%s: %i ", movestr, values[j]); strcat(str, tmpstr); } else { movetonotation(p, &movelist[j], movestr); sprintf(tmpstr, "%s:(%i) ", movestr, values[j]); strcat(str, tmpstr); } } sprintf(si->out,"%s", str); } logtofile(str); // now, order the list according to values for(j=0;j<n;j++) { for(i=0;i<n-1;i++) { if(values[i] < values[i+1]) { // swap tmpvalue = values[i]; values[i] = values[i+1]; values[i+1] = tmpvalue; tmpmove = movelist[i]; movelist[i] = movelist[i+1]; movelist[i+1] = tmpmove; } } } *best = movelist[0]; // last = *p; return 1; } int firstnegamax(SEARCHINFO *si, POSITION *p, CAKE_MOVE movelist[MAXMOVES], int d, int alpha, int beta, CAKE_MOVE *best) { /*-------------------------------------------------------------------------- | | | firstnegamax: first instance of negamax which returns a move | | | --------------------------------------------------------------------------*/ int i,value,swap=0,bestvalue=-MATE; static int n; static CAKE_MOVE ml2[MAXMOVES]; MATERIALCOUNT Lmatcount; int Lalpha=alpha; int forcefirst=0; int Lkiller=0; static POSITION last; CAKE_MOVE tmpmove; static int values[MAXMOVES]; /* holds the values of the respective moves - use to order */ int refnodes[MAXMOVES]; /* number of nodes searched to refute a move */ int statvalues[MAXMOVES]; int tmpnodes; int bestindex=0; HASH localhash; #ifdef PLAYNOW if(*(si->play)) return 0; #endif si->negamax++; // TODO: will static position last work here? and static movelist?? // probably i need to make a movelist in mtdf and send it to firstnegamax! for(i=0;i<MAXMOVES;i++) refnodes[i] = 0; // get number of moves in movelist n = numberofmoves(movelist); if(n==0) return -MATE+si->realdepth; //save old hashkey localhash = si->hash; // save old material balance Lmatcount = si->matcount; *best = movelist[0]; // For all moves do... for(i=0;i<n;i++) { togglemove(p,movelist[i]); countmaterial(p, &(si->matcount)); si->realdepth++; updatehashkey(&movelist[i], &(si->hash)); #ifdef REPCHECK si->repcheck[si->realdepth + HISTORYOFFSET].hash = si->hash.key; si->repcheck[si->realdepth + HISTORYOFFSET].irreversible = movelist[i].bm|movelist[i].wm; #endif tmpnodes = si->negamax; /********************recursion********************/ value = -negamax(si, p,d-FRAC,-beta, &Lkiller, &forcefirst, 0,0,0); /******************* end recursion ***************/ refnodes[i] = si->negamax-tmpnodes; values[i] = value; si->realdepth--; togglemove(p,movelist[i]); // restore the old hash key si->hash = localhash; // restore the old material balance si->matcount = Lmatcount; bestvalue = max(bestvalue,value); if(value >= beta) { *best = movelist[i];/*Lalpha=value;*/ swap=i; break; } if(value > Lalpha) { *best=movelist[i]; Lalpha=value; swap=i; } } /* save the position in the hashtable */ /* a bit complicated because we need to save best move as index */ // what if we don't set forcefirst here, i.e. set it to 0? n = makecapturelist(p, ml2, statvalues, 0); iscapture[si->realdepth] = n; if(n==0) n = makemovelist(si, p, ml2, statvalues, 0,0); // search the best move for(i=0; i<n; i++) { if(ml2[i].bm==best->bm && ml2[i].bk==best->bk && ml2[i].wm==best->wm && ml2[i].wk==best->wk) break; } bestindex = i; hashstore(si, p, bestvalue, alpha, d, best, bestindex); // set global Gbestindex for learn function si->Gbestindex = bestindex; // order movelist according to the number of nodes it took if(swap!=0) { tmpmove = movelist[swap]; tmpnodes = refnodes[swap]; for(i=swap;i>0;i--) { movelist[i] = movelist[i-1]; refnodes[i] = refnodes[i-1]; } movelist[0] = tmpmove; refnodes[0] = tmpnodes; } last=*p; return bestvalue; } int negamax(SEARCHINFO *si, POSITION *p, int d, int alpha, int *protokiller, int *bestmoveindex, int truncationdepth, int truncationdepth2, int iid) /*---------------------------------------------------------------------------- | | | negamax: the basic recursion routine of cake++ | | returns the negamax value of the current position | | sets protokiller to a compressed version of a move, | | if it's black's turn, protokiller = best.bm|best.bk | | *bestindex is set to the best move index, and is only | | used for IID: there, it returns the best index, and then | | we continue setting forcefirst to that index. | ----------------------------------------------------------------------------*/ { int value; int valuetype; int hashfound; int forcefirst = MAXMOVES-1; int n, localeval = MATE; int maxvalue = -MATE; int delta=0; #ifdef ETC int bestETCvalue; #endif int i,j; int index, bestmovevalue; int bestindex; int Lkiller=0; int stmcapture = 0; int sntmcapture = 0; #ifdef USEDB int dbresult; #endif int isdbpos = 0; int cl = 0; // conditional lookup - predefined as no. if CLDEPTH>d then it's 1. int ispvnode = 0; // is set to 1 in hashlookup if this position was part of a previous pv. #ifdef SAFE int safemovenum = 0; #endif #ifdef STOREEXACTDEPTH int originaldepth = d; #endif HASH localhash; POSITION q; // board for copy/make MATERIALCOUNT Lmatcount; CAKE_MOVE movelist[MAXMOVES]; int values[MAXMOVES]; /* * negamax does the following: * 1) abort search if time is elapsed * 2) return MATE value if one side has no material * 3) abort search if playnow is true * 4) return with evaluation if MAXDEPTH is reached (this practically never happens) * 5) hashlookup and return if successful * 6) IID if hashlookup unsuccessful and remaining depth sufficient * 7) check for repetition, return 0 if repetition * 8) get capture status of current position (stmcapture, sntmcapture) * 9) dblookup if no capture and stones < maxNdb * 10) extension and pruning decisions * 11) compute # of safe moves in position * 12) if depth small enough, no capture, and enough safe moves: return evaluation * 13) makemovelist & SINGLEEXTEND if n==1. * 14) ETClookup * 15) for all moves: domove, recursion, undomove * 16) hashstore * 17) return value */ si->negamax++; // check material: if(p->bm + p->bk == 0) return (p->color == BLACK) ? (-MATE+si->realdepth):(MATE-si->realdepth); if(p->wm + p->wk == 0) return (p->color == WHITE) ? (-MATE+si->realdepth):(MATE-si->realdepth); // return if calculation interrupt is requested #ifdef PLAYNOW if(*(si->play) != 0) return 0; #endif // stop search if maximal search depth is reached - this should basically never happen if(si->realdepth > MAXDEPTH) { si->leaf++; si->leafdepth += si->realdepth; return evaluation(p,&(si->matcount),alpha,&delta,0,maxNdb); } //------------------------------------------------// // search the current position in the hashtable // // only if there is still search depth left! // // should test this without d>0 !? // //------------------------------------------------// // TODO: check dblookup first! if(d >= 0 && !iid) { si->hashlookup++; hashfound = hashlookup(si, &value, &valuetype, d, &forcefirst, p->color, &ispvnode); if(hashfound) { si->hashlookupsuccess++; // return value 1: the position is in the hashtable and the depth // is sufficient. it's value and valuetype are used to shift bounds or even cutoff if(valuetype == LOWER) { //if(value >= beta) if(value > alpha) return value; } else //if(valuetype==UPPER) { if(value <= alpha) return value; } } } #ifdef REPCHECK // check for repetitions // TODO: maybe add repcheck[i-1].irreversible to the break statement. if(p->bk && p->wk) { for(i = si->realdepth + HISTORYOFFSET-2; i >= 0; i-=2) { // stop repetition search if move with a man is detected // this could be expanded with ....[i+-1] if(si->repcheck[i].irreversible) break; if(si->repcheck[i].hash == si->hash.key) return 0; } } #endif // get info on captures: can side to move or side not to move capture now? stmcapture = testcapture(p); // get info on capture by opponent (if there is a capture on the board, then the database // contains no valid data // TODO: do we ever use sntmcapture again? because if no, we could calculate this only // if we have a dblookup.... if(!stmcapture) { p->color ^= CC; sntmcapture = testcapture(p); p->color ^= CC; } if(stmcapture) n = makecapturelist(p,movelist,values,forcefirst); else n = 0; iscapture[si->realdepth] = n; //--------------------------------------------// // check for database use // // conditions: -> #of men < maxNdb // // -> no capture for either side // // else result is incorrect // //--------------------------------------------// #ifdef USEDB if(si->matcount.bm + si->matcount.bk + si->matcount.wm + si->matcount.wk <= maxNdb && max(si->matcount.bm + si->matcount.bk, si->matcount.wm + si->matcount.wk) <= MAXPIECE) { isdbpos = 1; if(!(stmcapture|sntmcapture)) { // this position can be looked up! si->dblookup++; if(d<CLDEPTH*FRAC && !ispvnode) cl=1; dbresult = dblookup(p,cl); // statistics if(dbresult == DB_NOT_LOOKED_UP) si->dblookupfail++; else if(dbresult != DB_UNKNOWN) { si->dblookupsuccess++; if(dbresult == DB_DRAW) return 0; if(dbresult == DB_WIN) { // TODO: we only really need dbwineval if the initial position // is a dbwin/dbloss. i.e. we could set value to + something big, and only if // value < localbeta we would get dbwineval. // TODO: try the following two lines once //if( lbeta < 400) // return 400; value = dbwineval(p, &(si->matcount)); //if(value >= localbeta) if(value > alpha) return value; // TODO check on this: does it ever happen? localeval = value; //printf("!"); } if(dbresult == DB_LOSS) { //if (alpha > -400) // return -400; p->color ^= CC; value = -dbwineval(p, &(si->matcount)); p->color ^= CC; if(value <= alpha) return value; localeval = value; } } } } #endif // USEDB //---------------------------------------------------// // check if we can return the evaluation // // depth must be <=0, and sidetomove has no capture // //---------------------------------------------------// if(d<=0 && !stmcapture) { // depth <= 0 and no capture, return value { // first, do some statistics: if(si->realdepth > si->maxdepth) si->maxdepth = si->realdepth; si->leaf++; si->leafdepth += si->realdepth; // localeval is initialized to MATE; if we already computed it, we don't have to again: if(localeval != MATE) value = localeval; else value = evaluation(p,&(si->matcount),alpha,&delta,0,maxNdb); return value; } } // we already made a capture list - if we have moves from there, we don't need to make a movelist. if(!n) n = makemovelist(si, p, movelist, values, forcefirst, *protokiller); if(n==0) // this can happen if side to move is stalemated. return -MATE+si->realdepth; // save old hashkey and old material balance localhash = si->hash; Lmatcount = si->matcount; // for all moves: domove, update hashkey&material, recursion, restore // material balance and hashkey, undomove, do alphabetatest // set best move in case of only fail-lows for(i=0;i<n;i++) { index=0; bestmovevalue=-1; for(j=0; j<n; j++) { if(values[j]>bestmovevalue) { bestmovevalue = values[j]; index = j; } } // TODO: think about swapping: put move at position n-1-i to position index // movelist[index] now holds the best move // set values[index] to -1, that means that this move will no longer be considered values[index]=-1; // domove domove(q,p,movelist[index]); q.color = p->color^CC; // if we had no hashmove, we have to set bestindex on the first iteration of this loop if(i == 0) bestindex = index; // inline material count if(p->color == BLACK) { if(stmcapture) { si->matcount.wm -= bitcount(movelist[index].wm); si->matcount.wk -= bitcount(movelist[index].wk); } if(movelist[index].bk && movelist[index].bm) {si->matcount.bk++; si->matcount.bm--;} } else { if(stmcapture) { si->matcount.bm -= bitcount(movelist[index].bm); si->matcount.bk -= bitcount(movelist[index].bk); } if(movelist[index].wk && movelist[index].wm) {si->matcount.wk++; si->matcount.wm--;} } //the above is equivalent to: countmaterial(); si->realdepth++; // update the hash key updatehashkey(&movelist[index], &(si->hash)); #ifdef REPCHECK si->repcheck[si->realdepth + HISTORYOFFSET].hash = si->hash.key; si->repcheck[si->realdepth + HISTORYOFFSET].irreversible = movelist[index].bm | movelist[index].wm; #endif /********************recursion********************/ value = -negamax(si, &q, d-FRAC,-(alpha+1),&Lkiller, &forcefirst, truncationdepth,truncationdepth2,0); /*************************************************/ //----------------undo the move------------------/ si->realdepth--; si->hash = localhash; si->matcount = Lmatcount; //----------------end undo move------------------/ // update best value so far maxvalue = max(value,maxvalue); // check cutoff if(maxvalue > alpha) { bestindex = index; if(i == 0) si->cutoffsatfirst++; si->cutoffs++; break; } } // end main recursive loop of forallmoves // set forcefirst in the calling negamax to the index of the best move- used for IID only *bestmoveindex = bestindex; // save the position in the hashtable // we can/should restore the depth with which negamax was originally entered // since this is the depth with which it would have been compared d = originaldepth; if(d>=0) hashstore(si, p, maxvalue, alpha, d, &movelist[bestindex], bestindex); // return best value return maxvalue; } int testcapture(POSITION *p) { // testcapture returns 1 if the side to move has a capture. int32 black,white,free,m; if (p->color == BLACK) { black = p->bm|p->bk; white = p->wm|p->wk; free = ~(black|white); m =((((black&LFJ2)<<4)&white)<<3); m|=((((black&LFJ1)<<3)&white)<<4); m|=((((black&RFJ1)<<4)&white)<<5); m|=((((black&RFJ2)<<5)&white)<<4); if(p->bk) { m|=((((p->bk&LBJ1)>>5)&white)>>4); m|=((((p->bk&LBJ2)>>4)&white)>>5); m|=((((p->bk&RBJ1)>>4)&white)>>3); m|=((((p->bk&RBJ2)>>3)&white)>>4); } if(m & free) return 1; return 0; } else { black = p->bm|p->bk; white = p->wm|p->wk; free = ~(black|white); m=((((white&LBJ1)>>5)&black)>>4); m|=((((white&LBJ2)>>4)&black)>>5); m|=((((white&RBJ1)>>4)&black)>>3); m|=((((white&RBJ2)>>3)&black)>>4); if(p->wk) { m|=((((p->wk&LFJ2)<<4)&black)<<3); m|=((((p->wk&LFJ1)<<3)&black)<<4); m|=((((p->wk&RFJ1)<<4)&black)<<5); m|=((((p->wk&RFJ2)<<5)&black)<<4); } if(m & free) return 1; return 0; } } void hashstore(SEARCHINFO *si, POSITION *p, int value, int alpha, int depth, CAKE_MOVE *best, int32 bestindex) { // store position in hashtable // based on the search window, alpha&beta, the value is assigned a valuetype // UPPER, LOWER or EXACT. the best move is stored in a reduced form // well, i no longer use EXACT, since i'm using MTD(f). int32 index,minindex; int mindepth=1000,iter=0; int from,to; si->hashstores++; //assert(alpha == beta-1); #ifdef MOHISTORY // update history table if(p->color==BLACK) { from = (best->bm|best->bk)&(p->bm|p->bk); /* bit set on square from */ to = (best->bm|best->bk)&(~(p->bm|p->bk)); history[LSB(from)][LSB(to)]++; } else { from = (best->wm|best->wk)&(p->wm|p->wk); /* bit set on square from */ to = (best->wm|best->wk)&(~(p->wm|p->wk)); history[LSB(from)][LSB(to)]++; } #endif index = si->hash.key & (hashsize-1); minindex = index; while(iter<HASHITER) { if(hashtable[index].lock == si->hash.lock || hashtable[index].lock==0) // vtune: use | instead of || /* found an index where we can write the entry */ { hashtable[index].lock = si->hash.lock; hashtable[index].depth =(int16) (depth); hashtable[index].best = bestindex; hashtable[index].color = (p->color>>1); hashtable[index].value =( sint16)value; /* determine valuetype */ if(value > alpha) hashtable[index].valuetype = LOWER; else hashtable[index].valuetype = UPPER; return; } else { /* have to overwrite */ if((int) hashtable[index].depth < mindepth) { minindex=index; mindepth=hashtable[index].depth; } } iter++; index++; } /* if we arrive here it means we have gone through all hashiter entries and all were occupied. in this case, we write the entry to minindex */ // if alwaysstore is not defined, and we have found no entry with equal or // lower importance, we don't overwrite it. #ifndef ALWAYSSTORE if(mindepth>(depth)) return; #endif hashtable[minindex].lock = si->hash.lock; hashtable[minindex].depth=depth; hashtable[minindex].best=bestindex; hashtable[minindex].color=(p->color>>1); hashtable[minindex].value=value; /* determine valuetype */ //if(value>=beta) if(value > alpha) hashtable[minindex].valuetype = LOWER; else hashtable[minindex].valuetype = UPPER; return; } int hashlookup(SEARCHINFO *si, int *value, int *valuetype, int depth, int *forcefirst, int color, int *ispvnode) { /* searches for a position in the hashtable. if the position is found and if (the stored depth is >= depth to search), hashlookup returns 1, indicating that the value and valuetype have useful information. else forcefirst is set to the best move found previously, and 0 returned if the position is not found at all, 0 is returned and forcefirst is left unchanged (at MAXMOVES-1). */ int32 index; int iter=0; index = si->hash.key & (hashsize-1); // expects that hashsize is a power of 2! // TODO: what is this "hashtable[index].lock" good for? while(iter<HASHITER && hashtable[index].lock) { if(hashtable[index].lock == si->hash.lock && ((int)hashtable[index].color==(color>>1))) { // we have found the position *ispvnode=hashtable[index].ispvnode; // move ordering *forcefirst=hashtable[index].best; // use value if depth in hashtable >= current depth if((int)hashtable[index].depth>=depth) { *value=hashtable[index].value; *valuetype=hashtable[index].valuetype; return 1; } } iter++; index++; } return 0; } int pvhashlookup(SEARCHINFO *si, int *value, int *valuetype, int depth, int32 *forcefirst, int color, int *ispvnode) { // pvhashlookup is like hashlookup, only with the exception that it marks the entry // in the hashtable as being part of the PV int32 index; int iter=0; index = si->hash.key & (hashsize-1); #ifdef THREADSAFEHT EnterCriticalSection(&hash_access); #endif while(iter<HASHITER && hashtable[index].lock) // vtune: use & instead { if(hashtable[index].lock == si->hash.lock && ((int)hashtable[index].color==(color>>1))) { // here's the only difference to the normal hashlookup! hashtable[index].ispvnode=1; /* move ordering */ *forcefirst=hashtable[index].best; /* use value if depth in hashtable >= current depth)*/ if((int)hashtable[index].depth>=depth) { *value=hashtable[index].value; *valuetype=hashtable[index].valuetype; #ifdef THREADSAFEHT LeaveCriticalSection(&hash_access); #endif return 1; } } iter++; index++; } #ifdef THREADSAFEHT LeaveCriticalSection(&hash_access); #endif return 0; } void getpv(SEARCHINFO *si, POSITION *p, char *str) { //---------------------------------------------------------------------- // retrieves the principal variation from the hashtable: | // looks up the position, finds the hashtable move, plays it, looks | // up the position again etc. | // color is the side to move, the whole PV gets written in *str | // getpv also marks pv nodes in the hashtable, so they won't be pruned! | //---------------------------------------------------------------------- CAKE_MOVE movelist[MAXMOVES]; int32 forcefirst; int dummy=0; int i,n; char Lstr[1024]; POSITION Lp; int values[MAXMOVES]; // int staticeval; int capture; //return; Lp=*p; absolutehashkey(&Lp, &(si->hash)); sprintf(str,"pv "); for(i=0;i<MAXDEPTH;i++) { forcefirst=100; // pvhashlookup also stores the fact that these nodes are pv nodes // in the hashtable pvhashlookup(si, &dummy,&dummy,0, &forcefirst,Lp.color,&dummy); if(forcefirst==100) { break; } n = makecapturelist(&Lp,movelist,values,forcefirst); if(n) capture = 1; else capture = 0; if(!n) n = makemovelist(si, &Lp, movelist, values, forcefirst, 0); if(!n) { absolutehashkey(p,&(si->hash)); return; } if(i<MAXPV) { #ifdef FULLLOG staticeval = evaluation(&Lp,&(si->matcount),0,&dummy,0,maxNdb); if(capture) sprintf(Lstr,"[-]",staticeval); else sprintf(Lstr,"[%i]",staticeval); strcat(str,Lstr); #endif // FULLLOG movetonotation(&Lp,&movelist[forcefirst],Lstr); strcat(str,Lstr); strcat(str," "); } togglemove((&Lp),movelist[forcefirst]); countmaterial(&Lp, &(si->matcount)); absolutehashkey(&Lp,&(si->hash)); } absolutehashkey(p,&(si->hash)); countmaterial(p, &(si->matcount)); return; } /* check for mobile black men, however, not all - only those on rows 3 or more */ /* how to use this stuff: like this! */ /*tmp=p->bm & 0xFFFFF000; while(tmp) //while black men { m= (tmp & (tmp-1))^tmp; // m is the least significant bit of tmp tmp = tmp&(tmp-1); // and we peel it away. // determine the white attack board without this man on: free = ~(p->bk|(p->bm^m)|p->wk|p->wm); wattack=backwardjump((p->wk|p->wm), free) | forwardjump(p->wk, free); // move this black man forward until he's on the last row, // look if there is a way for it to get there mobile = 20; while (m) { m=forward(m) & (~(p->wk | p->wm)) & (~wattack); if(m&0xF0000000) { mobileblackmen+=mobile; break; } mobile-=4; } } // only check for rows 2-6 */ /* table-lookup bitcount */ int bitcount(int32 n) // vtune: make this inlined maybe as a macro // returns the number of bits set in the 32-bit integer n { return (bitsinword[n&0x0000FFFF]+bitsinword[(n>>16)&0x0000FFFF]); } int LSB(int32 x) { //----------------------------------------------------------------------------------------------------- // returns the position of the least significant bit in a 32-bit word x // or -1 if not found, if x=0. // LSB uses "intrinsics" for an efficient implementation //----------------------------------------------------------------------------------------------------- /* if(_BitScanForward(&returnvalue,x)) return returnvalue; else return -1; */ //old, non-intrinsic code if(x&0x000000FF) return(LSBarray[x&0x000000FF]); if(x&0x0000FF00) return(LSBarray[(x>>8)&0x000000FF]+8); if(x&0x00FF0000) return(LSBarray[(x>>16)&0x000000FF]+16); if(x&0xFF000000) return(LSBarray[(x>>24)&0x000000FF]+24); return -1; } void updatehashkey(CAKE_MOVE *m, HASH *h) { // given a move m, updatehashkey updates the HASH structure h int32 x,y; x=m->bm; while(x) { y=LSB(x); h->key ^=hashxors[0][0][y]; h->lock^=hashxors[1][0][y]; x&=(x-1); } x=m->bk; while(x) { y=LSB(x); h->key ^=hashxors[0][1][y]; h->lock^=hashxors[1][1][y]; x&=(x-1); } x=m->wm; while(x) { y=LSB(x); h->key ^=hashxors[0][2][y]; h->lock^=hashxors[1][2][y]; x&=(x-1); } x=m->wk; while(x) { y=LSB(x); h->key ^=hashxors[0][3][y]; h->lock^=hashxors[1][3][y]; x&=(x-1); } } void absolutehashkey(POSITION *p, HASH *hash) { /* absolutehashkey calculates the hashkey completely. slower than using updatehashkey, but useful sometimes */ int32 x; hash->lock=0; hash->key=0; x=p->bm; while(x) { hash->key ^=hashxors[0][0][LSB(x)]; hash->lock^=hashxors[1][0][LSB(x)]; x&=(x-1); } x=p->bk; while(x) { hash->key ^=hashxors[0][1][LSB(x)]; hash->lock^=hashxors[1][1][LSB(x)]; x&=(x-1); } x=p->wm; while(x) { hash->key ^=hashxors[0][2][LSB(x)]; hash->lock^=hashxors[1][2][LSB(x)]; x&=(x-1); } x=p->wk; while(x) { hash->key ^=hashxors[0][3][LSB(x)]; hash->lock^=hashxors[1][3][LSB(x)]; x&=(x-1); } } void countmaterial(POSITION *p, MATERIALCOUNT *m) { // TODO: make a MATERIALCOUNT structure and pass that as parameter. /* countmaterial initializes the globals bm, bk, wm and wk, which hold the number of black men, kings, white men and white kings respectively. during the search these globals are updated incrementally */ m->bm = bitcount(p->bm); m->bk = bitcount(p->bk); m->wm = bitcount(p->wm); m->wk = bitcount(p->wk); } // put stuff like this into something like string.c // TODO: put this into book.c int booklookup(POSITION *p, int *value, int depth, int32 *remainingdepth, int *best, char str[256]) { /* searches for a position in the book hashtable. */ int32 index; int iter=0; int bookmoves; // todo: change this to bookhashentry! HASHENTRY *pointer; int bucketsize; int size; int bookfound = 0; int i,j,n; int bookcolor; int tmpvalue; CAKE_MOVE tmpmove,bestmove; int dummy[MAXMOVES], values[MAXMOVES],indices[MAXMOVES]; int depths[MAXMOVES]; CAKE_MOVE ml[MAXMOVES]; char Lstr[1024], Lstr2[1024]; HASH hash; SEARCHINFO s; resetsearchinfo(&s); bucketsize = BUCKETSIZEBOOK; pointer = book; size = bookentries; if(pointer == NULL) return 0; // now, look up current position absolutehashkey(p,&hash); index = hash.key % size; // harmonize colors between cake and book bookcolor = p->color; if(p->color==2) bookcolor=0; while(iter<bucketsize) { if(pointer[index].lock == hash.lock && ((int)pointer[index].color==bookcolor)) // use & { /* we have found the position */ *remainingdepth = pointer[index].depth; *value = pointer[index].value; *best = pointer[index].best; bookfound = 1; } iter++; index++; index %= size; if(bookfound) break; } bool gotValue=false; if(bookfound) { // search all successors in book n = makecapturelist(p, ml, dummy, 0); if(!n) n = makemovelist(&s, p, ml, dummy, 0,0); for(i=0;i<MAXMOVES;i++) { values[i]=-MATE; indices[i]=i; } bestmove = ml[*best]; // harmonize colors for book and cake bookcolor = (p->color^CC); if(bookcolor == 2) bookcolor=0; // for all moves look up successor position in book for(i=0;i<n;i++) { togglemove(p,ml[i]); absolutehashkey(p, &hash); index = hash.key % size; iter = 0; depths[i] = 0; values[i]=-MATE; while(iter<bucketsize) { if(pointer[index].lock == hash.lock && ((int)pointer[index].color==bookcolor)) { // found position in book depths[i] = pointer[index].depth+1; values[i] = -pointer[index].value; gotValue=true; } iter++; index++; index%=size; } togglemove(p,ml[i]); } } // print book moves. check if we have successors: // order moves so we can print them in status line if(bookfound && gotValue) { sprintf(str,"book "); for(i=0;i<n;i++) { for(j=0;j<n-1;j++) { if(100*values[j]+depths[j]<100*values[j+1]+depths[j+1]) { tmpvalue = values[j]; tmpmove = ml[j]; values[j] = values[j+1]; values[j+1] = tmpvalue; ml[j] = ml[j+1]; ml[j+1] = tmpmove; tmpvalue = depths[j]; depths[j] = depths[j+1]; depths[j+1] = tmpvalue; tmpvalue = indices[j]; indices[j] = indices[j+1]; indices[j+1] = tmpvalue; } } } // count number of available book moves and put in variabe bookmoves for(i=0;i<n;i++) { if(values[i] != -MATE) bookmoves = i; } bookmoves++; // create ouput string with all moves, values, depths ordered by value for(i=0;i<n;i++) { if(values[i]==-MATE) continue; movetonotation(p, &ml[i], Lstr); sprintf(Lstr2, " v%i d%i ", values[i], depths[i]); strcat(str,Lstr); strcat(str,Lstr2); } // now, select a move according to value of usethebook // if we have more than one available bookmove if(usethebook < BOOKBEST && bookmoves >1) { bookmoves = 0; if(usethebook == BOOKGOOD) { // select any move equal to the best in value for(i=1;i<n;i++) { if(values[i]==values[0]) bookmoves = i; } bookmoves++; } if(usethebook == BOOKALLKINDS) { // select any move that is > -30 in value, and within // 10 points of the best move for(i=1;i<n;i++) { if(values[i]>values[0]-10 && values[i]>-30) bookmoves = i; } bookmoves++; } // we have bookmoves equivalent book moves. // pick one at random if(bookmoves !=0) { //srand( (unsigned)time( NULL ) ); i = rand() % bookmoves; *remainingdepth = depths[i]; *value = values[i]; *best = indices[i]; //sprintf(Lstr," #%i/%i %i",i,bookmoves,values[i]); //strcat(Lstr,str); //sprintf(str,"%s",Lstr); } } } else if(bookfound) { // last book move movetonotation(p,&bestmove,Lstr); sprintf(str,"book move: %s v %i d %i", Lstr,*value, *remainingdepth); } return bookfound; }
25.151452
174
0.600115
jal278
6c0635c6bc402d6dddf27a65f28c4bcfcbe2d214
1,840
cpp
C++
School C++/LinkListTester/linklisttester.cpp
holtsoftware/potential-octo-wallhack
8e2165f0371522f42cb117ba83f8aea5c2a1b582
[ "Apache-2.0" ]
null
null
null
School C++/LinkListTester/linklisttester.cpp
holtsoftware/potential-octo-wallhack
8e2165f0371522f42cb117ba83f8aea5c2a1b582
[ "Apache-2.0" ]
null
null
null
School C++/LinkListTester/linklisttester.cpp
holtsoftware/potential-octo-wallhack
8e2165f0371522f42cb117ba83f8aea5c2a1b582
[ "Apache-2.0" ]
null
null
null
#include <lvector.h> #include <stdlib.h> #include <iostream.h> void main() { // char non; int i; lvector<double> testlist(2); testlist[0]=1; testlist[1]=2; cout<<"The lenght before resizeing "<<testlist.length()<<endl; testlist.resize(5); cout<<"The length of mylenght is "<<testlist.length()<<endl <<"Calculated length is "<<testlist.calcLength()<<endl; testlist[2]=3; testlist[3]=4; testlist[4]=5; cout<<"The values of test list are "; for(i=0;i<testlist.length();i++) { cout<<testlist[i]<<" "; } testlist.resize(3); cout<<endl<<"The length of mylenght is "<<testlist.length()<<endl <<"Calculated length is "<<testlist.calcLength()<<endl; cout<<"The values of test list are "; for(i=0;i<testlist.length();i++) { cout<<testlist[i]<<" "; } cout<<endl; lvector<double> testlist2=testlist; cout<<"After the use of the copy constructor the new link list has:"<<endl; for(i=0;i<testlist2.length();i++) { cout<<testlist2[i]<<" "; } cout<<endl<<"The Calculated lenght is: "<<testlist2.calcLength(); testlist2.resize(32); cout<<endl<<endl<<"After resizeing testlist2 to 32 the lenght is: "<<testlist2.length()<<endl <<"The Calculated length is: "<<testlist2.calcLength()<<endl<<endl; testlist2=testlist; cout<<"After seting testlist2 to testlist the lenght of testlist2 is: "<<testlist2.length() <<endl<<"The Calculated lenght is: "<<testlist2.calcLength()<<endl <<"And the elements of testlist2 are: "; for(i=0;i<testlist2.length();i++) { cout<<testlist2[i]<<" "; } cout<<endl; lvector<double> Testlist(5,6.995); cout<<"After creating Testlist the length is: "<<Testlist.length()<<endl <<"The Calculated length is: "<<Testlist.calcLength()<<endl <<"The Elements of Testlist are: "; for(i=0;i<Testlist.length();i++) { cout<<Testlist[i]<<" "; } cout<<endl; //cin>>non; }
26.285714
94
0.661413
holtsoftware
6c06c0cb47c2ff54d9be40cda36fe7defbdd079c
3,862
inl
C++
TAO/tao/CSD_Framework/CSD_Strategy_Base.inl
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tao/CSD_Framework/CSD_Strategy_Base.inl
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tao/CSD_Framework/CSD_Strategy_Base.inl
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// -*- C++ -*- // // $Id: CSD_Strategy_Base.inl 96992 2013-04-11 18:07:48Z huangh $ #include "tao/debug.h" TAO_BEGIN_VERSIONED_NAMESPACE_DECL ACE_INLINE TAO::CSD::Strategy_Base::Strategy_Base() : poa_activated_(false) { } ACE_INLINE void TAO::CSD::Strategy_Base::dispatch_request (TAO_ServerRequest& server_request, TAO::Portable_Server::Servant_Upcall& upcall) { DispatchResult result; if (server_request.collocated()) { result = this->dispatch_collocated_request_i(server_request, upcall.user_id(), this->poa_.in(), server_request.operation(), upcall.servant()); } else { result = this->dispatch_remote_request_i(server_request, upcall.user_id(), this->poa_.in(), server_request.operation(), upcall.servant()); } switch (result) { case DISPATCH_HANDLED: // Do nothing. Everything has been handled. break; case DISPATCH_REJECTED: if (server_request.collocated ()) { CORBA::NO_IMPLEMENT ex; ex._raise (); } else { // Raise an appropriate SystemException if the request is expecting // a reply. if (!server_request.sync_with_server() && server_request.response_expected() && !server_request.deferred_reply()) { CORBA::NO_IMPLEMENT ex; server_request.tao_send_reply_exception(ex); } } break; case DISPATCH_DEFERRED: // Perform the "default" dispatching strategy logic for this request // right now, using the current thread. upcall.servant()->_dispatch(server_request, &upcall); break; default: if (TAO_debug_level > 0) TAOLIB_ERROR((LM_ERROR, ACE_TEXT("(%P|%t) Unknown result (%d) from call to ") ACE_TEXT("dispatch_remote_request_i().\n"), result)); // Since we do not know what to do here, just do the minimum, which // treats this case just like the DISPATCH_HANDLED case, for better // or worse. Hitting this default case means a coding error. break; } } ACE_INLINE bool TAO::CSD::Strategy_Base::poa_activated_event(TAO_ORB_Core& orb_core) { // Notify the subclass of the event, saving the result. this->poa_activated_ = this->poa_activated_event_i(orb_core); // Return the result return this->poa_activated_; } ACE_INLINE void TAO::CSD::Strategy_Base::poa_deactivated_event() { if (this->poa_activated_) { this->poa_activated_ = false; // Notify the subclass of the event. this->poa_deactivated_event_i(); // Reset the poa to nil to decrement the reference count. // This will break the circular dependency of the deletion // of the CSD POA. this->poa_ = 0; } } ACE_INLINE void TAO::CSD::Strategy_Base::servant_activated_event (PortableServer::Servant servant, const PortableServer::ObjectId& oid) { this->servant_activated_event_i(servant, oid); } ACE_INLINE void TAO::CSD::Strategy_Base::servant_deactivated_event (PortableServer::Servant servant, const PortableServer::ObjectId& oid) { this->servant_deactivated_event_i(servant, oid); } TAO_END_VERSIONED_NAMESPACE_DECL
29.037594
79
0.555671
cflowe
6c07fd18e59c76360d02d84cfc137373b53d50fb
3,128
hh
C++
modules/cadac/vehicle.hh
mlouielu/mazu-sim
fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225
[ "BSD-3-Clause" ]
1
2020-03-26T07:09:54.000Z
2020-03-26T07:09:54.000Z
modules/cadac/vehicle.hh
mlouielu/mazu-sim
fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225
[ "BSD-3-Clause" ]
null
null
null
modules/cadac/vehicle.hh
mlouielu/mazu-sim
fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225
[ "BSD-3-Clause" ]
null
null
null
#ifndef __VEHICLE_HH__ #define __VEHICLE_HH__ #include <armadillo> #include <cstdio> #include <cstdlib> #include <map> #include <string> #include <vector> #include "aux.hh" #include "cadac_constants.hh" #include "component.hh" #include "vehicle_var.hh" /********************************* TRICK HEADER ******************************* PURPOSE: (Simulation module abstraction class and vehicle class) LIBRARY DEPENDENCY: ((../src/Vehicle.cpp)) PROGRAMMERS: (((Chun-Hsu Lai) () () () )) *******************************************************************************/ class Vehicle { protected: char Name[32]; int module_num; public: Vehicle(){}; ~Vehicle(){}; void set_name(char *in) { strcpy(Name, in); } char *get_name() { return Name; } }; class LaunchVehicle : public Vehicle { public: LaunchVehicle(double step_in); ~LaunchVehicle(){}; /* Set Aerodynamics variables */ void set_refa(double in); void set_refd(double in); void set_XCP(double in); void set_reference_point(double rp); void set_liftoff(int in); void load_angle(double yaw, double roll, double pitch); void load_angular_velocity(double ppx_in, double qqx_in, double rrx_in); void load_location(double lonx_in, double latx_in, double alt_in); void load_geodetic_velocity(double alpha0x, double beta0x, double dvbe); /* Set stage variables */ void Allocate_stage(unsigned int stage_num); void set_stage_var(double isp, double fmass_init, double vmass_init, double aexit_in, double fuel_flow_rate_in, double xcg0, double xcg1, double moi_roll0, double moi_roll1, double moi_pitch0, double moi_pitch1, double moi_yaw0, double moi_yaw1, unsigned int num_stage); void Allocate_RCS(int num, std::vector<RCS_Thruster *> &RT_list); void Allocate_ENG(int NumEng, std::vector<ENG *> &Eng_list_In); void set_payload_mass(double in); void set_faring_mass(double in); void set_stage_1(); void set_stage_2(); void set_stage_3(); void set_faring_sep(); void engine_ignition(); void set_no_thrust(); void set_mtvc(enum TVC_TYPE); void set_S1_TVC(); void set_S2_TVC(); void set_S3_TVC(); Aerodynamics_var *Aero; EarthEnvironment_var *Env; DM_var *DM; Prop_var *Prop; ACT_var *ACT; Sensor_var *Sensor; std::vector<STAGE_VAR *> Stage_var_list; std::vector<struct ENG *> Eng_list; std::vector<RCS_Thruster *> Thruster_list; std::vector<ENG *> S1_Eng_list; std::vector<ENG *> S2_Eng_list; std::vector<ENG *> S3_Eng_list; double dt; }; class FH_module { public: FH_module(){}; ~FH_module(){}; virtual void algorithm(LaunchVehicle *VehicleIn) = 0; virtual void init(LaunchVehicle *VehicleIn) = 0; protected: // Data_exchang *data_exchang; }; // class Vehicle_list { // private: // int howmany; // Vehicle **vehicle_ptr; // public: // Vehicle_list(){}; // ~Vehicle_list(){}; // void Add_vehicle(Vehicle *ptr); // }; #endif // __VEHICLE_HH__
27.438596
80
0.636189
mlouielu
6c09dc1bf052e904475ee699ef6138caf8ee3a64
3,985
cpp
C++
Old/m4a_Plugin/m4aInfoManager.cpp
Harteex/Tuniac
dac98a68c1b801b7fc82874aad16cc8adcabb606
[ "BSD-3-Clause" ]
3
2022-01-05T08:47:51.000Z
2022-01-06T12:42:18.000Z
Old/m4a_Plugin/m4aInfoManager.cpp
Harteex/Tuniac
dac98a68c1b801b7fc82874aad16cc8adcabb606
[ "BSD-3-Clause" ]
null
null
null
Old/m4a_Plugin/m4aInfoManager.cpp
Harteex/Tuniac
dac98a68c1b801b7fc82874aad16cc8adcabb606
[ "BSD-3-Clause" ]
1
2022-01-06T16:12:58.000Z
2022-01-06T16:12:58.000Z
#include "stdafx.h" #include "m4ainfomanager.h" #include "mp4ff.h" #include "utils.h" static int GetAACTrack(mp4ff_t *infile) { /* find AAC track */ int i, rc; int numTracks = mp4ff_total_tracks(infile); for (i = 0; i < numTracks; i++) { unsigned char *buff = NULL; int buff_size = 0; mp4AudioSpecificConfig mp4ASC; mp4ff_get_decoder_config(infile, i, &buff, (unsigned int *)&buff_size); if (buff) { rc = NeAACDecAudioSpecificConfig(buff, buff_size, &mp4ASC); free(buff); if (rc < 0) continue; return i; } } /* can't decode this */ return -1; } static uint32_t read_callback(void *user_data, void *buffer, uint32_t length) { return fread(buffer, 1, length, (FILE*)user_data); } static uint32_t seek_callback(void *user_data, uint64_t position) { return fseek((FILE*)user_data, position, SEEK_SET); } static uint32_t write_callback(void *user_data, void *buffer, uint32_t length) { return fwrite(buffer, 1, length, (FILE*)user_data); } static uint32_t truncate_callback(void *user_data) { chsize(fileno((FILE*)user_data), ftell((FILE*)user_data)); return 1; } Cm4aInfoManager::Cm4aInfoManager(void) { } Cm4aInfoManager::~Cm4aInfoManager(void) { } void Cm4aInfoManager::Destroy(void) { delete this; } unsigned long Cm4aInfoManager::GetNumExtensions(void) { return 2; } LPTSTR Cm4aInfoManager::SupportedExtension(unsigned long ulExtentionNum) { static LPTSTR exts[] = { TEXT(".m4a"), TEXT(".mp4") }; return exts[ulExtentionNum]; } bool Cm4aInfoManager::CanHandle(LPTSTR szSource) { if(PathIsURL(szSource)) return(false); for(unsigned int x=0; x<GetNumExtensions(); x++) { if(!StrCmpI(SupportedExtension(x), PathFindExtension(szSource))) { return(true); } } return(false); } bool Cm4aInfoManager::GetInfo(LibraryEntry * libEnt) { char *pVal = NULL; FILE *mp4File; mp4ff_callback_t mp4cb = {0}; mp4ff_t *file; mp4File = _wfopen(libEnt->szURL, TEXT("rbS")); mp4cb.read = read_callback; mp4cb.seek = seek_callback; mp4cb.write = write_callback; mp4cb.truncate = truncate_callback; mp4cb.user_data = mp4File; // put info extraction here! file = mp4ff_open_read(&mp4cb); if (file == NULL) return false; if(mp4ff_meta_get_artist(file, &pVal)) { MultiByteToWideChar(CP_UTF8, 0, pVal, strlen(pVal), libEnt->szArtist, 128); } if(mp4ff_meta_get_title(file, &pVal)) { MultiByteToWideChar(CP_UTF8, 0, pVal, strlen(pVal), libEnt->szTitle, 128); } if(mp4ff_meta_get_album(file, &pVal)) { MultiByteToWideChar(CP_UTF8, 0, pVal, strlen(pVal), libEnt->szAlbum, 128); } if(mp4ff_meta_get_genre(file, &pVal)) { MultiByteToWideChar(CP_UTF8, 0, pVal, strlen(pVal), libEnt->szGenre, 128); } if(mp4ff_meta_get_comment(file, &pVal)) { MultiByteToWideChar(CP_UTF8, 0, pVal, strlen(pVal), libEnt->szComment, 128); } if(mp4ff_meta_get_track(file, &pVal)) { libEnt->dwTrack[0] = atoi(pVal); } if(mp4ff_meta_get_totaltracks(file, &pVal)) { libEnt->dwTrack[1] = atoi(pVal); } if(mp4ff_meta_get_date(file, &pVal)) { libEnt->iYear = atoi(pVal); } int track; if ((track = GetAACTrack(file)) < 0) { } libEnt->iSampleRate = mp4ff_get_sample_rate(file, track); libEnt->iBitRate = mp4ff_get_avg_bitrate(file, track); libEnt->iChannels = mp4ff_get_channel_count(file, track); unsigned long Samples = mp4ff_get_track_duration(file, track); libEnt->iPlaybackTime = (float)Samples / (float)(libEnt->iSampleRate/1000); mp4ff_close(file); fclose(mp4File); return true; } bool Cm4aInfoManager::SetInfo(LibraryEntry * libEnt) { return true; }
20.863874
80
0.633626
Harteex
6c0c63d2bc9f00fd0c98cc6409f37e333a929049
2,282
hpp
C++
include/outputformat.hpp
nnaumenko/metafjson
6cd7fdc0d888481bead5d1cc2cff29fb41934167
[ "MIT" ]
null
null
null
include/outputformat.hpp
nnaumenko/metafjson
6cd7fdc0d888481bead5d1cc2cff29fb41934167
[ "MIT" ]
null
null
null
include/outputformat.hpp
nnaumenko/metafjson
6cd7fdc0d888481bead5d1cc2cff29fb41934167
[ "MIT" ]
null
null
null
/* * Copyright (C) 2020 Nick Naumenko (https://gitlab.com/nnaumenko, * https:://github.com/nnaumenko) * All rights reserved. * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #ifndef OUTPUTFORMAT_HPP #define OUTPUTFORMAT_HPP #include <iostream> #include <memory> #include "nlohmann/json_fwd.hpp" #include "datetimeformat.hpp" #include "valueformat.hpp" class Settings; namespace metaf { class Runway; class Temperature; class Speed; class Distance; class Direction; class Pressure; class Precipitation; class SurfaceFriction; class WaveHeight; enum class Weather; enum class WeatherDescriptor; struct ParseResult; } // namespace metaf class OutputFormat { public: OutputFormat(std::unique_ptr<const DateTimeFormat> dtFormat, std::unique_ptr<const ValueFormat> valFormat, bool rawStrings, int refYear, unsigned refMonth, unsigned refDay) : dateTimeFormat(std::move(dtFormat)), valueFormat(std::move(valFormat)), includeRawStrings(rawStrings), referenceYear(refYear), referenceMonth(refMonth), referenceDay(refDay) { } virtual ~OutputFormat() {} // Result of METAR or TAF report parsing and serialising to JSON enum class Result { OK, // Result parsed and serialised OK EXCEPTION // Exception occurred during parsing or serialising }; // Result toJson(const std::string &report, std::ostream &out = std::cout) const; protected: // Parse a METAR or TAF report and serialise to JSON virtual nlohmann::json toJson( const metaf::ParseResult &parseResult) const = 0; std::unique_ptr<const DateTimeFormat> dateTimeFormat; std::unique_ptr<const ValueFormat> valueFormat; bool getIncludeRawStrings() const { return includeRawStrings; } int getReferenceYear() const { return referenceYear; } int getReferenceMonth() const { return referenceMonth; } int getReferenceDay() const { return referenceDay; } private: bool includeRawStrings = false; int referenceYear = 0; int referenceMonth = 0; int referenceDay = 0; }; #endif //#ifndef OUTPUTFORMAT_HPP
27.166667
82
0.691937
nnaumenko
6c10fbdd2d044eb05045c14faf2bc6506da466f3
999
hpp
C++
include/RED4ext/Scripting/Natives/Generated/AI/ArgumentMapping.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/AI/ArgumentMapping.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/AI/ArgumentMapping.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/CName.hpp> #include <RED4ext/Handle.hpp> #include <RED4ext/NativeTypes.hpp> #include <RED4ext/Scripting/IScriptable.hpp> #include <RED4ext/Scripting/Natives/Generated/AI/ArgumentType.hpp> #include <RED4ext/Scripting/Natives/Generated/AI/ParameterizationType.hpp> namespace RED4ext { namespace AI { struct ArgumentMapping; } namespace AI { struct ArgumentMapping : IScriptable { static constexpr const char* NAME = "AIArgumentMapping"; static constexpr const char* ALIAS = NAME; Variant defaultValue; // 40 uint8_t unk58[0x5C - 0x58]; // 58 AI::ParameterizationType parameterizationType; // 5C AI::ArgumentType type; // 60 uint8_t unk64[0x68 - 0x64]; // 64 Handle<AI::ArgumentMapping> prefixValue; // 68 CName customTypeName; // 78 }; RED4EXT_ASSERT_SIZE(ArgumentMapping, 0x80); } // namespace AI } // namespace RED4ext
28.542857
74
0.742743
jackhumbert
6c116a9e2695047896718d2cee553286bfc56b7b
5,373
hpp
C++
include/HoudiniEngineUnity/HAPI_TransformEuler.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/HoudiniEngineUnity/HAPI_TransformEuler.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/HoudiniEngineUnity/HAPI_TransformEuler.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: HoudiniEngineUnity.HAPI_XYZOrder #include "HoudiniEngineUnity/HAPI_XYZOrder.hpp" // Including type: HoudiniEngineUnity.HAPI_RSTOrder #include "HoudiniEngineUnity/HAPI_RSTOrder.hpp" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Type namespace: HoudiniEngineUnity namespace HoudiniEngineUnity { // Forward declaring type: HAPI_TransformEuler struct HAPI_TransformEuler; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::HoudiniEngineUnity::HAPI_TransformEuler, "HoudiniEngineUnity", "HAPI_TransformEuler"); // Type namespace: HoudiniEngineUnity namespace HoudiniEngineUnity { // Size: 0x28 #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: HoudiniEngineUnity.HAPI_TransformEuler // [TokenAttribute] Offset: FFFFFFFF struct HAPI_TransformEuler/*, public ::System::ValueType*/ { public: public: // public System.Single[] position // Size: 0x8 // Offset: 0x0 ::ArrayW<float> position; // Field size check static_assert(sizeof(::ArrayW<float>) == 0x8); // public System.Single[] rotationEuler // Size: 0x8 // Offset: 0x8 ::ArrayW<float> rotationEuler; // Field size check static_assert(sizeof(::ArrayW<float>) == 0x8); // public System.Single[] scale // Size: 0x8 // Offset: 0x10 ::ArrayW<float> scale; // Field size check static_assert(sizeof(::ArrayW<float>) == 0x8); // public System.Single[] shear // Size: 0x8 // Offset: 0x18 ::ArrayW<float> shear; // Field size check static_assert(sizeof(::ArrayW<float>) == 0x8); // public HoudiniEngineUnity.HAPI_XYZOrder rotationOrder // Size: 0x4 // Offset: 0x20 ::HoudiniEngineUnity::HAPI_XYZOrder rotationOrder; // Field size check static_assert(sizeof(::HoudiniEngineUnity::HAPI_XYZOrder) == 0x4); // public HoudiniEngineUnity.HAPI_RSTOrder rstOrder // Size: 0x4 // Offset: 0x24 ::HoudiniEngineUnity::HAPI_RSTOrder rstOrder; // Field size check static_assert(sizeof(::HoudiniEngineUnity::HAPI_RSTOrder) == 0x4); public: // Creating value type constructor for type: HAPI_TransformEuler constexpr HAPI_TransformEuler(::ArrayW<float> position_ = ::ArrayW<float>(static_cast<void*>(nullptr)), ::ArrayW<float> rotationEuler_ = ::ArrayW<float>(static_cast<void*>(nullptr)), ::ArrayW<float> scale_ = ::ArrayW<float>(static_cast<void*>(nullptr)), ::ArrayW<float> shear_ = ::ArrayW<float>(static_cast<void*>(nullptr)), ::HoudiniEngineUnity::HAPI_XYZOrder rotationOrder_ = {}, ::HoudiniEngineUnity::HAPI_RSTOrder rstOrder_ = {}) noexcept : position{position_}, rotationEuler{rotationEuler_}, scale{scale_}, shear{shear_}, rotationOrder{rotationOrder_}, rstOrder{rstOrder_} {} // Creating interface conversion operator: operator ::System::ValueType operator ::System::ValueType() noexcept { return *reinterpret_cast<::System::ValueType*>(this); } // Get instance field reference: public System.Single[] position ::ArrayW<float>& dyn_position(); // Get instance field reference: public System.Single[] rotationEuler ::ArrayW<float>& dyn_rotationEuler(); // Get instance field reference: public System.Single[] scale ::ArrayW<float>& dyn_scale(); // Get instance field reference: public System.Single[] shear ::ArrayW<float>& dyn_shear(); // Get instance field reference: public HoudiniEngineUnity.HAPI_XYZOrder rotationOrder ::HoudiniEngineUnity::HAPI_XYZOrder& dyn_rotationOrder(); // Get instance field reference: public HoudiniEngineUnity.HAPI_RSTOrder rstOrder ::HoudiniEngineUnity::HAPI_RSTOrder& dyn_rstOrder(); // public System.Void .ctor(System.Boolean initializeFields) // Offset: 0x16AA6E0 HAPI_TransformEuler(bool initializeFields); // public System.Void Init() // Offset: 0x16AA78C void Init(); }; // HoudiniEngineUnity.HAPI_TransformEuler #pragma pack(pop) static check_size<sizeof(HAPI_TransformEuler), 36 + sizeof(::HoudiniEngineUnity::HAPI_RSTOrder)> __HoudiniEngineUnity_HAPI_TransformEulerSizeCheck; static_assert(sizeof(HAPI_TransformEuler) == 0x28); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: HoudiniEngineUnity::HAPI_TransformEuler::HAPI_TransformEuler // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: HoudiniEngineUnity::HAPI_TransformEuler::Init // Il2CppName: Init template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HAPI_TransformEuler::*)()>(&HoudiniEngineUnity::HAPI_TransformEuler::Init)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HAPI_TransformEuler), "Init", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
47.973214
584
0.729015
RedBrumbler
6c1ba257a16f8039573499420f9f1ce9037da361
4,180
cpp
C++
src/RInput.cpp
chilingg/redopera
c76d6e88c1f7bb0c048191c0c7eca41ed38754af
[ "MIT" ]
null
null
null
src/RInput.cpp
chilingg/redopera
c76d6e88c1f7bb0c048191c0c7eca41ed38754af
[ "MIT" ]
null
null
null
src/RInput.cpp
chilingg/redopera
c76d6e88c1f7bb0c048191c0c7eca41ed38754af
[ "MIT" ]
null
null
null
#include <RInput.h> using namespace Redopera; RSignal<bool, int> RInput::joyPresented; RSignal<int> RInput::wheeled; std::unordered_map<SDL_Joystick*, RInput::Joystick> RInput::joysticks_; RInput::Key RInput::key_; RInput::Mouse RInput::mouse_; void RInput::process(const SDL_Event &e) { switch(e.type) { case SDL_JOYBUTTONDOWN: case SDL_JOYBUTTONUP: joysticks_.at(SDL_JoystickFromInstanceID(e.jbutton.which)).status_[e.jbutton.button] = e.jbutton.state == SDL_PRESSED ? R_PRESSED : R_RELEASED; break; case SDL_KEYDOWN: key_.status_[e.key.keysym.scancode] = e.key.repeat ? R_REPEAR : R_PRESSED; break; case SDL_KEYUP: key_.status_[e.key.keysym.scancode] = R_RELEASED; break; case SDL_MOUSEMOTION: mouse_.moved_ = true; break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: if(e.button.state == SDL_PRESSED) mouse_.status_[e.button.button - 1] = e.button.clicks == 1 ? R_PRESSED : R_DOUBLECLICK; else mouse_.status_[e.button.button - 1] = R_RELEASED; break; case SDL_JOYDEVICEADDED: if(openJoystick(e.jdevice.which)) joyPresented.emit(true, SDL_JoystickGetDeviceInstanceID(e.jdevice.which)); break; case SDL_JOYDEVICEREMOVED: joyPresented.emit(false, e.jdevice.which); break; case SDL_MOUSEWHEEL: wheeled.emit(e.wheel.y); } } void RInput::updataClear() { for(auto &[jid, joy] : joysticks_) std::fill_n(joy.status_.get(), SDL_JoystickNumButtons(joy.joy_), R_NONE); std::for_each(key_.status_.begin(), key_.status_.end(), [](auto &it){ it.second = R_NONE; }); auto &key = key_; mouse_.moved_ = false; mouse_.status_ = { R_NONE, R_NONE, R_NONE }; } /* void RInput::initJoysticks() { for(int i = 0; i < SDL_NumJoysticks(); ++i) openJoystick(i); } */ SDL_Joystick* RInput::openJoystick(int device) { SDL_Joystick *joy = SDL_JoystickOpen(device); if(joy) { joysticks_[joy].joy_ = joy; joysticks_[joy].status_ = std::make_unique<int[]>(SDL_JoystickNumButtons(joy)); } return joy; } int RInput::Mouse::status(int *x, int *y) { return SDL_GetMouseState(&pos_.rx(), &pos_.ry()); } int RInput::Mouse::left() { return status_[0]; } int RInput::Mouse::middle() { return status_[1]; } int RInput::Mouse::right() { return status_[2]; } bool RInput::Mouse::move() { return moved_; } const RPoint2 &RInput::Mouse::pos() { SDL_GetMouseState(&pos_.rx(), &pos_.ry()); return pos_; } int RInput::Key::status(int key) { static int numkeys; static const uint8_t *kStatus = SDL_GetKeyboardState(&numkeys); if(key > 0 || key < numkeys) return kStatus[key]; else return R_NONE; } bool RInput::Key::press(int key) { if(status_.contains(key)) return status_[key] == R_PRESSED; else return false; } bool RInput::Key::release(int key) { if(status_.contains(key)) return status_[key] == R_RELEASED; else return false; } bool RInput::Key::repeat(int key) { if(status_.contains(key)) return status_[key] == R_REPEAR; else return false; } int RInput::Joystick::status(int btn) { if(btn > 0 || btn < SDL_JoystickNumButtons(joy_)) return status_[btn]; return R_NONE; } bool RInput::Joystick::press(int btn) { if(btn > 0 || btn < SDL_JoystickNumButtons(joy_)) return status_[btn] == R_PRESSED; return R_NONE; } bool RInput::Joystick::release(int btn) { if(btn > 0 || btn < SDL_JoystickNumButtons(joy_)) return status_[btn] == R_RELEASED; return R_NONE; } int RInput::Joystick::axis(int axis) { if(axis > 0 || axis < SDL_JoystickNumAxes(joy_)) return SDL_JoystickGetAxis(joy_, axis); else return 0; } int RInput::Joystick::rumble(unsigned low, unsigned high, unsigned ms) { return SDL_JoystickRumble(joy_, low, high, ms); } int RInput::Joystick::rumbleTriggers(unsigned left, unsigned right, unsigned ms) { return SDL_JoystickRumbleTriggers(joy_, left, right, ms); }
22.352941
99
0.640909
chilingg
6c1eadea3fcb04d352063da9fd78bf881707a984
1,096
cpp
C++
Gaia/Materials/material.cpp
tim0901/Gaia
ffe17ac9deedafd577ceb35efda37e7d573eeebd
[ "MIT" ]
null
null
null
Gaia/Materials/material.cpp
tim0901/Gaia
ffe17ac9deedafd577ceb35efda37e7d573eeebd
[ "MIT" ]
null
null
null
Gaia/Materials/material.cpp
tim0901/Gaia
ffe17ac9deedafd577ceb35efda37e7d573eeebd
[ "MIT" ]
null
null
null
#include "Material.h" Vec3d Reflect(const Vec3d& inDirection, const Vec3d& normal) { return unit_vector(2.0 * dot(inDirection, normal) * normal - inDirection); } bool Refract(const Vec3d& inDirection, const Vec3d& normal, const double& eta, Vec3d& outDirection) { Vec3d inBound = -inDirection; double cosTheta_i = dot(inDirection, normal); double descriminant = 1.0 - eta * eta * (1.0 - cosTheta_i * cosTheta_i); if (descriminant > 0.0) { outDirection = unit_vector(eta * inBound + (eta * cosTheta_i - sqrt(descriminant)) * normal); return true; } return false; } double Fresnel(Vec3d w_i, Vec3d n, double eta_t, double eta_i) { // Fresnel double eta_t2 = eta_t * eta_t; double eta_i2 = eta_i * eta_i; double c = abs(dot(w_i, n)); double gSquared = (eta_t2 / eta_i2) - 1.0 + (c * c); if (gSquared < 0.0) { // Return 1 if g is imaginary - total internal reflection return 1.0; } double g = sqrt(gSquared); return 0.5 * (((g - c) * (g - c)) / ((g + c) * (g + c))) * (1.0 + (((c * (g + c) - 1.0) * (c * (g + c) - 1.0)) / ((c * (g - c) + 1.0) * (c * (g - c) + 1.0)))); }
32.235294
160
0.620438
tim0901
6c22daa66cd3050a9d6952ce63ac6a871e1b33f3
1,541
cpp
C++
src/AdventOfCode2020/Day10-AdapterArray/test_Day10-AdapterArray.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
src/AdventOfCode2020/Day10-AdapterArray/test_Day10-AdapterArray.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
src/AdventOfCode2020/Day10-AdapterArray/test_Day10-AdapterArray.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
#include "Day10-AdapterArray.h" #include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h> __BEGIN_LIBRARIES_DISABLE_WARNINGS #include "CppUnitTest.h" __END_LIBRARIES_DISABLE_WARNINGS using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace CurrentDay = AdventOfCode::Year2020::Day10; TEST_CLASS(Day10AdapterArray) { public: TEST_METHOD(numOneAndThreeJoltDifferencesMultiplied_SimpleTests) { Assert::AreEqual(7 * 5, CurrentDay::numOneAndThreeJoltDifferencesMultiplied(m_joltageRatingsShort)); Assert::AreEqual(22 * 10, CurrentDay::numOneAndThreeJoltDifferencesMultiplied(m_joltageRatingsLong)); } TEST_METHOD(numDistinctAdapterArrangements_SimpleTests) { Assert::AreEqual(8ll, CurrentDay::numDistinctAdapterArrangements(m_joltageRatingsShort)); Assert::AreEqual(19208ll, CurrentDay::numDistinctAdapterArrangements(m_joltageRatingsLong)); } private: std::vector<int> m_joltageRatingsShort = { 16, 10, 15, 5, 1, 11, 7, 19, 6, 12, 4 }; std::vector<int> m_joltageRatingsLong = { 28, 33, 18, 42, 31, 14, 46, 20, 48, 47, 24, 23, 49, 45, 19, 38, 39, 11, 1, 32, 25, 35, 8, 17, 7, 9, 4, 2, 34, 10, 3 }; };
19.024691
109
0.5756
dbartok
6c2aff30b36928ef20331a4dee52752a14e8a654
2,123
cpp
C++
ui/src/clickandgoslider.cpp
joepadmiraal/qlcplus
ca7f083012c92eb4263bc38d957b2feda6d04185
[ "Apache-2.0" ]
2
2016-12-12T15:32:27.000Z
2021-05-18T17:55:30.000Z
ui/src/clickandgoslider.cpp
joepadmiraal/qlcplus
ca7f083012c92eb4263bc38d957b2feda6d04185
[ "Apache-2.0" ]
null
null
null
ui/src/clickandgoslider.cpp
joepadmiraal/qlcplus
ca7f083012c92eb4263bc38d957b2feda6d04185
[ "Apache-2.0" ]
null
null
null
/* Q Light Controller Plus clickandgoslider.cpp Copyright (c) Massimo Callegari 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.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "clickandgoslider.h" #include <QStyleOptionSlider> #include <QStyle> ClickAndGoSlider::ClickAndGoSlider(QWidget *parent) : QSlider(parent) { } void ClickAndGoSlider::setSliderStyleSheet(const QString &styleSheet) { if(isVisible()) QSlider::setStyleSheet(styleSheet); else m_styleSheet = styleSheet; } void ClickAndGoSlider::mousePressEvent ( QMouseEvent * event ) { if (event->modifiers() == Qt::ControlModifier) { emit controlClicked(); return; } QStyleOptionSlider opt; initStyleOption(&opt); QRect sr = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this); if (event->button() == Qt::LeftButton && // react only to left button press sr.contains(event->pos()) == false) // check if the click is not over the slider's handle { int newVal = 0; if (orientation() == Qt::Vertical) newVal = minimum() + ((maximum() - minimum()) * (height() - event->y())) / height(); else newVal = minimum() + ((maximum() - minimum()) * event->x()) / width(); if (invertedAppearance() == true) setValue( maximum() - newVal ); else setValue(newVal); event->accept(); } QSlider::mousePressEvent(event); } void ClickAndGoSlider::showEvent(QShowEvent *) { if (m_styleSheet.isEmpty() == false) { setSliderStyleSheet(m_styleSheet); m_styleSheet = ""; } }
28.306667
97
0.655205
joepadmiraal
6c2d3173c706cc5738410995563154f1f0f33f59
3,309
hh
C++
tests/InteractivityTest.hh
azjezz/hh-clilib
ef39116c527ac2496c985657f93af0253c9d8227
[ "MIT" ]
null
null
null
tests/InteractivityTest.hh
azjezz/hh-clilib
ef39116c527ac2496c985657f93af0253c9d8227
[ "MIT" ]
null
null
null
tests/InteractivityTest.hh
azjezz/hh-clilib
ef39116c527ac2496c985657f93af0253c9d8227
[ "MIT" ]
null
null
null
<?hh // strict /* * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ namespace Facebook\CLILib; use namespace HH\Lib\{Tuple, Vec}; use function Facebook\FBExpect\expect; use type Facebook\CLILib\TestLib\{StringInput, StringOutput}; final class InteractivityTest extends TestCase { private function getCLI( ): (TestCLIWithoutArguments, StringInput, StringOutput, StringOutput) { $stdin = new StringInput(); $stdout = new StringOutput(); $stderr = new StringOutput(); $cli = new TestCLIWithoutArguments( vec[__FILE__, '--interactive'], new Terminal($stdin, $stdout, $stderr), ); return tuple($cli, $stdin, $stdout, $stderr); } public async function testClosedInput(): Awaitable<void> { list($cli, $in, $out, $err) = $this->getCLI(); await $in->closeAsync(); $ret = await $cli->mainAsync(); expect($ret)->toBeSame(0); expect($out->getBuffer())->toBeSame(''); expect($err->getBuffer())->toBeSame(''); } public async function testSingleCommandBeforeStart(): Awaitable<void> { list($cli, $in, $out, $err) = $this->getCLI(); $in->appendToBuffer("echo hello, world\n"); await $in->closeAsync(); $ret = await $cli->mainAsync(); expect($err->getBuffer())->toBeSame(''); expect($out->getBuffer())->toBeSame("> hello, world\n"); expect($ret)->toBeSame(0); } public async function testSingleCommandAfterStart(): Awaitable<void> { list($cli, $in, $out, $err) = $this->getCLI(); list($ret, $_) = await Tuple\from_async( $cli->mainAsync(), async { await \HH\Asio\later(); expect($out->getBuffer())->toBeSame('> '); $out->clearBuffer(); $in->appendToBuffer("exit 123\n"); }, ); expect($ret)->toBeSame(123); expect($out->getBuffer())->toBeSame(''); } public async function testMultipleCommandBeforeStart(): Awaitable<void> { list($cli, $in, $out, $err) = $this->getCLI(); $in->appendToBuffer("echo hello, world\n"); $in->appendToBuffer("echo foo bar\n"); $in->appendToBuffer("exit 123\n"); await $in->closeAsync(); $ret = await $cli->mainAsync(); expect($err->getBuffer())->toBeSame(''); expect($out->getBuffer())->toBeSame("> hello, world\n> foo bar\n> "); expect($ret)->toBeSame(123); } public async function testMultipleCommandsSequentially(): Awaitable<void> { list($cli, $in, $out, $err) = $this->getCLI(); list($ret, $_) = await Tuple\from_async( $cli->mainAsync(), async { await \HH\Asio\later(); expect($out->getBuffer())->toBeSame('> '); $out->clearBuffer(); $in->appendToBuffer("echo foo bar\n"); await \HH\Asio\later(); expect($out->getBuffer())->toBeSame("foo bar\n> "); $out->clearBuffer(); $in->appendToBuffer("echo herp derp\n"); await \HH\Asio\later(); expect($out->getBuffer())->toBeSame("herp derp\n> "); $out->clearBuffer(); $in->appendToBuffer("exit 42\n"); }, ); expect($ret)->toBeSame(42); expect($out->getBuffer())->toBeSame(''); expect($err->getBuffer())->toBeSame(''); } }
31.817308
77
0.607434
azjezz
6c2d7d15d68e2d7db306c2b41211f2523f3af904
376
cpp
C++
cpp/basic_ostream/flush/src/basic_ostream/basic_ostream.cpp
bg1bgst333/Sample
68e3a5c26c6d9bc1906ce0cca2fd586f0790fa52
[ "MIT" ]
9
2016-12-22T20:24:09.000Z
2021-05-08T08:48:24.000Z
cpp/basic_ostream/flush/src/basic_ostream/basic_ostream.cpp
bg1bgst333/Sample
68e3a5c26c6d9bc1906ce0cca2fd586f0790fa52
[ "MIT" ]
36
2018-08-16T06:43:36.000Z
2022-03-25T19:01:34.000Z
cpp/basic_ostream/flush/src/basic_ostream/basic_ostream.cpp
bg1bgst333/Sample
68e3a5c26c6d9bc1906ce0cca2fd586f0790fa52
[ "MIT" ]
9
2016-09-03T02:57:31.000Z
2021-09-09T02:42:26.000Z
// ヘッダのインクルード #include <iostream> // 標準入出力 #include <unistd.h> // UNIX標準 // main関数 int main(){ // 1つ目の文字列を出力. std::cout << "str1"; // 出力演算子で"str1"を出力. // いったんフラッシュ. std::cout.flush(); // std::cout.flushでバッファをいったんフラッシュ. // 5秒スリープ sleep(5); // sleepで5秒待つ. // 2つ目の文字列を出力. std::cout << "str2"; // 出力演算子で"str2"を出力. // プログラムの終了. return 0; // 0を返して正常終了. }
15.666667
55
0.598404
bg1bgst333
6c2dc58807c94de92bd759e97ce4538a3ea3201a
4,560
cpp
C++
java projects/jtop/jtopas/versions.alt/seeded/v3/src/de/susebox/jtopas/TokenizerProperty.cpp
NazaninBayati/SMBFL
999c4bca166a32571e9f0b1ad99085a5d48550eb
[ "MIT" ]
3
2019-08-31T06:18:29.000Z
2020-09-07T12:36:38.000Z
java projects/jtop/jtopas/versions.alt/seeded/v3/src/de/susebox/jtopas/TokenizerProperty.cpp
NazaninBayati/SMBFL
999c4bca166a32571e9f0b1ad99085a5d48550eb
[ "MIT" ]
null
null
null
java projects/jtop/jtopas/versions.alt/seeded/v3/src/de/susebox/jtopas/TokenizerProperty.cpp
NazaninBayati/SMBFL
999c4bca166a32571e9f0b1ad99085a5d48550eb
[ "MIT" ]
null
null
null
package de.susebox.jtopas; public class TokenizerProperty { public static final byte PARSE_FLAG_MASK = 127; public void setType(int type) { _type = type; } public int getType() { return _type; } public void setFlags(int flags) { _flags = flags; } public int getFlags() { return _flags; } public void setImages(String[] images) throws IllegalArgumentException { _images = images; } public String[] getImages() { return _images; } public void setCompanion(Object companion) { _companion = companion; } public Object getCompanion() { return _companion; } public boolean isCaseSensitive() { return (getFlags() & TokenizerProperties.F_CASE) != 0; } public TokenizerProperty() { this(Token.UNKNOWN, null, null); } public TokenizerProperty(int type) { this(type, null, null); } public TokenizerProperty(int type, String[] values) { this(type, values, null); } public TokenizerProperty(int type, String[] values, Object companion) { this(type, values, companion, 0); } public TokenizerProperty(int type, String[] images, Object companion, int flags) { setType(type); setImages(images); setCompanion(companion); setFlags(flags); } public boolean equals(Object that) { if (that == null) { return false; } else if (that == this) { return true; } else if ( ! (that.getClass() == getClass())) { return false; } TokenizerProperty thatProp = (TokenizerProperty)that; if ( getType() == thatProp.getType() && getCompanion() == thatProp.getCompanion() && getFlags() == thatProp.getFlags()) { String[] thisImg = getImages(); String[] thatImg = thatProp.getImages(); if (thisImg != thatImg) { if (thisImg == null || thatImg == null || thisImg.length != thatImg.length) { return false; } for (int index = 0; index < thisImg.length; ++index) { if ( ( isCaseSensitive() && ! thisImg[index].equals(thatImg[index])) || ( ! isCaseSensitive() && ! thisImg[index].equalsIgnoreCase(thatImg[index]))) { return false; } } } return true; } else { return false; } } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(getClass().getName()); buffer.append(':'); switch (getType()) { case Token.NORMAL: buffer.append(" NORMAL, "); break; case Token.BLOCK_COMMENT: buffer.append(" BLOCK_COMMENT, "); break; case Token.LINE_COMMENT: buffer.append(" LINE_COMMENT, "); break; case Token.STRING: buffer.append(" STRING, "); break; case Token.PATTERN: buffer.append(" PATTERN, "); break; case Token.KEYWORD: buffer.append(" KEYWORD, "); break; case Token.WHITESPACE: buffer.append(" WHITESPACE, "); break; case Token.SEPARATOR: buffer.append(" SEPARATOR, "); break; case Token.SPECIAL_SEQUENCE: buffer.append(" SPECIAL_SEQUENCE, "); break; case Token.EOF: buffer.append(" EOF, "); break; case TokenizerProperty.PARSE_FLAG_MASK: buffer.append(" PARSE FLAG MASK, "); break; default: buffer.append(" UNKNOWN, "); } if (isCaseSensitive()) { buffer.append("case-sensitive:"); } else { buffer.append("case-insensitive:"); } if (_images != null) { for (int index = 0; index < _images.length; ++index) { if (_images[index] != null) { buffer.append(' '); buffer.append(_images[index]); } else { break; } } } return buffer.toString(); } private boolean isCaseSensitive(int flags, int caseFlag, int noCaseFlag) { boolean isCase = (flags & caseFlag) != 0; if ( ! isCase) { isCase = (flags & (TokenizerProperties.F_NO_CASE | noCaseFlag)) == 0; } return isCase; } protected int _type; protected int _flags; protected String[] _images; protected Object _companion; }
17.674419
95
0.540351
NazaninBayati
6c2ed407d7aa95953c9a231d34a2db3a1124f03c
1,062
cpp
C++
Source/wali/lib/witness/WitnessTrans.cpp
jusito/WALi-OpenNWA
2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99
[ "MIT" ]
15
2015-03-07T17:25:57.000Z
2022-02-04T20:17:00.000Z
Source/wali/lib/witness/WitnessTrans.cpp
jusito/WALi-OpenNWA
2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99
[ "MIT" ]
1
2018-03-03T05:58:55.000Z
2018-03-03T12:26:10.000Z
Source/wali/lib/witness/WitnessTrans.cpp
jusito/WALi-OpenNWA
2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99
[ "MIT" ]
15
2015-09-25T17:44:35.000Z
2021-07-18T18:25:38.000Z
/*! * @author Nicholas Kidd */ #include "wali/Common.hpp" #include "wali/witness/WitnessTrans.hpp" #include "wali/witness/Visitor.hpp" namespace wali { namespace witness { WitnessTrans::WitnessTrans( const wfa::ITrans& t_ ) : Witness(t_.weight()),t(t_) { min_length = 0UL; } // Destructor does nothing. WitnessTrans::~WitnessTrans() { } // // Override Witness::accept // void WitnessTrans::accept( Visitor& v, bool visitOnce ATTR_UNUSED ) { // TODO how does marking work...need a flag maybe (void) visitOnce; mark(); if (v.visitTrans(this)) { v.postvisitTrans(this); } } // Overrides Witness::prettyPrint std::ostream& WitnessTrans::prettyPrint( std::ostream& o,size_t depth ) const { formatDepth(o,depth); o << "WitnessTrans: "; t.print(o) << std::endl; return o; } const wfa::Trans& WitnessTrans::getTrans() const { return t; } } // namespace witness } // namespace wali /* * $Id$ */
18.310345
84
0.585687
jusito
6c2f2499b2fd88095195371e9bcdf6882f99527d
7,784
cpp
C++
IslandGame/src/islandgame/IslandGame.cpp
haferflocken/ConductorEngine
4914e419e5a736275e96d76eaa19b7aa56d69345
[ "Zlib", "BSD-2-Clause" ]
null
null
null
IslandGame/src/islandgame/IslandGame.cpp
haferflocken/ConductorEngine
4914e419e5a736275e96d76eaa19b7aa56d69345
[ "Zlib", "BSD-2-Clause" ]
null
null
null
IslandGame/src/islandgame/IslandGame.cpp
haferflocken/ConductorEngine
4914e419e5a736275e96d76eaa19b7aa56d69345
[ "Zlib", "BSD-2-Clause" ]
null
null
null
#include <islandgame/IslandGameData.h> #include <islandgame/client/IslandGameClient.h> #include <islandgame/host/IslandGameHost.h> #include <asset/AssetManager.h> #include <collection/LocklessQueue.h> #include <collection/ProgramParameters.h> #include <file/Path.h> #include <client/ClientWorld.h> #include <client/ConnectedHost.h> #include <client/IRenderInstance.h> #include <client/MessageToHost.h> #include <client/MessageToRenderInstance.h> #include <conductor/ApplicationErrorCode.h> #include <conductor/IGameData.h> #include <conductor/LocalClientHostMain.h> #include <conductor/HostMain.h> #include <conductor/RemoteClientMain.h> #include <condui/ConduiECSRegistration.h> #include <host/ConnectedClient.h> #include <host/HostNetworkWorld.h> #include <host/HostWorld.h> #include <host/MessageToClient.h> #include <input/InputMessage.h> #include <network/Socket.h> #include <renderer/AssetTypes.h> #include <renderer/RenderInstance.h> #include <iostream> namespace Internal_IslandGame { constexpr char* k_dataDirectoryParameter = "-datapath"; constexpr char* k_userGamePath = "Documents/My Games/IslandGame/"; constexpr char* k_applicationModeClientParameter = "-client"; constexpr char* k_applicationModeHostParameter = "-host"; enum class ApplicationMode { Invalid = 0, Client, Host, }; int ClientMain(const Collection::ProgramParameters& params, const File::Path& dataDirectory, const File::Path& userDirectory, Asset::AssetManager& assetManager, std::string& hostParam); int HostMain(const Collection::ProgramParameters& params, const File::Path& dataDirectory, const File::Path& userDirectory, Asset::AssetManager& assetManager, const std::string& port); // Define the factory functions that abstract game code away from engine code. Client::RenderInstanceFactory MakeRenderInstanceFactory() { return [](Asset::AssetManager& assetManager, const File::Path& dataDirectory, Collection::LocklessQueue<Client::MessageToRenderInstance>& clientToRenderInstanceMessages, Collection::LocklessQueue<Input::InputMessage>& inputToClientMessages) { return Mem::MakeUnique<Renderer::RenderInstance>(assetManager, clientToRenderInstanceMessages, inputToClientMessages, "IslandGame"); }; } Conductor::GameDataFactory MakeGameDataFactory() { return [](Asset::AssetManager& assetManager, const File::Path& dataDirectory, const File::Path& userDirectory) { auto gameData = Mem::MakeUnique<IslandGame::IslandGameData>(dataDirectory, userDirectory, assetManager); Condui::RegisterComponentTypes(gameData->GetComponentReflector()); Renderer::RenderInstance::RegisterComponentTypes(gameData->GetComponentReflector()); return gameData; }; } Mem::UniquePtr<Client::IClient> MakeClient(const Conductor::IGameData& gameData, const Math::Frustum& sceneViewFrustum, Client::ConnectedHost& connectedHost) { auto client = Mem::MakeUnique<IslandGame::Client::IslandGameClient>( static_cast<const IslandGame::IslandGameData&>(gameData), connectedHost); Condui::RegisterSystems(client->GetEntityManager(), sceneViewFrustum, client->GetInputCallbackRegistry()); return client; } Host::HostWorld::HostFactory MakeHostFactory() { return [](const Conductor::IGameData& gameData) { return Mem::MakeUnique<IslandGame::Host::IslandGameHost>( static_cast<const IslandGame::IslandGameData&>(gameData)); }; } } int main(const int argc, const char* argv[]) { using namespace Internal_IslandGame; // Extract the data directory from the command line parameters. const Collection::ProgramParameters params{ argc, argv }; std::string dataDirectoryStr; if (!params.TryGet(k_dataDirectoryParameter, dataDirectoryStr)) { std::cerr << "Missing required parameter: -datapath <dir>" << std::endl; return static_cast<int>(Conductor::ApplicationErrorCode::MissingDataPath); } const File::Path dataDirectory = File::MakePath(dataDirectoryStr.c_str()); // Get the user directory. char userDirBuffer[128]; size_t userDirLength; const errno_t userDirErrorCode = getenv_s(&userDirLength, userDirBuffer, "USERPROFILE"); if (userDirErrorCode != 0 || userDirLength == 0) { std::cerr << "Failed to get the user path from the system." << std::endl; return static_cast<int>(Conductor::ApplicationErrorCode::FailedToGetUserPath); } const File::Path userDirectory = File::MakePath(userDirBuffer) / k_userGamePath; // Determine the application mode from the command line parameters. ApplicationMode applicationMode = ApplicationMode::Invalid; std::string applicationModeParamater; if (params.TryGet(k_applicationModeClientParameter, applicationModeParamater)) { applicationMode = ApplicationMode::Client; } else if (params.TryGet(k_applicationModeHostParameter, applicationModeParamater)) { applicationMode = ApplicationMode::Host; } else { std::cerr << "Missing application mode parameter: -client hostName or -host hostPort" << std::endl; return static_cast<int>(Conductor::ApplicationErrorCode::MissingApplicationMode); } // Create an asset manager and register the asset types it needs. Asset::AssetManager assetManager{ dataDirectory }; Renderer::RegisterAssetTypes(assetManager); // Run the application in the specified mode. const int result = (applicationMode == ApplicationMode::Client) ? ClientMain(params, dataDirectory, userDirectory, assetManager, applicationModeParamater) : HostMain(params, dataDirectory, userDirectory, assetManager, applicationModeParamater); // Unregister the asset types from the asset manager in the opposite order they were registered. Renderer::UnregisterAssetTypes(assetManager); return result; } int Internal_IslandGame::ClientMain( const Collection::ProgramParameters& params, const File::Path& dataDirectory, const File::Path& userDirectory, Asset::AssetManager& assetManager, std::string& hostParam) { // Ensure a host parameter was specified. if (hostParam.size() < 3) { return static_cast<int>(Conductor::ApplicationErrorCode::MissingClientHostName); } // If the host is specified as "newhost", spin up a local host with no network thread: just direct communication. // Otherwise, connect to a remote host. if (strcmp(hostParam.c_str(), "newhost") == 0) { const Conductor::ApplicationErrorCode errorCode = Conductor::LocalClientHostMain(params, dataDirectory, userDirectory, assetManager, MakeRenderInstanceFactory(), MakeGameDataFactory(), &MakeClient, MakeHostFactory()); return static_cast<int>(errorCode); } else { // Extract the host name and port from hostParam. const size_t portStartIndex = hostParam.find_last_of(':'); if (portStartIndex == std::string::npos) { return static_cast<int>(Conductor::ApplicationErrorCode::MissingClientHostPort); } hostParam[portStartIndex] = '\0'; const char* const hostName = hostParam.c_str(); const char* const hostPort = hostName + portStartIndex + 1; const Conductor::ApplicationErrorCode errorCode = Conductor::RemoteClientMain(params, dataDirectory, userDirectory, assetManager, hostName, hostPort, MakeRenderInstanceFactory(), MakeGameDataFactory(), &MakeClient); return static_cast<int>(errorCode); } return static_cast<int>(Conductor::ApplicationErrorCode::NoError); } int Internal_IslandGame::HostMain( const Collection::ProgramParameters& params, const File::Path& dataDirectory, const File::Path& userDirectory, Asset::AssetManager& assetManager, const std::string& port) { // Ensure a port was specified. if (port.empty()) { return static_cast<int>(Conductor::ApplicationErrorCode::MissingHostPort); } // Run the host. const Conductor::ApplicationErrorCode errorCode = Conductor::HostMain(params, dataDirectory, userDirectory, assetManager, port.c_str(), MakeGameDataFactory(), MakeHostFactory()); return static_cast<int>(errorCode); }
34.90583
120
0.778905
haferflocken
6c3158db09db4f1b13e698d4319e52778fd0ff18
168
cpp
C++
pointer/pointer.cpp
riti2409/forplacements
9e8fb99c9d65b04eea71abb3fbdcffc2a1433a04
[ "MIT" ]
5
2021-12-03T14:29:16.000Z
2022-02-04T09:06:37.000Z
pointer/pointer.cpp
riti2409/forplacements
9e8fb99c9d65b04eea71abb3fbdcffc2a1433a04
[ "MIT" ]
null
null
null
pointer/pointer.cpp
riti2409/forplacements
9e8fb99c9d65b04eea71abb3fbdcffc2a1433a04
[ "MIT" ]
2
2022-01-16T14:20:42.000Z
2022-01-17T06:49:01.000Z
#include<bits/stdc++.h> using namespace std; int main(){ int a=10; int*aptr=&a; cout<<*aptr<<endl; *aptr=20; cout<<a<<endl; return 0; }
16.8
24
0.52381
riti2409
6c337e63a2ee954d66c3cf70f2f77467a5426c5c
3,638
hh
C++
RAVL2/OS/Time/DeadLineTimer.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/OS/Time/DeadLineTimer.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/OS/Time/DeadLineTimer.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
// This file is part of RAVL, Recognition And Vision Library // Copyright (C) 2001, University of Surrey // This code may be redistributed under the terms of the GNU Lesser // General Public License (LGPL). See the lgpl.licence file for details or // see http://www.gnu.org/copyleft/lesser.html // file-header-ends-here #ifndef RAVL_DEADLINETIMER_HEADER #define RAVL_DEADLINETIMER_HEADER 1 //////////////////////////////////////////////////////// //! rcsid="$Id: DeadLineTimer.hh 5240 2005-12-06 17:16:50Z plugger $" //! docentry="Ravl.API.OS.Time" //! example="exDeadLine.cc" //! file="Ravl/OS/Time/DeadLineTimer.hh" //! lib=RavlOS //! author="Charles Galambos" #include "Ravl/Types.hh" namespace RavlN { class DateC; //! userlevel=Normal //: Dead line timer. // When the timer is started the timesUp flag is set to // false, when the time expires the flag is set to true. // Note the timer flag is always true if the timer is not // running. <p> // You should not expect a resolution in time better than // 1ms. The actual resolution depends on the system the // code is run on and may be worse than this. // This is a SMALL object. <p> class DeadLineTimerC { public: DeadLineTimerC(bool useVirt = false) : virt(useVirt), timesUp(true), id(-1) {} //: Default constructor. ~DeadLineTimerC() { Stop(); } //: Destructor. DeadLineTimerC(const DateC &timetoGo,bool useVirt = false) : virt(useVirt), timesUp(true), id(-1) { Reset(timetoGo); } //: Constructor for an absolute time. DeadLineTimerC(RealT timetoGo,bool useVirt = false) : virt(useVirt), timesUp(true), id(-1) { Reset(timetoGo); } //: Constructor for a relative (to now) time. // Dead line will expire in 'timetoGo' seonds. // void Stop(); //: Stop timer. // This will set the timesUp flag, and free // the deadline timer. bool Reset(RealT time); //: Reset timer with 'time' left before deadline. // Will return false if deadline setup failed, or if // the time as expired before the setup is completed. // Any time smaller than zero is treated as infinite. // NB. There is currently a maximum number of 64 // deadline timers that can be active at any time. // <p> // This isn't a trivial routine, it involves several // system calles, and alot of mucking about. Avoid // calling it excessively. bool Reset(const DateC &time); //: Set the deadline for 'time' // Will return false if deadline setup failed, or if // the time as expired before the setup is completed. // NB. There is currently a maximum number of 64 // deadline timers that can be active at any time. // <p> // This isn't a trivial routine, it involves several // system calles, and alot of mucking about. Avoid // calling it excessively. inline volatile const bool &IsTimeUp() const { return timesUp; } //: Has dead line been reached ? inline bool IsRunning() const { return !timesUp; } //: Is timer still running ? inline bool IsVirtual() const { return virt; } //: Is virtual timer. RealT Remaining() const; //: Get an estimate of the time remaining on deadline. // If dead line has expired 0 is returned. bool WaitForIt() const; //: Wait for deadline to expire. // May return false if no deadline pending, which // could happen if the timer expires before the call. private: bool virt; // Virtual timer ? volatile bool timesUp; IntT id; }; } #endif
31.094017
74
0.642111
isuhao
6c340e988a3b12e8e248e7116664cb6a43a8cc86
6,097
cpp
C++
aws-cpp-sdk-lightsail/source/model/HeaderEnum.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-lightsail/source/model/HeaderEnum.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-lightsail/source/model/HeaderEnum.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/lightsail/model/HeaderEnum.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace Lightsail { namespace Model { namespace HeaderEnumMapper { static const int Accept_HASH = HashingUtils::HashString("Accept"); static const int Accept_Charset_HASH = HashingUtils::HashString("Accept-Charset"); static const int Accept_Datetime_HASH = HashingUtils::HashString("Accept-Datetime"); static const int Accept_Encoding_HASH = HashingUtils::HashString("Accept-Encoding"); static const int Accept_Language_HASH = HashingUtils::HashString("Accept-Language"); static const int Authorization_HASH = HashingUtils::HashString("Authorization"); static const int CloudFront_Forwarded_Proto_HASH = HashingUtils::HashString("CloudFront-Forwarded-Proto"); static const int CloudFront_Is_Desktop_Viewer_HASH = HashingUtils::HashString("CloudFront-Is-Desktop-Viewer"); static const int CloudFront_Is_Mobile_Viewer_HASH = HashingUtils::HashString("CloudFront-Is-Mobile-Viewer"); static const int CloudFront_Is_SmartTV_Viewer_HASH = HashingUtils::HashString("CloudFront-Is-SmartTV-Viewer"); static const int CloudFront_Is_Tablet_Viewer_HASH = HashingUtils::HashString("CloudFront-Is-Tablet-Viewer"); static const int CloudFront_Viewer_Country_HASH = HashingUtils::HashString("CloudFront-Viewer-Country"); static const int Host_HASH = HashingUtils::HashString("Host"); static const int Origin_HASH = HashingUtils::HashString("Origin"); static const int Referer_HASH = HashingUtils::HashString("Referer"); HeaderEnum GetHeaderEnumForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == Accept_HASH) { return HeaderEnum::Accept; } else if (hashCode == Accept_Charset_HASH) { return HeaderEnum::Accept_Charset; } else if (hashCode == Accept_Datetime_HASH) { return HeaderEnum::Accept_Datetime; } else if (hashCode == Accept_Encoding_HASH) { return HeaderEnum::Accept_Encoding; } else if (hashCode == Accept_Language_HASH) { return HeaderEnum::Accept_Language; } else if (hashCode == Authorization_HASH) { return HeaderEnum::Authorization; } else if (hashCode == CloudFront_Forwarded_Proto_HASH) { return HeaderEnum::CloudFront_Forwarded_Proto; } else if (hashCode == CloudFront_Is_Desktop_Viewer_HASH) { return HeaderEnum::CloudFront_Is_Desktop_Viewer; } else if (hashCode == CloudFront_Is_Mobile_Viewer_HASH) { return HeaderEnum::CloudFront_Is_Mobile_Viewer; } else if (hashCode == CloudFront_Is_SmartTV_Viewer_HASH) { return HeaderEnum::CloudFront_Is_SmartTV_Viewer; } else if (hashCode == CloudFront_Is_Tablet_Viewer_HASH) { return HeaderEnum::CloudFront_Is_Tablet_Viewer; } else if (hashCode == CloudFront_Viewer_Country_HASH) { return HeaderEnum::CloudFront_Viewer_Country; } else if (hashCode == Host_HASH) { return HeaderEnum::Host; } else if (hashCode == Origin_HASH) { return HeaderEnum::Origin; } else if (hashCode == Referer_HASH) { return HeaderEnum::Referer; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<HeaderEnum>(hashCode); } return HeaderEnum::NOT_SET; } Aws::String GetNameForHeaderEnum(HeaderEnum enumValue) { switch(enumValue) { case HeaderEnum::Accept: return "Accept"; case HeaderEnum::Accept_Charset: return "Accept-Charset"; case HeaderEnum::Accept_Datetime: return "Accept-Datetime"; case HeaderEnum::Accept_Encoding: return "Accept-Encoding"; case HeaderEnum::Accept_Language: return "Accept-Language"; case HeaderEnum::Authorization: return "Authorization"; case HeaderEnum::CloudFront_Forwarded_Proto: return "CloudFront-Forwarded-Proto"; case HeaderEnum::CloudFront_Is_Desktop_Viewer: return "CloudFront-Is-Desktop-Viewer"; case HeaderEnum::CloudFront_Is_Mobile_Viewer: return "CloudFront-Is-Mobile-Viewer"; case HeaderEnum::CloudFront_Is_SmartTV_Viewer: return "CloudFront-Is-SmartTV-Viewer"; case HeaderEnum::CloudFront_Is_Tablet_Viewer: return "CloudFront-Is-Tablet-Viewer"; case HeaderEnum::CloudFront_Viewer_Country: return "CloudFront-Viewer-Country"; case HeaderEnum::Host: return "Host"; case HeaderEnum::Origin: return "Origin"; case HeaderEnum::Referer: return "Referer"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace HeaderEnumMapper } // namespace Model } // namespace Lightsail } // namespace Aws
37.635802
118
0.625718
Neusoft-Technology-Solutions
6c35890eb8b6665681eca7f26fc9dbe77170ab05
915
cpp
C++
aten/src/ATen/core/TorchDispatchModeTLS.cpp
stungkit/pytorch
0f05e398705bf15406bce79f7ee57d3935ad2abd
[ "Intel" ]
2
2020-03-13T06:57:49.000Z
2020-05-17T04:18:14.000Z
aten/src/ATen/core/TorchDispatchModeTLS.cpp
stungkit/pytorch
0f05e398705bf15406bce79f7ee57d3935ad2abd
[ "Intel" ]
1
2022-01-10T18:39:28.000Z
2022-01-10T19:15:57.000Z
aten/src/ATen/core/TorchDispatchModeTLS.cpp
stungkit/pytorch
0f05e398705bf15406bce79f7ee57d3935ad2abd
[ "Intel" ]
1
2022-03-26T14:42:50.000Z
2022-03-26T14:42:50.000Z
#include <ATen/core/TorchDispatchModeTLS.h> #include <c10/core/SafePyObject.h> namespace at { namespace impl { thread_local std::shared_ptr<SafePyObject> torchDispatchModeState; void TorchDispatchModeTLS::set_state(std::shared_ptr<SafePyObject> state) { if (state) { c10::impl::tls_set_dispatch_key_included(DispatchKey::Python, true); c10::impl::tls_set_dispatch_key_included(DispatchKey::PythonTLSSnapshot, true); } else { TorchDispatchModeTLS::reset_state(); } torchDispatchModeState = std::move(state); } const std::shared_ptr<SafePyObject>& TorchDispatchModeTLS::get_state() { return torchDispatchModeState; } void TorchDispatchModeTLS::reset_state() { torchDispatchModeState.reset(); c10::impl::tls_set_dispatch_key_included(DispatchKey::Python, false); c10::impl::tls_set_dispatch_key_included(DispatchKey::PythonTLSSnapshot, false); } } // namespace impl } // namespace at
30.5
83
0.775956
stungkit
6c3737314783146e7753ae1448cb9a717c131d45
777
cpp
C++
y2018/filters/houghCircles.cpp
valkyrierobotics/vision2018
aa82e936c5481b7cc43a46ff5f6e68702c2166c2
[ "BSD-2-Clause" ]
2
2016-08-06T06:21:02.000Z
2017-01-10T05:45:13.000Z
y2018/filters/houghCircles.cpp
valkyrierobotics/vision2018
aa82e936c5481b7cc43a46ff5f6e68702c2166c2
[ "BSD-2-Clause" ]
1
2017-04-15T20:54:59.000Z
2017-04-15T20:54:59.000Z
y2018/filters/houghCircles.cpp
valkyrierobotics/vision2018
aa82e936c5481b7cc43a46ff5f6e68702c2166c2
[ "BSD-2-Clause" ]
3
2016-07-30T06:19:55.000Z
2017-02-07T01:55:05.000Z
#include "filters/houghCircles.hpp" void houghCircles(cv::Mat& img, int minDist, int minRadius, int maxRadius) { std::vector<cv::Vec3f> circles; cv::cvtColor(img, img, CV_BGR2GRAY); // cv::HoughCircles calls cv::Canny internally cv::HoughCircles(img, circles, CV_HOUGH_GRADIENT, 2, minDist, maxRadius, minRadius); for (size_t i = 0; i < circles.size(); i++) { // Each circle is encoded in a 3 element vector (x, y, radius) cv::Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); int radius = cvRound(circles[i][2]); // Draw center of circle cv::circle(img, center, 3, cv::Scalar(0,255,0), -1, 8, 0 ); // Draw circle cv::circle(img, center, radius, cv::Scalar(0,0,255), 3, 8, 0 ); } }
35.318182
86
0.616474
valkyrierobotics
6c3d612cdd2ddb7df5e4e2c665be8e45cc0d2d0a
21,619
cc
C++
src/test/libradosstriper/aio.cc
rpratap-bot/ceph
9834961a66927ae856935591f2fd51082e2ee484
[ "MIT" ]
4
2020-04-08T03:42:02.000Z
2020-10-01T20:34:48.000Z
src/test/libradosstriper/aio.cc
rpratap-bot/ceph
9834961a66927ae856935591f2fd51082e2ee484
[ "MIT" ]
93
2020-03-26T14:29:14.000Z
2020-11-12T05:54:55.000Z
src/test/libradosstriper/aio.cc
rpratap-bot/ceph
9834961a66927ae856935591f2fd51082e2ee484
[ "MIT" ]
23
2020-03-24T10:28:44.000Z
2020-09-24T09:42:19.000Z
#include "include/rados/librados.h" #include "include/rados/librados.hpp" #include "include/radosstriper/libradosstriper.h" #include "include/radosstriper/libradosstriper.hpp" #include "test/librados/test.h" #include "test/libradosstriper/TestCase.h" #include <boost/scoped_ptr.hpp> #include <fcntl.h> #include <semaphore.h> #include <errno.h> using namespace librados; using namespace libradosstriper; using std::pair; class AioTestData { public: AioTestData() : m_complete(false), m_safe(false) { m_sem = sem_open("test_libradosstriper_aio_sem", O_CREAT, 0644, 0); } ~AioTestData() { sem_unlink("test_libradosstriper_aio_sem"); sem_close(m_sem); } sem_t *m_sem; bool m_complete; bool m_safe; }; void set_completion_complete(rados_completion_t cb, void *arg) { AioTestData *test = static_cast<AioTestData*>(arg); test->m_complete = true; sem_post(test->m_sem); } void set_completion_safe(rados_completion_t cb, void *arg) { AioTestData *test = static_cast<AioTestData*>(arg); test->m_safe = true; sem_post(test->m_sem); } TEST_F(StriperTest, SimpleWrite) { AioTestData test_data; rados_completion_t my_completion; ASSERT_EQ(0, rados_aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe, &my_completion)); char buf[128]; memset(buf, 0xcc, sizeof(buf)); ASSERT_EQ(0, rados_striper_aio_write(striper, "StriperTest", my_completion, buf, sizeof(buf), 0)); TestAlarm alarm; sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); rados_aio_release(my_completion); } TEST_F(StriperTestPP, SimpleWritePP) { AioTestData test_data; AioCompletion *my_completion = librados::Rados::aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe); char buf[128]; memset(buf, 0xcc, sizeof(buf)); bufferlist bl1; bl1.append(buf, sizeof(buf)); ASSERT_EQ(0, striper.aio_write("SimpleWritePP", my_completion, bl1, sizeof(buf), 0)); TestAlarm alarm; sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); my_completion->release(); } TEST_F(StriperTest, WaitForSafe) { AioTestData test_data; rados_completion_t my_completion; ASSERT_EQ(0, rados_aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe, &my_completion)); char buf[128]; memset(buf, 0xcc, sizeof(buf)); ASSERT_EQ(0, rados_striper_aio_write(striper, "WaitForSafe", my_completion, buf, sizeof(buf), 0)); TestAlarm alarm; rados_aio_wait_for_safe(my_completion); sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); rados_aio_release(my_completion); } TEST_F(StriperTestPP, WaitForSafePP) { AioTestData test_data; AioCompletion *my_completion = librados::Rados::aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe); char buf[128]; memset(buf, 0xcc, sizeof(buf)); bufferlist bl1; bl1.append(buf, sizeof(buf)); ASSERT_EQ(0, striper.aio_write("WaitForSafePP", my_completion, bl1, sizeof(buf), 0)); TestAlarm alarm; my_completion->wait_for_safe(); sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); my_completion->release(); } TEST_F(StriperTest, RoundTrip) { AioTestData test_data; rados_completion_t my_completion; ASSERT_EQ(0, rados_aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe, &my_completion)); char buf[128]; memset(buf, 0xcc, sizeof(buf)); ASSERT_EQ(0, rados_striper_aio_write(striper, "RoundTrip", my_completion, buf, sizeof(buf), 0)); { TestAlarm alarm; sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); } char buf2[128]; memset(buf2, 0, sizeof(buf2)); rados_completion_t my_completion2; ASSERT_EQ(0, rados_aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe, &my_completion2)); ASSERT_EQ(0, rados_striper_aio_read(striper, "RoundTrip", my_completion2, buf2, sizeof(buf2), 0)); { TestAlarm alarm; rados_aio_wait_for_complete(my_completion2); } ASSERT_EQ(0, memcmp(buf, buf2, sizeof(buf))); sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); rados_aio_release(my_completion); rados_aio_release(my_completion2); } TEST_F(StriperTest, RoundTrip2) { AioTestData test_data; rados_completion_t my_completion; ASSERT_EQ(0, rados_aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe, &my_completion)); char buf[128]; memset(buf, 0xcc, sizeof(buf)); ASSERT_EQ(0, rados_striper_aio_write(striper, "RoundTrip2", my_completion, buf, sizeof(buf), 0)); { TestAlarm alarm; sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); } char buf2[128]; memset(buf2, 0, sizeof(buf2)); rados_completion_t my_completion2; ASSERT_EQ(0, rados_aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe, &my_completion2)); ASSERT_EQ(0, rados_striper_aio_read(striper, "RoundTrip2", my_completion2, buf2, sizeof(buf2), 0)); { TestAlarm alarm; rados_aio_wait_for_safe(my_completion2); } ASSERT_EQ(0, memcmp(buf, buf2, sizeof(buf))); sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); rados_aio_release(my_completion); rados_aio_release(my_completion2); } TEST_F(StriperTestPP, RoundTripPP) { AioTestData test_data; AioCompletion *my_completion = librados::Rados::aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe); char buf[128]; memset(buf, 0xcc, sizeof(buf)); bufferlist bl1; bl1.append(buf, sizeof(buf)); ASSERT_EQ(0, striper.aio_write("RoundTripPP", my_completion, bl1, sizeof(buf), 0)); { TestAlarm alarm; sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); } bufferlist bl2; AioCompletion *my_completion2 = librados::Rados::aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe); ASSERT_EQ(0, striper.aio_read("RoundTripPP", my_completion2, &bl2, sizeof(buf), 0)); { TestAlarm alarm; my_completion2->wait_for_complete(); } ASSERT_EQ(0, memcmp(buf, bl2.c_str(), sizeof(buf))); sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); my_completion->release(); my_completion2->release(); } TEST_F(StriperTestPP, RoundTripPP2) { AioTestData test_data; AioCompletion *my_completion = librados::Rados::aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe); char buf[128]; memset(buf, 0xcc, sizeof(buf)); bufferlist bl1; bl1.append(buf, sizeof(buf)); ASSERT_EQ(0, striper.aio_write("RoundTripPP2", my_completion, bl1, sizeof(buf), 0)); { TestAlarm alarm; sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); } bufferlist bl2; AioCompletion *my_completion2 = librados::Rados::aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe); ASSERT_EQ(0, striper.aio_read("RoundTripPP2", my_completion2, &bl2, sizeof(buf), 0)); { TestAlarm alarm; my_completion2->wait_for_safe(); } ASSERT_EQ(0, memcmp(buf, bl2.c_str(), sizeof(buf))); sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); my_completion->release(); my_completion2->release(); } TEST_F(StriperTest, IsComplete) { AioTestData test_data; rados_completion_t my_completion; ASSERT_EQ(0, rados_aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe, &my_completion)); char buf[128]; memset(buf, 0xcc, sizeof(buf)); ASSERT_EQ(0, rados_striper_aio_write(striper, "IsComplete", my_completion, buf, sizeof(buf), 0)); { TestAlarm alarm; sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); } char buf2[128]; memset(buf2, 0, sizeof(buf2)); rados_completion_t my_completion2; ASSERT_EQ(0, rados_aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe, &my_completion2)); ASSERT_EQ(0, rados_striper_aio_read(striper, "IsComplete", my_completion2, buf2, sizeof(buf2), 0)); { TestAlarm alarm; // Busy-wait until the AIO completes. // Normally we wouldn't do this, but we want to test rados_aio_is_complete. while (true) { int is_complete = rados_aio_is_complete(my_completion2); if (is_complete) break; } } ASSERT_EQ(0, memcmp(buf, buf2, sizeof(buf))); sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); rados_aio_release(my_completion); rados_aio_release(my_completion2); } TEST_F(StriperTestPP, IsCompletePP) { AioTestData test_data; AioCompletion *my_completion = librados::Rados::aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe); char buf[128]; memset(buf, 0xcc, sizeof(buf)); bufferlist bl1; bl1.append(buf, sizeof(buf)); ASSERT_EQ(0, striper.aio_write("IsCompletePP", my_completion, bl1, sizeof(buf), 0)); { TestAlarm alarm; sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); } bufferlist bl2; AioCompletion *my_completion2 = librados::Rados::aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe); ASSERT_EQ(0, striper.aio_read("IsCompletePP", my_completion2, &bl2, sizeof(buf), 0)); { TestAlarm alarm; // Busy-wait until the AIO completes. // Normally we wouldn't do this, but we want to test rados_aio_is_complete. while (true) { int is_complete = my_completion2->is_complete(); if (is_complete) break; } } ASSERT_EQ(0, memcmp(buf, bl2.c_str(), sizeof(buf))); sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); my_completion->release(); my_completion2->release(); } TEST_F(StriperTest, IsSafe) { AioTestData test_data; rados_completion_t my_completion; ASSERT_EQ(0, rados_aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe, &my_completion)); char buf[128]; memset(buf, 0xcc, sizeof(buf)); ASSERT_EQ(0, rados_striper_aio_write(striper, "IsSafe", my_completion, buf, sizeof(buf), 0)); { TestAlarm alarm; // Busy-wait until the AIO completes. // Normally we wouldn't do this, but we want to test rados_aio_is_safe. while (true) { int is_safe = rados_aio_is_safe(my_completion); if (is_safe) break; } } char buf2[128]; memset(buf2, 0, sizeof(buf2)); rados_completion_t my_completion2; ASSERT_EQ(0, rados_aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe, &my_completion2)); ASSERT_EQ(0, rados_striper_aio_read(striper, "IsSafe", my_completion2, buf2, sizeof(buf2), 0)); { TestAlarm alarm; rados_aio_wait_for_complete(my_completion2); } ASSERT_EQ(0, memcmp(buf, buf2, sizeof(buf))); sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); rados_aio_release(my_completion); rados_aio_release(my_completion2); } TEST_F(StriperTestPP, IsSafePP) { AioTestData test_data; AioCompletion *my_completion = librados::Rados::aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe); char buf[128]; memset(buf, 0xcc, sizeof(buf)); bufferlist bl1; bl1.append(buf, sizeof(buf)); ASSERT_EQ(0, striper.aio_write("IsSafePP", my_completion, bl1, sizeof(buf), 0)); { TestAlarm alarm; // Busy-wait until the AIO completes. // Normally we wouldn't do this, but we want to test rados_aio_is_safe. while (true) { int is_safe = my_completion->is_safe(); if (is_safe) break; } } bufferlist bl2; AioCompletion *my_completion2 = librados::Rados::aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe); ASSERT_EQ(0, striper.aio_read("IsSafePP", my_completion2, &bl2, sizeof(buf), 0)); { TestAlarm alarm; my_completion2->wait_for_complete(); } ASSERT_EQ(0, memcmp(buf, bl2.c_str(), sizeof(buf))); sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); my_completion->release(); my_completion2->release(); } TEST_F(StriperTest, RoundTripAppend) { AioTestData test_data; rados_completion_t my_completion, my_completion2, my_completion3; ASSERT_EQ(0, rados_aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe, &my_completion)); char buf[128]; memset(buf, 0xcc, sizeof(buf)); ASSERT_EQ(0, rados_striper_aio_append(striper, "RoundTripAppend", my_completion, buf, sizeof(buf))); { TestAlarm alarm; rados_aio_wait_for_complete(my_completion); } char buf2[128]; memset(buf2, 0xdd, sizeof(buf2)); ASSERT_EQ(0, rados_aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe, &my_completion2)); ASSERT_EQ(0, rados_striper_aio_append(striper, "RoundTripAppend", my_completion2, buf2, sizeof(buf))); { TestAlarm alarm; rados_aio_wait_for_complete(my_completion2); } char buf3[sizeof(buf) + sizeof(buf2)]; memset(buf3, 0, sizeof(buf3)); ASSERT_EQ(0, rados_aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe, &my_completion3)); ASSERT_EQ(0, rados_striper_aio_read(striper, "RoundTripAppend", my_completion3, buf3, sizeof(buf3), 0)); { TestAlarm alarm; rados_aio_wait_for_complete(my_completion3); } ASSERT_EQ((int)(sizeof(buf) + sizeof(buf2)), rados_aio_get_return_value(my_completion3)); ASSERT_EQ(0, memcmp(buf3, buf, sizeof(buf))); ASSERT_EQ(0, memcmp(buf3 + sizeof(buf), buf2, sizeof(buf2))); sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); rados_aio_release(my_completion); rados_aio_release(my_completion2); rados_aio_release(my_completion3); } TEST_F(StriperTestPP, RoundTripAppendPP) { AioTestData test_data; AioCompletion *my_completion = librados::Rados::aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe); char buf[128]; memset(buf, 0xcc, sizeof(buf)); bufferlist bl1; bl1.append(buf, sizeof(buf)); ASSERT_EQ(0, striper.aio_append("RoundTripAppendPP", my_completion, bl1, sizeof(buf))); { TestAlarm alarm; my_completion->wait_for_complete(); } char buf2[128]; memset(buf2, 0xdd, sizeof(buf2)); bufferlist bl2; bl2.append(buf2, sizeof(buf2)); AioCompletion *my_completion2 = librados::Rados::aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe); ASSERT_EQ(0, striper.aio_append("RoundTripAppendPP", my_completion2, bl2, sizeof(buf2))); { TestAlarm alarm; my_completion2->wait_for_complete(); } bufferlist bl3; AioCompletion *my_completion3 = librados::Rados::aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe); ASSERT_EQ(0, striper.aio_read("RoundTripAppendPP", my_completion3, &bl3, 2 * sizeof(buf), 0)); { TestAlarm alarm; my_completion3->wait_for_complete(); } ASSERT_EQ(sizeof(buf) + sizeof(buf2), (unsigned)my_completion3->get_return_value()); ASSERT_EQ(0, memcmp(bl3.c_str(), buf, sizeof(buf))); ASSERT_EQ(0, memcmp(bl3.c_str() + sizeof(buf), buf2, sizeof(buf2))); sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); my_completion->release(); my_completion2->release(); my_completion3->release(); } TEST_F(StriperTest, Flush) { AioTestData test_data; rados_completion_t my_completion; ASSERT_EQ(0, rados_aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe, &my_completion)); char buf[128]; memset(buf, 0xee, sizeof(buf)); ASSERT_EQ(0, rados_striper_aio_write(striper, "Flush", my_completion, buf, sizeof(buf), 0)); rados_striper_aio_flush(striper); char buf2[128]; memset(buf2, 0, sizeof(buf2)); rados_completion_t my_completion2; ASSERT_EQ(0, rados_aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe, &my_completion2)); ASSERT_EQ(0, rados_striper_aio_read(striper, "Flush", my_completion2, buf2, sizeof(buf2), 0)); { TestAlarm alarm; rados_aio_wait_for_complete(my_completion2); } ASSERT_EQ(0, memcmp(buf, buf2, sizeof(buf))); sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); rados_aio_release(my_completion); rados_aio_release(my_completion2); } TEST_F(StriperTestPP, FlushPP) { AioTestData test_data; AioCompletion *my_completion = librados::Rados::aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe); char buf[128]; memset(buf, 0xee, sizeof(buf)); bufferlist bl1; bl1.append(buf, sizeof(buf)); ASSERT_EQ(0, striper.aio_write("FlushPP", my_completion, bl1, sizeof(buf), 0)); striper.aio_flush(); bufferlist bl2; AioCompletion *my_completion2 = librados::Rados::aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe); ASSERT_EQ(0, striper.aio_read("FlushPP", my_completion2, &bl2, sizeof(buf), 0)); { TestAlarm alarm; my_completion2->wait_for_complete(); } ASSERT_EQ(0, memcmp(buf, bl2.c_str(), sizeof(buf))); sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); my_completion->release(); my_completion2->release(); } TEST_F(StriperTest, RoundTripWriteFull) { AioTestData test_data; rados_completion_t my_completion, my_completion2, my_completion3; ASSERT_EQ(0, rados_aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe, &my_completion)); char buf[128]; memset(buf, 0xcc, sizeof(buf)); ASSERT_EQ(0, rados_striper_aio_write(striper, "RoundTripWriteFull", my_completion, buf, sizeof(buf), 0)); { TestAlarm alarm; rados_aio_wait_for_complete(my_completion); } char buf2[64]; memset(buf2, 0xdd, sizeof(buf2)); ASSERT_EQ(0, rados_aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe, &my_completion2)); ASSERT_EQ(0, rados_striper_aio_write_full(striper, "RoundTripWriteFull", my_completion2, buf2, sizeof(buf2))); { TestAlarm alarm; rados_aio_wait_for_complete(my_completion2); } char buf3[sizeof(buf) + sizeof(buf2)]; memset(buf3, 0, sizeof(buf3)); ASSERT_EQ(0, rados_aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe, &my_completion3)); ASSERT_EQ(0, rados_striper_aio_read(striper, "RoundTripWriteFull", my_completion3, buf3, sizeof(buf3), 0)); { TestAlarm alarm; rados_aio_wait_for_complete(my_completion3); } ASSERT_EQ(sizeof(buf2), (unsigned)rados_aio_get_return_value(my_completion3)); ASSERT_EQ(0, memcmp(buf3, buf2, sizeof(buf2))); sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); rados_aio_release(my_completion); rados_aio_release(my_completion2); rados_aio_release(my_completion3); } TEST_F(StriperTestPP, RoundTripWriteFullPP) { AioTestData test_data; AioCompletion *my_completion = librados::Rados::aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe); char buf[128]; memset(buf, 0xcc, sizeof(buf)); bufferlist bl1; bl1.append(buf, sizeof(buf)); ASSERT_EQ(0, striper.aio_write("RoundTripWriteFullPP", my_completion, bl1, sizeof(buf), 0)); { TestAlarm alarm; my_completion->wait_for_complete(); } char buf2[64]; memset(buf2, 0xdd, sizeof(buf2)); bufferlist bl2; bl2.append(buf2, sizeof(buf2)); AioCompletion *my_completion2 = librados::Rados::aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe); ASSERT_EQ(0, striper.aio_write_full("RoundTripWriteFullPP", my_completion2, bl2)); { TestAlarm alarm; my_completion2->wait_for_complete(); } bufferlist bl3; AioCompletion *my_completion3 = librados::Rados::aio_create_completion ((void*)&test_data, set_completion_complete, set_completion_safe); ASSERT_EQ(0, striper.aio_read("RoundTripWriteFullPP", my_completion3, &bl3, sizeof(buf), 0)); { TestAlarm alarm; my_completion3->wait_for_complete(); } ASSERT_EQ(sizeof(buf2), (unsigned)my_completion3->get_return_value()); ASSERT_EQ(0, memcmp(bl3.c_str(), buf2, sizeof(buf2))); sem_wait(test_data.m_sem); sem_wait(test_data.m_sem); my_completion->release(); my_completion2->release(); my_completion3->release(); } TEST_F(StriperTest, RemoveTest) { char buf[128]; char buf2[sizeof(buf)]; // create oabject memset(buf, 0xaa, sizeof(buf)); ASSERT_EQ(0, rados_striper_write(striper, "RemoveTest", buf, sizeof(buf), 0)); // async remove it AioTestData test_data; rados_completion_t my_completion; ASSERT_EQ(0, rados_aio_create_completion((void*)&test_data, set_completion_complete, set_completion_safe, &my_completion)); ASSERT_EQ(0, rados_striper_aio_remove(striper, "RemoveTest", my_completion)); { TestAlarm alarm; ASSERT_EQ(0, rados_aio_wait_for_complete(my_completion)); } ASSERT_EQ(0, rados_aio_get_return_value(my_completion)); rados_aio_release(my_completion); // check we get ENOENT on reading ASSERT_EQ(-ENOENT, rados_striper_read(striper, "RemoveTest", buf2, sizeof(buf2), 0)); } TEST_F(StriperTestPP, RemoveTestPP) { char buf[128]; memset(buf, 0xaa, sizeof(buf)); bufferlist bl; bl.append(buf, sizeof(buf)); ASSERT_EQ(0, striper.write("RemoveTestPP", bl, sizeof(buf), 0)); AioCompletion *my_completion = cluster.aio_create_completion(0, 0, 0); ASSERT_EQ(0, striper.aio_remove("RemoveTestPP", my_completion)); { TestAlarm alarm; ASSERT_EQ(0, my_completion->wait_for_complete()); } ASSERT_EQ(0, my_completion->get_return_value()); bufferlist bl2; ASSERT_EQ(-ENOENT, striper.read("RemoveTestPP", &bl2, sizeof(buf), 0)); my_completion->release(); }
34.982201
112
0.736251
rpratap-bot
6c3ef40794a4151be768318ac2f28bfc81321042
1,259
cpp
C++
src/platform/vulkan/descriptor_set_layout.cpp
PedroSFreire/LiftPR.Version
61e8e135335e3c4def80f345548620db95f1662d
[ "BSD-3-Clause" ]
30
2019-07-24T09:58:22.000Z
2021-09-03T08:20:22.000Z
src/platform/vulkan/descriptor_set_layout.cpp
PedroSFreire/LiftPR.Version
61e8e135335e3c4def80f345548620db95f1662d
[ "BSD-3-Clause" ]
15
2020-06-20T13:20:50.000Z
2021-04-26T16:05:33.000Z
src/platform/vulkan/descriptor_set_layout.cpp
PedroSFreire/LiftPR.Version
61e8e135335e3c4def80f345548620db95f1662d
[ "BSD-3-Clause" ]
5
2020-06-17T08:38:34.000Z
2021-09-08T22:14:02.000Z
#include "descriptor_set_layout.h" #include "device.h" namespace vulkan { DescriptorSetLayout::DescriptorSetLayout(const Device& device, const std::vector<DescriptorBinding>& descriptor_bindings) : device_(device) { std::vector<VkDescriptorSetLayoutBinding> layout_bindings; for (const auto& binding : descriptor_bindings) { VkDescriptorSetLayoutBinding b = {}; b.binding = binding.Binding; b.descriptorCount = binding.DescriptorCount; b.descriptorType = binding.Type; b.stageFlags = binding.Stage; layout_bindings.push_back(b); } VkDescriptorSetLayoutCreateInfo layout_info = {}; layout_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layout_info.bindingCount = static_cast<uint32_t>(layout_bindings.size()); layout_info.pBindings = layout_bindings.data(); vulkanCheck(vkCreateDescriptorSetLayout(device.handle(), &layout_info, nullptr, &layout_), "create descriptor set layout"); } DescriptorSetLayout::~DescriptorSetLayout() { if (layout_ != nullptr) { vkDestroyDescriptorSetLayout(device_.handle(), layout_, nullptr); layout_ = nullptr; } } } // namespace vulkan
33.131579
101
0.69579
PedroSFreire
6c45a4713441b34549eb3b35a4cca840641e279f
1,700
cpp
C++
Source/StealthyAssessment/EnemyPatrolAIController.cpp
Zero-One101/StealthyAssessment
db79768bc13cfdf0cf282ca391366b087595ef61
[ "MIT" ]
null
null
null
Source/StealthyAssessment/EnemyPatrolAIController.cpp
Zero-One101/StealthyAssessment
db79768bc13cfdf0cf282ca391366b087595ef61
[ "MIT" ]
null
null
null
Source/StealthyAssessment/EnemyPatrolAIController.cpp
Zero-One101/StealthyAssessment
db79768bc13cfdf0cf282ca391366b087595ef61
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "StealthyAssessment.h" #include "EnemyPatrol.h" #include "Runtime/Engine/Classes/Components/SkeletalMeshComponent.h" #include "EnemyPatrolAIController.h" AEnemyPatrolAIController::AEnemyPatrolAIController(const class FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } void AEnemyPatrolAIController::BeginPlay() { // Set the player variable equal to the first player Player = (AStealthyAssessmentCharacter*) GetWorld()->GetFirstPlayerController(); if (Player) { // Set the player as the current target SetFocus(Player); // Make the owning actor move towards the player MoveToActor(Player); } Super::BeginPlay(); } void AEnemyPatrolAIController::Tick(float DeltaSeconds) { // Rotate the owning actor to face the player UpdateControlRotation(DeltaSeconds); } void AEnemyPatrolAIController::OnMoveCompleted(FAIRequestID RequestID, EPathFollowingResult::Type Result) { // Get the owning actor and cast it to an AEnemyPatrol pointer AEnemyPatrol* owner = (AEnemyPatrol*)GetPawn(); TArray<USkeletalMeshComponent*> Components; if (owner) { // Get all USkeletalMeshComponents from the owning actor and store them in the TArray owner->GetComponents<USkeletalMeshComponent>(Components); if (Components.Num() > 0) { // AEnemyPatrol only has one USkeletalMeshComponent, so we can just cast the first element in the array USkeletalMeshComponent* bodyMeshComponent = Components[0]; if (bodyMeshComponent) { // Make AI ragdoll on collision bodyMeshComponent->SetSimulatePhysics(true); bodyMeshComponent->WakeAllRigidBodies(); } } } }
27.868852
128
0.768235
Zero-One101
6c49f80670b81396fae894b8de0907946e9209a6
3,267
cpp
C++
Mendel's First Law.cpp
RonitPrasad1/Project_Rosalind-
59c59f6820b858f0dc08d62b2629a608d477ddb2
[ "MIT" ]
1
2022-03-22T22:33:14.000Z
2022-03-22T22:33:14.000Z
Mendel's First Law.cpp
RonitPrasad1/Project_Rosalind-
59c59f6820b858f0dc08d62b2629a608d477ddb2
[ "MIT" ]
null
null
null
Mendel's First Law.cpp
RonitPrasad1/Project_Rosalind-
59c59f6820b858f0dc08d62b2629a608d477ddb2
[ "MIT" ]
null
null
null
//Mendel's First Law: Not checked #include <iostream> #include <string> auto main(int argc, const char* argv[]) -> decltype ( 0 ) { std::cout << "Sample Dataset: " << '\n'; std::string RNA; std::cin >> RNA; int RNALength = RNA.size(); for (int64_t i = 0; i < RNALength; ++i) { if (RNA[i] == 'UUU' && RNA[i] == 'UUC') { RNA[i] = 'F'; } else if (RNA[i] == 'UUA' && RNA[i] == 'UUG') { RNA[i] = 'L'; } else if (RNA[i] == 'UCU' && RNA[i] == 'UCC' && RNA[i] == 'UCA' && RNA[i] == 'UCG' ) { RNA[i] = 'S'; } else if (RNA[i] == 'UAU' && RNA[i] == 'UAC') { RNA[i] = 'Y'; } else if (RNA[i] == 'UAA' && RNA[i] == 'UAG' && RNA[i] == 'UGA') { RNA[i] = 'Stop'; } else if (RNA[i] == 'UGU' && RNA[i] == 'UGC') { RNA[i] = 'C'; } else if (RNA[i] == 'UGG') { RNA[i] = 'W'; } else if (RNA[i] == 'CUU' && RNA[i] == 'CUC' && RNA[i] == 'CUA' && RNA[i] == 'CUG') { RNA[i] = 'L'; } else if (RNA[i] == 'CCU' && RNA[i] == 'CCC' && RNA[i] == 'CCA' && RNA[i] == 'CCG') { RNA[i] = 'P'; } else if (RNA[i] == 'CAU' && RNA[i] == 'CAC') { RNA[i] = 'H'; } else if (RNA[i] == 'CAA' && RNA[i] == 'CAG') { RNA[i] = 'Q'; } else if (RNA[i] == 'CGU' && RNA[i] == 'CGC' && RNA[i] == 'CGA' && RNA[i] == 'CGG') { RNA[i] = 'R'; } else if (RNA[i] == 'AUU' && RNA[i] == 'AUC' && RNA[i] == 'AUA') { RNA[i] = 'I'; } else if (RNA[i] == 'AUG') { RNA[i] = 'M'; } else if (RNA[i] == 'ACU' && RNA[i] == 'ACC' && RNA[i] == 'ACA' && RNA[i] == 'ACG') { RNA[i] = 'T'; } else if (RNA[i] == 'AAU' && RNA[i] == 'AAC') { RNA[i] = 'N'; } else if (RNA[i] == 'AAA' && RNA[i] == 'AAG') { RNA[i] = 'K'; } else if (RNA[i] == 'AGU' && RNA[i] == 'AGC') { RNA[i] = 'S'; } else if (RNA[i] == 'AGA' && RNA[i] == 'AGG') { RNA[i] = 'R'; } else if (RNA[i] == 'GUU' && RNA[i] == 'GUC' && RNA[i] == 'GUA' && RNA[i] == 'GUG') { RNA[i] = 'V'; } else if (RNA[i] == 'GCU' && RNA[i] == 'GCC' && RNA[i] == 'GCA' && RNA[i] == 'GCG') { RNA[i] = 'A'; } else if (RNA[i] == 'GAU' && RNA[i] == 'GAC') { RNA[i] = 'D'; } else if (RNA[i] == 'GAA' && RNA[i] == 'GAG') { RNA[i] = 'E'; } else if (RNA[i] == 'GGU' && RNA[i] == 'GGC' && RNA[i] == 'GGA' && RNA[i] == 'GGG') { RNA[i] = 'G'; } } std::cout << "Sample Output: " << '\n'; for (int64_t i = 0; i < RNALength; ++i) { std::cout << RNA[i]; } return 0; }
27.453782
92
0.289562
RonitPrasad1
6c4b5bbbe92433b8713488fec3f06cc8ca180722
2,938
cpp
C++
src/AddOns/GUI 020201/Family.cpp
clasqm/Squirrel99
09fb4cf9c26433b5bc1915dee1b31178222d9e81
[ "MIT" ]
2
2019-01-26T14:35:33.000Z
2020-03-31T10:39:39.000Z
src/AddOns/GUI 020201/Family.cpp
clasqm/Squirrel99
09fb4cf9c26433b5bc1915dee1b31178222d9e81
[ "MIT" ]
1
2018-12-12T17:04:17.000Z
2018-12-12T17:04:17.000Z
src/AddOns/GUI 020201/Family.cpp
clasqm/Squirrel99
09fb4cf9c26433b5bc1915dee1b31178222d9e81
[ "MIT" ]
1
2020-10-26T08:56:12.000Z
2020-10-26T08:56:12.000Z
/* * Squirrel project * * file ? Family.cpp * what ? Store all the font family & style * who ? jlv * when ? 11/21/99 * last ? 11/21/99 * * * (c) electron Technology 1999 */ #include "SQI-AddOn.h" #include "Family.h" typedef map<string,SQI_List *,less<string> > FFamilies; FFamilies Families; // global map of font families /* * function : InitFontFamilies * purpose : Get all the installed font * input : none * output : none * side effect : none */ void InitFontFamilies(SQI_Squirrel *squirrel) { int32 numStyles; int32 num_families = count_font_families(); font_family family; font_style style; uint32 flags; for(int32 i=0;i<num_families;i++) { if(get_font_family(i,&family,&flags)==B_OK) { numStyles = count_font_styles(family); SQI_List *lst = squirrel->LocalHeap->List(); lst->AddRef(); for(int32 j=0;j<numStyles;j++) { if(get_font_style(family,j,&style,&flags)==B_OK) lst->Add2End(squirrel->LocalHeap->String(style)); } Families[string(family)] = lst; } } } /* * function : GetFontFamilies * purpose : Get all the installed font in a list * input : * * SQI_List *list, the list to add the string in * * output : none * side effect : none */ void GetFontFamilies(SQI_List *list) { FFamilies::const_iterator i; for(i=Families.begin();i!=Families.end();i++) list->Add2End(list->heap->String(i->first)); } /* * function : GetFontStyles * purpose : Fill a list of all the style installed for a family * input : * * string *name, family name * * output : none * side effect : none */ SQI_List *GetFontStyles(string *name) { SQI_List *lst = NULL; lst = Families[*name]; if(!lst) Families.erase(*name); return lst; } /* * function : ExistFont * purpose : Return true if the font exist * input : * * string *name, family name * * output : bool * side effect : none */ bool ExistFont(string *name) { SQI_List *lst = NULL; lst = Families[*name]; if(!lst) { Families.erase(*name); return false; } else return true; } /* * function : ExistStyle * purpose : Return true if the style exist for a font * input : * * string *family, family name * string *style, style * * output : bool * side effect : none */ bool ExistStyle(font_family family,string *style) { SQI_List *lst = NULL; lst = Families[string(family)]; if(!lst) { Families.erase(string(family)); return false; } else { SQI_String *s; list<SQI_Object *>::const_iterator *i = lst->Iterator(); list<SQI_Object *>::const_iterator *e = lst->End(); for(i;*i!=*e;(*i)++) { s = IsString(*(*i)); if(*(s->Data()) == *style) break; } if(*i!=*e) { delete i; delete e; return true; } else { delete i; delete e; return false; } } }
17.282353
68
0.599387
clasqm
6c4d78ad738a07be087994f21a2be1c65d249b07
19,653
hpp
C++
libs/core/src/main/cpp/neurodidactic/core/arrays/detail/MdArrayCommon.hpp
tomault/neurodidactic
c2641d65ebe191667f945817227319f48388c55b
[ "Apache-2.0" ]
null
null
null
libs/core/src/main/cpp/neurodidactic/core/arrays/detail/MdArrayCommon.hpp
tomault/neurodidactic
c2641d65ebe191667f945817227319f48388c55b
[ "Apache-2.0" ]
null
null
null
libs/core/src/main/cpp/neurodidactic/core/arrays/detail/MdArrayCommon.hpp
tomault/neurodidactic
c2641d65ebe191667f945817227319f48388c55b
[ "Apache-2.0" ]
null
null
null
#ifndef __NEURODIDACTIC__CORE__ARRAYS__DETAIL__MDARRAYCOMMON_HPP__ #define __NEURODIDACTIC__CORE__ARRAYS__DETAIL__MDARRAYCOMMON_HPP__ #include <neurodidactic/core/arrays/DimensionList.hpp> #include <neurodidactic/core/arrays/AnyMdArray.hpp> #include <neurodidactic/core/arrays/detail/MklAdapter.hpp> #include <pistis/exceptions/ExceptionOrigin.hpp> #include <pistis/exceptions/IllegalValueError.hpp> namespace neurodidactic { namespace core { namespace arrays { namespace detail { template <typename DerivedArray, typename NewArray, typename ArraySlice, typename InnerProductResult, size_t ARRAY_ORDER, typename Field, typename Allocator> class MdArrayCommon : public AnyMdArray<DerivedArray> { protected: typedef typename std::allocator_traits<Allocator> ::template rebind_alloc<uint32_t> DimensionListAllocator; public: static constexpr const size_t ORDER = ARRAY_ORDER; typedef Field FieldType; typedef Allocator AllocatorType; typedef DimensionList<DimensionListAllocator> DimensionListType; typedef ArraySlice SliceType; typedef MdArrayCommon<DerivedArray, NewArray, ArraySlice, InnerProductResult, ARRAY_ORDER, Field, Allocator> ThisType; public: const AllocatorType& allocator() const { return this->self().allocator_(); } AllocatorType& allocator() { return this->self().allocator_(); } size_t size() const { return this->self().size_(); } size_t leadingDimension() const { return this->self().leadingDimension_(); } const DimensionListType& dimensions() const { return this->self().dimensions_(); } const Field* data() const { return this->self().data_(); } Field* data() { return this->self().data_(); } const Field* begin() const { return this->self().data_(); } Field* begin() { return this->self().data_(); } const Field* end() const { return this->self().end_(); } Field* end() { return this->self().end_(); } template <typename OtherArray, typename Enabled = typename std::enable_if< IsMdArray<OtherArray>::value, NewArray >::type > Enabled add(const OtherArray& other) const { validateDimensions_("Array \"other\"", other.dimensions(), PISTIS_EX_HERE); NewArray result(this->dimensions(), this->allocator()); return std::move(this->add(other, result)); } template <typename OtherArray, typename ResultArray, typename Enabled = typename std::enable_if< IsMdArray<OtherArray>::value && IsMdArray<ResultArray>::value, int >::type > ResultArray& add(const OtherArray& other, ResultArray& result, Enabled = 0) const { validateDimensions_("Array \"other\"", other.dimensions(), PISTIS_EX_HERE); validateDimensions_("Array \"result\"", result.dimensions(), PISTIS_EX_HERE); detail::MklAdapter<Field, typename OtherArray::FieldType>::add( this->size(), this->data(), other.data(), result.data() ); return result; } template <typename OtherArray, typename Enabled = typename std::enable_if<IsMdArray<OtherArray>::value, int >::type > DerivedArray& addInPlace(const OtherArray& other, Enabled = 0) { return this->add(other, this->self()); } template <typename OtherArray, typename Enabled = typename std::enable_if< IsMdArray<OtherArray>::value, NewArray >::type > Enabled scaleAndAdd(Field c, const OtherArray& other) const { validateDimensions_("Array \"other\"", other.dimensions(), PISTIS_EX_HERE); NewArray result(this->self()); return std::move(result.scaleAndAddInPlace(c, other)); } template <typename OtherArray, typename ResultArray, typename Enabled = typename std::enable_if< IsMdArray<OtherArray>::value && IsMdArray<ResultArray>::value, ResultArray >::type > Enabled& scaleAndAdd(Field c, const OtherArray& other, ResultArray& result) const { validateDimensions_("Array \"other\"", other.dimensions(), PISTIS_EX_HERE); validateDimensions_("Array \"result\"", result.dimensions(), PISTIS_EX_HERE); result = this->self(); return result.scaleAndAddInPlace(c, other); } template <typename OtherArray, typename Enabled = typename std::enable_if< IsMdArray<OtherArray>::value, int >::type > DerivedArray& scaleAndAddInPlace(Field c, const OtherArray& other, Enabled = 0) { validateDimensions_("Array \"other\"", other.dimensions(), PISTIS_EX_HERE); detail::MklAdapter<Field, typename OtherArray::FieldType>::scaleAndAdd( this->size(), c, other.data(), this->data() ); return this->self(); } template <typename OtherArray, typename Enabled = typename std::enable_if< IsMdArray<OtherArray>::value, NewArray >::type > Enabled scaleAndAdd(Field c1, Field c2, const OtherArray& other) const { validateDimensions_("Array \"other\"", other.dimensions(), PISTIS_EX_HERE); NewArray result(this->self()); return std::move(result.scaleAndAddInPlace(c1, c2, other)); } template <typename OtherArray, typename ResultArray, typename Enabled = typename std::enable_if< IsMdArray<OtherArray>::value && IsMdArray<ResultArray>::value, int >::type > ResultArray& scaleAndAdd(Field c1, Field c2, const OtherArray& other, ResultArray& result, Enabled = 0) const { validateDimensions_("Array \"other\"", other.dimensions(), PISTIS_EX_HERE); validateDimensions_("Array \"result\"", result.dimensions(), PISTIS_EX_HERE); result = this->self(); return result.scaleAndAddInPlace(c1, c2, other); } template <typename OtherArray, typename Enabled = typename std::enable_if<IsMdArray<OtherArray>::value, int >::type > DerivedArray& scaleAndAddInPlace(Field c1, Field c2, const OtherArray& other, Enabled = 0) { validateDimensions_("Array \"other\"", other.dimensions(), PISTIS_EX_HERE); detail::MklAdapter<Field, typename OtherArray::FieldType>::scaleAndAdd( this->size(), c2, other.data(), c1, this->data() ); return this->self(); } template <typename OtherArray, typename Enabled = typename std::enable_if< IsMdArray<OtherArray>::value, NewArray >::type > Enabled subtract(const OtherArray& other) const { validateDimensions_("array \"other\"", other.dimensions(), PISTIS_EX_HERE); NewArray result(dimensions(), allocator()); return std::move(this->subtract(other, result)); } template <typename OtherArray, typename ResultArray, typename Enabled = typename std::enable_if< IsMdArray<OtherArray>::value && IsMdArray<ResultArray>::value, int >::type > ResultArray& subtract(const OtherArray& other, ResultArray& result, Enabled = 0) const { validateDimensions_("array \"other\"", other.dimensions(), PISTIS_EX_HERE); validateDimensions_("array \"result\"", result.dimensions(), PISTIS_EX_HERE); detail::MklAdapter<Field, typename OtherArray::FieldType>::subtract( this->size(), this->data(), other.data(), result.data() ); return result; } template <typename OtherArray, typename Enabled = typename std::enable_if<IsMdArray<OtherArray>::value, int>::type > DerivedArray& subtractInPlace(const OtherArray& other, Enabled = 0) { return this->subtract(other, this->self()); } template <typename OtherArray, typename Enabled = typename std::enable_if< IsMdArray<OtherArray>::value, NewArray >::type > Enabled multiply(const OtherArray& other) const { validateDimensions_("array \"other\"", other.dimensions(), PISTIS_EX_HERE); NewArray result(dimensions(), allocator()); return std::move(this->multiply(other, result)); } template <typename OtherArray, typename ResultArray, typename Enabled = typename std::enable_if< IsMdArray<OtherArray>::value && IsMdArray<ResultArray>::value, int >::type > ResultArray& multiply(const OtherArray& other, ResultArray& result, Enabled = 0) const { validateDimensions_("array \"other\"", other.dimensions(), PISTIS_EX_HERE); validateDimensions_("array \"result\"", result.dimensions(), PISTIS_EX_HERE); detail::MklAdapter<Field, typename OtherArray::FieldType>::multiply( this->size(), this->data(), other.data(), result.data() ); return result; } template <typename OtherArray, typename Enabled = typename std::enable_if<IsMdArray<OtherArray>::value, int>::type > DerivedArray& multiplyInPlace(const OtherArray& other, Enabled = 0) { return this->multiply(other, this->self()); } NewArray multiply(Field c) const { NewArray result(this->self()); return std::move(result.multiplyInPlace(c)); } template <typename ResultArray, typename Enabled = typename std::enable_if<IsMdArray<ResultArray>::value, int>::type > ResultArray& multiply(Field c, ResultArray& result) const { validateDimensions_("Array \"result\"", result.dimensions(), PISTIS_EX_HERE); result = this->self(); return result.multiplyInPlace(c); } DerivedArray& multiplyInPlace(Field c) { detail::MklAdapter<Field, Field>::scale(this->size(), c, this->data()); return this->self(); } template <typename OtherArray, typename Enabled = typename std::enable_if< IsMdArray<OtherArray>::value, DerivedArray >::type > Enabled divide(const OtherArray& other) const { validateDimensions_("array \"other\"", other.dimensions(), PISTIS_EX_HERE); NewArray result(dimensions(), allocator()); return std::move(this->divide(other, result)); } template <typename OtherArray, typename ResultArray, typename Enabled = typename std::enable_if< IsMdArray<OtherArray>::value && IsMdArray<ResultArray>::value, int >::type > ResultArray& divide(const OtherArray& other, ResultArray& result, Enabled = 0) const { validateDimensions_("array \"other\"", other.dimensions(), PISTIS_EX_HERE); validateDimensions_("array \"result\"", result.dimensions(), PISTIS_EX_HERE); detail::MklAdapter<Field, typename OtherArray::FieldType>::divide( this->size(), this->data(), other.data(), result.data() ); return result; } template <typename OtherArray, typename Enabled = typename std::enable_if< IsMdArray<OtherArray>::value, int >::type > DerivedArray& divideInPlace(const OtherArray& other, Enabled = 0) { return this->divide(other, this->self()); } template <typename Vector, typename Enabled = typename std::enable_if< IsMdArray<Vector>::value && (Vector::ORDER == 1), InnerProductResult >::type > Enabled innerProduct(const Vector& v) const { this->validateInnerProductArgDimensions_("Vector \"v\"", v.dimensions(), PISTIS_EX_HERE); DimensionListType resultDimensions( this->dimensions().butLast(1) ); InnerProductResult result(resultDimensions, this->allocator()); return std::move(this->self().innerProduct(v, result)); } template <typename Vector, typename Enabled = typename std::enable_if< IsMdArray<Vector>::value && (Vector::ORDER == 1), InnerProductResult >::type > Enabled transposeInnerProduct(const Vector& v) const { this->validateTransposeInnerProductArgDimensions_("Vector \"v\"", v.dimensions(), PISTIS_EX_HERE); const DimensionListType resultDimensions = this->dimensions().remove(this->dimensions().size() - 2); InnerProductResult result(resultDimensions, this->allocator()); return std::move(this->self().transposeInnerProduct(v, result)); } template <typename Matrix, typename Enabled = typename std::enable_if< IsMdArray<Matrix>::value && (Matrix::ORDER == 2), NewArray >::type > Enabled matrixProduct(const Matrix& m) const { this->validateMatrixProductArgDimensions_("Matrix \"m\"", m.dimensions(), PISTIS_EX_HERE); DimensionListType resultDimensions( this->dimensions().replaceLast(m.dimensions()[1]) ); NewArray result(resultDimensions, this->allocator()); return std::move(this->self().matrixProduct(m, result)); } template <typename Function> NewArray map(const Function& f) const { NewArray result(this->dimensions(), this->allocator()); return std::move(this->map(f, result)); } template <typename Function, typename ResultArray, typename Enabled = typename std::enable_if< IsMdArray<ResultArray>::value && (ResultArray::ORDER == ARRAY_ORDER), ResultArray >::type > Enabled& map(const Function& f, ResultArray& result) const { if (result.dimensions() != this->dimensions()) { std::ostringstream msg; msg << "Array \"result\" has incorrect dimensions " << result.dimensions() << " -- it should have dimensions " << this->dimensions(); throw pistis::exceptions::IllegalValueError(msg.str(), PISTIS_EX_HERE); } auto p = this->data(); auto q = result.data(); #pragma omp parallel for { for (size_t i = 0; i < this->size(); ++i) { q[i] = f(p[i]); } } return result; } template <typename Function> DerivedArray& mapInPlace(Function f) { return this->map(f, this->self()); } // const SliceType operator[](size_t n) const { // return self()->slice_(n); // } // SliceType operator[](size_t n) { // return self()->slice_(n); // } protected: void validateDimensions_( const std::string& name, const DimensionListType& d, const pistis::exceptions::ExceptionOrigin& origin ) const { if (d != this->dimensions()) { std::ostringstream msg; msg << name << " has incorrect dimensions " << d << ". It should have dimensions " << this->dimensions(); throw pistis::exceptions::IllegalValueError(msg.str(), origin); } } void validateInnerProductArgDimensions_( const std::string& name, const DimensionListType& dimensions, const pistis::exceptions::ExceptionOrigin& origin ) const { const size_t lastDimension = this->dimensions().back(); if ((dimensions.size() != 1) || (dimensions[0] != lastDimension)) { std::ostringstream msg; msg << name << " has dimensions " << dimensions << ", but it should have dimension [ " << lastDimension << " ]"; throw pistis::exceptions::IllegalValueError(msg.str(), origin); } } void validateInnerProductResultDimensions_( const std::string& name, const DimensionListType& dimensions, const pistis::exceptions::ExceptionOrigin& origin ) const { const DimensionListType targetDimensions = this->dimensions().butLast(1); if (dimensions != targetDimensions) { std::ostringstream msg; msg << name << " has dimensions " << dimensions << ", but it should have dimensions " << targetDimensions; throw pistis::exceptions::IllegalValueError(msg.str(), origin); } } void validateMatrixProductArgDimensions_( const std::string& name, const DimensionListType& dimensions, const pistis::exceptions::ExceptionOrigin& origin ) const { if (dimensions.size() != 2) { std::ostringstream msg; msg << name << " is not a matrix. It is an array with order " << dimensions.size(); throw pistis::exceptions::IllegalValueError(msg.str(), origin); } if (dimensions[0] != this->self().dimensions().back()) { std::ostringstream msg; msg << name << " has incorrect dimensions " << dimensions << " -- the first dimension must match the last dimension" << " of this array (which is " << this->self().dimensions().back() << ")"; throw pistis::exceptions::IllegalValueError(msg.str(), origin); } } void validateMatrixProductResultDimensions_( const std::string& name, const DimensionListType& argDimensions, const DimensionListType& resultDimensions, const pistis::exceptions::ExceptionOrigin& origin ) const { const DimensionListType targetDimensions = this->self().dimensions().replaceLast(argDimensions[1]); if (resultDimensions != targetDimensions) { std::ostringstream msg; msg << name << " has incorrect dimensions " << targetDimensions << " -- it should have dimensions " << resultDimensions; throw pistis::exceptions::IllegalValueError(msg.str(), origin); } } void validateOuterProductDimensions_( const std::string& name, const DimensionListType& argDimensions, const DimensionListType& resultDimensions, const pistis::exceptions::ExceptionOrigin& origin ) const { const DimensionListType targetDimensions = argDimensions.insert(argDimensions.size() - 1, this->self().dimensions().back()); if (targetDimensions != resultDimensions) { std::ostringstream msg; msg << name << " has incorrect dimensions " << resultDimensions << " -- it should have dimensions " << targetDimensions; throw pistis::exceptions::IllegalValueError(msg.str(), origin); } } void validateTransposeInnerProductArgDimensions_( const std::string& name, const DimensionListType& argDimensions, const pistis::exceptions::ExceptionOrigin& origin ) const { if (this->self().dimensions().back(1) != argDimensions.front()) { std::ostringstream msg; msg << name << " has incorrect dimensions " << argDimensions << " -- it should have dimensions [ " << this->self().dimensions().back(1) << " ]"; throw pistis::exceptions::IllegalValueError(msg.str(), origin); } } void validateTransposeInnerProductResultDimensions_( const std::string& name, const DimensionListType& argDimensions, const DimensionListType& resultDimensions, const pistis::exceptions::ExceptionOrigin& origin ) const { const size_t n = this->self().dimensions().size(); const DimensionListType targetDimensions = this->self().dimensions().remove(n - 2); if (targetDimensions != resultDimensions) { std::ostringstream msg; msg << name << " has incorrect dimensions " << resultDimensions << " -- it should have dimensions " << targetDimensions; throw pistis::exceptions::IllegalValueError(msg.str(), origin); } } }; } } } } #endif
32.646179
76
0.630235
tomault
6c512fe4376cea6471f0a497a0d39039b8606b8d
6,256
cpp
C++
Engine/ModuleResource.cpp
Beautiful-Engines/Engine
fab1b2415d63218078cc6f2b2a33676e9ef45543
[ "MIT" ]
null
null
null
Engine/ModuleResource.cpp
Beautiful-Engines/Engine
fab1b2415d63218078cc6f2b2a33676e9ef45543
[ "MIT" ]
null
null
null
Engine/ModuleResource.cpp
Beautiful-Engines/Engine
fab1b2415d63218078cc6f2b2a33676e9ef45543
[ "MIT" ]
null
null
null
#include "Application.h" #include "ModuleFileSystem.h" #include "ModuleImport.h" #include "ModuleResource.h" #include "ModuleScene.h" #include "ImportMesh.h" #include "ResourceMesh.h" #include "ImportTexture.h" #include "ResourceTexture.h" #include "ImportModel.h" #include "ResourceModel.h" #include "ImportAnimation.h" #include "ResourceAnimation.h" #include "ResourceBone.h" #include "Primitive.h" #include <fstream> ModuleResource::ModuleResource(bool start_enabled) : Module(start_enabled) { name = "Resource"; } ModuleResource::~ModuleResource() { } bool ModuleResource::Start() { LOG("importing all assets"); return true; } Resource* ModuleResource::CreateResource(const char* extension, uint UID) { Resource* r = nullptr; if (extension == OUR_MESH_EXTENSION) { r = new ResourceMesh(); } else if (extension == OUR_TEXTURE_EXTENSION) { r = new ResourceTexture(); } else if (extension == OUR_MODEL_EXTENSION) { r = new ResourceModel(); } else if (extension == OUR_ANIMATION_EXTENSION) { r = new ResourceAnimation(); } else if (extension == OUR_BONE_EXTENSION) { r = new ResourceBone(); } if (r != nullptr && UID != 0) { r->SetId(UID); } if (r != nullptr) resources.emplace(r->GetId(), r); return r; } Resource* ModuleResource::Get(uint _UID) { std::map<uint, Resource*>::iterator it = resources.find(_UID); if (it != resources.end()) return it->second; return nullptr; } Resource* ModuleResource::GetAndUse(uint _UID) { std::map<uint, Resource*>::iterator it = resources.find(_UID); if (it != resources.end()) { it->second->SetCantities(1); return it->second; } return nullptr; } uint ModuleResource::GetId(std::string _file) { for (std::map<uint, Resource*>::iterator it = resources.begin(); it != resources.end(); ++it) { if (it->second->GetName() == _file) return it->first; } return 0; } std::map<uint, Resource*> ModuleResource::GetResources() { return resources; } void ModuleResource::LoadAllAssets() { App->importer->import_texture->DefaultTexture(); LoadByFolder(ASSETS_FOLDER); // just for delivery, then delete it std::string path = "skeleton@idle.fbx"; path = ASSETS_FOLDER + path; GameObject* go = App->importer->import_model->CreateModel((ResourceModel*)App->resource->GetAndUse(App->resource->GetId(path.c_str()))); go->SetStatic(false); go->GetTransform()->SetLocalScale({ 0.3, 0.3, 0.3 }); go->SetStatic(true); path = "skeleton@attack.fbx"; path = ASSETS_FOLDER + path; go = App->importer->import_model->CreateModel((ResourceModel*)App->resource->GetAndUse(App->resource->GetId(path.c_str()))); path = "skeleton@run.fbx"; path = ASSETS_FOLDER + path; go = App->importer->import_model->CreateModel((ResourceModel*)App->resource->GetAndUse(App->resource->GetId(path.c_str()))); path = "street environment_v01.fbx"; path = ASSETS_FOLDER + path; App->importer->import_model->CreateModel((ResourceModel*)App->resource->GetAndUse(App->resource->GetId(path.c_str()))); } void ModuleResource::LoadByFolder(const char* _folder) { std::vector<std::string> files_temp; std::vector<std::string> files; std::vector<std::string> directories; App->file_system->DiscoverFiles(_folder, files_temp, directories); for (int i = 0; i < files_temp.size(); ++i) { if (files_temp[i].find(".meta") > 1000) files.push_back(files_temp[i]); } std::vector<std::string>::iterator iterator = files.begin(); for (; iterator != files.end(); ++iterator) { if (first_textures && (*iterator).find(".fbx") > 1000) { App->file_system->SplitFilePath((*iterator).c_str(), nullptr, nullptr); App->importer->ImportFile((_folder + (*iterator)).c_str(), false, true); } else if (!first_textures && (*iterator).find(".fbx") < 1000) { App->file_system->SplitFilePath((*iterator).c_str(), nullptr, nullptr); App->importer->ImportFile((_folder + (*iterator)).c_str(), false, true); } } std::vector<std::string>::iterator iterator2 = directories.begin(); for (; iterator2 != directories.end(); ++iterator2) { std::string folder = _folder + (*iterator2) + "/"; LoadByFolder(folder.c_str()); } if (first_textures) { first_textures = false; LoadByFolder(ASSETS_FOLDER); } } void ModuleResource::LoadFile(const char * _path) { if (!App->resource->GetId(_path)) { std::string spath = _path; std::ifstream ifstream(spath); nlohmann::json json = nlohmann::json::parse(ifstream); uint UID = json["id"]; std::string exported_file = json["exported_file"]; std::string name = json["name"]; std::string extension; App->file_system->SplitFilePath(exported_file.c_str(), nullptr, nullptr, &extension); Resource *resource = nullptr; if ("." + extension == OUR_MESH_EXTENSION) { resource = CreateResource(OUR_MESH_EXTENSION, UID); resource->SetFile(exported_file); resource->SetName(name); App->importer->import_mesh->LoadMeshFromResource((ResourceMesh*)resource); } else if ("." + extension == OUR_TEXTURE_EXTENSION) { resource = CreateResource(OUR_TEXTURE_EXTENSION, UID); resource->SetName(name); App->importer->import_texture->LoadTexture(exported_file.c_str(), nullptr, (ResourceTexture*)resource); } else if ("." + extension == OUR_MODEL_EXTENSION) { resource = CreateResource(OUR_MODEL_EXTENSION, UID); resource->SetFile(exported_file); resource->SetName(name); ResourceModel* resource_model = (ResourceModel*)resource; for (nlohmann::json::iterator iterator = json.find("animations").value().begin(); iterator != json.find("animations").value().end(); ++iterator) { resource_model->animations.push_back((*iterator)["id"]); } App->importer->import_model->LoadModel(resource_model); } else if ("." + extension == OUR_ANIMATION_EXTENSION) { resource = CreateResource(OUR_ANIMATION_EXTENSION, UID); resource->SetFile(exported_file); resource->SetName(name); App->importer->import_animation->LoadAnimationFromResource((ResourceAnimation*)resource); } else if ("." + extension == OUR_BONE_EXTENSION) { resource = CreateResource(OUR_BONE_EXTENSION, UID); resource->SetFile(exported_file); resource->SetName(name); App->importer->import_animation->LoadBoneFromResource((ResourceBone*)resource); } } }
26.621277
147
0.69773
Beautiful-Engines
6c5800eafdeba2139ef403adc4b7835b9c6a2a46
26,336
cc
C++
google/cloud/channel/internal/cloud_channel_stub.cc
GoogleCloudPlatform/google-cloud-cpp
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
[ "Apache-2.0" ]
80
2017-11-24T00:19:45.000Z
2019-01-25T10:24:33.000Z
google/cloud/channel/internal/cloud_channel_stub.cc
GoogleCloudPlatform/google-cloud-cpp
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
[ "Apache-2.0" ]
1,579
2017-11-24T01:01:21.000Z
2019-01-28T23:41:21.000Z
google/cloud/channel/internal/cloud_channel_stub.cc
GoogleCloudPlatform/google-cloud-cpp
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
[ "Apache-2.0" ]
51
2017-11-24T00:56:11.000Z
2019-01-18T20:35:02.000Z
// Copyright 2022 Google LLC // // 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 // // https://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. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/channel/v1/service.proto #include "google/cloud/channel/internal/cloud_channel_stub.h" #include "google/cloud/grpc_error_delegate.h" #include "google/cloud/status_or.h" #include <google/cloud/channel/v1/service.grpc.pb.h> #include <google/longrunning/operations.grpc.pb.h> #include <memory> namespace google { namespace cloud { namespace channel_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN CloudChannelServiceStub::~CloudChannelServiceStub() = default; StatusOr<google::cloud::channel::v1::ListCustomersResponse> DefaultCloudChannelServiceStub::ListCustomers( grpc::ClientContext& client_context, google::cloud::channel::v1::ListCustomersRequest const& request) { google::cloud::channel::v1::ListCustomersResponse response; auto status = grpc_stub_->ListCustomers(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::Customer> DefaultCloudChannelServiceStub::GetCustomer( grpc::ClientContext& client_context, google::cloud::channel::v1::GetCustomerRequest const& request) { google::cloud::channel::v1::Customer response; auto status = grpc_stub_->GetCustomer(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::CheckCloudIdentityAccountsExistResponse> DefaultCloudChannelServiceStub::CheckCloudIdentityAccountsExist( grpc::ClientContext& client_context, google::cloud::channel::v1::CheckCloudIdentityAccountsExistRequest const& request) { google::cloud::channel::v1::CheckCloudIdentityAccountsExistResponse response; auto status = grpc_stub_->CheckCloudIdentityAccountsExist(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::Customer> DefaultCloudChannelServiceStub::CreateCustomer( grpc::ClientContext& client_context, google::cloud::channel::v1::CreateCustomerRequest const& request) { google::cloud::channel::v1::Customer response; auto status = grpc_stub_->CreateCustomer(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::Customer> DefaultCloudChannelServiceStub::UpdateCustomer( grpc::ClientContext& client_context, google::cloud::channel::v1::UpdateCustomerRequest const& request) { google::cloud::channel::v1::Customer response; auto status = grpc_stub_->UpdateCustomer(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } Status DefaultCloudChannelServiceStub::DeleteCustomer( grpc::ClientContext& client_context, google::cloud::channel::v1::DeleteCustomerRequest const& request) { google::protobuf::Empty response; auto status = grpc_stub_->DeleteCustomer(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return google::cloud::Status(); } StatusOr<google::cloud::channel::v1::Customer> DefaultCloudChannelServiceStub::ImportCustomer( grpc::ClientContext& client_context, google::cloud::channel::v1::ImportCustomerRequest const& request) { google::cloud::channel::v1::Customer response; auto status = grpc_stub_->ImportCustomer(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } future<StatusOr<google::longrunning::Operation>> DefaultCloudChannelServiceStub::AsyncProvisionCloudIdentity( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::channel::v1::ProvisionCloudIdentityRequest const& request) { return cq.MakeUnaryRpc( [this](grpc::ClientContext* context, google::cloud::channel::v1::ProvisionCloudIdentityRequest const& request, grpc::CompletionQueue* cq) { return grpc_stub_->AsyncProvisionCloudIdentity(context, request, cq); }, request, std::move(context)); } StatusOr<google::cloud::channel::v1::ListEntitlementsResponse> DefaultCloudChannelServiceStub::ListEntitlements( grpc::ClientContext& client_context, google::cloud::channel::v1::ListEntitlementsRequest const& request) { google::cloud::channel::v1::ListEntitlementsResponse response; auto status = grpc_stub_->ListEntitlements(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::ListTransferableSkusResponse> DefaultCloudChannelServiceStub::ListTransferableSkus( grpc::ClientContext& client_context, google::cloud::channel::v1::ListTransferableSkusRequest const& request) { google::cloud::channel::v1::ListTransferableSkusResponse response; auto status = grpc_stub_->ListTransferableSkus(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::ListTransferableOffersResponse> DefaultCloudChannelServiceStub::ListTransferableOffers( grpc::ClientContext& client_context, google::cloud::channel::v1::ListTransferableOffersRequest const& request) { google::cloud::channel::v1::ListTransferableOffersResponse response; auto status = grpc_stub_->ListTransferableOffers(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::Entitlement> DefaultCloudChannelServiceStub::GetEntitlement( grpc::ClientContext& client_context, google::cloud::channel::v1::GetEntitlementRequest const& request) { google::cloud::channel::v1::Entitlement response; auto status = grpc_stub_->GetEntitlement(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } future<StatusOr<google::longrunning::Operation>> DefaultCloudChannelServiceStub::AsyncCreateEntitlement( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::channel::v1::CreateEntitlementRequest const& request) { return cq.MakeUnaryRpc( [this]( grpc::ClientContext* context, google::cloud::channel::v1::CreateEntitlementRequest const& request, grpc::CompletionQueue* cq) { return grpc_stub_->AsyncCreateEntitlement(context, request, cq); }, request, std::move(context)); } future<StatusOr<google::longrunning::Operation>> DefaultCloudChannelServiceStub::AsyncChangeParameters( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::channel::v1::ChangeParametersRequest const& request) { return cq.MakeUnaryRpc( [this](grpc::ClientContext* context, google::cloud::channel::v1::ChangeParametersRequest const& request, grpc::CompletionQueue* cq) { return grpc_stub_->AsyncChangeParameters(context, request, cq); }, request, std::move(context)); } future<StatusOr<google::longrunning::Operation>> DefaultCloudChannelServiceStub::AsyncChangeRenewalSettings( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::channel::v1::ChangeRenewalSettingsRequest const& request) { return cq.MakeUnaryRpc( [this](grpc::ClientContext* context, google::cloud::channel::v1::ChangeRenewalSettingsRequest const& request, grpc::CompletionQueue* cq) { return grpc_stub_->AsyncChangeRenewalSettings(context, request, cq); }, request, std::move(context)); } future<StatusOr<google::longrunning::Operation>> DefaultCloudChannelServiceStub::AsyncChangeOffer( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::channel::v1::ChangeOfferRequest const& request) { return cq.MakeUnaryRpc( [this](grpc::ClientContext* context, google::cloud::channel::v1::ChangeOfferRequest const& request, grpc::CompletionQueue* cq) { return grpc_stub_->AsyncChangeOffer(context, request, cq); }, request, std::move(context)); } future<StatusOr<google::longrunning::Operation>> DefaultCloudChannelServiceStub::AsyncStartPaidService( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::channel::v1::StartPaidServiceRequest const& request) { return cq.MakeUnaryRpc( [this](grpc::ClientContext* context, google::cloud::channel::v1::StartPaidServiceRequest const& request, grpc::CompletionQueue* cq) { return grpc_stub_->AsyncStartPaidService(context, request, cq); }, request, std::move(context)); } future<StatusOr<google::longrunning::Operation>> DefaultCloudChannelServiceStub::AsyncSuspendEntitlement( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::channel::v1::SuspendEntitlementRequest const& request) { return cq.MakeUnaryRpc( [this]( grpc::ClientContext* context, google::cloud::channel::v1::SuspendEntitlementRequest const& request, grpc::CompletionQueue* cq) { return grpc_stub_->AsyncSuspendEntitlement(context, request, cq); }, request, std::move(context)); } future<StatusOr<google::longrunning::Operation>> DefaultCloudChannelServiceStub::AsyncCancelEntitlement( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::channel::v1::CancelEntitlementRequest const& request) { return cq.MakeUnaryRpc( [this]( grpc::ClientContext* context, google::cloud::channel::v1::CancelEntitlementRequest const& request, grpc::CompletionQueue* cq) { return grpc_stub_->AsyncCancelEntitlement(context, request, cq); }, request, std::move(context)); } future<StatusOr<google::longrunning::Operation>> DefaultCloudChannelServiceStub::AsyncActivateEntitlement( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::channel::v1::ActivateEntitlementRequest const& request) { return cq.MakeUnaryRpc( [this]( grpc::ClientContext* context, google::cloud::channel::v1::ActivateEntitlementRequest const& request, grpc::CompletionQueue* cq) { return grpc_stub_->AsyncActivateEntitlement(context, request, cq); }, request, std::move(context)); } future<StatusOr<google::longrunning::Operation>> DefaultCloudChannelServiceStub::AsyncTransferEntitlements( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::channel::v1::TransferEntitlementsRequest const& request) { return cq.MakeUnaryRpc( [this](grpc::ClientContext* context, google::cloud::channel::v1::TransferEntitlementsRequest const& request, grpc::CompletionQueue* cq) { return grpc_stub_->AsyncTransferEntitlements(context, request, cq); }, request, std::move(context)); } future<StatusOr<google::longrunning::Operation>> DefaultCloudChannelServiceStub::AsyncTransferEntitlementsToGoogle( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::channel::v1::TransferEntitlementsToGoogleRequest const& request) { return cq.MakeUnaryRpc( [this]( grpc::ClientContext* context, google::cloud::channel::v1::TransferEntitlementsToGoogleRequest const& request, grpc::CompletionQueue* cq) { return grpc_stub_->AsyncTransferEntitlementsToGoogle(context, request, cq); }, request, std::move(context)); } StatusOr<google::cloud::channel::v1::ListChannelPartnerLinksResponse> DefaultCloudChannelServiceStub::ListChannelPartnerLinks( grpc::ClientContext& client_context, google::cloud::channel::v1::ListChannelPartnerLinksRequest const& request) { google::cloud::channel::v1::ListChannelPartnerLinksResponse response; auto status = grpc_stub_->ListChannelPartnerLinks(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::ChannelPartnerLink> DefaultCloudChannelServiceStub::GetChannelPartnerLink( grpc::ClientContext& client_context, google::cloud::channel::v1::GetChannelPartnerLinkRequest const& request) { google::cloud::channel::v1::ChannelPartnerLink response; auto status = grpc_stub_->GetChannelPartnerLink(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::ChannelPartnerLink> DefaultCloudChannelServiceStub::CreateChannelPartnerLink( grpc::ClientContext& client_context, google::cloud::channel::v1::CreateChannelPartnerLinkRequest const& request) { google::cloud::channel::v1::ChannelPartnerLink response; auto status = grpc_stub_->CreateChannelPartnerLink(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::ChannelPartnerLink> DefaultCloudChannelServiceStub::UpdateChannelPartnerLink( grpc::ClientContext& client_context, google::cloud::channel::v1::UpdateChannelPartnerLinkRequest const& request) { google::cloud::channel::v1::ChannelPartnerLink response; auto status = grpc_stub_->UpdateChannelPartnerLink(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::CustomerRepricingConfig> DefaultCloudChannelServiceStub::GetCustomerRepricingConfig( grpc::ClientContext& client_context, google::cloud::channel::v1::GetCustomerRepricingConfigRequest const& request) { google::cloud::channel::v1::CustomerRepricingConfig response; auto status = grpc_stub_->GetCustomerRepricingConfig(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::ListCustomerRepricingConfigsResponse> DefaultCloudChannelServiceStub::ListCustomerRepricingConfigs( grpc::ClientContext& client_context, google::cloud::channel::v1::ListCustomerRepricingConfigsRequest const& request) { google::cloud::channel::v1::ListCustomerRepricingConfigsResponse response; auto status = grpc_stub_->ListCustomerRepricingConfigs(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::CustomerRepricingConfig> DefaultCloudChannelServiceStub::CreateCustomerRepricingConfig( grpc::ClientContext& client_context, google::cloud::channel::v1::CreateCustomerRepricingConfigRequest const& request) { google::cloud::channel::v1::CustomerRepricingConfig response; auto status = grpc_stub_->CreateCustomerRepricingConfig(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::CustomerRepricingConfig> DefaultCloudChannelServiceStub::UpdateCustomerRepricingConfig( grpc::ClientContext& client_context, google::cloud::channel::v1::UpdateCustomerRepricingConfigRequest const& request) { google::cloud::channel::v1::CustomerRepricingConfig response; auto status = grpc_stub_->UpdateCustomerRepricingConfig(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } Status DefaultCloudChannelServiceStub::DeleteCustomerRepricingConfig( grpc::ClientContext& client_context, google::cloud::channel::v1::DeleteCustomerRepricingConfigRequest const& request) { google::protobuf::Empty response; auto status = grpc_stub_->DeleteCustomerRepricingConfig(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return google::cloud::Status(); } StatusOr<google::cloud::channel::v1::ChannelPartnerRepricingConfig> DefaultCloudChannelServiceStub::GetChannelPartnerRepricingConfig( grpc::ClientContext& client_context, google::cloud::channel::v1::GetChannelPartnerRepricingConfigRequest const& request) { google::cloud::channel::v1::ChannelPartnerRepricingConfig response; auto status = grpc_stub_->GetChannelPartnerRepricingConfig( &client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::ListChannelPartnerRepricingConfigsResponse> DefaultCloudChannelServiceStub::ListChannelPartnerRepricingConfigs( grpc::ClientContext& client_context, google::cloud::channel::v1::ListChannelPartnerRepricingConfigsRequest const& request) { google::cloud::channel::v1::ListChannelPartnerRepricingConfigsResponse response; auto status = grpc_stub_->ListChannelPartnerRepricingConfigs( &client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::ChannelPartnerRepricingConfig> DefaultCloudChannelServiceStub::CreateChannelPartnerRepricingConfig( grpc::ClientContext& client_context, google::cloud::channel::v1:: CreateChannelPartnerRepricingConfigRequest const& request) { google::cloud::channel::v1::ChannelPartnerRepricingConfig response; auto status = grpc_stub_->CreateChannelPartnerRepricingConfig( &client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::ChannelPartnerRepricingConfig> DefaultCloudChannelServiceStub::UpdateChannelPartnerRepricingConfig( grpc::ClientContext& client_context, google::cloud::channel::v1:: UpdateChannelPartnerRepricingConfigRequest const& request) { google::cloud::channel::v1::ChannelPartnerRepricingConfig response; auto status = grpc_stub_->UpdateChannelPartnerRepricingConfig( &client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } Status DefaultCloudChannelServiceStub::DeleteChannelPartnerRepricingConfig( grpc::ClientContext& client_context, google::cloud::channel::v1:: DeleteChannelPartnerRepricingConfigRequest const& request) { google::protobuf::Empty response; auto status = grpc_stub_->DeleteChannelPartnerRepricingConfig( &client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return google::cloud::Status(); } StatusOr<google::cloud::channel::v1::Offer> DefaultCloudChannelServiceStub::LookupOffer( grpc::ClientContext& client_context, google::cloud::channel::v1::LookupOfferRequest const& request) { google::cloud::channel::v1::Offer response; auto status = grpc_stub_->LookupOffer(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::ListProductsResponse> DefaultCloudChannelServiceStub::ListProducts( grpc::ClientContext& client_context, google::cloud::channel::v1::ListProductsRequest const& request) { google::cloud::channel::v1::ListProductsResponse response; auto status = grpc_stub_->ListProducts(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::ListSkusResponse> DefaultCloudChannelServiceStub::ListSkus( grpc::ClientContext& client_context, google::cloud::channel::v1::ListSkusRequest const& request) { google::cloud::channel::v1::ListSkusResponse response; auto status = grpc_stub_->ListSkus(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::ListOffersResponse> DefaultCloudChannelServiceStub::ListOffers( grpc::ClientContext& client_context, google::cloud::channel::v1::ListOffersRequest const& request) { google::cloud::channel::v1::ListOffersResponse response; auto status = grpc_stub_->ListOffers(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::ListPurchasableSkusResponse> DefaultCloudChannelServiceStub::ListPurchasableSkus( grpc::ClientContext& client_context, google::cloud::channel::v1::ListPurchasableSkusRequest const& request) { google::cloud::channel::v1::ListPurchasableSkusResponse response; auto status = grpc_stub_->ListPurchasableSkus(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::ListPurchasableOffersResponse> DefaultCloudChannelServiceStub::ListPurchasableOffers( grpc::ClientContext& client_context, google::cloud::channel::v1::ListPurchasableOffersRequest const& request) { google::cloud::channel::v1::ListPurchasableOffersResponse response; auto status = grpc_stub_->ListPurchasableOffers(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::RegisterSubscriberResponse> DefaultCloudChannelServiceStub::RegisterSubscriber( grpc::ClientContext& client_context, google::cloud::channel::v1::RegisterSubscriberRequest const& request) { google::cloud::channel::v1::RegisterSubscriberResponse response; auto status = grpc_stub_->RegisterSubscriber(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::UnregisterSubscriberResponse> DefaultCloudChannelServiceStub::UnregisterSubscriber( grpc::ClientContext& client_context, google::cloud::channel::v1::UnregisterSubscriberRequest const& request) { google::cloud::channel::v1::UnregisterSubscriberResponse response; auto status = grpc_stub_->UnregisterSubscriber(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::cloud::channel::v1::ListSubscribersResponse> DefaultCloudChannelServiceStub::ListSubscribers( grpc::ClientContext& client_context, google::cloud::channel::v1::ListSubscribersRequest const& request) { google::cloud::channel::v1::ListSubscribersResponse response; auto status = grpc_stub_->ListSubscribers(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } future<StatusOr<google::longrunning::Operation>> DefaultCloudChannelServiceStub::AsyncGetOperation( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return cq.MakeUnaryRpc( [this](grpc::ClientContext* context, google::longrunning::GetOperationRequest const& request, grpc::CompletionQueue* cq) { return operations_->AsyncGetOperation(context, request, cq); }, request, std::move(context)); } future<Status> DefaultCloudChannelServiceStub::AsyncCancelOperation( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return cq .MakeUnaryRpc( [this](grpc::ClientContext* context, google::longrunning::CancelOperationRequest const& request, grpc::CompletionQueue* cq) { return operations_->AsyncCancelOperation(context, request, cq); }, request, std::move(context)) .then([](future<StatusOr<google::protobuf::Empty>> f) { return f.get().status(); }); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace channel_internal } // namespace cloud } // namespace google
39.016296
80
0.730977
GoogleCloudPlatform
6c5eb48d870b5a346b660c506c4be01414158af2
923
cpp
C++
GL/ShootingGame/Circle.cpp
KoreanGinseng/CreativeLabo4
a7c03ad2cea958be1509cd0c09581b1f4fc81275
[ "MIT" ]
null
null
null
GL/ShootingGame/Circle.cpp
KoreanGinseng/CreativeLabo4
a7c03ad2cea958be1509cd0c09581b1f4fc81275
[ "MIT" ]
null
null
null
GL/ShootingGame/Circle.cpp
KoreanGinseng/CreativeLabo4
a7c03ad2cea958be1509cd0c09581b1f4fc81275
[ "MIT" ]
null
null
null
#include "Circle.h" Circle::Circle() : x_(0.0f) , y_(0.0f) , r_(0.0f) { } Circle::Circle(float r) : x_(0.0f) , y_(0.0f) , r_(r) { } Circle::Circle(float x, float y, float r) : x_(x) , y_(y) , r_(r) { } Circle::~Circle() { } bool Circle::CollisionPoint(float x, float y) const { float distanceX = std::fabsf(x_ - x); float distanceY = std::fabsf(y_ - y); float distance = std::powf(distanceX, 2) + std::powf(distanceY, 2); return distance <= std::powf(r_, 2); } bool Circle::CollisionCircle(float x, float y, float r) const { float distanceX = std::fabsf(x_ - x); float distanceY = std::fabsf(y_ - y); float distance = std::powf(distanceX, 2) + std::powf(distanceY, 2); return distance <= std::powf(r_, 2) + std::powf(r, 2); } bool Circle::CollisionCircle(Circle circle) const { return CollisionCircle(circle.x(), circle.y(), circle.r()); }
22.512195
72
0.592633
KoreanGinseng
4842baec0e2e73ef3a1cb88c9df2b3ea3b356420
11,422
cpp
C++
AmbientGsm.cpp
mnltake/ambient_gpstracker_LTE
57d28327e4f47cc82ddff80796b3686ffd6a0014
[ "MIT" ]
null
null
null
AmbientGsm.cpp
mnltake/ambient_gpstracker_LTE
57d28327e4f47cc82ddff80796b3686ffd6a0014
[ "MIT" ]
null
null
null
AmbientGsm.cpp
mnltake/ambient_gpstracker_LTE
57d28327e4f47cc82ddff80796b3686ffd6a0014
[ "MIT" ]
null
null
null
/* * ambient.cpp - Library for sending data to Ambient * Created by Takehiko Shimojima, April 21, 2016 * change by mnltake ,2022 */ #include "AmbientGsm.h" #define AMBIENT_DEBUG 0 #if AMBIENT_DEBUG #define DBG(...) { Serial.print(__VA_ARGS__); } #define ERR(...) { Serial.print(__VA_ARGS__); } #else #define DBG(...) #define ERR(...) #endif /* AMBIENT_DBG */ // const char* AMBIENT_HOST = "54.65.206.59"; const char* AMBIENT_HOST = "ambidata.io"; int AMBIENT_PORT = 80; const char* AMBIENT_HOST_DEV = "192.168.11.2"; int AMBIENT_PORT_DEV = 4567; const char * ambient_keys[] = {"\"d1\":\"", "\"d2\":\"", "\"d3\":\"", "\"d4\":\"", "\"d5\":\"", "\"d6\":\"", "\"d7\":\"", "\"d8\":\"", "\"lat\":\"", "\"lng\":\"", "\"created\":\""}; Ambient::Ambient() { } bool Ambient::begin(unsigned int channelId, const char * writeKey, TinyGsmClient * c, const char * readKey, int dev) { this->channelId = channelId; if (sizeof(writeKey) > AMBIENT_WRITEKEY_SIZE) { ERR("writeKey length > AMBIENT_WRITEKEY_SIZE"); return false; } strcpy(this->writeKey, writeKey); if(NULL == c) { ERR("Socket Pointer is NULL, open a socket."); return false; } this->client = c; if (readKey != NULL) { strcpy(this->readKey, readKey); } else { strcpy(this->readKey, ""); } this->dev = dev; if (dev) { strcpy(this->host, AMBIENT_HOST_DEV); this->port = AMBIENT_PORT_DEV; } else { strcpy(this->host, AMBIENT_HOST); this->port = AMBIENT_PORT; } for (int i = 0; i < AMBIENT_NUM_PARAMS; i++) { this->data[i].set = false; } this->cmnt.set = false; return true; } bool Ambient::set(int field,const char * data) { --field; if (field < 0 || field >= AMBIENT_NUM_PARAMS) { return false; } if (strlen(data) > AMBIENT_DATA_SIZE) { return false; } this->data[field].set = true; strcpy(this->data[field].item, data); return true; } bool Ambient::set(int field, double data) { return set(field,String(data).c_str()); } bool Ambient::set(int field, int data) { return set(field, String(data).c_str()); } bool Ambient::clear(int field) { --field; if (field < 0 || field >= AMBIENT_NUM_PARAMS) { return false; } this->data[field].set = false; this->cmnt.set = false; return true; } bool Ambient::setcmnt(const char * data) { if (strlen(data) > AMBIENT_CMNT_SIZE) { return false; } this->cmnt.set = true; strcpy(this->cmnt.item, data); return true; } bool Ambient::connect2host(uint32_t tmout) { int retry; for (retry = 0; retry < AMBIENT_MAX_RETRY; retry++) { int ret; #if defined(ESP8266) this->client->setTimeout(tmout); ret = this->client->connect(this->host, this->port); #else ret = this->client->connect(this->host, this->port); #endif if (ret) { break ; } } if(retry == AMBIENT_MAX_RETRY) { ERR("Could not connect socket to host\r\n"); return false; } return true; } int Ambient::getStatusCode() { String _buf = this->client->readStringUntil('\n'); int from = _buf.indexOf("HTTP/1.1 ") + sizeof("HTTP/1.1 ") - 1; int to = _buf.indexOf(' ', from); this->status = _buf.substring(from, to).toInt(); return this->status; } bool Ambient::send(uint32_t tmout) { char str[180]; char body[192]; char inChar; this->status = 0; if (connect2host(tmout) == false) { return false; } memset(body, 0, sizeof(body)); strcat(body, "{\"writeKey\":\""); strcat(body, this->writeKey); strcat(body, "\","); for (int i = 0; i < AMBIENT_NUM_PARAMS; i++) { if (this->data[i].set) { strcat(body, ambient_keys[i]); strcat(body, this->data[i].item); strcat(body, "\","); } } if (this->cmnt.set) { strcat(body, "\"cmnt\":\""); strcat(body, this->cmnt.item); strcat(body, "\","); } body[strlen(body) - 1] = '\0'; strcat(body, "}\r\n"); memset(str, 0, sizeof(str)); sprintf(str, "POST /api/v2/channels/%u/data HTTP/1.1\r\n", this->channelId); if (this->port == 80) { sprintf(&str[strlen(str)], "Host: %s\r\n", this->host); } else { sprintf(&str[strlen(str)], "Host: %s:%d\r\n", this->host, this->port); } sprintf(&str[strlen(str)], "Content-Length: %d\r\n", strlen(body)); sprintf(&str[strlen(str)], "Content-Type: application/json\r\n\r\n"); DBG("sending: ");DBG(strlen(str));DBG("bytes\r\n");DBG(str); int ret; ret = this->client->print(str); delay(30); DBG(ret);DBG(" bytes sent\n\n"); if (ret == 0) { ERR("send failed\n"); return false; } ret = this->client->print(body); delay(30); DBG(ret);DBG(" bytes sent\n\n"); if (ret == 0) { ERR("send failed\n"); return false; } getStatusCode(); while (this->client->available()) { inChar = this->client->read(); #if AMBIENT_DEBUG Serial.write(inChar); #endif } this->client->stop(); for (int i = 0; i < AMBIENT_NUM_PARAMS; i++) { this->data[i].set = false; } this->cmnt.set = false; return true; } int Ambient::bulk_send(char *buf, uint32_t tmout) { char str[180]; char inChar; this->status = 0; if (connect2host(tmout) == false) { return false; } memset(str, 0, sizeof(str)); sprintf(str, "POST /api/v2/channels/%u/dataarray HTTP/1.1\r\n", this->channelId); if (this->port == 80) { sprintf(&str[strlen(str)], "Host: %s\r\n", this->host); } else { sprintf(&str[strlen(str)], "Host: %s:%d\r\n", this->host, this->port); } sprintf(&str[strlen(str)], "Content-Length: %d\r\n", strlen(buf)); sprintf(&str[strlen(str)], "Content-Type: application/json\r\n\r\n"); DBG("sending: ");DBG(strlen(str));DBG("bytes\r\n");DBG(str); int ret; ret = this->client->print(str); // send header delay(30); DBG(ret);DBG(" bytes sent\n\n"); if (ret == 0) { ERR("send failed\n"); return -1; } int sent = 0; unsigned long starttime = millis(); while ((millis() - starttime) < AMBIENT_TIMEOUT) { ret = this->client->print(&buf[sent]); delay(30); DBG(ret);DBG(" bytes sent\n\n"); if (ret == 0) { ERR("send failed\n"); return -1; } sent += ret; if (sent >= strlen(buf)) { break; } } delay(500); getStatusCode(); while (this->client->available()) { inChar = this->client->read(); #if AMBIENT_DEBUG Serial.write(inChar); #endif } this->client->stop(); for (int i = 0; i < AMBIENT_NUM_PARAMS; i++) { this->data[i].set = false; } this->cmnt.set = false; return (sent == 0) ? -1 : sent; } bool Ambient::read(char * buf, int len, int n, uint32_t tmout) { char str[180]; String _buf; this->status = 0; if (connect2host(tmout) == false) { return false; } memset(str, 0, sizeof(str)); sprintf(str, "GET /api/v2/channels/%u/data?readKey=%s&n=%d HTTP/1.1\r\n", this->channelId, this->readKey, n); if (this->port == 80) { sprintf(&str[strlen(str)], "Host: %s\r\n\r\n", this->host); } else { sprintf(&str[strlen(str)], "Host: %s:%d\r\n\r\n", this->host, this->port); } DBG("sending: ");DBG(strlen(str));DBG("bytes\r\n");DBG(str); int ret; ret = this->client->print(str); delay(30); DBG(ret);DBG(" bytes sent\n\n"); if (ret == 0) { ERR("send failed\n"); return false; } if (getStatusCode() != 200) { // ステータスコードが200でなければ while (this->client->available()) { // 残りを読み捨てる this->client->readStringUntil('\n'); } return false; } while (this->client->available()) { _buf = this->client->readStringUntil('\n'); if (_buf.length() == 1) // 空行を見つける break; } _buf = this->client->readStringUntil('\n'); _buf.toCharArray(buf, len); this->client->stop(); return true; } bool Ambient::delete_data(const char * userKey, uint32_t tmout) { char str[180]; char inChar; this->status = 0; if (connect2host(tmout) == false) { return false; } memset(str, 0, sizeof(str)); sprintf(str, "DELETE /api/v2/channels/%u/data?userKey=%s HTTP/1.1\r\n", this->channelId, userKey); if (this->port == 80) { sprintf(&str[strlen(str)], "Host: %s\r\n", this->host); } else { sprintf(&str[strlen(str)], "Host: %s:%d\r\n", this->host, this->port); } sprintf(&str[strlen(str)], "Content-Length: 0\r\n"); sprintf(&str[strlen(str)], "Content-Type: application/json\r\n\r\n"); DBG(str); int ret; ret = this->client->print(str); delay(30); DBG(ret);DBG(" bytes sent\r\n"); if (ret == 0) { ERR("send failed\r\n"); return false; } getStatusCode(); while (this->client->available()) { inChar = this->client->read(); #if AMBIENT_DEBUG Serial.write(inChar); #endif } this->client->stop(); for (int i = 0; i < AMBIENT_NUM_PARAMS; i++) { this->data[i].set = false; } this->cmnt.set = false; return true; } bool Ambient::getchannel(const char * userKey, const char * devKey, unsigned int & channelId, char * writeKey, int len, TinyGsmClient * c, uint32_t tmout, int dev) { this->status = 0; if(NULL == c) { ERR("Socket Pointer is NULL, open a socket."); return false; } this->client = c; this->dev = dev; if (dev) { strcpy(this->host, AMBIENT_HOST_DEV); this->port = AMBIENT_PORT_DEV; } else { strcpy(this->host, AMBIENT_HOST); this->port = AMBIENT_PORT; } if (connect2host(tmout) == false) { return false; } char str[1024]; char inChar; memset(str, 0, sizeof(str)); sprintf(str, "GET /api/v2/channels/?userKey=%s&devKey=%s HTTP/1.1\r\n", userKey, devKey); if (this->port == 80) { sprintf(&str[strlen(str)], "Host: %s\r\n", this->host); } else { sprintf(&str[strlen(str)], "Host: %s:%d\r\n", this->host, this->port); } sprintf(&str[strlen(str)], "Content-Type: application/json\r\n\r\n"); DBG(str); int ret; ret = this->client->print(str); delay(30); DBG(ret);DBG(" bytes sent\r\n"); if (ret == 0) { ERR("send failed\r\n"); return false; } if (getStatusCode() != 200) { // ステータスコードが200でなければ while (this->client->available()) { this->client->readStringUntil('\n'); } return false; } while (this->client->available()) { String buf = this->client->readStringUntil('\n'); if (buf.length() == 1) break; } String buf = this->client->readStringUntil('\n'); int from, to; from = buf.indexOf("\"ch\":\"") + strlen("\"ch\":\""); to = buf.indexOf("\",", from); channelId = buf.substring(from, to).toInt(); from = buf.indexOf("\"writeKey\":\"") + strlen("\"writeKey\":\""); to = buf.indexOf("\",", from); buf.substring(from, to).toCharArray(writeKey, len); this->client->stop(); return true; }
25.667416
181
0.548941
mnltake
4842c77d1d750453454405dd78d347cea6c68375
7,954
hpp
C++
include/mtx/responses/crypto.hpp
govynnus/mtxclient
3888ae70d51cdfe7b69d375560448f36991793e6
[ "MIT" ]
18
2019-03-11T20:23:53.000Z
2022-02-25T20:55:27.000Z
include/mtx/responses/crypto.hpp
govynnus/mtxclient
3888ae70d51cdfe7b69d375560448f36991793e6
[ "MIT" ]
55
2019-02-07T01:21:03.000Z
2022-03-06T15:42:34.000Z
include/mtx/responses/crypto.hpp
govynnus/mtxclient
3888ae70d51cdfe7b69d375560448f36991793e6
[ "MIT" ]
22
2019-02-24T17:28:31.000Z
2022-03-10T22:40:22.000Z
#pragma once /// @file /// @brief E2EE related endpoints. #if __has_include(<nlohmann/json_fwd.hpp>) #include <nlohmann/json_fwd.hpp> #else #include <nlohmann/json.hpp> #endif #include "mtx/common.hpp" #include "mtx/lightweight_error.hpp" #include <map> #include <string> namespace mtx { namespace responses { //! Response from the `POST /_matrix/client/r0/keys/upload` endpoint. struct UploadKeys { //! For each key algorithm, the number of unclaimed one-time keys //! of that type currently held on the server for this device. std::map<std::string, uint32_t> one_time_key_counts; }; void from_json(const nlohmann::json &obj, UploadKeys &response); using DeviceToKeysMap = std::map<std::string, mtx::crypto::DeviceKeys>; //! Response from the `POST /_matrix/client/r0/keys/query` endpoint. struct QueryKeys { //! If any remote homeservers could not be reached, they are //! recorded here. The names of the properties are the names //! of the unreachable servers. std::map<std::string, nlohmann::json> failures; //! Information on the queried devices. //! A map from user ID, to a map from device ID to device information. //! For each device, the information returned will be the same //! as uploaded via /keys/upload, with the addition of an unsigned property std::map<std::string, DeviceToKeysMap> device_keys; //! A map from user ID, to information about master_keys. std::map<std::string, mtx::crypto::CrossSigningKeys> master_keys; //! A map from user ID, to information about user_signing_keys. std::map<std::string, mtx::crypto::CrossSigningKeys> user_signing_keys; //! A map from user ID, to information about self_signing_keys. std::map<std::string, mtx::crypto::CrossSigningKeys> self_signing_keys; }; void to_json(nlohmann::json &obj, const QueryKeys &response); void from_json(const nlohmann::json &obj, QueryKeys &response); //! Request for `POST /_matrix/client/r0/keys/upload`. struct KeySignaturesUpload { //! Errors returned during upload. std::map<std::string, std::map<std::string, mtx::errors::LightweightError>> errors; }; void from_json(const nlohmann::json &obj, KeySignaturesUpload &response); //! Response from the `POST /_matrix/client/r0/keys/claim` endpoint. struct ClaimKeys { //! If any remote homeservers could not be reached, they are //! recorded here. The names of the properties are the names //! of the unreachable servers. std::map<std::string, nlohmann::json> failures; //! One-time keys for the queried devices. A map from user ID, //! to a map from <algorithm>:<key_id> to the key object. std::map<std::string, std::map<std::string, nlohmann::json>> one_time_keys; }; void from_json(const nlohmann::json &obj, ClaimKeys &response); //! Response from the `GET /_matrix/client/r0/keys/changes` endpoint. struct KeyChanges { //! The Matrix User IDs of all users who updated their device identity keys. std::vector<std::string> changed; //! The Matrix User IDs of all users who may have left all the end-to-end //! encrypted rooms they previously shared with the user. std::vector<std::string> left; }; void from_json(const nlohmann::json &obj, KeyChanges &response); //! KeysBackup related responses. namespace backup { //! Encrypted session data using the m.megolm_backup.v1.curve25519-aes-sha2 algorithm struct EncryptedSessionData { //! Generate an ephemeral curve25519 key, and perform an ECDH with the ephemeral key and the //! backup's public key to generate a shared secret. The public half of the ephemeral key, //! encoded using unpadded base64, becomes the ephemeral property std::string ephemeral; //! Stringify the JSON object, and encrypt it using AES-CBC-256 with PKCS#7 padding. This //! encrypted data, encoded using unpadded base64, becomes the ciphertext property of the //! session_data. std::string ciphertext; //! Pass the raw encrypted data (prior to base64 encoding) through HMAC-SHA-256 using the //! MAC key generated above. The first 8 bytes of the resulting MAC are base64-encoded, and //! become the mac property of the session_data. std::string mac; }; void from_json(const nlohmann::json &obj, EncryptedSessionData &response); void to_json(nlohmann::json &obj, const EncryptedSessionData &response); //! Responses from the `GET /_matrix/client/r0/room_keys/keys/{room_id}/{session_id}` endpoint struct SessionBackup { //! Required. The index of the first message in the session that the key can decrypt. int64_t first_message_index; //! Required. The number of times this key has been forwarded via key-sharing between //! devices. int64_t forwarded_count; //! Required. Whether the device backing up the key verified the device that the key is //! from. bool is_verified; //! Required. Algorithm-dependent data. See the documentation for the backup algorithms in //! Server-side key backups for more information on the expected format of the data. EncryptedSessionData session_data; }; void from_json(const nlohmann::json &obj, SessionBackup &response); void to_json(nlohmann::json &obj, const SessionBackup &response); //! Responses from the `GET /_matrix/client/r0/room_keys/keys/{room_id}` endpoint struct RoomKeysBackup { //! map of session id to the individual sessions std::map<std::string, SessionBackup> sessions; }; void from_json(const nlohmann::json &obj, RoomKeysBackup &response); void to_json(nlohmann::json &obj, const RoomKeysBackup &response); //! Responses from the `GET /_matrix/client/r0/room_keys/keys` endpoint struct KeysBackup { //! map of room id to map of session ids to backups of individual sessions std::map<std::string, RoomKeysBackup> rooms; }; void from_json(const nlohmann::json &obj, KeysBackup &response); void to_json(nlohmann::json &obj, const KeysBackup &response); constexpr const char *megolm_backup_v1 = "m.megolm_backup.v1.curve25519-aes-sha2"; //! Responses from the `GET /_matrix/client/r0/room_keys/version` endpoint struct BackupVersion { //! Required. The algorithm used for storing backups. Must be //! 'm.megolm_backup.v1.curve25519-aes-sha2'. std::string algorithm; //! Required. Algorithm-dependent data. See the documentation for the backup algorithms in //! Server-side key backups for more information on the expected format of the data. std::string auth_data; //! Required. The number of keys stored in the backup. int64_t count; //! Required. An opaque string representing stored keys in the backup. Clients can //! compare it with the etag value they received in the request of their last key storage //! request. If not equal, another client has modified the backup std::string etag; //! Required. The backup version std::string version; }; void from_json(const nlohmann::json &obj, BackupVersion &response); void to_json(nlohmann::json &obj, const BackupVersion &response); //! The SessionData stored in the KeysBackup. struct SessionData { //! Required. The end-to-end message encryption algorithm that the key is // for. Must be m.megolm.v1.aes-sha2. std::string algorithm; // Required. Chain of Curve25519 keys through which this // session was forwarded, via m.forwarded_room_key events. std::vector<std::string> forwarding_curve25519_key_chain; // Required. Unpadded base64-encoded device curve25519 key. std::string sender_key; // Required. A map from algorithm name (ed25519) to the identity // key for the sending device. std::map<std::string, std::string> sender_claimed_keys; // Required. Unpadded base64-encoded session key in session-sharing format. std::string session_key; }; void to_json(nlohmann::json &obj, const SessionData &desc); void from_json(const nlohmann::json &obj, SessionData &desc); } } // namespace responses } // namespace mtx
37.518868
96
0.729444
govynnus
48441cd0555c543fe874f8f754f553d2736764db
1,290
hpp
C++
src/lib/storage/vector_compression/bitpacking/bitpacking_vector.hpp
mrcl-tst/hyrise
eec50b39de9f530b0a1732ceb5822b7222f3fe17
[ "MIT" ]
583
2015-01-10T00:55:32.000Z
2022-03-25T12:24:30.000Z
src/lib/storage/vector_compression/bitpacking/bitpacking_vector.hpp
mrcl-tst/hyrise
eec50b39de9f530b0a1732ceb5822b7222f3fe17
[ "MIT" ]
1,573
2015-01-07T15:47:22.000Z
2022-03-31T11:48:03.000Z
src/lib/storage/vector_compression/bitpacking/bitpacking_vector.hpp
mrcl-tst/hyrise
eec50b39de9f530b0a1732ceb5822b7222f3fe17
[ "MIT" ]
145
2015-03-09T16:26:07.000Z
2022-02-15T12:53:23.000Z
#pragma once #include "bitpacking_decompressor.hpp" #include "bitpacking_iterator.hpp" #include "bitpacking_vector_type.hpp" #include "compact_vector.hpp" #include "storage/vector_compression/base_compressed_vector.hpp" namespace opossum { /** * @brief Bit-packed vector with fixed bit length * * Bit-packed Null Suppression. * All values of the sequences are compressed with the same bit length, which is determined by the bits required to * represent the maximum value of the sequence. The decoding runtime is only marginally slower than * FixedWidthIntegerVector but the compression rate of BitPacking is significantly better. * */ class BitPackingVector : public CompressedVector<BitPackingVector> { public: explicit BitPackingVector(pmr_compact_vector data); const pmr_compact_vector& data() const; size_t on_size() const; size_t on_data_size() const; std::unique_ptr<BaseVectorDecompressor> on_create_base_decompressor() const; BitPackingDecompressor on_create_decompressor() const; BitPackingIterator on_begin() const; BitPackingIterator on_end() const; std::unique_ptr<const BaseCompressedVector> on_copy_using_allocator(const PolymorphicAllocator<size_t>& alloc) const; private: const pmr_compact_vector _data; }; } // namespace opossum
30.714286
119
0.795349
mrcl-tst
484652da790a2aeceeec1f214398ed833e61f004
4,716
cpp
C++
tests/minimongo.cpp
almightycouch/meteorpp
e8af587c88902fb79820317a6d579ace43d883b1
[ "MIT" ]
24
2015-10-25T11:34:02.000Z
2018-09-10T17:10:52.000Z
tests/minimongo.cpp
almightycouch/meteorpp
e8af587c88902fb79820317a6d579ace43d883b1
[ "MIT" ]
3
2018-08-05T14:01:43.000Z
2019-02-15T14:44:42.000Z
tests/minimongo.cpp
almightycouch/meteorpp
e8af587c88902fb79820317a6d579ace43d883b1
[ "MIT" ]
9
2016-05-09T13:56:58.000Z
2021-11-01T23:53:38.000Z
#include <set> #include <meteorpp/collection.hpp> #include <boost/test/unit_test.hpp> struct fixture { fixture() : coll(std::make_shared<meteorpp::collection>("test")) {} std::shared_ptr<meteorpp::collection> coll; }; BOOST_AUTO_TEST_CASE(create_collection) { BOOST_CHECK_NO_THROW(std::make_shared<meteorpp::collection>("test")); } BOOST_AUTO_TEST_CASE(create_invalid_collection) { BOOST_CHECK_THROW(std::make_shared<meteorpp::collection>(""), meteorpp::ejdb_exception); } BOOST_FIXTURE_TEST_CASE(insert_with_oid, fixture) { std::string const oid = "d776bb695e5447997999b1fd"; BOOST_CHECK_EQUAL(coll->insert({{ "_id", oid }, { "foo", "bar" }}), oid); } BOOST_FIXTURE_TEST_CASE(insert_with_invalid_oid, fixture) { std::string const oid = "0xe5505"; BOOST_CHECK_THROW(coll->insert({{ "_id", oid }, { "foo", "bar" }}), meteorpp::ejdb_exception); } BOOST_FIXTURE_TEST_CASE(insert_count, fixture) { for(auto i = 1; i <= 10; ++i) { coll->insert({{ "foo", "bar" }}); BOOST_CHECK_EQUAL(coll->count(), i); } } BOOST_FIXTURE_TEST_CASE(insert_count_with_query, fixture) { coll->insert({{ "foo", "bar"}}); coll->insert({{ "foo", "baz"}}); coll->insert({{ "foo", "bar"}, { "bar", "foo" }}); coll->insert({{ "foo", "baz"}, { "bar", "foo" }}); BOOST_CHECK_EQUAL(coll->count({{ "foo", "bar" }}), 2); BOOST_CHECK_EQUAL(coll->count({{ "foo", "baz" }}), 2); BOOST_CHECK_EQUAL(coll->count({{ "bar", "foo" }}), 2); BOOST_CHECK_EQUAL(coll->count({{ "foo", "bar" }, { "bar", "foo" }}), 1); BOOST_CHECK_EQUAL(coll->count({{ "$or", { {{ "foo", "bar"}}, {{ "bar", "foo" }} } }}), 3); } BOOST_FIXTURE_TEST_CASE(insert_find_one, fixture) { nlohmann::json::object_t doc = {{ "foo", "bar" }}; doc.insert(std::make_pair("_id", coll->insert(doc))); BOOST_CHECK_EQUAL(coll->find_one(), doc); } BOOST_FIXTURE_TEST_CASE(insert_find_multi, fixture) { nlohmann::json::object_t doc1 = {{ "foo", "bar" }}; doc1.insert(std::make_pair("_id", coll->insert(doc1))); nlohmann::json::object_t doc2 = {{ "foo", "baz" }}; doc2.insert(std::make_pair("_id", coll->insert(doc2))); auto const excepted = { doc1, doc2 }; BOOST_CHECK_EQUAL(coll->find(), excepted); } BOOST_FIXTURE_TEST_CASE(insert_update_one, fixture) { nlohmann::json::object_t doc = {{ "foo", "bar" }}; doc.insert(std::make_pair("_id", coll->insert(doc))); auto const it = coll->update(doc, {{ "$set", {{ "foo", "baz" }}}}); BOOST_CHECK_EQUAL(it, 1); doc["foo"] = "baz"; BOOST_CHECK_EQUAL(coll->find_one(), doc); } BOOST_FIXTURE_TEST_CASE(insert_update_multi, fixture) { nlohmann::json::object_t doc1 = {{ "foo", "bar" }}; doc1.insert(std::make_pair("_id", coll->insert(doc1))); nlohmann::json::object_t doc2 = {{ "foo", "baz" }}; doc2.insert(std::make_pair("_id", coll->insert(doc2))); auto const it = coll->update({}, {{ "$set", {{ "bar", "foo" }}}}); BOOST_CHECK_EQUAL(it, 2); doc1["bar"] = "foo"; doc2["bar"] = "foo"; auto const excepted = { doc1, doc2 }; BOOST_CHECK_EQUAL(coll->find(), excepted); } BOOST_FIXTURE_TEST_CASE(insert_multi_update_one, fixture) { nlohmann::json::object_t doc1 = {{ "foo", "bar" }}; doc1.insert(std::make_pair("_id", coll->insert(doc1))); nlohmann::json::object_t doc2 = {{ "foo", "baz" }}; doc2.insert(std::make_pair("_id", coll->insert(doc2))); auto const it = coll->update(doc1, {{ "$set", {{ "bar", "foo" }}}}); BOOST_CHECK_EQUAL(it, 1); doc1["bar"] = "foo"; auto const result_vect = coll->find(); std::set<nlohmann::json::object_t> const result_set(result_vect.begin(), result_vect.end()); std::set<nlohmann::json::object_t> const excepted = { doc1, doc2 }; BOOST_CHECK_EQUAL(result_set, excepted); } BOOST_FIXTURE_TEST_CASE(insert_remove_one, fixture) { auto const id = coll->insert({{ "foo", "bar" }}); auto const it = coll->remove({{ "_id", id }}); BOOST_CHECK_EQUAL(it, 1); BOOST_CHECK(coll->find_one().empty()); } BOOST_FIXTURE_TEST_CASE(insert_remove_multi, fixture) { coll->insert({{ "foo", "bar" }}); coll->insert({{ "foo", "baz" }}); auto const it = coll->remove({}); BOOST_CHECK_EQUAL(it, 2); BOOST_CHECK(coll->find_one().empty()); } BOOST_FIXTURE_TEST_CASE(insert_multi_remove_one, fixture) { nlohmann::json::object_t doc1 = {{ "foo", "bar" }}; doc1.insert(std::make_pair("_id", coll->insert(doc1))); nlohmann::json::object_t doc2 = {{ "foo", "baz" }}; doc2.insert(std::make_pair("_id", coll->insert(doc2))); auto const it = coll->remove(doc1); BOOST_CHECK_EQUAL(it, 1); BOOST_CHECK_EQUAL(coll->find_one(), doc2); }
30.425806
98
0.626166
almightycouch
48499516798e6e901a3953c47941556f8d7ab2c8
6,269
hpp
C++
tests/unit/coherence/run/xml/XmlTokenTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-01T21:38:30.000Z
2021-11-03T01:35:11.000Z
tests/unit/coherence/run/xml/XmlTokenTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
1
2020-07-24T17:29:22.000Z
2020-07-24T18:29:04.000Z
tests/unit/coherence/run/xml/XmlTokenTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-10T18:40:58.000Z
2022-02-18T01:23:40.000Z
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ #include "cxxtest/TestSuite.h" #include "coherence/lang.ns" #include "private/coherence/run/xml/XmlToken.hpp" #include <stdio.h> using namespace coherence::lang; using namespace coherence::run::xml; using namespace std; /** * Test Suite for the XmlToken object. */ class XmlTokenSuite : public CxxTest::TestSuite { public: /** * Test getCategory */ void testGetCategory() { XmlToken::Handle token = XmlToken::create(XmlToken::cat_name, XmlToken::subcat_lit_pi, XmlToken::name, String::create("Value"), String::create("Text")); TS_ASSERT( token->getCategory()== XmlToken::cat_name); token = XmlToken::create(token, 0, 1, 2); TS_ASSERT( token->getCategory()== XmlToken::cat_name); token = XmlToken::create(XmlToken::cat_literal, XmlToken::subcat_lit_pi, XmlToken::name, String::create("Value"), String::create("Text"), 0, 1, 2); TS_ASSERT( token->getCategory()== XmlToken::cat_literal); } /** * Test getSubCategory */ void testGetSubCategory() { XmlToken::Handle token = XmlToken::create(XmlToken::cat_name, XmlToken::subcat_lit_pi, XmlToken::name, String::create("Value"), String::create("Text")); TS_ASSERT( token->getSubCategory()== XmlToken::subcat_lit_pi); token = XmlToken::create(token, 0, 1, 2); TS_ASSERT( token->getSubCategory()== XmlToken::subcat_lit_pi); token = XmlToken::create(XmlToken::cat_literal, XmlToken::subcat_lit_comment, XmlToken::name, String::create("Value"), String::create("Text"), 0, 1, 2); TS_ASSERT( token->getSubCategory()== XmlToken::subcat_lit_comment); } /** * Test getId */ void testGetId() { XmlToken::Handle token = XmlToken::create(XmlToken::cat_name, XmlToken::subcat_lit_pi, XmlToken::name, String::create("Value"), String::create("Text")); TS_ASSERT( token->getID()== XmlToken::name); token = XmlToken::create(token, 0, 1, 2); TS_ASSERT( token->getID()== XmlToken::name); token = XmlToken::create(XmlToken::cat_literal, XmlToken::subcat_lit_comment, XmlToken::literal, String::create("Value"), String::create("Text"), 0, 1, 2); TS_ASSERT( token->getID()== XmlToken::literal); } /** * Test getValue */ void testGetValue() { XmlToken::Handle token = XmlToken::create(XmlToken::cat_name, XmlToken::subcat_lit_pi, XmlToken::name, String::create("Value"), String::create("Text")); TS_ASSERT( String::create("Value")->equals(token->getValue())); token = XmlToken::create(token, 0, 1, 2); TS_ASSERT( String::create("Value")->equals(token->getValue())); token = XmlToken::create(XmlToken::cat_literal, XmlToken::subcat_lit_comment, XmlToken::literal, String::create("Another Value"), String::create("Text"), 0, 1, 2); TS_ASSERT( String::create("Another Value")->equals(token->getValue()) ); } /** * Test getText */ void testGetText() { XmlToken::Handle token = XmlToken::create(XmlToken::cat_name, XmlToken::subcat_lit_pi, XmlToken::name, String::create("Value"), String::create("Text")); TS_ASSERT( String::create("Text")->equals(token->getText())); token = XmlToken::create(token, 0, 1, 2); TS_ASSERT( String::create("Text")->equals(token->getText())); token = XmlToken::create(XmlToken::cat_literal, XmlToken::subcat_lit_comment, XmlToken::literal, String::create("Another Value"), String::create("More Text"), 0, 1, 2); TS_ASSERT( String::create("More Text")->equals(token->getText()) ); } /** * Test getLine */ void testGetLine() { XmlToken::Handle token = XmlToken::create(XmlToken::cat_name, XmlToken::subcat_lit_pi, XmlToken::name, String::create("Value"), String::create("Text")); TS_ASSERT( token->getLine()== 0); token = XmlToken::create(token, 0, 1, 2); TS_ASSERT( token->getLine()== 0); token = XmlToken::create(XmlToken::cat_literal, XmlToken::subcat_lit_comment, XmlToken::literal, String::create("Another Value"), String::create("More Text"), 99, 1, 2); TS_ASSERT( token->getLine()== 99); } /** * Test getOffset */ void testGetOffset() { XmlToken::Handle token = XmlToken::create(XmlToken::cat_name, XmlToken::subcat_lit_pi, XmlToken::name, String::create("Value"), String::create("Text")); TS_ASSERT( token->getOffset()== 0); token = XmlToken::create(token, 0, 1, 2); TS_ASSERT( token->getOffset()== 1); token = XmlToken::create(XmlToken::cat_literal, XmlToken::subcat_lit_comment, XmlToken::literal, String::create("Another Value"), String::create("More Text"), 0, 99, 2); TS_ASSERT( token->getOffset()== 99); } /** * Test getLength */ void testGetLength() { XmlToken::Handle token = XmlToken::create(XmlToken::cat_name, XmlToken::subcat_lit_pi, XmlToken::name, String::create("Value"), String::create("Text")); TS_ASSERT( token->getLength()== 0); token = XmlToken::create(token, 0, 1, 2); TS_ASSERT( token->getLength()== 2); token = XmlToken::create(XmlToken::cat_literal, XmlToken::subcat_lit_comment, XmlToken::literal, String::create("Another Value"), String::create("More Text"), 0, 1, 99); TS_ASSERT( token->getLength()== 99); } /** * Test adjust */ void testAdjust() { XmlToken::Handle token = XmlToken::create(XmlToken::cat_literal, XmlToken::subcat_lit_comment, XmlToken::literal, String::create("Another Value"), String::create("More Text"), 0, 1, 99); token->adjust( 10, 10 ); TS_ASSERT( token->getLine()== 10); TS_ASSERT( token->getOffset()== 11); token->adjust( -2, -2 ); TS_ASSERT( token->getLine()== 8); TS_ASSERT( token->getOffset()== 9); token->adjust( -10, -10 ); TS_ASSERT( token->getLine()== 0); TS_ASSERT( token->getOffset()== 0); } };
36.236994
194
0.624502
chpatel3
4849f31b0b403e5bcc426ebb76afa2f6d6cdfd21
1,980
cpp
C++
Stocks/UrlDownloader.cpp
caicaiking/AbamaAnalysis
d3d370e59c7049be36e06da61e1a315ba58d049d
[ "MIT" ]
null
null
null
Stocks/UrlDownloader.cpp
caicaiking/AbamaAnalysis
d3d370e59c7049be36e06da61e1a315ba58d049d
[ "MIT" ]
null
null
null
Stocks/UrlDownloader.cpp
caicaiking/AbamaAnalysis
d3d370e59c7049be36e06da61e1a315ba58d049d
[ "MIT" ]
null
null
null
#include "UrlDownloader.h" #include <QNetworkReply> namespace { inline int _calculateProgress(qint64 bytesReceived, qint64 bytesTotal) { if (!bytesTotal) return 0; if (bytesTotal == -1) return -1; return (bytesReceived * 100) / bytesTotal; } } //////////////////////////////////////////////////////////////////////////////// UrlDownloader::UrlDownloader(int taskId, const QUrl &url, QNetworkAccessManager &nam, QObject *parent /*= nullptr*/) : QObject(parent) , _taskId(taskId) , _url(url) , _nam(nam) , _reply(nullptr) { } int UrlDownloader::taskId() const { return _taskId; } void UrlDownloader::start() { _reply = _nam.get(QNetworkRequest(_url)); connect(_reply, SIGNAL(downloadProgress(qint64,qint64)), SLOT(onDownloadProgress(qint64,qint64))); connect(_reply, SIGNAL(readyRead()), SLOT(onReadyRead())); connect(_reply, SIGNAL(finished()), SLOT(onFinished())); } void UrlDownloader::stop() { if (!_reply) return; _reply->disconnect(); _reply->close(); _reply->deleteLater(); _reply = nullptr; } //////////////////////////////////////////////////////////////////////////////// void UrlDownloader::onDownloadProgress(qint64 bytesReceived, qint64 bytesTotal) { emit taskProgress(_taskId, _calculateProgress(bytesReceived, bytesTotal)); } void UrlDownloader::onReadyRead() { emit taskData(_taskId, _reply->readAll()); } void UrlDownloader::onFinished() { QNetworkReply::NetworkError errorCode = _reply->error(); switch(errorCode) { case QNetworkReply::NoError: emit taskProgress(_taskId, 100); emit taskComplete(_taskId); break; default: emit taskError(_taskId, _reply->errorString()); break; } _reply->disconnect(); _reply->deleteLater(); _reply = nullptr; emit taskFinished(this); }
22
116
0.581818
caicaiking
484c7085cea5c8a7255c3081659fbb1693c448f5
5,739
cpp
C++
src/main.cpp
attaoveisi/pseudo_particle_filter
0bcb66b92661c0cd8fdf12db5a57d6f3df1a7940
[ "MIT" ]
1
2021-01-10T10:52:13.000Z
2021-01-10T10:52:13.000Z
src/main.cpp
attaoveisi/pseudo_particle_filter
0bcb66b92661c0cd8fdf12db5a57d6f3df1a7940
[ "MIT" ]
null
null
null
src/main.cpp
attaoveisi/pseudo_particle_filter
0bcb66b92661c0cd8fdf12db5a57d6f3df1a7940
[ "MIT" ]
null
null
null
#include "Base.h" #include "Robot.h" #include "Map.h" #include <matplot/matplot.h> void visualization(int n, Robot robot, int step, std::vector<Robot> p, std::vector<Robot> pr, int num_landmarks) { //Draw the robot, landmarks, particles and resampled particles on a graph matplot::figure(1); //Graph Format matplot::title("MCL, step " + std::to_string(step)); matplot::xlim({0.0, 100.0}); matplot::ylim({0.0, 100.0}); //Draw particles in green for (int i = 0; i < n; i++) { matplot::hold(matplot::on); matplot::plot({ p[i].x }, { p[i].y }, "go"); } matplot::hold(matplot::on); //Draw resampled particles in yellow for (int i = 0; i < n; i++) { matplot::hold(matplot::on); matplot::plot({ pr[i].x }, { pr[i].y }, "yo"); } matplot::hold(matplot::on); //Draw landmarks in red for (int i = 0; i < num_landmarks; i++) { matplot::hold(matplot::on); matplot::plot({ robot.landmarks[i][0] }, { robot.landmarks[i][1] }, "ro"); } //Draw robot position in blue matplot::hold(matplot::on); matplot::plot({ robot.x }, { robot.y }, "bo"); //Save the image and close the plot matplot::show(); std::string fig_name = "./Images/Step" + std::to_string(step) + ".jpg"; std::cout << fig_name << " is saved." <<std::endl; matplot::save(fig_name); } int main() { Base base; // Landmarks Map map; // Map size in meters double map_size = 100.0; map.get_world_size(map_size); int num_landmarks = 8; std::vector<std::vector<double>> landmarks { { 20.0, 20.0 }, { 20.0, 80.0 }, { 20.0, 50.0 }, { 50.0, 20.0 }, { 50.0, 80.0 }, { 80.0, 80.0 }, { 80.0, 20.0 }, { 80.0, 50.0 } }; for (int i = 0; i < num_landmarks; i++){ std::cout << landmarks[i][0] << "\t" << landmarks[i][1] << std::endl; } map.get_landmarks(landmarks, num_landmarks); map.print_map(); //Initialize myrobot object and Initialize a measurment vector Robot myrobot; myrobot.get_world_size(map); myrobot.get_landmarks(map); myrobot.randomized_position(map); //myrobot.set(30.0, 50.0, M_PI / 2.0); myrobot.print_robot(); // Measurement vector std::vector<double> z(num_landmarks); std::vector<double> pz(num_landmarks); //Iterating 50 times over the set of particles int steps = 50; // Create a set of particles int n = 1000; std::vector<Robot> p(n); std::vector<Robot> p_temp(n); std::vector<Robot> p3(n); //std::cout << p[0].sense_noise << std::endl; for (int i = 0; i < n; i++) { p[i].get_world_size(map); p[i].get_landmarks(map); p[i].randomized_position(map); p3[i].get_world_size(map); p3[i].get_landmarks(map); p3[i].randomized_position(map); p[i].set_noise(0.05, 0.05, 5.0); //std::cout << p[i].show_pose() << std::endl; } for (int t = 0; t < steps; t++) { //Move the robot and sense the environment afterwards myrobot.move(0.1, 5.0); z = myrobot.sense(); //std::cout << z[0] << "\t" << z[1] << "\t" << z[2] << "\t" << z[3] << "\t" << z[4] << "\t" << z[5] << "\t" << z[6] << "\t" << z[7] << std::endl; // Simulate a robot motion for each of these particles for (int i = 0; i < n; i++) { p_temp[i] = p[i]; p_temp[i].move(0.1, 5.0); p[i] = p_temp[i]; //std::cout << p[i].show_pose() << std::endl; } //std::cout << p[0].show_pose() << std::endl; //Generate particle weights depending on robot's measurement std::vector<double> w(n); for (int i = 0; i < n; i++) { pz = p[i].sense(); w[i] = p[i].measurement_prob(z); //cout << w[i] << endl; } //Resample the particles with a sample probability proportional to the importance weight int index = base.gen_real_random() * n; //cout << index << endl; double beta = 0.0; double mw = base.max(w, n); //cout << mw; for (int i = 0; i < n; i++) { beta += base.gen_real_random() * 2.0 * mw; while (beta > w[index]) { beta -= w[index]; index = base.mod((index + 1), n); } p3[i] = p[index]; } for (int k=0; k < n; k++) { p[k] = p3[k]; //cout << p[k].show_pose() << endl; } //#### DON'T MODIFY ANYTHING ABOVE HERE! ENTER CODE BELOW #### //Evaluate the error by priting it in this form: // cout << "Step = " << t << ", Evaluation = " << ErrorValue << endl; double sum = 0.0; for (int i = 0; i < n; i++) { //the second part is because of world's cyclicity double dx = base.mod((p[i].x - myrobot.x + (map_size / 2.0)), map_size) - (map_size / 2.0); double dy = base.mod((p[i].y - myrobot.y + (map_size / 2.0)), map_size) - (map_size / 2.0); double err = sqrt(pow(dx, 2) + pow(dy, 2)); sum += err; } sum = sum / n; std::cout << "Step = " << t << ", Evaluation = " << sum << std::endl; //Graph the position of the robot and the particles at each step visualization(n, myrobot, t, p_temp, p3, num_landmarks); } //End of Steps loop return 0; }
33.758824
153
0.488935
attaoveisi
484e9dc8ca5f0efc2867c7a0f00708fa4ff331f0
2,846
cpp
C++
board/board.cpp
maxious/mbed-rak811-ttnmapper
65e336bbbb4dac15a7f9d7fb89f1ee84f0fbebae
[ "Apache-2.0" ]
null
null
null
board/board.cpp
maxious/mbed-rak811-ttnmapper
65e336bbbb4dac15a7f9d7fb89f1ee84f0fbebae
[ "Apache-2.0" ]
null
null
null
board/board.cpp
maxious/mbed-rak811-ttnmapper
65e336bbbb4dac15a7f9d7fb89f1ee84f0fbebae
[ "Apache-2.0" ]
null
null
null
/* / _____) _ | | ( (____ _____ ____ _| |_ _____ ____| |__ \____ \| ___ | (_ _) ___ |/ ___) _ \ _____) ) ____| | | || |_| ____( (___| | | | (______/|_____)_|_|_| \__)_____)\____)_| |_| (C)2015 Semtech Description: Target board general functions implementation License: Revised BSD License, see LICENSE.TXT file include in the project Maintainer: Miguel Luis and Gregory Cristian */ #include "mbed.h" #include "board.h" /*! * Unique Devices IDs register set ( STM32 ) */ #define ID1 ( 0x1FF800D0 ) #define ID2 ( 0x1FF800D4 ) #define ID3 ( 0x1FF800E4 ) DigitalOut GreenLed( LED_1 ); // Active Low DigitalOut BlueLed( LED_2 ); // Active Low GPS Gps( GPS_UART_TX , GPS_UART_RX, GPS_POWER_ON_PIN ); // Gps(tx, rx, en); DigitalIn I2cInterrupt( LIS3DH_INT1_PIN ); I2C I2c(I2C_SDA, I2C_SCL); LIS3DH acc(I2c, LIS3DH_V_CHIP_ADDR); AnalogIn Battery(BAT_LEVEL_PIN); #define AIN_VREF 3300 // STM32 internal refernce #define AIN_VBAT_DIV 2 // Resistor divider /*! * Nested interrupt counter. * * \remark Interrupt should only be fully disabled once the value is 0 */ static uint8_t IrqNestLevel = 0; void BoardDisableIrq( void ) { __disable_irq( ); IrqNestLevel++; } void BoardEnableIrq( void ) { IrqNestLevel--; if( IrqNestLevel == 0 ) { __enable_irq( ); } } void BoardInit( void ) { // Initalize LEDs BlueLed = 0; // Active Low GreenLed = 0; // Active Low TimerTimeCounterInit( ); Gps.enable( 1 ); Gps.init( ); } uint8_t BoardGetBatteryLevel( void ) { // Per LoRaWAN spec; 0 = Charging; 1...254 = level, 255 = N/A return ( Battery.read_u16( ) >> 8 ) + ( Battery.read_u16( ) >> 9 ); } uint32_t BoardGetBatteryVoltage( void ) { return ( Battery.read( ) * AIN_VREF * AIN_VBAT_DIV ); } uint32_t BoardGetRandomSeed( void ) { return ( ( *( uint32_t* )ID1 ) ^ ( *( uint32_t* )ID2 ) ^ ( *( uint32_t* )ID3 ) ); } void BoardGetDevEUI( uint8_t *id ) { uint32_t *pDevEuiHWord = ( uint32_t* )&id[4]; if( *pDevEuiHWord == 0 ) { *pDevEuiHWord = BoardGetRandomSeed( ); } } void BoardGetUniqueId( uint8_t *id ) { id[7] = ( ( *( uint32_t* )ID1 )+ ( *( uint32_t* )ID3 ) ) >> 24; id[6] = ( ( *( uint32_t* )ID1 )+ ( *( uint32_t* )ID3 ) ) >> 16; id[5] = ( ( *( uint32_t* )ID1 )+ ( *( uint32_t* )ID3 ) ) >> 8; id[4] = ( ( *( uint32_t* )ID1 )+ ( *( uint32_t* )ID3 ) ); id[3] = ( ( *( uint32_t* )ID2 ) ) >> 24; id[2] = ( ( *( uint32_t* )ID2 ) ) >> 16; id[1] = ( ( *( uint32_t* )ID2 ) ) >> 8; id[0] = ( ( *( uint32_t* )ID2 ) ); } BoardVersion_t BoardGetVersion( void ) { return BOARD_VERSION_3; }
22.409449
85
0.556219
maxious
484ffbfe261670a5eea4eeaba9d84f2fc5848b26
1,544
cpp
C++
sg/scene/transfer_function/Sequential.cpp
ebachard/ospray_studio
78928c93b482f9f95aa300c8f58c728dadedbe2f
[ "Apache-2.0" ]
52
2018-10-09T23:56:32.000Z
2022-03-25T09:27:40.000Z
sg/scene/transfer_function/Sequential.cpp
ebachard/ospray_studio
78928c93b482f9f95aa300c8f58c728dadedbe2f
[ "Apache-2.0" ]
11
2018-11-19T18:51:47.000Z
2022-03-28T14:03:57.000Z
sg/scene/transfer_function/Sequential.cpp
ebachard/ospray_studio
78928c93b482f9f95aa300c8f58c728dadedbe2f
[ "Apache-2.0" ]
8
2019-02-10T00:16:24.000Z
2022-02-17T19:50:15.000Z
// Copyright 2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #include "TransferFunction.h" namespace ospray { namespace sg { // Turbo ///////////////////////////////////////////////////////////////////// struct OSPSG_INTERFACE Turbo : public TransferFunction { Turbo(); virtual ~Turbo() override = default; }; OSP_REGISTER_SG_NODE_NAME(Turbo, transfer_function_turbo); Turbo::Turbo() : TransferFunction("piecewiseLinear") { colors.clear(); colors.emplace_back(0.190, 0.072, 0.232); colors.emplace_back(0.276, 0.421, 0.891); colors.emplace_back(0.158, 0.736, 0.923); colors.emplace_back(0.197, 0.949, 0.595); colors.emplace_back(0.644, 0.990, 0.234); colors.emplace_back(0.933, 0.812, 0.227); colors.emplace_back(0.984, 0.493, 0.128); colors.emplace_back(0.816, 0.185, 0.018); colors.emplace_back(0.480, 0.016, 0.011); initOpacities(); createChildData("color", colors); createChildData("opacity", opacities); } // Grayscale ///////////////////////////////////////////////////////////////// struct OSPSG_INTERFACE Grayscale : public TransferFunction { Grayscale(); virtual ~Grayscale() override = default; }; OSP_REGISTER_SG_NODE_NAME(Grayscale, transfer_function_grayscale); Grayscale::Grayscale() : TransferFunction("piecewiseLinear") { colors.clear(); colors.emplace_back(0.000, 0.000, 0.000); colors.emplace_back(1.000, 1.000, 1.000); initOpacities(); createChildData("color", colors); createChildData("opacity", opacities); } } // namespace sg } // namespace ospray
24.903226
78
0.658031
ebachard
48564be537c1b63c5f073e76ca0842d5adbc3a67
26,442
cpp
C++
libbiokanga/NeedlemanWunsch.cpp
rsuchecki/biokanga
ef0fa1cf58fb2903ae18d14e5b0f84de7b7e744e
[ "MIT" ]
null
null
null
libbiokanga/NeedlemanWunsch.cpp
rsuchecki/biokanga
ef0fa1cf58fb2903ae18d14e5b0f84de7b7e744e
[ "MIT" ]
null
null
null
libbiokanga/NeedlemanWunsch.cpp
rsuchecki/biokanga
ef0fa1cf58fb2903ae18d14e5b0f84de7b7e744e
[ "MIT" ]
null
null
null
/* * CSIRO Open Source Software License Agreement (GPLv3) * Copyright (c) 2017, Commonwealth Scientific and Industrial Research Organisation (CSIRO) ABN 41 687 119 230. * See LICENSE for the complete license information (https://github.com/csiro-crop-informatics/biokanga/LICENSE) * Contact: Alex Whan <alex.whan@csiro.au> */ #include "stdafx.h" #ifdef _WIN32 #include "./commhdrs.h" #else #include "./commhdrs.h" #endif CNeedlemanWunsch::CNeedlemanWunsch(void) { m_pTrcBckCells = NULL; m_pProbe = NULL; m_pTarg = NULL; m_pColBands = NULL; Reset(); } CNeedlemanWunsch::~CNeedlemanWunsch(void) { Reset(); } // Reset // Resets instance to that immediately following that of instance construction // Note that all buffers will be deallocated.. void CNeedlemanWunsch::Reset(void) { if(m_pTrcBckCells != NULL) { #ifdef _WIN32 free(m_pTrcBckCells); // was allocated with malloc/realloc, or mmap/mremap, not c++'s new.... #else if(m_pTrcBckCells != MAP_FAILED) munmap(m_pTrcBckCells,m_TrcBckCellsAllocdSize); #endif } m_TrcBckCellsAllocdSize = 0; m_TrcBckCellsAllocd = 0; m_TrcBckCellsUsed = 0; if(m_pProbe != NULL) { delete m_pProbe; m_pProbe = NULL; } m_ProbeAllocd = 0; // actual m_pProbe alloc'd size (in teNWSeqBases's) m_ProbeLen = 0; // current probe length if(m_pColBands != NULL) // each column in the matrix will contain a band of active cells { delete m_pColBands; m_pColBands = NULL; } m_ColBandsAllocd = 0; m_ColBandsUsed = 0; if(m_pTarg != NULL) // alloc'd target sequence memory { delete m_pTarg; m_pTarg = NULL; } m_TargAllocd = 0; // actual m_pTarg alloc'd size (in teNWSeqBases's) m_TargLen = 0; // current targ length m_MatchScore = cNWDfltMatchScore; // score for matching bases m_MismatchScore = cNWDfltMismatchScore; // mismatch penalty m_GapOpenScore = cNWDfltGapOpenScore; // gap opening penalty m_GapExtScore = cNWDfltGapExtScore; // gap extension penalty m_PeakScore = 0; m_NumBasesAligned = 0; m_NumBasesExact = 0; m_NumProbeInserts = 0; m_NumTargInserts = 0; m_ProbeAlignStartOfs = 0; m_TargAlignStartOfs = 0; m_bBanded = false; m_bAligned = false; } // SetScores // Set match, mismatch, gap opening and gap extension scores // Note that a check is made to ensure that MatchScore is > 0 and // that all other scores are <= 0 bool CNeedlemanWunsch::SetScores(int MatchScore,int MismatchScore,int GapOpenScore,int GapExtScore) { if(MatchScore <= 0 || MismatchScore > 0 || GapOpenScore > 0 || GapExtScore > 0) return(false); m_MatchScore = MatchScore; // score for matching bases m_MismatchScore = MismatchScore; // mismatch penalty m_GapOpenScore = GapOpenScore; // gap opening penalty m_GapExtScore = GapExtScore; // gap extension penalty m_ColBandsUsed = 0; m_TrcBckCellsUsed = 0; m_NumBasesAligned = 0; m_NumBasesExact = 0; m_NumProbeInserts = 0; m_NumTargInserts = 0; m_ProbeAlignStartOfs = 0; m_TargAlignStartOfs = 0; m_bAligned = false; m_bAligned = false; return(true); } // SetProbe // Set probe sequence to use in subsequent alignments // Probe sequence is used as the row increment // Only restriction is that the length must be in the range of cNWMinProbeTargLen to cNWMaxProbeTargLen bool CNeedlemanWunsch::SetProbe(UINT32 Len,etSeqBase *pSeq) { if(Len < cNWMinProbeOrTargLen || Len > cNWMaxProbeOrTargLen || pSeq == NULL) // can't be bothered with very short probes! return(false); if(m_pColBands == NULL || m_ColBandsAllocd < Len || m_ColBandsAllocd > Len * 2) { if(m_pColBands != NULL) delete m_pColBands; m_ColBandsAllocd = Len + 100; m_pColBands = new tsNWColBand [m_ColBandsAllocd]; if(m_pColBands == NULL) return(false); } if(m_pProbe == NULL || m_ProbeAllocd < Len) { if(m_pProbe != NULL) delete m_pProbe; m_ProbeAllocd = Len + 100; m_pProbe = new etSeqBase [Len + 100]; if(m_pProbe == NULL) return(false); } memmove(m_pProbe,pSeq,Len); m_ProbeLen = Len; m_ColBandsUsed = 0; m_TrcBckCellsUsed = 0; m_NumBasesAligned = 0; m_NumBasesExact = 0; m_NumProbeInserts = 0; m_NumTargInserts = 0; m_ProbeAlignStartOfs = 0; m_TargAlignStartOfs = 0; m_bAligned = false; return(true); } // SetTarg // Set target sequence to use in subsequent alignments // Target sequence is used as the column increment // Only restriction is that the length must be in the range of cNWMinProbeTargLen to cNWMaxProbeTargLen bool CNeedlemanWunsch::SetTarg(UINT32 Len,etSeqBase *pSeq) { if(Len < cNWMinProbeOrTargLen || Len > cNWMaxProbeOrTargLen || pSeq == NULL) // can't be bothered with very short targets! return(false); if(m_pTarg == NULL || m_TargAllocd < Len) { if(m_pTarg != NULL) delete m_pTarg; m_TargAllocd = Len + 100; m_pTarg = new etSeqBase [m_TargAllocd]; if(m_pTarg == NULL) return(false); } memmove(m_pTarg,pSeq,Len); m_TargLen = Len; m_ColBandsUsed = 0; m_TrcBckCellsUsed = 0; m_NumBasesAligned = 0; m_NumBasesExact = 0; m_NumProbeInserts = 0; m_NumTargInserts = 0; m_ProbeAlignStartOfs = 0; m_TargAlignStartOfs = 0; m_bAligned = false; return(true); } // Align // Align probe SetProbe() against target SetTarg() using scores specified via SetScores() // Needleman-Wunsch style global alignment dynamic programing with optimisations // Returns the peak score of all aligned subsequences int // peak score of all subsequence alignments CNeedlemanWunsch::Align(void) { UINT32 IdxP; // current index into m_Probe[] UINT32 IdxT; // current index into m_Targ[] UINT32 NumCells; // m_ProbeLen * m_TargLen - total number of cells int NewScore; int DiagScore; // putative diagonal score int LeftScore; // putative left score int DownScore; // putative down score int PrevScore; // score in back referenced cell tNWTrcBckCell DiagDir; // to hold back reference direction as diagonal etSeqBase *pProbe; // current &m_Probe[IdxP] etSeqBase ProbeBase; // current m_Probe[IdxP] etSeqBase *pTarg; // current &m_Targ[IdxT] etSeqBase TargBase; // current m_Targ[IdxT] tNWTrcBckCell *pCell; tNWTrcBckCell *pPrevCell; bool bMatch; m_bAligned = false; if(m_ProbeLen < cNWMinProbeOrTargLen || m_TargLen < cNWMinProbeOrTargLen || ((INT64)m_ProbeLen * (INT64)m_TargLen > (INT64)cNWMaxCells)) return(eBSFerrMaxEntries); NumCells = m_ProbeLen * m_TargLen; if(m_pTrcBckCells == NULL || m_TrcBckCellsAllocd < NumCells || ((UINT64)m_TrcBckCellsAllocd > (UINT64)NumCells * 2)) { NumCells += 100; // small overallocation as a saftety margin if(m_pTrcBckCells != NULL) { #ifdef _WIN32 free(m_pTrcBckCells); // was allocated with malloc/realloc, or mmap/mremap, not c++'s new.... #else if(m_pTrcBckCells != MAP_FAILED) munmap(m_pTrcBckCells,m_TrcBckCellsAllocdSize); #endif } m_TrcBckCellsAllocd = NumCells; m_TrcBckCellsAllocdSize = sizeof(tNWTrcBckCell) * m_TrcBckCellsAllocd; #ifdef _WIN32 m_pTrcBckCells = (tNWTrcBckCell *) malloc(m_TrcBckCellsAllocdSize); if(m_pTrcBckCells == NULL) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Fatal: unable to allocate %lld bytes contiguous memory for traceback cells",(INT64)m_TrcBckCellsAllocdSize); m_TrcBckCellsAllocdSize = 0; m_TrcBckCellsAllocd = 0; return(eBSFerrMem); } #else // gnu malloc is still in the 32bit world and seems to have issues if more than 2GB allocation m_pTrcBckCells = (tNWTrcBckCell *)mmap(NULL,m_TrcBckCellsAllocdSize, PROT_READ | PROT_WRITE,MAP_PRIVATE | MAP_ANONYMOUS, -1,0); if(m_pTrcBckCells == MAP_FAILED) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Fatal: unable to allocate %lld bytes contiguous memory for traceback cells",(INT64)m_TrcBckCellsAllocdSize); m_TrcBckCellsAllocdSize = 0; m_TrcBckCellsAllocd = 0; return(eBSFerrMem); } #endif } m_TrcBckCellsUsed = NumCells; m_PeakScore = 0; m_NumBasesAligned = 0; m_NumBasesExact = 0; m_ProbeAlignStartOfs = 0; m_TargAlignStartOfs = 0; pProbe = m_pProbe; pCell = m_pTrcBckCells; for(IdxP = 0; IdxP < m_ProbeLen; IdxP++) { ProbeBase = *pProbe++ & ~cRptMskFlg; pCell = &m_pTrcBckCells[(IdxP * m_TargLen)]; pTarg = &m_pTarg[0]; for(IdxT = 0; IdxT < m_TargLen; IdxT++, pCell++) { TargBase = *pTarg++ & ~cRptMskFlg; bMatch = ProbeBase == TargBase; // calc the 3 scores // diagonal is either MatchScore or MismatchScore added to prev diagonal score if(IdxT > 0 && IdxP > 0) { pPrevCell = pCell - m_TargLen - 1; PrevScore = (*pPrevCell & cNWScoreMsk); if(PrevScore & cNWScoreNegFlg) // if sign of score is negative then sign extend to left making score into negative int PrevScore |= ~cNWScoreMsk; DiagScore = PrevScore + (bMatch ? m_MatchScore : m_MismatchScore); } else // either first column or row, these use implied pre-existing scores related to the cell distance from the matrix origin { DiagScore = bMatch ? m_MatchScore : m_MismatchScore; if(IdxT > 0) { pPrevCell = pCell - 1; PrevScore = (*pPrevCell & cNWScoreMsk); if(PrevScore & cNWScoreNegFlg) // if sign of score is negative then sign extend to left making score into negative int PrevScore |= ~cNWScoreMsk; DiagScore += m_GapOpenScore; DiagScore += PrevScore; DiagDir = cNWTrcBckDownFlg; } else if(IdxP > 0) { pPrevCell = pCell - m_TargLen; PrevScore = (*pPrevCell & cNWScoreMsk); if(PrevScore & cNWScoreNegFlg) // if sign of score is negative then sign extend to left making score into negative int PrevScore |= ~cNWScoreMsk; DiagScore += m_GapOpenScore; DiagScore += PrevScore; DiagDir = cNWTrcBckLeftFlg; } else DiagDir = 0; *pCell = (DiagScore & cNWScoreMsk) | DiagDir | (bMatch ? cNWTrcBckMatchFlg : 0); if((IdxT == 0 && IdxP == 0) || DiagScore > m_PeakScore) m_PeakScore = DiagScore; continue; } // leftscore is either GapExtScore (if gap already opened) or GapOpenScore added to prev left score pPrevCell = pCell - m_TargLen; PrevScore = (*pPrevCell & cNWScoreMsk); if(PrevScore & cNWScoreNegFlg) // if sign of score is negative then sign extend to left making score into negative int PrevScore |= ~cNWScoreMsk; LeftScore = PrevScore + ((*pPrevCell & cNWGapOpnFlg) ? m_GapExtScore : m_GapOpenScore); // down score is either GapExtScore (if gap already opened) or GapOpenScore added to prev down score pPrevCell = pCell - 1; PrevScore = (*pPrevCell & cNWScoreMsk); if(PrevScore & cNWScoreNegFlg) // if sign of score is negative then sign extend to left making score into negative int PrevScore |= ~cNWScoreMsk; DownScore = PrevScore + ((*pPrevCell & cNWGapOpnFlg) ? m_GapExtScore : m_GapOpenScore); // select highest score into cell together with traceback and gap opened flag.. if(DiagScore >= DownScore && DiagScore >= LeftScore) { *pCell = (DiagScore & cNWScoreMsk) | cNWTrcBckDiagFlg | (bMatch ? cNWTrcBckMatchFlg : 0); NewScore = DiagScore; } else if(DownScore >= LeftScore) { *pCell = (DownScore & cNWScoreMsk) | cNWTrcBckDownFlg | (bMatch ? 0 : cNWGapOpnFlg); NewScore = DownScore; } else { *pCell = (LeftScore & cNWScoreMsk) | cNWTrcBckLeftFlg | (bMatch ? 0 : cNWGapOpnFlg); NewScore = LeftScore; } if(NewScore > m_PeakScore) m_PeakScore = NewScore; } } m_bAligned = true; return(m_PeakScore); } // GetNumAlignedBases // get number of bases which align (exactly plus subs), excluding InDels // Also internally updates m_ProbeAlignStart and m_TargAlignStart int CNeedlemanWunsch::GetNumAlignedBases(void) // get number of bases which align (exactly plus subs), excluding InDels { tNWTrcBckCell TrcBckDir; tNWTrcBckCell *pPeakCell; UINT32 ProbeIdx; UINT32 TargIdx; if(!m_bAligned) return(0); if(m_NumBasesAligned > 0) return(m_NumBasesAligned); m_ProbeAlignStartOfs = m_ProbeLen - 1; m_TargAlignStartOfs = m_TargLen - 1; m_NumBasesAligned = 0; m_NumBasesExact = 0; m_NumProbeInserts = 0; m_NumTargInserts = 0; if(m_bBanded) { ProbeIdx = m_ProbeLen; TargIdx = m_TargLen; pPeakCell = DerefBandCell(ProbeIdx,TargIdx); } else pPeakCell = &m_pTrcBckCells[(m_ProbeLen * m_TargLen) - 1]; do { switch(TrcBckDir = (*pPeakCell & cNWTrcBckMsk)) { case cNWTrcBckDiagFlg: // back on the diagonal, either a match or mismatch m_NumBasesAligned += 1; if(*pPeakCell & cNWTrcBckMatchFlg) m_NumBasesExact += 1; if(m_bBanded) { ProbeIdx -= 1; TargIdx -= 1; pPeakCell = DerefBandCell(ProbeIdx,TargIdx); } else pPeakCell -= m_TargLen + 1; m_ProbeAlignStartOfs -= 1; m_TargAlignStartOfs -= 1; break; case cNWTrcBckLeftFlg: // left, insertion into probe or deletion from target if(m_bBanded) { ProbeIdx -= 1; pPeakCell = DerefBandCell(ProbeIdx,TargIdx); } else pPeakCell -= m_TargLen; // treating as insertion into probe m_ProbeAlignStartOfs -= 1; m_NumProbeInserts += 1; break; case cNWTrcBckDownFlg: // down, insertion into target or deletion if(m_bBanded) { TargIdx -= 1; pPeakCell = DerefBandCell(ProbeIdx,TargIdx); } else pPeakCell -= 1; // treating as insertion into target m_TargAlignStartOfs -= 1; m_NumTargInserts += 1; break; default: // cell has no trace back so must be final cell in path m_NumBasesAligned += 1; if(*pPeakCell & cNWTrcBckMatchFlg) m_NumBasesExact += 1; break; } } while(TrcBckDir); return(m_NumBasesAligned); } int CNeedlemanWunsch::GetProbeAlign(UINT32 Len, etSeqBase *pBuff) // get probe alignment { tNWTrcBckCell TrcBckDir; tNWTrcBckCell *pPeakCell; etSeqBase *pProbe; etSeqBase *pProbeStart; UINT32 ProbeIdx; UINT32 TargIdx; if(!GetNumAlignedBases()) return(0); if(Len < (m_NumBasesAligned + m_NumProbeInserts + m_NumTargInserts)) return(0); if(m_bBanded) { ProbeIdx = m_ProbeLen; TargIdx = m_TargLen; pPeakCell = DerefBandCell(ProbeIdx,TargIdx); } else pPeakCell = &m_pTrcBckCells[(m_ProbeLen * m_TargLen) - 1]; pProbeStart = m_pProbe + m_ProbeAlignStartOfs; pProbe = pProbeStart + m_NumBasesAligned + m_NumProbeInserts - 1; pBuff += m_NumBasesAligned + m_NumProbeInserts + m_NumTargInserts - 1; do { TrcBckDir = *pPeakCell & cNWTrcBckMsk; switch(TrcBckDir) { case cNWTrcBckDiagFlg: // back on the diagonal, report base *pBuff-- = *pProbe--; if(m_bBanded) { ProbeIdx -= 1; TargIdx -= 1; pPeakCell = DerefBandCell(ProbeIdx,TargIdx); } else pPeakCell -= m_TargLen + 1; break; case cNWTrcBckLeftFlg: // left, treating as insertion into probe so report base *pBuff-- = *pProbe--; if(m_bBanded) { ProbeIdx -= 1; pPeakCell = DerefBandCell(ProbeIdx,TargIdx); } else pPeakCell -= m_TargLen; break; case cNWTrcBckDownFlg: // down, treating as insertion into target so report as InDel *pBuff-- = eBaseInDel; if(m_bBanded) { TargIdx -= 1; pPeakCell = DerefBandCell(ProbeIdx,TargIdx); } else pPeakCell -= 1; break; default: // no direction, must be final cell so report probe base *pBuff = *pProbe; break; } } while(TrcBckDir); return(m_NumBasesAligned + m_NumProbeInserts + m_NumTargInserts); } int CNeedlemanWunsch::GetTargAlign(UINT32 Len, etSeqBase *pBuff) // get target alignment { tNWTrcBckCell TrcBckDir; tNWTrcBckCell *pPeakCell; etSeqBase *pTarg; etSeqBase *pTargStart; UINT32 ProbeIdx; UINT32 TargIdx; if(!GetNumAlignedBases()) return(0); if(Len < (m_NumBasesAligned + m_NumProbeInserts + m_NumTargInserts)) return(0); if(m_bBanded) { ProbeIdx = m_ProbeLen; TargIdx = m_TargLen; pPeakCell = DerefBandCell(ProbeIdx,TargIdx); } else pPeakCell = &m_pTrcBckCells[(m_ProbeLen * m_TargLen) - 1]; pTargStart = m_pTarg + m_TargAlignStartOfs; pTarg = pTargStart + + m_NumBasesAligned + m_NumTargInserts - 1; pBuff += m_NumBasesAligned + m_NumProbeInserts + m_NumTargInserts - 1; do { TrcBckDir = *pPeakCell & cNWTrcBckMsk; switch(TrcBckDir) { case cNWTrcBckDiagFlg: // back on the diagonal, report base *pBuff-- = *pTarg--; if(m_bBanded) { ProbeIdx -= 1; TargIdx -= 1; pPeakCell = DerefBandCell(ProbeIdx,TargIdx); } else pPeakCell -= m_TargLen + 1; break; case cNWTrcBckLeftFlg: // left, treating as insertion into probe so report InDel *pBuff-- = eBaseInDel; if(m_bBanded) { ProbeIdx -= 1; pPeakCell = DerefBandCell(ProbeIdx,TargIdx); } else pPeakCell -= m_TargLen; break; case cNWTrcBckDownFlg: // down, treating as insertion into target so report as target base *pBuff-- = *pTarg--; if(m_bBanded) { TargIdx -= 1; pPeakCell = DerefBandCell(ProbeIdx,TargIdx); } else pPeakCell -= 1; break; default: // no direction, must be final cell so report target base *pBuff = *pTarg; break; } } while(TrcBckDir); return(m_NumBasesAligned + m_NumProbeInserts + m_NumTargInserts); } int // returned total alignment length between probe and target including InDels CNeedlemanWunsch::GetAlignStats(UINT32 *pNumAlignedBases, // returned number of bases aligning between probe and target UINT32 *pNumExactBases, // of the aligning bases there were this many exact matches, remainder were substitutions UINT32 *pNumProbeInsertBases, // this many bases were inserted into the probe relative to the target UINT32 *pNumTargInsertBases) // this many bases were inserted into the target relative to the probe { if(!GetNumAlignedBases()) return(-1); if(pNumAlignedBases != NULL) *pNumAlignedBases = m_NumBasesAligned; if(pNumExactBases != NULL) *pNumExactBases = m_NumBasesExact; if(pNumProbeInsertBases != NULL) *pNumProbeInsertBases = m_NumProbeInserts; if(pNumTargInsertBases != NULL) *pNumTargInsertBases = m_NumTargInserts; return(m_NumBasesAligned + m_NumProbeInserts + m_NumTargInserts); } // // Helper functions for Band cell dereferencing tNWTrcBckCell * // returns ptr to newly allocated cell or NULL if errors CNeedlemanWunsch::AllocBandCell(UINT32 ProbeBasePsn, // current probe base position 1..m_ProbeLen UINT32 TargBasePsn) // current target base position 1..m_TargLen { tsNWColBand *pNWColBand; tNWTrcBckCell *pTrcBckCell; if(ProbeBasePsn == 0 || ProbeBasePsn > m_ProbeLen || TargBasePsn == 0 || TargBasePsn > m_TargLen) return(NULL); if((ProbeBasePsn - 1) > m_ColBandsUsed || ProbeBasePsn < m_ColBandsUsed) return(NULL); if(m_TrcBckCellsUsed == m_TrcBckCellsAllocd) // need to allocate more? { size_t ReallocSize; UINT32 EstReqCells; tNWTrcBckCell *pRealloc; EstReqCells = 10000 + (UINT32)(((double)m_ProbeLen / ProbeBasePsn) * m_TrcBckCellsAllocd); ReallocSize = sizeof(tNWTrcBckCell) * EstReqCells; #ifdef _WIN32 pRealloc = (tNWTrcBckCell *)realloc(m_pTrcBckCells,ReallocSize); #else pRealloc = (tNWTrcBckCell *)mremap(m_pTrcBckCells,m_TrcBckCellsAllocdSize,ReallocSize,MREMAP_MAYMOVE); if(pRealloc == MAP_FAILED) pRealloc = NULL; #endif if(pRealloc == NULL) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"AllocBandCell: traceback cell memory re-allocation to %lld bytes - %s",(INT64)ReallocSize,strerror(errno)); return(NULL); } m_TrcBckCellsAllocdSize = ReallocSize; m_TrcBckCellsAllocd = EstReqCells; m_pTrcBckCells = pRealloc; } pNWColBand = &m_pColBands[ProbeBasePsn - 1]; pTrcBckCell = &m_pTrcBckCells[m_TrcBckCellsUsed++]; *pTrcBckCell = 0; if(ProbeBasePsn > m_ColBandsUsed) { m_ColBandsUsed += 1; pNWColBand->StartTargBasePsn = TargBasePsn; pNWColBand->EndTargBasePsn = TargBasePsn; pNWColBand->TrcBckCellPsn = m_TrcBckCellsUsed; return(pTrcBckCell); } if(pNWColBand->EndTargBasePsn != TargBasePsn - 1) { m_TrcBckCellsUsed -= 1; return(NULL); } pNWColBand->EndTargBasePsn = TargBasePsn; return(pTrcBckCell); } tNWTrcBckCell * // returns ptr to cell or NULL if errors CNeedlemanWunsch::DerefBandCell(UINT32 ProbeBasePsn, // current probe base position 1..m_ProbeLen UINT32 TargBasePsn) // current target base position 1..m_TargLen { UINT32 BandIdx; tsNWColBand *pNWColBand; if(m_ColBandsUsed == 0 || ProbeBasePsn == 0 || ProbeBasePsn > m_ColBandsUsed || TargBasePsn == 0 || TargBasePsn > m_TargLen) return(NULL); pNWColBand = &m_pColBands[ProbeBasePsn - 1]; if(TargBasePsn < pNWColBand->StartTargBasePsn || TargBasePsn > pNWColBand->EndTargBasePsn || pNWColBand->TrcBckCellPsn == 0) return(NULL); BandIdx = pNWColBand->TrcBckCellPsn - 1 + (TargBasePsn - pNWColBand->StartTargBasePsn); return(&m_pTrcBckCells[BandIdx]); } tNWTrcBckCell * // returns ptr to cell or NULL if errors CNeedlemanWunsch::DerefBandCellLeft(UINT32 ProbeBasePsn, // current probe base position 1..m_ProbeLen UINT32 TargBasePsn) // current target base position 1..m_TargLen { UINT32 BandIdx; tsNWColBand *pNWColBand; if(m_ColBandsUsed == 0 || ProbeBasePsn < 2 || ProbeBasePsn > m_ColBandsUsed || TargBasePsn == 0 || TargBasePsn > m_TargLen) return(NULL); pNWColBand = &m_pColBands[ProbeBasePsn - 2]; if(TargBasePsn < pNWColBand->StartTargBasePsn || TargBasePsn > pNWColBand->EndTargBasePsn || pNWColBand->TrcBckCellPsn == 0) return(NULL); BandIdx = pNWColBand->TrcBckCellPsn - 1 + (TargBasePsn - pNWColBand->StartTargBasePsn); return(&m_pTrcBckCells[BandIdx]); } tNWTrcBckCell * // returns ptr to cell or NULL if errors CNeedlemanWunsch::DerefBandCellDiag(UINT32 ProbeBasePsn, // current probe base position 1..m_ProbeLen UINT32 TargBasePsn) // current target base position 1..m_TargLen { UINT32 BandIdx; tsNWColBand *pNWColBand; if(m_ColBandsUsed == 0 || ProbeBasePsn < 2 || ProbeBasePsn > m_ColBandsUsed || TargBasePsn < 2 || TargBasePsn > m_TargLen) return(NULL); TargBasePsn -= 1; pNWColBand = &m_pColBands[ProbeBasePsn - 2]; if(TargBasePsn < pNWColBand->StartTargBasePsn || TargBasePsn > pNWColBand->EndTargBasePsn || pNWColBand->TrcBckCellPsn == 0) return(NULL); BandIdx = pNWColBand->TrcBckCellPsn - 1 + (TargBasePsn - pNWColBand->StartTargBasePsn); return(&m_pTrcBckCells[BandIdx]); } tNWTrcBckCell * // returns ptr to cell or NULL if errors CNeedlemanWunsch::DerefBandCellDown(UINT32 ProbeBasePsn, // current probe base position 1..m_ProbeLen UINT32 TargBasePsn) // current target base position 1..m_TargLen { UINT32 BandIdx; tsNWColBand *pNWColBand; if(m_ColBandsUsed == 0 || ProbeBasePsn == 0 || ProbeBasePsn > m_ColBandsUsed || TargBasePsn == 0 || TargBasePsn > m_TargLen) return(NULL); pNWColBand = &m_pColBands[ProbeBasePsn - 1]; if(TargBasePsn < pNWColBand->StartTargBasePsn || TargBasePsn > pNWColBand->EndTargBasePsn || pNWColBand->TrcBckCellPsn == 0) return(NULL); BandIdx = pNWColBand->TrcBckCellPsn - 1 + (TargBasePsn - pNWColBand->StartTargBasePsn); return(&m_pTrcBckCells[BandIdx - 1]); } int CNeedlemanWunsch::DumpScores(char *pszFile, // dump Smith-Waterman matrix to this csv file char Down, // use this char to represent cell down link representing base inserted into target relative to probe char Left, // use this char to represent cell left link representing base inserted into probe relative to target char Diag) // use this char to represent cell diagonal representing matching base either exact or mismatch { char *pszBuff; char *pRow; UINT32 BuffIdx; UINT32 TargIdx; UINT32 ProbeIdx; tNWTrcBckCell TrcBckDir; int TrcBckScore; int hDumpFile; tNWTrcBckCell *pCell; UINT32 EstDumpLen; if(m_bBanded) { gDiagnostics.DiagOut(eDLWarn,gszProcName,"Banded DumpScores not currently supported"); return(eBSFerrParams); } if(!m_bAligned || pszFile == NULL || pszFile[0] == '\0') return(eBSFerrParams); EstDumpLen = (UINT32)min((UINT64)m_TargLen * m_ProbeLen * 10,(UINT64)0x03ffff); if((pszBuff = new char [EstDumpLen])==NULL) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to allocate dump buffer memory %d bytes",EstDumpLen); return(eBSFerrMem); } #ifdef _WIN32 if((hDumpFile = open(pszFile, _O_RDWR | _O_BINARY | _O_SEQUENTIAL | _O_CREAT | _O_TRUNC, _S_IREAD | _S_IWRITE ))==-1) #else if((hDumpFile = open(pszFile,O_RDWR | O_CREAT | O_TRUNC,S_IREAD | S_IWRITE))==-1) #endif { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to create %s - %s",pszFile,strerror(errno)); return(eBSFerrCreateFile); } // target bases along top as columns, probe bases vertically as rows pRow = pszBuff; for(BuffIdx = TargIdx = 0; TargIdx < m_TargLen; TargIdx++) { BuffIdx += sprintf(&pszBuff[BuffIdx],",\" \",\"%c\"", CSeqTrans::MapBase2Ascii(m_pTarg[TargIdx])); if(BuffIdx + 1000 > EstDumpLen) { CUtility::SafeWrite(hDumpFile,pszBuff,BuffIdx); BuffIdx = 0; } } pCell = m_pTrcBckCells; for(ProbeIdx = 0; ProbeIdx < m_ProbeLen; ProbeIdx++) { BuffIdx += sprintf(&pszBuff[BuffIdx],"\n%c",CSeqTrans::MapBase2Ascii(m_pProbe[ProbeIdx])); for(TargIdx = 0; TargIdx < m_TargLen; TargIdx++,pCell++) { TrcBckDir = *pCell & cNWTrcBckMsk; TrcBckScore = *pCell & cNWScoreMsk; if(TrcBckScore & cNWScoreNegFlg) // if sign of score is negative then sign extend to left making score into negative int TrcBckScore |= ~cNWScoreMsk; if(TrcBckDir == cNWTrcBckDiagFlg) BuffIdx += sprintf(&pszBuff[BuffIdx],",\"%c\",%d",Diag,TrcBckScore); else { if(TrcBckDir == cNWTrcBckDownFlg) BuffIdx += sprintf(&pszBuff[BuffIdx],",\"%c\",%d",Down,TrcBckScore); else { if(TrcBckDir == cNWTrcBckLeftFlg) BuffIdx += sprintf(&pszBuff[BuffIdx],",\"%c\",%d",Left,TrcBckScore); else BuffIdx += sprintf(&pszBuff[BuffIdx],",\" \",%d",TrcBckScore); } } if(BuffIdx + 1000 > EstDumpLen) { CUtility::SafeWrite(hDumpFile,pszBuff,BuffIdx); BuffIdx = 0; } } } if(BuffIdx) CUtility::SafeWrite(hDumpFile,pszBuff,BuffIdx); #ifdef _WIN32 _commit(hDumpFile); #else fsync(hDumpFile); #endif close(hDumpFile); return(eBSFSuccess); }
31.516091
154
0.699115
rsuchecki
48565b4701e322be364081f515a1ecdd9a93f66f
14,757
cpp
C++
src/main.cpp
JamesBremner/pack2
b6156f5621206d9836a8d52172641a94fa52df13
[ "BSD-2-Clause" ]
2
2020-03-17T00:46:50.000Z
2020-04-13T21:22:10.000Z
src/main.cpp
JamesBremner/pack2
b6156f5621206d9836a8d52172641a94fa52df13
[ "BSD-2-Clause" ]
null
null
null
src/main.cpp
JamesBremner/pack2
b6156f5621206d9836a8d52172641a94fa52df13
[ "BSD-2-Clause" ]
null
null
null
#include <iostream> #include <sstream> #include <memory> #include <vector> #include <algorithm> #include <cutest.h> using namespace std; #include "pack2.h" TEST( CutList ) { pack2::cPackEngine E; E.add( pack2::bin_t( new pack2::cBin( "Bin1", 100, 100 )) ); E.addItem( "Item1", 20, 20 ); E.addItem( "Item2", 20, 20 ); Pack( E ); auto L = pack2::CutList( E ); // for( auto& c : L ) // { // for( int v : c ) // std::cout << v << ", "; // std::cout << "\n"; // } CHECK_EQUAL( 3, L.size() ); CHECK_EQUAL( 20, L[2][1] ); CHECK_EQUAL( 0, L[2][2] ); CHECK_EQUAL( 20, L[2][3] ); CHECK_EQUAL( 40, L[2][4] ); } TEST( CutListJoin ) { pack2::cPackEngine E; E.add( pack2::bin_t( new pack2::cBin( "CutListJoin", 1000, 1000 )) ); E.addItem( "Item1", 500, 200 ); E.addItem( "Item2", 500, 200 ); E.addItem( "Item3", 200, 20 ); E.addItem( "Item4", 600, 20 ); Pack( E ); auto L = pack2::CutList( E ); // for( auto& c : L ) // { // for( int v : c ) // std::cout << v << ", "; // std::cout << "\n"; // } CHECK_EQUAL( 6, L.size() ); } TEST( spin ) { pack2::cPackEngine E; auto b = pack2::bin_t( new pack2::cBin( "Bin1", 20, 100 )); E.add( b ); E.addItem( "Item1", 100, 10 ); E.addItem( "Item2", 100, 10 ); Pack( E ); CHECK_EQUAL( 0, BinCount( E ) ); E.clear(); b = pack2::bin_t( new pack2::cBin( "Bin1", 20, 100 )); E.add( b ); E.addItem( "Item1", 100, 10 ); E.addItem( "Item2", 100, 10 ); E.items()[0]->spinEnable(); E.items()[1]->spinEnable(); Pack( E ); CHECK_EQUAL( 1, BinCount( E ) ); } TEST( CreateRemainingSpaces ) { pack2::cPackEngine E; pack2::bin_t b = pack2::bin_t( new pack2::cBin( "Bin1", 100, 100 )); E.add( b ); pack2::item_t item = pack2::item_t( new pack2::cItem("i1",0,0)); item->sizX( 5 ); item->sizY( 10 ); CreateRemainingSpaces( E, b, item ); CHECK( pack2::cShape(5,0,95,100) == *(pack2::cShape*)Spaces(E,b)[0].get() ); CHECK( pack2::cShape(0,10,5,90) == *(pack2::cShape*)Spaces(E,b)[1].get() ); } TEST( StrightThru ) { pack2::cPackEngine E; E.Algorithm().fThruCuts = true; pack2::bin_t b = pack2::bin_t( new pack2::cBin( "Bin1", 100, 100 )); b->copyEnable(); E.add( b ); E.addItem( "Item50by40", 50, 40 ); Pack( E ); CHECK_EQUAL( 1, BinCount( E )); } TEST( pack1 ) { pack2::cPackEngine E; pack2::bin_t b = pack2::bin_t( new pack2::cBin( "Bin2", 100, 100 )); b->copyEnable(); E.add( b ); E.addItem( "Item50by40", 50, 40 ); E.addItem( "Item60by20", 60, 20 ); Pack( E ); CHECK_EQUAL( 1, BinCount( E )); E.clear(); b = pack2::bin_t( new pack2::cBin( "Bin3", 100, 100 )); E.add( b ); E.addItem( "Item90by80", 90, 80 ); E.addItem( "Item80by20", 80, 20 ); E.addItem( "Item5by100", 5, 100 ); Pack( E ); CHECK_EQUAL( 1, BinCount( E )); } TEST( subtract1 ) { pack2::cShape s1( "1",800,750); s1.locate( 1600,0 ); pack2::cShape s2( "2", 1100, 300 ); s2.locate( 1300, 700 ); CHECK( s1.isOverlap( s2 ) ); s1.subtract( s2 ); CHECK_EQUAL( 1600, s1.locX()); CHECK_EQUAL( 0, s1.locY()); CHECK_EQUAL( 800, s1.sizX() ); CHECK_EQUAL( 700, s1.sizY() ); } TEST( subtract2 ) { pack2::cShape s1( "1",1600,600); s1.locate( 0,1000 ); pack2::cShape s2( "2", 1100, 300 ); s2.locate( 1300, 700 ); CHECK( s1.isOverlap( s2 ) ); s1.subtract( s2 ); CHECK_EQUAL( 0, s1.locX()); CHECK_EQUAL( 1000, s1.locY()); CHECK_EQUAL( 1300, s1.sizX() ); CHECK_EQUAL( 600, s1.sizY() ); } TEST( subtract3 ) { pack2::cShape s1( "1",200,200); s1.locate( 1200,600 ); pack2::cShape s2( "2", 1100, 300 ); s2.locate( 1300, 700 ); CHECK( s1.isOverlap( s2 ) ); s1.subtract( s2 ); CHECK_EQUAL( 1200, s1.locX()); CHECK_EQUAL( 600, s1.locY()); CHECK_EQUAL( 100, s1.sizX() ); CHECK_EQUAL( 100, s1.sizY() ); } TEST( tid11 ) { pack2::cPackEngine thePackEngine; pack2::bin_t b = pack2::bin_t( new pack2::cBin( "Bin1", 2400,1200 )); b->copyEnable(); thePackEngine.add( b ); //thePackEngine.addItem( "621_1", 914,316 ); thePackEngine.addItem( "621_2", 1100,500 ); thePackEngine.addItem( "621_3", 1600,500 ); //thePackEngine.addItem( "621_4", 1600,250 ); thePackEngine.addItem( "621_5", 1200,250 ); Pack( thePackEngine ); } TEST( SortBinsIntoIncreasingSize ) { pack2::cPackEngine thePackEngine; pack2::bin_t b; b = pack2::bin_t( new pack2::cBin( "Bin1", 100, 100 )); thePackEngine.add( b ); pack2::bin_t b2 = pack2::bin_t( new pack2::cBin( b )); thePackEngine.add( b2 ); thePackEngine.add( pack2::bin_t( new pack2::cBin( b2, 50, 50, 3, 3 ))); thePackEngine.add( pack2::bin_t( new pack2::cBin( b, 50, 50, 10, 10 ))); thePackEngine.add( pack2::bin_t( new pack2::cBin( b, 60, 60, 5, 5 ))); SortBinsIntoIncreasingSize( thePackEngine ); // for( pack2::bin_t b : thePackEngine.bins() ) // std::cout << b->text(); CHECK_EQUAL( 5, thePackEngine.bins()[0]->sizX() ); CHECK_EQUAL( 10, thePackEngine.bins()[1]->sizX() ); CHECK_EQUAL( 3, thePackEngine.bins()[3]->sizX() ); } /* merge from BWPCENPLY16_GREY_21091HGL_cpy2 100 3174x5292 at 7484 6908 BWPCENPLY16_GREY_21091HGL_cpy2 99 7484x1824 at 0 10376 to BWPCENPLY16_GREY_21091HGL_cpy2 101 10658x1824 at 0 10376 BWPCENPLY16_GREY_21091HGL_cpy2 100 3174x3468 at 7484 6908 BWPCENPLY16_GREY_21091HGL_cpy2 99 7484x0 at 0 10376 */ TEST( MergePairs8 ) { pack2::cPackEngine thePackEngine; pack2::bin_t b; b = pack2::bin_t( new pack2::cBin( "Bin1", 24400,12200 )); thePackEngine.add( b ); thePackEngine.add( pack2::bin_t( new pack2::cBin( b, 7484, 6908, 3174, 5292 ))); thePackEngine.add( pack2::bin_t( new pack2::cBin( b, 0, 10376, 7484, 1824 ))); MergePairs( thePackEngine, b ); // for( pack2::bin_t b : thePackEngine.bins() ) // std::cout << b->text(); } TEST( MergePairs1 ) { pack2::cPackEngine thePackEngine; pack2::bin_t b; // equal spaces adjacent left/right even b = pack2::bin_t( new pack2::cBin( "Bin1", 100, 100 )); thePackEngine.add( b ); thePackEngine.add( pack2::bin_t( new pack2::cBin( b, 50, 50, 20, 20 ))); thePackEngine.add( pack2::bin_t( new pack2::cBin( b, 30, 50, 20, 20 ))); MergePairs( thePackEngine, b ); // for( pack2::bin_t b : thePackEngine.bins() ) // std::cout << b->text(); CHECK_EQUAL( 2, (int)thePackEngine.bins().size() ); CHECK_EQUAL(30, thePackEngine.bins()[1]->locX()); CHECK_EQUAL(50, thePackEngine.bins()[1]->locY()); CHECK_EQUAL(40, thePackEngine.bins()[1]->sizX()); CHECK_EQUAL(20, thePackEngine.bins()[1]->sizY()); } TEST( MergePairs2 ) { pack2::cPackEngine thePackEngine; pack2::bin_t b; // equal spaces adjacent left/right left higher b = pack2::bin_t( new pack2::cBin( "Bin1", 100, 100 )); thePackEngine.add( b ); thePackEngine.add( pack2::bin_t( new pack2::cBin( b, 50, 50, 20, 20 ))); thePackEngine.add( pack2::bin_t( new pack2::cBin( b, 30, 49, 20, 20 ))); MergePairs( thePackEngine, b ); // for( pack2::bin_t b : thePackEngine.bins() ) // std::cout << b->text(); CHECK_EQUAL( 4, (int)thePackEngine.bins().size() ); CHECK_EQUAL(50, thePackEngine.bins()[1]->locX()); CHECK_EQUAL(69, thePackEngine.bins()[1]->locY()); CHECK_EQUAL(20, thePackEngine.bins()[1]->sizX()); CHECK_EQUAL( 1, thePackEngine.bins()[1]->sizY()); CHECK_EQUAL(30, thePackEngine.bins()[2]->locX()); CHECK_EQUAL(49, thePackEngine.bins()[2]->locY()); CHECK_EQUAL(20, thePackEngine.bins()[2]->sizX()); CHECK_EQUAL( 1, thePackEngine.bins()[2]->sizY()); CHECK_EQUAL(30, thePackEngine.bins()[3]->locX()); CHECK_EQUAL(50, thePackEngine.bins()[3]->locY()); CHECK_EQUAL(40, thePackEngine.bins()[3]->sizX()); CHECK_EQUAL(19, thePackEngine.bins()[3]->sizY()); } TEST( MergePairs3 ) { pack2::cPackEngine thePackEngine; pack2::bin_t b; // equal spaces adjacent left/right left lower b = pack2::bin_t( new pack2::cBin( "Bin1", 100, 100 )); thePackEngine.add( b ); thePackEngine.add( pack2::bin_t( new pack2::cBin( b, 50, 50, 20, 20 ))); thePackEngine.add( pack2::bin_t( new pack2::cBin( b, 30, 51, 20, 20 ))); MergePairs( thePackEngine, b ); // for( pack2::bin_t b : thePackEngine.bins() ) // std::cout << b->text(); CHECK_EQUAL( 4, (int)thePackEngine.bins().size() ); CHECK_EQUAL(50, thePackEngine.bins()[1]->locX()); CHECK_EQUAL(50, thePackEngine.bins()[1]->locY()); CHECK_EQUAL(20, thePackEngine.bins()[1]->sizX()); CHECK_EQUAL( 1, thePackEngine.bins()[1]->sizY()); CHECK_EQUAL(30, thePackEngine.bins()[2]->locX()); CHECK_EQUAL(70, thePackEngine.bins()[2]->locY()); CHECK_EQUAL(20, thePackEngine.bins()[2]->sizX()); CHECK_EQUAL( 1, thePackEngine.bins()[2]->sizY()); CHECK_EQUAL(30, thePackEngine.bins()[3]->locX()); CHECK_EQUAL(51, thePackEngine.bins()[3]->locY()); CHECK_EQUAL(40, thePackEngine.bins()[3]->sizX()); CHECK_EQUAL(19, thePackEngine.bins()[3]->sizY()); } TEST( MergePairs4 ) { pack2::cPackEngine thePackEngine; pack2::bin_t b; // equal spaces adjacentup/down even b = pack2::bin_t( new pack2::cBin( "Bin1", 100, 100 )); thePackEngine.add( b ); thePackEngine.add( pack2::bin_t( new pack2::cBin( b, 50, 50, 20, 20 ))); thePackEngine.add( pack2::bin_t( new pack2::cBin( b, 50, 30, 20, 20 ))); MergePairs( thePackEngine, b ); // for( pack2::bin_t b : thePackEngine.bins() ) // std::cout << b->text(); CHECK_EQUAL( 2, (int)thePackEngine.bins().size() ); CHECK_EQUAL(50, thePackEngine.bins()[1]->locX()); CHECK_EQUAL(30, thePackEngine.bins()[1]->locY()); CHECK_EQUAL(20, thePackEngine.bins()[1]->sizX()); CHECK_EQUAL(40, thePackEngine.bins()[1]->sizY()); } TEST( MergePairs5 ) { pack2::cPackEngine thePackEngine; pack2::bin_t b; // equal spaces adjacent up/down top to left b = pack2::bin_t( new pack2::cBin( "Bin1", 100, 100 )); thePackEngine.add( b ); thePackEngine.add( pack2::bin_t( new pack2::cBin( b, 50, 50, 20, 20 ))); thePackEngine.add( pack2::bin_t( new pack2::cBin( b, 49, 30, 20, 20 ))); MergePairs( thePackEngine, b ); // for( pack2::bin_t b : thePackEngine.bins() ) // std::cout << b->text(); CHECK_EQUAL( 4, (int)thePackEngine.bins().size() ); CHECK_EQUAL(69, thePackEngine.bins()[1]->locX()); CHECK_EQUAL(50, thePackEngine.bins()[1]->locY()); CHECK_EQUAL(1, thePackEngine.bins()[1]->sizX()); CHECK_EQUAL(20, thePackEngine.bins()[1]->sizY()); CHECK_EQUAL(49, thePackEngine.bins()[2]->locX()); CHECK_EQUAL(30, thePackEngine.bins()[2]->locY()); CHECK_EQUAL(1, thePackEngine.bins()[2]->sizX()); CHECK_EQUAL( 20, thePackEngine.bins()[2]->sizY()); CHECK_EQUAL(50, thePackEngine.bins()[3]->locX()); CHECK_EQUAL(30, thePackEngine.bins()[3]->locY()); CHECK_EQUAL(19, thePackEngine.bins()[3]->sizX()); CHECK_EQUAL(40, thePackEngine.bins()[3]->sizY()); } TEST( MergePairs6 ) { pack2::cPackEngine thePackEngine; pack2::bin_t b; // equal spaces adjacent up/down top to right b = pack2::bin_t( new pack2::cBin( "Bin1", 100, 100 )); thePackEngine.add( b ); thePackEngine.add( pack2::bin_t( new pack2::cBin( b, 50, 50, 20, 20 ))); thePackEngine.add( pack2::bin_t( new pack2::cBin( b, 51, 30, 20, 20 ))); MergePairs( thePackEngine, b ); // for( pack2::bin_t b : thePackEngine.bins() ) // std::cout << b->text(); CHECK_EQUAL( 4, (int)thePackEngine.bins().size() ); CHECK_EQUAL(50, thePackEngine.bins()[1]->locX()); CHECK_EQUAL(50, thePackEngine.bins()[1]->locY()); CHECK_EQUAL(1, thePackEngine.bins()[1]->sizX()); CHECK_EQUAL(20, thePackEngine.bins()[1]->sizY()); CHECK_EQUAL(70, thePackEngine.bins()[2]->locX()); CHECK_EQUAL(30, thePackEngine.bins()[2]->locY()); CHECK_EQUAL(1, thePackEngine.bins()[2]->sizX()); CHECK_EQUAL( 20, thePackEngine.bins()[2]->sizY()); CHECK_EQUAL(51, thePackEngine.bins()[3]->locX()); CHECK_EQUAL(30, thePackEngine.bins()[3]->locY()); CHECK_EQUAL(19, thePackEngine.bins()[3]->sizX()); CHECK_EQUAL(40, thePackEngine.bins()[3]->sizY()); } TEST( MergePairs7 ) { pack2::cPackEngine thePackEngine; pack2::bin_t b; // equal spaces adjacent up/down top to right b = pack2::bin_t( new pack2::cBin( "Bin1", 100, 100 )); thePackEngine.add( b ); thePackEngine.add( pack2::bin_t( new pack2::cBin( b, 51, 30, 20, 20 ))); thePackEngine.add( pack2::bin_t( new pack2::cBin( b, 50, 50, 20, 20 ))); MergePairs( thePackEngine, b ); // for( pack2::bin_t b : thePackEngine.bins() ) // std::cout << b->text(); } int main() { pack2::cPackEngine thePackEngine; pack2::bin_t b; raven::set::UnitTest::RunAllTests(); thePackEngine.clear(); b = pack2::bin_t( new pack2::cBin( "Bin1", 100, 100 )); b->copyEnable(); thePackEngine.add( b ); thePackEngine.addItem( "Item1", 10, 10 ); thePackEngine.addItem( "Item2", 10, 10 ); thePackEngine.addItem( "Item3", 10, 10 ); thePackEngine.addItem( "Item4", 10, 10 ); Pack( thePackEngine ); if( BinCount( thePackEngine ) != 1 ) { std::cout << "Failed 1\n"; return 1; } //cout << CSV( thePackEngine ); thePackEngine.clear(); b = pack2::bin_t( new pack2::cBin( "Bin1", 100, 100 )); b->copyEnable(); thePackEngine.add( b ); thePackEngine.addItem( "Item1", 10, 10 ); thePackEngine.addItem( "Item2", 100, 100 ); Pack( thePackEngine ); if( BinCount( thePackEngine ) != 2 ) { std::cout << "Failed 2\n"; return 1; } //cout << CSV( thePackEngine ); int p = 0; for( pack2::bin_t b : thePackEngine.bins() ) { p++; switch( p ) { case 1: if( b->contents().size() != 1 ) { std::cout << "Failed 3\n"; return false; } if( b->contents()[0]->userID() != "Item2" ) { std::cout << "Failed 4\n"; return false; } break; case 2: if( b->contents().size() != 1 ) { std::cout << "Failed 5\n"; return false; } if( b->contents()[0]->userID() != "Item1" ) { std::cout << "Failed 4\n"; return false; } break; } } //cout << "Tests passed\n"; return 0; }
30.616183
84
0.581622
JamesBremner
485919b437fcc604bf1bcb5236837e824e733247
967
cpp
C++
src/source/SMARTEN.cpp
ManuelMcLure/TMCStepper
c425c40f0adfa24c1c21ce7d6428bcffc2c921ae
[ "MIT" ]
336
2018-03-26T13:51:46.000Z
2022-03-21T21:58:47.000Z
src/source/SMARTEN.cpp
ManuelMcLure/TMCStepper
c425c40f0adfa24c1c21ce7d6428bcffc2c921ae
[ "MIT" ]
218
2017-07-28T06:13:53.000Z
2022-03-26T16:41:21.000Z
src/source/SMARTEN.cpp
ManuelMcLure/TMCStepper
c425c40f0adfa24c1c21ce7d6428bcffc2c921ae
[ "MIT" ]
176
2018-09-11T22:16:27.000Z
2022-03-26T13:04:03.000Z
#include "TMCStepper.h" #include "TMC_MACROS.h" #define SET_REG(SETTING) SMARTEN_register.SETTING = B; write(SMARTEN_register.address, SMARTEN_register.sr) #define GET_REG(SETTING) return SMARTEN_register.SETTING uint32_t TMC2660Stepper::SMARTEN() { return SMARTEN_register.sr; } void TMC2660Stepper::SMARTEN(uint32_t data) { SMARTEN_register.sr = data; write(SMARTEN_register.address, SMARTEN_register.sr); } void TMC2660Stepper::seimin(bool B) { SET_REG(seimin); } void TMC2660Stepper::sedn(uint8_t B) { SET_REG(sedn); } void TMC2660Stepper::semax(uint8_t B) { SET_REG(semax); } void TMC2660Stepper::seup(uint8_t B) { SET_REG(seup); } void TMC2660Stepper::semin(uint8_t B) { SET_REG(semin); } bool TMC2660Stepper::seimin() { GET_REG(seimin); } uint8_t TMC2660Stepper::sedn() { GET_REG(sedn); } uint8_t TMC2660Stepper::semax() { GET_REG(semax); } uint8_t TMC2660Stepper::seup() { GET_REG(seup); } uint8_t TMC2660Stepper::semin() { GET_REG(semin); }
40.291667
107
0.752844
ManuelMcLure
4860c1ffbb99f39d02be1e4d1e1eaface023bf3a
22,455
cc
C++
tests/mps_statespace_test.cc
cognigami/qsim
e18c2f4dc3d1fd7edda696c78ed39708942b47e7
[ "Apache-2.0" ]
280
2020-03-04T18:30:16.000Z
2022-03-24T15:30:50.000Z
tests/mps_statespace_test.cc
cognigami/qsim
e18c2f4dc3d1fd7edda696c78ed39708942b47e7
[ "Apache-2.0" ]
274
2020-03-07T21:10:52.000Z
2022-03-30T19:45:48.000Z
tests/mps_statespace_test.cc
cognigami/qsim
e18c2f4dc3d1fd7edda696c78ed39708942b47e7
[ "Apache-2.0" ]
91
2020-03-06T18:58:55.000Z
2022-03-23T13:32:14.000Z
// Copyright 2019 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "../lib/mps_statespace.h" #include "../lib/formux.h" #include "gtest/gtest.h" namespace qsim { namespace mps { namespace { TEST(MPSStateSpaceTest, Create) { auto ss = MPSStateSpace<For, float>(1); auto mps = ss.Create(5, 8); EXPECT_EQ(mps.num_qubits(), 5); EXPECT_EQ(mps.bond_dim(), 8); } TEST(MPSStateSpaceTest, BlockOffset) { auto ss = MPSStateSpace<For, float>(1); auto mps = ss.Create(5, 8); for (unsigned i = 0; i < ss.Size(mps); ++i) { mps.get()[i] = i; } ASSERT_EQ(ss.GetBlockOffset(mps, 0), 0); ASSERT_EQ(ss.GetBlockOffset(mps, 1), 32); ASSERT_EQ(ss.GetBlockOffset(mps, 2), 256 + 32); ASSERT_EQ(ss.GetBlockOffset(mps, 3), 512 + 32); ASSERT_EQ(ss.GetBlockOffset(mps, 4), 768 + 32); } TEST(MPSStateSpaceTest, SetZero) { auto ss = MPSStateSpace<For, float>(1); auto mps = ss.Create(4, 8); for (unsigned i = 0; i < ss.Size(mps); ++i) { mps.get()[i] = i; } ss.SetStateZero(mps); for (unsigned i = 0; i < ss.Size(mps); ++i) { auto expected = 0.0; if (i == 0 || i == 32 || i == 256 + 32 || i == 512 + 32) { expected = 1; } EXPECT_NEAR(mps.get()[i], expected, 1e-5); } } TEST(MPSStateSpaceTest, Copy) { auto ss = MPSStateSpace<For, float>(1); auto mps = ss.Create(10, 8); auto mps2 = ss.Create(10, 8); auto mps3 = ss.Create(10, 4); for (unsigned i = 0; i < ss.Size(mps); ++i) { mps.get()[i] = i; } ASSERT_FALSE(ss.Copy(mps, mps3)); ss.Copy(mps, mps2); for (unsigned i = 0; i < ss.Size(mps); ++i) { EXPECT_NEAR(mps.get()[i], mps2.get()[i], 1e-5); } } TEST(MPSStateSpaceTest, ToWaveFunctionZero) { auto ss = MPSStateSpace<For, float>(1); auto mps = ss.Create(2, 8); ss.SetStateZero(mps); float *wf = new float[8]; ss.ToWaveFunction(mps, wf); EXPECT_NEAR(wf[0], 1, 1e-5); for (unsigned i = 1; i < 8; ++i) { EXPECT_NEAR(wf[i], 0, 1e-5); } delete[](wf); } TEST(MPSStateSpaceTest, ToWaveFunction3) { auto ss = MPSStateSpace<For, float>(1); auto mps = ss.Create(3, 4); // Set to highly entangled three qubit state. memset(mps.get(), 0, ss.RawSize(mps)); mps.get()[0] = -0.6622649924853867; mps.get()[1] = -0.3110490936135273; mps.get()[2] = 0.681488760344724; mps.get()[3] = -0.015052443773988289; mps.get()[8] = -0.537553225765131; mps.get()[9] = 0.4191539781192369; mps.get()[10] = -0.31650636199260096; mps.get()[11] = 0.659674338467379; mps.get()[16] = -0.21720151603221893; mps.get()[17] = 0.5354822278022766; mps.get()[18] = -0.24278810620307922; mps.get()[19] = 0.12074445933103561; mps.get()[24] = -0.10164494812488556; mps.get()[25] = -0.6021595597267151; mps.get()[26] = 0.49309641122817993; mps.get()[27] = 0.05576712265610695; mps.get()[32] = -0.3956003189086914; mps.get()[33] = -0.1778077632188797; mps.get()[34] = -0.1472112536430359; mps.get()[35] = 0.7757846117019653; mps.get()[40] = 0.3030144274234772; mps.get()[41] = -0.11498478055000305; mps.get()[42] = 0.06491414457559586; mps.get()[43] = -0.22911544144153595; mps.get()[80] = 0.5297775864601135; mps.get()[81] = 0.0; mps.get()[82] = -0.6799570918083191; mps.get()[83] = 0.41853320598602295; mps.get()[84] = -0.23835298418998718; mps.get()[85] = 0.0; mps.get()[86] = -0.13468137383460999; mps.get()[87] = 0.0829002782702446; // Check that the following transformation is carried out: // wf = einsum('ij,jkl,lm->ikm', *blocks) float *wf = new float[32]; ss.ToWaveFunction(mps, wf); EXPECT_NEAR(wf[0], -0.005946025252342224, 1e-4); EXPECT_NEAR(wf[1], -0.3386073410511017, 1e-4); EXPECT_NEAR(wf[2], 0.08402486890554428, 1e-4); EXPECT_NEAR(wf[3], 0.2276899814605713, 1e-4); EXPECT_NEAR(wf[4], 0.10889682918787003, 1e-4); EXPECT_NEAR(wf[5], 0.26689958572387695, 1e-4); EXPECT_NEAR(wf[6], -0.13812999427318573, 1e-4); EXPECT_NEAR(wf[7], -0.17624962329864502, 1e-4); EXPECT_NEAR(wf[8], 0.16325148940086365, 1e-4); EXPECT_NEAR(wf[9], -0.18776941299438477, 1e-4); EXPECT_NEAR(wf[10], 0.24669288098812103, 1e-4); EXPECT_NEAR(wf[11], 0.48989138007164, 1e-4); EXPECT_NEAR(wf[12], 0.18966005742549896, 1e-4); EXPECT_NEAR(wf[13], 0.204482764005661, 1e-4); EXPECT_NEAR(wf[14], -0.41462600231170654, 1e-4); EXPECT_NEAR(wf[15], -0.28409692645072937, 1e-4); delete[](wf); } TEST(MPSStateSpaceTest, ToWaveFunction5) { auto ss = MPSStateSpace<For, float>(1); auto mps = ss.Create(5, 4); // Set to highly entangled five qubit state. memset(mps.get(), 0, ss.RawSize(mps)); mps.get()[0] = -0.7942508170779394; mps.get()[1] = -0.08353012422743371; mps.get()[2] = -0.5956724071158231; mps.get()[3] = -0.0858062557546432; mps.get()[8] = 0.6008886732655473; mps.get()[9] = -0.03348407052200576; mps.get()[10] = -0.7985104374257858; mps.get()[11] = 0.013883241380578323; mps.get()[16] = -0.31778309393577153; mps.get()[17] = 0.08129081012436856; mps.get()[18] = -0.17084936092778547; mps.get()[19] = -0.02218120545861387; mps.get()[20] = -0.4708915300196999; mps.get()[21] = 0.5554105084817618; mps.get()[22] = 0.4771044130233731; mps.get()[23] = 0.3238455071330493; mps.get()[24] = -0.255477406163936; mps.get()[25] = 0.4374921994586982; mps.get()[26] = -0.5501925628308599; mps.get()[27] = 0.16130434535302918; mps.get()[28] = -0.22510697789781603; mps.get()[29] = 0.05157889931677101; mps.get()[30] = -0.5462643594366281; mps.get()[31] = -0.2507242261622358; mps.get()[32] = -0.257977790582352; mps.get()[33] = -0.11224285788942705; mps.get()[34] = -0.29538188714282193; mps.get()[35] = -0.38072576149146387; mps.get()[36] = 0.6001487220096956; mps.get()[37] = 0.1913733701851922; mps.get()[38] = -0.23636184929019038; mps.get()[39] = 0.4857749031783798; mps.get()[40] = 0.10130150715330866; mps.get()[41] = -0.7391377306145324; mps.get()[42] = -0.44876238752931974; mps.get()[43] = 0.4560672064449336; mps.get()[44] = 0.028438967271747218; mps.get()[45] = 0.13724346784210212; mps.get()[46] = 0.003584017578785237; mps.get()[47] = -0.11987932710918753; mps.get()[80] = 0.40840303886247986; mps.get()[81] = 0.0; mps.get()[82] = 0.07592798473660406; mps.get()[83] = 0.7192043122227202; mps.get()[84] = -0.1351739336607331; mps.get()[85] = 0.31415911338868924; mps.get()[86] = -0.2543437131216091; mps.get()[87] = 0.1901822451454096; mps.get()[88] = -0.49494962111198254; mps.get()[89] = 0.3938336604677486; mps.get()[90] = 0.12794790638132017; mps.get()[91] = 0.23588305655979178; mps.get()[92] = -0.08352038306191087; mps.get()[93] = 0.4006572203199725; mps.get()[94] = 0.36886860844013736; mps.get()[95] = -0.1586842041599526; mps.get()[96] = 0.1834561393756626; mps.get()[97] = 0.0; mps.get()[98] = 0.19628042396288672; mps.get()[99] = -0.40233821643752055; mps.get()[100] = -0.5974332727264484; mps.get()[101] = 0.19287040617030263; mps.get()[102] = 0.1053276514717207; mps.get()[103] = 0.016804190083581708; mps.get()[104] = -0.263327065774291; mps.get()[105] = 0.43922624365712193; mps.get()[106] = 0.10968978610217328; mps.get()[107] = -0.19665026336865873; mps.get()[108] = -0.06004766570619344; mps.get()[109] = -0.028059745847255218; mps.get()[110] = -0.24855708157570078; mps.get()[111] = 0.5751767140835897; mps.get()[112] = 0.25199694912392945; mps.get()[113] = 0.0; mps.get()[114] = -0.05739258827501658; mps.get()[115] = -0.30245742194728265; mps.get()[116] = 0.13607116127541907; mps.get()[117] = 0.17118330269631235; mps.get()[118] = -0.22592603732824876; mps.get()[119] = 0.27239431845297707; mps.get()[120] = 0.01047777976886481; mps.get()[121] = -0.21390579587098454; mps.get()[122] = 0.020345493365053653; mps.get()[123] = -0.15489716040222756; mps.get()[124] = -0.2920457586238394; mps.get()[125] = 0.32807225065061896; mps.get()[126] = -0.22441139544567443; mps.get()[127] = -0.15516902178850114; mps.get()[128] = 0.1303815766294433; mps.get()[129] = 0.0; mps.get()[130] = 0.09443469130980126; mps.get()[131] = 0.09749552478738743; mps.get()[132] = 0.07115934313302229; mps.get()[133] = 0.07172860752123576; mps.get()[134] = 0.35262084813015576; mps.get()[135] = 0.05559150244274026; mps.get()[136] = 0.05585983377252125; mps.get()[137] = -0.08787607283694769; mps.get()[138] = -0.02888091663074432; mps.get()[139] = 0.12419549395557358; mps.get()[140] = -0.24857309811183348; mps.get()[141] = -0.06536920925603362; mps.get()[142] = -0.026777844823335055; mps.get()[143] = 0.07798739264017497; mps.get()[144] = -0.4022885859012604; mps.get()[145] = 0.529089629650116; mps.get()[146] = 0.021047838032245636; mps.get()[147] = 0.11089000850915909; mps.get()[152] = -0.11812450736761093; mps.get()[153] = -0.3155742883682251; mps.get()[154] = -0.025639047846198082; mps.get()[155] = 0.5808156132698059; mps.get()[160] = 0.0904598981142044; mps.get()[161] = -0.03687569126486778; mps.get()[162] = 0.4893633723258972; mps.get()[163] = 0.2733270823955536; mps.get()[168] = 0.2756871283054352; mps.get()[169] = -0.2685239017009735; mps.get()[170] = 0.0703665167093277; mps.get()[171] = -0.11739754676818848; mps.get()[176] = -0.040402818471193314; mps.get()[177] = 0.024999519810080528; mps.get()[178] = 0.2142343968153; mps.get()[179] = 0.3487721085548401; mps.get()[184] = -0.38712623715400696; mps.get()[185] = 0.2719499170780182; mps.get()[186] = -0.28398218750953674; mps.get()[187] = -0.12957964837551117; mps.get()[192] = -0.16253285109996796; mps.get()[193] = 0.1666962057352066; mps.get()[194] = 0.029656991362571716; mps.get()[195] = -0.07687799632549286; mps.get()[200] = 0.05283937603235245; mps.get()[201] = 0.06291946768760681; mps.get()[202] = 0.01979890652000904; mps.get()[203] = -0.21019403636455536; mps.get()[208] = -0.7146716713905334; mps.get()[209] = 0.0; mps.get()[210] = 0.3957919478416443; mps.get()[211] = -0.1956116110086441; mps.get()[212] = -0.28512677550315857; mps.get()[213] = 0.0; mps.get()[214] = -0.41377660632133484; mps.get()[215] = 0.20450012385845184; // Check that the following transformation is carried out: // wf = einsum('ij,jkl,lmn,nop,pq->ikmoq', *blocks) float *wf = new float[128]; ss.ToWaveFunction(mps, wf); EXPECT_NEAR(wf[0], 0.0027854256331920624, 1e-4); EXPECT_NEAR(wf[1], -0.14140120148658752, 1e-4); EXPECT_NEAR(wf[2], 0.030212486162781715, 1e-4); EXPECT_NEAR(wf[3], 0.05706779286265373, 1e-4); EXPECT_NEAR(wf[4], -0.09160802513360977, 1e-4); EXPECT_NEAR(wf[5], -0.05029388517141342, 1e-4); EXPECT_NEAR(wf[6], -0.06708981841802597, 1e-4); EXPECT_NEAR(wf[7], -0.06412483751773834, 1e-4); EXPECT_NEAR(wf[8], -0.0774611234664917, 1e-4); EXPECT_NEAR(wf[9], 0.27072837948799133, 1e-4); EXPECT_NEAR(wf[10], -0.003501715138554573, 1e-4); EXPECT_NEAR(wf[11], -0.2887609601020813, 1e-4); EXPECT_NEAR(wf[12], 0.016577117145061493, 1e-4); EXPECT_NEAR(wf[13], 0.1369006335735321, 1e-4); EXPECT_NEAR(wf[14], 0.08254759013652802, 1e-4); EXPECT_NEAR(wf[15], 0.20499306917190552, 1e-4); EXPECT_NEAR(wf[16], 0.17876368761062622, 1e-4); EXPECT_NEAR(wf[17], -0.02268427424132824, 1e-4); EXPECT_NEAR(wf[18], 0.05583261698484421, 1e-4); EXPECT_NEAR(wf[19], 0.10677587240934372, 1e-4); EXPECT_NEAR(wf[20], 0.018177300691604614, 1e-4); EXPECT_NEAR(wf[21], 0.26146093010902405, 1e-4); EXPECT_NEAR(wf[22], -0.19240343570709229, 1e-4); EXPECT_NEAR(wf[23], -0.12706275284290314, 1e-4); EXPECT_NEAR(wf[24], 0.1699770838022232, 1e-4); EXPECT_NEAR(wf[25], 0.26863881945610046, 1e-4); EXPECT_NEAR(wf[26], -0.10701578855514526, 1e-4); EXPECT_NEAR(wf[27], -0.03779822587966919, 1e-4); EXPECT_NEAR(wf[28], -0.06767062097787857, 1e-4); EXPECT_NEAR(wf[29], 0.05558207631111145, 1e-4); EXPECT_NEAR(wf[30], 0.06148408725857735, 1e-4); EXPECT_NEAR(wf[31], -0.03445826843380928, 1e-4); EXPECT_NEAR(wf[32], -0.018822386860847473, 1e-4); EXPECT_NEAR(wf[33], -0.007597930729389191, 1e-4); EXPECT_NEAR(wf[34], -0.0027186088263988495, 1e-4); EXPECT_NEAR(wf[35], 0.003467019647359848, 1e-4); EXPECT_NEAR(wf[36], -0.26657143235206604, 1e-4); EXPECT_NEAR(wf[37], -0.029667221009731293, 1e-4); EXPECT_NEAR(wf[38], 0.1857101023197174, 1e-4); EXPECT_NEAR(wf[39], -0.055891260504722595, 1e-4); EXPECT_NEAR(wf[40], -0.060019031167030334, 1e-4); EXPECT_NEAR(wf[41], 0.06737485527992249, 1e-4); EXPECT_NEAR(wf[42], -0.038918495178222656, 1e-4); EXPECT_NEAR(wf[43], -0.045035410672426224, 1e-4); EXPECT_NEAR(wf[44], -0.1498071402311325, 1e-4); EXPECT_NEAR(wf[45], -0.15015973150730133, 1e-4); EXPECT_NEAR(wf[46], 0.11186741292476654, 1e-4); EXPECT_NEAR(wf[47], 0.057124655693769455, 1e-4); EXPECT_NEAR(wf[48], 0.16711947321891785, 1e-4); EXPECT_NEAR(wf[49], 0.2237841784954071, 1e-4); EXPECT_NEAR(wf[50], 0.20187999308109283, 1e-4); EXPECT_NEAR(wf[51], 0.02212279662489891, 1e-4); EXPECT_NEAR(wf[52], 0.07793829590082169, 1e-4); EXPECT_NEAR(wf[53], -0.11144962906837463, 1e-4); EXPECT_NEAR(wf[54], 0.11177311837673187, 1e-4); EXPECT_NEAR(wf[55], -0.02343379706144333, 1e-4); EXPECT_NEAR(wf[56], -0.08419902622699738, 1e-4); EXPECT_NEAR(wf[57], 0.029235713183879852, 1e-4); EXPECT_NEAR(wf[58], 0.12327411770820618, 1e-4); EXPECT_NEAR(wf[59], 0.059630997478961945, 1e-4); EXPECT_NEAR(wf[60], -0.04118343070149422, 1e-4); EXPECT_NEAR(wf[61], -0.14594365656375885, 1e-4); EXPECT_NEAR(wf[62], -0.11883178353309631, 1e-4); EXPECT_NEAR(wf[63], 0.1824525147676468, 1e-4); delete[](wf); } TEST(MPSStateSpaceTest, InnerProduct4) { auto ss = MPSStateSpace<For, float>(1); auto mps = ss.Create(4, 4); auto mps2 = ss.Create(4, 4); // Set to highly entangled four qubit state. memset(mps.get(), 0, ss.RawSize(mps)); memset(mps2.get(), 0, ss.RawSize(mps2)); mps.get()[0] = -0.916497861382668; mps.get()[1] = -0.0774770100056814; mps.get()[2] = -0.3905530508872181; mps.get()[3] = -0.038695257453215746; mps.get()[8] = 0.39242052841785685; mps.get()[9] = 0.005926209849421993; mps.get()[10] = -0.9193660433571464; mps.get()[11] = -0.027148413259157553; mps.get()[16] = -0.086494587815096; mps.get()[17] = -0.5161113650581821; mps.get()[18] = -0.3716843459879704; mps.get()[19] = -0.4149275842783076; mps.get()[20] = 0.3475684513942029; mps.get()[21] = -0.33731825676083277; mps.get()[22] = 0.03531924421420863; mps.get()[23] = 0.4242625462238508; mps.get()[24] = 0.1548611214464985; mps.get()[25] = -0.1629745551510658; mps.get()[26] = -0.3054123508603024; mps.get()[27] = 0.40742455983835185; mps.get()[28] = 0.051375370785247995; mps.get()[29] = 0.6739332289909812; mps.get()[30] = 0.1957074863128766; mps.get()[31] = 0.4416548486767887; mps.get()[32] = -0.4188134561454451; mps.get()[33] = -0.314779963690704; mps.get()[34] = 0.594871513074914; mps.get()[35] = 0.1253634938807484; mps.get()[36] = -0.3274468059583836; mps.get()[37] = -0.0033649355295961303; mps.get()[38] = -0.19836336090039158; mps.get()[39] = 0.4575368665727339; mps.get()[40] = -0.4319730509600821; mps.get()[41] = 0.46315571812161255; mps.get()[42] = -0.177092245869463; mps.get()[43] = 0.17165251096868606; mps.get()[44] = 0.4478329658040191; mps.get()[45] = 0.028284989048036946; mps.get()[46] = -0.5484962316855873; mps.get()[47] = 0.1893602226102037; mps.get()[80] = 0.5355256929496379; mps.get()[81] = 0.0; mps.get()[82] = -0.82749362448062; mps.get()[83] = 0.02904044194569624; mps.get()[84] = 0.0; mps.get()[85] = 3.1712172333499e-18; mps.get()[88] = 0.08673107202101067; mps.get()[89] = -0.26957426786565664; mps.get()[90] = 0.10136853320009953; mps.get()[91] = -0.16847174758615416; mps.get()[96] = 0.7256882794862672; mps.get()[97] = 0.0; mps.get()[98] = 0.49992356328580695; mps.get()[99] = -0.07465158451531788; mps.get()[100] = 0.0; mps.get()[101] = -2.73164461529292e-18; mps.get()[104] = -0.11096745459559126; mps.get()[105] = -0.11248021223295962; mps.get()[106] = -0.015939524128979008; mps.get()[107] = -0.04834685546748854; mps.get()[112] = -0.09137803308510727; mps.get()[113] = 0.0; mps.get()[114] = 0.041828533843678406; mps.get()[115] = -0.055516336152773675; mps.get()[116] = -1.7346894763697954e-17; mps.get()[117] = -7.589266459117856e-18; mps.get()[120] = -0.06982795298266756; mps.get()[121] = -0.2607434376975409; mps.get()[122] = 0.04055209540168665; mps.get()[123] = -0.0998159882317749; mps.get()[128] = -0.0013533723870614552; mps.get()[129] = 0.0; mps.get()[130] = 0.0030153696871580518; mps.get()[131] = -0.0007536486755610136; mps.get()[132] = 1.3706310124710953e-17; mps.get()[133] = 5.271657740273443e-18; mps.get()[136] = 0.009007639720827557; mps.get()[137] = 0.01160295765732885; mps.get()[138] = -0.002650020644033365; mps.get()[139] = -0.0347660454843333; mps.get()[144] = 0.7934826958343173; mps.get()[145] = 0.2097612636620367; mps.get()[146] = 0.40098701589649566; mps.get()[147] = 0.06292071832569604; mps.get()[148] = 0.17644861904250161; mps.get()[149] = 0.02508862414716359; mps.get()[150] = -0.36011160812021614; mps.get()[151] = -0.013850284789667294; // Set to slightly different four qubit state. mps2.get()[0] = -0.916497861382668; mps2.get()[1] = -0.0774770100056814; mps2.get()[2] = -0.3905530508872181; mps2.get()[3] = -0.038695257453215746; mps2.get()[8] = 0.39242052841785685; mps2.get()[9] = 0.005926209849421993; mps2.get()[10] = -0.9193660433571464; mps2.get()[11] = -0.027148413259157553; mps2.get()[16] = -0.38520893663443145; mps2.get()[17] = -0.08313325347846491; mps2.get()[18] = 0.37387886041396534; mps2.get()[19] = 0.7642074712965752; mps2.get()[20] = -0.27881372303099244; mps2.get()[21] = 0.1474857317523121; mps2.get()[22] = -0.1410007330015855; mps2.get()[23] = -0.039168047247753496; mps2.get()[24] = -0.0590745502568466; mps2.get()[25] = 0.11761847202902623; mps2.get()[26] = 0.11269537822823146; mps2.get()[27] = -0.3086460273383095; mps2.get()[28] = -0.6327237072338668; mps2.get()[29] = -0.28314375337094555; mps2.get()[30] = -0.15819977431031695; mps2.get()[31] = -0.6075990707063283; mps2.get()[32] = 0.8082960956126871; mps2.get()[33] = 0.4057876159937702; mps2.get()[34] = 0.12408608368116913; mps2.get()[35] = 0.3850457786727492; mps2.get()[36] = -0.029431664112584088; mps2.get()[37] = -0.08738621657419658; mps2.get()[38] = -0.039495020284007906; mps2.get()[39] = -0.0909603999525164; mps2.get()[40] = 0.0164446476145238; mps2.get()[41] = 0.095406687086266; mps2.get()[42] = 0.015460689255213836; mps2.get()[43] = -0.06589597358749627; mps2.get()[44] = -0.5539889126392532; mps2.get()[45] = -0.32341135258910775; mps2.get()[46] = 0.1325213431271281; mps2.get()[47] = 0.7463144784082719; mps2.get()[80] = 0.3879496172458074; mps2.get()[81] = 0.0; mps2.get()[82] = 0.7012769606101399; mps2.get()[83] = -0.12695868636166885; mps2.get()[84] = 1.1103700291614824e-16; mps2.get()[85] = 4.629873324419367e-18; mps2.get()[88] = 0.36012400471668854; mps2.get()[89] = 0.11784653120900945; mps2.get()[90] = -0.5483875743376463; mps2.get()[91] = -0.1637597971215351; mps2.get()[92] = 4.775145770909058e-18; mps2.get()[93] = 1.79364974950039e-17; mps2.get()[96] = -0.640372512495744; mps2.get()[97] = 0.0; mps2.get()[98] = 0.2548579767415688; mps2.get()[99] = -0.034454109442162505; mps2.get()[100] = 9.488019311652e-17; mps2.get()[101] = 1.0530014819474617e-17; mps2.get()[104] = 0.44752468366493875; mps2.get()[105] = -0.12895732984521566; mps2.get()[106] = 0.1804908199125375; mps2.get()[107] = -0.11201596042542786; mps2.get()[108] = -1.4515782829099415e-19; mps2.get()[109] = 4.5471437738577115e-18; mps2.get()[112] = -0.16454563839144662; mps2.get()[113] = 0.0; mps2.get()[114] = -0.024056710061469547; mps2.get()[115] = -0.1203420866582053; mps2.get()[116] = -3.1207550335607834e-17; mps2.get()[117] = -1.1028836460006021e-17; mps2.get()[120] = -0.13538852421270092; mps2.get()[121] = 0.17274307394393765; mps2.get()[122] = -0.15244639495683454; mps2.get()[123] = -0.06245206468145512; mps2.get()[124] = -1.5247965666831198e-18; mps2.get()[125] = 1.4070202389092805e-18; mps2.get()[128] = 0.03453277422180958; mps2.get()[129] = 0.0; mps2.get()[130] = -0.02287709221765174; mps2.get()[131] = -0.06623554376900025; mps2.get()[132] = -2.100635435828622e-17; mps2.get()[133] = 8.534146150309484e-19; mps2.get()[136] = 0.03199717502952966; mps2.get()[137] = 0.03835220263481228; mps2.get()[138] = 0.05616254494558428; mps2.get()[139] = -0.05491726676672418; mps2.get()[140] = -1.6687930640538633e-18; mps2.get()[141] = -1.0473130086052244e-19; mps2.get()[144] = 0.7934826958343173; mps2.get()[145] = 0.2097612636620367; mps2.get()[146] = 0.40098701589649566; mps2.get()[147] = 0.06292071832569604; mps2.get()[148] = 0.17644861904250161; mps2.get()[149] = 0.02508862414716359; mps2.get()[150] = -0.36011160812021614; mps2.get()[151] = -0.013850284789667294; // Computes the following contraction: // +---+ +---+ +---+ +---+ // mps2 | 0 +-+ 1 +-+ 2 +-+ 3 | // +-+-+ +-+-+ +-+-+ +-+-+ // | | | | // | | | | // +-+-+ +-+-+ +-+-+ +-+-+ // mps | 0 +-+ 1 +-+ 2 +-+ 3 | // +---+ +---+ +---+ +---+ // // 0.5524505270081406+0.2471560922399374j auto r = ss.InnerProduct(mps, mps2); EXPECT_NEAR(r.real(), 0.5524, 1e-4); EXPECT_NEAR(r.imag(), 0.2471, 1e-4); auto f = ss.RealInnerProduct(mps, mps2); EXPECT_NEAR(f, 0.5524, 1e-4); } } // namespace } // namespace mps } // namespace qsim int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
37.613065
75
0.655578
cognigami
486245bb7432d5c5d0c5faac89fc61d2babfb35a
20,065
cpp
C++
src/histogram.cpp
tylern4/clas12_elastic
b2630541b1b255a3138a191e61d9a705e25fcef9
[ "MIT" ]
null
null
null
src/histogram.cpp
tylern4/clas12_elastic
b2630541b1b255a3138a191e61d9a705e25fcef9
[ "MIT" ]
null
null
null
src/histogram.cpp
tylern4/clas12_elastic
b2630541b1b255a3138a191e61d9a705e25fcef9
[ "MIT" ]
1
2019-12-17T16:35:30.000Z
2019-12-17T16:35:30.000Z
/**************************************/ /* */ /* Created by Nick Tyler */ /* University Of South Carolina */ /**************************************/ #include "histogram.hpp" Histogram::Histogram(const std::string& output_file) { RootOutputFile = std::make_shared<TFile>(output_file.c_str(), "RECREATE"); def = std::make_shared<TCanvas>("def"); makeHists(); Nsparce = std::make_shared<THnSparseD>("nsparce", "nsparce", 3, sparce_bins, sparce_xmin, sparce_xmax); makeHists_electron_cuts(); } Histogram::~Histogram() { this->Write(); } void Histogram::Write() { std::cout << GREEN << "Writting" << DEF << std::endl; Write_SF(); Nsparce->Write(); std::cout << BOLDBLUE << "WvsQ2()" << DEF << std::endl; Write_WvsQ2(); std::cout << BOLDBLUE << "Write_MomVsBeta()" << DEF << std::endl; TDirectory* Write_MomVsBeta_folder = RootOutputFile->mkdir("Mom Vs Beta"); Write_MomVsBeta_folder->cd(); Write_MomVsBeta(); deltaT_proton[before_cut]->Write(); deltaT_proton[after_cut]->Write(); std::cerr << BOLDBLUE << "Write_Electron_cuts()" << DEF << std::endl; TDirectory* Electron_Cuts = RootOutputFile->mkdir("Electron_Cuts"); Electron_Cuts->cd(); Write_Electron_cuts(); std::cout << BOLDBLUE << "Done Writing!!!" << DEF << std::endl; } void Histogram::makeHists() { deltaT_proton[before_cut] = std::make_shared<TH2D>("DeltaTProton", "DeltaTProton", bins, zero, 10, bins, -5, 5); deltaT_proton[after_cut] = std::make_shared<TH2D>("DeltaTProton_cut", "DeltaTProton_cut", bins, zero, 10, bins, -5, 5); for (short sec = 0; sec < NUM_SECTORS; sec++) { MissingMass[sec] = std::make_shared<TH1D>(Form("MM2_hist_sec_%d", sec), Form("MM2_hist_sec_%d", sec), bins, -w_max, w_max); mass_pi0_hist[before_cut][sec] = std::make_shared<TH1D>(Form("mass_pi0_hist_%d", sec), Form("mass_pi0_hist_%d", sec), bins, 0, 1.0); mass_pi0_hist[after_cut][sec] = std::make_shared<TH1D>(Form("mass_pi0_hist_aferPcuts_%d", sec), Form("mass_pi0_hist_aferPcuts_%d", sec), bins, 0, 1.0); mass_eta_hist[before_cut][sec] = std::make_shared<TH1D>(Form("mass_eta_hist_%d", sec), Form("mass_eta_hist_%d", sec), (bins / 2), 0.0, 1.0); mass_eta_hist[after_cut][sec] = std::make_shared<TH1D>(Form("mass_eta_hist_aferPcuts_%d", sec), Form("mass_eta_hist_aferPcuts_%d", sec), bins / 2, 0.0, 1.0); W_hist_all_events[sec] = std::make_shared<TH1D>(Form("W_hist_sec_%d", sec), Form("W_hist_sec_%d", sec), bins, zero, w_max); W_hist_1pos[sec] = std::make_shared<TH1D>(Form("W_hist_1pos_%d", sec), Form("W_hist_1pos_%d", sec), bins, zero, w_max); W_hist_1pos_0charge[sec] = std::make_shared<TH1D>(Form("W_hist_1pos_MM0_%d", sec), Form("W_hist_1pos_MM0_%d", sec), bins, zero, w_max); W_hist_1pos_noOther[sec] = std::make_shared<TH1D>(Form("W_hist_1pos_noOther_%d", sec), Form("W_hist_1pos_noOther_%d", sec), bins, zero, w_max); W_vs_q2_all_events[sec] = std::make_shared<TH2D>(Form("WQ2_sec_%d", sec), Form("WQ2_sec_%d", sec), bins, zero, w_max, bins, zero, q2_max); W_vs_q2_1pos[sec] = std::make_shared<TH2D>(Form("WQ2_1pos_%d", sec), Form("WQ2_1pos_%d", sec), bins, zero, w_max, bins, zero, q2_max); W_vs_q2_1pos_0charge[sec] = std::make_shared<TH2D>(Form("WQ2_1pos_MM0_%d", sec), Form("WQ2_1pos_MM0_%d", sec), bins, zero, w_max, bins, zero, q2_max); W_vs_q2_1pos_noOther[sec] = std::make_shared<TH2D>( Form("WQ2_1pos_noOther_%d", sec), Form("WQ2_1pos_noOther_%d", sec), bins, zero, w_max, bins, zero, q2_max); for (auto&& det : detector_name) { int d = detector_fill[det.first]; ThetaVsP[d][sec] = std::make_shared<TH2D>(Form("MomVsTheta_pos_%s_%d", det.second.c_str(), sec), Form("MomVsTheta_pos_%s_%d", det.second.c_str(), sec), 500, zero, 6.0, 500, 0, 90); ThetaVsP_lowW[d][sec] = std::make_shared<TH2D>(Form("MomVsTheta_lowW_%s_%d", det.second.c_str(), sec), Form("MomVsTheta_lowW_%s_%d", det.second.c_str(), sec), 500, zero, 6.0, 500, 0, 90); ThetaVsPCalc[d][sec] = std::make_shared<TH2D>(Form("MomVsTheta_Calc_%s_%d", det.second.c_str(), sec), Form("MomVsTheta_Calc_%s_%d", det.second.c_str(), sec), 500, zero, 6.0, 500, 0, 90); MomVsBeta[d][sec] = std::make_shared<TH2D>(Form("MomVsBeta_%s_%d", det.second.c_str(), sec), Form("MomVsBeta_%s_%d", det.second.c_str(), sec), 500, zero, p_max, 500, zero, 1.2); Phie_vs_Phip[d][sec] = std::make_shared<TH2D>(Form("Phie_vs_Phip_%s_%d", det.second.c_str(), sec), Form("Phie_vs_Phip_%s_%d", det.second.c_str(), sec), 500, -PI, PI, 500, -PI, PI); Phie_Phip_hist[d][sec] = std::make_shared<TH1D>(Form("Phie_minus_Phip_%s_%d", det.second.c_str(), sec), Form("Phie_minus_Phip_%s_%d", det.second.c_str(), sec), 500, zero, 2 * PI); W_hist_1pos_at180[d][sec] = std::make_shared<TH1D>(Form("W_1pos_at180_%s_%d", det.second.c_str(), sec), Form("W_1pos_at180_%s_%d", det.second.c_str(), sec), bins, zero, w_max); W_vs_q2_1pos_at180[d][sec] = std::make_shared<TH2D>(Form("WQ2_1pos_at180_%s_%d", det.second.c_str(), sec), Form("WQ2_1pos_at180_%s_%d", det.second.c_str(), sec), bins, zero, w_max, bins, zero, q2_max); W_hist_1pos_at180_MM[d][sec] = std::make_shared<TH1D>(Form("W_1pos_at180_MM_%s_%d", det.second.c_str(), sec), Form("W_1pos_at180_MM_%s_%d", det.second.c_str(), sec), bins, zero, w_max); W_vs_q2_1pos_at180_MM[d][sec] = std::make_shared<TH2D>(Form("WQ2_1pos_at180_MM_%s_%d", det.second.c_str(), sec), Form("WQ2_1pos_at180_MM_%s_%d", det.second.c_str(), sec), bins, zero, w_max, bins, zero, q2_max); } } } void Histogram::makeHists_electron_cuts() { for (auto&& cut : before_after_cut) { int c = cut.first; auto type = cut.second.c_str(); EC_sampling_fraction[c] = std::make_shared<TH2D>(Form("EC_sampling_fraction%s", type), Form("EC_sampling_fraction%s", type), bins, p_min, p_max, bins, zero, 1.0); vz_position[c] = std::make_shared<TH1D>(Form("vz_position%s", type), Form("vz_position%s", type), bins, -40, 40); pcal_sec[c] = std::make_shared<TH2D>(Form("pcal_sec%s", type), Form("pcal_sec%s", type), bins, -420, 420, bins, -420, 420); dcr1_sec[c] = std::make_shared<TH2D>(Form("dcr1_sec%s", type), Form("dcr1_sec%s", type), bins, -180, 180, bins, -180, 180); dcr2_sec[c] = std::make_shared<TH2D>(Form("dcr2_sec%s", type), Form("dcr2_sec%s", type), bins, -270, 270, bins, -270, 270); dcr3_sec[c] = std::make_shared<TH2D>(Form("dcr3_sec%s", type), Form("dcr3_sec%s", type), bins, -320, 320, bins, -320, 320); } } void Histogram::Fill_SF(const std::shared_ptr<Branches12>& _d) { sf_hist->Fill(_d->p(0), _d->ec_tot_energy(0) / _d->p(0)); } void Histogram::FillHists_electron_cuts(const std::shared_ptr<Branches12>& _d) { vz_position[before_cut]->Fill(_d->vz(0)); pcal_sec[before_cut]->Fill(_d->ec_pcal_x(0), _d->ec_pcal_y(0)); dcr1_sec[before_cut]->Fill(_d->dc_r1_x(0), _d->dc_r1_y(0)); dcr2_sec[before_cut]->Fill(_d->dc_r2_x(0), _d->dc_r2_y(0)); dcr3_sec[before_cut]->Fill(_d->dc_r3_x(0), _d->dc_r3_y(0)); EC_sampling_fraction[before_cut]->Fill(_d->p(0), _d->ec_tot_energy(0) / _d->p(0)); } void Histogram::FillHists_electron_with_cuts(const std::shared_ptr<Branches12>& _d) { vz_position[after_cut]->Fill(_d->vz(0)); pcal_sec[after_cut]->Fill(_d->ec_pcal_x(0), _d->ec_pcal_y(0)); dcr1_sec[after_cut]->Fill(_d->dc_r1_x(0), _d->dc_r1_y(0)); dcr2_sec[after_cut]->Fill(_d->dc_r2_x(0), _d->dc_r2_y(0)); dcr3_sec[after_cut]->Fill(_d->dc_r3_x(0), _d->dc_r3_y(0)); EC_sampling_fraction[after_cut]->Fill(_d->p(0), _d->ec_tot_energy(0) / _d->p(0)); } void Histogram::Write_SF() { sf_hist->Write(); } void Histogram::Write_Electron_cuts() { for (auto&& cut : before_after_cut) { int c = cut.first; vz_position[c]->SetXTitle("vz (GeV)"); if (vz_position[c]->GetEntries()) vz_position[c]->Write(); pcal_sec[c]->SetXTitle("x (cm)"); pcal_sec[c]->SetYTitle("y (cm)"); pcal_sec[c]->SetOption("COLZ1"); if (pcal_sec[c]->GetEntries()) pcal_sec[c]->Write(); dcr1_sec[c]->SetXTitle("x (cm)"); dcr1_sec[c]->SetYTitle("y (cm)"); dcr1_sec[c]->SetOption("COLZ1"); if (dcr1_sec[c]->GetEntries()) dcr1_sec[c]->Write(); dcr2_sec[c]->SetXTitle("x (cm)"); dcr2_sec[c]->SetYTitle("y (cm)"); dcr2_sec[c]->SetOption("COLZ1"); if (dcr2_sec[c]->GetEntries()) dcr2_sec[c]->Write(); dcr3_sec[c]->SetXTitle("x (cm)"); dcr3_sec[c]->SetYTitle("y (cm)"); dcr3_sec[c]->SetOption("COLZ1"); if (dcr3_sec[c]->GetEntries()) dcr3_sec[c]->Write(); EC_sampling_fraction[c]->SetXTitle("Momentum (GeV)"); EC_sampling_fraction[c]->SetYTitle("Sampling Fraction"); EC_sampling_fraction[c]->SetOption("COLZ1"); EC_sampling_fraction[c]->Write(); } } void Histogram::Fill_Sparce(const std::shared_ptr<Reaction>& _e) { std::lock_guard<std::mutex> lk(mutex); double ret[NUM_DIM] = {_e->W(), _e->Q2(), static_cast<double>(_e->sec())}; Nsparce->Fill(ret); } void Histogram::Fill_WvsQ2(const std::shared_ptr<Reaction>& _e) { short sec = _e->sec(); short pos_det = _e->pos_det(); if ((sec > 0 && sec < NUM_SECTORS) || pos_det != -1) { W_hist_all_events[all_sectors]->Fill(_e->W()); W_vs_q2_all_events[all_sectors]->Fill(_e->W(), _e->Q2()); W_hist_all_events[sec]->Fill(_e->W()); W_vs_q2_all_events[sec]->Fill(_e->W(), _e->Q2()); if (_e->onePositive()) { W_hist_1pos[all_sectors]->Fill(_e->W()); W_vs_q2_1pos[all_sectors]->Fill(_e->W(), _e->Q2()); W_hist_1pos[sec]->Fill(_e->W()); W_vs_q2_1pos[sec]->Fill(_e->W(), _e->Q2()); Phie_vs_Phip[both_detectors][all_sectors]->Fill(_e->phi_e(), _e->phi_p()); Phie_Phip_hist[both_detectors][all_sectors]->Fill(_e->phi_diff()); Phie_vs_Phip[both_detectors][sec]->Fill(_e->phi_e(), _e->phi_p()); Phie_Phip_hist[both_detectors][sec]->Fill(_e->phi_diff()); Phie_vs_Phip[pos_det][all_sectors]->Fill(_e->phi_e(), _e->phi_p()); Phie_Phip_hist[pos_det][all_sectors]->Fill(_e->phi_diff()); Phie_vs_Phip[pos_det][sec]->Fill(_e->phi_e(), _e->phi_p()); Phie_Phip_hist[pos_det][sec]->Fill(_e->phi_diff()); } if (_e->onePositive_MM0()) { W_hist_1pos_0charge[all_sectors]->Fill(_e->W()); W_vs_q2_1pos_0charge[all_sectors]->Fill(_e->W(), _e->Q2()); W_hist_1pos_0charge[sec]->Fill(_e->W()); W_vs_q2_1pos_0charge[sec]->Fill(_e->W(), _e->Q2()); } if (_e->onePositive_noOther()) { W_hist_1pos_noOther[all_sectors]->Fill(_e->W()); W_vs_q2_1pos_noOther[all_sectors]->Fill(_e->W(), _e->Q2()); W_hist_1pos_noOther[sec]->Fill(_e->W()); W_vs_q2_1pos_noOther[sec]->Fill(_e->W(), _e->Q2()); } if (_e->onePositive_at180()) { MissingMass[all_sectors]->Fill(_e->MM2()); MissingMass[sec]->Fill(_e->MM2()); W_hist_1pos_at180[both_detectors][all_sectors]->Fill(_e->W()); W_vs_q2_1pos_at180[both_detectors][all_sectors]->Fill(_e->W(), _e->Q2()); W_hist_1pos_at180[both_detectors][sec]->Fill(_e->W()); W_vs_q2_1pos_at180[both_detectors][sec]->Fill(_e->W(), _e->Q2()); W_hist_1pos_at180[pos_det][all_sectors]->Fill(_e->W()); W_vs_q2_1pos_at180[pos_det][all_sectors]->Fill(_e->W(), _e->Q2()); W_hist_1pos_at180[pos_det][sec]->Fill(_e->W()); W_vs_q2_1pos_at180[pos_det][sec]->Fill(_e->W(), _e->Q2()); } if (_e->onePositive_at180_MM0()) { W_hist_1pos_at180_MM[both_detectors][all_sectors]->Fill(_e->W()); W_vs_q2_1pos_at180_MM[both_detectors][all_sectors]->Fill(_e->W(), _e->Q2()); W_hist_1pos_at180_MM[both_detectors][sec]->Fill(_e->W()); W_vs_q2_1pos_at180_MM[both_detectors][sec]->Fill(_e->W(), _e->Q2()); W_hist_1pos_at180_MM[pos_det][all_sectors]->Fill(_e->W()); W_vs_q2_1pos_at180_MM[pos_det][all_sectors]->Fill(_e->W(), _e->Q2()); W_hist_1pos_at180_MM[pos_det][sec]->Fill(_e->W()); W_vs_q2_1pos_at180_MM[pos_det][sec]->Fill(_e->W(), _e->Q2()); } } } void Histogram::Write_WvsQ2() { TDirectory* phi_folder = RootOutputFile->mkdir("Phi"); phi_folder->cd(); for (short j = 0; j < detector_name.size(); j++) { for (int i = 0; i < NUM_SECTORS; i++) { Phie_vs_Phip[j][i]->SetXTitle("Phie"); Phie_vs_Phip[j][i]->SetYTitle("Phip"); Phie_vs_Phip[j][i]->SetOption("COLZ"); Phie_vs_Phip[j][i]->Write(); } for (int i = 0; i < NUM_SECTORS; i++) { Phie_Phip_hist[j][i]->SetXTitle("Phi"); Phie_Phip_hist[j][i]->Write(); } } phi_folder->Write(); delete phi_folder; TDirectory* at180_folder = RootOutputFile->mkdir("at180"); at180_folder->cd(); for (short j = 0; j < detector_name.size(); j++) { for (int i = 0; i < NUM_SECTORS; i++) { W_hist_1pos_at180[j][i]->SetXTitle("W (GeV)"); W_hist_1pos_at180[j][i]->Write(); } for (int i = 0; i < NUM_SECTORS; i++) { W_vs_q2_1pos_at180[j][i]->SetXTitle("W (GeV)"); W_vs_q2_1pos_at180[j][i]->SetYTitle("Q^2 (GeV^2)"); W_vs_q2_1pos_at180[j][i]->SetOption("COLZ"); W_vs_q2_1pos_at180[j][i]->Write(); } } at180_folder->Write(); delete at180_folder; TDirectory* at180_MM_folder = RootOutputFile->mkdir("at180_MM"); at180_MM_folder->cd(); for (short j = 0; j < detector_name.size(); j++) { for (int i = 0; i < NUM_SECTORS; i++) { W_hist_1pos_at180_MM[j][i]->SetXTitle("W (GeV)"); W_hist_1pos_at180_MM[j][i]->Write(); } for (int i = 0; i < NUM_SECTORS; i++) { W_vs_q2_1pos_at180_MM[j][i]->SetXTitle("W (GeV)"); W_vs_q2_1pos_at180_MM[j][i]->SetYTitle("Q^2 (GeV^2)"); W_vs_q2_1pos_at180_MM[j][i]->SetOption("COLZ"); W_vs_q2_1pos_at180_MM[j][i]->Write(); } } at180_MM_folder->Write(); delete at180_MM_folder; TDirectory* W_vs_Q2_folder = RootOutputFile->mkdir("W_vs_Q2"); W_vs_Q2_folder->cd(); for (int i = 0; i < NUM_SECTORS; i++) { MissingMass[i]->SetXTitle("MM^2 (GeV)"); MissingMass[i]->Write(); mass_pi0_hist[before_cut][i]->SetXTitle("Mass (GeV)"); mass_pi0_hist[before_cut][i]->Write(); mass_pi0_hist[after_cut][i]->SetXTitle("Mass (GeV)"); mass_pi0_hist[after_cut][i]->Write(); mass_eta_hist[before_cut][i]->SetXTitle("Mass (GeV)"); mass_eta_hist[before_cut][i]->Write(); mass_eta_hist[after_cut][i]->SetXTitle("Mass (GeV)"); mass_eta_hist[after_cut][i]->Write(); W_hist_all_events[i]->SetXTitle("W (GeV)"); W_hist_all_events[i]->Write(); W_hist_1pos[i]->SetXTitle("W (GeV)"); W_hist_1pos[i]->Write(); W_hist_1pos_0charge[i]->SetXTitle("W (GeV)"); W_hist_1pos_0charge[i]->Write(); W_hist_1pos_noOther[i]->SetXTitle("W (GeV)"); W_hist_1pos_noOther[i]->Write(); W_vs_q2_all_events[i]->SetXTitle("W (GeV)"); W_vs_q2_all_events[i]->SetYTitle("Q^2 (GeV^2)"); W_vs_q2_all_events[i]->SetOption("COLZ"); W_vs_q2_all_events[i]->Write(); W_vs_q2_1pos[i]->SetXTitle("W (GeV)"); W_vs_q2_1pos[i]->SetYTitle("Q^2 (GeV^2)"); W_vs_q2_1pos[i]->SetOption("COLZ"); W_vs_q2_1pos[i]->Write(); W_vs_q2_1pos_0charge[i]->SetXTitle("W (GeV)"); W_vs_q2_1pos_0charge[i]->SetYTitle("Q^2 (GeV^2)"); W_vs_q2_1pos_0charge[i]->SetOption("COLZ"); W_vs_q2_1pos_0charge[i]->Write(); W_vs_q2_1pos_noOther[i]->SetXTitle("W (GeV)"); W_vs_q2_1pos_noOther[i]->SetYTitle("Q^2 (GeV^2)"); W_vs_q2_1pos_noOther[i]->SetOption("COLZ"); W_vs_q2_1pos_noOther[i]->Write(); } W_vs_Q2_folder->Write(); delete W_vs_Q2_folder; } void Histogram::Fill_MomVsBeta(const std::shared_ptr<Reaction>& _e) { if (!_e->onePositive_at180()) return; if (_e->pos_det() == -1) return; MomVsBeta[both_detectors][all_sectors]->Fill(_e->pos_P(), _e->pos_beta()); MomVsBeta[both_detectors][_e->sec()]->Fill(_e->pos_P(), _e->pos_beta()); ThetaVsP[both_detectors][all_sectors]->Fill(_e->pos_P(), _e->pos_theta()); ThetaVsP[both_detectors][_e->sec()]->Fill(_e->pos_P(), _e->pos_theta()); ThetaVsPCalc[both_detectors][all_sectors]->Fill(_e->pos_P(), _e->pos_theta_calc()); ThetaVsPCalc[both_detectors][_e->sec()]->Fill(_e->pos_P(), _e->pos_theta_calc()); MomVsBeta[_e->pos_det()][all_sectors]->Fill(_e->pos_P(), _e->pos_beta()); MomVsBeta[_e->pos_det()][_e->sec()]->Fill(_e->pos_P(), _e->pos_beta()); ThetaVsP[_e->pos_det()][all_sectors]->Fill(_e->pos_P(), _e->pos_theta()); ThetaVsP[_e->pos_det()][_e->sec()]->Fill(_e->pos_P(), _e->pos_theta()); ThetaVsPCalc[_e->pos_det()][all_sectors]->Fill(_e->pos_P(), _e->pos_theta_calc()); ThetaVsPCalc[_e->pos_det()][_e->sec()]->Fill(_e->pos_P(), _e->pos_theta_calc()); if (_e->W() < 2.0) { ThetaVsP_lowW[both_detectors][all_sectors]->Fill(_e->pos_P(), _e->pos_theta()); ThetaVsP_lowW[both_detectors][_e->sec()]->Fill(_e->pos_P(), _e->pos_theta()); ThetaVsP_lowW[_e->pos_det()][all_sectors]->Fill(_e->pos_P(), _e->pos_theta()); ThetaVsP_lowW[_e->pos_det()][_e->sec()]->Fill(_e->pos_P(), _e->pos_theta()); } } void Histogram::Write_MomVsBeta() { for (short i = 0; i < detector_name.size(); i++) { for (short p = 0; p < NUM_SECTORS; p++) { MomVsBeta[i][p]->SetXTitle("Momentum (GeV)"); MomVsBeta[i][p]->SetYTitle("#beta"); MomVsBeta[i][p]->SetOption("COLZ1"); MomVsBeta[i][p]->Write(); } for (short p = 0; p < NUM_SECTORS; p++) { ThetaVsP[i][p]->SetXTitle("Momentum (GeV)"); ThetaVsP[i][p]->SetYTitle("#theta"); ThetaVsP[i][p]->SetOption("COLZ1"); ThetaVsP[i][p]->Write(); } for (short p = 0; p < NUM_SECTORS; p++) { ThetaVsP_lowW[i][p]->SetXTitle("Momentum (GeV)"); ThetaVsP_lowW[i][p]->SetYTitle("#theta"); ThetaVsP_lowW[i][p]->SetOption("COLZ1"); ThetaVsP_lowW[i][p]->Write(); } for (short p = 0; p < NUM_SECTORS; p++) { ThetaVsPCalc[i][p]->SetXTitle("Momentum (GeV)"); ThetaVsPCalc[i][p]->SetYTitle("#theta"); ThetaVsPCalc[i][p]->SetOption("COLZ1"); ThetaVsPCalc[i][p]->Write(); } } } void Histogram::Fill_Dt(const std::shared_ptr<Delta_T>& dt) { for (int i = 0; i < dt->gpart(); i++) { if (dt->charge(i) == 1) deltaT_proton[before_cut]->Fill(dt->mom(i), dt->dt_P(i)); } } void Histogram::Fill_Dt(const std::shared_ptr<Delta_T>& dt, int part) { deltaT_proton[after_cut]->Fill(dt->mom(part), dt->dt_P(part)); } void Histogram::Fill_pi0(const std::shared_ptr<Reaction>& _e) { short sec = _e->sec(); short pos_det = _e->pos_det(); for (auto&& m : _e->pair_mass()) { mass_eta_hist[before_cut][all_sectors]->Fill(m); if ((sec > 0 && sec < NUM_SECTORS) || pos_det != -1) { mass_eta_hist[before_cut][sec]->Fill(m); if (_e->onePositive_at180_MM0()) { mass_eta_hist[after_cut][all_sectors]->Fill(m); mass_eta_hist[after_cut][sec]->Fill(m); } } } if (_e->pi0_mass() < 0.0001) return; mass_pi0_hist[before_cut][all_sectors]->Fill(_e->pi0_mass()); if ((sec > 0 && sec < NUM_SECTORS) || pos_det != -1) { mass_pi0_hist[before_cut][sec]->Fill(_e->pi0_mass()); if (_e->onePositive_at180_MM0()) { mass_pi0_hist[after_cut][all_sectors]->Fill(_e->pi0_mass()); mass_pi0_hist[after_cut][sec]->Fill(_e->pi0_mass()); } } }
44.293598
120
0.611313
tylern4
48643ecb23db6c91908494cc2de207bb205c2929
24,199
cpp
C++
src/ibp/widgets/curves.cpp
deiflou/ibp
9728f7569b59aa261dcaffc8332a1b02c2cd5fbe
[ "MIT" ]
6
2015-05-07T18:44:34.000Z
2018-12-12T15:57:40.000Z
src/ibp/widgets/curves.cpp
deiflou/ibp
9728f7569b59aa261dcaffc8332a1b02c2cd5fbe
[ "MIT" ]
null
null
null
src/ibp/widgets/curves.cpp
deiflou/ibp
9728f7569b59aa261dcaffc8332a1b02c2cd5fbe
[ "MIT" ]
2
2021-03-22T10:01:32.000Z
2021-12-20T05:23:46.000Z
// // MIT License // // Copyright (c) Deif Lou // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #include <QPainter> #include <QMouseEvent> #include <QKeyEvent> #include <QVBoxLayout> #include <math.h> #include "curves.h" #include "../misc/util.h" #include "../misc/nearestneighborsplineinterpolator1D.h" #include "../misc/linearsplineinterpolator1D.h" #include "../misc/cubicsplineinterpolator1D.h" namespace ibp { namespace widgets { const QSize Curves::kKnotSize(10, 10); Curves::Curves(QWidget *parent) : QWidget(parent), mZoomFactor(1.), mOffset(0.), mIsPeriodic(false), mIsInputEnabled(true), mInputStatus(NoStatus), mKnotIndex(-1), mSplineInterpolator(0), mInterpolationMode(Cubic), mPaintDelegate(0), mWidgetState(QStyle::State_None), mKnotStates(2, QStyle::State_None), mScrollBar(0), mEmitScrolbarSignals(true) { this->setMouseTracking(true); setFocusPolicy(Qt::StrongFocus); mSplineInterpolator = new CubicSplineInterpolator1D(); mSplineInterpolator->addKnot(0., 0.); mSplineInterpolator->addKnot(1., 1.); mScrollBar = new QScrollBar(Qt::Horizontal, this); mScrollBar->hide(); QVBoxLayout * layout = new QVBoxLayout(this); layout->setContentsMargins(kLeftMargin, kTopMargin, kRightMargin, kBottomMargin); layout->addStretch(1); layout->addWidget(mScrollBar); this->connect(mScrollBar, SIGNAL(valueChanged(int)), this, SLOT(On_mScrollBar_valueChanged(int))); mScrollBar->installEventFilter(this); updateScrollBar(); } void Curves::updateScrollBar() { int w = graphRect().width(); mScrollBar->setRange(0, w * mZoomFactor - w); mScrollBar->setValue(mOffset); mScrollBar->setPageStep(w); } QRect Curves::rectWithoutMargins() const { return this->rect().adjusted(kLeftMargin, kTopMargin, -kRightMargin, -kBottomMargin - (mZoomFactor > 1. ? mScrollBar->height() : 0)); } QRect Curves::graphRect() const { return mPaintDelegate ? mPaintDelegate->graphRect(rectWithoutMargins()) : rectWithoutMargins(); } int Curves::knotUnderCoords(const QPoint &p, bool addKnotIfPossible) { QRect gr = graphRect(); double kx, ky; const double rx = (kKnotSize.width() / 2.) / ((double)gr.width() * mZoomFactor); const double ry = (kKnotSize.height() / 2.) / ((double)gr.height()); const double x = mapToSplineInterpolator(p.x()); const double y = 1. - (p.y() - gr.top()) / ((double)gr.height()); const double minimumDistance = kMinimumDistanceToAddKnot / ((double)gr.height()); int index = -1; for (int i = 0; i < mSplineInterpolator->size() - mIsPeriodic ? 1 : 0; i++) { kx = mSplineInterpolator->knot(i).x(); ky = mSplineInterpolator->knot(i).y(); if (x > kx - rx && x < kx + rx && y > ky - ry && y < ky + ry) return i; } if (addKnotIfPossible && mSplineInterpolator->size() - (mIsPeriodic ? 1 : 0) < kMaximumNumberOfKnots && fabs(IBP_clamp(0., mSplineInterpolator->f(x), 1.) - y) < minimumDistance) { if (!mSplineInterpolator->addKnot(x, y, false, &index) || index == -1) return -1; const double min = index > 0 ? mSplineInterpolator->knot(index - 1).x() + kMinimumDistanceBetweenKnots : 0.; const double max = index < mSplineInterpolator->size() - (mIsPeriodic ? 2 : 1) ? mSplineInterpolator->knot(index + 1).x() - kMinimumDistanceBetweenKnots : 1.; mSplineInterpolator->setKnot(index, IBP_clamp(min, x, max), IBP_clamp(0., y, 1.)); if (mIsPeriodic && index == 0) mSplineInterpolator->setKnot(mSplineInterpolator->size() - 1, IBP_clamp(min, x, max) + 1., IBP_clamp(0., y, 1.)); if (mKnotIndex >= index) mKnotIndex++; mKnotStates.insert(index, QStyle::State_None); if (mPaintDelegate) mPaintDelegate->update(CurvesPaintDelegate::KnotsChanged, this, rectWithoutMargins()); emit knotsChanged(mSplineInterpolator->knots()); update(); return index; } return -1; } void Curves::paintEvent(QPaintEvent *) { if (!mPaintDelegate) return; QPainter p(this); p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); QRect r = this->rect().adjusted(kLeftMargin, kTopMargin, -kRightMargin, -kBottomMargin); // shadow p.setPen(Qt::NoPen); p.setBrush(QColor(0, 0, 0, 32)); p.drawRoundedRect(r.adjusted(-2, -1, 2, 3), 3, 3); p.drawRoundedRect(r.adjusted(-1, 0, 1, 2), 2, 2); p.setBrush(QColor(0, 0, 0, 50)); p.drawRoundedRect(r.adjusted(0, 1, 0, 1), 1, 1); // ---- QStyle::State widgetState = mWidgetState | (isEnabled() ? QStyle::State_Enabled : QStyle::State_None) | (hasFocus() ? QStyle::State_HasFocus : QStyle::State_None) | (!mIsInputEnabled ? QStyle::State_ReadOnly : QStyle::State_None); // ---- if (mZoomFactor > 1.) r.adjust(0, 0, 0, -mScrollBar->height()); // clip QPainterPath clippingPath; clippingPath.addRoundedRect(r, 1, 1); p.setClipPath(clippingPath); // graph QRect graphRectCopy = graphRect(); QPolygonF poly; for (int i = r.left(); i <= r.right(); i++) poly.append(QPointF(i, (1. - valueAt(mapToSplineInterpolator(i))) * graphRectCopy.height() + graphRectCopy.top())); // knots QVector<QPointF> knotPositions; if (graphRectCopy.width() >= kMinimumSizeForInput && graphRectCopy.height() >= kMinimumSizeForInput) for (int i = 0; i < mSplineInterpolator->size() - mIsPeriodic ? 1 : 0; i++) knotPositions << QPointF(mapFromSplineInterpolator(mSplineInterpolator->knot(i).x()), (1. - mSplineInterpolator->knot(i).y()) * graphRectCopy.height() + graphRectCopy.top()); p.save(); mPaintDelegate->paint(p, this, r, widgetState, poly, knotPositions, mKnotStates, kKnotSize); p.restore(); // focus rect if (widgetState & QStyle::State_HasFocus) { p.setPen(QPen(this->palette().color(QPalette::Highlight), 4)); p.setBrush(Qt::NoBrush); p.drawRect(r); } // paint if disabled if (!(widgetState & QStyle::State_Enabled)) { QColor disabledColor = this->palette().color(QPalette::Button); disabledColor.setAlpha(200); p.fillRect(r, disabledColor); } } void Curves::mousePressEvent(QMouseEvent * e) { if (!mIsInputEnabled || mInputStatus != NoStatus) return; QRect gr = graphRect(); if (gr.width() < kMinimumSizeForInput || gr.height() < kMinimumSizeForInput) return; int index; bool mustEmitSignal = false; if (e->button() == Qt::LeftButton) { if (mKnotIndex > -1) mKnotStates[mKnotIndex] &= ~QStyle::State_Selected; // add a knot and check if there is a knot in this position index = knotUnderCoords(e->pos(), true); mustEmitSignal = index != mKnotIndex; if (index != -1) { mKnotIndex = index; mInputStatus = DraggingKnot; mKnotStates[mKnotIndex] |= QStyle::State_Selected | QStyle::State_Sunken; update(); if (mustEmitSignal) emit selectedKnotChanged(mKnotIndex); return; } // clicked in non-input area, deselect selected item mKnotIndex = -1; mInputStatus = NoStatus; update(); if (mustEmitSignal) emit selectedKnotChanged(mKnotIndex); return; } if (e->button() == Qt::RightButton && mSplineInterpolator->size() > (mIsPeriodic ? 3 : 2)) { index = knotUnderCoords(e->pos()); if (index != -1) { mKnotStates.remove(index); if (index == mKnotIndex) { mKnotIndex = -1; mustEmitSignal = true; } else if (mKnotIndex > index) { mKnotIndex--; mustEmitSignal = true; } mSplineInterpolator->removeKnot(index); if (mIsPeriodic && index == 0) mSplineInterpolator->setKnot(mSplineInterpolator->size() - 1, mSplineInterpolator->knot(0).x() + 1., mSplineInterpolator->knot(0).y()); if (mPaintDelegate) mPaintDelegate->update(CurvesPaintDelegate::KnotsChanged, this, rectWithoutMargins()); update(); emit knotsChanged(mSplineInterpolator->knots()); if (mustEmitSignal) emit selectedKnotChanged(mKnotIndex); return; } } } void Curves::mouseReleaseEvent(QMouseEvent * e) { if (!mIsInputEnabled) return; if (e->button() == Qt::LeftButton) { for (int i = 0; i < mKnotStates.size(); i++) mKnotStates[i] &= ~QStyle::State_Sunken; mInputStatus = NoStatus; mouseMoveEvent(e); } } void Curves::mouseMoveEvent(QMouseEvent * e) { if (!mIsInputEnabled) return; mWidgetState = mWidgetState | QStyle::State_MouseOver; // dragging knot if (mInputStatus == DraggingKnot && mKnotIndex > -1 && e->buttons() & Qt::LeftButton) { QRect gr = graphRect(); QPointF position = e->pos(); const double min = mKnotIndex > 0 ? mSplineInterpolator->knot(mKnotIndex - 1).x() + kMinimumDistanceBetweenKnots : 0.; const double max = IBP_minimum(1., mKnotIndex < mSplineInterpolator->size() - 1 ? mSplineInterpolator->knot(mKnotIndex + 1).x() - kMinimumDistanceBetweenKnots : 1.); position.setX(IBP_clamp(min, mapToSplineInterpolator(position.x()), max)); position.setY(IBP_clamp(0., 1. - (position.y() - gr.top()) / (double)gr.height(), 1.)); mSplineInterpolator->setKnot(mKnotIndex, position.x(), position.y()); if (mIsPeriodic && mKnotIndex == 0) mSplineInterpolator->setKnot(mSplineInterpolator->size() - 1, IBP_maximum(1.001, position.x() + 1.), position.y()); if (mPaintDelegate) mPaintDelegate->update(CurvesPaintDelegate::KnotsChanged, this, rectWithoutMargins()); update(); emit knotsChanged(mSplineInterpolator->knots()); return; } // not dragging this->unsetCursor(); if (!rectWithoutMargins().contains(e->pos())) return; for (int i = 0; i < mKnotStates.size(); i++) mKnotStates[i] &= ~QStyle::State_MouseOver; const int index = knotUnderCoords(e->pos()); if (index != -1) mKnotStates[index] |= QStyle::State_MouseOver; update(); } void Curves::leaveEvent(QEvent *) { mWidgetState = mWidgetState & ~QStyle::State_MouseOver; for (int i = 0; i < mKnotStates.size(); i++) mKnotStates[i] &= ~QStyle::State_MouseOver; unsetCursor(); update(); } void Curves::resizeEvent(QResizeEvent * e) { if (e->oldSize().isEmpty()) return; setOffset(mOffset * e->size().width() / e->oldSize().width()); } bool Curves::eventFilter(QObject *o, QEvent *e) { if (o == mScrollBar && e->type() == QEvent::Enter) leaveEvent(e); return false; } void Curves::keyPressEvent(QKeyEvent *e) { if (mKnotIndex == -1) return; Interpolator1DKnot k = mSplineInterpolator->knot(mKnotIndex); const double min = mKnotIndex > 0 ? mSplineInterpolator->knot(mKnotIndex - 1).x() + kMinimumDistanceBetweenKnots : 0.; const double max = IBP_minimum(1., mKnotIndex < mSplineInterpolator->size() - 1 ? mSplineInterpolator->knot(mKnotIndex + 1).x() - kMinimumDistanceBetweenKnots : 1.); switch (e->key()) { case Qt::Key_Right: if (e->modifiers() & Qt::ControlModifier) { mKnotStates[mKnotIndex] &= ~QStyle::State_Selected; mKnotIndex++; if (mKnotIndex == mSplineInterpolator->size() - (mIsPeriodic ? 1 : 0)) mKnotIndex--; mKnotStates[mKnotIndex] |= QStyle::State_Selected; update(); emit selectedKnotChanged(mKnotIndex); } else { k.setX(IBP_clamp(min, k.x() + kKeypressIncrement, max)); mSplineInterpolator->setKnot(mKnotIndex, k); if (mIsPeriodic && mKnotIndex == 0) mSplineInterpolator->setKnot(mSplineInterpolator->size() - 1, IBP_maximum(1.001, k.x() + 1.), k.y()); if (mPaintDelegate) mPaintDelegate->update(CurvesPaintDelegate::KnotsChanged, this, rectWithoutMargins()); update(); emit knotsChanged(mSplineInterpolator->knots()); } break; case Qt::Key_Left: if (e->modifiers() & Qt::ControlModifier) { mKnotStates[mKnotIndex] &= ~QStyle::State_Selected; mKnotIndex--; if (mKnotIndex == -1) mKnotIndex = 0; mKnotStates[mKnotIndex] |= QStyle::State_Selected; update(); emit selectedKnotChanged(mKnotIndex); } else { k.setX(IBP_clamp(min, k.x() - kKeypressIncrement, max)); mSplineInterpolator->setKnot(mKnotIndex, k); if (mIsPeriodic && mKnotIndex == 0) mSplineInterpolator->setKnot(mSplineInterpolator->size() - 1, IBP_maximum(1.001, k.x() + 1.), k.y()); if (mPaintDelegate) mPaintDelegate->update(CurvesPaintDelegate::KnotsChanged, this, rectWithoutMargins()); update(); emit knotsChanged(mSplineInterpolator->knots()); } break; case Qt::Key_Up: k.setY(IBP_minimum(k.y() + kKeypressIncrement, 1.)); mSplineInterpolator->setKnot(mKnotIndex, k); if (mIsPeriodic && mKnotIndex == 0) mSplineInterpolator->setKnot(mSplineInterpolator->size() - 1, k.x() + 1., k.y()); if (mPaintDelegate) mPaintDelegate->update(CurvesPaintDelegate::KnotsChanged, this, rectWithoutMargins()); update(); emit knotsChanged(mSplineInterpolator->knots()); break; case Qt::Key_Down: k.setY(IBP_maximum(k.y() - kKeypressIncrement, 0.)); mSplineInterpolator->setKnot(mKnotIndex, k); if (mIsPeriodic && mKnotIndex == 0) mSplineInterpolator->setKnot(mSplineInterpolator->size() - 1, k.x() + 1., k.y()); if (mPaintDelegate) mPaintDelegate->update(CurvesPaintDelegate::KnotsChanged, this, rectWithoutMargins()); update(); emit knotsChanged(mSplineInterpolator->knots()); break; default: QWidget::keyPressEvent(e); return; } } double Curves::zoomFactor() const { return mZoomFactor; } double Curves::offset() const { return mOffset; } bool Curves::isPeriodic() const { return mIsPeriodic; } bool Curves::isInputEnabled() const { return mIsInputEnabled; } const Interpolator1DKnots & Curves::knots() const { return mSplineInterpolator->knots(); } int Curves::selectedKnotIndex() const { return mKnotIndex; } const Interpolator1DKnot & Curves::selectedKnot() const { static const Interpolator1DKnot nullSplineInterpolatorKnot; if (mKnotIndex == -1) return nullSplineInterpolatorKnot; return mSplineInterpolator->knot(mKnotIndex); } Curves::InterpolationMode Curves::interpolationMode() const { return mInterpolationMode; } CurvesPaintDelegate *Curves::paintDelegate() const { return mPaintDelegate; } double Curves::valueAt(double v) { return IBP_clamp(0., mSplineInterpolator->f(v), 1.); } double Curves::mapToSplineInterpolator(double v) const { QRect r = graphRect(); return (v - r.left() + mOffset) / ((r.width() - 1) * mZoomFactor); } double Curves::mapFromSplineInterpolator(double v) const { QRect r = graphRect(); return (v * (r.width() - 1) * mZoomFactor) - mOffset + r.left(); } void Curves::setZoomFactor(double v) { if (qFuzzyCompare(mZoomFactor, v)) return; double oldZoomFactor = mZoomFactor; mZoomFactor = v; if (v > 1.) setOffset(mOffset * mZoomFactor / oldZoomFactor); else center(); mScrollBar->setVisible(mZoomFactor > 1.); updateScrollBar(); if (mPaintDelegate) mPaintDelegate->update(CurvesPaintDelegate::ZoomFactorChanged, this, rectWithoutMargins()); update(); emit zoomFactorChanged(v); } void Curves::setOffset(double v) { if (qFuzzyCompare(mOffset, v)) return; int w = graphRect().width(); mOffset = IBP_clamp(0., v, w * mZoomFactor - w); mEmitScrolbarSignals = false; updateScrollBar(); mEmitScrolbarSignals = true; if (mPaintDelegate) mPaintDelegate->update(CurvesPaintDelegate::OffsetChanged, this, rectWithoutMargins()); update(); emit offsetChanged(v); } void Curves::center() { int w = graphRect().width(); setOffset((w * mZoomFactor - w) / 2); } void Curves::fit() { setZoomFactor(1.); center(); } void Curves::setPeriodic(bool v) { if (mIsPeriodic == v) return; mIsPeriodic = v; if (mIsPeriodic) { mSplineInterpolator->addKnot(IBP_maximum(1.001, mSplineInterpolator->knot(0).x() + 1.), mSplineInterpolator->knot(0).y()); mSplineInterpolator->setExtrapolationMode(Interpolator1D::ExtrapolationMode_Repeat, Interpolator1D::ExtrapolationMode_Repeat); if (mInterpolationMode == Cubic) ((CubicSplineInterpolator1D *)mSplineInterpolator)->setBoundaryConditions( CubicSplineInterpolator1D::BoundaryConditions_Periodic, CubicSplineInterpolator1D::BoundaryConditions_Periodic); } else { mSplineInterpolator->removeKnot(mSplineInterpolator->size() - 1); mSplineInterpolator->setExtrapolationMode(Interpolator1D::ExtrapolationMode_Clamp, Interpolator1D::ExtrapolationMode_Clamp); ((CubicSplineInterpolator1D *)mSplineInterpolator)->setBoundaryConditions( CubicSplineInterpolator1D::BoundaryConditions_Natural, CubicSplineInterpolator1D::BoundaryConditions_Natural); } if (mPaintDelegate) mPaintDelegate->update(CurvesPaintDelegate::PeriodicChanged, this, rectWithoutMargins()); update(); emit periodicChanged(v); } void Curves::setInputEnabled(bool v) { if (mIsInputEnabled == v) return; mIsInputEnabled = v; if (mPaintDelegate) mPaintDelegate->update(CurvesPaintDelegate::InputEnabledChanged, this, rectWithoutMargins()); update(); emit inputEnabledChanged(v); } void Curves::setKnots(const Interpolator1DKnots &k) { mSplineInterpolator->setKnots(k); mKnotStates = QVector<QStyle::State>(k.size(), QStyle::State_None); mKnotIndex = -1; if (mIsPeriodic) mSplineInterpolator->addKnot(IBP_maximum(1.001, k[0].x() + 1.), k[0].y()); if (mPaintDelegate) mPaintDelegate->update(CurvesPaintDelegate::KnotsChanged, this, rectWithoutMargins()); update(); emit knotsChanged(k); emit selectedKnotChanged(mKnotIndex); } void Curves::setSelectedKnot(double x, double y) { const double min = mKnotIndex > 0 ? mSplineInterpolator->knot(mKnotIndex - 1).x() + kMinimumDistanceBetweenKnots : 0.; const double max = mKnotIndex < mSplineInterpolator->size() - 1 ? mSplineInterpolator->knot(mKnotIndex + 1).x() - kMinimumDistanceBetweenKnots : 1.; mSplineInterpolator->setKnot(mKnotIndex, IBP_clamp(min, x, max), IBP_clamp(0., y, 1.)); if (mPaintDelegate) mPaintDelegate->update(CurvesPaintDelegate::KnotsChanged, this, rectWithoutMargins()); update(); emit knotsChanged(mSplineInterpolator->knots()); } void Curves::setSelectedKnot(const Interpolator1DKnot &k) { setSelectedKnot(k.x(), k.y()); } void Curves::setInterpolationMode(Curves::InterpolationMode m) { if (mInterpolationMode == m) return; mInterpolationMode = m; Interpolator1D * tmpSplineInterpolator = mSplineInterpolator; if (mInterpolationMode == NearestNeighbor) mSplineInterpolator = new NearestNeighborSplineInterpolator1D(); else if (mInterpolationMode == Linear) mSplineInterpolator = new LinearSplineInterpolator1D(); else { mSplineInterpolator = new CubicSplineInterpolator1D(); ((CubicSplineInterpolator1D *)mSplineInterpolator)->setBoundaryConditions( mIsPeriodic ? CubicSplineInterpolator1D::BoundaryConditions_Periodic : CubicSplineInterpolator1D::BoundaryConditions_Natural, mIsPeriodic ? CubicSplineInterpolator1D::BoundaryConditions_Periodic : CubicSplineInterpolator1D::BoundaryConditions_Natural); } mSplineInterpolator->setKnots(tmpSplineInterpolator->knots()); mSplineInterpolator->setExtrapolationMode(tmpSplineInterpolator->floorExtrapolationMode(), tmpSplineInterpolator->ceilExtrapolationMode(), tmpSplineInterpolator->floorExtrapolationValue(), tmpSplineInterpolator->ceilExtrapolationValue()); delete tmpSplineInterpolator; if (mPaintDelegate) mPaintDelegate->update(CurvesPaintDelegate::InterpolationModeChanged, this, rectWithoutMargins()); update(); emit interpolationModeChanged(m); } void Curves::setPaintDelegate(CurvesPaintDelegate *pd) { if (pd == mPaintDelegate) return; mPaintDelegate = pd; if (mPaintDelegate) { mPaintDelegate->update(CurvesPaintDelegate::KnotsChanged, this, rectWithoutMargins()); mPaintDelegate->update(CurvesPaintDelegate::ZoomFactorChanged, this, rectWithoutMargins()); mPaintDelegate->update(CurvesPaintDelegate::OffsetChanged, this, rectWithoutMargins()); mPaintDelegate->update(CurvesPaintDelegate::PeriodicChanged, this, rectWithoutMargins()); mPaintDelegate->update(CurvesPaintDelegate::InputEnabledChanged, this, rectWithoutMargins()); mPaintDelegate->update(CurvesPaintDelegate::InterpolationModeChanged, this, rectWithoutMargins()); this->connect(mPaintDelegate, SIGNAL(updateRequired()), this, SLOT(update())); } update(); emit paintDelegateChanged(pd); } void Curves::On_mScrollBar_valueChanged(int v) { if (mEmitScrolbarSignals) setOffset(v); } }}
33.377931
117
0.621637
deiflou
4864485476c26ac53ed64956481d56ab5bea8033
394
hh
C++
src/scorer/scorer.hh
RafaelOstertag/tetris
ea1abfecdd3f8183331853708291c9943453a962
[ "BSD-2-Clause" ]
1
2020-01-02T19:31:58.000Z
2020-01-02T19:31:58.000Z
src/scorer/scorer.hh
RafaelOstertag/tetris
ea1abfecdd3f8183331853708291c9943453a962
[ "BSD-2-Clause" ]
null
null
null
src/scorer/scorer.hh
RafaelOstertag/tetris
ea1abfecdd3f8183331853708291c9943453a962
[ "BSD-2-Clause" ]
null
null
null
#ifndef __SCORER_HH #define __SCORER_HH #include <memory> class Scorer { public: using score_t = unsigned int; using level_t = unsigned int; virtual ~Scorer() = default; virtual void scoreLinesRemoved(unsigned int numberOfLines) = 0; virtual score_t getScore() const = 0; virtual level_t getLevel() const = 0; }; using ScorerPtr = std::shared_ptr<Scorer>; #endif
19.7
67
0.703046
RafaelOstertag
4866834de98647a54e76f36e535cfbaa5a96f583
1,242
cpp
C++
Software/STM32CubeDemo/RotaryEncoderWithDisplay/TouchGFX/generated/fonts/src/Kerning_verdana_22_4bpp.cpp
MitkoDyakov/RED
3bacb4df47867bbbf23c3c02d0ea1f8faa8d5779
[ "MIT" ]
15
2021-09-21T13:55:54.000Z
2022-03-08T14:05:39.000Z
Software/STM32CubeDemo/RotaryEncoderWithDisplay/TouchGFX/generated/fonts/src/Kerning_verdana_22_4bpp.cpp
DynamixYANG/Roendi
2f6703d63922071fd0dfc8e4d2c9bba95ea04f08
[ "MIT" ]
7
2021-09-22T07:56:52.000Z
2022-03-21T17:39:34.000Z
Software/STM32CubeDemo/RotaryEncoderWithDisplay/TouchGFX/generated/fonts/src/Kerning_verdana_22_4bpp.cpp
DynamixYANG/Roendi
2f6703d63922071fd0dfc8e4d2c9bba95ea04f08
[ "MIT" ]
1
2022-03-07T07:51:50.000Z
2022-03-07T07:51:50.000Z
#include <touchgfx/Font.hpp> FONT_KERNING_LOCATION_FLASH_PRAGMA KEEP extern const touchgfx::KerningNode kerning_verdana_22_4bpp[] FONT_KERNING_LOCATION_FLASH_ATTRIBUTE = { { 0x0054, -2 }, // (First char = [0x0054, T], Second char = [0x003A, :], Kerning dist = -2) { 0x0054, 1 }, // (First char = [0x0054, T], Second char = [0x003F, ?], Kerning dist = 1) { 0x004C, -2 }, // (First char = [0x004C, L], Second char = [0x0054, T], Kerning dist = -2) { 0x0052, -1 }, // (First char = [0x0052, R], Second char = [0x0054, T], Kerning dist = -1) { 0x0054, -1 }, // (First char = [0x0054, T], Second char = [0x0054, T], Kerning dist = -1) { 0x0065, -1 }, // (First char = [0x0065, e], Second char = [0x0054, T], Kerning dist = -1) { 0x0054, -2 }, // (First char = [0x0054, T], Second char = [0x0065, e], Kerning dist = -2) { 0x0054, -2 }, // (First char = [0x0054, T], Second char = [0x006F, o], Kerning dist = -2) { 0x0054, -2 }, // (First char = [0x0054, T], Second char = [0x0075, u], Kerning dist = -2) { 0x004C, -1 }, // (First char = [0x004C, L], Second char = [0x0076, v], Kerning dist = -1) { 0x0054, -2 }, // (First char = [0x0054, T], Second char = [0x0076, v], Kerning dist = -2) };
73.058824
107
0.57971
MitkoDyakov
486781d77c422e446193beae41a89f88123a7a03
1,833
hpp
C++
include/make_matrix.hpp
SuperV1234/UNIME_numerical_calculus
f8f481641b0dfd9c5062bc819e127bd4fedf6f30
[ "AFL-3.0" ]
1
2016-06-30T14:03:37.000Z
2016-06-30T14:03:37.000Z
include/make_matrix.hpp
SuperV1234/UNIME_numerical_calculus
f8f481641b0dfd9c5062bc819e127bd4fedf6f30
[ "AFL-3.0" ]
null
null
null
include/make_matrix.hpp
SuperV1234/UNIME_numerical_calculus
f8f481641b0dfd9c5062bc819e127bd4fedf6f30
[ "AFL-3.0" ]
null
null
null
// Copyright (c) 2015-2016 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: http://opensource.org/licenses/AFL-3.0 // http://vittorioromeo.info | vittorio.romeo@outlook.com #pragma once #include <cstddef> #include <cassert> #include <cmath> #include <iostream> #include <tuple> #include <vector> #include <algorithm> #include <limits> #include <vrm/core/static_if.hpp> #include "utilities.hpp" #include "multiples.hpp" #include "equations.hpp" #include "folds.hpp" #include "representations.hpp" #include "sorted_vector.hpp" #include "matrix.hpp" namespace nc { // Crea una matrice NxM da NxM argomenti variadici. template <typename T0, std::size_t TRowCount, std::size_t TColumnCount, typename... Ts> auto make_matrix(Ts&&... xs) { matrix<T0, TRowCount, TColumnCount> result; // TODO: result.set_from_variadic(xs...); return result; } // Crea un matrice quadrata da N argomenti variadici. template <typename T0, std::size_t TDim, typename... Ts> auto make_square_matrix(Ts&&... xs) { return make_matrix<T0, TDim, TDim>(xs...); } // Crea un matrice identità NxN. template <typename T0, std::size_t TDim, typename... Ts> auto make_identity_matrix() { return matrix<T0, TDim, TDim>{init_identity{}}; } // Data una matrice `m`, restituisce la sua trasposta. template <typename T0, std::size_t TRowCount, std::size_t TColumnCount> auto make_transposed(const matrix<T0, TRowCount, TColumnCount>& m) { matrix<T0, TColumnCount, TRowCount> result; for(std::size_t i(0); i < TRowCount; ++i) for(std::size_t j(0); j < TColumnCount; ++j) { result(j, i) = m(i, j); } return result; } }
26.185714
75
0.637752
SuperV1234
4868d517b0680224cfb2a7bdbbb68ee8f1d60784
7,146
cpp
C++
servers/src/VisualServer2D.cpp
wookie41/blitz
7f587bee9b6189c32f0f60c69316bc8deca23c16
[ "MIT" ]
1
2020-01-04T21:04:52.000Z
2020-01-04T21:04:52.000Z
servers/src/VisualServer2D.cpp
wookie41/blitz
7f587bee9b6189c32f0f60c69316bc8deca23c16
[ "MIT" ]
15
2019-08-26T20:54:31.000Z
2020-03-15T14:11:44.000Z
servers/src/VisualServer2D.cpp
wookie41/blitz
7f587bee9b6189c32f0f60c69316bc8deca23c16
[ "MIT" ]
null
null
null
#include <servers/VisualServer2D.h> #include <core/ogl/texture/OpenGLTextureSampler.h> #include <core/Device.h> #include <core/Renderer.h> #include <scene/2d/Canvas.h> #include <scene/2d/Sprite.h> #include <blitzmemory/Memory.h> #include <core/RenderCommand.h> #include <front/ForwardRenderingPath.h> #include <platform/fs/FileSystem.h> #include <core/Texture.h> #include <blitzmemory/Memory.h> namespace blitz { extern VertexArray* quadVertexArray; extern Renderer* BLITZ_RENDERER; extern Device* BLITZ_DEVICE; static const uint8 MAX_CANVAS_COUNT = 5; VisualServer2D::VisualServer2D(uint8 numCanvases) { memory::resetThreadAllocator(); canvases = new Array<Canvas>(numCanvases); renderFramePool = new memory::PoolAllocator(5000000); renderFramePool->init(); renderingPath = new front::ForwardRenderingPath(BLITZ_RENDERER); } VisualServer2D::~VisualServer2D() { delete canvases; } CanvasID VisualServer2D::createCanvas() { const uint8 canvasID = canvases->getSize(); assert(canvasID < MAX_CANVAS_COUNT); canvases->add(Canvas{}); Canvas* canvas = canvases->get(canvasID); initChildren(canvas); return canvasID; } Canvas* VisualServer2D::getCanvas(CanvasID canvasID) const { assert(canvasID < MAX_CANVAS_COUNT); return canvases->get(canvasID); } void VisualServer2D::attachToCanvas(CanvasID canvasID, CanvasItem* item) { assert(canvasID < canvases->getSize()); Canvas* canvas = canvases->get(canvasID); canvas->childrenTail->child = item; canvas->childrenTail->next = new CanvasChild; canvas->childrenTail = canvas->childrenTail->next; } void VisualServer2D::detachFromCanvas(CanvasID canvasID, CanvasItem* item) { assert(canvasID < canvases->getSize()); Canvas* canvas = canvases->get(canvasID); CanvasChild* prevNode = nullptr; CanvasChild* childNode = canvas->children; while (childNode != nullptr) { if (childNode->child == item) { if (prevNode != nullptr) { prevNode->next = childNode->next; } childNode->child = nullptr; childNode->next = nullptr; return; } childNode = childNode->next; } } VisualServer2D* VisualServer2D::getInstance() { static VisualServer2D visualServer2D(MAX_CANVAS_COUNT); return &visualServer2D; } Sprite* VisualServer2D::createSprite() { Sprite* sprite = new Sprite; initChildren(sprite); return sprite; } void VisualServer2D::initChildren(CanvasItem* canvasItem) const { canvasItem->children = new CanvasChild; canvasItem->childrenTail = canvasItem->children; } void VisualServer2D::render(Framebuffer* target, const ViewPort* viewPort, const front::Camera* camera, const CanvasID& canvasID) const { renderFramePool->reset(); memory::setThreadAllocator(renderFramePool); assert(canvasID < canvases->getSize()); Canvas* canvas = canvases->get(canvasID); CanvasChild* nodeToRender = canvas->children; Array<RenderCommand>* renderCanvasCommands = new Array<RenderCommand>(128); while (nodeToRender->child != nullptr) { switch (nodeToRender->child->getType()) { case CanvasItemType::SPRITE: renderSprite(target, canvas->transform, (Sprite*)nodeToRender->child, renderCanvasCommands); break; } nodeToRender = nodeToRender->next; front::RenderList* renderList = new front::RenderList; renderList->viewPort = viewPort; renderList->camera = camera; renderList->framebuffer = target; renderList->geometry = renderCanvasCommands; renderList->lights = nullptr; renderingPath->render(renderList); } memory::resetThreadAllocator(); } void VisualServer2D::renderSprite(Framebuffer* target, const Transform2D& parentTransfrom, const Sprite* sprite, Array<RenderCommand>* commandsBuffer) const { static const hash SPRITE_POSITION_UNIFORM_HASH = hashString("_bSpritePosition"); static const hash SPRITE_SIZE_UNIFORM_HASH = hashString("_bSpriteSize"); static const hash SPRITE_TEXTURE_UNIFORM_HASH = hashString("_bSpriteTexture"); static const hash SPRITE_TEXTURE_REGION_SIZE = hashString("_bSpriteTexRegionSize"); static const hash SPRITE_TEXTURE_REGION_INDEX = hashString("_bSpriteTexRegionIndex"); static const hash SPRITE_TEXTURE_SIZE = hashString("_bSpriteTexSize"); commandsBuffer->add(RenderCommand{}); RenderCommand* renderCommand = commandsBuffer->get(commandsBuffer->getSize() - 1); renderCommand->buffers = nullptr; renderCommand->drawMode = DrawMode::NORMAL; renderCommand->numberOfVerticesToDraw = 4; renderCommand->numberOfIndicesToDraw = 0; renderCommand->primitiveType = PrimitiveType::TRIANGLE_STRIP; renderCommand->vertexArray = quadVertexArray; renderCommand->shader = sprite->material->shader; size_t materialPropertiesCount = sprite->material->properties == nullptr ? 0 : sprite->material->properties->getSize(); Array<UniformState>* uniformsStates = new Array<UniformState>(6 + materialPropertiesCount); for (size_t materialPropIdx = 0; materialPropIdx < materialPropertiesCount; ++materialPropIdx) { UniformState* materialUniformState = uniformsStates->get(materialPropIdx); uniformsStates->add(materialUniformState); } // TODO sampler should not have to be created every time it should at least be configurable blitz::TextureSampler* spriteTextureSampler = BLITZ_DEVICE->createSampler(sprite->texture); uniformsStates->add({ DataType::VECTOR2F, SPRITE_POSITION_UNIFORM_HASH, (void*)&sprite->transform.translate }); uniformsStates->add({ DataType::VECTOR2I, SPRITE_SIZE_UNIFORM_HASH, (void*)&sprite->spriteSize }); uniformsStates->add({ DataType::SAMPLER2D, SPRITE_TEXTURE_UNIFORM_HASH, (void*)spriteTextureSampler }); uniformsStates->add({ DataType::VECTOR2I, SPRITE_TEXTURE_REGION_INDEX, (void*)&sprite->texRegionIndex }); uniformsStates->add({ DataType::VECTOR2I, SPRITE_TEXTURE_REGION_SIZE, (void*)&sprite->texRegionSize }); uniformsStates->add({ DataType::VECTOR3I, SPRITE_TEXTURE_SIZE, (void*)&sprite->texture->getSize() }); renderCommand->uniformsState = uniformsStates; } } // namespace blitz
37.809524
140
0.637
wookie41
4869b98d1aeecdf2bc51d3b2ebcbd130e734862f
10,892
cpp
C++
interfaces/innerkits/appverify/src/provision/provision_verify.cpp
openharmony-sig-ci/security_appverify
5c705c648c87383f3ab4cbdae187933db9138e76
[ "Apache-2.0" ]
null
null
null
interfaces/innerkits/appverify/src/provision/provision_verify.cpp
openharmony-sig-ci/security_appverify
5c705c648c87383f3ab4cbdae187933db9138e76
[ "Apache-2.0" ]
null
null
null
interfaces/innerkits/appverify/src/provision/provision_verify.cpp
openharmony-sig-ci/security_appverify
5c705c648c87383f3ab4cbdae187933db9138e76
[ "Apache-2.0" ]
1
2021-09-13T11:13:32.000Z
2021-09-13T11:13:32.000Z
/* * Copyright (C) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "provision/provision_verify.h" #include <algorithm> #include "nlohmann/json.hpp" #ifndef STANDARD_SYSTEM #include "ohos_account_kits.h" #else #include "parameter.h" #include "sysparam_errno.h" #endif // STANDARD_SYSTEM #include "common/hap_verify_log.h" #include "init/device_type_manager.h" using namespace std; using namespace nlohmann; namespace { const string KEY_VERSION_CODE = "version-code"; const string KEY_VERSION_NAME = "version-name"; const string KEY_UUID = "uuid"; const string KEY_TYPE = "type"; const string KEY_APP_DIST_TYPE = "app-distribution-type"; const string KEY_BUNDLE_INFO = "bundle-info"; const string KEY_DEVELOPER_ID = "developer-id"; const string KEY_DEVELOPMENT_CERTIFICATE = "development-certificate"; const string KEY_DISTRIBUTION_CERTIFICATE = "distribution-certificate"; const string KEY_BUNDLE_NAME = "bundle-name"; const string KEY_APP_FEATURE = "app-feature"; const string KEY_PERMISSIONS = "permissions"; const string KEY_RESTRICTED_PERMISSIONS = "restricted-permissions"; const string KEY_RESTRICTED_CAPABILITIES = "restricted-capabilities"; const string KEY_DEBUG_INFO = "debug-info"; const string KEY_DEVICE_ID_TYPE = "device-id-type"; const string KEY_DEVICE_IDS = "device-ids"; const string KEY_ISSUER = "issuer"; const string VALUE_TYPE_RELEASE = "release"; const string VALUE_DIST_TYPE_APP_GALLERY = "app_gallery"; const string VALUE_DIST_TYPE_ENTERPRISE = "enterprise"; const string VALUE_DIST_TYPE_OS_INTEGRATION = "os_integration"; const string VALUE_DEVICE_ID_TYPE_UDID = "udid"; const string GENERIC_BUNDLE_NAME = ".*"; const int MAXIMUM_NUM_DEVICES = 100; inline void GetStringIfExist(const json& obj, const string& key, string& out) { if (obj.find(key.c_str()) != obj.end() && obj[key.c_str()].is_string()) { obj[key.c_str()].get_to(out); } } inline void GetInt32IfExist(const json& obj, const string& key, int32_t& out) { if (obj.find(key.c_str()) != obj.end() && obj[key.c_str()].is_number_integer()) { obj[key.c_str()].get_to(out); } } inline void GetStringArrayIfExist(const json& obj, const string& key, vector<string>& out) { if (obj.find(key.c_str()) != obj.end() && obj[key.c_str()].is_array()) { for (auto& item : obj[key.c_str()]) { if (item.is_string()) { out.push_back(item.get<string>()); } } } } inline bool IsObjectExist(const json& obj, const string& key) { return obj.find(key.c_str()) != obj.end() && obj[key.c_str()].is_object(); } } // namespace namespace OHOS { namespace Security { namespace Verify { void ParseType(const json& obj, ProvisionInfo& out) { string type; GetStringIfExist(obj, KEY_TYPE, type); /* If not release, then it's debug */ out.type = (type == VALUE_TYPE_RELEASE) ? ProvisionType::RELEASE : ProvisionType::DEBUG; } void ParseAppDistType(const json& obj, ProvisionInfo& out) { string distType; GetStringIfExist(obj, KEY_APP_DIST_TYPE, distType); if (distType == VALUE_DIST_TYPE_APP_GALLERY) { out.distributionType = AppDistType::APP_GALLERY; } else if (distType == VALUE_DIST_TYPE_ENTERPRISE) { out.distributionType = AppDistType::ENTERPRISE; } else if (distType == VALUE_DIST_TYPE_OS_INTEGRATION) { out.distributionType = AppDistType::OS_INTEGRATION; } else { out.distributionType = AppDistType::NONE_TYPE; } } void ParseBundleInfo(const json& obj, ProvisionInfo& out) { if (IsObjectExist(obj, KEY_BUNDLE_INFO)) { auto& bundleInfo = obj[KEY_BUNDLE_INFO]; GetStringIfExist(bundleInfo, KEY_DEVELOPER_ID, out.bundleInfo.developerId); GetStringIfExist(bundleInfo, KEY_DEVELOPMENT_CERTIFICATE, out.bundleInfo.developmentCertificate); GetStringIfExist(bundleInfo, KEY_DISTRIBUTION_CERTIFICATE, out.bundleInfo.distributionCertificate); GetStringIfExist(bundleInfo, KEY_BUNDLE_NAME, out.bundleInfo.bundleName); GetStringIfExist(bundleInfo, KEY_APP_FEATURE, out.bundleInfo.appFeature); } } void ParsePermissions(const json& obj, ProvisionInfo& out) { if (IsObjectExist(obj, KEY_PERMISSIONS)) { auto& permissions = obj[KEY_PERMISSIONS]; GetStringArrayIfExist(permissions, KEY_RESTRICTED_PERMISSIONS, out.permissions.restrictedPermissions); GetStringArrayIfExist(permissions, KEY_RESTRICTED_CAPABILITIES, out.permissions.restrictedCapabilities); } } void ParseDebugInfo(const json& obj, ProvisionInfo& out) { if (IsObjectExist(obj, KEY_DEBUG_INFO)) { GetStringIfExist(obj[KEY_DEBUG_INFO], KEY_DEVICE_ID_TYPE, out.debugInfo.deviceIdType); GetStringArrayIfExist(obj[KEY_DEBUG_INFO], KEY_DEVICE_IDS, out.debugInfo.deviceIds); } } void from_json(const json& obj, ProvisionInfo& out) { if (!obj.is_object()) { return; } GetInt32IfExist(obj, KEY_VERSION_CODE, out.versionCode); GetStringIfExist(obj, KEY_VERSION_NAME, out.versionName); GetStringIfExist(obj, KEY_UUID, out.uuid); ParseType(obj, out); ParseAppDistType(obj, out); ParseBundleInfo(obj, out); ParsePermissions(obj, out); ParseDebugInfo(obj, out); GetStringIfExist(obj, KEY_ISSUER, out.issuer); } #define RETURN_IF_STRING_IS_EMPTY(str, msg) \ if (str.empty()) { \ HAPVERIFY_LOG_ERROR(LABEL, msg); \ return PROVISION_INVALID; \ } #define RETURN_IF_INT_IS_NON_POSITIVE(num, msg) \ if (num <= 0) { \ HAPVERIFY_LOG_ERROR(LABEL, msg); \ return PROVISION_INVALID; \ } AppProvisionVerifyResult ParseProvision(const string& appProvision, ProvisionInfo& info) { json obj = json::parse(appProvision, nullptr, false); if (!obj.is_structured()) { HAPVERIFY_LOG_ERROR(LABEL, "Parsing appProvision failed. json: %{public}s", appProvision.c_str()); return PROVISION_INVALID; } obj.get_to(info); RETURN_IF_INT_IS_NON_POSITIVE(info.versionCode, "Tag version code is empty.") RETURN_IF_STRING_IS_EMPTY(info.versionName, "Tag version name is empty.") RETURN_IF_STRING_IS_EMPTY(info.uuid, "Tag uuid is empty.") RETURN_IF_STRING_IS_EMPTY(info.bundleInfo.developerId, "Tag developer-id is empty.") if (info.type == ProvisionType::DEBUG) { RETURN_IF_STRING_IS_EMPTY(info.bundleInfo.developmentCertificate, "Tag development-certificate is empty.") } else if (info.type == ProvisionType::RELEASE) { RETURN_IF_INT_IS_NON_POSITIVE(info.distributionType, "Tag app-distribution-type is empty.") RETURN_IF_STRING_IS_EMPTY(info.bundleInfo.distributionCertificate, "Tag distribution-certificate is empty.") } RETURN_IF_STRING_IS_EMPTY(info.bundleInfo.bundleName, "Tag bundle-name is empty.") if (info.bundleInfo.bundleName == GENERIC_BUNDLE_NAME) { HAPVERIFY_LOG_DEBUG(LABEL, "generic package name: %{public}s, is used.", GENERIC_BUNDLE_NAME.c_str()); } RETURN_IF_STRING_IS_EMPTY(info.bundleInfo.appFeature, "Tag app-feature is empty.") return PROVISION_OK; } inline bool CheckDeviceID(const std::vector<std::string>& deviceIds, const string& deviceId) { auto iter = find(deviceIds.begin(), deviceIds.end(), deviceId); if (iter == deviceIds.end()) { DeviceTypeManager& deviceTypeManager = DeviceTypeManager::GetInstance(); if (!deviceTypeManager.GetDeviceTypeInfo()) { HAPVERIFY_LOG_ERROR(LABEL, "current device is not authorized"); return false; } HAPVERIFY_LOG_INFO(LABEL, "current device is a debug device"); } return true; } AppProvisionVerifyResult CheckDeviceID(ProvisionInfo& info) { // Checking device ids if (info.debugInfo.deviceIds.empty()) { HAPVERIFY_LOG_ERROR(LABEL, "device-id list is empty."); return PROVISION_DEVICE_UNAUTHORIZED; } if (info.debugInfo.deviceIds.size() > MAXIMUM_NUM_DEVICES) { HAPVERIFY_LOG_ERROR(LABEL, "No. of device IDs in list exceed maximum number %{public}d", MAXIMUM_NUM_DEVICES); return PROVISION_NUM_DEVICE_EXCEEDED; } if (info.debugInfo.deviceIdType != VALUE_DEVICE_ID_TYPE_UDID) { HAPVERIFY_LOG_ERROR(LABEL, "type of device ID is not supported."); return PROVISION_UNSUPPORTED_DEVICE_TYPE; } string deviceId; #ifndef STANDARD_SYSTEM int32_t ret = OHOS::AccountSA::OhosAccountKits::GetInstance().GetUdid(deviceId); if (ret != 0) { HAPVERIFY_LOG_ERROR(LABEL, "obtaining current device id failed (%{public}d).", ret); return PROVISION_DEVICE_UNAUTHORIZED; } #else char udid[DEV_UUID_LEN] = {0}; int ret = GetDevUdid(udid, sizeof(udid)); if (ret != EC_SUCCESS) { HAPVERIFY_LOG_ERROR(LABEL, "obtaining current device id failed (%{public}d).", static_cast<int>(ret)); return PROVISION_DEVICE_UNAUTHORIZED; } deviceId = std::string(udid, sizeof(udid) - 1); HAPVERIFY_LOG_INFO(LABEL, "L2 UDID:%{public}s, len:%{public}d.", deviceId.c_str(), static_cast<int>(deviceId.size())); #endif // STANDARD_SYSTEM if (deviceId.empty()) { HAPVERIFY_LOG_ERROR(LABEL, "device-id of current device is empty."); return PROVISION_DEVICE_UNAUTHORIZED; } if (!CheckDeviceID(info.debugInfo.deviceIds, deviceId)) { return PROVISION_DEVICE_UNAUTHORIZED; } return PROVISION_OK; } AppProvisionVerifyResult ParseAndVerify(const string& appProvision, ProvisionInfo& info) { HAPVERIFY_LOG_DEBUG(LABEL, "Enter HarmonyAppProvision Verify"); AppProvisionVerifyResult ret = ParseProvision(appProvision, info); if (ret != PROVISION_OK) { return ret; } if (info.type == ProvisionType::DEBUG) { ret = CheckDeviceID(info); if (ret != PROVISION_OK) { return ret; } } HAPVERIFY_LOG_DEBUG(LABEL, "Leave HarmonyAppProvision Verify"); return PROVISION_OK; } } // namespace Verify } // namespace Security } // namespace OHOS
38.083916
119
0.690231
openharmony-sig-ci
4870bf9cce956d43eb016bd3a7837e052da96f34
2,421
cxx
C++
main/sfx2/source/view/viewfac.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sfx2/source/view/viewfac.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sfx2/source/view/viewfac.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" // INCLUDE --------------------------------------------------------------- #include <sfx2/app.hxx> #include "sfx2/viewfac.hxx" #include <rtl/ustrbuf.hxx> // STATIC DATA ----------------------------------------------------------- DBG_NAME(SfxViewFactory) SfxViewShell *SfxViewFactory::CreateInstance(SfxViewFrame *pFrame, SfxViewShell *pOldSh ) { DBG_CHKTHIS(SfxViewFactory, 0); return (*fnCreate)(pFrame, pOldSh); } void SfxViewFactory::InitFactory() { DBG_CHKTHIS(SfxViewFactory, 0); (*fnInit)(); } String SfxViewFactory::GetLegacyViewName() const { ::rtl::OUStringBuffer aViewName; aViewName.appendAscii( "view" ); aViewName.append( sal_Int32( GetOrdinal() ) ); return aViewName.makeStringAndClear(); } String SfxViewFactory::GetAPIViewName() const { if ( m_sViewName.Len() > 0 ) return m_sViewName; if ( GetOrdinal() == 0 ) return String::CreateFromAscii( "Default" ); return GetLegacyViewName(); } // CTOR / DTOR ----------------------------------------------------------- SfxViewFactory::SfxViewFactory( SfxViewCtor fnC, SfxViewInit fnI, sal_uInt16 nOrdinal, const sal_Char* asciiViewName ): fnCreate(fnC), fnInit(fnI), nOrd(nOrdinal), m_sViewName( String::CreateFromAscii( asciiViewName ) ) { DBG_CTOR(SfxViewFactory, 0); } SfxViewFactory::~SfxViewFactory() { DBG_DTOR(SfxViewFactory, 0); }
28.482353
89
0.634449
Grosskopf
4873198941398e47541c9e774b6fff48481642ae
14,644
cpp
C++
CFD/src/solver.cpp
CompilerLuke/NextEngine
aa1a8e9d9370bce004dba00854701597cab74989
[ "MIT" ]
1
2021-09-10T18:19:16.000Z
2021-09-10T18:19:16.000Z
CFD/src/solver.cpp
CompilerLuke/NextEngine
aa1a8e9d9370bce004dba00854701597cab74989
[ "MIT" ]
null
null
null
CFD/src/solver.cpp
CompilerLuke/NextEngine
aa1a8e9d9370bce004dba00854701597cab74989
[ "MIT" ]
2
2020-04-02T06:46:56.000Z
2021-06-17T16:47:57.000Z
#include "solver.h" #include "engine/handle.h" #include "core/memory/linear_allocator.h" #include "visualization/debug_renderer.h" #include "visualization/color_map.h" #include "vendor/eigen/Eigen/Sparse" #include "vendor/eigen/Eigen/IterativeLinearSolvers" using vec_x = Eigen::VectorXd; using SparseMt = Eigen::SparseMatrix<real>; using T = Eigen::Triplet<real>; Eigen::Vector3d to(vec3 vec) { return Eigen::Vector3d(vec.x, vec.y, vec.z); } vec3 from(Eigen::Vector3d vec) { return vec3(vec[0], vec[1], vec[2]); } struct Face { real area; real dx; vec3 normal; real parallel; vec3 ortho; uint cell1, cell2; }; struct BoundaryFace { real area; real dx; vec3 normal; uint cell; }; struct PressureBoundaryFace { real area; real dx; vec3 normal; real pressure; uint cell; }; struct Simulation { CFDDebugRenderer& debug; uint num_cells; vector<Face> faces; vector<BoundaryFace> boundary_faces; vector<PressureBoundaryFace> pressure_boundary_faces; SparseMt sparse_matrix; vec_x source_term; vector<T> coeffs; vector<Eigen::Matrix3d> velocity_gradients; vector<Eigen::Vector3d> pressure_gradients; vector<vec3> centers; vector<real> volumes; vec_x vel_and_pressure; vector<vec3> velocities_numer; vector<vec3> velocities_denom; }; real triangle_area(vec3 v[3]) { vec3 v01 = v[1] - v[0]; vec3 v02 = v[2] - v[0]; return length(cross(v01, v02))/2.0f; } real quad_area(vec3 v[4]) { vec3 v0[3] = {v[0], v[1], v[2]}; vec3 v1[3] = { v[0], v[2], v[3] }; return triangle_area(v0) + triangle_area(v1); } void right_angle_corrector(vec3 normal, vec3 to_center, real* parallel, vec3* ortho) { to_center = normalize(to_center); *parallel = dot(normal, to_center); *ortho = normal - to_center*(*parallel); } uint EQ = 4; uint VAR = 4; Simulation make_simulation(CFDVolume& mesh, CFDDebugRenderer& debug) { Simulation result{ debug }; result.num_cells = mesh.cells.length; result.centers.resize(result.num_cells); result.volumes.resize(result.num_cells); result.velocities_numer.resize(result.num_cells); result.velocities_denom.resize(result.num_cells); result.velocity_gradients.resize(result.num_cells); result.pressure_gradients.resize(result.num_cells); result.vel_and_pressure.resize(VAR * result.num_cells); result.sparse_matrix.resize(EQ * result.num_cells, VAR * result.num_cells); for (uint i = 0; i < mesh.cells.length; i++) { const CFDCell& cell = mesh.cells[i]; const ShapeDesc& shape = shapes[cell.type]; uint cell_id = i; vec3 center = compute_centroid(mesh, cell.vertices, shape.num_verts); result.centers[i] = center; real volume = 0.0f; for (uint f = 0; f < shape.num_faces; f++) { const ShapeDesc::Face& face = shape[f]; vec3 face_center; vec3 v[4]; for (uint j = 0; j < face.num_verts; j++) { v[j] = mesh.vertices[cell.vertices[face[j]].id].position; face_center += v[j]; } face_center /= face.num_verts; bool is_quad = face.num_verts == 4; vec3 normal = is_quad ? quad_normal(v) : triangle_normal(v); real area = is_quad ? quad_area(v) : triangle_area(v); cell_handle neighbor = cell.faces[f].neighbor; bool boundary = neighbor.id == -1; volume += area * dot(face_center, normal); if (boundary) { draw_line(debug, face_center, face_center + 0.05*normal, vec4(0,0,0,1)); real dx = 1.0 / (2.0*length(face_center - center)); if (cell.faces[f].pressure_grad != 0.0f) { result.pressure_boundary_faces.append(PressureBoundaryFace{ area, dx, normal, cell.faces[f].pressure_grad, cell_id }); } else { result.boundary_faces.append(BoundaryFace{ area, dx, normal, cell_id }); } } else if (neighbor.id > cell_id) { vec3 center_plus = compute_centroid(mesh, mesh[neighbor].vertices, 8); vec3 center_minus = center; vec3 t = center_plus - center_minus; real ratio = dot(t, normal) / length(t); result.faces.append(Face{area, 0, normal * ratio, 0, 0, cell_id, (uint)neighbor.id}); } } volume /= 3; result.volumes[cell_id] = volume; } for (Face& face : result.faces) { vec3 center_minus = result.centers[face.cell1]; vec3 center_plus = result.centers[face.cell2]; face.dx = 1.0 / length(center_plus - center_minus); right_angle_corrector(face.normal, center_plus - center_minus, &face.parallel, &face.ortho); } for (uint i = 0; i < result.num_cells; i++) { result.vel_and_pressure(i*4 + 0) = 0; result.vel_and_pressure(i*4 + 1) = 0; result.vel_and_pressure(i*4 + 2) = 0; result.vel_and_pressure(i*4 + 3) = 1.0; } suspend_execution(debug); return result; } vec3 get_velocity(Simulation& simulation, uint cell) { vec3 result; result.x = simulation.vel_and_pressure(cell * VAR + 0); result.y = simulation.vel_and_pressure(cell * VAR + 1); result.z = simulation.vel_and_pressure(cell * VAR + 2); return result; }; real get_pressure(Simulation& simulation, uint cell) { return simulation.vel_and_pressure[cell * VAR + 3]; }; Eigen::Matrix3d get_velocity_gradient(Simulation& simulation, uint cell) { return simulation.velocity_gradients[cell]; } vec3 get_pressure_gradient(Simulation& simulation, uint cell) { return from(simulation.pressure_gradients[cell]); } void compute_gradients(Simulation& simulation) { auto& velocity_gradients = simulation.velocity_gradients; auto& pressure_gradients = simulation.pressure_gradients; for (uint i = 0; i < simulation.num_cells; i++) { velocity_gradients[i].fill(0.0f); pressure_gradients[i].fill(0.0f); } for (Face f : simulation.faces) { vec3 velocity_down = get_velocity(simulation, f.cell1); vec3 velocity_up = get_velocity(simulation, f.cell2); vec3 velocity = (velocity_down + velocity_up) / 2; real pressure_down = get_pressure(simulation, f.cell1); real pressure_up = get_pressure(simulation, f.cell1); real pressure = (pressure_down + pressure_up) / 2; Eigen::Vector3d _velocity(velocity.x, velocity.y, velocity.z); Eigen::Vector3d normal(f.normal.x, f.normal.y, f.normal.z); normal *= f.area; Eigen::Matrix3d vel_gradient = _velocity * normal.transpose(); Eigen::Vector3d pressure_gradient = pressure * normal; velocity_gradients[f.cell1] += vel_gradient; pressure_gradients[f.cell1] += pressure_gradient; velocity_gradients[f.cell2] -= vel_gradient; pressure_gradients[f.cell2] -= pressure_gradient; } for (BoundaryFace f : simulation.boundary_faces) { Eigen::Vector3d normal(f.normal.x, f.normal.y, f.normal.z); normal *= f.area; real pressure = get_pressure(simulation, f.cell); pressure_gradients[f.cell] += pressure * normal; } for (PressureBoundaryFace f : simulation.pressure_boundary_faces) { Eigen::Vector3d velocity = to(get_velocity(simulation, f.cell)); Eigen::Vector3d normal = to(f.normal) * f.area; real pressure = get_pressure(simulation, f.cell); velocity_gradients[f.cell] += velocity * normal.transpose(); pressure_gradients[f.cell] += pressure * normal; } for (uint i = 0; i < simulation.num_cells; i++) { velocity_gradients[i] /= simulation.volumes[i]; pressure_gradients[i] /= simulation.volumes[i]; } } void build_coupled_matrix(Simulation& simulation) { vector<T>& coeffs = simulation.coeffs; vec_x& source = simulation.source_term; coeffs.clear(); source.resize(simulation.num_cells * EQ); source.fill(0); //momentum U coefficient auto m_U = [&](uint n, uint m, vec3 coeff) { coeffs.append(T(n*EQ + 0, m*VAR + 0, coeff.x)); coeffs.append(T(n*EQ + 1, m*VAR + 1, coeff.y)); coeffs.append(T(n*EQ + 2, m*VAR + 2, coeff.z)); }; auto m_U_dot = [&](uint n, uint m, vec3 coeff) { for (uint i = 0; i < 3; i++) { for (uint j = 0; j < 3; j++) { coeffs.append(T(n * EQ + i, m * VAR + j, coeff[j])); } } }; auto m_S = [&](uint cell, vec3 value) { source[cell * EQ + 0] += value.x; source[cell * EQ + 1] += value.y; source[cell * EQ + 2] += value.z; }; //momentum P coefficient auto m_P = [&](uint c, uint n, vec3 coeff) { coeffs.append(T(c*EQ + 0, n*VAR + 3, coeff.x)); coeffs.append(T(c*EQ + 1, n*VAR + 3, coeff.y)); coeffs.append(T(c*EQ + 2, n*VAR + 3, coeff.z)); }; //pressure U coefficient, dot product auto p_U = [&](uint n, uint m, vec3 coeff) { coeffs.append(T(n*EQ + 3, m*VAR + 0, coeff.x)); coeffs.append(T(n*EQ + 3, m*VAR + 1, coeff.y)); coeffs.append(T(n*EQ + 3, m*VAR + 2, coeff.z)); }; auto p_S = [&](uint c, real value) { source[c*EQ + 3] += value; }; //pressure auto p_P = [&](uint n, uint m, real coeff) { coeffs.append(T(n*EQ + 3, m*VAR + 3, coeff)); }; auto& vel_and_pressure = simulation.vel_and_pressure; real rho = 1; real mu = 1; auto face_contribution = [&](uint cell, uint neigh, vec3 vel_down, vec3 vel_up, vec3 normal, real parallel, vec3 ortho, real area, real dx) { vec3 anormal = normal * area; vec3 pressure_gradient_down = get_pressure_gradient(simulation, cell); vec3 pressure_gradient_up = get_pressure_gradient(simulation, neigh); Eigen::Matrix3d vel_gradient_down = get_velocity_gradient(simulation,cell); Eigen::Matrix3d vel_gradient_up = get_velocity_gradient(simulation, neigh); vec3 vel_face = (vel_up + vel_down) / 2.0f; Eigen::Matrix3d vel_gradient_face = (vel_gradient_down + vel_gradient_up) / 2; vec3 pressure_gradient_face = (pressure_gradient_down + pressure_gradient_up) / 2; real conv_coeff = rho * dot(vel_face, anormal); /* Eigen::Vector3d _anormal = to(anormal); vec3 div_coeff; div_coeff.x = vel_gradient_face.col(0).dot(_anormal); div_coeff.y = vel_gradient_face.col(1).dot(_anormal); div_coeff.z = vel_gradient_face.col(2).dot(_anormal); */ vec3 div_coeff = from(vel_gradient_face.transpose() * to(anormal)); auto& coef = coeffs; p_U(cell, cell, 10*0.5*anormal); p_U(cell, neigh, 10*0.5*anormal); //convective acceleration m_U(cell, neigh, 0.5*conv_coeff); m_U(cell, cell, 0.5*conv_coeff); //pressure source m_P(cell, neigh, 0.5 * anormal); m_P(cell, cell, 0.5 * anormal); //velocity gradient m_U(cell, neigh, -area * mu * dx * parallel); m_U(cell, cell, area * mu * dx * parallel); //orthogonal corrector m_S(cell, -area * mu * from(vel_gradient_face * to(ortho))); //pressure gradient p_P(cell, neigh, area * dx * parallel); p_P(cell, cell, -area * dx * parallel); //orthogonal corrector p_S(cell, -area * dot(pressure_gradient_face, ortho)); //velocity divergence source p_U(cell, neigh, 0.5 * rho * div_coeff); p_U(cell, cell, 0.5 * rho * div_coeff); }; bool first = false; for (const Face& face : simulation.faces) { vec3 vel_down = get_velocity(simulation, face.cell1); vec3 vel_up = get_velocity(simulation, face.cell2); face_contribution(face.cell1, face.cell2, vel_down, vel_up, face.normal, face.parallel, face.ortho, face.area, face.dx); face_contribution(face.cell2, face.cell1, vel_up, vel_down, -face.normal, face.parallel, -face.ortho, face.area, face.dx); } for (const BoundaryFace& face : simulation.boundary_faces) { uint cell = face.cell; real area = face.area; real dx = face.dx; vec3 anormal = face.normal * area; vec3 vel = get_velocity(simulation, cell); m_P(cell, cell, anormal); m_U(cell, cell, 2 * area * mu * dx); } for (const PressureBoundaryFace& face : simulation.pressure_boundary_faces) { uint cell = face.cell; real area = face.area; real dx = face.dx; vec3 anormal = face.normal * area; vec3 vel_face = get_velocity(simulation, cell); p_U(cell, cell, 10*anormal); m_U(cell, cell, rho * dot(vel_face, anormal)); m_S(cell, -face.pressure * anormal); p_P(cell, cell, area * -2 * dx); source[cell*4 + 3] -= area * 2 * face.pressure * dx; } simulation.sparse_matrix.setFromTriplets(coeffs.begin(), coeffs.end()); } #include <iostream> void solve_coupled_matrix(Simulation& simulation, bool first) { Eigen::BiCGSTAB<Eigen::SparseMatrix<real>> solver; solver.compute(simulation.sparse_matrix); std::cout << simulation.sparse_matrix << std::endl; std::cout << simulation.source_term << std::endl; if (first) { simulation.vel_and_pressure = solver.solve(simulation.source_term); } else { simulation.vel_and_pressure = solver.solveWithGuess(simulation.source_term, simulation.vel_and_pressure); } std::cout << "Solution" << std::endl; std::cout << simulation.vel_and_pressure << std::endl; } void draw_simulation_state(Simulation& simulation, bool show_velocity, bool show_pressure) { CFDDebugRenderer& debug = simulation.debug; clear_debug_stack(debug); float max_pressure = 0.0f; float max_velocity = 0.0f; for (uint i = 0; i < simulation.num_cells; i++) { vec3 vel = get_velocity(simulation, i); real pressure = get_pressure(simulation, i); max_pressure = fmaxf(max_pressure, pressure); max_velocity = fmaxf(max_velocity, length(vel)); } std::cout << "Max velocity! " << max_velocity << std::endl; std::cout << "Max pressure! " << max_pressure << std::endl; if (show_velocity) { for (uint i = 0; i < simulation.num_cells; i += 1) { vec3 c = simulation.centers[i]; vec3 u = get_velocity(simulation, i); vec3 t = normalize(u); vec3 n = vec3(0, 1, 0); vec3 b = normalize(cross(t, n)); vec4 color = color_map(length(u), 0, max_velocity); real l = 0.3*length(u)/max_velocity; vec3 start = c - t * l / 2; vec3 end = c + t * l / 2; float arrow = 0.1 * l; draw_line(debug, start, end, color); draw_line(debug, end, end + (n-t)*arrow, color); draw_line(debug, end, end + (-n-t)*arrow, color); } } if (show_pressure) { for (uint i = 0; i < simulation.num_cells; i += 1) { vec3 c = simulation.centers[i]; real p = get_pressure(simulation, i); real arrow = 0.1; vec4 color = color_map(p, 0, max_pressure); draw_line(debug, c + vec3(-arrow, 0, 0), c + vec3(arrow, 0, 0), color); draw_line(debug, c + vec3(0, -arrow, 0), c + vec3(0, arrow, 0), color); draw_line(debug, c + vec3(0, 0, -arrow), c + vec3(0, 0, arrow), color); } } } CFDResults simulate(CFDVolume& volume, CFDDebugRenderer& debug) { Simulation simulation = make_simulation(volume, debug); CFDResults result; uint n = 20; for (uint i = 0; i < n; i++) { printf("Iteration %i, (%ix%i)\n", i, simulation.num_cells * 4, simulation.num_cells * 4); compute_gradients(simulation); build_coupled_matrix(simulation); solve_coupled_matrix(simulation, i == 0); draw_simulation_state(simulation, true, false); suspend_execution(debug); draw_simulation_state(simulation, false, true); suspend_execution(debug); } //result.velocities = std::move(simulation.velocities); //result.pressures = std::move(simulation.pressures); return result; }
28.99802
142
0.687449
CompilerLuke
4877611196a94063f1ece7284bfc9989486d7d8a
5,196
cc
C++
nodejs-mobile/deps/chakrashim/src/v8propertydescriptor.cc
xuelongqy/cnode
ac256264d329e68b6c5ae3281b0e7bb5a95ae164
[ "MIT" ]
null
null
null
nodejs-mobile/deps/chakrashim/src/v8propertydescriptor.cc
xuelongqy/cnode
ac256264d329e68b6c5ae3281b0e7bb5a95ae164
[ "MIT" ]
4
2020-03-13T14:45:49.000Z
2020-03-15T16:31:22.000Z
nodejs-mobile/deps/chakrashim/src/v8propertydescriptor.cc
xuelongqy/cnode
ac256264d329e68b6c5ae3281b0e7bb5a95ae164
[ "MIT" ]
1
2020-03-15T16:02:18.000Z
2020-03-15T16:02:18.000Z
// Copyright Microsoft. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and / or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include "v8chakra.h" namespace v8 { struct PropertyDescriptor::PrivateData { PrivateData() : enumerable(false), has_enumerable(false), configurable(false), has_configurable(false), writable(false), has_writable(false), value(JS_INVALID_REFERENCE), get(JS_INVALID_REFERENCE), set(JS_INVALID_REFERENCE) {} bool has_value() { return value != JS_INVALID_REFERENCE; } bool has_get() { return get != JS_INVALID_REFERENCE; } bool has_set() { return set != JS_INVALID_REFERENCE; } bool enumerable : 1; bool has_enumerable : 1; bool configurable : 1; bool has_configurable : 1; bool writable : 1; bool has_writable : 1; JsValueRef value; JsValueRef get; JsValueRef set; }; PropertyDescriptor::PropertyDescriptor() : private_(new PrivateData()) {} PropertyDescriptor::PropertyDescriptor(Local<Value> value) : private_(new PrivateData()) { private_->value = reinterpret_cast<JsValueRef>(*value); if (private_->value != JS_INVALID_REFERENCE) { JsAddRef(private_->value, nullptr); } } PropertyDescriptor::PropertyDescriptor(Local<Value> value, bool writable) : private_(new PrivateData()) { private_->value = reinterpret_cast<JsValueRef>(*value); if (private_->value != JS_INVALID_REFERENCE) { JsAddRef(private_->value, nullptr); } private_->has_writable = true; private_->writable = writable; } PropertyDescriptor::PropertyDescriptor(Local<Value> get, Local<Value> set) : private_(new PrivateData()) { CHAKRA_ASSERT(get.IsEmpty() || get->IsUndefined() || get->IsFunction()); CHAKRA_ASSERT(set.IsEmpty() || set->IsUndefined() || set->IsFunction()); private_->get = reinterpret_cast<JsValueRef>(*get); private_->set = reinterpret_cast<JsValueRef>(*set); if (private_->get != JS_INVALID_REFERENCE) { JsAddRef(private_->get, nullptr); } if (private_->set != JS_INVALID_REFERENCE) { JsAddRef(private_->set, nullptr); } } PropertyDescriptor & PropertyDescriptor::operator=(PropertyDescriptor && other) { private_ = other.private_; other.private_ = nullptr; return* this; } PropertyDescriptor::~PropertyDescriptor() { if (private_ == nullptr) { return; } if (private_->value != JS_INVALID_REFERENCE) { JsRelease(private_->value, nullptr); } if (private_->get != JS_INVALID_REFERENCE) { JsRelease(private_->get, nullptr); } if (private_->set != JS_INVALID_REFERENCE) { JsRelease(private_->set, nullptr); } delete private_; } Local<Value> PropertyDescriptor::value() const { CHAKRA_ASSERT(private_->has_value()); return Local<Value>::New(private_->value); } Local<Value> PropertyDescriptor::get() const { return Local<Value>::New(private_->get); } Local<Value> PropertyDescriptor::set() const { return Local<Value>::New(private_->set); } bool PropertyDescriptor::has_value() const { return private_->has_value(); } bool PropertyDescriptor::has_get() const { return private_->has_get(); } bool PropertyDescriptor::has_set() const { return private_->has_set(); } bool PropertyDescriptor::writable() const { CHAKRA_ASSERT(private_->has_writable); return private_->writable; } bool PropertyDescriptor::has_writable() const { return private_->has_writable; } void PropertyDescriptor::set_enumerable(bool enumerable) { private_->has_enumerable = true; private_->enumerable = enumerable; } bool PropertyDescriptor::enumerable() const { CHAKRA_ASSERT(private_->has_enumerable); return private_->enumerable; } bool PropertyDescriptor::has_enumerable() const { return private_->has_enumerable; } void PropertyDescriptor::set_configurable(bool configurable) { private_->has_configurable = true; private_->configurable = configurable; } bool PropertyDescriptor::configurable() const { CHAKRA_ASSERT(private_->has_configurable); return private_->configurable; } bool PropertyDescriptor::has_configurable() const { return private_->has_configurable; } } // namespace v8
30.209302
80
0.71863
xuelongqy
4879704b1b035e0e4ed35ca52bb52035c93c3cd5
42,526
cpp
C++
TBDAnnotation/src/TBDAnnotation.cpp
marcorighini/tbdannotation
f22d395fce5c6c1007177623b0a0c60f7fcb9d4f
[ "Apache-2.0" ]
1
2021-06-13T10:49:43.000Z
2021-06-13T10:49:43.000Z
TBDAnnotation/src/TBDAnnotation.cpp
marcorighini/tbdannotation
f22d395fce5c6c1007177623b0a0c60f7fcb9d4f
[ "Apache-2.0" ]
null
null
null
TBDAnnotation/src/TBDAnnotation.cpp
marcorighini/tbdannotation
f22d395fce5c6c1007177623b0a0c60f7fcb9d4f
[ "Apache-2.0" ]
null
null
null
#include "Model/Page.hpp" #include "Model/Utils.hpp" #include "Model/DatabaseHandler.hpp" #include "Model/RegisteredPdfMap.hpp" #include "Model/FileManager.hpp" #include "Model/ImageProcessor.hpp" #include "Model/Triangle.hpp" #include "Model/FeaturesManager.hpp" #include "Model/WebCamCapture.hpp" #include <iostream> #include "Model/ProgramOptions.hpp" #include "Model/StateMachine/StateMachine.hpp" #include "Model/StateMachine/ExitState.hpp" #include "Model/StateMachine/PageDiscovering.hpp" #include "Model/StateMachine/MachineEvents.hpp" #include "Model/StateMachine/PageRetrieval.hpp" #include "Model/StateMachine/PageTracking.hpp" #include "Model/StateMachine/PageError.hpp" #include "Model/StateMachine/PageAnnotation.hpp" #include "Model/StateMachine/PdfCreation.hpp" #include <thread> #include <X11/Xlib.h> #include <vector> int main(int argc, char** argv) { //##############################################################################// // PROGRAM OPTIONS //##############################################################################// // Program options variables string appName = "TBDAnnotation"; string subcommand; string documentsPathString, outputPathString, datasetPathString; int nSets = 1; uint nRetained = 1; string pageNameString; string calibrationPathString; bool calibrationSupplied = false; // Help string std::string subcommandDesc = std::string("subcommand to execute: calibrate, register, annotate, test"); std::string helpDesc = std::string("print usage messages\n"); std::string documentsPathDesc = std::string("path to pdf documents"); std::string outputPathDesc = std::string("output files directory"); std::string datasetPathDesc = std::string("dataset files directory"); std::string nSetsDesc = std::string( "number of datasets. The i-th dataset has size i*nPages/nSets. Optional, default=1"); std::string nRetainedDesc = std::string( "number of same pages that will be present in every dataset. Required if nSets is setted"); std::string pageNameDesc = std::string("name of page to retrieve. Required if test mode enabled"); std::string calibrationPathDesc = std::string("calibration file path. Optional"); // Usage string usageFirstLine = "\nUsage:\n" "TBDAnnotation calibrate [-h] [--output CALIBRATION_OUTPUT_PATH] \n" "TBDAnnotation register [-h] [--documents DOCUMENTS_PATH] [--output DATASET_OUTPUT_PATH] [--nSets N_SETS] [--nRetained N_RETAINED]\n" "TBDAnnotation annotate [-h] [--dataset DATASET_PATH] [--output PDF_OUTPUT_PATH] [--calibration CALIBRATION_FILE]\n" "TBDAnnotation test [-h] [--dataset DATASET_PATH] [--pageName PAGE_NAME] \n\n"; po::options_description desc(usageFirstLine, 120); // Options desc.add_options()("help,h", helpDesc.c_str())("documents", po::value(&documentsPathString), documentsPathDesc.c_str())("output", po::value(&outputPathString), outputPathDesc.c_str())("nSets", po::value(&nSets), nSetsDesc.c_str())("nRetained", po::value(&nRetained), nRetainedDesc.c_str())("dataset", po::value(&datasetPathString), datasetPathDesc.c_str())("pageName", po::value(&pageNameString), pageNameDesc.c_str())("calibration", po::value(&calibrationPathString), calibrationPathDesc.c_str())( "subcommand", po::value<string>(&subcommand)->required(), subcommandDesc.c_str()); po::positional_options_description positionalOptions; positionalOptions.add("subcommand", 1); po::variables_map vm; try { // Parse command line po::store(po::command_line_parser(argc, argv).options(desc).positional(positionalOptions).run(), vm); if (vm.count("help") || argc == 1) { std::cout << usageFirstLine; po::OptionPrinter::printParametersDesc(appName, std::cout, desc, &positionalOptions); } // Handle valid subcommands and required options vector<string> subcommands; subcommands.push_back("calibrate"); subcommands.push_back("register"); subcommands.push_back("annotate"); subcommands.push_back("test"); po::validate_subcommands(vm, "subcommand", subcommands); vector<string> subcommand_calibrate_dependencies; subcommand_calibrate_dependencies.push_back("output"); vector<string> subcommand_register_dependencies; subcommand_register_dependencies.push_back("documents"); subcommand_register_dependencies.push_back("output"); vector<string> subcommand_annotate_dependencies; subcommand_annotate_dependencies.push_back("dataset"); subcommand_annotate_dependencies.push_back("output"); vector<string> subcommand_test_dependencies; subcommand_test_dependencies.push_back("dataset"); subcommand_test_dependencies.push_back("pageName"); po::subcommand_option_dependency(vm, "subcommand", "calibrate", subcommand_calibrate_dependencies); po::subcommand_option_dependency(vm, "subcommand", "register", subcommand_register_dependencies); po::subcommand_option_dependency(vm, "subcommand", "annotate", subcommand_annotate_dependencies); po::subcommand_option_dependency(vm, "subcommand", "test", subcommand_test_dependencies); po::notify(vm); if (nSets > 1) { po::option_dependency(vm, "nSets", "nRetained"); } po::notify(vm); // nSets cannot be zero or negative if (nSets < 1) { throw std::logic_error(std::string("Option nSets cannot be zero or negative.")); } // nRetained cannot be zero or negative if (nRetained < 1) { throw std::logic_error(std::string("Option nRetained cannot be zero or negative.")); } // Check if calibration is supplied if (vm.count("calibration")) { calibrationSupplied = true; } } catch (std::exception& e) { std::cerr << e.what() << "\n"; return 0; } /**********************************************************************************************************/ /**********************************************************************************************************/ if (vm["subcommand"].as<string>().compare("calibrate") == 0) { //##############################################################################// // CALIBRATION //##############################################################################// string destinationPath(outputPathString); stringstream filename; filename << destinationPath << Parameters::ANNOTATIONS_THRESHOLD_FILENAME; FileStorage fs(filename.str(), FileStorage::WRITE); if (!fs.isOpened()) { std::cerr << "ERROR: Can't create file \"" << filename.str() << "\"" << "\n"; return 0; } VideoCapture cap(0); bool drawRectangleOnTruth = true; // Instructions cout << "\nPlease, align a completely white sheet into the green rectangle and then\n" "draw a line (or whatever is enough visible) into each red rectangle.\n" "Then you have to put your hand in the second half of the window, below the green line.\n" "In the same area, draw some black lines for text simulation.\n" "Finally, don't forget to leave visible some part of the background (desk\n" "or something else) out of the green boundary.\n" "Take a look to the \"Truth\" window: the goal is to view only lines in the red rectangles.\n" "\"Truth\" is the mask that the algorithm will try to replicate (note that \"Truth\"\n" "is given in grayscale mode thanks to the absence of text).\n" "\n" "Press 's' to start searching...\n" "Press 't' to toggle rectangle draw in \"Truth\" window...\n" "Press 'Esc' to quit...\n"; for (;;) { Mat frame; cap >> frame; ImageProcessor::adjustWebCamImage(frame, Parameters::SELECTED_WEB_CAM_ORIENTATION); Mat frameGray = frame.clone(); cvtColor(frameGray, frameGray, CV_BGR2GRAY); // ############################################################# // // Truth definition section Mat adaptiveThresh; adaptiveThreshold(frameGray, adaptiveThresh, Parameters::THRESHOLD_MAX_VALUE, CV_ADAPTIVE_THRESH_GAUSSIAN_C, CV_THRESH_BINARY, Parameters::ADAPTIVE_THRESHOLD_BLOCK_SIZE, Parameters::ADAPTIVE_THRESHOLD_CONSTANT); Mat element = getStructuringElement(Parameters::MORPH_SE_SHAPE, Size(3, 3), Point(1, 1)); morphologyEx(adaptiveThresh, adaptiveThresh, MORPH_CLOSE, element); Mat truth = adaptiveThresh.clone(); // Clean up for (int i = 0; i < truth.rows; i++) { for (int j = 0; j < truth.cols; j++) { if (!(i >= Parameters::BOUNDARY_MARGIN && i <= truth.rows / 2 && j >= Parameters::BOUNDARY_MARGIN && j <= truth.cols - Parameters::BOUNDARY_MARGIN)) { truth.at<uchar>(i, j) = 255; } } } // Truth: white foreground truth = 255 - truth; // ###################################################### // Rectangles definition section // Page boundary rectangle Rect boundaryRect(Point(Parameters::BOUNDARY_MARGIN, Parameters::BOUNDARY_MARGIN), Point(frame.cols - Parameters::BOUNDARY_MARGIN, frame.rows - Parameters::BOUNDARY_MARGIN)); // Left rectangle int rectangleSxWidth = 50; Rect annotationRectSX( Point(Parameters::BOUNDARY_MARGIN * 2, (frame.rows / 2 - Parameters::BOUNDARY_MARGIN) / 4 + Parameters::BOUNDARY_MARGIN), Point(Parameters::BOUNDARY_MARGIN * 2 + rectangleSxWidth, (frame.rows / 2 - Parameters::BOUNDARY_MARGIN) * 3. / 4 + Parameters::BOUNDARY_MARGIN)); // Right rectangle int rectangleDxWidth = 50; Rect annotationRectDX( Point(frame.cols - (Parameters::BOUNDARY_MARGIN * 2 + rectangleDxWidth), (frame.rows / 2 - Parameters::BOUNDARY_MARGIN) / 4 + Parameters::BOUNDARY_MARGIN), Point(frame.cols - Parameters::BOUNDARY_MARGIN * 2, (frame.rows / 2 - Parameters::BOUNDARY_MARGIN) * 3. / 4 + Parameters::BOUNDARY_MARGIN)); // Top rectangle int rectangleTopHeight = 50; Rect annotationRectTOP( Point((frame.cols - Parameters::BOUNDARY_MARGIN * 2) / 4 + Parameters::BOUNDARY_MARGIN, Parameters::BOUNDARY_MARGIN * 2), Point((frame.cols - Parameters::BOUNDARY_MARGIN * 2) * 3. / 4 + Parameters::BOUNDARY_MARGIN, Parameters::BOUNDARY_MARGIN * 2 + rectangleTopHeight)); // Bottom rectangle int rectangleBotHeight = 50; Rect annotationRectBOTTOM( Point((frame.cols - Parameters::BOUNDARY_MARGIN * 2) / 4 + Parameters::BOUNDARY_MARGIN, frame.rows / 2 - Parameters::BOUNDARY_MARGIN), Point((frame.cols - Parameters::BOUNDARY_MARGIN * 2) * 3. / 4 + Parameters::BOUNDARY_MARGIN, frame.rows / 2 - (Parameters::BOUNDARY_MARGIN + rectangleBotHeight))); // ############################################################# // // Rectangles and lines drawing section Mat frameToShow = frame.clone(); Mat truthToShow; cvtColor(truth, truthToShow, CV_GRAY2BGR); // Linea di metà line(frameToShow, Point(0, frame.rows / 2), Point(frame.cols, frame.rows / 2), Scalar(0, 255, 0), 2, CV_AA); line(truthToShow, Point(0, frame.rows / 2), Point(frame.cols, frame.rows / 2), Scalar(0, 255, 0), 2, CV_AA); // Rettangoli vari rectangle(frameToShow, boundaryRect, Scalar(0, 255, 0), 1, CV_AA); rectangle(frameToShow, annotationRectSX, Scalar(0, 0, 255), 1, CV_AA); rectangle(frameToShow, annotationRectDX, Scalar(0, 0, 255), 1, CV_AA); rectangle(frameToShow, annotationRectTOP, Scalar(0, 0, 255), 1, CV_AA); rectangle(frameToShow, annotationRectBOTTOM, Scalar(0, 0, 255), 1, CV_AA); if (drawRectangleOnTruth) { rectangle(truthToShow, boundaryRect, Scalar(0, 255, 0), 1, CV_AA); rectangle(truthToShow, annotationRectSX, Scalar(0, 0, 255), 1, CV_AA); rectangle(truthToShow, annotationRectDX, Scalar(0, 0, 255), 1, CV_AA); rectangle(truthToShow, annotationRectTOP, Scalar(0, 0, 255), 1, CV_AA); rectangle(truthToShow, annotationRectBOTTOM, Scalar(0, 0, 255), 1, CV_AA); } // ############################################################# // // Image show section imshow("Webcam", frameToShow); moveWindow("Webcam", Parameters::WINDOW_FIRST_COL, Parameters::WINDOW_FIRST_ROW); imshow("Truth", truthToShow); moveWindow("Truth", Parameters::WINDOW_SECOND_COL, Parameters::WINDOW_FIRST_ROW); // ############################################################# // // Wait key section char key = waitKey(50); if (key == Parameters::ESC_KEY) { break; } else if (key == 't') { drawRectangleOnTruth = !drawRectangleOnTruth; } else if (key == 's') { // ############################################################# // // Search section // Channels vector (4 color spaces) Mat channelsVector[12]; vector<string> channelLabels; channelLabels.push_back("BGR_B"); channelLabels.push_back("BGR_G"); channelLabels.push_back("BGR_R"); channelLabels.push_back("HSV_H"); channelLabels.push_back("HSV_S"); channelLabels.push_back("HSV_V"); channelLabels.push_back("LAB_L"); channelLabels.push_back("LAB_A"); channelLabels.push_back("LAB_B"); channelLabels.push_back("YCRCB_Y"); channelLabels.push_back("YCRCB_CR"); channelLabels.push_back("YCRCB_CB"); // Blurred Mat blurred; blur(frame, blurred, Parameters::CALIBRATION_GAUSSIAN_BLUR_SIZE); // Channel split data structure vector<Mat> channelsSplit(3); // BGR split(blurred, channelsSplit); channelsVector[Parameters::BGR_B] = channelsSplit[0].clone(); channelsVector[Parameters::BGR_G] = channelsSplit[1].clone(); channelsVector[Parameters::BGR_R] = channelsSplit[2].clone(); // HSV Mat hsv; cvtColor(blurred, hsv, CV_BGR2HSV); split(hsv, channelsSplit); channelsVector[Parameters::HSV_H] = channelsSplit[0].clone(); channelsVector[Parameters::HSV_S] = channelsSplit[1].clone(); channelsVector[Parameters::HSV_V] = channelsSplit[2].clone(); // Lab Mat lab; cvtColor(blurred, lab, CV_BGR2Lab); split(lab, channelsSplit); channelsVector[Parameters::LAB_L] = channelsSplit[0].clone(); channelsVector[Parameters::LAB_A] = channelsSplit[1].clone(); channelsVector[Parameters::LAB_B] = channelsSplit[2].clone(); // yCbCr Mat yCbCr; cvtColor(blurred, yCbCr, CV_BGR2YCrCb); split(yCbCr, channelsSplit); channelsVector[Parameters::YCRCB_Y] = channelsSplit[0].clone(); channelsVector[Parameters::YCRCB_CR] = channelsSplit[1].clone(); channelsVector[Parameters::YCRCB_CB] = channelsSplit[2].clone(); if (Parameters::CHANNEL_PREPROCESSING) { // For each channel do some preprocessing for (int i = 0; i < 12; i++) { ImageProcessor::bottomHat(channelsVector[i], channelsVector[i], Parameters::CALIBRATION_BOTTOM_HAT_MORPH_SE_SIZE); medianBlur(channelsVector[i], channelsVector[i], Parameters::CALIBRATION_MEDIAN_BLUR_SIZE); } } /* * Channel choice (for optimization process) * NOTE: value channels are discarded! */ vector<int> channelToOptimize; channelToOptimize.push_back(Parameters::BGR_B); channelToOptimize.push_back(Parameters::BGR_G); channelToOptimize.push_back(Parameters::BGR_R); channelToOptimize.push_back(Parameters::HSV_H); channelToOptimize.push_back(Parameters::HSV_S); channelToOptimize.push_back(Parameters::LAB_A); channelToOptimize.push_back(Parameters::LAB_B); channelToOptimize.push_back(Parameters::YCRCB_CR); channelToOptimize.push_back(Parameters::YCRCB_CB); // Results vector vector<Parameters::ThresholdStructure> srVector; // Search type selection switch (Parameters::SELECTED_SEARCH) { case Parameters::BRUTE_FORCE_SEARCH: srVector = Utils::bruteForceSearch(truth, channelsVector, channelToOptimize, channelLabels); break; case Parameters::GREEDY_SEARCH: srVector = Utils::greedySearch(truth, channelsVector, channelToOptimize, channelLabels); break; default: break; } /* * Searching for a good combination of channels (max Parameters::MAX_COMBINATION channels) */ vector<Parameters::ThresholdStructure> best_vector; double best_value = std::numeric_limits<double>::min(); for (int k = 1; k <= Parameters::MAX_COMBINATION; k++) { double best_k_value = std::numeric_limits<double>::min(); vector<Parameters::ThresholdStructure> best_k_vector; cp::NextCombinationGenerator<Parameters::ThresholdStructure> combinationGen(srVector, k); cp::NextCombinationGenerator<Parameters::ThresholdStructure>::iterator combIt; for (combIt = combinationGen.begin(); combIt != combinationGen.end(); combIt++) { // Vector with the current combination vector<Parameters::ThresholdStructure> combination(*combIt); double value = Utils::objFunction(truth, channelsVector, combination); if (value > best_k_value) { best_k_value = value; best_k_vector = combination; } } /* * Is really necessary to select a more complicated combination? * Aspiration criteria: choose a more complicated combination if it leads * to an improvement proportional to the current best value */ if (best_k_value > best_value * Parameters::ASPIRATION_CRITERIA_FACTOR) { best_value = best_k_value; best_vector = best_k_vector; } } // ############################################################# // // Final results section Mat thresholded; Utils::getThresholdedImage(thresholded, channelsVector, best_vector); Mat result; Utils::getErrorImage(result, truth, thresholded); destroyWindow("Webcam"); destroyWindow("Truth"); imshow("Final Thresh", thresholded); moveWindow("Final Thresh", Parameters::WINDOW_FIRST_COL, Parameters::WINDOW_FIRST_ROW); imshow("Error wrt Truth", result); moveWindow("Error wrt Truth", Parameters::WINDOW_SECOND_COL, Parameters::WINDOW_FIRST_ROW); pair<double, double> precisionRecall = Utils::getPrecisionRecall(truth, thresholded); std::cout << "\nBest combination (max " << Parameters::MAX_COMBINATION << " channels):\n-------------------------------------------------\n"; cout << "F-Measure:\t" << best_value << "\n"; cout << "\tPrecision:\t" << precisionRecall.first << "\n"; cout << "\tRecall:\t\t" << precisionRecall.second << "\n"; cout << "Channels:\n"; for (unsigned int ch = 0; ch < best_vector.size(); ch++) { cout << "\t" << channelLabels[best_vector[ch].channel] << "\t"; cout << "[" << best_vector[ch].thresh.first << ", " << best_vector[ch].thresh.second << "]\n"; } // ############################################################# // // Saving section fs << "number" << (int) best_vector.size(); for (unsigned int ch = 0; ch < best_vector.size(); ch++) { stringstream ss; ss << "thresh" << "_" << ch; fs << ss.str() << "{"; fs << "channel" << channelLabels[best_vector[ch].channel]; fs << "channel_id" << best_vector[ch].channel; fs << "thresh" << "{" << "first" << best_vector[ch].thresh.first << "second" << best_vector[ch].thresh.second << "}"; fs << "}"; } fs.release(); std::cout << "\nSaving" << "\n-------------------------------------------------\n"; std::cout << "Saved on yml file \"" << filename.str() << "\"\n\n"; std::cout << "Press a key to reset...\n"; std::cout << "Press Esc to quit...\n"; key = waitKey(0); if (key == Parameters::ESC_KEY) { break; } destroyWindow("Final Thresh"); destroyWindow("Error wrt Truth"); } } } else if (vm["subcommand"].as<string>().compare("register") == 0) { //##############################################################################// // REGISTRATION //##############################################################################// std::cout << "Register\n------------------------------------------" << "\n\n"; path documentsPath(documentsPathString); path outputPath(outputPathString); // Number of sets std::cout << "> Number of sets:" << nSets << "\n\n"; if (nSets == 1) { // Standard registration process for all the documents path registeredPdfMapPath = outputPath / Parameters::REGISTERED_PDF_MAP_PATH; path databasePath = outputPath / Parameters::DATABASE_PATH; path outputImagesPath = outputPath / Parameters::IMAGES_PATH; // Validates dataset output path std::cout << "> Dataset output path validation" << std::endl; FileManager::parentPathValidation(outputPath, outputImagesPath); std::cout << std::endl; // Loads the registeredPdfMap FileManager::loadRegisteredPdfMap(Parameters::registeredPdfMap, registeredPdfMapPath); std::cout << "> RegisteredPdfMap:" << "\n" << "\t" << "Path: " << registeredPdfMapPath << "\n" << "\t" << "Size: " << Parameters::registeredPdfMap.size() << "\n\n"; // Open a connection to the given database DatabaseHandler::openDatabase(databasePath); std::cout << "> Database:" << "\n" << "\t" << "Path: " << databasePath << "\n\n"; // Gets a list of pdf if pdfPath is a directory of pdf, gets a list with one pdf if pdfPath is a pdf std::cout << "> Documents path:\t" << documentsPath << "\n\n"; list<string> pdfList; FileManager::getPdfListFromPath(documentsPath, pdfList); std::cout << "> # Pdf: " << pdfList.size() << "\n"; std::cout << "> Pdf List:\n"; // RegisteredPdfMap update flag bool updateData = false; // Iterate for all pdf in pdfList list<string>::iterator pdfListIt; for (pdfListIt = pdfList.begin(); pdfListIt != pdfList.end(); pdfListIt++) { string pdfPath = *pdfListIt; string pdfFileName = path(pdfPath).filename().string(); std::cout << "\t> " << pdfPath << "\n"; // Checks if the pdf was already registered (fileName is the key) if (Parameters::registeredPdfMap.find(pdfFileName) == Parameters::registeredPdfMap.end()) { // Pdf isn't already registered (and converted) std::cout << "\t\tNot registered, conversion in progress..." << std::flush; stringstream jpgPath; jpgPath << outputImagesPath.string() << pdfFileName << ".jpg"; // Conversion list<string> jpgList; int numPages = FileManager::createImagesFromPdf(pdfPath, jpgPath.str(), jpgList); if (numPages > 0) { updateData = true; std::cout << numPages << " pages converted\n"; bool errorDuringRegistration = false; list<string>::iterator it = jpgList.begin(); int n = 0; while (it != jpgList.end() && !errorDuringRegistration) { std::cout << "\t\tRegistration for " << *it << " (" << (n + 1) << "/" << jpgList.size() << ")\n"; // ################################## // PAGE REGISTRATION // ################################## // Get image features (centroids) vector<Point> featurePoints; Mat page = cv::imread(*it, CV_LOAD_IMAGE_GRAYSCALE); ImageProcessor::getImageFeaturePoints(page, featurePoints); string pageId = path(*it).filename().string(); FeaturesManager::registerFeatures(featurePoints, pageId); it++; n++; } if (!errorDuringRegistration) { std::pair<string, string> record(pdfFileName, pdfPath); // Updating the registeredPdfMap Parameters::registeredPdfMap.insert(record); } } else { std::cout << "an error occurred\n"; } } else { std::cout << "\t\tAlready registered" << "\n"; } } if (updateData) { std::cout << "\n" << "Saving RegisteredPdfMap..." << std::flush; // Saves the registeredPdfMap FileManager::saveRegisteredPdfMap(Parameters::registeredPdfMap, registeredPdfMapPath); std::cout << "DONE\n"; } // Close database connection DatabaseHandler::closeDatabase(); #ifdef DEBUG_FEATURES_MANAGER_DISCRETIZATION_STATISTICS std::cout << "\n" << "> Max Affine invariant: " << Parameters::maxAffineInvariant << "\n"; std::cout << "> Invalid affine invariants: " << Parameters::invalidAffineInvariants << "\n"; std::cout << "> Affine invariant discretization statistics:" << "\n"; for (unsigned int i = 0; i < Parameters::K; i++) { std::cout << "\t[" << i << "] = " << Parameters::DISCRETIZATION_STATISTICS[i] << "\n"; } std::cout << "\n" << "> Sorting affine invariant vector (" << Parameters::affineInvariantVector.size() << " elements)..." << std::flush; std::sort(Parameters::affineInvariantVector.begin(), Parameters::affineInvariantVector.end()); std::cout << "DONE\n"; std::cout << "> Optimal discretization vector ripartion (for these pdf):\n"; int step = Parameters::affineInvariantVector.size() / Parameters::K; for (unsigned int i = 1; i < Parameters::K; i++) { std::cout << "\t[" << (i * step) << "] = " << Parameters::affineInvariantVector[i * step] << "\n"; } #endif std::cout << "\n" << "> Terminated" << "\n"; } else { //##############################################################################// // REGISTRATION (WITH N_SETS>1) //##############################################################################// // srand initialization unsigned int seed; // Choose a fixed rand SEED or a new SEED based on time function if (Parameters::USE_FIXED_RAND_SEED) { seed = Parameters::FIXED_RAND_SEED; } else { seed = time(0); } srand(seed); path outputAllImagesPath = outputPath / Parameters::IMAGES_PATH; path convertedPdfMapPath = outputPath / Parameters::CONVERTED_PDF_MAP_PATH; // Validates dataset output path std::cout << "> Datasets output path validation" << std::endl; FileManager::parentPathValidation(outputPath, outputAllImagesPath); std::cout << std::endl; // Loads the convertedPdfMap FileManager::loadConvertedPdfMap(Parameters::convertedPdfMap, convertedPdfMapPath); std::cout << "> ConvertedPdfMap:" << "\n" << "\t" << "Path: " << convertedPdfMapPath << "\n" << "\t" << "Size: " << Parameters::convertedPdfMap.size() << "\n\n"; // Gets a list of pdf if pdfPath is a directory of pdf, gets a list with one pdf if pdfPath is a pdf std::cout << "> Documents path:\t" << documentsPath << "\n\n"; list<string> pdfList; FileManager::getPdfListFromPath(documentsPath, pdfList); std::cout << "> # Pdf: " << pdfList.size() << "\n"; std::cout << "> Pdf List:\n"; // Iterate for all pdf in pdfList and converts if not already converted list<string>::iterator pdfListIt; int pdfCounter = 1; uint numPages = 0; for (pdfListIt = pdfList.begin(); pdfListIt != pdfList.end(); pdfListIt++) { string pdfPath = *pdfListIt; string pdfFileName = path(pdfPath).filename().string(); // Checks if the pdf was already registered (fileName is the key) typedef map<string, pair<string, int>>::const_iterator const_iterator; const_iterator it = Parameters::convertedPdfMap.find(pdfFileName); if (it == Parameters::convertedPdfMap.end()) { // Pdf isn't already converted std::cout << "\t> " << pdfPath << " conversion in progress (" << pdfCounter << "/" << pdfList.size() << ")\n"; stringstream jpgPath; jpgPath << outputAllImagesPath.string() << pdfFileName << ".jpg"; // Conversion list<string> jpgList; int pages = FileManager::createImagesFromPdf(pdfPath, jpgPath.str(), jpgList); numPages += pages; if (pages > 0) { // Update convertedPdfMap std::pair<string, pair<string, int>> record(pdfFileName, make_pair(pdfPath, pages)); Parameters::convertedPdfMap.insert(record); } } else { numPages += (it->second).second; std::cout << "\t> " << pdfPath << " already converted (" << pdfCounter << "/" << pdfList.size() << ")\n"; } pdfCounter++; } // Save convertedPdfMap std::cout << "\n" << "> Saving convertedPdfMap..." << "\n"; FileManager::saveConvertedPdfMap(Parameters::convertedPdfMap, convertedPdfMapPath); std::cout << "\n" << "> # Total pages: " << numPages << "\n\n"; try { // Check if there are same pages converted but not in the converted list vector<string> jpgVector; FileManager::getJpgVectorFromPath(outputAllImagesPath, jpgVector); if (numPages != jpgVector.size()) { throw std::logic_error( std::string( "Number of pages in converted folder is inconsistent with the converted jpg list. Same pages may have been moved away from folder")); } // Check if pages converted are more then the nSets*nRetained if (numPages < nSets * nRetained) { throw std::logic_error( std::string("Converted pages cannot be less than nSets*nRetained (") + boost::lexical_cast<string>(nSets * nRetained) + std::string(").")); } // Check if retained folder already exists path outputRetainedImagesPath = outputPath / Parameters::RETAINED_IMAGES_PATH; std::cout << "> Retained images path validation" << std::endl; if (exists(outputRetainedImagesPath)) { throw std::logic_error( std::string("Retained images folder already exists. Please delete the folder.")); } FileManager::parentPathValidation(outputPath, outputRetainedImagesPath); // Check if some folder for sets already exists int nIncrement = numPages / nSets; std::cout << "\n> Sets output path validation" << std::endl << std::endl; for (int i = 0; i < nSets; i++) { int setSize = i * nIncrement + nIncrement; path datasetPath = outputPath / std::string(Parameters::DATASET_PREFIX + boost::lexical_cast<string>(setSize)); if (exists(datasetPath)) { throw std::logic_error( std::string(datasetPath.string() + " already exists. Please delete the folder.")); } } // Choose nRetained elements and save to retained folder vector<int> retainedIndexes; vector<string> retainedImagesPath; Utils::selectRandomDistinctIndexes(jpgVector.size(), retainedIndexes, nRetained); sort(retainedIndexes.begin(), retainedIndexes.end(), greater<int>()); for (unsigned i = 0; i < retainedIndexes.size(); i++) { int index = retainedIndexes.at(i); string retainedJpgPath = jpgVector.at(index); std::cout << "> Saving retained JPG #" << i + 1 << ": " << retainedJpgPath << "\n"; path imagePathFrom = retainedJpgPath; path imagePathTo = outputRetainedImagesPath / path(retainedJpgPath).filename(); copy_file(imagePathFrom, imagePathTo, copy_option::overwrite_if_exists); jpgVector.erase(jpgVector.begin() + index); retainedImagesPath.push_back(retainedJpgPath); } // Create and register each set for (int i = 0; i < nSets; i++) { #ifdef DEBUG_FEATURES_MANAGER_DISCRETIZATION_STATISTICS // Clear statistics vector Parameters::affineInvariantVector.clear(); Parameters::maxAffineInvariant = 0; Parameters::invalidAffineInvariants = 0; #endif int setSize = i * nIncrement + nIncrement; std::cout << "\n> Registering set #" << i + 1 << " (" << setSize << " elements)" << std::endl; // Create folders path datasetPath = outputPath / std::string(Parameters::DATASET_PREFIX + boost::lexical_cast<string>(setSize)); path databasePath = datasetPath / Parameters::DATABASE_PATH; path outputImagesPath = datasetPath / Parameters::IMAGES_PATH; // Validates dataset output paths std::cout << "> Dataset output paths validation" << std::endl; FileManager::parentPathValidation(outputPath, datasetPath); FileManager::parentPathValidation(datasetPath, outputImagesPath); // Open a connection to the given database DatabaseHandler::openDatabase(databasePath); // Create vector of pages int nToChoose = setSize - nRetained; list<string> datasetImages; for (unsigned j = 0; j < retainedImagesPath.size(); j++) { path imagePathFrom = retainedImagesPath[j]; path imagePathTo = outputImagesPath / path(retainedImagesPath[j]).filename(); copy_file(imagePathFrom, imagePathTo, copy_option::overwrite_if_exists); datasetImages.push_back(imagePathTo.string()); } vector<int> choosenIndexes; Utils::selectRandomDistinctIndexes(jpgVector.size(), choosenIndexes, nToChoose); for (unsigned k = 0; k < choosenIndexes.size(); k++) { int index = choosenIndexes.at(k); string jpgPath = jpgVector.at(index); path imagePathFrom = jpgPath; path imagePathTo = outputImagesPath / path(jpgPath).filename(); copy_file(imagePathFrom, imagePathTo, copy_option::overwrite_if_exists); datasetImages.push_back(imagePathTo.string()); } // Register bool errorDuringRegistration = false; list<string>::iterator it = datasetImages.begin(); int n = 0; while (it != datasetImages.end() && !errorDuringRegistration) { std::cout << "\tRegistration for " << *it << " (" << (n + 1) << "/" << datasetImages.size() << ")\n"; // ################################## // PAGE REGISTRATION // ################################## // Get image features (centroids) vector<Point> featurePoints; Mat page = cv::imread(*it, CV_LOAD_IMAGE_GRAYSCALE); ImageProcessor::getImageFeaturePoints(page, featurePoints); string pageId = path(*it).filename().string(); FeaturesManager::registerFeatures(featurePoints, pageId); it++; n++; } // Close database connection DatabaseHandler::closeDatabase(); #ifdef DEBUG_FEATURES_MANAGER_DISCRETIZATION_STATISTICS std::cout << "\n" << "> Max Affine invariant: " << Parameters::maxAffineInvariant << "\n"; std::cout << "> Invalid affine invariants: " << Parameters::invalidAffineInvariants << "\n"; std::cout << "> Affine invariant discretization statistics:" << "\n"; for (unsigned int i = 0; i < Parameters::K; i++) { std::cout << "\t[" << i << "] = " << Parameters::DISCRETIZATION_STATISTICS[i] << "\n"; } std::cout << "\n" << "> Sorting affine invariant vector (" << Parameters::affineInvariantVector.size() << " elements)..." << std::flush; std::sort(Parameters::affineInvariantVector.begin(), Parameters::affineInvariantVector.end()); std::cout << "DONE\n"; std::cout << "> Optimal discretization vector ripartion (for these pdf):\n"; int step = Parameters::affineInvariantVector.size() / Parameters::K; for (unsigned int i = 1; i < Parameters::K; i++) { std::cout << "\t[" << (i * step) << "] = " << Parameters::affineInvariantVector[i * step] << "\n"; } #endif } } catch (std::exception& e) { std::cerr << e.what() << "\n"; return 0; } } } else if (vm["subcommand"].as<string>().compare("annotate") == 0) { XInitThreads(); //##############################################################################// // ANNOTATION //##############################################################################// std::cout << "\nAnnotate\n------------------------------------------" << "\n"; path datasetPath(datasetPathString); path pdfOutputPath(outputPathString); path registeredPdfMapPath = datasetPath / Parameters::REGISTERED_PDF_MAP_PATH; path databasePath = datasetPath / Parameters::DATABASE_PATH; path masksPath = datasetPath / Parameters::MASKS_PATH; path annotationsPath = datasetPath / Parameters::ANNOTATIONS_PATH; // Validates masks path std::cout << "> Masks path validation" << std::endl; FileManager::parentPathValidation(datasetPath, masksPath); std::cout << std::endl; // Validates annotations path std::cout << "> Annotations path validation" << std::endl; FileManager::parentPathValidation(datasetPath, annotationsPath); std::cout << std::endl; // Validates pdf output path std::cout << "> Pdf output path validation" << std::endl; FileManager::pathValidation(pdfOutputPath); std::cout << std::endl; // Calibration file handle if (calibrationSupplied) { Parameters::ANNOTATION_COLOR_MODE = Parameters::ANNOTATION_COLOR_THRESHOLD_FILE_MODE; } else { Parameters::ANNOTATION_COLOR_MODE = Parameters::ANNOTATION_COLOR_FIXED_MODE; } if (Parameters::ANNOTATION_COLOR_MODE == Parameters::ANNOTATION_COLOR_THRESHOLD_FILE_MODE) { vector<string> channelLabels; channelLabels.push_back("BGR_B"); channelLabels.push_back("BGR_G"); channelLabels.push_back("BGR_R"); channelLabels.push_back("HSV_H"); channelLabels.push_back("HSV_S"); channelLabels.push_back("HSV_V"); channelLabels.push_back("LAB_L"); channelLabels.push_back("LAB_A"); channelLabels.push_back("LAB_B"); channelLabels.push_back("YCRCB_Y"); channelLabels.push_back("YCRCB_CR"); channelLabels.push_back("YCRCB_CB"); // Loads calibrated annotation thresholds FileManager::loadAnnotationThresholds(calibrationPathString); std::cout << "> Loaded calibrated annotation thresholds" << std::endl; cout << "> Channels:\n"; for (unsigned int ch = 0; ch < Parameters::annotationThresholds.size(); ch++) { cout << "\t" << channelLabels[Parameters::annotationThresholds[ch].channel] << "\t"; cout << "[" << Parameters::annotationThresholds[ch].thresh.first << ", " << Parameters::annotationThresholds[ch].thresh.second << "]\n"; } } else { std::cout << "> Fixed annotation thresholds (light blue)" << std::endl; } std::cout << std::endl; // Loads the registeredPdfMap FileManager::loadRegisteredPdfMap(Parameters::registeredPdfMap, registeredPdfMapPath); std::cout << "> RegisteredPdfMap:" << "\n" << "\t" << "Path: " << registeredPdfMapPath << "\n" << "\t" << "Size: " << Parameters::registeredPdfMap.size() << "\n\n"; // Open a connection to the given database DatabaseHandler::openDatabase(databasePath); std::cout << "> Database:" << "\n" << "\t" << "Path: " << databasePath << "\n\n"; /* * Inizializzazione macchina * #################################################################################### */ StateMachine* sm = new StateMachine(); // Inizializzazione stati PageDiscovering* pageDiscoveringState = new PageDiscovering(sm); PageRetrieval* pageRetrievalState = new PageRetrieval(sm); PageTracking* pageTrackingState = new PageTracking(sm); PageError* pageErrorState = new PageError(sm); PageAnnotation* pageAnnotationState = new PageAnnotation(sm); PdfCreation* pdfCreationState = new PdfCreation(sm); ExitState* exitState = new ExitState(sm); // Inizializzazione stati iniziali e finali sm->setInitialState(pageDiscoveringState); sm->setFinalState(exitState); // Inizializzazione transizioni sm->addTransition(pageDiscoveringState, pageDiscoveringState, EvPageDiscoveringFail()); sm->addTransition(pageDiscoveringState, pageRetrievalState, EvPageDiscoveringSuccess()); sm->addTransition(pageRetrievalState, pageTrackingState, EvPageRetrievalDone()); sm->addTransition(pageRetrievalState, pageErrorState, EvPageRetrievalError()); sm->addTransition(pageTrackingState, pageTrackingState, EvPageTrackingSuccess()); sm->addTransition(pageTrackingState, pageAnnotationState, EvPageAnnotationStart()); sm->addTransition(pageTrackingState, pageErrorState, EvPageTrackingFailGenericError()); sm->addTransition(pageTrackingState, pageErrorState, EvPageTrackingFailHandOcclusion()); sm->addTransition(pageTrackingState, pageErrorState, EvPageTrackingAnnotationSaveError()); sm->addTransition(pageTrackingState, pdfCreationState, EvPdfCreationRequest()); sm->addTransition(pageAnnotationState, pageTrackingState, EvPageAnnotationEnd()); sm->addTransition(pdfCreationState, pageTrackingState, EvPdfCreationDone()); sm->addTransition(pageErrorState, pageDiscoveringState, EvErrorReset()); // Exit transitions sm->addTransition(pageDiscoveringState, exitState, EvExit()); sm->addTransition(pageRetrievalState, exitState, EvExit()); sm->addTransition(pageTrackingState, exitState, EvExit()); sm->addTransition(pageAnnotationState, exitState, EvExit()); sm->addTransition(pdfCreationState, exitState, EvExit()); sm->addTransition(pageErrorState, exitState, EvExit()); // Set dataset path and pdf output path sm->setDatasetPath(datasetPath); sm->setPdfOutputPath(pdfOutputPath); sm->initiate(); // Deleting objects delete exitState; delete pageTrackingState; delete pageRetrievalState; delete pageDiscoveringState; delete pageErrorState; delete pageAnnotationState; delete pdfCreationState; delete sm; // Close database connection DatabaseHandler::closeDatabase(); std::cout << "\n" << "> Terminated" << "\n"; } else if (vm["subcommand"].as<string>().compare("test") == 0) { XInitThreads(); //##############################################################################// // TEST //##############################################################################// #ifndef DEBUG_RETRIEVE_PAGE_PRINT_FINAL_STATISTICS #define DEBUG_RETRIEVE_PAGE_PRINT_FINAL_STATISTICS #endif std::cout << "\nTest\n------------------------------------------" << "\n"; path datasetPath(datasetPathString); path databasePath = datasetPath / Parameters::DATABASE_PATH; // Open a connection to the given database DatabaseHandler::openDatabase(databasePath); std::cout << "> Database:" << "\n" << "\t" << "Path: " << databasePath << "\n\n"; /* * Inizializzazione macchina * #################################################################################### */ StateMachine* sm = new StateMachine(); // Inizializzazione stati PageDiscovering* pageDiscoveringState = new PageDiscovering(sm); PageRetrieval* pageRetrievalState = new PageRetrieval(sm); ExitState* exitState = new ExitState(sm); // Inizializzazione variabili di test sm->setTest(true); sm->setPageName(pageNameString); // Inizializzazione stati iniziali e finali sm->setInitialState(pageDiscoveringState); sm->setFinalState(exitState); // Inizializzazione transizioni sm->addTransition(pageDiscoveringState, pageDiscoveringState, EvPageDiscoveringFail()); sm->addTransition(pageDiscoveringState, pageRetrievalState, EvPageDiscoveringSuccess()); sm->addTransition(pageRetrievalState, exitState, EvPageRetrievalDone()); // Exit transitions sm->addTransition(pageDiscoveringState, exitState, EvExit()); sm->addTransition(pageRetrievalState, exitState, EvExit()); // Set dataset path and pdf output path sm->setDatasetPath(datasetPath); sm->initiate(); // Deleting objects delete exitState; delete pageRetrievalState; delete pageDiscoveringState; delete sm; // Close database connection DatabaseHandler::closeDatabase(); std::cout << "\n" << "> Terminated" << "\n"; } return 0; }
39.230627
142
0.647298
marcorighini
487bd774661be7faf45117117495df4072942e79
1,795
hpp
C++
AI_Engine_Development/Design_Tutorials/08-n-body-simulator/x10_design/pl_kernels/kernel/packet_sender.hpp
jlamperez/Vitis-Tutorials
9a5b611caabb5656bbb2879116e032227b164bfd
[ "Apache-2.0" ]
567
2019-10-01T16:31:26.000Z
2022-03-31T18:43:30.000Z
AI_Engine_Development/Design_Tutorials/08-n-body-simulator/x10_design/pl_kernels/kernel/packet_sender.hpp
jlamperez/Vitis-Tutorials
9a5b611caabb5656bbb2879116e032227b164bfd
[ "Apache-2.0" ]
142
2019-11-25T14:42:16.000Z
2022-03-31T15:06:56.000Z
AI_Engine_Development/Design_Tutorials/08-n-body-simulator/x10_design/pl_kernels/kernel/packet_sender.hpp
jlamperez/Vitis-Tutorials
9a5b611caabb5656bbb2879116e032227b164bfd
[ "Apache-2.0" ]
387
2019-10-10T09:14:00.000Z
2022-03-31T02:51:02.000Z
/* (c) Copyright 2021 Xilinx, 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 _PACKET_SENDER_H_ #define _PACKET_SENDER_H_ #include <cstring> #include <ap_int.h> #include <hls_stream.h> #include <ap_axi_sdata.h> #include "../../aie/build/Work_x4_x10/temp/packet_ids_c.h" #define NUM_CU 10 #define PACKET_NUM 4 #define PKTTYPE 0 #define PACKET_LEN 224 #define BURST_SIZE PACKET_LEN * PACKET_NUM //4 packets typedef ap_uint<32> data_t; typedef ap_axiu<32, 0, 0, 0> axis_pkt; static const unsigned int packet_ids[PACKET_NUM]={in_i0_0, in_i0_1, in_i0_2, in_i0_3}; //macro values are generated in packet_ids_c.h data_t generateHeader(unsigned int pktType, unsigned int ID); void packet_sender(hls::stream<axis_pkt>& rx, hls::stream<axis_pkt>& tx0, hls::stream<axis_pkt>& tx1, hls::stream<axis_pkt>& tx2, hls::stream<axis_pkt>& tx3, hls::stream<axis_pkt>& tx4, hls::stream<axis_pkt>& tx5, hls::stream<axis_pkt>& tx6, hls::stream<axis_pkt>& tx7, hls::stream<axis_pkt>& tx8, hls::stream<axis_pkt>& tx9 ); #endif // _PACKET_SENDER_H_
35.9
133
0.650696
jlamperez
487be57c7fbeb678ee3e855c2b9d51ad01597d1a
591
cpp
C++
src/render/texture.cpp
Alec-Sobeck/FPS-Game
3a0f3e82bdbc651ee99e7b10d71d55ba43bb6d35
[ "MIT" ]
null
null
null
src/render/texture.cpp
Alec-Sobeck/FPS-Game
3a0f3e82bdbc651ee99e7b10d71d55ba43bb6d35
[ "MIT" ]
null
null
null
src/render/texture.cpp
Alec-Sobeck/FPS-Game
3a0f3e82bdbc651ee99e7b10d71d55ba43bb6d35
[ "MIT" ]
1
2015-02-04T23:29:59.000Z
2015-02-04T23:29:59.000Z
#include "texture.h" using namespace gl; /** * Constructs a new Texture object, storing the specified textureID for binding * @param textureID the Integer representing the texture that can be bound */ Texture::Texture(std::string associatedFileName, gl::GLuint textureID) : textureID(textureID), associatedFileName(associatedFileName) { } /** * Binds the texture using GL11. The texture will remain bound until the next bind() call of a different * texture object, or manual call to GL11.glBindTexture(...) */ void Texture::bind() { glBindTexture(GL_TEXTURE_2D, textureID); }
25.695652
133
0.749577
Alec-Sobeck
487d5a32b3f19715ea2edea905d3026112de6da0
4,978
cpp
C++
source/lib/PccLibConformance/source/PCCConfigurationFileParser.cpp
giterator/mpeg-pcc-tmc2
4262af3b405e69f3823eedbd6ebb70d81c5f502a
[ "BSD-3-Clause" ]
80
2019-07-02T22:05:26.000Z
2022-03-29T12:46:31.000Z
source/lib/PccLibConformance/source/PCCConfigurationFileParser.cpp
ricardjidcc/mpeg-pcc-tmc2
588abd7750d24057f2ce8b1088cc92868a39bc16
[ "BSD-3-Clause" ]
null
null
null
source/lib/PccLibConformance/source/PCCConfigurationFileParser.cpp
ricardjidcc/mpeg-pcc-tmc2
588abd7750d24057f2ce8b1088cc92868a39bc16
[ "BSD-3-Clause" ]
34
2019-07-18T11:58:14.000Z
2022-03-18T06:47:48.000Z
/* The copyright in this software is being made available under the BSD * License, included below. This software may be subject to other third party * and contributor rights, including patent rights, and no such rights are * granted under this license. * * Copyright (c) 2010-2017, ITU/ISO/IEC * 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 ITU/ISO/IEC nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "PCCConfigurationFileParser.h" using namespace std; using namespace pcc; ostream& PCCErrorMessage::error( const std::string& errMessage, const std::string& where ) { is_errored_ = true; if ( !where.empty() ) { cerr << "\n\nError: " << errMessage << "\n" << where << endl; } else { cerr << "\n\nError: " << errMessage << endl; } return cerr; } std::ostream& PCCErrorMessage::warn( const std::string& warningMessage, const string& where ) { if ( !where.empty() ) { cerr << " Warning:" << warningMessage << "\n" << where << endl; } else { cerr << " Warning: " << warningMessage << endl; } return cerr; } void PCCConfigurationFileParser::scanLine( std::string& line, KeyValMaps& key_val_maps ) { // Ignore comment lines starting with "**********" if ( line.rfind( "**********", 0 ) == 0 ) { return; } std::map<std::string, std::string> key_val_map; std::string spKey[3] = {"Occupancy", "Geometry", "Attribute"}; if ( line.find( "#" ) != std::string::npos ) { return; } // skip comment line size_t start = line.find_first_not_of( " \t\n\r" ); if ( start == string::npos ) { return; } // blank line line.erase( std::remove( line.begin(), line.end(), ' ' ), line.end() ); line += " "; while ( line.size() > 1 ) { std::string keyName = "Not Set", keyValue = ""; size_t curPos = line.find_first_of( "=" ); if ( curPos != std::string::npos ) { keyName = line.substr( 0, curPos ); } else { for ( auto& e : spKey ) { size_t found = line.find( e ); if ( found != std::string::npos ) { key_val_map.insert( std::pair<std::string, std::string>( e, "" ) ); key_val_maps.push_back( key_val_map ); return; } } } if ( !validKey( keyName ) ) { error( where() ) << "Unknown Key: " << keyName << endl; return; } auto endPos = line.find_first_of( ", ", curPos ); if ( endPos != std::string::npos ) { keyValue = line.substr( curPos + 1, endPos - curPos - 1 ); // ajt::how to check valid key value in case of missing ,? } else { error( where() ) << " missing ',' " << endl; return; } key_val_map.insert( std::pair<std::string, std::string>( keyName, keyValue ) ); line.erase( 0, endPos + 1 ); } key_val_maps.push_back( key_val_map ); } void PCCConfigurationFileParser::scanStream( std::istream& in, KeyValMaps& key_val_maps ) { do { linenum_++; std::string line; getline( in, line ); scanLine( line, key_val_maps ); } while ( !!in ); } bool PCCConfigurationFileParser::parseFile( std::string& fileName, KeyValMaps& key_val_maps ) { name_ = fileName; linenum_ = 0; std::ifstream cfrStream( name_.c_str(), std::ifstream::in ); if ( !cfrStream ) { error( name_ ) << "Failed to Open : " << name_ << endl; return false; } scanStream( cfrStream, key_val_maps ); return true; } bool PCCConfigurationFileParser::validKey( std::string& name ) { bool found = false; for ( auto key : keyList_ ) { if ( !name.compare( key ) ) { found = true; } } return found; }
38.890625
95
0.649658
giterator
487d70365525e0524e8b956701e07282308b3b69
10,951
cc
C++
selfdrive/ui/qt/offroad/moc_networking.cc
leech2000/kona0813
c3e73e220b86614b82959712668408a48c33ebd3
[ "MIT" ]
1
2022-03-23T13:52:40.000Z
2022-03-23T13:52:40.000Z
selfdrive/ui/qt/offroad/moc_networking.cc
leech2000/kona0813
c3e73e220b86614b82959712668408a48c33ebd3
[ "MIT" ]
null
null
null
selfdrive/ui/qt/offroad/moc_networking.cc
leech2000/kona0813
c3e73e220b86614b82959712668408a48c33ebd3
[ "MIT" ]
5
2022-03-24T16:18:47.000Z
2022-03-30T02:18:49.000Z
/**************************************************************************** ** Meta object code from reading C++ file 'networking.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "networking.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'networking.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.12.8. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_WifiUI_t { QByteArrayData data[6]; char stringdata0[43]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_WifiUI_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_WifiUI_t qt_meta_stringdata_WifiUI = { { QT_MOC_LITERAL(0, 0, 6), // "WifiUI" QT_MOC_LITERAL(1, 7, 16), // "connectToNetwork" QT_MOC_LITERAL(2, 24, 0), // "" QT_MOC_LITERAL(3, 25, 7), // "Network" QT_MOC_LITERAL(4, 33, 1), // "n" QT_MOC_LITERAL(5, 35, 7) // "refresh" }, "WifiUI\0connectToNetwork\0\0Network\0n\0" "refresh" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_WifiUI[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 2, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: name, argc, parameters, tag, flags 1, 1, 24, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 5, 0, 27, 2, 0x0a /* Public */, // signals: parameters QMetaType::Void, 0x80000000 | 3, 4, // slots: parameters QMetaType::Void, 0 // eod }; void WifiUI::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<WifiUI *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->connectToNetwork((*reinterpret_cast< const Network(*)>(_a[1]))); break; case 1: _t->refresh(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); { using _t = void (WifiUI::*)(const Network & ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&WifiUI::connectToNetwork)) { *result = 0; return; } } } } QT_INIT_METAOBJECT const QMetaObject WifiUI::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_WifiUI.data, qt_meta_data_WifiUI, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *WifiUI::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *WifiUI::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_WifiUI.stringdata0)) return static_cast<void*>(this); return QWidget::qt_metacast(_clname); } int WifiUI::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 2) qt_static_metacall(this, _c, _id, _a); _id -= 2; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 2) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 2; } return _id; } // SIGNAL 0 void WifiUI::connectToNetwork(const Network & _t1) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } struct qt_meta_stringdata_AdvancedNetworking_t { QByteArrayData data[6]; char stringdata0[62]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_AdvancedNetworking_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_AdvancedNetworking_t qt_meta_stringdata_AdvancedNetworking = { { QT_MOC_LITERAL(0, 0, 18), // "AdvancedNetworking" QT_MOC_LITERAL(1, 19, 9), // "backPress" QT_MOC_LITERAL(2, 29, 0), // "" QT_MOC_LITERAL(3, 30, 15), // "toggleTethering" QT_MOC_LITERAL(4, 46, 7), // "enabled" QT_MOC_LITERAL(5, 54, 7) // "refresh" }, "AdvancedNetworking\0backPress\0\0" "toggleTethering\0enabled\0refresh" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_AdvancedNetworking[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 3, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: name, argc, parameters, tag, flags 1, 0, 29, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 3, 1, 30, 2, 0x0a /* Public */, 5, 0, 33, 2, 0x0a /* Public */, // signals: parameters QMetaType::Void, // slots: parameters QMetaType::Void, QMetaType::Bool, 4, QMetaType::Void, 0 // eod }; void AdvancedNetworking::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<AdvancedNetworking *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->backPress(); break; case 1: _t->toggleTethering((*reinterpret_cast< bool(*)>(_a[1]))); break; case 2: _t->refresh(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); { using _t = void (AdvancedNetworking::*)(); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&AdvancedNetworking::backPress)) { *result = 0; return; } } } } QT_INIT_METAOBJECT const QMetaObject AdvancedNetworking::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_AdvancedNetworking.data, qt_meta_data_AdvancedNetworking, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *AdvancedNetworking::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *AdvancedNetworking::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_AdvancedNetworking.stringdata0)) return static_cast<void*>(this); return QWidget::qt_metacast(_clname); } int AdvancedNetworking::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 3) qt_static_metacall(this, _c, _id, _a); _id -= 3; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 3) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 3; } return _id; } // SIGNAL 0 void AdvancedNetworking::backPress() { QMetaObject::activate(this, &staticMetaObject, 0, nullptr); } struct qt_meta_stringdata_Networking_t { QByteArrayData data[8]; char stringdata0[66]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_Networking_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_Networking_t qt_meta_stringdata_Networking = { { QT_MOC_LITERAL(0, 0, 10), // "Networking" QT_MOC_LITERAL(1, 11, 7), // "refresh" QT_MOC_LITERAL(2, 19, 0), // "" QT_MOC_LITERAL(3, 20, 16), // "connectToNetwork" QT_MOC_LITERAL(4, 37, 7), // "Network" QT_MOC_LITERAL(5, 45, 1), // "n" QT_MOC_LITERAL(6, 47, 13), // "wrongPassword" QT_MOC_LITERAL(7, 61, 4) // "ssid" }, "Networking\0refresh\0\0connectToNetwork\0" "Network\0n\0wrongPassword\0ssid" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_Networking[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 3, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 29, 2, 0x0a /* Public */, 3, 1, 30, 2, 0x08 /* Private */, 6, 1, 33, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, 0x80000000 | 4, 5, QMetaType::Void, QMetaType::QString, 7, 0 // eod }; void Networking::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<Networking *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->refresh(); break; case 1: _t->connectToNetwork((*reinterpret_cast< const Network(*)>(_a[1]))); break; case 2: _t->wrongPassword((*reinterpret_cast< const QString(*)>(_a[1]))); break; default: ; } } } QT_INIT_METAOBJECT const QMetaObject Networking::staticMetaObject = { { &QFrame::staticMetaObject, qt_meta_stringdata_Networking.data, qt_meta_data_Networking, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *Networking::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *Networking::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_Networking.stringdata0)) return static_cast<void*>(this); return QFrame::qt_metacast(_clname); } int Networking::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QFrame::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 3) qt_static_metacall(this, _c, _id, _a); _id -= 3; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 3) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 3; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
29.438172
100
0.611816
leech2000
487e0dfee4d2acf3dc12089a338bb6849b6daecd
7,677
hpp
C++
include/dualsynth/vs_wrapper.hpp
msg7086/MiniDeen
0342ed55d8cf2b5cb4077ff206d4e5bbaac734fa
[ "MIT" ]
6
2020-04-11T06:59:28.000Z
2021-07-20T14:31:01.000Z
include/dualsynth/vs_wrapper.hpp
HomeOfAviSynthPlusEvolution/neo_Gradient_Mask
d460f6070ece54e1a8fded93f9caacb718256ceb
[ "MIT" ]
2
2020-05-31T23:48:16.000Z
2022-03-28T09:41:50.000Z
include/dualsynth/vs_wrapper.hpp
HomeOfAviSynthPlusEvolution/neo_TMedian
9b6a8931badeaa1ce7c1b692ddbf1f06620c0e93
[ "MIT" ]
2
2020-08-15T03:40:50.000Z
2021-05-30T11:48:34.000Z
/* * Copyright 2020 Xinyue Lu * * DualSynth wrapper - VapourSynth. * */ #pragma once namespace Plugin { extern const char* Identifier; extern const char* Namespace; extern const char* Description; } namespace VSInterface { const VSAPI * API; struct VSInDelegator final : InDelegator { const VSMap *_in; const VSAPI *_vsapi; int _err; void Read(const char* name, int& output) override { auto _default = output; output = static_cast<int>(_vsapi->propGetInt(_in, name, 0, &_err)); if (_err) output = _default; } void Read(const char* name, int64_t& output) override { auto _default = output; output = _vsapi->propGetInt(_in, name, 0, &_err); if (_err) output = _default; } void Read(const char* name, float& output) override { auto _default = output; output = static_cast<float>(_vsapi->propGetFloat(_in, name, 0, &_err)); if (_err) output = _default; } void Read(const char* name, double& output) override { auto _default = output; output = _vsapi->propGetFloat(_in, name, 0, &_err); if (_err) output = _default; } void Read(const char* name, bool& output) override { auto output_int = _vsapi->propGetInt(_in, name, 0, &_err); if (!_err) output = output_int != 0; } void Read(const char* name, std::string& output) override { auto output_str = _vsapi->propGetData(_in, name, 0, &_err); if (!_err) output = output_str; } void Read(const char* name, std::vector<int>& output) override { auto size = _vsapi->propNumElements(_in, name); if (size < 0) return; output.clear(); for (int i = 0; i < size; i++) output.push_back(static_cast<int>(_vsapi->propGetInt(_in, name, i, &_err))); } void Read(const char* name, std::vector<int64_t>& output) override { auto size = _vsapi->propNumElements(_in, name); if (size < 0) return; output.clear(); for (int i = 0; i < size; i++) output.push_back(_vsapi->propGetInt(_in, name, i, &_err)); } void Read(const char* name, std::vector<float>& output) override { auto size = _vsapi->propNumElements(_in, name); if (size < 0) return; output.clear(); for (int i = 0; i < size; i++) output.push_back(static_cast<float>(_vsapi->propGetFloat(_in, name, i, &_err))); } void Read(const char* name, std::vector<double>& output) override { auto size = _vsapi->propNumElements(_in, name); if (size < 0) return; output.clear(); for (int i = 0; i < size; i++) output.push_back(_vsapi->propGetFloat(_in, name, i, &_err)); } void Read(const char* name, std::vector<bool>& output) override { auto size = _vsapi->propNumElements(_in, name); if (size < 0) return; output.clear(); for (int i = 0; i < size; i++) output.push_back(_vsapi->propGetInt(_in, name, i, &_err)); } void Read(const char* name, void*& output) override { output = reinterpret_cast<void *>(_vsapi->propGetNode(_in, name, 0, &_err)); } void Free(void*& clip) override { _vsapi->freeNode(reinterpret_cast<VSNodeRef *>(clip)); clip = nullptr; } VSInDelegator(const VSMap *in, const VSAPI *vsapi) : _in(in), _vsapi(vsapi) {} }; struct VSFetchFrameFunctor final : FetchFrameFunctor { VSNodeRef *_vs_clip; VSCore *_core; const VSAPI *_vsapi; VSFrameContext *_frameCtx; VSFetchFrameFunctor(VSNodeRef *clip, VSCore *core, const VSAPI *vsapi) : _vs_clip(clip), _core(core), _vsapi(vsapi) {} DSFrame operator()(int n) override { return DSFrame(_vsapi->getFrameFilter(n, _vs_clip, _frameCtx), _core, _vsapi); } ~VSFetchFrameFunctor() override { _vsapi->freeNode(_vs_clip); } }; template<typename FilterType> void VS_CC Initialize(VSMap *in, VSMap *out, void **instanceData, VSNode *node, VSCore *core, const VSAPI *vsapi) { auto Data = reinterpret_cast<FilterType*>(*instanceData); auto output_vi = Data->GetOutputVI(); vsapi->setVideoInfo(output_vi.ToVSVI(core, vsapi), 1, node); } template<typename FilterType> void VS_CC Delete(void *instanceData, VSCore *core, const VSAPI *vsapi) { auto filter = reinterpret_cast<FilterType*>(instanceData); auto functor = reinterpret_cast<VSFetchFrameFunctor*>(filter->fetch_frame); delete functor; delete filter; } template<typename FilterType> const VSFrameRef* VS_CC GetFrame(int n, int activationReason, void **instanceData, void **frameData, VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi) { auto filter = reinterpret_cast<FilterType*>(*instanceData); auto functor = reinterpret_cast<VSFetchFrameFunctor*>(filter->fetch_frame); if (functor) functor->_frameCtx = frameCtx; std::vector<int> ref_frames; if (activationReason == VSActivationReason::arInitial) { if (functor) { ref_frames = filter->RequestReferenceFrames(n); for (auto &&i : ref_frames) vsapi->requestFrameFilter(i, functor->_vs_clip, frameCtx); } else { std::unordered_map<int, DSFrame> in_frames; in_frames[n] = DSFrame(core, vsapi); auto vs_frame = (filter->GetFrame(n, in_frames).ToVSFrame()); return vs_frame; } } else if (activationReason == VSActivationReason::arAllFramesReady) { std::unordered_map<int, DSFrame> in_frames; if (functor) { ref_frames = filter->RequestReferenceFrames(n); for (auto &&i : ref_frames) in_frames[i] = DSFrame(vsapi->getFrameFilter(i, functor->_vs_clip, frameCtx), core, vsapi); } else in_frames[n] = DSFrame(core, vsapi); auto vs_frame = (filter->GetFrame(n, in_frames).ToVSFrame()); return vs_frame; } return nullptr; } template<typename FilterType> void VS_CC Create(const VSMap *in, VSMap *out, void *userData, VSCore *core, const VSAPI *vsapi) { auto filter = new FilterType{}; auto argument = VSInDelegator(in, vsapi); try { void* clip = nullptr; VSFetchFrameFunctor* functor = nullptr; DSVideoInfo input_vi; try { argument.Read("clip", clip); if (clip) { auto vs_clip = reinterpret_cast<VSNodeRef*>(clip); functor = new VSFetchFrameFunctor(vs_clip, core, vsapi); input_vi = DSVideoInfo(vsapi->getVideoInfo(vs_clip)); } } catch(const char *) { /* No clip, source filter */ } filter->Initialize(&argument, input_vi, functor); vsapi->createFilter(in, out, filter->VSName(), Initialize<FilterType>, GetFrame<FilterType>, Delete<FilterType>, filter->VSMode(), 0, filter, core); } catch(const char *err){ char msg_buff[256]; snprintf(msg_buff, 256, "%s: %s", filter->VSName(), err); vsapi->setError(out, msg_buff); delete filter; } } template<typename FilterType> void RegisterFilter(VSRegisterFunction registerFunc, VSPlugin* vsplugin) { FilterType filter; registerFunc(filter.VSName(), filter.VSParams().c_str(), Create<FilterType>, nullptr, vsplugin); } void RegisterPlugin(VSConfigPlugin configFunc, VSPlugin* vsplugin) { configFunc(Plugin::Identifier, Plugin::Namespace, Plugin::Description, VAPOURSYNTH_API_VERSION, 1, vsplugin); } } VS_EXTERNAL_API(void) VapourSynthPluginInit(VSConfigPlugin configFunc, VSRegisterFunction registerFunc, VSPlugin* vsplugin) { VSInterface::RegisterPlugin(configFunc, vsplugin); auto filters = RegisterVSFilters(); for (auto &&RegisterFilter : filters) { RegisterFilter(registerFunc, vsplugin); } }
36.732057
164
0.650775
msg7086
487e2bcec9779c34207ff341520e18663564b64a
1,050
cpp
C++
getopt.cpp
AlexeyAkhunov/espresso
5c7a57ad6fde2fb3af46171ca1a5c78d250716e9
[ "MIT" ]
null
null
null
getopt.cpp
AlexeyAkhunov/espresso
5c7a57ad6fde2fb3af46171ca1a5c78d250716e9
[ "MIT" ]
null
null
null
getopt.cpp
AlexeyAkhunov/espresso
5c7a57ad6fde2fb3af46171ca1a5c78d250716e9
[ "MIT" ]
null
null
null
#include <iostream> /* File : getopt.c Author : Henry Spencer, University of Toronto Updated: 28 April 1984 Purpose: get option letter from argv. */ #define NullS ((char *) 0) char *optarg; /* Global argument pointer. */ int optind = 0; /* Global argv index. */ int getopt(int argc, char* argv[], const char * optstring) { int c; char *place; static char *scan = NullS; /* Private scan pointer. */ optarg = NullS; if (scan == NullS || *scan == '\0') { if (optind == 0) optind++; if (optind >= argc) return EOF; place = argv[optind]; if (place[0] != '-' || place[1] == '\0') return EOF; optind++; if (place[1] == '-' && place[2] == '\0') return EOF; scan = place+1; } c = *scan++; place = strchr(optstring, c); if (place == NullS || c == ':') { fprintf(stderr, "%s: unknown option %c\n", argv[0], c); return '?'; } if (*++place == ':') { if (*scan != '\0') { optarg = scan, scan = NullS; } else { optarg = argv[optind], optind++; } } return c; }
23.333333
60
0.53619
AlexeyAkhunov
487edebbcb3d756bf076d8013b80fd33785d2ff4
3,550
cpp
C++
9/9.51/Date.cpp
kousikpramanik/C-_Primer_5th
e21fb665f04b26193fc13f9c2c263b782aea3f3c
[ "MIT" ]
null
null
null
9/9.51/Date.cpp
kousikpramanik/C-_Primer_5th
e21fb665f04b26193fc13f9c2c263b782aea3f3c
[ "MIT" ]
2
2020-08-15T17:33:00.000Z
2021-07-05T14:18:26.000Z
9/9.51/Date.cpp
kousikpramanik/C-_Primer_5th
e21fb665f04b26193fc13f9c2c263b782aea3f3c
[ "MIT" ]
1
2020-08-15T17:24:54.000Z
2020-08-15T17:24:54.000Z
#include "Date.h" #include <stdexcept> #include <string> #include <array> #include <cctype> Date::Date(unsigned a, unsigned b, unsigned c, unsigned style) : yyyy(a), mm(b), dd(c) { switch (style) { case 1: // dd/mm/yyyy dd = a; mm = b; yyyy = c; break; case 2: // mm/dd/yyyy dd = b; mm = a; yyyy = c; break; case 3: // dd/mm/yy dd = a; mm = b; yyyy = 2000 + c; break; default: // yyyy/mm/dd // handled by the constructor initialiser list break; } if (!valid()) { throw std::invalid_argument("Invalid input."); } } // allowed formats - // 1) <month name><delim><day><delim><year> // 2) <month name><delim><year><delim><day> only when year > 31, otherwise assumes (1) // 3) <day><delim><month name><delim><year> // 4) <year><delim><month name><delim><day> only when year > 31, otherwise assumes (3) // 5) <day><delim><month><delim><year> // 6) <year><delim><month><delim><day> only when year > 31, otherwise assumes (5) // delim must be one of " ", ", ", "/" Date::Date(const std::string &inp) { std::string str(inp); for (auto &c : str) { c = std::tolower(c); } constexpr std::array<char[4], 12> monName{"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"}; constexpr char alphabet[]("qwertyuiopasdfghjklzxcvbnm"); decltype(str.size()) processed; if (str.find_first_of(alphabet) == std::string::npos) { // numeric input dd = std::stoul(str, &processed); str.erase(0, processed); erase_delim(str); mm = std::stoul(str, &processed); str.erase(0, processed); erase_delim(str); } else { // alphabetic input. mm = 13; // invalid input if month name was not found in the loop bool mfirst = false; for (decltype(monName.size()) i = 0; i != 12; ++i) { decltype(str.size()) pos = str.find(monName[i], 0); if (pos != std::string::npos) { if (pos == 0) { mfirst = true; } mm = i + 1; break; } } if (mm == 13) { throw std::invalid_argument("Invalid month name."); } if (mfirst) { str.erase(0, str.find_first_not_of(alphabet)); erase_delim(str); dd = std::stoul(str, &processed); str.erase(0, processed); erase_delim(str); } else { dd = std::stoul(str, &processed); str.erase(0, processed); erase_delim(str); str.erase(0, str.find_first_not_of(alphabet)); erase_delim(str); } } yyyy = std::stoul(str); if (dd > 31) { auto temp = dd; dd = yyyy; yyyy = temp; } if (!valid()) { throw std::invalid_argument("Invalid input."); } } bool Date::valid() { constexpr std::array<int, 12> dInM{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if (mm == 0 || mm > 12) { return false; } if (leap_year() && mm == 2 && dd != 0 && dd <= 29) { return true; } return (dd != 0 && dd <= dInM[mm - 1]); } void Date::erase_delim(std::string &str) { auto delim = str.at(0); if (delim == ' ' || delim == '/') { str.erase(0, 1); } else if (delim == ',') { str.erase(0, 2); } else { throw std::invalid_argument("Invalid delimiter."); } }
30.34188
115
0.498592
kousikpramanik
487f422835613b034bde30d95dae871b83bc2c2f
7,152
hpp
C++
include/UnityEngine/TestTools/TestRunner/GUI/SynchronousFilter.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/UnityEngine/TestTools/TestRunner/GUI/SynchronousFilter.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/UnityEngine/TestTools/TestRunner/GUI/SynchronousFilter.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: NUnit.Framework.Interfaces.ITestFilter #include "NUnit/Framework/Interfaces/ITestFilter.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine::TestTools::TestRunner::GUI namespace UnityEngine::TestTools::TestRunner::GUI { } // Forward declaring namespace: NUnit::Framework::Interfaces namespace NUnit::Framework::Interfaces { // Forward declaring type: TNode class TNode; // Forward declaring type: ITest class ITest; } // Completed forward declares // Type namespace: UnityEngine.TestTools.TestRunner.GUI namespace UnityEngine::TestTools::TestRunner::GUI { // Forward declaring type: SynchronousFilter class SynchronousFilter; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter); DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter*, "UnityEngine.TestTools.TestRunner.GUI", "SynchronousFilter"); // Type namespace: UnityEngine.TestTools.TestRunner.GUI namespace UnityEngine::TestTools::TestRunner::GUI { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: UnityEngine.TestTools.TestRunner.GUI.SynchronousFilter // [TokenAttribute] Offset: FFFFFFFF class SynchronousFilter : public ::Il2CppObject/*, public ::NUnit::Framework::Interfaces::ITestFilter*/ { public: // Nested type: ::UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter::$$c class $$c; // Creating interface conversion operator: operator ::NUnit::Framework::Interfaces::ITestFilter operator ::NUnit::Framework::Interfaces::ITestFilter() noexcept { return *reinterpret_cast<::NUnit::Framework::Interfaces::ITestFilter*>(this); } // public NUnit.Framework.Interfaces.TNode ToXml(System.Boolean recursive) // Offset: 0x1950EC4 ::NUnit::Framework::Interfaces::TNode* ToXml(bool recursive); // public NUnit.Framework.Interfaces.TNode AddToXml(NUnit.Framework.Interfaces.TNode parentNode, System.Boolean recursive) // Offset: 0x1950F2C ::NUnit::Framework::Interfaces::TNode* AddToXml(::NUnit::Framework::Interfaces::TNode* parentNode, bool recursive); // public System.Boolean Pass(NUnit.Framework.Interfaces.ITest test) // Offset: 0x1950F88 bool Pass(::NUnit::Framework::Interfaces::ITest* test); // public System.Boolean IsExplicitMatch(NUnit.Framework.Interfaces.ITest test) // Offset: 0x19517E0 bool IsExplicitMatch(::NUnit::Framework::Interfaces::ITest* test); // public System.Void .ctor() // Offset: 0x19509D4 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static SynchronousFilter* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<SynchronousFilter*, creationType>())); } }; // UnityEngine.TestTools.TestRunner.GUI.SynchronousFilter #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter::ToXml // Il2CppName: ToXml template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::NUnit::Framework::Interfaces::TNode* (UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter::*)(bool)>(&UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter::ToXml)> { static const MethodInfo* get() { static auto* recursive = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter*), "ToXml", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{recursive}); } }; // Writing MetadataGetter for method: UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter::AddToXml // Il2CppName: AddToXml template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::NUnit::Framework::Interfaces::TNode* (UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter::*)(::NUnit::Framework::Interfaces::TNode*, bool)>(&UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter::AddToXml)> { static const MethodInfo* get() { static auto* parentNode = &::il2cpp_utils::GetClassFromName("NUnit.Framework.Interfaces", "TNode")->byval_arg; static auto* recursive = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter*), "AddToXml", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{parentNode, recursive}); } }; // Writing MetadataGetter for method: UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter::Pass // Il2CppName: Pass template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter::*)(::NUnit::Framework::Interfaces::ITest*)>(&UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter::Pass)> { static const MethodInfo* get() { static auto* test = &::il2cpp_utils::GetClassFromName("NUnit.Framework.Interfaces", "ITest")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter*), "Pass", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{test}); } }; // Writing MetadataGetter for method: UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter::IsExplicitMatch // Il2CppName: IsExplicitMatch template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter::*)(::NUnit::Framework::Interfaces::ITest*)>(&UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter::IsExplicitMatch)> { static const MethodInfo* get() { static auto* test = &::il2cpp_utils::GetClassFromName("NUnit.Framework.Interfaces", "ITest")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter*), "IsExplicitMatch", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{test}); } }; // Writing MetadataGetter for method: UnityEngine::TestTools::TestRunner::GUI::SynchronousFilter::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
62.191304
293
0.739793
RedBrumbler
487f85e84100134aaad3a16abd62bef51302e3bd
5,137
cc
C++
google/cloud/pubsub/internal/default_subscription_batch_source.cc
orinem/google-cloud-cpp
c43f73e9abeb2b9d8a6e99f7d9750cba37f2f6b1
[ "Apache-2.0" ]
null
null
null
google/cloud/pubsub/internal/default_subscription_batch_source.cc
orinem/google-cloud-cpp
c43f73e9abeb2b9d8a6e99f7d9750cba37f2f6b1
[ "Apache-2.0" ]
null
null
null
google/cloud/pubsub/internal/default_subscription_batch_source.cc
orinem/google-cloud-cpp
c43f73e9abeb2b9d8a6e99f7d9750cba37f2f6b1
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/pubsub/internal/default_subscription_batch_source.h" #include "google/cloud/internal/async_retry_loop.h" namespace google { namespace cloud { namespace pubsub_internal { inline namespace GOOGLE_CLOUD_CPP_PUBSUB_NS { using google::cloud::internal::AsyncRetryLoop; using google::cloud::internal::Idempotency; void DefaultSubscriptionBatchSource::Shutdown() {} future<Status> DefaultSubscriptionBatchSource::AckMessage( std::string const& ack_id, std::size_t) { google::pubsub::v1::AcknowledgeRequest request; request.set_subscription(subscription_full_name_); request.add_ack_ids(ack_id); auto& stub = stub_; return AsyncRetryLoop( retry_policy_->clone(), backoff_policy_->clone(), Idempotency::kIdempotent, cq_, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::pubsub::v1::AcknowledgeRequest const& request) { return stub->AsyncAcknowledge(cq, std::move(context), request); }, request, __func__); } future<Status> DefaultSubscriptionBatchSource::NackMessage( std::string const& ack_id, std::size_t) { google::pubsub::v1::ModifyAckDeadlineRequest request; request.set_subscription(subscription_full_name_); request.add_ack_ids(ack_id); request.set_ack_deadline_seconds(0); auto& stub = stub_; return AsyncRetryLoop( retry_policy_->clone(), backoff_policy_->clone(), Idempotency::kIdempotent, cq_, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::pubsub::v1::ModifyAckDeadlineRequest const& request) { return stub->AsyncModifyAckDeadline(cq, std::move(context), request); }, request, __func__); } future<Status> DefaultSubscriptionBatchSource::BulkNack( std::vector<std::string> ack_ids, std::size_t) { google::pubsub::v1::ModifyAckDeadlineRequest request; request.set_subscription(subscription_full_name_); for (auto& id : ack_ids) { request.add_ack_ids(std::move(id)); } request.set_ack_deadline_seconds(0); auto& stub = stub_; return AsyncRetryLoop( retry_policy_->clone(), backoff_policy_->clone(), Idempotency::kIdempotent, cq_, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::pubsub::v1::ModifyAckDeadlineRequest const& request) { return stub->AsyncModifyAckDeadline(cq, std::move(context), request); }, request, __func__); } future<Status> DefaultSubscriptionBatchSource::ExtendLeases( std::vector<std::string> ack_ids, std::chrono::seconds extension) { google::pubsub::v1::ModifyAckDeadlineRequest request; request.set_subscription(subscription_full_name_); auto const actual_extension = [extension] { // The service does not allow extending the deadline by more than 10 // minutes. auto constexpr kMaximumAckDeadline = std::chrono::seconds(600); if (extension < std::chrono::seconds(0)) return std::chrono::seconds(0); if (extension > kMaximumAckDeadline) return kMaximumAckDeadline; return extension; }(); request.set_ack_deadline_seconds( static_cast<std::int32_t>(actual_extension.count())); for (auto& a : ack_ids) request.add_ack_ids(std::move(a)); auto& stub = stub_; return AsyncRetryLoop( retry_policy_->clone(), backoff_policy_->clone(), Idempotency::kIdempotent, cq_, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::pubsub::v1::ModifyAckDeadlineRequest const& request) { return stub->AsyncModifyAckDeadline(cq, std::move(context), request); }, request, __func__); } future<StatusOr<google::pubsub::v1::PullResponse>> DefaultSubscriptionBatchSource::Pull(std::int32_t max_count) { google::pubsub::v1::PullRequest request; request.set_subscription(subscription_full_name_); request.set_max_messages(max_count); auto& stub = stub_; return AsyncRetryLoop( retry_policy_->clone(), backoff_policy_->clone(), Idempotency::kIdempotent, cq_, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::pubsub::v1::PullRequest const& request) { return stub->AsyncPull(cq, std::move(context), request); }, request, __func__); } } // namespace GOOGLE_CLOUD_CPP_PUBSUB_NS } // namespace pubsub_internal } // namespace cloud } // namespace google
38.916667
77
0.716177
orinem
4880514cdf89664a505f0c4cab4368b7dcea042e
2,736
cpp
C++
keyvi/3rdparty/msgpack-c/example/boost/msgpack_variant_capitalize.cpp
vvucetic/keyvi
e6f02373350fea000aa3d20be9cc1d0ec09441f7
[ "Apache-2.0" ]
147
2015-10-06T19:10:01.000Z
2021-08-19T07:52:02.000Z
keyvi/3rdparty/msgpack-c/example/boost/msgpack_variant_capitalize.cpp
vvucetic/keyvi
e6f02373350fea000aa3d20be9cc1d0ec09441f7
[ "Apache-2.0" ]
148
2015-10-06T09:24:56.000Z
2018-12-08T08:42:54.000Z
keyvi/3rdparty/msgpack-c/example/boost/msgpack_variant_capitalize.cpp
vvucetic/keyvi
e6f02373350fea000aa3d20be9cc1d0ec09441f7
[ "Apache-2.0" ]
34
2015-10-09T06:55:52.000Z
2021-01-05T18:43:57.000Z
// MessagePack for C++ example // // Copyright (C) 2015 KONDO Takatoshi // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #include <string> #include <sstream> #include <iostream> #include <algorithm> #include <cctype> #include <msgpack.hpp> struct user { std::string name; int age; std::string address; MSGPACK_DEFINE(name, age, address); }; struct proc:boost::static_visitor<void> { void operator()(std::string& v) const { std::cout << " match std::string& v" << std::endl; std::cout << " v: " << v << std::endl; std::cout << " capitalize" << std::endl; for (std::string::iterator it = v.begin(), end = v.end(); it != end; ++it) { *it = std::toupper(*it); } } void operator()(std::vector<msgpack::type::variant>& v) const { std::cout << "match vector (msgpack::type::ARRAY)" << std::endl; std::vector<msgpack::type::variant>::iterator it = v.begin(); std::vector<msgpack::type::variant>::const_iterator end = v.end(); for (; it != end; ++it) { boost::apply_visitor(*this, *it); } } template <typename T> void operator()(T const&) const { std::cout << " match others" << std::endl; } }; void print(std::string const& buf) { for (std::string::const_iterator it = buf.begin(), end = buf.end(); it != end; ++it) { std::cout << std::setw(2) << std::hex << std::setfill('0') << (static_cast<int>(*it) & 0xff) << ' '; } std::cout << std::dec << std::endl; } int main() { std::stringstream ss1; user u; u.name = "Takatoshi Kondo"; u.age = 42; u.address = "Tokyo, JAPAN"; std::cout << "Packing object." << std::endl; msgpack::pack(ss1, u); print(ss1.str()); msgpack::unpacked unp1 = msgpack::unpack(ss1.str().data(), ss1.str().size()); msgpack::object const& obj1 = unp1.get(); std::cout << "Unpacked msgpack object." << std::endl; std::cout << obj1 << std::endl; msgpack::type::variant v = obj1.as<msgpack::type::variant>(); std::cout << "Applying proc..." << std::endl; boost::apply_visitor(proc(), v); std::stringstream ss2; std::cout << "Packing modified object." << std::endl; msgpack::pack(ss2, v); print(ss2.str()); msgpack::unpacked unp2 = msgpack::unpack(ss2.str().data(), ss2.str().size()); msgpack::object const& obj2 = unp2.get(); std::cout << "Modified msgpack object." << std::endl; std::cout << obj2 << std::endl; }
28.8
81
0.550073
vvucetic
488164e55a149881e57cb01d4a1487931c57f1e4
291
hh
C++
src/Zynga/Framework/Dynamic/V1/Mocks/StaticClass.hh
chintan-j-patel/zynga-hacklang-framework
d9893b8873e3c8c7223772fd3c94d2531760172a
[ "MIT" ]
19
2018-04-23T09:30:48.000Z
2022-03-06T21:35:18.000Z
src/Zynga/Framework/Dynamic/V1/Mocks/StaticClass.hh
chintan-j-patel/zynga-hacklang-framework
d9893b8873e3c8c7223772fd3c94d2531760172a
[ "MIT" ]
22
2017-11-27T23:39:25.000Z
2019-08-09T08:56:57.000Z
src/Zynga/Framework/Dynamic/V1/Mocks/StaticClass.hh
chintan-j-patel/zynga-hacklang-framework
d9893b8873e3c8c7223772fd3c94d2531760172a
[ "MIT" ]
28
2017-11-16T20:53:56.000Z
2021-01-04T11:13:17.000Z
<?hh // strict namespace Zynga\Framework\Dynamic\V1\Mocks; class StaticClass { public static function testFunction(): bool { return true; } public static function testFunctionWithParams( string $param1, int $param2, ): string { return $param1.":".$param2; } }
15.315789
48
0.666667
chintan-j-patel
4888983725aab70b59e29dcc1ff408874f01b402
1,227
cpp
C++
Game/Source/Crate.cpp
KuronoaScarlet/ProjectII
5038d4366f39f26ec70cbebaf06d72e7c83e52a3
[ "MIT" ]
null
null
null
Game/Source/Crate.cpp
KuronoaScarlet/ProjectII
5038d4366f39f26ec70cbebaf06d72e7c83e52a3
[ "MIT" ]
1
2021-02-25T11:10:15.000Z
2021-04-18T16:48:04.000Z
Game/Source/Crate.cpp
KuronoaScarlet/ProjectII
5038d4366f39f26ec70cbebaf06d72e7c83e52a3
[ "MIT" ]
null
null
null
#include "Crate.h" #include "App.h" #include "Render.h" #include "Collisions.h" #include "Collider.h" #include "FadeToBlack.h" #include "Scene1.h" #include "Title.h" #include "Map.h" #include "Audio.h" #include "EntityManager.h" #include "Fonts.h" #include "Defs.h" #include "DialogSystem.h" Crate::Crate(Module* listener, fPoint position, SDL_Texture* texture, Type type) : Entity(listener, position, texture, type) { idleAnimation.loop = true; idleAnimation.PushBack({ 797,150, 28, 39 }); currentAnimation = &idleAnimation; currentMoodAnimation = &moodAnimation; collider = app->collisions->AddCollider(SDL_Rect({ (int)position.x, (int)position.y, 30, 46 }), Collider::Type::NPC, listener); } bool Crate::Start() { return true; } bool Crate::Update(float dt) { currentAnimation->Update(); currentMoodAnimation->Update(); return true; } bool Crate::Draw() { SDL_Rect rect = currentAnimation->GetCurrentFrame(); app->render->DrawTexture(texture, position.x, position.y, &rect); return true; } bool Crate::Interaction() { app->sceneManager->crate = true; pendingToDelete = true; collider->pendingToDelete = true; return true; } void Crate::Collision(Collider* coll) { } void Crate::CleanUp() { }
18.044118
128
0.713121
KuronoaScarlet
4898542f609201008c625cf881d791ea98b39b58
41,242
cpp
C++
Src/Analysis/RSMSobol2Analyzer.cpp
lbianchi-lbl/psuade-lite
09d7ca75aba8a9e31e1fb5c3e134af046fca3460
[ "Apache-2.0" ]
14
2017-10-31T17:52:38.000Z
2022-03-04T05:16:56.000Z
Src/Analysis/RSMSobol2Analyzer.cpp
lbianchi-lbl/psuade-lite
09d7ca75aba8a9e31e1fb5c3e134af046fca3460
[ "Apache-2.0" ]
3
2021-03-10T22:10:32.000Z
2022-01-14T04:31:05.000Z
Src/Analysis/RSMSobol2Analyzer.cpp
lbianchi-lbl/psuade-lite
09d7ca75aba8a9e31e1fb5c3e134af046fca3460
[ "Apache-2.0" ]
12
2017-12-13T01:08:17.000Z
2020-11-26T22:58:08.000Z
// ************************************************************************ // Copyright (c) 2007 Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the PSUADE team. // All rights reserved. // // Please see the COPYRIGHT and LICENSE file for the copyright notice, // disclaimer, contact information and the GNU Lesser General Public License. // // PSUADE 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) version 2.1 dated February 1999. // // PSUADE 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 terms and conditions of the GNU Lesser // General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // ************************************************************************ // Functions for the class RSMSobol2Analyzer // (Sobol' second order sensitivity analysis - with response surface) // AUTHOR : CHARLES TONG // DATE : 2006 // ************************************************************************ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <vector> #include "PsuadeUtil.h" #include "sysdef.h" #include "Vector.h" #include "Matrix.h" #include "Psuade.h" #include "FuncApprox.h" #include "Sampling.h" #include "RSConstraints.h" #include "PDFManager.h" #include "pData.h" #include "PsuadeData.h" #include "PsuadeConfig.h" #include "RSMSobol2Analyzer.h" #include "PrintingTS.h" // ************************************************************************ // constructor // ------------------------------------------------------------------------ RSMSobol2Analyzer::RSMSobol2Analyzer() : Analyzer(),nInputs_(0),outputMean_(0), outputStd_(0), vces_(0), ecvs_(0) { setName("RSMSOBOL2"); } // ************************************************************************ // destructor // ------------------------------------------------------------------------ RSMSobol2Analyzer::~RSMSobol2Analyzer() { if (vces_ != NULL) delete [] vces_; if (ecvs_ != NULL) delete [] ecvs_; } // ************************************************************************ // perform analysis (this is intended for library calls) // ------------------------------------------------------------------------ void RSMSobol2Analyzer::analyze(int nInps, int nSamp, double *lbs, double *ubs, double *X, double *Y) { int ii, *pdfFlags; double *inputMeans, *inputStdevs; aData adata; adata.nInputs_ = nInps; adata.nOutputs_ = 1; adata.nSamples_ = nSamp; adata.iLowerB_ = lbs; adata.iUpperB_ = ubs; adata.sampleInputs_ = X; adata.sampleOutputs_ = Y; adata.outputID_ = 0; adata.printLevel_ = 0; pdfFlags = new int[nInps]; inputMeans = new double[nInps]; inputStdevs = new double[nInps]; checkAllocate(inputStdevs, "inputStdevs in RSMSobol2::analyze (lib)"); for (ii = 0; ii < nInps; ii++) { pdfFlags[ii] = 0; inputMeans[ii] = 0; inputStdevs[ii] = 0; } adata.inputPDFs_ = pdfFlags; adata.inputMeans_ = inputMeans; adata.inputStdevs_ = inputStdevs; analyze2(adata); } // ************************************************************************ // perform analysis // ------------------------------------------------------------------------ double RSMSobol2Analyzer::analyze(aData &adata) { int nInputs, nOutputs, nSamples, ii, jj, kk, status, outputID; int nSubSamples=100, iL, sCnt, *SS, nLevels=100, noPDF=1, pdfNull=0; int ii2, iR, currNLevels, nSamp, printLevel, *pdfFlags, rstype; int *bins, totalCnt, *pdfFlags1, *pdfFlags2, selectedInput=-1; double *xLower, *xUpper, *X, *Y, *Y2, *YY, *cLower, *cUpper, *XX; double *oneSamplePt, *means, *vars, vce, ddata, variance, *ZZ; double dmean, ecv, *inputMeans, *inputStdevs, *mSamplePts; double *samplePts2D, *inputMeans1, *inputMeans2, *inputStdevs1; double *inputStdevs2; char pString[500], *cString, winput[500], winput2[500]; PsuadeData *ioPtr; FuncApprox *faPtr; RSConstraints *constrPtr; psVector vecIn, vecOut, vecUB, vecLB; pData pCorMat, pPDF; psMatrix *corMatp, corMat; PDFManager *pdfman, *pdfman1, *pdfman2; Sampling *sampler; printAsterisks(PL_INFO, 0); printOutTS(PL_INFO,"* RS-based Second Order Sobol' Indices \n"); printEquals(PL_INFO, 0); printOutTS(PL_INFO,"* TO GAIN ACCESS TO DIFFERENT OPTIONS: SET\n"); printOutTS(PL_INFO,"*\n"); printOutTS(PL_INFO, "* - ana_expert mode to finetune RSMSobol2 parameters \n"); printOutTS(PL_INFO, "* (e.g. sample size for integration can be adjusted).\n"); printOutTS(PL_INFO,"* - rs_expert mode to finetune response surface\n"); printOutTS(PL_INFO, "* - printlevel to 1 or higher to display more information\n"); printEquals(PL_INFO, 0); nInputs = adata.nInputs_; nInputs_ = nInputs; nOutputs = adata.nOutputs_; nSamples = adata.nSamples_; xLower = adata.iLowerB_; xUpper = adata.iUpperB_; X = adata.sampleInputs_; Y2 = adata.sampleOutputs_; outputID = adata.outputID_; ioPtr = adata.ioPtr_; printLevel = adata.printLevel_; pdfFlags = adata.inputPDFs_; inputMeans = adata.inputMeans_; inputStdevs = adata.inputStdevs_; if (inputMeans == NULL || pdfFlags == NULL || inputStdevs == NULL) { pdfNull = 1; pdfFlags = new int[nInputs]; inputMeans = new double[nInputs]; inputStdevs = new double[nInputs]; checkAllocate(inputStdevs, "inputStdevs in RSMSobol2::analyze"); for (ii = 0; ii < nInputs; ii++) { pdfFlags[ii] = 0; inputMeans[ii] = 0; inputStdevs[ii] = 0; } } if (pdfFlags != NULL) { for (ii = 0; ii < nInputs; ii++) if (pdfFlags[ii] != 0) noPDF = 0; } if (noPDF == 1) printOutTS(PL_INFO,"* RSMSobol2 INFO: all uniform distributions.\n"); else { printOutTS(PL_INFO, "RSMSobol2 INFO: non-uniform distributions detected -\n"); printOutTS(PL_INFO," will be used in this analysis.\n"); } if (nInputs <= 1 || nSamples <= 0 || nOutputs <= 0) { printOutTS(PL_ERROR,"RSMSobol2 ERROR: invalid arguments.\n"); printOutTS(PL_ERROR," nInputs = %d\n", nInputs); printOutTS(PL_ERROR," nOutputs = %d\n", nOutputs); printOutTS(PL_ERROR," nSamples = %d\n", nSamples); return PSUADE_UNDEFINED; } if (nInputs <= 2) { printOutTS(PL_ERROR, "RSMSobol2 ERROR: no need for this analysis (nInputs<=2).\n"); return PSUADE_UNDEFINED; } if (outputID < 0 || outputID >= nOutputs) { printOutTS(PL_ERROR, "RSMSobol2 ERROR: invalid outputID (%d).\n",outputID); return PSUADE_UNDEFINED; } if (ioPtr == NULL) { printOutTS(PL_INFO, "RSMSobol2 INFO: no data object (PsuadeData) found.\n"); printOutTS(PL_INFO," Several features will be turned off.\n"); corMatp = new psMatrix(); corMatp->setDim(nInputs, nInputs); for (ii = 0; ii < nInputs; ii++) corMatp->setEntry(ii,ii,1.0e0); } else { ioPtr->getParameter("input_cor_matrix", pCorMat); corMatp = (psMatrix *) pCorMat.psObject_; for (ii = 0; ii < nInputs; ii++) { for (jj = 0; jj < ii; jj++) { if (corMatp->getEntry(ii,jj) != 0.0) { printOutTS(PL_INFO, "RSMSobol2 INFO: this method cannot handle correlated\n"); printOutTS(PL_INFO, " inputs using joint PDFs. PSUADE will try\n"); printOutTS(PL_INFO, " a variant of this method, or you can re-run\n"); printOutTS(PL_INFO, " using the group variance-based method.\n"); if (pdfNull == 1) { delete [] pdfFlags; delete [] inputMeans; delete [] inputStdevs; } return analyze2(adata); } } if (pdfFlags[ii] == PSUADE_PDF_SAMPLE) { printOutTS(PL_ERROR, "RSMSobol2 INFO: this method cannot handle S PDF type.\n"); printOutTS(PL_INFO, " PSUADE will try a variant of this method.\n"); if (pdfNull == 1) { delete [] pdfFlags; delete [] inputMeans; delete [] inputStdevs; } return analyze2(adata); } } } status = 0; for (ii = 0; ii < nSamples; ii++) if (Y2[nOutputs*ii+outputID] > 0.9*PSUADE_UNDEFINED) status = 1; if (status == 1) { printOutTS(PL_ERROR, "RSMSobol2 ERROR: Some outputs are undefined. Prune\n"); printOutTS(PL_ERROR, " the undefined sample points first.\n"); return PSUADE_UNDEFINED; } if (ioPtr != NULL) { constrPtr = new RSConstraints(); constrPtr->genConstraints(ioPtr); } else { constrPtr = NULL; printf("RSMSobolTSI INFO: no PsuadeData ==> no constraints.\n"); } if (ioPtr == NULL) { printf("Select response surface. Options are: \n"); writeFAInfo(0); strcpy(pString, "Choose response surface: "); rstype = getInt(0, PSUADE_NUM_RS, pString); faPtr = genFA(rstype, nInputs, 0, nSamples); } else faPtr = genFAInteractive(ioPtr, 0); faPtr->setBounds(xLower, xUpper); Y = new double[nSamples]; checkAllocate(Y, "Y in RSMSobol2::analyze"); for (ii = 0; ii < nSamples; ii++) Y[ii] = Y2[ii*nOutputs+outputID]; status = faPtr->initialize(X, Y); printAsterisks(PL_INFO, 0); if (psAnaExpertMode_ == 1) { printOutTS(PL_INFO, "* RSMSobol2 generates a mesh of size K x K for every\n"); printOutTS(PL_INFO, "* pair of inputs and then creates a sample of size\n"); printOutTS(PL_INFO, "* M for each mesh point. The total sample size is:\n"); printOutTS(PL_INFO, "* N = M * K * K * nInputs * (nInputs - 1) / 2.\n"); printOutTS(PL_INFO,"* NOW, nInputs = %d\n", nInputs); printOutTS(PL_INFO,"* Please select M and K below.\n"); printOutTS(PL_INFO,"* Recommendation: K x K >> M.\n"); printOutTS(PL_INFO,"* NOTE: large M and K can take a long time.\n"); printOutTS(PL_INFO,"* Default M = %d\n", nSubSamples); printOutTS(PL_INFO,"* Default K = %d\n", nLevels); printEquals(PL_INFO, 0); sprintf(pString,"Enter M (suggestion: 100 - 1000) : "); nSubSamples = getInt(100, 1000, pString); sprintf(pString, "Enter K (suggestion: 50 - 500) : "); nLevels = getInt(50, 500, pString); } else { nSubSamples = 100; nLevels = 100; if (psConfig_ != NULL) { cString = psConfig_->getParameter("RSMSobol2_nsubsamples"); if (cString != NULL) { sscanf(cString, "%s %s %d", winput, winput2, &nSubSamples); if (nSubSamples < 100) { printOutTS(PL_INFO, "RSMSobol2 INFO: nSubSamples should be >= 100.\n"); nSubSamples = 100; } else { printOutTS(PL_INFO, "RSMSobol2 INFO: nSubSamples = %d (config).\n", nSubSamples); } } cString = psConfig_->getParameter("RSMSobol2_nlevels"); if (cString != NULL) { sscanf(cString, "%s %s %d", winput, winput2, &nLevels); if (nLevels < 100) { printOutTS(PL_INFO, "RSMSobol2 INFO: nLevels should be >= 100.\n"); nLevels = 100; } else { printOutTS(PL_INFO, "RSMSobol2 INFO: nLevels = %d (config).\n",nLevels); } } } if (printLevel > 0) { printOutTS(PL_INFO,"RSMSobol2: default M = %d.\n", nSubSamples); printOutTS(PL_INFO,"RSMSobol2: default K = %d.\n", nLevels); printOutTS(PL_INFO, "To change these settings, re-run with ana_expert mode on.\n"); } } printEquals(PL_INFO, 0); nSamp = 100000; printOutTS(PL_INFO, "RSMSobol2 INFO: creating a sample for basic statistics.\n"); printOutTS(PL_INFO," sample size = %d\n", nSamp); XX = new double[nSamp*nInputs]; YY = new double[nSamp]; checkAllocate(YY, "YY in RSMSobol2::analyze"); if (noPDF == 0) { pdfman = new PDFManager(); pdfman->initialize(nInputs,pdfFlags,inputMeans, inputStdevs,*corMatp,NULL,NULL); vecLB.load(nInputs, xLower); vecUB.load(nInputs, xUpper); vecOut.setLength(nSamp*nInputs); pdfman->genSample(nSamp, vecOut, vecLB, vecUB); for (ii = 0; ii < nSamp*nInputs; ii++) XX[ii] = vecOut[ii]; delete pdfman; } else { if (nInputs < 51) sampler = SamplingCreateFromID(PSUADE_SAMP_LPTAU); else sampler = SamplingCreateFromID(PSUADE_SAMP_LHS); sampler->setInputBounds(nInputs, xLower, xUpper); sampler->setOutputParams(1); sampler->setSamplingParams(nSamp, 1, 1); sampler->initialize(0); SS = new int[nSamp]; checkAllocate(SS, "SS in RSMSobol2::analyze"); sampler->getSamples(nSamp, nInputs, 1, XX, YY, SS); delete [] SS; delete sampler; } printOutTS(PL_INFO, "RSMSobol2: running the sample with response surface...\n"); faPtr->evaluatePoint(nSamp, XX, YY); printOutTS(PL_INFO, "RSMSobol2: done running the sample with response surface.\n"); for (ii = 0; ii < nSamp; ii++) { oneSamplePt = &(XX[ii*nInputs]); status = 1; if (constrPtr != NULL) ddata = constrPtr->evaluate(oneSamplePt,YY[ii],status); if (status == 0) YY[ii] = PSUADE_UNDEFINED; } dmean = 0.0; sCnt = 0; for (ii = 0; ii < nSamp; ii++) { if (YY[ii] != PSUADE_UNDEFINED) { dmean += YY[ii]; sCnt++; } } if (sCnt > 1) dmean /= (double) sCnt; else { printOutTS(PL_ERROR, "RSMSobol2 ERROR: too few samples that satisify\n"); printOutTS(PL_ERROR, "constraints (%d out of %d).\n",sCnt,nSamp); delete [] XX; delete [] YY; delete faPtr; if (ioPtr == NULL) delete corMatp; if (constrPtr != NULL) delete constrPtr; if (pdfNull == 1) { delete [] pdfFlags; delete [] inputMeans; delete [] inputStdevs; } return PSUADE_UNDEFINED; } variance = 0.0; for (ii = 0; ii < nSamp; ii++) { if (YY[ii] != PSUADE_UNDEFINED) variance += (YY[ii] - dmean) * (YY[ii] - dmean) ; } variance /= (double) sCnt; printOutTS(PL_INFO, "RSMSobol2: sample mean (based on N = %d) = %10.3e\n", sCnt, dmean); printOutTS(PL_INFO, "RSMSobol2: sample std dev (based on N = %d) = %10.3e\n", sCnt, sqrt(variance)); if (variance == 0.0) variance = 1.0; delete [] XX; delete [] YY; //save mean & std outputMean_ = dmean; outputStd_ = sqrt(variance); cLower = new double[nInputs]; cUpper = new double[nInputs]; nSamp = nSubSamples; XX = new double[nSubSamples*nInputs]; YY = new double[nSubSamples]; means = new double[nLevels*nLevels]; vars = new double[nLevels*nLevels]; bins = new int[nLevels*nLevels]; pdfFlags1 = new int[2]; inputMeans1 = new double[2]; inputStdevs1 = new double[2]; pdfFlags2 = new int[nInputs-2]; inputMeans2 = new double[nInputs-2]; inputStdevs2 = new double[nInputs-2]; samplePts2D = new double[nLevels*nLevels*2]; mSamplePts = new double[nInputs*nSubSamples]; checkAllocate(mSamplePts, "mSamplePts in RSMSobol2::analyze"); pData *pPtr = NULL; if (ioPtr != NULL) { pPtr = ioPtr->getAuxData(); pPtr->nDbles_ = nInputs * nInputs; pPtr->dbleArray_ = new double[nInputs * nInputs]; for (ii = 0; ii < nInputs*nInputs; ii++) pPtr->dbleArray_[ii] = 0.0; pPtr->dbleData_ = variance; } printAsterisks(PL_INFO, 0); vces_ = new double[nInputs*nInputs]; ecvs_ = new double[nInputs*nInputs]; for (ii = 0; ii < nInputs; ii++) { for (ii2 = 0; ii2 < nInputs; ii2++) { vce = 0.0; if (ii2 <= ii) continue; if (selectedInput != -1 && ii != selectedInput && ii2 != selectedInput) continue; printOutTS(PL_DETAIL, "RSMSobol2: processing input pair %d, %d\n", ii+1, ii2+1); currNLevels = nLevels / 2; for (iR = 0; iR < 2; iR++) { printOutTS(PL_DETAIL, "RSMSobol2: processing refinement %d (4)\n",iR+1); cLower[0] = xLower[ii]; cUpper[0] = xUpper[ii]; cLower[1] = xLower[ii2]; cUpper[1] = xUpper[ii2]; if (noPDF == 0) { corMat.setDim(2,2); corMat.setEntry(0, 0, corMatp->getEntry(ii,ii)); corMat.setEntry(1, 1, corMatp->getEntry(ii2,ii2)); pdfFlags1[0] = pdfFlags[ii]; pdfFlags1[1] = pdfFlags[ii2]; inputMeans1[0] = inputMeans[ii]; inputMeans1[1] = inputMeans[ii2]; inputStdevs1[0] = inputStdevs[ii]; inputStdevs1[1] = inputStdevs[ii2]; pdfman1 = new PDFManager(); pdfman1->initialize(2,pdfFlags1,inputMeans1, inputStdevs1,corMat,NULL,NULL); vecLB.load(2, cLower); vecUB.load(2, cUpper); vecOut.setLength(currNLevels*2); pdfman1->genSample(currNLevels*currNLevels,vecOut,vecLB,vecUB); for (jj = 0; jj < currNLevels*currNLevels*2; jj++) samplePts2D[jj] = vecOut[jj]; delete pdfman1; } else { sampler = SamplingCreateFromID(PSUADE_SAMP_LHS); sampler->setInputBounds(2, cLower, cUpper); sampler->setOutputParams(1); sampler->setSamplingParams(currNLevels*currNLevels, 1, 0); sampler->initialize(0); SS = new int[currNLevels*currNLevels]; ZZ = new double[currNLevels*currNLevels]; checkAllocate(ZZ, "ZZ in RSMSobol2::analyze"); sampler->getSamples(currNLevels*currNLevels,2,1, samplePts2D,ZZ,SS); delete [] SS; delete [] ZZ; delete sampler; } if (noPDF == 0) { corMat.setDim(nInputs-2, nInputs-2); for (jj = 0; jj < ii; jj++) { cLower[jj] = xLower[jj]; cUpper[jj] = xUpper[jj]; corMat.setEntry(jj, jj, corMatp->getEntry(jj,jj)); pdfFlags2[jj] = pdfFlags[jj]; inputMeans2[jj] = inputMeans[jj]; inputStdevs2[jj] = inputStdevs[jj]; } for (jj = ii+1; jj < ii2; jj++) { cLower[jj-1] = xLower[jj]; cUpper[jj-1] = xUpper[jj]; corMat.setEntry(jj-1, jj-1, corMatp->getEntry(jj,jj)); pdfFlags2[jj-1] = pdfFlags[jj]; inputMeans2[jj-1] = inputMeans[jj]; inputStdevs2[jj-1] = inputStdevs[jj]; } for (jj = ii2+1; jj < nInputs; jj++) { cLower[jj-2] = xLower[jj]; cUpper[jj-2] = xUpper[jj]; corMat.setEntry(jj-2, jj-2, corMatp->getEntry(jj,jj)); pdfFlags2[jj-2] = pdfFlags[jj]; inputMeans2[jj-2] = inputMeans[jj]; inputStdevs2[jj-2] = inputStdevs[jj]; } pdfman2 = new PDFManager(); pdfman2->initialize(nInputs-2,pdfFlags2,inputMeans2, inputStdevs2,corMat,NULL,NULL); vecLB.load(nInputs-2, cLower); vecUB.load(nInputs-2, cUpper); vecOut.setLength(nSubSamples*(nInputs-2)); pdfman2->genSample(nSubSamples, vecOut, vecLB, vecUB); for (jj = 0; jj < nSubSamples*(nInputs-2); jj++) XX[jj] = vecOut[jj]; delete pdfman2; } else { for (jj = 0; jj < ii; jj++) { cLower[jj] = xLower[jj]; cUpper[jj] = xUpper[jj]; } for (jj = ii+1; jj < ii2; jj++) { cLower[jj-1] = xLower[jj]; cUpper[jj-1] = xUpper[jj]; } for (jj = ii2+1; jj < nInputs; jj++) { cLower[jj-2] = xLower[jj]; cUpper[jj-2] = xUpper[jj]; } sampler = SamplingCreateFromID(PSUADE_SAMP_LHS); sampler->setInputBounds(nInputs-2, cLower, cUpper); sampler->setOutputParams(1); sampler->setSamplingParams(nSubSamples, 1, 1); sampler->initialize(0); SS = new int[nSubSamples]; ZZ = new double[nSubSamples]; checkAllocate(ZZ, "ZZ(2) in RSMSobol2::analyze"); sampler->getSamples(nSubSamples,nInputs-2,1,XX,ZZ,SS); delete [] SS; delete [] ZZ; delete sampler; } for (iL = 0; iL < currNLevels*currNLevels; iL++) { for (jj = 0; jj < nSubSamples; jj++) { oneSamplePt = &(XX[jj*(nInputs-2)]); for (kk = 0; kk < ii; kk++) mSamplePts[jj*nInputs+kk] = oneSamplePt[kk]; for (kk = ii+1; kk < ii2; kk++) mSamplePts[jj*nInputs+kk] = oneSamplePt[kk-1]; for (kk = ii2+1; kk < nInputs; kk++) mSamplePts[jj*nInputs+kk] = oneSamplePt[kk-2]; mSamplePts[jj*nInputs+ii] = samplePts2D[iL*2]; mSamplePts[jj*nInputs+ii2] = samplePts2D[iL*2+1]; } faPtr->evaluatePoint(nSubSamples,mSamplePts,YY); for (jj = 0; jj < nSubSamples; jj++) { oneSamplePt = &(mSamplePts[jj*nInputs]); status = 1; if (constrPtr != NULL) ddata = constrPtr->evaluate(oneSamplePt,YY[jj],status); if (status == 0) YY[jj] = PSUADE_UNDEFINED; } means[iL] = 0.0; sCnt = 0; for (jj = 0; jj < nSubSamples; jj++) { if (YY[jj] != PSUADE_UNDEFINED) { means[iL] += YY[jj]; sCnt++; } } bins[iL] = sCnt; if (sCnt < 1 && printLevel >= 5) printOutTS(PL_INFO, "RSMSobol2 WARNING: subsample size = 0.\n"); if (sCnt < 1) means[iL] = PSUADE_UNDEFINED; else means[iL] /= (double) sCnt; vars[iL] = 0.0; ddata = means[iL]; for (jj = 0; jj < nSubSamples; jj++) { if (YY[jj] != PSUADE_UNDEFINED) vars[iL] += (YY[jj]-ddata)*(YY[jj]-ddata); } if (sCnt < 1) vars[iL] = PSUADE_UNDEFINED; else vars[iL] /= (double) sCnt; } dmean = 0.0; totalCnt = 0; for (iL = 0; iL < currNLevels*currNLevels; iL++) totalCnt += bins[iL]; if (totalCnt == 0) { printOutTS(PL_ERROR, "RSMSobol2 ERROR: empty constrained space.\n"); printOutTS(PL_ERROR, " Either try larger sample size or\n"); printOutTS(PL_ERROR," use looser constraints.\n"); exit(1); } for (iL = 0; iL < currNLevels*currNLevels; iL++) { if (means[iL] != PSUADE_UNDEFINED) dmean += means[iL] * bins[iL] / totalCnt; } vce = 0.0; for (iL = 0; iL < currNLevels*currNLevels; iL++) { if (means[iL] != PSUADE_UNDEFINED) vce += (means[iL]-dmean) * (means[iL]-dmean) * bins[iL] / totalCnt; } ecv = 0.0; for (iL = 0; iL < currNLevels*currNLevels; iL++) if (vars[iL] != PSUADE_UNDEFINED) ecv += vars[iL] * bins[iL] / totalCnt; if (printLevel > 1 || iR == 1) printOutTS(PL_INFO, "VCE(%3d,%3d) = %12.4e, (normalized) = %10.3e\n", ii+1, ii2+1, vce, vce/variance); if (printLevel > 2) printOutTS(PL_INFO, "ECV(%3d,%3d) = %12.4e, (normalized) = %10.3e\n", ii+1, ii2+1, ecv, ecv/variance); currNLevels *= 2; } //save vces & ecvs vces_[ii*nInputs+ii2] = vce; ecvs_[ii*nInputs+ii2] = ecv; vces_[ii2*nInputs+ii] = vce; ecvs_[ii2*nInputs+ii] = ecv; if (pPtr != NULL) { pPtr->dbleArray_[ii*nInputs+ii2] = vce; pPtr->dbleArray_[ii2*nInputs+ii] = vce; } } } printAsterisks(PL_INFO, 0); delete [] cLower; delete [] cUpper; delete [] XX; delete [] YY; delete [] Y; delete [] means; delete [] vars; delete [] bins; delete [] mSamplePts; delete [] samplePts2D; delete [] pdfFlags1; delete [] pdfFlags2; delete [] inputMeans1; delete [] inputMeans2; delete [] inputStdevs1; delete [] inputStdevs2; delete faPtr; if (ioPtr == NULL) delete corMatp; if (constrPtr != NULL) delete constrPtr; if (pdfNull == 1) { delete [] pdfFlags; delete [] inputMeans; delete [] inputStdevs; } return 0.0; } // ************************************************************************ // perform analysis (for problems with joint PDFs) // ------------------------------------------------------------------------ double RSMSobol2Analyzer::analyze2(aData &adata) { int nInputs, nOutputs, nSamples, ii, ii2, jj, iR, status; int nSubSamples=100, iL, sCnt, nLevels=100, outputID; int currNLevels, nSamp, printLevel, *bins, totalCnt, bin1, bin2; double *xLower, *xUpper, *X, *Y, *XX, *YY, *Y2, dmean, ecv, ddata; double *oneSamplePt, *means, *vars, vce, variance, width1, width2; char pString[500]; pData pPDF; PsuadeData *ioPtr; FuncApprox *faPtr; RSConstraints *constrPtr; psVector vecIn, vecOut, vecUB, vecLB; PDFManager *pdfman; if (isScreenDumpModeOn()) { printAsterisks(PL_INFO, 0); printOutTS(PL_INFO,"RSMSobol2: since joint PDFs have been specified, a\n"); printOutTS(PL_INFO," different interaction analysis will be performed.\n"); } nInputs = adata.nInputs_; nInputs_ = nInputs; nOutputs = adata.nOutputs_; nSamples = adata.nSamples_; xLower = adata.iLowerB_; xUpper = adata.iUpperB_; X = adata.sampleInputs_; Y2 = adata.sampleOutputs_; outputID = adata.outputID_; ioPtr = adata.ioPtr_; printLevel = adata.printLevel_; Y = new double[nSamples]; checkAllocate(Y, "Y in RSMSobol2::analyze2"); for (ii = 0; ii < nSamples; ii++) Y[ii] = Y2[ii*nOutputs+outputID]; if (ioPtr != NULL) { constrPtr = new RSConstraints(); constrPtr->genConstraints(ioPtr); } else constrPtr = NULL; if (ioPtr == NULL) { if (rstype_ < 0) jj = 0; else jj = rstype_; faPtr = genFA(jj, nInputs, 0, nSamples); faPtr->setBounds(xLower, xUpper); faPtr->setOutputLevel(0); } else faPtr = genFAInteractive(ioPtr, 0); if (faPtr == NULL) { printOutTS(PL_ERROR, "RSMSobol2 ERROR: cannot create response surface.\n"); delete [] Y; delete constrPtr; return 1.0e12; } status = faPtr->initialize(X, Y); if (isScreenDumpModeOn() || psAnaExpertMode_ == 1) { printAsterisks(PL_INFO, 0); printOutTS(PL_INFO, "* RSMSobol2 generates a mesh of size K x K for every\n"); printOutTS(PL_INFO, "* pair of inputs and then creates a sample of size\n"); printOutTS(PL_INFO, "* M for each mesh point. The total sample size is:\n"); printOutTS(PL_INFO, "* N = M * K * K * nInputs * (nInputs - 1) / 2.\n"); printOutTS(PL_INFO,"* NOW, nInputs = %d\n", nInputs); printOutTS(PL_INFO,"* Please select your desired M and K.\n"); printOutTS(PL_INFO,"* Recommendation: K x K >> M.\n"); printOutTS(PL_INFO,"* NOTE: large M and K can take a long time.\n"); printEquals(PL_INFO, 0); sprintf(pString,"Enter M (suggestion: 100 - 1000) : "); nSubSamples = getInt(100, 1000, pString); sprintf(pString, "Enter nLevels (suggestion: 50 - 500) : "); nLevels = getInt(50, 500, pString); printAsterisks(PL_INFO, 0); } else { nSubSamples = 100; nLevels = 100; if (isScreenDumpModeOn()) { printOutTS(PL_INFO,"* RSMSobol2: default M = %d.\n", nSubSamples); printOutTS(PL_INFO,"* RSMSobol2: default K = %d.\n", nLevels); printOutTS(PL_INFO, "* To change these settings, re-run with ana_expert mode on.\n"); printAsterisks(PL_INFO, 0); } } nSamp = nLevels * nLevels * nSubSamples; if (isScreenDumpModeOn() && printLevel > 1) { printOutTS(PL_INFO, "* RSMSobol2 INFO: creating a sample for basic statistics.\n"); printOutTS(PL_INFO,"* sample size = %d\n", nSamp); } XX = new double[nSamp*nInputs]; YY = new double[nSamp]; checkAllocate(YY, "YY in RSMSobol2::analyze2"); pdfman = NULL; if (ioPtr != NULL) { pdfman = new PDFManager(); pdfman->initialize(ioPtr); } else { pdfman = new PDFManager(); int *inputPDFs = adata.inputPDFs_; double *inputMeans = adata.inputMeans_; double *inputStdevs = adata.inputStdevs_; if (inputPDFs == NULL || inputMeans == NULL || inputStdevs == NULL) { printf("RSMSobol2 ERROR: PDF information not provided.\n"); exit(1); } psMatrix cMat; cMat.setDim(nInputs, nInputs); for (ii = 0; ii < nInputs; ii++) cMat.setEntry(ii,ii,1); char **snames = new char*[nInputs]; for (ii = 0; ii < nInputs; ii++) { snames[ii] = new char[100]; sprintf(snames[ii], "X%d", ii+1); } pdfman->initialize(nInputs, inputPDFs, inputMeans, inputStdevs, cMat, snames, NULL); for (ii = 0; ii < nInputs; ii++) delete [] snames[ii]; delete [] snames; } vecLB.load(nInputs, xLower); vecUB.load(nInputs, xUpper); vecOut.setLength(nSamp*nInputs); pdfman->genSample(nSamp, vecOut, vecLB, vecUB); for (ii = 0; ii < nSamp*nInputs; ii++) XX[ii] = vecOut[ii]; if (isScreenDumpModeOn()) printOutTS(PL_INFO, "RSMSobol2: running the sample with response surface...\n"); faPtr->evaluatePoint(nSamp, XX, YY); if (isScreenDumpModeOn()) printOutTS(PL_INFO, "RSMSobol2: done running the sample with response surface.\n"); if (constrPtr != NULL) { for (ii = 0; ii < nSamp; ii++) { oneSamplePt = &(XX[ii*nInputs]); ddata = constrPtr->evaluate(oneSamplePt,YY[ii],status); if (status == 0) YY[ii] = PSUADE_UNDEFINED; } } dmean = 0.0; sCnt = 0; for (ii = 0; ii < nSamp; ii++) { if (YY[ii] != PSUADE_UNDEFINED) { dmean += YY[ii]; sCnt++; } } if (sCnt > 1) dmean /= (double) sCnt; else { printOutTS(PL_ERROR,"RSMSobol2 ERROR: too few samples that satisify\n"); printOutTS(PL_ERROR,"constraints (%d out of %d).\n",sCnt,nSamp); delete [] XX; delete [] YY; delete [] Y; delete faPtr; delete pdfman; delete constrPtr; return PSUADE_UNDEFINED; } variance = 0.0; for (ii = 0; ii < nSamp; ii++) { if (YY[ii] != PSUADE_UNDEFINED) variance += (YY[ii] - dmean) * (YY[ii] - dmean) ; } variance /= (double) sCnt; if (isScreenDumpModeOn()) { printOutTS(PL_INFO, "* RSMSobol2: sample mean (based on %d points) = %e\n", sCnt, dmean); printOutTS(PL_INFO, "* RSMSobol2: total std dev (based on %d points) = %e\n", sCnt, sqrt(variance)); printAsterisks(PL_INFO, 0); } if (variance == 0.0) variance = 1.0; delete pdfman; //save mean & std outputMean_ = dmean; outputStd_ = sqrt(variance); pData *pPtr = NULL; if (ioPtr != NULL) { pPtr = ioPtr->getAuxData(); pPtr->nDbles_ = nInputs * nInputs; pPtr->dbleArray_ = new double[nInputs * nInputs]; for (ii = 0; ii < nInputs*nInputs; ii++) pPtr->dbleArray_[ii] = 0.0; pPtr->dbleData_ = variance; } vces_ = new double[nInputs*nInputs]; ecvs_ = new double[nInputs*nInputs]; means = new double[nLevels*nLevels]; vars = new double[nLevels*nLevels]; bins = new int[nLevels*nLevels]; checkAllocate(bins, "bins in RSMSobol2::analyze2"); for (ii = 0; ii < nInputs; ii++) { for (ii2 = ii+1; ii2 < nInputs; ii2++) { if (isScreenDumpModeOn()) printOutTS(PL_DETAIL, "RSMSobol2: processing input pair %d, %d\n", ii+1, ii2+1); currNLevels = nLevels / 2; for (iR = 0; iR < 2; iR++) { if (isScreenDumpModeOn()) printOutTS(PL_DETAIL, "RSMSobol2: processing refinement %d\n",iR); width1 = (xUpper[ii] - xLower[ii]) / currNLevels; width2 = (xUpper[ii2] - xLower[ii2]) / currNLevels; for (iL = 0; iL < currNLevels*currNLevels; iL++) { means[iL] = 0.0; vars[iL] = 0.0; bins[iL] = 0; } for (jj = 0; jj < nSamp; jj++) { if (YY[jj] != PSUADE_UNDEFINED) { ddata = XX[jj*nInputs+ii]; bin1 = (int) ((ddata - xLower[ii]) / width1); ddata = XX[jj*nInputs+ii2]; bin2 = (int) ((ddata - xLower[ii2]) / width2); if (bin1 == currNLevels) bin1 = currNLevels - 1; if (bin2 == currNLevels) bin2 = currNLevels - 1; means[bin1*currNLevels+bin2] += YY[jj]; bins[bin1*currNLevels+bin2]++; } } for (iL = 0; iL < currNLevels*currNLevels; iL++) { sCnt = bins[iL]; if (sCnt < 1 && printLevel >= 5) printOutTS(PL_DUMP, "RSMSobol2 WARNING: subsample size = 0.\n"); if (sCnt < 1) means[iL] = PSUADE_UNDEFINED; else means[iL] /= (double) sCnt; } for (jj = 0; jj < nSamp; jj++) { if (YY[jj] != PSUADE_UNDEFINED) { ddata = XX[jj*nInputs+ii]; bin1 = (int) ((ddata - xLower[ii]) / width1); ddata = XX[jj*nInputs+ii2]; bin2 = (int) ((ddata - xLower[ii2]) / width2); if (bin1 == currNLevels) bin1 = currNLevels - 1; if (bin2 == currNLevels) bin2 = currNLevels - 1; ddata = means[bin1*currNLevels+bin2]; vars[bin1*currNLevels+bin2] += (YY[jj]-ddata)*(YY[jj]-ddata); } } for (iL = 0; iL < currNLevels*currNLevels; iL++) { sCnt = bins[iL]; if (sCnt < 1) vars[iL] = PSUADE_UNDEFINED; else vars[iL] /= (double) sCnt; } totalCnt = 0; for (iL = 0; iL < currNLevels*currNLevels; iL++) totalCnt += bins[iL]; if (totalCnt == 0) { printOutTS(PL_ERROR, "RSMSobol2 ERROR: empty constrained space.\n"); printOutTS(PL_ERROR, " Either try larger sample size or\n"); printOutTS(PL_ERROR, " use looser constraints.\n"); exit(1); } dmean = 0.0; for (iL = 0; iL < currNLevels*currNLevels; iL++) { if (means[iL] != PSUADE_UNDEFINED) dmean += means[iL] * bins[iL] / totalCnt; } vce = 0.0; for (iL = 0; iL < currNLevels*currNLevels; iL++) if (means[iL] != PSUADE_UNDEFINED) vce += (means[iL]-dmean) * (means[iL]-dmean) * bins[iL] / totalCnt; ecv = 0.0; for (iL = 0; iL < currNLevels*currNLevels; iL++) { if (vars[iL] != PSUADE_UNDEFINED) ecv += vars[iL] * bins[iL] / totalCnt; } if (isScreenDumpModeOn() && (printLevel > 2 || iR == 1)) { printOutTS(PL_INFO, "VCE(%3d,%3d) = %12.4e, (normalized) = %10.3e\n", ii+1, ii2+1, vce, vce/variance); } if (isScreenDumpModeOn() && (printLevel > 3 || iR == 1)) { printOutTS(PL_DETAIL, "ECV(%3d,%3d) = %12.4e, (normalized) = %10.3e\n", ii+1, ii2+1, ecv, ecv/variance); } currNLevels *= 2; } //save vces & ecvs vces_[ii*nInputs+ii2] = vces_[ii2*nInputs+ii] = vce; ecvs_[ii*nInputs+ii2] = ecvs_[ii2*nInputs+ii] = ecv; if (pPtr != NULL) { pPtr->dbleArray_[ii*nInputs+ii2] = vce; pPtr->dbleArray_[ii2*nInputs+ii] = vce; } } } if (isScreenDumpModeOn()) printAsterisks(PL_INFO, 0); delete constrPtr; delete faPtr; delete [] XX; delete [] YY; delete [] Y; delete [] means; delete [] vars; delete [] bins; return 0.0; } // ************************************************************************ // equal operator // ------------------------------------------------------------------------ RSMSobol2Analyzer& RSMSobol2Analyzer::operator=(const RSMSobol2Analyzer &) { printOutTS(PL_ERROR,"RSMSobol2 operator= ERROR: operation not allowed.\n"); exit(1); return (*this); } // ************************************************************************ // functions for getting results // ------------------------------------------------------------------------ int RSMSobol2Analyzer::get_nInputs() { return nInputs_; } double RSMSobol2Analyzer::get_outputMean() { return outputMean_; } double RSMSobol2Analyzer::get_outputStd() { return outputStd_; } double RSMSobol2Analyzer::get_vce(int ind1, int ind2) { if (ind1 < 0 || ind1 >= nInputs_) { printf("RSMSobol2 ERROR: get_vce index 1 error.\n"); return 0.0; } if (ind2 < 0 || ind2 >= nInputs_) { printf("RSMSobol2 ERROR: get_vce index 2 error.\n"); return 0.0; } if (vces_ == NULL) { printf("RSMSobol2 ERROR: get_vce has no value.\n"); return 0; } return vces_[ind1*nInputs_+ind2]/outputStd_/outputStd_; } double RSMSobol2Analyzer::get_ecv(int ind1, int ind2) { if (ind1 < 0 || ind1 >= nInputs_) { printf("RSMSobol2 ERROR: get_ecv index 1 error.\n"); return 0.0; } if (ind2 < 0 || ind2 >= nInputs_) { printf("RSMSobol2 ERROR: get_ecv index 2 error.\n"); return 0.0; } if (ecvs_ == NULL) { printf("RSMSobol2 ERROR: get_ecv has no value.\n"); return 0; } return ecvs_[ind1*nInputs_+ind2]/outputStd_/outputStd_; }
34.225726
83
0.511469
lbianchi-lbl
489912c199007ab87378b33eca4cb27a82dc881a
11,417
cpp
C++
gen/windows/kin/eigen/src/Jws_LeftToeBottom_to_RightToeBottom.cpp
UMich-BipedLab/Cassie_StateEstimation
d410ddce0ab342651f5ec0540c2867faf959a3a9
[ "BSD-3-Clause" ]
26
2018-07-20T15:20:19.000Z
2022-03-14T07:12:12.000Z
gen/windows/kin/eigen/src/Jws_LeftToeBottom_to_RightToeBottom.cpp
UMich-BipedLab/Cassie_StateEstimation
d410ddce0ab342651f5ec0540c2867faf959a3a9
[ "BSD-3-Clause" ]
2
2019-04-19T22:57:00.000Z
2022-01-11T12:46:20.000Z
gen/windows/kin/eigen/src/Jws_LeftToeBottom_to_RightToeBottom.cpp
UMich-BipedLab/Cassie_StateEstimation
d410ddce0ab342651f5ec0540c2867faf959a3a9
[ "BSD-3-Clause" ]
10
2018-07-29T08:05:14.000Z
2022-02-03T08:48:11.000Z
/* * Automatically Generated from Mathematica. * Thu 23 May 2019 13:35:31 GMT-04:00 */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "Jws_LeftToeBottom_to_RightToeBottom.h" #ifdef _MSC_VER #define INLINE __forceinline /* use __forceinline (VC++ specific) */ #else #define INLINE static inline /* use standard inline */ #endif /** * Copied from Wolfram Mathematica C Definitions file mdefs.hpp * Changed marcos to inline functions (Eric Cousineau) */ INLINE double Power(double x, double y) { return pow(x, y); } INLINE double Sqrt(double x) { return sqrt(x); } INLINE double Abs(double x) { return fabs(x); } INLINE double Exp(double x) { return exp(x); } INLINE double Log(double x) { return log(x); } INLINE double Sin(double x) { return sin(x); } INLINE double Cos(double x) { return cos(x); } INLINE double Tan(double x) { return tan(x); } INLINE double Csc(double x) { return 1.0/sin(x); } INLINE double Sec(double x) { return 1.0/cos(x); } INLINE double ArcSin(double x) { return asin(x); } INLINE double ArcCos(double x) { return acos(x); } /* update ArcTan function to use atan2 instead. */ INLINE double ArcTan(double x, double y) { return atan2(y,x); } INLINE double Sinh(double x) { return sinh(x); } INLINE double Cosh(double x) { return cosh(x); } INLINE double Tanh(double x) { return tanh(x); } #define E 2.71828182845904523536029 #define Pi 3.14159265358979323846264 #define Degree 0.01745329251994329576924 /* * Sub functions */ static void output1(Eigen::Matrix<double,3,14> &p_output1, const Eigen::Matrix<double,14,1> &var1) { double t536; double t580; double t522; double t543; double t614; double t703; double t548; double t644; double t692; double t519; double t741; double t742; double t757; double t770; double t699; double t762; double t763; double t503; double t775; double t805; double t846; double t884; double t765; double t852; double t855; double t343; double t886; double t919; double t941; double t1095; double t871; double t991; double t1053; double t277; double t1108; double t1128; double t1132; double t1283; double t1290; double t1291; double t1294; double t1309; double t1317; double t1292; double t1383; double t1398; double t1407; double t1408; double t1411; double t1401; double t1432; double t1481; double t1558; double t1565; double t1571; double t1508; double t1576; double t1594; double t1626; double t1643; double t1673; double t1094; double t1134; double t1156; double t1196; double t1208; double t1214; double t1607; double t1691; double t1703; double t1718; double t1722; double t1729; double t1790; double t1794; double t1828; double t1842; double t1877; double t1883; double t1918; double t1971; double t1973; double t1977; double t1968; double t1992; double t2033; double t2038; double t2052; double t2056; double t2037; double t2067; double t2077; double t2090; double t2092; double t2109; double t1765; double t1778; double t1785; double t1713; double t1732; double t1738; double t2089; double t2123; double t2126; double t2149; double t2152; double t2186; double t1191; double t1249; double t1272; double t2242; double t2247; double t2265; double t2133; double t2188; double t2189; double t2204; double t2212; double t2222; double t2226; double t2266; double t2285; double t2305; double t2310; double t2324; double t2339; double t2345; double t2361; double t2365; double t2387; double t2474; double t2477; double t2486; double t2478; double t2500; double t2527; double t2531; double t1741; double t1830; double t1838; double t2641; double t2650; double t2561; double t2563; double t2565; double t2686; double t2699; double t2410; double t2411; double t2412; double t2673; double t2681; double t2576; double t2581; double t2589; double t2618; double t2440; double t2457; double t2458; double t2628; double t2630; double t2632; double t2653; double t2685; double t2712; double t2715; double t2727; double t2731; double t2732; double t2736; double t2744; double t2747; double t2758; double t2771; double t2804; double t2808; double t2843; double t2860; double t2866; double t2974; double t3026; double t3042; double t3082; double t3105; double t3070; double t3072; double t3056; double t3074; double t3112; double t3138; double t3146; double t3156; double t3161; double t3162; double t3169; double t3170; double t3182; double t3187; t536 = Cos(var1[2]); t580 = Sin(var1[0]); t522 = Cos(var1[0]); t543 = Sin(var1[1]); t614 = Sin(var1[2]); t703 = Cos(var1[3]); t548 = t522*t536*t543; t644 = -1.*t580*t614; t692 = t548 + t644; t519 = Sin(var1[3]); t741 = -1.*t536*t580; t742 = -1.*t522*t543*t614; t757 = t741 + t742; t770 = Cos(var1[4]); t699 = -1.*t519*t692; t762 = t703*t757; t763 = t699 + t762; t503 = Sin(var1[4]); t775 = t703*t692; t805 = t519*t757; t846 = t775 + t805; t884 = Cos(var1[5]); t765 = t503*t763; t852 = t770*t846; t855 = t765 + t852; t343 = Sin(var1[5]); t886 = t770*t763; t919 = -1.*t503*t846; t941 = t886 + t919; t1095 = Cos(var1[6]); t871 = -1.*t343*t855; t991 = t884*t941; t1053 = t871 + t991; t277 = Sin(var1[6]); t1108 = t884*t855; t1128 = t343*t941; t1132 = t1108 + t1128; t1283 = t536*t580*t543; t1290 = t522*t614; t1291 = t1283 + t1290; t1294 = t522*t536; t1309 = -1.*t580*t543*t614; t1317 = t1294 + t1309; t1292 = -1.*t519*t1291; t1383 = t703*t1317; t1398 = t1292 + t1383; t1407 = t703*t1291; t1408 = t519*t1317; t1411 = t1407 + t1408; t1401 = t503*t1398; t1432 = t770*t1411; t1481 = t1401 + t1432; t1558 = t770*t1398; t1565 = -1.*t503*t1411; t1571 = t1558 + t1565; t1508 = -1.*t343*t1481; t1576 = t884*t1571; t1594 = t1508 + t1576; t1626 = t884*t1481; t1643 = t343*t1571; t1673 = t1626 + t1643; t1094 = t277*t1053; t1134 = t1095*t1132; t1156 = t1094 + t1134; t1196 = t1095*t1053; t1208 = -1.*t277*t1132; t1214 = t1196 + t1208; t1607 = t277*t1594; t1691 = t1095*t1673; t1703 = t1607 + t1691; t1718 = t1095*t1594; t1722 = -1.*t277*t1673; t1729 = t1718 + t1722; t1790 = 0.642788*t1703; t1794 = 0.766044*t1729; t1828 = t1790 + t1794; t1842 = Cos(var1[1]); t1877 = -1.*t1842*t536*t519; t1883 = -1.*t703*t1842*t614; t1918 = t1877 + t1883; t1971 = t703*t1842*t536; t1973 = -1.*t1842*t519*t614; t1977 = t1971 + t1973; t1968 = t503*t1918; t1992 = t770*t1977; t2033 = t1968 + t1992; t2038 = t770*t1918; t2052 = -1.*t503*t1977; t2056 = t2038 + t2052; t2037 = -1.*t343*t2033; t2067 = t884*t2056; t2077 = t2037 + t2067; t2090 = t884*t2033; t2092 = t343*t2056; t2109 = t2090 + t2092; t1765 = -0.766044*t1156; t1778 = 0.642788*t1214; t1785 = t1765 + t1778; t1713 = -0.766044*t1703; t1732 = 0.642788*t1729; t1738 = t1713 + t1732; t2089 = t277*t2077; t2123 = t1095*t2109; t2126 = t2089 + t2123; t2149 = t1095*t2077; t2152 = -1.*t277*t2109; t2186 = t2149 + t2152; t1191 = 0.642788*t1156; t1249 = 0.766044*t1214; t1272 = t1191 + t1249; t2242 = 0.642788*t2126; t2247 = 0.766044*t2186; t2265 = t2242 + t2247; t2133 = -0.766044*t2126; t2188 = 0.642788*t2186; t2189 = t2133 + t2188; t2204 = t522*t1842*t2189; t2212 = t543*t1785; t2222 = t2204 + t2212; t2226 = -1.*t1828*t2222; t2266 = t522*t1842*t2265; t2285 = t543*t1272; t2305 = t2266 + t2285; t2310 = t1738*t2305; t2324 = t2265*t1785; t2339 = -1.*t2189*t1272; t2345 = t2324 + t2339; t2361 = -1.*t1842*t580*t2345; t2365 = 0. + t2226 + t2310 + t2361; t2387 = 1/t2365; t2474 = -1.*t522; t2477 = 0. + t2474; t2486 = 0. + t580; t2478 = 0. + t2324 + t2339; t2500 = -1.*t2265*t1738; t2527 = t2189*t1828; t2531 = 0. + t2500 + t2527; t1741 = t1272*t1738; t1830 = -1.*t1785*t1828; t1838 = 0. + t1741 + t1830; t2641 = t1842*t580; t2650 = 0. + t2641; t2561 = -1.*t522*t1842*t2189; t2563 = -1.*t543*t1785; t2565 = 0. + t2561 + t2563; t2686 = -1.*t543; t2699 = 0. + t2686; t2410 = -1.*t1842*t580*t1785; t2411 = t522*t1842*t1738; t2412 = 0. + t2410 + t2411; t2673 = t522*t1842; t2681 = 0. + t2673; t2576 = t1842*t580*t2189; t2581 = t543*t1738; t2589 = 0. + t2576 + t2581; t2618 = 0. + t2266 + t2285; t2440 = t1842*t580*t1272; t2457 = -1.*t522*t1842*t1828; t2458 = 0. + t2440 + t2457; t2628 = -1.*t1842*t580*t2265; t2630 = -1.*t543*t1828; t2632 = 0. + t2628 + t2630; t2653 = t2650*t2478*t2387; t2685 = t2681*t2531*t2387; t2712 = t2699*t1838*t2387; t2715 = t2653 + t2685 + t2712; t2727 = t2650*t2565*t2387; t2731 = t2699*t2412*t2387; t2732 = t2681*t2589*t2387; t2736 = t2727 + t2731 + t2732; t2744 = t2650*t2618*t2387; t2747 = t2699*t2458*t2387; t2758 = t2681*t2632*t2387; t2771 = t2744 + t2747 + t2758; t2804 = Cos(var1[7]); t2808 = 0. + t2804; t2843 = Sin(var1[7]); t2860 = -1.*t2843; t2866 = 0. + t2860; t2974 = Cos(var1[8]); t3026 = -1.*t2974*t2843; t3042 = 0. + t3026; t3082 = Sin(var1[8]); t3105 = 0. + t3082; t3070 = -1.*t2804*t2974; t3072 = 0. + t3070; t3056 = t3042*t2478*t2387; t3074 = t3072*t2531*t2387; t3112 = t3105*t1838*t2387; t3138 = t3056 + t3074 + t3112; t3146 = t3042*t2565*t2387; t3156 = t3105*t2412*t2387; t3161 = t3072*t2589*t2387; t3162 = t3146 + t3156 + t3161; t3169 = t3042*t2618*t2387; t3170 = t3105*t2458*t2387; t3182 = t3072*t2632*t2387; t3187 = t3169 + t3170 + t3182; p_output1(0)=0. - 1.*t1838*t2387; p_output1(1)=0. - 1.*t2387*t2412; p_output1(2)=0. - 1.*t2387*t2458; p_output1(3)=0. + t2387*t2477*t2478 + t2387*t2486*t2531; p_output1(4)=0. + t2387*t2477*t2565 + t2387*t2486*t2589; p_output1(5)=0. + t2387*t2477*t2618 + t2387*t2486*t2632; p_output1(6)=t2715; p_output1(7)=t2736; p_output1(8)=t2771; p_output1(9)=t2715; p_output1(10)=t2736; p_output1(11)=t2771; p_output1(12)=t2715; p_output1(13)=t2736; p_output1(14)=t2771; p_output1(15)=t2715; p_output1(16)=t2736; p_output1(17)=t2771; p_output1(18)=t2715; p_output1(19)=t2736; p_output1(20)=t2771; p_output1(21)=0. + t1838*t2387; p_output1(22)=0. + t2387*t2412; p_output1(23)=0. + t2387*t2458; p_output1(24)=0. + t2387*t2478*t2808 + t2387*t2531*t2866; p_output1(25)=0. + t2387*t2565*t2808 + t2387*t2589*t2866; p_output1(26)=0. + t2387*t2618*t2808 + t2387*t2632*t2866; p_output1(27)=t3138; p_output1(28)=t3162; p_output1(29)=t3187; p_output1(30)=t3138; p_output1(31)=t3162; p_output1(32)=t3187; p_output1(33)=t3138; p_output1(34)=t3162; p_output1(35)=t3187; p_output1(36)=t3138; p_output1(37)=t3162; p_output1(38)=t3187; p_output1(39)=t3138; p_output1(40)=t3162; p_output1(41)=t3187; } Eigen::Matrix<double,3,14> Jws_LeftToeBottom_to_RightToeBottom(const Eigen::Matrix<double,14,1> &var1) //void Jws_LeftToeBottom_to_RightToeBottom(Eigen::Matrix<double,3,14> &p_output1, const Eigen::Matrix<double,14,1> &var1) { /* Call Subroutines */ Eigen::Matrix<double,3,14> p_output1; output1(p_output1, var1); return p_output1; }
22.298828
122
0.648945
UMich-BipedLab
489a77efd52fa8bddd112ca7ca052769063f84f3
530
hpp
C++
inference-engine/tests/ie_test_utils/functional_test_utils/plugin_cache.hpp
fujunwei/dldt
09497b7724de4be92629f7799b8538b483d809a2
[ "Apache-2.0" ]
null
null
null
inference-engine/tests/ie_test_utils/functional_test_utils/plugin_cache.hpp
fujunwei/dldt
09497b7724de4be92629f7799b8538b483d809a2
[ "Apache-2.0" ]
null
null
null
inference-engine/tests/ie_test_utils/functional_test_utils/plugin_cache.hpp
fujunwei/dldt
09497b7724de4be92629f7799b8538b483d809a2
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <string> #include <ie_core.hpp> #include <ie_plugin_ptr.hpp> class PluginCache { public: static PluginCache& get(); std::shared_ptr<InferenceEngine::Core> ie(const std::string &deviceToCheck = std::string()) const; void reset(); public: PluginCache(const PluginCache&) = delete; PluginCache& operator=(const PluginCache&) = delete; private: PluginCache(); ~PluginCache() = default; };
18.928571
102
0.69434
fujunwei
489b33ab5348de67e5166d8f5f173ec3f5272b21
3,651
cpp
C++
Util/FileSearcher.cpp
danzimm/zld
3b0b1f1511d7a91c2ec89626be6ef3e99494c395
[ "MIT" ]
null
null
null
Util/FileSearcher.cpp
danzimm/zld
3b0b1f1511d7a91c2ec89626be6ef3e99494c395
[ "MIT" ]
null
null
null
Util/FileSearcher.cpp
danzimm/zld
3b0b1f1511d7a91c2ec89626be6ef3e99494c395
[ "MIT" ]
null
null
null
// Copyright (c) 2020 Daniel Zimmerman #include "Util/FileSearcher.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" namespace llvm { namespace ald { namespace { PathList processSDKPrefixes(const std::vector<std::string> &SDKPrefixes, const std::unique_ptr<Path> &Cwd) { PathList RV; if (!SDKPrefixes.empty()) { for (const std::string &Prefix : SDKPrefixes) { RV.emplace_back(Prefix); auto &ProcessedPrefix = RV.back(); if (Cwd != nullptr) { sys::fs::make_absolute(*Cwd, ProcessedPrefix); } else { sys::fs::make_absolute(ProcessedPrefix); } if (ProcessedPrefix.back() == '/') { ProcessedPrefix.pop_back(); } } } else { RV.push_back(Path("")); } return RV; } } // namespace SearchPath::SearchPath(const std::vector<std::string> &SDKPrefixes, const std::vector<std::string> &Paths, const SmallVector<StringRef, 2> &DefaultPaths, std::unique_ptr<Path> Cwd) : SDKPrefixes_(processSDKPrefixes(SDKPrefixes, Cwd)) { if (Cwd == nullptr) { sys::fs::current_path(Cwd_); } else { Cwd_.assign(*Cwd); } if (Cwd_.back() != '/') { Cwd_.push_back('/'); } for (const std::string &Path : Paths) { Paths_.push_back(Path); if (Path.front() == '/') { NumAbsolute_ += 1; } } for (StringRef Path : DefaultPaths) { Paths_.push_back(Path.str()); if (Path.front() == '/') { NumAbsolute_ += 1; } } } namespace details { namespace { class FileNotFoundInSearchPath : public ErrorInfo<FileNotFoundInSearchPath> { public: static char ID; SmallString<256> File; SmallVector<SmallString<256>, 8> Paths; FileNotFoundInSearchPath(Twine Filename, SmallVector<SmallString<256>, 8> PS) : File(Filename.str()), Paths(std::move(PS)) {} void log(raw_ostream &OS) const override { OS << File << " not found in { "; if (!Paths.empty()) { auto Iter = Paths.begin(); auto End = Paths.end(); OS << *Iter++; while (Iter != End) { OS << ", " << *Iter++; } OS << " "; } OS << "}"; } std::error_code convertToErrorCode() const override { llvm_unreachable("Converting FileNotFoundInSearchPath to error_code" " not supported"); } }; char FileNotFoundInSearchPath::ID; } // namespace PathList FileSearcherImpl::getAllPaths() const { PathList RV; RV.reserve(SearchPath_.size()); SearchPath_.visit([&RV](const Twine &File) { RV.emplace_back(); File.toVector(RV.back()); return false; }); return RV; } Expected<Path> FileSearcherImpl::searchInternal(StringRef File) const { Path RV; auto Visitor = [&](const Twine &Dir) -> bool { return searchForFileInDirectory(File, Dir, RV) && validatePath(RV); }; if (SearchPath_.visit(Visitor)) { return std::move(RV); } return make_error<FileNotFoundInSearchPath>(File, getAllPaths()); } bool FileSearcherImpl::searchForFileInDirectory(StringRef File, const Twine &Dir, Path &Result) { Result.clear(); Dir.toVector(Result); sys::path::append(Result, File); if (!sys::fs::exists(Result)) { return false; } return true; } bool FileSearcherImpl::validatePath(StringRef File) const { bool RV = false; if (auto FD = sys::fs::openNativeFileForRead(File)) { RV = validateFile(*FD); sys::fs::closeFile(*FD); } return RV; } } // end namespace details } // end namespace ald } // end namespace llvm
23.862745
79
0.599288
danzimm
489b64cd17512088720803ddd1993fd6bfbcef25
495
cpp
C++
02. Bit Manipulation/05 One Odd Occurring/Bonus Question.cpp
VivekYadav105/Data-Structures-and-Algorithms
7287912da8068c9124e0bb89c93c4d52aa48c51f
[ "MIT" ]
190
2021-02-10T17:01:01.000Z
2022-03-20T00:21:43.000Z
02. Bit Manipulation/05 One Odd Occurring/Bonus Question.cpp
VivekYadav105/Data-Structures-and-Algorithms
7287912da8068c9124e0bb89c93c4d52aa48c51f
[ "MIT" ]
null
null
null
02. Bit Manipulation/05 One Odd Occurring/Bonus Question.cpp
VivekYadav105/Data-Structures-and-Algorithms
7287912da8068c9124e0bb89c93c4d52aa48c51f
[ "MIT" ]
27
2021-03-26T11:35:15.000Z
2022-03-06T07:34:54.000Z
#include<bits/stdc++.h> using namespace std; //find the element which is missing from the range 1 to n //trick 1 : xor of same numbers gives zero //trick 2 : xor of zero with any number returns original number int missing(int a[], int n)//time comp. O(n) { int X = 0; for (int i = 1; i <= n; i++) { X = X ^ i; } for (int i = 0; i < n - 1; i++) { X = X ^ a[i]; } return X; } int main() { int a[] = {1, 2, 3, 5, 6, 7, 8}; int n = 8; cout << missing(a, n) << endl; return 0; }
15.967742
63
0.553535
VivekYadav105
489f67706a943d43ed9178d902bb2d2694641879
10,049
cpp
C++
gcg/src/reader_cls.cpp
avrech/scipoptsuite-6.0.2-avrech
bb4ef31b6e84ff7e1e65cee982acf150739cda86
[ "MIT" ]
null
null
null
gcg/src/reader_cls.cpp
avrech/scipoptsuite-6.0.2-avrech
bb4ef31b6e84ff7e1e65cee982acf150739cda86
[ "MIT" ]
null
null
null
gcg/src/reader_cls.cpp
avrech/scipoptsuite-6.0.2-avrech
bb4ef31b6e84ff7e1e65cee982acf150739cda86
[ "MIT" ]
1
2022-01-19T01:15:11.000Z
2022-01-19T01:15:11.000Z
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program */ /* GCG --- Generic Column Generation */ /* a Dantzig-Wolfe decomposition based extension */ /* of the branch-cut-and-price framework */ /* SCIP --- Solving Constraint Integer Programs */ /* */ /* Copyright (C) 2010-2019 Operations Research, RWTH Aachen University */ /* Zuse Institute Berlin (ZIB) */ /* */ /* This program is free software; you can redistribute it and/or */ /* modify it under the terms of the GNU Lesser General Public License */ /* as published by the Free Software Foundation; either version 3 */ /* of the License, or (at your option) any later version. */ /* */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program; if not, write to the Free Software */ /* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.*/ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file reader_cls.cpp * @brief CLS reader for writing files containing classifier data * @author Michael Bastubbe * @author Julius Hense */ /*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/ #include <assert.h> #include <string.h> #if defined(_WIN32) || defined(_WIN64) #else #include <strings.h> /*lint --e{766}*/ /* needed for strcasecmp() */ #endif #include <ctype.h> #include "reader_cls.h" #include "cons_decomp.h" #include "class_seeedpool.h" #include "class_consclassifier.h" #include "class_varclassifier.h" #define READER_NAME "clsreader" #define READER_DESC "reader for writing classifier data" #define READER_EXTENSION "cls" #define DEFAULT_USETRANSFORM TRUE struct SCIP_ConshdlrData { gcg::Seeedpool* seeedpoolunpresolved; gcg::Seeedpool* seeedpool; }; /** data for dec reader */ struct SCIP_ReaderData { SCIP_Bool usetransform; }; /* * Local methods */ /** write a DEC file for a given decomposition */ SCIP_RETCODE GCGwriteCls( SCIP* scip, /**< SCIP data structure */ FILE* file /**< File pointer to write to */ ) { assert(scip != NULL); /* TODO * format description: * a) <number of classifiers> * for each classifier: * b1) VAR or CONS * b2) <name of classifier>> * b3) <number of classes> * b4) for each class: * c1) <name of class>: <description of class> * c2) <number of class elements> * c3) for each element of class: * d1) <name of element> (e.g. variable or constraint name, concerning transformed [default] or original problem) * * * 1. Write cons_decomp method(s) to get all relevant data, i.e. * - for all cons and var classifier in both presolved and unpresolved seeedpool: * - Class to index mapping, class names, class descriptions (and maybe class decomp info) * - Cons/var to classes mapping * - index to SCIPcons/SCIPvar mapping from unpresolved seeedpool (and maybe seeedpool) * * 2. Write an output method to write these information into a file * */ SCIP_Bool transformed; gcg::Seeedpool* seeedpool; assert(scip != NULL); SCIP_CALL( SCIPgetBoolParam(scip, "reading/clsreader/usetransform", &transformed)); if( SCIPgetStage(scip) < SCIP_STAGE_TRANSFORMED ) transformed = FALSE; if( !transformed && SCIPconshdlrDecompGetSeeedpoolUnpresolvedExtern(scip) == NULL ) SCIPconshdlrDecompCreateSeeedpoolUnpresolved(scip); if( transformed && SCIPconshdlrDecompGetSeeedpoolExtern(scip) == NULL ) SCIPconshdlrDecompCreateSeeedpool(scip); seeedpool = (gcg::Seeedpool*)(transformed ? SCIPconshdlrDecompGetSeeedpoolExtern(scip) : SCIPconshdlrDecompGetSeeedpoolUnpresolvedExtern(scip)); SCIPconshdlrDecompCreateSeeedpoolUnpresolved(scip); if( seeedpool->consclassescollection.size() == 0 ) seeedpool->calcClassifierAndNBlockCandidates(scip); SCIPinfoMessage(scip, file, "# a1) <number of classifiers>\n" ); SCIPinfoMessage(scip, file, "# a2) for each classifier:\n" ); SCIPinfoMessage(scip, file, "# b1) VAR or CONS\n" ); SCIPinfoMessage(scip, file, "# b2) <name of classifier>\n" ); SCIPinfoMessage(scip, file, "# b3) <number of classes>\n" ); SCIPinfoMessage(scip, file, "# b4) for each class:\n" ); SCIPinfoMessage(scip, file, "# c1) <name of class>: <description of class>\n" ); SCIPinfoMessage(scip, file, "# c2) <number of class elements>\n" ); SCIPinfoMessage(scip, file, "# c3) for each element of class:\n" ); SCIPinfoMessage(scip, file, "# d1) <name of element> (e.g. variable or constraint name, concerning transformed [default] or original problem)\n" ); SCIPinfoMessage(scip, file, "###########################################\n" ); /** a */ SCIPinfoMessage(scip, file, "%d\n", (int) seeedpool->consclassescollection.size() + (int) seeedpool->varclassescollection.size() ); for( size_t c = 0; c < seeedpool->consclassescollection.size() ; ++c ) { gcg::ConsClassifier* classifier = seeedpool->consclassescollection[c]; std::vector<std::vector<int> > conssofclasses = std::vector<std::vector<int> >(classifier->getNClasses()) ; for( int cons = 0; cons < seeedpool->getNConss(); ++cons ) conssofclasses[classifier->getClassOfCons(cons)].push_back(cons); /** b1 */ SCIPinfoMessage(scip, file, "CONS\n" ); /** b2 */ SCIPinfoMessage(scip, file, "%s \n", classifier->getName()); /** b3 */ SCIPinfoMessage(scip, file, "%d\n", classifier->getNClasses() ); for( int cl = 0; cl < classifier->getNClasses(); ++cl ) { /** c1 */ SCIPinfoMessage(scip, file, "%s: %s\n", classifier->getClassName(cl), classifier->getClassDescription(cl) ); /** c2 */ SCIPinfoMessage(scip, file, "%d\n", conssofclasses[cl].size() ); /** c3 */ for( size_t clm = 0; clm < conssofclasses[cl].size(); ++clm ) { SCIPinfoMessage(scip, file, "%s\n", SCIPconsGetName( seeedpool->getConsForIndex( conssofclasses[cl][clm])) ); } } } for( size_t c = 0; c < seeedpool->varclassescollection.size() ; ++c ) { gcg::VarClassifier* classifier = seeedpool->varclassescollection[c]; std::vector<std::vector<int> > varsofclasses = std::vector<std::vector<int> >(classifier->getNClasses()) ; for( int var = 0; var < seeedpool->getNVars(); ++var ) varsofclasses[classifier->getClassOfVar(var)].push_back(var); /** b1 */ SCIPinfoMessage(scip, file, "VAR\n" ); /** b2 */ SCIPinfoMessage(scip, file, "%s \n", classifier->getName()); /** b3 */ SCIPinfoMessage(scip, file, "%d\n", classifier->getNClasses() ); for( int cl = 0; cl < classifier->getNClasses(); ++cl ) { /** c1 */ SCIPinfoMessage(scip, file, "%s: %s\n", classifier->getClassName(cl), classifier->getClassDescription(cl) ); /** c2 */ SCIPinfoMessage(scip, file, "%d\n", classifier->getNVarsOfClasses()[cl] ); /** c3 */ for( size_t clm = 0; clm <varsofclasses[cl].size(); ++clm ) { SCIPinfoMessage(scip, file, "%s\n", SCIPvarGetName( seeedpool->getVarForIndex( varsofclasses[cl][clm])) ); } } } return SCIP_OKAY; } /* * Callback methods of reader */ #define readerCopyCls NULL /** destructor of reader to free user data (called when SCIP is exiting) */ static SCIP_DECL_READERFREE(readerFreeCls) { SCIP_READERDATA* readerdata; readerdata = SCIPreaderGetData( reader ); assert( readerdata != NULL ); SCIPfreeMemory( scip, &readerdata ); assert( strcmp( SCIPreaderGetName( reader ), READER_NAME ) == 0); return SCIP_OKAY; } /** problem reading method of reader */ #define readerReadCls NULL /** problem writing method of reader */ static SCIP_DECL_READERWRITE(readerWriteCls) { /*lint --e{715}*/ SCIP_CALL( GCGwriteCls( scip, file ) ); *result = SCIP_SUCCESS; return SCIP_OKAY; } /** includes the cls reader into SCIP */ SCIP_RETCODE SCIPincludeReaderCls( SCIP* scip /**< SCIP data structure */ ) { SCIP_READERDATA* readerdata; /* create cls reader data */ SCIP_CALL( SCIPallocMemory(scip, &readerdata) ); /* include cls reader */ SCIP_CALL( SCIPincludeReader(scip, READER_NAME, READER_DESC, READER_EXTENSION, readerCopyCls, readerFreeCls, readerReadCls, readerWriteCls, readerdata) ); SCIP_CALL( SCIPaddBoolParam(scip, "reading/clsreader/usetransform", "should the transformed (and possibly presolved problem) be use or original one", &readerdata->usetransform, FALSE, DEFAULT_USETRANSFORM, NULL, NULL) ); return SCIP_OKAY; }
37.218519
159
0.577172
avrech
48a0e4cbb710208c6ac0cb49267bf60f83099988
15,591
hpp
C++
src/frovedis/core/node_local.hpp
wmeddie/frovedis
c134e5e64114799cc7c265c72525ff98d06b49c1
[ "BSD-2-Clause" ]
null
null
null
src/frovedis/core/node_local.hpp
wmeddie/frovedis
c134e5e64114799cc7c265c72525ff98d06b49c1
[ "BSD-2-Clause" ]
null
null
null
src/frovedis/core/node_local.hpp
wmeddie/frovedis
c134e5e64114799cc7c265c72525ff98d06b49c1
[ "BSD-2-Clause" ]
null
null
null
#ifndef NODE_LOCAL_HPP #define NODE_LOCAL_HPP #include "DVID.hpp" #include "type_utility.hpp" namespace frovedis { template <class T> class node_local; template <class T> node_local<T> make_node_local_broadcast(const T& var); template <class T> class dvector; template <class T> class node_local { public: using value_type = T; node_local() : is_view(false) {} node_local(const DVID<T>& dvid_, bool is_view_ = false) : dvid(dvid_), is_view(is_view_) {} node_local(DVID<T>&& dvid_, bool is_view_ = false) : dvid(std::move(dvid_)), is_view(is_view_) {} node_local(const node_local<T>& src) : dvid(src.dvid.copy()), is_view(false) {} node_local(node_local<T>&& src) : is_view(false) {std::swap(dvid, src.dvid);} node_local<T>& operator=(const node_local<T>& src) { if(!is_view) dvid.delete_var(); dvid = src.dvid.copy(); is_view = false; return *this; } node_local<T>& operator=(node_local<T>&& src) { // dvid of original this will be deleted after swap if it is not view std::swap(dvid, src.dvid); std::swap(is_view, src.is_view); return *this; } ~node_local(){if(!is_view) dvid.delete_var();} template<class F> T reduce(const F& f) { return dvid.reduce(f); } template <class TT, class UU> T reduce(T(*f)(TT,UU)) {return reduce(make_serfunc(f));} template<class F> node_local<T> allreduce(const F& f) { return node_local<T>(dvid.allreduce(f)); } template <class TT, class UU> node_local<T> allreduce(T(*f)(TT,UU)) {return allreduce(make_serfunc(f));} std::vector<T> gather(){return dvid.gather();} template <class R, class F> node_local<R> map(const F& f) { return node_local<R>(dvid.template map<R>(f)); } template <class R, class TT> node_local<R> map(R(*f)(TT)) { return map<R>(make_serfunc(f)); } template <class R, class U, class F> node_local<R> map(const F& f, const node_local<U>& l) { return node_local<R>(dvid.template map<R>(f, l.get_dvid())); } template <class R, class U, class TT, class UU> node_local<R> map(R(*f)(TT,UU), const node_local<U>& l) { return map<R>(make_serfunc(f),l); } template <class R, class U, class V, class F> node_local<R> map(const F& f, const node_local<U>& l, const node_local<V>& l2) { return node_local<R>(dvid.template map<R>(f, l.get_dvid(), l2.get_dvid())); } template <class R, class U, class V, class TT, class UU, class VV> node_local<R> map(R(*f)(TT,UU,VV), const node_local<U>& l, const node_local<V>& l2) { return map<R>(make_serfunc(f),l,l2); } template <class R, class U, class V, class W, class F> node_local<R> map(const F& f, const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3) { return node_local<R>(dvid.template map<R>(f, l.get_dvid(), l2.get_dvid(), l3.get_dvid())); } template <class R, class U, class V, class W, class TT, class UU, class VV, class WW> node_local<R> map(R(*f)(TT,UU,VV,WW), const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3) { return map<R>(make_serfunc(f),l,l2,l3); } template <class R, class U, class V, class W, class X, class F> node_local<R> map(const F& f, const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4) { return node_local<R>(dvid.template map<R>(f, l.get_dvid(), l2.get_dvid(), l3.get_dvid(), l4.get_dvid())); } template <class R, class U, class V, class W, class X, class TT, class UU, class VV, class WW, class XX> node_local<R> map(R(*f)(TT,UU,VV,WW,XX), const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4) { return map<R>(make_serfunc(f),l,l2,l3,l4); } template <class R, class U, class V, class W, class X, class Y, class F> node_local<R> map(const F& f, const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4, const node_local<Y>& l5) { return node_local<R>(dvid.template map<R>(f, l.get_dvid(), l2.get_dvid(), l3.get_dvid(), l4.get_dvid(), l5.get_dvid())); } template <class R, class U, class V, class W, class X, class Y, class TT, class UU, class VV, class WW, class XX, class YY> node_local<R> map(R(*f)(TT,UU,VV,WW,XX,YY), const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4, const node_local<Y>& l5) { return map<R>(make_serfunc(f),l,l2,l3,l4,l5); } template <class R, class U, class V, class W, class X, class Y, class Z, class F> node_local<R> map(const F& f, const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4, const node_local<Y>& l5, const node_local<Z>& l6 ) { return node_local<R>(dvid.template map<R>(f, l.get_dvid(), l2.get_dvid(), l3.get_dvid(), l4.get_dvid(), l5.get_dvid(), l6.get_dvid() )); } template <class R, class U, class V, class W, class X, class Y, class Z, class TT, class UU, class VV, class WW, class XX, class YY, class ZZ> node_local<R> map(R(*f)(TT,UU,VV,WW,XX,YY,ZZ), const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4, const node_local<Y>& l5, const node_local<Z>& l6) { return map<R>(make_serfunc(f),l,l2,l3,l4,l5,l6); } template <class R, class U, class V, class W, class X, class Y, class Z, class A, class F> node_local<R> map(const F& f, const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4, const node_local<Y>& l5, const node_local<Z>& l6, const node_local<A>& l7 ) { return node_local<R>(dvid.template map<R>(f, l.get_dvid(), l2.get_dvid(), l3.get_dvid(), l4.get_dvid(), l5.get_dvid(), l6.get_dvid(), l7.get_dvid() )); } template <class R, class U, class V, class W, class X, class Y, class Z, class A, class TT, class UU, class VV, class WW, class XX, class YY, class ZZ, class AA> node_local<R> map(R(*f)(TT,UU,VV,WW,XX,YY,ZZ,AA), const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4, const node_local<Y>& l5, const node_local<Z>& l6, const node_local<A>& l7) { return map<R>(make_serfunc(f),l,l2,l3,l4,l5,l6,l7); } template <class R, class U, class V, class W, class X, class Y, class Z, class A, class B, class F> node_local<R> map(const F& f, const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4, const node_local<Y>& l5, const node_local<Z>& l6, const node_local<A>& l7, const node_local<B>& l8 ) { return node_local<R>(dvid.template map<R>(f, l.get_dvid(), l2.get_dvid(), l3.get_dvid(), l4.get_dvid(), l5.get_dvid(), l6.get_dvid(), l7.get_dvid(), l8.get_dvid() )); } template <class R, class U, class V, class W, class X, class Y, class Z, class A, class B, class TT, class UU, class VV, class WW, class XX, class YY, class ZZ, class AA, class BB> node_local<R> map(R(*f)(TT,UU,VV,WW,XX,YY,ZZ,AA,BB), const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4, const node_local<Y>& l5, const node_local<Z>& l6, const node_local<A>& l7, const node_local<B>& l8) { return map<R>(make_serfunc(f),l,l2,l3,l4,l5,l6,l7,l8); } template <typename F, typename... Types> node_local<map_result_t<F, T, Types...>> map(const F& f, const node_local<Types>&... ls) { return map<map_result_t<F, T, Types...>>(f, ls...); } template <class F> node_local<T>& mapv(const F& f){ dvid.mapv(f); return *this; } template <class TT> node_local<T>& mapv(void(*f)(TT)){return mapv(make_serfunc(f));} template <class U, class F> node_local<T>& mapv(const F& f, const node_local<U>& l) { dvid.mapv(f, l.get_dvid()); return *this; } template <class U, class V, class F> node_local<T>& mapv(const F& f, const node_local<U>& l, const node_local<V>& l2){ dvid.mapv(f, l.get_dvid(), l2.get_dvid()); return *this; } template <class U, class V, class TT, class UU, class VV> node_local<T>& mapv(void(*f)(TT,UU,VV), const node_local<U>& l, const node_local<V>& l2){ return mapv(make_serfunc(f),l,l2); } template <class U, class V, class W, class F> node_local<T>& mapv(const F& f, const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3) { dvid.mapv(f, l.get_dvid(), l2.get_dvid(), l3.get_dvid()); return *this; } template <class U, class V, class W, class TT, class UU, class VV, class WW> node_local<T>& mapv(void(*f)(TT,UU,VV,WW), const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3) { return mapv(make_serfunc(f),l,l2,l3); } template <class U, class V, class W, class X, class F> node_local<T>& mapv(const F& f, const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4){ dvid.mapv(f, l.get_dvid(), l2.get_dvid(), l3.get_dvid(), l4.get_dvid()); return *this; } template <class U, class V, class W, class X, class TT, class UU, class VV, class WW, class XX> node_local<T>& mapv(void(*f)(TT,UU,VV,WW,XX), const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4) { return mapv(make_serfunc(f),l,l2,l3,l4); } template <class U, class V, class W, class X, class Y, class F> node_local<T>& mapv(const F& f, const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4, const node_local<Y>& l5) { dvid.mapv(f, l.get_dvid(), l2.get_dvid(), l3.get_dvid(), l4.get_dvid(), l5.get_dvid()); return *this; } template <class U, class V, class W, class X, class Y, class TT, class UU, class VV, class WW, class XX, class YY> node_local<T>& mapv(void(*f)(TT,UU,VV,WW,XX), const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4, const node_local<Y>& l5) { return mapv(make_serfunc(f),l,l2,l3,l4,l5); } template <class U, class V, class W, class X, class Y, class Z, class F> node_local<T>& mapv(const F& f, const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4, const node_local<Y>& l5, const node_local<Z>& l6) { dvid.mapv(f, l.get_dvid(), l2.get_dvid(), l3.get_dvid(), l4.get_dvid(), l5.get_dvid(), l6.get_dvid()); return *this; } template <class U, class V, class W, class X, class Y, class Z, class TT, class UU, class VV, class WW, class XX, class YY, class ZZ> node_local<T>& mapv(void(*f)(TT,UU,VV,WW,XX,YY,ZZ), const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4, const node_local<Y>& l5, const node_local<Z>& l6) { return mapv(make_serfunc(f),l,l2,l3,l4,l5,l6); } template <class U, class V, class W, class X, class Y, class Z, class A, class F> node_local<T>& mapv(const F& f, const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4, const node_local<Y>& l5, const node_local<Z>& l6, const node_local<A>& l7) { dvid.mapv(f, l.get_dvid(), l2.get_dvid(), l3.get_dvid(), l4.get_dvid(), l5.get_dvid(), l6.get_dvid(), l7.get_dvid()); return *this; } template <class U, class V, class W, class X, class Y, class Z, class A, class TT, class UU, class VV, class WW, class XX, class YY, class ZZ, class AA> node_local<T>& mapv(void(*f)(TT,UU,VV,WW,XX,YY,ZZ,AA), const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4, const node_local<Y>& l5, const node_local<Z>& l6, const node_local<A>& l7) { return mapv(make_serfunc(f),l,l2,l3,l4,l5,l6,l7); } template <class U, class V, class W, class X, class Y, class Z, class A, class B, class F> node_local<T>& mapv(const F& f, const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4, const node_local<Y>& l5, const node_local<Z>& l6, const node_local<A>& l7, const node_local<B>& l8) { dvid.mapv(f, l.get_dvid(), l2.get_dvid(), l3.get_dvid(), l4.get_dvid(), l5.get_dvid(), l6.get_dvid(), l7.get_dvid(), l8.get_dvid()); return *this; } template <class U, class V, class W, class X, class Y, class Z, class A, class B, class TT, class UU, class VV, class WW, class XX, class YY, class ZZ, class AA, class BB> node_local<T>& mapv(void(*f)(TT,UU,VV,WW,XX,YY,ZZ,AA,BB), const node_local<U>& l, const node_local<V>& l2, const node_local<W>& l3, const node_local<X>& l4, const node_local<Y>& l5, const node_local<Z>& l6, const node_local<A>& l7, const node_local<B>& l8) { return mapv(make_serfunc(f),l,l2,l3,l4,l5,l6,l7,l8); } T vector_sum() {return dvid.vector_sum();} template <class U> dvector<U> as_dvector() const; template <class U> dvector<U> moveto_dvector(); template <class U> dvector<U> viewas_dvector(); void put(int node, const T& val) {dvid.put(node,val);} T get(int node) {return dvid.get(node);} DVID<T> get_dvid() const {return dvid;} private: DVID<T> dvid; bool is_view; SERIALIZE(dvid, is_view) }; // shortcut definition template <class T> using lvec = frovedis::node_local<std::vector<T>>; template <class T> node_local<T> make_node_local_broadcast(const T& var) { return node_local<T>(make_dvid_broadcast<T>(var)); } // shortcut expression template <class T> node_local<T> broadcast(const T& var) { return make_node_local_broadcast<T>(var); } template <class T> node_local<T> make_node_local_allocate() { return node_local<T>(make_dvid_allocate<T>()); } template <class T> node_local<T> make_node_local_scatter(std::vector<T>& v) { return node_local<T>(make_dvid_scatter<T>(v)); } } #endif
45.45481
101
0.577641
wmeddie
48a79f2fc0051d73041d9d6b43ab4f3cb6519920
332
cpp
C++
1943.cpp
Valarr/Uri
807de771b14b0e60d44b23835ad9ee7423c83471
[ "MIT" ]
null
null
null
1943.cpp
Valarr/Uri
807de771b14b0e60d44b23835ad9ee7423c83471
[ "MIT" ]
null
null
null
1943.cpp
Valarr/Uri
807de771b14b0e60d44b23835ad9ee7423c83471
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(){ int a; cin >> a; if(a<=1) cout <<"Top 1\n"; else if(a<=3) cout << "Top 3\n"; else if(a<=5) cout << "Top 5\n"; else if(a<=10) cout << "Top 10\n"; else if(a<=25) cout << "Top 25\n"; else if(a<=50) cout << "Top 50\n"; else if(a<=100) cout << "Top 100\n"; }
20.75
38
0.521084
Valarr
48a86969ec1a4fcaed5cef23db9c885e2b936137
6,150
cpp
C++
SystemTests/SystemTests.cpp
Cooolrik/ISD
c06afd5a2f4e7d2fe21ba3c77e60595c1bd24ade
[ "MIT" ]
null
null
null
SystemTests/SystemTests.cpp
Cooolrik/ISD
c06afd5a2f4e7d2fe21ba3c77e60595c1bd24ade
[ "MIT" ]
null
null
null
SystemTests/SystemTests.cpp
Cooolrik/ISD
c06afd5a2f4e7d2fe21ba3c77e60595c1bd24ade
[ "MIT" ]
null
null
null
// ISD Copyright (c) 2021 Ulrik Lindahl // Licensed under the MIT license https://github.com/Cooolrik/ISD/blob/main/LICENSE #include "../ISD/ISD.h" #include "../ISD/ISD_MemoryReadStream.h" #include "../ISD/ISD_MemoryWriteStream.h" #include "../ISD/ISD_Log.h" #include "../ISD/ISD_EntityWriter.h" #include "../ISD/ISD_EntityReader.h" #include "../ISD/ISD_EntityValidator.h" #include "../ISD/ISD_Dictionary.h" #include "../ISD/ISD_DirectedGraph.h" #include "../ISD/ISD_SceneLayer.h" #include "../ISD/ISD_SHA256.h" #include "../TestHelpers/random_vals.h" //#include <fbxsdk.h> #include <Rpc.h> #include "../ISD/ISD_Varying.h" extern void safe_thread_map_test(); #define RUN_TEST( name )\ printf("Running test: " #name "\n");\ name();\ printf(" - Test: " #name " done\n"); using namespace ISD; bool LoadFile( std::string file_path , std::vector<u8> &allocation ) { // open the file HANDLE file_handle = ::CreateFileA( file_path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, nullptr ); if( file_handle == INVALID_HANDLE_VALUE ) { // failed to open the file return false; } // get the size LARGE_INTEGER dfilesize = {}; if( !::GetFileSizeEx( file_handle, &dfilesize ) ) { // failed to get the size return false; } u64 total_bytes_to_read = dfilesize.QuadPart; // read in all of the file allocation.resize( total_bytes_to_read ); if( allocation.size() != total_bytes_to_read ) { // failed to allocate the memory return false; } u8 *buffer = allocation.data(); u64 bytes_read = 0; while( bytes_read < total_bytes_to_read ) { // check how much to read and cap each read at UINT_MAX u64 bytes_left = total_bytes_to_read - bytes_read; u32 bytes_to_read_this_time = UINT_MAX; if( bytes_left < UINT_MAX ) bytes_to_read_this_time = (u32)bytes_left; // read in bytes into the memory allocation DWORD bytes_that_were_read = 0; if( !::ReadFile( file_handle, &buffer[bytes_read], bytes_to_read_this_time, &bytes_that_were_read, nullptr ) ) { // failed to read return false; } // update number of bytes that were read bytes_read += bytes_that_were_read; } ::CloseHandle( file_handle ); return true; } class named_object { public: optional_value<std::string> object_name; }; void write_geometry() { idx_vector<vec3> *Vertices = new idx_vector<vec3>(); auto &values = Vertices->values(); auto &index = Vertices->index(); values.resize( 100000000 ); index.resize( 100000000 ); for( size_t i = 0; i < 100000000; ++i ) { values[i] = vec3( i, i, i ); index[i] = (int)i; } MemoryWriteStream ws; EntityWriter wr(ws); wr.Write( "Vertices", 8, *Vertices ); delete Vertices; FILE *fp; if( fopen_s( &fp, "test_write.dat", "wb" ) == 0 ) { fwrite( ws.GetData(), ws.GetSize(), 1, fp ); fclose( fp ); } } void read_geometry() { std::vector<u8> allocation; LoadFile( "test_write.dat", allocation ); MemoryReadStream rs(allocation.data(),allocation.size()); EntityReader er( rs ); idx_vector<vec3> DestVertices; er.Read( "Vertices", 8, DestVertices ); } // //template<class Graph> //void GenerateRandomTreeRecursive( Graph &graph , uint total_levels , uint current_level = 0, typename Graph::node_type parent_node = random_value<Graph::node_type>() ) // { // typedef Graph::node_type _Ty; // // // generate a random number of subnodes // size_t sub_nodes = capped_rand( 1, 7 ); // // // add to tree // for( size_t i = 0; i < sub_nodes; ++i ) // { // _Ty child_node = random_value<Graph::node_type>(); // // graph.GetEdges().insert( std::pair<_Ty, _Ty>( parent_node, child_node ) ); // // if( current_level < total_levels ) // { // GenerateRandomTreeRecursive( graph, total_levels, current_level + 1, child_node ); // } // } // } int main() { ISD::Varying var; auto &data = ISD::Varying::MF::SetType<optional_idx_vector<fvec4>>( var ); data.set(); data.values().resize( 1000 ); data.values()[4].x = 12.f; ISD::Varying::MF::SetType<fvec3>( var ); auto &data2 = var.Data<fvec3>(); data2.x = 78; if( var.IsA<optional_idx_vector<fvec4>>() ) { const auto &data3 = var.Data<optional_idx_vector<fvec4>>(); } //optional_value<std::string> test = std::string("hej"); //optional_value<std::string> test2; //optional_value<std::string> test3; // //test2 = test; //test = test3; //Dictionary<entity_ref, SceneMesh> dict; // //auto id = entity_ref(); //auto mesh = std::make_unique<SceneMesh>(); // //dict.Entries().emplace( id , std::move(mesh) ); //dict.Entries().emplace( entity_ref() , std::make_unique<SceneMesh>() ); // //uuid meshid = dict.Entries()[id]->MeshPacketId(); // //dict.Entries().erase( id ); // //std::cout << meshid << std::endl; //ISD::SceneLayer layer; // //ISD::hash h = ISD::hash_sup; // //bool b; // //b = (ISD::hash_sup == ISD::hash_inf); //b = ISD::uuid_sup == ISD::uuid_inf; // //std::vector<u8> randomvec; //random_vector( randomvec, 1000000000, 1000000000 ); // //for( uint i = 0; i < 10; ++i ) // { // SHA256 sha1; // u8 digest1[33]; // sha1.Update( randomvec.data(), randomvec.size() ); // sha1.GetDigest( digest1 ); // digest1[32] = 0; // printf( "%s\n", digest1 ); // // SHA256 sha2; // u8 digest2[33]; // sha2.Update( randomvec.data(), randomvec.size() ); // sha2.GetDigest( digest2 ); // digest2[32] = 0; // printf( "%s\n", digest2 ); // } //ISD::SceneNode node; // //node.Name() = "Nej"; // //layer.Nodes().Entries().emplace( id, new ISD::SceneNode(node) ); // //MemoryWriteStream ws; //EntityWriter writer(ws); // //SceneLayer::MF::Write( layer, writer ); // //ISD::SceneLayer layer2; // //MemoryReadStream rs( ws.GetData(), ws.GetSize() ); //EntityReader reader(rs); // //SceneLayer::MF::Read( layer2, reader ); // //EntityValidator validator; // //SceneLayer::MF::Validate( layer2, validator ); // //bool cmp = SceneLayer::MF::Equals( &layer, &layer2 ); // //MemoryWriteStream ws; //EntityWriter writer(ws); // //DirectedGraph<int>::MF::Write( dg, writer ); // //DirectedGraph<int> dg_read; // // // // //DirectedGraph<int>: return 0; }
22.693727
169
0.652358
Cooolrik
48ae54bc80180d3096abb3c3f70a1040c550eb86
346
cpp
C++
UOJ/147/make.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
UOJ/147/make.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
UOJ/147/make.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int T=4,n=23; int cnt[15]; int main(){ srand(time(0));freopen("code.in","w",stdout); printf("%d %d\n",T,n); while(T--){ memset(cnt,0,sizeof(cnt)); for(int i=1;i<=n;++i){ int t=rand()%14; while(!(t&&cnt[t]<=4||cnt[t]<=2))t=rand()%14; printf("%d %d\n",t,rand()%4+1); } } return 0; }
19.222222
48
0.546243
sjj118
48b0b4644194a385b65c3705db73d9cee8d8d52b
892
cpp
C++
Woopsi/examples/scrolltest/src/testpanel.cpp
ant512/Woopsi
e7a568dc5e16ae772a5cad850527861ac2c2e703
[ "BSD-3-Clause" ]
14
2016-01-25T01:01:25.000Z
2021-07-02T22:49:27.000Z
Woopsi/examples/scrolltest/src/testpanel.cpp
ant512/Woopsi
e7a568dc5e16ae772a5cad850527861ac2c2e703
[ "BSD-3-Clause" ]
1
2021-07-29T23:14:59.000Z
2021-07-29T23:14:59.000Z
Woopsi/examples/scrolltest/src/testpanel.cpp
ant512/Woopsi
e7a568dc5e16ae772a5cad850527861ac2c2e703
[ "BSD-3-Clause" ]
4
2016-01-25T01:01:45.000Z
2021-09-04T23:39:10.000Z
#include "testpanel.h" #include "graphicsport.h" #include "woopsifuncs.h" using namespace WoopsiUI; TestPanel::TestPanel(s16 x, s16 y, u16 width, u16 height, GadgetStyle* style) : ScrollingPanel(x, y, width, height, style) { // Set the dimensions of the virtual canvas setCanvasHeight(300); setCanvasWidth(600); // Enable the virtual canvas to be dragged with the stylus _flags.draggable = true; }; void TestPanel::drawContents(GraphicsPort* port) { // Draw background port->drawFilledRect(0, 0, getWidth(), getHeight(), getBackColour()); // Draw contents. Note that all co-ordinates are offset by the canvas // x and y co-ordinates port->drawText(30 + getCanvasX(), 60 + getCanvasY(), getFont(), "Scrolling Panel Test", 0, 20, woopsiRGB(0, 0, 15)); port->drawFilledRect(200 + getCanvasX(), 90 + getCanvasY(), 100, 100, woopsiRGB(15, 0, 0)); };
33.037037
125
0.691704
ant512
48b637bbaa2258a7eaa7656c6e69e947ba61cfb3
4,750
cpp
C++
provant_simulator_utils/provant_simulator_sdf_parser/src/sdf_parser.cpp
Guiraffo/ProVANT_Simulator
ef2260204b13f39a9f83ad2ab88a9552a0699bff
[ "MIT" ]
null
null
null
provant_simulator_utils/provant_simulator_sdf_parser/src/sdf_parser.cpp
Guiraffo/ProVANT_Simulator
ef2260204b13f39a9f83ad2ab88a9552a0699bff
[ "MIT" ]
null
null
null
provant_simulator_utils/provant_simulator_sdf_parser/src/sdf_parser.cpp
Guiraffo/ProVANT_Simulator
ef2260204b13f39a9f83ad2ab88a9552a0699bff
[ "MIT" ]
null
null
null
/* * This file is part of the ProVANT simulator project. * Licensed under the terms of the MIT open source license. More details at * https://github.com/Guiraffo/ProVANT-Simulator/blob/master/LICENSE.md */ /** * @file sdf_parser.cpp * @brief This file contains the implementation of the SDFParser class. * * @author Júnio Eduardo de Morais Aquino */ #include "provant_simulator_sdf_parser/sdf_parser.h" #include <provant_simulator_parser_utils/type_conversion.h> SDFParser::SDFParser(sdf::ElementPtr sdf) : _sdf(sdf) { } SDFParser::~SDFParser() { } sdf::ElementPtr SDFParser::GetElementPtr() const { return _sdf; } bool SDFParser::HasAttribute(const std::string& name) const { return _sdf->HasAttribute(name); } bool SDFParser::HasElement(const std::string& name) const { return _sdf->HasElement(name); } SDFStatus SDFParser::GetAttributeValue(const std::string& name, gsl::not_null<std::string*> value) const noexcept { value->clear(); if (HasAttribute(name)) { (*value) = _sdf->GetAttribute(name)->GetAsString(); return OkStatus(); } else { return AttributeNotFoundError(name); } } std::string SDFParser::GetAttributeValue(const std::string& name) const { if (!HasAttribute(name)) { throw AttributeNotFoundError(name); } return _sdf->GetAttribute(name)->GetAsString(); } SDFStatus SDFParser::GetElementText(const std::string& name, gsl::not_null<std::string*> value) const noexcept { value->clear(); if (HasElement(name)) { (*value) = _sdf->GetElement(name)->GetValue()->GetAsString(); return OkStatus(); } else { return ElementNotFoundError(name); } } std::string SDFParser::GetElementText(const std::string& name) const { if (!HasElement(name)) { throw ElementNotFoundError(name); } return _sdf->GetElement(name)->GetValue()->GetAsString(); } bool SDFParser::GetElementBool(const std::string& name) const { try { std::string strValue = GetElementText(name); try { return ParseBool(strValue); } catch (const std::exception& e) { throw ConversionError(name, strValue, "bool"); } } catch (const SDFStatus& e) { throw e; } } int SDFParser::GetElementInt(const std::string& name) const { try { std::string strValue = GetElementText(name); try { return ParseInt(strValue); } catch (const std::exception& e) { throw ConversionError(name, strValue, "int"); } } catch (const SDFStatus& e) { throw e; } } unsigned int SDFParser::GetElementUnsignedInt(const std::string& name) const { try { std::string strValue = GetElementText(name); try { return ParseUnsignedInt(strValue); } catch (const std::exception& e) { throw ConversionError(name, strValue, "unsigned int"); } } catch (const SDFStatus& e) { throw e; } } float SDFParser::GetElementFloat(const std::string& name) const { try { std::string strValue = GetElementText(name); try { return ParseFloat(strValue); } catch (const std::exception& e) { throw ConversionError(name, strValue, "float"); } } catch (const SDFStatus& e) { throw e; } } double SDFParser::GetElementDouble(const std::string& name) const { try { std::string strValue = GetElementText(name); try { return ParseDouble(strValue); } catch (const std::exception& e) { throw ConversionError(name, strValue, "double"); } } catch (const SDFStatus& e) { throw e; } } SDFStatus SDFParser::GetElementBool(const std::string& name, gsl::not_null<bool*> value) const noexcept { try { *value = GetElementBool(name); return OkStatus(); } catch (const SDFStatus& e) { return e; } } SDFStatus SDFParser::GetElementInt(const std::string& name, gsl::not_null<int*> value) const noexcept { try { *value = GetElementInt(name); return OkStatus(); } catch (const SDFStatus& e) { return e; } } SDFStatus SDFParser::GetElementUnsignedInt(const std::string& name, gsl::not_null<unsigned int*> value) const noexcept { try { *value = GetElementUnsignedInt(name); return OkStatus(); } catch (const SDFStatus& e) { return e; } } SDFStatus SDFParser::GetElementFloat(const std::string& name, gsl::not_null<float*> value) const noexcept { try { *value = GetElementFloat(name); return OkStatus(); } catch (const SDFStatus& e) { return e; } } SDFStatus SDFParser::GetElementDouble(const std::string& name, gsl::not_null<double*> value) const noexcept { try { *value = GetElementDouble(name); return OkStatus(); } catch (const SDFStatus& e) { return e; } }
19
118
0.656842
Guiraffo
48b7e0c4de443585c7baac70d42937cd33fc9edc
1,102
cpp
C++
src/audio/EmuEqualizer.cpp
AlexanderBrevig/emu-jukebox
131f73934e5aea4d587817b999e6869fa692d0ba
[ "BSD-2-Clause" ]
9
2019-03-09T16:55:00.000Z
2022-02-08T21:24:59.000Z
src/audio/EmuEqualizer.cpp
AlexanderBrevig/emu-jukebox
131f73934e5aea4d587817b999e6869fa692d0ba
[ "BSD-2-Clause" ]
69
2019-03-09T21:54:12.000Z
2021-12-26T09:30:20.000Z
src/audio/EmuEqualizer.cpp
AlexanderBrevig/emu-jukebox
131f73934e5aea4d587817b999e6869fa692d0ba
[ "BSD-2-Clause" ]
2
2019-03-11T19:03:54.000Z
2019-04-18T19:55:51.000Z
// // Created by robin on 16.01.19. // #include "EmuEqualizer.h" ebox::EmuEqualizer::EmuEqualizer() { } ebox::EmuEqualizer::EmuEqualizer(Music_Emu *emu) { initialize(emu); } void ebox::EmuEqualizer::draw() { if(m_emu != nullptr) { float treble = static_cast<float>(m_equalizer.treble); float bass = static_cast<float>(m_equalizer.bass); if (ImGui::SliderFloat("Treble", &treble, -50, 10, "%.0f")) m_emu->set_equalizer(m_equalizer); if (ImGui::SliderFloat("Bass", &bass, 16000, 1, "%.0f")) m_emu->set_equalizer(m_equalizer); m_equalizer.treble = treble; m_equalizer.bass = bass; } //ImGui::Text("-50.0 = muffled, 0 = flat, +5.0 = extra-crisp"); //if(ImGui::InputDouble("Treble", &m_equalizer.treble, 1, 5)) m_emu->set_equalizer(m_equalizer); //ImGui::Text("1 = full bass, 90 = average, 16000 = almost no bass"); //if(ImGui::InputDouble("Bass", &m_equalizer.bass, 1, 5)) m_emu->set_equalizer(m_equalizer); } void ebox::EmuEqualizer::initialize(Music_Emu *emu) { m_emu = emu; m_equalizer = emu->equalizer(); }
27.55
102
0.642468
AlexanderBrevig
48b9f6e55e869faa5fe81beea7479c6863ec5458
1,016
cpp
C++
stack-queue-deque/queue.cpp
rusucosmin/eMag---Hai-la-Olimpiada-
8adfa8e9cc6cf357e280a89e15b467c9cd77b2c2
[ "MIT" ]
null
null
null
stack-queue-deque/queue.cpp
rusucosmin/eMag---Hai-la-Olimpiada-
8adfa8e9cc6cf357e280a89e15b467c9cd77b2c2
[ "MIT" ]
null
null
null
stack-queue-deque/queue.cpp
rusucosmin/eMag---Hai-la-Olimpiada-
8adfa8e9cc6cf357e280a89e15b467c9cd77b2c2
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <stdio.h> #include <stack> using namespace std; stack<int> st1, st2; void push_back(int x) { printf(" read(%d)", x); printf(" push(1,%d)\n", x); st1.push(x); } void move() { while(st1.size() > 0) { printf(" pop(1)"); int x = st1.top(); st1.pop(); printf(" push(2,%d)", x); st2.push(x); } } void pop_back() { if(st2.size() == 0) move(); int x = st2.top(); st2.pop(); printf(" pop(2)"); printf(" write(%d)\n", x); } int main() { freopen("queue.in", "r", stdin); freopen("queue.out", "w", stdout); int n; scanf("%d\n", &n); for(int i = 0; i < n; ++ i) { printf("%d:", i + 1); int x; char a, b, s[100]; scanf("%c%c", &a, &b); if(a == 'p' && b == 'u') { scanf("sh_back(%d)\n", &x); push_back(x); } else { scanf("%s\n", s); pop_back(); } } }
17.824561
39
0.418307
rusucosmin
48be8f47fa1fcffc64d24d04606e30167ca2a31b
6,220
cpp
C++
src/wire/libevent_callbacks.cpp
xhad1234/peloton
60dea12ed528bc8873b1c43d1eca841a5d76ee44
[ "Apache-2.0" ]
2
2017-07-24T12:25:58.000Z
2022-03-17T11:43:42.000Z
src/wire/libevent_callbacks.cpp
xhad1234/peloton
60dea12ed528bc8873b1c43d1eca841a5d76ee44
[ "Apache-2.0" ]
2
2016-10-01T00:36:16.000Z
2016-11-05T23:40:07.000Z
src/wire/libevent_callbacks.cpp
xhad1234/peloton
60dea12ed528bc8873b1c43d1eca841a5d76ee44
[ "Apache-2.0" ]
3
2016-09-24T01:22:30.000Z
2019-01-09T16:17:25.000Z
//===----------------------------------------------------------------------===// // // Peloton // // libevent_callbacks.cpp // // Implements Libevent callbacks for the protocol and their helpers // // Identification: src/wire/libevent_callbacks.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <unistd.h> #include "wire/libevent_server.h" #include "common/macros.h" namespace peloton { namespace wire { void WorkerHandleNewConn(evutil_socket_t new_conn_recv_fd, UNUSED_ATTRIBUTE short ev_flags, void *arg) { // buffer used to receive messages from the main thread char m_buf[1]; std::shared_ptr<NewConnQueueItem> item; LibeventSocket *conn; LibeventWorkerThread *thread = static_cast<LibeventWorkerThread *>(arg); // pipe fds should match PL_ASSERT(new_conn_recv_fd == thread->new_conn_receive_fd); // read the operation that needs to be performed if (read(new_conn_recv_fd, m_buf, 1) != 1) { LOG_ERROR("Can't read from the libevent pipe"); return; } switch (m_buf[0]) { /* new connection case */ case 'c': { // fetch the new connection fd from the queue thread->new_conn_queue.Dequeue(item); conn = LibeventServer::GetConn(item->new_conn_fd); if (conn == nullptr) { LOG_DEBUG("Creating new socket fd:%d", item->new_conn_fd); /* create a new connection object */ LibeventServer::CreateNewConn(item->new_conn_fd, item->event_flags, static_cast<LibeventThread *>(thread), CONN_READ); } else { LOG_DEBUG("Reusing socket fd:%d", item->new_conn_fd); /* otherwise reset and reuse the existing conn object */ conn->Reset(); conn->Init(item->event_flags, static_cast<LibeventThread *>(thread), CONN_READ); } break; } default: LOG_ERROR("Unexpected message. Shouldn't reach here"); } } void EventHandler(UNUSED_ATTRIBUTE evutil_socket_t connfd, short ev_flags, void *arg) { LOG_TRACE("Event callback fired for connfd: %d", connfd); LibeventSocket *conn = static_cast<LibeventSocket *>(arg); PL_ASSERT(conn != nullptr); conn->event_flags = ev_flags; PL_ASSERT(connfd == conn->sock_fd); StateMachine(conn); } void StateMachine(LibeventSocket *conn) { bool done = false; while (done == false) { switch (conn->state) { case CONN_LISTENING: { struct sockaddr_storage addr; socklen_t addrlen = sizeof(addr); int new_conn_fd = accept(conn->sock_fd, (struct sockaddr *)&addr, &addrlen); if (new_conn_fd == -1) { LOG_ERROR("Failed to accept"); } (static_cast<LibeventMasterThread *>(conn->thread)) ->DispatchConnection(new_conn_fd, EV_READ | EV_PERSIST); done = true; break; } case CONN_READ: { auto res = conn->FillReadBuffer(); switch (res) { case READ_DATA_RECEIVED: // wait for some other event conn->TransitState(CONN_PROCESS); break; case READ_NO_DATA_RECEIVED: // process what we read conn->TransitState(CONN_WAIT); break; case READ_ERROR: // fatal error for the connection conn->TransitState(CONN_CLOSING); break; } break; } case CONN_WAIT : { if (conn->UpdateEvent(EV_READ | EV_PERSIST) == false) { LOG_ERROR("Failed to update event, closing"); conn->TransitState(CONN_CLOSING); break; } conn->TransitState(CONN_READ); done = true; break; } case CONN_PROCESS : { bool status; if (conn->rpkt.header_parsed == false) { // parse out the header first if (conn->ReadPacketHeader() == false) { // need more data conn->TransitState(CONN_WAIT); break; } } PL_ASSERT(conn->rpkt.header_parsed == true); if (conn->rpkt.is_initialized == false) { // packet needs to be initialized with rest of the contents if (conn->ReadPacket() == false) { // need more data conn->TransitState(CONN_WAIT); break; } } PL_ASSERT(conn->rpkt.is_initialized == true); if (conn->pkt_manager.is_started == false) { // We need to handle startup packet first status = conn->pkt_manager.ProcessStartupPacket(&conn->rpkt); conn->pkt_manager.is_started = true; } else { // Process all other packets status = conn->pkt_manager.ProcessPacket(&conn->rpkt); } if (status == false) { // packet processing can't proceed further conn->TransitState(CONN_CLOSING); } else { // We should have responses ready to send conn->TransitState(CONN_WRITE); } break; } case CONN_WRITE: { // examine write packets result switch(conn->WritePackets()) { case WRITE_COMPLETE: { // Input Packet can now be reset, before we parse the next packet conn->rpkt.Reset(); conn->UpdateEvent(EV_READ | EV_PERSIST); conn->TransitState(CONN_PROCESS); break; } case WRITE_NOT_READY: { // we can't write right now. Exit state machine // and wait for next callback done = true; break; } case WRITE_ERROR: { LOG_ERROR("Error during write, closing connection"); conn->TransitState(CONN_CLOSING); break; } } break; } case CONN_CLOSING: { conn->CloseSocket(); done = true; break; } case CONN_CLOSED: { done = true; break; } case CONN_INVALID: { PL_ASSERT(false); break; } } } } } }
28.796296
87
0.555466
xhad1234
48befcbd7f437ad897f4935c59fb6c8a2d7fe457
951
hpp
C++
abcd/util/Debug.hpp
Airbitz/airbitz-core-private
dc6742a5622f6d8bae750e60fcee3bb473bc67ce
[ "BSD-2-Clause-FreeBSD" ]
1
2021-05-28T02:52:00.000Z
2021-05-28T02:52:00.000Z
abcd/util/Debug.hpp
Airbitz/airbitz-core-private
dc6742a5622f6d8bae750e60fcee3bb473bc67ce
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
abcd/util/Debug.hpp
Airbitz/airbitz-core-private
dc6742a5622f6d8bae750e60fcee3bb473bc67ce
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
/* * Copyright (c) 2015, Airbitz, Inc. * All rights reserved. * * See the LICENSE file for more information. */ #ifndef ABC_UTIL_DEBUG_HPP #define ABC_UTIL_DEBUG_HPP #include "Status.hpp" #include "Data.hpp" #define DEBUG_LEVEL 1 #define ABC_DebugLevel(level, ...) \ { \ if (DEBUG_LEVEL >= level) \ { \ ABC_DebugLog(__VA_ARGS__); \ } \ } #define ABC_Debug(level, STR) \ { \ if (DEBUG_LEVEL >= level) \ { \ logInfo(STR); \ } \ } namespace abcd { Status debugInitialize(); void debugTerminate(); DataChunk debugLogLoad(); void ABC_DebugLog(const char *format, ...); /** * Like `ABC_DebugLog`, but takes `std::string`. */ void logInfo(const std::string &message); } // namespace abcd #endif
17.943396
48
0.500526
Airbitz
48c1a6dd1f2af3f73146257ac08639a7ba02b21e
2,551
cpp
C++
higan/ms/cpu/bus.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
38
2018-04-05T05:00:05.000Z
2022-02-06T00:02:02.000Z
higan/ms/cpu/bus.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
1
2018-04-29T19:45:14.000Z
2018-04-29T19:45:14.000Z
higan/ms/cpu/bus.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
8
2018-04-16T22:37:46.000Z
2021-02-10T07:37:03.000Z
auto CPU::read(uint16 addr) -> uint8 { uint8 data; if(auto result = cartridge.read(addr)) { data = result(); } else if(addr >= 0xc000) { data = ram[addr & 0x1fff]; } if(auto result = cheat.find(addr, data)) { data = result(); } return data; } auto CPU::write(uint16 addr, uint8 data) -> void { if(cartridge.write(addr, data)) { } else if(addr >= 0xc000) { ram[addr & 0x1fff] = data; } } auto CPU::in(uint8 addr) -> uint8 { switch(addr >> 6) { case 0: { if(Model::GameGear()) { bool start = !platform->inputPoll(ID::Port::Hardware, ID::Device::GameGearControls, 6); return start << 7 | 0x7f; } return 0xff; //SMS1 = MDR, SMS2 = 0xff } case 1: { return !addr.bit(0) ? vdp.vcounter() : vdp.hcounter(); } case 2: { return !addr.bit(0) ? vdp.data() : vdp.status(); } case 3: { if(Model::MasterSystem()) { bool reset = !platform->inputPoll(ID::Port::Hardware, ID::Device::MasterSystemControls, 0); auto port1 = controllerPort1.device->readData(); auto port2 = controllerPort2.device->readData(); if(addr.bit(0) == 0) { return port1.bits(0,5) << 0 | port2.bits(0,1) << 6; } else { return port2.bits(2,5) << 0 | reset << 4 | 1 << 5 | port1.bit(6) << 6 | port2.bit(6) << 7; } } if(Model::GameGear()) { bool up = !platform->inputPoll(ID::Port::Hardware, ID::Device::GameGearControls, 0); bool down = !platform->inputPoll(ID::Port::Hardware, ID::Device::GameGearControls, 1); bool left = !platform->inputPoll(ID::Port::Hardware, ID::Device::GameGearControls, 2); bool right = !platform->inputPoll(ID::Port::Hardware, ID::Device::GameGearControls, 3); bool one = !platform->inputPoll(ID::Port::Hardware, ID::Device::GameGearControls, 4); bool two = !platform->inputPoll(ID::Port::Hardware, ID::Device::GameGearControls, 5); if(!up && !down) up = 1, down = 1; if(!left && !right) left = 1, right = 1; if(addr.bit(0) == 0) { return up << 0 | down << 1 | left << 2 | right << 3 | one << 4 | two << 5 | 1 << 6 | 1 << 7; } else { return 0xff; } } return 0xff; } } return 0xff; } auto CPU::out(uint8 addr, uint8 data) -> void { if(addr == 0x06) { if(Model::GameGear()) return psg.balance(data); } switch(addr >> 6) { case 1: { return psg.write(data); } case 2: { return !addr.bit(0) ? vdp.data(data) : vdp.control(data); } case 3: { return; //unmapped } } }
25.257426
100
0.562132
13824125580
48c6adf5b49d812490b42bf2b9278003439506bd
5,649
cpp
C++
windows/win_socket_io_impl.cpp
jc-lab/mev
553ab28ec5c49bde8dc74b86f5eba6c882078490
[ "Apache-2.0" ]
null
null
null
windows/win_socket_io_impl.cpp
jc-lab/mev
553ab28ec5c49bde8dc74b86f5eba6c882078490
[ "Apache-2.0" ]
null
null
null
windows/win_socket_io_impl.cpp
jc-lab/mev
553ab28ec5c49bde8dc74b86f5eba6c882078490
[ "Apache-2.0" ]
null
null
null
/** * @file win_socket_io_impl.cpp * @class mev::win_socket_io_impl * @author Jichan (development@jc-lab.net / http://ablog.jc-lab.net/176 ) * @copyright Copyright (C) 2019 jichan.\n * This software may be modified and distributed under the terms * of the Apache License 2.0. See the LICENSE file for details. */ #include "win_socket_io_impl.hpp" #if defined(MEV_WINDOWS) && MEV_WINDOWS #include "mswsock.h" #pragma comment(lib,"ws2_32.lib") #pragma comment(lib,"mswsock.lib") namespace mev { safeobj<socket_io> wrap_socket(mev::socket_t socket) { return windows::win_socket_io_impl::wrap_socket(socket); } namespace windows { safeobj<win_socket_io_impl> win_socket_io_impl::wrap_socket(SOCKET handle) { safeobj<win_socket_io_impl> obj(new win_socket_io_impl(handle)); return obj; } win_socket_io_impl::win_socket_io_impl(SOCKET handle) { handle_ = handle; is_acceptance_ = false; is_recvfrom_ = false; accept_socket_ = NULL; } win_socket_io_impl::~win_socket_io_impl() { event_closed(NULL); } void* win_socket_io_impl::io_handle() const { return (void*)handle_; } int win_socket_io_impl::start_accept(void* platform_event_ctx) { int nrst; DWORD dwFlags = 0; LPOVERLAPPED pov = (LPOVERLAPPED)platform_event_ctx; is_acceptance_ = true; d_recv_buf_.resize(sizeof(sockaddr_storage) * 2); accept_socket_ = ::WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, NULL, WSA_FLAG_OVERLAPPED); nrst = ::AcceptEx(handle_, accept_socket_, &d_recv_buf_[0], 0, sizeof(sockaddr_storage), sizeof(sockaddr_storage), &d_recv_tfbytes_, pov); return nrst; } int win_socket_io_impl::start_recv(void* platform_event_ctx, int buf_size) { int nrst; DWORD dwFlags = 0; LPOVERLAPPED pov = (LPOVERLAPPED)platform_event_ctx; if (buf_size > 0) { d_recv_buf_.resize(buf_size); } else if (d_recv_buf_.size() == 0) { d_recv_buf_.resize(8192); } is_recvfrom_ = false; w_recv_buf_.buf = (CHAR*)& d_recv_buf_[0]; w_recv_buf_.len = d_recv_buf_.size(); nrst = ::WSARecv(handle_, &w_recv_buf_, 1, &d_recv_tfbytes_, &dwFlags, pov, NULL); return nrst; } int win_socket_io_impl::start_recvfrom(void* platform_event_ctx, int buf_size) { int nrst; DWORD dwFlags = 0; LPOVERLAPPED pov = (LPOVERLAPPED)platform_event_ctx; if (buf_size > 0) { d_recv_buf_.resize(buf_size); } else if (d_recv_buf_.size() == 0) { d_recv_buf_.resize(8192); } is_recvfrom_ = true; w_recv_buf_.buf = (CHAR*)& d_recv_buf_[0]; w_recv_buf_.len = d_recv_buf_.size(); d_recv_from_len_ = sizeof(d_recv_from_stor_); nrst = ::WSARecvFrom(handle_, &w_recv_buf_, 1, &d_recv_tfbytes_, &dwFlags, (sockaddr*)&d_recv_from_stor_, &d_recv_from_len_, pov, NULL); return nrst; } int win_socket_io_impl::start_send(void* platform_event_ctx, const void* data_ptr, int data_size) { int nrst; DWORD dwFlags = 0; LPOVERLAPPED pov = (LPOVERLAPPED)platform_event_ctx; WSABUF wsabuf; DWORD dwTransfferedBytes = 0; wsabuf.buf = (CHAR*)data_ptr; wsabuf.len = data_size; nrst = ::WSASend(handle_, &wsabuf, 1, &dwTransfferedBytes, 0, pov, NULL); return nrst; } void win_socket_io_impl::event_closed(loop* _loop) { if (accept_socket_) { ::closesocket(accept_socket_); accept_socket_ = NULL; } if (handle_) { ::shutdown(handle_, SD_BOTH); ::closesocket(handle_); handle_ = NULL; } } int win_socket_io_impl::mev_event(const safeobj<event_source>& evt_src, event_handler* user_handler, loop* _loop, event_type evt_type, void* userctx, event_info* evt_info) { int rc = -1; if ((evt_type & EVENT_READ) && is_acceptance_) { const unsigned char* bufptr = &d_recv_buf_[0]; socket_accept_event_info evtinfo; evtinfo.client_socket = accept_socket_; GetAcceptExSockaddrs((PVOID)bufptr, 0, sizeof(sockaddr_storage), sizeof(sockaddr_storage), &evtinfo.local_addr, &evtinfo.local_addr_len, &evtinfo.remote_addr, &evtinfo.remote_addr_len); rc = user_handler->mev_event(_loop, evt_src, evt_type, userctx, &evtinfo); if (handle_) { accept_socket_ = ::WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, NULL, WSA_FLAG_OVERLAPPED); rc = start_accept(evt_info->platform_event_ctx); } } else if ((evt_type & EVENT_READ) && !is_recvfrom_) { socket_recv_event_info evtinfo; evtinfo.transferred_size = evt_info->transferred_size; evtinfo.recv_buf = (const char*)& d_recv_buf_[0]; evtinfo.recv_size = evt_info->transferred_size; rc = user_handler->mev_event(_loop, evt_src, evt_type, userctx, &evtinfo); if (rc == 0) { if ((!(evt_type & EVENT_ONCE)) && handle_) rc = start_recv(evt_info->platform_event_ctx); } } else if ((evt_type & EVENT_READ) && is_recvfrom_) { socket_recvfrom_event_info evtinfo; evtinfo.transferred_size = evt_info->transferred_size; evtinfo.recv_buf = (const char*)& d_recv_buf_[0]; evtinfo.recv_size = evt_info->transferred_size; evtinfo.remote_addr = (sockaddr*)&d_recv_from_stor_; evtinfo.remote_addr_len = d_recv_from_len_; rc = user_handler->mev_event(_loop, evt_src, evt_type, userctx, &evtinfo); if (rc == 0) { if ((!(evt_type & EVENT_ONCE)) && handle_) rc = start_recvfrom(evt_info->platform_event_ctx); } } else if (evt_type & EVENT_WRITE) { socket_send_event_info evtinfo; evtinfo.transferred_size = evt_info->transferred_size; if(user_handler) rc = user_handler->mev_event(_loop, evt_src, evt_type, userctx, &evtinfo); } return rc; } } } #endif
31.735955
189
0.701717
jc-lab
48c86877a2224e4bd32455579428f1b9d68b83de
3,321
cpp
C++
mainwindow.cpp
isc1/QtThread01
7f74601091ec35cee7c89546365be6400f386fbb
[ "MIT" ]
null
null
null
mainwindow.cpp
isc1/QtThread01
7f74601091ec35cee7c89546365be6400f386fbb
[ "MIT" ]
null
null
null
mainwindow.cpp
isc1/QtThread01
7f74601091ec35cee7c89546365be6400f386fbb
[ "MIT" ]
null
null
null
// QtThread01 -- simple threaded GUI example // see README.md for description. // This code was written on Qt 5.11.1 on Windows 10. It may run on OS X and Linux with // modifications but we haven't done that. // This code is copyright 2018 inhabited.systems, and is shared under the MIT license. // (See file MIT-License.txt) This code is unsupported. #include "mainwindow.h" extern QMutex mutex; extern qreal locx; extern qreal locy; extern int shutdowncounter; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , mSceneWidth(600) , mSceneHeight(600) , mGraphicsScene(Q_NULLPTR) , mGraphicsView(Q_NULLPTR) , mEllipseItem(Q_NULLPTR) , mCircleSize(100) , mAppLoopUpdateInterval(5) // in milliseconds { setGeometry(0,0,mSceneWidth,mSceneHeight); QWidget *centralWidget = new QWidget(this); setCentralWidget(centralWidget); mGraphicsScene = new QGraphicsScene(parent); mGraphicsView = new QGraphicsView(mGraphicsScene); mGraphicsView->setGeometry(0,0,mSceneWidth,mSceneHeight); QLayout *mylayout = new QHBoxLayout(); centralWidget->setLayout(mylayout); mylayout->addWidget(mGraphicsView); QPen mypen; QBrush mybrush; mypen.setColor(QColor(Qt::transparent)); mypen.setWidth(1); mypen.setStyle(Qt::PenStyle(1)); mybrush.setColor(QColor(0,0,0)); // set a background color QGraphicsRectItem *rect_item1 = mGraphicsScene->addRect(0, 0, mSceneWidth, mSceneHeight); rect_item1->setBrush(QColor(255, 243, 230)); // light tan // create a reference square on the screen to help see where the circle ends up QGraphicsRectItem *rect_item2 = mGraphicsScene->addRect(mSceneWidth/4+mCircleSize/1.35, mSceneHeight/4+mCircleSize/1.35, mSceneWidth/4, mSceneHeight/4); // add the circle that is going to animate mEllipseItem = new QGraphicsEllipseItem(0,0,mCircleSize,mCircleSize); mGraphicsScene->addItem(mEllipseItem); locx = 30; locy = (mSceneHeight/2) - (mCircleSize/2); mGraphicsScene->addEllipse(locx,locy,mCircleSize,mCircleSize,mypen,mybrush); // For some reason, the previous addEllipse doesn't seem to setX,setY to locx,locy // so we have to do it explicitly: mEllipseItem->setX(locx); mEllipseItem->setY(locy); startAppLoopTimer(); } MainWindow::~MainWindow() { // I set this to try to tell threads to quit, but it doesn't work. We need to catch the // user clicking the X button to close the window, and make the threads quit from that. // try https://stackoverflow.com/a/26185770/10355150 shutdowncounter = 0; } void MainWindow::startAppLoopTimer() { // associate the signal timeout() to the slot appLoopTick(), and start our update timer QObject::connect(&mAppLoopTimer, SIGNAL(timeout()), this, SLOT(appLoopTick())); mAppLoopTimer.start(5); //qDebug() << __FUNCTION__ << "complete."; } void MainWindow::appLoopTick() { updatecircle(); shutdowncounter--; //qDebug() << "(mainwindow)" << __FUNCTION__ << "locx:" << locx << "shutdowncounter: " << shutdowncounter; mGraphicsScene->advance(); } void MainWindow::updatecircle() { if (mEllipseItem == nullptr) return; //qDebug() << "(mainwindow)" << __FUNCTION__ << "locx:" << locx << "shutdowncounter: " << shutdowncounter; mEllipseItem->setX(locx); }
34.59375
156
0.710027
isc1
48c90c29e5117c4520178a9f3f3d505cfb1dbf53
14,043
cpp
C++
Extern/JUCE/extras/JuceDemo/Source/demos/AudioDemoSynthPage.cpp
vinniefalco/SimpleDJ
30cf1929eaaf0906a1056a33378e8b330062c691
[ "MIT" ]
27
2015-05-07T02:10:39.000Z
2021-06-22T14:52:50.000Z
Extern/JUCE/extras/JuceDemo/Source/demos/AudioDemoSynthPage.cpp
JoseDiazRohena/SimpleDJ
30cf1929eaaf0906a1056a33378e8b330062c691
[ "MIT" ]
null
null
null
Extern/JUCE/extras/JuceDemo/Source/demos/AudioDemoSynthPage.cpp
JoseDiazRohena/SimpleDJ
30cf1929eaaf0906a1056a33378e8b330062c691
[ "MIT" ]
14
2015-09-12T12:00:22.000Z
2022-03-08T22:24:24.000Z
/* ============================================================================== This is an automatically generated file created by the Jucer! Creation date: 21 Sep 2012 12:10:20pm Be careful when adding custom code to these files, as only the code within the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded and re-saved. Jucer version: 1.12 ------------------------------------------------------------------------------ The Jucer is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-6 by Raw Material Software ltd. ============================================================================== */ //[Headers] You can add your own extra header files here... //[/Headers] #include "AudioDemoSynthPage.h" //[MiscUserDefs] You can add your own user definitions and misc code here... //============================================================================== /** Our demo synth sound is just a basic sine wave.. */ class SineWaveSound : public SynthesiserSound { public: SineWaveSound() { } bool appliesToNote (const int /*midiNoteNumber*/) { return true; } bool appliesToChannel (const int /*midiChannel*/) { return true; } }; //============================================================================== /** Our demo synth voice just plays a sine wave.. */ class SineWaveVoice : public SynthesiserVoice { public: SineWaveVoice() : angleDelta (0.0), tailOff (0.0) { } bool canPlaySound (SynthesiserSound* sound) { return dynamic_cast <SineWaveSound*> (sound) != 0; } void startNote (const int midiNoteNumber, const float velocity, SynthesiserSound* /*sound*/, const int /*currentPitchWheelPosition*/) { currentAngle = 0.0; level = velocity * 0.15; tailOff = 0.0; double cyclesPerSecond = MidiMessage::getMidiNoteInHertz (midiNoteNumber); double cyclesPerSample = cyclesPerSecond / getSampleRate(); angleDelta = cyclesPerSample * 2.0 * double_Pi; } void stopNote (const bool allowTailOff) { if (allowTailOff) { // start a tail-off by setting this flag. The render callback will pick up on // this and do a fade out, calling clearCurrentNote() when it's finished. if (tailOff == 0.0) // we only need to begin a tail-off if it's not already doing so - the // stopNote method could be called more than once. tailOff = 1.0; } else { // we're being told to stop playing immediately, so reset everything.. clearCurrentNote(); angleDelta = 0.0; } } void pitchWheelMoved (const int /*newValue*/) { // can't be bothered implementing this for the demo! } void controllerMoved (const int /*controllerNumber*/, const int /*newValue*/) { // not interested in controllers in this case. } void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples) { if (angleDelta != 0.0) { if (tailOff > 0) { while (--numSamples >= 0) { const float currentSample = (float) (sin (currentAngle) * level * tailOff); for (int i = outputBuffer.getNumChannels(); --i >= 0;) *outputBuffer.getSampleData (i, startSample) += currentSample; currentAngle += angleDelta; ++startSample; tailOff *= 0.99; if (tailOff <= 0.005) { clearCurrentNote(); angleDelta = 0.0; break; } } } else { while (--numSamples >= 0) { const float currentSample = (float) (sin (currentAngle) * level); for (int i = outputBuffer.getNumChannels(); --i >= 0;) *outputBuffer.getSampleData (i, startSample) += currentSample; currentAngle += angleDelta; ++startSample; } } } } private: double currentAngle, angleDelta, level, tailOff; }; // This is an audio source that streams the output of our demo synth. class SynthAudioSource : public AudioSource { public: //============================================================================== // this collects real-time midi messages from the midi input device, and // turns them into blocks that we can process in our audio callback MidiMessageCollector midiCollector; // this represents the state of which keys on our on-screen keyboard are held // down. When the mouse is clicked on the keyboard component, this object also // generates midi messages for this, which we can pass on to our synth. MidiKeyboardState& keyboardState; // the synth itself! Synthesiser synth; //============================================================================== SynthAudioSource (MidiKeyboardState& keyboardState_) : keyboardState (keyboardState_) { // add some voices to our synth, to play the sounds.. for (int i = 4; --i >= 0;) { synth.addVoice (new SineWaveVoice()); // These voices will play our custom sine-wave sounds.. synth.addVoice (new SamplerVoice()); // and these ones play the sampled sounds } // and add some sounds for them to play... setUsingSineWaveSound(); } void setUsingSineWaveSound() { synth.clearSounds(); synth.addSound (new SineWaveSound()); } void setUsingSampledSound() { synth.clearSounds(); WavAudioFormat wavFormat; ScopedPointer<AudioFormatReader> audioReader (wavFormat.createReaderFor (new MemoryInputStream (BinaryData::cello_wav, BinaryData::cello_wavSize, false), true)); BigInteger allNotes; allNotes.setRange (0, 128, true); synth.addSound (new SamplerSound ("demo sound", *audioReader, allNotes, 74, // root midi note 0.1, // attack time 0.1, // release time 10.0 // maximum sample length )); } void prepareToPlay (int /*samplesPerBlockExpected*/, double sampleRate) { midiCollector.reset (sampleRate); synth.setCurrentPlaybackSampleRate (sampleRate); } void releaseResources() { } void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) { // the synth always adds its output to the audio buffer, so we have to clear it // first.. bufferToFill.clearActiveBufferRegion(); // fill a midi buffer with incoming messages from the midi input. MidiBuffer incomingMidi; midiCollector.removeNextBlockOfMessages (incomingMidi, bufferToFill.numSamples); // pass these messages to the keyboard state so that it can update the component // to show on-screen which keys are being pressed on the physical midi keyboard. // This call will also add midi messages to the buffer which were generated by // the mouse-clicking on the on-screen keyboard. keyboardState.processNextMidiBuffer (incomingMidi, 0, bufferToFill.numSamples, true); // and now get the synth to process the midi events and generate its output. synth.renderNextBlock (*bufferToFill.buffer, incomingMidi, 0, bufferToFill.numSamples); } }; //[/MiscUserDefs] //============================================================================== AudioDemoSynthPage::AudioDemoSynthPage (AudioDeviceManager& deviceManager_) : deviceManager (deviceManager_), keyboardComponent (0), sineButton (0), sampledButton (0), liveAudioDisplayComp (0) { addAndMakeVisible (keyboardComponent = new MidiKeyboardComponent (keyboardState, MidiKeyboardComponent::horizontalKeyboard)); addAndMakeVisible (sineButton = new ToggleButton (String::empty)); sineButton->setButtonText ("Use sine wave"); sineButton->setRadioGroupId (321); sineButton->addListener (this); sineButton->setToggleState (true, false); addAndMakeVisible (sampledButton = new ToggleButton (String::empty)); sampledButton->setButtonText ("Use sampled sound"); sampledButton->setRadioGroupId (321); sampledButton->addListener (this); addAndMakeVisible (liveAudioDisplayComp = new LiveAudioInputDisplayComp()); //[UserPreSize] //[/UserPreSize] setSize (600, 400); //[Constructor] You can add your own custom stuff here.. deviceManager.addAudioCallback (liveAudioDisplayComp); synthAudioSource = new SynthAudioSource (keyboardState); audioSourcePlayer.setSource (synthAudioSource); deviceManager.addAudioCallback (&audioSourcePlayer); deviceManager.addMidiInputCallback (String::empty, &(synthAudioSource->midiCollector)); //[/Constructor] } AudioDemoSynthPage::~AudioDemoSynthPage() { //[Destructor_pre]. You can add your own custom destruction code here.. audioSourcePlayer.setSource (0); deviceManager.removeMidiInputCallback (String::empty, &(synthAudioSource->midiCollector)); deviceManager.removeAudioCallback (&audioSourcePlayer); deviceManager.removeAudioCallback (liveAudioDisplayComp); //[/Destructor_pre] deleteAndZero (keyboardComponent); deleteAndZero (sineButton); deleteAndZero (sampledButton); deleteAndZero (liveAudioDisplayComp); //[Destructor]. You can add your own custom destruction code here.. //[/Destructor] } //============================================================================== void AudioDemoSynthPage::paint (Graphics& g) { //[UserPrePaint] Add your own custom painting code here.. //[/UserPrePaint] g.fillAll (Colours::lightgrey); //[UserPaint] Add your own custom painting code here.. //[/UserPaint] } void AudioDemoSynthPage::resized() { keyboardComponent->setBounds (8, 96, getWidth() - 16, 64); sineButton->setBounds (16, 176, 150, 24); sampledButton->setBounds (16, 200, 150, 24); liveAudioDisplayComp->setBounds (8, 8, getWidth() - 16, 64); //[UserResized] Add your own custom resize handling here.. //[/UserResized] } void AudioDemoSynthPage::buttonClicked (Button* buttonThatWasClicked) { //[UserbuttonClicked_Pre] //[/UserbuttonClicked_Pre] if (buttonThatWasClicked == sineButton) { //[UserButtonCode_sineButton] -- add your button handler code here.. synthAudioSource->setUsingSineWaveSound(); //[/UserButtonCode_sineButton] } else if (buttonThatWasClicked == sampledButton) { //[UserButtonCode_sampledButton] -- add your button handler code here.. synthAudioSource->setUsingSampledSound(); //[/UserButtonCode_sampledButton] } //[UserbuttonClicked_Post] //[/UserbuttonClicked_Post] } //[MiscUserCode] You can add your own definitions of your custom methods or any other code here... //[/MiscUserCode] //============================================================================== #if 0 /* -- Jucer information section -- This is where the Jucer puts all of its metadata, so don't change anything in here! BEGIN_JUCER_METADATA <JUCER_COMPONENT documentType="Component" className="AudioDemoSynthPage" componentName="" parentClasses="public Component" constructorParams="AudioDeviceManager&amp; deviceManager_" variableInitialisers="deviceManager (deviceManager_)" snapPixels="8" snapActive="1" snapShown="1" overlayOpacity="0.330000013" fixedSize="0" initialWidth="600" initialHeight="400"> <BACKGROUND backgroundColour="ffd3d3d3"/> <GENERICCOMPONENT name="" id="86605ec4f02c4320" memberName="keyboardComponent" virtualName="" explicitFocusOrder="0" pos="8 96 16M 64" class="MidiKeyboardComponent" params="keyboardState, MidiKeyboardComponent::horizontalKeyboard"/> <TOGGLEBUTTON name="" id="d75101df45006ba9" memberName="sineButton" virtualName="" explicitFocusOrder="0" pos="16 176 150 24" buttonText="Use sine wave" connectedEdges="0" needsCallback="1" radioGroupId="321" state="1"/> <TOGGLEBUTTON name="" id="2d687b4ac3dad628" memberName="sampledButton" virtualName="" explicitFocusOrder="0" pos="16 200 150 24" buttonText="Use sampled sound" connectedEdges="0" needsCallback="1" radioGroupId="321" state="0"/> <GENERICCOMPONENT name="" id="7d70eb2617f56220" memberName="liveAudioDisplayComp" virtualName="" explicitFocusOrder="0" pos="8 8 16M 64" class="LiveAudioInputDisplayComp" params=""/> </JUCER_COMPONENT> END_JUCER_METADATA */ #endif
36.007692
131
0.564053
vinniefalco
48c9b67d799cdd591e7c463bc3f8c5f91a8e7a65
2,890
cc
C++
xigen/src/locale.cc
EPC-MSU/libximc
b0349721f57c8274b098a7b646d7ae67b8e70b9d
[ "BSD-2-Clause" ]
3
2020-12-08T14:41:48.000Z
2022-02-23T13:42:42.000Z
xigen/src/locale.cc
EPC-MSU/libximc
b0349721f57c8274b098a7b646d7ae67b8e70b9d
[ "BSD-2-Clause" ]
4
2020-12-08T20:15:06.000Z
2021-12-08T14:15:24.000Z
xigen/src/locale.cc
EPC-MSU/libximc
b0349721f57c8274b098a7b646d7ae67b8e70b9d
[ "BSD-2-Clause" ]
2
2020-11-02T02:17:35.000Z
2021-03-18T14:13:56.000Z
#include "common.hh" #include "model.hh" #include "generatorhelper.hh" #include "locale.hh" namespace xigen { // Russian class LocaleRussian : public Locale { public: std::string extractDoxygenComment(const Comment& comment) const { return helpers::extractLanguageDoxygenComment(comment,"russian"); } std::string extractDoxygenCommentOneLine(const Comment& comment) const { return helpers::extractLanguageDoxygenComment(comment, "russian", helpers::onlyOneLine); } std::string extractDoxygenCommentDescription(const Comment& comment) const { return helpers::extractLanguageDoxygenComment(comment, "russian", helpers::skipFirstLine); } std::string pluralizeBytes (int amount) const { return helpers::pluralize( amount, "байт", "байта", "байт"); } std::string wikiCommandCode () const { return "Код команды"; }; std::string wikiCommand () const { return "Команда"; }; std::string wikiCommandBack () const { return "Команда (возврат)"; }; std::string wikiRequest () const { return "Запрос"; }; std::string wikiAnswer () const { return "Ответ"; }; std::string wikiCRC () const { return "Контрольная сумма"; }; std::string wikiOr () const { return "Или"; }; std::string wikiReserved () const { return "Зарезервировано"; }; std::string wikiDescription () const { return "Описание"; }; }; // English class LocaleEnglish : public Locale { public: std::string extractDoxygenComment(const Comment& comment) const { return helpers::extractLanguageDoxygenComment(comment, "english"); } std::string extractDoxygenCommentOneLine(const Comment& comment) const { return helpers::extractLanguageDoxygenComment(comment, "english", helpers::onlyOneLine); } std::string extractDoxygenCommentDescription(const Comment& comment) const { return helpers::extractLanguageDoxygenComment(comment, "english", helpers::skipFirstLine); } std::string pluralizeBytes (int amount) const { return helpers::pluralize( amount, "byte", "bytes", "bytes"); } std::string wikiCommandCode () const { return "Command code"; }; std::string wikiCommand () const { return "Command"; }; std::string wikiCommandBack () const { return "Command (answer)"; }; std::string wikiRequest () const { return "Request"; }; std::string wikiAnswer () const { return "Answer"; }; std::string wikiCRC () const { return "Checksum"; }; std::string wikiOr () const { return "Or"; }; std::string wikiReserved () const { return "Reserved"; }; std::string wikiDescription () const { return "Description"; }; }; // Factory Locale* LocaleFactory::createLocale (Lang lang) { switch (lang) { case russian: return new LocaleRussian(); case english: return new LocaleEnglish(); default: throw std::runtime_error( "Wrong locale specified" ); } } } /* vim: set ts=2 sw=2: */
30.104167
93
0.692042
EPC-MSU