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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7596528a00b1a22c5b3ec9b6c348026f6afe386b | 6e3b592de89cb3e7d594993c784e7059bdb2a9ae | /Source/AllProjects/CQCTrayMon/CQCTrayMon_iTunesTab.cpp | 84c751eceba65b4061761f85226375ca70b2fe62 | [
"MIT"
] | permissive | jjzhang166/CQC | 9aae1b5ffeddde2c87fafc3bb4bd6e3c7a98a1c2 | 8933efb5d51b3c0cb43afe1220cdc86187389f93 | refs/heads/master | 2023-08-28T04:13:32.013199 | 2021-04-16T14:41:21 | 2021-04-16T14:41:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 41,173 | cpp | CQCTrayMon_iTunesTab.cpp | //
// FILE NAME: CQCTrayMon_iTunesTab.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 10/12/2012
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $Log$
//
// ---------------------------------------------------------------------------
// Facility specific includes
// ---------------------------------------------------------------------------
#include "CQCTrayMon.hpp"
// ---------------------------------------------------------------------------
// Do our RTTI macros
// ---------------------------------------------------------------------------
RTTIDecls(TiTMediaRepoEng,TCQCStdMediaRepoEng)
RTTIDecls(TDBQChangeInfo, TObject);
RTTIDecls(TCQCTrayiTunesTab, TCQCTrayMonTab)
// ---------------------------------------------------------------------------
// CLASS: TDBQChangeInfo
// PREFIX: dbci
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TDBQChangeInfo: Constructors and Destructor
// ---------------------------------------------------------------------------
TDBQChangeInfo::TDBQChangeInfo() :
m_bDelete(kCIDLib::False)
, m_i4Database(0)
, m_i4PlayList(0)
, m_i4Src(0)
, m_i4Track(0)
{
}
TDBQChangeInfo::TDBQChangeInfo( const tCIDLib::TInt4 i4Src
, const tCIDLib::TInt4 i4PlayList
, const tCIDLib::TInt4 i4Track
, const tCIDLib::TInt4 i4Database
, const tCIDLib::TBoolean bDelete) :
m_bDelete(bDelete)
, m_i4Database(i4Database)
, m_i4PlayList(i4PlayList)
, m_i4Src(i4Src)
, m_i4Track(i4Track)
{
}
TDBQChangeInfo::TDBQChangeInfo(const TDBQChangeInfo& dbciSrc) :
m_bDelete(dbciSrc.m_bDelete)
, m_i4Database(dbciSrc.m_i4Database)
, m_i4PlayList(dbciSrc.m_i4PlayList)
, m_i4Src(dbciSrc.m_i4Src)
, m_i4Track(dbciSrc.m_i4Track)
{
}
TDBQChangeInfo::~TDBQChangeInfo()
{
}
// ---------------------------------------------------------------------------
// TDBQChangeInfo: Public operators
// ---------------------------------------------------------------------------
TDBQChangeInfo& TDBQChangeInfo::operator=(const TDBQChangeInfo& dbciSrc)
{
if (&dbciSrc != this)
{
m_bDelete = dbciSrc.m_bDelete;
m_i4Database = dbciSrc.m_i4Database;
m_i4PlayList = dbciSrc.m_i4PlayList;
m_i4Src = dbciSrc.m_i4Src;
m_i4Track = dbciSrc.m_i4Track;
}
return *this;
}
// ---------------------------------------------------------------------------
// TDBQChangeInfo: Public, non-virtual methods
// ---------------------------------------------------------------------------
// Return the type of object we represent
tCQCTrayMon::EiTunesObjs TDBQChangeInfo::eObjType() const
{
if (m_i4Database || m_i4Track)
return tCQCTrayMon::EiTunesObjs::Track;
if (m_i4PlayList)
return tCQCTrayMon::EiTunesObjs::PlayList;
return tCQCTrayMon::EiTunesObjs::Source;
}
// ---------------------------------------------------------------------------
// CLASS: TiTMediaRepoEng
// PREFIX: srdb
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TiTMediaRepoEng: Constructors and Destructor
// ---------------------------------------------------------------------------
//
// Indicate the media types we support
//
TiTMediaRepoEng::TiTMediaRepoEng(const TString& strMoniker) :
TCQCStdMediaRepoEng(strMoniker, tCQCMedia::EMTFlags::Music)
{
}
TiTMediaRepoEng::~TiTMediaRepoEng()
{
}
// ---------------------------------------------------------------------------
// TiTMediaRepoEng: Public, inherited methods
// ---------------------------------------------------------------------------
//
// This is called if an image needs to be loaded. We only support large art directly
// so we scale down the large art if they ask for a thumb. We should never get called
// for anything we have already returned, since it will be cached.
//
// Unfortunately we can't cache the large art if we load it to create the thumb. If
// the large art is subsequently asked for, we have to load it again. We give up this
// slight efficiency in order for the standard repo DB engine code that calls this
// to be a lot simpler.
//
// We let exceptions propogate back.
//
tCIDLib::TCard4
TiTMediaRepoEng::c4LoadRawCoverArt( const TMediaImg& mimgToLoad
, TMemBuf& mbufToFill
, const tCQCMedia::ERArtTypes eType)
{
tCIDLib::TCard4 c4Ret = 0;
try
{
//
// If the large art has already been loaded and they want small, then we
// don't have to load the file again.
//
if (eType == tCQCMedia::ERArtTypes::SmlCover)
c4Ret = mimgToLoad.c4QueryArt(mbufToFill, tCQCMedia::ERArtTypes::LrgCover, 0);
if (!c4Ret)
{
//
// Apparently not so load the file. Keep in mind that we have to use the
// large art path here no matter what, since we don't support the small
// directly.
//
const TString& strPath = mimgToLoad.strArtPath(tCQCMedia::ERArtTypes::LrgCover);
if (!strPath.bIsEmpty() && TFileSys::bExists(strPath))
{
TBinaryFile flArt(strPath);
flArt.Open
(
tCIDLib::EAccessModes::Read
, tCIDLib::ECreateActs::OpenIfExists
, tCIDLib::EFilePerms::Default
, tCIDLib::EFileFlags::SequentialScan
);
c4Ret = tCIDLib::TCard4(flArt.c8CurSize());
flArt.c4ReadBuffer(mbufToFill, c4Ret, tCIDLib::EAllData::FailIfNotAll);
}
}
//
// If they asked for small art, let's scale it down since we don't support
// separate thumbs. We use the same persistent id either way, since it's
// the same image.
//
if ((eType == tCQCMedia::ERArtTypes::SmlCover) && c4Ret)
{
c4Ret = facCIDImgFact().c4CompactToJPEG
(
mbufToFill, c4Ret, TSize(kCQCMedia::c4DefThumbSz)
);
}
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
throw;
}
return c4Ret;
}
// ---------------------------------------------------------------------------
// CLASS: TCQCTrayiTunesTab
// PREFIX: wnd
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TCQCTrayiTunesTab: Constructors and Destructor
// ---------------------------------------------------------------------------
TCQCTrayiTunesTab::TCQCTrayiTunesTab() :
TCQCTrayMonTab(L"iTunes Server")
, m_bDBChanges(kCIDLib::False)
, m_bDelImages(kCIDLib::False)
, m_bForceReload(kCIDLib::False)
, m_bQuitNotification(kCIDLib::False)
, m_c4CurVolume(0)
, m_c4EvAdviseId(0)
, m_c4LastFailedCnt(0)
, m_c4LastIgnoredCnt(0)
, m_c4IgnoredCnt(0)
, m_c4LastTitleCnt(0)
, m_c4PlSerialNum(1)
, m_c4TitleCnt(0)
, m_c4TracksFailed(0)
, m_c4TracksIgnored(0)
, m_colDBChanges()
, m_colLogQ()
, m_colPlCmdQ()
, m_eLastStatus(tCQCMedia::ELoadStatus::Init)
, m_eLoadStatus(tCQCMedia::ELoadStatus::Init)
, m_eMediaType(tCQCMedia::EMediaTypes::Music)
, m_ePlState(TiTPlayerIntfServerBase::EPlStates::Stopped)
, m_eStatus(tCQCMedia::ELoadStatus::Init)
, m_i4MainListId(0)
, m_i4MainSrcId(0)
, m_mbufArtLoad(kCQCTrayMon::c4MaxImgPerIdBytes, kCQCTrayMon::c4MaxImgPerIdBytes)
, m_piTunes(nullptr)
, m_piTunesEv(nullptr)
, m_porbsPlIntf(nullptr)
, m_porbsRepoIntf(nullptr)
, m_pwndDelImages(nullptr)
, m_pwndFailedCnt(nullptr)
, m_pwndForceReload(nullptr)
, m_pwndIgnoredCnt(nullptr)
, m_pwndLog(nullptr)
, m_pwndStatus(nullptr)
, m_pwndTitleCnt(nullptr)
, m_srdbEng(TString(L"CQCTrayMon_") + TSysInfo::strIPHostName())
, m_strAllMusicCat(kMedMsgs::midCat_AllMusic, facCQCMedia())
, m_strPlayListCat(kMedMsgs::midCat_PlayLists, facCQCMedia())
, m_strmfUID(8, 0, tCIDLib::EHJustify::Right, L'0')
, m_strmFmt(64UL)
, m_thriTunes
(
TString(L"CQCTrayiTunes")
, TMemberFunc<TCQCTrayiTunesTab>(this, &TCQCTrayiTunesTab::eiTunesThread)
)
, m_tmidUpdate(0)
{
// Set up the path we store the art in
m_pathArtDir = facCQCKit().strClientDataDir();
m_pathArtDir.AddLevel(L"CQCTrayMon");
m_pathArtDir.AddLevel(L"iTunesArt");
}
TCQCTrayiTunesTab::~TCQCTrayiTunesTab()
{
}
// ---------------------------------------------------------------------------
// TCQCTrayiTunesTab: Public, inherited methods
// ---------------------------------------------------------------------------
// This is called after RemoveBindings, to do any final cleanup
tCIDLib::TVoid TCQCTrayiTunesTab::Cleanup()
{
// Stop our iTunes interface thread if it was started
if (m_thriTunes.bIsRunning())
{
try
{
m_thriTunes.ReqShutdownSync(10000);
m_thriTunes.eWaitForDeath(5000);
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
}
// Deregister our remote interfaces
if (m_porbsRepoIntf)
facCIDOrb().DeregisterObject(m_porbsRepoIntf);
if (m_porbsPlIntf)
facCIDOrb().DeregisterObject(m_porbsPlIntf);
}
// Called during shutdown to get us to unbind any bindings we have
tCIDLib::TVoid TCQCTrayiTunesTab::RemoveBindings(tCIDOrbUC::TNSrvProxy& orbcNS)
{
//
// Unbind the interfaces we expose for the iTunes repo and media
// renderer drivers.
//
TString strBind;
try
{
strBind = TiTunesPlCtrlImpl::strImplBinding;
strBind.eReplaceToken(TSysInfo::strIPHostName(), kCIDLib::chLatin_b);
orbcNS->RemoveBinding(strBind, kCIDLib::False);
}
catch(...)
{
}
try
{
strBind = TiTunesRepoCtrlImpl::strImplBinding;
strBind.eReplaceToken(TSysInfo::strIPHostName(), kCIDLib::chLatin_b);
orbcNS->RemoveBinding(strBind, kCIDLib::False);
}
catch(...)
{
}
}
//
// Called during start up to create our tab and any stuff we need.
//
tCIDLib::TVoid TCQCTrayiTunesTab::CreateTab(TTabbedWnd& wndParent)
{
wndParent.c4CreateTab(this, strName());
//
// Create and register our two interfaces
//
// !!NOTE!!
//
// For these we use the local host name as the binding, no
// matter what was set on the command line. The iTunes drivers that
// talk to us must be on the local machine and they automatically
// set up the binding using the local host name.
//
m_porbsPlIntf = new TiTunesPlCtrlImpl(this);
facCIDOrb().RegisterObject(m_porbsPlIntf, tCIDLib::EAdoptOpts::Adopt);
TString strBind = TiTunesPlCtrlImpl::strImplBinding;
strBind.eReplaceToken(TSysInfo::strIPHostName(), kCIDLib::chLatin_b);
facCIDOrbUC().RegRebindObj
(
m_porbsPlIntf->ooidThis()
, strBind
, L"CQC Tray Monitor iTunes Player Interface"
);
m_porbsRepoIntf = new TiTunesRepoCtrlImpl(this);
facCIDOrb().RegisterObject(m_porbsRepoIntf, tCIDLib::EAdoptOpts::Adopt);
strBind = TiTunesRepoCtrlImpl::strImplBinding;
strBind.eReplaceToken(TSysInfo::strIPHostName(), kCIDLib::chLatin_b);
facCIDOrbUC().RegRebindObj
(
m_porbsRepoIntf->ooidThis()
, strBind
, L"CQC Tray Monitor iTunes Repo Interface"
);
// Start up our processing thread
m_thriTunes.Start();
}
// ---------------------------------------------------------------------------
// TCQCTrayiTunesTab: Public, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean
TCQCTrayiTunesTab::bQueryData( const TString& strQType
, const TString& strDataName
, tCIDLib::TCard4& c4BufSz
, THeapBuf& mbufToFill)
{
c4BufSz = 0;
CheckDBReady(CID_LINE);
// Sync with the bgn thread
TLocker lockrSync(&m_mtxSync);
//
// We handle the query for metadata dumps here instead of passing it to
// the engine. We have the serial number info here.
//
if ((strQType == kCQCMedia::strQuery_BinMediaDump)
|| (strQType == kCQCMedia::strQuery_XMLMediaDump))
{
const TMediaDB& mdbDump = m_srdbEng.mdbInfo();
// If the serial number is the same, we return nothing
if (strDataName == m_strDBSerialNum)
{
c4BufSz = 0;
return kCIDLib::False;
}
// Get a dump of the requested type
if (strQType == kCQCMedia::strQuery_BinMediaDump)
{
c4BufSz = mdbDump.c4BuildBinDump
(
mbufToFill, L"CQCTrayMon", m_strDBSerialNum, m_srdbEng.eMediaTypes()
);
}
else
{
c4BufSz = mdbDump.c4BuildXMLDump
(
mbufToFill, L"CQCTrayMon", m_strDBSerialNum, m_srdbEng.eMediaTypes()
);
}
return kCIDLib::True;
}
return m_srdbEng.bQueryData(strQType, strDataName, c4BufSz, mbufToFill);
}
tCIDLib::TBoolean
TCQCTrayiTunesTab::bQueryData2( const TString& strQType
, tCIDLib::TCard4& c4BufSz
, THeapBuf& mbufIO)
{
CheckDBReady(CID_LINE);
// Sync with the bgn thread
TLocker lockrSync(&m_mtxSync);
return m_srdbEng.bQueryData2(strQType, c4BufSz, mbufIO);
}
tCIDLib::TBoolean
TCQCTrayiTunesTab::bQueryTextVal(const TString& strQType
, const TString& strDataName
, TString& strToFill)
{
CheckDBReady(CID_LINE);
// Sync with the bgn thread
TLocker lockrSync(&m_mtxSync);
return m_srdbEng.bQueryTextVal(strQType, strDataName, strToFill);
}
// The driver passes this along in reponse to a write to the ReloadDB field
tCIDLib::TBoolean TCQCTrayiTunesTab::bReloadDB()
{
// Sync while we get this data
TLocker lockrSync(&m_mtxSync);
if (!m_bForceReload)
m_bForceReload = kCIDLib::True;
return kCIDLib::True;
}
tCIDLib::TBoolean
TCQCTrayiTunesTab::bSendData(const TString& strSType
, TString& strDataName
, tCIDLib::TCard4& c4BufSz
, THeapBuf& mbufToSend)
{
CheckDBReady(CID_LINE);
// Sync with the bgn thread
TLocker lockrSync(&m_mtxSync);
return m_srdbEng.bSendData(strSType, strDataName, c4BufSz, mbufToSend);
}
tCIDLib::TCard4
TCQCTrayiTunesTab::c4QueryVal(const TString& strValId)
{
CheckDBReady(CID_LINE);
// Sync with the bgn thread
TLocker lockrSync(&m_mtxSync);
return m_srdbEng.c4QueryVal(strValId);
}
tCIDLib::TCard4
TCQCTrayiTunesTab::c4SendCmd(const TString& strCmdId
, const TString& strParms)
{
CheckDBReady(CID_LINE);
// Special case this oen since we have to handle it ourself
if (strCmdId == kCQCMedia::strCmd_SetUserRating)
{
TString strCookie(strParms);
TString strRating;
strCookie.bSplit(strRating, kCIDLib::chSpace);
strCookie.StripWhitespace();
strRating.StripWhitespace();
tCIDLib::TCard4 c4Rating = strRating.c4Val();
//
// Parse the cookie as a title cookie to make sure it is valid
// and to get the title set id and media type.
//
tCIDLib::TCard2 c2CatId;
tCIDLib::TCard2 c2TitleId;
tCQCMedia::EMediaTypes eMType = facCQCMedia().eParseTitleCookie
(
strCookie, c2CatId, c2TitleId
);
// Looks reasonable so do it
TLocker lockrSync(&m_mtxSync);
//
// Update our in-memory info. He'll return a pointer to the object if it
// is found, and we can use that to call a helper that will apply the
// change to the iTunes database.
//
TMediaDB& mdbTar = m_srdbEng.mdbInfo();
const TMediaTitleSet* pmtsUpdate = mdbTar.pmtsSetTitleRating
(
c2TitleId, eMType, c4Rating
);
if (pmtsUpdate)
{
SetUserRating(*pmtsUpdate, c4Rating);
QLogMsg(L"User rating updated for title '%(1)'", pmtsUpdate->strName());
}
return 1;
}
// Sync with the bgn thread
TLocker lockrSync(&m_mtxSync);
return m_srdbEng.c4SendCmd(strCmdId, strParms);
}
//
// One of the driver support methods. We return the status to the driver
// who can display it. He uses this as a regular ping as well.
//
tCIDLib::TVoid
TCQCTrayiTunesTab::QueryStatus( COP tCQCMedia::ELoadStatus& eCurStatus
, COP tCQCMedia::ELoadStatus& eLoadStatus
, COP TString& strDBSerialNum
, COP tCIDLib::TCard4& c4TitleCnt)
{
// Sync while we get this data
TLocker lockrSync(&m_mtxSync);
c4TitleCnt = m_c4TitleCnt;
eCurStatus = m_eStatus;
eLoadStatus = m_eLoadStatus;
strDBSerialNum = m_strDBSerialNum;
}
// ---------------------------------------------------------------------------
// TCQCTrayiTunesTab: Protected, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean TCQCTrayiTunesTab::bCreated()
{
TParent::bCreated();
// Load up our dialog resource and create our contents within that
TDlgDesc dlgdChildren;
facCQCTrayMon.bCreateDlgDesc(kCQCTrayMon::ridDlg_iTunes, dlgdChildren);
SetBgnColor(TDlgBox::rgbDlgBgn(dlgdChildren.eTheme()));
tCIDCtrls::TWndId widInitFocus;
CreateDlgItems(dlgdChildren, widInitFocus);
// Get typed pointers to some of them
CastChildWnd(*this, kCQCTrayMon::ridDlg_iTunes_DelImages, m_pwndDelImages);
CastChildWnd(*this, kCQCTrayMon::ridDlg_iTunes_FailedCnt, m_pwndFailedCnt);
CastChildWnd(*this, kCQCTrayMon::ridDlg_iTunes_ForceReload, m_pwndForceReload);
CastChildWnd(*this, kCQCTrayMon::ridDlg_iTunes_IgnoredCnt, m_pwndIgnoredCnt);
CastChildWnd(*this, kCQCTrayMon::ridDlg_iTunes_Log, m_pwndLog);
CastChildWnd(*this, kCQCTrayMon::ridDlg_iTunes_Status, m_pwndStatus);
CastChildWnd(*this, kCQCTrayMon::ridDlg_iTunes_TitleCnt, m_pwndTitleCnt);
// Initialize some of the values in case we can't ever start setting them
const TString strInitCnt(L"0");
m_pwndFailedCnt->strWndText(strInitCnt);
m_pwndIgnoredCnt->strWndText(strInitCnt);
m_pwndStatus->strWndText(L"Unknown");
m_pwndTitleCnt->strWndText(strInitCnt);
// Install handlers
m_pwndDelImages->pnothRegisterHandler(this, &TCQCTrayiTunesTab::eClickHandler);
m_pwndForceReload->pnothRegisterHandler(this, &TCQCTrayiTunesTab::eClickHandler);
// Start up an update timer to keep our display status current
m_tmidUpdate = tmidStartTimer(200);
return kCIDLib::True;
}
tCIDLib::TVoid TCQCTrayiTunesTab::Destroyed()
{
// Kill our update timer
if (m_tmidUpdate)
{
StopTimer(m_tmidUpdate);
m_tmidUpdate = 0;
}
// And pass it on
TParent::Destroyed();
}
//
// We start up a timer so that we can keep our display info updated.
//
tCIDLib::TVoid TCQCTrayiTunesTab::Timer(const tCIDCtrls::TTimerId tmidThis)
{
// If not our timer, pass it to our parent and return
if (tmidThis != m_tmidUpdate)
{
TParent::Timer(tmidThis);
return;
}
//
// If the loading status has changed, then update. Don't bother with
// locking here, we are just looking at a basic value.
//
if (m_eLastStatus != m_eStatus)
{
// Copy the new status first, so no timing issues
m_eLastStatus = m_eStatus;
const tCIDLib::TCh* pszNew = pszXlatStatus(m_eLastStatus);
m_pwndStatus->strWndText(pszNew);
// Enable/disable stuff based on state
m_pwndForceReload->SetEnable(m_eLastStatus == tCQCMedia::ELoadStatus::Ready);
}
// If the title count has changed, update that
if (m_c4LastTitleCnt != m_c4TitleCnt)
{
m_c4LastTitleCnt = m_c4TitleCnt;
m_strTimerTmp.SetFormatted(m_c4LastTitleCnt);
m_pwndTitleCnt->strWndText(m_strTimerTmp);
}
// If the ignored count has changed, update that
if (m_c4LastIgnoredCnt != m_c4TracksIgnored)
{
m_c4LastIgnoredCnt = m_c4TracksIgnored;
m_strTimerTmp.SetFormatted(m_c4LastIgnoredCnt);
m_pwndIgnoredCnt->strWndText(m_strTimerTmp);
}
// If the failed count has changed, update that
if (m_c4LastFailedCnt != m_c4TracksFailed)
{
m_c4LastFailedCnt = m_c4TracksFailed;
m_strTimerTmp.SetFormatted(m_c4LastFailedCnt);
m_pwndFailedCnt->strWndText(m_strTimerTmp);
}
// If any log message queued up, output them
if (!m_colLogQ.bIsEmpty())
{
TLocker lockrSync(&m_mtxSync);
while (m_colLogQ.bGetNextMv(m_strTimerTmp, 0, kCIDLib::False))
{
// Add a new line so the output window will treat it as a line
m_strTimerTmp.Append(L"\n");
m_pwndLog->AddString(m_strTimerTmp);
}
}
}
// ---------------------------------------------------------------------------
// TCQCTrayiTunesTab: Private, non-virtual methods
// ---------------------------------------------------------------------------
//
// Once we are loaded, this is called to watch for database change events or
// incoming driver commands to process.
//
tCIDLib::TBoolean TCQCTrayiTunesTab::bCheckEvents(TThread& thrThis)
{
//
// Make sure we are still connected. If not, disconnect and return.
// The thread will start trying to reconnect.
//
if (m_bQuitNotification)
{
Disconnect();
return kCIDLib::False;
}
//
// Seem to be connected still, so see if we got any database change
// notifications. If so, process them.
//
TLocker lockrSync(&m_mtxSync);
try
{
//
// While there are events in the list, process them. We call a
// helper in the overflow file since there's a good bit of work.
//
// If we see the force reload flag or get a shutdown request,
// we break out. In either case, these changes are no longer
// of use.
//
// Just in case, don't allow us to get stuck in here, so we'll
// do up to 64 at at time.
//
tCIDLib::TCard4 c4EvCnt = 0;
while (m_colDBChanges.bGetNext(m_dbciTmp, 5) && (c4EvCnt < 64))
{
if (m_bForceReload || thrThis.bCheckShutdownRequest())
break;
ProcessEvent(m_dbciTmp);
c4EvCnt++;
}
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
// If any player commands, do those
try
{
tCIDLib::TCard4 c4CmdCnt = 0;
while (m_colPlCmdQ.bGetNext(m_plcmdTmp, 5) && (c4CmdCnt < 4))
{
if (m_bForceReload || thrThis.bCheckShutdownRequest())
break;
// Call an command to do the command. This is in the 3 file
ProcessPlCmd(m_plcmdTmp);
c4CmdCnt++;
}
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
//
// If there's currently a track playing and it had duration info, then get
// the current position info.
//
if ((m_ePlState == TiTPlayerIntfServerBase::EPlStates::Playing) && m_enctCurTotal)
StoreCurPos();
return kCIDLib::True;
}
//
// Given an object id, we parse out the four values and give them back.
// For track oriented ones only the i4DB will be useful, the rest will
// be zero.
//
tCIDLib::TBoolean
TCQCTrayiTunesTab::bParseObjUID(const TString& strUID
, tCIDLib::TInt4& i4Src
, tCIDLib::TInt4& i4PL
, tCIDLib::TInt4& i4Track
, tCIDLib::TInt4& i4DB)
{
TStringTokenizer stokUID(&strUID, L"-");
TString strSrc;
TString strPL;
TString strTrack;
TString strDB;
if (!stokUID.bGetNextToken(strSrc)
|| !stokUID.bGetNextToken(strPL)
|| !stokUID.bGetNextToken(strTrack)
|| !stokUID.bGetNextToken(strDB))
{
return kCIDLib::False;
}
try
{
i4Src = strSrc.i4Val(tCIDLib::ERadices::Hex);
i4PL = strPL.i4Val(tCIDLib::ERadices::Hex);
i4Track = strTrack.i4Val(tCIDLib::ERadices::Hex);
i4DB = strDB.i4Val(tCIDLib::ERadices::Hex);
}
catch(...)
{
return kCIDLib::False;
}
return kCIDLib::True;
}
//
// Called by the methods that handle incoming calls from the driver, to
// see if the database is ready.
//
tCIDLib::TVoid
TCQCTrayiTunesTab::CheckDBReady(const tCIDLib::TCard4 c4Line)
{
if (m_eStatus != tCQCMedia::ELoadStatus::Ready)
{
facCQCTrayMon.ThrowErr
(
CID_FILE
, c4Line
, kTrayMonErrs::errciTunes_DBNotReady
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::NotReady
);
}
}
//
// At the end of a database load, if the user as checked the delete images on load
// check box, we go through and find all of the image files not in use and del them.
//
tCIDLib::TVoid TCQCTrayiTunesTab::CleanupArt(TMediaDB& mdbTar)
{
//
// Iterate all of the music images and create a hash set of the paths. We can
// use this below to know which paths are still referenced and which aren't.
//
tCIDLib::TStrHashSet colPaths(109, TStringKeyOps());
const tCIDLib::TCard4 c4ImgCnt = mdbTar.c4ImageCnt(m_eMediaType);
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4ImgCnt; c4Index++)
{
colPaths.objAdd
(
mdbTar.mimgAt(m_eMediaType, c4Index).strArtPath(tCQCMedia::ERArtTypes::LrgCover)
);
}
//
// Iterate all the files in the image directory and see if the path is in the
// list of paths we created above.
//
TDirIter diterLevel;
TFindBuf fndbSearch;
if (!diterLevel.bFindFirst(m_pathArtDir, L"*.*", fndbSearch, tCIDLib::EDirSearchFlags::NormalFiles))
return;
do
{
if (!colPaths.bHasElement(fndbSearch.pathFileName()))
{
try
{
TFileSys::DeleteFile(fndbSearch.pathFileName());
}
catch(...)
{
}
}
} while(diterLevel.bFindNext(fndbSearch));
}
// Handle buttons
tCIDCtrls::EEvResponses
TCQCTrayiTunesTab::eClickHandler(TButtClickInfo& wnotEvent)
{
if (wnotEvent.widSource() == kCQCTrayMon::ridDlg_iTunes_ForceReload)
{
// Just set the force reload flag for the bgn thread to see
m_bForceReload = kCIDLib::True;
}
else if (wnotEvent.widSource() == kCQCTrayMon::ridDlg_iTunes_DelImages)
{
// Just store the state for the bgn thread
m_bDelImages = m_pwndDelImages->bCheckedState();
}
return tCIDCtrls::EEvResponses::Handled;
}
//
// If there are servers installed, i.e. the app shell is running on this
// machine, we start this thread to monitor the state of the service.
//
tCIDLib::EExitCodes
TCQCTrayiTunesTab::eiTunesThread(TThread& thrThis, tCIDLib::TVoid* pData)
{
// Let the calling thread go
thrThis.Sync();
//
// A time stamp for limiting how often we regenerate a DB serial number in
// response to event driven changes. We do 25 seconds. That allows it to
// not lag too much, but also not to do it multiple times for a quick sequence
// of changes.
//
const tCIDLib::TEncodedTime enctDBCInterval(25 * kCIDLib::enctOneSecond);
tCIDLib::TEncodedTime enctNextDBC = TTime::enctNow() + enctDBCInterval;
// Loop until asked to shut down
while (kCIDLib::True)
{
try
{
//
// Based on our current start do the right thing, and decide if
// we want to sleep this round, and how much if so.
//
tCIDLib::TCard4 c4Sleep = 0;
switch(m_eStatus)
{
case tCQCMedia::ELoadStatus::Init :
{
//
// Try to create our COM interface and connect to the
// local iTunes instance.
//
try
{
ConnectToiTunes();
QLogMsg(L"Connected to iTunes successfully");
}
catch(TError& errToCatch)
{
if (facCQCTrayMon.eVerboseLvl() >= tCQCKit::EVerboseLvls::Medium)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
}
// Clear this since we are going to load anyway
m_bForceReload = kCIDLib::False;
// If we didn't move forward, then sleep this round
if (m_eStatus == tCQCMedia::ELoadStatus::Init)
c4Sleep = 25000;
break;
}
case tCQCMedia::ELoadStatus::Loading :
{
// Try to load the database
try
{
LoadDB(thrThis);
}
catch(TError& errToCatch)
{
if (facCQCTrayMon.eVerboseLvl() >= tCQCKit::EVerboseLvls::Medium)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
}
// We either loaded or tried, so clear this if set
m_bForceReload = kCIDLib::False;
// If we didn't move forward, then sleep this round
if (m_eStatus == tCQCMedia::ELoadStatus::Loading)
c4Sleep = 3000;
break;
}
case tCQCMedia::ELoadStatus::Ready :
{
//
// See if we have any database change or player command
// events to process. If so, let's deal with those. this
// will also make sure we are still connected. If not,
// it will disconnect and put us back into connecting
// state.
//
if (bCheckEvents(thrThis))
{
//
// If force reload is set, reset our status and don't
// sleep any. Else, sleep just a bit so we recheck
// quickly when in this state.
//
if (m_bForceReload)
{
m_bForceReload = kCIDLib::False;
StoreNewStatus(tCQCMedia::ELoadStatus::Loading);
}
else
{
c4Sleep = 200;
}
}
//
// If database changes and it's been more than the minimum
// interval, then let's generate a new DB serial number.
//
if (m_bDBChanges)
{
tCIDLib::TEncodedTime enctCur = TTime::enctNow();
if (enctCur >= enctNextDBC)
{
//
// Clear the flag and reset the time stamp first, in
// case of failure below
//
m_bDBChanges = kCIDLib::False;
enctNextDBC = enctCur + enctDBCInterval;
TString strDBSerNum;
CalcDBSerialNum(m_srdbEng.mdbInfo(), strDBSerNum);
//
// Lock and update. The poll thread reads the DB
// serial number member, so we can't just update it
// without locking.
//
TLocker lockrSync(&m_mtxSync);
m_strDBSerialNum = strDBSerNum;
}
}
break;
}
default :
break;
};
if (c4Sleep)
{
// Sleep the indictated amount. Break out if shutdown req
if (!thrThis.bSleep(c4Sleep))
break;
}
else
{
// No sleep, but do a shutdown request check
if (thrThis.bCheckShutdownRequest())
break;
}
}
//
// If we get to these, then something fundamental went wrong, since
// we handle exceptions individually above.
//
// So we panic, and restart. Sleep a little after we disconnect,
// just to back off and let things settle.
//
catch(TError& errToCatch)
{
if (!errToCatch.bLogged()
&& (facCQCTrayMon.eVerboseLvl() >= tCQCKit::EVerboseLvls::Medium))
{
TModule::LogEventObj(errToCatch);
}
Disconnect();
if (!thrThis.bSleep(2000))
break;
}
catch(...)
{
Disconnect();
if (!thrThis.bSleep(2000))
break;
}
}
// Disconnect since we are done
Disconnect();
return tCIDLib::EExitCodes::Normal;
}
//
// Format out the ids of an iTunes object into a unique id we can
// use in our media objects, and to map back and forth between
// them.
//
// See the class level comments for format details.
//
tCIDLib::TVoid
TCQCTrayiTunesTab::FormatListUID(const TDBQChangeInfo& dbciEv
, TString& strUID)
{
TString strTmp;
FormatObjUID
(
dbciEv.m_i4Src, dbciEv.m_i4PlayList, 0, 0, strUID, strTmp
);
}
tCIDLib::TVoid
TCQCTrayiTunesTab::FormatObjUID(const TDBQChangeInfo& dbciEv
, TString& strUID
, TString& strTrackUID)
{
FormatObjUID
(
dbciEv.m_i4Src
, dbciEv.m_i4PlayList
, dbciEv.m_i4Track
, dbciEv.m_i4Database
, strUID
, strTrackUID
);
}
tCIDLib::TVoid
TCQCTrayiTunesTab::FormatObjUID(const tCIDLib::TInt4 i4Src
, const tCIDLib::TInt4 i4PL
, const tCIDLib::TInt4 i4Track
, const tCIDLib::TInt4 i4DB
, TString& strUID
, TString& strTrackUID)
{
// Format the regular id first
TStreamJanitor janFmt(&m_strmFmt);
m_strmFmt.Reset();
m_strmFmt << m_strmfUID
<< TCardinal(i4Src, tCIDLib::ERadices::Hex)
<< TTextOutStream::RepChars(L'-', 1)
<< TCardinal(i4PL, tCIDLib::ERadices::Hex)
<< TTextOutStream::RepChars(L'-', 1)
<< TCardinal(i4Track, tCIDLib::ERadices::Hex)
<< TTextOutStream::RepChars(L'-', 1)
<< TCardinal(i4DB, tCIDLib::ERadices::Hex)
<< kCIDLib::FlushIt;
strUID = m_strmFmt.strData();
// If it's a track related one, do that version
if (i4DB)
{
//
// Set the default format temporarily so that we can put in the
// prefix bit, else it'll get truncated to the formatted width.
// After that we set it back to the UID format.
//
m_strmFmt.Reset();
m_strmFmt << TTextOutStream::strmfDefault()
<< L"00000000-00000000-00000000-"
<< m_strmfUID
<< TCardinal(i4DB, tCIDLib::ERadices::Hex)
<< kCIDLib::FlushIt;
strTrackUID = m_strmFmt.strData();
}
}
// Translate the status into a string
const tCIDLib::TCh*
TCQCTrayiTunesTab::pszXlatStatus(const tCQCMedia::ELoadStatus eStatus)
{
const tCIDLib::TCh* pszNew = L"????";;
switch(m_eLastStatus)
{
case tCQCMedia::ELoadStatus::Init :
pszNew = L"Connecting to iTunes";
break;
case tCQCMedia::ELoadStatus::Loading :
pszNew = L"Loading Database";
break;
case tCQCMedia::ELoadStatus::Ready :
pszNew = L"Database is Ready";
break;
default:
break;
};
return pszNew;
}
//
//
// Sync and queue up a log message on the log queue. Handle the queue
// getting backed up.
//
// We want to limit the length of the formatted values because they are
// typically the names of albums or tracks. So we pre-format them into
// separate strings first and cap/ellipse them if needed.
//
tCIDLib::TVoid TCQCTrayiTunesTab::QLogMsg(const TString& strMsg)
{
TLocker lockrSync(&m_mtxSync);
m_colLogQ.objAdd(strMsg);
}
tCIDLib::TVoid
TCQCTrayiTunesTab::QLogMsg( const TString& strMsg
, const MFormattable& mfmtblToken1)
{
m_strThreadLogTmp = strMsg;
m_strThreadLogTmp2 = L"%(1)";
m_strThreadLogTmp2.eReplaceToken(mfmtblToken1, L'1');
if (m_strThreadLogTmp2.c4Length() > 28)
{
m_strThreadLogTmp2.CapAt(24);
m_strThreadLogTmp2.Append(L"...");
}
m_strThreadLogTmp.eReplaceToken(m_strThreadLogTmp2, L'1');
TLocker lockrSync(&m_mtxSync);
m_colLogQ.objAdd(m_strThreadLogTmp);
}
tCIDLib::TVoid
TCQCTrayiTunesTab::QLogMsg( const TString& strMsg
, const MFormattable& mfmtblToken1
, const MFormattable& mfmtblToken2)
{
m_strThreadLogTmp = strMsg;
m_strThreadLogTmp2 = L"%(1)";
m_strThreadLogTmp2.eReplaceToken(mfmtblToken1, L'1');
if (m_strThreadLogTmp2.c4Length() > 28)
{
m_strThreadLogTmp2.CapAt(24);
m_strThreadLogTmp2.Append(L"...");
}
m_strThreadLogTmp.eReplaceToken(m_strThreadLogTmp2, L'1');
m_strThreadLogTmp2 = L"%(2)";
m_strThreadLogTmp2.eReplaceToken(mfmtblToken2, L'2');
if (m_strThreadLogTmp2.c4Length() > 28)
{
m_strThreadLogTmp2.CapAt(24);
m_strThreadLogTmp2.Append(L"...");
}
m_strThreadLogTmp.eReplaceToken(m_strThreadLogTmp2, L'2');
TLocker lockrSync(&m_mtxSync);
m_colLogQ.objAdd(m_strThreadLogTmp);
}
//
// Called when the bgn thread needs to store a new status. This is only called by
// the iTunes thread. It does set info that is accessed by the repo and player
// threads, but it only sets fundamental values, and the other threads only read
// these values, they don't change them. So no locking is currently required.
//
tCIDLib::TVoid
TCQCTrayiTunesTab::StoreNewStatus(const tCQCMedia::ELoadStatus eToSet)
{
if (eToSet != m_eStatus)
{
m_eStatus = eToSet;
// Bump the player status serial number
m_c4PlSerialNum++;
if (!m_c4PlSerialNum)
m_c4PlSerialNum++;
}
//
// And udpate the load status, which always runs up to loaded and then
// stays there.
//
if ((eToSet > m_eLoadStatus) && (eToSet < tCQCMedia::ELoadStatus::Failed))
m_eLoadStatus = eToSet;
}
|
478f4aa6caedd32ff5448150a0392e79ae743bb2 | 807217f84ac73f15c37e2d34aff75f4523debe2b | /src/debug.hpp | dc8213ea8cdaee625a62413e0caaa1810ca763ea | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | sherief/ygg | bca4b3f4f479b4956e91f2814165b5966d83fa3b | 196b4ae097ca8b48c0fb5640d503e49f6fefd93e | refs/heads/master | 2021-01-24T11:28:09.649257 | 2018-02-05T15:22:19 | 2018-02-05T15:22:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,401 | hpp | debug.hpp | //
// Created by lukas on 20.11.17.
//
#ifndef YGG_DEBUG_HPP
#define YGG_DEBUG_HPP
namespace ygg {
namespace debug {
template<class Node>
Node * dbg_find_root(Node * n) {
while (n->_rbt_parent != nullptr) {
n = n->_rbt_parent;
}
return n;
}
template <class Node, class NodeNameGetter>
class TreePrinter
{
public:
TreePrinter(Node *root_in, NodeNameGetter nng_in)
: root(root_in), nng(nng_in)
{}
void reset_root(Node * new_root)
{
this->root = new_root;
}
void
print() const
{
if (root == nullptr) {
std::cout << "(Empty)\n";
} else {
std::vector<std::string> prefix;
this->print_node(root, prefix, 0);
}
}
private:
void
print_node(Node *node, std::vector<std::string> & prefix, int direction) const
{
for (auto c : prefix) {
std::cout << c;
}
if (direction == 0) {
std::cout << "┌";
} else if (direction < 0) {
std::cout << "├";
prefix.push_back(std::string("│"));
} else {
std::cout << "└";
prefix.push_back(std::string(" "));
}
if (node == nullptr) {
std::cout << "─ (empty)\n";
} else {
std::cout << "┬";
std::cout << " " << nng.get_name(node);
std::cout << "\n";
this->print_node(node->_rbt_left, prefix, -1);
this->print_node(node->_rbt_right, prefix, 1);
}
if (direction != 0) {
prefix.pop_back();
}
}
Node *root;
NodeNameGetter nng;
};
}
}
#endif //YGG_DEBUG_HPP
|
5d7a970339f19ce82b6c1c4288a6ea45735d2c1b | ce8b9dbe1a3c0d9f733dba78237f04819ea6f3d1 | /Control-CPU-usage-curve/StraightForwardSolution.cpp | 9df022ec480f496605403a7d62a82ac8007b1369 | [] | no_license | hcoona/beauty-of-programming | 93e364009dcc0a5edc46a8f6bf258186aec15edd | 68d7b7fd2bf0931fac5155ebbb4a226e54973b80 | refs/heads/master | 2020-04-08T20:50:11.999037 | 2012-12-16T12:45:04 | 2012-12-16T12:45:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 437 | cpp | StraightForwardSolution.cpp | #include "StraightForwardSolution.h"
#include <Windows.h>
#include <stdexcept>
#include "FixProcessorHelper.h"
StraightForwardSolution::StraightForwardSolution(void)
{
}
StraightForwardSolution::~StraightForwardSolution(void)
{
}
void StraightForwardSolution::Draw(void)
{
while(true) {
const DWORD START_TICKS = GetTickCount();
while(GetTickCount() - START_TICKS <= BUSY_TIME) ;
Sleep(IDLE_TIME);
}
} |
db98a3168732011c152d2671435953f6bae88022 | 30292c6c61d53f432ff259e6858bceb9c6365b53 | /RobotBase/ThreadManagement/Thread_management.cpp | c20c63b80752e4d59121cbdf724803653aae5a7a | [] | no_license | Shangzheng98/roboBase | 2e749e0d1578e484c28868095282ed082b4af670 | 8cb68560f4e078aa1a2e3ffd07bce89d8d100c54 | refs/heads/master | 2023-02-06T10:18:07.347687 | 2020-12-15T10:40:42 | 2020-12-15T10:40:42 | 292,761,381 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,530 | cpp | Thread_management.cpp | //
// Created by jsz on 5/19/20.
//
#include "Thread_management.h"
using namespace std;
ThreadManagement::ThreadManagement() {
cout << "THEAD START WORKING !!!" << endl;
buffer.set_capacity(SIZE_);
daheng = new Daheng();
if (daheng->init() == 0) {
printf("fail to init Daheng camera library\n");
return;
}
serialPort = serial_port(name, B115200);
otherParam.level = 1;
otherParam.id = 0;
otherParam.mode = BIGBUFF;
if (otherParam.id == 13) // blue 3
{
otherParam.color = 0; //opposite is red
} else {
otherParam.color = 1;
}
}
void ThreadManagement::ImageProduce() {
cout << " ------ CAMERA PRODUCE TASK ON !!! ------ " << endl;
while (1) {
cv::Mat frame;
daheng->getImage(frame);
buffer_lock.lock();
buffer.push_back(frame);
buffer_lock.unlock();
}
}
void ThreadManagement::AutoAim() {
while (1) {
//auto time0 = static_cast<double>(getTickCount());
while(!aim_ready)
{
printf("aim wait\n");
std::unique_lock<std::mutex> lck_a(aim_mtx);
cond_aim. wait(lck_a);
}
printf("aim work\n");
buffer_lock.lock();
if (buffer.empty()) {
buffer_lock.unlock();
continue;
}
Mat frame = buffer.front();
buffer.pop_front();
buffer_lock.unlock();
//auto time0 = static_cast<double>(getTickCount());
armorDetector.armorTask(frame, otherParam, serialPort);
//time0 = ((double) getTickCount() - time0) / getTickFrequency();
//cout << "use time is " << time0 * 1000 << "ms" << endl;
}
}
void ThreadManagement::Bigbuff() {
BigbufDetector bigebufDetector(serialPort);
while (1) {
while(!buff_ready)
{
printf("buff wait\n");
//sleep(1);
std::unique_lock<std::mutex> lck_b(buff_mtx);
cond_buff.wait(lck_b);
}
printf("buff work\n");
//sleep(2);
buffer_lock.lock();
if (buffer.empty()) {
buffer_lock.unlock();
continue;
}
Mat frame = buffer.front();
buffer.pop_front();
buffer_lock.unlock();
bigebufDetector.feed_im(frame,otherParam);
//bigebufDetector.getTest_result();
}
}
void ThreadManagement::Communication_thread() {
int c;
while ((c = getchar()) != 'q')
{
switch(c)
{
case 'a':
pause('b');
sleep(1);
resume('a');
break;
case 'b':
pause('a');
sleep(1);
resume('b');
break;
}
}
}
void ThreadManagement::pause(char x) {
if (x == 'a')
{
std::unique_lock <std::mutex> lck(aim_mtx);
aim_ready = false;
cond_aim.notify_one();
}
else
{
std::unique_lock <std::mutex> lck(buff_mtx);
buff_ready = false;
cond_buff.notify_one();
}
}
void ThreadManagement::resume(char x) {
if (x == 'a')
{
std::unique_lock <std::mutex> lck(aim_mtx);
aim_ready = true;
cond_aim.notify_one();
}
else
{
std::unique_lock <std::mutex> lck(buff_mtx);
buff_ready = true;
cond_buff.notify_one();
}
}
void ThreadManagement::stop() {
}
ThreadManagement::~ThreadManagement() {
delete daheng;
}
|
f4dec473eeaa9bfffb433ad1679bc92a7d1ea5e9 | 6b550d3d0b182bcddda1f0a175d6b6cd07b60fb3 | /logdevice/common/test/NodesConfigurationInitTest.cpp | b3e2a3007b857e334cc327f5b5896288557a50f4 | [
"BSD-3-Clause"
] | permissive | Rachelmorrell/LogDevice | 5bd04f7ab0bdf9cc6e5b2da4a4b51210cdc9a4c8 | 3a8d800033fada47d878b64533afdf41dc79e057 | refs/heads/master | 2021-06-24T09:10:20.240011 | 2020-04-21T14:10:52 | 2020-04-21T14:13:09 | 157,563,026 | 1 | 0 | NOASSERTION | 2020-04-21T19:20:55 | 2018-11-14T14:43:33 | C++ | UTF-8 | C++ | false | false | 9,700 | cpp | NodesConfigurationInitTest.cpp | /**
* Copyright (c) 2018-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "logdevice/common/NodesConfigurationInit.h"
#include <folly/futures/Future.h>
#include <folly/init/Init.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <gtest/gtest_prod.h>
#include "logdevice/common/Timestamp.h"
#include "logdevice/common/configuration/nodes/NodesConfigurationCodec.h"
#include "logdevice/common/test/InMemNodesConfigurationStore.h"
#include "logdevice/common/test/NodesConfigurationTestUtil.h"
#include "logdevice/common/test/TestUtil.h"
using namespace facebook::logdevice;
using namespace facebook::logdevice::configuration::nodes;
using namespace facebook::logdevice::NodesConfigurationTestUtil;
namespace {
struct MockNodesConfigurationInit : public NodesConfigurationInit {
~MockNodesConfigurationInit() override = default;
using NodesConfigurationInit::NodesConfigurationInit;
void injectExtraSettings(Settings& settings) const override {
settings.enable_initial_get_cluster_state = false;
}
FRIEND_TEST(NodesConfigurationInitTest, ConfigCreation);
};
class TimeControlledNCS : public NodesConfigurationStore {
public:
using Timestamp = ::Timestamp<std::chrono::steady_clock,
detail::Holder,
std::chrono::milliseconds>;
TimeControlledNCS(
std::string config,
std::chrono::milliseconds unavailable_duration,
folly::Optional<std::chrono::milliseconds> get_delay = folly::none)
: config_(std::move(config)),
available_since_(Timestamp::now() + unavailable_duration),
get_delay_(std::move(get_delay)) {}
void getConfig(value_callback_t cb,
folly::Optional<version_t> base_version = {}) const override {
if (Timestamp::now() < available_since_) {
cb(E::NOTREADY, "");
return;
}
if (get_delay_.has_value()) {
folly::makeFuture()
.delayed(get_delay_.value())
.thenValue([mcb = std::move(cb), cfg = config_](auto&&) mutable {
ld_info("Calling delayed callback");
mcb(E::OK, std::move(cfg));
});
} else {
cb(E::OK, config_);
}
}
void getLatestConfig(value_callback_t cb) const override {
getConfig(std::move(cb));
}
Status
getConfigSync(std::string*,
folly::Optional<version_t> base_version = {}) const override {
ld_check(false);
return E::INTERNAL;
}
void readModifyWriteConfig(mutation_callback_t /* mutation callback */,
write_callback_t /* callback */) override {
ld_check(false);
}
void updateConfig(std::string, Condition, write_callback_t) override {
ld_check(false);
}
Status updateConfigSync(std::string,
Condition,
version_t*,
std::string*) override {
return E::INTERNAL;
}
void shutdown() override {}
private:
const std::string config_;
const Timestamp available_since_;
const folly::Optional<std::chrono::milliseconds> get_delay_;
};
TEST(NodesConfigurationInitTest, ConfigCreation) {
MockNodesConfigurationInit init(nullptr, UpdateableSettings<Settings>());
auto server_config =
Configuration::fromJsonFile(TEST_CONFIG_FILE("sample_valid.conf"))
->serverConfig();
auto config = init.buildBootstrappingServerConfig(
{
"10.0.0.2:4440",
"10.0.0.3:4440",
"10.0.0.4:4440",
},
server_config);
EXPECT_NE(nullptr, config);
auto nodes = config->getNodesConfiguration()->getServiceDiscovery();
EXPECT_EQ(3, nodes->numNodes());
EXPECT_EQ("10.0.0.2:4440",
nodes->getNodeAttributesPtr(node_index_t(0))->address.toString());
EXPECT_EQ("10.0.0.3:4440",
nodes->getNodeAttributesPtr(node_index_t(1))->address.toString());
EXPECT_EQ("10.0.0.4:4440",
nodes->getNodeAttributesPtr(node_index_t(2))->address.toString());
}
TEST(NodesConfigurationInitTest, InitTest) {
// Create a dummy nodes configuration
auto node_config = createSimpleNodesConfig(3);
auto metadata_config = createMetaDataLogsConfig(node_config, 2, 1);
node_config.generateNodesConfiguration(metadata_config, config_version_t(2));
auto nodes_configuration = node_config.getNodesConfiguration();
// Serialize it
auto serialized = NodesConfigurationCodec::serialize(*nodes_configuration);
// Write it to the InMemoryStore
auto store = std::make_unique<InMemNodesConfigurationStore>(
"/foo", [](folly::StringPiece) { return vcs_config_version_t(2); });
auto status = store->updateConfigSync(
serialized, NodesConfigurationStore::Condition::overwrite());
EXPECT_EQ(Status::OK, status);
MockNodesConfigurationInit init(
std::move(store), UpdateableSettings<Settings>());
auto fetched_node_config = std::make_shared<UpdateableNodesConfiguration>();
auto current_server_config =
Configuration::fromJsonFile(TEST_CONFIG_FILE("sample_valid.conf"))
->serverConfig();
int success = init.init(fetched_node_config,
make_test_plugin_registry(),
"data:10.0.0.2:4440",
current_server_config);
EXPECT_TRUE(success);
ASSERT_NE(nullptr, fetched_node_config->get());
EXPECT_EQ(vcs_config_version_t(2), fetched_node_config->get()->getVersion());
EXPECT_EQ(3, fetched_node_config->get()->clusterSize());
}
TEST(NodesConfigurationInitTest, Retry) {
auto nodes_configuration = provisionNodes();
auto serialized = NodesConfigurationCodec::serialize(*nodes_configuration);
Settings settings(create_default_settings<Settings>());
settings.nodes_configuration_init_timeout = std::chrono::seconds(10);
settings.nodes_configuration_init_retry_timeout =
chrono_expbackoff_t<std::chrono::milliseconds>(
std::chrono::milliseconds(50), std::chrono::milliseconds(200));
// store will be unavailable for 2 seconds
auto store =
std::make_unique<TimeControlledNCS>(serialized, std::chrono::seconds(2));
MockNodesConfigurationInit init(
std::move(store), UpdateableSettings<Settings>(settings));
auto fetched_node_config = std::make_shared<UpdateableNodesConfiguration>();
auto current_server_config =
Configuration::fromJsonFile(TEST_CONFIG_FILE("sample_valid.conf"))
->serverConfig();
int success = init.init(fetched_node_config,
make_test_plugin_registry(),
"data:10.0.0.2:4440",
current_server_config);
EXPECT_TRUE(success);
ASSERT_NE(nullptr, fetched_node_config->get());
EXPECT_EQ(*nodes_configuration, *fetched_node_config->get());
}
TEST(NodesConfigurationInitTest, Timeout) {
auto nodes_configuration = provisionNodes();
auto serialized = NodesConfigurationCodec::serialize(*nodes_configuration);
Settings settings(create_default_settings<Settings>());
settings.nodes_configuration_init_timeout = std::chrono::seconds(2);
settings.nodes_configuration_init_retry_timeout =
chrono_expbackoff_t<std::chrono::milliseconds>(
std::chrono::milliseconds(50), std::chrono::milliseconds(200));
// store will be unavailable for 300 seconds
auto store = std::make_unique<TimeControlledNCS>(
serialized, std::chrono::seconds(300));
MockNodesConfigurationInit init(
std::move(store), UpdateableSettings<Settings>(settings));
auto fetched_node_config = std::make_shared<UpdateableNodesConfiguration>();
auto current_server_config =
Configuration::fromJsonFile(TEST_CONFIG_FILE("sample_valid.conf"))
->serverConfig();
int success = init.init(fetched_node_config,
make_test_plugin_registry(),
"data:10.0.0.2:4440",
current_server_config);
EXPECT_FALSE(success);
ASSERT_EQ(nullptr, fetched_node_config->get());
}
TEST(NodesConfigurationInitTest, WithLongDurationCallback) {
auto nodes_configuration = provisionNodes();
auto serialized = NodesConfigurationCodec::serialize(*nodes_configuration);
Settings settings(create_default_settings<Settings>());
settings.nodes_configuration_init_timeout = std::chrono::seconds(1);
settings.nodes_configuration_init_retry_timeout =
chrono_expbackoff_t<std::chrono::milliseconds>(
std::chrono::milliseconds(50), std::chrono::milliseconds(200));
// store will be immediately available, however callbacks will be delayed 2s
auto store = std::make_unique<TimeControlledNCS>(
serialized, std::chrono::seconds(0), std::chrono::milliseconds(2000));
MockNodesConfigurationInit init(
std::move(store), UpdateableSettings<Settings>(settings));
auto fetched_node_config = std::make_shared<UpdateableNodesConfiguration>();
auto current_server_config =
Configuration::fromJsonFile(TEST_CONFIG_FILE("sample_valid.conf"))
->serverConfig();
int success = init.init(fetched_node_config,
make_test_plugin_registry(),
"data:10.0.0.2:4440",
current_server_config);
// we should still success after 2 seconds despite that the config init
// timeout is 1s
EXPECT_TRUE(success);
ASSERT_NE(nullptr, fetched_node_config->get());
EXPECT_EQ(*nodes_configuration, *fetched_node_config->get());
}
} // namespace
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
folly::init(&argc, &argv);
return RUN_ALL_TESTS();
}
|
7d1c6a760845f137f4b3fc9069463f5bd3cdcd9a | a809cd70ef136d7e2fcf70a207880f186d019207 | /modules/ui/src/types/Systems.cpp | 9004c1d8a982f1e346620b788e00c7b6c3bbe16f | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license",
"MPL-2.0",
"BSD-3-Clause",
"MIT",
"BSL-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | adobe/lagrange | ea9d4c700ed70003ee9c9ecef55fecd6b9d77ba7 | 2f78a647ecb867619c73489a5e3ea752f26353ef | refs/heads/main | 2023-08-10T05:18:14.852199 | 2023-06-28T18:29:31 | 2023-06-28T18:29:31 | 319,374,542 | 229 | 23 | Apache-2.0 | 2023-08-30T23:21:30 | 2020-12-07T16:14:06 | C++ | UTF-8 | C++ | false | false | 2,923 | cpp | Systems.cpp | /*
* Copyright 2021 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
#include <lagrange/ui/types/Systems.h>
namespace lagrange {
namespace ui {
void Systems::run(Stage stage, Registry& registry)
{
for (auto& item : m_items) {
if (item.stage == stage && item.enabled) item.system(registry);
}
}
StringID Systems::add(Stage stage, const System& system, StringID id /*= 0*/)
{
if (id != 0) {
if (std::find_if(m_items.begin(), m_items.end(), [&](const SystemItem& item) {
return item.id == id;
}) != m_items.end())
return 0;
}
const auto id_final = (id == 0) ? new_id() : id;
SystemItem item;
item.system = system;
item.stage = stage;
item.id = id_final;
m_items.push_back(std::move(item));
std::stable_sort(m_items.begin(), m_items.end(), [](const SystemItem& a, const SystemItem& b) {
return a.stage < b.stage;
});
return id_final;
}
bool Systems::enable(StringID id, bool value)
{
auto it = std::find_if(m_items.begin(), m_items.end(), [&](const SystemItem& item) {
return item.id == id;
});
if (it == m_items.end()) {
return false;
}
it->enabled = value;
return true;
}
bool Systems::succeeds(StringID system, StringID after)
{
assert(system != after);
auto it_sys = std::find_if(m_items.begin(), m_items.end(), [&](const SystemItem& item) {
return item.id == system;
});
auto it_after = std::find_if(m_items.begin(), m_items.end(), [&](const SystemItem& item) {
return item.id == after;
});
if (it_sys == m_items.end() || it_after == m_items.end()) return false;
auto i0 = std::distance(m_items.begin(), it_sys);
auto i1 = std::distance(m_items.begin(), it_after);
if (i0 > i1)
std::rotate(m_items.rend() - i0 - 1, m_items.rend() - i0, m_items.rend() - i1);
else
std::rotate(m_items.begin() + i0, m_items.begin() + i0 + 1, m_items.begin() + i1 + 1);
return true;
}
bool Systems::remove(StringID id)
{
auto it = std::find_if(m_items.begin(), m_items.end(), [&](const SystemItem& item) {
return item.id == id;
});
if (it == m_items.end()) return false;
m_items.erase(it);
return true;
}
StringID Systems::new_id()
{
return m_id_counter++;
}
} // namespace ui
} // namespace lagrange
|
448416e6225fb3673d9b7b253bfa8057221f6c4c | 41962e9c8473e0732d7dbc4713476a67cb212654 | /include/SidecarFile.h | 4300ff23bd907be102628d7fd0d847c28c32c6d5 | [] | no_license | SpatioTemporal/STAREmaster | 26f34a7fe932e59cbfa4d2b1d9128dff27084135 | b37725b925748e51fe3b74ee7e952be56f6ef512 | refs/heads/master | 2023-07-14T18:12:26.432531 | 2021-08-23T09:37:00 | 2021-08-23T09:37:00 | 279,120,040 | 1 | 3 | null | 2021-08-23T09:37:01 | 2020-07-12T18:03:02 | C++ | UTF-8 | C++ | false | false | 2,407 | h | SidecarFile.h | /// @file
/// This class contains the main functionality for creating and
/// manipulating sidecar files.
/// @author Ed Hartnett @date 3/16/20
#include <config.h>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <iomanip>
#include "ssc.h"
#ifndef SIDECAR_FILE_H_
#define SIDECAR_FILE_H_
/** This macro prints an error message with line number and name of
* test program. */
#define NCERR(ret) do { \
fflush(stdout); /* Make sure our stdout is synced with stderr. */ \
fprintf(stderr, "Sorry! Unexpected result, %s, line: %d %s\n", \
__FILE__, __LINE__, nc_strerror(ret)); \
fflush(stderr); \
return SSC_ENETCDF; \
} while (0)
using std::vector;
using std::string;
class SidecarFile {
private:
int ncid;
public:
int writeFile(const std::string fileName, int verbose,
int quiet, int build_level, int i, int j,
double *geo_lat, double *geo_lon,
unsigned long long *index);
/** Write a STARE index. */
int writeSTAREIndex(int verbose, int quiet, int build_level, int i, int j,
double *geo_lat, double *geo_lon,
unsigned long long *stare_index);
/** Write a STARE cover */
int writeSTARECover(int verbose, int quiet,
int stare_cover_size, unsigned long long *stare_cover);
/* Read a STARE sidecar file. */
int read_sidecar_file(const std::string fileName, int verbose, int &num_index,
vector<string> &stare_index_name, vector<size_t> &size_i,
vector<size_t> &size_j, vector<string> &variables,
vector<int> &stare_varid, int &ncid);
int createFile(const std::string fileName, int verbose, char *institution);
int writeSTAREIndex(int verbose, int build_level, int i, int j,
double *geo_lat, double *geo_lon, unsigned long long *stare_index,
vector<string> var_name, string stare_index_name);
int writeSTARECover(int verbose, int stare_cover_size, unsigned long long *stare_cover,
string stare_cover_name);
/** Close the file. */
int close_file();
};
#endif /* SIDECAR_FILE_H_ */
|
7e988471c9060cb00a78f76ba9e10decfb0b5460 | aa20ad6e7a424d050b6175721cda12b17896a573 | /v1/src/cage.cpp | 2fa09fba05bcafc1cb2874f8caebe5edc5c7ac8f | [] | no_license | verenaseverina/tboop1 | 38b6396119000ae927ca15a9cde34215371e6395 | de3d87766a2a563b66c958256a02bca9bb35e5b7 | refs/heads/master | 2021-01-17T05:06:08.107243 | 2017-03-16T02:11:21 | 2017-03-16T02:11:21 | 83,106,488 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,309 | cpp | cage.cpp | #include "cage.h"
#include <bits/stdc++.h>
//using namespace std;
Cage::Cage(int _size, vector<Habitat> &buf) : size(buf.size()) {
h = new Habitat[buf.size()];
for (int i = 0; i < size; i++) {
h[i] = buf[i];
}
neff = -1;
float temp_many_animal = 0.3 * size;
int many_animal = floor(temp_many_animal);
a = new Animal*[many_animal];
/*for (int i = 0; i < many_animal; i++) {
a[i] = new Animal;
}*/
}
Cage::Cage(const Cage& c) : size(c.size) {
h = new Habitat[c.size];
int i;
for (i = 0; i < size; i++) {
h[i] = c.h[i];
}
neff = c.neff;
float temp_many_animal = 0.3 * c.size;
int many_animal = floor(temp_many_animal);
a = new Animal*[many_animal];
for (i = 0; i < many_animal; i++) {
a[i] = c.a[i];
}
}
Cage::~Cage() {
/*delete h;
if (!IsEmpty()) {
for (int i = 0; i < neff; i++) {
delete a[i];
}
delete a;
}*/
}
Cage& Cage::operator=(const Cage& c) {
delete [] h;
delete [] a;
h = new Habitat[c.size];
int i;
for (i = 0; i < size; i++) {
h[i] = c.h[i];
}
float temp_many_animal = 0.3 * c.size;
int many_animal = floor(temp_many_animal);
a = new Animal*[many_animal];
neff = c.neff;
for (i = 0; i < many_animal; i++) {
a[i] = c.a[i];
}
return *this;
}
Cage& Cage::operator=(const vector<Habitat>& v) {
delete [] h;
h = new Habitat[v.size()];
for (int i = 0; i < size; i++) {
h[i] = v[i];
}
return *this;
}
int Cage::GetSize() {
return size;
}
Animal** Cage::GetAnimal() {
return a;
}
Habitat* Cage::GetHabitat() {
return h;
}
void Cage::AddAnimal(char animal, int i) {
int pos_id = 0;
do {
srand(time(NULL));
pos_id = rand() % size;
} while (ContainAnimal(h[pos_id].GetCellRow(), h[pos_id].GetCellCol()));
neff++;
switch(animal) {
case 'H' : {
a[neff] = new Tiger(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
case 'B' : {
a[neff] = new Panda(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
case 'A' : {
a[neff] = new Anoa(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
case 'R' : {
a[neff] = new Rhino(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
case 'D' : {
a[neff] = new Kangaroo(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
case 'L' : {
a[neff] = new Dolphin(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
case 'W' : {
a[neff] = new Whale(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
case 'S' : {
a[neff] = new Shark(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
case 'K' : {
a[neff] = new Kelelawar(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
case 'E' : {
a[neff] = new ElangB(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
case 'T' : {
a[neff] = new Toucan(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
case 'P' : {
a[neff] = new Penguin(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
case 'C' : {
a[neff] = new Crocodile(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
case 'N' : {
a[neff] = new Hippopotamus(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
case 'O' : {
a[neff] = new Ostrich(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
case 'Y' : {
a[neff] = new Kasuari(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
case 'I' : {
a[neff] = new Kiwi(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
case 'F' : {
a[neff] = new FlyingFish(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
case 'Z' : {
a[neff] = new Pelikan(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
case 'M' : {
a[neff] = new Cormorants(h[pos_id].GetCellRow(), h[pos_id].GetCellCol(), i);
break;
}
}
}
bool Cage::ContainAnimal(int x, int y) {
float temp_many_animal = 0.3 * size;
int many_animal = floor(temp_many_animal);
bool found = false;
int i = 0;
if(!IsEmpty()) {
while ((i < many_animal) && (!found)) {
if ((x == a[i]->GetX()) && (y == a[i]->GetY())) {
found = true;
}
else {
i++;
}
}
}
return found;
}
bool Cage::IsFull() {
float temp_many_animal = 0.3 * size;
int many_animal = floor(temp_many_animal);
return (many_animal == neff+1);
}
bool Cage::IsEmpty() {
return (neff == -1);
}
int Cage::GetNeff() {
return neff;
}
void Cage::UpdatePosition() {
for(int i = 0; i <= neff; i++){
bool found = false;
int j = 1;
while(!found) {
//srand(time(NULL));
switch(j) {
case 1:
for (int k = 0; k <= neff; k++) {
int y = a[i]->GetY()-1;
if (y != a[k]->GetY() && InsideCage(a[i]->GetX(),y)) {
a[i]->Move(1);
found = true;
}
}
j++;
break;
case 2:
for (int k = 0; k <= neff; k++) {
int x = a[i]->GetX()+1;
if (x != a[k]->GetX() && InsideCage(x,a[i]->GetY())) {
a[i]->Move(2);
found = true;
}
}
j++;
break;
case 3:
for (int k = 0; k <= neff; k++) {
int y = a[i]->GetY()+1;
if (y != a[k]->GetY() && InsideCage(a[i]->GetX(),y)) {
a[i]->Move(3);
found = true;
}
}
j++;
break;
case 4:
for (int k = 0; k <= neff; k++) {
int x = a[i]->GetX()-1;
if (x != a[k]->GetX() && InsideCage(x,a[i]->GetY())) {
a[i]->Move(4);
found = true;
}
}
j++;
break;
default:
found = true;
break;
}
}
}
}
bool Cage::InsideCage(int x, int y){
int i = 0;
bool found = false;
while (!found && i < size) {
if (x == h[i].GetCellRow() && y == h[i].GetCellCol()) {
found = true;
}
else {
i++;
}
}
return found;
}
|
680cd0578e1d4bf1c162f22b1cc0b9626a8af046 | 3b52957226a012ec352f3f73192fd77828ad501c | /UVA/10140 - Prime Distance.cpp | f2e2f4b1f6c4d0d14ee364d02b7194627f937614 | [] | no_license | jishnusaha/Competetive-Programming | 8912aa92962d4c72712de44449f6e9ac8f34fbbf | 5535ee9d67a37def87541639f488e328ba579a97 | refs/heads/master | 2021-06-30T00:18:26.959910 | 2020-12-21T18:18:37 | 2020-12-21T18:18:37 | 204,193,372 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,166 | cpp | 10140 - Prime Distance.cpp | #include<bits/stdc++.h>
using namespace std;
#define loop(i,n) for(int l=i;l<=n;l++)
#define loop2(i2,n2) for(int l2=i2;l2<=n2;l2++)
#define bloop(n,bn) for(int bl=n;bl>=bn;bl--)
#define il() while(1)
#define pi acos(-1)
#define ll long long
#define caseno printf("Case %d: ",tl);
#define int_limit 2147483647
#define ll_limit 9223372036854775807
const int p_limit=46340; ///comment out constraint and assign sqrt of upper limit in constraint
int status[p_limit/32+1];
vector<int>prime;
void setstatus(int &n,int pos)
{
n|=(1<<pos);
}
int check_status(int n,int pos)
{
return n=n&(1<<pos);
}
void sieve()
{
prime.push_back(2);
int c,i;
int sqrtn=sqrt(p_limit);
for(i=3;i<=sqrtn;i+=2)
{
if(check_status(status[i>>5],i&31)==0)
{
prime.push_back(i);
for(int j=i*i;j<=p_limit;j+=2*i)
{
setstatus(status[j>>5],j&31);
}
}
}
setstatus(status[0],1);
for(;i<=p_limit;i+=2)
{
if(check_status(status[i>>5],i&31)==0)
{
prime.push_back(i);
}
}
}
void seg_sieve(long long l,long long h,vector<int>&seg_prime) ///here 2 will be manually added if it belongs to range
{
if(h<2) return;
if(l<3)
{
l=3;
seg_prime.push_back(2);
}
else if(!(l&1)) l++;
// cout << "taking range : [" << l << "," << h << "]\n";
bool seg_status[h-l+1];
for(long long i=0;i<=h-l;i++) seg_status[i]=true;
// cout << "seg_prime array size : " << sizeof(seg_status)/sizeof(bool) << endl;
for(long long i=1;prime[i]*prime[i]<=h && i<prime.size();i++)
{
long long j=(long long)(l/prime[i])*prime[i];
if(j<l) j+=prime[i];
if(!(j&1)) j+=prime[i];
for(;j<=h;j+=prime[i]*2)
{
if(j!=prime[i]) seg_status[j-l]=false;
}
}
for(long long i=l;i<=h;i++)
{
if(i&1 && seg_status[i-l]==true)
{
seg_prime.push_back(i);
}
}
}
int main()
{
sieve();///taking prime
int l,h;
while(cin >> l)
{
cin >> h;
int max_dif=0,min_dif=int_limit,c1,c2,d1,d2;
vector<int>seg_prime;
seg_sieve(l,h,seg_prime);
// cout << "total prime : " << seg_prime.size() << endl;
int sz=seg_prime.size();
// printing all primes
// for(int i=0;i<sz;i++)
// {
// cout << seg_prime[i] << ' ';
// }
// cout << endl;
for(int i=1;i<sz;i++)
{
if(seg_prime[i]-seg_prime[i-1]<min_dif)
{
c1=seg_prime[i-1];
c2=seg_prime[i];
min_dif=c2-c1;
//cout << "c1 assigned : " << c1 << ". c2 assigned : " << c2 << endl;
}
if(seg_prime[i]-seg_prime[i-1]>max_dif)
{
d1=seg_prime[i-1];
d2=seg_prime[i];
max_dif=d2-d1;
}
}
if(max_dif)
{
printf("%d,%d are closest, %d,%d are most distant.\n",c1,c2,d1,d2);
}
else printf("There are no adjacent primes.\n");
}
} |
78d8cec1192d0254721c9ed4fce763211fdfe574 | 22d72d74732a59594e15d5d2d26ee31e7591e140 | /main_bonus.cpp | 20aa1aed7bc402e6de3cf27a9b9efd485ce39dcc | [] | no_license | yjch91/ft_containers | 0b5c015e5acd5845c54ab920b05ed8a9b4c1f6f9 | a2d30081dc3a5e5630040f8b5be7209620827c0b | refs/heads/main | 2023-06-10T03:49:50.484111 | 2021-07-01T04:50:57 | 2021-07-01T04:50:57 | 364,034,910 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 117 | cpp | main_bonus.cpp | #include "ft_containers_test.hpp"
int main(void)
{
set_test();
multiset_test();
multimap_test();
return (0);
}
|
993cdb9b33a683a9e67f89c782f99844a7c962bb | 2558167a68c1bdd1d4b2f59d7e5f95ae6202ab9a | /HW3/Shader.cpp | 79952fdd03b7235999579c75962e29e0a42a1137 | [] | no_license | Jerryh001/OpenGL-Homework | 62153e70f20e086fe269123e08d0ed4c6834eea5 | c4e9b2615e05484d6d05deedb2cb519b9846ba43 | refs/heads/master | 2021-04-15T05:38:44.946132 | 2018-06-20T04:12:14 | 2018-06-20T04:12:14 | 126,774,196 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,587 | cpp | Shader.cpp | #include "stdafx.h"
#include "Shader.h"
string Shader::ReadFile(const string & path)
{
ifstream file(path);
return string(istreambuf_iterator<char>(file), istreambuf_iterator<char>());
}
GLuint Shader::CompileShader(const GLenum & shaderType, const string & code)
{
GLuint result = glCreateShader(shaderType);
const GLchar* codechar = code.c_str();
glShaderSource(result, 1, &codechar, NULL);
glCompileShader(result);
glGetShaderiv(result, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(result, 512, nullptr, infoLog);
cout << "ERROR::SHADER::COMPILATION_FAILED\n" << infoLog << endl;
};
return result;
}
GLuint Shader::LinkProgram(const GLuint & vertex, const GLuint & fragment)
{
GLuint P = glCreateProgram();
glAttachShader(P, vertex);
glAttachShader(P, fragment);
glLinkProgram(P);
// 打印连接错误(如果有的话)
glGetProgramiv(this->Program, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(this->Program, 512, nullptr, infoLog);
cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << endl;
}
return P;
}
Shader::Shader(const string& vertexPath, const string& fragmentPath)
{
string vShaderCode = ReadFile(vertexPath);
string fShaderCode = ReadFile(fragmentPath);
GLuint vertex = CompileShader(GL_VERTEX_SHADER, vShaderCode);
GLuint fragment = CompileShader(GL_FRAGMENT_SHADER, fShaderCode);
Program = LinkProgram(vertex, fragment);
glDeleteShader(vertex);
glDeleteShader(fragment);
}
void Shader::Use()
{
glUseProgram(Program);
}
Shader::operator GLuint()
{
return Program;
}
|
bb7d49381a36e2620147cec9f96098a85ff5a441 | 9ac5d6ccb0edff8c97d519fa5c19f72906fd87d6 | /2kurs/IV sem/class/18-03-20-2.cpp | b4a912b46ad7fb6d6b61506687046c274a6f5f24 | [] | no_license | reginabezhanyan/study_tasks_contests | 057c38d4b06f4282f5d34b78a6dc6140951977dc | c75726f5a84fb4e29443794aa239ec150cc463f0 | refs/heads/master | 2023-04-09T13:20:44.162918 | 2021-04-14T11:51:43 | 2021-04-14T11:51:43 | 357,884,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,629 | cpp | 18-03-20-2.cpp | #include <map>
#include <iostream>
#include <map>
int main()
{
std::map<std::string, int> m1;
m1.size();
m1["a"] = 10;
std::cout << m1["a"] << std::endl;
std::cout << m1["b"] << std::endl; // значение 0
std::cout << m1.count("b") << std::endl;
std::cout << m1.count("c") << std::endl; //True - False
{
std::map<std::string, int>::iterator it = m1.find("a");
if (it != m1.end()) {
std::cout << it->second << std::endl;
}
}
//можно заключить в {}
if (auto it = m1.find("a"); it != m1.end()) {
std::cout << it->second << std::endl;
}
auto const &m2 = m1;
// std::cout << m2["a"] << std::endl; //не сработает
if (auto it = m2.find("a"); it != m1.end()) {
std::cout << it->second << std::endl;
}
m1.insert({ "d", 100500 });
std::cout << m1["d"] << std::endl;
static const std::map<double, int> m3 {
{ 3.4, 2},
{ 1.2, 11},
}
std::pair<bool, double> p1{true, 3.14};
std::cout << p1.first << "," << p1.second << std::endl;
for(auto i = m2.begin(); it != m2.end();++it) {
std::cout << it->first << "," << it->second << std::endl;
}
for (const auto &p : m2) {
std::cout << p.first << "," << p.second << std::endl;
}
std::pair p2{true, 2.71};
auto p3 = std::makepair(true, 44.4);
for (auto& [ key, value ] : m2) {
std::cout << key << "," << value << std::endl;
//value += 2; // не сработает. Неявно const перешел в value
}
} |
763da6acee389e21e1f3193416e665b305a15b45 | 54c67306d63bb69a5cf381d12108d3dc98ae0f5d | /goalc/build_level/gltf_mesh_extract.h | 1c5c62a8943cd3441e5a35d9dc46f8c292ac6618 | [
"ISC"
] | permissive | open-goal/jak-project | adf30a3459c24afda5b180e3abe1583c93458a37 | d96dce27149fbf58586160cfecb634614f055943 | refs/heads/master | 2023-09-01T21:51:16.736237 | 2023-09-01T16:10:59 | 2023-09-01T16:10:59 | 289,585,720 | 1,826 | 131 | ISC | 2023-09-14T13:27:47 | 2020-08-22T23:55:21 | Common Lisp | UTF-8 | C++ | false | false | 778 | h | gltf_mesh_extract.h | #pragma once
#include <string>
#include "common/custom_data/Tfrag3Data.h"
#include "goalc/build_level/TexturePool.h"
#include "goalc/build_level/collide_common.h"
namespace gltf_mesh_extract {
struct Input {
std::string filename;
TexturePool* tex_pool = nullptr;
bool get_colors = true;
bool auto_wall_enable = true;
float auto_wall_angle = 30.f;
bool double_sided_collide = false;
};
struct TfragOutput {
std::vector<tfrag3::StripDraw> strip_draws;
std::vector<tfrag3::PreloadedVertex> vertices;
std::vector<math::Vector<u8, 4>> color_palette;
};
struct CollideOutput {
std::vector<CollideFace> faces;
};
struct Output {
TfragOutput tfrag;
CollideOutput collide;
};
void extract(const Input& in, Output& out);
} // namespace gltf_mesh_extract |
66104b888b157b36bbe871906dada25fd12878dd | fe3cda9cf77b9afff5de9db1078d2316e95df2e6 | /kstar/opisrc/kwt/src/caImageMbbi.cpp | 6c3ab50bdf4b136e21f8af610d23604db3860958 | [] | no_license | Sangil-Lee/RefCode | c230f9dbab9246c510799cc8bc523e8acfdcf008 | c9bd25d1a9033c0071b70eab17b442b535a188fb | refs/heads/master | 2023-08-08T15:38:42.616284 | 2023-07-22T01:28:15 | 2023-07-22T01:28:15 | 34,648,348 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 6,032 | cpp | caImageMbbi.cpp | /* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
// vim: expandtab
#include "caImageMbbi.h"
class CAImageMbbi::PrivateData
{
public:
PrivateData():
index(0)
{
};
QString pvname;
DisplayMode dmode;
QPixmap pixmap[16];
QPixmap truepixmap;
QPixmap falsepixmap;
int index;
QLabel *label;
};
CAImageMbbi::CAImageMbbi(QWidget *parent):QWidget(parent)
{
initCAImageMbbi();
}
CAImageMbbi::~CAImageMbbi()
{
delete d_data;
}
QSize CAImageMbbi::sizeHint() const
{
return minimumSizeHint();
}
QSize CAImageMbbi::minimumSizeHint() const
{
int mw = 120;
int mh = 100;
QSize sz;
sz += QSize(mw, mh);
return sz;
}
const QString &CAImageMbbi::getPvname() const
{
return d_data->pvname;
}
void CAImageMbbi::setPvname(const QString &name)
{
d_data->pvname = name;
setStatusTip(QString("PVname : ").append(d_data->pvname));
}
CAImageMbbi::DisplayMode CAImageMbbi::getDisplaymode() const
{
return d_data->dmode;
}
void CAImageMbbi::setDisplaymode(DisplayMode dmode)
{
d_data->dmode = dmode;
}
const QPixmap &CAImageMbbi::getZrpixmap() const
{
return d_data->pixmap[0];
}
void CAImageMbbi::setZrpixmap(const QPixmap &pxm)
{
d_data->pixmap[0]= pxm;
}
const QPixmap &CAImageMbbi::getOnpixmap() const
{
return d_data->pixmap[1];
}
void CAImageMbbi::setOnpixmap(const QPixmap &pxm)
{
d_data->pixmap[1]= pxm;
}
const QPixmap &CAImageMbbi::getTwpixmap() const
{
return d_data->pixmap[2];
}
void CAImageMbbi::setTwpixmap(const QPixmap &pxm)
{
d_data->pixmap[2]= pxm;
}
const QPixmap &CAImageMbbi::getThpixmap() const
{
return d_data->pixmap[3];
}
void CAImageMbbi::setThpixmap(const QPixmap &pxm)
{
d_data->pixmap[3]= pxm;
}
const QPixmap &CAImageMbbi::getFrpixmap() const
{
return d_data->pixmap[4];
}
void CAImageMbbi::setFrpixmap(const QPixmap &pxm)
{
d_data->pixmap[4]= pxm;
}
const QPixmap &CAImageMbbi::getFvpixmap() const
{
return d_data->pixmap[5];
}
void CAImageMbbi::setFvpixmap(const QPixmap &pxm)
{
d_data->pixmap[5]= pxm;
}
const QPixmap &CAImageMbbi::getSxpixmap() const
{
return d_data->pixmap[6];
}
void CAImageMbbi::setSxpixmap(const QPixmap &pxm)
{
d_data->pixmap[6]= pxm;
}
const QPixmap &CAImageMbbi::getSvpixmap() const
{
return d_data->pixmap[7];
}
void CAImageMbbi::setSvpixmap(const QPixmap &pxm)
{
d_data->pixmap[7]= pxm;
}
const QPixmap &CAImageMbbi::getEipixmap() const
{
return d_data->pixmap[8];
}
void CAImageMbbi::setEipixmap(const QPixmap &pxm)
{
d_data->pixmap[8]= pxm;
}
const QPixmap &CAImageMbbi::getNipixmap() const
{
return d_data->pixmap[9];
}
void CAImageMbbi::setNipixmap(const QPixmap &pxm)
{
d_data->pixmap[9]= pxm;
}
const QPixmap &CAImageMbbi::getTepixmap() const
{
return d_data->pixmap[10];
}
void CAImageMbbi::setTepixmap(const QPixmap &pxm)
{
d_data->pixmap[10]= pxm;
}
const QPixmap &CAImageMbbi::getElpixmap() const
{
return d_data->pixmap[11];
}
void CAImageMbbi::setElpixmap(const QPixmap &pxm)
{
d_data->pixmap[11]= pxm;
}
const QPixmap &CAImageMbbi::getTvpixmap() const
{
return d_data->pixmap[12];
}
void CAImageMbbi::setTvpixmap(const QPixmap &pxm)
{
d_data->pixmap[12]= pxm;
}
const QPixmap &CAImageMbbi::getTtpixmap() const
{
return d_data->pixmap[13];
}
void CAImageMbbi::setTtpixmap(const QPixmap &pxm)
{
d_data->pixmap[13]= pxm;
}
const QPixmap &CAImageMbbi::getFtpixmap() const
{
return d_data->pixmap[14];
}
void CAImageMbbi::setFtpixmap(const QPixmap &pxm)
{
d_data->pixmap[14]= pxm;
}
const QPixmap &CAImageMbbi::getFfpixmap() const
{
return d_data->pixmap[15];
}
void CAImageMbbi::setFfpixmap(const QPixmap &pxm)
{
d_data->pixmap[15]= pxm;
}
const QPixmap &CAImageMbbi::getFalsepixmap() const
{
return d_data->falsepixmap;
}
void CAImageMbbi::setFalsepixmap(const QPixmap &pxm)
{
d_data->falsepixmap= pxm;
}
void CAImageMbbi::setTruepxm(const QPixmap &truepxm)
{
d_data->truepixmap = truepxm;
}
void CAImageMbbi::setFalsepxm(const QPixmap &falsepxm)
{
d_data->falsepixmap = falsepxm;
}
const QPixmap &CAImageMbbi::getTruepixmap() const
{
return d_data->truepixmap;
}
void CAImageMbbi::setTruepixmap(const QPixmap &pxm)
{
d_data->truepixmap= pxm;
}
int CAImageMbbi::getIndex() const
{
return d_data->index;
}
void CAImageMbbi::setIndex(int index)
{
d_data->index= index;
}
void CAImageMbbi::initCAImageMbbi()
{
#if QT_VERSION >= 0x040000
using namespace Qt;
#endif
d_data = new PrivateData;
setDisplaymode(Choice);
setPvname("pvname");
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setSpacing(0);
vbox->setMargin(0);
vbox->setObjectName(QString::fromUtf8("vboxLayout"));
d_data->label = new QLabel(this);
d_data->label->setObjectName(QString::fromUtf8("label"));
d_data->label->setAlignment(Qt::AlignLeft);
d_data->label->setText(getPvname());
d_data->label->setScaledContents(true);
d_data->label->setPixmap(QPixmap(":images/white.png"));
vbox->addWidget(d_data->label);
setLayout(vbox);
}
void CAImageMbbi::changeValue (const short &connstatus, const int &value)
{
if (connstatus != ECA_CONN)
{
d_data->label->setPixmap(QPixmap(":images/white.png"));
setStatusTip(QString("PVname : ").append(d_data->pvname).append(QString(", connstatus: ")).append(QString("%1").arg(connstatus)));
return;
}
else
{
switch(getDisplaymode())
{
case Choice:
d_data->label->setPixmap(d_data->pixmap[value]);
break;
case TrueFalse:
if (getIndex()==value)
{
d_data->label->setPixmap(d_data->truepixmap);
}
else
{
d_data->label->setPixmap(d_data->falsepixmap);
}
break;
default:
break;
}
setStatusTip(QString("PVname : ").append(d_data->pvname).append(QString(", Value: ")).append(QString("%1").arg((double)value,1,'g',0)));
}
}
|
55048c0f6a60881720d7fd268970f741747bc63e | f9e11c32d69e766d904fab8c06f501f147814438 | /cpp/old/moldCTests.cpp | 8812b91ea033ca5c7bfba426693857c3faf20de1 | [] | no_license | xenocampanoli/inlay_stalestate | d9ad7811b5a796f7a3e8e0d167ec6a67707115af | 83cba474504a359d9cd6de89c22e284367a77405 | refs/heads/master | 2020-07-02T14:21:22.472030 | 2019-08-09T23:59:43 | 2019-08-09T23:59:43 | 201,555,478 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 88 | cpp | moldCTests.cpp | // unittest_criterion_mold.cpp
class Mold {
};
// End of unittest_criterion_mold.cpp
|
36a5d2941aa88e4e838584c7c0fab2e64bd5b9f8 | 9cc10defe68caccd5ce607a8da08f94fc64f70e5 | /grid 1.cpp | 1d2562c0a31cffd54fc32a8ccee712f09acf2aa6 | [] | no_license | Aks32216/at-coder-dp | ccfeb08536b20bf544a86936e05819b7d2614a86 | e9079b8f29ae29ccf2e2c0fa8c6c9c4f8400064a | refs/heads/main | 2023-05-04T12:56:11.696201 | 2021-05-19T01:49:52 | 2021-05-19T01:49:52 | 368,714,295 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,631 | cpp | grid 1.cpp | #include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cmath>
#include <map>
#include <string.h>
#include <algorithm>
#include <bits/stdc++.h>
#include <vector>
using namespace std;
#define set_precision cout << fixed << setprecision(10)
#define rep(i, a, b) for (int i = a; i < b; i++)
#define repb(i, a, b) for (int i = a; i >= b; i--)
#define replb(i, a, b) for (ll i = a; i >= b; i--)
#define repl(i, a, b) for (ll i = a; i < b; i++)
#define repit(arr) for (auto it = arr.begin(); it != arr.end();
#define vi vector<int>
#define vb vector<bool>
#define vs vector<string>
#define vl vector<long long int>
#define Vi vector<vector<int>>
#define vpi vector<pair<int,int> >
#define seti set<int>
#define setl set<ll>
#define dseti set<int, greater<int>>
#define dsetl set<ll, greater<ll>>
#define mseti multiset<int>
#define msetl multiset<ll>
#define dmseti multiset<int, greater<int>>
#define dmsetl multiset<ll, greater<ll>>
#define sortA(arr) sort(arr.begin(), arr.end())
#define dsortA(arr) sort(arr.begin(), arr.end(), greater<int>())
#define ssort(arr) stable_sort(arr.begin(), arr.end())
#define search(arr, c) binary_search(arr.begin(), arr.end(), c)
#define pb push_back
#define ll long long
#define cl_bf cin.ignore(numeric_limits<streamsize>::max(), '\n');
#define castl static_cast<ll>
#define BRAHAMASTRA ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ull unsigned long long int
ll dp[1005][1005];
int n,m;
ll noofways()
{
for(int i=1;i<=n;)
{
if(dp[i][1]==0)
dp[i][1]=1,i++;
else
{
while(i<=n)
dp[i][1]=-1,i++;
}
}
dp[1][1]=0;
for(int i=1;i<=m;)
{
if(dp[1][i]==0)
dp[1][i]=1,i++;
else
{
while(i<=m)
dp[1][i]=-1,i++;
}
}
for(int i=2;i<=n;++i)
{
for(int j=2;j<=m;++j)
{
if(dp[i][j]==-1)
continue;
else if(dp[i-1][j]==-1 && dp[i][j-1]==-1)
dp[i][j]=-1;
else if(dp[i-1][j]==-1 && dp[i][j-1]!=-1)
dp[i][j]=dp[i][j-1];
else if(dp[i-1][j]!=-1 && dp[i][j-1]==-1)
dp[i][j]=dp[i-1][j];
else
dp[i][j]=(dp[i-1][j] + dp[i][j-1]) % 1000000007;
}
}
if(dp[n][m]==-1)
return 0;
else
return dp[n][m] % 1000000007;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("../../input.txt","r",stdin);
freopen("../../output.txt","w",stdout);
#endif
BRAHAMASTRA
cin>>n>>m;
char c;
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;++i)
{
for(int j=1;j<=m;++j)
{
cin>>c;
if(c=='.')
continue;
else
dp[i][j]=-1;
}
}
cout<<noofways()<<"\n";
}
|
2a70b306234cd09bf8934af8532bbbaaf73db489 | a6472f526703df47e0b22a4d6cc481c464088d61 | /c/src/semirings/semilinSetNdd.cpp | 6f8508d2cd1c4de2a8706059b2879958abe1b9a7 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | kobreu/FPsolve | 53e60abe9af6014d3999b200f84e1307fc8dbb58 | b253af449f0bc6f06daa0a0030784c6f1f4e9ad9 | refs/heads/master | 2021-01-18T07:36:16.101293 | 2014-06-08T11:20:15 | 2014-06-08T11:20:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,381 | cpp | semilinSetNdd.cpp | #include <iostream>
#include "semilinSetNdd.h"
int static_i = 0;
// insert an offset if it is unique in offsets
std::vector<std::vector<int>>& insert_offset(std::vector<std::vector<int>>& offsets, const std::vector<int>& offset) {
if(std::find(offsets.begin(), offsets.end(), offset) == offsets.end())
{
offsets.push_back(offset);
}
return offsets;
}
std::vector<std::vector<int>> multiply_offsets(const std::vector<std::vector<int>>& offsets1, const std::vector<std::vector<int>>& offsets2) {
std::vector<std::vector<int>> offsets;
for(auto o1 : offsets1) {
for(auto o2 : offsets2) {
assert(o1.size() == o2.size());
std::vector<int> o(o1.size());
for(int i=0; i<o1.size(); ++i) {
o.at(i) = o1.at(i) + o2.at(i);
}
offsets = insert_offset(offsets, o);
}
}
return offsets;
}
std::string serialize_offsets(const std::vector<std::vector<int>>& offsets) {
std::stringstream result;
result << "[";
for(const auto& offset : offsets) {
if(&offset != &offsets.at(0))
result << ",";
result << "(";
for(const auto& o : offset) {
if(&o != &offset.at(0))
result << ",";
result << o;
}
result << ")";
}
result << "]";
return result.str();
}
std::vector<int> add_vectors(const std::vector<int>& vec1, const std::vector<int>& vec2) {
assert(vec1.size() == vec2.size());
std::vector<int> result(vec1.size());
for(int i = 0; i < vec1.size(); ++i)
result.at(i) = vec1.at(i) + vec2.at(i);
return result;
}
std::vector<int> subtract_vectors(const std::vector<int>& vec1, const std::vector<int>& vec2) {
assert(vec1.size() == vec2.size());
std::vector<int> result(vec1.size());
for(int i = 0; i < vec1.size(); ++i)
result.at(i) = vec1.at(i) - vec2.at(i);
return result;
}
// check if the given candidate is truly a generator starting at the given offset
// n is number of offsets
bool SemilinSetNdd::isGenerator(const std::vector<int>& offset, const std::vector<int>& candidate, int n) const {
// try to sample enough points in the solution space
// from the given offset to be sure this is a generator.
// First guess is, n is enough for n > offsets.size()
auto solution = offset; // start at offset
for(int i = 0; i<=n; ++i) {
// solution += candidate;
for(int j = 0; j < candidate.size(); ++j)
solution.at(j)+=candidate.at(j);
if(!this->set.isSolution(solution))
return false; // this is not a generator for this offset
}
return true; // we tried n+1 sample points, this should be a generator, TODO: prove this!
}
// test if offset 2 = offset1 + N×candidate
bool SemilinSetNdd::isGeneratorFor(const std::vector<int>& offset1, const std::vector<int>& candidate, const std::vector<int>& offset2) const {
auto new_candidate = candidate;
std::vector<int> test(candidate.size());
int N = -1; // N should not be negative
for(int i = 0; i < candidate.size(); ++i) {
int tmp = offset2.at(i)-offset1.at(i);
if(tmp == 0 && tmp == candidate.at(i))
continue;
int tmp2;
if(candidate.at(i) != 0)
tmp2 = tmp / candidate.at(i);
else {
std::cout << " not a valid generator for this offset at " << i << " c:" << candidate.at(i) << " tmp: " << tmp << " ";
return false; // if candidate != tmp then this is not a valid generator for this offset
}
if(N == -1)
N = tmp2;
if(N != tmp2) {
std::cout << " not linear dependend ";
return false; // vectors are not linear dependent
}
}
// we managed to get here without returning false,
// there is an N for offset 2 = offset1 + N×candidate
return true;
}
// PSEUDOCODE
// for all offset1 in offsets:
// for all offset2 in offsets:
// let candidate_generator = offset2-offset1
// if candidate_generator is positive:
// if candidate_generator is generator at offset1:
// if offset1 is already generated by original_offset:
// let new_candidate_generator = offset2-original_offset
// if new_candidate_generator is positive:
// if new_candidate_generator is generator at original_offset:
// → offset2 is created by original_offset
// else:
// → offset1 seems to be necessary offset (TODO)
// else:
// → no useful generator
// →
// else:
// → offset2 is created by offset1
// else:
// → offset2 is not created by candidate_generator at offset1
// → continue
// else:
// → no useful generator
// → continue
// end for
// end for
//
// accumulate all offsets which can be used to create other offsets
// accumulate all offsets which cannot be created by other offsets+generators
bool isPositiveNotNull(const std::vector<int>& offset) {
int sum = 0;
for(auto o : offset) {
if(o < 0)
return false;
sum += o;
}
return sum > 0;
}
// return all unique offsets which are necessary
std::vector<std::vector<int>> SemilinSetNdd::getUniqueOffsets(const std::vector<std::vector<int>>& offsets) const {
// we set the respective element to true if we can generate this offset with another one.
std::vector<bool> generated(offsets.size(), false);
std::map<int,int> generated_by;
// TODO: optimize the number of candidates
for(unsigned int i = 0; i < offsets.size(); ++i) {
const auto& offset1 = offsets.at(i);
for(unsigned int j = 0; j < offsets.size(); ++j) {
const auto& offset2 = offsets.at(j);
auto candidate_generator = subtract_vectors(offset2,offset1);
if(isPositiveNotNull(candidate_generator)) {
if(isGenerator(offset1, candidate_generator, offsets.size())) {
// offset2 was indeed created by offset1+candidate
// TODO: be careful! there might be another offset which created offset1...
// but maybe this may not be the case because of the order in which we
// traverse the offsets (sorted lexicographically)
// INFO: we know the is a generator, which can create offset2 = offset1+candidate
// std::cout << "offset: ";
// for(const auto& o : offset1)
// std::cout << o;
// std::cout << " + N×";
// for(const auto& c : candidate_generator)
// std::cout << c;
// std::cout << " = ";
// for(const auto& o : offset2)
// std::cout << o;
if(generated.at(i)) { // offset1 was already generated by some other offset+generator
// std::cout << " offset 1 already generated. check if neccesary: → ";
const auto& original_offset = offsets.at(generated_by.at(i));
auto new_candidate_generator = subtract_vectors(offset2,original_offset);
if(isPositiveNotNull(new_candidate_generator)) {
if(isGenerator(original_offset, new_candidate_generator, offsets.size())) {
// std::cout << "offset2 is created by original_offset: → ";
generated_by[j] = generated_by.at(i);
generated.at(j) = true;
// TODO: still something left todo?
// for(auto o : original_offset)
// std::cout << o;
} else {
// std::cout << "offset1 seems to be necessary offset → ";
// TODO: what to do? → nothing as we do not know more than before - do not set generated_by
generated_by[j] = i;
generated.at(j) = true;
}
} else {
// std::cout << "new generator candidate is no generator at original_offset → ";
// offset2 is created by generator_candidate from offset1 but not from original_offset
generated_by[j] = i;
generated.at(j) = true;
}
} else {
// std::cout << "offset2 is generated by candidate generator at offset1 → ";
// TODO: we might need it
generated_by[j] = i;
generated.at(j) = true;
}
} else {
// std::cout << "nope candidate generator is not a generator for offset2 at offset1 → ";
// TODO: what to do?
}
} else {
// std::cout << "generator candidate is no generator at offset1";
}
// std::cout << std::endl << "--------------------------------" << std::endl;
}
}
std::set<std::vector<int>> result;
// accumulate all offsets which can be used to create other offsets
for(const auto& i : generated_by) {
const auto& offset = offsets.at(i.second);
result.insert(offset);
}
// accumulate all offsets which cannot be created by other offsets+generators
for(int i = 0; i < generated.size(); ++i) {
if(!generated.at(i)) // this offset is not to be found in other linear sets
result.insert(offsets.at(i));
}
std::vector<std::vector<int>> returned_result;
returned_result.insert(returned_result.end(), result.begin(), result.end());
return returned_result;
}
bool SemilinSetNdd::genepi_init(std::string pluginname, int number_of_variables)
{
genepi_loader_init();
genepi_loader_load_default_plugins();
plugin = genepi_loader_get_plugin(pluginname.c_str());
std::cout << "Plugin: " << genepi_plugin_get_name(plugin) << std::endl;
// TODO: use of cache???
solver = genepi_solver_create(plugin, 0, 0, 0);
k = number_of_variables;
return true; // TODO: return correct value!
}
bool SemilinSetNdd::genepi_dealloc() {
genepi_solver_delete(solver);
genepi_plugin_del_reference(plugin);
genepi_loader_terminate();
return true;
}
SemilinSetNdd::SemilinSetNdd() : set(Genepi(solver, k, false)) {
}
SemilinSetNdd::SemilinSetNdd(int zero) : set(Genepi(solver, k, false)) {
assert(zero == 0);
}
SemilinSetNdd::SemilinSetNdd(VarId var) : SemilinSetNdd(var, 1) {
}
SemilinSetNdd::SemilinSetNdd(VarId var, int cnt) {
auto v = var_map.find(var);
if(v == var_map.end())
{
var_map.insert(std::make_pair(var, var_map.size()));
v = var_map.find(var);
}
int position = v->second; // which position is this variable on?
std::vector<int> alpha(k);
alpha.at(position) = cnt;
this->set = Genepi(solver, alpha, false);
this->offsets.push_back(alpha);
}
SemilinSetNdd::SemilinSetNdd(Genepi set, std::vector<std::vector<int>> offsets) : set(set), offsets(offsets) {
}
SemilinSetNdd::SemilinSetNdd(const SemilinSetNdd& expr) : set(expr.set), offsets(expr.offsets) {
}
SemilinSetNdd::~SemilinSetNdd() {
}
SemilinSetNdd SemilinSetNdd::operator=(const SemilinSetNdd& term) {
this->set = term.set;
this->offsets = term.offsets;
return *this;
}
SemilinSetNdd SemilinSetNdd::operator+=(const SemilinSetNdd& term) {
this->set = this->set.union_op(term.set);
for(auto offset : term.offsets)
insert_offset(this->offsets, offset);
return *this;
}
SemilinSetNdd SemilinSetNdd::operator*=(const SemilinSetNdd& term) {
std::vector<int> sel_a(3*k, 1);
std::vector<int> sel_b(3*k, 1);
for(int i = 0; i < k; i++)
{
sel_a[3*i] = 0;
sel_b[3*i+1] = 0;
}
// inverse projection from original dimensions to an extended version, which is intersected with the natural numbers
Genepi a_ext(this->set.invproject(sel_a).intersect(Genepi(solver, 3*k, true)));
Genepi b_ext(term.set.invproject(sel_b).intersect(Genepi(solver, 3*k, true)));
std::vector<int> generic_alpha = {1, 1, -1}; // 1*a[i]+1*b[i]-1*c[i]=0
Genepi generic_sum(solver, generic_alpha, 0);
std::vector<int> component_selection(3*k, 1); // TODO: maybe we only use k+2 or so elements
std::vector<int> component_projection(3*k, 0); // we want to project away component 3i and 3i+1
// initialize the result automaton with (a_i,b_i,N) for i in 0..k-1
Genepi result(solver, 3*k, true); // natural numbers
result = result.intersect(a_ext).intersect(b_ext);
// one run for each variable
// at the end of each loop run we delete the used a and b component
// the new sum component will be at position i at the end of the loop run
// (a,b,a+b) component relevant for current run is at position (i,i+1,i+2) at the begin of a run
for(int i = 0; i < k; i++)
{
component_selection.resize(3*k-2*i);
component_projection.resize(3*k-2*i);
// TODO: figure out, if precalculating this and apply inv_project has better complexity
// than always create a new sum automaton for different components
component_selection[i] = 0;
component_selection[i+1] = 0;
component_selection[i+2] = 0;
// inverse projection on generic sum automaton to create automaton for component i
Genepi component_sum(generic_sum.invproject(component_selection));
// use this sum automaton on the intermediate result
result = result.intersect(component_sum);
component_selection[i] = 1; // reset component_selection
component_selection[i+1] = 1;
component_selection[i+2] = 1;
component_projection[i] = 1; // project away the already used a and b component at position (i,i+1)
component_projection[i+1] = 1;
result = result.project(component_projection);
component_projection[i] = 0;
component_projection[i+1] = 0;
}
this->set = result;
this->offsets = this->getUniqueOffsets(multiply_offsets(this->offsets, term.offsets));
return *this;
}
bool SemilinSetNdd::operator < (const SemilinSetNdd& term) const {
return this->set < term.set;
}
bool SemilinSetNdd::operator == (const SemilinSetNdd& term) const {
return this->set == term.set;
}
SemilinSetNdd SemilinSetNdd::star () const {
SemilinSetNdd offset_star = one();
for(auto offset : this->offsets) {
offset_star *= SemilinSetNdd(Genepi(this->solver, offset, true),{std::vector<int>(k,0)});
}
SemilinSetNdd result = one(); // result = 1
SemilinSetNdd temp = one();
for(int i = 1; i <= k; i++) { // 1..k
temp *= *this; // temp = S^i
result += temp;
}
result = one() + (result * offset_star); // S^i * offset_star
return result;
}
SemilinSetNdd SemilinSetNdd::null() {
if(!SemilinSetNdd::elem_null)
SemilinSetNdd::elem_null = std::shared_ptr<SemilinSetNdd>(new SemilinSetNdd());
return *SemilinSetNdd::elem_null;
}
SemilinSetNdd SemilinSetNdd::one() {
if(!SemilinSetNdd::elem_one)
SemilinSetNdd::elem_one = std::shared_ptr<SemilinSetNdd>(new SemilinSetNdd(Genepi(solver, std::vector<int>(k,0), false), {std::vector<int>(k,0)}));
return *SemilinSetNdd::elem_one;
}
std::string SemilinSetNdd::string() const {
std::stringstream result;
auto calculated_offsets = this->offsets;
result << "calculated offsets:\t\t" << serialize_offsets(calculated_offsets) << std::endl;
auto cleaned_calculated_offsets = this->getUniqueOffsets(calculated_offsets);
result << "calculated offsets (clean):\t" << serialize_offsets(cleaned_calculated_offsets) << std::endl;
result << "automaton written:\t" << this->set.output("result", static_i++, "") << std::endl;
return result.str();
}
const bool SemilinSetNdd::is_idempotent = true;
const bool SemilinSetNdd::is_commutative = true;
std::shared_ptr<SemilinSetNdd> SemilinSetNdd::elem_null;
std::shared_ptr<SemilinSetNdd> SemilinSetNdd::elem_one;
genepi_solver* SemilinSetNdd::solver;
genepi_plugin* SemilinSetNdd::plugin;
std::unordered_map<VarId, int> SemilinSetNdd::var_map;
int SemilinSetNdd::k = 0;
|
4e2005f8cc1a00cf98bd3dc5ebf8a3a4ea4545b8 | e5f4f37d941ceb8145d65f92028cc54658b1ac01 | /Code/Engine/GameEngine/Gameplay/Implementation/BlackboardComponent.cpp | 289577052a3b33925ec10e3596edf39a2bcac573 | [
"MIT"
] | permissive | ezEngine/ezEngine | 19983d2733a5409fb2665c6c3a0a575dadcefb50 | c46e3b4b2cd46798e4abb4938fbca281c054b039 | refs/heads/dev | 2023-09-06T02:17:28.152665 | 2023-09-05T18:25:43 | 2023-09-05T18:25:43 | 18,179,848 | 1,050 | 165 | MIT | 2023-09-14T21:44:39 | 2014-03-27T15:02:16 | C++ | UTF-8 | C++ | false | false | 12,015 | cpp | BlackboardComponent.cpp | #include <GameEngine/GameEnginePCH.h>
#include <Core/Messages/UpdateLocalBoundsMessage.h>
#include <Core/WorldSerializer/WorldReader.h>
#include <Core/WorldSerializer/WorldWriter.h>
#include <GameEngine/Gameplay/BlackboardComponent.h>
#include <GameEngine/Utils/BlackboardTemplateResource.h>
#include <RendererCore/Debug/DebugRenderer.h>
#include <RendererCore/Pipeline/RenderData.h>
#include <RendererCore/Pipeline/View.h>
// clang-format off
EZ_BEGIN_STATIC_REFLECTED_TYPE(ezBlackboardEntry, ezNoBase, 1, ezRTTIDefaultAllocator<ezBlackboardEntry>)
{
EZ_BEGIN_PROPERTIES
{
EZ_ACCESSOR_PROPERTY("Name", GetName, SetName),
EZ_MEMBER_PROPERTY("InitialValue", m_InitialValue)->AddAttributes(new ezDefaultValueAttribute(0)),
EZ_BITFLAGS_MEMBER_PROPERTY("Flags", ezBlackboardEntryFlags, m_Flags)
}
EZ_END_PROPERTIES;
}
EZ_END_STATIC_REFLECTED_TYPE;
// clang-format on
ezResult ezBlackboardEntry::Serialize(ezStreamWriter& inout_stream) const
{
inout_stream << m_sName;
inout_stream << m_InitialValue;
inout_stream << m_Flags;
return EZ_SUCCESS;
}
ezResult ezBlackboardEntry::Deserialize(ezStreamReader& inout_stream)
{
inout_stream >> m_sName;
inout_stream >> m_InitialValue;
inout_stream >> m_Flags;
return EZ_SUCCESS;
}
//////////////////////////////////////////////////////////////////////////
// clang-format off
EZ_IMPLEMENT_MESSAGE_TYPE(ezMsgBlackboardEntryChanged);
EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezMsgBlackboardEntryChanged, 1, ezRTTIDefaultAllocator<ezMsgBlackboardEntryChanged>)
{
EZ_BEGIN_PROPERTIES
{
EZ_ACCESSOR_PROPERTY("Name", GetName, SetName),
EZ_MEMBER_PROPERTY("OldValue", m_OldValue),
EZ_MEMBER_PROPERTY("NewValue", m_NewValue),
}
EZ_END_PROPERTIES;
EZ_BEGIN_ATTRIBUTES
{
new ezAutoGenVisScriptMsgHandler()
}
EZ_END_ATTRIBUTES;
}
EZ_END_DYNAMIC_REFLECTED_TYPE;
// clang-format on
//////////////////////////////////////////////////////////////////////////
// clang-format off
EZ_BEGIN_COMPONENT_TYPE(ezBlackboardComponent, 2, ezComponentMode::Static)
{
EZ_BEGIN_PROPERTIES
{
EZ_ACCESSOR_PROPERTY("BlackboardName", GetBlackboardName, SetBlackboardName),
EZ_ACCESSOR_PROPERTY("Template", GetTemplateFile, SetTemplateFile)->AddAttributes(new ezAssetBrowserAttribute("CompatibleAsset_BlackboardTemplate")),
EZ_ACCESSOR_PROPERTY("ShowDebugInfo", GetShowDebugInfo, SetShowDebugInfo),
EZ_ACCESSOR_PROPERTY("SendEntryChangedMessage", GetSendEntryChangedMessage, SetSendEntryChangedMessage),
EZ_ARRAY_ACCESSOR_PROPERTY("Entries", Entries_GetCount, Entries_GetValue, Entries_SetValue, Entries_Insert, Entries_Remove),
}
EZ_END_PROPERTIES;
EZ_BEGIN_MESSAGEHANDLERS
{
EZ_MESSAGE_HANDLER(ezMsgUpdateLocalBounds, OnUpdateLocalBounds),
EZ_MESSAGE_HANDLER(ezMsgExtractRenderData, OnExtractRenderData),
}
EZ_END_MESSAGEHANDLERS;
EZ_BEGIN_MESSAGESENDERS
{
EZ_MESSAGE_SENDER(m_EntryChangedSender)
}
EZ_END_MESSAGESENDERS;
EZ_BEGIN_FUNCTIONS
{
EZ_SCRIPT_FUNCTION_PROPERTY(SetEntryValue, In, "Name", In, "Value"),
EZ_SCRIPT_FUNCTION_PROPERTY(GetEntryValue, In, "Name"),
EZ_SCRIPT_FUNCTION_PROPERTY(Reflection_FindBlackboard, In, "SearchObject", In, "BlackboardName"),
}
EZ_END_FUNCTIONS;
EZ_BEGIN_ATTRIBUTES
{
new ezCategoryAttribute("Logic"),
}
EZ_END_ATTRIBUTES;
}
EZ_END_DYNAMIC_REFLECTED_TYPE
// clang-format on
ezBlackboardComponent::ezBlackboardComponent()
: m_pBoard(ezBlackboard::Create())
{
}
ezBlackboardComponent::ezBlackboardComponent(ezBlackboardComponent&& other) = default;
ezBlackboardComponent::~ezBlackboardComponent() = default;
ezBlackboardComponent& ezBlackboardComponent::operator=(ezBlackboardComponent&& other) = default;
// static
ezSharedPtr<ezBlackboard> ezBlackboardComponent::FindBlackboard(ezGameObject* pObject, ezStringView sBlackboardName /*= ezStringView()*/)
{
ezTempHashedString sBlackboardNameHashed(sBlackboardName);
ezBlackboardComponent* pBlackboardComponent = nullptr;
while (pObject != nullptr)
{
if (pObject->TryGetComponentOfBaseType(pBlackboardComponent))
{
if (sBlackboardName.IsEmpty() || pBlackboardComponent->GetBoard()->GetNameHashed() == sBlackboardNameHashed)
{
return pBlackboardComponent->GetBoard();
}
}
pObject = pObject->GetParent();
}
if (sBlackboardName.IsEmpty() == false)
{
ezHashedString sHashedBlackboardName;
sHashedBlackboardName.Assign(sBlackboardName);
return ezBlackboard::GetOrCreateGlobal(sHashedBlackboardName);
}
return nullptr;
}
void ezBlackboardComponent::OnActivated()
{
SUPER::OnActivated();
if (GetShowDebugInfo())
{
GetOwner()->UpdateLocalBounds();
}
// we already do this here, so that the BB is initialized even if OnSimulationStarted() hasn't been called yet
InitializeFromTemplate();
}
void ezBlackboardComponent::OnDeactivated()
{
if (GetShowDebugInfo())
{
GetOwner()->UpdateLocalBounds();
}
SUPER::OnDeactivated();
}
void ezBlackboardComponent::OnSimulationStarted()
{
SUPER::OnSimulationStarted();
// we repeat this here, mainly for the editor case, when the asset has been modified (new entries added)
// and we then press play, to have the new entries in the BB
// this would NOT update the initial values, though, if they changed
InitializeFromTemplate();
}
void ezBlackboardComponent::SerializeComponent(ezWorldWriter& inout_stream) const
{
SUPER::SerializeComponent(inout_stream);
ezStreamWriter& s = inout_stream.GetStream();
s << m_pBoard->GetName();
s.WriteArray(m_InitialEntries).IgnoreResult();
s << m_hTemplate;
}
void ezBlackboardComponent::DeserializeComponent(ezWorldReader& inout_stream)
{
SUPER::DeserializeComponent(inout_stream);
const ezUInt32 uiVersion = inout_stream.GetComponentTypeVersion(GetStaticRTTI());
ezStreamReader& s = inout_stream.GetStream();
ezStringBuilder sb;
s >> sb;
m_pBoard->SetName(sb);
// we don't write the data to m_InitialEntries, because that is never needed anymore at runtime
ezDynamicArray<ezBlackboardEntry> initialEntries;
if (s.ReadArray(initialEntries).Succeeded())
{
for (auto& entry : initialEntries)
{
m_pBoard->RegisterEntry(entry.m_sName, entry.m_InitialValue, entry.m_Flags);
}
}
if (uiVersion >= 2)
{
s >> m_hTemplate;
}
}
const ezSharedPtr<ezBlackboard>& ezBlackboardComponent::GetBoard()
{
return m_pBoard;
}
ezSharedPtr<const ezBlackboard> ezBlackboardComponent::GetBoard() const
{
return m_pBoard;
}
struct BCFlags
{
enum Enum
{
ShowDebugInfo = 0,
SendEntryChangedMessage
};
};
void ezBlackboardComponent::SetShowDebugInfo(bool bShow)
{
SetUserFlag(BCFlags::ShowDebugInfo, bShow);
if (IsActiveAndInitialized())
{
GetOwner()->UpdateLocalBounds();
}
}
bool ezBlackboardComponent::GetShowDebugInfo() const
{
return GetUserFlag(BCFlags::ShowDebugInfo);
}
void ezBlackboardComponent::SetSendEntryChangedMessage(bool bSend)
{
if (GetSendEntryChangedMessage() == bSend)
return;
SetUserFlag(BCFlags::SendEntryChangedMessage, bSend);
if (bSend)
{
m_pBoard->OnEntryEvent().AddEventHandler(ezMakeDelegate(&ezBlackboardComponent::OnEntryChanged, this));
}
else
{
m_pBoard->OnEntryEvent().RemoveEventHandler(ezMakeDelegate(&ezBlackboardComponent::OnEntryChanged, this));
}
}
bool ezBlackboardComponent::GetSendEntryChangedMessage() const
{
return GetUserFlag(BCFlags::SendEntryChangedMessage);
}
void ezBlackboardComponent::SetBlackboardName(const char* szName)
{
m_pBoard->SetName(szName);
}
const char* ezBlackboardComponent::GetBlackboardName() const
{
return m_pBoard->GetName();
}
void ezBlackboardComponent::SetEntryValue(const char* szName, const ezVariant& value)
{
if (m_pBoard->SetEntryValue(ezTempHashedString(szName), value).Failed())
{
ezLog::Error("Can't set blackboard entry '{}', because it doesn't exist.", szName);
}
}
ezVariant ezBlackboardComponent::GetEntryValue(const char* szName) const
{
return m_pBoard->GetEntryValue(ezTempHashedString(szName));
}
void ezBlackboardComponent::SetTemplateFile(const char* szName)
{
ezBlackboardTemplateResourceHandle hResource;
if (!ezStringUtils::IsNullOrEmpty(szName))
{
hResource = ezResourceManager::LoadResource<ezBlackboardTemplateResource>(szName);
}
m_hTemplate = hResource;
}
const char* ezBlackboardComponent::GetTemplateFile() const
{
if (m_hTemplate.IsValid())
{
return m_hTemplate.GetResourceID();
}
return "";
}
ezUInt32 ezBlackboardComponent::Entries_GetCount() const
{
return m_InitialEntries.GetCount();
}
const ezBlackboardEntry& ezBlackboardComponent::Entries_GetValue(ezUInt32 uiIndex) const
{
return m_InitialEntries[uiIndex];
}
void ezBlackboardComponent::Entries_SetValue(ezUInt32 uiIndex, const ezBlackboardEntry& entry)
{
m_InitialEntries.EnsureCount(uiIndex + 1);
if (const ezBlackboard::Entry* pEntry = m_pBoard->GetEntry(m_InitialEntries[uiIndex].m_sName))
{
if (m_InitialEntries[uiIndex].m_sName != entry.m_sName || pEntry->m_Flags != entry.m_Flags)
{
m_pBoard->UnregisterEntry(m_InitialEntries[uiIndex].m_sName);
m_pBoard->RegisterEntry(entry.m_sName, entry.m_InitialValue, entry.m_Flags);
}
}
else
{
m_pBoard->RegisterEntry(entry.m_sName, entry.m_InitialValue, entry.m_Flags);
}
m_pBoard->SetEntryValue(entry.m_sName, entry.m_InitialValue).AssertSuccess();
m_InitialEntries[uiIndex] = entry;
}
void ezBlackboardComponent::Entries_Insert(ezUInt32 uiIndex, const ezBlackboardEntry& entry)
{
m_InitialEntries.Insert(entry, uiIndex);
m_pBoard->RegisterEntry(entry.m_sName, entry.m_InitialValue, entry.m_Flags);
}
void ezBlackboardComponent::Entries_Remove(ezUInt32 uiIndex)
{
auto& entry = m_InitialEntries[uiIndex];
m_pBoard->UnregisterEntry(entry.m_sName);
m_InitialEntries.RemoveAtAndCopy(uiIndex);
}
// static
ezBlackboard* ezBlackboardComponent::Reflection_FindBlackboard(ezGameObject* pSearchObject, ezStringView sBlackboardName)
{
return FindBlackboard(pSearchObject, sBlackboardName).Borrow();
}
void ezBlackboardComponent::OnUpdateLocalBounds(ezMsgUpdateLocalBounds& msg) const
{
if (GetShowDebugInfo())
{
msg.AddBounds(ezBoundingSphere::MakeFromCenterAndRadius(ezVec3::MakeZero(), 2.0f), ezDefaultSpatialDataCategories::RenderDynamic);
}
}
void ezBlackboardComponent::OnExtractRenderData(ezMsgExtractRenderData& msg) const
{
if (!GetShowDebugInfo())
return;
if (msg.m_pView->GetCameraUsageHint() != ezCameraUsageHint::MainView &&
msg.m_pView->GetCameraUsageHint() != ezCameraUsageHint::EditorView)
return;
// Don't extract render data for selection.
if (msg.m_OverrideCategory != ezInvalidRenderDataCategory)
return;
auto& entries = m_pBoard->GetAllEntries();
if (entries.IsEmpty())
return;
ezStringBuilder sb;
sb.Append(m_pBoard->GetName(), "\n");
for (auto it = entries.GetIterator(); it.IsValid(); ++it)
{
sb.AppendFormat("{}: {}\n", it.Key(), it.Value().m_Value);
}
ezDebugRenderer::Draw3DText(msg.m_pView->GetHandle(), sb, GetOwner()->GetGlobalPosition(), ezColor::Orange);
}
void ezBlackboardComponent::OnEntryChanged(const ezBlackboard::EntryEvent& e)
{
if (!IsActiveAndInitialized())
return;
ezMsgBlackboardEntryChanged msg;
msg.m_sName = e.m_sName;
msg.m_OldValue = e.m_OldValue;
msg.m_NewValue = e.m_pEntry->m_Value;
m_EntryChangedSender.SendEventMessage(msg, this, GetOwner());
}
void ezBlackboardComponent::InitializeFromTemplate()
{
if (!m_hTemplate.IsValid())
return;
ezResourceLock<ezBlackboardTemplateResource> pTemplate(m_hTemplate, ezResourceAcquireMode::BlockTillLoaded_NeverFail);
if (pTemplate.GetAcquireResult() != ezResourceAcquireResult::Final)
return;
for (const auto& entry : pTemplate->GetDescriptor().m_Entries)
{
m_pBoard->RegisterEntry(entry.m_sName, entry.m_InitialValue, entry.m_Flags);
}
}
EZ_STATICLINK_FILE(GameEngine, GameEngine_Gameplay_Implementation_BlackboardComponent);
|
954f9e2ae37246c6657d7c3fd97a65e8d822d88d | e2fb3ae6e746d42e131ef6cf6adf0556e9245717 | /td/utils/GzipByteFlow.h | 1383b37fabf6c7ee3b2da8b9ef7f9096cc73126e | [] | no_license | arseny30/tdutils | a44405dbf04a4f09b5743800d0e16d986879f343 | 58f7b9b731e1cd0555ab0e2e9a70a819af083bac | refs/heads/master | 2021-06-04T05:03:50.632685 | 2020-08-20T19:28:00 | 2020-08-20T20:20:31 | 108,117,178 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 720 | h | GzipByteFlow.h | #pragma once
#include "td/utils/ByteFlow.h"
#include "td/utils/Gzip.h"
#include <limits>
namespace td {
#if TD_HAVE_ZLIB
class GzipByteFlow final : public ByteFlowBase {
public:
GzipByteFlow() = default;
explicit GzipByteFlow(Gzip::Mode mode) {
gzip_.init(mode).ensure();
}
void init_decode() {
gzip_.init_decode().ensure();
}
void init_encode() {
gzip_.init_encode().ensure();
}
void set_max_output_size(size_t max_output_size) {
max_output_size_ = max_output_size;
}
bool loop() override;
private:
Gzip gzip_;
size_t uncommited_size_ = 0;
size_t total_output_size_ = 0;
size_t max_output_size_ = std::numeric_limits<size_t>::max();
};
#endif
} // namespace td
|
23abe3b3240944a681f8fcaa9c6c212bf4ca9327 | bee24d551370def9055ef1ecde3feed4f8e2fdae | /34-丑数.cc | 743fa02d51fbfea2fb8a97693b29c7831adf1b5d | [] | no_license | HarukazeW/coding_interview | d00980c7641cca135af1ed8ad8c87e28d8cc6cdb | 9aaf641efc8225927bfa3a86734c4bb76aea7ced | refs/heads/master | 2022-01-31T10:30:21.960541 | 2019-08-03T02:43:25 | 2019-08-03T02:43:25 | 93,623,564 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,666 | cc | 34-丑数.cc | class Solution {
public:
//repeat num 要考虑,会有2×3=6,3×2=6这样的情况发生
int GetUglyNumber_Solution(int index) {
if(index<=0)
return 0;
vector<int> cur_ugly(index);
cur_ugly[0]=1;
int index_multi2=0;
int index_multi3=0;
int index_multi5=0;
int i=1;
while(i<index){
/*别人这样的代码更好,又精简,又直观
res[i] = min(res[t2] * 2, min(res[t3] * 3, res[t5] * 5));
if (res[i] == res[t2] * 2)t2++;
if (res[i] == res[t3] * 3)t3++;
if (res[i] == res[t5] * 5)t5++;
*/
int num2=cur_ugly[index_multi2]*2;
int num3=cur_ugly[index_multi3]*3;
int num5=cur_ugly[index_multi5]*5;
/*不能这样检验,因为很可能会有++index_multi2数组下标越界的情况发生
if(num2==num3 || num2==num5){
num2=cur_ugly[++index_multi2];
}
if(num3==num5){
num3=cur_ugly[++index_multi3];
}*/
if(num2<=num3 && num2<=num5){
if(cur_ugly[i-1]!=num2) //据此筛选掉重复值
cur_ugly[i++]=num2;
index_multi2++;
}
else if(num3<=num2 && num3<=num5){
if(cur_ugly[i-1]!=num3)
cur_ugly[i++]=num3;
index_multi3++;
}
else {
if(cur_ugly[i-1]!=num5)
cur_ugly[i++]=num5;
index_multi5++;
}
}
return cur_ugly[--i];
}
};
|
a296c2d196fff3df8eb8c61194211c78ce2a7b48 | 87085b9ea3a10d92988744bd57b8f6b0621d7dbe | /dependencies/mix.h | 569353c1c8a82e1fbbbfab7f160229f486d79c22 | [] | no_license | fordream/oiramExporter | 85146e68a3c618a560ce563576fb3643712cce27 | 59d0ba49ee4a4f43826a9dbeebde1eea50caeed5 | refs/heads/master | 2021-01-24T19:51:34.925165 | 2015-10-31T13:34:18 | 2015-10-31T13:34:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,039 | h | mix.h | #ifndef __MIXRENDER__H
#define __MIXRENDER__H
#include "IHardwareMaterial.h"
#include "3dsmaxport.h"
static Class_ID mixClassID(MIX_CLASS_ID,0);
#define NMIXSUBTEX 3 // number of texture map slots
#define NCOLS 2 // number of color swatches
#define MIX_CLASSNAME _T("")//GetString(IDS_RB_FOG)
//--------------------------------------------------------------
// Mix: A Mix texture map
//--------------------------------------------------------------
#define PB_REF 0
#define SUB1_REF 1
#define SUB2_REF 2
#define SUB3_REF 3
#define PB_TEXOUT 4
class MixDlgProc;
class Mix: public MultiTex {
public:
enum
{
mix_mix, mix_curvea, mix_curveb, mix_usecurve,
mix_color1, mix_color2,
mix_map1, mix_map2, mix_mask,
mix_map1_on, mix_map2_on, mix_mask_on, // main grad params
mix_output
};
static ParamDlg* texoutDlg;
static MixDlgProc *paramDlg;
TexHandle *texHandle[3];
int useSubForTex[3];
int numTexHandlesUsed;
int texOpsType[3];
Interval texHandleValid;
Color col[NCOLS];
IParamBlock2 *pblock; // ref #0
Texmap* subTex[NMIXSUBTEX]; // 3 More refs
BOOL mapOn[NMIXSUBTEX];
TextureOutput *texout; // ref #4
Interval ivalid;
float mix;
BOOL useCurve;
float crvA;
float crvB;
BOOL rollScroll;
public:
BOOL Param1;
Mix();
~Mix() {
DiscardTexHandles();
}
ParamDlg* CreateParamDlg(HWND hwMtlEdit, IMtlParams *imp);
void Update(TimeValue t, Interval& valid);
void Init();
void Reset();
Interval Validity(TimeValue t) { Interval v; Update(t,v); return ivalid; }
void SetOutputLevel(TimeValue t, float v) {texout->SetOutputLevel(t,v); }
void SetColor(int i, Color c, TimeValue t);
void SetMix(float f, TimeValue t);
void SetCrvA(float f, TimeValue t);
void SetCrvB(float f, TimeValue t);
void NotifyChanged();
void SwapInputs();
void EnableStuff();
float mixCurve(float x);
// Evaluate the color of map for the context.
AColor EvalColor(ShadeContext& sc);
float EvalMono(ShadeContext& sc);
AColor EvalFunction(ShadeContext& sc, float u, float v, float du, float dv);
// For Bump mapping, need a perturbation to apply to a normal.
// Leave it up to the Texmap to determine how to do this.
Point3 EvalNormalPerturb(ShadeContext& sc);
// Methods to access texture maps of material
int NumSubTexmaps() { return NMIXSUBTEX; }
Texmap* GetSubTexmap(int i) { return subTex[i]; }
void SetSubTexmap(int i, Texmap *m);
TSTR GetSubTexmapSlotName(int i);
Class_ID ClassID() { return mixClassID; }
SClass_ID SuperClassID() { return TEXMAP_CLASS_ID; }
void GetClassName(TSTR& s) { s= MIX_CLASSNAME; }
void DeleteThis() { delete this; }
int NumSubs() { return 2+NMIXSUBTEX; }
Animatable* SubAnim(int i);
TSTR SubAnimName(int i);
int SubNumToRefNum(int subNum) { return subNum; }
// From ref
int NumRefs() { return 2+NMIXSUBTEX; }
RefTargetHandle GetReference(int i);
void SetReference(int i, RefTargetHandle rtarg);
RefTargetHandle Clone(RemapDir &remap = DefaultRemapDir());
RefResult NotifyRefChanged( Interval changeInt, RefTargetHandle hTarget,
PartID& partID, RefMessage message );
// IO
// BOOL loadOnChecks;
IOResult Save(ISave *isave);
IOResult Load(ILoad *iload);
// JBW: direct ParamBlock access is added
int NumParamBlocks() { return 1; } // return number of ParamBlocks in this instance
IParamBlock2* GetParamBlock(int i) { return pblock; } // return i'th ParamBlock
IParamBlock2* GetParamBlockByID(BlockID id) { return (pblock->ID() == id) ? pblock : NULL; } // return id'd ParamBlock
BOOL SetDlgThing(ParamDlg* dlg);
void DiscardTexHandles() {
for (int i=0; i<3; i++) {
if (texHandle[i]) {
texHandle[i]->DeleteThis();
texHandle[i] = NULL;
}
}
texHandleValid.SetEmpty();
}
// Multiple map in vp support -- DS 4/24/00
BOOL SupportTexDisplay() { return TRUE; }
void ActivateTexDisplay(BOOL onoff);
BOOL SupportsMultiMapsInViewport() { return TRUE; }
void SetupGfxMultiMaps(TimeValue t, Material *mtl, MtlMakerCallback &cb);
// Multiple map code
void StuffAlpha(BITMAPINFO* bi1, BITMAPINFO *bi2, BOOL invert);
void StuffConstAlpha(float falpha, BITMAPINFO *bmi);
void ConstAlphaBlend(BITMAPINFO *bi1, BITMAPINFO *bi2, float a);
void ConstScale(BITMAPINFO *bi, float s);
void AlphaBlendMaps(BITMAPINFO *bi1,BITMAPINFO *bi2,BITMAPINFO *balph);
void FixupAlpha(BITMAPINFO *bi);
void SetTexOps(Material *mtl, int i, int type);
void SetHWTexOps(IHardwareMaterial *pIHWMat, int ntx, int type);
// From Texmap
bool IsLocalOutputMeaningful( ShadeContext& sc ) { return true; }
};
#endif
|
5331abbd0e432b98eb1863f84adc5fd81b2da480 | 8efd9c83d59166344c0700e702cd75f9fb771cf4 | /sameUserandTime.cpp | 9d0a3ac569a7ddcf5ceafb5007b871949d28c572 | [] | no_license | LilyZhaoZhao/AAAI | ed431a707b8458e43e10cdf08ca280a844065d8a | ac5e364bda75d1be45843f39fa48b8c5cf2361c7 | refs/heads/master | 2020-09-17T18:45:59.311647 | 2016-09-25T02:07:31 | 2016-09-25T02:07:31 | 67,461,535 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,757 | cpp | sameUserandTime.cpp | /*
1、check 0316和0323中每个(u,t)访问的ap中有重复类型的(u,t)的占比。
2、check 0316和0323中每个ap被访问的(u,t)重复的占比。
*/
#include <fstream>
#include <string>
#include <sstream>
#include <map>
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <cstring>
#include <ctime>
#include <cmath>
using namespace std;
map< pair<string, int>, set<int> > utCtgy16;
map< pair<string, int>, set<int> > utCtgy23;
map< pair<string, int>, set<string> > utMac16;
map< pair<string, int>, set<string> > utMac23;
map< pair<string, int>, set<int> > getMapCtgy(string s){ //newmoveSZ_0316_inCatagory
map< pair<string, int>, set<int> > utCtgy;
ifstream ifs1(s.c_str());
string guid, mac, token, line;
int start_hour=0, catagory = 0;
int count = 0;
while(getline(ifs1, line)){
istringstream iss(line);
count=0;
while(getline(iss, token, ',')){
count ++;
switch(count){
case 1:
guid = token;
break;
case 2:
mac = token;
break;
case 3:
start_hour = atoi(token.c_str());
break;
case 5:
catagory = atoi(token.c_str());
break;
}
}
utCtgy[make_pair(guid, start_hour)].insert(catagory);
}
ifs1.close();
return utCtgy;
}
map< pair<string, int>, set<string> > getMapMac(string s){ //newmoveSZ_0316_inCatagory
map< pair<string, int>, set<string> > utMac;
ifstream ifs1(s.c_str());
string guid, mac, token, line;
int start_hour=0, catagory = 0;
int count = 0;
while(getline(ifs1, line)){
istringstream iss(line);
count=0;
while(getline(iss, token, ',')){
count ++;
switch(count){
case 1:
guid = token;
break;
case 2:
mac = token;
break;
case 3:
start_hour = atoi(token.c_str());
break;
case 5:
catagory = atoi(token.c_str());
break;
}
}
utMac[make_pair(guid, start_hour)].insert(mac);
}
ifs1.close();
return utMac;
}
void getNum(){
int count = 0;//统计有相同类别的(u,t)的个数
map< pair<string, int>, set<int> >::iterator iter1;
set<int> set1, set2, set3;
pair<string, int> utpair;
string guid;
int hour;
cout<<"coming1"<<endl;
for(iter1=utCtgy16.begin(); iter1 != utCtgy16.end(); ++iter1){
set3.clear();
utpair = iter1->first;
guid = utpair.first;
hour = utpair.second;
set1 = iter1->second;
set2 = utCtgy23[utpair];
set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(set3, set3.begin()));
if(set3.size() > 0){
count ++;
//cout<< set3.size()<<endl;
}
set3.clear();
set2 = utCtgy23[make_pair(guid, hour-1)];
set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(set3, set3.begin()));
if(set3.size() > 0){
count ++;
//cout<< set3.size()<<endl;
}
set3.clear();
set2 = utCtgy23[make_pair(guid, hour+1)];
set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(set3, set3.begin()));
if(set3.size() > 0){
count ++;
//cout<< set3.size()<<endl;
}
}
cout<<count<<endl;
double percentage = double(count)/(utCtgy16.size());
cout<< percentage <<endl;
}
//输出0316一天中,每个(u,t)内的ap的个数,以及ctgy的个数。
void getNum2(){
int count = 0;//统计有相同类别的(u,t)的个数
map< pair<string, int>, set<int> >::iterator iter1;
set<int> set1, set2, set3;
pair<string, int> utpair;
string guid;
int hour=0, i=0, num1=0, num2=0, num3=0;
ofstream ofs("numOfCtgyandAp0316");
for(iter1=utCtgy16.begin(); iter1 != utCtgy16.end(); ++iter1){
set2.clear();
set3.clear();
utpair = iter1->first;
guid = utpair.first;
hour = utpair.second;
num1 = (iter1->second).size();
if(hour > 0)
{
if(utCtgy16.find(make_pair(guid, hour-1))!=utCtgy16.end())
num2 = utCtgy16[make_pair(guid, hour-1)].size();
else
num2 = 0;
//set2 = utCtgy16[make_pair(guid, hour-1)];
//num2 = set2.size();
}
else
num2 = 0;
if(hour < 23){
if(utCtgy16.find(make_pair(guid, hour+1))!=utCtgy16.end()) //注意判断是否是空值,不然会引起内存紊乱。
num3 = utCtgy16[make_pair(guid, hour+1)].size();
else
num3 = 0;
}
else
num3 = 0;
ofs<< num1 <<','<<num2<<','<<num3<<','<<(num1+num2+num3);
num1 = utMac16[utpair].size();
if(hour > 0)
{
if(utMac16.find(make_pair(guid, hour-1))!=utMac16.end())
num2 = utMac16[make_pair(guid, hour-1)].size();
else
num2 = 0;
//set2 = utCtgy16[make_pair(guid, hour-1)];
//num2 = set2.size();
}
else
num2 = 0;
if(hour < 23){
if(utMac16.find(make_pair(guid, hour+1))!=utMac16.end()) //注意判断是否是空值,不然会引起内存紊乱。
num3 = utMac16[make_pair(guid, hour+1)].size();
else
num3 = 0;
}
else
num3 = 0;
ofs<<','<<(num1+num2+num3)<<endl;
}
ofs.close();
}
//输出0316一天中,每个(u,t)内的ap的个数,以及ctgy的个数。
void getNum3(){
int count = 0;//统计有相同类别的(u,t)的个数
map< pair<string, int>, set<int> >::iterator iter1;
set<int> set1, set2, set3;
pair<string, int> utpair;
string guid;
int hour, i=0, set1Num, set2Num, set3Num;
vector<int> ivec(12,0);
ofstream ofs("numOfCtgyandAp0316");
for(iter1=utCtgy16.begin(); iter1 != utCtgy16.end(); ++iter1){
//set3.clear();
utpair = iter1->first;
guid = utpair.first;
hour = utpair.second;
set1Num = (iter1->second).size();
cout<< set1Num<<',';//输出该(u,t)的ctgy个数
set1Num = utMac16[make_pair(guid, hour)].size();
// ofs<< set1Num <<endl;//ap的个数
}
ofs.close();
}
int main(int argc, char* argv[]){
string s1 = argv[1];//newmoveSZ_0316_inCatagory
string s2 = argv[2];//newmoveSZ_0323_intCatagory
utCtgy16 = getMapCtgy(s1);
utMac16 = getMapMac(s1);
cout<<"getMap ok"<<endl;
//cout<<utCtgy16.size()<<endl;
//mypair = getMap(s2);
//utCtgy23 = mypair.first;
//utMac23 = mypair.second;
getNum2();
return 0;
}
/*
map<string, set<pair<string, int> > > conn16;
map<string, set<pair<string, int> > > conn23;
map<string, set<pair<string, int> > > getConn(string s1){ //newmoveSZ_0316_inCatagory
map<string, set<pair<string, int> > > conn;
conn.clear();
ifstream ifs1(s1.c_str());
string guid, mac, token, line;
int start_hour=0, catagory = 0;
int count = 0;
while(getline(ifs1, line)){
istringstream iss(line);
count=0;
while(getline(iss, token, ',')){
count ++;
switch(count){
case 1:
guid = token;
break;
case 2:
mac = token;
break;
case 3:
start_hour = atoi(token.c_str());
break;
case 5:
catagory = atoi(token.c_str());
break;
}
}
conn[mac].insert(make_pair(guid, start_hour));
}
ifs1.close();
return conn;
}
void getNum(){
int count = 0;//统计有相同类别的(u,t)的个数
map< pair<string, int>, set<int> >::iterator iter1;
set<int> set1, set2, set3;
pair<string, int> utpair;
for(iter1=utCtgy16.begin(); iter1 != utCtgy16.end(); ++iter1){
set3.clear();
utpair = iter1->first;
set1 = iter1->second;
set2 = utCtgy23[utpair];
set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(set3, set3.begin()));
if(set3.size() > 0){
count ++;
cout<< set3.size()<<endl;
}
}
cout<<count<<endl;
double percentage = double(count)/(utCtgy16.size());
cout<< percentage <<endl;
}
int main(int argc, char* argv[]){
string s1 = argv[1];//newmoveSZ_0316_inCatagory
string s2 = argv[2];//newmoveSZ_0323_intCatagory
utCtgy16 = getConn(s1);
utCtgy23 = getConn(s2);
getNum();
return 0;
}
*/
|
a5a50c41a45f5d9578259dfda264260f767603af | 1afe4400d60ec7faaed2d858bf2702997fbc0c31 | /codeforces/r599/a.cpp | 591a0820823338104ee5b0b5214b9a39864336db | [] | no_license | heitordnts/competitive-prog | 26f0a571ac9b9de7f28cf6ebc551badc09c73b3c | ae554c52ab7e3ea7b3fefead5341b80a15b489b7 | refs/heads/master | 2021-06-28T10:04:56.412846 | 2020-06-08T02:18:45 | 2020-06-08T02:18:45 | 175,509,679 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 503 | cpp | a.cpp | #include <bits/stdc++.h>
int main(){
int q,n;
scanf("%d",&q);
while(q--){
int heights[1000]={0};
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&heights[i]);
}
int maxSquare = -1;
for(int i=0;i<n;++i){
int c = 0;
for(int j=0;j<n;++j){
if(heights[i] <= heights[j]) c++;
}
if(c >= heights[i] && heights[i] > maxSquare )
maxSquare = heights[i];
else if(c < heights[i] && c > maxSquare)
maxSquare = c;
}
printf("%d\n",maxSquare);
}
return 0;
}
|
cc6ead04017520778d337dbb88b43aecc8c29f83 | 6463da9a716e1267cf0505e230b5801bc5b175aa | /transfer/transfer.cc | a30014f66961570886308effc13dc179d91278bf | [
"LicenseRef-scancode-public-domain"
] | permissive | lianzeng/cplusplus11.Examples | c333948f70a16b84ce139f1e5812ab9f0ba45afe | f27335ec622938d0af17d664877f5934e418dcd3 | refs/heads/master | 2021-01-24T18:38:42.216365 | 2016-11-16T17:13:53 | 2016-11-16T17:13:53 | 84,463,090 | 0 | 1 | null | 2018-01-31T04:22:41 | 2017-03-09T16:15:43 | C++ | UTF-8 | C++ | false | false | 4,703 | cc | transfer.cc | /*
C++11 example simple tcp/ip networking with sockets.
to send a file:
transfer-tool ipaddress port filename
to serve up files:
transfer-tool port
if your behind a router, be sure to forward that port
will serve up files in the local directory where the program is ran
written by Jared Bruni
vist me online @ http://facebook.com/LostSideDead0x
http://lostsidedead.com
*/
#include<iostream>
#include<thread>
#include<vector>
#include<fstream>
#include<mutex>
#include"socket.hpp"
// listen_at thread function
void listen_at(std::string user_ip, int sock_id) {
try {
mx::mxSocket sock{sock_id};
std::mutex mut;
int value;
sock.Read(&value, sizeof(value));
if(value>0) {
char *buffer = new char[value+1];
sock.Read(buffer, value);
buffer[value] = 0;
mut.lock();
std::cout << buffer << "\n";
std::string file_path=buffer;
delete [] buffer;
mut.unlock();
if(file_path.find("\\") != std::string::npos) {
mut.lock();
std::cout << "User: " << user_ip << " Sent illegal filename..\n";
mut.unlock();
}
auto pos = file_path.rfind("/");
std::string filename=file_path.substr(pos+1,file_path.length()-pos);
mut.lock();
std::cout << "Sending... " << filename << "\n";
mut.unlock();
std::string src_file="./"+filename;
std::fstream fs;
fs.open(src_file, std::ios::in | std::ios::binary);
if(!fs.is_open()) {
mut.lock();
std::cout << "Asked for file not in directory.\n";
mut.unlock();
sock.closeSocket();
return;
}
fs.seekg(0, std::ios::end);
int len = fs.tellg();
fs.seekg(0, std::ios::beg);
mut.unlock();
sock.Write(&len, sizeof(len));
while(!fs.eof()) {
char buff[256];
fs.read(buff, 256);
int bytes_read=fs.gcount();
if(bytes_read<=0) break;
sock.Write(buff, bytes_read);
}
sock.closeSocket();
mut.lock();
std::cout << " File sent..\n";
mut.unlock();
return;
}
}
catch(mx::ReadWriteError) {
std::cerr << "Error on read/write.\n";
}
}
// read file to this program on ip, port and filename
void read_file(std::string ip, int port, std::string file_path) {
mx::mxSocket sock;
sock.createSocket();
if(sock.connectTo(ip, port)) {
int value=file_path.length();
sock.Write(&value, sizeof(value));
sock.Write(const_cast<char*>(file_path.c_str()), value);
std::fstream fs;
auto p=file_path.rfind("/");
std::string local_name="downloaded."+file_path.substr(p+1, file_path.length());
fs.open(local_name, std::ios::binary | std::ios::out);
int file_size=0;
sock.Read(&file_size, sizeof(file_size));
ssize_t rd_bytes=0;
int packet_size = 255;
char buffer[255];
unsigned long total=0;
while((rd_bytes = sock.Read((char*)buffer,packet_size)) != 0) {
fs.write(buffer, rd_bytes);
total += rd_bytes;
if(total > (unsigned long)file_size) break;
}
fs.close();
sock.closeSocket();
}
}
int main(int argc, char **argv) {
try {
std::vector<std::thread> thread_array;
if(argc == 2) {
unsigned int port = atoi(argv[1]);
bool active = true;
mx::mxSocket sock;
sock.createSocket();
while(active == true) {
if(sock.listenAt(port)) {
std::string user_ip;
int sockid = sock.acceptNewSocket(user_ip);
std::cout << "Connected to: " << user_ip << "\n";
thread_array.emplace_back(listen_at, user_ip, sockid);
}
}
} else if(argc == 4) {
try {
std::string ip = argv[1];
unsigned int port = atoi(argv[2]);
std::string file_path=argv[3];
read_file(ip, port, file_path);
}
catch(mx::ReadWriteError) {
std::cerr << "Error on read or write.\n";
}
}
}
catch(std::exception &e) {
std::cerr << e.what() << "\n";
}
catch(...) {
std::cerr << "Unkwown Error ..\n";
}
return 0;
}
|
95e2d8fd52edffe609603da90c638c22038e64db | 90699fa45fdb43cd78668d0a99d70af1dafa79c3 | /ccc/friend/main1.cpp | f15df30f34a2b72491ce93e75fabb0dc6449c457 | [] | no_license | wallEVA96/ccc-c-trial | e75d62bdef0c5e6d95738095644eb8a8e3be9ac0 | 36287399e2cd817c33cbfbaf0ae2ee52b419a779 | refs/heads/master | 2021-07-13T13:05:40.932384 | 2020-07-06T11:41:12 | 2020-07-06T11:41:12 | 154,621,759 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 768 | cpp | main1.cpp | /*
* main1.cpp
* _ _
* __ ____ _| | | _____ ____ _
* \ \ /\ / / _` | | |/ _ \ \ / / _` |
* \ V V / (_| | | | __/\ V / (_| |
* \_/\_/ \__,_|_|_|\___| \_/ \__,_|
* Copyright (C) 2019 walleva <walleva@ubuntu>
*
* Distributed under terms of the MIT license.
*/
#include <iostream>
using namespace std;
class leaf;
class tree
{
public:
void printShape(leaf &l);
};
class leaf
{
friend void tree::printShape(leaf &l);
public:
static long l_num;
private:
char shape;
};
long leaf::l_num = 1333;
void tree::printShape(leaf &l)
{
cout << l.shape << endl;
}
int main(int argc, char **argv)
{
leaf ln;
cout << sizeof(ln) << endl;
cout << ln.l_num << endl;
return 0;
}
|
1fc79254c60a2b765c81ed97791f60242416d0e6 | 167b9fa1f143d7d777b9a914ef261db645bd214e | /driver.cpp | 8adeb616835d0d8da32251b65ee9d2901e20d8e2 | [] | no_license | ahhda/map-builder | f9426e041222822185cbc62f032ba1bbfb62124d | 4380703452cc5598c75ede662424edc8d1ef181f | refs/heads/master | 2021-01-19T13:11:51.750768 | 2017-04-12T16:35:07 | 2017-04-12T16:35:07 | 88,072,039 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 107 | cpp | driver.cpp | #include "grid.h"
#include "map.h"
int main(int argc, char const *argv[])
{
Map m;
m.run();
return 0;
} |
489c92b7e0e27bc342487c2d8d30382370097dd6 | 4ef59d52684155589dc393ea9f092c319a4ffc90 | /SnowGL/include/Window.h | b3e3b7ca86147ad00ccaa91c6edeb7a86fbf67cd | [] | no_license | AlasdairH/SnopenGL | 8304085e7c55c53742aa7b847dee463162d1a2f5 | 06885f580aae390186eebd997f198ac9a2e5aa45 | refs/heads/master | 2020-04-12T04:21:07.945770 | 2019-05-16T15:21:11 | 2019-05-16T15:21:11 | 162,293,125 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,462 | h | Window.h | #pragma once
// cstdlib
// external libs
// program
#include "PCH.h"
namespace SnowGL
{
/*! @class Window
* @brief An abstraction of the SDL Window class which can be used to create a window for OpenGL rendering
*
* This class uses the SDL Window class to create a window in the constructor. By use of default parameters,
* a default window can be created by passing no arguments to the constructor or various settings can be applied.
* An OpenGL Context is created with the window for rendering.
*/
class Window
{
public:
/** @brief The Window Constructor
* @param _title The Window Title that will be displayed in the OS
* @param _width The default width of the window
* @param _height The default height of the window
*
* The constructor takes default arguments for a standard window but title, width and height can be set
* by overwriting these provided values.
* The constructor creates an SDL Window, SDL Renderer and an accompanying GL Context.
*/
Window(const std::string _title = "Default", const int _width = 1920, const int _height = 1080);
/** @brief The Window Destructor
*
* This Destructor simply destorys the SDL Window and Renderer.
*/
~Window();
/** @brief Window Buffer Swap
*
* This method simply swaps the window buffer. Should be called per frame.
*/
void swapBuffer();
/** @brief Sets a new window size
* @param _width The new width of the window
* @param _height The new height of the window
*
* Resizes the window and applies the info to OpenGL
*/
void resize(int _width, int _height);
/** @brief Get the window width
* @return An integar containing the window width
*
* Returns the window width.
*/
inline int getWidth() { return m_width; }
/** @brief Get the window Height
* @return An integar containing the window height
*
* Returns the window height.
*/
inline int getHeight() { return m_height; }
/** @brief Get a pointer to the SDL Window
* @return A pointer to the SDL window
*
* Get a pointer to the SDL Window. Used by IMGUI.
*/
inline SDL_Window * getWindowPtr() { return m_window; }
protected:
SDL_Window *m_window; /**< A pointer to the SDL_Window. */
SDL_Renderer *m_renderer; /**< A pointer to the SDL_Renderer. */
SDL_GLContext m_openGLContext; /**< The GL Context for OpenGL Rendering. */
int m_width; /**< The Window Width */
int m_height; /**< The Window Width */
};
} |
1b4d1cd68e7aae1114dafd01a8e817a2d8434779 | 4b22c74bdbad8c9ef08626ec55a001283af2a755 | /src/Personaje.cpp | b914d40a6b8fbdc7301ee15f9afeded3b74cea66 | [] | no_license | EquipoF/Trabajo-Informatica | 520d2bbb828fc67dd6093910700d6189b6baa672 | df146f7d7de28bed3109b6aeeb2c281d2851d4f5 | refs/heads/master | 2022-11-30T02:48:32.564834 | 2020-07-04T14:52:25 | 2020-07-04T14:52:25 | 255,717,092 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 7,506 | cpp | Personaje.cpp | #include "Personaje.h"
#include "Interaccion.h"
//Parámetros del cuerpo
#define ALTO 1.0f
#define ANCHO 0.5f
#define GRAVEDAD -10.0f
//Parámetros matemáticos (para saltos)
#define COS_45 1/1.414f
#define SEN_45 1/1.414f
//Nombres de las teclas
enum { DCHA = 'd', IZQ = 'a', ABAJO = 's', ESPACIO = ' ', ESPACIO_SOLTADO = 0, DCHA_SOLTADO = 1, IZQ_SOLTADO = 2, ABAJO_SOLTADO=3 };
//Tipos de salto
enum { NORMAL = 0, PARED_DCHA = 1, PARED_IZQ = 2, SALTO_ABAJO = 4, CARGADO = 3 };
Personaje::Personaje(): sprite("imagenes/rana.png", 11), sprite_salto("imagenes/rana_salto.png"), sprite_caida("imagenes/caer.png"), sprite_camina("imagenes/Run.png", 12)
{
//Variables intrínsecas del personaje (no cambian cada vez que mueres)
vMov = 3.0;
vSalto = 7.0;
multiplicadorCargado = 2.0f;
cuerpo = Rectangulo(ANCHO, ALTO, Vector2D(0.0f, -2.0f)); //Inicializo el personaje como su ancho, alto y lo pongo en la posición inicial.
//Variables que se restablecen cada vez que el personaje muere
Personaje::Inicializa();
//inicializacion posiciones y tamaños sprites
Vector2D centro = Vector2D(0.5f, 0.45f);
Vector2D size = Vector2D(1.0f, 1.3f);
sprite.setCenter(centro.x, centro.y);
sprite.setSize(size.x, size.y);
sprite_salto.setCenter(centro.x, centro.y);
sprite_salto.setSize(size.x, size.y);
sprite_caida.setCenter(centro.x, centro.y);
sprite_caida.setSize(size.x, size.y);
sprite_camina.setCenter(centro.x, centro.y);
sprite_camina.setSize(size.x, size.y);
}
Personaje::~Personaje()
{
}
void Personaje::Inicializa()
{
Personaje::SetPos(0.0f, -2.0f); //Cambiar a parámetro de entrada
Personaje::SetVel(0.0, 0.0);
aceleracion.y = GRAVEDAD;
saltosRestantes = 2; //nº de saltos para probar
powerUpDisponible = 0;
//Variables de movimietno
dchaPresionado = false;
izqPresionado = false;
//variables de contacto
contactoParedDcha = false; //para saltos de pared
contactoParedIzq = false;
plataformaEnContacto = -1; //No está posado sobre ninguna plataforma
}
void Personaje::Dibuja()
{
glPushMatrix();
glTranslatef(posicion.x, posicion.y-0.05f, 0);
glColor3f(1.0f, 0.0f, 0.0f);
//gestion de direccion y animacion
if (velocidad.x > 0.01)sprite.flip(false, false);//sprite idle
if (velocidad.x < -0.01)sprite.flip(true, false);
if (velocidad.x > 0.01)sprite_salto.flip(false, false);//sprite salto
if (velocidad.x < -0.01)sprite_salto.flip(true, false);
if (velocidad.x > 0.01)sprite_caida.flip(false, false);//sprite caida
if (velocidad.x < -0.01)sprite_caida.flip(true, false);
if (velocidad.x > 0.01)sprite_camina.flip(false, false);//sprite camina
if (velocidad.x < -0.01)sprite_camina.flip(true, false);
if (velocidad.y > 0.01)
sprite_salto.draw();
else if (velocidad.y < -0.01)
sprite_caida.draw();
else if ((velocidad.y < 0.1 && velocidad.y > -0.1f) && (velocidad.x > 0.1 || velocidad.x < -0.1))
{
sprite_camina.draw();
sprite_camina.loop();
}
else if ((velocidad.y <= 0.1 && velocidad.y >= -0.1f) && (velocidad.x <= 0.1 && velocidad.x >= -0.1f))
{
sprite.draw();
sprite.loop();
}
glPopMatrix();
//cuerpo.Dibuja(); //dibujar para ver la hitbox
}
void Personaje::Mueve(float t, ListaRectangulos& plataformas)
{
ObjetoMovil::Mueve(t);
//Establecer velocidad en funcion de las teclas presionadas y las plataformas en las que está
if (dchaPresionado) {
velocidad.x = vMov;
if (plataformaEnContacto != -1) //Si estás en contactyo con una plataforma
{
velocidad.x = vMov + plataformas.lista[plataformaEnContacto]->GetVel().x; //Su velocidad se suma a la tuya
}
}
if (izqPresionado) {
velocidad.x = -vMov;
if (plataformaEnContacto != -1)
{
velocidad.x = -vMov + plataformas.lista[plataformaEnContacto]->GetVel().x;
}
}
if (!dchaPresionado && !izqPresionado) { //Si no pulsas nada
if (plataformaEnContacto != -1) //Si estás en contacto con una plataforma
{
velocidad.x = plataformas.lista[plataformaEnContacto]->GetVel().x;
}
}
//Correcciones de posición
int aux = Interaccion::Choque(plataformas, *this); //Evaluar si hay choque con plataforma y guarda el resultado en aux
if (aux != -1) { // Si hay choque con alguna plataforma
//Guardo aux en un atributo del personaje para que no se pierda al repetir la operación pero con la posición corregida
plataformaEnContacto = aux;
}
if (plataformaEnContacto != -1) {
Interaccion::SalidaLateral(*plataformas.lista[plataformaEnContacto], *this);
}
//Cambiar posición para dibujar
cuerpo.SetCentro(posicion);
}
void Personaje::Tecla(unsigned char key)
{
//Flags para la detección de teclas.
//(esto se peude tener como variables static si se usan solo en esta funcion o como atributo si se usa en otras)
static bool espacioPresionado = false; //Hago un booleano que perdura en el timepo para guardar el estado de las teclas
static bool abajoPresionado = false;
switch (key) //Llevar el tratamiento de las teclas (flags y eso) al main
{
//Movimiento derecha
case DCHA:
dchaPresionado = true;
break;
case DCHA_SOLTADO:
dchaPresionado = false;
break;
//Movimiento izquierda
case IZQ:
izqPresionado = true;
break;
case IZQ_SOLTADO:
izqPresionado = false;
break;
//Movimiento vertical
case ABAJO:
abajoPresionado = true;
break;
case ABAJO_SOLTADO:
abajoPresionado = false;
break;
//Se presiona la barra espaciadora => se solicita un salto
case ESPACIO:
//Meter aquí los distintos tipos de salto.
if (!espacioPresionado) //Si no estaba pulsada antes, es decir, la acabo de pulsar, genero un salto
{
if (contactoParedDcha && dchaPresionado) { //Salto de pared
Personaje::Salta(PARED_DCHA);
}
else if (contactoParedIzq && izqPresionado) { //Salto de pared
Personaje::Salta(PARED_IZQ);
}
else if (velocidad.modulo() == 0 && abajoPresionado && powerUpDisponible > 0) { //Si estás quieto y presionas abajo + salto (se puede añadir una espera) y has recogido algún powerUp
Personaje::Salta(CARGADO);
}
else { //Salto normal
Personaje::Salta(NORMAL);
}
}
espacioPresionado = true; //Marco la barra espaciadora como pulsada.
break;
//Se suelta la barra espaciadora
case ESPACIO_SOLTADO:
espacioPresionado = false; //La marco como no pulsada.
break;
}
}
void Personaje::Salta(unsigned int tipoSalto) {
//Cambio en variables al pulsar espacio
aceleracion.y = GRAVEDAD;//Gravedad ON
plataformaEnContacto = -1;//Deja de estar en contacto con una plataforma
//Elijo el tipo de salto (hacia dónde va el mvto. vertical)
switch (tipoSalto)
{
case (NORMAL):
if (saltosRestantes > 0) //Si hay saltos restantes
{
velocidad.y = vSalto; //Velocidad en Y para hacer un salto normal (hacia arriba)
saltosRestantes--; //resto 1 al número de saltos
}
break;
case (PARED_DCHA): //Ángulo de 45 grados SOLO SI la vel. de mvto. y la de salto son iguales, sino se necesitan más cálculos.
velocidad.x = -vMov * COS_45;
velocidad.y = vSalto * SEN_45;
contactoParedDcha = false;
break;
case (PARED_IZQ):
velocidad.x = vMov * COS_45;
velocidad.y = vSalto * SEN_45;
contactoParedIzq = false;
break;
case (CARGADO):
velocidad.y = multiplicadorCargado*vSalto;
saltosRestantes--;
powerUpDisponible--;
break;
}
}
void Personaje::SetSaltosRes(int saltosIn)
{
saltosRestantes = saltosIn;
}
int Personaje::GetSaltosRes(void)
{
return saltosRestantes;
}
void Personaje::SetPowerUpDisponible(int powerUpDisponibleIn)
{
powerUpDisponible = powerUpDisponibleIn;
} |
434edbc88196dbc879e6e5f7eb51402e4133f261 | 070c9dc81dd05048e2b6796bfcf6a64e10eb98db | /src/Exception.cpp | 01f0b93b158d8bf76735dda73002f207387776b5 | [
"MIT"
] | permissive | falltergeist/dat-unpacker | d48b34196d45030fc494bf206cffdd8aaeb6311e | d536ef630d9a47e866cddd7e826480c3ac34bb3d | refs/heads/develop | 2022-06-05T06:18:53.519470 | 2022-05-28T10:18:44 | 2022-05-28T10:18:44 | 17,872,846 | 7 | 7 | MIT | 2022-05-28T10:18:45 | 2014-03-18T16:19:25 | C++ | UTF-8 | C++ | false | false | 413 | cpp | Exception.cpp | // Project includes
#include "Exception.h"
// Third party includes
// stdlib
namespace DatUnpacker
{
Exception::Exception(const char* message) : _message(message)
{
}
Exception::Exception(const std::string& message) : _message(message)
{
}
Exception::~Exception() throw()
{
}
const char* Exception::what() const throw()
{
return _message.c_str();
}
}
|
edb0f093e4cd91dd48a9f480a1f122c02b007eef | 37dfba1452c9dc165080d4e308f210779da39f44 | /taller-seguridad/generador.cpp | 7fd73c331f577fb2263a098324021d0a5731c957 | [] | no_license | mtqp/dni-from-mars | 732e6403280ad3ad7219b2b9e81f272a3d3c01d4 | fba3e84fde70aa10e02e1bb0b0fc6f431beb8b6c | refs/heads/master | 2021-01-10T06:50:17.423538 | 2010-11-28T20:09:01 | 2010-11-28T20:09:01 | 36,199,835 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 322 | cpp | generador.cpp |
#include<string.h>
#include<stdlib.h>
#include "md5.h"
int main(int argc, char** argv)
{
int cantidad = atoi( argv[1] );
char hash[32];
char pass[] = "De Sousa Bispo, Grosso\0";
int i;
md5_buf_to_hex(pass, sizeof(pass), hash);
for( i = 0 ; i < cantidad ; i++ )
{
printf('A');
}
cout << hash;
return 0;
}
|
a1b238972a5276cf291df774044aea721815e068 | 5793887005d7507a0a08dc82f389d8b8849bc4ed | /vendor/mediatek/proprietary/hardware/mtkcam/legacy/platform/mt6735m/core/iopipe/test/test_normalstream.cpp | ef859ca5518aee6dcd3cb3a3e3fc5d713e37eaa9 | [] | no_license | wangbichao/dual_camera_x | 34b0e70bf2dc294c7fa077c637309498654430fa | fa4bf7e6d874adb7cf4c658235a8d24399f29f30 | refs/heads/master | 2020-04-05T13:40:56.119933 | 2017-07-10T13:57:33 | 2017-07-10T13:57:33 | 94,966,927 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,106 | cpp | test_normalstream.cpp | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek
* Software") have been modified by MediaTek Inc. All revisions are subject to
* any receiver's applicable license agreements with MediaTek Inc.
*/
///////////////////////////////////////////////////////////////////////////////
// No Warranty
// Except as may be otherwise agreed to in writing, no warranties of any
// kind, whether express or implied, are given by MTK with respect to any MTK
// Deliverables or any use thereof, and MTK Deliverables are provided on an
// "AS IS" basis. MTK hereby expressly disclaims all such warranties,
// including any implied warranties of merchantability, non-infringement and
// fitness for a particular purpose and any warranties arising out of course
// of performance, course of dealing or usage of trade. Parties further
// acknowledge that Company may, either presently and/or in the future,
// instruct MTK to assist it in the development and the implementation, in
// accordance with Company's designs, of certain softwares relating to
// Company's product(s) (the "Services"). Except as may be otherwise agreed
// to in writing, no warranties of any kind, whether express or implied, are
// given by MTK with respect to the Services provided, and the Services are
// provided on an "AS IS" basis. Company further acknowledges that the
// Services may contain errors, that testing is important and Company is
// solely responsible for fully testing the Services and/or derivatives
// thereof before they are used, sublicensed or distributed. Should there be
// any third party action brought against MTK, arising out of or relating to
// the Services, Company agree to fully indemnify and hold MTK harmless.
// If the parties mutually agree to enter into or continue a business
// relationship or other arrangement, the terms and conditions set forth
// hereunder shall remain effective and, unless explicitly stated otherwise,
// shall prevail in the event of a conflict in the terms in any agreements
// entered into between the parties.
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008, MediaTek Inc.
// All rights reserved.
//
// Unauthorized use, practice, perform, copy, distribution, reproduction,
// or disclosure of this information in whole or in part is prohibited.
////////////////////////////////////////////////////////////////////////////////
// AcdkCLITest.cpp $Revision$
////////////////////////////////////////////////////////////////////////////////
//! \file AcdkCLITest.cpp
//! \brief
#define LOG_TAG "CamIOpipeTest"
#include <vector>
using namespace std;
//#include <linux/cache.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <stdio.h>
//
#include <errno.h>
#include <fcntl.h>
#include <mtkcam/common.h>
#include <mtkcam/common/hw/hwstddef.h>
#include <mtkcam/iopipe/PostProc/INormalStream.h>
#include <mtkcam/imageio/ispio_pipe_ports.h>
#include <mtkcam/imageio/ispio_pipe_scenario.h>
#include <mtkcam/drv_common/imem_drv.h>
#include <mtkcam/drv/isp_drv.h>
#include <mtkcam/drv_common/isp_reg.h>
#include <mtkcam/IImageBuffer.h>
#include <utils/StrongPointer.h>
#include <mtkcam/utils/common.h>
#include <mtkcam/utils/ImageBufferHeap.h>
using namespace android;
using namespace NSCam;
using namespace NSIoPipe;
using namespace NSPostProc;
/*************************************************************************************
* Log Utility
*************************************************************************************/
#ifndef USING_MTK_LDVT // Not using LDVT.
#define DBG_LOG_TAG ""
#else
#define DBG_LOG_TAG LOG_TAG
#endif
#include <imageio_log.h> // Note: DBG_LOG_TAG/LEVEL will be used in header file, so header must be included after definition.
DECLARE_DBG_LOG_VARIABLE(P2PipeWrapper);
// Clear previous define, use our own define.
#undef LOG_VRB
#undef LOG_DBG
#undef LOG_INF
#undef LOG_WRN
#undef LOG_ERR
#undef LOG_AST
#define LOG_VRB(fmt, arg...) do { if (P2PipeWrapper_DbgLogEnable_VERBOSE) { BASE_LOG_VRB(fmt, ##arg); } } while(0)
#define LOG_DBG(fmt, arg...) do { if (P2PipeWrapper_DbgLogEnable_DEBUG ) { BASE_LOG_DBG(fmt, ##arg); } } while(0)
#define LOG_INF(fmt, arg...) do { if (P2PipeWrapper_DbgLogEnable_INFO ) { BASE_LOG_INF(fmt, ##arg); } } while(0)
#define LOG_WRN(fmt, arg...) do { if (P2PipeWrapper_DbgLogEnable_WARN ) { BASE_LOG_WRN(fmt, ##arg); } } while(0)
#define LOG_ERR(fmt, arg...) do { if (P2PipeWrapper_DbgLogEnable_ERROR ) { BASE_LOG_ERR(fmt, ##arg); } } while(0)
#define LOG_AST(cond, fmt, arg...) do { if (P2PipeWrapper_DbgLogEnable_ASSERT ) { BASE_LOG_AST(cond, fmt, ##arg); } } while(0)
#define FUNCTION_LOG_START LOG_INF("+");
#define FUNCTION_LOG_END LOG_INF("-");
#define ERROR_LOG LOG_ERR("Error");
static const PortID IMGI( NSIoPipe::EPortType_Memory, NSImageio::NSIspio::EPortIndex_IMGI, 0);
static const PortID DISPO( NSIoPipe::EPortType_Memory, NSImageio::NSIspio::EPortIndex_DISPO, 1);
static const PortID VIDO( NSIoPipe::EPortType_Memory, NSImageio::NSIspio::EPortIndex_VIDO, 1);
///////////////////////////////////////////////
//test cases
int pass2_BasicTest(int casenum);
/******************************************************************************
* save the buffer to the file
*******************************************************************************/
static bool
saveBufToFile(char const*const fname, MUINT8 *const buf, MUINT32 const size)
{
int nw, cnt = 0;
uint32_t written = 0;
LOG_INF("(name, buf, size) = (%s, %x, %d)", fname, buf, size);
LOG_INF("opening file [%s]\n", fname);
int fd = ::open(fname, O_RDWR | O_CREAT, S_IRWXU);
if (fd < 0) {
LOG_ERR("failed to create file [%s]: %s", fname, ::strerror(errno));
return false;
}
LOG_INF("writing %d bytes to file [%s]\n", size, fname);
while (written < size) {
nw = ::write(fd,
buf + written,
size - written);
if (nw < 0) {
LOG_ERR("failed to write to file [%s]: %s", fname, ::strerror(errno));
break;
}
written += nw;
cnt++;
}
LOG_INF("done writing %d bytes to file [%s] in %d passes\n", size, fname, cnt);
::close(fd);
return true;
}
/*******************************************************************************
* Postproc 1 IN / 2 Out
********************************************************************************/
int main_testNormalStream(int testcaseType,int testcaseNum)
{
LOG_INF("+");
int ret=0;
switch(testcaseType)
{
case 1:
ret=pass2_BasicTest(testcaseNum);
break;
case 2:
break;
default:
break;
}
return ret;
}
#include "pic/imgi_1280x720_bayer10.h"
/*******************************************************************************
* case1: single in(640x480 bayer10) / single out(dispo_640x480, yv12)
* case2: single in(640x480 bayer10) / two out(dispo_480x360, yuy2/vido_640x480, yv12)
********************************************************************************/
int pass2_BasicTest(int casenum)
{
int ret=0;
//objects
NSCam::NSIoPipe::NSPostProc::INormalStream* pStream = NSCam::NSIoPipe::NSPostProc::INormalStream::createInstance(LOG_TAG,
NSCam::NSIoPipe::NSPostProc::ENormalStreamTag_Stream,0,NSCam::NSIoPipe::NSPostProc::eScenarioFormat_RAW);
pStream->init();
IMemDrv* mpImemDrv=NULL;
mpImemDrv=IMemDrv::createInstance();
mpImemDrv->init();
IspDrv* mpIspDrv=NULL;
mpIspDrv=IspDrv::createInstance();
mpIspDrv->init();
QParams enqueParams;
enqueParams.mpPrivaData = NULL;
enqueParams.mFrameNo = 0;
///////
//create input
IMEM_BUF_INFO imgiBuf;
imgiBuf.size=sizeof(g_imgi_array_1280x720_b10);
mpImemDrv->allocVirtBuf(&imgiBuf);
memcpy( (MUINT8*)(imgiBuf.virtAddr), (MUINT8*)(g_imgi_array_1280x720_b10), imgiBuf.size);
//imem buffer 2 image heap
MUINT32 bufStridesInBytes[3] = {1600, 0, 0};
MINT32 bufBoundaryInBytes[3] = {0, 0, 0};
PortBufInfo_v1 portBufInfo = PortBufInfo_v1( imgiBuf.memID,imgiBuf.virtAddr,0,imgiBuf.bufSecu, imgiBuf.bufCohe);
IImageBufferAllocator::ImgParam imgParam = IImageBufferAllocator::ImgParam((eImgFmt_BAYER10),
MSize(1280, 720), bufStridesInBytes, bufBoundaryInBytes, 1);
sp<ImageBufferHeap> pHeap = ImageBufferHeap::create( LOG_TAG, imgParam,portBufInfo,true);
IImageBuffer* tempBuffer = pHeap->createImageBuffer();
tempBuffer->incStrong(tempBuffer);
tempBuffer->lockBuf(LOG_TAG,eBUFFER_USAGE_HW_CAMERA_READWRITE | eBUFFER_USAGE_SW_READ_OFTEN);
//
Input src;
src.mPortID=IMGI;
src.mBuffer=tempBuffer;
enqueParams.mvIn.push_back(src);
//crop
MCrpRsInfo crop;
crop.mGroupID=1;
crop.mCropRect.p_fractional.x=0;
crop.mCropRect.p_fractional.y=0;
crop.mCropRect.p_integral.x=0;
crop.mCropRect.p_integral.y=0;
crop.mCropRect.s.w=1280;
crop.mCropRect.s.h=720;
crop.mResizeDst.w=1280;
crop.mResizeDst.w=720;
if(casenum==1)
{}
else if(casenum==2)
{
crop.mCropRect.s.w=1000;
crop.mCropRect.s.h=600;
crop.mResizeDst.w=1000;
crop.mResizeDst.w=600;
}
enqueParams.mvCropRsInfo.push_back(crop);
/////////
//output buffer
IMEM_BUF_INFO wdmaoBuf;
IMEM_BUF_INFO wrotoBuf;
if(casenum==1)
{
wdmaoBuf.size=1280*720*2;
mpImemDrv->allocVirtBuf(&wdmaoBuf);
memset((MUINT8*)wdmaoBuf.virtAddr, 0x0, wdmaoBuf.size);
MUINT32 bufStridesInBytes_2[3] = {1280, 640, 640};
PortBufInfo_v1 portBufInfo_2 = PortBufInfo_v1( wdmaoBuf.memID,wdmaoBuf.virtAddr,0,wdmaoBuf.bufSecu, wdmaoBuf.bufCohe);
IImageBufferAllocator::ImgParam imgParam_2 = IImageBufferAllocator::ImgParam((eImgFmt_YV12),
MSize(1280, 720), bufStridesInBytes_2, bufBoundaryInBytes, 3);
sp<ImageBufferHeap> pHeap_2 = ImageBufferHeap::create( LOG_TAG, imgParam_2,portBufInfo_2,true);
IImageBuffer* outBuffer = pHeap_2->createImageBuffer();
outBuffer->incStrong(outBuffer);
outBuffer->lockBuf(LOG_TAG,eBUFFER_USAGE_HW_CAMERA_READWRITE | eBUFFER_USAGE_SW_READ_OFTEN);
Output dst;
dst.mPortID=DISPO;
dst.mBuffer=outBuffer;
enqueParams.mvOut.push_back(dst);
}
else if(casenum==2)
{
wdmaoBuf.size=640*480*2;
mpImemDrv->allocVirtBuf(&wdmaoBuf);
memset((MUINT8*)wdmaoBuf.virtAddr, 0x0, wdmaoBuf.size);
MUINT32 bufStridesInBytes_2[3] = {1280, 0, 0};
PortBufInfo_v1 portBufInfo_2 = PortBufInfo_v1( wdmaoBuf.memID,wdmaoBuf.virtAddr,0,wdmaoBuf.bufSecu, wdmaoBuf.bufCohe);
IImageBufferAllocator::ImgParam imgParam_2 = IImageBufferAllocator::ImgParam((eImgFmt_YUY2),
MSize(640, 480), bufStridesInBytes_2, bufBoundaryInBytes, 1);
sp<ImageBufferHeap> pHeap_2 = ImageBufferHeap::create( LOG_TAG, imgParam_2,portBufInfo_2,true);
IImageBuffer* outBuffer = pHeap_2->createImageBuffer();
outBuffer->incStrong(outBuffer);
outBuffer->lockBuf(LOG_TAG,eBUFFER_USAGE_HW_CAMERA_READWRITE | eBUFFER_USAGE_SW_READ_OFTEN);
Output dst;
dst.mPortID=DISPO;
dst.mBuffer=outBuffer;
enqueParams.mvOut.push_back(dst);
//
wrotoBuf.size=1280*720*2;
mpImemDrv->allocVirtBuf(&wrotoBuf);
memset((MUINT8*)wrotoBuf.virtAddr, 0x0, wrotoBuf.size);
MUINT32 bufStridesInBytes_3[3] = {1280, 640, 640};
PortBufInfo_v1 portBufInfo_3 = PortBufInfo_v1( wrotoBuf.memID,wrotoBuf.virtAddr,0,wrotoBuf.bufSecu, wrotoBuf.bufCohe);
IImageBufferAllocator::ImgParam imgParam_3 = IImageBufferAllocator::ImgParam((eImgFmt_YV12),
MSize(1280, 720), bufStridesInBytes_3, bufBoundaryInBytes, 3);
sp<ImageBufferHeap> pHeap_3 = ImageBufferHeap::create( LOG_TAG, imgParam_3,portBufInfo_3,true);
IImageBuffer* outBuffer2 = pHeap_3->createImageBuffer();
outBuffer2->incStrong(outBuffer2);
outBuffer2->lockBuf(LOG_TAG,eBUFFER_USAGE_HW_CAMERA_READWRITE | eBUFFER_USAGE_SW_READ_OFTEN);
Output dst2;
dst2.mPortID=VIDO;
dst2.mBuffer=outBuffer2;
enqueParams.mvOut.push_back(dst2);
}
else if(casenum==3)
{
wdmaoBuf.size=640*480*2;
mpImemDrv->allocVirtBuf(&wdmaoBuf);
memset((MUINT8*)wdmaoBuf.virtAddr, 0x0, wdmaoBuf.size);
MUINT32 bufStridesInBytes_2[3] = {1280, 0, 0};
PortBufInfo_v1 portBufInfo_2 = PortBufInfo_v1( wdmaoBuf.memID,wdmaoBuf.virtAddr,0,wdmaoBuf.bufSecu, wdmaoBuf.bufCohe);
IImageBufferAllocator::ImgParam imgParam_2 = IImageBufferAllocator::ImgParam((eImgFmt_YUY2),
MSize(640, 480), bufStridesInBytes_2, bufBoundaryInBytes, 1);
sp<ImageBufferHeap> pHeap_2 = ImageBufferHeap::create( LOG_TAG, imgParam_2,portBufInfo_2,true);
IImageBuffer* outBuffer = pHeap_2->createImageBuffer();
outBuffer->incStrong(outBuffer);
outBuffer->lockBuf(LOG_TAG,eBUFFER_USAGE_HW_CAMERA_READWRITE | eBUFFER_USAGE_SW_READ_OFTEN);
Output dst;
dst.mPortID=DISPO;
dst.mBuffer=outBuffer;
enqueParams.mvOut.push_back(dst);
//
wrotoBuf.size=960*640*2;
mpImemDrv->allocVirtBuf(&wrotoBuf);
memset((MUINT8*)wrotoBuf.virtAddr, 0x0, wrotoBuf.size);
MUINT32 bufStridesInBytes_3[3] = {640, 320, 320};
PortBufInfo_v1 portBufInfo_3 = PortBufInfo_v1( wrotoBuf.memID,wrotoBuf.virtAddr,0,wrotoBuf.bufSecu, wrotoBuf.bufCohe);
IImageBufferAllocator::ImgParam imgParam_3 = IImageBufferAllocator::ImgParam((eImgFmt_YV12),
MSize(640, 960), bufStridesInBytes_3, bufBoundaryInBytes, 3);
sp<ImageBufferHeap> pHeap_3 = ImageBufferHeap::create( LOG_TAG, imgParam_3,portBufInfo_3,true);
IImageBuffer* outBuffer2 = pHeap_3->createImageBuffer();
outBuffer2->incStrong(outBuffer2);
outBuffer2->lockBuf(LOG_TAG,eBUFFER_USAGE_HW_CAMERA_READWRITE | eBUFFER_USAGE_SW_READ_OFTEN);
Output dst2;
dst2.mPortID=VIDO;
dst2.mBuffer=outBuffer2;
dst2.mTransform=eTransform_ROT_90;
enqueParams.mvOut.push_back(dst2);
}
/////
//temp to add, (original done in pass1)
MUINT32 reg_val=0x0;
ISP_IOCTL_WRITE_ENABLE_REG(mpIspDrv,mpIspDrv->getRegAddrMap(),CAM_CTL_SEL, 0);
ISP_IOCTL_WRITE_ENABLE_REG(mpIspDrv,mpIspDrv->getRegAddrMap(),CAM_CTL_EN1, 0x40000000);
reg_val = ISP_IOCTL_READ_REG(mpIspDrv,mpIspDrv->getRegAddrMap(),CAM_CTL_EN2);
ISP_IOCTL_WRITE_ENABLE_REG(mpIspDrv,mpIspDrv->getRegAddrMap(),CAM_CTL_EN2, reg_val&0x04000000);//FMT_EN don't touch
ISP_IOCTL_WRITE_ENABLE_REG(mpIspDrv,mpIspDrv->getRegAddrMap(),CAM_CTL_DMA_EN, 0);
//disable GGM
ISP_IOCTL_WRITE_ENABLE_REG(mpIspDrv,mpIspDrv->getRegAddrMap(),CAM_GGM_CTRL, 0);
//reset GDMA relative setting
ISP_IOCTL_WRITE_ENABLE_REG(mpIspDrv,mpIspDrv->getRegAddrMap(),CAM_CTL_SEL, 0);
/////
//enque
pStream->enque(enqueParams);
LOG_INF("ENQUE DONE");
////
//deque
QParams dequeParams;
pStream->deque(enqueParams);
LOG_INF("DEQUE DONE");
////
//dump pic to watch
if(casenum==1)
{
char filename[256];
sprintf(filename, "/data/basicP2_1_disp%dx%d.yuv", 1280,720);
saveBufToFile(filename, reinterpret_cast<MUINT8*>(wdmaoBuf.virtAddr), 1280 *720 * 2);
}
else if(casenum==2)
{
char filename[256];
sprintf(filename, "/data/basicP2_2_disp%dx%d.yuv", 640,480);
saveBufToFile(filename, reinterpret_cast<MUINT8*>(wdmaoBuf.virtAddr), 640 *480 * 2);
char filename2[256];
sprintf(filename2, "/data/basicP2_2_vido%dx%d.yuv", 1280,720);
saveBufToFile(filename2, reinterpret_cast<MUINT8*>(wrotoBuf.virtAddr), 1280 *720 * 2);
}
else if(casenum==3)
{
char filename[256];
sprintf(filename, "/data/basicP2_3_disp%dx%d.yuv", 640,480);
saveBufToFile(filename, reinterpret_cast<MUINT8*>(wdmaoBuf.virtAddr), 640 *480 * 2);
char filename2[256];
sprintf(filename2, "/data/basicP2_3_vido%dx%d.yuv", 640,960);
saveBufToFile(filename2, reinterpret_cast<MUINT8*>(wrotoBuf.virtAddr), 640 *960 * 2);
}
////
//
pStream->uninit();
pStream->destroyInstance(LOG_TAG);
mpImemDrv->uninit();
mpImemDrv->destroyInstance();
mpIspDrv->uninit();
mpIspDrv->destroyInstance();
return ret;
}
|
f3486a846e40c1f592d22b2ca957d28cd0b87cef | 7350aeb811d8b4c06fe7da302ab54dfb34ff4f0b | /tests/Constexpr - Bulat Khabirov/005.cpp | a9a91f0b2985b0ef37856395f914a51f431c240c | [] | no_license | xiaobo996/test-driver-cpp | 369c4099b48d17b4e98e358706d0d0e4375b9a86 | e6c6a05f8b15f27d92b76d471a404e439caac9ef | refs/heads/master | 2022-01-04T20:48:49.170787 | 2019-04-28T12:58:31 | 2019-04-28T12:58:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 517 | cpp | 005.cpp | /**
@file 005.cpp
@brief Positive testing of constexpr constructor declarations.
@author Bulat Khabirov
*/
// A class with constexpr constructor and function
class Rectangle {
int h, w;
public:
// A constexpr constructor
constexpr Rectangle (int h, int w) : h(h), w(w) {}
constexpr int getArea () { return h * w; }
};
// driver program to test function
int main() {
constexpr Rectangle rect(10, 20);
int rectArea = rect.getArea();
assert(rectArea == 10*20);
return 0;
}
|
63d7683d76584ceda16f2252e454efd64da63bdb | 30b7ffd17845db982883a91ce8d04551281658c4 | /Toph/NHSPC 2020/Preli/C.cpp | 7cc3a54adb4dc25729e6847770c3254b5c5f3610 | [] | no_license | shas9/codehub | 95418765b602b52edb0d48a473ad7e7a798f76e5 | bda856bf6ca0f3a1d59980895cfab82f690c75a2 | refs/heads/master | 2023-06-21T01:09:34.275708 | 2021-07-26T14:54:03 | 2021-07-26T14:54:03 | 389,404,954 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,150 | cpp | C.cpp | // God put a smile upon your face <3
#include <bits/stdc++.h>`
#define slld(longvalue) scanf("%lld", &longvalue)
#define ll long long
#define ull unsigned long long
#define pll pair < long long, long long >
#define fastio ios_base:: sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define pb push_back
#define bug printf("BUG\n")
#define mxlld LLONG_MAX
#define mnlld -LLONG_MAX
#define mxd 2e8
#define mnd -2e8
using namespace std;
bool check(ll n, ll pos)
{
return n & (1LL << pos);
}
ll Set(ll n, ll pos)
{
return n = n | (1LL << pos);
}
int main()
{
ll i, j, k, l, m, n, o, r, q;
ll testcase;
ll input, flag, tag, ans;
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
slld(testcase);
for(ll cs = 1; cs <= testcase; cs++)
{
ll xt, yt, x0, y0, k;
cin >> xt >> yt >> x0 >> y0 >> k;
double pi = acos(-1.0);
double diffangle = (2 * pi) / k;
double r = sqrt((xt - x0) * (xt - x0) + (yt - y0) * (yt - y0));
double thita;
if(xt == x0 && yt == y0)
{
for(ll i = 1; i < k; i++)
{
printf("%lld %lld\n", x0, y0);
}
continue;
}
assert(r > 0);
if(x0 == xt) thita = pi / 2;
else thita = atan((double)(y0 - yt) / (double)(x0 - xt));
thita = abs(thita);
// cout << thita * (180 / pi) << endl;
if((x0 - xt) == 0 && (y0 - yt) == 0) assert(0);
else if((x0 - xt) == 0 && (y0 - yt) < 0) thita = pi + (pi / 2);
else if((y0 - yt) == 0 && (x0 - xt) < 0) thita = pi;
else if((y0 - yt) && (x0 -xt))
{
if((x0 - xt) < 0 && (y0 - yt) < 0) thita += pi;
else if((x0 - xt) < 0) thita = pi - thita;
else if((y0 - yt) < 0) thita = (2 * pi) -thita;
}
// cout << thita *(180 / pi) << endl;
for(ll i = 1; i < k; i++)
{
thita += diffangle;
double x = xt + r * cos(thita);
double y = yt + r * sin(thita);
printf("%.10f %.10f\n", x, y);
}
}
}
|
b6364309a8c909910caf82d8cd8cacc39205f1dd | a025db4c38e5a1bfc58fc6a81c33e5ab992a89fa | /src/Handler.cpp | 01b2fce1525e7b009d799437074bd91f0f5d0509 | [] | no_license | miner34006/smo_c_version | 05a70b7374d1a8d5ddca4ef75255df001437150d | b3d59622174ba7d203623da1fd4f586e8e140384 | refs/heads/master | 2020-04-02T07:21:01.655273 | 2018-12-03T13:12:19 | 2018-12-03T13:12:19 | 154,192,097 | 2 | 3 | null | 2018-11-23T20:11:23 | 2018-10-22T18:08:58 | C++ | UTF-8 | C++ | false | false | 1,190 | cpp | Handler.cpp | //
// Created by Богдан Полянок on 21.09.2018.
//
#include "../headers/Handler.hpp"
Handler::Handler(const double &intensity, const std::shared_ptr<TimeBehaviour> &timeBehaviour):
finishTime_(0),
intensity_(intensity),
timeBehaviour_(timeBehaviour)
{
if (intensity < 0) {
throw std::invalid_argument("Invalid intensity (it must be more than 0)");
}
if (!timeBehaviour) {
throw std::invalid_argument("Invalid timeBehaviour ptr");
}
}
double Handler::getFinishTime() const noexcept
{
return finishTime_;
}
void Handler::setIntensity(const double &intensity)
{
if (intensity < 0) {
throw std::invalid_argument("Invalid intensity (it must be more than 0)");
}
intensity_ = intensity;
}
void Handler::cleanUp() noexcept
{
finishTime_ = 0;
}
double Handler::handleApplication(const double &arrivalTime)
{
if (arrivalTime < 0) {
throw std::invalid_argument("Invalid arrivalTime (it must be more than 0)");
}
const double workingTime = timeBehaviour_->generateTime(intensity_);
finishTime_ = arrivalTime + workingTime;
return workingTime;
}
bool Handler::isWorking(const double &timeNow) {
return timeNow < getFinishTime();
}
|
3f2a1443e48890d76b0d7852913863557d8da034 | 5277208a0af92b1a61f112dd87018a03e848f392 | /include/FeLibs.h | 0feae9576487864affd51fbf766c91330d0e15e8 | [] | no_license | feliksh/CV_18-19 | 54e7ec4761b56854cd4436941302ac66c5ccf887 | a5a5cc46d8ebd9e1bf261b9a577c2dc974e77d8d | refs/heads/main | 2023-05-14T05:02:11.285204 | 2023-04-30T15:52:23 | 2023-04-30T15:52:23 | 335,088,300 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,997 | h | FeLibs.h | #ifndef FELIBS_H
#define FELIBS_H
#include <iostream>
#include <fstream>
#include <sstream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
// calculate otsu threshold for given image with 'levels' range of pixel values
int otsu_threshold(cv::Mat image, int levels) {
// Calculate histogram frequencies
std::vector<float> nk(levels); // frequencies
float total = image.rows * image.cols; // total number of pixels
float m_G = 0; // global mean
// scan every pixel and count occurrences of intensity levels
if(image.isContinuous()){ // if image is continuous
unsigned char* ptr = image.ptr(0);
unsigned char* end = ptr + (image.rows * image.cols);
while( ptr < end ){
nk[*ptr]++;
ptr++;
}
}
else{ // if image is not continuous
for(int j=0; j<image.rows; ++j){
unsigned char* ptr = image.ptr(j);
unsigned char* end = ptr + image.cols;
while( ptr < end ){
nk[*ptr]++;
ptr++;
}
}
}
// Normalize histogram and calculate global mean (m_G)
for(int i=0; i<levels; ++i){
nk[i] = nk[i] / total;
m_G += i * nk[i];
}
// Find the otsu threshold based on between variance for growing Ts
float P1_T = 0; // cumulative sum calculated on the run
float m_T = 0; // cumulative mean calculated on the run
float between = 0; // between variance
float maximum = 0; // max between-variance found so far
int otsu_level = 0; // level of max between-variance found so far
// for all possible thresholds T=i
for(int i=0; i<levels; ++i)
{
P1_T += nk[i]; // update cumulative sum for all Ts up to i
m_T += i * nk[i]; // update cumulative mean for all Ts up to i
// calculate between variance of threshold T=i
between = ( ((m_G*P1_T) - m_T)*((m_G*P1_T) - m_T) ) / ( P1_T*(1-P1_T) );
// if it is greater than previous max, then save actual level i
if( between > maximum ){
maximum = between;
otsu_level = i;
}
}
nk.clear();
return otsu_level;
}
// improved by receiving in input a pointer in which result is placed
// transform image in a black-white image based on threshold
void apply_threshold_gray(cv::Mat* input, int threshold){
// scan every pixel and assign 0 or 255 intensity based on threshold
if(input->isContinuous()){ // if image is continuous
unsigned char* ptr = input->ptr(0);
unsigned char* end = ptr + (input->rows * input->cols);
while( ptr < end ){
if(*ptr < threshold)
*ptr = 0;
else
*ptr = 255;
ptr++;
}
}
else{ // if image is not continuous
for(int j=0; j<input->rows; ++j){
unsigned char* ptr = input->ptr(j);
unsigned char* end = ptr + input->cols;
//unsigned char* outputPtr = output.ptr(j);
while( ptr < end ){
if(*ptr < threshold)
*ptr = 0;
else
*ptr = 255;
ptr++;
}
}
}
}
// merge input_a and input_b based on threshold_image(black-white)
cv::Mat merge_on_threshold(cv::Mat input_a, cv::Mat input_b, cv::Mat thresholded_image){
cv::Mat output(thresholded_image.size(), CV_8UC1); // same dimension
// scan every pixel and count occurrences of intensity
if(thresholded_image.isContinuous()){ // if image is continuous
unsigned char* thr_ptr = thresholded_image.ptr(0);
unsigned char* end = thr_ptr + (thresholded_image.rows * thresholded_image.cols);
unsigned char* in_a = input_a.ptr(0);
unsigned char* in_b = input_b.ptr(0);
unsigned char* out = output.ptr(0);
while( thr_ptr < end ){
if(*thr_ptr == 0)
*out = *in_a;
else // *thr_ptr == 255
*out = *in_b;
thr_ptr++;
in_a++;
in_b++;
out++;
}
}
else{ // if image is not continuous
for(int j=0; j<thresholded_image.rows; ++j){
unsigned char* thr_ptr = thresholded_image.ptr(j);
unsigned char* end = thr_ptr + thresholded_image.cols;
unsigned char* in_a = input_a.ptr(j);
unsigned char* in_b = input_b.ptr(j);
unsigned char* out = output.ptr(j);
while( thr_ptr < end ){
if(*thr_ptr == 0)
*out = *in_a;
else // *thr_ptr == 255
*out = *in_b;
thr_ptr++;
in_a++;
in_b++;
out++;
}
}
}
return output;
}
// adds 'padding' pixels (set to 0) of padding around the image
cv::Mat add_padding(cv::Mat input, int padding){
cv::Mat output(input.rows+(2*padding), input.cols+(2*padding), input.type());
unsigned int k = 0;
unsigned char* in_ptr;
// add zeros padding at border
for(int j=0; j<output.rows; ++j){
unsigned char* out_ptr = output.ptr(j);
unsigned char* end = out_ptr + output.cols;
unsigned int i = 0;
if(j >= padding && j <= input.rows+padding){
in_ptr = input.ptr(k);
k++;
}
while( out_ptr < end ){
if(j < padding || i < padding || j >= input.rows+padding || i >= input.cols+padding) {
*out_ptr = 0;
}else {
*out_ptr = *in_ptr;
in_ptr++;
}
i++;
out_ptr++;
}
}
return output;
}
// for debugging: prints neighbor of a given point. used for debugging
void print_neighbor(cv::Mat input, int r, int c, int size){
for(int row=r-size; row<r+size+1; row++) {
for (int col=c-size; col<c+size+1; col++) {
if(row>=0 && col>=0 && row<input.rows && col<input.cols) {
unsigned char *ptr = input.ptr(row);
ptr += col;
std::cout << (*ptr == 255) << " ";
}
}
std::cout << std::endl;
}
}
/***
* searches for the first uppermost, leftmost white pixel not seen yet.
* starts searching from coordinates (x, y).
* when encountering a boundary already seen, skips white pixels until the next black one,
* after which, continues the search.
* @param input gray scale image
* @param history vector of boundary points already seen
* @param starting(x, y) coordinates at which the search should start
* @return first uppermost, leftmost boundary point
*/
cv::Point2i find_white(cv::Mat input, std::vector<cv::Point2i> history, cv::Point2i starting){
bool found = false; // found white pixel
bool seen = false; // found an already seen boundary white pixel
int row = starting.y; // starting row
cv::Point2i pt(0, 0);
// check all rows starting from j
while(row < input.rows && !found){
unsigned char* ptr = input.ptr(row);
unsigned char* end = ptr + input.cols;
ptr = ptr + starting.x; // moves to (x, y)
unsigned int col = starting.x;
while( ptr < end && !found){
if(*ptr == 255){ // found white pixel
pt = cv::Point2i(col, row);
// check that it is the first time we see that pixel
found = true;
for(int k=0; k < history.size() && found; k++) {
// in case it has been already seen set 'seen' = true
if (history[k].x == col && history[k].y == row) {
found = false;
seen = true;
starting.x = 0;
}
}
}
// in case we encountered a boundary pixel already seen, skip the following white pixels
if(seen){
while(ptr < end && *ptr == 255) {
ptr++;
col++;
}
seen = false;
}
else {
ptr++;
col++;
}
}
row++;
}
if(found) return pt;
else { // in case we are at the end of file return a point out of boundaries
pt = cv::Point2i(input.cols, input.rows);
return pt;
}
}
// calculates boundaries using Moore algorithm
std::vector<std::vector<cv::Point2i>> moore_boundary(cv::Mat input, int min_perimeter, int max_perimeter){
cv::Point2i c0, b0(0, 0);
int cd, rd;
int perimeter = 0;
bool clocked; // true when we make a complete clockwise spin (useful for single white pixels)
bool found; // true when we find the next boundary point
std::vector<cv::Point2i> points_seen; // takes track of current components boundary points
std::vector<cv::Point2i> history; // takes track of all boundary points
std::vector<std::vector<cv::Point2i>> big_regions; // takes track only of required length components
// stops when receive a point out of the image
while(b0.y < input.rows && b0.x < input.cols){
perimeter = 0;
// find next uppermost leftmost boundary point not seen yet
b0 = find_white(input, history, b0);
if(b0.y >= input.rows && b0.x >= input.cols) {
clocked = true;
history.clear();
return big_regions;
}
else {
points_seen.push_back(cv::Point2i(b0.x, b0.y));
}
cv::Point2i bi = b0;
cv::Point2i c1, old;
// xd, yd express shifting coordinates (from bi) in which we should search.
// they move in clockwise direction
cd = -1; // column displacement
rd = 0; // row displacement
c0.y = b0.y + rd;
c0.x = b0.x + cd; // west neighbor of b0
c1 = c0;
old = c0;
// follow boundary
do {
// check for a 255 in neighbours in clockwise direction
clocked = false;
found = false;
while (!clocked && !found) {
// first half of clock
while ((rd < 0 || (rd == 0 && cd == 1)) && !clocked && !found) {
if (input.at<unsigned char>(bi.y+rd, bi.x+cd) == 255) {
bi.x = bi.x+cd;
bi.y = bi.y+rd;
points_seen.push_back(cv::Point2i(bi.x, bi.y));
c0 = old;
cd = c0.x-bi.x;
rd = c0.y-bi.y;
found = true;
perimeter++;
} else {
old.x = bi.x+cd;
old.y = bi.y+rd;
if (cd < 1) ++cd;
else ++rd;
c1.x = bi.x+cd;
c1.y = bi.y+rd;
}
if (c0 == c1) clocked = true;
}
// second half of clock
while ((rd > 0 || (rd == 0 && cd == -1)) && !clocked && !found) {
if (input.at<unsigned char>(bi.y+rd, bi.x+cd) == 255) {
bi.x = bi.x+cd;
bi.y = bi.y+rd;
points_seen.push_back(cv::Point2i(bi.x, bi.y));
c0 = old;
cd = c0.x-bi.x;
rd = c0.y-bi.y;
found = true;
perimeter++;
} else {
old.x = bi.x+cd;
old.y = bi.y+rd;
if (cd > -1) --cd;
else --rd;
c1.x = bi.x+cd;
c1.y = bi.y+rd;
}
if (c0 == c1) clocked = true;
}
}
} while (bi != b0 && !clocked);
// save only those points with required length
if (perimeter >= min_perimeter && perimeter <= max_perimeter) {
//big_regions.push_back(points_seen.begin(), points_seen.end());
big_regions.push_back(points_seen);
}
history.insert(history.end(), points_seen.begin(), points_seen.end());
points_seen.clear();
}
//for(int k=0; k < big_regions.size(); k++) output.at<unsigned char>(big_regions[k].x, big_regions[k].y) = 255;
history.clear();
return big_regions;
}
std::vector<std::vector<cv::Point2i>> moore_boundary(cv::Mat input, int min_perimeter){
return moore_boundary(input, min_perimeter, (input.rows+input.cols)*2);
}
// fill internal holes with white
cv::Mat fill_holes(cv::Mat input){
cv::Mat im_floodfill = input.clone();
floodFill(im_floodfill, cv::Point(0,0), cv::Scalar(255));
// Invert floodfilled image
cv::Mat im_floodfill_inv;
bitwise_not(im_floodfill, im_floodfill_inv);
// Combine the two images to get the foreground.
cv::Mat output;
output = (input | im_floodfill_inv);
im_floodfill.release();
im_floodfill_inv.release();
return output;
}
// applies Hough Transform and returns (r, theta) for which H[r, theta] is max, twice
std::vector<cv::Point2d> apply_hough_transform(cv::Mat input){
int slices = 180;
std::vector<cv::Point2d> result;
cv::Mat space(1400, slices, input.type(), cv::Scalar(0,0,0));
int maxe = 0;
cv::Point2d max_point(0, 0);
cv::Point2d max2(0, 0);
int y = 0;
double slice=CV_PI/slices, r=0;
unsigned char* ptr, *end, *spacePtr;
for(int x=0; x<input.rows; ++x){
y = 0;
r = 0;
ptr = input.ptr(x);
end = ptr + input.cols;
spacePtr;
while( ptr < end ) {
if( *ptr == 255 ) {
for (int theta = 0; theta <= slices; ++theta) {
r = (x * cos(slice * theta)) + (y * sin(slice * theta));
spacePtr = space.ptr(cvRound(r) + 500);
spacePtr += theta;
*spacePtr += 1;
if( *spacePtr > maxe ) {
maxe = *spacePtr;
max_point.x = cvRound(r);
max_point.y = theta*slice;
}
}
}
ptr++;
y++;
}
}
maxe = 0;
for(int y=0; y<space.rows; ++y){
for(int x=0; x<space.cols; ++x) {
spacePtr = space.ptr(y, x);
if (*spacePtr > maxe) {
maxe = *spacePtr;
max2.x = max_point.x;
max2.y = max_point.y;
max_point.x = y - 500;
max_point.y = x * slice;
}
}
}
result.push_back(max_point);
result.push_back(max2);
space.release();
return result;
}
#endif //FELIBS_H |
164e9de582d19e48df0cea1b0217766d72f48fde | ee81fa71c6b8433c77bea83911fe336aabcfa75a | /src/bc/user/frontend_adapters/mmpayddddemousersvr/src/code/comm/mmpayddddemousersvr_itf_oss_define.h | cd98e9714f6b6c84927037f4c9b519d1584853b2 | [] | no_license | wunglee/DDD-Demo-for-C | ed47815ef814e97bc45058cf4fd374fe960db6e4 | 858d84624ec69b590400a25cc88247cc2f151015 | refs/heads/main | 2023-06-03T03:03:50.690428 | 2021-06-11T03:35:30 | 2021-06-11T03:35:30 | 368,185,428 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,807 | h | mmpayddddemousersvr_itf_oss_define.h | // 瓦特任务ID:f48cbd20-c43f-11eb-bc64-1d35e522ece7
// 瓦特任务版本:1
#pragma once
//接口耗时监控
namespace mmpayddddemousersvr {
namespace itf {
namespace oss {
enum mmpayddddemousersvritfOssDef {
OSS_ID_0 =
//// XWATT-TAG-BEGIN:[flow][mmpayddddemousersvr-itf-oss-define-h][OSS_ID_0] // NOLINT
0,
//// XWATT-TAG-END:[flow][mmpayddddemousersvr-itf-oss-define-h][OSS_ID_0] // NOLINT
};
};
}; // namespace itf
}; // namespace mmpayddddemousersvr
// AddUser接口耗时0-10(ms)
#define OSS_KEY_ITF_COST_ADDUSER_IN_MS_0_10 mmpayddddemousersvr::itf::oss::OSS_ID_0, 0
// AddUser接口耗时10-20(ms)
#define OSS_KEY_ITF_COST_ADDUSER_IN_MS_10_20 mmpayddddemousersvr::itf::oss::OSS_ID_0, 1
// AddUser接口耗时20-40(ms)
#define OSS_KEY_ITF_COST_ADDUSER_IN_MS_20_40 mmpayddddemousersvr::itf::oss::OSS_ID_0, 2
// AddUser接口耗时40-100(ms)
#define OSS_KEY_ITF_COST_ADDUSER_IN_MS_40_100 mmpayddddemousersvr::itf::oss::OSS_ID_0, 3
// AddUser接口耗时100-200(ms)
#define OSS_KEY_ITF_COST_ADDUSER_IN_MS_100_200 mmpayddddemousersvr::itf::oss::OSS_ID_0, 4
// AddUser接口耗时200-500(ms)
#define OSS_KEY_ITF_COST_ADDUSER_IN_MS_200_500 mmpayddddemousersvr::itf::oss::OSS_ID_0, 5
// AddUser接口耗时500-1000(ms)
#define OSS_KEY_ITF_COST_ADDUSER_IN_MS_500_1000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 6
// AddUser接口耗时1000-2000(ms)
#define OSS_KEY_ITF_COST_ADDUSER_IN_MS_1000_2000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 7
// AddUser接口耗时2000-3000(ms)
#define OSS_KEY_ITF_COST_ADDUSER_IN_MS_2000_3000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 8
// AddUser接口耗时3000-10000(ms)
#define OSS_KEY_ITF_COST_ADDUSER_IN_MS_3000_10000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 9
// AddUser接口耗时10000-1000000000(ms)
#define OSS_KEY_ITF_COST_ADDUSER_IN_MS_10000_1000000000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 10
// AddUser请求
#define OSS_KEY_ITF_REQ_ADDUSER mmpayddddemousersvr::itf::oss::OSS_ID_0, 11
// AddUser成功
#define OSS_KEY_ITF_REQ_ADDUSER_SUC mmpayddddemousersvr::itf::oss::OSS_ID_0, 12
// AddUser系统错误
#define OSS_KEY_ITF_REQ_ADDUSER_SYS_ERR mmpayddddemousersvr::itf::oss::OSS_ID_0, 13
// AddUser业务错误
#define OSS_KEY_ITF_REQ_ADDUSER_BIZ_ERR mmpayddddemousersvr::itf::oss::OSS_ID_0, 14
// FreezeUser接口耗时0-10(ms)
#define OSS_KEY_ITF_COST_FREEZEUSER_IN_MS_0_10 mmpayddddemousersvr::itf::oss::OSS_ID_0, 15
// FreezeUser接口耗时10-20(ms)
#define OSS_KEY_ITF_COST_FREEZEUSER_IN_MS_10_20 mmpayddddemousersvr::itf::oss::OSS_ID_0, 16
// FreezeUser接口耗时20-40(ms)
#define OSS_KEY_ITF_COST_FREEZEUSER_IN_MS_20_40 mmpayddddemousersvr::itf::oss::OSS_ID_0, 17
// FreezeUser接口耗时40-100(ms)
#define OSS_KEY_ITF_COST_FREEZEUSER_IN_MS_40_100 mmpayddddemousersvr::itf::oss::OSS_ID_0, 18
// FreezeUser接口耗时100-200(ms)
#define OSS_KEY_ITF_COST_FREEZEUSER_IN_MS_100_200 mmpayddddemousersvr::itf::oss::OSS_ID_0, 19
// FreezeUser接口耗时200-500(ms)
#define OSS_KEY_ITF_COST_FREEZEUSER_IN_MS_200_500 mmpayddddemousersvr::itf::oss::OSS_ID_0, 20
// FreezeUser接口耗时500-1000(ms)
#define OSS_KEY_ITF_COST_FREEZEUSER_IN_MS_500_1000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 21
// FreezeUser接口耗时1000-2000(ms)
#define OSS_KEY_ITF_COST_FREEZEUSER_IN_MS_1000_2000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 22
// FreezeUser接口耗时2000-3000(ms)
#define OSS_KEY_ITF_COST_FREEZEUSER_IN_MS_2000_3000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 23
// FreezeUser接口耗时3000-10000(ms)
#define OSS_KEY_ITF_COST_FREEZEUSER_IN_MS_3000_10000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 24
// FreezeUser接口耗时10000-1000000000(ms)
#define OSS_KEY_ITF_COST_FREEZEUSER_IN_MS_10000_1000000000 \
mmpayddddemousersvr::itf::oss::OSS_ID_0, 25
// FreezeUser请求
#define OSS_KEY_ITF_REQ_FREEZEUSER mmpayddddemousersvr::itf::oss::OSS_ID_0, 26
// FreezeUser成功
#define OSS_KEY_ITF_REQ_FREEZEUSER_SUC mmpayddddemousersvr::itf::oss::OSS_ID_0, 27
// FreezeUser系统错误
#define OSS_KEY_ITF_REQ_FREEZEUSER_SYS_ERR mmpayddddemousersvr::itf::oss::OSS_ID_0, 28
// FreezeUser业务错误
#define OSS_KEY_ITF_REQ_FREEZEUSER_BIZ_ERR mmpayddddemousersvr::itf::oss::OSS_ID_0, 29
// UnFreezeUser接口耗时0-10(ms)
#define OSS_KEY_ITF_COST_UNFREEZEUSER_IN_MS_0_10 mmpayddddemousersvr::itf::oss::OSS_ID_0, 30
// UnFreezeUser接口耗时10-20(ms)
#define OSS_KEY_ITF_COST_UNFREEZEUSER_IN_MS_10_20 mmpayddddemousersvr::itf::oss::OSS_ID_0, 31
// UnFreezeUser接口耗时20-40(ms)
#define OSS_KEY_ITF_COST_UNFREEZEUSER_IN_MS_20_40 mmpayddddemousersvr::itf::oss::OSS_ID_0, 32
// UnFreezeUser接口耗时40-100(ms)
#define OSS_KEY_ITF_COST_UNFREEZEUSER_IN_MS_40_100 mmpayddddemousersvr::itf::oss::OSS_ID_0, 33
// UnFreezeUser接口耗时100-200(ms)
#define OSS_KEY_ITF_COST_UNFREEZEUSER_IN_MS_100_200 mmpayddddemousersvr::itf::oss::OSS_ID_0, 34
// UnFreezeUser接口耗时200-500(ms)
#define OSS_KEY_ITF_COST_UNFREEZEUSER_IN_MS_200_500 mmpayddddemousersvr::itf::oss::OSS_ID_0, 35
// UnFreezeUser接口耗时500-1000(ms)
#define OSS_KEY_ITF_COST_UNFREEZEUSER_IN_MS_500_1000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 36
// UnFreezeUser接口耗时1000-2000(ms)
#define OSS_KEY_ITF_COST_UNFREEZEUSER_IN_MS_1000_2000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 37
// UnFreezeUser接口耗时2000-3000(ms)
#define OSS_KEY_ITF_COST_UNFREEZEUSER_IN_MS_2000_3000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 38
// UnFreezeUser接口耗时3000-10000(ms)
#define OSS_KEY_ITF_COST_UNFREEZEUSER_IN_MS_3000_10000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 39
// UnFreezeUser接口耗时10000-1000000000(ms)
#define OSS_KEY_ITF_COST_UNFREEZEUSER_IN_MS_10000_1000000000 \
mmpayddddemousersvr::itf::oss::OSS_ID_0, 40
// UnFreezeUser请求
#define OSS_KEY_ITF_REQ_UNFREEZEUSER mmpayddddemousersvr::itf::oss::OSS_ID_0, 41
// UnFreezeUser成功
#define OSS_KEY_ITF_REQ_UNFREEZEUSER_SUC mmpayddddemousersvr::itf::oss::OSS_ID_0, 42
// UnFreezeUser系统错误
#define OSS_KEY_ITF_REQ_UNFREEZEUSER_SYS_ERR mmpayddddemousersvr::itf::oss::OSS_ID_0, 43
// UnFreezeUser业务错误
#define OSS_KEY_ITF_REQ_UNFREEZEUSER_BIZ_ERR mmpayddddemousersvr::itf::oss::OSS_ID_0, 44
// IsFrozen接口耗时0-10(ms)
#define OSS_KEY_ITF_COST_ISFROZEN_IN_MS_0_10 mmpayddddemousersvr::itf::oss::OSS_ID_0, 45
// IsFrozen接口耗时10-20(ms)
#define OSS_KEY_ITF_COST_ISFROZEN_IN_MS_10_20 mmpayddddemousersvr::itf::oss::OSS_ID_0, 46
// IsFrozen接口耗时20-40(ms)
#define OSS_KEY_ITF_COST_ISFROZEN_IN_MS_20_40 mmpayddddemousersvr::itf::oss::OSS_ID_0, 47
// IsFrozen接口耗时40-100(ms)
#define OSS_KEY_ITF_COST_ISFROZEN_IN_MS_40_100 mmpayddddemousersvr::itf::oss::OSS_ID_0, 48
// IsFrozen接口耗时100-200(ms)
#define OSS_KEY_ITF_COST_ISFROZEN_IN_MS_100_200 mmpayddddemousersvr::itf::oss::OSS_ID_0, 49
// IsFrozen接口耗时200-500(ms)
#define OSS_KEY_ITF_COST_ISFROZEN_IN_MS_200_500 mmpayddddemousersvr::itf::oss::OSS_ID_0, 50
// IsFrozen接口耗时500-1000(ms)
#define OSS_KEY_ITF_COST_ISFROZEN_IN_MS_500_1000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 51
// IsFrozen接口耗时1000-2000(ms)
#define OSS_KEY_ITF_COST_ISFROZEN_IN_MS_1000_2000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 52
// IsFrozen接口耗时2000-3000(ms)
#define OSS_KEY_ITF_COST_ISFROZEN_IN_MS_2000_3000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 53
// IsFrozen接口耗时3000-10000(ms)
#define OSS_KEY_ITF_COST_ISFROZEN_IN_MS_3000_10000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 54
// IsFrozen接口耗时10000-1000000000(ms)
#define OSS_KEY_ITF_COST_ISFROZEN_IN_MS_10000_1000000000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 55
// IsFrozen请求
#define OSS_KEY_ITF_REQ_ISFROZEN mmpayddddemousersvr::itf::oss::OSS_ID_0, 56
// IsFrozen成功
#define OSS_KEY_ITF_REQ_ISFROZEN_SUC mmpayddddemousersvr::itf::oss::OSS_ID_0, 57
// IsFrozen系统错误
#define OSS_KEY_ITF_REQ_ISFROZEN_SYS_ERR mmpayddddemousersvr::itf::oss::OSS_ID_0, 58
// IsFrozen业务错误
#define OSS_KEY_ITF_REQ_ISFROZEN_BIZ_ERR mmpayddddemousersvr::itf::oss::OSS_ID_0, 59
// GetUser接口耗时0-10(ms)
#define OSS_KEY_ITF_COST_GETUSER_IN_MS_0_10 mmpayddddemousersvr::itf::oss::OSS_ID_0, 60
// GetUser接口耗时10-20(ms)
#define OSS_KEY_ITF_COST_GETUSER_IN_MS_10_20 mmpayddddemousersvr::itf::oss::OSS_ID_0, 61
// GetUser接口耗时20-40(ms)
#define OSS_KEY_ITF_COST_GETUSER_IN_MS_20_40 mmpayddddemousersvr::itf::oss::OSS_ID_0, 62
// GetUser接口耗时40-100(ms)
#define OSS_KEY_ITF_COST_GETUSER_IN_MS_40_100 mmpayddddemousersvr::itf::oss::OSS_ID_0, 63
// GetUser接口耗时100-200(ms)
#define OSS_KEY_ITF_COST_GETUSER_IN_MS_100_200 mmpayddddemousersvr::itf::oss::OSS_ID_0, 64
// GetUser接口耗时200-500(ms)
#define OSS_KEY_ITF_COST_GETUSER_IN_MS_200_500 mmpayddddemousersvr::itf::oss::OSS_ID_0, 65
// GetUser接口耗时500-1000(ms)
#define OSS_KEY_ITF_COST_GETUSER_IN_MS_500_1000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 66
// GetUser接口耗时1000-2000(ms)
#define OSS_KEY_ITF_COST_GETUSER_IN_MS_1000_2000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 67
// GetUser接口耗时2000-3000(ms)
#define OSS_KEY_ITF_COST_GETUSER_IN_MS_2000_3000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 68
// GetUser接口耗时3000-10000(ms)
#define OSS_KEY_ITF_COST_GETUSER_IN_MS_3000_10000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 69
// GetUser接口耗时10000-1000000000(ms)
#define OSS_KEY_ITF_COST_GETUSER_IN_MS_10000_1000000000 mmpayddddemousersvr::itf::oss::OSS_ID_0, 70
// GetUser请求
#define OSS_KEY_ITF_REQ_GETUSER mmpayddddemousersvr::itf::oss::OSS_ID_0, 71
// GetUser成功
#define OSS_KEY_ITF_REQ_GETUSER_SUC mmpayddddemousersvr::itf::oss::OSS_ID_0, 72
// GetUser系统错误
#define OSS_KEY_ITF_REQ_GETUSER_SYS_ERR mmpayddddemousersvr::itf::oss::OSS_ID_0, 73
// GetUser业务错误
#define OSS_KEY_ITF_REQ_GETUSER_BIZ_ERR mmpayddddemousersvr::itf::oss::OSS_ID_0, 74
|
29a37338cd6b9ca61953e04e8c17e6d8e0351d75 | b49aad7726a8a8c51fe06239ea80b575647b6e17 | /include/KvsD.hpp | d01af0b95acc415646c4064856f1f2df6f83ce77 | [
"MIT"
] | permissive | jackred/CW_3D | 832fb33fe2326b07d57d59b341e96539bd07c95e | 090d48e30e969155430efbfc7887e48f0ff383f9 | refs/heads/master | 2022-12-05T22:49:38.270882 | 2020-08-27T12:46:57 | 2020-08-27T12:46:57 | 224,392,510 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 651 | hpp | KvsD.hpp | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the MIT License.
* If a copy of the ML was not distributed with this
* file, You can obtain one at https://opensource.org/licenses/MIT */
#ifndef _KVSD_H_
#define _KVSD_H_
#include <vector>
#include "glm/glm.hpp"
namespace play {
struct Play {
std::vector<glm::vec3> pawns;
std::vector<glm::vec3> rocks;
std::vector<glm::vec3> bishops;
std::vector<glm::vec3> kings;
std::vector<glm::vec3> queens;
};
Play getPlay(int i);
}
#endif /* _KVSD_H_ */
|
5e7aa1ebd8c0e524cd1630cb220655b99d7c13a7 | 8afcd7010d2b7abbc9e9b4afc34eb258825fa6d9 | /BanDoc.h | 5f9635efead7ad5ec226778addeb4fb9d4165e86 | [] | no_license | CuongDeppTryy/Nguyen-Duc-Cuong | 7a29b3621a56b2b5c69e64e7a72392a15a9da94d | abd6536185b9b24a48d89e9853bdc40c72b517f4 | refs/heads/master | 2020-03-19T16:20:49.318089 | 2018-06-09T10:12:20 | 2018-06-09T10:12:20 | 136,711,976 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 705 | h | BanDoc.h | #pragma once
#include "Sach.h"
class BanDoc
{
protected:
string sMaBanDoc;
Date NgayDangKi;
string sHoTen, sKhoa;
int nType;
public:
virtual void output() = 0;
virtual void ghiThongTin() = 0;
BanDoc(string sMaBanDoc, Date NgayDangKi, string sHoTen, string sKhoa, int nType)
{
this->sMaBanDoc = sMaBanDoc;
this->NgayDangKi = NgayDangKi;
this->sHoTen = sHoTen;
this->sKhoa = sKhoa;
this->nType = nType;
}
int getType();
int getNgayDangKi();
int getThangDangKi();
int getNamDangKi();
void setKhoa(string sKhoa);
void setHoTen(string sHoTen);
void setMaBanDoc(string sMaBanDoc);
string getKhoa();
string getHoTen();
string getMaBanDoc();
void outputBanDoc();
~BanDoc(void){};
}; |
afb9d7a9cd5d76c9c96e5778c7c3ab4d5b8b866f | faea1cc0ac6036bca12dcc30d09caa37243e65b9 | /STUDY/0821_STL_main/0821_main.cpp | c783315221c3a3c46c84666a092ec1c8fe095223 | [] | no_license | SeungHoons/Study_Cpp | 211544793a5315fda7d2fec96af7b5f4e8edbd67 | b2aa0eb639096404a25ae575368806ace44a6226 | refs/heads/master | 2020-07-01T00:54:54.434782 | 2019-10-17T08:58:57 | 2019-10-17T08:58:57 | 201,000,715 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 566 | cpp | 0821_main.cpp | #include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
using namespace std;
int main()
{
map<int, int > m;
m[5] = 100;
m[3] = 100;
m[8] = 30;
m[4] = 40;
m[1] = 70;
m[7] = 100;
m[9] = 50;
for (auto iter = m.begin(); iter != m.end(); iter++)
{
cout << "(" << (*iter).first << ',' << (*iter).second << ")" << " ";
}
cout << endl;
m[5] = 200;
for (auto iter = m.begin(); iter != m.end(); iter++)
{
cout << "(" << iter->first << ',' << iter->second << ")" << " ";
}
cout << endl;
return 0;
} |
b88f7b31e891a1bf1db99587b0d3a5b6efc2af8d | 89f230e1b83b8ac043c7a045f1420f5095fa91d4 | /cpp/cpp11/enable_shared_from_this/main.cpp | 63b9e604a966dd54ebca63639297f0860d67ac6d | [] | no_license | walterzhaoJR/CodeLearning | f264ae6975034e0b68e68d7007853e45c10b78d3 | 8b7197f8e4cc035c7a85765969a9b04750489dac | refs/heads/master | 2022-07-17T06:37:48.904401 | 2022-05-24T11:58:52 | 2022-05-24T11:58:52 | 227,797,226 | 0 | 0 | null | 2021-11-05T16:53:39 | 2019-12-13T08:55:50 | Python | UTF-8 | C++ | false | false | 1,062 | cpp | main.cpp | #include <iostream>
#include <memory>
using namespace std;
#if 0
class Bad
{
public:
std::shared_ptr<Bad> GetPtr() {
// error 因为这样会造成2个非共享的share_ptr指向同一个对象,未增加引用计数导对象被析构两次
return std::shared_ptr<Bad>(this);
}
~Bad() {
cout << "~B call" << endl;
}
};
int main()
{
std::shared_ptr<Bad> bp1(new Bad);
std::shared_ptr<Bad> bp2 = bp1->GetPtr();
cout << "bp1 count:" << bp1.use_count() << endl;
cout << "bp2 count:" << bp2.use_count() << endl;
// Bad 对象会被析构两次,导致内存错误
return 0;
}
#endif
class Good : public enable_shared_from_this<Good>
{
public:
std::shared_ptr<Good> GetPtr() {
return shared_from_this();
}
~Good() {
cout << "~Good() call" << endl;
}
};
int main()
{
std::shared_ptr<Good> gp1(new Good);
std::shared_ptr<Good> gp2 = gp1->GetPtr();
cout << "gp1 count:" << gp1.use_count() << endl;
cout << "gp2 count:" << gp2.use_count() << endl;
}
|
9b80a329d3005b69d55745e3e65ae66a67a4030f | c8bb8f8b907984b35fd58a9354ce0cfb054b4a58 | /CPP_GeneticAlgorithm_Army/Cap_Speed.cpp | ea8283d3f5e60ec97a22346662744407a64740e9 | [] | no_license | mathieu-h/CPP_GeneticAlgorithm_Army | 91ec983e29b65e68247910d7fc53253821b34c59 | 589f64be193ef2326a0edac5a09eda0eb7a5069a | refs/heads/master | 2016-09-06T18:55:08.059722 | 2015-02-28T21:13:51 | 2015-02-28T21:13:51 | 30,802,360 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45 | cpp | Cap_Speed.cpp | #include "stdafx.h"
#include "Cap_Speed.h"
|
61ee48ec9b722f8825baa4cc91a5135d304cc5fa | 16590eb2191ff6c556cc436bd230be04940a7e87 | /physeqrowdlg.cpp | da641fbd875cfecf65844416ce867dcc02249306 | [] | no_license | caolandix/DarkSynthesis | 600076a6d2d0229a80824598e8c357dad582bdf5 | 192ff4ce2ec56ffc376eb66413d1898cd2a540c6 | refs/heads/master | 2021-06-24T08:22:38.745162 | 2021-01-01T10:43:51 | 2021-01-01T10:43:51 | 39,728,006 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 222 | cpp | physeqrowdlg.cpp | #include "physeqrowdlg.h"
#include "ui_physeqrowdlg.h"
PhysEqRowDlg::PhysEqRowDlg(QWidget *parent) : QDialog(parent), ui(new Ui::PhysEqRowDlg) {
ui ->setupUi(this);
}
PhysEqRowDlg::~PhysEqRowDlg() {
delete ui;
}
|
c7c9f49e0a4995335284476ff1008aeb4c003e0f | 411976b2ac11d2c418bd2ba3b9a8beba41ac717e | /ALPDataIO/src/ExampleReferencingType.cc | a1052f61e2817b517e9017a445559db4a371ce2d | [] | no_license | qianyunma2020/CEPCDataModel | 9d13fb19768cdb1f05e0962ff2ae4f28cb89dc0b | dd1e566fe91f44aaf0e35a4aa9f28a76371f1794 | refs/heads/main | 2022-12-30T08:28:35.759649 | 2020-10-20T07:35:46 | 2020-10-20T07:35:46 | 305,052,323 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,270 | cc | ExampleReferencingType.cc | // datamodel specific includes
#include "ALPDataIO/datamodel/ExampleReferencingType.h"
#include "ALPDataIO/datamodel/ExampleReferencingTypeConst.h"
#include "ALPDataIO/datamodel/ExampleReferencingTypeObj.h"
#include "ALPDataIO/datamodel/ExampleReferencingTypeData.h"
#include "ALPDataIO/datamodel/ExampleReferencingTypeCollection.h"
#include <iostream>
ExampleReferencingType::ExampleReferencingType() : m_obj(new ExampleReferencingTypeObj()){
m_obj->acquire();
}
ExampleReferencingType::ExampleReferencingType(const ExampleReferencingType& other) : m_obj(other.m_obj) {
m_obj->acquire();
}
ExampleReferencingType& ExampleReferencingType::operator=(const ExampleReferencingType& other) {
if ( m_obj != nullptr) m_obj->release();
m_obj = other.m_obj;
return *this;
}
ExampleReferencingType::ExampleReferencingType(ExampleReferencingTypeObj* obj) : m_obj(obj){
if(m_obj != nullptr)
m_obj->acquire();
}
ExampleReferencingType ExampleReferencingType::clone() const {
return {new ExampleReferencingTypeObj(*m_obj)};
}
ExampleReferencingType::~ExampleReferencingType(){
if ( m_obj != nullptr) m_obj->release();
}
ExampleReferencingType::operator ConstExampleReferencingType() const {return ConstExampleReferencingType(m_obj);}
std::vector<::ConstExampleCluster>::const_iterator ExampleReferencingType::Clusters_begin() const {
auto ret_value = m_obj->m_Clusters->begin();
std::advance(ret_value, m_obj->data.Clusters_begin);
return ret_value;
}
std::vector<::ConstExampleCluster>::const_iterator ExampleReferencingType::Clusters_end() const {
auto ret_value = m_obj->m_Clusters->begin();
std::advance(ret_value, m_obj->data.Clusters_end);
return ret_value;
}
void ExampleReferencingType::addClusters(::ConstExampleCluster component) {
m_obj->m_Clusters->push_back(component);
m_obj->data.Clusters_end++;
}
unsigned int ExampleReferencingType::Clusters_size() const {
return (m_obj->data.Clusters_end-m_obj->data.Clusters_begin);
}
::ConstExampleCluster ExampleReferencingType::Clusters(unsigned int index) const {
if (Clusters_size() > index) {
return m_obj->m_Clusters->at(m_obj->data.Clusters_begin+index);
}
else throw std::out_of_range ("index out of bounds for existing references");
}
std::vector<::ConstExampleReferencingType>::const_iterator ExampleReferencingType::Refs_begin() const {
auto ret_value = m_obj->m_Refs->begin();
std::advance(ret_value, m_obj->data.Refs_begin);
return ret_value;
}
std::vector<::ConstExampleReferencingType>::const_iterator ExampleReferencingType::Refs_end() const {
auto ret_value = m_obj->m_Refs->begin();
std::advance(ret_value, m_obj->data.Refs_end);
return ret_value;
}
void ExampleReferencingType::addRefs(::ConstExampleReferencingType component) {
m_obj->m_Refs->push_back(component);
m_obj->data.Refs_end++;
}
unsigned int ExampleReferencingType::Refs_size() const {
return (m_obj->data.Refs_end-m_obj->data.Refs_begin);
}
::ConstExampleReferencingType ExampleReferencingType::Refs(unsigned int index) const {
if (Refs_size() > index) {
return m_obj->m_Refs->at(m_obj->data.Refs_begin+index);
}
else throw std::out_of_range ("index out of bounds for existing references");
}
bool ExampleReferencingType::isAvailable() const {
if (m_obj != nullptr) {
return true;
}
return false;
}
const podio::ObjectID ExampleReferencingType::getObjectID() const {
if (m_obj !=nullptr){
return m_obj->id;
}
return podio::ObjectID{-2,-2};
}
bool ExampleReferencingType::operator==(const ConstExampleReferencingType& other) const {
return (m_obj==other.m_obj);
}
std::ostream& operator<<( std::ostream& o,const ConstExampleReferencingType& value ){
o << " id : " << value.id() << std::endl ;
o << " Clusters : " ;
for(unsigned i=0,N=value.Clusters_size(); i<N ; ++i)
o << value.Clusters(i) << " " ;
o << std::endl ;
o << " Refs : " ;
for(unsigned i=0,N=value.Refs_size(); i<N ; ++i)
o << value.Refs(i) << " " ;
o << std::endl ;
return o ;
}
//bool operator< (const ExampleReferencingType& p1, const ExampleReferencingType& p2 ) {
// if( p1.m_containerID == p2.m_containerID ) {
// return p1.m_index < p2.m_index;
// } else {
// return p1.m_containerID < p2.m_containerID;
// }
//}
|
d77d9d363a45b60e1df12e279ecf452828dd5242 | e6bff21e52fd28deca52e3773f3832f1993c5e9e | /Assignment-5 (OpenMP, MPI)/6_posix.cpp | 240081f42dd3e60d75b75152ebee7cb6657e4cea | [] | no_license | gargk747/CPP-Lab | af1674642f711c694ec41612b80581541ec64fbf | 3b8f7f5519014050919afadfd8228b465d622942 | refs/heads/main | 2023-02-28T13:55:33.334487 | 2021-02-07T20:33:20 | 2021-02-07T20:33:20 | 336,870,520 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,317 | cpp | 6_posix.cpp | #include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define SIZE_OF_DATASET 9 void* quickSort( void* data);
int partition( int* a, int, int);
struct info {
int start_index;
int* data_set;
int end_index;
};
int main(int argc, char **argv)
{
int a[] = { 27, 12, 1, -2,-8,2,4,11,0};
pthread_t thread_id;
struct info *info = (struct info*)malloc(sizeof(struct info));
info->data_set = a;
info->data_set=a; info->start_index = 0;
info->end_index = SIZE_OF_DATASET-1;
int i;
printf("\n\nunsorted array is: \n");
for(i = 0; i < SIZE_OF_DATASET; ++i)
printf(" %d ", info->data_set[i]); printf("\n");
if (pthread_create(&thread_id, NULL, quickSort, info))
{
fprintf(stderr, "No threads for you.\n");
return 1;
}
pthread_join(thread_id, NULL);
printf("\n\nSorted array is: \n");
for(i = 0; i < SIZE_OF_DATASET; ++i)
printf(" %d ", info->data_set[i]);
printf("\n");
free(info);
pthread_exit(NULL);
}
void* quickSort( void *data)
{
struct info *info = (struct info *)data;
int j,l,r;
l = info->start_index;
r = info->end_index;
pthread_t thread_id1;
pthread_t thread_id2;
if( l < r )
{
j = partition( info->data_set, l, r);
info->start_index=l;
info->end_index=j-1;
struct info * left_info = new struct info;
struct info * right_info = new struct info;
left_info->data_set = right_info->data_set = info->data_set;
left_info->start_index = l;
left_info->end_index = j-1;
right_info->start_index = j+1;
right_info->end_index = r;
if(info->end_index<0)info->end_index=0;
if (pthread_create(&thread_id1, NULL, quickSort, left_info)) {
fprintf(stderr, "No threads for you.\n");
return NULL;
}
if (pthread_create(&thread_id2, NULL, quickSort, right_info)) {
fprintf(stderr, "No threads for you.\n");
return NULL;
}
pthread_join(thread_id1, NULL); pthread_join(thread_id2, NULL);
delete left_info;
delete right_info;
}
return NULL;
}
int partition( int* a, int l, int r) {
int pivot, i, j, t;
pivot = a[l];
i = l;
j = r+1;
while( 1)
{
do ++i; while( a[i] <= pivot && i <= r );
do --j; while( a[j] > pivot );
if( i >= j ) break;
t = a[i];
a[i] = a[j];
a[j] = t;
}
t = a[l];
a[l] = a[j];
a[j] = t;
return j;
}
|
ab055b6245fcb015d9fd2111c9366eacc419bbf5 | 734882ee191fd388ee7c368c6dca2f72ec11d8a0 | /src/Gratrix.cpp | 5393c0b1810301d668a85061c287e5587b71fd78 | [
"MIT",
"BSD-3-Clause"
] | permissive | ALEVOLDON/vcv-gratrix | 312eb83fe5cc4552448d5c8162e7effc51378293 | 26edbd8d1852037f6fffec2c3290a884e049ff46 | refs/heads/master | 2021-08-19T16:37:20.576553 | 2017-11-27T00:00:16 | 2017-11-27T00:00:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,232 | cpp | Gratrix.cpp | #include "Gratrix.hpp"
Plugin *plugin;
void init(rack::Plugin *p) {
plugin = p;
p->slug = "Gratrix";
#ifdef VERSION
p->version = TOSTRING(VERSION);
#endif
p->website = "http://gratrix.net/vcvrack";
p->addModel(createModel<GTX::MIDI_C1::Widget> ("Gratrix", "MIDI-C1", "MIDI-C1", MIDI_TAG, EXTERNAL_TAG));
p->addModel(createModel<GTX::MIDI_G1::Widget> ("Gratrix", "MIDI-G1", "MIDI-G1", MIDI_TAG, EXTERNAL_TAG));
p->addModel(createModel<GTX::VCO_F1::Widget> ("Gratrix", "VCO-F1", "VCO-F1", OSCILLATOR_TAG));
p->addModel(createModel<GTX::VCO_F2::Widget> ("Gratrix", "VCO-F2", "VCO-F2", OSCILLATOR_TAG));
p->addModel(createModel<GTX::VCF_F1::Widget> ("Gratrix", "VCF-F1", "VCF-F1", FILTER_TAG));
p->addModel(createModel<GTX::VCA_F1::Widget> ("Gratrix", "VCA-F1", "VCA-F1", AMPLIFIER_TAG));
p->addModel(createModel<GTX::Env_F1::Widget> ("Gratrix", "Env-F1", "Env-F1", ENVELOPE_GENERATOR_TAG));
p->addModel(createModel<GTX::Chord_G1::Widget> ("Gratrix", "Chord-G1", "Chord-G1", SYNTH_VOICE_TAG)); // right tag?
p->addModel(createModel<GTX::Octave_G1::Widget>("Gratrix", "Octave-G1", "Octave-G1", SYNTH_VOICE_TAG)); // right tag?
p->addModel(createModel<GTX::Fade_G1::Widget> ("Gratrix", "Fade-G1", "Fade-G1", MIXER_TAG)); // right tag?
p->addModel(createModel<GTX::Fade_G2::Widget> ("Gratrix", "Fade-G2", "Fade-G2", MIXER_TAG)); // right tag?
p->addModel(createModel<GTX::Keys_G1::Widget> ("Gratrix", "Keys-G1", "Keys-G1", VISUAL_TAG));
p->addModel(createModel<GTX::VU_G1::Widget> ("Gratrix", "VU-G1", "VU-G1", VISUAL_TAG));
p->addModel(createModel<GTX::Scope_G1::Widget> ("Gratrix", "Scope-G1", "Scope-G1", VISUAL_TAG));
p->addModel(createModel<GTX::Blank_03::Widget> ("Gratrix", "Blank3", "Blank 3", BLANK_TAG));
p->addModel(createModel<GTX::Blank_06::Widget> ("Gratrix", "Blank6", "Blank 6", BLANK_TAG));
p->addModel(createModel<GTX::Blank_09::Widget> ("Gratrix", "Blank9", "Blank 9", BLANK_TAG));
p->addModel(createModel<GTX::Blank_12::Widget> ("Gratrix", "Blank12", "Blank 12", BLANK_TAG));
// p->addModel(createModel<MuxWidget> ("Gratrix", "Mux", "Mux", MIXER_TAG));
}
|
1db084c7fbba3be3ce38dcbb3285516ed8d0f7ff | 4fafcf80996f5c4ee283348ba56929328ab6ea33 | /subject/Exam_8_rotate_array.cpp | 76a3bfc174d9cac78ac6079380bd0bab84021473 | [
"MIT"
] | permissive | LoyalBenny/OfferCoding | e20022ca77c105d760ec22fb9540ccbf4a70866a | 38d2b1fc2ea3f1d0aff025cb8d038a8696cd567e | refs/heads/master | 2020-11-26T20:41:03.889508 | 2018-05-29T04:17:30 | 2018-05-29T04:17:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,586 | cpp | Exam_8_rotate_array.cpp | #include <iostream>
#include <vector>
using std::vector;
/**
* 思路
* 排序数组中找最小:优先考虑二分搜索,先找可以折半的判断条件:
* {3,4,5,1,2},中间值比左边界大,则最小值在右边,中间比左边界小,则最小值在左边
* 通过上面的思考可以细化思路:
* 中间值>=左边界,则left=mid,否则right=mid,终止条件是left+1>=right,此时返回right
* 正常情况下是left+1==right,只有一个元素时会left+1>right
* 特例:(1)输入数组大小为0 (2)旋转了0个元素,即全排序数组(3)在判断相等时跳过最小值,{1,0,1,1,1}
*/
class Solution
{
public:
int minNumberInRotateArray(vector<int> &rotateArray)
{
if (rotateArray.empty()) //空数组
return 0;
size_t left = 0, right = rotateArray.size() - 1;
if (rotateArray[left] < rotateArray[right]) //旋转0个元素
return rotateArray[left];
size_t mid;
while (left + 1 < right)
{
mid = (left + right) >> 1;
if (rotateArray[left] == rotateArray[mid] && rotateArray[mid] == rotateArray[right])
return FindMinInOrder(rotateArray, left, right);
if (rotateArray[mid] >= rotateArray[left])
left = mid;
else
right = mid;
}
return rotateArray[right];
}
//特例:在判断相等时跳过最小值;只能按顺序判断
int FindMinInOrder(vector<int> &rotateArray, int left, int right)
{
int nMin = rotateArray[left];
for (int i = left; i <= right; ++i)
if (nMin > rotateArray[i])
nMin = rotateArray[i];
return nMin;
}
};
int main(int argc, char *argv[])
{
Solution s;
vector<int> input1{3, 4, 5, 1, 2}; //1.旋转数组
std::cout << s.minNumberInRotateArray(input1) << std::endl;
vector<int> input2; //2.空数组
std::cout << s.minNumberInRotateArray(input2) << std::endl;
vector<int> input3{3, 3, 3, 1, 1, 1, 1, 1}; //3.旋转数组,有相等的值
std::cout << s.minNumberInRotateArray(input3) << std::endl;
vector<int> input4{1, 2, 3, 4, 5}; //4.旋转0个,全排序数组
std::cout << s.minNumberInRotateArray(input4) << std::endl;
vector<int> input5{2, 1, 2, 2, 2}; //5.在判断相等时跳过最小值
std::cout << s.minNumberInRotateArray(input5) << std::endl;
vector<int> input6{2}; //6.只有一个元素
std::cout << s.minNumberInRotateArray(input6) << std::endl;
return 0;
} |
c3eec0fabfa760d91749e6c77ba1c7270ffa4f11 | d9a50abfe2b0a1adf655048ddba8ef302d750d53 | /DERAS-Server/include/ieee_sep/long.h | 6e365011524fe288c707d4487a88ffa8c6464def | [
"BSD-2-Clause"
] | permissive | psu-powerlab/DERAS-Server | f7ed520ee6885a77ac5d3b2f672d8a6502004c97 | 5b41f35148aa1ff45c1f6b3a96f94ce443a72d0f | refs/heads/master | 2022-11-29T15:01:50.874535 | 2020-06-18T20:06:10 | 2020-06-18T20:06:10 | 261,805,865 | 0 | 0 | BSD-2-Clause | 2020-07-06T18:53:10 | 2020-05-06T15:44:56 | C++ | UTF-8 | C++ | false | false | 501 | h | long.h | ///////////////////////////////////////////////////////////
// long.h
// Implementation of the Class long
// Created on: 13-Apr-2020 2:51:34 PM
///////////////////////////////////////////////////////////
#if !defined(EA_63B17B42_F104_4584_95AF_A16A114AB5ED__INCLUDED_)
#define EA_63B17B42_F104_4584_95AF_A16A114AB5ED__INCLUDED_
#include "integer.h"
class long : public integer
{
public:
long();
virtual ~long();
};
#endif // !defined(EA_63B17B42_F104_4584_95AF_A16A114AB5ED__INCLUDED_)
|
cb03a3e7fde82627327acdd0b9dab10197595263 | 8f0d91d30bee9c1c770283ca81ed4042c0c40291 | /GameMap.h | dc15aa5da2c08e17cb1be034ffac443905e38161 | [
"BSD-3-Clause"
] | permissive | cnlohr/noeuclid | e5fbdd7d09c79c80c80be58dcd77a832d8b2ebf6 | b2ab61112bd96c90eb4b04aa0f953f7e875d4f3b | refs/heads/master | 2023-09-05T11:30:54.765212 | 2022-11-09T21:51:07 | 2022-11-09T21:51:07 | 24,822,460 | 608 | 54 | BSD-3-Clause | 2022-11-09T21:51:09 | 2014-10-05T18:15:31 | C | UTF-8 | C++ | false | false | 4,293 | h | GameMap.h | #ifndef GAMEMAP_H
#define GAMEMAP_H
//Define all lava/death blocks.
//If the user touches one, he dies.
#define MAX_DEATH_BLOCKS 8192
#define MAX_PICKABLES 256
#include <functional>
#include "scripthelpers.h"
using initfn = std::function<void()>;
using runfn = std::function<void(double timeIn, double deltaTime)>;
#include "Room.h"
#include "TCC.h"
#include <unordered_map>
extern TCC tcc;
class GameMap {
public:
int lastroom = -1, curroom = 0, startroom = 0;
DeathBlock DeathBlocks[MAX_DEATH_BLOCKS];
PickableBlock PBlocks[MAX_PICKABLES];
vector<Room> rooms;
void update();
void die();
void setRoom(int newroom, bool reset = false);
void collision(struct CollisionProbe * ddat);
#define DONE (i>>ws).eof()
/**
* A list of functions that return partially apply the utility functions
* removing their parameters so that they can then be run when a room is initialized or updated
* TODO code is hard to read
*/
unordered_map<string, std::function<initfn(istream&)>> initfuncs {
{"EmptyBox", [](istream& i) -> initfn {
Vec3i p,s; BlockType b; i>>p>>s>>b;
int density = DEFAULT_DENSITY; if(!DONE) i>>density;
return bind(EmptyBoxV, p, s, true, RGBA{1, DEFAULT_BRIGHT, byte(density), static_cast<byte>(b)});
}}, {"Cell", [](istream& i) -> initfn {
Vec3i p; BlockType b; i>>p>>b;
return bind(ChangeCellV, 0, p, RGBA{1, DEFAULT_BRIGHT, 255, static_cast<byte>(b)});
}}, {"ClearCell", [](istream& i) -> initfn {
Vec3i p; i>>p; //TODO merge with "Block"
return bind(ChangeCellV, 0, p, RGBA{0, DEFAULT_BRIGHT, 0, DEFAULT_EMPTY_BLOCK});
}}, {"ClearRange", [](istream& i) -> initfn {
Vec3i p,s; i>>p>>s;
return bind(ClearRangeV, p, s);
}}, {"PaintRange", [](istream& i) -> initfn {
Vec3i p,s; BlockType b; i>>p>>s>>b;
int density = DEFAULT_DENSITY; if(!DONE) i>>density;
return bind(PaintRangeV, p, s, RGBA{1,190,byte(density),static_cast<byte>(b)});
}}, {"Warp", [](istream& i) -> initfn {
Vec3i p,s; Vec3f x;
i>>p>>s>>x;
return bind(WarpSpaceV, p, s, x);
}}, {"JumpSection", [](istream& i) -> initfn {
Vec3i p,s; Vec3f ofs, f1 = {1,0,0},f2={0,1,0},f3={0,0,1};
i>>p>>s>>ofs;
if(!DONE) i>>f1>>f2>>f3;
return bind(JumpSpaceV, p, s, ofs, f1, f2, f3);
}}, {"RequireRoom", [this](istream& i) -> initfn {
int room; i>>room;
return [this,room]() { rooms[room].begin(); };
}}
};
unordered_map<string, function<runfn(istream&)>> runfuncs {
{"AnimateOpen", [](istream& i) -> runfn {
Vec3i p,s; i>>p>>s;
return [p,s](double timeIn, double deltaTime) {
int capden = 255 - timeIn * 200;
PaintRangeV(p, s, {1, 190, byte(capden<0?0:capden), GOAL_BLOCK});
};
}}, {"AnimateClose", [](istream& i) -> runfn {
Vec3i p,s; i>>p>>s;
return [p,s](double timeIn, double deltaTime) {
int capden = 255 - timeIn * 200;
PaintRangeV(p, s, {1,190,byte(capden<0?255:255-capden),DEADGOAL_BLOCK});
};
}}, {"DieInRange", [](istream& i) -> runfn {
Vec3f p,s; i>>p>>s;
return [p,s](double timeIn, double deltaTime) {
if (PlayerInRangeV(p,s)) ::die();
};
}}
};
unordered_map<string, int> aliases;
void AddDeathBlock(Vec3i p);
bool IsOnDeathBlock(Vec3i p);
//Returns id if pickable is there.
//Returns -1 if no block.
//Returns -2 if block tween incomplete.
int GetPickableAt(Vec3i p);
void DissolvePickable(int pid);
//If -1, no pickables left.
//If -2, Pickable already there.
//Otherwise returns which pickable!
//initial_density should be 0 unless you want to shorten (+) or lengthen (-) tween.
int PlacePickableAt(Vec3i p, float initial_density);
void ClearPickableBlocks();
//Redraw
void UpdatePickableBlocks();
void PickableClick(bool left, Vec3f p, float dist);
private:
void loadRooms(string fname);
};
#endif /* GAMEMAP_H */
|
c63fb5a075626c64fdfc30855ab01c62a2eb4d4f | c0af36cfeadc3e7b44c9d2778f93373ea733f4d3 | /OperateLayer.cpp | a8f22a03e9f717388f299975d664534540df2c87 | [] | no_license | fzh1635239282/MarioMake | 3f85437c535a9f4cef68fbb4100b6f8dcf0a6180 | 331df4b0bfcb78c47a7310671c68c9d42d387c88 | refs/heads/master | 2021-01-14T08:21:07.162713 | 2017-04-12T00:11:21 | 2017-04-12T00:11:21 | 81,944,356 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,023 | cpp | OperateLayer.cpp | #include "OperateLayer.h"
#include "StartScene.h"
bool OperateLayer::init() {
Size winSize = Director::getInstance()->getWinSize();
Button * buttonAtk = Button::create();
buttonAtk->loadTextures("atk.png", "");
buttonAtk->setPosition(Vec2(winSize.width * 5 / 8, winSize.height * 3 / 20));
buttonAtk->setTag(50);
this->addChild(buttonAtk);
Button * buttonJump = Button::create();
buttonJump->loadTextures("jump.png", "");
buttonJump->setPosition(Vec2(winSize.width * 7 / 8, winSize.height * 3 / 20));
buttonJump->setTag(51);
this->addChild(buttonJump);
buttonAtk->addTouchEventListener(CC_CALLBACK_2(OperateLayer::touchCallBack,
this));
buttonJump->addTouchEventListener(CC_CALLBACK_2(OperateLayer::touchCallBack,
this));
return true;
}
void OperateLayer::touchCallBack(Ref * sender, Widget::TouchEventType
controlEvent) {
if (controlEvent == Widget::TouchEventType::ENDED) {
auto button = static_cast<Button*>(sender);
if (button->getTag() == 51) {
}
}
} |
d4e0737b1e9bd42a222e1f0d428e393077db3b5f | ad90fd7724d8bf72f3e8b3d967799e317769430a | /HelloWorld/win32/myUnitHeader.cpp | fed42e3f441efe33c6df764a7f4e138727608d40 | [] | no_license | geniikw/myFirst2DGame | f71865ec8eabdff35c33b2a013b3afd1711b7776 | d9050e71913000e9147fa3f889d4b6c7c35fda94 | refs/heads/master | 2021-07-09T21:09:57.886694 | 2016-12-15T16:50:51 | 2016-12-15T16:50:51 | 19,765,521 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26 | cpp | myUnitHeader.cpp | #include"myUnitHeader.h"
|
285ee28e4bdf2f2f8c116f2d73d64838b7d5ff0d | 730f2be3bb19c88d615cafbb93a1ee4a7db42120 | /persistent_tests/binary_tree_test.h | 947c0c392fe6e5c5cf0d0aaa1482243eb73587c8 | [] | no_license | vp255/persistent | a9dd9614d186e6fc9e7e6f2a592f010b528a5be1 | 7550012bbe9991ef4081fd3475cd523064cb29c9 | refs/heads/master | 2022-12-04T13:28:30.237894 | 2020-08-24T12:56:16 | 2020-08-24T12:56:16 | 285,978,036 | 0 | 1 | null | 2020-08-18T20:29:40 | 2020-08-08T05:14:05 | C++ | UTF-8 | C++ | false | false | 780 | h | binary_tree_test.h | #ifndef BINARY_TREE_TEST_H
#define BINARY_TREE_TEST_H
#include <iostream>
#include "persistent/binary_tree.h"
namespace BinaryTreeTests {
template <template <class> class C, class A, template <class> class T>
C<A> InOrderTraversal(const T<A>& tree) {
C<A> result;
InOrderTraversal(tree, result);
return result;
}
template <template <class> class C, class A, template <class> class T>
void InOrderTraversal(const T<A>& tree, C<A>& result) {
// not yet implemented
}
void run() {
std::cout << "Running BinaryTree Tests ..." << std::endl;
// not yet implemented
auto cblt = Persistent::BinaryTree<int>();
auto cblt2 = Persistent::BinaryTree<int>(4, cblt, cblt);
std::cout << " Root: " << cblt2.root() << std::endl;
}
} // end of ListTests namespace
#endif
|
536c4dfe9ef28329a760d316e8d7e36b9cb63f4e | 7e0ea62e544f93860a1c9de4e76afb9519075322 | /Parcial 1/Zoologico_clases/librerias.h | 7cf05323eaf3ed2d7cf826216f0a550c1206ec11 | [] | no_license | RamsesGA/Programacion_2_2019b_Ramses_Guerrero_Ambriz | d3873437b05f2373ce7fd1f13e53c48c66970861 | 9a8e45b157f0ce107ce632be8517fe4f623bf625 | refs/heads/master | 2020-05-18T02:40:12.042971 | 2019-08-14T17:35:21 | 2019-08-14T17:35:21 | 184,123,197 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 302 | h | librerias.h | #pragma once
#include <iostream>
#include <string>
#include <vector>
//Clase padre
#include "Animales.h"
//Clases hija/madre
#include "Carnivoro.h"
#include "Herbivoro.h"
#include "Omnivoro.h"
//Clases hijas
#include "animalesCarnivoros.h"
#include "animalesHerbivoros.h"
#include "animalesOmnivoros.h" |
1235d393e61de804eaafc7af2c78674f011d417a | 615a5d468c940ac71a2dd4038c6fd18ea714fc7c | /ALGOs_and_STLs.cpp | e09ec947d6f3de92e719f2d78d3f7b1e77beb8a9 | [] | no_license | shumbul/Cryptographic-Algorithms | 07a6a54d529a3af43861f53c69759ebe5b05f3bb | 45be59727ccc3f3e46208abf6b4c1f151ca0e214 | refs/heads/main | 2023-04-18T16:22:55.265922 | 2021-05-01T08:23:49 | 2021-05-01T08:23:49 | 326,958,741 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,034 | cpp | ALGOs_and_STLs.cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define int long long
#define vi vector<int>
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define inar(arr,n) for(int i=0; i<n; i++) cin>>arr[i];
#define suma(arr,n) for(int i=0; i<n; i++) sum+=arr[i];
#define for0(i,n) for(int i=0; i<n; i++)
#define for1(i,n) for(int i=1; i<=n; i++)
#define forr(i,n) for(int i=n-1; i>=0; i--)
#define rof(i,a,b) for(int i=a;i<=b;i++)
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
#define fast ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0)
const int mod = 1e9 + 7;
ll gcd (ll a, ll b) {return ( a ? gcd(b % a, a) : b );}
ll power(ll a, ll n) {ll p = 1; while (n > 0) {if (n % 2) {p = p * a;} n >>= 1; a *= a;} return p;}
ll power(ll a, ll n, ll mod) {ll p = 1; while (n > 0) {if (n % 2) {p = p * a; p %= mod;} n >>= 1; a *= a; a %= mod;} return p % mod;}
vi primes;
bool prime[100001];
void ALGO_sieve;
void STL_multisets();
void SORT();
bool isSubSequence(string str1, string str2);
void sub_sequence();
void STL_nth_element();
bool comp(int a, int b);
void STL_partial_sort();
string to_upper(string str);
signed main() {
fast;
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
// ALGO_sieve();
// STL_multisets();
// SORT();
// sub_sequence();
// STL_nth_element();
// STL_partial_sort();
// cout << " Tranform to upper case: " << to_upper("HeyYYy") << "\n";
return 0;
}
void ALGO_sieve() {
memset(prime, true, sizeof prime);
int n = sizeof(prime) - 1;
for (int p = 2; p * p <= n ; p++) {
if (prime[p] == true) {
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
for (int p = 2; p <= n; p++)
if (prime[p])
primes.pb(p);
}
void STL_multisets() {
//DECLARE
multiset<int> mset;
//INSERT
mset.insert(10);
mset.insert(30);
mset.insert(50);
mset.insert(20);
mset.insert(30);
mset.insert(50);
//PRINT
cout << "Printing mset\n";
multiset<int>::iterator it;
for (it = mset.begin(); it != mset.end(); ++it) {
cout << *it << "\n";
}
//ASSIGN TO ANOTHER MULTISET
multiset<int, greater<int> > mset2(mset.begin(), mset.end());
cout << "Printing mset2\n";
for (it = mset2.begin(); it != mset2.end(); ++it) {
cout << *it << "\n";
}
//ERASE
// 1. removes elements from beginning till a given value is found
mset2.erase(mset2.begin(), mset2.find(30));
cout << "Printing mset2\n";
for (it = mset2.begin(); it != mset2.end(); ++it) {
cout << *it << "\n";
}
// 2. remove an element
mset2.erase(20);
cout << "Printing mset2\n";
for (it = mset2.begin(); it != mset2.end(); ++it) {
cout << *it << "\n";
}
// *NOTE* copies are also deleted by default
// otherwise mention this to delete single instance:
mset2.erase(mset2.find(30));
cout << "Printing mset2\n";
for (it = mset2.begin(); it != mset2.end(); ++it) {
cout << *it << "\n";
}
//COUNT
cout << "COUNT of 50 in mset is: \n" << mset.count(50) << "\n";
//LOWER AND UPPER BOUNDS
cout << "Printing mset\n";
for (it = mset.begin(); it != mset.end(); ++it) {
cout << *it << "\n";
}
cout << "MSET Lower bound for 40: \n" << *mset.lower_bound(40) << "\n";
cout << "MSET Lower bound for 50: \n" << *mset.lower_bound(50) << "\n";
cout << "MSET Lower bound for 10: \n" << *mset.lower_bound(10) << "\n";
cout << "MSET Lower bound for 30: \n" << *mset.lower_bound(30) << "\n";
cout << "MSET Lower bound for 0: \n" << *mset.lower_bound(0) << "\n";
cout << "MSET Lower bound for 70: \n" << *mset.lower_bound(70) << "\n";
cout << "MSET Upper bound for 40: \n" << *mset.upper_bound(40) << "\n";
cout << "MSET Upper bound for 50: \n" << *mset.upper_bound(50) << "\n";
cout << "MSET Upper bound for 10: \n" << *mset.upper_bound(10) << "\n";
cout << "MSET Upper bound for 30: \n" << *mset.upper_bound(30) << "\n";
cout << "MSET Upper bound for 0: \n" << *mset.upper_bound(0) << "\n";
cout << "MSET Upper bound for 70: \n" << *mset.upper_bound(70) << "\n";
}
struct compare {
inline bool operator() (const string &s1, const string &s2) const {
if (s1.length() == s2.length())
return s1 < s2;
return s1.length() > s2.length();
}
};
void SORT() {
vector<string> v;
v = {"ale", "apple", "monkey", "plea"};
// sort length wise and lexicographically smaller wise
compare c;
sort(v.begin(), v.end(), c);
for (auto s : v) {
cout << s << " ";
}
cout << '\n';
/*
ANOTHER SORT METHOD:
sort(inc.begin(), inc.end(), [](const auto & s1, const auto & s2) {
return s1.ss <= s2.ss;
});
*/
}
// Returns true if str1[] is a subsequence of str2[].
// m is length of str1 and n is length of str2
bool isSubSequence(string str1, string str2)
{
int m = str1.length(), n = str2.length();
int j = 0; // For index of str1 (or subsequence
// Traverse str2 and str1, and compare current
// character of str2 with first unmatched char
// of str1, if matched then move ahead in str1
for (int i = 0; i < n && j < m; i++)
if (str1[j] == str2[i])
j++;
// If all characters of str1 were found in str2
return (j == m);
}
void sub_sequence() {
cout << "Subsequence \n";
string s1, s2; cin >> s1 >> s2;
int b = isSubSequence(s1, s2) | isSubSequence(s2, s1);
if (b) {
cout << "yes\n";
}
else cout << "no\n";
}
void STL_nth_element() {
int N; cin >> N;
int n; cin >> n;
vector<int> vec(N);
for (int i = 0; i < N; i++) {
cin >> vec[i];
}
cout << " Find the kth element in a vector\n";
nth_element(vec.begin(), vec.begin() + n - 1, vec.end(), greater<int>());
cout << vec[n - 1] << "\n";
}
bool comp(int a, int b) {
return (a < b);
}
void STL_partial_sort() {
int N; cin >> N;
int n; cin >> n;
vector<int> vec(N);
for (int i = 0; i < N; i++) {
cin >> vec[i];
}
/*
Template
void partial_sort (RandomAccessIterator first, RandomAccessIterator middle,
RandomAccessIterator last);
OR
void partial_sort (RandomAccessIterator first, RandomAccessIterator middle,
RandomAccessIterator last, Compare comp);
*/
// sort n elements from somewhere in the middle
partial_sort(vec.begin() + 1, vec.begin() + n, vec.end());
for (int i = 0; i < N; i++)
cout << vec[i] << " ";
cout << "\n";
/*
5
3
10 5 5 7 2
=> 10 2 5 7 5
*/
partial_sort(vec.begin() + 1, vec.begin() + n, vec.end(), greater<int>());
for (int i = 0; i < N; i++)
cout << vec[i] << " ";
cout << "\n";
/*
5
3
10 5 5 7 2
=> 10 7 5 2 5
*/
// sort using comparator
partial_sort(vec.begin() + 1, vec.begin() + n, vec.end(), comp);
for (int i = 0; i < N; i++)
cout << vec[i] << " ";
cout << "\n";
/*
5
3
10 5 5 7 2
=> 10 2 5 7 5
*/
partial_sort(vec.begin() + 1, vec.begin() + n, vec.end(), [](const auto & s1, const auto & s2) {
return s1 > s2;
});
for (int i = 0; i < N; i++)
cout << vec[i] << " ";
cout << "\n";
/*
5
3
10 5 5 7 2
=> 10 7 5 2 5
*/
}
string to_upper(string str) {
//code
transform(str.begin(), str.end(), str.begin(), ::toupper);
return str;
} |
5bb20ca3e120126250d851d0ad850838d655a4a3 | 32e98e74c027f9cb533ef78afe1d824e65f8fda4 | /samples/utils/glfw_freecam.hpp | cb16aebf223d2877ef9158fc6d59474e4123490c | [
"MIT"
] | permissive | albedo-engine/3DEngine | bdfcf2300ee5ffa305a4ff1092ec7b8cfb2a003a | 8473120f2104257e640293949fe5a92cb1591372 | refs/heads/master | 2022-03-04T07:05:52.495616 | 2016-10-13T20:08:35 | 2016-10-13T20:08:35 | 52,114,699 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,231 | hpp | glfw_freecam.hpp | #pragma once
#include <iostream>
#include <engine.hpp>
#include <GLFW/glfw3.h>
using namespace Engine;
using namespace Engine::Scene;
static void freecam_key_dispatch(GLFWwindow* window, int key, int scancode, int action, int mods);
static void freecam_mouse_dispatch(GLFWwindow* window, double xpos, double ypos);
static void freecam_error_callback(int error, const char* description);
class GLFW_Freecam
{
public:
GLFW_Freecam(int width, int height, const char* title);
~GLFW_Freecam();
public:
void pre_update();
void post_update();
bool should_close();
void set_camera(Node::NodePtr camera_node);
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
private:
void init(int width, int height, const char* title);
void update_camera_lookat(GLfloat x_offset, GLfloat y_offset);
void update_camera_position();
private:
Node::NodePtr camera;
GLfloat camera_yaw;
GLfloat camera_pitch;
double last_mouse_x;
double last_mouse_y;
GLfloat game_time;
GLfloat last_frame;
GLFWwindow* window;
bool keys[512];
bool init_mouse;
};
|
70ef6a428be1c3551e6d97b2c4885b7c9d747f20 | b10188e71cbf39c08f5c574392830863a91beaef | /src/gui/gamewidget.cpp | 3df9e2ae813d46df283847ec4d8411956aa3e7eb | [] | no_license | lastmc/IncredibleSTG | a6a950b2ffd82977d6f57cdb9ec2af33621de651 | f08eddf27a136a3dcc5516a586a5da1aed6a827c | refs/heads/master | 2020-06-19T16:17:23.043111 | 2019-08-19T06:16:18 | 2019-08-19T06:16:18 | 196,780,107 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,436 | cpp | gamewidget.cpp | #include "gamewidget.h"
#include "ui_gamewidget.h"
#include <QPainter>
#include <QKeyEvent>
#include "../core/MainMenuScene.h"
#include "../core/GameScene.h"
#include "../core/GameOverScene.h"
#include "../core/StageClearScene.h"
#include "../core/ReplayScene.h"
#include "../core/AIScene.h"
GameWidget::GameWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::GameWidget)
{
//Initialization
ui->setupUi(this);
setPalette(QPalette(Qt::white));
buffPixMap=QPixmap(this->width(),this->height());
buffPixMap.fill(Qt::white);
buffPainter.begin(&buffPixMap);
scene=new STG::MainMenuScene();
timer.setTimerType(Qt::PreciseTimer);
timer.setInterval(10);
connect(&timer,SIGNAL(timeout()),this,SLOT(repaint()));
connect(&timer,SIGNAL(timeout()),this,SLOT(updateScene()));
timer.start();
}
GameWidget::~GameWidget()
{
delete ui;
if(scene) delete scene;
}
void GameWidget::updateScene(){
switch(scene->update(10)){
case STG::BaseScene::Replay:
delete scene;
scene=new STG::ReplayScene();
break;
case STG::BaseScene::AIStart:
delete scene;
scene=new STG::AIScene();
break;
case STG::BaseScene::GameStart:
case STG::BaseScene::Retry:
delete scene;
scene=new STG::GameScene();
break;
case STG::BaseScene::GameOver:{
STG::GameScene* ptr=dynamic_cast<STG::GameScene*>(scene);
int score=-1;
if(ptr) score=ptr->getScore();
delete scene;
scene=new STG::GameOverScene(score);
break;
}
case STG::BaseScene::StageClear:{
STG::GameScene* ptr=dynamic_cast<STG::GameScene*>(scene);
int score=-1;
if(ptr) score=ptr->getScore();
delete scene;
scene=new STG::StageClearScene(score);
break;
}
case STG::BaseScene::MainMenu:
delete scene;
scene=new STG::MainMenuScene();
break;
case STG::BaseScene::ExitGame:
exit(0);
default:
break;
}
}
void GameWidget::paintEvent(QPaintEvent*){
buffPixMap.fill(Qt::white);
if(scene) scene->paint(&buffPainter);
QPainter painter(this);
painter.drawPixmap(0,0,this->width(),this->height(),buffPixMap);
}
void GameWidget::keyPressEvent(QKeyEvent *event){
scene->keyPress(event->key());
}
void GameWidget::keyReleaseEvent(QKeyEvent *event){
scene->keyRelease(event->key());
}
|
5526b3c1b65cb1e64f2ea91044c62f32f1e43b1e | ae6393273d7101d7faf0518fa8ce648d468e7d5e | /platform_io/Board_3/src/main.cpp | d366a6e903b6a5abf20b7cc3e7aac397f75f873c | [] | no_license | nnonnoon/web-project | 1e9ee9a6fa4de25b912793e38111afd77b9c3965 | d3e80599a75a5df47d916f599ef130561961cd15 | refs/heads/main | 2023-04-16T19:07:14.727991 | 2021-04-29T04:07:01 | 2021-04-29T04:07:01 | 302,548,740 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 966 | cpp | main.cpp | #include <esp_now.h>
#include <WiFi.h>
typedef struct struct_message {
int id;
String tag;
}struct_message;
struct_message myData;
struct_message board_1;
struct_message board_2;
struct_message boardsStruct[2] = {board_1, board_2};
void OnDataRecv(const uint8_t * mac_addr, const uint8_t *incomingData, int len){
char macStr[18];
snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",
mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);
memcpy(&myData, incomingData, sizeof(myData));
boardsStruct[myData.id-1].id = myData.id;
boardsStruct[myData.id-1].tag = myData.tag;
Serial.printf("%x,", boardsStruct[myData.id-1].id);
Serial.println(boardsStruct[myData.id-1].tag);
}
void setup(){
Serial.begin(9600);
WiFi.mode(WIFI_STA);
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
esp_now_register_recv_cb(OnDataRecv);
}
void loop() {
} |
1ed619e2e7e3399a8aea5e25cf36961ce0a2ed45 | 0aa79c23e206edf17c002d07dfeabcae91491048 | /HMM_estimate_model.cpp | 5f245a7864f37526418e33fa96454c35d41b3839 | [] | no_license | Malacefi/ai | e99f818b2a485d17e612a748ab361262d6df85a8 | d47fe71159d2c816090d95ddf85ade36617ce327 | refs/heads/master | 2021-05-06T10:20:54.335640 | 2017-12-13T12:40:52 | 2017-12-13T12:40:52 | 114,118,454 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,290 | cpp | HMM_estimate_model.cpp | // Emelie Eriksson, Pontus Brink
#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
class Matrix {
public:
int rows, cols;
long double ** matrix;
Matrix(int rows, int cols){
this->rows= rows;
this->cols = cols;
this->matrix = new long double*[rows];
for (int i = 0; i<rows; ++i){
this->matrix[i] = new long double[cols];
}
}
Matrix(const Matrix& m){
this->rows = m.rows;
this->cols = m.cols;
this->matrix = new long double*[rows];
for (int i =0; i<this->rows; ++i){
this->matrix[i] = new long double[cols];
for (int j = 0; j<this->cols; ++j){
this->matrix[i][j] = m.matrix[i][j];
}
}
}
long double* operator[](int col){
return matrix[col];
}
Matrix operator=(const Matrix& m2){
for (int i =0; i<this->rows; ++i){
for (int j = 0; j<this->cols; ++j){
long double value = m2.matrix[i][j];
this->matrix[i][j] = value;
}
}
return *this;
}
Matrix operator-(Matrix m2){
Matrix result(this->rows, this->cols);
for (int i =0; i<this->rows; ++i){
for (int j = 0; j<this->cols; ++j){
if (this->matrix[i][j] > m2[i][j]){
result[i][j] = this->matrix[i][j] - m2[i][j];
}
else{
result[i][j] = m2[i][j]-this->matrix[i][j];
}
//cout << result[i][j] << " ";
}
//cout << "\n";
}
return result;
}
long double sum(void){
long double sum = 0.0;
for (int i = 0; i< this->rows; ++i){
for (int j = 0; j<this->cols; ++j){
sum += this->matrix[i][j];
//cout << sum << "\n";
}
}
return sum;
}
Matrix operator*(Matrix m2){
if (this->cols != m2.rows){
throw invalid_argument("Invalid matrix dimensions\n");
}
Matrix result(this->rows, m2.cols);
long double temp;
for (int i = 0; i<this->rows; ++i){
for (int j = 0; j<m2.cols; ++j){
// Now we are at a element in result matrix
temp = 0.0;
for (int k = 0; k<this->cols; ++k){
temp += this->matrix[i][k]*m2[k][j];
}
result[i][j] = temp;
}
}
return result;
}
void print(void){
cout << this->rows << " " << this->cols << " ";
for (int i = 0; i<this->rows; ++i){
for (int j = 0; j<this->cols; ++j){
cout << this->matrix[i][j] << " ";
}
}
cout << "\n";
}
};
Matrix alpha(Matrix A, Matrix B, Matrix pi, Matrix omissionSequence){
Matrix alpha(omissionSequence.cols, A.rows);
for (int i = 0; i<A.rows; ++i){
alpha[0][i] = B[i][int(omissionSequence[0][0])] * pi[0][i];
}
for(int t = 1; t<omissionSequence.cols; ++t){
for (int i = 0; i<A.rows;++i){
long double sum = 0;
for (int j = 0; j<A.rows; ++j){
sum += A[j][i] * alpha[t-1][j];
}
alpha[t][i] = B[i][int(omissionSequence[0][t])] * sum;
}
}
return alpha;
}
Matrix beta(Matrix A, Matrix B, Matrix omissionSequence){
Matrix beta(omissionSequence.cols, A.rows);
for (int i = 0; i<A.rows; ++i){
beta[omissionSequence.cols-1][i] = 1;
}
for (int t = omissionSequence.cols-2; t>=0; --t){
for (int i = 0; i<A.rows; ++i){
long double sum = 0;
for (int j = 0; j<A.rows; ++j){
sum += beta[t+1][j] * B[j][int(omissionSequence[0][t+1])] * A[i][j];
}
beta[t][i] = sum;
}
}
return beta;
}
void digamma(Matrix A, Matrix B, Matrix alpha, Matrix beta, Matrix omissionSequence, vector<Matrix>& digamma){
for (int t = 0; t<omissionSequence.cols-1; ++t){
Matrix toAdd(A.rows, A.cols);
//cout << "running digamma: " << t << "\n";
for (int i = 0; i<A.rows; ++i){
for (int j = 0; j<A.rows; ++j){
long double numerator = alpha[t][i] * A[i][j] * B[j][int(omissionSequence[0][t+1])] * beta[t+1][j];
//cout << "Crashed at numerator calc\n";
long double denominator = 0;
for (int k = 0; k<A.rows; ++k){
denominator += alpha[omissionSequence.cols-1][k];
}
toAdd[i][j] = numerator/denominator;
}
}
//cout << "DIGAMMA DUN\n";
digamma.push_back(toAdd);
//cout << "digamma pushed\n";
}
}
Matrix gamma(int omissionLength, vector<Matrix> &digamma){
Matrix gamma(omissionLength-1, digamma.at(0).rows);
for (int t = 0; t<gamma.rows; ++t){
for (int i = 0; i<gamma.cols; ++i){
long double sum = 0;
for (int j = 0; j<gamma.cols; ++j){
sum += digamma.at(t)[i][j];
}
gamma[t][i] = sum;
}
}
return gamma;
}
void updateLambda(Matrix &A, Matrix &B, Matrix &pi, Matrix omissionSequence, vector<Matrix> &digamma, Matrix gamma){
for (int i = 0; i<A.rows; ++i){
for (int j = 0; j<A.cols; ++j){
long double numerator = 0;
long double denominator = 0;
for(int t = 0; t<omissionSequence.cols-1; ++t){
numerator += digamma.at(t)[i][j];
denominator += gamma[t][i];
}
A[i][j] = numerator / denominator;
}
}
for(int j = 0; j<A.rows; ++j){
for(int k = 0; k<B.cols; ++k){
long double numerator = 0;
long double denominator = 0;
for(int t = 0; t<omissionSequence.cols-1; ++t){
if (omissionSequence[0][t] == k){
numerator += gamma[t][j];
}
denominator += gamma[t][j];
}
B[j][k] = numerator/denominator;
}
}
for (int i = 0; i<pi.cols; ++i){
pi[0][i] = gamma[0][i];
}
}
bool converges(Matrix A, Matrix oldA, Matrix B, Matrix oldB, Matrix pi, Matrix oldpi){
long double threshold = 0.001;
//cout << "DIFFERENCE: " << (A - oldA).sum() << "\n";
if ((A - oldA).sum() > threshold){
return true;
}
return false;
}
Matrix viterbi(Matrix A, Matrix B, Matrix pi, Matrix omissionSequence){
Matrix t1(A.rows, omissionSequence.cols);
Matrix t2(A.rows, omissionSequence.cols);
for (int i = 0; i<A.rows; ++i){
t1[i][0] = pi[0][i] * B[i][int(omissionSequence[0][0])];
t2[i][0] = 0;
}
long double maxTxA = 0;
int maxState = 0;
for (int i = 1; i<omissionSequence.cols; ++i){
for (int j = 0; j<A.rows; ++j){
maxTxA = 0;
maxState = 0;
for (int k = 0; k<A.rows; ++k){
if (maxTxA < t1[k][i-1] * A[k][j]){
maxTxA = t1[k][i-1] * A[k][j];
maxState = k;
}
}
t1[j][i] = B[j][int(omissionSequence[0][i])] * maxTxA;
t2[j][i] = maxState;
}
}
Matrix X(1, omissionSequence.cols);
long double maxInT = 0;
int index = 0;
for (int i = 0; i<A.rows; ++i){
if (maxInT < t1[i][omissionSequence.cols-1]){
maxInT = t1[i][omissionSequence.cols-1];
index = i;
}
}
X[0][omissionSequence.cols-1] = index;
for (int i = omissionSequence.cols-1; i>0; --i){
X[0][i-1] = t2[X[0][i]][i];
}
return X;
}
int main(){
int maRows, maCols, mbRows, mbCols;
// Init ma.
cin >> maRows >> maCols;
Matrix ma(maRows, maCols);
for (int i = 0; i<maRows; ++i){
for (int j = 0; j<maCols; ++j){
cin >> ma[i][j];
}
}
// Init mb.
cin >> mbRows >> mbCols;
Matrix mb(mbRows, mbCols);
for (int i = 0; i<mbRows; ++i){
for (int j = 0; j<mbCols; ++j){
cin >> mb[i][j];
}
}
// Init pi
int piRows, piCols;
cin >> piRows >> piCols;
Matrix pi(piRows, piCols);
//cout << piRows << " " << piCols << "\n";
for (int i = 0; i<piRows; ++i){
//cout << "Survived row\n";
for (int j = 0; j<piCols; ++j){
cin >> pi[i][j];
}
}
//cout << "Pi survived\n";
int M;
cin >> M;
Matrix omissionSequence(1,M);
for (int i = 0; i<M; ++i){
cin >> omissionSequence[0][i];
}
Matrix al = alpha(ma, mb, pi, omissionSequence);
Matrix be = beta(ma, mb, omissionSequence);
vector<Matrix> dig;
digamma(ma, mb, al, be, omissionSequence, dig);
Matrix ga = gamma(omissionSequence.cols, dig);
Matrix oldMa = ma;
Matrix oldMb = mb;
Matrix oldPi = pi;
updateLambda(ma, mb, pi, omissionSequence, dig, ga);
int max = 0;
bool keepGoing = converges(ma, oldMa, mb, oldMb, pi, oldPi);
while(keepGoing){
dig.clear();
al = alpha(ma, mb, pi, omissionSequence);
be = beta(ma, mb, omissionSequence);
digamma(ma, mb, al, be, omissionSequence, dig);
ga = gamma(omissionSequence.cols, dig);
oldMa = ma;
oldMb = mb;
oldPi = pi;
//ma.print();
updateLambda(ma, mb, pi, omissionSequence, dig, ga);
//ma.print();
++max;
keepGoing = converges(ma, oldMa, mb, oldMb, pi, oldPi);
}
ma.print();
mb.print();
//cout << max << "\n";
} |
39eef8f4dca1a64bd30b410953a653ebb53c9da4 | 3852cd1bd5e282dd23b8f7c64309cc2f598e3b75 | /tests/c++/VHTestGame/ToolContainer.cpp | e958c799f1c5f13a947f396c92004ec672a9692e | [] | no_license | chandl34/public | 4e6ca43afa410cd50f54f93d589a1784f51b55dc | e288ac323166f5170aaac7cd97d37dabffa70090 | refs/heads/master | 2021-08-18T05:42:00.234407 | 2021-07-29T02:43:03 | 2021-07-29T02:43:03 | 2,938,300 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 520 | cpp | ToolContainer.cpp | #include "ToolContainer.h"
set<Brush*> ToolContainer::_brush;
set<Pen*> ToolContainer::_pen;
ToolContainer::ToolContainer()
{
}
ToolContainer::~ToolContainer()
{
for(set<Brush*>::iterator iter = _brush.begin(); iter != _brush.end(); ++iter)
delete *iter;
for(set<Pen*>::iterator iter = _pen.begin(); iter != _pen.end(); ++iter)
delete *iter;
}
Brush* ToolContainer::getBrush(const Color& color)
{
}
Pen* ToolContainer::getPen(const Color& color, int thickness)
{
}
|
42683af79216e799d6a1e6c963603f5f58a6a012 | a7764174fb0351ea666faa9f3b5dfe304390a011 | /inc/BRep_TVertex.hxx | 0ad1a709ce3d7527d17b98b24f22a8d732494804 | [] | no_license | uel-dataexchange/Opencascade_uel | f7123943e9d8124f4fa67579e3cd3f85cfe52d91 | 06ec93d238d3e3ea2881ff44ba8c21cf870435cd | refs/heads/master | 2022-11-16T07:40:30.837854 | 2020-07-08T01:56:37 | 2020-07-08T01:56:37 | 276,290,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,281 | hxx | BRep_TVertex.hxx | // This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#ifndef _BRep_TVertex_HeaderFile
#define _BRep_TVertex_HeaderFile
#ifndef _Standard_HeaderFile
#include <Standard.hxx>
#endif
#ifndef _Standard_DefineHandle_HeaderFile
#include <Standard_DefineHandle.hxx>
#endif
#ifndef _Handle_BRep_TVertex_HeaderFile
#include <Handle_BRep_TVertex.hxx>
#endif
#ifndef _gp_Pnt_HeaderFile
#include <gp_Pnt.hxx>
#endif
#ifndef _Standard_Real_HeaderFile
#include <Standard_Real.hxx>
#endif
#ifndef _BRep_ListOfPointRepresentation_HeaderFile
#include <BRep_ListOfPointRepresentation.hxx>
#endif
#ifndef _TopoDS_TVertex_HeaderFile
#include <TopoDS_TVertex.hxx>
#endif
#ifndef _Handle_TopoDS_TShape_HeaderFile
#include <Handle_TopoDS_TShape.hxx>
#endif
class gp_Pnt;
class BRep_ListOfPointRepresentation;
class TopoDS_TShape;
//! The TVertex from BRep inherits from the TVertex <br>
//! from TopoDS. It contains the geometric data. <br>
//! <br>
//! The TVertex contains a 3d point and a tolerance. <br>
//! <br>
class BRep_TVertex : public TopoDS_TVertex {
public:
Standard_EXPORT BRep_TVertex();
Standard_Real Tolerance() const;
void Tolerance(const Standard_Real T) ;
//! Sets the tolerance to the max of <T> and the <br>
//! current tolerance. <br>
//! <br>
void UpdateTolerance(const Standard_Real T) ;
const gp_Pnt& Pnt() const;
void Pnt(const gp_Pnt& P) ;
const BRep_ListOfPointRepresentation& Points() const;
BRep_ListOfPointRepresentation& ChangePoints() ;
//! Returns a copy of the TShape with no sub-shapes. <br>
Standard_EXPORT Handle_TopoDS_TShape EmptyCopy() const;
DEFINE_STANDARD_RTTI(BRep_TVertex)
protected:
private:
gp_Pnt myPnt;
Standard_Real myTolerance;
BRep_ListOfPointRepresentation myPoints;
};
#include <BRep_TVertex.lxx>
// other Inline functions and methods (like "C++: function call" methods)
#endif
|
6aa87027aea1af5a9c55fb4fee25ce0449a4c75d | e0d906c1e84c1f83a3da27db086aab7b7b4212af | /Server/Server/geometry.h | 66f5a0da769bbd658f845ac175354c22b2711dbf | [] | no_license | StarikTenger/SpaceSodomyOnline | 8904034c5ec400e17404f6e41bafb9da5fe7d2ff | cdbe6975d293bd214f8a591cbe5dfba4ea415a5d | refs/heads/master | 2023-02-09T04:53:11.604384 | 2020-12-30T19:02:45 | 2020-12-30T19:02:45 | 237,202,605 | 3 | 5 | null | 2020-12-30T18:55:32 | 2020-01-30T11:51:53 | C++ | UTF-8 | C++ | false | false | 682 | h | geometry.h | #pragma once
#include "Vec2.h"
#include <vector>
# define M_PI 3.14159265358979323846 /* pi */
# define EPS 0.0001
namespace geom {
bool isCross(Vec2 a, Vec2 b, Vec2 c, Vec2 d);
Vec2 getCross(Vec2 a, Vec2 b, Vec2 c, Vec2 d);
Vec2 direction(double a);
Vec2 direction(Vec2 a, Vec2 b);
double dir(Vec2 p);
double dir(Vec2 a, Vec2 b, Vec2 c);
double distance(Vec2 a, Vec2 b);
double distance(Vec2 p, Vec2 a, Vec2 b);
Vec2 rotate(Vec2 p, double dir);
double square(std::vector<Vec2> polygon);
bool inPolygon(Vec2 point, std::vector<Vec2> polygon);
std::vector<double> angleDistribution(double direction, double width, int n);
double normalizeAngle(double dir);
} |
af21e49fba3328d878646057741d033dafe2b13a | 33adf3a0ad47ffd99be5ec1b14d85811040ad855 | /Chapter8/func_template_multiple_params_stage1.cpp | ad1f5fac7d92e4fe115bf3a53175d7e4e7864cbb | [] | no_license | anhkhoa91280/C-Primer-Plus-Programming-Exercises-Solutions | c369fb9ebbd344ab9bea48a9845ef6aa6162cb3b | d68a378172d07701b6590564aaa6919b6fa82c83 | refs/heads/master | 2020-06-19T11:54:27.182250 | 2020-02-12T12:50:04 | 2020-02-12T12:50:04 | 196,697,022 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 676 | cpp | func_template_multiple_params_stage1.cpp | /*
* Name: Dang Nguyen Anh Khoa
* Date: 20191020
* Desc: This program shows function template with multiple params in stage 1 where
* var is of the same type as the unparenthesized indentifier.
* Reference: C++ Primer Plus - 6th Edition.
* */
#include <iostream>
int main() {
double a = 5.5;
double & ra = a;
double * c = &a;
decltype(a) b = 6.5; //b is a double
decltype(ra) rb = b; //rb is a double &
decltype(c) d = &b; //d is a double *
std::cout << "b = " << b << ", size: " << sizeof(b) << std::endl;
std::cout << "rb = " << rb << ", size: " << sizeof(rb) << std::endl;
std::cout << "d = " << *d << ", size: " << sizeof(d) << std::endl;
return 0;
}
|
226ef800aba147ca806c540bbe2e26cfa1b02c0c | 9d88712ccf434db1ff0b16325d4ca2b7c079573a | /Resources/Value.h | ceb5ec79cd7022edee8255fab61b9c7393843e6b | [] | no_license | cpgoodri/jsrc | 6d041e2c7b0315168dc8cf7caf9fd26226b498cd | 5ed76c42eed211d6abf886e8710fccea44e753e5 | refs/heads/master | 2020-04-11T02:36:41.468656 | 2018-10-04T13:32:20 | 2018-10-04T13:32:20 | 9,376,153 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,933 | h | Value.h | /*
* Value.h
* Percolation
*
* Created by Samuel Schoenholz on 6/7/10.
* Copyright 2010 Swarthmore College. All rights reserved.
*
*/
#ifndef VALUE
#define VALUE
#include <map>
#include <string>
#include <typeinfo>
/*
This code introduces typeless, invisible variables.
The code is constructed from the article
Chameleon Objects, or how to write a generic, type safe wrapper class
Volker Simonis1
Wilhelm-Schickard-Institut für Informatik
Universität Tübingen, 72076 Tübingen, Germany
E-mail: simonis@informatik.uni-tuebingen.de
29 November 1999
*/
//class that handles casting between incompatible types
class Incompatible_Type_Exception
{
private:
string errorType;
public:
Incompatible_Type_Exception(const string &s) {errorType = s;}
string getError() const {return errorType;}
};
template <class T>
istream &operator>>(istream &in,T *v)
{
return in >> *v;
}
//class that seamlessly handles arbitrary types
class Value
{
protected:
enum Action {GET,SET,DELETE};
//primary method that adds items to a static lookup table
template<class T> T& value(T t = T(),Action = GET) throw (Incompatible_Type_Exception&);
typedef void(Value::*FuncPointer)(void);
typedef void(Value::*ClonePointer)(Value*) const;
typedef ostream&(Value::*PrintPointer)(ostream&) const;
typedef istream&(Value::*ReadPointer)(istream&) const;
typedef Value(Value::*DereferencePointer)(void) const;
ClonePointer fp_CLONE; //pointer to the cloning function
FuncPointer fp_DELETE; //pointer to the deletion function
PrintPointer fp_PRINT; //pointer to the printer function
ReadPointer fp_READ; //pointer to the writing function
DereferencePointer fp_DEREFERENCE;
public:
enum Type {POINTER};
Value() : fp_DELETE(NULL), fp_CLONE(NULL) , fp_PRINT(NULL), fp_READ(NULL), fp_DEREFERENCE(NULL) {} //default constructor
template<class T> Value(const T& t) : fp_DELETE(NULL), fp_DEREFERENCE(NULL) {value(t,SET);} //generic constructor
template<class T> Value(T *t,Type) : fp_DELETE(NULL) {value<T*>(t,SET); fp_DEREFERENCE = &Value::DereferenceValue<T>;}
inline Value(const Value &); //copy constructor
~Value() {if(fp_DELETE!=NULL) (this->*fp_DELETE)();}//generic destructor
template<class T> operator T() const throw (Incompatible_Type_Exception&) { //generic casting function
return const_cast<Value*>(this)->template value<T>();
}
template <class T> T& operator=(const T &t) {return value(t,SET);}
Value &operator=(const Value&); //clone function
template <class T> inline void DeleteValue(); //helper function to delete value
template <class T> void CloneValue(Value *) const; //generic function to clone an object
template <class T> void Pointer(T *t) {value<T*>(t,SET);fp_DEREFERENCE = &Value::DereferenceValue<T>;}
Value operator*();
template <class T> Value DereferenceValue() const;
//printing functions
template <class T> ostream &PrintValue(ostream &out) const{
return out << const_cast<Value*>(this)->template value<T>();}
friend ostream &operator <<(ostream &out, const Value &e){
if(e.fp_PRINT) return (e.*e.fp_PRINT)(out);
else return (out << "nil");
}
//writing functions
template <class T>istream &ReadValue(istream &in) const{
T t = const_cast<Value*>(this)->template value<T>(); in >> t; const_cast<Value*>(this)->template value<T>(t,SET);return in;
}
friend istream &operator>>(istream &in, const Value &e){
if(e.fp_READ) return (e.*e.fp_READ)(in);
else return in;
}
};
//copy creation operator
inline Value::Value(const Value &val) : fp_DELETE(NULL), fp_PRINT(NULL), fp_READ(NULL), fp_DEREFERENCE(NULL)
{
if(val.fp_CLONE!=NULL)
(val.*val.fp_CLONE)(this);
else fp_CLONE = NULL;
}
//implementation of value uses a static lookup table for each datatype to provide functionality
template <class T>
T &Value::value(T t,Action action) throw (Incompatible_Type_Exception&)
{
static map<Value*, T> values;
switch(action)
{
case SET: //sets an object in the map for the correct type of object
{
values[this] = t;
fp_READ = &Value::ReadValue<T>;
fp_PRINT = &Value::PrintValue<T>;
fp_CLONE = &Value::CloneValue<T>;//sets the clone pointer to have the correct type
if(fp_DELETE == NULL) fp_DELETE = &Value::DeleteValue<T>; //set fp_DELETE to point to this types function pointer
else if (fp_DELETE!=(FuncPointer)&Value::DeleteValue<T>)
{
(this->*fp_DELETE)(); //otherwise delete the type
fp_DELETE = &Value::DeleteValue<T>;//and remember the deletion function for the correct type
}
return t;
}
case GET: //if the object of this type exists then get it otherwise throw and error
{
if(values.count(this))
return values[this];
else
throw Incompatible_Type_Exception(typeid(T).name());
}
case DELETE: //only called by the destructor
{
if(values.count(this)) values.erase(this);
return t;
}
default:
return t;
}
}
//function to delete a value of type T
template<class T>
inline void Value::DeleteValue()
{
static T t;
value(t,DELETE);
}
//function to clone Value.
//fp_CLONE holds a pointer to the function of type val.
Value &Value::operator=(const Value& val)
{
if(this != &val&&val.fp_CLONE!=NULL){
(val.*val.fp_CLONE)(this);
return *this;
}
}
//function to actually perform the cloning of an object
template <class T>
void Value::CloneValue(Value *val) const
{
val->template value<T>(const_cast<Value*>(this)->template value<T>(),SET);
if(fp_DEREFERENCE){val->fp_DEREFERENCE = fp_DEREFERENCE;}
}
//operator to give a value that is one time dereferenced from the value
Value Value::operator*()
{
if(fp_DEREFERENCE)
return (this->*fp_DEREFERENCE)();
}
//function to return a dereferenced copy of this value
template<class T>
Value Value::DereferenceValue() const
{
return Value(*(const_cast<Value*>(this)->template value<T*>()));
}
#define INTEGER 0
#define STRING string()
#define FLOAT 0.0f
#define DOUBLE 0.0
#endif
|
07bb5ddf278242b1f035d5a0eedd21cdb9b4314b | 71c1c86b30c1518e21728f7d5e0f09b5e602baac | /Algo_Engine/ROM_Handler/ExchangeServers/EXCHANGESERVERS/ACT/ActSession.h | 7834117a8618dce1cb57ac969ede8dbb0032310a | [] | no_license | ssh352/ronin | 3ddf360fec5f106015c6902b5107aedefe934836 | 33301b6c5e68fa9d02c7d54bc86f6b7732985fc2 | refs/heads/master | 2023-05-03T11:00:39.368460 | 2021-05-17T18:41:08 | 2021-05-17T18:41:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,567 | h | ActSession.h | // ActSession.h: interface for the CFixSession class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_FIXSESSION_H__E69D7592_E5AA_11D1_8D02_006008CD4894__INCLUDED_)
#define AFX_FIXSESSION_H__E69D7592_E5AA_11D1_8D02_006008CD4894__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#include "Act.h"
class CActSession //: public CExchangeSession
{
public:
CActSession();
virtual ~CActSession();
public:
virtual void ProcessTimer();
long ProcessActEntry(CCsv*);
virtual long ProcessEntry(COrder& Order) { return 0;}
void ProcessMessage(const char *Msg, int Size);
private:
CString m_Date;
CPtrList m_ActMsgList;
CTime m_LastSendTime;
int m_HeartbtInt;
private:
void ProcessLogonResponse();
//void ProcessHeartBeatQuery();
void ProcessHeartBeatResponse();
//void ProcessFlowControl(const char *Msg);
void ProcessChannelStateQuery(const char *Msg);
//void ProcessChannelStateResponse(const char *Msg);
void ProcessActResponse(const char* Msg, u_short Size);
//void ProcessAct(CString Msg, int Size);
//void ProcessLogon(const char *Msg);
//void ProcessHeartBeat();
BOOL SendLogin();
BOOL SendAct(const char *Act);
BOOL SendActMsgs();
BOOL SendChannelState(BYTE Channel);
BOOL SendHeartBeat();
void ConnectionCheck();
void TrimLeadingZeros(CString &s);
//void SetEnvelope(char * MsgBuffer, int BodySize);
};
#endif // !defined(AFX_FIXSESSION_H__E69D7592_E5AA_11D1_8D02_006008CD4894__INCLUDED_)
|
179f9e2043ceb5d05dfe597722bbc5f85ba80ff6 | 3273c7087ba6f3a805a4dfc6ba66bfea801012a3 | /src/libcore/destination.h | 4baa0d9791cf7a1163f1769f962f2345693ab8e4 | [] | no_license | zhouxingtuan/gammaServer | e4d38cfaf8a05b0229048af7a1b4010839b2017e | 868d5c2d2cc9b65181489d42971e4a52efc1b800 | refs/heads/master | 2021-01-22T21:45:55.588529 | 2019-03-25T09:06:59 | 2019-03-25T09:06:59 | 85,474,498 | 12 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 3,246 | h | destination.h | //
// Created by IntelliJ IDEA.
// User: AppleTree
// Date: 17/2/26
// Time: 下午2:00
// To change this template use File | Settings | File Templates.
//
#ifndef __hive__destination__
#define __hive__destination__
#include "common.h"
NS_HIVE_BEGIN
typedef struct DestinationHandle {
union{
struct{
// unsigned int version : 8; // 版本
unsigned int node : 8; // 节点
unsigned int service : 5; // 服务
unsigned int type : 3; // 类型
unsigned int index : 16; // 下标
};
unsigned int handle : 32; // 句柄
};
public:
DestinationHandle(unsigned int h){ this->handle = h; }
DestinationHandle(void) : handle(0) {}
~DestinationHandle(void){}
inline unsigned int getService(void) const { return this->service; }
inline unsigned int getType(void) const { return this->type; }
inline unsigned int getIndex(void) const { return this->index; }
// inline unsigned int getVersion(void) const { return this->version; }
inline unsigned int getNode(void) const { return this->node; }
inline unsigned int getHandle(void) const { return this->handle; }
inline void setService(unsigned int s){ this->service = s; }
inline void setType(unsigned int t){ this->type = t; }
inline void setIndex(unsigned int index){ this->index = index; }
inline void setNode(unsigned int node){ this->node = node; }
// inline void increaseVersion(void){ ++(this->version); }
inline bool operator==(unsigned int h) const { return (this->handle == h); }
inline bool operator==(const DestinationHandle& h) const{ return (this->handle == h.handle); }
inline bool operator<(unsigned int h) const { return (this->handle < h); }
inline bool operator<(const DestinationHandle& h) const { return (this->handle < h.handle); }
inline DestinationHandle& operator=(unsigned int h){ this->handle = h; return *this; }
inline DestinationHandle& operator=(const DestinationHandle& h){ this->handle = h.handle; return *this; }
}DestinationHandle;
class Packet;
class Task;
class Destination
{
public:
typedef uint32 handle_type;
// typedef uint32 version_type;
typedef uint32 node_type;
typedef uint32 index_type;
typedef uint32 type_type;
protected:
DestinationHandle m_handle;
public:
Destination(void) : m_handle(0) {}
virtual ~Destination(void){}
inline unsigned int getService(void) const { return m_handle.getService(); }
inline unsigned int getType(void) const { return m_handle.getType(); }
inline unsigned int getIndex(void) const { return m_handle.getIndex(); }
// inline unsigned int getVersion(void) const { return m_handle.getVersion(); }
inline unsigned int getNode(void) const { return m_handle.getNode(); }
inline unsigned int getHandle(void) const { return m_handle.getHandle(); }
inline void setService(unsigned int s){ m_handle.setService(s); }
inline void setType(unsigned int t){ m_handle.setType(t); }
inline void setIndex(unsigned int index){ m_handle.setIndex(index); }
inline void setNode(unsigned int node){ m_handle.setNode(node); }
// inline void increaseVersion(void){ m_handle.increaseVersion(); }
inline void setHandle(unsigned int handle) { m_handle = handle; }
// 目标接收到packet
virtual void onReceivePacket(Packet* pPacket, Task* pTask) = 0;
};
NS_HIVE_END
#endif
|
3302bea26f371519944ca281d4273b2a5f5c4e30 | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/d9/8d07c2d443450a/main.cpp | 7881d49b16d99d647373446bd555189bc1c30825 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 431 | cpp | main.cpp | #include <vector>
using namespace std;
template<class T>
class Stack : private vector<T>
{
vector<T> S;
public:
Stack<T> push(T str);
Stack<T> operator += (const Stack<T> &str);
};
template<class T>
Stack<T> Stack<T>::push(T str)
{
S.push_back(qElem(str));
}
template<class T>
Stack<T> Stack<T>::operator += (const Stack<T> &str)
{
return this->push(str);
}
int main() {
Stack<int> s;
s += 5;
} |
fc408e342061e3b43bfc1a13d056b14b02f20de1 | 12a5d6aa64cf3bbbcc5df234d04a34ca03a7b629 | /Celcius to Kelvin/Celcius to Kelvin/Source.cpp | e76bad28322ae5688d352943cfb66f69864ebece | [] | no_license | JohanvandenHeuvel/Projects | 9b8ada0cf08a9888827636d337a30fc6f24fb864 | af3e43064674bd25722b88346e22027a15888ba7 | refs/heads/master | 2020-05-20T12:41:18.286955 | 2017-01-30T14:46:03 | 2017-01-30T14:46:03 | 80,428,914 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,466 | cpp | Source.cpp | #include "../../std_lib_facilities.h"
class Bad_temp{};
class Case_unknown{};
double CtoK(double c)
{
if (c < -273.15 )
throw Bad_temp{};
double k = c + 273.15;
return k;
}
double KtoC(double k)
{
if (k < 0)
throw Bad_temp{};
double c = k - 273.15;
return c;
}
double CtoF(double c)
{
if (c < -273.15)
throw Bad_temp{};
double f = (9 / 5)*c + 32;
return f;
}
double FtoC(double f)
{
if (f < -459.66)
throw Bad_temp{};
double c = (f - 32) / (9 / 5);
return c;
}
int main()
try {
cout << "1-- Celcius to Kelvin\n"
<< "2-- Kelvin to Celcius\n"
<< "3-- Celcius to Fahrenheit\n"
<< "4-- Fahrenheit to Celcius\n";
int input;
cin >> input; //make a choice of 4 options
double c = 0; //celcius
double k = 0; //kelvin
double f = 0; //fahrenheit
switch (input)
{
case 1: //C to K
cout << "Enter Celcius\n";
cin >> c;
k = CtoK(c);
cout << k <<'\n';
break;
case 2: //K to C
cout << "Enter Kelvin\n";
cin >> k;
c = KtoC(k);
cout << c << '\n';
break;
case 3: //C to F
cout << "Enter Celcius\n";
cin >> c;
f = CtoF(c);
cout << f << '\n';
break;
case 4: //F to C
cout << "Enter Fahrenheit\n";
cin >> f;
c = FtoC(f);
cout << c << '\n';
break;
default:
throw Case_unknown{};
break;
}
keep_window_open();
return 0;
}
catch(Bad_temp){
cout << "Error: cannot go lower then 273.15 C\n";
keep_window_open();
}
catch (Case_unknown) {
cout << "Error: case unknown\n";
keep_window_open();
}
|
330ac2025d285503cd876eef00e2569eed268f15 | b239039156fe541fb157f81d487b1758b84fc286 | /win-odbc64/odbcclient/DSNConverter/DSList.cpp | 15ae519b26c35baf882c9e7831fbbe4b22163b09 | [
"Apache-2.0"
] | permissive | radumarias/incubator-trafodion | a26da84a628dbde0559ba2e903bb777fab1903d3 | 6edf28c6a4ee1721d3225d47d0be541d125b6138 | refs/heads/master | 2021-01-16T00:22:54.566854 | 2015-09-03T04:44:32 | 2015-09-03T04:44:32 | 41,851,063 | 0 | 0 | null | 2015-09-03T09:10:16 | 2015-09-03T09:10:15 | null | UTF-8 | C++ | false | false | 5,589 | cpp | DSList.cpp | /**********************************************************************
// @@@ START COPYRIGHT @@@
//
// (C) Copyright 2002-2014 Hewlett-Packard Development Company, L.P.
//
// 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.
//
// @@@ END COPYRIGHT @@@
********************************************************************/
// DSList.cpp: implementation of the CDSList class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "DSList.h"
#include <string.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
const int CDSList::NAME = 0;
const int CDSList::VALUE = 1;
CDSList::CDSList():
m_iIndex(0), m_pNext(NULL), m_pPrev(NULL),
m_pName(NULL), m_pValue(NULL), m_pAttribs(NULL)
{
}
CDSList::CDSList(CDSList *pParent):
m_iIndex(pParent->getIndex() + 1), m_pNext(NULL), m_pPrev(pParent),
m_pName(NULL), m_pValue(NULL), m_pAttribs(NULL)
{
}
CDSList::~CDSList()
{
// Don't delete the previous object since its destructor is
// destroying *this* object through its m_pNext member.
delete [] m_pName;
delete [] m_pValue;
delete m_pNext;
delete m_pAttribs;
}
bool CDSList::append(const char* name, const char* value /* = NULL */)
{
// Check to make sure that this name is unique to the list. Names
// are always added to the "bottom" of the list. Since this function
// is be called recursivly, turn the search option off to save on
// repetitive searches.
if (name == NULL || findName(name, false) >= 0)
return false;
// Append only if a value of name hasn't already been assigned to it.
if (m_pName == NULL)
{
// set the name
int length = strlen(name) + 1;
m_pName = new char[length];
memset(m_pName, 0, length);
strcpy(m_pName, name);
// set the optional value
if (value != NULL)
{
length = strlen(value) + 1;
m_pValue = new char[length];
memset(m_pValue, 0, length);
strcpy(m_pValue, value);
}
return true;
}
else
{
if (m_pNext == NULL)
m_pNext = new CDSList(this);
return m_pNext->append(name, value);
}
}
int CDSList::getIndex()
{
return m_iIndex;
}
int CDSList::findName(const char* name, bool Search /* = true */)
{
// If there is no name, then there will be no children, so don't
// bother checking.
if (name == NULL || m_pName == NULL)
return -1;
// If we don't have the name then traverse the list if the search
// option is set.
if (strcmp(m_pName, name) == 0)
return m_iIndex;
else if (m_pNext != NULL && Search)
return m_pNext->findName(name);
else
return -1;
}
int CDSList::getCount()
{
CDSList* pIndex = this;
int count = 0;
while (pIndex != NULL)
{
// Only objects with names count.
if (pIndex->m_pName != NULL)
count++;
pIndex = pIndex->m_pNext;
}
return count;
}
int CDSList::getAttribCount(const char* name)
{
int index = findName(name);
return getAttribCount(index);
}
int CDSList::getAttribCount(int index)
{
if (m_iIndex == index)
{
if (m_pAttribs != NULL)
return m_pAttribs->getCount();
else
return 0;
}
else
{
if (m_pNext != NULL)
return m_pNext->getAttribCount(index);
else
return -1;
}
}
bool CDSList::addAttrib(int index, const char* attrib,
const char* attrib_value /* = NULL */)
{
// Verify that the index is valid.
if (index < 0)
return false;
// Get the right CDSList object based on index
if (m_iIndex == index)
{
// If necessary, create an attribute list before adding.
if (m_pAttribs == NULL)
m_pAttribs = new CDSList();
return m_pAttribs->append(attrib, attrib_value);
}
else
{
if (m_pNext != NULL)
return m_pNext->addAttrib(index, attrib, attrib_value);
else
return false;
}
}
bool CDSList::addAttrib(const char* name, const char* attrib,
const char* attrib_value /* = NULL */)
{
int index = findName(name);
return addAttrib(index, attrib, attrib_value);
}
char* CDSList::getAttribValue(int index, const char* attrib)
{
if (index < 0)
return NULL;
if (index == m_iIndex)
{
if (m_pAttribs != NULL)
{
int att_index = m_pAttribs->findName(attrib);
return m_pAttribs->getAt(att_index, CDSList::VALUE);
}
}
else
{
if (m_pNext != NULL)
return m_pNext->getAttribValue(index, attrib);
}
return NULL;
}
char* CDSList::getAt(int index, int type /* = CDSList::NAME */)
{
// Index values are zero or higher.
if (index < 0)
return NULL;
if (index == m_iIndex)
{
char* copy = NULL;
if (type == NAME && m_pName != NULL)
{
copy = new char[strlen(m_pName) + 1];
strcpy(copy, m_pName);
}
else if (type == VALUE && m_pValue != NULL)
{
copy = new char[strlen(m_pValue) + 1];
strcpy(copy, m_pValue);
}
return copy;
}
else
{
if (m_pNext != NULL)
return m_pNext->getAt(index, type);
else
return NULL;
}
} |
075ac782340ef7101d2c22a122ac8da0dbcc9419 | 6680f8d317de48876d4176d443bfd580ec7a5aef | /misRepresentation/misDistanceRepresentation2D.cpp | cf4848d804560d746a09378079d38401b36c50c8 | [] | no_license | AlirezaMojtabavi/misInteractiveSegmentation | 1b51b0babb0c6f9601330fafc5c15ca560d6af31 | 4630a8c614f6421042636a2adc47ed6b5d960a2b | refs/heads/master | 2020-12-10T11:09:19.345393 | 2020-03-04T11:34:26 | 2020-03-04T11:34:26 | 233,574,482 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,500 | cpp | misDistanceRepresentation2D.cpp | #include "stdafx.h"
/*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile: misDistanceRepresentation2D.cxx,v $
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "misDistanceRepresentation2D.h"
using namespace std;
vtkStandardNewMacro(misDistanceRepresentation2D);
//----------------------------------------------------------------------
misDistanceRepresentation2D::misDistanceRepresentation2D()
{
this->IsNormalWidget = true;
this->m_Orientation = UNKnownDirection;
}
//----------------------------------------------------------------------
misDistanceRepresentation2D::~misDistanceRepresentation2D()
{
}
//----------------------------------------------------------------------
void misDistanceRepresentation2D::GetPoint1WorldPosition(double pos[3])
{
this->Point1Representation->GetWorldPosition(pos);
}
//----------------------------------------------------------------------
void misDistanceRepresentation2D::GetPoint2WorldPosition(double pos[3])
{
this->Point2Representation->GetWorldPosition(pos);
}
//----------------------------------------------------------------------
double* misDistanceRepresentation2D::GetPoint1WorldPosition()
{
if (!this->Point1Representation)
{
static double temp[3]= {0, 0, 0};
return temp;
}
return this->Point1Representation->GetWorldPosition();
}
//----------------------------------------------------------------------
double* misDistanceRepresentation2D::GetPoint2WorldPosition()
{
if (!this->Point2Representation)
{
static double temp[3]= {0, 0, 0};
return temp;
}
return this->Point2Representation->GetWorldPosition();
}
//----------------------------------------------------------------------
void misDistanceRepresentation2D::SetPoint1DisplayPosition(double x[3])
{
this->Point1Representation->SetDisplayPosition(x);
double p[3];
this->Point1Representation->GetWorldPosition(p);
this->Point1Representation->SetWorldPosition(p);
this->AxisActor->GetPoint1Coordinate()->SetValue(p);
}
//----------------------------------------------------------------------
void misDistanceRepresentation2D::SetPoint2DisplayPosition(double x[3])
{
this->Point2Representation->SetDisplayPosition(x);
double p[3];
this->Point2Representation->GetWorldPosition(p);
this->Point2Representation->SetWorldPosition(p);
this->AxisActor->GetPoint2Coordinate()->SetValue(p);
}
//----------------------------------------------------------------------
void misDistanceRepresentation2D::SetPoint1WorldPosition(double x[3])
{
if (this->Point1Representation)
{
this->Point1Representation->SetWorldPosition(x);
this->AxisActor->GetPoint1Coordinate()->SetValue(x);
}
}
//----------------------------------------------------------------------
void misDistanceRepresentation2D::SetPoint2WorldPosition(double x[3])
{
if (this->Point2Representation)
{
this->Point2Representation->SetWorldPosition(x);
this->AxisActor->GetPoint2Coordinate()->SetValue(x);
}
}
//----------------------------------------------------------------------
void misDistanceRepresentation2D::GetPoint1DisplayPosition(double pos[3])
{
this->Point1Representation->GetDisplayPosition(pos);
pos[2] = 0.0;
}
//----------------------------------------------------------------------
void misDistanceRepresentation2D::GetPoint2DisplayPosition(double pos[3])
{
this->Point2Representation->GetDisplayPosition(pos);
pos[2] = 0.0;
}
//----------------------------------------------------------------------
//vtkAxisActor2D *misDistanceRepresentation2D::GetAxis()
//{
// return this->AxisActor;
//}
//----------------------------------------------------------------------
void misDistanceRepresentation2D::BuildRepresentation()
{
string measurmentFactor;
if ( this->GetMTime() > this->BuildTime ||
this->Point1Representation->GetMTime() > this->BuildTime ||
this->Point2Representation->GetMTime() > this->BuildTime ||
(this->Renderer && this->Renderer->GetVTKWindow() &&
this->Renderer->GetVTKWindow()->GetMTime() > this->BuildTime) )
{
this->Superclass::BuildRepresentation();
//vtkDistanceRepresentation::BuildRepresentation();
// Okay, compute the distance and set the label
double p1[3], p2[3];
this->Point1Representation->GetWorldPosition(p1);
this->Point2Representation->GetWorldPosition(p2);
switch (this->GetImageOrientation())
{
case AXIAL :
p2[2] = p1[2];
break;
case SAGITTAL:
p2[0] = p1[0];
break;
case CORONAL:
p2[1] = p1[1];
break;
}
this->Distance = sqrt(vtkMath::Distance2BetweenPoints(p1,p2));
char t_string[512];
sprintf_s(t_string, this->LabelFormat, this->Distance);
measurmentFactor.append(t_string);
measurmentFactor.append("mm");
this->AxisActor->SetTitle(measurmentFactor.c_str());
this->BuildTime.Modified();
}
}
void misDistanceRepresentation2D::SetPoint1ToFocalPoint( double *pos )
{
double position[3];
position[0] = pos[0];
position[1] = pos[1];
position[2] = pos[2];
this->SetPoint1DisplayPosition(position);
}
void misDistanceRepresentation2D::StartWidgetInteraction( double e[2] )
{
double pos[3];
pos[0] = e[0];
pos[1] = e[1];
pos[2] = 0.0;
if (this->IsNormalWidget)
this->SetPoint1DisplayPosition(pos);
this->SetPoint2DisplayPosition(pos);
}
void misDistanceRepresentation2D::setRepresentationMode( bool type )
{
if (!type)
this->IsNormalWidget = false;
}
void misDistanceRepresentation2D::SetImageOrientation( IMAGEORIENTATION orientation )
{
this->m_Orientation = orientation;
}
IMAGEORIENTATION misDistanceRepresentation2D::GetImageOrientation()
{
return this->m_Orientation;
}
//
//void misDistanceRepresentation2D::WidgetInteraction( double e[2] )
//{
// double pos[3];
// pos[0] = e[0];
// pos[1] = e[1];
// pos[2] = 0.0;
// this->SetPoint2DisplayPosition(pos);
//}
//----------------------------------------------------------------------
//void misDistanceRepresentation2D::ReleaseGraphicsResources(vtkWindow *w)
//{
// this->AxisActor->ReleaseGraphicsResources(w);
//}
//
////----------------------------------------------------------------------
//int misDistanceRepresentation2D::RenderOverlay(vtkViewport *v)
//{
// this->BuildRepresentation();
//
// if ( this->AxisActor->GetVisibility() )
// {
// return this->AxisActor->RenderOverlay(v);
// }
// else
// {
// return 0;
// }
//}
//
////----------------------------------------------------------------------
//int misDistanceRepresentation2D::RenderOpaqueGeometry(vtkViewport *v)
//{
// this->BuildRepresentation();
//
// if ( this->AxisActor->GetVisibility() )
// {
// return this->AxisActor->RenderOpaqueGeometry(v);
// }
// else
// {
// return 0;
// }
//}
//
////----------------------------------------------------------------------
//void misDistanceRepresentation2D::PrintSelf(ostream& os, vtkIndent indent)
//{
// //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h
// this->Superclass::PrintSelf(os,indent);
//}
|
72ee77c3c479bec46315624b1349c2d56d8d5f7e | 3e0e7a144449929a0cd73abe542980ae9deebc94 | /przyklad/main.cpp | 815dad5293ded4b67a96cdeccb4ec4a08b714688 | [] | no_license | scprivate/PornHub-The-Game | 45d0e1a2ee3d56f25767ffb2c35509172717d80b | 1e138d6ff6b9b3982f0840b583df6248d9386b38 | refs/heads/master | 2020-06-08T00:30:58.323485 | 2018-06-27T22:52:02 | 2018-06-27T22:52:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,261 | cpp | main.cpp | #include <iostream>
#include <windows.h>
#include <stdlib.h>
#include <cstdlib>
#include <time.h>
#include <stdio.h>
#include <conio.h>
using namespace std;
void HideCursor()
{
::HANDLE hConsoleOut =::GetStdHandle( STD_OUTPUT_HANDLE );
::CONSOLE_CURSOR_INFO hCCI;
::GetConsoleCursorInfo( hConsoleOut, & hCCI );
hCCI.bVisible = FALSE;
::SetConsoleCursorInfo( hConsoleOut, & hCCI );
}
int main()
{
HideCursor();
int lamiglowka;
cout<<"Kurwa pulapka wylosuj ponad 50, a przejdziesz dalej."<<endl;
cout<<"Wcisnij T..."<<endl;
for(unsigned lamiglowka=0;lamiglowka<99;lamiglowka++)
{
cout<<"\rliczba: "<<lamiglowka;
Sleep(4);
if (lamiglowka==98)
{
lamiglowka=0;
}
if( kbhit() )
if( getch() == 't' )
{
if(lamiglowka<=50)
{
goto t;
}
else if(lamiglowka>=51)
{
goto x;
}
}
}
x:
cout<<endl<<"Udalo ci sie kurwo przeszedles dalej"<<endl;
system("PAUSE");
goto l;
t:
cout<<endl<<"przejebales"<<endl;
l:
return 0;
}
|
cd8bfcbb9e4ec4f31ad9b5883927e153b20f0c90 | f3bb54dd01200b7de410ff1cf6e57076a1ffd2e4 | /src/GameEntity.cpp | 4f7a3294cf42a52ec4d3b62b890b5b52427803a9 | [] | no_license | bdelpey/cpp_rush00_shot_-em_up | c3c0b3190906b3b044718b1cb916ce86b7bb2b9c | a963f6717d5468a2c6989b8f375095e73be29f20 | refs/heads/master | 2016-09-05T18:20:09.978350 | 2015-01-12T11:31:55 | 2015-01-12T11:31:55 | 29,132,408 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,511 | cpp | GameEntity.cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* GameEntity.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bdelpey <bdelpey@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/01/10 16:16:32 by bdelpey #+# #+# */
/* Updated: 2015/01/12 03:43:36 by ffourati ### ########.fr */
/* */
/* ************************************************************************** */
#include "GameEntity.hpp"
const int GameEntity::_DEFAULT_X = 0;
const int GameEntity::_DEFAULT_Y = 0;
const std::string GameEntity::_DEFAULT_ART = "*";
GameEntity::GameEntity(void) :
_x(_DEFAULT_X),
_y(_DEFAULT_Y),
_art(_DEFAULT_ART),
_live(1)
{
return;
}
GameEntity::GameEntity(int x, int y, std::string str) :
_x(x),
_y(y),
_art(str),
_live(1)
{
return;
}
GameEntity::GameEntity(GameEntity const & src) {
*this = src;
return;
}
GameEntity::~GameEntity(void) {
return;
}
GameEntity & GameEntity::operator=(GameEntity const & rhs) {
if (this != &rhs)
{
this->_x = rhs._x;
this->_y = rhs._y;
this->_art = rhs._art;
this->_live = rhs._live;
}
return *this;
}
int GameEntity::getX(void) const {
return this->_x;
}
int GameEntity::getY(void) const {
return this->_y;
}
std::string GameEntity::getArt(void) const {
return this->_art;
}
void GameEntity::setX(int x) {
this->_x = x;
if (this->_x < 0)
this->_x = 0;
if (this ->_x > 30)
this->_x = 30;
return;
}
void GameEntity::setY(int y) {
this->_y = y;
if (this->_y < 0)
this->_y = 0;
if (this ->_y > 104)
this->_y = 104;
return;
}
void GameEntity::setArt(std::string const s) {
this->_art = s;
return;
}
bool GameEntity::collidesWith(GameEntity const& other) const
{
return (other.getX() == this->getX()
&& (other.getY() == this->getY() || other.getY() + 1 == this->getY()));
}
void GameEntity::die(void)
{
this->_live = false;
}
bool GameEntity::isAlive(void) const
{
return this->_live;
}
void GameEntity::setAlive(bool live)
{
_live = live;
}
|
fb8710fc46db4a464b176ae2f89b2018b5675e27 | fddcb81537c699e185ce02d878644880cac504e3 | /2.cpp | f487bccffc4042f01141a4a13c5626542386dd96 | [] | no_license | bspy02/ENGG1340-COMP-2113-Assignment-1 | 905e50f3781cb04c7cc086ea2627bdd7905bff4a | 7bc4018a75ea988776a4dec9ae54d5a5acb66451 | refs/heads/master | 2022-12-30T18:26:47.005258 | 2020-10-17T13:41:02 | 2020-10-17T13:41:02 | 299,178,294 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 400 | cpp | 2.cpp | #include <iostream>
using namespace std;
int main()
{
short m,n,a,b,c,d;
cout<< "a: "; cin >> a;
cout<< "b: "; cin >> b;
cout<< "Divisor 1: ";
cin >> c;
cout<< "Divisor 2: ";
cin >> d;
cout<< "M "<< c <<' '<< d << '\n';
for (int i = a; i < b; ++i)
{
int e = (i%c==0);
int f = (i%d==0);
cout<< i <<' ' << e << ' ' << f << '\n';
}
} |
ea2605b1f2c927f9115b6d3697f560b58f8c2f22 | fc48cd25cd7a6a1061a15826c4d5502bee88fe2a | /FinalFramework/Client/Code/UndeadThrowRoute.h | 511228d5cc2ab56e689066b93d931c08700afe36 | [] | no_license | Daruria/CopyProject | 9e3b5ba0f607930b6f58104e9eb52c4f04e2f98f | 672bc7c90aff617d2aa5f087e77f30129565d9a0 | refs/heads/master | 2022-11-20T12:19:03.801310 | 2020-07-26T17:02:55 | 2020-07-26T17:02:55 | 282,668,688 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,084 | h | UndeadThrowRoute.h | #ifndef UndeadThrowRoute_h__
#define UndeadThrowRoute_h__
#include "Defines.h"
#include "MoveOnRoute.h"
BEGIN(Engine)
class CTransform;
END
class CUndeadThrowRoute : public Engine::CMoveOnRoute
{
protected:
explicit CUndeadThrowRoute();
virtual ~CUndeadThrowRoute();
public:
HRESULT Ready_Component(Engine::CTransform* pTransform, const _vec3* pStartPos, const _vec3* pCenterPos, const _vec3* pMoveDir, const _float& fSpeed, const _float& fAngularSpeed);
virtual _int Update_Component(const _float& fTimeDelta) override;
private:
Engine::CTransform* m_pTransform = nullptr;
_vec3 m_vCenterPos = {};
_vec3 m_vAxis = {};
_vec3 m_vOutDir = {};
_vec3 m_vMoveDir;
_float m_fRadius = 0.f;
_float m_fSpeed = 0.1f;
_float m_fAngularSpeed = 0.1f;
_float m_fAngle = 0.f;
public:
static CUndeadThrowRoute* Create(Engine::CTransform* pTransform, const _vec3* pStartPos, const _vec3* pCenterPos, const _vec3* pMoveDir, const _float& fSpeed, const _float& fAngularSpeed);
protected:
virtual void Free() override;
};
#endif // UndeadThrowRoute_h__
|
30ac8e5a398898c3add4bd086a826dbfe4f9aa02 | 30643de1d33317525566a43ef57eb10bd9f77ebc | /USACO/subset.cpp | f19a4631df3342e0c957d5eceecad74677a35cc6 | [] | no_license | RhythmBoys/AlgoContest | 7aad7ba076e8c6c566a1d6ec95aa1b4b1e7a0ab2 | 2a69cc9dd9633e5dc0f108509432e1b97ea92530 | refs/heads/master | 2023-03-17T17:21:28.585335 | 2015-05-23T12:16:14 | 2015-05-23T12:16:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 583 | cpp | subset.cpp | /*
ID: mail.ji1
PROG: subset
LANG: C++11
*/
#include <cstdio>
#include <cstring>
using namespace std;
// dp[i]代表1...N中有多少種子集和為i
long long dp[1000];
int main(void) {
freopen("subset.in", "r", stdin);
freopen("subset.out", "w", stdout);
int n;
while(scanf("%d", &n) != EOF) {
if( (n*(n+1))/2 % 2) { printf("0\n"); continue; }
memset(dp, 0, sizeof(dp));
dp[0] = 1;
for(int i = 1; i <= n; ++i)
for(int j = (n*(n+1))/2 - i; j >= 0; --j) {
dp[j+i] += dp[j];
}
printf("%lld\n", dp[(n*(n+1))/4]/2);
}
return 0;
}
|
8867007056cc29d38218150e65dc21f84cebc8b4 | 51ac5b5b1cb60bccd48c5bba3e2f1a12571d30b0 | /math/B-Spline/BSpline.cpp | 0dd48a99d6db0592d10c6877f20a3e53d9dbee1f | [] | no_license | ZhangPeike/Algorithm | dfc909128a0f7dd7fda5e51633c1dcff46bf3bd1 | ec04e793b513d8101a1fa57cd99c9b0294e62e1d | refs/heads/master | 2020-05-15T16:31:28.810989 | 2020-01-19T09:38:01 | 2020-01-19T09:38:01 | 182,390,245 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,683 | cpp | BSpline.cpp | #include "BSpline.hpp"
namespace bspline_pk {
Eigen::MatrixXd BSpline::M(const int k, const int i) {
if (k == 1) {
Eigen::MatrixXd M(1, 1);
M(0, 0) = 1;
return M;
} else {
Eigen::MatrixXd M_km1 = M(k - 1, i);
Eigen::MatrixXd M1 = Eigen::MatrixXd::Zero(k, k - 1);
Eigen::MatrixXd M2 = Eigen::MatrixXd::Zero(k, k - 1);
M1.topRows(k - 1) = M_km1;
M2.bottomRows(k - 1) = M_km1;
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(k - 1, k);
for (int l = 0; l < k - 1; l++) {
int j = i - k + 2 + l;
A(l, l) = 1 - d0(k, i, j);
A(l, l + 1) = d0(k, i, j);
}
Eigen::MatrixXd B = Eigen::MatrixXd::Zero(k - 1, k);
for (int l = 0; l < k - 1; l++) {
int j = i - k + 2 + l;
B(l, l) -= d1(k, i, j);
B(l, l + 1) = d1(k, i, j);
}
Eigen::MatrixXd M = M1 * A + M2 * B;
return M;
}
}
void BSpline::InitSpline(const Eigen::VectorXd ×,
const Eigen::MatrixXd &interpolation_points,
const int num_segments, const double lambda) {
int num_knots = NumKnotsReq(num_segments);
int num_coeff = NumCoeffReq(num_segments);
int num_dimension = interpolation_points.rows();
std::vector<double> knots(num_knots);
double dt = (times[times.size() - 1] - times[0]) / num_segments;
for (int i = 0; i < num_knots; i++) {
knots[i] = times[0] + (i - spline_order_ + 1) * dt;
}
knots_ = knots;
coeffcients_ = Eigen::MatrixXd::Zero(num_dimension, num_coeff);
basis_matrices_.resize(num_segments);
for (size_t i = 0; i < basis_matrices_.size(); i++) {
basis_matrices_[i] = M(spline_order_, i + spline_order_ - 1);
}
}
} // namespace bspline_pk |
4bd02f3b3d96f509be6fe0c208cc4f7de437f421 | 8ce629133d865500ab547486ae54bcda619acdda | /Source/Native/framework/Utility.h | d5725de30e12c74f8c2a1c8e51495344ed7911de | [] | no_license | PlumpMath/ToolFramework | 56744b76eb41c4d4932d16f9b84b05cf6a5c550a | 86984dcfbeaf1e33d4a9c5476b018cafd46a182a | refs/heads/master | 2020-04-07T06:54:24.362012 | 2017-07-11T05:33:43 | 2017-07-11T05:33:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 806 | h | Utility.h | // FrameSkip.h
#ifndef __FRAMESKIP_H
#define __FRAMESKIP_H
#define FRAME_VELOCITY 40.0f
class CUtility
{
public:
struct sFrameSkip
{
sFrameSkip();
BOOL Skip (void);
int Wait (void);
void GetTime (void);
void ResetFrame (void);
float m_fTime;
int m_nFps;
float m_fRate;
DWORD m_dwTimeSaving;
};
static void ResetFrame();
static BOOL FrameSkip();
static void SetTimer(DWORD dwTime);
static float AngleBetweenV( D3DXVECTOR3 &P1, D3DXVECTOR3 &P2 );
static float FrameSecDist(float speed,DWORD time);
char* GetAssetPath( const string& fileName );
static CUtility& GetInstance();
public:
string m_rootPath;
private:
static sFrameSkip g_FrameSkip;
static DWORD g_dwCurrentTime;
vector<char*> m_store;
};
#define g_Utility CUtility::GetInstance()
#endif |
83bcb6efdd150e5a260b43191344ab00b284bd0c | 92f34c5d36ee1ddb5bb695471520786989c86ec6 | /1012.cpp | bbbd8c2b986839e6a256e9d1586776326fa9b4ec | [] | no_license | yangyiLTS/pat_basic | 74d37f7f38aea1d03bfd8747f91c134a76685f57 | 60140f5ef3d7432a2e17fa8f3022d74f7cdd3d25 | refs/heads/master | 2021-09-05T12:09:27.331637 | 2018-01-27T10:45:23 | 2018-01-27T10:45:23 | 118,708,226 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,666 | cpp | 1012.cpp | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <iomanip>
using namespace std;
/*
段错误
非常的瓜皮
因为分配大量节点时内存超限
有空用数组改写
http://blog.csdn.net/apie_czx/article/details/45200921
http://blog.csdn.net/jk110333/article/details/19685127
*/
struct Node{
int data;
Node *next;
Node *prior;
};
Node *head;
Node *eptr;
void DelElem(Node *N);
int main()
{
int count;
cin >> count;
if (count == 0) {
cout << "N N N N N";
return 0;
}
for (int i = 0; i < count; i++) {
Node *N = new Node;
if (i == 0) {
N->prior = NULL;
head = N;
eptr = N;
cin >> N->data;
}
else if (i < count - 1) {
N->prior = eptr;
eptr->next = N;
cin >> N->data;
eptr = N;
}
else if (i == count - 1) {
N->prior = eptr;
eptr->next = N;
cin >> N->data;
N->next = NULL;
eptr = N;
}
}
/*----------A1----------*/
Node *tag = head;
int A1 = 0, A1flag = 0;
while (1) {
if (tag->data % 5 == 0 && tag->data % 2 == 0) {
A1 += tag->data;
A1flag = 1;
DelElem(tag);
}
if (!tag->next)
break;
tag = tag->next;
}
if (!A1flag) cout << "N ";
else cout << A1 << ' ';
/*----------A2----------*/
tag = head;
int A2 = 0, A2flag = 0;
while (1) {
if (tag->data % 5 == 1) {
A2flag++;
if (A2flag % 2) A2 += tag->data;
else A2 -= tag->data;
DelElem(tag);
}
if (!tag->next)
break;
tag = tag->next;
}
if (!A2flag) cout << "N ";
else cout << A2 << ' ';
/*----------A3----------*/
tag = head;
int A3 = 0, A3flag;
while (1) {
if (tag->data % 5 == 2) {
A3++;
A3flag = 1;
DelElem(tag);
}
if (!tag->next)
break;
tag = tag->next;
}
if (!A3flag) cout << "N ";
else cout << A3 << ' ';
/*----------A4----------*/
tag = head;
float A4 = 0;
int A4flag = 0;
while (1) {
if (tag->data % 5 == 3) {
A4flag++;
A4 += tag->data;
DelElem(tag);
}
if (!tag->next)
break;
tag = tag->next;
}
if (!A4flag) cout << "N ";
else cout << setprecision(1) << setiosflags(ios::fixed) << A4 / A4flag << ' ';
/*----------A5----------*/
tag = head;
int A5 = 0;
while (1) {
if (tag->data % 5 == 4) {
if (tag == head)
A5 = tag->data;
else {
if (tag->data > A5)
A5 = tag->data;
}
}
if (!tag->next)
break;
tag = tag->next;
}
if (!A5) cout << 'N';
else cout << A5;
system("pause");
return 0;
}
void DelElem(Node *N) {
if (N->prior == NULL) {
head = N->next;
N->next->prior = N->prior;
return;
}
if (N->next == NULL) {
eptr = N->prior;
N->prior->next = N->next;
return;
}
N->prior->next = N->next;
N->next->prior = N->prior;
}
// 13 1 2 3 4 5 6 7 8 9 10 20 16 18 |
499b532d56bde274f8b96ad33b1d6d07a7b9d850 | 840a6a470b45b63180634287bf396024f8b9e8ee | /brewchain-crypto/icrypto/src/icrypto_impl.cpp | be888dde6424a90894c5ddc48fc6d3c35fb95a74 | [] | no_license | CryptoWorldChain/crypto | 6863a96839bebec861ade176c70b94d71be343e9 | b3b6f325e7c8003b5df753f3249cca73bab8365c | refs/heads/master | 2020-03-22T02:41:38.782250 | 2018-07-23T09:47:05 | 2018-07-23T09:47:05 | 139,387,183 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,740 | cpp | icrypto_impl.cpp | /* DO NOT EDIT THIS FILE - it is machine generated */
#include "icrypto_jni.h"
#include "icrypto.h"
#include "hash-library/sha256.h"
#include "hash-library/sha3.h"
#include "hash-library/md5.h"
#include "hash-library/keccak.h"
#define RELEASE_ARRAY(__arr,j__arr) if(j__arr!=NULL){ env->ReleaseByteArrayElements(__arr, j__arr, JNI_ABORT); }
typedef unsigned char byte;
/*
* Class: org_brewchain_core_crypto_jni_IPPCrypto
* Method: init
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_org_brewchain_core_crypto_jni_IPPCrypto_init
(JNIEnv *, jobject){
printf("init!!");
}
/*
* Class: org_brewchain_core_crypto_jni_IPPCrypto
* Method: genKeys
* Signature: ([B[B[B)V
*/
JNIEXPORT void JNICALL Java_org_brewchain_core_crypto_jni_IPPCrypto_genKeys
(JNIEnv *env, jobject obj,jbyteArray s, jbyteArray p, jbyteArray x, jbyteArray y){
ICKeyPair256 kp;
int len = 0;
jbyte* js = NULL;
if(s!=NULL){
len = env->GetArrayLength(s) / 4;
if(len>0)
{
js = env->GetByteArrayElements(s, 0);
}
}
genKeyPair(&kp,len,(Ipp32u*)js);
env->SetByteArrayRegion(p, 0,32 ,(jbyte*)kp.p);
env->SetByteArrayRegion(x, 0,32 ,(jbyte*)kp.x);
env->SetByteArrayRegion(y, 0,32 ,(jbyte*)kp.y);
RELEASE_ARRAY(s,js);
}
JNIEXPORT jboolean JNICALL Java_org_brewchain_core_crypto_jni_IPPCrypto_fromPrikey
(JNIEnv *env, jobject obj, jbyteArray p, jbyteArray x, jbyteArray y){
ICKeyPair256 kp;
jbyte* jp =env->GetByteArrayElements(p, 0);
memcpy(kp.p,jp,32);
if(fromPriKey(&kp))
{
env->SetByteArrayRegion(x, 0,32 ,(jbyte*)kp.x);
env->SetByteArrayRegion(y, 0,32 ,(jbyte*)kp.y);
RELEASE_ARRAY(p,jp);
return true;
}else{
RELEASE_ARRAY(p,jp);
return false;
}
}
/*
* Class: org_brewchain_core_crypto_jni_IPPCrypto
* Method: signMessage
* Signature: ([B[B[BLjava/lang/String;[B[B)Z
*/
JNIEXPORT jboolean JNICALL Java_org_brewchain_core_crypto_jni_IPPCrypto_signMessage
(JNIEnv *env, jobject obj, jbyteArray p, jbyteArray x, jbyteArray y, jbyteArray msg, jbyteArray s, jbyteArray a){
jbyte* jp =env->GetByteArrayElements(p, 0);
jbyte* jx =env->GetByteArrayElements(x, 0);
jbyte* jy =env->GetByteArrayElements(y, 0);
jbyte* jmsg = env->GetByteArrayElements(msg, 0);
ICKeyPair256 kp;
memcpy(kp.p,jp,32);
memcpy(kp.x,jx,32);
memcpy(kp.y,jy,32);
if(signMessage(&kp,(Ipp8u*)jmsg)){
env->SetByteArrayRegion(s, 0,32 ,(jbyte*)kp.s);
env->SetByteArrayRegion(a, 0,32 ,(jbyte*)kp.a);
RELEASE_ARRAY(p,jp);
RELEASE_ARRAY(x,jx);
RELEASE_ARRAY(y,jy);
RELEASE_ARRAY(msg,jmsg);
return true;
}
RELEASE_ARRAY(p,jp);
RELEASE_ARRAY(x,jx);
RELEASE_ARRAY(y,jy);
RELEASE_ARRAY(msg,jmsg);
return false;
}
/*
* Class: org_brewchain_core_crypto_jni_IPPCrypto
* Method: verifyMessage
* Signature: ([B[BLjava/lang/String;[B[B)Z
*/
JNIEXPORT jboolean JNICALL Java_org_brewchain_core_crypto_jni_IPPCrypto_verifyMessage
(JNIEnv *env, jobject obj, jbyteArray x, jbyteArray y, jbyteArray msg, jbyteArray s, jbyteArray a){
jbyte* jx =env->GetByteArrayElements(x, 0);
jbyte* jy =env->GetByteArrayElements(y, 0);
jbyte* js =env->GetByteArrayElements(s, 0);
jbyte* ja =env->GetByteArrayElements(a, 0);
jbyte* jmsg = env->GetByteArrayElements(msg, 0);
ICKeyPair256 kp;
memcpy(kp.x,jx,32);
memcpy(kp.y,jy,32);
memcpy(kp.s,js,32);
memcpy(kp.a,ja,32);
if(verifyMessage(&kp,(Ipp8u*)jmsg)){
RELEASE_ARRAY(x,jx);
RELEASE_ARRAY(y,jy);
RELEASE_ARRAY(s,js);
RELEASE_ARRAY(a,ja);
RELEASE_ARRAY(msg,jmsg);
return true;
}
RELEASE_ARRAY(x,jx);
RELEASE_ARRAY(y,jy);
RELEASE_ARRAY(s,js);
RELEASE_ARRAY(a,ja);
RELEASE_ARRAY(msg,jmsg);
return false;
}
JNIEXPORT jstring JNICALL Java_org_brewchain_core_crypto_jni_IPPCrypto_sha3
(JNIEnv *env, jobject obj, jbyteArray x){
jbyte* jx =env->GetByteArrayElements(x, 0);
int len = env->GetArrayLength(x);
if(jx!=NULL&&len>0){
SHA3 sha3;
std::string v = sha3(jx,len);
RELEASE_ARRAY(x,jx);
return env->NewStringUTF( v.c_str());
}
RELEASE_ARRAY(x,jx);
return env->NewStringUTF( "");
}
JNIEXPORT jstring JNICALL Java_org_brewchain_core_crypto_jni_IPPCrypto_sha256
(JNIEnv *env, jobject obj, jbyteArray x){
jbyte* jx =env->GetByteArrayElements(x, 0);
int len = env->GetArrayLength(x);
if(jx!=NULL&&len>0){
SHA256 sha256;
std::string v = sha256(jx,len);
RELEASE_ARRAY(x,jx);
return env->NewStringUTF( v.c_str());
}
RELEASE_ARRAY(x,jx);
return env->NewStringUTF( "");
}
JNIEXPORT jstring JNICALL Java_org_brewchain_core_crypto_jni_IPPCrypto_md5
(JNIEnv *env, jobject obj, jbyteArray x){
jbyte* jx =env->GetByteArrayElements(x, 0);
int len = env->GetArrayLength(x);
if(jx!=NULL&&len>0){
MD5 md5;
std::string v = md5(jx,len);
RELEASE_ARRAY(x,jx);
return env->NewStringUTF(v.c_str());
}
RELEASE_ARRAY(x,jx);
return env->NewStringUTF("");
}
JNIEXPORT jstring JNICALL Java_org_brewchain_core_crypto_jni_IPPCrypto_keccak
(JNIEnv *env, jobject obj, jbyteArray x){
jbyte* jx =env->GetByteArrayElements(x, 0);
int len = env->GetArrayLength(x);
if(jx!=NULL&&len>0){
Keccak keccak;
std::string v = keccak(jx,len);
RELEASE_ARRAY(x,jx);
return env->NewStringUTF( v.c_str());
}
RELEASE_ARRAY(x,jx);
return env->NewStringUTF("");
}
JNIEXPORT jboolean JNICALL Java_org_brewchain_core_crypto_jni_IPPCrypto_bsha3
(JNIEnv *env, jobject obj, jbyteArray x, jbyteArray o){
jbyte* jx =env->GetByteArrayElements(x, 0);
int len = env->GetArrayLength(x);
int dlen = env->GetArrayLength(o);
if(jx!=NULL&&len>0&&dlen>0){
SHA3 sha3;
unique_ptr<byte[]> d(new byte[dlen]);
sha3(jx,len,d.get(),dlen);
env->SetByteArrayRegion(o, 0,dlen ,(jbyte*)d.get());
RELEASE_ARRAY(x,jx);
return true;
}
RELEASE_ARRAY(x,jx);
return false;
}
JNIEXPORT jboolean JNICALL Java_org_brewchain_core_crypto_jni_IPPCrypto_bsha256
(JNIEnv *env, jobject obj, jbyteArray x, jbyteArray o){
jbyte* jx =env->GetByteArrayElements(x, 0);
int len = env->GetArrayLength(x);
int dlen = env->GetArrayLength(o);
if(jx!=NULL&&len>0&&dlen==32){
unique_ptr<byte[]> d(new byte[dlen]);
SHA256 sha256;
sha256(jx,len,d.get(),dlen);
// ippSHA256((Ipp8u *)jx,len,(Ipp8u *)d.get());
env->SetByteArrayRegion(o, 0, dlen ,(jbyte*)d.get());
RELEASE_ARRAY(x,jx);
return true;
}
RELEASE_ARRAY(x,jx);
return false;
}
JNIEXPORT jboolean JNICALL Java_org_brewchain_core_crypto_jni_IPPCrypto_bmd5
(JNIEnv *env, jobject obj, jbyteArray x, jbyteArray o){
jbyte* jx =env->GetByteArrayElements(x, 0);
int len = env->GetArrayLength(x);
int dlen = env->GetArrayLength(o);
if(jx!=NULL&&len>0&&dlen>0){
MD5 md5;
unique_ptr<byte[]> d(new byte[dlen]);
md5(jx,len,d.get(),dlen);
env->SetByteArrayRegion(o, 0,dlen ,(jbyte*)d.get());
RELEASE_ARRAY(x,jx);
return true;
}
RELEASE_ARRAY(x,jx);
return false;
}
JNIEXPORT jboolean JNICALL Java_org_brewchain_core_crypto_jni_IPPCrypto_bkeccak
(JNIEnv *env, jobject obj, jbyteArray x, jbyteArray o){
jbyte* jx =env->GetByteArrayElements(x, 0);
int len = env->GetArrayLength(x);
int dlen = env->GetArrayLength(o);
if(jx!=NULL&&len>0&&dlen>0){
Keccak keccak;
unique_ptr<byte[]> d(new byte[dlen]);
keccak(jx,len,d.get(),dlen);
env->SetByteArrayRegion(o, 0,dlen ,(jbyte*)d.get());
RELEASE_ARRAY(x,jx);
return true;
}
RELEASE_ARRAY(x,jx);
return false;
}
|
c435451f6b655432b21d21e2c5a306523e2165d7 | 7d7b1edeee921e1e7b367abd2cb66bcdac0579ce | /FreqOfNotes/XNotes.h | 36e12da2ba61b44b30d4d78a91be42a8dc863203 | [] | no_license | W-Mai/FreqOfNotes | c4a4a0559122b5ef99e02e562dc726397bebf229 | 973f62add90d3842bbedf821bce6911001365fa3 | refs/heads/master | 2020-04-23T11:30:58.923882 | 2019-03-23T01:34:13 | 2019-03-23T01:34:13 | 171,139,185 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 584 | h | XNotes.h | #pragma once
#include "XMainHeader.h"
typedef double Freq;
typedef int Major;
typedef struct Notes {
char name[3];
Major major;
} Notes;
class XNotesManager {
private:
Freq BASE = 440.00; // A4
const double DEGREE = 1.0594630943592953;
const double DEGREE_1 = 0.9438743126816935;
const int GREAT_DEGREE[]{ 0, 2, -9, -7, -5, -4, -2 };
public:
int getDeltaNoteDis(int note, int stage);
int * analyseNote(const char * notes);
Major getNotes(const Freq freq);
Freq getFreq_rela(const int notes);
XNotesManager(const Freq baseFreq = 440.00);
~XNotesManager();
};
|
e98088fed7e08d81e36c743f8dd5c059c8385ee6 | 6aeccfb60568a360d2d143e0271f0def40747d73 | /sandbox/async/boost/async/algorithm/get_until.hpp | c34e151379143dc7bfcc7636cfab0d9315c86bcf | [] | no_license | ttyang/sandbox | 1066b324a13813cb1113beca75cdaf518e952276 | e1d6fde18ced644bb63e231829b2fe0664e51fac | refs/heads/trunk | 2021-01-19T17:17:47.452557 | 2013-06-07T14:19:55 | 2013-06-07T14:19:55 | 13,488,698 | 1 | 3 | null | 2023-03-20T11:52:19 | 2013-10-11T03:08:51 | C++ | UTF-8 | C++ | false | false | 2,700 | hpp | get_until.hpp | //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Vicente J. Botet Escriba 2008-2009. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/async for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_ASYNC_GET_UNTIL__HPP
#define BOOST_ASYNC_GET_UNTIL__HPP
#include <boost/fusion/include/transform.hpp>
#include <boost/fusion/include/size.hpp>
#include <boost/fusion/include/at_c.hpp>
#include <boost/fusion/include/pop_front.hpp>
#include <boost/fusion/include/push_front.hpp>
#include <utility>
#include <boost/utility/enable_if.hpp>
#ifdef BOOST_HAS_CHRONO_LIB
#include <boost/chrono/chrono.hpp>
#else
#include <boost/thread/thread_time.hpp>
#endif
#include <boost/async/algorithm/wait_until.hpp>
#include <boost/config/abi_prefix.hpp>
namespace boost {
namespace async {
namespace result_of {
template <typename ACT>
struct get_until {
typedef typename act_traits<ACT>::move_dest_type type;
};
}
namespace result_of {
template <typename ACT, typename Duration>
struct get_for {
typedef typename act_traits<ACT>::move_dest_type type;
};
}
namespace partial_specialization_workaround {
template< typename ACT >
struct get_until {
static typename result_of::template get_until<ACT>::type apply( ACT& act, const system_time& abs_time ) {
async::wait_until(act, abs_time);
return act.get();
}
};
template< typename ACT, typename Duration>
struct get_for {
static typename result_of::template get_for<ACT,Duration>::type apply( ACT& act, Duration rel_time ) {
async::wait_for(act, rel_time);
return act.get();
}
};
}
template <typename ACT>
typename boost::enable_if<has_future_if<ACT>,
typename result_of::template get_until<ACT>::type
>::type get_until(ACT& act, const system_time& abs_time) {
return partial_specialization_workaround::get_until<ACT>::apply(act, abs_time);
}
template <typename ACT, typename Duration>
typename boost::enable_if<has_future_if<ACT>,typename result_of::template get_for<ACT,Duration>::type >::type
get_for(ACT& act, Duration rel_time) {
return partial_specialization_workaround::get_for<ACT, Duration>::apply(act, rel_time);
}
}
} // namespace boost
#include <boost/config/abi_suffix.hpp>
#endif
|
8b77c904885640ff1e3050fc981d6f273808da66 | 95acccaad0bac999ced5dccc4cd5db30a2b0060f | /CharShiftTime/src/CharShiftTime.cpp | 1ab18b06683ba7d9e61d74dcd32637d30ea85af8 | [] | no_license | gokaykacan/Cpp-works | 26f65d652957e68cdbc5ccfa7f93140d9f0d2674 | 6b5b51af5f545f82e9b555eca2bfe542543b80e3 | refs/heads/master | 2021-12-27T14:22:11.337977 | 2021-11-24T11:57:43 | 2021-11-24T11:57:43 | 168,695,659 | 0 | 1 | null | null | null | null | MacCentralEurope | C++ | false | false | 1,394 | cpp | CharShiftTime.cpp | //============================================================================
// Name : CharShiftTime.cpp
// Author : Gokay Kacan
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <algorithm>
#include "string.h"
using namespace std;
//this function returns how many times str1 is rotated to right at str2
int CharShiftTime(char* str1, char* str2){
int n=-1;
unsigned int size1 = strlen(str1);
unsigned int size2 = strlen(str2);
int flag = 0;
cout << "size1: " << size1 << ", size2: " << size2 << endl;
if(size1 != size2){
return n;
}
if(*str1 == *str2)//if they are equal, return 0 immediately
return 0;
for(unsigned int i=1; i<size1; i++){
if(str1[0] == str2[i]){
for(unsigned int j=0; j<size2; j++){
if((i+j) < size1){
if(str1[j] == str2[j+i])
flag = 1;
else
flag =0;
}
else{
if(str1[j] == str2[(j+i)-size1])
flag = 1;
else
flag = 0;
}
if(!flag) // if one element are not equal, increment shift time
i=i+1;
}
if(flag){
n = i;
break;
}
}
}
return n;
}
int main() {
char str1[] = "coffee";
char str2[] = "eecoff";
cout << "SonuÁ: " << CharShiftTime(str1, str2) << endl;
return 0;
}
|
a2ddb582d4216a6b684ff4277ca8acce5fc8fbed | f6af9cb6f5be53ce4b93e8cdaf2ca2fd0ac9d6c8 | /Codechef/PLMU - Plus Multiply.cpp | 85b1afd19c9b7e603d19c46d9d87d3eb3a16d60c | [] | no_license | KhanShaheb34/Solved-OJ-Problems | 1731996b9c71e8174e69ca0edf8d6e05eca67c11 | 8e744137a386c1798a5723f9cc3a988b18f158c0 | refs/heads/master | 2021-08-26T08:58:26.222918 | 2021-08-18T21:46:36 | 2021-08-18T21:46:36 | 169,293,476 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,036 | cpp | PLMU - Plus Multiply.cpp |
/*
* @site Codechef
* @problem_no PLMU
* @problem_name Plus Multiply
* @author KhanShaheb
* @Language C++
* @status
* @time
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<int> vi;
inline void fast_io() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); }
#define INF 1000000000
#define endl '\n'
#define ashche cerr<<"Ekhane Ashche!"<<endl
#define mem(a,x) memset(a,x,sizeof(a))
#define fout(x) fixed<<setprecision(x)
const int mod=1e9+7;
int main()
{
fast_io();
int q; // FOR TESTCASES
cin >> q;
while(q--)
{
int n, twos = 0, z = 0, num;
cin >> n;
while(n--) {
cin >> num;
if(num == 2) twos++;
if(num == 0) z++;
}
twos = (twos * (twos-1)) / 2;
z = (z * (z-1)) / 2;
cout << twos + z << endl;
}
return 0;
} |
2cbf02ca9a896e0d09c985066c030bb660d3c4e9 | 81a37a6ffd3879358a499e12600fb81583d06b00 | /main.cpp | 4c02b627a23eeed7c2649aee2c708b309db3bcb3 | [] | no_license | binbinmeng/datastruct_algrithom | 298b7db3df03315e1244ac55bf550abfd08addc8 | 073349239cd7e01da974cb263f11a12fb2afac1f | refs/heads/master | 2020-03-26T19:26:28.830138 | 2018-08-21T03:01:42 | 2018-08-21T03:01:42 | 145,265,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,802 | cpp | main.cpp | #include <iostream>
#include "ArrayStack.h"
#include "ListStack.h"
#include "SingleDirectionList.h"
#include "BinaryTree.h"
#include "string"
#include "RingList.h"
#include "vector"
int stack_test() {
ArrayStack * stack = new ArrayStack();
stack->pop();
stack->showStack();
stack->push(5);
stack->push(3);
stack->push(2);
stack->push(6);
std::cout<<"top : "<<stack->getTop()<<std::endl;
stack->push(9);
stack->showStack();
stack->deleteStack();
stack->showStack();
delete stack;
return 0;
}
int list_stack_test()
{
ListStack * liststack = new ListStack();
liststack->pop();
liststack->push(5);
liststack->push(3);
liststack->push(2);
liststack->push(6);
//liststack->showStack();
liststack->pop();
//liststack->showStack();
liststack->deleteStack();
liststack->showStack();
delete liststack;
return 0;
}
bool palindrome_alg1(std::string in_string){
/*
* Judge a string if is a palindrome or not
*
*/
int start =0;
int end =in_string.length()-1;
while(start <= end)
{
if(in_string[start]==in_string[end]){
end--;
start++;
} else{
return false;
}
}
return true;
}
void redix_convert(std::string in_string, int src_redix, int dst_redix)
{
/*
* given a decimal number, convert it to any redix number
*/
ArrayStack *arrayStack =new ArrayStack();
long data = atoi(in_string.c_str());
while(data/dst_redix > 0)
{
arrayStack->push(data%dst_redix);
data = data/dst_redix;
}
arrayStack->push(data%dst_redix);
arrayStack->showStack();
delete arrayStack;
}
int gcd(int a, int b)
{
/*
*Caculate greatest common divisor of a,b
*
*/
/* if(b == 0)
return a;
gcd(b,a%b);
*
*/
while(b !=0 )
{
int temp;
temp = a;
a = b;
b = temp%b;
}
return a;
}
int test_single_direction_list()
{
int data[7] ={1,2,2,3,4,5,6};
SingleDirectionList * list = new SingleDirectionList(data,7);
list->Show();
std::cout<<list->Length()<<std::endl;
//list->Delete(6);
//list->Show();
//std::cout<<list->Length()<<std::endl;
//list->Insert(3,8);
//list->Show();
//std::cout<<list->Length()<<std::endl;
SingleDirectionList * reverselist = new SingleDirectionList(list->Reverse(list->HeadNode()));
reverselist->Show();
std::cout<<reverselist->Length()<<std::endl;
//list->Insert(9);
//list->Show();
//std::cout<<list->Length()<<std::endl;
//list->Delete_Duplication();
//list->Insert(9);
//std::cout<<list->FindMiddleNode(list->HeadNode())->data<<std::endl;
//list->ReverseShow(list->HeadNode());
list->Show();
std::cout<<list->Length()<<std::endl;
}
void test_binary_tree()
{
BinaryTree * tree = new BinaryTree();
printf("-----previst-----\n");
tree->PreOderVist(tree->GetRoot());
printf("-----postvist-----\n");
tree->PostOderVist(tree->GetRoot());
printf("-----middlevist-----\n");
tree->MiddleOderVist(tree->GetRoot());
}
void test_ringlist()
{
int array[15] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
RingList * ringlist = new RingList(array, 15);
ringlist->Show();
ringlist->DeleteSkipElement(4);
//ringlist->Show();
}
int main()
{
//stack_test();
//list_stack_test();
//std::cout<<palindrome_alg1("hellolleh")<<std::endl;
//redix_convert("1099",10,16);
//std::cout<<gcd(30,21)<<std::endl;
//test_single_direction_list();
//test_binary_tree();
test_ringlist();
std::cout << "Hello, World!" << std::endl;
} |
0965d64f9546f25f54df06728187af0c379565a3 | 4cdbf32fb134311cb138fad731ec856a7ac0b0eb | /rtmp_amf0.cpp | 12d013d4b8987af00ac0733e7077cf5ec66ff465 | [] | no_license | qhzxz/simple-rtmp-client | 3972b017768596b030f922c925b3e961117632c9 | 7588d31e6ce55ed1c1e0c9dde537ef10b79c1fe9 | refs/heads/master | 2020-04-06T06:52:43.043215 | 2016-09-18T02:28:54 | 2016-09-18T02:28:54 | 65,205,931 | 1 | 0 | null | 2016-08-09T07:13:50 | 2016-08-08T13:21:39 | C | UTF-8 | C++ | false | false | 10,758 | cpp | rtmp_amf0.cpp | //
// Created by 秦汉 on 16/7/16.
//
//#include <iostream>
#include <iostream>
#include <spdlog/spdlog.h>
#include "rtmp_amf0.h"
#include "rtmp_utility.h"
#include "rtmp_log.h"
AmfData::~AmfData() {
}
int AmfArray::getSize() {
if (size == -1) {
size = 5; // 1 + 4:1 byte for AmfType ,4 bytes for its length
if (items != NULL) {
for (std::vector<AmfData *>::iterator begin = items->begin(); begin != items->end(); ++begin) {
AmfData *data = *begin;
size += data->getSize();
}
}
}
return size;
}
AmfArray::~AmfArray() {
clear();
}
void AmfArray::clear() {
if (NULL != items) {
for (auto begin = items->begin(); begin != items->end(); ++begin) {
AmfData *data = *begin;
delete data;
}
items->clear();
delete items;
items = NULL;
}
}
AmfArray::AmfArray() {
items = new std::vector<AmfData *>;
}
const std::vector<AmfData *> *AmfArray::getitems() {
if (NULL != items) {
return items;
}
return NULL;
}
void AmfArray::addItems(AmfData *data) {
if (NULL != items) {
items->push_back(data);
} else {
delete data;
}
}
void AmfArray::writeTo(RtmpStream *stream) {}
void AmfArray::readFrom(RtmpStream *stream) {
// Skip data type byte (we assume it's already read)
int length = readUnsignedInt32(stream);
size = 5; // 1 + 4
if (NULL != items) {
clear();
}
items = new std::vector<AmfData *>(length);
for (int i = 0; i < length; i++) {
AmfData *dataItem = AmfDecoder::decode(stream);
size += dataItem->getSize();
items->push_back(dataItem);
}
}
int AmfBoolean::getSize() {
return 2;
}
bool AmfBoolean::readBooleanFrom(RtmpStream *stream) {
// Skip data type byte (we assume it's already read)
return (stream->read_1byte() == 0x01) ? true : false;
}
void AmfBoolean::readFrom(RtmpStream *stream) {
value = (stream->read_1byte() == 0x01) ? true : false;
}
void AmfBoolean::writeTo(RtmpStream *stream) {
stream->write_1byte(AMF0_BOOLEAN);
stream->write_1byte(value ? 0x01 : 0x00);
}
bool AmfBoolean::isValue() {
return value;
}
void AmfBoolean::setValue(bool value) {
this->value = value;
}
AmfBoolean::AmfBoolean(bool value) : value(value) {
}
AmfBoolean::AmfBoolean() {
}
AmfString::AmfString() {}
AmfString::AmfString(std::string value) : value(value) {}
std::string AmfString::getValue() {
return value;
}
void AmfString::setValue(std::string value) {
this->value = value;
}
void AmfString::writeTo(RtmpStream *stream) {
stream->write_1byte(AMF0_STRING);
// Write 2 bytes indicating string length
writeUnsignedInt16(stream, value.length());
// Write string
stream->write_bytes((byte *) value.data(), value.length());
}
void AmfString::readFrom(RtmpStream *stream) {
// Skip data type byte (we assume it's already read)
int length = readUnsignedInt16(stream);
size = 3 + length; // 1 + 2 + length
// Read string value
byte byteValue[length];
readBytesUntilFull(stream, byteValue, length);
value = std::string((char *) byteValue, length);
}
int AmfString::getSize() {
if (size == -1) {
size = 1 + 2 + value.length();
}
return size;
}
void AmfNumber::writeTo(RtmpStream *stream) {
stream->write_1byte(AMF0_NUMBER);
writeDouble(stream, value);
}
void AmfNumber::setValue(double value) {
this->value = value;
}
int AmfNumber::getSize() {
return SIZE;
}
AmfNumber::AmfNumber(double value) : value(value) {}
AmfNumber::AmfNumber() {}
double AmfNumber::getValue() {
return value;
}
double AmfNumber::readNumberFrom(RtmpStream *in) {
// Skip data type byte
in->read_1byte();
return readDouble(in);
}
void AmfNumber::readFrom(RtmpStream *stream) {
value = readDouble(stream);
}
const byte AmfObject::OBJECT_END_MARKER[3] = {0x00, 0x00, 0x09};
AmfObject::AmfObject() {
properties = new PropertyMap;
}
AmfData *AmfObject::getProperty(std::string key) {
AmfData *pData = NULL;
PropertyMap::iterator it = properties->find(key);
if (it != properties->end()) {
pData = (*it).second;
}
return pData;
}
void AmfObject::setDataProperty(std::string key, AmfData *value) {
PropertyPair pair(key, value);
properties->insert(pair);
}
void AmfObject::setBoolProperty(std::string key, bool value) {
PropertyPair pair(key, new AmfBoolean(value));
properties->insert(pair);
}
void AmfObject::setStringProperty(std::string key, std::string value) {
PropertyPair pair(key, new AmfString(value));
properties->insert(pair);
}
void AmfObject::setIntProperty(std::string key, int value) {
PropertyPair pair(key, new AmfNumber(value));
properties->insert(pair);
}
void AmfObject::setDoubleProperty(std::string key, double value) {
PropertyPair pair(key, new AmfNumber(value));
properties->insert(pair);
}
void AmfObject::writeTo(RtmpStream *out) {
// Begin the object
out->write_1byte(AMF0_OBJECT);
// Write key/value pairs in this object
for (PropertyMap::iterator mapIterator = properties->begin(); mapIterator != properties->end(); ++mapIterator) {
// The key must be a AMF0_STRING type, and thus the "type-definition" byte is implied (not included in message)
std::string key = (*mapIterator).first;
AmfData *data = (*mapIterator).second;
writeUnsignedInt16(out, key.length());
if (key.length() > 0) {
out->write_bytes((byte *) key.c_str(), key.length());
}
data->writeTo(out);
}
// End the object
out->write_bytes((byte *) OBJECT_END_MARKER, 3);
}
void AmfObject::readFrom(RtmpStream *in) {
// Skip data type byte (we assume it's already read)
RtmpByteArrayStream *byte_arr = dynamic_cast<RtmpByteArrayStream *>(in);
if (byte_arr == NULL) {
return;
}
size = 1;
while (!byte_arr->empty()) {
// Look for the 3-byte object end marker [0x00 0x00 0x09]
byte endMarker[3];
byte_arr->read_bytes(endMarker, 3);
if (endMarker[0] == OBJECT_END_MARKER[0] && endMarker[1] == OBJECT_END_MARKER[1] &&
endMarker[2] == OBJECT_END_MARKER[2]) {
// End marker found
size += 3;
return;
} else {
// End marker not found; reset the stream to the marked current_position_pointer and read an AMF property
byte_arr->skip(-3);
// Read the property key...
int length = readUnsignedInt16(byte_arr);
// Read string value
byte byteValue[length];
readBytesUntilFull(byte_arr, byteValue, length);
std::string key = std::string((char *) byteValue, length);
int key_length = 2 + length;
size += key_length;
// ...and the property value
AmfData *value = AmfDecoder::decode(byte_arr);
size += value->getSize();
PropertyPair pair(key, value);
properties->insert(pair);
}
}
}
int AmfObject::getSize() {
if (size == -1) {
size = 1; // object marker
for (PropertyMap::iterator mapIterator = properties->begin(); mapIterator != properties->end(); ++mapIterator) {
// The key must be a AMF0_STRING type, and thus the "type-definition" byte is implied (not included in message)
std::string key = (*mapIterator).first;
size += (2 + key.length());// 2 byte for key length
AmfData *data = (*mapIterator).second;
size += data->getSize();
}
size += 3; // end of object marker
}
return size;
}
AmfObject::~AmfObject() {
for (PropertyMap::iterator mapIterator = properties->begin(); mapIterator != properties->end(); ++mapIterator) {
// The key must be a AMF0_STRING type, and thus the "type-definition" byte is implied (not included in message)
AmfData *data = (*mapIterator).second;
delete data;
data = NULL;
}
properties->clear();
}
void AmfEcmaArray::writeTo(RtmpStream *out) {
// Begin the object
out->write_1byte(AMF0_MAP);
// Write key/value pairs in this object
writeUnsignedInt32(out, properties->size());
for (auto mapIterator = properties->begin(); mapIterator != properties->end(); ++mapIterator) {
// The key must be a AMF0_STRING type, and thus the "type-definition" byte is implied (not included in message)
std::string key = (*mapIterator).first;
AmfData *data = (*mapIterator).second;
writeUnsignedInt16(out, key.length());
if (key.length() > 0) {
out->write_bytes((byte *) key.c_str(), key.length());
}
data->writeTo(out);
}
// End the object
out->write_bytes((byte *) OBJECT_END_MARKER, 3);
}
void AmfEcmaArray::readFrom(RtmpStream *in) {
int32_t length = readUnsignedInt32(in);
AmfObject::readFrom(in);
size += 4;
}
int AmfEcmaArray::getSize() {
if (size == -1) {
size = AmfObject::getSize();
size += 4;
}
return size;
}
void AmfNull::writeTo(RtmpStream *stream) {
stream->write_1byte(AMF0_NULL);
}
void AmfNull::writeNullTo(RtmpStream *stream) {
stream->write_1byte(AMF0_NULL);
}
void AmfNull::readFrom(RtmpStream *stream) {}
int AmfNull::getSize() { return 1; }
int AmfUndefined::getSize() { return 1; }
void AmfUndefined::writeTo(RtmpStream *stream) {
stream->write_1byte(AMF0_UNDEFINED);
}
void AmfUndefined::writeUndefinedTo(RtmpStream *stream) {
stream->write_1byte(AMF0_UNDEFINED);
}
void AmfUndefined::readFrom(RtmpStream *stream) {}
AmfData *AmfDecoder::decode(RtmpStream *stream) {
byte amfTypeByte = stream->read_1byte();
AmfType amfType = AmfType(amfTypeByte);
AmfData *amfData = NULL;
switch (amfType) {
case AMF0_NUMBER:
amfData = new AmfNumber;
break;
case AMF0_BOOLEAN:
amfData = new AmfBoolean;
break;
case AMF0_STRING:
amfData = new AmfString;
break;
case AMF0_OBJECT:
amfData = new AmfObject;
break;
case AMF0_NULL:
return new AmfNull;
case AMF0_UNDEFINED:
return new AmfUndefined;
case AMF0_MAP:
amfData = new AmfEcmaArray;
break;
case AMF0_ARRAY:
amfData = new AmfArray;
break;
default:
RTMP_LOG_INFO("unknow AMF0 TYPE:{0:x}", amfTypeByte);
break;
}
if (NULL != amfData) {
amfData->readFrom(stream);
}
return amfData;
} |
47ba90f2fe53808f562e0b3f17ab86330df02cb0 | 7d64e03e403eca85248677d8dc72751c93940e48 | /tool/dbgen/MojDbGen.cpp | e82a9a309896acf8759efb0676269507eae2d997 | [
"Apache-2.0"
] | permissive | webosce/db8 | a6f6ec64d3cb8653dc522ee7a3e8fad78fcc0203 | 994da8732319c6cafc59778eec5f82186f73b6ab | refs/heads/webosce | 2023-05-13T15:18:39.562208 | 2018-08-23T08:51:14 | 2018-09-14T13:30:43 | 145,513,369 | 0 | 1 | Apache-2.0 | 2023-04-26T02:43:57 | 2018-08-21T05:52:45 | C++ | UTF-8 | C++ | false | false | 4,188 | cpp | MojDbGen.cpp | // Copyright (c) 2009-2018 LG Electronics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#include "db/MojDb.h"
#include "core/MojUtil.h"
#include <vector>
enum class DATA_TYPE {
dataTypeKind,
dataTypePermission,
dataTypeObject,
};
//DBGen
MojErr genDbImage(const MojChar* dirPath, MojDb& db, DATA_TYPE type)
{
// open dir
MojString entryPath;
MojDirT dir = MojInvalidDir;
MojErr err = MojDirOpen(dir, dirPath);
MojErrCheck(err);
//process files from directory path
for(;;){
bool entRead = false;
MojDirentT ent;
err = MojDirRead(dir, &ent, entRead);
MojErrGoto(err, Done);
if (!entRead)
break;
if (MojStrCmp(ent.d_name, _T(".")) == 0 ||MojStrCmp(ent.d_name, _T("..")) == 0)
continue;
entryPath.clear();
entryPath.append(dirPath);
entryPath.append(ent.d_name);
MojStatT stat;
MojErr err = MojStat(entryPath.data(), &stat);
MojErrGoto(err, Done);
if (stat.st_mode & S_IFREG){
if (type == DATA_TYPE::dataTypeObject) {
MojUInt32 count;
err = db.load(entryPath.data(), count);
} else {
MojString inputStr;
MojObject inputObj;
err = MojFileToString(entryPath.data(), inputStr);
MojErrGoto(err, Done);
err = inputObj.fromJson(inputStr);
MojErrGoto(err, Done);
if (type == DATA_TYPE::dataTypeKind) {
err = db.putKind(inputObj);
} else if (type == DATA_TYPE::dataTypePermission) {
// permission files form with array object
MojObject::ArrayIterator begin;
err = inputObj.arrayBegin(begin);
MojErrGoto(err, Done);
MojObject::ConstArrayIterator end = inputObj.arrayEnd();
err = db.putPermissions(begin, end);
}
}
MojErrGoto(err, Done);
} else {
// there are must be regular files.
err = MojErrUnknown;
MojErrGoto(err, Done);
}
}
Done:
if (dir != MojInvalidDir)
(void) MojDirClose(dir);
return err;
}
int main(int argc, char**argv)
{
if (argc < 3) {
LOG_ERROR(MSGID_DB_ERROR, 0, "Invalid arg, This program need two args(input and output path)");
return -1;
}
typedef struct {
const MojChar* dirName;
DATA_TYPE type;
} DBGEN_T;
const std::vector<DBGEN_T> dbGenType { {_T("kinds/"), DATA_TYPE::dataTypeKind},
{_T("permissions/"), DATA_TYPE::dataTypePermission},
{_T("data/"), DATA_TYPE::dataTypeObject}
};
MojDb db;
MojString dirName;
MojErr err = db.open(argv[2]);
MojErrCheck(err);
/* find each sub dir(1.kind -> 2.permissions -> 3.data) */
for (auto iter = dbGenType.begin(); iter != dbGenType.end(); ++iter )
{
dirName.clear();
dirName.append(argv[1]);
dirName.append(iter->dirName);
err = genDbImage(dirName.data(), db, iter->type);
if (err != MojErrNone) {
MojString str;
MojErrToString(err, str);
LOG_ERROR(MSGID_DB_ERROR, 1,
PMLOGKS("data", str.data()),
"error occured during generating DB image");
db.drop(argv[2]);
break;
}
}
db.close();
return 0;
}
|
80bf5e0c2baefb3ef5771a732888160a529acdae | 6f460b783d9427222581bf1ffa8938174e26fa50 | /include/Compressor/AbstractCompressor.h | d1dbe53dbf873ca120f90b581b29a4f3d9506a7a | [] | no_license | dvalenzu/FRESCO | ece4e1af56dba0520aae64f89405a90646eb0ff3 | 418d7cacb51a0a10b75cc15087bb4dc4b421bd92 | refs/heads/master | 2020-05-14T15:16:27.039613 | 2019-04-25T21:20:17 | 2019-04-25T21:20:17 | 181,849,459 | 0 | 0 | null | 2019-04-17T08:29:04 | 2019-04-17T08:29:03 | null | UTF-8 | C++ | false | false | 1,933 | h | AbstractCompressor.h | #ifndef ABSTRACTCOMPRESSOR_H_INCLUDED
#define ABSTRACTCOMPRESSOR_H_INCLUDED
class ReferentialMatchEntry
{
public:
ReferentialMatchEntry(long _pos, long _length, char _mismatchchar, long _mismatchcount)
{
pos=_pos;
length=_length;
mismatchchar=_mismatchchar;
mismatchcount=_mismatchcount;
}
long getTotalLength()
{
return length+mismatchcount;
}
string toString()
{
string result;
result="("+boost::lexical_cast<string>(pos)+","+boost::lexical_cast<string>(length)+","+mismatchchar+","+boost::lexical_cast<string>(mismatchcount)+")";
return result;
}
bool operator<( const ReferentialMatchEntry& other ) const
{
if (pos==other.pos)
{
if (length==other.length)
{
if (mismatchchar==other.mismatchchar)
return mismatchcount<other.mismatchcount;
else
{
return mismatchchar<other.mismatchchar;
}
} else
{
return length<other.length;
}
}else
return pos<other.pos;
}
bool operator==( const ReferentialMatchEntry& other ) const
{
if (pos!=other.pos) return false;
if (length!=other.length) return false;
if (mismatchchar!=other.mismatchchar) return false;
if (mismatchcount!=other.mismatchcount) return false;
return true;
}
int pos;
int length;
int mismatchcount;
char mismatchchar;
};
class AbstractCompressor
{
public:
virtual ~AbstractCompressor(){};
virtual void compress(AbstractSequence *seq, AbstractIndex *ci, vector<ReferentialMatchEntry> &outputRMEs) {};
virtual void decompress(vector<ReferentialMatchEntry> inputRMEs, AbstractIndex *ci, AbstractSequence *seq) {};
};
#endif // ABSTRACTCOMPRESSOR_H_INCLUDED
|
77f638d33ca850b3a47b6605ed3b88940fc86666 | 88812e7dd2802c48403dba2d71341bbcf89d4fdc | /src/ofxLibRocketSystemInterface.cpp | 110592a037ad96e5c27fbd936d6fd3797a732db1 | [] | no_license | underdoeg/ofxLibRocket | d8f630db4201b5ba7c53d380b78ab44d735921a5 | 14360ed8fd3428aa0a2e052f6363e5daa0bf0d75 | refs/heads/master | 2020-04-18T09:16:59.567723 | 2013-02-22T11:16:37 | 2013-02-22T11:16:37 | 3,849,045 | 13 | 5 | null | 2013-02-22T11:16:38 | 2012-03-27T22:03:18 | C++ | UTF-8 | C++ | false | false | 1,189 | cpp | ofxLibRocketSystemInterface.cpp | #include "ofxLibRocketSystemInterface.h"
#include "ofMain.h"
using namespace Rocket::Core;
ofxLibRocketSystemInterface::ofxLibRocketSystemInterface() {
}
ofxLibRocketSystemInterface::~ofxLibRocketSystemInterface() {
}
void ofxLibRocketSystemInterface::ActivateKeyboard() {
}
void ofxLibRocketSystemInterface::DeactivateKeyboard() {
}
float ofxLibRocketSystemInterface::GetElapsedTime() {
return ofGetElapsedTimef();
}
bool ofxLibRocketSystemInterface::LogMessage(Log::Type type, const String& message) {
ofLogLevel level = OF_LOG_SILENT;
switch(type) {
case Log::LT_ERROR:
level = OF_LOG_ERROR;
break;
case Log::LT_ALWAYS:
level = OF_LOG_NOTICE;
break;
case Log::LT_ASSERT:
level = OF_LOG_FATAL_ERROR;
break;
case Log::LT_WARNING:
level = OF_LOG_WARNING;
break;
case Log::LT_INFO:
level = OF_LOG_NOTICE;
break;
case Log::LT_DEBUG:
level = OF_LOG_NOTICE;
break;
case Log::LT_MAX:
level = OF_LOG_FATAL_ERROR;
break;
}
ofLog(level, message.CString());
return true;
}
int ofxLibRocketSystemInterface::TranslateString(String& translated, const String& input) {
translated = input;
return 0;
}
void ofxLibRocketSystemInterface::Release()
{
}
|
af09e2547aac79901af21311f328aa621fe23013 | da86d9f9cf875db42fd912e3366cfe9e0aa392c6 | /2017/solutions/C/VIK-Ruse/color.cpp | 0fc4fb55b9fe53bd01e5e00e7c939002ca23e796 | [] | no_license | Alaxe/noi2-ranking | 0c98ea9af9fc3bd22798cab523f38fd75ed97634 | bb671bacd369b0924a1bfa313acb259f97947d05 | refs/heads/master | 2021-01-22T23:33:43.481107 | 2020-02-15T17:33:25 | 2020-02-15T17:33:25 | 85,631,202 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 524 | cpp | color.cpp | #include<iostream>
using namespace std;
int arr[100001];
int main ()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int t,n,i,j,x,maxi=0;
cin>>t;
for(i=0;i<t;i++)
{
cin>>n;
for(j=0;j<n;j++)
{
cin>>x;
arr[x]++;
if(arr[x]>maxi)maxi=arr[x];
}
cout<<maxi+1<<endl;
maxi=0;
for(j=1;j<=n;j++)arr[j]=0;
}
return 0;
} |
2537db8eae7764bc6d4f9f357de25db80310a2ce | 65e3391b6afbef10ec9429ca4b43a26b5cf480af | /TEvtGen/EvtGen/EvtGenBase/EvtParticleDecay.cpp | 10f87a48da3b66052b412346012e707cabe57580 | [] | permissive | alisw/AliRoot | c0976f7105ae1e3d107dfe93578f819473b2b83f | d3f86386afbaac9f8b8658da6710eed2bdee977f | refs/heads/master | 2023-08-03T11:15:54.211198 | 2023-07-28T12:39:57 | 2023-07-28T12:39:57 | 53,312,169 | 61 | 299 | BSD-3-Clause | 2023-07-28T13:19:50 | 2016-03-07T09:20:12 | C++ | UTF-8 | C++ | false | false | 1,938 | cpp | EvtParticleDecay.cpp | //--------------------------------------------------------------------------
//
// Environment:
// This software is part of the EvtGen package developed jointly
// for the BaBar and CLEO collaborations. If you use all or part
// of it, please give an appropriate acknowledgement.
//
// Copyright Information: See EvtGen/COPYRIGHT
// Copyright (C) 1998 Caltech, UCSB
//
// Module: EvtDecayParm.cc
//
// Description: Store decay parameters for one decay.
//
// Modification history:
//
// RYD April 5, 1997 Module created
//
//------------------------------------------------------------------------
//
#include "EvtGenBase/EvtPatches.hh"
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <ctype.h>
#include "EvtGenBase/EvtParticleDecay.hh"
#include "EvtGenBase/EvtParticle.hh"
#include "EvtGenBase/EvtRandom.hh"
#include "EvtGenBase/EvtReport.hh"
#include "EvtGenBase/EvtPDL.hh"
#include "EvtGenBase/EvtId.hh"
#include <string>
#include <vector>
using std::fstream;
void EvtParticleDecay::printSummary(){
if (_decay!=0) _decay->printSummary();
}
void EvtParticleDecay::chargeConj(EvtParticleDecay *decay){
_brfrsum=decay->_brfrsum;
_massmin=decay->_massmin;
_decay=decay->_decay->clone();
int ndaug=decay->_decay->getNDaug();
int narg=decay->_decay->getNArg();
double brfr=decay->_decay->getBranchingFraction();
std::string name=decay->_decay->getName();
EvtId ipar=EvtPDL::chargeConj(decay->_decay->getParentId());
int i;
EvtId* daug=new EvtId[ndaug];
for(i=0;i<ndaug;i++){
daug[i]=EvtPDL::chargeConj(decay->_decay->getDaug(i));
}
//Had to add 1 to make sure the vector is not empty!
std::vector<std::string> args;
for(i=0;i<narg;i++){
args.push_back(decay->_decay->getArgStr(i));
}
_decay->saveDecayInfo(ipar,ndaug,daug,narg,args,name,brfr);
if (decay->_decay->getPHOTOS()) _decay->setPHOTOS();
delete [] daug;
}
|
e3512862b621286330e35e794f93876d3b070224 | 367377e0f331e2fb52afb8b5d5a96b12496aeb2e | /Set.h | 4ef2f5b85b234faeb008521e5fd6b1994974ecf9 | [] | no_license | dayu521/vczh-re | 1f87301cb428ada42890055c0c1b18be1eaed284 | dc35d33c3877f1b5e4c1f7ee92ca6a9f04e56c92 | refs/heads/master | 2022-12-06T06:43:03.036137 | 2020-08-31T11:06:58 | 2020-08-31T11:06:58 | 290,640,641 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,202 | h | Set.h | #ifndef SET_H
#define SET_H
#include <iostream>
#include <stdlib.h>
#include "Link.h"
using namespace std;
template<typename _Type>
class Set
{
public:
Link<_Type> Data;
int Size;
Set()
{
Size=0;
}
~Set()
{
}
Node<_Type>* GetHead()
{
return Data.GetHead();
}
void Copy(Set<_Type>& Object)
{
Data.Copy(Object.Data);
Size=Object.Size;
}
void Sub(Set<_Type>& Object)
{
Node<_Type>* Temp_Object=Object.GetHead();
while (Temp_Object)
{
Node<_Type>* Temp=Data.GetHead();
while (Temp)
{
if (Temp_Object->Data==Temp->Data)
{
Node<_Type>* TempDelete=Temp;
Temp=Temp->Next;
Data.Delete(TempDelete);
--Size;
}
else Temp=Temp->Next;
}
Temp_Object=Temp_Object->Next;
}
}
bool Add(const _Type& Object)
{
Node<_Type>* Temp=Data.GetHead();
if (Temp)
{
while (Temp)
{
if (Object==Temp->Data)
return false;
Temp=Temp->Next;
}
}
Data.AddLast()->Data=Object;
++Size;
return true;
}
void Add(const Set<_Type>& Object)
{
Node<_Type>* Temp=Object.Data.Head;
while (Temp)
{
Add(Temp->Data);
++Size;
Temp=Temp->Next;
}
}
void Delete(Node<_Type>* Object)
{
Data.Delete(Object);
--Size;
}
Node<_Type>* Find(const _Type& Object)
{
return Data.Find(Object);
}
bool Exists(const _Type& Object)
{
return Data.Find(Object)!=0;
}
bool operator==(Set<_Type>& Object)const
{
if (Size==Object.Size)
{
Node<_Type>* Temp=Data.Head;
while(Temp)
{
bool Judge=false;
Node<_Type>* Temp_Object=Object.GetHead();
while (Temp_Object)
{
if (Temp->Data==Temp_Object->Data)
{
Judge=true;
break;
}
Temp_Object=Temp_Object->Next;
}
if (!Judge) return false;
Temp=Temp->Next;
}
return true;
}
else return false;
}
void Zero()
{
Data.Zero();
}
};
/*
template<typename _Type>
class Set
{
public:
OrderedLink<_Type, false> Data;
Set()
{
}
~Set()
{
}
Node<_Type>* GetHead()
{
return Data.GetHead();
}
void Copy(Set<_Type>& Object)
{
Data.Copy(Object.Data);
}
void Sub(Set<_Type>& Object)
{
Node<_Type>* Temp_Object=Object.GetHead();
while (Temp_Object)
{
Node<_Type>* Temp=Data.GetHead();
while (Temp)
{
if (Temp_Object->Data==Temp->Data)
{
Node<_Type>* TempDelete=Temp;
Temp=Temp->Next;
Data.Delete(TempDelete);
}
else Temp=Temp->Next;
}
Temp_Object=Temp_Object->Next;
}
}
bool Add(const _Type& Object)
{
return Data.Add(Object);
}
void Add(const Set<_Type>& Object)
{
Node<_Type>* Temp=Object.Data.Head;
while (Temp)
{
Data.Add(Temp->Data);
Temp=Temp->Next;
}
}
void Delete(Node<_Type>* Object)
{
Data.Delete(Object);
}
Node<_Type>* Find(const _Type& Object)
{
return Data.Find(Object);
}
bool Exists(const _Type& Object)
{
return Data.Exists(Object);
}
bool operator==(Set<_Type>& Object)const
{
return (Data==Object.Data);
}
};
*/
#endif
|
151cc34d0a776b9000332369b1d1ded4bfca2925 | 74a1279ff17c35d86c04a15632b98b26e93245b9 | /minifee/objects/EnemyBulletLargeShot.h | 5ec9f9bd35f3abd57a9b0feae189732b999329e5 | [] | no_license | logicow/minifee | 182af0d7ad46f54c8f8636bcac91df15f11bbe4f | 788546c2b995d5082eb1cbed2f8a5af462a09740 | refs/heads/master | 2021-01-10T08:13:25.742739 | 2016-02-25T21:02:21 | 2016-02-25T21:02:21 | 47,075,995 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 297 | h | EnemyBulletLargeShot.h | #pragma once
#include "EnemyBullet.h"
class EnemyBulletLargeShot : public EnemyBullet
{
public:
float x;
float y;
float w;
float h;
float dirx;
float diry;
float speed;
float timer;
EnemyBulletLargeShot(float x, float y, float tx, float ty);
virtual void update(gameState& state);
}; |
f8baac6082af006111f4acd48b197c6b6e6116b0 | 8c72fd61a0115fec9ea69536b0d3db1ffb63128f | /src/python-bindings/secman.cpp | 8430e2f3ee1269e3db0895d4f1cda36de4a43ce0 | [
"DOC",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | pavlo-svirin/htcondor | 0aee74af7857ede238f07f68ca0c0109b7e90e9a | 9e00a5874cc2579f5fdc81bb778f540b40b48c87 | refs/heads/master | 2021-06-20T02:22:17.819621 | 2019-06-26T21:54:10 | 2019-06-26T21:54:10 | 193,559,154 | 0 | 0 | Apache-2.0 | 2019-06-24T18:34:57 | 2019-06-24T18:34:56 | null | UTF-8 | C++ | false | false | 11,296 | cpp | secman.cpp | // Note - python_bindings_common.h must be included first so it can manage macro definition conflicts
// between python and condor.
#include "python_bindings_common.h"
#include <Python.h>
// Note - condor_secman.h can't be included directly. The following headers must
// be loaded first. Sigh.
#include "condor_ipverify.h"
#include "sock.h"
#include "condor_secman.h"
#include "classad_wrapper.h"
#include "module_lock.h"
#include "secman.h"
#include <boost/python/overloads.hpp>
#include "condor_attributes.h"
#include "command_strings.h"
#include "daemon.h"
#include "old_boost.h"
using namespace boost::python;
MODULE_LOCK_TLS_KEY SecManWrapper::m_key;
bool SecManWrapper::m_key_allocated = false;
static
int getCommand(object command)
{
int res = -1;
extract<std::string> extract_string(command);
if (extract_string.check())
{
std::string cmdstring = extract_string();
if (-1 != (res = getPermissionFromString(cmdstring.c_str())))
{
return getSampleCommand(res);
}
if (-1 != (res = getCommandNum(cmdstring.c_str())))
{
return res;
}
}
extract<int> extract_int(command);
if (extract_int.check())
{
return extract_int();
}
THROW_EX(ValueError, "Unable to determine DaemonCore command value")
return 0;
}
SecManWrapper::SecManWrapper()
: m_secman()
, m_config_overrides(true)
, m_tag_set(false), m_pool_pass_set(false), m_cred_set(false)
{}
void
SecManWrapper::invalidateAllCache()
{
m_secman.invalidateAllCache();
}
boost::shared_ptr<ClassAdWrapper>
SecManWrapper::ping(object locate_obj, object command_obj)
{
int num = getCommand(command_obj);
extract<ClassAdWrapper&> ad_extract(locate_obj);
std::string addr;
if (ad_extract.check())
{
ClassAdWrapper& ad = ad_extract();
if (!ad.EvaluateAttrString(ATTR_MY_ADDRESS, addr))
{
THROW_EX(ValueError, "Daemon address not specified.");
}
}
else
{
addr = extract<std::string>(locate_obj);
}
Daemon daemon(DT_ANY, addr.c_str(), NULL);
if (!daemon.locate())
{
THROW_EX(RuntimeError, "Unable to find daemon.");
}
CondorError errstack;
boost::shared_ptr<ClassAdWrapper> authz_ad(new ClassAdWrapper());
ReliSock *sock = NULL;
condor::ModuleLock ml;
if (!(sock = (ReliSock*) daemon.makeConnectedSocket( Stream::reli_sock, 0, 0, &errstack )))
{
ml.release();
THROW_EX(RuntimeError, "Unable to connect to daemon.");
}
if (!(daemon.startSubCommand(DC_SEC_QUERY, num, sock, 0, &errstack)))
{
ml.release();
THROW_EX(RuntimeError, "Unable to send security query to daemon.");
}
sock->decode();
if (!getClassAd(sock, *authz_ad.get()) || !sock->end_of_message())
{
ml.release();
THROW_EX(RuntimeError, "Failed to get security session information from remote daemon.");
}
// Replace addr with the sinful string that ReliSock has associated with the socket,
// since this is what the SecMan object will do, and we need to do the same thing
// for the SecMan::command_map lookups to succeed below. Note that
// get_connect_addr() may return a different sinful string than was used to
// create the socket, due to processing of things like private network interfaces.
addr = sock->get_connect_addr();
// Don't leak sock!
delete sock;
sock = NULL;
ml.release();
MyString cmd_map_ent;
const std::string &tag = m_tag_set ? m_tag : SecMan::getTag();
if (tag.size()) {
cmd_map_ent.formatstr ("{%s,%s,<%i>}", tag.c_str(), addr.c_str(), num);
} else {
cmd_map_ent.formatstr ("{%s,<%i>}", addr.c_str(), num);
}
MyString session_id;
KeyCacheEntry *k = NULL;
ClassAd *policy = NULL;
// IMPORTANT: this hashtable returns 0 on success!
if ((SecMan::command_map).lookup(cmd_map_ent, session_id))
{
THROW_EX(RuntimeError, "No valid entry in command map hash table!");
}
// Session cache lookup is tag-dependent; hence, we may need to temporarily override
std::string origTag = SecMan::getTag();
if (m_tag_set) {SecMan::setTag(tag);}
// IMPORTANT: this hashtable returns 1 on success!
if (!(SecMan::session_cache)->lookup(session_id.Value(), k))
{
if (m_tag_set) {SecMan::setTag(origTag);}
THROW_EX(RuntimeError, "No valid entry in session map hash table!");
}
if (m_tag_set) {SecMan::setTag(origTag);}
policy = k->policy();
authz_ad->Update(*policy);
return authz_ad;
}
std::string
SecManWrapper::getCommandString(int cmd)
{
return ::getCommandString(cmd);
}
boost::shared_ptr<SecManWrapper>
SecManWrapper::enter(boost::shared_ptr<SecManWrapper> obj)
{
if ( ! m_key_allocated) {
m_key_allocated = 0 == MODULE_LOCK_TLS_ALLOC(m_key);
}
MODULE_LOCK_TLS_SET(m_key, obj.get());
return obj;
}
bool
SecManWrapper::exit(boost::python::object obj1, boost::python::object /*obj2*/, boost::python::object /*obj3*/)
{
MODULE_LOCK_TLS_SET(m_key, NULL);
//PRAGMA_REMIND("should m_cred_set, etc be cleared here?")
m_tag = "";
m_pool_pass = "";
m_cred = "";
m_config_overrides.reset();
return (obj1.ptr() == Py_None);
}
const char *
SecManWrapper::getThreadLocalTag()
{
if ( ! m_key_allocated) return NULL;
SecManWrapper *man = static_cast<SecManWrapper*>(MODULE_LOCK_TLS_GET(m_key));
return (man && man->m_tag_set) ? man->m_tag.c_str() : NULL;
}
const char *
SecManWrapper::getThreadLocalPoolPassword()
{
if ( ! m_key_allocated) return NULL;
SecManWrapper *man = static_cast<SecManWrapper*>(MODULE_LOCK_TLS_GET(m_key));
return (man && man->m_pool_pass_set) ? man->m_pool_pass.c_str() : NULL;
}
const char *
SecManWrapper::getThreadLocalGSICred()
{
if ( ! m_key_allocated) return NULL;
SecManWrapper *man = static_cast<SecManWrapper*>(MODULE_LOCK_TLS_GET(m_key));
return (man && man->m_cred_set) ? man->m_cred.c_str() : NULL;
}
bool SecManWrapper::applyThreadLocalConfigOverrides(ConfigOverrides & old)
{
if ( ! m_key_allocated) return false;
SecManWrapper *man = static_cast<SecManWrapper*>(MODULE_LOCK_TLS_GET(m_key));
if (man) { man->m_config_overrides.apply(&old); return true; }
return false;
}
void
SecManWrapper::setTag(const std::string &tag)
{
m_tag = tag;
m_tag_set = true;
}
void
SecManWrapper::setPoolPassword(const std::string &pool_pass)
{
m_pool_pass = pool_pass;
m_pool_pass_set = true;
}
void
SecManWrapper::setGSICredential(const std::string &cred)
{
m_cred = cred;
m_cred_set = true;
}
void
SecManWrapper::setConfig(const std::string &key, const std::string &val)
{
m_config_overrides.set(key, val.c_str());
}
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(ping_overloads, SecManWrapper::ping, 1, 2);
void
export_secman()
{
class_<SecManWrapper>("SecMan",
R"C0ND0R(
A class that represents the internal HTCondor security state.
If a security session becomes invalid, for example, because the remote daemon restarts,
reuses the same port, and the client continues to use the session, then all future
commands will fail with strange connection errors. This is the only mechanism to
invalidate in-memory sessions.
The :class:`SecMan` can also behave as a context manager; when created, the object can
be used to set temporary security configurations that only last during the lifetime
of the security object.
)C0ND0R")
.def(boost::python::init<>(boost::python::args("self")))
.def("invalidateAllSessions", &SecManWrapper::invalidateAllCache,
R"C0ND0R(
Invalidate all security sessions. Any future connections to a daemon will
cause a new security session to be created.
)C0ND0R",
boost::python::args("self"))
.def("ping", &SecManWrapper::ping, ping_overloads(
R"C0ND0R(
Perform a test authorization against a remote daemon for a given command.
:param ad: The ClassAd of the daemon as returned by :meth:`Collector.locate`;
alternately, the sinful string can be given directly as the first parameter.
:type ad: str or :class:`~classad.ClassAd`
:param command: The DaemonCore command to try; if not given, ``'DC_NOP'`` will be used.
:return: An ad describing the results of the test security negotiation.
:rtype: :class:`~classad.ClassAd`
)C0ND0R",
(boost::python::arg("self"), boost::python::arg("ad"), boost::python::arg("command")="DC_NOP")))
.def("getCommandString", &SecManWrapper::getCommandString,
R"C0ND0R(
Return the string name corresponding to a given integer command.
:param int command_int: The integer command to get the string name of.
)C0ND0R",
boost::python::args("self", "command_int"))
.def("__exit__", &SecManWrapper::exit, "Exit the context manager.")
.def("__enter__", &SecManWrapper::enter, "Enter the context manager.")
.def("setTag", &SecManWrapper::setTag,
R"C0ND0R(
Set the authentication context tag for the current thread.
All security sessions negotiated with the same tag will only
be utilized when that tag is active.
For example, if thread A has a tag set to ``'Joe'`` and thread B
has a tag set to ``'Jane'``, then all security sessions negotiated
for thread A will not be used for thread B.
:param str tag: New tag to set.
)C0ND0R",
boost::python::args("self", "tag"))
.def("setPoolPassword", &SecManWrapper::setPoolPassword,
R"C0ND0R(
Set the pool password.
:param str new_pass: Updated pool password to use for new
security negotiations.
)C0ND0R",
boost::python::args("self", "new_pass"))
.def("setGSICredential", &SecManWrapper::setGSICredential,
R"C0ND0R(
Set the GSI credential to be used for security negotiation.
:param str filename: File name of the GSI credential.
)C0ND0R",
boost::python::args("self", "filename"))
.def("setConfig", &SecManWrapper::setConfig,
R"C0ND0R(
Set a temporary configuration variable; this will be kept for all security
sessions in this thread for as long as the :class:`SecMan` object is alive.
:param str key: Configuration key to set.
:param str value: Temporary value to set.
)C0ND0R",
boost::python::args("self", "key", "value"))
;
}
|
115122df5a0c276917189b9dde79978b53851599 | d0b19e5a55fc33a191c98ed2c4e1b1095e115d15 | /3-Graphs/EJ15/Source.cpp | ce007992936a7a663ee445356b219e1246f7811e | [] | no_license | David-Ortiz-Fernandez/Algorithmic-design | f921c49b6320f2afe3f41b3b3f42d8f1a33eac81 | c393ad856ddd2266f761572d0ad84497bc3788e2 | refs/heads/master | 2020-06-21T10:35:46.260244 | 2019-07-17T19:26:20 | 2019-07-17T19:26:20 | 197,423,509 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 3,779 | cpp | Source.cpp | // DA19 - David Ortiz - Andrés Ortiz
#include <fstream>
#include <iostream>
#include <vector>
#include "UnionFind2D.h"
using namespace std;
// Verifica posiciones adyacentes buscando posibles # para unirlas.
void verify(const vector<vector<bool>> &a, int F, int C, int x, int y, UnionFind2D &ag);
// Hemos usado una matriz booleana para recoger los datos.
// Cuando pasámos los datos a la partición para unir dos conjuntos usamos una fórmula de desplazamiento para convertir las posiciones de la matriz
// a su correspondiente posición en un vector unidimensional.
// Recorremos la matriz uniendo las # añadidas de inicio.
// Si no hay ninguna el tamaño máximo es 0.
// Volvemos a recorrer posiciones adyacentes para las nuevas # y mostramos su tamaño máximo actualizado.
// Coste:
// Inicializar el vector de booleanos de dos dimensiones a false ( entiendo que es un coste de preprocesado y no lo voy a contar en la solución final).
// Para cada # del vector comprobar sus posiciones adyacentes ( como máximo 8 ) y unir los conjuntos pertinentes.
// Unir = O(find) + O(unir) = O(find) que es en el peor caso Log N en el número de elementos totales.
// Coste de inicializar F*C posiciones en el vector unidimensional de la partición a -1. O(F*C) ( entiendo que es un coste que solo se hace 1 vez y no lo voy a contar).
// O((F*C posiciones)*8(posibles posiciones adyacentes)*(unir)).
// O(F*C*8*Log(F*C)). = O(N*8 log(N))= O (N LOG(N)).
int main() {
#ifndef DOMJUDGE
std::ifstream in("casos.txt");
auto cinbuf = std::cin.rdbuf(in.rdbuf());
#endif
int F;
int C;
char aux;
cin >> F;
while (!cin.fail()) { // Mientras que haya casos..
cin >> C;
vector < vector<bool>> matrix(F, vector<bool>(C, false)); // Inicializamos vector de 2 dimensiones.
UnionFind2D algorithm(F, C); // Inicializamos la partición .
for (int i = 0; i < F; i++) {
for (int j = 0; j < C; j++) {
if (j == 0) cin.ignore();
cin.get(aux);
if (aux == '#'){
matrix[i][j] = true;
if (algorithm.maxTam == 0) algorithm.maxTam = -1; // si hemos añadido un # cambiamos el tamaño máximo del conjunto a 1.
}
}
}
// Para cada posición del vector con # verificamos sus posiciones adyacentes buscando más # y unificándolas en un solo conjunto.
for (int i = 0; i < F; i++) {
for (int j = 0; j < C; j++) {
if (matrix[i][j]) verify(matrix, F, C, i, j, algorithm);
}
}
cout << -algorithm.maxTam << " "; // Mostramos el tamaño del mayor conjunto antes de añadir nuevas #.
int numCel;
int a;
int b;
cin >> numCel;
for (int i = 0; i < numCel; i++) {
cin >> a;
cin >> b;
matrix[a - 1][b - 1] = true;
verify(matrix, F, C, a - 1, b - 1, algorithm); // Verificamos para la nueva posición.
if (algorithm.maxTam == 0) cout << 1; // Si el tamaño máximo era vacío lo cambiamos a 1.
else {
cout << -algorithm.maxTam; // Mostramos el tamaño del conjunto más grande.
}
if (i != numCel - 1) cout << " ";
}
cout << endl;
cin >> F;
}
#ifndef DOMJUDGE
std::cin.rdbuf(cinbuf);
system("PAUSE");
#endif
return 0;
}
void verify(const vector<vector<bool>> &a, int F, int C, int x, int y, UnionFind2D &ag) {
// Para las 8 posiciones adyacentes válidas verificamos si podemos unirlas.
for (int i = x - 1; i < x + 2; i++) {
for (int j = y - 1; j < y + 2; j++) {
if ((i >= 0 && i < F) && (j >= 0 && j < C) && (a[i][j])) {
// Fórmula de desplazamiento para convertir posiciones X e Y de una matriz en su correspondiente
// posición en un vector unidimensional (única).
int a = ((x )*C + y );
int b = ((i )*C + j );
ag.unir(a, b);
}
}
}
} |
7dbb7e70acdb647ae59f9d255910f9435a1f39fa | 27b3a921bc8cc4d82f71ca962d31c59f65e99617 | /infotainmentQt/mainscreen.h | 4dd23be49d748817c46e388dbea19b28cda4bdd5 | [] | no_license | essamkhattab/Infotainment-System-Yocto | 06340d242e1545496b0be0c320413dcf6aeb9185 | df098b6211871848e04e0454a9455a64fd5f1ccd | refs/heads/master | 2023-07-28T11:21:29.303398 | 2020-07-15T18:06:26 | 2020-07-15T18:06:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,732 | h | mainscreen.h | #ifndef MAINSCREEN_H
#define MAINSCREEN_H
#include <QMainWindow>
/* Time & Date inclusions */
#include <QTimer>
#include <QDate>
#include <QTime>
/* Media inclusions */
#include <QIcon>
/* Music inclusions */
#include <QFile>
#include <QTextStream>
#include <QListWidget>
#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QDirIterator>
#include <QDir>
#include <QUrl>
/* MP4 inclusions */
#include <QRectF>
#include <QGraphicsScene>
#include <QGraphicsVideoItem>
#include <unistd.h>
#include <bits/stdc++.h>
#include <regex>
#include <iostream>
using namespace std;
#include <typeinfo>
#include <QDebug>
namespace Ui {
class mainScreen;
}
class mainScreen : public QMainWindow
{
Q_OBJECT
public:
explicit mainScreen(QWidget *parent = 0);
QTimer *timer;
QTimer *flashDetectionTimer;
QTimer * bluetoothDetectionTimer;
QDate currentDate;
QString date;
QTime currentTime;
QString time;
QMediaPlaylist *playList = new QMediaPlaylist;
QMediaPlayer *musicPlayer = new QMediaPlayer;
QMediaPlayer *videoPlayer = new QMediaPlayer;
QMediaPlaylist *videoPlayList = new QMediaPlaylist;
QGraphicsScene *videoScene = new QGraphicsScene;
QGraphicsVideoItem *videoGraphicsItem = new QGraphicsVideoItem;
~mainScreen();
private slots:
void on_videoButton_clicked();
void on_musicButton_clicked();
void on_bluetoothButton_clicked();
void on_settingsButton_clicked();
void goBackHome();
void updateTime();
void updateFlashStatus();
void updatBluetoothDevices();
void updateSongsList();
void on_playButton_clicked();
void on_forwardButton_clicked();
void on_backwardButton_clicked();
void on_repeatButton_clicked();
void on_shuffleButton_clicked();
void on_stopButton_clicked();
void playSong();
void playToggle();
void onSongListItemClicked(QListWidgetItem* item);
void onSongChange();
void on_volumeDownButton_clicked();
void on_volumeUpButton_clicked();
void on_darkThemeButton_clicked();
void updateVideosList();
void on_goTovideosListButton_clicked();
void onVideoListItemClicked(QListWidgetItem* item);
void on_backwardVideoButton_clicked();
void on_forwardVideoButton_clicked();
void on_playVideoButton_clicked();
void on_stopVideoButton_clicked();
void on_volumeDownVideoButton_clicked();
void on_volumeUpVideoButton_clicked();
void playVideo();
void stopVideo();
void enableBluetooth();
void on_setTimeDateButton_clicked();
void on_doneTimeDateButton_clicked();
void on_cancelTimeDateButton_clicked();
private:
Ui::mainScreen *ui;
};
#endif // MAINSCREEN_H
|
c16e996237da2890c0523f54bc7f71efbaec8199 | ec795b6c18a5976f482d79831524db60dd54fbd7 | /src/client/tclmc_impl.h | 019070bf757fe79f8ceb529e34bc391ff600b3c8 | [] | no_license | erbth/TCLM | edc9b7b84633fa07b93d38bd91f6dd3dd97eb8a3 | a2e858718bf193a5b28c13430670b7abd5a30a19 | refs/heads/master | 2021-08-22T17:51:26.155150 | 2021-07-23T04:43:22 | 2021-07-23T04:43:22 | 206,416,949 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,113 | h | tclmc_impl.h | #ifndef __TCLMC_IMPL_H
#define __TCLMC_IMPL_H
#include <string>
#include <memory>
#include "tclm_config.h"
#include "Access_Concentrator.h"
#include "tclm_client.hpp"
/* Policy first draft:
*
* Once a connection to a tclmd is made all is done to keep it alive. That is if
* if is closed, a new one is established silently. The methods may only throw
* an exception if that cannot be done at all (may also block indefenitely), or
* if the server died and e.g. the process is not known to it anymore. */
namespace tclm_client {
/* Prototypes */
class Process_impl;
class Lock_impl;
class tclmc_impl : public tclmc, public std::enable_shared_from_this<tclmc_impl>
{
protected:
Access_Concentrator ac;
friend Process_impl;
friend Lock_impl;
public:
/* May throw a cannot_connect_exception */
tclmc_impl (const std::string &servername,
const uint16_t tcp_port = SERVER_TCP_PORT, const uint16_t udp_port = 0);
~tclmc_impl () override;
std::shared_ptr<Process> register_process () override;
std::shared_ptr<Lock> define_lock (const std::string &path) override;
};
}
#endif /* __TCLMC_IMPL_H */
|
4fecae2bec74d83d639f8127edf04c2b07143926 | 01bcef56ade123623725ca78d233ac8653a91ece | /matchmaking/mm_session_online_search.h | cce539bd77c4d0af84e514e04ce2e313680db538 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | SwagSoftware/Kisak-Strike | 1085ba3c6003e622dac5ebc0c9424cb16ef58467 | 4c2fdc31432b4f5b911546c8c0d499a9cff68a85 | refs/heads/master | 2023-09-01T02:06:59.187775 | 2022-09-05T00:51:46 | 2022-09-05T00:51:46 | 266,676,410 | 921 | 123 | null | 2022-10-01T16:26:41 | 2020-05-25T03:41:35 | C++ | WINDOWS-1252 | C++ | false | false | 4,317 | h | mm_session_online_search.h | //===== Copyright © 1996-2009, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
//===========================================================================//
#ifndef MM_SESSION_ONLINE_SEARCH_H
#define MM_SESSION_ONLINE_SEARCH_H
#ifdef _WIN32
#pragma once
#endif
//
// CMatchSessionOnlineSearch
//
// Implementation of an online session search (aka matchmaking)
//
class CMatchSearcher_OnlineSearch;
class CMatchSessionOnlineSearch : public IMatchSessionInternal
{
// Methods of IMatchSession
public:
// Get an internal pointer to session system-specific data
virtual KeyValues * GetSessionSystemData() { return NULL; }
// Get an internal pointer to session settings
virtual KeyValues * GetSessionSettings();
// Update session settings, only changing keys and values need
// to be passed and they will be updated
virtual void UpdateSessionSettings( KeyValues *pSettings );
virtual void UpdateTeamProperties( KeyValues *pTeamProperties );
// Issue a session command
virtual void Command( KeyValues *pCommand );
virtual uint64 GetSessionID();
// Run a frame update
virtual void Update();
// Destroy the session object
virtual void Destroy();
// Debug print a session object
virtual void DebugPrint();
// Check if another session is joinable
virtual bool IsAnotherSessionJoinable( char const *pszAnotherSessionInfo ) { return true; }
// Process event
virtual void OnEvent( KeyValues *pEvent );
enum Result
{
RESULT_UNDEFINED,
RESULT_SUCCESS,
RESULT_FAIL
};
Result GetResult() { return m_result; }
public:
explicit CMatchSessionOnlineSearch( KeyValues *pSettings );
virtual ~CMatchSessionOnlineSearch();
protected:
CMatchSessionOnlineSearch(); // for derived classes construction
//
// Overrides when search is used as a nested object
//
protected:
virtual CMatchSearcher *OnStartSearching();
virtual void OnSearchCompletedEmpty( KeyValues *pSettings );
virtual void OnSearchCompletedSuccess( CSysSessionClient *pSysSession, KeyValues *pSettings );
virtual void OnSearchEvent( KeyValues *pNotify );
virtual CSysSessionClient * OnBeginJoiningSearchResult();
protected:
void StartJoinNextFoundSession();
void ValidateSearchResultWhitelist();
void ConnectJoinLobbyNextFoundSession();
void OnSearchDoneNoResultsMatch();
protected:
KeyValues *m_pSettings;
KeyValues::AutoDelete m_autodelete_pSettings;
friend class CMatchSearcher_OnlineSearch;
CMatchSearcher *m_pMatchSearcher;
Result m_result;
enum State_t
{
STATE_INIT,
STATE_SEARCHING,
STATE_JOIN_NEXT,
#if !defined( NO_STEAM )
STATE_VALIDATING_WHITELIST,
#endif
STATE_JOINING,
STATE_CLOSING,
};
State_t m_eState;
CUtlVector< CMatchSearcher::SearchResult_t const * > m_arrSearchResults;
CSysSessionClient *m_pSysSession;
CSysSessionConTeamHost *m_pSysSessionConTeam;
#if !defined( NO_STEAM )
void SetupSteamRankingConfiguration();
bool IsSteamRankingConfigured() const;
class CServerListListener : public ISteamMatchmakingServerListResponse
{
public:
explicit CServerListListener( CMatchSessionOnlineSearch *pDsSearcher, CUtlVector< MatchMakingKeyValuePair_t > &filters );
void Destroy();
public:
// Server has responded ok with updated data
virtual void ServerResponded( HServerListRequest hReq, int iServer ) { HandleServerResponse( hReq, iServer, true ); }
// Server has failed to respond
virtual void ServerFailedToRespond( HServerListRequest hReq, int iServer ) { HandleServerResponse( hReq, iServer, false ); }
// A list refresh you had initiated is now 100% completed
virtual void RefreshComplete( HServerListRequest hReq, EMatchMakingServerResponse response );
protected:
void HandleServerResponse( HServerListRequest hReq, int iServer, bool bResponded );
CMatchSessionOnlineSearch *m_pOuter;
HServerListRequest m_hRequest;
};
friend class CServerListListener;
CServerListListener *m_pServerListListener;
void Steam_OnDedicatedServerListFetched();
#endif
float m_flInitializeTimestamp;
};
class CMatchSearcher_OnlineSearch : public CMatchSearcher
{
public:
CMatchSearcher_OnlineSearch( CMatchSessionOnlineSearch *pSession, KeyValues *pSettings );
public:
virtual void OnSearchEvent( KeyValues *pNotify );
virtual void OnSearchDone();
protected:
CMatchSessionOnlineSearch *m_pSession;
};
#endif
|
ff8994555bfdcf9f7de2c597104cb9aaa131e1a9 | c097c09c748cb8294d83d4763d744957501cd67c | /ProyectoMVCMallasFastRequerimientos/Controlador.h | bfccd3000ae1e9dae66b9c4827f887ab98bb7f05 | [] | no_license | PeterGabrielVE/CPlusPlus | afd9af5c4b5507fe0eb16793bea76f4ba76dc247 | b82a3df577570cc1e8deac2aa14c7baf494dc158 | refs/heads/master | 2021-05-11T04:03:03.054773 | 2018-04-01T02:50:01 | 2018-04-01T02:50:01 | 117,926,636 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 313 | h | Controlador.h | /*
*
* Author:Pedro Gabriel Leal
*
*/
#ifndef CONTROLADOR_H
#define CONTROLADOR_H
#include "MEmpresa.h"
#include "VCliente.h"
#include "VEmpresa.h"
using namespace std;
class Controlador
{
private:
MEmpresa me;
public:
Controlador();
void ProcesarEmpresa();
void Reporte();
};
#endif
|
cc5ec391387457b1183f1343ce050db8e3ff8c76 | e5dd597b9904b84709ecce1ff382ea6d54a4cd55 | /src/DXApp.cpp | 1631eed7eefa6940e8f231085066780f277d57eb | [] | no_license | jwalker-depaul/Graphics | 559e5ad142b2c339ab2758029a9bf73e05c82e09 | dda1c8f9984e8d4068bd36593f9a1c60d35c77f9 | refs/heads/master | 2020-03-20T20:09:08.536091 | 2018-06-17T17:20:02 | 2018-06-17T17:20:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,635 | cpp | DXApp.cpp | #include "DXApp.h"
#include <windows.h>
#include <sstream>
#include <assert.h>
#include "d3dUtil.h"
// needed to load shaders from file
#include <d3dcompiler.h>
#include "Model.h"
#include "ShaderColor.h"
#include "DirectXTex.h"
#include "Texture.h"
#include "FlatPlane.h"
#include "TerrainModel.h"
#include "SkyBox.h"
void DXApp::InitDemo()
{
/************************
*** LOAD TEXTURES ***
************************/
textureCube = new Texture(md3dDevice, L"../Assets/Textures/Companion_Cube.tga");
texSkyBox = new Texture(md3dDevice, L"../Assets/Textures/cloud_skybox.tga");
texTerrain = new Texture(md3dDevice, L"../Assets/Textures/sandgrass.tga", D3D11_FILTER_MIN_MAG_MIP_LINEAR);
texturePyramid = new Texture(md3dDevice, L"../Assets/Textures/pyramid_texture.tga");
textureTree = new Texture(md3dDevice, L"../Assets/Textures/tree_texture.tga");
textureSixFace = new Texture(md3dDevice, L"../Assets/Textures/water_skybox.tga");
/******************
*** SHADERS ***
******************/
pShaderTexture = new ShaderTexture(md3dDevice);
pShaderTextureLight = new ShaderTextureLight(md3dDevice);
pShaderColor = new ShaderColor(md3dDevice);
//pShaderColorLight = new ShaderColorLight(md3dDevice);
/*****************
*** MODELS ***
*****************/
modelCompanionCube = new Model(md3dDevice, Model::PreMadedeModels::UnitBoxRepeatedTexture);
modelSun = new Model(md3dDevice, Model::PreMadedeModels::UnitSphere);
modelPyramid = new Model(md3dDevice, Model::PreMadedeModels::CreateUnitPyramidRepTexture);
modelTree = new Model(md3dDevice, "../Assets/Models/tree.azul");
modelSixFaceBox = new Model(md3dDevice, Model::PreMadedeModels::UnitBoxSixFaceTexture);
/*************************
*** WORLD MATRICES ***
*************************/
mWorld1 = Matrix(SCALE, 1, 1, 1) * Matrix(TRANS, 0, 0, 0);
pos2 = Vect(-100, 0, -4);
worldSun = Matrix(SCALE, 5, 5, 5) * Matrix(TRANS, pos2);
worldSkyBox = Matrix(TRANS, 0, 0, 0);
worldTerrain = Matrix(TRANS, -350, 0, -400);
pyramidWorld = Matrix(SCALE, 5, 5, 5) * Matrix(TRANS, 0, -4, 0);
/*****************
*** SKYBOX ***
*****************/
//pSkyBox = new SkyBox(md3dDevice, 200);
GO_SkyBox = new GraphicObject_SkyBox(pShaderTexture, md3dDevice, 400, texSkyBox);
/******************
*** TERRAIN ***
******************/
pShaderTextureLight->SetDirectionalLightParameters(Vect(-1, -1, 1).getNorm(), .9 * Vect(1, 1, 1), .5 * Vect(1, 1, 1), Vect(1, 1, 1));
pTerrainModel = new TerrainModel(md3dDevice, L"../Assets/Textures/TerrainMap.tga", 2, 150, -49, 100, 100);
GO_Terrain = new GraphicObject_TerrainLight(pShaderTextureLight, pTerrainModel);
GO_Terrain->SetTexture(texTerrain);
GO_Terrain->SetWorld(worldTerrain);
/******************
*** PYRAMID ***
******************/
// Setup light
Vect position = Vect(0, 0, 0);
float range = 5000;
Vect attenuation = .5 * Vect(1, 0, 0);
Vect direction = Vect(0, -200, 0);
float spotExp = 50;
Vect ambient = 5 * Colors::White;//.2 * Vect(1, 1, 1);
Vect diffuse = 3 * Colors::Blue;//3 * Vect(1, 1, 1);
Vect specular = 1 * Vect(1, 1, 1, 150);
pShaderTextureLight->SetSpotLightParameters(position, range, attenuation, direction, spotExp, ambient, diffuse, specular);
GO_Pyramid = new GraphicObject_TextureLight(pShaderTextureLight, modelPyramid);
GO_Pyramid->SetTexture(texturePyramid);
GO_Pyramid->SetMaterial(Colors::AliceBlue, Colors::AliceBlue, Vect(1, 1, 1, 100));
GO_Pyramid->SetWorld(pyramidWorld);
/****************
*** TREES ***
****************/
// Tree 1
position = Vect(3, 0, 10);
range = 50;
direction = Vect(3, -20, 10);
pShaderTextureLight->SetSpotLightParameters2(position, range, attenuation, direction, spotExp, ambient, diffuse, specular);
worldTree = Matrix(SCALE, .3f, .3f, .3f) * Matrix(RotType::ROT_X, -.5 * 3.14) * Matrix(TRANS, 3, -4, 10);
GO_ModelTree_1 = new GraphicObject_TextureLight(pShaderTextureLight, modelTree);
GO_ModelTree_1->SetTexture(textureTree);
GO_ModelTree_1->SetMaterial(Colors::AliceBlue, Colors::AliceBlue, Vect(1, 1, 1, 100));
GO_ModelTree_1->SetWorld(worldTree);
// Tree 2
//position = Vect(-5, 0, 12);
//range = 50;
//direction = Vect(3, -20, 10);
//pShaderTextureLight->SetSpotLightParameters3(position, range, attenuation, direction, spotExp, ambient, diffuse, specular);
worldTree = Matrix(SCALE, .5f, .5f, .5f) * Matrix(RotType::ROT_X, -.5 * 3.14) * Matrix(TRANS, -5, -5, 12);
GO_ModelTree_2 = new GraphicObject_TextureLight(pShaderTextureLight, modelTree);
GO_ModelTree_2->SetTexture(textureTree);
GO_ModelTree_2->SetMaterial(Colors::AliceBlue, Colors::AliceBlue, Vect(1, 1, 1, 100));
GO_ModelTree_2->SetWorld(worldTree);
// Tree 3
worldTree = Matrix(SCALE, .3f, .3f, .3f) * Matrix(RotType::ROT_X, -.5 * 3.14) * Matrix(TRANS, -7, -4, 3);
GO_ModelTree_3 = new GraphicObject_TextureLight(pShaderTextureLight, modelTree);
GO_ModelTree_3->SetTexture(textureTree);
GO_ModelTree_3->SetMaterial(Colors::AliceBlue, Colors::AliceBlue, Vect(1, 1, 1, 100));
GO_ModelTree_3->SetWorld(worldTree);
// Tree 4
worldTree = Matrix(SCALE, .7f, .7f, .7f) * Matrix(RotType::ROT_X, -.5 * 3.14) * Matrix(TRANS, -3, 0, -4);
GO_ModelTree_4 = new GraphicObject_TextureLight(pShaderTextureLight, modelTree);
GO_ModelTree_4->SetTexture(textureTree);
GO_ModelTree_4->SetMaterial(Colors::AliceBlue, Colors::AliceBlue, Vect(1, 1, 1, 100));
GO_ModelTree_4->SetWorld(worldTree);
// Tree 5
worldTree = Matrix(SCALE, 5, 5, 5) * Matrix(RotType::ROT_X, -.5 * 3.14) * Matrix(TRANS, -30, 20, -80);
GO_ModelTree_5 = new GraphicObject_TextureLight(pShaderTextureLight, modelTree);
GO_ModelTree_5->SetTexture(textureTree);
GO_ModelTree_5->SetMaterial(Colors::AliceBlue, Colors::AliceBlue, Vect(1, 1, 1, 100));
GO_ModelTree_5->SetWorld(worldTree);
/****************
*** OTHER ***
****************/
// Initialize the projection matrix
mCam.setPerspective(3.14159 / 3, mClientWidth / (float)mClientHeight, 1.0f, 1000.0f);
mCam.setOrientAndPosition(Vect(0, 1, 0), Vect(0, 0, 0), Vect(-5, 2, -8));
// Initialize gimmicky mouse control values
mTheta = .5;
mPhi = 3.1415f / 8;
mRadius = 6;
mTimer.Reset();
}
void DXApp::UpdateScene()
{
worldSun *= Matrix(ROT_Y, .003f); // Simple slow rotation about y axis
pos2 = worldSun.get(MatrixRowType::ROW_3);
MoveLightPos = worldSun.get(MatrixRowType::ROW_3);
mCam.getPos(tempCamPos);
worldSkyBox = Matrix(TRANS, tempCamPos);
if (GetKeyState('W') & 0x08000)
{
mCam.TranslateFwdBack(camSpeed);
}
else if (GetKeyState('S') & 0x08000)
{
mCam.TranslateFwdBack(-camSpeed);
}
if (GetKeyState('A') & 0x08000)
{
mCam.TranslateLeftRight(-camSpeed);
}
else if (GetKeyState('D') & 0x08000)
{
mCam.TranslateLeftRight(camSpeed);
}
if (GetKeyState(VK_LEFT) & 0x08000)
{
mCam.TurnLeftRight(rotSpeed);
}
else if (GetKeyState(VK_RIGHT) & 0x08000)
{
mCam.TurnLeftRight(-rotSpeed);
}
if (GetKeyState(VK_UP) & 0x08000)
{
mCam.TiltUpDown(rotSpeed);
}
else if (GetKeyState(VK_DOWN) & 0x08000)
{
mCam.TiltUpDown(-rotSpeed);
}
mCam.updateCamera();
}
void DXApp::DrawScene()
{
// Clear the back buffer
md3dImmediateContext->ClearRenderTargetView(mRenderTargetView, VasA(BackgroundColor));
// Clear the depth stencil;
md3dImmediateContext->ClearDepthStencilView(mpDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
mCam.getPos(eyepos);
/*************************
*** COMPANION CUBE ***
*************************/
worldHoverLight = mWorld1 * Matrix(TRANS, 0, 2 * cosf(mTimer.TotalTime()), 0);
pShaderTexture->SetToContext(md3dImmediateContext);
pShaderTexture->SetTextureResourceAndSampler(textureCube);
pShaderTexture->SendCamMatrices(mCam.getViewMatrix(), mCam.getProjMatrix());
pShaderTexture->SendWorld(worldHoverLight);
modelCompanionCube->Render(md3dImmediateContext);
/***********************
*** SIX FACE BOX ***
***********************/
worldSixFace = Matrix(TRANS, 0 , 3 , 0);
worldSixFace = mWorld1 * Matrix(TRANS, 2 * cosf(mTimer.TotalTime()), 0, 0);
pShaderTexture->SetTextureResourceAndSampler(textureSixFace);
pShaderTexture->SendWorld(worldSixFace);
modelSixFaceBox->Render(md3dImmediateContext);
/**************
*** SUN ***
**************/
pShaderTextureLight->SetSpotLightParameters3(MoveLightPos, 50, .5 * Vect(1, 0, 0), Vect(0, -200, 0), 50, 5 * Colors::White, 3 * Colors::Blue, 1 * Vect(1, 1, 1, 150));
pShaderColor->SetToContext(md3dImmediateContext);
pShaderColor->SendCamMatrices(mCam.getViewMatrix(), mCam.getProjMatrix());
pShaderColor->SendWorldColor(worldSun, Colors::Yellow);
modelSun->Render(md3dImmediateContext);
/*****************
*** SKYBOX ***
*****************/
pShaderTexture->SetToContext(md3dImmediateContext);
pShaderTexture->SendCamMatrices(mCam.getViewMatrix(), mCam.getProjMatrix());
pShaderTexture->SendWorld(worldSkyBox);
GO_SkyBox->SetWorld(worldSkyBox);
GO_SkyBox->Render();
/******************
*** TERRAIN ***
******************/
pShaderTextureLight->SetToContext(md3dImmediateContext);
pShaderTextureLight->SetTextureResourceAndSampler(texTerrain);
pShaderTextureLight->SendCamMatrices(mCam.getViewMatrix(), mCam.getProjMatrix());
pShaderTextureLight->SendFogDetails(5, 50); // 5, 50
//texTerrain->SetToContext(md3dImmediateContext);
//pTerrainModel->Render(md3dImmediateContext);
GO_Terrain->SetMaterial(Colors::AntiqueWhite, Colors::Firebrick, Vect(1, 1, 1, 100));
// Eye position
pShaderTextureLight->SendLightParameters(eyepos);
GO_Terrain->Render();
/******************
*** PYRAMID ***
******************/
pShaderTextureLight->SetToContext(md3dImmediateContext);
Matrix temp = mWorld1 * Matrix(TRANS, 0, 2 * cosf(mTimer.TotalTime()), 0);
pShaderTextureLight->SendWorldAndMaterial(worldHoverLight, .2 * Colors::Blue, 3 * Colors::Blue, 1 * Vect(1, 1, 1, 150));
pShaderTextureLight->SendCamMatrices(mCam.getViewMatrix(), mCam.getProjMatrix());
// Eye position
pShaderTextureLight->SendLightParameters(eyepos);
// Render
GO_Pyramid->Render();
/****************
*** TREES ***
****************/
pShaderTextureLight->SetToContext(md3dImmediateContext);
GO_ModelTree_1->Render();
GO_ModelTree_2->Render();
GO_ModelTree_3->Render();
GO_ModelTree_4->Render();
GO_ModelTree_5->Render();
// Switches the display to show the now-finished back-buffer
mSwapChain->Present(0, 0);
}
DXApp::DXApp(HWND hwnd)
{
assert(hwnd);
mhMainWnd = hwnd;
BackgroundColor = Colors::MidnightBlue;
md3dDevice = nullptr;
md3dImmediateContext = nullptr;
mSwapChain = nullptr;
mRenderTargetView = nullptr;
// Get window data through the window handle
RECT rc;
BOOL err = GetClientRect(mhMainWnd, &rc); // Seriously MS: Redifining BOOL as int? Confusing much?
assert(err);
// get width/hight
mClientWidth = rc.right - rc.left;
mClientHeight = rc.bottom - rc.top;
// Get window caption
const int MAX_LABEL_LENGTH = 100; // probably overkill...
WCHAR str[MAX_LABEL_LENGTH];
GetWindowText(mhMainWnd, str, MAX_LABEL_LENGTH);
mMainWndCaption = str;
// Initialize DX11
this->InitDirect3D();
// Demo initialization
this->InitDemo();
}
DXApp::~DXApp()
{
// Textures
delete textureCube;
delete texSkyBox;
delete texTerrain;
delete texturePyramid;
delete textureTree;
delete textureSixFace;
// Shaders
delete pShaderTexture;
delete pShaderTextureLight;
delete pShaderColor;
// Models
delete modelCompanionCube;
delete modelSun;
delete modelPyramid;
delete modelTree;
delete modelSixFaceBox;
// Skybox
delete GO_SkyBox;
// Terrain
delete pTerrainModel;
delete GO_Terrain;
// Pyramid
delete GO_Pyramid;
// Trees
delete GO_ModelTree_1;
delete GO_ModelTree_2;
delete GO_ModelTree_3;
delete GO_ModelTree_4;
delete GO_ModelTree_5;
ReleaseAndDeleteCOMobject(FrontFaceAsCCWRS);
ReleaseAndDeleteCOMobject(mRenderTargetView);
ReleaseAndDeleteCOMobject(mpDepthStencilView);
ReleaseAndDeleteCOMobject(mSwapChain);
ReleaseAndDeleteCOMobject(md3dImmediateContext);
// Must be done BEFORE the device is released
ReportLiveDXObjects(); // See http://masterkenth.com/directx-leak-debugging/
ReleaseAndDeleteCOMobject(md3dDevice);
}
// See http://masterkenth.com/directx-leak-debugging/
void DXApp::ReportLiveDXObjects()
{
#ifdef _DEBUG
HRESULT hr = S_OK;
// Now we set up the Debug interface, to be queried on shutdown
ID3D11Debug* debugDev;
hr = md3dDevice->QueryInterface(__uuidof(ID3D11Debug), reinterpret_cast<void**>(&debugDev));
assert(SUCCEEDED(hr));
debugDev->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL);
ReleaseAndDeleteCOMobject(debugDev);
#endif
}
void DXApp::InitDirect3D()
{
HRESULT hr = S_OK;
UINT createDeviceFlags = 0;
#ifdef _DEBUG
createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
// This is a *greatly* simplified process to create a DX device and context:
// We force the use of DX11 feature level since that's what CDM labs are limited to.
// For real-life applications would need to test what's the best feature level and act accordingly
hr = D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, nullptr, 0, D3D11_SDK_VERSION, &md3dDevice, nullptr, &md3dImmediateContext);
assert(SUCCEEDED(hr));
// Now we obtain the associated DXGIfactory1 with our device
// Many steps...
IDXGIDevice* dxgiDevice = nullptr;
hr = md3dDevice->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&dxgiDevice));
assert(SUCCEEDED(hr));
IDXGIAdapter* adapter = nullptr;
hr = dxgiDevice->GetAdapter(&adapter);
assert(SUCCEEDED(hr));
IDXGIFactory1* dxgiFactory1 = nullptr;
hr = adapter->GetParent(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&dxgiFactory1));
assert(SUCCEEDED(hr));
// See also note on weird stuff with factories and swap chains (1s and 2s)
// https://msdn.microsoft.com/en-us/library/windows/desktop/jj863687(v=vs.85).aspx
// We are done with these now...
ReleaseAndDeleteCOMobject(adapter);
ReleaseAndDeleteCOMobject(dxgiDevice);
// Controls MSAA option:
// - 4x count level garanteed for all DX11
// - MUST be the same for depth buffer!
// - We _need_ to work with the depth buffer because reasons... (see below)
DXGI_SAMPLE_DESC sampDesc;
sampDesc.Count = 1;
sampDesc.Quality = static_cast<UINT>(D3D11_CENTER_MULTISAMPLE_PATTERN); // MS: what's with the type mismtach?
DXGI_MODE_DESC buffdesc; // https://msdn.microsoft.com/en-us/library/windows/desktop/bb173064(v=vs.85).aspx
ZeroMemory(&buffdesc, sizeof(buffdesc));
buffdesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
// Next we create a swap chain.
// Useful thread: http://stackoverflow.com/questions/27270504/directx-creating-the-swapchain
// Note that this is for a DirectX 11.0: in a real app, we should test the feature levels and act accordingly
DXGI_SWAP_CHAIN_DESC sd; // See MSDN: https://msdn.microsoft.com/en-us/library/windows/desktop/bb173075(v=vs.85).aspx
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 2; // Much confusion about this number... see http://www.gamedev.net/topic/633807-swap-chain-buffer-count/
sd.BufferDesc = buffdesc;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = mhMainWnd;
sd.SampleDesc = sampDesc;
sd.Windowed = TRUE;
hr = dxgiFactory1->CreateSwapChain(md3dDevice, &sd, &mSwapChain);
assert(SUCCEEDED(hr));
ReleaseAndDeleteCOMobject(dxgiFactory1);
// Create a render target view https://msdn.microsoft.com/en-us/library/windows/desktop/ff476582(v=vs.85).aspx
ID3D11Texture2D* pBackBuffer = nullptr;
hr = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&pBackBuffer));
assert(SUCCEEDED(hr));;
hr = md3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &mRenderTargetView);
ReleaseAndDeleteCOMobject(pBackBuffer);
assert(SUCCEEDED(hr));
/**********************************************************/
// First we fix what it means for triangles to be front facing.
// Requires setting a whole new rasterizer state
//*
D3D11_RASTERIZER_DESC rd;
rd.FillMode = D3D11_FILL_SOLID; // Also: D3D11_FILL_WIREFRAME
rd.CullMode = D3D11_CULL_BACK;
rd.FrontCounterClockwise = true; // true for RH forward facing
rd.DepthBias = 0;
rd.SlopeScaledDepthBias = 0.0f;
rd.DepthBiasClamp = 0.0f;
rd.DepthClipEnable = true;
rd.ScissorEnable = false;
rd.MultisampleEnable = true; // Does not in fact turn on/off multisample: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476198(v=vs.85).aspx
rd.AntialiasedLineEnable = false;
//ID3D11RasterizerState* rs;
md3dDevice->CreateRasterizerState(&rd, &FrontFaceAsCCWRS);
md3dImmediateContext->RSSetState(FrontFaceAsCCWRS);
//ReleaseAndDeleteCOMobject(rs); // we can release this resource since we won't be changing it any further
//*/
// We must turn on the abilty to process depth during rendering.
// Done through depth stencils (see https://msdn.microsoft.com/en-us/library/windows/desktop/bb205074(v=vs.85).aspx)
// Below is a simplified version
//*
D3D11_TEXTURE2D_DESC descDepth;
descDepth.Width = mClientWidth;
descDepth.Height = mClientHeight;
descDepth.MipLevels = 1;
descDepth.ArraySize = 1;
descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
descDepth.SampleDesc = sampDesc;
descDepth.Usage = D3D11_USAGE_DEFAULT;
descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
descDepth.CPUAccessFlags = 0;
descDepth.MiscFlags = 0;
ID3D11Texture2D* pDepthStencil;
hr = md3dDevice->CreateTexture2D(&descDepth, NULL, &pDepthStencil);
assert(SUCCEEDED(hr));
// Create the depth stencil view
D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
ZeroMemory(&descDSV, sizeof(descDSV));
descDSV.Format = descDepth.Format;
descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS;
descDSV.Texture2D.MipSlice = 0;;
hr = md3dDevice->CreateDepthStencilView(pDepthStencil, &descDSV, &mpDepthStencilView);
assert(SUCCEEDED(hr));
ReleaseAndDeleteCOMobject(pDepthStencil);
//*/
/**********************************************************/
//md3dImmediateContext->OMSetRenderTargets(1, &mRenderTargetView, nullptr); // to use without depth stencil
md3dImmediateContext->OMSetRenderTargets(1, &mRenderTargetView, mpDepthStencilView);
// Setup the viewport
D3D11_VIEWPORT vp;
vp.Width = (FLOAT)mClientWidth;
vp.Height = (FLOAT)mClientHeight;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
md3dImmediateContext->RSSetViewports(1, &vp);
}
void DXApp::CalculateFrameStats()
{
// Code computes the average frames per second, and also the
// average time it takes to render one frame. These stats
// are appended to the window caption bar.
static int frameCnt = 0;
static float timeElapsed = 0.0f;
frameCnt++;
// Compute averages over one second period.
if ((mTimer.TotalTime() - timeElapsed) >= 1.0f)
{
float fps = (float)frameCnt; // fps = frameCnt / 1
float mspf = 1000.0f / fps;
std::wostringstream outs;
outs.precision(6);
outs << mMainWndCaption << L" "
<< L"FPS: " << fps << L" "
<< L"Frame Time: " << mspf << L" (ms)";
SetWindowText(mhMainWnd, outs.str().c_str());
// Reset for next average.
frameCnt = 0;
timeElapsed += 1.0f;
}
}
void DXApp::FrameTick()
{
mTimer.Tick();
CalculateFrameStats();
this->UpdateScene();
this->DrawScene();
}
void DXApp::OnMouseDown(WPARAM btnState, int xval, int yval)
{
// Gimmicky mouse control
if (btnState & MK_LBUTTON)
{
MousePos[x] = static_cast<float>(xval);
MousePos[y] = static_cast<float>(yval);
}
}
void DXApp::OnMouseUp(WPARAM btnState, int xval, int yval)
{
UNREFERENCED_PARAMETER(btnState);
UNREFERENCED_PARAMETER(xval);
UNREFERENCED_PARAMETER(yval);
}
void DXApp::OnMouseMove(WPARAM btnState, int xval, int yval)
{
// Gimmicky mouse control
if (btnState & MK_LBUTTON)
{
float dx = 0.01f*(MousePos[x] - xval);
float dy = 0.01f*(MousePos[y] - yval);
// Update angles based on input to orbit camera around box.
mTheta += dx;
mPhi -= dy;
static float verticalMax = MATH_PI2 - 0.2f;
if (mPhi > verticalMax)
mPhi = verticalMax;
else if (mPhi < -verticalMax)
mPhi = -verticalMax;
// Build the view matrix using gimmicky trick
Vect target = Vect(0, 0, 0, 0);
Vect up = Vect(0, 1, 0, 0);
Vect pos = Vect(0, 0, -mRadius) * Matrix(ROT_Y, mTheta) * Matrix(ROT_X, mPhi);
mCam.setOrientAndPosition(up, target, pos);
}
MousePos[x] = static_cast<float>(xval);
MousePos[y] = static_cast<float>(yval);
}
void DXApp::OnMouseWheel(short delta)
{
if (delta > 0)
{
mRadius -= 1;
}
else
{
mRadius += 1;
}
}
// Shader loading utility. Will be moved elsewhere later...
// Needs to be moved. Requires
HRESULT DXApp::CompileShaderFromFile(WCHAR* szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut)
{
HRESULT hr = S_OK;
DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#ifdef _DEBUG
// Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags |= D3DCOMPILE_DEBUG;
// Disable optimizations to further improve shader debugging
dwShaderFlags |= D3DCOMPILE_SKIP_OPTIMIZATION;
#endif
ID3DBlob* pErrorBlob = nullptr;
hr = D3DCompileFromFile(szFileName, nullptr, nullptr, szEntryPoint, szShaderModel, dwShaderFlags, 0, ppBlobOut, &pErrorBlob);
if (FAILED(hr))
{
if (pErrorBlob)
{
OutputDebugStringA(reinterpret_cast<const char*>(pErrorBlob->GetBufferPointer()));
pErrorBlob->Release();
}
return hr;
}
if (pErrorBlob) pErrorBlob->Release();
return S_OK;
} |
3c36441e454922b0618eea7e8e47520437975a0b | 4554bf2ef932f3356deed0c7a896a01f2a72003f | /Base/MpkLib/Src/SFileExtractFile.cpp | 17fa47a517bb1dda4f1dc60d9a642d9c55850c0a | [] | no_license | kevinchen2015/xgame | 61364bf24daae2b69202df609b1e4c52a821fd46 | e4cc0916923c624beedd17592a6dd89ff30525af | refs/heads/master | 2021-01-23T18:45:07.418341 | 2017-09-08T02:09:48 | 2017-09-08T02:09:48 | 102,805,922 | 0 | 0 | null | 2017-09-08T02:08:11 | 2017-09-08T02:08:11 | null | UTF-8 | C++ | false | false | 1,503 | cpp | SFileExtractFile.cpp | #define __MPKLIB_SELF__
#include "MpkLib.h"
#include "SCommon.h"
BOOL WINAPI SFileExtractFile(HANDLE hMpk, const char * szToExtract, const char * szExtracted)
{
HANDLE hLocalFile = INVALID_HANDLE_VALUE;
HANDLE hMpkFile = NULL;
int nError = ERROR_SUCCESS;
// Create the local file
if(nError == ERROR_SUCCESS)
{
hLocalFile = CreateFile(szExtracted, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL);
if(hLocalFile == INVALID_HANDLE_VALUE)
nError = GetLastError();
}
// Open the MPK file
if(nError == ERROR_SUCCESS)
{
if(!SFileOpenFileEx(hMpk, szToExtract, 0, &hMpkFile))
nError = GetLastError();
}
// Copy the file's content
if(nError == ERROR_SUCCESS)
{
char szBuffer[0x1000];
DWORD dwTransferred = 1;
while(dwTransferred > 0)
{
SFileReadFile(hMpkFile, szBuffer, sizeof(szBuffer), &dwTransferred, NULL);
if(dwTransferred == 0)
break;
WriteFile(hLocalFile, szBuffer, dwTransferred, &dwTransferred, NULL);
if(dwTransferred == 0)
break;
}
}
// Close the files
if(hMpkFile != NULL)
SFileCloseFile(hMpkFile);
if(hLocalFile != INVALID_HANDLE_VALUE)
CloseHandle(hLocalFile);
if(nError != ERROR_SUCCESS)
SetLastError(nError);
return (BOOL)(nError == ERROR_SUCCESS);
}
|
886956fa9fa8c557080550165d7f6104ea2a6ab6 | c46c81a49cd9cbfa872a1ab5db79a6111468bf5d | /src/Box2DPhysicsSystem/Private/Box2DPhysicsBody.cpp | a34beda612bcce58dfb8bbb1ffb8d750800afdef | [] | no_license | fuzzything44/ManaForge-Engine | 20400608ecb29155ff7878f5e9c560c02220ef88 | 1c6b57138e094cb052faeaf1cc4dd6725c99f854 | refs/heads/master | 2021-03-27T12:59:33.543934 | 2015-10-31T22:24:58 | 2015-10-31T22:24:58 | 26,368,851 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,935 | cpp | Box2DPhysicsBody.cpp | #include "Box2DPhysicsBody.h"
#include "Box2DPhysicsSystem.h"
#include "Box2DActorTransformController.h"
#include <Helper.h>
Box2DPhysicsBody::Box2DPhysicsBody(
Box2DPhysicsShape& shape, PhysicsComponent& owner, Box2DPhysicsSystem& system)
: system(system)
, ownerComponent(owner)
, shouldCallStartContact(false)
, shouldCallEndContact(false)
{
auto iter = system.bodies.find(&(owner.getOwner()));
if (iter == system.bodies.end()) MFLOG(Fatal) << "could not find actor in ActorTransformController map";
ownerController = iter->second;
b2FixtureDef fixtureDef;
fixtureDef.shape = shape.shape.get();
fixtureDef.userData = this;
assert(ownerController->body);
assert(ownerController->body->GetWorld());
fixture = ownerController->body->CreateFixture(&fixtureDef);
}
Box2DPhysicsBody::~Box2DPhysicsBody() { ownerController->body->DestroyFixture(fixture); }
void Box2DPhysicsBody::setRestitution(float newRestitution)
{
fixture->SetRestitution(newRestitution);
ownerController->body->ResetMassData();
}
float Box2DPhysicsBody::getRestitution() const { return fixture->GetRestitution(); }
void Box2DPhysicsBody::setDensity(float newDensity)
{
fixture->SetDensity(newDensity);
ownerController->body->ResetMassData();
}
float Box2DPhysicsBody::getDensity() const { return fixture->GetDensity(); }
void Box2DPhysicsBody::setFriction(float newFriction) { fixture->SetFriction(newFriction); }
float Box2DPhysicsBody::getFriction() const { return fixture->GetFriction(); }
void Box2DPhysicsBody::setIsSensor(bool newIsSensor) { fixture->SetSensor(newIsSensor); }
bool Box2DPhysicsBody::getIsSensor() const { return fixture->IsSensor(); }
void Box2DPhysicsBody::setStartContactCallback(const std::function<void(PhysicsComponent&)>& callback)
{
startContactCallback = callback;
}
void Box2DPhysicsBody::setEndContactCallback(const std::function<void(PhysicsComponent&)>& callback)
{
endContactCallback = callback;
}
|
69fb2e58244781aa46bfc132ab605ab486447ea8 | 98d8ff124bdc8ae8aa9c7a78e46129f8ea3a7bb6 | /caffeRecog/caffeRecog.cpp | cb44bf7f5a7d57ea488c1365c163cf81898e82b1 | [] | no_license | Nfreewind/opencv_test-1 | 912738cd299e0716e4321fb3a69cd43a310772bf | 3c85978bc33b639cbbad1ff4b7d8e5061ece18ca | refs/heads/master | 2020-09-13T18:52:18.087753 | 2017-08-18T09:51:57 | 2017-08-18T09:51:57 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 652 | cpp | caffeRecog.cpp | // caffeRecog.cpp : 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
#include "caffeRecog.h"
#include "ClassifierImpl.h"
#include "caffeHeader.h"
// 这是已导出类的构造函数。
// 有关类定义的信息,请参阅 caffeRecog.h
CcaffeRecog::CcaffeRecog(const std::string & model_file, const std::string & trained_file, const std::string & mean_file, const std::string& label_file)
{
Impl = new ClassifierImpl(model_file, trained_file, mean_file, label_file);
}
CcaffeRecog::~CcaffeRecog()
{
delete Impl;
}
std::vector<Prediction> CcaffeRecog::Classify(const cv::Mat & img, int N)
{
return Impl->Classify(img, N);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.