blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
โŒ€
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
โŒ€
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
โŒ€
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
72657ed7c0558e5f13ffee8c6e247e0460c694d8
ea19ea0929a84362a4dd9f6c8a02d3ea185d5fa5
/software/examples/cpp/01-temperatures/main.cpp
5823edba817b87163874d4386f03e9cbe7abb7ab
[ "MIT" ]
permissive
esysberlin/lufo-ifez-datenkonzentrator
bc96568d8a65f775332536514e6a1fac69d9580e
f803724b316e2df46e69afab91afa22c64a8d920
refs/heads/master
2020-04-15T05:48:02.151118
2019-10-21T15:31:57
2019-10-21T15:31:57
164,437,649
2
0
null
null
null
null
UTF-8
C++
false
false
570
cpp
main.cpp
#include "now.h" #include "spi.h" #include <iostream> int main() { const auto NUM_QUERIES = 1000; std::string spiResponse = ""; auto begin = Now::msSinceEpoch(); for (auto i = 0; i < NUM_QUERIES; ++i) { spiResponse = Spi::query(Spi::SLAVE_THERMO_ELEMENTS, Spi::CMD_THERMO_ELEMENTS_GET_TEMPERATURES); } auto end = Now::msSinceEpoch(); std::cout << "It took " << end - begin << "ms to query the temperature sensors " << NUM_QUERIES << " times." << std::endl; std::cout << "Last response: " << spiResponse << std::endl; return 0; }
4ea3672759c274f565461712dcfcc8862c9e0f1e
8ee0be0b14ec99858712a5c37df4116a52cb9801
/Client/Interface/DLGs/CSeparateDlg.cpp
5e2c2815e1d53282bb7286d29a390ca2ebd61cb1
[]
no_license
eRose-DatabaseCleaning/Sources-non-evo
47968c0a4fd773d6ff8c9eb509ad19caf3f48d59
2b152f5dba3bce3c135d98504ebb7be5a6c0660e
refs/heads/master
2021-01-13T14:31:36.871082
2019-05-24T14:46:41
2019-05-24T14:46:41
72,851,710
6
3
null
2016-11-14T23:30:24
2016-11-04T13:47:51
C++
UHC
C++
false
false
8,659
cpp
CSeparateDlg.cpp
#include "stdafx.h" #include ".\cseparatedlg.h" #include "../CDragItem.h" #include "../icon/ciconitem.h" #include "../it_mgr.h" #include "../command/uicommand.h" #include "../../common/cinventory.h" #include "../../gamedata/event/cteventseparate.h" #include "../../gamedata/cseparate.h" #include "../../gamecommon/item.h" #include "../../object.h" #include "../TypeResource.h" CSeparateDlg::CSeparateDlg(void) { CSlot Slot; POINT pt = { 169, 172 }; int iType = DLG_TYPE_SEPARATE; for( int i = 0; i < 4; ++i ) { Slot.SetOffset( pt ); Slot.SetParent( iType ); m_OutputItemSlots.push_back( Slot ); pt.y += 46; } ///์ œ์กฐํ•  ์•„์ดํ…œ์ด ๋“ค์–ด๊ฐˆ Slot m_pDragItem = new CDragItem; CTCommand* pCmd = new CTCmdTakeOutItemFromSeparateDlg; m_pDragItem->AddTarget( iType, NULL ); m_pDragItem->AddTarget( CDragItem::TARGET_ALL, pCmd ); pt.x = 169; pt.y = 99; m_MaterialItemSlot.SetOffset( pt ); m_MaterialItemSlot.SetParent( iType ); m_MaterialItemSlot.SetDragAvailable(); m_MaterialItemSlot.SetDragItem( m_pDragItem ); SetDialogType( iType ); } CSeparateDlg::~CSeparateDlg(void) { SAFE_DELETE( m_pDragItem ); } void CSeparateDlg::Update( CObservable* pObservable, CTObject* pObj ) { assert( pObservable ); assert( pObj && strcmp( pObj->toString() ,"Separate" ) == 0 ); if( pObj == NULL || strcmp( pObj->toString() ,"Separate" ) ) return; CTEventSeparate* pEvent = (CTEventSeparate*)pObj; switch( pEvent->GetID() ) { case CTEventSeparate::EID_REMOVE_MATERIAL_ITEM: m_MaterialItemSlot.DetachIcon(); break; case CTEventSeparate::EID_SET_MATERIAL_ITEM: { CItem* pItem = pEvent->GetItem(); assert( pItem ); if( pItem ) m_MaterialItemSlot.AttachIcon( pItem->CreateItemIcon() ); break; } case CTEventSeparate::EID_REMOVE_OUTPUT_ITEM: { int iIndex = pEvent->GetIndex(); assert( iIndex >= 0 && iIndex < (int)m_OutputItemSlots.size() ); if( iIndex >= 0 && iIndex < (int)m_OutputItemSlots.size() ) m_OutputItemSlots[iIndex].DetachIcon(); break; } case CTEventSeparate::EID_SET_OUTPUT_ITEM: { int iIndex = pEvent->GetIndex(); assert( iIndex >= 0 && iIndex < (int)m_OutputItemSlots.size() ); if( iIndex >= 0 && iIndex < (int)m_OutputItemSlots.size() ) { CItem* pItem = pEvent->GetItem(); assert( pItem && m_OutputItemSlots[iIndex].GetIcon() == NULL ); if( pItem && m_OutputItemSlots[iIndex].GetIcon() == NULL ) m_OutputItemSlots[iIndex].AttachIcon( pItem->CreateItemIcon() ); } break; } default: assert( 0 && "Invalid Separate Event Type" ); break; } } unsigned CSeparateDlg::Process( unsigned uiMsg, WPARAM wParam, LPARAM lParam ) { if( !IsVision() ) return 0; if( unsigned uiProcID = CTDialog::Process( uiMsg, wParam, lParam ) ) { if( m_MaterialItemSlot.Process( uiMsg, wParam , lParam ) ) return uiMsg; if( uiMsg == WM_LBUTTONUP ) { switch( uiProcID ) { case IID_BTN_START: { CSeparate& Separate = CSeparate::GetInstance(); CIcon* pIcon = m_MaterialItemSlot.GetIcon(); if( pIcon == NULL )///์žฌ๋ฃŒ๊ฐ€ ์—†๋‹ค๋ฉด Disable { g_itMGR.OpenMsgBox(STR_SEPARATE_EMPTY_TARGETITEM); break; } int iCount = 0; std::vector< CSlot >::iterator iterOutput; for( iterOutput = m_OutputItemSlots.begin(); iterOutput != m_OutputItemSlots.end(); ++iterOutput ) { if( iterOutput->GetIcon() ) ++iCount; } if( iCount <= 0 ) { g_itMGR.OpenMsgBox( STR_CANT_SEPARATE ); break; } switch( Separate.GetType() ) { case CSeparate::TYPE_SKILL: { if( Separate.GetRequireMp() > g_pAVATAR->Get_MP() ) { g_itMGR.OpenMsgBox(STR_NOT_ENOUGH_MANA); return uiMsg; } break; } case CSeparate::TYPE_NPC: { if( Separate.GetRequireMoney() > g_pAVATAR->Get_MONEY() ) { g_itMGR.OpenMsgBox(STR_NOT_ENOUGH_MONEY); return uiMsg; } break; } default: break; } CIconItem* pItem = (CIconItem*)pIcon; if( !HasEnoughInventoryEmptySlot( pItem,m_OutputItemSlots ) ) { g_itMGR.OpenMsgBox(STR_NOTENOUGH_EMPTY_INVENTORYSLOT); break; } CSeparate::GetInstance().Send_CRAFT_BREAKUP_REQ(); break; } case IID_BTN_CLOSE: { Hide(); CSeparate::GetInstance().RemoveItem(); break; } default: break; } } return uiMsg; } return 0; } void CSeparateDlg::Update( POINT ptMouse ) { if( !IsVision() ) return; CTDialog::Update( ptMouse ); m_MaterialItemSlot.Update( ptMouse ); std::vector< CSlot >::iterator iter; for( iter = m_OutputItemSlots.begin(); iter != m_OutputItemSlots.end(); ++iter ) iter->Update( ptMouse ); if( CSeparate::GetInstance().GetType() == CSeparate::TYPE_NPC ) { WORD wNpcSvrIdx = CSeparate::GetInstance().GetNpcSvrIdx(); CObjCHAR* pNpc = g_pObjMGR->Get_ClientCharOBJ( wNpcSvrIdx, false ); if( !( pNpc && g_pAVATAR->IsInRANGE( pNpc, AVT_CLICK_EVENT_RANGE )) ) { Hide(); CSeparate::GetInstance().RemoveItem(); } } } void CSeparateDlg::Show() { if( IsVision() ) return; CTDialog::Show(); switch( CSeparate::GetInstance().GetType() ) { case CSeparate::TYPE_SKILL: HideChild( IID_TEXT_COST ); break; default: break; } } //*-------------------------------------------------------------------/ /// ๋ถ„๋ฆฌ/๋ถ„ํ•ดํ›„ ์•„์ดํ…œ์ด ๋“ค์–ด๊ฐˆ ์ž๋ฆฌ๊ฐ€ ์ถฉ๋ถ„ํžˆ ์žˆ๋Š”๊ฐ€? //*-------------------------------------------------------------------/ bool CSeparateDlg::HasEnoughInventoryEmptySlot( CIconItem* pItemIcon, std::vector<CSlot>& OutputItems ) { assert( pItemIcon ); if( pItemIcon == NULL ) return false; ///์ผ๋‹จ ๋ชจ๋“  ํƒ€์ž…์˜ ๋นˆ ์Šฌ๋กฏ์„ ๊ตฌํ•œ๋‹ค. short nEmptySlotCount[ MAX_INV_TYPE ]; CInventory* pInven = g_pAVATAR->GetInventory(); assert( pInven ); for( int i = INV_WEAPON; i < MAX_INV_TYPE; ++i ) nEmptySlotCount[i] = pInven->GetEmptyInvenSlotCount( (t_InvTYPE)i ); /// ๋ถ„๋ฆฌ/๋ถ„ํ•ดํ•  ์•„์ดํ…œ์˜ ์ž๋ฆฌ๋ฅผ ๋นˆ์Šฌ๋กฏ์œผ๋กœ ๊ณ„์‚ฐํ•œ๋‹ค( ๊ฐœ์ˆ˜๊ฐ€ ์—†๊ฑฐ๋‚˜ ๊ฐœ์ˆ˜๊ฐ€ ์žˆ์ง€๋งŒ 1๊ฐœ์ผ๊ฒฝ์šฐ) tagITEM& Item = pItemIcon->GetItem(); if( (Item.IsEnableDupCNT() && Item.GetQuantity() == 1 ) || !Item.IsEnableDupCNT() ) nEmptySlotCount[ CInventory::GetInvPageTYPE( Item ) ]++; CIcon* pIcon = NULL; CIconItem* pOutputItemIcon = NULL; std::vector<CSlot>::iterator iter; for( iter = OutputItems.begin(); iter != OutputItems.end(); ++iter ) { if( pIcon = iter->GetIcon() ) { pOutputItemIcon = ( CIconItem* )pIcon; nEmptySlotCount[ CInventory::GetInvPageTYPE( pOutputItemIcon->GetItem() ) ]--; if( nEmptySlotCount[ CInventory::GetInvPageTYPE( pOutputItemIcon->GetItem() ) ] <= 0 ) return false; } } return true; } void CSeparateDlg::Draw() { if( !IsVision() ) return; CTDialog::Draw(); m_MaterialItemSlot.Draw(); CIcon* pIcon = NULL; RECT rcDraw; if( pIcon = m_MaterialItemSlot.GetIcon() ) { SetRect( &rcDraw, -130, 21, -17, 39 ); drawFont( g_GameDATA.m_hFONT[ FONT_NORMAL ], true, &rcDraw ,g_dwWHITE,DT_CENTER | DT_VCENTER, pIcon->GetName() ); ///ํ•„์š” MP or ์ค„๋ฆฌ D3DXMATRIX mat; D3DXMatrixTranslation( &mat, (float)m_sPosition.x, (float)m_sPosition.y,0.0f); ::setTransformSprite( mat ); SetRect( &rcDraw, 176,379,176+34,379+15 ); CSeparate& Separate = CSeparate::GetInstance(); switch( Separate.GetType() ) { case CSeparate::TYPE_SKILL: drawFontf( g_GameDATA.m_hFONT[ FONT_NORMAL ], true, &rcDraw ,g_dwWHITE,DT_RIGHT,"%d", Separate.GetRequireMp() ); break; case CSeparate::TYPE_NPC: drawFontf( g_GameDATA.m_hFONT[ FONT_NORMAL ], true, &rcDraw ,g_dwWHITE,DT_RIGHT,"%d", Separate.GetRequireMoney() ); break; default: break; } } SetRect( &rcDraw, -140, 15, -55, 33 ); std::vector< CSlot >::iterator iter; for( iter = m_OutputItemSlots.begin(); iter != m_OutputItemSlots.end(); ++iter ) { iter->Draw(); if( pIcon = iter->GetIcon() ) drawFont( g_GameDATA.m_hFONT[ FONT_NORMAL ], true, &rcDraw ,g_dwWHITE,DT_CENTER | DT_VCENTER , pIcon->GetName() ); } } void CSeparateDlg::MoveWindow( POINT pt ) { CTDialog::MoveWindow( pt ); m_MaterialItemSlot.MoveWindow( m_sPosition ); std::vector< CSlot >::iterator iter; for( iter = m_OutputItemSlots.begin(); iter != m_OutputItemSlots.end(); ++iter ) iter->MoveWindow( m_sPosition ); }
e83ed006915605e3ead6673f85fd778d8490e5f4
a8ed4ea435be7b035c6d086208559221863811ba
/src/Main.cpp
a568ef6d786310a0fe903b8d73db0c3987f5157b
[]
no_license
Tequilac/SpaceInvaders
8e34027d0ae2fd32a1764035f0a44f5b38556970
ab962d5bb9ae2943d64000f795e7a368c566227f
refs/heads/master
2023-02-09T00:21:07.580848
2020-12-31T12:34:42
2020-12-31T12:34:42
325,796,526
0
0
null
null
null
null
UTF-8
C++
false
false
2,773
cpp
Main.cpp
#include <iostream> #include <vector> #include <memory> #include <SFML/Graphics.hpp> #include "Object.h" #include "Laser.h" #include "Player.h" int main() { sf::Texture playerTexture; playerTexture.loadFromFile("res/enemy.png"); sf::Sprite playerSprite; playerSprite.setTexture(playerTexture); Player player(sf::Vector2f(200.0f, 500.0f), playerSprite); std::vector<Entity> entities; entities.reserve(60); sf::Texture enemyTexture; enemyTexture.loadFromFile("res/enemy.png"); sf::Sprite enemySprite; enemySprite.setTexture(enemyTexture); for (int i = 0; i < 5; ++i) for (int j = 0; j < 12; ++j) entities.emplace_back(Entity(sf::Vector2f(40*j, 30 + 40*i), enemySprite)); //330 std::vector<Laser> lasers; sf::Texture laserTexture; laserTexture.loadFromFile("res/enemy.png"); sf::Sprite laserSprite; laserSprite.setTexture(laserTexture); sf::RenderWindow window(sf::VideoMode(800, 600), "SFML works!"); MoveDirection currentDirection = MoveDirection::Right; sf::Clock clock; float timeStep; float lastFrameTime = 0.0f; int count = 0; int lastShot = 60; clock.restart(); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } player.handleInput(lasers, laserSprite, lastShot); for(auto& entity : entities) entity.onUpdate(currentDirection); for(auto& laser : lasers) laser.onUpdate(); auto i = std::begin(lasers); while (i != std::end(lasers)) { int collided = i->collides(entities); if (collided != -1) { if(collided != -2) entities.erase(entities.begin() + collided); i = lasers.erase(i); } else ++i; } window.clear(); window.draw(player.getSprite()); for(auto& entity : entities) window.draw(entity.getSprite()); for(auto& laser : lasers) window.draw(laser.getSprite()); window.display(); float time = clock.getElapsedTime().asSeconds(); timeStep = time - lastFrameTime; lastFrameTime = time; std::cout << timeStep << "\n"; if (timeStep < 1.0f / 60.0f) sf::sleep(sf::seconds(1.0f / 60.0f - timeStep )); count++; if(count == 1650) { count = 0; currentDirection = ((currentDirection == MoveDirection::Right)? MoveDirection::Left : MoveDirection::Right); } lastShot--; } return 0; }
897b51af11f923254c6506026f0cbede488d4ae2
fa1563c5a3fd3e800a3e586fcc2db920ea34a8ab
/permut2.cpp
e65b0b6abc5aec983fe4d37bafbba215d85c328a
[]
no_license
pratz1997/SPOJ
2d1ea5d3bc013772d8f65072c5ba7f75e19c5256
f2a81e7eca1dcdd90691ef04b1ff69e6cf99731e
refs/heads/master
2021-08-30T11:18:56.573808
2017-12-17T17:41:21
2017-12-17T17:41:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
470
cpp
permut2.cpp
#include<iostream> #include<vector> using namespace std; int main() { while(1) { int n; cin>>n; if(!n) break; else { unsigned int f=0,k,i; vector<unsigned int> v; while(n--) { cin>>k; v.push_back(k); } vector <unsigned int>::iterator it; for(i=1,it=v.begin();it!=v.end();i++,it++) if(v[*it-1]!=i) { f++; break; } if(f) cout<<"not ambiguous"<<endl; else cout<<"ambiguous"<<endl; } } return 0; }
d581ba8496e40b3c7d08e22976a930540060c172
9dc21dc52cba61932aafb5d422ed825aafce9e22
/src/appleseed/foundation/utility/api/specializedapiarrays.cpp
306c41381eaba8d77c602255d337fa871fd67e47
[ "MIT" ]
permissive
MarcelRaschke/appleseed
c8613a0e0c268d77e83367fef2d5f22f68568480
802dbf67bdf3a53c983bbb638e7f08a2c90323db
refs/heads/master
2023-07-19T05:48:06.415165
2020-01-18T15:28:31
2020-01-19T11:52:15
236,110,136
2
0
MIT
2023-04-03T23:00:15
2020-01-25T01:12:57
null
UTF-8
C++
false
false
3,024
cpp
specializedapiarrays.cpp
// // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "specializedapiarrays.h" // Standard headers. #include <cassert> #include <string> #include <vector> namespace foundation { APPLESEED_DEFINE_APIARRAY(FloatArray); APPLESEED_DEFINE_APIARRAY(DoubleArray); APPLESEED_DEFINE_APIARRAY(DictionaryArray); // // StringArray class implementation. // struct StringArray::Impl : public std::vector<std::string> { }; StringArray::StringArray() : impl(new Impl()) { } StringArray::StringArray(const StringArray& rhs) : impl(new Impl(*rhs.impl)) { } StringArray::StringArray( const size_type size, const value_type* values) : impl(new Impl()) { assert(size > 0); assert(values); impl->resize(size); for (size_t i = 0; i < size; ++i) (*impl)[i] = values[i]; } StringArray::~StringArray() { delete impl; } StringArray& StringArray::operator=(const StringArray& rhs) { *impl = *rhs.impl; return *this; } StringArray::size_type StringArray::size() const { return impl->size(); } bool StringArray::empty() const { return impl->empty(); } void StringArray::clear() { impl->clear(); } void StringArray::reserve(const size_type count) { impl->reserve(count); } void StringArray::resize(const size_type new_size) { impl->resize(new_size); } void StringArray::push_back(const value_type val) { impl->push_back(val); } void StringArray::set(const size_type pos, const value_type val) { assert(val); (*impl)[pos] = val; } StringArray::value_type StringArray::operator[](const size_type pos) const { return (*impl)[pos].c_str(); } } // namespace foundation
97b5b4993692b0e2755ce752ea23d657f5591b88
6e69ef80d5743105c192df5867110ab2fbc197f6
/src/actions/single_action/single_action_class.h
df96776a8d086f0744d35e6f93904fd2c94ea5c5
[]
no_license
domischi/simpimc
b632b1af87184cda3873b280edad5bfca6de74c5
5c062959be49ec6e5a67a12b1b7a0605531ff72f
refs/heads/master
2021-01-16T19:47:18.081454
2015-09-02T13:46:45
2015-09-02T13:46:45
42,102,631
0
0
null
2015-09-08T09:24:30
2015-09-08T09:24:30
null
UTF-8
C++
false
false
1,190
h
single_action_class.h
#ifndef SIMPIMC_ACTIONS_SINGLE_ACTION_CLASS_H_ #define SIMPIMC_ACTIONS_SINGLE_ACTION_CLASS_H_ #include "../action_class.h" /// Action class for actions affecting only a single species of particles class SingleAction : public Action { protected: double i_4_lambda_tau; ///< 1/(4\lambda\tau) double lambda; ///< h_bar^2/2m uint32_t n_part; ///< Number of particles in the species affected by the action uint32_t species_i; ///< Index of species affected by the action std::string species; ///< Name of species affected by the action public: /// Constructor only instatiates parent Action class SingleAction(Path &path, Input &in, IO &out) : Action(path,in,out) { // Set species variables species = in.GetAttribute<std::string>("species"); out.Write("Actions/"+name+"/species", species); species_list.push_back(species); path.GetSpeciesInfo(species,species_i); n_part = path.species_list[species_i]->n_part; lambda = path.species_list[species_i]->lambda; i_4_lambda_tau = 1./(4.*lambda*path.tau); std::cout << "Setting up " << name << " for " << species << "..." << std::endl; } }; #endif // SIMPIMC_ACTIONS_SINGLE_ACTION_CLASS_H_
6b7fa6ddea6fb75892b9e56b16c9b7a772c1a945
e1b83db0ce6f8c9c840bfb36a8357469ba1a97c7
/ocam_calibration.h
69f58044d355b85fc83bbb6c55e11d0dbe4a4132
[]
no_license
siposcsaba89/ocam-calib-cpp
b09082e0b081afa3d3c159c8ae72db891374ab0a
056cd13b592cea293de77455bb0ba710c97bb3f6
refs/heads/master
2023-02-20T19:35:26.990515
2023-02-08T15:22:05
2023-02-08T15:22:05
62,483,078
29
16
null
null
null
null
UTF-8
C++
false
false
457
h
ocam_calibration.h
#pragma once #include <vector> #include <opencv2/opencv.hpp> struct OcamCalibRes { std::vector<double> ss; std::vector<double> ss_inv; double center_x; double center_y; std::vector<std::vector<double>> R; std::vector<std::vector<double>> T; }; double calibrateCameraOcam2(const std::vector<std::vector<cv::Point3f> > & objectPoints, const std::vector<std::vector<cv::Point2f> > & imagePoints, const cv::Size & imageSize, OcamCalibRes & res);
74acd4649ddc5d65f782a7a58ae8ae70c1c6252c
0c9cae0ec0f276b6f727cab8b0829b831dd0b7fb
/RotateImage/RotateImage/RotateImage.cpp
3c39aee9adf97dcbfd50124755b6090b8d5986ec
[]
no_license
timruning/leecode
e7b97bd52cf2e064b3873d980c81d040043090a6
899643daeb40a8f6b4ebe975f3c76ff1865f7959
refs/heads/master
2021-01-19T02:55:42.357388
2016-07-26T14:02:13
2016-07-26T14:02:13
45,767,185
0
0
null
null
null
null
GB18030
C++
false
false
379
cpp
RotateImage.cpp
// RotateImage.cpp : ๅฎšไน‰ๆŽงๅˆถๅฐๅบ”็”จ็จ‹ๅบ็š„ๅ…ฅๅฃ็‚นใ€‚'; // #include "stdafx.h" #include<vector> #include<iostream> using namespace std; class Solution { public: void rotate(vector<vector<int>>& matrix) { for (int i = 0; i < matrix.size(); i++){ for (int j = 0; j < matrix[0].size(); j++){ } } } }; int _tmain(int argc, _TCHAR* argv[]) { return 0; }
185d632cd39f832cb11c782e9904d00e10069981
8d5c4edf79d4127186ea085244401339f6db1f19
/hospitalv5.cpp
7ebd77a868d4b3e2a639cc6b9259b49cddcee362
[]
no_license
Seemanthini/Hospital_Mgmt
289c7f0b4debc575ad6551594df76783e68e6b7e
29a4f26e2ab24fdd4278ddda498dc3d57a60524d
refs/heads/master
2016-08-12T13:05:02.369761
2015-06-06T20:43:31
2015-06-06T20:43:31
36,993,700
1
2
null
null
null
null
UTF-8
C++
false
false
12,529
cpp
hospitalv5.cpp
#include<iostream> #include<new> #include<cstdlib> #include<cstring> #define MAXPATIENTS 200 #define MAXROOMS 200 using namespace std; int deluxe=0,semi=0,normal=0; int numOfPatients=0,numOfRooms=0; // the structure containing the node... info and a link *next to point to the next node struct nod{ string name; string dob; string bloodgroup; string doc; string sex; string wardt; long long int contact; int age,ward; struct nod *next; }; typedef struct nod node; class hospital{ //the hospital class(list class) node *f; //node that points to null public: hospital(){f=NULL;} //initialize f to null in constructor //function to admit the patien void PatientAdmit(char *n,int a,char *db,char *b,char *s,long long int c,int w,char *wrd,char *d){ node *h=new node; //allocate memory for new node {h->name=n; h->age=a; h->dob=db; h->bloodgroup=b; h->sex=s; h->contact=c; h->ward=w; h->wardt=wrd; h->doc=d;} h->next=f; //after assigning info.. point to next node (null) f=h; } //Function to Discharge Desired patient int PatientDischarge(int num){ node *temp, *prev; temp=f; if(f==NULL) cout<<"List Is Empty\n"; while(temp!=NULL) { if(temp->ward==num) { if(temp==f) { { /*cout<<"\n\nThe Patient with the following Details has been discharged Succesfully:\n"; cout<<"Name: "<<f->name<<"\n"; cout<<"Date Of Birth: "<<f->dob<<"\n"; cout<<"Blood Group: "<<f->bloodgroup<<"\n"; cout<<"Sex: "<<f->sex<<"\n"; cout<<"Age: "<<f->age<<"\n"; cout<<"Contact Number: "<<f->contact<<"\n"; cout<<"Ward Type: "<<f->wardt<<"\n"; cout<<"Ward Number: "<<f->ward<<"\n";} cout<<"Doctor assigned: "<<f->doc<<"\n";*/ f=temp->next; free(temp); return 1; } } else { prev->next=temp->next; free(temp); return 1; } } else { prev=temp; temp= temp->next; } } cout<<"Patient Does Not Exist \n"; return 0; } //function to display the list of admitted patients void display(){ int i=1; node *temp=f; if(f==NULL) cout<<"List Is Empty\n"; else{ cout<<"The Patients in the list are:\n"; while(temp!=NULL){ { cout<<"Details of Patient:"<<i<<"\n"; cout<<"Name:"<<temp->name<<"\n"; cout<<"Date Of Birth:"<<temp->dob<<"\n"; cout<<"Blood Group:"<<temp->bloodgroup<<"\n"; cout<<"Sex:"<<temp->sex<<"\n"; cout<<"Age:"<<temp->age<<"\n"; cout<<"Contact Number:"<<temp->contact<<"\n"; cout<<"Ward Type:"<<temp->wardt<<"\n"; cout<<"Ward Number: "<<temp->ward<<"\n"; cout<<"Doctor: "<<temp->doc<<"\n"; cout<<"\n\n";} temp=temp->next; i++; } } } //seperate function to check if list is empty or not.. to be called in main int list_empty() { if(f==NULL) { return 0; } else { return 1; } } }; // LINKED LIST 2 TO PERFORM LINEAR SEARCH TO PREVENT ADDITION OF SAME WARD NUMBER struct nod2{ int wardno; struct nod2 *next; }; typedef struct nod2 w_node; class list:public nod2{ w_node *f; public: list(){f=NULL;} //insert ward number void ins(int num){ w_node *p=new w_node; p->wardno=num; p->next=f; f=p; } //delete ward number int del(int num){ w_node *temp, *prev; temp=f; if(f==NULL) cout<<"List Is Empty\n"; while(temp!=NULL) { if(temp->wardno==num) { if(temp==f) { f=temp->next; free(temp); return 1; } else { prev->next=temp->next; free(temp); return 1; } } else { prev=temp; temp= temp->next; } } cout<<"Patient Does Not Exist \n"; return 0; } //checking if ward exists or not using linear search int checkWard(int item) { int loc=0,i; i=0; w_node *ptr=f; while(ptr!=NULL) { if((ptr->wardno)==item) { return 0; break; } ptr=ptr->next; i++; } return 1; } //for developers use only void display_ward(){ w_node *temp=f; if(f==NULL) cout<<"Empty\n"; else{ cout<<"The Occupied Ward Numbers are:\n"; while(temp!=NULL){ cout<<" "<<temp->wardno; temp=temp->next; } } } //function to check if list is empty or not int list_empty() { if(f==NULL) { cout<<"\nLinked List is empty"; return 0; } else { return 1; } } }; //beginning of main program int main(){ char nme[20],db[10],bg[5],da[20],sx[20]; char ward[20]; long long int cn; int ag,l,wrd,suc,suc1,ch2,item,loc,ch1; int choice,patientCount=MAXPATIENTS,roomCount=MAXROOMS; hospital ob; list wd; cout<<".......................HOSPITAL MANAGEMENT MENU........................\n\n"; while(patientCount!=0){ cout<<"1.Patient Admission 2.Patient Discharge 3.Display 4.Exit\n\n"; cout<<"Enter your choice: "; cin>>choice; cout<<"\n"; switch(choice){ case 1: //accept info of patients.. no need of getdetails() cout<<"ENTER THE DETAILS OF PATIENT BELOW\n"; cout<<"\nEnter name of patient:"; cin>>nme; cout<<"\nEnter the age of person:"; cin>>ag; cout<<"\nEnter the Date Of Birth:"; cin>>db; cout<<"\nEnter the Blood Group:"; cin>>bg; cout<<"\nSex:"; cin>>sx; cout<<"\nEnter the contact number:"; cin>>cn; cout<<"Enter Type Of Ward Patient Requires:1.Normal 2.Semi 3.Deluxe\n"; cin>>ch1; switch(ch1){ case 1:strcpy(ward,"Normal"); break; case 2:strcpy(ward,"Semi"); break; case 3:strcpy(ward,"Deluxe"); break; default:cout<<"wrong choice entered\n"; } label: cout<<"\nEnter the Ward Number For The Patient:"; cin>>wrd; if((wrd<=0)||(wrd>MAXROOMS)){ cout<<"Enter a valid ward number\n"; goto label; } loc=wd.checkWard(wrd); if(loc==1) { cout<<" Room allocated Succesfully\n"; wd.ins(wrd); } else{ cout<<"Ward already Allocated, Please Enter a different ward\n"; goto label; } --roomCount; cout<<"Total Number Of rooms available:"<<roomCount<<"\n"; cout<<"\nDoctor Assigned:"; cin>>da; cout<<"Admission Succesfull \n"; //pass above info as parameters to admit function ob.PatientAdmit(nme,ag,db,bg,sx,cn,wrd,ward,da); patientCount--;//decrement count when patient admitted cout<<"vacancy left: "<<patientCount<<" Patients \n"; //Display Vacancy break; case 2: if(ob.list_empty()==0) cout<<"List Empty\n"; else{ cout<<"Enter Ward Number of person to be discharged\n"; cin>>l; suc=ob.PatientDischarge(l); if(suc==1){ if(patientCount<MAXPATIENTS) patientCount++; cout<<"vacancy left: "<<patientCount<<" Patients \n"; if(roomCount<MAXROOMS) roomCount++; cout<<"Room Vacany left: "<<roomCount<<" Rooms\n"; } else{ cout<<"Invalid entry\n"; } } break; case 3: ob.display(); break; case 4:exit(0); //easiest part of program break; default: cout<<"Invalid Choice Entered... Please Try Again\n"; } } return 0; }
b39a6708ae562034971ce8e85c9f13e0796f4049
b6d1df49c1ec621a02204b1100312ecbb3e76ad3
/src/video/photoannotationdbfuncs.cc
572db6d252eecd880d268469499cecba16055fac
[]
no_license
flylong0204/projects
5271acde325cf3947fac7433077353b52fa07bc4
b1e5c918d4aeb34c36576dababc5509dbb89afd1
refs/heads/master
2017-12-06T06:35:20.926786
2017-01-24T23:53:13
2017-01-24T23:53:13
79,988,197
1
2
null
2017-01-25T06:11:23
2017-01-25T06:11:23
null
UTF-8
C++
false
false
16,511
cc
photoannotationdbfuncs.cc
// ========================================================================== // Photoannotationdbfunc namespace method definitions // ========================================================================== // Last modified on 1/18/11 // ========================================================================== #include <iostream> #include "astro_geo/Clock.h" #include "postgres/gis_database.h" #include "video/photoannotationdbfuncs.h" #include "general/stringfuncs.h" #include "math/twovector.h" using std::cout; using std::endl; using std::string; using std::vector; namespace photoannotationdbfunc { // ========================================================================== // Manipulation methods for photo annotations table in TOC database // ========================================================================== bool insert_photo_annotation( gis_database* gis_database_ptr,int fieldtest_ID,int photo_ID, double secs_since_epoch,string username,string label, string description,string color,int importance,double U,double V) { string curr_insert_command= photoannotationdbfunc::generate_insert_photo_annotation_SQL_command( fieldtest_ID,photo_ID,secs_since_epoch, username,label,description,color,importance,U,V); vector<string> insert_commands; insert_commands.push_back(curr_insert_command); // cout << "insert_commands.back() = " << insert_commands.back() << endl; // cout << "gis_database_ptr = " << gis_database_ptr << endl; gis_database_ptr->set_SQL_commands(insert_commands); return gis_database_ptr->execute_SQL_commands(); } // --------------------------------------------------------------------- // Method generate_insert_photo_annotation_SQL_command() takes in // metadata associated with a single photo annotation. It generates // and returns a string containing a SQL insert command needed to // populate a row within the photo_annotations table of the // TOC database. string generate_insert_photo_annotation_SQL_command( int fieldtest_ID,int photo_ID,double secs_since_epoch, string username,string label,string description,string color, int importance,double U,double V) { // cout << "inside photoannotationdbfunc::generate_insert_photo_annotation_SQL_command()" << endl; Clock clock; clock.convert_elapsed_secs_to_date(secs_since_epoch); string date_str=clock.YYYY_MM_DD_H_M_S(); string SQL_command="insert into photo_annotations "; SQL_command += "(fieldtest_ID,photo_ID,creation_time,"; SQL_command += "username,label,description,color,"; SQL_command += "importance,uv_posn) "; SQL_command += "values( "; SQL_command += stringfunc::number_to_string(fieldtest_ID)+","; SQL_command += stringfunc::number_to_string(photo_ID)+","; SQL_command += "'"+date_str+"',"; SQL_command += "'"+username+"',"; SQL_command += "'"+label+"',"; SQL_command += "'"+description+"',"; SQL_command += "'"+color+"',"; SQL_command += stringfunc::number_to_string(importance)+","; SQL_command += "'SRID=4326; POINT(" +stringfunc::number_to_string(U,9) +" "+stringfunc::number_to_string(V,9)+")'"; SQL_command += ");"; cout << SQL_command << endl; return SQL_command; } // --------------------------------------------------------------------- // Method get_photo_annotation_ID() takes in username, label and // description fields. It returns the integer ID automatically // generated by the photo_annotations table within the TOC database at // the time the photo annotation was inserted. If no photo annotation // matching the input parameters is found, this method returns -1. int get_photo_annotation_ID( gis_database* gis_database_ptr, string username,string label,string description) { // cout << "inside photoannotationdbfunc::get_photo_annotation_ID()" << endl; // cout << "username = " << username // << " label = " << label // << " description = " << description << endl; string SQL_command="select id from photo_annotations "; SQL_command += "WHERE username='"+username+"' "; SQL_command += "AND label='"+label+"' "; SQL_command += "AND description='"+description+"';"; // cout << "SQL_command = " << SQL_command << endl; Genarray<string>* field_array_ptr= gis_database_ptr->select_data(SQL_command); if (field_array_ptr==NULL) return -1; // cout << "*field_array_ptr = " << *field_array_ptr << endl; int annotation_ID=stringfunc::string_to_number( field_array_ptr->get(0,0)); // cout << "annotation_ID = " << annotation_ID << endl; return annotation_ID; } // --------------------------------------------------------------------- // Method get_particular_photo_annotations() queries the // photo_annotations table within the TOC database for all annotations // associated with a particular photo ID. void get_particular_photo_annotations( gis_database* gis_database_ptr,int photo_ID, vector<int>& annotation_IDs,vector<string>& creation_times, vector<string>& usernames,vector<string>& labels, vector<string>& descriptions,vector<string>& colors, vector<int>& importances,vector<twovector>& UVs) { // cout << "inside photoannotationdbfunc::get_particular_photo_annotation()" << endl; // cout << "photo_ID = " << photo_ID << endl; string SQL_command="SELECT id,creation_time,username,"; SQL_command += "label,description,color,importance,"; SQL_command += "x(uv_posn),y(uv_posn) from photo_annotations "; SQL_command += "WHERE photo_ID="+stringfunc::number_to_string( photo_ID)+";"; // cout << "SQL_command = " << SQL_command << endl; Genarray<string>* field_array_ptr= gis_database_ptr->select_data(SQL_command); if (field_array_ptr==NULL) return; unsigned int mdim=field_array_ptr->get_mdim(); // unsigned int ndim=field_array_ptr->get_ndim(); // cout << "mdim = " << mdim << " ndim = " << ndim << endl; for (unsigned int i=0; i<mdim; i++) { annotation_IDs.push_back(stringfunc::string_to_number( field_array_ptr->get(i,0))); creation_times.push_back(field_array_ptr->get(i,1)); usernames.push_back(field_array_ptr->get(i,2)); labels.push_back(field_array_ptr->get(i,3)); descriptions.push_back(field_array_ptr->get(i,4)); colors.push_back(field_array_ptr->get(i,5)); importances.push_back(stringfunc::string_to_number( field_array_ptr->get(i,6))); double U=stringfunc::string_to_number( field_array_ptr->get(i,7)); double V=stringfunc::string_to_number( field_array_ptr->get(i,8)); UVs.push_back(twovector(U,V)); cout << "annotation_ID = " << annotation_IDs.back() << endl; cout << "creation_time = " << creation_times.back() << endl; cout << "username = " << usernames.back() << endl; cout << "label = " << labels.back() << endl; cout << "description = " << descriptions.back() << endl; cout << "color = " << colors.back() << endl; cout << "importance = " << importances.back() << endl; cout << "U = " << U << " V = " << V << endl; } // loop over index i labeling world annotations } // --------------------------------------------------------------------- // Method get_all_photo_annotations() void get_all_photo_annotations( gis_database* gis_database_ptr,int fieldtest_ID, vector<int>& annotation_IDs,vector<string>& creation_times, vector<string>& usernames,vector<string>& labels, vector<string>& descriptions,vector<string>& colors, vector<int>& importances,vector<twovector>& UVs) { // cout << "inside photoannotationdbfunc::get_all_photo_annotations()" << endl; // cout << "fieldtest_ID = " << fieldtest_ID << endl; string SQL_command="SELECT id,creation_time,username,"; SQL_command += "label,description,color,importance,"; SQL_command += "x(uv_posn),y(uv_posn) from photo_annotations "; SQL_command += "WHERE fieldtest_ID="+stringfunc::number_to_string( fieldtest_ID)+";"; // cout << "SQL_command = " << SQL_command << endl; Genarray<string>* field_array_ptr= gis_database_ptr->select_data(SQL_command); if (field_array_ptr==NULL) return; unsigned int mdim=field_array_ptr->get_mdim(); // unsigned int ndim=field_array_ptr->get_ndim(); // cout << "mdim = " << mdim << " ndim = " << ndim << endl; for (unsigned int i=0; i<mdim; i++) { annotation_IDs.push_back(stringfunc::string_to_number( field_array_ptr->get(i,0))); creation_times.push_back(field_array_ptr->get(i,1)); usernames.push_back(field_array_ptr->get(i,2)); labels.push_back(field_array_ptr->get(i,3)); descriptions.push_back(field_array_ptr->get(i,4)); colors.push_back(field_array_ptr->get(i,5)); importances.push_back(stringfunc::string_to_number( field_array_ptr->get(i,6))); double U=stringfunc::string_to_number( field_array_ptr->get(i,7)); double V=stringfunc::string_to_number( field_array_ptr->get(i,8)); UVs.push_back(twovector(U,V)); cout << "annotation_ID = " << annotation_IDs.back() << endl; cout << "creation_time = " << creation_times.back() << endl; cout << "username = " << usernames.back() << endl; cout << "label = " << labels.back() << endl; cout << "description = " << descriptions.back() << endl; cout << "color = " << colors.back() << endl; cout << "importance = " << importances.back() << endl; cout << "U = " << U << " V = " << V << endl; } // loop over index i labeling world annotations } // --------------------------------------------------------------------- // Method get_fieldtest_photo_annotations() void get_fieldtest_photo_annotations( gis_database* gis_database_ptr,int fieldtest_ID, vector<int>& annotation_IDs,vector<int>& photo_IDs, vector<string>& photo_times, vector<string>& usernames,vector<string>& labels, vector<string>& descriptions,vector<string>& colors, vector<int>& importances,vector<twovector>& UVs) { // cout << "inside photoannotationdbfunc::get_fieldtest_photo_annotations()" << endl; // cout << "mission_ID = " << mission_ID << endl; string SQL_command="SELECT id,creation_time,username,"; SQL_command += "label,description,color,importance,"; SQL_command += "x(uv_posn),y(uv_posn),photo_id from photo_annotations "; SQL_command += "WHERE fieldtest_ID="+stringfunc::number_to_string( fieldtest_ID)+";"; // cout << "SQL_command = " << SQL_command << endl; Genarray<string>* field_array_ptr= gis_database_ptr->select_data(SQL_command); if (field_array_ptr==NULL) return; unsigned int mdim=field_array_ptr->get_mdim(); // unsigned int ndim=field_array_ptr->get_ndim(); // cout << "mdim = " << mdim << " ndim = " << ndim << endl; for (unsigned int i=0; i<mdim; i++) { annotation_IDs.push_back(stringfunc::string_to_number( field_array_ptr->get(i,0))); photo_times.push_back(field_array_ptr->get(i,1)); usernames.push_back(field_array_ptr->get(i,2)); labels.push_back(field_array_ptr->get(i,3)); descriptions.push_back(field_array_ptr->get(i,4)); colors.push_back(field_array_ptr->get(i,5)); importances.push_back(stringfunc::string_to_number( field_array_ptr->get(i,6))); double U=stringfunc::string_to_number( field_array_ptr->get(i,7)); double V=stringfunc::string_to_number( field_array_ptr->get(i,8)); UVs.push_back(twovector(U,V)); photo_IDs.push_back(stringfunc::string_to_number( field_array_ptr->get(i,9))); cout << "annotation_ID = " << annotation_IDs.back() << endl; cout << "photo_time = " << photo_times.back() << endl; cout << "username = " << usernames.back() << endl; cout << "label = " << labels.back() << endl; cout << "description = " << descriptions.back() << endl; cout << "color = " << colors.back() << endl; cout << "importance = " << importances.back() << endl; cout << "U = " << U << " V = " << V << endl; } // loop over index i labeling world annotations } // --------------------------------------------------------------------- // Method update_photo_annotation() takes in metadata for a single // annotation which is intended to be tied to a 2D photo point. It // update the appropriate entry within *gis_database_ptr. bool update_photo_annotation( gis_database* gis_database_ptr, int annotation_ID,double secs_since_epoch, string username,string label,string description,string color, int importance,double U,double V) { // cout << "inside photoannotationdbfunc::update_photo_annotations()" << endl; string curr_update_command= photoannotationdbfunc::generate_update_photo_annotation_SQL_command( annotation_ID,secs_since_epoch, username,label,description,color,importance,U,V); vector<string> update_commands; update_commands.push_back(curr_update_command); // cout << "update_commands.back() = " << update_commands.back() << endl; // cout << "gis_database_ptr = " << gis_database_ptr << endl; gis_database_ptr->set_SQL_commands(update_commands); return gis_database_ptr->execute_SQL_commands(); } // --------------------------------------------------------------------- // Method generate_update_photo_annotation_SQL_command() takes in // metadata associated with a single photo annotation. It generates // and returns a string containing a SQL update command needed to // alter a row within the photo_annotations table of the // TOC database. string generate_update_photo_annotation_SQL_command( int annotation_ID,double secs_since_epoch, string username,string label,string description,string color, int importance,double U,double V) { // cout << "inside photoannotationdbfunc::generate_update_photo_annotation_SQL_command()" << endl; Clock clock; clock.convert_elapsed_secs_to_date(secs_since_epoch); string date_str=clock.YYYY_MM_DD_H_M_S(); string SQL_command="UPDATE photo_annotations"; SQL_command += " SET creation_time='"+date_str+"',"; if (username.size() > 0) SQL_command += "username='"+username+"',"; if (label.size() > 0) SQL_command += "label='"+label+"',"; if (description.size() > 0) SQL_command += "description='"+description+"',"; if (color.size() > 0) SQL_command += "color='"+color+"',"; if (importance > 0) SQL_command += "importance="+stringfunc::number_to_string( importance)+","; SQL_command += "uv_posn=PointFromText('POINT(' || "; SQL_command += stringfunc::number_to_string(U,9)+" || ' ' || "; SQL_command += stringfunc::number_to_string(V,9)+" || ')',4326) "; SQL_command += " WHERE id = "+stringfunc::number_to_string( annotation_ID)+";"; cout << SQL_command << endl; return SQL_command; } // --------------------------------------------------------------------- // Method delete_photo_annotation() bool delete_photo_annotation( gis_database* gis_database_ptr,int annotation_ID) { // cout << "inside databasefunc::delete_photo_annotation()" << endl; string SQL_command="delete from photo_annotations where id="; SQL_command += stringfunc::number_to_string(annotation_ID)+";"; vector<string> delete_commands; delete_commands.push_back(SQL_command); // cout << "delete_commands.back() = " << delete_commands.back() << endl; // cout << "gis_database_ptr = " << gis_database_ptr << endl; gis_database_ptr->set_SQL_commands(delete_commands); return gis_database_ptr->execute_SQL_commands(); } } // photoannotationdbfunc namespace
1b7dd607dba11041737aa225319105b552e851ee
f3a9174535cd7e76d1c1e0f0fa1a3929751fb48d
/SDK/PVR_BP_KillCam_classes.hpp
159f9eab8381d714e1473e1bca81bac20a0dc421
[]
no_license
hinnie123/PavlovVRSDK
9fcdf97e7ed2ad6c5cb485af16652a4c83266a2b
503f8d9a6770046cc23f935f2df1f1dede4022a8
refs/heads/master
2020-03-31T05:30:40.125042
2020-01-28T20:16:11
2020-01-28T20:16:11
151,949,019
5
2
null
null
null
null
UTF-8
C++
false
false
636
hpp
PVR_BP_KillCam_classes.hpp
#pragma once // PavlovVR (Dumped by Hinnie) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_KillCam.BP_KillCam_C // 0x0000 (0x03D8 - 0x03D8) class ABP_KillCam_C : public AKillCam { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_KillCam.BP_KillCam_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
cbcae2ae4f6ffca8356da63ba3b344f40ad888c7
5109f1bdba55c119b1b754b0359a87a8af3f9dd5
/Source/FNX_LineShape.cpp
a652e4a61578864a0838db7d308dd656c988bdc2
[ "MIT" ]
permissive
krzysztofzablocki/Fenix_2003
2db8317a3866339a63ac313caaf8091a22d9401a
c0259a1ff3a0670a3c364671b37d2bc5c51e0114
refs/heads/master
2021-01-10T07:59:48.386893
2015-10-01T14:46:24
2015-10-01T14:46:24
43,500,734
0
1
null
null
null
null
UTF-8
C++
false
false
4,662
cpp
FNX_LineShape.cpp
#include "FNX_PhysInc.h" #include "FNX_BaseShape.h" #include "FNX_LineShape.h" #include "FNX_Actor.h" FNX_LineShape::FNX_LineShape(FNX_Actor *actor, const FNX_LineShapeDesc &desc) : FNX_BaseShape(actor, desc) { int Dir=1; if(desc.Start.y>desc.End.y)Dir=-1; FNX_Vector v1,v2; v1=FNX_Vector(Dir,0); v2=desc.End-desc.Start; v1.Normalize();v2.Normalize(); float dot=v1 | v2; Coords.T=desc.Start+(desc.End-desc.Start)/2.0f; Coords.R=FNX_Rotation(acosf(dot)); Extents.x=(desc.End-desc.Start).Length()/2.0f; Extents.y=desc.BrushSize; } bool FNX_LineShape::IsTouchingPoint(const FNX_Vector &point) { FNX_Coords inv_world = -GetWorldCoords(); FNX_Vector local = inv_world * point; if (local.x < -Extents.x || local.x > Extents.x) return false; if (local.y < -Extents.y || local.y > Extents.y) return false; return true; } inline FNX_Vector FNX_LineShape::GetSize(){ return Extents; } void FNX_LineShape::Update() { // Update center and axis vectors FNX_Coords coords = GetWorldCoords(); Center = coords.T; Axis[0] = coords.R.AxisX(); Axis[1] = coords.R.AxisY(); // Update shape bounding Line FNX_Vector min, max; GetInterval_MinMax(FNX_Vector(1,0), min.x, max.x); GetInterval_MinMax(FNX_Vector(0,1), min.y, max.y); WorldBox.Set(min, max); } int FNX_LineShape::GetNumEdges() { return 2; } FNX_Vector FNX_LineShape::GetEdgeDir(int i) { return Axis[i]; } void FNX_LineShape::GetInterval_CenExt(const FNX_Vector &axis, float &center, float &extents) { center = Center | axis; extents = abs(Axis[0] | axis) * Extents.x; extents += abs(Axis[1] | axis) * Extents.y; } int FNX_LineShape::GetSupportVertices(const FNX_Vector &axis, FNX_Vector *vertices) { const float EdgeEpsilon = 2.6E-3f; float dots[2]; // Calculate dots for (int i=0; i<2; i++) { dots[i] = axis | Axis[i]; } // Test edges for (int i=0; i<2; i++) { // Check if edge is aligned if (FNX_Abs(dots[i]) > EdgeEpsilon) continue; // It's not // Get edge center int crossAxis = (i+1)%2; FNX_Vector C = Center - (Axis[crossAxis] * FNX_Sign(dots[crossAxis]) * Extents[crossAxis]); // Finalize edge vertices[0] = C - Axis[i] * Extents[i]; vertices[1] = C + Axis[i] * Extents[i]; return 2; } // Use vertex vertices[0] = Center; vertices[0] -= Axis[0] * Extents.x * FNX_Sign(dots[0]); vertices[0] -= Axis[1] * Extents.y * FNX_Sign(dots[1]); return 1; } /* FNX_LineShape::FNX_LineShape(FNX_Actor *actor, const FNX_LineShapeDesc &desc) : FNX_BaseShape(actor, desc) { int Dir=1; if(desc.Start.y>desc.End.y)Dir=-1; FNX_Vector v1,v2; v1=FNX_Vector(Dir,0); v2=desc.End-desc.Start; v1.Normalize();v2.Normalize(); float dot=v1 | v2; Coords.T=desc.Start+(desc.End-desc.Start)/2.0f; Coords.R=FNX_Rotation(acosf(dot)); Extents.x=(desc.End-desc.Start).Length()/2.0f; Extents.y=0.5f; }; bool FNX_LineShape::IsTouchingPoint(const FNX_Vector &point) { FNX_Coords inv_world = -GetWorldCoords(); FNX_Vector local = inv_world * point; if (local.x < -Extents.x || local.x > Extents.x) return false; if (local.y < -1 || local.y > 1) return false; return true; } inline FNX_Vector FNX_LineShape::GetSize(){ return Extents; } void FNX_LineShape::Update() { // Update center and axis vectors FNX_Coords coords = GetWorldCoords(); Center = coords.T; Axis[0] = coords.R.AxisX(); Axis[1] = coords.R.AxisY(); // Update shape bounding Line FNX_Vector min, max; GetInterval_MinMax(FNX_Vector(1,0), min.x, max.x); GetInterval_MinMax(FNX_Vector(0,1), min.y, max.y); WorldBox.Set(min, max); } int FNX_LineShape::GetNumEdges() {//changed from box return 2; } FNX_Vector FNX_LineShape::GetEdgeDir(int i) { //changed from box return Axis[i]; } void FNX_LineShape::GetInterval_CenExt(const FNX_Vector &axis, float &center, float &extents) { center = Center | axis; extents = abs(Axis[0] | axis) * Extents.x; extents += abs(Axis[1] | axis) * Extents.y; } int FNX_LineShape::GetSupportVertices(const FNX_Vector &axis, FNX_Vector *vertices) { const float EdgeEpsilon = 2.6E-3f; float dots[2]; // Calculate dots for (int i=1; i<2; i++) { dots[i] = axis | Axis[i]; } // Test edges for (int i=1; i<2; i++) { // Check if edge is aligned if (FNX_Abs(dots[i]) > EdgeEpsilon) continue; // It's not // Get edge center int crossAxis = 1; FNX_Vector C = Center - (Axis[crossAxis] * FNX_Sign(dots[crossAxis]) * Extents[crossAxis]); // Finalize edge vertices[0] = C - Axis[i] * Extents[i]; vertices[1] = C + Axis[i] * Extents[i]; return 2; } // Use vertex vertices[0] = Center; vertices[0] -= Axis[0] * Extents.x * FNX_Sign(dots[0]); vertices[0] -= Axis[1] * Extents.y * FNX_Sign(dots[1]); return 1; } */
3ee494af1c5255b2d58753e8128e7ff66da260fe
62c976bbd8ba0e2bbfa251ba21a24b3005484dd2
/CalificaArreglo/CalificaArreglo/main.cpp
74eb4e9c0ac788e7d6154742d897fc92b4e1e7fe
[]
no_license
PatricioSaldivar/FundamentsOfProgramming
7e5c81c79cd48fd273880d0590630d52c65284d7
f66ee4cd7b34db72111c5bcb303e0b61900996a6
refs/heads/master
2020-03-29T06:56:07.857308
2018-09-20T17:37:38
2018-09-20T17:37:38
149,634,691
0
0
null
null
null
null
UTF-8
C++
false
false
1,182
cpp
main.cpp
// // main.cpp // CalificaArreglo // // Created by Pato Saldivar on 30/10/17. // Copyright ยฉ 2017 Pato Saldivar. All rights reserved. // #include <iostream> #include <cmath> using namespace std; void PideDatos(char respuestas[], int &tam){ do{ cout<< "Cuantos datos?"; cin>>tam; }while(tam<1||tam>20); for (int i=0; i<tam; i++) { cin>> respuestas[i]; } } void ExamenDeAlumno(char respuestas[],int tam, int &alumnos,char resp_alumnos[],int correctos, int incorrectos ){ cout<< "Cuantos alumnos?"; cin>>alumnos; for (int c=0; c<alumnos; c++) { correctos=0; incorrectos=0; for (int i=0; i<tam; i++) { cin>> resp_alumnos[i]; if (resp_alumnos[i]==respuestas[i]) { correctos++; } else incorrectos++; } cout<< correctos<<" "<<incorrectos<<endl;; } } int main(){ char resp[20],resp_alumnos[20]; int preguntas, alumnos, correctos=0, incorrectos=0; PideDatos(resp, preguntas); ExamenDeAlumno(resp, preguntas, alumnos, resp_alumnos, correctos, incorrectos); }
4fc0b23223994e0ea681411188058ed976e20d40
d32b701f6ccd833293c8571b5411fa55a57b0cb9
/src/select_module.h
810201563e1c11511408eecd633f4266f0c072ef
[]
no_license
mitchellgordon95/GraphicsFromScratch
d0108795d50eb500a3d166602f761cad102e4ea7
30b678f713597a95370411eaf48450737a3d2399
refs/heads/master
2020-05-29T21:14:59.508395
2015-05-05T05:14:45
2015-05-05T05:14:45
35,078,624
0
0
null
null
null
null
UTF-8
C++
false
false
379
h
select_module.h
#ifndef SELECT_MODULE_H #define SELECT_MODULE_H #include "cli_module.h" // Implements the select command for the cli class CLI_Select: public CLI_Module { private: // Configures the filter that is used, globally. void execute(std::vector<char *> &params); public: CLI_Select(): CLI_Module("select", 1) {}; ~CLI_Select(); const char * getHelp(); }; #endif
a05fbd214c8a43f791c95ab287c24999b9091d27
d2b81ede3d3a516f5313835ce07dfea97db46c87
/farey/farey_threads.cpp
9706acad39be8f3b59a5070892ae0491977664dc
[]
no_license
p15-git-acc/code
8b847ad95cd59a13446f595ac65d96d6bc45b512
59337447523018dfab71cbbbda53b4bb88b7ce59
refs/heads/master
2022-12-16T14:38:09.073676
2020-09-16T09:23:00
2020-09-16T09:23:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,794
cpp
farey_threads.cpp
// compute Farey discrepancy sigma (p/q-l/m)^2 #include <math.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> #include <sys/resource.h> #include <gmp.h> #include "A005728_table.h" // from https://oeis.org/A005728/b005728.txt #include "pthread.h" #include "slint.h" #include "inttypes.h" // globals long N,n_threads,M; double DM,*s1,*s2; // sum p/q long *ls; #define CPU_TIME (getrusage(RUSAGE_SELF,&ruse), ruse.ru_utime.tv_sec + \ ruse.ru_stime.tv_sec + 1e-6 * \ (ruse.ru_utime.tv_usec + ruse.ru_stime.tv_usec)) typedef unsigned long ulong; struct rusage ruse; double t0,t1; ulong A005728(ulong n) { // A005728 Number of fractions in Farey series of order n. // a(5)=11 because the fractions are 0/1, 1/5, 1/4, 1/3, 2/5, 1/2, 3/5, 2/3, 3/4, 4/5, 1/1. // a(n) = n(n+3)/2 - Sum(k = 2 to n, a([n/k])) = 1 + Sum_{i=1..n} phi(i). // a[0]=1, a[1]=2, 3, 5, 7, 11, 13, 19, 23, 29, 33, 43, 47, 59, 65, 73, 81, ulong k,sum; // replace below by global table from A005728_table.h //unsigned int A005728_table[]={1,2,3,5,7,11,13,19,23,29,33,43,47,59,65,73,81,97,103,121,129,141,151,173,181,201,213,231,243,271,279,309,325,345,361,385,397,433,451,475,491,531,543,585,605,629,651,697,713,755,775,807,831,883,901,941,965}; if (n<A005728_table_size) return A005728_table[n]; sum=0; for (k=2; k<=n; k++) sum+=A005728(n/k); return (n*(n+3))/2-sum; } // compute the next farey fraction after a/b in sequence F_n void compute_next(long &c, long &d, long p, long q, long n) { if(p==0) { c=1;d=n; //printf("Next after %ld/%ld in F_%ld is %ld/%ld.\n",p,q,n,c,d); } else { long r=q-InvMod(p,q); long m=(n-r)/q; d=m*q+r; c=(d*p+1)/q; //printf("Next after %ld/%ld in F_%ld is %ld/%ld.\n",p,q,n,c,d); } } // compute the farey fractions from thread_no/(2*no_threads) // to (thread_no+1)/(2*no_threads) // we dont know where l should start so we guess and adjust afterwards void *farey(void *arg) { long *thread_no_ptr=(long *)arg; long thread_no=thread_no_ptr[0]; long a,b,c,d,m,cc,dd,k,l=thread_no*M/(2*n_threads); // our guess b=n_threads*2; a=thread_no; long a_stop=thread_no+1,b_stop=n_threads*2; long g=GCD(a,b); a/=g;b/=g; g=GCD(a_stop,b_stop); a_stop/=g;b_stop/=g; compute_next(c,d,a,b,N); double dist,tmp; long double ss1=0.0,ss2=0.0; // to avoid referencing s1 etc. in loop while((a!=a_stop)||(b!=b_stop)) { dist=a;dist/=b; ss1+=dist; // sum p/q needed to correct afterwards tmp=dist-(double)l/DM; ss2+=tmp*tmp; // our first guess at the discrepancy l++; cc=c; dd=d; k=(N+b)/d; d=k*d-b; c=k*c-a; a=cc; b=dd; } s1[thread_no]=ss1; s2[thread_no]=ss2; ls[thread_no]=l-thread_no*M/(2*n_threads); } // this is the adjustment needed if our guessed l wasn't right double dl_term(long th, long l0, long l1, double ss1, double ss2) { long l=th*M/(2*n_threads); // we actually started with l long d=l-l0; double res=d/DM*((double)(l1-l0)*(double)(l1+l0-1)/DM+d*(double)(l1-l0)/DM-2*ss1); return(ss2-res); } int main(int argc, char* argv[]) { if(argc!=3) { printf("Usage:- %s <n> <no threads>.\n",argv[0]); return 0; } printf("Command line:- %s",argv[0]); for(int i=1;i<argc;i++) printf(" %s",argv[i]); printf("\n"); N=atol(argv[1]); n_threads=atol(argv[2]); M=A005728(N)-1; printf("m=%ld\n",M); DM=M; s1=(double *)malloc(sizeof(double)*n_threads); s2=(double *)malloc(sizeof(double)*n_threads); ls=(long *)malloc(sizeof(long)*n_threads); for(int i=0;i<n_threads;i++) { s1[i]=0.0;s2[i]=0.0;ls[i]=0; } // a vector to hold the thread id's pthread_t *thread_id; thread_id=(pthread_t *)malloc(sizeof(pthread_t)*n_threads); // a vector containing 0..n_threads-1 to pass to the sieve routine // so it knows which a's to sieve long *thread_indices; thread_indices=(long *)malloc(sizeof(long)*n_threads); // number the threads from 0 to n_threads-1 for(int n=0;n<n_threads;n++) thread_indices[n]=n; // fire off the threads for(int thread=0,err;thread<n_threads;thread++) { err=pthread_create(thread_id+thread,NULL,farey,thread_indices+thread); if(err!=0) { printf("Error creating thread %d. Exiting.\n",thread); return 0; } } // wait for all threads to complete for(int thread=0;thread<n_threads;thread++) pthread_join(thread_id[thread],NULL); double tot=s2[0]; // the zero'th result needs no adjustment long l0=ls[0]; for(int i=1;i<n_threads;i++) { tot+=dl_term(i,l0,l0+ls[i],s1[i],s2[i]); l0+=ls[i]; } tot*=2.0; // we've only done to fraction 1/2-epsilon printf("Total = %8.6e %8.6e\n",tot,tot*N); return 0; }
cd135ed38c3562f5967cb7d1825b9676c74348b0
66ac7cc546a5ffbb39601e479276d926782fe7b2
/include/cloudapi/bean/ConfirmBean.h
eb5cdabfebcc262a34dbe00b691ed548afd4a9fb
[]
no_license
fengfansky/cloudappclient_linux
487035f69f77aa2657b64087e419907399b6a2b4
90a806e7b4c1cabd741e3d0f6ebc658a7e3b2339
refs/heads/master
2021-01-01T17:45:59.630445
2017-08-23T11:30:41
2017-08-23T11:30:41
98,153,489
0
0
null
null
null
null
UTF-8
C++
false
false
932
h
ConfirmBean.h
// // Created by Fan Feng on 2017/8/7. // #ifndef CLOUDAPPCLIENT_CONFIRMBEAN_H #define CLOUDAPPCLIENT_CONFIRMBEAN_H #include <vector> #include "../action/BaseAction.h" namespace CloudAppClient{ class ConfirmBean { private: std::string confirmIntent; std::string confirmSlot; std::vector<string> optionWords; public: ConfirmBean(); virtual ~ConfirmBean(); bool operator==(const ConfirmBean &rhs) const; bool operator!=(const ConfirmBean &rhs) const; ConfirmBean&operator=(const ConfirmBean &rhs); const string &getConfirmIntent() const; void setConfirmIntent(const string &confirmIntent); const string &getConfirmSlot() const; void setConfirmSlot(const string &confirmSlot); const std::vector<string> &getOptionWords() const; void setOptionWords(const std::vector<string> &optionWords); }; } #endif
e2db3148293a5d45470a5da00736e5b688e04b98
9a879c0669bc70facf5dc2fadaca2eff54bb8a53
/alljoyn/common/inc/qcc/StringSource.h
13ff2f71cec2d5b9e62a62de586e824d0ca035b2
[ "ISC" ]
permissive
octoblu/alljoyn
d86c4d2bb60f989f52f3a3f9a0ce8d11ef5cd3f9
a74003fa25af1d0790468bf781a4d49347ec05c4
refs/heads/master
2021-01-21T12:47:18.034834
2016-03-15T16:23:31
2016-03-15T16:23:31
21,958,119
37
29
null
2016-03-15T16:12:35
2014-07-17T21:24:28
C++
UTF-8
C++
false
false
2,769
h
StringSource.h
/** * @file * * Source implementation used to retrieve bytes from qcc::String */ /****************************************************************************** * Copyright (c) 2009-2011, 2014, AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ #ifndef _QCC_STRINGSOURCE_H #define _QCC_STRINGSOURCE_H #include <qcc/platform.h> #include <qcc/String.h> #include <qcc/Event.h> #include <qcc/Stream.h> #include <algorithm> namespace qcc { /** * StringSource provides Source based retrieval from std:string storage. */ class StringSource : public Source { public: /** * Construct a StringSource. * @param str Source contents */ StringSource(const qcc::String str) : str(str), outIdx(0) { } /** * Construct a StringSource from data. * * @param data Source contents * @param len The length of the data. */ StringSource(const void* data, size_t len) : outIdx(0) { str.insert(0, (const char*)data, len); } /** Destructor */ virtual ~StringSource() { } /** * Pull bytes from the source. * The source is exhausted when ER_EOF is returned. * * @param buf Buffer to store pulled bytes * @param reqBytes Number of bytes requested to be pulled from source. * @param actualBytes Actual number of bytes retrieved from source. * @param timeout Timeout in milliseconds. * @return ER_OK if successful. ER_EOF if source is exhausted. Otherwise an error. */ QStatus PullBytes(void* buf, size_t reqBytes, size_t& actualBytes, uint32_t timeout = Event::WAIT_FOREVER); /** * Return the number of octets not yet read. * * @return Number of octets not read. */ size_t Remaining() const { return str.size() - outIdx; } private: qcc::String str; /**< storage for byte stream */ size_t outIdx; /**< index to next byte in str to be returned */ }; } #endif
b6eba1d73f38639919e82904d9d05d65051d9958
9f5846ee31946ac0defb7d0a11a9fa5da78feaf4
/Points in Segments (II).cpp
215f2020cd12e105294496ea519994b50c7d178c
[]
no_license
MohamedAboBakr/LightOJ
565a44b42b951b96dc8ec2c0194e4163d0e508c7
9287a04771a01b12d6872febdd5cbcd4d7b570b4
refs/heads/master
2020-03-13T19:16:37.255696
2018-04-27T05:41:49
2018-04-27T05:41:49
131,250,438
0
0
null
null
null
null
UTF-8
C++
false
false
2,053
cpp
Points in Segments (II).cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll ; typedef pair<int,int>pi; int readInt () { bool minus = false; int result = 0; char ch; ch = getchar(); while (true) { if (ch == '-') break; if (ch >= '0' && ch <= '9') break; ch = getchar(); } if (ch == '-') minus = true; else result = ch-'0'; while (true) { ch = getchar(); if (ch < '0' || ch > '9') break; result = result*10 + (ch - '0'); } if (minus) return -result; else return result; } map<int,int>mp; set<int> sett; int st[600010]; void add(int p,int l,int r,int i,int j){ if(i>r || j<l) return; if(i<=l && j>=r){ st[p]++; return; } int lft,rgt,mid; lft = 2*p ; rgt = lft+1; mid = (l+r)/2; st[lft]+=st[p]; st[rgt]+=st[p]; st[p]=0; add(lft,l,mid,i,j);add(rgt,mid+1,r,i,j); } int sum(int p,int l,int r,int index){ if(l==r) return st[p]; int lft,rgt,mid; lft = 2*p ; rgt = lft+1; mid = (l+r)/2; st[lft]+=st[p]; st[rgt]+=st[p]; st[p]=0; if(index<=mid) return sum(lft,l,mid,index); return sum(rgt,mid+1,r,index); } int main(){ int t,n,c,q,l,r,j=1; t=readInt(); while(j<=t){ printf("Case %d:\n",j); memset(st,0,sizeof(st)); mp.clear(); sett.clear(); vector<pi>segs; vector<int> querys; n=readInt();q=readInt(); for(int i=0;i<n;i++){ l=readInt();r=readInt(); segs.push_back(pi(l,r)); sett.insert(l);sett.insert(r); } for(int i=0;i<q;i++){ l=readInt(); querys.push_back(l); sett.insert(l); } c=0; set<int>::iterator it=sett.begin(); for(;it!=sett.end();it++){ mp[*it]=c++; } int ind1,ind2; for(int i=0;i<n;i++){ ind1=mp[segs[i].first];ind2=mp[segs[i].second]; add(1,0,150000,ind1,ind2); } for(int i=0;i<q;i++){ ind1 = mp[querys[i]]; printf("%d\n",sum(1,0,150000,ind1)); } j++; } return 0; }
31d6d0e41f266642ea82309b11efd5bc4d4f251c
a11366c47aca47cd9dc186c0dc950359571648ef
/3-POTENCIOMETRO/Entrada_Analogica/Entrada_Analogica.ino
3feffb95c801d0645a194ed28ca2ea2ece3a5c1b
[]
no_license
Canal-Eletronica-Facil/Projeto3_U2_Potenciometro_ESP32
f8174d6cbb2022be8fca29fe976b9efaead45410
7399d064fc44434dc7b4c4755cc57806379a2bf4
refs/heads/master
2022-03-30T13:58:58.863216
2020-01-30T20:45:43
2020-01-30T20:45:43
237,302,187
0
0
null
null
null
null
UTF-8
C++
false
false
3,425
ino
Entrada_Analogica.ino
//... Livro IoT na Prรกtica - PROGRAMA 3 - Leitura de Entradas Analรณgicas ...// //............. BLOCO 1 - NOMEAR PINOS USADOS NO PROJETO .............// int POTENCIOMETRO = 34; // Seleciona o nome POTENCIOMETRO para o GPIO 34 do ESP32 int Leitura_POT = 0; // Variรกvel que irรก salvar o valor obtido da conversรฃo ADC float tensao = 0; // Variรกvel que irรก armazenar o valor calculado da tensรฃo elรฉtrica int LED1 = 32; // Seleciona o nome LED1 para o GPIO 32 do ESP32 int LED2 = 33; // Seleciona o nome LED1 para o GPIO 33 do ESP32 int LED3 = 25; // Seleciona o nome LED1 para o GPIO 25 do ESP32 int LED4 = 27; // Seleciona o nome LED1 para o GPIO 27 do ESP32 int LED5 = 12; // Seleciona o nome LED1 para o GPIO 12 do ESP32 int LED6 = 13; // Seleciona o nome LED1 para o GPIO 13 do ESP32 //............. BLOCO 2 - CONFIGURAR PINOS USADOS NO PROJETO .............// void setup() { pinMode(POTENCIOMETRO,INPUT); // Configura o GPIO 34 do ESP32 como entrada pinMode(LED1, OUTPUT); // Configura o GPIO 32 do ESP32 como saรญda pinMode(LED2, OUTPUT); // Configura o GPIO 33 do ESP32 como saรญda pinMode(LED3, OUTPUT); // Configura o GPIO 25 do ESP32 como saรญda pinMode(LED4, OUTPUT); // Configura o GPIO 27 do ESP32 como saรญda pinMode(LED5, OUTPUT); // Configura o GPIO 12 do ESP32 como saรญda pinMode(LED6, OUTPUT); // Configura o GPIO 13 do ESP32 como saรญda Serial.begin(115200); } //......... BLOCO 3 - REPETIร‡รƒO DAS TAREFAS USADAS NO PROJETO ...........// void loop() { Leitura_POT = analogRead(POTENCIOMETRO); Serial.print("O Valor do ADC eh:"); Serial.print(Leitura_POT); tensao = (Leitura_POT * 3.3) / 4095; Serial.print(" O Valor da tensao eletrica eh:"); Serial.print(tensao); Serial.println(" Volts"); if(tensao < 0.5) { digitalWrite(LED1,LOW); digitalWrite(LED2,LOW); digitalWrite(LED3,LOW); digitalWrite(LED4,LOW); digitalWrite(LED5,LOW); digitalWrite(LED6,LOW); } else if(tensao > 0.5 && tensao < 1.0) { digitalWrite(LED1,HIGH); digitalWrite(LED2,LOW); digitalWrite(LED3,LOW); digitalWrite(LED4,LOW); digitalWrite(LED5,LOW); digitalWrite(LED6,LOW); } else if(tensao > 1.0 && tensao < 1.5) { digitalWrite(LED1,HIGH); digitalWrite(LED2,HIGH); digitalWrite(LED3,LOW); digitalWrite(LED4,LOW); digitalWrite(LED5,LOW); digitalWrite(LED6,LOW); } else if(tensao > 1.5 && tensao < 2.0) { digitalWrite(LED1,HIGH); digitalWrite(LED2,HIGH); digitalWrite(LED3,HIGH); digitalWrite(LED4,LOW); digitalWrite(LED5,LOW); digitalWrite(LED6,LOW); } else if(tensao > 2.0 && tensao < 2.5) { digitalWrite(LED1,HIGH); digitalWrite(LED2,HIGH); digitalWrite(LED3,HIGH); digitalWrite(LED4,HIGH); digitalWrite(LED5,LOW); digitalWrite(LED6,LOW); } else if(tensao > 2.5 && tensao < 3.0) { digitalWrite(LED1,HIGH); digitalWrite(LED2,HIGH); digitalWrite(LED3,HIGH); digitalWrite(LED4,HIGH); digitalWrite(LED5,HIGH); digitalWrite(LED6,LOW); } else if(tensao > 3.0) { digitalWrite(LED1,HIGH); digitalWrite(LED2,HIGH); digitalWrite(LED3,HIGH); digitalWrite(LED4,HIGH); digitalWrite(LED5,HIGH); digitalWrite(LED6,HIGH); } delay(100); }
f702fd86e8d533d20ae238321ab0383b9575951d
b28630e51de521151d56a3489c402bde14fd9ffb
/Mx/Input/MxGamepad.h
eda1adb1b0ecf15a4f0ae0614c9613f363450581
[]
no_license
hitsz-ldjam/MixEngine
d1f9891ed15621e47f9c4ebdb4a8e371831eba99
005f4c9341d55b38f8d0b5955d32951887b08d46
refs/heads/master
2020-04-13T19:41:06.377357
2019-12-21T13:08:24
2019-12-21T13:08:24
163,409,978
4
5
null
2019-11-26T11:34:50
2018-12-28T12:48:40
C++
UTF-8
C++
false
false
1,167
h
MxGamepad.h
#pragma once #ifndef MX_GAMEPAD_H_ #define MX_GAMEPAD_H_ #include "../Engine/MxPlatform.h" #include <SDL2/SDL.h> namespace Mix { class Input; class Gamepad :GeneralBase::NoCopyBase { friend class Input; public: Gamepad(int _index, Input* _input); ~Gamepad(); Gamepad(Gamepad&& _other) noexcept; Gamepad& operator=(Gamepad&& _other) noexcept; const std::string& getName() const { return mName; } int getInstanceId() const { return mInstanceId; } uint8_t getButtonState(ButtonCode _button) const; float getAxis(AxisCode _axis) const; Vector2f getAxis(AxisCode _x, AxisCode _y) const; void nextFrame(); private: static const uint32_t sAxisCount = static_cast<uint32_t>(AxisCode::GamepadAxisCount); static const uint32_t sButtonCount = static_cast<uint32_t>(ButtonCode::GamepadCount); int mInstanceId = -1; std::string mName; SDL_GameController* mGameController; Input* mInput; float mStickDeadZone = 0.2f; float mAxisState[sAxisCount]{}; uint8_t mButtonState[sButtonCount]{}; void updateAxis(const PFGamepadAxisEventData& _data); void updateButton(const PFGamepadButtonEventData& _data); }; } #endif
8c9a9c7b75a4eb872f76400916c5aebb39f905c3
a02220745ccf218c81353edc04becfbf0e9bcc82
/kinematics.h
f7fe3b7d7acbb500065c2dc40ab507c6f61871d6
[]
no_license
Yuancheng-Zhang/Romi-Line-Following-Task
c034f853398ef1bf2403cc3327c6e6895d286187
3c12487433905acc7c3e9dda8d9abcf34c6db0dc
refs/heads/master
2022-12-17T08:45:46.295891
2020-09-22T00:47:21
2020-09-22T00:47:21
297,494,787
1
0
null
null
null
null
UTF-8
C++
false
false
3,193
h
kinematics.h
#ifndef _Kinematics #define _Kinematics_h #define PI 3.1415926535897932384626433832795 //You may want to use some/all of these variables const float WHEEL_DIAMETER = 70.0f; // Diameter in mm. const float WHEEL_RADIUS = 35.0f; // Radius in mm. const float WHEEL_SEPERATION = 140.0f; // Distance between wheels. const float GEAR_RATIO = 1.0f/120.0f; // Gearbox --- 1 : 120. const float COUNTS_PER_SHAFT_REVOLUTION = 12.0f; // 1 Shaft Revolution = 12 counts const float COUNTS_PER_WHEEL_REVOLUTION = 1440.0f; // 1 Wheel Revolution = 1440 counts. const float COUNTS_PER_MM = (1 / (WHEEL_DIAMETER * PI)) * COUNTS_PER_WHEEL_REVOLUTION; // Build up your Kinematics class. class Kinematics { public: Kinematics(); // Constructor, required. void update(long count_left, long count_right); // should calucate an update to pose. float face_home(); float home_distance(); float get_theta(); float get_xpos(); float get_ypos(); void reset_theta(); private: //Private variables and methods go here float xpos; float ypos; float theta; long old_count_left; long old_count_right; }; // Required constructor. Initialise variables. Kinematics::Kinematics() // works as the setup(); { xpos = 0; ypos = 0; theta = 0; old_count_left = 0; old_count_right = 0; } void Kinematics :: update(long count_left, long count_right) { // count the change of count of both wheels: long left_count_change = count_left - old_count_left; long right_count_change = count_right - old_count_right; // calculate the distance (mm) of two wheels: float left_distance = (float)left_count_change / COUNTS_PER_MM; float right_distance = (float)right_count_change / COUNTS_PER_MM; // use the mean change in encoder count between the two wheels. // avg_distance float d = (left_distance + right_distance) / 2.0f; // from the view of the map: going right, x++; going up, y--; xpos = xpos + d * cos(theta); ypos = ypos + d * sin(theta); // turn right / rot --- theta ++ ; turn left / anti-rot --- theta -- ; theta = theta + (left_distance - right_distance) / WHEEL_SEPERATION; // unit rad. // Serial.print( xpos ); // Serial.print( ", " ); // Serial.print( ypos ); // Serial.print( ", " ); // Serial.println( theta ); old_count_left = count_left; old_count_right = count_right; return; } // This part is tricky. float Kinematics :: face_home() { float angle = 180 - (theta / (2 * PI) * 360); // unit: degree. // float angle = atan2(ypos, xpos); return angle; } // Calculate the distance from pos to home. float Kinematics :: home_distance() { float distance = sqrt(xpos * xpos + ypos * ypos); return distance; } void Kinematics :: reset_theta() { theta = 0; } float Kinematics :: get_theta() { return theta; } float Kinematics :: get_xpos() { return xpos; } float Kinematics :: get_ypos() { return ypos; } #endif // end kinematics
65bbe17ac0e2fb8bbafb3a6426ff4619cf2a2575
3dd49f1ebae3af35d6d24c58ade47880dbdfa11f
/exercise/chapter16/ex16_13.cpp
0f390bde7595f7e3977e2043658ed38032a554c5
[]
no_license
xiaoqiangkx/cpp_primer
dc6be8e602247f4bd0c6346ecefac8049b7f1207
37c51fcb1559b80dbe871fff22c8abb05396a608
refs/heads/master
2021-01-23T12:37:43.916372
2014-10-10T07:58:41
2014-10-10T07:58:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
332
cpp
ex16_13.cpp
#include <iostream> #include <vector> using namespace std; template <typename T> void printElem(const T &container) { typename T::size_type len = container.size(); for (int i=0; i<len; i++) { cout << container[i] << endl; } } int main() { vector<int> data(5, 1); printElem(data); return 0; }
6ae00ced4522937575392be4484ac955e94f2eb6
0085c801412b5695c824ca53cd0d103daff37027
/qnod3d/itool.cpp
7f26f0c7c1693c21d47b6e0a4071c77840edc332
[]
no_license
alesegdia/qnod3d
f8926b9d516a23e8bf6005be57689974309728c6
5e71c56d02333b8640910a171d417b3a9e2a452c
refs/heads/master
2021-01-22T10:21:16.531096
2015-08-31T01:48:09
2015-08-31T01:48:09
39,013,661
1
0
null
null
null
null
UTF-8
C++
false
false
63
cpp
itool.cpp
#include "itool.h" ITool::ITool() { } ITool::~ITool() { }
d875b0f64192e3ab1bddeb5bd37281adaf4b3b6a
67a6e8dfe7952cecfd7ce69255f8fdc54de4a2fa
/loon/code/util.cpp
9da33594a24d7092efc089dbbb6d2e2b3f833902
[ "MIT" ]
permissive
stoman/HashCode2017Warmup
3749fa5c83fc9cfa393b8eda75063022177b5082
14e0a07822321e9cb6c02fcf4570418c3ab231e1
refs/heads/master
2020-04-06T04:41:40.399316
2017-03-31T08:48:36
2017-03-31T08:48:36
82,566,422
1
1
null
null
null
null
UTF-8
C++
false
false
2,275
cpp
util.cpp
#pragma once typedef long long ll; #include <algorithm> #include <iostream> #include <limits> #include <map> #include <string> #include <time.h> #include <utility> #include <vector> #include <queue> using namespace std; //util classes struct Cluster { double center_r, center_c; int id; vector<pair<int, int>> cells; }; struct Balloon { int id, cluster_id; vector<int> r, c, h; }; struct Input { int r, c, a, l, v, b, t, rs, cs; vector<Cluster> clusters; vector<Balloon> balloons; vector<int> cell_r; vector<int> cell_c; vector<vector<vector<int>>> movement_r; vector<vector<vector<int>>> movement_c; vector<vector<int>> cell_field; }; //input handling void readInput(Input& input, istream& in) { in >> input.r >> input.c >> input.a; in >> input.l >> input.v >> input.b >> input.t; in >> input.rs >> input.cs; for (int i = 0; i < input.l; ++i) { int ri, ci; in >> ri >> ci; input.cell_r.push_back(ri); input.cell_c.push_back(ci); } // resize movement input.movement_r.resize(input.r); input.movement_c.resize(input.r); for (int i = 0; i < input.r; ++i) { input.movement_r[i].resize(input.c); input.movement_c[i].resize(input.c); for (int j = 0; j < input.c; ++j) { input.movement_r[i][j].resize(input.a+1); input.movement_c[i][j].resize(input.a+1); } } // set movements of altitude level 0 to (0,0) for (int r = 0; r < input.r; ++r) { for (int c = 0; c < input.c; ++c) { input.movement_r[r][c][0] = 0; input.movement_c[r][c][0] = 0; } } for (int a = 1; a <= input.a; ++a) { for (int r = 0; r < input.r; ++r) { for (int c = 0; c < input.c; ++c) { int dr, dc; in >> dr >> dc; input.movement_r[r][c][a] = dr; input.movement_c[r][c][a] = dc; } } } // set start coordinates as first coordinate of every balloon input.balloons.resize(input.b); for (int b = 0; b < input.b; ++b) { input.balloons[b].r.push_back(input.rs); input.balloons[b].c.push_back(input.cs); input.balloons[b].h.push_back(0); } // initialize cell field input.cell_field.resize(input.r); for (int i = 0; i < input.r; ++i) input.cell_field[i].resize(input.c, 0); for (int i = 0; i < input.cell_r.size(); ++i) input.cell_field[input.cell_r[i]][input.cell_c[i]] = 1; }
b748ea91c76399de957466822dfad72c03c37044
75baca9483e9f9f107d21b75910db826b93954c1
/Git.cpp
a35ae71e26697070539b6577d0b6fccd1ce9f8df
[ "MIT" ]
permissive
effolkronium/GitChat
365588e8784bdec01ae167d55114c2d034052670
82abbdefe50bd8718fcf655fbb2fe3981c89ade9
refs/heads/master
2020-09-12T01:02:25.065416
2019-12-09T23:46:09
2019-12-09T23:46:09
222,249,445
0
0
null
null
null
null
UTF-8
C++
false
false
7,322
cpp
Git.cpp
#include "Git.h" #include <QDir> #include <QProcess> #include <QUuid> #include <QMessageBox> #include <QFile> #include <QTextStream> #include <stdexcept> #include <iostream> using namespace std::literals; Git::Git(QString gitUrl, QString login, const QString& password) : m_gitCredUrl([&]{ return std::move(gitUrl.replace("https://", "https://" + login + ":" + password + "@")); }()), m_gitLogin{std::move(login)}, m_gitRepoPath{QDir::tempPath() + QDir::separator() + QUuid::createUuid().toString()}, m_gitMessagesPath{m_gitRepoPath + QDir::separator() + "messages"} { CloneRepo(); if(IsNewRepo()) InitRepo(); QMessageBox m; m.show(); m_isRunning = true; m_newMsgThread = std::thread{[this]{ while(m_isRunning) { std::this_thread::sleep_for(4s); if(m_toSend.empty()) continue; std::lock_guard guard{m_mutex}; { QFile file(m_gitMessagesPath); if(!file.open(QIODevice::Append)) { throw std::runtime_error{file.errorString().toUtf8()}; } if(m_messagePos > file.size()) throw std::runtime_error{"New message db is smaller then old"}; QTextStream in(&file); in.setCodec("UTF-8"); while(!m_toSend.empty()) { std::tuple<QString, QString, QString> nextMsg; m_toSend.wait_and_pop(nextMsg); in << '\n' << std::get<0>(nextMsg).toUtf8() << "," << std::get<1>(nextMsg).toUtf8() << "," << std::get<2>(nextMsg).toUtf8(); } in.flush(); } std::this_thread::sleep_for(1s); #ifndef __WIN32 QProcess::execute("sync; echo 3 | sudo tee /proc/sys/vm/drop_caches"); #endif std::this_thread::sleep_for(1s); ExecuteGit("add messages"); ExecuteGit("commit -m\"Git::PushMessage\""); std::cout << "\nPRE_PUSH\n"; while(0 != ExecuteGit2("push")) { std::cout << "\nPRE_PULL\n"; std::this_thread::sleep_for(1s); if(0 != ExecuteGit2("pull")) { std::cout << "\nFIX_CONFLICTS\n"; FixConflicts(); } } } }}; } Git::~Git() { m_isRunning = false; if(m_newMsgThread.joinable()) m_newMsgThread.join(); try { QDir{m_gitRepoPath}.removeRecursively(); } catch (const std::exception& err) { std::cerr << "Git::~Git() has failed: " << err.what(); } } bool Git::IsNewRepo() const { return !QFile{m_gitMessagesPath}.exists(); } void Git::InitRepo() { QFile file(m_gitMessagesPath); file.open(QIODevice::WriteOnly); file.close(); ExecuteGit("add messages"); ExecuteGit("commit -m\"Git::InitRepo()\""); ExecuteGit("push"); } void Git::PushMessage(const QString& author, const QString& message) { auto newGuid = QUuid::createUuid().toString(); { std::lock_guard _{m_presendMsgGuids_mutex}; m_presendMsgGuids.insert(newGuid); } m_toSend.push({newGuid, author, message}); } void Git::FixConflicts() { #ifdef __WIN32 { QFile file(m_gitMessagesPath); if(!file.open(QIODevice::ReadWrite | QIODevice::Append)) { throw std::runtime_error{file.errorString().toUtf8()}; } if(m_messagePos > file.size()) throw std::runtime_error{"New message db is smaller then old"}; { QTextStream in(&file); in.setCodec("UTF-8"); if(!in.seek(0)) throw std::runtime_error{"if(!file.seek(m_messagePos))"}; QString textWithoutConflits; while(!in.atEnd()) { QString line = in.readLine(); if(!line.startsWith("{")) continue; textWithoutConflits += line += '\n'; } if(!in.seek(0)) throw std::runtime_error{"if(!file.seek(m_messagePos))"}; in << textWithoutConflits.toUtf8(); in.flush(); } if(!file.resize(file.pos())) throw std::runtime_error{"if(!file.resize(file.pos()))"}; file.flush(); } std::this_thread::sleep_for(1s); #else QProcess::execute("sed -i \"s/<.*//g\" " + m_gitMessagesPath); QProcess::execute("sed -i \"s/>.*//g\" " + m_gitMessagesPath); QProcess::execute("sed -i \"s/=.*//g\" " + m_gitMessagesPath); QProcess::execute("sync; echo 3 | sudo tee /proc/sys/vm/drop_caches"); #endif std::this_thread::sleep_for(1s); std::cout << "\nPRE_ADD_MSG_CONF\n"; ExecuteGit("add messages"); std::cout << "\nPRE_FIX_CONFLICT_COMMIT_CONF\n"; ExecuteGit("commit -m\"Git::FixConflicts\""); } std::queue<std::pair<QString, QString>> Git::GetNewMessages() { std::lock_guard guard{m_mutex}; ExecuteGit("pull"); QFile file(m_gitMessagesPath); if(!file.open(QIODevice::ReadOnly)) { throw std::runtime_error{file.errorString().toUtf8()}; } if(m_messagePos > file.size()) throw std::runtime_error{"New message db is smaller then old"}; QTextStream in(&file); in.setCodec("UTF-8"); if(!in.seek(m_messagePos)) throw std::runtime_error{"if(!file.seek(m_messagePos))"}; std::queue<std::pair<QString, QString>> messages; while(!in.atEnd()) { QString line = in.readLine(); if(line.size() == 0) continue; QStringList fields = line.split(","); if(fields.size() != 3) throw std::runtime_error{"Corrupted messages file"}; bool isMsgWasPresended = false; { std::lock_guard _{m_presendMsgGuids_mutex}; auto findIt = m_presendMsgGuids.find(fields[0]); if(m_presendMsgGuids.end() != findIt) { isMsgWasPresended = true; } else { m_presendMsgGuids.emplace(fields[0]); } } if(!isMsgWasPresended) messages.emplace(std::move(fields[1]), std::move(fields[2])); } m_messagePos = 0; return messages; } void Git::CloneRepo() { if(QDir{m_gitRepoPath}.exists()) throw std::runtime_error{("The directory " + m_gitRepoPath + " already exist").toUtf8()}; QDir().mkdir(m_gitRepoPath); ExecuteGit(QString{"clone "} + m_gitCredUrl + " " + m_gitRepoPath); } void Git::ExecuteGit(const QString& command) { std::lock_guard guard{gc_mutex}; auto gitCommand = "git -C \"" + m_gitRepoPath + "\" " + "-c user.name='" + m_gitLogin + "' -c user.email='<>' " + command; if(0 != QProcess::execute(gitCommand)) throw std::runtime_error{("The command \"" + gitCommand + "\" has failed").toUtf8()}; } int Git::ExecuteGit2(const QString& command) { std::lock_guard guard{gc_mutex}; auto gitCommand = "git -C \"" + m_gitRepoPath + "\" " + "-c user.name='" + m_gitLogin + "' -c user.email='<>' " + command; return QProcess::execute(gitCommand); }
5663a70c26ed45c4c4c8c7aed4b28e83c82ed7c4
77175d4ea07c21ae29b774568f9728fa0d033776
/xtc/InDatagramIterator.hh
f6306a90298dbec907a8400b55f58c7a56b4185c
[]
no_license
lcls-daq/pds
e7c8e33250df6bf172d26966d687fb6b4b9eb2d4
2f23434a8b215a0b17097732226e9f56fb208d1b
refs/heads/master
2023-08-31T20:03:35.704427
2023-08-17T10:16:05
2023-08-17T10:16:05
87,124,361
0
1
null
null
null
null
UTF-8
C++
false
false
781
hh
InDatagramIterator.hh
#ifndef Pds_InDatagramIterator_hh #define Pds_InDatagramIterator_hh #include <sys/socket.h> namespace Pds { class InDatagramIterator { public: virtual ~InDatagramIterator() {} // skip over "len" bytes // returns number of bytes skipped virtual int skip(int len) = 0; // read "len" bytes and assign "iov" to reference them // returns number of bytes read virtual int read(iovec* iov, int maxiov, int len) = 0; // read "len" bytes. // if they are not already contiguous, copy them into "buffer". // returns location of contiguous data. virtual void* read_contiguous(int len, void* buffer) = 0; // copy "len" bytes to "dst" // returns number of bytes copied int copy( void* dst, int len ); }; } #endif
fd4a89942f14895078a624903f1f951cf29f21fa
dc44574b58526b5f6d6271a4df6e85fb715d4372
/Binary_Tree_Maximum_Path_Sum.cpp
d289fb4c0ca83d5950aa04ff999d414866aab989
[]
no_license
asuo1986/LeetCode-1
d94ed17ce83320f50dddbca140802ad93b8a0e4f
39ef37d1c25277685686f31dd4032e36d0c63d21
refs/heads/master
2020-04-05T23:36:31.013517
2017-03-03T22:53:05
2017-03-03T22:53:05
22,616,447
0
0
null
2017-03-03T22:53:06
2014-08-04T19:09:38
C++
UTF-8
C++
false
false
1,349
cpp
Binary_Tree_Maximum_Path_Sum.cpp
/* Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. For example: Given the below binary tree, 1 / \ 2 3 Return 6. */ /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ // Ke Hu (mrhuke@gmail.com) Apr. 2013 class Solution { public: int maxPathSum(TreeNode *root, int &leftToRoot, int &rightToRoot) { if (!root){ leftToRoot = 0; rightToRoot = 0; return INT_MIN; } int leftLeftToRoot, leftRightToRoot,rightLeftToRoot, rightRightToRoot; int leftPath = maxPathSum(root->left, leftLeftToRoot, leftRightToRoot); int rightPath = maxPathSum(root->right, rightLeftToRoot, rightRightToRoot); leftToRoot = max( max(leftLeftToRoot, leftRightToRoot) + root->val, root->val); rightToRoot = max( max(rightLeftToRoot, rightRightToRoot) + root->val, root->val); int maxPath = max( leftToRoot + rightToRoot - root->val, max(leftPath, rightPath) ); return maxPath; } int maxPathSum(TreeNode *root) { int leftToRoot, rightToRoot; return maxPathSum(root, leftToRoot, rightToRoot); } };
e3217c17c7e9094dc84fbf048af4485413d9760d
6b4e2a7f51647524db22208eb98e925d1537fb6b
/String/2456. Most Popular Video Creator.cpp
ba7d70e9ce0dd664b4b217bb5c34163f3cbc701e
[]
no_license
denis-gubar/Leetcode
a099e0fd07600ae63456059753332f90ddd96542
ad54bee10fdf59644cc762218277a2f9de9b3509
refs/heads/master
2023-07-21T04:25:57.949932
2023-07-09T12:46:24
2023-07-09T12:46:24
218,048,440
5
0
null
null
null
null
UTF-8
C++
false
false
773
cpp
2456. Most Popular Video Creator.cpp
class Solution { public: vector<vector<string>> mostPopularCreator(vector<string>& creators, vector<string>& ids, vector<int>& views) { int N = creators.size(); vector<vector<string>> result; unordered_map<string, long long> M; unordered_map<string, vector<pair<int, string>>> P; for (int i = 0; i < N; ++i) { M[creators[i]] += views[i]; P[creators[i]].push_back({ -views[i], ids[i] }); } long long best = 0; for (auto [key, value] : M) best = max(best, value); for (auto const& [key, value] : P) if (M[key] == best) result.push_back({ key, min_element(value.begin(), value.end())->second }); return result; } };
531bf1b70e9f6c708b2e0baa7a2d57f6777bd07c
6e8c0b99a8156e28dd8bb35bb5085d3e4167ad4e
/smart-room/heater_server/heater_server.ino
5384b8ae479aec87d0cf707d8a648e03c9e8077c
[]
no_license
bhatt-007/smart-home
3bd49ebfa3055f6446ae5d0c8003be11900ffab6
81598ca7168920577508f957a7ac2152d88f5690
refs/heads/main
2023-02-05T21:44:39.996528
2020-12-27T17:57:16
2020-12-27T17:57:16
324,815,185
0
0
null
null
null
null
UTF-8
C++
false
false
2,197
ino
heater_server.ino
#include <ESPmDNS.h> #include <WiFi.h> #include <WebServer.h> #define POWER_ON 1 #define POWER_OFF 0 // Replace with your network credentials const char* ssid = "Toofan"; const char* password = "NahiBataunga"; // Set web server port number to 80 WebServer server(80); int heaterpin = 23; int status = 0; void setup() { Serial.begin(115200); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected."); Serial.println("IP address: "); Serial.println(WiFi.localIP()); if(!MDNS.begin("heater-server")) { Serial.println("Error starting mDNS"); return; } MDNS.addService("http", "tcp", 80); server.on("/power-status", handle_get_power_status); server.on("/power-on", handle_post_power_on); server.on("/power-off", handle_post_power_off); server.onNotFound(handle_NotFound); server.begin(); Serial.begin(115200); pinMode(heaterpin, OUTPUT); } void handle_NotFound() { server.send(404, "text/plain", "Not found"); } void handle_get_power_status() { Serial.println("In get power status"); char power_status[5]=""; sprintf(power_status, "%d",status ); server.send(200, "text/html", power_status); } void handle_post_power_on() { if(status == POWER_OFF){ Serial.println("Powering On"); digitalWrite(heaterpin, HIGH); // turn the LED on (HIGH is the voltage level) char power_status[3]=""; status = POWER_ON; sprintf(power_status, "%d",status ); server.send(200, "text/html", power_status); } else { server.send(200, "text/html"); Serial.println("Power already On"); } } void handle_post_power_off() { if(status == POWER_ON) { Serial.println("Powering OFF"); digitalWrite(heaterpin, LOW); // turn the LED on (HIGH is the voltage level) char power_status[5]=""; status = POWER_OFF; sprintf(power_status, "%d",status ); server.send(200, "text/html", power_status); } else { server.send(200, "text/html"); Serial.println("Power already Off"); } } void loop() { server.handleClient(); }
7fd61199bcf16b3c749a4398707bd9915b93ef6b
1bbbb810b5b74130c4e0ae89de7c0157573f14c3
/Plugins/Wwise/Source/AkAudio/Private/AkWaapiUMG/Components/SAkItemBoolProperties.cpp
e47d475c55ade2b322492a1267fa57355c44e40d
[ "MIT" ]
permissive
marcowchan/GMTK2021
0ce8be50662784b4776fcdd91561332fec632c4f
d638a7ae3ab1fa56839b77e9d15abf70ac3bde7f
refs/heads/new-main
2023-06-02T05:47:45.688156
2021-06-17T22:49:41
2021-06-17T22:49:41
374,914,307
0
0
MIT
2021-06-17T22:49:42
2021-06-08T07:03:59
C++
UTF-8
C++
false
false
8,740
cpp
SAkItemBoolProperties.cpp
/******************************************************************************* The content of the files in this repository include portions of the AUDIOKINETIC Wwise Technology released in source code form as part of the SDK package. Commercial License Usage Licensees holding valid commercial licenses to the AUDIOKINETIC Wwise Technology may use these files in accordance with the end user license agreement provided with the software or, alternatively, in accordance with the terms contained in a written agreement between you and Audiokinetic Inc. Copyright (c) 2021 Audiokinetic Inc. *******************************************************************************/ /*------------------------------------------------------------------------------------ SAkItemBoolProperties.cpp ------------------------------------------------------------------------------------*/ /*------------------------------------------------------------------------------------ includes. ------------------------------------------------------------------------------------*/ #include "AkWaapiUMG/Components/SAkItemBoolProperties.h" #include "AkAudioDevice.h" #include "Widgets/Input/SSearchBox.h" #include "Widgets/Input/SButton.h" #include "Misc/ScopedSlowTask.h" #include "AkAudioStyle.h" #include "Framework/Application/SlateApplication.h" /*------------------------------------------------------------------------------------ Defines ------------------------------------------------------------------------------------*/ #define LOCTEXT_NAMESPACE "AkAudio" DEFINE_LOG_CATEGORY(LogAkItemBoolProperties); /*------------------------------------------------------------------------------------ Statics and Globals ------------------------------------------------------------------------------------*/ namespace SAkItemBoolProperties_Helpers { static const FString FullBoolPropertiesList[] = { TEXT("BypassEffect"), TEXT("BypassEffect0"), TEXT("BypassEffect1"), TEXT("BypassEffect2"), TEXT("BypassEffect3"), #if AK_WWISESDK_VERSION_MAJOR <= 2017 TEXT("DynamicPositioning"), #endif #if AK_WWISESDK_VERSION_MAJOR >= 2019 TEXT("EnableAttenuation"), #endif TEXT("EnableLoudnessNormalization"), TEXT("EnableMidiNoteTracking"), #if AK_WWISESDK_VERSION_MAJOR <= 2017 TEXT("EnablePanner"), TEXT("EnablePositioning"), TEXT("FollowListenerOrientation"), #endif TEXT("HdrEnableEnvelope"), #if AK_WWISESDK_VERSION_MAJOR >= 2018 TEXT("HoldEmitterPositionOrientation"), TEXT("HoldListenerOrientation"), #endif TEXT("IgnoreParentMaxSoundInstance"), TEXT("Inclusion"), TEXT("IsLoopingEnabled"), TEXT("IsLoopingInfinite"), TEXT("IsNonCachable"), TEXT("IsStreamingEnabled"), TEXT("IsZeroLantency"), #if AK_WWISESDK_VERSION_MAJOR >= 2018 TEXT("ListenerRelativeRouting"), #endif TEXT("MidiBreakOnNoteOff"), TEXT("OverrideAnalysis"), TEXT("OverrideConversion"), TEXT("OverrideEffect"), TEXT("OverrideGameAuxSends"), TEXT("OverrideHdrEnvelope"), TEXT("OverrideMidiEventsBehavior"), TEXT("OverrideMidiNoteTracking"), TEXT("OverrideOutput"), TEXT("OverridePositioning"), TEXT("OverridePriority"), TEXT("OverrideUserAuxSends"), TEXT("OverrideVirtualVoice"), TEXT("PriorityDistanceFactor"), TEXT("RenderEffect0"), TEXT("RenderEffect1"), TEXT("RenderEffect2"), TEXT("RenderEffect3"), #if AK_WWISESDK_VERSION_MAJOR <= 2017 TEXT("Spatialization"), #endif TEXT("UseGameAuxSends"), TEXT("UseMaxSoundPerInstance") }; enum { FullBoolPropertiesListSize = sizeof(FullBoolPropertiesList) / sizeof(*FullBoolPropertiesList) }; } /*------------------------------------------------------------------------------------ Helpers ------------------------------------------------------------------------------------*/ /*------------------------------------------------------------------------------------ SAkItemBoolProperties ------------------------------------------------------------------------------------*/ SAkItemBoolProperties::SAkItemBoolProperties() {} SAkItemBoolProperties::~SAkItemBoolProperties() {} void SAkItemBoolProperties::Construct(const FArguments& InArgs) { OnDragDetected = InArgs._OnDragDetected; OnSelectionChanged = InArgs._OnSelectionChanged; if (InArgs._FocusSearchBoxWhenOpened) { RegisterActiveTimer(0.f, FWidgetActiveTimerDelegate::CreateSP(this, &SAkItemBoolProperties::SetFocusPostConstruct)); } SearchBoxFilter = MakeShareable( new StringFilter( StringFilter::FItemToStringArray::CreateSP( this, &SAkItemBoolProperties::PopulateSearchStrings ) ) ); SearchBoxFilter->OnChanged().AddSP( this, &SAkItemBoolProperties::FilterUpdated ); ChildSlot [ SNew(SBorder) .Padding(4) .BorderImage(FAkAudioStyle::GetBrush("AudiokineticTools.GroupBorder")) [ SNew(SVerticalBox) // Search + SVerticalBox::Slot() .AutoHeight() .Padding(0, 1, 0, 3) [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() [ InArgs._SearchContent.Widget ] + SHorizontalBox::Slot() .FillWidth(1.0f) [ SAssignNew(SearchBoxPtr,SSearchBox) .HintText( LOCTEXT( "PropertiesSearchHint", "Search an item property" ) ) .ToolTipText(LOCTEXT("PropertiesSearchTooltip", "Type here to search for a property")) .OnTextChanged(SearchBoxFilter.Get(), &StringFilter::SetRawFilterText) .SelectAllTextWhenFocused(false) .DelayChangeNotificationsWhileTyping(true) ] ] // Tree +SVerticalBox::Slot() .FillHeight(1.f) [ SAssignNew(ListViewPtr, SListView< TSharedPtr<FString> >) .ListItemsSource(&PropertiesList) .OnGenerateRow( this, &SAkItemBoolProperties::GenerateRow ) .ItemHeight(18) .SelectionMode(InArgs._SelectionMode) .OnSelectionChanged(this, &SAkItemBoolProperties::ListSelectionChanged) .ClearSelectionOnClick(false) ] ] ]; for (const auto& Property : SAkItemBoolProperties_Helpers::FullBoolPropertiesList) { PropertiesList.Add(MakeShareable(new FString(Property))); } ListViewPtr->RequestListRefresh(); } TSharedRef<ITableRow> SAkItemBoolProperties::GenerateRow( TSharedPtr<FString> ItemProperty, const TSharedRef<STableViewBase>& OwnerTable ) { check(ItemProperty.IsValid()); TSharedPtr<ITableRow> NewRow = SNew(STableRow< TSharedPtr<FString> >, OwnerTable) .OnDragDetected(this, &SAkItemBoolProperties::HandleOnDragDetected) [ SNew(STextBlock) .Text(FText::FromString(*ItemProperty.Get())) .HighlightText(SearchBoxFilter.Get(), &StringFilter::GetRawFilterText) ]; return NewRow.ToSharedRef(); } FReply SAkItemBoolProperties::HandleOnDragDetected(const FGeometry& Geometry, const FPointerEvent& MouseEvent) { // Refresh the contents if(OnDragDetected.IsBound()) return OnDragDetected.Execute(Geometry,MouseEvent); return FReply::Unhandled(); } void SAkItemBoolProperties::PopulateSearchStrings( const FString& PropertyName, OUT TArray< FString >& OutSearchStrings ) const { OutSearchStrings.Add( PropertyName ); } void SAkItemBoolProperties::FilterUpdated() { FScopedSlowTask SlowTask(2.f, LOCTEXT("AK_PopulatingPicker", "Populating Properties Picker...")); SlowTask.MakeDialog(); PropertiesList.Empty(SAkItemBoolProperties_Helpers::FullBoolPropertiesListSize); FString FilterString = SearchBoxFilter->GetRawFilterText().ToString(); if (FilterString.IsEmpty()) { for (const auto& Property : SAkItemBoolProperties_Helpers::FullBoolPropertiesList) { PropertiesList.Add(MakeShareable(new FString(Property))); } } else { for (const auto& Property : SAkItemBoolProperties_Helpers::FullBoolPropertiesList) { if (Property.Contains(FilterString)) { PropertiesList.Add(MakeShareable(new FString(Property))); } } } ListViewPtr->RequestListRefresh(); } void SAkItemBoolProperties::ListSelectionChanged( TSharedPtr< FString > ItemProperty, ESelectInfo::Type /*SelectInfo*/ ) { if (OnSelectionChanged.IsBound()) OnSelectionChanged.Execute(ItemProperty, ESelectInfo::OnMouseClick); } const TArray<TSharedPtr<FString>> SAkItemBoolProperties::GetSelectedProperties() const { return ListViewPtr->GetSelectedItems(); } const FString SAkItemBoolProperties::GetSearchText() const { return SearchBoxFilter->GetRawFilterText().ToString(); } const void SAkItemBoolProperties::SetSearchText(const FString& newText) { SearchBoxPtr->SetText(FText::FromString(newText)); } EActiveTimerReturnType SAkItemBoolProperties::SetFocusPostConstruct(double InCurrentTime, float InDeltaTime) { FWidgetPath WidgetToFocusPath; FSlateApplication::Get().GeneratePathToWidgetUnchecked(SearchBoxPtr.ToSharedRef(), WidgetToFocusPath); FSlateApplication::Get().SetKeyboardFocus(WidgetToFocusPath, EFocusCause::SetDirectly); return EActiveTimerReturnType::Stop; } #undef LOCTEXT_NAMESPACE
24ad06fff20192603aeac14987cd894ced7dc173
f511554b0e1d08d4bf4f4837a9c464fc8dafee3f
/Dynamic_Programming/KS01.cpp
48d133a0df429ffb27b972b47bf7b0228fc7f748
[]
no_license
Subrat2196/Placement_CB
f0770415ddebc1a27474e3a6e9753c9662651154
04923eb5c9f114d920906f30b34125b7b65f7e5d
refs/heads/master
2023-06-17T13:27:03.843544
2021-07-04T12:48:28
2021-07-04T12:48:28
369,576,385
0
0
null
null
null
null
UTF-8
C++
false
false
581
cpp
KS01.cpp
#include <iostream> #include <climits> using namespace std; int KS01(int m,int n,int profit[],int wt[]) { //base case if(m==0||n==0) return 0; if(wt[n-1]>m) return KS01(m,n-1,profit,wt); else { int a=KS01(m-wt[n-1],n-1,profit,wt) + profit[n-1]; int b=KS01(m,n-1,profit,wt); int c=max(a,b); return c; } } int main() { //we need the capacity of the knapsack cout<<"Tell the capacity"<<endl; int m; cin>>m; int n=5; int profit[5]={25,70,50,10,60}; int wt[5]={5,3,2,4,5}; int maxProfit=KS01(m,n,profit,wt); cout<<maxProfit<<endl; return 0; }
871f3152b2ca01ea1b5430491da36d1297121eac
fa04d2f56c8d4ebfb931968392811a127a4cb46c
/trunk/Cities3D/src/UICore/ChatWindow.h
da0b1a249a085b68ed12a35f8dc15a03f71c56ff
[]
no_license
andrewlangemann/Cities3D
9ea8b04eb8ec43d05145e0b91d1c542fa3163ab3
58c6510f609a0c8ef801c77f5be9ea622e338f9a
refs/heads/master
2022-10-04T10:44:51.565770
2020-06-03T23:44:07
2020-06-03T23:44:07
268,979,591
0
0
null
2020-06-03T03:25:54
2020-06-03T03:25:53
null
UTF-8
C++
false
false
4,287
h
ChatWindow.h
/* * Cities3D - Copyright (C) 2001-2009 Jason Fugate (saladyears@gmail.com) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. */ #pragma once #include "style.h" //READ THIS BEFORE MAKING ANY CHANGES TO THIS FILE!!! //---------------------------- SYSTEM INCLUDES -----------------------------// //---------------------------- USER INCLUDES -----------------------------// #include "DataObject.h" #include "UIExport.h" //---------------------------- DEFINES -----------------------------// //---------------------------- TYPEDEFS -----------------------------// class wxHtmlWindowEx; class wxChatInputTextCtrl; //---------------------------- CLASSES -----------------------------// //---------------------------------------------------------------------------// // Class: wxChatWindow // // The network chat window. Contains two sub windows, one that displays the // chat log, the other which allows chat text entry. // // Derived From: // <wxWindow> // // Project: // <UICore> // // Include: // ChatWindow.h // class UI_EXPORT_SPEC wxChatWindow : public wxWindow { //-----------------------------------------------------------------------// // Section: Public // public: //-----------------------------------------------------------------------// // Group: Constructors // //-----------------------------------------------------------------------// // Constructor: wxChatWindow // // The wxChatWindow constructor. // // Parameters: // parent - The parent window. Must not be NULL. // id - The window id. // entry - Whether the chat window should have a text entry control. // pos - The starting window position. // size - The starting window size. // wxChatWindow(wxWindow* parent, wxWindowID id, const bool entry = true, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize); //-----------------------------------------------------------------------// // Group: Destructor // //-----------------------------------------------------------------------// // Destructor: ~wxChatWindow // // The wxChatWindow destructor. // virtual ~wxChatWindow(); //-----------------------------------------------------------------------// // Group: Variables // //-----------------------------------------------------------------------// // Macro: DECLARE_EVENT_TABLE // // The wxWidgets event table declaration. // DECLARE_EVENT_TABLE() //-----------------------------------------------------------------------// // Section: Private // private: //-----------------------------------------------------------------------// // Group: Game Event Functions // //-----------------------------------------------------------------------// // Function: OnChatMessage // // Handles an incoming chat message. // // Parameters: // object - The chat message to display. // void OnChatMessage(const DataObject &object); //-----------------------------------------------------------------------// // Group: Event Message Handling // //-----------------------------------------------------------------------// // Function: OnSize // // Resizes the window. // // Parameters: // event - The size event. // void OnSize(wxSizeEvent& event); //-----------------------------------------------------------------------// // Group: Variables // //-----------------------------------------------------------------------// // Pointer: mpHtmlWindow // // The HTML chat window. // wxHtmlWindowEx *mpHtmlWindow; //-----------------------------------------------------------------------// // Pointer: mpInputText // // The chat entry window. // wxChatInputTextCtrl *mpInputText; }; //---------------------------- PROTOTYPES -----------------------------//
0c0ccdbfba0e84ff09a366c23862f530b0ab9544
5aa4d7c5815346144a4654f807bded1dd12b6e0b
/src/Probe/Hardware.cpp
b6e0e4657a742bab4291d2c609d427b2c6fb4ebd
[]
no_license
janemxq/Scope
dce82f192750da730ccf52f294e6b0d03e050ade
c3cdda7ec5246fea3380fd879aa4e8db3dca9fbe
refs/heads/master
2023-03-29T03:57:04.330659
2017-03-18T11:02:27
2017-03-18T11:02:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
364
cpp
Hardware.cpp
#include "Hardware.h" void hardware_init() { // Initialize outputs. pinMode(DO_BEEPER, OUTPUT); // Setup fast ADC. bitSet(ADCSRA, ADPS2); bitClear(ADCSRA, ADPS1); bitClear(ADCSRA, ADPS0); } void beep(uint8_t times) { while (times > 0) { digitalWrite(DO_BEEPER, HIGH); delay(1); digitalWrite(DO_BEEPER, LOW); if (--times > 0) delay(100); } }
5306a0f7e010b8a1b39fc313e58f7178fb9bc9f3
95f8132db29d4ad024df35f2a3220dc0aa881d39
/LinkedList/doublyLLandImpl.cpp
bbfe0bf37186c93af09d372645dc005aad52e088
[]
no_license
jakaria9001/20DaysOfDS
c42b8e7e01a7b8c7edb9c2ee6924d8098984b5dc
764b19c0fa604510e3ecc3ee1b115c7efa530f6c
refs/heads/main
2023-03-31T21:33:59.297245
2021-04-13T19:15:05
2021-04-13T19:15:05
354,094,219
0
0
null
null
null
null
UTF-8
C++
false
false
1,624
cpp
doublyLLandImpl.cpp
#include <bits/stdc++.h> using namespace std; struct Node{ int data; Node *next; Node *prev; Node(int x) : data(x) , next(NULL) , prev(NULL) {} }; // advantages: reverse lookup; // disadvantage: extra memory for prev node; Node *insertAtBeg(Node *head, int x){ Node *newnode = new Node(x); if(!head) return newnode; newnode->next = head; head->prev = newnode; head = newnode; return head; } Node *insertAtEnd(Node *head, int x){ Node *newnode = new Node(x); if(!head) return newnode; Node *temp = head; while(temp->next) temp = temp->next; temp->next = newnode; newnode->prev = temp; return head; } void printLL(Node *head){ if(!head){ cout<<"Empty List\n"; return; } while(head){ cout<<head->data<<" "; head = head->next; } } void reversePrint(Node *head){ if(!head){ // cout<<"Empty List\n"; return; } // recursive : reversePrint(head->next); cout<<head->data; // iterative : /* Node *temp = head; while(temp->next) temp = temp->next; while(temp){ cout<<temp->data<<" "; temp = temp->prev; } */ } int main(){ cout<<"Enter no of operations: "; int n; cin>>n; int x,ch; Node *head = NULL; while(n--){ cout<<"\nEnter value : "; cin>>x; cout<<"\n1. insertAtBeg, 2. insertAtEnd : "; cin>>ch; if(ch==1) head = insertAtBeg(head, x); else head = insertAtEnd(head, x); cout<<"Current List: " printLL(head); } }
659ca635214f54d8f83320728a572fe7379408eb
f7d4abf7da3af463f48b9d3f690671007513cc38
/quadcopter_test/src/main.cpp
10e67f95f64a096772a80f037291cd4bee0729fc
[]
no_license
chicagoedt/iarc_mission7
12314eee7fe029b1093c292b4f0c03b204cfd9bc
1a14b198591a820eedea9974431c3040a1cda854
refs/heads/master
2021-09-07T11:15:48.606887
2018-02-22T05:12:58
2018-02-22T05:12:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,815
cpp
main.cpp
#include "flight_test.h" int main(int argc, char **argv) { ros::init(argc, argv, "talker"); flight fl; fl.run(); /* ros::Publisher pub = n.advertise<geometry_msgs::Twist>("cmd_vel", 1); ros::Subscriber sub= n.subscribe("ground_truth_to_tf/pose", 1, callback); ros::Rate loop_rate(1); geometry_msgs::Twist msg; /* ros::Time begin = ros::Time::now(); while(ros::Time::now()-begin<5.0) { msg.linear.z = 2.0; // +1.0 m/s Z (upward) velocity ROS_INFO_STREAM("Z velocity is: " << msg.linear.z ); pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); } ros::Time begin = ros::Time::now(); while(ros::Time::now()-begin<5.0) { msg.linear.z = 0.0; // +1.0 m/s Z (upward) velocity msg.linear.x = 2.0; ROS_INFO_STREAM("X velocity is: " << msg.linear.x ); pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); } */ /* for(int i=0; i<=12;++i) {msg.linear.z = 2.0; ROS_INFO_STREAM("Z velocity is: " << msg.linear.z ); pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); } for(int i=0; i<=5;++i) {msg.linear.z = 0; msg.linear.x = 1.0; pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); } for(int i=0; i<=5; ++i) {msg.linear.z=-2.0; msg.linear.x=0.0; pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); } for(int i=0; i<=5; ++i) {msg.linear.z = 0.0; msg.linear.x = -1.0; pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); } for(int i=0; i<=7;++i) { msg.linear.z = -2.0; msg.linear.x = 0.0; ROS_INFO_STREAM("Z velocity is: " << msg.linear.z ); pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); } msg.linear.z = 0.0; msg.angular.z = 0.0; msg.linear.x = 0.0; pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); */ return 0; }
9f146e02b158022486193bb0a6103bca5962952a
239091e0ea1412e76e29c43acdfb969bc6a5f1dc
/OpenPass_Source_Code/openPASS/Components_PCM/Sensor_Collision/sensor_collision_implementation.cpp
da97817e28a5398f81843e92bb75e47c8b832c5a
[]
no_license
hlrs-vis/openpass
080a2625d6427ffff835bdc122954df8d022f382
7375cb9cd5bd77c8aad5094766169ddb225c7f13
refs/heads/master
2021-05-15T14:00:49.331352
2019-11-05T14:20:55
2019-11-05T14:20:55
107,249,522
4
1
null
null
null
null
UTF-8
C++
false
false
5,856
cpp
sensor_collision_implementation.cpp
/******************************************************************************* * Copyright (c) 2019 in-tech GmbH * 2017, 2018 ITK Engineering GmbH * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ #include <memory> #include <qglobal.h> #include "sensor_collision_implementation.h" Sensor_Collision_Implementation::Sensor_Collision_Implementation(int componentId, bool isInit, int priority, int offsetTime, int responseTime, int cycleTime, StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, const std::map<int, ObservationInterface *> *observations, const CallbackInterface *callbacks, AgentInterface *agent) : SensorInterface(componentId, isInit, priority, offsetTime, responseTime, cycleTime, stochastics, world, parameters, observations, callbacks, agent) { try { std::map<int, int> parameterMapIntExternal = GetParameters()->GetParametersInt(); foreach (auto &iterator, parameterMapInt) { int id = iterator.first; parameterMapInt.at(id)->SetValue(parameterMapIntExternal.at(id)); } } catch (...) { const std::string msg = COMPONENTNAME + " could not init parameters"; LOG(CbkLogLevel::Error, msg); throw std::runtime_error(msg); } } Sensor_Collision_Implementation::~Sensor_Collision_Implementation() { } void Sensor_Collision_Implementation::UpdateInput(int localLinkId, const std::shared_ptr<SignalInterface const> &data, int time) { // no input necessary Q_UNUSED(localLinkId); Q_UNUSED(data); Q_UNUSED(time); std::runtime_error("invalid link"); } void Sensor_Collision_Implementation::UpdateOutput(int localLinkId, std::shared_ptr<SignalInterface const> &data, int time) { Q_UNUSED(time); std::stringstream log; log << COMPONENTNAME << " UpdateOutput"; LOG(CbkLogLevel::Debug, log.str()); log.str(std::string()); bool success = outputPorts.at(localLinkId)->GetSignalValue(data); if (success) { log << COMPONENTNAME << " UpdateOutput successful"; LOG(CbkLogLevel::Debug, log.str()); } else { log << COMPONENTNAME << " UpdateOutput failed"; LOG(CbkLogLevel::Error, log.str()); } } void Sensor_Collision_Implementation::Trigger(int time) { std::vector<int> collisionPartners = GetAgent()->GetCollisionPartners(); size_t numberOfCollisionData = 0; for (size_t i = 0; i < collisionPartners.size(); i++) { std::vector<void *> collisionData = GetAgent()->GetCollisionData(collisionPartners.at(i), POSTCRASHDYNAMICID); numberOfCollisionData += collisionData.size(); } CollisionState nextState = CollisionState::NOCOLLISION; switch (collisionState) { case CollisionState::NOCOLLISION: if (previousNumberOfCollisionData == numberOfCollisionData) { nextState = CollisionState::NOCOLLISION; } else { if (penetrationTime.GetValue() < GetCycleTime()) { nextState = CollisionState::COLLISION; } else { timeOfFirstCollision = time; nextState = CollisionState::COLLISIONPENETRATING; } } break; case CollisionState::COLLISIONPENETRATING: if (((time - timeOfFirstCollision) < (penetrationTime.GetValue() - GetCycleTime())) // collision penetration time is not over && (previousNumberOfCollisionData != numberOfCollisionData)) // collision is still happening { nextState = CollisionState::COLLISIONPENETRATING; } else { nextState = CollisionState::COLLISION; } break; case CollisionState::COLLISION: if (previousNumberOfCollisionData == numberOfCollisionData) { nextState = CollisionState::NOCOLLISION; } else { nextState = CollisionState::COLLISION; } break; } switch (nextState) { case CollisionState::NOCOLLISION: case CollisionState::COLLISIONPENETRATING: collisionOccured.SetValue(false); GetAgent()->SetCollisionState(false); break; case CollisionState::COLLISION: collisionOccured.SetValue(true); GetAgent()->SetCollisionState(true); break; } collisionState = nextState; previousNumberOfCollisionData = numberOfCollisionData; }
370c89a33192991e2a81f05d3a0a9aae0c8e2eed
7c3da5fec7f36ce8c82879ed8df6f22d3521011e
/controller/dloginwarningdialog.h
ec697214bf4e99edfeae68e083d6f0af34b6189a
[]
no_license
xiaoduge/controller_Code
000c20e38369173516b002833aa326aae2ce6ebe
26e9f933d2dfbb556a611eed1d6c7f1748735260
refs/heads/master
2022-03-25T00:45:44.834280
2019-12-03T05:41:19
2019-12-03T05:41:19
166,188,535
1
0
null
null
null
null
UTF-8
C++
false
false
995
h
dloginwarningdialog.h
#ifndef DLOGINWARNINGDIALOG_H #define DLOGINWARNINGDIALOG_H #include <QDialog> class QLabel; class QVBoxLayout; class QPushButton; class DLoginWarningDialog : public QDialog { Q_OBJECT private: explicit DLoginWarningDialog(QWidget *parent = 0); DLoginWarningDialog(const DLoginWarningDialog &obj); DLoginWarningDialog& operator =(const DLoginWarningDialog &obj); public: static void getInstance(QString strText); ~DLoginWarningDialog(); protected slots: void on_closeBtn_clicked(); void on_timer_event(); void mousePressEvent(QMouseEvent* event); void mouseMoveEvent(QMouseEvent* event); private: void setInfo(QString strText); void start(); void deleteInstance(); private: QLabel *m_pLbInfo; QVBoxLayout *m_pBottomLayout; QTimer* m_timer; QPushButton* m_pColoseBtn; QPoint m_offsetPoint; static DLoginWarningDialog *instance; }; #endif // DLOGINWARNINGDIALOG_H
a150c446b9a6178598b2aa6ab0b0409fa5bbca93
4db59c173b73c45559331ed90476fc13dbde735d
/Codes/ConWMWater2.cpp
234221b8f51177550371e561d47eaaa0cb17cba1
[]
no_license
36V3mA21Hz/LeetCodePractice
3410c2bd9483d16bba5899255aa0c64e0c437d1b
1c39d99e0206483d945ed23c577afe8d2859ecd6
refs/heads/master
2021-01-18T19:21:52.316991
2015-04-03T01:51:00
2015-04-03T01:51:00
15,559,534
0
0
null
null
null
null
UTF-8
C++
false
false
1,015
cpp
ConWMWater2.cpp
class Solution { public: int maxArea(vector<int> &height) { if (height.empty()) return 0; int n = (int)height.size(); int max = 0, mL = height[0], mH = height[0], iL = 0, iH = 0; for (int i = 1; i < n; i++) { int ai = height[i]; int m1 = min(ai, mL) * (i - iL); int m2 = min(ai, mH) * (i - iH); if (m1 > max || m2 > max) { if (m1 >= m2) { max = m1; if (ai < mL) { mH = mL, iH = iL; mL = ai, iL = i; } else { mH = ai, iH = i; } } else { max = m2; if (ai < mH) { mL = ai, iL = i; } else { mL = mH, iL = iH; mH = ai, iH = i; } } } } return max; } };
c6454aacdb396d1ddefc4755acc059540428fbe1
79eb737b20cfd332c84d5a6926365868f94ebdad
/include/yarp/os/impl/RunCheckpoints.h
229c0fec8a013ba7bea7419d142e59efec302c1b
[]
no_license
johnty/libYARP_OS_iOS
70d6555d8e0bc05b7feaa8711fca6efe9277e16c
65bc7bf382e3de1004acff408b110808da3ff9c0
refs/heads/master
2020-08-26T20:08:47.955399
2014-02-12T01:02:00
2014-02-12T01:02:00
16,746,103
1
0
null
null
null
null
UTF-8
C++
false
false
1,386
h
RunCheckpoints.h
// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /* * Copyright (C) 2007-2009 RobotCub Consortium * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * author Alessandro Scalzo alessandro.scalzo@iit.it */ #ifndef __YARPRUN_RUN_CHECKPOINTS__ #define __YARPRUN_RUN_CHECKPOINTS__ #include <string> #include <list> class YarprunCheckpoints // singleton { private: YarprunCheckpoints(); public: ~YarprunCheckpoints(); static YarprunCheckpoints& instance(); void checkpoint(const char* prefix,const char* label,const char* sFile,int line); private: FILE* mLogFile; }; #ifdef YARPRUN_LOG #define _BEGIN YarprunCheckpoints::instance().checkpoint("BEGIN",__FUNCTION__,__FILE__,__LINE__); #define _CHECKPOINT YarprunCheckpoints::instance().checkpoint(" ",__FUNCTION__,__FILE__,__LINE__); #define _RETURN(val) { YarprunCheckpoints::instance().checkpoint("END ",__FUNCTION__,__FILE__,__LINE__); return val; } #define _RETURN_VOID { YarprunCheckpoints::instance().checkpoint("END ",__FUNCTION__,__FILE__,__LINE__); return; } #define _EXIT(val) { YarprunCheckpoints::instance().checkpoint("END ",__FUNCTION__,__FILE__,__LINE__); exit(val); } #else #define _BEGIN #define _CHECKPOINT #define _RETURN(val) return val; #define _RETURN_VOID return; #define _EXIT(val) exit(val); #endif #endif
83c90498d409d2169ad294c31c1c81727db0091c
05ca2db4e7b0a2be23f3e2e35244c1fb500f482e
/(2019.12.31) 628. Maximum Product of Three Numbers/kai.cpp
51bb8005b7bfef0fcdc0089df270d12f509567a7
[]
no_license
William1Wu/Leetcode-Practice
2d8cc370260706b257c0a31c4cd4659e965015f7
fdb80f23eacdd52d6cda24c4511d23bfa5f8c932
refs/heads/master
2020-09-16T19:11:15.495132
2020-02-08T14:07:52
2020-02-08T14:07:52
223,863,342
0
2
null
null
null
null
UTF-8
C++
false
false
295
cpp
kai.cpp
class Solution { public: int maximumProduct(vector<int>& nums) { sort(nums.begin(), nums.end()); int right = nums[nums.size()-3]*nums[nums.size()-2]*nums[nums.size()-1]; int left = nums[0]*nums[1]*nums[nums.size()-1]; return max(right, left); } };
2a4d631973a957d3366ec97b4544f3f0bc8207db
fcae25b75fbb83de18bb6dd46a50d7a1eb8f396c
/HistogramMerger.cpp
270bc70576864afb8d91280bb960be2d52e40d3f
[]
no_license
joe-singh/ringFitterSystematics
9d649c7b891a5229fb7b8aa23156e36da9fc61cc
87e374a4383448ca964214722f9d87579d6fafb3
refs/heads/master
2020-12-02T11:05:45.690310
2017-08-14T02:15:51
2017-08-14T02:15:51
96,599,101
0
1
null
2017-07-24T16:37:44
2017-07-08T05:52:27
C++
UTF-8
C++
false
false
11,776
cpp
HistogramMerger.cpp
/** @class HistogramMerger * Takes a nominal, lower, and upper file and * merges the histograms as appropriate, changing errors * where needed. * @authors Jyotirmai Singh, Max Smiley */ #include <cmath> #include "HistogramMerger.h" #include "HistogramMaker.h" HistogramMerger::HistogramMerger(TFile* nomFile, TFile* upFile, TFile* lowFile, TFile* outFile, bool useData) { _nomFile = nomFile; _upFile = upFile; _lowFile = lowFile; _outFile = outFile; _data = useData; } /** Applies bin error correction to a nominal histogram, changing its bin errors * to abs(upperError - lowerError). If this quantity is 0, we don't change the * bin error since the SetBinError function behaves strangely when the error is * 0 and the error bars are not drawn properly. * @param nominal The nominal histogram whose errors are changed. * @param upper The histogram resulting from applying upper systematics. * @param lower The histogram resulting from applying lower systematics. */ void HistogramMerger::applyBinErrorCorrection(TH1F* nominal, TH1F* upper, TH1F* lower) { int nBins = nominal->GetSize(); for (int i = 0; i < nBins; i++) { double upperErr = upper->GetBinContent(i); double lowerErr = lower->GetBinContent(i); double error = fabs(upperErr - lowerErr); if (error == 0.0) { continue; } nominal->SetBinError(i, error); } } /** Overlays nominal with statistical and systematic errors. * @param nominal The nominal histogram to be overlaid. * @param upper The histogram resulting from applying upper systematics. * @param lower The histogram resulting from applying lower systematics. * @param canv The canvas on which the overlaid nominal plots are drawn. */ void HistogramMerger::mergeHistograms(TH1F* nominal, TH1F* upper, TH1F* lower, TCanvas* canv) { TCanvas* canvas = canv; TH1F* clonedHisto = nominal->Clone(); clonedHisto->Draw("e1"); this->applyBinErrorCorrection(nominal, upper, lower); nominal->SetFillColor(kRed); nominal->SetFillStyle(3001); nominal->Draw("e2 same"); canv->Update(); } /** Overlays nominal with statistical and systematic errors. Specialised * for mean histograms where a division by a norm histogram is required. * Performs division by norm first and then calls mergeHistograms. * @param nominal The nominal histogram to be overlaid. * @param upper The histogram resulting from applying upper systematics. * @param lower The histogram resulting from applying lower systematics. * @param nominalNorm What nominal is divided by. * @param upperNorm What upper is divided by. * @param lowerNorm What lower is divided by. * @param canv The canvas on which the overlaid nominal plots are drawn. */ void HistogramMerger::mergeNormDivisionHistograms(TH1F* nominal, TH1F* upper, TH1F* lower, TH1F* nominalNorm, TH1F* upperNorm, TH1F* lowerNorm, TCanvas* canv) { nominal->Sumw2(); nominalNorm->Sumw2(); upper->Sumw2(); upperNorm->Sumw2(); lower->Sumw2(); lowerNorm->Sumw2(); nominal->Divide(nominalNorm); upper->Divide(upperNorm); lower->Divide(lowerNorm); this->mergeHistograms(nominal, upper, lower, canv); } void HistogramMerger::plotPromptHistogram(TH1F* nominal, TH1F* upper, TH1F* lower, TCanvas* canv) { if (_data) { TCanvas* c = canv; nominal->Draw("e1"); } else { this->mergeHistograms(nominal, upper, lower, canv); } } void HistogramMerger::plotMeanFollowerHistogram(TH1F *nominal, TH1F *upper, TH1F *lower, TH1F *nominalNorm, TH1F *upperNorm, TH1F *lowerNorm, TCanvas *canv) { if (_data) { TCanvas* c = canv; nominal->Sumw2(); nominalNorm->Sumw2(); nominal->Divide(nominalNorm); nominal->Draw("e1"); } else { this->mergeNormDivisionHistograms(nominal, upper, lower, nominalNorm, upperNorm, lowerNorm, canv); } } /** Main method, makes all histograms and draws them on * canvases. Saves canvases to _outFile for later access. Applies * merging of histograms when necessary. */ void HistogramMerger::makeHistograms() { HistogramMaker* histsNominal = new HistogramMaker(_nomFile); HistogramMaker* histsUpper = new HistogramMaker(_upFile); HistogramMaker* histsLower = new HistogramMaker(_lowFile); TCanvas* cfitpos = new TCanvas("cfitpos", "Fitted Position for Prompt", 1600, 800); cfitpos->Divide(3,2); cfitpos->cd(1); histsNominal->hfitpos[0]->Draw(); cfitpos->cd(2); histsNominal->hfitpos[1]->Draw(); cfitpos->cd(3); histsNominal->hfitpos[2]->Draw(); cfitpos->cd(4); histsNominal->hfitposdiff[0]->Draw(); cfitpos->cd(5); histsNominal->hfitposdiff[1]->Draw(); cfitpos->cd(6); histsNominal->hfitposdiff[2]->Draw(); TCanvas* cseedpos = new TCanvas("cseedpos", "Seed Position for Prompt", 1600, 800); cseedpos->Divide(3,2); cseedpos->cd(1); histsNominal->hseedpos[0]->Draw(); cseedpos->cd(2); histsNominal->hseedpos[1]->Draw(); cseedpos->cd(3); histsNominal->hseedpos[2]->Draw(); cseedpos->cd(4); histsNominal->hseedposdiff[0]->Draw(); cseedpos->cd(5); histsNominal->hseedposdiff[1]->Draw(); cseedpos->cd(6); histsNominal->hseedposdiff[2]->Draw(); TCanvas* cprompt = new TCanvas("cprompt","Prompt Distributions", 1600, 800); cprompt->Divide(3,2); cprompt->cd(1); histsNominal->hprompt_nhits->Draw("e1"); cprompt->cd(2); histsNominal->hprompt_nrings->Draw("e1"); cprompt->cd(3); histsNominal->hprompt_pid->Draw("e1"); cprompt->cd(4); plotPromptHistogram(histsNominal->hprompt_eeffenergy, histsUpper->hprompt_eeffenergy, histsLower->hprompt_eeffenergy, cprompt); cprompt->cd(5); plotPromptHistogram(histsNominal->hprompt_ueffenergy, histsUpper->hprompt_ueffenergy, histsLower->hprompt_ueffenergy, cprompt); cprompt->cd(6); plotPromptHistogram(histsNominal->hprompt_meffenergy, histsUpper->hprompt_meffenergy, histsLower->hprompt_meffenergy, cprompt); cprompt->Update(); TCanvas* cmichele = new TCanvas("cmichele","Michel-e Distributions",900,600); cmichele->Divide(3,2); cmichele->cd(1); histsNominal->hmichele_nhits->Draw("e1"); cmichele->cd(2); histsNominal->hmichele_deltat->Draw("e1"); cmichele->cd(4); histsNominal->hmichele_energy0->Draw("e1"); cmichele->cd(5); histsNominal->hmichele_energy1->Draw("e1"); cmichele->cd(6); histsNominal->hmichele_energy2->Draw("e1"); TCanvas* cfollowers = new TCanvas("cfollowers","Neutron Followers Distributions",1200,600); cfollowers->Divide(4,2); cfollowers->cd(1); histsNominal->hfollowers_nhits->Draw("e1"); cfollowers->cd(2); histsNominal->hfollowers_energy0->Draw("e1"); cfollowers->cd(3); histsNominal->hfollowers_deltat->Draw("e1"); cfollowers->cd(4); histsNominal->hfollowers_dist->Draw("e1"); cfollowers->cd(5); histsNominal->hfollowers_energy0->Draw("e1"); cfollowers->cd(6); histsNominal->hfollowers_energy1->Draw("e1"); cfollowers->cd(7); histsNominal->hfollowers_energy2->Draw("e1"); TCanvas* cnfollow = new TCanvas("cnfollow","Number of Followers",900,300); cnfollow->Divide(3,1); cnfollow->cd(1); histsNominal->nfollowers_tot->Draw("e1"); cnfollow->cd(2); histsNominal->nfollowers_sring->Draw("e1"); cnfollow->cd(3); histsNominal->nfollowers_mring->Draw("e1"); TCanvas* cnhit_nofollow = new TCanvas("cnhit_nofollow","NHit for Prompt Events with NO Followers",900,300); cnhit_nofollow->Divide(3,1); cnhit_nofollow->cd(1); histsNominal->nhit_nofollow_tot->Draw("e1"); cnhit_nofollow->cd(2); histsNominal->nhit_nofollow_sring->Draw("e1"); cnhit_nofollow->cd(3); histsNominal->nhit_nofollow_mring->Draw("e1"); TCanvas* cnfollowmean_eeffenergy = new TCanvas("cnfollowmean_eeffenergy","Number of Followers vs Prompt Energy",700,900); gStyle->SetPalette(56); cnfollowmean_eeffenergy->Divide(2,3); cnfollowmean_eeffenergy->cd(1); cnfollowmean_eeffenergy->cd(1)->SetLogx(); this->plotMeanFollowerHistogram(histsNominal->nfollowersmean_eeffenergy, histsUpper->nfollowersmean_eeffenergy, histsLower->nfollowersmean_eeffenergy, histsNominal->nfollowersmean_eeffenergy_norm, histsUpper->nfollowersmean_eeffenergy_norm, histsLower->nfollowersmean_eeffenergy_norm, cnfollowmean_eeffenergy); cnfollowmean_eeffenergy->cd(2); cnfollowmean_eeffenergy->cd(2)->SetLogx(); histsNominal->nfollowers_eeffenergy->Draw("colz"); cnfollowmean_eeffenergy->cd(3); cnfollowmean_eeffenergy->cd(3)->SetLogx(); this->plotMeanFollowerHistogram(histsNominal->nfollowersmean_sr_eeffenergy, histsUpper->nfollowersmean_sr_eeffenergy, histsLower->nfollowersmean_sr_eeffenergy, histsNominal->nfollowersmean_sr_eeffenergy_norm, histsUpper->nfollowersmean_sr_eeffenergy_norm, histsLower->nfollowersmean_sr_eeffenergy_norm, cnfollowmean_eeffenergy); cnfollowmean_eeffenergy->cd(4); cnfollowmean_eeffenergy->cd(4)->SetLogx(); histsNominal->nfollowers_sr_eeffenergy->Draw("colz"); cnfollowmean_eeffenergy->cd(5); cnfollowmean_eeffenergy->cd(5)->SetLogx(); this->plotMeanFollowerHistogram(histsNominal->nfollowersmean_mr_eeffenergy, histsUpper->nfollowersmean_mr_eeffenergy, histsLower->nfollowersmean_mr_eeffenergy, histsNominal->nfollowersmean_mr_eeffenergy_norm, histsUpper->nfollowersmean_mr_eeffenergy_norm, histsLower->nfollowersmean_mr_eeffenergy_norm, cnfollowmean_eeffenergy); cnfollowmean_eeffenergy->cd(6); cnfollowmean_eeffenergy->cd(6)->SetLogx(); histsNominal->nfollowers_mr_eeffenergy->Draw("colz"); TCanvas* neutron_efficiency = new TCanvas("neutronEfficiency", "Neutron Efficiency", 1000, 600); histsNominal->nfollowers_radial->Sumw2(); histsNominal->nfollowers_detected_radial->Sumw2(); histsNominal->nfollowers_detected_radial->Divide(histsNominal->nfollowers_radial); histsNominal->nfollowers_detected_radial->Draw("e1"); _outFile->WriteTObject(cfitpos); _outFile->WriteTObject(cseedpos); _outFile->WriteTObject(cprompt); _outFile->WriteTObject(cmichele); _outFile->WriteTObject(cfollowers); _outFile->WriteTObject(cnfollow); _outFile->WriteTObject(cnhit_nofollow); _outFile->WriteTObject(cnfollowmean_eeffenergy); _outFile->WriteTObject(neutron_efficiency); // Write histograms to output file for later use - i.e. superimposing data and MC histsNominal->writeAllToFileVec(_outFile); histsUpper->removeAll(); histsLower->removeAll(); _outFile->Close(); }
2e9152642f95edc909ea5419262e672c4c065d61
caec6295097544335ad3a269ba5274a4c048e11d
/WpnAutoFire.h
66516cf0e9241c0c38b31ab6405bddcfa196cba3
[]
no_license
henningerlandsen/SpaceShooterConsole
66816ca4ab062a0ae2f2827868da1fb68202651c
1f6645b0d56d3bb28cc72146547acbe288b44da1
refs/heads/master
2020-04-17T22:54:40.702547
2014-03-03T10:24:11
2014-03-03T10:24:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,749
h
WpnAutoFire.h
#pragma once #include "Weapon.h" class WpnAutoFire : public Weapon { float _pHeight; float _pWidth; int _counter; void resetProjectile(Projectile &p); // Resets a projectile to initial state. public: WpnAutoFire(DrawingAssistant *drw, Vector2d* position, bool *fireControl); ~WpnAutoFire(); void draw(); void move(); void deployProjectile(); }; WpnAutoFire::WpnAutoFire(DrawingAssistant *drw, Vector2d *position, bool *fireControl) : Weapon(drw, position, fireControl) { _energySurge = 5; _pHeight = 0.05; _pWidth = 0.05; _autoFire = true; _refireRate = 5; _counter = 0; for(int i=0; i<MAX_PROJECTILES; i++) { resetProjectile(_projectiles[i]); } } WpnAutoFire::~WpnAutoFire() {} // -------------------------------- Constructor & Destructor // // Private member-functions -------------------------------- // void WpnAutoFire::resetProjectile(Weapon::Projectile &p) { p.active = false; p.dir = Vector2d(0, 1); p.pos = Vector2d(); p.speed = 0.07; } // -------------------------------- Private member-functions // // Public member-functions --------------------------------- // void WpnAutoFire::draw() { _drw->setTexture(DrawingAssistant::T_PARTICLE); glBlendFunc(GL_SRC_ALPHA, GL_ONE); glDepthFunc(GL_ALWAYS); for(int i=0; i<MAX_PROJECTILES; i++) { if(_projectiles[i].active) { for(int j=0; j<10; j++) { float factor = j/10.0; glColor4f(0.5, 0.7, 1.0, 1.0-factor); _drw->drawTextured2dQuadCenter(_projectiles[i].pos._x, _projectiles[i].pos._y - factor*0.3, _pWidth*(1-factor), _pHeight*(1-factor)); } /*glColor4f(0.0, 0.7, 1.0, 1.0); _drw->drawTextured2dQuadCenter(_projectiles[i].pos._x, _projectiles[i].pos._y, _pWidth, _pHeight); glColor4f(0.0, 0.7, 1.0, .8); _drw->drawTextured2dQuadCenter(_projectiles[i].pos._x, _projectiles[i].pos._y-0.03, _pWidth/1.2, _pHeight/1.2); glColor4f(0.0, 0.7, 1.0, .6); _drw->drawTextured2dQuadCenter(_projectiles[i].pos._x, _projectiles[i].pos._y-0.06, _pWidth/1.5, _pHeight/1.5); glColor4f(0.0, 0.7, 1.0, .4); _drw->drawTextured2dQuadCenter(_projectiles[i].pos._x, _projectiles[i].pos._y-0.09, _pWidth/1.7, _pHeight/1.7); glColor4f(0.0, 0.7, 1.0, .2); _drw->drawTextured2dQuadCenter(_projectiles[i].pos._x, _projectiles[i].pos._y-0.11, _pWidth/2, _pHeight/2);*/ } } glDepthFunc(GL_LEQUAL); } void WpnAutoFire::deployProjectile() { _counter = 0; } void WpnAutoFire::move() { cout << *_fireControl << endl; if(*_fireControl && _counter%_refireRate == 0) { _launchOffset = Vector2d(-0.05, 0.02); Weapon::deployProjectile(); _launchOffset = Vector2d(0.05, 0.02); Weapon::deployProjectile(); } _counter++; Weapon::move(); } // --------------------------------- Public member-functions //
fed9b5ec502047cbc0d461f14c8fb6fa4f47019a
bbe049dba23a04d9f48359ecedd2b4d682960027
/todoitem.cpp
ac8fef590254ecfce15c17da85dead539599f680
[]
no_license
orgnnice/OrgNNice
f6e3e2e83fe621ff397986f29abc6c56af4bf309
81f318deb46c7c04dc110f901d42bf1c88da377e
refs/heads/master
2021-01-10T06:03:30.075540
2016-03-29T11:25:44
2016-03-29T11:25:44
45,345,710
4
0
null
null
null
null
UTF-8
C++
false
false
2,122
cpp
todoitem.cpp
#include "todoitem.h" #include <dbhandler.h> #include "main.h" ToDoItem::ToDoItem() { } /** * @brief ToDoItem::ToDoItem * @param fach_name * @param beschreibung * @param deadline * @param done */ ToDoItem::ToDoItem(QString subject_name, QString description, QDateTime deadline, bool done) { this->subject_id = pDBh->select("pk_id", "SchoolSubject", "name='" + subject_name + "'").replace('"', "").toInt(); this->description = description; this->deadline = deadline; this->done = done; qDebug() << "DBHandler::insertTODOandReturnId" << this->toString(); this->id = pDBh->insertTODOandReturnId(*this); } /** * @brief ToDoItem::ToDoItem to be called by DBHandler to select Todos from the database * @param subject_id * @param description * @param deadline * @param done */ ToDoItem::ToDoItem(int id, QString description, QDateTime deadline, bool done, int subject_id) { this->subject_id = subject_id; this->description = description; this->deadline = deadline; this->done = done; this->id = id; } void ToDoItem::updateToDoItem() { pDBh->updateTODO(*this); } void ToDoItem::deleteToDoItem() { pDBh->deleteToDo(*this); } void ToDoItem::setSubjectID(int id) { this->subject_id = id; } QString ToDoItem::toString() { QString result = "TODO: "; result += this->description + " | Deadline: " + this->deadline.toString() + " | Done: " + QString::number((this->getDone() > 0 ? 1 : 0)) + " | Fachname: " + QString::number(this->subject_id) + " | ID: " + QString::number(this->id); return result; } int ToDoItem::getID() { return this->id; } int ToDoItem::getSubjectID() { return this->subject_id; } bool ToDoItem::getDone() { return this->done; } QString ToDoItem::getDescription() { return this->description; } QDateTime ToDoItem::getDeadline() { return this->deadline; } void ToDoItem::setDescription(QString description) { this->description = description; } void ToDoItem::setDeadline(QDateTime deadline) { this->deadline = deadline; } void ToDoItem::setDone(bool done) { this->done = done; }
643c6354f700499b6aa3a0673ba643d37cc2e107
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/base/fs/utils/ufat/inc/eaheader.hxx
f5de1602211233344be426e67f770b61d8576bcf
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
4,253
hxx
eaheader.hxx
/*++ Copyright (c) 1990 Microsoft Corporation Module Name: eaheader.hxx Abstract: This class models the header and tables of the EA file. Author: Norbert P. Kusters (norbertk) 28-Nov-90 Notes: Luckily all the structures are well aligned. --*/ #if !defined(EA_HEADER_DEFN) #define EA_HEADER_DEFN #include "cluster.hxx" #if defined ( _AUTOCHECK_ ) #define UFAT_EXPORT #elif defined ( _UFAT_MEMBER_ ) #define UFAT_EXPORT __declspec(dllexport) #else #define UFAT_EXPORT __declspec(dllimport) #endif // // Forward references // DECLARE_CLASS( EA_HEADER ); DECLARE_CLASS( FAT ); DECLARE_CLASS( FAT_SA ); DECLARE_CLASS( LOG_IO_DP_DRIVE ); DECLARE_CLASS( MEM ); struct _EA_FILE_HEADER { USHORT Signature; USHORT FormatType; USHORT LogType; USHORT Cluster1; USHORT NewCValue1; USHORT Cluster2; USHORT NewCValue2; USHORT Cluster3; USHORT NewCValue3; USHORT Handle; USHORT NewHOffset; UCHAR Reserved[10]; }; DEFINE_TYPE( struct _EA_FILE_HEADER, EA_FILE_HEADER ); CONST BaseTableSize = 240; struct _EA_MAP_TBL { USHORT BaseTab[BaseTableSize]; USHORT OffTab[1]; }; DEFINE_TYPE( struct _EA_MAP_TBL, EA_MAP_TBL ); struct _EA_HEADER_AND_TABLE { EA_FILE_HEADER Header; EA_MAP_TBL Table; }; DEFINE_TYPE( struct _EA_HEADER_AND_TABLE, EA_HEADER_AND_TABLE ); CONST USHORT HeaderSignature = 0x4445; CONST USHORT CurrentFormatType = 0; CONST USHORT CurrentLogType = 0; CONST USHORT Bit15 = 0x8000; CONST USHORT InvalidHandle = 0xFFFF; class EA_HEADER : public CLUSTER_CHAIN { public: UFAT_EXPORT DECLARE_CONSTRUCTOR( EA_HEADER ); VIRTUAL UFAT_EXPORT ~EA_HEADER( ); NONVIRTUAL UFAT_EXPORT BOOLEAN Initialize( IN OUT PMEM Mem, IN OUT PLOG_IO_DP_DRIVE Drive, IN PFAT_SA FatSuperArea, IN PCFAT Fat, IN ULONG StartingCluster, IN ULONG LengthOfChain DEFAULT 0 ); NONVIRTUAL PEA_FILE_HEADER GetEaFileHeader( ); NONVIRTUAL PEA_MAP_TBL GetMapTable( ); NONVIRTUAL LONG QueryOffTabSize( ) CONST; NONVIRTUAL UFAT_EXPORT USHORT QueryEaSetClusterNumber( IN USHORT Handle ) CONST; private: NONVIRTUAL VOID Construct( ); NONVIRTUAL VOID Destroy( ); PEA_HEADER_AND_TABLE _ht; LONG _off_tab_size; }; INLINE PEA_FILE_HEADER EA_HEADER::GetEaFileHeader( ) /*++ Routine Description: This routine returns a pointer to the EA file header. Dereferencing this pointer will allow the client to examine and modify the EA file header. These changes will take effect on disk when the client issues a 'Write' command. Arguments: None. Return Value: A pointer to the EA file header. --*/ { return _ht ? &_ht->Header : NULL; } INLINE PEA_MAP_TBL EA_HEADER::GetMapTable( ) /*++ Routine Description: This routine returns a pointer to the EA mapping table. Dereferencing this pointer will allow the client to examine and modify the EA mapping table. These changes will take effect on disk when the client issues a 'Write' command. Arguments: None. Return Value: A pointer to the EA mapping table. --*/ { return _ht ? &_ht->Table : NULL; } INLINE LONG EA_HEADER::QueryOffTabSize( ) CONST /*++ Routine Description: Computes the number of entries in the offset table. Arguments: None. Return Value: Returns the number of entries in the offset table. --*/ { return _off_tab_size; } #endif // EA_HEADER_DEFN
86e87543ffea180acb1566e1aaeb57370bd1ada1
8d5ec68b918279bd47ab6b57fa2cce7567c4b3a6
/Framework/Environment/Scattering.cpp
5db0ea3a0b9034aa8238fb5abf18a709465d2dff
[]
no_license
sork777/PortFolio
7d6a77a595ca35f821486f620a0b1318d6e7511c
152d9d8b3d38f490ffccb644691f5a052b677307
refs/heads/master
2022-12-30T17:10:58.267379
2020-01-11T05:32:26
2020-01-11T05:32:26
232,132,922
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
5,166
cpp
Scattering.cpp
#include "Framework.h" #include "Scattering.h" Scattering::Scattering(Shader * shader) : shader(shader), width(256), height(128), domeCount(32) { mieTarget = new RenderTarget(width, height, DXGI_FORMAT_R32G32B32A32_FLOAT); rayleighTarget = new RenderTarget(width, height, DXGI_FORMAT_R32G32B32A32_FLOAT); depthStencil = new DepthStencil(width, height); viewport = new Viewport((float)width, (float)height); render2D = new Render2D(); render2D->GetTransform()->Scale(200, 200, 1); render2D->GetTransform()->RotationDegree(0, 0, -90); CreateQuad(); CreateDome(); sRayleighSRV = shader->AsSRV("RayleighMap"); sMieSRV = shader->AsSRV("MieMap"); } Scattering::~Scattering() { SafeDelete(render2D); SafeDelete(mieTarget); SafeDelete(rayleighTarget); SafeDelete(depthStencil); SafeDelete(viewport); SafeDelete(vertexBuffer); SafeDelete(domeVertexBuffer); SafeDelete(domeIndexBuffer); } void Scattering::Update() { render2D->Update(); } void Scattering::PreRender() { vector<RenderTarget *> rtvs; rtvs.push_back(rayleighTarget); rtvs.push_back(mieTarget); RenderTarget::Sets(rtvs, depthStencil->DSV()); viewport->RSSetViewport(); UINT stride = sizeof(VertexTexture); UINT offset = 0; vertexBuffer->Render(); D3D::GetDC()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); shader->Draw(0, 0, 6); } void Scattering::Render() { sRayleighSRV->SetResource(rayleighTarget->SRV()); sMieSRV->SetResource(mieTarget->SRV()); //sStar->SetResource(texture->SRV()); domeVertexBuffer->Render(); domeIndexBuffer->Render(); D3D::GetDC()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); shader->DrawIndexed(0, 1, domeIndexCount); } void Scattering::PostRender() { render2D->SRV(rayleighTarget->SRV()); render2D->GetTransform()->Position(0 + 100, 0 + 100, 0); render2D->Update(); render2D->Render(); render2D->SRV(mieTarget->SRV()); render2D->GetTransform()->Position(200 + 100, 0 + 100, 0); render2D->Update(); render2D->Render(); } void Scattering::CreateQuad() { VertexTexture vertices[6]; vertices[0].Position = Vector3(-1.0f, -1.0f, 0.0f); vertices[1].Position = Vector3(-1.0f, +1.0f, 0.0f); vertices[2].Position = Vector3(+1.0f, -1.0f, 0.0f); vertices[3].Position = Vector3(+1.0f, -1.0f, 0.0f); vertices[4].Position = Vector3(-1.0f, +1.0f, 0.0f); vertices[5].Position = Vector3(+1.0f, +1.0f, 0.0f); vertices[0].Uv = Vector2(0, 1); vertices[1].Uv = Vector2(0, 0); vertices[2].Uv = Vector2(1, 1); vertices[3].Uv = Vector2(1, 1); vertices[4].Uv = Vector2(0, 0); vertices[5].Uv = Vector2(1, 0); vertexBuffer = new VertexBuffer(vertices, 6, sizeof(VertexTexture)); } void Scattering::CreateDome() { UINT latitude = domeCount / 2; // ร€ยงยตยต UINT longitude = domeCount; // ยฐรฆยตยต domeVertexCount = longitude * latitude * 2; domeIndexCount = (longitude - 1) * (latitude - 1) * 2 * 8; VertexTexture* vertices = new VertexTexture[domeVertexCount]; UINT index = 0; for (UINT i = 0; i < longitude; i++) { float xz = 100.0f * (i / (longitude - 1.0f)) * Math::PI / 180.0f; for (UINT j = 0; j < latitude; j++) { float y = Math::PI * j / (latitude - 1); vertices[index].Position.x = sinf(xz) * cosf(y); vertices[index].Position.y = cosf(xz)*2; vertices[index].Position.z = sinf(xz) * sinf(y); vertices[index].Uv.x = 0.5f / (float)longitude + i / (float)longitude; vertices[index].Uv.y = 0.5f / (float)latitude + j / (float)latitude; index++; } // for(j) } // for(i) for (UINT i = 0; i < longitude; i++) { float xz = 100.0f * (i / (longitude - 1.0f)) * Math::PI / 180.0f; for (UINT j = 0; j < latitude; j++) { float y = (Math::PI * 2.0f) - (Math::PI * j / (latitude - 1)); vertices[index].Position.x = sinf(xz) * cosf(y); vertices[index].Position.y = cosf(xz)*2; vertices[index].Position.z = sinf(xz) * sinf(y); vertices[index].Uv.x = 0.5f / (float)longitude + i / (float)longitude; vertices[index].Uv.y = 0.5f / (float)latitude + j / (float)latitude; index++; } // for(j) } // for(i) index = 0; UINT* indices = new UINT[domeIndexCount * 3]; for (UINT i = 0; i < longitude - 1; i++) { for (UINT j = 0; j < latitude - 1; j++) { indices[index++] = i * latitude + j; indices[index++] = (i + 1) * latitude + j; indices[index++] = (i + 1) * latitude + (j + 1); indices[index++] = (i + 1) * latitude + (j + 1); indices[index++] = i * latitude + (j + 1); indices[index++] = i * latitude + j; } } UINT offset = latitude * longitude; for (UINT i = 0; i < longitude - 1; i++) { for (UINT j = 0; j < latitude - 1; j++) { indices[index++] = offset + i * latitude + j; indices[index++] = offset + (i + 1) * latitude + (j + 1); indices[index++] = offset + (i + 1) * latitude + j; indices[index++] = offset + i * latitude + (j + 1); indices[index++] = offset + (i + 1) * latitude + (j + 1); indices[index++] = offset + i * latitude + j; } } domeVertexBuffer = new VertexBuffer(vertices, domeVertexCount, sizeof(VertexTexture), 0); domeIndexBuffer = new IndexBuffer(indices, domeIndexCount); SafeDeleteArray(vertices); SafeDeleteArray(indices); }
c3bf23ff3e1cca483bab0bc8cfe3d0fbf4da6d45
ca0e6f4bfa50d8750bad3e95a7bb3c30aa4b6113
/Triangulation.hpp
cd15d3dba4fcb223b0c26221bf9be765fddd8709
[]
no_license
MohFarahani/WaveFEM
876126e39aec6f3f801f62ca39575d6dfa78cbcd
113493bbdd95a602f4bb5d164d13380dba325f63
refs/heads/main
2023-04-19T18:06:44.046979
2021-05-04T16:35:05
2021-05-04T16:35:05
364,320,316
0
0
null
null
null
null
UTF-8
C++
false
false
1,227
hpp
Triangulation.hpp
#ifndef TRIANGULATION_HPP #define TRIANGULATION_HPP #include<iostream> #include<fstream> #include<vector> #include <algorithm> #include<string> #include"Vertex.hpp" #include "Triangle.hpp" #include <stdlib.h> //******************************************************************************************************************* /*! Triangulation class * In this class, we create our triangular our domain. Therefore, we need to know about all of the vertex (which here store in vertices_) * and the relationship between each vertex ( which is in triangle) that stores in triangles_ */ //******************************************************************************************************************* class Triangulation { public: Triangulation() ; ~Triangulation() ; std::vector<Vertex>& vertices() ; std::vector<Triangle>& triangles(); int& refinement_level() ; void mid_vertex(Vertex& mid_vertex_1_2 , const Vertex& vertex1 , const Vertex& vertex2 ) ; int find(const Vertex& vert) ; void update_index() ; int initialize(const char* file_name) ; void refinement() ; private: std::vector<Vertex> vertices_; std::vector<Triangle> triangles_ ; int refinement_level_ ; }; #endif //TRIANGULATION-H
df50c17552506a379398fc3dc261e0a578f31112
e897ad3b1cb19f822f9c56d6daa2dbb8172e768a
/cpp/uva/00787.cpp
fcc8236e6e5cc70ec222503d4d895ad4c7908434
[]
no_license
cocoslime/AlgoProblem
409cb8257cc05bfcebe13a8d6c662cd3308a5678
b9d66df04ad95917e0765cb8a4c7305016ca48ee
refs/heads/master
2023-02-20T03:19:26.226799
2023-02-05T08:15:01
2023-02-05T08:15:01
103,516,243
0
0
null
null
null
null
UTF-8
C++
false
false
1,290
cpp
00787.cpp
#define _CRT_SECURE_NO_WARNINGS #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <cmath> #include <vector> #include <climits> #include <queue> #include <map> using namespace std; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; #define REP(i, a, b) for (int i = int(a) ; i < int(b); i++) #include <iostream> int num = 0; long long arr[101]; long long cache[101][101]; long long findsubMax(int s, int e) { if (e - s == 1) return arr[s]; if (cache[e - 1] / cache[s] < 0) { return max(findsubMax(s, e - 1), findsubMax(s + 1, e)); } else { return cache[e - 1] / cache[s]; } } long long findMax(int s, int e) { if (e - s == 1) return arr[s]; if (e == s) return 0; int i = 0; for (i = s; i < e; i++) { if (arr[i] == 0) { break; } } if (i == e){ if (cache[e - 1] > 0) return cache[e - 1]; else { return findsubMax(s, e); } } else { return max((long long)0, max(findMax(s, i), findMax(i + 1, e)) ); } } int main() { int value; while (scanf("%d", &value) == 1) { if (value != -999999) { arr[num] = value; num++; } else { for (int i = 0; i < num; i++) { fill(begin(cache[i]), end(cache[i]), -1); } cout << findMax(0, num) << endl; num = 0; } } return 0; }
6d73cda3288ee829337d1913fe49a921a4d16c9a
d49ae7489f1c26de887f7b521a935b55e66c83c7
/234.ๅ›žๆ–‡้“พ่กจ.cpp
476ee69e903d5b069ad92f9dc0460a1381b502ad
[]
no_license
Sander-houqi/leetcode-cpp
391d4c97c5dbbc7b7a9690539409c156090a867f
c0b6a06d246555ece17cebcb35309209f31e22bf
refs/heads/main
2023-05-02T20:39:34.811841
2021-05-21T08:08:51
2021-05-21T08:08:51
341,105,472
0
0
null
null
null
null
UTF-8
C++
false
false
1,304
cpp
234.ๅ›žๆ–‡้“พ่กจ.cpp
/* * @lc app=leetcode.cn id=234 lang=cpp * * [234] ๅ›žๆ–‡้“พ่กจ */ // @lc code=start /* struct ListNode{ int val; ListNode *next; ListNode() : val(0),next(nullptr) {} ListNode(int x) : val(x), next(nullptr){} ListNode(int x, ListNode* next): val(x),next(next){} }; */ #include<vector> using namespace std; class Solution { public: bool isPalindrome(ListNode* head) { if(!head || ! head->next) return true; ListNode *slow = head , *fast = head; //ๆ‰พๅˆฐไธญ้—ด่Š‚็‚น๏ผŒๅŽๅŠๆฎตๅ่ฝฌ while (fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; } ListNode * p1 = head; //ๅฅ‡ๆ•ฐไธช่Š‚็‚น๏ผŒไธญ้—ด้ƒจๅˆ†็œ‹ๅšๅ‰ๅŠ้ƒจๅˆ† ListNode * p2 = reverseList(slow->next); while (p2) { if(p1->val != p2->val){ return false; } p1 = p1->next; p2 = p2->next; } return true; } ListNode * reverseList(ListNode *head){ ListNode *prev = nullptr, *curr = head, *tmp; while (curr) { tmp = curr->next; curr->next = prev; prev = curr; curr = tmp; } return prev; } }; // @lc code=end
b9c4c0284c54bb9f6320a60bb3a24c0fad93715f
82facc6a8f6d5e07983fb6a9d58b072c75a769c8
/core/src/BoundingBox.hpp
972402d7849edf5dc158992c1320e95d5f52c093
[ "Apache-2.0" ]
permissive
YoucefSklab/utymap
d0e1c9db8b5bfd657cb57207b30b436bbf154c97
d8b777d0713a9450931732b8f42af1e6f0a0bedf
refs/heads/master
2020-03-27T23:20:50.488234
2018-09-04T08:20:08
2018-09-04T08:20:08
147,311,520
1
0
Apache-2.0
2018-09-04T08:14:51
2018-09-04T08:14:51
null
UTF-8
C++
false
false
3,294
hpp
BoundingBox.hpp
#ifndef BOUNDINGBOX_HPP_DEFINED #define BOUNDINGBOX_HPP_DEFINED #include "GeoCoordinate.hpp" #include <algorithm> namespace utymap { /// Represents geo bounding box struct BoundingBox final { /// Point with minimal latitude and longitude. GeoCoordinate minPoint; /// Point with maximum latitude and longitude. GeoCoordinate maxPoint; BoundingBox() : BoundingBox(GeoCoordinate(90, 180), GeoCoordinate(-90, -180)) { } BoundingBox(const GeoCoordinate &minPoint, const GeoCoordinate &maxPoint) : minPoint(minPoint), maxPoint(maxPoint) { } BoundingBox &operator+=(const BoundingBox &rhs) { expand(rhs); return *this; } bool isValid() const { // TODO possible that minLon > maxLon at some locations return minPoint.latitude <= maxPoint.latitude && minPoint.longitude <= maxPoint.longitude; } /// Expands bounding box using another bounding box. void expand(const BoundingBox &rhs) { minPoint.latitude = std::min(minPoint.latitude, rhs.minPoint.latitude); minPoint.longitude = std::min(minPoint.longitude, rhs.minPoint.longitude); maxPoint.latitude = std::max(maxPoint.latitude, rhs.maxPoint.latitude); maxPoint.longitude = std::max(maxPoint.longitude, rhs.maxPoint.longitude); } /// Expands bounding box using given coordinate. void expand(const GeoCoordinate &c) { minPoint = GeoCoordinate( std::min(minPoint.latitude, c.latitude), std::min(minPoint.longitude, c.longitude)); maxPoint = GeoCoordinate( std::max(maxPoint.latitude, c.latitude), std::max(maxPoint.longitude, c.longitude)); } /// Expands bounging box from collection of geo data. template<typename ForwardIterator> void expand(ForwardIterator begin, ForwardIterator end) { for (; begin!=end; ++begin) expand(*begin); } /// Checks whether given bounding box inside the current one. bool contains(const BoundingBox &bbox) const { return contains(bbox.minPoint) && contains(bbox.maxPoint); } /// Checks whether given coordinate inside the bounding box. bool contains(const GeoCoordinate &coordinate) const { return coordinate.latitude > minPoint.latitude && coordinate.longitude > minPoint.longitude && coordinate.latitude < maxPoint.latitude && coordinate.longitude < maxPoint.longitude; } /// Checks whether given bounding box intersects the current one. bool intersects(const BoundingBox &rhs) const { double minLat = std::max(rhs.minPoint.latitude, minPoint.latitude); double minLon = std::max(rhs.minPoint.longitude, minPoint.longitude); double maxLat = std::min(rhs.maxPoint.latitude, maxPoint.latitude); double maxLon = std::min(rhs.maxPoint.longitude, maxPoint.longitude); return minLat <= maxLat && minLon <= maxLon; } /// Returns center of bounding box. GeoCoordinate center() const { return GeoCoordinate( minPoint.latitude + (maxPoint.latitude - minPoint.latitude)/2, minPoint.longitude + (maxPoint.longitude - minPoint.longitude)/2); } /// Returns width. double width() const { return maxPoint.longitude - minPoint.longitude; } /// Returns height. double height() const { return maxPoint.latitude - minPoint.latitude; } }; } #endif // BOUNDINGBOX_HPP_DEFINED
aa62ab9256091bea5589cd25d9db4d354588ed77
28996e87064acfd1e5c5d7554b18ccaee2da3b9d
/include/imlab/util/Operator.h
4817c25545256a9731d2671827fd8e6eaf8cb712
[ "MIT" ]
permissive
JigaoLuo/Data_Blocks
c1615417ffd5518ab0804684f38fcb5b14fcc53c
72ba7e352118ca25f4d0cb5d07853e4e0976e07e
refs/heads/main
2022-12-28T05:51:49.731597
2020-10-10T20:35:48
2020-10-10T20:35:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,967
h
Operator.h
// --------------------------------------------------------------------------------------------------- // IMLAB // --------------------------------------------------------------------------------------------------- #ifndef INCLUDE_IMLAB_UTIL_OPERATOR_H #define INCLUDE_IMLAB_UTIL_OPERATOR_H // -------------------------------------------------------------------------------------------------- #include <memory> #include <cstdint> #include <cassert> #include <utility> // --------------------------------------------------------------------------------------------------- namespace imlab { namespace util { // --------------------------------------------------------------------------------------------------- /// Idea from stl_function.h /// Motivation: I have no between functional operator from the <functional> library, so I mock one for my scan case: BETWEEN /// Inorder to use all these functions to get type checked in the compile time, I mock all the function as tertiary_function /** * Idea from Implementation of unary_function and binary_function */ template<typename _Arg1, typename _Arg2, typename _Arg3, typename _Result> struct ternary_function { /// @c first_argument_type is the type of the first argument typedef _Arg1 first_argument_type; /// @c second_argument_type is the type of the second argument typedef _Arg2 second_argument_type; /// @c third_argument_type is the type of the second argument typedef _Arg3 third_argument_type; /// @c result_type is the return type typedef _Result result_type; }; template<typename _Tp> struct equal_to : public ternary_function<_Tp, _Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __value,const _Tp& __l, const _Tp& __r) const { return __value == __l; } }; template<typename _Tp> struct greater : public ternary_function<_Tp, _Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __value,const _Tp& __l, const _Tp& __r) const { return __value > __l; } }; template<typename _Tp> struct less : public ternary_function<_Tp, _Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __value,const _Tp& __l, const _Tp& __r) const { return __value < __l; } }; template<typename _Tp> struct between : public ternary_function<_Tp, _Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __value,const _Tp& __l, const _Tp& __r) const { return __l <= __value && __value <= __r; } }; // --------------------------------------------------------------------------------------------------- } // namespace util // --------------------------------------------------------------------------------------------------- } // namespace imlab // --------------------------------------------------------------------------------------------------- #endif // INCLUDE_IMLAB_UTIL_OPERATOR_H // ---------------------------------------------------------------------------------------------------
7733a6427d7d259b96108d9615c2e33776daae97
4910c0f3d03935fc8ee03f1e9dc20dfdb2c7c04b
/Codigos estudiantes por lenguaje/C++/Bryann Valderrama/Strings/boyerMoore.cpp
c468ea03756e9a65a9a710bac917d4769c284c6b
[]
no_license
roca12/gpccodes
ab15eeedc0cadc0735651262887b44f1c2e65b93
aa034a3014c6fb879ec5392c51f9714bdc5b50c2
refs/heads/master
2023-02-01T13:49:27.563662
2023-01-19T22:50:58
2023-01-19T22:50:58
270,723,328
3
5
null
null
null
null
UTF-8
C++
false
false
1,417
cpp
boyerMoore.cpp
#include <bits/stdc++.h> #include <cstdlib> using namespace std; #define NO_OF_CHARS 256 int maximo(int a, int b) { return (a > b) ? a : b; } //string str void badCharHeuristic(char str[], int tam, int badchar[]) { int i; for (i = 0; i < NO_OF_CHARS; i++) { badchar[i] = -1; } for (i = 0; i < tam; i++) { badchar[(int)str[i]] = i; } } //string txt string pat void boyerMoore(char txt[], char pat[]) { int m = strlen(pat); int n = strlen(txt); int badchar[NO_OF_CHARS]; badCharHeuristic(pat, m, badchar); int s = 0; while (s <= (n - m)) { int j = m - 1; while (j >= 0 && pat[j] == txt[s + j]) { j--; } if (j < 0) { cout << "Patron encontrado encontrado en salto " << s << endl; s += (s + m < m) ? m - badchar[txt[s + m]] : 1; } else { s += maximo(1, j - badchar[txt[s + j]]); } } } int main(int argc, char const *argv[]) { string txt1 = "holacomoestasholahola"; int n = txt1.length(); char txt[n + 1]; strcpy(txt, txt1.c_str()); string pat1 = "hola"; int n2 = pat1.length(); char pat[n2 + 1]; strcpy(pat, pat1.c_str()); //Directamente con arreglo de char // char txt[] = "holacomoestasholahola"; // char pat[] = "hola"; boyerMoore(txt, pat); return 0; }
d4213b61967daf41b19d286c51f4f482f83e3280
7202e3375199793f5c36c6c16e0e90b773a5e66e
/IControlsSolution/IControls/AnimationviewItem.cpp
8c111446214bacc6215ae35b557de0291db841d4
[]
no_license
gsueros/itourperu1
cdddbfbfdbd893e7835270c8dda84e0491900148
731e53d6eff1bf816f979e2793733fb24ca2d8d9
refs/heads/master
2021-05-27T00:04:52.581331
2013-03-21T16:21:40
2013-03-21T16:21:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,033
cpp
AnimationviewItem.cpp
#include "pch.h" using namespace IControls ; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; AnimationViewItem::AnimationViewItem() { this->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Left ; this->_imageitem = ref new Image(); this->_imageitem->Stretch = Stretch::Fill ; this->_itemtransform = ref new CompositeTransform(); //this->_itemtransform->CenterX = 0.0 ; this->RenderTransform = this->_itemtransform ; this->Children->Append(this->_imageitem); this->_imageitem->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Center ; initanimations(); } void AnimationViewItem::initanimations() { Windows::Foundation::TimeSpan ts; ts.Duration = 4500000 ; Windows::UI::Xaml::Duration dur(ts) ; this->_translatestory = ref new Windows::UI::Xaml::Media::Animation::Storyboard(); this->_translatexanimation = ref new Windows::UI::Xaml::Media::Animation::DoubleAnimation(); this->_translatexanimation->Duration = dur ; this->_translatestory->Children->Append(this->_translatexanimation); Windows::UI::Xaml::Media::Animation::Storyboard::SetTarget(this->_translatexanimation, this->_itemtransform) ; Windows::UI::Xaml::Media::Animation::Storyboard::SetTargetProperty(this->_translatexanimation , "TranslateX") ; Windows::UI::Xaml::Media::Animation::CubicEase ^ ease1 = ref new Windows::UI::Xaml::Media::Animation::CubicEase(); ease1->EasingMode = Windows::UI::Xaml::Media::Animation::EasingMode::EaseOut ; this->_translatexanimation->EasingFunction = ease1 ; this->_translateyanimation = ref new Windows::UI::Xaml::Media::Animation::DoubleAnimation(); this->_translateyanimation->Duration = dur ; this->_translatestory->Children->Append(this->_translateyanimation); Windows::UI::Xaml::Media::Animation::Storyboard::SetTarget(this->_translateyanimation, this->_itemtransform) ; Windows::UI::Xaml::Media::Animation::Storyboard::SetTargetProperty(this->_translateyanimation , "TranslateY") ; Windows::UI::Xaml::Media::Animation::CubicEase ^ ease2 = ref new Windows::UI::Xaml::Media::Animation::CubicEase(); ease2->EasingMode = Windows::UI::Xaml::Media::Animation::EasingMode::EaseOut ; this->_translateyanimation->EasingFunction = ease2 ; this->_translatestory->Completed += ref new EventHandler<Platform::Object^>(this, &IControls::AnimationViewItem::Storyboard_Completed_1); } void AnimationViewItem::AnimateTo(float64 _x , float64 _y) { this->_translatexanimation->To = _x ; this->_translateyanimation->To = _y ; this->_translatestory->Begin(); } void IControls::AnimationViewItem::Storyboard_Completed_1(Platform::Object^ sender, Platform::Object^ e) { AnimationViewItemCompleted(this); }
26c9831358458fc9705e2fb30076f585c5f2cb0d
6c2d4fe52afff8516fa51e2fd7f8d804e4b4bcb1
/include/circle.h
e0ffe36ff0c5c95f9a813792019b73fce7c324a4
[]
no_license
evankersey/chaosEC3
cdca5171c03d7787ee9761253fbd031b8eeba382
c232dbeb5c25b3efd45d43bebe9165df6bea32be
refs/heads/master
2022-06-21T10:56:19.629406
2022-06-15T19:20:23
2022-06-15T19:20:23
183,584,313
1
0
null
null
null
null
UTF-8
C++
false
false
279
h
circle.h
#ifndef CIRCLE_H #define CIRCLE_H class circle { public: circle(int maxWidth, int maxHeight); virtual ~circle(); int centerX; int centerY; int radius; const double pi = 3.14159265359; protected: private: int diameter; }; #endif // CIRCLE_H
6d1822ec8c4b7936afaee5c50603478963c749f7
9fdd3494a80d2eed0ab7f399fabf68fd80d3d678
/DirectX11/Project/Include/Script/IronGolemAttack13State.h
e41720de27e47813065c587885911032f2b3e7ff
[]
no_license
minesammul/DirectX11-Project
490053cc5540643b4bbec96ebd480cf8309457c7
23fd4d5ae6df7661cf0168bdd13906c77eb84461
refs/heads/master
2022-06-20T17:01:25.772676
2020-05-15T10:41:39
2020-05-15T10:41:39
196,714,638
0
0
null
null
null
null
UTF-8
C++
false
false
111
h
IronGolemAttack13State.h
#pragma once class IronGolemAttack13State { public: IronGolemAttack13State(); ~IronGolemAttack13State(); };
f1ac54216188d3dbe1b13e2907687bf116baeb6d
714423f3011f41ffd26d0534ed99640e482dbf93
/FtsUtilityAI/Source/FtsUtilityAI/Private/Score/FtsUtilityAIMultiScoreModifier.cpp
f7f46ced55101bf839fee75ca4098641fb54a340
[ "MIT" ]
permissive
FreetimeStudio/FtsUtilityAI
2053abd9e4e3ab9f415686e24b7de9d58cfc426c
cf1f214d685fcc3c24f426881bdad6c8257e36e3
refs/heads/main
2023-02-25T02:00:40.624764
2021-02-03T21:03:00
2021-02-03T21:03:00
312,661,459
1
0
null
null
null
null
UTF-8
C++
false
false
380
cpp
FtsUtilityAIMultiScoreModifier.cpp
// (c) MIT 2020 by FreetimeStudio #include "Score/FtsUtilityAIMultiScoreModifier.h" #if WITH_EDITOR void UFtsUtilityAIMultiScoreModifier::ClearInputs() { ModifiedScores.Empty(); } void UFtsUtilityAIMultiScoreModifier::AddInput(UFtsUtilityAiObject* NewInput) { auto Score = Cast<UFtsUtilityAIScore>(NewInput); check(Score); ModifiedScores.Add(Score); } #endif
a43e0d1708449f43b971175e676891ead2b3667f
75b0a6967d1de8c11276f2cf07d20b4d2958dafa
/RingBuffer.h
11cfcdb6510653eeca805043548618cdfe369b66
[]
no_license
CodeByKim/IOCP-Sample
38968330969bd4b52dd6687b5110ed9ab87ad089
e72f95e1dbdaec954948b5c6cf156d0a73fc6ac8
refs/heads/master
2023-04-24T12:10:21.700726
2021-05-15T10:50:29
2021-05-15T10:50:29
367,604,252
0
0
null
null
null
null
UTF-8
C++
false
false
575
h
RingBuffer.h
๏ปฟ#pragma once #include <Windows.h> class RingBuffer { public: RingBuffer(int size); ~RingBuffer(); bool Enqueue(char* data, int size); bool Dequeue(char* outData, int size); bool Peek(char* outData, int size); void MoveFront(int size); void MoveRear(int size); bool IsEmpty(); int GetRemainQueueSize(); int GetUseSize(); char* GetBufferFront(); char* GetBufferRear(); int GetDirectEnqueueSize(); int GetDirectDequeueSize(); void Clear(); private: char* mBuffer; char* mBufferFront; char* mBufferRear; char* mBufferEnd; int mSize; int mCapacity; };
c69ca667cff70da5a1a8c179d587afa67da4f307
32fd4f562e5ac49b52352dc3f5b9cc00e0d7e05d
/hw/api_irq.hpp
16c99dd7b7227d040e3ff976e2ebb2a205dd67b8
[ "MIT" ]
permissive
JehTeh/jel
986dd663179f00220b929e1e4d581df1abd8117a
2c43cf23ea7b89e7ec0f7c2e9549be74ab0bbc4b
refs/heads/master
2021-03-30T18:26:42.429234
2019-01-05T03:59:33
2019-01-05T03:59:33
118,649,373
14
0
null
null
null
null
UTF-8
C++
false
false
4,945
hpp
api_irq.hpp
/** @file hw/api_irq.hpp * @brief General interrupt controller interface routines are exposed via this interface. * * @detail * * * @author Jonathan Thomson */ /** * MIT License * * Copyright 2018, Jonathan Thomson * * 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. */ #pragma once /** C/C++ Standard Library Headers */ #include <cstdint> /** jel Library Headers */ namespace jel { namespace hw { namespace irq { /** @enum Index * @brief Generic indexes used for enabling or disabling specific interrupt vectors in the * interrupt controller. * * IRQ/FIQ indexes are considered generic across hardware, with the different mappings for different * processors. While it is possible to explicitly enable and disable indexes in the application * code, it is recommended this functionality generally remain at the driver level, and where * necessary that the application controls a specific interrupt vector the driver implementation * provides a function that returns the correct index for that target. For example, * @code * //Generic Uart API example, visible to the application * class OutputUart : public os::SerialWriterInterface * { * ... * irq::Index getUartIsrIndex() noexcept; * ... * }; * * //Implementation in the uart source file for one target * irq::Index OutputUart::getUartIsrIndex() { return isr::Index::chan7; } * //Implementation in the uart source file for another target * irq::Index OutputUart::getUartIsrIndex() { return isr::Index::chan17; } * @endcode * This allows for the application to ensure it always controls the correct interrupt line for that * peripheral. It also allows for interrupt remapping to be done in the background, either at * compile time due to design changes or at runtime. * */ enum class Index : uint32_t { chan0 = 0, chan1, chan2, chan3, chan4, chan5, chan6, chan7, chan8, chan9, chan10, chan11, chan12, chan13, chan14, chan15, chan16, chan17, chan18, chan19, chan20, chan21, chan22, chan23, chan24, chan25, chan26, chan27, chan28, chan29, chan30, chan31, chan32, chan33, chan34, chan35, chan36, chan37, chan38, chan39, chan40, chan41, chan42, chan43, chan44, chan45, chan46, chan47, chan48, chan49, chan50, chan51, chan52, chan53, chan54, chan55, chan56, chan57, chan58, chan59, chan60, chan61, chan62, chan63, chan64, chan65, chan66, chan67, chan68, chan69, chan70, chan71, chan72, chan73, chan74, chan75, chan76, chan77, chan78, chan79, chan80, chan81, chan82, chan83, chan84, chan85, chan86, chan87, chan88, chan89, chan90, chan91, chan92, chan93, chan94, chan95, chan96, chan97, chan98, chan99, chan100, chan101, chan102, chan103, chan104, chan105, chan106, chan107, chan108, chan109, chan110, chan111, chan112, chan113, chan114, chan115, chan116, chan117, chan118, chan119, chan120, chan121, chan122, chan123, chan124, chan125, chan126, chan127 }; enum class IrqType { irq, fiq }; class InterruptController { public: /** Sets the global interrupt enabled state to true. On MCUs with additional interrupt signals, * such as the Cortex-R series FIQs, these are also enabled. */ static void enableGlobalInterrupts(); /** Disable all disable-able interrupts. On MCUs such as the Cortex-R series, this does *not* * disable FIQs, as they can not be disabled short of a POR. */ static void disableGlobalInterrupts(); /** Enables a specific interrupt channel, of either the FIQ or IRQ type. On MCUs without FIQ * support all requests are treated as IRQs. */ static void enableInterrupt(const Index channel, const IrqType type = IrqType::irq); /** Disables a specific interrupt channel, of either the FIQ or IRQ type. On MCUs without FIQ * support all requests are treated as IRQs. */ static void disableInterrupt(const Index channel, const IrqType type = IrqType::irq); }; } } /** namespace hw */ } /** namespace jel */
adebdea11b4c69ba08e49027845c9c77a71eff31
1dd791ef8132ed6bebc458d7c3c1ba5a9c8ca985
/src/rx/core/assert.cpp
c8bbf94720172a8435d091fd9b747ada01834e71
[ "MIT" ]
permissive
BuckeyeSoftware/rex
e4ef1a743745b027eb02c629541edf85faf1d026
a0380e2e3ce26e610b4c9fcbe0ece19ecc8c3531
refs/heads/main
2021-12-20T17:41:51.163916
2021-12-05T04:07:52
2021-12-05T04:07:52
171,078,375
40
7
MIT
2020-12-15T03:24:33
2019-02-17T03:38:52
C++
UTF-8
C++
false
false
555
cpp
assert.cpp
#include "rx/core/abort.h" // abort #include "rx/core/assert.h" namespace Rx { [[noreturn]] void assert_message(const char* _expression, const SourceLocation& _source_location, const char* _message, bool _truncated) { abort("Assertion failed:\n" " Expression: %s\n" " Location: %s:%d\n" " Function: %s\n" " Description: %s%s", _expression, _source_location.file(), _source_location.line(), _source_location.function(), _message, _truncated ? "... [truncated]" : ""); } } // namespace Rx
a08ac84a9e767edc97efe5a320cc1313e2fda32c
db21ae7bfcad8d0917ac8695a077d824a09738e9
/source/xdynamics_object/xMassSpringModel.cpp
d77374f3271acdcde513d8fc165a5d7fdf4782e4
[]
no_license
miniwooki/xdynamics_dll
11dfa7ebf1ff02c7900742f6b11d016749707863
30723bf724ce0c6b83c1b863f2bd69e586f2959b
refs/heads/master
2022-04-25T09:47:47.100655
2020-04-27T06:50:43
2020-04-27T06:50:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
245
cpp
xMassSpringModel.cpp
#include "xdynamics_object/xMassSpringModel.h" xMassSpringModel::xMassSpringModel() : xObject() { } xMassSpringModel::xMassSpringModel(std::string _name) : xObject(_name, MASS_SPRING_MODEL) { } xMassSpringModel::~xMassSpringModel() { }
204653570879dc51a00bffb3ade86ef76fe64e45
73227b7289fcbdcc81f72b28660f6856d097bf63
/practice_17_ๅฆ็ฑปๅŠ ๆณ• .cpp
91692a59de60240d4c72d7a52916025b98fea6b7
[]
no_license
Adenson/Practice_Code
699245c0ef974796a5837995e549cb6b701d5c97
2170227d3639b12b6f36f87b2aa312b2791d402a
refs/heads/master
2020-09-09T13:56:47.044883
2020-06-09T15:29:58
2020-06-09T15:29:58
221,464,616
0
0
null
null
null
null
UTF-8
C++
false
false
749
cpp
practice_17_ๅฆ็ฑปๅŠ ๆณ• .cpp
้ข˜็›ฎID๏ผš25083 --ๅฆ็ฑปๅŠ ๆณ• ้“พๆŽฅ๏ผšhttps://www.nowcoder.com/practice/e7e0d226f1e84ba7ab8b28efc6e1aebc?tpId=8& &tqId=11065&rp=1&ru=/activity/oj&qru=/ta/cracking-the-coding-interview/question-ranking class UnusualAdd { public: int addAB(int A, int B) { int add = 0; int tmp = 0; while (B != 0) { add = A ^ B;//ๅฏนๅบ”ไฝ็š„ๅ’Œ tmp = (A&B) << 1;//ๅฏนๅบ”ไฝ็š„ๅ’Œ็š„่ฟ›ไฝ A = add; B = tmp; } return A; } }; //่ฟ™ไธชๅบ”่ฏฅไนŸ็ฎ—ๆ˜ฏๆฏ”่พƒๅทงๅฆ™ๅง public class Solution { public int Add(int num1,int num2) { if(num1>0) { while(num1--!=0) num2++; } else if(num1<0) { while(num1++!=0) num2--; } return num2; } }
64e5a0d1206b59d53217d876eef513a0a3ee762e
708a93b5f83894b9a01f3283e04f66ddd974b1b5
/src/kivm/classpath/classLoader.cpp
313ad3dca3c95c1f25268e38397a0605ffd57250
[ "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
imkiva/KiVM
6efac67905ef2892a7fde24dc46ee64b4c113afb
879e0586eaf24a799a4d1318730bbfe4335c2996
refs/heads/master
2022-04-29T12:43:11.088601
2022-03-10T13:46:49
2022-03-10T13:46:49
122,769,206
241
38
MIT
2022-03-10T13:46:51
2018-02-24T18:49:14
C++
UTF-8
C++
false
false
2,384
cpp
classLoader.cpp
// // Created by kiva on 2018/2/27. // #include <sparsepp/spp.h> #include <kivm/classpath/classLoader.h> #include <kivm/classpath/system.h> #include <kivm/oop/klass.h> #include <shared/lock.h> namespace kivm { static RecursiveLock &bootstrapLock() { static RecursiveLock lock; return lock; } Klass *ClassLoader::requireClass(ClassLoader *classLoader, const String &className) { if (classLoader == nullptr) { // This is a bootstrap class classLoader = BootstrapClassLoader::get(); } Klass *loadedClass = classLoader == nullptr ? nullptr : classLoader->loadClass(className); if (loadedClass == nullptr) { // TODO: throw LinkageError PANIC("LinkageError"); } return loadedClass; } ClassLoader *ClassLoader::getCurrentClassLoader() { // TODO: support user-defined class loader return BootstrapClassLoader::get(); } BootstrapClassLoader *BootstrapClassLoader::get() { static BootstrapClassLoader classLoader; return &classLoader; } Klass *BootstrapClassLoader::loadClass(const String &className) { RecursiveLockGuard guard(bootstrapLock()); // check whether class is already loaded auto iter = SystemDictionary::get()->find(className); if (iter != nullptr) { return iter; } // OK, let's find it! auto *klass = BaseClassLoader::loadClass(className); if (klass != nullptr) { SystemDictionary::get()->put(className, klass); klass->setClassState(ClassState::LOADED); klass->linkClass(); } return klass; } Klass *BootstrapClassLoader::loadClass(u1 *classBytes, size_t classSize) { RecursiveLockGuard guard(bootstrapLock()); Klass *klass = BaseClassLoader::loadClass(classBytes, classSize); if (klass == nullptr) { return nullptr; } auto iter = SystemDictionary::get()->find(klass->getName()); if (iter != nullptr) { delete klass; return iter; } SystemDictionary::get()->put(klass->getName(), klass); klass->setClassState(ClassState::LOADED); klass->linkClass(); return klass; } }
fcd0fcc4c9e92ebfe5d78d0b29e45925a2eb5657
f477976db292ec51fd16f3b67f4255820002c62f
/src/Channel.h
53a34882dea5d057af5d120e79e0279c9ad8290f
[]
no_license
shine4net/RabbitMQClient
7c534b5634fa9f5c4512238eb86a7003fed38788
4511dd6b7dc7f58cd1b4940432b695f4a25e00e8
refs/heads/master
2021-01-22T13:52:51.752124
2017-08-18T09:59:59
2017-08-18T09:59:59
100,695,371
4
0
null
null
null
null
UTF-8
C++
false
false
791
h
Channel.h
#pragma once #include "Corlib.h" // class RabbitMQClient; class Channel { public: Channel(); Channel(RabbitMQClient* client, int channel_no); ~Channel(); private: bool closed = false; int channel_no; amqp_connection_state_t conn; public: Channel& exchange(char* exchange, char* exchangetype); Channel& queue(char* queue); Channel& bind(char* queue, char* exchange, char* bindingkey); void send(char* exchange, char* routingkey, char* messagebody); const char* sendRPC(char* exchange, char* routingkey, char* messagebody, char* replyQueue); void send_bytes(char* exchange, char* routingkey, void *messagebody, const int len); void send_amqp_bytes(amqp_bytes_t exchange, amqp_bytes_t routingkey, amqp_bytes_t messagebody); void close(); public: int Get_ChannelNo(); };
617115028399a6af960a8fba9c379809b4261404
97e642461856458e1912627510619fe2cd3f27be
/code/utils/lipschitz.h
9d4c61c1863988398c748b849a361e557df8bafc
[ "Apache-2.0" ]
permissive
eth-sri/deepg
390d3da1a04af7fc46564dc13518aff0df17b0c6
f7e553028eaffd99eb59a1594c9e58ef830a80b1
refs/heads/master
2023-04-06T20:26:25.654823
2021-07-15T13:38:19
2021-07-15T13:38:19
218,042,975
16
6
Apache-2.0
2023-03-24T23:25:37
2019-10-28T12:35:53
Python
UTF-8
C++
false
false
3,327
h
lipschitz.h
#include "domains/interval.h" #include "utils/constants.h" #include "utils/utilities.h" #include <iostream> #include <vector> #include <cassert> #include <cmath> #include <tuple> #include <algorithm> #include <functional> #include <random> #pragma once using namespace std; class PointD { public: vector<double> x; PointD() {} PointD(vector<double> x) { this->x = x; } operator vector<double>() const { return x; } PointD operator + (const PointD& other) const; }; class HyperBox { public: vector<Interval> it; size_t dim; HyperBox() { dim = 0; } HyperBox(vector<Interval> intervals) { this->it = intervals; this-> dim = intervals.size(); } PointD center() const; int getIndexToCut(pair<bool, vector<Interval>> grad) const; double diameter() const; Interval& operator[](int i); vector<PointD> sample(int, std::default_random_engine) const; // sample point from HyperBox uniformly at random vector<HyperBox> split(int k, vector<vector<double>>& splitPoints) const; // split HyperBox in smaller HyperBoxes, make k splits per dimension bool inside(PointD p) const; // check whether point is inside of hbox void split(size_t dim1, HyperBox& hbox1, HyperBox& hbox2) const; static HyperBox concatenate(const HyperBox& hbox1, const HyperBox& hbox2); }; std::ostream& operator << (std::ostream& os, const PointD& pt); std::ostream& operator << (std::ostream& os, const HyperBox& box); class LipschitzFunction { public: function<double(vector<double>)> f; // function from vector<double> to double HyperBox domain; // domain represented as HyperBox function<pair<bool, vector<Interval>>(const HyperBox& hbox)> gradF_interval = [](const HyperBox& hbox) { cout << "empty" << endl; assert(false); return make_pair(false, vector<Interval>()); }; LipschitzFunction(function<double(vector<double>)> f, HyperBox domain, // const DLFunction dlfunc, function<pair<bool, vector<Interval>>(const HyperBox& hbox)> gradF_interval = nullptr) { this->f = f; this->domain = domain; if (gradF_interval != nullptr) { this->gradF_interval = gradF_interval; } } void setGradientFunction(function<pair<bool, vector<Interval>>(const HyperBox& hbox)> gradF_interval) { this->gradF_interval = gradF_interval; } LipschitzFunction operator + (const LipschitzFunction&); LipschitzFunction operator - (const LipschitzFunction&); LipschitzFunction operator - () const; double getUpperBoundCauchySchwarz(const HyperBox& subdomain, PointD x, pair<bool, vector<Interval>> grad) const; double getUpperBoundTriangle(const HyperBox& subdomain, PointD x, pair<bool, vector<Interval>> grad) const; double getUpperBound(const HyperBox& subdomain, PointD x) const; double maximize(double epsilon, int p, Statistics& counter, int maxIter = 1000000000) const; double minimize(double epsilon, int p, Statistics& counter, int maxIter = 1000000000) const; static LipschitzFunction getLinear(HyperBox domain, vector<double> weights, double bias, int degree); }; LipschitzFunction operator * (const double, const LipschitzFunction&); vector<HyperBox> branching(HyperBox& box, int p, pair<bool, vector<Interval>> grad);
031c016e288c30cac2c950c750ea275cfd37801e
6990b0b5e1d4c5d38f5e4ec74551a82962d916e3
/ANR/Gordian/Source/GordianEngine/FileIO/Public/StackableIniReader.h
0ce5c11028e20c15233b28ab811e4f9637d71a52
[]
no_license
danieljluna/ANR
f832c11cd6036235262fb5e3cea41b610e10808d
ce7fcc2dcba4c10a176c04ac10703577c496a7d6
refs/heads/master
2022-12-16T07:52:37.044123
2022-07-24T06:13:47
2022-07-24T06:13:47
119,308,824
0
0
null
2022-11-22T02:14:08
2018-01-28T23:48:05
C
UTF-8
C++
false
false
854
h
StackableIniReader.h
// Gordian by Daniel Luna (2019) #pragma once #include <string> #include "inih/INIReader.h" namespace Gordian { // Reads ini files, mapping string keys to the last declared value found // in the read ini. Can read multiple files, stacking any settings on top // of values found in previous inis. class FStackableIniReader : public INIReader { public: // Initializes this Reader with the given file. explicit FStackableIniReader(const std::string& RootIni); // This will read the passed file as an ini and stomp any matching keys // that already exist in this reader. This will also update the error value. int OverwriteWithIni(const std::string& IniToOverwriteWith); private: // Called to parse new ini values static int ValueHandler(void* user, const char* section, const char* name, const char* value); }; };
3c5a721af0f596993d66cb43f50321c9ef68c490
233b7240a05471c55e43ddd162603520b2db78ca
/musicplayerl_finalone/pausetimer.h
17925ab3f7581c654315e441b6c5d398e05ba990
[]
no_license
xinruxiao/simple-music-player
691fa074aca891f9e4711a472647a44dc38a4554
7d403c46d65aacf2c13b2d22280d7c478423a87d
refs/heads/master
2022-12-03T02:23:28.581018
2020-08-19T16:14:53
2020-08-19T16:14:53
288,779,320
0
0
null
null
null
null
UTF-8
C++
false
false
1,525
h
pausetimer.h
#ifndef PAUSETIMER_H #define PAUSETIMER_H #include <QDialog> #include <QTimer> #include <QTime> namespace Ui { class PauseTimer; } class PauseTimer : public QDialog { Q_OBJECT QTimer *timer; public: explicit PauseTimer(QWidget *parent = 0); ~PauseTimer(); signals: // ่ฟ™ไธชไฟกๅทๆ˜ฏๅ‘็ป™็ˆถ็ช—ๅฃ็š„ใ€‚ void ChildWindowEvent(); private: Ui::PauseTimer *ui; protected slots: // ็‚นๅ‡ปๅญ็ช—ๅฃไธญๆŒ‰้’ฎ็š„slot void ClickedBtn() { // ่งฆๅ‘ๅญ็ช—ๅฃ็š„ไฟกๅท็ป™็ˆถ็ช—ๅฃๆŽฅๆ”ถใ€‚ emit ChildWindowEvent(); } void minutes5() { QTimer *timer= new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(ClickedBtn())); timer->start(300*1000); } void minutes10() { QTimer *timer= new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(ClickedBtn())); timer->start(600*1000); } void minutes20() { QTimer *timer= new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(ClickedBtn())); timer->start(1200*1000); } void minutes30() { QTimer *timer= new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(ClickedBtn())); timer->start(1800*1000); } void minutes45() { QTimer *timer= new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(ClickedBtn())); timer->start(2700*1000); } void minutes60() { QTimer *timer= new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(ClickedBtn())); timer->start(3600*1000); } }; #endif // PAUSETIMER_H
7ebf24a0ca7e678ec66d5822d5c87f23515168a0
268d59529b0b81b906d11151dff53c3c03f49fee
/vstgui4/vstgui/lib/cvstguitimer.cpp
e3101239aa39aebf7fd09d3949ceae102a0d0106
[]
no_license
jazzman31/VST3-SDK
4396d3d3f0b8080b02e43686c72426e3e704dce1
9da168bc8c9207e64b5c9ad0210d642094887f1f
refs/heads/master
2016-09-07T14:20:44.175681
2014-03-06T18:02:06
2014-03-06T18:02:06
17,487,209
1
2
null
null
null
null
UTF-8
C++
false
false
5,202
cpp
cvstguitimer.cpp
//----------------------------------------------------------------------------- // VST Plug-Ins SDK // VSTGUI: Graphical User Interface Framework for VST plugins // // Version 4.2 // //----------------------------------------------------------------------------- // VSTGUI LICENSE // (c) 2013, Steinberg Media Technologies, 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 Steinberg Media Technologies nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- #include "cvstguitimer.h" #if WINDOWS #include <windows.h> #include <list> namespace VSTGUI { static std::list<CVSTGUITimer*> gTimerList; } // namespace #endif #if DEBUG #define DEBUGLOG 0 #endif namespace VSTGUI { //----------------------------------------------------------------------------- IdStringPtr CVSTGUITimer::kMsgTimer = "timer fired"; //----------------------------------------------------------------------------- CVSTGUITimer::CVSTGUITimer (CBaseObject* timerObject, int32_t fireTime) : fireTime (fireTime) , timerObject (timerObject) , platformTimer (0) { } //----------------------------------------------------------------------------- CVSTGUITimer::~CVSTGUITimer () { stop (); } //----------------------------------------------------------------------------- bool CVSTGUITimer::start () { if (platformTimer == 0) { #if MAC CFRunLoopTimerContext timerContext = {0}; timerContext.info = this; platformTimer = CFRunLoopTimerCreate (kCFAllocatorDefault, CFAbsoluteTimeGetCurrent () + fireTime * 0.001f, fireTime * 0.001f, 0, 0, timerCallback, &timerContext); if (platformTimer) CFRunLoopAddTimer (CFRunLoopGetCurrent (), (CFRunLoopTimerRef)platformTimer, kCFRunLoopCommonModes); #elif WINDOWS platformTimer = (void*)SetTimer ((HWND)NULL, (UINT_PTR)0, fireTime, TimerProc); if (platformTimer) gTimerList.push_back (this); #endif #if DEBUGLOG DebugPrint ("Timer started (0x%x)\n", timerObject); #endif } return (platformTimer != 0); } //----------------------------------------------------------------------------- bool CVSTGUITimer::stop () { if (platformTimer) { #if MAC CFRunLoopTimerInvalidate ((CFRunLoopTimerRef)platformTimer); CFRelease ((CFRunLoopTimerRef)platformTimer); #elif WINDOWS KillTimer ((HWND)NULL, (UINT_PTR)platformTimer); std::list<CVSTGUITimer*>::iterator it = gTimerList.begin (); while (it != gTimerList.end ()) { if ((*it) == this) { gTimerList.remove (*it); break; } it++; } #endif platformTimer = 0; #if DEBUGLOG DebugPrint ("Timer stopped (0x%x)\n", timerObject); #endif return true; } return false; } //----------------------------------------------------------------------------- bool CVSTGUITimer::setFireTime (int32_t newFireTime) { if (fireTime != newFireTime) { bool wasRunning = stop (); fireTime = newFireTime; if (wasRunning) return start (); return true; } return false; } #if MAC //----------------------------------------------------------------------------- void CVSTGUITimer::timerCallback (CFRunLoopTimerRef t, void *info) { CVSTGUITimer* timer = (CVSTGUITimer*)info; if (timer->timerObject) timer->timerObject->notify (timer, kMsgTimer); } #elif WINDOWS //------------------------------------------------------------------------ VOID CALLBACK CVSTGUITimer::TimerProc (HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) { std::list<CVSTGUITimer*>::iterator it = gTimerList.begin (); while (it != gTimerList.end ()) { if ((UINT_PTR)((*it)->platformTimer) == idEvent) { (*it)->timerObject->notify ((*it), kMsgTimer); break; } it++; } } #endif } // namespace
400099be51be309949d40d268dc68452d5f8e312
78c67291179b41e9d15c28f78fe2af215c2efda1
/Szkoล‚a Programowania/Rozdziaล‚ 18 Listing 18.9 variadic/Rozdziaล‚ 18 Listing 18.9 variadic/variadic.cpp
d9e526aa8583f5bb39e7240a56469515dd6837aa
[]
no_license
piotrpopiolek/Code
4d2da9e964a2cf11e64b6f8269a64e143ae90c61
4cb7979df951eea18e9986f7dc8d743f64959ffd
refs/heads/master
2021-01-13T10:45:24.855860
2016-12-18T05:35:58
2016-12-18T05:35:58
76,739,674
0
0
null
null
null
null
UTF-8
C++
false
false
473
cpp
variadic.cpp
#include<iostream> #include<string> //definicja dla pustej listy parametrow -- wywolanie konczace rekurencje void show_list3(){} //definicja dla jednego badz wielu parametrow template<typename T, typename... Args> void show_list3(T value, Args... args) { std::cout << value << ", "; show_list3(args...); } int main() { int n = 14; double x = 2.71828; std::string mr = "Mosci String tez!"; show_list3(n, x); show_list3(x*x, '!', 7, mr); system("pause"); return 0; }
ed8da96708bc9e4b300e5fa633fd80391c7dca94
08cde8de37c109b7ee222d01c371b31cdba013b7
/codecheaf/FINXOR.cpp
30621df1b7bfedde4168755b3faefa4e062bc459
[]
no_license
ayanchyaziz123/all-competitive-programming-documents-and-problem-solving
6ec534e70ccc78c7744cb662899ca4639bb047f5
cebc6a6e596a00d4e69d41927f672f82241ef402
refs/heads/master
2023-07-12T07:03:48.966461
2021-08-21T13:53:51
2021-08-21T13:53:51
289,900,378
1
0
null
null
null
null
UTF-8
C++
false
false
1,248
cpp
FINXOR.cpp
#include <bits/stdc++.h> #define mod 1000000007 using namespace std; int subMain() { long long n, answer = 0; cin >> n; vector<long long> xorsum; long long x; for (long long i = 1; i <= 20; i++) { cout << 1 << " " << (1ul << i) << endl; cout.flush(); cin >> x; xorsum.push_back(x); } reverse(xorsum.begin(), xorsum.end()); long long sum = xorsum[0] - n * (1ul << 20); for (long long i = 1; i < xorsum.size(); i++) { if (xorsum[i] >= sum) { xorsum[i] = ((n - (xorsum[i] - sum) / (1ul << (xorsum.size() - i))) / 2); } else { xorsum[i] = (n + (sum - xorsum[i]) / (1ul << (xorsum.size() - i))) / 2; } } for (int i = 1; i < xorsum.size(); i++) { if (xorsum[i] % 2 != 0) answer += 1ul << (xorsum.size() - i); if (sum % 2 != 0) answer++; cout << 2 << " " << answer << endl; cout.flush(); int result; cin >> result; return result; } } int main() { int t = 1; cin >> t; while (t--) { if (!subMain()) break; cout << endl; cout.flush(); } return 0; }
7be7f1a653cac927e7ed6e897546be74d870ef9d
a7adadec859eaf69eebfd6c0fec2e9f63a9e6a2a
/XenoBand/midieditorcore.h
54ca26f3c5e5eac4369732bc79290fc59ff87512
[]
no_license
yuxiangmusic/XenoBand
a01676ef930e304474c618b352ddf44d012882ff
e4dff6e02cec1a0c7057bd6c927edd79c62266b1
refs/heads/master
2020-06-14T01:16:27.967061
2017-04-02T08:12:24
2017-04-02T08:12:24
75,687,529
0
2
null
null
null
null
UTF-8
C++
false
false
1,072
h
midieditorcore.h
#ifndef MIDIEDITORCORE_H #define MIDIEDITORCORE_H #include "core.h" #include "midinoteevent.h" #include <QGraphicsRectItem> class MIDIEditorCore { public: MIDIEditorCore(); QList<MIDINoteEvent *> noteEventList; /* binary search for position and then insert */ void insertNoteEvent(MIDINoteEvent *event); /* binary search for position and then remove */ void removeNoteEvent(MIDINoteEvent *event); /* Removes the note event on given index in note event list */ void removeNoteEvent(int index); /* remove all events */ void clear(); /* Returns the appropriate index to insert into note event list for given start position */ int getIndex(int position); /* Returns an on event corresponding to given MIDI note */ MIDINoteEvent* getOnEvent(QGraphicsRectItem *item); /* Returns an off event corresponding to given MIDI note */ MIDINoteEvent* getOffEvent(QGraphicsRectItem *item); private: /* Fixed size of the height of each note representation */ int yPerPitch; }; #endif // MIDITRACKCORE_H
5eaca42806001a7f9507f830b7c354e830aca7a0
ae05c77c2417098b1cd6d19dda1087f0dc97ba40
/Tictocs-master/PinControl.h
571534dc02d5dee10023df166969b2b8fa17f436
[]
no_license
francoiswindels/arduino-libraries
4e6238a12f85d351d0d44e11663b600b720ab573
784c18797333ccfe0054ff9b76996b13e45a46e1
refs/heads/master
2021-01-23T16:13:31.581211
2017-06-04T03:17:58
2017-06-04T03:17:58
93,286,909
0
0
null
null
null
null
UTF-8
C++
false
false
1,788
h
PinControl.h
/* Copyright (C) 2012 J. Coliz <maniacbug@ymail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. */ #ifndef __PINCONTROL_H__ #define __PINCONTROL_H__ // STL includes // C includes // Library includes #include <Connector.h> // Project includes namespace Tictocs { /** * Control a single GPIO pin based purely on signals */ class PinControl: public Connectable { private: uint8_t pin; /**< The pin being controlled */ uint8_t signal_low; /**< The signal which sets the pin LOW */ uint8_t signal_high; /**< The signal which sets the pin HIGH */ protected: virtual void onNotify(const Connectable*, uint8_t signal); /** * Get the pin being controlled * * @return The pin being controlled */ uint8_t get_pin(void) const { return pin; } /** * Toggle the current value of the pin */ void toggle(void); public: PinControl(Connector& _conn,int _pin,uint8_t _signal_low, uint8_t _signal_high): Connectable(_conn), pin(_pin), signal_low(_signal_low), signal_high(_signal_high) {} /** * Begin operation. Call only once, after static init complete. */ void begin(void); /** * Begin operation, and listen to a particular object * * @param _whom To whom we should listen, or NULL for listen to all */ void begin(Connectable* _whom) { begin(); listen(_whom); } /** * Listen to a particular object. When this object raises the signals * we're listening for, we'll act. * * @param _whom To whom we should listen, or NULL for listen to all */ void listen(Connectable* _whom); }; } // namespace Tictocs #endif // __PINCONTROL_H__ // vim:cin:ai:sts=2 sw=2 ft=cpp
97e82df24041c07f09a180623a3ac1ae8c1dff0e
e0c04fd4b5150b3f969f3e3a525d480c86bced6f
/C++ Fibonacci Sayฤฑsฤฑ.cpp
352c73824b561fcee17209e43c8b91d2a6512263
[]
no_license
vankenobi/my_first_examples
b709b432eb507ccf573656a587662360286811de
3ede50c1448fe4a64c5c5fad23bc5a1aab3c33fe
refs/heads/master
2021-07-11T18:47:20.805584
2020-06-14T18:11:27
2020-06-14T18:11:27
148,028,984
3
0
null
null
null
null
UTF-8
C++
false
false
378
cpp
C++ Fibonacci Sayฤฑsฤฑ.cpp
#include<iostream> using namespace std; int num1=1, num2 = 1,toplam = 0, r; int main() { cout << "Lutfen pozitif bir sayi giriniz: "; cin >> r; cout <<"Fibonacci Series:"<<endl<<toplam <<endl<<num1<<endl<<num2<<endl; toplam = num1 + num2; while (toplam<=r) { cout << toplam << endl; num1 = num2; num2 = toplam; toplam = num1 + num2; } system("PAUSE"); }
0c69b6bbe111ca0743f0084532ec07b00a8ccb46
02bd12b9b15cf70ed33bbf2dd3fec3539ec6e91d
/SampleCode/kennir-drawstory_client/drawstory/Classes/PaintingScene_PaintingLayer.h
fd2ec847045fd835b9206d6df27e3b399d8c2a85
[]
no_license
zephyroal/CC2DXLuaSample2
f146993b1411f895ed44dc9e217519ee80e6d3bc
f6d9540ac32aef9231fe853bded0f696fbfef7f0
refs/heads/master
2021-01-04T14:10:52.023053
2012-10-15T12:08:26
2012-10-15T12:08:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
830
h
PaintingScene_PaintingLayer.h
// // PaintingScene_PaintingLayer.h // drawstory // // Created by ๅผ  ้–ๅฎ‡ on 12-4-2. // Copyright (c) 2012ๅนด __MyCompanyName__. All rights reserved. // #ifndef drawstory_PaintingScene_PaintingLayer_h #define drawstory_PaintingScene_PaintingLayer_h #include "cocos2d.h" #include "Brush.h" #include "PaintCommand.h" namespace PaintingScene { class CommandBarLayer; class PaintingCanvasLayer; class PaintingLayer : public cocos2d::CCLayer{ public: LAYER_NODE_FUNC(PaintingLayer) PaintingLayer(); virtual ~PaintingLayer(); virtual bool init(); virtual void onEnter(); virtual void onExit(); virtual bool ccTouchBegan(cocos2d::CCTouch* touch,cocos2d::CCEvent* event); protected: }; } #endif
bea103f252b19b383b6bf2b1992a8821235cd170
120710380f3aa89cae316ffa84f2944c17b56535
/day06/complex.cpp
10b9059196332e8016632f8c0f2ed89663b63712
[]
no_license
liuqingtao/daneicplusplus
1ca51b22803ada435b1216e4763f8e5a88c6aaef
2be2a7ebd71542c6ca526732d92ff98fb93904c4
refs/heads/master
2020-03-19T00:13:06.419057
2018-06-12T03:10:29
2018-06-12T03:10:29
135,463,216
0
0
null
null
null
null
UTF-8
C++
false
false
315
cpp
complex.cpp
#include<iostream> using namespace std; class Complex{ public: Complex(int r=0,int i=0):m_r(r),m_i(i){} void print(void) const{ cout<<'('<<m_r<<'+'<<m_i<<"i)"<<endl; } private: int m_r; int m_i; }; int main(void){ Complex c1(1,2); Complex c2(3,4); c1.print(); return 0; }
1969c26a4609fb335f7258080e1cc69dfda271e1
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/admin/pchealth/upload/client/uploadmanager/module.cpp
7ddd7f81b71194534a7ca792eefb3550240d13cb
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
20,973
cpp
module.cpp
/****************************************************************************** Copyright (c) 2000 Microsoft Corporation Module Name: module.cpp Abstract: This file contains the implementation of the CServiceModule class, which is used to handling service-related routines. Revision History: Davide Massarenti (Dmassare) 03/14/2000 created ******************************************************************************/ #include "stdafx.h" ///////////////////////////////////////////////////////////////////////////// DWORD dwTimeOut = 8*1000; // time for EXE to be idle before shutting down const DWORD dwPause = 1000; // time to wait for threads to finish up CServiceModule _Module; MPC::NTEvent g_NTEvents; CMPCConfig g_Config; ///////////////////////////////////////////////////////////////////////////// // // These variables control the overriding of properties for debug. // bool g_Override_History = false; UL_HISTORY g_Override_History_Value = UL_HISTORY_NONE; bool g_Override_Persist = false; VARIANT_BOOL g_Override_Persist_Value = false; bool g_Override_Compressed = false; VARIANT_BOOL g_Override_Compressed_Value = false; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// const WCHAR c_szMessageFile [] = L"%WINDIR%\\PCHealth\\UploadLB\\Binaries\\UploadM.exe"; const WCHAR c_szRegistryLog [] = L"SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\UploadM"; const WCHAR c_szRegistryLog_File [] = L"EventMessageFile"; const WCHAR c_szRegistryLog_Flags[] = L"TypesSupported"; ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// #ifdef DEBUG #define DEBUG_REGKEY L"SOFTWARE\\Microsoft\\PCHealth\\UploadM\\Debug" #define DEBUG_TIMEOUT L"TIMEOUT" #define DEBUG_BREAKONSTART L"BREAKONSTART" #define DEBUG_HISTORY L"HISTORY" #define DEBUG_PERSIST L"PERSIST" #define DEBUG_COMPRESSED L"COMPRESSED" void CServiceModule::ReadDebugSettings() { __ULT_FUNC_ENTRY( "CServiceModule::ReadDebugSettings" ); HRESULT hr; MPC::RegKey rkBase; bool fFound; __MPC_EXIT_IF_METHOD_FAILS(hr, rkBase.SetRoot( HKEY_LOCAL_MACHINE )); __MPC_EXIT_IF_METHOD_FAILS(hr, rkBase.Attach ( DEBUG_REGKEY )); __MPC_EXIT_IF_METHOD_FAILS(hr, rkBase.Exists ( fFound )); if(fFound) { CComVariant vValue; __MPC_EXIT_IF_METHOD_FAILS(hr, rkBase.get_Value( vValue, fFound, DEBUG_BREAKONSTART )); if(fFound && vValue.vt == VT_I4) { if(vValue.lVal == 1) DebugBreak(); if(vValue.lVal == 2) while(vValue.lVal) ::Sleep( 100 ); } __MPC_EXIT_IF_METHOD_FAILS(hr, rkBase.get_Value( vValue, fFound, DEBUG_TIMEOUT )); if(fFound && vValue.vt == VT_I4) { dwTimeOut = 1000 * vValue.lVal; } __MPC_EXIT_IF_METHOD_FAILS(hr, rkBase.get_Value( vValue, fFound, DEBUG_HISTORY )); if(fFound && vValue.vt == VT_I4 && vValue.lVal != -1) { g_Override_History = true; g_Override_History_Value = (UL_HISTORY)vValue.lVal; } __MPC_EXIT_IF_METHOD_FAILS(hr, rkBase.get_Value( vValue, fFound, DEBUG_PERSIST )); if(fFound && vValue.vt == VT_I4 && vValue.lVal != -1) { g_Override_Persist = true; g_Override_Persist_Value = vValue.lVal ? VARIANT_TRUE : VARIANT_FALSE; } __MPC_EXIT_IF_METHOD_FAILS(hr, rkBase.get_Value( vValue, fFound, DEBUG_COMPRESSED )); if(fFound && vValue.vt == VT_I4 && vValue.lVal != -1) { g_Override_Compressed = true; g_Override_Compressed_Value = vValue.lVal ? VARIANT_TRUE : VARIANT_FALSE; } } __ULT_FUNC_CLEANUP; } #endif ///////////////////////////////////////////////////////////////////////////// static const WCHAR s_SvcHost[] = L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Svchost"; static const WCHAR s_Key [] = L"System\\CurrentControlSet\\Services\\%s"; static const WCHAR s_Key2 [] = L"\\Parameters"; static const WCHAR s_Name [] = L"ServiceDll"; static const WCHAR s_Value[] = L"%WINDIR%\\PCHealth\\HelpCtr\\Binaries\\pchsvc.dll"; static HRESULT ServiceHost_Install( LPCWSTR szName, LPCWSTR szGroup ) { __ULT_FUNC_ENTRY( "ServiceHost_Install" ); HRESULT hr; // // Register the message file into the registry. // { MPC::wstring szPath ( c_szMessageFile ); MPC::SubstituteEnvVariables( szPath ); MPC::RegKey rkEventLog; CComVariant vValue; __MPC_EXIT_IF_METHOD_FAILS(hr, rkEventLog.SetRoot( HKEY_LOCAL_MACHINE, KEY_ALL_ACCESS )); __MPC_EXIT_IF_METHOD_FAILS(hr, rkEventLog.Attach ( c_szRegistryLog )); __MPC_EXIT_IF_METHOD_FAILS(hr, rkEventLog.Create ( )); vValue = szPath.c_str(); __MPC_EXIT_IF_METHOD_FAILS(hr, rkEventLog.put_Value( vValue, c_szRegistryLog_File )); vValue = (long)0x1F ; __MPC_EXIT_IF_METHOD_FAILS(hr, rkEventLog.put_Value( vValue, c_szRegistryLog_Flags )); } { WCHAR rgRegPath[_MAX_PATH]; swprintf( rgRegPath, s_Key, szName ); wcscat( rgRegPath, s_Key2 ); __MPC_EXIT_IF_METHOD_FAILS(hr, MPC::RegKey_Value_Write( s_Value, rgRegPath, s_Name, HKEY_LOCAL_MACHINE, true )); } { MPC::RegKey rk; MPC::WStringList lstValue; bool fFound; bool fGot = false; __MPC_EXIT_IF_METHOD_FAILS(hr, rk.SetRoot( HKEY_LOCAL_MACHINE, KEY_ALL_ACCESS )); __MPC_EXIT_IF_METHOD_FAILS(hr, rk.Attach ( s_SvcHost )); __MPC_EXIT_IF_METHOD_FAILS(hr, rk.Create ( )); if(SUCCEEDED(rk.Read( lstValue, fFound, szGroup ))) { for(MPC::WStringIterConst it = lstValue.begin(); it != lstValue.end(); it++) { if(!MPC::StrICmp( *it, szName )) { fGot = true; break; } } } if(fGot == false) { lstValue.push_back( szName ); __MPC_EXIT_IF_METHOD_FAILS(hr, rk.Write( lstValue, szGroup )); } } hr = S_OK; __ULT_FUNC_CLEANUP; __ULT_FUNC_EXIT(hr); } static HRESULT ServiceHost_Uninstall( LPCWSTR szName, LPCWSTR szGroup ) { __ULT_FUNC_ENTRY( "ServiceHost_Uninstall" ); HRESULT hr; { WCHAR rgRegPath[_MAX_PATH]; swprintf( rgRegPath, s_Key, szName ); MPC::RegKey rk; __MPC_EXIT_IF_METHOD_FAILS(hr, rk.SetRoot( HKEY_LOCAL_MACHINE, KEY_ALL_ACCESS )); __MPC_EXIT_IF_METHOD_FAILS(hr, rk.Attach ( rgRegPath )); (void)rk.Delete( /*fDeep*/true ); } { MPC::RegKey rk; MPC::WStringList lstValue; bool fFound; __MPC_EXIT_IF_METHOD_FAILS(hr, rk.SetRoot( HKEY_LOCAL_MACHINE, KEY_ALL_ACCESS )); __MPC_EXIT_IF_METHOD_FAILS(hr, rk.Attach ( s_SvcHost )); if(SUCCEEDED(rk.Read( lstValue, fFound, szGroup ))) { MPC::WStringIterConst it = lstValue.begin(); bool fGot = false; while(it != lstValue.end()) { MPC::WStringIterConst it2 = it++; if(!MPC::StrICmp( *it2, szName )) { lstValue.erase( it2 ); fGot = true; } } if(fGot) { __MPC_EXIT_IF_METHOD_FAILS(hr, rk.Write( lstValue, szGroup )); } } } hr = S_OK; __ULT_FUNC_CLEANUP; __ULT_FUNC_EXIT(hr); } ///////////////////////////////////////////////////////////////////////////// CServiceModule::CServiceModule() { m_hEventShutdown = NULL; // HANDLE m_hEventShutdown; m_dwThreadID = 0; // DWORD m_dwThreadID; m_hMonitor = NULL; // HANDLE m_hMonitor; m_bActivity = FALSE; // BOOL m_bActivity; // m_szServiceName = NULL; // LPCWSTR m_szServiceName; m_iDisplayName = 0; // UINT m_iDisplayName; m_iDescription = 0; // UINT m_iDescription; m_hServiceStatus = NULL; // SERVICE_STATUS_HANDLE m_hServiceStatus; // SERVICE_STATUS m_status; m_bService = FALSE; // BOOL m_bService; ::ZeroMemory( &m_status, sizeof( m_status ) ); } CServiceModule::~CServiceModule() { if(m_hEventShutdown) ::CloseHandle( m_hEventShutdown ); if(m_hMonitor ) ::CloseHandle( m_hMonitor ); } ///////////////////////////////////////////////////////////////////////////// LONG CServiceModule::Lock() { LONG lCount = CComModule::Lock(); return lCount; } LONG CServiceModule::Unlock() { LONG lCount = CComModule::Unlock(); if(lCount == 0) { m_bActivity = TRUE; if(m_hEventShutdown) ::SetEvent( m_hEventShutdown ); // tell monitor that we transitioned to zero } return lCount; } void CServiceModule::MonitorShutdown() { while(1) { DWORD dwWait; m_bActivity = FALSE; dwWait = ::WaitForSingleObject( m_hEventShutdown, dwTimeOut ); if(dwWait == WAIT_OBJECT_0) continue; // We are alive... if(g_Root.CanContinue()) continue; // // If no activity let's really bail. // if(m_bActivity == FALSE && m_nLockCnt <= 0) { ::CoSuspendClassObjects(); if(m_bActivity == FALSE && m_nLockCnt <= 0) break; } } ForceShutdown(); } void CServiceModule::ForceShutdown() { // // Tell process to exit. // ::PostThreadMessage( m_dwThreadID, WM_QUIT, 0, 0 ); } BOOL CServiceModule::StartMonitor() { DWORD dwThreadID; m_hMonitor = ::CreateThread( NULL, 0, _Monitor, this, 0, &dwThreadID ); if(m_hMonitor == NULL) return FALSE; return TRUE; } ///////////////////////////////////////////////////////////////////////////// HRESULT CServiceModule::RegisterServer( BOOL bRegTypeLib, BOOL bService, LPCWSTR szSvcHostGroup ) { HRESULT hr; // Remove any previous service since it may point to the incorrect file Uninstall( szSvcHostGroup ); if(bService) { // Create service Install( szSvcHostGroup ); } // Add object entries if(FAILED(hr = CComModule::RegisterServer( TRUE ))) return hr; if(FAILED(hr = _Module.UpdateRegistryFromResource( IDR_UPLOADMANAGER, TRUE ))) return hr; return S_OK; } HRESULT CServiceModule::UnregisterServer( LPCWSTR szSvcHostGroup ) { HRESULT hr; // Remove service Uninstall( szSvcHostGroup ); // Remove object entries if(FAILED(hr = CComModule::UnregisterServer( TRUE ))) return hr; if(FAILED(hr = _Module.UpdateRegistryFromResource( IDR_UPLOADMANAGER, FALSE ))) return hr; return S_OK; } void CServiceModule::Init( _ATL_OBJMAP_ENTRY* p, HINSTANCE h, LPCWSTR szServiceName, UINT iDisplayName, UINT iDescription, const GUID* plibid ) { CComModule::Init( p, h, plibid ); m_szServiceName = szServiceName; m_iDisplayName = iDisplayName; m_iDescription = iDescription; // set up the initial service status m_hServiceStatus = NULL; m_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; m_status.dwCurrentState = SERVICE_STOPPED; m_status.dwControlsAccepted = SERVICE_ACCEPT_STOP; m_status.dwWin32ExitCode = 0; m_status.dwServiceSpecificExitCode = 0; m_status.dwCheckPoint = 0; m_status.dwWaitHint = 0; } BOOL CServiceModule::IsInstalled() { BOOL bResult = FALSE; SC_HANDLE hSCM = ::OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS ); if((hSCM = ::OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS ))) { SC_HANDLE hService; if((hService = ::OpenServiceW( hSCM, m_szServiceName, SERVICE_QUERY_CONFIG ))) { bResult = TRUE; ::CloseServiceHandle( hService ); } ::CloseServiceHandle( hSCM ); } return bResult; } BOOL CServiceModule::Install( LPCWSTR szSvcHostGroup ) { BOOL bResult = FALSE; SC_HANDLE hSCM; if((hSCM = ::OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS ))) { LPCWSTR szDisplayName; WCHAR rgDisplayName[512]; WCHAR rgDescription[512]; WCHAR rgFilePath [_MAX_PATH]; SC_HANDLE hService; DWORD dwServiceType; OSVERSIONINFOEXW ver; DWORD dwStartType; if(szSvcHostGroup) { dwServiceType = SERVICE_WIN32_SHARE_PROCESS; swprintf( rgFilePath, L"%%SystemRoot%%\\System32\\svchost.exe -k %s", szSvcHostGroup ); } else { dwServiceType = SERVICE_WIN32_OWN_PROCESS; ::GetModuleFileNameW( NULL, rgFilePath, _MAX_PATH ); } if(::LoadStringW( _Module.GetResourceInstance(), m_iDisplayName, rgDisplayName, MAXSTRLEN(rgDisplayName) ) != 0) { szDisplayName = rgDisplayName; } else { szDisplayName = m_szServiceName; } if(::LoadStringW( _Module.GetResourceInstance(), m_iDescription, rgDescription, MAXSTRLEN(rgDescription) ) == 0) { rgDescription[0] = 0; } ::ZeroMemory( &ver, sizeof(ver) ); ver.dwOSVersionInfoSize = sizeof(ver); ::GetVersionExW( (LPOSVERSIONINFOW)&ver ); if(ver.wSuiteMask & VER_SUITE_DATACENTER) { dwStartType = SERVICE_DISABLED; } else { dwStartType = SERVICE_DEMAND_START; } hService = ::OpenServiceW( hSCM, m_szServiceName, SERVICE_QUERY_CONFIG ); if(hService == NULL) { hService = ::CreateServiceW( hSCM , m_szServiceName , szDisplayName , SERVICE_ALL_ACCESS , dwServiceType , dwStartType , SERVICE_ERROR_NORMAL, rgFilePath , NULL , NULL , L"RPCSS\0" , NULL , NULL ); } if(hService) { if(rgDescription[0]) { SERVICE_DESCRIPTIONW desc; ::ZeroMemory( &desc , sizeof(desc ) ); SERVICE_FAILURE_ACTIONSW recovery; ::ZeroMemory( &recovery, sizeof(recovery) ); SC_ACTION actions[] = { { SC_ACTION_RESTART, 100 }, { SC_ACTION_RESTART, 100 }, { SC_ACTION_NONE , 100 }, }; desc.lpDescription = rgDescription; recovery.dwResetPeriod = 24 * 60 * 60; // 1 day recovery.cActions = ARRAYSIZE(actions); recovery.lpsaActions = actions; ::ChangeServiceConfig2W( hService, SERVICE_CONFIG_DESCRIPTION , &desc ); ::ChangeServiceConfig2W( hService, SERVICE_CONFIG_FAILURE_ACTIONS, &recovery ); } if(szSvcHostGroup) { if(SUCCEEDED(ServiceHost_Install( m_szServiceName, szSvcHostGroup ))) { bResult = TRUE; } } else { bResult = TRUE; } ::CloseServiceHandle( hService ); } if(bResult == FALSE) { (void)g_NTEvents.LogEvent( EVENTLOG_ERROR_TYPE, UPLOADM_ERR_CANNOTCREATESERVICE, NULL ); } ::CloseServiceHandle( hSCM ); } else { (void)g_NTEvents.LogEvent( EVENTLOG_ERROR_TYPE, UPLOADM_ERR_CANNOTOPENSCM, NULL ); } return bResult; } BOOL CServiceModule::Uninstall( LPCWSTR szSvcHostGroup ) { BOOL bResult = FALSE; SC_HANDLE hSCM; if((hSCM = ::OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS ))) { SC_HANDLE hService; if((hService = ::OpenServiceW( hSCM, m_szServiceName, SERVICE_STOP | DELETE ))) { SERVICE_STATUS status; ::ControlService( hService, SERVICE_CONTROL_STOP, &status ); bResult = ::DeleteService( hService ); if(bResult) { ::Sleep( 2000 ); // Let the service stop down... if(szSvcHostGroup) { if(FAILED(ServiceHost_Uninstall( m_szServiceName, szSvcHostGroup ))) { bResult = FALSE; } } } if(bResult == FALSE) { (void)g_NTEvents.LogEvent( EVENTLOG_ERROR_TYPE, UPLOADM_ERR_CANNOTDELETESERVICE, NULL ); } ::CloseServiceHandle( hService ); } ::CloseServiceHandle( hSCM ); } else { (void)g_NTEvents.LogEvent( EVENTLOG_ERROR_TYPE, UPLOADM_ERR_CANNOTOPENSCM, NULL ); } return bResult; } ////////////////////////////////////////////////////////////////////////////////////////////// // Service startup and registration BOOL CServiceModule::Start( BOOL bService ) { SERVICE_TABLE_ENTRYW st[] = { { (LPWSTR)m_szServiceName, _ServiceMain }, { NULL , NULL } }; m_hEventShutdown = ::CreateEvent( NULL, FALSE, FALSE, NULL ); if(m_hEventShutdown == NULL) return FALSE; if((m_bService = bService) && !::StartServiceCtrlDispatcherW( st )) { DWORD dwRes = ::GetLastError(); m_bService = FALSE; } if(m_bService == FALSE) { if(StartMonitor() == FALSE) return FALSE; if(FAILED(Run())) return FALSE; } return TRUE; } void CServiceModule::ServiceMain( DWORD dwArgc, LPWSTR lpszArgv[] ) { // Register the control request handler m_status.dwCurrentState = SERVICE_START_PENDING; if((m_hServiceStatus = ::RegisterServiceCtrlHandlerW( m_szServiceName, _Handler ))) { SetServiceStatus( SERVICE_START_PENDING ); m_status.dwWin32ExitCode = S_OK; m_status.dwCheckPoint = 0; m_status.dwWaitHint = 0; // When the Run function returns, the service has stopped. Run(); SetServiceStatus( SERVICE_STOPPED ); (void)g_NTEvents.LogEvent( EVENTLOG_INFORMATION_TYPE, UPLOADM_INFO_STOPPED, NULL ); } else { (void)g_NTEvents.LogEvent( EVENTLOG_ERROR_TYPE, UPLOADM_ERR_REGISTERHANDLER, NULL ); } } void CServiceModule::Handler( DWORD dwOpcode ) { switch(dwOpcode) { case SERVICE_CONTROL_STOP: SetServiceStatus( SERVICE_STOP_PENDING ); ForceShutdown(); break; case SERVICE_CONTROL_PAUSE: break; case SERVICE_CONTROL_CONTINUE: break; case SERVICE_CONTROL_INTERROGATE: break; case SERVICE_CONTROL_SHUTDOWN: break; default: (void)g_NTEvents.LogEvent( EVENTLOG_ERROR_TYPE, UPLOADM_ERR_BADSVCREQUEST, NULL ); } } HRESULT CServiceModule::Run() { __ULT_FUNC_ENTRY( "CServiceModule::Run" ); HRESULT hr; MSG msg; m_dwThreadID = ::GetCurrentThreadId(); __MPC_EXIT_IF_METHOD_FAILS(hr, ::CoInitializeEx( NULL, COINIT_MULTITHREADED )); // We need to be a multi-threaded application. __MPC_EXIT_IF_METHOD_FAILS(hr, RegisterClassObjects( CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER, REGCLS_MULTIPLEUSE )); (void)g_NTEvents.LogEvent( EVENTLOG_INFORMATION_TYPE, UPLOADM_INFO_STARTED, NULL ); if(m_bService) { SetServiceStatus( SERVICE_RUNNING ); } // // Load the state of the queue. // __MPC_EXIT_IF_METHOD_FAILS(hr, g_Root.Init()); while(::GetMessage( &msg, 0, 0, 0 )) { ::DispatchMessage( &msg ); } _Module.RevokeClassObjects(); ::Sleep( dwPause ); //wait for any threads to finish hr = S_OK; __ULT_FUNC_CLEANUP; __ULT_FUNC_EXIT(hr); } void CServiceModule::SetServiceStatus( DWORD dwState ) { m_status.dwCurrentState = dwState; ::SetServiceStatus( m_hServiceStatus, &m_status ); } //////////////////////////////////////////////////////////////////////////////// void WINAPI CServiceModule::_ServiceMain( DWORD dwArgc, LPWSTR* lpszArgv ) { _Module.ServiceMain( dwArgc, lpszArgv ); } void WINAPI CServiceModule::_Handler( DWORD dwOpcode ) { _Module.Handler( dwOpcode ); } DWORD WINAPI CServiceModule::_Monitor( void* pv ) { ((CServiceModule*)pv)->MonitorShutdown(); return 0; }
55e3d34c592100a9ce44d7239a7a92921dffaf72
8a8087142e60dbf5c10568604a6c665dcf60496e
/ATV/1165/main.cpp
0acbca0822f68d93e24226d0fa01e92386e3b604
[]
no_license
luizalexandrewarchive/URIOnlineJudge
786b0b7c8584f1db3f2b99552455b7b22bf2ba9a
11644dbe76d2f8a30af8d2997e4b506f8c0f8e88
refs/heads/master
2021-06-19T07:50:47.408237
2017-05-16T00:22:22
2017-05-16T00:22:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
745
cpp
main.cpp
#include <iostream> #include <stdio.h> #include <math.h> using namespace std; int main(){ int i,j,k,nuu,n,count=0; while(scanf("%d",&k)==1){ for(i=1;i<=k;i++){ scanf("%d",&n); if(n==1 || n==0){ printf("%d nao eh primo\n",n); }else { count=0; nuu=sqrt(n); for(j=2;j<=nuu;j++){ if(n%j==0){ count=1; break; } } if(count==1){ printf("%d nao eh primo\n",n); }else{ printf("%d eh primo\n",n); } count=0; } } } }
39285eb2d84750e25e1201d033601fa0eaea453d
274e1169a03062140871e4fddaf4836e30cce503
/src/LogATE/Net/TcpJsonPerformanceTest.manual.cpp
10f6109d4e3d2b71b4aedb066d03f25f11475554
[ "BSD-2-Clause" ]
permissive
el-bart/LogATE
38df676a9874c42d9ec862cf3090e0e31bc134f2
88569417c0758318a049205bb69f3ecee4d13a32
refs/heads/master
2023-08-29T14:45:26.924602
2023-07-25T17:55:13
2023-07-25T17:55:13
152,469,962
3
3
null
null
null
null
UTF-8
C++
false
false
3,233
cpp
TcpJsonPerformanceTest.manual.cpp
#include "LogATE/Net/TcpServer.hpp" #include "LogATE/Net/TcpRawClient.hpp" #include <But/Threading/JoiningThread.hpp> #include <iostream> #include <thread> #include <chrono> using Clock = std::chrono::system_clock; using Thread = But::Threading::JoiningThread<std::thread>; int main() { const auto port = LogATE::Net::Port{6666}; const auto workers = But::makeSharedNN<LogATE::Utils::WorkerThreads>(); const auto parseMode = LogATE::Net::TcpServer::JsonParsingMode::ParseToEndOfJson; const auto keyPath = LogATE::Tree::Path::parse(".But::PreciseDT"); LogATE::Net::TcpServer server{workers, port, keyPath, parseMode}; LogATE::Net::TcpRawClient client{"127.0.0.1", port}; const auto N = 1'000'000u; const auto testLog = std::string{ #if 1 R"({ "PING": { "PONG": { "narf": { "fran": "a_c" } } }, "foo": { "bar": "a/c" }, "array": [ { "one": 1 }, { "two": 2 } ] })" #else R"({ "one": { "PING": { "PONG": { "narf": 42 } } }, "two": { "PING": { "PONG": { "narf": { "fran": "aaa" } } } }, "three": { "foo": { "bar": "xxx" } }, "four": { "foo": { "bar": "yyy" } }, "five": { "foo": [ { "one": 1 }, { "two": 2 } ] } })" #endif }; // string Thread thClient{ [&] { for(auto i=0u; i<N; ++i) client.write(testLog); } }; const auto printDelay = std::chrono::seconds{1}; auto deadline = Clock::now(); for(auto i=0u; i<N;) { i += server.readNextLogs().size(); const auto now = Clock::now(); if( now > deadline ) { deadline += printDelay; std::cout << i << " / " << N << std::endl; } } }
2c784f5bbdba72c436d95c02f2dd06c33cadee3a
0e0a39875ad5089ca1d49d1e1c68d6ef337941ff
/deps/NVIDIATextureTools/src/nvimage/DirectDrawSurface.h
9a964e4aa0d55bc001023641c348234f4734015b
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
FloodProject/flood
aeb30ba9eb969ec2470bd34be8260423cd83ab9f
466ad3f4d8758989b883f089f67fbc24dcb29abd
refs/heads/master
2020-05-18T01:56:45.619407
2016-02-14T17:00:53
2016-02-14T17:18:40
4,555,061
6
2
null
2014-06-21T18:08:53
2012-06-05T02:49:39
C#
UTF-8
C++
false
false
12,100
h
DirectDrawSurface.h
// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com> // // 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. #pragma once #ifndef NV_IMAGE_DIRECTDRAWSURFACE_H #define NV_IMAGE_DIRECTDRAWSURFACE_H #include "nvimage.h" #if !defined(MAKEFOURCC) #define MAKEFOURCC(ch0, ch1, ch2, ch3) \ (uint(uint8(ch0)) | (uint(uint8(ch1)) << 8) | \ (uint(uint8(ch2)) << 16) | (uint(uint8(ch3)) << 24 )) #endif namespace nv { class Image; class Stream; struct ColorBlock; enum DDPF { DDPF_ALPHAPIXELS = 0x00000001U, DDPF_ALPHA = 0x00000002U, DDPF_FOURCC = 0x00000004U, DDPF_RGB = 0x00000040U, DDPF_PALETTEINDEXED1 = 0x00000800U, DDPF_PALETTEINDEXED2 = 0x00001000U, DDPF_PALETTEINDEXED4 = 0x00000008U, DDPF_PALETTEINDEXED8 = 0x00000020U, DDPF_LUMINANCE = 0x00020000U, DDPF_ALPHAPREMULT = 0x00008000U, // Custom NVTT flags. DDPF_NORMAL = 0x80000000U, DDPF_SRGB = 0x40000000U, }; enum D3DFORMAT { // 32 bit RGB formats. D3DFMT_R8G8B8 = 20, D3DFMT_A8R8G8B8 = 21, D3DFMT_X8R8G8B8 = 22, D3DFMT_R5G6B5 = 23, D3DFMT_X1R5G5B5 = 24, D3DFMT_A1R5G5B5 = 25, D3DFMT_A4R4G4B4 = 26, D3DFMT_R3G3B2 = 27, D3DFMT_A8 = 28, D3DFMT_A8R3G3B2 = 29, D3DFMT_X4R4G4B4 = 30, D3DFMT_A2B10G10R10 = 31, D3DFMT_A8B8G8R8 = 32, D3DFMT_X8B8G8R8 = 33, D3DFMT_G16R16 = 34, D3DFMT_A2R10G10B10 = 35, D3DFMT_A16B16G16R16 = 36, // Palette formats. D3DFMT_A8P8 = 40, D3DFMT_P8 = 41, // Luminance formats. D3DFMT_L8 = 50, D3DFMT_A8L8 = 51, D3DFMT_A4L4 = 52, D3DFMT_L16 = 81, // Floating point formats D3DFMT_R16F = 111, D3DFMT_G16R16F = 112, D3DFMT_A16B16G16R16F = 113, D3DFMT_R32F = 114, D3DFMT_G32R32F = 115, D3DFMT_A32B32G32R32F = 116, }; enum FOURCC { FOURCC_NVTT = MAKEFOURCC('N', 'V', 'T', 'T'), FOURCC_DDS = MAKEFOURCC('D', 'D', 'S', ' '), FOURCC_DXT1 = MAKEFOURCC('D', 'X', 'T', '1'), FOURCC_DXT2 = MAKEFOURCC('D', 'X', 'T', '2'), FOURCC_DXT3 = MAKEFOURCC('D', 'X', 'T', '3'), FOURCC_DXT4 = MAKEFOURCC('D', 'X', 'T', '4'), FOURCC_DXT5 = MAKEFOURCC('D', 'X', 'T', '5'), FOURCC_RXGB = MAKEFOURCC('R', 'X', 'G', 'B'), FOURCC_ATI1 = MAKEFOURCC('A', 'T', 'I', '1'), FOURCC_ATI2 = MAKEFOURCC('A', 'T', 'I', '2'), FOURCC_A2XY = MAKEFOURCC('A', '2', 'X', 'Y'), FOURCC_DX10 = MAKEFOURCC('D', 'X', '1', '0'), FOURCC_UVER = MAKEFOURCC('U', 'V', 'E', 'R'), }; // D3D1x resource dimensions. enum DDS_DIMENSION // D3D10_RESOURCE_DIMENSION { DDS_DIMENSION_UNKNOWN = 0, DDS_DIMENSION_BUFFER = 1, DDS_DIMENSION_TEXTURE1D = 2, DDS_DIMENSION_TEXTURE2D = 3, DDS_DIMENSION_TEXTURE3D = 4, }; enum DDS_MISC_FLAG { DDS_MISC_TEXTURECUBE = 0x4, }; // DXGI formats. enum DXGI_FORMAT { DXGI_FORMAT_UNKNOWN = 0, DXGI_FORMAT_R32G32B32A32_TYPELESS = 1, DXGI_FORMAT_R32G32B32A32_FLOAT = 2, DXGI_FORMAT_R32G32B32A32_UINT = 3, DXGI_FORMAT_R32G32B32A32_SINT = 4, DXGI_FORMAT_R32G32B32_TYPELESS = 5, DXGI_FORMAT_R32G32B32_FLOAT = 6, DXGI_FORMAT_R32G32B32_UINT = 7, DXGI_FORMAT_R32G32B32_SINT = 8, DXGI_FORMAT_R16G16B16A16_TYPELESS = 9, DXGI_FORMAT_R16G16B16A16_FLOAT = 10, DXGI_FORMAT_R16G16B16A16_UNORM = 11, DXGI_FORMAT_R16G16B16A16_UINT = 12, DXGI_FORMAT_R16G16B16A16_SNORM = 13, DXGI_FORMAT_R16G16B16A16_SINT = 14, DXGI_FORMAT_R32G32_TYPELESS = 15, DXGI_FORMAT_R32G32_FLOAT = 16, DXGI_FORMAT_R32G32_UINT = 17, DXGI_FORMAT_R32G32_SINT = 18, DXGI_FORMAT_R32G8X24_TYPELESS = 19, DXGI_FORMAT_D32_FLOAT_S8X24_UINT = 20, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = 21, DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = 22, DXGI_FORMAT_R10G10B10A2_TYPELESS = 23, DXGI_FORMAT_R10G10B10A2_UNORM = 24, DXGI_FORMAT_R10G10B10A2_UINT = 25, DXGI_FORMAT_R11G11B10_FLOAT = 26, DXGI_FORMAT_R8G8B8A8_TYPELESS = 27, DXGI_FORMAT_R8G8B8A8_UNORM = 28, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 29, DXGI_FORMAT_R8G8B8A8_UINT = 30, DXGI_FORMAT_R8G8B8A8_SNORM = 31, DXGI_FORMAT_R8G8B8A8_SINT = 32, DXGI_FORMAT_R16G16_TYPELESS = 33, DXGI_FORMAT_R16G16_FLOAT = 34, DXGI_FORMAT_R16G16_UNORM = 35, DXGI_FORMAT_R16G16_UINT = 36, DXGI_FORMAT_R16G16_SNORM = 37, DXGI_FORMAT_R16G16_SINT = 38, DXGI_FORMAT_R32_TYPELESS = 39, DXGI_FORMAT_D32_FLOAT = 40, DXGI_FORMAT_R32_FLOAT = 41, DXGI_FORMAT_R32_UINT = 42, DXGI_FORMAT_R32_SINT = 43, DXGI_FORMAT_R24G8_TYPELESS = 44, DXGI_FORMAT_D24_UNORM_S8_UINT = 45, DXGI_FORMAT_R24_UNORM_X8_TYPELESS = 46, DXGI_FORMAT_X24_TYPELESS_G8_UINT = 47, DXGI_FORMAT_R8G8_TYPELESS = 48, DXGI_FORMAT_R8G8_UNORM = 49, DXGI_FORMAT_R8G8_UINT = 50, DXGI_FORMAT_R8G8_SNORM = 51, DXGI_FORMAT_R8G8_SINT = 52, DXGI_FORMAT_R16_TYPELESS = 53, DXGI_FORMAT_R16_FLOAT = 54, DXGI_FORMAT_D16_UNORM = 55, DXGI_FORMAT_R16_UNORM = 56, DXGI_FORMAT_R16_UINT = 57, DXGI_FORMAT_R16_SNORM = 58, DXGI_FORMAT_R16_SINT = 59, DXGI_FORMAT_R8_TYPELESS = 60, DXGI_FORMAT_R8_UNORM = 61, DXGI_FORMAT_R8_UINT = 62, DXGI_FORMAT_R8_SNORM = 63, DXGI_FORMAT_R8_SINT = 64, DXGI_FORMAT_A8_UNORM = 65, DXGI_FORMAT_R1_UNORM = 66, DXGI_FORMAT_R9G9B9E5_SHAREDEXP = 67, DXGI_FORMAT_R8G8_B8G8_UNORM = 68, DXGI_FORMAT_G8R8_G8B8_UNORM = 69, DXGI_FORMAT_BC1_TYPELESS = 70, DXGI_FORMAT_BC1_UNORM = 71, DXGI_FORMAT_BC1_UNORM_SRGB = 72, DXGI_FORMAT_BC2_TYPELESS = 73, DXGI_FORMAT_BC2_UNORM = 74, DXGI_FORMAT_BC2_UNORM_SRGB = 75, DXGI_FORMAT_BC3_TYPELESS = 76, DXGI_FORMAT_BC3_UNORM = 77, DXGI_FORMAT_BC3_UNORM_SRGB = 78, DXGI_FORMAT_BC4_TYPELESS = 79, DXGI_FORMAT_BC4_UNORM = 80, DXGI_FORMAT_BC4_SNORM = 81, DXGI_FORMAT_BC5_TYPELESS = 82, DXGI_FORMAT_BC5_UNORM = 83, DXGI_FORMAT_BC5_SNORM = 84, DXGI_FORMAT_B5G6R5_UNORM = 85, DXGI_FORMAT_B5G5R5A1_UNORM = 86, DXGI_FORMAT_B8G8R8A8_UNORM = 87, DXGI_FORMAT_B8G8R8X8_UNORM = 88, DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM = 89, DXGI_FORMAT_B8G8R8A8_TYPELESS = 90, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB = 91, DXGI_FORMAT_B8G8R8X8_TYPELESS = 92, DXGI_FORMAT_B8G8R8X8_UNORM_SRGB = 93, DXGI_FORMAT_BC6H_TYPELESS = 94, DXGI_FORMAT_BC6H_UF16 = 95, DXGI_FORMAT_BC6H_SF16 = 96, DXGI_FORMAT_BC7_TYPELESS = 97, DXGI_FORMAT_BC7_UNORM = 98, DXGI_FORMAT_BC7_UNORM_SRGB = 99, }; extern uint findD3D9Format(uint bitcount, uint rmask, uint gmask, uint bmask, uint amask); struct NVIMAGE_CLASS DDSPixelFormat { uint size; uint flags; uint fourcc; uint bitcount; uint rmask; uint gmask; uint bmask; uint amask; }; struct NVIMAGE_CLASS DDSCaps { uint caps1; uint caps2; uint caps3; uint caps4; }; /// DDS file header for DX10. struct NVIMAGE_CLASS DDSHeader10 { uint dxgiFormat; uint resourceDimension; uint miscFlag; uint arraySize; uint reserved; }; /// DDS file header. struct NVIMAGE_CLASS DDSHeader { uint fourcc; uint size; uint flags; uint height; uint width; uint pitch; uint depth; uint mipmapcount; uint reserved[11]; DDSPixelFormat pf; DDSCaps caps; uint notused; DDSHeader10 header10; // Helper methods. DDSHeader(); void setWidth(uint w); void setHeight(uint h); void setDepth(uint d); void setMipmapCount(uint count); void setTexture2D(); void setTexture3D(); void setTextureCube(); void setLinearSize(uint size); void setPitch(uint pitch); void setFourCC(uint8 c0, uint8 c1, uint8 c2, uint8 c3); void setFormatCode(uint code); void setSwizzleCode(uint8 c0, uint8 c1, uint8 c2, uint8 c3); void setPixelFormat(uint bitcount, uint rmask, uint gmask, uint bmask, uint amask); void setDX10Format(uint format); void setNormalFlag(bool b); void setSrgbFlag(bool b); void setHasAlphaFlag(bool b); void setUserVersion(int version); void swapBytes(); bool hasDX10Header() const; uint signature() const; uint toolVersion() const; uint userVersion() const; bool isNormalMap() const; bool isSrgb() const; bool hasAlpha() const; uint d3d9Format() const; uint pixelSize() const; // In bits! uint blockSize() const; // In bytes! bool isBlockFormat() const; }; NVIMAGE_API Stream & operator<< (Stream & s, DDSHeader & header); /// DirectDraw Surface. (DDS) class NVIMAGE_CLASS DirectDrawSurface { public: DirectDrawSurface(); DirectDrawSurface(const char * file); DirectDrawSurface(Stream * stream); ~DirectDrawSurface(); bool load(const char * filename); bool load(Stream * stream); bool isValid() const; bool isSupported() const; bool hasAlpha() const; uint mipmapCount() const; uint width() const; uint height() const; uint depth() const; bool isTexture1D() const; bool isTexture2D() const; bool isTexture3D() const; bool isTextureCube() const; void setNormalFlag(bool b); void setHasAlphaFlag(bool b); void setUserVersion(int version); void mipmap(Image * img, uint f, uint m); uint surfaceWidth(uint mipmap) const; uint surfaceHeight(uint mipmap) const; uint surfaceDepth(uint mipmap) const; uint surfaceSize(uint mipmap) const; bool readSurface(uint face, uint mipmap, void * data, uint size); void printInfo() const; // Only initialized after loading. DDSHeader header; private: uint faceSize() const; uint offset(uint face, uint mipmap); void readLinearImage(Image * img); void readBlockImage(Image * img); void readBlock(ColorBlock * rgba); private: Stream * stream; }; } // nv namespace #endif // NV_IMAGE_DIRECTDRAWSURFACE_H
80651b40e3a7d36186de48693320c63fbcc927db
0372536877e68ba414619d4abe9965dd9e86a2c7
/Rook.cpp
db1a82047bbd7c0038d81de001ccf22b56dd9347
[]
no_license
Benelcoding/Chess
95e80cc681d503487662824cf1e3e4885b45397c
11176352ffbd4217533d4749c9cfcf3d5871c75a
refs/heads/master
2021-01-05T05:12:20.668756
2020-03-26T12:06:10
2020-03-26T12:06:10
240,891,994
0
0
null
null
null
null
UTF-8
C++
false
false
360
cpp
Rook.cpp
#include "Rook.hpp" Rook::Rook() {}//default constructor. Rook::Rook(int x, int y,int p)//constructs Rook. { Piece::init(x, y, p,ROOK_SYMBOL); } int Rook::valid_move(int target_x, int target_y) { //Checks if the coordinated inputted are considered a valid move for the Rook. if ((target_x == get_x()) || (target_y == get_y())) { return 1; } return 0; }
92b3b0ed23cd9dd78bc230719e35c82ccc8fdd30
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/mutt/gumtree/mutt_new_log_215.cpp
20900eeda9746219edfdeafad72cdb2f4085fde9
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
47
cpp
mutt_new_log_215.cpp
state_puts (_("Error: copy data failed\n"), s);
651862c8eca7d57959c2c035919a9c3f47134eb1
62d7b7f0a47d600ddb86e63a5181b6837086536c
/include/feats/segmentations/equal_nb_of_segments.hxx
5f8684ca585e5b923033b651332043777fa2fb6c
[]
no_license
vishalbelsare/FEATS
9492d9b6785275def64e6f3ebfa1eb74242eaacb
de83f78f73989c81b3311cdee2a90ae0ceb0b367
refs/heads/master
2021-05-27T22:16:23.266745
2012-05-10T13:39:57
2012-05-10T13:39:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,546
hxx
equal_nb_of_segments.hxx
#ifndef EQUAL_NB_OF_SEGMENTS_HXX #define EQUAL_NB_OF_SEGMENTS_HXX #include<vector> #include <boost/shared_ptr.hpp> namespace feats{ namespace segmentations{ /* this class computes segmentations over a set of time series Static Parameters segmentation algorithm i.e. optimal_split<linear0_model<...> Note: for clustering of adaptive segmentations, we segment clusters of time series with linear0_prototype_level_meta_model over the series of the linear0_model over the population WeightIt constructeur */ template<typename Segmentation> struct equal_nb_of_segments { typedef Segmentation seg_type; typedef boost::shared_ptr<seg_type> ptr_seg_type; typedef std::vector<ptr_seg_type> segs_container; typedef typename seg_type::cost_type cost_type; typedef typename seg_type::nb_segments_type nb_segments_type; typedef nb_segments_type size_type; template<typename SeriesItPairsIt> equal_nb_of_segments(const boost::tuple<SeriesItPairsIt,SeriesItPairsIt>& seriesItPairsItPair) : nbSeries_(std::distance(boost::get<0>(seriesItPairsItPair),boost::get<1>(seriesItPairsItPair))), nbSegments_(0) ,segs_(nbSeries_) { // init segmentations SeriesItPairsIt it(boost::get<0>(seriesItPairsItPair)); for(size_type i(0); i!=nbSeries_; ++i,++it){ segs_[i]=ptr_seg_type(new seg_type(typename seg_type::segment_type(boost::get<0>(*it), boost::get<1>(*it)))); } nbSegments_=nbSeries_; } template<typename Out> Out nb_episodes(Out o){ for(size_type i(0); i!=nbSeries_; ++i,++o) { *o=segs_[i]->nb_segs();} return o; } template<typename Out> Out costs(Out o){ for(size_type i(0); i!=nbSeries_; ++i,++o) { *o=segs_[i]->cost();} return o; } template<typename Out> Out segments(size_type nS, Out o) { return segs_[nS]->segments(o);} cost_type cost()const{ cost_type res(0.); for ( size_type i(0); i!=nbSeries_; ++i) { res+=segs_[i]->cost();} return res; } nb_segments_type nb_segments()const{return nbSegments_;} void inc_segments(){ ++nbSegments_; // we find the first series having less segments than the previous one size_type i(1); for(size_type prev=segs_[0]->nb_segs(); i!=nbSeries_ && prev==segs_[i]->nb_segs(); ++i) { prev= segs_[i]->nb_segs(); } if(i==nbSeries_)i=0; segs_[i]->inc_segments(); } private: size_type nbSeries_, nbSegments_; segs_container segs_; }; } } #endif
83b4bc29ee675e4e16920ab299530e4422ecf749
4d107a97633559963f6510767bb9297febbcbb02
/applications/ContactStructuralMechanicsApplication/custom_conditions/ALM_mortar_contact_condition.cpp
93bc51a90e84ef05f4ac43e8095384844d5ff3a6
[]
no_license
asroy/Kratos
45dc4a9ad77a2b203ab2e0c6c5fe030633433181
e89d6808670d4d645319c7678da548b37825abe3
refs/heads/master
2021-03-24T13:28:43.618915
2017-12-19T15:38:20
2017-12-19T15:38:20
102,793,791
1
0
null
null
null
null
UTF-8
C++
false
false
65,243
cpp
ALM_mortar_contact_condition.cpp
// KRATOS ___| | | | // \___ \ __| __| | | __| __| | | __| _` | | // | | | | | ( | | | | ( | | // _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS // // License: BSD License // license: StructuralMechanicsApplication/license.txt // // Main authors: Vicente Mataix Ferrandiz // // System includes #ifdef KRATOS_DEBUG #include <iomanip> #endif // External includes // Project includes /* Mortar includes */ #include "custom_conditions/ALM_mortar_contact_condition.h" /* Additional includes */ #include <algorithm> /* Utilities */ #include "utilities/math_utils.h" #include "custom_utilities/search_utilities.h" namespace Kratos { /** * Flags related to the condition computation */ // Avoiding using the macro since this has a template parameter. If there was no template plase use the KRATOS_CREATE_LOCAL_FLAG macro template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> const Kratos::Flags AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::COMPUTE_RHS_VECTOR(Kratos::Flags::Create(0)); template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> const Kratos::Flags AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::COMPUTE_LHS_MATRIX(Kratos::Flags::Create(1)); /************************************* OPERATIONS **********************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> Condition::Pointer AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::Create( IndexType NewId, NodesArrayType const& rThisNodes, PropertiesType::Pointer pProperties ) const { KRATOS_ERROR << "You are calling to the base class method Create, check your condition declaration" << std::endl; return boost::make_shared< AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation> >( NewId, this->GetGeometry().Create( rThisNodes ), pProperties ); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> Condition::Pointer AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::Create( IndexType NewId, GeometryType::Pointer pGeom, PropertiesType::Pointer pProperties) const { KRATOS_ERROR << "You are calling to the base class method Create, check your condition declaration" << std::endl; return boost::make_shared< AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation> >( NewId, pGeom, pProperties ); } /************************************* DESTRUCTOR **********************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::~AugmentedLagrangianMethodMortarContactCondition( ) = default; //************************** STARTING - ENDING METHODS ***************************// /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::Initialize( ) { KRATOS_TRY; mIntegrationOrder = GetProperties().Has(INTEGRATION_ORDER_CONTACT) ? GetProperties().GetValue(INTEGRATION_ORDER_CONTACT) : 2; KRATOS_CATCH( "" ); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::InitializeSolutionStep( ProcessInfo& rCurrentProcessInfo ) { KRATOS_TRY; // First populate of the vector of master elements ConditionMap::Pointer& all_conditions_maps = this->GetValue( MAPPING_PAIRS ); mPairSize = all_conditions_maps->size(); mThisMasterElements.resize( mPairSize ); mThisMasterElementsActive.resize( mPairSize ); unsigned int i_cond = 0; for (auto it_pair = all_conditions_maps->begin(); it_pair != all_conditions_maps->end(); ++it_pair ) { mThisMasterElements[i_cond] = (it_pair->first); mThisMasterElementsActive[i_cond] = (it_pair->second); i_cond += 1; } KRATOS_CATCH( "" ); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::InitializeNonLinearIteration( ProcessInfo& rCurrentProcessInfo ) { KRATOS_TRY; if (rCurrentProcessInfo[CONSIDER_PAIR_VARIATION] == true) { // We update the active/inactive pair ConditionMap::Pointer& all_conditions_maps = this->GetValue( MAPPING_PAIRS ); unsigned int i_cond = 0; for (auto it_pair = all_conditions_maps->begin(); it_pair != all_conditions_maps->end(); ++it_pair ) { mThisMasterElementsActive[i_cond] = (it_pair->second); i_cond += 1; } } KRATOS_CATCH( "" ); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::FinalizeSolutionStep( ProcessInfo& rCurrentProcessInfo ) { KRATOS_TRY; // NOTE: Add things if necessary KRATOS_CATCH( "" ); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::FinalizeNonLinearIteration( ProcessInfo& rCurrentProcessInfo ) { KRATOS_TRY; this->Set(VISITED, true); if (rCurrentProcessInfo[CONSIDER_PAIR_VARIATION] == true) { // Check pairs ConditionMap::Pointer& all_conditions_maps = this->GetValue( MAPPING_PAIRS ); GeometryType& this_geometry = GetGeometry(); const double active_check_length = this_geometry.Length() * rCurrentProcessInfo[ACTIVE_CHECK_FACTOR]; SearchUtilities::ExactContactContainerChecker<TDim,TNumNodes>(all_conditions_maps, this_geometry, this->GetValue(NORMAL), active_check_length); } KRATOS_CATCH( "" ); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::CalculateLocalSystem( MatrixType& rLeftHandSideMatrix, VectorType& rRightHandSideVector, ProcessInfo& rCurrentProcessInfo ) { KRATOS_TRY; // Create local system components LocalSystem local_system; // Calculation flags local_system.CalculationFlags.Set( AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::COMPUTE_LHS_MATRIX, true ); local_system.CalculationFlags.Set( AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::COMPUTE_RHS_VECTOR, true ); // Initialize sizes for the system components: this->InitializeSystemMatrices( rLeftHandSideMatrix, rRightHandSideVector, local_system.CalculationFlags ); // Set Variables to Local system components local_system.SetLeftHandSideMatrix( rLeftHandSideMatrix ); local_system.SetRightHandSideVector( rRightHandSideVector ); // Calculate condition system this->CalculateConditionSystem( local_system, rCurrentProcessInfo ); KRATOS_CATCH( "" ); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::CalculateLeftHandSide( MatrixType& rLeftHandSideMatrix, ProcessInfo& rCurrentProcessInfo ) { // Create local system components LocalSystem local_system; // Calculation flags local_system.CalculationFlags.Set( AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::COMPUTE_LHS_MATRIX, true ); VectorType right_hand_side_vector = Vector( ); // Initialize sizes for the system components: this->InitializeSystemMatrices( rLeftHandSideMatrix, right_hand_side_vector, local_system.CalculationFlags ); // Set Variables to Local system components local_system.SetLeftHandSideMatrix( rLeftHandSideMatrix ); local_system.SetRightHandSideVector( right_hand_side_vector ); // Calculate condition system this->CalculateConditionSystem( local_system, rCurrentProcessInfo ); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::CalculateRightHandSide( VectorType& rRightHandSideVector, ProcessInfo& rCurrentProcessInfo ) { // Create local system components LocalSystem local_system; // Calculation flags local_system.CalculationFlags.Set( AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::COMPUTE_RHS_VECTOR, true); MatrixType left_hand_side_matrix = Matrix( ); // Initialize size for the system components this->InitializeSystemMatrices( left_hand_side_matrix, rRightHandSideVector,local_system.CalculationFlags); //Set Variables to Local system components local_system.SetLeftHandSideMatrix( left_hand_side_matrix ); local_system.SetRightHandSideVector( rRightHandSideVector ); // Calculate condition system this->CalculateConditionSystem( local_system, rCurrentProcessInfo ); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::InitializeSystemMatrices( MatrixType& rLeftHandSideMatrix, VectorType& rRightHandSideVector, Flags& rCalculationFlags ) { const unsigned int condition_size = this->CalculateConditionSize( ); // Resizing as needed the LHS if ( rCalculationFlags.Is( AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::COMPUTE_LHS_MATRIX ) ) // Calculation of the matrix is required { if ( rLeftHandSideMatrix.size1() != condition_size ) { rLeftHandSideMatrix.resize( condition_size, condition_size, false ); } noalias( rLeftHandSideMatrix ) = ZeroMatrix( condition_size, condition_size ); // Resetting LHS } // Resizing as needed the RHS if ( rCalculationFlags.Is( AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::COMPUTE_RHS_VECTOR ) ) // Calculation of the matrix is required { if ( rRightHandSideVector.size() != condition_size ) { rRightHandSideVector.resize( condition_size, false ); } rRightHandSideVector = ZeroVector( condition_size ); // Resetting RHS } } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::CalculateMassMatrix( MatrixType& rMassMatrix, ProcessInfo& rCurrentProcessInfo ) { KRATOS_TRY; rMassMatrix.resize(0, 0, false); KRATOS_CATCH( "" ); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::CalculateDampingMatrix( MatrixType& rDampingMatrix, ProcessInfo& rCurrentProcessInfo ) { KRATOS_TRY; rDampingMatrix.resize(0, 0, false); KRATOS_CATCH( "" ); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::AddExplicitContribution(ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY; // The slave geometry GeometryType& slave_geometry = GetGeometry(); const array_1d<double, 3>& normal_slave = this->GetValue(NORMAL); // Create and initialize condition variables GeneralVariables rVariables; // Create the current contact data DerivativeDataType rDerivativeData; rDerivativeData.Initialize(slave_geometry, rCurrentProcessInfo); // Create the mortar operators MortarConditionMatrices rThisMortarConditionMatrices; // We call the exact integration utility IntegrationUtility integration_utility = IntegrationUtility (mIntegrationOrder); // If we consider the normal variation const NormalDerivativesComputation consider_normal_variation = static_cast<NormalDerivativesComputation>(rCurrentProcessInfo[CONSIDER_NORMAL_VARIATION]); // Iterate over the master segments for (unsigned int pair_index = 0; pair_index < mPairSize; ++pair_index) { if (mThisMasterElementsActive[pair_index] == true) { GeometryType& master_geometry = mThisMasterElements[pair_index]->GetGeometry(); // The normal of the master condition const array_1d<double, 3>& master_normal = mThisMasterElements[pair_index]->GetValue(NORMAL); // Reading integration points ConditionArrayListType conditions_points_slave; const bool is_inside = integration_utility.GetExactIntegration(slave_geometry, normal_slave, master_geometry, master_normal, conditions_points_slave); double integration_area; integration_utility.GetTotalArea(slave_geometry, conditions_points_slave, integration_area); if ((is_inside == true) && ((integration_area/slave_geometry.Area()) > 1.0e-3 * slave_geometry.Area())) { IntegrationMethod this_integration_method = GetIntegrationMethod(); // Initialize general variables for the current master element rVariables.Initialize(); // Update slave element info rDerivativeData.UpdateMasterPair(mThisMasterElements[pair_index]); // Initialize the mortar operators rThisMortarConditionMatrices.Initialize(); const bool dual_LM = DerivativesUtilitiesType::CalculateAeAndDeltaAe(slave_geometry, normal_slave, mThisMasterElements[pair_index], rDerivativeData, rVariables, consider_normal_variation, conditions_points_slave, this_integration_method, GetAxisymmetricCoefficient(rVariables)); for (unsigned int i_geom = 0; i_geom < conditions_points_slave.size(); ++i_geom) { std::vector<PointType::Pointer> points_array (TDim); // The points are stored as local coordinates, we calculate the global coordinates of this points array_1d<BelongType, TDim> belong_array; for (unsigned int i_node = 0; i_node < TDim; ++i_node) { PointType global_point; slave_geometry.GlobalCoordinates(global_point, conditions_points_slave[i_geom][i_node]); points_array[i_node] = boost::make_shared<PointType>(global_point); belong_array[i_node] = conditions_points_slave[i_geom][i_node].GetBelong(); } DecompositionType decomp_geom( points_array ); const bool bad_shape = (TDim == 2) ? MortarUtilities::LengthCheck(decomp_geom, slave_geometry.Length() * 1.0e-6) : MortarUtilities::HeronCheck(decomp_geom); if (bad_shape == false) { const GeometryType::IntegrationPointsArrayType& integration_points_slave = decomp_geom.IntegrationPoints( this_integration_method ); // Integrating the mortar operators for ( unsigned int point_number = 0; point_number < integration_points_slave.size(); ++point_number ) { // We compute the local coordinates const PointType local_point_decomp = integration_points_slave[point_number].Coordinates(); PointType local_point_parent; PointType gp_global; decomp_geom.GlobalCoordinates(gp_global, local_point_decomp); slave_geometry.PointLocalCoordinates(local_point_parent, gp_global); // Calculate the kinematic variables this->CalculateKinematics( rVariables, rDerivativeData, master_normal, pair_index, local_point_decomp, local_point_parent, decomp_geom, dual_LM);//, delta_position_slave); const double integration_weight = integration_points_slave[point_number].Weight() * GetAxisymmetricCoefficient(rVariables); rThisMortarConditionMatrices.CalculateMortarOperators(rVariables, integration_weight); } } } // Setting the weighted gap // Mortar condition matrices - DOperator and MOperator const bounded_matrix<double, TNumNodes, TNumNodes>& DOperator = rThisMortarConditionMatrices.DOperator; const bounded_matrix<double, TNumNodes, TNumNodes>& MOperator = rThisMortarConditionMatrices.MOperator; // Current coordinates const bounded_matrix<double, TNumNodes, TDim>& x1 = MortarUtilities::GetCoordinates<TDim,TNumNodes>(slave_geometry); const bounded_matrix<double, TNumNodes, TDim>& x2 = MortarUtilities::GetCoordinates<TDim,TNumNodes>(master_geometry); const bounded_matrix<double, TNumNodes, TDim> D_x1_M_x2 = prod(DOperator, x1) - prod(MOperator, x2); for (unsigned int i_node = 0; i_node < TNumNodes; ++i_node) { const array_1d<double, 3>& normal = slave_geometry[i_node].FastGetSolutionStepValue(NORMAL); const array_1d<double, TDim> aux_array = row(D_x1_M_x2, i_node); double& weighted_gap = slave_geometry[i_node].FastGetSolutionStepValue(WEIGHTED_GAP); #pragma omp atomic weighted_gap += inner_prod(aux_array, - subrange(normal, 0, TDim)); } if (TFrictional == true) // TODO: Check this!!! { // Old coordinates const bounded_matrix<double, TNumNodes, TDim>& x1_old = MortarUtilities::GetCoordinates<TDim,TNumNodes>(slave_geometry, false, 1); const bounded_matrix<double, TNumNodes, TDim>& x2_old = MortarUtilities::GetCoordinates<TDim,TNumNodes>(master_geometry, false, 1); const bounded_matrix<double, TNumNodes, TDim> D_x1_old_M_x2_old = prod(DOperator, x1_old) - prod(MOperator, x2_old); for (unsigned int i_node = 0; i_node < TNumNodes; ++i_node) { // We compute the tangent const array_1d<double, 3>& normal = slave_geometry[i_node].FastGetSolutionStepValue(NORMAL); const array_1d<double, 3>& lm = slave_geometry[i_node].FastGetSolutionStepValue(VECTOR_LAGRANGE_MULTIPLIER); const double lm_normal = inner_prod(normal, lm); array_1d<double, 3> tangent_lm = lm - lm_normal * normal; tangent_lm /= norm_2(tangent_lm); const array_1d<double, TDim>& tangent = subrange(tangent_lm, 0, TDim); const array_1d<double, TDim>& aux_array = row(D_x1_old_M_x2_old, i_node); double& weighted_slip = slave_geometry[i_node].FastGetSolutionStepValue(WEIGHTED_SLIP); #pragma omp atomic weighted_slip += inner_prod(aux_array, tangent); } } } } } KRATOS_CATCH( "" ); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> const unsigned int AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::CalculateConditionSize( ) { const unsigned int condition_size = mPairSize * MatrixSize; return condition_size; } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim, TNumNodes, TFrictional, TNormalVariation>::CalculateConditionSystem( LocalSystem& rLocalSystem, const ProcessInfo& rCurrentProcessInfo ) { KRATOS_TRY; // The slave geometry GeometryType& slave_geometry = this->GetGeometry(); const array_1d<double, 3>& normal_slave = this->GetValue(NORMAL); // Create and initialize condition variables GeneralVariables rVariables; // Create the current contact data DerivativeDataType rDerivativeData; rDerivativeData.Initialize(slave_geometry, rCurrentProcessInfo); const NormalDerivativesComputation consider_normal_variation = static_cast<NormalDerivativesComputation>(rCurrentProcessInfo[CONSIDER_NORMAL_VARIATION]); // We compute the normal derivatives if (TNormalVariation) DerivativesUtilitiesType::CalculateDeltaNormal(rDerivativeData.DeltaNormalSlave, GetGeometry()); // Create the mortar operators MortarConditionMatrices rThisMortarConditionMatrices; // We call the exact integration utility IntegrationUtility integration_utility = IntegrationUtility (mIntegrationOrder); // Iterate over the master segments for (unsigned int pair_index = 0; pair_index < mPairSize; ++pair_index) { GeometryType& master_geometry = mThisMasterElements[pair_index]->GetGeometry(); if (mThisMasterElementsActive[pair_index] == true) { // The normal of the master condition const array_1d<double, 3>& master_normal = mThisMasterElements[pair_index]->GetValue(NORMAL); // Reading integration points ConditionArrayListType conditions_points_slave; const bool is_inside = integration_utility.GetExactIntegration(slave_geometry, normal_slave, master_geometry, master_normal, conditions_points_slave); double integration_area; integration_utility.GetTotalArea(slave_geometry, conditions_points_slave, integration_area); if ((is_inside == true) && ((integration_area/slave_geometry.Area()) > 1.0e-3 * slave_geometry.Area())) { IntegrationMethod this_integration_method = GetIntegrationMethod(); // Initialize general variables for the current master element rVariables.Initialize(); // Update slave element info rDerivativeData.UpdateMasterPair(mThisMasterElements[pair_index]); // Initialize the mortar operators rThisMortarConditionMatrices.Initialize(); if (TNormalVariation) DerivativesUtilitiesType::CalculateDeltaNormal(rDerivativeData.DeltaNormalMaster, master_geometry); const bool dual_LM = DerivativesUtilitiesType::CalculateAeAndDeltaAe(slave_geometry, normal_slave, mThisMasterElements[pair_index], rDerivativeData, rVariables, consider_normal_variation, conditions_points_slave, this_integration_method, GetAxisymmetricCoefficient(rVariables)); #ifdef KRATOS_DEBUG if (dual_LM == false) { std::cout << "WARNING:: NOT USING DUAL LM. Integration area: " << integration_area << "\tOriginal area: " << slave_geometry.Area() << "\tRatio: " << integration_area/slave_geometry.Area() << std::endl; // IntegrationUtility::MathematicaDebug(this->Id(), slave_geometry, mThisMasterElements[pair_index]->Id(), master_geometry, conditions_points_slave); } #endif for (unsigned int i_geom = 0; i_geom < conditions_points_slave.size(); ++i_geom) { std::vector<PointType::Pointer> points_array (TDim); // The points are stored as local coordinates, we calculate the global coordinates of this points array_1d<BelongType, TDim> belong_array; for (unsigned int i_node = 0; i_node < TDim; ++i_node) { PointType global_point; slave_geometry.GlobalCoordinates(global_point, conditions_points_slave[i_geom][i_node]); points_array[i_node] = boost::make_shared<PointType>(global_point); belong_array[i_node] = conditions_points_slave[i_geom][i_node].GetBelong(); } DecompositionType decomp_geom( points_array ); const bool bad_shape = (TDim == 2) ? MortarUtilities::LengthCheck(decomp_geom, slave_geometry.Length() * 1.0e-6) : MortarUtilities::HeronCheck(decomp_geom); if (bad_shape == false) { // // Delta position // Matrix delta_position_slave; // delta_position_slave = DerivativesUtilitiesType::CalculateDeltaPosition(delta_position_slave, slave_geometry, conditions_points_slave[i_geom]); const GeometryType::IntegrationPointsArrayType& integration_points_slave = decomp_geom.IntegrationPoints( this_integration_method ); // Integrating the mortar operators for ( unsigned int point_number = 0; point_number < integration_points_slave.size(); ++point_number ) { // We reset the derivatives rDerivativeData.ResetDerivatives(); // We compute the local coordinates const PointType local_point_decomp = integration_points_slave[point_number].Coordinates(); PointType local_point_parent; PointType gp_global; decomp_geom.GlobalCoordinates(gp_global, local_point_decomp); slave_geometry.PointLocalCoordinates(local_point_parent, gp_global); // Calculate the kinematic variables this->CalculateKinematics( rVariables, rDerivativeData, master_normal, pair_index, local_point_decomp, local_point_parent, decomp_geom, dual_LM);//, delta_position_slave); const double integration_weight = integration_points_slave[point_number].Weight() * GetAxisymmetricCoefficient(rVariables); if ( rLocalSystem.CalculationFlags.Is( AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::COMPUTE_LHS_MATRIX )) { /* Update the derivatives */ // Update the derivative of the integration vertex (just in 3D) if (TDim == 3) DerivativesUtilitiesType::CalculateDeltaCellVertex(rVariables, rDerivativeData, belong_array, consider_normal_variation, slave_geometry, master_geometry, normal_slave); // Update the derivative of DetJ DerivativesUtilitiesType::CalculateDeltaDetjSlave(decomp_geom, rVariables, rDerivativeData); // Update the derivatives of the shape functions and the gap DerivativesUtilitiesType::CalculateDeltaN(rVariables, rDerivativeData, slave_geometry, master_geometry, normal_slave, master_normal, decomp_geom, local_point_decomp, local_point_parent, consider_normal_variation, dual_LM); rThisMortarConditionMatrices.CalculateDeltaMortarOperators(rVariables, rDerivativeData, integration_weight); } else // In case we are computing RHS we don't compute derivatives (not necessary) { rThisMortarConditionMatrices.CalculateMortarOperators(rVariables, integration_weight); } } } } // // Debug // std::cout << "--------------------------------------------------" << std::endl; // KRATOS_WATCH(this->Id()); // KRATOS_WATCH(pair_index); // rThisMortarConditionMatrices.print(); // Calculates the active/inactive combination pair const unsigned int active_inactive = GetActiveInactiveValue(slave_geometry); // Assemble of the matrix is required if ( rLocalSystem.CalculationFlags.Is( AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::COMPUTE_LHS_MATRIX ) ) { // Calculate the local contribution const bounded_matrix<double, MatrixSize, MatrixSize> LHS_contact_pair = this->CalculateLocalLHS( rThisMortarConditionMatrices, rDerivativeData, active_inactive); // Contributions to stiffness matrix calculated on the reference config this->CalculateAndAddLHS( rLocalSystem, LHS_contact_pair, pair_index ); // // Debug // // KRATOS_WATCH(LHS_contact_pair); // LOG_MATRIX_PRETTY( LHS_contact_pair ); } // Assemble of the vector is required if ( rLocalSystem.CalculationFlags.Is( AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::COMPUTE_RHS_VECTOR )) { // Calculate the local contribution const array_1d<double, MatrixSize> RHS_contact_pair = this->CalculateLocalRHS( rThisMortarConditionMatrices, rDerivativeData, active_inactive); // Contribution to previous step contact force and residuals vector this->CalculateAndAddRHS( rLocalSystem, RHS_contact_pair, pair_index ); // // Debug // // KRATOS_WATCH(RHS_contact_pair); // LOG_VECTOR_PRETTY( RHS_contact_pair ); } } } } // Reseting flag if ((this)->Is(VISITED) == true) { (this)->Set(VISITED, false); } KRATOS_CATCH( "" ); } /*********************************COMPUTE KINEMATICS*********************************/ /************************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::CalculateKinematics( GeneralVariables& rVariables, const DerivativeDataType rDerivativeData, const array_1d<double, 3> MasterNormal, const unsigned int PairIndex, const PointType& LocalPointDecomp, const PointType& LocalPointParent, GeometryPointType& GeometryDecomp, const bool DualLM, Matrix DeltaPosition ) { /// SLAVE CONDITION /// /* SHAPE FUNCTIONS */ GetGeometry().ShapeFunctionsValues( rVariables.NSlave, LocalPointParent.Coordinates() ); rVariables.PhiLagrangeMultipliers = (DualLM == true) ? prod(rDerivativeData.Ae, rVariables.NSlave) : rVariables.NSlave; /* SHAPE FUNCTION DERIVATIVES */ GetGeometry().ShapeFunctionsLocalGradients( rVariables.DNDeSlave, LocalPointParent ); /* CALCULATE JACOBIAN AND JACOBIAN DETERMINANT */ rVariables.jSlave = GeometryDecomp.Jacobian( rVariables.jSlave, LocalPointDecomp.Coordinates());//, DeltaPosition); // rVariables.DetjSlave = MathUtils<double>::GeneralizedDet(rVariables.jSlave); rVariables.DetjSlave = GeometryDecomp.DeterminantOfJacobian( LocalPointDecomp ); if (rVariables.DetjSlave < 0.0) { KRATOS_ERROR << "WARNING:: CONDITION ID: " << this->Id() << " INVERTED. DETJ: " << rVariables.DetjSlave << std::endl; } /// MASTER CONDITION /// this->MasterShapeFunctionValue( rVariables, MasterNormal, LocalPointParent, PairIndex); } /***********************************************************************************/ /*************** METHODS TO CALCULATE THE CONTACT CONDITION MATRICES ***************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::MasterShapeFunctionValue( GeneralVariables& rVariables, const array_1d<double, 3> MasterNormal, const PointType& LocalPoint, const unsigned int PairIndex ) { GeometryType& master_geometry = mThisMasterElements[PairIndex]->GetGeometry(); PointType projected_gp_global; const array_1d<double,3> gp_normal = MortarUtilities::GaussPointUnitNormal(rVariables.NSlave, GetGeometry()); GeometryType::CoordinatesArrayType slave_gp_global; this->GetGeometry( ).GlobalCoordinates( slave_gp_global, LocalPoint ); MortarUtilities::FastProjectDirection( master_geometry, slave_gp_global, projected_gp_global, MasterNormal, -gp_normal ); // The opposite direction GeometryType::CoordinatesArrayType projected_gp_local; master_geometry.PointLocalCoordinates( projected_gp_local, projected_gp_global.Coordinates( ) ) ; // SHAPE FUNCTIONS master_geometry.ShapeFunctionsValues( rVariables.NMaster, projected_gp_local ); master_geometry.ShapeFunctionsLocalGradients( rVariables.DNDeMaster, projected_gp_local ); // JACOBIAN // Matrix delta_position_master; // MASTER // delta_position_master = DerivativesUtilitiesType::CalculateDeltaPosition(delta_position_master, GetGeometry() master_geometry); rVariables.jMaster = master_geometry.Jacobian( rVariables.jMaster, projected_gp_local);//, delta_position_master); // Add delta Position } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::CalculateAndAddLHS( LocalSystem& rLocalSystem, const bounded_matrix<double, MatrixSize, MatrixSize>& LHS_contact_pair, const unsigned int rPairIndex ) { /* SINGLE LHS MATRIX */ MatrixType& rLeftHandSideMatrix = rLocalSystem.GetLeftHandSideMatrix( ); // Assemble in the correct position this->AssembleContactPairLHSToConditionSystem(LHS_contact_pair, rLeftHandSideMatrix, rPairIndex); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::AssembleContactPairLHSToConditionSystem( const bounded_matrix<double, MatrixSize, MatrixSize>& rPairLHS, MatrixType& rConditionLHS, const unsigned int rPairIndex ) { // Find location of the pair's master DOFs in ConditionRHS const unsigned int index_begin = rPairIndex * MatrixSize; const unsigned int index_end = index_begin + MatrixSize; subrange( rConditionLHS, index_begin, index_end, index_begin, index_end) += rPairLHS; } /***********************************************************************************/ /***********************************************************************************/ template<> bounded_matrix<double, 10, 10> AugmentedLagrangianMethodMortarContactCondition<2,2, false, false>::CalculateLocalLHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalLHS, check your condition definition" << std::endl; return ZeroMatrix(10, 10); } /***********************************************************************************/ /***********************************************************************************/ template<> bounded_matrix<double, 21, 21> AugmentedLagrangianMethodMortarContactCondition<3,3, false, false>::CalculateLocalLHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalLHS, check your condition definition" << std::endl; return ZeroMatrix(21, 21); } /***********************************************************************************/ /***********************************************************************************/ template<> bounded_matrix<double, 28, 28> AugmentedLagrangianMethodMortarContactCondition<3,4, false, false>::CalculateLocalLHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalLHS, check your condition definition" << std::endl; return ZeroMatrix(28, 28); } /***********************************************************************************/ /***********************************************************************************/ template<> bounded_matrix<double, 12, 12> AugmentedLagrangianMethodMortarContactCondition<2,2, true, false>::CalculateLocalLHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalLHS, check your condition definition" << std::endl; return ZeroMatrix(12, 12); } /***********************************************************************************/ /***********************************************************************************/ template<> bounded_matrix<double, 27, 27> AugmentedLagrangianMethodMortarContactCondition<3, 3, true, false>::CalculateLocalLHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalLHS, check your condition definition" << std::endl; return ZeroMatrix(27, 27); } /***********************************************************************************/ /***********************************************************************************/ template<> bounded_matrix<double, 36, 36> AugmentedLagrangianMethodMortarContactCondition<3, 4, true, false>::CalculateLocalLHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalLHS, check your condition definition" << std::endl; return ZeroMatrix(36, 36); } /***********************************************************************************/ /***********************************************************************************/ template<> bounded_matrix<double, 10, 10> AugmentedLagrangianMethodMortarContactCondition<2,2, false, true>::CalculateLocalLHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalLHS, check your condition definition" << std::endl; return ZeroMatrix(10, 10); } /***********************************************************************************/ /***********************************************************************************/ template<> bounded_matrix<double, 21, 21> AugmentedLagrangianMethodMortarContactCondition<3,3, false, true>::CalculateLocalLHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalLHS, check your condition definition" << std::endl; return ZeroMatrix(21, 21); } /***********************************************************************************/ /***********************************************************************************/ template<> bounded_matrix<double, 28, 28> AugmentedLagrangianMethodMortarContactCondition<3,4, false, true>::CalculateLocalLHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalLHS, check your condition definition" << std::endl; return ZeroMatrix(28, 28); } /***********************************************************************************/ /***********************************************************************************/ template<> bounded_matrix<double, 12, 12> AugmentedLagrangianMethodMortarContactCondition<2,2, true, true>::CalculateLocalLHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalLHS, check your condition definition" << std::endl; return ZeroMatrix(12, 12); } /***********************************************************************************/ /***********************************************************************************/ template<> bounded_matrix<double, 27, 27> AugmentedLagrangianMethodMortarContactCondition<3, 3, true, true>::CalculateLocalLHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalLHS, check your condition definition" << std::endl; return ZeroMatrix(27, 27); } /***********************************************************************************/ /***********************************************************************************/ template<> bounded_matrix<double, 36, 36> AugmentedLagrangianMethodMortarContactCondition<3, 4, true, true>::CalculateLocalLHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalLHS, check your condition definition" << std::endl; return ZeroMatrix(36, 36); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::CalculateAndAddRHS( LocalSystem& rLocalSystem, const array_1d<double, MatrixSize>& RHS_contact_pair, const unsigned int rPairIndex ) { /* SINGLE RHS VECTOR */ VectorType& rRightHandSideVector = rLocalSystem.GetRightHandSideVector(); // Assemble this->AssembleContactPairRHSToConditionSystem( RHS_contact_pair, rRightHandSideVector, rPairIndex ); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::AssembleContactPairRHSToConditionSystem( const array_1d<double, MatrixSize>& rPairRHS, VectorType& rConditionRHS, const unsigned int rPairIndex ) { // Find location of the pair's master DOFs in ConditionRHS const unsigned int index_begin = rPairIndex * MatrixSize; const unsigned int index_end = index_begin + MatrixSize; subrange( rConditionRHS, index_begin, index_end) += rPairRHS; } /***********************************************************************************/ /***********************************************************************************/ template<> array_1d<double,10> AugmentedLagrangianMethodMortarContactCondition<2, 2, false, false>::CalculateLocalRHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalRHS, check your condition definition" << std::endl; return ZeroVector(10); } /***********************************************************************************/ /***********************************************************************************/ template<> array_1d<double,21> AugmentedLagrangianMethodMortarContactCondition<3, 3, false, false>::CalculateLocalRHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalRHS, check your condition definition" << std::endl; return ZeroVector(21); } /***********************************************************************************/ /***********************************************************************************/ template<> array_1d<double,28> AugmentedLagrangianMethodMortarContactCondition<3, 4, false, false>::CalculateLocalRHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalRHS, check your condition definition" << std::endl; return ZeroVector(28); } /***********************************************************************************/ /***********************************************************************************/ template<> array_1d<double,12> AugmentedLagrangianMethodMortarContactCondition<2, 2, true, false>::CalculateLocalRHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalRHS, check your condition definition" << std::endl; return ZeroVector(12); } /***********************************************************************************/ /***********************************************************************************/ template<> array_1d<double,27> AugmentedLagrangianMethodMortarContactCondition<3, 3, true, false>::CalculateLocalRHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalRHS, check your condition definition" << std::endl; return ZeroVector(27); } /***********************************************************************************/ /***********************************************************************************/ template<> array_1d<double,36> AugmentedLagrangianMethodMortarContactCondition<3, 4, true, false>::CalculateLocalRHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalRHS, check your condition definition" << std::endl; return ZeroVector(36); } /***********************************************************************************/ /***********************************************************************************/ template<> array_1d<double,10> AugmentedLagrangianMethodMortarContactCondition<2, 2, false, true>::CalculateLocalRHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalRHS, check your condition definition" << std::endl; return ZeroVector(10); } /***********************************************************************************/ /***********************************************************************************/ template<> array_1d<double,21> AugmentedLagrangianMethodMortarContactCondition<3, 3, false, true>::CalculateLocalRHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalRHS, check your condition definition" << std::endl; return ZeroVector(21); } /***********************************************************************************/ /***********************************************************************************/ template<> array_1d<double,28> AugmentedLagrangianMethodMortarContactCondition<3, 4, false, true>::CalculateLocalRHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalRHS, check your condition definition" << std::endl; return ZeroVector(28); } /***********************************************************************************/ /***********************************************************************************/ template<> array_1d<double,12> AugmentedLagrangianMethodMortarContactCondition<2, 2, true, true>::CalculateLocalRHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalRHS, check your condition definition" << std::endl; return ZeroVector(12); } /***********************************************************************************/ /***********************************************************************************/ template<> array_1d<double,27> AugmentedLagrangianMethodMortarContactCondition<3, 3, true, true>::CalculateLocalRHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalRHS, check your condition definition" << std::endl; return ZeroVector(27); } /***********************************************************************************/ /***********************************************************************************/ template<> array_1d<double,36> AugmentedLagrangianMethodMortarContactCondition<3, 4, true, true>::CalculateLocalRHS( const MortarConditionMatrices& rMortarConditionMatrices, const DerivativeDataType& rDerivativeData, const unsigned int rActiveInactive ) { KRATOS_ERROR << "You are calling to the base class method CalculateLocalRHS, check your condition definition" << std::endl; return ZeroVector(36); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::EquationIdVector( EquationIdVectorType& rResult, ProcessInfo& CurrentProcessInfo ) { KRATOS_ERROR << "You are calling to the base class method EquationIdVector, check your condition definition" << std::endl; } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim, TNumNodes, TFrictional, TNormalVariation>::GetDofList( DofsVectorType& rConditionalDofList, ProcessInfo& rCurrentProcessInfo ) { KRATOS_ERROR << "You are calling to the base class method GetDofList, check your condition definition" << std::endl; } //******************************* GET DOUBLE VALUE *********************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::GetValueOnIntegrationPoints( const Variable<double>& rVariable, std::vector<double>& rValues, const ProcessInfo& rCurrentProcessInfo ) { this->CalculateOnIntegrationPoints( rVariable, rValues, rCurrentProcessInfo ); } //******************************* GET ARRAY_1D VALUE *******************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::GetValueOnIntegrationPoints( const Variable<array_1d<double, 3 > >& rVariable, std::vector<array_1d<double, 3 > >& rValues, const ProcessInfo& rCurrentProcessInfo ) { this->CalculateOnIntegrationPoints( rVariable, rValues, rCurrentProcessInfo ); } //******************************* GET VECTOR VALUE *********************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::GetValueOnIntegrationPoints( const Variable<Vector>& rVariable, std::vector<Vector>& rValues, const ProcessInfo& rCurrentProcessInfo ) { this->CalculateOnIntegrationPoints( rVariable, rValues, rCurrentProcessInfo ); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::CalculateOnIntegrationPoints( const Variable<double>& rVariable, std::vector<double>& rOutput, const ProcessInfo& rCurrentProcessInfo ) { KRATOS_TRY; // TODO: Fill this!!! KRATOS_CATCH( "" ); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::CalculateOnIntegrationPoints( const Variable<array_1d<double, 3 > >& rVariable, std::vector< array_1d<double, 3 > >& rOutput, const ProcessInfo& rCurrentProcessInfo ) { KRATOS_TRY; // TODO: Fill this!!! KRATOS_CATCH( "" ); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> void AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::CalculateOnIntegrationPoints( const Variable<Vector>& rVariable, std::vector<Vector>& rOutput, const ProcessInfo& rCurrentProcessInfo ) { KRATOS_TRY; // TODO: Fill this!!! KRATOS_CATCH( "" ); } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> int AugmentedLagrangianMethodMortarContactCondition<TDim,TNumNodes,TFrictional, TNormalVariation>::Check( const ProcessInfo& rCurrentProcessInfo ) { KRATOS_TRY // Base class checks for positive Jacobian and Id > 0 int ierr = Condition::Check(rCurrentProcessInfo); if(ierr != 0) return ierr; // Check that all required variables have been registered KRATOS_CHECK_VARIABLE_KEY(DISPLACEMENT) KRATOS_CHECK_VARIABLE_KEY(WEIGHTED_GAP) KRATOS_CHECK_VARIABLE_KEY(NORMAL) KRATOS_ERROR_IF(!(this->Has(NORMAL))) << "NORMAL not defined in the AugmentedLagrangianMethodMortarContactCondition" << std::endl; KRATOS_ERROR_IF(!(this->Has(MAPPING_PAIRS))) << "MAPPING_PAIRS not defined in the AugmentedLagrangianMethodMortarContactCondition" << std::endl; // Check that the element's nodes contain all required SolutionStepData and Degrees of freedom for ( unsigned int i = 0; i < TNumNodes; i++ ) { Node<3> &rnode = this->GetGeometry()[i]; KRATOS_CHECK_VARIABLE_IN_NODAL_DATA(DISPLACEMENT,rnode) KRATOS_CHECK_VARIABLE_IN_NODAL_DATA(WEIGHTED_GAP,rnode) KRATOS_CHECK_VARIABLE_IN_NODAL_DATA(NORMAL,rnode) KRATOS_CHECK_DOF_IN_NODE(DISPLACEMENT_X, rnode) KRATOS_CHECK_DOF_IN_NODE(DISPLACEMENT_Y, rnode) KRATOS_CHECK_DOF_IN_NODE(DISPLACEMENT_Z, rnode) } return ierr; KRATOS_CATCH("") } /***********************************************************************************/ /***********************************************************************************/ template< unsigned int TDim, unsigned int TNumNodes, bool TFrictional, bool TNormalVariation> double AugmentedLagrangianMethodMortarContactCondition< TDim, TNumNodes, TFrictional, TNormalVariation>::GetAxisymmetricCoefficient(const GeneralVariables& rVariables) const { return 1.0; } /***********************************************************************************/ /***********************************************************************************/ // Frictionless cases template class AugmentedLagrangianMethodMortarContactCondition<2, 2, false, false>; template class AugmentedLagrangianMethodMortarContactCondition<3, 3, false, false>; template class AugmentedLagrangianMethodMortarContactCondition<3, 4, false, false>; template class AugmentedLagrangianMethodMortarContactCondition<2, 2, false, true>; template class AugmentedLagrangianMethodMortarContactCondition<3, 3, false, true>; template class AugmentedLagrangianMethodMortarContactCondition<3, 4, false, true>; // Frictional cases template class AugmentedLagrangianMethodMortarContactCondition<2, 2, true, false>; template class AugmentedLagrangianMethodMortarContactCondition<3, 3, true, false>; template class AugmentedLagrangianMethodMortarContactCondition<3, 4, true, false>; template class AugmentedLagrangianMethodMortarContactCondition<2, 2, true, true>; template class AugmentedLagrangianMethodMortarContactCondition<3, 3, true, true>; template class AugmentedLagrangianMethodMortarContactCondition<3, 4, true, true>; } // Namespace Kratos
acd1b7cba827634bb49c19efe171699608c3ceba
b116936c9b44d82199058b1069d60c0bff9a30d6
/apps/srba-slam/srba-slam_common.h
000aab60bfc067dc6b2ea5c6033bb7ab45dd3650
[ "BSD-3-Clause" ]
permissive
rubengooj/srba
a38efd24c1b85796da5a1ef8bc701ad5ee002b8f
ee939939f652347c5cc1876ef1a620d6416c0ad4
refs/heads/master
2021-01-16T20:27:02.350452
2016-04-19T08:26:27
2016-04-19T08:26:27
50,524,638
3
2
null
2016-01-27T17:26:40
2016-01-27T17:26:40
null
UTF-8
C++
false
false
4,868
h
srba-slam_common.h
/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2015, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #pragma once #include <srba.h> // It seems TCLAP isn't ready to be included in different translation units, so I added this tweak... #include <mrpt/otherlibs/tclap/CmdLine.h> #include <sstream> // For stringstream #include <memory> // For auto_ptr, unique_ptr // ---------------- All the parameters of this app: -------------- struct RBASLAM_Params { // Declare the supported options. TCLAP::CmdLine cmd; TCLAP::ValueArg<std::string> arg_dataset; TCLAP::ValueArg<std::string> arg_gt_map; TCLAP::ValueArg<std::string> arg_gt_path; TCLAP::ValueArg<unsigned int> arg_max_known_feats_per_frame; TCLAP::SwitchArg arg_se2,arg_se3; TCLAP::SwitchArg arg_lm2d,arg_lm3d; TCLAP::SwitchArg arg_graph_slam; TCLAP::ValueArg<std::string> arg_obs; TCLAP::ValueArg<std::string> arg_sensor_params; TCLAP::SwitchArg arg_list_obs; TCLAP::SwitchArg arg_no_gui; TCLAP::SwitchArg arg_gui_step_by_step; TCLAP::ValueArg<std::string> arg_profile_stats; TCLAP::ValueArg<unsigned int> arg_profile_stats_length; TCLAP::SwitchArg arg_add_noise; TCLAP::ValueArg<double> arg_noise; TCLAP::ValueArg<double> arg_noise_ang; TCLAP::ValueArg<unsigned int> arg_max_tree_depth; TCLAP::ValueArg<unsigned int> arg_max_opt_depth; TCLAP::ValueArg<double> arg_max_lambda; TCLAP::ValueArg<unsigned int> arg_max_iters; TCLAP::ValueArg<unsigned int> arg_submap_size; TCLAP::ValueArg<unsigned int> arg_verbose; TCLAP::ValueArg<int> arg_random_seed; TCLAP::ValueArg<std::string> arg_rba_params_cfg_file; TCLAP::ValueArg<std::string> arg_write_rba_params_cfg_file; TCLAP::ValueArg<std::string> arg_video; TCLAP::ValueArg<unsigned int> arg_gui_delay; TCLAP::ValueArg<double> arg_video_fps; TCLAP::SwitchArg arg_debug_dump_cur_spantree; TCLAP::ValueArg<std::string> arg_save_final_graph; TCLAP::ValueArg<std::string> arg_save_final_graph_landmarks; TCLAP::SwitchArg arg_eval_overall_sqr_error; TCLAP::SwitchArg arg_eval_overall_se3_error; TCLAP::SwitchArg arg_eval_connectivity; // Parse all cmd-line arguments at construction // --------------------------------------------------- RBASLAM_Params(int argc, char**argv); }; // ---------------- The main RBA-Runner class ----------------------- struct RBA_Run_Base { virtual int run(RBASLAM_Params &params) = 0; RBA_Run_Base() {} virtual ~RBA_Run_Base() {} }; #if MRPT_HAS_CXX11 typedef std::unique_ptr<RBA_Run_Base> RBA_Run_BasePtr; #else typedef std::auto_ptr< RBA_Run_Base > RBA_Run_BasePtr; #endif // Forward decl: template <class KF2KF_POSE_TYPE,class LM_TYPE,class OBS_TYPE, class RBA_OPTIONS> struct RBA_Run; // ----------- RBA Problem factories ---------------------------- template <class KF2KF_POSE_TYPE,class LM_TYPE,class OBS_TYPE> struct RBA_Run_Factory { // Fwd. declaration: instantiated in separate .cpp files to avoid huge RAM requirements while compiling. static RBA_Run_BasePtr create(); }; // ----------- A registry of implemented RBA problems ------------------- // Each implementation should return an empty pointer if the params do not // match the RBA problem type, or a problem object if it does. typedef RBA_Run_BasePtr (*factory_functor_t)( RBASLAM_Params &params); struct RBA_implemented_registry { // It's a singleton: static RBA_implemented_registry & getInstance(); void doRegister(factory_functor_t functor, const std::string &description); RBA_Run_BasePtr searchImplementation( RBASLAM_Params &params) const; void dumpAllKnownProblems() const; private: struct TEntry { const factory_functor_t functor; const std::string description; TEntry(const factory_functor_t functor_, const std::string &description_ ) : functor(functor_),description(description_) { } }; typedef std::list<TEntry> list_t; RBA_implemented_registry() { } list_t m_registered; }; // Declare a "srba_options_t" type for each kind of problem: // ------------------------------------------------------------------------ template <class KF2KF_POSE_TYPE,class LM_TYPE,class OBS_TYPE> struct problem_options_traits_t { // Default implementation: typedef srba::RBA_OPTIONS_DEFAULT srba_options_t; typedef KF2KF_POSE_TYPE kf2kf_pose_t; typedef LM_TYPE landmark_t; typedef OBS_TYPE obs_t; };
53d8d5d81e585cbc8fb9bb890e1ee19ffc1aab00
8a5c16899c2d516b36f830f5343f0818eedd2e05
/mask.h
d3f78ef021a44817036e6ff2961843212f7b06e7
[ "MIT" ]
permissive
fundies/PolyEditQT
3da959f235451d1a9fb08bd893db3c9a275b6f6e
cdcd1c7a14f9731eb2372d7c10d362e23fed096e
refs/heads/master
2020-06-09T17:36:25.490140
2015-08-10T20:13:03
2015-08-10T20:13:03
37,226,365
0
1
null
null
null
null
UTF-8
C++
false
false
2,574
h
mask.h
#ifndef MASK_H #define MASK_H #include <QList> #include <QOpenGLWidget> #include "coordinate.h" #include "shapes.h" /** * @brief The Mask class */ class Mask { public: /** * @brief Mask Constructor * @param parent parent */ Mask(QOpenGLWidget *parent); /** * @brief addc add c * @param c new c */ void addc(Coordinate c); /** * @brief replace replace c * @param index index to replace * @param c new c */ void replace(int index, Coordinate c); /** * @brief deletec delete a c * @param index index to delete */ void deletec(int index); /** * @brief render draw */ void render(); /** * @brief render render a temporary shape based on mouse's position * @param mousePos mouse position */ void render(Coordinate mousePos); /** * @brief clear clear all vertecies */ void clear(); /** * @brief size returns number of vertecies * @return number of vertecies */ int size(); /** * @brief setCircle set the mask type to circle * @param origin origin * @param radius radius */ void setCircle(Coordinate origin, int mRadius); /** * @brief setBox set mask type to box * @param left left * @param top top * @param width width * @param height height */ void setBox(int left, int top, int width, int height); /** * @brief getc returns a coordinate st specified index * @param i index * @return coordinate[index] */ const Coordinate &getc(int index) const; /** * @brief getRadius returns radius if type == circle * @return radius */ int getRadius() const; /** * @brief setRadius set the radius used with circle masks only * @param value */ void setRadius(int radius); /** * @brief setType set the type of mask * @param type Polygon, Circle, Box... */ void setType(const PolyEdit::Shape &type); /** * @brief scale sets the scale * @param scale scale */ void scale(float scale); /** * @brief scale sets the scale * @param x xscale * @param y yscale */ void scale(float x, float y); /** * @brief exportSVG exports mask to SVG file * @param fpath file path */ void exportSVG(QString fpath); private: QList<Coordinate> mcs; QOpenGLWidget *mParent; PolyEdit::Shape mType; float xscale; float yscale; int mRadius; }; #endif // MASK_H
bad5ee158e3ac838190c2bb7c9de0bfaa537e1b2
b3ed13ce7fc528b75e41439ebf38d94e7fbe90da
/libstats/socket/tests/stats_writer_test.cpp
749599ff3143324a38b4423b2c59359e26ef799f
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
Descendant-XI/system_core
b88ba0b88664e94f2e36e918a5ee9cbf28b8fe3b
ed51e0ccf3d3a34f7272f69f29cdecbdbfbc83aa
refs/heads/eleven-staging
2023-06-04T19:09:22.006961
2021-06-16T17:27:32
2021-06-16T17:27:32
334,330,936
1
6
NOASSERTION
2021-03-09T07:33:53
2021-01-30T04:54:05
C++
UTF-8
C++
false
false
1,204
cpp
stats_writer_test.cpp
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include "stats_buffer_writer.h" #include "stats_event.h" #include "stats_socket.h" TEST(StatsWriterTest, TestSocketClose) { AStatsEvent* event = AStatsEvent_obtain(); AStatsEvent_setAtomId(event, 100); AStatsEvent_writeInt32(event, 5); int successResult = AStatsEvent_write(event); AStatsEvent_release(event); // In the case of a successful write, we return the number of bytes written. EXPECT_GT(successResult, 0); EXPECT_FALSE(stats_log_is_closed()); AStatsSocket_close(); EXPECT_TRUE(stats_log_is_closed()); }
218ad514ace543dc73485e722632e29ae17c74f6
367d4dba6b3ff0d26a1e8f8d6238e7d4232165c6
/isoRPG/include/systems/mouse_clicked.h
427799e47dfdbbae108a9972ab7a5706de8b19f0
[]
no_license
osjurso/IsometricRPG
2f5d708c804aa76fb0487efe97ad56e49211c6a8
a635eef4e8889ef8cdf358e0cbecc9db44b0325e
refs/heads/master
2023-04-04T18:02:30.504974
2021-04-21T19:40:37
2021-04-21T19:40:37
157,831,119
2
0
null
null
null
null
UTF-8
C++
false
false
1,040
h
mouse_clicked.h
#ifndef ISORPG_MOUSE_CLICKED_H #define ISORPG_MOUSE_CLICKED_H #include <anax/System.hpp> #include <states/state_base.h> #include <components/Comp_size.h> #include <components/Comp_mousedOver.h> #include <components/Comp_position.h> #include <iostream> #include "loot.h" #include "talk.h" #include <include/systems/pathfinding.h> #include <components/Comp_movable.h> struct MouseClicked : anax::System<anax::Requires<PositionComponent, SizeComponent, MousedOver>> { public: MouseClicked(StateBase::Context context); void Clicked(anax::Entity& player,sf::View cam, float zoom, std::string state); private: void process(anax::Entity& e, float MouseXT, float MouseYT, anax::World& world, anax::Entity player, sf::RenderWindow& window, sf::View cam, float zoom); void processMenu(anax::Entity& e, float MouseXT, float MouseYT,sf::RenderWindow& window, sf::View cam, float zoom); void createPlayerPath(anax::Entity player, float MouseX, float MouseY); StateBase::Context context; }; #endif //ISORPG_MOUSE_CLICKED_H
660b618fcab32edb1889bf4c6a590152065dad3c
820c845012656cdd73c3a2ad7e873be8c1b39488
/twoHashTable.cpp
3d8b9b68be7587be358493c96862d569e9b54023
[]
no_license
amritspandher/GroceryHashTable
014937a2f5c1b8340187c8e866b69ef04e142c02
4060cb006b8c931300aabaa6cb1cce50ca02985f
refs/heads/main
2023-03-06T23:48:26.501785
2021-02-18T19:36:00
2021-02-18T19:36:00
340,156,959
0
0
null
null
null
null
UTF-8
C++
false
false
1,837
cpp
twoHashTable.cpp
//twoHashTable.cpp //Amrit Pandher //12/4/2020 //twoHashTable implementation file #include "twoHashTable.h" #include "UPCEntry.h" #include "list.h" #include <fstream> #include <iostream> using namespace std; TwoHashTable::TwoHashTable(string filename, int size){ //creates a dynamic array of lists and integers, reads data from file and updates arrays this->size = size; arr = new List<UPCEntry>[size]; lengths = new int[size]; string line; ifstream file; UPCEntry entry; file.open(filename); getline(file,line); while(getline(file, line)){ entry = UPCEntry(line); insert(entry); } for(int i = 0; i<size; i++){ lengths[i] = arr[i].size; } } bool TwoHashTable::insert(UPCEntry &item){ //checks hash values with each other and appends to smaller value placement. If both are the same it appends to h1 int h1 = item.hash1(size); int h2 = item.hash2(size); if(arr[h1].size <= arr[h2].size){ arr[h1].InsertNode(0,item); return true; } if(arr[h1].size > arr[h2].size){ arr[h2].InsertNode(0,item); return true; } return false; } Position TwoHashTable::search(UPCEntry &item){ //checks hash1 location, then hash2 location and returns the position of the item int h1 = item.hash1(size); int h2 = item.hash2(size); Position place; if(arr[h1].FindNode(item) != -1){ place.indexInTable = h1; place.indexInBin = arr[h1].FindNode(item); return place; } else if(arr[h2].FindNode(item) != -1){ place.indexInTable = h2; place.indexInBin = arr[h2].FindNode(item); } return place; } float TwoHashTable::getStdDev(){ //returns standard deviation return stddev(lengths, size); }
363d7ea8c6400b4970f0f70fb9a78ec08b5100e9
5990d4faa44eb4010cb62b693eb2b777e02ff599
/Les1/ScheduleOption2/ScheduleOption2/DateTime.h
aec280e4f4caa84c696b38ca6973178be8e32c9f
[]
no_license
gijsoman/INOOP
bb75179709c63d2ace6cd8d1a8e10e740c9d188a
046e2bfc4d845f595ade33f6430fe768dc89b635
refs/heads/master
2021-07-20T03:44:33.372575
2017-10-27T18:01:59
2017-10-27T18:01:59
103,014,695
0
0
null
null
null
null
UTF-8
C++
false
false
172
h
DateTime.h
#pragma once #include <ctime> class DateTime { public: DateTime(); ~DateTime(); int dateYear; int dateMonth; int dateDay; time_t beginTime; time_t enndTime; };
e1b2eae78f57872a0f524fc15ef205bcdae21aa4
433286e87672a10b0cfc08f8e0df4664d03b3d2f
/510B Fox And Two Dots.cpp
25bdbc9ce82c8f7fb021bfaf62744ee6fb8972ee
[]
no_license
LeeTaeSoon/Codeforces
ed4115888d23bf26162319358e0cf4f60011b598
e298c0456b6d72f43293170f0523f54350e2679a
refs/heads/master
2021-04-12T08:15:56.254939
2018-06-05T09:11:30
2018-06-05T09:11:30
126,024,414
2
0
null
null
null
null
UTF-8
C++
false
false
1,846
cpp
510B Fox And Two Dots.cpp
/* B. Fox And Tow Dots ์—ฌ์šฐ Ciel ์€ "Tow Dots" ๋ผ๊ณ  ๋ถˆ๋ฆฌ๋Š” ๋ชจ๋ฐ”์ผ ํผ์ฆ ๊ฒŒ์ž„์„ ํ•˜๊ณ ์žˆ๋‹ค. ๊ธฐ๋ณธ ๋ ˆ๋ฒจ๋“ค์€ n x m ํฌ๊ธฐ์˜ ํŒ์—์„œ ์ง„ํ–‰๋œ๋‹ค. ๊ฐ ์…€์€ ๊ฐ™์€ ์ƒ‰์˜ ์ ์„ ํฌํ•จํ•œ๋‹ค. ์šฐ๋ฆฌ๋Š” ๋‹ค๋ฅธ ์ƒ‰์„ ํ‘œํ˜„ํ•˜๊ธฐ ์œ„ํ•ด ๋‹ค๋ฅธ ๋ผํ‹ด ๋Œ€๋ฌธ์ž๋ฅผ ์‚ฌ์šฉํ•  ๊ฒƒ์ด๋‹ค. ์ด ๊ฒŒ์ž„์˜ ์—ด์‡ ๋Š” ๊ฐ™์€ ์ƒ‰์˜ ์ ๋“ค์„ ํฌํ•จํ•˜๋Š” ์›์„ ์ฐพ๋Š” ๊ฒƒ์ด๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด ๊ทธ๋ฆผ์—์„œ ์›์„ ๋งŒ๋“œ๋Š” 4 ๊ฐœ์˜ ํŒŒ๋ž€ ์ ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค. ๊ณต์‹์ ์œผ๋กœ ์šฐ๋ฆฌ๋Š” d1, d2, ..., dk ์˜ ์•„๋ž˜ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ์—ฐ์†๋˜๋Š” ์ ์„ ์›์ด๋ผ ๋ถ€๋ฅธ๋‹ค. 1. k ๊ฐœ์˜ ์ ๋“ค์€ ๋ชจ๋‘ ๋‹ค๋ฅด๋‹ค. : ๋งŒ์•ฝ i != j ๋ผ๋ฉด di != dj ์ด๋‹ค. 2. k ๋Š” ์ตœ์†Œ 4 ์ด๋‹ค. 3. ๋ชจ๋“  ์ ๋“ค์€ ๊ฐ™์€ ์ƒ‰์ด๋‹ค. 4. 1 <= i <= k - 1 ์ธ ๋ชจ๋“  di ์™€ d(i + 1) ์€ ์ธ์ ‘ํ•œ๋‹ค. ๋˜ํ•œ dk ์™€ d1 ๋˜ํ•œ ์ธ์ ‘ํ•œ๋‹ค. x, y ์…€๋“ค์€ ๋ชจ์„œ๋ฆฌ๋ฅผ ๊ณต์œ ํ•˜๋ฉด ์ธ์ ‘ํ•œ๋‹ค. ์›์ด ์กด์žฌํ•˜๋Š”์ง€ ๊ฒ€์‚ฌํ•ด๋ผ. */ #include <iostream> using namespace std; int n, m; bool dfs(char** arr, int x, int y, char color, int pre) { char c = arr[x][y]; if (abs(c) != color) return false; if (-c == color) return true; arr[x][y] = -color; if (pre != 2 && 0 < x && dfs(arr, x - 1, y, color, 1)) return true; if (pre != 1 && x < n - 1 && dfs(arr, x + 1, y, color, 2)) return true; if (pre != 4 && 0 < y && dfs(arr, x, y - 1, color, 3)) return true; if (pre != 3 && y < m - 1 && dfs(arr, x, y + 1, color, 4)) return true; arr[x][y] = 0; return false; } int main() { cin >> n >> m; char** arr = new char*[n]; for (int i = 0; i < n; i++) { arr[i] = new char[m]; cin >> arr[i]; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (arr[i][j] > 0 && dfs(arr, i, j, arr[i][j], 0)) { cout << "Yes"; return 0; } } } cout << "No"; return 0; }
a415c9b096d615fc954bcb40f8f54e305bc86ec0
fdbfbcf4d6a0ef6f3c1b600e7b8037eed0f03f9e
/manipulation/util/test/robot_plan_interpolator_test.cc
5c3dd9496cfdc6f354498b6fa58eea5d4bad5f34
[ "BSD-3-Clause" ]
permissive
RobotLocomotion/drake
4529c397f8424145623dd70665531b5e246749a0
3905758e8e99b0f2332461b1cb630907245e0572
refs/heads/master
2023-08-30T21:45:12.782437
2023-08-30T15:59:07
2023-08-30T15:59:07
16,256,144
2,904
1,270
NOASSERTION
2023-09-14T20:51:30
2014-01-26T16:11:05
C++
UTF-8
C++
false
false
8,643
cc
robot_plan_interpolator_test.cc
#include "drake/manipulation/util/robot_plan_interpolator.h" #include <gtest/gtest.h> #include "drake/common/find_resource.h" #include "drake/lcmt_robot_plan.hpp" namespace drake { namespace manipulation { namespace util { namespace { static const int kNumJoints = 7; const char* const kIiwaUrdf = "drake/manipulation/models/iiwa_description/urdf/" "iiwa14_polytope_collision.urdf"; const char* const kDualIiwaUrdf = "drake/manipulation/models/iiwa_description/urdf/" "dual_iiwa14_polytope_collision.urdf"; GTEST_TEST(RobotPlanInterpolatorTest, InstanceTest) { // Test that the constructor works and that the expected ports are // present. RobotPlanInterpolator dut(FindResourceOrThrow(kIiwaUrdf)); EXPECT_EQ(dut.get_plan_input_port().get_data_type(), systems::kAbstractValued); EXPECT_EQ(dut.get_state_output_port().get_data_type(), systems::kVectorValued); EXPECT_EQ(dut.get_state_output_port().size(), kNumJoints * 2); EXPECT_EQ(dut.get_acceleration_output_port().get_data_type(), systems::kVectorValued); EXPECT_EQ(dut.get_acceleration_output_port().size(), kNumJoints); } GTEST_TEST(RobotPlanInterpolatorTest, DualInstanceTest) { // Check that the port sizes come out appropriately for a dual armed // model. RobotPlanInterpolator dut(FindResourceOrThrow(kDualIiwaUrdf)); EXPECT_EQ(dut.plant().num_positions(), kNumJoints * 2); EXPECT_EQ(dut.plant().num_velocities(), kNumJoints * 2); EXPECT_EQ(dut.get_plan_input_port().get_data_type(), systems::kAbstractValued); EXPECT_EQ(dut.get_state_output_port().get_data_type(), systems::kVectorValued); EXPECT_EQ(dut.get_state_output_port().size(), kNumJoints * 4); EXPECT_EQ(dut.get_acceleration_output_port().get_data_type(), systems::kVectorValued); EXPECT_EQ(dut.get_acceleration_output_port().size(), kNumJoints * 2); } struct TrajectoryTestCase { TrajectoryTestCase(double time_in, double position_in, double velocity_in, double accel_in) : time(time_in), position(position_in), velocity(velocity_in), accel(accel_in) {} const double time{}; const double position{}; const double velocity{}; const double accel{}; }; void DoTrajectoryTest(InterpolatorType interp_type) { RobotPlanInterpolator dut(FindResourceOrThrow(kIiwaUrdf), interp_type); std::vector<double> t{0, 1, 2, 3, 4}; Eigen::MatrixXd q = Eigen::MatrixXd::Zero(kNumJoints, t.size()); // Only bother with one joint. q(0, 1) = 1; q(0, 2) = 1.5; q(0, 3) = 1.5; q(0, 4) = 1; std::vector<int> info(t.size(), 1); const int num_time_steps = q.cols(); // Encode into an lcmt_robot_plan structure. lcmt_robot_plan plan{}; plan.num_states = num_time_steps; const lcmt_robot_state default_robot_state{}; plan.plan.resize(num_time_steps, default_robot_state); std::vector<std::string> joint_names; for (int i = 0; i < dut.plant().num_joints(); ++i) { const multibody::Joint<double>& joint = dut.plant().get_joint(multibody::JointIndex(i)); if (joint.num_positions() != 1) { continue; } joint_names.push_back(joint.name()); } ASSERT_EQ(joint_names.size(), kNumJoints); for (int i = 0; i < num_time_steps; i++) { lcmt_robot_state& step = plan.plan[i]; step.utime = t[i] * 1e6; step.num_joints = q.rows(); step.joint_name = joint_names; for (int j = 0; j < step.num_joints; j++) { step.joint_position.push_back(q(j, i)); } } std::unique_ptr<systems::Context<double>> context = dut.CreateDefaultContext(); std::unique_ptr<systems::SystemOutput<double>> output = dut.AllocateOutput(); dut.get_plan_input_port().FixValue(context.get(), plan); dut.Initialize(0, Eigen::VectorXd::Zero(kNumJoints), &context->get_mutable_state()); dut.UpdatePlan(context.get()); // Test we're running the plan through time by watching the // positions, velocities, and acceleration change. std::vector<TrajectoryTestCase> cases; std::string interp_str; switch (interp_type) { case InterpolatorType::ZeroOrderHold: interp_str = "Zero Order Hold"; cases.push_back(TrajectoryTestCase{0.5, 0, 0, 0}); cases.push_back(TrajectoryTestCase{1.5, 1, 0, 0}); cases.push_back(TrajectoryTestCase{2.7, 1.5, 0, 0}); cases.push_back(TrajectoryTestCase{3.5, 1.5, 0, 0}); break; case InterpolatorType::FirstOrderHold: interp_str = "First Order Hold"; cases.push_back(TrajectoryTestCase{0.5, 0.5, 1, 0}); cases.push_back(TrajectoryTestCase{1.5, 1.25, 0.5, 0}); cases.push_back(TrajectoryTestCase{2.7, 1.5, 0, 0}); cases.push_back(TrajectoryTestCase{3.5, 1.25, -0.5, 0}); break; case InterpolatorType::Pchip: interp_str = "Pchip"; cases.push_back(TrajectoryTestCase{0.5, 0.417, 1.333, 0.666}); cases.push_back(TrajectoryTestCase{1.5, 1.333, 0.583, -0.666}); cases.push_back(TrajectoryTestCase{2.7, 1.5, 0, 0}); cases.push_back(TrajectoryTestCase{3.5, 1.250, -0.75, 0}); break; case InterpolatorType::Cubic: interp_str = "Cubic"; cases.push_back(TrajectoryTestCase{0.5, 0.3661, 1.232, 1.071}); cases.push_back(TrajectoryTestCase{1.5, 1.357, 0.429, -0.857}); cases.push_back(TrajectoryTestCase{2.7, 1.577, -0.101, -0.900}); cases.push_back(TrajectoryTestCase{3.5, 1.196, -0.642, 0.429}); break; } for (const TrajectoryTestCase& kase : cases) { context->SetTime(kase.time); dut.UpdatePlan(context.get()); dut.CalcOutput(*context, output.get()); const double position = output->get_vector_data(dut.get_state_output_port().get_index()) ->GetAtIndex(0); const double velocity = output->get_vector_data(dut.get_state_output_port().get_index()) ->GetAtIndex(kNumJoints); const double accel = output->get_vector_data(dut.get_acceleration_output_port().get_index()) ->GetAtIndex(0); const double err_tol = 1e-3; EXPECT_NEAR(position, kase.position, err_tol) << "Failed at interpolator type: " << interp_str; EXPECT_NEAR(velocity, kase.velocity, err_tol) << "Failed at interpolator type: " << interp_str; EXPECT_NEAR(accel, kase.accel, err_tol) << "Failed at interpolator type: " << interp_str; } // Check that the final knot point has zero acceleration and // velocity. if (interp_type == InterpolatorType::Cubic || interp_type == InterpolatorType::ZeroOrderHold || interp_type == InterpolatorType::Pchip) { context->SetTime(t.back() + 0.01); dut.UpdatePlan(context.get()); dut.CalcOutput(*context, output.get()); const double velocity = output->get_vector_data(dut.get_state_output_port().get_index()) ->GetAtIndex(kNumJoints); const double accel = output->get_vector_data(dut.get_acceleration_output_port().get_index()) ->GetAtIndex(0); EXPECT_FLOAT_EQ(velocity, 0) << "Failed at interpolator type: " << interp_str; EXPECT_FLOAT_EQ(accel, 0) << "Failed at interpolator type: " << interp_str; } // Check that sending an empty plan causes us to continue to output // the same commanded position. context->SetTime(1); dut.UpdatePlan(context.get()); dut.CalcOutput(*context, output.get()); double position = output->get_vector_data(dut.get_state_output_port().get_index()) ->GetAtIndex(0); EXPECT_DOUBLE_EQ(1, position) << "Failed at interpolator type: " << interp_str; plan.num_states = 0; plan.plan.clear(); dut.get_plan_input_port().FixValue(context.get(), plan); dut.UpdatePlan(context.get()); dut.CalcOutput(*context, output.get()); position = output->get_vector_data(dut.get_state_output_port().get_index()) ->GetAtIndex(0); EXPECT_DOUBLE_EQ(1, position) << "Failed at interpolator type: " << interp_str; } class TrajectoryTestClass : public testing::TestWithParam<InterpolatorType> { public: virtual void SetUp() {} virtual void TearDown() {} }; INSTANTIATE_TEST_SUITE_P(InstantiationName, TrajectoryTestClass, ::testing::Values(InterpolatorType::ZeroOrderHold, InterpolatorType::FirstOrderHold, InterpolatorType::Pchip, InterpolatorType::Cubic)); TEST_P(TrajectoryTestClass, TrajectoryTest) { DoTrajectoryTest(GetParam()); } } // namespace } // namespace util } // namespace manipulation } // namespace drake
33c2ec2e271a96b9ca99e7427df9381d147545cd
f5f2da1cee9b84463fbb5af8657e42bed14666ba
/GAME_MAP.cpp
8cb4f8877693786234d858ba5227491f02b9e7d6
[]
no_license
hosigawa/MYGAME
1b3a329adfb1db8acaabdeb76f52b7c9a0e6c36a
3897d3279a14a2d82ce0ec69206fa0fc34d6761d
refs/heads/master
2021-01-23T11:40:28.623979
2015-03-15T16:52:45
2015-03-15T16:52:45
32,271,513
0
0
null
null
null
null
UTF-8
C++
false
false
3,968
cpp
GAME_MAP.cpp
#include "StdAfx.h" #include<stdio.h> #include"GAME_MAP.h" #include"GAME_ROLE.h" extern int GameState; extern MAN man; extern GAMENPC npc; MAP::MAP() { mapd=NULL; } MAP::~MAP() { if(mapd) { free(mapd); mapd=NULL; } } void MAP::GetClntInfo(HWND hWnd,LPARAM lParam) { gamew=LOWORD(lParam); gameh=HIWORD(lParam); hwnd=hWnd; } int MAP::Getiblocks() { return iblocks; } int MAP::Getmapw() { return mapw; } void MAP::SetView(POINT pt) { View=pt; } POINT MAP::GetView() { return View; } MapData MAP::Getmapd(int seq) { return mapd[seq]; } int MAP::Getgamew() { return gamew; } int MAP::Getgameh() { return gameh; } char* MAP::GetMusic() { return Music; } void MAP::Init(HINSTANCE hinstance,char* pchar) { FILE *fp=NULL; char path[32]={}; fp=fopen(pchar,"rb+"); char temp[512]={}; fgets(temp,32,fp); strcpy(path,"pic/bkground/"); sscanf(temp,"%s",path+13); if(hbmp) DeleteObject(hbmp); hbmp=(HBITMAP)LoadImage(hinstance,path,IMAGE_BITMAP,0,0,LR_LOADFROMFILE); GetObject(hbmp,sizeof(BITMAP),&bm); cxBmp=bm.bmWidth; cyBmp=bm.bmHeight; fgets(temp,32,fp); strcpy(Music,"sound/"); sscanf(temp,"%s",Music+6); fgets(temp,3*sizeof(int),fp); sscanf(temp,"%d%d%d",&iblocks,&mapw,&sourcew); if(mapd) { free(mapd); mapd=NULL; } mapd=(MapData*)malloc(sizeof(MapData)*iblocks); for(int i=0;i<iblocks;i++) { fgets(temp,sizeof(MapData),fp); if(temp[0]==*";") fgets(temp,sizeof(MapData),fp); strcpy(mapd[i].MapName,"maps/"); sscanf(temp,"%d%d%d%d%d%s",&mapd[i].iGroud,&mapd[i].iSecond,&mapd[i].iThird,&mapd[i].ispecial,&mapd[i].iMapPoint,mapd[i].MapName+5); } if(npc.bchange) { fgets(temp,sizeof(int),fp); sscanf(temp,"%d",&npc.NpcNum); HDC hdc=GetDC(hwnd); for(int i=0;i<npc.NpcNum;i++) { ManData md; POINT pt; fgets(temp,512,fp); strcpy(md.path,"pic/role/"); sscanf(temp,"%d%s%s%d%d%s%d%d%d%d%d%d%d%d%d",&md.Id,md.name,md.path+9, &pt.x,&pt.y,md.sex,&md.bVisible,&md.enemy, &md.bWalk,&md.Level,&md.Health,&md.Power,&md.Define, &md.Magic,&md.Speed); npc.man[i].SetbRolerun(false); npc.man[i].SetMand(md); npc.man[i].Init(hinstance,npc.man[i].GetMand().path,4,4); npc.man[i].Setwens(md.enemy); npc.man[i].SetiFrame(md.Level); npc.man[i].Device(hdc); npc.man[i].SetPos(pt.x,pt.y); } ReleaseDC(hwnd,hdc); } fclose(fp); } void MAP::Device(HDC hdc) { if(hcombmp) DeleteObject(hcombmp); hcombmp=CreateCompatibleBitmap(hdc,32*mapw,32*((iblocks-1)/mapw+1)); if(hmask) DeleteObject(hmask); hmask=CreateBitmap(cxBmp,cyBmp,1,1,NULL); if(hdcdest) DeleteDC(hdcdest); hdcdest=CreateCompatibleDC(hdc); if(hdcmask) DeleteDC(hdcmask); hdcmask=CreateCompatibleDC(hdc); if(hdcsrc) DeleteDC(hdcsrc); hdcsrc=CreateCompatibleDC(hdc); SelectObject(hdcmask,hmask); SelectObject(hdcsrc,hbmp); oldColor=SetBkColor(hdcsrc,RGB(0,1,0)); BitBlt(hdcmask,0,0,cxBmp,cyBmp,hdcsrc,0,0,SRCINVERT); SetBkColor(hdcsrc,oldColor); SelectObject(hdcdest,hcombmp); for(int i=0;i<iblocks;i++) { BitBlt(hdcdest,(i%mapw)*32,(i/mapw)*32,32,32,hdcsrc,mapd[i].iGroud%sourcew*32,mapd[i].iGroud/sourcew*32,SRCCOPY); } for(int i=0;i<iblocks;i++) { if(mapd[i].iSecond) { BitBlt(hdcdest,(i%mapw)*32,(i/mapw)*32,32,32,hdcmask,mapd[i].iSecond%sourcew*32,mapd[i].iSecond/sourcew*32,SRCAND); BitBlt(hdcdest,(i%mapw)*32,(i/mapw)*32,32,32,hdcsrc,mapd[i].iSecond%sourcew*32,mapd[i].iSecond/sourcew*32,SRCPAINT); } if(mapd[i].iThird) { BitBlt(hdcdest,(i%mapw)*32,(i/mapw)*32,32,32,hdcmask,mapd[i].iThird%sourcew*32,mapd[i].iThird/sourcew*32,SRCAND); BitBlt(hdcdest,(i%mapw)*32,(i/mapw)*32,32,32,hdcsrc,mapd[i].iThird%sourcew*32,mapd[i].iThird/sourcew*32,SRCPAINT); } } } void MAP::Draw(HDC hdc) { BitBlt(hdc,0,0,32*mapw,32*((iblocks-1)/mapw+1),hdcdest,0,0,SRCCOPY); }
34fe1478989e2f930df73542e89899f7a2fb0978
e36dc5abcbe07d57a79b0f3c091a3a3a4e44a770
/CentralBank.cpp
af42d8599ad079100185a01d63c6ed17ec6d04d6
[]
no_license
sophiepeneva/CurrencyBank
9b97498b14abad9359b920730fd5d0cf72e32707
0323d431fa4e6cb7f619fdc95f82c10b25b7b329
refs/heads/master
2020-03-21T09:27:42.559590
2018-06-23T13:00:33
2018-06-23T13:00:33
138,400,836
0
0
null
null
null
null
UTF-8
C++
false
false
1,905
cpp
CentralBank.cpp
# CurrencyBank #include "CentralBank.h" CentralBank::CentralBank(const char* name, std::vector<Currency> currencies, std::vector<Observer*> observers) { setName(name); this->currencies = currencies; for(int i=0;i<observers.size();i++) { this->observers[i] = observers[i]; } } void CentralBank::CopyFrom(const CentralBank& cB) { setName(cB.name); currencies = cB.currencies; for (int i = 0; i<observers.size(); i++) { observers[i] = cB.observers[i]; } } void CentralBank::setName(const char* n) { name = new char[strlen(n) + 1]; strcpy_s(name, strlen(n) + 1, n); } void CentralBank::setRate(const Currency& c) { for(int i=0;i<currencies.size();i++) { if (strcmp(currencies[i].getName(), c.getName()) == 0) { currencies[i].setRate(c.getRate()); notify(currencies[i]); } } } void CentralBank::deleteCurrency(const Currency& c) { int index = -1; for (int i = 0; i<currencies.size(); i++) { if (strcmp(currencies[i].getName(), c.getName()) == 0)index = i; } if (index != -1) currencies.erase(currencies.begin() + index); else { std::cout << "Action failed : There is no currency with this name"; } } void CentralBank::Destroy() { delete[] name; } void CentralBank::printCurrencies() const { for (int i = 0; i < currencies.size(); i++)currencies[i].print(); } void CentralBank::notify(const Currency& c) const { for (int i = 0; i < observers.size(); i++)observers[i]->update(c); } void CentralBank::registerObserver(const Observer& o) { ConcreteObserver* cO = new ConcreteObserver(o.getName()); observers.push_back(cO); } void CentralBank::unregister(const Observer& o) { int index = -1; for (int i = 0; i < observers.size(); i++) { if (strcmp(observers[i]->getName(), o.getName()) == 0)index = i; } if (index != -1) observers.erase(observers.begin() + index); else { std::cout << "Action failed : There is no observer with this name"; } }
78cb1d557e3fd85cd535f36fffe965c55e17409c
ef34de2efecd0c98854c1a34d21b54277bb30e9d
/hw8/fifo-lifo2/fifo-lifo2/funcs.cpp
4f7de58b9b6bea300dcc96ef06cb48ae0a78d86f
[]
no_license
nowirak/cs201
9ce92bae90af15e4ae32d80048d098d9b2fbe17f
2a3f6833b583760a7e9574f3d64abed5be1eabb3
refs/heads/master
2023-04-11T05:09:01.165269
2021-04-30T07:37:19
2021-04-30T07:37:19
332,578,018
1
0
null
null
null
null
UTF-8
C++
false
false
3,161
cpp
funcs.cpp
/** filename: funcs.cpp author: Nick Wirak date: 4/26/2021 summary: TestFifo: Automatically pushes a sequence of strings to a vector. The sequence is defined in the source code. Then automatically pops, according to fifo, the strings from the first vector to a second vector. The resulting sequence of strings is checked against a known correct sequence defined in the source code. No inputs are necessary to verify fifo functionality. TestLifo: Automatically pushes a sequence of strings to a vector. The sequence is defined in the source code. Then automatically pops, according to lifo, the strings from the first vector to a second vector. The resulting sequence of strings is checked against a known correct sequence defined in the source code. No inputs are necessary to verify lifo functionality. */ #include "funcs.hpp" #include "Container.hpp" #include <iostream> using std::cout; using std::endl; #include <string> using std::string; #include <vector> using std::vector; bool TestFifo() { vector<string> testPushSeq{ "push \"A\"", "push \"B\"", "push \"C\"", "push \"D\"" }; vector<string> testPopSeq{ "pop", "pop", "pop", "pop" }; vector<string> correctReturn{ "A", "B", "C", "D" }; Container storage; vector<string> returnSeq; //Read instruction and push string if appropriate. for (int i = 0; i < 4; i++) { if (testPushSeq.at(i).size() >= 7 && testPushSeq.at(i).substr(0, 6) == "push \"" && testPushSeq.at(i).back() == '"') { storage.fifoPush(testPushSeq.at(i).substr(6, testPushSeq.at(i).size() - 7)); } else { return 0; } } //Read instruction and pop string if appropriate. for (int i = 0; i < 4; i++) { if (testPopSeq.at(i) == "pop") { returnSeq.resize(i + 1); storage.fifoPop(returnSeq.at(i)); } else { return 0; } } //Check returned sequence against the know correct sequence. //Return 0 if there is any inconsistency, return 1 if test //is passed. for (int i = 0; i < 4; i++) { if (returnSeq.at(i) != correctReturn.at(i)) return 0; else return 1; } } bool TestLifo() { vector<string> testPushSeq{ "push \"A\"", "push \"B\"", "push \"C\"", "push \"D\"" }; vector<string> testPopSeq{ "pop", "pop", "pop", "pop" }; vector<string> correctReturn{ "D", "C", "B", "A" }; Container storage; vector<string> returnSeq; //Read instruction and push string if appropriate. for (int i = 0; i < 4; i++) { if (testPushSeq.at(i).size() >= 7 && testPushSeq.at(i).substr(0, 6) == "push \"" && testPushSeq.at(i).back() == '"') { storage.lifoPush(testPushSeq.at(i).substr(6, testPushSeq.at(i).size() - 7)); } else { return 0; } } //Read instruction and pop string if appropriate. for (int i = 0; i < 4; i++) { if (testPopSeq.at(i) == "pop") { returnSeq.resize(i + 1); storage.lifoPop(returnSeq.at(i)); } else { return 0; } } //Check returned sequence against the know correct sequence. //Return 0 if there is any inconsistency, return 1 if test //is passed. for (int i = 0; i < 4; i++) { if (returnSeq.at(i) != correctReturn.at(i)) return 0; else return 1; } }
136ba3bcad95b49d11cf05d1e8fc57176b5a2b84
4ebca3da4bbf909d27fe2051695ab2e011b81927
/GameDemo/Classes/Menu.h
cf003a8af274d76fe407a24dd9e83647951591bd
[]
no_license
980538137/cocos2dx-demo
7218bbe82d2fe645554cfe65085589917454872f
51a32b08218bbaf61deafd1c595b976857d1a4d1
refs/heads/master
2021-01-17T17:07:20.495360
2014-01-02T14:38:10
2014-01-02T14:38:10
null
0
0
null
null
null
null
GB18030
C++
false
false
714
h
Menu.h
//------------------------------ //้กน็›ฎๅ็งฐ๏ผšๆ‰“ๅœฐ้ผ  //------------------------------ //ๅŠŸ่ƒฝๆจกๅ—๏ผš่œๅ•็•Œ้ข //ไฝœ ่€…๏ผšๅญค็‹ผ //ๆœ€ๅŽไฟฎๆ”นๆ—ถ้—ด๏ผš2013/07/30 //------------------------------ #ifndef __MENU_SCENE_H__ #define __MENU_SCENE_H__ #include "cocos2d.h" #include "Box2D/Box2D.h" #include "SimpleAudioEngine.h" #include "cocos-ext.h" USING_NS_CC; USING_NS_CC_EXT; class Menu : public cocos2d::CCLayer { public: virtual bool init(); static cocos2d::CCScene* scene(); void menuCloseCallback(CCObject* pSender); CREATE_FUNC(Menu); virtual void onEnter(); virtual void onEnterTransitionDidFinish(); virtual void onExit(); //ๅฏๅŠจๆธธๆˆ void rungame(CCObject* pSender); }; #endif
2889e6b922ade04a2441e40155cd58029f610377
b91023982fc98e348ca3d8539704e827ecb3a33f
/synthsoma2/databus.h
19022b2377b880ad770f66bfda5ba2004d8c9a8c
[]
no_license
somaproject/synthsoma2
833f1a61090fd5743e92dc49248783c8379b78cc
dd819ef23500b9bfa4ad1f358038b4c7ab3738a8
refs/heads/master
2016-09-06T05:24:49.802259
2009-11-24T15:33:42
2009-11-24T15:33:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,993
h
databus.h
#ifndef __SYNTHSOMA2_DATABUS_H__ #define __SYNTHSOMA2_DATABUS_H__ #include <boost/thread/condition_variable.hpp> #include <synthsoma2/types.h> #include <synthsoma2/netdataserver.h> #include <somanetwork/tspike.h> #include <somanetwork/wave.h> #include <somanetwork/raw.h> namespace synthsoma2 { class IDataBus { public: // visitor callbacks virtual void newData(sn::datasource_t src, const sn::TSpike_t &) =0; virtual void newData(sn::datasource_t src, const sn::Wave_t &) = 0; virtual void newData(sn::datasource_t src, const sn::Raw_t &) = 0; }; class DataBusStats { public: inline DataBusStats() : submittedPackets(0) { } size_t submittedPackets; }; class DataBus : public IDataBus, boost::noncopyable { /* The DataBus is simpler than the EventBus, and as a result we don't need quite as much logic as the event bus. That's a lie, because the data bus does the bulk of its work in its own thread. It polls the data devices in its own thread, and transferrs data to them in its own thread. And it is a slave to the ecycle signal, which triggers a condition variable in the other thread. Note that all of the data types have a src field, and that combined with the data type itself should be enough to pass them off. Inputs: src, TSpike_t, src, Wave_t, src, Raw_t we have a list of pDataSource_t objects, and we go round-robin and invoke, visitor-pattern-style, their visitSubmitData(DataBus*) method, where they can then call one of the type-safe new data methods: DataBus::newData(src, TSpike_t); DataBus::newData(src, Wave_t); DataBus::newData(src, Raw_t); // Performance data is the one place I really care about performance, because we're potentially sending a -ton- of large packets. So the architecture should be as zero-copy as possible. to do this, we mate the data bus more closely with the data network. */ public: typedef std::map<sn::datasource_t, pDataDevice_t> devicemap_t; typedef std::pair<sn::datasource_t, pDataDevice_t> devicepair_t; DataBus(devicemap_t); void ecycle(ecyclecnt_t cnt); // thread-safe void run(); void shutdown(); void setDataSink(pDataSink_t ds); // visitor callbacks void newData(sn::datasource_t src, const sn::TSpike_t &); void newData(sn::datasource_t src, const sn::Wave_t &); void newData(sn::datasource_t src, const sn::Raw_t &); DataBusStats getStats(); private: devicemap_t devices_; pDataSink_t datasink_; bool running_; void ecycle_triggered_thread(); // mutex bool newevent_; boost::condition_variable cond_; boost::mutex mutex_; boost::thread * pthread_; DataBusStats stats_; }; typedef boost::shared_ptr<DataBus> pDataBus_t; } #endif
be6902d39350ef89b8d3c3c7c2c7427ddfed01e2
f4c05c00bedd9252b70f7436804644dba5d2fb95
/ๅ‰‘ๆŒ‡offer_c++/60_ๆŠŠไบŒๅ‰ๆ ‘ๆ‰“ๅฐๆˆๅคš่กŒ.cpp
5392bd1eea617b3b5e0f0e27f447af805ddb1021
[]
no_license
zhugege215/JianzhiOffer_C
af0768556947a2a2592b61f6635dedc54c3ab2b7
7072c21f261fd40eafcd80668e35112d0bc9e766
refs/heads/master
2021-05-02T03:59:00.404897
2019-03-06T00:59:54
2019-03-06T00:59:54
120,907,479
0
0
null
null
null
null
UTF-8
C++
false
false
683
cpp
60_ๆŠŠไบŒๅ‰ๆ ‘ๆ‰“ๅฐๆˆๅคš่กŒ.cpp
#include <vector> #include <queue> using namespace std; struct TreeNode { int val; struct TreeNode *left, *right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; class Solution { public: vector<vector<int>> Print(TreeNode* pRoot) { vector<vector<int> > vec; if (pRoot == nullptr) return vec; queue<TreeNode*> q; q.push(pRoot); while (!q.empty()) { int cur = 0, length = q.size(); vector<int> c; while (cur++ < length) { TreeNode* temp = q.front(); q.pop(); c.push_back(temp->val); if (temp->left) q.push(temp->left); if (temp->right) q.push(temp->right); } vec.push_back(c); } return vec; } };
18c7e4d4775a52e88fbc57f380f1d85a9fc3ed68
03eb3f665c8c9830a6c06d359f3a7e998b781db9
/src/lib/operators/table_scan/column_vs_column_table_scan_impl.hpp
f7a82c64e9af4e52bf7ce8b4a7deb5688331460b
[ "MIT" ]
permissive
hyrise/hyrise
25f8f396fcf3be2e4a4f7c3b432e3999ee0d6c60
46f13fa510aa7e8b232b3081ee1a25b7f0958e55
refs/heads/master
2023-09-01T10:35:56.802881
2023-08-25T07:18:08
2023-08-25T07:18:08
87,414,843
687
156
MIT
2023-09-14T21:17:51
2017-04-06T10:03:31
C++
UTF-8
C++
false
false
1,884
hpp
column_vs_column_table_scan_impl.hpp
#pragma once #include <memory> #include "abstract_table_scan_impl.hpp" #include "types.hpp" namespace hyrise { class Table; /** * @brief Compares two columns to each other * * Supports: * - comparing columns of different numerical data types * - comparing dictionary and value segments * - comparing reference segments * * Note: Since we have ruled out the possibility that a table might have * reference segments and data segments, comparing a reference to a * data segment is not supported. */ class ColumnVsColumnTableScanImpl : public AbstractTableScanImpl { public: ColumnVsColumnTableScanImpl(const std::shared_ptr<const Table>& in_table, const ColumnID left_column_id, const PredicateCondition& predicate_condition, const ColumnID right_column_id); std::string description() const override; std::shared_ptr<RowIDPosList> scan_chunk(ChunkID chunk_id) override; private: const std::shared_ptr<const Table> _in_table; const ColumnID _left_column_id; const PredicateCondition _predicate_condition; const ColumnID _right_column_id; template <EraseTypes erase_comparator_type, typename LeftIterable, typename RightIterable> std::shared_ptr<RowIDPosList> _typed_scan_chunk_with_iterables(ChunkID chunk_id, const LeftIterable& left_iterable, const RightIterable& right_iterable) const; template <EraseTypes erase_comparator_type, typename LeftIterator, typename RightIterator> std::shared_ptr<RowIDPosList> _typed_scan_chunk_with_iterators(ChunkID chunk_id, LeftIterator& left_it, const LeftIterator& left_end, RightIterator& right_it, const RightIterator& right_end) const; }; } // namespace hyrise
5a546895d667bab01575a7f9665033712b01efa8
01aa77758f69215e3fe559140c1fd91f314fb536
/ml/base/math.h
6bba9fd67cff9395ecd0a6b8bdf4d12684a0559e
[]
no_license
yuchenguangfd/Longan
30f1acc66d76a859363a9421bf719b9d9a50f4f8
da895e2704731c055ba36df2f05297186bbdf9fa
refs/heads/master
2020-05-30T06:09:19.404290
2015-06-02T11:32:18
2015-06-02T11:32:18
22,028,930
0
0
null
null
null
null
UTF-8
C++
false
false
480
h
math.h
/* * math.h * Created on: Jan 26, 2015 * Author: chenguangyu */ #ifndef ML_BASE_MATH_H #define ML_BASE_MATH_H #include "common/math/math.h" #include "common/math/vector.h" namespace longan { inline Vector64F Sigmoid(const Vector64F& vec){ Vector64F result(vec.Size()); for (int i = 0; i < vec.Size(); ++i) { result[i] = Math::Sigmoid(vec[i]); } return std::move(result); } } //~ namespace longan #endif // ML_BASE_MATH_H
a641b556bddf57bc74dcc4bd151c121217a74b99
cadb836d9ac9c9e3b618cf44c936015a0aea24a8
/ge2500/LT2512_2023-01-30_Reward_Top_K_Students.cpp
d897baa405d7ae2ac9ca8f3c9eaec17d7a24e890
[]
no_license
checkoutb/LeetCodeCCpp
c6341a9fa5583a69046555a892bb41052624e83c
38832f7ccadf26b781cd8c9783c50916d1380554
refs/heads/master
2023-09-03T22:35:50.266523
2023-09-03T06:31:51
2023-09-03T06:31:51
182,722,336
0
1
null
null
null
null
GB18030
C++
false
false
5,209
cpp
LT2512_2023-01-30_Reward_Top_K_Students.cpp
#include "../header/myheader.h" struct MyTrie { MyTrie* next[26] = {}; int status; // point. MyTrie(int status) : status(status) {} MyTrie() {} }; void showMyTrie(MyTrie* mt, string s) { if (mt->status != 0) { cout << s << " ==== " << mt->status << endl; } //for (MyTrie* nxt : mt->next) for (int i = 0; i < 26; ++i) { MyTrie* nxt = mt->next[i]; if (nxt == nullptr) continue; showMyTrie(nxt, s + string(1, (char)(i + 'a'))); } } class LT2512 { public: // D D // unordered_set<string> pos(begin(pos_feed), end(pos_feed)), neg(begin(neg_feed), end(neg_feed)); //partial_sort(begin(sid), begin(sid) + k, end(sid)); //transform(begin(sid), begin(sid) + k, back_inserter(res), [](const auto& p) { return p.second; }); //Runtime275 ms // Beats // 88.84 % // Memory138.6 MB // Beats // 5 % // good + 3 // bad -1 // vector<int> lt2512a( vector<string>& positive_feedback, vector<string>& negative_feedback, vector<string>& report, vector<int>& student_id, int k) { MyTrie root(0); for (string& s : positive_feedback) { MyTrie* mt = &root; for (char ch : s) { if (mt->next[ch - 'a'] == nullptr) { mt->next[ch - 'a'] = new MyTrie(0); } mt = mt->next[ch - 'a']; } mt->status = 3; } for (string& s : negative_feedback) { MyTrie* mt = &root; for (char ch : s) { if (mt->next[ch - 'a'] == nullptr) { mt->next[ch - 'a'] = new MyTrie(0); } mt = mt->next[ch - 'a']; } mt->status = -1; } #ifdef __test showMyTrie(&root, ""); #endif //priority_queue<pair<int, int>, vector<pair<int, int>>, std::greater<pair<int, int>>> priq; vector<pair<int, int>> vp; int pt = 0; MyTrie* mt = nullptr; bool skp = false; for (int i = 0; i < report.size(); ++i) { pt = 0; mt = &root; skp = false; //for (char ch : report[i]) for (int j = 0; j <= report[i].size(); ++j) { char ch = j == report[i].size() ? ' ' : report[i][j]; if (ch == ' ') { #ifdef __test cout << " " << j << " : " << pt << " - " << mt->status << endl; #endif pt += mt->status; mt = &root; skp = false; continue; } if (skp) continue; if (mt->next[ch - 'a'] == nullptr) { mt = &root; // .... skp = true; //continue; } else { mt = mt->next[ch - 'a']; } } pt += mt->status; vp.push_back(std::make_pair(pt, -student_id[i])); //priq.push(std::make_pair(pt, -student_id[i])); // ๅŒๅˆ†ๆ•ฐ๏ผŒไธ่ƒฝ็›ดๆŽฅ่ธขใ€‚ๅฏไปฅๅ…ˆsortไธ‹ report ๅ’Œ student_id //if (priq.size() > k) // priq.pop(); } sort(begin(vp), end(vp)); vector<int> ans(k); for (int i = k - 1; i >= 0; --i) { //ans[i] = -priq.top().second; ans[i] = -vp[vp.size() - 1 - i].second; //priq.pop(); } return ans; // dfs to delete MyTrie..... } }; int main() { LT2512 lt; //vector<string> vs = { "smart","brilliant","studious" }; //vector<string> vs2 = { "not" }; //vector<string> vs3 = { "this student is not studious","the student is smart" }; //vector<int> vi = {1,2}; //int k = 2; vector<string> vs = { "wgefr","bvptpf","xdfubxy","b","aegzi","leoddbsuxn","egzx","ey","zm" }; vector<string> vs2 = { "hijeexl","vbx","kd","lh","zwoejaa","sc","wey","npdhv","jkjt","uqoa" }; vector<string> vs3 = { "qaaw lh aegzi wey azvlpimv uqoa bvptpf od vbx wgefr", "uqoa egzx m acatblp wey egzx b vbx leoddbsuxn cikhq", "ezla aegzi zozlvyyrav uqoa yacqi egzx leoddbsuxn dmyeedhc bvptpf jkjt", "fhyvkl hijeexl pxcvk ygwqoar uqoa jkjt febjtltzxg q oamhxwibr egzx", "xytp adrexy rm hxpmo bvptpf zwoejaa hijeexl sc uqoa ey", "hijeexl jkjt eif sc sc bvptpf egzx ey kd uqoa", "s ey wgefr wey lh leoddbsuxn jkjt n au b", "wbqtrzr wey wzococvxk ussh axdbjsv fm npdhv ey kd zm", "jkjt wgefr bjplvykmt xdfubxy udemdjge hijeexl zm zwoejaa cvxyehta atktdi" }; vector<int> vi = { 255960841,785571191,451771677,378536391,176054195,40699643, 667928495, 658582184, 641095424 }; int k = 6; myvi v = lt.lt2512a(vs, vs2, vs3, vi, k); showVectorInt(v); return 0; }
9bc78de9fcdc2290738658b6f703633d3276da88
fe93ba244d637aa6ae9716c67cc80b0c3b7e7eab
/lib/ecs/sources/components/Component.cpp
7031f0b9f47d6c60006e5c1b34fef9aaee017138
[]
no_license
Pywwo/rtype
1d2ad47e2caa950b7f844416b92816644dbab341
d12260798d9889aa189aaae4024f77360a9048ff
refs/heads/master
2021-01-09T14:09:54.871199
2020-02-22T11:38:22
2020-02-22T11:38:22
242,329,815
0
0
null
null
null
null
UTF-8
C++
false
false
275
cpp
Component.cpp
/* Created by Romain FOUYER on 05/11/2019 at 10:14. */ #include "components/Component.hpp" ecs::components::Component::Component(ecs::entities::Entity &entity) : _entity(entity) { } ecs::entities::IEntity &ecs::components::Component::getEntity() { return _entity; }
3ef4341fb51a0f8fb1ac682937621f0131e4a4b1
7030bdc16a529c04ebacc9d18c5eff9251320ca9
/stable/player/core/playmanager/v1_02/src/PlayManagerImp.cpp
546dec7fa62e8f6f059e8f781987c5f17d8e0616
[]
no_license
pleasemarkdarkly/iomega_hipzip
cd770e6cf1b1e719098d5e33e810d897249c0f69
ee741ddf30d3f0875420384837ba8eb9581f5bf2
refs/heads/master
2021-05-24T18:53:04.662340
2020-04-07T08:22:21
2020-04-07T08:22:21
253,705,949
4
0
null
null
null
null
UTF-8
C++
false
false
21,794
cpp
PlayManagerImp.cpp
// // PlayManagerImp.cpp // // Copyright (c) 1998 - 2001 Interactive Objects (TM). All rights reserved // // This file was distributed as part of the Dadio (TM) Software Development Kit // under the Dadio (TM) Software Development Kit license. Please see the file // "Dadio Software Development Kit license agreement.pdf" contained in the // "Legal" folder on the Dadio Distribution CD. // #include "PlayManagerImp.h" #include <codec/common/Codec.h> // set_stream_event_data_t definition #include <content/common/ContentManager.h> #include <content/common/Metadata.h> #include <core/events/SystemEvents.h> #include <datasource/datasourcemanager/DataSourceManager.h> #include <datasource/common/DataSource.h> #include <playlist/common/Playlist.h> #include <core/playmanager/PlayManager.h> #include <core/mediaplayer/PlayStream.h> #include <datasource/cddatasource/CDDataSource.h> #include <main/main/DJPlayerState.h> #include <_modules.h> #include <util/debug/debug.h> #if defined(DDOMOD_EXTRAS_CDMETADATA) #include <extras/cdmetadata/CDMetadataEvents.h> #include <extras/cdmetadata/DiskInfo.h> #endif DEBUG_USE_MODULE( PM ); CPlayManagerImp::CPlayManagerImp() { m_pContentManager = NULL; m_pPlaylist = NULL; m_pMediaPlayer = CMediaPlayer::GetInstance(); m_pDataSourceManager = CDataSourceManager::GetInstance(); m_playlistMode = IPlaylist::NORMAL; m_playState = m_pMediaPlayer->GetPlayState(); } CPlayManagerImp::~CPlayManagerImp() { delete m_pPlaylist; } void CPlayManagerImp::AddDataSource( IDataSource* pDS ) { m_pDataSourceManager->AddDataSource( pDS ); } void CPlayManagerImp::RefreshAllContent(IDataSource::RefreshMode mode, int iUpdateChunkSize) { int count = m_pDataSourceManager->GetDataSourceCount(); for( int i = 0; i < count; i++ ) { if (IDataSource* pDS = m_pDataSourceManager->GetDataSourceByIndex( i )) { m_pDataSourceManager->RefreshContent(pDS->GetInstanceID(), mode, iUpdateChunkSize); } } } unsigned short CPlayManagerImp::RefreshContent(int iDataSourceID, IDataSource::RefreshMode mode, int iUpdateChunkSize) { return m_pDataSourceManager->RefreshContent(iDataSourceID, mode, iUpdateChunkSize); } void CPlayManagerImp::NotifyContentUpdate( content_record_update_t* pContentUpdate ) { m_pContentManager->AddContentRecords( pContentUpdate ); if (pContentUpdate->bTwoPass && !pContentUpdate->media.IsEmpty()) { DEBUG(PM, DBGLEV_INFO, "Beginning second pass on DS %d\n", pContentUpdate->iDataSourceID); m_pDataSourceManager->GetContentMetadata(pContentUpdate); } else delete pContentUpdate; } void CPlayManagerImp::NotifyContentMetadataUpdate( content_record_update_t* pContentUpdate ) { m_pContentManager->AddContentRecords( pContentUpdate ); delete pContentUpdate; } void CPlayManagerImp::SetContentManager( IContentManager* pCM ) { m_pContentManager = pCM; } IContentManager* CPlayManagerImp::GetContentManager() const { return m_pContentManager; } void CPlayManagerImp::SetPlaylist( IPlaylist* pPL ) { m_pPlaylist = pPL; } IPlaylist* CPlayManagerImp::GetPlaylist() const { return m_pPlaylist; } void CPlayManagerImp::SetPlaystream( const CPlayStreamSettings* pSettings, FNCreatePlayStream* pfnCreatePlayStream ) { // we can ditch this error code, it's probably not important :> m_pMediaPlayer->SetPlayStreamSettings( pSettings ); m_pMediaPlayer->SetCreatePlayStreamFunction( pfnCreatePlayStream ); } void CPlayManagerImp::SetPlaylistMode(IPlaylist::PlaylistMode mode) { if (m_pPlaylist && ((mode == IPlaylist::RANDOM) || (mode == IPlaylist::REPEAT_RANDOM))) { m_pPlaylist->ReshuffleRandomEntries(); } if( m_pPlaylist ) { if( m_playlistMode == IPlaylist::RANDOM || m_playlistMode == IPlaylist::REPEAT_RANDOM || mode == IPlaylist::RANDOM || mode == IPlaylist::REPEAT_RANDOM || (mode == IPlaylist::NORMAL && m_playlistMode == IPlaylist::REPEAT_ALL && !m_pPlaylist->GetNextEntry(m_pPlaylist->GetCurrentEntry(), mode))) { // The playlist mode changed // The logic here is clunky; certain play mode transitions dont warrant clearing out the autoset track // basically, if we were in a random mode, or are switching to a random mode, assume that the next // track is no longer valid; otherwise, if we were in repeat all and are switching to normal, and are // on the last track, the next track (which is the first track in the playlist) is no longer valid m_pMediaPlayer->InvalidateNextSong(); } } m_playlistMode = mode; } ERESULT CPlayManagerImp::SetSong( IPlaylistEntry* pNewSong ) { ERESULT res = m_pMediaPlayer->SetSong(pNewSong); if (SUCCEEDED(res)) { if (m_playState == CMediaPlayer::NOT_CONFIGURED || m_playState == CMediaPlayer::PAUSED) m_playState = CMediaPlayer::STOPPED; return PM_NO_ERROR; } else return PM_ERROR; } void CPlayManagerImp::Deconfigure() { m_pMediaPlayer->Deconfigure(); m_playState = CMediaPlayer::NOT_CONFIGURED; } ERESULT CPlayManagerImp::Play() { static char SpinBuf[2352]; /* Junk buffer to use in read to spin up CD drive. */ if (m_pMediaPlayer->GetPlayState() == CMediaPlayer::NOT_CONFIGURED) { if (IPlaylistEntry* pEntry = m_pPlaylist->GetCurrentEntry()) { ERESULT res = m_pMediaPlayer->SetSong(pEntry); if (SUCCEEDED(res)) { m_playState = CMediaPlayer::PLAYING; /* Spin the drive to prevent a pause in audio when it comes out of sleep. The pause comes from the CD drive locking the ATA bus while the decoder is trying to write ripped data to the HD. Spinning now puts the pause before playback begins. */ if (CDJPlayerState::GetInstance()->GetSource() == CDJPlayerState::CD) { CDJPlayerState::GetInstance()->GetCDDataSource()->Read(0,1,SpinBuf); } if( FAILED(res = m_pMediaPlayer->Play()) ) { m_playState = m_pMediaPlayer->GetPlayState(); } return res; } else { DEBUG(PM, DBGLEV_WARNING, "Unable to set track: %s\n", pEntry->GetContentRecord()->GetURL()); return res; } } else return PM_NO_GOOD_TRACKS; } else { m_playState = CMediaPlayer::PLAYING; /* See comment above. */ if (CDJPlayerState::GetInstance()->GetSource() == CDJPlayerState::CD) { CDJPlayerState::GetInstance()->GetCDDataSource()->Read(0,1,SpinBuf); } ERESULT res = m_pMediaPlayer->Play(); if( FAILED(res) ) m_playState = m_pMediaPlayer->GetPlayState(); return res; } } ERESULT CPlayManagerImp::Pause() { ERESULT res = m_pMediaPlayer->Pause(); if (SUCCEEDED(res)) m_playState = CMediaPlayer::PAUSED; else m_playState = m_pMediaPlayer->GetPlayState(); return res; } ERESULT CPlayManagerImp::Stop() { ERESULT res = m_pMediaPlayer->Stop(); if (SUCCEEDED(res)) { // Reset the current track. if (m_pPlaylist) { IPlaylistEntry* pEntry = m_pPlaylist->GetCurrentEntry(); if (pEntry) res = m_pMediaPlayer->SetSong(pEntry); } } // sync the playstate m_playState = m_pMediaPlayer->GetPlayState(); // return a mapped error code if( SUCCEEDED(res) ) { return PM_NO_ERROR; } return PM_ERROR; } ERESULT CPlayManagerImp::Seek( unsigned long secSeek ) { return m_pMediaPlayer->Seek( secSeek ); } CMediaPlayer::PlayState CPlayManagerImp::GetPlayState() { // Resynchronize the playstate here if we are in the middle of a transition // if (m_playState == CMediaPlayer::NOT_CONFIGURED) // m_playState = m_pMediaPlayer->GetPlayState(); return m_playState; } ERESULT CPlayManagerImp::NextTrack(bool bBacktrackIfNeeded) { IPlaylistEntry* pNextEntry = m_pPlaylist->SetNextEntry(m_playlistMode); ERESULT res = PM_ERROR; CMediaPlayer::PlayState lastState = m_playState; if( pNextEntry ) { IPlaylistEntry* pCurrentEntry = m_pPlaylist->GetCurrentEntry(); do { // Determine what the next play state should be prior to setting the track m_playState = ( m_playState == CMediaPlayer::PLAYING ? m_playState : CMediaPlayer::STOPPED ); res = m_pMediaPlayer->SetSong( pNextEntry ); if (SUCCEEDED(res)) { if ((lastState == CMediaPlayer::PLAYING) && (m_pMediaPlayer->GetPlayState() != CMediaPlayer::PLAYING)) { if (SUCCEEDED(m_pMediaPlayer->Play())) return PM_PLAYING; } else if (m_playState == CMediaPlayer::NOT_CONFIGURED) m_playState = m_pMediaPlayer->GetPlayState(); return res; } else DEBUG(PM, DBGLEV_WARNING, "Unable to set track: %s\n", pNextEntry->GetContentRecord()->GetURL()); pNextEntry = m_pPlaylist->SetNextEntry(m_playlistMode); } while (pNextEntry && (pNextEntry != pCurrentEntry)); // If a good track wasn't found, then return to the original track. if (FAILED(res) && bBacktrackIfNeeded) { DEBUG(PM, DBGLEV_WARNING, "No good next track found, returning to previous good track\n"); if (m_pPlaylist->SetCurrentEntry(pCurrentEntry)) { if (SUCCEEDED(res = m_pMediaPlayer->SetSong(pCurrentEntry))) { if ((lastState == CMediaPlayer::PLAYING) && (m_pMediaPlayer->GetPlayState() != CMediaPlayer::PLAYING)) { if (SUCCEEDED(m_pMediaPlayer->Play())) return PM_PLAYING; } else if (m_playState == CMediaPlayer::NOT_CONFIGURED) m_playState = m_pMediaPlayer->GetPlayState(); return res; } // Couldn't even set the current song. This is bad. DEBUG(PM, DBGLEV_WARNING, "Couldn't set original track: %s\n", pCurrentEntry->GetContentRecord()->GetURL()); // Try to go to the previous track. if (FAILED(res = PreviousTrack(false))) { DEBUG(PM, DBGLEV_WARNING, "No good files found\n"); // This playlist is invalid. Tell someone. return PM_NO_GOOD_TRACKS; } } } return res; } else return PM_PLAYLIST_END; } ERESULT CPlayManagerImp::PreviousTrack(bool bBacktrackIfNeeded) { IPlaylistEntry* pPreviousEntry = m_pPlaylist->SetPreviousEntry(m_playlistMode); ERESULT res = PM_ERROR; CMediaPlayer::PlayState lastState = m_playState; if( pPreviousEntry ) { IPlaylistEntry* pCurrentEntry = m_pPlaylist->GetCurrentEntry(); do { // Determine what the next play state should be prior to setting the track m_playState = ( m_playState == CMediaPlayer::PLAYING ? m_playState : CMediaPlayer::STOPPED ); res = m_pMediaPlayer->SetSong( pPreviousEntry ); if (SUCCEEDED(res)) { if ((lastState == CMediaPlayer::PLAYING) && (m_pMediaPlayer->GetPlayState() != CMediaPlayer::PLAYING)) { if (SUCCEEDED(m_pMediaPlayer->Play())) return PM_PLAYING; } else if (m_playState == CMediaPlayer::NOT_CONFIGURED) m_playState = m_pMediaPlayer->GetPlayState(); return res; } else DEBUG(PM, DBGLEV_WARNING, "Unable to set track: %s\n", pPreviousEntry->GetContentRecord()->GetURL()); pPreviousEntry = m_pPlaylist->SetPreviousEntry(m_playlistMode); } while (pPreviousEntry && (pPreviousEntry != pCurrentEntry)); // If a good track wasn't found, then return to the original track. if (FAILED(res) && bBacktrackIfNeeded) { DEBUG(PM, DBGLEV_WARNING, "No good next track found, returning to previous good track\n"); if (m_pPlaylist->SetCurrentEntry(pCurrentEntry)) { if (SUCCEEDED(res = m_pMediaPlayer->SetSong(pCurrentEntry))) { if ((lastState == CMediaPlayer::PLAYING) && (m_pMediaPlayer->GetPlayState() != CMediaPlayer::PLAYING)) { if (SUCCEEDED(m_pMediaPlayer->Play())) return PM_PLAYING; } else if (m_playState == CMediaPlayer::NOT_CONFIGURED) m_playState = m_pMediaPlayer->GetPlayState(); return res; } // Couldn't even set the current song. This is bad. DEBUG(PM, DBGLEV_WARNING, "Couldn't set original track: %s\n", pCurrentEntry->GetContentRecord()->GetURL()); // Try to go to the next track. if (FAILED(res = NextTrack(false))) { DEBUG(PM, DBGLEV_WARNING, "No good files found\n"); // This playlist is invalid. Tell someone. return PM_NO_GOOD_TRACKS; } } } return res; } else return PM_PLAYLIST_END; } // The default event handler. ERESULT CPlayManagerImp::HandleEvent( int key, void* data ) { switch( key ) { case EVENT_CONTENT_UPDATE_BEGIN: { DEBUGP( PM, DBGLEV_INFO, "Starting content update on data source %d\n", GET_DATA_SOURCE_ID((int)data)); m_pContentManager->MarkRecordsFromDataSourceUnverified(GET_DATA_SOURCE_ID((int)data)); break; } case EVENT_CONTENT_UPDATE: { NotifyContentUpdate( (content_record_update_t*)data ); break; } case EVENT_CONTENT_UPDATE_END: { DEBUGP( PM, DBGLEV_INFO, "Finished content update on data source %d\n", GET_DATA_SOURCE_ID((int)data)); m_pContentManager->DeleteUnverifiedRecordsFromDataSource(GET_DATA_SOURCE_ID((int)data)); break; } case EVENT_CONTENT_UPDATE_ERROR: { DEBUGP( PM, DBGLEV_INFO, "Error updating content update on data source %d\n", GET_DATA_SOURCE_ID((int)data)); m_pContentManager->DeleteUnverifiedRecordsFromDataSource(GET_DATA_SOURCE_ID((int)data)); break; } case EVENT_CONTENT_METADATA_UPDATE_BEGIN: { DEBUGP( PM, DBGLEV_INFO, "Metadata update begin message from data source %d, scan ID %d\n", GET_DATA_SOURCE_ID((int)data), GET_SCAN_ID((int)data)); m_pDataSourceManager->NotifyContentMetadataUpdateEnd((int)data); break; } case EVENT_CONTENT_METADATA_UPDATE: { NotifyContentMetadataUpdate( (content_record_update_t*)data ); break; } case EVENT_STREAM_AUTOSET: { change_stream_event_data_t* pChangeEvent = (change_stream_event_data_t*)data; // Find the next entry with the given URL. if (m_pPlaylist) { IPlaylistEntry *pPE = m_pPlaylist->GetCurrentEntry(); if (pPE) { do { pPE = m_pPlaylist->GetNextEntry(pPE, m_playlistMode); } while (pPE && strcmp(pPE->GetContentRecord()->GetURL(), pChangeEvent->szURL)); delete [] pChangeEvent->szURL; // delete pChangeEvent->pMediaPlayerMetadata; delete pChangeEvent->pPreviousStream; delete pChangeEvent; if (pPE != NULL) { m_pPlaylist->SetCurrentEntry(pPE); IPlaylistEntry* pNE = m_pPlaylist->GetNextEntry(pPE, m_playlistMode); if( pNE != pPE ) { // Try to get the next track ready. No big deal if it fails. m_pMediaPlayer->SetNextSong(pNE); } return PM_PLAYING; } } } delete [] pChangeEvent->szURL; // delete pChangeEvent->pMediaPlayerMetadata; delete pChangeEvent->pPreviousStream; delete pChangeEvent; // Weren't able to set the playlist to the currently playing entry. That really shouldn't happen. DEBUGP( PM, DBGLEV_ERROR, "EVENT_STREAM_AUTOSET handler couldn't set playlist to new playlist entry\n"); return PM_ERROR; } case EVENT_STREAM_SET: { set_stream_event_data_t* pSSED = (set_stream_event_data_t*)data; delete [] pSSED->szURL; // delete pSSED->pMediaPlayerMetadata; delete pSSED; // Try to get the next track ready. No big deal if it fails. IPlaylistEntry *pPE = m_pPlaylist->GetCurrentEntry(); if (pPE) { IPlaylistEntry* pNE = m_pPlaylist->GetNextEntry(pPE, m_playlistMode); if( pPE != pNE ) { m_pMediaPlayer->SetNextSong(pNE); } } break; } case EVENT_STREAM_PAUSED: { return PM_NO_ERROR; } case EVENT_STREAM_STOPPED: { change_stream_event_data_t* pChangeEvent = (change_stream_event_data_t*)data; delete pChangeEvent->pPreviousStream; delete [] pChangeEvent->szURL; delete pChangeEvent; return PM_NO_ERROR; } case EVENT_STREAM_END: case EVENT_STREAM_FAIL: { change_stream_event_data_t* pChangeEvent = (change_stream_event_data_t*)data; if (pChangeEvent) { // delete pChangeEvent->pMediaPlayerMetadata; delete pChangeEvent->pPreviousStream; delete pChangeEvent; } ERESULT res = NextTrack(); if (SUCCEEDED(res)) { if (m_playState == CMediaPlayer::PLAYING) { if (SUCCEEDED(Play())) return PM_PLAYING; else { m_playState = m_pMediaPlayer->GetPlayState(); return PM_NO_ERROR; } } else return PM_NO_ERROR; } else { m_playState = m_pMediaPlayer->GetPlayState(); return res; } } case EVENT_MEDIA_REMOVED: { DEBUGP( PM, DBGLEV_INFO, "Data source %d media removed\n", (int)data); NotifyMediaRemoved((int)data); break; } case EVENT_MEDIA_INSERTED: { DEBUGP( PM, DBGLEV_INFO, "Data source %d media changed\n", (int)data); NotifyMediaInserted((int)data); break; } #if defined(DDOMOD_EXTRAS_CDMETADATA) case EVENT_CD_METADATA_MULTIPLE_HITS: { cd_multiple_hit_event_t* pEvent = (cd_multiple_hit_event_t*)data; ClearDiskList(pEvent->svDisks); delete pEvent; break; } #endif // DDOMOD_EXTRAS_CDMETADATA default: { DEBUG( PM, DBGLEV_INFO, "Unhandled event %x\n", key ); break; } } return PM_NO_ERROR; } // Called from the event handler when a data source's media is removed. void CPlayManagerImp::NotifyMediaRemoved(int iDataSourceID) { IPlaylistEntry* pCurrentEntry = m_pPlaylist->GetCurrentEntry(); if (pCurrentEntry && (pCurrentEntry->GetContentRecord()->GetDataSourceID() == iDataSourceID)) { m_pMediaPlayer->Deconfigure(); pCurrentEntry = 0; m_playState = CMediaPlayer::STOPPED; } m_pPlaylist->DeleteEntriesFromDataSource(iDataSourceID); if (!pCurrentEntry && (pCurrentEntry = m_pPlaylist->GetCurrentEntry())) { if (FAILED(m_pMediaPlayer->SetSong(pCurrentEntry))) { DEBUG(PM, DBGLEV_WARNING, "Unable to set track: %s\n", pCurrentEntry->GetContentRecord()->GetURL()); m_playState = CMediaPlayer::STOPPED; } else if (m_playState == CMediaPlayer::PLAYING) { if (FAILED(m_pMediaPlayer->Play())) m_playState = m_pMediaPlayer->GetPlayState(); } } m_pContentManager->DeleteRecordsFromDataSource(iDataSourceID); } // Called from the event handler when a data source's media is changed. void CPlayManagerImp::NotifyMediaInserted(int iDataSourceID) { m_pDataSourceManager->RefreshContent(iDataSourceID, IDataSource::DSR_DEFAULT, DS_DEFAULT_CHUNK_SIZE); }