hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
57121d0a35995fa55a197a9d74bedae40fc22706 | 65,051 | cpp | C++ | ToolKit/CommandBars/XTPOffice2007Theme.cpp | 11Zero/DemoBCG | 8f41d5243899cf1c82990ca9863fb1cb9f76491c | [
"MIT"
] | 2 | 2018-03-30T06:40:08.000Z | 2022-02-23T12:40:13.000Z | ToolKit/CommandBars/XTPOffice2007Theme.cpp | 11Zero/DemoBCG | 8f41d5243899cf1c82990ca9863fb1cb9f76491c | [
"MIT"
] | null | null | null | ToolKit/CommandBars/XTPOffice2007Theme.cpp | 11Zero/DemoBCG | 8f41d5243899cf1c82990ca9863fb1cb9f76491c | [
"MIT"
] | 1 | 2020-08-11T05:48:02.000Z | 2020-08-11T05:48:02.000Z | // XTPOffice2007Theme.cpp : implementation of the CXTPOffice2007Theme class.
//
// This file is a part of the XTREME COMMANDBARS MFC class library.
// (c)1998-2011 Codejock Software, All Rights Reserved.
//
// THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE
// RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN
// CONSENT OF CODEJOCK SOFTWARE.
//
// THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED
// IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO
// YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A
// SINGLE COMPUTER.
//
// CONTACT INFORMATION:
// support@codejock.com
// http://www.codejock.com
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Common/XTPDrawHelpers.h"
#include "Common/XTPResourceImage.h"
#include "Common/XTPVc80Helpers.h"
#include "Common/XTPHookManager.h"
#include "Common/XTPMarkupRender.h"
#include "Common/XTPResourceManager.h"
#include "XTPControls.h"
#include "XTPControl.h"
#include "XTPControlPopup.h"
#include "XTPCommandBar.h"
#include "XTPPopupBar.h"
#include "XTPControlGallery.h"
#include "XTPStatusBar.h"
#include "XTPMessageBar.h"
#include "XTPControlProgress.h"
#include "XTPOffice2007Theme.h"
#include "XTPOffice2007FrameHook.h"
#ifdef _XTP_INCLUDE_RIBBON
#include "Ribbon/XTPRibbonPaintManager.h"
#endif
#ifndef OIC_WINLOGO
#define OIC_WINLOGO 32517
#endif
#ifndef LAYOUT_BITMAPORIENTATIONPRESERVED
#define LAYOUT_BITMAPORIENTATIONPRESERVED 0x00000008
#endif
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
class _XTP_EXT_CLASS CXTPSliderOffice2007Theme : public CXTPSliderPaintManager
{
public:
CXTPSliderOffice2007Theme(CXTPPaintManager* pPaintManager)
: CXTPSliderPaintManager(pPaintManager)
{
}
public:
virtual void DrawScrollBar(CDC* pDC, CXTPScrollBase* pGallery);
virtual void RefreshMetrics();
};
class _XTP_EXT_CLASS CXTPProgressOffice2007Theme : public CXTPProgressPaintManager
{
public:
CXTPProgressOffice2007Theme(CXTPPaintManager* pPaintManager);
public:
virtual void DrawProgress(CDC* pDC, CXTPProgressBase* pGallery);
};
IMPLEMENT_DYNAMIC(CXTPOffice2007Theme, CXTPOffice2003Theme)
CXTPOffice2007Theme::CXTPOffice2007Theme()
{
m_pShadowManager->SetShadowOptions(xtpShadowOfficeAlpha | xtpShadowShowPopupControl);
m_systemTheme = xtpSystemThemeUnknown;
m_bThemedStatusBar = TRUE;
m_bOffice2007Padding = TRUE;
delete m_pGalleryPaintManager;
m_pGalleryPaintManager = new CXTPControlGalleryOffice2007Theme(this);
delete m_pSliderPaintManager;
m_pSliderPaintManager = new CXTPSliderOffice2007Theme(this);
delete m_pProgressPaintManager;
m_pProgressPaintManager = new CXTPProgressOffice2007Theme(this);
m_pImages = XTPResourceImages();
}
CXTPFramePaintManager* CXTPOffice2007Theme::GetFramePaintManager()
{
if (!m_pFramePaintManager)
{
m_pFramePaintManager = new CXTPFramePaintManager(this);
m_pFramePaintManager->RefreshMetrics();
}
return m_pFramePaintManager;
}
CXTPRibbonPaintManager* CXTPOffice2007Theme::GetRibbonPaintManager()
{
#ifdef _XTP_INCLUDE_RIBBON
if (!m_pRibbonPaintManager)
{
m_pRibbonPaintManager = new CXTPRibbonPaintManager(this);
m_pRibbonPaintManager->RefreshMetrics();
}
#endif
return m_pRibbonPaintManager;
}
CXTPOffice2007Theme::~CXTPOffice2007Theme()
{
m_pImages->RemoveAll();
}
CXTPResourceImages* CXTPOffice2007Theme::GetImages() const
{
return m_pImages;
}
void CXTPOffice2007Theme::SetImages(CXTPResourceImages* pImages)
{
m_pImages = pImages;
}
void CXTPOffice2007Theme::SetImageHandle(HMODULE hResource, LPCTSTR lpszIniFileName)
{
GetImages()->SetHandle(hResource, lpszIniFileName);
RefreshMetrics();
}
CXTPResourceImage* CXTPOffice2007Theme::LoadImage(LPCTSTR lpszFileName)
{
return GetImages()->LoadFile(lpszFileName);
}
BOOL CXTPOffice2007Theme::IsImagesAvailable()
{
return TRUE;
}
COLORREF CXTPOffice2007Theme::GetRectangleTextColor(BOOL bSelected, BOOL bPressed, BOOL bEnabled, BOOL bChecked, BOOL bPopuped, XTPBarType barType, XTPBarPosition barPosition)
{
if (barType == xtpBarTypeMenuBar && !bSelected && bEnabled && !bPressed && !bChecked && !bPopuped)
{
return m_clrMenuBarText;
}
return CXTPOffice2003Theme::GetRectangleTextColor(bSelected, bPressed, bEnabled, bChecked, bPopuped, barType, barPosition);
}
void CXTPOffice2007Theme::RefreshMetrics()
{
CXTPOffice2003Theme::RefreshMetrics();
//////////////////////////////////////////////////////////////////////////
GetImages()->AssertValid();
//////////////////////////////////////////////////////////////////////////
m_clrStatusTextColor = GetImages()->GetImageColor(_T("StatusBar"), _T("StatusBarText"));
m_clrStatusBarShadow = GetImages()->GetImageColor(_T("StatusBar"), _T("StatusBarShadow"));
m_clrStatusBarTop.SetStandardValue(GetImages()->GetImageColor(_T("StatusBar"), _T("StatusBarFaceTopLight")),
GetImages()->GetImageColor(_T("StatusBar"), _T("StatusBarFaceTopDark")));
m_clrStatusBarBottom.SetStandardValue(GetImages()->GetImageColor(_T("StatusBar"), _T("StatusBarFaceBottomLight")),
GetImages()->GetImageColor(_T("StatusBar"), _T("StatusBarFaceBottomDark")));
m_clrDockBar.SetStandardValue(GetImages()->GetImageColor(_T("Toolbar"), _T("DockBarFace")));
m_clrCommandBar.SetStandardValue(GetImages()->GetImageColor(_T("Toolbar"), _T("ToolbarFaceLight")),
GetImages()->GetImageColor(_T("Toolbar"), _T("ToolbarFaceDark")), 0.75f);
m_clrToolbarShadow.SetStandardValue(GetImages()->GetImageColor(_T("Toolbar"), _T("ToolbarFaceShadow")));
m_clrToolbarExpand.SetStandardValue(GetImages()->GetImageColor(_T("Toolbar"), _T("ControlToolbarExpandLight")),
GetImages()->GetImageColor(_T("Toolbar"), _T("ControlToolbarExpandDark")), 0.75f);
m_clrPopupControl.SetStandardValue(GetImages()->GetImageColor(_T("Toolbar"), _T("ControlHighlightPopupedLight")),
GetImages()->GetImageColor(_T("Toolbar"), _T("ControlHighlightPopupedDark")));
m_clrMenuGripper.SetStandardValue(GetImages()->GetImageColor(_T("Toolbar"), _T("MenuPopupGripperLight")),
GetImages()->GetImageColor(_T("Toolbar"), _T("MenuPopupGripperDark")));
m_clrMenuExpandedGripper.SetStandardValue(GetImages()->GetImageColor(_T("Toolbar"), _T("MenuPopupExpandedGripperLight")),
GetImages()->GetImageColor(_T("Toolbar"), _T("MenuPopupExpandedGripperDark")));
m_clrMenuExpand = m_clrPopupControl;
m_pShadowManager->SetShadowColor(0);
m_clrTearOffGripper.SetStandardValue(GetImages()->GetImageColor(_T("Toolbar"), _T("MenuPopupTearOffGripper")));
m_clrMenuBarText = GetImages()->GetImageColor(_T("Toolbar"), _T("MenuBarText"));
m_arrColor[XPCOLOR_MENUBAR_FACE].SetStandardValue(RGB(246, 246, 246));
m_arrColor[XPCOLOR_MENUBAR_BORDER].SetStandardValue(GetImages()->GetImageColor(_T("Toolbar"), _T("MenuPopupBorder")));
m_arrColor[XPCOLOR_TOOLBAR_GRIPPER].SetStandardValue(GetImages()->GetImageColor(_T("Toolbar"), _T("ToolbarGripper")));
m_arrColor[XPCOLOR_MENUBAR_TEXT].SetStandardValue(0);
m_arrColor[XPCOLOR_HIGHLIGHT_TEXT].SetStandardValue(0);
m_arrColor[XPCOLOR_TOOLBAR_TEXT].SetStandardValue(0);
m_arrColor[XPCOLOR_TOOLBAR_GRAYTEXT].SetStandardValue(RGB(141, 141, 141));
m_arrColor[XPCOLOR_HIGHLIGHT_DISABLED_BORDER].SetStandardValue(RGB(141, 141, 141));
m_arrColor[XPCOLOR_MENUBAR_GRAYTEXT].SetStandardValue(RGB(141, 141, 141));
m_arrColor[XPCOLOR_FRAME].SetStandardValue(GetImages()->GetImageColor(_T("Window"), _T("WindowFrame")));
m_clrFloatingGripper.SetStandardValue(GetImages()->GetImageColor(_T("Toolbar"), _T("FloatingBarGripper")));
m_clrFloatingGripperText.SetStandardValue(GetImages()->GetImageColor(_T("Toolbar"), _T("FloatingBarGripperText")));
m_arrColor[XPCOLOR_FLOATBAR_BORDER].SetStandardValue(GetImages()->GetImageColor(_T("Toolbar"), _T("FloatingBarBorder")));
m_arrColor[COLOR_APPWORKSPACE].SetStandardValue(GetImages()->GetImageColor(_T("Workspace"), _T("AppWorkspace")));
m_arrColor[XPCOLOR_3DFACE].SetStandardValue(GetImages()->GetImageColor(_T("Window"), _T("ButtonFace")));
m_arrColor[XPCOLOR_3DSHADOW].SetStandardValue(m_clrToolbarShadow);
m_arrColor[XPCOLOR_TOOLBAR_FACE].SetStandardValue(GetImages()->GetImageColor(_T("Toolbar"), _T("ToolbarFace")));
m_arrColor[XPCOLOR_SEPARATOR].SetStandardValue(GetImages()->GetImageColor(_T("Toolbar"), _T("ToolbarSeparator")));
m_arrColor[XPCOLOR_DISABLED].SetStandardValue(GetImages()->GetImageColor(_T("Toolbar"), _T("ControlDisabledIcon")));
m_clrWorkspaceClientTop = GetImages()->GetImageColor(_T("Workspace"), _T("WorkspaceClientTop"));
m_clrWorkspaceClientMiddle = GetImages()->GetImageColor(_T("Workspace"), _T("WorkspaceClientMiddle"));
m_clrWorkspaceClientBottom = GetImages()->GetImageColor(_T("Workspace"), _T("WorkspaceClientBottom"));
m_arrColor[XPCOLOR_HIGHLIGHT].SetStandardValue(GetImages()->GetImageColor(_T("Window"), _T("HighlightSelected")));
m_arrColor[XPCOLOR_HIGHLIGHT_BORDER].SetStandardValue(GetImages()->GetImageColor(_T("Window"), _T("HighlightSelectedBorder")));
m_arrColor[XPCOLOR_HIGHLIGHT_PUSHED].SetStandardValue(GetImages()->GetImageColor(_T("Window"), _T("HighlightPressed")));
m_arrColor[XPCOLOR_HIGHLIGHT_PUSHED_BORDER].SetStandardValue(GetImages()->GetImageColor(_T("Window"), _T("HighlightPressedBorder")));
m_arrColor[XPCOLOR_HIGHLIGHT_CHECKED].SetStandardValue(GetImages()->GetImageColor(_T("Window"), _T("HighlightChecked")));
m_arrColor[XPCOLOR_HIGHLIGHT_CHECKED_BORDER].SetStandardValue(GetImages()->GetImageColor(_T("Window"), _T("HighlightCheckedBorder")));
m_arrColor[XPCOLOR_PUSHED_TEXT].SetStandardValue(0);
m_bLunaTheme = TRUE;
m_grcLunaSelected.SetStandardValue(GetImages()->GetImageColor(_T("Window"), _T("HighlightSelectedLight")),
GetImages()->GetImageColor(_T("Window"), _T("HighlightSelectedDark")));
m_grcLunaChecked.SetStandardValue(GetImages()->GetImageColor(_T("Window"), _T("HighlightCheckedLight")),
GetImages()->GetImageColor(_T("Window"), _T("HighlightCheckedDark")));
m_grcLunaPushed.SetStandardValue(GetImages()->GetImageColor(_T("Window"), _T("HighlightPressedLight")),
GetImages()->GetImageColor(_T("Window"), _T("HighlightPressedDark")));
m_arrColor[XPCOLOR_LABEL].SetStandardValue(GetImages()->GetImageColor(_T("Toolbar"), _T("ControlLabel")));
m_arrColor[XPCOLOR_EDITCTRLBORDER].SetStandardValue(GetImages()->GetImageColor(_T("Toolbar"), _T("ControlEditBorder")));
m_clrDisabledIcon.SetStandardValue(GetImages()->GetImageColor(_T("Toolbar"), _T("ControlDisabledIconLight")),
GetImages()->GetImageColor(_T("Toolbar"), _T("ControlDisabledIconDark")));
m_clrMessageBar.SetStandardValue(GetImages()->GetImageColor(_T("MessageBar"), _T("MessageBarLight")),
GetImages()->GetImageColor(_T("MessageBar"), _T("MessageBarDark")));
m_clrMessageBarFrame = GetImages()->GetImageColor(_T("MessageBar"), _T("MessageBarFrame"));
m_clrMessageBarText = GetImages()->GetImageColor(_T("MessageBar"), _T("MessageBarText"));
m_clrMessageBarFace = GetImages()->GetImageColor(_T("MessageBar"), _T("MessageBar"));
CreateGradientCircle();
}
void CXTPOffice2007Theme::FillWorkspace(CDC* pDC, CRect rc, CRect rcExclude)
{
CRgn rgn;
rgn.CreateRectRgnIndirect(rc);
pDC->SelectClipRgn(&rgn);
pDC->ExcludeClipRect(rcExclude);
CXTPResourceImage* pImage = LoadImage(_T("WORKSPACETOPLEFT"));
ASSERT(pImage);
if (!pImage)
return;
CRect rcSrc(pImage->GetSource());
CRect rcTopLeft(rc);
rcTopLeft.bottom = rcTopLeft.top + rcSrc.Height();
rcTopLeft.right = rcTopLeft.left + max(rcTopLeft.Width(), rcSrc.Width());
pImage->DrawImage(pDC, rcTopLeft, rcSrc, CRect(rcSrc.Width() - 1, 0, 0, 0));
CRect rcFill(rc.left, rc.top + rcSrc.Height(), rc.right, rc.bottom);
CRect rcFillTop(rcFill.left, rcFill.top, rcFill.right, rcFill.top + rcFill.Height() * 2 / 3);
CRect rcFillBottom(rcFill.left, rcFillTop.bottom, rcFill.right, rcFill.bottom);
XTPDrawHelpers()->GradientFill(pDC, rcFillTop, m_clrWorkspaceClientTop, m_clrWorkspaceClientMiddle, FALSE);
XTPDrawHelpers()->GradientFill(pDC, rcFillBottom, m_clrWorkspaceClientMiddle, m_clrWorkspaceClientBottom, FALSE);
pDC->SelectClipRgn(NULL);
}
void CXTPOffice2007Theme::FillStatusBar(CDC* pDC, CXTPStatusBar* pBar)
{
CXTPClientRect rc(pBar);
pDC->FillSolidRect(rc.left, rc.top, rc.Width(), 1, m_clrStatusBarShadow);
XTPDrawHelpers()->GradientFill(pDC, CRect(rc.left, rc.top + 1, rc.right, rc.top + 9),
m_clrStatusBarTop, FALSE);
XTPDrawHelpers()->GradientFill(pDC, CRect(rc.left, rc.top + 9, rc.right, rc.bottom),
m_clrStatusBarBottom, FALSE);
}
void CXTPOffice2007Theme::FillMessageBar(CDC* pDC, CXTPMessageBar* pBar)
{
CXTPClientRect rcClient(pBar);
pDC->FillSolidRect(rcClient, m_clrMessageBarFace);
CRect rcMessage = pBar->GetMessageRect();
pDC->Draw3dRect(rcMessage, m_clrMessageBarFrame, m_clrMessageBarFrame);
rcMessage.DeflateRect(1, 1);
XTPDrawHelpers()->GradientFill(pDC, rcMessage, m_clrMessageBar, FALSE);
}
void CXTPOffice2007Theme::DrawMessageBarButton(CDC* pDC, CXTPMessageBarButton* pButton)
{
BOOL bCloseButton = (pButton->m_nID == SC_CLOSE);
CRect rc(pButton->m_rcButton);
if (pButton->m_bPressed && bCloseButton)
{
pDC->FillSolidRect(rc, GetXtremeColor(XPCOLOR_HIGHLIGHT_PUSHED));
pDC->Draw3dRect(rc, GetXtremeColor(XPCOLOR_HIGHLIGHT_PUSHED_BORDER), GetXtremeColor(XPCOLOR_HIGHLIGHT_PUSHED_BORDER));
}
else if (pButton->m_bHot)
{
pDC->FillSolidRect(rc, GetXtremeColor(XPCOLOR_HIGHLIGHT));
pDC->Draw3dRect(rc, GetXtremeColor(XPCOLOR_HIGHLIGHT_BORDER), GetXtremeColor(XPCOLOR_HIGHLIGHT_BORDER));
}
else if (!bCloseButton)
{
pDC->FillSolidRect(rc, 0xFFFFFF);
pDC->Draw3dRect(rc, m_clrMessageBarFrame, m_clrMessageBarFrame);
}
if (bCloseButton)
{
CXTPResourceImage* pImage = LoadImage(_T("FRAMECAPTIONCLOSE17"));
CRect rcSrc(pImage->GetSource(0, 5));
CRect rcGlyph(CPoint((rc.right + rc.left - rcSrc.Width()) / 2, (rc.top + rc.bottom - rcSrc.Height()) / 2), rcSrc.Size());
pImage->DrawImage(pDC, rcGlyph, rcSrc, CRect(0, 0, 0, 0), 0xFF00FF);
}
}
void CXTPOffice2007Theme::DrawStatusBarPaneBorder(CDC* pDC, CRect rc, CXTPStatusBarPane* /*pPane*/, BOOL bGripperPane)
{
if (!bGripperPane)
{
pDC->FillSolidRect(rc.right - 1, rc.top, 1, rc.Height() - 2, GetXtremeColor(XPCOLOR_SEPARATOR));
pDC->FillSolidRect(rc.right, rc.top, 1, rc.Height() - 2, RGB(255, 255, 255));
}
}
void CXTPOffice2007Theme::DrawStatusBarGripper(CDC* pDC, CRect rcClient)
{
CPoint pt(rcClient.right - 3, rcClient.bottom - 3);
for (int y = 0; y < 3; y++)
{
for (int x = 0; x < 3 - y; x++)
{
pDC->FillSolidRect(pt.x + 1 - x * 4, pt.y + 1 - y * 4, 2, 2, RGB(255, 255, 255));
pDC->FillSolidRect(pt.x + 0 - x * 4, pt.y + 0 - y * 4, 2, 2, GetXtremeColor(XPCOLOR_SEPARATOR));
}
}
}
//////////////////////////////////////////////////////////////////////////
// CXTPControlGalleryOffice2007Theme
CXTPControlGalleryOffice2007Theme::CXTPControlGalleryOffice2007Theme(CXTPPaintManager* pPaintManager)
: CXTPControlGalleryPaintManager(pPaintManager)
{
}
void CXTPControlGalleryOffice2007Theme::FillControl(CDC* pDC, CXTPControlGallery* pGallery, CRect rcControl)
{
pDC->FillSolidRect(rcControl,
pGallery->GetParent()->GetPosition() == xtpBarPopup && pGallery->GetParent()->GetType() == xtpBarTypePopup?
m_pPaintManager->GetXtremeColor(XPCOLOR_MENUBAR_FACE) :
pGallery->GetSelected() && pGallery->GetEnabled() ? m_clrControlGallerySelected : m_clrControlGalleryNormal);
if (pGallery->IsShowBorders())
{
pDC->Draw3dRect(rcControl, m_clrControlGalleryBorder, m_clrControlGalleryBorder);
}
if (pGallery->HasBottomSeparator())
{
pDC->FillSolidRect(rcControl.left, rcControl.bottom - 2, rcControl.Width(), 1, RGB(197, 197, 197));
}
}
void CXTPControlGalleryOffice2007Theme::RefreshMetrics()
{
CXTPControlGalleryPaintManager::RefreshMetrics();
m_cxHScroll = GetSystemMetrics(SM_CXHSCROLL);
m_cyHScroll = GetSystemMetrics(SM_CYHSCROLL);
m_cxVScroll = GetSystemMetrics(SM_CXVSCROLL);
m_cyVScroll = GetSystemMetrics(SM_CYVSCROLL);
m_cyPopupUp = 21;
m_cyPopupDown = 19;
CXTPOffice2007Theme* pPaintManager = (CXTPOffice2007Theme*)m_pPaintManager;
m_clrControlGallerySelected = pPaintManager->GetImages()->GetImageColor(_T("Toolbar"), _T("ControlGallerySelected"));
m_clrControlGalleryNormal = pPaintManager->GetImages()->GetImageColor(_T("Toolbar"), _T("ControlGalleryNormal"));
m_clrControlGalleryBorder = pPaintManager->GetImages()->GetImageColor(_T("Toolbar"), _T("ControlGalleryBorder"));
}
void CXTPControlGalleryOffice2007Theme::DrawLabel(CDC* pDC, CXTPControlGalleryItem* pLabel, CRect rcItem)
{
CXTPPaintManager* pPaintManager = m_pPaintManager;
pDC->FillSolidRect(rcItem, pPaintManager->GetXtremeColor(XPCOLOR_LABEL));
pDC->FillSolidRect(rcItem.left, rcItem.bottom - 1, rcItem.Width(), 1, RGB(197, 197, 197));
CXTPFontDC fnt(pDC, pPaintManager->GetRegularBoldFont());
CRect rcText(rcItem);
rcText.DeflateRect(10, 0);
pDC->SetTextColor(pPaintManager->GetXtremeColor(XPCOLOR_MENUBAR_TEXT));
pDC->DrawText(pLabel->GetCaption(), rcText, DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
}
void CXTPControlGalleryOffice2007Theme::DrawPopupScrollBar(CDC* pDC, CXTPControlGallery* pGallery)
{
#define GETPARTSTATE3(ht, bEnabled) \
(!bEnabled ? 4 : nPressetHt == ht ? 3 : nHotHt == ht ? 2 : nHotHt > 0 || nPressetHt > 0 ? 1 : 0)
CXTPControlGallery::SCROLLBARTRACKINFO* pSBTrack = pGallery->GetScrollBarTrackInfo();
CXTPControlGallery::SCROLLBARPOSINFO* pSBInfo = pGallery->GetScrollBarPosInfo();
CRect rcControl = pGallery->GetRect();
CRect rcScroll(rcControl.right - 15, rcControl.top, rcControl.right, rcControl.bottom);
CRect rcScrollUp(rcScroll.left, rcScroll.top, rcScroll.right, rcScroll.top + m_cyPopupUp);
CRect rcScrollDown(rcScroll.left, rcScrollUp.bottom, rcScroll.right, rcScrollUp.bottom + m_cyPopupDown);
CRect rcScrollPopup(rcScroll.left, rcScrollDown.bottom, rcScroll.right, rcScroll.bottom);
CXTPOffice2007Theme* pPaintManager = (CXTPOffice2007Theme*)m_pPaintManager;
CXTPResourceImage* pImage = pPaintManager->LoadImage(_T("CONTROLGALLERYUP"));
ASSERT(pImage);
if (!pImage)
return;
BOOL bControlEnabled = pGallery->GetEnabled();
BOOL nPressetHt = pSBTrack ? pSBInfo->ht : -1;
BOOL nHotHt = pSBTrack ? -1 : pSBInfo->ht;
if (nHotHt == HTNOWHERE && nPressetHt == -1 && bControlEnabled && IsKeyboardSelected(pGallery->GetSelected()) && pGallery->GetSelectedItem() == -1)
nHotHt = XTP_HTSCROLLPOPUP;
int nState = GETPARTSTATE3(XTP_HTSCROLLUP, (bControlEnabled && pGallery->IsScrollButtonEnabled(XTP_HTSCROLLUP)));
pImage->DrawImage(pDC, rcScrollUp, pImage->GetSource(nState, 5), CRect(3, 3, 3, 3), 0xFF00FF);
nState = GETPARTSTATE3(XTP_HTSCROLLDOWN, (bControlEnabled && pGallery->IsScrollButtonEnabled(XTP_HTSCROLLDOWN)));
pImage = pPaintManager->LoadImage(_T("CONTROLGALLERYDOWN"));
pImage->DrawImage(pDC, rcScrollDown, pImage->GetSource(nState, 5), CRect(3, 3, 3, 3), 0xFF00FF);
nState = GETPARTSTATE3(XTP_HTSCROLLPOPUP, bControlEnabled);
pImage = pPaintManager->LoadImage(_T("CONTROLGALLERYPOPUP"));
pImage->DrawImage(pDC, rcScrollPopup, pImage->GetSource(nState, 5), CRect(3, 3, 3, 3), 0xFF00FF);
}
AFX_INLINE CRect OffsetSourceRect(CRect rc, int nState)
{
rc.OffsetRect(0, (nState - 1) * rc.Height());
return rc;
}
void CXTPControlGalleryOffice2007Theme::DrawScrollBar(CDC* pDC, CXTPScrollBase* pGallery)
{
XTPScrollBarStyle barStyle = pGallery->GetScrollBarStyle();
if (barStyle != xtpScrollStyleOffice2007Light && barStyle != xtpScrollStyleOffice2007Dark)
{
CXTPControlGalleryPaintManager::DrawScrollBar(pDC, pGallery);
return;
}
BOOL bLight = (barStyle == xtpScrollStyleOffice2007Light);
#define GETPARTSTATE2(ht) \
(!bEnabled ? 0 : nPressetHt == ht ? 3 : nHotHt == ht ? 2 : nHotHt > 0 || nPressetHt > 0 ? 1 : 0)
CXTPControlGallery::SCROLLBARTRACKINFO* pSBTrack = pGallery->GetScrollBarTrackInfo();
CXTPControlGallery::SCROLLBARPOSINFO* pSBInfo = pGallery->GetScrollBarPosInfo();
BOOL nPressetHt = pSBTrack ? pSBInfo->ht : -1;
BOOL nHotHt = pSBTrack ? -1 : pSBInfo->ht;
int cWidth = (pSBInfo->pxRight - pSBInfo->pxLeft);
if (cWidth <= 0)
{
return;
}
BOOL bEnabled = (pSBInfo->posMax - pSBInfo->posMin - pSBInfo->page + 1 > 0) && pGallery->IsScrollBarEnabled();
int nBtnTrackSize = pSBInfo->pxThumbBottom - pSBInfo->pxThumbTop;
int nBtnTrackPos = pSBInfo->pxThumbTop - pSBInfo->pxUpArrow;
if (!bEnabled || pSBInfo->pxThumbBottom > pSBInfo->pxDownArrow)
nBtnTrackPos = nBtnTrackSize = 0;
CXTPOffice2007Theme* pPaintManager = (CXTPOffice2007Theme*)m_pPaintManager;
CXTPResourceImage* pImageArrowGlyphs = NULL;
if (!bLight)
{
pImageArrowGlyphs = pPaintManager->LoadImage(_T("CONTROLGALLERYSCROLLARROWGLYPHSDARK"));
}
if (!pImageArrowGlyphs) pImageArrowGlyphs = pPaintManager->LoadImage(_T("CONTROLGALLERYSCROLLARROWGLYPHS"));
ASSERT(pImageArrowGlyphs);
if (!pImageArrowGlyphs)
return;
CRect rcArrowGripperSrc(0, 0, 9, 9);
if (pSBInfo->fVert)
{
CXTPResourceImage* pImageBackground = pPaintManager->LoadImage(
bLight ? _T("CONTROLGALLERYSCROLLVERTICALLIGHT") : _T("CONTROLGALLERYSCROLLVERTICALDARK"));
ASSERT(pImageBackground);
if (!pImageBackground)
return;
pImageBackground->DrawImage(pDC, pSBInfo->rc, pImageBackground->GetSource(0, 2), CRect(1, 0, 1, 0));
CRect rcVScroll(pSBInfo->rc);
rcVScroll.DeflateRect(1, 0);
CRect rcArrowUp(rcVScroll.left, rcVScroll.top, rcVScroll.right, pSBInfo->pxUpArrow);
CRect rcArrowDown(rcVScroll.left, pSBInfo->pxDownArrow, rcVScroll.right, rcVScroll.bottom);
CXTPResourceImage* pImage = pPaintManager->LoadImage(
bLight ? _T("CONTROLGALLERYSCROLLARROWSVERTICALLIGHT") : _T("CONTROLGALLERYSCROLLARROWSVERTICALDARK"));
ASSERT(pImage);
if (!pImage)
return;
int nState = GETPARTSTATE2(XTP_HTSCROLLUP);
if (nState != 0)
{
pImage->DrawImage(pDC, rcArrowUp, pImage->GetSource(nState, 4), CRect(3, 3, 3, 3));
}
CRect rcArrowUpGripper(CPoint((rcArrowUp.left + rcArrowUp.right - 9) / 2, (rcArrowUp.top + rcArrowUp.bottom - 9) / 2), CSize(9, 9));
pImageArrowGlyphs->DrawImage(pDC, rcArrowUpGripper, OffsetSourceRect(rcArrowGripperSrc, !bEnabled ? ABS_UPDISABLED : nState != 0 ? ABS_UPHOT : ABS_UPNORMAL), CRect(0, 0, 0, 0), RGB(255, 0, 255));
nState = GETPARTSTATE2(XTP_HTSCROLLDOWN);
if (nState != 0)
{
pImage->DrawImage(pDC, rcArrowDown, pImage->GetSource(nState, 4), CRect(3, 3, 3, 3));
}
CRect rcArrowDownGripper(CPoint((rcArrowDown.left + rcArrowDown.right - 9) / 2, (rcArrowDown.top + rcArrowDown.bottom - 9) / 2), CSize(9, 9));
pImageArrowGlyphs->DrawImage(pDC, rcArrowDownGripper, OffsetSourceRect(rcArrowGripperSrc, !bEnabled ? ABS_DOWNDISABLED : nState != 0 ? ABS_DOWNHOT : ABS_DOWNNORMAL), CRect(0, 0, 0, 0), RGB(255, 0, 255));
CRect rcTrack(rcVScroll.left, rcArrowUp.bottom, rcVScroll.right, rcArrowDown.top);
if (!rcTrack.IsRectEmpty())
{
CRect rcLowerTrack(rcTrack.left - 1, rcTrack.top, rcTrack.right + 1, rcTrack.top + nBtnTrackPos);
CRect rcBtnTrack(rcTrack.left, rcLowerTrack.bottom, rcTrack.right, rcLowerTrack.bottom + nBtnTrackSize);
CRect rcUpperTrack(rcTrack.left - 1, rcBtnTrack.bottom, rcTrack.right + 1, rcTrack.bottom);
if (!rcLowerTrack.IsRectEmpty() && (GETPARTSTATE2(XTP_HTSCROLLUPPAGE) == 3))
{
pImageBackground->DrawImage(pDC, rcLowerTrack,
pImageBackground->GetSource(1, 2), CRect(1, 0, 1, 0));
}
if (!rcBtnTrack.IsRectEmpty())
{
nState = GETPARTSTATE2(XTP_HTSCROLLTHUMB);
if (nState > 0) nState--;
if (!bLight)
{
pImage = pPaintManager->LoadImage(_T("CONTROLGALLERYSCROLLTHUMBVERTICALDARK"));
if (!pImage) pImage = pPaintManager->LoadImage(_T("CONTROLGALLERYSCROLLTHUMBVERTICAL"));
}
else
{
pImage = pPaintManager->LoadImage(_T("CONTROLGALLERYSCROLLTHUMBVERTICAL"));
}
ASSERT(pImage);
if (!pImage)
return;
pImage->DrawImage(pDC, rcBtnTrack, pImage->GetSource(nState, 3), CRect(5, 5, 5, 5));
if (rcBtnTrack.Height() > 10)
{
pImage = pPaintManager->LoadImage(_T("CONTROLGALLERYSCROLLTHUMBGRIPPERVERTICAL"));
CRect rcGripper(CPoint(rcBtnTrack.CenterPoint().x - 4, rcBtnTrack.CenterPoint().y - 4), CSize(8, 8));
pImage->DrawImage(pDC, rcGripper, pImage->GetSource(nState, 3), CRect(0, 0, 0, 0));
}
}
if (!rcUpperTrack.IsRectEmpty() && (GETPARTSTATE2(XTP_HTSCROLLDOWNPAGE) == 3))
{
pImageBackground->DrawImage(pDC, rcUpperTrack,
pImageBackground->GetSource(1, 2), CRect(1, 0, 1, 0));
}
}
}
else
{
CXTPResourceImage* pImageBackground = pPaintManager->LoadImage(
bLight ? _T("CONTROLGALLERYSCROLLHORIZONTALLIGHT") : _T("CONTROLGALLERYSCROLLHORIZONTALDARK"));
if (!pImageBackground)
{
CXTPControlGalleryPaintManager::DrawScrollBar(pDC, pGallery);
return;
}
pImageBackground->DrawImage(pDC, pSBInfo->rc, pImageBackground->GetSource(0, 2), CRect(0, 1, 0, 1));
CRect rcHScroll(pSBInfo->rc);
rcHScroll.DeflateRect(0, 1);
CRect rcArrowLeft(rcHScroll.left, rcHScroll.top, pSBInfo->pxUpArrow, rcHScroll.bottom);
CRect rcArrowRight(pSBInfo->pxDownArrow, rcHScroll.top, rcHScroll.right, rcHScroll.bottom);
CXTPResourceImage* pImage = pPaintManager->LoadImage(
bLight ? _T("CONTROLGALLERYSCROLLARROWSHORIZONTALLIGHT") : _T("CONTROLGALLERYSCROLLARROWSHORIZONTALDARK"));
ASSERT(pImage);
if (!pImage)
return;
int nState = GETPARTSTATE2(XTP_HTSCROLLUP);
if (nState != 0)
{
pImage->DrawImage(pDC, rcArrowLeft, pImage->GetSource(nState, 4), CRect(3, 3, 3, 3));
}
CRect rcArrowLeftGripper(CPoint((rcArrowLeft.left + rcArrowLeft.right - 9) / 2, (rcArrowLeft.top + rcArrowLeft.bottom - 9) / 2), CSize(9, 9));
pImageArrowGlyphs->DrawImage(pDC, rcArrowLeftGripper, OffsetSourceRect(rcArrowGripperSrc, !bEnabled ? ABS_LEFTDISABLED : nState != 0 ? ABS_LEFTHOT : ABS_LEFTNORMAL), CRect(0, 0, 0, 0), RGB(255, 0, 255));
nState = GETPARTSTATE2(XTP_HTSCROLLDOWN);
if (nState != 0)
{
pImage->DrawImage(pDC, rcArrowRight, pImage->GetSource(nState, 4), CRect(3, 3, 3, 3));
}
CRect rcArrowRightGripper(CPoint((rcArrowRight.left + rcArrowRight.right - 9) / 2, (rcArrowRight.top + rcArrowRight.bottom - 9) / 2), CSize(9, 9));
pImageArrowGlyphs->DrawImage(pDC, rcArrowRightGripper, OffsetSourceRect(rcArrowGripperSrc, !bEnabled ? ABS_RIGHTDISABLED : nState != 0 ? ABS_RIGHTHOT : ABS_RIGHTNORMAL), CRect(0, 0, 0, 0), RGB(255, 0, 255));
CRect rcTrack(rcArrowLeft.right, rcHScroll.top, rcArrowRight.left, rcHScroll.bottom);
if (!rcTrack.IsRectEmpty())
{
CRect rcLowerTrack(rcTrack.left, rcTrack.top - 1, rcTrack.left + nBtnTrackPos, rcTrack.bottom + 1);
CRect rcBtnTrack(rcLowerTrack.right, rcTrack.top, rcLowerTrack.right + nBtnTrackSize, rcTrack.bottom);
CRect rcUpperTrack(rcBtnTrack.right, rcTrack.top - 1, rcTrack.right, rcTrack.bottom + 1);
if (!rcLowerTrack.IsRectEmpty() && (GETPARTSTATE2(XTP_HTSCROLLUPPAGE) == 3))
{
pImageBackground->DrawImage(pDC, rcLowerTrack,
pImageBackground->GetSource(1, 2), CRect(0, 1, 0, 1));
}
if (!rcBtnTrack.IsRectEmpty())
{
nState = GETPARTSTATE2(XTP_HTSCROLLTHUMB);
if (nState > 0) nState--;
if (!bLight)
{
pImage = pPaintManager->LoadImage(_T("CONTROLGALLERYSCROLLTHUMBHORIZONTALDARK"));
if (!pImage) pImage = pPaintManager->LoadImage(_T("CONTROLGALLERYSCROLLTHUMBHORIZONTAL"));
}
else
{
pImage = pPaintManager->LoadImage(_T("CONTROLGALLERYSCROLLTHUMBHORIZONTAL"));
}
ASSERT(pImage);
if (!pImage)
return;
pImage->DrawImage(pDC, rcBtnTrack, pImage->GetSource(nState, 3), CRect(5, 5, 5, 5));
if (rcBtnTrack.Width() > 10)
{
pImage = pPaintManager->LoadImage(_T("CONTROLGALLERYSCROLLTHUMBGRIPPERHORIZONTAL"));
CRect rcGripper(CPoint(rcBtnTrack.CenterPoint().x - 3, rcBtnTrack.CenterPoint().y - 4), CSize(8, 8));
pImage->DrawImage(pDC, rcGripper, pImage->GetSource(nState, 3), CRect(0, 0, 0, 0));
}
}
if (!rcUpperTrack.IsRectEmpty() && (GETPARTSTATE2(XTP_HTSCROLLDOWNPAGE) == 3))
{
pImageBackground->DrawImage(pDC, rcUpperTrack,
pImageBackground->GetSource(1, 2), CRect(0, 1, 0, 1));
}
}
}
}
//////////////////////////////////////////////////////////////////////////
// CXTPControlSliderOffice2007Theme
void CXTPSliderOffice2007Theme::RefreshMetrics()
{
CXTPSliderPaintManager::RefreshMetrics();
CXTPResourceImage* pImage = ((CXTPOffice2007Theme*)m_pPaintManager)->LoadImage(_T("SLIDERUP"));
if (pImage)
{
m_cyHScroll = pImage->GetSource(0, 3).Height();
m_cxHScroll = pImage->GetSource(0, 3).Width();
}
m_cThumb = 11;
}
void CXTPSliderOffice2007Theme::DrawScrollBar(CDC* pDC, CXTPScrollBase* pGallery)
{
#define GETPARTSTATE4(ht) (nPressetHt == ht ? 2 : nHotHt == ht ? 1 : 0)
CXTPScrollBase::SCROLLBARTRACKINFO* pSBTrack = pGallery->GetScrollBarTrackInfo();
CXTPScrollBase::SCROLLBARPOSINFO* pSBInfo = pGallery->GetScrollBarPosInfo();
BOOL nPressetHt = pSBTrack ? (pSBTrack->bTrackThumb || pSBTrack->fHitOld ? pSBInfo->ht : -1) : -1;
BOOL nHotHt = pSBTrack ? -1 : pSBInfo->ht;
int cWidth = (pSBInfo->pxRight - pSBInfo->pxLeft);
if (cWidth <= 0)
{
return;
}
BOOL bEnabled = (pSBInfo->posMax - pSBInfo->posMin - pSBInfo->page + 1 > 0) && pGallery->IsScrollBarEnabled();
int nBtnTrackSize = pSBInfo->pxThumbBottom - pSBInfo->pxThumbTop;
int nBtnTrackPos = pSBInfo->pxThumbTop - pSBInfo->pxUpArrow;
if (!bEnabled || pSBInfo->pxThumbBottom > pSBInfo->pxDownArrow)
nBtnTrackPos = nBtnTrackSize = 0;
CXTPOffice2007Theme* pPaintManager = (CXTPOffice2007Theme*)m_pPaintManager;
if (!pSBInfo->fVert)
{
CRect rcHScroll(pSBInfo->rc);
CRect rcArrowLeft(rcHScroll.left, rcHScroll.top, pSBInfo->pxUpArrow, rcHScroll.bottom);
CRect rcArrowRight(pSBInfo->pxDownArrow, rcHScroll.top, rcHScroll.right, rcHScroll.bottom);
CRect rcTrack(rcArrowLeft.right, rcHScroll.top, rcArrowRight.left, rcHScroll.bottom);
CRect rcBtnTrack(rcTrack.left + nBtnTrackPos, rcTrack.top, rcTrack.left + nBtnTrackPos + nBtnTrackSize, rcTrack.bottom);
CXTPResourceImage* pImage = pPaintManager->LoadImage(_T("SLIDERTRACK"));
ASSERT(pImage);
if (!pImage)
return;
CRect rcTrackDest(CPoint(rcTrack.left, (rcTrack.top + rcTrack.bottom - pImage->GetHeight()) / 2), CSize(rcTrack.Width(), pImage->GetHeight()));
pImage->DrawImage(pDC, rcTrackDest, pImage->GetSource());
pImage = pPaintManager->LoadImage(_T("SLIDERTICK"));
CXTPScrollBase::SLIDERTICKS* pTicks = pGallery->GetTicks();
if (!pTicks || (pSBInfo->posMax <= pSBInfo->posMin))
{
CRect rcTrackTickDest(CPoint((rcTrackDest.left + rcTrackDest.right - pImage->GetWidth()) / 2,
(rcTrackDest.top + rcTrackDest.bottom - pImage->GetHeight()) / 2), pImage->GetExtent());
pImage->DrawImage(pDC, rcTrackTickDest, pImage->GetSource(), CRect(0, 0, 0, 0), 0xFF00FF);
}
else
{
rcTrackDest.DeflateRect(6, 0);
for (int i = 0; i < pTicks->nCount; i++)
{
double dTick = pTicks->pTicks[i];
double dPos = (dTick - pSBInfo->posMin) * rcTrackDest.Width() / (pSBInfo->posMax - pSBInfo->posMin);
if (dPos >= 0 && dPos <= rcTrackDest.Width())
{
CRect rcTrackTickDest(CPoint(rcTrackDest.left + (int)dPos - pImage->GetWidth() / 2,
(rcTrackDest.top + rcTrackDest.bottom - pImage->GetHeight()) / 2), pImage->GetExtent());
pImage->DrawImage(pDC, rcTrackTickDest, pImage->GetSource(), CRect(0, 0, 0, 0), 0xFF00FF);
}
}
}
pImage = pPaintManager->LoadImage(_T("SLIDERUP"));
pImage->DrawImage(pDC, rcArrowLeft, pImage->GetSource(GETPARTSTATE4(XTP_HTSCROLLUP), 3));
pImage = pPaintManager->LoadImage(_T("SLIDERDOWN"));
pImage->DrawImage(pDC, rcArrowRight, pImage->GetSource(GETPARTSTATE4(XTP_HTSCROLLDOWN), 3));
if (bEnabled)
{
pImage = pPaintManager->LoadImage(_T("SLIDERTHUMB"));
CRect rcImgSrc = pImage->GetSource(
nPressetHt == XTP_HTSCROLLTHUMB ? 2 : nPressetHt == XTP_HTSCROLLUPPAGE || nPressetHt == XTP_HTSCROLLDOWNPAGE ||
nHotHt == XTP_HTSCROLLUPPAGE || nHotHt == XTP_HTSCROLLDOWNPAGE || nHotHt == XTP_HTSCROLLTHUMB ? 1 : 0, 3);
CRect rcBtnTrackDest(CPoint((rcBtnTrack.left + rcBtnTrack.right - rcImgSrc.Width()) / 2,
(rcBtnTrack.top + rcBtnTrack.bottom - rcImgSrc.Height()) / 2), rcImgSrc.Size());
pImage->DrawImage(pDC, rcBtnTrackDest, rcImgSrc);
}
}
}
//////////////////////////////////////////////////////////////////////////
// CXTPProgressOffice2007Theme
CXTPProgressOffice2007Theme::CXTPProgressOffice2007Theme(CXTPPaintManager* pPaintManager)
: CXTPProgressPaintManager(pPaintManager)
{
m_cyProgress = 12;
}
void CXTPProgressOffice2007Theme::DrawProgress(CDC* pDC, CXTPProgressBase* pProgressBar)
{
CXTPOffice2007Theme* pPaintManager = (CXTPOffice2007Theme*)m_pPaintManager;
CXTPResourceImage* pImage = pPaintManager->LoadImage(_T("PROGRESSTRACK"));
ASSERT(pImage);
if (!pImage)
return;
CRect rc = pProgressBar->GetProgressRect();
pImage->DrawImage(pDC, rc, pImage->GetSource(), CRect(2, 2, 2, 2), 0xFF00FF);
int nLower, nUpper, nPos;
pProgressBar->GetRange(nLower, nUpper);
nPos = pProgressBar->GetPos();
rc.DeflateRect(2, 2);
int nWidth = rc.Width();
int x = MulDiv(nWidth, nPos - nLower, nUpper - nLower);
pImage = pPaintManager->LoadImage(_T("PROGRESSCHUNK"));
ASSERT(pImage);
if (!pImage)
return;
CRect rcSrc(pImage->GetSource());
rcSrc.right -= 4;
CRect rcDest(rc.left, rc.top, rc.left + x, rc.bottom);
if (rcDest.Width() < rcSrc.Width())
rcSrc.left = rcSrc.right - rcDest.Width();
pImage->DrawImage(pDC, rcDest, rcSrc, CRect(2, 2, 2, 2), 0xFF00FF);
if (rc.left + x < rc.right - 1)
{
int nShadow = min(4, rc.right - rc.left - x);
rcSrc = CRect(rcSrc.right, rcSrc.top, rcSrc.right + nShadow, rcSrc.bottom);
rcDest = CRect(rcDest.right, rcDest.top, rcDest.right + nShadow, rcDest.bottom);
pImage->DrawImage(pDC, rcDest, rcSrc, CRect(0, 2, 0, 2), 0xFF00FF);
return;
}
}
//////////////////////////////////////////////////////////////////////////
// CXTPFramePaintManager
CXTPFramePaintManager::CXTPFramePaintManager(CXTPPaintManager* pPaintManager)
{
m_pPaintManager = pPaintManager;
m_bFrameStatusBar = FALSE;
m_bRoundedCornersAlways = FALSE;
}
CXTPFramePaintManager::~CXTPFramePaintManager()
{
}
HRGN CXTPFramePaintManager::CalcFrameRegion(CXTPOffice2007FrameHook* pFrameHook, CSize sz)
{
if (pFrameHook->GetSite()->GetStyle() & WS_MAXIMIZE)
{
return NULL;
}
int cx = sz.cx, cy = sz.cy;
RECT rgnTopFrame[] =
{
{4, 0, cx - 4, 1}, {2, 1, cx - 2, 2}, {1, 2, cx - 1, 3}, {1, 3, cx - 1, 4}, {0, 4, cx, cy - 4}
};
RECT rgnRibbonBottomFrame[] =
{
{1, cy - 4, cx - 1, cy - 2}, {2, cy - 2, cx - 2, cy - 1}, {4, cy - 1, cx - 4, cy - 0}
};
RECT rgnSimpleBottomFrame[] =
{
{0, cy - 4, cx, cy}
};
BOOL bHasStatusBar = (m_bRoundedCornersAlways || pFrameHook->IsFrameHasStatusBar()) && pFrameHook->GetFrameBorder() > 3;
int nSizeTopRect = sizeof(rgnTopFrame);
int nSizeBottomRect = bHasStatusBar ? sizeof(rgnRibbonBottomFrame) : sizeof(rgnSimpleBottomFrame);
int nSizeData = sizeof(RGNDATAHEADER) + nSizeTopRect + nSizeBottomRect;
RGNDATA* pRgnData = (RGNDATA*)malloc(nSizeData);
if (!pRgnData)
return NULL;
memcpy(&pRgnData->Buffer, (void*)&rgnTopFrame, nSizeTopRect);
memcpy(&pRgnData->Buffer + nSizeTopRect, bHasStatusBar ? (void*)&rgnRibbonBottomFrame : (void*)&rgnSimpleBottomFrame, nSizeBottomRect);
pRgnData->rdh.dwSize = sizeof(RGNDATAHEADER);
pRgnData->rdh.iType = RDH_RECTANGLES;
pRgnData->rdh.nCount = (nSizeTopRect + nSizeBottomRect) / sizeof(RECT);
pRgnData->rdh.nRgnSize = 0;
pRgnData->rdh.rcBound = CRect(0, 0, cx, cy);
CRgn rgnResult;
VERIFY(rgnResult.CreateFromData(NULL, nSizeData, pRgnData));
free(pRgnData);
return (HRGN)rgnResult.Detach();
}
void CXTPFramePaintManager::DrawCaptionText(CDC* pDC, CRect rcCaptionText, CWnd* pSite, BOOL bActive)
{
CString strWindowText;
CXTPDrawHelpers::GetWindowCaption(pSite->GetSafeHwnd(), strWindowText);
pDC->SetBkMode(TRANSPARENT);
CXTPFontDC font(pDC, &m_fontFrameCaption);
pDC->SetTextColor(!bActive ? m_clrFrameCaptionTextInActive : m_clrFrameCaptionTextActive); //RGB(62, 106, 170));
if (pSite->GetStyle() & FWS_PREFIXTITLE)
{
#if _MSC_VER >= 1200
CFrameWnd* pFrame = pSite->IsFrameWnd() ? (CFrameWnd*)pSite : NULL;
CString strTitle = pFrame ? pFrame->GetTitle() : _T("");
if (!strTitle.IsEmpty() && strWindowText.Right(strTitle.GetLength()) == strTitle & ((pSite->GetExStyle() & WS_EX_LAYOUTRTL) == 0))
{
strWindowText.Delete(strWindowText.GetLength() - strTitle.GetLength(), strTitle.GetLength());
pDC->DrawText(strWindowText, rcCaptionText, DT_VCENTER | DT_LEFT| DT_END_ELLIPSIS | DT_SINGLELINE | DT_NOPREFIX);
int nExtent = pDC->GetTextExtent(strWindowText).cx;
rcCaptionText.left += nExtent + 2;
if (rcCaptionText.left < rcCaptionText.right - 5)
{
if (bActive) pDC->SetTextColor(m_clrFrameCaptionTextActiveTitle);
pDC->DrawText(strTitle, rcCaptionText, DT_VCENTER | DT_LEFT| DT_END_ELLIPSIS | DT_SINGLELINE | DT_NOPREFIX);
}
}
else
#endif
{
pDC->DrawText(strWindowText, rcCaptionText, DT_VCENTER | DT_LEFT| DT_END_ELLIPSIS | DT_SINGLELINE | DT_NOPREFIX);
}
}
else
{
pDC->DrawText(strWindowText, rcCaptionText, DT_VCENTER | DT_LEFT| DT_END_ELLIPSIS | DT_SINGLELINE | DT_NOPREFIX);
}
}
void CXTPFramePaintManager::RefreshMetrics()
{
GetImages()->AssertValid();
m_nFrameCaptionHeight = GetSystemMetrics(SM_CYCAPTION);
m_nFrameCaptionHeight = max(m_nFrameCaptionHeight, 17);
m_clrFrameBorderActive0 = GetImages()->GetImageColor(_T("Window"), _T("BorderActive0"));
m_clrFrameBorderActive1 = GetImages()->GetImageColor(_T("Window"), _T("BorderActive1"));
m_clrFrameBorderActive2 = GetImages()->GetImageColor(_T("Window"), _T("BorderActive2"));
m_clrFrameBorderActive3 = GetImages()->GetImageColor(_T("Window"), _T("BorderActive3"));
m_clrFrameBorderInactive0 = GetImages()->GetImageColor(_T("Window"), _T("BorderInactive0"));
m_clrFrameBorderInactive1 = GetImages()->GetImageColor(_T("Window"), _T("BorderInactive1"));
m_clrFrameBorderInactive2 = GetImages()->GetImageColor(_T("Window"), _T("BorderInactive2"));
m_clrFrameBorderInactive3 = GetImages()->GetImageColor(_T("Window"), _T("BorderInactive3"));
m_clrFrameCaptionTextActiveTitle = GetImages()->GetImageColor(_T("Window"), _T("CaptionTextActiveTitle"));
m_clrFrameCaptionTextInActive = GetImages()->GetImageColor(_T("Window"), _T("CaptionTextInActive"));
m_clrFrameCaptionTextActive = GetImages()->GetImageColor(_T("Window"), _T("CaptionTextActive"));
m_bFlatFrame = GetImages()->GetImageInt(_T("Window"), _T("FlatFrame"), 0);
CXTPPaintManager::CNonClientMetrics ncm;
ncm.lfSmCaptionFont.lfWeight = FW_NORMAL;
if (m_pPaintManager->m_bClearTypeTextQuality &&
XTPSystemVersion()->IsClearTypeTextQualitySupported())
{
ncm.lfCaptionFont.lfQuality = 5;
}
ncm.lfCaptionFont.lfWeight = FW_NORMAL;
if (m_pPaintManager->m_bUseOfficeFont && CXTPDrawHelpers::FontExists(m_pPaintManager->m_strOfficeFont))
STRCPY_S(ncm.lfCaptionFont.lfFaceName, LF_FACESIZE, m_pPaintManager->m_strOfficeFont);
if (ncm.lfCaptionFont.lfHeight < 0)
ncm.lfCaptionFont.lfHeight = min(-11, ncm.lfCaptionFont.lfHeight);
ncm.lfCaptionFont.lfCharSet = XTPResourceManager()->GetFontCharset();
m_fontFrameCaption.SetStandardFont(&ncm.lfCaptionFont);
}
CXTPResourceImages* CXTPFramePaintManager::GetImages() const
{
return XTPResourceImages();
}
CXTPResourceImage* CXTPFramePaintManager::LoadImage(LPCTSTR lpszFileName)
{
return GetImages()->LoadFile(lpszFileName);
}
void CXTPFramePaintManager::DrawFrame(CDC* pDC, CXTPOffice2007FrameHook* pFrameHook)
{
CWnd* pSite = pFrameHook->GetSite();
BOOL bActive = pFrameHook->IsFrameActive();
CXTPClientRect rcBorders(pSite);
pSite->ClientToScreen(rcBorders);
CXTPWindowRect rc(pSite);
int nRightBorder = rcBorders.left - rc.left, nLeftBorder = rcBorders.left - rc.left, nBorder = pFrameHook->GetFrameBorder();
int nBottomBorder = rc.bottom - rcBorders.bottom;
rc.OffsetRect(-rc.TopLeft());
CRect rcFrame(rc);
int nCaptionHeight = pFrameHook->GetCaptionHeight();
rcFrame.top += nCaptionHeight;
int nStatusHeight = 0;
BOOL bHasStatusBar = pFrameHook->IsFrameHasStatusBar(&nStatusHeight);
int nBordersHeight = bHasStatusBar ? rcFrame.Height() - nStatusHeight - 1 : rcFrame.Height();
if (nLeftBorder > 0) pDC->FillSolidRect(rc.left + 0, rcFrame.top, 1, rcFrame.Height(), bActive ? m_clrFrameBorderActive0 : m_clrFrameBorderInactive0);
if (nLeftBorder > 1) pDC->FillSolidRect(rc.left + 1, rcFrame.top, 1, nBordersHeight, bActive ? m_clrFrameBorderActive1 : m_clrFrameBorderInactive1);
if (nRightBorder > 0) pDC->FillSolidRect(rc.right - 1, rcFrame.top, 1, rcFrame.Height(), bActive ? m_clrFrameBorderActive0 : m_clrFrameBorderInactive0);
if (nRightBorder > 1) pDC->FillSolidRect(rc.right - 2, rcFrame.top, 1, nBordersHeight, bActive ? m_clrFrameBorderActive1 : m_clrFrameBorderInactive1);
if (m_bFlatFrame)
{
if (nLeftBorder > 2) pDC->FillSolidRect(rc.left + 2, rcFrame.top, nLeftBorder - 3, nBordersHeight, bActive ? m_clrFrameBorderActive2 : m_clrFrameBorderInactive2);
if (nLeftBorder > 2) pDC->FillSolidRect(rc.left + nLeftBorder - 1, rcFrame.top, 1, nBordersHeight, bActive ? m_clrFrameBorderActive3 : m_clrFrameBorderInactive3);
if (nRightBorder > 2) pDC->FillSolidRect(rc.right - nRightBorder + 1, rcFrame.top, nRightBorder - 3, nBordersHeight, bActive ? m_clrFrameBorderActive2 : m_clrFrameBorderInactive2);
if (nRightBorder > 2) pDC->FillSolidRect(rc.right - nRightBorder, rcFrame.top, 1, nBordersHeight, bActive ? m_clrFrameBorderActive3 : m_clrFrameBorderInactive3);
}
else
{
if (nLeftBorder > 2) pDC->FillSolidRect(rc.left + 2, rcFrame.top, 1, nBordersHeight, bActive ? m_clrFrameBorderActive2 : m_clrFrameBorderInactive2);
if (nLeftBorder > 3) pDC->FillSolidRect(rc.left + 3, rcFrame.top, nLeftBorder - 3, nBordersHeight, bActive ? m_clrFrameBorderActive3 : m_clrFrameBorderInactive3);
if (nRightBorder > 2) pDC->FillSolidRect(rc.right - 3, rcFrame.top, 1, nBordersHeight, bActive ? m_clrFrameBorderActive2 : m_clrFrameBorderInactive2);
if (nRightBorder > 3) pDC->FillSolidRect(rc.right - nRightBorder, rcFrame.top, nRightBorder - 3, nBordersHeight, bActive ? m_clrFrameBorderActive3 : m_clrFrameBorderInactive3);
}
pDC->FillSolidRect(rc.left, rc.bottom - 1, rc.Width(), 1,
bActive ? pSite->GetStyle() & WS_MAXIMIZE ? m_clrFrameBorderActive3 : m_clrFrameBorderActive0 : m_clrFrameBorderInactive0);
if (nBottomBorder > 1)
{
if (m_bFlatFrame)
{
pDC->FillSolidRect(rc.left + nLeftBorder, rc.bottom - nBottomBorder, rc.Width() - nLeftBorder - nRightBorder, 1, bActive ? m_clrFrameBorderActive3 : m_clrFrameBorderInactive3);
pDC->FillSolidRect(rc.left + 1, rc.bottom - nBottomBorder + 1, rc.Width() - 2, nBottomBorder - 2, bActive ? m_clrFrameBorderActive2 : m_clrFrameBorderInactive2);
}
else
{
pDC->FillSolidRect(rc.left + 1, rc.bottom - nBottomBorder, rc.Width() - 2, nBottomBorder - 1, bActive ? m_clrFrameBorderActive3 : m_clrFrameBorderInactive3);
}
}
//////////////////////////////////////////////////////////////////////////
CRect rcCaption(rc.left, rc.top, rc.right, rc.top + nCaptionHeight);
if (pFrameHook->IsCaptionVisible())
{
CXTPBufferDC dc(*pDC, rcCaption);
CRect rcTopLeft, rcTopRight, rcTopCenter, rcSrcTopLeft, rcSrcTopRight;
rcTopLeft.SetRectEmpty();
rcTopRight.SetRectEmpty();
rcTopCenter.SetRectEmpty();
rcSrcTopLeft.SetRectEmpty();
rcSrcTopRight.SetRectEmpty();
CXTPResourceImage* pImage = LoadImage(_T("FRAMETOPLEFT"));
if (pImage)
{
rcSrcTopLeft = pImage->GetSource(bActive ? 0 : 1, 2);
rcTopLeft.SetRect(rc.left, rc.top, rc.left + rcSrcTopLeft.Width(), rcCaption.bottom);
pImage->DrawImage(&dc, rcTopLeft, rcSrcTopLeft, CRect(0, 5, 0, 3));
}
//
pImage = LoadImage(_T("FRAMETOPRIGHT"));
if (pImage)
{
rcSrcTopRight = pImage->GetSource(bActive ? 0 : 1, 2);
rcTopRight.SetRect(rc.right - rcSrcTopRight.Width(), rc.top, rc.right, rcCaption.bottom);
pImage->DrawImage(&dc, rcTopRight, rcSrcTopRight, CRect(0, 5, 0, 3));
}
pImage = LoadImage(_T("FRAMETOPCENTER"));
if (pImage)
{
rcTopCenter.SetRect(rc.left + rcTopLeft.Width(), rc.top, rc.right - rcSrcTopRight.Width(), rcCaption.bottom);
pImage->DrawImage(&dc, rcTopCenter, pImage->GetSource(bActive ? 0 : 1, 2), CRect(0, 5, 0, 3));
}
CRect rcCaptionText(rcCaption);
rcCaptionText.left = 7;
rcCaptionText.DeflateRect(0, nBorder, 0, 3);
HICON hIcon = GetFrameSmallIcon(pSite);
if (hIcon)
{
CSize szIcon(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON));
int cBorders = nBorder - 1;
int cxySlot = rcCaption.Height() - cBorders;
int nTop = cBorders + (cxySlot - szIcon.cy - 1)/2;
DWORD dwLayout = XTPDrawHelpers()->IsContextRTL(&dc);
if (dwLayout & LAYOUT_RTL)
XTPDrawHelpers()->SetContextRTL(&dc, dwLayout | LAYOUT_BITMAPORIENTATIONPRESERVED);
DrawIconEx(dc.m_hDC, rcCaptionText.left, nTop, hIcon,
szIcon.cx, szIcon.cy, 0, NULL, DI_NORMAL);
if (dwLayout & LAYOUT_RTL)
XTPDrawHelpers()->SetContextRTL(&dc, dwLayout);
rcCaptionText.left = 7 + szIcon.cx + 5;
}
CXTPControls* pCaptionButtons = pFrameHook->GetCaptionButtons();
for (int i = 0; i < pCaptionButtons->GetCount(); i++)
{
CXTPControl* pControl = pCaptionButtons->GetAt(i);
if (!pControl->IsVisible())
continue;
DrawFrameCaptionButton(&dc, pControl->GetRect(), pControl->GetID(), pControl->GetSelected(), pControl->GetPressed(), pControl->GetEnabled() && bActive);
rcCaptionText.right = min(rcCaptionText.right, pControl->GetRect().left);
}
rcCaptionText.right -= nRightBorder;
DrawCaptionText(&dc, rcCaptionText, pSite, bActive);
if (m_bFlatFrame)
{
dc.FillSolidRect(rcCaption.left + nLeftBorder, rcCaption.bottom - 1, rcCaption.Width() -
nLeftBorder - nRightBorder, 1, bActive ? m_clrFrameBorderActive3 : m_clrFrameBorderInactive3);
}
}
else
{
CRect rcSrc;
rcSrc.SetRectEmpty();
CXTPResourceImage* pImage = LoadImage(_T("FRAMETOPLEFT"));
if (pImage)
{
rcSrc = pImage->GetSource(bActive ? 0 : 1, 2);
rcSrc.right = nLeftBorder;
CRect rcTopLeft(rc.left, rcCaption.top, rc.left + nLeftBorder, rcCaption.bottom);
pImage->DrawImage(pDC, rcTopLeft, rcSrc, CRect(0, 5, 0, 3));
}
pImage = LoadImage(_T("FRAMETOPRIGHT"));
if (pImage)
{
rcSrc = pImage->GetSource(bActive ? 0 : 1, 2);
rcSrc.left = rcSrc.right - nRightBorder;
CRect rcTopRight(rc.right - nRightBorder, rcCaption.top, rc.right, rcCaption.bottom);
pImage->DrawImage(pDC, rcTopRight, rcSrc, CRect(0, 5, 0, 3));
}
pImage = LoadImage(_T("FRAMETOPCENTER"));
if (pImage)
{
rcSrc = pImage->GetSource(bActive ? 0 : 1, 2);
rcSrc.bottom = rcSrc.top + nBorder;
CRect rcTopCenter(rc.left + nLeftBorder, rc.top, rc.right - nRightBorder, rc.top + nBorder);
pImage->DrawImage(pDC, rcTopCenter, rcSrc, CRect(0, 0, 0, 0));
}
pFrameHook->DrawRibbonFramePart(pDC);
}
if (bHasStatusBar)
{
CRect rcSrc;
rcSrc.SetRectEmpty();
CXTPResourceImage* pImage;
if (!m_bFlatFrame)
{
pImage = LoadImage(_T("STATUSBARLIGHT"));
if (pImage)
{
rcSrc.SetRect(0, 0, nLeftBorder - 1, pImage->GetHeight());
CRect rcLight(rc.left + 1, rc.bottom - nStatusHeight - nBottomBorder, rc.left + nLeftBorder, rc.bottom - nBottomBorder);
pImage->DrawImage(pDC, rcLight, rcSrc, CRect(0, 0, 0, 0));
}
pImage = LoadImage(_T("STATUSBARDARK"));
if (pImage)
{
rcSrc.SetRect(0, 0, nRightBorder - 1, pImage->GetHeight());
CRect rcDark(rc.right - nRightBorder, rc.bottom - nStatusHeight - nBottomBorder, rc.right - 1, rc.bottom - nBottomBorder);
pImage->DrawImage(pDC, rcDark, rcSrc, CRect(0, 0, 0, 0));
}
}
else
{
CRect rcLight(rc.left + 1, rc.bottom - nStatusHeight - nBottomBorder, rc.left + nLeftBorder, rc.bottom - nBottomBorder + 1);
pDC->FillSolidRect(rcLight, bActive ? m_clrFrameBorderActive2 : m_clrFrameBorderInactive2);
CRect rcDark(rc.right - nRightBorder, rc.bottom - nStatusHeight - nBottomBorder, rc.right - 1, rc.bottom - nBottomBorder + 1);
pDC->FillSolidRect(rcDark, bActive ? m_clrFrameBorderActive2 : m_clrFrameBorderInactive2);
if (nBottomBorder > 1)
{
pDC->FillSolidRect(rc.left + nLeftBorder - 1, rc.bottom - nStatusHeight - nBottomBorder, 1, nStatusHeight,
bActive ? m_clrFrameBorderActive3 : m_clrFrameBorderInactive3);
pDC->FillSolidRect(rc.right - nRightBorder, rc.bottom - nStatusHeight - nBottomBorder, 1, nStatusHeight,
bActive ? m_clrFrameBorderActive3 : m_clrFrameBorderInactive3);
}
}
}
if (bHasStatusBar || m_bRoundedCornersAlways)
{
CXTPResourceImage* pImage;
CRect rcSrc;
if (nLeftBorder > 3)
{
pImage = LoadImage(_T("FRAMEBOTTOMLEFT"));
if (pImage)
{
rcSrc = pImage->GetSource(bActive ? 0 : 1, 2);
CRect rcBottomLeft(rc.left, rc.bottom - rcSrc.Height(), rc.left + rcSrc.Width(), rc.bottom);
pImage->DrawImage(pDC, rcBottomLeft, rcSrc, CRect(0, 0, 0, 0), 0xFF00FF);
}
}
if (nRightBorder > 3)
{
pImage = LoadImage(_T("FRAMEBOTTOMRIGHT"));
if (pImage)
{
rcSrc = pImage->GetSource(bActive ? 0 : 1, 2);
CRect rcBottomRight(rc.right - rcSrc.Width(), rc.bottom - rcSrc.Height(), rc.right, rc.bottom);
pImage->DrawImage(pDC, rcBottomRight, rcSrc, CRect(0, 0, 0, 0), 0xFF00FF);
}
}
}
}
void CXTPFramePaintManager::DrawFrameCaptionButton(CDC* pDC, CRect rc, int nId, BOOL bSelected, BOOL bPressed, BOOL bActive)
{
int nState = !bActive ? 3 : bPressed && bSelected ? 2 : bSelected || bPressed ? 1 : 0;
int nGlyphSize = 23;
if (rc.Width() < 27) nGlyphSize = 17;
if (rc.Width() < 15) nGlyphSize = 13;
LPCTSTR lpszButton = nId == SC_CLOSE ? _T("CLOSE") : nId == SC_MINIMIZE ? _T("MINIMIZE") :
nId == SC_MAXIMIZE ? _T("MAXIMIZE") : _T("RESTORE");
if (bSelected || bPressed)
{
CString strImage;
strImage.Format(_T("FRAMECAPTION%sBUTTON"), lpszButton);
CXTPResourceImage* pImage = LoadImage(strImage);
if (!pImage) pImage = LoadImage(_T("FRAMECAPTIONBUTTON"));
pImage->DrawImage(pDC, rc, pImage->GetSource(bPressed && bSelected ? 1 : 0, 2), CRect(3, 3, 3, 3), 0xFF00FF);
}
CString strImage;
strImage.Format(_T("FRAMECAPTION%s%i"), lpszButton, nGlyphSize);
CXTPResourceImage* pImage = LoadImage(strImage);
CRect rcSrc(pImage->GetSource(nState, 5));
CRect rcGlyph(CPoint((rc.right + rc.left - rcSrc.Width()) / 2, (rc.top + rc.bottom - rcSrc.Height()) / 2), rcSrc.Size());
pImage->DrawImage(pDC, rcGlyph, rcSrc, CRect(0, 0, 0, 0), 0xFF00FF);
}
HICON CXTPFramePaintManager::GetFrameSmallIcon(CWnd* pFrame)
{
if (!pFrame)
return NULL;
DWORD dwStyle = pFrame->GetStyle();
DWORD dwExStyle = pFrame->GetExStyle();
if (dwExStyle & WS_EX_TOOLWINDOW)
return NULL;
if ((dwStyle & WS_SYSMENU) == 0)
return NULL;
HICON hIcon = (HICON)(DWORD_PTR)::SendMessage(pFrame->m_hWnd, WM_GETICON, ICON_SMALL, 0);
if (hIcon)
return hIcon;
hIcon = (HICON)(DWORD_PTR)::GetClassLongPtr(pFrame->m_hWnd, GCLP_HICONSM);
if (hIcon)
return hIcon;
if (((dwStyle & (WS_BORDER | WS_DLGFRAME)) != WS_DLGFRAME) && ((dwExStyle & WS_EX_DLGMODALFRAME) == 0))
{
ULONG_PTR dwResult;
if (SendMessageTimeout(pFrame->GetSafeHwnd(),
WM_QUERYDRAGICON,
0,
0,
SMTO_NORMAL,
100,
&dwResult))
{
hIcon = (HICON)dwResult;
}
if (hIcon == NULL)
{
hIcon = AfxGetApp()->LoadOEMIcon(OIC_WINLOGO);
}
}
return hIcon;
}
HICON CXTPFramePaintManager::GetFrameLargeIcon(CWnd* pFrame)
{
if (!pFrame)
return NULL;
HICON hIcon = (HICON)(DWORD_PTR)::SendMessage(pFrame->m_hWnd, WM_GETICON, ICON_BIG, 0);
if (hIcon)
return hIcon;
hIcon = (HICON)(DWORD_PTR)::GetClassLongPtr(pFrame->m_hWnd, GCLP_HICON);
if (hIcon)
return hIcon;
return hIcon;
}
///
//
//////////////////////////////////////////////////////////////////////////
// CXTPRibbonSystemFrameTheme
CXTPRibbonSystemFrameTheme::CXTPRibbonSystemFrameTheme(CXTPPaintManager* pPaintManager)
: CXTPFramePaintManager(pPaintManager)
{
m_pMarkupContext = XTPMarkupCreateContext(0);
}
CXTPRibbonSystemFrameTheme::~CXTPRibbonSystemFrameTheme()
{
XTPMarkupReleaseContext(m_pMarkupContext);
}
void CXTPRibbonSystemFrameTheme::RefreshMetrics()
{
CXTPFramePaintManager::RefreshMetrics();
m_clrFrameBorderActive0 = GetXtremeColor(COLOR_ACTIVECAPTION);
m_clrFrameBorderActive1 = GetXtremeColor(COLOR_GRADIENTACTIVECAPTION);
m_clrFrameBorderActive2 = GetXtremeColor(COLOR_GRADIENTACTIVECAPTION);
m_clrFrameBorderActive3 = GetXtremeColor(COLOR_GRADIENTACTIVECAPTION);
m_clrFrameBorderInactive0 = GetXtremeColor(COLOR_INACTIVECAPTION);
m_clrFrameBorderInactive1 = GetXtremeColor(COLOR_GRADIENTINACTIVECAPTION);
m_clrFrameBorderInactive2 = GetXtremeColor(COLOR_GRADIENTINACTIVECAPTION);
m_clrFrameBorderInactive3 = GetXtremeColor(COLOR_GRADIENTINACTIVECAPTION);
m_clrFrameCaptionTextActiveTitle = GetXtremeColor(COLOR_CAPTIONTEXT);
m_clrFrameCaptionTextInActive = GetXtremeColor(COLOR_INACTIVECAPTIONTEXT);
m_clrFrameCaptionTextActive = GetXtremeColor(COLOR_CAPTIONTEXT);
m_bFlatFrame = FALSE;
}
void CXTPRibbonSystemFrameTheme::RenderMarkup(CDC* pDC, CRect rc, LPCTSTR lpszMarkupText)
{
CXTPMarkupUIElement* pMarkupUIElement = XTPMarkupParseText(m_pMarkupContext, lpszMarkupText);
XTPMarkupRenderElement(pMarkupUIElement, pDC->GetSafeHdc(), rc);
XTPMarkupReleaseElement(pMarkupUIElement);
}
void CXTPRibbonSystemFrameTheme::DrawFrame(CDC* pDC, CXTPOffice2007FrameHook* pFrameHook)
{
CWnd* pSite = pFrameHook->GetSite();
BOOL bActive = pFrameHook->IsFrameActive();
CXTPClientRect rcBorders(pSite);
pSite->ClientToScreen(rcBorders);
CXTPWindowRect rc(pSite);
int nRightBorder = rcBorders.left - rc.left, nLeftBorder = rcBorders.left - rc.left, nBorder = pFrameHook->GetFrameBorder();
int nBottomBorder = rc.bottom - rcBorders.bottom;
int nTopBorder = rcBorders.top - rc.top;
rc.OffsetRect(-rc.TopLeft());
CRect rcFrame(rc);
int nCaptionHeight = pFrameHook->GetCaptionHeight();
rcFrame.top += nCaptionHeight;
int nStatusHeight = 0;
BOOL bHasStatusBar = pFrameHook->IsFrameHasStatusBar(&nStatusHeight);
int nBordersHeight = bHasStatusBar ? rcFrame.Height() - nStatusHeight - 1 : rcFrame.Height();
if (nLeftBorder > 0) pDC->FillSolidRect(rc.left + 0, rcFrame.top, 1, rcFrame.Height(), bActive ? m_clrFrameBorderActive0 : m_clrFrameBorderInactive0);
if (nLeftBorder > 1) pDC->FillSolidRect(rc.left + 1, rcFrame.top, 1, nBordersHeight, bActive ? m_clrFrameBorderActive1 : m_clrFrameBorderInactive1);
if (nLeftBorder > 2) pDC->FillSolidRect(rc.left + 2, rcFrame.top, 1, nBordersHeight, bActive ? m_clrFrameBorderActive2 : m_clrFrameBorderInactive2);
if (nLeftBorder > 3) pDC->FillSolidRect(rc.left + 3, rcFrame.top, nLeftBorder - 3, nBordersHeight, bActive ? m_clrFrameBorderActive3 : m_clrFrameBorderInactive3);
if (nRightBorder > 0) pDC->FillSolidRect(rc.right - 1, rcFrame.top, 1, rcFrame.Height(), bActive ? m_clrFrameBorderActive0 : m_clrFrameBorderInactive0);
if (nRightBorder > 1) pDC->FillSolidRect(rc.right - 2, rcFrame.top, 1, nBordersHeight, bActive ? m_clrFrameBorderActive1 : m_clrFrameBorderInactive1);
if (nRightBorder > 2) pDC->FillSolidRect(rc.right - 3, rcFrame.top, 1, nBordersHeight, bActive ? m_clrFrameBorderActive2 : m_clrFrameBorderInactive2);
if (nRightBorder > 3) pDC->FillSolidRect(rc.right - nRightBorder, rcFrame.top, nRightBorder - 3, nBordersHeight, bActive ? m_clrFrameBorderActive3 : m_clrFrameBorderInactive3);
pDC->FillSolidRect(rc.left, rc.bottom - 1, rc.Width(), 1,
bActive ? pSite->GetStyle() & WS_MAXIMIZE ? m_clrFrameBorderActive3 : m_clrFrameBorderActive0 : m_clrFrameBorderInactive0);
if (nBottomBorder > 1)
{
pDC->FillSolidRect(rc.left + 1, rc.bottom - nBottomBorder, rc.Width() - 2, nBottomBorder - 1, bActive ? m_clrFrameBorderActive3 : m_clrFrameBorderInactive3);
}
//////////////////////////////////////////////////////////////////////////
CRect rcCaption(rc.left, rc.top, rc.right, rc.top + nCaptionHeight);
if (pFrameHook->IsCaptionVisible())
{
CXTPBufferDC dc(*pDC, rcCaption);
LPCTSTR lpszMarkupText = bActive ?
_T("<Grid>")
_T("<Border BorderThickness='0,0,0,1'> <Border.Background>")
_T("<LinearGradientBrush StartPoint='0,0' EndPoint='0,1'>")
_T(" <GradientStop Offset='0' Color='{x:Static SystemColors.GradientActiveCaptionColor}'/>")
_T(" <GradientStop Offset='0.2' Color='{x:Static SystemColors.ActiveCaptionColor}'/>")
_T(" <GradientStop Offset='1.5' Color='{x:Static SystemColors.GradientActiveCaptionColor}'/>")
_T("</LinearGradientBrush></Border.Background></Border>")
_T("<Border BorderThickness='1' CornerRadius='5, 5, 0, 0' BorderBrush='{x:Static SystemColors.ActiveCaptionBrush}' />")
_T("</Grid>") :
_T("<Grid>")
_T("<Border BorderThickness='0,0,0,1'> <Border.Background>")
_T("<LinearGradientBrush StartPoint='0,0' EndPoint='0,1'>")
_T(" <GradientStop Offset='0' Color='{x:Static SystemColors.GradientInactiveCaptionColor}'/>")
_T(" <GradientStop Offset='0.2' Color='{x:Static SystemColors.InactiveCaptionColor}'/>")
_T(" <GradientStop Offset='1.5' Color='{x:Static SystemColors.GradientInactiveCaptionColor}'/>")
_T("</LinearGradientBrush></Border.Background></Border>")
_T("<Border BorderThickness='1' CornerRadius='5, 5, 0, 0' BorderBrush='{x:Static SystemColors.InactiveCaptionBrush}' />")
_T("</Grid>");
RenderMarkup(&dc, rcCaption, lpszMarkupText);
CRect rcCaptionText(rcCaption);
rcCaptionText.left = 7;
rcCaptionText.DeflateRect(0, nBorder, 0, 3);
HICON hIcon = GetFrameSmallIcon(pSite);
if (hIcon)
{
CSize szIcon(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON));
int cBorders = nBorder - 1;
int cxySlot = rcCaption.Height() - cBorders;
int nTop = cBorders + (cxySlot - szIcon.cy - 1)/2;
DWORD dwLayout = XTPDrawHelpers()->IsContextRTL(&dc);
if (dwLayout & LAYOUT_RTL)
XTPDrawHelpers()->SetContextRTL(&dc, dwLayout | LAYOUT_BITMAPORIENTATIONPRESERVED);
DrawIconEx(dc.m_hDC, rcCaptionText.left, nTop, hIcon,
szIcon.cx, szIcon.cy, 0, NULL, DI_NORMAL);
if (dwLayout & LAYOUT_RTL)
XTPDrawHelpers()->SetContextRTL(&dc, dwLayout);
rcCaptionText.left = 7 + szIcon.cx + 5;
}
CXTPControls* pCaptionButtons = pFrameHook->GetCaptionButtons();
for (int i = 0; i < pCaptionButtons->GetCount(); i++)
{
CXTPControl* pControl = pCaptionButtons->GetAt(i);
if (!pControl->IsVisible())
continue;
DrawFrameCaptionButton(&dc, pControl->GetRect(), pControl->GetID(), pControl->GetSelected(), pControl->GetPressed(), pControl->GetEnabled() && bActive);
rcCaptionText.right = min(rcCaptionText.right, pControl->GetRect().left);
}
rcCaptionText.right -= nRightBorder;
DrawCaptionText(&dc, rcCaptionText, pSite, bActive);
}
else
{
LPCTSTR lpszMarkupText = bActive ?
_T("<Grid>")
_T("<Border BorderThickness='0,0,0,1'> <Border.Background>")
_T("<LinearGradientBrush StartPoint='0,0' EndPoint='0,1'>")
_T(" <GradientStop Offset='0' Color='{x:Static SystemColors.GradientActiveCaptionColor}'/>")
_T(" <GradientStop Offset='0.2' Color='{x:Static SystemColors.ActiveCaptionColor}'/>")
_T(" <GradientStop Offset='1.5' Color='{x:Static SystemColors.GradientActiveCaptionColor}'/>")
_T("</LinearGradientBrush></Border.Background></Border>")
_T("<Border BorderThickness='1' CornerRadius='5, 5, 0, 0' BorderBrush='{x:Static SystemColors.ActiveCaptionBrush}' />")
_T("</Grid>") :
_T("<Grid>")
_T("<Border BorderThickness='0,0,0,1'> <Border.Background>")
_T("<LinearGradientBrush StartPoint='0,0' EndPoint='0,1'>")
_T(" <GradientStop Offset='0' Color='{x:Static SystemColors.GradientInactiveCaptionColor}'/>")
_T(" <GradientStop Offset='0.2' Color='{x:Static SystemColors.InactiveCaptionColor}'/>")
_T(" <GradientStop Offset='1.5' Color='{x:Static SystemColors.GradientInactiveCaptionColor}'/>")
_T("</LinearGradientBrush></Border.Background></Border>")
_T("<Border BorderThickness='1' CornerRadius='5, 5, 0, 0' BorderBrush='{x:Static SystemColors.InactiveCaptionBrush}' />")
_T("</Grid>");
CRect rcClient(rcCaption.left + nLeftBorder, rcCaption.top + nTopBorder, rcCaption.right - nRightBorder, rcCaption.bottom);
pDC->ExcludeClipRect(rcClient);
RenderMarkup(pDC, rcCaption, lpszMarkupText);
}
}
void CXTPRibbonSystemFrameTheme::DrawFrameCaptionButton(CDC* pDC, CRect rc, int nId, BOOL bSelected, BOOL bPressed, BOOL /*bActive*/)
{
LPCTSTR lpszMarkupText = NULL;
if (bPressed && bSelected)
{
lpszMarkupText =
_T("<Grid>")
_T("<Border Margin='1' BorderThickness='1' CornerRadius ='2' BorderBrush='{x:Static SystemColors.ActiveCaptionTextBrush}'> <Border.Background>")
_T("<LinearGradientBrush StartPoint='0,0' EndPoint='1,1'>")
_T(" <GradientStop Offset='-0.5' Color='{x:Static SystemColors.ActiveCaptionColor}'/>")
_T(" <GradientStop Offset='2.0' Color='Black'/>")
_T("</LinearGradientBrush></Border.Background></Border>")
_T("</Grid>");
}
else if (bSelected || bPressed)
{
lpszMarkupText =
_T("<Grid>")
_T("<Border Margin='1' BorderThickness='1' CornerRadius ='2' BorderBrush='{x:Static SystemColors.ActiveCaptionTextBrush}'> <Border.Background>")
_T("<LinearGradientBrush StartPoint='0,0' EndPoint='1,1'>")
_T(" <GradientStop Offset='-0.5' Color='{x:Static SystemColors.ControlLightLightColor}'/>")
_T(" <GradientStop Offset='0.8' Color='Transparent'/>")
_T(" <GradientStop Offset='1' Color='Transparent'/>")
_T("</LinearGradientBrush></Border.Background></Border>")
_T("</Grid>");
}
if (lpszMarkupText)
{
RenderMarkup(pDC, rc, lpszMarkupText);
}
lpszMarkupText = NULL;
int nGlyphSize = rc.Width() >= 21 ? 11 : 9;
CRect rcGlyph(CPoint((rc.left + rc.right - nGlyphSize) / 2, (rc.top + rc.bottom - nGlyphSize) / 2),
CSize(nGlyphSize, nGlyphSize));
if (nId == SC_CLOSE)
{
lpszMarkupText =
nGlyphSize == 11 ?
_T("<Canvas><Line X2='11' Y2='11' StrokeThickness='2' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/>")
_T("<Line X1='11' Y2='11' StrokeThickness='2' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/></Canvas>") :
_T("<Canvas><Line X2='9' Y2='9' StrokeThickness='2' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/>")
_T("<Line X1='9' Y2='9' StrokeThickness='2' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/></Canvas>");
}
if (nId == SC_MINIMIZE)
{
lpszMarkupText =
nGlyphSize == 11 ?
_T("<Canvas><Line X1 ='0' X2='8' Y1='9' Y2='9' StrokeThickness='3' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/></Canvas>") :
_T("<Canvas><Line X1 ='0' X2='7' Y1='8' Y2='8' StrokeThickness='2' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/></Canvas>");
}
if (nId == SC_MAXIMIZE)
{
lpszMarkupText =
nGlyphSize == 11 ?
_T("<Canvas Margin='0, 1, 0, 0'><Line X1 ='0' X2='11' StrokeThickness='3' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/>")
_T("<Rectangle Width='11' Height='10' StrokeThickness='1' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/></Canvas>") :
_T("<Canvas Margin='0, 1, 0, 0'><Line X1 ='0' X2='9' StrokeThickness='2' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/>")
_T("<Rectangle Width='9' Height='8' StrokeThickness='1' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/></Canvas>");
}
if (nId == SC_RESTORE)
{
lpszMarkupText =
nGlyphSize == 11 ?
_T("<Canvas Margin='0, 1, 0, 0'><Line X1 ='3' X2='9' Y1='1' Y2='1' StrokeThickness='2' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/>")
_T("<Line X1 ='9' X2='9' Y1='0' Y2 = '6' StrokeThickness='1' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/><Line X1 ='8' X2='9' Y1='6' Y2 = '6' StrokeThickness='1' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/>")
_T("<Line X1 ='0' Y1='4' X2='7' Y2='4' StrokeThickness='2' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/>")
_T("<Rectangle Canvas.Top='4' Width='7' Height='6' StrokeThickness='1' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/></Canvas>"):
_T("<Canvas Margin='0, 1, 0, 0'><Line X1 ='2' X2='8' Y1='1' Y2='1' StrokeThickness='2' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/>")
_T("<Line X1 ='8' X2='8' Y1='0' Y2 = '5' StrokeThickness='1' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/><Line X1 ='7' X2='8' Y1='5' Y2 = '5' StrokeThickness='1' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/>")
_T("<Line X1 ='0' Y1='4' X2='7' Y2='4' StrokeThickness='2' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/>")
_T("<Rectangle Canvas.Top='4' Width='7' Height='5' StrokeThickness='1' Stroke='{x:Static SystemColors.ActiveCaptionTextBrush}'/></Canvas>");
}
if (lpszMarkupText)
{
RenderMarkup(pDC, rcGlyph, lpszMarkupText);
}
}
| 37.129566 | 237 | 0.722449 | 11Zero |
57146c208bcc5eb9197cd457f651b034f0c145d7 | 379 | cpp | C++ | formatters.cpp | vovkasm/input-source-switcher | c5bab3de716db5e3dae3703ed3b72f2bf1cd51d3 | [
"MIT"
] | 120 | 2015-01-01T12:28:42.000Z | 2022-03-24T06:44:49.000Z | formatters.cpp | vovkasm/input-source-switcher | c5bab3de716db5e3dae3703ed3b72f2bf1cd51d3 | [
"MIT"
] | 8 | 2015-04-04T07:40:39.000Z | 2021-06-10T14:34:51.000Z | formatters.cpp | vovkasm/input-source-switcher | c5bab3de716db5e3dae3703ed3b72f2bf1cd51d3 | [
"MIT"
] | 10 | 2017-05-14T05:18:52.000Z | 2022-01-05T00:03:11.000Z | #include "formatters.h"
#include "utils.h"
#include <iostream>
std::ostream&
InputSourceFormatter::write(std::ostream& os) const {
CFStringRef value = (CFStringRef)TISGetInputSourceProperty(_is, kTISPropertyInputSourceID);
return os << stringFromCFString(value);
}
std::ostream& operator<<(std::ostream& os, const InputSourceFormatter& is) {
return is.write(os);
}
| 27.071429 | 95 | 0.741425 | vovkasm |
57221477cf4421cbb70c283c7392b2d21d6f627d | 16,510 | cpp | C++ | kernel/user_krnl/scatter_krnl/src/hls/scatter.cpp | WenqiJiang/FPGA-ANNS-with_network | 8586986e99593d8099ab3fb3ee6b919ffd480253 | [
"zlib-acknowledgement"
] | 86 | 2020-11-11T13:10:50.000Z | 2022-03-30T15:41:02.000Z | kernel/user_krnl/scatter_krnl/src/hls/scatter.cpp | pouya-haghi/Vitis_with_100Gbps_TCP-IP | fda50cf01e6ab6eba376c7cbf0b5ccc73deb9136 | [
"zlib-acknowledgement"
] | 4 | 2020-11-20T16:40:33.000Z | 2022-02-23T09:58:37.000Z | kernel/user_krnl/scatter_krnl/src/hls/scatter.cpp | pouya-haghi/Vitis_with_100Gbps_TCP-IP | fda50cf01e6ab6eba376c7cbf0b5ccc73deb9136 | [
"zlib-acknowledgement"
] | 33 | 2020-11-23T12:41:07.000Z | 2022-03-30T13:42:47.000Z | /************************************************
Copyright (c) 2018, Systems Group, ETH Zurich.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
************************************************/
#include "scatter_config.hpp"
#include "scatter.hpp"
#include <iostream>
//Buffers open status coming from the TCP stack
void openStatus_handler(hls::stream<openStatus>& openConStatus,
hls::stream<openStatus>& openConStatusBuffer)
{
#pragma HLS PIPELINE II=1
#pragma HLS INLINE off
if (!openConStatus.empty())
{
openStatus resp = openConStatus.read();
openConStatusBuffer.write(resp);
}
}
void txMetaData_handler(hls::stream<appTxMeta>& txMetaDataBuffer,
hls::stream<appTxMeta>& txMetaData)
{
#pragma HLS PIPELINE II=1
#pragma HLS INLINE off
if (!txMetaDataBuffer.empty())
{
appTxMeta metaDataReq = txMetaDataBuffer.read();
txMetaData.write(metaDataReq);
}
}
void txStatus_handler(hls::stream<appTxRsp>& txStatus,
hls::stream<appTxRsp>& txStatusBuffer)
{
#pragma HLS PIPELINE II=1
#pragma HLS INLINE off
if (!txStatus.empty())
{
appTxRsp resp = txStatus.read();
txStatusBuffer.write(resp);
}
}
//sends out close connection when the whole application finishes
//the connection buffer size should larger than the maximum connection number
void closeConnection_handler(hls::stream<ap_uint<16> >& closeConnectionBuffer,
hls::stream<ap_uint<16> >& closeConnection,
ap_uint<1> finishExperiment,
ap_uint<16> useConn)
{
#pragma HLS PIPELINE II=1
#pragma HLS INLINE off
// enum closeConnection_handlerFsmStateType {IDLE, CLOSE_CON};
// static closeConnection_handlerFsmStateType closeConnection_handlerFsmState = IDLE;
// static ap_uint<16> closeIt = 0;
// switch(closeConnection_handlerFsmState)
// {
// case IDLE:
// closeIt = 0;
// if (finishExperiment)
// {
// closeConnection_handlerFsmState = CLOSE_CON;
// }
// break;
// case CLOSE_CON:
if (!closeConnectionBuffer.empty())
{
ap_uint<16> closeConnectionReq = closeConnectionBuffer.read();
closeConnection.write(closeConnectionReq);
// closeIt ++;
}
// if (closeIt == useConn)
// {
// closeConnection_handlerFsmState = IDLE;
// }
// break;
// }//switch
}
template <int WIDTH>
void client( hls::stream<ipTuple>& openConnection,
hls::stream<openStatus>& openConStatusBuffer,
hls::stream<ap_uint<16> >& closeConnectionBuffer,
hls::stream<appTxMeta>& txMetaDataBuffer,
hls::stream<net_axis<WIDTH> >& txData,
hls::stream<appTxRsp>& txStatusBuffer,
ap_uint<1> runExperiment,
ap_uint<16> useConn, //total number of connection
ap_uint<16> useIpAddr, //total ip addr used
ap_uint<16> pkgWordCount,
ap_uint<16> regBasePort,
ap_uint<16> expectedRespInKB,
// ap_uint<32> delayedCycles,
ap_uint<32> clientPkgNum,
ap_uint<32> regIpAddress0,
ap_uint<32> regIpAddress1,
ap_uint<32> regIpAddress2,
ap_uint<32> regIpAddress3,
ap_uint<32> regIpAddress4,
ap_uint<32> regIpAddress5,
ap_uint<32> regIpAddress6,
ap_uint<32> regIpAddress7,
ap_uint<32> regIpAddress8,
ap_uint<32> regIpAddress9,
ap_uint<32> regIpAddress10
)
{
#pragma HLS PIPELINE II=1
#pragma HLS INLINE off
enum scatterFsmStateType {IDLE, INIT_CON, WAIT_CON, CHECK_REQ, WRITE_PKG, CLOSE_CON};
static scatterFsmStateType scatterFsmState = IDLE;
static ap_uint<16> numConnections = 0;
static ap_uint<16> currentSessionID;
static ap_uint<16> sessionIt = 0;
static ap_uint<16> closeIt = 0;
static ap_uint<16> wordCount = 0;
static ap_uint<16> ipAddressIdx = 0;
static ap_uint<16> currentPort;
// static ap_uint<32> delayedCyclesCnt = 0;
static ap_uint<32> clientPkgCnt = 0;
static bool sentFirstWord = false;
//support max 128 connections
ap_uint<16> sessionIDTable [128];
/*
* CLIENT FSM
*/
switch (scatterFsmState)
{
case IDLE:
sessionIt = 0;
closeIt = 0;
numConnections = 0;
ipAddressIdx = 0;
currentPort = 0;
// delayedCyclesCnt = 0;
clientPkgCnt = 0;
sentFirstWord = false;
if (runExperiment)
{
scatterFsmState = INIT_CON;
currentPort = regBasePort;
}
break;
case INIT_CON:
if (sessionIt < useConn)
{
ipTuple openTuple;
switch (ipAddressIdx)
{
case 0:
openTuple.ip_address = regIpAddress0;
break;
case 1:
openTuple.ip_address = regIpAddress1;
break;
case 2:
openTuple.ip_address = regIpAddress2;
break;
case 3:
openTuple.ip_address = regIpAddress3;
break;
case 4:
openTuple.ip_address = regIpAddress4;
break;
case 5:
openTuple.ip_address = regIpAddress5;
break;
case 6:
openTuple.ip_address = regIpAddress6;
break;
case 7:
openTuple.ip_address = regIpAddress7;
break;
case 8:
openTuple.ip_address = regIpAddress8;
break;
case 9:
openTuple.ip_address = regIpAddress9;
break;
case 10:
openTuple.ip_address = regIpAddress10;
break;
}
openTuple.ip_port = currentPort;
openConnection.write(openTuple);
ipAddressIdx++;
if (ipAddressIdx == useIpAddr)
{
ipAddressIdx = 0;
currentPort++;
}
}
sessionIt++;
if (sessionIt == useConn)
{
sessionIt = 0;
currentPort = 0;
scatterFsmState = WAIT_CON;
}
break;
case WAIT_CON:
if (!openConStatusBuffer.empty())
{
openStatus status = openConStatusBuffer.read();
if (status.success)
{
std::cout << "Connection successfully opened." << std::endl;
txMetaDataBuffer.write(appTxMeta(status.sessionID, pkgWordCount*(WIDTH/8)));
sessionIDTable[numConnections] = status.sessionID;
numConnections++;
}
else
{
std::cout << "Connection could not be opened." << std::endl;
}
sessionIt++;
if (sessionIt == useConn)
{
sessionIt = 0;
scatterFsmState = CHECK_REQ;
}
}
break;
case CHECK_REQ:
if (!txStatusBuffer.empty())
{
appTxRsp resp = txStatusBuffer.read();
if (resp.error == 0)
{
currentSessionID = resp.sessionID;
scatterFsmState = WRITE_PKG;
}
else
{
//Check if connection was torn down
if (resp.error == 1)
{
std::cout << "Connection was torn down. " << resp.sessionID << std::endl;
numConnections--;
}
else
{
txMetaDataBuffer.write(appTxMeta(resp.sessionID, pkgWordCount*(WIDTH/8)));
}
}
}
break;
case WRITE_PKG:
{
wordCount++;
net_axis<WIDTH> currWord;
if ((sentFirstWord == false) & (clientPkgCnt < (clientPkgNum -1)))
{
txMetaDataBuffer.write(appTxMeta(currentSessionID, pkgWordCount*(WIDTH/8)));
sentFirstWord = true;
}
for (int i = 0; i < (WIDTH/64); i++)
{
#pragma HLS UNROLL
currWord.data(i*64+63, i*64) = expectedRespInKB;
currWord.keep(i*8+7, i*8) = 0xff;
}
currWord.last = (wordCount == pkgWordCount);
txData.write(currWord);
if (currWord.last)
{
wordCount = 0;
clientPkgCnt++;
sentFirstWord = false;
if (clientPkgCnt == clientPkgNum)
{
clientPkgCnt = 0;
scatterFsmState = CLOSE_CON;
}
else
{
scatterFsmState = CHECK_REQ;
}
}
}
break;
case CLOSE_CON:
if (closeIt == numConnections)
{
scatterFsmState = IDLE;
}
else
{
ap_uint<16> closeSessionID = sessionIDTable[closeIt];
closeConnectionBuffer.write(closeSessionID);
closeIt++;
if (closeIt != numConnections)
{
scatterFsmState = CLOSE_CON;
}
}
break;
} //switch
}
template <int WIDTH>
void server( hls::stream<ap_uint<16> >& listenPort,
hls::stream<bool>& listenPortStatus,
hls::stream<appNotification>& notifications,
hls::stream<appReadRequest>& readRequest,
hls::stream<ap_uint<16> >& rxMetaData,
hls::stream<net_axis<WIDTH> >& rxData,
ap_uint<1> runExperiment,
ap_uint<16> usePort, //total number of listen port
ap_uint<16> regBasePort)
{
#pragma HLS PIPELINE II=1
#pragma HLS INLINE off
enum listenFsmStateType {IDLE, OPEN_PORT, WAIT_PORT_STATUS};
static listenFsmStateType listenState = IDLE;
enum consumeFsmStateType {WAIT_PKG, CONSUME};
static consumeFsmStateType serverFsmState = WAIT_PKG;
#pragma HLS RESET variable=listenState
static ap_uint<16> currentPort = 0;
static ap_uint<16> openedPort = 0;
switch (listenState)
{
case IDLE:
currentPort = 0;
openedPort = 0;
if (runExperiment)
{
currentPort = regBasePort;
listenState = OPEN_PORT;
}
break;
case OPEN_PORT:
// Open Port
listenPort.write(currentPort);
listenState = WAIT_PORT_STATUS;
std::cout << "Open listen request on port "<< currentPort<< std::endl;
break;
case WAIT_PORT_STATUS:
if (!listenPortStatus.empty())
{
bool open = listenPortStatus.read();
if (!open)
{
listenState = OPEN_PORT;
std::cout << "failed open listen port "<< currentPort<< std::endl;
}
else
{
std::cout << "successfully open listen port "<< currentPort<< std::endl;
currentPort++;
openedPort ++;
if (openedPort == usePort)
{
listenState = IDLE;
openedPort = 0;
currentPort = 0;
}
else
listenState = OPEN_PORT;
}
}
break;
}
if (!notifications.empty())
{
appNotification notification = notifications.read();
if (notification.length != 0)
{
readRequest.write(appReadRequest(notification.sessionID, notification.length));
}
}
switch (serverFsmState)
{
case WAIT_PKG:
if (!rxMetaData.empty() && !rxData.empty())
{
rxMetaData.read();
net_axis<WIDTH> receiveWord = rxData.read();
if (!receiveWord.last)
{
serverFsmState = CONSUME;
}
}
break;
case CONSUME:
if (!rxData.empty())
{
net_axis<WIDTH> receiveWord = rxData.read();
if (receiveWord.last)
{
serverFsmState = WAIT_PKG;
}
}
break;
}
}
void scatter( hls::stream<ap_uint<16> >& listenPort,
hls::stream<bool>& listenPortStatus,
hls::stream<appNotification>& notifications,
hls::stream<appReadRequest>& readRequest,
hls::stream<ap_uint<16> >& rxMetaData,
hls::stream<net_axis<DATA_WIDTH> >& rxData,
hls::stream<ipTuple>& openConnection,
hls::stream<openStatus>& openConStatus,
hls::stream<ap_uint<16> >& closeConnection,
hls::stream<appTxMeta>& txMetaData,
hls::stream<net_axis<DATA_WIDTH> >& txData,
hls::stream<appTxRsp>& txStatus,
ap_uint<1> runExperiment,
ap_uint<16> useConn,
ap_uint<16> useIpAddr,
ap_uint<16> pkgWordCount,
ap_uint<16> regBasePort,
ap_uint<16> usePort,
ap_uint<16> expectedRespInKB,
ap_uint<1> finishExperiment,
// ap_uint<32> delayedCycles,
ap_uint<32> clientPkgNum,
ap_uint<32> regIpAddress0,
ap_uint<32> regIpAddress1,
ap_uint<32> regIpAddress2,
ap_uint<32> regIpAddress3,
ap_uint<32> regIpAddress4,
ap_uint<32> regIpAddress5,
ap_uint<32> regIpAddress6,
ap_uint<32> regIpAddress7,
ap_uint<32> regIpAddress8,
ap_uint<32> regIpAddress9,
ap_uint<32> regIpAddress10)
{
#pragma HLS DATAFLOW disable_start_propagation
#pragma HLS INTERFACE ap_ctrl_none port=return
#pragma HLS INTERFACE axis register port=listenPort name=m_axis_listen_port
#pragma HLS INTERFACE axis register port=listenPortStatus name=s_axis_listen_port_status
#pragma HLS INTERFACE axis register port=notifications name=s_axis_notifications
#pragma HLS INTERFACE axis register port=readRequest name=m_axis_read_package
#pragma HLS DATA_PACK variable=notifications
#pragma HLS DATA_PACK variable=readRequest
#pragma HLS INTERFACE axis register port=rxMetaData name=s_axis_rx_metadata
#pragma HLS INTERFACE axis register port=rxData name=s_axis_rx_data
#pragma HLS INTERFACE axis register port=openConnection name=m_axis_open_connection
#pragma HLS INTERFACE axis register port=openConStatus name=s_axis_open_status
#pragma HLS DATA_PACK variable=openConnection
#pragma HLS DATA_PACK variable=openConStatus
#pragma HLS INTERFACE axis register port=closeConnection name=m_axis_close_connection
#pragma HLS INTERFACE axis register port=txMetaData name=m_axis_tx_metadata
#pragma HLS INTERFACE axis register port=txData name=m_axis_tx_data
#pragma HLS INTERFACE axis register port=txStatus name=s_axis_tx_status
#pragma HLS DATA_PACK variable=txMetaData
#pragma HLS DATA_PACK variable=txStatus
#pragma HLS INTERFACE ap_none register port=runExperiment
#pragma HLS INTERFACE ap_none register port=useConn
#pragma HLS INTERFACE ap_none register port=pkgWordCount
#pragma HLS INTERFACE ap_none register port=useIpAddr
#pragma HLS INTERFACE ap_none register port=regBasePort
#pragma HLS INTERFACE ap_none register port=usePort
#pragma HLS INTERFACE ap_none register port=expectedRespInKB
#pragma HLS INTERFACE ap_none register port=finishExperiment
// #pragma HLS INTERFACE ap_none register port=delayedCycles
#pragma HLS INTERFACE ap_none register port=clientPkgNum
#pragma HLS INTERFACE ap_none register port=regIpAddress0
#pragma HLS INTERFACE ap_none register port=regIpAddress1
#pragma HLS INTERFACE ap_none register port=regIpAddress2
#pragma HLS INTERFACE ap_none register port=regIpAddress3
#pragma HLS INTERFACE ap_none register port=regIpAddress4
#pragma HLS INTERFACE ap_none register port=regIpAddress5
#pragma HLS INTERFACE ap_none register port=regIpAddress6
#pragma HLS INTERFACE ap_none register port=regIpAddress7
#pragma HLS INTERFACE ap_none register port=regIpAddress8
#pragma HLS INTERFACE ap_none register port=regIpAddress9
#pragma HLS INTERFACE ap_none register port=regIpAddress10
static hls::stream<openStatus> openConStatusBuffer("openConStatusBuffer");
#pragma HLS STREAM variable=openConStatusBuffer depth=512
static hls::stream<appTxMeta> txMetaDataBuffer("txMetaDataBuffer");
#pragma HLS STREAM variable=txMetaDataBuffer depth=512
static hls::stream<appTxRsp> txStatusBuffer("txStatusBuffer");
#pragma HLS STREAM variable=txStatusBuffer depth=512
static hls::stream<ap_uint<16> > closeConnectionBuffer("closeConnectionBuffer");
#pragma HLS STREAM variable=closeConnectionBuffer depth=512
/*
* Client
*/
openStatus_handler(openConStatus, openConStatusBuffer);
txStatus_handler(txStatus, txStatusBuffer);
client<DATA_WIDTH>( openConnection,
openConStatusBuffer,
closeConnectionBuffer,
txMetaDataBuffer,
txData,
txStatusBuffer,
runExperiment,
useConn,
useIpAddr,
pkgWordCount,
regBasePort,
expectedRespInKB,
// delayedCycles,
clientPkgNum,
regIpAddress0,
regIpAddress1,
regIpAddress2,
regIpAddress3,
regIpAddress4,
regIpAddress5,
regIpAddress6,
regIpAddress7,
regIpAddress8,
regIpAddress9,
regIpAddress10);
txMetaData_handler(txMetaDataBuffer, txMetaData);
closeConnection_handler(closeConnectionBuffer, closeConnection, finishExperiment, useConn);
/*
* Server
*/
server<DATA_WIDTH>( listenPort,
listenPortStatus,
notifications,
readRequest,
rxMetaData,
rxData,
runExperiment,
usePort, //total number of listen port
regBasePort);
}
| 27.562604 | 101 | 0.711448 | WenqiJiang |
5723fb1252c32683cfecff1963da1c9415daf650 | 708 | cpp | C++ | beluga/base/CountDownLatch.cpp | ZhangSenyan/beluga | 1a44f062e82d0edd6bace9ab5ff0c5745e99d881 | [
"MIT"
] | 1 | 2019-07-09T12:36:24.000Z | 2019-07-09T12:36:24.000Z | beluga/base/CountDownLatch.cpp | SenyanZhang/HCCServer | 1a44f062e82d0edd6bace9ab5ff0c5745e99d881 | [
"MIT"
] | null | null | null | beluga/base/CountDownLatch.cpp | SenyanZhang/HCCServer | 1a44f062e82d0edd6bace9ab5ff0c5745e99d881 | [
"MIT"
] | null | null | null | /**
* @author Zhang Senyan
* Date: 2019-06-10
*/
#include "beluga/base/CountDownLatch.h"
// 构造函数
CountDownLatch::CountDownLatch(int count)
: _mutex(),
_condition(),
_count(count)
{
}
/**
* Function: 每来一个线程 count值 减 1
* 当所有线程都到达时,通知所有线程开始运行
*/
void CountDownLatch::countDown()
{
std::unique_lock<std::mutex> l(_mutex);
//count值 减 1
--_count;
if (_count == 0)
{
//所有线程已经到齐,通知所有线程
_condition.notify_all();
}
else{
//不满足条件就循环等待
while (_count > 0)
{
_condition.wait(l);
}
}
}
// 返回当前到达栅栏的进程数量
int CountDownLatch::getCount() const
{
std::unique_lock<std::mutex> l(_mutex);
return _count;
}
| 14.16 | 43 | 0.574859 | ZhangSenyan |
5725436faf16dac191929c2b7ec0107303fb71be | 5,484 | cpp | C++ | libs/tweedledum/tests/Passes/Optimization/gate_cancellation.cpp | fmozafari/starter | de9d431c6f660dd09ac746ebc478bb9df6f0e956 | [
"MIT"
] | 7 | 2020-03-13T17:08:01.000Z | 2021-11-17T11:43:58.000Z | libs/tweedledum/tests/Passes/Optimization/gate_cancellation.cpp | fmozafari/starter | de9d431c6f660dd09ac746ebc478bb9df6f0e956 | [
"MIT"
] | 2 | 2021-03-16T12:05:50.000Z | 2021-03-16T13:06:47.000Z | libs/tweedledum/tests/Passes/Optimization/gate_cancellation.cpp | fmozafari/starter | de9d431c6f660dd09ac746ebc478bb9df6f0e956 | [
"MIT"
] | 8 | 2020-02-13T18:05:55.000Z | 2021-03-16T11:12:33.000Z | /*------------------------------------------------------------------------------
| Part of Tweedledum Project. This file is distributed under the MIT License.
| See accompanying file /LICENSE for details.
*-----------------------------------------------------------------------------*/
#include "tweedledum/Passes/Optimization/gate_cancellation.h"
#include "tweedledum/IR/Circuit.h"
#include "tweedledum/IR/Wire.h"
#include "tweedledum/Operators/All.h"
#include "tweedledum/Passes/Utility/inverse.h"
#include "../check_unitary.h"
#include "../test_circuits.h"
#include <catch.hpp>
using namespace tweedledum;
TEST_CASE("Trivial gate cancellation", "[gate_cancellation][optimization]")
{
Circuit circuit;
Qubit const q0 = circuit.create_qubit();
Qubit const q1 = circuit.create_qubit();
SECTION("Single qubit operators")
{
circuit.apply_operator(Op::H(), {q0});
circuit.apply_operator(Op::H(), {q0});
circuit.apply_operator(Op::H(), {q1});
circuit.apply_operator(Op::T(), {q1});
circuit.apply_operator(Op::Tdg(), {q1});
auto optimized = gate_cancellation(circuit);
CHECK(optimized.size() == 1);
CHECK(check_unitary(circuit, optimized));
}
SECTION("Two qubit X operator (0)")
{
circuit.apply_operator(Op::X(), {q0, q1});
circuit.apply_operator(Op::X(), {q1, q0});
auto optimized = gate_cancellation(circuit);
CHECK(optimized.size() == 2);
CHECK(check_unitary(circuit, optimized));
}
SECTION("Two qubit X operator (1)")
{
circuit.apply_operator(Op::X(), {q0, q1});
circuit.apply_operator(Op::X(), {q0, q1});
circuit.apply_operator(Op::X(), {q1, q0});
auto optimized = gate_cancellation(circuit);
CHECK(optimized.size() == 1);
CHECK(check_unitary(circuit, optimized));
}
SECTION("Two qubit X operator (2)")
{
Qubit const q2 = circuit.create_qubit();
circuit.apply_operator(Op::X(), {q0, q2});
circuit.apply_operator(Op::X(), {q1, q0});
circuit.apply_operator(Op::X(), {q1, q0});
circuit.apply_operator(Op::X(), {q0, q2});
auto optimized = gate_cancellation(circuit);
CHECK(optimized.size() == 0);
CHECK(check_unitary(circuit, optimized));
}
}
TEMPLATE_TEST_CASE("Even Sequences (self-adjoint)",
"[gate_cancellation][optimization]", Op::H, Op::X, Op::Y, Op::Z)
{
Circuit circuit;
Qubit const q0 = circuit.create_qubit();
SECTION("One qubit")
{
for (uint32_t i = 0u; i < 1024u; ++i) {
circuit.apply_operator(TestType(), {q0});
}
auto optimized = gate_cancellation(circuit);
CHECK(optimized.size() == 0);
}
Qubit const q1 = circuit.create_qubit();
SECTION("Controlled")
{
for (uint32_t i = 0u; i < 1024u; ++i) {
circuit.apply_operator(TestType(), {q1, q0});
}
auto optimized = gate_cancellation(circuit);
CHECK(optimized.size() == 0);
}
Qubit const q2 = circuit.create_qubit();
SECTION("Multiple controls")
{
for (uint32_t i = 0u; i < 1024u; ++i) {
circuit.apply_operator(TestType(), {q1, q2, q0});
}
auto optimized = gate_cancellation(circuit);
CHECK(optimized.size() == 0);
}
}
TEMPLATE_TEST_CASE("Odd Sequences (self-adjoint)",
"[gate_cancellation][optimization]", Op::H, Op::X, Op::Y, Op::Z)
{
Circuit circuit;
Qubit const q0 = circuit.create_qubit();
SECTION("One qubit")
{
for (uint32_t i = 0u; i < 1023u; ++i) {
circuit.apply_operator(TestType(), {q0});
}
auto optimized = gate_cancellation(circuit);
CHECK(optimized.size() == 1);
}
Qubit const q1 = circuit.create_qubit();
SECTION("Controlled")
{
for (uint32_t i = 0u; i < 1023; ++i) {
circuit.apply_operator(TestType(), {q1, q0});
}
auto optimized = gate_cancellation(circuit);
CHECK(optimized.size() == 1);
}
Qubit const q2 = circuit.create_qubit();
SECTION("Multiple controls")
{
for (uint32_t i = 0u; i < 1023u; ++i) {
circuit.apply_operator(TestType(), {q1, q2, q0});
}
auto optimized = gate_cancellation(circuit);
CHECK(optimized.size() == 1);
}
}
TEST_CASE("Inverted circuits.", "[gate_cancellation][optimization]")
{
using namespace tweedledum;
SECTION("Toffoli operator")
{
Circuit circuit = toffoli();
std::optional<Circuit> adjoint = inverse(circuit);
CHECK(adjoint);
circuit.append(*adjoint, circuit.qubits(), circuit.cbits());
Circuit optimized = gate_cancellation(circuit);
CHECK(optimized.size() == 0u);
}
SECTION("Graph coloring init")
{
Circuit circuit = graph_coloring_init();
std::optional<Circuit> adjoint = inverse(circuit);
CHECK(adjoint);
circuit.append(*adjoint, circuit.qubits(), circuit.cbits());
Circuit optimized = gate_cancellation(circuit);
CHECK(optimized.size() == 0u);
}
SECTION("IBM Contest 2019 init")
{
Circuit circuit = ibm_contest2019_init();
std::optional<Circuit> adjoint = inverse(circuit);
CHECK(adjoint);
circuit.append(*adjoint, circuit.qubits(), circuit.cbits());
Circuit optimized = gate_cancellation(circuit);
CHECK(optimized.size() == 0u);
}
}
| 33.851852 | 80 | 0.586798 | fmozafari |
5729580abb93f63233c9e63c68d484269e474e4e | 464 | cpp | C++ | LeetCodeSolutions/LeetCode_0452.cpp | lih627/python-algorithm-templates | a61fd583e33a769b44ab758990625d3381793768 | [
"MIT"
] | 24 | 2020-03-28T06:10:25.000Z | 2021-11-23T05:01:29.000Z | LeetCodeSolutions/LeetCode_0452.cpp | lih627/python-algorithm-templates | a61fd583e33a769b44ab758990625d3381793768 | [
"MIT"
] | null | null | null | LeetCodeSolutions/LeetCode_0452.cpp | lih627/python-algorithm-templates | a61fd583e33a769b44ab758990625d3381793768 | [
"MIT"
] | 8 | 2020-05-18T02:43:16.000Z | 2021-05-24T18:11:38.000Z | bool cmp(const vector<int> &a, const vector<int> & b){
return a[1] < b[1];
}
class Solution {
public:
int findMinArrowShots(vector<vector<int>>& points) {
if (points.size() == 0) return 0;
sort(points.begin(), points.end(), cmp);
int cnt = 1;
int r = points[0][1];
for(auto &p: points){
if (p[0] > r){
++cnt;
r = p[1];
}
}
return cnt;
}
}; | 23.2 | 56 | 0.446121 | lih627 |
572b98f6c9bab8b9db04bfc9b6d4fe24433bf717 | 342 | hpp | C++ | bsengine/src/bstorm/lua_util.hpp | At-sushi/bstorm | 156036afd698d98f0ed67f0efa6bc416115806f7 | [
"MIT"
] | null | null | null | bsengine/src/bstorm/lua_util.hpp | At-sushi/bstorm | 156036afd698d98f0ed67f0efa6bc416115806f7 | [
"MIT"
] | null | null | null | bsengine/src/bstorm/lua_util.hpp | At-sushi/bstorm | 156036afd698d98f0ed67f0efa6bc416115806f7 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <luajit/lua.hpp>
namespace bstorm
{
void* GetPointerFromLuaRegistry(lua_State* L, const char* key);
void SetPointerToLuaRegistry(lua_State* L, const char* key, void* p);
// serialize stack top chunk. this function doesn't remove stack top.
void SerializeChunk(lua_State* L, std::string& byteCode);
} | 26.307692 | 69 | 0.763158 | At-sushi |
5732f9d033d5694dc42d03b439807ec6a7bcdc4c | 4,041 | cpp | C++ | system/src/active_object.cpp | zsoltmazlo/indoor-controller2 | 5fde9f40b30d087af03f6cccdb97821719941955 | [
"MIT"
] | null | null | null | system/src/active_object.cpp | zsoltmazlo/indoor-controller2 | 5fde9f40b30d087af03f6cccdb97821719941955 | [
"MIT"
] | null | null | null | system/src/active_object.cpp | zsoltmazlo/indoor-controller2 | 5fde9f40b30d087af03f6cccdb97821719941955 | [
"MIT"
] | null | null | null | /**
******************************************************************************
Copyright (c) 2015 Particle Industries, Inc. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, see <http://www.gnu.org/licenses/>.
******************************************************************************
*/
#include "active_object.h"
#include "spark_wiring_interrupts.h"
#include "debug.h"
#if PLATFORM_THREADING
#include <string.h>
#include "concurrent_hal.h"
#include "timer_hal.h"
void ActiveObjectBase::start_thread()
{
// prevent the started thread from running until the thread id has been assigned
// so that calls to isCurrentThread() work correctly
set_thread(std::thread(run_active_object, this));
while (!started) {
os_thread_yield();
}
}
void ActiveObjectBase::run()
{
std::lock_guard<std::mutex> lck (_start);
started = true;
uint32_t last_background_run = 0;
for (;;)
{
uint32_t now;
if (!process())
{
configuration.background_task();
}
else if ((now=HAL_Timer_Get_Milli_Seconds())-last_background_run > configuration.take_wait)
{
last_background_run = now;
configuration.background_task();
}
}
}
bool ActiveObjectBase::process()
{
bool result = false;
Item item = nullptr;
if (take(item) && item)
{
Message& msg = *item;
msg();
result = true;
}
return result;
}
void ActiveObjectBase::run_active_object(ActiveObjectBase* object)
{
object->run();
}
#endif // PLATFORM_THREADING
ISRTaskQueue::ISRTaskQueue(size_t size) :
tasks_(nullptr),
availTask_(nullptr),
firstTask_(nullptr),
lastTask_(nullptr) {
if (size) {
// Initialize pool of task objects
tasks_ = new(std::nothrow) Task[size];
if (tasks_) {
for (size_t i = 0; i < size; ++i) {
Task* t = tasks_ + i;
if (i != size - 1) {
t->next = t + 1;
} else {
t->next = nullptr;
}
}
}
availTask_ = tasks_;
}
}
ISRTaskQueue::~ISRTaskQueue() {
delete[] tasks_;
}
bool ISRTaskQueue::enqueue(TaskFunc func, void* data) {
SPARK_ASSERT(func && HAL_IsISR());
ATOMIC_BLOCK() { // Prevent preemption of the current ISR
// Take task object from the pool
Task* t = availTask_;
if (!t) {
return false;
}
availTask_ = t->next;
// Initialize task object
t->func = func;
t->data = data;
t->next = nullptr;
// Add task object to the queue
if (lastTask_) {
lastTask_->next = t;
} else { // The queue is empty
firstTask_ = t;
}
lastTask_ = t;
}
return true;
}
bool ISRTaskQueue::process() {
SPARK_ASSERT(!HAL_IsISR());
TaskFunc func = nullptr;
void* data = nullptr;
ATOMIC_BLOCK() {
// Take task object from the queue
Task *t = firstTask_;
if (!t) {
return false;
}
firstTask_ = firstTask_->next;
if (!firstTask_) {
lastTask_ = nullptr;
}
func = t->func;
data = t->data;
// Return task object to the pool
t->next = availTask_;
availTask_ = t;
}
// Invoke task function
func(data);
return true;
}
| 25.738854 | 99 | 0.563722 | zsoltmazlo |
573507ee5fa5d94dabcf72c51e4056ab27fc592c | 5,233 | hpp | C++ | ct_core/include/ct/external/cppad/cg/atomic_fun.hpp | vklemm/control-toolbox | f5f8cf9331c0aecd721ff6296154e2a55c72f679 | [
"BSD-2-Clause"
] | 1 | 2019-12-01T14:45:18.000Z | 2019-12-01T14:45:18.000Z | ct_core/include/external/cppad/cg/atomic_fun.hpp | ADVRHumanoids/ct | 774ad978c032fda0ef3c2eed0dc3f25f829df7f8 | [
"Apache-2.0"
] | null | null | null | ct_core/include/external/cppad/cg/atomic_fun.hpp | ADVRHumanoids/ct | 774ad978c032fda0ef3c2eed0dc3f25f829df7f8 | [
"Apache-2.0"
] | 1 | 2022-02-03T06:28:39.000Z | 2022-02-03T06:28:39.000Z | #ifndef CPPAD_CG_ATOMIC_FUN_INCLUDED
#define CPPAD_CG_ATOMIC_FUN_INCLUDED
/* --------------------------------------------------------------------------
* CppADCodeGen: C++ Algorithmic Differentiation with Source Code Generation:
* Copyright (C) 2013 Ciengis
*
* CppADCodeGen is distributed under multiple licenses:
*
* - Eclipse Public License Version 1.0 (EPL1), and
* - GNU General Public License Version 3 (GPL3).
*
* EPL1 terms and conditions can be found in the file "epl-v10.txt", while
* terms and conditions for the GPL3 can be found in the file "gpl3.txt".
* ----------------------------------------------------------------------------
* Author: Joao Leal
*/
namespace CppAD {
namespace cg {
/**
* An atomic function for source code generation
*
* @author Joao Leal
*/
template <class Base>
class CGAtomicFun : public CGAbstractAtomicFun<Base> {
protected:
atomic_base<Base>& atomicFun_;
public:
/**
* Creates a new atomic function wrapper that is responsible for
* defining the dependencies to calls of a user atomic function.
*
* @param atomicFun The atomic function to the called by the compiled
* source.
* @param standAlone Whether or not forward and reverse function calls
* do not require the Taylor coefficients for the
* dependent variables (ty) and the previous
* evaluation of other forward/reverse modes.
*/
CGAtomicFun(atomic_base<Base>& atomicFun, bool standAlone = false) :
CGAbstractAtomicFun<Base>(atomicFun.afun_name(), standAlone),
atomicFun_(atomicFun) {
}
template <class ADVector>
void operator()(const ADVector& ax, ADVector& ay, size_t id = 0) {
this->CGAbstractAtomicFun<Base>::operator()(ax, ay, id);
}
virtual bool for_sparse_jac(size_t q,
const CppAD::vector< std::set<size_t> >& r,
CppAD::vector< std::set<size_t> >& s) override {
return atomicFun_.for_sparse_jac(q, r, s);
}
virtual bool for_sparse_jac(size_t q,
const CppAD::vector<bool>& r,
CppAD::vector<bool>& s) override {
return atomicFun_.for_sparse_jac(q, r, s);
}
virtual bool rev_sparse_jac(size_t q,
const CppAD::vector< std::set<size_t> >& rt,
CppAD::vector< std::set<size_t> >& st) override {
return atomicFun_.rev_sparse_jac(q, rt, st);
}
virtual bool rev_sparse_jac(size_t q,
const CppAD::vector<bool>& rt,
CppAD::vector<bool>& st) override {
return atomicFun_.rev_sparse_jac(q, rt, st);
}
virtual bool rev_sparse_hes(const CppAD::vector<bool>& vx,
const CppAD::vector<bool>& s,
CppAD::vector<bool>& t,
size_t q,
const CppAD::vector< std::set<size_t> >& r,
const CppAD::vector< std::set<size_t> >& u,
CppAD::vector< std::set<size_t> >& v) override {
return atomicFun_.rev_sparse_hes(vx, s, t, q, r, u, v);
}
virtual bool rev_sparse_hes(const CppAD::vector<bool>& vx,
const CppAD::vector<bool>& s,
CppAD::vector<bool>& t,
size_t q,
const CppAD::vector<bool>& r,
const CppAD::vector<bool>& u,
CppAD::vector<bool>& v) override {
return atomicFun_.rev_sparse_hes(vx, s, t, q, r, u, v);
}
virtual ~CGAtomicFun() {
}
protected:
virtual void zeroOrderDependency(const CppAD::vector<bool>& vx,
CppAD::vector<bool>& vy) override {
using CppAD::vector;
size_t m = vy.size();
size_t n = vx.size();
vector<std::set<size_t> > rt(m);
for (size_t j = 0; j < m; j++) {
rt[j].insert(j);
}
vector<std::set<size_t> > st(n);
rev_sparse_jac(m, rt, st);
for (size_t j = 0; j < n; j++) {
for (size_t i : st[j]) {
if (vx[j]) {
vy[i] = true;
}
}
}
}
virtual bool atomicForward(size_t q,
size_t p,
const CppAD::vector<Base>& tx,
CppAD::vector<Base>& ty) override {
CppAD::vector<bool> vx, vy;
return atomicFun_.forward(q, p, vx, vy, tx, ty);
}
virtual bool atomicReverse(size_t p,
const CppAD::vector<Base>& tx,
const CppAD::vector<Base>& ty,
CppAD::vector<Base>& px,
const CppAD::vector<Base>& py) override {
return atomicFun_.reverse(p, tx, ty, px, py);
}
};
} // END cg namespace
} // END CppAD namespace
#endif | 35.598639 | 81 | 0.501624 | vklemm |
57406487b1cc9c7e646db11d66cd573c0fd93905 | 1,742 | cpp | C++ | Day_73.cpp | iamakkkhil/DailyCoding | 8422ddbcc2a179f3fd449871e2241ad94a845efb | [
"MIT"
] | 8 | 2021-02-07T16:31:28.000Z | 2021-06-11T18:53:23.000Z | Day_73.cpp | iamakkkhil/DailyCoding | 8422ddbcc2a179f3fd449871e2241ad94a845efb | [
"MIT"
] | null | null | null | Day_73.cpp | iamakkkhil/DailyCoding | 8422ddbcc2a179f3fd449871e2241ad94a845efb | [
"MIT"
] | 1 | 2021-05-25T17:17:58.000Z | 2021-05-25T17:17:58.000Z | /*
DAY 73 : Merge Sort for Doubly Linked List.
https://www.geeksforgeeks.org/merge-sort-for-doubly-linked-list/
QUESTION : Given Pointer/Reference to the head of a doubly linked list of N nodes,
the task is to Sort the given doubly linked list using Merge Sort in both non-decreasing
and non-increasing order.
Example:
Input:
N = 8
value[] = {7,3,5,2,6,4,1,8}
Output:
1 2 3 4 5 6 7 8
8 7 6 5 4 3 2 1
Explanation: After sorting the given
linked list in both ways, resultant
matrix will be as given in the first
two line of output, where first line
is the output for non-decreasing
order and next line is for non-
increasing order.
Constraints:
1 <= N <= 10^5
*/
Node* split(Node* head) {
Node* fast = head;
Node* slow = head;
while (fast->next!=NULL && fast->next->next!=NULL)
{
slow = slow->next;
fast = fast->next->next;
}
Node *mid = slow->next;
slow->next = NULL;
return mid;
}
Node* Merge(Node* head, Node* second) {
while(!head) {
return second;
}
while(!second) {
return head;
}
if(head->data < second->data){
head->next = Merge(head->next, second);
head->next->prev = head;
head->prev = NULL;
return head;
}
else {
second->next = Merge(head, second->next);
second->next->prev = second;
second->prev = NULL;
return second;
}
}
void Merge_Sort(Node* head) {
if (!head and head->next==NULL) {
return;
}
Node* second = split(head);
head = Merge_Sort(head);
second = Merge_Sort(second);
return Merge(head, second);
} | 23.226667 | 90 | 0.56946 | iamakkkhil |
57417dc3d97cc4b3c0b4153984d67c0eae47081f | 1,465 | hpp | C++ | include/cppcoro/detail/get_awaiter.hpp | richard-vock/cppcoro | 8933f03ff18b6a004a3ff2a271f4f74fafb29a96 | [
"MIT"
] | 2,324 | 2017-04-20T00:53:31.000Z | 2022-03-31T08:30:35.000Z | include/cppcoro/detail/get_awaiter.hpp | AlexCr4ckPentest/cppcoro | 4e6b44eaec34b8a7fb82357515ece84d64381a50 | [
"MIT"
] | 165 | 2017-04-10T21:40:51.000Z | 2022-02-25T15:45:38.000Z | include/cppcoro/detail/get_awaiter.hpp | AlexCr4ckPentest/cppcoro | 4e6b44eaec34b8a7fb82357515ece84d64381a50 | [
"MIT"
] | 325 | 2017-05-04T18:48:21.000Z | 2022-03-28T19:29:54.000Z | ///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Lewis Baker
// Licenced under MIT license. See LICENSE.txt for details.
///////////////////////////////////////////////////////////////////////////////
#ifndef CPPCORO_DETAIL_GET_AWAITER_HPP_INCLUDED
#define CPPCORO_DETAIL_GET_AWAITER_HPP_INCLUDED
#include <cppcoro/detail/is_awaiter.hpp>
#include <cppcoro/detail/any.hpp>
namespace cppcoro
{
namespace detail
{
template<typename T>
auto get_awaiter_impl(T&& value, int)
noexcept(noexcept(static_cast<T&&>(value).operator co_await()))
-> decltype(static_cast<T&&>(value).operator co_await())
{
return static_cast<T&&>(value).operator co_await();
}
template<typename T>
auto get_awaiter_impl(T&& value, long)
noexcept(noexcept(operator co_await(static_cast<T&&>(value))))
-> decltype(operator co_await(static_cast<T&&>(value)))
{
return operator co_await(static_cast<T&&>(value));
}
template<
typename T,
std::enable_if_t<cppcoro::detail::is_awaiter<T&&>::value, int> = 0>
T&& get_awaiter_impl(T&& value, cppcoro::detail::any) noexcept
{
return static_cast<T&&>(value);
}
template<typename T>
auto get_awaiter(T&& value)
noexcept(noexcept(detail::get_awaiter_impl(static_cast<T&&>(value), 123)))
-> decltype(detail::get_awaiter_impl(static_cast<T&&>(value), 123))
{
return detail::get_awaiter_impl(static_cast<T&&>(value), 123);
}
}
}
#endif
| 29.3 | 79 | 0.634812 | richard-vock |
57419cd4bacc108d7d3b42a8794cf17af04b80a4 | 179 | cpp | C++ | cpp/451-460/Minimum Moves to Equal Array Elements.cpp | KaiyuWei/leetcode | fd61f5df60cfc7086f7e85774704bacacb4aaa5c | [
"MIT"
] | 150 | 2015-04-04T06:53:49.000Z | 2022-03-21T13:32:08.000Z | cpp/451-460/Minimum Moves to Equal Array Elements.cpp | yizhu1012/leetcode | d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7 | [
"MIT"
] | 1 | 2015-04-13T15:15:40.000Z | 2015-04-21T20:23:16.000Z | cpp/451-460/Minimum Moves to Equal Array Elements.cpp | yizhu1012/leetcode | d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7 | [
"MIT"
] | 64 | 2015-06-30T08:00:07.000Z | 2022-01-01T16:44:14.000Z | class Solution {
public:
int minMoves(vector<int>& nums) {
return accumulate(begin(nums), end(nums), 0) - nums.size() * *min_element(begin(nums), end(nums));
}
};
| 25.571429 | 106 | 0.620112 | KaiyuWei |
574233ee48c1636f6f89996586f890c722689385 | 647 | cpp | C++ | tests/thread_pool_options.t.cpp | alfishe/thread-pool-cpp | ddf4468b056c686917082f0570a7c8c926231214 | [
"MIT"
] | 6 | 2018-10-05T07:38:51.000Z | 2021-02-21T15:08:52.000Z | tests/thread_pool_options.t.cpp | alfishe/thread-pool-cpp | ddf4468b056c686917082f0570a7c8c926231214 | [
"MIT"
] | null | null | null | tests/thread_pool_options.t.cpp | alfishe/thread-pool-cpp | ddf4468b056c686917082f0570a7c8c926231214 | [
"MIT"
] | 2 | 2020-07-01T16:08:44.000Z | 2021-02-10T19:35:11.000Z | #include <gtest/gtest.h>
#include <thread_pool/thread_pool_options.hpp>
#include <thread>
TEST(ThreadPoolOptions, ctor)
{
tp::ThreadPoolOptions options;
ASSERT_EQ(1024, options.queueSize());
ASSERT_EQ(std::max<size_t>(1u, std::thread::hardware_concurrency()),
options.threadCount());
}
TEST(ThreadPoolOptions, modification)
{
tp::ThreadPoolOptions options;
options.setThreadCount(5);
ASSERT_EQ(5, options.threadCount());
options.setQueueSize(32);
ASSERT_EQ(32, options.queueSize());
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 20.870968 | 72 | 0.692427 | alfishe |
57484dc13d9249df4f69fbafd93f82cd8595f57c | 682 | cpp | C++ | com/example/use_tmap.cpp | onecoolx/xoc | bf8a18cb19826a9f210abf68de21bc684e3e35bf | [
"BSD-3-Clause"
] | 111 | 2015-08-21T01:53:55.000Z | 2022-03-07T12:24:30.000Z | src/com/example/use_tmap.cpp | onecoolx/xocfe | d021e522184ca921d9a19d56a8756f223385dbb7 | [
"BSD-3-Clause"
] | 7 | 2015-01-27T03:16:48.000Z | 2022-01-01T09:22:24.000Z | src/com/example/use_tmap.cpp | onecoolx/xocfe | d021e522184ca921d9a19d56a8756f223385dbb7 | [
"BSD-3-Clause"
] | 17 | 2015-08-06T03:10:28.000Z | 2021-03-28T11:17:51.000Z | #include "stdio.h"
#include "xcominc.h"
int main()
{
TMap<int, char const*> map;
map.set(123, "Mike");
map.set(234, "Charlie");
map.set(345, "Tom");
printf("\nIterate map via string pointer:\n");
TMapIter<int, char const*> iter;
char const* str;
for (int v = map.get_first(iter, &str);
str != nullptr; v = map.get_next(iter, &str)) {
printf("%d->%s\n", v, str);
}
printf("\nIterate map via iter itself:\n");
for (int v = map.get_first(iter, &str);
iter.get_elem_count() != 0; v = map.get_next(iter, &str)) {
printf("%d->%s\n", v, str);
}
printf("%d\n", map.get_elem_count());
return 0;
}
| 24.357143 | 68 | 0.546921 | onecoolx |
574bcd3a19afd6ee0d949b1c3f0a3e5f56101dcc | 15,224 | cpp | C++ | src/test-kl-term.cpp | boennecd/VAJointSurv | 3c777ec89f7efb92dbfbfa0f751b3954bcfbfdc2 | [
"MIT"
] | null | null | null | src/test-kl-term.cpp | boennecd/VAJointSurv | 3c777ec89f7efb92dbfbfa0f751b3954bcfbfdc2 | [
"MIT"
] | 1 | 2021-11-17T08:12:46.000Z | 2021-11-17T08:12:46.000Z | src/test-kl-term.cpp | boennecd/VAJointSurv | 3c777ec89f7efb92dbfbfa0f751b3954bcfbfdc2 | [
"MIT"
] | null | null | null | #include "testthat-wrapper.h"
#include "kl-term.h"
#include <memory.h>
#include "log-cholesky.h"
namespace {
/*
set.seed(1)
n_shared <- 2L
n_shared_surv <- 3L
n_vars <- n_shared + n_shared_surv
Omega <- drop(rWishart(1, n_vars, diag(n_vars)))
Xi <- drop(rWishart(1, n_shared_surv, diag(n_shared_surv)))
Psi <- drop(rWishart(1, n_shared, diag(n_shared)))
zeta <- rnorm(n_vars)
f <- function(Omega, Xi, Psi, zeta)
(-determinant(Omega)$modulus + determinant(Xi)$modulus +
determinant(Psi)$modulus +
drop(zeta[1:n_shared] %*% solve(Psi, zeta[1:n_shared])) +
drop(zeta[-(1:n_shared)] %*% solve(Xi, zeta[-(1:n_shared)])) +
sum(diag(solve(Psi, Omega[1:n_shared, 1:n_shared]))) +
sum(diag(solve(Xi, Omega[-(1:n_shared), -(1:n_shared)]))) -
n_shared - n_shared_surv)/2
dput(f(Omega, Xi, Psi, zeta))
dput(Xi)
dput(Psi)
dput(Omega)
dput(zeta)
log_chol <- function(x){
x <- chol(x)
diag(x) <- log(diag(x))
x[upper.tri(x, TRUE)]
}
log_chol_inv <- function(x){
n <- (sqrt(8 * length(x) + 1) - 1) / 2
out <- matrix(0, n, n)
out[upper.tri(out, TRUE)] <- x
diag(out) <- exp(diag(out))
crossprod(out)
}
dput(Xi_chol <- log_chol(Xi))
dput(Psi_chol <- log_chol(Psi))
dput(Omega_chol <- log_chol(Omega))
g <- function(x){
Xi_chol <- x[seq_along(Xi_chol)]
Psi_chol <- x[seq_along(Psi_chol) + length(Xi_chol)]
Omega_chol <- x[seq_along(Omega_chol) + length(Xi_chol) + length(Psi_chol)]
zeta <- tail(x, length(zeta))
f(Omega = log_chol_inv(Omega_chol), Psi = log_chol_inv(Psi_chol),
Xi = log_chol_inv(Xi_chol), zeta = zeta)
}
g(c(Xi_chol, Psi_chol, Omega_chol, zeta))
deriv <- numDeriv::grad(g, c(Xi_chol, Psi_chol, Omega_chol, zeta))
dput(Xi_deriv <- deriv[seq_along(Xi_chol)])
dput(Psi_deriv <- deriv[seq_along(Psi_chol) + length(Xi_chol)])
dput(Omega_deriv <- deriv[
seq_along(Omega_chol) + length(Xi_chol) + length(Psi_chol)])
dput(zeta_deriv <- tail(deriv, length(zeta)))
# only with the markers
f <- function(Omega, Xi, Psi, zeta)
(-determinant(Omega[1:n_shared, 1:n_shared])$modulus + # determinant(Xi)$modulus +
determinant(Psi)$modulus +
drop(zeta[1:n_shared] %*% solve(Psi, zeta[1:n_shared])) +
# drop(zeta[-(1:n_shared)] %*% solve(Xi, zeta[-(1:n_shared)])) +
sum(diag(solve(Psi, Omega[1:n_shared, 1:n_shared]))) +
# sum(diag(solve(Xi, Omega[-(1:n_shared), -(1:n_shared)])))
-n_shared)/2
dput(f(Omega, Xi, Psi, zeta))
deriv <- numDeriv::grad(g, c(Xi_chol, Psi_chol, Omega_chol, zeta))
dput(Xi_deriv <- deriv[seq_along(Xi_chol)])
dput(Psi_deriv <- deriv[seq_along(Psi_chol) + length(Xi_chol)])
dput(Omega_deriv <- deriv[
seq_along(Omega_chol) + length(Xi_chol) + length(Psi_chol)])
dput(zeta_deriv <- tail(deriv, length(zeta)))
# only survival
f <- function(Omega, Xi, Psi, zeta)
(-determinant(Omega[-(1:n_shared), -(1:n_shared)])$modulus +
determinant(Xi)$modulus +
# determinant(Psi)$modulus +
# drop(zeta[1:n_shared] %*% solve(Psi, zeta[1:n_shared])) +
drop(zeta[-(1:n_shared)] %*% solve(Xi, zeta[-(1:n_shared)])) +
# sum(diag(solve(Psi, Omega[1:n_shared, 1:n_shared]))) +
sum(diag(solve(Xi, Omega[-(1:n_shared), -(1:n_shared)]))) -
n_shared_surv)/2
dput(f(Omega, Xi, Psi, zeta))
deriv <- numDeriv::grad(g, c(Xi_chol, Psi_chol, Omega_chol, zeta))
dput(Xi_deriv <- deriv[seq_along(Xi_chol)])
dput(Psi_deriv <- deriv[seq_along(Psi_chol) + length(Xi_chol)])
dput(Omega_deriv <- deriv[
seq_along(Omega_chol) + length(Xi_chol) + length(Psi_chol)])
dput(zeta_deriv <- tail(deriv, length(zeta)))
*/
constexpr vajoint_uint n_shared = 2,
n_shared_surv = 3,
n_vars = n_shared + n_shared_surv;
constexpr double Xi[n_shared_surv * n_shared_surv] { 1.96775053611171, -1.73597597741474, 0.529397523176239, -1.73597597741474, 3.24256054526995, -0.292627703276501, 0.529397523176239, -0.292627703276501, 0.634396281932773 },
Psi[n_shared * n_shared] { 2.4606560951913, 0.789983565757713, 0.789983565757713, 0.892097273439034},
Omega[n_vars * n_vars] { 2.42434323779257, 1.9812109601339, -2.3977488177111, 0.896508989006271, -0.967290384087283, 1.9812109601339, 8.7605890723572, -4.44094380859342, -0.0834669056878007, -6.70896207863171, -2.3977488177111, -4.44094380859342, 6.14892949801278, 1.97812834810877, 4.9338943130402, 0.896508989006271, -0.0834669056878007, 1.97812834810877, 3.33690095112284, 1.98372476564407, -0.967290384087283, -6.70896207863171, 4.9338943130402, 1.98372476564407, 7.74887957345459 },
zeta[n_vars] { 1.08576936214569, -0.69095383969683, -1.28459935387219, 0.046726172188352, -0.235706556439501 },
Xi_chol[dim_tri(n_shared_surv)] { 0.338445515244742, -1.23753842192996, 0.268556296839291, 0.377395645981701, 0.133336360814841, -0.373073361500074 },
Psi_chol[dim_tri(n_shared)] { 0.450214009873517, 0.503607972233726, -0.224335373954299 },
Omega_chol[dim_tri(n_vars)] { 0.442780328966089, 1.2724293214294, 0.982962307931023, -1.53995004190371, -0.928567034713538, 0.534977211455984, 0.575781351653492, -0.305388387156356, 1.51178116845085, -0.23369758278885, -0.621240580541804, -2.2146998871775, 1.12493091814311, -0.0449336090152294, 0.0872100127375849 };
constexpr double true_kl_term = 14.58945197638;
constexpr double Xi_deriv[dim_tri(n_shared_surv)] { -5.80311449958224, -3.32225269517676, -5.84896643091192, -3.36986740874183,
-4.70975985678572, -9.17044789534625 },
Psi_deriv[dim_tri(n_shared)] { -0.427035663737666, -0.0740751249053278, -12.8125448527808 },
Omega_deriv[dim_tri(n_vars)] { -0.61960594919438, 1.20999189744859, 10.1852434869524, -1.08994359451185,
0.348923601855757, 2.67579154568366, -0.430153063324311, -0.259508809540019,
1.68692480260345, -0.612398324838771, -0.268131842823628, -3.90191228270156,
0.754827608496878, -0.264923488296771, 1.51071293143399 },
zeta_deriv[n_vars] { 0.963963111992338, -1.62815076284324, -1.38009039095917, -0.682457259304228,
0.465330561405237 };
// without the survival part
constexpr double true_kl_term_no_surv{5.43857866944945},
Xi_deriv_no_s[] = {0., 0., 0., 0., 0., 0.},
Psi_deriv_no_s[] = {-0.427035663832965, -0.0740751251107456, -12.8125448527058},
Omega_deriv_no_s[] = {-0.619605949523746, 1.20999189732096, 10.1852434869334, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
zeta_deriv_no_s[] = {0.963963112174406, -1.62815076286685, 0, 0, 0};
// without markers
constexpr double true_kl_term_no_marker{7.47606508560383},
Xi_deriv_no_m[] = {-5.803114499632, -3.32225269517634, -5.84896643129221, -3.36986740815176,
-4.70975985768593, -9.17044789529971},
Psi_deriv_no_m[] = {0, 0, 0},
Omega_deriv_no_m[] = {0, 0, 0, -0.619384955968862, 0.201941440223768, 3.26394555054402,
-0.808825953840981, -0.314820162313017, 1.31531055565136, 0.15054243930918,
-0.39063512977232, -3.50835643881455, 0.858372808603325, -0.221739103733836,
2.19167623243605},
zeta_deriv_no_m[] = {0, 0, -1.3800903909731, -0.682457259664746, 0.46533056191001};
} // namespace
context("testing kl-terms") {
test_that("eval gives the right result") {
double const eps = std::sqrt(std::numeric_limits<double>::epsilon());
subset_params params;
params.add_marker({ 2, 2, 1 });
params.add_marker({ 1, 4, 1 });
params.add_surv({ 5, 2, {1, 1}, true });
params.add_surv({ 1, 4, {1, 1}, true });
params.add_surv({ 5, 2, {1, 1}, true });
// create and fill parameter vector
vajoint_uint const n_params_w_va = params.n_params_w_va();
std::unique_ptr<double[]> par(new double[n_params_w_va]);
std::fill(par.get(), par.get() + n_params_w_va, 0.);
auto fill_par = [](double const *value, vajoint_uint const n_ele,
double *out){
std::copy(value, value + n_ele, out);
};
fill_par(Xi, n_shared_surv * n_shared_surv,
par.get() + params.vcov_surv());
fill_par(Psi, n_shared * n_shared,
par.get() + params.vcov_vary());
fill_par(Omega, n_vars * n_vars,
par.get() + params.va_vcov());
fill_par(zeta, n_vars,
par.get() + params.va_mean());
// compute the kl term
kl_term term(params);
std::unique_ptr<double[]> mem(new double[term.n_wmem()]);
term.setup(par.get(), mem.get());
expect_true(pass_rel_err(term.eval(par.get(), mem.get()), true_kl_term));
// check the gradient
std::unique_ptr<double[]> gr(new double[n_params_w_va]),
gr_res(new double[params.n_params_w_va<true>()]);
std::fill(gr.get(), gr.get() + n_params_w_va, 0.);
std::fill(gr_res.get(), gr_res.get() + params.n_params_w_va<true>(), 0.);
double val = term.grad(gr.get(), par.get(), mem.get());
expect_true(pass_rel_err(val, true_kl_term));
auto test_grad = [&](double const *Xi_deriv, double const *Psi_deriv,
double const *Omega_deriv, double const *zeta_deriv){
{
double *g_out = gr_res.get() + params.vcov_surv<true>();
double const *g_in = gr.get() + params.vcov_surv();
log_chol::dpd_mat::get(Xi_chol, n_shared_surv, g_out, g_in);
for(vajoint_uint i = 0; i < dim_tri(n_shared_surv); ++i)
expect_true(pass_rel_err(g_out[i], Xi_deriv[i]));
}
{
double *g_out = gr_res.get() + params.vcov_vary<true>();
double const *g_in = gr.get() + params.vcov_vary();
log_chol::dpd_mat::get(Psi_chol, n_shared, g_out, g_in);
for(vajoint_uint i = 0; i < dim_tri(n_shared); ++i)
expect_true(pass_rel_err(g_out[i], Psi_deriv[i]));
}
{
double *g_out = gr_res.get() + params.va_vcov<true>();
double const *g_in = gr.get() + params.va_vcov();
log_chol::dpd_mat::get(Omega_chol, n_vars, g_out, g_in);
for(vajoint_uint i = 0; i < dim_tri(n_vars); ++i)
expect_true(pass_rel_err(g_out[i], Omega_deriv[i]));
}
{
double const *g_out = gr.get() + params.va_mean();
for(vajoint_uint i = 0; i < n_vars; ++i)
expect_true(pass_rel_err(g_out[i], zeta_deriv[i]));
}
};
test_grad(Xi_deriv, Psi_deriv, Omega_deriv, zeta_deriv);
term.setup(par.get(), mem.get(), lb_terms::markers);
expect_true(
pass_rel_err(term.eval(par.get(), mem.get()), true_kl_term_no_surv));
std::fill(gr.get(), gr.get() + n_params_w_va, 0.);
std::fill(gr_res.get(), gr_res.get() + params.n_params_w_va<true>(), 0.);
val = term.grad(gr.get(), par.get(), mem.get());
expect_true(pass_rel_err(val, true_kl_term_no_surv));
test_grad(Xi_deriv_no_s, Psi_deriv_no_s, Omega_deriv_no_s, zeta_deriv_no_s);
term.setup(par.get(), mem.get(), lb_terms::surv);
expect_true(
pass_rel_err(term.eval(par.get(), mem.get()), true_kl_term_no_marker));
// clean up
wmem::clear_all();
}
test_that("eval gives the right result with survival terms without frailty") {
double const eps = std::sqrt(std::numeric_limits<double>::epsilon());
subset_params params;
params.add_marker({ 2, 2, 1 });
params.add_marker({ 1, 4, 1 });
params.add_surv({ 1, 2, {0, 0}, false });
params.add_surv({ 5, 2, {1, 1}, true });
params.add_surv({ 1, 4, {1, 1}, true });
params.add_surv({ 5, 2, {1, 1}, true });
params.add_surv({ 3, 4, {0, 0}, false });
// create and fill parameter vector
vajoint_uint const n_params_w_va = params.n_params_w_va();
std::unique_ptr<double[]> par(new double[n_params_w_va]);
std::fill(par.get(), par.get() + n_params_w_va, 0.);
auto fill_par = [](double const *value, vajoint_uint const n_ele,
double *out){
std::copy(value, value + n_ele, out);
};
fill_par(Xi, n_shared_surv * n_shared_surv,
par.get() + params.vcov_surv());
fill_par(Psi, n_shared * n_shared,
par.get() + params.vcov_vary());
fill_par(Omega, n_vars * n_vars,
par.get() + params.va_vcov());
fill_par(zeta, n_vars,
par.get() + params.va_mean());
// compute the kl term
kl_term term(params);
std::unique_ptr<double[]> mem(new double[term.n_wmem()]);
term.setup(par.get(), mem.get());
expect_true(pass_rel_err(term.eval(par.get(), mem.get()), true_kl_term));
// check the gradient
std::unique_ptr<double[]> gr(new double[n_params_w_va]),
gr_res(new double[params.n_params_w_va<true>()]);
std::fill(gr.get(), gr.get() + n_params_w_va, 0.);
std::fill(gr_res.get(), gr_res.get() + params.n_params_w_va<true>(), 0.);
double val = term.grad(gr.get(), par.get(), mem.get());
expect_true(pass_rel_err(val, true_kl_term));
auto test_grad = [&](double const *Xi_deriv, double const *Psi_deriv,
double const *Omega_deriv, double const *zeta_deriv){
{
double *g_out = gr_res.get() + params.vcov_surv<true>();
double const *g_in = gr.get() + params.vcov_surv();
log_chol::dpd_mat::get(Xi_chol, n_shared_surv, g_out, g_in);
for(vajoint_uint i = 0; i < dim_tri(n_shared_surv); ++i)
expect_true(pass_rel_err(g_out[i], Xi_deriv[i]));
}
{
double *g_out = gr_res.get() + params.vcov_vary<true>();
double const *g_in = gr.get() + params.vcov_vary();
log_chol::dpd_mat::get(Psi_chol, n_shared, g_out, g_in);
for(vajoint_uint i = 0; i < dim_tri(n_shared); ++i)
expect_true(pass_rel_err(g_out[i], Psi_deriv[i]));
}
{
double *g_out = gr_res.get() + params.va_vcov<true>();
double const *g_in = gr.get() + params.va_vcov();
log_chol::dpd_mat::get(Omega_chol, n_vars, g_out, g_in);
for(vajoint_uint i = 0; i < dim_tri(n_vars); ++i)
expect_true(pass_rel_err(g_out[i], Omega_deriv[i]));
}
{
double const *g_out = gr.get() + params.va_mean();
for(vajoint_uint i = 0; i < n_vars; ++i)
expect_true(pass_rel_err(g_out[i], zeta_deriv[i]));
}
};
test_grad(Xi_deriv, Psi_deriv, Omega_deriv, zeta_deriv);
term.setup(par.get(), mem.get(), lb_terms::markers);
expect_true(
pass_rel_err(term.eval(par.get(), mem.get()), true_kl_term_no_surv));
std::fill(gr.get(), gr.get() + n_params_w_va, 0.);
std::fill(gr_res.get(), gr_res.get() + params.n_params_w_va<true>(), 0.);
val = term.grad(gr.get(), par.get(), mem.get());
expect_true(pass_rel_err(val, true_kl_term_no_surv));
test_grad(Xi_deriv_no_s, Psi_deriv_no_s, Omega_deriv_no_s, zeta_deriv_no_s);
term.setup(par.get(), mem.get(), lb_terms::surv);
expect_true(
pass_rel_err(term.eval(par.get(), mem.get()), true_kl_term_no_marker));
// clean up
wmem::clear_all();
}
}
| 42.52514 | 501 | 0.630452 | boennecd |
57530570e040e9271cd97c63f84eb65ee98db4b1 | 68,104 | hpp | C++ | src/gfcc/contrib/hf_tamm_common.hpp | smferdous1/gfcc | e7112c0dd60566266728e4d51ea8d30aea4b775d | [
"MIT"
] | null | null | null | src/gfcc/contrib/hf_tamm_common.hpp | smferdous1/gfcc | e7112c0dd60566266728e4d51ea8d30aea4b775d | [
"MIT"
] | null | null | null | src/gfcc/contrib/hf_tamm_common.hpp | smferdous1/gfcc | e7112c0dd60566266728e4d51ea8d30aea4b775d | [
"MIT"
] | null | null | null |
#ifndef TAMM_METHODS_HF_TAMM_COMMON_HPP_
#define TAMM_METHODS_HF_TAMM_COMMON_HPP_
#include "scf_guess.hpp"
//TODO: UHF,ROHF,diis,3c,dft
template<typename TensorType>
void diis(ExecutionContext& ec, TiledIndexSpace& tAO, Tensor<TensorType> D, Tensor<TensorType> F, Tensor<TensorType> err_mat,
int iter, int max_hist, int ndiis, const int n_lindep,
std::vector<Tensor<TensorType>>& diis_hist, std::vector<Tensor<TensorType>>& fock_hist);
template<typename TensorType>
void energy_diis(ExecutionContext& ec, TiledIndexSpace& tAO, int iter, int max_hist,
Tensor<TensorType> D, Tensor<TensorType> F, std::vector<Tensor<TensorType>>& D_hist,
std::vector<Tensor<TensorType>>& fock_hist, std::vector<Tensor<TensorType>>& ehf_tamm_hist);
template<typename TensorType>
void compute_1body_ints(ExecutionContext& ec, Tensor<TensorType>& tensor1e,
std::vector<libint2::Atom>& atoms, libint2::BasisSet& shells, libint2::Operator otype,
std::vector<size_t>& shell_tile_map, std::vector<Tile>& AO_tiles);
std::tuple<int,int,int,int> get_hf_nranks(const size_t N) {
// auto nranks = GA_Nnodes();
auto nnodes = GA_Cluster_nnodes();
auto ppn = GA_Cluster_nprocs(0);
int hf_guessranks = std::ceil(0.3*N);
int hf_nnodes = hf_guessranks/ppn;
if(hf_guessranks%ppn>0 || hf_nnodes==0) hf_nnodes++;
if(hf_nnodes > nnodes) hf_nnodes = nnodes;
int hf_nranks = hf_nnodes * ppn;
return std::make_tuple(nnodes,hf_nnodes,ppn,hf_nranks);
}
void compute_shellpair_list(const ExecutionContext& ec, const libint2::BasisSet& shells){
auto rank = ec.pg().rank();
// compute OBS non-negligible shell-pair list
std::tie(obs_shellpair_list, obs_shellpair_data) = compute_shellpairs(shells);
size_t nsp = 0;
for (auto& sp : obs_shellpair_list) {
nsp += sp.second.size();
}
if(rank==0) std::cout << "# of {all,non-negligible} shell-pairs = {"
<< shells.size() * (shells.size() + 1) / 2 << "," << nsp << "}"
<< endl;
}
std::tuple<int,double> compute_NRE(const ExecutionContext& ec, std::vector<libint2::Atom>& atoms, const int focc){
auto rank = ec.pg().rank();
// std::cout << "Geometries in bohr units " << std::endl;
// for (auto i = 0; i < atoms.size(); ++i)
// std::cout << atoms[i].atomic_number << " " << atoms[i].x<< " " <<
// atoms[i].y<< " " << atoms[i].z << endl;
// count the number of electrons
auto nelectron = 0;
for(size_t i = 0; i < atoms.size(); ++i)
nelectron += atoms[i].atomic_number;
const auto ndocc = nelectron / focc;
// compute the nuclear repulsion energy
double enuc = 0.0;
for(size_t i = 0; i < atoms.size(); i++)
for(size_t j = i + 1; j < atoms.size(); j++) {
double xij = atoms[i].x - atoms[j].x;
double yij = atoms[i].y - atoms[j].y;
double zij = atoms[i].z - atoms[j].z;
double r2 = xij * xij + yij * yij + zij * zij;
double r = sqrt(r2);
enuc += atoms[i].atomic_number * atoms[j].atomic_number / r;
}
return std::make_tuple(ndocc,enuc);
}
std::tuple<std::vector<size_t>, std::vector<Tile>, std::vector<Tile>>
compute_AO_tiles(const ExecutionContext& ec, const SystemData& sys_data, libint2::BasisSet& shells){
tamm::Tile tile_size = sys_data.options_map.scf_options.AO_tilesize;
auto rank = ec.pg().rank();
auto N = nbasis(shells);
//heuristic to set tilesize to atleast 5% of nbf
if(tile_size < N*0.05 && !sys_data.options_map.scf_options.force_tilesize) {
tile_size = std::ceil(N*0.05);
final_AO_tilesize = tile_size;
if(rank == 0) cout << "***** Reset tilesize to nbf*5% = " << tile_size << endl;
}
std::vector<Tile> AO_tiles;
for(auto s : shells) AO_tiles.push_back(s.size());
if(rank==0)
cout << "Number of AO tiles = " << AO_tiles.size() << endl;
tamm::Tile est_ts = 0;
std::vector<Tile> AO_opttiles;
std::vector<size_t> shell_tile_map;
for(auto s=0U;s<shells.size();s++){
est_ts += shells[s].size();
if(est_ts>=tile_size) {
AO_opttiles.push_back(est_ts);
shell_tile_map.push_back(s); //shell id specifying tile boundary
est_ts=0;
}
}
if(est_ts>0){
AO_opttiles.push_back(est_ts);
shell_tile_map.push_back(shells.size()-1);
}
// std::vector<int> vtc(AO_tiles.size());
// std::iota (std::begin(vtc), std::end(vtc), 0);
// cout << "AO tile indexes = " << vtc;
// cout << "orig AO tiles = " << AO_tiles;
// cout << "print new opt AO tiles = " << AO_opttiles;
// cout << "print shell-tile map = " << shell_tile_map;
return std::make_tuple(shell_tile_map,AO_tiles,AO_opttiles);
}
Matrix compute_orthogonalizer(ExecutionContext& ec, SystemData& sys_data, TAMMTensors& ttensors) {
auto hf_t1 = std::chrono::high_resolution_clock::now();
auto rank = ec.pg().rank();
// compute orthogonalizer X such that X.transpose() . S . X = I
//TODO: Xinv not used
Matrix X, Xinv;
double XtX_condition_number; // condition number of "re-conditioned"
// overlap obtained as Xinv.transpose() . Xinv
// one should think of columns of Xinv as the conditioned basis
// Re: name ... cond # (Xinv.transpose() . Xinv) = cond # (X.transpose() . X)
// by default assume can manage to compute with condition number of S <= 1/eps
// this is probably too optimistic, but in well-behaved cases even 10^11 is OK
std::tie(X, Xinv, XtX_condition_number) =
conditioning_orthogonalizer(ec, sys_data, ttensors.S1);
// TODO Redeclare TAMM S1 with new dims?
auto hf_t2 = std::chrono::high_resolution_clock::now();
auto hf_time = std::chrono::duration_cast<std::chrono::duration<double>>((hf_t2 - hf_t1)).count();
if(rank == 0) std::cout << "Time for computing orthogonalizer: " << hf_time << " secs" << endl << endl;
return X;
}
template<typename TensorType>
void compute_hamiltonian(
ExecutionContext& ec, std::vector<libint2::Atom>& atoms, libint2::BasisSet& shells,
std::vector<size_t>& shell_tile_map, std::vector<Tile>& AO_tiles, TAMMTensors& ttensors, EigenTensors& etensors){
using libint2::Operator;
// const size_t N = nbasis(shells);
auto rank = ec.pg().rank();
ttensors.H1 = {tAO, tAO};
ttensors.S1 = {tAO, tAO};
ttensors.T1 = {tAO, tAO};
ttensors.V1 = {tAO, tAO};
Tensor<TensorType>::allocate(&ec, ttensors.H1, ttensors.S1, ttensors.T1, ttensors.V1);
auto [mu, nu] = tAO.labels<2>("all");
auto hf_t1 = std::chrono::high_resolution_clock::now();
compute_1body_ints(ec,ttensors.S1,atoms,shells,Operator::overlap,shell_tile_map,AO_tiles);
compute_1body_ints(ec,ttensors.T1,atoms,shells,Operator::kinetic,shell_tile_map,AO_tiles);
compute_1body_ints(ec,ttensors.V1,atoms,shells,Operator::nuclear,shell_tile_map,AO_tiles);
auto hf_t2 = std::chrono::high_resolution_clock::now();
auto hf_time = std::chrono::duration_cast<std::chrono::duration<double>>((hf_t2 - hf_t1)).count();
if(rank == 0) std::cout << std::endl << "Time for computing 1-e integrals T, V, S: " << hf_time << " secs" << endl;
// Core Hamiltonian = T + V
Scheduler{ec}
(ttensors.H1(mu, nu) = ttensors.T1(mu, nu))
(ttensors.H1(mu, nu) += ttensors.V1(mu, nu)).execute();
// tamm::scale_ip(ttensors.H1(),2.0);
}
void scf_restart_test(const ExecutionContext& ec, const SystemData& sys_data, const std::string& filename,
bool restart, std::string files_prefix) {
if(!restart) return;
const auto rank = ec.pg().rank();
const bool is_uhf = (sys_data.scf_type == sys_data.SCFType::uhf);
int rstatus = 1;
std::string movecsfile_alpha = files_prefix + ".alpha.movecs";
std::string densityfile_alpha = files_prefix + ".alpha.density";
std::string movecsfile_beta = files_prefix + ".beta.movecs";
std::string densityfile_beta = files_prefix + ".beta.density";
bool status = false;
if(rank==0) {
status = fs::exists(movecsfile_alpha) && fs::exists(densityfile_alpha);
if(is_uhf)
status = status && fs::exists(movecsfile_beta) && fs::exists(densityfile_beta);
}
rstatus = status;
ec.pg().barrier();
MPI_Bcast(&rstatus ,1,mpi_type<int>() ,0,ec.pg().comm());
std::string fnf = movecsfile_alpha + "; " + densityfile_alpha;
if(is_uhf) fnf = fnf + "; " + movecsfile_beta + "; " + densityfile_beta;
if(rstatus == 0) tamm_terminate("Error reading one or all of the files: [" + fnf + "]");
}
void scf_restart(const ExecutionContext& ec, const SystemData& sys_data, const std::string& filename,
EigenTensors& etensors, std::string files_prefix) {
const auto rank = ec.pg().rank();
const auto N = sys_data.nbf_orig;
const auto Northo = N - sys_data.n_lindep;
const bool is_uhf = (sys_data.scf_type == sys_data.SCFType::uhf);
EXPECTS(Northo == sys_data.nbf);
std::string movecsfile_alpha = files_prefix + ".alpha.movecs";
std::string densityfile_alpha = files_prefix + ".alpha.density";
if(rank==0) {
cout << "Reading movecs and density files ... ";
etensors.C = read_scf_mat<TensorType>(movecsfile_alpha);
etensors.D = read_scf_mat<TensorType>(densityfile_alpha);
if(is_uhf) {
std::string movecsfile_beta = files_prefix + ".beta.movecs";
std::string densityfile_beta = files_prefix + ".beta.density";
etensors.C_beta = read_scf_mat<TensorType>(movecsfile_beta);
etensors.D_beta = read_scf_mat<TensorType>(densityfile_beta);
}
cout << "done" << endl;
}
ec.pg().barrier();
TensorType *Dbufp_a = etensors.D.data();
MPI_Bcast(Dbufp_a,N*N,mpi_type<TensorType>(),0,ec.pg().comm());
if(is_uhf) {
TensorType *Dbufp_b = etensors.D_beta.data();
MPI_Bcast(Dbufp_b,N*N,mpi_type<TensorType>(),0,ec.pg().comm());
}
ec.pg().barrier();
}
template<typename TensorType>
double tt_trace(ExecutionContext& ec, Tensor<TensorType>& T1, Tensor<TensorType>& T2){
Tensor<TensorType> tensor = {tAO, tAO};
Tensor<TensorType>::allocate(&ec,tensor);
Scheduler{ec} (tensor(mu,nu) = T1(mu,ku) * T2(ku,nu)).execute();
double trace = tamm::trace(tensor);
Tensor<TensorType>::deallocate(tensor);
return trace;
}
void print_energies(ExecutionContext& ec, TAMMTensors& ttensors, const SystemData& sys_data, bool debug=false){
const bool is_uhf = (sys_data.scf_type == sys_data.SCFType::uhf);
const bool is_rhf = (sys_data.scf_type == sys_data.SCFType::rhf);
double nelectrons = 0.0;
double kinetic_1e = 0.0;
double NE_1e = 0.0;
double energy_1e = 0.0;
double energy_2e = 0.0;
if(is_rhf) {
nelectrons = tt_trace(ec,ttensors.D_tamm,ttensors.S1);
kinetic_1e = tt_trace(ec,ttensors.D_tamm,ttensors.T1);
NE_1e = tt_trace(ec,ttensors.D_tamm,ttensors.V1);
energy_1e = tt_trace(ec,ttensors.D_tamm,ttensors.H1);
energy_2e = 0.5 * tt_trace(ec,ttensors.D_tamm,ttensors.F1tmp1);
}
if(is_uhf) {
nelectrons = tt_trace(ec,ttensors.D_tamm,ttensors.S1);
kinetic_1e = tt_trace(ec,ttensors.D_tamm,ttensors.T1);
NE_1e = tt_trace(ec,ttensors.D_tamm,ttensors.V1);
energy_1e = tt_trace(ec,ttensors.D_tamm,ttensors.H1);
energy_2e = 0.5 * tt_trace(ec,ttensors.D_tamm,ttensors.F1tmp1);
nelectrons += tt_trace(ec,ttensors.D_beta_tamm,ttensors.S1);
kinetic_1e += tt_trace(ec,ttensors.D_beta_tamm,ttensors.T1);
NE_1e += tt_trace(ec,ttensors.D_beta_tamm,ttensors.V1);
energy_1e += tt_trace(ec,ttensors.D_beta_tamm,ttensors.H1);
energy_2e += 0.5 * tt_trace(ec,ttensors.D_beta_tamm,ttensors.F1tmp1_beta);
}
if(ec.pg().rank() == 0){
std::cout << "#electrons = " << nelectrons << endl;
std::cout << "1e energy kinetic = "<< std::setprecision(16) << kinetic_1e << endl;
std::cout << "1e energy N-e = " << NE_1e << endl;
std::cout << "1e energy = " << energy_1e << endl;
std::cout << "2e energy = " << energy_2e << std::endl;
}
}
template<typename TensorType>
std::tuple<TensorType,TensorType> scf_iter_body(ExecutionContext& ec,
#ifdef USE_SCALAPACK
blacspp::Grid* blacs_grid,
scalapackpp::BlockCyclicDist2D* blockcyclic_dist,
#endif
const int& iter, const SystemData& sys_data,
TAMMTensors& ttensors, EigenTensors& etensors, bool ediis, bool scf_restart=false){
const bool is_uhf = (sys_data.scf_type == sys_data.SCFType::uhf);
const bool is_rhf = (sys_data.scf_type == sys_data.SCFType::rhf);
Tensor<TensorType>& H1 = ttensors.H1;
Tensor<TensorType>& S1 = ttensors.S1;
Tensor<TensorType>& D_diff = ttensors.D_diff;
Tensor<TensorType>& ehf_tmp = ttensors.ehf_tmp;
Tensor<TensorType>& ehf_tamm = ttensors.ehf_tamm;
Matrix& X_a = etensors.X;
Matrix& F_alpha = etensors.F;
Matrix& C_alpha = etensors.C;
Matrix& D_alpha = etensors.D;
Matrix& C_occ = etensors.C_occ;
Tensor<TensorType>& F1_alpha = ttensors.F1;
Tensor<TensorType>& F1tmp1_alpha = ttensors.F1tmp1;
Tensor<TensorType>& FD_alpha_tamm = ttensors.FD_tamm;
Tensor<TensorType>& FDS_alpha_tamm = ttensors.FDS_tamm;
Tensor<TensorType>& D_alpha_tamm = ttensors.D_tamm;
Tensor<TensorType>& D_last_alpha_tamm = ttensors.D_last_tamm;
Matrix& X_b = etensors.X_beta;
Matrix& F_beta = etensors.F_beta;
Matrix& C_beta = etensors.C_beta;
Matrix& D_beta = etensors.D_beta;
Tensor<TensorType>& F1_beta = ttensors.F1_beta;
Tensor<TensorType>& F1tmp1_beta = ttensors.F1tmp1_beta;
Tensor<TensorType>& FD_beta_tamm = ttensors.FD_beta_tamm;
Tensor<TensorType>& FDS_beta_tamm = ttensors.FDS_beta_tamm;
Tensor<TensorType>& D_beta_tamm = ttensors.D_beta_tamm;
Tensor<TensorType>& D_last_beta_tamm = ttensors.D_last_beta_tamm;
Scheduler sch{ec};
const int64_t N = sys_data.nbf_orig;
auto rank = ec.pg().rank();
auto debug = sys_data.options_map.scf_options.debug;
auto [mu, nu, ku] = tAO.labels<3>("all"); //TODO
const int max_hist = sys_data.options_map.scf_options.diis_hist;
sch
(F1_alpha() = H1())
(F1_alpha() += F1tmp1_alpha())
.execute();
if(is_uhf) {
sch
(F1_beta() = H1())
(F1_beta() += F1tmp1_beta())
.execute();
}
Tensor<TensorType> err_mat_alpha_tamm{tAO, tAO};
Tensor<TensorType> err_mat_beta_tamm{tAO, tAO};
Tensor<TensorType>::allocate(&ec, err_mat_alpha_tamm);
if(is_uhf) Tensor<TensorType>::allocate(&ec, err_mat_beta_tamm);
sch
(FD_alpha_tamm(mu,nu) = F1_alpha(mu,ku) * D_last_alpha_tamm(ku,nu))
(FDS_alpha_tamm(mu,nu) = FD_alpha_tamm(mu,ku) * S1(ku,nu))
(err_mat_alpha_tamm(mu,nu) = FDS_alpha_tamm(mu,nu))
(err_mat_alpha_tamm(mu,nu) -= FDS_alpha_tamm(nu,mu))
.execute();
if(is_uhf) {
sch
(FD_beta_tamm(mu,nu) = F1_beta(mu,ku) * D_last_beta_tamm(ku,nu))
(FDS_beta_tamm(mu,nu) = FD_beta_tamm(mu,ku) * S1(ku,nu))
(err_mat_beta_tamm(mu,nu) = FDS_beta_tamm(mu,nu))
(err_mat_beta_tamm(mu,nu) -= FDS_beta_tamm(nu,mu))
.execute();
}
if(iter >= 1 && !ediis) {
if(is_rhf) {
++idiis;
diis(ec, tAO, D_alpha_tamm, F1_alpha, err_mat_alpha_tamm, iter, max_hist, idiis, sys_data.n_lindep,
ttensors.diis_hist, ttensors.fock_hist);
}
if(is_uhf) {
Tensor<TensorType> F1_T{tAO, tAO};
Tensor<TensorType> F1_S{tAO, tAO};
Tensor<TensorType> D_T{tAO, tAO};
Tensor<TensorType> D_S{tAO, tAO};
sch
.allocate(F1_T,F1_S,D_T,D_S)
(F1_T() = F1_alpha())
(F1_T() += F1_beta())
(F1_S() = F1_alpha())
(F1_S() -= F1_beta())
(D_T() = D_alpha_tamm())
(D_T() += D_beta_tamm())
(D_S() = D_alpha_tamm())
(D_S() -= D_beta_tamm())
.execute();
diis(ec, tAO, D_T, F1_T, err_mat_alpha_tamm, iter, max_hist, idiis, sys_data.n_lindep,
ttensors.diis_hist, ttensors.fock_hist);
diis(ec, tAO, D_S, F1_S, err_mat_beta_tamm, iter, max_hist, idiis, sys_data.n_lindep,
ttensors.diis_beta_hist, ttensors.fock_beta_hist);
sch
(F1_alpha() = 0.5 * F1_T())
(F1_alpha() += 0.5 * F1_S())
(F1_beta() = 0.5 * F1_T())
(F1_beta() -= 0.5 * F1_S())
(D_alpha_tamm() = 0.5 * D_T())
(D_alpha_tamm() += 0.5 * D_S())
(D_beta_tamm() = 0.5 * D_T())
(D_beta_tamm() -= 0.5 * D_S())
.deallocate(F1_T,F1_S,D_T,D_S)
.execute();
}
}
if( rank == 0 ) {
tamm_to_eigen_tensor(F1_alpha,F_alpha);
if(is_uhf) {
tamm_to_eigen_tensor(F1_beta, F_beta);
}
}
auto do_t1 = std::chrono::high_resolution_clock::now();
if(!scf_restart){
// solve F C = e S C by (conditioned) transformation to F' C' = e C',
// where
// F' = X.transpose() . F . X; the original C is obtained as C = X . C'
#ifdef USE_SCALAPACK
const auto& grid = *blacs_grid;
const auto mb = blockcyclic_dist->mb();
const auto Northo = sys_data.nbf;
if( grid.ipr() >= 0 and grid.ipc() >= 0 ) {
// std::cout << "IN SCALAPACK " << rank << std::endl;
// TODO: Optimize intermediates here
scalapackpp::BlockCyclicMatrix<double>
Fa_sca ( grid, N, N, mb, mb ),
Xa_sca ( grid, Northo, N, mb, mb ), // Xa is row-major
Fp_sca ( grid, Northo, Northo, mb, mb ),
Ca_sca ( grid, Northo, Northo, mb, mb ),
TMP1_sca( grid, N, Northo, mb, mb ),
TMP2_sca( grid, Northo, N, mb, mb );
// Scatter Fock / X alpha from root
Fa_sca.scatter_to( N, N, F_alpha.data(), N, 0, 0 );
Xa_sca.scatter_to( Northo, N, X_a.data(), Northo, 0, 0 );
// Compute TMP = F * X -> F * X**T (b/c row-major)
scalapackpp::pgemm( scalapackpp::Op::NoTrans, scalapackpp::Op::Trans,
1., Fa_sca, Xa_sca, 0., TMP1_sca );
// Compute Fp = X**T * TMP -> X * TMP (b/c row-major)
scalapackpp::pgemm( scalapackpp::Op::NoTrans, scalapackpp::Op::NoTrans,
1., Xa_sca, TMP1_sca, 0., Fp_sca );
// Solve EVP
std::vector<double> eps_a( Northo );
scalapackpp::hereigd( scalapackpp::Job::Vec, scalapackpp::Uplo::Lower,
Fp_sca, eps_a.data(), Ca_sca );
// Backtransform TMP = X * Ca -> TMP**T = Ca**T * X
scalapackpp::pgemm( scalapackpp::Op::Trans, scalapackpp::Op::NoTrans,
1., Ca_sca, Xa_sca, 0., TMP2_sca );
// Gather results
if( rank == 0 ) C_alpha.resize( N, Northo );
TMP2_sca.gather_from( Northo, N, C_alpha.data(), Northo, 0, 0 );
if(is_uhf) {
// Scatter Fock / X beta from root
Fa_sca.scatter_to( N, N, F_beta.data(), N, 0, 0 );
Xa_sca.scatter_to( Northo, N, X_b.data(), Northo, 0, 0 );
// Compute TMP = F * X -> F * X**T (b/c row-major)
scalapackpp::pgemm( scalapackpp::Op::NoTrans, scalapackpp::Op::Trans,
1., Fa_sca, Xa_sca, 0., TMP1_sca );
// Compute Fp = X**T * TMP -> X * TMP (b/c row-major)
scalapackpp::pgemm( scalapackpp::Op::NoTrans, scalapackpp::Op::NoTrans,
1., Xa_sca, TMP1_sca, 0., Fp_sca );
// Solve EVP
std::vector<double> eps_a( Northo );
scalapackpp::hereigd( scalapackpp::Job::Vec, scalapackpp::Uplo::Lower,
Fp_sca, eps_a.data(), Ca_sca );
// Backtransform TMP = X * Cb -> TMP**T = Cb**T * X
scalapackpp::pgemm( scalapackpp::Op::Trans, scalapackpp::Op::NoTrans,
1., Ca_sca, Xa_sca, 0., TMP2_sca );
// Gather results
if( rank == 0 ) C_beta.resize( N, Northo );
TMP2_sca.gather_from( Northo, N, C_beta.data(), Northo, 0, 0 );
}
} // rank participates in ScaLAPACK call
#elif defined(EIGEN_DIAG)
if(is_rhf) {
Eigen::SelfAdjointEigenSolver<Matrix> eig_solver_alpha(X_a.transpose() * F_alpha * X_a);
C_alpha = X_a * eig_solver_alpha.eigenvectors();
}
if(is_uhf) {
Eigen::SelfAdjointEigenSolver<Matrix> eig_solver_alpha(X_a.transpose() * F_alpha * X_a);
C_alpha = X_a * eig_solver_alpha.eigenvectors();
Eigen::SelfAdjointEigenSolver<Matrix> eig_solver_beta( X_b.transpose() * F_beta * X_b);
C_beta = X_b * eig_solver_beta.eigenvectors();
}
#else
if(is_rhf) {
const int64_t Northo_a = sys_data.nbf; //X_a.cols();
if( rank == 0 ) {
Matrix Fp = F_alpha; // XXX: Can F be destroyed?
C_alpha.resize(N,Northo_a);
linalg::blas::gemm( 'N', 'T', N, Northo_a, N,
1., Fp.data(), N, X_a.data(), Northo_a,
0., C_alpha.data(), N );
linalg::blas::gemm( 'N', 'N', Northo_a, Northo_a, N,
1., X_a.data(), Northo_a, C_alpha.data(), N,
0., Fp.data(), Northo_a );
std::vector<double> eps_a(Northo_a);
linalg::lapack::syevd( 'V', 'L', Northo_a, Fp.data(), Northo_a, eps_a.data() );
linalg::blas::gemm( 'T', 'N', Northo_a, N, Northo_a,
1., Fp.data(), Northo_a, X_a.data(), Northo_a,
0., C_alpha.data(), Northo_a );
}
// else C_alpha.resize( N, Northo_a );
// if( ec.pg().size() > 1 )
// MPI_Bcast( C_alpha.data(), C_alpha.size(), MPI_DOUBLE, 0, ec.pg().comm() );
}
if(is_uhf) {
const int64_t Northo_a = sys_data.nbf; //X_a.cols();
const int64_t Northo_b = sys_data.nbf; //X_b.cols();
if( rank == 0 ) {
//alpha
Matrix Fp = F_alpha;
C_alpha.resize(N,Northo_a);
linalg::blas::gemm( 'N', 'T', N, Northo_a, N,
1., Fp.data(), N, X_a.data(), Northo_a,
0., C_alpha.data(), N );
linalg::blas::gemm( 'N', 'N', Northo_a, Northo_a, N,
1., X_a.data(), Northo_a, C_alpha.data(), N,
0., Fp.data(), Northo_a );
std::vector<double> eps_a(Northo_a);
linalg::lapack::syevd( 'V', 'L', Northo_a, Fp.data(), Northo_a, eps_a.data() );
linalg::blas::gemm( 'T', 'N', Northo_a, N, Northo_a,
1., Fp.data(), Northo_a, X_a.data(), Northo_a,
0., C_alpha.data(), Northo_a );
//beta
Fp = F_beta;
C_beta.resize(N,Northo_b);
linalg::blas::gemm( 'N', 'T', N, Northo_b, N,
1., Fp.data(), N, X_b.data(), Northo_b,
0., C_beta.data(), N );
linalg::blas::gemm( 'N', 'N', Northo_b, Northo_b, N,
1., X_b.data(), Northo_b, C_beta.data(), N,
0., Fp.data(), Northo_b );
std::vector<double> eps_b(Northo_b);
linalg::lapack::syevd( 'V', 'L', Northo_b, Fp.data(), Northo_b, eps_b.data() );
linalg::blas::gemm( 'T', 'N', Northo_b, N, Northo_b,
1., Fp.data(), Northo_b, X_b.data(), Northo_b,
0., C_beta.data(), Northo_b );
}
// else {
// C_alpha.resize(N, Northo_a);
// C_beta.resize(N, Northo_b);
// }
// if( ec.pg().size() > 1 ) {
// MPI_Bcast( C_alpha.data(), C_alpha.size(), MPI_DOUBLE, 0, ec.pg().comm() );
// MPI_Bcast( C_beta.data(), C_beta.size(), MPI_DOUBLE, 0, ec.pg().comm() );
// }
}
#endif
// compute density
if( rank == 0 ) {
if(is_rhf) {
C_occ = C_alpha.leftCols(sys_data.nelectrons_alpha);
D_alpha = 2.0 * C_occ * C_occ.transpose();
X_a = C_alpha;
}
if(is_uhf) {
C_occ = C_alpha.leftCols(sys_data.nelectrons_alpha);
D_alpha = C_occ * C_occ.transpose();
X_a = C_alpha;
C_occ = C_beta.leftCols(sys_data.nelectrons_beta);
D_beta = C_occ * C_occ.transpose();
X_b = C_beta;
}
}
auto do_t2 = std::chrono::high_resolution_clock::now();
auto do_time =
std::chrono::duration_cast<std::chrono::duration<double>>((do_t2 - do_t1)).count();
if(rank == 0 && debug) std::cout << "eigen_solve:" << do_time << "s, " << std::endl;
}//end scf_restart
if(rank == 0) {
eigen_to_tamm_tensor(D_alpha_tamm,D_alpha);
if(is_uhf) {
eigen_to_tamm_tensor(D_beta_tamm, D_beta);
}
}
MPI_Bcast(D_alpha.data(), D_alpha.size(), MPI_DOUBLE, 0, ec.pg().comm() );
if(is_uhf) MPI_Bcast(D_beta.data(), D_beta.size(), MPI_DOUBLE, 0, ec.pg().comm() );
double ehf = 0.0;
if(is_rhf) {
sch
(ehf_tmp(mu,nu) = H1(mu,nu))
(ehf_tmp(mu,nu) += F1_alpha(mu,nu))
(ehf_tamm() = 0.5 * D_last_alpha_tamm() * ehf_tmp())
.execute();
}
if(is_uhf) {
sch
(ehf_tmp(mu,nu) = H1(mu,nu))
(ehf_tmp(mu,nu) += F1_alpha(mu,nu))
(ehf_tamm() = 0.5 * D_last_alpha_tamm() * ehf_tmp())
(ehf_tmp(mu,nu) = H1(mu,nu))
(ehf_tmp(mu,nu) += F1_beta(mu,nu))
(ehf_tamm() += 0.5 * D_last_beta_tamm() * ehf_tmp())
.execute();
}
ehf = get_scalar(ehf_tamm);
// if(ediis) {
// compute_2bf<TensorType>(ec, sys_data, obs, do_schwarz_screen, shell2bf, SchwarzK,
// max_nprim4,shells, ttensors, etensors, do_density_fitting);
// Tensor<TensorType> Dcopy{tAO,tAO};
// Tensor<TensorType> Fcopy{tAO, tAO};
// Tensor<TensorType> ehf_tamm_copy{};
// Tensor<TensorType>::allocate(&ec,Dcopy,Fcopy,ehf_tamm_copy);
// sch
// (Dcopy() = D_alpha_tamm())
// (Fcopy() = F1tmp1_alpha())
// (ehf_tmp(mu,nu) = F1tmp1_alpha(mu,nu))
// (ehf_tamm_copy() = 0.5 * D_alpha_tamm() * ehf_tmp())
// // (ehf_tamm_copy() = ehf_tamm())
// .execute();
// ttensors.D_hist.push_back(Dcopy);
// ttensors.fock_hist.push_back(Fcopy);
// ttensors.ehf_tamm_hist.push_back(ehf_tamm_copy);
// if(rank==0) cout << "iter: " << iter << "," << (int)ttensors.D_hist.size() << endl;
// energy_diis(ec, tAO, iter, max_hist, D_alpha_tamm,
// ttensors.D_hist, ttensors.fock_hist, ttensors.ehf_tamm_hist);
// }
double rmsd = 0.0;
sch
(D_diff() = D_alpha_tamm())
(D_diff() -= D_last_alpha_tamm())
.execute();
rmsd = norm(D_diff)/(double)(1.0*N);
if(is_uhf) {
sch
(D_diff() = D_beta_tamm())
(D_diff() -= D_last_beta_tamm())
.execute();
rmsd += norm(D_diff)/(double)(1.0*N);
}
double alpha = sys_data.options_map.scf_options.alpha;
if(rmsd < 1e-6) {
switch_diis = true;
} //rmsd check
// D = alpha*D + (1.0-alpha)*D_last;
if(is_rhf) {
tamm::scale_ip(D_alpha_tamm(),alpha);
sch(D_alpha_tamm() += (1.0-alpha)*D_last_alpha_tamm()).execute();
tamm_to_eigen_tensor(D_alpha_tamm,D_alpha);
}
if(is_uhf) {
tamm::scale_ip(D_alpha_tamm(),alpha);
sch(D_alpha_tamm() += (1.0-alpha) * D_last_alpha_tamm()).execute();
tamm_to_eigen_tensor(D_alpha_tamm,D_alpha);
tamm::scale_ip(D_beta_tamm(),alpha);
sch(D_beta_tamm() += (1.0-alpha) * D_last_beta_tamm()).execute();
tamm_to_eigen_tensor(D_beta_tamm, D_beta);
}
return std::make_tuple(ehf,rmsd);
}
template<typename TensorType>
void compute_2bf_simple(ExecutionContext& ec, const SystemData& sys_data, const libint2::BasisSet& obs,
const bool do_schwarz_screen, const std::vector<size_t>& shell2bf,
const Matrix& SchwarzK,
const size_t& max_nprim4, libint2::BasisSet& shells,
TAMMTensors& ttensors, EigenTensors& etensors, const bool do_density_fitting=false){
using libint2::Operator;
const bool is_uhf = (sys_data.scf_type == sys_data.SCFType::uhf);
const bool is_rhf = (sys_data.scf_type == sys_data.SCFType::rhf);
Matrix& G_a = etensors.G;
Matrix& D_a = etensors.D;
Tensor<TensorType>& F1tmp = ttensors.F1tmp;
Tensor<TensorType>& F1tmp1_a = ttensors.F1tmp1;
Matrix& G_b = etensors.G_beta;
Matrix& D_b = etensors.D_beta;
Tensor<TensorType>& F1tmp1_b = ttensors.F1tmp1_beta;
double fock_precision = std::min(sys_data.options_map.scf_options.tol_int, 1e-3 * sys_data.options_map.scf_options.conve);
auto rank = ec.pg().rank();
auto N = sys_data.nbf_orig;
auto debug = sys_data.options_map.scf_options.debug;
Matrix D_shblk_norm = compute_shellblock_norm(obs, D_a); // matrix of infty-norms of shell blocks
double engine_precision = fock_precision;
// construct the 2-electron repulsion integrals engine pool
using libint2::Engine;
Engine engine(Operator::coulomb, obs.max_nprim(), obs.max_l(), 0);
engine.set_precision(engine_precision);
const auto& buf = engine.results();
auto comp_2bf_lambda = [&](IndexVector blockid) {
auto s1 = blockid[0];
auto bf1_first = shell2bf[s1];
auto n1 = obs[s1].size();
auto sp12_iter = obs_shellpair_data.at(s1).begin();
auto s2 = blockid[1];
auto s2spl = obs_shellpair_list[s1];
auto s2_itr = std::find(s2spl.begin(),s2spl.end(),s2);
if(s2_itr == s2spl.end()) return;
auto s2_pos = std::distance(s2spl.begin(),s2_itr);
auto bf2_first = shell2bf[s2];
auto n2 = obs[s2].size();
std::advance(sp12_iter,s2_pos);
const auto* sp12 = sp12_iter->get();
const auto Dnorm12 = do_schwarz_screen ? D_shblk_norm(s1, s2) : 0.;
for (decltype(s1) s3 = 0; s3 <= s1; ++s3) {
auto bf3_first = shell2bf[s3];
auto n3 = obs[s3].size();
const auto Dnorm123 =
do_schwarz_screen
? std::max(D_shblk_norm(s1, s3),
std::max(D_shblk_norm(s2, s3), Dnorm12))
: 0.;
auto sp34_iter = obs_shellpair_data.at(s3).begin();
const auto s4_max = (s1 == s3) ? s2 : s3;
for (const auto& s4 : obs_shellpair_list[s3]) {
if (s4 > s4_max)
break; // for each s3, s4 are stored in monotonically increasing
// order
// must update the iter even if going to skip s4
const auto* sp34 = sp34_iter->get();
++sp34_iter;
const auto Dnorm1234 =
do_schwarz_screen
? std::max(D_shblk_norm(s1, s4),
std::max(D_shblk_norm(s2, s4),
std::max(D_shblk_norm(s3, s4), Dnorm123)))
: 0.;
if (do_schwarz_screen &&
Dnorm1234 * SchwarzK(s1, s2) * SchwarzK(s3, s4) < fock_precision)
continue;
auto bf4_first = shell2bf[s4];
auto n4 = obs[s4].size();
// compute the permutational degeneracy (i.e. # of equivalents) of
// the given shell set
auto s12_deg = (s1 == s2) ? 1 : 2;
auto s34_deg = (s3 == s4) ? 1 : 2;
auto s12_34_deg = (s1 == s3) ? (s2 == s4 ? 1 : 2) : 2;
auto s1234_deg = s12_deg * s34_deg * s12_34_deg;
engine.compute2<Operator::coulomb, libint2::BraKet::xx_xx, 0>(
obs[s1], obs[s2], obs[s3], obs[s4], sp12, sp34);
const auto* buf_1234 = buf[0];
if (buf_1234 == nullptr)
continue; // if all integrals screened out, skip to next quartet
// 1) each shell set of integrals contributes up to 6 shell sets of
// the Fock matrix:
// F(a,b) += 1/2 * (ab|cd) * D(c,d)
// F(c,d) += 1/2 * (ab|cd) * D(a,b)
// F(b,d) -= 1/8 * (ab|cd) * D(a,c)
// F(b,c) -= 1/8 * (ab|cd) * D(a,d)
// F(a,c) -= 1/8 * (ab|cd) * D(b,d)
// F(a,d) -= 1/8 * (ab|cd) * D(b,c)
// 2) each permutationally-unique integral (shell set) must be
// scaled by its degeneracy,
// i.e. the number of the integrals/sets equivalent to it
// 3) the end result must be symmetrized
for (decltype(n1) f1 = 0, f1234 = 0; f1 != n1; ++f1) {
const auto bf1 = f1 + bf1_first;
for (decltype(n2) f2 = 0; f2 != n2; ++f2) {
const auto bf2 = f2 + bf2_first;
for (decltype(n3) f3 = 0; f3 != n3; ++f3) {
const auto bf3 = f3 + bf3_first;
for (decltype(n4) f4 = 0; f4 != n4; ++f4, ++f1234) {
const auto bf4 = f4 + bf4_first;
const auto value = buf_1234[f1234];
const auto value_scal_by_deg = value * s1234_deg;
if(is_uhf) {
//alpha_part
G_a(bf1, bf2) += 0.5 * D_a(bf3, bf4) * value_scal_by_deg;
G_a(bf3, bf4) += 0.5 * D_a(bf1, bf2) * value_scal_by_deg;
G_a(bf1, bf2) += 0.5 * D_b(bf3, bf4) * value_scal_by_deg;
G_a(bf3, bf4) += 0.5 * D_b(bf1, bf2) * value_scal_by_deg;
G_a(bf1, bf3) -= 0.25 * D_a(bf2, bf4) * value_scal_by_deg;
G_a(bf2, bf4) -= 0.25 * D_a(bf1, bf3) * value_scal_by_deg;
G_a(bf1, bf4) -= 0.25 * D_a(bf2, bf3) * value_scal_by_deg;
G_a(bf2, bf3) -= 0.25 * D_a(bf1, bf4) * value_scal_by_deg;
//beta_part
G_b(bf1, bf2) += 0.5 * D_b(bf3, bf4) * value_scal_by_deg;
G_b(bf3, bf4) += 0.5 * D_b(bf1, bf2) * value_scal_by_deg;
G_b(bf1, bf2) += 0.5 * D_a(bf3, bf4) * value_scal_by_deg;
G_b(bf3, bf4) += 0.5 * D_a(bf1, bf2) * value_scal_by_deg;
G_b(bf1, bf3) -= 0.25 * D_b(bf2, bf4) * value_scal_by_deg;
G_b(bf2, bf4) -= 0.25 * D_b(bf1, bf3) * value_scal_by_deg;
G_b(bf1, bf4) -= 0.25 * D_b(bf2, bf3) * value_scal_by_deg;
G_b(bf2, bf3) -= 0.25 * D_b(bf1, bf4) * value_scal_by_deg;
}
if(is_rhf) {
G_a(bf1, bf2) += 0.5 * D_a(bf3, bf4) * value_scal_by_deg;
G_a(bf3, bf4) += 0.5 * D_a(bf1, bf2) * value_scal_by_deg;
G_a(bf1, bf3) -= 0.125 * D_a(bf2, bf4) * value_scal_by_deg;
G_a(bf2, bf4) -= 0.125 * D_a(bf1, bf3) * value_scal_by_deg;
G_a(bf1, bf4) -= 0.125 * D_a(bf2, bf3) * value_scal_by_deg;
G_a(bf2, bf3) -= 0.125 * D_a(bf1, bf4) * value_scal_by_deg;
}
}
}
}
}
}
}
};
G_a.setZero(N,N);
if(is_uhf) G_b.setZero(N,N);
block_for(ec, F1tmp(), comp_2bf_lambda);
//symmetrize G
Matrix Gt = 0.5*(G_a + G_a.transpose());
G_a = Gt;
if(is_uhf) {
Gt = 0.5*(G_b + G_b.transpose());
G_b = Gt;
}
Gt.resize(0,0);
eigen_to_tamm_tensor_acc(F1tmp1_a,G_a);
if(is_uhf) eigen_to_tamm_tensor_acc(F1tmp1_b,G_b);
ec.pg().barrier();
// auto F1tmp1_nrm = norm(F1tmp1);
// if(rank==0) cout << std::setprecision(18) << "in compute_2bf, norm of F1tmp1: " << F1tmp1_nrm << endl;
}
template<typename TensorType>
void compute_2bf(ExecutionContext& ec, const SystemData& sys_data, const libint2::BasisSet& obs,
const bool do_schwarz_screen, const std::vector<size_t>& shell2bf,
const Matrix& SchwarzK,
const size_t& max_nprim4, libint2::BasisSet& shells,
TAMMTensors& ttensors, EigenTensors& etensors, const bool do_density_fitting=false){
using libint2::Operator;
const bool is_uhf = (sys_data.scf_type == sys_data.SCFType::uhf);
const bool is_rhf = (sys_data.scf_type == sys_data.SCFType::rhf);
Matrix& G = etensors.G;
Matrix& D = etensors.D;
Matrix& G_beta = etensors.G_beta;
Matrix& D_beta = etensors.D_beta;
Tensor<TensorType>& F1tmp = ttensors.F1tmp;
Tensor<TensorType>& F1tmp1 = ttensors.F1tmp1;
Tensor<TensorType>& F1tmp1_beta = ttensors.F1tmp1_beta;
Tensor<TensorType>& Zxy_tamm = ttensors.Zxy_tamm;
Tensor<TensorType>& xyK_tamm = ttensors.xyK_tamm;
double fock_precision = std::min(sys_data.options_map.scf_options.tol_int, 1e-3 * sys_data.options_map.scf_options.conve);
auto rank = ec.pg().rank();
auto N = sys_data.nbf_orig;
auto debug = sys_data.options_map.scf_options.debug;
auto do_t1 = std::chrono::high_resolution_clock::now();
Matrix D_shblk_norm = compute_shellblock_norm(obs, D); // matrix of infty-norms of shell blocks
//TODO: Revisit
double engine_precision = fock_precision;
if(rank == 0)
assert(engine_precision > max_engine_precision &&
"using precomputed shell pair data limits the max engine precision"
" ... make max_engine_precision smaller and recompile");
// construct the 2-electron repulsion integrals engine pool
using libint2::Engine;
Engine engine(Operator::coulomb, obs.max_nprim(), obs.max_l(), 0);
engine.set_precision(engine_precision);
const auto& buf = engine.results();
#if 1
auto comp_2bf_lambda = [&](IndexVector blockid) {
auto s1 = blockid[0];
auto bf1_first = shell2bf[s1];
auto n1 = obs[s1].size();
auto sp12_iter = obs_shellpair_data.at(s1).begin();
auto s2 = blockid[1];
auto s2spl = obs_shellpair_list[s1];
auto s2_itr = std::find(s2spl.begin(),s2spl.end(),s2);
if(s2_itr == s2spl.end()) return;
auto s2_pos = std::distance(s2spl.begin(),s2_itr);
auto bf2_first = shell2bf[s2];
auto n2 = obs[s2].size();
std::advance(sp12_iter,s2_pos);
const auto* sp12 = sp12_iter->get();
const auto Dnorm12 = do_schwarz_screen ? D_shblk_norm(s1, s2) : 0.;
for (decltype(s1) s3 = 0; s3 <= s1; ++s3) {
auto bf3_first = shell2bf[s3];
auto n3 = obs[s3].size();
const auto Dnorm123 =
do_schwarz_screen
? std::max(D_shblk_norm(s1, s3),
std::max(D_shblk_norm(s2, s3), Dnorm12))
: 0.;
auto sp34_iter = obs_shellpair_data.at(s3).begin();
const auto s4_max = (s1 == s3) ? s2 : s3;
for (const auto& s4 : obs_shellpair_list[s3]) {
if (s4 > s4_max)
break; // for each s3, s4 are stored in monotonically increasing
// order
// must update the iter even if going to skip s4
const auto* sp34 = sp34_iter->get();
++sp34_iter;
const auto Dnorm1234 =
do_schwarz_screen
? std::max(D_shblk_norm(s1, s4),
std::max(D_shblk_norm(s2, s4),
std::max(D_shblk_norm(s3, s4), Dnorm123)))
: 0.;
if (do_schwarz_screen &&
Dnorm1234 * SchwarzK(s1, s2) * SchwarzK(s3, s4) < fock_precision)
continue;
auto bf4_first = shell2bf[s4];
auto n4 = obs[s4].size();
// compute the permutational degeneracy (i.e. # of equivalents) of
// the given shell set
auto s12_deg = (s1 == s2) ? 1 : 2;
auto s34_deg = (s3 == s4) ? 1 : 2;
auto s12_34_deg = (s1 == s3) ? (s2 == s4 ? 1 : 2) : 2;
auto s1234_deg = s12_deg * s34_deg * s12_34_deg;
engine.compute2<Operator::coulomb, libint2::BraKet::xx_xx, 0>(
obs[s1], obs[s2], obs[s3], obs[s4], sp12, sp34);
const auto* buf_1234 = buf[0];
if (buf_1234 == nullptr)
continue; // if all integrals screened out, skip to next quartet
// 1) each shell set of integrals contributes up to 6 shell sets of
// the Fock matrix:
// F(a,b) += 1/2 * (ab|cd) * D(c,d)
// F(c,d) += 1/2 * (ab|cd) * D(a,b)
// F(b,d) -= 1/8 * (ab|cd) * D(a,c)
// F(b,c) -= 1/8 * (ab|cd) * D(a,d)
// F(a,c) -= 1/8 * (ab|cd) * D(b,d)
// F(a,d) -= 1/8 * (ab|cd) * D(b,c)
// 2) each permutationally-unique integral (shell set) must be
// scaled by its degeneracy,
// i.e. the number of the integrals/sets equivalent to it
// 3) the end result must be symmetrized
for (decltype(n1) f1 = 0, f1234 = 0; f1 != n1; ++f1) {
const auto bf1 = f1 + bf1_first;
for (decltype(n2) f2 = 0; f2 != n2; ++f2) {
const auto bf2 = f2 + bf2_first;
for (decltype(n3) f3 = 0; f3 != n3; ++f3) {
const auto bf3 = f3 + bf3_first;
for (decltype(n4) f4 = 0; f4 != n4; ++f4, ++f1234) {
const auto bf4 = f4 + bf4_first;
const auto value = buf_1234[f1234];
const auto value_scal_by_deg = value * s1234_deg;
if(is_uhf) {
//alpha_part
G(bf1, bf2) += 0.5 * D(bf3, bf4) * value_scal_by_deg;
G(bf3, bf4) += 0.5 * D(bf1, bf2) * value_scal_by_deg;
G(bf1, bf2) += 0.5 * D_beta(bf3, bf4) * value_scal_by_deg;
G(bf3, bf4) += 0.5 * D_beta(bf1, bf2) * value_scal_by_deg;
G(bf1, bf3) -= 0.25 * D(bf2, bf4) * value_scal_by_deg;
G(bf2, bf4) -= 0.25 * D(bf1, bf3) * value_scal_by_deg;
G(bf1, bf4) -= 0.25 * D(bf2, bf3) * value_scal_by_deg;
G(bf2, bf3) -= 0.25 * D(bf1, bf4) * value_scal_by_deg;
//beta_part
G_beta(bf1, bf2) += 0.5 * D_beta(bf3, bf4) * value_scal_by_deg;
G_beta(bf3, bf4) += 0.5 * D_beta(bf1, bf2) * value_scal_by_deg;
G_beta(bf1, bf2) += 0.5 * D(bf3, bf4) * value_scal_by_deg;
G_beta(bf3, bf4) += 0.5 * D(bf1, bf2) * value_scal_by_deg;
G_beta(bf1, bf3) -= 0.25 * D_beta(bf2, bf4) * value_scal_by_deg;
G_beta(bf2, bf4) -= 0.25 * D_beta(bf1, bf3) * value_scal_by_deg;
G_beta(bf1, bf4) -= 0.25 * D_beta(bf2, bf3) * value_scal_by_deg;
G_beta(bf2, bf3) -= 0.25 * D_beta(bf1, bf4) * value_scal_by_deg;
}
if(is_rhf) {
G(bf1, bf2) += 0.5 * D(bf3, bf4) * value_scal_by_deg;
G(bf3, bf4) += 0.5 * D(bf1, bf2) * value_scal_by_deg;
G(bf1, bf3) -= 0.125 * D(bf2, bf4) * value_scal_by_deg;
G(bf2, bf4) -= 0.125 * D(bf1, bf3) * value_scal_by_deg;
G(bf1, bf4) -= 0.125 * D(bf2, bf3) * value_scal_by_deg;
G(bf2, bf3) -= 0.125 * D(bf1, bf4) * value_scal_by_deg;
}
}
}
}
}
}
}
};
#endif
decltype(do_t1) do_t2;
double do_time;
if(!do_density_fitting){
G.setZero(N,N);
if(is_uhf) G_beta.setZero(N,N);
block_for(ec, F1tmp(), comp_2bf_lambda);
//symmetrize G
Matrix Gt = 0.5*(G + G.transpose());
G = Gt;
if(is_uhf) {
Gt = 0.5*(G_beta + G_beta.transpose());
G_beta = Gt;
}
Gt.resize(0,0);
do_t2 = std::chrono::high_resolution_clock::now();
do_time =
std::chrono::duration_cast<std::chrono::duration<double>>((do_t2 - do_t1)).count();
if(rank == 0 && debug) std::cout << "2BF:" << do_time << "s, ";
eigen_to_tamm_tensor_acc(F1tmp1,G);
if(is_uhf) eigen_to_tamm_tensor_acc(F1tmp1_beta,G_beta);
// ec.pg().barrier();
}
else {
#if 1
// const auto n = obs.nbf();
// const auto ndf = dfbs.nbf();
using libint2::Operator;
using libint2::BraKet;
using libint2::Engine;
// using first time? compute 3-center ints and transform to inv sqrt
// representation
if (!is_3c_init) {
is_3c_init = true;
// const auto nshells = obs.size();
// const auto nshells_df = dfbs.size();
const auto& unitshell = libint2::Shell::unit();
auto engine = libint2::Engine(libint2::Operator::coulomb,
std::max(obs.max_nprim(), dfbs.max_nprim()),
std::max(obs.max_l(), dfbs.max_l()), 0);
engine.set(libint2::BraKet::xs_xx);
auto shell2bf = obs.shell2bf();
auto shell2bf_df = dfbs.shell2bf();
const auto& results = engine.results();
// Tensor<TensorType>::allocate(&ec, Zxy_tamm);
#if 1
//TODO: Screening?
auto compute_2body_fock_dfC_lambda = [&](const IndexVector& blockid) {
auto bi0 = blockid[0];
auto bi1 = blockid[1];
auto bi2 = blockid[2];
const TAMM_SIZE size = Zxy_tamm.block_size(blockid);
auto block_dims = Zxy_tamm.block_dims(blockid);
std::vector<TensorType> dbuf(size);
auto bd1 = block_dims[1];
auto bd2 = block_dims[2];
auto s0range_end = df_shell_tile_map[bi0];
decltype(s0range_end) s0range_start = 0l;
if (bi0>0) s0range_start = df_shell_tile_map[bi0-1]+1;
for (auto s0 = s0range_start; s0 <= s0range_end; ++s0) {
// auto n0 = dfbs[s0].size();
auto s1range_end = shell_tile_map[bi1];
decltype(s1range_end) s1range_start = 0l;
if (bi1>0) s1range_start = shell_tile_map[bi1-1]+1;
for (auto s1 = s1range_start; s1 <= s1range_end; ++s1) {
// auto n1 = shells[s1].size();
auto s2range_end = shell_tile_map[bi2];
decltype(s2range_end) s2range_start = 0l;
if (bi2>0) s2range_start = shell_tile_map[bi2-1]+1;
for (auto s2 = s2range_start; s2 <= s2range_end; ++s2) {
//// if (s2>s1) continue;
// auto n2 = shells[s2].size();
// auto n123 = n0*n1*n2;
// std::vector<TensorType> tbuf(n123);
engine.compute2<Operator::coulomb, BraKet::xs_xx, 0>(
dfbs[s0], unitshell, obs[s1], obs[s2]);
const auto* buf = results[0];
if (buf == nullptr) continue;
// std::copy(buf, buf + n123, tbuf.begin());
tamm::Tile curshelloffset_i = 0U;
tamm::Tile curshelloffset_j = 0U;
tamm::Tile curshelloffset_k = 0U;
for(auto x=s1range_start;x<s1;x++) curshelloffset_i += AO_tiles[x];
for(auto x=s2range_start;x<s2;x++) curshelloffset_j += AO_tiles[x];
for(auto x=s0range_start;x<s0;x++) curshelloffset_k += dfAO_tiles[x];
size_t c = 0;
auto dimi = curshelloffset_i + AO_tiles[s1];
auto dimj = curshelloffset_j + AO_tiles[s2];
auto dimk = curshelloffset_k + dfAO_tiles[s0];
for(auto k = curshelloffset_k; k < dimk; k++)
for(auto i = curshelloffset_i; i < dimi; i++)
for(auto j = curshelloffset_j; j < dimj; j++, c++)
dbuf[(k*bd1+i)*bd2+j] = buf[c]; //tbuf[c]
} //s2
} //s1
} //s0
Zxy_tamm.put(blockid,dbuf);
};
do_t1 = std::chrono::high_resolution_clock::now();
block_for(ec, Zxy_tamm(), compute_2body_fock_dfC_lambda);
do_t2 = std::chrono::high_resolution_clock::now();
do_time =
std::chrono::duration_cast<std::chrono::duration<double>>((do_t2 - do_t1)).count();
if(rank == 0 && debug) std::cout << "2BF-DFC:" << do_time << "s, ";
#endif
Tensor<TensorType> K_tamm{tdfAO, tdfAO}; //ndf,ndf
Tensor<TensorType>::allocate(&ec, K_tamm);
/*** ============================== ***/
/*** compute 2body-2index integrals ***/
/*** ============================== ***/
engine =
Engine(libint2::Operator::coulomb, dfbs.max_nprim(), dfbs.max_l(), 0);
engine.set(BraKet::xs_xs);
const auto& buf2 = engine.results();
auto compute_2body_2index_ints_lambda = [&](const IndexVector& blockid) {
auto bi0 = blockid[0];
auto bi1 = blockid[1];
const TAMM_SIZE size = K_tamm.block_size(blockid);
auto block_dims = K_tamm.block_dims(blockid);
std::vector<TensorType> dbuf(size);
auto bd1 = block_dims[1];
auto s1range_end = df_shell_tile_map[bi0];
decltype(s1range_end) s1range_start = 0l;
if (bi0>0) s1range_start = df_shell_tile_map[bi0-1]+1;
for (auto s1 = s1range_start; s1 <= s1range_end; ++s1) {
auto n1 = dfbs[s1].size();
auto s2range_end = df_shell_tile_map[bi1];
decltype(s2range_end) s2range_start = 0l;
if (bi1>0) s2range_start = df_shell_tile_map[bi1-1]+1;
for (auto s2 = s2range_start; s2 <= s2range_end; ++s2) {
// if (s2>s1) continue;
// if(s2>s1){ TODO: screening doesnt work - revisit
// auto s2spl = dfbs_shellpair_list[s2];
// if(std::find(s2spl.begin(),s2spl.end(),s1) == s2spl.end()) continue;
// }
// else{
// auto s2spl = dfbs_shellpair_list[s1];
// if(std::find(s2spl.begin(),s2spl.end(),s2) == s2spl.end()) continue;
// }
auto n2 = dfbs[s2].size();
std::vector<TensorType> tbuf(n1*n2);
engine.compute(dfbs[s1], dfbs[s2]);
if (buf2[0] == nullptr) continue;
Eigen::Map<const Matrix> buf_mat(buf2[0], n1, n2);
Eigen::Map<Matrix>(&tbuf[0],n1,n2) = buf_mat;
tamm::Tile curshelloffset_i = 0U;
tamm::Tile curshelloffset_j = 0U;
for(decltype(s1) x=s1range_start;x<s1;x++) curshelloffset_i += dfAO_tiles[x];
for(decltype(s2) x=s2range_start;x<s2;x++) curshelloffset_j += dfAO_tiles[x];
size_t c = 0;
auto dimi = curshelloffset_i + dfAO_tiles[s1];
auto dimj = curshelloffset_j + dfAO_tiles[s2];
for(auto i = curshelloffset_i; i < dimi; i++)
for(auto j = curshelloffset_j; j < dimj; j++, c++)
dbuf[i*bd1+j] = tbuf[c];
//TODO: not needed if screening works
// if (s1 != s2) // if s1 >= s2, copy {s1,s2} to the corresponding {s2,s1}
// // block, note the transpose!
// result.block(bf2, bf1, n2, n1) = buf_mat.transpose();
}
}
K_tamm.put(blockid,dbuf);
};
block_for(ec, K_tamm(), compute_2body_2index_ints_lambda);
Matrix V(ndf,ndf);
V.setZero();
tamm_to_eigen_tensor(K_tamm,V);
#if 1
auto ig1 = std::chrono::high_resolution_clock::now();
std::vector<TensorType> eps(ndf);
linalg::lapack::syevd( 'V', 'L', ndf, V.data(), ndf, eps.data() );
Matrix Vp = V;
for (size_t j=0; j<ndf; ++j) {
double tmp=1.0/sqrt(eps[j]);
linalg::blas::scal( ndf, tmp, Vp.data() + j*ndf, 1 );
}
Matrix ke(ndf,ndf);
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, ndf, ndf, ndf,
1, Vp.data(), ndf, V.data(), ndf, 0, ke.data(), ndf);
eigen_to_tamm_tensor(K_tamm,ke);
// Scheduler{ec}
// (k_tmp(d_mu,d_nu) = V_tamm(d_ku,d_mu) * V_tamm(d_ku,d_nu))
// (K_tamm(d_mu,d_nu) = eps_tamm(d_mu,d_ku) * k_tmp(d_ku,d_nu)) .execute();
//Tensor<TensorType>::deallocate(k_tmp, eps_tamm, V_tamm);
auto ig2 = std::chrono::high_resolution_clock::now();
auto igtime =
std::chrono::duration_cast<std::chrono::duration<double>>((ig2 - ig1)).count();
if(rank == 0 && debug) std::cout << "V^-1/2:" << igtime << "s, ";
#endif
// contract(1.0, Zxy, {1, 2, 3}, K, {1, 4}, 0.0, xyK, {2, 3, 4});
// Tensor3D xyK = Zxy.contract(K,aidx_00);
Scheduler{ec}
(xyK_tamm(mu,nu,d_nu) = Zxy_tamm(d_mu,mu,nu) * K_tamm(d_mu,d_nu)).execute();
Tensor<TensorType>::deallocate(K_tamm); //release memory Zxy_tamm
} // if (!is_3c_init)
Scheduler sch{ec};
auto ig1 = std::chrono::high_resolution_clock::now();
auto tig1 = ig1;
Tensor<TensorType> Jtmp_tamm{tdfAO}; //ndf
Tensor<TensorType> xiK_tamm{tAO,tdfCocc,tdfAO}; //n, nocc, ndf
Tensor<TensorType>& C_occ_tamm = ttensors.C_occ_tamm;
eigen_to_tamm_tensor(C_occ_tamm,etensors.C_occ);
auto ig2 = std::chrono::high_resolution_clock::now();
auto igtime =
std::chrono::duration_cast<std::chrono::duration<double>>((ig2 - ig1)).count();
ec.pg().barrier();
if(rank == 0 && debug) std::cout << " C_occ_tamm <- C_occ:" << igtime << "s, ";
ig1 = std::chrono::high_resolution_clock::now();
// contract(1.0, xyK, {1, 2, 3}, Co, {2, 4}, 0.0, xiK, {1, 4, 3});
sch.allocate(xiK_tamm,Jtmp_tamm)
(xiK_tamm(mu,dCocc_til,d_mu) = xyK_tamm(mu,nu,d_mu) * C_occ_tamm(nu, dCocc_til)).execute();
ig2 = std::chrono::high_resolution_clock::now();
igtime =
std::chrono::duration_cast<std::chrono::duration<double>>((ig2 - ig1)).count();
if(rank == 0 && debug) std::cout << " xiK_tamm:" << igtime << "s, ";
ig1 = std::chrono::high_resolution_clock::now();
// compute Coulomb
// contract(1.0, xiK, {1, 2, 3}, Co, {1, 2}, 0.0, Jtmp, {3});
// Jtmp = xiK.contract(Co,idx_0011);
sch(Jtmp_tamm(d_mu) = xiK_tamm(mu,dCocc_til,d_mu) * C_occ_tamm(mu,dCocc_til)).execute();
ig2 = std::chrono::high_resolution_clock::now();
igtime =
std::chrono::duration_cast<std::chrono::duration<double>>((ig2 - ig1)).count();
if(rank == 0 && debug) std::cout << " Jtmp_tamm:" << igtime << "s, ";
ig1 = std::chrono::high_resolution_clock::now();
// contract(1.0, xiK, {1, 2, 3}, xiK, {4, 2, 3}, 0.0, G, {1, 4});
// Tensor2D K_ret = xiK.contract(xiK,idx_1122);
// xiK.resize(0, 0, 0);
sch
(F1tmp1(mu,ku) += -1.0 * xiK_tamm(mu,dCocc_til,d_mu) * xiK_tamm(ku,dCocc_til,d_mu))
.deallocate(xiK_tamm).execute();
ig2 = std::chrono::high_resolution_clock::now();
igtime =
std::chrono::duration_cast<std::chrono::duration<double>>((ig2 - ig1)).count();
if(rank == 0 && debug) std::cout << " F1tmp1:" << igtime << "s, ";
ig1 = std::chrono::high_resolution_clock::now();
//contract(2.0, xyK, {1, 2, 3}, Jtmp, {3}, -1.0, G, {1, 2});
// Tensor2D J_ret = xyK.contract(Jtmp,aidx_20);
sch
(F1tmp1(mu,nu) += 2.0 * xyK_tamm(mu,nu,d_mu) * Jtmp_tamm(d_mu))
.deallocate(Jtmp_tamm).execute();
// (F1tmp1(mu,nu) = 2.0 * J_ret_tamm(mu,nu))
// (F1tmp1(mu,nu) += -1.0 * K_ret_tamm(mu,nu)).execute();
ig2 = std::chrono::high_resolution_clock::now();
igtime =
std::chrono::duration_cast<std::chrono::duration<double>>((ig2 - ig1)).count();
if(rank == 0 && debug) std::cout << " F1tmp1:" << igtime << "s, ";
auto tig2 = std::chrono::high_resolution_clock::now();
auto tigtime =
std::chrono::duration_cast<std::chrono::duration<double>>((tig2 - tig1)).count();
if(rank == 0 && debug) std::cout << "3c contractions:" << tigtime << "s, ";
#endif
} //end density fitting
}
template<typename TensorType>
void energy_diis(ExecutionContext& ec, TiledIndexSpace& tAO, int iter, int max_hist,
Tensor<TensorType> D, Tensor<TensorType> F, Tensor<TensorType> ehf_tamm,
std::vector<Tensor<TensorType>>& D_hist,
std::vector<Tensor<TensorType>>& fock_hist, std::vector<Tensor<TensorType>>& ehf_tamm_hist) {
tamm::Scheduler sch{ec};
auto rank = ec.pg().rank().value();
// if(rank == 0) cout << "contructing pulay matrix" << endl;
int64_t idim = std::min((int)D_hist.size(), max_hist);
if(idim < 2) return;
int64_t info = -1;
int64_t N = idim+1;
std::vector<double> X(N, 0.);
Tensor<TensorType> dhi_trace{};
auto [mu, nu] = tAO.labels<2>("all");
Tensor<TensorType>::allocate(&ec,dhi_trace);
// ----- Construct Pulay matrix -----
Matrix A = Matrix::Zero(idim + 1, idim + 1);
Tensor<TensorType> dFij{tAO, tAO};
Tensor<TensorType> dDij{tAO, tAO};
Tensor<TensorType>::allocate(&ec,dFij,dDij);
for(int i = 0; i < idim; i++) {
for(int j = i+1; j < idim; j++) {
sch
(dFij() = fock_hist[i]())
(dFij() -= fock_hist[j]())
(dDij() = D_hist[i]())
(dDij() -= D_hist[j]())
(dhi_trace() = dFij(nu,mu) * dDij(mu,nu))
.execute();
double dhi = get_scalar(dhi_trace);
A(i+1,j+1) = dhi;
}
}
Tensor<TensorType>::deallocate(dFij,dDij);
for(int i = 1; i <= idim; i++) {
for(int j = i+1; j <= idim; j++) {
A(j, i) = A(i, j);
}
}
for(int i = 1; i <= idim; i++) {
A(i, 0) = -1.0;
A(0, i) = -1.0;
}
// if(rank == 0) cout << std::setprecision(8) << "in ediis, A: " << endl << A << endl;
while(info!=0) {
N = idim+1;
std::vector<double> AC( N*(N+1)/2 );
std::vector<double> AF( AC.size() );
std::vector<double> B(N, 0.); B.front() = -1.0;
// if(rank == 0) cout << std::setprecision(8) << "in ediis, B ini: " << endl << B << endl;
for(int i = 1; i < N; i++) {
double dhi = get_scalar(ehf_tamm_hist[i-1]);
// if(rank==0) cout << "i,N,dhi: " << i << "," << N << "," << dhi << endl;
B[i] = dhi;
}
X.resize(N);
if(rank == 0) cout << std::setprecision(8) << "in ediis, B: " << endl << B << endl;
int ac_i = 0;
for(int i = 0; i <= idim; i++) {
for(int j = i; j <= idim; j++) {
AC[ac_i] = A(j, i); ac_i++;
}
}
double RCOND;
std::vector<int64_t> IPIV(N);
std::vector<double> BERR(1), FERR(1); // NRHS
info = linalg::lapack::spsvx( 'N', 'L', N, 1, AC.data(), AF.data(),
IPIV.data(), B.data(), N, X.data(), N, RCOND, FERR.data(), BERR.data() );
if(info!=0) {
// if(rank==0) cout << "<E-DIIS> Singularity in Pulay matrix. Density and Fock difference matrices removed." << endl;
fock_hist.erase(fock_hist.begin());
D_hist.erase(D_hist.begin());
idim--;
if(idim==1) return;
Matrix A_pl = A.block(2,2,idim,idim);
Matrix A_new = Matrix::Zero(idim + 1, idim + 1);
for(int i = 1; i <= idim; i++) {
A_new(i, 0) = -1.0;
A_new(0, i) = -1.0;
}
A_new.block(1,1,idim,idim) = A_pl;
A=A_new;
}
} //while
Tensor<TensorType>::deallocate(dhi_trace);
// if(rank == 0) cout << std::setprecision(8) << "in ediis, X: " << endl << X << endl;
std::vector<double> X_final(N);
//Reordering [0...N] -> [1...N,0] to match eigen's lu solve
X_final.back() = X.front();
std::copy ( X.begin()+1, X.end(), X_final.begin() );
if(rank == 0) cout << std::setprecision(8) << "in ediis, X_reordered: " << endl << X_final << endl;
sch
(D() = 0)
(F() = 0)
(ehf_tamm() = 0)
.execute();
for(int j = 0; j < idim; j++) {
sch
(D() += X_final[j] * D_hist[j]())
(F() += X_final[j] * fock_hist[j]())
(ehf_tamm() += X_final[j] * ehf_tamm_hist[j]())
;
}
sch.execute();
// if(rank == 0) cout << "end of ediis" << endl;
}
template<typename TensorType>
void diis(ExecutionContext& ec, TiledIndexSpace& tAO, Tensor<TensorType> D, Tensor<TensorType> F,
Tensor<TensorType> err_mat, int iter, int max_hist, int ndiis, const int n_lindep,
std::vector<Tensor<TensorType>>& diis_hist, std::vector<Tensor<TensorType>>& fock_hist) {
using Vector =
Eigen::Matrix<TensorType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
tamm::Scheduler sch{ec};
auto rank = ec.pg().rank().value();
if(ndiis > max_hist) {
auto maxe = 0;
if(!switch_diis) {
std::vector<TensorType> max_err(diis_hist.size());
for (size_t i=0; i<diis_hist.size(); i++) {
max_err[i] = tamm::norm(diis_hist[i]);
}
maxe = std::distance(max_err.begin(),
std::max_element(max_err.begin(),max_err.end()));
}
diis_hist.erase(diis_hist.begin()+maxe);
fock_hist.erase(fock_hist.begin()+maxe);
}
else{
if(ndiis == (int)(max_hist/2) && n_lindep > 1) {
diis_hist.clear();
fock_hist.clear();
}
}
Tensor<TensorType> Fcopy{tAO, tAO};
Tensor<TensorType>::allocate(&ec,Fcopy);
sch(Fcopy() = F()).execute();
diis_hist.push_back(err_mat);
fock_hist.push_back(Fcopy);
Matrix A;
Vector b;
int idim = std::min((int)diis_hist.size(), max_hist);
int64_t info = -1;
int64_t N = idim+1;
std::vector<TensorType> X;
// Tensor<TensorType> dhi_trans{tAO, tAO};
Tensor<TensorType> dhi_trace{};
auto [mu, nu] = tAO.labels<2>("all");
Tensor<TensorType>::allocate(&ec,dhi_trace); //dhi_trans
// ----- Construct Pulay matrix -----
A = Matrix::Zero(idim + 1, idim + 1);
for(int i = 0; i < idim; i++) {
for(int j = i; j < idim; j++) {
//A(i, j) = (diis_hist[i].transpose() * diis_hist[j]).trace();
sch(dhi_trace() = diis_hist[i](nu,mu) * diis_hist[j](mu,nu)).execute();
TensorType dhi = get_scalar(dhi_trace); //dhi_trace.trace();
A(i+1,j+1) = dhi;
}
}
for(int i = 1; i <= idim; i++) {
for(int j = i; j <= idim; j++) { A(j, i) = A(i, j); }
}
for(int i = 1; i <= idim; i++) {
A(i, 0) = -1.0;
A(0, i) = -1.0;
}
while(info!=0) {
if(idim==1) return;
N = idim+1;
std::vector<TensorType> AC( N*(N+1)/2 );
std::vector<TensorType> AF( AC.size() );
std::vector<TensorType> B(N, 0.); B.front() = -1.0;
X.resize(N);
int ac_i = 0;
for(int i = 0; i <= idim; i++) {
for(int j = i; j <= idim; j++) { AC[ac_i] = A(j, i); ac_i++; }
}
TensorType RCOND;
std::vector<int64_t> IPIV(N);
std::vector<TensorType> BERR(1), FERR(1); // NRHS
info = linalg::lapack::spsvx( 'N', 'L', N, 1, AC.data(), AF.data(),
IPIV.data(), B.data(), N, X.data(), N, RCOND, FERR.data(), BERR.data() );
if(info!=0) {
if(rank==0) cout << "<DIIS> Singularity in Pulay matrix detected." /*Error and Fock matrices removed." */ << endl;
diis_hist.erase(diis_hist.begin());
fock_hist.erase(fock_hist.begin());
idim--;
if(idim==1) return;
Matrix A_pl = A.block(2,2,idim,idim);
Matrix A_new = Matrix::Zero(idim + 1, idim + 1);
for(int i = 1; i <= idim; i++) {
A_new(i, 0) = -1.0;
A_new(0, i) = -1.0;
}
A_new.block(1,1,idim,idim) = A_pl;
A=A_new;
}
} //while
Tensor<TensorType>::deallocate(dhi_trace); //dhi_trans
std::vector<TensorType> X_final(N);
//Reordering [0...N] -> [1...N,0] to match eigen's lu solve
X_final.back() = X.front();
std::copy ( X.begin()+1, X.end(), X_final.begin() );
//if(rank==0 && scf_options.debug)
// std::cout << "diis weights sum, vector: " << std::setprecision(5) << std::accumulate(X.begin(),X.end(),0.0d) << std::endl << X << std::endl << X_final << std::endl;
sch(F() = 0).execute();
for(int j = 0; j < idim; j++) {
sch(F() += X_final[j] * fock_hist[j]());
}
// sch(F() += 0.5 * D()); //level shift
sch.execute();
}
#endif // TAMM_METHODS_HF_TAMM_COMMON_HPP_
| 40.683393 | 169 | 0.527194 | smferdous1 |
575bd60daeb03316072ee5c5d48fe88600650dd9 | 3,980 | cpp | C++ | include/hydro/vm/opcodes.cpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | include/hydro/vm/opcodes.cpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | include/hydro/vm/opcodes.cpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | //
// __ __ __
// / / / /__ __ ____/ /_____ ____
// / /_/ // / / // __ // ___// __ \
// / __ // /_/ // /_/ // / / /_/ /
// /_/ /_/ \__, / \__,_//_/ \____/
// /____/
//
// The Hydro Programming Language
//
#include "opcodes.hpp"
namespace hydro
{
std::string opcode_to_string(uint8_t opcode)
{
switch (opcode)
{
case pop_instr:
return "pop";
case swp_instr:
return "swap";
case dup_instr:
return "dup";
case ret_instr:
return "ret";
case hlt_instr:
return "hlt";
case closure_instr:
return "closure";
case jmp_instr:
return "jmp";
case brt_instr:
return "brt";
case brf_instr:
return "brf";
case push_instr:
return "push";
case inf_instr:
return "inf";
case nan_instr:
return "nan";
case true_instr:
return "true";
case false_instr:
return "false";
case null_instr:
return "nil";
case undefined_instr:
return "und";
case this_instr:
return "this";
case rload_instr:
return "loadclass";
case object_instr:
return "object";
case json_instr:
return "json";
case list_instr:
return "array";
case listpush:
return "arraypush";
case dict_instr:
return "dict";
case rgx_instr:
return "regex";
case xml_instr:
return "xml";
case att_instr:
return "attr";
case cmt_instr:
return "com";
case txt_instr:
return "txt";
case pin_instr:
return "pin";
case cdt_instr:
return "cdt";
case tup_instr:
return "tup";
case nup_instr:
return "nup";
case pos_instr:
return "pos";
case neg_instr:
return "neg";
case exp_instr:
return "exp";
case mul_instr:
return "mul";
case div_instr:
return "div";
case mod_instr:
return "mod";
case add_instr:
return "add";
case sub_instr:
return "sub";
case leq_instr:
return "leq";
case liq_instr:
return "liq";
case seq_instr:
return "seq";
case siq_instr:
return "siq";
case gt_instr:
return "gt";
case gte_instr:
return "gte";
case lt_instr:
return "lt";
case lte_instr:
return "lte";
case lnt_instr:
return "lnt";
case lnd_instr:
return "lnd";
case lor_instr:
return "lor";
case bnt_instr:
return "bnt";
case bnd_instr:
return "bnd";
case bor_instr:
return "bor";
case bxr_instr:
return "bxr";
case brs_instr:
return "brs";
case bls_instr:
return "bls";
case new_instr:
return "new";
case store_instr:
return "store";
case storex_instr:
return "storex";
case load_instr:
return "load";
case loadx_instr:
return "loadx";
case getindex_instr:
return "iload";
case setproperty_instr:
return "setproperty";
case setstatic_instr:
return "setstatic";
case setpropertyx_instr:
return "setpropertyx";
case setstaticx_instr:
return "setstaticx";
case getproperty_instr:
return "getproperty";
case getpropertyx_instr:
return "getpropertyx";
case gstore_instr:
return "gstore";
case gstorex_instr:
return "gstorex";
case gload_instr:
return "gload";
case gloadx_instr:
return "gloadx";
case setindex_instr:
return "istore";
case uload_instr:
return "upload";
case ustore_instr:
return "upstore";
case call_instr:
return "call";
case callx_instr:
return "callx";
case callproperty_instr:
return "callproperty";
case callpropertyx_instr:
return "callpropertyx";
case callstatic_instr:
return "callstatic";
case callindex_instr:
return "icall";
case ocall_instr:
return "ocall";
case chain_instr:
return "chain";
case chainx_instr:
return "chainx";
case typeof_instr:
return "typeof";
case classof_instr:
return "classof";
case instanceof_instr:
return "instanceof";
case is_instr:
return "is";
case as_instr:
return "as";
case define_instr:
return "define";
case definex_instr:
return "definex";
case fire_instr:
return "fire";
default:
{
// do nothing
break;
}
}
return "(unknown opcode)";
}
} // namespace hydro
| 18.256881 | 50 | 0.651256 | hydraate |
575cdf4e598f7fc44d408de41714626774f44a4a | 5,615 | cpp | C++ | test/burst/functional/each.cpp | izvolov/thrust | 399e12eed54131d731c4c5ef40512b17107bca56 | [
"BSL-1.0"
] | 85 | 2015-11-25T14:05:42.000Z | 2021-11-15T11:47:19.000Z | test/burst/functional/each.cpp | izvolov/burst | 399e12eed54131d731c4c5ef40512b17107bca56 | [
"BSL-1.0"
] | 147 | 2015-01-11T08:36:53.000Z | 2021-11-04T09:03:36.000Z | test/burst/functional/each.cpp | izvolov/thrust | 399e12eed54131d731c4c5ef40512b17107bca56 | [
"BSL-1.0"
] | 6 | 2016-06-02T17:28:26.000Z | 2020-04-05T11:16:16.000Z | #include <burst/algorithm/sum.hpp>
#include <burst/functional/each.hpp>
#include <burst/functional/only.hpp>
#include <burst/integer/intlog2.hpp>
#include <burst/tuple/make_tuple.hpp>
#include <utility/caller_dummies.hpp>
#include <utility/io/tuple.hpp>
#include <doctest/doctest.h>
#include <functional>
#include <string>
#include <tuple>
namespace // anonymous
{
struct doubler
{
explicit doubler (std::size_t & calls):
calls(calls)
{
}
template <typename T>
auto operator () (T t) const
{
++calls;
return t * t;
}
std::size_t & calls;
};
struct dummy
{
dummy ()
{
++instances_count;
}
dummy (const dummy &)
{
++instances_count;
}
dummy (dummy &&)
{
++instances_count;
}
~dummy ()
{
--instances_count;
}
static int instances_count;
};
int dummy::instances_count = 0;
} // namespace anonymous
TEST_SUITE("each")
{
TEST_CASE("Пробрасывает входные аргументы, преобразуя их с помощью заданной функции")
{
auto e = burst::each([] (auto x) {return x + x;}) | burst::make_tuple;
auto t = e(4, std::string("qwe"));
CHECK(t == std::make_tuple(8, "qweqwe"));
}
TEST_CASE("Может быть скомпонована с другим burst::each")
{
const auto square = [] (auto x) {return x * x;};
auto e = burst::each(square) | burst::each(square) | burst::sum;
auto r = e(1, 2, 3);
CHECK(r == 1 + 16 + 81);
}
TEST_CASE("Результат композиции может участвовать в новой композиции")
{
const auto square = [] (auto x) {return x * x;};
auto e = burst::each(square) | burst::sum | square;
auto r = e(1, 2, 3);
CHECK(r == (1 + 4 + 9) * (1 + 4 + 9));
}
TEST_CASE("Вызывает хранимую функцию на каждый входной элемент")
{
auto calls = std::size_t{0};
auto e = burst::each(doubler{calls}) | burst::make_tuple;
e(4, 'a', 3.14);
CHECK(calls == 3);
}
TEST_CASE("Каждая переданная функция хранится внутри созданного функционального объекта")
{
const auto old_instances_count = dummy::instances_count;
auto e = burst::each(dummy{}) | burst::each(dummy{});
static_cast<void>(e);
CHECK(dummy::instances_count == old_instances_count + 2);
}
TEST_CASE("Функции, переданные с помощью std::ref, не хранятся внутри")
{
auto d = dummy{};
const auto old_instances_count = dummy::instances_count;
auto e = burst::each(std::ref(d));
static_cast<void>(e);
CHECK(dummy::instances_count == old_instances_count);
}
TEST_CASE("Если созданный функциональный объект вызывается как const lvalue, то хранимый "
"функциональный объект вызывается так же")
{
auto calls = std::size_t{0};
const auto each =
burst::each(utility::const_lvalue_call_counter(calls)) | burst::make_tuple;
each(1, "qwe");
CHECK(calls == 2);
}
TEST_CASE("Если созданный функциональный объект вызывается как lvalue, то хранимый "
"функциональный объект вызывается так же")
{
auto calls = std::size_t{0};
auto each = burst::each(utility::lvalue_call_counter(calls)) | burst::make_tuple;
each(1, "qwe");
CHECK(calls == 2);
}
TEST_CASE("Если созданный функциональный объект вызывается как rvalue, то скомпонованный "
"функциональный объект вызывается как rvalue")
{
auto calls = std::size_t{0};
(burst::each([] (auto x) {return x + x;}) | utility::rvalue_call_counter(calls))(1, 2, 3);
CHECK(calls == 1);
}
TEST_CASE("Если созданный функциональный объект вызывается как rvalue, то хранимый "
"внутри each функциональный объект вызывается как lvalue")
{
auto calls = std::size_t{0};
(burst::each(utility::lvalue_call_counter(calls)) | burst::make_tuple)(1, "qwe");
CHECK(calls == 2);
}
TEST_CASE("Функции, переданные с помощью std::ref, всегда вызываются как lvalue")
{
auto calls = std::size_t{0};
auto c = utility::lvalue_call_counter(calls);
const auto each = burst::each(std::ref(c)) | burst::make_tuple;
each(1, "qwe");
CHECK(calls == 2);
}
TEST_CASE("Неизменяемые функции, переданные с помощью std::ref, всегда вызываются как "
"const lvalue")
{
auto calls = std::size_t{0};
const auto c = utility::const_lvalue_call_counter(calls);
const auto each = burst::each(std::ref(c)) | burst::make_tuple;
each(1, "qwe");
CHECK(calls == 2);
}
TEST_CASE("Может быть вычислена на этапе компиляции")
{
constexpr auto e = burst::each(&burst::intlog2<int>) | burst::make_tuple;
constexpr auto t = e(1, 256, 1024);
CHECK(t == std::make_tuple(0, 8, 10));
}
TEST_CASE("Компонуема с burst::only")
{
const auto cube = [] (auto x) {return x * x * x;};
const auto stringify = [] (auto x) {return std::to_string(x);};
const auto twice = [] (auto x) {return x + x;};
const auto size = [] (const auto & s) {return s.size();};
const auto f =
burst::only<1>(cube) |
burst::each(stringify) |
burst::only<0>(twice) |
burst::each(size) |
burst::sum;
CHECK(f(10, 20, 30) == 10);
}
}
| 27.257282 | 98 | 0.56919 | izvolov |
575fa2d9d35b946fe7d857ab35c666577962fdfa | 1,204 | cc | C++ | test/GridTest.cc | batman-nair/IRCIS | 9072f79cc8887ebf3b35cd4e977bf79686a94760 | [
"MIT"
] | 104 | 2020-02-13T19:12:30.000Z | 2022-01-29T21:33:35.000Z | test/GridTest.cc | batman-nair/IRCIS | 9072f79cc8887ebf3b35cd4e977bf79686a94760 | [
"MIT"
] | 6 | 2020-02-22T06:29:51.000Z | 2020-06-04T13:18:48.000Z | test/GridTest.cc | batman-nair/IRCIS | 9072f79cc8887ebf3b35cd4e977bf79686a94760 | [
"MIT"
] | 3 | 2020-02-16T11:58:26.000Z | 2020-10-15T02:38:39.000Z | #include <gtest/gtest.h>
#include <Grid.h>
namespace Ircis {
class GridTest : public ::testing::Test {
protected:
void SetUp() override {
}
// void TearDown() override {}
Grid file_test_{"hello_world.txt"};
};
TEST_F(GridTest, NullTest) {
try {
Grid test("nonexistent_text_file.txt");
FAIL() << "File read error not thrown";
} catch (Grid::GridFileNotFoundException& ex) {
ASSERT_STREQ("File nonexistent_text_file.txt not found", ex.what());
} catch (...) {
FAIL() << "Random exception occured while reading file";
}
}
TEST_F(GridTest, AccessTest) {
EXPECT_EQ('v', file_test_.get(0, 0));
EXPECT_EQ('W', file_test_.get(8, 1));
EXPECT_EQ('.', file_test_.get(24, 0));
EXPECT_EQ('.', file_test_.get(24, 3));
EXPECT_EQ(false, file_test_.is_inside(24, 4));
EXPECT_EQ(true, file_test_.is_inside(2, 2));
try {
file_test_.get(24, 4);
FAIL() << "Grid getter doesn't have bound checking";
} catch (Grid::GridOutOfBoundsException& ex) {
EXPECT_STREQ("Point (24, 4) is outside grid", ex.what());
} catch (...) {
FAIL() << "Random exception occured while calling getter";
}
}
}
| 27.363636 | 74 | 0.615449 | batman-nair |
576073545174c1e6ecb804ae99c6a9bda1337799 | 24,600 | cpp | C++ | src/IDTF/Helpers/ConverterHelpers.cpp | alemuntoni/u3d | 7907b907464a2db53dac03fdc137dcb46d447513 | [
"Apache-2.0"
] | 44 | 2016-05-06T00:47:11.000Z | 2022-02-11T06:51:37.000Z | src/IDTF/Helpers/ConverterHelpers.cpp | alemuntoni/u3d | 7907b907464a2db53dac03fdc137dcb46d447513 | [
"Apache-2.0"
] | 3 | 2016-06-27T12:37:31.000Z | 2021-03-24T12:39:48.000Z | src/IDTF/Helpers/ConverterHelpers.cpp | alemuntoni/u3d | 7907b907464a2db53dac03fdc137dcb46d447513 | [
"Apache-2.0"
] | 15 | 2016-02-28T11:08:30.000Z | 2021-06-01T03:32:01.000Z | //***************************************************************************
//
// Copyright (c) 1999 - 2006 Intel Corporation
//
// 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.
//
//***************************************************************************
/**
@file ConverterHelpers.cpp
This module defines ...
*/
//***************************************************************************
// Includes
//***************************************************************************
#include <string.h>
#include <stdlib.h>
#include <float.h>
#include <wchar.h>
#include "IFXResult.h"
#include "IFXDebug.h"
#include "IFXCheckX.h"
#include "ConverterOptions.h"
#include "IFXOSLoader.h"
extern FILE *stdmsg;
namespace U3D_IDTF
{
//***************************************************************************
// Defines
//***************************************************************************
//***************************************************************************
// Constants
//***************************************************************************
//***************************************************************************
// Enumerations
//***************************************************************************
//***************************************************************************
// Classes, structures and types
//***************************************************************************
//***************************************************************************
// Global data
//***************************************************************************
//***************************************************************************
// Local data
//***************************************************************************
//***************************************************************************
// Local function prototypes
//***************************************************************************
void DumpHelpInfo( wchar_t* argv[] );
void ParseParameterFileX( const wchar_t* fileName,
ConverterOptions* pConverterOptions,
FileOptions* pFileOptions );
//***************************************************************************
// Public methods
//***************************************************************************
//***************************************************************************
// Protected methods
//***************************************************************************
//***************************************************************************
// Private methods
//***************************************************************************
//***************************************************************************
// Global functions
//***************************************************************************
extern "C"
void SetDefaultOptionsX(
ConverterOptions* pConverterOptions,
FileOptions* pFileOptions )
{
IFXCHECKX( pFileOptions->outFile.Assign( L"Debugout.u3d" ) );
pFileOptions->exportOptions = IFXExportOptions(65535);
pFileOptions->profile = 0;
pFileOptions->scalingFactor = 1.0f;
pFileOptions->debugLevel = 0;
pConverterOptions->positionQuality = 1000;
pConverterOptions->texCoordQuality = 1000;
pConverterOptions->normalQuality = 1000;
pConverterOptions->diffuseQuality = 1000;
pConverterOptions->specularQuality = 1000;
pConverterOptions->geoQuality = 1000;
pConverterOptions->textureQuality = 100;
pConverterOptions->animQuality = 1000;
pConverterOptions->textureLimit = 0;
pConverterOptions->removeZeroAreaFaces = TRUE;
pConverterOptions->zeroAreaFaceTolerance = 100.0f * FLT_EPSILON;
pConverterOptions->excludeNormals = FALSE;
}
extern "C"
IFXRESULT ReadAndSetUserOptionsX( int argc, wchar_t* argv[],
ConverterOptions* pConverterOptions,
FileOptions* pFileOptions )
{
int argCount = 1;
if( 1 == argc )
{
DumpHelpInfo( argv );
return IFX_E_UNDEFINED;
}
//----------------------------------------------
// Now parse the rest of the input arguments
//----------------------------------------------
while( ( argCount < argc ) && ( NULL != argv[argCount] ) )
{
int value = 0;
// Set the output file name
if( 0 == wcscmp(L"-output", argv[argCount] ) ||
0 == wcscmp(L"-o", argv[argCount] ) )
{
argCount++;
IFXCHECKX( pFileOptions->outFile.Assign( (IFXCHAR*)argv[argCount] ) );
argCount++;
continue;
}
// Get the debug level
if( 0 == wcscmp(L"-debuglevel", argv[argCount] ) ||
0 == wcscmp(L"-dl", argv[argCount] ) )
{
argCount++;
swscanf( argv[argCount], L"%d", &value );
if( value <= 0)
pFileOptions->debugLevel = 0;
else if( value >= 1)
pFileOptions->debugLevel = 1;
argCount++;
continue;
}
// Get the profile identifier
if( 0 == wcscmp(L"-profile", argv[argCount] ) ||
0 == wcscmp(L"-p", argv[argCount] ) )
{
argCount++;
swscanf( argv[argCount], L"%d", &value );
if( value <= 0)
pFileOptions->profile = 0;
else if( value >= 14)
pFileOptions->profile = 14;
else
pFileOptions->profile = (U32)value;
argCount++;
continue;
}
// Get the scaling factor
if( 0 == wcscmp(L"-scalingfactor", argv[argCount] ) ||
0 == wcscmp(L"-sf", argv[argCount] ) )
{
argCount++;
F32 scalingFactor;
swscanf( argv[argCount], L"%f", &scalingFactor );
if( scalingFactor == 0.0f )
pFileOptions->scalingFactor = 1.0f;
else if( scalingFactor < 0.0f )
pFileOptions->scalingFactor = -scalingFactor;
else
pFileOptions->scalingFactor = scalingFactor;
argCount++;
continue;
}
// Get the position quality
if( 0 == wcscmp(L"-pquality", argv[argCount] ) ||
0 == wcscmp(L"-pq", argv[argCount] ) )
{
argCount++;
swscanf( argv[argCount], L"%d", &value );
if( value < 0)
pConverterOptions->positionQuality = 0;
else if( value > 1000)
pConverterOptions->positionQuality = 1000;
else
pConverterOptions->positionQuality = (U32)value;
argCount++;
continue;
}
// Get the texture coordinate quality
if( 0 == wcscmp(L"-tcquality", argv[argCount] ) ||
0 == wcscmp(L"-tcq", argv[argCount] ) )
{
argCount++;
swscanf( argv[argCount], L"%d", &value );
if( value < 0)
pConverterOptions->texCoordQuality = 0;
else if( value > 1000)
pConverterOptions->texCoordQuality = 1000;
else
pConverterOptions->texCoordQuality = (U32)value;
argCount++;
continue;
}
// Get the normal quality
if( 0 == wcscmp(L"-nquality", argv[argCount] ) ||
0 == wcscmp(L"-nq", argv[argCount] ) )
{
argCount++;
swscanf( argv[argCount], L"%d", &value );
if( value < 0)
pConverterOptions->normalQuality = 0;
else if( value > 1000)
pConverterOptions->normalQuality = 1000;
else
pConverterOptions->normalQuality = (U32)value;
argCount++;
continue;
}
// Get the diffuse color quality
if( 0 == wcscmp(L"-dcuality", argv[argCount] ) ||
0 == wcscmp(L"-dcq", argv[argCount] ) )
{
argCount++;
swscanf( argv[argCount], L"%d", &value );
if( value < 0)
pConverterOptions->diffuseQuality = 0;
else if( value > 1000)
pConverterOptions->diffuseQuality = 1000;
else
pConverterOptions->diffuseQuality = (U32)value;
argCount++;
continue;
}
// Get the specular color quality
if( 0 == wcscmp(L"-scquality", argv[argCount] ) ||
0 == wcscmp(L"-scq", argv[argCount] ) )
{
argCount++;
swscanf( argv[argCount], L"%d", &value );
if( value < 0)
pConverterOptions->specularQuality = 0;
else if( value > 1000)
pConverterOptions->specularQuality = 1000;
else
pConverterOptions->specularQuality = (U32)value;
argCount++;
continue;
}
// Get the geometry quality
if( 0 == wcscmp(L"-gquality", argv[argCount] ) ||
0 == wcscmp(L"-gq", argv[argCount] ) )
{
argCount++;
swscanf( argv[argCount], L"%d", &value );
if( value < 0)
pConverterOptions->geoQuality = 0;
else if( value > 1000)
pConverterOptions->geoQuality = 1000;
else
pConverterOptions->geoQuality = (U32)value;
argCount++;
continue;
}
// Get the texture quality
if( 0 == wcscmp(L"-tquality", argv[argCount] ) ||
0 == wcscmp(L"-tq", argv[argCount] ) )
{
argCount++;
swscanf( argv[argCount], L"%d", &value );
if( value < 0)
pConverterOptions->textureQuality = 0;
else if( value > 100)
pConverterOptions->textureQuality = 100;
else
pConverterOptions->textureQuality = (U32)value;
argCount++;
continue;
}
// Get the animation quality
if( 0 == wcscmp(L"-aquality", argv[argCount] ) ||
0 == wcscmp(L"-aq", argv[argCount] ) )
{
argCount++;
swscanf( argv[argCount], L"%d", &value );
if( value < 0)
pConverterOptions->animQuality = 0;
else if( value > 1000)
pConverterOptions->animQuality = 1000;
else
pConverterOptions->animQuality = (U32)value;
argCount++;
continue;
}
// Get the zero area faces removal mode
if( 0 == wcscmp(L"-removezerofaces", argv[argCount] ) ||
0 == wcscmp(L"-rzf", argv[argCount] ) )
{
argCount++;
swscanf( argv[argCount], L"%d", &value );
if( value <= 0 )
pConverterOptions->removeZeroAreaFaces = FALSE;
else
pConverterOptions->removeZeroAreaFaces = TRUE;
argCount++;
continue;
}
// Get the zero area face tolerance
if( 0 == wcscmp(L"-zerofacetolerance", argv[argCount] ) ||
0 == wcscmp(L"-zft", argv[argCount] ) )
{
argCount++;
F32 tolerance;
swscanf( argv[argCount], L"%f", &tolerance );
if( tolerance < 0 )
pConverterOptions->zeroAreaFaceTolerance = -tolerance;
else
pConverterOptions->zeroAreaFaceTolerance = tolerance;
argCount++;
continue;
}
// Get the normals exclusion mode
if( 0 == wcscmp(L"-excludenormals", argv[argCount] ) ||
0 == wcscmp(L"-en", argv[argCount] ) )
{
argCount++;
swscanf( argv[argCount], L"%d", &value );
if( value <= 0 )
pConverterOptions->excludeNormals = FALSE;
else
pConverterOptions->excludeNormals = TRUE;
argCount++;
continue;
}
// Get the export options
if( 0 == wcscmp(L"-exportoptions", argv[argCount] ) ||
0 == wcscmp(L"-eo", argv[argCount] ) )
{
int rawOption = 0;
argCount++;
swscanf( argv[argCount], L"%d", &rawOption );
if( rawOption < 0)
rawOption = 0;
if( rawOption > 65535)
rawOption = 65535;
pFileOptions->exportOptions = IFXExportOptions(
(rawOption & IFXEXPORT_GEOMETRY) |
(rawOption & IFXEXPORT_MATERIALS) |
(rawOption & IFXEXPORT_TEXTURES) |
(rawOption & IFXEXPORT_LIGHTS) |
(rawOption & IFXEXPORT_ANIMATION) |
(rawOption & IFXEXPORT_VIEWS) |
(rawOption & IFXEXPORT_FILEREFERENCES) |
(rawOption & IFXEXPORT_NODE_HIERARCHY) |
(rawOption & IFXEXPORT_SHADERS) );
argCount++;
continue;
}
// Get the texture size limit
if( 0 == wcscmp(L"-texturelimit", argv[argCount] ) ||
0 == wcscmp(L"-tl", argv[argCount] ) )
{
argCount++;
swscanf( argv[argCount], L"%d", &value );
if( value < 0)
pConverterOptions->textureLimit = 0;
else if( value > 4096)
pConverterOptions->textureLimit = 4096;
else
pConverterOptions->textureLimit = (U32)value;
argCount++;
continue;
}
// Read in an input file (multiple "-input" arguments, or none, are legal).
if( 0 == wcscmp(L"-input", argv[argCount] ) ||
0 == wcscmp(L"-i", argv[argCount] ) )
{
argCount++;
IFXCHECKX( pFileOptions->inFile.Assign( (IFXCHAR*)argv[argCount] ) );
argCount++;
continue;
}
// Read in an input file (multiple "-input" arguments, or none, are legal).
if( 0 == wcscmp(L"-pfile", argv[argCount] ) ||
0 == wcscmp(L"-pf", argv[argCount] ) )
{
argCount++;
ParseParameterFileX( argv[argCount], pConverterOptions, pFileOptions );
argCount++;
continue;
}
// Skip keywords that we do not recognize.
fwprintf(stdmsg, L"Did not recognize keyword = %ls\n", argv[argCount] );
argCount++;
}
const IFXCHAR* inFile = pFileOptions->inFile.Raw();
const IFXCHAR* outFile = pFileOptions->outFile.Raw();
// Note our settings.
fprintf(stdmsg,"\n");
fwprintf(stdmsg,L"Input file name = %ls\n", inFile );
fwprintf(stdmsg,L"Output file name = %ls\n", outFile );
fprintf(stdmsg,"Profile = %d\n", pFileOptions->profile);
fprintf(stdmsg,"Scaling factor = %f\n", pFileOptions->scalingFactor);
fprintf(stdmsg,"Debug level = %d\n", pFileOptions->debugLevel);
fprintf(stdmsg,"Position Quality = %d\n", pConverterOptions->positionQuality);
fprintf(stdmsg,"Texture Coordinate Quality = %d\n", pConverterOptions->texCoordQuality);
fprintf(stdmsg,"Normal Quality = %d\n", pConverterOptions->normalQuality);
fprintf(stdmsg,"Diffuse Color Quality = %d\n", pConverterOptions->diffuseQuality);
fprintf(stdmsg,"Specular Color Quality = %d\n", pConverterOptions->specularQuality);
fprintf(stdmsg,"Geometry Default Quality = %d\n", pConverterOptions->geoQuality);
fprintf(stdmsg,"Texture Quality = %d\n", pConverterOptions->textureQuality);
fprintf(stdmsg,"Animation Quality = %d\n", pConverterOptions->animQuality);
if( TRUE == pConverterOptions->removeZeroAreaFaces )
{
fprintf(stdmsg,"Zero Area Faces Removal = ENABLED\n");
fprintf(stdmsg,"Zero Area Face Tolerance = %f\n",
pConverterOptions->zeroAreaFaceTolerance);
}
else
fprintf(stdmsg,"Zero Area Faces Removal = DISABLED\n");
fprintf(stdmsg,"Exclude Normals = %s\n",
( pConverterOptions->excludeNormals == TRUE ? "TRUE" : "FALSE" ) );
fprintf(stdmsg,"Export Option Flags = %x\n", pFileOptions->exportOptions );
fprintf(stdmsg,"Texture size limit = %d\n", pConverterOptions->textureLimit);
fprintf(stdmsg,"\n");
return IFX_OK;
}
//***************************************************************************
// Local functions
//***************************************************************************
void DumpHelpInfo( wchar_t* argv[] )
{
fprintf(stdmsg,"\n\n");
fwprintf(stdmsg,L"%ls <arguments> <input_file_list>\n", argv[0]);
fprintf(stdmsg,"Note: argument order is important - what happens depends on\n");
fprintf(stdmsg," what arguments were already parsed\n");
fprintf(stdmsg,"\n");
fprintf(stdmsg,"Debugging:\n");
fprintf(stdmsg," -debuglevel <number>\n");
fprintf(stdmsg," 0 - no debug dump - silent conversion (default)\n");
fprintf(stdmsg," 1 - dump debug information to the file\n");
fprintf(stdmsg,"\n");
fprintf(stdmsg,"Export Options:\n");
fprintf(stdmsg," -profile or -p <number>: profile identifier\n");
fprintf(stdmsg," -scalingfactor or -sf <number>: units scaling factor\n");
fprintf(stdmsg," -pquality or -pq <number 0 to 1000>: mesh's position quality\n");
fprintf(stdmsg," -tcquality or -tcq <number 0 to 1000>: mesh's texture coordinate quality\n");
fprintf(stdmsg," -nquality or -nq <number 0 to 1000>: mesh's normal quality\n");
fprintf(stdmsg," -dcquality or -dcq <number 0 to 1000>: mesh's diffuse color quality\n");
fprintf(stdmsg," -scquality or -scq <number 0 to 1000>: mesh's specular color quality\n");
fprintf(stdmsg," -gquality or -gq <number 0 to 1000>: geometry default quality\n");
fprintf(stdmsg," -tquality or -tq <number 0 to 100>: texture quality\n");
fprintf(stdmsg," -aquality or -aq <number 0 to 1000>: animation quality\n");
fprintf(stdmsg," -removezerofaces or -rzf <number 0 or 1>: disable or enable zero area faces removal\n");
fprintf(stdmsg," -zerofacetolerance or -zft <positive float number>: zero area face tolerance\n");
fprintf(stdmsg," -excludenormals or -en <number 0 or 1>: disable or enable normals exclusion\n");
fprintf(stdmsg," -exportoptions or -eo <number>\n");
fprintf(stdmsg," 0 - do not export scene\n");
fprintf(stdmsg," 1 - export animation\n");
fprintf(stdmsg," 2 - export geometry\n");
fprintf(stdmsg," 4 - export lights\n");
fprintf(stdmsg," 8 - export materials\n");
fprintf(stdmsg," 16 - export node hierarchy\n");
fprintf(stdmsg," 32 - export shaders\n");
fprintf(stdmsg," 64 - export textures\n");
fprintf(stdmsg," 65535 - export everything (default)\n");
fprintf(stdmsg," -texturelimit or -tl <number>: limit textures to <number> by <number> in size (0 = None), up to 4096\n");
fprintf(stdmsg,"\n");
fprintf(stdmsg,"I/O:\n");
fprintf(stdmsg," -input <filename>\n");
fprintf(stdmsg," -output <filename>\n");
fprintf(stdmsg," -pfile <filename> - Read user options from a parameter file. Overrides command line params\n");
fprintf(stdmsg,"\n");
}
void ParseParameterFileX( const wchar_t* fileName,
ConverterOptions* pConverterOptions,
FileOptions* pFileOptions )
{
FILE* pFile = NULL;
IFXCHAR buffer[1024];
if( !pConverterOptions || !fileName )
{
fprintf(stdmsg,"Bad pointers passed to parser\n");
IFXCHECKX( IFX_E_INVALID_POINTER );
}
pFile = IFXOSFileOpen( fileName, L"r" );
if( !pFile )
{
fwprintf(stdmsg,L"Unable to open file %ls\n", fileName );
IFXCHECKX( IFX_E_INVALID_FILE );
}
while( fgets( (char*)&buffer, 1024, pFile ) )
{
IFXCHAR* pCommand = NULL;
IFXCHAR* pArgument = NULL;
IFXCHAR* pQuote = NULL;
int value = 0;
pQuote = wcschr(buffer, L'\"');
#ifdef WIN32
pCommand = wcstok(buffer, L" ");
if( pQuote )
pArgument = wcstok(NULL, L"\"");
else
pArgument = wcstok(NULL, L"\n");
#else
IFXCHAR* state;
pCommand = wcstok(buffer, L" ", &state);
if( pQuote )
pArgument = wcstok(NULL, L"\"", &state);
else
pArgument = wcstok(NULL, L"\n", &state);
#endif
// Set the output file name
if( 0 == wcscmp(L"-output", pCommand ) ||
0 == wcscmp(L"-o", pCommand ) )
{
IFXCHECKX( pFileOptions->outFile.Assign( pArgument ) );
continue;
}
// Get the debug level
if( 0 == wcscmp(L"-debuglevel", pCommand ) ||
0 == wcscmp(L"-dl", pCommand ) )
{
swscanf( pArgument, L"%d", &value );
if( value <= 0)
pFileOptions->debugLevel = 0;
else if( value >= 1)
pFileOptions->debugLevel = 1;
continue;
}
// Get the profile identifier
if( 0 == wcscmp(L"-profile", pCommand ) ||
0 == wcscmp(L"-p", pCommand ) )
{
swscanf( pArgument, L"%d", &value );
if( value <= 0)
pFileOptions->profile = 0;
else if( value >= 6)
pFileOptions->profile = 6;
continue;
}
// Get the scaling factor
if( 0 == wcscmp(L"-scalingfactor", pCommand ) ||
0 == wcscmp(L"-sf", pCommand ) )
{
F32 scalingFactor;
swscanf( pArgument, L"%f", &scalingFactor );
if( scalingFactor == 0.0f )
pFileOptions->scalingFactor = 1.0f;
else if( scalingFactor < 0.0f )
pFileOptions->scalingFactor = -scalingFactor;
else
pFileOptions->scalingFactor = scalingFactor;
continue;
}
// Get the position quality
if( 0 == wcscmp(L"-pquality", pCommand ) ||
0 == wcscmp(L"-pq", pCommand ) )
{
swscanf( pArgument, L"%d", &value);
if( value < 0)
pConverterOptions->positionQuality = 0;
else if( value > 1000)
pConverterOptions->positionQuality = 1000;
else
pConverterOptions->positionQuality = (U32)value;
continue;
}
// Get the texture coordinate quality
if( 0 == wcscmp(L"-tcquality", pCommand ) ||
0 == wcscmp(L"-tcq", pCommand ) )
{
swscanf( pArgument, L"%d", &value);
if( value < 0)
pConverterOptions->texCoordQuality = 0;
else if( value > 1000)
pConverterOptions->texCoordQuality = 1000;
else
pConverterOptions->texCoordQuality = (U32)value;
continue;
}
// Get the normal quality
if( 0 == wcscmp(L"-nquality", pCommand ) ||
0 == wcscmp(L"-nq", pCommand ) )
{
swscanf( pArgument, L"%d", &value );
if( value < 0)
pConverterOptions->normalQuality = 0;
else if( value > 1000)
pConverterOptions->normalQuality = 1000;
else
pConverterOptions->normalQuality = (U32)value;
continue;
}
// Get the diffuse color quality
if( 0 == wcscmp(L"-dcuality", pCommand ) ||
0 == wcscmp(L"-dcq", pCommand ) )
{
swscanf( pArgument, L"%d", &value );
if( value < 0)
pConverterOptions->diffuseQuality = 0;
else if( value > 1000)
pConverterOptions->diffuseQuality = 1000;
else
pConverterOptions->diffuseQuality = (U32)value;
continue;
}
// Get the specular color quality
if( 0 == wcscmp(L"-scquality", pCommand ) ||
0 == wcscmp(L"-scq", pCommand ) )
{
swscanf( pArgument, L"%d", &value );
if( value < 0)
pConverterOptions->specularQuality = 0;
else if( value > 1000)
pConverterOptions->specularQuality = 1000;
else
pConverterOptions->specularQuality = (U32)value;
continue;
}
// Get the geometry quality
if( 0 == wcscmp(L"-gquality", pCommand ) ||
0 == wcscmp(L"-gq", pCommand ) )
{
swscanf( pArgument, L"%d", &value );
if( value < 0)
pConverterOptions->geoQuality = 0;
else if( value > 1000)
pConverterOptions->geoQuality = 1000;
else
pConverterOptions->geoQuality = (U32)value;
continue;
}
// Get the texture quality
if( 0 == wcscmp(L"-tquality", pCommand ) ||
0 == wcscmp(L"-tq", pCommand ) )
{
swscanf( pArgument, L"%d", &value );
if( value < 0)
pConverterOptions->textureQuality = 0;
else if( value > 100)
pConverterOptions->textureQuality = 100;
else
pConverterOptions->textureQuality = (U32)value;
continue;
}
// Get the animation quality
if( 0 == wcscmp(L"-aquality", pCommand ) ||
0 == wcscmp(L"-aq", pCommand ) )
{
swscanf( pArgument, L"%d", &value );
if( value < 0)
pConverterOptions->animQuality = 0;
else if( value > 1000)
pConverterOptions->animQuality = 1000;
else
pConverterOptions->animQuality = (U32)value;
continue;
}
// Get the zero area faces removal
if( 0 == wcscmp(L"-removezerofaces", pCommand ) ||
0 == wcscmp(L"-rzf", pCommand ) )
{
swscanf( pArgument, L"%d", &value );
if( value <= 0 )
pConverterOptions->removeZeroAreaFaces = FALSE;
else
pConverterOptions->removeZeroAreaFaces = TRUE;
continue;
}
// Get the zero area face tolerance
if( 0 == wcscmp(L"-zerofacetolerance", pCommand ) ||
0 == wcscmp(L"-zft", pCommand ) )
{
F32 tolerance = 0.0f;
swscanf( pArgument, L"%f", &tolerance );
if( tolerance < 0 )
pConverterOptions->zeroAreaFaceTolerance = -tolerance;
else
pConverterOptions->zeroAreaFaceTolerance = tolerance;
continue;
}
// Get the normals exclusion mode
if( 0 == wcscmp(L"-excludenormals", pCommand ) ||
0 == wcscmp(L"-en", pCommand ) )
{
swscanf( pArgument, L"%d", &value );
if( value <= 0 )
pConverterOptions->excludeNormals = FALSE;
else
pConverterOptions->excludeNormals = TRUE;
continue;
}
// Get the export options
if( 0 == wcscmp(L"-exportoptions", pCommand ) ||
0 == wcscmp(L"-eo", pCommand ) )
{
int rawOption = 0;
swscanf( pArgument, L"%d", &rawOption );
if( rawOption < 0)
rawOption = 0;
if( rawOption > 65535)
rawOption = 65535;
pFileOptions->exportOptions = IFXExportOptions(
(rawOption & IFXEXPORT_GEOMETRY) |
(rawOption & IFXEXPORT_MATERIALS) |
(rawOption & IFXEXPORT_TEXTURES) |
(rawOption & IFXEXPORT_LIGHTS) |
(rawOption & IFXEXPORT_ANIMATION) |
(rawOption & IFXEXPORT_NODE_HIERARCHY) |
(rawOption & IFXEXPORT_SHADERS) );
continue;
}
// Get the texture size limit
if( 0 == wcscmp(L"-texturelimit", pCommand ) ||
0 == wcscmp(L"-tl", pCommand ) )
{
swscanf( pArgument, L"%d", &value );
if( value < 0)
pConverterOptions->textureLimit = 0;
else if( value > 4096)
pConverterOptions->textureLimit = 4096;
else
pConverterOptions->textureLimit = (U32)value;
continue;
}
// Read in an input file
if( 0 == wcscmp(L"-input", pCommand ) ||
0 == wcscmp(L"-i", pCommand ) )
{
IFXCHECKX( pFileOptions->inFile.Assign( pArgument ) );
continue;
}
// Skip keywords that we do not recognize.
fwprintf(stdmsg,L"Did not recognize keyword = %ls\n", pCommand);
} // While lines in parameter file
fclose( pFile );
}
}
| 29.74607 | 126 | 0.585976 | alemuntoni |
5762948219dec61ac231c532bd1f7b2bb317f6bd | 4,600 | cpp | C++ | examples/google-code-jam/morbidel/qualify_C.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | examples/google-code-jam/morbidel/qualify_C.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | examples/google-code-jam/morbidel/qualify_C.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | /*
* Google Code Jam 2017
* Qualification Round - Problem C - Bathroom Stalls
*/
#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <algorithm>
#include <queue>
#include <iostream>
#include <sstream>
#include <functional>
#include <deque>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <utility>
#define MIN(a, b) ((a) > (b) ? (b) : (a))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define ABS(x) ((x) > 0 ? (x) : -(x))
#define SGN(x) (((x) == 0) ? 0 : ((x) > 0 ? 1 : -1))
#define SZ(a) ((a).size())
#define FORN(_i, _n) for (int (_i) = 0; (_i) < (_n); ++(_i))
#define FOR_(_i, _a, _b) for (int (_i) = (_a); (_i) <= (_b); ++(_i))
#define ALL(stl) (stl).begin(), (stl).end()
#define INF 1000000000
typedef unsigned long long LLU;
using namespace std;
#define OFFICIAL 1
#if OFFICIAL
#define INPUT_FILE "C-large.in"
#define OUTPUT_FILE "C-large.out"
#else
#define INPUT_FILE "input.txt"
#define OUTPUT_FILE "output.txt"
#endif
LLU N, K;
vector<int> V;
map<LLU, LLU, greater<LLU> > Current, Next;
void PreGen()
{
// stuff which executes only once, before reading the input
}
void Simulate(int& maxLR, int& minLR)
{
int the_place = -1;
int max_minLR = 0 , max_maxLR = 0;
for (int i = 0; i < V.size(); ++i)
if (V[i] == 0)
{
int l = 0, r = 0;
for (int j = i - 1; j >= 0; --j)
if (V[j] == 1) break;
else
{
++l;
}
for (int j = i + 1; j < V.size(); ++j)
if (V[j] == 1) break;
else
{
++r;
}
if (the_place == -1)
{
the_place = i;
max_minLR = MIN(l, r);
max_maxLR = MAX(l, r);
}
else if (MIN(l, r) > max_minLR)
{
max_minLR = MIN(l, r);
max_maxLR = MAX(l, r);
the_place = i;
}
else if (MIN(l, r) == max_minLR && MAX(l, r) > max_maxLR)
{
the_place = i;
max_maxLR = MAX(l, r);
}
}
if (the_place == -1)
{
printf("no place found !!!\n");
}
else
{
V[the_place] = 1;
maxLR = max_maxLR;
minLR = max_minLR;
}
printf("%d %d\n", maxLR, minLR);
for (int i = 0; i < V.size(); ++i)
printf("%d", V[i]);
printf("\n");
}
int Solve()
{
// stuff which is executed for each input
// expects the output to be printed out
scanf("%llu %llu", &N, &K);
LLU minLR, maxLR;
/*V.clear();
V.resize(N + 2, 0);
V[0] = V[N + 1] = 1;
for (int i = 0; i < K; ++i)
{
Simulate(maxLR, minLR);
}*/
Next.clear();
Current.clear();
Current.insert(make_pair(N, 1));
LLU currK = 0;
while (currK < K)
{
for (map<LLU, LLU, greater<LLU> >::const_iterator it = Current.begin(); it != Current.end(); ++it)
{
LLU hole = it->first;
LLU count = it->second;
// before splitting current hole, we put some guys to pee there, for which the answer (max, min) is the same
currK += count;
// hole is it->first size, so max is the bigger half, min is the smaller half
maxLR = MAX(hole / 2, hole - hole / 2 - 1);
minLR = MIN(hole / 2, hole - hole / 2 - 1);
// we reached at least K iterations, exit
if (currK >= K) break;
LLU group = hole / 2;
if (group > 0)
Next[group] += count;
group = hole - group - 1; // 1 disappears as the guy wants to pee
if (group > 0)
Next[group] += count;
// copy 1-holes as they are
if (hole == 1)
{
Next[hole] += count;
}
}
Current.clear();
Current = Next;
Next.clear();
// when we have only 1-holes, break -> we can fill them in any order, and the result for each of these guys is (0, 0)
if (Current.size() == 1 && Current.begin()->first == 1)
{
break;
}
}
if (currK < K)
{
// only 1-holes, answer is (0, 0)
maxLR = minLR = 0;
}
printf("%lld %lld", maxLR, minLR);
return 0;
}
int main()
{
freopen(INPUT_FILE, "rt", stdin);
#if OFFICIAL
freopen(OUTPUT_FILE, "wt", stdout);
#endif
PreGen();
int T, nt;
scanf("%d\n", &T);
for (nt = 1; nt <= T; ++nt)
{
printf("Case #%d: ", nt);
if (Solve())
{
}
printf("\n");
}
return 0;
} | 21.004566 | 122 | 0.481957 | rbenic-fer |
5767011d207c350e387968f3a0a2de6438c45c48 | 76 | cc | C++ | Ex02_Factory_Method/src/3_factory_method_advanced/java.cc | kks32/cpp-software-development | 3ce0c66d812d9a166191a1007111501615c97a2c | [
"MIT"
] | 64 | 2015-01-18T17:53:56.000Z | 2022-03-06T11:37:25.000Z | Ex02_Factory_Method/src/3_factory_method_advanced/java.cc | kks32/cpp-software-development | 3ce0c66d812d9a166191a1007111501615c97a2c | [
"MIT"
] | null | null | null | Ex02_Factory_Method/src/3_factory_method_advanced/java.cc | kks32/cpp-software-development | 3ce0c66d812d9a166191a1007111501615c97a2c | [
"MIT"
] | 24 | 2015-03-22T02:00:10.000Z | 2022-01-18T13:17:26.000Z | #include "java.h"
#include "factory.h"
REGISTER_CLASS("Java", Java);
| 12.666667 | 30 | 0.644737 | kks32 |
5767211b54e310e51da10b711ab450bd1abd8947 | 6,769 | cpp | C++ | cpp/src/datacentric/dc/platform/data_source/mongo/mongo_data_source_base_data.cpp | datacentricorg/datacentric | b9e2dedfac35759ea09bb5653095daba5861512e | [
"Apache-2.0"
] | 1 | 2019-08-08T01:27:47.000Z | 2019-08-08T01:27:47.000Z | cpp/src/datacentric/dc/platform/data_source/mongo/mongo_data_source_base_data.cpp | datacentricorg/datacentric | b9e2dedfac35759ea09bb5653095daba5861512e | [
"Apache-2.0"
] | null | null | null | cpp/src/datacentric/dc/platform/data_source/mongo/mongo_data_source_base_data.cpp | datacentricorg/datacentric | b9e2dedfac35759ea09bb5653095daba5861512e | [
"Apache-2.0"
] | null | null | null | /*
Copyright (C) 2013-present The DataCentric Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <dc/precompiled.hpp>
#include <dc/implement.hpp>
#include <dc/platform/data_source/mongo/mongo_data_source_base_data.hpp>
#include <dc/platform/data_source/mongo/MongoServerData.hpp>
#include <dc/platform/context/context_base.hpp>
#include <mongocxx/instance.hpp>
namespace dc
{
dot::list<char> mongo_data_source_base_data_impl::prohibitedDbNameSymbols_ = dot::make_list<char>({ '/', '\\', '.', ' ', '"', '$', '*', '<', '>', ':', '|', '?' });
int mongo_data_source_base_data_impl::maxDbNameLength_ = 64;
void mongo_data_source_base_data_impl::Init(context_base context)
{
static mongocxx::instance instance{};
// Initialize the base class
data_source_data_impl::Init(context);
// Configures serialization conventions for standard types
if (db_name == nullptr) throw dot::exception("DB key is null or empty.");
if (db_name->instance_type == instance_type::empty) throw dot::exception("DB instance type is not specified.");
if (dot::string::is_null_or_empty(db_name->instance_name)) throw dot::exception("DB instance name is not specified.");
if (dot::string::is_null_or_empty(db_name->env_name)) throw dot::exception("DB environment name is not specified.");
// The name is the database key in the standard semicolon delimited format.
dbName_ = db_name->to_string();
instance_type_ = db_name->instance_type;
// Perform additional validation for restricted characters and database name length.
if (dbName_->index_of_any(prohibitedDbNameSymbols_) != -1)
throw dot::exception(
dot::string::format("MongoDB database name {0} contains a space or another ", dbName_) +
"prohibited character from the following list: /\\.\"$*<>:|?");
if (dbName_->length() > maxDbNameLength_)
throw dot::exception(
dot::string::format("MongoDB database name {0} exceeds the maximum length of 64 characters.", dbName_));
// Get client interface using the server
dot::string dbUri = db_server->Load(Context).as<MongoServerData>()->GetMongoServerUri();
client_ = mongocxx::client{ mongocxx::uri(*dbUri) };
// Get database interface using the client and database name
db_ = client_[*dbName_];
}
dot::object_id mongo_data_source_base_data_impl::create_ordered_object_id()
{
check_not_read_only();
// Generate dot::object_id and check that it is later
// than the previous generated dot::object_id
dot::object_id result = dot::object_id::generate_new_id();
int retryCounter = 0;
while (result.oid() <= prev_object_id_.oid())
{
// Getting inside the while loop will be very rare as this would
// require the increment to roll from max int to min int within
// the same second, therefore it is a good idea to log the event
if (retryCounter++ == 0) std::cerr << "MongoDB generated dot::object_id not in increasing order, retrying." << std::endl;
// If new dot::object_id is not strictly greater than the previous one,
// keep generating new dot::object_ids until it changes
result = dot::object_id::generate_new_id();
}
// Report the number of retries
if (retryCounter != 0)
{
std::cerr << *dot::string::format("Generated dot::object_id in increasing order after {0} retries.", retryCounter);
}
// Update previous dot::object_id and return
prev_object_id_ = result;
return result;
}
void mongo_data_source_base_data_impl::delete_db()
{
check_not_read_only();
// Do not delete (drop) the database this class did not create
if (client_ && db_)
{
// As an extra safety measure, this method will delete
// the database only if the first token of its name is
// TEST or DEV.
//
// Use other tokens such as UAT or PROD to protect the
// database from accidental deletion
if (instance_type_ == instance_type::DEV
|| instance_type_ == instance_type::USER
|| instance_type_ == instance_type::TEST)
{
// The name is the database key in the standard
// semicolon delimited format. However this method
// performs additional validation for restricted
// characters and database name length.
client_[*dbName_].drop();
}
else
{
throw dot::exception(
dot::string::format("As an extra safety measure, database {0} cannot be ", dbName_) +
"dropped because this operation is not permitted for database " +
dot::string::format("instance type {0}.", instance_type_.to_string()));
}
}
}
mongocxx::collection mongo_data_source_base_data_impl::GetCollection(dot::type_t dataType)
{
dot::type_t curr = dataType;
while (curr->name != "Record" && curr->name != "Key")
{
curr = curr->base_type();
if (curr.is_empty())
throw dot::exception(dot::string::format("Couldn't detect collection name for type {0}", dataType->name));
}
dot::string typeName = curr->get_generic_arguments()[0]->name;
return GetCollection(typeName);
}
mongocxx::collection mongo_data_source_base_data_impl::GetCollection(dot::string typeName)
{
int prefixSize = 0; //! TODO change to ClassInfo.MappedName
dot::string collectionName;
if (typeName->ends_with("Data"))
collectionName = typeName->substring(prefixSize, typeName->length() - std::string("Data").length() - prefixSize);
else if (typeName->ends_with("Key"))
collectionName = typeName->substring(prefixSize, typeName->length() - std::string("Key").length() - prefixSize);
else throw dot::exception("Unknown type");
return db_[*collectionName];
}
}
| 43.670968 | 167 | 0.635692 | datacentricorg |
5771fd768792e98746f4aa037bb9ee4f86e05fe9 | 334 | cpp | C++ | resource/cpp/primer-ppt/class3_code/14_this指针3.cpp | yuenshome/yuenshome.github.io | 5d9c4f27fc58d62dde1eb90b49affff51417e22a | [
"MIT"
] | 73 | 2018-11-29T08:15:58.000Z | 2022-02-14T08:45:24.000Z | resource/cpp/primer-ppt/class3_code/14_this指针3.cpp | yuenshome/yuenshome.github.io | 5d9c4f27fc58d62dde1eb90b49affff51417e22a | [
"MIT"
] | 136 | 2017-11-04T07:51:31.000Z | 2021-12-24T11:10:52.000Z | resource/cpp/primer-ppt/class3_code/14_this指针3.cpp | yuenshome/yuenshome.github.io | 5d9c4f27fc58d62dde1eb90b49affff51417e22a | [
"MIT"
] | 15 | 2019-02-28T11:51:36.000Z | 2022-02-14T08:45:26.000Z | #include <iostream>
#include <string.h>
using namespace std;
class A {
public:
A(int num) { this->num = num; }
A& add(int n) { num += n; return *this; }
int get_num()const { return num; }
private:
int num;
};
int main() {
A a1(1);
a1.add(2).add(3).add(4).add(5);
cout << a1.get_num() << endl; //15
return 0;
} | 19.647059 | 43 | 0.565868 | yuenshome |
57765801a2295b3a3434e8c40cd7154492aa22e7 | 431 | cpp | C++ | products/ROCKET-STATS/rstats_modules/generic_random_numbers/src/UIRStatsGRN.cpp | cbtek/RStats2017 | e383416ee52784be6486b9a2e5f517fbfaf8a416 | [
"MIT"
] | null | null | null | products/ROCKET-STATS/rstats_modules/generic_random_numbers/src/UIRStatsGRN.cpp | cbtek/RStats2017 | e383416ee52784be6486b9a2e5f517fbfaf8a416 | [
"MIT"
] | 3 | 2017-07-12T17:10:52.000Z | 2017-09-21T19:06:59.000Z | products/ROCKET-STATS/rstats_modules/generic_random_numbers/src/UIRStatsGRN.cpp | cbtek/RStats2017 | e383416ee52784be6486b9a2e5f517fbfaf8a416 | [
"MIT"
] | null | null | null | /*
UIRStatsGRN.cpp
*/
//UIRStatsGRN.cpp generated by cbtek on 06-03-2017 at 06:54:36 PM
#include "UIRStatsGRN.h"
#include "ui_UIRStatsGRN.h"
namespace cbtek {
namespace rocketstats {
namespace modules {
namespace grn {
UIRStatsGRN::UIRStatsGRN(QWidget *parent) :
QMainWindow(parent),
m_ui(new Ui_UIRStatsGRN)
{
m_ui->setupUi(this);
}
UIRStatsGRN::~UIRStatsGRN()
{
delete m_ui;
}
}}}}//end namespace
| 14.366667 | 65 | 0.693735 | cbtek |
577f5458af6a0232d234a26b6030cc1ea9fa26ff | 3,890 | cc | C++ | Encoding.cc | Ratismal/phosg | df1169fcd67fa854d2d136f0e53565f4d7a827b0 | [
"MIT"
] | null | null | null | Encoding.cc | Ratismal/phosg | df1169fcd67fa854d2d136f0e53565f4d7a827b0 | [
"MIT"
] | null | null | null | Encoding.cc | Ratismal/phosg | df1169fcd67fa854d2d136f0e53565f4d7a827b0 | [
"MIT"
] | null | null | null | #include "Encoding.hh"
#include <stdexcept>
using namespace std;
const char* DEFAULT_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const char* URLSAFE_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
string base64_encode(const void* vdata, size_t size, const char* alphabet) {
const uint8_t* data = reinterpret_cast<const uint8_t*>(vdata);
if (!alphabet) {
alphabet = DEFAULT_ALPHABET;
}
string ret;
// encode blocks of 3 bytes first
size_t end_offset = (size / 3) * 3;
for (size_t offset = 0; offset < end_offset; offset += 3) {
// aaaaaabb bbbbcccc ccdddddd
uint8_t c1 = data[offset];
uint8_t c2 = data[offset + 1];
uint8_t c3 = data[offset + 2];
ret.push_back(alphabet[(c1 >> 2) & 0x3F]);
ret.push_back(alphabet[((c1 << 4) & 0x30) | ((c2 >> 4) & 0x0F)]);
ret.push_back(alphabet[((c2 << 2) & 0x3C) | ((c3 >> 6) & 0x03)]);
ret.push_back(alphabet[c3 & 0x3F]);
}
if (size - end_offset == 2) {
// aaaaaabb bbbbcccc ========
uint8_t c1 = data[end_offset];
uint8_t c2 = data[end_offset + 1];
ret.push_back(alphabet[(c1 >> 2) & 0x3F]);
ret.push_back(alphabet[((c1 << 4) & 0x30) | ((c2 >> 4) & 0x0F)]);
ret.push_back(alphabet[((c2 << 2) & 0x3C)]);
ret.push_back('=');
} else if (size - end_offset == 1) {
// aaaaaabb ======== ========
uint8_t c1 = data[end_offset];
ret.push_back(alphabet[(c1 >> 2) & 0x3F]);
ret.push_back(alphabet[((c1 << 4) & 0x30)]);
ret.push_back('=');
ret.push_back('=');
}
return ret;
}
string base64_encode(const string& data, const char* alphabet) {
return base64_encode(data.data(), data.size(), alphabet);
}
string base64_decode(const void* vdata, size_t size, const char* alphabet) {
const uint8_t* data = reinterpret_cast<const uint8_t*>(vdata);
if (!alphabet) {
alphabet = DEFAULT_ALPHABET;
}
// the length must be a multiple of 4
if (size & 3) {
throw invalid_argument("size must be a multiple of 4 bytes");
}
// compute the inverse alphabet for easier decoding
// TODO: make this not happen every time, at least for the default alphabets
string inverse_alphabet(0x100, 0xFF);
for (size_t x = 0; x < 0x40; x++) {
inverse_alphabet[alphabet[x]] = x;
}
inverse_alphabet['='] = 0x80;
// decode blocks of 4 bytes first
string ret;
size_t end_offset = size & (~3);
for (size_t offset = 0; offset < end_offset; offset += 4) {
// aaaaaabb bbbbcccc ccdddddd
uint8_t c1 = inverse_alphabet[data[offset]];
uint8_t c2 = inverse_alphabet[data[offset + 1]];
uint8_t c3 = inverse_alphabet[data[offset + 2]];
uint8_t c4 = inverse_alphabet[data[offset + 3]];
// TODO: this is pretty ugly; clean it up
if (c4 == 0x80) {
if (offset != end_offset - 4) {
throw invalid_argument("string contains padding not at the end");
}
if (c3 == 0x80) {
if ((c1 >= 0x40) || (c2 >= 0x40)) {
throw invalid_argument("string contains non-base64 characters");
}
ret.push_back(((c1 << 2) & 0xFC) | ((c2 >> 4) & 0x03));
} else {
if ((c1 >= 0x40) || (c2 >= 0x40) || (c2 >= 0x40)) {
throw invalid_argument("string contains non-base64 characters");
}
ret.push_back(((c1 << 2) & 0xFC) | ((c2 >> 4) & 0x03));
ret.push_back(((c2 << 4) & 0xF0) | ((c3 >> 2) & 0x0F));
}
} else {
if ((c1 >= 0x40) || (c2 >= 0x40) || (c3 >= 0x40) || (c4 >= 0x40)) {
throw invalid_argument("string contains non-base64 characters");
}
ret.push_back((c1 << 2) | ((c2 >> 4) & 0x03));
ret.push_back((c2 << 4) | ((c3 >> 2) & 0x0F));
ret.push_back((c3 << 6) | c4);
}
}
return ret;
}
string base64_decode(const string& data, const char* alphabet) {
return base64_decode(data.data(), data.size(), alphabet);
} | 32.689076 | 98 | 0.604113 | Ratismal |
578399706fdcc3bae08c4743eaf4c97f412795de | 1,811 | hpp | C++ | ql/experimental/models/all.hpp | universe1987/QuantLib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 4 | 2016-03-28T15:05:23.000Z | 2020-02-17T23:05:57.000Z | ql/experimental/models/all.hpp | universe1987/QuantLib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 1 | 2015-02-02T20:32:43.000Z | 2015-02-02T20:32:43.000Z | ql/experimental/models/all.hpp | pcaspers/quantlib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 10 | 2015-01-26T14:50:24.000Z | 2015-10-23T07:41:30.000Z | /* This file is automatically generated; do not edit. */
/* Add the files to be included into Makefile.am instead. */
#include <ql/experimental/models/adjusterhelper.hpp>
#include <ql/experimental/models/betaeta.hpp>
#include <ql/experimental/models/betaetacore.hpp>
#include <ql/experimental/models/betaetaswaptionengine.hpp>
#include <ql/experimental/models/cclgm.hpp>
#include <ql/experimental/models/cclgm1.hpp>
#include <ql/experimental/models/cclgmanalyticfxoptionengine.hpp>
#include <ql/experimental/models/cclgmparametrization.hpp>
#include <ql/experimental/models/cclgmpiecewise.hpp>
#include <ql/experimental/models/cclgmprocess.hpp>
#include <ql/experimental/models/fxoptionhelper.hpp>
#include <ql/experimental/models/gsrprocess_riskneutral.hpp>
#include <ql/experimental/models/lgm.hpp>
#include <ql/experimental/models/lgm1.hpp>
#include <ql/experimental/models/lgmfxparametrization.hpp>
#include <ql/experimental/models/lgmfxpiecewisesigma.hpp>
#include <ql/experimental/models/lgmparametrization.hpp>
#include <ql/experimental/models/lgmstateprocess.hpp>
#include <ql/experimental/models/lgmpiecewisealphaconstantkappa.hpp>
#include <ql/experimental/models/lgmswaptionengine_ad.hpp>
#include <ql/experimental/models/longstaffschwartzproxypathpricer.hpp>
#include <ql/experimental/models/mcgaussian1dnonstandardswaptionengine.hpp>
#include <ql/experimental/models/proxynonstandardswaptionengine.hpp>
#include <ql/experimental/models/qg1dlinearmodel.hpp>
#include <ql/experimental/models/qg1dlocalvolmodel.hpp>
#include <ql/experimental/models/quadraticlfm.hpp>
#include <ql/experimental/models/sbsmilesection.hpp>
#include <ql/experimental/models/splinedensitysmilesection.hpp>
#include <ql/experimental/models/hestonslvfdmmodel.hpp>
#include <ql/experimental/models/hestonslvmcmodel.hpp>
| 51.742857 | 75 | 0.829376 | universe1987 |
5788d7682f790720eefff879dc05cee774b6d34c | 2,109 | hpp | C++ | algo/hash.hpp | Better-Idea/Mix-C | 71f34a5fc8c17a516cf99bc397289d046364a82e | [
"Apache-2.0"
] | 41 | 2019-09-24T02:17:34.000Z | 2022-01-18T03:14:46.000Z | algo/hash.hpp | Better-Idea/Mix-C | 71f34a5fc8c17a516cf99bc397289d046364a82e | [
"Apache-2.0"
] | 2 | 2019-11-04T09:01:40.000Z | 2020-06-23T03:03:38.000Z | algo/hash.hpp | Better-Idea/Mix-C | 71f34a5fc8c17a516cf99bc397289d046364a82e | [
"Apache-2.0"
] | 8 | 2019-09-24T02:17:35.000Z | 2021-09-11T00:21:03.000Z | /* 模块:hash
* 类型:函数单体
* 功能:得到一个对象的 hash 值
* 用法:
* TODO ===========================================================
*
* 注意:
* - 不同字节数的类型即使值相同也会具有不同的 hash 值
* - hash(u08('a')) != hash(u16('a'))
*/
#ifndef xpack_algo_hash
#define xpack_algo_hash
#pragma push_macro("xuser")
#undef xuser
#define xuser mixc::algo_hash::inc
#include"instruction/ring_shift_left.hpp"
#include"instruction/count_of_set.hpp"
#include"interface/seqptr.hpp"
#include"macro/xexport.hpp"
#include"macro/xref.hpp"
#include"meta/is_origin_array.hpp"
#include"meta/is_same.hpp"
#pragma pop_macro("xuser")
namespace mixc::algo_hash::origin{
/* 函数:底层哈希函数
* 参数:
* - mem 为要 hash 的对象首地址
* - blocks 为该对象可分成多少个 uxx 机器字长的块(向下取整)
* - rest 为该对象向下取整时剩余的字节数
* - seed 为随机数种子,用于避免 hash 攻击
* 返回:
* - hash 结果
*/
inline uxx hash(voidp mem, uxx blocks, uxx rest, uxx seed = 0){
uxxp ptr = (uxxp)mem;
uxx mask = (uxx(1) << (rest * 8)) - 1;
uxx val = (ptr[blocks] & mask);
uxx x = (val + seed + rest);
uxx y = (magic_number * (u32(-1) >> 1));
for(uxx i = 0; i <= blocks; i++){
y += i == blocks ? ptr[i] & mask : ptr[i];
x += inc::count_of_set(y);
y += inc::ring_shift_left(x, y);
x += inc::ring_shift_left(y, x);
}
return x;
}
/* 函数:上层哈希函数
* 参数:
* - value 为要 hash 的对象
* - seed 为随机数种子,用于避免 hash 攻击
* 返回:
* - hash 结果
*/
template<class type_t>
inline uxx hash(type_t const & value, uxx seed = 0){
if constexpr (
inc::is_same<type_t, asciis> or
inc::is_same<type_t, words> or
inc::is_origin_array<type_t>){
uxx i = 0;
while(value[i] != '\0'){
i++;
}
return hash(voidp(value), i / sizeof(uxx), i % sizeof(uxx), seed);
}
else{
return hash(xref(value), sizeof(type_t) / sizeof(uxx), sizeof(type_t) % sizeof(uxx), seed);
}
}
}
#endif
xexport_space(mixc::algo_hash::origin)
| 26.3625 | 103 | 0.521574 | Better-Idea |
c232948cea0f446dae3856388e8ee3071b0cb546 | 692 | cc | C++ | lib/tonic/dart_sticky_error.cc | bleonard252/gfuchsiaos-topaz | 1d01e18fdb932f3bef20fd41d035035969297e04 | [
"BSD-3-Clause"
] | null | null | null | lib/tonic/dart_sticky_error.cc | bleonard252/gfuchsiaos-topaz | 1d01e18fdb932f3bef20fd41d035035969297e04 | [
"BSD-3-Clause"
] | null | null | null | lib/tonic/dart_sticky_error.cc | bleonard252/gfuchsiaos-topaz | 1d01e18fdb932f3bef20fd41d035035969297e04 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "lib/tonic/dart_sticky_error.h"
namespace tonic {
bool DartStickyError::MaybeSet(Dart_Handle result) {
if (!Dart_IsError(result)) {
// Not an error.
return false;
}
if (Dart_HasStickyError()) {
// We only remember the first error.
return false;
}
if (!Dart_IsUnhandledExceptionError(result)) {
result = Dart_NewUnhandledExceptionError(result);
}
Dart_SetStickyError(result);
return true;
}
bool DartStickyError::IsSet() {
return Dart_HasStickyError();
}
} // namespace tonic
| 23.066667 | 73 | 0.713873 | bleonard252 |
c23479eea22d6a2a9a691b5a11f0cac9329f1207 | 10,382 | cpp | C++ | Blizzlike/Trinity/Scripts/Dungeons/FrozenHalls/ForgeOfSouls/forge_of_souls.cpp | 499453466/Lua-Other | 43fd2b72405faf3f2074fd2a2706ef115d16faa6 | [
"Unlicense"
] | 2 | 2015-06-23T16:26:32.000Z | 2019-06-27T07:45:59.000Z | Blizzlike/Trinity/Scripts/Dungeons/FrozenHalls/ForgeOfSouls/forge_of_souls.cpp | Eduardo-Silla/Lua-Other | db610f946dbcaf81b3de9801f758e11a7bf2753f | [
"Unlicense"
] | null | null | null | Blizzlike/Trinity/Scripts/Dungeons/FrozenHalls/ForgeOfSouls/forge_of_souls.cpp | Eduardo-Silla/Lua-Other | db610f946dbcaf81b3de9801f758e11a7bf2753f | [
"Unlicense"
] | 3 | 2015-01-10T18:22:59.000Z | 2021-04-27T21:28:28.000Z | /*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "ScriptedGossip.h"
#include "forge_of_souls.h"
enum Events
{
EVENT_NONE,
// Jaina/Sylvanas Intro
EVENT_INTRO_1,
EVENT_INTRO_2,
EVENT_INTRO_3,
EVENT_INTRO_4,
EVENT_INTRO_5,
EVENT_INTRO_6,
EVENT_INTRO_7,
EVENT_INTRO_8,
};
/****************************************SYLVANAS************************************/
#define GOSSIP_SYLVANAS_ITEM "What would you have of me, Banshee Queen?"
#define GOSSIP_JAINA_ITEM "What would you have of me, my lady?"
enum Yells
{
SAY_JAINA_INTRO_1 = -1632040,
SAY_JAINA_INTRO_2 = -1632041,
SAY_JAINA_INTRO_3 = -1632042,
SAY_JAINA_INTRO_4 = -1632043,
SAY_JAINA_INTRO_5 = -1632044,
SAY_JAINA_INTRO_6 = -1632045,
SAY_JAINA_INTRO_7 = -1632046,
SAY_JAINA_INTRO_8 = -1632047,
SAY_SYLVANAS_INTRO_1 = -1632050,
SAY_SYLVANAS_INTRO_2 = -1632051,
SAY_SYLVANAS_INTRO_3 = -1632052,
SAY_SYLVANAS_INTRO_4 = -1632053,
SAY_SYLVANAS_INTRO_5 = -1632054,
SAY_SYLVANAS_INTRO_6 = -1632055,
};
enum eSylvanas
{
GOSSIP_SPEECHINTRO = 13525,
ACTION_INTRO,
};
enum Phase
{
PHASE_NORMAL,
PHASE_INTRO,
};
class npc_sylvanas_fos : public CreatureScript
{
public:
npc_sylvanas_fos() : CreatureScript("npc_sylvanas_fos") { }
struct npc_sylvanas_fosAI : public ScriptedAI
{
npc_sylvanas_fosAI(Creature* creature) : ScriptedAI(creature)
{
instance = me->GetInstanceScript();
me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
}
InstanceScript* instance;
EventMap events;
Phase phase;
void Reset()
{
events.Reset();
phase = PHASE_NORMAL;
}
void DoAction(const int32 actionId)
{
switch (actionId)
{
case ACTION_INTRO:
{
phase = PHASE_INTRO;
me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
events.Reset();
events.ScheduleEvent(EVENT_INTRO_1, 1000);
}
}
}
void UpdateAI(const uint32 diff)
{
if (phase == PHASE_INTRO)
{
if (!instance)
return;
events.Update(diff);
switch (events.ExecuteEvent())
{
case EVENT_INTRO_1:
DoScriptText(SAY_SYLVANAS_INTRO_1, me);
events.ScheduleEvent(EVENT_INTRO_2, 11500);
break;
case EVENT_INTRO_2:
DoScriptText(SAY_SYLVANAS_INTRO_2, me);
events.ScheduleEvent(EVENT_INTRO_3, 10500);
break;
case EVENT_INTRO_3:
DoScriptText(SAY_SYLVANAS_INTRO_3, me);
events.ScheduleEvent(EVENT_INTRO_4, 9500);
break;
case EVENT_INTRO_4:
DoScriptText(SAY_SYLVANAS_INTRO_4, me);
events.ScheduleEvent(EVENT_INTRO_5, 10500);
break;
case EVENT_INTRO_5:
DoScriptText(SAY_SYLVANAS_INTRO_5, me);
events.ScheduleEvent(EVENT_INTRO_6, 9500);
break;
case EVENT_INTRO_6:
DoScriptText(SAY_SYLVANAS_INTRO_6, me);
// End of Intro
phase = PHASE_NORMAL;
break;
}
}
//Return since we have no target
if (!UpdateVictim())
return;
events.Update(diff);
DoMeleeAttackIfReady();
}
};
bool OnGossipHello(Player* player, Creature* creature)
{
if (creature->isQuestGiver())
player->PrepareQuestMenu(creature->GetGUID());
if (creature->GetEntry() == NPC_JAINA_PART1)
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_JAINA_ITEM, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
else
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SYLVANAS_ITEM, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
player->SEND_GOSSIP_MENU(DEFAULT_GOSSIP_MESSAGE, creature->GetGUID());
return true;
}
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action)
{
player->PlayerTalkClass->ClearMenus();
switch (action)
{
case GOSSIP_ACTION_INFO_DEF+1:
player->CLOSE_GOSSIP_MENU();
if (creature->AI())
creature->AI()->DoAction(ACTION_INTRO);
break;
}
return true;
}
CreatureAI* GetAI(Creature* creature) const
{
return new npc_sylvanas_fosAI(creature);
}
};
class npc_jaina_fos : public CreatureScript
{
public:
npc_jaina_fos() : CreatureScript("npc_jaina_fos") { }
struct npc_jaina_fosAI: public ScriptedAI
{
npc_jaina_fosAI(Creature* creature) : ScriptedAI(creature)
{
instance = me->GetInstanceScript();
me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
}
InstanceScript* instance;
EventMap events;
Phase phase;
void Reset()
{
events.Reset();
phase = PHASE_NORMAL;
}
void DoAction(const int32 actionId)
{
switch (actionId)
{
case ACTION_INTRO:
{
phase = PHASE_INTRO;
me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
events.Reset();
events.ScheduleEvent(EVENT_INTRO_1, 1000);
}
}
}
void UpdateAI(const uint32 diff)
{
if (phase == PHASE_INTRO)
{
if (!instance)
return;
events.Update(diff);
switch (events.ExecuteEvent())
{
case EVENT_INTRO_1:
DoScriptText(SAY_JAINA_INTRO_1, me);
events.ScheduleEvent(EVENT_INTRO_2, 8000);
break;
case EVENT_INTRO_2:
DoScriptText(SAY_JAINA_INTRO_2, me);
events.ScheduleEvent(EVENT_INTRO_3, 8500);
break;
case EVENT_INTRO_3:
DoScriptText(SAY_JAINA_INTRO_3, me);
events.ScheduleEvent(EVENT_INTRO_4, 8000);
break;
case EVENT_INTRO_4:
DoScriptText(SAY_JAINA_INTRO_4, me);
events.ScheduleEvent(EVENT_INTRO_5, 10000);
break;
case EVENT_INTRO_5:
DoScriptText(SAY_JAINA_INTRO_5, me);
events.ScheduleEvent(EVENT_INTRO_6, 8000);
break;
case EVENT_INTRO_6:
DoScriptText(SAY_JAINA_INTRO_6, me);
events.ScheduleEvent(EVENT_INTRO_7, 12000);
break;
case EVENT_INTRO_7:
DoScriptText(SAY_JAINA_INTRO_7, me);
events.ScheduleEvent(EVENT_INTRO_8, 8000);
break;
case EVENT_INTRO_8:
DoScriptText(SAY_JAINA_INTRO_8, me);
// End of Intro
phase = PHASE_NORMAL;
break;
}
}
//Return since we have no target
if (!UpdateVictim())
return;
events.Update(diff);
DoMeleeAttackIfReady();
}
};
bool OnGossipHello(Player* player, Creature* creature)
{
if (creature->isQuestGiver())
player->PrepareQuestMenu(creature->GetGUID());
if (creature->GetEntry() == NPC_JAINA_PART1)
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_JAINA_ITEM, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
else
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SYLVANAS_ITEM, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
player->SEND_GOSSIP_MENU(DEFAULT_GOSSIP_MESSAGE, creature->GetGUID());
return true;
}
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action)
{
player->PlayerTalkClass->ClearMenus();
switch (action)
{
case GOSSIP_ACTION_INFO_DEF+1:
player->CLOSE_GOSSIP_MENU();
if (creature->AI())
creature->AI()->DoAction(ACTION_INTRO);
break;
}
return true;
}
CreatureAI* GetAI(Creature* creature) const
{
return new npc_jaina_fosAI(creature);
}
};
void AddSC_forge_of_souls()
{
new npc_sylvanas_fos();
new npc_jaina_fos();
}
| 30.445748 | 122 | 0.518108 | 499453466 |
c236e0243ae7eea0c01dfe5f7149d82859c663e1 | 16,217 | cpp | C++ | AIPDebug/sql/sqldesktop.cpp | Bluce-Song/Master-AIP | 1757ab392504d839de89460da17630d268ff3eed | [
"Apache-2.0"
] | null | null | null | AIPDebug/sql/sqldesktop.cpp | Bluce-Song/Master-AIP | 1757ab392504d839de89460da17630d268ff3eed | [
"Apache-2.0"
] | null | null | null | AIPDebug/sql/sqldesktop.cpp | Bluce-Song/Master-AIP | 1757ab392504d839de89460da17630d268ff3eed | [
"Apache-2.0"
] | null | null | null | #include "sqldesktop.h"
#include <QApplication>
SqlDesktop::SqlDesktop(QWidget *parent) : QWidget(parent)
{
initUI();
initDir();
initSql();
}
SqlDesktop::~SqlDesktop()
{
thread->quit();
thread->wait();
}
void SqlDesktop::initUI()
{
initLayout();
initSqlSignOut();
initSqlDisplay();
initSqlProduct();
initSqlHistory();
initSqlNetwork();
initSqlExports();
}
void SqlDesktop::initDir()
{
QDir dir;
if (!dir.exists("nandflash")) {
dir.mkdir("nandflash");
}
if (!dir.exists("./nandflash/sqlite.db")) {
QFile file("./nandflash/sqlite.db");
file.open(QIODevice::ReadWrite | QIODevice::Text);
file.close();
}
if (!dir.exists("nandflash/record.db")) {
QFile file("nandflash/record.db");
file.open(QIODevice::ReadWrite | QIODevice::Text);
file.close();
}
qDebug() << system("rm ./nandflash/*.db-journal");
}
void SqlDesktop::initSql()
{
QSqlDatabase sqlite = QSqlDatabase::addDatabase("QSQLITE", "sqlite");
sqlite.setDatabaseName("./nandflash/sqlite.db");
if (sqlite.open()) {
} else {
qDebug() << "sqlite:" << sqlite.lastError();
}
QSqlDatabase record = QSqlDatabase::addDatabase("QSQLITE", "record");
record.setDatabaseName("./nandflash/record.db");
if (record.open()) {
} else {
qDebug() << "record:" << record.lastError();
}
backupSqlRecord();
createSqlRecord();
tmpMap.insert("enum", QMessageBox::Open);
tmpMap.insert("sqliteName", "sqlite");
tmpMap.insert("recordName", "record");
emit sendSqlMap(tmpMap);
tmpMap.clear();
}
void SqlDesktop::initLayout()
{
#ifdef __arm__
this->setWindowFlags(Qt::FramelessWindowHint);
#endif
stack = new QStackedWidget(this);
btnLayout = new QVBoxLayout;
btnLayout->setMargin(0);
btnLayout->setSpacing(5);
stack->setStyleSheet((".QStackedWidget{background-color:#191919; color:white; border:none;}"));
text = new QLabel(this);
text->setWordWrap(true);
text->setFixedSize(WIDTH, 200);
text->setStyleSheet((".QLabel{background-color:#191919; color:white; border:none;}"));
QVBoxLayout *leftLayout = new QVBoxLayout;
leftLayout->addLayout(btnLayout);
leftLayout->addStretch();
leftLayout->addWidget(text);
QWidget *leftWidget = new QWidget(this);
leftWidget->setObjectName("leftWidget");
leftWidget->setLayout(leftLayout);
leftWidget->setStyleSheet(".QWidget{background-color:#191919; color:white; border:none;}");
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(stack);
layout->addWidget(leftWidget);
QHBoxLayout *background_layout = new QHBoxLayout;
QFrame *back = new QFrame;
back->setStyleSheet(".QFrame{background-color:#191919; color:white; border:none;}");
back->setLayout(layout);
back->resize(800, 600);
background_layout->addWidget(back);
background_layout->setMargin(0);
this->setLayout(background_layout);
this->resize(800, 600);
}
void SqlDesktop::initSqlDisplay()
{
QString objName = "sqldisplay";
SqlDisplay *sqldisplay = new SqlDisplay(this);
sqldisplay->setObjectName(objName);
stack->addWidget(sqldisplay);
connect(sqldisplay, SIGNAL(sendSqlMap(QVariantMap)), this, SLOT(recvSqlMap(QVariantMap)));
connect(this, SIGNAL(sendSqlMap(QVariantMap)), sqldisplay, SLOT(recvSqlMap(QVariantMap)));
QPushButton *btnsqldisplay = new QPushButton(tr("近期数据"), this);
btnsqldisplay->setFlat(true);
btnsqldisplay->setCheckable(true);
btnsqldisplay->setFixedSize(WIDTH, Heigth);
btnsqldisplay->setFocusPolicy(Qt::NoFocus);
buttons.append(btnsqldisplay);
btnLayout->addWidget(btnsqldisplay);
btnsqldisplay->setObjectName(objName);
connect(btnsqldisplay, SIGNAL(clicked(bool)), this, SLOT(clickButton()));
}
void SqlDesktop::initSqlProduct()
{
QString objName = "sqlproduct";
SqlProduct *sqlproduct = new SqlProduct(this);
sqlproduct->setObjectName(objName);
stack->addWidget(sqlproduct);
connect(this, SIGNAL(sendSqlMap(QVariantMap)), sqlproduct, SLOT(recvSqlMap(QVariantMap)));
QPushButton *btnsqlproduct = new QPushButton(tr("近期产量"), this);
btnsqlproduct->setFlat(true);
btnsqlproduct->setCheckable(true);
btnsqlproduct->setFixedSize(WIDTH, Heigth);
btnsqlproduct->setFocusPolicy(Qt::NoFocus);
buttons.append(btnsqlproduct);
btnLayout->addWidget(btnsqlproduct);
btnsqlproduct->setObjectName(objName);
connect(btnsqlproduct, SIGNAL(clicked(bool)), this, SLOT(clickButton()));
}
void SqlDesktop::initSqlNetwork()
{
SqlNetwork *sqlnetwork = new SqlNetwork(this);
sqlnetwork->setObjectName("sqlnetwork");
stack->addWidget(sqlnetwork);
connect(this, SIGNAL(sendSqlMap(QVariantMap)), sqlnetwork, SLOT(recvSqlMap(QVariantMap)));
QPushButton *btnsqlnetwork = new QPushButton(tr("网络管理"), this);
btnsqlnetwork->setFlat(true);
btnsqlnetwork->setCheckable(true);
btnsqlnetwork->setFixedSize(WIDTH, Heigth);
btnsqlnetwork->setFocusPolicy(Qt::NoFocus);
buttons.append(btnsqlnetwork);
btnLayout->addWidget(btnsqlnetwork);
btnsqlnetwork->setObjectName("sqlnetwork");
connect(btnsqlnetwork, SIGNAL(clicked(bool)), this, SLOT(clickButton()));
}
void SqlDesktop::initSqlHistory()
{
SqlHistory *sqlhistory = new SqlHistory(this);
sqlhistory->setObjectName("sqlhistory");
stack->addWidget(sqlhistory);
connect(sqlhistory, SIGNAL(sendSqlMap(QVariantMap)), this, SLOT(recvSqlMap(QVariantMap)));
QPushButton *btnsqlnetwork = new QPushButton(tr("历史数据"), this);
btnsqlnetwork->setFlat(true);
btnsqlnetwork->setCheckable(true);
btnsqlnetwork->setFixedSize(WIDTH, Heigth);
btnsqlnetwork->setFocusPolicy(Qt::NoFocus);
buttons.append(btnsqlnetwork);
btnLayout->addWidget(btnsqlnetwork);
btnsqlnetwork->setObjectName("sqlhistory");
connect(btnsqlnetwork, SIGNAL(clicked(bool)), this, SLOT(clickButton()));
}
void SqlDesktop::initSqlExports()
{
thread = new QThread(this);
SqlExports *sqlexports = new SqlExports;
sqlexports->setObjectName("sqlexports");
sqlexports->moveToThread(thread);
thread->start();
connect(sqlexports, SIGNAL(sendSqlMap(QVariantMap)), this, SLOT(recvSqlMap(QVariantMap)));
connect(this, SIGNAL(sendSqlMap(QVariantMap)), sqlexports, SLOT(recvSqlMap(QVariantMap)));
}
void SqlDesktop::initSqlSignOut()
{
QPushButton *btnLogout = new QPushButton(tr("退出设置"), this);
btnLogout->setFlat(true);
btnLogout->setCheckable(true);
btnLogout->setFixedSize(WIDTH, Heigth);
btnLogout->setFocusPolicy(Qt::NoFocus);
buttons.append(btnLogout);
btnLayout->addWidget(btnLogout);
btnLogout->setObjectName("");
connect(btnLogout, SIGNAL(clicked(bool)), this, SLOT(widget_hide()));
}
void SqlDesktop::widget_hide() {
Signal_Data_to_Main(QStringList(""), 0, 1); // 主页面
this->hide();
}
void SqlDesktop::sendSqlExports(QVariantMap msg)
{
QString path = existsFlashDisk();
if (path.isEmpty()) {
#ifdef __arm__
text->setText(tr("未发现U盘"));
QMessageBox::warning(this, "", tr("请插入U盘"), QMessageBox::Ok);
#else
text->setText(tr("导出取消"));
#endif
return;
}
tmpMap = msg;
tmpMap.insert("path", path);
emit sendSqlMap(tmpMap);
tmpMap.clear();
initProgressBar();
}
void SqlDesktop::initProgressBar()
{
pBar = new QProgressDialog(this, Qt::Dialog);
pBar->setWindowTitle(tr("数据导出进度"));
pBar->setLabelText(tr("正在查询数据"));
pBar->setFixedWidth(300);
pBar->show();
}
void SqlDesktop::createSqlRecord()
{
QSqlQuery query(QSqlDatabase::database("record"));
QString cmd;
cmd = "create table if not exists aip_record (";
cmd += "uuid bigint primary key, guid bigint, numb integer,";
cmd += "item text,parm text,rslt text,pass text)";
if (!query.exec(cmd))
qDebug() << "aip_record:" << query.lastError();
}
void SqlDesktop::backupSqlRecord()
{
#ifdef __arm__
QProcess cmd;
cmd.start("du -s /mnt/nandflash/record.db");
cmd.waitForFinished();
int ss = 0;
QByteArray df = cmd.readAll();
QString sf = df.mid(0, df.indexOf("\t"));
ss = sf.toInt();
if (ss > SD_SIZE) {
QString w = tr("当前存储的数据量较多,正在备份到SD卡...");
t.restart();
box = new QMessageBox(this);
box->setText(w);
box->show();
QTimer::singleShot(100, this, SLOT(updateSqlMessage()));
}
#endif
}
void SqlDesktop::updateSqlMessage()
{
QProcess cmd;
QString name = QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
if (existsSdcardDisk()) {
QString p = "mv /mnt/nandflash/record.db /mnt/sdcard/";
p.append(name + ".db");
cmd.start(p);
cmd.waitForFinished();
} else {
QString w = tr("未发现SD卡,点击OK后清除数据");
QMessageBox::warning(this, "", w, QMessageBox::Ok);
qDebug() << system("rm /mnt/nandflash/record.db");
}
qDebug() << system("reboot");
}
void SqlDesktop::clickButton()
{
QString sourceName = QObject::sender()->objectName();
for (int i=0; i < buttons.size(); i++) {
if (buttons.at(i)->objectName() != sourceName) {
buttons.at(i)->setChecked(false);
}
}
for (int i=0; i < stack->count(); i++) {
if (stack->widget(i)->objectName() == sourceName) {
stack->setCurrentIndex(i);
break;
}
}
}
bool SqlDesktop::existsSdcardDisk()
{
bool isExist = false;
QProcess cmddf;
cmddf.start("df -h");
if (cmddf.waitForFinished()) {
QByteArray bytedf = cmddf.readAll();
QStringList listdf = QString(bytedf).split("\n");
for (int i=0; i < listdf.size(); i++) {
if (listdf.at(i).startsWith("/dev/mmcblk0p1")) {
isExist = true;
break;
}
}
}
cmddf.deleteLater();
return isExist;
}
QString SqlDesktop::existsFlashDisk()
{
QString path;
QString name = QDateTime::currentDateTime().toString("yyMMddhhmmss");
#ifdef __arm__
QProcess cmddf;
cmddf.start("df -h");
cmddf.waitForFinished();
QByteArray bytedf = cmddf.readAll();
cmddf.deleteLater();
QStringList listdf = QString(bytedf).split("\n");
for (int i=0; i < listdf.size(); i++) {
if (listdf.at(i).startsWith("/dev/sd")) {
QStringList tmp = listdf.at(i).split(" ");
path = tmp.last();
}
}
if (!path.isEmpty()) {
path.append("/" + name + ".csv");
}
#else
path = QFileDialog::getSaveFileName(this,
tr("Open Config"),
name,
tr("Config Files (*.csv)"));
path += ".csv";
#endif
return path;
}
void SqlDesktop::deleteFlashDisk()
{
#ifdef __arm__
QProcess cmddf;
cmddf.start("df -h");
cmddf.waitForFinished();
QByteArray bytedf = cmddf.readAll();
QStringList listdf = QString(bytedf).split("\n");
QString path;
for (int i=0; i < listdf.size(); i++) {
if (listdf.at(i).startsWith("/dev/sd")) {
QStringList tmp = listdf.at(i).split(" ");
if (tmp.last().startsWith("/mnt/usb")) {
path = tmp.first();
cmddf.start(tr("umount %1").arg(path));
cmddf.waitForFinished();
}
}
}
cmddf.deleteLater();
#endif
}
void SqlDesktop::updateSqlExport()
{
time--;
time = qMax(time, 0);
#ifdef __arm__
int t = quan*25/LENTH;
#else
int t = quan/LENTH*0.5;
#endif
int r = (t-time)*100/t -1;
pBar->setLabelText(tr("共找到%1条数据,预计剩余%2s").arg(quan).arg(time));
pBar->setValue(r);
}
void SqlDesktop::recvQuan(QVariantMap msg)
{
quan = msg.value("quan").toInt();
#ifdef __arm__
time = quan*25/LENTH;
#else
time = quan/LENTH*0.5;
#endif
pBar->setValue(1);
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateSqlExport()));
timer->start(1000);
}
void SqlDesktop::recvOver(QVariantMap msg)
{
if (msg.value("fail").toString() == "fail") {
text->setText("导出失败");
}
timer->stop();
pBar->deleteLater();
timer->deleteLater();
deleteFlashDisk();
}
void SqlDesktop::recvSqlMap(QVariantMap msg)
{
switch (msg.value("enum").toInt()) {
case QMessageBox::Close:
recvOver(msg);
break;
case QMessageBox::Abort:
text->setText(tr("导出失败"));
break;
case QMessageBox::Question:
recvQuan(msg);
break;
case QMessageBox::Information:
qDebug() << msg.value("text").toString();
text->setText(msg.value("text").toString());
break;
case QMessageBox::Apply:
sendSqlExports(msg);
break;
default:
break;
}
}
void SqlDesktop::recvSqlDat(QVariantMap msg)
{
QSqlQuery query(QSqlDatabase::database("record"));
QSqlDatabase::database("record").transaction();
SqlSnowUid snow;
quint64 uuid = snow.getId();
items.clear();
QStringList content = msg.value("data").toString().split("\n");
for (int i=0; i < content.size(); i++) {
QStringList temp = QString(content.at(i)).split("@");
if (temp.size() >= 4) {
int numb = getNumber(temp.at(0));
query.prepare("insert into aip_record values(?,?,?,?,?,?,?)");
query.addBindValue(snow.getId());
query.addBindValue(uuid);
query.addBindValue(QString::number(numb));
query.addBindValue(temp.at(0));
query.addBindValue(temp.at(1));
query.addBindValue(((QString)(temp.at(2))).replace(QRegExp("\\,"), " "));
query.addBindValue(temp.at(3));
if (!query.exec()) {
qDebug() << "insert error" << query.lastError();
}
}
}
query.prepare("insert into aip_record values(?,?,?,?,?,?,?)");
query.addBindValue(snow.getId());
query.addBindValue(uuid);
query.addBindValue(1);
query.addBindValue(msg.value("user").toString());
query.addBindValue(msg.value("temp").toString());
query.addBindValue(msg.value("post").toString());
query.addBindValue(msg.value("numb").toString());
if (!query.exec()) {
qDebug() << "insert error" << query.lastError();
}
query.prepare("insert into aip_record values(?,?,?,?,?,?,?)");
query.addBindValue(uuid);
query.addBindValue(uuid);
query.addBindValue(0);
query.addBindValue(QDate::currentDate().toString("yyyy-MM-dd"));
query.addBindValue(QTime::currentTime().toString("hh:mm:ss"));
query.addBindValue(msg.value("type").toString());
query.addBindValue(msg.value("pass").toString());
if (!query.exec()) {
qDebug() << "insert error" << query.lastError();
}
QSqlDatabase::database("record").commit();
}
int SqlDesktop::getNumber(QString msg)
{
int numb = 0;
int item = 0;
QStringList names;
names << tr("电阻") << tr("反嵌") << tr("绝缘") << tr("交耐") << tr("直耐")
<< tr("匝间") << tr("电参") << tr("电感") << tr("堵转") << tr("低启")
<< tr("霍尔") << tr("负载") << tr("空载") << tr("反势");
for (int i=0; i < names.size(); i++) {
if (msg.startsWith(names.at(i))) {
item = i+1;
}
}
names.clear();
names << tr("电阻")<< tr("反嵌") << tr("绝缘") << tr("交耐") << tr("直耐")
<< tr("匝间") << tr("电参") << tr("电感") << tr("堵转") << tr("低启")
<< tr("FG") << tr("负载") << tr("空载") << tr("BEMF");
for (int i=0; i < names.size(); i++) {
if (msg.startsWith(names.at(i))) {
item = i+1;
}
}
if (item == 0) {
if (msg.startsWith(tr("-电阻-"))) {
numb = 0x0180;
} else if (msg.startsWith(tr("磁旋"))) {
numb = 0x0280;
} else if (msg.startsWith(tr("转向"))) {
numb = 0x0780;
} else if (msg.startsWith(tr("-电感-"))) {
numb = 0x0880;
} else if (msg.startsWith("Q")) {
numb = 0x0980;
} else {
numb = 0xFFFF;
}
} else {
items[item]++;
numb = 256*item + items[item];
}
return numb;
}
| 29.97597 | 99 | 0.608867 | Bluce-Song |
c23791e0e269ff8e30743f53cc0e645a359aa687 | 2,936 | cpp | C++ | storage/driver.azure/src/logging_windows.cpp | gamunu/bolt | c1a2956f02656f3ec2c244486a816337126905ae | [
"Apache-2.0"
] | 1 | 2022-03-06T09:23:56.000Z | 2022-03-06T09:23:56.000Z | storage/driver.azure/src/logging_windows.cpp | gamunu/bolt | c1a2956f02656f3ec2c244486a816337126905ae | [
"Apache-2.0"
] | 3 | 2021-04-23T18:12:20.000Z | 2021-04-23T18:12:47.000Z | storage/driver.azure/src/logging_windows.cpp | gamunu/bolt | c1a2956f02656f3ec2c244486a816337126905ae | [
"Apache-2.0"
] | null | null | null | // -----------------------------------------------------------------------------------------
// <copyright file="logging_windows.cpp" company="Microsoft">
// Copyright 2013 Microsoft Corporation
//
// 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.
// </copyright>
// -----------------------------------------------------------------------------------------
#include "stdafx.h"
#include "wascore/logging.h"
#include <evntprov.h>
#include <evntrace.h>
namespace azure {
namespace storage {
namespace core {
// {EE5D17C5-1B3E-4792-B0F9-F8C5FC6AC22A}
static const GUID event_provider_guid = { 0xee5d17c5, 0x1b3e, 0x4792, { 0xb0, 0xf9, 0xf8, 0xc5, 0xfc, 0x6a, 0xc2, 0x2a } };
static REGHANDLE g_event_provider_handle;
UCHAR get_etw_log_level(client_log_level level)
{
switch (level)
{
case client_log_level::log_level_off:
throw std::invalid_argument("level");
case client_log_level::log_level_error:
return TRACE_LEVEL_ERROR;
case client_log_level::log_level_warning:
return TRACE_LEVEL_WARNING;
case client_log_level::log_level_informational:
return TRACE_LEVEL_INFORMATION;
}
return TRACE_LEVEL_VERBOSE;
}
logger::logger()
{
if (EventRegister(&event_provider_guid, NULL, NULL, &g_event_provider_handle) != ERROR_SUCCESS)
{
g_event_provider_handle = NULL;
}
}
logger::~logger()
{
if (g_event_provider_handle != NULL)
{
EventUnregister(g_event_provider_handle);
}
}
void logger::log(azure::storage::operation_context context, client_log_level level, const std::string& message) const
{
if (g_event_provider_handle != NULL)
{
utf16string utf16_message = utility::conversions::to_utf16string(message);
EventWriteString(g_event_provider_handle, get_etw_log_level(level), 0, utf16_message.c_str());
}
}
void logger::log(azure::storage::operation_context context, client_log_level level, const std::wstring& message) const
{
if (g_event_provider_handle != NULL)
{
EventWriteString(g_event_provider_handle, get_etw_log_level(level), 0, message.c_str());
}
}
bool logger::should_log(azure::storage::operation_context context, client_log_level level) const
{
return (g_event_provider_handle != NULL) && (level <= context.log_level());
}
logger logger::m_instance;
}
}
} // namespace azure::storage::core | 31.913043 | 126 | 0.665531 | gamunu |
c237cf9da89d5b5527a68a0f88613f7206dbdd6f | 26,423 | cpp | C++ | bot/src/cpp/navigation/WaypointNavMethod.cpp | Bots-United/whichbot | c5db2a6cc3f90930139503b344074376a9cdaabb | [
"BSD-2-Clause"
] | null | null | null | bot/src/cpp/navigation/WaypointNavMethod.cpp | Bots-United/whichbot | c5db2a6cc3f90930139503b344074376a9cdaabb | [
"BSD-2-Clause"
] | null | null | null | bot/src/cpp/navigation/WaypointNavMethod.cpp | Bots-United/whichbot | c5db2a6cc3f90930139503b344074376a9cdaabb | [
"BSD-2-Clause"
] | 1 | 2020-04-06T02:02:28.000Z | 2020-04-06T02:02:28.000Z | //
// $Id: WaypointNavMethod.cpp,v 1.8 2005/12/14 19:25:39 clamatius Exp $
// Copyright (c) 2003, WhichBot Project
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the WhichBot Project nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BotTypedefs.h"
#include "navigation/WaypointNavMethod.h"
#include "framework/Log.h"
#include "worldstate/AreaManager.h"
#include "BotManager.h"
#include "config/TranslationManager.h"
#include "worldstate/WorldStateUtil.h"
Log WaypointNavMethod::_log(__FILE__);
const float WAYPOINT_HEIGHT_OFFSET = -10.0;
const float LAST_USED_SWITCH_TIME = 2.5;
const float MAX_TIME_TO_TRAVERSE_WAYPOINTS = 10.0;
const float MAX_TIME_TO_TRAVERSE_GOAL = 60.0;
const float NEAR_WPT_DISTANCE = 40.0;
const float ONOS_NEAR_WPT_DISTANCE = 80.0;
const float REOPTIMISE_FACTOR = 3.0;
const float LONG_DISTANCE = 1000.0;
const float WAYPOINT_LENGTH_ADJUSTMENT_RATE = 0.1;
const float WAYPOINT_NOT_REACHED_TIME_PENALTY = 60.0;
const float IMPASSABLE_THRESHOLD = 40.0;
const float LIFT_NEAR = 50.0;
const float LIFT_TIMEOUT = 15.0;
WaypointNavMethod::WaypointNavMethod(Bot& bot, bool initialSpawn) :
_mode(LOST),
_nextWptId(-1),
_useButtonTime(0),
_lastWptTime(gpGlobals->time),
_bot(bot),
_evolution(bot.getEvolution()),
_waitAtWp(false)
{
tTerrainGraph* pExpectedTerrain = &gpBotManager->getWaypointManager().getTerrainGraph(_bot.getEvolution());
if (_bot.getPathManager().getTerrain() != pExpectedTerrain) {
_bot.getPathManager().setTerrain(pExpectedTerrain);
}
}
WaypointNavMethod::~WaypointNavMethod()
{
}
int WaypointNavMethod::getNearestWaypointId()
{
WaypointManager::tWaypointQueue wptQueue =
gpBotManager->getWaypointManager().getNearestWaypoints(_bot.getEvolution(), _bot.getEdict()->v.origin, _bot.getEdict());
if (!wptQueue.empty()) {
tNodeId wptId = wptQueue.top().wptId;
if (wptId == prevWaypointId() && !wptQueue.empty()) {
wptQueue.pop();
if (wptQueue.empty()) {
return INVALID_NODE_ID;
} else {
wptId = wptQueue.top().wptId;
}
}
return wptId;
} else {
return INVALID_NODE_ID;
}
}
NavigationMethod* WaypointNavMethod::navigate()
{
if (_bot.getMovement() == NULL) {
return NULL;
}
// check to make sure we didn't just change evolution
if (_bot.getEvolution() != _evolution) {
changedEvolution();
}
switch (_mode) {
case LOST:
navigateLost();
break;
case SEEKING_NEAREST:
//DrawDebugBeam(_nextWptId);
//DrawDebugBeam(_bot.getEdict()->v.origin, gpBotManager->getWaypointManager().getOrigin(_nextWptId), 0, 0, 255);
if (_nextWptId != prevWaypointId()) {
addHistoryWaypoint(_nextWptId);
}
if (_bot.getPathManager().nodeIdValid(_nextWptId) && (_bot.getPathManager().getRootNodeId() == INVALID_NODE_ID)) {
_bot.getPathManager().setRootNode(_nextWptId);
}
_bot.getPathManager().reoptimiseTree((int)(gpBotManager->getWaypointManager().getNumWaypoints() * REOPTIMISE_FACTOR));
seekNearestWaypoint();
break;
case SEEKING_REWARDS:
//DrawDebugBeam(_nextWptId);
//DrawDebugBeam(_bot.getEdict()->v.origin, gpBotManager->getWaypointManager().getOrigin(_nextWptId), 255, 0, 0);
_bot.getPathManager().reoptimiseTree((int)(gpBotManager->getWaypointManager().getNumWaypoints() * REOPTIMISE_FACTOR));
seekRewards();
break;
case FINDING_SWITCH:
findSwitch();
break;
case RETRACING_STEPS:
retraceSteps();
break;
case WAIT_AT_WAYPOINT:
// _bot.getPathManager().reoptimiseTree((int)(gpBotManager->getWaypointManager().getNumWaypoints() * REOPTIMISE_FACTOR));
// Don't move the bot.
waitAtWaypoint();
return NULL;
case WAIT_FOR_LIFT:
waitForLift();
break;
}
if (_bot.getPathManager().nodeIdValid(_nextWptId) &&
(gpBotManager->getWaypointManager().getFlags(_nextWptId) & W_FL_JUMP) != 0)
{
if (RANDOM_LONG(0,100) > 50) {
_bot.getEdict()->v.button |= IN_JUMP;
}
}
if (_bot.getMovement() != NULL) {
if (_bot.getMovement()->shouldUseMeleeAttack()) {
_bot.selectWeapon(NULL, 0, true);
_bot.fireWeapon();
}
_bot.getMovement()->move(_bot.getEvolution());
}
//DrawDebugBeam(_nextWptId);
return NULL;
}
void WaypointNavMethod::pause()
{
_waitAtWp = true;
}
void WaypointNavMethod::resume()
{
_waitAtWp = false;
}
void WaypointNavMethod::changedEvolution()
{
_evolution = _bot.getEvolution();
tTerrainGraph* terrain = &gpBotManager->getWaypointManager().getTerrainGraph(_evolution);
_bot.getPathManager().setTerrain(terrain);
_nextWptId = getNearestWaypointId();
if (_bot.getPathManager().nodeIdValid(_nextWptId)) {
_bot.getPathManager().setRootNode(_nextWptId);
_bot.getPathManager().reoptimiseTree((int)(REOPTIMISE_FACTOR * gpBotManager->getWaypointManager().getNumWaypoints()));
_bot.getPathManager().trickleRewards(_bot.getStrategyManager().getRewards(_evolution));
setNextWaypointTarget();
} else {
_mode = LOST;
}
}
void WaypointNavMethod::navigateLost()
{
_nextWptId = getNearestWaypointId();
if (_bot.getPathManager().nodeIdValid(_nextWptId)) {
//_log.Debug("Nearest visible waypoint is %d", _nextWptId);
_lastWptTime = gpGlobals->time;
_mode = SEEKING_NEAREST;
setNextWaypointTarget();
} else {
_log.Debug("No nearby visible waypoint found");
if (_bot.getMovement() != NULL) {
_bot.getMovement()->setRandomTarget();
_bot.getMovement()->move(_bot.getEvolution());
}
}
}
Vector WaypointNavMethod::getWptOrigin(tNodeId wptId)
{
return gpBotManager->getWaypointManager().getOrigin(wptId) + Vector(0, 0, WAYPOINT_HEIGHT_OFFSET);
}
float WaypointNavMethod::getMinTargetDistance()
{
return (_evolution != kOnos) ? NEAR_WPT_DISTANCE : ONOS_NEAR_WPT_DISTANCE;
}
Vector WaypointNavMethod::vectorToWaypoint(int wptId)
{
return getWptOrigin(wptId) - _bot.getEdict()->v.origin;
}
void WaypointNavMethod::foundRouteWaypoint()
{
int flags = gpBotManager->getWaypointManager().getFlags(_nextWptId);
if (_bot.getPathManager().nodeIdValid(_nextWptId)) {
_bot.getStrategyManager().visitedWaypoint(_bot.getEvolution(), _nextWptId);
_bot.getPathManager().setRootNode(_nextWptId);
_bot.getPathManager().trickleRewards(_bot.getStrategyManager().getRewards(_bot.getEvolution()));
int prevWptId = prevWaypointId();
if (_bot.getPathManager().nodeIdValid(prevWptId) &&
gpBotManager->getWaypointManager().isLadder(_nextWptId) &&
gpBotManager->getWaypointManager().isLadder(prevWptId))
{
Vector vecBetweenWaypoints(getWptOrigin(_nextWptId) - getWptOrigin(prevWaypointId()));
if (vecBetweenWaypoints.z < 0) {
// jump off ladders at the bottom
_bot.getEdict()->v.button |= IN_JUMP;
}
}
} else {
_log.Debug("Strange - we found the route waypoint, but next wpt id was invalid");
}
if ((flags & W_FL_DOOR) && (gpGlobals->time > (_useButtonTime + LAST_USED_SWITCH_TIME))) {
_mode = FINDING_SWITCH;
} else if ((_evolution != kSkulk) && (flags & W_FL_LIFT_SWITCH) && (gpGlobals->time > (_useButtonTime + LAST_USED_SWITCH_TIME)) && !liftIsNear()) {
_mode = FINDING_SWITCH;
} else if ((_evolution != kSkulk) && (flags & W_FL_LIFT_WAIT) && !liftIsNear()) {
_mode = WAIT_FOR_LIFT;
} else if ((_evolution != kSkulk) && (flags & W_FL_LIFT) && liftIsNear() && (gpGlobals->time > (_useButtonTime + LAST_USED_SWITCH_TIME))) {
// we have to hit the switch to move the damn lift again
_log.Debug("On lift. Hitting switch to move lift...");
_nextWptId = gpBotManager->getWaypointManager().findFlaggedWaypoint(prevWaypointId(), W_FL_LIFT_SWITCH);
}
}
void WaypointNavMethod::seekNearestWaypoint()
{
assert(_bot.getPathManager().getTerrain() != NULL);
assert(_bot.getPathManager().nodeIdValid(_nextWptId));
if ((_bot.getPathManager().getTerrain() != NULL) && (_bot.getPathManager().nodeIdValid(_nextWptId))) {
Vector vecToWpt(vectorToWaypoint(_nextWptId));
bool hitWaypoint = didWeHitWaypoint(vecToWpt);
if (hitWaypoint) {
// we hit it
//_log.Debug("Hit nearest waypoint");
foundRouteWaypoint();
_mode = _waitAtWp ? WAIT_AT_WAYPOINT : SEEKING_REWARDS;
} else if (_bot.getMovement()->getDistanceToTarget(_bot.getEvolution()) > LONG_DISTANCE) {
_mode = LOST;
_log.Debug("Nearest waypoint %d (%s) is a suspiciously long way away, resetting", _nextWptId, TranslationManager::getTranslation(AreaManager::getAreaName(gpBotManager->getWaypointManager().getOrigin(_nextWptId))).c_str());
} else {
if (!checkStuck()) {
setNextWaypointTarget();
} else {
_log.Debug("Got stuck finding nearest waypoint, resetting...");
_mode = LOST;
}
}
}
}
void WaypointNavMethod::setNextWaypointTarget()
{
int prevWptId = prevWaypointId();
bool amWalking = ((_bot.getEvolution() >= MIN_WALK_EVOLUTION) && (_bot.getEvolution() <= MAX_WALK_EVOLUTION));
Vector verticalOffset(0, 0, WAYPOINT_HEIGHT_OFFSET);
Vector target(getWptOrigin(_nextWptId) + verticalOffset);
if (amWalking && isLadderPath(prevWptId, _nextWptId)) {
_bot.getMovement()->setLadderTarget(target,
getWptOrigin(_nextWptId).z > _bot.getEdict()->v.origin.z,
getMinTargetDistance() * 0.75);
} else {
_bot.getMovement()->setTarget(target, getMinTargetDistance());
}
}
void WaypointNavMethod::unableToFindNextWaypoint()
{
if (_wptHistory.size() > 0) {
if (_mode != RETRACING_STEPS) {
_log.Debug("Suspect we're stuck, trying to go to %d (%s). Going back to earliest waypoint",
_nextWptId, TranslationManager::getTranslation(AreaManager::getAreaName(gpBotManager->getWaypointManager().getOrigin(_nextWptId))).c_str());
updateUnreachedWaypointTravelTime();
Edge* thisWay = _bot.getPathManager().getTerrain()->getEdge(prevWaypointId(), _nextWptId);
if (thisWay == NULL || thisWay->getCost() > IMPASSABLE_THRESHOLD) {
_wptHistory.clear();
giveUpOnNextWaypoint();
} else {
_mode = RETRACING_STEPS;
_lastWptTime = gpGlobals->time;
_nextWptId = prevWaypointId();
}
} else {
_wptHistory.clear();
_log.Debug("Giving up on next waypoint while retracing steps.");
giveUpOnNextWaypoint();
}
} else {
_log.Debug("Stuck, and no history. Time to reboot...");
giveUpOnNextWaypoint();
}
}
bool WaypointNavMethod::checkStuck()
{
if ((gpGlobals->time > _lastWptTime + MAX_TIME_TO_TRAVERSE_WAYPOINTS/2.0) && (_evolution == kOnos)) {
_bot.getEdict()->v.button |= IN_DUCK;
}
float timeout = _lastWptTime +
(WorldStateUtil::isOnLadder(_bot.getEdict()) ?
MAX_TIME_TO_TRAVERSE_WAYPOINTS * 5.0 :
MAX_TIME_TO_TRAVERSE_WAYPOINTS);
if (gpGlobals->time > timeout) {
// stuck?
if (_bot.getEvolution() != kGorge) {
// jumping when we're stuck gets us out of a bunch of situations
_bot.getEdict()->v.button |= IN_JUMP;
} else {
// Gorges can actually get stuck inside entities thanks to a bug, so we'll try teleporting them
// a tad. :)
_log.Debug("We're stuck. Trying special gorge unstuck teleport...");
moveOutsideEntity(_bot.getEdict());
}
unableToFindNextWaypoint();
return true;
}
return false;
}
void WaypointNavMethod::seekRewards()
{
assert(_bot.getPathManager().getTerrain() != NULL);
if (_bot.getPathManager().getTerrain() != NULL) {
if (!_bot.getPathManager().nodeIdValid(_nextWptId)) {
_log.Debug("Uh-oh, can't find next waypoint id");
_mode = LOST;
return;
}
if (_bot.getMovement()->getDistanceToTarget(_bot.getEvolution()) > LONG_DISTANCE) {
_log.Debug("Strange, next waypoint %d (%s) is a long way away. Resetting to LOST", _nextWptId, TranslationManager::getTranslation(AreaManager::getAreaName(gpBotManager->getWaypointManager().getOrigin(_nextWptId))).c_str());
_mode = LOST;
return;
}
Vector vecToWpt(vectorToWaypoint(_nextWptId));
bool hitWaypoint = didWeHitWaypoint(vecToWpt);
if (hitWaypoint) {
int prevWptId = prevWaypointId();
if (prevWptId != _nextWptId) {
updateWaypointTravelTime(prevWptId, _nextWptId, gpGlobals->time - _lastWptTime);
}
foundRouteWaypoint();
if (_waitAtWp) {
_mode = WAIT_AT_WAYPOINT;
} else {
calculateNextWaypoint();
if (_bot.getPathManager().nodeIdValid(_nextWptId)) {
setNextWaypointTarget();
}
}
} else {
int currentNextId = _nextWptId;
float lastWptTime = _lastWptTime;
if (!checkStuck()) {
moveBetweenWaypoints();
}
}
}
}
void WaypointNavMethod::moveBetweenWaypoints()
{
Vector target(getWptOrigin(_nextWptId));
}
bool WaypointNavMethod::didWeHitWaypoint(Vector& vecToWpt)
{
bool hitWaypoint = false;
int prevWptId = prevWaypointId();
if (!WorldStateUtil::isOnLadder(_bot.getEdict())) {
hitWaypoint = _bot.getMovement()->isAtTargetVector();
}
// if we didn't use the short-cut (less than some min distance) waypointhit check, and we are going from
// one waypoint to another
if (!hitWaypoint && (_bot.getPathManager().nodeIdValid(prevWptId)))
{
Vector vecBetweenWaypoints(getWptOrigin(_nextWptId) - getWptOrigin(prevWptId));
if (vecBetweenWaypoints.Length() == 0) {
hitWaypoint = true;
} else {
Vector vecFromPrevWaypoint(_bot.getEdict()->v.origin - getWptOrigin(prevWptId));
float projectionDistance = DotProduct(vecFromPrevWaypoint, vecBetweenWaypoints) / vecBetweenWaypoints.Length();
if (projectionDistance + NEAR_WPT_DISTANCE >= vecBetweenWaypoints.Length()) {
hitWaypoint = true;
}
}
}
return hitWaypoint;
}
bool WaypointNavMethod::isLadderPath(tNodeId prevWptId, tNodeId nextWptId)
{
//WaypointDebugger::drawDebugBeam(nextWptId);
// are both of the waypoints a ladder wpt?
return ((gpBotManager->getWaypointManager().isLadder(prevWptId) ||
!_bot.getPathManager().nodeIdValid(prevWptId)) &&
gpBotManager->getWaypointManager().isLadder(nextWptId));
}
void WaypointNavMethod::calculateNextWaypoint()
{
if (prevWaypointId() != _nextWptId) {
addHistoryWaypoint(_nextWptId);
}
_nextWptId = _bot.getPathManager().getOptimalNextNodeId();
if (_bot.getPathManager().nodeIdValid(_nextWptId)) {
const string& areaName = AreaManager::getAreaName(
gpBotManager->getWaypointManager().getOrigin(_nextWptId));
const string& locationName = TranslationManager::getTranslation(areaName);
//_log.Debug("Next waypoint is %d in %s", _nextWptId, locationName.c_str());
} else {
_log.Debug("Can't get a valid next wpt from path manager. Giving up for now...");
giveUpOnNextWaypoint();
}
}
void WaypointNavMethod::giveUpOnNextWaypoint()
{
_log.Debug("Giving up on next waypoint %d", _nextWptId);
// TODO - use alternate route instead of just randomly giving up
_mode = LOST;
updateUnreachedWaypointTravelTime();
}
int InFieldOfView(float view_angle, Vector dest)
{
// find angles from source to destination...
Vector entity_angles = UTIL_VecToAngles(dest);
// make yaw angle 0 to 360 degrees if negative...
if (entity_angles.y < 0) {
entity_angles.y += 360;
}
// make view angle 0 to 360 degrees if negative...
if (view_angle < 0) {
view_angle += 360;
}
// return the absolute value of angle to destination entity
// zero degrees means straight ahead, 45 degrees to the left or
// 45 degrees to the right is the limit of the normal view angle
int angle = abs((int)view_angle - (int)entity_angles.y);
if (angle > 180) {
angle = 360 - angle;
}
return angle;
}
const int SEARCH_RADIUS = 200;
const char* BUTTON_CLASSNAME = "func_button";
const char* ROTATOR_BUTTON_CLASSNAME = "func_rot_button";
const char* DOOR_CLASSNAME = "func_door";
void WaypointNavMethod::findSwitch()
{
bool entityFound = tryToUseEntity(BUTTON_CLASSNAME);
if (!entityFound) {
entityFound = tryToUseEntity(ROTATOR_BUTTON_CLASSNAME);
}
if (!entityFound) {
entityFound = tryToUseEntity(DOOR_CLASSNAME);
}
// if we couldn't see it from where we are now, let's try going back to the waypoint to see if we have better luck next time
if (!entityFound && _bot.getPathManager().nodeIdValid(prevWaypointId())) {
setNextWaypointTarget();
}
checkStuck();
}
bool WaypointNavMethod::tryToUseEntity(const char* entityClassname)
{
Vector targetOrigin;
if (_nextWptId >= 0) {
targetOrigin = getWptOrigin(_nextWptId);
} else {
targetOrigin = _bot.getEdict()->v.origin;
}
edict_t* pEntity = WorldStateUtil::findClosestSwitchEntity(entityClassname, targetOrigin);
if (pEntity == NULL) {
return false;
}
Vector entity_origin = pEntity->v.absmin + (pEntity->v.size * 0.5);
Vector vecStart = _bot.getEdict()->v.origin + _bot.getEdict()->v.view_ofs;
Vector vecToEntity = entity_origin - vecStart;
float distance = vecToEntity.Length();
if (distance > SEARCH_RADIUS) {
return false;
}
TraceResult tr;
WorldStateUtil::checkVector(vecStart);
WorldStateUtil::checkVector(entity_origin);
// trace a line from bot's centre to func_ entity...
UTIL_TraceLine(vecStart, entity_origin, dont_ignore_monsters,
_bot.getEdict()->v.pContainingEntity, &tr);
//WaypointDebugger::drawDebugBeam(vecStart, entity_origin, 255, 0, 0);
if ((_useButtonTime + LAST_USED_SWITCH_TIME) < gpGlobals->time) {
// check if flag not set and facing it...
int angleToEntity = InFieldOfView(_bot.getEdict()->v.v_angle.y, vecToEntity);
if (angleToEntity <= 10) {
float minDistance = 75;
if (distance < minDistance) {
_log.Debug("Using button");
_bot.getEdict()->v.button |= IN_USE;
_useButtonTime = gpGlobals->time;
_bot.getMovement()->stop(_evolution);
if ((_evolution != kSkulk) &&
(gpBotManager->getWaypointManager().getFlags(_nextWptId) | W_FL_LIFT_SWITCH) != 0)
{
int nearestWaitWaypoint =
gpBotManager->getWaypointManager().findFlaggedWaypoint(_nextWptId, W_FL_LIFT_WAIT);
if (nearestWaitWaypoint >= 0) {
_nextWptId = nearestWaitWaypoint;
}
}
_mode = SEEKING_REWARDS;
calculateNextWaypoint();
}
}
}
_bot.getMovement()->setTarget(entity_origin, getMinTargetDistance());
return true;
}
const int MAX_HISTORY_LENGTH = 4;
void WaypointNavMethod::addHistoryWaypoint(int wptId)
{
_lastWptTime = gpGlobals->time;
_wptHistory.push_front(wptId);
if (_wptHistory.size() >= MAX_HISTORY_LENGTH) {
_wptHistory.pop_back();
}
}
void WaypointNavMethod::resetWaypointHistory()
{
_wptHistory.clear();
}
void WaypointNavMethod::retraceSteps()
{
if (_wptHistory.size() > 0) {
_nextWptId = _wptHistory.front();
}
if (_bot.getPathManager().nodeIdValid(_nextWptId)) {
Vector vecToWpt(vectorToWaypoint(_nextWptId));
bool hitWaypoint = didWeHitWaypoint(vecToWpt);
if (hitWaypoint) {
//_log.Debug("Reached next waypoint on route, %d", _nextWptId);
_lastWptTime = gpGlobals->time;
_wptHistory.pop_front();
_bot.getPathManager().setRootNode(_nextWptId);
if (_wptHistory.size() > 0) {
_nextWptId = _wptHistory.front();
} else {
_mode = SEEKING_REWARDS;
}
} else {
if (!checkStuck()) {
setNextWaypointTarget();
}
}
} else {
_log.Debug("Invalid waypoint in retrace steps %d, going to lost mode", _nextWptId);
_mode = LOST;
}
}
void WaypointNavMethod::updateWaypointTravelTime(int prevWptId, int nextWptId, float travelTime)
{
if ((travelTime > 0) && _bot.getPathManager().nodeIdValid(prevWptId) && _bot.getPathManager().nodeIdValid(nextWptId)) {
// find the edge we just travelled
vector<Edge>& edges = _bot.getPathManager().getTerrain()->getEdges(prevWptId);
Edge* thisWay = _bot.getPathManager().getTerrain()->getEdge(prevWptId, nextWptId);
// it's sometimes possible for this to be null (e.g. if we evolved between waypoints where one waypoint isn't valid
// for one evolution's terrain).
if (thisWay != NULL) {
Edge* otherWay = _bot.getPathManager().getTerrain()->getEdge(nextWptId, prevWptId);
if (otherWay != NULL) {
float currentCost = thisWay->getCost();
float newCost = currentCost + (travelTime - currentCost) * WAYPOINT_LENGTH_ADJUSTMENT_RATE;
float costDiff = newCost - currentCost;
assert(newCost > 0);
if (currentCost != newCost) {
thisWay->setCost(newCost);
otherWay->setCost(newCost);
// _log.Debug("Updated waypoint travel cost from %d to %d to %f from %f",
// prevWptId, nextWptId, newCost, currentCost);
if (newCost > currentCost) {
gpBotManager->terrainUpdated(_bot.getEvolution(), prevWptId, nextWptId, costDiff);
}
}
}
}
}
}
void WaypointNavMethod::updateUnreachedWaypointTravelTime()
{
int prevWptId = prevWaypointId();
if (_bot.getPathManager().nodeIdValid(prevWptId)) {
Edge* edge = _bot.getPathManager().getTerrain()->getEdge(prevWptId, _nextWptId);
if (edge != NULL) {
float prevTravelTime = edge->getCost();
float newTravelTime = prevTravelTime + WAYPOINT_NOT_REACHED_TIME_PENALTY;
_log.Debug("Updating unreached wpt travel time to %f from %f", newTravelTime, prevTravelTime);
updateWaypointTravelTime(prevWptId, _nextWptId, newTravelTime);
}
}
}
void WaypointNavMethod::waitAtWaypoint()
{
_bot.getMovement()->stop(_evolution);
_bot.getMovement()->move(_evolution);
_bot.getStrategyManager().waitedAtWaypoint(_bot.getEvolution(), _nextWptId);
_lastWptTime = gpGlobals->time;
if (!_waitAtWp) {
// Ok, we're ready to move again.
calculateNextWaypoint();
_mode = SEEKING_REWARDS;
}
}
void WaypointNavMethod::waitForLift()
{
if (!liftIsNear() && (gpGlobals->time < _lastWptTime + LIFT_TIMEOUT)) {
_log.Debug("Waiting for lift...");
_bot.getMovement()->stop(_evolution);
} else {
_mode = SEEKING_REWARDS;
}
}
bool WaypointNavMethod::liftIsNear()
{
if (_lastLiftEntity.isNull() || (_lastLiftCheckWpt != _nextWptId)) {
int nearestLiftWaypoint = gpBotManager->getWaypointManager().findFlaggedWaypoint(_nextWptId, W_FL_LIFT);
if (_bot.getPathManager().nodeIdValid(nearestLiftWaypoint)) {
_lastLiftEntity.setEdict(WorldStateUtil::findClosestEntity("func_door", gpBotManager->getWaypointManager().getOrigin(nearestLiftWaypoint)));
}
}
if (!_lastLiftEntity.isNull()) {
_lastLiftCheckWpt = _nextWptId;
return fabs(_lastLiftEntity.getOrigin()->z - _bot.getEdict()->v.origin.z) < LIFT_NEAR;
}
// default to true if we don't find the lift
_log.Debug("No lift found near lift flagged waypoints!");
return true;
}
string WaypointNavMethod::getName() const
{
return "WaypointNavigation";
}
| 33.02875 | 236 | 0.643341 | Bots-United |
c23a8c54e3aa47c199b3edd44eb5907605b86c1e | 5,662 | cpp | C++ | lib/helion/ast.cpp | nickwanninger/helion | 5821af2893b77c21293779c93e34aa73fdb25846 | [
"MIT"
] | 1 | 2019-06-11T06:49:15.000Z | 2019-06-11T06:49:15.000Z | lib/helion/ast.cpp | nickwanninger/helion | 5821af2893b77c21293779c93e34aa73fdb25846 | [
"MIT"
] | null | null | null | lib/helion/ast.cpp | nickwanninger/helion | 5821af2893b77c21293779c93e34aa73fdb25846 | [
"MIT"
] | 1 | 2019-06-10T16:48:55.000Z | 2019-06-10T16:48:55.000Z | // [License]
// MIT - See LICENSE.md file in the package.
#include <cxxabi.h>
#include <helion/ast.h>
#include <helion/pstate.h>
#include <atomic>
using namespace helion;
using namespace helion::ast;
text ast::module::str(int depth) {
text s;
for (auto d : typedefs) {
s += d->str(0);
s += "\n";
}
if (globals.size() > 0) {
s += "# global variables\n";
for (auto d : globals) {
s += d->str(0);
s += "\n";
}
s += "\n";
}
for (auto d : stmts) {
s += d->str(0);
s += "\n";
}
return s;
}
text ast::number::str(int) {
if (type == floating) {
return std::to_string(as.floating);
} else {
return std::to_string(as.integer);
}
}
text ast::binary_op::str(int depth) {
text s;
// s += "(";
s += left->str();
s += " ";
s += op;
s += " ";
s += right->str();
// s += ")";
return s;
}
text ast::dot::str(int) {
text s;
// s += "(";
s += expr->str();
s += ".";
s += sub;
// s += ")";
return s;
}
text ast::subscript::str(int) {
text s;
s += "(";
s += expr->str();
s += "[";
for (size_t i = 0; i < subs.size(); i++) {
auto& v = subs[i];
if (v != nullptr) {
s += v->str();
}
if (i < subs.size() - 1) s += ", ";
}
s += "])";
return s;
}
std::atomic<int> var_index = 0;
ast::var_decl::var_decl(scope* s) : node(s) { ind = var_index++; }
text ast::var_decl::str(int d) {
text s;
if (!is_arg) s += "let ";
if (global) s += "global ";
s += name;
if (type != nullptr) {
s += ": ";
s += type->str();
}
if (value != nullptr) {
s += " = ";
s += value->str(d);
}
return s;
}
text ast::var::str(int) {
if (global) return global_name;
return decl->name;
}
text ast::call::str(int) {
text t;
t += func->str();
t += "(";
for (size_t i = 0; i < args.size(); i++) {
auto& v = args[i];
if (v != nullptr) {
t += v->str();
}
if (i < args.size() - 1) t += ", ";
}
t += ")";
return t;
}
text ast::tuple::str(int) {
text t;
t += "(";
for (size_t i = 0; i < vals.size(); i++) {
auto& v = vals[i];
if (v != nullptr) {
t += v->str();
}
if (vals.size() == 1) {
t += ",";
break;
}
if (i < vals.size() - 1) t += ", ";
}
t += ")";
return t;
}
text ast::string::str(int) {
text s;
s += "'";
s += val;
s += "'";
return s;
}
text ast::keyword::str(int) {
text s;
s += val;
return s;
}
text ast::nil::str(int) {
text s;
s += "nil";
return s;
}
text ast::do_block::str(int depth) {
text indent = "";
for (int i = 0; i < depth; i++) indent += ". ";
text s;
s += "do\n";
for (auto e : exprs) {
s += indent;
s += " ";
s += e->str(depth + 1);
s += "\n";
}
s += indent;
s += "end";
return s;
}
text ast::typeassert::str(int) {
text s;
s += "(";
s += val->str();
s += " :: ";
s += type->str();
s += ")";
return s;
}
text ast::type_node::str(int) {
text s;
if (name == "->") {
if (params[0]->params.size() == 1) {
s += params[0]->params[0]->str();
} else {
s += params[0]->str();
}
s += " -> ";
s += params[1]->str();
return s;
}
if (name == "()") {
s += "(";
for (size_t i = 0; i < params.size(); i++) {
auto& param = params[i];
s += param->str();
if (i < params.size() - 1) {
s += ", ";
}
}
s += ")";
return s;
}
s += name;
for (auto& param : params) {
s += " ";
s += param->str();
}
return s;
}
text ast::prototype::str(int) {
text s;
s += "(";
for (size_t i = 0; i < args.size(); i++) {
auto& arg = args[i];
s += arg->str();
if (i < args.size() - 1) {
s += ", ";
}
}
s += ")";
if (type != nullptr) {
auto typ = type->params.back();
s += ": ";
s += typ->str();
}
return s;
}
text ast::func::str(int depth) {
text indent = "";
for (int i = 0; i < depth; i++) indent += " ";
text s;
s += "[";
int i = 0;
for (auto& c : captures) {
i++;
s += c;
if (i < captures.size() - 1) s += ", ";
}
s += "]";
if (proto != nullptr) {
s += proto->str();
} else {
s += "()";
}
s += " => ";
s += stmt->str(depth);
return s;
}
text ast::def::str(int depth) {
text indent = "";
for (int i = 0; i < depth; i++) indent += " ";
text s;
s += "def ";
s += fn->name;
s += " ";
if (fn->proto != nullptr) s += fn->proto->str();
s += "\n";
for (auto& e : fn->stmt->as<ast::do_block*>()->exprs) {
s += indent;
s += " ";
s += e->str(depth + 1);
s += "\n";
}
s += indent;
s += "end";
return s;
}
text ast::typedef_node::str(int depth) {
text indent = "";
for (int i = 0; i < depth; i++) indent += " ";
text s;
s += "type ";
s += type->str();
if (extends != nullptr) {
s += " extends ";
s += extends->str();
}
s += "\n";
for (auto& field : fields) {
s += indent;
s += " ";
s += field.type->str();
s += " ";
s += field.name;
s += "\n";
}
for (auto& def : defs) {
s += indent;
s += " ";
s += def->str(depth + 1);
s += "\n";
}
s += indent;
s += "end";
return s;
}
text ast::return_node::str(int depth) {
text s;
s += "return ";
s += val->str(depth + 1);
return s;
}
text ast::if_node::str(int depth) {
text s;
text indent = "";
for (int i = 0; i < depth; i++) indent += " ";
s += "if ";
s += cond->str();
s += " then ";
s += true_expr->str(depth);
if (false_expr != nullptr) {
s += " else ";
s += false_expr->str(depth);
}
return s;
}
| 14.084577 | 66 | 0.423878 | nickwanninger |
c23ea5ec79839db0b76773914e28a1b08b195e19 | 3,498 | cpp | C++ | source/laplace/render/r_context.cpp | ogryzko/laplace | be63caa0c6d1c4fceab02ab5b41b6d307ef7baaf | [
"MIT"
] | 3 | 2021-05-17T21:15:28.000Z | 2021-09-06T23:01:52.000Z | source/laplace/render/r_context.cpp | ogryzko/laplace | be63caa0c6d1c4fceab02ab5b41b6d307ef7baaf | [
"MIT"
] | 33 | 2021-10-20T10:47:07.000Z | 2022-02-26T02:24:20.000Z | source/laplace/render/r_context.cpp | automainint/laplace | 66956df506918d48d79527e524ff606bb197d8af | [
"MIT"
] | null | null | null | /* laplace/render/r_context.cpp
*
* Copyright (c) 2021 Mitya Selivanov
*
* This file is part of the Laplace project.
*
* Laplace is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the MIT License for more details.
*/
#include "context.h"
#include "../math/transform.h"
#include "../platform/opengl.h"
namespace laplace::render {
namespace flat = graphics::flat;
using std::make_shared, std::weak_ptr, std::span,
graphics::ref_texture, graphics::vec2, graphics::cref_vec2,
flat::solid_shader, flat::ptr_solid_shader,
flat::ptr_sprite_shader;
weak_ptr<context> context::m_default;
void context::setup(ptr_solid_shader shader) {
m_solid_shader = shader;
}
void context::setup(ptr_sprite_shader shader) {
m_sprite_shader = shader;
}
void context::adjust_frame_size(sl::whole width, sl::whole height) {
const auto x0 = width < 0 ? 1.f : -1.f;
const auto y0 = height < 0 ? -1.f : 1.f;
const auto w = 2.f / static_cast<float>(width);
const auto h = -2.f / static_cast<float>(height);
if (m_solid_shader) {
m_solid_shader->use();
m_solid_shader->set_view_position({ x0, y0 });
m_solid_shader->set_view_scale({ w, h });
}
if (m_sprite_shader) {
m_sprite_shader->use();
m_sprite_shader->set_view_position({ x0, y0 });
m_sprite_shader->set_view_scale({ w, h });
}
}
void context::render(span<const solid_vertex> vertices) {
this->render(vertices, vec2 { 0.f, 0.f }, vec2 { 1.f, 1.f });
}
void context::render(span<const solid_vertex> vertices,
cref_vec2 position, cref_vec2 scale) {
if (m_solid_shader) {
m_solid_shader->use();
m_solid_shader->set_mesh_position(position);
m_solid_shader->set_mesh_scale(scale);
m_solid_buffer.render(vertices);
}
}
void context::render_strip(span<const solid_vertex> vertices) {
if (m_solid_shader) {
m_solid_shader->use();
m_solid_shader->set_mesh_position({ 0.f, 0.f });
m_solid_shader->set_mesh_scale({ 1.f, 1.f });
m_solid_buffer.render_strip(vertices);
}
}
void context::render(span<const sprite_vertex> vertices,
ref_texture tex) {
this->render(vertices, vec2 { 0.f, 0.f }, vec2 { 1.f, 1.f }, tex);
}
void context::render(span<const sprite_vertex> vertices,
cref_vec2 position, cref_vec2 scale,
ref_texture tex) {
if (m_sprite_shader) {
m_sprite_shader->use();
m_sprite_shader->set_mesh_position(position);
m_sprite_shader->set_mesh_scale(scale);
m_sprite_shader->set_texture(0);
tex.bind_2d(0);
m_sprite_buffer.render(vertices);
}
}
void context::render_strip(span<const sprite_vertex> vertices,
ref_texture tex) {
if (m_sprite_shader) {
m_sprite_shader->use();
m_sprite_shader->set_mesh_position({ 0.f, 0.f });
m_sprite_shader->set_mesh_scale({ 1.f, 1.f });
m_sprite_shader->set_texture(0);
tex.bind_2d(0);
m_sprite_buffer.render_strip(vertices);
}
}
auto context::get_default() -> ptr_context {
auto result = m_default.lock();
if (!result) {
result = make_shared<context>();
m_default = result;
}
return result;
}
}
| 27.984 | 70 | 0.634648 | ogryzko |
c244d0764ec49e5e6f436851fb429e5726f2ecd4 | 2,293 | cpp | C++ | non_convex_cuda/Common/family.cpp | dongdong12311/Non-convex-Risk-Parity- | 2cc254de0aa52493e062db94a5671307092f284a | [
"MIT"
] | null | null | null | non_convex_cuda/Common/family.cpp | dongdong12311/Non-convex-Risk-Parity- | 2cc254de0aa52493e062db94a5671307092f284a | [
"MIT"
] | null | null | null | non_convex_cuda/Common/family.cpp | dongdong12311/Non-convex-Risk-Parity- | 2cc254de0aa52493e062db94a5671307092f284a | [
"MIT"
] | null | null | null | #include"family.h"
#include"MultiScaleTools.h"
#include<stdio.h>
#include<iostream>
#include<stdlib.h>
Family::Family(std::vector<int> &dim_,std::vector<double> &mu_,int nlayers):
dim(dim_),mu(mu_)
{
this->totalnum = 1;
for (int i = 0 ; i < dim.size() ; ++i){
this->totalnum *= dim[i];
}
this->dimension = dim.size();
this->nLayers = nlayers;
this->nCells.resize(nLayers);
}
int Family::init(){
TDoubleMatrix muX;
std::vector<double> mu_ = this->mu;
std::vector<int> dim_ = this->dim;
muX.data=mu_.data();
muX.dimensions=dim_.data();
muX.depth=dim.size();
TMultiScaleSetupSingleGrid MultiScaleSetup(&muX,this->nLayers);
int msg;
msg=MultiScaleSetup.Setup();
if(msg!=0) { printf("error: %d\n",msg); return msg; }
msg=MultiScaleSetup.SetupRadii();
if(msg!=0) { printf("error: %d\n",msg); return msg; }
msg=MultiScaleSetup.SetupDuals();
if(msg!=0) { printf("error: %d\n",msg); return msg; }
int nLayers = MultiScaleSetup.nLayers;
printf("total layers %d\n",nLayers);
int num_nChildren = 0;
int num_parent = 0;
for (int i = 0 ; i < nLayers ; ++i){
this->nCells[i] = MultiScaleSetup.HP->layers[i]->nCells;
printf("i = %d\t,cellnum = %d\n",i,this->nCells[i]);
for (int j = 0; j < this->nCells[i] ;++j){
num_nChildren += MultiScaleSetup.HP->layers[i]->nChildren[j];
num_parent += MultiScaleSetup.HP->layers[i]->parent[j];
// printf("parent = %d\t",parent);
// layersY->layer[i].nChildren[j] = MultiScaleSetupY.HP->layers[i]->nChildren[j];
// layersY->layer[i].nLeaves[j] = MultiScaleSetupY.HP->layers[i]->nLeaves[j];
// for (int k = 0 ; k < num_nChildren; ++k){
// layersY->layer[i].children[j][k] =MultiScaleSetupY.HP->layers[i]->children[j][k];
// layersY->layer[i].leaves[j][k] =MultiScaleSetupY.HP->layers[i]->leaves[j][k];
// }
}
printf("\n");
}
printf("number num_nChildren = %d\t",num_nChildren);
printf("number num_parent = %d\t",num_parent);
int t = total_children(this->dimension,this->nLayers,this->totalnum);
printf("t = %d\n",t);
return 0;
}
//create a family based on 1dimension vector
| 31.847222 | 97 | 0.590493 | dongdong12311 |
c24746b5dca1fa77f117e4a1204bc877dfb5430d | 507 | cpp | C++ | BOJ_백준/10025 게으른 백곰 (슬라이딩 윈도우).cpp | woorimlee/cpp_CTCI_6E_APSS | ff1d42e871ba853ac3de726df0c609885ba07573 | [
"MIT"
] | 2 | 2020-12-30T03:35:51.000Z | 2021-02-28T20:39:09.000Z | BOJ_백준/10025 게으른 백곰 (슬라이딩 윈도우).cpp | woorimlee/cpp_CTCI_6E_APSS | ff1d42e871ba853ac3de726df0c609885ba07573 | [
"MIT"
] | 1 | 2020-12-08T08:48:40.000Z | 2021-04-09T04:58:57.000Z | BOJ_백준/10025 게으른 백곰 (슬라이딩 윈도우).cpp | woorimlee/Algorithm-Repository | ff1d42e871ba853ac3de726df0c609885ba07573 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int arr[1000001] = { 0, };
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(NULL);
int N, K, g, x;
cin >> N >> K;
for (int i = 0; i < N; i++) {
cin >> g >> x;
arr[x] = g;
}
K = 2 * K + 1;
int ans = 0, sum = 0;
for (int i = 0; i <= 1000000; i++) {
if (i >= K)
sum -= arr[i - K];
sum += arr[i];
ans = ans > sum ? ans : sum;
}
cout << ans << "\n";
return 0;
}
| 16.354839 | 40 | 0.39645 | woorimlee |
c24b508ee7d4abd2478ed42db14ea2e82110be0e | 3,707 | hpp | C++ | addons/modules/includes/moduleActivationAttributes.hpp | Krzyciu/A3CS | b7144fc9089b5ded6e37cc1fad79b1c2879521be | [
"MIT"
] | 1 | 2020-06-07T00:45:49.000Z | 2020-06-07T00:45:49.000Z | addons/modules/includes/moduleActivationAttributes.hpp | Krzyciu/A3CS | b7144fc9089b5ded6e37cc1fad79b1c2879521be | [
"MIT"
] | 27 | 2020-05-24T11:09:56.000Z | 2020-05-25T12:28:10.000Z | addons/modules/includes/moduleActivationAttributes.hpp | Krzyciu/A3CS | b7144fc9089b5ded6e37cc1fad79b1c2879521be | [
"MIT"
] | 2 | 2020-05-31T08:52:45.000Z | 2021-04-16T23:16:37.000Z |
class GVAR(activationSettingsSubCategory): GVAR(moduleSubCategory) {
displayName = CSTRING(Attributes_activationSettingsSubCategory);
property = QGVAR(activationSettingsSubCategory);
};
class GVAR(activationMode): Default {
displayName = CSTRING(Attributes_activationMode);
tooltip = CSTRING(Attributes_activationMode_Tooltip);
property = QGVAR(activationMode);
typeName = "NUMBER";
GVAR(observeValue) = 1;
ATTRIBUTE_LOCAL;
#ifdef MODULE_ACTIVATOR_CONTROL
control = MODULE_ACTIVATOR_CONTROL;
#undef MODULE_ACTIVATOR_CONTROL
#else
control = QGVAR(dynamicToolboxActivationMode);
#endif
#ifdef MODULE_ACTIVATOR_DEFAULT_VALUE
defaultValue = MODULE_ACTIVATOR_DEFAULT_VALUE;
#undef MODULE_ACTIVATOR_DEFAULT_VALUE
#else
defaultValue = "0";
#endif
};
class GVAR(activationNearestPlayerDistance): GVAR(dynamicSlider) {
displayName = CSTRING(Attributes_activationNearestPlayerDistance);
tooltip = CSTRING(Attributes_activationNearestPlayerDistance_Tooltip);
property = QGVAR(activationNearestPlayerDistance);
defaultValue = "800";
typeName = "NUMBER";
GVAR(range[]) = {1, 3000};
GVAR(valueUnit) = "m";
GVAR(conditionActive) = QUOTE((_this getVariable QQGVAR(activationMode)) isEqualTo 0);
ATTRIBUTE_LOCAL;
};
class GVAR(activationIgnoreHelicopters): GVAR(dynamicCheckbox) {
displayName = CSTRING(Attributes_activationIgnoreHelicopters);
tooltip = CSTRING(Attributes_activationIgnoreHelicopters_tooltip);
property = QGVAR(activationIgnoreHelicopters);
GVAR(observeValue) = 0;
GVAR(conditionActive) = QUOTE((_this getVariable QQGVAR(activationMode)) isEqualTo 0);
ATTRIBUTE_LOCAL;
};
class GVAR(activationIgnorePlanes): GVAR(dynamicCheckbox) {
displayName = CSTRING(Attributes_activationIgnorePlanes);
tooltip = CSTRING(Attributes_activationIgnorePlanes_tooltip);
property = QGVAR(activationIgnorePlanes);
GVAR(observeValue) = 0;
GVAR(conditionActive) = QUOTE((_this getVariable QQGVAR(activationMode)) isEqualTo 0);
ATTRIBUTE_LOCAL;
};
class GVAR(activationFlags): GVAR(dynamicLogicFlagCondActivator) {
displayName = CSTRING(Attributes_activationFlags);
tooltip = CSTRING(Attributes_activationFlags_Tooltip);
property = QGVAR(activationFlags);
defaultValue = "'[]'";
GVAR(conditionActive) = QUOTE((_this getVariable QQGVAR(activationMode)) isEqualTo 1);
ATTRIBUTE_LOCAL;
};
class GVAR(activationCondition): GVAR(dynamicEditCodeMulti5) {
displayName = CSTRING(Attributes_activationCondition);
tooltip = CSTRING(Attributes_activationCondition_Tooltip);
property = QGVAR(activationCondition);
defaultValue = "'true'";
typeName = "STRING";
validate = "condition";
GVAR(conditionActive) = QUOTE((_this getVariable QQGVAR(activationMode)) isEqualTo 2);
ATTRIBUTE_LOCAL;
};
class GVAR(activationDelay): GVAR(dynamicCheckbox) {
displayName = CSTRING(Attributes_activationDelay);
tooltip = CSTRING(Attributes_activationDelay_tooltip);
property = QGVAR(activationDelay);
GVAR(conditionActive) = QUOTE((_this getVariable QQGVAR(activationMode)) isNotEqualTo -1);
ATTRIBUTE_LOCAL;
};
class GVAR(activationDelayTime): GVAR(dynamicEdit) {
displayName = CSTRING(Attributes_activationDelayTime);
tooltip = CSTRING(Attributes_activationDelayTime_Tooltip);
property = QGVAR(activationDelayTime);
defaultValue = "'0'";
typeName = "NUMBER";
validate = "number";
GVAR(conditionActive) = QUOTE(((_this getVariable QQGVAR(activationDelay)) isEqualTo true) &&((_this getVariable QQGVAR(activationMode)) isNotEqualTo -1));
ATTRIBUTE_LOCAL;
};
| 40.736264 | 159 | 0.753439 | Krzyciu |
c2504519bf80afe8eeabb869b9f306c703b8e401 | 8,469 | cpp | C++ | lib/ut_content_codec.cpp | mheily/fs123 | b92a3108defcdad623abc08fb2e837d74d6210da | [
"BSD-3-Clause"
] | null | null | null | lib/ut_content_codec.cpp | mheily/fs123 | b92a3108defcdad623abc08fb2e837d74d6210da | [
"BSD-3-Clause"
] | null | null | null | lib/ut_content_codec.cpp | mheily/fs123 | b92a3108defcdad623abc08fb2e837d74d6210da | [
"BSD-3-Clause"
] | 1 | 2019-09-06T02:07:22.000Z | 2019-09-06T02:07:22.000Z | #include "fs123/content_codec.hpp"
#include "fs123/acfd.hpp"
#include "fs123/sharedkeydir.hpp"
#include <core123/sew.hpp>
#include <core123/autoclosers.hpp>
#include <core123/exnest.hpp>
#include <core123/strutils.hpp>
#include <cassert>
#include <functional>
#include <iostream>
using namespace core123;
static std::string sfname;
static acfd sffd;
void replace_sf(const std::string& encoding_key,
std::map<std::string, std::string> newcontents){
std::ostringstream cmd;
sew::system(fmt("[ -d '%s' ] && rm %s/*", sfname.c_str(), sfname.c_str()).c_str());
auto tmpname = sfname + "/encode.keyid";
acfd fd = sew::open(tmpname.c_str(), O_RDWR|O_TRUNC|O_CREAT, 0600);
sew::write(fd, encoding_key.data(), encoding_key.size());
for(auto& kv : newcontents){
auto fname = sfname + "/" + kv.first + ".sharedkey";
fd = sew::open(fname.c_str(), O_RDWR|O_TRUNC|O_CREAT, 0600);
sew::write(fd, kv.second.c_str(), kv.second.size());
}
fd.close();
}
struct blob{
std::unique_ptr<char[]> _buf;
str_view _content;
str_view _arena;
blob(size_t leader, const std::string& content, size_t trailer){
_buf = std::make_unique<char[]>(leader + content.size() + trailer);
_arena = str_view(_buf.get(), leader + content.size() + trailer);
_content = str_view(_buf.get()+leader, content.size());
::memcpy(const_cast<char*>(_content.data()), content.data(), content.size());
};
str_view arena() const { return _arena; }
str_view content() const { return _content; }
size_t leader() const { return _content.data() - _arena.data(); }
void replace_content(const std::string& s){
// no bounds checking!!!!
::memcpy(const_cast<char*>(_content.data()), s.data(), s.size());
_content = str_view(_content.data(), s.size());
}
};
void
expect_throw(const std::string& msg, std::function<void()> f) {
bool caught = false;
try{
f();
}catch(std::exception& e){
caught = true;
std::cout << "OK - expected exception (" << msg << ") caught:\n";
for(auto& v : exnest(e))
std::cout << "\t" << v.what() << "\n";
}
if(!caught)
throw std::runtime_error("Expected throw did not materialize: " + msg);
}
void try_to_use_sfname(){
sharedkeydir cc(sffd, "encode", 1);
auto sid = cc.get_encode_sid();
cc.get_sharedkey(sid);
}
int main(int /*argc*/, char **/*argv*/) try {
// Testing for "success" is easy. Encode something. Check that
// it's garbled. Then decode it. It's also worth checking that
// encoding twice with derived_nonce=false produces two different
// ciphertexts and with derived_nonce=true produces the same
// ciphertext. But none of that is very interesting: problems
// with encoding and decoding will show up very quickly when the
// class is used.
//
// It's much more important to test that content_codec and
// the secret_manager fail when they should. E.g.,
//
// - missing sharedkeydir or a garbled .sharedkey file
// - garbage in the .sharedkey file
// - required secret not in sharedkeydir
// - ciphertext fails authentication
//
// Such errors are much less likely to be immediately noticed
// in end-to-end testing.
//
// There are also issues related to the refresh time... E.g., do
// the shared pointers have the expected lifetimes? That's pretty
// hard to test - it needs two threads to hit a narrow window
// in which one reloads the .sharedkey while the other is in
// the process of using it.
sfname = "ut_content_codec.secret.d";
mkdir(sfname.c_str(), 0700); // no sew - EEXIST is fine.
sffd = sew::open(sfname.c_str(), O_RDONLY|O_DIRECTORY);
replace_sf("1",
{{"1", "12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678\n"}});
// Let's encode "hello"
sharedkeydir sm(sffd, "encode", 1);
std::string hello = "hello";
blob ws1(48, hello, 8);
core123::str_view encoded;
auto esid = sm.get_encode_sid();
auto esecret = sm.get_sharedkey(esid);
encoded = content_codec::encode(content_codec::CE_FS123_SECRETBOX, esid, esecret, ws1.content(), ws1.arena(), 4);
std::cout << "This should look like noise: " << quopri({encoded.data(), encoded.size()}) << "\n";
auto s1 = std::string(encoded);
// Do it again - expect to get a different ciphertext because we'll get a different
// nonce from /dev/urandom
ws1.replace_content(hello);
encoded = content_codec::encode(content_codec::CE_FS123_SECRETBOX, esid, esecret, ws1.content(), ws1.arena(), 4);
std::cout << "And this should look like different noise: " << quopri({encoded.data(), encoded.size()}) << "\n";
auto s2 = std::string(encoded);
assert(s1 != s2);
std::cout << "OK - two encodes with derived_nonce=false are different\n";
// Check that both of them decode back to "hello"
auto d1 = content_codec::decode(content_codec::CE_FS123_SECRETBOX, s1, sm);
auto d2 = content_codec::decode(content_codec::CE_FS123_SECRETBOX, s2, sm);
assert(d1 == hello);
assert(d2 == hello);
std::cout << "OK - roundtrip with derived_nonce=false\n";
// Try it again with derived_nonce=false:
ws1.replace_content(hello);
encoded = content_codec::encode(content_codec::CE_FS123_SECRETBOX, esid, esecret, ws1.content(), ws1.arena(), 4, true);
auto s3 = std::string(encoded);
assert(s3 != s2);
std::cout << "OK - encodes with derived_nonce=true and false are different\n";
ws1.replace_content(hello);
encoded = content_codec::encode(content_codec::CE_FS123_SECRETBOX, esid, esecret, ws1.content(), ws1.arena(), 4, true);
auto s4 = std::string(encoded);
assert(s4 == s3);
std::cout << "OK - two encodes with derived nonce are the same\n";
auto d4 = content_codec::decode(content_codec::CE_FS123_SECRETBOX, s4, sm);
assert(d4 == hello);
std::cout << "OK - roundtrip with derived_nonce=true\n";
// Now let's try to break things...
// First, let's check that the constructor fails when it's supposed to:
sharedkeydir smx(-1, "encode", 10);
// the constructor doesn't care that the file doesn't exist. but
// encode and decode do:
expect_throw("secretfile does not exist (encode)", [&](){
ws1.replace_content(hello);
smx.get_sharedkey(esid);
});
replace_sf("2\n",{
{"1", "12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678\n"}});
expect_throw("encode_sid not in sharedkeydir", [&](){
sharedkeydir smy(sffd, "encode", 1);
blob b(48, "hello", 1);
auto s = smy.get_sharedkey("2");
content_codec::encode(content_codec::CE_FS123_SECRETBOX, "2", s, b.content(), b.arena(), 1);
});
replace_sf("1\n",
{{"abc", " 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678\n"},
{"1", "12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678\n"}});
try_to_use_sfname(); // shouldn't throw. abc is a perfectly good secretid
replace_sf("fred\n",{
{"fred", "barney 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678\n"},
{"1", "12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678\n"}
});
expect_throw("keyfile has non-hex", [&](){ try_to_use_sfname(); });
replace_sf("1\n", {
{"22", "12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 xyz\n"},
{"1", " 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678 12345678\n"}
});
try_to_use_sfname(); // it's not a problem to use keyid=1.
expect_throw("non-numeric secret in secretfile", [&](){
sharedkeydir cc(sffd, "encode", 1);
cc.get_sharedkey("22");
});
return 0;
}catch(std::exception& e){
for(auto& v : exnest(e))
std::cout << v.what() << "\n";
std::cout << "FAIL\n";
exit(1);
}
| 42.989848 | 144 | 0.641634 | mheily |
c251ad3d91af6bcb12018fa938354462eb5b1d5a | 1,492 | cpp | C++ | assignment4/main.cpp | connorramsden/game-architecture | 52a1a7bedad8ccc2c73cd43c14fc8165f608b2ce | [
"MIT"
] | null | null | null | assignment4/main.cpp | connorramsden/game-architecture | 52a1a7bedad8ccc2c73cd43c14fc8165f608b2ce | [
"MIT"
] | null | null | null | assignment4/main.cpp | connorramsden/game-architecture | 52a1a7bedad8ccc2c73cd43c14fc8165f608b2ce | [
"MIT"
] | null | null | null | /*********************************************************************
** Author: Connor Ramsden **
** Class: EGP-310-02 **
** Assignment: Assignment 04 **
** Certification of Authenticity: **
** I certify that this assignment is entirely my own work. **
** Assignment 04 Author: Connor Ramsden **
*********************************************************************/
/*
Disclosures:
1. I BORROWED Nick Da Costa's Assignment 02 as a baseline for my Assignment 03 work.
This was done with EXPLICIT PERMISSION from the author.
I have NOT removed his certificate(s) of authenticity from his files so that this is clearly apparent.
2. I did NOT borrow anyone's work for the assignment 03 files used to start Assignment 04
3. NO other help was received in the creation of this assignmnet
*/
// C/C++ Includes
#include <iostream>
#include <string>
// DeanLib Includes
#include <MemoryTracker.h>
// GraphicsLib Includes
#include "Game.h"
int main()
{
// Initialize a Game instance
Game::initInstance();
// Instantiate a Game object from the initialized instance
gpGame = Game::getGameInstance();
// Run the core game loop
gpGame->runGameLoop();
// When the game loop breaks, clean up the Game instance
Game::cleanupInstance();
// Report memory leaks to console
MemoryTracker::getInstance()->reportAllocations(std::cout);
// Wait for user input before returning
system("pause");
// Exit the console window
return 0;
} | 29.254902 | 104 | 0.636729 | connorramsden |
c2521d12bdb8fd9b269635c2e8c1062c19b1df65 | 2,813 | cpp | C++ | src/render/circle/renderCircle.cpp | ilidemi/visa-viz | 2f7eb55b9f2b2dedf0b7dbe224cfda59f1958926 | [
"MIT"
] | 11 | 2021-11-29T10:32:29.000Z | 2022-02-13T12:11:26.000Z | src/render/circle/renderCircle.cpp | ilidemi/visa-viz | 2f7eb55b9f2b2dedf0b7dbe224cfda59f1958926 | [
"MIT"
] | null | null | null | src/render/circle/renderCircle.cpp | ilidemi/visa-viz | 2f7eb55b9f2b2dedf0b7dbe224cfda59f1958926 | [
"MIT"
] | null | null | null | #pragma once
#include "../../util/util.cpp"
#include "../common/canvasContext.cpp"
#include "../common/color.cpp"
#include "../common/coordinateSpace.cpp"
#include "../common/glUtil.cpp"
#include <emscripten.h>
struct LayoutedCircle
{
CoordinateSpace coordinateSpace;
float x, y;
float size;
Color color;
static LayoutedCircle createScreen(float x, float y, float size, Color color)
{
return { CoordinateSpace::Screen, x, y, size, color };
}
};
struct CircleRenderer
{
GLuint program;
GLuint posPos, sizePos, matPos, colorPos;
GLuint textureUvPos;
CanvasContext *canvasCtx;
GLuint quad;
void init(CanvasContext *canvasCtx, GLuint vertexShader, GLuint quad)
{
const char fragmentShaderCode[] =
#include "circleFragmentShader.glsl"
GLuint fragmentShader = compileShader(GL_FRAGMENT_SHADER, fragmentShaderCode);
this->program = createProgram(vertexShader, fragmentShader);
this->posPos = glGetUniformLocation(this->program, "pos");
this->sizePos = glGetUniformLocation(this->program, "size");
this->matPos = glGetUniformLocation(this->program, "mat");
this->colorPos = glGetUniformLocation(this->program, "color");
this->textureUvPos = glGetAttribLocation(this->program, "textureUv");
this->canvasCtx = canvasCtx;
this->quad = quad;
}
void render(LayoutedCircle *circle, float displayViewportX, float displayViewportY)
{
float displayX = circle->x;
float displayY = circle->y;
if (circle->coordinateSpace == CoordinateSpace::Screen)
{
assertOrAbort(displayViewportX == 0, "Viewport is not applicable in screen space");
assertOrAbort(displayViewportY == 0, "Viewport is not applicable in screen space");
if (circle->x < 0)
{
displayX = this->canvasCtx->displayWidth + circle->x - circle->size;
}
if (circle->y < 0)
{
displayY = this->canvasCtx->displayHeight + circle->y - circle->size;
}
}
float mat[16];
initTransformationMatrix(mat, this->canvasCtx, displayViewportX, displayViewportY);
glUseProgram(this->program);
glUniform2f(this->posPos, displayX, displayY);
glUniform2f(this->sizePos, circle->size, circle->size);
glUniformMatrix4fv(this->matPos, 1, 0, mat);
glUniformColor4f(this->colorPos, circle->color);
glBindBuffer(GL_ARRAY_BUFFER, this->quad);
glEnableVertexAttribArray(this->textureUvPos);
glVertexAttribPointer(this->textureUvPos, 2, GL_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDisableVertexAttribArray(this->textureUvPos);
}
};
| 31.255556 | 95 | 0.646285 | ilidemi |
c254c1cda30211dcf84c866ed314dfcfbe6f7701 | 617 | hpp | C++ | include/httpserver/HttpServer.hpp | aetas/RoomHub | 9661c5a04a572ae99a812492db7091da07cf5789 | [
"MIT"
] | 8 | 2019-06-10T19:44:48.000Z | 2021-06-10T23:03:24.000Z | include/httpserver/HttpServer.hpp | aetas/RoomHub | 9661c5a04a572ae99a812492db7091da07cf5789 | [
"MIT"
] | 10 | 2019-05-15T21:01:54.000Z | 2021-01-16T23:08:53.000Z | include/httpserver/HttpServer.hpp | aetas/RoomHub | 9661c5a04a572ae99a812492db7091da07cf5789 | [
"MIT"
] | 2 | 2021-09-17T08:20:07.000Z | 2022-03-29T01:17:07.000Z | #pragma once
#include <WString.h>
#include <Client.h>
#include <functional>
#include "HttpMethod.hpp"
#include "ServerHandler.hpp"
class HttpServer {
public:
~HttpServer();
void handleClient(Client& client);
void on(HttpMethod method, const String& path, ServerHandler::THandlerFunction fn);
void send(int code, const String& content_type, const String& content);
private:
ServerHandler* handlers[16];
uint8_t handlersSize = 0;
Client* currentClient;
void handle(HttpMethod method, const String& path, const String& body);
HttpMethod methodFromString(String& methodString);
}; | 25.708333 | 87 | 0.730956 | aetas |
c26093993f9d174a9d7cc03b7606566b54e979d4 | 1,656 | hpp | C++ | fon9/io/win/IocpTcpServer.hpp | fonwin/Plan | 3bfa9407ab04a26293ba8d23c2208bbececb430e | [
"Apache-2.0"
] | 21 | 2019-01-29T14:41:46.000Z | 2022-03-11T00:22:56.000Z | fon9/io/win/IocpTcpServer.hpp | fonwin/Plan | 3bfa9407ab04a26293ba8d23c2208bbececb430e | [
"Apache-2.0"
] | null | null | null | fon9/io/win/IocpTcpServer.hpp | fonwin/Plan | 3bfa9407ab04a26293ba8d23c2208bbececb430e | [
"Apache-2.0"
] | 9 | 2019-01-27T14:19:33.000Z | 2022-03-11T06:18:24.000Z | /// \file fon9/io/win/IocpTcpServer.hpp
/// \author fonwinz@gmail.com
#ifndef __fon9_io_win_IocpTcpServer_hpp__
#define __fon9_io_win_IocpTcpServer_hpp__
#include "fon9/io/win/IocpSocket.hpp"
#include "fon9/io/TcpServerBase.hpp"
namespace fon9 { namespace io {
class IocpTcpListener;
/// \ingroup io
/// Windows TcpServer 使用 IOCP
using IocpTcpServer = TcpServerBase<IocpTcpListener, IocpServiceSP>;
using IocpTcpServerSP = DeviceSPT<IocpTcpServer>;
class fon9_API IocpTcpListener : public DeviceListener, public IocpHandler {
fon9_NON_COPY_NON_MOVE(IocpTcpListener);
class AcceptedClient;
/// (LocalAddressLength+16) + (RemoteAddressLength+16)
/// +16 是 Windows 的規定:
/// This value must be at least 16 bytes more than the maximum address length for the transport protocol in use.
char AcceptBuffer_[(sizeof(SocketAddress) + 16) * 2];
WSAOVERLAPPED ListenOverlapped_;
Socket ListenSocket_;
Socket ClientSocket_;
virtual void OnIocp_Error(OVERLAPPED* lpOverlapped, DWORD eno) override;
virtual void OnIocp_Done(OVERLAPPED* lpOverlapped, DWORD bytesTransfered) override;
void ResetupAccepter();
bool SetupAccepter(SocketResult& soRes);
virtual void OnListener_Dispose() override;
friend IocpTcpServer;
/// 必須啟動 dev.CommonTimerRunAfter(); 才會有此事件.
void OnTcpServer_OnCommonTimer();
IocpTcpListener(IocpServiceSP&& iosv, IocpTcpServerSP&& server, Socket&& soListen);
public:
const IocpTcpServerSP Server_;
static DeviceListenerSP CreateListener(IocpTcpServerSP server, SocketResult& soRes);
};
} } // namespaces
#endif//__fon9_io_win_IocpTcpServer_hpp__
| 33.12 | 115 | 0.759058 | fonwin |
c26ace84ba60c308c9044f91f45eba984ae6209c | 979 | hpp | C++ | AnimSprite.hpp | sim642/AirTraffic | f53451c2976923ef94ed44f96d94f753e4a038c8 | [
"MIT"
] | 2 | 2016-06-10T06:05:28.000Z | 2019-02-07T16:21:15.000Z | AnimSprite.hpp | sim642/AirTraffic | f53451c2976923ef94ed44f96d94f753e4a038c8 | [
"MIT"
] | 2 | 2015-07-06T12:16:28.000Z | 2016-12-20T20:12:53.000Z | AnimSprite.hpp | sim642/AirTraffic | f53451c2976923ef94ed44f96d94f753e4a038c8 | [
"MIT"
] | null | null | null | #ifndef ANIMSPRITE_H
#define ANIMSPRITE_H
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/System/Vector2.hpp>
class AnimSprite : public sf::Sprite
{
public:
AnimSprite(); // doesn't work properly
AnimSprite(const sf::Texture &texture, const sf::Vector2i &frameSize, const float &frameRate);
void setFrameSize(const sf::Vector2i &frameSize);
const sf::Vector2i& getFrameSize() const;
void setFrameRate(const float &frameRate);
const float getFrameRate() const;
void setFrame(const unsigned int &frame);
const unsigned int& getFrame() const;
const unsigned int getFrameCount() const;
void resetTime();
void update(const float &FT);
void updateRect();
private:
sf::Vector2i myFrameSize;
sf::Vector2i myFrameCount;
float myFrameTime; // unsure about framerate 0.f
unsigned int myFrame;
float myTime;
};
#endif // ANIMSPRITE_H
| 25.763158 | 102 | 0.65475 | sim642 |
c26c253bc884ddf59257612a8fabc2818a1f4d76 | 909 | cpp | C++ | unused/tinyxml_test2.cpp | tyt2y3/tinybind | 04a50a813521b468ae3994f848baac0c6f61e4dc | [
"Unlicense",
"MIT"
] | 18 | 2015-02-25T09:04:38.000Z | 2021-06-10T13:57:20.000Z | unused/tinyxml_test2.cpp | chinarouter/tinybind2 | d4e898332cdfd1ecf47cee382ad1d8b3f0cabf11 | [
"Unlicense",
"MIT"
] | 1 | 2016-03-18T11:03:31.000Z | 2016-03-24T17:32:56.000Z | unused/tinyxml_test2.cpp | tyt2y3/tinybind | 04a50a813521b468ae3994f848baac0c6f61e4dc | [
"Unlicense",
"MIT"
] | 12 | 2015-04-09T06:34:49.000Z | 2020-06-09T11:42:22.000Z | #include <stdio.h>
#include <stdlib.h>
#include "svg_cpp_definition.h"
#include "../tinyxml/tinyxml.h"
#include "../tinyxml/tinyxml.cpp"
#include "../tinyxml/tinyxmlerror.cpp"
#include "../tinyxml/tinyxmlparser.cpp"
#include "../tinyxml/tinystr.cpp"
#include "../tinyxml/tinystr.h"
#include "win32com.h" //to solve "error: ‘stricmp’ was not declared in this scope"
namespace svg_de
{
//helper functions
void attr_tostruct( TiXmlElement* xmle, const char* attr_content, const char* attr_name)
{
*attr_content = xmle->Attribute( attr_name);
}
void attr_toxml( TiXmlElement* xmle, const char* attr_content, const char* attr_name)
{
xmle->SetAttribute( attr_name, *attr_content);
}
void svg::print()
{
printf("xmlns: %s, xmlns:xlink: %s\n", xmlns, xmlns_xlink);
}
int main()
{
svg SVG;
SVG.xmlns="hello";
SVG.xmlns_xlink="world";
SVG.print();
}
}
//this does not work anymore
//just for experimenting
| 22.725 | 88 | 0.718372 | tyt2y3 |
c26d52188ca2228890315622355f3a45b8afb063 | 175 | cpp | C++ | interpreter/AST/ASTIfElseStatementNode.cpp | FlareCoding/Trent | afaf81d2854aaf4f394036e78a8df4b361177753 | [
"MIT"
] | 4 | 2021-07-16T12:25:25.000Z | 2021-12-11T08:52:09.000Z | interpreter/AST/ASTIfElseStatementNode.cpp | FlareCoding/Trent | afaf81d2854aaf4f394036e78a8df4b361177753 | [
"MIT"
] | null | null | null | interpreter/AST/ASTIfElseStatementNode.cpp | FlareCoding/Trent | afaf81d2854aaf4f394036e78a8df4b361177753 | [
"MIT"
] | null | null | null | #include "ASTIfElseStatementNode.h"
namespace trent
{
ASTIfElseStatementNode::ASTIfElseStatementNode()
{
this->d_type = ASTNodeType::IfElseStatement;
}
}
| 17.5 | 52 | 0.708571 | FlareCoding |
c26f78c565aa905f78a26a60cbc68d34535a5f88 | 250 | cc | C++ | c++/basic/DS/stl/vector.cc | dannypsnl/languages-learn | 2351a235bd55e720394111237d41f65482eb89ec | [
"MIT"
] | 2 | 2018-01-04T00:47:25.000Z | 2018-01-12T08:07:50.000Z | c++/basic/DS/stl/vector.cc | dannypsnl/languages-learn | 2351a235bd55e720394111237d41f65482eb89ec | [
"MIT"
] | 1 | 2018-01-08T14:45:55.000Z | 2018-01-09T05:02:09.000Z | c++/basic/DS/stl/vector.cc | dannypsnl/languages-learn | 2351a235bd55e720394111237d41f65482eb89ec | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <vector>
using std::vector;
void print(int i) { std::cout << i; }
int main() {
vector<int> L{1, 2, 3, 4, 5};
L.push_back(-1);
std::for_each(L.begin(), L.end(), print);
std::cout << '\n';
}
| 16.666667 | 43 | 0.584 | dannypsnl |
c2716eec98d32deb9c67074d7a30ea8f33cbbfef | 2,153 | cpp | C++ | z.cpp | pexeer/p-base | 14830facd0ba6831575ae271dd506071c90763aa | [
"BSD-3-Clause"
] | null | null | null | z.cpp | pexeer/p-base | 14830facd0ba6831575ae271dd506071c90763aa | [
"BSD-3-Clause"
] | null | null | null | z.cpp | pexeer/p-base | 14830facd0ba6831575ae271dd506071c90763aa | [
"BSD-3-Clause"
] | 1 | 2018-04-21T15:57:52.000Z | 2018-04-21T15:57:52.000Z | #include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "p/base/endpoint.h"
#include "p/base/socket.h"
#include <string>
#include <signal.h>
#include <assert.h>
int main() {
p::base::EndPoint endpoint;
printf("sizeof(EndPoint) == %lu\n", sizeof(endpoint));
if (endpoint) {
printf("endpoint true\n");
} else {
printf("endpoint false\n");
}
p::base::EndPoint edx(" www.baidu.com:8001 ");
if (edx) {
printf("ed0 true\n");
} else {
printf("ed0 false\n");
}
p::base::EndPoint ed0("www.baidu.com:8001");
if (ed0) {
printf("ed0 true\n");
} else {
printf("ed0 false\n");
}
p::base::EndPoint ed1("www.baidu.com:8001 ");
if (ed1) {
printf("ed1 true\n");
} else {
printf("ed1 false\n");
}
p::base::EndPoint ed2("www.baidu.com 8001");
if (ed2) {
printf("ed2 true\n");
} else {
printf("ed2 false\n");
}
p::base::EndPoint ed3("www.baidu.com:8001 9");
if (ed3) {
printf("ed3 true\n");
} else {
printf("ed3 false\n");
}
p::base::EndPoint ed4("www.baidu.com:");
if (ed4) {
printf("ed4 true\n");
} else {
printf("ed4 false\n");
}
p::base::EndPoint ed5("192.34:104");
if (ed5) {
printf("ed5 true\n");
} else {
printf("ed5 false\n");
}
p::base::Socket x;
p::base::EndPoint tmp("127.0.0.1", 9099);
// Ignore SIGPIPE.~
struct sigaction oldact;
if (sigaction(SIGPIPE, NULL, &oldact) != 0 ||
(oldact.sa_handler == NULL && oldact.sa_sigaction == NULL)) {
assert(nullptr == signal(SIGPIPE, SIG_IGN));
}
#if 1
if (tmp) {
if (0 == x.Connect(tmp)) {
printf("conect ok\n");
} else {
printf("conect failed\n");
}
} else {
printf("failed endpoint.\n");
return 1;
}
std::string buf(1024000, 'a');
while (true) {
ssize_t ret = x.Write(buf.data(), buf.size());
printf("%ld\n", ret);
sleep(1);
}
#endif
return 0;
}
| 21.107843 | 73 | 0.503484 | pexeer |
c27450f7ebbbe050edb7ccfa346adc3b5f2c4696 | 882 | cpp | C++ | BitEngine/src/BitEngine/Game/ECS/Transform2DComponent.cpp | MateusMP/BitEngine | 920bbf693b74cd87dc98703ee48b126785bcf4db | [
"Zlib"
] | 3 | 2018-01-15T17:12:15.000Z | 2020-01-28T22:39:41.000Z | BitEngine/src/BitEngine/Game/ECS/Transform2DComponent.cpp | MateusMP/BitEngine | 920bbf693b74cd87dc98703ee48b126785bcf4db | [
"Zlib"
] | null | null | null | BitEngine/src/BitEngine/Game/ECS/Transform2DComponent.cpp | MateusMP/BitEngine | 920bbf693b74cd87dc98703ee48b126785bcf4db | [
"Zlib"
] | null | null | null | #include "BitEngine/Game/ECS/Transform2DComponent.h"
#include <math.h>
namespace BitEngine {
Transform2DComponent::Transform2DComponent()
: position(0.0f, 0.0f)
, scale(1.0f, 1.0f)
, rotation(0.0f)
, m_dirty(true)
{
}
Transform2DComponent::~Transform2DComponent()
{
}
const Vec2& Transform2DComponent::getLocalPosition() const
{
return position;
}
void Transform2DComponent::setLocalPosition(const Vec2& p)
{
position = p;
m_dirty = true;
}
const Vec2& Transform2DComponent::getLocalScale() const
{
return scale;
}
void Transform2DComponent::setLocalScale(const Vec2& s)
{
scale = s;
m_dirty = true;
}
float Transform2DComponent::getLocalRotation() const
{
return rotation;
}
void Transform2DComponent::setLocalRotation(float rad)
{
rotation = rad;
m_dirty = true;
}
}
| 16.961538 | 59 | 0.665533 | MateusMP |
c27ac0da460dcdbff5e35777d8ca5d3aff04fb3d | 653 | hpp | C++ | nd-coursework/books/cpp/C++Templates/traits/removecv.hpp | crdrisko/nd-grad | f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44 | [
"MIT"
] | 1 | 2020-09-26T12:38:55.000Z | 2020-09-26T12:38:55.000Z | nd-coursework/books/cpp/C++Templates/traits/removecv.hpp | crdrisko/nd-research | f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44 | [
"MIT"
] | null | null | null | nd-coursework/books/cpp/C++Templates/traits/removecv.hpp | crdrisko/nd-research | f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44 | [
"MIT"
] | null | null | null | // Copyright (c) 2017 by Addison-Wesley, David Vandevoorde, Nicolai M. Josuttis, and Douglas Gregor. All rights reserved.
// See the LICENSE file in the project root for move information.
//
// Name: removecv.hpp
// Author: crdrisko
// Date: 08/18/2020-13:16:29
// Description: A trait for removing const and volatile qualifiers from a template parameter, based off std::remove_cv<>
#ifndef REMOVECV_HPP
#define REMOVECV_HPP
#include "removeconst.hpp"
#include "removevolatile.hpp"
template<typename T>
struct RemoveCVT : RemoveConstT<typename RemoveVolatileT<T>::Type> {};
template<typename T>
using RemoveCV = typename RemoveCVT<T>::Type;
#endif
| 29.681818 | 121 | 0.762634 | crdrisko |
c27afd4333d768abf5b3160e1ff80c55195fbc3d | 2,508 | cpp | C++ | class 16 - solve class/N.cpp | pioneerAlpha/CP_Beginner_B4_Amar_iSchool | 271a851cfaf570e9dbde390574c9b0a419299823 | [
"MIT"
] | null | null | null | class 16 - solve class/N.cpp | pioneerAlpha/CP_Beginner_B4_Amar_iSchool | 271a851cfaf570e9dbde390574c9b0a419299823 | [
"MIT"
] | null | null | null | class 16 - solve class/N.cpp | pioneerAlpha/CP_Beginner_B4_Amar_iSchool | 271a851cfaf570e9dbde390574c9b0a419299823 | [
"MIT"
] | 1 | 2021-04-01T16:35:53.000Z | 2021-04-01T16:35:53.000Z | //#include<cstdio>
//#include<cassert>
//#include<iostream>
//#include<cstring>
//#include<algorithm>
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
#define MAX ((int)2e9 + 5)
#define MAXP ((int)1e5 + 5)
#define MAXL ((ll)1e18 + 5)
#define MAX_X ((int)2001)
#define MAX_Y ((int)2001)
#define pi acos(-1)
#define MOD ((int)1e9 + 7)
//#define MOD ((int)998244353 + 0)
#define BAS ((int)1e6 + 3)
//#define BAS ((int)2e5 + 3)
#define N ((int)1e5 + 9)
#define eps (1e-8)
#define fastio ios_base::sync_with_stdio(false),cin.tie(NULL)
#define logn 17
#define endl "\n"
#define mpp make_pair
#define BUCK 105
#define LEF (idx<<1)
#define RIG ((idx<<1)|1)
//#define int ll
//#pragma GCC optimize("Ofast,unroll-loops")
//#pragma GCC target("avx,avx2,fma")
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef unsigned long long ull;
/*fast io
ios_base::sync_with_stdio(false);
cin.tie(NULL);
*/
typedef tree < int, null_type, less < int >, rb_tree_tag, tree_order_statistics_node_update > o_set;
typedef tree < pair < int, int >, null_type, less < pair < int, int > >, rb_tree_tag, tree_order_statistics_node_update > o_setp;
/// o_set s;
/// s.order_of_key(k) : Number of items strictly smaller than k .
/// *(s.find_by_order(k)) : K-th element in a set (counting from zero).
typedef long double ldd;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int my_rand(int l, int r)
{
return uniform_int_distribution<int>(l,r) (rng);
}
int arr[N];
int srch(vector < int >& vec, int val) /// returns the index of the last element
{ /// from left which is less than or equal to val
int L = 0 , R = (int)vec.size() - 1;
while(L<R){
int mid = (L+R+1)>>1;
if(vec[mid] <= val) L = mid;
else R = mid-1;
}
return L;
}
int main()
{
fastio;
int t ,caseno = 1;
cin>>t;
while(t--){
int n , q;
cin>>n>>q;
vector < int > from , too;
for(int i = 1 ; i<=n ; i++){
int a , b;
cin>>a>>b;
from.push_back(a);
too.push_back(b);
}
from.push_back(-1);
too.push_back(-1);
sort(from.begin() , from.end());
sort(too.begin() , too.end());
cout<<"Case "<<caseno++<<":\n";
while(q--){
int x;
cin>>x;
cout<<srch(from,x) - srch(too,x-1)<<endl;
}
}
return 0;
}
| 24.349515 | 133 | 0.586922 | pioneerAlpha |
c27f7267a54efc548706f6d22dbb5cd266ae9545 | 1,706 | cpp | C++ | src/cube/src/syntax/cubepl/evaluators/nullary/CubeSizeOfVariableEvaluation.cpp | OpenCMISS-Dependencies/cube | bb425e6f75ee5dbdf665fa94b241b48deee11505 | [
"Cube"
] | null | null | null | src/cube/src/syntax/cubepl/evaluators/nullary/CubeSizeOfVariableEvaluation.cpp | OpenCMISS-Dependencies/cube | bb425e6f75ee5dbdf665fa94b241b48deee11505 | [
"Cube"
] | null | null | null | src/cube/src/syntax/cubepl/evaluators/nullary/CubeSizeOfVariableEvaluation.cpp | OpenCMISS-Dependencies/cube | bb425e6f75ee5dbdf665fa94b241b48deee11505 | [
"Cube"
] | 2 | 2016-09-19T00:16:05.000Z | 2021-03-29T22:06:45.000Z | /****************************************************************************
** CUBE http://www.scalasca.org/ **
*****************************************************************************
** Copyright (c) 1998-2016 **
** Forschungszentrum Juelich GmbH, Juelich Supercomputing Centre **
** **
** Copyright (c) 2009-2015 **
** German Research School for Simulation Sciences GmbH, **
** Laboratory for Parallel Programming **
** **
** This software may be modified and distributed under the terms of **
** a BSD-style license. See the COPYING file in the package base **
** directory for details. **
****************************************************************************/
#ifndef __SIZEOF_VARIABLE_EVALUATION_CPP
#define __SIZEOF_VARIABLE_EVALUATION_CPP 0
#include <iomanip>
#include <sstream>
#include "CubeSizeOfVariableEvaluation.h"
using namespace cube;
using namespace std;
SizeOfVariableEvaluation::~SizeOfVariableEvaluation()
{
}
double
SizeOfVariableEvaluation::eval()
{
return ( double )( memory->size_of( variable, kind ) );
}
string
SizeOfVariableEvaluation::strEval()
{
size_t _size = memory->size_of( variable, kind );
stringstream sstr;
string str;
sstr << setprecision( 14 ) << _size;
sstr >> str;
return str;
}
#endif
| 32.807692 | 77 | 0.439039 | OpenCMISS-Dependencies |
c2865cc9a99a4f458353c2a42a14d5f1792f60a2 | 1,077 | hpp | C++ | libs/core/include/fcppt/type_traits/integral_cast.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 13 | 2015-02-21T18:35:14.000Z | 2019-12-29T14:08:29.000Z | libs/core/include/fcppt/type_traits/integral_cast.hpp | cpreh/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 5 | 2016-08-27T07:35:47.000Z | 2019-04-21T10:55:34.000Z | libs/core/include/fcppt/type_traits/integral_cast.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 8 | 2015-01-10T09:22:37.000Z | 2019-12-01T08:31:12.000Z | // Copyright Carl Philipp Reh 2009 - 2021.
// 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)
#ifndef FCPPT_TYPE_TRAITS_INTEGRAL_CAST_HPP_INCLUDED
#define FCPPT_TYPE_TRAITS_INTEGRAL_CAST_HPP_INCLUDED
#include <fcppt/type_traits/detail/integral_cast_value.hpp>
#include <fcppt/config/external_begin.hpp>
#include <type_traits>
#include <fcppt/config/external_end.hpp>
namespace fcppt::type_traits
{
/**
\brief Does an integral cast on an integral constant
\ingroup fcppttype_traits
Casts \a Integral to an integral constant of type \a Dest. The cast is
done using \a Conv from fcppt.casts.
\tparam Dest An integral type to cast to
\tparam Conv A cast function from fcppt.casts
\tparam Integral A std::integral_constant to cast from
*/
template <typename Dest, typename Conv, typename Integral>
using integral_cast = std::integral_constant<
Dest,
fcppt::type_traits::detail::integral_cast_value<Dest, Conv, Integral>::value>;
}
#endif
| 28.342105 | 82 | 0.770659 | freundlich |
c28af2357b2c407a57df19f07d1134a04acc3b6a | 2,656 | cpp | C++ | Tree_Fractal/Tree.cpp | freddyox/ROOT | 214a7d55f8c50ec27769bd85260a1746746d3b4c | [
"MIT"
] | null | null | null | Tree_Fractal/Tree.cpp | freddyox/ROOT | 214a7d55f8c50ec27769bd85260a1746746d3b4c | [
"MIT"
] | null | null | null | Tree_Fractal/Tree.cpp | freddyox/ROOT | 214a7d55f8c50ec27769bd85260a1746746d3b4c | [
"MIT"
] | null | null | null | #include "Tree.hh"
#include "TApplication.h"
#include <cmath>
#include <iostream>
Tree::Tree(){
fDisx = 1300;
fDisy = 1000;
xhat = TVector2(1.0,0.0);
yhat = TVector2(0.0,1.0);
fCanvas = new TCanvas("c1","Tree Fractal",0,1000,fDisx,fDisy);
fCanvas->SetFillColor(1);
deg2rad = TMath::Pi()/180.0;
fIter = 15;
fLength = 0.3;
fOrigin = TVector2(0.5,0.5);
fOffsetY = fLength;
GenerateTree();
}
void Tree::GenerateTree(){
TLine *trunk = new TLine( fOrigin.X(), fOrigin.Y() - fLength/2.0 - fOffsetY,
fOrigin.X(), fOrigin.Y()+fLength/2.0 - fOffsetY );
trunk->SetLineColor(kOrange+2);
for( fTheta = 0; fTheta < 361; fTheta++ ) {
int dummy = 0;
fBranches.clear();
fBranches.push_back( trunk );
fStorage.clear();
fTemp.clear();
fStorage = fBranches;
while( dummy < fIter ) {
if( dummy > 0 ){
fStorage.clear();
fStorage = fTemp;
fTemp.clear();
}
for( fVit=fStorage.begin(); fVit!=fStorage.end(); fVit++ ){
// Grab Coordinates:
TVector2 bot( (*fVit)->GetX1(), (*fVit)->GetY1() );
TVector2 top( (*fVit)->GetX2(), (*fVit)->GetY2() );
double length = (top-bot).Mod();
// Lets generate two more with these dimensions:
double next_length = length*0.65;
// Build a "normal"
TVector2 nhat = (top-bot).Unit();
double ang_wrt_x = (TMath::ACos(nhat*xhat))/deg2rad;
// Next starting point
TVector2 nstart = top;
for( int i=1; i<3; i++ ){
double ang = ang_wrt_x + pow(-1,i)*fTheta;
if( nhat*yhat < 0 ) { ang = -ang_wrt_x + pow(-1,i)*fTheta;}
TVector2 next_nhat( cos(ang*deg2rad), sin(ang*deg2rad) );
TVector2 end = nstart + next_length*next_nhat;
TLine *branch = new TLine( nstart.X(), nstart.Y(), end.X(), end.Y() );
if( dummy >= 0 && dummy <=1 ) {
branch->SetLineColor(kGreen+3);
}
if( dummy >= 2 && dummy <=3 ) {
branch->SetLineColor(kGreen+1);
}
if( dummy >= 4 && dummy < fIter-2 ) {
branch->SetLineColor(kGreen);
}
if( dummy == fIter-2){
branch->SetLineColor(kRed);
}
if( dummy == fIter-1 ) {
branch->SetLineColor(kPink+10);
}
fBranches.push_back( branch );
fTemp.push_back( branch );
}
}
dummy++;
}
fCanvas->Clear();
Draw();
TString temp;
temp.Form("%d",fTheta);
TString title = "Screenshots1/FractalTree_" + temp + ".png";
fCanvas->SaveAs(title);
}
}
void Tree::Draw(){
if( !fBranches.empty() ){
for( fVit=fBranches.begin(); fVit!=fBranches.end(); fVit++){
(*fVit)->Draw("gl");
}
}
}
int main(int argc, char **argv ) {
TApplication theApp("App",&argc, argv);
new Tree();
theApp.Run();
return 0;
}
| 23.927928 | 78 | 0.587349 | freddyox |
c28bfdd83cea8d3b43c59f9c0f4015e5a714c126 | 1,966 | cpp | C++ | lib/passes/manager.cpp | llpm/llpm | 47000202b2bb5f09cf739b9094f948744f6d72d2 | [
"Apache-2.0"
] | 1 | 2021-11-28T14:56:21.000Z | 2021-11-28T14:56:21.000Z | lib/passes/manager.cpp | llpm/llpm | 47000202b2bb5f09cf739b9094f948744f6d72d2 | [
"Apache-2.0"
] | null | null | null | lib/passes/manager.cpp | llpm/llpm | 47000202b2bb5f09cf739b9094f948744f6d72d2 | [
"Apache-2.0"
] | null | null | null | #include "manager.hpp"
#include <llpm/module.hpp>
#include <util/misc.hpp>
#include <backends/graphviz/graphviz.hpp>
#include <boost/format.hpp>
using namespace std;
namespace llpm {
void PassManager::debug(Pass* p, Module* mod) {
unsigned ctr = _debugCounter[mod];
string fn = str(boost::format("%1%_%2%%3$03u.gv")
% mod->name()
% _name
% ctr);
auto f =_design.workingDir()->create(fn);
_design.gv()->writeModule(
f,
mod,
true,
"After pass " + cpp_demangle(typeid(*p).name()));
_debugCounter[mod]++;
f->close();
}
bool PassManager::run(bool debug) {
bool ret = false;
for (auto&& p: _passes) {
printf("== Pass: %s\n", cpp_demangle(typeid(*p).name()).c_str());
if(p->run()) {
ret = true;
if (debug)
for (Module* mod: _design.modules())
this->debug(p.get(), mod);
}
}
return ret;
}
bool PassManager::run(Module* mod, bool debug) {
bool ret = false;
for (auto&& p: _passes) {
printf("== Pass: %s\n", cpp_demangle(typeid(*p).name()).c_str());
ModulePass* mp = dynamic_cast<ModulePass*>(p.get());
if (mp)
if (mp->run(mod))
ret = true;
LambdaModulePass historypass(_design,
[p](Module* m) {
std::set<Block*> blocks;
m->conns()->findAllBlocks(blocks);
for (Block* b: blocks) {
if (b->history().src() == BlockHistory::Unset) {
b->history().setUnknown();
b->history().meta(
cpp_demangle(typeid(*p).name()));
}
}
});
historypass.run(mod);
if (ret && debug)
this->debug(p.get(), mod);
}
mod->validityCheck();
return ret;
}
};
| 26.567568 | 73 | 0.476094 | llpm |
c291f1c847a3385e82e00b3e033a66a178d96f10 | 2,361 | cpp | C++ | LibPhysics/Intersection/Wm4ExtremalQuery3.cpp | wjezxujian/WildMagic4 | 249a17f8c447cf57c6283408e01009039810206a | [
"BSL-1.0"
] | 3 | 2021-08-02T04:03:03.000Z | 2022-01-04T07:31:20.000Z | LibPhysics/Intersection/Wm4ExtremalQuery3.cpp | wjezxujian/WildMagic4 | 249a17f8c447cf57c6283408e01009039810206a | [
"BSL-1.0"
] | null | null | null | LibPhysics/Intersection/Wm4ExtremalQuery3.cpp | wjezxujian/WildMagic4 | 249a17f8c447cf57c6283408e01009039810206a | [
"BSL-1.0"
] | 5 | 2019-10-13T02:44:19.000Z | 2021-08-02T04:03:10.000Z | // Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// The Wild Magic Version 4 Restricted Libraries source code is supplied
// under the terms of the license agreement
// http://www.geometrictools.com/License/Wm4RestrictedLicense.pdf
// and may not be copied or disclosed except in accordance with the terms
// of that agreement.
#include "Wm4PhysicsPCH.h"
#include "Wm4ExtremalQuery3.h"
namespace Wm4
{
//----------------------------------------------------------------------------
template <class Real>
ExtremalQuery3<Real>::ExtremalQuery3 (
const ConvexPolyhedron3<Real>& rkPolytope)
:
m_rkPolytope(rkPolytope)
{
// Create the triangle normals.
const Vector3<Real>* akVertex = m_rkPolytope.GetVertices();
int iTQuantity = m_rkPolytope.GetTQuantity();
const int* piIndex = m_rkPolytope.GetIndices();
m_akFaceNormal = WM4_NEW Vector3<Real>[iTQuantity];
for (int i = 0; i < iTQuantity; i++)
{
const Vector3<Real>& rkV0 = akVertex[*piIndex++];
const Vector3<Real>& rkV1 = akVertex[*piIndex++];
const Vector3<Real>& rkV2 = akVertex[*piIndex++];
Vector3<Real> kEdge1 = rkV1 - rkV0;
Vector3<Real> kEdge2 = rkV2 - rkV0;
m_akFaceNormal[i] = kEdge1.UnitCross(kEdge2);
}
}
//----------------------------------------------------------------------------
template <class Real>
ExtremalQuery3<Real>::~ExtremalQuery3 ()
{
WM4_DELETE[] m_akFaceNormal;
}
//----------------------------------------------------------------------------
template <class Real>
const ConvexPolyhedron3<Real>& ExtremalQuery3<Real>::GetPolytope () const
{
return m_rkPolytope;
}
//----------------------------------------------------------------------------
template <class Real>
const Vector3<Real>* ExtremalQuery3<Real>::GetFaceNormals () const
{
return m_akFaceNormal;
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// explicit instantiation
//----------------------------------------------------------------------------
template WM4_PHYSICS_ITEM
class ExtremalQuery3<float>;
template WM4_PHYSICS_ITEM
class ExtremalQuery3<double>;
//----------------------------------------------------------------------------
}
| 34.720588 | 78 | 0.523083 | wjezxujian |
c29ee2e6d7f88fd4489f5c143053aa3889998a43 | 2,485 | cpp | C++ | tests/day13_tests.cpp | beached/aoc_2017 | 553d42e50b81384ad93aae6e0aec624ca7c8bf58 | [
"MIT"
] | 1 | 2017-12-11T16:17:18.000Z | 2017-12-11T16:17:18.000Z | tests/day13_tests.cpp | beached/aoc_2017 | 553d42e50b81384ad93aae6e0aec624ca7c8bf58 | [
"MIT"
] | null | null | null | tests/day13_tests.cpp | beached/aoc_2017 | 553d42e50b81384ad93aae6e0aec624ca7c8bf58 | [
"MIT"
] | null | null | null | // The MIT License (MIT)
//
// Copyright (c) 2017 Darrell Wright
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files( the "Software" ), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#define BOOST_TEST_MODULE aoc_2017_day13
#include <daw/boost_test.h>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include "day13.h"
namespace daw {
namespace aoc_2017 {
namespace day13 {
BOOST_AUTO_TEST_CASE( test_001 ) {
std::vector<std::string> const tst = {"0: 3", "1: 2", "4: 4", "6: 4"};
auto const ans1 = severity( tst );
BOOST_REQUIRE_EQUAL( ans1, 24 );
auto const ans2 = min_cost( tst );
BOOST_REQUIRE_EQUAL( ans2, 10 );
}
BOOST_AUTO_TEST_CASE( test_002 ) {
std::vector<std::string> const tst = {
"0: 5", "1: 2", "2: 3", "4: 4", "6: 6", "8: 4", "10: 6", "12: 10", "14: 6", "16: 8", "18: 6",
"20: 9", "22: 8", "24: 8", "26: 8", "28: 12", "30: 12", "32: 8", "34: 8", "36: 12", "38: 14", "40: 12",
"42: 10", "44: 14", "46: 12", "48: 12", "50: 24", "52: 14", "54: 12", "56: 12", "58: 14", "60: 12", "62: 14",
"64: 12", "66: 14", "68: 14", "72: 14", "74: 14", "80: 14", "82: 14", "86: 14", "90: 18", "92: 17"};
auto const ans1 = severity( tst );
BOOST_REQUIRE_EQUAL( ans1, 788 );
std::cout << "Answer #1: " << ans1 << '\n';
auto const ans2 = min_cost( tst );
BOOST_REQUIRE_EQUAL( ans2, 3905748 );
std::cout << "Answer #2: " << ans2 << '\n';
}
} // namespace day13
} // namespace aoc_2017
} // namespace daw
| 41.416667 | 115 | 0.633803 | beached |
c2af820511d77ef8ee812586f066b3c5807dff6a | 4,960 | cpp | C++ | Source/Add On - Windows/CFilesystem-Windows-WinRT.cpp | StevoSM/CppToolbox | 11c73e083a4510797d7674e040e096bf5dc7ea2d | [
"MIT"
] | 1 | 2019-05-02T23:49:03.000Z | 2019-05-02T23:49:03.000Z | Source/Add On - Windows/CFilesystem-Windows-WinRT.cpp | StevoSM/CppToolbox | 11c73e083a4510797d7674e040e096bf5dc7ea2d | [
"MIT"
] | null | null | null | Source/Add On - Windows/CFilesystem-Windows-WinRT.cpp | StevoSM/CppToolbox | 11c73e083a4510797d7674e040e096bf5dc7ea2d | [
"MIT"
] | null | null | null | //----------------------------------------------------------------------------------------------------------------------
// CFilesystem-Windows-WinRT.cpp ©2021 Stevo Brock All rights reserved.
//----------------------------------------------------------------------------------------------------------------------
#include "CFilesystem.h"
#include "SError-Windows-WinRT.h"
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Storage.h>
using namespace winrt::Windows::Storage;
//----------------------------------------------------------------------------------------------------------------------
// MARK: Macros
#define CFilesystemReportErrorFileFolderX1(error, message, fileFolder) \
{ \
CLogServices::logError(error, message, __FILE__, __func__, __LINE__); \
fileFolder.logAsError(CString::mSpaceX4); \
}
#define CFilesystemReportErrorFileFolderX1AndReturnError(error, message, fileFolder) \
{ \
CLogServices::logError(error, message, __FILE__, __func__, __LINE__); \
fileFolder.logAsError(CString::mSpaceX4); \
\
return OI<SError>(error); \
}
#define CFilesystemReportErrorFileFolderX2AndReturnError(error, message, fileFolder1, fileFolder2) \
{ \
CLogServices::logError(error, message, __FILE__, __func__, __LINE__); \
fileFolder1.logAsError(CString::mSpaceX4); \
fileFolder2.logAsError(CString::mSpaceX4); \
\
return OI<SError>(error); \
}
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
// MARK: - CFilesystem
// MARK: Class methods
//----------------------------------------------------------------------------------------------------------------------
TIResult<SFoldersFiles> CFilesystem::getFoldersFiles(const CFolder& folder, bool deep)
//----------------------------------------------------------------------------------------------------------------------
{
AssertFailUnimplemented();
return TIResult<SFoldersFiles>(SError::mUnimplemented);
}
//----------------------------------------------------------------------------------------------------------------------
TIResult<TArray<CFolder> > CFilesystem::getFolders(const CFolder& folder, bool deep)
//----------------------------------------------------------------------------------------------------------------------
{
AssertFailUnimplemented();
return TIResult<TArray<CFolder> >(SError::mUnimplemented);
}
//----------------------------------------------------------------------------------------------------------------------
TIResult<TArray<CFile> > CFilesystem::getFiles(const CFolder& folder, bool deep)
//----------------------------------------------------------------------------------------------------------------------
{
// Catch errors
try {
// Setup
auto storageFolder =
StorageFolder::GetFolderFromPathAsync(folder.getFilesystemPath().getString().getOSString())
.get();
// Compose files
TNArray<CFile> files;
// Check deep
if (deep) {
// Iterate folders
for (auto const& childStorageFolder : storageFolder.GetFoldersAsync().get()) {
// Get files for this folder
auto result = getFiles(CFolder(CFilesystemPath(CString(childStorageFolder.Path().data()))));
if (result.hasInstance())
// Success
files += *result;
else
// Error
return TIResult<TArray<CFile> >(result.getError());
}
}
// Iterate files
for (auto const& storageFile : storageFolder.GetFilesAsync().get())
// Add file
files += CFile(CFilesystemPath(storageFile.Path().data()));
return TIResult<TArray<CFile> >(files);
} catch (const hresult_error& exception) {
// Error
SError error = SErrorFromHRESULTError(exception);
CFilesystemReportErrorFileFolderX1(error, "getting files", folder);
return TIResult<TArray<CFile>>(error);
}
}
//----------------------------------------------------------------------------------------------------------------------
OI<SError> CFilesystem::copy(const CFile& file, const CFolder& destinationFolder)
//----------------------------------------------------------------------------------------------------------------------
{
AssertFailUnimplemented();
return OI<SError>();
}
//----------------------------------------------------------------------------------------------------------------------
OI<SError> CFilesystem::replace(const CFile& sourceFile, const CFile& destinationFile)
//----------------------------------------------------------------------------------------------------------------------
{
AssertFailUnimplemented();
return OI<SError>();
}
| 41.333333 | 120 | 0.429435 | StevoSM |
c2afcde4c96739d99fae8e822319cb28f954f616 | 3,903 | cpp | C++ | src/parser/Parser.cpp | TimotheeDurand/SuperDeutschLerner3000 | 4a0cc676bd15db49d5b7aeb8cff1c88910bd69dc | [
"Unlicense"
] | 1 | 2018-03-17T08:01:46.000Z | 2018-03-17T08:01:46.000Z | src/parser/Parser.cpp | TimotheeDurand/SuperDeutschLerner3000 | 4a0cc676bd15db49d5b7aeb8cff1c88910bd69dc | [
"Unlicense"
] | 6 | 2018-02-27T13:19:26.000Z | 2018-03-26T21:06:52.000Z | src/parser/Parser.cpp | TimotheeDurand/SuperDeutschLerner3000 | 4a0cc676bd15db49d5b7aeb8cff1c88910bd69dc | [
"Unlicense"
] | 1 | 2018-03-01T09:24:28.000Z | 2018-03-01T09:24:28.000Z | #include "Parser.h"
#include <QDebug>
std::tuple<Lesson, Parser::IOStatus> Parser::parseFile (const QFileInfo& fileInfo)
{
QFile file (fileInfo.filePath ());
Lesson lesson;
if (file.open (QIODevice::ReadOnly | QIODevice::Text))
{
QTextStream in (&file);
in.setCodec ("UTF-8");
in >> lesson;
file.close ();
}
else return { lesson, CANNOT_OPEN_FILE };
return { lesson, SUCCESS };
}
Parser::IOStatus Parser::writeFile (Lesson & lesson, const QFileInfo& fileInfo)
{
QFile file (fileInfo.filePath ());
if (file.open (QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text))
{
QTextStream out(&file);
out.setCodec ("UTF-8");
out.setGenerateByteOrderMark (true);
out << lesson;
file.close ();
}
else return CANNOT_OPEN_FILE;
return SUCCESS;
}
QFileInfoList Parser::listLessonsInFolder (const QDir& dir)
{
return dir.entryInfoList ({ QString ("*") + QString (DEFAULT_LESSON_FILE_EXTENSION) });;
}
QString Parser::MoveFileToTrash (const QFileInfo & fileInfo)
{
return MoveToTrashImpl (fileInfo);
}
#ifdef Q_OS_WIN32
#include "windows.h"
QString Parser::MoveToTrashImpl (const QFileInfo & fileinfo) {
if (!fileinfo.exists ())
return "File doesnt exists, cant move to trash";
WCHAR from[MAX_PATH];
memset (from, 0, sizeof (from));
int l = fileinfo.absoluteFilePath ().toWCharArray (from);
Q_ASSERT (0 <= l && l < MAX_PATH);
from[l] = '\0';
SHFILEOPSTRUCTW fileop;
memset (&fileop, 0, sizeof (fileop));
fileop.wFunc = FO_DELETE;
fileop.pFrom = from;
fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT;
int rv = SHFileOperationW (&fileop);
if (0 != rv) {
qDebug () << rv << QString::number (rv).toInt (0, 8);
return "move to trash failed";
}
fileinfo.absoluteFilePath ();
return "";
}
#endif
#ifdef Q_OS_LINUX
bool TrashInitialized = false;
QString TrashPath;
QString TrashPathInfo;
QString TrashPathFiles;
QString Parser::MoveToTrashImpl (const QFileInfo & fileinfo) {
if (!TrashInitialized) {
QStringList paths;
const char* xdg_data_home = getenv ("XDG_DATA_HOME");
if (xdg_data_home) {
qDebug () << "XDG_DATA_HOME not yet tested";
QString xdgTrash (xdg_data_home);
paths.append (xdgTrash + "/Trash");
}
QString home = QStandardPaths::writableLocation (QStandardPaths::HomeLocation);
paths.append (home + "/.local/share/Trash");
paths.append (home + "/.trash");
foreach (QString path, paths) {
if (TrashPath.isEmpty ()) {
QDir dir (path);
if (dir.exists ()) {
TrashPath = path;
}
}
}
if (TrashPath.isEmpty ())
return "Cant detect trash folder";
TrashPathInfo = TrashPath + "/info";
TrashPathFiles = TrashPath + "/files";
if (!QDir (TrashPathInfo).exists () || !QDir (TrashPathFiles).exists ())
return "Trash doesnt looks like FreeDesktop.org Trash specification";
TrashInitialized = true;
}
QFileInfo original = fileinfo;
if (!original.exists ())
return "File doesnt exists, cant move to trash";
QString info;
info += "[Trash Info]\nPath=";
info += original.absoluteFilePath ();
info += "\nDeletionDate=";
info += QDateTime::currentDateTime ().toString ("yyyy-MM-ddThh:mm:ss.zzzZ");
info += "\n";
QString trashname = original.fileName ();
QString infopath = TrashPathInfo + "/" + trashname + ".trashinfo";
QString filepath = TrashPathFiles + "/" + trashname;
int nr = 1;
while (QFileInfo (infopath).exists () || QFileInfo (filepath).exists ()) {
nr++;
trashname = original.baseName () + "." + QString::number (nr);
if (!original.completeSuffix ().isEmpty ()) {
trashname += QString (".") + original.completeSuffix ();
}
infopath = TrashPathInfo + "/" + trashname + ".trashinfo";
filepath = TrashPathFiles + "/" + trashname;
}
QDir dir;
if (!dir.rename (original.absoluteFilePath (), filepath)) {
return "move to trash failed";
}
File infofile;
infofile.createUtf8 (infopath, info);
return "";
}
#endif
| 27.680851 | 89 | 0.683321 | TimotheeDurand |
c2afffcf75ee0b3b7e7ea41851f8378261cf2718 | 16,009 | cpp | C++ | src/addressgroup.cpp | Peter2121/nmdaemon | 3edc679d634838b96f83d36644a250980c430f21 | [
"BSD-3-Clause"
] | 2 | 2021-12-05T13:44:57.000Z | 2021-12-06T19:09:30.000Z | src/addressgroup.cpp | Peter2121/nmdaemon | 3edc679d634838b96f83d36644a250980c430f21 | [
"BSD-3-Clause"
] | null | null | null | src/addressgroup.cpp | Peter2121/nmdaemon | 3edc679d634838b96f83d36644a250980c430f21 | [
"BSD-3-Clause"
] | null | null | null | #include "addressgroup.h"
AddressGroup::AddressGroup(struct ifaddrs* ifa) : flags(0), isAddrRunning(false), isAddrPrimary(false)
{
if(ifa==nullptr)
throw nmExcept;
if(ifa->ifa_addr==nullptr)
throw nmExcept;
if(ifa->ifa_addr->sa_family == AF_LINK)
ipType = AddressGroupType::LINK;
else if( (ifa->ifa_flags & IFF_POINTOPOINT ) != 0 )
ipType = AddressGroupType::PPP;
else if(ifa->ifa_addr->sa_family==AF_INET6)
ipType = AddressGroupType::BCAST;
else if((ifa->ifa_broadaddr) && (ifa->ifa_addr->sa_family==AF_INET))
ipType = AddressGroupType::BCAST;
else
throw nmExcept;
if( (ifa->ifa_flags & IFF_LOOPBACK) != 0 )
ipType = AddressGroupType::LOOPBACK;
if( (ifa->ifa_flags & IFF_UP) != 0 )
isAddrUp = true;
else
isAddrUp = false;
if( (ifa->ifa_flags & IFF_RUNNING) != 0 )
isAddrRunning = true;
else
isAddrRunning = false;
std::string if_name = std::string(ifa->ifa_name);
std::string def_addr;
switch(ifa->ifa_addr->sa_family)
{
case AF_INET:
spIpAddress = std::make_shared<AddressIp4>(reinterpret_cast<sockaddr_in*>(ifa->ifa_addr));
if(ifa->ifa_netmask)
{
spIpMask = std::make_shared<AddressIp4>(reinterpret_cast<sockaddr_in*>(ifa->ifa_netmask));
}
else
throw nmExcept;
def_addr = Tool::getIfPrimaryAddr4(if_name);
if( !def_addr.empty() && (def_addr==spIpAddress->getStrAddr()) )
isAddrPrimary = true;
switch(ipType)
{
case AddressGroupType::BCAST:
case AddressGroupType::LOOPBACK:
if(ifa->ifa_broadaddr)
{
spIpData = std::make_shared<AddressIp4>(reinterpret_cast<sockaddr_in*>(ifa->ifa_broadaddr));
}
else
throw nmExcept;
break;
case AddressGroupType::PPP:
case AddressGroupType::ROUTE:
// We can have only IPv4 or only IPv6 ifa_dstaddr not the both
// In such case ifa->ifa_dstaddr->sa_family is 0
if( (ifa->ifa_dstaddr) && (ifa->ifa_dstaddr->sa_family==AF_INET) )
{
spIpData = std::make_shared<AddressIp4>(reinterpret_cast<sockaddr_in*>(ifa->ifa_dstaddr));
}
break;
default:
break;
}
break; // end of case AF_INET
case AF_INET6:
spIpAddress = std::make_shared<AddressIp6>(reinterpret_cast<sockaddr_in6*>(ifa->ifa_addr));
if(ifa->ifa_netmask)
{
spIpMask = std::make_shared<AddressIp6>(reinterpret_cast<sockaddr_in6*>(ifa->ifa_netmask));
}
else
throw nmExcept;
switch(ipType)
{
case AddressGroupType::BCAST:
if(ifa->ifa_broadaddr)
{
spIpData = std::make_shared<AddressIp6>(reinterpret_cast<sockaddr_in6*>(ifa->ifa_broadaddr));
}
break;
case AddressGroupType::PPP:
case AddressGroupType::ROUTE:
// We can have only IPv4 or only IPv6 ifa_dstaddr not the both
// In such case ifa->ifa_dstaddr->sa_family is 0
if( (ifa->ifa_dstaddr) && (ifa->ifa_dstaddr->sa_family==AF_INET6) )
{
spIpData = std::make_shared<AddressIp6>(reinterpret_cast<sockaddr_in6*>(ifa->ifa_dstaddr));
}
break;
default:
break;
}
break; // end of case AF_INET6
case AF_LINK:
spIpAddress = std::make_shared<AddressLink>(reinterpret_cast<sockaddr_dl*>(ifa->ifa_addr));
break;
default:
throw nmExcept;
break;
}
}
AddressGroup::AddressGroup( std::shared_ptr<AddressBase> addr,
std::shared_ptr<AddressBase> mask,
std::shared_ptr<AddressBase> data,
AddressGroupType type, bool up, int fl, bool primary, bool running) :
ipType(type), spIpAddress(addr), spIpMask(mask), spIpData(data), flags(fl), isAddrUp(up), isAddrRunning(running), isAddrPrimary(primary)
{
}
AddressGroup::AddressGroup() :
ipType(AddressGroupType::UNKNOWN), spIpAddress(nullptr), spIpMask(nullptr), spIpData(nullptr), flags(0), isAddrUp(false), isAddrRunning(false), isAddrPrimary(false)
{
}
AddressGroup::~AddressGroup()
{
}
void AddressGroup::setAddr(std::shared_ptr<AddressBase> spaddr)
{
spIpAddress = spaddr;
}
void AddressGroup::setMask(std::shared_ptr<AddressBase> spmask)
{
spIpMask = spmask;
}
void AddressGroup::setData(std::shared_ptr<AddressBase> spdata)
{
spIpData = spdata;
}
void AddressGroup::setType(AddressGroupType type)
{
ipType = type;
}
// TODO: customize separator and eol strings (take them from arguments)
const std::string AddressGroup::getAddrString() const
{
std::string retAddrStr = "";
std::string separator = ":";
std::string eol = "\n";
std::string strTitle = "";
strTitle = std::string(magic_enum::enum_name(ipType));
retAddrStr += JSON_PARAM_ADDR_TYPE + separator + strTitle + eol;
if(spIpAddress != nullptr)
{
switch(spIpAddress->getFamily())
{
case AF_INET:
strTitle = JSON_PARAM_IPV4_ADDR;
break;
case AF_INET6:
strTitle = JSON_PARAM_IPV6_ADDR;
break;
case AF_LINK:
strTitle = JSON_PARAM_LINK_ADDR;
break;
default:
break;
}
retAddrStr += strTitle + separator + spIpAddress->getStrAddr() + eol;
switch(ipType)
{
case AddressGroupType::BCAST:
case AddressGroupType::LOOPBACK:
if(spIpMask != nullptr)
{
strTitle = (spIpAddress->getFamily() == AF_INET) ? JSON_PARAM_IPV4_MASK : JSON_PARAM_IPV6_MASK;
retAddrStr += strTitle + separator + spIpMask->getStrAddr() + eol;
}
if(spIpData != nullptr)
{
strTitle = (spIpAddress->getFamily() == AF_INET) ? JSON_PARAM_IPV4_BCAST : JSON_PARAM_IPV6_BCAST;
retAddrStr += strTitle + separator + spIpData->getStrAddr() + eol;
}
break;
case AddressGroupType::PPP:
case AddressGroupType::ROUTE:
if(spIpMask != nullptr)
{
strTitle = (spIpAddress->getFamily() == AF_INET) ? JSON_PARAM_IPV4_MASK : JSON_PARAM_IPV6_MASK;
retAddrStr += strTitle + separator + spIpMask->getStrAddr() + eol;
}
if(spIpData != nullptr)
{
strTitle = (spIpAddress->getFamily() == AF_INET) ? JSON_PARAM_IPV4_GW : JSON_PARAM_IPV6_GW;
retAddrStr += strTitle + separator + spIpData->getStrAddr() + eol;
}
break;
case AddressGroupType::LINK:
default:
break;
}
}
return retAddrStr;
}
const nlohmann::json AddressGroup::getAddrJson() const
{
nlohmann::json retAddrJson;
nlohmann::json dataJson;
std::string strTitle = "";
std::string strMainTitle = "";
/*
IPv4 broadcast address JSON example:
{
"ADDRESS TYPE" : "BCAST",
"BCAST" : {
"IPV4 ADDRESS" : "192.168.211.21",
"IPV4 SUBNET MASK" : "255.255.255.0",
"IPV4 BROADCAST ADDRESS" : "192.168.211.255"
},
"PRIMARY" : true
}
*/
strMainTitle = std::string(magic_enum::enum_name(ipType));
retAddrJson[JSON_PARAM_ADDR_TYPE] = strMainTitle;
if(isAddrPrimary)
retAddrJson[JSON_PARAM_ADDR_PRIMARY] = isAddrPrimary;
// retAddrJson[JSON_PARAM_ADDR_RUNNING] = isAddrRunning;
if(spIpAddress != nullptr)
{
switch(spIpAddress->getFamily())
{
case AF_INET:
strTitle = JSON_PARAM_IPV4_ADDR;
break;
case AF_INET6:
strTitle = JSON_PARAM_IPV6_ADDR;
break;
case AF_LINK:
strTitle = JSON_PARAM_LINK_ADDR;
break;
default:
break;
}
dataJson[strTitle] = spIpAddress->getStrAddr();
switch(ipType)
{
case AddressGroupType::BCAST:
case AddressGroupType::LOOPBACK:
if(spIpMask != nullptr)
{
strTitle = (spIpAddress->getFamily() == AF_INET) ? JSON_PARAM_IPV4_MASK : JSON_PARAM_IPV6_MASK;
dataJson[strTitle] = spIpMask->getStrAddr();
}
if(spIpData != nullptr)
{
strTitle = (spIpAddress->getFamily() == AF_INET) ? JSON_PARAM_IPV4_BCAST : JSON_PARAM_IPV6_BCAST;
dataJson[strTitle] = spIpData->getStrAddr();
}
break;
case AddressGroupType::PPP:
case AddressGroupType::ROUTE:
if(spIpMask != nullptr)
{
strTitle = (spIpAddress->getFamily() == AF_INET) ? JSON_PARAM_IPV4_MASK : JSON_PARAM_IPV6_MASK;
dataJson[strTitle] = spIpMask->getStrAddr();
}
if(spIpData != nullptr)
{
strTitle = (spIpAddress->getFamily() == AF_INET) ? JSON_PARAM_IPV4_GW : JSON_PARAM_IPV6_GW;
dataJson[strTitle] = spIpData->getStrAddr();
}
break;
case AddressGroupType::LINK:
// TODO: show link data (speed, status etc.)
default:
break;
}
switch(ipType)
{
case AddressGroupType::ROUTE:
dataJson[JSON_PARAM_FLAGS] = getFlagsRoute();
break;
default:
// TODO: add flags for other types of addresses
break;
}
retAddrJson[strMainTitle] = dataJson;
}
return retAddrJson;
}
bool AddressGroup::isUp() const
{
return isAddrUp;
}
short AddressGroup::getFamily() const
{
return spIpAddress->getFamily();
}
const AddressBase* AddressGroup::getAddrAB() const
{
return spIpAddress.get();
}
const AddressBase* AddressGroup::getMaskAB() const
{
return spIpMask.get();
}
const AddressBase* AddressGroup::getDataAB() const
{
return spIpData.get();
}
const std::shared_ptr<AddressBase> AddressGroup::getAddr() const
{
return spIpAddress;
}
const std::shared_ptr<AddressBase> AddressGroup::getMask() const
{
return spIpMask;
}
const std::shared_ptr<AddressBase> AddressGroup::getData() const
{
return spIpData;
}
bool AddressGroup::isValidIp() const
{
switch(spIpAddress->getFamily())
{
case AF_INET6:
return isValidIp6();
case AF_INET:
return isValidIp4();
case AF_LINK:
return true;
}
return true;
}
bool AddressGroup::isValidIp4() const
{
uint32_t addr_nbo=0;
uint32_t mask_nbo=0;
uint32_t gw_nbo=0;
uint32_t bcast_nbo=0;
if(spIpAddress!=nullptr)
{
addr_nbo = ((struct sockaddr_in*)(spIpAddress->getSockAddr()))->sin_addr.s_addr;
}
if(spIpMask!=nullptr)
{
mask_nbo = ((struct sockaddr_in*)(spIpMask->getSockAddr()))->sin_addr.s_addr;
}
switch(ipType)
{
case AddressGroupType::BCAST:
if(spIpData!=nullptr)
{
bcast_nbo = ((struct sockaddr_in*)(spIpData->getSockAddr()))->sin_addr.s_addr;
return Tool::isValidBcast4(addr_nbo, mask_nbo, bcast_nbo);
}
return false;
case AddressGroupType::PPP:
if(spIpData!=nullptr)
{
gw_nbo = ((struct sockaddr_in*)(spIpData->getSockAddr()))->sin_addr.s_addr;
return Tool::isValidGw4(addr_nbo, mask_nbo, gw_nbo);
}
return false;
default:
return true; // Not (yet) implemented
}
}
bool AddressGroup::isValidIp6() const
{
return true; // Not (yet) implemented
}
int AddressGroup::getFlags() const
{
return flags;
}
void AddressGroup::setFlags(int f)
{
flags = f;
}
const std::vector<std::string> AddressGroup::getFlagsRoute() const
{
std::vector<std::string> retFlags;
/*
#define RTF_UP 0x1 // route usable
const std::string JSON_DATA_RTFLAG_UP = "UP";
#define RTF_GATEWAY 0x2 // destination is a gateway
const std::string JSON_DATA_RTFLAG_GATEWAY = "GATEWAY";
#define RTF_HOST 0x4 // host entry (net otherwise)
const std::string JSON_DATA_RTFLAG_HOST = "HOST";
#define RTF_REJECT 0x8 // host or net unreachable
const std::string JSON_DATA_RTFLAG_REJECT = "REJECT";
#define RTF_DYNAMIC 0x10 // created dynamically (by redirect)
const std::string JSON_DATA_RTFLAG_DYNAMIC = "DYNAMIC";
#define RTF_MODIFIED 0x20 // modified dynamically (by redirect)
const std::string JSON_DATA_RTFLAG_MODIFIED = "MODIFIED";
#define RTF_LLINFO 0x400 // DEPRECATED - exists ONLY for backward compatibility
const std::string JSON_DATA_RTFLAG_LLINFO = "LLINFO";
#define RTF_STATIC 0x800 // manually added
const std::string JSON_DATA_RTFLAG_STATIC = "STATIC";
#define RTF_BLACKHOLE 0x1000 // just discard pkts (during updates)
const std::string JSON_DATA_RTFLAG_BLACKHOLE = "BLACKHOLE";
#define RTF_FIXEDMTU 0x80000 // MTU was explicitly specified
const std::string JSON_DATA_RTFLAG_FIXEDMTU = "FIXEDMTU";
#define RTF_PINNED 0x100000 // route is immutable
const std::string JSON_DATA_RTFLAG_PINNED = "PINNED";
#define RTF_LOCAL 0x200000 // route represents a local address
const std::string JSON_DATA_RTFLAG_LOCAL = "LOCAL";
#define RTF_BROADCAST 0x400000 // route represents a bcast address
const std::string JSON_DATA_RTFLAG_BROADCAST = "BROADCAST";
#define RTF_MULTICAST 0x800000 // route represents a mcast address
const std::string JSON_DATA_RTFLAG_MULTICAST = "MULTICAST";
#define RTF_STICKY 0x10000000 // always route dst->src
const std::string JSON_DATA_RTFLAG_STICKY = "STICKY";
*/
if(flags & RTF_UP)
retFlags.push_back(JSON_DATA_RTFLAG_UP);
if(flags & RTF_GATEWAY)
retFlags.push_back(JSON_DATA_RTFLAG_GATEWAY);
if(flags & RTF_HOST)
retFlags.push_back(JSON_DATA_RTFLAG_HOST);
if(flags & RTF_REJECT)
retFlags.push_back(JSON_DATA_RTFLAG_REJECT);
if(flags & RTF_DYNAMIC)
retFlags.push_back(JSON_DATA_RTFLAG_DYNAMIC);
if(flags & RTF_MODIFIED)
retFlags.push_back(JSON_DATA_RTFLAG_MODIFIED);
if(flags & RTF_LLINFO)
retFlags.push_back(JSON_DATA_RTFLAG_LLINFO);
if(flags & RTF_STATIC)
retFlags.push_back(JSON_DATA_RTFLAG_STATIC);
if(flags & RTF_BLACKHOLE)
retFlags.push_back(JSON_DATA_RTFLAG_BLACKHOLE);
if(flags & RTF_FIXEDMTU)
retFlags.push_back(JSON_DATA_RTFLAG_FIXEDMTU);
if(flags & RTF_PINNED)
retFlags.push_back(JSON_DATA_RTFLAG_PINNED);
if(flags & RTF_LOCAL)
retFlags.push_back(JSON_DATA_RTFLAG_LOCAL);
if(flags & RTF_BROADCAST)
retFlags.push_back(JSON_DATA_RTFLAG_BROADCAST);
if(flags & RTF_MULTICAST)
retFlags.push_back(JSON_DATA_RTFLAG_MULTICAST);
if(flags & RTF_STICKY)
retFlags.push_back(JSON_DATA_RTFLAG_STICKY);
return retFlags;
}
bool AddressGroup::isPrimary() const
{
return isAddrPrimary;
}
bool AddressGroup::isRunning() const
{
return isAddrRunning;
}
| 30.493333 | 168 | 0.589856 | Peter2121 |
c2b234593b10a631ad28beec39fb1d9a36800dc9 | 2,211 | cpp | C++ | src/shell/sensor_impl.cpp | hrandib/pc_fancontrol | 74fd5e38a7910144bfcf5fe690ad4b22c7356c91 | [
"MIT"
] | null | null | null | src/shell/sensor_impl.cpp | hrandib/pc_fancontrol | 74fd5e38a7910144bfcf5fe690ad4b22c7356c91 | [
"MIT"
] | 4 | 2020-12-22T17:48:49.000Z | 2021-02-20T21:48:24.000Z | src/shell/sensor_impl.cpp | hrandib/pc_fancontrol | 74fd5e38a7910144bfcf5fe690ad4b22c7356c91 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2020 Dmytro Shestakov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "shell/sensor_impl.h"
#include <array>
#include <iostream>
ShellSensor::ShellSensor(const std::string& path) : executablePath{path}
{ }
int32_t ShellSensor::get()
{
auto now = std::chrono::system_clock::now();
if(now > READ_PERIOD + prevReadTime_) {
try {
cachedVal_ = exec(executablePath.c_str());
prevReadTime_ = now;
}
catch(std::exception& e) {
std::cerr << e.what() << "\n";
}
}
return cachedVal_;
}
int ShellSensor::exec(const char* cmd)
{
std::array<char, 128> buffer{};
std::string rawResult;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
if(!pipe) {
throw std::runtime_error("popen() failed!");
}
while(fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
rawResult += buffer.data();
}
int result{};
try {
result = std::stoi(rawResult);
}
catch(std::exception&) {
throw std::invalid_argument("Parsing shell command output failed: " + rawResult);
}
return result;
}
| 34.015385 | 89 | 0.674355 | hrandib |
c2b501ffa186f033efc856af1192eb1dd26fe9a3 | 243 | hpp | C++ | src/comp/components.hpp | vanill4Sky/aconitum | fe0449376995d469f9dcfff524f3e36ba2097f5c | [
"MIT"
] | null | null | null | src/comp/components.hpp | vanill4Sky/aconitum | fe0449376995d469f9dcfff524f3e36ba2097f5c | [
"MIT"
] | null | null | null | src/comp/components.hpp | vanill4Sky/aconitum | fe0449376995d469f9dcfff524f3e36ba2097f5c | [
"MIT"
] | null | null | null | #pragma once
#include "animation.hpp"
#include "collider.hpp"
#include "direction.hpp"
#include "entity_state.hpp"
#include "iob.hpp"
#include "mob.hpp"
#include "player.hpp"
#include "position.hpp"
#include "sprite.hpp"
#include "target.hpp" | 20.25 | 27 | 0.740741 | vanill4Sky |
c2bcca62d65ed434b09224d68926b6883e8e4511 | 579 | cpp | C++ | pgm06_24.cpp | neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C- | c9a29d2dd43ad8561e828c25f98de6a8c8f2317a | [
"Unlicense"
] | 1 | 2021-07-13T03:58:36.000Z | 2021-07-13T03:58:36.000Z | pgm06_24.cpp | neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C- | c9a29d2dd43ad8561e828c25f98de6a8c8f2317a | [
"Unlicense"
] | null | null | null | pgm06_24.cpp | neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C- | c9a29d2dd43ad8561e828c25f98de6a8c8f2317a | [
"Unlicense"
] | null | null | null | //
// This file contains the C++ code from Program 6.24 of
// "Data Structures and Algorithms
// with Object-Oriented Design Patterns in C++"
// by Bruno R. Preiss.
//
// Copyright (c) 1998 by Bruno R. Preiss, P.Eng. All rights reserved.
//
// http://www.pads.uwaterloo.ca/Bruno.Preiss/books/opus4/programs/pgm06_24.cpp
//
Object& DequeAsArray::Head () const
{ return QueueAsArray::Head (); }
void DequeAsArray::EnqueueTail (Object& object)
{ QueueAsArray::Enqueue (object); }
Object& DequeAsArray::DequeueHead ()
{ return QueueAsArray::Dequeue (); }
| 30.473684 | 80 | 0.680484 | neharkarvishal |
c2c5a4dd9dcff34ac52f7bca729c39ac8e22580e | 3,279 | cpp | C++ | Src/HLSL/DxilRootSignature.cpp | gongminmin/Dilithium | 976ce6d6420e45ac3088fe345793bfca80cd3acd | [
"MIT"
] | 178 | 2017-02-08T14:08:56.000Z | 2022-02-22T02:19:44.000Z | Src/HLSL/DxilRootSignature.cpp | gongminmin/Dilithium | 976ce6d6420e45ac3088fe345793bfca80cd3acd | [
"MIT"
] | 7 | 2017-02-09T08:19:29.000Z | 2021-09-13T14:28:09.000Z | Src/HLSL/DxilRootSignature.cpp | gongminmin/Dilithium | 976ce6d6420e45ac3088fe345793bfca80cd3acd | [
"MIT"
] | 15 | 2017-02-14T09:42:25.000Z | 2021-12-16T15:49:17.000Z | /**
* @file DxilRootSignature.cpp
* @author Minmin Gong
*
* @section DESCRIPTION
*
* This source file is part of Dilithium
* For the latest info, see https://github.com/gongminmin/Dilithium
*
* @section LICENSE
*
* The MIT License (MIT)
*
* Copyright (c) 2017 Minmin Gong. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files(the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions :
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <Dilithium/Dilithium.hpp>
#include <Dilithium/dxc/HLSL/DxilRootSignature.hpp>
namespace
{
using namespace Dilithium;
template <typename T>
void DeleteRootSignatureTemplate(T const & root_signature_desc)
{
for (uint32_t i = 0; i < root_signature_desc.num_parameters; ++ i)
{
auto const & param = root_signature_desc.parameters[i];
if (param.parameter_type == DxilRootParameterType::DescriptorTable)
{
delete[] param.descriptor_table.descriptor_ranges;
}
}
delete[] root_signature_desc.parameters;
delete[] root_signature_desc.static_samplers;
}
void DeleteRootSignature(DxilVersionedRootSignatureDesc const * root_signature)
{
if (root_signature != nullptr)
{
switch (root_signature->version)
{
case DxilRootSignatureVersion::Version_1_0:
DeleteRootSignatureTemplate<DxilRootSignatureDesc>(root_signature->desc_1_0);
break;
case DxilRootSignatureVersion::Version_1_1:
default:
BOOST_ASSERT_MSG(root_signature->version == DxilRootSignatureVersion::Version_1_1, "Invalid version");
DeleteRootSignatureTemplate<DxilRootSignatureDesc1>(root_signature->desc_1_1);
break;
}
delete root_signature;
}
}
}
namespace Dilithium
{
DxilRootSignatureHandle::DxilRootSignatureHandle(DxilRootSignatureHandle&& rhs)
{
desc_ = std::move(rhs.desc_);
serialized_ = std::move(rhs.serialized_);
}
void DxilRootSignatureHandle::Clear()
{
DeleteRootSignature(desc_);
desc_ = nullptr;
serialized_.clear();
}
uint8_t const * DxilRootSignatureHandle::GetSerializedBytes() const
{
return serialized_.data();
}
uint32_t DxilRootSignatureHandle::GetSerializedSize() const
{
return static_cast<uint32_t>(serialized_.size());
}
void DxilRootSignatureHandle::LoadSerialized(uint8_t const * data, uint32_t length)
{
BOOST_ASSERT(this->IsEmpty());
serialized_.assign(data, data + length);
}
}
| 29.540541 | 106 | 0.752973 | gongminmin |
c2c9ac3315eec7a5324d6f1440d225c5fed1eac9 | 6,949 | cpp | C++ | ui.cpp | mmaldacker/VortexEditor | c3661f766f0ea704dc5777fa39d1483e202a1ae6 | [
"MIT"
] | 8 | 2020-03-06T06:09:59.000Z | 2020-08-08T11:13:25.000Z | ui.cpp | mmaldacker/VortexEditor | c3661f766f0ea704dc5777fa39d1483e202a1ae6 | [
"MIT"
] | null | null | null | ui.cpp | mmaldacker/VortexEditor | c3661f766f0ea704dc5777fa39d1483e202a1ae6 | [
"MIT"
] | 2 | 2020-03-06T06:00:41.000Z | 2021-07-14T00:58:16.000Z | #include "ui.h"
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtx/vector_angle.hpp>
#include <imgui.h>
#include <imgui_internal.h>
#include <Box2D/Box2D.h>
#include <GLFW/glfw3.h>
namespace
{
const glm::vec2 radius(16.0f);
const glm::vec2 anchor = radius / glm::vec2(2.0f);
static glm::vec4 green = glm::vec4(92.0f, 173.0f, 159.0f, 255.0f) / glm::vec4(255.0f);
static glm::vec4 red = glm::vec4(208.0f, 43.0f, 10.0f, 255.0f) / glm::vec4(255.0f);
} // namespace
b2BodyType GetBox2DType(int type)
{
switch (type)
{
case 0:
return b2_staticBody;
case 1:
case 2:
return b2_dynamicBody;
default:
return b2_staticBody;
}
}
Vortex2D::Fluid::RigidBody::Type GetVortex2DType(int type)
{
switch (type)
{
case 0:
return Vortex2D::Fluid::RigidBody::Type::eStatic;
case 1:
return Vortex2D::Fluid::RigidBody::Type::eWeak;
case 2:
return Vortex2D::Fluid::RigidBody::Type::eStrong;
default:
return Vortex2D::Fluid::RigidBody::Type::eStatic;
}
}
UI::UI(const Vortex2D::Renderer::Device& device, World& world, const glm::ivec2& size, float scale)
: mDevice(device)
, mSize(size)
, mScale(scale)
, mWorld(world)
, mCurrentEntity(nullptr)
, mShapeType(Rectangle{})
, mForce(device, radius)
{
mForce.Colour = glm::vec4(0.0f);
mWorld.RecordVelocity(mForce);
}
void UI::RenderFluid()
{
auto& io = ImGui::GetIO();
glm::vec2 pos = {io.MouseClickedPos[0].x / mScale, io.MouseClickedPos[0].y / mScale};
if (io.KeysDown[GLFW_KEY_LEFT_CONTROL])
{
auto size = glm::abs(glm::vec2{(io.MouseClickedPos[0].x - io.MousePos.x) / mScale,
(io.MouseClickedPos[0].y - io.MousePos.y) / mScale});
mFluid = std::make_shared<Vortex2D::Renderer::IntRectangle>(mDevice, size);
mForce.Colour = glm::vec4(0.0f);
}
else
{
mFluid = std::make_shared<Vortex2D::Renderer::IntRectangle>(mDevice, radius);
mFluid->Anchor = anchor;
glm::vec2 currPos = {io.MousePos.x / mScale, io.MousePos.y / mScale};
glm::vec2 delta = currPos - pos;
mForce.Position = pos;
mForce.Anchor = anchor;
mForce.Colour = glm::vec4(delta, 0.0f, 0.0f);
}
mFluid->Colour = glm::vec4(4);
mFluid->Position = pos;
mWorld.GetWorld().RecordParticleCount({*mFluid}).Submit();
}
void UI::MoveShape(Entity& entity)
{
auto& io = ImGui::GetIO();
glm::vec2 centre = entity.mShape->Position;
if (io.KeysDown[GLFW_KEY_LEFT_CONTROL])
{
// rotation
glm::vec2 v1 = {io.MouseClickedPos[0].x - centre.x, io.MouseClickedPos[0].y - centre.y};
glm::vec2 v2 = {io.MousePos.x - centre.x, io.MousePos.y - centre.y};
auto angle = glm::orientedAngle(glm::normalize(v1), glm::normalize(v2));
entity.SetTransform(centre, glm::degrees(angle));
}
else
{
// translation
glm::vec2 delta = {io.MouseDelta.x, io.MouseDelta.y};
entity.SetTransform(centre + delta, entity.mShape->Rotation);
}
}
void UI::ResizeShape(Vortex2D::Renderer::RenderTarget& target)
{
auto& io = ImGui::GetIO();
auto size = glm::abs(
glm::vec2{io.MouseClickedPos[0].x - io.MousePos.x, io.MouseClickedPos[0].y - io.MousePos.y});
mShapeType.match(
[&](Rectangle& rectangle) {
auto halfSize = size / glm::vec2(2.0f);
mBuildShape = std::make_unique<Vortex2D::Renderer::Rectangle>(mDevice, size);
mBuildShape->Position =
glm::vec2(io.MouseClickedPos[0].x, io.MouseClickedPos[0].y) + halfSize;
mBuildShape->Anchor = halfSize;
rectangle.mSize = size;
},
[&](Circle& circle) {
auto radius = glm::length(size);
mBuildShape =
std::make_unique<Vortex2D::Renderer::Ellipse>(mDevice, glm::vec2(radius, radius));
mBuildShape->Position = {io.MouseClickedPos[0].x, io.MouseClickedPos[0].y};
circle.mRadius = radius;
},
[&](Polygon& /*polygon*/) {
});
mBuildShape->Colour = green;
Vortex2D::Renderer::ColorBlendState blendState;
blendState.ColorBlend.setBlendEnable(true)
.setAlphaBlendOp(vk::BlendOp::eAdd)
.setColorBlendOp(vk::BlendOp::eAdd)
.setSrcColorBlendFactor(vk::BlendFactor::eSrcAlpha)
.setSrcAlphaBlendFactor(vk::BlendFactor::eOne)
.setDstColorBlendFactor(vk::BlendFactor::eOneMinusSrcAlpha)
.setDstAlphaBlendFactor(vk::BlendFactor::eZero);
mBuildCmd = target.Record({*mBuildShape}, blendState);
}
void UI::CreateShape()
{
if (mBuildShape && IsValid(mShapeType))
{
EntityPtr entity = std::make_unique<Entity>(mDevice,
mSize,
mScale,
mShapeType,
std::move(mBuildShape),
std::move(mBuildCmd),
mWorld.GetBox2dWorld());
mWorld.Add(std::move(entity));
}
}
void UI::Update(Vortex2D::Renderer::RenderTarget& target)
{
static bool renderFluid = false;
auto& io = ImGui::GetIO();
if (ImGui::BeginPopupContextVoid("World Manager"))
{
if (mCurrentEntity == nullptr)
{
if (ImGui::Selectable("Rectangle", !renderFluid && mShapeType.is<Rectangle>()))
{
mShapeType = Rectangle{};
renderFluid = false;
}
if (ImGui::Selectable("Circle", !renderFluid && mShapeType.is<Circle>()))
{
mShapeType = Circle{};
renderFluid = false;
}
if (ImGui::Selectable("Fluid", renderFluid))
{
renderFluid = true;
}
}
else
{
if (ImGui::Selectable("Static"))
{
mCurrentEntity->mRigidbody->mBody->SetType(GetBox2DType(0));
mCurrentEntity->mRigidbody->mRigidbody->SetType(GetVortex2DType(0));
mCurrentEntity = nullptr;
}
if (ImGui::Selectable("Dynamic"))
{
mCurrentEntity->mRigidbody->mBody->SetType(GetBox2DType(1));
mCurrentEntity->mRigidbody->mRigidbody->SetType(GetVortex2DType(1));
mCurrentEntity->mShape->Colour = red;
mCurrentEntity = nullptr;
}
if (ImGui::Selectable("Delete"))
{
mWorld.Delete(mCurrentEntity);
mCurrentEntity = nullptr;
}
}
if (ImGui::Selectable("Clear"))
{
mWorld.Clear();
}
ImGui::EndPopup();
}
if (io.WantCaptureMouse)
{
return;
}
if (io.MouseClicked[0] || io.MouseClicked[1])
{
mCurrentEntity = mWorld.FindEntity({io.MousePos.x, io.MousePos.y});
}
if (io.MouseDown[0])
{
if (renderFluid)
{
RenderFluid();
}
else if (mCurrentEntity != nullptr)
{
MoveShape(*mCurrentEntity);
}
else
{
ResizeShape(target);
}
}
if (io.MouseReleased[0])
{
if (mCurrentEntity == nullptr)
{
CreateShape();
}
mCurrentEntity = nullptr;
}
mBuildCmd.Submit();
}
| 26.222642 | 99 | 0.602677 | mmaldacker |
c2cd265b59283d925007237da6b29ce9eff0467e | 3,843 | cpp | C++ | source/drivers/HID.cpp | mmoskal/codal-core | f4df7e461d96726b43e97e4b425279805eadb297 | [
"MIT"
] | 1 | 2021-03-15T07:09:15.000Z | 2021-03-15T07:09:15.000Z | source/drivers/HID.cpp | mmoskal/codal-core | f4df7e461d96726b43e97e4b425279805eadb297 | [
"MIT"
] | 1 | 2021-01-28T10:01:21.000Z | 2021-01-28T11:20:31.000Z | source/drivers/HID.cpp | mmoskal/codal-core | f4df7e461d96726b43e97e4b425279805eadb297 | [
"MIT"
] | 1 | 2021-03-15T07:09:18.000Z | 2021-03-15T07:09:18.000Z | /*
The MIT License (MIT)
Copyright (c) 2017 Lancaster University.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include "HID.h"
#if CONFIG_ENABLED(DEVICE_USB)
using namespace codal;
static const char hidDescriptor[] = {
0x06, 0x00, 0xFF, // usage page vendor #0
0x09, 0x01, // usage 1
0xA1, 0x01, // collection - application
0x15, 0x00, // logical min 0
0x26, 0xFF, 0x00, // logical max 255
0x75, 8, // report size 8
0x95, 64, // report count 64
0x09, 0x01, // usage 1
0x81, 0x02, // input: data, variable, absolute
0x95, 64, // report count 64
0x09, 0x01, // usage 1
0x91, 0x02, // output: data, variable, absolute
0x95, 1, // report count 1
0x09, 0x01, // usage 1
0xB1, 0x02, // feature: data, variable, absolute
0xC0, // end
};
static const HIDReportDescriptor reportDesc = {
9,
0x21, // HID
0x100, // hidbcd 1.00
0x00, // country code
0x01, // num desc
0x22, // report desc type
sizeof(hidDescriptor), // size of 0x22
};
static const InterfaceInfo ifaceInfo = {
&reportDesc,
sizeof(reportDesc),
1,
{
2, // numEndpoints
0x03, /// class code - HID
0x00, // subclass
0x00, // protocol
0x00, //
0x00, //
},
{USB_EP_TYPE_INTERRUPT, 1},
{USB_EP_TYPE_INTERRUPT, 1},
};
USBHID::USBHID() : CodalUSBInterface()
{
}
int USBHID::stdRequest(UsbEndpointIn &ctrl, USBSetup &setup)
{
if (setup.bRequest == USB_REQ_GET_DESCRIPTOR)
{
if (setup.wValueH == 0x21)
{
InterfaceDescriptor tmp;
fillInterfaceInfo(&tmp);
return ctrl.write(&tmp, sizeof(tmp));
}
else if (setup.wValueH == 0x22)
{
return ctrl.write(hidDescriptor, sizeof(hidDescriptor));
}
}
return DEVICE_NOT_SUPPORTED;
}
int USBHID::endpointRequest()
{
uint8_t buf[64];
int len = out->read(buf, sizeof(buf));
if (len <= 0)
return len;
for (int i = 1; i < 4; ++i)
{
buf[i] ^= 'a' - 'A';
}
// this should echo-back serial
return in->write(buf, sizeof(buf));
}
const InterfaceInfo *USBHID::getInterfaceInfo()
{
return &ifaceInfo;
}
int USBHID::classRequest(UsbEndpointIn &ctrl, USBSetup &setup)
{
uint8_t buf[8] = {0};
switch (setup.bRequest)
{
case HID_REQUEST_GET_PROTOCOL:
case HID_REQUEST_GET_IDLE:
case HID_REQUEST_GET_REPORT:
return ctrl.write(buf, sizeof(buf));
case HID_REQUEST_SET_IDLE:
case HID_REQUEST_SET_REPORT:
case HID_REQUEST_SET_PROTOCOL:
return ctrl.write(buf, 0);
}
return DEVICE_NOT_SUPPORTED;
}
#endif
| 27.45 | 74 | 0.625813 | mmoskal |
c2d56a85e647f114a0cba067216aed2f8235e0b1 | 1,935 | cpp | C++ | src/subsystems_computer/suspension_onboard.cpp | 2535Rover/RoverSystem | 300dd4d754bac2e4caff25ed1da244c109d289be | [
"Apache-2.0"
] | 1 | 2018-10-16T02:32:49.000Z | 2018-10-16T02:32:49.000Z | src/subsystems_computer/suspension_onboard.cpp | 2535Rover/RoverSystem | 300dd4d754bac2e4caff25ed1da244c109d289be | [
"Apache-2.0"
] | 13 | 2018-10-23T20:35:10.000Z | 2018-11-23T22:44:32.000Z | src/subsystems_computer/suspension_onboard.cpp | 2535Rover/RoverSystem | 300dd4d754bac2e4caff25ed1da244c109d289be | [
"Apache-2.0"
] | 1 | 2018-10-16T03:11:39.000Z | 2018-10-16T03:11:39.000Z | #include <cstring>
//#include <stdio.h>
#include "../rocs/rocs.hpp"
#include "suspension.hpp"
namespace suspension {
// Scale the input down by 2.
const uint16_t PRESCALE = 1;
uint8_t global_slave_addr;
// Assumes rocs has already been initialized!
Error init(uint8_t slave_addr) {
global_slave_addr = slave_addr;
// TODO: Prevent buffer overflows by taking buffer len in ROCS!
char name_buffer[100];
if (rocs::read_name(global_slave_addr, name_buffer) != rocs::Error::OK) {
return Error::READ;
}
if (strcmp(name_buffer, "suspension") != 0) {
return Error::DEVICE_NOT_RECOGNIZED;
}
return Error::OK;
}
uint8_t side_to_dir_register_map[2] = {
[static_cast<int>(Side::LEFT)] = 0x05,
[static_cast<int>(Side::RIGHT)] = 0x07,
};
uint8_t side_to_speed_register_map[2] = {
[static_cast<int>(Side::LEFT)] = 0x06,
[static_cast<int>(Side::RIGHT)] = 0x08,
};
uint8_t dir_to_value_map[2] = {
[static_cast<int>(Direction::FORWARD)] = 0x00,
[static_cast<int>(Direction::BACKWARD)] = 0x01,
};
const uint8_t READ_LEFT_VELOCITY = 0x09;
const uint8_t READ_RIGHT_VELOCITY = 0x0A;
Error read_variable_velocity(){
auto rocs_res = rocs::write_to_register(global_slave_addr, )
}
Error update(Side side, Direction direction, uint8_t speed) {
auto rocs_res = rocs::write_to_register(global_slave_addr, side_to_speed_register_map[side], speed);
if (rocs_res != rocs::Error::OK){
return Error::WRITE;
}
rocs_res = rocs::write_to_register(global_slave_addr, side_to_dir_register_map[side], dir_to_value_map[direction]);
if (rocs_res != rocs::Error::OK){
return Error::WRITE;
}
return Error::OK;
}
Error stop(Side side) {
auto rocs_res = rocs::write_to_register(global_slave_addr, side_to_speed_register_map[side], 0);
if (rocs_res != rocs::Error::OK){
return Error::WRITE;
}
return Error::OK;
}
}
| 25.460526 | 119 | 0.686822 | 2535Rover |
c2d5dc683bfa72f6747a286f7ef7e1c0e3baf92b | 15,263 | cpp | C++ | tests/test_reg.cpp | sqc1999-oi/LxRunOffline | bdc6d7d77f886c6dcdab3b4c9c136557ca6694c4 | [
"BSL-1.0",
"MIT"
] | 3,353 | 2017-03-02T15:12:49.000Z | 2022-03-31T08:28:45.000Z | tests/test_reg.cpp | sqc1999-oi/LxRunOffline | bdc6d7d77f886c6dcdab3b4c9c136557ca6694c4 | [
"BSL-1.0",
"MIT"
] | 187 | 2017-03-11T10:49:50.000Z | 2022-03-27T17:42:00.000Z | tests/test_reg.cpp | sqc1999-oi/LxRunOffline | bdc6d7d77f886c6dcdab3b4c9c136557ca6694c4 | [
"BSL-1.0",
"MIT"
] | 250 | 2017-03-08T16:14:56.000Z | 2022-03-30T10:11:36.000Z | #include <boost/test/unit_test.hpp>
#include <boost/test/data/monomorphic.hpp>
#include <boost/test/data/test_case.hpp>
#include "pch.h"
#include "fixtures.h"
#include "utils.h"
using namespace boost::unit_test;
extern "C" const wchar_t *const reg_base_path = fixture_tmp_reg::PATH;
BOOST_AUTO_TEST_SUITE(test_reg)
class reg_key {
HKEY hk;
static HKEY dup_hkey(const HKEY hk) {
const auto hp = GetCurrentProcess();
HKEY nhk;
BOOST_TEST_REQUIRE(DuplicateHandle(hp, hk, hp, reinterpret_cast<LPHANDLE>(&nhk), 0, false, DUPLICATE_SAME_ACCESS));
return nhk;
}
public:
explicit reg_key(const HKEY hk) : hk(dup_hkey(hk)) {}
reg_key(const reg_key &other) : hk(dup_hkey(other.hk)) {}
~reg_key() {
RegCloseKey(hk);
}
[[nodiscard]]
reg_key open_subkey(const std::wstring &path, const bool create) const {
HKEY hk_sub;
DWORD disp;
BOOST_TEST_REQUIRE(RegCreateKeyEx(hk, path.c_str(), 0, nullptr, 0, KEY_ALL_ACCESS, nullptr, &hk_sub, &disp) == ERROR_SUCCESS);
if (create) {
BOOST_TEST(disp == REG_CREATED_NEW_KEY);
} else {
BOOST_TEST(disp == REG_OPENED_EXISTING_KEY);
}
const auto ret = reg_key(hk_sub);
RegCloseKey(hk_sub);
return ret;
}
[[nodiscard]]
std::vector<std::wstring> get_subkey_names() const {
DWORD subkey_count, subkey_max_len;
BOOST_TEST_REQUIRE(RegQueryInfoKey(hk, nullptr, nullptr, nullptr, &subkey_count, &subkey_max_len, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr) == ERROR_SUCCESS);
std::vector<std::wstring> ret;
const auto buf = std::make_unique<wchar_t[]>(static_cast<size_t>(subkey_max_len) + 1);
for (DWORD i = 0; i < subkey_count; i++) {
auto len = subkey_max_len + 1;
BOOST_TEST_REQUIRE(RegEnumKeyEx(hk, i, buf.get(), &len, nullptr, nullptr, nullptr, nullptr) == ERROR_SUCCESS);
ret.emplace_back(buf.get());
}
return ret;
}
[[nodiscard]]
DWORD get_value_count() const {
DWORD ret;
BOOST_TEST_REQUIRE(RegQueryInfoKey(hk, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &ret, nullptr, nullptr, nullptr, nullptr) == ERROR_SUCCESS);
return ret;
}
[[nodiscard]]
DWORD get_dword_value(const std::wstring &name) const {
DWORD ret, len = sizeof(DWORD);
BOOST_TEST_REQUIRE(RegGetValue(hk, nullptr, name.c_str(), RRF_RT_DWORD, nullptr, &ret, &len) == ERROR_SUCCESS);
BOOST_TEST(len == sizeof(DWORD));
return ret;
}
void set_dword_value(const std::wstring &name, const DWORD value) const {
BOOST_TEST_REQUIRE(RegSetKeyValue(hk, nullptr, name.c_str(), REG_DWORD, &value, sizeof(DWORD)) == ERROR_SUCCESS);
}
[[nodiscard]]
std::wstring get_sz_value(const std::wstring &name) const {
DWORD len = 0;
BOOST_TEST_REQUIRE(RegGetValue(hk, nullptr, name.c_str(), RRF_RT_REG_SZ, nullptr, nullptr, &len) == ERROR_SUCCESS);
const auto buf = std::make_unique<wchar_t[]>(static_cast<size_t>(len));
BOOST_TEST_REQUIRE(RegGetValue(hk, nullptr, name.c_str(), RRF_RT_REG_SZ, nullptr, buf.get(), &len) == ERROR_SUCCESS);
return buf.get();
}
void set_sz_value(const std::wstring &name, const std::wstring &value) const {
const auto len = static_cast<DWORD>((value.size() + 1) * sizeof(wchar_t));
BOOST_TEST_REQUIRE(RegSetKeyValue(hk, nullptr, name.c_str(), REG_SZ, value.c_str(), len) == ERROR_SUCCESS);
}
[[nodiscard]]
std::vector<std::wstring> get_multi_sz_value(const std::wstring &name) const {
DWORD len = 0;
BOOST_TEST_REQUIRE(RegGetValue(hk, nullptr, name.c_str(), RRF_RT_REG_MULTI_SZ, nullptr, nullptr, &len) == ERROR_SUCCESS);
const auto buf = std::make_unique<wchar_t[]>(static_cast<size_t>(len));
BOOST_TEST_REQUIRE(RegGetValue(hk, nullptr, name.c_str(), RRF_RT_REG_MULTI_SZ, nullptr, buf.get(), &len) == ERROR_SUCCESS);
std::vector<std::wstring> ret;
for (const auto *p = buf.get(); (p - buf.get() + 1) * 2 < len;) {
const auto str = std::wstring(p);
p += str.size() + 1;
ret.push_back(str);
}
return ret;
}
void set_multi_sz_value(const std::wstring &name, const std::vector<std::wstring> &value) const {
std::vector<wchar_t> buf;
for (const auto &str : value) {
buf.insert(buf.end(), str.begin(), str.end());
buf.push_back(0);
}
buf.push_back(0);
const auto len = static_cast<DWORD>(buf.size() * sizeof(wchar_t));
BOOST_TEST_REQUIRE(RegSetKeyValue(hk, nullptr, name.c_str(), REG_MULTI_SZ, buf.data(), len) == ERROR_SUCCESS);
}
};
static std::wstring register_test_distro(const reg_key &root_key, const std::wstring &name, const std::wstring &path) {
auto distro_id = new_guid();
const auto distro_key = root_key.open_subkey(distro_id, true);
distro_key.set_sz_value(L"DistributionName", name);
distro_key.set_sz_value(L"BasePath", path);
distro_key.set_dword_value(L"State", 1);
distro_key.set_dword_value(L"Version", 2);
return distro_id;
}
BOOST_FIXTURE_TEST_CASE(test_list_distros, fixture_tmp_reg) {
const auto root_key = reg_key(get_hkey());
register_test_distro(root_key, L"foo1", L"C:\\bar1");
register_test_distro(root_key, L"foo2", L"C:\\bar2");
register_test_distro(root_key, L"foo3", L"C:\\bar3");
const auto non_guid_key = root_key.open_subkey(L"AppxInstallerCache", true);
const auto long_key = root_key.open_subkey(
L"a string which is longer than the buffer for GUID in list_distro_id", true);
auto list = list_distros();
std::sort(list.begin(), list.end());
BOOST_TEST(list == (std::vector<std::wstring> { L"foo1", L"foo2", L"foo3" }));
}
BOOST_FIXTURE_TEST_CASE(test_register_distro, fixture_tmp_reg) {
register_distro(L"foo", L"C:\\bar1", 2);
const auto root_key = reg_key(get_hkey());
const auto subkeys = root_key.get_subkey_names();
BOOST_TEST(subkeys.size() == 1);
const auto distro_key = root_key.open_subkey(subkeys[0], false);
BOOST_TEST(distro_key.get_value_count() == 4);
BOOST_TEST(distro_key.get_sz_value(L"DistributionName").c_str() == L"foo");
BOOST_TEST(distro_key.get_sz_value(L"BasePath").c_str() == L"C:\\bar1");
BOOST_TEST(distro_key.get_dword_value(L"State") == 1);
BOOST_TEST(distro_key.get_dword_value(L"Version") == 2);
BOOST_CHECK_THROW(register_distro(L"foo", L"C:\\bar2", 2), lro_error);
}
BOOST_FIXTURE_TEST_CASE(test_unregister_distro, fixture_tmp_reg) {
const auto root_key = reg_key(get_hkey());
const auto distro_id = register_test_distro(root_key, L"foo", L"C:\\bar");
BOOST_CHECK_THROW(unregister_distro(L"foo"), lro_error);
root_key.set_sz_value(L"DefaultDistribution", distro_id);
BOOST_CHECK_THROW(unregister_distro(L"bar"), lro_error);
unregister_distro(L"foo");
BOOST_TEST(root_key.get_subkey_names().empty());
}
BOOST_FIXTURE_TEST_CASE(test_get_distro_dir, fixture_tmp_reg) {
BOOST_CHECK_THROW(get_distro_dir(L"foo"), lro_error);
const auto root_key = reg_key(get_hkey());
register_test_distro(root_key, L"foo", L"C:\\bar");
BOOST_TEST(_wcsicmp(get_distro_dir(L"foo").c_str(), L"C:\\bar") == 0);
}
BOOST_FIXTURE_TEST_CASE(test_set_distro_dir, fixture_tmp_reg) {
BOOST_CHECK_THROW(set_distro_dir(L"foo", L"C:\\bar"), lro_error);
const auto root_key = reg_key(get_hkey());
const auto distro_id = register_test_distro(root_key, L"foo", L"");
const auto distro_key = root_key.open_subkey(distro_id, false);
set_distro_dir(L"foo", L"C:\\bar");
BOOST_TEST(_wcsicmp(distro_key.get_sz_value(L"BasePath").c_str(), L"C:\\bar") == 0);
set_distro_dir(L"foo", L"bar");
BOOST_TEST(_wcsicmp(distro_key.get_sz_value(L"BasePath").c_str(), (std::filesystem::current_path() / L"bar").wstring().c_str()) == 0);
}
BOOST_FIXTURE_TEST_CASE(test_get_distro_version, fixture_tmp_reg) {
BOOST_CHECK_THROW(get_distro_version(L"foo"), lro_error);
const auto root_key = reg_key(get_hkey());
register_test_distro(root_key, L"foo", L"C:\\bar");
BOOST_TEST(get_distro_version(L"foo") == 2);
}
BOOST_AUTO_TEST_SUITE(test_default_distro)
BOOST_FIXTURE_TEST_CASE(test_get_default_distro, fixture_tmp_reg) {
BOOST_CHECK_THROW(get_default_distro(), lro_error);
const auto root_key = reg_key(get_hkey());
const auto distro_id = register_test_distro(root_key, L"foo", L"C:\\bar");
root_key.set_sz_value(L"DefaultDistribution", distro_id);
BOOST_TEST(get_default_distro().c_str() == L"foo");
}
BOOST_FIXTURE_TEST_CASE(test_set_default_distro, fixture_tmp_reg) {
BOOST_CHECK_THROW(set_default_distro(L"foo"), lro_error);
const auto root_key = reg_key(get_hkey());
const auto distro_id = register_test_distro(root_key, L"foo", L"C:\\bar");
set_default_distro(L"foo");
BOOST_TEST(root_key.get_sz_value(L"DefaultDistribution").c_str() == distro_id.c_str());
}
BOOST_FIXTURE_TEST_CASE(test_register_default, fixture_tmp_reg) {
register_distro(L"foo", L"C:\\bar", 2);
const auto root_key = reg_key(get_hkey());
BOOST_TEST(root_key.get_value_count() == 1);
const auto default_distro = root_key.get_sz_value(L"DefaultDistribution");
const auto distro_id = root_key.get_subkey_names()[0];
BOOST_TEST(default_distro.c_str() == distro_id.c_str());
}
BOOST_FIXTURE_TEST_CASE(test_register_non_default, fixture_tmp_reg) {
const auto root_key = reg_key(get_hkey());
const auto distro_id = register_test_distro(root_key, L"foo1", L"C:\\bar1");
root_key.set_sz_value(L"DefaultDistribution", distro_id);
register_distro(L"foo2", L"C:\\bar2", 2);
BOOST_TEST(root_key.get_sz_value(L"DefaultDistribution").c_str() == distro_id.c_str());
}
BOOST_FIXTURE_TEST_CASE(test_unregister_default, fixture_tmp_reg) {
const auto root_key = reg_key(get_hkey());
const auto distro_id = register_test_distro(root_key, L"foo", L"C:\\bar");
root_key.set_sz_value(L"DefaultDistribution", distro_id);
unregister_distro(L"foo");
BOOST_TEST(root_key.get_value_count() == 0);
}
BOOST_FIXTURE_TEST_CASE(test_unregister_non_default, fixture_tmp_reg) {
const auto root_key = reg_key(get_hkey());
const auto distro_id = register_test_distro(root_key, L"foo1", L"C:\\bar1");
root_key.set_sz_value(L"DefaultDistribution", distro_id);
register_test_distro(root_key, L"foo2", L"C:\\bar2");
unregister_distro(L"foo2");
BOOST_TEST(root_key.get_sz_value(L"DefaultDistribution").c_str() == distro_id.c_str());
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE(test_reg_config)
BOOST_AUTO_TEST_CASE(test_default_value) {
reg_config conf(false);
const std::vector<std::wstring> expected_env = {
L"HOSTTYPE=x86_64",
L"LANG=en_US.UTF-8",
L"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games",
L"TERM=xterm-256color"
};
BOOST_TEST(conf.env == expected_env);
BOOST_TEST(conf.uid == 0);
BOOST_TEST(conf.kernel_cmd.c_str() == L"BOOT_IMAGE=/kernel init=/init ro");
BOOST_TEST(conf.get_flags() == 7);
}
static reg_config get_test_conf(const bool is_wsl2) {
reg_config conf(is_wsl2);
conf.env = { L"FOO1=bar1", L"FOO2=bar2" };
conf.uid = 42;
conf.kernel_cmd = L"foo";
conf.set_flags(1);
return conf;
}
BOOST_TEST_DECORATOR(*fixture<fixture_tmp_dir>())
BOOST_AUTO_TEST_CASE(test_load_save_file) {
const auto conf1 = get_test_conf(true);
reg_config conf2(false);
conf1.save_file(L"foo.xml");
BOOST_CHECK_THROW(conf2.load_file(L"bar.xml"), lro_error);
conf2.load_file(L"foo.xml");
BOOST_TEST(conf1.env == conf2.env);
BOOST_TEST(conf1.uid == conf2.uid);
BOOST_TEST(conf1.kernel_cmd.c_str() == conf2.kernel_cmd.c_str());
BOOST_TEST(conf1.get_flags() == conf2.get_flags());
}
BOOST_DATA_TEST_CASE_F(fixture_tmp_reg, test_load_mask, data::xrange(0, 8), mask) {
const auto root_key = reg_key(get_hkey());
const auto distro_key = root_key.open_subkey(register_test_distro(root_key, L"foo", L"C:\\bar"), false);
const auto conf1 = get_test_conf(false);
if (mask & config_env) {
distro_key.set_multi_sz_value(L"DefaultEnvironment", conf1.env);
}
if (mask & config_uid) {
distro_key.set_dword_value(L"DefaultUid", conf1.uid);
}
if (mask & config_kernel_cmd) {
distro_key.set_sz_value(L"KernelCommandLine", conf1.kernel_cmd);
}
if (mask & config_flags) {
distro_key.set_dword_value(L"Flags", conf1.get_flags());
}
const reg_config conf2(false);
auto conf3 = conf2;
conf3.load_distro(L"foo", static_cast<config_item_flags>(mask));
if (mask & config_env) {
BOOST_TEST(conf3.env == conf1.env);
} else {
BOOST_TEST(conf3.env == conf2.env);
}
if (mask & config_uid) {
BOOST_TEST(conf3.uid == conf1.uid);
} else {
BOOST_TEST(conf3.uid == conf2.uid);
}
if (mask & config_kernel_cmd) {
BOOST_TEST(conf3.kernel_cmd.c_str() == conf1.kernel_cmd.c_str());
} else {
BOOST_TEST(conf3.kernel_cmd.c_str() == conf2.kernel_cmd.c_str());
}
if (mask & config_flags) {
BOOST_TEST(conf3.get_flags() == conf1.get_flags());
} else {
BOOST_TEST(conf3.get_flags() == conf2.get_flags());
}
}
BOOST_FIXTURE_TEST_CASE(test_load_default, fixture_tmp_reg) {
BOOST_CHECK_THROW(reg_config(false).load_distro(L"foo", config_all), lro_error);
const auto root_key = reg_key(get_hkey());
register_test_distro(root_key, L"foo", L"C:\\bar");
const auto conf1 = get_test_conf(false);
auto conf2 = conf1;
conf2.load_distro(L"foo", config_all);
BOOST_TEST(conf1.env == conf2.env);
BOOST_TEST(conf1.uid == conf2.uid);
BOOST_TEST(conf1.kernel_cmd.c_str() == conf2.kernel_cmd.c_str());
BOOST_TEST(conf1.get_flags() == conf2.get_flags());
}
BOOST_DATA_TEST_CASE_F(fixture_tmp_reg, test_configure_mask, data::xrange(0, 8), mask) {
BOOST_CHECK_THROW(reg_config(false).configure_distro(L"foo", static_cast<config_item_flags>(mask)), lro_error);
const auto root_key = reg_key(get_hkey());
const auto distro_key = root_key.open_subkey(register_test_distro(root_key, L"foo", L"C:\\bar"), false);
const auto old_value_count = distro_key.get_value_count();
const auto conf = get_test_conf(false);
conf.configure_distro(L"foo", static_cast<config_item_flags>(mask));
auto config_count = 0;
if (mask & config_env) {
config_count++;
BOOST_TEST(distro_key.get_multi_sz_value(L"DefaultEnvironment") == conf.env);
}
if (mask & config_uid) {
config_count++;
BOOST_TEST(distro_key.get_dword_value(L"DefaultUid") == conf.uid);
}
if (mask & config_kernel_cmd) {
config_count++;
BOOST_TEST(distro_key.get_sz_value(L"KernelCommandLine").c_str() == conf.kernel_cmd.c_str());
}
if (mask & config_flags) {
config_count++;
BOOST_TEST(distro_key.get_dword_value(L"Flags") == conf.get_flags());
}
BOOST_TEST(distro_key.get_value_count() == old_value_count + config_count);
}
BOOST_TEST_DECORATOR(*fixture<fixture_tmp_dir>())
BOOST_FIXTURE_TEST_CASE(test_wsl2_flag, fixture_tmp_reg) {
auto conf1 = get_test_conf(false);
BOOST_TEST(!conf1.is_wsl2());
BOOST_CHECK_THROW(conf1.set_flags(conf1.get_flags() | 8), lro_error);
conf1 = get_test_conf(true);
BOOST_TEST((conf1.get_flags() & 8) == 0);
BOOST_TEST(conf1.is_wsl2());
conf1.set_flags(0);
BOOST_TEST(conf1.is_wsl2());
const auto root_key = reg_key(get_hkey());
const auto distro_key = root_key.open_subkey(register_test_distro(root_key, L"foo", L"C:\\bar"), false);
conf1.configure_distro(L"foo", config_flags);
BOOST_TEST(distro_key.get_dword_value(L"Flags") == (conf1.get_flags() | 8));
reg_config conf2(false);
conf2.load_distro(L"foo", config_flags);
BOOST_TEST(conf2.get_flags() == conf1.get_flags());
BOOST_TEST(conf2.is_wsl2());
conf1.save_file(L"foo.xml");
conf2 = reg_config(false);
conf2.load_file(L"foo.xml");
BOOST_TEST(conf2.get_flags() == conf1.get_flags());
BOOST_TEST(conf2.is_wsl2());
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
| 38.738579 | 172 | 0.737666 | sqc1999-oi |
c2d774b0b56aec8637621af60fbe8f2817d24a1e | 5,424 | cpp | C++ | src/dynamic.cpp | miazgatron/kopt | 64525697b8980e7101092d506b08f07c3e2e5218 | [
"MIT"
] | null | null | null | src/dynamic.cpp | miazgatron/kopt | 64525697b8980e7101092d506b08f07c3e2e5218 | [
"MIT"
] | null | null | null | src/dynamic.cpp | miazgatron/kopt | 64525697b8980e7101092d506b08f07c3e2e5218 | [
"MIT"
] | null | null | null | #include <dynamic.h>
#include <fast_embedding.h>
namespace kopt {
namespace {
Dynamic::Result DynamicResult(Dynamic::Bag &bag, Dynamic::Table &table, Dynamic::Result &left, Dynamic::Result &right) {
return std::make_unique<Dynamic::ResultStruct>(bag, std::move(table), std::move(left), std::move(right));
}
Dynamic::Result DynamicResult(Dynamic::Bag &bag, Dynamic::Table &table, Dynamic::Result &left) {
return std::make_unique<Dynamic::ResultStruct>(bag, std::move(table), std::move(left), nullptr);
}
Dynamic::Result DynamicResult(Dynamic::Bag &bag, Dynamic::Table &table) {
return std::make_unique<Dynamic::ResultStruct>(bag, std::move(table), nullptr, nullptr);
}
} // namespace
static const int64_t kNone = std::numeric_limits<int64_t>::min();
Dynamic::Table::Table(Set<SigEdge> bag, int graph_size)
: table_(Embedding::IdSize(bag, graph_size), kNone),
bag_(bag), graph_size_(graph_size) {}
template<class Index>
int64_t& Dynamic::Table::operator[](const Index &idx) {
return table_[idx.Id()];
}
template<class Index>
const int64_t& Dynamic::Table::operator[](const Index &idx) const {
return table_[idx.Id()];
}
struct Clock {
Clock(char id, int arg): id(id), arg(arg), start(clock()) {}
~Clock() {
clock_t end = clock();
std::cerr << id << ' ' << arg << ' ' << end - start << '\n';
}
char id;
int arg;
clock_t start;
};
Dynamic::Dynamic(int graph_size, GainFunc gain) : graph_size_(graph_size), gain_(gain) {}
Dynamic::Result Dynamic::Leaf() const {
auto bag = Set<SigEdge>();
auto table = Table(bag, graph_size_);
auto embedding = Embedding(bag, graph_size_);
table[embedding] = 0;
return DynamicResult(bag, table);
}
Dynamic::Result Dynamic::Introduce(SigEdge introduced, Result child) const {
auto parent_bag = child->bag + Bag(introduced);
auto parent_table = Table(parent_bag, graph_size_);
auto parent_embedding = Embedding(parent_bag, graph_size_);
do {
auto &parent_gain = parent_table[parent_embedding];
auto &child_gain = child->table[parent_embedding - introduced];
if (child_gain != kNone) {
parent_gain = child_gain + gain_.Introduce(parent_embedding, introduced);
}
} while (parent_embedding.Next());
return DynamicResult(parent_bag, parent_table, child);
}
Dynamic::Result Dynamic::Forget(SigEdge forgotten, Result child) const {
auto parent_bag = child->bag - Bag(forgotten);
auto parent_table = Table(parent_bag, graph_size_);
auto child_embedding = Embedding(child->bag, graph_size_);
do {
auto &parent_gain = parent_table[child_embedding - forgotten];
auto &child_gain = child->table[child_embedding];
parent_gain = std::max(parent_gain, child_gain);
} while (child_embedding.Next());
return DynamicResult(parent_bag, parent_table, child);
}
Dynamic::Result Dynamic::Join(Result left, Result right) const {
auto parent_bag = left->bag;
auto parent_table = Table(left->bag, graph_size_);
auto parent_embedding = Embedding(left->bag, graph_size_);
do {
auto &parent_gain = parent_table[parent_embedding];
auto &left_gain = left->table[parent_embedding];
auto &right_gain = right->table[parent_embedding];
if (left_gain != kNone && right_gain != kNone) {
parent_gain = left_gain + right_gain - gain_.Join(parent_embedding);
}
} while (parent_embedding.Next());
return DynamicResult(parent_bag, parent_table, left, right);
}
void RetrieveEmbeddingDfs(const Dynamic::Result &subtree, SlowEmbedding *full, SlowEmbedding *bag) {
if (!subtree->left) {
// Leaf
} else if (subtree->right) {
// Join
SlowEmbedding bag_copy = *bag;
RetrieveEmbeddingDfs(subtree->left, full, bag);
*bag = bag_copy;
RetrieveEmbeddingDfs(subtree->right, full, bag);
} else if (subtree->bag.Size() > subtree->left->bag.Size()) {
// Introduce
SigEdge introduced = *(subtree->bag - subtree->left->bag).begin();
bag->Remove(introduced);
RetrieveEmbeddingDfs(subtree->left, full, bag);
} else {
// Forget
SigEdge forgotten = *(subtree->left->bag - subtree->bag).begin();
int idx = bag->Domain().Index(forgotten);
int lowest = idx > 0 ? (*bag)(bag->Domain().Nth(idx)).id + 1 : 0;
int highest = idx < bag->Domain().Size() ? (*bag)(bag->Domain().Nth(idx + 1)).id - 1 : bag->Codomain() - 1;
int64_t best = std::numeric_limits<int64_t>::min();
int best_i = -1;
for (int i = lowest; i <= highest; ++i) {
bag->SetVal(forgotten, CycleEdge(i));
int64_t now = subtree->left->table[bag->Index()];
if (now > best) {
best = now;
best_i = i;
}
}
full->SetVal(forgotten, CycleEdge(best_i));
bag->SetVal(forgotten, CycleEdge(best_i));
RetrieveEmbeddingDfs(subtree->left, full, bag);
}
}
SlowEmbedding RetrieveEmbedding(const Dynamic::Result &root, int graph_size) {
SlowEmbedding full(graph_size), bag(graph_size);
RetrieveEmbeddingDfs(root, &full, &bag);
return full;
}
std::ostream& operator<<(std::ostream &stream, const Dynamic::Result &result) {
return stream << "bag: " << result->bag << "\ntable: " << result->table;
}
std::ostream& operator<<(std::ostream &stream, const Dynamic::Table &table) {
stream << "{\n";
Embedding embedding(table.bag_, table.graph_size_);
do {
stream << embedding << ": " << table[embedding] << '\n';
} while (embedding.Next());
stream << "}\n";
return stream;
}
} // namespace kopt
| 33.9 | 120 | 0.676438 | miazgatron |
c2d89cae8b5e5c00cb67576c69d4670cd2b8e0ca | 1,574 | cpp | C++ | 0472-Binary Tree Path Sum III/0472-Binary Tree Path Sum III.cpp | nmdis1999/LintCode-1 | 316fa395c9a6de9bfac1d9c9cf58acb5ffb384a6 | [
"MIT"
] | 77 | 2017-12-30T13:33:37.000Z | 2022-01-16T23:47:08.000Z | 0401-0500/0472-Binary Tree Path Sum III/0472-Binary Tree Path Sum III.cpp | jxhangithub/LintCode-1 | a8aecc65c47a944e9debad1971a7bc6b8776e48b | [
"MIT"
] | 1 | 2018-05-14T14:15:40.000Z | 2018-05-14T14:15:40.000Z | 0401-0500/0472-Binary Tree Path Sum III/0472-Binary Tree Path Sum III.cpp | jxhangithub/LintCode-1 | a8aecc65c47a944e9debad1971a7bc6b8776e48b | [
"MIT"
] | 39 | 2017-12-07T14:36:25.000Z | 2022-03-10T23:05:37.000Z | /**
* Definition of ParentTreeNode:
* class ParentTreeNode {
* public:
* int val;
* ParentTreeNode *parent, *left, *right;
* }
*/
class Solution {
public:
/**
* @param root the root of binary tree
* @param target an integer
* @return all valid paths
*/
vector<vector<int>> binaryTreePathSum3(ParentTreeNode *root, int target) {
// Write your code here
vector<vector<int>> result;
dfs(root, target, result);
return result;
}
private:
void dfs(ParentTreeNode* root, int target, vector<vector<int>>& result) {
if (root == nullptr)
{
return;
}
vector<int> path;
findSum(root, nullptr, target, path, result);
dfs(root->left, target, result);
dfs(root->right, target, result);
}
void findSum(ParentTreeNode* root, ParentTreeNode* prev, int target,
vector<int>& path, vector<vector<int>>& result) {
path.push_back(root->val);
target -= root->val;
if (target == 0) {
result.push_back(path);
}
if (root->parent && root->parent != prev) {
findSum(root->parent, root, target, path, result);
}
if (root->left && root->left != prev) {
findSum(root->left, root, target, path, result);
}
if (root->right && root->right != prev) {
findSum(root->right, root, target, path, result);
}
path.pop_back();
}
};
| 26.677966 | 78 | 0.52033 | nmdis1999 |
c2d9e510f92b68c5283fcd660a91a1018ff5c2c6 | 17,005 | cpp | C++ | src/cut/CutHelper.cpp | akazachk/vpc | 2339159e963b30287f780b6c03202fcbf0e9c131 | [
"MIT"
] | 6 | 2019-03-18T00:22:43.000Z | 2022-03-16T19:21:21.000Z | src/cut/CutHelper.cpp | akazachk/vpc | 2339159e963b30287f780b6c03202fcbf0e9c131 | [
"MIT"
] | 14 | 2019-03-18T03:30:53.000Z | 2020-10-08T15:32:45.000Z | src/cut/CutHelper.cpp | akazachk/vpc | 2339159e963b30287f780b6c03202fcbf0e9c131 | [
"MIT"
] | 2 | 2021-10-05T17:44:29.000Z | 2021-11-04T20:45:01.000Z | /**
* @file CutHelper.hpp
* @author A. M. Kazachkov
* @date 2019-02-20
*/
#include "CutHelper.hpp"
#include <numeric> // inner_product, sqrt
#include <OsiCuts.hpp>
#include <OsiSolverInterface.hpp>
#include "CglVPC.hpp" // For FailureType
#include "SolverHelper.hpp"
/**
* @details The cut is stored as alpha x >= beta.
*/
void setOsiRowCut(OsiRowCut* const cut, const std::vector<int>& nonZeroColIndex,
const int num_coeff, const double* coeff, const double rhs,
const double EPS) {
std::vector<int> indices;
std::vector<double> sparse_coeff;
indices.reserve(num_coeff);
sparse_coeff.reserve(num_coeff);
for (int i = 0; i < num_coeff; i++) {
if (!isZero(coeff[i], EPS)) {
indices.push_back((nonZeroColIndex.size() > 0) ? nonZeroColIndex[i] : i);
sparse_coeff.push_back(coeff[i]);
}
}
cut->setLb(rhs);
cut->setRow((int) indices.size(), indices.data(),
sparse_coeff.data());
} /* setOsiRowCut */
/**
* @brief Remove small coefficients if we are fairly sure they do not matter
* @details Taken from CglGMI with some modifications, including switching to >= cut as we use.
*
* More recently (2021-05-21), function does not remove some small coefficients,
* namely when there is no bound associated with the variable,
* due to issue with original/coral/neos-593853 -d2.
*
* TODO there should be a safer way of doing this method,
* such as making sure we do not cut any of the "verification points and rays"
* (i.e., the rows of the PRLP, but in structural space).
*/
void removeSmallCoefficients(OsiRowCut* const cut, const OsiSolverInterface* const solver, const double EPS, const double EPS_COEFF) {
CoinPackedVector vec = cut->mutableRow();
int cutNz = vec.getNumElements();
int* cutIndex = vec.getIndices();
double* cutElem = vec.getElements();
double cutRhs = cut->rhs();
const double* colLower = solver->getColLower();
const double* colUpper = solver->getColUpper();
double coeff, absval;
int currPos = 0;
int col;
for (int i = 0; i < cutNz; ++i) {
col = cutIndex[i];
coeff = cutElem[i];
absval = std::abs(coeff);
if (isZero(absval, EPS)
&& isZero(absval * solver->getObjCoefficients()[col], EPS)) {
continue; // throw away this element
}
if (absval <= EPS_COEFF) {
// small coefficient: remove and adjust rhs if possible
if ((coeff < 0.0) && !isNegInfinity(colLower[col])) {
cutRhs -= coeff * colLower[col];
} else if ((coeff > 0.0) && !isInfinity(colUpper[col])) {
cutRhs -= coeff * colUpper[col];
} else {
// Added this because sometimes small coefficients are necessary,
// such as in the case of original/coral/neos-593853 -d2,
// in which there are large matrix coefficients,
// and setting coefficient alpha_{612} = 0 (from 6e-7)
// causes an invalid cut
// TODO however, this is probably not ideal for other instances,
// and we should implement a more careful check
if (currPos < i) {
cutIndex[currPos] = col;
cutElem[currPos] = coeff;
}
currPos++;
}
} else if (absval > EPS_COEFF) {
if (currPos < i) {
cutIndex[currPos] = col;
cutElem[currPos] = coeff;
}
currPos++;
}
}
cutNz = currPos;
cut->setRow(cutNz, cutIndex, cutElem);
if (isZero(cutRhs, EPS)) {
cutRhs = 0.;
}
cut->setLb(cutRhs);
} /* removeSmallCoefficients */
/// @brief Returns whether \p cutNz > \p max_sup_abs + \p max_sup_rel * \p numCols
bool badSupport(const int cutNz, const int numCols, const double max_sup_abs, const double max_sup_rel) {
return (cutNz > max_sup_abs + max_sup_rel * numCols);
} /* badSupport */
bool badViolation(const OsiRowCut* const cut, const OsiSolverInterface* const solver, const double min_viol_abs, const double min_viol_rel) {
// Check the cut
const double currCutNorm = cut->row().twoNorm();
const double violation = cut->violated(solver->getColSolution());
// const bool cuttingSolutionFlagAbs = (inNBSpace)
// ? lessThanVal(cutSolver->getObjValue() - beta, 0.0, param.getMIN_VIOL_ABS())
// : greaterThanVal(currCut.violated(origSolver->getColSolution()), 0.0, param.getMIN_VIOL_ABS());
// const bool cuttingSolutionFlagRel = (inNBSpace)
// ? lessThanVal(cutSolver->getObjValue() - beta, 0.0, currCutNorm * param.getMIN_VIOL_REL())
// : greaterThanVal(currCut.violated(origSolver->getColSolution()), 0.0, currCutNorm * param.getMIN_VIOL_REL());
const bool cuttingSolutionFlagAbs = //(inNBSpace) ||
greaterThanVal(violation, 0.0, min_viol_abs);
const bool cuttingSolutionFlagRel = //(inNBSpace) ||
greaterThanVal(violation, 0.0, currCutNorm * min_viol_rel);
return (!cuttingSolutionFlagAbs || !cuttingSolutionFlagRel);
} /* badViolation */
/// @brief Check whether max coeff in the cut and min coeff in the cut are too different in scale
bool badDynamism(const OsiRowCut* const cut, const double minAbsCoeff, const double maxAbsCoeff, const double SENSIBLE_MAX, const double EPS) {
const CoinPackedVector vec = cut->row();
const int num_el = vec.getNumElements();
const double* el = vec.getElements();
double minAbsElem = 0.0, maxAbsElem = 0.0;
for (int i = 0; i < num_el; i++) {
const double absCurr = std::abs(el[i]);
if (isZero(absCurr, EPS)) { // make sure min and max are not zero
continue;
}
if ((minAbsElem > absCurr) || isZero(minAbsElem, EPS)) {
minAbsElem = absCurr;
}
if (maxAbsElem < absCurr) {
maxAbsElem = absCurr;
}
}
const double absCurr = std::abs(cut->rhs());
if (absCurr > maxAbsElem) {
maxAbsElem = absCurr;
}
return isZero(maxAbsElem, EPS)
// || isZero(minAbsElem / maxAbsElem)
|| greaterThanVal(maxAbsElem / minAbsElem, SENSIBLE_MAX, EPS)
|| (!isZero(minAbsCoeff, EPS)
&& greaterThanVal(std::abs(maxAbsElem / minAbsCoeff),
std::abs(SENSIBLE_MAX * maxAbsCoeff / minAbsCoeff), EPS));
} /* badDynamism */
/// @details Scale cut so that coefficients are neither too small nor too big
/// similarly to how rays are scaled in nbspace.cpp #setCompNBCoorRay
void scaleCut(OsiRowCut* const cut, const double EPS) {
CoinPackedVector vec = cut->mutableRow();
const int num_el = vec.getNumElements();
double* el = vec.getElements();
double minAbsElem = 0.0, maxAbsElem = 0.0;
for (int i = 0; i < num_el; i++) {
const double absCurr = std::abs(el[i]);
if (isZero(absCurr, EPS)) { // make sure min and max are not zero
continue;
}
if ((minAbsElem > absCurr) || isZero(minAbsElem, EPS)) {
minAbsElem = absCurr;
}
if (maxAbsElem < absCurr) {
maxAbsElem = absCurr;
}
} // loop over cut coefficients
const double absRHS = std::abs(cut->rhs());
if (absRHS > maxAbsElem) {
maxAbsElem = absRHS;
}
// TODO I am not sure where these values come from exactly...
int minExponent = std::log10(minAbsElem);
int maxExponent = std::log10(maxAbsElem);
const double avgExponents = 0.5 * (minExponent + maxExponent);
int scale_exp = 0;
if (avgExponents < -0.25) {
scale_exp = 1 - static_cast<int>(avgExponents + 0.25);
}
const double scale = std::pow(10., static_cast<double>(scale_exp));
vec *= scale;
cut->setLb(cut->lb() * scale);
} /* scaleCut */
/**
* @details Based on the similar method in CglGMI, we clean the cut coefficients and check if the cut is good
* Returns 0 if no error, otherwise returns -1 * (fail index + 1)
*/
int cleanCut(OsiRowCut* const cut,
const OsiSolverInterface* const solver,
const double EPS_COEFF,
const double MAX_DYN,
const int MAX_SUP_ABS,
const double MAX_SUP_REL,
const double MIN_VIOL_ABS,
const double MIN_VIOL_REL,
const double MIN_ABS_COEFF,
const double MAX_ABS_COEFF,
const double EPS,
const bool checkViolation) {
removeSmallCoefficients(cut, solver, EPS, EPS_COEFF);
if (badSupport(cut->row().getNumElements(), solver->getNumCols(), MAX_SUP_ABS, MAX_SUP_REL)) {
return -1 * (static_cast<int>(CglVPC::FailureType::BAD_SUPPORT) + 1);
}
if (checkViolation && badViolation(cut, solver, MIN_VIOL_ABS, MIN_VIOL_REL)) {
return -1 * (static_cast<int>(CglVPC::FailureType::BAD_VIOLATION) + 1);
}
if (badDynamism(cut, MIN_ABS_COEFF, MAX_ABS_COEFF,
CoinMax((EPS > 0) ? 1. / EPS : MAX_DYN, MAX_DYN), EPS)) {
return -1 * (static_cast<int>(CglVPC::FailureType::BAD_DYNAMISM) + 1);
}
return 0;
} /* cleanCut */
/**
* @details The value of eps will be used to determine whether a cut coefficient is zero or not.
* We are roughly checking that whether cut1 = ratio * cut2 for some ratio.
* Let ratio = rhs1 / rhs2. (If both are non-zero. Typically both are = 1.)
* We say the cuts are "truly different" if |coeff^1_j - ratio * coeff^2_j| >= diffeps.
* However, might be that the cut coefficients are scaled versions, but the rhs values are different.
* So we also compute ratio_coeff = coeff^1_j / coeff^2_j for the first j where both are non-zero.
* If |coeff^1_j - ratio * coeff^2_j| >= diffeps for some j,
* but |coeff^1_j - ratio_coeff * coeff^2_j| < diffeps for all j,
* then the return code will be -1 or 1 (essentially, one cut will dominate the other).
*
* By the way, this is all essentially checking orthogonality...
*
* @return
* 0: seem same in coeff and rhs,
* +/-1: seem same in coeff, but diff in rhs (-1: cut1 better, +1: cut2 better),
* 2: seem different in coeff and rhs.
*/
int isRowDifferent(const CoinPackedVectorBase* const cut1Vec, const double cut1rhs,
const CoinPackedVectorBase* const cut2Vec, const double cut2rhs, const double EPS) {
const int numElem1 = cut1Vec->getNumElements();
const int* index1 = cut1Vec->getIndices();
const double* value1 = cut1Vec->getElements();
const int numElem2 = cut2Vec->getNumElements();
const int* index2 = cut2Vec->getIndices();
const double* value2 = cut2Vec->getElements();
double ratio = -1.0;
double ratio_coeff = -1.0;
double maxDiff = 0.;
double maxDiffCoeff = 0.;
double maxDiffZero = 0.;
// First, we try to get the ratio from RHS
if (isZero(cut1rhs, EPS) || isZero(cut2rhs, EPS)) {
// If one but not both are 0, then the cuts are clearly different
// But they may only differ in the rhs
if (!isZero(cut1rhs, EPS)) {
maxDiff = std::abs(cut1rhs);
} else if (!isZero(cut2rhs, EPS)) {
maxDiff = std::abs(cut2rhs);
}
// Otherwise, they're both near zero,
// and we're not going to be able to get
// any kind of ratio from here
} else {
ratio = cut1rhs / cut2rhs;
}
// Now check if this ratio (if we found one) holds for
// all the coefficients. In particular, we check that
// std::abs(cut1.coeff - ratio * cut2.coeff) < eps
int ind2 = 0;
for (int ind1 = 0; ind1 < numElem1; ind1++) {
// Find matching indices
while (ind2 < numElem2 && index1[ind1] > index2[ind2]) {
if (!isZero(value2[ind2], EPS)) {
return 2;
}
if (value2[ind2] > maxDiffZero) {
maxDiffZero = std::abs(value2[ind2]);
}
ind2++;
}
// If we reached end of the second cut,
// or index1[ind1] does not exist in the second cut,
// capture maxDiffZero, or exit early if something "really different" detected
if (ind2 >= numElem2 || index2[ind2] > index1[ind1]) {
if (!isZero(value1[ind1], EPS)) {
return 2;
}
if (value1[ind1] > maxDiffZero) {
maxDiffZero = std::abs(value1[ind1]);
}
continue;
}
// Either one or both of the coefficients may be zero,
// in which case both better be zero.
if (isZero(value1[ind1], EPS) || isZero(value2[ind2], EPS)) {
if (!isZero(value1[ind1], EPS) || !isZero(value2[ind2], EPS)) {
return 2; // truly different
}
ind2++;
continue;
}
// Alternatively, we make sure inequality is not scaled version of other
// Set scale factor if it has not been set before
if (lessThanVal(ratio, 0.0)) {
ratio = value1[ind1] / value2[ind2];
if (lessThanVal(ratio, 0.0)) {
// The scale is negative
// Potentially one cut is the negative of the other,
// but they are thus still distinct
// (all cuts are ax >= b)
return 2;
}
} else {
const double diff = std::abs(value1[ind1] - ratio * value2[ind2]);
if (diff > maxDiff) {
maxDiff = diff;
}
}
// Also check the ratio_coeff in case one cut dominates the other
if (lessThanVal(ratio_coeff, 0.0)) {
ratio_coeff = value1[ind1] / value2[ind2];
if (lessThanVal(ratio_coeff, 0.0)) {
// The scale is negative
// Potentially one cut is the negative of the other,
// but they are thus still distinct
// (all cuts are ax >= b)
return 2;
}
} else {
const double diff = std::abs(value1[ind1] - ratio_coeff * value2[ind2]);
if (diff > maxDiffCoeff) {
maxDiffCoeff = diff;
}
}
if (!isZero(maxDiff, EPS) && !isZero(maxDiffCoeff, EPS)) {
return 2;
}
ind2++;
} /* iterate over cut1 coefficients */
// Check any remaining cut2 indices that were not matched
while (ind2 < numElem2) {
if (!isZero(value2[ind2], EPS)) {
return 2;
}
if (value2[ind2] > maxDiffZero) {
maxDiffZero = std::abs(value2[ind2]);
}
ind2++;
}
// Are the cuts scaled versions of one another?
if (isZero(maxDiff, EPS)) {
return 0; // they seem the same
}
// Are the cut coefficients scaled versions of one another?
if (isZero(maxDiffCoeff, EPS)) {
if (lessThanVal(ratio_coeff, 0., EPS)) {
return 2; // cuts face opposite directions
}
// Either one or the other rhs will be better
const double rhs_diff = cut1rhs - ratio_coeff * cut2rhs;
if (isZero(rhs_diff, EPS)) {
return 0; // they seem the same, not sure how ratio missed it
} else if (greaterThanVal(rhs_diff, 0., EPS)) {
return -1;
} else {
return 1;
}
}
return 0;
} /* isRowDifferent */
/**
* Two vectors are parallel iff u.v/|u|*|v| = 1
*/
double getParallelism(const CoinPackedVectorBase& vec1,
const CoinPackedVectorBase& vec2) {
const double scalarprod = dotProduct(vec1, vec2);
return scalarprod / (vec1.twoNorm() * vec2.twoNorm());
} /* getParallelism (packed vectors) */
/**
* Two vectors are parallel iff u.v/|u|*|v| = 1
*/
double getParallelism(const CoinPackedVectorBase& vec1, const int numElem,
const double* vec2) {
const double scalarprod = vec1.dotProduct(vec2);
const double norm1 = vec1.twoNorm();
const double norm2 = std::sqrt(std::inner_product(vec2, vec2 + numElem, vec2, 0.0L));
return scalarprod / (norm1 * norm2);
} /* getParallelism (packed and not packed) */
/**
* Two vectors are parallel iff u.v/|u|*|v| = 1
*/
double getParallelism(const int numElem, const double* vec1,
const double* vec2) {
const double scalarprod = dotProduct(vec1, vec2, numElem);
const double norm1 = std::sqrt(std::inner_product(vec1, vec1 + numElem, vec1, 0.0L));
const double norm2 = std::sqrt(std::inner_product(vec2, vec2 + numElem, vec2, 0.0L));
return scalarprod / (norm1 * norm2);
} /* getParallelism (not packed) */
/**
* Two vectors are parallel iff u.v/|u|*|v| = 1
*/
double getOrthogonality(const CoinPackedVectorBase& vec1,
const CoinPackedVectorBase& vec2) {
return 1. - getParallelism(vec1, vec2);
} /* getOrthogonality (packed vectors) */
/**
* Two vectors are parallel iff u.v/|u|*|v| = 1
*/
double getOrthogonality(const CoinPackedVectorBase& vec1, const int numElem,
const double* vec2) {
return 1. - getParallelism(vec1, numElem, vec2);
} /* getOrthogonality (packed and not packed) */
/**
* Two vectors are parallel iff u.v/|u|*|v| = 1
*/
double getOrthogonality(const int numElem, const double* vec1,
const double* vec2) {
return 1. - getParallelism(numElem, vec1, vec2);
} /* getOrthogonality (not packed) */
/**
* @details Check whether a cut is duplicate or too orthogonal to a previous cut in the collection
*/
int howDuplicate(const OsiCuts& cuts, const OsiRowCut& tmpCut,
const int startIndex, int& duplicateCutIndex, int& minOrthoIndex,
double& minOrtho, const double MIN_ORTHO, const double EPS) {
duplicateCutIndex = -1;
minOrthoIndex = -1;
minOrtho = 2.;
for (int i = startIndex; i < cuts.sizeCuts(); i++) {
const OsiRowCut* currCut = cuts.rowCutPtr(i);
if (MIN_ORTHO > 0) {
const double this_ortho = getOrthogonality(tmpCut.row(), currCut->row());
if (this_ortho < minOrtho) {
minOrtho = this_ortho;
minOrthoIndex = i;
}
}
const int howDifferent = isRowDifferent(&currCut->row(), currCut->rhs(), &tmpCut.row(), tmpCut.rhs(), EPS);
if (howDifferent != 2) {
duplicateCutIndex = i;
return howDifferent;
}
}
return 0;
} /* howDuplicate */
| 35.501044 | 143 | 0.65122 | akazachk |
c2da09d7d51ba964b16f7ec809caacc2ceb60e22 | 593 | hpp | C++ | src/face/detecter/retinaface/retinaface.hpp | bububa/openvision | 0864e48ec8e69ac13d6889d41f7e1171f53236dd | [
"Apache-2.0"
] | 1 | 2022-02-08T06:42:05.000Z | 2022-02-08T06:42:05.000Z | src/face/detecter/retinaface/retinaface.hpp | bububa/openvision | 0864e48ec8e69ac13d6889d41f7e1171f53236dd | [
"Apache-2.0"
] | null | null | null | src/face/detecter/retinaface/retinaface.hpp | bububa/openvision | 0864e48ec8e69ac13d6889d41f7e1171f53236dd | [
"Apache-2.0"
] | null | null | null | #ifndef _RETINAFACE_H_
#define _RETINAFACE_H_
#include "../detecter.hpp"
#include "net.h"
namespace ovface {
using ANCHORS = std::vector<ov::Rect>;
class RetinaFace : public Detecter {
public:
int LoadModel(const char* root_path);
int DetectFace(const unsigned char* rgbdata,
int img_width, int img_height,
std::vector<FaceInfo>* faces);
private:
std::vector<ANCHORS> anchors_generated_;
const int RPNs_[3] = { 32, 16, 8 };
const Size inputSize_ = { 300, 300 };
const float iouThreshold_ = 0.4f;
const float scoreThreshold_ = 0.8f;
};
}
#endif // !_RETINAFACE_H_
| 20.448276 | 45 | 0.70489 | bububa |
c2dc1f3b339b3d8ae67c56ad65abf4ff43ce5fd6 | 1,185 | cpp | C++ | src/Components/MovementComponent.cpp | BrianErikson/GameEngine | afe798607dda0a6a367867382d628fe02192643c | [
"MIT"
] | null | null | null | src/Components/MovementComponent.cpp | BrianErikson/GameEngine | afe798607dda0a6a367867382d628fe02192643c | [
"MIT"
] | 2 | 2017-04-05T01:23:55.000Z | 2017-04-05T02:29:45.000Z | src/Components/MovementComponent.cpp | BrianErikson/GameEngine | afe798607dda0a6a367867382d628fe02192643c | [
"MIT"
] | null | null | null |
#include "MovementComponent.h"
MovementComponent::MovementComponent() {
this->type = EActorComponent::MOVEMENT;
this->position = Vector3(0,0,0);
this->identity = Matrix();
this->matrix = Matrix();
}
void MovementComponent::tick(const double &deltaTime) {
}
void MovementComponent::render(const double &deltaTime) {
}
void MovementComponent::translate(Vector3 &vec) {
this->translation *= vec;
}
void MovementComponent::rotate(Vector3 &rotator) {
if (rotator.x != 0) {
this->rotation.matrix[1][1] = cos(rotator.x);
this->rotation.matrix[1][2] = sin(rotator.x);
this->rotation.matrix[2][1] = -sin(rotator.x);
this->rotation.matrix[2][2] = cos(rotator.x);
}
if (rotator.y != 0) {
this->rotation.matrix[0][0] = cos(rotator.y);
this->rotation.matrix[0][2] = -sin(rotator.y);
this->rotation.matrix[2][0] = sin(rotator.y);
this->rotation.matrix[2][2] = cos(rotator.y);
}
if (rotator.z != 0) {
this->rotation.matrix[0][0] = cos(rotator.z);
this->rotation.matrix[0][1] = sin(rotator.z);
this->rotation.matrix[1][0] = -sin(rotator.z);
this->rotation.matrix[1][1] = cos(rotator.z);
}
}
Vector3 MovementComponent::getPos() {
return this->translation;
} | 25.76087 | 57 | 0.669198 | BrianErikson |
124140387638308d95c3d34e20770511148f3f4b | 676 | cpp | C++ | Arrays/duplicate.cpp | harshit2000/My-Data-Structures-and-algorithms | 103559086f6fd6a6cee01bed4765c7f4d8681cad | [
"MIT"
] | null | null | null | Arrays/duplicate.cpp | harshit2000/My-Data-Structures-and-algorithms | 103559086f6fd6a6cee01bed4765c7f4d8681cad | [
"MIT"
] | null | null | null | Arrays/duplicate.cpp | harshit2000/My-Data-Structures-and-algorithms | 103559086f6fd6a6cee01bed4765c7f4d8681cad | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int findDuplicate(int arr[], int n){
if (n<=1){
return 0;
}
int tortoise = arr[0];
int hare = arr[arr[0]];
while (hare!=tortoise){
tortoise = arr[tortoise];
hare = arr[arr[hare]];
}
hare = 0;
while (tortoise!=hare){
tortoise = arr[tortoise];
hare = arr[hare];
}
return tortoise;
}
signed main(){
int n;
cout<<"Enter size of the array\n";
cin>>n;
int arr[n];
int i=0;
cout<<"Enter the array\n";
while (i<n){
cin>>arr[i];
i++;
}
int ans = findDuplicate(arr,n);
cout<<endl<<ans<<endl;
} | 16.095238 | 38 | 0.502959 | harshit2000 |
124294663d28a53676af4b0d53f4b8e3fd465689 | 2,053 | cpp | C++ | 146.cpp | adlternative/algorithm-Brush | 0ad801ae519a0d1258faac364a8802e435397899 | [
"Apache-2.0"
] | null | null | null | 146.cpp | adlternative/algorithm-Brush | 0ad801ae519a0d1258faac364a8802e435397899 | [
"Apache-2.0"
] | null | null | null | 146.cpp | adlternative/algorithm-Brush | 0ad801ae519a0d1258faac364a8802e435397899 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
#include <errno.h>
#include <fcntl.h>
#include <memory>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
class LRUCache {
public:
LRUCache(int capacity) : capacity_(capacity) {}
int get(int key) {
const auto &vPtr = kv.find(key);
/* 没找到 */
if (vPtr == kv.end())
return -1;
/* 找到了则通过迭代器的索引找到
并重新放到链表头 (删除再插入)*/
auto kv = vPtr->second;
int k = kv->first;
int v = kv->second;
l.erase(kv);
l.push_front({k, v});
vPtr->second = l.begin();
return v;
}
void put(int key, int value) {
// /* 找到了 修改就好 将值设到最大*/
const auto &vPtr = kv.find(key);
// /* 找到 */
if (vPtr != kv.end()) {
auto kv = vPtr->second;
l.erase(kv);
l.push_front({key, value});
vPtr->second = l.begin();
return;
}
/* 否则如果满了 */
if (kv.size() == capacity_) {
kv.erase(l.back().first);
l.pop_back();
l.push_front({key, value});
kv[key] = l.begin();
} else {
l.push_front({key, value});
kv[key] = l.begin();
}
}
list<pair<int, int>> l; /* 时间升序链表 存放k,v */
int capacity_; /* 容量 */
unordered_map<int, list<pair<int, int>>::iterator>
kv; /* k->list::iter 负责get O1*/
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
int main(int argc, char const *argv[]) {
/* code */
LRUCache *lRUCache = new LRUCache(2);
lRUCache->put(1, 1); // 缓存是 {1=1}
lRUCache->put(2, 2); // 缓存是 {1=1, 2=2}×
std::cout << lRUCache->get(1) << std::endl; // 返回 1
lRUCache->put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
std::cout << lRUCache->get(2) << std::endl; // 返回 -1 (未找到)
lRUCache->put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
std::cout << lRUCache->get(1) << std::endl; // 返回 -1 (未找到)
std::cout << lRUCache->get(3) << std::endl; // 返回 3
std::cout << lRUCache->get(4) << std::endl; // 返回 4
return 0;
}
| 25.6625 | 64 | 0.53434 | adlternative |
12482c41cbb6292757221fdf09ed133b1df5cab0 | 3,643 | cpp | C++ | src/TryEngine/Window/TEWindow.cpp | b-pelmoine/TryEngine | 2495504106da8b42f7fb86bdf1f1a42f6b4ce581 | [
"MIT"
] | null | null | null | src/TryEngine/Window/TEWindow.cpp | b-pelmoine/TryEngine | 2495504106da8b42f7fb86bdf1f1a42f6b4ce581 | [
"MIT"
] | null | null | null | src/TryEngine/Window/TEWindow.cpp | b-pelmoine/TryEngine | 2495504106da8b42f7fb86bdf1f1a42f6b4ce581 | [
"MIT"
] | null | null | null | #include "TryEngine/Window/TEWindow.hpp"
#include <TryEngine.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Graphics.hpp>
TEWindow::TEWindow(TEWindowOptions&& options) :
m_options(options), m_texture(std::make_shared<sf::RenderTexture>()), m_input(std::make_shared<TEInput>()), m_active(false), bUsePostProcess(false)
{
for(size_t i=0; i < static_cast<size_t>(Layer::_Count); ++i)
{
m_drawables[static_cast<Layer>(i)] = std::vector<std::weak_ptr<sf::Drawable>>();
}
ApplyConfig();
}
TEWindow::TEWindow(std::shared_ptr<sf::RenderWindow> window) :
m_window(window), m_texture(std::make_shared<sf::RenderTexture>()), m_input(std::make_shared<TEInput>()), m_active(true), bUsePostProcess(true)
{
for(size_t i=0; i < static_cast<size_t>(Layer::_Count); ++i)
{
m_drawables[static_cast<Layer>(i)] = std::vector<std::weak_ptr<sf::Drawable>>();
}
SaveCurrentConfig();
InitializeRenderTexture();
}
void TEWindow::ConfigurePostProcess(const std::string& shaderID)
{
bUsePostProcess = !shaderID.empty();
if(bUsePostProcess)
TE.Resources().lock()->GetShader(shaderID, m_postProcessShader);
}
void TEWindow::Config(const TEWindowOptions& options)
{
m_options = options;
ApplyConfig();
}
void TEWindow::SaveCurrentConfig()
{
m_options.size = m_window->getSize();
m_options.settings = m_window->getSettings();
}
void TEWindow::ApplyConfig()
{
sf::VideoMode mode = (m_options.style == sf::Style::Fullscreen)
? m_options.fullScreenMode : sf::VideoMode(m_options.size.x, m_options.size.y);
if(!m_window)
{
m_window = std::make_shared<sf::RenderWindow>(
mode,
m_options.name,
m_options.style,
m_options.settings
);
}
else
{
m_window->create(
mode,
m_options.name,
m_options.style,
m_options.settings
);
}
m_active = true;
InitializeRenderTexture();
m_window->setPosition(m_options.position);
}
void TEWindow::InitializeRenderTexture()
{
if(m_options.style == sf::Style::Fullscreen)
{
auto size = m_window->getSize();
m_texture->create(size.x, size.y);
}
else
{
m_texture->create(m_options.size.x, m_options.size.y);
}
}
void TEWindow::HandleEvents()
{
sf::Event event;
while (m_window->pollEvent(event)) {
m_input->Handle(event);
}
if(m_input->ReceivedCloseEvent())
{
m_active = false;
}
}
void TEWindow::PostUpdate()
{
m_input->PostUpdate();
}
void TEWindow::Draw()
{
m_texture->clear(sf::Color::Blue);
for(const auto& layer: m_drawables)
{
for(const auto& drawable: layer.second)
{
m_texture->draw(*(drawable.lock()));
}
}
m_texture->display();
m_window->clear(sf::Color::Black);
sf::Sprite processedPicture(m_texture->getTexture());
if(bUsePostProcess)
{
m_window->draw(processedPicture, &m_postProcessShader->Get());
}
else
{
m_window->draw(processedPicture);
}
}
void TEWindow::Display()
{
m_window->display();
}
void TEWindow::AddDrawable(std::shared_ptr<sf::Drawable> drawable, const Layer& layer)
{
m_drawables[layer].push_back(drawable);
}
void TEWindow::RemoveDrawable(std::shared_ptr<sf::Drawable> drawable, const Layer& layer)
{
auto& vector = m_drawables[layer];
vector.erase(std::remove_if(vector.begin(), vector.end(),
[drawable](std::weak_ptr<sf::Drawable> other) {
return drawable == other.lock();
}), vector.end());
} | 24.614865 | 147 | 0.634642 | b-pelmoine |
124a9d3ca4f8dee49b14fbac3170ba9637e6a637 | 2,874 | hpp | C++ | include/ethutilities/ArpController.hpp | JohnnyB1290/jblib-platform-abstract-netutilities | 83a843f79d12a89e01b758ad6b352f56a4c41eca | [
"Apache-2.0"
] | null | null | null | include/ethutilities/ArpController.hpp | JohnnyB1290/jblib-platform-abstract-netutilities | 83a843f79d12a89e01b758ad6b352f56a4c41eca | [
"Apache-2.0"
] | null | null | null | include/ethutilities/ArpController.hpp | JohnnyB1290/jblib-platform-abstract-netutilities | 83a843f79d12a89e01b758ad6b352f56a4c41eca | [
"Apache-2.0"
] | null | null | null | /**
* @file
* @brief Arp Controller class Description
*
*
* @note
* Copyright © 2019 Evgeniy Ivanov. Contacts: <strelok1290@gmail.com>
* All rights reserved.
* @note
* 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
* @note
* 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.
*
* @note
* This file is a part of JB_Lib.
*/
#ifndef ARP_CONTROLLER_HPP_
#define ARP_CONTROLLER_HPP_
#include "jbkernel/jb_common.h"
#include "ethutilities/EthernetUtilities.hpp"
#include "jbkernel/IVoidEthernet.hpp"
#include "jbkernel/callback_interfaces.hpp"
namespace jblib
{
namespace ethutilities
{
using namespace jbkernel;
#pragma pack(push, 1)
typedef struct {
uint8_t ip[ARP_CONTROLLER_MAX_NUM_IP_FOR_REPLY][ETX_PROTO_SIZE]{};
uint8_t mask[ARP_CONTROLLER_MAX_NUM_IP_FOR_REPLY][ETX_PROTO_SIZE]{};
uint16_t ipCount = 0;
}IpTableForReply_t;
typedef struct{
uint8_t ip[ETX_PROTO_SIZE]{}; // ip
uint8_t mac[ETX_HW_SIZE]{}; //mac
uint32_t timeAfterUpdate = 0; //time after last arp update
}ArpTableLine_t;
typedef struct {
uint16_t recordCounter = 0;
ArpTableLine_t line[ARP_CONTROLLER_ARP_TABLE_SIZE];
}ArpTable_t;
#pragma pack(pop)
class ArpController : public IEthernetListener, IVoidCallback
{
public:
ArpController(IVoidEthernet* ethernetAdapter);
virtual ~ArpController(void);
virtual void parseFrame(EthernetFrame* const frame,
uint16_t frameSize, IVoidEthernet* const source, void* parameter);
void sendGratiousArp(uint8_t* srcIp);
void sendArpRequest(uint8_t* dstIp);
void sendArpRequest(uint8_t* dstIp, uint8_t* srcIp);
void addIpForArpReply(uint8_t* ip);
void addIpForArpReply(uint8_t* ip, uint8_t* mask);
bool isIpInTableForReply(uint8_t* ip);
bool getMac(uint8_t* ip, uint8_t* mac);
bool getIp(uint8_t* mac, uint8_t* ip);
virtual void voidCallback(void* const source, void* parameter);
ArpTable_t* getArpTable(void);
private:
int16_t getArpTableIndex(uint8_t* ip);
void createReply(uint8_t* request, uint8_t* reply, uint8_t* srcMac, uint16_t* frameSize);
void createReply(const uint8_t* dstMac, const uint8_t* dstIp, uint8_t* srcMac, uint8_t* srcIp, uint8_t* reply, uint16_t* frameSize);
void createRequest(const uint8_t* dstIp, uint8_t* srcMac,uint8_t* srcIp, uint8_t* request, uint16_t* frameSize);
uint8_t* mac_ = NULL;
IVoidEthernet* ethernetAdapter_ = NULL;
IpTableForReply_t ipTableForReply_;
ArpTable_t arpTable_;
};
}
}
#endif /* ARP_CONTROLLER_HPP_ */
| 28.74 | 133 | 0.764092 | JohnnyB1290 |
125382d6def9a4983547ad4da454e6dc3b13bc80 | 296 | cpp | C++ | UPCFramework/NCamera2D.cpp | UPC-DESARROLLO-JUEGOS-1/DJ12017-II-FinalProject | 4a866769056ea4443bafea43f875885e550549ba | [
"MIT"
] | 1 | 2020-04-24T21:50:50.000Z | 2020-04-24T21:50:50.000Z | Sesion-1-Ambiente/UPCFramework/NCamera2D.cpp | UPC-DESARROLLO-JUEGOS-1/2017-II-Shooter2D- | e8c17abe3023272f807cad38a11991d21b9242b8 | [
"MIT"
] | null | null | null | Sesion-1-Ambiente/UPCFramework/NCamera2D.cpp | UPC-DESARROLLO-JUEGOS-1/2017-II-Shooter2D- | e8c17abe3023272f807cad38a11991d21b9242b8 | [
"MIT"
] | null | null | null | #include "NCamera2D.h"
void NCamera2D::Initialize(int screenWidth, int screenHeight) {
NBaseCamera::Initialize(screenWidth, screenHeight);
mProjectionMatrix = glm::ortho(0.0f, (float)screenWidth,
(float)screenHeight, 0.0f);
}
void NCamera2D::Update(float dt) {
NBaseCamera::Update(dt);
} | 24.666667 | 63 | 0.75 | UPC-DESARROLLO-JUEGOS-1 |
1255def4202850ce85dc0a00884f6d27fcf094e8 | 414 | cpp | C++ | codeforces/Competitions/CD#490/sec.cpp | dhwanisanmukhani/competitive-coding | 5392dea65b6ac370ac641c993120d7f252f5b1ac | [
"MIT"
] | null | null | null | codeforces/Competitions/CD#490/sec.cpp | dhwanisanmukhani/competitive-coding | 5392dea65b6ac370ac641c993120d7f252f5b1ac | [
"MIT"
] | null | null | null | codeforces/Competitions/CD#490/sec.cpp | dhwanisanmukhani/competitive-coding | 5392dea65b6ac370ac641c993120d7f252f5b1ac | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
#define icin(x) scanf("%d", &x)
#define lcin(x) scanf("%lld", &x)
typedef long long ll;
int main(){
int n;
icin(n);
string s;
cin >> s;
string t=s;
for(int i=1;i<=n;i++){
if(n%i==0){
for(int j=0;j<i;j++){
t[i-1-j] = s[j];
}
s = t;
}
}
cout << t <<'\n';
} | 14.785714 | 33 | 0.555556 | dhwanisanmukhani |
125e18c07cb52eed2acb54727af9954e2bbcf65f | 5,116 | cpp | C++ | samples/gl/BlinnPhongLighting.cpp | kunka/SoftRender | 8089844e9ab00ab71ef1a820641ec07ae8df248d | [
"MIT"
] | 6 | 2019-01-25T08:41:14.000Z | 2021-08-22T07:06:11.000Z | samples/gl/BlinnPhongLighting.cpp | kunka/SoftRender | 8089844e9ab00ab71ef1a820641ec07ae8df248d | [
"MIT"
] | null | null | null | samples/gl/BlinnPhongLighting.cpp | kunka/SoftRender | 8089844e9ab00ab71ef1a820641ec07ae8df248d | [
"MIT"
] | 3 | 2019-01-25T08:41:16.000Z | 2020-09-04T06:04:29.000Z | //
// Created by huangkun on 2018/4/11.
//
#include "BlinnPhongLighting.h"
#include "Input.h"
TEST_NODE_IMP_BEGIN
BlinnPhongLighting::BlinnPhongLighting() {
const char *vert = R"(
#version 330 core
layout (location = 0) in vec3 a_position;
layout (location = 1) in vec3 a_normal;
layout (location = 2) in vec2 a_tex;
// declare an interface block; see 'Advanced GLSL' for what these are.
out VS_OUT {
vec3 FragPos;
vec3 Normal;
vec2 TexCoords;
} vs_out;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main()
{
gl_Position = projection * view * model * vec4(a_position, 1.0);
vs_out.FragPos = vec3(model * vec4(a_position, 1.0));
vs_out.Normal = mat3(transpose(inverse(model))) * a_normal; // should cal on CPU
// vs_out.Normal = a_normal;
vs_out.TexCoords = a_tex;
}
)";
const char *frag = R"(
#version 330 core
in VS_OUT {
vec3 FragPos;
vec3 Normal;
vec2 TexCoords;
} fs_in;
struct Material {
sampler2D diffuse;
};
uniform Material material;
struct Light {
vec3 position;
vec3 ambient;
vec3 diffuse;
vec3 specular;
};
uniform Light light;
uniform vec3 viewPos;
out vec4 FragColor;
uniform bool blinn;
void main()
{
vec3 color = texture(material.diffuse, fs_in.TexCoords).rgb;
vec3 ambient = light.ambient * color;
vec3 norm = normalize(fs_in.Normal);
vec3 lightDir = normalize(light.position - fs_in.FragPos);
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = light.diffuse * diff * color;
vec3 viewDir = normalize(viewPos - fs_in.FragPos);
float spec = 0;
if(blinn)
{
vec3 halfwayDir = normalize(lightDir + viewDir);
spec = pow(max(dot(norm, halfwayDir), 0.0), 16.0);
}
else
{
vec3 reflectDir = reflect(-lightDir, norm);
spec = pow(max(dot(viewDir, reflectDir), 0.0), 8.0);
}
vec3 specular = light.specular * spec;
FragColor = vec4(diffuse + ambient + specular, 1.0);
}
)";
shader.loadStr(vert, frag);
float vertices[] = {
// positions // normals // texcoords
10.0f, -0.5f, 10.0f, 0.0f, 1.0f, 0.0f, 10.0f, 0.0f,
-10.0f, -0.5f, 10.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
-10.0f, -0.5f, -10.0f, 0.0f, 1.0f, 0.0f, 0.0f, 10.0f,
10.0f, -0.5f, 10.0f, 0.0f, 1.0f, 0.0f, 10.0f, 0.0f,
-10.0f, -0.5f, -10.0f, 0.0f, 1.0f, 0.0f, 0.0f, 10.0f,
10.0f, -0.5f, -10.0f, 0.0f, 1.0f, 0.0f, 10.0f, 10.0f
};
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void *) 0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void *) (3 * sizeof(float)));
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void *) (6 * sizeof(float)));
glEnableVertexAttribArray(2);
// texture
texture = loadTexture("../res/wood.png");
cameraPos = vec3(0.0f, 0.0f, 3.0f);
cameraDir = vec3(0.0f, 0.0f, -1.0f);
glm::quat quat = glm::quat_cast(view);
vec3 angles = eulerAngles(quat);
pitch = -degrees(angles.x);
shader.use();
shader.setMat4("projection", projection);
shader.setInt("material.diffuse", 0);
shader.setVec3("light.ambient", vec3(0.05f, 0.05f, 0.05f));
shader.setVec3("light.diffuse", vec3(1.0f, 1.0f, 1.0f));
shader.setVec3("light.specular", vec3(0.5f, 0.5f, 0.5f));
shader.setVec3("light.position", vec3(0, 0, 0));
}
void BlinnPhongLighting::draw(const mat4 &transform) {
glEnable(GL_DEPTH_TEST);
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
view = glm::lookAt(cameraPos, cameraPos + cameraDir, cameraUp);
shader.use();
shader.setMat4("view", view);
// floor
model = glm::mat4();
shader.setMat4("model", model);
shader.setVec3("viewPos", cameraPos);
shader.setInt("blinn", blinn);
glBindVertexArray(VAO);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisable(GL_DEPTH_TEST);
}
void BlinnPhongLighting::fixedUpdate(float delta) {
CustomDraw::fixedUpdate(delta);
Input *input = Input::getInstance();
if (input->isKeyPressed(GLFW_KEY_B) == GLFW_PRESS && !blinnKeyPressed) {
blinn = !blinn;
blinnKeyPressed = true;
}
if (input->isKeyPressed(GLFW_KEY_B) == GLFW_RELEASE) {
blinnKeyPressed = false;
}
}
BlinnPhongLighting::~BlinnPhongLighting() {
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
}
TEST_NODE_IMP_END | 28.581006 | 105 | 0.603597 | kunka |
12633278144286a73cd3b491f8734bb44ac916df | 1,036 | cpp | C++ | src/folding/mystack.cpp | suncongxd/ReCFA | 55ddadd40a7dc078616e0c4fec7274c26a06aabe | [
"MIT"
] | 4 | 2021-09-09T12:03:36.000Z | 2021-11-28T03:33:46.000Z | src/folding/mystack.cpp | suncongxd/ReCFA | 55ddadd40a7dc078616e0c4fec7274c26a06aabe | [
"MIT"
] | null | null | null | src/folding/mystack.cpp | suncongxd/ReCFA | 55ddadd40a7dc078616e0c4fec7274c26a06aabe | [
"MIT"
] | 1 | 2021-09-09T12:03:41.000Z | 2021-09-09T12:03:41.000Z | #include "mystack.hpp"
#include <iostream>
#include <string.h>
MyStack::MyStack() {
stacktop = 0;
// 初始栈大小为1M
length = 1048576;
stack = new int[length];
}
MyStack::~MyStack() { delete stack; }
int MyStack::pop() {
stacktop--;
return stack[stacktop];
}
int MyStack::top() {
if (stacktop == 0) {
printf("栈空,无栈顶数据\n");
exit(-1);
} else {
return stack[stacktop - 1];
}
}
int MyStack::size() { return stacktop; }
bool MyStack::empty() { return stacktop == 0; }
void MyStack::changePos(int pos) {
if (pos < 0) {
std::cout << "change position wrong,program exit\n";
exit(1);
} else {
stacktop = pos;
}
}
void MyStack::push(int data) {
if (stacktop == length) {
expand();
}
stack[stacktop++] = data;
}
void MyStack::expand() {
int newlength = length * 5;
int *newStack = new int[newlength];
printf("stack expand to %d\n", newlength);
memcpy(newStack, stack, length * 4);
// memcpy(newStack, stack, length);
delete stack;
stack = newStack;
length = newlength;
}
| 17.862069 | 56 | 0.609073 | suncongxd |
1269180601c5ba91869220dd61bc584ebbdda7f9 | 730 | cpp | C++ | 31-40/39. Combination Sum.cpp | zzuliLL/Leetcode- | a14fe1188da008a39d7aaf4e142ee582493b7c60 | [
"MIT"
] | null | null | null | 31-40/39. Combination Sum.cpp | zzuliLL/Leetcode- | a14fe1188da008a39d7aaf4e142ee582493b7c60 | [
"MIT"
] | null | null | null | 31-40/39. Combination Sum.cpp | zzuliLL/Leetcode- | a14fe1188da008a39d7aaf4e142ee582493b7c60 | [
"MIT"
] | null | null | null | //贼暴力的方法。。。
class Solution {
public:
void dfs(int i, int len, vector<int> &nums, int target, int sum, vector<int> x)
{
if(i == len)
{
if(sum == target) ans.push_back(x);
return ;
}
if(sum > target) return ;
dfs(i+1, len, nums, target, sum, x);
for(int j = 1; ; j++)
{
if(target < sum+nums[i]*j) break;
x.push_back(nums[i]);
dfs(i+1, len, nums, target, sum+nums[i]*j, x);
}
}
vector<vector<int>> ans;
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<int> x;
dfs(0, candidates.size(), candidates, target, 0, x);
return ans;
}
}; | 28.076923 | 83 | 0.491781 | zzuliLL |
126993bcc7975bfe1e524e9c79d2922575931bf1 | 1,611 | cpp | C++ | solutions/0235.lowest-common-ancestor-of-a-binary-search-tree/0235.lowest-common-ancestor-of-a-binary-search-tree.1548160270.cpp | nettee/leetcode | 19aa8d54d64cce3679db5878ee0194fad95d8fa1 | [
"MIT"
] | 1 | 2021-01-14T06:01:02.000Z | 2021-01-14T06:01:02.000Z | solutions/0235.lowest-common-ancestor-of-a-binary-search-tree/0235.lowest-common-ancestor-of-a-binary-search-tree.1548160270.cpp | nettee/leetcode | 19aa8d54d64cce3679db5878ee0194fad95d8fa1 | [
"MIT"
] | 8 | 2018-03-27T11:47:19.000Z | 2018-11-12T06:02:12.000Z | solutions/0235.lowest-common-ancestor-of-a-binary-search-tree/0235.lowest-common-ancestor-of-a-binary-search-tree.1548160270.cpp | nettee/leetcode | 19aa8d54d64cce3679db5878ee0194fad95d8fa1 | [
"MIT"
] | 2 | 2020-04-30T09:47:01.000Z | 2020-12-03T09:34:08.000Z | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
string pcode = encode(root, p->val);
string qcode = encode(root, q->val);
int i = 0;
while (i < pcode.length() && i < qcode.length() && pcode[i] == qcode[i]) {
i++;
}
string compre(pcode, 0, i);
return locate(root, compre);
}
string encode(TreeNode* root, int val) {
string res;
bool found = false;
encode(root, val, "", found, res);
return res;
}
void encode(TreeNode* root, int val, string s, bool& found, string& res) {
if (found) {
return;
}
if (root == NULL) {
return;
}
if (root->val == val) {
found = true;
res = s;
return;
}
encode(root->left, val, s + '0', found, res);
encode(root->right, val, s + '1', found, res);
}
TreeNode* locate(TreeNode* root, const string& compre) {
return locate(root, compre, 0);
}
TreeNode* locate(TreeNode* root, const string& compre, int i) {
if (i >= compre.length()) {
return root;
}
if (compre[i] == '0') {
return locate(root->left, compre, i+1);
} else {
return locate(root->right, compre, i+1);
}
}
};
| 26.409836 | 82 | 0.484792 | nettee |
126c8e14a3e27d39cbe76858a838839225f270cf | 932 | cpp | C++ | 014-longest-common-prefix/longest-common-prefix.cpp | nagestx/MyLeetCode | ef2a98b48485a0cebc442bbbbdb2690ba51484e1 | [
"MIT"
] | 3 | 2018-12-15T14:07:12.000Z | 2020-07-19T23:18:09.000Z | 014-longest-common-prefix/longest-common-prefix.cpp | yangyangu/MyLeetCode | ef2a98b48485a0cebc442bbbbdb2690ba51484e1 | [
"MIT"
] | null | null | null | 014-longest-common-prefix/longest-common-prefix.cpp | yangyangu/MyLeetCode | ef2a98b48485a0cebc442bbbbdb2690ba51484e1 | [
"MIT"
] | null | null | null | // Write a function to find the longest common prefix string amongst an array of strings.
//
// If there is no common prefix, return an empty string "".
//
// Example 1:
//
//
// Input: ["flower","flow","flight"]
// Output: "fl"
//
//
// Example 2:
//
//
// Input: ["dog","racecar","car"]
// Output: ""
// Explanation: There is no common prefix among the input strings.
//
//
// Note:
//
// All given inputs are in lowercase letters a-z.
//
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()) return "";
int i = 0;
vector<string>::iterator it = strs.begin();
string s = *it;
for(++ it;it != strs.end(); ++it){
string r;
string t = *it;
for(i = 0; i <= t.length()-1; ++i){
if(s[i] == t[i]){
r += t[i];
}
else break;
}
s = r;
}
return s;
}
};
| 19.416667 | 90 | 0.505365 | nagestx |
126d34696df58ab55554b25a077a1149dc5460fa | 1,533 | cpp | C++ | 3_memory_mgmt/2_memory_allocation/00_memory_allocation_sample.cpp | aalfianrachmat/CppND-practice | 6c35141c106b9fa867392a846b35c482ded74e62 | [
"MIT"
] | 27 | 2019-10-08T13:43:32.000Z | 2021-08-30T08:00:28.000Z | 3_memory_mgmt/2_memory_allocation/00_memory_allocation_sample.cpp | aalfianrachmat/CppND-practice | 6c35141c106b9fa867392a846b35c482ded74e62 | [
"MIT"
] | 1 | 2020-10-11T23:20:15.000Z | 2020-10-11T23:20:15.000Z | 3_memory_mgmt/2_memory_allocation/00_memory_allocation_sample.cpp | aalfianrachmat/CppND-practice | 6c35141c106b9fa867392a846b35c482ded74e62 | [
"MIT"
] | 14 | 2019-09-22T15:17:59.000Z | 2021-07-13T06:06:37.000Z | #include <iostream>
// Illustration of memory allocation and deallocation
int main() {
int *ptr = nullptr;
/*
When using new, best practice in coding states that we need to enclose it within a try-catch block.
The new operator throws an exception and does not return a value.
To force the new operator to return a value, you canuse the nothrow qualifier as shown below:
*/
ptr = new(std::nothrow) int;
if (!ptr) {
std::cout << "Mem alloc failed!" << std::endl;
}
else {
// assigning value to newly allocated address
*ptr = 31;
// checking our pointer state:
std::cout<<" Address is: " << ptr << std::endl;
std::cout<<" Value is: " << *ptr << std::endl;
}
// We are creating pointer to array of integers
int *arr_ptr = new(std::nothrow) int[3];
// We are storing new values to created array
// 0 1 4
for (int i=0; i<3; i++)
arr_ptr[i] = (i*i);
// Writing our arr_ptr pointer info:
for (int i=0; i<3; i++) {
// notice notation for retrieval of memory address
// in array pointers ( we are using references)
std::cout<<" Address is: " << &arr_ptr[i] << std::endl;
std::cout<<" Value is: " << arr_ptr[i] << std::endl;
}
// Before our program is finished, we have responsibility
// to deallocate all of our allocated memory:
// integer pointer
delete ptr;
// array of integers pointer - block of memory
delete[] arr_ptr;
return 0;
} | 31.285714 | 104 | 0.596869 | aalfianrachmat |
126dbc43678dff5ce61030116c2270eea714b390 | 435 | cpp | C++ | source/procedural_graph/construction_argument_not_found.cpp | diegoarjz/selector | 976abd0d9e721639e6314e2599ef7e6f3dafdc4f | [
"MIT"
] | 12 | 2019-04-16T17:35:53.000Z | 2020-04-12T14:37:27.000Z | source/procedural_graph/construction_argument_not_found.cpp | diegoarjz/selector | 976abd0d9e721639e6314e2599ef7e6f3dafdc4f | [
"MIT"
] | 47 | 2019-05-27T15:24:43.000Z | 2020-04-27T17:54:54.000Z | source/procedural_graph/construction_argument_not_found.cpp | diegoarjz/selector | 976abd0d9e721639e6314e2599ef7e6f3dafdc4f | [
"MIT"
] | null | null | null | #include "construction_argument_not_found.h"
namespace pagoda
{
ConstructionArgumentNotFound::ConstructionArgumentNotFound(const std::string nodeName, const uint32_t nodeId,
const std::string &argName)
: Exception("Construction argument " + argName + " not found for node " + nodeName +
" (id: " + std::to_string(nodeId) + ")")
{
}
} // namespace pagoda
| 36.25 | 109 | 0.611494 | diegoarjz |
126de05c2b77973686ff8e06811645eb52836171 | 3,400 | hpp | C++ | MemoryPool.hpp | phisko/putils | 741e143cef837ae78526656dd7c926283ccbebc9 | [
"MIT"
] | 26 | 2018-11-12T03:29:13.000Z | 2021-11-30T22:43:44.000Z | MemoryPool.hpp | phisko/putils | 741e143cef837ae78526656dd7c926283ccbebc9 | [
"MIT"
] | null | null | null | MemoryPool.hpp | phisko/putils | 741e143cef837ae78526656dd7c926283ccbebc9 | [
"MIT"
] | 9 | 2018-12-28T08:37:06.000Z | 2020-04-27T08:17:17.000Z | /*-
* Copyright (c) 2013 Cosku Acay, http://www.coskuacay.com
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#pragma once
#include <climits>
#include <cstddef>
namespace putils {
template <typename T, size_t BlockSize = 4096>
class MemoryPool
{
public:
/* Member types */
typedef T value_type;
typedef T * pointer;
typedef T & reference;
typedef const T * const_pointer;
typedef const T & const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef std::false_type propagate_on_container_copy_assignment;
typedef std::true_type propagate_on_container_move_assignment;
typedef std::true_type propagate_on_container_swap;
template <typename U> struct rebind {
typedef MemoryPool<U, BlockSize> other;
};
/* Member functions */
MemoryPool() noexcept = default;
~MemoryPool() noexcept = default;
MemoryPool(const MemoryPool & memoryPool) noexcept = default;
MemoryPool & operator=(const MemoryPool & memoryPool) = default;
MemoryPool(MemoryPool && memoryPool) noexcept = default;
MemoryPool & operator=(MemoryPool && memoryPool) noexcept = default;
template <class U, size_t B>
MemoryPool(const MemoryPool<U, B> & memoryPool) noexcept {}
// Can only allocate one object at a time. n and hint are ignored
pointer allocate(size_type n = 1, const_pointer hint = 0);
void deallocate(pointer p, size_type n = 1);
size_type max_size() const noexcept;
private:
union Slot_ {
value_type element;
Slot_ * next;
~Slot_() noexcept = delete;
};
typedef char * data_pointer_;
typedef Slot_ slot_type_;
typedef Slot_ * slot_pointer_;
static inline slot_pointer_ currentBlock_ = nullptr;
static inline slot_pointer_ currentSlot_ = nullptr;
static inline slot_pointer_ lastSlot_ = nullptr;
static inline slot_pointer_ freeSlots_ = nullptr;
size_type padPointer(data_pointer_ p, size_type align) const noexcept;
void allocateBlock();
static_assert(BlockSize >= 2 * sizeof(slot_type_), "BlockSize too small.");
};
}
#include "MemoryPool.inl" | 37.362637 | 83 | 0.679706 | phisko |
126f6e5859cc8566b3f9baf5dd1b926c7a6f9c52 | 227 | cpp | C++ | jp.atcoder/abc081/arc086_a/11919937.cpp | kagemeka/atcoder-submissions | 91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e | [
"MIT"
] | 1 | 2022-02-09T03:06:25.000Z | 2022-02-09T03:06:25.000Z | jp.atcoder/abc081/arc086_a/11919937.cpp | kagemeka/atcoder-submissions | 91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e | [
"MIT"
] | 1 | 2022-02-05T22:53:18.000Z | 2022-02-09T01:29:30.000Z | jp.atcoder/abc081/arc086_a/11919937.cpp | kagemeka/atcoder-submissions | 91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e | [
"MIT"
] | null | null | null | import sys
from collections import Counter
n, k, *a = map(int, sys.stdin.read().split())
def main():
c = Counter(a)
res = sum(sorted(c.values())[:-k])
print(res)
if __name__ == '__main__':
main()
| 17.461538 | 46 | 0.568282 | kagemeka |
127088cace5ea2c2be7342aed6d03cdf34ab96df | 795 | cpp | C++ | C++/restore-the-array-from-adjacent-pairs.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/restore-the-array-from-adjacent-pairs.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/restore-the-array-from-adjacent-pairs.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // Time: O(n)
// Space: O(n)
class Solution {
public:
vector<int> restoreArray(vector<vector<int>>& adjacentPairs) {
unordered_map<int, vector<int>> adj;
for (const auto& pair : adjacentPairs) {
adj[pair[0]].emplace_back(pair[1]);
adj[pair[1]].emplace_back(pair[0]);
}
vector<int> result;
for (const auto& [first, neighbors] : adj) {
if (size(neighbors) == 1) {
result.emplace_back(first);
result.emplace_back(neighbors.front());
break;
}
}
while (size(result) != size(adjacentPairs) + 1) {
result.emplace_back(adj[result.back()][adj[result.back()][0] == result[size(result) - 2]]);
}
return result;
}
};
| 30.576923 | 103 | 0.522013 | Priyansh2 |
1271c06c840187db45b414a2eae9ec8c5f004f49 | 549 | cpp | C++ | KROSS/src/Kross/Core/Stack.cpp | WillianKoessler/KROSS-ENGINE | 0e680b455ffd071565fe8b99343805ad16ca1e91 | [
"Apache-2.0"
] | null | null | null | KROSS/src/Kross/Core/Stack.cpp | WillianKoessler/KROSS-ENGINE | 0e680b455ffd071565fe8b99343805ad16ca1e91 | [
"Apache-2.0"
] | null | null | null | KROSS/src/Kross/Core/Stack.cpp | WillianKoessler/KROSS-ENGINE | 0e680b455ffd071565fe8b99343805ad16ca1e91 | [
"Apache-2.0"
] | null | null | null | #include <Kross_pch.h>
#include "Stack.h"
#include "Kross/Core/Stack.h"
#include "Kross/Renderer/Shaders.h"
#include "Kross/Renderer/Textures/Textures.h"
//#include "Kross/Core/Layer.h"
#include "Kross/Renderer/Mesh/Mesh.h"
#define __impl__STACK_TEMPLATE(x)\
std::vector<Stack<##x>::Entry> Stack<##x>::stack;\
std::string Stack<##x>::Entry::table = "";\
template class Stack<##x>;
namespace Kross {
__impl__STACK_TEMPLATE(Shader);
__impl__STACK_TEMPLATE(Texture::T2D);
//__impl__STACK_TEMPLATE(Layer);
//__impl__STACK_TEMPLATE(Mesh::Base);
} | 26.142857 | 50 | 0.734062 | WillianKoessler |
1273e8d5307b315c1e4bb39dd3f6dfa82a2c370c | 175 | hpp | C++ | tests/unit/include/helpers.hpp | karel-burda/function-dll-extractor | ca54cc86da1e2cc0106623e12ba20e608c33f37b | [
"MIT"
] | 8 | 2019-10-10T16:05:12.000Z | 2022-01-27T21:49:45.000Z | tests/unit/include/helpers.hpp | karel-burda/function-dll-extractor | ca54cc86da1e2cc0106623e12ba20e608c33f37b | [
"MIT"
] | 7 | 2018-10-01T04:08:36.000Z | 2021-08-24T12:52:07.000Z | tests/unit/include/helpers.hpp | karel-burda/function-dll-extractor | ca54cc86da1e2cc0106623e12ba20e608c33f37b | [
"MIT"
] | 4 | 2018-09-27T06:41:31.000Z | 2022-01-27T21:49:50.000Z | #pragma once
namespace burda
{
namespace function_loader
{
namespace testing
{
constexpr const char * get_demo_library_file_path()
{
return "./demo-library.dll";
}
}
}
}
| 10.9375 | 51 | 0.731429 | karel-burda |
12740264134124e3b12501aab6174f4cf1d75dd6 | 9,975 | cpp | C++ | Engine/Source/GameBase/src/HumanView.cpp | AnkurSheel/RoutePlanner | a50b6ccb735db42ff4e5b2f4c87e710819c4564b | [
"CC-BY-4.0"
] | null | null | null | Engine/Source/GameBase/src/HumanView.cpp | AnkurSheel/RoutePlanner | a50b6ccb735db42ff4e5b2f4c87e710819c4564b | [
"CC-BY-4.0"
] | null | null | null | Engine/Source/GameBase/src/HumanView.cpp | AnkurSheel/RoutePlanner | a50b6ccb735db42ff4e5b2f4c87e710819c4564b | [
"CC-BY-4.0"
] | null | null | null | #include "stdafx.h"
#include "HumanView.h"
#include "GraphicsClass.hxx"
#include "BaseApp.hxx"
#include "BaseControl.hxx"
#include "MainWindow.hxx"
#include "Camera.hxx"
#include "ParamLoaders.hxx"
#include "Audio.hxx"
#include "SoundProcess.hxx"
#include "GameOptions.h"
#include "GameDirectories.h"
#include "ProcessManager.hxx"
#include "KeyboardController.hxx"
using namespace Utilities;
using namespace Graphics;
using namespace Base;
using namespace GameBase;
using namespace Sound;
// *******************************************************************************************************************
cHumanView::cHumanView()
: m_bRunFullSpeed(true)
, m_pAppWindowControl(NULL)
, m_pCamera(NULL)
, m_bDisplayFPS(false)
, m_hashSFXChannel("SFXChannelProcess")
, m_hashMusicChannel("MusicChannelProcess")
{
}
// *******************************************************************************************************************
cHumanView::~cHumanView()
{
VOnDestroyDevice();
}
// *******************************************************************************************************************
void cHumanView::VOnCreateDevice(IBaseApp* pBaseApp)
{
m_pGame = pBaseApp;
if(m_pGame->VGetParamLoader() != NULL)
{
m_bDisplayFPS = m_pGame->VGetParamLoader()->VGetParameterValueAsBool("-DisplayFPS", false);
}
cWindowControlDef def;
def.wType = cWindowControlDef::WT_DESKTOP;
def.strControlName = "App";
def.vSize = cVector2(static_cast<float>(cGameOptions::GameOptions().iWidth), static_cast<float>(cGameOptions::GameOptions().iHeight));
if(m_pGame->VGetParamLoader() != NULL)
{
def.bAllowMovingControls = m_pGame->VGetParamLoader()->VGetParameterValueAsBool("-AllowMovingControls", false);
}
m_pAppWindowControl = IBaseControl::CreateWindowControl(def);
m_pCamera = ICamera::CreateCamera();
// m_pCursorSprite = ISprite::CreateSprite();
// m_pCursorSprite->Init(IDXBase::GetInstance()->VGetDevice(),
// "cursor.png");
// m_pCursorSprite->SetSize((float)iClientWidth/30, (float)iClientHeight/30);
// m_pCursorSprite->SetFlags(D3DXSPRITE_ALPHABLEND);
cLabelControlDef fpsLabelDef;
fpsLabelDef.strControlName = "FPSLabel";
fpsLabelDef.strFont= "arial";
fpsLabelDef.textColor = cColor::WHITE;
fpsLabelDef.fTextHeight = 30;
fpsLabelDef.vPosition = cVector2(static_cast<float>(cGameOptions::GameOptions().iWidth/2- 75), 0.0f);
fpsLabelDef.bAutoSize = false;
fpsLabelDef.vSize = cVector2(150, 30);
CreateFPSLabel(fpsLabelDef);
}
// *******************************************************************************************************************
void cHumanView::VOnUpdate(const TICK tickCurrent, const float fElapsedTime)
{
if (m_pCamera)
{
m_pCamera->VUpdate();
}
}
// *******************************************************************************************************************
void cHumanView::VOnRender(const TICK tickCurrent, const float fElapsedTime)
{
HRESULT hr;
hr = OnBeginRender(tickCurrent);
if(SUCCEEDED(hr))
{
VRenderPrivate();
OnEndRender(hr);
}
}
// *******************************************************************************************************************
void cHumanView::VOnDestroyDevice()
{
SafeDelete(&m_pAppWindowControl);
SafeDelete(&m_pCamera);
IAudio::Destroy();
IKeyboardController::Destroy();
}
// *******************************************************************************************************************
bool cHumanView::VOnMsgProc( const Base::AppMsg & msg )
{
bool bHandled = false;
switch(msg.m_uMsg)
{
case WM_CHAR:
if (m_pAppWindowControl)
{
bHandled = m_pAppWindowControl->VPostMsg(msg);
}
//if(!bHandled)
//{
// switch (msg.m_wParam)
// {
// case VK_SPACE:
// IMainWindow::GetInstance()->VToggleFullScreen();
// Log_Write_L3(ILogger::LT_DEBUG, "Toggled FullScreen");
// }
//}
break;
case WM_MOUSEMOVE:
case WM_LBUTTONUP:
case WM_LBUTTONDOWN:
case WM_KEYUP:
case WM_KEYDOWN:
if (m_pAppWindowControl)
{
bHandled = m_pAppWindowControl->VPostMsg(msg);
}
if (msg.m_wParam == VK_F2 && !IKeyboardController::Instance()->VIsKeyLocked(VK_F2) )
{
// lock the F2 key
IKeyboardController::Instance()->VLockKey(VK_F2);
m_bDisplayFPS = !m_bDisplayFPS;
if(m_pFpsLabel)
{
m_pFpsLabel->VSetVisible(m_bDisplayFPS);
}
}
break;
}
return bHandled;
}
// *******************************************************************************************************************
IGameView::GAMEVIEWTYPE cHumanView::VGetType()
{
return GV_HUMAN;
}
// *******************************************************************************************************************
GameViewId cHumanView::VGetId() const
{
return -1;
}
// *******************************************************************************************************************
void cHumanView::VOnAttach(GameViewId id)
{
m_idView = id;
}
const ICamera * const cHumanView::GetCamera() const
{
return m_pCamera;
}
// *******************************************************************************************************************
HRESULT cHumanView::OnBeginRender(TICK tickCurrent)
{
m_tickCurrent = tickCurrent;
HRESULT hr = S_OK;
IGraphicsClass::GetInstance()->VBeginRender();
return hr;
}
// *******************************************************************************************************************
void cHumanView::VRenderPrivate()
{
if (m_pAppWindowControl)
{
m_pAppWindowControl->VRender(m_pCamera);
}
// if (m_pCursorSprite->IsVisible())
// {
// m_pCursorSprite->SetPosition(D3DXVECTOR3((float)m_pInput->GetX(), (float)m_pInput->GetY(), 0.0f));
// m_pCursorSprite->OnRender(IDXBase::GetInstance()->VGetDevice());
// }
if (m_bDisplayFPS && m_pFpsLabel && m_pGame)
{
m_pFpsLabel->VSetText(cStringUtilities::MakeFormatted("%0.2f", m_pGame->VGetFPS()));
}
}
// *******************************************************************************************************************
void cHumanView::OnEndRender(const HRESULT hr)
{
m_tickLastDraw = m_tickCurrent;
IGraphicsClass::GetInstance()->VEndRender();
}
// *******************************************************************************************************************
void cHumanView::SetCursorVisible( bool bVisible )
{
// if (m_pCursorSprite)
// {
// m_pCursorSprite->SetVisible(bVisible);
// }
}
// *******************************************************************************************************************
void cHumanView::PlaySFX(const cString & strSoundFile)
{
if(cGameOptions::GameOptions().bPlaySfx)
{
shared_ptr<ISoundProcess> pSFXChannelProcess(ISoundProcess::CreateSoundProcess(m_hashSFXChannel.GetString(),
cGameDirectories::GetSoundSFXDirectory() + strSoundFile, cGameOptions::GameOptions().iSFXVolume, false));
m_pGame->VGetProcessManager()->VAttachProcess(pSFXChannelProcess);
}
}
// *******************************************************************************************************************
void cHumanView::PlayMusic(const cString & strMusicFile, const bool bLooping)
{
shared_ptr<ISoundProcess> pMusicChannelProcess = ISoundProcess::CreateSoundProcess(m_hashMusicChannel.GetString(),
cGameDirectories::GetSoundMusicDirectory() + strMusicFile, cGameOptions::GameOptions().iMusicVolume, bLooping);
m_pGame->VGetProcessManager()->VAttachProcess(pMusicChannelProcess);
m_pGame->VGetProcessManager()->VSetProcessesActive(m_hashMusicChannel, cGameOptions::GameOptions().bPlayMusic);
}
// *******************************************************************************************************************
void cHumanView::SetMusicVolume()
{
ProcessList pProcessList;
m_pGame->VGetProcessManager()->VGetProcesses(m_hashMusicChannel, pProcessList);
for (auto curProcess = pProcessList.begin(); curProcess != pProcessList.end(); curProcess++)
{
shared_ptr<ISoundProcess> p = dynamic_pointer_cast<ISoundProcess>(*curProcess);
p->VSetVolume(cGameOptions::GameOptions().iMusicVolume);
}
}
// *******************************************************************************************************************
void cHumanView::SetSFXVolume()
{
ProcessList pProcessList;
m_pGame->VGetProcessManager()->VGetProcesses(m_hashSFXChannel, pProcessList);
for (auto curProcess = pProcessList.begin(); curProcess != pProcessList.end(); curProcess++)
{
shared_ptr<ISoundProcess> p = dynamic_pointer_cast<ISoundProcess>(*curProcess);
p->VSetVolume(cGameOptions::GameOptions().iSFXVolume);
}
}
// *******************************************************************************************************************
void cHumanView::MusicCheckBoxPressed(const stUIEventCallbackParam & params)
{
cGameOptions::GameOptions().bPlayMusic = params.bChecked;
m_pGame->VGetProcessManager()->VSetProcessesActive(m_hashMusicChannel, cGameOptions::GameOptions().bPlayMusic);
}
// *******************************************************************************************************************
void cHumanView::SfxCheckBoxPressed(const stUIEventCallbackParam & params)
{
cGameOptions::GameOptions().bPlaySfx = params.bChecked;
m_pGame->VGetProcessManager()->VSetProcessesActive(m_hashSFXChannel, cGameOptions::GameOptions().bPlaySfx);
}
// *******************************************************************************************************************
void cHumanView::FullScreenCheckBoxPressed(const stUIEventCallbackParam & params)
{
cGameOptions::GameOptions().bFullScreen = !(cGameOptions::GameOptions().bFullScreen);
IGraphicsClass::GetInstance()->VSetFullScreenMode(cGameOptions::GameOptions().bFullScreen);
}
// *******************************************************************************************************************
void cHumanView::CreateFPSLabel(const cLabelControlDef & def)
{
m_pFpsLabel = shared_ptr<IBaseControl>(IBaseControl::CreateLabelControl(def));
m_pAppWindowControl->VAddChildControl(m_pFpsLabel);
}
| 34.635417 | 135 | 0.55589 | AnkurSheel |
1283630f292e33228ca3a9cfd861250d91797834 | 326 | hpp | C++ | include/meejson/parser.hpp | tomvanwoow/meejson | a478b646306f0323c53e2ad1ce33a1e4ee6d1451 | [
"MIT"
] | null | null | null | include/meejson/parser.hpp | tomvanwoow/meejson | a478b646306f0323c53e2ad1ce33a1e4ee6d1451 | [
"MIT"
] | null | null | null | include/meejson/parser.hpp | tomvanwoow/meejson | a478b646306f0323c53e2ad1ce33a1e4ee6d1451 | [
"MIT"
] | null | null | null | #ifndef JSON_PARSER_HPP
#define JSON_PARSER_HPP
#include <string_view>
#include "value.hpp"
#include "lexer.hpp"
namespace mee::json {
auto parse(std::string_view) noexcept -> result<value>;
auto parse(const std::vector<token>&) noexcept -> result<value>;
auto operator""_json(const char*, std::size_t) -> value;
}
#endif
| 20.375 | 64 | 0.736196 | tomvanwoow |
128b8c6d349a1822558ff413e0c3b217a1101276 | 24,520 | cpp | C++ | Tutorial1/src/main.cpp | RichardRanft/LearningDirectX12 | fce26d5fcec1bfd3e06c433fc596a7f030cff929 | [
"MIT"
] | null | null | null | Tutorial1/src/main.cpp | RichardRanft/LearningDirectX12 | fce26d5fcec1bfd3e06c433fc596a7f030cff929 | [
"MIT"
] | null | null | null | Tutorial1/src/main.cpp | RichardRanft/LearningDirectX12 | fce26d5fcec1bfd3e06c433fc596a7f030cff929 | [
"MIT"
] | null | null | null | #define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <shellapi.h> // For CommandLineToArgvW
#include "../resource.h"
// The min/max macros conflict with like-named member functions.
// Only use std::min and std::max defined in <algorithm>.
#if defined(min)
#undef min
#endif
#if defined(max)
#undef max
#endif
// In order to define a function called CreateWindow, the Windows macro needs to
// be undefined.
#if defined(CreateWindow)
#undef CreateWindow
#endif
// Windows Runtime Library. Needed for Microsoft::WRL::ComPtr<> template class.
#include <wrl.h>
using namespace Microsoft::WRL;
// DirectX 12 specific headers.
#include <d3d12.h>
#include <dxgi1_6.h>
#include <d3dcompiler.h>
#include <DirectXMath.h>
// D3D12 extension library.
#include <d3dx12.h>
// STL Headers
#include <algorithm>
#include <cassert>
#include <chrono>
// Helper functions
#include <Helpers.h>
// The number of swap chain back buffers.
const uint8_t g_NumFrames = 3;
// Use WARP adapter
bool g_UseWarp = false;
uint32_t g_ClientWidth = 1280;
uint32_t g_ClientHeight = 720;
// Set to true once the DX12 objects have been initialized.
bool g_IsInitialized = false;
// Window handle.
HWND g_hWnd;
// Window rectangle (used to toggle fullscreen state).
RECT g_WindowRect;
// DirectX 12 Objects
ComPtr<ID3D12Device2> g_Device;
ComPtr<ID3D12CommandQueue> g_CommandQueue;
ComPtr<IDXGISwapChain4> g_SwapChain;
ComPtr<ID3D12Resource> g_BackBuffers[g_NumFrames];
ComPtr<ID3D12GraphicsCommandList> g_CommandList;
ComPtr<ID3D12CommandAllocator> g_CommandAllocators[g_NumFrames];
ComPtr<ID3D12DescriptorHeap> g_RTVDescriptorHeap;
UINT g_RTVDescriptorSize;
UINT g_CurrentBackBufferIndex;
// Synchronization objects
ComPtr<ID3D12Fence> g_Fence;
uint64_t g_FenceValue = 0;
uint64_t g_FrameFenceValues[g_NumFrames] = {};
HANDLE g_FenceEvent;
// By default, enable V-Sync.
// Can be toggled with the V key.
bool g_VSync = true;
bool g_TearingSupported = false;
// By default, use windowed mode.
// Can be toggled with the Alt+Enter or F11
bool g_Fullscreen = false;
// Window callback function.
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void ParseCommandLineArguments()
{
int argc;
wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
for (size_t i = 0; i < argc; ++i)
{
if (::wcscmp(argv[i], L"-w") == 0 || ::wcscmp(argv[i], L"--width") == 0)
{
g_ClientWidth = ::wcstol(argv[++i], nullptr, 10);
}
if (::wcscmp(argv[i], L"-h") == 0 || ::wcscmp(argv[i], L"--height") == 0)
{
g_ClientHeight = ::wcstol(argv[++i], nullptr, 10);
}
if (::wcscmp(argv[i], L"-warp") == 0 || ::wcscmp(argv[i], L"--warp") == 0)
{
g_UseWarp = true;
}
}
// Free memory allocated by CommandLineToArgvW
::LocalFree(argv);
}
void EnableDebugLayer()
{
#if defined(_DEBUG)
// Always enable the debug layer before doing anything DX12 related
// so all possible errors generated while creating DX12 objects
// are caught by the debug layer.
ComPtr<ID3D12Debug> debugInterface;
ThrowIfFailed(D3D12GetDebugInterface(IID_PPV_ARGS(&debugInterface)));
debugInterface->EnableDebugLayer();
#endif
}
void RegisterWindowClass( HINSTANCE hInst, const wchar_t* windowClassName )
{
// Register a window class for creating our render window with.
WNDCLASSEXW windowClass = {};
windowClass.cbSize = sizeof(WNDCLASSEXW);
windowClass.style = CS_HREDRAW | CS_VREDRAW;
windowClass.lpfnWndProc = &WndProc;
windowClass.cbClsExtra = 0;
windowClass.cbWndExtra = 0;
windowClass.hInstance = hInst;
windowClass.hIcon = ::LoadIcon(hInst, MAKEINTRESOURCE(APP_ICON)); // MAKEINTRESOURCE(APPLICATION_ICON));
windowClass.hCursor = ::LoadCursor(NULL, IDC_ARROW);
windowClass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
windowClass.lpszMenuName = NULL;
windowClass.lpszClassName = windowClassName;
windowClass.hIconSm = ::LoadIcon(hInst, MAKEINTRESOURCE(APP_ICON)); // MAKEINTRESOURCE(APPLICATION_ICON));
static ATOM atom = ::RegisterClassExW(&windowClass);
assert(atom > 0);
}
HWND CreateWindow(const wchar_t* windowClassName, HINSTANCE hInst,
const wchar_t* windowTitle, uint32_t width, uint32_t height)
{
int screenWidth = ::GetSystemMetrics(SM_CXSCREEN);
int screenHeight = ::GetSystemMetrics(SM_CYSCREEN);
RECT windowRect = { 0, 0, static_cast<LONG>(width), static_cast<LONG>(height) };
::AdjustWindowRect(&windowRect, WS_OVERLAPPEDWINDOW, FALSE);
int windowWidth = windowRect.right - windowRect.left;
int windowHeight = windowRect.bottom - windowRect.top;
// Center the window within the screen. Clamp to 0, 0 for the top-left corner.
int windowX = std::max<int>(0, (screenWidth - windowWidth) / 2);
int windowY = std::max<int>(0, (screenHeight - windowHeight) / 2);
HWND hWnd = ::CreateWindowExW(
NULL,
windowClassName,
windowTitle,
WS_OVERLAPPEDWINDOW,
windowX,
windowY,
windowWidth,
windowHeight,
NULL,
NULL,
hInst,
nullptr
);
assert(hWnd && "Failed to create window");
return hWnd;
}
ComPtr<IDXGIAdapter4> GetAdapter(bool useWarp)
{
ComPtr<IDXGIFactory4> dxgiFactory;
UINT createFactoryFlags = 0;
#if defined(_DEBUG)
createFactoryFlags = DXGI_CREATE_FACTORY_DEBUG;
#endif
ThrowIfFailed(CreateDXGIFactory2(createFactoryFlags, IID_PPV_ARGS(&dxgiFactory)));
ComPtr<IDXGIAdapter1> dxgiAdapter1;
ComPtr<IDXGIAdapter4> dxgiAdapter4;
if (useWarp)
{
ThrowIfFailed(dxgiFactory->EnumWarpAdapter(IID_PPV_ARGS(&dxgiAdapter1)));
ThrowIfFailed(dxgiAdapter1.As(&dxgiAdapter4));
}
else
{
SIZE_T maxDedicatedVideoMemory = 0;
for (UINT i = 0; dxgiFactory->EnumAdapters1(i, &dxgiAdapter1) != DXGI_ERROR_NOT_FOUND; ++i)
{
DXGI_ADAPTER_DESC1 dxgiAdapterDesc1;
dxgiAdapter1->GetDesc1(&dxgiAdapterDesc1);
// Check to see if the adapter can create a D3D12 device without actually
// creating it. The adapter with the largest dedicated video memory
// is favored.
if ((dxgiAdapterDesc1.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) == 0 &&
SUCCEEDED(D3D12CreateDevice(dxgiAdapter1.Get(),
D3D_FEATURE_LEVEL_11_0, __uuidof(ID3D12Device), nullptr)) &&
dxgiAdapterDesc1.DedicatedVideoMemory > maxDedicatedVideoMemory )
{
maxDedicatedVideoMemory = dxgiAdapterDesc1.DedicatedVideoMemory;
ThrowIfFailed(dxgiAdapter1.As(&dxgiAdapter4));
}
}
}
return dxgiAdapter4;
}
ComPtr<ID3D12Device2> CreateDevice(ComPtr<IDXGIAdapter4> adapter)
{
ComPtr<ID3D12Device2> d3d12Device2;
ThrowIfFailed(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&d3d12Device2)));
// Enable debug messages in debug mode.
#if defined(_DEBUG)
ComPtr<ID3D12InfoQueue> pInfoQueue;
if (SUCCEEDED(d3d12Device2.As(&pInfoQueue)))
{
pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, TRUE);
pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, TRUE);
pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, TRUE);
// Suppress whole categories of messages
//D3D12_MESSAGE_CATEGORY Categories[] = {};
// Suppress messages based on their severity level
D3D12_MESSAGE_SEVERITY Severities[] =
{
D3D12_MESSAGE_SEVERITY_INFO
};
// Suppress individual messages by their ID
D3D12_MESSAGE_ID DenyIds[] = {
D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE, // I'm really not sure how to avoid this message.
D3D12_MESSAGE_ID_MAP_INVALID_NULLRANGE, // This warning occurs when using capture frame while graphics debugging.
D3D12_MESSAGE_ID_UNMAP_INVALID_NULLRANGE, // This warning occurs when using capture frame while graphics debugging.
};
D3D12_INFO_QUEUE_FILTER NewFilter = {};
//NewFilter.DenyList.NumCategories = _countof(Categories);
//NewFilter.DenyList.pCategoryList = Categories;
NewFilter.DenyList.NumSeverities = _countof(Severities);
NewFilter.DenyList.pSeverityList = Severities;
NewFilter.DenyList.NumIDs = _countof(DenyIds);
NewFilter.DenyList.pIDList = DenyIds;
ThrowIfFailed(pInfoQueue->PushStorageFilter(&NewFilter));
}
#endif
return d3d12Device2;
}
ComPtr<ID3D12CommandQueue> CreateCommandQueue(ComPtr<ID3D12Device2> device, D3D12_COMMAND_LIST_TYPE type )
{
ComPtr<ID3D12CommandQueue> d3d12CommandQueue;
D3D12_COMMAND_QUEUE_DESC desc = {};
desc.Type = type;
desc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
desc.NodeMask = 0;
ThrowIfFailed(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&d3d12CommandQueue)));
return d3d12CommandQueue;
}
bool CheckTearingSupport()
{
BOOL allowTearing = FALSE;
// Rather than create the DXGI 1.5 factory interface directly, we create the
// DXGI 1.4 interface and query for the 1.5 interface. This is to enable the
// graphics debugging tools which will not support the 1.5 factory interface
// until a future update.
ComPtr<IDXGIFactory4> factory4;
if (SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory4))))
{
ComPtr<IDXGIFactory5> factory5;
if (SUCCEEDED(factory4.As(&factory5)))
{
if (FAILED(factory5->CheckFeatureSupport(
DXGI_FEATURE_PRESENT_ALLOW_TEARING,
&allowTearing, sizeof(allowTearing))))
{
allowTearing = FALSE;
}
}
}
return allowTearing == TRUE;
}
ComPtr<IDXGISwapChain4> CreateSwapChain(HWND hWnd,
ComPtr<ID3D12CommandQueue> commandQueue,
uint32_t width, uint32_t height, uint32_t bufferCount )
{
ComPtr<IDXGISwapChain4> dxgiSwapChain4;
ComPtr<IDXGIFactory4> dxgiFactory4;
UINT createFactoryFlags = 0;
#if defined(_DEBUG)
createFactoryFlags = DXGI_CREATE_FACTORY_DEBUG;
#endif
ThrowIfFailed(CreateDXGIFactory2(createFactoryFlags, IID_PPV_ARGS(&dxgiFactory4)));
DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {};
swapChainDesc.Width = width;
swapChainDesc.Height = height;
swapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDesc.Stereo = FALSE;
swapChainDesc.SampleDesc = { 1, 0 };
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferCount = bufferCount;
swapChainDesc.Scaling = DXGI_SCALING_STRETCH;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
// It is recommended to always allow tearing if tearing support is available.
swapChainDesc.Flags = CheckTearingSupport() ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0;
ComPtr<IDXGISwapChain1> swapChain1;
ThrowIfFailed(dxgiFactory4->CreateSwapChainForHwnd(
commandQueue.Get(),
hWnd,
&swapChainDesc,
nullptr,
nullptr,
&swapChain1));
// Disable the Alt+Enter fullscreen toggle feature. Switching to fullscreen
// will be handled manually.
ThrowIfFailed(dxgiFactory4->MakeWindowAssociation(hWnd, DXGI_MWA_NO_ALT_ENTER));
ThrowIfFailed(swapChain1.As(&dxgiSwapChain4));
return dxgiSwapChain4;
}
ComPtr<ID3D12DescriptorHeap> CreateDescriptorHeap(ComPtr<ID3D12Device2> device,
D3D12_DESCRIPTOR_HEAP_TYPE type, uint32_t numDescriptors)
{
ComPtr<ID3D12DescriptorHeap> descriptorHeap;
D3D12_DESCRIPTOR_HEAP_DESC desc = {};
desc.NumDescriptors = numDescriptors;
desc.Type = type;
ThrowIfFailed(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&descriptorHeap)));
return descriptorHeap;
}
void UpdateRenderTargetViews(ComPtr<ID3D12Device2> device,
ComPtr<IDXGISwapChain4> swapChain, ComPtr<ID3D12DescriptorHeap> descriptorHeap)
{
auto rtvDescriptorSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(descriptorHeap->GetCPUDescriptorHandleForHeapStart());
for (int i = 0; i < g_NumFrames; ++i)
{
ComPtr<ID3D12Resource> backBuffer;
ThrowIfFailed(swapChain->GetBuffer(i, IID_PPV_ARGS(&backBuffer)));
device->CreateRenderTargetView(backBuffer.Get(), nullptr, rtvHandle);
g_BackBuffers[i] = backBuffer;
rtvHandle.Offset(rtvDescriptorSize);
}
}
ComPtr<ID3D12CommandAllocator> CreateCommandAllocator(ComPtr<ID3D12Device2> device,
D3D12_COMMAND_LIST_TYPE type)
{
ComPtr<ID3D12CommandAllocator> commandAllocator;
ThrowIfFailed(device->CreateCommandAllocator(type, IID_PPV_ARGS(&commandAllocator)));
return commandAllocator;
}
ComPtr<ID3D12GraphicsCommandList> CreateCommandList(ComPtr<ID3D12Device2> device,
ComPtr<ID3D12CommandAllocator> commandAllocator, D3D12_COMMAND_LIST_TYPE type)
{
ComPtr<ID3D12GraphicsCommandList> commandList;
ThrowIfFailed(device->CreateCommandList(0, type, commandAllocator.Get(), nullptr, IID_PPV_ARGS(&commandList)));
ThrowIfFailed(commandList->Close());
return commandList;
}
ComPtr<ID3D12Fence> CreateFence(ComPtr<ID3D12Device2> device)
{
ComPtr<ID3D12Fence> fence;
ThrowIfFailed(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)));
return fence;
}
HANDLE CreateEventHandle()
{
HANDLE fenceEvent;
fenceEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
assert(fenceEvent && "Failed to create fence event.");
return fenceEvent;
}
uint64_t Signal(ComPtr<ID3D12CommandQueue> commandQueue, ComPtr<ID3D12Fence> fence,
uint64_t& fenceValue)
{
uint64_t fenceValueForSignal = ++fenceValue;
ThrowIfFailed(commandQueue->Signal(fence.Get(), fenceValueForSignal));
return fenceValueForSignal;
}
void WaitForFenceValue(ComPtr<ID3D12Fence> fence, uint64_t fenceValue, HANDLE fenceEvent,
std::chrono::milliseconds duration = std::chrono::milliseconds::max() )
{
if (fence->GetCompletedValue() < fenceValue)
{
ThrowIfFailed(fence->SetEventOnCompletion(fenceValue, fenceEvent));
::WaitForSingleObject(fenceEvent, static_cast<DWORD>(duration.count()));
}
}
void Flush(ComPtr<ID3D12CommandQueue> commandQueue, ComPtr<ID3D12Fence> fence,
uint64_t& fenceValue, HANDLE fenceEvent )
{
uint64_t fenceValueForSignal = Signal(commandQueue, fence, fenceValue);
WaitForFenceValue(fence, fenceValueForSignal, fenceEvent);
}
void Update()
{
static uint64_t frameCounter = 0;
static double elapsedSeconds = 0.0;
static std::chrono::high_resolution_clock clock;
static auto t0 = clock.now();
frameCounter++;
auto t1 = clock.now();
auto deltaTime = t1 - t0;
t0 = t1;
elapsedSeconds += deltaTime.count() * 1e-9;
if (elapsedSeconds > 1.0)
{
char buffer[500];
auto fps = frameCounter / elapsedSeconds;
sprintf_s(buffer, 500, "FPS: %f\n", fps);
OutputDebugString(buffer);
frameCounter = 0;
elapsedSeconds = 0.0;
}
}
void Render()
{
auto commandAllocator = g_CommandAllocators[g_CurrentBackBufferIndex];
auto backBuffer = g_BackBuffers[g_CurrentBackBufferIndex];
commandAllocator->Reset();
g_CommandList->Reset(commandAllocator.Get(), nullptr);
// Clear the render target.
{
CD3DX12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(
backBuffer.Get(),
D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET);
g_CommandList->ResourceBarrier(1, &barrier);
FLOAT clearColor[] = { 0.4f, 0.6f, 0.9f, 1.0f };
CD3DX12_CPU_DESCRIPTOR_HANDLE rtv(g_RTVDescriptorHeap->GetCPUDescriptorHandleForHeapStart(),
g_CurrentBackBufferIndex, g_RTVDescriptorSize);
g_CommandList->ClearRenderTargetView(rtv, clearColor, 0, nullptr);
}
// Present
{
CD3DX12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(
backBuffer.Get(),
D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT);
g_CommandList->ResourceBarrier(1, &barrier);
ThrowIfFailed(g_CommandList->Close());
ID3D12CommandList* const commandLists[] = {
g_CommandList.Get()
};
g_CommandQueue->ExecuteCommandLists(_countof(commandLists), commandLists);
UINT syncInterval = g_VSync ? 1 : 0;
UINT presentFlags = g_TearingSupported && !g_VSync ? DXGI_PRESENT_ALLOW_TEARING : 0;
ThrowIfFailed(g_SwapChain->Present(syncInterval, presentFlags));
g_FrameFenceValues[g_CurrentBackBufferIndex] = Signal( g_CommandQueue, g_Fence, g_FenceValue );
g_CurrentBackBufferIndex = g_SwapChain->GetCurrentBackBufferIndex();
WaitForFenceValue(g_Fence, g_FrameFenceValues[g_CurrentBackBufferIndex], g_FenceEvent);
}
}
void Resize(uint32_t width, uint32_t height)
{
if (g_ClientWidth != width || g_ClientHeight != height)
{
// Don't allow 0 size swap chain back buffers.
g_ClientWidth = std::max(1u, width );
g_ClientHeight = std::max( 1u, height);
// Flush the GPU queue to make sure the swap chain's back buffers
// are not being referenced by an in-flight command list.
Flush(g_CommandQueue, g_Fence, g_FenceValue, g_FenceEvent);
for (int i = 0; i < g_NumFrames; ++i)
{
// Any references to the back buffers must be released
// before the swap chain can be resized.
g_BackBuffers[i].Reset();
g_FrameFenceValues[i] = g_FrameFenceValues[g_CurrentBackBufferIndex];
}
DXGI_SWAP_CHAIN_DESC swapChainDesc = {};
ThrowIfFailed(g_SwapChain->GetDesc(&swapChainDesc));
ThrowIfFailed(g_SwapChain->ResizeBuffers(g_NumFrames, g_ClientWidth, g_ClientHeight,
swapChainDesc.BufferDesc.Format, swapChainDesc.Flags));
g_CurrentBackBufferIndex = g_SwapChain->GetCurrentBackBufferIndex();
UpdateRenderTargetViews(g_Device, g_SwapChain, g_RTVDescriptorHeap);
}
}
void SetFullscreen(bool fullscreen)
{
if (g_Fullscreen != fullscreen)
{
g_Fullscreen = fullscreen;
if (g_Fullscreen) // Switching to fullscreen.
{
// Store the current window dimensions so they can be restored
// when switching out of fullscreen state.
::GetWindowRect(g_hWnd, &g_WindowRect);
// Set the window style to a borderless window so the client area fills
// the entire screen.
UINT windowStyle = WS_OVERLAPPEDWINDOW & ~(WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX);
::SetWindowLongW(g_hWnd, GWL_STYLE, windowStyle);
// Query the name of the nearest display device for the window.
// This is required to set the fullscreen dimensions of the window
// when using a multi-monitor setup.
HMONITOR hMonitor = ::MonitorFromWindow(g_hWnd, MONITOR_DEFAULTTONEAREST);
MONITORINFOEX monitorInfo = {};
monitorInfo.cbSize = sizeof(MONITORINFOEX);
::GetMonitorInfo(hMonitor, &monitorInfo);
::SetWindowPos(g_hWnd, HWND_TOP,
monitorInfo.rcMonitor.left,
monitorInfo.rcMonitor.top,
monitorInfo.rcMonitor.right - monitorInfo.rcMonitor.left,
monitorInfo.rcMonitor.bottom - monitorInfo.rcMonitor.top,
SWP_FRAMECHANGED | SWP_NOACTIVATE);
::ShowWindow(g_hWnd, SW_MAXIMIZE);
}
else
{
// Restore all the window decorators.
::SetWindowLong(g_hWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW);
::SetWindowPos(g_hWnd, HWND_NOTOPMOST,
g_WindowRect.left,
g_WindowRect.top,
g_WindowRect.right - g_WindowRect.left,
g_WindowRect.bottom - g_WindowRect.top,
SWP_FRAMECHANGED | SWP_NOACTIVATE);
::ShowWindow(g_hWnd, SW_NORMAL);
}
}
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if ( g_IsInitialized )
{
switch (message)
{
case WM_PAINT:
Update();
Render();
break;
case WM_SYSKEYDOWN:
case WM_KEYDOWN:
{
bool alt = (::GetAsyncKeyState(VK_MENU) & 0x8000) != 0;
switch (wParam)
{
case 'V':
g_VSync = !g_VSync;
break;
case VK_ESCAPE:
::PostQuitMessage(0);
break;
case VK_RETURN:
if ( alt )
{
case VK_F11:
SetFullscreen(!g_Fullscreen);
}
break;
}
}
break;
// The default window procedure will play a system notification sound
// when pressing the Alt+Enter keyboard combination if this message is
// not handled.
case WM_SYSCHAR:
break;
case WM_SIZE:
{
RECT clientRect = {};
::GetClientRect(g_hWnd, &clientRect);
int width = clientRect.right - clientRect.left;
int height = clientRect.bottom - clientRect.top;
Resize(width, height);
}
break;
case WM_DESTROY:
::PostQuitMessage(0);
break;
default:
return ::DefWindowProcW(hwnd, message, wParam, lParam);
}
}
else
{
return ::DefWindowProcW(hwnd, message, wParam, lParam);
}
return 0;
}
int CALLBACK wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR lpCmdLine, int nCmdShow)
{
// Windows 10 Creators update adds Per Monitor V2 DPI awareness context.
// Using this awareness context allows the client area of the window
// to achieve 100% scaling while still allowing non-client window content to
// be rendered in a DPI sensitive fashion.
SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
// Window class name. Used for registering / creating the window.
const wchar_t* windowClassName = L"DX12WindowClass";
ParseCommandLineArguments();
EnableDebugLayer();
g_TearingSupported = CheckTearingSupport();
RegisterWindowClass(hInstance, windowClassName);
g_hWnd = CreateWindow(windowClassName, hInstance, L"Learning DirectX 12 - Lesson 1",
g_ClientWidth, g_ClientHeight);
// Initialize the global window rect variable.
::GetWindowRect(g_hWnd, &g_WindowRect);
ComPtr<IDXGIAdapter4> dxgiAdapter4 = GetAdapter(g_UseWarp);
g_Device = CreateDevice(dxgiAdapter4);
g_CommandQueue = CreateCommandQueue(g_Device, D3D12_COMMAND_LIST_TYPE_DIRECT);
g_SwapChain = CreateSwapChain(g_hWnd, g_CommandQueue,
g_ClientWidth, g_ClientHeight, g_NumFrames);
g_CurrentBackBufferIndex = g_SwapChain->GetCurrentBackBufferIndex();
g_RTVDescriptorHeap = CreateDescriptorHeap(g_Device, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, g_NumFrames);
g_RTVDescriptorSize = g_Device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
UpdateRenderTargetViews(g_Device, g_SwapChain, g_RTVDescriptorHeap);
for (int i = 0; i < g_NumFrames; ++i)
{
g_CommandAllocators[i] = CreateCommandAllocator(g_Device, D3D12_COMMAND_LIST_TYPE_DIRECT);
}
g_CommandList = CreateCommandList(g_Device,
g_CommandAllocators[g_CurrentBackBufferIndex], D3D12_COMMAND_LIST_TYPE_DIRECT);
g_Fence = CreateFence(g_Device);
g_FenceEvent = CreateEventHandle();
g_IsInitialized = true;
::ShowWindow(g_hWnd, SW_SHOW);
MSG msg = {};
while (msg.message != WM_QUIT)
{
if (::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
}
// Make sure the command queue has finished all commands before closing.
Flush(g_CommandQueue, g_Fence, g_FenceValue, g_FenceEvent);
::CloseHandle(g_FenceEvent);
return 0;
} | 32.956989 | 149 | 0.682259 | RichardRanft |
129321220fb08fa0b0b2d3706a18782bebda7a2a | 1,143 | cpp | C++ | src/main.cpp | degarashi/sprinkler | afc6301ae2c7185f514148100da63dcef94d7f00 | [
"MIT"
] | null | null | null | src/main.cpp | degarashi/sprinkler | afc6301ae2c7185f514148100da63dcef94d7f00 | [
"MIT"
] | null | null | null | src/main.cpp | degarashi/sprinkler | afc6301ae2c7185f514148100da63dcef94d7f00 | [
"MIT"
] | null | null | null | #include "sprinkler.hpp"
#include "toml_settings.hpp"
#include <QApplication>
#include <QTranslator>
#include <QTextCodec>
#include <QLibraryInfo>
#include <QSettings>
int main(int argc, char *argv[]) {
// for XmbTextPropertyToTextList(for Linux)
std::setlocale(LC_ALL, "");
QApplication a(argc, argv);
// set organization name etc...
QCoreApplication::setOrganizationName("DegarashiLab");
QCoreApplication::setOrganizationDomain("Degarashi.deg");
QCoreApplication::setApplicationName("sprinkler");
// set default settings file format (INI)
QSettings::setDefaultFormat(QSettings::IniFormat);
// install translation
QTranslator tr;
{
QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf8"));
QString loc = QLocale::system().name();
tr.load("qtbase_" + loc,
QLibraryInfo::location(QLibraryInfo::TranslationsPath)
);
tr.load(QString("sprinkler_") + loc, QApplication::applicationDirPath());
a.installTranslator(&tr);
}
constexpr const char* TomlFileName = "settings.toml";
dg::TomlSettings ts(QApplication::applicationDirPath() + "/" + TomlFileName);
const dg::Sprinkler spr;
return a.exec();
}
| 27.878049 | 78 | 0.738408 | degarashi |
129482ad63f88477de364232ecccd481d87c90f1 | 34,934 | cpp | C++ | WaveletTL/galerkin/tframe_equation.cpp | kedingagnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | 3 | 2018-05-20T15:25:58.000Z | 2021-01-19T18:46:48.000Z | WaveletTL/galerkin/tframe_equation.cpp | agnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | null | null | null | WaveletTL/galerkin/tframe_equation.cpp | agnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | 2 | 2019-04-24T18:23:26.000Z | 2020-09-17T10:00:27.000Z | // implementation for tframe_equation.h
#include <cmath>
#include <time.h>
#include <utils/fixed_array1d.h>
#include <numerics/gauss_data.h>
#include <numerics/eigenvalues.h>
#include <cube/tframe_support.h>
namespace WaveletTL
{
// //PERFORMANCE : wozu compute_rhs? welches jmax in den Konstruktoren? (wenn überhaupt)
// template <class IFRAME, unsigned int DIM, class TENSORFRAME>
// TensorFrameEquation<IFRAME,DIM,TENSORFRAME>::TensorFrameEquation(EllipticBVP<DIM>* bvp,
// const FixedArray1D<bool,2*DIM>& bc,
// const bool precompute_rhs)
// : bvp_(bvp), frame_(bc), normA(0.0), normAinv(0.0)
// {
// if (precompute_rhs == true)
// {
// cout << "Maximal level is set to "<<multi_degree(frame_.j0())<< ". Maximal polynomial to " << 0 << ". You may want to increase that." << endl;
// frame_.set_jpmax(multi_degree(frame_.j0()),0);
// compute_rhs();
// }
// }
// template <class IFRAME, unsigned int DIM, class TENSORFRAME>
// TensorFrameEquation<IFRAME,DIM,TENSORFRAME>::TensorFrameEquation(const EllipticBVP<DIM>* bvp,
// const FixedArray1D<int,2*DIM>& bc,
// const bool precompute)
// : bvp_(bvp), frame_(bc), normA(0.0), normAinv(0.0)
// {
// if (precompute == true)
// {
// cout << "Maximal level is set to "<<multi_degree(frame_.j0())<< ". Maximal polynomial to " << 0 << ". You may want to increase that." << endl;
// frame_.set_jpmax(multi_degree(frame_.j0()),0); // for a first quick hack
// compute_rhs();
// }
// }
template <class IFRAME, unsigned int DIM, class TENSORFRAME>
TensorFrameEquation<IFRAME,DIM,TENSORFRAME>::TensorFrameEquation(const EllipticBVP<DIM>* bvp, const Frame* frame, const bool precompute_rhs)
: nonzeroneumann_(false), bvp_(bvp), frame_(frame), normA(0.0), normAinv(0.0)
{
#ifndef DYADIC
compute_diagonal();
#endif
if (precompute_rhs)
{
// cout << "Maximal level is set to "<<multi_degree(frame_->j0())<< ". Maximal polynomial to " << 0 << ". You may want to increase that." << endl;
// frame_->set_jpmax(multi_degree(frame_->j0()),0);
compute_rhs();
}
}
//constructor with given neumann-bc function
template <class IFRAME, unsigned int DIM, class TENSORFRAME>
TensorFrameEquation<IFRAME,DIM,TENSORFRAME>::TensorFrameEquation(const EllipticBVP<DIM>* bvp, const Frame* frame, const Function<DIM>* phi, const bool precompute_rhs)
: nonzeroneumann_(true), bvp_(bvp), frame_(frame), phi_(phi), normA(0.0), normAinv(0.0)
{
cout<<"set non-zero neumann boundary conditions"<<endl;
#ifndef DYADIC
compute_diagonal();
#endif
if (precompute_rhs)
{
// cout << "Maximal level is set to "<<multi_degree(frame_->j0())<< ". Maximal polynomial to " << 0 << ". You may want to increase that." << endl;
// frame_->set_jpmax(multi_degree(frame_->j0()),0);
compute_rhs();
}
}
template <class IFRAME, unsigned int DIM, class TENSORFRAME>
TensorFrameEquation<IFRAME,DIM,TENSORFRAME>::TensorFrameEquation(const TensorFrameEquation& eq)
: bvp_(eq.bvp_), frame_(eq.frame_),
fcoeffs(eq.fcoeffs), fnorm_sqr(eq.fnorm_sqr),
normA(eq.normA), normAinv(eq.normAinv)
{
#ifndef DYADIC
compute_diagonal();
#endif
// cout << "Maximal level is set to "<<multi_degree(frame_.j0())<< ". Maximal polynomial to " << 0 << ". You may want to increase that." << endl;
// frame_.set_jpmax(multi_degree(frame_.j0()),0);
}
// TODO PERFORMANCE:: use setup_full_collection entries
template <class IFRAME, unsigned int DIM, class TENSORFRAME>
void
TensorFrameEquation<IFRAME,DIM,TENSORFRAME>::compute_rhs()
{
cout << "TensorFrameEquation(): precompute right-hand side..." << endl;
// precompute the right-hand side on a fine level
InfiniteVector<double,Index> fhelp;
InfiniteVector<double,int> fhelp_int;
fnorm_sqr = 0;
double coeff;
#if PARALLEL_RHS==1
double fnorm_sqr_help = 0.;
cout<<"parallel computing rhs"<<endl;
#pragma omp parallel
{
// cout<<"number of threads: "<<omp_get_num_threads()<<endl;
#pragma omp for private(coeff) schedule(static) reduction(+:fnorm_sqr_help)
for (unsigned int i = 0; (int)i< frame_->degrees_of_freedom();i++)
{
coeff = f(frame_->get_quarklet(i)) / D(frame_->get_quarklet(i));
if (fabs(coeff)>1e-15)
{
#pragma omp critical
{fhelp.set_coefficient(frame_->get_quarklet(i), coeff);
fhelp_int.set_coefficient(i, coeff);}
fnorm_sqr_help += coeff*coeff;
}
}
}
fnorm_sqr=fnorm_sqr_help;
#else
for (int i = 0; i< frame_->degrees_of_freedom();i++)
{
// cout<<i<<": "<<*(frame_->get_quarklet(i))<<endl;
coeff = f(*(frame_->get_quarklet(i))) / D(*(frame_->get_quarklet(i)));
if (fabs(coeff)>1e-15)
{
fhelp.set_coefficient(*(frame_->get_quarklet(i)), coeff);
fnorm_sqr += coeff*coeff;
fhelp_int.set_coefficient(i, coeff);
}
}
#endif
cout << "... done, sort the entries in modulus..." << endl;
// sort the coefficients into fcoeffs
fcoeffs.resize(0); // clear eventual old values
fcoeffs_int.resize(0);
fcoeffs.resize(fhelp.size());
fcoeffs_int.resize(fhelp_int.size());
unsigned int id(0), id2(0);
for (typename InfiniteVector<double,Index>::const_iterator it(fhelp.begin()), itend(fhelp.end());it != itend; ++it, ++id)
{
fcoeffs[id] = std::pair<Index,double>(it.index(), *it);
// cout << it.index() << ", " << *it << endl;
}
for (typename InfiniteVector<double,int>::const_iterator it(fhelp_int.begin()), itend(fhelp_int.end()); it != itend; ++it, ++id2){
fcoeffs_int[id2] = std::pair<int,double>(it.index(), *it);
// cout << it.index() << ", " << *it << endl;
}
sort(fcoeffs.begin(), fcoeffs.end(), typename InfiniteVector<double,Index>::decreasing_order());
sort(fcoeffs_int.begin(), fcoeffs_int.end(), typename InfiniteVector<double,int>::decreasing_order());
cout << "... done, all integrals for right-hand side computed!" << endl;
// cout<<fcoeffs.size()<<endl;
}
template <class IFRAME, unsigned int DIM, class TENSORFRAME>
inline
double
TensorFrameEquation<IFRAME,DIM,TENSORFRAME>::D(const Index& lambda) const
{
#ifdef DYADIC
double hspreconditioner(0), l2preconditioner(1);
for (int i=0; i<space_dimension; i++){
hspreconditioner+=pow(1+lambda.p()[i],8)*(1<<(2*lambda.j()[i]));
l2preconditioner*=pow(1+lambda.p()[i],2);
}
double preconditioner = sqrt(hspreconditioner)*l2preconditioner;
return preconditioner;
#endif
#ifdef TRIVIAL
return 1;
#endif
#ifdef ENERGY
return stiff_diagonal[lambda.number()];
#endif
#ifdef DYPLUSEN
double hspreconditioner(0), l2preconditioner(1);
for (int i=0; i<space_dimension; i++){
hspreconditioner+=pow(1+lambda.p()[i],6);
l2preconditioner*=pow(1+lambda.p()[i],2);
}
double preconditioner = sqrt(hspreconditioner)*l2preconditioner*stiff_diagonal[lambda.number()]/sqrt(space_dimension);
// double preconditioner = sqrt(0.1)*stiff_diagonal[lambda.number()];
return preconditioner;
#endif
}
template <class IFRAME, unsigned int DIM, class TENSORFRAME>
inline
double
TensorFrameEquation<IFRAME,DIM,TENSORFRAME>::a(const Index& lambda,
const Index& nu) const
{
return a(lambda, nu, 2*IFRAME::primal_polynomial_degree());
}
template <class IFRAME, unsigned int DIM, class TENSORFRAME>
double
TensorFrameEquation<IFRAME,DIM,TENSORFRAME>::a(const Index& la,
const Index& nu,
const unsigned int p) const
{
// a(u,v) = \int_Omega [a(x)grad u(x)grad v(x)+q(x)u(x)v(x)] dx
double r = 0;
// Frame1D myframe;
const Index* lambda = &la;
const Index* mu = ν
// first decide whether the supports of psi_lambda and psi_mu intersect
typedef typename Frame::Support Support;
Support supp;
if (intersect_supports(*frame_, *lambda, *mu, supp))
{
// Point<DIM> x;
// const double ax = bvp_->constant_coefficients() ? bvp_->a(x) : 0.0; //currently we do not support this
// const double qx = bvp_->constant_coefficients() ? bvp_->q(x) : 0.0;
int N_Gauss [DIM];
for (unsigned int i = 0; i < DIM; i++) {
N_Gauss[i] = (p+1)/2+(lambda->p()[i]+mu->p()[i]+1)/2;
}
// loop over spatial direction
for (unsigned int i = 0; i < DIM; i++) {
double t = 1.;
for (unsigned int j = 0; j < DIM; j++) {
if (j == i)
continue;
// IFRAME frame1d_la= frame_->frames(lambda->patch(),j);
// IFRAME frame1d_mu= frame_->frames(mu->patch(),j);
IndexQ1D<IFRAME> i1(IntervalQIndex<IFRAME> (
lambda->p()[j],lambda->j()[j],lambda->e()[j],lambda->k()[j],
frame_->frames()[j]
),
0,j,0 //patch not relevant
);
IndexQ1D<IFRAME> i2(IntervalQIndex<IFRAME> (mu->p()[j],mu->j()[j],mu->e()[j],mu->k()[j],
frame_->frames()[j]
),
0,j,0
);
t *= integrate(i1, i2, N_Gauss[j], j, supp);
// cout << "Zwischenergebnis Richtung: " << j << "Wert: " << t << endl;
}
// IFRAME frame1d_la= frame_->frames(lambda->patch(),i);
// IFRAME frame1d_mu= frame_->frames(mu->patch(),i);
IndexQ1D<IFRAME> i1(IntervalQIndex<IFRAME> (
lambda->p()[i],lambda->j()[i],lambda->e()[i],lambda->k()[i],
frame_->frames()[i]
),
0,i,1 //patch not relevant
);
IndexQ1D<IFRAME> i2(IntervalQIndex<IFRAME> (mu->p()[i],mu->j()[i],mu->e()[i],mu->k()[i],
frame_->frames()[i]
),
0,i,1
);
t *= integrate(i1, i2, N_Gauss[i], i, supp);
r += t;
}
// double integral[space_dimension], der_integral[space_dimension];
// integral[0]=0, integral[1]=0, der_integral[0]=0, der_integral[1]=0;
// FixedArray1D<Array1D<double>,DIM> psi_lambda_values, // values of the components of psi_lambda at gauss_points[i]
// psi_mu_values, // -"-, for psi_mu
// psi_lambda_der_values, // values of the 1st deriv. of the components of psi_lambda at gauss_points[i]
// psi_mu_der_values; // -"-, for psi_mu
//
//
// const int N_Gauss = (p+1)/2+(multi_degree(lambda->p())+multi_degree(mu->p())+1)/2;
//
// FixedArray1D<Array1D<double>,DIM> gauss_points, gauss_weights;
//
// for (unsigned int i = 0; i < DIM; i++) {
//
//
// hi = ldexp(1.0, -supp.j[i]);
// gauss_points[i].resize(N_Gauss*(supp.b[i]-supp.a[i]));
// gauss_weights[i].resize(N_Gauss*(supp.b[i]-supp.a[i]));
// for (int patch = supp.a[i]; patch < supp.b[i]; patch++)
// for (int n = 0; n < N_Gauss; n++) {
// gauss_points[i][(patch-supp.a[i])*N_Gauss+n]
// = hi*(2*patch+1+GaussPoints[N_Gauss-1][n])/2.;
// gauss_weights[i][(patch-supp.a[i])*N_Gauss+n]
// = hi*GaussWeights[N_Gauss-1][n];
// }
//
//
//
// evaluate(*(frame_->frames()[i]),
// lambda->p()[i],
// lambda->j()[i],
// lambda->e()[i],
// lambda->k()[i],
// gauss_points[i], psi_lambda_values[i], psi_lambda_der_values[i]);
//
// evaluate(*(frame_->frames()[i]),
// mu->p()[i],
// mu->j()[i],
// mu->e()[i],
// mu->k()[i],
// gauss_points[i], psi_mu_values[i], psi_mu_der_values[i]);
//
// for (unsigned int ind = 0; ind < gauss_points[i].size(); ind++){
//
// integral[i] += psi_lambda_values[i][ind] * psi_mu_values[i][ind] * gauss_weights[i][ind];
// der_integral[i] += psi_lambda_der_values[i][ind] * psi_mu_der_values[i][ind] * gauss_weights[i][ind];
// }
//
// }
//
// r = ax * (der_integral[0] * integral[1] + integral[0] * der_integral[1]) + qx * (integral[0] * integral[1]);
}
return r;
}
template <class IFRAME, unsigned int DIM, class TENSORFRAME>
double
TensorFrameEquation<IFRAME,DIM,TENSORFRAME>::f(const Index& lambda) const
{
// f(v) = \int_0^1 g(t)v(t) dt
#if 0
double r = 1.;
for (unsigned int i = 0; i < DIM; i++)
r *= evaluate(*frame_.frames()[i], 0,
typename IFRAME::Index(lambda.j()[i],
lambda.e()[i],
lambda.k()[i],
frame_.frames()[i]),
0.5);
return r;
#endif
#if 1
double r = 0;
// first compute supp(psi_lambda)
typedef typename Frame::Support Support;
Support supp;
support(*frame_, lambda, supp);
// setup Gauss points and weights for a composite quadrature formula:
const int N_Gauss = 6;
// FixedArray1D<double,DIM> h; // = ldexp(1.0, -supp.j); // granularity for the quadrature
double hi; // granularity for the quadrature
FixedArray1D<Array1D<double>,DIM> gauss_points, gauss_weights, v_values;
for (unsigned int i = 0; i < DIM; i++) {
hi = ldexp(1.0,-supp.j[i]);
gauss_points[i].resize(N_Gauss*(supp.b[i]-supp.a[i]));
gauss_weights[i].resize(N_Gauss*(supp.b[i]-supp.a[i]));
for (int patch = supp.a[i]; patch < supp.b[i]; patch++)
for (int n = 0; n < N_Gauss; n++) {
gauss_points[i][(patch-supp.a[i])*N_Gauss+n]
= hi*(2*patch+1+GaussPoints[N_Gauss-1][n])/2.;
gauss_weights[i][(patch-supp.a[i])*N_Gauss+n]
= hi*GaussWeights[N_Gauss-1][n];
}
}
// compute the point values of the integrand (where we use that it is a tensor product)
for (unsigned int i = 0; i < DIM; i++)
evaluate(*(frame_->frames()[i]), 0,
lambda.p()[i],
lambda.j()[i],
lambda.e()[i],
lambda.k()[i],
gauss_points[i], v_values[i]);
// iterate over all points and sum up the integral shares
int index[DIM]; // current multiindex for the point values
for (unsigned int i = 0; i < DIM; i++)
index[i] = 0;
Point<DIM> x;
while (true) {
for (unsigned int i = 0; i < DIM; i++)
x[i] = gauss_points[i][index[i]];
double share = bvp_->f(x);
for (unsigned int i = 0; i < DIM; i++)
share *= gauss_weights[i][index[i]] * v_values[i][index[i]];
r += share;
// "++index"
bool exit = false;
for (unsigned int i = 0; i < DIM; i++) {
if (index[i] == N_Gauss*(supp.b[i]-supp.a[i])-1) {
index[i] = 0;
exit = (i == DIM-1);
} else {
index[i]++;
break;
}
}
if (exit) break;
}
// cout<<"r="<<r<<endl;
//#ifdef NONZERONEUMANN
if(nonzeroneumann_){
//add boundary integral
double rrand=0;
// cout<<"bin hier"<<endl;
Array1D<double> phi_values;
if(DIM==2){
// loop over spatial direction
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
if (j == i)
continue;
phi_values.resize(N_Gauss*(supp.b[j]-supp.a[j]));
for(int rand_punkt=0;rand_punkt<2;rand_punkt++){
double rand_value=frame_->frames()[i]->evaluate(0,lambda.p()[i],lambda.j()[i],lambda.e()[i],lambda.k()[i],rand_punkt);
// if((j==1 && rand_punkt==0) || (j==0 && rand_punkt==1)){
//
// }
for(int i2=0;i2<N_Gauss*(supp.b[j]-supp.a[j]);i2++){
x[i]=rand_punkt; x[j]=gauss_points[j][i2];
// cout<<x<<endl;
phi_values[i2]=phi(x);
rrand+=phi_values[i2]*rand_value*gauss_weights[j][i2]*v_values[j][i2];
}
// if(rand_value!=0){
// cout<<"weights:"<<gauss_weights[j]<<endl;
// cout<<"points:"<<gauss_points[j]<<endl;
// cout<<"v_values:"<<v_values[j]<<endl;
// cout<<"phi_values:"<<phi_values<<endl;
// }
}
}
// cout<<"rrand="<<rrand<<endl;
}
}
r+=rrand;
}
//#endif
// cout<<"rrand="<<rrand<<endl;
#ifdef DELTADIS
//r+= 4*frame_->frames()[0]->evaluate(0,lambda.p()[0],lambda.j()[0],lambda.e()[0],lambda.k()[0],0.5);
for(int i2=0;i2<N_Gauss*(supp.b[1]-supp.a[1]);i2++){
r+=4*frame_->frames()[0]->evaluate(0,lambda.p()[0],lambda.j()[0],lambda.e()[0],lambda.k()[0],0.5)*gauss_weights[1][i2]*v_values[1][i2];
}
#endif
return r;
#endif
}
template <class IFRAME, unsigned int DIM, class TENSORFRAME>
void
TensorFrameEquation<IFRAME,DIM,TENSORFRAME>::RHS(const double eta,
InfiniteVector<double, Index>& coeffs) const
{
coeffs.clear();
double coarsenorm(0);
double bound(fnorm_sqr - eta*eta);
// typedef typename Frame::Index Index;
typename Array1D<std::pair<Index, double> >::const_iterator it(fcoeffs.begin());
while (it != fcoeffs.end() && coarsenorm < bound)
{
coarsenorm += it->second * it->second;
coeffs.set_coefficient(it->first, it->second);
++it;
}
}
template <class IFRAME, unsigned int DIM, class TENSORFRAME>
void
TensorFrameEquation<IFRAME,DIM,TENSORFRAME>::RHS(const double eta,
InfiniteVector<double, int>& coeffs) const
{
coeffs.clear();
double coarsenorm(0);
double bound(fnorm_sqr - eta*eta);
typename Array1D<std::pair<int, double> >::const_iterator it(fcoeffs_int.begin());
while (it != fcoeffs_int.end() && coarsenorm < bound)
{
coarsenorm += it->second * it->second;
coeffs.set_coefficient(it->first, it->second);
++it;
}
}
template <class IFRAME, unsigned int DIM, class TENSORFRAME>
void
TensorFrameEquation<IFRAME,DIM,TENSORFRAME>::set_bvp(const EllipticBVP<DIM>* bvp)
{
bvp_ = bvp;
compute_rhs();
}
template <class IFRAME, unsigned int DIM, class TENSORFRAME>
void
TensorFrameEquation<IFRAME,DIM,TENSORFRAME>::set_f(const Function<DIM>* fnew)
{
bvp_->set_f(fnew);
compute_rhs();
}
// template <class IFRAME, unsigned int DIM, class TENSORFRAME>
// double
// TensorFrameEquation<IFRAME,DIM,TENSORFRAME>::s_star() const
// {
// return 1000.1; // a big number, since s_star == \infty
/*
// notation from [St04a]
const double t = operator_order();
const int n = DIM;
const int dT = QuarkletFrame::primal_vanishing_moments();
const double gamma = QuarkletFrame::primal_regularity();
return (n == 1
? t+dT // [St04a], Th. 2.3 for n=1
: std::min((t+dT)/(double)n, (gamma-t)/(n-1.))); // [St04a, Th. 2.3]
*/
// }
template <class IFRAME, unsigned int DIM, class TENSORFRAME>
void
TensorFrameEquation<IFRAME, DIM, TENSORFRAME>::compute_diagonal()
{
cout << " TensorFrameEquation(): precompute diagonal of stiffness matrix..." << endl;
SparseMatrix<double> diag(1,frame_->degrees_of_freedom());
// char filename[50];
// char matrixname[50];
// #ifdef ONE_D
// int d = IFRAME::primal_polynomial_degree();
// int dT = IFRAME::primal_vanishing_moments();
// #else
// #ifdef TWO_D
// int d = IFRAME::primal_polynomial_degree();
// int dT = IFRAME::primal_vanishing_moments();
// #endif
// #endif
// prepare filenames for 1D and 2D case
#ifdef ONE_D
sprintf(filename, "%s%d%s%d", "stiff_diagonal_poisson_interval_lap07_d", d, "_dT", dT);
sprintf(matrixname, "%s%d%s%d", "stiff_diagonal_poisson_1D_lap07_d", d, "_dT", dT);
#endif
#ifdef TWO_D
//sprintf(filename, "%s%d%s%d", "stiff_diagonal_poisson_lshaped_lap1_d", d, "_dT", dT);
//sprintf(matrixname, "%s%d%s%d", "stiff_diagonal_poisson_2D_lap1_d", d, "_dT", dT);
#endif
#ifndef PRECOMP_DIAG
std::list<Vector<double>::size_type> indices;
std::list<double> entries;
#endif
#ifdef PRECOMP_DIAG
cout << "reading in diagonal of unpreconditioned stiffness matrix from file "
<< filename << "..." << endl;
diag.matlab_input(filename);
cout << "...ready" << endl;
#endif
stiff_diagonal.resize(frame_->degrees_of_freedom());
for (int i = 0; i < frame_->degrees_of_freedom(); i++) {
#ifdef PRECOMP_DIAG
stiff_diagonal[i] = diag.get_entry(0,i);
#endif
#ifndef PRECOMP_DIAG
#ifdef FRAME
stiff_diagonal[i] = sqrt(a(*(frame_->get_quarklet(i)),*(frame_->get_quarklet(i))));
#endif
#ifdef BASIS
stiff_diagonal[i] = sqrt(a(*(frame_->get_wavelet(i)),*(frame_->get_wavelet(i))));
#endif
indices.push_back(i);
entries.push_back(stiff_diagonal[i]);
#endif
//cout << stiff_diagonal[i] << " " << *(frame_->get_wavelet(i)) << endl;
}
#ifndef PRECOMP_DIAG
diag.set_row(0,indices, entries);
//diag.matlab_output(filename, matrixname, 1);
#endif
cout << "... done, diagonal of stiffness matrix computed" << endl;
}
// PERFORMANCE :: use setup_full_collection
template <class IFRAME, unsigned int DIM, class TENSORFRAME>
double
TensorFrameEquation<IFRAME,DIM,TENSORFRAME>::norm_A() const
{
if (normA == 0.0) {
typedef typename Index::polynomial_type polynomial_type;
int offsetj, offsetp;
switch (space_dimension) {
case 1:
offsetj = 2, offsetp = std::min((int)frame_->get_pmax(),2);
break;
case 2:
// offsetj = 1,
offsetj=std::min(1,(int)frame_->get_jmax()-(int)multi_degree(frame_->j0()));
offsetp = std::min((int)frame_->get_pmax(),2);
break;
default:
offsetj = 0, offsetp = 0;
}
std::set<Index> Lambda;
// cout << "tframe_equation.norm_A :: last quarklet = " << (frame_.last_quarklet(multi_degree(frame_.j0())+offset)) << endl;
polynomial_type p;
for (Index lambda = frame_->first_generator(frame_->j0(), p) ;;) {
Lambda.insert(lambda);
if (lambda == frame_->last_quarklet(multi_degree(frame_->j0())+offsetj, p)){
++p;
if ((int)multi_degree(p)>offsetp) break;
lambda = frame_->first_generator(frame_->j0(), p);
}
else
++lambda;
}
// typename std::set<Index>::const_iterator it(Lambda.begin()), itend(Lambda.end());
// for(int zaehler=0;it!=itend;it++){
// ++zaehler;
// cout << zaehler << ", " << *it << endl;
// }
SparseMatrix<double> A_Lambda;
setup_stiffness_matrix(*this, Lambda, A_Lambda);
A_Lambda.compress(1e-10);
#if 1
// double help;
// unsigned int iterations;
// LanczosIteration(A_Lambda, 1e-6, help, normA, 200, iterations);
// normAinv = 1./help;
Matrix<double> evecs;
Vector<double> evals;
SymmEigenvalues(A_Lambda, evals, evecs);
int i = 0;
while(abs(evals(i))<1e-2){
++i;
}
normA = evals(evals.size()-1);
normAinv = 1./evals(i);
#else
Vector<double> xk(Lambda.size(), false);
xk = 1;
unsigned int iterations;
normA = PowerIteration(A_Lambda, xk, 1e-6, 100, iterations);
#endif
}
return normA;
}
template <class IFRAME, unsigned int DIM, class TENSORFRAME>
double
TensorFrameEquation<IFRAME,DIM,TENSORFRAME>::norm_Ainv() const
{
if (normAinv == 0.0) {
typedef typename Frame::Index Index;
typedef typename Index::polynomial_type polynomial_type;
std::set<Index> Lambda;
polynomial_type p;
//const int j0 = frame().j0();
//const int jmax = j0+3;
int offsetj, offsetp;
switch (space_dimension) {
case 1:
offsetj = 2, offsetp = std::min((int)frame_->get_pmax(),2);
break;
case 2:
// offsetj = 1,
offsetj=std::min(1,(int)frame_->get_jmax()-(int)multi_degree(frame_->j0()));
offsetp = std::min((int)frame_->get_pmax(),2);
break;
default:
offsetj = 0, offsetp = 0;
}
for (Index lambda = frame_->first_generator(frame_->j0()) ;;) {
Lambda.insert(lambda);
if (lambda == frame_->last_quarklet(multi_degree(frame_->j0())+offsetj, p) ){
++p;
if ((int)multi_degree(p)>offsetp) break;
lambda = frame_->first_generator(frame_->j0(), p);
}
else
++lambda;
}
SparseMatrix<double> A_Lambda;
setup_stiffness_matrix(*this, Lambda, A_Lambda);
A_Lambda.compress(1e-10);
#if 1
// double help;
// unsigned int iterations;
// LanczosIteration(A_Lambda, 1e-6, help, normA, 200, iterations);
// normAinv = 1./help;
Matrix<double> evecs;
Vector<double> evals;
SymmEigenvalues(A_Lambda, evals, evecs);
cout << evals << endl;
int i = 0;
while(abs(evals(i))<1e-2){
++i;
}
normA = evals(evals.size()-1);
normAinv = 1./evals(i);
#else
Vector<double> xk(Lambda.size(), false);
xk = 1;
unsigned int iterations;
normAinv = InversePowerIteration(A_Lambda, xk, 1e-6, 200, iterations);
#endif
}
return normAinv;
}
template <class IFRAME, unsigned int DIM, class TENSORFRAME>
double
TensorFrameEquation<IFRAME, DIM, TENSORFRAME>:: integrate(const IndexQ1D<IFRAME>& la,
const IndexQ1D<IFRAME>& nu,
const int N_Gauss,
const int dir,
typename Frame::Support supp) const
{
double res=0.;
// cout<<"testing integrate"<<endl;
// cout<<"direction="<<dir<<endl;
// It makes sense to store the one dimensional
// integrals arising when we make use of the tensor product structure. This costs quite
// some memory, but really speeds up the algorithm!
const IndexQ1D<IFRAME>* lambda= nu < la? &la : ν
const IndexQ1D<IFRAME>* mu= nu < la ? &nu : &la;
// if(lambda->number()==lambda->index().number())
// cout << "truueee: " << lambda->index() << endl;
// if(lambda->number()!=lambda->index().number())
// cout << "faaaalsse: " << lambda->index() << ", " << lambda->number() << endl;
// cout << mu->number() << endl;
typename One_D_IntegralCache::iterator col_lb(one_d_integrals.lower_bound(*lambda));
typename One_D_IntegralCache::iterator col_it(col_lb);
if (col_lb == one_d_integrals.end() ||
one_d_integrals.key_comp()(*lambda,col_lb->first))
{
// insert a new column
typedef typename One_D_IntegralCache::value_type value_type;
col_it = one_d_integrals.insert(col_lb, value_type(*lambda, Column1D()));
}
Column1D& col(col_it->second);
typename Column1D::iterator lb(col.lower_bound(*mu));
typename Column1D::iterator it(lb);
if (lb == col.end() ||
col.key_comp()(*mu, lb->first))
{
double h; // granularity for the quadrature
Array1D<double> gauss_points, gauss_weights;
//compute gauss points and weights
double a =supp.a[dir];
double b =supp.b[dir];
// cout << "current support: ["<<a<<","<<b<<"]"<<endl;
// int e = std::max(lambda->e()[i], mu->e()[i]); //correct granularity
h = ldexp(1.0, -supp.j[dir]/*-e*/);
gauss_points.resize(N_Gauss*(b-a));
gauss_weights.resize(N_Gauss*(b-a));
for (int interval = a; interval < b; interval++){
for (int n = 0; n < N_Gauss; n++) {
gauss_points[(interval-a)*N_Gauss+n]= h*(2*interval+1+GaussPoints[N_Gauss-1][n])/2.;
gauss_weights[(interval-a)*N_Gauss+n]= h*GaussWeights[N_Gauss-1][n];
}
}
Array1D<double> lambda_gauss_points(gauss_points), mu_gauss_points(gauss_points);
Array1D<double> lambda_values, // values of the components of psi_lambda at gauss_points[i]
mu_values; // -"-, for psi_mu
const IFRAME* frame1D_lambda = frame_->frames()[dir];
const IFRAME* frame1D_mu = frame_->frames()[dir];
WaveletTL::evaluate(*frame1D_lambda, lambda->derivative(), lambda->index(),
/*lambda->index().p(),
lambda->index().j(),
lambda->index().e(),
lambda->index().k(),*/
lambda_gauss_points, lambda_values);
WaveletTL::evaluate(*frame1D_mu, mu->derivative(), mu->index(),
/*mu->index().p(),
mu->index().j(),
mu->index().e(),
mu->index().k(),*/
mu_gauss_points, mu_values);
// - add all integral shares
for (unsigned int ind = 0; ind < gauss_points.size(); ind++){
res += lambda_values[ind] * mu_values[ind] * gauss_weights[ind];
// der_integral += lambda_der_values[ind] * mu_der_values[ind] * gauss_weights[ind];
}
//store the calculated values
typedef typename Column1D::value_type value_type;
// cout << "Neuberechnung" << endl;
it = col.insert(lb, value_type(*mu, res));
}
else {
// cout << "aus dem Cache" << endl;
res = it->second;
}
// (lambda->derivative()==0? return integral : return der_integral);
// cout<<res<<endl;
return res;
}
}
| 42.447145 | 174 | 0.489065 | kedingagnumerikunimarburg |
1295a45e18959b43399fc3d7601a44dd5903f775 | 2,197 | cpp | C++ | tests/overview/src/main.cpp | makaleks/cxxplug | 7bec529fed7b685d255ea568cd16b900376a0efc | [
"MIT"
] | 1 | 2022-02-05T07:32:16.000Z | 2022-02-05T07:32:16.000Z | tests/overview/src/main.cpp | makaleks/cxxplug | 7bec529fed7b685d255ea568cd16b900376a0efc | [
"MIT"
] | null | null | null | tests/overview/src/main.cpp | makaleks/cxxplug | 7bec529fed7b685d255ea568cd16b900376a0efc | [
"MIT"
] | null | null | null | #include <iostream>
#include <string_view>
#include <vector>
#include <type_traits>
using namespace std;
#include <cxxplug.hpp>
#include <cxxplug/some_source_providers/filesystem_dynlib_provider.hpp>
#include <cxxplug/some_load_providers/libload_provider.hpp>
#include "cxxplug_gen/builtin/plugin_human_builtin.hpp"
#include <filesystem>
template <typename PlugLoaded>
void print_plugin_human (PlugLoaded &loaded) {
char lang[] = "eng";
int value = 10;
cout << "\
PluginHuman {\n\
src: " <<
(
loaded.is_builtin
? "<built_in>"
: (string("\"") + loaded.source_name + "\"")
) << "\n\
\n\
name: \"" << loaded.impl.get_implementation_name(lang) << "\"\n\
uuid: " << *(Uuid*)loaded.impl.get_implementation_id() << "\n\
\n\
first_name: \"" << loaded.impl.get_first_name() << "\"\n\
last_name: \"" << loaded.impl.get_last_name() << "\"\n\
age: " << std::dec << (unsigned)loaded.impl.get_age() << "\n\
work_with_int: " << value;
loaded.impl.work_with_int(&value);
cout << " => " << value << "\n\
}\n";
}
int main () {
cout << filesystem::current_path() << '\n';
// Yes, you are free to define and set your own LoadProvider, SourceProvider
// and even collection of builtin plugins - cxxplug flexible enough
CxxPlug<
PluginHumanInterface,
SourceProviderFilesystemDynLib<PluginHumanInterface>,
LoadProviderLibload
> plug(
"plugin_human",
// This array was generated using `cxxplug-gen-collected-proxies` tool
span<PluginHumanInterface>(begin(plugin_human),end(plugin_human))
);
auto lst = plug.get_available();
for (size_t i = 0; i < lst.size(); i++) {
cout << i << ": " << lst[i].string() << "\n";
}
if (0 != lst.size()) {
cout << "\n";
}
vector<result_of<
decltype(&decltype(plug)::load)(decltype(plug), decltype(lst[0]))
>::type> loaded;
for (size_t i = 0; i < lst.size(); i++) {
loaded.emplace_back(plug.load(lst[i]));
cout << i << ": ";
print_plugin_human(loaded[i]);
}
cout << "\nDone\n";
return 0;
}
| 28.166667 | 80 | 0.588075 | makaleks |
129f42ef576c1d18f4bfdab4ecee350710564449 | 7,014 | cpp | C++ | src/Image2D.cpp | vadosnaprimer/desktop-m3g | fa04787e8609cd0f4e63defc7f2c669c8cc78d1f | [
"MIT"
] | 2 | 2019-05-14T08:14:15.000Z | 2021-01-19T13:28:38.000Z | src/Image2D.cpp | vadosnaprimer/desktop-m3g | fa04787e8609cd0f4e63defc7f2c669c8cc78d1f | [
"MIT"
] | null | null | null | src/Image2D.cpp | vadosnaprimer/desktop-m3g | fa04787e8609cd0f4e63defc7f2c669c8cc78d1f | [
"MIT"
] | null | null | null | #include "m3g/m3g-gl.hpp"
#include "m3g/Image2D.hpp"
#include "m3g/Exception.hpp"
#include "m3g/RenderState.hpp"
#include "m3g/stb_image_writer.hpp"
#include <iostream>
#include <fstream>
#include <cstring>
using namespace m3g;
using namespace std;
const int Image2D:: ALPHA;
const int Image2D:: LUMINANCE;
const int Image2D:: LUMINANCE_ALPHA;
const int Image2D:: RGB;
const int Image2D:: RGBA;
Image2D:: Image2D (int format_, int width_, int height_) :
format(format_), width(width_), height(height_), image(0), immutable(false)
{
if (width <= 0 || height <= 0) {
throw IllegalArgumentException (__FILE__, __func__, "Width or height is invalid, width=%f, height=%f.", width, height);
}
if (format != Image2D::ALPHA && format != Image2D::LUMINANCE && format != Image2D::LUMINANCE_ALPHA &&
format != Image2D::RGB && format != Image2D::RGBA) {
throw IllegalArgumentException (__FILE__, __func__, "Format is invalid, format=%d", format);
}
int bpp = format_to_bpp (format);
image = new char [height*width*bpp];
memset (image, 0, height*width*bpp);
}
Image2D:: Image2D (int format_, int width_, int height_, void* pixels) :
format(format_), width(width_), height(height_), image(0), immutable(true)
{
if (width <= 0 || height <= 0) {
throw IllegalArgumentException (__FILE__, __func__, "Width or height is invalid, width=%f, height=%f.", width, height);
}
if (pixels == NULL) {
throw NullPointerException (__FILE__, __func__, "Image is NULL.");
}
if (format != Image2D::ALPHA && format != Image2D::LUMINANCE && format != Image2D::LUMINANCE_ALPHA &&
format != Image2D::RGB && format != Image2D::RGBA) {
throw IllegalArgumentException (__FILE__, __func__, "Format is invalid, format=%d", format);
}
int bpp = format_to_bpp (format);
image = new char [height*width*bpp];
memcpy (image, pixels, height*width*bpp);
}
Image2D:: Image2D (int format_, int width_, int height_, unsigned char* pixels, void* palette) :
format(format_), width(width_), height(height_), image(0), immutable(true)
{
if (pixels == NULL || palette == NULL) {
throw NullPointerException (__FILE__, __func__, "Palette or index is NULL.");
}
if (width <= 0 || height <= 0) {
throw IllegalArgumentException (__FILE__, __func__, "Width or height is invalid, width=%f, height=%f.", width, height);
}
if (format != Image2D::ALPHA && format != Image2D::LUMINANCE && format != Image2D::LUMINANCE_ALPHA &&
format != Image2D::RGB && format != Image2D::RGBA) {
throw IllegalArgumentException (__FILE__, __func__, "Format is invalid, format=%d", format);
}
int bpp = format_to_bpp (format);
image = new char [height*width*bpp];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int index = pixels[y*width + x];
memcpy (image + (y*width + x)*bpp, (char*)palette + index*bpp, bpp);
}
}
}
Image2D:: ~Image2D ()
{
delete [] image;
}
Image2D* Image2D:: duplicate () const
{
return duplicate_xxx (NULL);
}
Image2D* Image2D:: duplicate_xxx (Object3D* obj) const
{
Image2D* img = dynamic_cast<Image2D*>(obj);
if (img == NULL) {
if (immutable)
img = new Image2D (format, width, height, image);
else
img = new Image2D (format, width, height);
}
Object3D:: duplicate_xxx (img);
return img;
}
int Image2D:: getFormat () const
{
return format;
}
int Image2D:: getHeight () const
{
return height;
}
int Image2D:: getWidth () const
{
return width;
}
bool Image2D:: isMutable () const
{
return !immutable;
}
void Image2D:: set (int px, int py, int wid, int hei, const void* pixels)
{
if (immutable) {
throw IllegalStateException (__FILE__, __func__, "This image is immutable.");
}
if (px < 0 || px >= width || py < 0 || py >= height) {
throw IllegalArgumentException (__FILE__, __func__, "Coordinate(px,py) is invalid, px=%d, py=%d.", px, py);
}
if (wid < 0 || wid > width || hei < 0 || hei > height) {
throw IllegalArgumentException (__FILE__, __func__, "Size(width,height) is invalid, width=%d, height=%d.", wid, hei);
}
if (pixels == NULL) {
throw NullPointerException (__FILE__, __func__, "Image is NULL.");
}
int bpp = format_to_bpp (format);
for (int y = py; y < py+hei; y++) {
memcpy (image + y*width*bpp + px*bpp, (char*)pixels + (y-py)*wid*bpp, wid*bpp);
}
}
/**
* 注意:OpenGLは左下が(0,0)
*/
void Image2D:: writePNG (const char* name) const
{
if (name == NULL) {
throw NullPointerException (__FILE__, __func__, "File name is NULL.");
}
int comp = format_to_bpp(format);
int ret = stbi_write_png (name, width, height, comp, image, width*comp);
if (ret == 0) {
throw IOException (__FILE__, __func__, "Can't write png, name=%s.", name);
}
}
unsigned int Image2D:: getOpenGLFormat () const
{
switch (format) {
case Image2D::ALPHA : return GL_ALPHA;
case Image2D::LUMINANCE : return GL_LUMINANCE;
case Image2D::LUMINANCE_ALPHA: return GL_LUMINANCE_ALPHA;
case Image2D::RGB : return GL_RGB;
case Image2D::RGBA : return GL_RGBA;
default: throw InternalException (__FILE__, __func__, "Image format is unknown, format=%d.", format);
}
}
void* Image2D:: getOpenGLPointer () const
{
return image;
}
/**
* メモ: (非公開)この関数は通常のrender()関数と異なり、
* 現在のフレームバッファーの内容をこのImag2Dへ取り込む.
* 別の名前にしたほうがいいだろう。
*/
void Image2D:: render_xxx (RenderState& state) const
{
unsigned int gl_format = getOpenGLFormat ();
unsigned int gl_type = GL_UNSIGNED_BYTE;
glReadPixels (0, 0, width, height, gl_format, gl_type, (unsigned char*)image);
}
int m3g::format_to_bpp (int format)
{
switch (format) {
case Image2D::ALPHA : return 1;
case Image2D::LUMINANCE : return 1;
case Image2D::LUMINANCE_ALPHA: return 2;
case Image2D::RGB : return 3;
case Image2D::RGBA : return 4;
default: throw InternalException (__FILE__, __func__, "Format is unknown, format=%d.", format);
}
}
static
const char* format_to_string (int format)
{
switch (format) {
case Image2D::ALPHA : return "ALPHA";
case Image2D::LUMINANCE : return "LUMINANCE";
case Image2D::LUMINANCE_ALPHA: return "LUMINANCE_ALPHA";
case Image2D::RGB : return "RGB";
case Image2D::RGBA : return "RGBA";
default: return "Unknown";
}
}
std::ostream& Image2D:: print (std::ostream& out) const
{
out << "Image2D: ";
out << " format=" << format_to_string(format);
out << ", width=" << width;
out << ", height=" << height;
out << ", immutable=" << immutable;
return out;
}
std::ostream& operator<< (std::ostream& out, const Image2D& img)
{
return img.print(out);
}
| 29.34728 | 127 | 0.621044 | vadosnaprimer |
12a028451d0afb5b5bcf9d3471bb9549bb682abe | 1,525 | cpp | C++ | Source/Tests/Platform.cpp | Negrutiu/nsis | 14eed5608d44e998309892fe8226aeb5252b9ab9 | [
"BSD-3-Clause"
] | null | null | null | Source/Tests/Platform.cpp | Negrutiu/nsis | 14eed5608d44e998309892fe8226aeb5252b9ab9 | [
"BSD-3-Clause"
] | null | null | null | Source/Tests/Platform.cpp | Negrutiu/nsis | 14eed5608d44e998309892fe8226aeb5252b9ab9 | [
"BSD-3-Clause"
] | null | null | null | #include <cppunit/extensions/HelperMacros.h>
#include "../Platform.h"
#include "../tchar.h"
#include "../util.h"
class PlatformTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE( PlatformTest );
CPPUNIT_TEST( testCore );
CPPUNIT_TEST( testCoreString );
CPPUNIT_TEST( testCoreMath );
CPPUNIT_TEST_SUITE_END();
public:
void testCore() {
CPPUNIT_ASSERT(sizeof(WINWCHAR) == 2);
CPPUNIT_ASSERT(sizeof(wchar_t) >= sizeof(WINWCHAR));
}
void testCoreString() {
TCHAR tbuf[42];
CPPUNIT_ASSERT(3 == my_strncpy(tbuf, _T("abc"), 4) && tbuf[2] == _T('c') && tbuf[3] == _T('\0'));
CPPUNIT_ASSERT(2 == my_strncpy(tbuf, _T("abc"), 3) && tbuf[1] == _T('b') && tbuf[2] == _T('\0'));
CPPUNIT_ASSERT(ChIsHex('f')); CPPUNIT_ASSERT(ChIsHex('F'));
CPPUNIT_ASSERT(ChIsHex(L'f')); CPPUNIT_ASSERT(ChIsHex(L'F'));
}
void testCoreMath() {
unsigned int ut;
CPPUNIT_ASSERT(ui_add(ut, 0, 0) != false);
CPPUNIT_ASSERT(ui_add(ut, UINT_MAX, 0) != false && ut == UINT_MAX);
CPPUNIT_ASSERT(ui_add(ut, UINT_MAX, 1) == false);
int st;
CPPUNIT_ASSERT(si_add(st, 0, 0) != false);
CPPUNIT_ASSERT(si_add(st, INT_MAX, 0) != false && st == INT_MAX);
CPPUNIT_ASSERT(si_add(st, INT_MAX, 1) == false);
CPPUNIT_ASSERT(si_add(st, INT_MAX, -1) != false);
CPPUNIT_ASSERT(si_add(st, INT_MIN, 0) != false);
CPPUNIT_ASSERT(si_add(st, INT_MIN, 1) != false);
CPPUNIT_ASSERT(si_add(st, INT_MIN, -1) == false);
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( PlatformTest );
| 30.5 | 101 | 0.646557 | Negrutiu |
12a0367437dde8b91fa1bb2a21bff72c86869495 | 7,194 | cpp | C++ | src/runtime_src/core/edge/user/aie/aie.cpp | Ralender/XRT | ade04554314f6afe3aed99309bfd16868bfce506 | [
"Apache-2.0"
] | null | null | null | src/runtime_src/core/edge/user/aie/aie.cpp | Ralender/XRT | ade04554314f6afe3aed99309bfd16868bfce506 | [
"Apache-2.0"
] | null | null | null | src/runtime_src/core/edge/user/aie/aie.cpp | Ralender/XRT | ade04554314f6afe3aed99309bfd16868bfce506 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2020 Xilinx, Inc
* Author(s): Larry Liu
* ZNYQ XRT Library layered on top of ZYNQ zocl kernel driver
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may
* not use this file except in compliance with the License. A copy of the
* License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "aie.h"
#include "core/common/error.h"
#include "core/common/message.h"
#include <iostream>
#include <cerrno>
namespace zynqaie {
Aie::Aie(std::shared_ptr<xrt_core::device> device)
{
/* TODO where are these number from */
numRows = 8;
numCols = 50;
aieAddrArrayOff = 0x800;
XAIEGBL_HWCFG_SET_CONFIG((&aieConfig), numRows, numCols, aieAddrArrayOff);
XAieGbl_HwInit(&aieConfig);
aieConfigPtr = XAieGbl_LookupConfig(XPAR_AIE_DEVICE_ID);
int tileArraySize = numCols * (numRows + 1);
tileArray.resize(tileArraySize);
/*
* Initialize AIE tile array.
*
* TODO is void good here?
*/
(void) XAieGbl_CfgInitialize(&aieInst, tileArray.data(), aieConfigPtr);
/* Initialize graph GMIO metadata */
for (auto& gmio : xrt_core::edge::aie::get_gmios(device.get()))
gmios.emplace_back(std::move(gmio));
/*
* Initialize AIE shim DMA on column base if there is one for
* this column.
*/
shim_dma.resize(numCols);
for (auto& gmio : gmios) {
auto dma = &shim_dma.at(gmio.shim_col);
auto pos = getTilePos(gmio.shim_col, 0);
if (!dma->configured) {
XAieDma_ShimSoftInitialize(&(tileArray.at(pos)), &(dma->handle));
XAieDma_ShimBdClearAll(&(dma->handle));
dma->configured = true;
}
auto chan = gmio.channel_number;
XAieDma_ShimChControl((&(dma->handle)), chan, XAIE_DISABLE, XAIE_DISABLE, XAIE_ENABLE);
for (int i = 0; i < XAIEGBL_NOC_DMASTA_STARTQ_MAX; ++i) {
/*
* 16 BDs are allocated to 4 channels.
* Channel0: BD0~BD3
* Channel1: BD4~BD7
* Channel2: BD8~BD11
* Channel3: BD12~BD15
*/
int bd_num = chan * XAIEGBL_NOC_DMASTA_STARTQ_MAX + i;
BD bd;
bd.bd_num = bd_num;
dma->dma_chan[chan].idle_bds.push(bd);
XAieDma_ShimBdSetAxi(&(dma->handle), bd_num, 0, gmio.burst_len, 0, 0, 0);
}
}
#ifndef __AIESIM__
/* Disable AIE interrupts */
u32 reg = XAieGbl_NPIRead32(XAIE_NPI_ISR);
XAieGbl_NPIWrite32(XAIE_NPI_ISR, reg);
if (XAieTile_EventsHandlingInitialize(&aieInst) != XAIE_SUCCESS)
throw xrt_core::error("Failed to initialize AIE Events Handling.");
/* Register all AIE error events */
XAieTile_ErrorRegisterNotification(&aieInst, XAIEGBL_MODULE_ALL, XAIETILE_ERROR_ALL, error_cb, NULL);
/* Enable AIE interrupts */
XAieTile_EventsEnableInterrupt(&aieInst);
#endif
}
Aie::~Aie()
{
}
int Aie::getTilePos(int col, int row)
{
return col * (numRows + 1) + row;
}
XAieGbl* Aie::getAieInst()
{
return &aieInst;
}
XAieGbl_ErrorHandleStatus
Aie::error_cb(struct XAieGbl *aie_inst, XAie_LocType loc, u8 module, u8 error, void *arg)
{
#ifndef __AIESIM__
auto severity = xrt_core::message::severity_level::XRT_INFO;
switch (module) {
case XAIEGBL_MODULE_CORE:
switch (error) {
case XAIETILE_EVENT_CORE_TLAST_IN_WSS_WORDS_0_2:
case XAIETILE_EVENT_CORE_PM_REG_ACCESS_FAILURE:
case XAIETILE_EVENT_CORE_STREAM_PKT_PARITY_ERROR:
case XAIETILE_EVENT_CORE_CONTROL_PKT_ERROR:
case XAIETILE_EVENT_CORE_INSTRUCTION_DECOMPRESSION_ERROR:
case XAIETILE_EVENT_CORE_DM_ADDRESS_OUT_OF_RANGE:
case XAIETILE_EVENT_CORE_AXI_MM_SLAVE_ERROR:
case XAIETILE_EVENT_CORE_PM_ECC_ERROR_SCRUB_2BIT:
case XAIETILE_EVENT_CORE_PM_ADDRESS_OUT_OF_RANGE:
case XAIETILE_EVENT_CORE_DM_ACCESS_TO_UNAVAILABLE:
case XAIETILE_EVENT_CORE_LOCK_ACCESS_TO_UNAVAILABLE:
severity = xrt_core::message::severity_level::XRT_EMERGENCY;
break;
case XAIETILE_EVENT_CORE_FP_OVERFLOW:
case XAIETILE_EVENT_CORE_FP_UNDERFLOW:
case XAIETILE_EVENT_CORE_FP_INVALID:
case XAIETILE_EVENT_CORE_FP_DIV_BY_ZERO:
case XAIETILE_EVENT_CORE_INSTR_WARNING:
case XAIETILE_EVENT_CORE_INSTR_ERROR:
severity = xrt_core::message::severity_level::XRT_ERROR;
break;
case XAIETILE_EVENT_CORE_SRS_SATURATE:
case XAIETILE_EVENT_CORE_UPS_SATURATE:
severity = xrt_core::message::severity_level::XRT_NOTICE;
break;
default:
break;
}
break;
case XAIEGBL_MODULE_MEM:
switch (error) {
case XAIETILE_EVENT_MEM_DM_ECC_ERROR_2BIT:
case XAIETILE_EVENT_MEM_DMA_S2MM_0_ERROR:
case XAIETILE_EVENT_MEM_DMA_S2MM_1_ERROR:
case XAIETILE_EVENT_MEM_DMA_MM2S_0_ERROR:
case XAIETILE_EVENT_MEM_DMA_MM2S_1_ERROR:
severity = xrt_core::message::severity_level::XRT_EMERGENCY;
break;
case XAIETILE_EVENT_MEM_DM_PARITY_ERROR_BANK_2:
case XAIETILE_EVENT_MEM_DM_PARITY_ERROR_BANK_3:
case XAIETILE_EVENT_MEM_DM_PARITY_ERROR_BANK_4:
case XAIETILE_EVENT_MEM_DM_PARITY_ERROR_BANK_5:
case XAIETILE_EVENT_MEM_DM_PARITY_ERROR_BANK_6:
case XAIETILE_EVENT_MEM_DM_PARITY_ERROR_BANK_7:
severity = xrt_core::message::severity_level::XRT_CRITICAL;
break;
default:
break;
}
break;
case XAIEGBL_MODULE_PL:
switch (error) {
case XAIETILE_EVENT_SHIM_AXI_MM_SLAVE_TILE_ERROR:
case XAIETILE_EVENT_SHIM_CONTROL_PKT_ERROR:
case XAIETILE_EVENT_SHIM_AXI_MM_DECODE_NSU_ERROR_NOC:
case XAIETILE_EVENT_SHIM_AXI_MM_SLAVE_NSU_ERROR_NOC:
case XAIETILE_EVENT_SHIM_AXI_MM_UNSUPPORTED_TRAFFIC_NOC:
case XAIETILE_EVENT_SHIM_AXI_MM_UNSECURE_ACCESS_IN_SECURE_MODE_NOC:
case XAIETILE_EVENT_SHIM_AXI_MM_BYTE_STROBE_ERROR_NOC:
case XAIETILE_EVENT_SHIM_DMA_S2MM_0_ERROR_NOC:
case XAIETILE_EVENT_SHIM_DMA_S2MM_1_ERROR_NOC:
case XAIETILE_EVENT_SHIM_DMA_MM2S_0_ERROR_NOC:
case XAIETILE_EVENT_SHIM_DMA_MM2S_1_ERROR_NOC:
severity = xrt_core::message::severity_level::XRT_EMERGENCY;
break;
default:
break;
}
break;
default:
break;
}
xrt_core::message::send(severity, "XRT", "AIE ERROR: module %d, error %d", module, error);
#endif
return XAIETILE_ERROR_HANDLED;
}
}
| 33.460465 | 105 | 0.660272 | Ralender |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.